{
    "file_diffs": [
        {
            "old_file_content": "import operator\nimport os\nimport warnings\nimport zlib\nfrom collections import MutableSequence, Iterable, Sequence, Sized\nfrom functools import reduce\nfrom itertools import chain\nfrom numbers import Real, Integral\nfrom threading import Lock, RLock\n\nimport bottleneck as bn\nimport numpy as np\nfrom scipy import sparse as sp\n\nimport Orange.data  # import for io.py\nfrom Orange.data import (\n    _contingency, _valuecount,\n    Domain, Variable, Storage, StringVariable, Unknown, Value, Instance,\n    ContinuousVariable, DiscreteVariable, MISSING_VALUES\n)\nfrom Orange.data.util import SharedComputeValue, vstack, hstack, \\\n    assure_array_dense, assure_array_sparse, \\\n    assure_column_dense, assure_column_sparse\nfrom Orange.statistics.util import bincount, countnans, contingency, \\\n    stats as fast_stats, sparse_has_implicit_zeros, sparse_count_implicit_zeros, \\\n    sparse_implicit_zero_weights\nfrom Orange.util import flatten\n\n__all__ = [\"dataset_dirs\", \"get_sample_datasets_dir\", \"RowInstance\", \"Table\"]\n\n\ndef get_sample_datasets_dir():\n    orange_data_table = os.path.dirname(__file__)\n    dataset_dir = os.path.join(orange_data_table, '..', 'datasets')\n    return os.path.realpath(dataset_dir)\n\n\ndataset_dirs = ['', get_sample_datasets_dir()]\n\n\n\"\"\"Domain conversion cache used in Table.from_table. It is global so that\nchaining of domain conversions also works with caching even with descendants\nof Table.\"\"\"\n_conversion_cache = None\n_conversion_cache_lock = RLock()\n\n\ndef pending_deprecation_resize(name):\n    warnings.warn(f\"Method Table.{name} will be removed in Orange 3.24\",\n                  PendingDeprecationWarning)\n\n\nclass DomainTransformationError(Exception):\n    pass\n\n\nclass RowInstance(Instance):\n    sparse_x = None\n    sparse_y = None\n    sparse_metas = None\n    _weight = None\n\n    def __init__(self, table, row_index):\n        \"\"\"\n        Construct a data instance representing the given row of the table.\n        \"\"\"\n        self.table = table\n        self._domain = table.domain\n        self.row_index = row_index\n        self.id = table.ids[row_index]\n        self._x = table.X[row_index]\n        if sp.issparse(self._x):\n            self.sparse_x = sp.csr_matrix(self._x)\n            self._x = np.asarray(self._x.todense())[0]\n        self._y = table._Y[row_index]\n        if sp.issparse(self._y):\n            self.sparse_y = sp.csr_matrix(self._y)\n            self._y = np.asarray(self._y.todense())[0]\n        self._metas = table.metas[row_index]\n        if sp.issparse(self._metas):\n            self.sparse_metas = sp.csr_matrix(self._metas)\n            self._metas = np.asarray(self._metas.todense())[0]\n\n    @property\n    def weight(self):\n        if not self.table.has_weights():\n            return 1\n        return self.table.W[self.row_index]\n\n    @weight.setter\n    def weight(self, weight):\n        if not self.table.has_weights():\n            self.table.set_weights()\n        self.table.W[self.row_index] = weight\n\n    def set_class(self, value):\n        self._check_single_class()\n        if not isinstance(value, Real):\n            value = self.table.domain.class_var.to_val(value)\n        self._y[0] = value\n        if self.sparse_y:\n            self.table._Y[self.row_index, 0] = value\n\n    def __setitem__(self, key, value):\n        if not isinstance(key, Integral):\n            key = self._domain.index(key)\n        if isinstance(value, str):\n            var = self._domain[key]\n            value = var.to_val(value)\n        if key >= 0:\n            if not isinstance(value, Real):\n                raise TypeError(\"Expected primitive value, got '%s'\" %\n                                type(value).__name__)\n            if key < len(self._x):\n                self._x[key] = value\n                if self.sparse_x is not None:\n                    self.table.X[self.row_index, key] = value\n            else:\n                self._y[key - len(self._x)] = value\n                if self.sparse_y is not None:\n                    self.table._Y[self.row_index, key - len(self._x)] = value\n        else:\n            self._metas[-1 - key] = value\n            if self.sparse_metas:\n                self.table.metas[self.row_index, -1 - key] = value\n\n    def _str(self, limit):\n        def sp_values(matrix, variables):\n            if not sp.issparse(matrix):\n                if matrix.ndim == 1:\n                    matrix = matrix[:, np.newaxis]\n                return Instance.str_values(matrix[row], variables, limit)\n\n            row_entries, idx = [], 0\n            while idx < len(variables):\n                # Make sure to stop printing variables if we limit the output\n                if limit and len(row_entries) >= 5:\n                    break\n\n                var = variables[idx]\n                if var.is_discrete or matrix[row, idx]:\n                    row_entries.append(\"%s=%s\" % (var.name, var.str_val(matrix[row, idx])))\n\n                idx += 1\n\n            s = \", \".join(row_entries)\n\n            if limit and idx < len(variables):\n                s += \", ...\"\n\n            return s\n\n        table = self.table\n        domain = table.domain\n        row = self.row_index\n        s = \"[\" + sp_values(table.X, domain.attributes)\n        if domain.class_vars:\n            s += \" | \" + sp_values(table.Y, domain.class_vars)\n        s += \"]\"\n        if self._domain.metas:\n            s += \" {\" + sp_values(table.metas, domain.metas) + \"}\"\n        return s\n\n    def __str__(self):\n        return self._str(False)\n\n    def __repr__(self):\n        return self._str(True)\n\n\nclass Columns:\n    def __init__(self, domain):\n        for v in chain(domain.variables, domain.metas):\n            setattr(self, v.name.replace(\" \", \"_\"), v)\n\n\n# noinspection PyPep8Naming\nclass Table(MutableSequence, Storage):\n    __file__ = None\n    name = \"untitled\"\n\n    @property\n    def columns(self):\n        \"\"\"\n        A class whose attributes contain attribute descriptors for columns.\n        For a table `table`, setting `c = table.columns` will allow accessing\n        the table's variables with, for instance `c.gender`, `c.age` ets.\n        Spaces are replaced with underscores.\n        \"\"\"\n        return Columns(self.domain)\n\n    _next_instance_id = 0\n    _next_instance_lock = Lock()\n\n    @property\n    def Y(self):\n        if self._Y.shape[1] == 1:\n            return self._Y[:, 0]\n        return self._Y\n\n    @Y.setter\n    def Y(self, value):\n        if len(value.shape) == 1:\n            value = value[:, None]\n        if sp.issparse(value) and len(self) != value.shape[0]:\n            value = value.T\n        self._Y = value\n\n    def __new__(cls, *args, **kwargs):\n        if not args and not kwargs:\n            return super().__new__(cls)\n\n        if 'filename' in kwargs:\n            args = [kwargs.pop('filename')]\n\n        if not args:\n            raise TypeError(\n                \"Table takes at least 1 positional argument (0 given))\")\n\n        if isinstance(args[0], str):\n            if args[0].startswith('https://') or args[0].startswith('http://'):\n                return cls.from_url(args[0], **kwargs)\n            else:\n                return cls.from_file(args[0])\n        elif isinstance(args[0], Table):\n            return cls.from_table(args[0].domain, args[0])\n        elif isinstance(args[0], Domain):\n            domain, args = args[0], args[1:]\n            if not args:\n                return cls.from_domain(domain, **kwargs)\n            if isinstance(args[0], Table):\n                return cls.from_table(domain, *args)\n            elif isinstance(args[0], list):\n                return cls.from_list(domain, *args)\n        else:\n            domain = None\n\n        return cls.from_numpy(domain, *args, **kwargs)\n\n    def __init__(self, *args, **kwargs):\n        # So subclasses can expect to call super without breakage; noop\n        pass\n\n    @classmethod\n    def from_domain(cls, domain, n_rows=0, weights=False):\n        \"\"\"\n        Construct a new `Table` with the given number of rows for the given\n        domain. The optional vector of weights is initialized to 1's.\n\n        :param domain: domain for the `Table`\n        :type domain: Orange.data.Domain\n        :param n_rows: number of rows in the new table\n        :type n_rows: int\n        :param weights: indicates whether to construct a vector of weights\n        :type weights: bool\n        :return: a new table\n        :rtype: Orange.data.Table\n        \"\"\"\n        self = cls()\n        self.domain = domain\n        self.n_rows = n_rows\n        self.X = np.zeros((n_rows, len(domain.attributes)))\n        self.Y = np.zeros((n_rows, len(domain.class_vars)))\n        if weights:\n            self.W = np.ones(n_rows)\n        else:\n            self.W = np.empty((n_rows, 0))\n        self.metas = np.empty((n_rows, len(self.domain.metas)), object)\n        cls._init_ids(self)\n        self.attributes = {}\n        return self\n\n    @classmethod\n    def from_table(cls, domain, source, row_indices=...):\n        \"\"\"\n        Create a new table from selected columns and/or rows of an existing\n        one. The columns are chosen using a domain. The domain may also include\n        variables that do not appear in the source table; they are computed\n        from source variables if possible.\n\n        The resulting data may be a view or a copy of the existing data.\n\n        :param domain: the domain for the new table\n        :type domain: Orange.data.Domain\n        :param source: the source table\n        :type source: Orange.data.Table\n        :param row_indices: indices of the rows to include\n        :type row_indices: a slice or a sequence\n        :return: a new table\n        :rtype: Orange.data.Table\n        \"\"\"\n\n        global _conversion_cache\n\n        def get_columns(row_indices, src_cols, n_rows, dtype=np.float64, is_sparse=False):\n            if not len(src_cols):\n                if is_sparse:\n                    return sp.csr_matrix((n_rows, 0), dtype=source.X.dtype)\n                else:\n                    return np.zeros((n_rows, 0), dtype=source.X.dtype)\n\n            # match density for subarrays\n            match_density = assure_array_sparse if is_sparse else assure_array_dense\n            n_src_attrs = len(source.domain.attributes)\n            if all(isinstance(x, Integral) and 0 <= x < n_src_attrs\n                   for x in src_cols):\n                return match_density(_subarray(source.X, row_indices, src_cols))\n            if all(isinstance(x, Integral) and x < 0 for x in src_cols):\n                arr = match_density(_subarray(source.metas, row_indices,\n                                              [-1 - x for x in src_cols]))\n                if arr.dtype != dtype:\n                    return arr.astype(dtype)\n                return arr\n            if all(isinstance(x, Integral) and x >= n_src_attrs\n                   for x in src_cols):\n                return match_density(_subarray(\n                    source._Y, row_indices,\n                    [x - n_src_attrs for x in src_cols]))\n\n            # initialize final array & set `match_density` for columns\n            if is_sparse:\n                a = sp.dok_matrix((n_rows, len(src_cols)), dtype=dtype)\n                match_density = assure_column_sparse\n            else:\n                a = np.empty((n_rows, len(src_cols)), dtype=dtype)\n                match_density = assure_column_dense\n\n            shared_cache = _conversion_cache\n            for i, col in enumerate(src_cols):\n                if col is None:\n                    a[:, i] = Unknown\n                elif not isinstance(col, Integral):\n                    if isinstance(col, SharedComputeValue):\n                        if (id(col.compute_shared), id(source)) not in shared_cache:\n                            shared_cache[id(col.compute_shared), id(source)] = \\\n                                col.compute_shared(source)\n                        shared = shared_cache[id(col.compute_shared), id(source)]\n                        if row_indices is not ...:\n                            a[:, i] = match_density(\n                                col(source, shared_data=shared)[row_indices])\n                        else:\n                            a[:, i] = match_density(\n                                col(source, shared_data=shared))\n                    else:\n                        if row_indices is not ...:\n                            a[:, i] = match_density(col(source)[row_indices])\n                        else:\n                            a[:, i] = match_density(col(source))\n                elif col < 0:\n                    a[:, i] = match_density(source.metas[row_indices, -1 - col])\n                elif col < n_src_attrs:\n                    a[:, i] = match_density(source.X[row_indices, col])\n                else:\n                    a[:, i] = match_density(\n                        source._Y[row_indices, col - n_src_attrs])\n\n            if is_sparse:\n                a = a.tocsr()\n\n            return a\n\n        with _conversion_cache_lock:\n            new_cache = _conversion_cache is None\n            try:\n                if new_cache:\n                    _conversion_cache = {}\n                else:\n                    cached = _conversion_cache.get((id(domain), id(source)))\n                    if cached:\n                        return cached\n                if domain == source.domain:\n                    table = cls.from_table_rows(source, row_indices)\n                    # assure resulting domain is the instance passed on input\n                    table.domain = domain\n                    # since sparse flags are not considered when checking for\n                    # domain equality, fix manually.\n                    table = assure_domain_conversion_sparsity(table, source)\n                    return table\n\n                if isinstance(row_indices, slice):\n                    start, stop, stride = row_indices.indices(source.X.shape[0])\n                    n_rows = (stop - start) // stride\n                    if n_rows < 0:\n                        n_rows = 0\n                elif row_indices is ...:\n                    n_rows = len(source)\n                else:\n                    n_rows = len(row_indices)\n\n                self = cls()\n                self.domain = domain\n                conversion = domain.get_conversion(source.domain)\n                self.X = get_columns(row_indices, conversion.attributes, n_rows,\n                                     is_sparse=conversion.sparse_X)\n                if self.X.ndim == 1:\n                    self.X = self.X.reshape(-1, len(self.domain.attributes))\n\n                self.Y = get_columns(row_indices, conversion.class_vars, n_rows,\n                                     is_sparse=conversion.sparse_Y)\n\n                dtype = np.float64\n                if any(isinstance(var, StringVariable) for var in domain.metas):\n                    dtype = np.object\n                self.metas = get_columns(row_indices, conversion.metas,\n                                         n_rows, dtype,\n                                         is_sparse=conversion.sparse_metas)\n                if self.metas.ndim == 1:\n                    self.metas = self.metas.reshape(-1, len(self.domain.metas))\n                if source.has_weights():\n                    self.W = source.W[row_indices]\n                else:\n                    self.W = np.empty((n_rows, 0))\n                self.name = getattr(source, 'name', '')\n                if hasattr(source, 'ids'):\n                    self.ids = source.ids[row_indices]\n                else:\n                    cls._init_ids(self)\n                self.attributes = getattr(source, 'attributes', {})\n                _conversion_cache[(id(domain), id(source))] = self\n                return self\n            finally:\n                if new_cache:\n                    _conversion_cache = None\n\n    def transform(self, domain):\n        \"\"\"\n        Construct a table with a different domain.\n\n        The new table keeps the row ids and other information. If the table\n        is a subclass of :obj:`Table`, the resulting table will be of the same\n        type.\n\n        In a typical scenario, an existing table is augmented with a new\n        column by ::\n\n            domain = Domain(old_domain.attributes + [new_attribute],\n                            old_domain.class_vars,\n                            old_domain.metas)\n            table = data.transform(domain)\n            table[:, new_attribute] = new_column\n\n        Args:\n            domain (Domain): new domain\n\n        Returns:\n            A new table\n        \"\"\"\n        return type(self).from_table(domain, self)\n\n    @classmethod\n    def from_table_rows(cls, source, row_indices):\n        \"\"\"\n        Construct a new table by selecting rows from the source table.\n\n        :param source: an existing table\n        :type source: Orange.data.Table\n        :param row_indices: indices of the rows to include\n        :type row_indices: a slice or a sequence\n        :return: a new table\n        :rtype: Orange.data.Table\n        \"\"\"\n        self = cls()\n        self.domain = source.domain\n        self.X = source.X[row_indices]\n        if self.X.ndim == 1:\n            self.X = self.X.reshape(-1, len(self.domain.attributes))\n        self.Y = source._Y[row_indices]\n        self.metas = source.metas[row_indices]\n        if self.metas.ndim == 1:\n            self.metas = self.metas.reshape(-1, len(self.domain.metas))\n        self.W = source.W[row_indices]\n        self.name = getattr(source, 'name', '')\n        self.ids = np.array(source.ids[row_indices])\n        self.attributes = getattr(source, 'attributes', {})\n        return self\n\n    @classmethod\n    def from_numpy(cls, domain, X, Y=None, metas=None, W=None):\n        \"\"\"\n        Construct a table from numpy arrays with the given domain. The number\n        of variables in the domain must match the number of columns in the\n        corresponding arrays. All arrays must have the same number of rows.\n        Arrays may be of different numpy types, and may be dense or sparse.\n\n        :param domain: the domain for the new table\n        :type domain: Orange.data.Domain\n        :param X: array with attribute values\n        :type X: np.array\n        :param Y: array with class values\n        :type Y: np.array\n        :param metas: array with meta attributes\n        :type metas: np.array\n        :param W: array with weights\n        :type W: np.array\n        :return:\n        \"\"\"\n        X, Y, W = _check_arrays(X, Y, W, dtype='float64')\n        metas, = _check_arrays(metas, dtype=object)\n\n        if Y is not None and Y.ndim == 1:\n            Y = Y.reshape(Y.shape[0], 1)\n        if domain is None:\n            domain = Domain.from_numpy(X, Y, metas)\n\n        if Y is None:\n            if sp.issparse(X):\n                Y = np.empty((X.shape[0], 0), dtype=np.float64)\n            else:\n                Y = X[:, len(domain.attributes):]\n                X = X[:, :len(domain.attributes)]\n        if metas is None:\n            metas = np.empty((X.shape[0], 0), object)\n        if W is None or W.size == 0:\n            W = np.empty((X.shape[0], 0))\n        else:\n            W = W.reshape(W.size)\n\n        if X.shape[1] != len(domain.attributes):\n            raise ValueError(\n                \"Invalid number of variable columns ({} != {})\".format(\n                    X.shape[1], len(domain.attributes))\n            )\n        if Y.shape[1] != len(domain.class_vars):\n            raise ValueError(\n                \"Invalid number of class columns ({} != {})\".format(\n                    Y.shape[1], len(domain.class_vars))\n            )\n        if metas.shape[1] != len(domain.metas):\n            raise ValueError(\n                \"Invalid number of meta attribute columns ({} != {})\".format(\n                    metas.shape[1], len(domain.metas))\n            )\n        if not X.shape[0] == Y.shape[0] == metas.shape[0] == W.shape[0]:\n            raise ValueError(\n                \"Parts of data contain different numbers of rows.\")\n\n        self = cls()\n        self.domain = domain\n        self.X = X\n        self.Y = Y\n        self.metas = metas\n        self.W = W\n        self.n_rows = self.X.shape[0]\n        cls._init_ids(self)\n        self.attributes = {}\n        return self\n\n    @classmethod\n    def from_list(cls, domain, rows, weights=None):\n        if weights is not None and len(rows) != len(weights):\n            raise ValueError(\"mismatching number of instances and weights\")\n        self = cls.from_domain(domain, len(rows), weights is not None)\n        attrs, classes = domain.attributes, domain.class_vars\n        metas = domain.metas\n        nattrs, ncls = len(domain.attributes), len(domain.class_vars)\n        for i, row in enumerate(rows):\n            if isinstance(row, Instance):\n                row = row.list\n            for j, (var, val) in enumerate(zip(attrs, row)):\n                self.X[i, j] = var.to_val(val)\n            for j, (var, val) in enumerate(zip(classes, row[nattrs:])):\n                self._Y[i, j] = var.to_val(val)\n            for j, (var, val) in enumerate(zip(metas, row[nattrs + ncls:])):\n                self.metas[i, j] = var.to_val(val)\n        if weights is not None:\n            self.W = np.array(weights)\n        self.attributes = {}\n        return self\n\n    @classmethod\n    def _init_ids(cls, obj):\n        with cls._next_instance_lock:\n            obj.ids = np.array(range(cls._next_instance_id, cls._next_instance_id + obj.X.shape[0]))\n            cls._next_instance_id += obj.X.shape[0]\n\n    @classmethod\n    def new_id(cls):\n        with cls._next_instance_lock:\n            id = cls._next_instance_id\n            cls._next_instance_id += 1\n            return id\n\n    def save(self, filename):\n        \"\"\"\n        Save a data table to a file. The path can be absolute or relative.\n\n        :param filename: File name\n        :type filename: str\n        \"\"\"\n        ext = os.path.splitext(filename)[1]\n        from Orange.data.io import FileFormat\n        writer = FileFormat.writers.get(ext)\n        if not writer:\n            desc = FileFormat.names.get(ext)\n            if desc:\n                raise IOError(\n                    \"Writing of {}s is not supported\".format(desc.lower()))\n            else:\n                raise IOError(\"Unknown file name extension.\")\n        writer.write_file(filename, self)\n\n    @classmethod\n    def from_file(cls, filename, sheet=None):\n        \"\"\"\n        Read a data table from a file. The path can be absolute or relative.\n\n        :param filename: File name\n        :type filename: str\n        :param sheet: Sheet in a file (optional)\n        :type sheet: str\n        :return: a new data table\n        :rtype: Orange.data.Table\n        \"\"\"\n        from Orange.data.io import FileFormat\n\n        absolute_filename = FileFormat.locate(filename, dataset_dirs)\n        reader = FileFormat.get_reader(absolute_filename)\n        reader.select_sheet(sheet)\n        data = reader.read()\n\n        # Readers return plain table. Make sure to cast it to appropriate\n        # (subclass) type\n        if cls != data.__class__:\n            data = cls(data)\n\n        # no need to call _init_ids as fuctions from .io already\n        # construct a table with .ids\n\n        data.__file__ = absolute_filename\n        return data\n\n    @classmethod\n    def from_url(cls, url):\n        from Orange.data.io import UrlReader\n        reader = UrlReader(url)\n        data = reader.read()\n        if cls != data.__class__:\n            data = cls(data)\n        return data\n\n    # Helper function for __setitem__ and insert:\n    # Set the row of table data matrices\n    # noinspection PyProtectedMember\n    def _set_row(self, example, row):\n        domain = self.domain\n        if isinstance(example, Instance):\n            if example.domain == domain:\n                if isinstance(example, RowInstance):\n                    self.X[row] = example._x\n                    self._Y[row] = example._y\n                else:\n                    self.X[row] = example._x\n                    self._Y[row] = example._y\n                self.metas[row] = example._metas\n                return\n\n            self.X[row], self._Y[row], self.metas[row] = \\\n                self.domain.convert(example)\n            try:\n                self.ids[row] = example.id\n            except:\n                with type(self)._next_instance_lock:\n                    self.ids[row] = type(self)._next_instance_id\n                    type(self)._next_instance_id += 1\n\n        else:\n            self.X[row] = [var.to_val(val)\n                           for var, val in zip(domain.attributes, example)]\n            self._Y[row] = [var.to_val(val)\n                            for var, val in\n                            zip(domain.class_vars,\n                                example[len(domain.attributes):])]\n            self.metas[row] = np.array([var.Unknown for var in domain.metas],\n                                       dtype=object)\n\n    def _check_all_dense(self):\n        return all(x in (Storage.DENSE, Storage.MISSING)\n                   for x in (self.X_density(), self.Y_density(),\n                             self.metas_density()))\n\n    # A helper function for extend and insert\n    # Resize X, Y, metas and W.\n    def _resize_all(self, new_length):\n        old_length = self.X.shape[0]\n        if old_length == new_length:\n            return\n        if not self._check_all_dense():\n            raise ValueError(\"Tables with sparse data cannot be resized\")\n        try:\n            self.X.resize(new_length, self.X.shape[1])\n            self._Y.resize(new_length, self._Y.shape[1])\n            self.metas.resize(new_length, self.metas.shape[1])\n            if self.W.ndim == 2:\n                self.W.resize((new_length, 0))\n            else:\n                self.W.resize(new_length)\n            self.ids.resize(new_length)\n        except Exception:\n            if self.X.shape[0] == new_length:\n                self.X.resize(old_length, self.X.shape[1])\n            if self._Y.shape[0] == new_length:\n                self._Y.resize(old_length, self._Y.shape[1])\n            if self.metas.shape[0] == new_length:\n                self.metas.resize(old_length, self.metas.shape[1])\n            if self.W.shape[0] == new_length:\n                if self.W.ndim == 2:\n                    self.W.resize((old_length, 0))\n                else:\n                    self.W.resize(old_length)\n            if self.ids.shape[0] == new_length:\n                self.ids.resize(old_length)\n            raise\n\n    def __getitem__(self, key):\n        if isinstance(key, Integral):\n            return RowInstance(self, key)\n        if not isinstance(key, tuple):\n            return self.from_table_rows(self, key)\n\n        if len(key) != 2:\n            raise IndexError(\"Table indices must be one- or two-dimensional\")\n\n        row_idx, col_idx = key\n        if isinstance(row_idx, Integral):\n            if isinstance(col_idx, (str, Integral, Variable)):\n                col_idx = self.domain.index(col_idx)\n                var = self.domain[col_idx]\n                if 0 <= col_idx < len(self.domain.attributes):\n                    return Value(var, self.X[row_idx, col_idx])\n                elif col_idx >= len(self.domain.attributes):\n                    return Value(\n                        var,\n                        self._Y[row_idx,\n                                col_idx - len(self.domain.attributes)])\n                elif col_idx < 0:\n                    return Value(var, self.metas[row_idx, -1 - col_idx])\n            else:\n                row_idx = [row_idx]\n\n        # multiple rows OR single row but multiple columns:\n        # construct a new table\n        attributes, col_indices = self.domain._compute_col_indices(col_idx)\n        if attributes is not None:\n            n_attrs = len(self.domain.attributes)\n            r_attrs = [attributes[i]\n                       for i, col in enumerate(col_indices)\n                       if 0 <= col < n_attrs]\n            r_classes = [attributes[i]\n                         for i, col in enumerate(col_indices)\n                         if col >= n_attrs]\n            r_metas = [attributes[i]\n                       for i, col in enumerate(col_indices) if col < 0]\n            domain = Domain(r_attrs, r_classes, r_metas)\n        else:\n            domain = self.domain\n        return self.from_table(domain, self, row_idx)\n\n    def __setitem__(self, key, value):\n        if not isinstance(key, tuple):\n            if isinstance(value, Real):\n                self.X[key, :] = value\n                return\n            self._set_row(value, key)\n            return\n\n        if len(key) != 2:\n            raise IndexError(\"Table indices must be one- or two-dimensional\")\n        row_idx, col_idx = key\n\n        # single row\n        if isinstance(row_idx, Integral):\n            if isinstance(col_idx, slice):\n                col_idx = range(*slice.indices(col_idx, self.X.shape[1]))\n            if not isinstance(col_idx, str) and isinstance(col_idx, Iterable):\n                col_idx = list(col_idx)\n            if not isinstance(col_idx, str) and isinstance(col_idx, Sized):\n                if isinstance(value, (Sequence, np.ndarray)):\n                    values = value\n                elif isinstance(value, Iterable):\n                    values = list(value)\n                else:\n                    raise TypeError(\"Setting multiple values requires a \"\n                                    \"sequence or numpy array\")\n                if len(values) != len(col_idx):\n                    raise ValueError(\"Invalid number of values\")\n            else:\n                col_idx, values = [col_idx], [value]\n            for value, col_idx in zip(values, col_idx):\n                if not isinstance(value, Integral):\n                    value = self.domain[col_idx].to_val(value)\n                if not isinstance(col_idx, Integral):\n                    col_idx = self.domain.index(col_idx)\n                if col_idx >= 0:\n                    if col_idx < self.X.shape[1]:\n                        self.X[row_idx, col_idx] = value\n                    else:\n                        self._Y[row_idx, col_idx - self.X.shape[1]] = value\n                else:\n                    self.metas[row_idx, -1 - col_idx] = value\n\n        # multiple rows, multiple columns\n        attributes, col_indices = self.domain._compute_col_indices(col_idx)\n        if col_indices is ...:\n            col_indices = range(len(self.domain))\n        n_attrs = self.X.shape[1]\n        if isinstance(value, str):\n            if not attributes:\n                attributes = self.domain.attributes\n            for var, col in zip(attributes, col_indices):\n                if 0 <= col < n_attrs:\n                    self.X[row_idx, col] = var.to_val(value)\n                elif col >= n_attrs:\n                    self._Y[row_idx, col - n_attrs] = var.to_val(value)\n                else:\n                    self.metas[row_idx, -1 - col] = var.to_val(value)\n        else:\n            attr_cols = np.fromiter(\n                (col for col in col_indices if 0 <= col < n_attrs), int)\n            class_cols = np.fromiter(\n                (col - n_attrs for col in col_indices if col >= n_attrs), int)\n            meta_cols = np.fromiter(\n                (-1 - col for col in col_indices if col < 0), int)\n            if value is None:\n                value = Unknown\n\n            if not isinstance(value, (Real, np.ndarray)) and \\\n                    (len(attr_cols) or len(class_cols)):\n                raise TypeError(\n                    \"Ordinary attributes can only have primitive values\")\n            if len(attr_cols):\n                self.X[row_idx, attr_cols] = value\n            if len(class_cols):\n                self._Y[row_idx, class_cols] = value\n            if len(meta_cols):\n                self.metas[row_idx, meta_cols] = value\n\n    def __delitem__(self, key):\n        pending_deprecation_resize(\"__delitem__(key)\")\n        if not self._check_all_dense():\n            raise ValueError(\"Rows of sparse data cannot be deleted\")\n        if key is ...:\n            key = range(len(self))\n        self.X = np.delete(self.X, key, axis=0)\n        self.Y = np.delete(self._Y, key, axis=0)\n        self.metas = np.delete(self.metas, key, axis=0)\n        self.W = np.delete(self.W, key, axis=0)\n        self.ids = np.delete(self.ids, key, axis=0)\n\n    def __len__(self):\n        return self.X.shape[0]\n\n    def __str__(self):\n        return \"[\" + \",\\n \".join(str(ex) for ex in self) + \"]\"\n\n    def __repr__(self):\n        head = 5\n        if self.is_sparse():\n            head = min(self.X.shape[0], head)\n        s = \"[\" + \",\\n \".join(repr(ex) for ex in self[:head])\n        if len(self) > head:\n            s += \",\\n ...\"\n        s += \"\\n]\"\n        return s\n\n    def clear(self):\n        \"\"\"Remove all rows from the table.\"\"\"\n        pending_deprecation_resize(\"clear()\")\n        if not self._check_all_dense():\n            raise ValueError(\"Tables with sparse data cannot be cleared\")\n        del self[...]\n\n    def append(self, instance):\n        \"\"\"\n        Append a data instance to the table.\n\n        :param instance: a data instance\n        :type instance: Orange.data.Instance or a sequence of values\n        \"\"\"\n        pending_deprecation_resize(\"append(inst)\")\n        self.insert(len(self), instance)\n\n    def insert(self, row, instance):\n        \"\"\"\n        Insert a data instance into the table.\n\n        :param row: row index\n        :type row: int\n        :param instance: a data instance\n        :type instance: Orange.data.Instance or a sequence of values\n        \"\"\"\n        pending_deprecation_resize(\"insert(i, inst)\")\n        if row < 0:\n            row += len(self)\n        if row < 0 or row > len(self):\n            raise IndexError(\"Index out of range\")\n        self.ensure_copy()  # ensure that numpy arrays are single-segment for resize\n        self._resize_all(len(self) + 1)\n        if row < len(self):\n            self.X[row + 1:] = self.X[row:-1]\n            self._Y[row + 1:] = self._Y[row:-1]\n            self.metas[row + 1:] = self.metas[row:-1]\n            self.W[row + 1:] = self.W[row:-1]\n            self.ids[row + 1:] = self.ids[row:-1]\n        try:\n            self._set_row(instance, row)\n            if self.W.shape[-1]:\n                self.W[row] = 1\n        except Exception:\n            self.X[row:-1] = self.X[row + 1:]\n            self._Y[row:-1] = self._Y[row + 1:]\n            self.metas[row:-1] = self.metas[row + 1:]\n            self.W[row:-1] = self.W[row + 1:]\n            self.ids[row:-1] = self.ids[row + 1:]\n            self._resize_all(len(self) - 1)\n            raise\n\n    def extend(self, instances):\n        \"\"\"\n        Extend the table with the given instances. The instances can be given\n        as a table of the same or a different domain, or a sequence. In the\n        latter case, each instances can be given as\n        :obj:`~Orange.data.Instance` or a sequence of values (e.g. list,\n        tuple, numpy.array).\n\n        :param instances: additional instances\n        :type instances: Orange.data.Table or a sequence of instances\n        \"\"\"\n        pending_deprecation_resize(\"extend(insts)\")\n        if isinstance(instances, Table) and instances.domain == self.domain:\n            self.X = vstack((self.X, instances.X))\n            self._Y = vstack((self._Y, instances._Y))\n            self.metas = vstack((self.metas, instances.metas))\n            self.W = vstack((self.W, instances.W))\n            self.ids = hstack((self.ids, instances.ids))\n        else:\n            try:\n                old_length = len(self)\n                self._resize_all(old_length + len(instances))\n                for i, example in enumerate(instances):\n                    self[old_length + i] = example\n                    try:\n                        self.ids[old_length + i] = example.id\n                    except AttributeError:\n                        self.ids[old_length + i] = self.new_id()\n            except Exception:\n                self._resize_all(old_length)\n                raise\n\n    @classmethod\n    def concatenate(cls, tables, axis=1):\n        \"\"\"Return concatenation of `tables` by `axis`.\"\"\"\n        def vstack(arrs):\n            return [np, sp][any(sp.issparse(arr) for arr in arrs)].vstack(arrs)\n\n        def merge1d(arrs):\n            arrs = list(arrs)\n            ydims = {arr.ndim for arr in arrs}\n            if ydims == {1}:\n                return np.hstack(arrs)\n            else:\n                return vstack([\n                    arr if arr.ndim == 2 else np.atleast_2d(arr).T\n                    for arr in arrs\n                ])\n\n        def collect(attr):\n            return [getattr(arr, attr) for arr in tables]\n\n        if not tables:\n            raise ValueError('need at least one table to concatenate')\n        if len(tables) == 1:\n            return tables[0].copy()\n        CONCAT_ROWS, CONCAT_COLS = 0, 1\n        if axis == CONCAT_ROWS:\n            domain = tables[0].domain\n            if any(table.domain != domain for table in tables):\n                raise ValueError('concatenated tables must have the same domain')\n\n            conc = cls.from_numpy(\n                domain,\n                vstack(collect(\"X\")),\n                merge1d(collect(\"Y\")),\n                vstack(collect(\"metas\")),\n                merge1d(collect(\"W\"))\n            )\n            conc.ids = np.hstack([table.ids for table in tables])\n            names = [table.name for table in tables if table.name != \"untitled\"]\n            if names:\n                conc.name = names[0]\n            # TODO: Add attributes = {} to __init__\n            conc.attributes = getattr(conc, \"attributes\", {})\n            for table in reversed(tables):\n                conc.attributes.update(table.attributes)\n            return conc\n        elif axis == CONCAT_COLS:\n            pending_deprecation_resize(\"concatenate with axis=1\")\n            if reduce(operator.iand,\n                      (set(map(operator.attrgetter('name'),\n                               chain(t.domain.variables, t.domain.metas)))\n                       for t in tables)):\n                raise ValueError('Concatenating two domains with variables '\n                                 'with same name is undefined')\n            domain = Domain(flatten(t.domain.attributes for t in tables),\n                            flatten(t.domain.class_vars for t in tables),\n                            flatten(t.domain.metas for t in tables))\n\n            def ndmin(A):\n                return A if A.ndim > 1 else A.reshape(A.shape[0], 1)\n\n            table = Table.from_numpy(domain,\n                                     np.hstack(tuple(ndmin(t.X) for t in tables)),\n                                     np.hstack(tuple(ndmin(t.Y) for t in tables)),\n                                     np.hstack(tuple(ndmin(t.metas) for t in tables)),\n                                     np.hstack(tuple(ndmin(t.W) for t in tables)))\n            return table\n        raise ValueError('axis {} out of bounds [0, 2)'.format(axis))\n\n    def is_view(self):\n        \"\"\"\n        Return `True` if all arrays represent a view referring to another table\n        \"\"\"\n        return ((not self.X.shape[-1] or self.X.base is not None) and\n                (not self._Y.shape[-1] or self._Y.base is not None) and\n                (not self.metas.shape[-1] or self.metas.base is not None) and\n                (not self._weights.shape[-1] or self.W.base is not None))\n\n    def is_copy(self):\n        \"\"\"\n        Return `True` if the table owns its data\n        \"\"\"\n        return ((not self.X.shape[-1] or self.X.base is None) and\n                (self._Y.base is None) and\n                (self.metas.base is None) and\n                (self.W.base is None))\n\n    def is_sparse(self):\n        \"\"\"\n        Return `True` if the table stores data in sparse format\n        \"\"\"\n        return any(sp.issparse(i) for i in [self.X, self.Y, self.metas])\n\n    def ensure_copy(self):\n        \"\"\"\n        Ensure that the table owns its data; copy arrays when necessary.\n        \"\"\"\n        def is_view(x):\n            # Sparse matrices don't have views like numpy arrays. Since indexing on\n            # them creates copies in constructor we can skip this check here.\n            return not sp.issparse(x) and x.base is not None\n\n        if is_view(self.X):\n            self.X = self.X.copy()\n        if is_view(self._Y):\n            self._Y = self._Y.copy()\n        if is_view(self.metas):\n            self.metas = self.metas.copy()\n        if is_view(self.W):\n            self.W = self.W.copy()\n\n    def copy(self):\n        \"\"\"\n        Return a copy of the table\n        \"\"\"\n        t = self.__class__(self)\n        t.ensure_copy()\n        return t\n\n    @staticmethod\n    def __determine_density(data):\n        if data is None:\n            return Storage.Missing\n        if data is not None and sp.issparse(data):\n            return Storage.SPARSE_BOOL if (data.data == 1).all() else Storage.SPARSE\n        else:\n            return Storage.DENSE\n\n    def X_density(self):\n        if not hasattr(self, \"_X_density\"):\n            self._X_density = self.__determine_density(self.X)\n        return self._X_density\n\n    def Y_density(self):\n        if not hasattr(self, \"_Y_density\"):\n            self._Y_density = self.__determine_density(self._Y)\n        return self._Y_density\n\n    def metas_density(self):\n        if not hasattr(self, \"_metas_density\"):\n            self._metas_density = self.__determine_density(self.metas)\n        return self._metas_density\n\n    def set_weights(self, weight=1):\n        \"\"\"\n        Set weights of data instances; create a vector of weights if necessary.\n        \"\"\"\n        if not self.W.shape[-1]:\n            self.W = np.empty(len(self))\n        self.W[:] = weight\n\n    def has_weights(self):\n        \"\"\"Return `True` if the data instances are weighed. \"\"\"\n        return self.W.shape[-1] != 0\n\n    def total_weight(self):\n        \"\"\"\n        Return the total weight of instances in the table, or their number if\n        they are unweighted.\n        \"\"\"\n        if self.W.shape[-1]:\n            return sum(self.W)\n        return len(self)\n\n    def has_missing(self):\n        \"\"\"Return `True` if there are any missing attribute or class values.\"\"\"\n        missing_x = not sp.issparse(self.X) and bn.anynan(self.X)   # do not check for sparse X\n        return missing_x or bn.anynan(self._Y)\n\n    def has_missing_attribute(self):\n        \"\"\"Return `True` if there are any missing attribute values.\"\"\"\n        return not sp.issparse(self.X) and bn.anynan(self.X)    # do not check for sparse X\n\n    def has_missing_class(self):\n        \"\"\"Return `True` if there are any missing class values.\"\"\"\n        return bn.anynan(self._Y)\n\n    def get_nan_frequency_attribute(self):\n        if self.X.size == 0:\n            return 0\n        return np.isnan(self.X).sum() / self.X.size\n\n    def get_nan_frequency_class(self):\n        if self.Y.size == 0:\n            return 0\n        return np.isnan(self._Y).sum() / self._Y.size\n\n    def checksum(self, include_metas=True):\n        # TODO: zlib.adler32 does not work for numpy arrays with dtype object\n        # (after pickling and unpickling such arrays, checksum changes)\n        # Why, and should we fix it or remove it?\n        \"\"\"Return a checksum over X, Y, metas and W.\"\"\"\n        cs = zlib.adler32(np.ascontiguousarray(self.X))\n        cs = zlib.adler32(np.ascontiguousarray(self._Y), cs)\n        if include_metas:\n            cs = zlib.adler32(np.ascontiguousarray(self.metas), cs)\n        cs = zlib.adler32(np.ascontiguousarray(self.W), cs)\n        return cs\n\n    def shuffle(self):\n        \"\"\"Randomly shuffle the rows of the table.\"\"\"\n        if not self._check_all_dense():\n            raise ValueError(\"Rows of sparse data cannot be shuffled\")\n        ind = np.arange(self.X.shape[0])\n        np.random.shuffle(ind)\n        self.X = self.X[ind]\n        self._Y = self._Y[ind]\n        self.metas = self.metas[ind]\n        self.W = self.W[ind]\n\n    def get_column_view(self, index):\n        \"\"\"\n        Return a vector - as a view, not a copy - with a column of the table,\n        and a bool flag telling whether this column is sparse. Note that\n        vertical slicing of sparse matrices is inefficient.\n\n        :param index: the index of the column\n        :type index: int, str or Orange.data.Variable\n        :return: (one-dimensional numpy array, sparse)\n        \"\"\"\n\n        def rx(M):\n            if sp.issparse(M):\n                return np.asarray(M.todense())[:, 0], True\n            else:\n                return M, False\n\n        if not isinstance(index, Integral):\n            index = self.domain.index(index)\n        if index >= 0:\n            if index < self.X.shape[1]:\n                return rx(self.X[:, index])\n            else:\n                return rx(self._Y[:, index - self.X.shape[1]])\n        else:\n            return rx(self.metas[:, -1 - index])\n\n    def _filter_is_defined(self, columns=None, negate=False):\n        if columns is None:\n            if sp.issparse(self.X):\n                remove = (self.X.indptr[1:] !=\n                          self.X.indptr[-1:] + self.X.shape[1])\n            else:\n                remove = bn.anynan(self.X, axis=1)\n            if sp.issparse(self._Y):\n                remove = np.logical_or(remove, self._Y.indptr[1:] !=\n                                       self._Y.indptr[-1:] + self._Y.shape[1])\n            else:\n                remove = np.logical_or(remove, bn.anynan(self._Y, axis=1))\n        else:\n            remove = np.zeros(len(self), dtype=bool)\n            for column in columns:\n                col, sparse = self.get_column_view(column)\n                if sparse:\n                    remove = np.logical_or(remove, col == 0)\n                else:\n                    remove = np.logical_or(remove, bn.anynan([col], axis=0))\n        retain = remove if negate else np.logical_not(remove)\n        return self.from_table_rows(self, retain)\n\n    def _filter_has_class(self, negate=False):\n        if sp.issparse(self._Y):\n            if negate:\n                retain = (self._Y.indptr[1:] !=\n                          self._Y.indptr[-1:] + self._Y.shape[1])\n            else:\n                retain = (self._Y.indptr[1:] ==\n                          self._Y.indptr[-1:] + self._Y.shape[1])\n        else:\n            retain = bn.anynan(self._Y, axis=1)\n            if not negate:\n                retain = np.logical_not(retain)\n        return self.from_table_rows(self, retain)\n\n    def _filter_same_value(self, column, value, negate=False):\n        if not isinstance(value, Real):\n            value = self.domain[column].to_val(value)\n        sel = self.get_column_view(column)[0] == value\n        if negate:\n            sel = np.logical_not(sel)\n        return self.from_table_rows(self, sel)\n\n    def _filter_values(self, filter):\n        selection = self._values_filter_to_indicator(filter)\n        return self.from_table(self.domain, self, selection)\n\n    def _values_filter_to_indicator(self, filter):\n        \"\"\"Return selection of rows matching the filter conditions\n\n        Handles conjunction/disjunction and negate modifiers\n\n        Parameters\n        ----------\n        filter: Values object containing the conditions\n\n        Returns\n        -------\n        A 1d bool array. len(result) == len(self)\n        \"\"\"\n        from Orange.data.filter import Values\n\n        if isinstance(filter, Values):\n            conditions = filter.conditions\n            conjunction = filter.conjunction\n        else:\n            conditions = [filter]\n            conjunction = True\n        if conjunction:\n            sel = np.ones(len(self), dtype=bool)\n        else:\n            sel = np.zeros(len(self), dtype=bool)\n\n        for f in conditions:\n            selection = self._filter_to_indicator(f)\n\n            if conjunction:\n                sel *= selection\n            else:\n                sel += selection\n\n        if filter.negate:\n            sel = ~sel\n        return sel\n\n    def _filter_to_indicator(self, filter):\n        \"\"\"Return selection of rows that match the condition.\n\n        Parameters\n        ----------\n        filter: ValueFilter describing the condition\n\n        Returns\n        -------\n        A 1d bool array. len(result) == len(self)\n        \"\"\"\n        from Orange.data.filter import (\n            FilterContinuous, FilterDiscrete, FilterRegex, FilterString,\n            FilterStringList, Values\n        )\n        if isinstance(filter, Values):\n            return self._values_filter_to_indicator(filter)\n\n        col = self.get_column_view(filter.column)[0]\n\n        if isinstance(filter, FilterDiscrete):\n            return self._discrete_filter_to_indicator(filter, col)\n\n        if isinstance(filter, FilterContinuous):\n            return self._continuous_filter_to_indicator(filter, col)\n\n        if isinstance(filter, FilterString):\n            return self._string_filter_to_indicator(filter, col)\n\n        if isinstance(filter, FilterStringList):\n            if not filter.case_sensitive:\n                col = np.char.lower(np.array(col, dtype=str))\n                vals = [val.lower() for val in filter.values]\n            else:\n                vals = filter.values\n            return reduce(operator.add, (col == val for val in vals))\n\n        if isinstance(filter, FilterRegex):\n            return np.vectorize(filter)(col)\n\n        raise TypeError(\"Invalid filter\")\n\n    def _discrete_filter_to_indicator(self, filter, col):\n        \"\"\"Return selection of rows matched by the given discrete filter.\n\n        Parameters\n        ----------\n        filter: FilterDiscrete\n        col: np.ndarray\n\n        Returns\n        -------\n        A 1d bool array. len(result) == len(self)\n        \"\"\"\n        if filter.values is None:  # <- is defined filter\n            col = col.astype(float)\n            return ~np.isnan(col)\n\n        sel = np.zeros(len(self), dtype=bool)\n        for val in filter.values:\n            if not isinstance(val, Real):\n                val = self.domain[filter.column].to_val(val)\n            sel += (col == val)\n        return sel\n\n    def _continuous_filter_to_indicator(self, filter, col):\n        \"\"\"Return selection of rows matched by the given continuous filter.\n\n        Parameters\n        ----------\n        filter: FilterContinuous\n        col: np.ndarray\n\n        Returns\n        -------\n        A 1d bool array. len(result) == len(self)\n        \"\"\"\n        if filter.oper == filter.IsDefined:\n            col = col.astype(float)\n            return ~np.isnan(col)\n\n        return self._range_filter_to_indicator(filter, col, filter.min, filter.max)\n\n    def _string_filter_to_indicator(self, filter, col):\n        \"\"\"Return selection of rows matched by the given string filter.\n\n        Parameters\n        ----------\n        filter: FilterString\n        col: np.ndarray\n\n        Returns\n        -------\n        A 1d bool array. len(result) == len(self)\n        \"\"\"\n        if filter.oper == filter.IsDefined:\n            return col.astype(bool)\n\n        col = col.astype(str)\n        fmin = filter.min or \"\"\n        fmax = filter.max or \"\"\n\n        if not filter.case_sensitive:\n            # convert all to lower case\n            col = np.char.lower(col)\n            fmin = fmin.lower()\n            fmax = fmax.lower()\n\n        if filter.oper == filter.Contains:\n            return np.fromiter((fmin in e for e in col),\n                               dtype=bool)\n        if filter.oper == filter.StartsWith:\n            return np.fromiter((e.startswith(fmin) for e in col),\n                               dtype=bool)\n        if filter.oper == filter.EndsWith:\n            return np.fromiter((e.endswith(fmin) for e in col),\n                               dtype=bool)\n\n        return self._range_filter_to_indicator(filter, col, fmin, fmax)\n\n    @staticmethod\n    def _range_filter_to_indicator(filter, col, fmin, fmax):\n        if filter.oper == filter.Equal:\n            return col == fmin\n        if filter.oper == filter.NotEqual:\n            return col != fmin\n        if filter.oper == filter.Less:\n            return col < fmin\n        if filter.oper == filter.LessEqual:\n            return col <= fmin\n        if filter.oper == filter.Greater:\n            return col > fmin\n        if filter.oper == filter.GreaterEqual:\n            return col >= fmin\n        if filter.oper == filter.Between:\n            return (col >= fmin) * (col <= fmax)\n        if filter.oper == filter.Outside:\n            return (col < fmin) + (col > fmax)\n\n        raise TypeError(\"Invalid operator\")\n\n    def _compute_basic_stats(self, columns=None,\n                             include_metas=False, compute_variance=False):\n        if compute_variance:\n            raise NotImplementedError(\"computation of variance is \"\n                                      \"not implemented yet\")\n        W = self.W if self.has_weights() else None\n        rr = []\n        stats = []\n        if not columns:\n            if self.domain.attributes:\n                rr.append(fast_stats(self.X, W))\n            if self.domain.class_vars:\n                rr.append(fast_stats(self._Y, W))\n            if include_metas and self.domain.metas:\n                rr.append(fast_stats(self.metas, W))\n            if len(rr):\n                stats = np.vstack(tuple(rr))\n        else:\n            nattrs = len(self.domain.attributes)\n            for column in columns:\n                c = self.domain.index(column)\n                if 0 <= c < nattrs:\n                    S = fast_stats(self.X[:, [c]], W and W[:, [c]])\n                elif c >= nattrs:\n                    S = fast_stats(self._Y[:, [c-nattrs]], W and W[:, [c-nattrs]])\n                else:\n                    S = fast_stats(self.metas[:, [-1-c]], W and W[:, [-1-c]])\n                stats.append(S[0])\n        return stats\n\n    def _compute_distributions(self, columns=None):\n        if columns is None:\n            columns = range(len(self.domain.variables))\n        else:\n            columns = [self.domain.index(var) for var in columns]\n\n        distributions = []\n        if sp.issparse(self.X):\n            self.X = self.X.tocsc()\n\n        W = self.W.ravel() if self.has_weights() else None\n\n        for col in columns:\n            variable = self.domain[col]\n\n            # Select the correct data column from X, Y or metas\n            if 0 <= col < self.X.shape[1]:\n                x = self.X[:, col]\n            elif col < 0:\n                x = self.metas[:, col * (-1) - 1]\n                if np.issubdtype(x.dtype, np.dtype(object)):\n                    x = x.astype(float)\n            else:\n                x = self._Y[:, col - self.X.shape[1]]\n\n            if variable.is_discrete:\n                dist, unknowns = bincount(x, weights=W, max_val=len(variable.values) - 1)\n            elif not x.shape[0]:\n                dist, unknowns = np.zeros((2, 0)), 0\n            else:\n                if W is not None:\n                    if sp.issparse(x):\n                        arg_sort = np.argsort(x.data)\n                        ranks = x.indices[arg_sort]\n                        vals = np.vstack((x.data[arg_sort], W[ranks]))\n                    else:\n                        ranks = np.argsort(x)\n                        vals = np.vstack((x[ranks], W[ranks]))\n                else:\n                    x_values = x.data if sp.issparse(x) else x\n                    vals = np.ones((2, x_values.shape[0]))\n                    vals[0, :] = x_values\n                    vals[0, :].sort()\n\n                dist = np.array(_valuecount.valuecount(vals))\n                # If sparse, then 0s will not be counted with `valuecount`, so\n                # we have to add them to the result manually.\n                if sp.issparse(x) and sparse_has_implicit_zeros(x):\n                    if W is not None:\n                        zero_weights = sparse_implicit_zero_weights(x, W).sum()\n                    else:\n                        zero_weights = sparse_count_implicit_zeros(x)\n                    zero_vec = [0, zero_weights]\n                    dist = np.insert(dist, np.searchsorted(dist[0], 0), zero_vec, axis=1)\n                # Since `countnans` assumes vector shape to be (1, n) and `x`\n                # shape is (n, 1), we pass the transpose\n                unknowns = countnans(x.T, W)\n            distributions.append((dist, unknowns))\n\n        return distributions\n\n    def _compute_contingency(self, col_vars=None, row_var=None):\n        n_atts = self.X.shape[1]\n\n        if col_vars is None:\n            col_vars = range(len(self.domain.variables))\n        else:\n            col_vars = [self.domain.index(var) for var in col_vars]\n        if row_var is None:\n            row_var = self.domain.class_var\n            if row_var is None:\n                raise ValueError(\"No row variable\")\n\n        row_desc = self.domain[row_var]\n        if not row_desc.is_discrete:\n            raise TypeError(\"Row variable must be discrete\")\n        row_indi = self.domain.index(row_var)\n        n_rows = len(row_desc.values)\n        if 0 <= row_indi < n_atts:\n            row_data = self.X[:, row_indi]\n        elif row_indi < 0:\n            row_data = self.metas[:, -1 - row_indi]\n        else:\n            row_data = self._Y[:, row_indi - n_atts]\n\n        W = self.W if self.has_weights() else None\n        nan_inds = None\n\n        col_desc = [self.domain[var] for var in col_vars]\n        col_indi = [self.domain.index(var) for var in col_vars]\n\n        if any(not (var.is_discrete or var.is_continuous)\n               for var in col_desc):\n            raise ValueError(\"contingency can be computed only for discrete \"\n                             \"and continuous values\")\n\n        if row_data.dtype.kind != \"f\": #meta attributes can be stored as type object\n            row_data = row_data.astype(float)\n\n        unknown_rows = countnans(row_data)\n        if unknown_rows:\n            nan_inds = np.isnan(row_data)\n            row_data = row_data[~nan_inds]\n            if W:\n                W = W[~nan_inds]\n                unknown_rows = np.sum(W[nan_inds])\n\n        contingencies = [None] * len(col_desc)\n        for arr, f_cond, f_ind in (\n                (self.X, lambda i: 0 <= i < n_atts, lambda i: i),\n                (self._Y, lambda i: i >= n_atts, lambda i: i - n_atts),\n                (self.metas, lambda i: i < 0, lambda i: -1 - i)):\n\n            if nan_inds is not None:\n                arr = arr[~nan_inds]\n\n            arr_indi = [e for e, ind in enumerate(col_indi) if f_cond(ind)]\n\n            vars = [(e, f_ind(col_indi[e]), col_desc[e]) for e in arr_indi]\n            disc_vars = [v for v in vars if v[2].is_discrete]\n            if disc_vars:\n                if sp.issparse(arr):\n                    max_vals = max(len(v[2].values) for v in disc_vars)\n                    disc_indi = {i for _, i, _ in disc_vars}\n                    mask = [i in disc_indi for i in range(arr.shape[1])]\n                    conts, nans = contingency(arr, row_data, max_vals - 1,\n                                              n_rows - 1, W, mask)\n                    for col_i, arr_i, var in disc_vars:\n                        n_vals = len(var.values)\n                        contingencies[col_i] = (conts[arr_i][:, :n_vals],\n                                                nans[arr_i])\n                else:\n                    for col_i, arr_i, var in disc_vars:\n                        contingencies[col_i] = contingency(\n                            arr[:, arr_i].astype(float),\n                            row_data, len(var.values) - 1, n_rows - 1, W)\n\n            cont_vars = [v for v in vars if v[2].is_continuous]\n            if cont_vars:\n\n                classes = row_data.astype(dtype=np.intp)\n                if W is not None:\n                    W = W.astype(dtype=np.float64)\n                if sp.issparse(arr):\n                    arr = sp.csc_matrix(arr)\n\n                for col_i, arr_i, _ in cont_vars:\n                    if sp.issparse(arr):\n                        col_data = arr.data[arr.indptr[arr_i]:arr.indptr[arr_i + 1]]\n                        rows = arr.indices[arr.indptr[arr_i]:arr.indptr[arr_i + 1]]\n                        W_ = None if W is None else W[rows]\n                        classes_ = classes[rows]\n                    else:\n                        col_data, W_, classes_ = arr[:, arr_i], W, classes\n\n                    col_data = col_data.astype(dtype=np.float64)\n                    U, C, unknown = _contingency.contingency_floatarray(\n                        col_data, classes_, n_rows, W_)\n                    contingencies[col_i] = ([U, C], unknown)\n\n        return contingencies, unknown_rows\n\n    @classmethod\n    def transpose(cls, table, feature_names_column=\"\", meta_attr_name=\"Feature name\",\n                  feature_name=\"Feature\"):\n        \"\"\"\n        Transpose the table.\n\n        :param table: Table - table to transpose\n        :param feature_names_column: str - name of (String) meta attribute to\n            use for feature names\n        :param meta_attr_name: str - name of new meta attribute into which\n            feature names are mapped\n        :return: Table - transposed table\n        \"\"\"\n\n        self = cls()\n        n_cols, self.n_rows = table.X.shape\n        old_domain = table.attributes.get(\"old_domain\")\n\n        # attributes\n        # - classes and metas to attributes of attributes\n        # - arbitrary meta column to feature names\n        self.X = table.X.T\n        attributes = [ContinuousVariable(str(row[feature_names_column]))\n                      for row in table] if feature_names_column else \\\n            [ContinuousVariable(feature_name + \" \" + str(i + 1).zfill(\n                int(np.ceil(np.log10(n_cols))))) for i in range(n_cols)]\n        if old_domain is not None and feature_names_column:\n            for i, _ in enumerate(attributes):\n                if attributes[i].name in old_domain:\n                    var = old_domain[attributes[i].name]\n                    attr = ContinuousVariable(var.name) if var.is_continuous \\\n                        else DiscreteVariable(var.name, var.values)\n                    attr.attributes = var.attributes.copy()\n                    attributes[i] = attr\n\n        def set_attributes_of_attributes(_vars, _table):\n            for i, variable in enumerate(_vars):\n                if variable.name == feature_names_column:\n                    continue\n                for j, row in enumerate(_table):\n                    value = variable.repr_val(row) if np.isscalar(row) \\\n                        else row[i] if isinstance(row[i], str) \\\n                        else variable.repr_val(row[i])\n\n                    if value not in MISSING_VALUES:\n                        attributes[j].attributes[variable.name] = value\n\n        set_attributes_of_attributes(table.domain.class_vars, table.Y)\n        set_attributes_of_attributes(table.domain.metas, table.metas)\n\n        # weights\n        self.W = np.empty((self.n_rows, 0))\n\n        def get_table_from_attributes_of_attributes(_vars, _dtype=float):\n            T = np.empty((self.n_rows, len(_vars)), dtype=_dtype)\n            for i, _attr in enumerate(table.domain.attributes):\n                for j, _var in enumerate(_vars):\n                    val = str(_attr.attributes.get(_var.name, \"\"))\n                    if not _var.is_string:\n                        val = np.nan if val in MISSING_VALUES else \\\n                            _var.values.index(val) if \\\n                                _var.is_discrete else float(val)\n                    T[i, j] = val\n            return T\n\n        # class_vars - attributes of attributes to class - from old domain\n        class_vars = []\n        if old_domain is not None:\n            class_vars = old_domain.class_vars\n        self.Y = get_table_from_attributes_of_attributes(class_vars)\n\n        # metas\n        # - feature names and attributes of attributes to metas\n        self.metas, metas = np.empty((self.n_rows, 0), dtype=object), []\n        if meta_attr_name not in [m.name for m in table.domain.metas] and \\\n                table.domain.attributes:\n            self.metas = np.array([[a.name] for a in table.domain.attributes],\n                                  dtype=object)\n            metas.append(StringVariable(meta_attr_name))\n\n        names = chain.from_iterable(list(attr.attributes)\n                                    for attr in table.domain.attributes)\n        names = sorted(set(names) - {var.name for var in class_vars})\n\n        def guessed_var(i, var_name):\n            orig_vals = M[:, i]\n            val_map, vals, var_type = Orange.data.io.guess_data_type(orig_vals)\n            values, variable = Orange.data.io.sanitize_variable(\n                val_map, vals, orig_vals, var_type, {}, name=var_name)\n            M[:, i] = values\n            return variable\n\n        _metas = [StringVariable(n) for n in names]\n        if old_domain is not None:\n            _metas = [m for m in old_domain.metas if m.name != meta_attr_name]\n        M = get_table_from_attributes_of_attributes(_metas, _dtype=object)\n        if old_domain is None:\n            _metas = [guessed_var(i, m.name) for i, m in enumerate(_metas)]\n        if _metas:\n            self.metas = np.hstack((self.metas, M))\n            metas.extend(_metas)\n\n        self.domain = Domain(attributes, class_vars, metas)\n        cls._init_ids(self)\n        self.attributes = table.attributes.copy()\n        self.attributes[\"old_domain\"] = table.domain\n        return self\n\n    def to_sparse(self, sparse_attributes=True, sparse_class=False,\n                  sparse_metas=False):\n        def sparsify(features):\n            for f in features:\n                f.sparse = True\n\n        new_domain = self.domain.copy()\n\n        if sparse_attributes:\n            sparsify(new_domain.attributes)\n        if sparse_class:\n            sparsify(new_domain.class_vars)\n        if sparse_metas:\n            sparsify(new_domain.metas)\n        return self.transform(new_domain)\n\n    def to_dense(self, dense_attributes=True, dense_class=True,\n                 dense_metas=True):\n        def densify(features):\n            for f in features:\n                f.sparse = False\n\n        new_domain = self.domain.copy()\n\n        if dense_attributes:\n            densify(new_domain.attributes)\n        if dense_class:\n            densify(new_domain.class_vars)\n        if dense_metas:\n            densify(new_domain.metas)\n        t = self.transform(new_domain)\n        t.ids = self.ids    # preserve indices\n        return t\n\n\ndef _check_arrays(*arrays, dtype=None):\n    checked = []\n    if not len(arrays):\n        return checked\n\n    def ninstances(array):\n        if hasattr(array, \"shape\"):\n            return array.shape[0]\n        else:\n            return len(array) if array is not None else 0\n\n    shape_1 = ninstances(arrays[0])\n\n    for array in arrays:\n        if array is None:\n            checked.append(array)\n            continue\n\n        if ninstances(array) != shape_1:\n            raise ValueError(\"Leading dimension mismatch (%d != %d)\"\n                             % (ninstances(array), shape_1))\n\n        if sp.issparse(array):\n            array.data = np.asarray(array.data)\n            has_inf = _check_inf(array.data)\n        else:\n            if dtype is not None:\n                array = np.asarray(array, dtype=dtype)\n            else:\n                array = np.asarray(array)\n            has_inf = _check_inf(array)\n\n        if has_inf:\n            raise ValueError(\"Array contains infinity.\")\n        checked.append(array)\n\n    return checked\n\n\ndef _check_inf(array):\n    return array.dtype.char in np.typecodes['AllFloat'] and \\\n           np.isinf(array.data).any()\n\n\ndef _subarray(arr, rows, cols):\n    rows = _optimize_indices(rows, arr.shape[0])\n    cols = _optimize_indices(cols, arr.shape[1])\n    return arr[_rxc_ix(rows, cols)]\n\n\ndef _optimize_indices(indices, maxlen):\n    \"\"\"\n    Convert integer indices to slice if possible. It only converts increasing\n    integer ranges with positive steps and valid starts and ends.\n    Only convert valid ends so that invalid ranges will still raise\n    an exception.\n\n    Allows numpy to reuse the data array, because it defaults to copying\n    if given indices.\n\n    Parameters\n    ----------\n    indices : 1D sequence, slice or Ellipsis\n    \"\"\"\n    if isinstance(indices, slice):\n        return indices\n\n    if indices is ...:\n        return slice(None, None, 1)\n\n    if len(indices) >= 1:\n        indices = np.asarray(indices)\n        if indices.dtype != np.bool:\n            begin = indices[0]\n            end = indices[-1]\n            steps = np.diff(indices) if len(indices) > 1 else np.array([1])\n            step = steps[0]\n\n            # continuous ranges with constant step and valid start and stop index can be slices\n            if np.all(steps == step) and step > 0 and begin >= 0 and end < maxlen:\n                return slice(begin, end + step, step)\n\n    return indices\n\n\ndef _rxc_ix(rows, cols):\n    \"\"\"\n    Construct an index object to index the `rows` x `cols` cross product.\n\n    Rows and columns can be a 1d bool or int sequence, or a slice.\n    The later is a convenience and is interpreted the same\n    as `slice(None, None, -1)`\n\n    Parameters\n    ----------\n    rows : 1D sequence, slice\n        Row indices.\n    cols : 1D sequence, slice\n        Column indices.\n\n    See Also\n    --------\n    numpy.ix_\n\n    Examples\n    --------\n    >>> import numpy as np\n    >>> a = np.arange(10).reshape(2, 5)\n    >>> a[_rxc_ix([0, 1], [3, 4])]\n    array([[3, 4],\n           [8, 9]])\n    >>> a[_rxc_ix([False, True], slice(None, None, 1))]\n    array([[5, 6, 7, 8, 9]])\n\n    \"\"\"\n    isslice = (isinstance(rows, slice), isinstance(cols, slice))\n    if isslice == (True, True):\n        return rows, cols\n    elif isslice == (True, False):\n        return rows, np.asarray(np.ix_(cols), int).ravel()\n    elif isslice == (False, True):\n        return np.asarray(np.ix_(rows), int).ravel(), cols\n    else:\n        r, c = np.ix_(rows, cols)\n        return np.asarray(r, int), np.asarray(c, int)\n\n\ndef assure_domain_conversion_sparsity(target, source):\n    \"\"\"\n    Assure that the table obeys the domain conversion's suggestions about sparsity.\n\n    Args:\n        target (Table): the target table.\n        source (Table): the source table.\n\n    Returns:\n        Table: with fixed sparsity. The sparsity is set as it is recommended by domain conversion\n            for transformation from source to the target domain.\n    \"\"\"\n    conversion = target.domain.get_conversion(source.domain)\n    match_density = [assure_array_dense, assure_array_sparse]\n    target.X = match_density[conversion.sparse_X](target.X)\n    target.Y = match_density[conversion.sparse_Y](target.Y)\n    target.metas = match_density[conversion.sparse_metas](target.metas)\n    return target\n",
            "new_file_content": "import operator\nimport os\nimport warnings\nimport zlib\nfrom collections import MutableSequence, Iterable, Sequence, Sized\nfrom functools import reduce\nfrom itertools import chain\nfrom numbers import Real, Integral\nfrom threading import Lock, RLock\n\nimport bottleneck as bn\nimport numpy as np\nfrom scipy import sparse as sp\n\nimport Orange.data  # import for io.py\nfrom Orange.data import (\n    _contingency, _valuecount,\n    Domain, Variable, Storage, StringVariable, Unknown, Value, Instance,\n    ContinuousVariable, DiscreteVariable, MISSING_VALUES\n)\nfrom Orange.data.util import SharedComputeValue, vstack, hstack, \\\n    assure_array_dense, assure_array_sparse, \\\n    assure_column_dense, assure_column_sparse\nfrom Orange.statistics.util import bincount, countnans, contingency, \\\n    stats as fast_stats, sparse_has_implicit_zeros, sparse_count_implicit_zeros, \\\n    sparse_implicit_zero_weights\nfrom Orange.util import flatten\n\n__all__ = [\"dataset_dirs\", \"get_sample_datasets_dir\", \"RowInstance\", \"Table\"]\n\n\ndef get_sample_datasets_dir():\n    orange_data_table = os.path.dirname(__file__)\n    dataset_dir = os.path.join(orange_data_table, '..', 'datasets')\n    return os.path.realpath(dataset_dir)\n\n\ndataset_dirs = ['', get_sample_datasets_dir()]\n\n\n\"\"\"Domain conversion cache used in Table.from_table. It is global so that\nchaining of domain conversions also works with caching even with descendants\nof Table.\"\"\"\n_conversion_cache = None\n_conversion_cache_lock = RLock()\n\n\ndef pending_deprecation_resize(name):\n    warnings.warn(f\"Method Table.{name} will be removed in Orange 3.24\",\n                  PendingDeprecationWarning)\n\n\nclass DomainTransformationError(Exception):\n    pass\n\n\nclass RowInstance(Instance):\n    sparse_x = None\n    sparse_y = None\n    sparse_metas = None\n    _weight = None\n\n    def __init__(self, table, row_index):\n        \"\"\"\n        Construct a data instance representing the given row of the table.\n        \"\"\"\n        self.table = table\n        self._domain = table.domain\n        self.row_index = row_index\n        self.id = table.ids[row_index]\n        self._x = table.X[row_index]\n        if sp.issparse(self._x):\n            self.sparse_x = sp.csr_matrix(self._x)\n            self._x = np.asarray(self._x.todense())[0]\n        self._y = table._Y[row_index]\n        if sp.issparse(self._y):\n            self.sparse_y = sp.csr_matrix(self._y)\n            self._y = np.asarray(self._y.todense())[0]\n        self._metas = table.metas[row_index]\n        if sp.issparse(self._metas):\n            self.sparse_metas = sp.csr_matrix(self._metas)\n            self._metas = np.asarray(self._metas.todense())[0]\n\n    @property\n    def weight(self):\n        if not self.table.has_weights():\n            return 1\n        return self.table.W[self.row_index]\n\n    @weight.setter\n    def weight(self, weight):\n        if not self.table.has_weights():\n            self.table.set_weights()\n        self.table.W[self.row_index] = weight\n\n    def set_class(self, value):\n        self._check_single_class()\n        if not isinstance(value, Real):\n            value = self.table.domain.class_var.to_val(value)\n        self._y[0] = value\n        if self.sparse_y:\n            self.table._Y[self.row_index, 0] = value\n\n    def __setitem__(self, key, value):\n        if not isinstance(key, Integral):\n            key = self._domain.index(key)\n        if isinstance(value, str):\n            var = self._domain[key]\n            value = var.to_val(value)\n        if key >= 0:\n            if not isinstance(value, Real):\n                raise TypeError(\"Expected primitive value, got '%s'\" %\n                                type(value).__name__)\n            if key < len(self._x):\n                self._x[key] = value\n                if self.sparse_x is not None:\n                    self.table.X[self.row_index, key] = value\n            else:\n                self._y[key - len(self._x)] = value\n                if self.sparse_y is not None:\n                    self.table._Y[self.row_index, key - len(self._x)] = value\n        else:\n            self._metas[-1 - key] = value\n            if self.sparse_metas:\n                self.table.metas[self.row_index, -1 - key] = value\n\n    def _str(self, limit):\n        def sp_values(matrix, variables):\n            if not sp.issparse(matrix):\n                if matrix.ndim == 1:\n                    matrix = matrix[:, np.newaxis]\n                return Instance.str_values(matrix[row], variables, limit)\n\n            row_entries, idx = [], 0\n            while idx < len(variables):\n                # Make sure to stop printing variables if we limit the output\n                if limit and len(row_entries) >= 5:\n                    break\n\n                var = variables[idx]\n                if var.is_discrete or matrix[row, idx]:\n                    row_entries.append(\"%s=%s\" % (var.name, var.str_val(matrix[row, idx])))\n\n                idx += 1\n\n            s = \", \".join(row_entries)\n\n            if limit and idx < len(variables):\n                s += \", ...\"\n\n            return s\n\n        table = self.table\n        domain = table.domain\n        row = self.row_index\n        s = \"[\" + sp_values(table.X, domain.attributes)\n        if domain.class_vars:\n            s += \" | \" + sp_values(table.Y, domain.class_vars)\n        s += \"]\"\n        if self._domain.metas:\n            s += \" {\" + sp_values(table.metas, domain.metas) + \"}\"\n        return s\n\n    def __str__(self):\n        return self._str(False)\n\n    def __repr__(self):\n        return self._str(True)\n\n\nclass Columns:\n    def __init__(self, domain):\n        for v in chain(domain.variables, domain.metas):\n            setattr(self, v.name.replace(\" \", \"_\"), v)\n\n\n# noinspection PyPep8Naming\nclass Table(MutableSequence, Storage):\n    __file__ = None\n    name = \"untitled\"\n\n    @property\n    def columns(self):\n        \"\"\"\n        A class whose attributes contain attribute descriptors for columns.\n        For a table `table`, setting `c = table.columns` will allow accessing\n        the table's variables with, for instance `c.gender`, `c.age` ets.\n        Spaces are replaced with underscores.\n        \"\"\"\n        return Columns(self.domain)\n\n    _next_instance_id = 0\n    _next_instance_lock = Lock()\n\n    @property\n    def Y(self):\n        if self._Y.shape[1] == 1:\n            return self._Y[:, 0]\n        return self._Y\n\n    @Y.setter\n    def Y(self, value):\n        if len(value.shape) == 1:\n            value = value[:, None]\n        if sp.issparse(value) and len(self) != value.shape[0]:\n            value = value.T\n        self._Y = value\n\n    def __new__(cls, *args, **kwargs):\n        if not args and not kwargs:\n            return super().__new__(cls)\n\n        if 'filename' in kwargs:\n            args = [kwargs.pop('filename')]\n\n        if not args:\n            raise TypeError(\n                \"Table takes at least 1 positional argument (0 given))\")\n\n        if isinstance(args[0], str):\n            if args[0].startswith('https://') or args[0].startswith('http://'):\n                return cls.from_url(args[0], **kwargs)\n            else:\n                return cls.from_file(args[0])\n        elif isinstance(args[0], Table):\n            return cls.from_table(args[0].domain, args[0])\n        elif isinstance(args[0], Domain):\n            domain, args = args[0], args[1:]\n            if not args:\n                return cls.from_domain(domain, **kwargs)\n            if isinstance(args[0], Table):\n                return cls.from_table(domain, *args)\n            elif isinstance(args[0], list):\n                return cls.from_list(domain, *args)\n        else:\n            domain = None\n\n        return cls.from_numpy(domain, *args, **kwargs)\n\n    def __init__(self, *args, **kwargs):\n        # So subclasses can expect to call super without breakage; noop\n        pass\n\n    @classmethod\n    def from_domain(cls, domain, n_rows=0, weights=False):\n        \"\"\"\n        Construct a new `Table` with the given number of rows for the given\n        domain. The optional vector of weights is initialized to 1's.\n\n        :param domain: domain for the `Table`\n        :type domain: Orange.data.Domain\n        :param n_rows: number of rows in the new table\n        :type n_rows: int\n        :param weights: indicates whether to construct a vector of weights\n        :type weights: bool\n        :return: a new table\n        :rtype: Orange.data.Table\n        \"\"\"\n        self = cls()\n        self.domain = domain\n        self.n_rows = n_rows\n        self.X = np.zeros((n_rows, len(domain.attributes)))\n        self.Y = np.zeros((n_rows, len(domain.class_vars)))\n        if weights:\n            self.W = np.ones(n_rows)\n        else:\n            self.W = np.empty((n_rows, 0))\n        self.metas = np.empty((n_rows, len(self.domain.metas)), object)\n        cls._init_ids(self)\n        self.attributes = {}\n        return self\n\n    @classmethod\n    def from_table(cls, domain, source, row_indices=...):\n        \"\"\"\n        Create a new table from selected columns and/or rows of an existing\n        one. The columns are chosen using a domain. The domain may also include\n        variables that do not appear in the source table; they are computed\n        from source variables if possible.\n\n        The resulting data may be a view or a copy of the existing data.\n\n        :param domain: the domain for the new table\n        :type domain: Orange.data.Domain\n        :param source: the source table\n        :type source: Orange.data.Table\n        :param row_indices: indices of the rows to include\n        :type row_indices: a slice or a sequence\n        :return: a new table\n        :rtype: Orange.data.Table\n        \"\"\"\n\n        global _conversion_cache\n\n        def get_columns(row_indices, src_cols, n_rows, dtype=np.float64, is_sparse=False):\n            if not len(src_cols):\n                if is_sparse:\n                    return sp.csr_matrix((n_rows, 0), dtype=source.X.dtype)\n                else:\n                    return np.zeros((n_rows, 0), dtype=source.X.dtype)\n\n            # match density for subarrays\n            match_density = assure_array_sparse if is_sparse else assure_array_dense\n            n_src_attrs = len(source.domain.attributes)\n            if all(isinstance(x, Integral) and 0 <= x < n_src_attrs\n                   for x in src_cols):\n                return match_density(_subarray(source.X, row_indices, src_cols))\n            if all(isinstance(x, Integral) and x < 0 for x in src_cols):\n                arr = match_density(_subarray(source.metas, row_indices,\n                                              [-1 - x for x in src_cols]))\n                if arr.dtype != dtype:\n                    return arr.astype(dtype)\n                return arr\n            if all(isinstance(x, Integral) and x >= n_src_attrs\n                   for x in src_cols):\n                return match_density(_subarray(\n                    source._Y, row_indices,\n                    [x - n_src_attrs for x in src_cols]))\n\n            # initialize final array & set `match_density` for columns\n            if is_sparse:\n                a = sp.dok_matrix((n_rows, len(src_cols)), dtype=dtype)\n                match_density = assure_column_sparse\n            else:\n                a = np.empty((n_rows, len(src_cols)), dtype=dtype)\n                match_density = assure_column_dense\n\n            shared_cache = _conversion_cache\n            for i, col in enumerate(src_cols):\n                if col is None:\n                    a[:, i] = Unknown\n                elif not isinstance(col, Integral):\n                    if isinstance(col, SharedComputeValue):\n                        if (id(col.compute_shared), id(source)) not in shared_cache:\n                            shared_cache[id(col.compute_shared), id(source)] = \\\n                                col.compute_shared(source)\n                        shared = shared_cache[id(col.compute_shared), id(source)]\n                        if row_indices is not ...:\n                            a[:, i] = match_density(\n                                col(source, shared_data=shared)[row_indices])\n                        else:\n                            a[:, i] = match_density(\n                                col(source, shared_data=shared))\n                    else:\n                        if row_indices is not ...:\n                            a[:, i] = match_density(col(source)[row_indices])\n                        else:\n                            a[:, i] = match_density(col(source))\n                elif col < 0:\n                    a[:, i] = match_density(source.metas[row_indices, -1 - col])\n                elif col < n_src_attrs:\n                    a[:, i] = match_density(source.X[row_indices, col])\n                else:\n                    a[:, i] = match_density(\n                        source._Y[row_indices, col - n_src_attrs])\n\n            if is_sparse:\n                a = a.tocsr()\n\n            return a\n\n        with _conversion_cache_lock:\n            new_cache = _conversion_cache is None\n            try:\n                if new_cache:\n                    _conversion_cache = {}\n                else:\n                    cached = _conversion_cache.get((id(domain), id(source)))\n                    if cached:\n                        return cached\n                if domain == source.domain:\n                    table = cls.from_table_rows(source, row_indices)\n                    # assure resulting domain is the instance passed on input\n                    table.domain = domain\n                    # since sparse flags are not considered when checking for\n                    # domain equality, fix manually.\n                    table = assure_domain_conversion_sparsity(table, source)\n                    return table\n\n                if isinstance(row_indices, slice):\n                    start, stop, stride = row_indices.indices(source.X.shape[0])\n                    n_rows = (stop - start) // stride\n                    if n_rows < 0:\n                        n_rows = 0\n                elif row_indices is ...:\n                    n_rows = len(source)\n                else:\n                    n_rows = len(row_indices)\n\n                self = cls()\n                self.domain = domain\n                conversion = domain.get_conversion(source.domain)\n                self.X = get_columns(row_indices, conversion.attributes, n_rows,\n                                     is_sparse=conversion.sparse_X)\n                if self.X.ndim == 1:\n                    self.X = self.X.reshape(-1, len(self.domain.attributes))\n\n                self.Y = get_columns(row_indices, conversion.class_vars, n_rows,\n                                     is_sparse=conversion.sparse_Y)\n\n                dtype = np.float64\n                if any(isinstance(var, StringVariable) for var in domain.metas):\n                    dtype = np.object\n                self.metas = get_columns(row_indices, conversion.metas,\n                                         n_rows, dtype,\n                                         is_sparse=conversion.sparse_metas)\n                if self.metas.ndim == 1:\n                    self.metas = self.metas.reshape(-1, len(self.domain.metas))\n                if source.has_weights():\n                    self.W = source.W[row_indices]\n                else:\n                    self.W = np.empty((n_rows, 0))\n                self.name = getattr(source, 'name', '')\n                if hasattr(source, 'ids'):\n                    self.ids = source.ids[row_indices]\n                else:\n                    cls._init_ids(self)\n                self.attributes = getattr(source, 'attributes', {})\n                _conversion_cache[(id(domain), id(source))] = self\n                return self\n            finally:\n                if new_cache:\n                    _conversion_cache = None\n\n    def transform(self, domain):\n        \"\"\"\n        Construct a table with a different domain.\n\n        The new table keeps the row ids and other information. If the table\n        is a subclass of :obj:`Table`, the resulting table will be of the same\n        type.\n\n        In a typical scenario, an existing table is augmented with a new\n        column by ::\n\n            domain = Domain(old_domain.attributes + [new_attribute],\n                            old_domain.class_vars,\n                            old_domain.metas)\n            table = data.transform(domain)\n            table[:, new_attribute] = new_column\n\n        Args:\n            domain (Domain): new domain\n\n        Returns:\n            A new table\n        \"\"\"\n        return type(self).from_table(domain, self)\n\n    @classmethod\n    def from_table_rows(cls, source, row_indices):\n        \"\"\"\n        Construct a new table by selecting rows from the source table.\n\n        :param source: an existing table\n        :type source: Orange.data.Table\n        :param row_indices: indices of the rows to include\n        :type row_indices: a slice or a sequence\n        :return: a new table\n        :rtype: Orange.data.Table\n        \"\"\"\n        self = cls()\n        self.domain = source.domain\n        self.X = source.X[row_indices]\n        if self.X.ndim == 1:\n            self.X = self.X.reshape(-1, len(self.domain.attributes))\n        self.Y = source._Y[row_indices]\n        self.metas = source.metas[row_indices]\n        if self.metas.ndim == 1:\n            self.metas = self.metas.reshape(-1, len(self.domain.metas))\n        self.W = source.W[row_indices]\n        self.name = getattr(source, 'name', '')\n        self.ids = np.array(source.ids[row_indices])\n        self.attributes = getattr(source, 'attributes', {})\n        return self\n\n    @classmethod\n    def from_numpy(cls, domain, X, Y=None, metas=None, W=None):\n        \"\"\"\n        Construct a table from numpy arrays with the given domain. The number\n        of variables in the domain must match the number of columns in the\n        corresponding arrays. All arrays must have the same number of rows.\n        Arrays may be of different numpy types, and may be dense or sparse.\n\n        :param domain: the domain for the new table\n        :type domain: Orange.data.Domain\n        :param X: array with attribute values\n        :type X: np.array\n        :param Y: array with class values\n        :type Y: np.array\n        :param metas: array with meta attributes\n        :type metas: np.array\n        :param W: array with weights\n        :type W: np.array\n        :return:\n        \"\"\"\n        X, Y, W = _check_arrays(X, Y, W, dtype='float64')\n        metas, = _check_arrays(metas, dtype=object)\n\n        if Y is not None and Y.ndim == 1:\n            Y = Y.reshape(Y.shape[0], 1)\n        if domain is None:\n            domain = Domain.from_numpy(X, Y, metas)\n\n        if Y is None:\n            if sp.issparse(X):\n                Y = np.empty((X.shape[0], 0), dtype=np.float64)\n            else:\n                Y = X[:, len(domain.attributes):]\n                X = X[:, :len(domain.attributes)]\n        if metas is None:\n            metas = np.empty((X.shape[0], 0), object)\n        if W is None or W.size == 0:\n            W = np.empty((X.shape[0], 0))\n        else:\n            W = W.reshape(W.size)\n\n        if X.shape[1] != len(domain.attributes):\n            raise ValueError(\n                \"Invalid number of variable columns ({} != {})\".format(\n                    X.shape[1], len(domain.attributes))\n            )\n        if Y.shape[1] != len(domain.class_vars):\n            raise ValueError(\n                \"Invalid number of class columns ({} != {})\".format(\n                    Y.shape[1], len(domain.class_vars))\n            )\n        if metas.shape[1] != len(domain.metas):\n            raise ValueError(\n                \"Invalid number of meta attribute columns ({} != {})\".format(\n                    metas.shape[1], len(domain.metas))\n            )\n        if not X.shape[0] == Y.shape[0] == metas.shape[0] == W.shape[0]:\n            raise ValueError(\n                \"Parts of data contain different numbers of rows.\")\n\n        self = cls()\n        self.domain = domain\n        self.X = X\n        self.Y = Y\n        self.metas = metas\n        self.W = W\n        self.n_rows = self.X.shape[0]\n        cls._init_ids(self)\n        self.attributes = {}\n        return self\n\n    @classmethod\n    def from_list(cls, domain, rows, weights=None):\n        if weights is not None and len(rows) != len(weights):\n            raise ValueError(\"mismatching number of instances and weights\")\n        self = cls.from_domain(domain, len(rows), weights is not None)\n        attrs, classes = domain.attributes, domain.class_vars\n        metas = domain.metas\n        nattrs, ncls = len(domain.attributes), len(domain.class_vars)\n        for i, row in enumerate(rows):\n            if isinstance(row, Instance):\n                row = row.list\n            for j, (var, val) in enumerate(zip(attrs, row)):\n                self.X[i, j] = var.to_val(val)\n            for j, (var, val) in enumerate(zip(classes, row[nattrs:])):\n                self._Y[i, j] = var.to_val(val)\n            for j, (var, val) in enumerate(zip(metas, row[nattrs + ncls:])):\n                self.metas[i, j] = var.to_val(val)\n        if weights is not None:\n            self.W = np.array(weights)\n        self.attributes = {}\n        return self\n\n    @classmethod\n    def _init_ids(cls, obj):\n        with cls._next_instance_lock:\n            obj.ids = np.array(range(cls._next_instance_id, cls._next_instance_id + obj.X.shape[0]))\n            cls._next_instance_id += obj.X.shape[0]\n\n    @classmethod\n    def new_id(cls):\n        with cls._next_instance_lock:\n            id = cls._next_instance_id\n            cls._next_instance_id += 1\n            return id\n\n    def save(self, filename):\n        \"\"\"\n        Save a data table to a file. The path can be absolute or relative.\n\n        :param filename: File name\n        :type filename: str\n        \"\"\"\n        ext = os.path.splitext(filename)[1]\n        from Orange.data.io import FileFormat\n        writer = FileFormat.writers.get(ext)\n        if not writer:\n            desc = FileFormat.names.get(ext)\n            if desc:\n                raise IOError(\n                    \"Writing of {}s is not supported\".format(desc.lower()))\n            else:\n                raise IOError(\"Unknown file name extension.\")\n        writer.write_file(filename, self)\n\n    @classmethod\n    def from_file(cls, filename, sheet=None):\n        \"\"\"\n        Read a data table from a file. The path can be absolute or relative.\n\n        :param filename: File name\n        :type filename: str\n        :param sheet: Sheet in a file (optional)\n        :type sheet: str\n        :return: a new data table\n        :rtype: Orange.data.Table\n        \"\"\"\n        from Orange.data.io import FileFormat\n\n        absolute_filename = FileFormat.locate(filename, dataset_dirs)\n        reader = FileFormat.get_reader(absolute_filename)\n        reader.select_sheet(sheet)\n        data = reader.read()\n\n        # Readers return plain table. Make sure to cast it to appropriate\n        # (subclass) type\n        if cls != data.__class__:\n            data = cls(data)\n\n        # no need to call _init_ids as fuctions from .io already\n        # construct a table with .ids\n\n        data.__file__ = absolute_filename\n        return data\n\n    @classmethod\n    def from_url(cls, url):\n        from Orange.data.io import UrlReader\n        reader = UrlReader(url)\n        data = reader.read()\n        if cls != data.__class__:\n            data = cls(data)\n        return data\n\n    # Helper function for __setitem__ and insert:\n    # Set the row of table data matrices\n    # noinspection PyProtectedMember\n    def _set_row(self, example, row):\n        domain = self.domain\n        if isinstance(example, Instance):\n            if example.domain == domain:\n                if isinstance(example, RowInstance):\n                    self.X[row] = example._x\n                    self._Y[row] = example._y\n                else:\n                    self.X[row] = example._x\n                    self._Y[row] = example._y\n                self.metas[row] = example._metas\n                return\n\n            self.X[row], self._Y[row], self.metas[row] = \\\n                self.domain.convert(example)\n            try:\n                self.ids[row] = example.id\n            except:\n                with type(self)._next_instance_lock:\n                    self.ids[row] = type(self)._next_instance_id\n                    type(self)._next_instance_id += 1\n\n        else:\n            self.X[row] = [var.to_val(val)\n                           for var, val in zip(domain.attributes, example)]\n            self._Y[row] = [var.to_val(val)\n                            for var, val in\n                            zip(domain.class_vars,\n                                example[len(domain.attributes):])]\n            self.metas[row] = np.array([var.Unknown for var in domain.metas],\n                                       dtype=object)\n\n    def _check_all_dense(self):\n        return all(x in (Storage.DENSE, Storage.MISSING)\n                   for x in (self.X_density(), self.Y_density(),\n                             self.metas_density()))\n\n    # A helper function for extend and insert\n    # Resize X, Y, metas and W.\n    def _resize_all(self, new_length):\n        old_length = self.X.shape[0]\n        if old_length == new_length:\n            return\n        if not self._check_all_dense():\n            raise ValueError(\"Tables with sparse data cannot be resized\")\n        try:\n            self.X.resize(new_length, self.X.shape[1])\n            self._Y.resize(new_length, self._Y.shape[1])\n            self.metas.resize(new_length, self.metas.shape[1])\n            if self.W.ndim == 2:\n                self.W.resize((new_length, 0))\n            else:\n                self.W.resize(new_length)\n            self.ids.resize(new_length)\n        except Exception:\n            if self.X.shape[0] == new_length:\n                self.X.resize(old_length, self.X.shape[1])\n            if self._Y.shape[0] == new_length:\n                self._Y.resize(old_length, self._Y.shape[1])\n            if self.metas.shape[0] == new_length:\n                self.metas.resize(old_length, self.metas.shape[1])\n            if self.W.shape[0] == new_length:\n                if self.W.ndim == 2:\n                    self.W.resize((old_length, 0))\n                else:\n                    self.W.resize(old_length)\n            if self.ids.shape[0] == new_length:\n                self.ids.resize(old_length)\n            raise\n\n    def __getitem__(self, key):\n        if isinstance(key, Integral):\n            return RowInstance(self, key)\n        if not isinstance(key, tuple):\n            return self.from_table_rows(self, key)\n\n        if len(key) != 2:\n            raise IndexError(\"Table indices must be one- or two-dimensional\")\n\n        row_idx, col_idx = key\n        if isinstance(row_idx, Integral):\n            if isinstance(col_idx, (str, Integral, Variable)):\n                col_idx = self.domain.index(col_idx)\n                var = self.domain[col_idx]\n                if 0 <= col_idx < len(self.domain.attributes):\n                    return Value(var, self.X[row_idx, col_idx])\n                elif col_idx >= len(self.domain.attributes):\n                    return Value(\n                        var,\n                        self._Y[row_idx,\n                                col_idx - len(self.domain.attributes)])\n                elif col_idx < 0:\n                    return Value(var, self.metas[row_idx, -1 - col_idx])\n            else:\n                row_idx = [row_idx]\n\n        # multiple rows OR single row but multiple columns:\n        # construct a new table\n        attributes, col_indices = self.domain._compute_col_indices(col_idx)\n        if attributes is not None:\n            n_attrs = len(self.domain.attributes)\n            r_attrs = [attributes[i]\n                       for i, col in enumerate(col_indices)\n                       if 0 <= col < n_attrs]\n            r_classes = [attributes[i]\n                         for i, col in enumerate(col_indices)\n                         if col >= n_attrs]\n            r_metas = [attributes[i]\n                       for i, col in enumerate(col_indices) if col < 0]\n            domain = Domain(r_attrs, r_classes, r_metas)\n        else:\n            domain = self.domain\n        return self.from_table(domain, self, row_idx)\n\n    def __setitem__(self, key, value):\n        if not isinstance(key, tuple):\n            if isinstance(value, Real):\n                self.X[key, :] = value\n                return\n            self._set_row(value, key)\n            return\n\n        if len(key) != 2:\n            raise IndexError(\"Table indices must be one- or two-dimensional\")\n        row_idx, col_idx = key\n\n        # single row\n        if isinstance(row_idx, Integral):\n            if isinstance(col_idx, slice):\n                col_idx = range(*slice.indices(col_idx, self.X.shape[1]))\n            if not isinstance(col_idx, str) and isinstance(col_idx, Iterable):\n                col_idx = list(col_idx)\n            if not isinstance(col_idx, str) and isinstance(col_idx, Sized):\n                if isinstance(value, (Sequence, np.ndarray)):\n                    values = value\n                elif isinstance(value, Iterable):\n                    values = list(value)\n                else:\n                    raise TypeError(\"Setting multiple values requires a \"\n                                    \"sequence or numpy array\")\n                if len(values) != len(col_idx):\n                    raise ValueError(\"Invalid number of values\")\n            else:\n                col_idx, values = [col_idx], [value]\n            for value, col_idx in zip(values, col_idx):\n                if not isinstance(value, Integral):\n                    value = self.domain[col_idx].to_val(value)\n                if not isinstance(col_idx, Integral):\n                    col_idx = self.domain.index(col_idx)\n                if col_idx >= 0:\n                    if col_idx < self.X.shape[1]:\n                        self.X[row_idx, col_idx] = value\n                    else:\n                        self._Y[row_idx, col_idx - self.X.shape[1]] = value\n                else:\n                    self.metas[row_idx, -1 - col_idx] = value\n\n        # multiple rows, multiple columns\n        attributes, col_indices = self.domain._compute_col_indices(col_idx)\n        if col_indices is ...:\n            col_indices = range(len(self.domain))\n        n_attrs = self.X.shape[1]\n        if isinstance(value, str):\n            if not attributes:\n                attributes = self.domain.attributes\n            for var, col in zip(attributes, col_indices):\n                if 0 <= col < n_attrs:\n                    self.X[row_idx, col] = var.to_val(value)\n                elif col >= n_attrs:\n                    self._Y[row_idx, col - n_attrs] = var.to_val(value)\n                else:\n                    self.metas[row_idx, -1 - col] = var.to_val(value)\n        else:\n            attr_cols = np.fromiter(\n                (col for col in col_indices if 0 <= col < n_attrs), int)\n            class_cols = np.fromiter(\n                (col - n_attrs for col in col_indices if col >= n_attrs), int)\n            meta_cols = np.fromiter(\n                (-1 - col for col in col_indices if col < 0), int)\n            if value is None:\n                value = Unknown\n\n            if not isinstance(value, (Real, np.ndarray)) and \\\n                    (len(attr_cols) or len(class_cols)):\n                raise TypeError(\n                    \"Ordinary attributes can only have primitive values\")\n            if len(attr_cols):\n                self.X[row_idx, attr_cols] = value\n            if len(class_cols):\n                self._Y[row_idx, class_cols] = value\n            if len(meta_cols):\n                self.metas[row_idx, meta_cols] = value\n\n    def __delitem__(self, key):\n        pending_deprecation_resize(\"__delitem__(key)\")\n        if not self._check_all_dense():\n            raise ValueError(\"Rows of sparse data cannot be deleted\")\n        if key is ...:\n            key = range(len(self))\n        self.X = np.delete(self.X, key, axis=0)\n        self.Y = np.delete(self._Y, key, axis=0)\n        self.metas = np.delete(self.metas, key, axis=0)\n        self.W = np.delete(self.W, key, axis=0)\n        self.ids = np.delete(self.ids, key, axis=0)\n\n    def __len__(self):\n        return self.X.shape[0]\n\n    def __str__(self):\n        return \"[\" + \",\\n \".join(str(ex) for ex in self) + \"]\"\n\n    def __repr__(self):\n        head = 5\n        if self.is_sparse():\n            head = min(self.X.shape[0], head)\n        s = \"[\" + \",\\n \".join(repr(ex) for ex in self[:head])\n        if len(self) > head:\n            s += \",\\n ...\"\n        s += \"\\n]\"\n        return s\n\n    def clear(self):\n        \"\"\"Remove all rows from the table.\"\"\"\n        pending_deprecation_resize(\"clear()\")\n        if not self._check_all_dense():\n            raise ValueError(\"Tables with sparse data cannot be cleared\")\n        del self[...]\n\n    def append(self, instance):\n        \"\"\"\n        Append a data instance to the table.\n\n        :param instance: a data instance\n        :type instance: Orange.data.Instance or a sequence of values\n        \"\"\"\n        pending_deprecation_resize(\"append(inst)\")\n        self.insert(len(self), instance)\n\n    def insert(self, row, instance):\n        \"\"\"\n        Insert a data instance into the table.\n\n        :param row: row index\n        :type row: int\n        :param instance: a data instance\n        :type instance: Orange.data.Instance or a sequence of values\n        \"\"\"\n        pending_deprecation_resize(\"insert(i, inst)\")\n        if row < 0:\n            row += len(self)\n        if row < 0 or row > len(self):\n            raise IndexError(\"Index out of range\")\n        self.ensure_copy()  # ensure that numpy arrays are single-segment for resize\n        self._resize_all(len(self) + 1)\n        if row < len(self):\n            self.X[row + 1:] = self.X[row:-1]\n            self._Y[row + 1:] = self._Y[row:-1]\n            self.metas[row + 1:] = self.metas[row:-1]\n            self.W[row + 1:] = self.W[row:-1]\n            self.ids[row + 1:] = self.ids[row:-1]\n        try:\n            self._set_row(instance, row)\n            if self.W.shape[-1]:\n                self.W[row] = 1\n        except Exception:\n            self.X[row:-1] = self.X[row + 1:]\n            self._Y[row:-1] = self._Y[row + 1:]\n            self.metas[row:-1] = self.metas[row + 1:]\n            self.W[row:-1] = self.W[row + 1:]\n            self.ids[row:-1] = self.ids[row + 1:]\n            self._resize_all(len(self) - 1)\n            raise\n\n    def extend(self, instances):\n        \"\"\"\n        Extend the table with the given instances. The instances can be given\n        as a table of the same or a different domain, or a sequence. In the\n        latter case, each instances can be given as\n        :obj:`~Orange.data.Instance` or a sequence of values (e.g. list,\n        tuple, numpy.array).\n\n        :param instances: additional instances\n        :type instances: Orange.data.Table or a sequence of instances\n        \"\"\"\n        pending_deprecation_resize(\"extend(insts)\")\n        if isinstance(instances, Table) and instances.domain == self.domain:\n            self.X = vstack((self.X, instances.X))\n            self._Y = vstack((self._Y, instances._Y))\n            self.metas = vstack((self.metas, instances.metas))\n            self.W = vstack((self.W, instances.W))\n            self.ids = hstack((self.ids, instances.ids))\n        else:\n            try:\n                old_length = len(self)\n                self._resize_all(old_length + len(instances))\n                for i, example in enumerate(instances):\n                    self[old_length + i] = example\n                    try:\n                        self.ids[old_length + i] = example.id\n                    except AttributeError:\n                        self.ids[old_length + i] = self.new_id()\n            except Exception:\n                self._resize_all(old_length)\n                raise\n\n    @classmethod\n    def concatenate(cls, tables, axis=1):\n        \"\"\"Return concatenation of `tables` by `axis`.\"\"\"\n        def vstack(arrs):\n            return [np, sp][any(sp.issparse(arr) for arr in arrs)].vstack(arrs)\n\n        def merge1d(arrs):\n            arrs = list(arrs)\n            ydims = {arr.ndim for arr in arrs}\n            if ydims == {1}:\n                return np.hstack(arrs)\n            else:\n                return vstack([\n                    arr if arr.ndim == 2 else np.atleast_2d(arr).T\n                    for arr in arrs\n                ])\n\n        def collect(attr):\n            return [getattr(arr, attr) for arr in tables]\n\n        if not tables:\n            raise ValueError('need at least one table to concatenate')\n        if len(tables) == 1:\n            return tables[0].copy()\n        CONCAT_ROWS, CONCAT_COLS = 0, 1\n        if axis == CONCAT_ROWS:\n            domain = tables[0].domain\n            if any(table.domain != domain for table in tables):\n                raise ValueError('concatenated tables must have the same domain')\n\n            conc = cls.from_numpy(\n                domain,\n                vstack(collect(\"X\")),\n                merge1d(collect(\"Y\")),\n                vstack(collect(\"metas\")),\n                merge1d(collect(\"W\"))\n            )\n            conc.ids = np.hstack([table.ids for table in tables])\n            names = [table.name for table in tables if table.name != \"untitled\"]\n            if names:\n                conc.name = names[0]\n            # TODO: Add attributes = {} to __init__\n            conc.attributes = getattr(conc, \"attributes\", {})\n            for table in reversed(tables):\n                conc.attributes.update(table.attributes)\n            return conc\n        elif axis == CONCAT_COLS:\n            pending_deprecation_resize(\"concatenate with axis=1\")\n            if reduce(operator.iand,\n                      (set(map(operator.attrgetter('name'),\n                               chain(t.domain.variables, t.domain.metas)))\n                       for t in tables)):\n                raise ValueError('Concatenating two domains with variables '\n                                 'with same name is undefined')\n            domain = Domain(flatten(t.domain.attributes for t in tables),\n                            flatten(t.domain.class_vars for t in tables),\n                            flatten(t.domain.metas for t in tables))\n\n            def ndmin(A):\n                return A if A.ndim > 1 else A.reshape(A.shape[0], 1)\n\n            table = Table.from_numpy(domain,\n                                     np.hstack(tuple(ndmin(t.X) for t in tables)),\n                                     np.hstack(tuple(ndmin(t.Y) for t in tables)),\n                                     np.hstack(tuple(ndmin(t.metas) for t in tables)),\n                                     np.hstack(tuple(ndmin(t.W) for t in tables)))\n            return table\n        raise ValueError('axis {} out of bounds [0, 2)'.format(axis))\n\n    def is_view(self):\n        \"\"\"\n        Return `True` if all arrays represent a view referring to another table\n        \"\"\"\n        return ((not self.X.shape[-1] or self.X.base is not None) and\n                (not self._Y.shape[-1] or self._Y.base is not None) and\n                (not self.metas.shape[-1] or self.metas.base is not None) and\n                (not self._weights.shape[-1] or self.W.base is not None))\n\n    def is_copy(self):\n        \"\"\"\n        Return `True` if the table owns its data\n        \"\"\"\n        return ((not self.X.shape[-1] or self.X.base is None) and\n                (self._Y.base is None) and\n                (self.metas.base is None) and\n                (self.W.base is None))\n\n    def is_sparse(self):\n        \"\"\"\n        Return `True` if the table stores data in sparse format\n        \"\"\"\n        return any(sp.issparse(i) for i in [self.X, self.Y, self.metas])\n\n    def ensure_copy(self):\n        \"\"\"\n        Ensure that the table owns its data; copy arrays when necessary.\n        \"\"\"\n        def is_view(x):\n            # Sparse matrices don't have views like numpy arrays. Since indexing on\n            # them creates copies in constructor we can skip this check here.\n            return not sp.issparse(x) and x.base is not None\n\n        if is_view(self.X):\n            self.X = self.X.copy()\n        if is_view(self._Y):\n            self._Y = self._Y.copy()\n        if is_view(self.metas):\n            self.metas = self.metas.copy()\n        if is_view(self.W):\n            self.W = self.W.copy()\n\n    def copy(self):\n        \"\"\"\n        Return a copy of the table\n        \"\"\"\n        t = self.__class__(self)\n        t.ensure_copy()\n        return t\n\n    @staticmethod\n    def __determine_density(data):\n        if data is None:\n            return Storage.Missing\n        if data is not None and sp.issparse(data):\n            return Storage.SPARSE_BOOL if (data.data == 1).all() else Storage.SPARSE\n        else:\n            return Storage.DENSE\n\n    def X_density(self):\n        if not hasattr(self, \"_X_density\"):\n            self._X_density = self.__determine_density(self.X)\n        return self._X_density\n\n    def Y_density(self):\n        if not hasattr(self, \"_Y_density\"):\n            self._Y_density = self.__determine_density(self._Y)\n        return self._Y_density\n\n    def metas_density(self):\n        if not hasattr(self, \"_metas_density\"):\n            self._metas_density = self.__determine_density(self.metas)\n        return self._metas_density\n\n    def set_weights(self, weight=1):\n        \"\"\"\n        Set weights of data instances; create a vector of weights if necessary.\n        \"\"\"\n        if not self.W.shape[-1]:\n            self.W = np.empty(len(self))\n        self.W[:] = weight\n\n    def has_weights(self):\n        \"\"\"Return `True` if the data instances are weighed. \"\"\"\n        return self.W.shape[-1] != 0\n\n    def total_weight(self):\n        \"\"\"\n        Return the total weight of instances in the table, or their number if\n        they are unweighted.\n        \"\"\"\n        if self.W.shape[-1]:\n            return sum(self.W)\n        return len(self)\n\n    def has_missing(self):\n        \"\"\"Return `True` if there are any missing attribute or class values.\"\"\"\n        missing_x = not sp.issparse(self.X) and bn.anynan(self.X)   # do not check for sparse X\n        return missing_x or bn.anynan(self._Y)\n\n    def has_missing_attribute(self):\n        \"\"\"Return `True` if there are any missing attribute values.\"\"\"\n        return not sp.issparse(self.X) and bn.anynan(self.X)    # do not check for sparse X\n\n    def has_missing_class(self):\n        \"\"\"Return `True` if there are any missing class values.\"\"\"\n        return bn.anynan(self._Y)\n\n    def get_nan_frequency_attribute(self):\n        if self.X.size == 0:\n            return 0\n        return np.isnan(self.X).sum() / self.X.size\n\n    def get_nan_frequency_class(self):\n        if self.Y.size == 0:\n            return 0\n        return np.isnan(self._Y).sum() / self._Y.size\n\n    def checksum(self, include_metas=True):\n        # TODO: zlib.adler32 does not work for numpy arrays with dtype object\n        # (after pickling and unpickling such arrays, checksum changes)\n        # Why, and should we fix it or remove it?\n        \"\"\"Return a checksum over X, Y, metas and W.\"\"\"\n        cs = zlib.adler32(np.ascontiguousarray(self.X))\n        cs = zlib.adler32(np.ascontiguousarray(self._Y), cs)\n        if include_metas:\n            cs = zlib.adler32(np.ascontiguousarray(self.metas), cs)\n        cs = zlib.adler32(np.ascontiguousarray(self.W), cs)\n        return cs\n\n    def shuffle(self):\n        \"\"\"Randomly shuffle the rows of the table.\"\"\"\n        if not self._check_all_dense():\n            raise ValueError(\"Rows of sparse data cannot be shuffled\")\n        ind = np.arange(self.X.shape[0])\n        np.random.shuffle(ind)\n        self.X = self.X[ind]\n        self._Y = self._Y[ind]\n        self.metas = self.metas[ind]\n        self.W = self.W[ind]\n\n    def get_column_view(self, index):\n        \"\"\"\n        Return a vector - as a view, not a copy - with a column of the table,\n        and a bool flag telling whether this column is sparse. Note that\n        vertical slicing of sparse matrices is inefficient.\n\n        :param index: the index of the column\n        :type index: int, str or Orange.data.Variable\n        :return: (one-dimensional numpy array, sparse)\n        \"\"\"\n\n        def rx(M):\n            if sp.issparse(M):\n                return np.asarray(M.todense())[:, 0], True\n            else:\n                return M, False\n\n        if not isinstance(index, Integral):\n            index = self.domain.index(index)\n        if index >= 0:\n            if index < self.X.shape[1]:\n                return rx(self.X[:, index])\n            else:\n                return rx(self._Y[:, index - self.X.shape[1]])\n        else:\n            return rx(self.metas[:, -1 - index])\n\n    def _filter_is_defined(self, columns=None, negate=False):\n        if columns is None:\n            if sp.issparse(self.X):\n                remove = (self.X.indptr[1:] !=\n                          self.X.indptr[-1:] + self.X.shape[1])\n            else:\n                remove = bn.anynan(self.X, axis=1)\n            if sp.issparse(self._Y):\n                remove = np.logical_or(remove, self._Y.indptr[1:] !=\n                                       self._Y.indptr[-1:] + self._Y.shape[1])\n            else:\n                remove = np.logical_or(remove, bn.anynan(self._Y, axis=1))\n        else:\n            remove = np.zeros(len(self), dtype=bool)\n            for column in columns:\n                col, sparse = self.get_column_view(column)\n                if sparse:\n                    remove = np.logical_or(remove, col == 0)\n                else:\n                    remove = np.logical_or(remove, bn.anynan([col], axis=0))\n        retain = remove if negate else np.logical_not(remove)\n        return self.from_table_rows(self, retain)\n\n    def _filter_has_class(self, negate=False):\n        if sp.issparse(self._Y):\n            if negate:\n                retain = (self._Y.indptr[1:] !=\n                          self._Y.indptr[-1:] + self._Y.shape[1])\n            else:\n                retain = (self._Y.indptr[1:] ==\n                          self._Y.indptr[-1:] + self._Y.shape[1])\n        else:\n            retain = bn.anynan(self._Y, axis=1)\n            if not negate:\n                retain = np.logical_not(retain)\n        return self.from_table_rows(self, retain)\n\n    def _filter_same_value(self, column, value, negate=False):\n        if not isinstance(value, Real):\n            value = self.domain[column].to_val(value)\n        sel = self.get_column_view(column)[0] == value\n        if negate:\n            sel = np.logical_not(sel)\n        return self.from_table_rows(self, sel)\n\n    def _filter_values(self, filter):\n        selection = self._values_filter_to_indicator(filter)\n        return self.from_table(self.domain, self, selection)\n\n    def _values_filter_to_indicator(self, filter):\n        \"\"\"Return selection of rows matching the filter conditions\n\n        Handles conjunction/disjunction and negate modifiers\n\n        Parameters\n        ----------\n        filter: Values object containing the conditions\n\n        Returns\n        -------\n        A 1d bool array. len(result) == len(self)\n        \"\"\"\n        from Orange.data.filter import Values\n\n        if isinstance(filter, Values):\n            conditions = filter.conditions\n            conjunction = filter.conjunction\n        else:\n            conditions = [filter]\n            conjunction = True\n        if conjunction:\n            sel = np.ones(len(self), dtype=bool)\n        else:\n            sel = np.zeros(len(self), dtype=bool)\n\n        for f in conditions:\n            selection = self._filter_to_indicator(f)\n\n            if conjunction:\n                sel *= selection\n            else:\n                sel += selection\n\n        if filter.negate:\n            sel = ~sel\n        return sel\n\n    def _filter_to_indicator(self, filter):\n        \"\"\"Return selection of rows that match the condition.\n\n        Parameters\n        ----------\n        filter: ValueFilter describing the condition\n\n        Returns\n        -------\n        A 1d bool array. len(result) == len(self)\n        \"\"\"\n        from Orange.data.filter import (\n            FilterContinuous, FilterDiscrete, FilterRegex, FilterString,\n            FilterStringList, Values\n        )\n        if isinstance(filter, Values):\n            return self._values_filter_to_indicator(filter)\n\n        col = self.get_column_view(filter.column)[0]\n\n        if isinstance(filter, FilterDiscrete):\n            return self._discrete_filter_to_indicator(filter, col)\n\n        if isinstance(filter, FilterContinuous):\n            return self._continuous_filter_to_indicator(filter, col)\n\n        if isinstance(filter, FilterString):\n            return self._string_filter_to_indicator(filter, col)\n\n        if isinstance(filter, FilterStringList):\n            if not filter.case_sensitive:\n                col = np.char.lower(np.array(col, dtype=str))\n                vals = [val.lower() for val in filter.values]\n            else:\n                vals = filter.values\n            return reduce(operator.add, (col == val for val in vals))\n\n        if isinstance(filter, FilterRegex):\n            return np.vectorize(filter)(col)\n\n        raise TypeError(\"Invalid filter\")\n\n    def _discrete_filter_to_indicator(self, filter, col):\n        \"\"\"Return selection of rows matched by the given discrete filter.\n\n        Parameters\n        ----------\n        filter: FilterDiscrete\n        col: np.ndarray\n\n        Returns\n        -------\n        A 1d bool array. len(result) == len(self)\n        \"\"\"\n        if filter.values is None:  # <- is defined filter\n            col = col.astype(float)\n            return ~np.isnan(col)\n\n        sel = np.zeros(len(self), dtype=bool)\n        for val in filter.values:\n            if not isinstance(val, Real):\n                val = self.domain[filter.column].to_val(val)\n            sel += (col == val)\n        return sel\n\n    def _continuous_filter_to_indicator(self, filter, col):\n        \"\"\"Return selection of rows matched by the given continuous filter.\n\n        Parameters\n        ----------\n        filter: FilterContinuous\n        col: np.ndarray\n\n        Returns\n        -------\n        A 1d bool array. len(result) == len(self)\n        \"\"\"\n        if filter.oper == filter.IsDefined:\n            col = col.astype(float)\n            return ~np.isnan(col)\n\n        return self._range_filter_to_indicator(filter, col, filter.min, filter.max)\n\n    def _string_filter_to_indicator(self, filter, col):\n        \"\"\"Return selection of rows matched by the given string filter.\n\n        Parameters\n        ----------\n        filter: FilterString\n        col: np.ndarray\n\n        Returns\n        -------\n        A 1d bool array. len(result) == len(self)\n        \"\"\"\n        if filter.oper == filter.IsDefined:\n            return col.astype(bool)\n\n        col = col.astype(str)\n        fmin = filter.min or \"\"\n        fmax = filter.max or \"\"\n\n        if not filter.case_sensitive:\n            # convert all to lower case\n            col = np.char.lower(col)\n            fmin = fmin.lower()\n            fmax = fmax.lower()\n\n        if filter.oper == filter.Contains:\n            return np.fromiter((fmin in e for e in col),\n                               dtype=bool)\n        if filter.oper == filter.StartsWith:\n            return np.fromiter((e.startswith(fmin) for e in col),\n                               dtype=bool)\n        if filter.oper == filter.EndsWith:\n            return np.fromiter((e.endswith(fmin) for e in col),\n                               dtype=bool)\n\n        return self._range_filter_to_indicator(filter, col, fmin, fmax)\n\n    @staticmethod\n    def _range_filter_to_indicator(filter, col, fmin, fmax):\n        if filter.oper == filter.Equal:\n            return col == fmin\n        if filter.oper == filter.NotEqual:\n            return col != fmin\n        if filter.oper == filter.Less:\n            return col < fmin\n        if filter.oper == filter.LessEqual:\n            return col <= fmin\n        if filter.oper == filter.Greater:\n            return col > fmin\n        if filter.oper == filter.GreaterEqual:\n            return col >= fmin\n        if filter.oper == filter.Between:\n            return (col >= fmin) * (col <= fmax)\n        if filter.oper == filter.Outside:\n            return (col < fmin) + (col > fmax)\n\n        raise TypeError(\"Invalid operator\")\n\n    def _compute_basic_stats(self, columns=None,\n                             include_metas=False, compute_variance=False):\n        if compute_variance:\n            raise NotImplementedError(\"computation of variance is \"\n                                      \"not implemented yet\")\n        W = self.W if self.has_weights() else None\n        rr = []\n        stats = []\n        if not columns:\n            if self.domain.attributes:\n                rr.append(fast_stats(self.X, W))\n            if self.domain.class_vars:\n                rr.append(fast_stats(self._Y, W))\n            if include_metas and self.domain.metas:\n                rr.append(fast_stats(self.metas, W))\n            if len(rr):\n                stats = np.vstack(tuple(rr))\n        else:\n            nattrs = len(self.domain.attributes)\n            for column in columns:\n                c = self.domain.index(column)\n                if 0 <= c < nattrs:\n                    S = fast_stats(self.X[:, [c]], W and W[:, [c]])\n                elif c >= nattrs:\n                    S = fast_stats(self._Y[:, [c-nattrs]], W and W[:, [c-nattrs]])\n                else:\n                    S = fast_stats(self.metas[:, [-1-c]], W and W[:, [-1-c]])\n                stats.append(S[0])\n        return stats\n\n    def _compute_distributions(self, columns=None):\n        if columns is None:\n            columns = range(len(self.domain.variables))\n        else:\n            columns = [self.domain.index(var) for var in columns]\n\n        distributions = []\n        if sp.issparse(self.X):\n            self.X = self.X.tocsc()\n\n        W = self.W.ravel() if self.has_weights() else None\n\n        for col in columns:\n            variable = self.domain[col]\n\n            # Select the correct data column from X, Y or metas\n            if 0 <= col < self.X.shape[1]:\n                x = self.X[:, col]\n            elif col < 0:\n                x = self.metas[:, col * (-1) - 1]\n                if np.issubdtype(x.dtype, np.dtype(object)):\n                    x = x.astype(float)\n            else:\n                x = self._Y[:, col - self.X.shape[1]]\n\n            if variable.is_discrete:\n                dist, unknowns = bincount(x, weights=W, max_val=len(variable.values) - 1)\n            elif not x.shape[0]:\n                dist, unknowns = np.zeros((2, 0)), 0\n            else:\n                if W is not None:\n                    if sp.issparse(x):\n                        arg_sort = np.argsort(x.data)\n                        ranks = x.indices[arg_sort]\n                        vals = np.vstack((x.data[arg_sort], W[ranks]))\n                    else:\n                        ranks = np.argsort(x)\n                        vals = np.vstack((x[ranks], W[ranks]))\n                else:\n                    x_values = x.data if sp.issparse(x) else x\n                    vals = np.ones((2, x_values.shape[0]))\n                    vals[0, :] = x_values\n                    vals[0, :].sort()\n\n                dist = np.array(_valuecount.valuecount(vals))\n                # If sparse, then 0s will not be counted with `valuecount`, so\n                # we have to add them to the result manually.\n                if sp.issparse(x) and sparse_has_implicit_zeros(x):\n                    if W is not None:\n                        zero_weights = sparse_implicit_zero_weights(x, W).sum()\n                    else:\n                        zero_weights = sparse_count_implicit_zeros(x)\n                    zero_vec = [0, zero_weights]\n                    dist = np.insert(dist, np.searchsorted(dist[0], 0), zero_vec, axis=1)\n                # Since `countnans` assumes vector shape to be (1, n) and `x`\n                # shape is (n, 1), we pass the transpose\n                unknowns = countnans(x.T, W)\n            distributions.append((dist, unknowns))\n\n        return distributions\n\n    def _compute_contingency(self, col_vars=None, row_var=None):\n        n_atts = self.X.shape[1]\n\n        if col_vars is None:\n            col_vars = range(len(self.domain.variables))\n        else:\n            col_vars = [self.domain.index(var) for var in col_vars]\n        if row_var is None:\n            row_var = self.domain.class_var\n            if row_var is None:\n                raise ValueError(\"No row variable\")\n\n        row_desc = self.domain[row_var]\n        if not row_desc.is_discrete:\n            raise TypeError(\"Row variable must be discrete\")\n        row_indi = self.domain.index(row_var)\n        n_rows = len(row_desc.values)\n        if 0 <= row_indi < n_atts:\n            row_data = self.X[:, row_indi]\n        elif row_indi < 0:\n            row_data = self.metas[:, -1 - row_indi]\n        else:\n            row_data = self._Y[:, row_indi - n_atts]\n\n        W = self.W if self.has_weights() else None\n        nan_inds = None\n\n        col_desc = [self.domain[var] for var in col_vars]\n        col_indi = [self.domain.index(var) for var in col_vars]\n\n        if any(not (var.is_discrete or var.is_continuous)\n               for var in col_desc):\n            raise ValueError(\"contingency can be computed only for discrete \"\n                             \"and continuous values\")\n\n        if row_data.dtype.kind != \"f\": #meta attributes can be stored as type object\n            row_data = row_data.astype(float)\n\n        unknown_rows = countnans(row_data)\n        if unknown_rows:\n            nan_inds = np.isnan(row_data)\n            row_data = row_data[~nan_inds]\n            if W:\n                W = W[~nan_inds]\n                unknown_rows = np.sum(W[nan_inds])\n\n        contingencies = [None] * len(col_desc)\n        for arr, f_cond, f_ind in (\n                (self.X, lambda i: 0 <= i < n_atts, lambda i: i),\n                (self._Y, lambda i: i >= n_atts, lambda i: i - n_atts),\n                (self.metas, lambda i: i < 0, lambda i: -1 - i)):\n\n            if nan_inds is not None:\n                arr = arr[~nan_inds]\n\n            arr_indi = [e for e, ind in enumerate(col_indi) if f_cond(ind)]\n\n            vars = [(e, f_ind(col_indi[e]), col_desc[e]) for e in arr_indi]\n            disc_vars = [v for v in vars if v[2].is_discrete]\n            if disc_vars:\n                if sp.issparse(arr):\n                    max_vals = max(len(v[2].values) for v in disc_vars)\n                    disc_indi = {i for _, i, _ in disc_vars}\n                    mask = [i in disc_indi for i in range(arr.shape[1])]\n                    conts, nans = contingency(arr, row_data, max_vals - 1,\n                                              n_rows - 1, W, mask)\n                    for col_i, arr_i, var in disc_vars:\n                        n_vals = len(var.values)\n                        contingencies[col_i] = (conts[arr_i][:, :n_vals],\n                                                nans[arr_i])\n                else:\n                    for col_i, arr_i, var in disc_vars:\n                        contingencies[col_i] = contingency(\n                            arr[:, arr_i].astype(float),\n                            row_data, len(var.values) - 1, n_rows - 1, W)\n\n            cont_vars = [v for v in vars if v[2].is_continuous]\n            if cont_vars:\n\n                classes = row_data.astype(dtype=np.intp)\n                if W is not None:\n                    W = W.astype(dtype=np.float64)\n                if sp.issparse(arr):\n                    arr = sp.csc_matrix(arr)\n\n                for col_i, arr_i, _ in cont_vars:\n                    if sp.issparse(arr):\n                        col_data = arr.data[arr.indptr[arr_i]:arr.indptr[arr_i + 1]]\n                        rows = arr.indices[arr.indptr[arr_i]:arr.indptr[arr_i + 1]]\n                        W_ = None if W is None else W[rows]\n                        classes_ = classes[rows]\n                    else:\n                        col_data, W_, classes_ = arr[:, arr_i], W, classes\n\n                    col_data = col_data.astype(dtype=np.float64)\n                    U, C, unknown = _contingency.contingency_floatarray(\n                        col_data, classes_, n_rows, W_)\n                    contingencies[col_i] = ([U, C], unknown)\n\n        return contingencies, unknown_rows\n\n    @classmethod\n    def transpose(cls, table, feature_names_column=\"\", meta_attr_name=\"Feature name\",\n                  feature_name=\"Feature\"):\n        \"\"\"\n        Transpose the table.\n\n        :param table: Table - table to transpose\n        :param feature_names_column: str - name of (String) meta attribute to\n            use for feature names\n        :param meta_attr_name: str - name of new meta attribute into which\n            feature names are mapped\n        :return: Table - transposed table\n        \"\"\"\n\n        self = cls()\n        n_cols, self.n_rows = table.X.shape\n        old_domain = table.attributes.get(\"old_domain\")\n\n        # attributes\n        # - classes and metas to attributes of attributes\n        # - arbitrary meta column to feature names\n        self.X = table.X.T\n        attributes = [ContinuousVariable(str(row[feature_names_column]))\n                      for row in table] if feature_names_column else \\\n            [ContinuousVariable(feature_name + \" \" + str(i + 1).zfill(\n                int(np.ceil(np.log10(n_cols))))) for i in range(n_cols)]\n        if old_domain is not None and feature_names_column:\n            for i, _ in enumerate(attributes):\n                if attributes[i].name in old_domain:\n                    var = old_domain[attributes[i].name]\n                    attr = ContinuousVariable(var.name) if var.is_continuous \\\n                        else DiscreteVariable(var.name, var.values)\n                    attr.attributes = var.attributes.copy()\n                    attributes[i] = attr\n\n        def set_attributes_of_attributes(_vars, _table):\n            for i, variable in enumerate(_vars):\n                if variable.name == feature_names_column:\n                    continue\n                for j, row in enumerate(_table):\n                    value = variable.repr_val(row) if np.isscalar(row) \\\n                        else row[i] if isinstance(row[i], str) \\\n                        else variable.repr_val(row[i])\n\n                    if value not in MISSING_VALUES:\n                        attributes[j].attributes[variable.name] = value\n\n        set_attributes_of_attributes(table.domain.class_vars, table.Y)\n        set_attributes_of_attributes(table.domain.metas, table.metas)\n\n        # weights\n        self.W = np.empty((self.n_rows, 0))\n\n        def get_table_from_attributes_of_attributes(_vars, _dtype=float):\n            T = np.empty((self.n_rows, len(_vars)), dtype=_dtype)\n            for i, _attr in enumerate(table.domain.attributes):\n                for j, _var in enumerate(_vars):\n                    val = str(_attr.attributes.get(_var.name, \"\"))\n                    if not _var.is_string:\n                        val = np.nan if val in MISSING_VALUES else \\\n                            _var.values.index(val) if \\\n                                _var.is_discrete else float(val)\n                    T[i, j] = val\n            return T\n\n        # class_vars - attributes of attributes to class - from old domain\n        class_vars = []\n        if old_domain is not None:\n            class_vars = old_domain.class_vars\n        self.Y = get_table_from_attributes_of_attributes(class_vars)\n\n        # metas\n        # - feature names and attributes of attributes to metas\n        self.metas, metas = np.empty((self.n_rows, 0), dtype=object), []\n        if meta_attr_name not in [m.name for m in table.domain.metas] and \\\n                table.domain.attributes:\n            self.metas = np.array([[a.name] for a in table.domain.attributes],\n                                  dtype=object)\n            metas.append(StringVariable(meta_attr_name))\n\n        names = chain.from_iterable(list(attr.attributes)\n                                    for attr in table.domain.attributes)\n        names = sorted(set(names) - {var.name for var in class_vars})\n\n        def guessed_var(i, var_name):\n            orig_vals = M[:, i]\n            val_map, vals, var_type = Orange.data.io.guess_data_type(orig_vals)\n            values, variable = Orange.data.io.sanitize_variable(\n                val_map, vals, orig_vals, var_type, {}, name=var_name)\n            M[:, i] = values\n            return variable\n\n        _metas = [StringVariable(n) for n in names]\n        if old_domain is not None:\n            _metas = [m for m in old_domain.metas if m.name != meta_attr_name]\n        M = get_table_from_attributes_of_attributes(_metas, _dtype=object)\n        if old_domain is None:\n            _metas = [guessed_var(i, m.name) for i, m in enumerate(_metas)]\n        if _metas:\n            self.metas = np.hstack((self.metas, M))\n            metas.extend(_metas)\n\n        self.domain = Domain(attributes, class_vars, metas)\n        cls._init_ids(self)\n        self.attributes = table.attributes.copy()\n        self.attributes[\"old_domain\"] = table.domain\n        return self\n\n    def to_sparse(self, sparse_attributes=True, sparse_class=False,\n                  sparse_metas=False):\n        def sparsify(features):\n            for f in features:\n                f.sparse = True\n\n        new_domain = self.domain.copy()\n\n        if sparse_attributes:\n            sparsify(new_domain.attributes)\n        if sparse_class:\n            sparsify(new_domain.class_vars)\n        if sparse_metas:\n            sparsify(new_domain.metas)\n        return self.transform(new_domain)\n\n    def to_dense(self, dense_attributes=True, dense_class=True,\n                 dense_metas=True):\n        def densify(features):\n            for f in features:\n                f.sparse = False\n\n        new_domain = self.domain.copy()\n\n        if dense_attributes:\n            densify(new_domain.attributes)\n        if dense_class:\n            densify(new_domain.class_vars)\n        if dense_metas:\n            densify(new_domain.metas)\n        t = self.transform(new_domain)\n        t.ids = self.ids    # preserve indices\n        return t\n\n\ndef _check_arrays(*arrays, dtype=None):\n    checked = []\n    if not len(arrays):\n        return checked\n\n    def ninstances(array):\n        if hasattr(array, \"shape\"):\n            return array.shape[0]\n        else:\n            return len(array) if array is not None else 0\n\n    shape_1 = ninstances(arrays[0])\n\n    for array in arrays:\n        if array is None:\n            checked.append(array)\n            continue\n\n        if ninstances(array) != shape_1:\n            raise ValueError(\"Leading dimension mismatch (%d != %d)\"\n                             % (ninstances(array), shape_1))\n\n        if sp.issparse(array):\n            array.data = np.asarray(array.data)\n            has_inf = _check_inf(array.data)\n        else:\n            if dtype is not None:\n                array = np.asarray(array, dtype=dtype)\n            else:\n                array = np.asarray(array)\n            has_inf = _check_inf(array)\n\n        if has_inf:\n            array[np.isinf(array)] = np.nan\n            warnings.warn(\"Array contains infinity.\", RuntimeWarning)\n        checked.append(array)\n\n    return checked\n\n\ndef _check_inf(array):\n    return array.dtype.char in np.typecodes['AllFloat'] and \\\n           np.isinf(array.data).any()\n\n\ndef _subarray(arr, rows, cols):\n    rows = _optimize_indices(rows, arr.shape[0])\n    cols = _optimize_indices(cols, arr.shape[1])\n    return arr[_rxc_ix(rows, cols)]\n\n\ndef _optimize_indices(indices, maxlen):\n    \"\"\"\n    Convert integer indices to slice if possible. It only converts increasing\n    integer ranges with positive steps and valid starts and ends.\n    Only convert valid ends so that invalid ranges will still raise\n    an exception.\n\n    Allows numpy to reuse the data array, because it defaults to copying\n    if given indices.\n\n    Parameters\n    ----------\n    indices : 1D sequence, slice or Ellipsis\n    \"\"\"\n    if isinstance(indices, slice):\n        return indices\n\n    if indices is ...:\n        return slice(None, None, 1)\n\n    if len(indices) >= 1:\n        indices = np.asarray(indices)\n        if indices.dtype != np.bool:\n            begin = indices[0]\n            end = indices[-1]\n            steps = np.diff(indices) if len(indices) > 1 else np.array([1])\n            step = steps[0]\n\n            # continuous ranges with constant step and valid start and stop index can be slices\n            if np.all(steps == step) and step > 0 and begin >= 0 and end < maxlen:\n                return slice(begin, end + step, step)\n\n    return indices\n\n\ndef _rxc_ix(rows, cols):\n    \"\"\"\n    Construct an index object to index the `rows` x `cols` cross product.\n\n    Rows and columns can be a 1d bool or int sequence, or a slice.\n    The later is a convenience and is interpreted the same\n    as `slice(None, None, -1)`\n\n    Parameters\n    ----------\n    rows : 1D sequence, slice\n        Row indices.\n    cols : 1D sequence, slice\n        Column indices.\n\n    See Also\n    --------\n    numpy.ix_\n\n    Examples\n    --------\n    >>> import numpy as np\n    >>> a = np.arange(10).reshape(2, 5)\n    >>> a[_rxc_ix([0, 1], [3, 4])]\n    array([[3, 4],\n           [8, 9]])\n    >>> a[_rxc_ix([False, True], slice(None, None, 1))]\n    array([[5, 6, 7, 8, 9]])\n\n    \"\"\"\n    isslice = (isinstance(rows, slice), isinstance(cols, slice))\n    if isslice == (True, True):\n        return rows, cols\n    elif isslice == (True, False):\n        return rows, np.asarray(np.ix_(cols), int).ravel()\n    elif isslice == (False, True):\n        return np.asarray(np.ix_(rows), int).ravel(), cols\n    else:\n        r, c = np.ix_(rows, cols)\n        return np.asarray(r, int), np.asarray(c, int)\n\n\ndef assure_domain_conversion_sparsity(target, source):\n    \"\"\"\n    Assure that the table obeys the domain conversion's suggestions about sparsity.\n\n    Args:\n        target (Table): the target table.\n        source (Table): the source table.\n\n    Returns:\n        Table: with fixed sparsity. The sparsity is set as it is recommended by domain conversion\n            for transformation from source to the target domain.\n    \"\"\"\n    conversion = target.domain.get_conversion(source.domain)\n    match_density = [assure_array_dense, assure_array_sparse]\n    target.X = match_density[conversion.sparse_X](target.X)\n    target.Y = match_density[conversion.sparse_Y](target.Y)\n    target.metas = match_density[conversion.sparse_metas](target.metas)\n    return target\n",
            "header": {
                "file": {
                    "path": "Orange/data/table.py"
                },
                "misc_line": null
            },
            "index_line": {
                "old_commit_hash": "5bcc2ad91",
                "new_commit_hash": "73c0ba96d",
                "mode": "100644"
            },
            "is_binary_file": false,
            "binary_line": null,
            "minus_file": {
                "path": "a/Orange/data/table.py"
            },
            "plus_file": {
                "path": "b/Orange/data/table.py"
            },
            "hunks": [
                {
                    "descriptor": {
                        "old_range": {
                            "start": 1779,
                            "length": 7
                        },
                        "new_range": {
                            "start": 1779,
                            "length": 8
                        },
                        "section": "def _check_arrays(*arrays, dtype=None):"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "            has_inf = _check_inf(array)",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "        if has_inf:",
                                "type": "context"
                            },
                            {
                                "content": "            raise ValueError(\"Array contains infinity.\")",
                                "type": "deleted"
                            },
                            {
                                "content": "            array[np.isinf(array)] = np.nan",
                                "type": "added"
                            },
                            {
                                "content": "            warnings.warn(\"Array contains infinity.\", RuntimeWarning)",
                                "type": "added"
                            },
                            {
                                "content": "        checked.append(array)",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "    return checked",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [
                        {
                            "file_name": "Orange/data/table.py",
                            "type": "function",
                            "name": "_check_arrays",
                            "content": "def _check_arrays(*arrays, dtype=None):\n    checked = []\n    if not len(arrays):\n        return checked\n\n    def ninstances(array):\n        if hasattr(array, \"shape\"):\n            return array.shape[0]\n        else:\n            return len(array) if array is not None else 0\n\n    shape_1 = ninstances(arrays[0])\n\n    for array in arrays:\n        if array is None:\n            checked.append(array)\n            continue\n\n        if ninstances(array) != shape_1:\n            raise ValueError(\"Leading dimension mismatch (%d != %d)\"\n                             % (ninstances(array), shape_1))\n\n        if sp.issparse(array):\n            array.data = np.asarray(array.data)\n            has_inf = _check_inf(array.data)\n        else:\n            if dtype is not None:\n                array = np.asarray(array, dtype=dtype)\n            else:\n                array = np.asarray(array)\n            has_inf = _check_inf(array)\n\n        if has_inf:\n            raise ValueError(\"Array contains infinity.\")\n        checked.append(array)\n\n    return checked",
                            "ast_type_str": "FunctionDef",
                            "start_lineno": 1749,
                            "end_lineno": 1785,
                            "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 copy\nimport os\nimport random\nimport unittest\nfrom unittest.mock import Mock, MagicMock, patch\nfrom distutils.version import LooseVersion\nfrom itertools import chain\nfrom math import isnan\n\nimport numpy as np\nimport scipy.sparse as sp\n\nimport Orange\nfrom Orange import data\nfrom Orange.data import (filter, Unknown, Variable, Table, DiscreteVariable,\n                         ContinuousVariable, Domain, StringVariable)\nfrom Orange.tests import test_dirname, assert_array_nanequal\nfrom Orange.data.table import _optimize_indices\n\n\nif LooseVersion(Orange.__version__) < LooseVersion(\"3.24\"):\n    def skip_deprecated_length(f):\n        return unittest.skip(\n            f\"Method {f.__name__} will be deprecated; tests are \"\n            \"skipped because it already fails on Python 3.7 on travis\")(f)\nelse:\n    def skip_deprecated_length(f):\n        def raise_deprecation(_):\n            raise RuntimeError(\n                f\"We reached 3.24 and method {f.__name__} is now deprecated. \"\n                f\"Remove the method the corresponding tests.\")\n        # Also don't forget to remove this function and imports of LooseVersion\n        # and Orange\n        return raise_deprecation\n\n\nclass TableTestCase(unittest.TestCase):\n    def setUp(self):\n        Variable._clear_all_caches()\n        data.table.dataset_dirs.append(test_dirname())\n\n    def tearDown(self):\n        data.table.dataset_dirs.remove(test_dirname())\n\n    def test_indexing_class(self):\n        d = data.Table(\"test1\")\n        self.assertEqual([e.get_class() for e in d], [\"t\", \"t\", \"f\"])\n        cind = len(d.domain) - 1\n        self.assertEqual([e[cind] for e in d], [\"t\", \"t\", \"f\"])\n        self.assertEqual([e[\"d\"] for e in d], [\"t\", \"t\", \"f\"])\n        cvar = d.domain.class_var\n        self.assertEqual([e[cvar] for e in d], [\"t\", \"t\", \"f\"])\n\n    def test_filename(self):\n        dir = data.table.get_sample_datasets_dir()\n        d = data.Table(\"iris\")\n        self.assertEqual(d.__file__, os.path.join(dir, \"iris.tab\"))\n\n        d = data.Table(\"test2.tab\")\n        self.assertTrue(d.__file__.endswith(\"test2.tab\"))  # platform dependent\n\n    def test_indexing(self):\n        import warnings\n\n        with warnings.catch_warnings():\n            warnings.simplefilter(\"ignore\")\n            d = data.Table(\"test2\")\n\n            # regular, discrete\n            varc = d.domain[\"c\"]\n            self.assertEqual(d[0, 1], \"0\")\n            self.assertEqual(d[0, varc], \"0\")\n            self.assertEqual(d[0, \"c\"], \"0\")\n            self.assertEqual(d[0][1], \"0\")\n            self.assertEqual(d[0][varc], \"0\")\n            self.assertEqual(d[0][\"c\"], \"0\")\n            self.assertEqual(d[np.int_(0), np.int_(1)], \"0\")\n            self.assertEqual(d[np.int_(0)][np.int_(1)], \"0\")\n\n            # regular, continuous\n            varb = d.domain[\"b\"]\n            self.assertEqual(d[0, 0], 0)\n            self.assertEqual(d[0, varb], 0)\n            self.assertEqual(d[0, \"b\"], 0)\n            self.assertEqual(d[0][0], 0)\n            self.assertEqual(d[0][varb], 0)\n            self.assertEqual(d[0][\"b\"], 0)\n            self.assertEqual(d[np.int_(0), np.int_(0)], 0)\n            self.assertEqual(d[np.int_(0)][np.int_(0)], 0)\n\n            # negative\n            varb = d.domain[\"b\"]\n            self.assertEqual(d[-2, 0], 3.333)\n            self.assertEqual(d[-2, varb], 3.333)\n            self.assertEqual(d[-2, \"b\"], 3.333)\n            self.assertEqual(d[-2][0], 3.333)\n            self.assertEqual(d[-2][varb], 3.333)\n            self.assertEqual(d[-2][\"b\"], 3.333)\n            self.assertEqual(d[np.int_(-2), np.int_(0)], 3.333)\n            self.assertEqual(d[np.int_(-2)][np.int_(0)], 3.333)\n\n            # meta, discrete\n            vara = d.domain[\"a\"]\n            metaa = d.domain.index(\"a\")\n            self.assertEqual(d[0, metaa], \"A\")\n            self.assertEqual(d[0, vara], \"A\")\n            self.assertEqual(d[0, \"a\"], \"A\")\n            self.assertEqual(d[0][metaa], \"A\")\n            self.assertEqual(d[0][vara], \"A\")\n            self.assertEqual(d[0][\"a\"], \"A\")\n            self.assertEqual(d[np.int_(0), np.int_(metaa)], \"A\")\n            self.assertEqual(d[np.int_(0)][np.int_(metaa)], \"A\")\n\n            # meta, string\n            vare = d.domain[\"e\"]\n            metae = d.domain.index(\"e\")\n            self.assertEqual(d[0, metae], \"i\")\n            self.assertEqual(d[0, vare], \"i\")\n            self.assertEqual(d[0, \"e\"], \"i\")\n            self.assertEqual(d[0][metae], \"i\")\n            self.assertEqual(d[0][vare], \"i\")\n            self.assertEqual(d[0][\"e\"], \"i\")\n            self.assertEqual(d[np.int_(0), np.int_(metae)], \"i\")\n            self.assertEqual(d[np.int_(0)][np.int_(metae)], \"i\")\n\n    def test_indexing_example(self):\n        import warnings\n\n        with warnings.catch_warnings():\n            warnings.simplefilter(\"ignore\")\n            d = data.Table(\"test2\")\n            e = d[0]\n\n            # regular, discrete\n            varc = d.domain[\"c\"]\n            self.assertEqual(e[1], \"0\")\n            self.assertEqual(e[varc], \"0\")\n            self.assertEqual(e[\"c\"], \"0\")\n            self.assertEqual(e[np.int_(1)], \"0\")\n\n            # regular, continuous\n            varb = d.domain[\"b\"]\n            self.assertEqual(e[0], 0)\n            self.assertEqual(e[varb], 0)\n            self.assertEqual(e[\"b\"], 0)\n            self.assertEqual(e[np.int_(0)], 0)\n\n            # meta, discrete\n            vara = d.domain[\"a\"]\n            metaa = d.domain.index(\"a\")\n            self.assertEqual(e[metaa], \"A\")\n            self.assertEqual(e[vara], \"A\")\n            self.assertEqual(e[\"a\"], \"A\")\n            self.assertEqual(e[np.int_(metaa)], \"A\")\n\n            # meta, string\n            vare = d.domain[\"e\"]\n            metae = d.domain.index(\"e\")\n            self.assertEqual(e[metae], \"i\")\n            self.assertEqual(e[vare], \"i\")\n            self.assertEqual(e[\"e\"], \"i\")\n            self.assertEqual(e[np.int_(metae)], \"i\")\n\n    def test_indexing_assign_value(self):\n        import warnings\n\n        with warnings.catch_warnings():\n            warnings.simplefilter(\"ignore\")\n            d = data.Table(\"test2\")\n\n            # meta\n            vara = d.domain[\"a\"]\n            metaa = d.domain.index(\"a\")\n\n            self.assertEqual(d[0, \"a\"], \"A\")\n            d[0, \"a\"] = \"B\"\n            self.assertEqual(d[0, \"a\"], \"B\")\n            d[0][\"a\"] = \"A\"\n            self.assertEqual(d[0, \"a\"], \"A\")\n\n            d[0, vara] = \"B\"\n            self.assertEqual(d[0, \"a\"], \"B\")\n            d[0][vara] = \"A\"\n            self.assertEqual(d[0, \"a\"], \"A\")\n\n            d[0, metaa] = \"B\"\n            self.assertEqual(d[0, \"a\"], \"B\")\n            d[0][metaa] = \"A\"\n            self.assertEqual(d[0, \"a\"], \"A\")\n\n            d[0, np.int_(metaa)] = \"B\"\n            self.assertEqual(d[0, \"a\"], \"B\")\n            d[0][np.int_(metaa)] = \"A\"\n            self.assertEqual(d[0, \"a\"], \"A\")\n\n            # regular\n            varb = d.domain[\"b\"]\n\n            self.assertEqual(d[0, \"b\"], 0)\n            d[0, \"b\"] = 42\n            self.assertEqual(d[0, \"b\"], 42)\n            d[0][\"b\"] = 0\n            self.assertEqual(d[0, \"b\"], 0)\n\n            d[0, varb] = 42\n            self.assertEqual(d[0, \"b\"], 42)\n            d[0][varb] = 0\n            self.assertEqual(d[0, \"b\"], 0)\n\n            d[0, 0] = 42\n            self.assertEqual(d[0, \"b\"], 42)\n            d[0][0] = 0\n            self.assertEqual(d[0, \"b\"], 0)\n\n            d[0, np.int_(0)] = 42\n            self.assertEqual(d[0, \"b\"], 42)\n            d[0][np.int_(0)] = 0\n            self.assertEqual(d[0, \"b\"], 0)\n\n    @skip_deprecated_length\n    def test_indexing_del_example(self):\n        import warnings\n\n        with warnings.catch_warnings():\n            warnings.simplefilter(\"ignore\")\n            d = data.Table(\"test2\")\n            initlen = len(d)\n\n            # remove first\n            d[4, \"e\"] = \"4ex\"\n            self.assertEqual(d[4, \"e\"], \"4ex\")\n            del d[0]\n            self.assertEqual(len(d), initlen - 1)\n            self.assertEqual(d[3, \"e\"], \"4ex\")\n\n            # remove middle\n            del d[2]\n            self.assertEqual(len(d), initlen - 2)\n            self.assertEqual(d[2, \"e\"], \"4ex\")\n\n            # remove middle\n            del d[4]\n            self.assertEqual(len(d), initlen - 3)\n            self.assertEqual(d[2, \"e\"], \"4ex\")\n\n            # remove last\n            d[-1, \"e\"] = \"was last\"\n            del d[-1]\n            self.assertEqual(len(d), initlen - 4)\n            self.assertEqual(d[2, \"e\"], \"4ex\")\n            self.assertNotEqual(d[-1, \"e\"], \"was last\")\n\n            # remove one before last\n            d[-1, \"e\"] = \"was last\"\n            del d[-2]\n            self.assertEqual(len(d), initlen - 5)\n            self.assertEqual(d[2, \"e\"], \"4ex\")\n            self.assertEqual(d[-1, \"e\"], \"was last\")\n\n            d[np.int_(2), \"e\"] = \"2ex\"\n            del d[np.int_(2)]\n            self.assertEqual(len(d), initlen - 6)\n            self.assertNotEqual(d[2, \"e\"], \"2ex\")\n\n            with self.assertRaises(IndexError):\n                del d[100]\n            self.assertEqual(len(d), initlen - 6)\n\n            with self.assertRaises(IndexError):\n                del d[-100]\n            self.assertEqual(len(d), initlen - 6)\n\n    def test_indexing_assign_example(self):\n        def almost_equal_list(s, t):\n            for e, f in zip(s, t):\n                self.assertAlmostEqual(e, f)\n\n        import warnings\n\n        with warnings.catch_warnings():\n            warnings.simplefilter(\"ignore\")\n            d = data.Table(\"test2\")\n\n            vara = d.domain[\"a\"]\n            metaa = d.domain.index(vara)\n\n            self.assertFalse(isnan(d[0, \"a\"]))\n            d[0] = [\"3.14\", \"1\", \"f\"]\n            almost_equal_list(d[0].values(), [3.14, \"1\", \"f\"])\n            self.assertTrue(isnan(d[0, \"a\"]))\n            d[0] = [3.15, 1, \"t\"]\n            almost_equal_list(d[0].values(), [3.15, \"0\", \"t\"])\n            d[np.int_(0)] = [3.15, 2, \"f\"]\n            almost_equal_list(d[0].values(), [3.15, 2, \"f\"])\n\n            with self.assertRaises(ValueError):\n                d[0] = [\"3.14\", \"1\"]\n\n            with self.assertRaises(ValueError):\n                d[np.int_(0)] = [\"3.14\", \"1\"]\n\n            ex = data.Instance(d.domain, [\"3.16\", \"1\", \"f\"])\n            d[0] = ex\n            almost_equal_list(d[0].values(), [3.16, \"1\", \"f\"])\n\n            ex = data.Instance(d.domain, [\"3.16\", 2, \"t\"])\n            d[np.int_(0)] = ex\n            almost_equal_list(d[0].values(), [3.16, 2, \"t\"])\n\n            ex = data.Instance(d.domain, [\"3.16\", \"1\", \"f\"])\n            ex[\"e\"] = \"mmmapp\"\n            d[0] = ex\n            almost_equal_list(d[0].values(), [3.16, \"1\", \"f\"])\n            self.assertEqual(d[0, \"e\"], \"mmmapp\")\n\n    def test_slice(self):\n        import warnings\n\n        with warnings.catch_warnings():\n            warnings.simplefilter(\"ignore\")\n            d = data.Table(\"test2\")\n            x = d[:3]\n            self.assertEqual(len(x), 3)\n            self.assertEqual([e[0] for e in x], [0, 1.1, 2.22])\n\n            x = d[2:5]\n            self.assertEqual(len(x), 3)\n            self.assertEqual([e[0] for e in x], [2.22, 2.23, 2.24])\n\n            x = d[4:1:-1]\n            self.assertEqual(len(x), 3)\n            self.assertEqual([e[0] for e in x], [2.24, 2.23, 2.22])\n\n            x = d[-3:]\n            self.assertEqual(len(x), 3)\n            self.assertEqual([e[0] for e in x], [2.26, 3.333, Unknown])\n\n    def test_assign_slice_value(self):\n        import warnings\n\n        with warnings.catch_warnings():\n            warnings.simplefilter(\"ignore\")\n            d = data.Table(\"test2\")\n            d[2:5, 0] = 42\n            self.assertEqual([e[0] for e in d],\n                             [0, 1.1, 42, 42, 42, 2.25, 2.26, 3.333, Unknown])\n            d[:3, \"b\"] = 43\n            self.assertEqual([e[0] for e in d],\n                             [43, 43, 43, 42, 42, 2.25, 2.26, 3.333, None])\n            d[-2:, d.domain[0]] = 44\n            self.assertEqual([e[0] for e in d],\n                             [43, 43, 43, 42, 42, 2.25, 2.26, 44, 44])\n\n            d[2:5, \"a\"] = \"A\"\n            self.assertEqual([e[\"a\"] for e in d], list(\"ABAAACCDE\"))\n\n    @skip_deprecated_length\n    def test_del_slice_example(self):\n        import warnings\n\n        with warnings.catch_warnings():\n            warnings.simplefilter(\"ignore\")\n            d = data.Table(\"test2\")\n\n            vals = [e[0] for e in d]\n\n            del d[2:2]\n            self.assertEqual([e[0] for e in d], vals)\n\n            del d[2:5]\n            del vals[2:5]\n            self.assertEqual([e[0] for e in d], vals)\n\n            del d[:]\n            self.assertEqual(len(d), 0)\n\n    @skip_deprecated_length\n    def test_del_slice_ids(self):\n        # __del__ updates `ids` member\n        d = data.Table(\"test2\")\n        ids = d.ids.copy()\n        del d[2:4]\n        np.testing.assert_array_equal(d.ids, np.delete(ids, slice(2, 4)))\n\n    @skip_deprecated_length\n    def test_set_slice_example(self):\n        import warnings\n\n        with warnings.catch_warnings():\n            warnings.simplefilter(\"ignore\")\n            d = data.Table(\"test2\")\n            d[5, 0] = 42\n            d[:3] = d[5]\n            self.assertEqual(d[1, 0], 42)\n\n            d[5:2:-1] = [3, None, None]\n            self.assertEqual([e[0] for e in d],\n                             [42, 42, 42, 3, 3, 3, 2.26, 3.333, None])\n            self.assertTrue(isnan(d[3, 2]))\n\n            d[2:5] = 42\n            self.assertTrue(np.all(d.X[2:5] == 42))\n            self.assertEqual(d.Y[2], 0)\n\n    def test_multiple_indices(self):\n        import warnings\n\n        with warnings.catch_warnings():\n            warnings.simplefilter(\"ignore\")\n            d = data.Table(\"test2\")\n\n            with self.assertRaises(IndexError):\n                x = d[2, 5, 1]\n\n            with self.assertRaises(IndexError):\n                x = d[(2, 5, 1)]\n\n            x = d[[2, 5, 1]]\n            self.assertEqual([e[0] for e in x], [2.22, 2.25, 1.1])\n\n    def test_assign_multiple_indices_value(self):\n        import warnings\n\n        with warnings.catch_warnings():\n            warnings.simplefilter(\"ignore\")\n            d = data.Table(\"test2\")\n\n            d[1:4, \"b\"] = 42\n            self.assertEqual([e[0] for e in d],\n                             [0, 42, 42, 42, 2.24, 2.25, 2.26, 3.333, None])\n\n            d[range(5, 2, -1), \"b\"] = None\n            self.assertEqual([e[d.domain[0]] for e in d],\n                             [0, 42, 42, None, \"?\", \"\", 2.26, 3.333, None])\n\n    @skip_deprecated_length\n    def test_del_multiple_indices_example(self):\n        import warnings\n\n        with warnings.catch_warnings():\n            warnings.simplefilter(\"ignore\")\n            d = data.Table(\"test2\")\n\n            vals = [e[0] for e in d]\n\n            del d[[1, 5, 2]]\n            del vals[5]\n            del vals[2]\n            del vals[1]\n            self.assertEqual([e[0] for e in d], vals)\n\n            del d[range(1, 3)]\n            del vals[1:3]\n            self.assertEqual([e[0] for e in d], vals)\n\n    def test_set_multiple_indices_example(self):\n        import warnings\n\n        with warnings.catch_warnings():\n            warnings.simplefilter(\"ignore\")\n            d = data.Table(\"test2\")\n\n            vals = [e[0] for e in d]\n            d[[1, 2, 5]] = [42, None, None]\n            vals[1] = vals[2] = vals[5] = 42\n            self.assertEqual([e[0] for e in d], vals)\n\n    @skip_deprecated_length\n    def test_views(self):\n        d = data.Table(\"zoo\")\n        crc = d.checksum(True)\n        x = d[:20]\n        self.assertEqual(crc, d.checksum(True))\n        del x[13]\n        self.assertEqual(crc, d.checksum(True))\n        del x[4:9]\n        self.assertEqual(crc, d.checksum(True))\n\n    def test_bool(self):\n        d = data.Table(\"iris\")\n        self.assertTrue(d)\n\n        d = data.Table(\"test3\")\n        self.assertFalse(d)\n\n        d = data.Table(\"iris\")\n        self.assertTrue(d)\n\n    def test_checksum(self):\n        d = data.Table(\"zoo\")\n        d[42, 3] = 0\n        crc1 = d.checksum(False)\n        d[42, 3] = 1\n        crc2 = d.checksum(False)\n        self.assertNotEqual(crc1, crc2)\n        d[42, 3] = 0\n        crc3 = d.checksum(False)\n        self.assertEqual(crc1, crc3)\n        _ = d[42, \"name\"]\n        d[42, \"name\"] = \"non-animal\"\n        crc4 = d.checksum(False)\n        self.assertEqual(crc1, crc4)\n        crc4 = d.checksum(True)\n        crc5 = d.checksum(1)\n        crc6 = d.checksum(False)\n        self.assertNotEqual(crc1, crc4)\n        self.assertNotEqual(crc1, crc5)\n        self.assertEqual(crc1, crc6)\n\n    def test_total_weight(self):\n        d = data.Table(\"zoo\")\n        self.assertEqual(d.total_weight(), len(d))\n\n        d.set_weights(0)\n        d[0].weight = 0.1\n        d[10].weight = 0.2\n        d[-1].weight = 0.3\n        self.assertAlmostEqual(d.total_weight(), 0.6)\n\n    def test_has_missing(self):\n        d = data.Table(\"zoo\")\n        self.assertFalse(d.has_missing())\n        self.assertFalse(d.has_missing_class())\n\n        d[10, 3] = \"?\"\n        self.assertTrue(d.has_missing())\n        self.assertFalse(d.has_missing_class())\n\n        d[10].set_class(\"?\")\n        self.assertTrue(d.has_missing())\n        self.assertTrue(d.has_missing_class())\n\n        d = data.Table(\"test3\")\n        self.assertFalse(d.has_missing())\n        self.assertFalse(d.has_missing_class())\n\n    def test_shuffle(self):\n        d = data.Table(\"zoo\")\n        crc = d.checksum()\n        names = set(str(x[\"name\"]) for x in d)\n\n        d.shuffle()\n        self.assertNotEqual(crc, d.checksum())\n        self.assertSetEqual(names, set(str(x[\"name\"]) for x in d))\n        crc2 = d.checksum()\n\n        x = d[2:10]\n        crcx = x.checksum()\n        d.shuffle()\n        self.assertNotEqual(crc2, d.checksum())\n        self.assertEqual(crcx, x.checksum())\n\n        crc2 = d.checksum()\n        x.shuffle()\n        self.assertNotEqual(crcx, x.checksum())\n        self.assertEqual(crc2, d.checksum())\n\n    @staticmethod\n    def not_less_ex(ex1, ex2):\n        for v1, v2 in zip(ex1, ex2):\n            if v1 != v2:\n                return v1 < v2\n        return True\n\n    @staticmethod\n    def sorted(d):\n        for i in range(1, len(d)):\n            if not TableTestCase.not_less_ex(d[i - 1], d[i]):\n                return False\n        return True\n\n    @staticmethod\n    def not_less_ex_ord(ex1, ex2, ord):\n        for a in ord:\n            if ex1[a] != ex2[a]:\n                return ex1[a] < ex2[a]\n        return True\n\n    @staticmethod\n    def sorted_ord(d, ord):\n        for i in range(1, len(d)):\n            if not TableTestCase.not_less_ex_ord(d[i - 1], d[i], ord):\n                return False\n        return True\n\n    @skip_deprecated_length\n    def test_append(self):\n        d = data.Table(\"test3\")\n        d.append([None] * 3)\n        self.assertEqual(1, len(d))\n        self.assertTrue(all(isnan(i) for i in d[0]))\n\n        d.append([42, \"0\", None])\n        self.assertEqual(2, len(d))\n        self.assertEqual(d[1], [42, \"0\", None])\n\n        assert_array_nanequal(\n            d.metas,\n            np.array([[v.Unknown for v in d.domain.metas]] * 2,\n                     dtype=object))\n\n    @skip_deprecated_length\n    def test_append2(self):\n        d = data.Table(\"iris\")\n        d.shuffle()\n        l1 = len(d)\n        d.append([1, 2, 3, 4, 0])\n        self.assertEqual(len(d), l1 + 1)\n        self.assertEqual(d[-1], [1, 2, 3, 4, 0])\n\n        x = data.Instance(d[10])\n        d.append(x)\n        self.assertEqual(d[-1], d[10])\n\n        x = d[:50]\n        x.ensure_copy()\n        x.append(d[50])\n        self.assertEqual(x[50], d[50])\n\n    @skip_deprecated_length\n    def test_extend(self):\n        d = data.Table(\"iris\")\n        d.shuffle()\n\n        x = d[:5]\n        x.ensure_copy()\n        d.extend(x)\n        for i in range(5):\n            self.assertEqual(d[i], d[-5 + i])\n\n        y = d[:2, 1]\n        x.ensure_copy()\n        x.extend(y)\n        np.testing.assert_almost_equal(x[-2:, 1].X, y.X)\n        self.assertEqual(np.isnan(x).sum(), 8)\n\n    @skip_deprecated_length\n    def test_extend2(self):\n        d = data.Table(\"test3\")\n        d.extend([[None] * 3,\n                  [None] * 3])\n        assert_array_nanequal(\n            d.metas,\n            np.array([[v.Unknown for v in d.domain.metas]] * 2,\n                     dtype=object))\n\n    def test_copy(self):\n        t = data.Table(np.zeros((5, 3)), np.arange(5), np.zeros((5, 3)))\n\n        copy = t.copy()\n        self.assertTrue(np.all(t.X == copy.X))\n        self.assertTrue(np.all(t.Y == copy.Y))\n        self.assertTrue(np.all(t.metas == copy.metas))\n        copy[0] = [1, 1, 1, 1, 1, 1, 1, 1]\n        self.assertFalse(np.all(t.X == copy.X))\n        self.assertFalse(np.all(t.Y == copy.Y))\n        self.assertFalse(np.all(t.metas == copy.metas))\n\n    def test_copy_sparse(self):\n        t = data.Table('iris').to_sparse()\n        copy = t.copy()\n\n        self.assertEqual((t.X != copy.X).nnz, 0)      # sparse matrices match by content\n        np.testing.assert_equal(t.Y, copy.Y)\n        np.testing.assert_equal(t.metas, copy.metas)\n\n        self.assertNotEqual(id(t.X), id(copy.X))\n        self.assertNotEqual(id(t._Y), id(copy._Y))\n        self.assertNotEqual(id(t.metas), id(copy.metas))\n\n    def test_concatenate(self):\n        d1 = data.Domain([data.ContinuousVariable('a1')])\n        t1 = data.Table.from_numpy(d1, [[1],\n                                        [2]])\n        d2 = data.Domain([data.ContinuousVariable('a2')],\n                         metas=[data.StringVariable('s')])\n        t2 = data.Table.from_numpy(d2, [[3],\n                                        [4]], metas=[['foo'],\n                                                     ['fuu']])\n        self.assertRaises(ValueError,\n                          lambda: data.Table.concatenate((t1, t2), axis=5))\n\n        t3 = data.Table.concatenate((t1, t2))\n        self.assertEqual(t3.domain.attributes,\n                         t1.domain.attributes + t2.domain.attributes)\n        self.assertEqual(len(t3.domain.metas), 1)\n        self.assertEqual(t3.X.shape, (2, 2))\n        self.assertRaises(ValueError, lambda: data.Table.concatenate((t3, t1)))\n        self.assertRaises(ValueError, lambda: data.Table.concatenate((t3, t1), axis=0))\n\n        t4 = data.Table.concatenate((t3, t3), axis=0)\n        np.testing.assert_equal(t4.X, [[1, 3],\n                                       [2, 4],\n                                       [1, 3],\n                                       [2, 4]])\n\n    def test_sparse_concatenate_rows(self):\n        iris = Table(\"iris\")\n        iris.X = sp.csc_matrix(iris.X)\n        new = Table.concatenate([iris, iris], axis=0)\n        self.assertEqual(len(new), 300)\n        self.assertTrue(sp.issparse(new.X), \"Concatenated X is not sparse.\")\n        self.assertFalse(sp.issparse(new.Y), \"Concatenated Y is not dense.\")\n        self.assertFalse(sp.issparse(new.metas), \"Concatenated metas is not dense.\")\n        self.assertEqual(len(new.ids), 300)\n\n    @skip_deprecated_length\n    def test_convert_through_append(self):\n        d = data.Table(\"iris\")\n        dom2 = data.Domain([d.domain[0], d.domain[2], d.domain[4]])\n        d2 = data.Table(dom2)\n        dom3 = data.Domain([d.domain[1], d.domain[2]], None)\n        d3 = data.Table(dom3)\n        for e in d[:5]:\n            d2.append(e)\n            d3.append(e)\n        for e, e2, e3 in zip(d, d2, d3):\n            self.assertEqual(e[0], e2[0])\n            self.assertEqual(e[1], e3[0])\n\n    def test_pickle(self):\n        import pickle\n\n        d = data.Table(\"zoo\")\n        s = pickle.dumps(d)\n        d2 = pickle.loads(s)\n        self.assertEqual(d[0], d2[0])\n\n        self.assertEqual(d.checksum(include_metas=False),\n                         d2.checksum(include_metas=False))\n\n        d = data.Table(\"iris\")\n        s = pickle.dumps(d)\n        d2 = pickle.loads(s)\n        self.assertEqual(d[0], d2[0])\n        self.assertEqual(d.checksum(include_metas=False),\n                         d2.checksum(include_metas=False))\n\n    def test_translate_through_slice(self):\n        d = data.Table(\"iris\")\n        dom = data.Domain([\"petal length\", \"sepal length\", \"iris\"],\n                          source=d.domain)\n        d_ref = d[:10, dom.variables]\n        self.assertEqual(d_ref.domain.class_var, d.domain.class_var)\n        self.assertEqual(d_ref[0, \"petal length\"], d[0, \"petal length\"])\n        self.assertEqual(d_ref[0, \"sepal length\"], d[0, \"sepal length\"])\n        self.assertEqual(d_ref.X.shape, (10, 2))\n        self.assertEqual(d_ref.Y.shape, (10,))\n\n    def test_saveTab(self):\n        d = data.Table(\"iris\")[:3]\n        d.save(\"test-save.tab\")\n        try:\n            d2 = data.Table(\"test-save.tab\")\n            for e1, e2 in zip(d, d2):\n                self.assertEqual(e1, e2)\n        finally:\n            os.remove(\"test-save.tab\")\n            os.remove(\"test-save.tab.metadata\")\n\n        dom = data.Domain([data.ContinuousVariable(\"a\")])\n        d = data.Table(dom, [[i] for i in range(3)])\n        d.save(\"test-save.tab\")\n        try:\n            d2 = data.Table(\"test-save.tab\")\n            self.assertEqual(len(d.domain.attributes), 1)\n            self.assertEqual(d.domain.class_var, None)\n            for i in range(3):\n                self.assertEqual(d2[i], [i])\n        finally:\n            os.remove(\"test-save.tab\")\n\n        dom = data.Domain([data.ContinuousVariable(\"a\")], None)\n        d = data.Table(dom, [[i] for i in range(3)])\n        d.save(\"test-save.tab\")\n        try:\n            d2 = data.Table(\"test-save.tab\")\n            self.assertEqual(len(d.domain.attributes), 1)\n            for i in range(3):\n                self.assertEqual(d2[i], [i])\n        finally:\n            os.remove(\"test-save.tab\")\n\n        d = data.Table(\"zoo\")\n        d.save(\"test-zoo.tab\")\n        dd = data.Table(\"test-zoo\")\n        try:\n            self.assertTupleEqual(d.domain.metas, dd.domain.metas,\n                                  msg=\"Meta attributes don't match.\")\n            self.assertTupleEqual(d.domain.variables, dd.domain.variables,\n                                  msg=\"Attributes don't match.\")\n\n            np.testing.assert_almost_equal(d.W, dd.W,\n                                           err_msg=\"Weights don't match.\")\n            for i in range(10):\n                for j in d.domain.variables:\n                    self.assertEqual(d[i][j], dd[i][j])\n        finally:\n            os.remove(\"test-zoo.tab\")\n\n        d = data.Table(\"zoo\")\n        d.set_weights(range(len(d)))\n        d.save(\"test-zoo-weights.tab\")\n        dd = data.Table(\"test-zoo-weights\")\n        try:\n            self.assertTupleEqual(d.domain.metas, dd.domain.metas,\n                                  msg=\"Meta attributes don't match.\")\n            self.assertTupleEqual(d.domain.variables, dd.domain.variables,\n                                  msg=\"Attributes don't match.\")\n\n            np.testing.assert_almost_equal(d.W, dd.W,\n                                           err_msg=\"Weights don't match.\")\n            for i in range(10):\n                for j in d.domain.variables:\n                    self.assertEqual(d[i][j], dd[i][j])\n        finally:\n            os.remove(\"test-zoo-weights.tab\")\n\n    def test_save_pickle(self):\n        table = data.Table(\"iris\")\n        try:\n            table.save(\"iris.pickle\")\n            table2 = data.Table.from_file(\"iris.pickle\")\n            np.testing.assert_almost_equal(table.X, table2.X)\n            np.testing.assert_almost_equal(table.Y, table2.Y)\n            self.assertEqual(table.domain[0], table2.domain[0])\n        finally:\n            os.remove(\"iris.pickle\")\n\n    def test_from_numpy(self):\n        a = np.arange(20, dtype=\"d\").reshape((4, 5))\n        a[:, -1] = [0, 0, 0, 1]\n        dom = data.Domain([data.ContinuousVariable(x) for x in \"abcd\"],\n                          data.DiscreteVariable(\"e\", values=[\"no\", \"yes\"]))\n        table = data.Table(dom, a)\n        for i in range(4):\n            self.assertEqual(table[i].get_class(), \"no\" if i < 3 else \"yes\")\n            for j in range(5):\n                self.assertEqual(a[i, j], table[i, j])\n                table[i, j] = random.random()\n                self.assertEqual(a[i, j], table[i, j])\n\n        with self.assertRaises(IndexError):\n            table[0, -5] = 5\n\n    def test_filter_is_defined(self):\n        d = data.Table(\"iris\")\n        d[1, 4] = Unknown\n        self.assertTrue(isnan(d[1, 4]))\n        d[140, 0] = Unknown\n        e = filter.IsDefined()(d)\n        self.assertEqual(len(e), len(d) - 2)\n        self.assertEqual(e[0], d[0])\n        self.assertEqual(e[1], d[2])\n        self.assertEqual(e[147], d[149])\n        self.assertTrue(d.has_missing())\n        self.assertFalse(e.has_missing())\n\n    def test_filter_has_class(self):\n        d = data.Table(\"iris\")\n        d[1, 4] = Unknown\n        self.assertTrue(isnan(d[1, 4]))\n        d[140, 0] = Unknown\n        e = filter.HasClass()(d)\n        self.assertEqual(len(e), len(d) - 1)\n        self.assertEqual(e[0], d[0])\n        self.assertEqual(e[1], d[2])\n        self.assertEqual(e[148], d[149])\n        self.assertTrue(d.has_missing())\n        self.assertTrue(e.has_missing())\n        self.assertFalse(e.has_missing_class())\n\n    def test_filter_random(self):\n        d = data.Table(\"iris\")\n        e = filter.Random(50)(d)\n        self.assertEqual(len(e), 50)\n        e = filter.Random(50, negate=True)(d)\n        self.assertEqual(len(e), 100)\n        for i in range(5):\n            e = filter.Random(0.2)(d)\n            self.assertEqual(len(e), 30)\n            bc = np.bincount(np.array(e.Y[:], dtype=int))\n            if min(bc) > 7:\n                break\n        else:\n            self.fail(\"Filter returns too uneven distributions\")\n\n    def test_filter_values_nested(self):\n        d = data.Table(\"iris\")\n        f1 = filter.FilterContinuous(d.columns.sepal_length,\n                                     filter.FilterContinuous.Between,\n                                     min=4.5, max=5.0)\n        f2 = filter.FilterContinuous(d.columns.sepal_width,\n                                     filter.FilterContinuous.Between,\n                                     min=3.1, max=3.4)\n        f3 = filter.FilterDiscrete(d.columns.iris, [0, 1])\n        f = filter.Values([filter.Values([f1, f2], conjunction=False), f3])\n        self.assertEqual(41, len(f(d)))\n\n    def test_filter_string_works_for_numeric_columns(self):\n        var = StringVariable(\"s\")\n        data = Table(Domain([], metas=[var]), [[x] for x in range(21)])\n        # 1, 2, 3, ..., 18, 19, 20\n\n        fs = filter.FilterString\n        filters = [\n            ((fs.Greater, \"5\"), dict(rows=4)),\n            # 6, 7, 8, 9\n            ((fs.Between, \"15\", \"2\"), dict(rows=6)),\n            # 15, 16, 17, 18, 19, 2\n            ((fs.Contains, \"2\"), dict(rows=3)),\n            # 2, 12, 20\n        ]\n\n        for args, expected in filters:\n            f = fs(var, *args)\n            filtered_data = filter.Values([f])(data)\n            self.assertEqual(len(filtered_data), expected[\"rows\"],\n                             \"{} returned wrong number of rows\".format(args))\n\n    def test_filter_value_continuous(self):\n        d = data.Table(\"iris\")\n        col = d.X[:, 2]\n\n        v = d.columns\n        f = filter.FilterContinuous(v.petal_length,\n                                    filter.FilterContinuous.Between,\n                                    min=4.5, max=5.1)\n\n        x = filter.Values([f])(d)\n        self.assertTrue(np.all(x.X[:, 2] >= 4.5))\n        self.assertTrue(np.all(x.X[:, 2] <= 5.1))\n        self.assertEqual(sum((col >= 4.5) * (col <= 5.1)), len(x))\n\n        f.ref = 5.1\n        f.oper = filter.FilterContinuous.Equal\n        x = filter.Values([f])(d)\n        self.assertTrue(np.all(x.X[:, 2] == 5.1))\n        self.assertEqual(sum(col == 5.1), len(x))\n\n        f.oper = filter.FilterContinuous.NotEqual\n        x = filter.Values([f])(d)\n        self.assertTrue(np.all(x.X[:, 2] != 5.1))\n        self.assertEqual(sum(col != 5.1), len(x))\n\n        f.oper = filter.FilterContinuous.Less\n        x = filter.Values([f])(d)\n        self.assertTrue(np.all(x.X[:, 2] < 5.1))\n        self.assertEqual(sum(col < 5.1), len(x))\n\n        f.oper = filter.FilterContinuous.LessEqual\n        x = filter.Values([f])(d)\n        self.assertTrue(np.all(x.X[:, 2] <= 5.1))\n        self.assertEqual(sum(col <= 5.1), len(x))\n\n        f.oper = filter.FilterContinuous.Greater\n        x = filter.Values([f])(d)\n        self.assertTrue(np.all(x.X[:, 2] > 5.1))\n        self.assertEqual(sum(col > 5.1), len(x))\n\n        f.oper = filter.FilterContinuous.GreaterEqual\n        x = filter.Values([f])(d)\n        self.assertTrue(np.all(x.X[:, 2] >= 5.1))\n        self.assertEqual(sum(col >= 5.1), len(x))\n\n        f.oper = filter.FilterContinuous.Outside\n        f.ref, f.max = 4.5, 5.1\n        x = filter.Values([f])(d)\n        for e in x:\n            self.assertTrue(e[2] < 4.5 or e[2] > 5.1)\n        self.assertEqual(sum((col < 4.5) + (col > 5.1)), len(x))\n\n        f.oper = filter.FilterContinuous.IsDefined\n        f.ref = f.max = None\n        x = filter.Values([f])(d)\n        self.assertEqual(len(x), len(d))\n\n        d[:30, v.petal_length] = Unknown\n        x = filter.Values([f])(d)\n        self.assertEqual(len(x), len(d) - 30)\n\n    def test_filter_value_continuous_args(self):\n        d = data.Table(\"iris\")\n        col = d.X[:, 2]\n        v = d.columns\n\n        f = filter.FilterContinuous(v.petal_length,\n                                    filter.FilterContinuous.Equal, ref=5.1)\n        x = filter.Values([f])(d)\n        self.assertTrue(np.all(x.X[:, 2] == 5.1))\n        self.assertEqual(sum(col == 5.1), len(x))\n\n        f = filter.FilterContinuous(2,\n                                    filter.FilterContinuous.Equal, ref=5.1)\n        self.assertTrue(np.all(x.X[:, 2] == 5.1))\n        self.assertEqual(sum(col == 5.1), len(x))\n\n        f = filter.FilterContinuous(\"petal length\",\n                                    filter.FilterContinuous.Equal, ref=5.1)\n        self.assertTrue(np.all(x.X[:, 2] == 5.1))\n        self.assertEqual(sum(col == 5.1), len(x))\n\n        f = filter.FilterContinuous(\"sepal length\",\n                                    filter.FilterContinuous.Equal, ref=5.1)\n        f.column = 2\n        self.assertTrue(np.all(x.X[:, 2] == 5.1))\n        self.assertEqual(sum(col == 5.1), len(x))\n\n        f = filter.FilterContinuous(\"sepal length\",\n                                    filter.FilterContinuous.Equal, ref=5.1)\n        f.column = v.petal_length\n        self.assertTrue(np.all(x.X[:, 2] == 5.1))\n        self.assertEqual(sum(col == 5.1), len(x))\n\n        f = filter.FilterContinuous(v.petal_length,\n                                    filter.FilterContinuous.Equal, ref=18)\n        f.ref = 5.1\n        x = filter.Values([f])(d)\n        self.assertTrue(np.all(x.X[:, 2] == 5.1))\n        self.assertEqual(sum(col == 5.1), len(x))\n\n        f = filter.FilterContinuous(v.petal_length,\n                                    filter.FilterContinuous.Equal, ref=18)\n        f.ref = 5.1\n        x = filter.Values([f])(d)\n        self.assertTrue(np.all(x.X[:, 2] == 5.1))\n        self.assertEqual(sum(col == 5.1), len(x))\n\n    def test_valueFilter_discrete(self):\n        d = data.Table(\"zoo\")\n\n        f = filter.FilterDiscrete(d.domain.class_var, values=[2, 3, 4])\n        for e in filter.Values([f])(d):\n            self.assertTrue(e.get_class() in [2, 3, 4])\n\n        f.values = [\"mammal\"]\n        for e in filter.Values([f])(d):\n            self.assertEqual(e.get_class(), \"mammal\")\n\n        f = filter.FilterDiscrete(d.domain.class_var, values=[2, \"mammal\"])\n        for e in filter.Values([f])(d):\n            self.assertTrue(e.get_class() in [2, \"mammal\"])\n\n        f = filter.FilterDiscrete(d.domain.class_var, values=[2, \"martian\"])\n        self.assertRaises(ValueError, d._filter_values, f)\n\n        f = filter.FilterDiscrete(d.domain.class_var, values=[2, data.Table])\n        self.assertRaises(TypeError, d._filter_values, f)\n\n        v = d.columns\n        f = filter.FilterDiscrete(v.hair, values=None)\n        self.assertEqual(len(filter.Values([f])(d)), len(d))\n\n        d[:5, v.hair] = Unknown\n        self.assertEqual(len(filter.Values([f])(d)), len(d) - 5)\n\n    def test_valueFilter_string_is_defined(self):\n        d = data.Table(\"test9.tab\")\n        f = filter.FilterString(-5, filter.FilterString.IsDefined)\n        x = filter.Values([f])(d)\n        self.assertEqual(len(x), 7)\n\n    def test_valueFilter_discrete_meta_is_defined(self):\n        d = data.Table(\"test9.tab\")\n        f = filter.FilterDiscrete(-4, None)\n        x = filter.Values([f])(d)\n        self.assertEqual(len(x), 8)\n\n    def test_valueFilter_string_case_sens(self):\n        d = data.Table(\"zoo\")\n        col = d[:, \"name\"].metas[:, 0]\n\n        f = filter.FilterString(\"name\",\n                                filter.FilterString.Equal, \"girl\")\n        x = filter.Values([f])(d)\n        self.assertEqual(len(x), 1)\n        self.assertEqual(x[0, \"name\"], \"girl\")\n        self.assertTrue(np.all(x.metas == \"girl\"))\n\n        f.oper = f.NotEqual\n        x = filter.Values([f])(d)\n        self.assertEqual(len(x), len(d) - 1)\n        self.assertTrue(np.all(x[:, \"name\"] != \"girl\"))\n\n        f.oper = f.Less\n        x = filter.Values([f])(d)\n        self.assertEqual(len(x), sum(col < \"girl\"))\n        self.assertTrue(np.all(x.metas < \"girl\"))\n\n        f.oper = f.LessEqual\n        x = filter.Values([f])(d)\n        self.assertEqual(len(x), sum(col <= \"girl\"))\n        self.assertTrue(np.all(x.metas <= \"girl\"))\n\n        f.oper = f.Greater\n        x = filter.Values([f])(d)\n        self.assertEqual(len(x), sum(col > \"girl\"))\n        self.assertTrue(np.all(x.metas > \"girl\"))\n\n        f.oper = f.GreaterEqual\n        x = filter.Values([f])(d)\n        self.assertEqual(len(x), sum(col >= \"girl\"))\n        self.assertTrue(np.all(x.metas >= \"girl\"))\n\n        f.oper = f.Between\n        f.max = \"lion\"\n        x = filter.Values([f])(d)\n        self.assertEqual(len(x), sum((col >= \"girl\") * (col <= \"lion\")))\n        self.assertTrue(np.all(x.metas >= \"girl\"))\n        self.assertTrue(np.all(x.metas <= \"lion\"))\n\n        f.oper = f.Outside\n        x = filter.Values([f])(d)\n        self.assertEqual(len(x), sum(col < \"girl\") + sum(col > \"lion\"))\n        self.assertTrue(np.all((x.metas < \"girl\") + (x.metas > \"lion\")))\n\n        f.oper = f.Contains\n        f.ref = \"ea\"\n        x = filter.Values([f])(d)\n        for e in x:\n            self.assertTrue(\"ea\" in e[\"name\"])\n        self.assertEqual(len(x), len([e for e in col if \"ea\" in e]))\n\n        f.oper = f.StartsWith\n        f.ref = \"sea\"\n        x = filter.Values([f])(d)\n        for e in x:\n            self.assertTrue(str(e[\"name\"]).startswith(\"sea\"))\n        self.assertEqual(len(x), len([e for e in col if e.startswith(\"sea\")]))\n\n        f.oper = f.EndsWith\n        f.ref = \"ion\"\n        x = filter.Values([f])(d)\n        for e in x:\n            self.assertTrue(str(e[\"name\"]).endswith(\"ion\"))\n        self.assertEqual(len(x), len([e for e in col if e.endswith(\"ion\")]))\n\n    def test_valueFilter_string_case_insens(self):\n        d = data.Table(\"zoo\")\n        d[d[:, \"name\"].metas[:, 0] == \"girl\", \"name\"] = \"GIrl\"\n\n        col = d[:, \"name\"].metas[:, 0]\n\n        f = filter.FilterString(\"name\",\n                                filter.FilterString.Equal, \"giRL\")\n        f.case_sensitive = False\n        x = filter.Values([f])(d)\n        self.assertEqual(len(x), 1)\n        self.assertEqual(x[0, \"name\"], \"GIrl\")\n        self.assertTrue(np.all(x.metas == \"GIrl\"))\n\n        f.oper = f.NotEqual\n        x = filter.Values([f])(d)\n        self.assertEqual(len(x), len(d) - 1)\n        self.assertTrue(np.all(x[:, \"name\"] != \"GIrl\"))\n\n        f.oper = f.Less\n        f.ref = \"CHiCKEN\"\n        x = filter.Values([f])(d)\n        self.assertEqual(len(x), sum(col < \"chicken\") - 1)  # girl!\n        self.assertTrue(np.all(x.metas < \"chicken\"))\n\n        f.oper = f.LessEqual\n        x = filter.Values([f])(d)\n        self.assertEqual(len(x), sum(col <= \"chicken\") - 1)\n        self.assertTrue(np.all(x.metas <= \"chicken\"))\n\n        f.oper = f.Greater\n        x = filter.Values([f])(d)\n        self.assertEqual(len(x), sum(col > \"chicken\") + 1)\n        for e in x:\n            self.assertGreater(str(e[\"name\"]).lower(), \"chicken\")\n\n        f.oper = f.GreaterEqual\n        x = filter.Values([f])(d)\n        self.assertEqual(len(x), sum(col >= \"chicken\") + 1)\n        for e in x:\n            self.assertGreaterEqual(str(e[\"name\"]).lower(), \"chicken\")\n\n        f.oper = f.Between\n        f.max = \"liOn\"\n        x = filter.Values([f])(d)\n        self.assertEqual(len(x), sum((col >= \"chicken\") * (col <= \"lion\")) + 1)\n        for e in x:\n            self.assertTrue(\"chicken\" <= str(e[\"name\"]).lower() <= \"lion\")\n\n        f.oper = f.Outside\n        x = filter.Values([f])(d)\n        self.assertEqual(len(x), sum(col < \"chicken\") + sum(col > \"lion\") - 1)\n        self.assertTrue(np.all((x.metas < \"chicken\") + (x.metas > \"lion\")))\n\n        f.oper = f.Contains\n        f.ref = \"iR\"\n        x = filter.Values([f])(d)\n        for e in x:\n            self.assertTrue(\"ir\" in str(e[\"name\"]).lower())\n        self.assertEqual(len(x), len([e for e in col if \"ir\" in e]) + 1)\n\n        f.oper = f.StartsWith\n        f.ref = \"GI\"\n        x = filter.Values([f])(d)\n        for e in x:\n            self.assertTrue(str(e[\"name\"]).lower().startswith(\"gi\"))\n        self.assertEqual(len(x),\n                         len([e for e in col if e.lower().startswith(\"gi\")]))\n\n        f.oper = f.EndsWith\n        f.ref = \"ion\"\n        x = filter.Values([f])(d)\n        for e in x:\n            self.assertTrue(str(e[\"name\"]).endswith(\"ion\"))\n            self.assertTrue(str(e[\"name\"]).endswith(\"ion\"))\n        self.assertEqual(len(x), len([e for e in col if e.endswith(\"ion\")]))\n\n    def test_valueFilter_regex(self):\n        d = data.Table(\"zoo\")\n        f = filter.FilterRegex(d.domain['name'], '^c...$')\n        x = filter.Values([f])(d)\n        self.assertEqual(len(x), 7)\n\n    def test_valueFilter_stringList(self):\n        data = Table(\"zoo\")\n        var = data.domain[\"name\"]\n\n        fs = filter.FilterStringList\n        filters = [\n            (([\"swan\", \"tuna\", \"wasp\"], True), dict(rows=3)),\n            (([\"swan\", \"tuna\", \"wasp\"], False), dict(rows=3)),\n            (([\"WoRm\", \"TOad\", \"vOLe\"], True), dict(rows=0)),\n            (([\"WoRm\", \"TOad\", \"vOLe\"], False), dict(rows=3)),\n        ]\n\n        for args, expected in filters:\n            f = fs(var, *args)\n            filtered_data = filter.Values([f])(data)\n            self.assertEqual(len(filtered_data), expected[\"rows\"],\n                             \"{} returned wrong number of rows\".format(args))\n\n    def test_table_dtypes(self):\n        table = data.Table(\"iris\")\n        metas = np.hstack((table.metas, table.Y.reshape(len(table), 1)))\n        attributes_metas = table.domain.metas + table.domain.class_vars\n        domain_metas = data.Domain(table.domain.attributes,\n                                   table.domain.class_vars,\n                                   attributes_metas)\n        table_metas = data.Table(domain_metas, table.X, table.Y, metas)\n        new_table = data.Table(data.Domain(table_metas.domain.metas,\n                                           table_metas.domain.metas,\n                                           table_metas.domain.metas),\n                               table_metas)\n        self.assertEqual(new_table.X.dtype, np.float64)\n        self.assertEqual(new_table.Y.dtype, np.float64)\n        self.assertEqual(new_table.metas.dtype, np.float64)\n\n    def test_attributes(self):\n        table = data.Table(\"iris\")\n        table.attributes = {1: \"test\"}\n        table2 = table[:4]\n        self.assertEqual(table2.attributes[1], \"test\")\n        table2.attributes[1] = \"modified\"\n        self.assertEqual(table.attributes[1], \"modified\")\n\n    # TODO Test conjunctions and disjunctions of conditions\n\n    def test_is_sparse(self):\n        table = data.Table(\"iris\")\n        self.assertFalse(table.is_sparse())\n\n        table.X = sp.csr_matrix(table.X)\n        self.assertTrue(table.is_sparse())\n\n    def test_repr_sparse_with_one_row(self):\n        table = data.Table(\"iris\")[:1]\n        table.X = sp.csr_matrix(table.X)\n        repr(table)     # make sure repr does not crash\n\n\ndef column_sizes(table):\n    return (len(table.domain.attributes),\n            len(table.domain.class_vars),\n            len(table.domain.metas))\n\n\nclass TableTests(unittest.TestCase):\n    attributes = [\"Feature %i\" % i for i in range(10)]\n    class_vars = [\"Class %i\" % i for i in range(1)]\n    metas = [\"Meta %i\" % i for i in range(5)]\n    nrows = 10\n    row_indices = (1, 5, 7, 9)\n\n    data = np.random.random((nrows, len(attributes)))\n    class_data = np.random.random((nrows, len(class_vars)))\n    meta_data = np.random.random((nrows, len(metas)))\n    weight_data = np.random.random((nrows, 1))\n\n    def setUp(self):\n        self.data = np.random.random((self.nrows, len(self.attributes)))\n        self.class_data = np.random.random((self.nrows, len(self.class_vars)))\n        if len(self.class_vars) == 1:\n            self.class_data = self.class_data.flatten()\n        self.meta_data = np.random.randint(0, 5, (self.nrows, len(self.metas))\n                                          ).astype(object)\n        self.weight_data = np.random.random((self.nrows, 1))\n\n    def mock_domain(self, with_classes=False, with_metas=False):\n        attributes = self.attributes\n        class_vars = self.class_vars if with_classes else []\n        metas = self.metas if with_metas else []\n        variables = attributes + class_vars\n        return MagicMock(data.Domain,\n                         attributes=attributes,\n                         class_vars=class_vars,\n                         metas=metas,\n                         variables=variables)\n\n    def create_domain(self, attributes=(), classes=(), metas=()):\n        attr_vars = [data.ContinuousVariable(name=a) if isinstance(a, str)\n                     else a for a in attributes]\n        class_vars = [data.ContinuousVariable(name=c) if isinstance(c, str)\n                      else c for c in classes]\n        meta_vars = [data.DiscreteVariable(name=m, values=map(str, range(5)))\n                     if isinstance(m, str) else m for m in metas]\n\n        domain = data.Domain(attr_vars, class_vars, meta_vars)\n        return domain\n\n\nclass CreateEmptyTable(TableTests):\n    def test_calling_new_with_no_parameters_constructs_a_new_instance(self):\n        table = data.Table()\n        self.assertIsInstance(table, data.Table)\n\n    def test_table_has_file(self):\n        table = data.Table()\n        self.assertIsNone(table.__file__)\n\n\nclass CreateTableWithFilename(TableTests):\n    filename = \"data.tab\"\n\n    @patch(\"os.path.exists\", Mock(return_value=True))\n    def test_read_data_calls_reader(self):\n        table_mock = Mock(data.Table)\n        reader_instance = Mock(read=Mock(return_value=table_mock))\n        reader_mock = Mock(return_value=reader_instance)\n\n        with patch.dict(data.io.FileFormat.readers,\n                        {'.xlsx': reader_mock}):\n            table = data.Table.from_file(\"test.xlsx\")\n\n        reader_mock.assert_called_with(\"test.xlsx\")\n        reader_instance.read.assert_called_with()\n        self.assertEqual(table, table_mock)\n\n    @patch(\"os.path.exists\", Mock(return_value=False))\n    def test_raises_error_if_file_does_not_exist(self):\n        with self.assertRaises(IOError):\n            data.Table.from_file(self.filename)\n\n    @patch(\"os.path.exists\", Mock(return_value=True))\n    def test_raises_error_if_file_has_unknown_extension(self):\n        with self.assertRaises(IOError):\n            data.Table.from_file(\"file.invalid_extension\")\n\n    @patch(\"Orange.data.table.Table.from_file\")\n    def test_calling_new_with_string_argument_calls_read_data(self, read_data):\n        data.Table(self.filename)\n\n        read_data.assert_called_with(self.filename)\n\n    @patch(\"Orange.data.table.Table.from_file\")\n    def test_calling_new_with_keyword_argument_filename_calls_read_data(\n            self, read_data):\n        data.Table(filename=self.filename)\n\n        read_data.assert_called_with(self.filename)\n\n\nclass CreateTableWithUrl(TableTests):\n    def test_url_no_scheme(self):\n\n        class SkipRest(Exception):\n            pass\n\n        mock_urlopen = Mock(side_effect=SkipRest())\n        url = 'www.foo.bar/xx.csv'\n\n        with patch('Orange.data.io.UrlReader.urlopen', mock_urlopen):\n            try:\n                Table.from_url(url)\n            except SkipRest:\n                pass\n\n        mock_urlopen.assert_called_once_with('http://' + url)\n\n    class _MockUrlOpen(MagicMock):\n        headers = {'content-disposition': 'attachment; filename=\"Something-FormResponses.tsv\"; '\n                                          'filename*=UTF-8''Something%20%28Responses%29.tsv'}\n        def __enter__(self):\n            return self\n\n        def __exit__(self, *args, **kwargs):\n            pass\n\n        def read(self):\n            return b'''\\\na\\tb\\tc\n1\\t2\\t3\n2\\t3\\t4'''\n\n    urlopen = _MockUrlOpen()\n\n    @patch('Orange.data.io.urlopen', urlopen)\n    def test_trimmed_urls(self):\n        for url in ('https://docs.google.com/spreadsheets/d/ABCD/edit',\n                    'https://www.dropbox.com/s/ABCD/filename.csv'):\n            self._MockUrlOpen.url = url\n            d = data.Table(url)\n            request = self.urlopen.call_args[0][0]\n            self.assertNotEqual(url, request.full_url)\n            self.assertIn('Mozilla/5.0', request.headers.get('User-agent', ''))\n            self.assertEqual(len(d), 2)\n            self.assertEqual(d.name, 'Something-FormResponses')\n\n\nclass CreateTableWithDomain(TableTests):\n    def test_creates_an_empty_table_with_given_domain(self):\n        domain = self.mock_domain()\n        table = data.Table.from_domain(domain)\n\n        self.assertEqual(table.domain, domain)\n\n    def test_creates_zero_filled_rows_in_X_if_domain_contains_attributes(self):\n        domain = self.mock_domain()\n        table = data.Table.from_domain(domain, self.nrows)\n\n        self.assertEqual(table.X.shape, (self.nrows, len(domain.attributes)))\n        self.assertFalse(table.X.any())\n\n    def test_creates_zero_filled_rows_in_Y_if_domain_contains_class_vars(self):\n        domain = self.mock_domain(with_classes=True)\n        table = data.Table.from_domain(domain, self.nrows)\n\n        if len(domain.class_vars) != 1:\n            self.assertEqual(table.Y.shape,\n                             (self.nrows, len(domain.class_vars)))\n        else:\n            self.assertEqual(table.Y.shape, (self.nrows,))\n        self.assertFalse(table.Y.any())\n\n    def test_creates_zero_filled_rows_in_metas_if_domain_contains_metas(self):\n        domain = self.mock_domain(with_metas=True)\n        table = data.Table.from_domain(domain, self.nrows)\n\n        self.assertEqual(table.metas.shape, (self.nrows, len(domain.metas)))\n        self.assertFalse(table.metas.any())\n\n    def test_creates_weights_if_weights_are_true(self):\n        domain = self.mock_domain()\n        table = data.Table.from_domain(domain, self.nrows, True)\n\n        self.assertEqual(table.W.shape, (self.nrows, ))\n\n    def test_does_not_create_weights_if_weights_are_false(self):\n        domain = self.mock_domain()\n        table = data.Table.from_domain(domain, self.nrows, False)\n\n        self.assertEqual(table.W.shape, (self.nrows, 0))\n\n    @patch(\"Orange.data.table.Table.from_domain\")\n    def test_calling_new_with_domain_calls_new_from_domain(\n            self, new_from_domain):\n        domain = self.mock_domain()\n        data.Table(domain)\n\n        new_from_domain.assert_called_with(domain)\n\n\nclass CreateTableWithData(TableTests):\n    def test_creates_a_table_with_given_X(self):\n        # from numpy\n        table = data.Table(np.array(self.data))\n        self.assertIsInstance(table.domain, data.Domain)\n        np.testing.assert_almost_equal(table.X, self.data)\n\n        # from list\n        table = data.Table(list(self.data))\n        self.assertIsInstance(table.domain, data.Domain)\n        np.testing.assert_almost_equal(table.X, self.data)\n\n        # from tuple\n        table = data.Table(tuple(self.data))\n        self.assertIsInstance(table.domain, data.Domain)\n        np.testing.assert_almost_equal(table.X, self.data)\n\n    def test_creates_a_table_from_domain_and_list(self):\n        domain = data.Domain([data.DiscreteVariable(name=\"a\", values=\"mf\"),\n                              data.ContinuousVariable(name=\"b\")],\n                             data.DiscreteVariable(name=\"y\", values=\"abc\"))\n        table = data.Table(domain, [[0, 1, 2],\n                                    [1, 2, \"?\"],\n                                    [\"m\", 3, \"a\"],\n                                    [\"?\", \"?\", \"c\"]])\n        self.assertIs(table.domain, domain)\n        np.testing.assert_almost_equal(\n            table.X, np.array([[0, 1], [1, 2], [0, 3], [np.nan, np.nan]]))\n        np.testing.assert_almost_equal(table.Y, np.array([2, np.nan, 0, 2]))\n\n    def test_creates_a_table_from_domain_and_list_and_weights(self):\n        domain = data.Domain([data.DiscreteVariable(name=\"a\", values=\"mf\"),\n                              data.ContinuousVariable(name=\"b\")],\n                             data.DiscreteVariable(name=\"y\", values=\"abc\"))\n        table = data.Table(domain, [[0, 1, 2],\n                                    [1, 2, \"?\"],\n                                    [\"m\", 3, \"a\"],\n                                    [\"?\", \"?\", \"c\"]], [1, 2, 3, 4])\n        self.assertIs(table.domain, domain)\n        np.testing.assert_almost_equal(\n            table.X, np.array([[0, 1], [1, 2], [0, 3], [np.nan, np.nan]]))\n        np.testing.assert_almost_equal(table.Y, np.array([2, np.nan, 0, 2]))\n        np.testing.assert_almost_equal(table.W, np.array([1, 2, 3, 4]))\n\n    def test_creates_a_table_from_domain_and_list_and_metas(self):\n        metas = [data.DiscreteVariable(\"Meta 1\", values=\"XYZ\"),\n                 data.ContinuousVariable(\"Meta 2\"),\n                 data.StringVariable(\"Meta 3\")]\n        domain = data.Domain([data.DiscreteVariable(name=\"a\", values=\"mf\"),\n                              data.ContinuousVariable(name=\"b\")],\n                             data.DiscreteVariable(name=\"y\", values=\"abc\"),\n                             metas=metas)\n        table = data.Table(domain, [[0, 1, 2, \"X\", 2, \"bb\"],\n                                    [1, 2, \"?\", \"Y\", 1, \"aa\"],\n                                    [\"m\", 3, \"a\", \"Z\", 3, \"bb\"],\n                                    [\"?\", \"?\", \"c\", \"X\", 1, \"aa\"]])\n        self.assertIs(table.domain, domain)\n        np.testing.assert_almost_equal(\n            table.X, np.array([[0, 1], [1, 2], [0, 3], [np.nan, np.nan]]))\n        np.testing.assert_almost_equal(table.Y, np.array([2, np.nan, 0, 2]))\n        np.testing.assert_array_equal(table.metas,\n                                      np.array([[0, 2., \"bb\"],\n                                                [1, 1., \"aa\"],\n                                                [2, 3., \"bb\"],\n                                                [0, 1., \"aa\"]],\n                                               dtype=object))\n\n    def test_creates_a_table_from_list_of_instances(self):\n        table = data.Table('iris')\n        new_table = data.Table(table.domain, [d for d in table])\n        self.assertIs(table.domain, new_table.domain)\n        np.testing.assert_almost_equal(table.X, new_table.X)\n        np.testing.assert_almost_equal(table.Y, new_table.Y)\n        np.testing.assert_almost_equal(table.W, new_table.W)\n        self.assertEqual(table.domain, new_table.domain)\n        np.testing.assert_array_equal(table.metas, new_table.metas)\n\n    def test_creates_a_table_from_list_of_instances_with_metas(self):\n        table = data.Table('zoo')\n        new_table = data.Table(table.domain, [d for d in table])\n        self.assertIs(table.domain, new_table.domain)\n        np.testing.assert_almost_equal(table.X, new_table.X)\n        np.testing.assert_almost_equal(table.Y, new_table.Y)\n        np.testing.assert_almost_equal(table.W, new_table.W)\n        self.assertEqual(table.domain, new_table.domain)\n        np.testing.assert_array_equal(table.metas, new_table.metas)\n\n    def test_creates_a_table_with_domain_and_given_X(self):\n        domain = self.mock_domain()\n\n        table = data.Table(domain, self.data)\n        self.assertIsInstance(table.domain, data.Domain)\n        self.assertEqual(table.domain, domain)\n        np.testing.assert_almost_equal(table.X, self.data)\n\n    def test_creates_a_table_with_given_X_and_Y(self):\n        table = data.Table(self.data, self.class_data)\n\n        self.assertIsInstance(table.domain, data.Domain)\n        np.testing.assert_almost_equal(table.X, self.data)\n        np.testing.assert_almost_equal(table.Y, self.class_data)\n\n    def test_creates_a_table_with_given_X_Y_and_metas(self):\n        table = data.Table(self.data, self.class_data, self.meta_data)\n\n        self.assertIsInstance(table.domain, data.Domain)\n        np.testing.assert_almost_equal(table.X, self.data)\n        np.testing.assert_almost_equal(table.Y, self.class_data)\n        np.testing.assert_almost_equal(table.metas, self.meta_data)\n\n    def test_creates_a_discrete_class_if_Y_has_few_distinct_values(self):\n        Y = np.array([float(np.random.randint(0, 2)) for i in self.data])\n        table = data.Table(self.data, Y, self.meta_data)\n\n        np.testing.assert_almost_equal(table.Y, Y)\n        self.assertIsInstance(table.domain.class_vars[0],\n                              data.DiscreteVariable)\n        self.assertEqual(table.domain.class_vars[0].values, [\"v1\", \"v2\"])\n\n    def test_creates_a_table_with_given_domain(self):\n        domain = self.mock_domain()\n        table = data.Table.from_numpy(domain, self.data)\n\n        self.assertEqual(table.domain, domain)\n\n    def test_sets_Y_if_given(self):\n        domain = self.mock_domain(with_classes=True)\n        table = data.Table.from_numpy(domain, self.data, self.class_data)\n\n        np.testing.assert_almost_equal(table.Y, self.class_data)\n\n    def test_sets_metas_if_given(self):\n        domain = self.mock_domain(with_metas=True)\n        table = data.Table.from_numpy(domain, self.data, metas=self.meta_data)\n\n        np.testing.assert_almost_equal(table.metas, self.meta_data)\n\n    def test_sets_weights_if_given(self):\n        domain = self.mock_domain()\n        table = data.Table.from_numpy(domain, self.data, W=self.weight_data)\n\n        np.testing.assert_equal(table.W.shape, (len(self.data), ))\n        np.testing.assert_almost_equal(table.W.flatten(),\n                                       self.weight_data.flatten())\n\n    def test_splits_X_and_Y_if_given_in_same_array(self):\n        joined_data = np.column_stack((self.data, self.class_data))\n        domain = self.mock_domain(with_classes=True)\n        table = data.Table.from_numpy(domain, joined_data)\n\n        np.testing.assert_almost_equal(table.X, self.data)\n        np.testing.assert_almost_equal(table.Y, self.class_data)\n\n    def test_initializes_Y_metas_and_W_if_not_given(self):\n        domain = self.mock_domain()\n        table = data.Table.from_numpy(domain, self.data)\n\n        self.assertEqual(table.Y.shape, (self.nrows, len(domain.class_vars)))\n        self.assertEqual(table.metas.shape, (self.nrows, len(domain.metas)))\n        self.assertEqual(table.W.shape, (self.nrows, 0))\n\n    def test_raises_error_if_columns_in_domain_and_data_do_not_match(self):\n        domain = self.mock_domain(with_classes=True, with_metas=True)\n        ones = np.zeros((self.nrows, 1))\n\n        with self.assertRaises(ValueError):\n            data_ = np.hstack((self.data, ones))\n            data.Table.from_numpy(domain, data_, self.class_data,\n                                  self.meta_data)\n\n        with self.assertRaises(ValueError):\n            classes_ = np.hstack((self.class_data, ones))\n            data.Table.from_numpy(domain, self.data, classes_,\n                                  self.meta_data)\n\n        with self.assertRaises(ValueError):\n            metas_ = np.hstack((self.meta_data, ones))\n            data.Table.from_numpy(domain, self.data, self.class_data,\n                                  metas_)\n\n    def test_raises_error_if_lengths_of_data_do_not_match(self):\n        domain = self.mock_domain(with_classes=True, with_metas=True)\n\n        with self.assertRaises(ValueError):\n            data_ = np.vstack((self.data, np.zeros((1, len(self.attributes)))))\n            data.Table(domain, data_, self.class_data, self.meta_data)\n\n        with self.assertRaises(ValueError):\n            class_data_ = np.vstack((self.class_data,\n                                     np.zeros((1, len(self.class_vars)))))\n            data.Table(domain, self.data, class_data_, self.meta_data)\n\n        with self.assertRaises(ValueError):\n            meta_data_ = np.vstack((self.meta_data,\n                                    np.zeros((1, len(self.metas)))))\n            data.Table(domain, self.data, self.class_data, meta_data_)\n\n    @patch(\"Orange.data.table.Table.from_numpy\")\n    def test_calling_new_with_domain_and_numpy_arrays_calls_new_from_numpy(\n            self, new_from_numpy):\n        domain = self.mock_domain()\n        data.Table(domain, self.data)\n        new_from_numpy.assert_called_with(domain, self.data)\n\n        domain = self.mock_domain(with_classes=True)\n        data.Table(domain, self.data, self.class_data)\n        new_from_numpy.assert_called_with(domain, self.data, self.class_data)\n\n        domain = self.mock_domain(with_classes=True, with_metas=True)\n        data.Table(domain, self.data, self.class_data, self.meta_data)\n        new_from_numpy.assert_called_with(\n            domain, self.data, self.class_data, self.meta_data)\n\n        data.Table(domain, self.data, self.class_data,\n                   self.meta_data, self.weight_data)\n        new_from_numpy.assert_called_with(domain, self.data, self.class_data,\n                                          self.meta_data, self.weight_data)\n\n    def test_from_numpy_reconstructable(self):\n        def assert_equal(T1, T2):\n            np.testing.assert_array_equal(T1.X, T2.X)\n            np.testing.assert_array_equal(T1.Y, T2.Y)\n            np.testing.assert_array_equal(T1.metas, T2.metas)\n            np.testing.assert_array_equal(T1.W, T2.W)\n\n        nullcol = np.empty((self.nrows, 0))\n        domain = self.create_domain(self.attributes)\n        table = data.Table(domain, self.data)\n\n        table_1 = data.Table.from_numpy(\n            domain, table.X, table.Y, table.metas, table.W)\n        assert_equal(table, table_1)\n\n        domain = self.create_domain(classes=self.class_vars)\n        table = data.Table(domain, nullcol, self.class_data)\n\n        table_1 = data.Table.from_numpy(\n            domain, table.X, table.Y, table.metas, table.W)\n        assert_equal(table, table_1)\n\n        domain = self.create_domain(metas=self.metas)\n        table = data.Table(domain, nullcol, nullcol, self.meta_data)\n\n        table_1 = data.Table.from_numpy(\n            domain, table.X, table.Y, table.metas, table.W)\n        assert_equal(table, table_1)\n\n\nclass CreateTableWithDomainAndTable(TableTests):\n    interesting_slices = [\n        slice(0, 0),  # [0:0] - empty slice\n        slice(1),  # [:1]  - only first element\n        slice(1, None),  # [1:]  - all but first\n        slice(-1, None),  # [-1:] - only last element\n        slice(-1),  # [:-1] - all but last\n        slice(None),  # [:]   - all elements\n        slice(None, None, 2),  # [::2] - even elements\n        slice(None, None, -1),  # [::-1]- all elements reversed\n    ]\n\n    row_indices = [1, 5, 6, 7]\n\n    def setUp(self):\n        self.domain = self.create_domain(\n            self.attributes, self.class_vars, self.metas)\n        self.table = data.Table(\n            self.domain, self.data, self.class_data, self.meta_data)\n\n    def test_creates_table_with_given_domain(self):\n        new_table = data.Table.from_table(self.table.domain, self.table)\n\n        self.assertIsInstance(new_table, data.Table)\n        self.assertIsNot(self.table, new_table)\n        self.assertEqual(new_table.domain, self.domain)\n\n    def test_transform(self):\n        class MyTableClass(data.Table):\n            pass\n\n        table = MyTableClass.from_table(self.table.domain, self.table)\n        domain = table.domain\n        attr = ContinuousVariable(\"x\")\n        new_domain = data.Domain(list(domain.attributes) + [attr], None)\n        new_table = table.transform(new_domain)\n\n        self.assertIsInstance(new_table, MyTableClass)\n        self.assertIsNot(table, new_table)\n        self.assertIs(new_table.domain, new_domain)\n\n    def test_transform_same_domain(self):\n        iris = data.Table(\"iris\")\n        new_domain = copy.copy(iris.domain)\n        new_data = iris.transform(new_domain)\n        self.assertIs(new_data.domain, new_domain)\n\n    def test_can_copy_table(self):\n        new_table = data.Table.from_table(self.domain, self.table)\n        self.assert_table_with_filter_matches(new_table, self.table)\n\n    def test_can_filter_rows_with_list(self):\n        for indices in ([0], [1, 5, 6, 7]):\n            new_table = data.Table.from_table(\n                self.domain, self.table, row_indices=indices)\n            self.assert_table_with_filter_matches(\n                new_table, self.table, rows=indices)\n\n    def test_can_filter_row_with_slice(self):\n        for slice_ in self.interesting_slices:\n            new_table = data.Table.from_table(\n                self.domain, self.table, row_indices=slice_)\n            self.assert_table_with_filter_matches(\n                new_table, self.table, rows=slice_)\n\n    def test_can_use_attributes_as_new_columns(self):\n        a, _, _ = column_sizes(self.table)\n        order = [random.randrange(a) for _ in self.domain.attributes]\n        new_attributes = [self.domain.attributes[i] for i in order]\n        new_domain = self.create_domain(\n            new_attributes, new_attributes, new_attributes)\n        new_table = data.Table.from_table(new_domain, self.table)\n\n        self.assert_table_with_filter_matches(\n            new_table, self.table, xcols=order, ycols=order, mcols=order)\n\n    def test_can_use_class_vars_as_new_columns(self):\n        a, c, _ = column_sizes(self.table)\n        order = [random.randrange(a, a + c) for _ in self.domain.class_vars]\n        new_classes = [self.domain.class_vars[i - a] for i in order]\n        new_domain = self.create_domain(new_classes, new_classes, new_classes)\n        new_table = data.Table.from_table(new_domain, self.table)\n\n        self.assert_table_with_filter_matches(\n            new_table, self.table, xcols=order, ycols=order, mcols=order)\n\n    def test_can_use_metas_as_new_columns(self):\n        _, _, m = column_sizes(self.table)\n        order = [random.randrange(-m + 1, 0) for _ in self.domain.metas]\n        new_metas = [self.domain.metas[::-1][i] for i in order]\n        new_domain = self.create_domain(new_metas, new_metas, new_metas)\n        new_table = data.Table.from_table(new_domain, self.table)\n\n        self.assert_table_with_filter_matches(\n            new_table, self.table, xcols=order, ycols=order, mcols=order)\n\n    def test_can_use_combination_of_all_as_new_columns(self):\n        a, c, m = column_sizes(self.table)\n        order = ([random.randrange(a) for _ in self.domain.attributes] +\n                 [random.randrange(a, a + c) for _ in self.domain.class_vars] +\n                 [random.randrange(-m + 1, 0) for _ in self.domain.metas])\n        random.shuffle(order)\n        vars = list(self.domain.variables) + list(self.domain.metas[::-1])\n        vars = [vars[i] for i in order]\n\n        new_domain = self.create_domain(vars, vars, vars)\n        new_table = data.Table.from_table(new_domain, self.table)\n        self.assert_table_with_filter_matches(\n            new_table, self.table, xcols=order, ycols=order, mcols=order)\n\n    def test_creates_table_with_given_domain_and_row_filter(self):\n        a, c, m = column_sizes(self.table)\n        order = ([random.randrange(a) for _ in self.domain.attributes] +\n                 [random.randrange(a, a + c) for _ in self.domain.class_vars] +\n                 [random.randrange(-m + 1, 0) for _ in self.domain.metas])\n        random.shuffle(order)\n        vars = list(self.domain.variables) + list(self.domain.metas[::-1])\n        vars = [vars[i] for i in order]\n\n        new_domain = self.create_domain(vars, vars, vars)\n        new_table = data.Table.from_table(new_domain, self.table, [0])\n        self.assert_table_with_filter_matches(\n            new_table, self.table[:1], xcols=order, ycols=order, mcols=order)\n\n        new_table = data.Table.from_table(new_domain, self.table, [2, 1, 0])\n        self.assert_table_with_filter_matches(\n            new_table, self.table[2::-1], xcols=order, ycols=order, mcols=order)\n\n        new_table = data.Table.from_table(new_domain, self.table, [])\n        self.assert_table_with_filter_matches(\n            new_table, self.table[:0], xcols=order, ycols=order, mcols=order)\n\n    def test_from_table_sparse_move_some_to_empty_metas(self):\n        iris = data.Table(\"iris\").to_sparse()\n        new_domain = data.domain.Domain(\n            iris.domain.attributes[:2], iris.domain.class_vars,\n            iris.domain.attributes[2:], source=iris.domain)\n        new_iris = iris.transform(new_domain)\n\n        self.assertTrue(sp.issparse(new_iris.X))\n        self.assertTrue(sp.issparse(new_iris.metas))\n        self.assertEqual(new_iris.X.shape, (len(iris), 2))\n        self.assertEqual(new_iris.metas.shape, (len(iris), 2))\n\n        # move back\n        back_iris = new_iris.transform(iris.domain)\n        self.assertEqual(back_iris.domain, iris.domain)\n        self.assertTrue(sp.issparse(back_iris.X))\n        self.assertFalse(sp.issparse(back_iris.metas))\n        self.assertEqual(back_iris.X.shape, iris.X.shape)\n        self.assertEqual(back_iris.metas.shape, iris.metas.shape)\n\n    def test_from_table_sparse_move_all_to_empty_metas(self):\n        iris = data.Table(\"iris\").to_sparse()\n        new_domain = data.domain.Domain(\n            [], iris.domain.class_vars, iris.domain.attributes,\n            source=iris.domain)\n        new_iris = iris.transform(new_domain)\n\n        self.assertFalse(sp.issparse(new_iris.X))\n        self.assertTrue(sp.issparse(new_iris.metas))\n        self.assertEqual(new_iris.X.shape, (len(iris), 0))\n        self.assertEqual(new_iris.metas.shape, (len(iris), 4))\n\n        # move back\n        back_iris = new_iris.transform(iris.domain)\n        self.assertEqual(back_iris.domain, iris.domain)\n        self.assertTrue(sp.issparse(back_iris.X))\n        self.assertFalse(sp.issparse(back_iris.metas))\n        self.assertEqual(back_iris.X.shape, iris.X.shape)\n        self.assertEqual(back_iris.metas.shape, iris.metas.shape)\n\n    def test_from_table_sparse_move_to_nonempty_metas(self):\n        brown = data.Table(\"brown-selected\").to_sparse()\n        n_attr = len(brown.domain.attributes)\n        n_metas = len(brown.domain.metas)\n        new_domain = data.domain.Domain(\n            brown.domain.attributes[:-10],\n            brown.domain.class_vars,\n            brown.domain.attributes[-10:] + brown.domain.metas,\n            source=brown.domain)\n        new_brown = data.Table.from_table(new_domain, brown)\n\n        self.assertTrue(sp.issparse(new_brown.X))\n        self.assertFalse(sp.issparse(new_brown.metas))\n        self.assertEqual(new_brown.X.shape, (len(new_brown), n_attr-10))\n        self.assertEqual(new_brown.metas.shape, (len(new_brown), n_metas+10))\n\n        # move back\n        back_brown = data.Table.from_table(brown.domain, new_brown)\n        self.assertEqual(brown.domain, back_brown.domain)\n        self.assertTrue(sp.issparse(back_brown.X))\n        self.assertFalse(sp.issparse(back_brown.metas))\n        self.assertEqual(back_brown.X.shape, brown.X.shape)\n        self.assertEqual(back_brown.metas.shape, brown.metas.shape)\n\n    def assert_table_with_filter_matches(\n            self, new_table, old_table,\n            rows=..., xcols=..., ycols=..., mcols=...):\n        a, c, m = column_sizes(old_table)\n        xcols = slice(a) if xcols is Ellipsis else xcols\n        ycols = slice(a, a + c) if ycols is Ellipsis else ycols\n        mcols = slice(None, -m - 1, -1) if mcols is Ellipsis else mcols\n\n        # Indexing used by convert_domain uses positive indices for variables\n        # and classes (classes come after attributes) and negative indices for\n        # meta features. This is equivalent to ordinary indexing in a magic\n        # table below.\n        magic = np.hstack((old_table.X, old_table.Y[:, None],\n                           old_table.metas[:, ::-1]))\n        np.testing.assert_almost_equal(new_table.X, magic[rows, xcols])\n        Y = magic[rows, ycols]\n        if Y.shape[1] == 1:\n            Y = Y.flatten()\n        np.testing.assert_almost_equal(new_table.Y, Y)\n        np.testing.assert_almost_equal(new_table.metas, magic[rows, mcols])\n        np.testing.assert_almost_equal(new_table.W, old_table.W[rows])\n\n\ndef isspecial(s):\n    return isinstance(s, slice) or s is Ellipsis\n\n\ndef split_columns(indices, t):\n    a, c, m = column_sizes(t)\n    if indices is ...:\n        return slice(a), slice(c), slice(m)\n    elif isinstance(indices, slice):\n        return indices, slice(0, 0), slice(0, 0)\n    elif not isinstance(indices, list) and not isinstance(indices, tuple):\n        indices = [indices]\n    return (\n        [t.domain.index(x)\n         for x in indices if 0 <= t.domain.index(x) < a] or slice(0, 0),\n        [t.domain.index(x) - a\n         for x in indices if t.domain.index(x) >= a] or slice(0, 0),\n        [-t.domain.index(x) - 1\n         for x in indices if t.domain.index(x) < 0] or slice(0, 0))\n\n\ndef getname(variable):\n    return variable.name\n\n\nclass TableIndexingTests(TableTests):\n    def setUp(self):\n        super().setUp()\n        d = self.domain = \\\n            self.create_domain(self.attributes, self.class_vars, self.metas)\n        t = self.table = \\\n            data.Table(self.domain, self.data, self.class_data, self.meta_data)\n        self.magic_table = \\\n            np.column_stack((self.table.X, self.table.Y,\n                             self.table.metas[:, ::-1]))\n\n        self.rows = [0, -1]\n        self.multiple_rows = [slice(0, 0), ..., slice(1, -1, -1)]\n        a, c, m = column_sizes(t)\n        columns = [0, a - 1, a, a + c - 1, -1, -m]\n        self.columns = chain(columns,\n                             map(lambda x: d[x], columns),\n                             map(lambda x: d[x].name, columns))\n        self.multiple_columns = chain(\n            self.multiple_rows,\n            [d.attributes, d.class_vars, d.metas, [0, a, -1]],\n            [self.attributes, self.class_vars, self.metas],\n            [self.attributes + self.class_vars + self.metas])\n\n        # TODO: indexing with [[0,1], [0,1]] produces weird results\n        # TODO: what should be the results of table[1, :]\n\n    def test_can_select_a_single_value(self):\n        for r in self.rows:\n            for c in self.columns:\n                value = self.table[r, c]\n                self.assertAlmostEqual(\n                    value, self.magic_table[r, self.domain.index(c)])\n\n                value = self.table[r][c]\n                self.assertAlmostEqual(\n                    value, self.magic_table[r, self.domain.index(c)])\n\n    def test_can_select_a_single_row(self):\n        for r in self.rows:\n            row = self.table[r]\n            new_row = np.hstack(\n                (self.data[r, :],\n                 self.class_data[r, None]))\n            np.testing.assert_almost_equal(\n                np.array(list(row)), new_row)\n\n\n    def test_can_select_a_subset_of_rows_and_columns(self):\n        for r in self.rows:\n            for c in self.multiple_columns:\n                table = self.table[r, c]\n\n                attr, cls, metas = split_columns(c, self.table)\n                X = self.table.X[[r], attr]\n                if X.ndim == 1:\n                    X = X.reshape(-1, len(table.domain.attributes))\n                np.testing.assert_almost_equal(table.X, X)\n                Y = self.table.Y[:, None][[r], cls]\n                if len(Y.shape) == 1 or Y.shape[1] == 1:\n                    Y = Y.flatten()\n                np.testing.assert_almost_equal(table.Y, Y)\n                metas_ = self.table.metas[[r], metas]\n                if metas_.ndim == 1:\n                    metas_ = metas_.reshape(-1, len(table.domain.metas))\n                np.testing.assert_almost_equal(table.metas, metas_)\n\n        for r in self.multiple_rows:\n            for c in chain(self.columns, self.multiple_rows):\n                table = self.table[r, c]\n\n                attr, cls, metas = split_columns(c, self.table)\n                np.testing.assert_almost_equal(table.X, self.table.X[r, attr])\n                Y = self.table.Y[:, None][r, cls]\n                if len(Y.shape) > 1 and Y.shape[1] == 1:\n                    Y = Y.flatten()\n                np.testing.assert_almost_equal(table.Y, Y)\n                np.testing.assert_almost_equal(table.metas,\n                                               self.table.metas[r, metas])\n\n\n    def test_optimize_indices(self):\n        # ordinary conversion\n        self.assertEqual(_optimize_indices([1, 2, 3], 4), slice(1, 4, 1))\n        self.assertEqual(_optimize_indices([], 1), [])\n        self.assertEqual(_optimize_indices([0, 2], 3), slice(0, 4, 2))\n\n        # not slices\n        np.testing.assert_equal(_optimize_indices([1, 2, 4], 5), [1, 2, 4])\n        np.testing.assert_equal(_optimize_indices((1, 2, 4), 5), [1, 2, 4])\n\n        # leave boolean arrays\n        np.testing.assert_equal(_optimize_indices([True, False, True], 3), [True, False, True])\n\n        # do not convert if step is negative\n        np.testing.assert_equal(_optimize_indices([4, 2, 0], 5), [4, 2, 0])\n\n        # try range\n        np.testing.assert_equal(_optimize_indices([3, 4, 5], 5), [3, 4, 5])  # out of range\n        self.assertEqual(_optimize_indices((3, 4, 5), 6), slice(3, 6, 1))\n\n        # negative elements\n        np.testing.assert_equal(_optimize_indices([-1, 0, 1], 5), [-1, 0, 1])\n\n        # single element\n        self.assertEqual(_optimize_indices([1], 2), slice(1, 2, 1))\n        np.testing.assert_equal(_optimize_indices([1], 1), [1])\n\n\nclass TableElementAssignmentTest(TableTests):\n    def setUp(self):\n        super().setUp()\n        self.domain = \\\n            self.create_domain(self.attributes, self.class_vars, self.metas)\n        self.table = \\\n            data.Table(self.domain, self.data, self.class_data, self.meta_data)\n\n    def test_can_assign_values(self):\n        self.table[0, 0] = 42.\n        self.assertAlmostEqual(self.table.X[0, 0], 42.)\n\n    def test_can_assign_values_to_classes(self):\n        a, _, _ = column_sizes(self.table)\n        self.table[0, a] = 42.\n        self.assertAlmostEqual(self.table.Y[0], 42.)\n\n    def test_can_assign_values_to_metas(self):\n        self.table[0, -1] = 42.\n        self.assertAlmostEqual(self.table.metas[0, 0], 42.)\n\n    def test_can_assign_rows_to_rows(self):\n        self.table[0] = self.table[1]\n        np.testing.assert_almost_equal(\n            self.table.X[0], self.table.X[1])\n        np.testing.assert_almost_equal(\n            self.table.Y[0], self.table.Y[1])\n        np.testing.assert_almost_equal(\n            self.table.metas[0], self.table.metas[1])\n\n    def test_can_assign_lists(self):\n        a, _, _ = column_sizes(self.table)\n        new_example = [float(i)\n                       for i in range(len(self.attributes + self.class_vars))]\n        self.table[0] = new_example\n        np.testing.assert_almost_equal(\n            self.table.X[0], np.array(new_example[:a]))\n        np.testing.assert_almost_equal(\n            self.table.Y[0], np.array(new_example[a:]))\n\n    def test_can_assign_np_array(self):\n        a, _, _ = column_sizes(self.table)\n        new_example = \\\n            np.array([float(i)\n                      for i in range(len(self.attributes + self.class_vars))])\n        self.table[0] = new_example\n        np.testing.assert_almost_equal(self.table.X[0], new_example[:a])\n        np.testing.assert_almost_equal(self.table.Y[0], new_example[a:])\n\n\nclass InterfaceTest(unittest.TestCase):\n    \"\"\"Basic tests each implementation of Table should pass.\"\"\"\n\n    features = (\n        data.ContinuousVariable(name=\"Continuous Feature 1\"),\n        data.ContinuousVariable(name=\"Continuous Feature 2\"),\n        data.DiscreteVariable(name=\"Discrete Feature 1\", values=[\"0\", \"1\"]),\n        data.DiscreteVariable(name=\"Discrete Feature 2\",\n                              values=[\"value1\", \"value2\"]),\n    )\n\n    class_vars = (\n        data.ContinuousVariable(name=\"Continuous Class\"),\n        data.DiscreteVariable(name=\"Discrete Class\", values=[\"m\", \"f\"])\n    )\n\n    feature_data = (\n        (1, 0, 0, 0),\n        (0, 1, 0, 0),\n        (0, 0, 1, 0),\n        (0, 0, 0, 1),\n    )\n\n    class_data = (\n        (1, 0),\n        (0, 1),\n        (1, 0),\n        (0, 1)\n    )\n\n    data = tuple(a + c for a, c in zip(feature_data, class_data))\n\n    nrows = 4\n\n    def setUp(self):\n        self.domain = data.Domain(attributes=self.features,\n                                  class_vars=self.class_vars)\n        self.table = data.Table.from_numpy(\n            self.domain,\n            np.array(self.feature_data),\n            np.array(self.class_data),\n        )\n\n    def test_len(self):\n        self.assertEqual(len(self.table), self.nrows)\n\n    def test_row_len(self):\n        for i in range(self.nrows):\n            self.assertEqual(len(self.table[i]), len(self.data[i]))\n\n    def test_iteration(self):\n        for row, expected_data in zip(self.table, self.data):\n            self.assertEqual(tuple(row), expected_data)\n\n    def test_row_indexing(self):\n        for i in range(self.nrows):\n            self.assertEqual(tuple(self.table[i]), self.data[i])\n\n    def test_row_slicing(self):\n        t = self.table[1:]\n        self.assertEqual(len(t), self.nrows - 1)\n\n    def test_value_indexing(self):\n        for i in range(self.nrows):\n            for j in range(len(self.table[i])):\n                self.assertEqual(self.table[i, j], self.data[i][j])\n\n    def test_row_assignment(self):\n        new_value = 2.\n        for i in range(self.nrows):\n            new_row = [new_value] * len(self.data[i])\n            self.table[i] = np.array(new_row)\n            self.assertEqual(list(self.table[i]), new_row)\n\n    def test_value_assignment(self):\n        new_value = 0.\n        for i in range(self.nrows):\n            for j in range(len(self.table[i])):\n                self.table[i, j] = new_value\n                self.assertEqual(self.table[i, j], new_value)\n\n    @skip_deprecated_length\n    def test_append_rows(self):\n        new_value = 2\n        new_row = [new_value] * len(self.data[0])\n        self.table.append(new_row)\n        self.assertEqual(list(self.table[-1]), new_row)\n\n    @skip_deprecated_length\n    def test_insert_rows(self):\n        new_value = 2\n        new_row = [new_value] * len(self.data[0])\n        self.table.insert(0, new_row)\n        self.assertEqual(list(self.table[0]), new_row)\n        for row, expected in zip(self.table[1:], self.data):\n            self.assertEqual(tuple(row), expected)\n\n    @skip_deprecated_length\n    def test_insert_view(self):\n        new_row = [1] * len(self.data[0])\n        tab = self.table[:2]\n        self.assertFalse(tab.is_copy())\n        tab.insert(0, new_row)\n        tab = data.Table.from_numpy(self.table.domain, self.table)\n        self.assertFalse(tab.X.flags.c_contiguous)\n        tab.insert(0, new_row)\n\n    @skip_deprecated_length\n    def test_delete_rows(self):\n        for i in range(self.nrows):\n            del self.table[0]\n            for j in range(len(self.table)):\n                self.assertEqual(tuple(self.table[j]), self.data[i + j + 1])\n\n    @skip_deprecated_length\n    def test_clear(self):\n        self.table.clear()\n        self.assertEqual(len(self.table), 0)\n        for _ in self.table:\n            self.fail(\"Table should not contain any rows.\")\n\n    def test_subclasses(self):\n        from pathlib import Path\n\n        class _ExtendedTable(data.Table):\n            pass\n\n        data_file = _ExtendedTable('iris')\n        data_url = _ExtendedTable.from_url(\n            Path(os.path.dirname(__file__), 'test1.tab').as_uri())\n\n        self.assertIsInstance(data_file, _ExtendedTable)\n        self.assertIsInstance(data_url, _ExtendedTable)\n\n\nclass TestTableStats(TableTests):\n    def test_get_nan_frequency(self):\n        domain = self.create_domain(self.attributes, self.class_vars)\n        table = data.Table(domain, self.data, self.class_data)\n        self.assertEqual(table.get_nan_frequency_attribute(), 0)\n        self.assertEqual(table.get_nan_frequency_class(), 0)\n\n        table.X[1, 2] = table.X[4, 5] = np.nan\n        self.assertEqual(table.get_nan_frequency_attribute(), 2 / table.X.size)\n        self.assertEqual(table.get_nan_frequency_class(), 0)\n\n        table.Y[3:6] = np.nan\n        self.assertEqual(table.get_nan_frequency_attribute(), 2 / table.X.size)\n        self.assertEqual(table.get_nan_frequency_class(), 3 / table.Y.size)\n\n        table.X[1, 2] = table.X[4, 5] = 0\n        self.assertEqual(table.get_nan_frequency_attribute(), 0)\n        self.assertEqual(table.get_nan_frequency_class(), 3 / table.Y.size)\n\n    def test_get_nan_frequency_empty_table(self):\n        domain = self.create_domain(self.attributes, self.class_vars)\n        table = data.Table(domain)\n        self.assertEqual(table.get_nan_frequency_attribute(), 0)\n        self.assertEqual(table.get_nan_frequency_class(), 0)\n\n\nclass TestRowInstance(unittest.TestCase):\n    def test_assignment(self):\n        table = data.Table(\"zoo\")\n        inst = table[2]\n        self.assertIsInstance(inst, data.RowInstance)\n\n        inst[1] = 0\n        self.assertEqual(table[2, 1], 0)\n        inst[1] = 1\n        self.assertEqual(table[2, 1], 1)\n\n        inst.set_class(\"mammal\")\n        self.assertEqual(table[2, len(table.domain.attributes)], \"mammal\")\n        inst.set_class(\"fish\")\n        self.assertEqual(table[2, len(table.domain.attributes)], \"fish\")\n\n        inst[-1] = \"Foo\"\n        self.assertEqual(table[2, -1], \"Foo\")\n\n    def test_iteration_with_assignment(self):\n        table = data.Table(\"iris\")\n        for i, row in enumerate(table):\n            row[0] = i\n        np.testing.assert_array_equal(table.X[:, 0], np.arange(len(table)))\n\n    def test_sparse_assignment(self):\n        X = np.eye(4)\n        Y = X[2]\n        table = data.Table(X, Y)\n        row = table[1]\n        self.assertFalse(sp.issparse(row.sparse_x))\n        self.assertEqual(row[0], 0)\n        self.assertEqual(row[1], 1)\n\n        table.X = sp.csr_matrix(table.X)\n        table._Y = sp.csr_matrix(table._Y)\n        sparse_row = table[1]\n        self.assertTrue(sp.issparse(sparse_row.sparse_x))\n        self.assertEqual(sparse_row[0], 0)\n        self.assertEqual(sparse_row[1], 1)\n        sparse_row[1] = 0\n        self.assertEqual(sparse_row[1], 0)\n        self.assertEqual(table.X[1, 1], 0)\n        self.assertEqual(table[2][4], 1)\n        table[2][4] = 0\n        self.assertEqual(table[2][4], 0)\n\n\nclass TestTableTranspose(unittest.TestCase):\n    def test_transpose_no_class(self):\n        attrs = [ContinuousVariable(\"c1\"), ContinuousVariable(\"c2\")]\n        data = Table(Domain(attrs), np.arange(8).reshape((4, 2)))\n\n        att = [ContinuousVariable(\"Feature 1\"), ContinuousVariable(\"Feature 2\"),\n               ContinuousVariable(\"Feature 3\"), ContinuousVariable(\"Feature 4\")]\n        domain = Domain(att, metas=[StringVariable(\"Feature name\")])\n        result = Table(domain, np.arange(8).reshape((4, 2)).T,\n                       metas=np.array([\"c1\", \"c2\"])[:, None])\n\n        # transpose and compare\n        self._compare_tables(result, Table.transpose(data))\n\n        # transpose of transpose is original\n        t = Table.transpose(Table.transpose(data), \"Feature name\")\n        self._compare_tables(data, t)\n\n        # original should not change\n        self.assertDictEqual(data.domain.attributes[0].attributes, {})\n\n    def test_transpose_discrete_class(self):\n        attrs = [ContinuousVariable(\"c1\"), ContinuousVariable(\"c2\")]\n        domain = Domain(attrs, [DiscreteVariable(\"cls\", values=[\"a\", \"b\"])])\n        data = Table(domain, np.arange(8).reshape((4, 2)),\n                     np.array([1, 1, 0, 0]))\n\n        att = [ContinuousVariable(\"Feature 1\"), ContinuousVariable(\"Feature 2\"),\n               ContinuousVariable(\"Feature 3\"), ContinuousVariable(\"Feature 4\")]\n        att[0].attributes = {\"cls\": \"b\"}\n        att[1].attributes = {\"cls\": \"b\"}\n        att[2].attributes = {\"cls\": \"a\"}\n        att[3].attributes = {\"cls\": \"a\"}\n        domain = Domain(att, metas=[StringVariable(\"Feature name\")])\n        result = Table(domain, np.arange(8).reshape((4, 2)).T,\n                       metas=np.array([\"c1\", \"c2\"])[:, None])\n\n        # transpose and compare\n        self._compare_tables(result, Table.transpose(data))\n\n        # transpose of transpose is original\n        t = Table.transpose(Table.transpose(data), \"Feature name\")\n        self._compare_tables(data, t)\n\n        # original should not change\n        self.assertDictEqual(data.domain.attributes[0].attributes, {})\n\n    def test_transpose_continuous_class(self):\n        attrs = [ContinuousVariable(\"c1\"), ContinuousVariable(\"c2\")]\n        domain = Domain(attrs, [ContinuousVariable(\"cls\")])\n        data = Table(domain, np.arange(8).reshape((4, 2)), np.arange(4, 0, -1))\n\n        att = [ContinuousVariable(\"Feature 1\"), ContinuousVariable(\"Feature 2\"),\n               ContinuousVariable(\"Feature 3\"), ContinuousVariable(\"Feature 4\")]\n        att[0].attributes = {\"cls\": \"4\"}\n        att[1].attributes = {\"cls\": \"3\"}\n        att[2].attributes = {\"cls\": \"2\"}\n        att[3].attributes = {\"cls\": \"1\"}\n        domain = Domain(att, metas=[StringVariable(\"Feature name\")])\n        result = Table(domain, np.arange(8).reshape((4, 2)).T,\n                       metas=np.array([\"c1\", \"c2\"])[:, None])\n\n        # transpose and compare\n        self._compare_tables(result, Table.transpose(data))\n\n        # transpose of transpose\n        t = Table.transpose(Table.transpose(data), \"Feature name\")\n        self._compare_tables(data, t)\n\n        # original should not change\n        self.assertDictEqual(data.domain.attributes[0].attributes, {})\n\n    def test_transpose_missing_class(self):\n        attrs = [ContinuousVariable(\"c1\"), ContinuousVariable(\"c2\")]\n        domain = Domain(attrs, [ContinuousVariable(\"cls\")])\n        data = Table(domain, np.arange(8).reshape((4, 2)),\n                     np.array([np.nan, 3, 2, 1]))\n\n        att = [ContinuousVariable(\"Feature 1\"), ContinuousVariable(\"Feature 2\"),\n               ContinuousVariable(\"Feature 3\"), ContinuousVariable(\"Feature 4\")]\n        att[1].attributes = {\"cls\": \"3\"}\n        att[2].attributes = {\"cls\": \"2\"}\n        att[3].attributes = {\"cls\": \"1\"}\n        domain = Domain(att, metas=[StringVariable(\"Feature name\")])\n        result = Table(domain, np.arange(8).reshape((4, 2)).T,\n                       metas=np.array([\"c1\", \"c2\"])[:, None])\n\n        # transpose and compare\n        self._compare_tables(result, Table.transpose(data))\n\n        # transpose of transpose\n        t = Table.transpose(Table.transpose(data), \"Feature name\")\n        self._compare_tables(data, t)\n\n        # original should not change\n        self.assertDictEqual(data.domain.attributes[0].attributes, {})\n\n    def test_transpose_multiple_class(self):\n        attrs = [ContinuousVariable(\"c1\"), ContinuousVariable(\"c2\")]\n        class_vars = [ContinuousVariable(\"cls1\"), ContinuousVariable(\"cls2\")]\n        domain = Domain(attrs, class_vars)\n        data = Table(domain, np.arange(8).reshape((4, 2)),\n                     np.arange(8).reshape((4, 2)))\n\n        att = [ContinuousVariable(\"Feature 1\"), ContinuousVariable(\"Feature 2\"),\n               ContinuousVariable(\"Feature 3\"), ContinuousVariable(\"Feature 4\")]\n        att[0].attributes = {\"cls1\": \"0\", \"cls2\": \"1\"}\n        att[1].attributes = {\"cls1\": \"2\", \"cls2\": \"3\"}\n        att[2].attributes = {\"cls1\": \"4\", \"cls2\": \"5\"}\n        att[3].attributes = {\"cls1\": \"6\", \"cls2\": \"7\"}\n        domain = Domain(att, metas=[StringVariable(\"Feature name\")])\n        result = Table(domain, np.arange(8).reshape((4, 2)).T,\n                       metas=np.array([\"c1\", \"c2\"])[:, None])\n\n        # transpose and compare\n        self._compare_tables(result, Table.transpose(data))\n\n        # transpose of transpose\n        t = Table.transpose(Table.transpose(data), \"Feature name\")\n        self._compare_tables(data, t)\n\n        # original should not change\n        self.assertDictEqual(data.domain.attributes[0].attributes, {})\n\n    def test_transpose_metas(self):\n        attrs = [ContinuousVariable(\"c1\"), ContinuousVariable(\"c2\")]\n        metas = [StringVariable(\"m1\")]\n        domain = Domain(attrs, metas=metas)\n        X = np.arange(8).reshape((4, 2))\n        M = np.array([\"aa\", \"bb\", \"cc\", \"dd\"])[:, None]\n        data = Table(domain, X, metas=M)\n\n        att = [ContinuousVariable(\"Feature 1\"), ContinuousVariable(\"Feature 2\"),\n               ContinuousVariable(\"Feature 3\"), ContinuousVariable(\"Feature 4\")]\n        att[0].attributes = {\"m1\": \"aa\"}\n        att[1].attributes = {\"m1\": \"bb\"}\n        att[2].attributes = {\"m1\": \"cc\"}\n        att[3].attributes = {\"m1\": \"dd\"}\n        domain = Domain(att, metas=[StringVariable(\"Feature name\")])\n        result = Table(domain, np.arange(8).reshape((4, 2)).T,\n                       metas=np.array([\"c1\", \"c2\"])[:, None])\n\n        # transpose and compare\n        self._compare_tables(result, Table.transpose(data))\n\n        # transpose of transpose\n        t = Table.transpose(Table.transpose(data), \"Feature name\")\n        self._compare_tables(data, t)\n\n        # original should not change\n        self.assertDictEqual(data.domain.attributes[0].attributes, {})\n\n    def test_transpose_discrete_metas(self):\n        attrs = [ContinuousVariable(\"c1\"), ContinuousVariable(\"c2\")]\n        metas = [DiscreteVariable(\"m1\", values=[\"aa\", \"bb\"])]\n        domain = Domain(attrs, metas=metas)\n        X = np.arange(8).reshape((4, 2))\n        M = np.array([0, 1, 0, 1])[:, None]\n        data = Table(domain, X, metas=M)\n\n        att = [ContinuousVariable(\"Feature 1\"), ContinuousVariable(\"Feature 2\"),\n               ContinuousVariable(\"Feature 3\"), ContinuousVariable(\"Feature 4\")]\n        att[0].attributes = {\"m1\": \"aa\"}\n        att[1].attributes = {\"m1\": \"bb\"}\n        att[2].attributes = {\"m1\": \"aa\"}\n        att[3].attributes = {\"m1\": \"bb\"}\n        domain = Domain(att, metas=[StringVariable(\"Feature name\")])\n        result = Table(domain, np.arange(8).reshape((4, 2)).T,\n                       metas=np.array([\"c1\", \"c2\"])[:, None])\n\n        # transpose and compare\n        self._compare_tables(result, Table.transpose(data))\n\n        # transpose of transpose is original\n        t = Table.transpose(Table.transpose(data), \"Feature name\")\n        self._compare_tables(data, t)\n\n        # original should not change\n        self.assertDictEqual(data.domain.attributes[0].attributes, {})\n\n    def test_transpose_continuous_metas(self):\n        attrs = [ContinuousVariable(\"c1\"), ContinuousVariable(\"c2\")]\n        metas = [ContinuousVariable(\"m1\")]\n        domain = Domain(attrs, metas=metas)\n        X = np.arange(8).reshape((4, 2))\n        M = np.array([0.0, 1.0, 0.0, 1.0])[:, None]\n        data = Table(domain, X, metas=M)\n\n        att = [ContinuousVariable(\"Feature 1\"), ContinuousVariable(\"Feature 2\"),\n               ContinuousVariable(\"Feature 3\"), ContinuousVariable(\"Feature 4\")]\n        att[0].attributes = {\"m1\": \"0\"}\n        att[1].attributes = {\"m1\": \"1\"}\n        att[2].attributes = {\"m1\": \"0\"}\n        att[3].attributes = {\"m1\": \"1\"}\n        domain = Domain(att, metas=[StringVariable(\"Feature name\")])\n        result = Table(domain, np.arange(8).reshape((4, 2)).T,\n                       metas=np.array([\"c1\", \"c2\"])[:, None])\n\n        # transpose and compare\n        self._compare_tables(result, Table.transpose(data))\n\n        # transpose of transpose is original\n        t = Table.transpose(Table.transpose(data), \"Feature name\")\n        self._compare_tables(data, t)\n\n        # original should not change\n        self.assertDictEqual(data.domain.attributes[0].attributes, {})\n\n    def test_transpose_missing_metas(self):\n        attrs = [ContinuousVariable(\"c1\"), ContinuousVariable(\"c2\")]\n        metas = [StringVariable(\"m1\")]\n        domain = Domain(attrs, metas=metas)\n        X = np.arange(8).reshape((4, 2))\n        M = np.array([\"aa\", \"bb\", \"\", \"dd\"])[:, None]\n        data = Table(domain, X, metas=M)\n\n        att = [ContinuousVariable(\"Feature 1\"), ContinuousVariable(\"Feature 2\"),\n               ContinuousVariable(\"Feature 3\"), ContinuousVariable(\"Feature 4\")]\n        att[0].attributes = {\"m1\": \"aa\"}\n        att[1].attributes = {\"m1\": \"bb\"}\n        att[3].attributes = {\"m1\": \"dd\"}\n        domain = Domain(att, metas=[StringVariable(\"Feature name\")])\n        result = Table(domain, np.arange(8).reshape((4, 2)).T,\n                       metas=np.array([\"c1\", \"c2\"])[:, None])\n\n        # transpose and compare\n        self._compare_tables(result, Table.transpose(data))\n\n        # transpose of transpose\n        t = Table.transpose(Table.transpose(data), \"Feature name\")\n        self._compare_tables(data, t)\n\n        # original should not change\n        self.assertDictEqual(data.domain.attributes[0].attributes, {})\n\n    def test_transpose_multiple_metas(self):\n        attrs = [ContinuousVariable(\"c1\"), ContinuousVariable(\"c2\")]\n        metas = [StringVariable(\"m1\"), StringVariable(\"m2\")]\n        domain = Domain(attrs, metas=metas)\n        X = np.arange(8).reshape((4, 2))\n        M = np.array([[\"aa\", \"aaa\"], [\"bb\", \"bbb\"],\n                      [\"cc\", \"ccc\"], [\"dd\", \"ddd\"]])\n        data = Table(domain, X, metas=M)\n\n        att = [ContinuousVariable(\"Feature 1\"), ContinuousVariable(\"Feature 2\"),\n               ContinuousVariable(\"Feature 3\"), ContinuousVariable(\"Feature 4\")]\n        att[0].attributes = {\"m1\": \"aa\", \"m2\": \"aaa\"}\n        att[1].attributes = {\"m1\": \"bb\", \"m2\": \"bbb\"}\n        att[2].attributes = {\"m1\": \"cc\", \"m2\": \"ccc\"}\n        att[3].attributes = {\"m1\": \"dd\", \"m2\": \"ddd\"}\n        domain = Domain(att, metas=[StringVariable(\"Feature name\")])\n        result = Table(domain, np.arange(8).reshape((4, 2)).T,\n                       metas=np.array([\"c1\", \"c2\"])[:, None])\n\n        # transpose and compare\n        self._compare_tables(result, Table.transpose(data))\n\n        # transpose of transpose\n        t = Table.transpose(Table.transpose(data), \"Feature name\")\n        self._compare_tables(data, t)\n\n        # original should not change\n        self.assertDictEqual(data.domain.attributes[0].attributes, {})\n\n    def test_transpose_class_and_metas(self):\n        attrs = [ContinuousVariable(\"c1\"), ContinuousVariable(\"c2\")]\n        metas = [StringVariable(\"m1\"), StringVariable(\"m2\")]\n        domain = Domain(attrs, [ContinuousVariable(\"cls\")], metas)\n        M = np.array([[\"aa\", \"aaa\"], [\"bb\", \"bbb\"],\n                      [\"cc\", \"ccc\"], [\"dd\", \"ddd\"]])\n        data = Table(domain, np.arange(8).reshape((4, 2)), np.arange(1, 5), M)\n\n        att = [ContinuousVariable(\"Feature 1\"), ContinuousVariable(\"Feature 2\"),\n               ContinuousVariable(\"Feature 3\"), ContinuousVariable(\"Feature 4\")]\n        att[0].attributes = {\"cls\": \"1\", \"m1\": \"aa\", \"m2\": \"aaa\"}\n        att[1].attributes = {\"cls\": \"2\", \"m1\": \"bb\", \"m2\": \"bbb\"}\n        att[2].attributes = {\"cls\": \"3\", \"m1\": \"cc\", \"m2\": \"ccc\"}\n        att[3].attributes = {\"cls\": \"4\", \"m1\": \"dd\", \"m2\": \"ddd\"}\n        domain = Domain(att, metas=[StringVariable(\"Feature name\")])\n        result = Table(domain, np.arange(8).reshape((4, 2)).T,\n                       metas=np.array([\"c1\", \"c2\"])[:, None])\n\n        # transpose and compare\n        self._compare_tables(result, Table.transpose(data))\n\n        # transpose of transpose\n        t = Table.transpose(Table.transpose(data), \"Feature name\")\n        self._compare_tables(data, t)\n\n        # original should not change\n        self.assertDictEqual(data.domain.attributes[0].attributes, {})\n\n    def test_transpose_attributes_of_attributes_discrete(self):\n        attrs = [ContinuousVariable(\"c1\"), ContinuousVariable(\"c2\")]\n        attrs[0].attributes = {\"attr1\": \"a\", \"attr2\": \"aa\"}\n        attrs[1].attributes = {\"attr1\": \"b\", \"attr2\": \"bb\"}\n        domain = Domain(attrs)\n        data = Table(domain, np.arange(8).reshape((4, 2)))\n\n        att = [ContinuousVariable(\"Feature 1\"), ContinuousVariable(\"Feature 2\"),\n               ContinuousVariable(\"Feature 3\"), ContinuousVariable(\"Feature 4\")]\n        metas = [StringVariable(\"Feature name\"),\n                 DiscreteVariable(\"attr1\", values=(\"a\", \"b\")),\n                 DiscreteVariable(\"attr2\", values=(\"aa\", \"bb\"))]\n        domain = Domain(att, metas=metas)\n        M = np.array([[\"c1\", 0.0, 0.0], [\"c2\", 1.0, 1.0]], dtype=object)\n        result = Table(domain, np.arange(8).reshape((4, 2)).T, metas=M)\n\n        # transpose and compare\n        self._compare_tables(result, Table.transpose(data))\n\n        # transpose of transpose\n        t = Table.transpose(Table.transpose(data), \"Feature name\")\n        self._compare_tables(data, t)\n\n        # original should not change\n        self.assertDictEqual(data.domain.attributes[0].attributes,\n                             {\"attr1\": \"a\", \"attr2\": \"aa\"})\n\n    def test_transpose_attributes_of_attributes_continuous(self):\n        attrs = [ContinuousVariable(\"c1\"), ContinuousVariable(\"c2\")]\n        attrs[0].attributes = {\"attr1\": \"1.1\", \"attr2\": \"1.3\"}\n        attrs[1].attributes = {\"attr1\": \"2.2\", \"attr2\": \"2.3\"}\n        domain = Domain(attrs)\n        data = Table(domain, np.arange(8).reshape((4, 2)))\n\n        att = [ContinuousVariable(\"Feature 1\"), ContinuousVariable(\"Feature 2\"),\n               ContinuousVariable(\"Feature 3\"), ContinuousVariable(\"Feature 4\")]\n        metas = [StringVariable(\"Feature name\"), ContinuousVariable(\"attr1\"),\n                 ContinuousVariable(\"attr2\")]\n        domain = Domain(att, metas=metas)\n        result = Table(domain, np.arange(8).reshape((4, 2)).T,\n                       metas=np.array([[\"c1\", 1.1, 1.3],\n                                       [\"c2\", 2.2, 2.3]], dtype=object))\n\n        # transpose and compare\n        self._compare_tables(result, Table.transpose(data))\n\n        # transpose of transpose\n        t = Table.transpose(Table.transpose(data), \"Feature name\")\n        self._compare_tables(data, t)\n\n        # original should not change\n        self.assertDictEqual(data.domain.attributes[0].attributes,\n                             {\"attr1\": \"1.1\", \"attr2\": \"1.3\"})\n\n    def test_transpose_attributes_of_attributes_missings(self):\n        attrs = [ContinuousVariable(\"c1\"), ContinuousVariable(\"c2\")]\n        attrs[0].attributes = {\"attr1\": \"a\", \"attr2\": \"aa\"}\n        attrs[1].attributes = {\"attr1\": \"b\"}\n        domain = Domain(attrs)\n        data = Table(domain, np.arange(8).reshape((4, 2)))\n\n        att = [ContinuousVariable(\"Feature 1\"), ContinuousVariable(\"Feature 2\"),\n               ContinuousVariable(\"Feature 3\"), ContinuousVariable(\"Feature 4\")]\n        metas = [StringVariable(\"Feature name\"),\n                 DiscreteVariable(\"attr1\", values=(\"a\", \"b\")),\n                 DiscreteVariable(\"attr2\", values=(\"aa\",))]\n        domain = Domain(att, metas=metas)\n        M = np.array([[\"c1\", 0.0, 0.0], [\"c2\", 1.0, np.nan]], dtype=object)\n        result = Table(domain, np.arange(8).reshape((4, 2)).T, metas=M)\n\n        # transpose and compare\n        self._compare_tables(result, Table.transpose(data))\n\n        # transpose of transpose\n        t = Table.transpose(Table.transpose(data), \"Feature name\")\n        self._compare_tables(data, t)\n\n        # original should not change\n        self.assertDictEqual(data.domain.attributes[0].attributes,\n                             {\"attr1\": \"a\", \"attr2\": \"aa\"})\n\n    def test_transpose_class_metas_attributes(self):\n        attrs = [ContinuousVariable(\"c1\"), ContinuousVariable(\"c2\")]\n        attrs[0].attributes = {\"attr1\": \"a1\", \"attr2\": \"aa1\"}\n        attrs[1].attributes = {\"attr1\": \"b1\", \"attr2\": \"bb1\"}\n        metas = [StringVariable(\"m1\"), StringVariable(\"m2\")]\n        domain = Domain(attrs, [ContinuousVariable(\"cls\")], metas)\n        M = np.array([[\"aa\", \"aaa\"], [\"bb\", \"bbb\"],\n                      [\"cc\", \"ccc\"], [\"dd\", \"ddd\"]])\n        data = Table(domain, np.arange(8).reshape((4, 2)), np.arange(1, 5), M)\n\n        att = [ContinuousVariable(\"Feature 1\"), ContinuousVariable(\"Feature 2\"),\n               ContinuousVariable(\"Feature 3\"), ContinuousVariable(\"Feature 4\")]\n        att[0].attributes = {\"cls\": \"1\", \"m1\": \"aa\", \"m2\": \"aaa\"}\n        att[1].attributes = {\"cls\": \"2\", \"m1\": \"bb\", \"m2\": \"bbb\"}\n        att[2].attributes = {\"cls\": \"3\", \"m1\": \"cc\", \"m2\": \"ccc\"}\n        att[3].attributes = {\"cls\": \"4\", \"m1\": \"dd\", \"m2\": \"ddd\"}\n        metas = [StringVariable(\"Feature name\"),\n                 DiscreteVariable(\"attr1\", values=(\"a1\", \"b1\")),\n                 DiscreteVariable(\"attr2\", values=(\"aa1\", \"bb1\"))]\n        domain = Domain(att, metas=metas)\n        M = np.array([[\"c1\", 0.0, 0.0], [\"c2\", 1.0, 1.0]], dtype=object)\n        result = Table(domain, np.arange(8).reshape((4, 2)).T, metas=M)\n\n        # transpose and compare\n        self._compare_tables(result, Table.transpose(data))\n\n        # transpose of transpose\n        t = Table.transpose(Table.transpose(data), \"Feature name\")\n        self._compare_tables(data, t)\n\n        # original should not change\n        self.assertDictEqual(data.domain.attributes[0].attributes,\n                             {\"attr1\": \"a1\", \"attr2\": \"aa1\"})\n\n    def test_transpose(self):\n        zoo = Table(\"zoo\")\n        t1 = Table.transpose(zoo)\n        t2 = Table.transpose(t1, \"Feature name\")\n        t3 = Table.transpose(t2)\n        self._compare_tables(zoo, t2)\n        self._compare_tables(t1, t3)\n\n    def _compare_tables(self, table1, table2):\n        self.assertEqual(table1.n_rows, table2.n_rows)\n        np.testing.assert_array_equal(table1.X, table2.X)\n        np.testing.assert_array_equal(table1.Y, table2.Y)\n        np.testing.assert_array_equal(table1.metas.astype(str),\n                                      table2.metas.astype(str))\n        np.testing.assert_array_equal(table1.W, table2.W)\n\n        self.assertEqual([(type(x), x.name, x.attributes)\n                          for x in table1.domain.attributes],\n                         [(type(x), x.name, x.attributes)\n                          for x in table2.domain.attributes])\n        self.assertEqual([(type(x), x.name, x.attributes)\n                          for x in table1.domain.class_vars],\n                         [(type(x), x.name, x.attributes)\n                          for x in table2.domain.class_vars])\n        self.assertEqual([(type(x), x.name, x.attributes)\n                          for x in table1.domain.metas],\n                         [(type(x), x.name, x.attributes)\n                          for x in table2.domain.metas])\n\n\nclass SparseCV:\n    def __call__(self, data):\n        return sp.csr_matrix((len(data), 1))\n\n\nclass TestTableSparseDense(unittest.TestCase):\n    def setUp(self):\n        self.iris = Table('iris')\n\n    def test_sparse_dense_transformation(self):\n        iris = Table('iris')\n        iris_sparse = iris.to_sparse(sparse_attributes=True)\n        self.assertTrue(sp.issparse(iris_sparse.X))\n        self.assertFalse(sp.issparse(iris_sparse.Y))\n        self.assertFalse(sp.issparse(iris_sparse.metas))\n\n        iris_sparse = iris.to_sparse(sparse_attributes=True, sparse_class=True)\n        self.assertTrue(sp.issparse(iris_sparse.X))\n        self.assertTrue(sp.issparse(iris_sparse.Y))\n        self.assertFalse(sp.issparse(iris_sparse.metas))\n\n        dense_iris = iris_sparse.to_dense()\n        self.assertFalse(sp.issparse(dense_iris.X))\n        self.assertFalse(sp.issparse(dense_iris.Y))\n        self.assertFalse(sp.issparse(dense_iris.metas))\n\n    def test_from_table_add_one_sparse_column(self):\n        # add one sparse feature, should remain dense\n        domain = self.iris.domain.copy()\n        domain.attributes += (\n            ContinuousVariable('S1', compute_value=SparseCV(), sparse=True),\n        )\n        d = self.iris.transform(domain)\n        self.assertFalse(sp.issparse(d.X))\n\n    def test_from_table_add_lots_of_sparse_columns(self):\n        n_attrs = len(self.iris.domain.attributes)\n\n        # add 2*n_attrs+1 sparse feature, should became sparse\n        domain = self.iris.domain.copy()\n        domain.attributes += tuple(\n            ContinuousVariable('S' + str(i), compute_value=SparseCV(), sparse=True)\n            for i in range(2*n_attrs + 1)\n        )\n        d = self.iris.transform(domain)\n        self.assertTrue(sp.issparse(d.X))\n\n    def test_from_table_replace_attrs_with_sparse(self):\n        # replace attrs with a sparse feature, should became sparse\n        domain = self.iris.domain.copy()\n        domain.attributes = (\n            ContinuousVariable('S1', compute_value=SparseCV(), sparse=True),\n        )\n        d = self.iris.transform(domain)\n        self.assertTrue(sp.issparse(d.X))\n\n    def test_from_table_sparse_metas(self):\n        # replace metas with a sparse feature, should became sparse\n        domain = self.iris.domain.copy()\n        domain._metas = (\n            ContinuousVariable('S1', compute_value=SparseCV(), sparse=True),\n        )\n        d = self.iris.transform(domain)\n        self.assertTrue(sp.issparse(d.metas))\n\n    def test_from_table_sparse_metas_with_strings(self):\n        # replace metas with text and 100 sparse features, should be dense\n        domain = self.iris.domain.copy()\n        domain._metas = (StringVariable('text'),) + tuple(\n            ContinuousVariable('S' + str(i), compute_value=SparseCV(), sparse=True)\n            for i in range(100)\n        )\n        d = self.iris.transform(domain)\n        self.assertFalse(sp.issparse(d.metas))\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 copy\nimport os\nimport random\nimport unittest\nfrom unittest.mock import Mock, MagicMock, patch\nfrom distutils.version import LooseVersion\nfrom itertools import chain\nfrom math import isnan\n\nimport numpy as np\nimport scipy.sparse as sp\n\nimport Orange\nfrom Orange import data\nfrom Orange.data import (filter, Unknown, Variable, Table, DiscreteVariable,\n                         ContinuousVariable, Domain, StringVariable)\nfrom Orange.tests import test_dirname, assert_array_nanequal\nfrom Orange.data.table import _optimize_indices\n\n\nif LooseVersion(Orange.__version__) < LooseVersion(\"3.24\"):\n    def skip_deprecated_length(f):\n        return unittest.skip(\n            f\"Method {f.__name__} will be deprecated; tests are \"\n            \"skipped because it already fails on Python 3.7 on travis\")(f)\nelse:\n    def skip_deprecated_length(f):\n        def raise_deprecation(_):\n            raise RuntimeError(\n                f\"We reached 3.24 and method {f.__name__} is now deprecated. \"\n                f\"Remove the method the corresponding tests.\")\n        # Also don't forget to remove this function and imports of LooseVersion\n        # and Orange\n        return raise_deprecation\n\n\nclass TableTestCase(unittest.TestCase):\n    def setUp(self):\n        Variable._clear_all_caches()\n        data.table.dataset_dirs.append(test_dirname())\n\n    def tearDown(self):\n        data.table.dataset_dirs.remove(test_dirname())\n\n    def test_indexing_class(self):\n        d = data.Table(\"test1\")\n        self.assertEqual([e.get_class() for e in d], [\"t\", \"t\", \"f\"])\n        cind = len(d.domain) - 1\n        self.assertEqual([e[cind] for e in d], [\"t\", \"t\", \"f\"])\n        self.assertEqual([e[\"d\"] for e in d], [\"t\", \"t\", \"f\"])\n        cvar = d.domain.class_var\n        self.assertEqual([e[cvar] for e in d], [\"t\", \"t\", \"f\"])\n\n    def test_filename(self):\n        dir = data.table.get_sample_datasets_dir()\n        d = data.Table(\"iris\")\n        self.assertEqual(d.__file__, os.path.join(dir, \"iris.tab\"))\n\n        d = data.Table(\"test2.tab\")\n        self.assertTrue(d.__file__.endswith(\"test2.tab\"))  # platform dependent\n\n    def test_indexing(self):\n        import warnings\n\n        with warnings.catch_warnings():\n            warnings.simplefilter(\"ignore\")\n            d = data.Table(\"test2\")\n\n            # regular, discrete\n            varc = d.domain[\"c\"]\n            self.assertEqual(d[0, 1], \"0\")\n            self.assertEqual(d[0, varc], \"0\")\n            self.assertEqual(d[0, \"c\"], \"0\")\n            self.assertEqual(d[0][1], \"0\")\n            self.assertEqual(d[0][varc], \"0\")\n            self.assertEqual(d[0][\"c\"], \"0\")\n            self.assertEqual(d[np.int_(0), np.int_(1)], \"0\")\n            self.assertEqual(d[np.int_(0)][np.int_(1)], \"0\")\n\n            # regular, continuous\n            varb = d.domain[\"b\"]\n            self.assertEqual(d[0, 0], 0)\n            self.assertEqual(d[0, varb], 0)\n            self.assertEqual(d[0, \"b\"], 0)\n            self.assertEqual(d[0][0], 0)\n            self.assertEqual(d[0][varb], 0)\n            self.assertEqual(d[0][\"b\"], 0)\n            self.assertEqual(d[np.int_(0), np.int_(0)], 0)\n            self.assertEqual(d[np.int_(0)][np.int_(0)], 0)\n\n            # negative\n            varb = d.domain[\"b\"]\n            self.assertEqual(d[-2, 0], 3.333)\n            self.assertEqual(d[-2, varb], 3.333)\n            self.assertEqual(d[-2, \"b\"], 3.333)\n            self.assertEqual(d[-2][0], 3.333)\n            self.assertEqual(d[-2][varb], 3.333)\n            self.assertEqual(d[-2][\"b\"], 3.333)\n            self.assertEqual(d[np.int_(-2), np.int_(0)], 3.333)\n            self.assertEqual(d[np.int_(-2)][np.int_(0)], 3.333)\n\n            # meta, discrete\n            vara = d.domain[\"a\"]\n            metaa = d.domain.index(\"a\")\n            self.assertEqual(d[0, metaa], \"A\")\n            self.assertEqual(d[0, vara], \"A\")\n            self.assertEqual(d[0, \"a\"], \"A\")\n            self.assertEqual(d[0][metaa], \"A\")\n            self.assertEqual(d[0][vara], \"A\")\n            self.assertEqual(d[0][\"a\"], \"A\")\n            self.assertEqual(d[np.int_(0), np.int_(metaa)], \"A\")\n            self.assertEqual(d[np.int_(0)][np.int_(metaa)], \"A\")\n\n            # meta, string\n            vare = d.domain[\"e\"]\n            metae = d.domain.index(\"e\")\n            self.assertEqual(d[0, metae], \"i\")\n            self.assertEqual(d[0, vare], \"i\")\n            self.assertEqual(d[0, \"e\"], \"i\")\n            self.assertEqual(d[0][metae], \"i\")\n            self.assertEqual(d[0][vare], \"i\")\n            self.assertEqual(d[0][\"e\"], \"i\")\n            self.assertEqual(d[np.int_(0), np.int_(metae)], \"i\")\n            self.assertEqual(d[np.int_(0)][np.int_(metae)], \"i\")\n\n    def test_indexing_example(self):\n        import warnings\n\n        with warnings.catch_warnings():\n            warnings.simplefilter(\"ignore\")\n            d = data.Table(\"test2\")\n            e = d[0]\n\n            # regular, discrete\n            varc = d.domain[\"c\"]\n            self.assertEqual(e[1], \"0\")\n            self.assertEqual(e[varc], \"0\")\n            self.assertEqual(e[\"c\"], \"0\")\n            self.assertEqual(e[np.int_(1)], \"0\")\n\n            # regular, continuous\n            varb = d.domain[\"b\"]\n            self.assertEqual(e[0], 0)\n            self.assertEqual(e[varb], 0)\n            self.assertEqual(e[\"b\"], 0)\n            self.assertEqual(e[np.int_(0)], 0)\n\n            # meta, discrete\n            vara = d.domain[\"a\"]\n            metaa = d.domain.index(\"a\")\n            self.assertEqual(e[metaa], \"A\")\n            self.assertEqual(e[vara], \"A\")\n            self.assertEqual(e[\"a\"], \"A\")\n            self.assertEqual(e[np.int_(metaa)], \"A\")\n\n            # meta, string\n            vare = d.domain[\"e\"]\n            metae = d.domain.index(\"e\")\n            self.assertEqual(e[metae], \"i\")\n            self.assertEqual(e[vare], \"i\")\n            self.assertEqual(e[\"e\"], \"i\")\n            self.assertEqual(e[np.int_(metae)], \"i\")\n\n    def test_indexing_assign_value(self):\n        import warnings\n\n        with warnings.catch_warnings():\n            warnings.simplefilter(\"ignore\")\n            d = data.Table(\"test2\")\n\n            # meta\n            vara = d.domain[\"a\"]\n            metaa = d.domain.index(\"a\")\n\n            self.assertEqual(d[0, \"a\"], \"A\")\n            d[0, \"a\"] = \"B\"\n            self.assertEqual(d[0, \"a\"], \"B\")\n            d[0][\"a\"] = \"A\"\n            self.assertEqual(d[0, \"a\"], \"A\")\n\n            d[0, vara] = \"B\"\n            self.assertEqual(d[0, \"a\"], \"B\")\n            d[0][vara] = \"A\"\n            self.assertEqual(d[0, \"a\"], \"A\")\n\n            d[0, metaa] = \"B\"\n            self.assertEqual(d[0, \"a\"], \"B\")\n            d[0][metaa] = \"A\"\n            self.assertEqual(d[0, \"a\"], \"A\")\n\n            d[0, np.int_(metaa)] = \"B\"\n            self.assertEqual(d[0, \"a\"], \"B\")\n            d[0][np.int_(metaa)] = \"A\"\n            self.assertEqual(d[0, \"a\"], \"A\")\n\n            # regular\n            varb = d.domain[\"b\"]\n\n            self.assertEqual(d[0, \"b\"], 0)\n            d[0, \"b\"] = 42\n            self.assertEqual(d[0, \"b\"], 42)\n            d[0][\"b\"] = 0\n            self.assertEqual(d[0, \"b\"], 0)\n\n            d[0, varb] = 42\n            self.assertEqual(d[0, \"b\"], 42)\n            d[0][varb] = 0\n            self.assertEqual(d[0, \"b\"], 0)\n\n            d[0, 0] = 42\n            self.assertEqual(d[0, \"b\"], 42)\n            d[0][0] = 0\n            self.assertEqual(d[0, \"b\"], 0)\n\n            d[0, np.int_(0)] = 42\n            self.assertEqual(d[0, \"b\"], 42)\n            d[0][np.int_(0)] = 0\n            self.assertEqual(d[0, \"b\"], 0)\n\n    @skip_deprecated_length\n    def test_indexing_del_example(self):\n        import warnings\n\n        with warnings.catch_warnings():\n            warnings.simplefilter(\"ignore\")\n            d = data.Table(\"test2\")\n            initlen = len(d)\n\n            # remove first\n            d[4, \"e\"] = \"4ex\"\n            self.assertEqual(d[4, \"e\"], \"4ex\")\n            del d[0]\n            self.assertEqual(len(d), initlen - 1)\n            self.assertEqual(d[3, \"e\"], \"4ex\")\n\n            # remove middle\n            del d[2]\n            self.assertEqual(len(d), initlen - 2)\n            self.assertEqual(d[2, \"e\"], \"4ex\")\n\n            # remove middle\n            del d[4]\n            self.assertEqual(len(d), initlen - 3)\n            self.assertEqual(d[2, \"e\"], \"4ex\")\n\n            # remove last\n            d[-1, \"e\"] = \"was last\"\n            del d[-1]\n            self.assertEqual(len(d), initlen - 4)\n            self.assertEqual(d[2, \"e\"], \"4ex\")\n            self.assertNotEqual(d[-1, \"e\"], \"was last\")\n\n            # remove one before last\n            d[-1, \"e\"] = \"was last\"\n            del d[-2]\n            self.assertEqual(len(d), initlen - 5)\n            self.assertEqual(d[2, \"e\"], \"4ex\")\n            self.assertEqual(d[-1, \"e\"], \"was last\")\n\n            d[np.int_(2), \"e\"] = \"2ex\"\n            del d[np.int_(2)]\n            self.assertEqual(len(d), initlen - 6)\n            self.assertNotEqual(d[2, \"e\"], \"2ex\")\n\n            with self.assertRaises(IndexError):\n                del d[100]\n            self.assertEqual(len(d), initlen - 6)\n\n            with self.assertRaises(IndexError):\n                del d[-100]\n            self.assertEqual(len(d), initlen - 6)\n\n    def test_indexing_assign_example(self):\n        def almost_equal_list(s, t):\n            for e, f in zip(s, t):\n                self.assertAlmostEqual(e, f)\n\n        import warnings\n\n        with warnings.catch_warnings():\n            warnings.simplefilter(\"ignore\")\n            d = data.Table(\"test2\")\n\n            vara = d.domain[\"a\"]\n            metaa = d.domain.index(vara)\n\n            self.assertFalse(isnan(d[0, \"a\"]))\n            d[0] = [\"3.14\", \"1\", \"f\"]\n            almost_equal_list(d[0].values(), [3.14, \"1\", \"f\"])\n            self.assertTrue(isnan(d[0, \"a\"]))\n            d[0] = [3.15, 1, \"t\"]\n            almost_equal_list(d[0].values(), [3.15, \"0\", \"t\"])\n            d[np.int_(0)] = [3.15, 2, \"f\"]\n            almost_equal_list(d[0].values(), [3.15, 2, \"f\"])\n\n            with self.assertRaises(ValueError):\n                d[0] = [\"3.14\", \"1\"]\n\n            with self.assertRaises(ValueError):\n                d[np.int_(0)] = [\"3.14\", \"1\"]\n\n            ex = data.Instance(d.domain, [\"3.16\", \"1\", \"f\"])\n            d[0] = ex\n            almost_equal_list(d[0].values(), [3.16, \"1\", \"f\"])\n\n            ex = data.Instance(d.domain, [\"3.16\", 2, \"t\"])\n            d[np.int_(0)] = ex\n            almost_equal_list(d[0].values(), [3.16, 2, \"t\"])\n\n            ex = data.Instance(d.domain, [\"3.16\", \"1\", \"f\"])\n            ex[\"e\"] = \"mmmapp\"\n            d[0] = ex\n            almost_equal_list(d[0].values(), [3.16, \"1\", \"f\"])\n            self.assertEqual(d[0, \"e\"], \"mmmapp\")\n\n    def test_slice(self):\n        import warnings\n\n        with warnings.catch_warnings():\n            warnings.simplefilter(\"ignore\")\n            d = data.Table(\"test2\")\n            x = d[:3]\n            self.assertEqual(len(x), 3)\n            self.assertEqual([e[0] for e in x], [0, 1.1, 2.22])\n\n            x = d[2:5]\n            self.assertEqual(len(x), 3)\n            self.assertEqual([e[0] for e in x], [2.22, 2.23, 2.24])\n\n            x = d[4:1:-1]\n            self.assertEqual(len(x), 3)\n            self.assertEqual([e[0] for e in x], [2.24, 2.23, 2.22])\n\n            x = d[-3:]\n            self.assertEqual(len(x), 3)\n            self.assertEqual([e[0] for e in x], [2.26, 3.333, Unknown])\n\n    def test_assign_slice_value(self):\n        import warnings\n\n        with warnings.catch_warnings():\n            warnings.simplefilter(\"ignore\")\n            d = data.Table(\"test2\")\n            d[2:5, 0] = 42\n            self.assertEqual([e[0] for e in d],\n                             [0, 1.1, 42, 42, 42, 2.25, 2.26, 3.333, Unknown])\n            d[:3, \"b\"] = 43\n            self.assertEqual([e[0] for e in d],\n                             [43, 43, 43, 42, 42, 2.25, 2.26, 3.333, None])\n            d[-2:, d.domain[0]] = 44\n            self.assertEqual([e[0] for e in d],\n                             [43, 43, 43, 42, 42, 2.25, 2.26, 44, 44])\n\n            d[2:5, \"a\"] = \"A\"\n            self.assertEqual([e[\"a\"] for e in d], list(\"ABAAACCDE\"))\n\n    @skip_deprecated_length\n    def test_del_slice_example(self):\n        import warnings\n\n        with warnings.catch_warnings():\n            warnings.simplefilter(\"ignore\")\n            d = data.Table(\"test2\")\n\n            vals = [e[0] for e in d]\n\n            del d[2:2]\n            self.assertEqual([e[0] for e in d], vals)\n\n            del d[2:5]\n            del vals[2:5]\n            self.assertEqual([e[0] for e in d], vals)\n\n            del d[:]\n            self.assertEqual(len(d), 0)\n\n    @skip_deprecated_length\n    def test_del_slice_ids(self):\n        # __del__ updates `ids` member\n        d = data.Table(\"test2\")\n        ids = d.ids.copy()\n        del d[2:4]\n        np.testing.assert_array_equal(d.ids, np.delete(ids, slice(2, 4)))\n\n    @skip_deprecated_length\n    def test_set_slice_example(self):\n        import warnings\n\n        with warnings.catch_warnings():\n            warnings.simplefilter(\"ignore\")\n            d = data.Table(\"test2\")\n            d[5, 0] = 42\n            d[:3] = d[5]\n            self.assertEqual(d[1, 0], 42)\n\n            d[5:2:-1] = [3, None, None]\n            self.assertEqual([e[0] for e in d],\n                             [42, 42, 42, 3, 3, 3, 2.26, 3.333, None])\n            self.assertTrue(isnan(d[3, 2]))\n\n            d[2:5] = 42\n            self.assertTrue(np.all(d.X[2:5] == 42))\n            self.assertEqual(d.Y[2], 0)\n\n    def test_multiple_indices(self):\n        import warnings\n\n        with warnings.catch_warnings():\n            warnings.simplefilter(\"ignore\")\n            d = data.Table(\"test2\")\n\n            with self.assertRaises(IndexError):\n                x = d[2, 5, 1]\n\n            with self.assertRaises(IndexError):\n                x = d[(2, 5, 1)]\n\n            x = d[[2, 5, 1]]\n            self.assertEqual([e[0] for e in x], [2.22, 2.25, 1.1])\n\n    def test_assign_multiple_indices_value(self):\n        import warnings\n\n        with warnings.catch_warnings():\n            warnings.simplefilter(\"ignore\")\n            d = data.Table(\"test2\")\n\n            d[1:4, \"b\"] = 42\n            self.assertEqual([e[0] for e in d],\n                             [0, 42, 42, 42, 2.24, 2.25, 2.26, 3.333, None])\n\n            d[range(5, 2, -1), \"b\"] = None\n            self.assertEqual([e[d.domain[0]] for e in d],\n                             [0, 42, 42, None, \"?\", \"\", 2.26, 3.333, None])\n\n    @skip_deprecated_length\n    def test_del_multiple_indices_example(self):\n        import warnings\n\n        with warnings.catch_warnings():\n            warnings.simplefilter(\"ignore\")\n            d = data.Table(\"test2\")\n\n            vals = [e[0] for e in d]\n\n            del d[[1, 5, 2]]\n            del vals[5]\n            del vals[2]\n            del vals[1]\n            self.assertEqual([e[0] for e in d], vals)\n\n            del d[range(1, 3)]\n            del vals[1:3]\n            self.assertEqual([e[0] for e in d], vals)\n\n    def test_set_multiple_indices_example(self):\n        import warnings\n\n        with warnings.catch_warnings():\n            warnings.simplefilter(\"ignore\")\n            d = data.Table(\"test2\")\n\n            vals = [e[0] for e in d]\n            d[[1, 2, 5]] = [42, None, None]\n            vals[1] = vals[2] = vals[5] = 42\n            self.assertEqual([e[0] for e in d], vals)\n\n    @skip_deprecated_length\n    def test_views(self):\n        d = data.Table(\"zoo\")\n        crc = d.checksum(True)\n        x = d[:20]\n        self.assertEqual(crc, d.checksum(True))\n        del x[13]\n        self.assertEqual(crc, d.checksum(True))\n        del x[4:9]\n        self.assertEqual(crc, d.checksum(True))\n\n    def test_bool(self):\n        d = data.Table(\"iris\")\n        self.assertTrue(d)\n\n        d = data.Table(\"test3\")\n        self.assertFalse(d)\n\n        d = data.Table(\"iris\")\n        self.assertTrue(d)\n\n    def test_checksum(self):\n        d = data.Table(\"zoo\")\n        d[42, 3] = 0\n        crc1 = d.checksum(False)\n        d[42, 3] = 1\n        crc2 = d.checksum(False)\n        self.assertNotEqual(crc1, crc2)\n        d[42, 3] = 0\n        crc3 = d.checksum(False)\n        self.assertEqual(crc1, crc3)\n        _ = d[42, \"name\"]\n        d[42, \"name\"] = \"non-animal\"\n        crc4 = d.checksum(False)\n        self.assertEqual(crc1, crc4)\n        crc4 = d.checksum(True)\n        crc5 = d.checksum(1)\n        crc6 = d.checksum(False)\n        self.assertNotEqual(crc1, crc4)\n        self.assertNotEqual(crc1, crc5)\n        self.assertEqual(crc1, crc6)\n\n    def test_total_weight(self):\n        d = data.Table(\"zoo\")\n        self.assertEqual(d.total_weight(), len(d))\n\n        d.set_weights(0)\n        d[0].weight = 0.1\n        d[10].weight = 0.2\n        d[-1].weight = 0.3\n        self.assertAlmostEqual(d.total_weight(), 0.6)\n\n    def test_has_missing(self):\n        d = data.Table(\"zoo\")\n        self.assertFalse(d.has_missing())\n        self.assertFalse(d.has_missing_class())\n\n        d[10, 3] = \"?\"\n        self.assertTrue(d.has_missing())\n        self.assertFalse(d.has_missing_class())\n\n        d[10].set_class(\"?\")\n        self.assertTrue(d.has_missing())\n        self.assertTrue(d.has_missing_class())\n\n        d = data.Table(\"test3\")\n        self.assertFalse(d.has_missing())\n        self.assertFalse(d.has_missing_class())\n\n    def test_shuffle(self):\n        d = data.Table(\"zoo\")\n        crc = d.checksum()\n        names = set(str(x[\"name\"]) for x in d)\n\n        d.shuffle()\n        self.assertNotEqual(crc, d.checksum())\n        self.assertSetEqual(names, set(str(x[\"name\"]) for x in d))\n        crc2 = d.checksum()\n\n        x = d[2:10]\n        crcx = x.checksum()\n        d.shuffle()\n        self.assertNotEqual(crc2, d.checksum())\n        self.assertEqual(crcx, x.checksum())\n\n        crc2 = d.checksum()\n        x.shuffle()\n        self.assertNotEqual(crcx, x.checksum())\n        self.assertEqual(crc2, d.checksum())\n\n    @staticmethod\n    def not_less_ex(ex1, ex2):\n        for v1, v2 in zip(ex1, ex2):\n            if v1 != v2:\n                return v1 < v2\n        return True\n\n    @staticmethod\n    def sorted(d):\n        for i in range(1, len(d)):\n            if not TableTestCase.not_less_ex(d[i - 1], d[i]):\n                return False\n        return True\n\n    @staticmethod\n    def not_less_ex_ord(ex1, ex2, ord):\n        for a in ord:\n            if ex1[a] != ex2[a]:\n                return ex1[a] < ex2[a]\n        return True\n\n    @staticmethod\n    def sorted_ord(d, ord):\n        for i in range(1, len(d)):\n            if not TableTestCase.not_less_ex_ord(d[i - 1], d[i], ord):\n                return False\n        return True\n\n    @skip_deprecated_length\n    def test_append(self):\n        d = data.Table(\"test3\")\n        d.append([None] * 3)\n        self.assertEqual(1, len(d))\n        self.assertTrue(all(isnan(i) for i in d[0]))\n\n        d.append([42, \"0\", None])\n        self.assertEqual(2, len(d))\n        self.assertEqual(d[1], [42, \"0\", None])\n\n        assert_array_nanequal(\n            d.metas,\n            np.array([[v.Unknown for v in d.domain.metas]] * 2,\n                     dtype=object))\n\n    @skip_deprecated_length\n    def test_append2(self):\n        d = data.Table(\"iris\")\n        d.shuffle()\n        l1 = len(d)\n        d.append([1, 2, 3, 4, 0])\n        self.assertEqual(len(d), l1 + 1)\n        self.assertEqual(d[-1], [1, 2, 3, 4, 0])\n\n        x = data.Instance(d[10])\n        d.append(x)\n        self.assertEqual(d[-1], d[10])\n\n        x = d[:50]\n        x.ensure_copy()\n        x.append(d[50])\n        self.assertEqual(x[50], d[50])\n\n    @skip_deprecated_length\n    def test_extend(self):\n        d = data.Table(\"iris\")\n        d.shuffle()\n\n        x = d[:5]\n        x.ensure_copy()\n        d.extend(x)\n        for i in range(5):\n            self.assertEqual(d[i], d[-5 + i])\n\n        y = d[:2, 1]\n        x.ensure_copy()\n        x.extend(y)\n        np.testing.assert_almost_equal(x[-2:, 1].X, y.X)\n        self.assertEqual(np.isnan(x).sum(), 8)\n\n    @skip_deprecated_length\n    def test_extend2(self):\n        d = data.Table(\"test3\")\n        d.extend([[None] * 3,\n                  [None] * 3])\n        assert_array_nanequal(\n            d.metas,\n            np.array([[v.Unknown for v in d.domain.metas]] * 2,\n                     dtype=object))\n\n    def test_copy(self):\n        t = data.Table(np.zeros((5, 3)), np.arange(5), np.zeros((5, 3)))\n\n        copy = t.copy()\n        self.assertTrue(np.all(t.X == copy.X))\n        self.assertTrue(np.all(t.Y == copy.Y))\n        self.assertTrue(np.all(t.metas == copy.metas))\n        copy[0] = [1, 1, 1, 1, 1, 1, 1, 1]\n        self.assertFalse(np.all(t.X == copy.X))\n        self.assertFalse(np.all(t.Y == copy.Y))\n        self.assertFalse(np.all(t.metas == copy.metas))\n\n    def test_copy_sparse(self):\n        t = data.Table('iris').to_sparse()\n        copy = t.copy()\n\n        self.assertEqual((t.X != copy.X).nnz, 0)      # sparse matrices match by content\n        np.testing.assert_equal(t.Y, copy.Y)\n        np.testing.assert_equal(t.metas, copy.metas)\n\n        self.assertNotEqual(id(t.X), id(copy.X))\n        self.assertNotEqual(id(t._Y), id(copy._Y))\n        self.assertNotEqual(id(t.metas), id(copy.metas))\n\n    def test_concatenate(self):\n        d1 = data.Domain([data.ContinuousVariable('a1')])\n        t1 = data.Table.from_numpy(d1, [[1],\n                                        [2]])\n        d2 = data.Domain([data.ContinuousVariable('a2')],\n                         metas=[data.StringVariable('s')])\n        t2 = data.Table.from_numpy(d2, [[3],\n                                        [4]], metas=[['foo'],\n                                                     ['fuu']])\n        self.assertRaises(ValueError,\n                          lambda: data.Table.concatenate((t1, t2), axis=5))\n\n        t3 = data.Table.concatenate((t1, t2))\n        self.assertEqual(t3.domain.attributes,\n                         t1.domain.attributes + t2.domain.attributes)\n        self.assertEqual(len(t3.domain.metas), 1)\n        self.assertEqual(t3.X.shape, (2, 2))\n        self.assertRaises(ValueError, lambda: data.Table.concatenate((t3, t1)))\n        self.assertRaises(ValueError, lambda: data.Table.concatenate((t3, t1), axis=0))\n\n        t4 = data.Table.concatenate((t3, t3), axis=0)\n        np.testing.assert_equal(t4.X, [[1, 3],\n                                       [2, 4],\n                                       [1, 3],\n                                       [2, 4]])\n\n    def test_sparse_concatenate_rows(self):\n        iris = Table(\"iris\")\n        iris.X = sp.csc_matrix(iris.X)\n        new = Table.concatenate([iris, iris], axis=0)\n        self.assertEqual(len(new), 300)\n        self.assertTrue(sp.issparse(new.X), \"Concatenated X is not sparse.\")\n        self.assertFalse(sp.issparse(new.Y), \"Concatenated Y is not dense.\")\n        self.assertFalse(sp.issparse(new.metas), \"Concatenated metas is not dense.\")\n        self.assertEqual(len(new.ids), 300)\n\n    @skip_deprecated_length\n    def test_convert_through_append(self):\n        d = data.Table(\"iris\")\n        dom2 = data.Domain([d.domain[0], d.domain[2], d.domain[4]])\n        d2 = data.Table(dom2)\n        dom3 = data.Domain([d.domain[1], d.domain[2]], None)\n        d3 = data.Table(dom3)\n        for e in d[:5]:\n            d2.append(e)\n            d3.append(e)\n        for e, e2, e3 in zip(d, d2, d3):\n            self.assertEqual(e[0], e2[0])\n            self.assertEqual(e[1], e3[0])\n\n    def test_pickle(self):\n        import pickle\n\n        d = data.Table(\"zoo\")\n        s = pickle.dumps(d)\n        d2 = pickle.loads(s)\n        self.assertEqual(d[0], d2[0])\n\n        self.assertEqual(d.checksum(include_metas=False),\n                         d2.checksum(include_metas=False))\n\n        d = data.Table(\"iris\")\n        s = pickle.dumps(d)\n        d2 = pickle.loads(s)\n        self.assertEqual(d[0], d2[0])\n        self.assertEqual(d.checksum(include_metas=False),\n                         d2.checksum(include_metas=False))\n\n    def test_translate_through_slice(self):\n        d = data.Table(\"iris\")\n        dom = data.Domain([\"petal length\", \"sepal length\", \"iris\"],\n                          source=d.domain)\n        d_ref = d[:10, dom.variables]\n        self.assertEqual(d_ref.domain.class_var, d.domain.class_var)\n        self.assertEqual(d_ref[0, \"petal length\"], d[0, \"petal length\"])\n        self.assertEqual(d_ref[0, \"sepal length\"], d[0, \"sepal length\"])\n        self.assertEqual(d_ref.X.shape, (10, 2))\n        self.assertEqual(d_ref.Y.shape, (10,))\n\n    def test_saveTab(self):\n        d = data.Table(\"iris\")[:3]\n        d.save(\"test-save.tab\")\n        try:\n            d2 = data.Table(\"test-save.tab\")\n            for e1, e2 in zip(d, d2):\n                self.assertEqual(e1, e2)\n        finally:\n            os.remove(\"test-save.tab\")\n            os.remove(\"test-save.tab.metadata\")\n\n        dom = data.Domain([data.ContinuousVariable(\"a\")])\n        d = data.Table(dom, [[i] for i in range(3)])\n        d.save(\"test-save.tab\")\n        try:\n            d2 = data.Table(\"test-save.tab\")\n            self.assertEqual(len(d.domain.attributes), 1)\n            self.assertEqual(d.domain.class_var, None)\n            for i in range(3):\n                self.assertEqual(d2[i], [i])\n        finally:\n            os.remove(\"test-save.tab\")\n\n        dom = data.Domain([data.ContinuousVariable(\"a\")], None)\n        d = data.Table(dom, [[i] for i in range(3)])\n        d.save(\"test-save.tab\")\n        try:\n            d2 = data.Table(\"test-save.tab\")\n            self.assertEqual(len(d.domain.attributes), 1)\n            for i in range(3):\n                self.assertEqual(d2[i], [i])\n        finally:\n            os.remove(\"test-save.tab\")\n\n        d = data.Table(\"zoo\")\n        d.save(\"test-zoo.tab\")\n        dd = data.Table(\"test-zoo\")\n        try:\n            self.assertTupleEqual(d.domain.metas, dd.domain.metas,\n                                  msg=\"Meta attributes don't match.\")\n            self.assertTupleEqual(d.domain.variables, dd.domain.variables,\n                                  msg=\"Attributes don't match.\")\n\n            np.testing.assert_almost_equal(d.W, dd.W,\n                                           err_msg=\"Weights don't match.\")\n            for i in range(10):\n                for j in d.domain.variables:\n                    self.assertEqual(d[i][j], dd[i][j])\n        finally:\n            os.remove(\"test-zoo.tab\")\n\n        d = data.Table(\"zoo\")\n        d.set_weights(range(len(d)))\n        d.save(\"test-zoo-weights.tab\")\n        dd = data.Table(\"test-zoo-weights\")\n        try:\n            self.assertTupleEqual(d.domain.metas, dd.domain.metas,\n                                  msg=\"Meta attributes don't match.\")\n            self.assertTupleEqual(d.domain.variables, dd.domain.variables,\n                                  msg=\"Attributes don't match.\")\n\n            np.testing.assert_almost_equal(d.W, dd.W,\n                                           err_msg=\"Weights don't match.\")\n            for i in range(10):\n                for j in d.domain.variables:\n                    self.assertEqual(d[i][j], dd[i][j])\n        finally:\n            os.remove(\"test-zoo-weights.tab\")\n\n    def test_save_pickle(self):\n        table = data.Table(\"iris\")\n        try:\n            table.save(\"iris.pickle\")\n            table2 = data.Table.from_file(\"iris.pickle\")\n            np.testing.assert_almost_equal(table.X, table2.X)\n            np.testing.assert_almost_equal(table.Y, table2.Y)\n            self.assertEqual(table.domain[0], table2.domain[0])\n        finally:\n            os.remove(\"iris.pickle\")\n\n    def test_from_numpy(self):\n        a = np.arange(20, dtype=\"d\").reshape((4, 5))\n        a[:, -1] = [0, 0, 0, 1]\n        dom = data.Domain([data.ContinuousVariable(x) for x in \"abcd\"],\n                          data.DiscreteVariable(\"e\", values=[\"no\", \"yes\"]))\n        table = data.Table(dom, a)\n        for i in range(4):\n            self.assertEqual(table[i].get_class(), \"no\" if i < 3 else \"yes\")\n            for j in range(5):\n                self.assertEqual(a[i, j], table[i, j])\n                table[i, j] = random.random()\n                self.assertEqual(a[i, j], table[i, j])\n\n        with self.assertRaises(IndexError):\n            table[0, -5] = 5\n\n    def test_filter_is_defined(self):\n        d = data.Table(\"iris\")\n        d[1, 4] = Unknown\n        self.assertTrue(isnan(d[1, 4]))\n        d[140, 0] = Unknown\n        e = filter.IsDefined()(d)\n        self.assertEqual(len(e), len(d) - 2)\n        self.assertEqual(e[0], d[0])\n        self.assertEqual(e[1], d[2])\n        self.assertEqual(e[147], d[149])\n        self.assertTrue(d.has_missing())\n        self.assertFalse(e.has_missing())\n\n    def test_filter_has_class(self):\n        d = data.Table(\"iris\")\n        d[1, 4] = Unknown\n        self.assertTrue(isnan(d[1, 4]))\n        d[140, 0] = Unknown\n        e = filter.HasClass()(d)\n        self.assertEqual(len(e), len(d) - 1)\n        self.assertEqual(e[0], d[0])\n        self.assertEqual(e[1], d[2])\n        self.assertEqual(e[148], d[149])\n        self.assertTrue(d.has_missing())\n        self.assertTrue(e.has_missing())\n        self.assertFalse(e.has_missing_class())\n\n    def test_filter_random(self):\n        d = data.Table(\"iris\")\n        e = filter.Random(50)(d)\n        self.assertEqual(len(e), 50)\n        e = filter.Random(50, negate=True)(d)\n        self.assertEqual(len(e), 100)\n        for i in range(5):\n            e = filter.Random(0.2)(d)\n            self.assertEqual(len(e), 30)\n            bc = np.bincount(np.array(e.Y[:], dtype=int))\n            if min(bc) > 7:\n                break\n        else:\n            self.fail(\"Filter returns too uneven distributions\")\n\n    def test_filter_values_nested(self):\n        d = data.Table(\"iris\")\n        f1 = filter.FilterContinuous(d.columns.sepal_length,\n                                     filter.FilterContinuous.Between,\n                                     min=4.5, max=5.0)\n        f2 = filter.FilterContinuous(d.columns.sepal_width,\n                                     filter.FilterContinuous.Between,\n                                     min=3.1, max=3.4)\n        f3 = filter.FilterDiscrete(d.columns.iris, [0, 1])\n        f = filter.Values([filter.Values([f1, f2], conjunction=False), f3])\n        self.assertEqual(41, len(f(d)))\n\n    def test_filter_string_works_for_numeric_columns(self):\n        var = StringVariable(\"s\")\n        data = Table(Domain([], metas=[var]), [[x] for x in range(21)])\n        # 1, 2, 3, ..., 18, 19, 20\n\n        fs = filter.FilterString\n        filters = [\n            ((fs.Greater, \"5\"), dict(rows=4)),\n            # 6, 7, 8, 9\n            ((fs.Between, \"15\", \"2\"), dict(rows=6)),\n            # 15, 16, 17, 18, 19, 2\n            ((fs.Contains, \"2\"), dict(rows=3)),\n            # 2, 12, 20\n        ]\n\n        for args, expected in filters:\n            f = fs(var, *args)\n            filtered_data = filter.Values([f])(data)\n            self.assertEqual(len(filtered_data), expected[\"rows\"],\n                             \"{} returned wrong number of rows\".format(args))\n\n    def test_filter_value_continuous(self):\n        d = data.Table(\"iris\")\n        col = d.X[:, 2]\n\n        v = d.columns\n        f = filter.FilterContinuous(v.petal_length,\n                                    filter.FilterContinuous.Between,\n                                    min=4.5, max=5.1)\n\n        x = filter.Values([f])(d)\n        self.assertTrue(np.all(x.X[:, 2] >= 4.5))\n        self.assertTrue(np.all(x.X[:, 2] <= 5.1))\n        self.assertEqual(sum((col >= 4.5) * (col <= 5.1)), len(x))\n\n        f.ref = 5.1\n        f.oper = filter.FilterContinuous.Equal\n        x = filter.Values([f])(d)\n        self.assertTrue(np.all(x.X[:, 2] == 5.1))\n        self.assertEqual(sum(col == 5.1), len(x))\n\n        f.oper = filter.FilterContinuous.NotEqual\n        x = filter.Values([f])(d)\n        self.assertTrue(np.all(x.X[:, 2] != 5.1))\n        self.assertEqual(sum(col != 5.1), len(x))\n\n        f.oper = filter.FilterContinuous.Less\n        x = filter.Values([f])(d)\n        self.assertTrue(np.all(x.X[:, 2] < 5.1))\n        self.assertEqual(sum(col < 5.1), len(x))\n\n        f.oper = filter.FilterContinuous.LessEqual\n        x = filter.Values([f])(d)\n        self.assertTrue(np.all(x.X[:, 2] <= 5.1))\n        self.assertEqual(sum(col <= 5.1), len(x))\n\n        f.oper = filter.FilterContinuous.Greater\n        x = filter.Values([f])(d)\n        self.assertTrue(np.all(x.X[:, 2] > 5.1))\n        self.assertEqual(sum(col > 5.1), len(x))\n\n        f.oper = filter.FilterContinuous.GreaterEqual\n        x = filter.Values([f])(d)\n        self.assertTrue(np.all(x.X[:, 2] >= 5.1))\n        self.assertEqual(sum(col >= 5.1), len(x))\n\n        f.oper = filter.FilterContinuous.Outside\n        f.ref, f.max = 4.5, 5.1\n        x = filter.Values([f])(d)\n        for e in x:\n            self.assertTrue(e[2] < 4.5 or e[2] > 5.1)\n        self.assertEqual(sum((col < 4.5) + (col > 5.1)), len(x))\n\n        f.oper = filter.FilterContinuous.IsDefined\n        f.ref = f.max = None\n        x = filter.Values([f])(d)\n        self.assertEqual(len(x), len(d))\n\n        d[:30, v.petal_length] = Unknown\n        x = filter.Values([f])(d)\n        self.assertEqual(len(x), len(d) - 30)\n\n    def test_filter_value_continuous_args(self):\n        d = data.Table(\"iris\")\n        col = d.X[:, 2]\n        v = d.columns\n\n        f = filter.FilterContinuous(v.petal_length,\n                                    filter.FilterContinuous.Equal, ref=5.1)\n        x = filter.Values([f])(d)\n        self.assertTrue(np.all(x.X[:, 2] == 5.1))\n        self.assertEqual(sum(col == 5.1), len(x))\n\n        f = filter.FilterContinuous(2,\n                                    filter.FilterContinuous.Equal, ref=5.1)\n        self.assertTrue(np.all(x.X[:, 2] == 5.1))\n        self.assertEqual(sum(col == 5.1), len(x))\n\n        f = filter.FilterContinuous(\"petal length\",\n                                    filter.FilterContinuous.Equal, ref=5.1)\n        self.assertTrue(np.all(x.X[:, 2] == 5.1))\n        self.assertEqual(sum(col == 5.1), len(x))\n\n        f = filter.FilterContinuous(\"sepal length\",\n                                    filter.FilterContinuous.Equal, ref=5.1)\n        f.column = 2\n        self.assertTrue(np.all(x.X[:, 2] == 5.1))\n        self.assertEqual(sum(col == 5.1), len(x))\n\n        f = filter.FilterContinuous(\"sepal length\",\n                                    filter.FilterContinuous.Equal, ref=5.1)\n        f.column = v.petal_length\n        self.assertTrue(np.all(x.X[:, 2] == 5.1))\n        self.assertEqual(sum(col == 5.1), len(x))\n\n        f = filter.FilterContinuous(v.petal_length,\n                                    filter.FilterContinuous.Equal, ref=18)\n        f.ref = 5.1\n        x = filter.Values([f])(d)\n        self.assertTrue(np.all(x.X[:, 2] == 5.1))\n        self.assertEqual(sum(col == 5.1), len(x))\n\n        f = filter.FilterContinuous(v.petal_length,\n                                    filter.FilterContinuous.Equal, ref=18)\n        f.ref = 5.1\n        x = filter.Values([f])(d)\n        self.assertTrue(np.all(x.X[:, 2] == 5.1))\n        self.assertEqual(sum(col == 5.1), len(x))\n\n    def test_valueFilter_discrete(self):\n        d = data.Table(\"zoo\")\n\n        f = filter.FilterDiscrete(d.domain.class_var, values=[2, 3, 4])\n        for e in filter.Values([f])(d):\n            self.assertTrue(e.get_class() in [2, 3, 4])\n\n        f.values = [\"mammal\"]\n        for e in filter.Values([f])(d):\n            self.assertEqual(e.get_class(), \"mammal\")\n\n        f = filter.FilterDiscrete(d.domain.class_var, values=[2, \"mammal\"])\n        for e in filter.Values([f])(d):\n            self.assertTrue(e.get_class() in [2, \"mammal\"])\n\n        f = filter.FilterDiscrete(d.domain.class_var, values=[2, \"martian\"])\n        self.assertRaises(ValueError, d._filter_values, f)\n\n        f = filter.FilterDiscrete(d.domain.class_var, values=[2, data.Table])\n        self.assertRaises(TypeError, d._filter_values, f)\n\n        v = d.columns\n        f = filter.FilterDiscrete(v.hair, values=None)\n        self.assertEqual(len(filter.Values([f])(d)), len(d))\n\n        d[:5, v.hair] = Unknown\n        self.assertEqual(len(filter.Values([f])(d)), len(d) - 5)\n\n    def test_valueFilter_string_is_defined(self):\n        d = data.Table(\"test9.tab\")\n        f = filter.FilterString(-5, filter.FilterString.IsDefined)\n        x = filter.Values([f])(d)\n        self.assertEqual(len(x), 7)\n\n    def test_valueFilter_discrete_meta_is_defined(self):\n        d = data.Table(\"test9.tab\")\n        f = filter.FilterDiscrete(-4, None)\n        x = filter.Values([f])(d)\n        self.assertEqual(len(x), 8)\n\n    def test_valueFilter_string_case_sens(self):\n        d = data.Table(\"zoo\")\n        col = d[:, \"name\"].metas[:, 0]\n\n        f = filter.FilterString(\"name\",\n                                filter.FilterString.Equal, \"girl\")\n        x = filter.Values([f])(d)\n        self.assertEqual(len(x), 1)\n        self.assertEqual(x[0, \"name\"], \"girl\")\n        self.assertTrue(np.all(x.metas == \"girl\"))\n\n        f.oper = f.NotEqual\n        x = filter.Values([f])(d)\n        self.assertEqual(len(x), len(d) - 1)\n        self.assertTrue(np.all(x[:, \"name\"] != \"girl\"))\n\n        f.oper = f.Less\n        x = filter.Values([f])(d)\n        self.assertEqual(len(x), sum(col < \"girl\"))\n        self.assertTrue(np.all(x.metas < \"girl\"))\n\n        f.oper = f.LessEqual\n        x = filter.Values([f])(d)\n        self.assertEqual(len(x), sum(col <= \"girl\"))\n        self.assertTrue(np.all(x.metas <= \"girl\"))\n\n        f.oper = f.Greater\n        x = filter.Values([f])(d)\n        self.assertEqual(len(x), sum(col > \"girl\"))\n        self.assertTrue(np.all(x.metas > \"girl\"))\n\n        f.oper = f.GreaterEqual\n        x = filter.Values([f])(d)\n        self.assertEqual(len(x), sum(col >= \"girl\"))\n        self.assertTrue(np.all(x.metas >= \"girl\"))\n\n        f.oper = f.Between\n        f.max = \"lion\"\n        x = filter.Values([f])(d)\n        self.assertEqual(len(x), sum((col >= \"girl\") * (col <= \"lion\")))\n        self.assertTrue(np.all(x.metas >= \"girl\"))\n        self.assertTrue(np.all(x.metas <= \"lion\"))\n\n        f.oper = f.Outside\n        x = filter.Values([f])(d)\n        self.assertEqual(len(x), sum(col < \"girl\") + sum(col > \"lion\"))\n        self.assertTrue(np.all((x.metas < \"girl\") + (x.metas > \"lion\")))\n\n        f.oper = f.Contains\n        f.ref = \"ea\"\n        x = filter.Values([f])(d)\n        for e in x:\n            self.assertTrue(\"ea\" in e[\"name\"])\n        self.assertEqual(len(x), len([e for e in col if \"ea\" in e]))\n\n        f.oper = f.StartsWith\n        f.ref = \"sea\"\n        x = filter.Values([f])(d)\n        for e in x:\n            self.assertTrue(str(e[\"name\"]).startswith(\"sea\"))\n        self.assertEqual(len(x), len([e for e in col if e.startswith(\"sea\")]))\n\n        f.oper = f.EndsWith\n        f.ref = \"ion\"\n        x = filter.Values([f])(d)\n        for e in x:\n            self.assertTrue(str(e[\"name\"]).endswith(\"ion\"))\n        self.assertEqual(len(x), len([e for e in col if e.endswith(\"ion\")]))\n\n    def test_valueFilter_string_case_insens(self):\n        d = data.Table(\"zoo\")\n        d[d[:, \"name\"].metas[:, 0] == \"girl\", \"name\"] = \"GIrl\"\n\n        col = d[:, \"name\"].metas[:, 0]\n\n        f = filter.FilterString(\"name\",\n                                filter.FilterString.Equal, \"giRL\")\n        f.case_sensitive = False\n        x = filter.Values([f])(d)\n        self.assertEqual(len(x), 1)\n        self.assertEqual(x[0, \"name\"], \"GIrl\")\n        self.assertTrue(np.all(x.metas == \"GIrl\"))\n\n        f.oper = f.NotEqual\n        x = filter.Values([f])(d)\n        self.assertEqual(len(x), len(d) - 1)\n        self.assertTrue(np.all(x[:, \"name\"] != \"GIrl\"))\n\n        f.oper = f.Less\n        f.ref = \"CHiCKEN\"\n        x = filter.Values([f])(d)\n        self.assertEqual(len(x), sum(col < \"chicken\") - 1)  # girl!\n        self.assertTrue(np.all(x.metas < \"chicken\"))\n\n        f.oper = f.LessEqual\n        x = filter.Values([f])(d)\n        self.assertEqual(len(x), sum(col <= \"chicken\") - 1)\n        self.assertTrue(np.all(x.metas <= \"chicken\"))\n\n        f.oper = f.Greater\n        x = filter.Values([f])(d)\n        self.assertEqual(len(x), sum(col > \"chicken\") + 1)\n        for e in x:\n            self.assertGreater(str(e[\"name\"]).lower(), \"chicken\")\n\n        f.oper = f.GreaterEqual\n        x = filter.Values([f])(d)\n        self.assertEqual(len(x), sum(col >= \"chicken\") + 1)\n        for e in x:\n            self.assertGreaterEqual(str(e[\"name\"]).lower(), \"chicken\")\n\n        f.oper = f.Between\n        f.max = \"liOn\"\n        x = filter.Values([f])(d)\n        self.assertEqual(len(x), sum((col >= \"chicken\") * (col <= \"lion\")) + 1)\n        for e in x:\n            self.assertTrue(\"chicken\" <= str(e[\"name\"]).lower() <= \"lion\")\n\n        f.oper = f.Outside\n        x = filter.Values([f])(d)\n        self.assertEqual(len(x), sum(col < \"chicken\") + sum(col > \"lion\") - 1)\n        self.assertTrue(np.all((x.metas < \"chicken\") + (x.metas > \"lion\")))\n\n        f.oper = f.Contains\n        f.ref = \"iR\"\n        x = filter.Values([f])(d)\n        for e in x:\n            self.assertTrue(\"ir\" in str(e[\"name\"]).lower())\n        self.assertEqual(len(x), len([e for e in col if \"ir\" in e]) + 1)\n\n        f.oper = f.StartsWith\n        f.ref = \"GI\"\n        x = filter.Values([f])(d)\n        for e in x:\n            self.assertTrue(str(e[\"name\"]).lower().startswith(\"gi\"))\n        self.assertEqual(len(x),\n                         len([e for e in col if e.lower().startswith(\"gi\")]))\n\n        f.oper = f.EndsWith\n        f.ref = \"ion\"\n        x = filter.Values([f])(d)\n        for e in x:\n            self.assertTrue(str(e[\"name\"]).endswith(\"ion\"))\n            self.assertTrue(str(e[\"name\"]).endswith(\"ion\"))\n        self.assertEqual(len(x), len([e for e in col if e.endswith(\"ion\")]))\n\n    def test_valueFilter_regex(self):\n        d = data.Table(\"zoo\")\n        f = filter.FilterRegex(d.domain['name'], '^c...$')\n        x = filter.Values([f])(d)\n        self.assertEqual(len(x), 7)\n\n    def test_valueFilter_stringList(self):\n        data = Table(\"zoo\")\n        var = data.domain[\"name\"]\n\n        fs = filter.FilterStringList\n        filters = [\n            (([\"swan\", \"tuna\", \"wasp\"], True), dict(rows=3)),\n            (([\"swan\", \"tuna\", \"wasp\"], False), dict(rows=3)),\n            (([\"WoRm\", \"TOad\", \"vOLe\"], True), dict(rows=0)),\n            (([\"WoRm\", \"TOad\", \"vOLe\"], False), dict(rows=3)),\n        ]\n\n        for args, expected in filters:\n            f = fs(var, *args)\n            filtered_data = filter.Values([f])(data)\n            self.assertEqual(len(filtered_data), expected[\"rows\"],\n                             \"{} returned wrong number of rows\".format(args))\n\n    def test_table_dtypes(self):\n        table = data.Table(\"iris\")\n        metas = np.hstack((table.metas, table.Y.reshape(len(table), 1)))\n        attributes_metas = table.domain.metas + table.domain.class_vars\n        domain_metas = data.Domain(table.domain.attributes,\n                                   table.domain.class_vars,\n                                   attributes_metas)\n        table_metas = data.Table(domain_metas, table.X, table.Y, metas)\n        new_table = data.Table(data.Domain(table_metas.domain.metas,\n                                           table_metas.domain.metas,\n                                           table_metas.domain.metas),\n                               table_metas)\n        self.assertEqual(new_table.X.dtype, np.float64)\n        self.assertEqual(new_table.Y.dtype, np.float64)\n        self.assertEqual(new_table.metas.dtype, np.float64)\n\n    def test_attributes(self):\n        table = data.Table(\"iris\")\n        table.attributes = {1: \"test\"}\n        table2 = table[:4]\n        self.assertEqual(table2.attributes[1], \"test\")\n        table2.attributes[1] = \"modified\"\n        self.assertEqual(table.attributes[1], \"modified\")\n\n    # TODO Test conjunctions and disjunctions of conditions\n\n    def test_is_sparse(self):\n        table = data.Table(\"iris\")\n        self.assertFalse(table.is_sparse())\n\n        table.X = sp.csr_matrix(table.X)\n        self.assertTrue(table.is_sparse())\n\n    def test_repr_sparse_with_one_row(self):\n        table = data.Table(\"iris\")[:1]\n        table.X = sp.csr_matrix(table.X)\n        repr(table)     # make sure repr does not crash\n\n    def test_inf(self):\n        a = np.array([[2,   0,      0,      0],\n                      [0,   np.nan, np.nan, 1],\n                      [0,   0,      np.inf, 0]])\n        with self.assertWarns(Warning):\n            tab = data.Table(a)\n        self.assertEqual(tab.get_nan_frequency_attribute(), 3/12)\n\n\ndef column_sizes(table):\n    return (len(table.domain.attributes),\n            len(table.domain.class_vars),\n            len(table.domain.metas))\n\n\nclass TableTests(unittest.TestCase):\n    attributes = [\"Feature %i\" % i for i in range(10)]\n    class_vars = [\"Class %i\" % i for i in range(1)]\n    metas = [\"Meta %i\" % i for i in range(5)]\n    nrows = 10\n    row_indices = (1, 5, 7, 9)\n\n    data = np.random.random((nrows, len(attributes)))\n    class_data = np.random.random((nrows, len(class_vars)))\n    meta_data = np.random.random((nrows, len(metas)))\n    weight_data = np.random.random((nrows, 1))\n\n    def setUp(self):\n        self.data = np.random.random((self.nrows, len(self.attributes)))\n        self.class_data = np.random.random((self.nrows, len(self.class_vars)))\n        if len(self.class_vars) == 1:\n            self.class_data = self.class_data.flatten()\n        self.meta_data = np.random.randint(0, 5, (self.nrows, len(self.metas))\n                                          ).astype(object)\n        self.weight_data = np.random.random((self.nrows, 1))\n\n    def mock_domain(self, with_classes=False, with_metas=False):\n        attributes = self.attributes\n        class_vars = self.class_vars if with_classes else []\n        metas = self.metas if with_metas else []\n        variables = attributes + class_vars\n        return MagicMock(data.Domain,\n                         attributes=attributes,\n                         class_vars=class_vars,\n                         metas=metas,\n                         variables=variables)\n\n    def create_domain(self, attributes=(), classes=(), metas=()):\n        attr_vars = [data.ContinuousVariable(name=a) if isinstance(a, str)\n                     else a for a in attributes]\n        class_vars = [data.ContinuousVariable(name=c) if isinstance(c, str)\n                      else c for c in classes]\n        meta_vars = [data.DiscreteVariable(name=m, values=map(str, range(5)))\n                     if isinstance(m, str) else m for m in metas]\n\n        domain = data.Domain(attr_vars, class_vars, meta_vars)\n        return domain\n\n\nclass CreateEmptyTable(TableTests):\n    def test_calling_new_with_no_parameters_constructs_a_new_instance(self):\n        table = data.Table()\n        self.assertIsInstance(table, data.Table)\n\n    def test_table_has_file(self):\n        table = data.Table()\n        self.assertIsNone(table.__file__)\n\n\nclass CreateTableWithFilename(TableTests):\n    filename = \"data.tab\"\n\n    @patch(\"os.path.exists\", Mock(return_value=True))\n    def test_read_data_calls_reader(self):\n        table_mock = Mock(data.Table)\n        reader_instance = Mock(read=Mock(return_value=table_mock))\n        reader_mock = Mock(return_value=reader_instance)\n\n        with patch.dict(data.io.FileFormat.readers,\n                        {'.xlsx': reader_mock}):\n            table = data.Table.from_file(\"test.xlsx\")\n\n        reader_mock.assert_called_with(\"test.xlsx\")\n        reader_instance.read.assert_called_with()\n        self.assertEqual(table, table_mock)\n\n    @patch(\"os.path.exists\", Mock(return_value=False))\n    def test_raises_error_if_file_does_not_exist(self):\n        with self.assertRaises(IOError):\n            data.Table.from_file(self.filename)\n\n    @patch(\"os.path.exists\", Mock(return_value=True))\n    def test_raises_error_if_file_has_unknown_extension(self):\n        with self.assertRaises(IOError):\n            data.Table.from_file(\"file.invalid_extension\")\n\n    @patch(\"Orange.data.table.Table.from_file\")\n    def test_calling_new_with_string_argument_calls_read_data(self, read_data):\n        data.Table(self.filename)\n\n        read_data.assert_called_with(self.filename)\n\n    @patch(\"Orange.data.table.Table.from_file\")\n    def test_calling_new_with_keyword_argument_filename_calls_read_data(\n            self, read_data):\n        data.Table(filename=self.filename)\n\n        read_data.assert_called_with(self.filename)\n\n\nclass CreateTableWithUrl(TableTests):\n    def test_url_no_scheme(self):\n\n        class SkipRest(Exception):\n            pass\n\n        mock_urlopen = Mock(side_effect=SkipRest())\n        url = 'www.foo.bar/xx.csv'\n\n        with patch('Orange.data.io.UrlReader.urlopen', mock_urlopen):\n            try:\n                Table.from_url(url)\n            except SkipRest:\n                pass\n\n        mock_urlopen.assert_called_once_with('http://' + url)\n\n    class _MockUrlOpen(MagicMock):\n        headers = {'content-disposition': 'attachment; filename=\"Something-FormResponses.tsv\"; '\n                                          'filename*=UTF-8''Something%20%28Responses%29.tsv'}\n        def __enter__(self):\n            return self\n\n        def __exit__(self, *args, **kwargs):\n            pass\n\n        def read(self):\n            return b'''\\\na\\tb\\tc\n1\\t2\\t3\n2\\t3\\t4'''\n\n    urlopen = _MockUrlOpen()\n\n    @patch('Orange.data.io.urlopen', urlopen)\n    def test_trimmed_urls(self):\n        for url in ('https://docs.google.com/spreadsheets/d/ABCD/edit',\n                    'https://www.dropbox.com/s/ABCD/filename.csv'):\n            self._MockUrlOpen.url = url\n            d = data.Table(url)\n            request = self.urlopen.call_args[0][0]\n            self.assertNotEqual(url, request.full_url)\n            self.assertIn('Mozilla/5.0', request.headers.get('User-agent', ''))\n            self.assertEqual(len(d), 2)\n            self.assertEqual(d.name, 'Something-FormResponses')\n\n\nclass CreateTableWithDomain(TableTests):\n    def test_creates_an_empty_table_with_given_domain(self):\n        domain = self.mock_domain()\n        table = data.Table.from_domain(domain)\n\n        self.assertEqual(table.domain, domain)\n\n    def test_creates_zero_filled_rows_in_X_if_domain_contains_attributes(self):\n        domain = self.mock_domain()\n        table = data.Table.from_domain(domain, self.nrows)\n\n        self.assertEqual(table.X.shape, (self.nrows, len(domain.attributes)))\n        self.assertFalse(table.X.any())\n\n    def test_creates_zero_filled_rows_in_Y_if_domain_contains_class_vars(self):\n        domain = self.mock_domain(with_classes=True)\n        table = data.Table.from_domain(domain, self.nrows)\n\n        if len(domain.class_vars) != 1:\n            self.assertEqual(table.Y.shape,\n                             (self.nrows, len(domain.class_vars)))\n        else:\n            self.assertEqual(table.Y.shape, (self.nrows,))\n        self.assertFalse(table.Y.any())\n\n    def test_creates_zero_filled_rows_in_metas_if_domain_contains_metas(self):\n        domain = self.mock_domain(with_metas=True)\n        table = data.Table.from_domain(domain, self.nrows)\n\n        self.assertEqual(table.metas.shape, (self.nrows, len(domain.metas)))\n        self.assertFalse(table.metas.any())\n\n    def test_creates_weights_if_weights_are_true(self):\n        domain = self.mock_domain()\n        table = data.Table.from_domain(domain, self.nrows, True)\n\n        self.assertEqual(table.W.shape, (self.nrows, ))\n\n    def test_does_not_create_weights_if_weights_are_false(self):\n        domain = self.mock_domain()\n        table = data.Table.from_domain(domain, self.nrows, False)\n\n        self.assertEqual(table.W.shape, (self.nrows, 0))\n\n    @patch(\"Orange.data.table.Table.from_domain\")\n    def test_calling_new_with_domain_calls_new_from_domain(\n            self, new_from_domain):\n        domain = self.mock_domain()\n        data.Table(domain)\n\n        new_from_domain.assert_called_with(domain)\n\n\nclass CreateTableWithData(TableTests):\n    def test_creates_a_table_with_given_X(self):\n        # from numpy\n        table = data.Table(np.array(self.data))\n        self.assertIsInstance(table.domain, data.Domain)\n        np.testing.assert_almost_equal(table.X, self.data)\n\n        # from list\n        table = data.Table(list(self.data))\n        self.assertIsInstance(table.domain, data.Domain)\n        np.testing.assert_almost_equal(table.X, self.data)\n\n        # from tuple\n        table = data.Table(tuple(self.data))\n        self.assertIsInstance(table.domain, data.Domain)\n        np.testing.assert_almost_equal(table.X, self.data)\n\n    def test_creates_a_table_from_domain_and_list(self):\n        domain = data.Domain([data.DiscreteVariable(name=\"a\", values=\"mf\"),\n                              data.ContinuousVariable(name=\"b\")],\n                             data.DiscreteVariable(name=\"y\", values=\"abc\"))\n        table = data.Table(domain, [[0, 1, 2],\n                                    [1, 2, \"?\"],\n                                    [\"m\", 3, \"a\"],\n                                    [\"?\", \"?\", \"c\"]])\n        self.assertIs(table.domain, domain)\n        np.testing.assert_almost_equal(\n            table.X, np.array([[0, 1], [1, 2], [0, 3], [np.nan, np.nan]]))\n        np.testing.assert_almost_equal(table.Y, np.array([2, np.nan, 0, 2]))\n\n    def test_creates_a_table_from_domain_and_list_and_weights(self):\n        domain = data.Domain([data.DiscreteVariable(name=\"a\", values=\"mf\"),\n                              data.ContinuousVariable(name=\"b\")],\n                             data.DiscreteVariable(name=\"y\", values=\"abc\"))\n        table = data.Table(domain, [[0, 1, 2],\n                                    [1, 2, \"?\"],\n                                    [\"m\", 3, \"a\"],\n                                    [\"?\", \"?\", \"c\"]], [1, 2, 3, 4])\n        self.assertIs(table.domain, domain)\n        np.testing.assert_almost_equal(\n            table.X, np.array([[0, 1], [1, 2], [0, 3], [np.nan, np.nan]]))\n        np.testing.assert_almost_equal(table.Y, np.array([2, np.nan, 0, 2]))\n        np.testing.assert_almost_equal(table.W, np.array([1, 2, 3, 4]))\n\n    def test_creates_a_table_from_domain_and_list_and_metas(self):\n        metas = [data.DiscreteVariable(\"Meta 1\", values=\"XYZ\"),\n                 data.ContinuousVariable(\"Meta 2\"),\n                 data.StringVariable(\"Meta 3\")]\n        domain = data.Domain([data.DiscreteVariable(name=\"a\", values=\"mf\"),\n                              data.ContinuousVariable(name=\"b\")],\n                             data.DiscreteVariable(name=\"y\", values=\"abc\"),\n                             metas=metas)\n        table = data.Table(domain, [[0, 1, 2, \"X\", 2, \"bb\"],\n                                    [1, 2, \"?\", \"Y\", 1, \"aa\"],\n                                    [\"m\", 3, \"a\", \"Z\", 3, \"bb\"],\n                                    [\"?\", \"?\", \"c\", \"X\", 1, \"aa\"]])\n        self.assertIs(table.domain, domain)\n        np.testing.assert_almost_equal(\n            table.X, np.array([[0, 1], [1, 2], [0, 3], [np.nan, np.nan]]))\n        np.testing.assert_almost_equal(table.Y, np.array([2, np.nan, 0, 2]))\n        np.testing.assert_array_equal(table.metas,\n                                      np.array([[0, 2., \"bb\"],\n                                                [1, 1., \"aa\"],\n                                                [2, 3., \"bb\"],\n                                                [0, 1., \"aa\"]],\n                                               dtype=object))\n\n    def test_creates_a_table_from_list_of_instances(self):\n        table = data.Table('iris')\n        new_table = data.Table(table.domain, [d for d in table])\n        self.assertIs(table.domain, new_table.domain)\n        np.testing.assert_almost_equal(table.X, new_table.X)\n        np.testing.assert_almost_equal(table.Y, new_table.Y)\n        np.testing.assert_almost_equal(table.W, new_table.W)\n        self.assertEqual(table.domain, new_table.domain)\n        np.testing.assert_array_equal(table.metas, new_table.metas)\n\n    def test_creates_a_table_from_list_of_instances_with_metas(self):\n        table = data.Table('zoo')\n        new_table = data.Table(table.domain, [d for d in table])\n        self.assertIs(table.domain, new_table.domain)\n        np.testing.assert_almost_equal(table.X, new_table.X)\n        np.testing.assert_almost_equal(table.Y, new_table.Y)\n        np.testing.assert_almost_equal(table.W, new_table.W)\n        self.assertEqual(table.domain, new_table.domain)\n        np.testing.assert_array_equal(table.metas, new_table.metas)\n\n    def test_creates_a_table_with_domain_and_given_X(self):\n        domain = self.mock_domain()\n\n        table = data.Table(domain, self.data)\n        self.assertIsInstance(table.domain, data.Domain)\n        self.assertEqual(table.domain, domain)\n        np.testing.assert_almost_equal(table.X, self.data)\n\n    def test_creates_a_table_with_given_X_and_Y(self):\n        table = data.Table(self.data, self.class_data)\n\n        self.assertIsInstance(table.domain, data.Domain)\n        np.testing.assert_almost_equal(table.X, self.data)\n        np.testing.assert_almost_equal(table.Y, self.class_data)\n\n    def test_creates_a_table_with_given_X_Y_and_metas(self):\n        table = data.Table(self.data, self.class_data, self.meta_data)\n\n        self.assertIsInstance(table.domain, data.Domain)\n        np.testing.assert_almost_equal(table.X, self.data)\n        np.testing.assert_almost_equal(table.Y, self.class_data)\n        np.testing.assert_almost_equal(table.metas, self.meta_data)\n\n    def test_creates_a_discrete_class_if_Y_has_few_distinct_values(self):\n        Y = np.array([float(np.random.randint(0, 2)) for i in self.data])\n        table = data.Table(self.data, Y, self.meta_data)\n\n        np.testing.assert_almost_equal(table.Y, Y)\n        self.assertIsInstance(table.domain.class_vars[0],\n                              data.DiscreteVariable)\n        self.assertEqual(table.domain.class_vars[0].values, [\"v1\", \"v2\"])\n\n    def test_creates_a_table_with_given_domain(self):\n        domain = self.mock_domain()\n        table = data.Table.from_numpy(domain, self.data)\n\n        self.assertEqual(table.domain, domain)\n\n    def test_sets_Y_if_given(self):\n        domain = self.mock_domain(with_classes=True)\n        table = data.Table.from_numpy(domain, self.data, self.class_data)\n\n        np.testing.assert_almost_equal(table.Y, self.class_data)\n\n    def test_sets_metas_if_given(self):\n        domain = self.mock_domain(with_metas=True)\n        table = data.Table.from_numpy(domain, self.data, metas=self.meta_data)\n\n        np.testing.assert_almost_equal(table.metas, self.meta_data)\n\n    def test_sets_weights_if_given(self):\n        domain = self.mock_domain()\n        table = data.Table.from_numpy(domain, self.data, W=self.weight_data)\n\n        np.testing.assert_equal(table.W.shape, (len(self.data), ))\n        np.testing.assert_almost_equal(table.W.flatten(),\n                                       self.weight_data.flatten())\n\n    def test_splits_X_and_Y_if_given_in_same_array(self):\n        joined_data = np.column_stack((self.data, self.class_data))\n        domain = self.mock_domain(with_classes=True)\n        table = data.Table.from_numpy(domain, joined_data)\n\n        np.testing.assert_almost_equal(table.X, self.data)\n        np.testing.assert_almost_equal(table.Y, self.class_data)\n\n    def test_initializes_Y_metas_and_W_if_not_given(self):\n        domain = self.mock_domain()\n        table = data.Table.from_numpy(domain, self.data)\n\n        self.assertEqual(table.Y.shape, (self.nrows, len(domain.class_vars)))\n        self.assertEqual(table.metas.shape, (self.nrows, len(domain.metas)))\n        self.assertEqual(table.W.shape, (self.nrows, 0))\n\n    def test_raises_error_if_columns_in_domain_and_data_do_not_match(self):\n        domain = self.mock_domain(with_classes=True, with_metas=True)\n        ones = np.zeros((self.nrows, 1))\n\n        with self.assertRaises(ValueError):\n            data_ = np.hstack((self.data, ones))\n            data.Table.from_numpy(domain, data_, self.class_data,\n                                  self.meta_data)\n\n        with self.assertRaises(ValueError):\n            classes_ = np.hstack((self.class_data, ones))\n            data.Table.from_numpy(domain, self.data, classes_,\n                                  self.meta_data)\n\n        with self.assertRaises(ValueError):\n            metas_ = np.hstack((self.meta_data, ones))\n            data.Table.from_numpy(domain, self.data, self.class_data,\n                                  metas_)\n\n    def test_raises_error_if_lengths_of_data_do_not_match(self):\n        domain = self.mock_domain(with_classes=True, with_metas=True)\n\n        with self.assertRaises(ValueError):\n            data_ = np.vstack((self.data, np.zeros((1, len(self.attributes)))))\n            data.Table(domain, data_, self.class_data, self.meta_data)\n\n        with self.assertRaises(ValueError):\n            class_data_ = np.vstack((self.class_data,\n                                     np.zeros((1, len(self.class_vars)))))\n            data.Table(domain, self.data, class_data_, self.meta_data)\n\n        with self.assertRaises(ValueError):\n            meta_data_ = np.vstack((self.meta_data,\n                                    np.zeros((1, len(self.metas)))))\n            data.Table(domain, self.data, self.class_data, meta_data_)\n\n    @patch(\"Orange.data.table.Table.from_numpy\")\n    def test_calling_new_with_domain_and_numpy_arrays_calls_new_from_numpy(\n            self, new_from_numpy):\n        domain = self.mock_domain()\n        data.Table(domain, self.data)\n        new_from_numpy.assert_called_with(domain, self.data)\n\n        domain = self.mock_domain(with_classes=True)\n        data.Table(domain, self.data, self.class_data)\n        new_from_numpy.assert_called_with(domain, self.data, self.class_data)\n\n        domain = self.mock_domain(with_classes=True, with_metas=True)\n        data.Table(domain, self.data, self.class_data, self.meta_data)\n        new_from_numpy.assert_called_with(\n            domain, self.data, self.class_data, self.meta_data)\n\n        data.Table(domain, self.data, self.class_data,\n                   self.meta_data, self.weight_data)\n        new_from_numpy.assert_called_with(domain, self.data, self.class_data,\n                                          self.meta_data, self.weight_data)\n\n    def test_from_numpy_reconstructable(self):\n        def assert_equal(T1, T2):\n            np.testing.assert_array_equal(T1.X, T2.X)\n            np.testing.assert_array_equal(T1.Y, T2.Y)\n            np.testing.assert_array_equal(T1.metas, T2.metas)\n            np.testing.assert_array_equal(T1.W, T2.W)\n\n        nullcol = np.empty((self.nrows, 0))\n        domain = self.create_domain(self.attributes)\n        table = data.Table(domain, self.data)\n\n        table_1 = data.Table.from_numpy(\n            domain, table.X, table.Y, table.metas, table.W)\n        assert_equal(table, table_1)\n\n        domain = self.create_domain(classes=self.class_vars)\n        table = data.Table(domain, nullcol, self.class_data)\n\n        table_1 = data.Table.from_numpy(\n            domain, table.X, table.Y, table.metas, table.W)\n        assert_equal(table, table_1)\n\n        domain = self.create_domain(metas=self.metas)\n        table = data.Table(domain, nullcol, nullcol, self.meta_data)\n\n        table_1 = data.Table.from_numpy(\n            domain, table.X, table.Y, table.metas, table.W)\n        assert_equal(table, table_1)\n\n\nclass CreateTableWithDomainAndTable(TableTests):\n    interesting_slices = [\n        slice(0, 0),  # [0:0] - empty slice\n        slice(1),  # [:1]  - only first element\n        slice(1, None),  # [1:]  - all but first\n        slice(-1, None),  # [-1:] - only last element\n        slice(-1),  # [:-1] - all but last\n        slice(None),  # [:]   - all elements\n        slice(None, None, 2),  # [::2] - even elements\n        slice(None, None, -1),  # [::-1]- all elements reversed\n    ]\n\n    row_indices = [1, 5, 6, 7]\n\n    def setUp(self):\n        self.domain = self.create_domain(\n            self.attributes, self.class_vars, self.metas)\n        self.table = data.Table(\n            self.domain, self.data, self.class_data, self.meta_data)\n\n    def test_creates_table_with_given_domain(self):\n        new_table = data.Table.from_table(self.table.domain, self.table)\n\n        self.assertIsInstance(new_table, data.Table)\n        self.assertIsNot(self.table, new_table)\n        self.assertEqual(new_table.domain, self.domain)\n\n    def test_transform(self):\n        class MyTableClass(data.Table):\n            pass\n\n        table = MyTableClass.from_table(self.table.domain, self.table)\n        domain = table.domain\n        attr = ContinuousVariable(\"x\")\n        new_domain = data.Domain(list(domain.attributes) + [attr], None)\n        new_table = table.transform(new_domain)\n\n        self.assertIsInstance(new_table, MyTableClass)\n        self.assertIsNot(table, new_table)\n        self.assertIs(new_table.domain, new_domain)\n\n    def test_transform_same_domain(self):\n        iris = data.Table(\"iris\")\n        new_domain = copy.copy(iris.domain)\n        new_data = iris.transform(new_domain)\n        self.assertIs(new_data.domain, new_domain)\n\n    def test_can_copy_table(self):\n        new_table = data.Table.from_table(self.domain, self.table)\n        self.assert_table_with_filter_matches(new_table, self.table)\n\n    def test_can_filter_rows_with_list(self):\n        for indices in ([0], [1, 5, 6, 7]):\n            new_table = data.Table.from_table(\n                self.domain, self.table, row_indices=indices)\n            self.assert_table_with_filter_matches(\n                new_table, self.table, rows=indices)\n\n    def test_can_filter_row_with_slice(self):\n        for slice_ in self.interesting_slices:\n            new_table = data.Table.from_table(\n                self.domain, self.table, row_indices=slice_)\n            self.assert_table_with_filter_matches(\n                new_table, self.table, rows=slice_)\n\n    def test_can_use_attributes_as_new_columns(self):\n        a, _, _ = column_sizes(self.table)\n        order = [random.randrange(a) for _ in self.domain.attributes]\n        new_attributes = [self.domain.attributes[i] for i in order]\n        new_domain = self.create_domain(\n            new_attributes, new_attributes, new_attributes)\n        new_table = data.Table.from_table(new_domain, self.table)\n\n        self.assert_table_with_filter_matches(\n            new_table, self.table, xcols=order, ycols=order, mcols=order)\n\n    def test_can_use_class_vars_as_new_columns(self):\n        a, c, _ = column_sizes(self.table)\n        order = [random.randrange(a, a + c) for _ in self.domain.class_vars]\n        new_classes = [self.domain.class_vars[i - a] for i in order]\n        new_domain = self.create_domain(new_classes, new_classes, new_classes)\n        new_table = data.Table.from_table(new_domain, self.table)\n\n        self.assert_table_with_filter_matches(\n            new_table, self.table, xcols=order, ycols=order, mcols=order)\n\n    def test_can_use_metas_as_new_columns(self):\n        _, _, m = column_sizes(self.table)\n        order = [random.randrange(-m + 1, 0) for _ in self.domain.metas]\n        new_metas = [self.domain.metas[::-1][i] for i in order]\n        new_domain = self.create_domain(new_metas, new_metas, new_metas)\n        new_table = data.Table.from_table(new_domain, self.table)\n\n        self.assert_table_with_filter_matches(\n            new_table, self.table, xcols=order, ycols=order, mcols=order)\n\n    def test_can_use_combination_of_all_as_new_columns(self):\n        a, c, m = column_sizes(self.table)\n        order = ([random.randrange(a) for _ in self.domain.attributes] +\n                 [random.randrange(a, a + c) for _ in self.domain.class_vars] +\n                 [random.randrange(-m + 1, 0) for _ in self.domain.metas])\n        random.shuffle(order)\n        vars = list(self.domain.variables) + list(self.domain.metas[::-1])\n        vars = [vars[i] for i in order]\n\n        new_domain = self.create_domain(vars, vars, vars)\n        new_table = data.Table.from_table(new_domain, self.table)\n        self.assert_table_with_filter_matches(\n            new_table, self.table, xcols=order, ycols=order, mcols=order)\n\n    def test_creates_table_with_given_domain_and_row_filter(self):\n        a, c, m = column_sizes(self.table)\n        order = ([random.randrange(a) for _ in self.domain.attributes] +\n                 [random.randrange(a, a + c) for _ in self.domain.class_vars] +\n                 [random.randrange(-m + 1, 0) for _ in self.domain.metas])\n        random.shuffle(order)\n        vars = list(self.domain.variables) + list(self.domain.metas[::-1])\n        vars = [vars[i] for i in order]\n\n        new_domain = self.create_domain(vars, vars, vars)\n        new_table = data.Table.from_table(new_domain, self.table, [0])\n        self.assert_table_with_filter_matches(\n            new_table, self.table[:1], xcols=order, ycols=order, mcols=order)\n\n        new_table = data.Table.from_table(new_domain, self.table, [2, 1, 0])\n        self.assert_table_with_filter_matches(\n            new_table, self.table[2::-1], xcols=order, ycols=order, mcols=order)\n\n        new_table = data.Table.from_table(new_domain, self.table, [])\n        self.assert_table_with_filter_matches(\n            new_table, self.table[:0], xcols=order, ycols=order, mcols=order)\n\n    def test_from_table_sparse_move_some_to_empty_metas(self):\n        iris = data.Table(\"iris\").to_sparse()\n        new_domain = data.domain.Domain(\n            iris.domain.attributes[:2], iris.domain.class_vars,\n            iris.domain.attributes[2:], source=iris.domain)\n        new_iris = iris.transform(new_domain)\n\n        self.assertTrue(sp.issparse(new_iris.X))\n        self.assertTrue(sp.issparse(new_iris.metas))\n        self.assertEqual(new_iris.X.shape, (len(iris), 2))\n        self.assertEqual(new_iris.metas.shape, (len(iris), 2))\n\n        # move back\n        back_iris = new_iris.transform(iris.domain)\n        self.assertEqual(back_iris.domain, iris.domain)\n        self.assertTrue(sp.issparse(back_iris.X))\n        self.assertFalse(sp.issparse(back_iris.metas))\n        self.assertEqual(back_iris.X.shape, iris.X.shape)\n        self.assertEqual(back_iris.metas.shape, iris.metas.shape)\n\n    def test_from_table_sparse_move_all_to_empty_metas(self):\n        iris = data.Table(\"iris\").to_sparse()\n        new_domain = data.domain.Domain(\n            [], iris.domain.class_vars, iris.domain.attributes,\n            source=iris.domain)\n        new_iris = iris.transform(new_domain)\n\n        self.assertFalse(sp.issparse(new_iris.X))\n        self.assertTrue(sp.issparse(new_iris.metas))\n        self.assertEqual(new_iris.X.shape, (len(iris), 0))\n        self.assertEqual(new_iris.metas.shape, (len(iris), 4))\n\n        # move back\n        back_iris = new_iris.transform(iris.domain)\n        self.assertEqual(back_iris.domain, iris.domain)\n        self.assertTrue(sp.issparse(back_iris.X))\n        self.assertFalse(sp.issparse(back_iris.metas))\n        self.assertEqual(back_iris.X.shape, iris.X.shape)\n        self.assertEqual(back_iris.metas.shape, iris.metas.shape)\n\n    def test_from_table_sparse_move_to_nonempty_metas(self):\n        brown = data.Table(\"brown-selected\").to_sparse()\n        n_attr = len(brown.domain.attributes)\n        n_metas = len(brown.domain.metas)\n        new_domain = data.domain.Domain(\n            brown.domain.attributes[:-10],\n            brown.domain.class_vars,\n            brown.domain.attributes[-10:] + brown.domain.metas,\n            source=brown.domain)\n        new_brown = data.Table.from_table(new_domain, brown)\n\n        self.assertTrue(sp.issparse(new_brown.X))\n        self.assertFalse(sp.issparse(new_brown.metas))\n        self.assertEqual(new_brown.X.shape, (len(new_brown), n_attr-10))\n        self.assertEqual(new_brown.metas.shape, (len(new_brown), n_metas+10))\n\n        # move back\n        back_brown = data.Table.from_table(brown.domain, new_brown)\n        self.assertEqual(brown.domain, back_brown.domain)\n        self.assertTrue(sp.issparse(back_brown.X))\n        self.assertFalse(sp.issparse(back_brown.metas))\n        self.assertEqual(back_brown.X.shape, brown.X.shape)\n        self.assertEqual(back_brown.metas.shape, brown.metas.shape)\n\n    def assert_table_with_filter_matches(\n            self, new_table, old_table,\n            rows=..., xcols=..., ycols=..., mcols=...):\n        a, c, m = column_sizes(old_table)\n        xcols = slice(a) if xcols is Ellipsis else xcols\n        ycols = slice(a, a + c) if ycols is Ellipsis else ycols\n        mcols = slice(None, -m - 1, -1) if mcols is Ellipsis else mcols\n\n        # Indexing used by convert_domain uses positive indices for variables\n        # and classes (classes come after attributes) and negative indices for\n        # meta features. This is equivalent to ordinary indexing in a magic\n        # table below.\n        magic = np.hstack((old_table.X, old_table.Y[:, None],\n                           old_table.metas[:, ::-1]))\n        np.testing.assert_almost_equal(new_table.X, magic[rows, xcols])\n        Y = magic[rows, ycols]\n        if Y.shape[1] == 1:\n            Y = Y.flatten()\n        np.testing.assert_almost_equal(new_table.Y, Y)\n        np.testing.assert_almost_equal(new_table.metas, magic[rows, mcols])\n        np.testing.assert_almost_equal(new_table.W, old_table.W[rows])\n\n\ndef isspecial(s):\n    return isinstance(s, slice) or s is Ellipsis\n\n\ndef split_columns(indices, t):\n    a, c, m = column_sizes(t)\n    if indices is ...:\n        return slice(a), slice(c), slice(m)\n    elif isinstance(indices, slice):\n        return indices, slice(0, 0), slice(0, 0)\n    elif not isinstance(indices, list) and not isinstance(indices, tuple):\n        indices = [indices]\n    return (\n        [t.domain.index(x)\n         for x in indices if 0 <= t.domain.index(x) < a] or slice(0, 0),\n        [t.domain.index(x) - a\n         for x in indices if t.domain.index(x) >= a] or slice(0, 0),\n        [-t.domain.index(x) - 1\n         for x in indices if t.domain.index(x) < 0] or slice(0, 0))\n\n\ndef getname(variable):\n    return variable.name\n\n\nclass TableIndexingTests(TableTests):\n    def setUp(self):\n        super().setUp()\n        d = self.domain = \\\n            self.create_domain(self.attributes, self.class_vars, self.metas)\n        t = self.table = \\\n            data.Table(self.domain, self.data, self.class_data, self.meta_data)\n        self.magic_table = \\\n            np.column_stack((self.table.X, self.table.Y,\n                             self.table.metas[:, ::-1]))\n\n        self.rows = [0, -1]\n        self.multiple_rows = [slice(0, 0), ..., slice(1, -1, -1)]\n        a, c, m = column_sizes(t)\n        columns = [0, a - 1, a, a + c - 1, -1, -m]\n        self.columns = chain(columns,\n                             map(lambda x: d[x], columns),\n                             map(lambda x: d[x].name, columns))\n        self.multiple_columns = chain(\n            self.multiple_rows,\n            [d.attributes, d.class_vars, d.metas, [0, a, -1]],\n            [self.attributes, self.class_vars, self.metas],\n            [self.attributes + self.class_vars + self.metas])\n\n        # TODO: indexing with [[0,1], [0,1]] produces weird results\n        # TODO: what should be the results of table[1, :]\n\n    def test_can_select_a_single_value(self):\n        for r in self.rows:\n            for c in self.columns:\n                value = self.table[r, c]\n                self.assertAlmostEqual(\n                    value, self.magic_table[r, self.domain.index(c)])\n\n                value = self.table[r][c]\n                self.assertAlmostEqual(\n                    value, self.magic_table[r, self.domain.index(c)])\n\n    def test_can_select_a_single_row(self):\n        for r in self.rows:\n            row = self.table[r]\n            new_row = np.hstack(\n                (self.data[r, :],\n                 self.class_data[r, None]))\n            np.testing.assert_almost_equal(\n                np.array(list(row)), new_row)\n\n\n    def test_can_select_a_subset_of_rows_and_columns(self):\n        for r in self.rows:\n            for c in self.multiple_columns:\n                table = self.table[r, c]\n\n                attr, cls, metas = split_columns(c, self.table)\n                X = self.table.X[[r], attr]\n                if X.ndim == 1:\n                    X = X.reshape(-1, len(table.domain.attributes))\n                np.testing.assert_almost_equal(table.X, X)\n                Y = self.table.Y[:, None][[r], cls]\n                if len(Y.shape) == 1 or Y.shape[1] == 1:\n                    Y = Y.flatten()\n                np.testing.assert_almost_equal(table.Y, Y)\n                metas_ = self.table.metas[[r], metas]\n                if metas_.ndim == 1:\n                    metas_ = metas_.reshape(-1, len(table.domain.metas))\n                np.testing.assert_almost_equal(table.metas, metas_)\n\n        for r in self.multiple_rows:\n            for c in chain(self.columns, self.multiple_rows):\n                table = self.table[r, c]\n\n                attr, cls, metas = split_columns(c, self.table)\n                np.testing.assert_almost_equal(table.X, self.table.X[r, attr])\n                Y = self.table.Y[:, None][r, cls]\n                if len(Y.shape) > 1 and Y.shape[1] == 1:\n                    Y = Y.flatten()\n                np.testing.assert_almost_equal(table.Y, Y)\n                np.testing.assert_almost_equal(table.metas,\n                                               self.table.metas[r, metas])\n\n\n    def test_optimize_indices(self):\n        # ordinary conversion\n        self.assertEqual(_optimize_indices([1, 2, 3], 4), slice(1, 4, 1))\n        self.assertEqual(_optimize_indices([], 1), [])\n        self.assertEqual(_optimize_indices([0, 2], 3), slice(0, 4, 2))\n\n        # not slices\n        np.testing.assert_equal(_optimize_indices([1, 2, 4], 5), [1, 2, 4])\n        np.testing.assert_equal(_optimize_indices((1, 2, 4), 5), [1, 2, 4])\n\n        # leave boolean arrays\n        np.testing.assert_equal(_optimize_indices([True, False, True], 3), [True, False, True])\n\n        # do not convert if step is negative\n        np.testing.assert_equal(_optimize_indices([4, 2, 0], 5), [4, 2, 0])\n\n        # try range\n        np.testing.assert_equal(_optimize_indices([3, 4, 5], 5), [3, 4, 5])  # out of range\n        self.assertEqual(_optimize_indices((3, 4, 5), 6), slice(3, 6, 1))\n\n        # negative elements\n        np.testing.assert_equal(_optimize_indices([-1, 0, 1], 5), [-1, 0, 1])\n\n        # single element\n        self.assertEqual(_optimize_indices([1], 2), slice(1, 2, 1))\n        np.testing.assert_equal(_optimize_indices([1], 1), [1])\n\n\nclass TableElementAssignmentTest(TableTests):\n    def setUp(self):\n        super().setUp()\n        self.domain = \\\n            self.create_domain(self.attributes, self.class_vars, self.metas)\n        self.table = \\\n            data.Table(self.domain, self.data, self.class_data, self.meta_data)\n\n    def test_can_assign_values(self):\n        self.table[0, 0] = 42.\n        self.assertAlmostEqual(self.table.X[0, 0], 42.)\n\n    def test_can_assign_values_to_classes(self):\n        a, _, _ = column_sizes(self.table)\n        self.table[0, a] = 42.\n        self.assertAlmostEqual(self.table.Y[0], 42.)\n\n    def test_can_assign_values_to_metas(self):\n        self.table[0, -1] = 42.\n        self.assertAlmostEqual(self.table.metas[0, 0], 42.)\n\n    def test_can_assign_rows_to_rows(self):\n        self.table[0] = self.table[1]\n        np.testing.assert_almost_equal(\n            self.table.X[0], self.table.X[1])\n        np.testing.assert_almost_equal(\n            self.table.Y[0], self.table.Y[1])\n        np.testing.assert_almost_equal(\n            self.table.metas[0], self.table.metas[1])\n\n    def test_can_assign_lists(self):\n        a, _, _ = column_sizes(self.table)\n        new_example = [float(i)\n                       for i in range(len(self.attributes + self.class_vars))]\n        self.table[0] = new_example\n        np.testing.assert_almost_equal(\n            self.table.X[0], np.array(new_example[:a]))\n        np.testing.assert_almost_equal(\n            self.table.Y[0], np.array(new_example[a:]))\n\n    def test_can_assign_np_array(self):\n        a, _, _ = column_sizes(self.table)\n        new_example = \\\n            np.array([float(i)\n                      for i in range(len(self.attributes + self.class_vars))])\n        self.table[0] = new_example\n        np.testing.assert_almost_equal(self.table.X[0], new_example[:a])\n        np.testing.assert_almost_equal(self.table.Y[0], new_example[a:])\n\n\nclass InterfaceTest(unittest.TestCase):\n    \"\"\"Basic tests each implementation of Table should pass.\"\"\"\n\n    features = (\n        data.ContinuousVariable(name=\"Continuous Feature 1\"),\n        data.ContinuousVariable(name=\"Continuous Feature 2\"),\n        data.DiscreteVariable(name=\"Discrete Feature 1\", values=[\"0\", \"1\"]),\n        data.DiscreteVariable(name=\"Discrete Feature 2\",\n                              values=[\"value1\", \"value2\"]),\n    )\n\n    class_vars = (\n        data.ContinuousVariable(name=\"Continuous Class\"),\n        data.DiscreteVariable(name=\"Discrete Class\", values=[\"m\", \"f\"])\n    )\n\n    feature_data = (\n        (1, 0, 0, 0),\n        (0, 1, 0, 0),\n        (0, 0, 1, 0),\n        (0, 0, 0, 1),\n    )\n\n    class_data = (\n        (1, 0),\n        (0, 1),\n        (1, 0),\n        (0, 1)\n    )\n\n    data = tuple(a + c for a, c in zip(feature_data, class_data))\n\n    nrows = 4\n\n    def setUp(self):\n        self.domain = data.Domain(attributes=self.features,\n                                  class_vars=self.class_vars)\n        self.table = data.Table.from_numpy(\n            self.domain,\n            np.array(self.feature_data),\n            np.array(self.class_data),\n        )\n\n    def test_len(self):\n        self.assertEqual(len(self.table), self.nrows)\n\n    def test_row_len(self):\n        for i in range(self.nrows):\n            self.assertEqual(len(self.table[i]), len(self.data[i]))\n\n    def test_iteration(self):\n        for row, expected_data in zip(self.table, self.data):\n            self.assertEqual(tuple(row), expected_data)\n\n    def test_row_indexing(self):\n        for i in range(self.nrows):\n            self.assertEqual(tuple(self.table[i]), self.data[i])\n\n    def test_row_slicing(self):\n        t = self.table[1:]\n        self.assertEqual(len(t), self.nrows - 1)\n\n    def test_value_indexing(self):\n        for i in range(self.nrows):\n            for j in range(len(self.table[i])):\n                self.assertEqual(self.table[i, j], self.data[i][j])\n\n    def test_row_assignment(self):\n        new_value = 2.\n        for i in range(self.nrows):\n            new_row = [new_value] * len(self.data[i])\n            self.table[i] = np.array(new_row)\n            self.assertEqual(list(self.table[i]), new_row)\n\n    def test_value_assignment(self):\n        new_value = 0.\n        for i in range(self.nrows):\n            for j in range(len(self.table[i])):\n                self.table[i, j] = new_value\n                self.assertEqual(self.table[i, j], new_value)\n\n    @skip_deprecated_length\n    def test_append_rows(self):\n        new_value = 2\n        new_row = [new_value] * len(self.data[0])\n        self.table.append(new_row)\n        self.assertEqual(list(self.table[-1]), new_row)\n\n    @skip_deprecated_length\n    def test_insert_rows(self):\n        new_value = 2\n        new_row = [new_value] * len(self.data[0])\n        self.table.insert(0, new_row)\n        self.assertEqual(list(self.table[0]), new_row)\n        for row, expected in zip(self.table[1:], self.data):\n            self.assertEqual(tuple(row), expected)\n\n    @skip_deprecated_length\n    def test_insert_view(self):\n        new_row = [1] * len(self.data[0])\n        tab = self.table[:2]\n        self.assertFalse(tab.is_copy())\n        tab.insert(0, new_row)\n        tab = data.Table.from_numpy(self.table.domain, self.table)\n        self.assertFalse(tab.X.flags.c_contiguous)\n        tab.insert(0, new_row)\n\n    @skip_deprecated_length\n    def test_delete_rows(self):\n        for i in range(self.nrows):\n            del self.table[0]\n            for j in range(len(self.table)):\n                self.assertEqual(tuple(self.table[j]), self.data[i + j + 1])\n\n    @skip_deprecated_length\n    def test_clear(self):\n        self.table.clear()\n        self.assertEqual(len(self.table), 0)\n        for _ in self.table:\n            self.fail(\"Table should not contain any rows.\")\n\n    def test_subclasses(self):\n        from pathlib import Path\n\n        class _ExtendedTable(data.Table):\n            pass\n\n        data_file = _ExtendedTable('iris')\n        data_url = _ExtendedTable.from_url(\n            Path(os.path.dirname(__file__), 'test1.tab').as_uri())\n\n        self.assertIsInstance(data_file, _ExtendedTable)\n        self.assertIsInstance(data_url, _ExtendedTable)\n\n\nclass TestTableStats(TableTests):\n    def test_get_nan_frequency(self):\n        domain = self.create_domain(self.attributes, self.class_vars)\n        table = data.Table(domain, self.data, self.class_data)\n        self.assertEqual(table.get_nan_frequency_attribute(), 0)\n        self.assertEqual(table.get_nan_frequency_class(), 0)\n\n        table.X[1, 2] = table.X[4, 5] = np.nan\n        self.assertEqual(table.get_nan_frequency_attribute(), 2 / table.X.size)\n        self.assertEqual(table.get_nan_frequency_class(), 0)\n\n        table.Y[3:6] = np.nan\n        self.assertEqual(table.get_nan_frequency_attribute(), 2 / table.X.size)\n        self.assertEqual(table.get_nan_frequency_class(), 3 / table.Y.size)\n\n        table.X[1, 2] = table.X[4, 5] = 0\n        self.assertEqual(table.get_nan_frequency_attribute(), 0)\n        self.assertEqual(table.get_nan_frequency_class(), 3 / table.Y.size)\n\n    def test_get_nan_frequency_empty_table(self):\n        domain = self.create_domain(self.attributes, self.class_vars)\n        table = data.Table(domain)\n        self.assertEqual(table.get_nan_frequency_attribute(), 0)\n        self.assertEqual(table.get_nan_frequency_class(), 0)\n\n\nclass TestRowInstance(unittest.TestCase):\n    def test_assignment(self):\n        table = data.Table(\"zoo\")\n        inst = table[2]\n        self.assertIsInstance(inst, data.RowInstance)\n\n        inst[1] = 0\n        self.assertEqual(table[2, 1], 0)\n        inst[1] = 1\n        self.assertEqual(table[2, 1], 1)\n\n        inst.set_class(\"mammal\")\n        self.assertEqual(table[2, len(table.domain.attributes)], \"mammal\")\n        inst.set_class(\"fish\")\n        self.assertEqual(table[2, len(table.domain.attributes)], \"fish\")\n\n        inst[-1] = \"Foo\"\n        self.assertEqual(table[2, -1], \"Foo\")\n\n    def test_iteration_with_assignment(self):\n        table = data.Table(\"iris\")\n        for i, row in enumerate(table):\n            row[0] = i\n        np.testing.assert_array_equal(table.X[:, 0], np.arange(len(table)))\n\n    def test_sparse_assignment(self):\n        X = np.eye(4)\n        Y = X[2]\n        table = data.Table(X, Y)\n        row = table[1]\n        self.assertFalse(sp.issparse(row.sparse_x))\n        self.assertEqual(row[0], 0)\n        self.assertEqual(row[1], 1)\n\n        table.X = sp.csr_matrix(table.X)\n        table._Y = sp.csr_matrix(table._Y)\n        sparse_row = table[1]\n        self.assertTrue(sp.issparse(sparse_row.sparse_x))\n        self.assertEqual(sparse_row[0], 0)\n        self.assertEqual(sparse_row[1], 1)\n        sparse_row[1] = 0\n        self.assertEqual(sparse_row[1], 0)\n        self.assertEqual(table.X[1, 1], 0)\n        self.assertEqual(table[2][4], 1)\n        table[2][4] = 0\n        self.assertEqual(table[2][4], 0)\n\n\nclass TestTableTranspose(unittest.TestCase):\n    def test_transpose_no_class(self):\n        attrs = [ContinuousVariable(\"c1\"), ContinuousVariable(\"c2\")]\n        data = Table(Domain(attrs), np.arange(8).reshape((4, 2)))\n\n        att = [ContinuousVariable(\"Feature 1\"), ContinuousVariable(\"Feature 2\"),\n               ContinuousVariable(\"Feature 3\"), ContinuousVariable(\"Feature 4\")]\n        domain = Domain(att, metas=[StringVariable(\"Feature name\")])\n        result = Table(domain, np.arange(8).reshape((4, 2)).T,\n                       metas=np.array([\"c1\", \"c2\"])[:, None])\n\n        # transpose and compare\n        self._compare_tables(result, Table.transpose(data))\n\n        # transpose of transpose is original\n        t = Table.transpose(Table.transpose(data), \"Feature name\")\n        self._compare_tables(data, t)\n\n        # original should not change\n        self.assertDictEqual(data.domain.attributes[0].attributes, {})\n\n    def test_transpose_discrete_class(self):\n        attrs = [ContinuousVariable(\"c1\"), ContinuousVariable(\"c2\")]\n        domain = Domain(attrs, [DiscreteVariable(\"cls\", values=[\"a\", \"b\"])])\n        data = Table(domain, np.arange(8).reshape((4, 2)),\n                     np.array([1, 1, 0, 0]))\n\n        att = [ContinuousVariable(\"Feature 1\"), ContinuousVariable(\"Feature 2\"),\n               ContinuousVariable(\"Feature 3\"), ContinuousVariable(\"Feature 4\")]\n        att[0].attributes = {\"cls\": \"b\"}\n        att[1].attributes = {\"cls\": \"b\"}\n        att[2].attributes = {\"cls\": \"a\"}\n        att[3].attributes = {\"cls\": \"a\"}\n        domain = Domain(att, metas=[StringVariable(\"Feature name\")])\n        result = Table(domain, np.arange(8).reshape((4, 2)).T,\n                       metas=np.array([\"c1\", \"c2\"])[:, None])\n\n        # transpose and compare\n        self._compare_tables(result, Table.transpose(data))\n\n        # transpose of transpose is original\n        t = Table.transpose(Table.transpose(data), \"Feature name\")\n        self._compare_tables(data, t)\n\n        # original should not change\n        self.assertDictEqual(data.domain.attributes[0].attributes, {})\n\n    def test_transpose_continuous_class(self):\n        attrs = [ContinuousVariable(\"c1\"), ContinuousVariable(\"c2\")]\n        domain = Domain(attrs, [ContinuousVariable(\"cls\")])\n        data = Table(domain, np.arange(8).reshape((4, 2)), np.arange(4, 0, -1))\n\n        att = [ContinuousVariable(\"Feature 1\"), ContinuousVariable(\"Feature 2\"),\n               ContinuousVariable(\"Feature 3\"), ContinuousVariable(\"Feature 4\")]\n        att[0].attributes = {\"cls\": \"4\"}\n        att[1].attributes = {\"cls\": \"3\"}\n        att[2].attributes = {\"cls\": \"2\"}\n        att[3].attributes = {\"cls\": \"1\"}\n        domain = Domain(att, metas=[StringVariable(\"Feature name\")])\n        result = Table(domain, np.arange(8).reshape((4, 2)).T,\n                       metas=np.array([\"c1\", \"c2\"])[:, None])\n\n        # transpose and compare\n        self._compare_tables(result, Table.transpose(data))\n\n        # transpose of transpose\n        t = Table.transpose(Table.transpose(data), \"Feature name\")\n        self._compare_tables(data, t)\n\n        # original should not change\n        self.assertDictEqual(data.domain.attributes[0].attributes, {})\n\n    def test_transpose_missing_class(self):\n        attrs = [ContinuousVariable(\"c1\"), ContinuousVariable(\"c2\")]\n        domain = Domain(attrs, [ContinuousVariable(\"cls\")])\n        data = Table(domain, np.arange(8).reshape((4, 2)),\n                     np.array([np.nan, 3, 2, 1]))\n\n        att = [ContinuousVariable(\"Feature 1\"), ContinuousVariable(\"Feature 2\"),\n               ContinuousVariable(\"Feature 3\"), ContinuousVariable(\"Feature 4\")]\n        att[1].attributes = {\"cls\": \"3\"}\n        att[2].attributes = {\"cls\": \"2\"}\n        att[3].attributes = {\"cls\": \"1\"}\n        domain = Domain(att, metas=[StringVariable(\"Feature name\")])\n        result = Table(domain, np.arange(8).reshape((4, 2)).T,\n                       metas=np.array([\"c1\", \"c2\"])[:, None])\n\n        # transpose and compare\n        self._compare_tables(result, Table.transpose(data))\n\n        # transpose of transpose\n        t = Table.transpose(Table.transpose(data), \"Feature name\")\n        self._compare_tables(data, t)\n\n        # original should not change\n        self.assertDictEqual(data.domain.attributes[0].attributes, {})\n\n    def test_transpose_multiple_class(self):\n        attrs = [ContinuousVariable(\"c1\"), ContinuousVariable(\"c2\")]\n        class_vars = [ContinuousVariable(\"cls1\"), ContinuousVariable(\"cls2\")]\n        domain = Domain(attrs, class_vars)\n        data = Table(domain, np.arange(8).reshape((4, 2)),\n                     np.arange(8).reshape((4, 2)))\n\n        att = [ContinuousVariable(\"Feature 1\"), ContinuousVariable(\"Feature 2\"),\n               ContinuousVariable(\"Feature 3\"), ContinuousVariable(\"Feature 4\")]\n        att[0].attributes = {\"cls1\": \"0\", \"cls2\": \"1\"}\n        att[1].attributes = {\"cls1\": \"2\", \"cls2\": \"3\"}\n        att[2].attributes = {\"cls1\": \"4\", \"cls2\": \"5\"}\n        att[3].attributes = {\"cls1\": \"6\", \"cls2\": \"7\"}\n        domain = Domain(att, metas=[StringVariable(\"Feature name\")])\n        result = Table(domain, np.arange(8).reshape((4, 2)).T,\n                       metas=np.array([\"c1\", \"c2\"])[:, None])\n\n        # transpose and compare\n        self._compare_tables(result, Table.transpose(data))\n\n        # transpose of transpose\n        t = Table.transpose(Table.transpose(data), \"Feature name\")\n        self._compare_tables(data, t)\n\n        # original should not change\n        self.assertDictEqual(data.domain.attributes[0].attributes, {})\n\n    def test_transpose_metas(self):\n        attrs = [ContinuousVariable(\"c1\"), ContinuousVariable(\"c2\")]\n        metas = [StringVariable(\"m1\")]\n        domain = Domain(attrs, metas=metas)\n        X = np.arange(8).reshape((4, 2))\n        M = np.array([\"aa\", \"bb\", \"cc\", \"dd\"])[:, None]\n        data = Table(domain, X, metas=M)\n\n        att = [ContinuousVariable(\"Feature 1\"), ContinuousVariable(\"Feature 2\"),\n               ContinuousVariable(\"Feature 3\"), ContinuousVariable(\"Feature 4\")]\n        att[0].attributes = {\"m1\": \"aa\"}\n        att[1].attributes = {\"m1\": \"bb\"}\n        att[2].attributes = {\"m1\": \"cc\"}\n        att[3].attributes = {\"m1\": \"dd\"}\n        domain = Domain(att, metas=[StringVariable(\"Feature name\")])\n        result = Table(domain, np.arange(8).reshape((4, 2)).T,\n                       metas=np.array([\"c1\", \"c2\"])[:, None])\n\n        # transpose and compare\n        self._compare_tables(result, Table.transpose(data))\n\n        # transpose of transpose\n        t = Table.transpose(Table.transpose(data), \"Feature name\")\n        self._compare_tables(data, t)\n\n        # original should not change\n        self.assertDictEqual(data.domain.attributes[0].attributes, {})\n\n    def test_transpose_discrete_metas(self):\n        attrs = [ContinuousVariable(\"c1\"), ContinuousVariable(\"c2\")]\n        metas = [DiscreteVariable(\"m1\", values=[\"aa\", \"bb\"])]\n        domain = Domain(attrs, metas=metas)\n        X = np.arange(8).reshape((4, 2))\n        M = np.array([0, 1, 0, 1])[:, None]\n        data = Table(domain, X, metas=M)\n\n        att = [ContinuousVariable(\"Feature 1\"), ContinuousVariable(\"Feature 2\"),\n               ContinuousVariable(\"Feature 3\"), ContinuousVariable(\"Feature 4\")]\n        att[0].attributes = {\"m1\": \"aa\"}\n        att[1].attributes = {\"m1\": \"bb\"}\n        att[2].attributes = {\"m1\": \"aa\"}\n        att[3].attributes = {\"m1\": \"bb\"}\n        domain = Domain(att, metas=[StringVariable(\"Feature name\")])\n        result = Table(domain, np.arange(8).reshape((4, 2)).T,\n                       metas=np.array([\"c1\", \"c2\"])[:, None])\n\n        # transpose and compare\n        self._compare_tables(result, Table.transpose(data))\n\n        # transpose of transpose is original\n        t = Table.transpose(Table.transpose(data), \"Feature name\")\n        self._compare_tables(data, t)\n\n        # original should not change\n        self.assertDictEqual(data.domain.attributes[0].attributes, {})\n\n    def test_transpose_continuous_metas(self):\n        attrs = [ContinuousVariable(\"c1\"), ContinuousVariable(\"c2\")]\n        metas = [ContinuousVariable(\"m1\")]\n        domain = Domain(attrs, metas=metas)\n        X = np.arange(8).reshape((4, 2))\n        M = np.array([0.0, 1.0, 0.0, 1.0])[:, None]\n        data = Table(domain, X, metas=M)\n\n        att = [ContinuousVariable(\"Feature 1\"), ContinuousVariable(\"Feature 2\"),\n               ContinuousVariable(\"Feature 3\"), ContinuousVariable(\"Feature 4\")]\n        att[0].attributes = {\"m1\": \"0\"}\n        att[1].attributes = {\"m1\": \"1\"}\n        att[2].attributes = {\"m1\": \"0\"}\n        att[3].attributes = {\"m1\": \"1\"}\n        domain = Domain(att, metas=[StringVariable(\"Feature name\")])\n        result = Table(domain, np.arange(8).reshape((4, 2)).T,\n                       metas=np.array([\"c1\", \"c2\"])[:, None])\n\n        # transpose and compare\n        self._compare_tables(result, Table.transpose(data))\n\n        # transpose of transpose is original\n        t = Table.transpose(Table.transpose(data), \"Feature name\")\n        self._compare_tables(data, t)\n\n        # original should not change\n        self.assertDictEqual(data.domain.attributes[0].attributes, {})\n\n    def test_transpose_missing_metas(self):\n        attrs = [ContinuousVariable(\"c1\"), ContinuousVariable(\"c2\")]\n        metas = [StringVariable(\"m1\")]\n        domain = Domain(attrs, metas=metas)\n        X = np.arange(8).reshape((4, 2))\n        M = np.array([\"aa\", \"bb\", \"\", \"dd\"])[:, None]\n        data = Table(domain, X, metas=M)\n\n        att = [ContinuousVariable(\"Feature 1\"), ContinuousVariable(\"Feature 2\"),\n               ContinuousVariable(\"Feature 3\"), ContinuousVariable(\"Feature 4\")]\n        att[0].attributes = {\"m1\": \"aa\"}\n        att[1].attributes = {\"m1\": \"bb\"}\n        att[3].attributes = {\"m1\": \"dd\"}\n        domain = Domain(att, metas=[StringVariable(\"Feature name\")])\n        result = Table(domain, np.arange(8).reshape((4, 2)).T,\n                       metas=np.array([\"c1\", \"c2\"])[:, None])\n\n        # transpose and compare\n        self._compare_tables(result, Table.transpose(data))\n\n        # transpose of transpose\n        t = Table.transpose(Table.transpose(data), \"Feature name\")\n        self._compare_tables(data, t)\n\n        # original should not change\n        self.assertDictEqual(data.domain.attributes[0].attributes, {})\n\n    def test_transpose_multiple_metas(self):\n        attrs = [ContinuousVariable(\"c1\"), ContinuousVariable(\"c2\")]\n        metas = [StringVariable(\"m1\"), StringVariable(\"m2\")]\n        domain = Domain(attrs, metas=metas)\n        X = np.arange(8).reshape((4, 2))\n        M = np.array([[\"aa\", \"aaa\"], [\"bb\", \"bbb\"],\n                      [\"cc\", \"ccc\"], [\"dd\", \"ddd\"]])\n        data = Table(domain, X, metas=M)\n\n        att = [ContinuousVariable(\"Feature 1\"), ContinuousVariable(\"Feature 2\"),\n               ContinuousVariable(\"Feature 3\"), ContinuousVariable(\"Feature 4\")]\n        att[0].attributes = {\"m1\": \"aa\", \"m2\": \"aaa\"}\n        att[1].attributes = {\"m1\": \"bb\", \"m2\": \"bbb\"}\n        att[2].attributes = {\"m1\": \"cc\", \"m2\": \"ccc\"}\n        att[3].attributes = {\"m1\": \"dd\", \"m2\": \"ddd\"}\n        domain = Domain(att, metas=[StringVariable(\"Feature name\")])\n        result = Table(domain, np.arange(8).reshape((4, 2)).T,\n                       metas=np.array([\"c1\", \"c2\"])[:, None])\n\n        # transpose and compare\n        self._compare_tables(result, Table.transpose(data))\n\n        # transpose of transpose\n        t = Table.transpose(Table.transpose(data), \"Feature name\")\n        self._compare_tables(data, t)\n\n        # original should not change\n        self.assertDictEqual(data.domain.attributes[0].attributes, {})\n\n    def test_transpose_class_and_metas(self):\n        attrs = [ContinuousVariable(\"c1\"), ContinuousVariable(\"c2\")]\n        metas = [StringVariable(\"m1\"), StringVariable(\"m2\")]\n        domain = Domain(attrs, [ContinuousVariable(\"cls\")], metas)\n        M = np.array([[\"aa\", \"aaa\"], [\"bb\", \"bbb\"],\n                      [\"cc\", \"ccc\"], [\"dd\", \"ddd\"]])\n        data = Table(domain, np.arange(8).reshape((4, 2)), np.arange(1, 5), M)\n\n        att = [ContinuousVariable(\"Feature 1\"), ContinuousVariable(\"Feature 2\"),\n               ContinuousVariable(\"Feature 3\"), ContinuousVariable(\"Feature 4\")]\n        att[0].attributes = {\"cls\": \"1\", \"m1\": \"aa\", \"m2\": \"aaa\"}\n        att[1].attributes = {\"cls\": \"2\", \"m1\": \"bb\", \"m2\": \"bbb\"}\n        att[2].attributes = {\"cls\": \"3\", \"m1\": \"cc\", \"m2\": \"ccc\"}\n        att[3].attributes = {\"cls\": \"4\", \"m1\": \"dd\", \"m2\": \"ddd\"}\n        domain = Domain(att, metas=[StringVariable(\"Feature name\")])\n        result = Table(domain, np.arange(8).reshape((4, 2)).T,\n                       metas=np.array([\"c1\", \"c2\"])[:, None])\n\n        # transpose and compare\n        self._compare_tables(result, Table.transpose(data))\n\n        # transpose of transpose\n        t = Table.transpose(Table.transpose(data), \"Feature name\")\n        self._compare_tables(data, t)\n\n        # original should not change\n        self.assertDictEqual(data.domain.attributes[0].attributes, {})\n\n    def test_transpose_attributes_of_attributes_discrete(self):\n        attrs = [ContinuousVariable(\"c1\"), ContinuousVariable(\"c2\")]\n        attrs[0].attributes = {\"attr1\": \"a\", \"attr2\": \"aa\"}\n        attrs[1].attributes = {\"attr1\": \"b\", \"attr2\": \"bb\"}\n        domain = Domain(attrs)\n        data = Table(domain, np.arange(8).reshape((4, 2)))\n\n        att = [ContinuousVariable(\"Feature 1\"), ContinuousVariable(\"Feature 2\"),\n               ContinuousVariable(\"Feature 3\"), ContinuousVariable(\"Feature 4\")]\n        metas = [StringVariable(\"Feature name\"),\n                 DiscreteVariable(\"attr1\", values=(\"a\", \"b\")),\n                 DiscreteVariable(\"attr2\", values=(\"aa\", \"bb\"))]\n        domain = Domain(att, metas=metas)\n        M = np.array([[\"c1\", 0.0, 0.0], [\"c2\", 1.0, 1.0]], dtype=object)\n        result = Table(domain, np.arange(8).reshape((4, 2)).T, metas=M)\n\n        # transpose and compare\n        self._compare_tables(result, Table.transpose(data))\n\n        # transpose of transpose\n        t = Table.transpose(Table.transpose(data), \"Feature name\")\n        self._compare_tables(data, t)\n\n        # original should not change\n        self.assertDictEqual(data.domain.attributes[0].attributes,\n                             {\"attr1\": \"a\", \"attr2\": \"aa\"})\n\n    def test_transpose_attributes_of_attributes_continuous(self):\n        attrs = [ContinuousVariable(\"c1\"), ContinuousVariable(\"c2\")]\n        attrs[0].attributes = {\"attr1\": \"1.1\", \"attr2\": \"1.3\"}\n        attrs[1].attributes = {\"attr1\": \"2.2\", \"attr2\": \"2.3\"}\n        domain = Domain(attrs)\n        data = Table(domain, np.arange(8).reshape((4, 2)))\n\n        att = [ContinuousVariable(\"Feature 1\"), ContinuousVariable(\"Feature 2\"),\n               ContinuousVariable(\"Feature 3\"), ContinuousVariable(\"Feature 4\")]\n        metas = [StringVariable(\"Feature name\"), ContinuousVariable(\"attr1\"),\n                 ContinuousVariable(\"attr2\")]\n        domain = Domain(att, metas=metas)\n        result = Table(domain, np.arange(8).reshape((4, 2)).T,\n                       metas=np.array([[\"c1\", 1.1, 1.3],\n                                       [\"c2\", 2.2, 2.3]], dtype=object))\n\n        # transpose and compare\n        self._compare_tables(result, Table.transpose(data))\n\n        # transpose of transpose\n        t = Table.transpose(Table.transpose(data), \"Feature name\")\n        self._compare_tables(data, t)\n\n        # original should not change\n        self.assertDictEqual(data.domain.attributes[0].attributes,\n                             {\"attr1\": \"1.1\", \"attr2\": \"1.3\"})\n\n    def test_transpose_attributes_of_attributes_missings(self):\n        attrs = [ContinuousVariable(\"c1\"), ContinuousVariable(\"c2\")]\n        attrs[0].attributes = {\"attr1\": \"a\", \"attr2\": \"aa\"}\n        attrs[1].attributes = {\"attr1\": \"b\"}\n        domain = Domain(attrs)\n        data = Table(domain, np.arange(8).reshape((4, 2)))\n\n        att = [ContinuousVariable(\"Feature 1\"), ContinuousVariable(\"Feature 2\"),\n               ContinuousVariable(\"Feature 3\"), ContinuousVariable(\"Feature 4\")]\n        metas = [StringVariable(\"Feature name\"),\n                 DiscreteVariable(\"attr1\", values=(\"a\", \"b\")),\n                 DiscreteVariable(\"attr2\", values=(\"aa\",))]\n        domain = Domain(att, metas=metas)\n        M = np.array([[\"c1\", 0.0, 0.0], [\"c2\", 1.0, np.nan]], dtype=object)\n        result = Table(domain, np.arange(8).reshape((4, 2)).T, metas=M)\n\n        # transpose and compare\n        self._compare_tables(result, Table.transpose(data))\n\n        # transpose of transpose\n        t = Table.transpose(Table.transpose(data), \"Feature name\")\n        self._compare_tables(data, t)\n\n        # original should not change\n        self.assertDictEqual(data.domain.attributes[0].attributes,\n                             {\"attr1\": \"a\", \"attr2\": \"aa\"})\n\n    def test_transpose_class_metas_attributes(self):\n        attrs = [ContinuousVariable(\"c1\"), ContinuousVariable(\"c2\")]\n        attrs[0].attributes = {\"attr1\": \"a1\", \"attr2\": \"aa1\"}\n        attrs[1].attributes = {\"attr1\": \"b1\", \"attr2\": \"bb1\"}\n        metas = [StringVariable(\"m1\"), StringVariable(\"m2\")]\n        domain = Domain(attrs, [ContinuousVariable(\"cls\")], metas)\n        M = np.array([[\"aa\", \"aaa\"], [\"bb\", \"bbb\"],\n                      [\"cc\", \"ccc\"], [\"dd\", \"ddd\"]])\n        data = Table(domain, np.arange(8).reshape((4, 2)), np.arange(1, 5), M)\n\n        att = [ContinuousVariable(\"Feature 1\"), ContinuousVariable(\"Feature 2\"),\n               ContinuousVariable(\"Feature 3\"), ContinuousVariable(\"Feature 4\")]\n        att[0].attributes = {\"cls\": \"1\", \"m1\": \"aa\", \"m2\": \"aaa\"}\n        att[1].attributes = {\"cls\": \"2\", \"m1\": \"bb\", \"m2\": \"bbb\"}\n        att[2].attributes = {\"cls\": \"3\", \"m1\": \"cc\", \"m2\": \"ccc\"}\n        att[3].attributes = {\"cls\": \"4\", \"m1\": \"dd\", \"m2\": \"ddd\"}\n        metas = [StringVariable(\"Feature name\"),\n                 DiscreteVariable(\"attr1\", values=(\"a1\", \"b1\")),\n                 DiscreteVariable(\"attr2\", values=(\"aa1\", \"bb1\"))]\n        domain = Domain(att, metas=metas)\n        M = np.array([[\"c1\", 0.0, 0.0], [\"c2\", 1.0, 1.0]], dtype=object)\n        result = Table(domain, np.arange(8).reshape((4, 2)).T, metas=M)\n\n        # transpose and compare\n        self._compare_tables(result, Table.transpose(data))\n\n        # transpose of transpose\n        t = Table.transpose(Table.transpose(data), \"Feature name\")\n        self._compare_tables(data, t)\n\n        # original should not change\n        self.assertDictEqual(data.domain.attributes[0].attributes,\n                             {\"attr1\": \"a1\", \"attr2\": \"aa1\"})\n\n    def test_transpose(self):\n        zoo = Table(\"zoo\")\n        t1 = Table.transpose(zoo)\n        t2 = Table.transpose(t1, \"Feature name\")\n        t3 = Table.transpose(t2)\n        self._compare_tables(zoo, t2)\n        self._compare_tables(t1, t3)\n\n    def _compare_tables(self, table1, table2):\n        self.assertEqual(table1.n_rows, table2.n_rows)\n        np.testing.assert_array_equal(table1.X, table2.X)\n        np.testing.assert_array_equal(table1.Y, table2.Y)\n        np.testing.assert_array_equal(table1.metas.astype(str),\n                                      table2.metas.astype(str))\n        np.testing.assert_array_equal(table1.W, table2.W)\n\n        self.assertEqual([(type(x), x.name, x.attributes)\n                          for x in table1.domain.attributes],\n                         [(type(x), x.name, x.attributes)\n                          for x in table2.domain.attributes])\n        self.assertEqual([(type(x), x.name, x.attributes)\n                          for x in table1.domain.class_vars],\n                         [(type(x), x.name, x.attributes)\n                          for x in table2.domain.class_vars])\n        self.assertEqual([(type(x), x.name, x.attributes)\n                          for x in table1.domain.metas],\n                         [(type(x), x.name, x.attributes)\n                          for x in table2.domain.metas])\n\n\nclass SparseCV:\n    def __call__(self, data):\n        return sp.csr_matrix((len(data), 1))\n\n\nclass TestTableSparseDense(unittest.TestCase):\n    def setUp(self):\n        self.iris = Table('iris')\n\n    def test_sparse_dense_transformation(self):\n        iris = Table('iris')\n        iris_sparse = iris.to_sparse(sparse_attributes=True)\n        self.assertTrue(sp.issparse(iris_sparse.X))\n        self.assertFalse(sp.issparse(iris_sparse.Y))\n        self.assertFalse(sp.issparse(iris_sparse.metas))\n\n        iris_sparse = iris.to_sparse(sparse_attributes=True, sparse_class=True)\n        self.assertTrue(sp.issparse(iris_sparse.X))\n        self.assertTrue(sp.issparse(iris_sparse.Y))\n        self.assertFalse(sp.issparse(iris_sparse.metas))\n\n        dense_iris = iris_sparse.to_dense()\n        self.assertFalse(sp.issparse(dense_iris.X))\n        self.assertFalse(sp.issparse(dense_iris.Y))\n        self.assertFalse(sp.issparse(dense_iris.metas))\n\n    def test_from_table_add_one_sparse_column(self):\n        # add one sparse feature, should remain dense\n        domain = self.iris.domain.copy()\n        domain.attributes += (\n            ContinuousVariable('S1', compute_value=SparseCV(), sparse=True),\n        )\n        d = self.iris.transform(domain)\n        self.assertFalse(sp.issparse(d.X))\n\n    def test_from_table_add_lots_of_sparse_columns(self):\n        n_attrs = len(self.iris.domain.attributes)\n\n        # add 2*n_attrs+1 sparse feature, should became sparse\n        domain = self.iris.domain.copy()\n        domain.attributes += tuple(\n            ContinuousVariable('S' + str(i), compute_value=SparseCV(), sparse=True)\n            for i in range(2*n_attrs + 1)\n        )\n        d = self.iris.transform(domain)\n        self.assertTrue(sp.issparse(d.X))\n\n    def test_from_table_replace_attrs_with_sparse(self):\n        # replace attrs with a sparse feature, should became sparse\n        domain = self.iris.domain.copy()\n        domain.attributes = (\n            ContinuousVariable('S1', compute_value=SparseCV(), sparse=True),\n        )\n        d = self.iris.transform(domain)\n        self.assertTrue(sp.issparse(d.X))\n\n    def test_from_table_sparse_metas(self):\n        # replace metas with a sparse feature, should became sparse\n        domain = self.iris.domain.copy()\n        domain._metas = (\n            ContinuousVariable('S1', compute_value=SparseCV(), sparse=True),\n        )\n        d = self.iris.transform(domain)\n        self.assertTrue(sp.issparse(d.metas))\n\n    def test_from_table_sparse_metas_with_strings(self):\n        # replace metas with text and 100 sparse features, should be dense\n        domain = self.iris.domain.copy()\n        domain._metas = (StringVariable('text'),) + tuple(\n            ContinuousVariable('S' + str(i), compute_value=SparseCV(), sparse=True)\n            for i in range(100)\n        )\n        d = self.iris.transform(domain)\n        self.assertFalse(sp.issparse(d.metas))\n\nif __name__ == \"__main__\":\n    unittest.main()\n",
            "header": {
                "file": {
                    "path": "Orange/tests/test_table.py"
                },
                "misc_line": null
            },
            "index_line": {
                "old_commit_hash": "a4beba674",
                "new_commit_hash": "80c49be31",
                "mode": "100644"
            },
            "is_binary_file": false,
            "binary_line": null,
            "minus_file": {
                "path": "a/Orange/tests/test_table.py"
            },
            "plus_file": {
                "path": "b/Orange/tests/test_table.py"
            },
            "hunks": [
                {
                    "descriptor": {
                        "old_range": {
                            "start": 1277,
                            "length": 6
                        },
                        "new_range": {
                            "start": 1277,
                            "length": 14
                        },
                        "section": "class TableTestCase(unittest.TestCase):"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "        table.X = sp.csr_matrix(table.X)",
                                "type": "context"
                            },
                            {
                                "content": "        repr(table)     # make sure repr does not crash",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "    def test_inf(self):",
                                "type": "added"
                            },
                            {
                                "content": "        a = np.array([[2,   0,      0,      0],",
                                "type": "added"
                            },
                            {
                                "content": "                      [0,   np.nan, np.nan, 1],",
                                "type": "added"
                            },
                            {
                                "content": "                      [0,   0,      np.inf, 0]])",
                                "type": "added"
                            },
                            {
                                "content": "        with self.assertWarns(Warning):",
                                "type": "added"
                            },
                            {
                                "content": "            tab = data.Table(a)",
                                "type": "added"
                            },
                            {
                                "content": "        self.assertEqual(tab.get_nan_frequency_attribute(), 3/12)",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "def column_sizes(table):",
                                "type": "context"
                            },
                            {
                                "content": "    return (len(table.domain.attributes),",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [
                        {
                            "file_name": "Orange/tests/test_table.py",
                            "type": "class",
                            "name": "TableTestCase",
                            "content": "class TableTestCase(unittest.TestCase):\n    def setUp(self):\n        Variable._clear_all_caches()\n        data.table.dataset_dirs.append(test_dirname())\n\n    def tearDown(self):\n        data.table.dataset_dirs.remove(test_dirname())\n\n    def test_indexing_class(self):\n        d = data.Table(\"test1\")\n        self.assertEqual([e.get_class() for e in d], [\"t\", \"t\", \"f\"])\n        cind = len(d.domain) - 1\n        self.assertEqual([e[cind] for e in d], [\"t\", \"t\", \"f\"])\n        self.assertEqual([e[\"d\"] for e in d], [\"t\", \"t\", \"f\"])\n        cvar = d.domain.class_var\n        self.assertEqual([e[cvar] for e in d], [\"t\", \"t\", \"f\"])\n\n    def test_filename(self):\n        dir = data.table.get_sample_datasets_dir()\n        d = data.Table(\"iris\")\n        self.assertEqual(d.__file__, os.path.join(dir, \"iris.tab\"))\n\n        d = data.Table(\"test2.tab\")\n        self.assertTrue(d.__file__.endswith(\"test2.tab\"))  # platform dependent\n\n    def test_indexing(self):\n        import warnings\n\n        with warnings.catch_warnings():\n            warnings.simplefilter(\"ignore\")\n            d = data.Table(\"test2\")\n\n            # regular, discrete\n            varc = d.domain[\"c\"]\n            self.assertEqual(d[0, 1], \"0\")\n            self.assertEqual(d[0, varc], \"0\")\n            self.assertEqual(d[0, \"c\"], \"0\")\n            self.assertEqual(d[0][1], \"0\")\n            self.assertEqual(d[0][varc], \"0\")\n            self.assertEqual(d[0][\"c\"], \"0\")\n            self.assertEqual(d[np.int_(0), np.int_(1)], \"0\")\n            self.assertEqual(d[np.int_(0)][np.int_(1)], \"0\")\n\n            # regular, continuous\n            varb = d.domain[\"b\"]\n            self.assertEqual(d[0, 0], 0)\n            self.assertEqual(d[0, varb], 0)\n            self.assertEqual(d[0, \"b\"], 0)\n            self.assertEqual(d[0][0], 0)\n            self.assertEqual(d[0][varb], 0)\n            self.assertEqual(d[0][\"b\"], 0)\n            self.assertEqual(d[np.int_(0), np.int_(0)], 0)\n            self.assertEqual(d[np.int_(0)][np.int_(0)], 0)\n\n            # negative\n            varb = d.domain[\"b\"]\n            self.assertEqual(d[-2, 0], 3.333)\n            self.assertEqual(d[-2, varb], 3.333)\n            self.assertEqual(d[-2, \"b\"], 3.333)\n            self.assertEqual(d[-2][0], 3.333)\n            self.assertEqual(d[-2][varb], 3.333)\n            self.assertEqual(d[-2][\"b\"], 3.333)\n            self.assertEqual(d[np.int_(-2), np.int_(0)], 3.333)\n            self.assertEqual(d[np.int_(-2)][np.int_(0)], 3.333)\n\n            # meta, discrete\n            vara = d.domain[\"a\"]\n            metaa = d.domain.index(\"a\")\n            self.assertEqual(d[0, metaa], \"A\")\n            self.assertEqual(d[0, vara], \"A\")\n            self.assertEqual(d[0, \"a\"], \"A\")\n            self.assertEqual(d[0][metaa], \"A\")\n            self.assertEqual(d[0][vara], \"A\")\n            self.assertEqual(d[0][\"a\"], \"A\")\n            self.assertEqual(d[np.int_(0), np.int_(metaa)], \"A\")\n            self.assertEqual(d[np.int_(0)][np.int_(metaa)], \"A\")\n\n            # meta, string\n            vare = d.domain[\"e\"]\n            metae = d.domain.index(\"e\")\n            self.assertEqual(d[0, metae], \"i\")\n            self.assertEqual(d[0, vare], \"i\")\n            self.assertEqual(d[0, \"e\"], \"i\")\n            self.assertEqual(d[0][metae], \"i\")\n            self.assertEqual(d[0][vare], \"i\")\n            self.assertEqual(d[0][\"e\"], \"i\")\n            self.assertEqual(d[np.int_(0), np.int_(metae)], \"i\")\n            self.assertEqual(d[np.int_(0)][np.int_(metae)], \"i\")\n\n    def test_indexing_example(self):\n        import warnings\n\n        with warnings.catch_warnings():\n            warnings.simplefilter(\"ignore\")\n            d = data.Table(\"test2\")\n            e = d[0]\n\n            # regular, discrete\n            varc = d.domain[\"c\"]\n            self.assertEqual(e[1], \"0\")\n            self.assertEqual(e[varc], \"0\")\n            self.assertEqual(e[\"c\"], \"0\")\n            self.assertEqual(e[np.int_(1)], \"0\")\n\n            # regular, continuous\n            varb = d.domain[\"b\"]\n            self.assertEqual(e[0], 0)\n            self.assertEqual(e[varb], 0)\n            self.assertEqual(e[\"b\"], 0)\n            self.assertEqual(e[np.int_(0)], 0)\n\n            # meta, discrete\n            vara = d.domain[\"a\"]\n            metaa = d.domain.index(\"a\")\n            self.assertEqual(e[metaa], \"A\")\n            self.assertEqual(e[vara], \"A\")\n            self.assertEqual(e[\"a\"], \"A\")\n            self.assertEqual(e[np.int_(metaa)], \"A\")\n\n            # meta, string\n            vare = d.domain[\"e\"]\n            metae = d.domain.index(\"e\")\n            self.assertEqual(e[metae], \"i\")\n            self.assertEqual(e[vare], \"i\")\n            self.assertEqual(e[\"e\"], \"i\")\n            self.assertEqual(e[np.int_(metae)], \"i\")\n\n    def test_indexing_assign_value(self):\n        import warnings\n\n        with warnings.catch_warnings():\n            warnings.simplefilter(\"ignore\")\n            d = data.Table(\"test2\")\n\n            # meta\n            vara = d.domain[\"a\"]\n            metaa = d.domain.index(\"a\")\n\n            self.assertEqual(d[0, \"a\"], \"A\")\n            d[0, \"a\"] = \"B\"\n            self.assertEqual(d[0, \"a\"], \"B\")\n            d[0][\"a\"] = \"A\"\n            self.assertEqual(d[0, \"a\"], \"A\")\n\n            d[0, vara] = \"B\"\n            self.assertEqual(d[0, \"a\"], \"B\")\n            d[0][vara] = \"A\"\n            self.assertEqual(d[0, \"a\"], \"A\")\n\n            d[0, metaa] = \"B\"\n            self.assertEqual(d[0, \"a\"], \"B\")\n            d[0][metaa] = \"A\"\n            self.assertEqual(d[0, \"a\"], \"A\")\n\n            d[0, np.int_(metaa)] = \"B\"\n            self.assertEqual(d[0, \"a\"], \"B\")\n            d[0][np.int_(metaa)] = \"A\"\n            self.assertEqual(d[0, \"a\"], \"A\")\n\n            # regular\n            varb = d.domain[\"b\"]\n\n            self.assertEqual(d[0, \"b\"], 0)\n            d[0, \"b\"] = 42\n            self.assertEqual(d[0, \"b\"], 42)\n            d[0][\"b\"] = 0\n            self.assertEqual(d[0, \"b\"], 0)\n\n            d[0, varb] = 42\n            self.assertEqual(d[0, \"b\"], 42)\n            d[0][varb] = 0\n            self.assertEqual(d[0, \"b\"], 0)\n\n            d[0, 0] = 42\n            self.assertEqual(d[0, \"b\"], 42)\n            d[0][0] = 0\n            self.assertEqual(d[0, \"b\"], 0)\n\n            d[0, np.int_(0)] = 42\n            self.assertEqual(d[0, \"b\"], 42)\n            d[0][np.int_(0)] = 0\n            self.assertEqual(d[0, \"b\"], 0)\n\n    @skip_deprecated_length\n    def test_indexing_del_example(self):\n        import warnings\n\n        with warnings.catch_warnings():\n            warnings.simplefilter(\"ignore\")\n            d = data.Table(\"test2\")\n            initlen = len(d)\n\n            # remove first\n            d[4, \"e\"] = \"4ex\"\n            self.assertEqual(d[4, \"e\"], \"4ex\")\n            del d[0]\n            self.assertEqual(len(d), initlen - 1)\n            self.assertEqual(d[3, \"e\"], \"4ex\")\n\n            # remove middle\n            del d[2]\n            self.assertEqual(len(d), initlen - 2)\n            self.assertEqual(d[2, \"e\"], \"4ex\")\n\n            # remove middle\n            del d[4]\n            self.assertEqual(len(d), initlen - 3)\n            self.assertEqual(d[2, \"e\"], \"4ex\")\n\n            # remove last\n            d[-1, \"e\"] = \"was last\"\n            del d[-1]\n            self.assertEqual(len(d), initlen - 4)\n            self.assertEqual(d[2, \"e\"], \"4ex\")\n            self.assertNotEqual(d[-1, \"e\"], \"was last\")\n\n            # remove one before last\n            d[-1, \"e\"] = \"was last\"\n            del d[-2]\n            self.assertEqual(len(d), initlen - 5)\n            self.assertEqual(d[2, \"e\"], \"4ex\")\n            self.assertEqual(d[-1, \"e\"], \"was last\")\n\n            d[np.int_(2), \"e\"] = \"2ex\"\n            del d[np.int_(2)]\n            self.assertEqual(len(d), initlen - 6)\n            self.assertNotEqual(d[2, \"e\"], \"2ex\")\n\n            with self.assertRaises(IndexError):\n                del d[100]\n            self.assertEqual(len(d), initlen - 6)\n\n            with self.assertRaises(IndexError):\n                del d[-100]\n            self.assertEqual(len(d), initlen - 6)\n\n    def test_indexing_assign_example(self):\n        def almost_equal_list(s, t):\n            for e, f in zip(s, t):\n                self.assertAlmostEqual(e, f)\n\n        import warnings\n\n        with warnings.catch_warnings():\n            warnings.simplefilter(\"ignore\")\n            d = data.Table(\"test2\")\n\n            vara = d.domain[\"a\"]\n            metaa = d.domain.index(vara)\n\n            self.assertFalse(isnan(d[0, \"a\"]))\n            d[0] = [\"3.14\", \"1\", \"f\"]\n            almost_equal_list(d[0].values(), [3.14, \"1\", \"f\"])\n            self.assertTrue(isnan(d[0, \"a\"]))\n            d[0] = [3.15, 1, \"t\"]\n            almost_equal_list(d[0].values(), [3.15, \"0\", \"t\"])\n            d[np.int_(0)] = [3.15, 2, \"f\"]\n            almost_equal_list(d[0].values(), [3.15, 2, \"f\"])\n\n            with self.assertRaises(ValueError):\n                d[0] = [\"3.14\", \"1\"]\n\n            with self.assertRaises(ValueError):\n                d[np.int_(0)] = [\"3.14\", \"1\"]\n\n            ex = data.Instance(d.domain, [\"3.16\", \"1\", \"f\"])\n            d[0] = ex\n            almost_equal_list(d[0].values(), [3.16, \"1\", \"f\"])\n\n            ex = data.Instance(d.domain, [\"3.16\", 2, \"t\"])\n            d[np.int_(0)] = ex\n            almost_equal_list(d[0].values(), [3.16, 2, \"t\"])\n\n            ex = data.Instance(d.domain, [\"3.16\", \"1\", \"f\"])\n            ex[\"e\"] = \"mmmapp\"\n            d[0] = ex\n            almost_equal_list(d[0].values(), [3.16, \"1\", \"f\"])\n            self.assertEqual(d[0, \"e\"], \"mmmapp\")\n\n    def test_slice(self):\n        import warnings\n\n        with warnings.catch_warnings():\n            warnings.simplefilter(\"ignore\")\n            d = data.Table(\"test2\")\n            x = d[:3]\n            self.assertEqual(len(x), 3)\n            self.assertEqual([e[0] for e in x], [0, 1.1, 2.22])\n\n            x = d[2:5]\n            self.assertEqual(len(x), 3)\n            self.assertEqual([e[0] for e in x], [2.22, 2.23, 2.24])\n\n            x = d[4:1:-1]\n            self.assertEqual(len(x), 3)\n            self.assertEqual([e[0] for e in x], [2.24, 2.23, 2.22])\n\n            x = d[-3:]\n            self.assertEqual(len(x), 3)\n            self.assertEqual([e[0] for e in x], [2.26, 3.333, Unknown])\n\n    def test_assign_slice_value(self):\n        import warnings\n\n        with warnings.catch_warnings():\n            warnings.simplefilter(\"ignore\")\n            d = data.Table(\"test2\")\n            d[2:5, 0] = 42\n            self.assertEqual([e[0] for e in d],\n                             [0, 1.1, 42, 42, 42, 2.25, 2.26, 3.333, Unknown])\n            d[:3, \"b\"] = 43\n            self.assertEqual([e[0] for e in d],\n                             [43, 43, 43, 42, 42, 2.25, 2.26, 3.333, None])\n            d[-2:, d.domain[0]] = 44\n            self.assertEqual([e[0] for e in d],\n                             [43, 43, 43, 42, 42, 2.25, 2.26, 44, 44])\n\n            d[2:5, \"a\"] = \"A\"\n            self.assertEqual([e[\"a\"] for e in d], list(\"ABAAACCDE\"))\n\n    @skip_deprecated_length\n    def test_del_slice_example(self):\n        import warnings\n\n        with warnings.catch_warnings():\n            warnings.simplefilter(\"ignore\")\n            d = data.Table(\"test2\")\n\n            vals = [e[0] for e in d]\n\n            del d[2:2]\n            self.assertEqual([e[0] for e in d], vals)\n\n            del d[2:5]\n            del vals[2:5]\n            self.assertEqual([e[0] for e in d], vals)\n\n            del d[:]\n            self.assertEqual(len(d), 0)\n\n    @skip_deprecated_length\n    def test_del_slice_ids(self):\n        # __del__ updates `ids` member\n        d = data.Table(\"test2\")\n        ids = d.ids.copy()\n        del d[2:4]\n        np.testing.assert_array_equal(d.ids, np.delete(ids, slice(2, 4)))\n\n    @skip_deprecated_length\n    def test_set_slice_example(self):\n        import warnings\n\n        with warnings.catch_warnings():\n            warnings.simplefilter(\"ignore\")\n            d = data.Table(\"test2\")\n            d[5, 0] = 42\n            d[:3] = d[5]\n            self.assertEqual(d[1, 0], 42)\n\n            d[5:2:-1] = [3, None, None]\n            self.assertEqual([e[0] for e in d],\n                             [42, 42, 42, 3, 3, 3, 2.26, 3.333, None])\n            self.assertTrue(isnan(d[3, 2]))\n\n            d[2:5] = 42\n            self.assertTrue(np.all(d.X[2:5] == 42))\n            self.assertEqual(d.Y[2], 0)\n\n    def test_multiple_indices(self):\n        import warnings\n\n        with warnings.catch_warnings():\n            warnings.simplefilter(\"ignore\")\n            d = data.Table(\"test2\")\n\n            with self.assertRaises(IndexError):\n                x = d[2, 5, 1]\n\n            with self.assertRaises(IndexError):\n                x = d[(2, 5, 1)]\n\n            x = d[[2, 5, 1]]\n            self.assertEqual([e[0] for e in x], [2.22, 2.25, 1.1])\n\n    def test_assign_multiple_indices_value(self):\n        import warnings\n\n        with warnings.catch_warnings():\n            warnings.simplefilter(\"ignore\")\n            d = data.Table(\"test2\")\n\n            d[1:4, \"b\"] = 42\n            self.assertEqual([e[0] for e in d],\n                             [0, 42, 42, 42, 2.24, 2.25, 2.26, 3.333, None])\n\n            d[range(5, 2, -1), \"b\"] = None\n            self.assertEqual([e[d.domain[0]] for e in d],\n                             [0, 42, 42, None, \"?\", \"\", 2.26, 3.333, None])\n\n    @skip_deprecated_length\n    def test_del_multiple_indices_example(self):\n        import warnings\n\n        with warnings.catch_warnings():\n            warnings.simplefilter(\"ignore\")\n            d = data.Table(\"test2\")\n\n            vals = [e[0] for e in d]\n\n            del d[[1, 5, 2]]\n            del vals[5]\n            del vals[2]\n            del vals[1]\n            self.assertEqual([e[0] for e in d], vals)\n\n            del d[range(1, 3)]\n            del vals[1:3]\n            self.assertEqual([e[0] for e in d], vals)\n\n    def test_set_multiple_indices_example(self):\n        import warnings\n\n        with warnings.catch_warnings():\n            warnings.simplefilter(\"ignore\")\n            d = data.Table(\"test2\")\n\n            vals = [e[0] for e in d]\n            d[[1, 2, 5]] = [42, None, None]\n            vals[1] = vals[2] = vals[5] = 42\n            self.assertEqual([e[0] for e in d], vals)\n\n    @skip_deprecated_length\n    def test_views(self):\n        d = data.Table(\"zoo\")\n        crc = d.checksum(True)\n        x = d[:20]\n        self.assertEqual(crc, d.checksum(True))\n        del x[13]\n        self.assertEqual(crc, d.checksum(True))\n        del x[4:9]\n        self.assertEqual(crc, d.checksum(True))\n\n    def test_bool(self):\n        d = data.Table(\"iris\")\n        self.assertTrue(d)\n\n        d = data.Table(\"test3\")\n        self.assertFalse(d)\n\n        d = data.Table(\"iris\")\n        self.assertTrue(d)\n\n    def test_checksum(self):\n        d = data.Table(\"zoo\")\n        d[42, 3] = 0\n        crc1 = d.checksum(False)\n        d[42, 3] = 1\n        crc2 = d.checksum(False)\n        self.assertNotEqual(crc1, crc2)\n        d[42, 3] = 0\n        crc3 = d.checksum(False)\n        self.assertEqual(crc1, crc3)\n        _ = d[42, \"name\"]\n        d[42, \"name\"] = \"non-animal\"\n        crc4 = d.checksum(False)\n        self.assertEqual(crc1, crc4)\n        crc4 = d.checksum(True)\n        crc5 = d.checksum(1)\n        crc6 = d.checksum(False)\n        self.assertNotEqual(crc1, crc4)\n        self.assertNotEqual(crc1, crc5)\n        self.assertEqual(crc1, crc6)\n\n    def test_total_weight(self):\n        d = data.Table(\"zoo\")\n        self.assertEqual(d.total_weight(), len(d))\n\n        d.set_weights(0)\n        d[0].weight = 0.1\n        d[10].weight = 0.2\n        d[-1].weight = 0.3\n        self.assertAlmostEqual(d.total_weight(), 0.6)\n\n    def test_has_missing(self):\n        d = data.Table(\"zoo\")\n        self.assertFalse(d.has_missing())\n        self.assertFalse(d.has_missing_class())\n\n        d[10, 3] = \"?\"\n        self.assertTrue(d.has_missing())\n        self.assertFalse(d.has_missing_class())\n\n        d[10].set_class(\"?\")\n        self.assertTrue(d.has_missing())\n        self.assertTrue(d.has_missing_class())\n\n        d = data.Table(\"test3\")\n        self.assertFalse(d.has_missing())\n        self.assertFalse(d.has_missing_class())\n\n    def test_shuffle(self):\n        d = data.Table(\"zoo\")\n        crc = d.checksum()\n        names = set(str(x[\"name\"]) for x in d)\n\n        d.shuffle()\n        self.assertNotEqual(crc, d.checksum())\n        self.assertSetEqual(names, set(str(x[\"name\"]) for x in d))\n        crc2 = d.checksum()\n\n        x = d[2:10]\n        crcx = x.checksum()\n        d.shuffle()\n        self.assertNotEqual(crc2, d.checksum())\n        self.assertEqual(crcx, x.checksum())\n\n        crc2 = d.checksum()\n        x.shuffle()\n        self.assertNotEqual(crcx, x.checksum())\n        self.assertEqual(crc2, d.checksum())\n\n    @staticmethod\n    def not_less_ex(ex1, ex2):\n        for v1, v2 in zip(ex1, ex2):\n            if v1 != v2:\n                return v1 < v2\n        return True\n\n    @staticmethod\n    def sorted(d):\n        for i in range(1, len(d)):\n            if not TableTestCase.not_less_ex(d[i - 1], d[i]):\n                return False\n        return True\n\n    @staticmethod\n    def not_less_ex_ord(ex1, ex2, ord):\n        for a in ord:\n            if ex1[a] != ex2[a]:\n                return ex1[a] < ex2[a]\n        return True\n\n    @staticmethod\n    def sorted_ord(d, ord):\n        for i in range(1, len(d)):\n            if not TableTestCase.not_less_ex_ord(d[i - 1], d[i], ord):\n                return False\n        return True\n\n    @skip_deprecated_length\n    def test_append(self):\n        d = data.Table(\"test3\")\n        d.append([None] * 3)\n        self.assertEqual(1, len(d))\n        self.assertTrue(all(isnan(i) for i in d[0]))\n\n        d.append([42, \"0\", None])\n        self.assertEqual(2, len(d))\n        self.assertEqual(d[1], [42, \"0\", None])\n\n        assert_array_nanequal(\n            d.metas,\n            np.array([[v.Unknown for v in d.domain.metas]] * 2,\n                     dtype=object))\n\n    @skip_deprecated_length\n    def test_append2(self):\n        d = data.Table(\"iris\")\n        d.shuffle()\n        l1 = len(d)\n        d.append([1, 2, 3, 4, 0])\n        self.assertEqual(len(d), l1 + 1)\n        self.assertEqual(d[-1], [1, 2, 3, 4, 0])\n\n        x = data.Instance(d[10])\n        d.append(x)\n        self.assertEqual(d[-1], d[10])\n\n        x = d[:50]\n        x.ensure_copy()\n        x.append(d[50])\n        self.assertEqual(x[50], d[50])\n\n    @skip_deprecated_length\n    def test_extend(self):\n        d = data.Table(\"iris\")\n        d.shuffle()\n\n        x = d[:5]\n        x.ensure_copy()\n        d.extend(x)\n        for i in range(5):\n            self.assertEqual(d[i], d[-5 + i])\n\n        y = d[:2, 1]\n        x.ensure_copy()\n        x.extend(y)\n        np.testing.assert_almost_equal(x[-2:, 1].X, y.X)\n        self.assertEqual(np.isnan(x).sum(), 8)\n\n    @skip_deprecated_length\n    def test_extend2(self):\n        d = data.Table(\"test3\")\n        d.extend([[None] * 3,\n                  [None] * 3])\n        assert_array_nanequal(\n            d.metas,\n            np.array([[v.Unknown for v in d.domain.metas]] * 2,\n                     dtype=object))\n\n    def test_copy(self):\n        t = data.Table(np.zeros((5, 3)), np.arange(5), np.zeros((5, 3)))\n\n        copy = t.copy()\n        self.assertTrue(np.all(t.X == copy.X))\n        self.assertTrue(np.all(t.Y == copy.Y))\n        self.assertTrue(np.all(t.metas == copy.metas))\n        copy[0] = [1, 1, 1, 1, 1, 1, 1, 1]\n        self.assertFalse(np.all(t.X == copy.X))\n        self.assertFalse(np.all(t.Y == copy.Y))\n        self.assertFalse(np.all(t.metas == copy.metas))\n\n    def test_copy_sparse(self):\n        t = data.Table('iris').to_sparse()\n        copy = t.copy()\n\n        self.assertEqual((t.X != copy.X).nnz, 0)      # sparse matrices match by content\n        np.testing.assert_equal(t.Y, copy.Y)\n        np.testing.assert_equal(t.metas, copy.metas)\n\n        self.assertNotEqual(id(t.X), id(copy.X))\n        self.assertNotEqual(id(t._Y), id(copy._Y))\n        self.assertNotEqual(id(t.metas), id(copy.metas))\n\n    def test_concatenate(self):\n        d1 = data.Domain([data.ContinuousVariable('a1')])\n        t1 = data.Table.from_numpy(d1, [[1],\n                                        [2]])\n        d2 = data.Domain([data.ContinuousVariable('a2')],\n                         metas=[data.StringVariable('s')])\n        t2 = data.Table.from_numpy(d2, [[3],\n                                        [4]], metas=[['foo'],\n                                                     ['fuu']])\n        self.assertRaises(ValueError,\n                          lambda: data.Table.concatenate((t1, t2), axis=5))\n\n        t3 = data.Table.concatenate((t1, t2))\n        self.assertEqual(t3.domain.attributes,\n                         t1.domain.attributes + t2.domain.attributes)\n        self.assertEqual(len(t3.domain.metas), 1)\n        self.assertEqual(t3.X.shape, (2, 2))\n        self.assertRaises(ValueError, lambda: data.Table.concatenate((t3, t1)))\n        self.assertRaises(ValueError, lambda: data.Table.concatenate((t3, t1), axis=0))\n\n        t4 = data.Table.concatenate((t3, t3), axis=0)\n        np.testing.assert_equal(t4.X, [[1, 3],\n                                       [2, 4],\n                                       [1, 3],\n                                       [2, 4]])\n\n    def test_sparse_concatenate_rows(self):\n        iris = Table(\"iris\")\n        iris.X = sp.csc_matrix(iris.X)\n        new = Table.concatenate([iris, iris], axis=0)\n        self.assertEqual(len(new), 300)\n        self.assertTrue(sp.issparse(new.X), \"Concatenated X is not sparse.\")\n        self.assertFalse(sp.issparse(new.Y), \"Concatenated Y is not dense.\")\n        self.assertFalse(sp.issparse(new.metas), \"Concatenated metas is not dense.\")\n        self.assertEqual(len(new.ids), 300)\n\n    @skip_deprecated_length\n    def test_convert_through_append(self):\n        d = data.Table(\"iris\")\n        dom2 = data.Domain([d.domain[0], d.domain[2], d.domain[4]])\n        d2 = data.Table(dom2)\n        dom3 = data.Domain([d.domain[1], d.domain[2]], None)\n        d3 = data.Table(dom3)\n        for e in d[:5]:\n            d2.append(e)\n            d3.append(e)\n        for e, e2, e3 in zip(d, d2, d3):\n            self.assertEqual(e[0], e2[0])\n            self.assertEqual(e[1], e3[0])\n\n    def test_pickle(self):\n        import pickle\n\n        d = data.Table(\"zoo\")\n        s = pickle.dumps(d)\n        d2 = pickle.loads(s)\n        self.assertEqual(d[0], d2[0])\n\n        self.assertEqual(d.checksum(include_metas=False),\n                         d2.checksum(include_metas=False))\n\n        d = data.Table(\"iris\")\n        s = pickle.dumps(d)\n        d2 = pickle.loads(s)\n        self.assertEqual(d[0], d2[0])\n        self.assertEqual(d.checksum(include_metas=False),\n                         d2.checksum(include_metas=False))\n\n    def test_translate_through_slice(self):\n        d = data.Table(\"iris\")\n        dom = data.Domain([\"petal length\", \"sepal length\", \"iris\"],\n                          source=d.domain)\n        d_ref = d[:10, dom.variables]\n        self.assertEqual(d_ref.domain.class_var, d.domain.class_var)\n        self.assertEqual(d_ref[0, \"petal length\"], d[0, \"petal length\"])\n        self.assertEqual(d_ref[0, \"sepal length\"], d[0, \"sepal length\"])\n        self.assertEqual(d_ref.X.shape, (10, 2))\n        self.assertEqual(d_ref.Y.shape, (10,))\n\n    def test_saveTab(self):\n        d = data.Table(\"iris\")[:3]\n        d.save(\"test-save.tab\")\n        try:\n            d2 = data.Table(\"test-save.tab\")\n            for e1, e2 in zip(d, d2):\n                self.assertEqual(e1, e2)\n        finally:\n            os.remove(\"test-save.tab\")\n            os.remove(\"test-save.tab.metadata\")\n\n        dom = data.Domain([data.ContinuousVariable(\"a\")])\n        d = data.Table(dom, [[i] for i in range(3)])\n        d.save(\"test-save.tab\")\n        try:\n            d2 = data.Table(\"test-save.tab\")\n            self.assertEqual(len(d.domain.attributes), 1)\n            self.assertEqual(d.domain.class_var, None)\n            for i in range(3):\n                self.assertEqual(d2[i], [i])\n        finally:\n            os.remove(\"test-save.tab\")\n\n        dom = data.Domain([data.ContinuousVariable(\"a\")], None)\n        d = data.Table(dom, [[i] for i in range(3)])\n        d.save(\"test-save.tab\")\n        try:\n            d2 = data.Table(\"test-save.tab\")\n            self.assertEqual(len(d.domain.attributes), 1)\n            for i in range(3):\n                self.assertEqual(d2[i], [i])\n        finally:\n            os.remove(\"test-save.tab\")\n\n        d = data.Table(\"zoo\")\n        d.save(\"test-zoo.tab\")\n        dd = data.Table(\"test-zoo\")\n        try:\n            self.assertTupleEqual(d.domain.metas, dd.domain.metas,\n                                  msg=\"Meta attributes don't match.\")\n            self.assertTupleEqual(d.domain.variables, dd.domain.variables,\n                                  msg=\"Attributes don't match.\")\n\n            np.testing.assert_almost_equal(d.W, dd.W,\n                                           err_msg=\"Weights don't match.\")\n            for i in range(10):\n                for j in d.domain.variables:\n                    self.assertEqual(d[i][j], dd[i][j])\n        finally:\n            os.remove(\"test-zoo.tab\")\n\n        d = data.Table(\"zoo\")\n        d.set_weights(range(len(d)))\n        d.save(\"test-zoo-weights.tab\")\n        dd = data.Table(\"test-zoo-weights\")\n        try:\n            self.assertTupleEqual(d.domain.metas, dd.domain.metas,\n                                  msg=\"Meta attributes don't match.\")\n            self.assertTupleEqual(d.domain.variables, dd.domain.variables,\n                                  msg=\"Attributes don't match.\")\n\n            np.testing.assert_almost_equal(d.W, dd.W,\n                                           err_msg=\"Weights don't match.\")\n            for i in range(10):\n                for j in d.domain.variables:\n                    self.assertEqual(d[i][j], dd[i][j])\n        finally:\n            os.remove(\"test-zoo-weights.tab\")\n\n    def test_save_pickle(self):\n        table = data.Table(\"iris\")\n        try:\n            table.save(\"iris.pickle\")\n            table2 = data.Table.from_file(\"iris.pickle\")\n            np.testing.assert_almost_equal(table.X, table2.X)\n            np.testing.assert_almost_equal(table.Y, table2.Y)\n            self.assertEqual(table.domain[0], table2.domain[0])\n        finally:\n            os.remove(\"iris.pickle\")\n\n    def test_from_numpy(self):\n        a = np.arange(20, dtype=\"d\").reshape((4, 5))\n        a[:, -1] = [0, 0, 0, 1]\n        dom = data.Domain([data.ContinuousVariable(x) for x in \"abcd\"],\n                          data.DiscreteVariable(\"e\", values=[\"no\", \"yes\"]))\n        table = data.Table(dom, a)\n        for i in range(4):\n            self.assertEqual(table[i].get_class(), \"no\" if i < 3 else \"yes\")\n            for j in range(5):\n                self.assertEqual(a[i, j], table[i, j])\n                table[i, j] = random.random()\n                self.assertEqual(a[i, j], table[i, j])\n\n        with self.assertRaises(IndexError):\n            table[0, -5] = 5\n\n    def test_filter_is_defined(self):\n        d = data.Table(\"iris\")\n        d[1, 4] = Unknown\n        self.assertTrue(isnan(d[1, 4]))\n        d[140, 0] = Unknown\n        e = filter.IsDefined()(d)\n        self.assertEqual(len(e), len(d) - 2)\n        self.assertEqual(e[0], d[0])\n        self.assertEqual(e[1], d[2])\n        self.assertEqual(e[147], d[149])\n        self.assertTrue(d.has_missing())\n        self.assertFalse(e.has_missing())\n\n    def test_filter_has_class(self):\n        d = data.Table(\"iris\")\n        d[1, 4] = Unknown\n        self.assertTrue(isnan(d[1, 4]))\n        d[140, 0] = Unknown\n        e = filter.HasClass()(d)\n        self.assertEqual(len(e), len(d) - 1)\n        self.assertEqual(e[0], d[0])\n        self.assertEqual(e[1], d[2])\n        self.assertEqual(e[148], d[149])\n        self.assertTrue(d.has_missing())\n        self.assertTrue(e.has_missing())\n        self.assertFalse(e.has_missing_class())\n\n    def test_filter_random(self):\n        d = data.Table(\"iris\")\n        e = filter.Random(50)(d)\n        self.assertEqual(len(e), 50)\n        e = filter.Random(50, negate=True)(d)\n        self.assertEqual(len(e), 100)\n        for i in range(5):\n            e = filter.Random(0.2)(d)\n            self.assertEqual(len(e), 30)\n            bc = np.bincount(np.array(e.Y[:], dtype=int))\n            if min(bc) > 7:\n                break\n        else:\n            self.fail(\"Filter returns too uneven distributions\")\n\n    def test_filter_values_nested(self):\n        d = data.Table(\"iris\")\n        f1 = filter.FilterContinuous(d.columns.sepal_length,\n                                     filter.FilterContinuous.Between,\n                                     min=4.5, max=5.0)\n        f2 = filter.FilterContinuous(d.columns.sepal_width,\n                                     filter.FilterContinuous.Between,\n                                     min=3.1, max=3.4)\n        f3 = filter.FilterDiscrete(d.columns.iris, [0, 1])\n        f = filter.Values([filter.Values([f1, f2], conjunction=False), f3])\n        self.assertEqual(41, len(f(d)))\n\n    def test_filter_string_works_for_numeric_columns(self):\n        var = StringVariable(\"s\")\n        data = Table(Domain([], metas=[var]), [[x] for x in range(21)])\n        # 1, 2, 3, ..., 18, 19, 20\n\n        fs = filter.FilterString\n        filters = [\n            ((fs.Greater, \"5\"), dict(rows=4)),\n            # 6, 7, 8, 9\n            ((fs.Between, \"15\", \"2\"), dict(rows=6)),\n            # 15, 16, 17, 18, 19, 2\n            ((fs.Contains, \"2\"), dict(rows=3)),\n            # 2, 12, 20\n        ]\n\n        for args, expected in filters:\n            f = fs(var, *args)\n            filtered_data = filter.Values([f])(data)\n            self.assertEqual(len(filtered_data), expected[\"rows\"],\n                             \"{} returned wrong number of rows\".format(args))\n\n    def test_filter_value_continuous(self):\n        d = data.Table(\"iris\")\n        col = d.X[:, 2]\n\n        v = d.columns\n        f = filter.FilterContinuous(v.petal_length,\n                                    filter.FilterContinuous.Between,\n                                    min=4.5, max=5.1)\n\n        x = filter.Values([f])(d)\n        self.assertTrue(np.all(x.X[:, 2] >= 4.5))\n        self.assertTrue(np.all(x.X[:, 2] <= 5.1))\n        self.assertEqual(sum((col >= 4.5) * (col <= 5.1)), len(x))\n\n        f.ref = 5.1\n        f.oper = filter.FilterContinuous.Equal\n        x = filter.Values([f])(d)\n        self.assertTrue(np.all(x.X[:, 2] == 5.1))\n        self.assertEqual(sum(col == 5.1), len(x))\n\n        f.oper = filter.FilterContinuous.NotEqual\n        x = filter.Values([f])(d)\n        self.assertTrue(np.all(x.X[:, 2] != 5.1))\n        self.assertEqual(sum(col != 5.1), len(x))\n\n        f.oper = filter.FilterContinuous.Less\n        x = filter.Values([f])(d)\n        self.assertTrue(np.all(x.X[:, 2] < 5.1))\n        self.assertEqual(sum(col < 5.1), len(x))\n\n        f.oper = filter.FilterContinuous.LessEqual\n        x = filter.Values([f])(d)\n        self.assertTrue(np.all(x.X[:, 2] <= 5.1))\n        self.assertEqual(sum(col <= 5.1), len(x))\n\n        f.oper = filter.FilterContinuous.Greater\n        x = filter.Values([f])(d)\n        self.assertTrue(np.all(x.X[:, 2] > 5.1))\n        self.assertEqual(sum(col > 5.1), len(x))\n\n        f.oper = filter.FilterContinuous.GreaterEqual\n        x = filter.Values([f])(d)\n        self.assertTrue(np.all(x.X[:, 2] >= 5.1))\n        self.assertEqual(sum(col >= 5.1), len(x))\n\n        f.oper = filter.FilterContinuous.Outside\n        f.ref, f.max = 4.5, 5.1\n        x = filter.Values([f])(d)\n        for e in x:\n            self.assertTrue(e[2] < 4.5 or e[2] > 5.1)\n        self.assertEqual(sum((col < 4.5) + (col > 5.1)), len(x))\n\n        f.oper = filter.FilterContinuous.IsDefined\n        f.ref = f.max = None\n        x = filter.Values([f])(d)\n        self.assertEqual(len(x), len(d))\n\n        d[:30, v.petal_length] = Unknown\n        x = filter.Values([f])(d)\n        self.assertEqual(len(x), len(d) - 30)\n\n    def test_filter_value_continuous_args(self):\n        d = data.Table(\"iris\")\n        col = d.X[:, 2]\n        v = d.columns\n\n        f = filter.FilterContinuous(v.petal_length,\n                                    filter.FilterContinuous.Equal, ref=5.1)\n        x = filter.Values([f])(d)\n        self.assertTrue(np.all(x.X[:, 2] == 5.1))\n        self.assertEqual(sum(col == 5.1), len(x))\n\n        f = filter.FilterContinuous(2,\n                                    filter.FilterContinuous.Equal, ref=5.1)\n        self.assertTrue(np.all(x.X[:, 2] == 5.1))\n        self.assertEqual(sum(col == 5.1), len(x))\n\n        f = filter.FilterContinuous(\"petal length\",\n                                    filter.FilterContinuous.Equal, ref=5.1)\n        self.assertTrue(np.all(x.X[:, 2] == 5.1))\n        self.assertEqual(sum(col == 5.1), len(x))\n\n        f = filter.FilterContinuous(\"sepal length\",\n                                    filter.FilterContinuous.Equal, ref=5.1)\n        f.column = 2\n        self.assertTrue(np.all(x.X[:, 2] == 5.1))\n        self.assertEqual(sum(col == 5.1), len(x))\n\n        f = filter.FilterContinuous(\"sepal length\",\n                                    filter.FilterContinuous.Equal, ref=5.1)\n        f.column = v.petal_length\n        self.assertTrue(np.all(x.X[:, 2] == 5.1))\n        self.assertEqual(sum(col == 5.1), len(x))\n\n        f = filter.FilterContinuous(v.petal_length,\n                                    filter.FilterContinuous.Equal, ref=18)\n        f.ref = 5.1\n        x = filter.Values([f])(d)\n        self.assertTrue(np.all(x.X[:, 2] == 5.1))\n        self.assertEqual(sum(col == 5.1), len(x))\n\n        f = filter.FilterContinuous(v.petal_length,\n                                    filter.FilterContinuous.Equal, ref=18)\n        f.ref = 5.1\n        x = filter.Values([f])(d)\n        self.assertTrue(np.all(x.X[:, 2] == 5.1))\n        self.assertEqual(sum(col == 5.1), len(x))\n\n    def test_valueFilter_discrete(self):\n        d = data.Table(\"zoo\")\n\n        f = filter.FilterDiscrete(d.domain.class_var, values=[2, 3, 4])\n        for e in filter.Values([f])(d):\n            self.assertTrue(e.get_class() in [2, 3, 4])\n\n        f.values = [\"mammal\"]\n        for e in filter.Values([f])(d):\n            self.assertEqual(e.get_class(), \"mammal\")\n\n        f = filter.FilterDiscrete(d.domain.class_var, values=[2, \"mammal\"])\n        for e in filter.Values([f])(d):\n            self.assertTrue(e.get_class() in [2, \"mammal\"])\n\n        f = filter.FilterDiscrete(d.domain.class_var, values=[2, \"martian\"])\n        self.assertRaises(ValueError, d._filter_values, f)\n\n        f = filter.FilterDiscrete(d.domain.class_var, values=[2, data.Table])\n        self.assertRaises(TypeError, d._filter_values, f)\n\n        v = d.columns\n        f = filter.FilterDiscrete(v.hair, values=None)\n        self.assertEqual(len(filter.Values([f])(d)), len(d))\n\n        d[:5, v.hair] = Unknown\n        self.assertEqual(len(filter.Values([f])(d)), len(d) - 5)\n\n    def test_valueFilter_string_is_defined(self):\n        d = data.Table(\"test9.tab\")\n        f = filter.FilterString(-5, filter.FilterString.IsDefined)\n        x = filter.Values([f])(d)\n        self.assertEqual(len(x), 7)\n\n    def test_valueFilter_discrete_meta_is_defined(self):\n        d = data.Table(\"test9.tab\")\n        f = filter.FilterDiscrete(-4, None)\n        x = filter.Values([f])(d)\n        self.assertEqual(len(x), 8)\n\n    def test_valueFilter_string_case_sens(self):\n        d = data.Table(\"zoo\")\n        col = d[:, \"name\"].metas[:, 0]\n\n        f = filter.FilterString(\"name\",\n                                filter.FilterString.Equal, \"girl\")\n        x = filter.Values([f])(d)\n        self.assertEqual(len(x), 1)\n        self.assertEqual(x[0, \"name\"], \"girl\")\n        self.assertTrue(np.all(x.metas == \"girl\"))\n\n        f.oper = f.NotEqual\n        x = filter.Values([f])(d)\n        self.assertEqual(len(x), len(d) - 1)\n        self.assertTrue(np.all(x[:, \"name\"] != \"girl\"))\n\n        f.oper = f.Less\n        x = filter.Values([f])(d)\n        self.assertEqual(len(x), sum(col < \"girl\"))\n        self.assertTrue(np.all(x.metas < \"girl\"))\n\n        f.oper = f.LessEqual\n        x = filter.Values([f])(d)\n        self.assertEqual(len(x), sum(col <= \"girl\"))\n        self.assertTrue(np.all(x.metas <= \"girl\"))\n\n        f.oper = f.Greater\n        x = filter.Values([f])(d)\n        self.assertEqual(len(x), sum(col > \"girl\"))\n        self.assertTrue(np.all(x.metas > \"girl\"))\n\n        f.oper = f.GreaterEqual\n        x = filter.Values([f])(d)\n        self.assertEqual(len(x), sum(col >= \"girl\"))\n        self.assertTrue(np.all(x.metas >= \"girl\"))\n\n        f.oper = f.Between\n        f.max = \"lion\"\n        x = filter.Values([f])(d)\n        self.assertEqual(len(x), sum((col >= \"girl\") * (col <= \"lion\")))\n        self.assertTrue(np.all(x.metas >= \"girl\"))\n        self.assertTrue(np.all(x.metas <= \"lion\"))\n\n        f.oper = f.Outside\n        x = filter.Values([f])(d)\n        self.assertEqual(len(x), sum(col < \"girl\") + sum(col > \"lion\"))\n        self.assertTrue(np.all((x.metas < \"girl\") + (x.metas > \"lion\")))\n\n        f.oper = f.Contains\n        f.ref = \"ea\"\n        x = filter.Values([f])(d)\n        for e in x:\n            self.assertTrue(\"ea\" in e[\"name\"])\n        self.assertEqual(len(x), len([e for e in col if \"ea\" in e]))\n\n        f.oper = f.StartsWith\n        f.ref = \"sea\"\n        x = filter.Values([f])(d)\n        for e in x:\n            self.assertTrue(str(e[\"name\"]).startswith(\"sea\"))\n        self.assertEqual(len(x), len([e for e in col if e.startswith(\"sea\")]))\n\n        f.oper = f.EndsWith\n        f.ref = \"ion\"\n        x = filter.Values([f])(d)\n        for e in x:\n            self.assertTrue(str(e[\"name\"]).endswith(\"ion\"))\n        self.assertEqual(len(x), len([e for e in col if e.endswith(\"ion\")]))\n\n    def test_valueFilter_string_case_insens(self):\n        d = data.Table(\"zoo\")\n        d[d[:, \"name\"].metas[:, 0] == \"girl\", \"name\"] = \"GIrl\"\n\n        col = d[:, \"name\"].metas[:, 0]\n\n        f = filter.FilterString(\"name\",\n                                filter.FilterString.Equal, \"giRL\")\n        f.case_sensitive = False\n        x = filter.Values([f])(d)\n        self.assertEqual(len(x), 1)\n        self.assertEqual(x[0, \"name\"], \"GIrl\")\n        self.assertTrue(np.all(x.metas == \"GIrl\"))\n\n        f.oper = f.NotEqual\n        x = filter.Values([f])(d)\n        self.assertEqual(len(x), len(d) - 1)\n        self.assertTrue(np.all(x[:, \"name\"] != \"GIrl\"))\n\n        f.oper = f.Less\n        f.ref = \"CHiCKEN\"\n        x = filter.Values([f])(d)\n        self.assertEqual(len(x), sum(col < \"chicken\") - 1)  # girl!\n        self.assertTrue(np.all(x.metas < \"chicken\"))\n\n        f.oper = f.LessEqual\n        x = filter.Values([f])(d)\n        self.assertEqual(len(x), sum(col <= \"chicken\") - 1)\n        self.assertTrue(np.all(x.metas <= \"chicken\"))\n\n        f.oper = f.Greater\n        x = filter.Values([f])(d)\n        self.assertEqual(len(x), sum(col > \"chicken\") + 1)\n        for e in x:\n            self.assertGreater(str(e[\"name\"]).lower(), \"chicken\")\n\n        f.oper = f.GreaterEqual\n        x = filter.Values([f])(d)\n        self.assertEqual(len(x), sum(col >= \"chicken\") + 1)\n        for e in x:\n            self.assertGreaterEqual(str(e[\"name\"]).lower(), \"chicken\")\n\n        f.oper = f.Between\n        f.max = \"liOn\"\n        x = filter.Values([f])(d)\n        self.assertEqual(len(x), sum((col >= \"chicken\") * (col <= \"lion\")) + 1)\n        for e in x:\n            self.assertTrue(\"chicken\" <= str(e[\"name\"]).lower() <= \"lion\")\n\n        f.oper = f.Outside\n        x = filter.Values([f])(d)\n        self.assertEqual(len(x), sum(col < \"chicken\") + sum(col > \"lion\") - 1)\n        self.assertTrue(np.all((x.metas < \"chicken\") + (x.metas > \"lion\")))\n\n        f.oper = f.Contains\n        f.ref = \"iR\"\n        x = filter.Values([f])(d)\n        for e in x:\n            self.assertTrue(\"ir\" in str(e[\"name\"]).lower())\n        self.assertEqual(len(x), len([e for e in col if \"ir\" in e]) + 1)\n\n        f.oper = f.StartsWith\n        f.ref = \"GI\"\n        x = filter.Values([f])(d)\n        for e in x:\n            self.assertTrue(str(e[\"name\"]).lower().startswith(\"gi\"))\n        self.assertEqual(len(x),\n                         len([e for e in col if e.lower().startswith(\"gi\")]))\n\n        f.oper = f.EndsWith\n        f.ref = \"ion\"\n        x = filter.Values([f])(d)\n        for e in x:\n            self.assertTrue(str(e[\"name\"]).endswith(\"ion\"))\n            self.assertTrue(str(e[\"name\"]).endswith(\"ion\"))\n        self.assertEqual(len(x), len([e for e in col if e.endswith(\"ion\")]))\n\n    def test_valueFilter_regex(self):\n        d = data.Table(\"zoo\")\n        f = filter.FilterRegex(d.domain['name'], '^c...$')\n        x = filter.Values([f])(d)\n        self.assertEqual(len(x), 7)\n\n    def test_valueFilter_stringList(self):\n        data = Table(\"zoo\")\n        var = data.domain[\"name\"]\n\n        fs = filter.FilterStringList\n        filters = [\n            (([\"swan\", \"tuna\", \"wasp\"], True), dict(rows=3)),\n            (([\"swan\", \"tuna\", \"wasp\"], False), dict(rows=3)),\n            (([\"WoRm\", \"TOad\", \"vOLe\"], True), dict(rows=0)),\n            (([\"WoRm\", \"TOad\", \"vOLe\"], False), dict(rows=3)),\n        ]\n\n        for args, expected in filters:\n            f = fs(var, *args)\n            filtered_data = filter.Values([f])(data)\n            self.assertEqual(len(filtered_data), expected[\"rows\"],\n                             \"{} returned wrong number of rows\".format(args))\n\n    def test_table_dtypes(self):\n        table = data.Table(\"iris\")\n        metas = np.hstack((table.metas, table.Y.reshape(len(table), 1)))\n        attributes_metas = table.domain.metas + table.domain.class_vars\n        domain_metas = data.Domain(table.domain.attributes,\n                                   table.domain.class_vars,\n                                   attributes_metas)\n        table_metas = data.Table(domain_metas, table.X, table.Y, metas)\n        new_table = data.Table(data.Domain(table_metas.domain.metas,\n                                           table_metas.domain.metas,\n                                           table_metas.domain.metas),\n                               table_metas)\n        self.assertEqual(new_table.X.dtype, np.float64)\n        self.assertEqual(new_table.Y.dtype, np.float64)\n        self.assertEqual(new_table.metas.dtype, np.float64)\n\n    def test_attributes(self):\n        table = data.Table(\"iris\")\n        table.attributes = {1: \"test\"}\n        table2 = table[:4]\n        self.assertEqual(table2.attributes[1], \"test\")\n        table2.attributes[1] = \"modified\"\n        self.assertEqual(table.attributes[1], \"modified\")\n\n    # TODO Test conjunctions and disjunctions of conditions\n\n    def test_is_sparse(self):\n        table = data.Table(\"iris\")\n        self.assertFalse(table.is_sparse())\n\n        table.X = sp.csr_matrix(table.X)\n        self.assertTrue(table.is_sparse())\n\n    def test_repr_sparse_with_one_row(self):\n        table = data.Table(\"iris\")[:1]\n        table.X = sp.csr_matrix(table.X)\n        repr(table)     # make sure repr does not crash\n\n    def test_inf(self):\n        a = np.array([[2,   0,      0,      0],\n                      [0,   np.nan, np.nan, 1],\n                      [0,   0,      np.inf, 0]])\n        with self.assertWarns(Warning):\n            tab = data.Table(a)\n        self.assertEqual(tab.get_nan_frequency_attribute(), 3/12)",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 40,
                            "end_lineno": 1286,
                            "parent": null
                        }
                    ],
                    "added_entities": [
                        {
                            "file_name": "Orange/tests/test_table.py",
                            "type": "method",
                            "name": "TableTestCase.test_inf",
                            "content": "class TableTestCase(unittest.TestCase):\n    def setUp(self):\n        Variable._clear_all_caches()\n        data.table.dataset_dirs.append(test_dirname())\n\n    def tearDown(self):\n        data.table.dataset_dirs.remove(test_dirname())\n\n    def test_indexing_class(self):\n        d = data.Table(\"test1\")\n        self.assertEqual([e.get_class() for e in d], [\"t\", \"t\", \"f\"])\n        cind = len(d.domain) - 1\n        self.assertEqual([e[cind] for e in d], [\"t\", \"t\", \"f\"])\n        self.assertEqual([e[\"d\"] for e in d], [\"t\", \"t\", \"f\"])\n        cvar = d.domain.class_var\n        self.assertEqual([e[cvar] for e in d], [\"t\", \"t\", \"f\"])\n\n    def test_filename(self):\n        dir = data.table.get_sample_datasets_dir()\n        d = data.Table(\"iris\")\n        self.assertEqual(d.__file__, os.path.join(dir, \"iris.tab\"))\n\n        d = data.Table(\"test2.tab\")\n        self.assertTrue(d.__file__.endswith(\"test2.tab\"))  # platform dependent\n\n    def test_indexing(self):\n        import warnings\n\n        with warnings.catch_warnings():\n            warnings.simplefilter(\"ignore\")\n            d = data.Table(\"test2\")\n\n            # regular, discrete\n            varc = d.domain[\"c\"]\n            self.assertEqual(d[0, 1], \"0\")\n            self.assertEqual(d[0, varc], \"0\")\n            self.assertEqual(d[0, \"c\"], \"0\")\n            self.assertEqual(d[0][1], \"0\")\n            self.assertEqual(d[0][varc], \"0\")\n            self.assertEqual(d[0][\"c\"], \"0\")\n            self.assertEqual(d[np.int_(0), np.int_(1)], \"0\")\n            self.assertEqual(d[np.int_(0)][np.int_(1)], \"0\")\n\n            # regular, continuous\n            varb = d.domain[\"b\"]\n            self.assertEqual(d[0, 0], 0)\n            self.assertEqual(d[0, varb], 0)\n            self.assertEqual(d[0, \"b\"], 0)\n            self.assertEqual(d[0][0], 0)\n            self.assertEqual(d[0][varb], 0)\n            self.assertEqual(d[0][\"b\"], 0)\n            self.assertEqual(d[np.int_(0), np.int_(0)], 0)\n            self.assertEqual(d[np.int_(0)][np.int_(0)], 0)\n\n            # negative\n            varb = d.domain[\"b\"]\n            self.assertEqual(d[-2, 0], 3.333)\n            self.assertEqual(d[-2, varb], 3.333)\n            self.assertEqual(d[-2, \"b\"], 3.333)\n            self.assertEqual(d[-2][0], 3.333)\n            self.assertEqual(d[-2][varb], 3.333)\n            self.assertEqual(d[-2][\"b\"], 3.333)\n            self.assertEqual(d[np.int_(-2), np.int_(0)], 3.333)\n            self.assertEqual(d[np.int_(-2)][np.int_(0)], 3.333)\n\n            # meta, discrete\n            vara = d.domain[\"a\"]\n            metaa = d.domain.index(\"a\")\n            self.assertEqual(d[0, metaa], \"A\")\n            self.assertEqual(d[0, vara], \"A\")\n            self.assertEqual(d[0, \"a\"], \"A\")\n            self.assertEqual(d[0][metaa], \"A\")\n            self.assertEqual(d[0][vara], \"A\")\n            self.assertEqual(d[0][\"a\"], \"A\")\n            self.assertEqual(d[np.int_(0), np.int_(metaa)], \"A\")\n            self.assertEqual(d[np.int_(0)][np.int_(metaa)], \"A\")\n\n            # meta, string\n            vare = d.domain[\"e\"]\n            metae = d.domain.index(\"e\")\n            self.assertEqual(d[0, metae], \"i\")\n            self.assertEqual(d[0, vare], \"i\")\n            self.assertEqual(d[0, \"e\"], \"i\")\n            self.assertEqual(d[0][metae], \"i\")\n            self.assertEqual(d[0][vare], \"i\")\n            self.assertEqual(d[0][\"e\"], \"i\")\n            self.assertEqual(d[np.int_(0), np.int_(metae)], \"i\")\n            self.assertEqual(d[np.int_(0)][np.int_(metae)], \"i\")\n\n    def test_indexing_example(self):\n        import warnings\n\n        with warnings.catch_warnings():\n            warnings.simplefilter(\"ignore\")\n            d = data.Table(\"test2\")\n            e = d[0]\n\n            # regular, discrete\n            varc = d.domain[\"c\"]\n            self.assertEqual(e[1], \"0\")\n            self.assertEqual(e[varc], \"0\")\n            self.assertEqual(e[\"c\"], \"0\")\n            self.assertEqual(e[np.int_(1)], \"0\")\n\n            # regular, continuous\n            varb = d.domain[\"b\"]\n            self.assertEqual(e[0], 0)\n            self.assertEqual(e[varb], 0)\n            self.assertEqual(e[\"b\"], 0)\n            self.assertEqual(e[np.int_(0)], 0)\n\n            # meta, discrete\n            vara = d.domain[\"a\"]\n            metaa = d.domain.index(\"a\")\n            self.assertEqual(e[metaa], \"A\")\n            self.assertEqual(e[vara], \"A\")\n            self.assertEqual(e[\"a\"], \"A\")\n            self.assertEqual(e[np.int_(metaa)], \"A\")\n\n            # meta, string\n            vare = d.domain[\"e\"]\n            metae = d.domain.index(\"e\")\n            self.assertEqual(e[metae], \"i\")\n            self.assertEqual(e[vare], \"i\")\n            self.assertEqual(e[\"e\"], \"i\")\n            self.assertEqual(e[np.int_(metae)], \"i\")\n\n    def test_indexing_assign_value(self):\n        import warnings\n\n        with warnings.catch_warnings():\n            warnings.simplefilter(\"ignore\")\n            d = data.Table(\"test2\")\n\n            # meta\n            vara = d.domain[\"a\"]\n            metaa = d.domain.index(\"a\")\n\n            self.assertEqual(d[0, \"a\"], \"A\")\n            d[0, \"a\"] = \"B\"\n            self.assertEqual(d[0, \"a\"], \"B\")\n            d[0][\"a\"] = \"A\"\n            self.assertEqual(d[0, \"a\"], \"A\")\n\n            d[0, vara] = \"B\"\n            self.assertEqual(d[0, \"a\"], \"B\")\n            d[0][vara] = \"A\"\n            self.assertEqual(d[0, \"a\"], \"A\")\n\n            d[0, metaa] = \"B\"\n            self.assertEqual(d[0, \"a\"], \"B\")\n            d[0][metaa] = \"A\"\n            self.assertEqual(d[0, \"a\"], \"A\")\n\n            d[0, np.int_(metaa)] = \"B\"\n            self.assertEqual(d[0, \"a\"], \"B\")\n            d[0][np.int_(metaa)] = \"A\"\n            self.assertEqual(d[0, \"a\"], \"A\")\n\n            # regular\n            varb = d.domain[\"b\"]\n\n            self.assertEqual(d[0, \"b\"], 0)\n            d[0, \"b\"] = 42\n            self.assertEqual(d[0, \"b\"], 42)\n            d[0][\"b\"] = 0\n            self.assertEqual(d[0, \"b\"], 0)\n\n            d[0, varb] = 42\n            self.assertEqual(d[0, \"b\"], 42)\n            d[0][varb] = 0\n            self.assertEqual(d[0, \"b\"], 0)\n\n            d[0, 0] = 42\n            self.assertEqual(d[0, \"b\"], 42)\n            d[0][0] = 0\n            self.assertEqual(d[0, \"b\"], 0)\n\n            d[0, np.int_(0)] = 42\n            self.assertEqual(d[0, \"b\"], 42)\n            d[0][np.int_(0)] = 0\n            self.assertEqual(d[0, \"b\"], 0)\n\n    @skip_deprecated_length\n    def test_indexing_del_example(self):\n        import warnings\n\n        with warnings.catch_warnings():\n            warnings.simplefilter(\"ignore\")\n            d = data.Table(\"test2\")\n            initlen = len(d)\n\n            # remove first\n            d[4, \"e\"] = \"4ex\"\n            self.assertEqual(d[4, \"e\"], \"4ex\")\n            del d[0]\n            self.assertEqual(len(d), initlen - 1)\n            self.assertEqual(d[3, \"e\"], \"4ex\")\n\n            # remove middle\n            del d[2]\n            self.assertEqual(len(d), initlen - 2)\n            self.assertEqual(d[2, \"e\"], \"4ex\")\n\n            # remove middle\n            del d[4]\n            self.assertEqual(len(d), initlen - 3)\n            self.assertEqual(d[2, \"e\"], \"4ex\")\n\n            # remove last\n            d[-1, \"e\"] = \"was last\"\n            del d[-1]\n            self.assertEqual(len(d), initlen - 4)\n            self.assertEqual(d[2, \"e\"], \"4ex\")\n            self.assertNotEqual(d[-1, \"e\"], \"was last\")\n\n            # remove one before last\n            d[-1, \"e\"] = \"was last\"\n            del d[-2]\n            self.assertEqual(len(d), initlen - 5)\n            self.assertEqual(d[2, \"e\"], \"4ex\")\n            self.assertEqual(d[-1, \"e\"], \"was last\")\n\n            d[np.int_(2), \"e\"] = \"2ex\"\n            del d[np.int_(2)]\n            self.assertEqual(len(d), initlen - 6)\n            self.assertNotEqual(d[2, \"e\"], \"2ex\")\n\n            with self.assertRaises(IndexError):\n                del d[100]\n            self.assertEqual(len(d), initlen - 6)\n\n            with self.assertRaises(IndexError):\n                del d[-100]\n            self.assertEqual(len(d), initlen - 6)\n\n    def test_indexing_assign_example(self):\n        def almost_equal_list(s, t):\n            for e, f in zip(s, t):\n                self.assertAlmostEqual(e, f)\n\n        import warnings\n\n        with warnings.catch_warnings():\n            warnings.simplefilter(\"ignore\")\n            d = data.Table(\"test2\")\n\n            vara = d.domain[\"a\"]\n            metaa = d.domain.index(vara)\n\n            self.assertFalse(isnan(d[0, \"a\"]))\n            d[0] = [\"3.14\", \"1\", \"f\"]\n            almost_equal_list(d[0].values(), [3.14, \"1\", \"f\"])\n            self.assertTrue(isnan(d[0, \"a\"]))\n            d[0] = [3.15, 1, \"t\"]\n            almost_equal_list(d[0].values(), [3.15, \"0\", \"t\"])\n            d[np.int_(0)] = [3.15, 2, \"f\"]\n            almost_equal_list(d[0].values(), [3.15, 2, \"f\"])\n\n            with self.assertRaises(ValueError):\n                d[0] = [\"3.14\", \"1\"]\n\n            with self.assertRaises(ValueError):\n                d[np.int_(0)] = [\"3.14\", \"1\"]\n\n            ex = data.Instance(d.domain, [\"3.16\", \"1\", \"f\"])\n            d[0] = ex\n            almost_equal_list(d[0].values(), [3.16, \"1\", \"f\"])\n\n            ex = data.Instance(d.domain, [\"3.16\", 2, \"t\"])\n            d[np.int_(0)] = ex\n            almost_equal_list(d[0].values(), [3.16, 2, \"t\"])\n\n            ex = data.Instance(d.domain, [\"3.16\", \"1\", \"f\"])\n            ex[\"e\"] = \"mmmapp\"\n            d[0] = ex\n            almost_equal_list(d[0].values(), [3.16, \"1\", \"f\"])\n            self.assertEqual(d[0, \"e\"], \"mmmapp\")\n\n    def test_slice(self):\n        import warnings\n\n        with warnings.catch_warnings():\n            warnings.simplefilter(\"ignore\")\n            d = data.Table(\"test2\")\n            x = d[:3]\n            self.assertEqual(len(x), 3)\n            self.assertEqual([e[0] for e in x], [0, 1.1, 2.22])\n\n            x = d[2:5]\n            self.assertEqual(len(x), 3)\n            self.assertEqual([e[0] for e in x], [2.22, 2.23, 2.24])\n\n            x = d[4:1:-1]\n            self.assertEqual(len(x), 3)\n            self.assertEqual([e[0] for e in x], [2.24, 2.23, 2.22])\n\n            x = d[-3:]\n            self.assertEqual(len(x), 3)\n            self.assertEqual([e[0] for e in x], [2.26, 3.333, Unknown])\n\n    def test_assign_slice_value(self):\n        import warnings\n\n        with warnings.catch_warnings():\n            warnings.simplefilter(\"ignore\")\n            d = data.Table(\"test2\")\n            d[2:5, 0] = 42\n            self.assertEqual([e[0] for e in d],\n                             [0, 1.1, 42, 42, 42, 2.25, 2.26, 3.333, Unknown])\n            d[:3, \"b\"] = 43\n            self.assertEqual([e[0] for e in d],\n                             [43, 43, 43, 42, 42, 2.25, 2.26, 3.333, None])\n            d[-2:, d.domain[0]] = 44\n            self.assertEqual([e[0] for e in d],\n                             [43, 43, 43, 42, 42, 2.25, 2.26, 44, 44])\n\n            d[2:5, \"a\"] = \"A\"\n            self.assertEqual([e[\"a\"] for e in d], list(\"ABAAACCDE\"))\n\n    @skip_deprecated_length\n    def test_del_slice_example(self):\n        import warnings\n\n        with warnings.catch_warnings():\n            warnings.simplefilter(\"ignore\")\n            d = data.Table(\"test2\")\n\n            vals = [e[0] for e in d]\n\n            del d[2:2]\n            self.assertEqual([e[0] for e in d], vals)\n\n            del d[2:5]\n            del vals[2:5]\n            self.assertEqual([e[0] for e in d], vals)\n\n            del d[:]\n            self.assertEqual(len(d), 0)\n\n    @skip_deprecated_length\n    def test_del_slice_ids(self):\n        # __del__ updates `ids` member\n        d = data.Table(\"test2\")\n        ids = d.ids.copy()\n        del d[2:4]\n        np.testing.assert_array_equal(d.ids, np.delete(ids, slice(2, 4)))\n\n    @skip_deprecated_length\n    def test_set_slice_example(self):\n        import warnings\n\n        with warnings.catch_warnings():\n            warnings.simplefilter(\"ignore\")\n            d = data.Table(\"test2\")\n            d[5, 0] = 42\n            d[:3] = d[5]\n            self.assertEqual(d[1, 0], 42)\n\n            d[5:2:-1] = [3, None, None]\n            self.assertEqual([e[0] for e in d],\n                             [42, 42, 42, 3, 3, 3, 2.26, 3.333, None])\n            self.assertTrue(isnan(d[3, 2]))\n\n            d[2:5] = 42\n            self.assertTrue(np.all(d.X[2:5] == 42))\n            self.assertEqual(d.Y[2], 0)\n\n    def test_multiple_indices(self):\n        import warnings\n\n        with warnings.catch_warnings():\n            warnings.simplefilter(\"ignore\")\n            d = data.Table(\"test2\")\n\n            with self.assertRaises(IndexError):\n                x = d[2, 5, 1]\n\n            with self.assertRaises(IndexError):\n                x = d[(2, 5, 1)]\n\n            x = d[[2, 5, 1]]\n            self.assertEqual([e[0] for e in x], [2.22, 2.25, 1.1])\n\n    def test_assign_multiple_indices_value(self):\n        import warnings\n\n        with warnings.catch_warnings():\n            warnings.simplefilter(\"ignore\")\n            d = data.Table(\"test2\")\n\n            d[1:4, \"b\"] = 42\n            self.assertEqual([e[0] for e in d],\n                             [0, 42, 42, 42, 2.24, 2.25, 2.26, 3.333, None])\n\n            d[range(5, 2, -1), \"b\"] = None\n            self.assertEqual([e[d.domain[0]] for e in d],\n                             [0, 42, 42, None, \"?\", \"\", 2.26, 3.333, None])\n\n    @skip_deprecated_length\n    def test_del_multiple_indices_example(self):\n        import warnings\n\n        with warnings.catch_warnings():\n            warnings.simplefilter(\"ignore\")\n            d = data.Table(\"test2\")\n\n            vals = [e[0] for e in d]\n\n            del d[[1, 5, 2]]\n            del vals[5]\n            del vals[2]\n            del vals[1]\n            self.assertEqual([e[0] for e in d], vals)\n\n            del d[range(1, 3)]\n            del vals[1:3]\n            self.assertEqual([e[0] for e in d], vals)\n\n    def test_set_multiple_indices_example(self):\n        import warnings\n\n        with warnings.catch_warnings():\n            warnings.simplefilter(\"ignore\")\n            d = data.Table(\"test2\")\n\n            vals = [e[0] for e in d]\n            d[[1, 2, 5]] = [42, None, None]\n            vals[1] = vals[2] = vals[5] = 42\n            self.assertEqual([e[0] for e in d], vals)\n\n    @skip_deprecated_length\n    def test_views(self):\n        d = data.Table(\"zoo\")\n        crc = d.checksum(True)\n        x = d[:20]\n        self.assertEqual(crc, d.checksum(True))\n        del x[13]\n        self.assertEqual(crc, d.checksum(True))\n        del x[4:9]\n        self.assertEqual(crc, d.checksum(True))\n\n    def test_bool(self):\n        d = data.Table(\"iris\")\n        self.assertTrue(d)\n\n        d = data.Table(\"test3\")\n        self.assertFalse(d)\n\n        d = data.Table(\"iris\")\n        self.assertTrue(d)\n\n    def test_checksum(self):\n        d = data.Table(\"zoo\")\n        d[42, 3] = 0\n        crc1 = d.checksum(False)\n        d[42, 3] = 1\n        crc2 = d.checksum(False)\n        self.assertNotEqual(crc1, crc2)\n        d[42, 3] = 0\n        crc3 = d.checksum(False)\n        self.assertEqual(crc1, crc3)\n        _ = d[42, \"name\"]\n        d[42, \"name\"] = \"non-animal\"\n        crc4 = d.checksum(False)\n        self.assertEqual(crc1, crc4)\n        crc4 = d.checksum(True)\n        crc5 = d.checksum(1)\n        crc6 = d.checksum(False)\n        self.assertNotEqual(crc1, crc4)\n        self.assertNotEqual(crc1, crc5)\n        self.assertEqual(crc1, crc6)\n\n    def test_total_weight(self):\n        d = data.Table(\"zoo\")\n        self.assertEqual(d.total_weight(), len(d))\n\n        d.set_weights(0)\n        d[0].weight = 0.1\n        d[10].weight = 0.2\n        d[-1].weight = 0.3\n        self.assertAlmostEqual(d.total_weight(), 0.6)\n\n    def test_has_missing(self):\n        d = data.Table(\"zoo\")\n        self.assertFalse(d.has_missing())\n        self.assertFalse(d.has_missing_class())\n\n        d[10, 3] = \"?\"\n        self.assertTrue(d.has_missing())\n        self.assertFalse(d.has_missing_class())\n\n        d[10].set_class(\"?\")\n        self.assertTrue(d.has_missing())\n        self.assertTrue(d.has_missing_class())\n\n        d = data.Table(\"test3\")\n        self.assertFalse(d.has_missing())\n        self.assertFalse(d.has_missing_class())\n\n    def test_shuffle(self):\n        d = data.Table(\"zoo\")\n        crc = d.checksum()\n        names = set(str(x[\"name\"]) for x in d)\n\n        d.shuffle()\n        self.assertNotEqual(crc, d.checksum())\n        self.assertSetEqual(names, set(str(x[\"name\"]) for x in d))\n        crc2 = d.checksum()\n\n        x = d[2:10]\n        crcx = x.checksum()\n        d.shuffle()\n        self.assertNotEqual(crc2, d.checksum())\n        self.assertEqual(crcx, x.checksum())\n\n        crc2 = d.checksum()\n        x.shuffle()\n        self.assertNotEqual(crcx, x.checksum())\n        self.assertEqual(crc2, d.checksum())\n\n    @staticmethod\n    def not_less_ex(ex1, ex2):\n        for v1, v2 in zip(ex1, ex2):\n            if v1 != v2:\n                return v1 < v2\n        return True\n\n    @staticmethod\n    def sorted(d):\n        for i in range(1, len(d)):\n            if not TableTestCase.not_less_ex(d[i - 1], d[i]):\n                return False\n        return True\n\n    @staticmethod\n    def not_less_ex_ord(ex1, ex2, ord):\n        for a in ord:\n            if ex1[a] != ex2[a]:\n                return ex1[a] < ex2[a]\n        return True\n\n    @staticmethod\n    def sorted_ord(d, ord):\n        for i in range(1, len(d)):\n            if not TableTestCase.not_less_ex_ord(d[i - 1], d[i], ord):\n                return False\n        return True\n\n    @skip_deprecated_length\n    def test_append(self):\n        d = data.Table(\"test3\")\n        d.append([None] * 3)\n        self.assertEqual(1, len(d))\n        self.assertTrue(all(isnan(i) for i in d[0]))\n\n        d.append([42, \"0\", None])\n        self.assertEqual(2, len(d))\n        self.assertEqual(d[1], [42, \"0\", None])\n\n        assert_array_nanequal(\n            d.metas,\n            np.array([[v.Unknown for v in d.domain.metas]] * 2,\n                     dtype=object))\n\n    @skip_deprecated_length\n    def test_append2(self):\n        d = data.Table(\"iris\")\n        d.shuffle()\n        l1 = len(d)\n        d.append([1, 2, 3, 4, 0])\n        self.assertEqual(len(d), l1 + 1)\n        self.assertEqual(d[-1], [1, 2, 3, 4, 0])\n\n        x = data.Instance(d[10])\n        d.append(x)\n        self.assertEqual(d[-1], d[10])\n\n        x = d[:50]\n        x.ensure_copy()\n        x.append(d[50])\n        self.assertEqual(x[50], d[50])\n\n    @skip_deprecated_length\n    def test_extend(self):\n        d = data.Table(\"iris\")\n        d.shuffle()\n\n        x = d[:5]\n        x.ensure_copy()\n        d.extend(x)\n        for i in range(5):\n            self.assertEqual(d[i], d[-5 + i])\n\n        y = d[:2, 1]\n        x.ensure_copy()\n        x.extend(y)\n        np.testing.assert_almost_equal(x[-2:, 1].X, y.X)\n        self.assertEqual(np.isnan(x).sum(), 8)\n\n    @skip_deprecated_length\n    def test_extend2(self):\n        d = data.Table(\"test3\")\n        d.extend([[None] * 3,\n                  [None] * 3])\n        assert_array_nanequal(\n            d.metas,\n            np.array([[v.Unknown for v in d.domain.metas]] * 2,\n                     dtype=object))\n\n    def test_copy(self):\n        t = data.Table(np.zeros((5, 3)), np.arange(5), np.zeros((5, 3)))\n\n        copy = t.copy()\n        self.assertTrue(np.all(t.X == copy.X))\n        self.assertTrue(np.all(t.Y == copy.Y))\n        self.assertTrue(np.all(t.metas == copy.metas))\n        copy[0] = [1, 1, 1, 1, 1, 1, 1, 1]\n        self.assertFalse(np.all(t.X == copy.X))\n        self.assertFalse(np.all(t.Y == copy.Y))\n        self.assertFalse(np.all(t.metas == copy.metas))\n\n    def test_copy_sparse(self):\n        t = data.Table('iris').to_sparse()\n        copy = t.copy()\n\n        self.assertEqual((t.X != copy.X).nnz, 0)      # sparse matrices match by content\n        np.testing.assert_equal(t.Y, copy.Y)\n        np.testing.assert_equal(t.metas, copy.metas)\n\n        self.assertNotEqual(id(t.X), id(copy.X))\n        self.assertNotEqual(id(t._Y), id(copy._Y))\n        self.assertNotEqual(id(t.metas), id(copy.metas))\n\n    def test_concatenate(self):\n        d1 = data.Domain([data.ContinuousVariable('a1')])\n        t1 = data.Table.from_numpy(d1, [[1],\n                                        [2]])\n        d2 = data.Domain([data.ContinuousVariable('a2')],\n                         metas=[data.StringVariable('s')])\n        t2 = data.Table.from_numpy(d2, [[3],\n                                        [4]], metas=[['foo'],\n                                                     ['fuu']])\n        self.assertRaises(ValueError,\n                          lambda: data.Table.concatenate((t1, t2), axis=5))\n\n        t3 = data.Table.concatenate((t1, t2))\n        self.assertEqual(t3.domain.attributes,\n                         t1.domain.attributes + t2.domain.attributes)\n        self.assertEqual(len(t3.domain.metas), 1)\n        self.assertEqual(t3.X.shape, (2, 2))\n        self.assertRaises(ValueError, lambda: data.Table.concatenate((t3, t1)))\n        self.assertRaises(ValueError, lambda: data.Table.concatenate((t3, t1), axis=0))\n\n        t4 = data.Table.concatenate((t3, t3), axis=0)\n        np.testing.assert_equal(t4.X, [[1, 3],\n                                       [2, 4],\n                                       [1, 3],\n                                       [2, 4]])\n\n    def test_sparse_concatenate_rows(self):\n        iris = Table(\"iris\")\n        iris.X = sp.csc_matrix(iris.X)\n        new = Table.concatenate([iris, iris], axis=0)\n        self.assertEqual(len(new), 300)\n        self.assertTrue(sp.issparse(new.X), \"Concatenated X is not sparse.\")\n        self.assertFalse(sp.issparse(new.Y), \"Concatenated Y is not dense.\")\n        self.assertFalse(sp.issparse(new.metas), \"Concatenated metas is not dense.\")\n        self.assertEqual(len(new.ids), 300)\n\n    @skip_deprecated_length\n    def test_convert_through_append(self):\n        d = data.Table(\"iris\")\n        dom2 = data.Domain([d.domain[0], d.domain[2], d.domain[4]])\n        d2 = data.Table(dom2)\n        dom3 = data.Domain([d.domain[1], d.domain[2]], None)\n        d3 = data.Table(dom3)\n        for e in d[:5]:\n            d2.append(e)\n            d3.append(e)\n        for e, e2, e3 in zip(d, d2, d3):\n            self.assertEqual(e[0], e2[0])\n            self.assertEqual(e[1], e3[0])\n\n    def test_pickle(self):\n        import pickle\n\n        d = data.Table(\"zoo\")\n        s = pickle.dumps(d)\n        d2 = pickle.loads(s)\n        self.assertEqual(d[0], d2[0])\n\n        self.assertEqual(d.checksum(include_metas=False),\n                         d2.checksum(include_metas=False))\n\n        d = data.Table(\"iris\")\n        s = pickle.dumps(d)\n        d2 = pickle.loads(s)\n        self.assertEqual(d[0], d2[0])\n        self.assertEqual(d.checksum(include_metas=False),\n                         d2.checksum(include_metas=False))\n\n    def test_translate_through_slice(self):\n        d = data.Table(\"iris\")\n        dom = data.Domain([\"petal length\", \"sepal length\", \"iris\"],\n                          source=d.domain)\n        d_ref = d[:10, dom.variables]\n        self.assertEqual(d_ref.domain.class_var, d.domain.class_var)\n        self.assertEqual(d_ref[0, \"petal length\"], d[0, \"petal length\"])\n        self.assertEqual(d_ref[0, \"sepal length\"], d[0, \"sepal length\"])\n        self.assertEqual(d_ref.X.shape, (10, 2))\n        self.assertEqual(d_ref.Y.shape, (10,))\n\n    def test_saveTab(self):\n        d = data.Table(\"iris\")[:3]\n        d.save(\"test-save.tab\")\n        try:\n            d2 = data.Table(\"test-save.tab\")\n            for e1, e2 in zip(d, d2):\n                self.assertEqual(e1, e2)\n        finally:\n            os.remove(\"test-save.tab\")\n            os.remove(\"test-save.tab.metadata\")\n\n        dom = data.Domain([data.ContinuousVariable(\"a\")])\n        d = data.Table(dom, [[i] for i in range(3)])\n        d.save(\"test-save.tab\")\n        try:\n            d2 = data.Table(\"test-save.tab\")\n            self.assertEqual(len(d.domain.attributes), 1)\n            self.assertEqual(d.domain.class_var, None)\n            for i in range(3):\n                self.assertEqual(d2[i], [i])\n        finally:\n            os.remove(\"test-save.tab\")\n\n        dom = data.Domain([data.ContinuousVariable(\"a\")], None)\n        d = data.Table(dom, [[i] for i in range(3)])\n        d.save(\"test-save.tab\")\n        try:\n            d2 = data.Table(\"test-save.tab\")\n            self.assertEqual(len(d.domain.attributes), 1)\n            for i in range(3):\n                self.assertEqual(d2[i], [i])\n        finally:\n            os.remove(\"test-save.tab\")\n\n        d = data.Table(\"zoo\")\n        d.save(\"test-zoo.tab\")\n        dd = data.Table(\"test-zoo\")\n        try:\n            self.assertTupleEqual(d.domain.metas, dd.domain.metas,\n                                  msg=\"Meta attributes don't match.\")\n            self.assertTupleEqual(d.domain.variables, dd.domain.variables,\n                                  msg=\"Attributes don't match.\")\n\n            np.testing.assert_almost_equal(d.W, dd.W,\n                                           err_msg=\"Weights don't match.\")\n            for i in range(10):\n                for j in d.domain.variables:\n                    self.assertEqual(d[i][j], dd[i][j])\n        finally:\n            os.remove(\"test-zoo.tab\")\n\n        d = data.Table(\"zoo\")\n        d.set_weights(range(len(d)))\n        d.save(\"test-zoo-weights.tab\")\n        dd = data.Table(\"test-zoo-weights\")\n        try:\n            self.assertTupleEqual(d.domain.metas, dd.domain.metas,\n                                  msg=\"Meta attributes don't match.\")\n            self.assertTupleEqual(d.domain.variables, dd.domain.variables,\n                                  msg=\"Attributes don't match.\")\n\n            np.testing.assert_almost_equal(d.W, dd.W,\n                                           err_msg=\"Weights don't match.\")\n            for i in range(10):\n                for j in d.domain.variables:\n                    self.assertEqual(d[i][j], dd[i][j])\n        finally:\n            os.remove(\"test-zoo-weights.tab\")\n\n    def test_save_pickle(self):\n        table = data.Table(\"iris\")\n        try:\n            table.save(\"iris.pickle\")\n            table2 = data.Table.from_file(\"iris.pickle\")\n            np.testing.assert_almost_equal(table.X, table2.X)\n            np.testing.assert_almost_equal(table.Y, table2.Y)\n            self.assertEqual(table.domain[0], table2.domain[0])\n        finally:\n            os.remove(\"iris.pickle\")\n\n    def test_from_numpy(self):\n        a = np.arange(20, dtype=\"d\").reshape((4, 5))\n        a[:, -1] = [0, 0, 0, 1]\n        dom = data.Domain([data.ContinuousVariable(x) for x in \"abcd\"],\n                          data.DiscreteVariable(\"e\", values=[\"no\", \"yes\"]))\n        table = data.Table(dom, a)\n        for i in range(4):\n            self.assertEqual(table[i].get_class(), \"no\" if i < 3 else \"yes\")\n            for j in range(5):\n                self.assertEqual(a[i, j], table[i, j])\n                table[i, j] = random.random()\n                self.assertEqual(a[i, j], table[i, j])\n\n        with self.assertRaises(IndexError):\n            table[0, -5] = 5\n\n    def test_filter_is_defined(self):\n        d = data.Table(\"iris\")\n        d[1, 4] = Unknown\n        self.assertTrue(isnan(d[1, 4]))\n        d[140, 0] = Unknown\n        e = filter.IsDefined()(d)\n        self.assertEqual(len(e), len(d) - 2)\n        self.assertEqual(e[0], d[0])\n        self.assertEqual(e[1], d[2])\n        self.assertEqual(e[147], d[149])\n        self.assertTrue(d.has_missing())\n        self.assertFalse(e.has_missing())\n\n    def test_filter_has_class(self):\n        d = data.Table(\"iris\")\n        d[1, 4] = Unknown\n        self.assertTrue(isnan(d[1, 4]))\n        d[140, 0] = Unknown\n        e = filter.HasClass()(d)\n        self.assertEqual(len(e), len(d) - 1)\n        self.assertEqual(e[0], d[0])\n        self.assertEqual(e[1], d[2])\n        self.assertEqual(e[148], d[149])\n        self.assertTrue(d.has_missing())\n        self.assertTrue(e.has_missing())\n        self.assertFalse(e.has_missing_class())\n\n    def test_filter_random(self):\n        d = data.Table(\"iris\")\n        e = filter.Random(50)(d)\n        self.assertEqual(len(e), 50)\n        e = filter.Random(50, negate=True)(d)\n        self.assertEqual(len(e), 100)\n        for i in range(5):\n            e = filter.Random(0.2)(d)\n            self.assertEqual(len(e), 30)\n            bc = np.bincount(np.array(e.Y[:], dtype=int))\n            if min(bc) > 7:\n                break\n        else:\n            self.fail(\"Filter returns too uneven distributions\")\n\n    def test_filter_values_nested(self):\n        d = data.Table(\"iris\")\n        f1 = filter.FilterContinuous(d.columns.sepal_length,\n                                     filter.FilterContinuous.Between,\n                                     min=4.5, max=5.0)\n        f2 = filter.FilterContinuous(d.columns.sepal_width,\n                                     filter.FilterContinuous.Between,\n                                     min=3.1, max=3.4)\n        f3 = filter.FilterDiscrete(d.columns.iris, [0, 1])\n        f = filter.Values([filter.Values([f1, f2], conjunction=False), f3])\n        self.assertEqual(41, len(f(d)))\n\n    def test_filter_string_works_for_numeric_columns(self):\n        var = StringVariable(\"s\")\n        data = Table(Domain([], metas=[var]), [[x] for x in range(21)])\n        # 1, 2, 3, ..., 18, 19, 20\n\n        fs = filter.FilterString\n        filters = [\n            ((fs.Greater, \"5\"), dict(rows=4)),\n            # 6, 7, 8, 9\n            ((fs.Between, \"15\", \"2\"), dict(rows=6)),\n            # 15, 16, 17, 18, 19, 2\n            ((fs.Contains, \"2\"), dict(rows=3)),\n            # 2, 12, 20\n        ]\n\n        for args, expected in filters:\n            f = fs(var, *args)\n            filtered_data = filter.Values([f])(data)\n            self.assertEqual(len(filtered_data), expected[\"rows\"],\n                             \"{} returned wrong number of rows\".format(args))\n\n    def test_filter_value_continuous(self):\n        d = data.Table(\"iris\")\n        col = d.X[:, 2]\n\n        v = d.columns\n        f = filter.FilterContinuous(v.petal_length,\n                                    filter.FilterContinuous.Between,\n                                    min=4.5, max=5.1)\n\n        x = filter.Values([f])(d)\n        self.assertTrue(np.all(x.X[:, 2] >= 4.5))\n        self.assertTrue(np.all(x.X[:, 2] <= 5.1))\n        self.assertEqual(sum((col >= 4.5) * (col <= 5.1)), len(x))\n\n        f.ref = 5.1\n        f.oper = filter.FilterContinuous.Equal\n        x = filter.Values([f])(d)\n        self.assertTrue(np.all(x.X[:, 2] == 5.1))\n        self.assertEqual(sum(col == 5.1), len(x))\n\n        f.oper = filter.FilterContinuous.NotEqual\n        x = filter.Values([f])(d)\n        self.assertTrue(np.all(x.X[:, 2] != 5.1))\n        self.assertEqual(sum(col != 5.1), len(x))\n\n        f.oper = filter.FilterContinuous.Less\n        x = filter.Values([f])(d)\n        self.assertTrue(np.all(x.X[:, 2] < 5.1))\n        self.assertEqual(sum(col < 5.1), len(x))\n\n        f.oper = filter.FilterContinuous.LessEqual\n        x = filter.Values([f])(d)\n        self.assertTrue(np.all(x.X[:, 2] <= 5.1))\n        self.assertEqual(sum(col <= 5.1), len(x))\n\n        f.oper = filter.FilterContinuous.Greater\n        x = filter.Values([f])(d)\n        self.assertTrue(np.all(x.X[:, 2] > 5.1))\n        self.assertEqual(sum(col > 5.1), len(x))\n\n        f.oper = filter.FilterContinuous.GreaterEqual\n        x = filter.Values([f])(d)\n        self.assertTrue(np.all(x.X[:, 2] >= 5.1))\n        self.assertEqual(sum(col >= 5.1), len(x))\n\n        f.oper = filter.FilterContinuous.Outside\n        f.ref, f.max = 4.5, 5.1\n        x = filter.Values([f])(d)\n        for e in x:\n            self.assertTrue(e[2] < 4.5 or e[2] > 5.1)\n        self.assertEqual(sum((col < 4.5) + (col > 5.1)), len(x))\n\n        f.oper = filter.FilterContinuous.IsDefined\n        f.ref = f.max = None\n        x = filter.Values([f])(d)\n        self.assertEqual(len(x), len(d))\n\n        d[:30, v.petal_length] = Unknown\n        x = filter.Values([f])(d)\n        self.assertEqual(len(x), len(d) - 30)\n\n    def test_filter_value_continuous_args(self):\n        d = data.Table(\"iris\")\n        col = d.X[:, 2]\n        v = d.columns\n\n        f = filter.FilterContinuous(v.petal_length,\n                                    filter.FilterContinuous.Equal, ref=5.1)\n        x = filter.Values([f])(d)\n        self.assertTrue(np.all(x.X[:, 2] == 5.1))\n        self.assertEqual(sum(col == 5.1), len(x))\n\n        f = filter.FilterContinuous(2,\n                                    filter.FilterContinuous.Equal, ref=5.1)\n        self.assertTrue(np.all(x.X[:, 2] == 5.1))\n        self.assertEqual(sum(col == 5.1), len(x))\n\n        f = filter.FilterContinuous(\"petal length\",\n                                    filter.FilterContinuous.Equal, ref=5.1)\n        self.assertTrue(np.all(x.X[:, 2] == 5.1))\n        self.assertEqual(sum(col == 5.1), len(x))\n\n        f = filter.FilterContinuous(\"sepal length\",\n                                    filter.FilterContinuous.Equal, ref=5.1)\n        f.column = 2\n        self.assertTrue(np.all(x.X[:, 2] == 5.1))\n        self.assertEqual(sum(col == 5.1), len(x))\n\n        f = filter.FilterContinuous(\"sepal length\",\n                                    filter.FilterContinuous.Equal, ref=5.1)\n        f.column = v.petal_length\n        self.assertTrue(np.all(x.X[:, 2] == 5.1))\n        self.assertEqual(sum(col == 5.1), len(x))\n\n        f = filter.FilterContinuous(v.petal_length,\n                                    filter.FilterContinuous.Equal, ref=18)\n        f.ref = 5.1\n        x = filter.Values([f])(d)\n        self.assertTrue(np.all(x.X[:, 2] == 5.1))\n        self.assertEqual(sum(col == 5.1), len(x))\n\n        f = filter.FilterContinuous(v.petal_length,\n                                    filter.FilterContinuous.Equal, ref=18)\n        f.ref = 5.1\n        x = filter.Values([f])(d)\n        self.assertTrue(np.all(x.X[:, 2] == 5.1))\n        self.assertEqual(sum(col == 5.1), len(x))\n\n    def test_valueFilter_discrete(self):\n        d = data.Table(\"zoo\")\n\n        f = filter.FilterDiscrete(d.domain.class_var, values=[2, 3, 4])\n        for e in filter.Values([f])(d):\n            self.assertTrue(e.get_class() in [2, 3, 4])\n\n        f.values = [\"mammal\"]\n        for e in filter.Values([f])(d):\n            self.assertEqual(e.get_class(), \"mammal\")\n\n        f = filter.FilterDiscrete(d.domain.class_var, values=[2, \"mammal\"])\n        for e in filter.Values([f])(d):\n            self.assertTrue(e.get_class() in [2, \"mammal\"])\n\n        f = filter.FilterDiscrete(d.domain.class_var, values=[2, \"martian\"])\n        self.assertRaises(ValueError, d._filter_values, f)\n\n        f = filter.FilterDiscrete(d.domain.class_var, values=[2, data.Table])\n        self.assertRaises(TypeError, d._filter_values, f)\n\n        v = d.columns\n        f = filter.FilterDiscrete(v.hair, values=None)\n        self.assertEqual(len(filter.Values([f])(d)), len(d))\n\n        d[:5, v.hair] = Unknown\n        self.assertEqual(len(filter.Values([f])(d)), len(d) - 5)\n\n    def test_valueFilter_string_is_defined(self):\n        d = data.Table(\"test9.tab\")\n        f = filter.FilterString(-5, filter.FilterString.IsDefined)\n        x = filter.Values([f])(d)\n        self.assertEqual(len(x), 7)\n\n    def test_valueFilter_discrete_meta_is_defined(self):\n        d = data.Table(\"test9.tab\")\n        f = filter.FilterDiscrete(-4, None)\n        x = filter.Values([f])(d)\n        self.assertEqual(len(x), 8)\n\n    def test_valueFilter_string_case_sens(self):\n        d = data.Table(\"zoo\")\n        col = d[:, \"name\"].metas[:, 0]\n\n        f = filter.FilterString(\"name\",\n                                filter.FilterString.Equal, \"girl\")\n        x = filter.Values([f])(d)\n        self.assertEqual(len(x), 1)\n        self.assertEqual(x[0, \"name\"], \"girl\")\n        self.assertTrue(np.all(x.metas == \"girl\"))\n\n        f.oper = f.NotEqual\n        x = filter.Values([f])(d)\n        self.assertEqual(len(x), len(d) - 1)\n        self.assertTrue(np.all(x[:, \"name\"] != \"girl\"))\n\n        f.oper = f.Less\n        x = filter.Values([f])(d)\n        self.assertEqual(len(x), sum(col < \"girl\"))\n        self.assertTrue(np.all(x.metas < \"girl\"))\n\n        f.oper = f.LessEqual\n        x = filter.Values([f])(d)\n        self.assertEqual(len(x), sum(col <= \"girl\"))\n        self.assertTrue(np.all(x.metas <= \"girl\"))\n\n        f.oper = f.Greater\n        x = filter.Values([f])(d)\n        self.assertEqual(len(x), sum(col > \"girl\"))\n        self.assertTrue(np.all(x.metas > \"girl\"))\n\n        f.oper = f.GreaterEqual\n        x = filter.Values([f])(d)\n        self.assertEqual(len(x), sum(col >= \"girl\"))\n        self.assertTrue(np.all(x.metas >= \"girl\"))\n\n        f.oper = f.Between\n        f.max = \"lion\"\n        x = filter.Values([f])(d)\n        self.assertEqual(len(x), sum((col >= \"girl\") * (col <= \"lion\")))\n        self.assertTrue(np.all(x.metas >= \"girl\"))\n        self.assertTrue(np.all(x.metas <= \"lion\"))\n\n        f.oper = f.Outside\n        x = filter.Values([f])(d)\n        self.assertEqual(len(x), sum(col < \"girl\") + sum(col > \"lion\"))\n        self.assertTrue(np.all((x.metas < \"girl\") + (x.metas > \"lion\")))\n\n        f.oper = f.Contains\n        f.ref = \"ea\"\n        x = filter.Values([f])(d)\n        for e in x:\n            self.assertTrue(\"ea\" in e[\"name\"])\n        self.assertEqual(len(x), len([e for e in col if \"ea\" in e]))\n\n        f.oper = f.StartsWith\n        f.ref = \"sea\"\n        x = filter.Values([f])(d)\n        for e in x:\n            self.assertTrue(str(e[\"name\"]).startswith(\"sea\"))\n        self.assertEqual(len(x), len([e for e in col if e.startswith(\"sea\")]))\n\n        f.oper = f.EndsWith\n        f.ref = \"ion\"\n        x = filter.Values([f])(d)\n        for e in x:\n            self.assertTrue(str(e[\"name\"]).endswith(\"ion\"))\n        self.assertEqual(len(x), len([e for e in col if e.endswith(\"ion\")]))\n\n    def test_valueFilter_string_case_insens(self):\n        d = data.Table(\"zoo\")\n        d[d[:, \"name\"].metas[:, 0] == \"girl\", \"name\"] = \"GIrl\"\n\n        col = d[:, \"name\"].metas[:, 0]\n\n        f = filter.FilterString(\"name\",\n                                filter.FilterString.Equal, \"giRL\")\n        f.case_sensitive = False\n        x = filter.Values([f])(d)\n        self.assertEqual(len(x), 1)\n        self.assertEqual(x[0, \"name\"], \"GIrl\")\n        self.assertTrue(np.all(x.metas == \"GIrl\"))\n\n        f.oper = f.NotEqual\n        x = filter.Values([f])(d)\n        self.assertEqual(len(x), len(d) - 1)\n        self.assertTrue(np.all(x[:, \"name\"] != \"GIrl\"))\n\n        f.oper = f.Less\n        f.ref = \"CHiCKEN\"\n        x = filter.Values([f])(d)\n        self.assertEqual(len(x), sum(col < \"chicken\") - 1)  # girl!\n        self.assertTrue(np.all(x.metas < \"chicken\"))\n\n        f.oper = f.LessEqual\n        x = filter.Values([f])(d)\n        self.assertEqual(len(x), sum(col <= \"chicken\") - 1)\n        self.assertTrue(np.all(x.metas <= \"chicken\"))\n\n        f.oper = f.Greater\n        x = filter.Values([f])(d)\n        self.assertEqual(len(x), sum(col > \"chicken\") + 1)\n        for e in x:\n            self.assertGreater(str(e[\"name\"]).lower(), \"chicken\")\n\n        f.oper = f.GreaterEqual\n        x = filter.Values([f])(d)\n        self.assertEqual(len(x), sum(col >= \"chicken\") + 1)\n        for e in x:\n            self.assertGreaterEqual(str(e[\"name\"]).lower(), \"chicken\")\n\n        f.oper = f.Between\n        f.max = \"liOn\"\n        x = filter.Values([f])(d)\n        self.assertEqual(len(x), sum((col >= \"chicken\") * (col <= \"lion\")) + 1)\n        for e in x:\n            self.assertTrue(\"chicken\" <= str(e[\"name\"]).lower() <= \"lion\")\n\n        f.oper = f.Outside\n        x = filter.Values([f])(d)\n        self.assertEqual(len(x), sum(col < \"chicken\") + sum(col > \"lion\") - 1)\n        self.assertTrue(np.all((x.metas < \"chicken\") + (x.metas > \"lion\")))\n\n        f.oper = f.Contains\n        f.ref = \"iR\"\n        x = filter.Values([f])(d)\n        for e in x:\n            self.assertTrue(\"ir\" in str(e[\"name\"]).lower())\n        self.assertEqual(len(x), len([e for e in col if \"ir\" in e]) + 1)\n\n        f.oper = f.StartsWith\n        f.ref = \"GI\"\n        x = filter.Values([f])(d)\n        for e in x:\n            self.assertTrue(str(e[\"name\"]).lower().startswith(\"gi\"))\n        self.assertEqual(len(x),\n                         len([e for e in col if e.lower().startswith(\"gi\")]))\n\n        f.oper = f.EndsWith\n        f.ref = \"ion\"\n        x = filter.Values([f])(d)\n        for e in x:\n            self.assertTrue(str(e[\"name\"]).endswith(\"ion\"))\n            self.assertTrue(str(e[\"name\"]).endswith(\"ion\"))\n        self.assertEqual(len(x), len([e for e in col if e.endswith(\"ion\")]))\n\n    def test_valueFilter_regex(self):\n        d = data.Table(\"zoo\")\n        f = filter.FilterRegex(d.domain['name'], '^c...$')\n        x = filter.Values([f])(d)\n        self.assertEqual(len(x), 7)\n\n    def test_valueFilter_stringList(self):\n        data = Table(\"zoo\")\n        var = data.domain[\"name\"]\n\n        fs = filter.FilterStringList\n        filters = [\n            (([\"swan\", \"tuna\", \"wasp\"], True), dict(rows=3)),\n            (([\"swan\", \"tuna\", \"wasp\"], False), dict(rows=3)),\n            (([\"WoRm\", \"TOad\", \"vOLe\"], True), dict(rows=0)),\n            (([\"WoRm\", \"TOad\", \"vOLe\"], False), dict(rows=3)),\n        ]\n\n        for args, expected in filters:\n            f = fs(var, *args)\n            filtered_data = filter.Values([f])(data)\n            self.assertEqual(len(filtered_data), expected[\"rows\"],\n                             \"{} returned wrong number of rows\".format(args))\n\n    def test_table_dtypes(self):\n        table = data.Table(\"iris\")\n        metas = np.hstack((table.metas, table.Y.reshape(len(table), 1)))\n        attributes_metas = table.domain.metas + table.domain.class_vars\n        domain_metas = data.Domain(table.domain.attributes,\n                                   table.domain.class_vars,\n                                   attributes_metas)\n        table_metas = data.Table(domain_metas, table.X, table.Y, metas)\n        new_table = data.Table(data.Domain(table_metas.domain.metas,\n                                           table_metas.domain.metas,\n                                           table_metas.domain.metas),\n                               table_metas)\n        self.assertEqual(new_table.X.dtype, np.float64)\n        self.assertEqual(new_table.Y.dtype, np.float64)\n        self.assertEqual(new_table.metas.dtype, np.float64)\n\n    def test_attributes(self):\n        table = data.Table(\"iris\")\n        table.attributes = {1: \"test\"}\n        table2 = table[:4]\n        self.assertEqual(table2.attributes[1], \"test\")\n        table2.attributes[1] = \"modified\"\n        self.assertEqual(table.attributes[1], \"modified\")\n\n    # TODO Test conjunctions and disjunctions of conditions\n\n    def test_is_sparse(self):\n        table = data.Table(\"iris\")\n        self.assertFalse(table.is_sparse())\n\n        table.X = sp.csr_matrix(table.X)\n        self.assertTrue(table.is_sparse())\n\n    def test_repr_sparse_with_one_row(self):\n        table = data.Table(\"iris\")[:1]\n        table.X = sp.csr_matrix(table.X)\n        repr(table)     # make sure repr does not crash\n\n    def test_inf(self):\n        a = np.array([[2,   0,      0,      0],\n                      [0,   np.nan, np.nan, 1],\n                      [0,   0,      np.inf, 0]])\n        with self.assertWarns(Warning):\n            tab = data.Table(a)\n        self.assertEqual(tab.get_nan_frequency_attribute(), 3/12)",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 1280,
                            "end_lineno": 1286,
                            "parent": {
                                "file_name": "Orange/tests/test_table.py",
                                "type": "class",
                                "name": "TableTestCase",
                                "content": "class TableTestCase(unittest.TestCase):\n    def setUp(self):\n        Variable._clear_all_caches()\n        data.table.dataset_dirs.append(test_dirname())\n\n    def tearDown(self):\n        data.table.dataset_dirs.remove(test_dirname())\n\n    def test_indexing_class(self):\n        d = data.Table(\"test1\")\n        self.assertEqual([e.get_class() for e in d], [\"t\", \"t\", \"f\"])\n        cind = len(d.domain) - 1\n        self.assertEqual([e[cind] for e in d], [\"t\", \"t\", \"f\"])\n        self.assertEqual([e[\"d\"] for e in d], [\"t\", \"t\", \"f\"])\n        cvar = d.domain.class_var\n        self.assertEqual([e[cvar] for e in d], [\"t\", \"t\", \"f\"])\n\n    def test_filename(self):\n        dir = data.table.get_sample_datasets_dir()\n        d = data.Table(\"iris\")\n        self.assertEqual(d.__file__, os.path.join(dir, \"iris.tab\"))\n\n        d = data.Table(\"test2.tab\")\n        self.assertTrue(d.__file__.endswith(\"test2.tab\"))  # platform dependent\n\n    def test_indexing(self):\n        import warnings\n\n        with warnings.catch_warnings():\n            warnings.simplefilter(\"ignore\")\n            d = data.Table(\"test2\")\n\n            # regular, discrete\n            varc = d.domain[\"c\"]\n            self.assertEqual(d[0, 1], \"0\")\n            self.assertEqual(d[0, varc], \"0\")\n            self.assertEqual(d[0, \"c\"], \"0\")\n            self.assertEqual(d[0][1], \"0\")\n            self.assertEqual(d[0][varc], \"0\")\n            self.assertEqual(d[0][\"c\"], \"0\")\n            self.assertEqual(d[np.int_(0), np.int_(1)], \"0\")\n            self.assertEqual(d[np.int_(0)][np.int_(1)], \"0\")\n\n            # regular, continuous\n            varb = d.domain[\"b\"]\n            self.assertEqual(d[0, 0], 0)\n            self.assertEqual(d[0, varb], 0)\n            self.assertEqual(d[0, \"b\"], 0)\n            self.assertEqual(d[0][0], 0)\n            self.assertEqual(d[0][varb], 0)\n            self.assertEqual(d[0][\"b\"], 0)\n            self.assertEqual(d[np.int_(0), np.int_(0)], 0)\n            self.assertEqual(d[np.int_(0)][np.int_(0)], 0)\n\n            # negative\n            varb = d.domain[\"b\"]\n            self.assertEqual(d[-2, 0], 3.333)\n            self.assertEqual(d[-2, varb], 3.333)\n            self.assertEqual(d[-2, \"b\"], 3.333)\n            self.assertEqual(d[-2][0], 3.333)\n            self.assertEqual(d[-2][varb], 3.333)\n            self.assertEqual(d[-2][\"b\"], 3.333)\n            self.assertEqual(d[np.int_(-2), np.int_(0)], 3.333)\n            self.assertEqual(d[np.int_(-2)][np.int_(0)], 3.333)\n\n            # meta, discrete\n            vara = d.domain[\"a\"]\n            metaa = d.domain.index(\"a\")\n            self.assertEqual(d[0, metaa], \"A\")\n            self.assertEqual(d[0, vara], \"A\")\n            self.assertEqual(d[0, \"a\"], \"A\")\n            self.assertEqual(d[0][metaa], \"A\")\n            self.assertEqual(d[0][vara], \"A\")\n            self.assertEqual(d[0][\"a\"], \"A\")\n            self.assertEqual(d[np.int_(0), np.int_(metaa)], \"A\")\n            self.assertEqual(d[np.int_(0)][np.int_(metaa)], \"A\")\n\n            # meta, string\n            vare = d.domain[\"e\"]\n            metae = d.domain.index(\"e\")\n            self.assertEqual(d[0, metae], \"i\")\n            self.assertEqual(d[0, vare], \"i\")\n            self.assertEqual(d[0, \"e\"], \"i\")\n            self.assertEqual(d[0][metae], \"i\")\n            self.assertEqual(d[0][vare], \"i\")\n            self.assertEqual(d[0][\"e\"], \"i\")\n            self.assertEqual(d[np.int_(0), np.int_(metae)], \"i\")\n            self.assertEqual(d[np.int_(0)][np.int_(metae)], \"i\")\n\n    def test_indexing_example(self):\n        import warnings\n\n        with warnings.catch_warnings():\n            warnings.simplefilter(\"ignore\")\n            d = data.Table(\"test2\")\n            e = d[0]\n\n            # regular, discrete\n            varc = d.domain[\"c\"]\n            self.assertEqual(e[1], \"0\")\n            self.assertEqual(e[varc], \"0\")\n            self.assertEqual(e[\"c\"], \"0\")\n            self.assertEqual(e[np.int_(1)], \"0\")\n\n            # regular, continuous\n            varb = d.domain[\"b\"]\n            self.assertEqual(e[0], 0)\n            self.assertEqual(e[varb], 0)\n            self.assertEqual(e[\"b\"], 0)\n            self.assertEqual(e[np.int_(0)], 0)\n\n            # meta, discrete\n            vara = d.domain[\"a\"]\n            metaa = d.domain.index(\"a\")\n            self.assertEqual(e[metaa], \"A\")\n            self.assertEqual(e[vara], \"A\")\n            self.assertEqual(e[\"a\"], \"A\")\n            self.assertEqual(e[np.int_(metaa)], \"A\")\n\n            # meta, string\n            vare = d.domain[\"e\"]\n            metae = d.domain.index(\"e\")\n            self.assertEqual(e[metae], \"i\")\n            self.assertEqual(e[vare], \"i\")\n            self.assertEqual(e[\"e\"], \"i\")\n            self.assertEqual(e[np.int_(metae)], \"i\")\n\n    def test_indexing_assign_value(self):\n        import warnings\n\n        with warnings.catch_warnings():\n            warnings.simplefilter(\"ignore\")\n            d = data.Table(\"test2\")\n\n            # meta\n            vara = d.domain[\"a\"]\n            metaa = d.domain.index(\"a\")\n\n            self.assertEqual(d[0, \"a\"], \"A\")\n            d[0, \"a\"] = \"B\"\n            self.assertEqual(d[0, \"a\"], \"B\")\n            d[0][\"a\"] = \"A\"\n            self.assertEqual(d[0, \"a\"], \"A\")\n\n            d[0, vara] = \"B\"\n            self.assertEqual(d[0, \"a\"], \"B\")\n            d[0][vara] = \"A\"\n            self.assertEqual(d[0, \"a\"], \"A\")\n\n            d[0, metaa] = \"B\"\n            self.assertEqual(d[0, \"a\"], \"B\")\n            d[0][metaa] = \"A\"\n            self.assertEqual(d[0, \"a\"], \"A\")\n\n            d[0, np.int_(metaa)] = \"B\"\n            self.assertEqual(d[0, \"a\"], \"B\")\n            d[0][np.int_(metaa)] = \"A\"\n            self.assertEqual(d[0, \"a\"], \"A\")\n\n            # regular\n            varb = d.domain[\"b\"]\n\n            self.assertEqual(d[0, \"b\"], 0)\n            d[0, \"b\"] = 42\n            self.assertEqual(d[0, \"b\"], 42)\n            d[0][\"b\"] = 0\n            self.assertEqual(d[0, \"b\"], 0)\n\n            d[0, varb] = 42\n            self.assertEqual(d[0, \"b\"], 42)\n            d[0][varb] = 0\n            self.assertEqual(d[0, \"b\"], 0)\n\n            d[0, 0] = 42\n            self.assertEqual(d[0, \"b\"], 42)\n            d[0][0] = 0\n            self.assertEqual(d[0, \"b\"], 0)\n\n            d[0, np.int_(0)] = 42\n            self.assertEqual(d[0, \"b\"], 42)\n            d[0][np.int_(0)] = 0\n            self.assertEqual(d[0, \"b\"], 0)\n\n    @skip_deprecated_length\n    def test_indexing_del_example(self):\n        import warnings\n\n        with warnings.catch_warnings():\n            warnings.simplefilter(\"ignore\")\n            d = data.Table(\"test2\")\n            initlen = len(d)\n\n            # remove first\n            d[4, \"e\"] = \"4ex\"\n            self.assertEqual(d[4, \"e\"], \"4ex\")\n            del d[0]\n            self.assertEqual(len(d), initlen - 1)\n            self.assertEqual(d[3, \"e\"], \"4ex\")\n\n            # remove middle\n            del d[2]\n            self.assertEqual(len(d), initlen - 2)\n            self.assertEqual(d[2, \"e\"], \"4ex\")\n\n            # remove middle\n            del d[4]\n            self.assertEqual(len(d), initlen - 3)\n            self.assertEqual(d[2, \"e\"], \"4ex\")\n\n            # remove last\n            d[-1, \"e\"] = \"was last\"\n            del d[-1]\n            self.assertEqual(len(d), initlen - 4)\n            self.assertEqual(d[2, \"e\"], \"4ex\")\n            self.assertNotEqual(d[-1, \"e\"], \"was last\")\n\n            # remove one before last\n            d[-1, \"e\"] = \"was last\"\n            del d[-2]\n            self.assertEqual(len(d), initlen - 5)\n            self.assertEqual(d[2, \"e\"], \"4ex\")\n            self.assertEqual(d[-1, \"e\"], \"was last\")\n\n            d[np.int_(2), \"e\"] = \"2ex\"\n            del d[np.int_(2)]\n            self.assertEqual(len(d), initlen - 6)\n            self.assertNotEqual(d[2, \"e\"], \"2ex\")\n\n            with self.assertRaises(IndexError):\n                del d[100]\n            self.assertEqual(len(d), initlen - 6)\n\n            with self.assertRaises(IndexError):\n                del d[-100]\n            self.assertEqual(len(d), initlen - 6)\n\n    def test_indexing_assign_example(self):\n        def almost_equal_list(s, t):\n            for e, f in zip(s, t):\n                self.assertAlmostEqual(e, f)\n\n        import warnings\n\n        with warnings.catch_warnings():\n            warnings.simplefilter(\"ignore\")\n            d = data.Table(\"test2\")\n\n            vara = d.domain[\"a\"]\n            metaa = d.domain.index(vara)\n\n            self.assertFalse(isnan(d[0, \"a\"]))\n            d[0] = [\"3.14\", \"1\", \"f\"]\n            almost_equal_list(d[0].values(), [3.14, \"1\", \"f\"])\n            self.assertTrue(isnan(d[0, \"a\"]))\n            d[0] = [3.15, 1, \"t\"]\n            almost_equal_list(d[0].values(), [3.15, \"0\", \"t\"])\n            d[np.int_(0)] = [3.15, 2, \"f\"]\n            almost_equal_list(d[0].values(), [3.15, 2, \"f\"])\n\n            with self.assertRaises(ValueError):\n                d[0] = [\"3.14\", \"1\"]\n\n            with self.assertRaises(ValueError):\n                d[np.int_(0)] = [\"3.14\", \"1\"]\n\n            ex = data.Instance(d.domain, [\"3.16\", \"1\", \"f\"])\n            d[0] = ex\n            almost_equal_list(d[0].values(), [3.16, \"1\", \"f\"])\n\n            ex = data.Instance(d.domain, [\"3.16\", 2, \"t\"])\n            d[np.int_(0)] = ex\n            almost_equal_list(d[0].values(), [3.16, 2, \"t\"])\n\n            ex = data.Instance(d.domain, [\"3.16\", \"1\", \"f\"])\n            ex[\"e\"] = \"mmmapp\"\n            d[0] = ex\n            almost_equal_list(d[0].values(), [3.16, \"1\", \"f\"])\n            self.assertEqual(d[0, \"e\"], \"mmmapp\")\n\n    def test_slice(self):\n        import warnings\n\n        with warnings.catch_warnings():\n            warnings.simplefilter(\"ignore\")\n            d = data.Table(\"test2\")\n            x = d[:3]\n            self.assertEqual(len(x), 3)\n            self.assertEqual([e[0] for e in x], [0, 1.1, 2.22])\n\n            x = d[2:5]\n            self.assertEqual(len(x), 3)\n            self.assertEqual([e[0] for e in x], [2.22, 2.23, 2.24])\n\n            x = d[4:1:-1]\n            self.assertEqual(len(x), 3)\n            self.assertEqual([e[0] for e in x], [2.24, 2.23, 2.22])\n\n            x = d[-3:]\n            self.assertEqual(len(x), 3)\n            self.assertEqual([e[0] for e in x], [2.26, 3.333, Unknown])\n\n    def test_assign_slice_value(self):\n        import warnings\n\n        with warnings.catch_warnings():\n            warnings.simplefilter(\"ignore\")\n            d = data.Table(\"test2\")\n            d[2:5, 0] = 42\n            self.assertEqual([e[0] for e in d],\n                             [0, 1.1, 42, 42, 42, 2.25, 2.26, 3.333, Unknown])\n            d[:3, \"b\"] = 43\n            self.assertEqual([e[0] for e in d],\n                             [43, 43, 43, 42, 42, 2.25, 2.26, 3.333, None])\n            d[-2:, d.domain[0]] = 44\n            self.assertEqual([e[0] for e in d],\n                             [43, 43, 43, 42, 42, 2.25, 2.26, 44, 44])\n\n            d[2:5, \"a\"] = \"A\"\n            self.assertEqual([e[\"a\"] for e in d], list(\"ABAAACCDE\"))\n\n    @skip_deprecated_length\n    def test_del_slice_example(self):\n        import warnings\n\n        with warnings.catch_warnings():\n            warnings.simplefilter(\"ignore\")\n            d = data.Table(\"test2\")\n\n            vals = [e[0] for e in d]\n\n            del d[2:2]\n            self.assertEqual([e[0] for e in d], vals)\n\n            del d[2:5]\n            del vals[2:5]\n            self.assertEqual([e[0] for e in d], vals)\n\n            del d[:]\n            self.assertEqual(len(d), 0)\n\n    @skip_deprecated_length\n    def test_del_slice_ids(self):\n        # __del__ updates `ids` member\n        d = data.Table(\"test2\")\n        ids = d.ids.copy()\n        del d[2:4]\n        np.testing.assert_array_equal(d.ids, np.delete(ids, slice(2, 4)))\n\n    @skip_deprecated_length\n    def test_set_slice_example(self):\n        import warnings\n\n        with warnings.catch_warnings():\n            warnings.simplefilter(\"ignore\")\n            d = data.Table(\"test2\")\n            d[5, 0] = 42\n            d[:3] = d[5]\n            self.assertEqual(d[1, 0], 42)\n\n            d[5:2:-1] = [3, None, None]\n            self.assertEqual([e[0] for e in d],\n                             [42, 42, 42, 3, 3, 3, 2.26, 3.333, None])\n            self.assertTrue(isnan(d[3, 2]))\n\n            d[2:5] = 42\n            self.assertTrue(np.all(d.X[2:5] == 42))\n            self.assertEqual(d.Y[2], 0)\n\n    def test_multiple_indices(self):\n        import warnings\n\n        with warnings.catch_warnings():\n            warnings.simplefilter(\"ignore\")\n            d = data.Table(\"test2\")\n\n            with self.assertRaises(IndexError):\n                x = d[2, 5, 1]\n\n            with self.assertRaises(IndexError):\n                x = d[(2, 5, 1)]\n\n            x = d[[2, 5, 1]]\n            self.assertEqual([e[0] for e in x], [2.22, 2.25, 1.1])\n\n    def test_assign_multiple_indices_value(self):\n        import warnings\n\n        with warnings.catch_warnings():\n            warnings.simplefilter(\"ignore\")\n            d = data.Table(\"test2\")\n\n            d[1:4, \"b\"] = 42\n            self.assertEqual([e[0] for e in d],\n                             [0, 42, 42, 42, 2.24, 2.25, 2.26, 3.333, None])\n\n            d[range(5, 2, -1), \"b\"] = None\n            self.assertEqual([e[d.domain[0]] for e in d],\n                             [0, 42, 42, None, \"?\", \"\", 2.26, 3.333, None])\n\n    @skip_deprecated_length\n    def test_del_multiple_indices_example(self):\n        import warnings\n\n        with warnings.catch_warnings():\n            warnings.simplefilter(\"ignore\")\n            d = data.Table(\"test2\")\n\n            vals = [e[0] for e in d]\n\n            del d[[1, 5, 2]]\n            del vals[5]\n            del vals[2]\n            del vals[1]\n            self.assertEqual([e[0] for e in d], vals)\n\n            del d[range(1, 3)]\n            del vals[1:3]\n            self.assertEqual([e[0] for e in d], vals)\n\n    def test_set_multiple_indices_example(self):\n        import warnings\n\n        with warnings.catch_warnings():\n            warnings.simplefilter(\"ignore\")\n            d = data.Table(\"test2\")\n\n            vals = [e[0] for e in d]\n            d[[1, 2, 5]] = [42, None, None]\n            vals[1] = vals[2] = vals[5] = 42\n            self.assertEqual([e[0] for e in d], vals)\n\n    @skip_deprecated_length\n    def test_views(self):\n        d = data.Table(\"zoo\")\n        crc = d.checksum(True)\n        x = d[:20]\n        self.assertEqual(crc, d.checksum(True))\n        del x[13]\n        self.assertEqual(crc, d.checksum(True))\n        del x[4:9]\n        self.assertEqual(crc, d.checksum(True))\n\n    def test_bool(self):\n        d = data.Table(\"iris\")\n        self.assertTrue(d)\n\n        d = data.Table(\"test3\")\n        self.assertFalse(d)\n\n        d = data.Table(\"iris\")\n        self.assertTrue(d)\n\n    def test_checksum(self):\n        d = data.Table(\"zoo\")\n        d[42, 3] = 0\n        crc1 = d.checksum(False)\n        d[42, 3] = 1\n        crc2 = d.checksum(False)\n        self.assertNotEqual(crc1, crc2)\n        d[42, 3] = 0\n        crc3 = d.checksum(False)\n        self.assertEqual(crc1, crc3)\n        _ = d[42, \"name\"]\n        d[42, \"name\"] = \"non-animal\"\n        crc4 = d.checksum(False)\n        self.assertEqual(crc1, crc4)\n        crc4 = d.checksum(True)\n        crc5 = d.checksum(1)\n        crc6 = d.checksum(False)\n        self.assertNotEqual(crc1, crc4)\n        self.assertNotEqual(crc1, crc5)\n        self.assertEqual(crc1, crc6)\n\n    def test_total_weight(self):\n        d = data.Table(\"zoo\")\n        self.assertEqual(d.total_weight(), len(d))\n\n        d.set_weights(0)\n        d[0].weight = 0.1\n        d[10].weight = 0.2\n        d[-1].weight = 0.3\n        self.assertAlmostEqual(d.total_weight(), 0.6)\n\n    def test_has_missing(self):\n        d = data.Table(\"zoo\")\n        self.assertFalse(d.has_missing())\n        self.assertFalse(d.has_missing_class())\n\n        d[10, 3] = \"?\"\n        self.assertTrue(d.has_missing())\n        self.assertFalse(d.has_missing_class())\n\n        d[10].set_class(\"?\")\n        self.assertTrue(d.has_missing())\n        self.assertTrue(d.has_missing_class())\n\n        d = data.Table(\"test3\")\n        self.assertFalse(d.has_missing())\n        self.assertFalse(d.has_missing_class())\n\n    def test_shuffle(self):\n        d = data.Table(\"zoo\")\n        crc = d.checksum()\n        names = set(str(x[\"name\"]) for x in d)\n\n        d.shuffle()\n        self.assertNotEqual(crc, d.checksum())\n        self.assertSetEqual(names, set(str(x[\"name\"]) for x in d))\n        crc2 = d.checksum()\n\n        x = d[2:10]\n        crcx = x.checksum()\n        d.shuffle()\n        self.assertNotEqual(crc2, d.checksum())\n        self.assertEqual(crcx, x.checksum())\n\n        crc2 = d.checksum()\n        x.shuffle()\n        self.assertNotEqual(crcx, x.checksum())\n        self.assertEqual(crc2, d.checksum())\n\n    @staticmethod\n    def not_less_ex(ex1, ex2):\n        for v1, v2 in zip(ex1, ex2):\n            if v1 != v2:\n                return v1 < v2\n        return True\n\n    @staticmethod\n    def sorted(d):\n        for i in range(1, len(d)):\n            if not TableTestCase.not_less_ex(d[i - 1], d[i]):\n                return False\n        return True\n\n    @staticmethod\n    def not_less_ex_ord(ex1, ex2, ord):\n        for a in ord:\n            if ex1[a] != ex2[a]:\n                return ex1[a] < ex2[a]\n        return True\n\n    @staticmethod\n    def sorted_ord(d, ord):\n        for i in range(1, len(d)):\n            if not TableTestCase.not_less_ex_ord(d[i - 1], d[i], ord):\n                return False\n        return True\n\n    @skip_deprecated_length\n    def test_append(self):\n        d = data.Table(\"test3\")\n        d.append([None] * 3)\n        self.assertEqual(1, len(d))\n        self.assertTrue(all(isnan(i) for i in d[0]))\n\n        d.append([42, \"0\", None])\n        self.assertEqual(2, len(d))\n        self.assertEqual(d[1], [42, \"0\", None])\n\n        assert_array_nanequal(\n            d.metas,\n            np.array([[v.Unknown for v in d.domain.metas]] * 2,\n                     dtype=object))\n\n    @skip_deprecated_length\n    def test_append2(self):\n        d = data.Table(\"iris\")\n        d.shuffle()\n        l1 = len(d)\n        d.append([1, 2, 3, 4, 0])\n        self.assertEqual(len(d), l1 + 1)\n        self.assertEqual(d[-1], [1, 2, 3, 4, 0])\n\n        x = data.Instance(d[10])\n        d.append(x)\n        self.assertEqual(d[-1], d[10])\n\n        x = d[:50]\n        x.ensure_copy()\n        x.append(d[50])\n        self.assertEqual(x[50], d[50])\n\n    @skip_deprecated_length\n    def test_extend(self):\n        d = data.Table(\"iris\")\n        d.shuffle()\n\n        x = d[:5]\n        x.ensure_copy()\n        d.extend(x)\n        for i in range(5):\n            self.assertEqual(d[i], d[-5 + i])\n\n        y = d[:2, 1]\n        x.ensure_copy()\n        x.extend(y)\n        np.testing.assert_almost_equal(x[-2:, 1].X, y.X)\n        self.assertEqual(np.isnan(x).sum(), 8)\n\n    @skip_deprecated_length\n    def test_extend2(self):\n        d = data.Table(\"test3\")\n        d.extend([[None] * 3,\n                  [None] * 3])\n        assert_array_nanequal(\n            d.metas,\n            np.array([[v.Unknown for v in d.domain.metas]] * 2,\n                     dtype=object))\n\n    def test_copy(self):\n        t = data.Table(np.zeros((5, 3)), np.arange(5), np.zeros((5, 3)))\n\n        copy = t.copy()\n        self.assertTrue(np.all(t.X == copy.X))\n        self.assertTrue(np.all(t.Y == copy.Y))\n        self.assertTrue(np.all(t.metas == copy.metas))\n        copy[0] = [1, 1, 1, 1, 1, 1, 1, 1]\n        self.assertFalse(np.all(t.X == copy.X))\n        self.assertFalse(np.all(t.Y == copy.Y))\n        self.assertFalse(np.all(t.metas == copy.metas))\n\n    def test_copy_sparse(self):\n        t = data.Table('iris').to_sparse()\n        copy = t.copy()\n\n        self.assertEqual((t.X != copy.X).nnz, 0)      # sparse matrices match by content\n        np.testing.assert_equal(t.Y, copy.Y)\n        np.testing.assert_equal(t.metas, copy.metas)\n\n        self.assertNotEqual(id(t.X), id(copy.X))\n        self.assertNotEqual(id(t._Y), id(copy._Y))\n        self.assertNotEqual(id(t.metas), id(copy.metas))\n\n    def test_concatenate(self):\n        d1 = data.Domain([data.ContinuousVariable('a1')])\n        t1 = data.Table.from_numpy(d1, [[1],\n                                        [2]])\n        d2 = data.Domain([data.ContinuousVariable('a2')],\n                         metas=[data.StringVariable('s')])\n        t2 = data.Table.from_numpy(d2, [[3],\n                                        [4]], metas=[['foo'],\n                                                     ['fuu']])\n        self.assertRaises(ValueError,\n                          lambda: data.Table.concatenate((t1, t2), axis=5))\n\n        t3 = data.Table.concatenate((t1, t2))\n        self.assertEqual(t3.domain.attributes,\n                         t1.domain.attributes + t2.domain.attributes)\n        self.assertEqual(len(t3.domain.metas), 1)\n        self.assertEqual(t3.X.shape, (2, 2))\n        self.assertRaises(ValueError, lambda: data.Table.concatenate((t3, t1)))\n        self.assertRaises(ValueError, lambda: data.Table.concatenate((t3, t1), axis=0))\n\n        t4 = data.Table.concatenate((t3, t3), axis=0)\n        np.testing.assert_equal(t4.X, [[1, 3],\n                                       [2, 4],\n                                       [1, 3],\n                                       [2, 4]])\n\n    def test_sparse_concatenate_rows(self):\n        iris = Table(\"iris\")\n        iris.X = sp.csc_matrix(iris.X)\n        new = Table.concatenate([iris, iris], axis=0)\n        self.assertEqual(len(new), 300)\n        self.assertTrue(sp.issparse(new.X), \"Concatenated X is not sparse.\")\n        self.assertFalse(sp.issparse(new.Y), \"Concatenated Y is not dense.\")\n        self.assertFalse(sp.issparse(new.metas), \"Concatenated metas is not dense.\")\n        self.assertEqual(len(new.ids), 300)\n\n    @skip_deprecated_length\n    def test_convert_through_append(self):\n        d = data.Table(\"iris\")\n        dom2 = data.Domain([d.domain[0], d.domain[2], d.domain[4]])\n        d2 = data.Table(dom2)\n        dom3 = data.Domain([d.domain[1], d.domain[2]], None)\n        d3 = data.Table(dom3)\n        for e in d[:5]:\n            d2.append(e)\n            d3.append(e)\n        for e, e2, e3 in zip(d, d2, d3):\n            self.assertEqual(e[0], e2[0])\n            self.assertEqual(e[1], e3[0])\n\n    def test_pickle(self):\n        import pickle\n\n        d = data.Table(\"zoo\")\n        s = pickle.dumps(d)\n        d2 = pickle.loads(s)\n        self.assertEqual(d[0], d2[0])\n\n        self.assertEqual(d.checksum(include_metas=False),\n                         d2.checksum(include_metas=False))\n\n        d = data.Table(\"iris\")\n        s = pickle.dumps(d)\n        d2 = pickle.loads(s)\n        self.assertEqual(d[0], d2[0])\n        self.assertEqual(d.checksum(include_metas=False),\n                         d2.checksum(include_metas=False))\n\n    def test_translate_through_slice(self):\n        d = data.Table(\"iris\")\n        dom = data.Domain([\"petal length\", \"sepal length\", \"iris\"],\n                          source=d.domain)\n        d_ref = d[:10, dom.variables]\n        self.assertEqual(d_ref.domain.class_var, d.domain.class_var)\n        self.assertEqual(d_ref[0, \"petal length\"], d[0, \"petal length\"])\n        self.assertEqual(d_ref[0, \"sepal length\"], d[0, \"sepal length\"])\n        self.assertEqual(d_ref.X.shape, (10, 2))\n        self.assertEqual(d_ref.Y.shape, (10,))\n\n    def test_saveTab(self):\n        d = data.Table(\"iris\")[:3]\n        d.save(\"test-save.tab\")\n        try:\n            d2 = data.Table(\"test-save.tab\")\n            for e1, e2 in zip(d, d2):\n                self.assertEqual(e1, e2)\n        finally:\n            os.remove(\"test-save.tab\")\n            os.remove(\"test-save.tab.metadata\")\n\n        dom = data.Domain([data.ContinuousVariable(\"a\")])\n        d = data.Table(dom, [[i] for i in range(3)])\n        d.save(\"test-save.tab\")\n        try:\n            d2 = data.Table(\"test-save.tab\")\n            self.assertEqual(len(d.domain.attributes), 1)\n            self.assertEqual(d.domain.class_var, None)\n            for i in range(3):\n                self.assertEqual(d2[i], [i])\n        finally:\n            os.remove(\"test-save.tab\")\n\n        dom = data.Domain([data.ContinuousVariable(\"a\")], None)\n        d = data.Table(dom, [[i] for i in range(3)])\n        d.save(\"test-save.tab\")\n        try:\n            d2 = data.Table(\"test-save.tab\")\n            self.assertEqual(len(d.domain.attributes), 1)\n            for i in range(3):\n                self.assertEqual(d2[i], [i])\n        finally:\n            os.remove(\"test-save.tab\")\n\n        d = data.Table(\"zoo\")\n        d.save(\"test-zoo.tab\")\n        dd = data.Table(\"test-zoo\")\n        try:\n            self.assertTupleEqual(d.domain.metas, dd.domain.metas,\n                                  msg=\"Meta attributes don't match.\")\n            self.assertTupleEqual(d.domain.variables, dd.domain.variables,\n                                  msg=\"Attributes don't match.\")\n\n            np.testing.assert_almost_equal(d.W, dd.W,\n                                           err_msg=\"Weights don't match.\")\n            for i in range(10):\n                for j in d.domain.variables:\n                    self.assertEqual(d[i][j], dd[i][j])\n        finally:\n            os.remove(\"test-zoo.tab\")\n\n        d = data.Table(\"zoo\")\n        d.set_weights(range(len(d)))\n        d.save(\"test-zoo-weights.tab\")\n        dd = data.Table(\"test-zoo-weights\")\n        try:\n            self.assertTupleEqual(d.domain.metas, dd.domain.metas,\n                                  msg=\"Meta attributes don't match.\")\n            self.assertTupleEqual(d.domain.variables, dd.domain.variables,\n                                  msg=\"Attributes don't match.\")\n\n            np.testing.assert_almost_equal(d.W, dd.W,\n                                           err_msg=\"Weights don't match.\")\n            for i in range(10):\n                for j in d.domain.variables:\n                    self.assertEqual(d[i][j], dd[i][j])\n        finally:\n            os.remove(\"test-zoo-weights.tab\")\n\n    def test_save_pickle(self):\n        table = data.Table(\"iris\")\n        try:\n            table.save(\"iris.pickle\")\n            table2 = data.Table.from_file(\"iris.pickle\")\n            np.testing.assert_almost_equal(table.X, table2.X)\n            np.testing.assert_almost_equal(table.Y, table2.Y)\n            self.assertEqual(table.domain[0], table2.domain[0])\n        finally:\n            os.remove(\"iris.pickle\")\n\n    def test_from_numpy(self):\n        a = np.arange(20, dtype=\"d\").reshape((4, 5))\n        a[:, -1] = [0, 0, 0, 1]\n        dom = data.Domain([data.ContinuousVariable(x) for x in \"abcd\"],\n                          data.DiscreteVariable(\"e\", values=[\"no\", \"yes\"]))\n        table = data.Table(dom, a)\n        for i in range(4):\n            self.assertEqual(table[i].get_class(), \"no\" if i < 3 else \"yes\")\n            for j in range(5):\n                self.assertEqual(a[i, j], table[i, j])\n                table[i, j] = random.random()\n                self.assertEqual(a[i, j], table[i, j])\n\n        with self.assertRaises(IndexError):\n            table[0, -5] = 5\n\n    def test_filter_is_defined(self):\n        d = data.Table(\"iris\")\n        d[1, 4] = Unknown\n        self.assertTrue(isnan(d[1, 4]))\n        d[140, 0] = Unknown\n        e = filter.IsDefined()(d)\n        self.assertEqual(len(e), len(d) - 2)\n        self.assertEqual(e[0], d[0])\n        self.assertEqual(e[1], d[2])\n        self.assertEqual(e[147], d[149])\n        self.assertTrue(d.has_missing())\n        self.assertFalse(e.has_missing())\n\n    def test_filter_has_class(self):\n        d = data.Table(\"iris\")\n        d[1, 4] = Unknown\n        self.assertTrue(isnan(d[1, 4]))\n        d[140, 0] = Unknown\n        e = filter.HasClass()(d)\n        self.assertEqual(len(e), len(d) - 1)\n        self.assertEqual(e[0], d[0])\n        self.assertEqual(e[1], d[2])\n        self.assertEqual(e[148], d[149])\n        self.assertTrue(d.has_missing())\n        self.assertTrue(e.has_missing())\n        self.assertFalse(e.has_missing_class())\n\n    def test_filter_random(self):\n        d = data.Table(\"iris\")\n        e = filter.Random(50)(d)\n        self.assertEqual(len(e), 50)\n        e = filter.Random(50, negate=True)(d)\n        self.assertEqual(len(e), 100)\n        for i in range(5):\n            e = filter.Random(0.2)(d)\n            self.assertEqual(len(e), 30)\n            bc = np.bincount(np.array(e.Y[:], dtype=int))\n            if min(bc) > 7:\n                break\n        else:\n            self.fail(\"Filter returns too uneven distributions\")\n\n    def test_filter_values_nested(self):\n        d = data.Table(\"iris\")\n        f1 = filter.FilterContinuous(d.columns.sepal_length,\n                                     filter.FilterContinuous.Between,\n                                     min=4.5, max=5.0)\n        f2 = filter.FilterContinuous(d.columns.sepal_width,\n                                     filter.FilterContinuous.Between,\n                                     min=3.1, max=3.4)\n        f3 = filter.FilterDiscrete(d.columns.iris, [0, 1])\n        f = filter.Values([filter.Values([f1, f2], conjunction=False), f3])\n        self.assertEqual(41, len(f(d)))\n\n    def test_filter_string_works_for_numeric_columns(self):\n        var = StringVariable(\"s\")\n        data = Table(Domain([], metas=[var]), [[x] for x in range(21)])\n        # 1, 2, 3, ..., 18, 19, 20\n\n        fs = filter.FilterString\n        filters = [\n            ((fs.Greater, \"5\"), dict(rows=4)),\n            # 6, 7, 8, 9\n            ((fs.Between, \"15\", \"2\"), dict(rows=6)),\n            # 15, 16, 17, 18, 19, 2\n            ((fs.Contains, \"2\"), dict(rows=3)),\n            # 2, 12, 20\n        ]\n\n        for args, expected in filters:\n            f = fs(var, *args)\n            filtered_data = filter.Values([f])(data)\n            self.assertEqual(len(filtered_data), expected[\"rows\"],\n                             \"{} returned wrong number of rows\".format(args))\n\n    def test_filter_value_continuous(self):\n        d = data.Table(\"iris\")\n        col = d.X[:, 2]\n\n        v = d.columns\n        f = filter.FilterContinuous(v.petal_length,\n                                    filter.FilterContinuous.Between,\n                                    min=4.5, max=5.1)\n\n        x = filter.Values([f])(d)\n        self.assertTrue(np.all(x.X[:, 2] >= 4.5))\n        self.assertTrue(np.all(x.X[:, 2] <= 5.1))\n        self.assertEqual(sum((col >= 4.5) * (col <= 5.1)), len(x))\n\n        f.ref = 5.1\n        f.oper = filter.FilterContinuous.Equal\n        x = filter.Values([f])(d)\n        self.assertTrue(np.all(x.X[:, 2] == 5.1))\n        self.assertEqual(sum(col == 5.1), len(x))\n\n        f.oper = filter.FilterContinuous.NotEqual\n        x = filter.Values([f])(d)\n        self.assertTrue(np.all(x.X[:, 2] != 5.1))\n        self.assertEqual(sum(col != 5.1), len(x))\n\n        f.oper = filter.FilterContinuous.Less\n        x = filter.Values([f])(d)\n        self.assertTrue(np.all(x.X[:, 2] < 5.1))\n        self.assertEqual(sum(col < 5.1), len(x))\n\n        f.oper = filter.FilterContinuous.LessEqual\n        x = filter.Values([f])(d)\n        self.assertTrue(np.all(x.X[:, 2] <= 5.1))\n        self.assertEqual(sum(col <= 5.1), len(x))\n\n        f.oper = filter.FilterContinuous.Greater\n        x = filter.Values([f])(d)\n        self.assertTrue(np.all(x.X[:, 2] > 5.1))\n        self.assertEqual(sum(col > 5.1), len(x))\n\n        f.oper = filter.FilterContinuous.GreaterEqual\n        x = filter.Values([f])(d)\n        self.assertTrue(np.all(x.X[:, 2] >= 5.1))\n        self.assertEqual(sum(col >= 5.1), len(x))\n\n        f.oper = filter.FilterContinuous.Outside\n        f.ref, f.max = 4.5, 5.1\n        x = filter.Values([f])(d)\n        for e in x:\n            self.assertTrue(e[2] < 4.5 or e[2] > 5.1)\n        self.assertEqual(sum((col < 4.5) + (col > 5.1)), len(x))\n\n        f.oper = filter.FilterContinuous.IsDefined\n        f.ref = f.max = None\n        x = filter.Values([f])(d)\n        self.assertEqual(len(x), len(d))\n\n        d[:30, v.petal_length] = Unknown\n        x = filter.Values([f])(d)\n        self.assertEqual(len(x), len(d) - 30)\n\n    def test_filter_value_continuous_args(self):\n        d = data.Table(\"iris\")\n        col = d.X[:, 2]\n        v = d.columns\n\n        f = filter.FilterContinuous(v.petal_length,\n                                    filter.FilterContinuous.Equal, ref=5.1)\n        x = filter.Values([f])(d)\n        self.assertTrue(np.all(x.X[:, 2] == 5.1))\n        self.assertEqual(sum(col == 5.1), len(x))\n\n        f = filter.FilterContinuous(2,\n                                    filter.FilterContinuous.Equal, ref=5.1)\n        self.assertTrue(np.all(x.X[:, 2] == 5.1))\n        self.assertEqual(sum(col == 5.1), len(x))\n\n        f = filter.FilterContinuous(\"petal length\",\n                                    filter.FilterContinuous.Equal, ref=5.1)\n        self.assertTrue(np.all(x.X[:, 2] == 5.1))\n        self.assertEqual(sum(col == 5.1), len(x))\n\n        f = filter.FilterContinuous(\"sepal length\",\n                                    filter.FilterContinuous.Equal, ref=5.1)\n        f.column = 2\n        self.assertTrue(np.all(x.X[:, 2] == 5.1))\n        self.assertEqual(sum(col == 5.1), len(x))\n\n        f = filter.FilterContinuous(\"sepal length\",\n                                    filter.FilterContinuous.Equal, ref=5.1)\n        f.column = v.petal_length\n        self.assertTrue(np.all(x.X[:, 2] == 5.1))\n        self.assertEqual(sum(col == 5.1), len(x))\n\n        f = filter.FilterContinuous(v.petal_length,\n                                    filter.FilterContinuous.Equal, ref=18)\n        f.ref = 5.1\n        x = filter.Values([f])(d)\n        self.assertTrue(np.all(x.X[:, 2] == 5.1))\n        self.assertEqual(sum(col == 5.1), len(x))\n\n        f = filter.FilterContinuous(v.petal_length,\n                                    filter.FilterContinuous.Equal, ref=18)\n        f.ref = 5.1\n        x = filter.Values([f])(d)\n        self.assertTrue(np.all(x.X[:, 2] == 5.1))\n        self.assertEqual(sum(col == 5.1), len(x))\n\n    def test_valueFilter_discrete(self):\n        d = data.Table(\"zoo\")\n\n        f = filter.FilterDiscrete(d.domain.class_var, values=[2, 3, 4])\n        for e in filter.Values([f])(d):\n            self.assertTrue(e.get_class() in [2, 3, 4])\n\n        f.values = [\"mammal\"]\n        for e in filter.Values([f])(d):\n            self.assertEqual(e.get_class(), \"mammal\")\n\n        f = filter.FilterDiscrete(d.domain.class_var, values=[2, \"mammal\"])\n        for e in filter.Values([f])(d):\n            self.assertTrue(e.get_class() in [2, \"mammal\"])\n\n        f = filter.FilterDiscrete(d.domain.class_var, values=[2, \"martian\"])\n        self.assertRaises(ValueError, d._filter_values, f)\n\n        f = filter.FilterDiscrete(d.domain.class_var, values=[2, data.Table])\n        self.assertRaises(TypeError, d._filter_values, f)\n\n        v = d.columns\n        f = filter.FilterDiscrete(v.hair, values=None)\n        self.assertEqual(len(filter.Values([f])(d)), len(d))\n\n        d[:5, v.hair] = Unknown\n        self.assertEqual(len(filter.Values([f])(d)), len(d) - 5)\n\n    def test_valueFilter_string_is_defined(self):\n        d = data.Table(\"test9.tab\")\n        f = filter.FilterString(-5, filter.FilterString.IsDefined)\n        x = filter.Values([f])(d)\n        self.assertEqual(len(x), 7)\n\n    def test_valueFilter_discrete_meta_is_defined(self):\n        d = data.Table(\"test9.tab\")\n        f = filter.FilterDiscrete(-4, None)\n        x = filter.Values([f])(d)\n        self.assertEqual(len(x), 8)\n\n    def test_valueFilter_string_case_sens(self):\n        d = data.Table(\"zoo\")\n        col = d[:, \"name\"].metas[:, 0]\n\n        f = filter.FilterString(\"name\",\n                                filter.FilterString.Equal, \"girl\")\n        x = filter.Values([f])(d)\n        self.assertEqual(len(x), 1)\n        self.assertEqual(x[0, \"name\"], \"girl\")\n        self.assertTrue(np.all(x.metas == \"girl\"))\n\n        f.oper = f.NotEqual\n        x = filter.Values([f])(d)\n        self.assertEqual(len(x), len(d) - 1)\n        self.assertTrue(np.all(x[:, \"name\"] != \"girl\"))\n\n        f.oper = f.Less\n        x = filter.Values([f])(d)\n        self.assertEqual(len(x), sum(col < \"girl\"))\n        self.assertTrue(np.all(x.metas < \"girl\"))\n\n        f.oper = f.LessEqual\n        x = filter.Values([f])(d)\n        self.assertEqual(len(x), sum(col <= \"girl\"))\n        self.assertTrue(np.all(x.metas <= \"girl\"))\n\n        f.oper = f.Greater\n        x = filter.Values([f])(d)\n        self.assertEqual(len(x), sum(col > \"girl\"))\n        self.assertTrue(np.all(x.metas > \"girl\"))\n\n        f.oper = f.GreaterEqual\n        x = filter.Values([f])(d)\n        self.assertEqual(len(x), sum(col >= \"girl\"))\n        self.assertTrue(np.all(x.metas >= \"girl\"))\n\n        f.oper = f.Between\n        f.max = \"lion\"\n        x = filter.Values([f])(d)\n        self.assertEqual(len(x), sum((col >= \"girl\") * (col <= \"lion\")))\n        self.assertTrue(np.all(x.metas >= \"girl\"))\n        self.assertTrue(np.all(x.metas <= \"lion\"))\n\n        f.oper = f.Outside\n        x = filter.Values([f])(d)\n        self.assertEqual(len(x), sum(col < \"girl\") + sum(col > \"lion\"))\n        self.assertTrue(np.all((x.metas < \"girl\") + (x.metas > \"lion\")))\n\n        f.oper = f.Contains\n        f.ref = \"ea\"\n        x = filter.Values([f])(d)\n        for e in x:\n            self.assertTrue(\"ea\" in e[\"name\"])\n        self.assertEqual(len(x), len([e for e in col if \"ea\" in e]))\n\n        f.oper = f.StartsWith\n        f.ref = \"sea\"\n        x = filter.Values([f])(d)\n        for e in x:\n            self.assertTrue(str(e[\"name\"]).startswith(\"sea\"))\n        self.assertEqual(len(x), len([e for e in col if e.startswith(\"sea\")]))\n\n        f.oper = f.EndsWith\n        f.ref = \"ion\"\n        x = filter.Values([f])(d)\n        for e in x:\n            self.assertTrue(str(e[\"name\"]).endswith(\"ion\"))\n        self.assertEqual(len(x), len([e for e in col if e.endswith(\"ion\")]))\n\n    def test_valueFilter_string_case_insens(self):\n        d = data.Table(\"zoo\")\n        d[d[:, \"name\"].metas[:, 0] == \"girl\", \"name\"] = \"GIrl\"\n\n        col = d[:, \"name\"].metas[:, 0]\n\n        f = filter.FilterString(\"name\",\n                                filter.FilterString.Equal, \"giRL\")\n        f.case_sensitive = False\n        x = filter.Values([f])(d)\n        self.assertEqual(len(x), 1)\n        self.assertEqual(x[0, \"name\"], \"GIrl\")\n        self.assertTrue(np.all(x.metas == \"GIrl\"))\n\n        f.oper = f.NotEqual\n        x = filter.Values([f])(d)\n        self.assertEqual(len(x), len(d) - 1)\n        self.assertTrue(np.all(x[:, \"name\"] != \"GIrl\"))\n\n        f.oper = f.Less\n        f.ref = \"CHiCKEN\"\n        x = filter.Values([f])(d)\n        self.assertEqual(len(x), sum(col < \"chicken\") - 1)  # girl!\n        self.assertTrue(np.all(x.metas < \"chicken\"))\n\n        f.oper = f.LessEqual\n        x = filter.Values([f])(d)\n        self.assertEqual(len(x), sum(col <= \"chicken\") - 1)\n        self.assertTrue(np.all(x.metas <= \"chicken\"))\n\n        f.oper = f.Greater\n        x = filter.Values([f])(d)\n        self.assertEqual(len(x), sum(col > \"chicken\") + 1)\n        for e in x:\n            self.assertGreater(str(e[\"name\"]).lower(), \"chicken\")\n\n        f.oper = f.GreaterEqual\n        x = filter.Values([f])(d)\n        self.assertEqual(len(x), sum(col >= \"chicken\") + 1)\n        for e in x:\n            self.assertGreaterEqual(str(e[\"name\"]).lower(), \"chicken\")\n\n        f.oper = f.Between\n        f.max = \"liOn\"\n        x = filter.Values([f])(d)\n        self.assertEqual(len(x), sum((col >= \"chicken\") * (col <= \"lion\")) + 1)\n        for e in x:\n            self.assertTrue(\"chicken\" <= str(e[\"name\"]).lower() <= \"lion\")\n\n        f.oper = f.Outside\n        x = filter.Values([f])(d)\n        self.assertEqual(len(x), sum(col < \"chicken\") + sum(col > \"lion\") - 1)\n        self.assertTrue(np.all((x.metas < \"chicken\") + (x.metas > \"lion\")))\n\n        f.oper = f.Contains\n        f.ref = \"iR\"\n        x = filter.Values([f])(d)\n        for e in x:\n            self.assertTrue(\"ir\" in str(e[\"name\"]).lower())\n        self.assertEqual(len(x), len([e for e in col if \"ir\" in e]) + 1)\n\n        f.oper = f.StartsWith\n        f.ref = \"GI\"\n        x = filter.Values([f])(d)\n        for e in x:\n            self.assertTrue(str(e[\"name\"]).lower().startswith(\"gi\"))\n        self.assertEqual(len(x),\n                         len([e for e in col if e.lower().startswith(\"gi\")]))\n\n        f.oper = f.EndsWith\n        f.ref = \"ion\"\n        x = filter.Values([f])(d)\n        for e in x:\n            self.assertTrue(str(e[\"name\"]).endswith(\"ion\"))\n            self.assertTrue(str(e[\"name\"]).endswith(\"ion\"))\n        self.assertEqual(len(x), len([e for e in col if e.endswith(\"ion\")]))\n\n    def test_valueFilter_regex(self):\n        d = data.Table(\"zoo\")\n        f = filter.FilterRegex(d.domain['name'], '^c...$')\n        x = filter.Values([f])(d)\n        self.assertEqual(len(x), 7)\n\n    def test_valueFilter_stringList(self):\n        data = Table(\"zoo\")\n        var = data.domain[\"name\"]\n\n        fs = filter.FilterStringList\n        filters = [\n            (([\"swan\", \"tuna\", \"wasp\"], True), dict(rows=3)),\n            (([\"swan\", \"tuna\", \"wasp\"], False), dict(rows=3)),\n            (([\"WoRm\", \"TOad\", \"vOLe\"], True), dict(rows=0)),\n            (([\"WoRm\", \"TOad\", \"vOLe\"], False), dict(rows=3)),\n        ]\n\n        for args, expected in filters:\n            f = fs(var, *args)\n            filtered_data = filter.Values([f])(data)\n            self.assertEqual(len(filtered_data), expected[\"rows\"],\n                             \"{} returned wrong number of rows\".format(args))\n\n    def test_table_dtypes(self):\n        table = data.Table(\"iris\")\n        metas = np.hstack((table.metas, table.Y.reshape(len(table), 1)))\n        attributes_metas = table.domain.metas + table.domain.class_vars\n        domain_metas = data.Domain(table.domain.attributes,\n                                   table.domain.class_vars,\n                                   attributes_metas)\n        table_metas = data.Table(domain_metas, table.X, table.Y, metas)\n        new_table = data.Table(data.Domain(table_metas.domain.metas,\n                                           table_metas.domain.metas,\n                                           table_metas.domain.metas),\n                               table_metas)\n        self.assertEqual(new_table.X.dtype, np.float64)\n        self.assertEqual(new_table.Y.dtype, np.float64)\n        self.assertEqual(new_table.metas.dtype, np.float64)\n\n    def test_attributes(self):\n        table = data.Table(\"iris\")\n        table.attributes = {1: \"test\"}\n        table2 = table[:4]\n        self.assertEqual(table2.attributes[1], \"test\")\n        table2.attributes[1] = \"modified\"\n        self.assertEqual(table.attributes[1], \"modified\")\n\n    # TODO Test conjunctions and disjunctions of conditions\n\n    def test_is_sparse(self):\n        table = data.Table(\"iris\")\n        self.assertFalse(table.is_sparse())\n\n        table.X = sp.csr_matrix(table.X)\n        self.assertTrue(table.is_sparse())\n\n    def test_repr_sparse_with_one_row(self):\n        table = data.Table(\"iris\")[:1]\n        table.X = sp.csr_matrix(table.X)\n        repr(table)     # make sure repr does not crash\n\n    def test_inf(self):\n        a = np.array([[2,   0,      0,      0],\n                      [0,   np.nan, np.nan, 1],\n                      [0,   0,      np.inf, 0]])\n        with self.assertWarns(Warning):\n            tab = data.Table(a)\n        self.assertEqual(tab.get_nan_frequency_attribute(), 3/12)",
                                "ast_type_str": "ClassDef",
                                "start_lineno": 40,
                                "end_lineno": 1286,
                                "parent": null
                            }
                        }
                    ],
                    "deleted_entities": []
                }
            ]
        }
    ],
    "old_commit_hash": "f3b183551b877f025889242567b0451e1a92a2ea^",
    "new_commit_hash": "f3b183551b877f025889242567b0451e1a92a2ea",
    "commit_message": "Table.from_numpy: Replace infs with nans.",
    "commit_date": "2019-02-22T14:24:14+01:00",
    "metadata": {}
}
{
    "repo_name": "orange3",
    "new_commit_hash": "f3b183551b877f025889242567b0451e1a92a2ea",
    "test_file_codes": [
        "# Test methods with long descriptive names can omit docstrings\n# pylint: disable=missing-docstring\n\nimport copy\nimport os\nimport random\nimport unittest\nfrom unittest.mock import Mock, MagicMock, patch\nfrom distutils.version import LooseVersion\nfrom itertools import chain\nfrom math import isnan\n\nimport numpy as np\nimport scipy.sparse as sp\n\nimport Orange\nfrom Orange import data\nfrom Orange.data import (filter, Unknown, Variable, Table, DiscreteVariable,\n                         ContinuousVariable, Domain, StringVariable)\nfrom Orange.tests import test_dirname, assert_array_nanequal\nfrom Orange.data.table import _optimize_indices\n\n\nif LooseVersion(Orange.__version__) < LooseVersion(\"3.24\"):\n    def skip_deprecated_length(f):\n        return unittest.skip(\n            f\"Method {f.__name__} will be deprecated; tests are \"\n            \"skipped because it already fails on Python 3.7 on travis\")(f)\nelse:\n    def skip_deprecated_length(f):\n        def raise_deprecation(_):\n            raise RuntimeError(\n                f\"We reached 3.24 and method {f.__name__} is now deprecated. \"\n                f\"Remove the method the corresponding tests.\")\n        # Also don't forget to remove this function and imports of LooseVersion\n        # and Orange\n        return raise_deprecation\n\n\nclass TableTestCase(unittest.TestCase):\n    def setUp(self):\n        Variable._clear_all_caches()\n        data.table.dataset_dirs.append(test_dirname())\n\n    def tearDown(self):\n        data.table.dataset_dirs.remove(test_dirname())\n\n    def test_indexing_class(self):\n        d = data.Table(\"test1\")\n        self.assertEqual([e.get_class() for e in d], [\"t\", \"t\", \"f\"])\n        cind = len(d.domain) - 1\n        self.assertEqual([e[cind] for e in d], [\"t\", \"t\", \"f\"])\n        self.assertEqual([e[\"d\"] for e in d], [\"t\", \"t\", \"f\"])\n        cvar = d.domain.class_var\n        self.assertEqual([e[cvar] for e in d], [\"t\", \"t\", \"f\"])\n\n    def test_filename(self):\n        dir = data.table.get_sample_datasets_dir()\n        d = data.Table(\"iris\")\n        self.assertEqual(d.__file__, os.path.join(dir, \"iris.tab\"))\n\n        d = data.Table(\"test2.tab\")\n        self.assertTrue(d.__file__.endswith(\"test2.tab\"))  # platform dependent\n\n    def test_indexing(self):\n        import warnings\n\n        with warnings.catch_warnings():\n            warnings.simplefilter(\"ignore\")\n            d = data.Table(\"test2\")\n\n            # regular, discrete\n            varc = d.domain[\"c\"]\n            self.assertEqual(d[0, 1], \"0\")\n            self.assertEqual(d[0, varc], \"0\")\n            self.assertEqual(d[0, \"c\"], \"0\")\n            self.assertEqual(d[0][1], \"0\")\n            self.assertEqual(d[0][varc], \"0\")\n            self.assertEqual(d[0][\"c\"], \"0\")\n            self.assertEqual(d[np.int_(0), np.int_(1)], \"0\")\n            self.assertEqual(d[np.int_(0)][np.int_(1)], \"0\")\n\n            # regular, continuous\n            varb = d.domain[\"b\"]\n            self.assertEqual(d[0, 0], 0)\n            self.assertEqual(d[0, varb], 0)\n            self.assertEqual(d[0, \"b\"], 0)\n            self.assertEqual(d[0][0], 0)\n            self.assertEqual(d[0][varb], 0)\n            self.assertEqual(d[0][\"b\"], 0)\n            self.assertEqual(d[np.int_(0), np.int_(0)], 0)\n            self.assertEqual(d[np.int_(0)][np.int_(0)], 0)\n\n            # negative\n            varb = d.domain[\"b\"]\n            self.assertEqual(d[-2, 0], 3.333)\n            self.assertEqual(d[-2, varb], 3.333)\n            self.assertEqual(d[-2, \"b\"], 3.333)\n            self.assertEqual(d[-2][0], 3.333)\n            self.assertEqual(d[-2][varb], 3.333)\n            self.assertEqual(d[-2][\"b\"], 3.333)\n            self.assertEqual(d[np.int_(-2), np.int_(0)], 3.333)\n            self.assertEqual(d[np.int_(-2)][np.int_(0)], 3.333)\n\n            # meta, discrete\n            vara = d.domain[\"a\"]\n            metaa = d.domain.index(\"a\")\n            self.assertEqual(d[0, metaa], \"A\")\n            self.assertEqual(d[0, vara], \"A\")\n            self.assertEqual(d[0, \"a\"], \"A\")\n            self.assertEqual(d[0][metaa], \"A\")\n            self.assertEqual(d[0][vara], \"A\")\n            self.assertEqual(d[0][\"a\"], \"A\")\n            self.assertEqual(d[np.int_(0), np.int_(metaa)], \"A\")\n            self.assertEqual(d[np.int_(0)][np.int_(metaa)], \"A\")\n\n            # meta, string\n            vare = d.domain[\"e\"]\n            metae = d.domain.index(\"e\")\n            self.assertEqual(d[0, metae], \"i\")\n            self.assertEqual(d[0, vare], \"i\")\n            self.assertEqual(d[0, \"e\"], \"i\")\n            self.assertEqual(d[0][metae], \"i\")\n            self.assertEqual(d[0][vare], \"i\")\n            self.assertEqual(d[0][\"e\"], \"i\")\n            self.assertEqual(d[np.int_(0), np.int_(metae)], \"i\")\n            self.assertEqual(d[np.int_(0)][np.int_(metae)], \"i\")\n\n    def test_indexing_example(self):\n        import warnings\n\n        with warnings.catch_warnings():\n            warnings.simplefilter(\"ignore\")\n            d = data.Table(\"test2\")\n            e = d[0]\n\n            # regular, discrete\n            varc = d.domain[\"c\"]\n            self.assertEqual(e[1], \"0\")\n            self.assertEqual(e[varc], \"0\")\n            self.assertEqual(e[\"c\"], \"0\")\n            self.assertEqual(e[np.int_(1)], \"0\")\n\n            # regular, continuous\n            varb = d.domain[\"b\"]\n            self.assertEqual(e[0], 0)\n            self.assertEqual(e[varb], 0)\n            self.assertEqual(e[\"b\"], 0)\n            self.assertEqual(e[np.int_(0)], 0)\n\n            # meta, discrete\n            vara = d.domain[\"a\"]\n            metaa = d.domain.index(\"a\")\n            self.assertEqual(e[metaa], \"A\")\n            self.assertEqual(e[vara], \"A\")\n            self.assertEqual(e[\"a\"], \"A\")\n            self.assertEqual(e[np.int_(metaa)], \"A\")\n\n            # meta, string\n            vare = d.domain[\"e\"]\n            metae = d.domain.index(\"e\")\n            self.assertEqual(e[metae], \"i\")\n            self.assertEqual(e[vare], \"i\")\n            self.assertEqual(e[\"e\"], \"i\")\n            self.assertEqual(e[np.int_(metae)], \"i\")\n\n    def test_indexing_assign_value(self):\n        import warnings\n\n        with warnings.catch_warnings():\n            warnings.simplefilter(\"ignore\")\n            d = data.Table(\"test2\")\n\n            # meta\n            vara = d.domain[\"a\"]\n            metaa = d.domain.index(\"a\")\n\n            self.assertEqual(d[0, \"a\"], \"A\")\n            d[0, \"a\"] = \"B\"\n            self.assertEqual(d[0, \"a\"], \"B\")\n            d[0][\"a\"] = \"A\"\n            self.assertEqual(d[0, \"a\"], \"A\")\n\n            d[0, vara] = \"B\"\n            self.assertEqual(d[0, \"a\"], \"B\")\n            d[0][vara] = \"A\"\n            self.assertEqual(d[0, \"a\"], \"A\")\n\n            d[0, metaa] = \"B\"\n            self.assertEqual(d[0, \"a\"], \"B\")\n            d[0][metaa] = \"A\"\n            self.assertEqual(d[0, \"a\"], \"A\")\n\n            d[0, np.int_(metaa)] = \"B\"\n            self.assertEqual(d[0, \"a\"], \"B\")\n            d[0][np.int_(metaa)] = \"A\"\n            self.assertEqual(d[0, \"a\"], \"A\")\n\n            # regular\n            varb = d.domain[\"b\"]\n\n            self.assertEqual(d[0, \"b\"], 0)\n            d[0, \"b\"] = 42\n            self.assertEqual(d[0, \"b\"], 42)\n            d[0][\"b\"] = 0\n            self.assertEqual(d[0, \"b\"], 0)\n\n            d[0, varb] = 42\n            self.assertEqual(d[0, \"b\"], 42)\n            d[0][varb] = 0\n            self.assertEqual(d[0, \"b\"], 0)\n\n            d[0, 0] = 42\n            self.assertEqual(d[0, \"b\"], 42)\n            d[0][0] = 0\n            self.assertEqual(d[0, \"b\"], 0)\n\n            d[0, np.int_(0)] = 42\n            self.assertEqual(d[0, \"b\"], 42)\n            d[0][np.int_(0)] = 0\n            self.assertEqual(d[0, \"b\"], 0)\n\n    @skip_deprecated_length\n    def test_indexing_del_example(self):\n        import warnings\n\n        with warnings.catch_warnings():\n            warnings.simplefilter(\"ignore\")\n            d = data.Table(\"test2\")\n            initlen = len(d)\n\n            # remove first\n            d[4, \"e\"] = \"4ex\"\n            self.assertEqual(d[4, \"e\"], \"4ex\")\n            del d[0]\n            self.assertEqual(len(d), initlen - 1)\n            self.assertEqual(d[3, \"e\"], \"4ex\")\n\n            # remove middle\n            del d[2]\n            self.assertEqual(len(d), initlen - 2)\n            self.assertEqual(d[2, \"e\"], \"4ex\")\n\n            # remove middle\n            del d[4]\n            self.assertEqual(len(d), initlen - 3)\n            self.assertEqual(d[2, \"e\"], \"4ex\")\n\n            # remove last\n            d[-1, \"e\"] = \"was last\"\n            del d[-1]\n            self.assertEqual(len(d), initlen - 4)\n            self.assertEqual(d[2, \"e\"], \"4ex\")\n            self.assertNotEqual(d[-1, \"e\"], \"was last\")\n\n            # remove one before last\n            d[-1, \"e\"] = \"was last\"\n            del d[-2]\n            self.assertEqual(len(d), initlen - 5)\n            self.assertEqual(d[2, \"e\"], \"4ex\")\n            self.assertEqual(d[-1, \"e\"], \"was last\")\n\n            d[np.int_(2), \"e\"] = \"2ex\"\n            del d[np.int_(2)]\n            self.assertEqual(len(d), initlen - 6)\n            self.assertNotEqual(d[2, \"e\"], \"2ex\")\n\n            with self.assertRaises(IndexError):\n                del d[100]\n            self.assertEqual(len(d), initlen - 6)\n\n            with self.assertRaises(IndexError):\n                del d[-100]\n            self.assertEqual(len(d), initlen - 6)\n\n    def test_indexing_assign_example(self):\n        def almost_equal_list(s, t):\n            for e, f in zip(s, t):\n                self.assertAlmostEqual(e, f)\n\n        import warnings\n\n        with warnings.catch_warnings():\n            warnings.simplefilter(\"ignore\")\n            d = data.Table(\"test2\")\n\n            vara = d.domain[\"a\"]\n            metaa = d.domain.index(vara)\n\n            self.assertFalse(isnan(d[0, \"a\"]))\n            d[0] = [\"3.14\", \"1\", \"f\"]\n            almost_equal_list(d[0].values(), [3.14, \"1\", \"f\"])\n            self.assertTrue(isnan(d[0, \"a\"]))\n            d[0] = [3.15, 1, \"t\"]\n            almost_equal_list(d[0].values(), [3.15, \"0\", \"t\"])\n            d[np.int_(0)] = [3.15, 2, \"f\"]\n            almost_equal_list(d[0].values(), [3.15, 2, \"f\"])\n\n            with self.assertRaises(ValueError):\n                d[0] = [\"3.14\", \"1\"]\n\n            with self.assertRaises(ValueError):\n                d[np.int_(0)] = [\"3.14\", \"1\"]\n\n            ex = data.Instance(d.domain, [\"3.16\", \"1\", \"f\"])\n            d[0] = ex\n            almost_equal_list(d[0].values(), [3.16, \"1\", \"f\"])\n\n            ex = data.Instance(d.domain, [\"3.16\", 2, \"t\"])\n            d[np.int_(0)] = ex\n            almost_equal_list(d[0].values(), [3.16, 2, \"t\"])\n\n            ex = data.Instance(d.domain, [\"3.16\", \"1\", \"f\"])\n            ex[\"e\"] = \"mmmapp\"\n            d[0] = ex\n            almost_equal_list(d[0].values(), [3.16, \"1\", \"f\"])\n            self.assertEqual(d[0, \"e\"], \"mmmapp\")\n\n    def test_slice(self):\n        import warnings\n\n        with warnings.catch_warnings():\n            warnings.simplefilter(\"ignore\")\n            d = data.Table(\"test2\")\n            x = d[:3]\n            self.assertEqual(len(x), 3)\n            self.assertEqual([e[0] for e in x], [0, 1.1, 2.22])\n\n            x = d[2:5]\n            self.assertEqual(len(x), 3)\n            self.assertEqual([e[0] for e in x], [2.22, 2.23, 2.24])\n\n            x = d[4:1:-1]\n            self.assertEqual(len(x), 3)\n            self.assertEqual([e[0] for e in x], [2.24, 2.23, 2.22])\n\n            x = d[-3:]\n            self.assertEqual(len(x), 3)\n            self.assertEqual([e[0] for e in x], [2.26, 3.333, Unknown])\n\n    def test_assign_slice_value(self):\n        import warnings\n\n        with warnings.catch_warnings():\n            warnings.simplefilter(\"ignore\")\n            d = data.Table(\"test2\")\n            d[2:5, 0] = 42\n            self.assertEqual([e[0] for e in d],\n                             [0, 1.1, 42, 42, 42, 2.25, 2.26, 3.333, Unknown])\n            d[:3, \"b\"] = 43\n            self.assertEqual([e[0] for e in d],\n                             [43, 43, 43, 42, 42, 2.25, 2.26, 3.333, None])\n            d[-2:, d.domain[0]] = 44\n            self.assertEqual([e[0] for e in d],\n                             [43, 43, 43, 42, 42, 2.25, 2.26, 44, 44])\n\n            d[2:5, \"a\"] = \"A\"\n            self.assertEqual([e[\"a\"] for e in d], list(\"ABAAACCDE\"))\n\n    @skip_deprecated_length\n    def test_del_slice_example(self):\n        import warnings\n\n        with warnings.catch_warnings():\n            warnings.simplefilter(\"ignore\")\n            d = data.Table(\"test2\")\n\n            vals = [e[0] for e in d]\n\n            del d[2:2]\n            self.assertEqual([e[0] for e in d], vals)\n\n            del d[2:5]\n            del vals[2:5]\n            self.assertEqual([e[0] for e in d], vals)\n\n            del d[:]\n            self.assertEqual(len(d), 0)\n\n    @skip_deprecated_length\n    def test_del_slice_ids(self):\n        # __del__ updates `ids` member\n        d = data.Table(\"test2\")\n        ids = d.ids.copy()\n        del d[2:4]\n        np.testing.assert_array_equal(d.ids, np.delete(ids, slice(2, 4)))\n\n    @skip_deprecated_length\n    def test_set_slice_example(self):\n        import warnings\n\n        with warnings.catch_warnings():\n            warnings.simplefilter(\"ignore\")\n            d = data.Table(\"test2\")\n            d[5, 0] = 42\n            d[:3] = d[5]\n            self.assertEqual(d[1, 0], 42)\n\n            d[5:2:-1] = [3, None, None]\n            self.assertEqual([e[0] for e in d],\n                             [42, 42, 42, 3, 3, 3, 2.26, 3.333, None])\n            self.assertTrue(isnan(d[3, 2]))\n\n            d[2:5] = 42\n            self.assertTrue(np.all(d.X[2:5] == 42))\n            self.assertEqual(d.Y[2], 0)\n\n    def test_multiple_indices(self):\n        import warnings\n\n        with warnings.catch_warnings():\n            warnings.simplefilter(\"ignore\")\n            d = data.Table(\"test2\")\n\n            with self.assertRaises(IndexError):\n                x = d[2, 5, 1]\n\n            with self.assertRaises(IndexError):\n                x = d[(2, 5, 1)]\n\n            x = d[[2, 5, 1]]\n            self.assertEqual([e[0] for e in x], [2.22, 2.25, 1.1])\n\n    def test_assign_multiple_indices_value(self):\n        import warnings\n\n        with warnings.catch_warnings():\n            warnings.simplefilter(\"ignore\")\n            d = data.Table(\"test2\")\n\n            d[1:4, \"b\"] = 42\n            self.assertEqual([e[0] for e in d],\n                             [0, 42, 42, 42, 2.24, 2.25, 2.26, 3.333, None])\n\n            d[range(5, 2, -1), \"b\"] = None\n            self.assertEqual([e[d.domain[0]] for e in d],\n                             [0, 42, 42, None, \"?\", \"\", 2.26, 3.333, None])\n\n    @skip_deprecated_length\n    def test_del_multiple_indices_example(self):\n        import warnings\n\n        with warnings.catch_warnings():\n            warnings.simplefilter(\"ignore\")\n            d = data.Table(\"test2\")\n\n            vals = [e[0] for e in d]\n\n            del d[[1, 5, 2]]\n            del vals[5]\n            del vals[2]\n            del vals[1]\n            self.assertEqual([e[0] for e in d], vals)\n\n            del d[range(1, 3)]\n            del vals[1:3]\n            self.assertEqual([e[0] for e in d], vals)\n\n    def test_set_multiple_indices_example(self):\n        import warnings\n\n        with warnings.catch_warnings():\n            warnings.simplefilter(\"ignore\")\n            d = data.Table(\"test2\")\n\n            vals = [e[0] for e in d]\n            d[[1, 2, 5]] = [42, None, None]\n            vals[1] = vals[2] = vals[5] = 42\n            self.assertEqual([e[0] for e in d], vals)\n\n    @skip_deprecated_length\n    def test_views(self):\n        d = data.Table(\"zoo\")\n        crc = d.checksum(True)\n        x = d[:20]\n        self.assertEqual(crc, d.checksum(True))\n        del x[13]\n        self.assertEqual(crc, d.checksum(True))\n        del x[4:9]\n        self.assertEqual(crc, d.checksum(True))\n\n    def test_bool(self):\n        d = data.Table(\"iris\")\n        self.assertTrue(d)\n\n        d = data.Table(\"test3\")\n        self.assertFalse(d)\n\n        d = data.Table(\"iris\")\n        self.assertTrue(d)\n\n    def test_checksum(self):\n        d = data.Table(\"zoo\")\n        d[42, 3] = 0\n        crc1 = d.checksum(False)\n        d[42, 3] = 1\n        crc2 = d.checksum(False)\n        self.assertNotEqual(crc1, crc2)\n        d[42, 3] = 0\n        crc3 = d.checksum(False)\n        self.assertEqual(crc1, crc3)\n        _ = d[42, \"name\"]\n        d[42, \"name\"] = \"non-animal\"\n        crc4 = d.checksum(False)\n        self.assertEqual(crc1, crc4)\n        crc4 = d.checksum(True)\n        crc5 = d.checksum(1)\n        crc6 = d.checksum(False)\n        self.assertNotEqual(crc1, crc4)\n        self.assertNotEqual(crc1, crc5)\n        self.assertEqual(crc1, crc6)\n\n    def test_total_weight(self):\n        d = data.Table(\"zoo\")\n        self.assertEqual(d.total_weight(), len(d))\n\n        d.set_weights(0)\n        d[0].weight = 0.1\n        d[10].weight = 0.2\n        d[-1].weight = 0.3\n        self.assertAlmostEqual(d.total_weight(), 0.6)\n\n    def test_has_missing(self):\n        d = data.Table(\"zoo\")\n        self.assertFalse(d.has_missing())\n        self.assertFalse(d.has_missing_class())\n\n        d[10, 3] = \"?\"\n        self.assertTrue(d.has_missing())\n        self.assertFalse(d.has_missing_class())\n\n        d[10].set_class(\"?\")\n        self.assertTrue(d.has_missing())\n        self.assertTrue(d.has_missing_class())\n\n        d = data.Table(\"test3\")\n        self.assertFalse(d.has_missing())\n        self.assertFalse(d.has_missing_class())\n\n    def test_shuffle(self):\n        d = data.Table(\"zoo\")\n        crc = d.checksum()\n        names = set(str(x[\"name\"]) for x in d)\n\n        d.shuffle()\n        self.assertNotEqual(crc, d.checksum())\n        self.assertSetEqual(names, set(str(x[\"name\"]) for x in d))\n        crc2 = d.checksum()\n\n        x = d[2:10]\n        crcx = x.checksum()\n        d.shuffle()\n        self.assertNotEqual(crc2, d.checksum())\n        self.assertEqual(crcx, x.checksum())\n\n        crc2 = d.checksum()\n        x.shuffle()\n        self.assertNotEqual(crcx, x.checksum())\n        self.assertEqual(crc2, d.checksum())\n\n    @staticmethod\n    def not_less_ex(ex1, ex2):\n        for v1, v2 in zip(ex1, ex2):\n            if v1 != v2:\n                return v1 < v2\n        return True\n\n    @staticmethod\n    def sorted(d):\n        for i in range(1, len(d)):\n            if not TableTestCase.not_less_ex(d[i - 1], d[i]):\n                return False\n        return True\n\n    @staticmethod\n    def not_less_ex_ord(ex1, ex2, ord):\n        for a in ord:\n            if ex1[a] != ex2[a]:\n                return ex1[a] < ex2[a]\n        return True\n\n    @staticmethod\n    def sorted_ord(d, ord):\n        for i in range(1, len(d)):\n            if not TableTestCase.not_less_ex_ord(d[i - 1], d[i], ord):\n                return False\n        return True\n\n    @skip_deprecated_length\n    def test_append(self):\n        d = data.Table(\"test3\")\n        d.append([None] * 3)\n        self.assertEqual(1, len(d))\n        self.assertTrue(all(isnan(i) for i in d[0]))\n\n        d.append([42, \"0\", None])\n        self.assertEqual(2, len(d))\n        self.assertEqual(d[1], [42, \"0\", None])\n\n        assert_array_nanequal(\n            d.metas,\n            np.array([[v.Unknown for v in d.domain.metas]] * 2,\n                     dtype=object))\n\n    @skip_deprecated_length\n    def test_append2(self):\n        d = data.Table(\"iris\")\n        d.shuffle()\n        l1 = len(d)\n        d.append([1, 2, 3, 4, 0])\n        self.assertEqual(len(d), l1 + 1)\n        self.assertEqual(d[-1], [1, 2, 3, 4, 0])\n\n        x = data.Instance(d[10])\n        d.append(x)\n        self.assertEqual(d[-1], d[10])\n\n        x = d[:50]\n        x.ensure_copy()\n        x.append(d[50])\n        self.assertEqual(x[50], d[50])\n\n    @skip_deprecated_length\n    def test_extend(self):\n        d = data.Table(\"iris\")\n        d.shuffle()\n\n        x = d[:5]\n        x.ensure_copy()\n        d.extend(x)\n        for i in range(5):\n            self.assertEqual(d[i], d[-5 + i])\n\n        y = d[:2, 1]\n        x.ensure_copy()\n        x.extend(y)\n        np.testing.assert_almost_equal(x[-2:, 1].X, y.X)\n        self.assertEqual(np.isnan(x).sum(), 8)\n\n    @skip_deprecated_length\n    def test_extend2(self):\n        d = data.Table(\"test3\")\n        d.extend([[None] * 3,\n                  [None] * 3])\n        assert_array_nanequal(\n            d.metas,\n            np.array([[v.Unknown for v in d.domain.metas]] * 2,\n                     dtype=object))\n\n    def test_copy(self):\n        t = data.Table(np.zeros((5, 3)), np.arange(5), np.zeros((5, 3)))\n\n        copy = t.copy()\n        self.assertTrue(np.all(t.X == copy.X))\n        self.assertTrue(np.all(t.Y == copy.Y))\n        self.assertTrue(np.all(t.metas == copy.metas))\n        copy[0] = [1, 1, 1, 1, 1, 1, 1, 1]\n        self.assertFalse(np.all(t.X == copy.X))\n        self.assertFalse(np.all(t.Y == copy.Y))\n        self.assertFalse(np.all(t.metas == copy.metas))\n\n    def test_copy_sparse(self):\n        t = data.Table('iris').to_sparse()\n        copy = t.copy()\n\n        self.assertEqual((t.X != copy.X).nnz, 0)      # sparse matrices match by content\n        np.testing.assert_equal(t.Y, copy.Y)\n        np.testing.assert_equal(t.metas, copy.metas)\n\n        self.assertNotEqual(id(t.X), id(copy.X))\n        self.assertNotEqual(id(t._Y), id(copy._Y))\n        self.assertNotEqual(id(t.metas), id(copy.metas))\n\n    def test_concatenate(self):\n        d1 = data.Domain([data.ContinuousVariable('a1')])\n        t1 = data.Table.from_numpy(d1, [[1],\n                                        [2]])\n        d2 = data.Domain([data.ContinuousVariable('a2')],\n                         metas=[data.StringVariable('s')])\n        t2 = data.Table.from_numpy(d2, [[3],\n                                        [4]], metas=[['foo'],\n                                                     ['fuu']])\n        self.assertRaises(ValueError,\n                          lambda: data.Table.concatenate((t1, t2), axis=5))\n\n        t3 = data.Table.concatenate((t1, t2))\n        self.assertEqual(t3.domain.attributes,\n                         t1.domain.attributes + t2.domain.attributes)\n        self.assertEqual(len(t3.domain.metas), 1)\n        self.assertEqual(t3.X.shape, (2, 2))\n        self.assertRaises(ValueError, lambda: data.Table.concatenate((t3, t1)))\n        self.assertRaises(ValueError, lambda: data.Table.concatenate((t3, t1), axis=0))\n\n        t4 = data.Table.concatenate((t3, t3), axis=0)\n        np.testing.assert_equal(t4.X, [[1, 3],\n                                       [2, 4],\n                                       [1, 3],\n                                       [2, 4]])\n\n    def test_sparse_concatenate_rows(self):\n        iris = Table(\"iris\")\n        iris.X = sp.csc_matrix(iris.X)\n        new = Table.concatenate([iris, iris], axis=0)\n        self.assertEqual(len(new), 300)\n        self.assertTrue(sp.issparse(new.X), \"Concatenated X is not sparse.\")\n        self.assertFalse(sp.issparse(new.Y), \"Concatenated Y is not dense.\")\n        self.assertFalse(sp.issparse(new.metas), \"Concatenated metas is not dense.\")\n        self.assertEqual(len(new.ids), 300)\n\n    @skip_deprecated_length\n    def test_convert_through_append(self):\n        d = data.Table(\"iris\")\n        dom2 = data.Domain([d.domain[0], d.domain[2], d.domain[4]])\n        d2 = data.Table(dom2)\n        dom3 = data.Domain([d.domain[1], d.domain[2]], None)\n        d3 = data.Table(dom3)\n        for e in d[:5]:\n            d2.append(e)\n            d3.append(e)\n        for e, e2, e3 in zip(d, d2, d3):\n            self.assertEqual(e[0], e2[0])\n            self.assertEqual(e[1], e3[0])\n\n    def test_pickle(self):\n        import pickle\n\n        d = data.Table(\"zoo\")\n        s = pickle.dumps(d)\n        d2 = pickle.loads(s)\n        self.assertEqual(d[0], d2[0])\n\n        self.assertEqual(d.checksum(include_metas=False),\n                         d2.checksum(include_metas=False))\n\n        d = data.Table(\"iris\")\n        s = pickle.dumps(d)\n        d2 = pickle.loads(s)\n        self.assertEqual(d[0], d2[0])\n        self.assertEqual(d.checksum(include_metas=False),\n                         d2.checksum(include_metas=False))\n\n    def test_translate_through_slice(self):\n        d = data.Table(\"iris\")\n        dom = data.Domain([\"petal length\", \"sepal length\", \"iris\"],\n                          source=d.domain)\n        d_ref = d[:10, dom.variables]\n        self.assertEqual(d_ref.domain.class_var, d.domain.class_var)\n        self.assertEqual(d_ref[0, \"petal length\"], d[0, \"petal length\"])\n        self.assertEqual(d_ref[0, \"sepal length\"], d[0, \"sepal length\"])\n        self.assertEqual(d_ref.X.shape, (10, 2))\n        self.assertEqual(d_ref.Y.shape, (10,))\n\n    def test_saveTab(self):\n        d = data.Table(\"iris\")[:3]\n        d.save(\"test-save.tab\")\n        try:\n            d2 = data.Table(\"test-save.tab\")\n            for e1, e2 in zip(d, d2):\n                self.assertEqual(e1, e2)\n        finally:\n            os.remove(\"test-save.tab\")\n            os.remove(\"test-save.tab.metadata\")\n\n        dom = data.Domain([data.ContinuousVariable(\"a\")])\n        d = data.Table(dom, [[i] for i in range(3)])\n        d.save(\"test-save.tab\")\n        try:\n            d2 = data.Table(\"test-save.tab\")\n            self.assertEqual(len(d.domain.attributes), 1)\n            self.assertEqual(d.domain.class_var, None)\n            for i in range(3):\n                self.assertEqual(d2[i], [i])\n        finally:\n            os.remove(\"test-save.tab\")\n\n        dom = data.Domain([data.ContinuousVariable(\"a\")], None)\n        d = data.Table(dom, [[i] for i in range(3)])\n        d.save(\"test-save.tab\")\n        try:\n            d2 = data.Table(\"test-save.tab\")\n            self.assertEqual(len(d.domain.attributes), 1)\n            for i in range(3):\n                self.assertEqual(d2[i], [i])\n        finally:\n            os.remove(\"test-save.tab\")\n\n        d = data.Table(\"zoo\")\n        d.save(\"test-zoo.tab\")\n        dd = data.Table(\"test-zoo\")\n        try:\n            self.assertTupleEqual(d.domain.metas, dd.domain.metas,\n                                  msg=\"Meta attributes don't match.\")\n            self.assertTupleEqual(d.domain.variables, dd.domain.variables,\n                                  msg=\"Attributes don't match.\")\n\n            np.testing.assert_almost_equal(d.W, dd.W,\n                                           err_msg=\"Weights don't match.\")\n            for i in range(10):\n                for j in d.domain.variables:\n                    self.assertEqual(d[i][j], dd[i][j])\n        finally:\n            os.remove(\"test-zoo.tab\")\n\n        d = data.Table(\"zoo\")\n        d.set_weights(range(len(d)))\n        d.save(\"test-zoo-weights.tab\")\n        dd = data.Table(\"test-zoo-weights\")\n        try:\n            self.assertTupleEqual(d.domain.metas, dd.domain.metas,\n                                  msg=\"Meta attributes don't match.\")\n            self.assertTupleEqual(d.domain.variables, dd.domain.variables,\n                                  msg=\"Attributes don't match.\")\n\n            np.testing.assert_almost_equal(d.W, dd.W,\n                                           err_msg=\"Weights don't match.\")\n            for i in range(10):\n                for j in d.domain.variables:\n                    self.assertEqual(d[i][j], dd[i][j])\n        finally:\n            os.remove(\"test-zoo-weights.tab\")\n\n    def test_save_pickle(self):\n        table = data.Table(\"iris\")\n        try:\n            table.save(\"iris.pickle\")\n            table2 = data.Table.from_file(\"iris.pickle\")\n            np.testing.assert_almost_equal(table.X, table2.X)\n            np.testing.assert_almost_equal(table.Y, table2.Y)\n            self.assertEqual(table.domain[0], table2.domain[0])\n        finally:\n            os.remove(\"iris.pickle\")\n\n    def test_from_numpy(self):\n        a = np.arange(20, dtype=\"d\").reshape((4, 5))\n        a[:, -1] = [0, 0, 0, 1]\n        dom = data.Domain([data.ContinuousVariable(x) for x in \"abcd\"],\n                          data.DiscreteVariable(\"e\", values=[\"no\", \"yes\"]))\n        table = data.Table(dom, a)\n        for i in range(4):\n            self.assertEqual(table[i].get_class(), \"no\" if i < 3 else \"yes\")\n            for j in range(5):\n                self.assertEqual(a[i, j], table[i, j])\n                table[i, j] = random.random()\n                self.assertEqual(a[i, j], table[i, j])\n\n        with self.assertRaises(IndexError):\n            table[0, -5] = 5\n\n    def test_filter_is_defined(self):\n        d = data.Table(\"iris\")\n        d[1, 4] = Unknown\n        self.assertTrue(isnan(d[1, 4]))\n        d[140, 0] = Unknown\n        e = filter.IsDefined()(d)\n        self.assertEqual(len(e), len(d) - 2)\n        self.assertEqual(e[0], d[0])\n        self.assertEqual(e[1], d[2])\n        self.assertEqual(e[147], d[149])\n        self.assertTrue(d.has_missing())\n        self.assertFalse(e.has_missing())\n\n    def test_filter_has_class(self):\n        d = data.Table(\"iris\")\n        d[1, 4] = Unknown\n        self.assertTrue(isnan(d[1, 4]))\n        d[140, 0] = Unknown\n        e = filter.HasClass()(d)\n        self.assertEqual(len(e), len(d) - 1)\n        self.assertEqual(e[0], d[0])\n        self.assertEqual(e[1], d[2])\n        self.assertEqual(e[148], d[149])\n        self.assertTrue(d.has_missing())\n        self.assertTrue(e.has_missing())\n        self.assertFalse(e.has_missing_class())\n\n    def test_filter_random(self):\n        d = data.Table(\"iris\")\n        e = filter.Random(50)(d)\n        self.assertEqual(len(e), 50)\n        e = filter.Random(50, negate=True)(d)\n        self.assertEqual(len(e), 100)\n        for i in range(5):\n            e = filter.Random(0.2)(d)\n            self.assertEqual(len(e), 30)\n            bc = np.bincount(np.array(e.Y[:], dtype=int))\n            if min(bc) > 7:\n                break\n        else:\n            self.fail(\"Filter returns too uneven distributions\")\n\n    def test_filter_values_nested(self):\n        d = data.Table(\"iris\")\n        f1 = filter.FilterContinuous(d.columns.sepal_length,\n                                     filter.FilterContinuous.Between,\n                                     min=4.5, max=5.0)\n        f2 = filter.FilterContinuous(d.columns.sepal_width,\n                                     filter.FilterContinuous.Between,\n                                     min=3.1, max=3.4)\n        f3 = filter.FilterDiscrete(d.columns.iris, [0, 1])\n        f = filter.Values([filter.Values([f1, f2], conjunction=False), f3])\n        self.assertEqual(41, len(f(d)))\n\n    def test_filter_string_works_for_numeric_columns(self):\n        var = StringVariable(\"s\")\n        data = Table(Domain([], metas=[var]), [[x] for x in range(21)])\n        # 1, 2, 3, ..., 18, 19, 20\n\n        fs = filter.FilterString\n        filters = [\n            ((fs.Greater, \"5\"), dict(rows=4)),\n            # 6, 7, 8, 9\n            ((fs.Between, \"15\", \"2\"), dict(rows=6)),\n            # 15, 16, 17, 18, 19, 2\n            ((fs.Contains, \"2\"), dict(rows=3)),\n            # 2, 12, 20\n        ]\n\n        for args, expected in filters:\n            f = fs(var, *args)\n            filtered_data = filter.Values([f])(data)\n            self.assertEqual(len(filtered_data), expected[\"rows\"],\n                             \"{} returned wrong number of rows\".format(args))\n\n    def test_filter_value_continuous(self):\n        d = data.Table(\"iris\")\n        col = d.X[:, 2]\n\n        v = d.columns\n        f = filter.FilterContinuous(v.petal_length,\n                                    filter.FilterContinuous.Between,\n                                    min=4.5, max=5.1)\n\n        x = filter.Values([f])(d)\n        self.assertTrue(np.all(x.X[:, 2] >= 4.5))\n        self.assertTrue(np.all(x.X[:, 2] <= 5.1))\n        self.assertEqual(sum((col >= 4.5) * (col <= 5.1)), len(x))\n\n        f.ref = 5.1\n        f.oper = filter.FilterContinuous.Equal\n        x = filter.Values([f])(d)\n        self.assertTrue(np.all(x.X[:, 2] == 5.1))\n        self.assertEqual(sum(col == 5.1), len(x))\n\n        f.oper = filter.FilterContinuous.NotEqual\n        x = filter.Values([f])(d)\n        self.assertTrue(np.all(x.X[:, 2] != 5.1))\n        self.assertEqual(sum(col != 5.1), len(x))\n\n        f.oper = filter.FilterContinuous.Less\n        x = filter.Values([f])(d)\n        self.assertTrue(np.all(x.X[:, 2] < 5.1))\n        self.assertEqual(sum(col < 5.1), len(x))\n\n        f.oper = filter.FilterContinuous.LessEqual\n        x = filter.Values([f])(d)\n        self.assertTrue(np.all(x.X[:, 2] <= 5.1))\n        self.assertEqual(sum(col <= 5.1), len(x))\n\n        f.oper = filter.FilterContinuous.Greater\n        x = filter.Values([f])(d)\n        self.assertTrue(np.all(x.X[:, 2] > 5.1))\n        self.assertEqual(sum(col > 5.1), len(x))\n\n        f.oper = filter.FilterContinuous.GreaterEqual\n        x = filter.Values([f])(d)\n        self.assertTrue(np.all(x.X[:, 2] >= 5.1))\n        self.assertEqual(sum(col >= 5.1), len(x))\n\n        f.oper = filter.FilterContinuous.Outside\n        f.ref, f.max = 4.5, 5.1\n        x = filter.Values([f])(d)\n        for e in x:\n            self.assertTrue(e[2] < 4.5 or e[2] > 5.1)\n        self.assertEqual(sum((col < 4.5) + (col > 5.1)), len(x))\n\n        f.oper = filter.FilterContinuous.IsDefined\n        f.ref = f.max = None\n        x = filter.Values([f])(d)\n        self.assertEqual(len(x), len(d))\n\n        d[:30, v.petal_length] = Unknown\n        x = filter.Values([f])(d)\n        self.assertEqual(len(x), len(d) - 30)\n\n    def test_filter_value_continuous_args(self):\n        d = data.Table(\"iris\")\n        col = d.X[:, 2]\n        v = d.columns\n\n        f = filter.FilterContinuous(v.petal_length,\n                                    filter.FilterContinuous.Equal, ref=5.1)\n        x = filter.Values([f])(d)\n        self.assertTrue(np.all(x.X[:, 2] == 5.1))\n        self.assertEqual(sum(col == 5.1), len(x))\n\n        f = filter.FilterContinuous(2,\n                                    filter.FilterContinuous.Equal, ref=5.1)\n        self.assertTrue(np.all(x.X[:, 2] == 5.1))\n        self.assertEqual(sum(col == 5.1), len(x))\n\n        f = filter.FilterContinuous(\"petal length\",\n                                    filter.FilterContinuous.Equal, ref=5.1)\n        self.assertTrue(np.all(x.X[:, 2] == 5.1))\n        self.assertEqual(sum(col == 5.1), len(x))\n\n        f = filter.FilterContinuous(\"sepal length\",\n                                    filter.FilterContinuous.Equal, ref=5.1)\n        f.column = 2\n        self.assertTrue(np.all(x.X[:, 2] == 5.1))\n        self.assertEqual(sum(col == 5.1), len(x))\n\n        f = filter.FilterContinuous(\"sepal length\",\n                                    filter.FilterContinuous.Equal, ref=5.1)\n        f.column = v.petal_length\n        self.assertTrue(np.all(x.X[:, 2] == 5.1))\n        self.assertEqual(sum(col == 5.1), len(x))\n\n        f = filter.FilterContinuous(v.petal_length,\n                                    filter.FilterContinuous.Equal, ref=18)\n        f.ref = 5.1\n        x = filter.Values([f])(d)\n        self.assertTrue(np.all(x.X[:, 2] == 5.1))\n        self.assertEqual(sum(col == 5.1), len(x))\n\n        f = filter.FilterContinuous(v.petal_length,\n                                    filter.FilterContinuous.Equal, ref=18)\n        f.ref = 5.1\n        x = filter.Values([f])(d)\n        self.assertTrue(np.all(x.X[:, 2] == 5.1))\n        self.assertEqual(sum(col == 5.1), len(x))\n\n    def test_valueFilter_discrete(self):\n        d = data.Table(\"zoo\")\n\n        f = filter.FilterDiscrete(d.domain.class_var, values=[2, 3, 4])\n        for e in filter.Values([f])(d):\n            self.assertTrue(e.get_class() in [2, 3, 4])\n\n        f.values = [\"mammal\"]\n        for e in filter.Values([f])(d):\n            self.assertEqual(e.get_class(), \"mammal\")\n\n        f = filter.FilterDiscrete(d.domain.class_var, values=[2, \"mammal\"])\n        for e in filter.Values([f])(d):\n            self.assertTrue(e.get_class() in [2, \"mammal\"])\n\n        f = filter.FilterDiscrete(d.domain.class_var, values=[2, \"martian\"])\n        self.assertRaises(ValueError, d._filter_values, f)\n\n        f = filter.FilterDiscrete(d.domain.class_var, values=[2, data.Table])\n        self.assertRaises(TypeError, d._filter_values, f)\n\n        v = d.columns\n        f = filter.FilterDiscrete(v.hair, values=None)\n        self.assertEqual(len(filter.Values([f])(d)), len(d))\n\n        d[:5, v.hair] = Unknown\n        self.assertEqual(len(filter.Values([f])(d)), len(d) - 5)\n\n    def test_valueFilter_string_is_defined(self):\n        d = data.Table(\"test9.tab\")\n        f = filter.FilterString(-5, filter.FilterString.IsDefined)\n        x = filter.Values([f])(d)\n        self.assertEqual(len(x), 7)\n\n    def test_valueFilter_discrete_meta_is_defined(self):\n        d = data.Table(\"test9.tab\")\n        f = filter.FilterDiscrete(-4, None)\n        x = filter.Values([f])(d)\n        self.assertEqual(len(x), 8)\n\n    def test_valueFilter_string_case_sens(self):\n        d = data.Table(\"zoo\")\n        col = d[:, \"name\"].metas[:, 0]\n\n        f = filter.FilterString(\"name\",\n                                filter.FilterString.Equal, \"girl\")\n        x = filter.Values([f])(d)\n        self.assertEqual(len(x), 1)\n        self.assertEqual(x[0, \"name\"], \"girl\")\n        self.assertTrue(np.all(x.metas == \"girl\"))\n\n        f.oper = f.NotEqual\n        x = filter.Values([f])(d)\n        self.assertEqual(len(x), len(d) - 1)\n        self.assertTrue(np.all(x[:, \"name\"] != \"girl\"))\n\n        f.oper = f.Less\n        x = filter.Values([f])(d)\n        self.assertEqual(len(x), sum(col < \"girl\"))\n        self.assertTrue(np.all(x.metas < \"girl\"))\n\n        f.oper = f.LessEqual\n        x = filter.Values([f])(d)\n        self.assertEqual(len(x), sum(col <= \"girl\"))\n        self.assertTrue(np.all(x.metas <= \"girl\"))\n\n        f.oper = f.Greater\n        x = filter.Values([f])(d)\n        self.assertEqual(len(x), sum(col > \"girl\"))\n        self.assertTrue(np.all(x.metas > \"girl\"))\n\n        f.oper = f.GreaterEqual\n        x = filter.Values([f])(d)\n        self.assertEqual(len(x), sum(col >= \"girl\"))\n        self.assertTrue(np.all(x.metas >= \"girl\"))\n\n        f.oper = f.Between\n        f.max = \"lion\"\n        x = filter.Values([f])(d)\n        self.assertEqual(len(x), sum((col >= \"girl\") * (col <= \"lion\")))\n        self.assertTrue(np.all(x.metas >= \"girl\"))\n        self.assertTrue(np.all(x.metas <= \"lion\"))\n\n        f.oper = f.Outside\n        x = filter.Values([f])(d)\n        self.assertEqual(len(x), sum(col < \"girl\") + sum(col > \"lion\"))\n        self.assertTrue(np.all((x.metas < \"girl\") + (x.metas > \"lion\")))\n\n        f.oper = f.Contains\n        f.ref = \"ea\"\n        x = filter.Values([f])(d)\n        for e in x:\n            self.assertTrue(\"ea\" in e[\"name\"])\n        self.assertEqual(len(x), len([e for e in col if \"ea\" in e]))\n\n        f.oper = f.StartsWith\n        f.ref = \"sea\"\n        x = filter.Values([f])(d)\n        for e in x:\n            self.assertTrue(str(e[\"name\"]).startswith(\"sea\"))\n        self.assertEqual(len(x), len([e for e in col if e.startswith(\"sea\")]))\n\n        f.oper = f.EndsWith\n        f.ref = \"ion\"\n        x = filter.Values([f])(d)\n        for e in x:\n            self.assertTrue(str(e[\"name\"]).endswith(\"ion\"))\n        self.assertEqual(len(x), len([e for e in col if e.endswith(\"ion\")]))\n\n    def test_valueFilter_string_case_insens(self):\n        d = data.Table(\"zoo\")\n        d[d[:, \"name\"].metas[:, 0] == \"girl\", \"name\"] = \"GIrl\"\n\n        col = d[:, \"name\"].metas[:, 0]\n\n        f = filter.FilterString(\"name\",\n                                filter.FilterString.Equal, \"giRL\")\n        f.case_sensitive = False\n        x = filter.Values([f])(d)\n        self.assertEqual(len(x), 1)\n        self.assertEqual(x[0, \"name\"], \"GIrl\")\n        self.assertTrue(np.all(x.metas == \"GIrl\"))\n\n        f.oper = f.NotEqual\n        x = filter.Values([f])(d)\n        self.assertEqual(len(x), len(d) - 1)\n        self.assertTrue(np.all(x[:, \"name\"] != \"GIrl\"))\n\n        f.oper = f.Less\n        f.ref = \"CHiCKEN\"\n        x = filter.Values([f])(d)\n        self.assertEqual(len(x), sum(col < \"chicken\") - 1)  # girl!\n        self.assertTrue(np.all(x.metas < \"chicken\"))\n\n        f.oper = f.LessEqual\n        x = filter.Values([f])(d)\n        self.assertEqual(len(x), sum(col <= \"chicken\") - 1)\n        self.assertTrue(np.all(x.metas <= \"chicken\"))\n\n        f.oper = f.Greater\n        x = filter.Values([f])(d)\n        self.assertEqual(len(x), sum(col > \"chicken\") + 1)\n        for e in x:\n            self.assertGreater(str(e[\"name\"]).lower(), \"chicken\")\n\n        f.oper = f.GreaterEqual\n        x = filter.Values([f])(d)\n        self.assertEqual(len(x), sum(col >= \"chicken\") + 1)\n        for e in x:\n            self.assertGreaterEqual(str(e[\"name\"]).lower(), \"chicken\")\n\n        f.oper = f.Between\n        f.max = \"liOn\"\n        x = filter.Values([f])(d)\n        self.assertEqual(len(x), sum((col >= \"chicken\") * (col <= \"lion\")) + 1)\n        for e in x:\n            self.assertTrue(\"chicken\" <= str(e[\"name\"]).lower() <= \"lion\")\n\n        f.oper = f.Outside\n        x = filter.Values([f])(d)\n        self.assertEqual(len(x), sum(col < \"chicken\") + sum(col > \"lion\") - 1)\n        self.assertTrue(np.all((x.metas < \"chicken\") + (x.metas > \"lion\")))\n\n        f.oper = f.Contains\n        f.ref = \"iR\"\n        x = filter.Values([f])(d)\n        for e in x:\n            self.assertTrue(\"ir\" in str(e[\"name\"]).lower())\n        self.assertEqual(len(x), len([e for e in col if \"ir\" in e]) + 1)\n\n        f.oper = f.StartsWith\n        f.ref = \"GI\"\n        x = filter.Values([f])(d)\n        for e in x:\n            self.assertTrue(str(e[\"name\"]).lower().startswith(\"gi\"))\n        self.assertEqual(len(x),\n                         len([e for e in col if e.lower().startswith(\"gi\")]))\n\n        f.oper = f.EndsWith\n        f.ref = \"ion\"\n        x = filter.Values([f])(d)\n        for e in x:\n            self.assertTrue(str(e[\"name\"]).endswith(\"ion\"))\n            self.assertTrue(str(e[\"name\"]).endswith(\"ion\"))\n        self.assertEqual(len(x), len([e for e in col if e.endswith(\"ion\")]))\n\n    def test_valueFilter_regex(self):\n        d = data.Table(\"zoo\")\n        f = filter.FilterRegex(d.domain['name'], '^c...$')\n        x = filter.Values([f])(d)\n        self.assertEqual(len(x), 7)\n\n    def test_valueFilter_stringList(self):\n        data = Table(\"zoo\")\n        var = data.domain[\"name\"]\n\n        fs = filter.FilterStringList\n        filters = [\n            (([\"swan\", \"tuna\", \"wasp\"], True), dict(rows=3)),\n            (([\"swan\", \"tuna\", \"wasp\"], False), dict(rows=3)),\n            (([\"WoRm\", \"TOad\", \"vOLe\"], True), dict(rows=0)),\n            (([\"WoRm\", \"TOad\", \"vOLe\"], False), dict(rows=3)),\n        ]\n\n        for args, expected in filters:\n            f = fs(var, *args)\n            filtered_data = filter.Values([f])(data)\n            self.assertEqual(len(filtered_data), expected[\"rows\"],\n                             \"{} returned wrong number of rows\".format(args))\n\n    def test_table_dtypes(self):\n        table = data.Table(\"iris\")\n        metas = np.hstack((table.metas, table.Y.reshape(len(table), 1)))\n        attributes_metas = table.domain.metas + table.domain.class_vars\n        domain_metas = data.Domain(table.domain.attributes,\n                                   table.domain.class_vars,\n                                   attributes_metas)\n        table_metas = data.Table(domain_metas, table.X, table.Y, metas)\n        new_table = data.Table(data.Domain(table_metas.domain.metas,\n                                           table_metas.domain.metas,\n                                           table_metas.domain.metas),\n                               table_metas)\n        self.assertEqual(new_table.X.dtype, np.float64)\n        self.assertEqual(new_table.Y.dtype, np.float64)\n        self.assertEqual(new_table.metas.dtype, np.float64)\n\n    def test_attributes(self):\n        table = data.Table(\"iris\")\n        table.attributes = {1: \"test\"}\n        table2 = table[:4]\n        self.assertEqual(table2.attributes[1], \"test\")\n        table2.attributes[1] = \"modified\"\n        self.assertEqual(table.attributes[1], \"modified\")\n\n    # TODO Test conjunctions and disjunctions of conditions\n\n    def test_is_sparse(self):\n        table = data.Table(\"iris\")\n        self.assertFalse(table.is_sparse())\n\n        table.X = sp.csr_matrix(table.X)\n        self.assertTrue(table.is_sparse())\n\n    def test_repr_sparse_with_one_row(self):\n        table = data.Table(\"iris\")[:1]\n        table.X = sp.csr_matrix(table.X)\n        repr(table)     # make sure repr does not crash\n\n    def test_inf(self):\n        a = np.array([[2,   0,      0,      0],\n                      [0,   np.nan, np.nan, 1],\n                      [0,   0,      np.inf, 0]])\n        with self.assertWarns(Warning):\n            tab = data.Table(a)\n        self.assertEqual(tab.get_nan_frequency_attribute(), 3/12)\n\n\ndef column_sizes(table):\n    return (len(table.domain.attributes),\n            len(table.domain.class_vars),\n            len(table.domain.metas))\n\n\nclass TableTests(unittest.TestCase):\n    attributes = [\"Feature %i\" % i for i in range(10)]\n    class_vars = [\"Class %i\" % i for i in range(1)]\n    metas = [\"Meta %i\" % i for i in range(5)]\n    nrows = 10\n    row_indices = (1, 5, 7, 9)\n\n    data = np.random.random((nrows, len(attributes)))\n    class_data = np.random.random((nrows, len(class_vars)))\n    meta_data = np.random.random((nrows, len(metas)))\n    weight_data = np.random.random((nrows, 1))\n\n    def setUp(self):\n        self.data = np.random.random((self.nrows, len(self.attributes)))\n        self.class_data = np.random.random((self.nrows, len(self.class_vars)))\n        if len(self.class_vars) == 1:\n            self.class_data = self.class_data.flatten()\n        self.meta_data = np.random.randint(0, 5, (self.nrows, len(self.metas))\n                                          ).astype(object)\n        self.weight_data = np.random.random((self.nrows, 1))\n\n    def mock_domain(self, with_classes=False, with_metas=False):\n        attributes = self.attributes\n        class_vars = self.class_vars if with_classes else []\n        metas = self.metas if with_metas else []\n        variables = attributes + class_vars\n        return MagicMock(data.Domain,\n                         attributes=attributes,\n                         class_vars=class_vars,\n                         metas=metas,\n                         variables=variables)\n\n    def create_domain(self, attributes=(), classes=(), metas=()):\n        attr_vars = [data.ContinuousVariable(name=a) if isinstance(a, str)\n                     else a for a in attributes]\n        class_vars = [data.ContinuousVariable(name=c) if isinstance(c, str)\n                      else c for c in classes]\n        meta_vars = [data.DiscreteVariable(name=m, values=map(str, range(5)))\n                     if isinstance(m, str) else m for m in metas]\n\n        domain = data.Domain(attr_vars, class_vars, meta_vars)\n        return domain\n\n\nclass CreateEmptyTable(TableTests):\n    def test_calling_new_with_no_parameters_constructs_a_new_instance(self):\n        table = data.Table()\n        self.assertIsInstance(table, data.Table)\n\n    def test_table_has_file(self):\n        table = data.Table()\n        self.assertIsNone(table.__file__)\n\n\nclass CreateTableWithFilename(TableTests):\n    filename = \"data.tab\"\n\n    @patch(\"os.path.exists\", Mock(return_value=True))\n    def test_read_data_calls_reader(self):\n        table_mock = Mock(data.Table)\n        reader_instance = Mock(read=Mock(return_value=table_mock))\n        reader_mock = Mock(return_value=reader_instance)\n\n        with patch.dict(data.io.FileFormat.readers,\n                        {'.xlsx': reader_mock}):\n            table = data.Table.from_file(\"test.xlsx\")\n\n        reader_mock.assert_called_with(\"test.xlsx\")\n        reader_instance.read.assert_called_with()\n        self.assertEqual(table, table_mock)\n\n    @patch(\"os.path.exists\", Mock(return_value=False))\n    def test_raises_error_if_file_does_not_exist(self):\n        with self.assertRaises(IOError):\n            data.Table.from_file(self.filename)\n\n    @patch(\"os.path.exists\", Mock(return_value=True))\n    def test_raises_error_if_file_has_unknown_extension(self):\n        with self.assertRaises(IOError):\n            data.Table.from_file(\"file.invalid_extension\")\n\n    @patch(\"Orange.data.table.Table.from_file\")\n    def test_calling_new_with_string_argument_calls_read_data(self, read_data):\n        data.Table(self.filename)\n\n        read_data.assert_called_with(self.filename)\n\n    @patch(\"Orange.data.table.Table.from_file\")\n    def test_calling_new_with_keyword_argument_filename_calls_read_data(\n            self, read_data):\n        data.Table(filename=self.filename)\n\n        read_data.assert_called_with(self.filename)\n\n\nclass CreateTableWithUrl(TableTests):\n    def test_url_no_scheme(self):\n\n        class SkipRest(Exception):\n            pass\n\n        mock_urlopen = Mock(side_effect=SkipRest())\n        url = 'www.foo.bar/xx.csv'\n\n        with patch('Orange.data.io.UrlReader.urlopen', mock_urlopen):\n            try:\n                Table.from_url(url)\n            except SkipRest:\n                pass\n\n        mock_urlopen.assert_called_once_with('http://' + url)\n\n    class _MockUrlOpen(MagicMock):\n        headers = {'content-disposition': 'attachment; filename=\"Something-FormResponses.tsv\"; '\n                                          'filename*=UTF-8''Something%20%28Responses%29.tsv'}\n        def __enter__(self):\n            return self\n\n        def __exit__(self, *args, **kwargs):\n            pass\n\n        def read(self):\n            return b'''\\\na\\tb\\tc\n1\\t2\\t3\n2\\t3\\t4'''\n\n    urlopen = _MockUrlOpen()\n\n    @patch('Orange.data.io.urlopen', urlopen)\n    def test_trimmed_urls(self):\n        for url in ('https://docs.google.com/spreadsheets/d/ABCD/edit',\n                    'https://www.dropbox.com/s/ABCD/filename.csv'):\n            self._MockUrlOpen.url = url\n            d = data.Table(url)\n            request = self.urlopen.call_args[0][0]\n            self.assertNotEqual(url, request.full_url)\n            self.assertIn('Mozilla/5.0', request.headers.get('User-agent', ''))\n            self.assertEqual(len(d), 2)\n            self.assertEqual(d.name, 'Something-FormResponses')\n\n\nclass CreateTableWithDomain(TableTests):\n    def test_creates_an_empty_table_with_given_domain(self):\n        domain = self.mock_domain()\n        table = data.Table.from_domain(domain)\n\n        self.assertEqual(table.domain, domain)\n\n    def test_creates_zero_filled_rows_in_X_if_domain_contains_attributes(self):\n        domain = self.mock_domain()\n        table = data.Table.from_domain(domain, self.nrows)\n\n        self.assertEqual(table.X.shape, (self.nrows, len(domain.attributes)))\n        self.assertFalse(table.X.any())\n\n    def test_creates_zero_filled_rows_in_Y_if_domain_contains_class_vars(self):\n        domain = self.mock_domain(with_classes=True)\n        table = data.Table.from_domain(domain, self.nrows)\n\n        if len(domain.class_vars) != 1:\n            self.assertEqual(table.Y.shape,\n                             (self.nrows, len(domain.class_vars)))\n        else:\n            self.assertEqual(table.Y.shape, (self.nrows,))\n        self.assertFalse(table.Y.any())\n\n    def test_creates_zero_filled_rows_in_metas_if_domain_contains_metas(self):\n        domain = self.mock_domain(with_metas=True)\n        table = data.Table.from_domain(domain, self.nrows)\n\n        self.assertEqual(table.metas.shape, (self.nrows, len(domain.metas)))\n        self.assertFalse(table.metas.any())\n\n    def test_creates_weights_if_weights_are_true(self):\n        domain = self.mock_domain()\n        table = data.Table.from_domain(domain, self.nrows, True)\n\n        self.assertEqual(table.W.shape, (self.nrows, ))\n\n    def test_does_not_create_weights_if_weights_are_false(self):\n        domain = self.mock_domain()\n        table = data.Table.from_domain(domain, self.nrows, False)\n\n        self.assertEqual(table.W.shape, (self.nrows, 0))\n\n    @patch(\"Orange.data.table.Table.from_domain\")\n    def test_calling_new_with_domain_calls_new_from_domain(\n            self, new_from_domain):\n        domain = self.mock_domain()\n        data.Table(domain)\n\n        new_from_domain.assert_called_with(domain)\n\n\nclass CreateTableWithData(TableTests):\n    def test_creates_a_table_with_given_X(self):\n        # from numpy\n        table = data.Table(np.array(self.data))\n        self.assertIsInstance(table.domain, data.Domain)\n        np.testing.assert_almost_equal(table.X, self.data)\n\n        # from list\n        table = data.Table(list(self.data))\n        self.assertIsInstance(table.domain, data.Domain)\n        np.testing.assert_almost_equal(table.X, self.data)\n\n        # from tuple\n        table = data.Table(tuple(self.data))\n        self.assertIsInstance(table.domain, data.Domain)\n        np.testing.assert_almost_equal(table.X, self.data)\n\n    def test_creates_a_table_from_domain_and_list(self):\n        domain = data.Domain([data.DiscreteVariable(name=\"a\", values=\"mf\"),\n                              data.ContinuousVariable(name=\"b\")],\n                             data.DiscreteVariable(name=\"y\", values=\"abc\"))\n        table = data.Table(domain, [[0, 1, 2],\n                                    [1, 2, \"?\"],\n                                    [\"m\", 3, \"a\"],\n                                    [\"?\", \"?\", \"c\"]])\n        self.assertIs(table.domain, domain)\n        np.testing.assert_almost_equal(\n            table.X, np.array([[0, 1], [1, 2], [0, 3], [np.nan, np.nan]]))\n        np.testing.assert_almost_equal(table.Y, np.array([2, np.nan, 0, 2]))\n\n    def test_creates_a_table_from_domain_and_list_and_weights(self):\n        domain = data.Domain([data.DiscreteVariable(name=\"a\", values=\"mf\"),\n                              data.ContinuousVariable(name=\"b\")],\n                             data.DiscreteVariable(name=\"y\", values=\"abc\"))\n        table = data.Table(domain, [[0, 1, 2],\n                                    [1, 2, \"?\"],\n                                    [\"m\", 3, \"a\"],\n                                    [\"?\", \"?\", \"c\"]], [1, 2, 3, 4])\n        self.assertIs(table.domain, domain)\n        np.testing.assert_almost_equal(\n            table.X, np.array([[0, 1], [1, 2], [0, 3], [np.nan, np.nan]]))\n        np.testing.assert_almost_equal(table.Y, np.array([2, np.nan, 0, 2]))\n        np.testing.assert_almost_equal(table.W, np.array([1, 2, 3, 4]))\n\n    def test_creates_a_table_from_domain_and_list_and_metas(self):\n        metas = [data.DiscreteVariable(\"Meta 1\", values=\"XYZ\"),\n                 data.ContinuousVariable(\"Meta 2\"),\n                 data.StringVariable(\"Meta 3\")]\n        domain = data.Domain([data.DiscreteVariable(name=\"a\", values=\"mf\"),\n                              data.ContinuousVariable(name=\"b\")],\n                             data.DiscreteVariable(name=\"y\", values=\"abc\"),\n                             metas=metas)\n        table = data.Table(domain, [[0, 1, 2, \"X\", 2, \"bb\"],\n                                    [1, 2, \"?\", \"Y\", 1, \"aa\"],\n                                    [\"m\", 3, \"a\", \"Z\", 3, \"bb\"],\n                                    [\"?\", \"?\", \"c\", \"X\", 1, \"aa\"]])\n        self.assertIs(table.domain, domain)\n        np.testing.assert_almost_equal(\n            table.X, np.array([[0, 1], [1, 2], [0, 3], [np.nan, np.nan]]))\n        np.testing.assert_almost_equal(table.Y, np.array([2, np.nan, 0, 2]))\n        np.testing.assert_array_equal(table.metas,\n                                      np.array([[0, 2., \"bb\"],\n                                                [1, 1., \"aa\"],\n                                                [2, 3., \"bb\"],\n                                                [0, 1., \"aa\"]],\n                                               dtype=object))\n\n    def test_creates_a_table_from_list_of_instances(self):\n        table = data.Table('iris')\n        new_table = data.Table(table.domain, [d for d in table])\n        self.assertIs(table.domain, new_table.domain)\n        np.testing.assert_almost_equal(table.X, new_table.X)\n        np.testing.assert_almost_equal(table.Y, new_table.Y)\n        np.testing.assert_almost_equal(table.W, new_table.W)\n        self.assertEqual(table.domain, new_table.domain)\n        np.testing.assert_array_equal(table.metas, new_table.metas)\n\n    def test_creates_a_table_from_list_of_instances_with_metas(self):\n        table = data.Table('zoo')\n        new_table = data.Table(table.domain, [d for d in table])\n        self.assertIs(table.domain, new_table.domain)\n        np.testing.assert_almost_equal(table.X, new_table.X)\n        np.testing.assert_almost_equal(table.Y, new_table.Y)\n        np.testing.assert_almost_equal(table.W, new_table.W)\n        self.assertEqual(table.domain, new_table.domain)\n        np.testing.assert_array_equal(table.metas, new_table.metas)\n\n    def test_creates_a_table_with_domain_and_given_X(self):\n        domain = self.mock_domain()\n\n        table = data.Table(domain, self.data)\n        self.assertIsInstance(table.domain, data.Domain)\n        self.assertEqual(table.domain, domain)\n        np.testing.assert_almost_equal(table.X, self.data)\n\n    def test_creates_a_table_with_given_X_and_Y(self):\n        table = data.Table(self.data, self.class_data)\n\n        self.assertIsInstance(table.domain, data.Domain)\n        np.testing.assert_almost_equal(table.X, self.data)\n        np.testing.assert_almost_equal(table.Y, self.class_data)\n\n    def test_creates_a_table_with_given_X_Y_and_metas(self):\n        table = data.Table(self.data, self.class_data, self.meta_data)\n\n        self.assertIsInstance(table.domain, data.Domain)\n        np.testing.assert_almost_equal(table.X, self.data)\n        np.testing.assert_almost_equal(table.Y, self.class_data)\n        np.testing.assert_almost_equal(table.metas, self.meta_data)\n\n    def test_creates_a_discrete_class_if_Y_has_few_distinct_values(self):\n        Y = np.array([float(np.random.randint(0, 2)) for i in self.data])\n        table = data.Table(self.data, Y, self.meta_data)\n\n        np.testing.assert_almost_equal(table.Y, Y)\n        self.assertIsInstance(table.domain.class_vars[0],\n                              data.DiscreteVariable)\n        self.assertEqual(table.domain.class_vars[0].values, [\"v1\", \"v2\"])\n\n    def test_creates_a_table_with_given_domain(self):\n        domain = self.mock_domain()\n        table = data.Table.from_numpy(domain, self.data)\n\n        self.assertEqual(table.domain, domain)\n\n    def test_sets_Y_if_given(self):\n        domain = self.mock_domain(with_classes=True)\n        table = data.Table.from_numpy(domain, self.data, self.class_data)\n\n        np.testing.assert_almost_equal(table.Y, self.class_data)\n\n    def test_sets_metas_if_given(self):\n        domain = self.mock_domain(with_metas=True)\n        table = data.Table.from_numpy(domain, self.data, metas=self.meta_data)\n\n        np.testing.assert_almost_equal(table.metas, self.meta_data)\n\n    def test_sets_weights_if_given(self):\n        domain = self.mock_domain()\n        table = data.Table.from_numpy(domain, self.data, W=self.weight_data)\n\n        np.testing.assert_equal(table.W.shape, (len(self.data), ))\n        np.testing.assert_almost_equal(table.W.flatten(),\n                                       self.weight_data.flatten())\n\n    def test_splits_X_and_Y_if_given_in_same_array(self):\n        joined_data = np.column_stack((self.data, self.class_data))\n        domain = self.mock_domain(with_classes=True)\n        table = data.Table.from_numpy(domain, joined_data)\n\n        np.testing.assert_almost_equal(table.X, self.data)\n        np.testing.assert_almost_equal(table.Y, self.class_data)\n\n    def test_initializes_Y_metas_and_W_if_not_given(self):\n        domain = self.mock_domain()\n        table = data.Table.from_numpy(domain, self.data)\n\n        self.assertEqual(table.Y.shape, (self.nrows, len(domain.class_vars)))\n        self.assertEqual(table.metas.shape, (self.nrows, len(domain.metas)))\n        self.assertEqual(table.W.shape, (self.nrows, 0))\n\n    def test_raises_error_if_columns_in_domain_and_data_do_not_match(self):\n        domain = self.mock_domain(with_classes=True, with_metas=True)\n        ones = np.zeros((self.nrows, 1))\n\n        with self.assertRaises(ValueError):\n            data_ = np.hstack((self.data, ones))\n            data.Table.from_numpy(domain, data_, self.class_data,\n                                  self.meta_data)\n\n        with self.assertRaises(ValueError):\n            classes_ = np.hstack((self.class_data, ones))\n            data.Table.from_numpy(domain, self.data, classes_,\n                                  self.meta_data)\n\n        with self.assertRaises(ValueError):\n            metas_ = np.hstack((self.meta_data, ones))\n            data.Table.from_numpy(domain, self.data, self.class_data,\n                                  metas_)\n\n    def test_raises_error_if_lengths_of_data_do_not_match(self):\n        domain = self.mock_domain(with_classes=True, with_metas=True)\n\n        with self.assertRaises(ValueError):\n            data_ = np.vstack((self.data, np.zeros((1, len(self.attributes)))))\n            data.Table(domain, data_, self.class_data, self.meta_data)\n\n        with self.assertRaises(ValueError):\n            class_data_ = np.vstack((self.class_data,\n                                     np.zeros((1, len(self.class_vars)))))\n            data.Table(domain, self.data, class_data_, self.meta_data)\n\n        with self.assertRaises(ValueError):\n            meta_data_ = np.vstack((self.meta_data,\n                                    np.zeros((1, len(self.metas)))))\n            data.Table(domain, self.data, self.class_data, meta_data_)\n\n    @patch(\"Orange.data.table.Table.from_numpy\")\n    def test_calling_new_with_domain_and_numpy_arrays_calls_new_from_numpy(\n            self, new_from_numpy):\n        domain = self.mock_domain()\n        data.Table(domain, self.data)\n        new_from_numpy.assert_called_with(domain, self.data)\n\n        domain = self.mock_domain(with_classes=True)\n        data.Table(domain, self.data, self.class_data)\n        new_from_numpy.assert_called_with(domain, self.data, self.class_data)\n\n        domain = self.mock_domain(with_classes=True, with_metas=True)\n        data.Table(domain, self.data, self.class_data, self.meta_data)\n        new_from_numpy.assert_called_with(\n            domain, self.data, self.class_data, self.meta_data)\n\n        data.Table(domain, self.data, self.class_data,\n                   self.meta_data, self.weight_data)\n        new_from_numpy.assert_called_with(domain, self.data, self.class_data,\n                                          self.meta_data, self.weight_data)\n\n    def test_from_numpy_reconstructable(self):\n        def assert_equal(T1, T2):\n            np.testing.assert_array_equal(T1.X, T2.X)\n            np.testing.assert_array_equal(T1.Y, T2.Y)\n            np.testing.assert_array_equal(T1.metas, T2.metas)\n            np.testing.assert_array_equal(T1.W, T2.W)\n\n        nullcol = np.empty((self.nrows, 0))\n        domain = self.create_domain(self.attributes)\n        table = data.Table(domain, self.data)\n\n        table_1 = data.Table.from_numpy(\n            domain, table.X, table.Y, table.metas, table.W)\n        assert_equal(table, table_1)\n\n        domain = self.create_domain(classes=self.class_vars)\n        table = data.Table(domain, nullcol, self.class_data)\n\n        table_1 = data.Table.from_numpy(\n            domain, table.X, table.Y, table.metas, table.W)\n        assert_equal(table, table_1)\n\n        domain = self.create_domain(metas=self.metas)\n        table = data.Table(domain, nullcol, nullcol, self.meta_data)\n\n        table_1 = data.Table.from_numpy(\n            domain, table.X, table.Y, table.metas, table.W)\n        assert_equal(table, table_1)\n\n\nclass CreateTableWithDomainAndTable(TableTests):\n    interesting_slices = [\n        slice(0, 0),  # [0:0] - empty slice\n        slice(1),  # [:1]  - only first element\n        slice(1, None),  # [1:]  - all but first\n        slice(-1, None),  # [-1:] - only last element\n        slice(-1),  # [:-1] - all but last\n        slice(None),  # [:]   - all elements\n        slice(None, None, 2),  # [::2] - even elements\n        slice(None, None, -1),  # [::-1]- all elements reversed\n    ]\n\n    row_indices = [1, 5, 6, 7]\n\n    def setUp(self):\n        self.domain = self.create_domain(\n            self.attributes, self.class_vars, self.metas)\n        self.table = data.Table(\n            self.domain, self.data, self.class_data, self.meta_data)\n\n    def test_creates_table_with_given_domain(self):\n        new_table = data.Table.from_table(self.table.domain, self.table)\n\n        self.assertIsInstance(new_table, data.Table)\n        self.assertIsNot(self.table, new_table)\n        self.assertEqual(new_table.domain, self.domain)\n\n    def test_transform(self):\n        class MyTableClass(data.Table):\n            pass\n\n        table = MyTableClass.from_table(self.table.domain, self.table)\n        domain = table.domain\n        attr = ContinuousVariable(\"x\")\n        new_domain = data.Domain(list(domain.attributes) + [attr], None)\n        new_table = table.transform(new_domain)\n\n        self.assertIsInstance(new_table, MyTableClass)\n        self.assertIsNot(table, new_table)\n        self.assertIs(new_table.domain, new_domain)\n\n    def test_transform_same_domain(self):\n        iris = data.Table(\"iris\")\n        new_domain = copy.copy(iris.domain)\n        new_data = iris.transform(new_domain)\n        self.assertIs(new_data.domain, new_domain)\n\n    def test_can_copy_table(self):\n        new_table = data.Table.from_table(self.domain, self.table)\n        self.assert_table_with_filter_matches(new_table, self.table)\n\n    def test_can_filter_rows_with_list(self):\n        for indices in ([0], [1, 5, 6, 7]):\n            new_table = data.Table.from_table(\n                self.domain, self.table, row_indices=indices)\n            self.assert_table_with_filter_matches(\n                new_table, self.table, rows=indices)\n\n    def test_can_filter_row_with_slice(self):\n        for slice_ in self.interesting_slices:\n            new_table = data.Table.from_table(\n                self.domain, self.table, row_indices=slice_)\n            self.assert_table_with_filter_matches(\n                new_table, self.table, rows=slice_)\n\n    def test_can_use_attributes_as_new_columns(self):\n        a, _, _ = column_sizes(self.table)\n        order = [random.randrange(a) for _ in self.domain.attributes]\n        new_attributes = [self.domain.attributes[i] for i in order]\n        new_domain = self.create_domain(\n            new_attributes, new_attributes, new_attributes)\n        new_table = data.Table.from_table(new_domain, self.table)\n\n        self.assert_table_with_filter_matches(\n            new_table, self.table, xcols=order, ycols=order, mcols=order)\n\n    def test_can_use_class_vars_as_new_columns(self):\n        a, c, _ = column_sizes(self.table)\n        order = [random.randrange(a, a + c) for _ in self.domain.class_vars]\n        new_classes = [self.domain.class_vars[i - a] for i in order]\n        new_domain = self.create_domain(new_classes, new_classes, new_classes)\n        new_table = data.Table.from_table(new_domain, self.table)\n\n        self.assert_table_with_filter_matches(\n            new_table, self.table, xcols=order, ycols=order, mcols=order)\n\n    def test_can_use_metas_as_new_columns(self):\n        _, _, m = column_sizes(self.table)\n        order = [random.randrange(-m + 1, 0) for _ in self.domain.metas]\n        new_metas = [self.domain.metas[::-1][i] for i in order]\n        new_domain = self.create_domain(new_metas, new_metas, new_metas)\n        new_table = data.Table.from_table(new_domain, self.table)\n\n        self.assert_table_with_filter_matches(\n            new_table, self.table, xcols=order, ycols=order, mcols=order)\n\n    def test_can_use_combination_of_all_as_new_columns(self):\n        a, c, m = column_sizes(self.table)\n        order = ([random.randrange(a) for _ in self.domain.attributes] +\n                 [random.randrange(a, a + c) for _ in self.domain.class_vars] +\n                 [random.randrange(-m + 1, 0) for _ in self.domain.metas])\n        random.shuffle(order)\n        vars = list(self.domain.variables) + list(self.domain.metas[::-1])\n        vars = [vars[i] for i in order]\n\n        new_domain = self.create_domain(vars, vars, vars)\n        new_table = data.Table.from_table(new_domain, self.table)\n        self.assert_table_with_filter_matches(\n            new_table, self.table, xcols=order, ycols=order, mcols=order)\n\n    def test_creates_table_with_given_domain_and_row_filter(self):\n        a, c, m = column_sizes(self.table)\n        order = ([random.randrange(a) for _ in self.domain.attributes] +\n                 [random.randrange(a, a + c) for _ in self.domain.class_vars] +\n                 [random.randrange(-m + 1, 0) for _ in self.domain.metas])\n        random.shuffle(order)\n        vars = list(self.domain.variables) + list(self.domain.metas[::-1])\n        vars = [vars[i] for i in order]\n\n        new_domain = self.create_domain(vars, vars, vars)\n        new_table = data.Table.from_table(new_domain, self.table, [0])\n        self.assert_table_with_filter_matches(\n            new_table, self.table[:1], xcols=order, ycols=order, mcols=order)\n\n        new_table = data.Table.from_table(new_domain, self.table, [2, 1, 0])\n        self.assert_table_with_filter_matches(\n            new_table, self.table[2::-1], xcols=order, ycols=order, mcols=order)\n\n        new_table = data.Table.from_table(new_domain, self.table, [])\n        self.assert_table_with_filter_matches(\n            new_table, self.table[:0], xcols=order, ycols=order, mcols=order)\n\n    def test_from_table_sparse_move_some_to_empty_metas(self):\n        iris = data.Table(\"iris\").to_sparse()\n        new_domain = data.domain.Domain(\n            iris.domain.attributes[:2], iris.domain.class_vars,\n            iris.domain.attributes[2:], source=iris.domain)\n        new_iris = iris.transform(new_domain)\n\n        self.assertTrue(sp.issparse(new_iris.X))\n        self.assertTrue(sp.issparse(new_iris.metas))\n        self.assertEqual(new_iris.X.shape, (len(iris), 2))\n        self.assertEqual(new_iris.metas.shape, (len(iris), 2))\n\n        # move back\n        back_iris = new_iris.transform(iris.domain)\n        self.assertEqual(back_iris.domain, iris.domain)\n        self.assertTrue(sp.issparse(back_iris.X))\n        self.assertFalse(sp.issparse(back_iris.metas))\n        self.assertEqual(back_iris.X.shape, iris.X.shape)\n        self.assertEqual(back_iris.metas.shape, iris.metas.shape)\n\n    def test_from_table_sparse_move_all_to_empty_metas(self):\n        iris = data.Table(\"iris\").to_sparse()\n        new_domain = data.domain.Domain(\n            [], iris.domain.class_vars, iris.domain.attributes,\n            source=iris.domain)\n        new_iris = iris.transform(new_domain)\n\n        self.assertFalse(sp.issparse(new_iris.X))\n        self.assertTrue(sp.issparse(new_iris.metas))\n        self.assertEqual(new_iris.X.shape, (len(iris), 0))\n        self.assertEqual(new_iris.metas.shape, (len(iris), 4))\n\n        # move back\n        back_iris = new_iris.transform(iris.domain)\n        self.assertEqual(back_iris.domain, iris.domain)\n        self.assertTrue(sp.issparse(back_iris.X))\n        self.assertFalse(sp.issparse(back_iris.metas))\n        self.assertEqual(back_iris.X.shape, iris.X.shape)\n        self.assertEqual(back_iris.metas.shape, iris.metas.shape)\n\n    def test_from_table_sparse_move_to_nonempty_metas(self):\n        brown = data.Table(\"brown-selected\").to_sparse()\n        n_attr = len(brown.domain.attributes)\n        n_metas = len(brown.domain.metas)\n        new_domain = data.domain.Domain(\n            brown.domain.attributes[:-10],\n            brown.domain.class_vars,\n            brown.domain.attributes[-10:] + brown.domain.metas,\n            source=brown.domain)\n        new_brown = data.Table.from_table(new_domain, brown)\n\n        self.assertTrue(sp.issparse(new_brown.X))\n        self.assertFalse(sp.issparse(new_brown.metas))\n        self.assertEqual(new_brown.X.shape, (len(new_brown), n_attr-10))\n        self.assertEqual(new_brown.metas.shape, (len(new_brown), n_metas+10))\n\n        # move back\n        back_brown = data.Table.from_table(brown.domain, new_brown)\n        self.assertEqual(brown.domain, back_brown.domain)\n        self.assertTrue(sp.issparse(back_brown.X))\n        self.assertFalse(sp.issparse(back_brown.metas))\n        self.assertEqual(back_brown.X.shape, brown.X.shape)\n        self.assertEqual(back_brown.metas.shape, brown.metas.shape)\n\n    def assert_table_with_filter_matches(\n            self, new_table, old_table,\n            rows=..., xcols=..., ycols=..., mcols=...):\n        a, c, m = column_sizes(old_table)\n        xcols = slice(a) if xcols is Ellipsis else xcols\n        ycols = slice(a, a + c) if ycols is Ellipsis else ycols\n        mcols = slice(None, -m - 1, -1) if mcols is Ellipsis else mcols\n\n        # Indexing used by convert_domain uses positive indices for variables\n        # and classes (classes come after attributes) and negative indices for\n        # meta features. This is equivalent to ordinary indexing in a magic\n        # table below.\n        magic = np.hstack((old_table.X, old_table.Y[:, None],\n                           old_table.metas[:, ::-1]))\n        np.testing.assert_almost_equal(new_table.X, magic[rows, xcols])\n        Y = magic[rows, ycols]\n        if Y.shape[1] == 1:\n            Y = Y.flatten()\n        np.testing.assert_almost_equal(new_table.Y, Y)\n        np.testing.assert_almost_equal(new_table.metas, magic[rows, mcols])\n        np.testing.assert_almost_equal(new_table.W, old_table.W[rows])\n\n\ndef isspecial(s):\n    return isinstance(s, slice) or s is Ellipsis\n\n\ndef split_columns(indices, t):\n    a, c, m = column_sizes(t)\n    if indices is ...:\n        return slice(a), slice(c), slice(m)\n    elif isinstance(indices, slice):\n        return indices, slice(0, 0), slice(0, 0)\n    elif not isinstance(indices, list) and not isinstance(indices, tuple):\n        indices = [indices]\n    return (\n        [t.domain.index(x)\n         for x in indices if 0 <= t.domain.index(x) < a] or slice(0, 0),\n        [t.domain.index(x) - a\n         for x in indices if t.domain.index(x) >= a] or slice(0, 0),\n        [-t.domain.index(x) - 1\n         for x in indices if t.domain.index(x) < 0] or slice(0, 0))\n\n\ndef getname(variable):\n    return variable.name\n\n\nclass TableIndexingTests(TableTests):\n    def setUp(self):\n        super().setUp()\n        d = self.domain = \\\n            self.create_domain(self.attributes, self.class_vars, self.metas)\n        t = self.table = \\\n            data.Table(self.domain, self.data, self.class_data, self.meta_data)\n        self.magic_table = \\\n            np.column_stack((self.table.X, self.table.Y,\n                             self.table.metas[:, ::-1]))\n\n        self.rows = [0, -1]\n        self.multiple_rows = [slice(0, 0), ..., slice(1, -1, -1)]\n        a, c, m = column_sizes(t)\n        columns = [0, a - 1, a, a + c - 1, -1, -m]\n        self.columns = chain(columns,\n                             map(lambda x: d[x], columns),\n                             map(lambda x: d[x].name, columns))\n        self.multiple_columns = chain(\n            self.multiple_rows,\n            [d.attributes, d.class_vars, d.metas, [0, a, -1]],\n            [self.attributes, self.class_vars, self.metas],\n            [self.attributes + self.class_vars + self.metas])\n\n        # TODO: indexing with [[0,1], [0,1]] produces weird results\n        # TODO: what should be the results of table[1, :]\n\n    def test_can_select_a_single_value(self):\n        for r in self.rows:\n            for c in self.columns:\n                value = self.table[r, c]\n                self.assertAlmostEqual(\n                    value, self.magic_table[r, self.domain.index(c)])\n\n                value = self.table[r][c]\n                self.assertAlmostEqual(\n                    value, self.magic_table[r, self.domain.index(c)])\n\n    def test_can_select_a_single_row(self):\n        for r in self.rows:\n            row = self.table[r]\n            new_row = np.hstack(\n                (self.data[r, :],\n                 self.class_data[r, None]))\n            np.testing.assert_almost_equal(\n                np.array(list(row)), new_row)\n\n\n    def test_can_select_a_subset_of_rows_and_columns(self):\n        for r in self.rows:\n            for c in self.multiple_columns:\n                table = self.table[r, c]\n\n                attr, cls, metas = split_columns(c, self.table)\n                X = self.table.X[[r], attr]\n                if X.ndim == 1:\n                    X = X.reshape(-1, len(table.domain.attributes))\n                np.testing.assert_almost_equal(table.X, X)\n                Y = self.table.Y[:, None][[r], cls]\n                if len(Y.shape) == 1 or Y.shape[1] == 1:\n                    Y = Y.flatten()\n                np.testing.assert_almost_equal(table.Y, Y)\n                metas_ = self.table.metas[[r], metas]\n                if metas_.ndim == 1:\n                    metas_ = metas_.reshape(-1, len(table.domain.metas))\n                np.testing.assert_almost_equal(table.metas, metas_)\n\n        for r in self.multiple_rows:\n            for c in chain(self.columns, self.multiple_rows):\n                table = self.table[r, c]\n\n                attr, cls, metas = split_columns(c, self.table)\n                np.testing.assert_almost_equal(table.X, self.table.X[r, attr])\n                Y = self.table.Y[:, None][r, cls]\n                if len(Y.shape) > 1 and Y.shape[1] == 1:\n                    Y = Y.flatten()\n                np.testing.assert_almost_equal(table.Y, Y)\n                np.testing.assert_almost_equal(table.metas,\n                                               self.table.metas[r, metas])\n\n\n    def test_optimize_indices(self):\n        # ordinary conversion\n        self.assertEqual(_optimize_indices([1, 2, 3], 4), slice(1, 4, 1))\n        self.assertEqual(_optimize_indices([], 1), [])\n        self.assertEqual(_optimize_indices([0, 2], 3), slice(0, 4, 2))\n\n        # not slices\n        np.testing.assert_equal(_optimize_indices([1, 2, 4], 5), [1, 2, 4])\n        np.testing.assert_equal(_optimize_indices((1, 2, 4), 5), [1, 2, 4])\n\n        # leave boolean arrays\n        np.testing.assert_equal(_optimize_indices([True, False, True], 3), [True, False, True])\n\n        # do not convert if step is negative\n        np.testing.assert_equal(_optimize_indices([4, 2, 0], 5), [4, 2, 0])\n\n        # try range\n        np.testing.assert_equal(_optimize_indices([3, 4, 5], 5), [3, 4, 5])  # out of range\n        self.assertEqual(_optimize_indices((3, 4, 5), 6), slice(3, 6, 1))\n\n        # negative elements\n        np.testing.assert_equal(_optimize_indices([-1, 0, 1], 5), [-1, 0, 1])\n\n        # single element\n        self.assertEqual(_optimize_indices([1], 2), slice(1, 2, 1))\n        np.testing.assert_equal(_optimize_indices([1], 1), [1])\n\n\nclass TableElementAssignmentTest(TableTests):\n    def setUp(self):\n        super().setUp()\n        self.domain = \\\n            self.create_domain(self.attributes, self.class_vars, self.metas)\n        self.table = \\\n            data.Table(self.domain, self.data, self.class_data, self.meta_data)\n\n    def test_can_assign_values(self):\n        self.table[0, 0] = 42.\n        self.assertAlmostEqual(self.table.X[0, 0], 42.)\n\n    def test_can_assign_values_to_classes(self):\n        a, _, _ = column_sizes(self.table)\n        self.table[0, a] = 42.\n        self.assertAlmostEqual(self.table.Y[0], 42.)\n\n    def test_can_assign_values_to_metas(self):\n        self.table[0, -1] = 42.\n        self.assertAlmostEqual(self.table.metas[0, 0], 42.)\n\n    def test_can_assign_rows_to_rows(self):\n        self.table[0] = self.table[1]\n        np.testing.assert_almost_equal(\n            self.table.X[0], self.table.X[1])\n        np.testing.assert_almost_equal(\n            self.table.Y[0], self.table.Y[1])\n        np.testing.assert_almost_equal(\n            self.table.metas[0], self.table.metas[1])\n\n    def test_can_assign_lists(self):\n        a, _, _ = column_sizes(self.table)\n        new_example = [float(i)\n                       for i in range(len(self.attributes + self.class_vars))]\n        self.table[0] = new_example\n        np.testing.assert_almost_equal(\n            self.table.X[0], np.array(new_example[:a]))\n        np.testing.assert_almost_equal(\n            self.table.Y[0], np.array(new_example[a:]))\n\n    def test_can_assign_np_array(self):\n        a, _, _ = column_sizes(self.table)\n        new_example = \\\n            np.array([float(i)\n                      for i in range(len(self.attributes + self.class_vars))])\n        self.table[0] = new_example\n        np.testing.assert_almost_equal(self.table.X[0], new_example[:a])\n        np.testing.assert_almost_equal(self.table.Y[0], new_example[a:])\n\n\nclass InterfaceTest(unittest.TestCase):\n    \"\"\"Basic tests each implementation of Table should pass.\"\"\"\n\n    features = (\n        data.ContinuousVariable(name=\"Continuous Feature 1\"),\n        data.ContinuousVariable(name=\"Continuous Feature 2\"),\n        data.DiscreteVariable(name=\"Discrete Feature 1\", values=[\"0\", \"1\"]),\n        data.DiscreteVariable(name=\"Discrete Feature 2\",\n                              values=[\"value1\", \"value2\"]),\n    )\n\n    class_vars = (\n        data.ContinuousVariable(name=\"Continuous Class\"),\n        data.DiscreteVariable(name=\"Discrete Class\", values=[\"m\", \"f\"])\n    )\n\n    feature_data = (\n        (1, 0, 0, 0),\n        (0, 1, 0, 0),\n        (0, 0, 1, 0),\n        (0, 0, 0, 1),\n    )\n\n    class_data = (\n        (1, 0),\n        (0, 1),\n        (1, 0),\n        (0, 1)\n    )\n\n    data = tuple(a + c for a, c in zip(feature_data, class_data))\n\n    nrows = 4\n\n    def setUp(self):\n        self.domain = data.Domain(attributes=self.features,\n                                  class_vars=self.class_vars)\n        self.table = data.Table.from_numpy(\n            self.domain,\n            np.array(self.feature_data),\n            np.array(self.class_data),\n        )\n\n    def test_len(self):\n        self.assertEqual(len(self.table), self.nrows)\n\n    def test_row_len(self):\n        for i in range(self.nrows):\n            self.assertEqual(len(self.table[i]), len(self.data[i]))\n\n    def test_iteration(self):\n        for row, expected_data in zip(self.table, self.data):\n            self.assertEqual(tuple(row), expected_data)\n\n    def test_row_indexing(self):\n        for i in range(self.nrows):\n            self.assertEqual(tuple(self.table[i]), self.data[i])\n\n    def test_row_slicing(self):\n        t = self.table[1:]\n        self.assertEqual(len(t), self.nrows - 1)\n\n    def test_value_indexing(self):\n        for i in range(self.nrows):\n            for j in range(len(self.table[i])):\n                self.assertEqual(self.table[i, j], self.data[i][j])\n\n    def test_row_assignment(self):\n        new_value = 2.\n        for i in range(self.nrows):\n            new_row = [new_value] * len(self.data[i])\n            self.table[i] = np.array(new_row)\n            self.assertEqual(list(self.table[i]), new_row)\n\n    def test_value_assignment(self):\n        new_value = 0.\n        for i in range(self.nrows):\n            for j in range(len(self.table[i])):\n                self.table[i, j] = new_value\n                self.assertEqual(self.table[i, j], new_value)\n\n    @skip_deprecated_length\n    def test_append_rows(self):\n        new_value = 2\n        new_row = [new_value] * len(self.data[0])\n        self.table.append(new_row)\n        self.assertEqual(list(self.table[-1]), new_row)\n\n    @skip_deprecated_length\n    def test_insert_rows(self):\n        new_value = 2\n        new_row = [new_value] * len(self.data[0])\n        self.table.insert(0, new_row)\n        self.assertEqual(list(self.table[0]), new_row)\n        for row, expected in zip(self.table[1:], self.data):\n            self.assertEqual(tuple(row), expected)\n\n    @skip_deprecated_length\n    def test_insert_view(self):\n        new_row = [1] * len(self.data[0])\n        tab = self.table[:2]\n        self.assertFalse(tab.is_copy())\n        tab.insert(0, new_row)\n        tab = data.Table.from_numpy(self.table.domain, self.table)\n        self.assertFalse(tab.X.flags.c_contiguous)\n        tab.insert(0, new_row)\n\n    @skip_deprecated_length\n    def test_delete_rows(self):\n        for i in range(self.nrows):\n            del self.table[0]\n            for j in range(len(self.table)):\n                self.assertEqual(tuple(self.table[j]), self.data[i + j + 1])\n\n    @skip_deprecated_length\n    def test_clear(self):\n        self.table.clear()\n        self.assertEqual(len(self.table), 0)\n        for _ in self.table:\n            self.fail(\"Table should not contain any rows.\")\n\n    def test_subclasses(self):\n        from pathlib import Path\n\n        class _ExtendedTable(data.Table):\n            pass\n\n        data_file = _ExtendedTable('iris')\n        data_url = _ExtendedTable.from_url(\n            Path(os.path.dirname(__file__), 'test1.tab').as_uri())\n\n        self.assertIsInstance(data_file, _ExtendedTable)\n        self.assertIsInstance(data_url, _ExtendedTable)\n\n\nclass TestTableStats(TableTests):\n    def test_get_nan_frequency(self):\n        domain = self.create_domain(self.attributes, self.class_vars)\n        table = data.Table(domain, self.data, self.class_data)\n        self.assertEqual(table.get_nan_frequency_attribute(), 0)\n        self.assertEqual(table.get_nan_frequency_class(), 0)\n\n        table.X[1, 2] = table.X[4, 5] = np.nan\n        self.assertEqual(table.get_nan_frequency_attribute(), 2 / table.X.size)\n        self.assertEqual(table.get_nan_frequency_class(), 0)\n\n        table.Y[3:6] = np.nan\n        self.assertEqual(table.get_nan_frequency_attribute(), 2 / table.X.size)\n        self.assertEqual(table.get_nan_frequency_class(), 3 / table.Y.size)\n\n        table.X[1, 2] = table.X[4, 5] = 0\n        self.assertEqual(table.get_nan_frequency_attribute(), 0)\n        self.assertEqual(table.get_nan_frequency_class(), 3 / table.Y.size)\n\n    def test_get_nan_frequency_empty_table(self):\n        domain = self.create_domain(self.attributes, self.class_vars)\n        table = data.Table(domain)\n        self.assertEqual(table.get_nan_frequency_attribute(), 0)\n        self.assertEqual(table.get_nan_frequency_class(), 0)\n\n\nclass TestRowInstance(unittest.TestCase):\n    def test_assignment(self):\n        table = data.Table(\"zoo\")\n        inst = table[2]\n        self.assertIsInstance(inst, data.RowInstance)\n\n        inst[1] = 0\n        self.assertEqual(table[2, 1], 0)\n        inst[1] = 1\n        self.assertEqual(table[2, 1], 1)\n\n        inst.set_class(\"mammal\")\n        self.assertEqual(table[2, len(table.domain.attributes)], \"mammal\")\n        inst.set_class(\"fish\")\n        self.assertEqual(table[2, len(table.domain.attributes)], \"fish\")\n\n        inst[-1] = \"Foo\"\n        self.assertEqual(table[2, -1], \"Foo\")\n\n    def test_iteration_with_assignment(self):\n        table = data.Table(\"iris\")\n        for i, row in enumerate(table):\n            row[0] = i\n        np.testing.assert_array_equal(table.X[:, 0], np.arange(len(table)))\n\n    def test_sparse_assignment(self):\n        X = np.eye(4)\n        Y = X[2]\n        table = data.Table(X, Y)\n        row = table[1]\n        self.assertFalse(sp.issparse(row.sparse_x))\n        self.assertEqual(row[0], 0)\n        self.assertEqual(row[1], 1)\n\n        table.X = sp.csr_matrix(table.X)\n        table._Y = sp.csr_matrix(table._Y)\n        sparse_row = table[1]\n        self.assertTrue(sp.issparse(sparse_row.sparse_x))\n        self.assertEqual(sparse_row[0], 0)\n        self.assertEqual(sparse_row[1], 1)\n        sparse_row[1] = 0\n        self.assertEqual(sparse_row[1], 0)\n        self.assertEqual(table.X[1, 1], 0)\n        self.assertEqual(table[2][4], 1)\n        table[2][4] = 0\n        self.assertEqual(table[2][4], 0)\n\n\nclass TestTableTranspose(unittest.TestCase):\n    def test_transpose_no_class(self):\n        attrs = [ContinuousVariable(\"c1\"), ContinuousVariable(\"c2\")]\n        data = Table(Domain(attrs), np.arange(8).reshape((4, 2)))\n\n        att = [ContinuousVariable(\"Feature 1\"), ContinuousVariable(\"Feature 2\"),\n               ContinuousVariable(\"Feature 3\"), ContinuousVariable(\"Feature 4\")]\n        domain = Domain(att, metas=[StringVariable(\"Feature name\")])\n        result = Table(domain, np.arange(8).reshape((4, 2)).T,\n                       metas=np.array([\"c1\", \"c2\"])[:, None])\n\n        # transpose and compare\n        self._compare_tables(result, Table.transpose(data))\n\n        # transpose of transpose is original\n        t = Table.transpose(Table.transpose(data), \"Feature name\")\n        self._compare_tables(data, t)\n\n        # original should not change\n        self.assertDictEqual(data.domain.attributes[0].attributes, {})\n\n    def test_transpose_discrete_class(self):\n        attrs = [ContinuousVariable(\"c1\"), ContinuousVariable(\"c2\")]\n        domain = Domain(attrs, [DiscreteVariable(\"cls\", values=[\"a\", \"b\"])])\n        data = Table(domain, np.arange(8).reshape((4, 2)),\n                     np.array([1, 1, 0, 0]))\n\n        att = [ContinuousVariable(\"Feature 1\"), ContinuousVariable(\"Feature 2\"),\n               ContinuousVariable(\"Feature 3\"), ContinuousVariable(\"Feature 4\")]\n        att[0].attributes = {\"cls\": \"b\"}\n        att[1].attributes = {\"cls\": \"b\"}\n        att[2].attributes = {\"cls\": \"a\"}\n        att[3].attributes = {\"cls\": \"a\"}\n        domain = Domain(att, metas=[StringVariable(\"Feature name\")])\n        result = Table(domain, np.arange(8).reshape((4, 2)).T,\n                       metas=np.array([\"c1\", \"c2\"])[:, None])\n\n        # transpose and compare\n        self._compare_tables(result, Table.transpose(data))\n\n        # transpose of transpose is original\n        t = Table.transpose(Table.transpose(data), \"Feature name\")\n        self._compare_tables(data, t)\n\n        # original should not change\n        self.assertDictEqual(data.domain.attributes[0].attributes, {})\n\n    def test_transpose_continuous_class(self):\n        attrs = [ContinuousVariable(\"c1\"), ContinuousVariable(\"c2\")]\n        domain = Domain(attrs, [ContinuousVariable(\"cls\")])\n        data = Table(domain, np.arange(8).reshape((4, 2)), np.arange(4, 0, -1))\n\n        att = [ContinuousVariable(\"Feature 1\"), ContinuousVariable(\"Feature 2\"),\n               ContinuousVariable(\"Feature 3\"), ContinuousVariable(\"Feature 4\")]\n        att[0].attributes = {\"cls\": \"4\"}\n        att[1].attributes = {\"cls\": \"3\"}\n        att[2].attributes = {\"cls\": \"2\"}\n        att[3].attributes = {\"cls\": \"1\"}\n        domain = Domain(att, metas=[StringVariable(\"Feature name\")])\n        result = Table(domain, np.arange(8).reshape((4, 2)).T,\n                       metas=np.array([\"c1\", \"c2\"])[:, None])\n\n        # transpose and compare\n        self._compare_tables(result, Table.transpose(data))\n\n        # transpose of transpose\n        t = Table.transpose(Table.transpose(data), \"Feature name\")\n        self._compare_tables(data, t)\n\n        # original should not change\n        self.assertDictEqual(data.domain.attributes[0].attributes, {})\n\n    def test_transpose_missing_class(self):\n        attrs = [ContinuousVariable(\"c1\"), ContinuousVariable(\"c2\")]\n        domain = Domain(attrs, [ContinuousVariable(\"cls\")])\n        data = Table(domain, np.arange(8).reshape((4, 2)),\n                     np.array([np.nan, 3, 2, 1]))\n\n        att = [ContinuousVariable(\"Feature 1\"), ContinuousVariable(\"Feature 2\"),\n               ContinuousVariable(\"Feature 3\"), ContinuousVariable(\"Feature 4\")]\n        att[1].attributes = {\"cls\": \"3\"}\n        att[2].attributes = {\"cls\": \"2\"}\n        att[3].attributes = {\"cls\": \"1\"}\n        domain = Domain(att, metas=[StringVariable(\"Feature name\")])\n        result = Table(domain, np.arange(8).reshape((4, 2)).T,\n                       metas=np.array([\"c1\", \"c2\"])[:, None])\n\n        # transpose and compare\n        self._compare_tables(result, Table.transpose(data))\n\n        # transpose of transpose\n        t = Table.transpose(Table.transpose(data), \"Feature name\")\n        self._compare_tables(data, t)\n\n        # original should not change\n        self.assertDictEqual(data.domain.attributes[0].attributes, {})\n\n    def test_transpose_multiple_class(self):\n        attrs = [ContinuousVariable(\"c1\"), ContinuousVariable(\"c2\")]\n        class_vars = [ContinuousVariable(\"cls1\"), ContinuousVariable(\"cls2\")]\n        domain = Domain(attrs, class_vars)\n        data = Table(domain, np.arange(8).reshape((4, 2)),\n                     np.arange(8).reshape((4, 2)))\n\n        att = [ContinuousVariable(\"Feature 1\"), ContinuousVariable(\"Feature 2\"),\n               ContinuousVariable(\"Feature 3\"), ContinuousVariable(\"Feature 4\")]\n        att[0].attributes = {\"cls1\": \"0\", \"cls2\": \"1\"}\n        att[1].attributes = {\"cls1\": \"2\", \"cls2\": \"3\"}\n        att[2].attributes = {\"cls1\": \"4\", \"cls2\": \"5\"}\n        att[3].attributes = {\"cls1\": \"6\", \"cls2\": \"7\"}\n        domain = Domain(att, metas=[StringVariable(\"Feature name\")])\n        result = Table(domain, np.arange(8).reshape((4, 2)).T,\n                       metas=np.array([\"c1\", \"c2\"])[:, None])\n\n        # transpose and compare\n        self._compare_tables(result, Table.transpose(data))\n\n        # transpose of transpose\n        t = Table.transpose(Table.transpose(data), \"Feature name\")\n        self._compare_tables(data, t)\n\n        # original should not change\n        self.assertDictEqual(data.domain.attributes[0].attributes, {})\n\n    def test_transpose_metas(self):\n        attrs = [ContinuousVariable(\"c1\"), ContinuousVariable(\"c2\")]\n        metas = [StringVariable(\"m1\")]\n        domain = Domain(attrs, metas=metas)\n        X = np.arange(8).reshape((4, 2))\n        M = np.array([\"aa\", \"bb\", \"cc\", \"dd\"])[:, None]\n        data = Table(domain, X, metas=M)\n\n        att = [ContinuousVariable(\"Feature 1\"), ContinuousVariable(\"Feature 2\"),\n               ContinuousVariable(\"Feature 3\"), ContinuousVariable(\"Feature 4\")]\n        att[0].attributes = {\"m1\": \"aa\"}\n        att[1].attributes = {\"m1\": \"bb\"}\n        att[2].attributes = {\"m1\": \"cc\"}\n        att[3].attributes = {\"m1\": \"dd\"}\n        domain = Domain(att, metas=[StringVariable(\"Feature name\")])\n        result = Table(domain, np.arange(8).reshape((4, 2)).T,\n                       metas=np.array([\"c1\", \"c2\"])[:, None])\n\n        # transpose and compare\n        self._compare_tables(result, Table.transpose(data))\n\n        # transpose of transpose\n        t = Table.transpose(Table.transpose(data), \"Feature name\")\n        self._compare_tables(data, t)\n\n        # original should not change\n        self.assertDictEqual(data.domain.attributes[0].attributes, {})\n\n    def test_transpose_discrete_metas(self):\n        attrs = [ContinuousVariable(\"c1\"), ContinuousVariable(\"c2\")]\n        metas = [DiscreteVariable(\"m1\", values=[\"aa\", \"bb\"])]\n        domain = Domain(attrs, metas=metas)\n        X = np.arange(8).reshape((4, 2))\n        M = np.array([0, 1, 0, 1])[:, None]\n        data = Table(domain, X, metas=M)\n\n        att = [ContinuousVariable(\"Feature 1\"), ContinuousVariable(\"Feature 2\"),\n               ContinuousVariable(\"Feature 3\"), ContinuousVariable(\"Feature 4\")]\n        att[0].attributes = {\"m1\": \"aa\"}\n        att[1].attributes = {\"m1\": \"bb\"}\n        att[2].attributes = {\"m1\": \"aa\"}\n        att[3].attributes = {\"m1\": \"bb\"}\n        domain = Domain(att, metas=[StringVariable(\"Feature name\")])\n        result = Table(domain, np.arange(8).reshape((4, 2)).T,\n                       metas=np.array([\"c1\", \"c2\"])[:, None])\n\n        # transpose and compare\n        self._compare_tables(result, Table.transpose(data))\n\n        # transpose of transpose is original\n        t = Table.transpose(Table.transpose(data), \"Feature name\")\n        self._compare_tables(data, t)\n\n        # original should not change\n        self.assertDictEqual(data.domain.attributes[0].attributes, {})\n\n    def test_transpose_continuous_metas(self):\n        attrs = [ContinuousVariable(\"c1\"), ContinuousVariable(\"c2\")]\n        metas = [ContinuousVariable(\"m1\")]\n        domain = Domain(attrs, metas=metas)\n        X = np.arange(8).reshape((4, 2))\n        M = np.array([0.0, 1.0, 0.0, 1.0])[:, None]\n        data = Table(domain, X, metas=M)\n\n        att = [ContinuousVariable(\"Feature 1\"), ContinuousVariable(\"Feature 2\"),\n               ContinuousVariable(\"Feature 3\"), ContinuousVariable(\"Feature 4\")]\n        att[0].attributes = {\"m1\": \"0\"}\n        att[1].attributes = {\"m1\": \"1\"}\n        att[2].attributes = {\"m1\": \"0\"}\n        att[3].attributes = {\"m1\": \"1\"}\n        domain = Domain(att, metas=[StringVariable(\"Feature name\")])\n        result = Table(domain, np.arange(8).reshape((4, 2)).T,\n                       metas=np.array([\"c1\", \"c2\"])[:, None])\n\n        # transpose and compare\n        self._compare_tables(result, Table.transpose(data))\n\n        # transpose of transpose is original\n        t = Table.transpose(Table.transpose(data), \"Feature name\")\n        self._compare_tables(data, t)\n\n        # original should not change\n        self.assertDictEqual(data.domain.attributes[0].attributes, {})\n\n    def test_transpose_missing_metas(self):\n        attrs = [ContinuousVariable(\"c1\"), ContinuousVariable(\"c2\")]\n        metas = [StringVariable(\"m1\")]\n        domain = Domain(attrs, metas=metas)\n        X = np.arange(8).reshape((4, 2))\n        M = np.array([\"aa\", \"bb\", \"\", \"dd\"])[:, None]\n        data = Table(domain, X, metas=M)\n\n        att = [ContinuousVariable(\"Feature 1\"), ContinuousVariable(\"Feature 2\"),\n               ContinuousVariable(\"Feature 3\"), ContinuousVariable(\"Feature 4\")]\n        att[0].attributes = {\"m1\": \"aa\"}\n        att[1].attributes = {\"m1\": \"bb\"}\n        att[3].attributes = {\"m1\": \"dd\"}\n        domain = Domain(att, metas=[StringVariable(\"Feature name\")])\n        result = Table(domain, np.arange(8).reshape((4, 2)).T,\n                       metas=np.array([\"c1\", \"c2\"])[:, None])\n\n        # transpose and compare\n        self._compare_tables(result, Table.transpose(data))\n\n        # transpose of transpose\n        t = Table.transpose(Table.transpose(data), \"Feature name\")\n        self._compare_tables(data, t)\n\n        # original should not change\n        self.assertDictEqual(data.domain.attributes[0].attributes, {})\n\n    def test_transpose_multiple_metas(self):\n        attrs = [ContinuousVariable(\"c1\"), ContinuousVariable(\"c2\")]\n        metas = [StringVariable(\"m1\"), StringVariable(\"m2\")]\n        domain = Domain(attrs, metas=metas)\n        X = np.arange(8).reshape((4, 2))\n        M = np.array([[\"aa\", \"aaa\"], [\"bb\", \"bbb\"],\n                      [\"cc\", \"ccc\"], [\"dd\", \"ddd\"]])\n        data = Table(domain, X, metas=M)\n\n        att = [ContinuousVariable(\"Feature 1\"), ContinuousVariable(\"Feature 2\"),\n               ContinuousVariable(\"Feature 3\"), ContinuousVariable(\"Feature 4\")]\n        att[0].attributes = {\"m1\": \"aa\", \"m2\": \"aaa\"}\n        att[1].attributes = {\"m1\": \"bb\", \"m2\": \"bbb\"}\n        att[2].attributes = {\"m1\": \"cc\", \"m2\": \"ccc\"}\n        att[3].attributes = {\"m1\": \"dd\", \"m2\": \"ddd\"}\n        domain = Domain(att, metas=[StringVariable(\"Feature name\")])\n        result = Table(domain, np.arange(8).reshape((4, 2)).T,\n                       metas=np.array([\"c1\", \"c2\"])[:, None])\n\n        # transpose and compare\n        self._compare_tables(result, Table.transpose(data))\n\n        # transpose of transpose\n        t = Table.transpose(Table.transpose(data), \"Feature name\")\n        self._compare_tables(data, t)\n\n        # original should not change\n        self.assertDictEqual(data.domain.attributes[0].attributes, {})\n\n    def test_transpose_class_and_metas(self):\n        attrs = [ContinuousVariable(\"c1\"), ContinuousVariable(\"c2\")]\n        metas = [StringVariable(\"m1\"), StringVariable(\"m2\")]\n        domain = Domain(attrs, [ContinuousVariable(\"cls\")], metas)\n        M = np.array([[\"aa\", \"aaa\"], [\"bb\", \"bbb\"],\n                      [\"cc\", \"ccc\"], [\"dd\", \"ddd\"]])\n        data = Table(domain, np.arange(8).reshape((4, 2)), np.arange(1, 5), M)\n\n        att = [ContinuousVariable(\"Feature 1\"), ContinuousVariable(\"Feature 2\"),\n               ContinuousVariable(\"Feature 3\"), ContinuousVariable(\"Feature 4\")]\n        att[0].attributes = {\"cls\": \"1\", \"m1\": \"aa\", \"m2\": \"aaa\"}\n        att[1].attributes = {\"cls\": \"2\", \"m1\": \"bb\", \"m2\": \"bbb\"}\n        att[2].attributes = {\"cls\": \"3\", \"m1\": \"cc\", \"m2\": \"ccc\"}\n        att[3].attributes = {\"cls\": \"4\", \"m1\": \"dd\", \"m2\": \"ddd\"}\n        domain = Domain(att, metas=[StringVariable(\"Feature name\")])\n        result = Table(domain, np.arange(8).reshape((4, 2)).T,\n                       metas=np.array([\"c1\", \"c2\"])[:, None])\n\n        # transpose and compare\n        self._compare_tables(result, Table.transpose(data))\n\n        # transpose of transpose\n        t = Table.transpose(Table.transpose(data), \"Feature name\")\n        self._compare_tables(data, t)\n\n        # original should not change\n        self.assertDictEqual(data.domain.attributes[0].attributes, {})\n\n    def test_transpose_attributes_of_attributes_discrete(self):\n        attrs = [ContinuousVariable(\"c1\"), ContinuousVariable(\"c2\")]\n        attrs[0].attributes = {\"attr1\": \"a\", \"attr2\": \"aa\"}\n        attrs[1].attributes = {\"attr1\": \"b\", \"attr2\": \"bb\"}\n        domain = Domain(attrs)\n        data = Table(domain, np.arange(8).reshape((4, 2)))\n\n        att = [ContinuousVariable(\"Feature 1\"), ContinuousVariable(\"Feature 2\"),\n               ContinuousVariable(\"Feature 3\"), ContinuousVariable(\"Feature 4\")]\n        metas = [StringVariable(\"Feature name\"),\n                 DiscreteVariable(\"attr1\", values=(\"a\", \"b\")),\n                 DiscreteVariable(\"attr2\", values=(\"aa\", \"bb\"))]\n        domain = Domain(att, metas=metas)\n        M = np.array([[\"c1\", 0.0, 0.0], [\"c2\", 1.0, 1.0]], dtype=object)\n        result = Table(domain, np.arange(8).reshape((4, 2)).T, metas=M)\n\n        # transpose and compare\n        self._compare_tables(result, Table.transpose(data))\n\n        # transpose of transpose\n        t = Table.transpose(Table.transpose(data), \"Feature name\")\n        self._compare_tables(data, t)\n\n        # original should not change\n        self.assertDictEqual(data.domain.attributes[0].attributes,\n                             {\"attr1\": \"a\", \"attr2\": \"aa\"})\n\n    def test_transpose_attributes_of_attributes_continuous(self):\n        attrs = [ContinuousVariable(\"c1\"), ContinuousVariable(\"c2\")]\n        attrs[0].attributes = {\"attr1\": \"1.1\", \"attr2\": \"1.3\"}\n        attrs[1].attributes = {\"attr1\": \"2.2\", \"attr2\": \"2.3\"}\n        domain = Domain(attrs)\n        data = Table(domain, np.arange(8).reshape((4, 2)))\n\n        att = [ContinuousVariable(\"Feature 1\"), ContinuousVariable(\"Feature 2\"),\n               ContinuousVariable(\"Feature 3\"), ContinuousVariable(\"Feature 4\")]\n        metas = [StringVariable(\"Feature name\"), ContinuousVariable(\"attr1\"),\n                 ContinuousVariable(\"attr2\")]\n        domain = Domain(att, metas=metas)\n        result = Table(domain, np.arange(8).reshape((4, 2)).T,\n                       metas=np.array([[\"c1\", 1.1, 1.3],\n                                       [\"c2\", 2.2, 2.3]], dtype=object))\n\n        # transpose and compare\n        self._compare_tables(result, Table.transpose(data))\n\n        # transpose of transpose\n        t = Table.transpose(Table.transpose(data), \"Feature name\")\n        self._compare_tables(data, t)\n\n        # original should not change\n        self.assertDictEqual(data.domain.attributes[0].attributes,\n                             {\"attr1\": \"1.1\", \"attr2\": \"1.3\"})\n\n    def test_transpose_attributes_of_attributes_missings(self):\n        attrs = [ContinuousVariable(\"c1\"), ContinuousVariable(\"c2\")]\n        attrs[0].attributes = {\"attr1\": \"a\", \"attr2\": \"aa\"}\n        attrs[1].attributes = {\"attr1\": \"b\"}\n        domain = Domain(attrs)\n        data = Table(domain, np.arange(8).reshape((4, 2)))\n\n        att = [ContinuousVariable(\"Feature 1\"), ContinuousVariable(\"Feature 2\"),\n               ContinuousVariable(\"Feature 3\"), ContinuousVariable(\"Feature 4\")]\n        metas = [StringVariable(\"Feature name\"),\n                 DiscreteVariable(\"attr1\", values=(\"a\", \"b\")),\n                 DiscreteVariable(\"attr2\", values=(\"aa\",))]\n        domain = Domain(att, metas=metas)\n        M = np.array([[\"c1\", 0.0, 0.0], [\"c2\", 1.0, np.nan]], dtype=object)\n        result = Table(domain, np.arange(8).reshape((4, 2)).T, metas=M)\n\n        # transpose and compare\n        self._compare_tables(result, Table.transpose(data))\n\n        # transpose of transpose\n        t = Table.transpose(Table.transpose(data), \"Feature name\")\n        self._compare_tables(data, t)\n\n        # original should not change\n        self.assertDictEqual(data.domain.attributes[0].attributes,\n                             {\"attr1\": \"a\", \"attr2\": \"aa\"})\n\n    def test_transpose_class_metas_attributes(self):\n        attrs = [ContinuousVariable(\"c1\"), ContinuousVariable(\"c2\")]\n        attrs[0].attributes = {\"attr1\": \"a1\", \"attr2\": \"aa1\"}\n        attrs[1].attributes = {\"attr1\": \"b1\", \"attr2\": \"bb1\"}\n        metas = [StringVariable(\"m1\"), StringVariable(\"m2\")]\n        domain = Domain(attrs, [ContinuousVariable(\"cls\")], metas)\n        M = np.array([[\"aa\", \"aaa\"], [\"bb\", \"bbb\"],\n                      [\"cc\", \"ccc\"], [\"dd\", \"ddd\"]])\n        data = Table(domain, np.arange(8).reshape((4, 2)), np.arange(1, 5), M)\n\n        att = [ContinuousVariable(\"Feature 1\"), ContinuousVariable(\"Feature 2\"),\n               ContinuousVariable(\"Feature 3\"), ContinuousVariable(\"Feature 4\")]\n        att[0].attributes = {\"cls\": \"1\", \"m1\": \"aa\", \"m2\": \"aaa\"}\n        att[1].attributes = {\"cls\": \"2\", \"m1\": \"bb\", \"m2\": \"bbb\"}\n        att[2].attributes = {\"cls\": \"3\", \"m1\": \"cc\", \"m2\": \"ccc\"}\n        att[3].attributes = {\"cls\": \"4\", \"m1\": \"dd\", \"m2\": \"ddd\"}\n        metas = [StringVariable(\"Feature name\"),\n                 DiscreteVariable(\"attr1\", values=(\"a1\", \"b1\")),\n                 DiscreteVariable(\"attr2\", values=(\"aa1\", \"bb1\"))]\n        domain = Domain(att, metas=metas)\n        M = np.array([[\"c1\", 0.0, 0.0], [\"c2\", 1.0, 1.0]], dtype=object)\n        result = Table(domain, np.arange(8).reshape((4, 2)).T, metas=M)\n\n        # transpose and compare\n        self._compare_tables(result, Table.transpose(data))\n\n        # transpose of transpose\n        t = Table.transpose(Table.transpose(data), \"Feature name\")\n        self._compare_tables(data, t)\n\n        # original should not change\n        self.assertDictEqual(data.domain.attributes[0].attributes,\n                             {\"attr1\": \"a1\", \"attr2\": \"aa1\"})\n\n    def test_transpose(self):\n        zoo = Table(\"zoo\")\n        t1 = Table.transpose(zoo)\n        t2 = Table.transpose(t1, \"Feature name\")\n        t3 = Table.transpose(t2)\n        self._compare_tables(zoo, t2)\n        self._compare_tables(t1, t3)\n\n    def _compare_tables(self, table1, table2):\n        self.assertEqual(table1.n_rows, table2.n_rows)\n        np.testing.assert_array_equal(table1.X, table2.X)\n        np.testing.assert_array_equal(table1.Y, table2.Y)\n        np.testing.assert_array_equal(table1.metas.astype(str),\n                                      table2.metas.astype(str))\n        np.testing.assert_array_equal(table1.W, table2.W)\n\n        self.assertEqual([(type(x), x.name, x.attributes)\n                          for x in table1.domain.attributes],\n                         [(type(x), x.name, x.attributes)\n                          for x in table2.domain.attributes])\n        self.assertEqual([(type(x), x.name, x.attributes)\n                          for x in table1.domain.class_vars],\n                         [(type(x), x.name, x.attributes)\n                          for x in table2.domain.class_vars])\n        self.assertEqual([(type(x), x.name, x.attributes)\n                          for x in table1.domain.metas],\n                         [(type(x), x.name, x.attributes)\n                          for x in table2.domain.metas])\n\n\nclass SparseCV:\n    def __call__(self, data):\n        return sp.csr_matrix((len(data), 1))\n\n\nclass TestTableSparseDense(unittest.TestCase):\n    def setUp(self):\n        self.iris = Table('iris')\n\n    def test_sparse_dense_transformation(self):\n        iris = Table('iris')\n        iris_sparse = iris.to_sparse(sparse_attributes=True)\n        self.assertTrue(sp.issparse(iris_sparse.X))\n        self.assertFalse(sp.issparse(iris_sparse.Y))\n        self.assertFalse(sp.issparse(iris_sparse.metas))\n\n        iris_sparse = iris.to_sparse(sparse_attributes=True, sparse_class=True)\n        self.assertTrue(sp.issparse(iris_sparse.X))\n        self.assertTrue(sp.issparse(iris_sparse.Y))\n        self.assertFalse(sp.issparse(iris_sparse.metas))\n\n        dense_iris = iris_sparse.to_dense()\n        self.assertFalse(sp.issparse(dense_iris.X))\n        self.assertFalse(sp.issparse(dense_iris.Y))\n        self.assertFalse(sp.issparse(dense_iris.metas))\n\n    def test_from_table_add_one_sparse_column(self):\n        # add one sparse feature, should remain dense\n        domain = self.iris.domain.copy()\n        domain.attributes += (\n            ContinuousVariable('S1', compute_value=SparseCV(), sparse=True),\n        )\n        d = self.iris.transform(domain)\n        self.assertFalse(sp.issparse(d.X))\n\n    def test_from_table_add_lots_of_sparse_columns(self):\n        n_attrs = len(self.iris.domain.attributes)\n\n        # add 2*n_attrs+1 sparse feature, should became sparse\n        domain = self.iris.domain.copy()\n        domain.attributes += tuple(\n            ContinuousVariable('S' + str(i), compute_value=SparseCV(), sparse=True)\n            for i in range(2*n_attrs + 1)\n        )\n        d = self.iris.transform(domain)\n        self.assertTrue(sp.issparse(d.X))\n\n    def test_from_table_replace_attrs_with_sparse(self):\n        # replace attrs with a sparse feature, should became sparse\n        domain = self.iris.domain.copy()\n        domain.attributes = (\n            ContinuousVariable('S1', compute_value=SparseCV(), sparse=True),\n        )\n        d = self.iris.transform(domain)\n        self.assertTrue(sp.issparse(d.X))\n\n    def test_from_table_sparse_metas(self):\n        # replace metas with a sparse feature, should became sparse\n        domain = self.iris.domain.copy()\n        domain._metas = (\n            ContinuousVariable('S1', compute_value=SparseCV(), sparse=True),\n        )\n        d = self.iris.transform(domain)\n        self.assertTrue(sp.issparse(d.metas))\n\n    def test_from_table_sparse_metas_with_strings(self):\n        # replace metas with text and 100 sparse features, should be dense\n        domain = self.iris.domain.copy()\n        domain._metas = (StringVariable('text'),) + tuple(\n            ContinuousVariable('S' + str(i), compute_value=SparseCV(), sparse=True)\n            for i in range(100)\n        )\n        d = self.iris.transform(domain)\n        self.assertFalse(sp.issparse(d.metas))\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...\nWarning: 'keywords' should be a list, got type 'tuple'\nWarning: 'classifiers' should be a list, got type 'tuple'\nWarning: 'keywords' should be a list, got type 'tuple'\nWarning: 'classifiers' should be a list, got type 'tuple'\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.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/tmp3wx7t8ky/tmp\ncreating /tmp/tmp3wx7t8ky/tmp/tmp3wx7t8ky\ncompile options: '-MMD -MF /tmp/tmp3wx7t8ky/file.c.d -c'\ncc: /tmp/tmp3wx7t8ky/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/tmppc4xi_z7/tmp\ncreating /tmp/tmppc4xi_z7/tmp/tmppc4xi_z7\ncompile options: '-MMD -MF /tmp/tmppc4xi_z7/file.c.d -c'\ncc: /tmp/tmppc4xi_z7/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_f3b183551b877f025889242567b0451e1a92a2ea/.venv/lib/python3.7/site-packages/numpy/core/include -I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_f3b183551b877f025889242567b0451e1a92a2ea/.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_f3b183551b877f025889242567b0451e1a92a2ea/.venv/lib/python3.7/site-packages/numpy/core/include -I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_f3b183551b877f025889242567b0451e1a92a2ea/.venv/lib/python3.7/site-packages/numpy/core/include -I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_f3b183551b877f025889242567b0451e1a92a2ea/.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_f3b183551b877f025889242567b0451e1a92a2ea/.venv/lib/python3.7/site-packages/numpy/core/include -I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_f3b183551b877f025889242567b0451e1a92a2ea/.venv/lib/python3.7/site-packages/numpy/core/include -I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_f3b183551b877f025889242567b0451e1a92a2ea/.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_f3b183551b877f025889242567b0451e1a92a2ea/.venv/lib/python3.7/site-packages/numpy/core/include -I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_f3b183551b877f025889242567b0451e1a92a2ea/.venv/lib/python3.7/site-packages/numpy/core/include -I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_f3b183551b877f025889242567b0451e1a92a2ea/.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_f3b183551b877f025889242567b0451e1a92a2ea/.venv/lib/python3.7/site-packages/numpy/core/include -I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_f3b183551b877f025889242567b0451e1a92a2ea/.venv/lib/python3.7/site-packages/numpy/core/include -I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_f3b183551b877f025889242567b0451e1a92a2ea/.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_f3b183551b877f025889242567b0451e1a92a2ea/.venv/lib/python3.7/site-packages/numpy/core/include -I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_f3b183551b877f025889242567b0451e1a92a2ea/.venv/lib/python3.7/site-packages/numpy/core/include -I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_f3b183551b877f025889242567b0451e1a92a2ea/.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_f3b183551b877f025889242567b0451e1a92a2ea/.venv/lib/python3.7/site-packages/numpy/core/include -I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_f3b183551b877f025889242567b0451e1a92a2ea/.venv/lib/python3.7/site-packages/numpy/core/include -I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_f3b183551b877f025889242567b0451e1a92a2ea/.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_f3b183551b877f025889242567b0451e1a92a2ea/.venv/lib/python3.7/site-packages/numpy/core/include -I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_f3b183551b877f025889242567b0451e1a92a2ea/.venv/lib/python3.7/site-packages/numpy/core/include -I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_f3b183551b877f025889242567b0451e1a92a2ea/.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_f3b183551b877f025889242567b0451e1a92a2ea/.venv/lib/python3.7/site-packages/numpy/core/include -I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_f3b183551b877f025889242567b0451e1a92a2ea/.venv/lib/python3.7/site-packages/numpy/core/include -I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_f3b183551b877f025889242567b0451e1a92a2ea/.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.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_f3b183551b877f025889242567b0451e1a92a2ea/.venv/lib/python3.7/site-packages/numpy/core/include -I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_f3b183551b877f025889242567b0451e1a92a2ea/.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\nWarning: 'keywords' should be a list, got type 'tuple'\nWarning: 'classifiers' should be a list, got type 'tuple'\nWarning: 'keywords' should be a list, got type 'tuple'\nWarning: 'classifiers' should be a list, got type 'tuple'\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.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 '*.html' under directory 'Orange/canvas'\nwarning: no files found matching '*.css' 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/tmpobc2eld1/tmp\ncreating /tmp/tmpobc2eld1/tmp/tmpobc2eld1\ncompile options: '-MMD -MF /tmp/tmpobc2eld1/file.c.d -c'\ncc: /tmp/tmpobc2eld1/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/tmpzr_8957a/tmp\ncreating /tmp/tmpzr_8957a/tmp/tmpzr_8957a\ncompile options: '-MMD -MF /tmp/tmpzr_8957a/file.c.d -c'\ncc: /tmp/tmpzr_8957a/file.c\ncustomize UnixCCompiler using build_ext\nCreating /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_f3b183551b877f025889242567b0451e1a92a2ea/.venv/lib/python3.7/site-packages/Orange3.egg-link (link to .)\nAdding Orange3 3.21.0.dev0+f3b1835 to easy-install.pth file\nInstalling orange-canvas script to /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_f3b183551b877f025889242567b0451e1a92a2ea/.venv/bin\n\nInstalled /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_f3b183551b877f025889242567b0451e1a92a2ea\nProcessing dependencies for Orange3==3.21.0.dev0+f3b1835\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_f3b183551b877f025889242567b0451e1a92a2ea/.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_f3b183551b877f025889242567b0451e1a92a2ea/.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_f3b183551b877f025889242567b0451e1a92a2ea/.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_f3b183551b877f025889242567b0451e1a92a2ea/.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_f3b183551b877f025889242567b0451e1a92a2ea/.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_f3b183551b877f025889242567b0451e1a92a2ea/.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_f3b183551b877f025889242567b0451e1a92a2ea/.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_f3b183551b877f025889242567b0451e1a92a2ea/.venv/lib/python3.7/site-packages\nSearching for pyqtgraph==0.12.4\nBest match: pyqtgraph 0.12.4\nAdding pyqtgraph 0.12.4 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_f3b183551b877f025889242567b0451e1a92a2ea/.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_f3b183551b877f025889242567b0451e1a92a2ea/.venv/bin\nInstalling pip3 script to /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_f3b183551b877f025889242567b0451e1a92a2ea/.venv/bin\nInstalling pip3.10 script to /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_f3b183551b877f025889242567b0451e1a92a2ea/.venv/bin\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_f3b183551b877f025889242567b0451e1a92a2ea/.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_f3b183551b877f025889242567b0451e1a92a2ea/.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_f3b183551b877f025889242567b0451e1a92a2ea/.venv/bin\nInstalling f2py3 script to /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_f3b183551b877f025889242567b0451e1a92a2ea/.venv/bin\nInstalling f2py3.7 script to /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_f3b183551b877f025889242567b0451e1a92a2ea/.venv/bin\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_f3b183551b877f025889242567b0451e1a92a2ea/.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_f3b183551b877f025889242567b0451e1a92a2ea/.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_f3b183551b877f025889242567b0451e1a92a2ea/.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_f3b183551b877f025889242567b0451e1a92a2ea/.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_f3b183551b877f025889242567b0451e1a92a2ea/.venv/bin\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_f3b183551b877f025889242567b0451e1a92a2ea/.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_f3b183551b877f025889242567b0451e1a92a2ea/.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_f3b183551b877f025889242567b0451e1a92a2ea/.venv/bin\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_f3b183551b877f025889242567b0451e1a92a2ea/.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_f3b183551b877f025889242567b0451e1a92a2ea/.venv/bin\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_f3b183551b877f025889242567b0451e1a92a2ea/.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_f3b183551b877f025889242567b0451e1a92a2ea/.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_f3b183551b877f025889242567b0451e1a92a2ea/.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_f3b183551b877f025889242567b0451e1a92a2ea/.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_f3b183551b877f025889242567b0451e1a92a2ea/.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_f3b183551b877f025889242567b0451e1a92a2ea/.venv/bin\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_f3b183551b877f025889242567b0451e1a92a2ea/.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_f3b183551b877f025889242567b0451e1a92a2ea/.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_f3b183551b877f025889242567b0451e1a92a2ea/.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_f3b183551b877f025889242567b0451e1a92a2ea/.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_f3b183551b877f025889242567b0451e1a92a2ea/.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_f3b183551b877f025889242567b0451e1a92a2ea/.venv/bin\nInstalling pyftmerge script to /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_f3b183551b877f025889242567b0451e1a92a2ea/.venv/bin\nInstalling pyftsubset script to /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_f3b183551b877f025889242567b0451e1a92a2ea/.venv/bin\nInstalling ttx script to /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_f3b183551b877f025889242567b0451e1a92a2ea/.venv/bin\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_f3b183551b877f025889242567b0451e1a92a2ea/.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_f3b183551b877f025889242567b0451e1a92a2ea/.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_f3b183551b877f025889242567b0451e1a92a2ea/.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_f3b183551b877f025889242567b0451e1a92a2ea/.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_f3b183551b877f025889242567b0451e1a92a2ea/.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_f3b183551b877f025889242567b0451e1a92a2ea/.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_f3b183551b877f025889242567b0451e1a92a2ea/.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_f3b183551b877f025889242567b0451e1a92a2ea/.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_f3b183551b877f025889242567b0451e1a92a2ea/.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_f3b183551b877f025889242567b0451e1a92a2ea/.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_f3b183551b877f025889242567b0451e1a92a2ea/.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_f3b183551b877f025889242567b0451e1a92a2ea/.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_f3b183551b877f025889242567b0451e1a92a2ea/.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_f3b183551b877f025889242567b0451e1a92a2ea/.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_f3b183551b877f025889242567b0451e1a92a2ea/.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_f3b183551b877f025889242567b0451e1a92a2ea/.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_f3b183551b877f025889242567b0451e1a92a2ea/.venv/lib/python3.7/site-packages\nFinished processing dependencies for Orange3==3.21.0.dev0+f3b1835\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 97ms\nPrepared 18 packages in 10ms\nInstalled 18 packages in 81ms\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 33 packages in 235ms\nInstalled 28 packages in 365ms\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 + 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 + more-itertools==9.1.0\n + networkx==2.6.3\n + opentsne==1.0.1\n + pip==24.0\n + pycparser==2.21\n + python-louvain==0.16\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 + threadpoolctl==3.1.0\n + urllib3==2.0.7\n + xlrd==2.0.1\n + xlsxwriter==3.2.0\nResolved 14 packages in 60ms\nInstalled 11 packages in 351ms\n + anyqt==0.2.0\n + cycler==0.11.0\n + docutils==0.20.1\n + fonttools==4.38.0\n + kiwisolver==1.4.5\n + matplotlib==3.5.3\n + pillow==9.5.0\n + pyparsing==3.1.4\n + pyqtgraph==0.12.4\n + python-dateutil==2.9.0.post0\n + six==1.17.0\nResolved 2 packages in 3ms\nInstalled 2 packages in 73ms\n + psycopg2==2.9.9\n + pymssql==2.3.2\nResolved 5 packages in 15ms\nInstalled 2 packages in 200ms\n + pandas==1.3.5\n + pytz==2024.2\nAudited 2 packages in 40ms\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_f3b183551b877f025889242567b0451e1a92a2ea/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/ndarraytypes.h:1830,\n                 from /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_f3b183551b877f025889242567b0451e1a92a2ea/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/ndarrayobject.h:12,\n                 from /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_f3b183551b877f025889242567b0451e1a92a2ea/.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_f3b183551b877f025889242567b0451e1a92a2ea/.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_f3b183551b877f025889242567b0451e1a92a2ea/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/ndarraytypes.h:1830,\n                 from /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_f3b183551b877f025889242567b0451e1a92a2ea/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/ndarrayobject.h:12,\n                 from /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_f3b183551b877f025889242567b0451e1a92a2ea/.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_f3b183551b877f025889242567b0451e1a92a2ea/.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_f3b183551b877f025889242567b0451e1a92a2ea/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/ndarraytypes.h:1830,\n                 from /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_f3b183551b877f025889242567b0451e1a92a2ea/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/ndarrayobject.h:12,\n                 from /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_f3b183551b877f025889242567b0451e1a92a2ea/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/arrayobject.h:4,\n                 from Orange/data/_contingency.c:567:\n/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_f3b183551b877f025889242567b0451e1a92a2ea/.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_f3b183551b877f025889242567b0451e1a92a2ea/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/ndarraytypes.h:1830,\n                 from /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_f3b183551b877f025889242567b0451e1a92a2ea/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/ndarrayobject.h:12,\n                 from /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_f3b183551b877f025889242567b0451e1a92a2ea/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/arrayobject.h:4,\n                 from Orange/distance/_distance.c:567:\n/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_f3b183551b877f025889242567b0451e1a92a2ea/.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_f3b183551b877f025889242567b0451e1a92a2ea/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/ndarraytypes.h:1830,\n                 from /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_f3b183551b877f025889242567b0451e1a92a2ea/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/ndarrayobject.h:12,\n                 from /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_f3b183551b877f025889242567b0451e1a92a2ea/.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_f3b183551b877f025889242567b0451e1a92a2ea/.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_f3b183551b877f025889242567b0451e1a92a2ea/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/ndarraytypes.h:1830,\n                 from /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_f3b183551b877f025889242567b0451e1a92a2ea/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/ndarrayobject.h:12,\n                 from /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_f3b183551b877f025889242567b0451e1a92a2ea/.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_f3b183551b877f025889242567b0451e1a92a2ea/.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      |  ^~~~~~~\n/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_f3b183551b877f025889242567b0451e1a92a2ea/.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_f3b183551b877f025889242567b0451e1a92a2ea/.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_f3b183551b877f025889242567b0451e1a92a2ea/.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_f3b183551b877f025889242567b0451e1a92a2ea/.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": 1,
    "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_f3b183551b877f025889242567b0451e1a92a2ea\ncollected 157 items\n\nr2e_tests/test_1.py .ss......s..sssss..............s.........s.......... [ 33%]\n...s............................................................sssss... [ 78%]\n...F.............................                                        [100%]\n\n=================================== FAILURES ===================================\n________________________ InterfaceTest.test_subclasses _________________________\n\nself = <urllib.request.FileHandler object at 0x727d9b9c9090>\nreq = <urllib.request.Request object at 0x727d9b9b2d50>\n\n    def open_local_file(self, req):\n        import email.utils\n        import mimetypes\n        host = req.host\n        filename = req.selector\n        localfile = url2pathname(filename)\n        try:\n>           stats = os.stat(localfile)\nE           FileNotFoundError: [Errno 2] No such file or directory: '/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_f3b183551b877f025889242567b0451e1a92a2ea/r2e_tests/test1.tab'\n\n../../../../.local/share/uv/python/cpython-3.7.9-linux-x86_64-gnu/lib/python3.7/urllib/request.py:1506: FileNotFoundError\n\nDuring handling of the above exception, another exception occurred:\n\nself = <r2e_tests.test_1.InterfaceTest testMethod=test_subclasses>\n\n    def test_subclasses(self):\n        from pathlib import Path\n    \n        class _ExtendedTable(data.Table):\n            pass\n    \n        data_file = _ExtendedTable('iris')\n        data_url = _ExtendedTable.from_url(\n>           Path(os.path.dirname(__file__), 'test1.tab').as_uri())\n\nr2e_tests/test_1.py:2270: \n_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ \nOrange/data/table.py:636: in from_url\n    data = reader.read()\nOrange/data/io.py:1089: in read\n    self.filename = self._trim(self._resolve_redirects(self.filename))\nOrange/data/io.py:1106: in _resolve_redirects\n    with contextlib.closing(self.urlopen(url)) as response:\nOrange/data/io.py:1086: in urlopen\n    return urlopen(req, timeout=10)\n../../../../.local/share/uv/python/cpython-3.7.9-linux-x86_64-gnu/lib/python3.7/urllib/request.py:222: in urlopen\n    return opener.open(url, data, timeout)\n../../../../.local/share/uv/python/cpython-3.7.9-linux-x86_64-gnu/lib/python3.7/urllib/request.py:525: in open\n    response = self._open(req, data)\n../../../../.local/share/uv/python/cpython-3.7.9-linux-x86_64-gnu/lib/python3.7/urllib/request.py:543: in _open\n    '_open', req)\n../../../../.local/share/uv/python/cpython-3.7.9-linux-x86_64-gnu/lib/python3.7/urllib/request.py:503: in _call_chain\n    result = func(*args)\n../../../../.local/share/uv/python/cpython-3.7.9-linux-x86_64-gnu/lib/python3.7/urllib/request.py:1484: in file_open\n    return self.open_local_file(req)\n_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ \n\nself = <urllib.request.FileHandler object at 0x727d9b9c9090>\nreq = <urllib.request.Request object at 0x727d9b9b2d50>\n\n    def open_local_file(self, req):\n        import email.utils\n        import mimetypes\n        host = req.host\n        filename = req.selector\n        localfile = url2pathname(filename)\n        try:\n            stats = os.stat(localfile)\n            size = stats.st_size\n            modified = email.utils.formatdate(stats.st_mtime, usegmt=True)\n            mtype = mimetypes.guess_type(filename)[0]\n            headers = email.message_from_string(\n                'Content-type: %s\\nContent-length: %d\\nLast-modified: %s\\n' %\n                (mtype or 'text/plain', size, modified))\n            if host:\n                host, port = splitport(host)\n            if not host or \\\n                (not port and _safe_gethostbyname(host) in self.get_names()):\n                if host:\n                    origurl = 'file://' + host + filename\n                else:\n                    origurl = 'file://' + filename\n                return addinfourl(open(localfile, 'rb'), headers, origurl)\n        except OSError as exp:\n>           raise URLError(exp)\nE           urllib.error.URLError: <urlopen error [Errno 2] No such file or directory: '/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_f3b183551b877f025889242567b0451e1a92a2ea/r2e_tests/test1.tab'>\n\n../../../../.local/share/uv/python/cpython-3.7.9-linux-x86_64-gnu/lib/python3.7/urllib/request.py:1523: URLError\n==================================== PASSES ====================================\n=========================== short test summary info ============================\nPASSED r2e_tests/test_1.py::test_dirname\nPASSED r2e_tests/test_1.py::TableTestCase::test_assign_multiple_indices_value\nPASSED r2e_tests/test_1.py::TableTestCase::test_assign_slice_value\nPASSED r2e_tests/test_1.py::TableTestCase::test_attributes\nPASSED r2e_tests/test_1.py::TableTestCase::test_bool\nPASSED r2e_tests/test_1.py::TableTestCase::test_checksum\nPASSED r2e_tests/test_1.py::TableTestCase::test_concatenate\nPASSED r2e_tests/test_1.py::TableTestCase::test_copy\nPASSED r2e_tests/test_1.py::TableTestCase::test_copy_sparse\nPASSED r2e_tests/test_1.py::TableTestCase::test_filename\nPASSED r2e_tests/test_1.py::TableTestCase::test_filter_has_class\nPASSED r2e_tests/test_1.py::TableTestCase::test_filter_is_defined\nPASSED r2e_tests/test_1.py::TableTestCase::test_filter_random\nPASSED r2e_tests/test_1.py::TableTestCase::test_filter_string_works_for_numeric_columns\nPASSED r2e_tests/test_1.py::TableTestCase::test_filter_value_continuous\nPASSED r2e_tests/test_1.py::TableTestCase::test_filter_value_continuous_args\nPASSED r2e_tests/test_1.py::TableTestCase::test_filter_values_nested\nPASSED r2e_tests/test_1.py::TableTestCase::test_from_numpy\nPASSED r2e_tests/test_1.py::TableTestCase::test_has_missing\nPASSED r2e_tests/test_1.py::TableTestCase::test_indexing\nPASSED r2e_tests/test_1.py::TableTestCase::test_indexing_assign_example\nPASSED r2e_tests/test_1.py::TableTestCase::test_indexing_assign_value\nPASSED r2e_tests/test_1.py::TableTestCase::test_indexing_class\nPASSED r2e_tests/test_1.py::TableTestCase::test_indexing_example\nPASSED r2e_tests/test_1.py::TableTestCase::test_inf\nPASSED r2e_tests/test_1.py::TableTestCase::test_is_sparse\nPASSED r2e_tests/test_1.py::TableTestCase::test_multiple_indices\nPASSED r2e_tests/test_1.py::TableTestCase::test_pickle\nPASSED r2e_tests/test_1.py::TableTestCase::test_repr_sparse_with_one_row\nPASSED r2e_tests/test_1.py::TableTestCase::test_saveTab\nPASSED r2e_tests/test_1.py::TableTestCase::test_save_pickle\nPASSED r2e_tests/test_1.py::TableTestCase::test_set_multiple_indices_example\nPASSED r2e_tests/test_1.py::TableTestCase::test_shuffle\nPASSED r2e_tests/test_1.py::TableTestCase::test_slice\nPASSED r2e_tests/test_1.py::TableTestCase::test_sparse_concatenate_rows\nPASSED r2e_tests/test_1.py::TableTestCase::test_table_dtypes\nPASSED r2e_tests/test_1.py::TableTestCase::test_total_weight\nPASSED r2e_tests/test_1.py::TableTestCase::test_translate_through_slice\nPASSED r2e_tests/test_1.py::TableTestCase::test_valueFilter_discrete\nPASSED r2e_tests/test_1.py::TableTestCase::test_valueFilter_discrete_meta_is_defined\nPASSED r2e_tests/test_1.py::TableTestCase::test_valueFilter_regex\nPASSED r2e_tests/test_1.py::TableTestCase::test_valueFilter_stringList\nPASSED r2e_tests/test_1.py::TableTestCase::test_valueFilter_string_case_insens\nPASSED r2e_tests/test_1.py::TableTestCase::test_valueFilter_string_case_sens\nPASSED r2e_tests/test_1.py::TableTestCase::test_valueFilter_string_is_defined\nPASSED r2e_tests/test_1.py::CreateEmptyTable::test_calling_new_with_no_parameters_constructs_a_new_instance\nPASSED r2e_tests/test_1.py::CreateEmptyTable::test_table_has_file\nPASSED r2e_tests/test_1.py::CreateTableWithFilename::test_calling_new_with_keyword_argument_filename_calls_read_data\nPASSED r2e_tests/test_1.py::CreateTableWithFilename::test_calling_new_with_string_argument_calls_read_data\nPASSED r2e_tests/test_1.py::CreateTableWithFilename::test_raises_error_if_file_does_not_exist\nPASSED r2e_tests/test_1.py::CreateTableWithFilename::test_raises_error_if_file_has_unknown_extension\nPASSED r2e_tests/test_1.py::CreateTableWithFilename::test_read_data_calls_reader\nPASSED r2e_tests/test_1.py::CreateTableWithUrl::test_trimmed_urls\nPASSED r2e_tests/test_1.py::CreateTableWithUrl::test_url_no_scheme\nPASSED r2e_tests/test_1.py::CreateTableWithDomain::test_calling_new_with_domain_calls_new_from_domain\nPASSED r2e_tests/test_1.py::CreateTableWithDomain::test_creates_an_empty_table_with_given_domain\nPASSED r2e_tests/test_1.py::CreateTableWithDomain::test_creates_weights_if_weights_are_true\nPASSED r2e_tests/test_1.py::CreateTableWithDomain::test_creates_zero_filled_rows_in_X_if_domain_contains_attributes\nPASSED r2e_tests/test_1.py::CreateTableWithDomain::test_creates_zero_filled_rows_in_Y_if_domain_contains_class_vars\nPASSED r2e_tests/test_1.py::CreateTableWithDomain::test_creates_zero_filled_rows_in_metas_if_domain_contains_metas\nPASSED r2e_tests/test_1.py::CreateTableWithDomain::test_does_not_create_weights_if_weights_are_false\nPASSED r2e_tests/test_1.py::CreateTableWithData::test_calling_new_with_domain_and_numpy_arrays_calls_new_from_numpy\nPASSED r2e_tests/test_1.py::CreateTableWithData::test_creates_a_discrete_class_if_Y_has_few_distinct_values\nPASSED r2e_tests/test_1.py::CreateTableWithData::test_creates_a_table_from_domain_and_list\nPASSED r2e_tests/test_1.py::CreateTableWithData::test_creates_a_table_from_domain_and_list_and_metas\nPASSED r2e_tests/test_1.py::CreateTableWithData::test_creates_a_table_from_domain_and_list_and_weights\nPASSED r2e_tests/test_1.py::CreateTableWithData::test_creates_a_table_from_list_of_instances\nPASSED r2e_tests/test_1.py::CreateTableWithData::test_creates_a_table_from_list_of_instances_with_metas\nPASSED r2e_tests/test_1.py::CreateTableWithData::test_creates_a_table_with_domain_and_given_X\nPASSED r2e_tests/test_1.py::CreateTableWithData::test_creates_a_table_with_given_X\nPASSED r2e_tests/test_1.py::CreateTableWithData::test_creates_a_table_with_given_X_Y_and_metas\nPASSED r2e_tests/test_1.py::CreateTableWithData::test_creates_a_table_with_given_X_and_Y\nPASSED r2e_tests/test_1.py::CreateTableWithData::test_creates_a_table_with_given_domain\nPASSED r2e_tests/test_1.py::CreateTableWithData::test_from_numpy_reconstructable\nPASSED r2e_tests/test_1.py::CreateTableWithData::test_initializes_Y_metas_and_W_if_not_given\nPASSED r2e_tests/test_1.py::CreateTableWithData::test_raises_error_if_columns_in_domain_and_data_do_not_match\nPASSED r2e_tests/test_1.py::CreateTableWithData::test_raises_error_if_lengths_of_data_do_not_match\nPASSED r2e_tests/test_1.py::CreateTableWithData::test_sets_Y_if_given\nPASSED r2e_tests/test_1.py::CreateTableWithData::test_sets_metas_if_given\nPASSED r2e_tests/test_1.py::CreateTableWithData::test_sets_weights_if_given\nPASSED r2e_tests/test_1.py::CreateTableWithData::test_splits_X_and_Y_if_given_in_same_array\nPASSED r2e_tests/test_1.py::CreateTableWithDomainAndTable::test_can_copy_table\nPASSED r2e_tests/test_1.py::CreateTableWithDomainAndTable::test_can_filter_row_with_slice\nPASSED r2e_tests/test_1.py::CreateTableWithDomainAndTable::test_can_filter_rows_with_list\nPASSED r2e_tests/test_1.py::CreateTableWithDomainAndTable::test_can_use_attributes_as_new_columns\nPASSED r2e_tests/test_1.py::CreateTableWithDomainAndTable::test_can_use_class_vars_as_new_columns\nPASSED r2e_tests/test_1.py::CreateTableWithDomainAndTable::test_can_use_combination_of_all_as_new_columns\nPASSED r2e_tests/test_1.py::CreateTableWithDomainAndTable::test_can_use_metas_as_new_columns\nPASSED r2e_tests/test_1.py::CreateTableWithDomainAndTable::test_creates_table_with_given_domain\nPASSED r2e_tests/test_1.py::CreateTableWithDomainAndTable::test_creates_table_with_given_domain_and_row_filter\nPASSED r2e_tests/test_1.py::CreateTableWithDomainAndTable::test_from_table_sparse_move_all_to_empty_metas\nPASSED r2e_tests/test_1.py::CreateTableWithDomainAndTable::test_from_table_sparse_move_some_to_empty_metas\nPASSED r2e_tests/test_1.py::CreateTableWithDomainAndTable::test_from_table_sparse_move_to_nonempty_metas\nPASSED r2e_tests/test_1.py::CreateTableWithDomainAndTable::test_transform\nPASSED r2e_tests/test_1.py::CreateTableWithDomainAndTable::test_transform_same_domain\nPASSED r2e_tests/test_1.py::TableIndexingTests::test_can_select_a_single_row\nPASSED r2e_tests/test_1.py::TableIndexingTests::test_can_select_a_single_value\nPASSED r2e_tests/test_1.py::TableIndexingTests::test_can_select_a_subset_of_rows_and_columns\nPASSED r2e_tests/test_1.py::TableIndexingTests::test_optimize_indices\nPASSED r2e_tests/test_1.py::TableElementAssignmentTest::test_can_assign_lists\nPASSED r2e_tests/test_1.py::TableElementAssignmentTest::test_can_assign_np_array\nPASSED r2e_tests/test_1.py::TableElementAssignmentTest::test_can_assign_rows_to_rows\nPASSED r2e_tests/test_1.py::TableElementAssignmentTest::test_can_assign_values\nPASSED r2e_tests/test_1.py::TableElementAssignmentTest::test_can_assign_values_to_classes\nPASSED r2e_tests/test_1.py::TableElementAssignmentTest::test_can_assign_values_to_metas\nPASSED r2e_tests/test_1.py::InterfaceTest::test_iteration\nPASSED r2e_tests/test_1.py::InterfaceTest::test_len\nPASSED r2e_tests/test_1.py::InterfaceTest::test_row_assignment\nPASSED r2e_tests/test_1.py::InterfaceTest::test_row_indexing\nPASSED r2e_tests/test_1.py::InterfaceTest::test_row_len\nPASSED r2e_tests/test_1.py::InterfaceTest::test_row_slicing\nPASSED r2e_tests/test_1.py::InterfaceTest::test_value_assignment\nPASSED r2e_tests/test_1.py::InterfaceTest::test_value_indexing\nPASSED r2e_tests/test_1.py::TestTableStats::test_get_nan_frequency\nPASSED r2e_tests/test_1.py::TestTableStats::test_get_nan_frequency_empty_table\nPASSED r2e_tests/test_1.py::TestRowInstance::test_assignment\nPASSED r2e_tests/test_1.py::TestRowInstance::test_iteration_with_assignment\nPASSED r2e_tests/test_1.py::TestRowInstance::test_sparse_assignment\nPASSED r2e_tests/test_1.py::TestTableTranspose::test_transpose\nPASSED r2e_tests/test_1.py::TestTableTranspose::test_transpose_attributes_of_attributes_continuous\nPASSED r2e_tests/test_1.py::TestTableTranspose::test_transpose_attributes_of_attributes_discrete\nPASSED r2e_tests/test_1.py::TestTableTranspose::test_transpose_attributes_of_attributes_missings\nPASSED r2e_tests/test_1.py::TestTableTranspose::test_transpose_class_and_metas\nPASSED r2e_tests/test_1.py::TestTableTranspose::test_transpose_class_metas_attributes\nPASSED r2e_tests/test_1.py::TestTableTranspose::test_transpose_continuous_class\nPASSED r2e_tests/test_1.py::TestTableTranspose::test_transpose_continuous_metas\nPASSED r2e_tests/test_1.py::TestTableTranspose::test_transpose_discrete_class\nPASSED r2e_tests/test_1.py::TestTableTranspose::test_transpose_discrete_metas\nPASSED r2e_tests/test_1.py::TestTableTranspose::test_transpose_metas\nPASSED r2e_tests/test_1.py::TestTableTranspose::test_transpose_missing_class\nPASSED r2e_tests/test_1.py::TestTableTranspose::test_transpose_missing_metas\nPASSED r2e_tests/test_1.py::TestTableTranspose::test_transpose_multiple_class\nPASSED r2e_tests/test_1.py::TestTableTranspose::test_transpose_multiple_metas\nPASSED r2e_tests/test_1.py::TestTableTranspose::test_transpose_no_class\nPASSED r2e_tests/test_1.py::TestTableSparseDense::test_from_table_add_lots_of_sparse_columns\nPASSED r2e_tests/test_1.py::TestTableSparseDense::test_from_table_add_one_sparse_column\nPASSED r2e_tests/test_1.py::TestTableSparseDense::test_from_table_replace_attrs_with_sparse\nPASSED r2e_tests/test_1.py::TestTableSparseDense::test_from_table_sparse_metas\nPASSED r2e_tests/test_1.py::TestTableSparseDense::test_from_table_sparse_metas_with_strings\nPASSED r2e_tests/test_1.py::TestTableSparseDense::test_sparse_dense_transformation\nSKIPPED [1] r2e_tests/test_1.py:589: Method test_append will be deprecated; tests are skipped because it already fails on Python 3.7 on travis\nSKIPPED [1] r2e_tests/test_1.py:605: Method test_append2 will be deprecated; tests are skipped because it already fails on Python 3.7 on travis\nSKIPPED [1] r2e_tests/test_1.py:710: Method test_convert_through_append will be deprecated; tests are skipped because it already fails on Python 3.7 on travis\nSKIPPED [1] r2e_tests/test_1.py:439: Method test_del_multiple_indices_example will be deprecated; tests are skipped because it already fails on Python 3.7 on travis\nSKIPPED [1] r2e_tests/test_1.py:360: Method test_del_slice_example will be deprecated; tests are skipped because it already fails on Python 3.7 on travis\nSKIPPED [1] r2e_tests/test_1.py:380: Method test_del_slice_ids will be deprecated; tests are skipped because it already fails on Python 3.7 on travis\nSKIPPED [1] r2e_tests/test_1.py:623: Method test_extend will be deprecated; tests are skipped because it already fails on Python 3.7 on travis\nSKIPPED [1] r2e_tests/test_1.py:640: Method test_extend2 will be deprecated; tests are skipped because it already fails on Python 3.7 on travis\nSKIPPED [1] r2e_tests/test_1.py:223: Method test_indexing_del_example will be deprecated; tests are skipped because it already fails on Python 3.7 on travis\nSKIPPED [1] r2e_tests/test_1.py:388: Method test_set_slice_example will be deprecated; tests are skipped because it already fails on Python 3.7 on travis\nSKIPPED [1] r2e_tests/test_1.py:471: Method test_views will be deprecated; tests are skipped because it already fails on Python 3.7 on travis\nSKIPPED [1] r2e_tests/test_1.py:2222: Method test_append_rows will be deprecated; tests are skipped because it already fails on Python 3.7 on travis\nSKIPPED [1] r2e_tests/test_1.py:2255: Method test_clear will be deprecated; tests are skipped because it already fails on Python 3.7 on travis\nSKIPPED [1] r2e_tests/test_1.py:2248: Method test_delete_rows will be deprecated; tests are skipped because it already fails on Python 3.7 on travis\nSKIPPED [1] r2e_tests/test_1.py:2229: Method test_insert_rows will be deprecated; tests are skipped because it already fails on Python 3.7 on travis\nSKIPPED [1] r2e_tests/test_1.py:2238: Method test_insert_view will be deprecated; tests are skipped because it already fails on Python 3.7 on travis\nFAILED r2e_tests/test_1.py::InterfaceTest::test_subclasses - urllib.error.URL...\n================== 1 failed, 140 passed, 16 skipped in 2.15s ===================\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_f3b183551b877f025889242567b0451e1a92a2ea\ncollected 157 items\n\nr2e_tests/test_1.py .ss......s..sssss..............s.F.......s.......... [ 33%]\n...s............................................................sssss... [ 78%]\n...F.............................                                        [100%]\n\n=================================== FAILURES ===================================\n____________________________ TableTestCase.test_inf ____________________________\n\nself = <r2e_tests.test_1.TableTestCase testMethod=test_inf>\n\n    def test_inf(self):\n        a = np.array([[2,   0,      0,      0],\n                      [0,   np.nan, np.nan, 1],\n                      [0,   0,      np.inf, 0]])\n        with self.assertWarns(Warning):\n>           tab = data.Table(a)\n\nr2e_tests/test_1.py:1285: \n_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ \nOrange/data/table.py:238: in __new__\n    return cls.from_numpy(domain, *args, **kwargs)\nOrange/data/table.py:497: in from_numpy\n    X, Y, W = _check_arrays(X, Y, W, dtype='float64')\n_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ \n\ndtype = 'float64'\narrays = (array([[ 2.,  0.,  0.,  0.],\n       [ 0., nan, nan,  1.],\n       [ 0.,  0., inf,  0.]]), None, None)\nchecked = []\nninstances = <function _check_arrays.<locals>.ninstances at 0x74780c8585f0>\n\n    def _check_arrays(*arrays, dtype=None):\n        checked = []\n        if not len(arrays):\n            return checked\n    \n        def ninstances(array):\n            if hasattr(array, \"shape\"):\n                return array.shape[0]\n            else:\n                return len(array) if array is not None else 0\n    \n        shape_1 = ninstances(arrays[0])\n    \n        for array in arrays:\n            if array is None:\n                checked.append(array)\n                continue\n    \n            if ninstances(array) != shape_1:\n                raise ValueError(\"Leading dimension mismatch (%d != %d)\"\n                                 % (ninstances(array), shape_1))\n    \n            if sp.issparse(array):\n                array.data = np.asarray(array.data)\n                has_inf = _check_inf(array.data)\n            else:\n                if dtype is not None:\n                    array = np.asarray(array, dtype=dtype)\n                else:\n                    array = np.asarray(array)\n                has_inf = _check_inf(array)\n    \n            if has_inf:\n>               raise ValueError(\"Array contains infinity.\")\nE               ValueError: Array contains infinity.\n\nOrange/data/table.py:1782: ValueError\n________________________ InterfaceTest.test_subclasses _________________________\n\nself = <urllib.request.FileHandler object at 0x747806acc710>\nreq = <urllib.request.Request object at 0x74780c8a8f90>\n\n    def open_local_file(self, req):\n        import email.utils\n        import mimetypes\n        host = req.host\n        filename = req.selector\n        localfile = url2pathname(filename)\n        try:\n>           stats = os.stat(localfile)\nE           FileNotFoundError: [Errno 2] No such file or directory: '/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_f3b183551b877f025889242567b0451e1a92a2ea/r2e_tests/test1.tab'\n\n../../../../.local/share/uv/python/cpython-3.7.9-linux-x86_64-gnu/lib/python3.7/urllib/request.py:1506: FileNotFoundError\n\nDuring handling of the above exception, another exception occurred:\n\nself = <r2e_tests.test_1.InterfaceTest testMethod=test_subclasses>\n\n    def test_subclasses(self):\n        from pathlib import Path\n    \n        class _ExtendedTable(data.Table):\n            pass\n    \n        data_file = _ExtendedTable('iris')\n        data_url = _ExtendedTable.from_url(\n>           Path(os.path.dirname(__file__), 'test1.tab').as_uri())\n\nr2e_tests/test_1.py:2270: \n_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ \nOrange/data/table.py:636: in from_url\n    data = reader.read()\nOrange/data/io.py:1089: in read\n    self.filename = self._trim(self._resolve_redirects(self.filename))\nOrange/data/io.py:1106: in _resolve_redirects\n    with contextlib.closing(self.urlopen(url)) as response:\nOrange/data/io.py:1086: in urlopen\n    return urlopen(req, timeout=10)\n../../../../.local/share/uv/python/cpython-3.7.9-linux-x86_64-gnu/lib/python3.7/urllib/request.py:222: in urlopen\n    return opener.open(url, data, timeout)\n../../../../.local/share/uv/python/cpython-3.7.9-linux-x86_64-gnu/lib/python3.7/urllib/request.py:525: in open\n    response = self._open(req, data)\n../../../../.local/share/uv/python/cpython-3.7.9-linux-x86_64-gnu/lib/python3.7/urllib/request.py:543: in _open\n    '_open', req)\n../../../../.local/share/uv/python/cpython-3.7.9-linux-x86_64-gnu/lib/python3.7/urllib/request.py:503: in _call_chain\n    result = func(*args)\n../../../../.local/share/uv/python/cpython-3.7.9-linux-x86_64-gnu/lib/python3.7/urllib/request.py:1484: in file_open\n    return self.open_local_file(req)\n_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ \n\nself = <urllib.request.FileHandler object at 0x747806acc710>\nreq = <urllib.request.Request object at 0x74780c8a8f90>\n\n    def open_local_file(self, req):\n        import email.utils\n        import mimetypes\n        host = req.host\n        filename = req.selector\n        localfile = url2pathname(filename)\n        try:\n            stats = os.stat(localfile)\n            size = stats.st_size\n            modified = email.utils.formatdate(stats.st_mtime, usegmt=True)\n            mtype = mimetypes.guess_type(filename)[0]\n            headers = email.message_from_string(\n                'Content-type: %s\\nContent-length: %d\\nLast-modified: %s\\n' %\n                (mtype or 'text/plain', size, modified))\n            if host:\n                host, port = splitport(host)\n            if not host or \\\n                (not port and _safe_gethostbyname(host) in self.get_names()):\n                if host:\n                    origurl = 'file://' + host + filename\n                else:\n                    origurl = 'file://' + filename\n                return addinfourl(open(localfile, 'rb'), headers, origurl)\n        except OSError as exp:\n>           raise URLError(exp)\nE           urllib.error.URLError: <urlopen error [Errno 2] No such file or directory: '/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_f3b183551b877f025889242567b0451e1a92a2ea/r2e_tests/test1.tab'>\n\n../../../../.local/share/uv/python/cpython-3.7.9-linux-x86_64-gnu/lib/python3.7/urllib/request.py:1523: URLError\n==================================== PASSES ====================================\n=========================== short test summary info ============================\nPASSED r2e_tests/test_1.py::test_dirname\nPASSED r2e_tests/test_1.py::TableTestCase::test_assign_multiple_indices_value\nPASSED r2e_tests/test_1.py::TableTestCase::test_assign_slice_value\nPASSED r2e_tests/test_1.py::TableTestCase::test_attributes\nPASSED r2e_tests/test_1.py::TableTestCase::test_bool\nPASSED r2e_tests/test_1.py::TableTestCase::test_checksum\nPASSED r2e_tests/test_1.py::TableTestCase::test_concatenate\nPASSED r2e_tests/test_1.py::TableTestCase::test_copy\nPASSED r2e_tests/test_1.py::TableTestCase::test_copy_sparse\nPASSED r2e_tests/test_1.py::TableTestCase::test_filename\nPASSED r2e_tests/test_1.py::TableTestCase::test_filter_has_class\nPASSED r2e_tests/test_1.py::TableTestCase::test_filter_is_defined\nPASSED r2e_tests/test_1.py::TableTestCase::test_filter_random\nPASSED r2e_tests/test_1.py::TableTestCase::test_filter_string_works_for_numeric_columns\nPASSED r2e_tests/test_1.py::TableTestCase::test_filter_value_continuous\nPASSED r2e_tests/test_1.py::TableTestCase::test_filter_value_continuous_args\nPASSED r2e_tests/test_1.py::TableTestCase::test_filter_values_nested\nPASSED r2e_tests/test_1.py::TableTestCase::test_from_numpy\nPASSED r2e_tests/test_1.py::TableTestCase::test_has_missing\nPASSED r2e_tests/test_1.py::TableTestCase::test_indexing\nPASSED r2e_tests/test_1.py::TableTestCase::test_indexing_assign_example\nPASSED r2e_tests/test_1.py::TableTestCase::test_indexing_assign_value\nPASSED r2e_tests/test_1.py::TableTestCase::test_indexing_class\nPASSED r2e_tests/test_1.py::TableTestCase::test_indexing_example\nPASSED r2e_tests/test_1.py::TableTestCase::test_is_sparse\nPASSED r2e_tests/test_1.py::TableTestCase::test_multiple_indices\nPASSED r2e_tests/test_1.py::TableTestCase::test_pickle\nPASSED r2e_tests/test_1.py::TableTestCase::test_repr_sparse_with_one_row\nPASSED r2e_tests/test_1.py::TableTestCase::test_saveTab\nPASSED r2e_tests/test_1.py::TableTestCase::test_save_pickle\nPASSED r2e_tests/test_1.py::TableTestCase::test_set_multiple_indices_example\nPASSED r2e_tests/test_1.py::TableTestCase::test_shuffle\nPASSED r2e_tests/test_1.py::TableTestCase::test_slice\nPASSED r2e_tests/test_1.py::TableTestCase::test_sparse_concatenate_rows\nPASSED r2e_tests/test_1.py::TableTestCase::test_table_dtypes\nPASSED r2e_tests/test_1.py::TableTestCase::test_total_weight\nPASSED r2e_tests/test_1.py::TableTestCase::test_translate_through_slice\nPASSED r2e_tests/test_1.py::TableTestCase::test_valueFilter_discrete\nPASSED r2e_tests/test_1.py::TableTestCase::test_valueFilter_discrete_meta_is_defined\nPASSED r2e_tests/test_1.py::TableTestCase::test_valueFilter_regex\nPASSED r2e_tests/test_1.py::TableTestCase::test_valueFilter_stringList\nPASSED r2e_tests/test_1.py::TableTestCase::test_valueFilter_string_case_insens\nPASSED r2e_tests/test_1.py::TableTestCase::test_valueFilter_string_case_sens\nPASSED r2e_tests/test_1.py::TableTestCase::test_valueFilter_string_is_defined\nPASSED r2e_tests/test_1.py::CreateEmptyTable::test_calling_new_with_no_parameters_constructs_a_new_instance\nPASSED r2e_tests/test_1.py::CreateEmptyTable::test_table_has_file\nPASSED r2e_tests/test_1.py::CreateTableWithFilename::test_calling_new_with_keyword_argument_filename_calls_read_data\nPASSED r2e_tests/test_1.py::CreateTableWithFilename::test_calling_new_with_string_argument_calls_read_data\nPASSED r2e_tests/test_1.py::CreateTableWithFilename::test_raises_error_if_file_does_not_exist\nPASSED r2e_tests/test_1.py::CreateTableWithFilename::test_raises_error_if_file_has_unknown_extension\nPASSED r2e_tests/test_1.py::CreateTableWithFilename::test_read_data_calls_reader\nPASSED r2e_tests/test_1.py::CreateTableWithUrl::test_trimmed_urls\nPASSED r2e_tests/test_1.py::CreateTableWithUrl::test_url_no_scheme\nPASSED r2e_tests/test_1.py::CreateTableWithDomain::test_calling_new_with_domain_calls_new_from_domain\nPASSED r2e_tests/test_1.py::CreateTableWithDomain::test_creates_an_empty_table_with_given_domain\nPASSED r2e_tests/test_1.py::CreateTableWithDomain::test_creates_weights_if_weights_are_true\nPASSED r2e_tests/test_1.py::CreateTableWithDomain::test_creates_zero_filled_rows_in_X_if_domain_contains_attributes\nPASSED r2e_tests/test_1.py::CreateTableWithDomain::test_creates_zero_filled_rows_in_Y_if_domain_contains_class_vars\nPASSED r2e_tests/test_1.py::CreateTableWithDomain::test_creates_zero_filled_rows_in_metas_if_domain_contains_metas\nPASSED r2e_tests/test_1.py::CreateTableWithDomain::test_does_not_create_weights_if_weights_are_false\nPASSED r2e_tests/test_1.py::CreateTableWithData::test_calling_new_with_domain_and_numpy_arrays_calls_new_from_numpy\nPASSED r2e_tests/test_1.py::CreateTableWithData::test_creates_a_discrete_class_if_Y_has_few_distinct_values\nPASSED r2e_tests/test_1.py::CreateTableWithData::test_creates_a_table_from_domain_and_list\nPASSED r2e_tests/test_1.py::CreateTableWithData::test_creates_a_table_from_domain_and_list_and_metas\nPASSED r2e_tests/test_1.py::CreateTableWithData::test_creates_a_table_from_domain_and_list_and_weights\nPASSED r2e_tests/test_1.py::CreateTableWithData::test_creates_a_table_from_list_of_instances\nPASSED r2e_tests/test_1.py::CreateTableWithData::test_creates_a_table_from_list_of_instances_with_metas\nPASSED r2e_tests/test_1.py::CreateTableWithData::test_creates_a_table_with_domain_and_given_X\nPASSED r2e_tests/test_1.py::CreateTableWithData::test_creates_a_table_with_given_X\nPASSED r2e_tests/test_1.py::CreateTableWithData::test_creates_a_table_with_given_X_Y_and_metas\nPASSED r2e_tests/test_1.py::CreateTableWithData::test_creates_a_table_with_given_X_and_Y\nPASSED r2e_tests/test_1.py::CreateTableWithData::test_creates_a_table_with_given_domain\nPASSED r2e_tests/test_1.py::CreateTableWithData::test_from_numpy_reconstructable\nPASSED r2e_tests/test_1.py::CreateTableWithData::test_initializes_Y_metas_and_W_if_not_given\nPASSED r2e_tests/test_1.py::CreateTableWithData::test_raises_error_if_columns_in_domain_and_data_do_not_match\nPASSED r2e_tests/test_1.py::CreateTableWithData::test_raises_error_if_lengths_of_data_do_not_match\nPASSED r2e_tests/test_1.py::CreateTableWithData::test_sets_Y_if_given\nPASSED r2e_tests/test_1.py::CreateTableWithData::test_sets_metas_if_given\nPASSED r2e_tests/test_1.py::CreateTableWithData::test_sets_weights_if_given\nPASSED r2e_tests/test_1.py::CreateTableWithData::test_splits_X_and_Y_if_given_in_same_array\nPASSED r2e_tests/test_1.py::CreateTableWithDomainAndTable::test_can_copy_table\nPASSED r2e_tests/test_1.py::CreateTableWithDomainAndTable::test_can_filter_row_with_slice\nPASSED r2e_tests/test_1.py::CreateTableWithDomainAndTable::test_can_filter_rows_with_list\nPASSED r2e_tests/test_1.py::CreateTableWithDomainAndTable::test_can_use_attributes_as_new_columns\nPASSED r2e_tests/test_1.py::CreateTableWithDomainAndTable::test_can_use_class_vars_as_new_columns\nPASSED r2e_tests/test_1.py::CreateTableWithDomainAndTable::test_can_use_combination_of_all_as_new_columns\nPASSED r2e_tests/test_1.py::CreateTableWithDomainAndTable::test_can_use_metas_as_new_columns\nPASSED r2e_tests/test_1.py::CreateTableWithDomainAndTable::test_creates_table_with_given_domain\nPASSED r2e_tests/test_1.py::CreateTableWithDomainAndTable::test_creates_table_with_given_domain_and_row_filter\nPASSED r2e_tests/test_1.py::CreateTableWithDomainAndTable::test_from_table_sparse_move_all_to_empty_metas\nPASSED r2e_tests/test_1.py::CreateTableWithDomainAndTable::test_from_table_sparse_move_some_to_empty_metas\nPASSED r2e_tests/test_1.py::CreateTableWithDomainAndTable::test_from_table_sparse_move_to_nonempty_metas\nPASSED r2e_tests/test_1.py::CreateTableWithDomainAndTable::test_transform\nPASSED r2e_tests/test_1.py::CreateTableWithDomainAndTable::test_transform_same_domain\nPASSED r2e_tests/test_1.py::TableIndexingTests::test_can_select_a_single_row\nPASSED r2e_tests/test_1.py::TableIndexingTests::test_can_select_a_single_value\nPASSED r2e_tests/test_1.py::TableIndexingTests::test_can_select_a_subset_of_rows_and_columns\nPASSED r2e_tests/test_1.py::TableIndexingTests::test_optimize_indices\nPASSED r2e_tests/test_1.py::TableElementAssignmentTest::test_can_assign_lists\nPASSED r2e_tests/test_1.py::TableElementAssignmentTest::test_can_assign_np_array\nPASSED r2e_tests/test_1.py::TableElementAssignmentTest::test_can_assign_rows_to_rows\nPASSED r2e_tests/test_1.py::TableElementAssignmentTest::test_can_assign_values\nPASSED r2e_tests/test_1.py::TableElementAssignmentTest::test_can_assign_values_to_classes\nPASSED r2e_tests/test_1.py::TableElementAssignmentTest::test_can_assign_values_to_metas\nPASSED r2e_tests/test_1.py::InterfaceTest::test_iteration\nPASSED r2e_tests/test_1.py::InterfaceTest::test_len\nPASSED r2e_tests/test_1.py::InterfaceTest::test_row_assignment\nPASSED r2e_tests/test_1.py::InterfaceTest::test_row_indexing\nPASSED r2e_tests/test_1.py::InterfaceTest::test_row_len\nPASSED r2e_tests/test_1.py::InterfaceTest::test_row_slicing\nPASSED r2e_tests/test_1.py::InterfaceTest::test_value_assignment\nPASSED r2e_tests/test_1.py::InterfaceTest::test_value_indexing\nPASSED r2e_tests/test_1.py::TestTableStats::test_get_nan_frequency\nPASSED r2e_tests/test_1.py::TestTableStats::test_get_nan_frequency_empty_table\nPASSED r2e_tests/test_1.py::TestRowInstance::test_assignment\nPASSED r2e_tests/test_1.py::TestRowInstance::test_iteration_with_assignment\nPASSED r2e_tests/test_1.py::TestRowInstance::test_sparse_assignment\nPASSED r2e_tests/test_1.py::TestTableTranspose::test_transpose\nPASSED r2e_tests/test_1.py::TestTableTranspose::test_transpose_attributes_of_attributes_continuous\nPASSED r2e_tests/test_1.py::TestTableTranspose::test_transpose_attributes_of_attributes_discrete\nPASSED r2e_tests/test_1.py::TestTableTranspose::test_transpose_attributes_of_attributes_missings\nPASSED r2e_tests/test_1.py::TestTableTranspose::test_transpose_class_and_metas\nPASSED r2e_tests/test_1.py::TestTableTranspose::test_transpose_class_metas_attributes\nPASSED r2e_tests/test_1.py::TestTableTranspose::test_transpose_continuous_class\nPASSED r2e_tests/test_1.py::TestTableTranspose::test_transpose_continuous_metas\nPASSED r2e_tests/test_1.py::TestTableTranspose::test_transpose_discrete_class\nPASSED r2e_tests/test_1.py::TestTableTranspose::test_transpose_discrete_metas\nPASSED r2e_tests/test_1.py::TestTableTranspose::test_transpose_metas\nPASSED r2e_tests/test_1.py::TestTableTranspose::test_transpose_missing_class\nPASSED r2e_tests/test_1.py::TestTableTranspose::test_transpose_missing_metas\nPASSED r2e_tests/test_1.py::TestTableTranspose::test_transpose_multiple_class\nPASSED r2e_tests/test_1.py::TestTableTranspose::test_transpose_multiple_metas\nPASSED r2e_tests/test_1.py::TestTableTranspose::test_transpose_no_class\nPASSED r2e_tests/test_1.py::TestTableSparseDense::test_from_table_add_lots_of_sparse_columns\nPASSED r2e_tests/test_1.py::TestTableSparseDense::test_from_table_add_one_sparse_column\nPASSED r2e_tests/test_1.py::TestTableSparseDense::test_from_table_replace_attrs_with_sparse\nPASSED r2e_tests/test_1.py::TestTableSparseDense::test_from_table_sparse_metas\nPASSED r2e_tests/test_1.py::TestTableSparseDense::test_from_table_sparse_metas_with_strings\nPASSED r2e_tests/test_1.py::TestTableSparseDense::test_sparse_dense_transformation\nSKIPPED [1] r2e_tests/test_1.py:589: Method test_append will be deprecated; tests are skipped because it already fails on Python 3.7 on travis\nSKIPPED [1] r2e_tests/test_1.py:605: Method test_append2 will be deprecated; tests are skipped because it already fails on Python 3.7 on travis\nSKIPPED [1] r2e_tests/test_1.py:710: Method test_convert_through_append will be deprecated; tests are skipped because it already fails on Python 3.7 on travis\nSKIPPED [1] r2e_tests/test_1.py:439: Method test_del_multiple_indices_example will be deprecated; tests are skipped because it already fails on Python 3.7 on travis\nSKIPPED [1] r2e_tests/test_1.py:360: Method test_del_slice_example will be deprecated; tests are skipped because it already fails on Python 3.7 on travis\nSKIPPED [1] r2e_tests/test_1.py:380: Method test_del_slice_ids will be deprecated; tests are skipped because it already fails on Python 3.7 on travis\nSKIPPED [1] r2e_tests/test_1.py:623: Method test_extend will be deprecated; tests are skipped because it already fails on Python 3.7 on travis\nSKIPPED [1] r2e_tests/test_1.py:640: Method test_extend2 will be deprecated; tests are skipped because it already fails on Python 3.7 on travis\nSKIPPED [1] r2e_tests/test_1.py:223: Method test_indexing_del_example will be deprecated; tests are skipped because it already fails on Python 3.7 on travis\nSKIPPED [1] r2e_tests/test_1.py:388: Method test_set_slice_example will be deprecated; tests are skipped because it already fails on Python 3.7 on travis\nSKIPPED [1] r2e_tests/test_1.py:471: Method test_views will be deprecated; tests are skipped because it already fails on Python 3.7 on travis\nSKIPPED [1] r2e_tests/test_1.py:2222: Method test_append_rows will be deprecated; tests are skipped because it already fails on Python 3.7 on travis\nSKIPPED [1] r2e_tests/test_1.py:2255: Method test_clear will be deprecated; tests are skipped because it already fails on Python 3.7 on travis\nSKIPPED [1] r2e_tests/test_1.py:2248: Method test_delete_rows will be deprecated; tests are skipped because it already fails on Python 3.7 on travis\nSKIPPED [1] r2e_tests/test_1.py:2229: Method test_insert_rows will be deprecated; tests are skipped because it already fails on Python 3.7 on travis\nSKIPPED [1] r2e_tests/test_1.py:2238: Method test_insert_view will be deprecated; tests are skipped because it already fails on Python 3.7 on travis\nFAILED r2e_tests/test_1.py::TableTestCase::test_inf - ValueError: Array conta...\nFAILED r2e_tests/test_1.py::InterfaceTest::test_subclasses - urllib.error.URL...\n================== 2 failed, 139 passed, 16 skipped in 2.80s ===================\n",
    "old_commit_res_stderr": ""
}
Orange/data/table.py Orange/tests/test_table.py
We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
**Analysis:**

- **Key Parts of Commit Details and Test Results:**
  - **Commit Message:** "Table.from_numpy: Replace infs with nans.."
  - **Commit Patch:** Modifies the `_check_arrays` function to replace infinite values with NaNs and issue a warning instead of raising a `ValueError`.
  - **Added Test (`test_inf`):** Checks that creating a `Table` with an array containing infinities issues a warning and correctly calculates the frequency of NaNs.
  - **Test Results:**
    - **Old Commit:** The test failed with `ValueError: Array contains infinity.`
    - **New Commit:** The test passes, indicating successful handling of infinite values.

- **Main Problem Highlighted by Test Results:**
  The `Table.from_numpy` function does not handle arrays containing infinite values appropriately, causing a `ValueError` and preventing the creation of the table.

- **Expected Behavior:**
  When provided with an array containing infinite values, the function should replace these infinities with NaNs, issue a runtime warning about the presence of infinities, and successfully create the table with accurate NaN frequency attributes.

- **Actual Behavior:**
  The function raises a `ValueError` with the message "Array contains infinity," stopping the table creation process.

- **Issue Description:**
  The `Table.from_numpy` function fails to handle arrays with infinite values by raising an error instead of managing them gracefully.

---

[ISSUE]
**Title:** Table.from_numpy Raises ValueError When Array Contains Infinities

**Description:**
When attempting to create a `Table` from a numpy array that includes infinite values, the `Table.from_numpy` function raises a `ValueError` instead of handling the infinities by replacing them with NaNs and issuing a warning.

**Example Code:**
```python
import numpy as np
from Orange.data import Table

def create_table_with_infinities():
    a = np.array([
        [2, 0, 0, 0],
        [0, np.nan, np.nan, 1],
        [0, 0, np.inf, 0]
    ])
    tab = Table(a)
```

**Expected Behavior:**
Infinite values in the input array should be replaced with NaNs. Additionally, a runtime warning should be issued to notify the user about the presence of infinity values. The table creation should complete successfully, correctly reflecting the NaN frequency attributes.

**Actual Behavior:**
Executing the above code results in a `ValueError` with the message "Array contains infinity," preventing the `Table` from being created.

[/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/data/table.py
import operator
import os
import warnings
import zlib
from collections import MutableSequence, Iterable, Sequence, Sized
from functools import reduce
from itertools import chain
from numbers import Real, Integral
from threading import Lock, RLock

import bottleneck as bn
import numpy as np
from scipy import sparse as sp

import Orange.data  # import for io.py
from Orange.data import (
    _contingency, _valuecount,
    Domain, Variable, Storage, StringVariable, Unknown, Value, Instance,
    ContinuousVariable, DiscreteVariable, MISSING_VALUES
)
from Orange.data.util import SharedComputeValue, vstack, hstack, \
    assure_array_dense, assure_array_sparse, \
    assure_column_dense, assure_column_sparse
from Orange.statistics.util import bincount, countnans, contingency, \
    stats as fast_stats, sparse_has_implicit_zeros, sparse_count_implicit_zeros, \
    sparse_implicit_zero_weights
from Orange.util import flatten

__all__ = ["dataset_dirs", "get_sample_datasets_dir", "RowInstance", "Table"]


def get_sample_datasets_dir():
    orange_data_table = os.path.dirname(__file__)
    dataset_dir = os.path.join(orange_data_table, '..', 'datasets')
    return os.path.realpath(dataset_dir)


dataset_dirs = ['', get_sample_datasets_dir()]


"""Domain conversion cache used in Table.from_table. It is global so that
chaining of domain conversions also works with caching even with descendants
of Table."""
_conversion_cache = None
_conversion_cache_lock = RLock()


def pending_deprecation_resize(name):
    warnings.warn(f"Method Table.{name} will be removed in Orange 3.24",
                  PendingDeprecationWarning)


class DomainTransformationError(Exception):
    pass


class RowInstance(Instance):
    sparse_x = None
    sparse_y = None
    sparse_metas = None
    _weight = None

    def __init__(self, table, row_index):
        """
        Construct a data instance representing the given row of the table.
        """
        self.table = table
        self._domain = table.domain
        self.row_index = row_index
        self.id = table.ids[row_index]
        self._x = table.X[row_index]
        if sp.issparse(self._x):
            self.sparse_x = sp.csr_matrix(self._x)
            self._x = np.asarray(self._x.todense())[0]
        self._y = table._Y[row_index]
        if sp.issparse(self._y):
            self.sparse_y = sp.csr_matrix(self._y)
            self._y = np.asarray(self._y.todense())[0]
        self._metas = table.metas[row_index]
        if sp.issparse(self._metas):
            self.sparse_metas = sp.csr_matrix(self._metas)
            self._metas = np.asarray(self._metas.todense())[0]

    @property
    def weight(self):
        if not self.table.has_weights():
            return 1
        return self.table.W[self.row_index]

    @weight.setter
    def weight(self, weight):
        if not self.table.has_weights():
            self.table.set_weights()
        self.table.W[self.row_index] = weight

    def set_class(self, value):
        self._check_single_class()
        if not isinstance(value, Real):
            value = self.table.domain.class_var.to_val(value)
        self._y[0] = value
        if self.sparse_y:
            self.table._Y[self.row_index, 0] = value

    def __setitem__(self, key, value):
        if not isinstance(key, Integral):
            key = self._domain.index(key)
        if isinstance(value, str):
            var = self._domain[key]
            value = var.to_val(value)
        if key >= 0:
            if not isinstance(value, Real):
                raise TypeError("Expected primitive value, got '%s'" %
                                type(value).__name__)
            if key < len(self._x):
                self._x[key] = value
                if self.sparse_x is not None:
                    self.table.X[self.row_index, key] = value
            else:
                self._y[key - len(self._x)] = value
                if self.sparse_y is not None:
                    self.table._Y[self.row_index, key - len(self._x)] = value
        else:
            self._metas[-1 - key] = value
            if self.sparse_metas:
                self.table.metas[self.row_index, -1 - key] = value

    def _str(self, limit):
        def sp_values(matrix, variables):
            if not sp.issparse(matrix):
                if matrix.ndim == 1:
                    matrix = matrix[:, np.newaxis]
                return Instance.str_values(matrix[row], variables, limit)

            row_entries, idx = [], 0
            while idx < len(variables):
                # Make sure to stop printing variables if we limit the output
                if limit and len(row_entries) >= 5:
                    break

                var = variables[idx]
                if var.is_discrete or matrix[row, idx]:
                    row_entries.append("%s=%s" % (var.name, var.str_val(matrix[row, idx])))

                idx += 1

            s = ", ".join(row_entries)

            if limit and idx < len(variables):
                s += ", ..."

            return s

        table = self.table
        domain = table.domain
        row = self.row_index
        s = "[" + sp_values(table.X, domain.attributes)
        if domain.class_vars:
            s += " | " + sp_values(table.Y, domain.class_vars)
        s += "]"
        if self._domain.metas:
            s += " {" + sp_values(table.metas, domain.metas) + "}"
        return s

    def __str__(self):
        return self._str(False)

    def __repr__(self):
        return self._str(True)


class Columns:
    def __init__(self, domain):
        for v in chain(domain.variables, domain.metas):
            setattr(self, v.name.replace(" ", "_"), v)


# noinspection PyPep8Naming
class Table(MutableSequence, Storage):
    __file__ = None
    name = "untitled"

    @property
    def columns(self):
        """
        A class whose attributes contain attribute descriptors for columns.
        For a table `table`, setting `c = table.columns` will allow accessing
        the table's variables with, for instance `c.gender`, `c.age` ets.
        Spaces are replaced with underscores.
        """
        return Columns(self.domain)

    _next_instance_id = 0
    _next_instance_lock = Lock()

    @property
    def Y(self):
        if self._Y.shape[1] == 1:
            return self._Y[:, 0]
        return self._Y

    @Y.setter
    def Y(self, value):
        if len(value.shape) == 1:
            value = value[:, None]
        if sp.issparse(value) and len(self) != value.shape[0]:
            value = value.T
        self._Y = value

    def __new__(cls, *args, **kwargs):
        if not args and not kwargs:
            return super().__new__(cls)

        if 'filename' in kwargs:
            args = [kwargs.pop('filename')]

        if not args:
            raise TypeError(
                "Table takes at least 1 positional argument (0 given))")

        if isinstance(args[0], str):
            if args[0].startswith('https://') or args[0].startswith('http://'):
                return cls.from_url(args[0], **kwargs)
            else:
                return cls.from_file(args[0])
        elif isinstance(args[0], Table):
            return cls.from_table(args[0].domain, args[0])
        elif isinstance(args[0], Domain):
            domain, args = args[0], args[1:]
            if not args:
                return cls.from_domain(domain, **kwargs)
            if isinstance(args[0], Table):
                return cls.from_table(domain, *args)
            elif isinstance(args[0], list):
                return cls.from_list(domain, *args)
        else:
            domain = None

        return cls.from_numpy(domain, *args, **kwargs)

    def __init__(self, *args, **kwargs):
        # So subclasses can expect to call super without breakage; noop
        pass

    @classmethod
    def from_domain(cls, domain, n_rows=0, weights=False):
        """
        Construct a new `Table` with the given number of rows for the given
        domain. The optional vector of weights is initialized to 1's.

        :param domain: domain for the `Table`
        :type domain: Orange.data.Domain
        :param n_rows: number of rows in the new table
        :type n_rows: int
        :param weights: indicates whether to construct a vector of weights
        :type weights: bool
        :return: a new table
        :rtype: Orange.data.Table
        """
        self = cls()
        self.domain = domain
        self.n_rows = n_rows
        self.X = np.zeros((n_rows, len(domain.attributes)))
        self.Y = np.zeros((n_rows, len(domain.class_vars)))
        if weights:
            self.W = np.ones(n_rows)
        else:
            self.W = np.empty((n_rows, 0))
        self.metas = np.empty((n_rows, len(self.domain.metas)), object)
        cls._init_ids(self)
        self.attributes = {}
        return self

    @classmethod
    def from_table(cls, domain, source, row_indices=...):
        """
        Create a new table from selected columns and/or rows of an existing
        one. The columns are chosen using a domain. The domain may also include
        variables that do not appear in the source table; they are computed
        from source variables if possible.

        The resulting data may be a view or a copy of the existing data.

        :param domain: the domain for the new table
        :type domain: Orange.data.Domain
        :param source: the source table
        :type source: Orange.data.Table
        :param row_indices: indices of the rows to include
        :type row_indices: a slice or a sequence
        :return: a new table
        :rtype: Orange.data.Table
        """

        global _conversion_cache

        def get_columns(row_indices, src_cols, n_rows, dtype=np.float64, is_sparse=False):
            if not len(src_cols):
                if is_sparse:
                    return sp.csr_matrix((n_rows, 0), dtype=source.X.dtype)
                else:
                    return np.zeros((n_rows, 0), dtype=source.X.dtype)

            # match density for subarrays
            match_density = assure_array_sparse if is_sparse else assure_array_dense
            n_src_attrs = len(source.domain.attributes)
            if all(isinstance(x, Integral) and 0 <= x < n_src_attrs
                   for x in src_cols):
                return match_density(_subarray(source.X, row_indices, src_cols))
            if all(isinstance(x, Integral) and x < 0 for x in src_cols):
                arr = match_density(_subarray(source.metas, row_indices,
                                              [-1 - x for x in src_cols]))
                if arr.dtype != dtype:
                    return arr.astype(dtype)
                return arr
            if all(isinstance(x, Integral) and x >= n_src_attrs
                   for x in src_cols):
                return match_density(_subarray(
                    source._Y, row_indices,
                    [x - n_src_attrs for x in src_cols]))

            # initialize final array & set `match_density` for columns
            if is_sparse:
                a = sp.dok_matrix((n_rows, len(src_cols)), dtype=dtype)
                match_density = assure_column_sparse
            else:
                a = np.empty((n_rows, len(src_cols)), dtype=dtype)
                match_density = assure_column_dense

            shared_cache = _conversion_cache
            for i, col in enumerate(src_cols):
                if col is None:
                    a[:, i] = Unknown
                elif not isinstance(col, Integral):
                    if isinstance(col, SharedComputeValue):
                        if (id(col.compute_shared), id(source)) not in shared_cache:
                            shared_cache[id(col.compute_shared), id(source)] = \
                                col.compute_shared(source)
                        shared = shared_cache[id(col.compute_shared), id(source)]
                        if row_indices is not ...:
                            a[:, i] = match_density(
                                col(source, shared_data=shared)[row_indices])
                        else:
                            a[:, i] = match_density(
                                col(source, shared_data=shared))
                    else:
                        if row_indices is not ...:
                            a[:, i] = match_density(col(source)[row_indices])
                        else:
                            a[:, i] = match_density(col(source))
                elif col < 0:
                    a[:, i] = match_density(source.metas[row_indices, -1 - col])
                elif col < n_src_attrs:
                    a[:, i] = match_density(source.X[row_indices, col])
                else:
                    a[:, i] = match_density(
                        source._Y[row_indices, col - n_src_attrs])

            if is_sparse:
                a = a.tocsr()

            return a

        with _conversion_cache_lock:
            new_cache = _conversion_cache is None
            try:
                if new_cache:
                    _conversion_cache = {}
                else:
                    cached = _conversion_cache.get((id(domain), id(source)))
                    if cached:
                        return cached
                if domain == source.domain:
                    table = cls.from_table_rows(source, row_indices)
                    # assure resulting domain is the instance passed on input
                    table.domain = domain
                    # since sparse flags are not considered when checking for
                    # domain equality, fix manually.
                    table = assure_domain_conversion_sparsity(table, source)
                    return table

                if isinstance(row_indices, slice):
                    start, stop, stride = row_indices.indices(source.X.shape[0])
                    n_rows = (stop - start) // stride
                    if n_rows < 0:
                        n_rows = 0
                elif row_indices is ...:
                    n_rows = len(source)
                else:
                    n_rows = len(row_indices)

                self = cls()
                self.domain = domain
                conversion = domain.get_conversion(source.domain)
                self.X = get_columns(row_indices, conversion.attributes, n_rows,
                                     is_sparse=conversion.sparse_X)
                if self.X.ndim == 1:
                    self.X = self.X.reshape(-1, len(self.domain.attributes))

                self.Y = get_columns(row_indices, conversion.class_vars, n_rows,
                                     is_sparse=conversion.sparse_Y)

                dtype = np.float64
                if any(isinstance(var, StringVariable) for var in domain.metas):
                    dtype = np.object
                self.metas = get_columns(row_indices, conversion.metas,
                                         n_rows, dtype,
                                         is_sparse=conversion.sparse_metas)
                if self.metas.ndim == 1:
                    self.metas = self.metas.reshape(-1, len(self.domain.metas))
                if source.has_weights():
                    self.W = source.W[row_indices]
                else:
                    self.W = np.empty((n_rows, 0))
                self.name = getattr(source, 'name', '')
                if hasattr(source, 'ids'):
                    self.ids = source.ids[row_indices]
                else:
                    cls._init_ids(self)
                self.attributes = getattr(source, 'attributes', {})
                _conversion_cache[(id(domain), id(source))] = self
                return self
            finally:
                if new_cache:
                    _conversion_cache = None

    def transform(self, domain):
        """
        Construct a table with a different domain.

        The new table keeps the row ids and other information. If the table
        is a subclass of :obj:`Table`, the resulting table will be of the same
        type.

        In a typical scenario, an existing table is augmented with a new
        column by ::

            domain = Domain(old_domain.attributes + [new_attribute],
                            old_domain.class_vars,
                            old_domain.metas)
            table = data.transform(domain)
            table[:, new_attribute] = new_column

        Args:
            domain (Domain): new domain

        Returns:
            A new table
        """
        return type(self).from_table(domain, self)

    @classmethod
    def from_table_rows(cls, source, row_indices):
        """
        Construct a new table by selecting rows from the source table.

        :param source: an existing table
        :type source: Orange.data.Table
        :param row_indices: indices of the rows to include
        :type row_indices: a slice or a sequence
        :return: a new table
        :rtype: Orange.data.Table
        """
        self = cls()
        self.domain = source.domain
        self.X = source.X[row_indices]
        if self.X.ndim == 1:
            self.X = self.X.reshape(-1, len(self.domain.attributes))
        self.Y = source._Y[row_indices]
        self.metas = source.metas[row_indices]
        if self.metas.ndim == 1:
            self.metas = self.metas.reshape(-1, len(self.domain.metas))
        self.W = source.W[row_indices]
        self.name = getattr(source, 'name', '')
        self.ids = np.array(source.ids[row_indices])
        self.attributes = getattr(source, 'attributes', {})
        return self

    @classmethod
    def from_numpy(cls, domain, X, Y=None, metas=None, W=None):
        """
        Construct a table from numpy arrays with the given domain. The number
        of variables in the domain must match the number of columns in the
        corresponding arrays. All arrays must have the same number of rows.
        Arrays may be of different numpy types, and may be dense or sparse.

        :param domain: the domain for the new table
        :type domain: Orange.data.Domain
        :param X: array with attribute values
        :type X: np.array
        :param Y: array with class values
        :type Y: np.array
        :param metas: array with meta attributes
        :type metas: np.array
        :param W: array with weights
        :type W: np.array
        :return:
        """
        X, Y, W = _check_arrays(X, Y, W, dtype='float64')
        metas, = _check_arrays(metas, dtype=object)

        if Y is not None and Y.ndim == 1:
            Y = Y.reshape(Y.shape[0], 1)
        if domain is None:
            domain = Domain.from_numpy(X, Y, metas)

        if Y is None:
            if sp.issparse(X):
                Y = np.empty((X.shape[0], 0), dtype=np.float64)
            else:
                Y = X[:, len(domain.attributes):]
                X = X[:, :len(domain.attributes)]
        if metas is None:
            metas = np.empty((X.shape[0], 0), object)
        if W is None or W.size == 0:
            W = np.empty((X.shape[0], 0))
        else:
            W = W.reshape(W.size)

        if X.shape[1] != len(domain.attributes):
            raise ValueError(
                "Invalid number of variable columns ({} != {})".format(
                    X.shape[1], len(domain.attributes))
            )
        if Y.shape[1] != len(domain.class_vars):
            raise ValueError(
                "Invalid number of class columns ({} != {})".format(
                    Y.shape[1], len(domain.class_vars))
            )
        if metas.shape[1] != len(domain.metas):
            raise ValueError(
                "Invalid number of meta attribute columns ({} != {})".format(
                    metas.shape[1], len(domain.metas))
            )
        if not X.shape[0] == Y.shape[0] == metas.shape[0] == W.shape[0]:
            raise ValueError(
                "Parts of data contain different numbers of rows.")

        self = cls()
        self.domain = domain
        self.X = X
        self.Y = Y
        self.metas = metas
        self.W = W
        self.n_rows = self.X.shape[0]
        cls._init_ids(self)
        self.attributes = {}
        return self

    @classmethod
    def from_list(cls, domain, rows, weights=None):
        if weights is not None and len(rows) != len(weights):
            raise ValueError("mismatching number of instances and weights")
        self = cls.from_domain(domain, len(rows), weights is not None)
        attrs, classes = domain.attributes, domain.class_vars
        metas = domain.metas
        nattrs, ncls = len(domain.attributes), len(domain.class_vars)
        for i, row in enumerate(rows):
            if isinstance(row, Instance):
                row = row.list
            for j, (var, val) in enumerate(zip(attrs, row)):
                self.X[i, j] = var.to_val(val)
            for j, (var, val) in enumerate(zip(classes, row[nattrs:])):
                self._Y[i, j] = var.to_val(val)
            for j, (var, val) in enumerate(zip(metas, row[nattrs + ncls:])):
                self.metas[i, j] = var.to_val(val)
        if weights is not None:
            self.W = np.array(weights)
        self.attributes = {}
        return self

    @classmethod
    def _init_ids(cls, obj):
        with cls._next_instance_lock:
            obj.ids = np.array(range(cls._next_instance_id, cls._next_instance_id + obj.X.shape[0]))
            cls._next_instance_id += obj.X.shape[0]

    @classmethod
    def new_id(cls):
        with cls._next_instance_lock:
            id = cls._next_instance_id
            cls._next_instance_id += 1
            return id

    def save(self, filename):
        """
        Save a data table to a file. The path can be absolute or relative.

        :param filename: File name
        :type filename: str
        """
        ext = os.path.splitext(filename)[1]
        from Orange.data.io import FileFormat
        writer = FileFormat.writers.get(ext)
        if not writer:
            desc = FileFormat.names.get(ext)
            if desc:
                raise IOError(
                    "Writing of {}s is not supported".format(desc.lower()))
            else:
                raise IOError("Unknown file name extension.")
        writer.write_file(filename, self)

    @classmethod
    def from_file(cls, filename, sheet=None):
        """
        Read a data table from a file. The path can be absolute or relative.

        :param filename: File name
        :type filename: str
        :param sheet: Sheet in a file (optional)
        :type sheet: str
        :return: a new data table
        :rtype: Orange.data.Table
        """
        from Orange.data.io import FileFormat

        absolute_filename = FileFormat.locate(filename, dataset_dirs)
        reader = FileFormat.get_reader(absolute_filename)
        reader.select_sheet(sheet)
        data = reader.read()

        # Readers return plain table. Make sure to cast it to appropriate
        # (subclass) type
        if cls != data.__class__:
            data = cls(data)

        # no need to call _init_ids as fuctions from .io already
        # construct a table with .ids

        data.__file__ = absolute_filename
        return data

    @classmethod
    def from_url(cls, url):
        from Orange.data.io import UrlReader
        reader = UrlReader(url)
        data = reader.read()
        if cls != data.__class__:
            data = cls(data)
        return data

    # Helper function for __setitem__ and insert:
    # Set the row of table data matrices
    # noinspection PyProtectedMember
    def _set_row(self, example, row):
        domain = self.domain
        if isinstance(example, Instance):
            if example.domain == domain:
                if isinstance(example, RowInstance):
                    self.X[row] = example._x
                    self._Y[row] = example._y
                else:
                    self.X[row] = example._x
                    self._Y[row] = example._y
                self.metas[row] = example._metas
                return

            self.X[row], self._Y[row], self.metas[row] = \
                self.domain.convert(example)
            try:
                self.ids[row] = example.id
            except:
                with type(self)._next_instance_lock:
                    self.ids[row] = type(self)._next_instance_id
                    type(self)._next_instance_id += 1

        else:
            self.X[row] = [var.to_val(val)
                           for var, val in zip(domain.attributes, example)]
            self._Y[row] = [var.to_val(val)
                            for var, val in
                            zip(domain.class_vars,
                                example[len(domain.attributes):])]
            self.metas[row] = np.array([var.Unknown for var in domain.metas],
                                       dtype=object)

    def _check_all_dense(self):
        return all(x in (Storage.DENSE, Storage.MISSING)
                   for x in (self.X_density(), self.Y_density(),
                             self.metas_density()))

    # A helper function for extend and insert
    # Resize X, Y, metas and W.
    def _resize_all(self, new_length):
        old_length = self.X.shape[0]
        if old_length == new_length:
            return
        if not self._check_all_dense():
            raise ValueError("Tables with sparse data cannot be resized")
        try:
            self.X.resize(new_length, self.X.shape[1])
            self._Y.resize(new_length, self._Y.shape[1])
            self.metas.resize(new_length, self.metas.shape[1])
            if self.W.ndim == 2:
                self.W.resize((new_length, 0))
            else:
                self.W.resize(new_length)
            self.ids.resize(new_length)
        except Exception:
            if self.X.shape[0] == new_length:
                self.X.resize(old_length, self.X.shape[1])
            if self._Y.shape[0] == new_length:
                self._Y.resize(old_length, self._Y.shape[1])
            if self.metas.shape[0] == new_length:
                self.metas.resize(old_length, self.metas.shape[1])
            if self.W.shape[0] == new_length:
                if self.W.ndim == 2:
                    self.W.resize((old_length, 0))
                else:
                    self.W.resize(old_length)
            if self.ids.shape[0] == new_length:
                self.ids.resize(old_length)
            raise

    def __getitem__(self, key):
        if isinstance(key, Integral):
            return RowInstance(self, key)
        if not isinstance(key, tuple):
            return self.from_table_rows(self, key)

        if len(key) != 2:
            raise IndexError("Table indices must be one- or two-dimensional")

        row_idx, col_idx = key
        if isinstance(row_idx, Integral):
            if isinstance(col_idx, (str, Integral, Variable)):
                col_idx = self.domain.index(col_idx)
                var = self.domain[col_idx]
                if 0 <= col_idx < len(self.domain.attributes):
                    return Value(var, self.X[row_idx, col_idx])
                elif col_idx >= len(self.domain.attributes):
                    return Value(
                        var,
                        self._Y[row_idx,
                                col_idx - len(self.domain.attributes)])
                elif col_idx < 0:
                    return Value(var, self.metas[row_idx, -1 - col_idx])
            else:
                row_idx = [row_idx]

        # multiple rows OR single row but multiple columns:
        # construct a new table
        attributes, col_indices = self.domain._compute_col_indices(col_idx)
        if attributes is not None:
            n_attrs = len(self.domain.attributes)
            r_attrs = [attributes[i]
                       for i, col in enumerate(col_indices)
                       if 0 <= col < n_attrs]
            r_classes = [attributes[i]
                         for i, col in enumerate(col_indices)
                         if col >= n_attrs]
            r_metas = [attributes[i]
                       for i, col in enumerate(col_indices) if col < 0]
            domain = Domain(r_attrs, r_classes, r_metas)
        else:
            domain = self.domain
        return self.from_table(domain, self, row_idx)

    def __setitem__(self, key, value):
        if not isinstance(key, tuple):
            if isinstance(value, Real):
                self.X[key, :] = value
                return
            self._set_row(value, key)
            return

        if len(key) != 2:
            raise IndexError("Table indices must be one- or two-dimensional")
        row_idx, col_idx = key

        # single row
        if isinstance(row_idx, Integral):
            if isinstance(col_idx, slice):
                col_idx = range(*slice.indices(col_idx, self.X.shape[1]))
            if not isinstance(col_idx, str) and isinstance(col_idx, Iterable):
                col_idx = list(col_idx)
            if not isinstance(col_idx, str) and isinstance(col_idx, Sized):
                if isinstance(value, (Sequence, np.ndarray)):
                    values = value
                elif isinstance(value, Iterable):
                    values = list(value)
                else:
                    raise TypeError("Setting multiple values requires a "
                                    "sequence or numpy array")
                if len(values) != len(col_idx):
                    raise ValueError("Invalid number of values")
            else:
                col_idx, values = [col_idx], [value]
            for value, col_idx in zip(values, col_idx):
                if not isinstance(value, Integral):
                    value = self.domain[col_idx].to_val(value)
                if not isinstance(col_idx, Integral):
                    col_idx = self.domain.index(col_idx)
                if col_idx >= 0:
                    if col_idx < self.X.shape[1]:
                        self.X[row_idx, col_idx] = value
                    else:
                        self._Y[row_idx, col_idx - self.X.shape[1]] = value
                else:
                    self.metas[row_idx, -1 - col_idx] = value

        # multiple rows, multiple columns
        attributes, col_indices = self.domain._compute_col_indices(col_idx)
        if col_indices is ...:
            col_indices = range(len(self.domain))
        n_attrs = self.X.shape[1]
        if isinstance(value, str):
            if not attributes:
                attributes = self.domain.attributes
            for var, col in zip(attributes, col_indices):
                if 0 <= col < n_attrs:
                    self.X[row_idx, col] = var.to_val(value)
                elif col >= n_attrs:
                    self._Y[row_idx, col - n_attrs] = var.to_val(value)
                else:
                    self.metas[row_idx, -1 - col] = var.to_val(value)
        else:
            attr_cols = np.fromiter(
                (col for col in col_indices if 0 <= col < n_attrs), int)
            class_cols = np.fromiter(
                (col - n_attrs for col in col_indices if col >= n_attrs), int)
            meta_cols = np.fromiter(
                (-1 - col for col in col_indices if col < 0), int)
            if value is None:
                value = Unknown

            if not isinstance(value, (Real, np.ndarray)) and \
                    (len(attr_cols) or len(class_cols)):
                raise TypeError(
                    "Ordinary attributes can only have primitive values")
            if len(attr_cols):
                self.X[row_idx, attr_cols] = value
            if len(class_cols):
                self._Y[row_idx, class_cols] = value
            if len(meta_cols):
                self.metas[row_idx, meta_cols] = value

    def __delitem__(self, key):
        pending_deprecation_resize("__delitem__(key)")
        if not self._check_all_dense():
            raise ValueError("Rows of sparse data cannot be deleted")
        if key is ...:
            key = range(len(self))
        self.X = np.delete(self.X, key, axis=0)
        self.Y = np.delete(self._Y, key, axis=0)
        self.metas = np.delete(self.metas, key, axis=0)
        self.W = np.delete(self.W, key, axis=0)
        self.ids = np.delete(self.ids, key, axis=0)

    def __len__(self):
        return self.X.shape[0]

    def __str__(self):
        return "[" + ",\n ".join(str(ex) for ex in self) + "]"

    def __repr__(self):
        head = 5
        if self.is_sparse():
            head = min(self.X.shape[0], head)
        s = "[" + ",\n ".join(repr(ex) for ex in self[:head])
        if len(self) > head:
            s += ",\n ..."
        s += "\n]"
        return s

    def clear(self):
        """Remove all rows from the table."""
        pending_deprecation_resize("clear()")
        if not self._check_all_dense():
            raise ValueError("Tables with sparse data cannot be cleared")
        del self[...]

    def append(self, instance):
        """
        Append a data instance to the table.

        :param instance: a data instance
        :type instance: Orange.data.Instance or a sequence of values
        """
        pending_deprecation_resize("append(inst)")
        self.insert(len(self), instance)

    def insert(self, row, instance):
        """
        Insert a data instance into the table.

        :param row: row index
        :type row: int
        :param instance: a data instance
        :type instance: Orange.data.Instance or a sequence of values
        """
        pending_deprecation_resize("insert(i, inst)")
        if row < 0:
            row += len(self)
        if row < 0 or row > len(self):
            raise IndexError("Index out of range")
        self.ensure_copy()  # ensure that numpy arrays are single-segment for resize
        self._resize_all(len(self) + 1)
        if row < len(self):
            self.X[row + 1:] = self.X[row:-1]
            self._Y[row + 1:] = self._Y[row:-1]
            self.metas[row + 1:] = self.metas[row:-1]
            self.W[row + 1:] = self.W[row:-1]
            self.ids[row + 1:] = self.ids[row:-1]
        try:
            self._set_row(instance, row)
            if self.W.shape[-1]:
                self.W[row] = 1
        except Exception:
            self.X[row:-1] = self.X[row + 1:]
            self._Y[row:-1] = self._Y[row + 1:]
            self.metas[row:-1] = self.metas[row + 1:]
            self.W[row:-1] = self.W[row + 1:]
            self.ids[row:-1] = self.ids[row + 1:]
            self._resize_all(len(self) - 1)
            raise

    def extend(self, instances):
        """
        Extend the table with the given instances. The instances can be given
        as a table of the same or a different domain, or a sequence. In the
        latter case, each instances can be given as
        :obj:`~Orange.data.Instance` or a sequence of values (e.g. list,
        tuple, numpy.array).

        :param instances: additional instances
        :type instances: Orange.data.Table or a sequence of instances
        """
        pending_deprecation_resize("extend(insts)")
        if isinstance(instances, Table) and instances.domain == self.domain:
            self.X = vstack((self.X, instances.X))
            self._Y = vstack((self._Y, instances._Y))
            self.metas = vstack((self.metas, instances.metas))
            self.W = vstack((self.W, instances.W))
            self.ids = hstack((self.ids, instances.ids))
        else:
            try:
                old_length = len(self)
                self._resize_all(old_length + len(instances))
                for i, example in enumerate(instances):
                    self[old_length + i] = example
                    try:
                        self.ids[old_length + i] = example.id
                    except AttributeError:
                        self.ids[old_length + i] = self.new_id()
            except Exception:
                self._resize_all(old_length)
                raise

    @classmethod
    def concatenate(cls, tables, axis=1):
        """Return concatenation of `tables` by `axis`."""
        def vstack(arrs):
            return [np, sp][any(sp.issparse(arr) for arr in arrs)].vstack(arrs)

        def merge1d(arrs):
            arrs = list(arrs)
            ydims = {arr.ndim for arr in arrs}
            if ydims == {1}:
                return np.hstack(arrs)
            else:
                return vstack([
                    arr if arr.ndim == 2 else np.atleast_2d(arr).T
                    for arr in arrs
                ])

        def collect(attr):
            return [getattr(arr, attr) for arr in tables]

        if not tables:
            raise ValueError('need at least one table to concatenate')
        if len(tables) == 1:
            return tables[0].copy()
        CONCAT_ROWS, CONCAT_COLS = 0, 1
        if axis == CONCAT_ROWS:
            domain = tables[0].domain
            if any(table.domain != domain for table in tables):
                raise ValueError('concatenated tables must have the same domain')

            conc = cls.from_numpy(
                domain,
                vstack(collect("X")),
                merge1d(collect("Y")),
                vstack(collect("metas")),
                merge1d(collect("W"))
            )
            conc.ids = np.hstack([table.ids for table in tables])
            names = [table.name for table in tables if table.name != "untitled"]
            if names:
                conc.name = names[0]
            # TODO: Add attributes = {} to __init__
            conc.attributes = getattr(conc, "attributes", {})
            for table in reversed(tables):
                conc.attributes.update(table.attributes)
            return conc
        elif axis == CONCAT_COLS:
            pending_deprecation_resize("concatenate with axis=1")
            if reduce(operator.iand,
                      (set(map(operator.attrgetter('name'),
                               chain(t.domain.variables, t.domain.metas)))
                       for t in tables)):
                raise ValueError('Concatenating two domains with variables '
                                 'with same name is undefined')
            domain = Domain(flatten(t.domain.attributes for t in tables),
                            flatten(t.domain.class_vars for t in tables),
                            flatten(t.domain.metas for t in tables))

            def ndmin(A):
                return A if A.ndim > 1 else A.reshape(A.shape[0], 1)

            table = Table.from_numpy(domain,
                                     np.hstack(tuple(ndmin(t.X) for t in tables)),
                                     np.hstack(tuple(ndmin(t.Y) for t in tables)),
                                     np.hstack(tuple(ndmin(t.metas) for t in tables)),
                                     np.hstack(tuple(ndmin(t.W) for t in tables)))
            return table
        raise ValueError('axis {} out of bounds [0, 2)'.format(axis))

    def is_view(self):
        """
        Return `True` if all arrays represent a view referring to another table
        """
        return ((not self.X.shape[-1] or self.X.base is not None) and
                (not self._Y.shape[-1] or self._Y.base is not None) and
                (not self.metas.shape[-1] or self.metas.base is not None) and
                (not self._weights.shape[-1] or self.W.base is not None))

    def is_copy(self):
        """
        Return `True` if the table owns its data
        """
        return ((not self.X.shape[-1] or self.X.base is None) and
                (self._Y.base is None) and
                (self.metas.base is None) and
                (self.W.base is None))

    def is_sparse(self):
        """
        Return `True` if the table stores data in sparse format
        """
        return any(sp.issparse(i) for i in [self.X, self.Y, self.metas])

    def ensure_copy(self):
        """
        Ensure that the table owns its data; copy arrays when necessary.
        """
        def is_view(x):
            # Sparse matrices don't have views like numpy arrays. Since indexing on
            # them creates copies in constructor we can skip this check here.
            return not sp.issparse(x) and x.base is not None

        if is_view(self.X):
            self.X = self.X.copy()
        if is_view(self._Y):
            self._Y = self._Y.copy()
        if is_view(self.metas):
            self.metas = self.metas.copy()
        if is_view(self.W):
            self.W = self.W.copy()

    def copy(self):
        """
        Return a copy of the table
        """
        t = self.__class__(self)
        t.ensure_copy()
        return t

    @staticmethod
    def __determine_density(data):
        if data is None:
            return Storage.Missing
        if data is not None and sp.issparse(data):
            return Storage.SPARSE_BOOL if (data.data == 1).all() else Storage.SPARSE
        else:
            return Storage.DENSE

    def X_density(self):
        if not hasattr(self, "_X_density"):
            self._X_density = self.__determine_density(self.X)
        return self._X_density

    def Y_density(self):
        if not hasattr(self, "_Y_density"):
            self._Y_density = self.__determine_density(self._Y)
        return self._Y_density

    def metas_density(self):
        if not hasattr(self, "_metas_density"):
            self._metas_density = self.__determine_density(self.metas)
        return self._metas_density

    def set_weights(self, weight=1):
        """
        Set weights of data instances; create a vector of weights if necessary.
        """
        if not self.W.shape[-1]:
            self.W = np.empty(len(self))
        self.W[:] = weight

    def has_weights(self):
        """Return `True` if the data instances are weighed. """
        return self.W.shape[-1] != 0

    def total_weight(self):
        """
        Return the total weight of instances in the table, or their number if
        they are unweighted.
        """
        if self.W.shape[-1]:
            return sum(self.W)
        return len(self)

    def has_missing(self):
        """Return `True` if there are any missing attribute or class values."""
        missing_x = not sp.issparse(self.X) and bn.anynan(self.X)   # do not check for sparse X
        return missing_x or bn.anynan(self._Y)

    def has_missing_attribute(self):
        """Return `True` if there are any missing attribute values."""
        return not sp.issparse(self.X) and bn.anynan(self.X)    # do not check for sparse X

    def has_missing_class(self):
        """Return `True` if there are any missing class values."""
        return bn.anynan(self._Y)

    def get_nan_frequency_attribute(self):
        if self.X.size == 0:
            return 0
        return np.isnan(self.X).sum() / self.X.size

    def get_nan_frequency_class(self):
        if self.Y.size == 0:
            return 0
        return np.isnan(self._Y).sum() / self._Y.size

    def checksum(self, include_metas=True):
        # TODO: zlib.adler32 does not work for numpy arrays with dtype object
        # (after pickling and unpickling such arrays, checksum changes)
        # Why, and should we fix it or remove it?
        """Return a checksum over X, Y, metas and W."""
        cs = zlib.adler32(np.ascontiguousarray(self.X))
        cs = zlib.adler32(np.ascontiguousarray(self._Y), cs)
        if include_metas:
            cs = zlib.adler32(np.ascontiguousarray(self.metas), cs)
        cs = zlib.adler32(np.ascontiguousarray(self.W), cs)
        return cs

    def shuffle(self):
        """Randomly shuffle the rows of the table."""
        if not self._check_all_dense():
            raise ValueError("Rows of sparse data cannot be shuffled")
        ind = np.arange(self.X.shape[0])
        np.random.shuffle(ind)
        self.X = self.X[ind]
        self._Y = self._Y[ind]
        self.metas = self.metas[ind]
        self.W = self.W[ind]

    def get_column_view(self, index):
        """
        Return a vector - as a view, not a copy - with a column of the table,
        and a bool flag telling whether this column is sparse. Note that
        vertical slicing of sparse matrices is inefficient.

        :param index: the index of the column
        :type index: int, str or Orange.data.Variable
        :return: (one-dimensional numpy array, sparse)
        """

        def rx(M):
            if sp.issparse(M):
                return np.asarray(M.todense())[:, 0], True
            else:
                return M, False

        if not isinstance(index, Integral):
            index = self.domain.index(index)
        if index >= 0:
            if index < self.X.shape[1]:
                return rx(self.X[:, index])
            else:
                return rx(self._Y[:, index - self.X.shape[1]])
        else:
            return rx(self.metas[:, -1 - index])

    def _filter_is_defined(self, columns=None, negate=False):
        if columns is None:
            if sp.issparse(self.X):
                remove = (self.X.indptr[1:] !=
                          self.X.indptr[-1:] + self.X.shape[1])
            else:
                remove = bn.anynan(self.X, axis=1)
            if sp.issparse(self._Y):
                remove = np.logical_or(remove, self._Y.indptr[1:] !=
                                       self._Y.indptr[-1:] + self._Y.shape[1])
            else:
                remove = np.logical_or(remove, bn.anynan(self._Y, axis=1))
        else:
            remove = np.zeros(len(self), dtype=bool)
            for column in columns:
                col, sparse = self.get_column_view(column)
                if sparse:
                    remove = np.logical_or(remove, col == 0)
                else:
                    remove = np.logical_or(remove, bn.anynan([col], axis=0))
        retain = remove if negate else np.logical_not(remove)
        return self.from_table_rows(self, retain)

    def _filter_has_class(self, negate=False):
        if sp.issparse(self._Y):
            if negate:
                retain = (self._Y.indptr[1:] !=
                          self._Y.indptr[-1:] + self._Y.shape[1])
            else:
                retain = (self._Y.indptr[1:] ==
                          self._Y.indptr[-1:] + self._Y.shape[1])
        else:
            retain = bn.anynan(self._Y, axis=1)
            if not negate:
                retain = np.logical_not(retain)
        return self.from_table_rows(self, retain)

    def _filter_same_value(self, column, value, negate=False):
        if not isinstance(value, Real):
            value = self.domain[column].to_val(value)
        sel = self.get_column_view(column)[0] == value
        if negate:
            sel = np.logical_not(sel)
        return self.from_table_rows(self, sel)

    def _filter_values(self, filter):
        selection = self._values_filter_to_indicator(filter)
        return self.from_table(self.domain, self, selection)

    def _values_filter_to_indicator(self, filter):
        """Return selection of rows matching the filter conditions

        Handles conjunction/disjunction and negate modifiers

        Parameters
        ----------
        filter: Values object containing the conditions

        Returns
        -------
        A 1d bool array. len(result) == len(self)
        """
        from Orange.data.filter import Values

        if isinstance(filter, Values):
            conditions = filter.conditions
            conjunction = filter.conjunction
        else:
            conditions = [filter]
            conjunction = True
        if conjunction:
            sel = np.ones(len(self), dtype=bool)
        else:
            sel = np.zeros(len(self), dtype=bool)

        for f in conditions:
            selection = self._filter_to_indicator(f)

            if conjunction:
                sel *= selection
            else:
                sel += selection

        if filter.negate:
            sel = ~sel
        return sel

    def _filter_to_indicator(self, filter):
        """Return selection of rows that match the condition.

        Parameters
        ----------
        filter: ValueFilter describing the condition

        Returns
        -------
        A 1d bool array. len(result) == len(self)
        """
        from Orange.data.filter import (
            FilterContinuous, FilterDiscrete, FilterRegex, FilterString,
            FilterStringList, Values
        )
        if isinstance(filter, Values):
            return self._values_filter_to_indicator(filter)

        col = self.get_column_view(filter.column)[0]

        if isinstance(filter, FilterDiscrete):
            return self._discrete_filter_to_indicator(filter, col)

        if isinstance(filter, FilterContinuous):
            return self._continuous_filter_to_indicator(filter, col)

        if isinstance(filter, FilterString):
            return self._string_filter_to_indicator(filter, col)

        if isinstance(filter, FilterStringList):
            if not filter.case_sensitive:
                col = np.char.lower(np.array(col, dtype=str))
                vals = [val.lower() for val in filter.values]
            else:
                vals = filter.values
            return reduce(operator.add, (col == val for val in vals))

        if isinstance(filter, FilterRegex):
            return np.vectorize(filter)(col)

        raise TypeError("Invalid filter")

    def _discrete_filter_to_indicator(self, filter, col):
        """Return selection of rows matched by the given discrete filter.

        Parameters
        ----------
        filter: FilterDiscrete
        col: np.ndarray

        Returns
        -------
        A 1d bool array. len(result) == len(self)
        """
        if filter.values is None:  # <- is defined filter
            col = col.astype(float)
            return ~np.isnan(col)

        sel = np.zeros(len(self), dtype=bool)
        for val in filter.values:
            if not isinstance(val, Real):
                val = self.domain[filter.column].to_val(val)
            sel += (col == val)
        return sel

    def _continuous_filter_to_indicator(self, filter, col):
        """Return selection of rows matched by the given continuous filter.

        Parameters
        ----------
        filter: FilterContinuous
        col: np.ndarray

        Returns
        -------
        A 1d bool array. len(result) == len(self)
        """
        if filter.oper == filter.IsDefined:
            col = col.astype(float)
            return ~np.isnan(col)

        return self._range_filter_to_indicator(filter, col, filter.min, filter.max)

    def _string_filter_to_indicator(self, filter, col):
        """Return selection of rows matched by the given string filter.

        Parameters
        ----------
        filter: FilterString
        col: np.ndarray

        Returns
        -------
        A 1d bool array. len(result) == len(self)
        """
        if filter.oper == filter.IsDefined:
            return col.astype(bool)

        col = col.astype(str)
        fmin = filter.min or ""
        fmax = filter.max or ""

        if not filter.case_sensitive:
            # convert all to lower case
            col = np.char.lower(col)
            fmin = fmin.lower()
            fmax = fmax.lower()

        if filter.oper == filter.Contains:
            return np.fromiter((fmin in e for e in col),
                               dtype=bool)
        if filter.oper == filter.StartsWith:
            return np.fromiter((e.startswith(fmin) for e in col),
                               dtype=bool)
        if filter.oper == filter.EndsWith:
            return np.fromiter((e.endswith(fmin) for e in col),
                               dtype=bool)

        return self._range_filter_to_indicator(filter, col, fmin, fmax)

    @staticmethod
    def _range_filter_to_indicator(filter, col, fmin, fmax):
        if filter.oper == filter.Equal:
            return col == fmin
        if filter.oper == filter.NotEqual:
            return col != fmin
        if filter.oper == filter.Less:
            return col < fmin
        if filter.oper == filter.LessEqual:
            return col <= fmin
        if filter.oper == filter.Greater:
            return col > fmin
        if filter.oper == filter.GreaterEqual:
            return col >= fmin
        if filter.oper == filter.Between:
            return (col >= fmin) * (col <= fmax)
        if filter.oper == filter.Outside:
            return (col < fmin) + (col > fmax)

        raise TypeError("Invalid operator")

    def _compute_basic_stats(self, columns=None,
                             include_metas=False, compute_variance=False):
        if compute_variance:
            raise NotImplementedError("computation of variance is "
                                      "not implemented yet")
        W = self.W if self.has_weights() else None
        rr = []
        stats = []
        if not columns:
            if self.domain.attributes:
                rr.append(fast_stats(self.X, W))
            if self.domain.class_vars:
                rr.append(fast_stats(self._Y, W))
            if include_metas and self.domain.metas:
                rr.append(fast_stats(self.metas, W))
            if len(rr):
                stats = np.vstack(tuple(rr))
        else:
            nattrs = len(self.domain.attributes)
            for column in columns:
                c = self.domain.index(column)
                if 0 <= c < nattrs:
                    S = fast_stats(self.X[:, [c]], W and W[:, [c]])
                elif c >= nattrs:
                    S = fast_stats(self._Y[:, [c-nattrs]], W and W[:, [c-nattrs]])
                else:
                    S = fast_stats(self.metas[:, [-1-c]], W and W[:, [-1-c]])
                stats.append(S[0])
        return stats

    def _compute_distributions(self, columns=None):
        if columns is None:
            columns = range(len(self.domain.variables))
        else:
            columns = [self.domain.index(var) for var in columns]

        distributions = []
        if sp.issparse(self.X):
            self.X = self.X.tocsc()

        W = self.W.ravel() if self.has_weights() else None

        for col in columns:
            variable = self.domain[col]

            # Select the correct data column from X, Y or metas
            if 0 <= col < self.X.shape[1]:
                x = self.X[:, col]
            elif col < 0:
                x = self.metas[:, col * (-1) - 1]
                if np.issubdtype(x.dtype, np.dtype(object)):
                    x = x.astype(float)
            else:
                x = self._Y[:, col - self.X.shape[1]]

            if variable.is_discrete:
                dist, unknowns = bincount(x, weights=W, max_val=len(variable.values) - 1)
            elif not x.shape[0]:
                dist, unknowns = np.zeros((2, 0)), 0
            else:
                if W is not None:
                    if sp.issparse(x):
                        arg_sort = np.argsort(x.data)
                        ranks = x.indices[arg_sort]
                        vals = np.vstack((x.data[arg_sort], W[ranks]))
                    else:
                        ranks = np.argsort(x)
                        vals = np.vstack((x[ranks], W[ranks]))
                else:
                    x_values = x.data if sp.issparse(x) else x
                    vals = np.ones((2, x_values.shape[0]))
                    vals[0, :] = x_values
                    vals[0, :].sort()

                dist = np.array(_valuecount.valuecount(vals))
                # If sparse, then 0s will not be counted with `valuecount`, so
                # we have to add them to the result manually.
                if sp.issparse(x) and sparse_has_implicit_zeros(x):
                    if W is not None:
                        zero_weights = sparse_implicit_zero_weights(x, W).sum()
                    else:
                        zero_weights = sparse_count_implicit_zeros(x)
                    zero_vec = [0, zero_weights]
                    dist = np.insert(dist, np.searchsorted(dist[0], 0), zero_vec, axis=1)
                # Since `countnans` assumes vector shape to be (1, n) and `x`
                # shape is (n, 1), we pass the transpose
                unknowns = countnans(x.T, W)
            distributions.append((dist, unknowns))

        return distributions

    def _compute_contingency(self, col_vars=None, row_var=None):
        n_atts = self.X.shape[1]

        if col_vars is None:
            col_vars = range(len(self.domain.variables))
        else:
            col_vars = [self.domain.index(var) for var in col_vars]
        if row_var is None:
            row_var = self.domain.class_var
            if row_var is None:
                raise ValueError("No row variable")

        row_desc = self.domain[row_var]
        if not row_desc.is_discrete:
            raise TypeError("Row variable must be discrete")
        row_indi = self.domain.index(row_var)
        n_rows = len(row_desc.values)
        if 0 <= row_indi < n_atts:
            row_data = self.X[:, row_indi]
        elif row_indi < 0:
            row_data = self.metas[:, -1 - row_indi]
        else:
            row_data = self._Y[:, row_indi - n_atts]

        W = self.W if self.has_weights() else None
        nan_inds = None

        col_desc = [self.domain[var] for var in col_vars]
        col_indi = [self.domain.index(var) for var in col_vars]

        if any(not (var.is_discrete or var.is_continuous)
               for var in col_desc):
            raise ValueError("contingency can be computed only for discrete "
                             "and continuous values")

        if row_data.dtype.kind != "f": #meta attributes can be stored as type object
            row_data = row_data.astype(float)

        unknown_rows = countnans(row_data)
        if unknown_rows:
            nan_inds = np.isnan(row_data)
            row_data = row_data[~nan_inds]
            if W:
                W = W[~nan_inds]
                unknown_rows = np.sum(W[nan_inds])

        contingencies = [None] * len(col_desc)
        for arr, f_cond, f_ind in (
                (self.X, lambda i: 0 <= i < n_atts, lambda i: i),
                (self._Y, lambda i: i >= n_atts, lambda i: i - n_atts),
                (self.metas, lambda i: i < 0, lambda i: -1 - i)):

            if nan_inds is not None:
                arr = arr[~nan_inds]

            arr_indi = [e for e, ind in enumerate(col_indi) if f_cond(ind)]

            vars = [(e, f_ind(col_indi[e]), col_desc[e]) for e in arr_indi]
            disc_vars = [v for v in vars if v[2].is_discrete]
            if disc_vars:
                if sp.issparse(arr):
                    max_vals = max(len(v[2].values) for v in disc_vars)
                    disc_indi = {i for _, i, _ in disc_vars}
                    mask = [i in disc_indi for i in range(arr.shape[1])]
                    conts, nans = contingency(arr, row_data, max_vals - 1,
                                              n_rows - 1, W, mask)
                    for col_i, arr_i, var in disc_vars:
                        n_vals = len(var.values)
                        contingencies[col_i] = (conts[arr_i][:, :n_vals],
                                                nans[arr_i])
                else:
                    for col_i, arr_i, var in disc_vars:
                        contingencies[col_i] = contingency(
                            arr[:, arr_i].astype(float),
                            row_data, len(var.values) - 1, n_rows - 1, W)

            cont_vars = [v for v in vars if v[2].is_continuous]
            if cont_vars:

                classes = row_data.astype(dtype=np.intp)
                if W is not None:
                    W = W.astype(dtype=np.float64)
                if sp.issparse(arr):
                    arr = sp.csc_matrix(arr)

                for col_i, arr_i, _ in cont_vars:
                    if sp.issparse(arr):
                        col_data = arr.data[arr.indptr[arr_i]:arr.indptr[arr_i + 1]]
                        rows = arr.indices[arr.indptr[arr_i]:arr.indptr[arr_i + 1]]
                        W_ = None if W is None else W[rows]
                        classes_ = classes[rows]
                    else:
                        col_data, W_, classes_ = arr[:, arr_i], W, classes

                    col_data = col_data.astype(dtype=np.float64)
                    U, C, unknown = _contingency.contingency_floatarray(
                        col_data, classes_, n_rows, W_)
                    contingencies[col_i] = ([U, C], unknown)

        return contingencies, unknown_rows

    @classmethod
    def transpose(cls, table, feature_names_column="", meta_attr_name="Feature name",
                  feature_name="Feature"):
        """
        Transpose the table.

        :param table: Table - table to transpose
        :param feature_names_column: str - name of (String) meta attribute to
            use for feature names
        :param meta_attr_name: str - name of new meta attribute into which
            feature names are mapped
        :return: Table - transposed table
        """

        self = cls()
        n_cols, self.n_rows = table.X.shape
        old_domain = table.attributes.get("old_domain")

        # attributes
        # - classes and metas to attributes of attributes
        # - arbitrary meta column to feature names
        self.X = table.X.T
        attributes = [ContinuousVariable(str(row[feature_names_column]))
                      for row in table] if feature_names_column else \
            [ContinuousVariable(feature_name + " " + str(i + 1).zfill(
                int(np.ceil(np.log10(n_cols))))) for i in range(n_cols)]
        if old_domain is not None and feature_names_column:
            for i, _ in enumerate(attributes):
                if attributes[i].name in old_domain:
                    var = old_domain[attributes[i].name]
                    attr = ContinuousVariable(var.name) if var.is_continuous \
                        else DiscreteVariable(var.name, var.values)
                    attr.attributes = var.attributes.copy()
                    attributes[i] = attr

        def set_attributes_of_attributes(_vars, _table):
            for i, variable in enumerate(_vars):
                if variable.name == feature_names_column:
                    continue
                for j, row in enumerate(_table):
                    value = variable.repr_val(row) if np.isscalar(row) \
                        else row[i] if isinstance(row[i], str) \
                        else variable.repr_val(row[i])

                    if value not in MISSING_VALUES:
                        attributes[j].attributes[variable.name] = value

        set_attributes_of_attributes(table.domain.class_vars, table.Y)
        set_attributes_of_attributes(table.domain.metas, table.metas)

        # weights
        self.W = np.empty((self.n_rows, 0))

        def get_table_from_attributes_of_attributes(_vars, _dtype=float):
            T = np.empty((self.n_rows, len(_vars)), dtype=_dtype)
            for i, _attr in enumerate(table.domain.attributes):
                for j, _var in enumerate(_vars):
                    val = str(_attr.attributes.get(_var.name, ""))
                    if not _var.is_string:
                        val = np.nan if val in MISSING_VALUES else \
                            _var.values.index(val) if \
                                _var.is_discrete else float(val)
                    T[i, j] = val
            return T

        # class_vars - attributes of attributes to class - from old domain
        class_vars = []
        if old_domain is not None:
            class_vars = old_domain.class_vars
        self.Y = get_table_from_attributes_of_attributes(class_vars)

        # metas
        # - feature names and attributes of attributes to metas
        self.metas, metas = np.empty((self.n_rows, 0), dtype=object), []
        if meta_attr_name not in [m.name for m in table.domain.metas] and \
                table.domain.attributes:
            self.metas = np.array([[a.name] for a in table.domain.attributes],
                                  dtype=object)
            metas.append(StringVariable(meta_attr_name))

        names = chain.from_iterable(list(attr.attributes)
                                    for attr in table.domain.attributes)
        names = sorted(set(names) - {var.name for var in class_vars})

        def guessed_var(i, var_name):
            orig_vals = M[:, i]
            val_map, vals, var_type = Orange.data.io.guess_data_type(orig_vals)
            values, variable = Orange.data.io.sanitize_variable(
                val_map, vals, orig_vals, var_type, {}, name=var_name)
            M[:, i] = values
            return variable

        _metas = [StringVariable(n) for n in names]
        if old_domain is not None:
            _metas = [m for m in old_domain.metas if m.name != meta_attr_name]
        M = get_table_from_attributes_of_attributes(_metas, _dtype=object)
        if old_domain is None:
            _metas = [guessed_var(i, m.name) for i, m in enumerate(_metas)]
        if _metas:
            self.metas = np.hstack((self.metas, M))
            metas.extend(_metas)

        self.domain = Domain(attributes, class_vars, metas)
        cls._init_ids(self)
        self.attributes = table.attributes.copy()
        self.attributes["old_domain"] = table.domain
        return self

    def to_sparse(self, sparse_attributes=True, sparse_class=False,
                  sparse_metas=False):
        def sparsify(features):
            for f in features:
                f.sparse = True

        new_domain = self.domain.copy()

        if sparse_attributes:
            sparsify(new_domain.attributes)
        if sparse_class:
            sparsify(new_domain.class_vars)
        if sparse_metas:
            sparsify(new_domain.metas)
        return self.transform(new_domain)

    def to_dense(self, dense_attributes=True, dense_class=True,
                 dense_metas=True):
        def densify(features):
            for f in features:
                f.sparse = False

        new_domain = self.domain.copy()

        if dense_attributes:
            densify(new_domain.attributes)
        if dense_class:
            densify(new_domain.class_vars)
        if dense_metas:
            densify(new_domain.metas)
        t = self.transform(new_domain)
        t.ids = self.ids    # preserve indices
        return t


def _check_arrays(*arrays, dtype=None):
    checked = []
    if not len(arrays):
        return checked

    def ninstances(array):
        if hasattr(array, "shape"):
            return array.shape[0]
        else:
            return len(array) if array is not None else 0

    shape_1 = ninstances(arrays[0])

    for array in arrays:
        if array is None:
            checked.append(array)
            continue

        if ninstances(array) != shape_1:
            raise ValueError("Leading dimension mismatch (%d != %d)"
                             % (ninstances(array), shape_1))

        if sp.issparse(array):
            array.data = np.asarray(array.data)
            has_inf = _check_inf(array.data)
        else:
            if dtype is not None:
                array = np.asarray(array, dtype=dtype)
            else:
                array = np.asarray(array)
            has_inf = _check_inf(array)

        if has_inf:
            raise ValueError("Array contains infinity.")
        checked.append(array)

    return checked


def _check_inf(array):
    return array.dtype.char in np.typecodes['AllFloat'] and \
           np.isinf(array.data).any()


def _subarray(arr, rows, cols):
    rows = _optimize_indices(rows, arr.shape[0])
    cols = _optimize_indices(cols, arr.shape[1])
    return arr[_rxc_ix(rows, cols)]


def _optimize_indices(indices, maxlen):
    """
    Convert integer indices to slice if possible. It only converts increasing
    integer ranges with positive steps and valid starts and ends.
    Only convert valid ends so that invalid ranges will still raise
    an exception.

    Allows numpy to reuse the data array, because it defaults to copying
    if given indices.

    Parameters
    ----------
    indices : 1D sequence, slice or Ellipsis
    """
    if isinstance(indices, slice):
        return indices

    if indices is ...:
        return slice(None, None, 1)

    if len(indices) >= 1:
        indices = np.asarray(indices)
        if indices.dtype != np.bool:
            begin = indices[0]
            end = indices[-1]
            steps = np.diff(indices) if len(indices) > 1 else np.array([1])
            step = steps[0]

            # continuous ranges with constant step and valid start and stop index can be slices
            if np.all(steps == step) and step > 0 and begin >= 0 and end < maxlen:
                return slice(begin, end + step, step)

    return indices


def _rxc_ix(rows, cols):
    """
    Construct an index object to index the `rows` x `cols` cross product.

    Rows and columns can be a 1d bool or int sequence, or a slice.
    The later is a convenience and is interpreted the same
    as `slice(None, None, -1)`

    Parameters
    ----------
    rows : 1D sequence, slice
        Row indices.
    cols : 1D sequence, slice
        Column indices.

    See Also
    --------
    numpy.ix_

    Examples
    --------
    >>> import numpy as np
    >>> a = np.arange(10).reshape(2, 5)
    >>> a[_rxc_ix([0, 1], [3, 4])]
    array([[3, 4],
           [8, 9]])
    >>> a[_rxc_ix([False, True], slice(None, None, 1))]
    array([[5, 6, 7, 8, 9]])

    """
    isslice = (isinstance(rows, slice), isinstance(cols, slice))
    if isslice == (True, True):
        return rows, cols
    elif isslice == (True, False):
        return rows, np.asarray(np.ix_(cols), int).ravel()
    elif isslice == (False, True):
        return np.asarray(np.ix_(rows), int).ravel(), cols
    else:
        r, c = np.ix_(rows, cols)
        return np.asarray(r, int), np.asarray(c, int)


def assure_domain_conversion_sparsity(target, source):
    """
    Assure that the table obeys the domain conversion's suggestions about sparsity.

    Args:
        target (Table): the target table.
        source (Table): the source table.

    Returns:
        Table: with fixed sparsity. The sparsity is set as it is recommended by domain conversion
            for transformation from source to the target domain.
    """
    conversion = target.domain.get_conversion(source.domain)
    match_density = [assure_array_dense, assure_array_sparse]
    target.X = match_density[conversion.sparse_X](target.X)
    target.Y = match_density[conversion.sparse_Y](target.Y)
    target.metas = match_density[conversion.sparse_metas](target.metas)
    return target

```
--- 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.
**Analysis:**

- **Key Parts of Commit Details and Test Results:**
  - **Commit Message:** "Table.from_numpy: Replace infs with nans.."
  - **Commit Patch:** Modifies the `_check_arrays` function to replace infinite values with NaNs and issue a warning instead of raising a `ValueError`.
  - **Added Test (`test_inf`):** Checks that creating a `Table` with an array containing infinities issues a warning and correctly calculates the frequency of NaNs.
  - **Test Results:**
    - **Old Commit:** The test failed with `ValueError: Array contains infinity.`
    - **New Commit:** The test passes, indicating successful handling of infinite values.

- **Main Problem Highlighted by Test Results:**
  The `Table.from_numpy` function does not handle arrays containing infinite values appropriately, causing a `ValueError` and preventing the creation of the table.

- **Expected Behavior:**
  When provided with an array containing infinite values, the function should replace these infinities with NaNs, issue a runtime warning about the presence of infinities, and successfully create the table with accurate NaN frequency attributes.

- **Actual Behavior:**
  The function raises a `ValueError` with the message "Array contains infinity," stopping the table creation process.

- **Issue Description:**
  The `Table.from_numpy` function fails to handle arrays with infinite values by raising an error instead of managing them gracefully.

---

[ISSUE]
**Title:** Table.from_numpy Raises ValueError When Array Contains Infinities

**Description:**
When attempting to create a `Table` from a numpy array that includes infinite values, the `Table.from_numpy` function raises a `ValueError` instead of handling the infinities by replacing them with NaNs and issuing a warning.

**Example Code:**
```python
import numpy as np
from Orange.data import Table

def create_table_with_infinities():
    a = np.array([
        [2, 0, 0, 0],
        [0, np.nan, np.nan, 1],
        [0, 0, np.inf, 0]
    ])
    tab = Table(a)
```

**Expected Behavior:**
Infinite values in the input array should be replaced with NaNs. Additionally, a runtime warning should be issued to notify the user about the presence of infinity values. The table creation should complete successfully, correctly reflecting the NaN frequency attributes.

**Actual Behavior:**
Executing the above code results in a `ValueError` with the message "Array contains infinity," preventing the `Table` from being created.

[/ISSUE]
{
    "test_dirname": "PASSED",
    "TableTestCase.test_assign_multiple_indices_value": "PASSED",
    "TableTestCase.test_assign_slice_value": "PASSED",
    "TableTestCase.test_attributes": "PASSED",
    "TableTestCase.test_bool": "PASSED",
    "TableTestCase.test_checksum": "PASSED",
    "TableTestCase.test_concatenate": "PASSED",
    "TableTestCase.test_copy": "PASSED",
    "TableTestCase.test_copy_sparse": "PASSED",
    "TableTestCase.test_filename": "PASSED",
    "TableTestCase.test_filter_has_class": "PASSED",
    "TableTestCase.test_filter_is_defined": "PASSED",
    "TableTestCase.test_filter_random": "PASSED",
    "TableTestCase.test_filter_string_works_for_numeric_columns": "PASSED",
    "TableTestCase.test_filter_value_continuous": "PASSED",
    "TableTestCase.test_filter_value_continuous_args": "PASSED",
    "TableTestCase.test_filter_values_nested": "PASSED",
    "TableTestCase.test_from_numpy": "PASSED",
    "TableTestCase.test_has_missing": "PASSED",
    "TableTestCase.test_indexing": "PASSED",
    "TableTestCase.test_indexing_assign_example": "PASSED",
    "TableTestCase.test_indexing_assign_value": "PASSED",
    "TableTestCase.test_indexing_class": "PASSED",
    "TableTestCase.test_indexing_example": "PASSED",
    "TableTestCase.test_inf": "PASSED",
    "TableTestCase.test_is_sparse": "PASSED",
    "TableTestCase.test_multiple_indices": "PASSED",
    "TableTestCase.test_pickle": "PASSED",
    "TableTestCase.test_repr_sparse_with_one_row": "PASSED",
    "TableTestCase.test_saveTab": "PASSED",
    "TableTestCase.test_save_pickle": "PASSED",
    "TableTestCase.test_set_multiple_indices_example": "PASSED",
    "TableTestCase.test_shuffle": "PASSED",
    "TableTestCase.test_slice": "PASSED",
    "TableTestCase.test_sparse_concatenate_rows": "PASSED",
    "TableTestCase.test_table_dtypes": "PASSED",
    "TableTestCase.test_total_weight": "PASSED",
    "TableTestCase.test_translate_through_slice": "PASSED",
    "TableTestCase.test_valueFilter_discrete": "PASSED",
    "TableTestCase.test_valueFilter_discrete_meta_is_defined": "PASSED",
    "TableTestCase.test_valueFilter_regex": "PASSED",
    "TableTestCase.test_valueFilter_stringList": "PASSED",
    "TableTestCase.test_valueFilter_string_case_insens": "PASSED",
    "TableTestCase.test_valueFilter_string_case_sens": "PASSED",
    "TableTestCase.test_valueFilter_string_is_defined": "PASSED",
    "CreateEmptyTable.test_calling_new_with_no_parameters_constructs_a_new_instance": "PASSED",
    "CreateEmptyTable.test_table_has_file": "PASSED",
    "CreateTableWithFilename.test_calling_new_with_keyword_argument_filename_calls_read_data": "PASSED",
    "CreateTableWithFilename.test_calling_new_with_string_argument_calls_read_data": "PASSED",
    "CreateTableWithFilename.test_raises_error_if_file_does_not_exist": "PASSED",
    "CreateTableWithFilename.test_raises_error_if_file_has_unknown_extension": "PASSED",
    "CreateTableWithFilename.test_read_data_calls_reader": "PASSED",
    "CreateTableWithUrl.test_trimmed_urls": "PASSED",
    "CreateTableWithUrl.test_url_no_scheme": "PASSED",
    "CreateTableWithDomain.test_calling_new_with_domain_calls_new_from_domain": "PASSED",
    "CreateTableWithDomain.test_creates_an_empty_table_with_given_domain": "PASSED",
    "CreateTableWithDomain.test_creates_weights_if_weights_are_true": "PASSED",
    "CreateTableWithDomain.test_creates_zero_filled_rows_in_X_if_domain_contains_attributes": "PASSED",
    "CreateTableWithDomain.test_creates_zero_filled_rows_in_Y_if_domain_contains_class_vars": "PASSED",
    "CreateTableWithDomain.test_creates_zero_filled_rows_in_metas_if_domain_contains_metas": "PASSED",
    "CreateTableWithDomain.test_does_not_create_weights_if_weights_are_false": "PASSED",
    "CreateTableWithData.test_calling_new_with_domain_and_numpy_arrays_calls_new_from_numpy": "PASSED",
    "CreateTableWithData.test_creates_a_discrete_class_if_Y_has_few_distinct_values": "PASSED",
    "CreateTableWithData.test_creates_a_table_from_domain_and_list": "PASSED",
    "CreateTableWithData.test_creates_a_table_from_domain_and_list_and_metas": "PASSED",
    "CreateTableWithData.test_creates_a_table_from_domain_and_list_and_weights": "PASSED",
    "CreateTableWithData.test_creates_a_table_from_list_of_instances": "PASSED",
    "CreateTableWithData.test_creates_a_table_from_list_of_instances_with_metas": "PASSED",
    "CreateTableWithData.test_creates_a_table_with_domain_and_given_X": "PASSED",
    "CreateTableWithData.test_creates_a_table_with_given_X": "PASSED",
    "CreateTableWithData.test_creates_a_table_with_given_X_Y_and_metas": "PASSED",
    "CreateTableWithData.test_creates_a_table_with_given_X_and_Y": "PASSED",
    "CreateTableWithData.test_creates_a_table_with_given_domain": "PASSED",
    "CreateTableWithData.test_from_numpy_reconstructable": "PASSED",
    "CreateTableWithData.test_initializes_Y_metas_and_W_if_not_given": "PASSED",
    "CreateTableWithData.test_raises_error_if_columns_in_domain_and_data_do_not_match": "PASSED",
    "CreateTableWithData.test_raises_error_if_lengths_of_data_do_not_match": "PASSED",
    "CreateTableWithData.test_sets_Y_if_given": "PASSED",
    "CreateTableWithData.test_sets_metas_if_given": "PASSED",
    "CreateTableWithData.test_sets_weights_if_given": "PASSED",
    "CreateTableWithData.test_splits_X_and_Y_if_given_in_same_array": "PASSED",
    "CreateTableWithDomainAndTable.test_can_copy_table": "PASSED",
    "CreateTableWithDomainAndTable.test_can_filter_row_with_slice": "PASSED",
    "CreateTableWithDomainAndTable.test_can_filter_rows_with_list": "PASSED",
    "CreateTableWithDomainAndTable.test_can_use_attributes_as_new_columns": "PASSED",
    "CreateTableWithDomainAndTable.test_can_use_class_vars_as_new_columns": "PASSED",
    "CreateTableWithDomainAndTable.test_can_use_combination_of_all_as_new_columns": "PASSED",
    "CreateTableWithDomainAndTable.test_can_use_metas_as_new_columns": "PASSED",
    "CreateTableWithDomainAndTable.test_creates_table_with_given_domain": "PASSED",
    "CreateTableWithDomainAndTable.test_creates_table_with_given_domain_and_row_filter": "PASSED",
    "CreateTableWithDomainAndTable.test_from_table_sparse_move_all_to_empty_metas": "PASSED",
    "CreateTableWithDomainAndTable.test_from_table_sparse_move_some_to_empty_metas": "PASSED",
    "CreateTableWithDomainAndTable.test_from_table_sparse_move_to_nonempty_metas": "PASSED",
    "CreateTableWithDomainAndTable.test_transform": "PASSED",
    "CreateTableWithDomainAndTable.test_transform_same_domain": "PASSED",
    "TableIndexingTests.test_can_select_a_single_row": "PASSED",
    "TableIndexingTests.test_can_select_a_single_value": "PASSED",
    "TableIndexingTests.test_can_select_a_subset_of_rows_and_columns": "PASSED",
    "TableIndexingTests.test_optimize_indices": "PASSED",
    "TableElementAssignmentTest.test_can_assign_lists": "PASSED",
    "TableElementAssignmentTest.test_can_assign_np_array": "PASSED",
    "TableElementAssignmentTest.test_can_assign_rows_to_rows": "PASSED",
    "TableElementAssignmentTest.test_can_assign_values": "PASSED",
    "TableElementAssignmentTest.test_can_assign_values_to_classes": "PASSED",
    "TableElementAssignmentTest.test_can_assign_values_to_metas": "PASSED",
    "InterfaceTest.test_iteration": "PASSED",
    "InterfaceTest.test_len": "PASSED",
    "InterfaceTest.test_row_assignment": "PASSED",
    "InterfaceTest.test_row_indexing": "PASSED",
    "InterfaceTest.test_row_len": "PASSED",
    "InterfaceTest.test_row_slicing": "PASSED",
    "InterfaceTest.test_value_assignment": "PASSED",
    "InterfaceTest.test_value_indexing": "PASSED",
    "TestTableStats.test_get_nan_frequency": "PASSED",
    "TestTableStats.test_get_nan_frequency_empty_table": "PASSED",
    "TestRowInstance.test_assignment": "PASSED",
    "TestRowInstance.test_iteration_with_assignment": "PASSED",
    "TestRowInstance.test_sparse_assignment": "PASSED",
    "TestTableTranspose.test_transpose": "PASSED",
    "TestTableTranspose.test_transpose_attributes_of_attributes_continuous": "PASSED",
    "TestTableTranspose.test_transpose_attributes_of_attributes_discrete": "PASSED",
    "TestTableTranspose.test_transpose_attributes_of_attributes_missings": "PASSED",
    "TestTableTranspose.test_transpose_class_and_metas": "PASSED",
    "TestTableTranspose.test_transpose_class_metas_attributes": "PASSED",
    "TestTableTranspose.test_transpose_continuous_class": "PASSED",
    "TestTableTranspose.test_transpose_continuous_metas": "PASSED",
    "TestTableTranspose.test_transpose_discrete_class": "PASSED",
    "TestTableTranspose.test_transpose_discrete_metas": "PASSED",
    "TestTableTranspose.test_transpose_metas": "PASSED",
    "TestTableTranspose.test_transpose_missing_class": "PASSED",
    "TestTableTranspose.test_transpose_missing_metas": "PASSED",
    "TestTableTranspose.test_transpose_multiple_class": "PASSED",
    "TestTableTranspose.test_transpose_multiple_metas": "PASSED",
    "TestTableTranspose.test_transpose_no_class": "PASSED",
    "TestTableSparseDense.test_from_table_add_lots_of_sparse_columns": "PASSED",
    "TestTableSparseDense.test_from_table_add_one_sparse_column": "PASSED",
    "TestTableSparseDense.test_from_table_replace_attrs_with_sparse": "PASSED",
    "TestTableSparseDense.test_from_table_sparse_metas": "PASSED",
    "TestTableSparseDense.test_from_table_sparse_metas_with_strings": "PASSED",
    "TestTableSparseDense.test_sparse_dense_transformation": "PASSED",
    "InterfaceTest.test_subclasses": "FAILED"
}
diff --git a/Orange/data/table.py b/Orange/data/table.py
index 5bcc2ad91..73c0ba96d 100644
--- a/Orange/data/table.py
+++ b/Orange/data/table.py
@@ -1779,7 +1779,8 @@ def _check_arrays(*arrays, dtype=None):
             has_inf = _check_inf(array)
 
         if has_inf:
-            raise ValueError("Array contains infinity.")
+            array[np.isinf(array)] = np.nan
+            warnings.warn("Array contains infinity.", RuntimeWarning)
         checked.append(array)
 
     return checked

{"Orange/data/table.py": "import operator\nimport os\nimport warnings\nimport zlib\nfrom collections import MutableSequence, Iterable, Sequence, Sized\nfrom functools import reduce\nfrom itertools import chain\nfrom numbers import Real, Integral\nfrom threading import Lock, RLock\n\nimport bottleneck as bn\nimport numpy as np\nfrom scipy import sparse as sp\n\nimport Orange.data  # import for io.py\nfrom Orange.data import (\n    _contingency, _valuecount,\n    Domain, Variable, Storage, StringVariable, Unknown, Value, Instance,\n    ContinuousVariable, DiscreteVariable, MISSING_VALUES\n)\nfrom Orange.data.util import SharedComputeValue, vstack, hstack, \\\n    assure_array_dense, assure_array_sparse, \\\n    assure_column_dense, assure_column_sparse\nfrom Orange.statistics.util import bincount, countnans, contingency, \\\n    stats as fast_stats, sparse_has_implicit_zeros, sparse_count_implicit_zeros, \\\n    sparse_implicit_zero_weights\nfrom Orange.util import flatten\n\n__all__ = [\"dataset_dirs\", \"get_sample_datasets_dir\", \"RowInstance\", \"Table\"]\n\n\ndef get_sample_datasets_dir():\n    orange_data_table = os.path.dirname(__file__)\n    dataset_dir = os.path.join(orange_data_table, '..', 'datasets')\n    return os.path.realpath(dataset_dir)\n\n\ndataset_dirs = ['', get_sample_datasets_dir()]\n\n\n\"\"\"Domain conversion cache used in Table.from_table. It is global so that\nchaining of domain conversions also works with caching even with descendants\nof Table.\"\"\"\n_conversion_cache = None\n_conversion_cache_lock = RLock()\n\n\ndef pending_deprecation_resize(name):\n    warnings.warn(f\"Method Table.{name} will be removed in Orange 3.24\",\n                  PendingDeprecationWarning)\n\n\nclass DomainTransformationError(Exception):\n    pass\n\n\nclass RowInstance(Instance):\n    sparse_x = None\n    sparse_y = None\n    sparse_metas = None\n    _weight = None\n\n    def __init__(self, table, row_index):\n        \"\"\"\n        Construct a data instance representing the given row of the table.\n        \"\"\"\n        self.table = table\n        self._domain = table.domain\n        self.row_index = row_index\n        self.id = table.ids[row_index]\n        self._x = table.X[row_index]\n        if sp.issparse(self._x):\n            self.sparse_x = sp.csr_matrix(self._x)\n            self._x = np.asarray(self._x.todense())[0]\n        self._y = table._Y[row_index]\n        if sp.issparse(self._y):\n            self.sparse_y = sp.csr_matrix(self._y)\n            self._y = np.asarray(self._y.todense())[0]\n        self._metas = table.metas[row_index]\n        if sp.issparse(self._metas):\n            self.sparse_metas = sp.csr_matrix(self._metas)\n            self._metas = np.asarray(self._metas.todense())[0]\n\n    @property\n    def weight(self):\n        if not self.table.has_weights():\n            return 1\n        return self.table.W[self.row_index]\n\n    @weight.setter\n    def weight(self, weight):\n        if not self.table.has_weights():\n            self.table.set_weights()\n        self.table.W[self.row_index] = weight\n\n    def set_class(self, value):\n        self._check_single_class()\n        if not isinstance(value, Real):\n            value = self.table.domain.class_var.to_val(value)\n        self._y[0] = value\n        if self.sparse_y:\n            self.table._Y[self.row_index, 0] = value\n\n    def __setitem__(self, key, value):\n        if not isinstance(key, Integral):\n            key = self._domain.index(key)\n        if isinstance(value, str):\n            var = self._domain[key]\n            value = var.to_val(value)\n        if key >= 0:\n            if not isinstance(value, Real):\n                raise TypeError(\"Expected primitive value, got '%s'\" %\n                                type(value).__name__)\n            if key < len(self._x):\n                self._x[key] = value\n                if self.sparse_x is not None:\n                    self.table.X[self.row_index, key] = value\n            else:\n                self._y[key - len(self._x)] = value\n                if self.sparse_y is not None:\n                    self.table._Y[self.row_index, key - len(self._x)] = value\n        else:\n            self._metas[-1 - key] = value\n            if self.sparse_metas:\n                self.table.metas[self.row_index, -1 - key] = value\n\n    def _str(self, limit):\n        def sp_values(matrix, variables):\n            if not sp.issparse(matrix):\n                if matrix.ndim == 1:\n                    matrix = matrix[:, np.newaxis]\n                return Instance.str_values(matrix[row], variables, limit)\n\n            row_entries, idx = [], 0\n            while idx < len(variables):\n                # Make sure to stop printing variables if we limit the output\n                if limit and len(row_entries) >= 5:\n                    break\n\n                var = variables[idx]\n                if var.is_discrete or matrix[row, idx]:\n                    row_entries.append(\"%s=%s\" % (var.name, var.str_val(matrix[row, idx])))\n\n                idx += 1\n\n            s = \", \".join(row_entries)\n\n            if limit and idx < len(variables):\n                s += \", ...\"\n\n            return s\n\n        table = self.table\n        domain = table.domain\n        row = self.row_index\n        s = \"[\" + sp_values(table.X, domain.attributes)\n        if domain.class_vars:\n            s += \" | \" + sp_values(table.Y, domain.class_vars)\n        s += \"]\"\n        if self._domain.metas:\n            s += \" {\" + sp_values(table.metas, domain.metas) + \"}\"\n        return s\n\n    def __str__(self):\n        return self._str(False)\n\n    def __repr__(self):\n        return self._str(True)\n\n\nclass Columns:\n    def __init__(self, domain):\n        for v in chain(domain.variables, domain.metas):\n            setattr(self, v.name.replace(\" \", \"_\"), v)\n\n\n# noinspection PyPep8Naming\nclass Table(MutableSequence, Storage):\n    __file__ = None\n    name = \"untitled\"\n\n    @property\n    def columns(self):\n        \"\"\"\n        A class whose attributes contain attribute descriptors for columns.\n        For a table `table`, setting `c = table.columns` will allow accessing\n        the table's variables with, for instance `c.gender`, `c.age` ets.\n        Spaces are replaced with underscores.\n        \"\"\"\n        return Columns(self.domain)\n\n    _next_instance_id = 0\n    _next_instance_lock = Lock()\n\n    @property\n    def Y(self):\n        if self._Y.shape[1] == 1:\n            return self._Y[:, 0]\n        return self._Y\n\n    @Y.setter\n    def Y(self, value):\n        if len(value.shape) == 1:\n            value = value[:, None]\n        if sp.issparse(value) and len(self) != value.shape[0]:\n            value = value.T\n        self._Y = value\n\n    def __new__(cls, *args, **kwargs):\n        if not args and not kwargs:\n            return super().__new__(cls)\n\n        if 'filename' in kwargs:\n            args = [kwargs.pop('filename')]\n\n        if not args:\n            raise TypeError(\n                \"Table takes at least 1 positional argument (0 given))\")\n\n        if isinstance(args[0], str):\n            if args[0].startswith('https://') or args[0].startswith('http://'):\n                return cls.from_url(args[0], **kwargs)\n            else:\n                return cls.from_file(args[0])\n        elif isinstance(args[0], Table):\n            return cls.from_table(args[0].domain, args[0])\n        elif isinstance(args[0], Domain):\n            domain, args = args[0], args[1:]\n            if not args:\n                return cls.from_domain(domain, **kwargs)\n            if isinstance(args[0], Table):\n                return cls.from_table(domain, *args)\n            elif isinstance(args[0], list):\n                return cls.from_list(domain, *args)\n        else:\n            domain = None\n\n        return cls.from_numpy(domain, *args, **kwargs)\n\n    def __init__(self, *args, **kwargs):\n        # So subclasses can expect to call super without breakage; noop\n        pass\n\n    @classmethod\n    def from_domain(cls, domain, n_rows=0, weights=False):\n        \"\"\"\n        Construct a new `Table` with the given number of rows for the given\n        domain. The optional vector of weights is initialized to 1's.\n\n        :param domain: domain for the `Table`\n        :type domain: Orange.data.Domain\n        :param n_rows: number of rows in the new table\n        :type n_rows: int\n        :param weights: indicates whether to construct a vector of weights\n        :type weights: bool\n        :return: a new table\n        :rtype: Orange.data.Table\n        \"\"\"\n        self = cls()\n        self.domain = domain\n        self.n_rows = n_rows\n        self.X = np.zeros((n_rows, len(domain.attributes)))\n        self.Y = np.zeros((n_rows, len(domain.class_vars)))\n        if weights:\n            self.W = np.ones(n_rows)\n        else:\n            self.W = np.empty((n_rows, 0))\n        self.metas = np.empty((n_rows, len(self.domain.metas)), object)\n        cls._init_ids(self)\n        self.attributes = {}\n        return self\n\n    @classmethod\n    def from_table(cls, domain, source, row_indices=...):\n        \"\"\"\n        Create a new table from selected columns and/or rows of an existing\n        one. The columns are chosen using a domain. The domain may also include\n        variables that do not appear in the source table; they are computed\n        from source variables if possible.\n\n        The resulting data may be a view or a copy of the existing data.\n\n        :param domain: the domain for the new table\n        :type domain: Orange.data.Domain\n        :param source: the source table\n        :type source: Orange.data.Table\n        :param row_indices: indices of the rows to include\n        :type row_indices: a slice or a sequence\n        :return: a new table\n        :rtype: Orange.data.Table\n        \"\"\"\n\n        global _conversion_cache\n\n        def get_columns(row_indices, src_cols, n_rows, dtype=np.float64, is_sparse=False):\n            if not len(src_cols):\n                if is_sparse:\n                    return sp.csr_matrix((n_rows, 0), dtype=source.X.dtype)\n                else:\n                    return np.zeros((n_rows, 0), dtype=source.X.dtype)\n\n            # match density for subarrays\n            match_density = assure_array_sparse if is_sparse else assure_array_dense\n            n_src_attrs = len(source.domain.attributes)\n            if all(isinstance(x, Integral) and 0 <= x < n_src_attrs\n                   for x in src_cols):\n                return match_density(_subarray(source.X, row_indices, src_cols))\n            if all(isinstance(x, Integral) and x < 0 for x in src_cols):\n                arr = match_density(_subarray(source.metas, row_indices,\n                                              [-1 - x for x in src_cols]))\n                if arr.dtype != dtype:\n                    return arr.astype(dtype)\n                return arr\n            if all(isinstance(x, Integral) and x >= n_src_attrs\n                   for x in src_cols):\n                return match_density(_subarray(\n                    source._Y, row_indices,\n                    [x - n_src_attrs for x in src_cols]))\n\n            # initialize final array & set `match_density` for columns\n            if is_sparse:\n                a = sp.dok_matrix((n_rows, len(src_cols)), dtype=dtype)\n                match_density = assure_column_sparse\n            else:\n                a = np.empty((n_rows, len(src_cols)), dtype=dtype)\n                match_density = assure_column_dense\n\n            shared_cache = _conversion_cache\n            for i, col in enumerate(src_cols):\n                if col is None:\n                    a[:, i] = Unknown\n                elif not isinstance(col, Integral):\n                    if isinstance(col, SharedComputeValue):\n                        if (id(col.compute_shared), id(source)) not in shared_cache:\n                            shared_cache[id(col.compute_shared), id(source)] = \\\n                                col.compute_shared(source)\n                        shared = shared_cache[id(col.compute_shared), id(source)]\n                        if row_indices is not ...:\n                            a[:, i] = match_density(\n                                col(source, shared_data=shared)[row_indices])\n                        else:\n                            a[:, i] = match_density(\n                                col(source, shared_data=shared))\n                    else:\n                        if row_indices is not ...:\n                            a[:, i] = match_density(col(source)[row_indices])\n                        else:\n                            a[:, i] = match_density(col(source))\n                elif col < 0:\n                    a[:, i] = match_density(source.metas[row_indices, -1 - col])\n                elif col < n_src_attrs:\n                    a[:, i] = match_density(source.X[row_indices, col])\n                else:\n                    a[:, i] = match_density(\n                        source._Y[row_indices, col - n_src_attrs])\n\n            if is_sparse:\n                a = a.tocsr()\n\n            return a\n\n        with _conversion_cache_lock:\n            new_cache = _conversion_cache is None\n            try:\n                if new_cache:\n                    _conversion_cache = {}\n                else:\n                    cached = _conversion_cache.get((id(domain), id(source)))\n                    if cached:\n                        return cached\n                if domain == source.domain:\n                    table = cls.from_table_rows(source, row_indices)\n                    # assure resulting domain is the instance passed on input\n                    table.domain = domain\n                    # since sparse flags are not considered when checking for\n                    # domain equality, fix manually.\n                    table = assure_domain_conversion_sparsity(table, source)\n                    return table\n\n                if isinstance(row_indices, slice):\n                    start, stop, stride = row_indices.indices(source.X.shape[0])\n                    n_rows = (stop - start) // stride\n                    if n_rows < 0:\n                        n_rows = 0\n                elif row_indices is ...:\n                    n_rows = len(source)\n                else:\n                    n_rows = len(row_indices)\n\n                self = cls()\n                self.domain = domain\n                conversion = domain.get_conversion(source.domain)\n                self.X = get_columns(row_indices, conversion.attributes, n_rows,\n                                     is_sparse=conversion.sparse_X)\n                if self.X.ndim == 1:\n                    self.X = self.X.reshape(-1, len(self.domain.attributes))\n\n                self.Y = get_columns(row_indices, conversion.class_vars, n_rows,\n                                     is_sparse=conversion.sparse_Y)\n\n                dtype = np.float64\n                if any(isinstance(var, StringVariable) for var in domain.metas):\n                    dtype = np.object\n                self.metas = get_columns(row_indices, conversion.metas,\n                                         n_rows, dtype,\n                                         is_sparse=conversion.sparse_metas)\n                if self.metas.ndim == 1:\n                    self.metas = self.metas.reshape(-1, len(self.domain.metas))\n                if source.has_weights():\n                    self.W = source.W[row_indices]\n                else:\n                    self.W = np.empty((n_rows, 0))\n                self.name = getattr(source, 'name', '')\n                if hasattr(source, 'ids'):\n                    self.ids = source.ids[row_indices]\n                else:\n                    cls._init_ids(self)\n                self.attributes = getattr(source, 'attributes', {})\n                _conversion_cache[(id(domain), id(source))] = self\n                return self\n            finally:\n                if new_cache:\n                    _conversion_cache = None\n\n    def transform(self, domain):\n        \"\"\"\n        Construct a table with a different domain.\n\n        The new table keeps the row ids and other information. If the table\n        is a subclass of :obj:`Table`, the resulting table will be of the same\n        type.\n\n        In a typical scenario, an existing table is augmented with a new\n        column by ::\n\n            domain = Domain(old_domain.attributes + [new_attribute],\n                            old_domain.class_vars,\n                            old_domain.metas)\n            table = data.transform(domain)\n            table[:, new_attribute] = new_column\n\n        Args:\n            domain (Domain): new domain\n\n        Returns:\n            A new table\n        \"\"\"\n        return type(self).from_table(domain, self)\n\n    @classmethod\n    def from_table_rows(cls, source, row_indices):\n        \"\"\"\n        Construct a new table by selecting rows from the source table.\n\n        :param source: an existing table\n        :type source: Orange.data.Table\n        :param row_indices: indices of the rows to include\n        :type row_indices: a slice or a sequence\n        :return: a new table\n        :rtype: Orange.data.Table\n        \"\"\"\n        self = cls()\n        self.domain = source.domain\n        self.X = source.X[row_indices]\n        if self.X.ndim == 1:\n            self.X = self.X.reshape(-1, len(self.domain.attributes))\n        self.Y = source._Y[row_indices]\n        self.metas = source.metas[row_indices]\n        if self.metas.ndim == 1:\n            self.metas = self.metas.reshape(-1, len(self.domain.metas))\n        self.W = source.W[row_indices]\n        self.name = getattr(source, 'name', '')\n        self.ids = np.array(source.ids[row_indices])\n        self.attributes = getattr(source, 'attributes', {})\n        return self\n\n    @classmethod\n    def from_numpy(cls, domain, X, Y=None, metas=None, W=None):\n        \"\"\"\n        Construct a table from numpy arrays with the given domain. The number\n        of variables in the domain must match the number of columns in the\n        corresponding arrays. All arrays must have the same number of rows.\n        Arrays may be of different numpy types, and may be dense or sparse.\n\n        :param domain: the domain for the new table\n        :type domain: Orange.data.Domain\n        :param X: array with attribute values\n        :type X: np.array\n        :param Y: array with class values\n        :type Y: np.array\n        :param metas: array with meta attributes\n        :type metas: np.array\n        :param W: array with weights\n        :type W: np.array\n        :return:\n        \"\"\"\n        X, Y, W = _check_arrays(X, Y, W, dtype='float64')\n        metas, = _check_arrays(metas, dtype=object)\n\n        if Y is not None and Y.ndim == 1:\n            Y = Y.reshape(Y.shape[0], 1)\n        if domain is None:\n            domain = Domain.from_numpy(X, Y, metas)\n\n        if Y is None:\n            if sp.issparse(X):\n                Y = np.empty((X.shape[0], 0), dtype=np.float64)\n            else:\n                Y = X[:, len(domain.attributes):]\n                X = X[:, :len(domain.attributes)]\n        if metas is None:\n            metas = np.empty((X.shape[0], 0), object)\n        if W is None or W.size == 0:\n            W = np.empty((X.shape[0], 0))\n        else:\n            W = W.reshape(W.size)\n\n        if X.shape[1] != len(domain.attributes):\n            raise ValueError(\n                \"Invalid number of variable columns ({} != {})\".format(\n                    X.shape[1], len(domain.attributes))\n            )\n        if Y.shape[1] != len(domain.class_vars):\n            raise ValueError(\n                \"Invalid number of class columns ({} != {})\".format(\n                    Y.shape[1], len(domain.class_vars))\n            )\n        if metas.shape[1] != len(domain.metas):\n            raise ValueError(\n                \"Invalid number of meta attribute columns ({} != {})\".format(\n                    metas.shape[1], len(domain.metas))\n            )\n        if not X.shape[0] == Y.shape[0] == metas.shape[0] == W.shape[0]:\n            raise ValueError(\n                \"Parts of data contain different numbers of rows.\")\n\n        self = cls()\n        self.domain = domain\n        self.X = X\n        self.Y = Y\n        self.metas = metas\n        self.W = W\n        self.n_rows = self.X.shape[0]\n        cls._init_ids(self)\n        self.attributes = {}\n        return self\n\n    @classmethod\n    def from_list(cls, domain, rows, weights=None):\n        if weights is not None and len(rows) != len(weights):\n            raise ValueError(\"mismatching number of instances and weights\")\n        self = cls.from_domain(domain, len(rows), weights is not None)\n        attrs, classes = domain.attributes, domain.class_vars\n        metas = domain.metas\n        nattrs, ncls = len(domain.attributes), len(domain.class_vars)\n        for i, row in enumerate(rows):\n            if isinstance(row, Instance):\n                row = row.list\n            for j, (var, val) in enumerate(zip(attrs, row)):\n                self.X[i, j] = var.to_val(val)\n            for j, (var, val) in enumerate(zip(classes, row[nattrs:])):\n                self._Y[i, j] = var.to_val(val)\n            for j, (var, val) in enumerate(zip(metas, row[nattrs + ncls:])):\n                self.metas[i, j] = var.to_val(val)\n        if weights is not None:\n            self.W = np.array(weights)\n        self.attributes = {}\n        return self\n\n    @classmethod\n    def _init_ids(cls, obj):\n        with cls._next_instance_lock:\n            obj.ids = np.array(range(cls._next_instance_id, cls._next_instance_id + obj.X.shape[0]))\n            cls._next_instance_id += obj.X.shape[0]\n\n    @classmethod\n    def new_id(cls):\n        with cls._next_instance_lock:\n            id = cls._next_instance_id\n            cls._next_instance_id += 1\n            return id\n\n    def save(self, filename):\n        \"\"\"\n        Save a data table to a file. The path can be absolute or relative.\n\n        :param filename: File name\n        :type filename: str\n        \"\"\"\n        ext = os.path.splitext(filename)[1]\n        from Orange.data.io import FileFormat\n        writer = FileFormat.writers.get(ext)\n        if not writer:\n            desc = FileFormat.names.get(ext)\n            if desc:\n                raise IOError(\n                    \"Writing of {}s is not supported\".format(desc.lower()))\n            else:\n                raise IOError(\"Unknown file name extension.\")\n        writer.write_file(filename, self)\n\n    @classmethod\n    def from_file(cls, filename, sheet=None):\n        \"\"\"\n        Read a data table from a file. The path can be absolute or relative.\n\n        :param filename: File name\n        :type filename: str\n        :param sheet: Sheet in a file (optional)\n        :type sheet: str\n        :return: a new data table\n        :rtype: Orange.data.Table\n        \"\"\"\n        from Orange.data.io import FileFormat\n\n        absolute_filename = FileFormat.locate(filename, dataset_dirs)\n        reader = FileFormat.get_reader(absolute_filename)\n        reader.select_sheet(sheet)\n        data = reader.read()\n\n        # Readers return plain table. Make sure to cast it to appropriate\n        # (subclass) type\n        if cls != data.__class__:\n            data = cls(data)\n\n        # no need to call _init_ids as fuctions from .io already\n        # construct a table with .ids\n\n        data.__file__ = absolute_filename\n        return data\n\n    @classmethod\n    def from_url(cls, url):\n        from Orange.data.io import UrlReader\n        reader = UrlReader(url)\n        data = reader.read()\n        if cls != data.__class__:\n            data = cls(data)\n        return data\n\n    # Helper function for __setitem__ and insert:\n    # Set the row of table data matrices\n    # noinspection PyProtectedMember\n    def _set_row(self, example, row):\n        domain = self.domain\n        if isinstance(example, Instance):\n            if example.domain == domain:\n                if isinstance(example, RowInstance):\n                    self.X[row] = example._x\n                    self._Y[row] = example._y\n                else:\n                    self.X[row] = example._x\n                    self._Y[row] = example._y\n                self.metas[row] = example._metas\n                return\n\n            self.X[row], self._Y[row], self.metas[row] = \\\n                self.domain.convert(example)\n            try:\n                self.ids[row] = example.id\n            except:\n                with type(self)._next_instance_lock:\n                    self.ids[row] = type(self)._next_instance_id\n                    type(self)._next_instance_id += 1\n\n        else:\n            self.X[row] = [var.to_val(val)\n                           for var, val in zip(domain.attributes, example)]\n            self._Y[row] = [var.to_val(val)\n                            for var, val in\n                            zip(domain.class_vars,\n                                example[len(domain.attributes):])]\n            self.metas[row] = np.array([var.Unknown for var in domain.metas],\n                                       dtype=object)\n\n    def _check_all_dense(self):\n        return all(x in (Storage.DENSE, Storage.MISSING)\n                   for x in (self.X_density(), self.Y_density(),\n                             self.metas_density()))\n\n    # A helper function for extend and insert\n    # Resize X, Y, metas and W.\n    def _resize_all(self, new_length):\n        old_length = self.X.shape[0]\n        if old_length == new_length:\n            return\n        if not self._check_all_dense():\n            raise ValueError(\"Tables with sparse data cannot be resized\")\n        try:\n            self.X.resize(new_length, self.X.shape[1])\n            self._Y.resize(new_length, self._Y.shape[1])\n            self.metas.resize(new_length, self.metas.shape[1])\n            if self.W.ndim == 2:\n                self.W.resize((new_length, 0))\n            else:\n                self.W.resize(new_length)\n            self.ids.resize(new_length)\n        except Exception:\n            if self.X.shape[0] == new_length:\n                self.X.resize(old_length, self.X.shape[1])\n            if self._Y.shape[0] == new_length:\n                self._Y.resize(old_length, self._Y.shape[1])\n            if self.metas.shape[0] == new_length:\n                self.metas.resize(old_length, self.metas.shape[1])\n            if self.W.shape[0] == new_length:\n                if self.W.ndim == 2:\n                    self.W.resize((old_length, 0))\n                else:\n                    self.W.resize(old_length)\n            if self.ids.shape[0] == new_length:\n                self.ids.resize(old_length)\n            raise\n\n    def __getitem__(self, key):\n        if isinstance(key, Integral):\n            return RowInstance(self, key)\n        if not isinstance(key, tuple):\n            return self.from_table_rows(self, key)\n\n        if len(key) != 2:\n            raise IndexError(\"Table indices must be one- or two-dimensional\")\n\n        row_idx, col_idx = key\n        if isinstance(row_idx, Integral):\n            if isinstance(col_idx, (str, Integral, Variable)):\n                col_idx = self.domain.index(col_idx)\n                var = self.domain[col_idx]\n                if 0 <= col_idx < len(self.domain.attributes):\n                    return Value(var, self.X[row_idx, col_idx])\n                elif col_idx >= len(self.domain.attributes):\n                    return Value(\n                        var,\n                        self._Y[row_idx,\n                                col_idx - len(self.domain.attributes)])\n                elif col_idx < 0:\n                    return Value(var, self.metas[row_idx, -1 - col_idx])\n            else:\n                row_idx = [row_idx]\n\n        # multiple rows OR single row but multiple columns:\n        # construct a new table\n        attributes, col_indices = self.domain._compute_col_indices(col_idx)\n        if attributes is not None:\n            n_attrs = len(self.domain.attributes)\n            r_attrs = [attributes[i]\n                       for i, col in enumerate(col_indices)\n                       if 0 <= col < n_attrs]\n            r_classes = [attributes[i]\n                         for i, col in enumerate(col_indices)\n                         if col >= n_attrs]\n            r_metas = [attributes[i]\n                       for i, col in enumerate(col_indices) if col < 0]\n            domain = Domain(r_attrs, r_classes, r_metas)\n        else:\n            domain = self.domain\n        return self.from_table(domain, self, row_idx)\n\n    def __setitem__(self, key, value):\n        if not isinstance(key, tuple):\n            if isinstance(value, Real):\n                self.X[key, :] = value\n                return\n            self._set_row(value, key)\n            return\n\n        if len(key) != 2:\n            raise IndexError(\"Table indices must be one- or two-dimensional\")\n        row_idx, col_idx = key\n\n        # single row\n        if isinstance(row_idx, Integral):\n            if isinstance(col_idx, slice):\n                col_idx = range(*slice.indices(col_idx, self.X.shape[1]))\n            if not isinstance(col_idx, str) and isinstance(col_idx, Iterable):\n                col_idx = list(col_idx)\n            if not isinstance(col_idx, str) and isinstance(col_idx, Sized):\n                if isinstance(value, (Sequence, np.ndarray)):\n                    values = value\n                elif isinstance(value, Iterable):\n                    values = list(value)\n                else:\n                    raise TypeError(\"Setting multiple values requires a \"\n                                    \"sequence or numpy array\")\n                if len(values) != len(col_idx):\n                    raise ValueError(\"Invalid number of values\")\n            else:\n                col_idx, values = [col_idx], [value]\n            for value, col_idx in zip(values, col_idx):\n                if not isinstance(value, Integral):\n                    value = self.domain[col_idx].to_val(value)\n                if not isinstance(col_idx, Integral):\n                    col_idx = self.domain.index(col_idx)\n                if col_idx >= 0:\n                    if col_idx < self.X.shape[1]:\n                        self.X[row_idx, col_idx] = value\n                    else:\n                        self._Y[row_idx, col_idx - self.X.shape[1]] = value\n                else:\n                    self.metas[row_idx, -1 - col_idx] = value\n\n        # multiple rows, multiple columns\n        attributes, col_indices = self.domain._compute_col_indices(col_idx)\n        if col_indices is ...:\n            col_indices = range(len(self.domain))\n        n_attrs = self.X.shape[1]\n        if isinstance(value, str):\n            if not attributes:\n                attributes = self.domain.attributes\n            for var, col in zip(attributes, col_indices):\n                if 0 <= col < n_attrs:\n                    self.X[row_idx, col] = var.to_val(value)\n                elif col >= n_attrs:\n                    self._Y[row_idx, col - n_attrs] = var.to_val(value)\n                else:\n                    self.metas[row_idx, -1 - col] = var.to_val(value)\n        else:\n            attr_cols = np.fromiter(\n                (col for col in col_indices if 0 <= col < n_attrs), int)\n            class_cols = np.fromiter(\n                (col - n_attrs for col in col_indices if col >= n_attrs), int)\n            meta_cols = np.fromiter(\n                (-1 - col for col in col_indices if col < 0), int)\n            if value is None:\n                value = Unknown\n\n            if not isinstance(value, (Real, np.ndarray)) and \\\n                    (len(attr_cols) or len(class_cols)):\n                raise TypeError(\n                    \"Ordinary attributes can only have primitive values\")\n            if len(attr_cols):\n                self.X[row_idx, attr_cols] = value\n            if len(class_cols):\n                self._Y[row_idx, class_cols] = value\n            if len(meta_cols):\n                self.metas[row_idx, meta_cols] = value\n\n    def __delitem__(self, key):\n        pending_deprecation_resize(\"__delitem__(key)\")\n        if not self._check_all_dense():\n            raise ValueError(\"Rows of sparse data cannot be deleted\")\n        if key is ...:\n            key = range(len(self))\n        self.X = np.delete(self.X, key, axis=0)\n        self.Y = np.delete(self._Y, key, axis=0)\n        self.metas = np.delete(self.metas, key, axis=0)\n        self.W = np.delete(self.W, key, axis=0)\n        self.ids = np.delete(self.ids, key, axis=0)\n\n    def __len__(self):\n        return self.X.shape[0]\n\n    def __str__(self):\n        return \"[\" + \",\\n \".join(str(ex) for ex in self) + \"]\"\n\n    def __repr__(self):\n        head = 5\n        if self.is_sparse():\n            head = min(self.X.shape[0], head)\n        s = \"[\" + \",\\n \".join(repr(ex) for ex in self[:head])\n        if len(self) > head:\n            s += \",\\n ...\"\n        s += \"\\n]\"\n        return s\n\n    def clear(self):\n        \"\"\"Remove all rows from the table.\"\"\"\n        pending_deprecation_resize(\"clear()\")\n        if not self._check_all_dense():\n            raise ValueError(\"Tables with sparse data cannot be cleared\")\n        del self[...]\n\n    def append(self, instance):\n        \"\"\"\n        Append a data instance to the table.\n\n        :param instance: a data instance\n        :type instance: Orange.data.Instance or a sequence of values\n        \"\"\"\n        pending_deprecation_resize(\"append(inst)\")\n        self.insert(len(self), instance)\n\n    def insert(self, row, instance):\n        \"\"\"\n        Insert a data instance into the table.\n\n        :param row: row index\n        :type row: int\n        :param instance: a data instance\n        :type instance: Orange.data.Instance or a sequence of values\n        \"\"\"\n        pending_deprecation_resize(\"insert(i, inst)\")\n        if row < 0:\n            row += len(self)\n        if row < 0 or row > len(self):\n            raise IndexError(\"Index out of range\")\n        self.ensure_copy()  # ensure that numpy arrays are single-segment for resize\n        self._resize_all(len(self) + 1)\n        if row < len(self):\n            self.X[row + 1:] = self.X[row:-1]\n            self._Y[row + 1:] = self._Y[row:-1]\n            self.metas[row + 1:] = self.metas[row:-1]\n            self.W[row + 1:] = self.W[row:-1]\n            self.ids[row + 1:] = self.ids[row:-1]\n        try:\n            self._set_row(instance, row)\n            if self.W.shape[-1]:\n                self.W[row] = 1\n        except Exception:\n            self.X[row:-1] = self.X[row + 1:]\n            self._Y[row:-1] = self._Y[row + 1:]\n            self.metas[row:-1] = self.metas[row + 1:]\n            self.W[row:-1] = self.W[row + 1:]\n            self.ids[row:-1] = self.ids[row + 1:]\n            self._resize_all(len(self) - 1)\n            raise\n\n    def extend(self, instances):\n        \"\"\"\n        Extend the table with the given instances. The instances can be given\n        as a table of the same or a different domain, or a sequence. In the\n        latter case, each instances can be given as\n        :obj:`~Orange.data.Instance` or a sequence of values (e.g. list,\n        tuple, numpy.array).\n\n        :param instances: additional instances\n        :type instances: Orange.data.Table or a sequence of instances\n        \"\"\"\n        pending_deprecation_resize(\"extend(insts)\")\n        if isinstance(instances, Table) and instances.domain == self.domain:\n            self.X = vstack((self.X, instances.X))\n            self._Y = vstack((self._Y, instances._Y))\n            self.metas = vstack((self.metas, instances.metas))\n            self.W = vstack((self.W, instances.W))\n            self.ids = hstack((self.ids, instances.ids))\n        else:\n            try:\n                old_length = len(self)\n                self._resize_all(old_length + len(instances))\n                for i, example in enumerate(instances):\n                    self[old_length + i] = example\n                    try:\n                        self.ids[old_length + i] = example.id\n                    except AttributeError:\n                        self.ids[old_length + i] = self.new_id()\n            except Exception:\n                self._resize_all(old_length)\n                raise\n\n    @classmethod\n    def concatenate(cls, tables, axis=1):\n        \"\"\"Return concatenation of `tables` by `axis`.\"\"\"\n        def vstack(arrs):\n            return [np, sp][any(sp.issparse(arr) for arr in arrs)].vstack(arrs)\n\n        def merge1d(arrs):\n            arrs = list(arrs)\n            ydims = {arr.ndim for arr in arrs}\n            if ydims == {1}:\n                return np.hstack(arrs)\n            else:\n                return vstack([\n                    arr if arr.ndim == 2 else np.atleast_2d(arr).T\n                    for arr in arrs\n                ])\n\n        def collect(attr):\n            return [getattr(arr, attr) for arr in tables]\n\n        if not tables:\n            raise ValueError('need at least one table to concatenate')\n        if len(tables) == 1:\n            return tables[0].copy()\n        CONCAT_ROWS, CONCAT_COLS = 0, 1\n        if axis == CONCAT_ROWS:\n            domain = tables[0].domain\n            if any(table.domain != domain for table in tables):\n                raise ValueError('concatenated tables must have the same domain')\n\n            conc = cls.from_numpy(\n                domain,\n                vstack(collect(\"X\")),\n                merge1d(collect(\"Y\")),\n                vstack(collect(\"metas\")),\n                merge1d(collect(\"W\"))\n            )\n            conc.ids = np.hstack([table.ids for table in tables])\n            names = [table.name for table in tables if table.name != \"untitled\"]\n            if names:\n                conc.name = names[0]\n            # TODO: Add attributes = {} to __init__\n            conc.attributes = getattr(conc, \"attributes\", {})\n            for table in reversed(tables):\n                conc.attributes.update(table.attributes)\n            return conc\n        elif axis == CONCAT_COLS:\n            pending_deprecation_resize(\"concatenate with axis=1\")\n            if reduce(operator.iand,\n                      (set(map(operator.attrgetter('name'),\n                               chain(t.domain.variables, t.domain.metas)))\n                       for t in tables)):\n                raise ValueError('Concatenating two domains with variables '\n                                 'with same name is undefined')\n            domain = Domain(flatten(t.domain.attributes for t in tables),\n                            flatten(t.domain.class_vars for t in tables),\n                            flatten(t.domain.metas for t in tables))\n\n            def ndmin(A):\n                return A if A.ndim > 1 else A.reshape(A.shape[0], 1)\n\n            table = Table.from_numpy(domain,\n                                     np.hstack(tuple(ndmin(t.X) for t in tables)),\n                                     np.hstack(tuple(ndmin(t.Y) for t in tables)),\n                                     np.hstack(tuple(ndmin(t.metas) for t in tables)),\n                                     np.hstack(tuple(ndmin(t.W) for t in tables)))\n            return table\n        raise ValueError('axis {} out of bounds [0, 2)'.format(axis))\n\n    def is_view(self):\n        \"\"\"\n        Return `True` if all arrays represent a view referring to another table\n        \"\"\"\n        return ((not self.X.shape[-1] or self.X.base is not None) and\n                (not self._Y.shape[-1] or self._Y.base is not None) and\n                (not self.metas.shape[-1] or self.metas.base is not None) and\n                (not self._weights.shape[-1] or self.W.base is not None))\n\n    def is_copy(self):\n        \"\"\"\n        Return `True` if the table owns its data\n        \"\"\"\n        return ((not self.X.shape[-1] or self.X.base is None) and\n                (self._Y.base is None) and\n                (self.metas.base is None) and\n                (self.W.base is None))\n\n    def is_sparse(self):\n        \"\"\"\n        Return `True` if the table stores data in sparse format\n        \"\"\"\n        return any(sp.issparse(i) for i in [self.X, self.Y, self.metas])\n\n    def ensure_copy(self):\n        \"\"\"\n        Ensure that the table owns its data; copy arrays when necessary.\n        \"\"\"\n        def is_view(x):\n            # Sparse matrices don't have views like numpy arrays. Since indexing on\n            # them creates copies in constructor we can skip this check here.\n            return not sp.issparse(x) and x.base is not None\n\n        if is_view(self.X):\n            self.X = self.X.copy()\n        if is_view(self._Y):\n            self._Y = self._Y.copy()\n        if is_view(self.metas):\n            self.metas = self.metas.copy()\n        if is_view(self.W):\n            self.W = self.W.copy()\n\n    def copy(self):\n        \"\"\"\n        Return a copy of the table\n        \"\"\"\n        t = self.__class__(self)\n        t.ensure_copy()\n        return t\n\n    @staticmethod\n    def __determine_density(data):\n        if data is None:\n            return Storage.Missing\n        if data is not None and sp.issparse(data):\n            return Storage.SPARSE_BOOL if (data.data == 1).all() else Storage.SPARSE\n        else:\n            return Storage.DENSE\n\n    def X_density(self):\n        if not hasattr(self, \"_X_density\"):\n            self._X_density = self.__determine_density(self.X)\n        return self._X_density\n\n    def Y_density(self):\n        if not hasattr(self, \"_Y_density\"):\n            self._Y_density = self.__determine_density(self._Y)\n        return self._Y_density\n\n    def metas_density(self):\n        if not hasattr(self, \"_metas_density\"):\n            self._metas_density = self.__determine_density(self.metas)\n        return self._metas_density\n\n    def set_weights(self, weight=1):\n        \"\"\"\n        Set weights of data instances; create a vector of weights if necessary.\n        \"\"\"\n        if not self.W.shape[-1]:\n            self.W = np.empty(len(self))\n        self.W[:] = weight\n\n    def has_weights(self):\n        \"\"\"Return `True` if the data instances are weighed. \"\"\"\n        return self.W.shape[-1] != 0\n\n    def total_weight(self):\n        \"\"\"\n        Return the total weight of instances in the table, or their number if\n        they are unweighted.\n        \"\"\"\n        if self.W.shape[-1]:\n            return sum(self.W)\n        return len(self)\n\n    def has_missing(self):\n        \"\"\"Return `True` if there are any missing attribute or class values.\"\"\"\n        missing_x = not sp.issparse(self.X) and bn.anynan(self.X)   # do not check for sparse X\n        return missing_x or bn.anynan(self._Y)\n\n    def has_missing_attribute(self):\n        \"\"\"Return `True` if there are any missing attribute values.\"\"\"\n        return not sp.issparse(self.X) and bn.anynan(self.X)    # do not check for sparse X\n\n    def has_missing_class(self):\n        \"\"\"Return `True` if there are any missing class values.\"\"\"\n        return bn.anynan(self._Y)\n\n    def get_nan_frequency_attribute(self):\n        if self.X.size == 0:\n            return 0\n        return np.isnan(self.X).sum() / self.X.size\n\n    def get_nan_frequency_class(self):\n        if self.Y.size == 0:\n            return 0\n        return np.isnan(self._Y).sum() / self._Y.size\n\n    def checksum(self, include_metas=True):\n        # TODO: zlib.adler32 does not work for numpy arrays with dtype object\n        # (after pickling and unpickling such arrays, checksum changes)\n        # Why, and should we fix it or remove it?\n        \"\"\"Return a checksum over X, Y, metas and W.\"\"\"\n        cs = zlib.adler32(np.ascontiguousarray(self.X))\n        cs = zlib.adler32(np.ascontiguousarray(self._Y), cs)\n        if include_metas:\n            cs = zlib.adler32(np.ascontiguousarray(self.metas), cs)\n        cs = zlib.adler32(np.ascontiguousarray(self.W), cs)\n        return cs\n\n    def shuffle(self):\n        \"\"\"Randomly shuffle the rows of the table.\"\"\"\n        if not self._check_all_dense():\n            raise ValueError(\"Rows of sparse data cannot be shuffled\")\n        ind = np.arange(self.X.shape[0])\n        np.random.shuffle(ind)\n        self.X = self.X[ind]\n        self._Y = self._Y[ind]\n        self.metas = self.metas[ind]\n        self.W = self.W[ind]\n\n    def get_column_view(self, index):\n        \"\"\"\n        Return a vector - as a view, not a copy - with a column of the table,\n        and a bool flag telling whether this column is sparse. Note that\n        vertical slicing of sparse matrices is inefficient.\n\n        :param index: the index of the column\n        :type index: int, str or Orange.data.Variable\n        :return: (one-dimensional numpy array, sparse)\n        \"\"\"\n\n        def rx(M):\n            if sp.issparse(M):\n                return np.asarray(M.todense())[:, 0], True\n            else:\n                return M, False\n\n        if not isinstance(index, Integral):\n            index = self.domain.index(index)\n        if index >= 0:\n            if index < self.X.shape[1]:\n                return rx(self.X[:, index])\n            else:\n                return rx(self._Y[:, index - self.X.shape[1]])\n        else:\n            return rx(self.metas[:, -1 - index])\n\n    def _filter_is_defined(self, columns=None, negate=False):\n        if columns is None:\n            if sp.issparse(self.X):\n                remove = (self.X.indptr[1:] !=\n                          self.X.indptr[-1:] + self.X.shape[1])\n            else:\n                remove = bn.anynan(self.X, axis=1)\n            if sp.issparse(self._Y):\n                remove = np.logical_or(remove, self._Y.indptr[1:] !=\n                                       self._Y.indptr[-1:] + self._Y.shape[1])\n            else:\n                remove = np.logical_or(remove, bn.anynan(self._Y, axis=1))\n        else:\n            remove = np.zeros(len(self), dtype=bool)\n            for column in columns:\n                col, sparse = self.get_column_view(column)\n                if sparse:\n                    remove = np.logical_or(remove, col == 0)\n                else:\n                    remove = np.logical_or(remove, bn.anynan([col], axis=0))\n        retain = remove if negate else np.logical_not(remove)\n        return self.from_table_rows(self, retain)\n\n    def _filter_has_class(self, negate=False):\n        if sp.issparse(self._Y):\n            if negate:\n                retain = (self._Y.indptr[1:] !=\n                          self._Y.indptr[-1:] + self._Y.shape[1])\n            else:\n                retain = (self._Y.indptr[1:] ==\n                          self._Y.indptr[-1:] + self._Y.shape[1])\n        else:\n            retain = bn.anynan(self._Y, axis=1)\n            if not negate:\n                retain = np.logical_not(retain)\n        return self.from_table_rows(self, retain)\n\n    def _filter_same_value(self, column, value, negate=False):\n        if not isinstance(value, Real):\n            value = self.domain[column].to_val(value)\n        sel = self.get_column_view(column)[0] == value\n        if negate:\n            sel = np.logical_not(sel)\n        return self.from_table_rows(self, sel)\n\n    def _filter_values(self, filter):\n        selection = self._values_filter_to_indicator(filter)\n        return self.from_table(self.domain, self, selection)\n\n    def _values_filter_to_indicator(self, filter):\n        \"\"\"Return selection of rows matching the filter conditions\n\n        Handles conjunction/disjunction and negate modifiers\n\n        Parameters\n        ----------\n        filter: Values object containing the conditions\n\n        Returns\n        -------\n        A 1d bool array. len(result) == len(self)\n        \"\"\"\n        from Orange.data.filter import Values\n\n        if isinstance(filter, Values):\n            conditions = filter.conditions\n            conjunction = filter.conjunction\n        else:\n            conditions = [filter]\n            conjunction = True\n        if conjunction:\n            sel = np.ones(len(self), dtype=bool)\n        else:\n            sel = np.zeros(len(self), dtype=bool)\n\n        for f in conditions:\n            selection = self._filter_to_indicator(f)\n\n            if conjunction:\n                sel *= selection\n            else:\n                sel += selection\n\n        if filter.negate:\n            sel = ~sel\n        return sel\n\n    def _filter_to_indicator(self, filter):\n        \"\"\"Return selection of rows that match the condition.\n\n        Parameters\n        ----------\n        filter: ValueFilter describing the condition\n\n        Returns\n        -------\n        A 1d bool array. len(result) == len(self)\n        \"\"\"\n        from Orange.data.filter import (\n            FilterContinuous, FilterDiscrete, FilterRegex, FilterString,\n            FilterStringList, Values\n        )\n        if isinstance(filter, Values):\n            return self._values_filter_to_indicator(filter)\n\n        col = self.get_column_view(filter.column)[0]\n\n        if isinstance(filter, FilterDiscrete):\n            return self._discrete_filter_to_indicator(filter, col)\n\n        if isinstance(filter, FilterContinuous):\n            return self._continuous_filter_to_indicator(filter, col)\n\n        if isinstance(filter, FilterString):\n            return self._string_filter_to_indicator(filter, col)\n\n        if isinstance(filter, FilterStringList):\n            if not filter.case_sensitive:\n                col = np.char.lower(np.array(col, dtype=str))\n                vals = [val.lower() for val in filter.values]\n            else:\n                vals = filter.values\n            return reduce(operator.add, (col == val for val in vals))\n\n        if isinstance(filter, FilterRegex):\n            return np.vectorize(filter)(col)\n\n        raise TypeError(\"Invalid filter\")\n\n    def _discrete_filter_to_indicator(self, filter, col):\n        \"\"\"Return selection of rows matched by the given discrete filter.\n\n        Parameters\n        ----------\n        filter: FilterDiscrete\n        col: np.ndarray\n\n        Returns\n        -------\n        A 1d bool array. len(result) == len(self)\n        \"\"\"\n        if filter.values is None:  # <- is defined filter\n            col = col.astype(float)\n            return ~np.isnan(col)\n\n        sel = np.zeros(len(self), dtype=bool)\n        for val in filter.values:\n            if not isinstance(val, Real):\n                val = self.domain[filter.column].to_val(val)\n            sel += (col == val)\n        return sel\n\n    def _continuous_filter_to_indicator(self, filter, col):\n        \"\"\"Return selection of rows matched by the given continuous filter.\n\n        Parameters\n        ----------\n        filter: FilterContinuous\n        col: np.ndarray\n\n        Returns\n        -------\n        A 1d bool array. len(result) == len(self)\n        \"\"\"\n        if filter.oper == filter.IsDefined:\n            col = col.astype(float)\n            return ~np.isnan(col)\n\n        return self._range_filter_to_indicator(filter, col, filter.min, filter.max)\n\n    def _string_filter_to_indicator(self, filter, col):\n        \"\"\"Return selection of rows matched by the given string filter.\n\n        Parameters\n        ----------\n        filter: FilterString\n        col: np.ndarray\n\n        Returns\n        -------\n        A 1d bool array. len(result) == len(self)\n        \"\"\"\n        if filter.oper == filter.IsDefined:\n            return col.astype(bool)\n\n        col = col.astype(str)\n        fmin = filter.min or \"\"\n        fmax = filter.max or \"\"\n\n        if not filter.case_sensitive:\n            # convert all to lower case\n            col = np.char.lower(col)\n            fmin = fmin.lower()\n            fmax = fmax.lower()\n\n        if filter.oper == filter.Contains:\n            return np.fromiter((fmin in e for e in col),\n                               dtype=bool)\n        if filter.oper == filter.StartsWith:\n            return np.fromiter((e.startswith(fmin) for e in col),\n                               dtype=bool)\n        if filter.oper == filter.EndsWith:\n            return np.fromiter((e.endswith(fmin) for e in col),\n                               dtype=bool)\n\n        return self._range_filter_to_indicator(filter, col, fmin, fmax)\n\n    @staticmethod\n    def _range_filter_to_indicator(filter, col, fmin, fmax):\n        if filter.oper == filter.Equal:\n            return col == fmin\n        if filter.oper == filter.NotEqual:\n            return col != fmin\n        if filter.oper == filter.Less:\n            return col < fmin\n        if filter.oper == filter.LessEqual:\n            return col <= fmin\n        if filter.oper == filter.Greater:\n            return col > fmin\n        if filter.oper == filter.GreaterEqual:\n            return col >= fmin\n        if filter.oper == filter.Between:\n            return (col >= fmin) * (col <= fmax)\n        if filter.oper == filter.Outside:\n            return (col < fmin) + (col > fmax)\n\n        raise TypeError(\"Invalid operator\")\n\n    def _compute_basic_stats(self, columns=None,\n                             include_metas=False, compute_variance=False):\n        if compute_variance:\n            raise NotImplementedError(\"computation of variance is \"\n                                      \"not implemented yet\")\n        W = self.W if self.has_weights() else None\n        rr = []\n        stats = []\n        if not columns:\n            if self.domain.attributes:\n                rr.append(fast_stats(self.X, W))\n            if self.domain.class_vars:\n                rr.append(fast_stats(self._Y, W))\n            if include_metas and self.domain.metas:\n                rr.append(fast_stats(self.metas, W))\n            if len(rr):\n                stats = np.vstack(tuple(rr))\n        else:\n            nattrs = len(self.domain.attributes)\n            for column in columns:\n                c = self.domain.index(column)\n                if 0 <= c < nattrs:\n                    S = fast_stats(self.X[:, [c]], W and W[:, [c]])\n                elif c >= nattrs:\n                    S = fast_stats(self._Y[:, [c-nattrs]], W and W[:, [c-nattrs]])\n                else:\n                    S = fast_stats(self.metas[:, [-1-c]], W and W[:, [-1-c]])\n                stats.append(S[0])\n        return stats\n\n    def _compute_distributions(self, columns=None):\n        if columns is None:\n            columns = range(len(self.domain.variables))\n        else:\n            columns = [self.domain.index(var) for var in columns]\n\n        distributions = []\n        if sp.issparse(self.X):\n            self.X = self.X.tocsc()\n\n        W = self.W.ravel() if self.has_weights() else None\n\n        for col in columns:\n            variable = self.domain[col]\n\n            # Select the correct data column from X, Y or metas\n            if 0 <= col < self.X.shape[1]:\n                x = self.X[:, col]\n            elif col < 0:\n                x = self.metas[:, col * (-1) - 1]\n                if np.issubdtype(x.dtype, np.dtype(object)):\n                    x = x.astype(float)\n            else:\n                x = self._Y[:, col - self.X.shape[1]]\n\n            if variable.is_discrete:\n                dist, unknowns = bincount(x, weights=W, max_val=len(variable.values) - 1)\n            elif not x.shape[0]:\n                dist, unknowns = np.zeros((2, 0)), 0\n            else:\n                if W is not None:\n                    if sp.issparse(x):\n                        arg_sort = np.argsort(x.data)\n                        ranks = x.indices[arg_sort]\n                        vals = np.vstack((x.data[arg_sort], W[ranks]))\n                    else:\n                        ranks = np.argsort(x)\n                        vals = np.vstack((x[ranks], W[ranks]))\n                else:\n                    x_values = x.data if sp.issparse(x) else x\n                    vals = np.ones((2, x_values.shape[0]))\n                    vals[0, :] = x_values\n                    vals[0, :].sort()\n\n                dist = np.array(_valuecount.valuecount(vals))\n                # If sparse, then 0s will not be counted with `valuecount`, so\n                # we have to add them to the result manually.\n                if sp.issparse(x) and sparse_has_implicit_zeros(x):\n                    if W is not None:\n                        zero_weights = sparse_implicit_zero_weights(x, W).sum()\n                    else:\n                        zero_weights = sparse_count_implicit_zeros(x)\n                    zero_vec = [0, zero_weights]\n                    dist = np.insert(dist, np.searchsorted(dist[0], 0), zero_vec, axis=1)\n                # Since `countnans` assumes vector shape to be (1, n) and `x`\n                # shape is (n, 1), we pass the transpose\n                unknowns = countnans(x.T, W)\n            distributions.append((dist, unknowns))\n\n        return distributions\n\n    def _compute_contingency(self, col_vars=None, row_var=None):\n        n_atts = self.X.shape[1]\n\n        if col_vars is None:\n            col_vars = range(len(self.domain.variables))\n        else:\n            col_vars = [self.domain.index(var) for var in col_vars]\n        if row_var is None:\n            row_var = self.domain.class_var\n            if row_var is None:\n                raise ValueError(\"No row variable\")\n\n        row_desc = self.domain[row_var]\n        if not row_desc.is_discrete:\n            raise TypeError(\"Row variable must be discrete\")\n        row_indi = self.domain.index(row_var)\n        n_rows = len(row_desc.values)\n        if 0 <= row_indi < n_atts:\n            row_data = self.X[:, row_indi]\n        elif row_indi < 0:\n            row_data = self.metas[:, -1 - row_indi]\n        else:\n            row_data = self._Y[:, row_indi - n_atts]\n\n        W = self.W if self.has_weights() else None\n        nan_inds = None\n\n        col_desc = [self.domain[var] for var in col_vars]\n        col_indi = [self.domain.index(var) for var in col_vars]\n\n        if any(not (var.is_discrete or var.is_continuous)\n               for var in col_desc):\n            raise ValueError(\"contingency can be computed only for discrete \"\n                             \"and continuous values\")\n\n        if row_data.dtype.kind != \"f\": #meta attributes can be stored as type object\n            row_data = row_data.astype(float)\n\n        unknown_rows = countnans(row_data)\n        if unknown_rows:\n            nan_inds = np.isnan(row_data)\n            row_data = row_data[~nan_inds]\n            if W:\n                W = W[~nan_inds]\n                unknown_rows = np.sum(W[nan_inds])\n\n        contingencies = [None] * len(col_desc)\n        for arr, f_cond, f_ind in (\n                (self.X, lambda i: 0 <= i < n_atts, lambda i: i),\n                (self._Y, lambda i: i >= n_atts, lambda i: i - n_atts),\n                (self.metas, lambda i: i < 0, lambda i: -1 - i)):\n\n            if nan_inds is not None:\n                arr = arr[~nan_inds]\n\n            arr_indi = [e for e, ind in enumerate(col_indi) if f_cond(ind)]\n\n            vars = [(e, f_ind(col_indi[e]), col_desc[e]) for e in arr_indi]\n            disc_vars = [v for v in vars if v[2].is_discrete]\n            if disc_vars:\n                if sp.issparse(arr):\n                    max_vals = max(len(v[2].values) for v in disc_vars)\n                    disc_indi = {i for _, i, _ in disc_vars}\n                    mask = [i in disc_indi for i in range(arr.shape[1])]\n                    conts, nans = contingency(arr, row_data, max_vals - 1,\n                                              n_rows - 1, W, mask)\n                    for col_i, arr_i, var in disc_vars:\n                        n_vals = len(var.values)\n                        contingencies[col_i] = (conts[arr_i][:, :n_vals],\n                                                nans[arr_i])\n                else:\n                    for col_i, arr_i, var in disc_vars:\n                        contingencies[col_i] = contingency(\n                            arr[:, arr_i].astype(float),\n                            row_data, len(var.values) - 1, n_rows - 1, W)\n\n            cont_vars = [v for v in vars if v[2].is_continuous]\n            if cont_vars:\n\n                classes = row_data.astype(dtype=np.intp)\n                if W is not None:\n                    W = W.astype(dtype=np.float64)\n                if sp.issparse(arr):\n                    arr = sp.csc_matrix(arr)\n\n                for col_i, arr_i, _ in cont_vars:\n                    if sp.issparse(arr):\n                        col_data = arr.data[arr.indptr[arr_i]:arr.indptr[arr_i + 1]]\n                        rows = arr.indices[arr.indptr[arr_i]:arr.indptr[arr_i + 1]]\n                        W_ = None if W is None else W[rows]\n                        classes_ = classes[rows]\n                    else:\n                        col_data, W_, classes_ = arr[:, arr_i], W, classes\n\n                    col_data = col_data.astype(dtype=np.float64)\n                    U, C, unknown = _contingency.contingency_floatarray(\n                        col_data, classes_, n_rows, W_)\n                    contingencies[col_i] = ([U, C], unknown)\n\n        return contingencies, unknown_rows\n\n    @classmethod\n    def transpose(cls, table, feature_names_column=\"\", meta_attr_name=\"Feature name\",\n                  feature_name=\"Feature\"):\n        \"\"\"\n        Transpose the table.\n\n        :param table: Table - table to transpose\n        :param feature_names_column: str - name of (String) meta attribute to\n            use for feature names\n        :param meta_attr_name: str - name of new meta attribute into which\n            feature names are mapped\n        :return: Table - transposed table\n        \"\"\"\n\n        self = cls()\n        n_cols, self.n_rows = table.X.shape\n        old_domain = table.attributes.get(\"old_domain\")\n\n        # attributes\n        # - classes and metas to attributes of attributes\n        # - arbitrary meta column to feature names\n        self.X = table.X.T\n        attributes = [ContinuousVariable(str(row[feature_names_column]))\n                      for row in table] if feature_names_column else \\\n            [ContinuousVariable(feature_name + \" \" + str(i + 1).zfill(\n                int(np.ceil(np.log10(n_cols))))) for i in range(n_cols)]\n        if old_domain is not None and feature_names_column:\n            for i, _ in enumerate(attributes):\n                if attributes[i].name in old_domain:\n                    var = old_domain[attributes[i].name]\n                    attr = ContinuousVariable(var.name) if var.is_continuous \\\n                        else DiscreteVariable(var.name, var.values)\n                    attr.attributes = var.attributes.copy()\n                    attributes[i] = attr\n\n        def set_attributes_of_attributes(_vars, _table):\n            for i, variable in enumerate(_vars):\n                if variable.name == feature_names_column:\n                    continue\n                for j, row in enumerate(_table):\n                    value = variable.repr_val(row) if np.isscalar(row) \\\n                        else row[i] if isinstance(row[i], str) \\\n                        else variable.repr_val(row[i])\n\n                    if value not in MISSING_VALUES:\n                        attributes[j].attributes[variable.name] = value\n\n        set_attributes_of_attributes(table.domain.class_vars, table.Y)\n        set_attributes_of_attributes(table.domain.metas, table.metas)\n\n        # weights\n        self.W = np.empty((self.n_rows, 0))\n\n        def get_table_from_attributes_of_attributes(_vars, _dtype=float):\n            T = np.empty((self.n_rows, len(_vars)), dtype=_dtype)\n            for i, _attr in enumerate(table.domain.attributes):\n                for j, _var in enumerate(_vars):\n                    val = str(_attr.attributes.get(_var.name, \"\"))\n                    if not _var.is_string:\n                        val = np.nan if val in MISSING_VALUES else \\\n                            _var.values.index(val) if \\\n                                _var.is_discrete else float(val)\n                    T[i, j] = val\n            return T\n\n        # class_vars - attributes of attributes to class - from old domain\n        class_vars = []\n        if old_domain is not None:\n            class_vars = old_domain.class_vars\n        self.Y = get_table_from_attributes_of_attributes(class_vars)\n\n        # metas\n        # - feature names and attributes of attributes to metas\n        self.metas, metas = np.empty((self.n_rows, 0), dtype=object), []\n        if meta_attr_name not in [m.name for m in table.domain.metas] and \\\n                table.domain.attributes:\n            self.metas = np.array([[a.name] for a in table.domain.attributes],\n                                  dtype=object)\n            metas.append(StringVariable(meta_attr_name))\n\n        names = chain.from_iterable(list(attr.attributes)\n                                    for attr in table.domain.attributes)\n        names = sorted(set(names) - {var.name for var in class_vars})\n\n        def guessed_var(i, var_name):\n            orig_vals = M[:, i]\n            val_map, vals, var_type = Orange.data.io.guess_data_type(orig_vals)\n            values, variable = Orange.data.io.sanitize_variable(\n                val_map, vals, orig_vals, var_type, {}, name=var_name)\n            M[:, i] = values\n            return variable\n\n        _metas = [StringVariable(n) for n in names]\n        if old_domain is not None:\n            _metas = [m for m in old_domain.metas if m.name != meta_attr_name]\n        M = get_table_from_attributes_of_attributes(_metas, _dtype=object)\n        if old_domain is None:\n            _metas = [guessed_var(i, m.name) for i, m in enumerate(_metas)]\n        if _metas:\n            self.metas = np.hstack((self.metas, M))\n            metas.extend(_metas)\n\n        self.domain = Domain(attributes, class_vars, metas)\n        cls._init_ids(self)\n        self.attributes = table.attributes.copy()\n        self.attributes[\"old_domain\"] = table.domain\n        return self\n\n    def to_sparse(self, sparse_attributes=True, sparse_class=False,\n                  sparse_metas=False):\n        def sparsify(features):\n            for f in features:\n                f.sparse = True\n\n        new_domain = self.domain.copy()\n\n        if sparse_attributes:\n            sparsify(new_domain.attributes)\n        if sparse_class:\n            sparsify(new_domain.class_vars)\n        if sparse_metas:\n            sparsify(new_domain.metas)\n        return self.transform(new_domain)\n\n    def to_dense(self, dense_attributes=True, dense_class=True,\n                 dense_metas=True):\n        def densify(features):\n            for f in features:\n                f.sparse = False\n\n        new_domain = self.domain.copy()\n\n        if dense_attributes:\n            densify(new_domain.attributes)\n        if dense_class:\n            densify(new_domain.class_vars)\n        if dense_metas:\n            densify(new_domain.metas)\n        t = self.transform(new_domain)\n        t.ids = self.ids    # preserve indices\n        return t\n\n\ndef _check_arrays(*arrays, dtype=None):\n    checked = []\n    if not len(arrays):\n        return checked\n\n    def ninstances(array):\n        if hasattr(array, \"shape\"):\n            return array.shape[0]\n        else:\n            return len(array) if array is not None else 0\n\n    shape_1 = ninstances(arrays[0])\n\n    for array in arrays:\n        if array is None:\n            checked.append(array)\n            continue\n\n        if ninstances(array) != shape_1:\n            raise ValueError(\"Leading dimension mismatch (%d != %d)\"\n                             % (ninstances(array), shape_1))\n\n        if sp.issparse(array):\n            array.data = np.asarray(array.data)\n            has_inf = _check_inf(array.data)\n        else:\n            if dtype is not None:\n                array = np.asarray(array, dtype=dtype)\n            else:\n                array = np.asarray(array)\n            has_inf = _check_inf(array)\n\n        if has_inf:\n            raise ValueError(\"Array contains infinity.\")\n        checked.append(array)\n\n    return checked\n\n\ndef _check_inf(array):\n    return array.dtype.char in np.typecodes['AllFloat'] and \\\n           np.isinf(array.data).any()\n\n\ndef _subarray(arr, rows, cols):\n    rows = _optimize_indices(rows, arr.shape[0])\n    cols = _optimize_indices(cols, arr.shape[1])\n    return arr[_rxc_ix(rows, cols)]\n\n\ndef _optimize_indices(indices, maxlen):\n    \"\"\"\n    Convert integer indices to slice if possible. It only converts increasing\n    integer ranges with positive steps and valid starts and ends.\n    Only convert valid ends so that invalid ranges will still raise\n    an exception.\n\n    Allows numpy to reuse the data array, because it defaults to copying\n    if given indices.\n\n    Parameters\n    ----------\n    indices : 1D sequence, slice or Ellipsis\n    \"\"\"\n    if isinstance(indices, slice):\n        return indices\n\n    if indices is ...:\n        return slice(None, None, 1)\n\n    if len(indices) >= 1:\n        indices = np.asarray(indices)\n        if indices.dtype != np.bool:\n            begin = indices[0]\n            end = indices[-1]\n            steps = np.diff(indices) if len(indices) > 1 else np.array([1])\n            step = steps[0]\n\n            # continuous ranges with constant step and valid start and stop index can be slices\n            if np.all(steps == step) and step > 0 and begin >= 0 and end < maxlen:\n                return slice(begin, end + step, step)\n\n    return indices\n\n\ndef _rxc_ix(rows, cols):\n    \"\"\"\n    Construct an index object to index the `rows` x `cols` cross product.\n\n    Rows and columns can be a 1d bool or int sequence, or a slice.\n    The later is a convenience and is interpreted the same\n    as `slice(None, None, -1)`\n\n    Parameters\n    ----------\n    rows : 1D sequence, slice\n        Row indices.\n    cols : 1D sequence, slice\n        Column indices.\n\n    See Also\n    --------\n    numpy.ix_\n\n    Examples\n    --------\n    >>> import numpy as np\n    >>> a = np.arange(10).reshape(2, 5)\n    >>> a[_rxc_ix([0, 1], [3, 4])]\n    array([[3, 4],\n           [8, 9]])\n    >>> a[_rxc_ix([False, True], slice(None, None, 1))]\n    array([[5, 6, 7, 8, 9]])\n\n    \"\"\"\n    isslice = (isinstance(rows, slice), isinstance(cols, slice))\n    if isslice == (True, True):\n        return rows, cols\n    elif isslice == (True, False):\n        return rows, np.asarray(np.ix_(cols), int).ravel()\n    elif isslice == (False, True):\n        return np.asarray(np.ix_(rows), int).ravel(), cols\n    else:\n        r, c = np.ix_(rows, cols)\n        return np.asarray(r, int), np.asarray(c, int)\n\n\ndef assure_domain_conversion_sparsity(target, source):\n    \"\"\"\n    Assure that the table obeys the domain conversion's suggestions about sparsity.\n\n    Args:\n        target (Table): the target table.\n        source (Table): the source table.\n\n    Returns:\n        Table: with fixed sparsity. The sparsity is set as it is recommended by domain conversion\n            for transformation from source to the target domain.\n    \"\"\"\n    conversion = target.domain.get_conversion(source.domain)\n    match_density = [assure_array_dense, assure_array_sparse]\n    target.X = match_density[conversion.sparse_X](target.X)\n    target.Y = match_density[conversion.sparse_Y](target.Y)\n    target.metas = match_density[conversion.sparse_metas](target.metas)\n    return target\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 ---
**Analysis:**

- **Key Parts of Commit Details and Test Results:**
  - **Commit Message:** "Table.from_numpy: Replace infs with nans.."
  - **Commit Patch:** Modifies the `_check_arrays` function to replace infinite values with NaNs and issue a warning instead of raising a `ValueError`.
  - **Added Test (`test_inf`):** Checks that creating a `Table` with an array containing infinities issues a warning and correctly calculates the frequency of NaNs.
  - **Test Results:**
    - **Old Commit:** The test failed with `ValueError: Array contains infinity.`
    - **New Commit:** The test passes, indicating successful handling of infinite values.

- **Main Problem Highlighted by Test Results:**
  The `Table.from_numpy` function does not handle arrays containing infinite values appropriately, causing a `ValueError` and preventing the creation of the table.

- **Expected Behavior:**
  When provided with an array containing infinite values, the function should replace these infinities with NaNs, issue a runtime warning about the presence of infinities, and successfully create the table with accurate NaN frequency attributes.

- **Actual Behavior:**
  The function raises a `ValueError` with the message "Array contains infinity," stopping the table creation process.

- **Issue Description:**
  The `Table.from_numpy` function fails to handle arrays with infinite values by raising an error instead of managing them gracefully.

---

[ISSUE]
**Title:** Table.from_numpy Raises ValueError When Array Contains Infinities

**Description:**
When attempting to create a `Table` from a numpy array that includes infinite values, the `Table.from_numpy` function raises a `ValueError` instead of handling the infinities by replacing them with NaNs and issuing a warning.

**Example Code:**
```python
import numpy as np
from Orange.data import Table

def create_table_with_infinities():
    a = np.array([
        [2, 0, 0, 0],
        [0, np.nan, np.nan, 1],
        [0, 0, np.inf, 0]
    ])
    tab = Table(a)
```

**Expected Behavior:**
Infinite values in the input array should be replaced with NaNs. Additionally, a runtime warning should be issued to notify the user about the presence of infinity values. The table creation should complete successfully, correctly reflecting the NaN frequency attributes.

**Actual Behavior:**
Executing the above code results in a `ValueError` with the message "Array contains infinity," preventing the `Table` from being created.

[/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/data/table.py
import operator
import os
import warnings
import zlib
from collections import MutableSequence, Iterable, Sequence, Sized
from functools import reduce
from itertools import chain
from numbers import Real, Integral
from threading import Lock, RLock

import bottleneck as bn
import numpy as np
from scipy import sparse as sp

import Orange.data  # import for io.py
from Orange.data import (
    _contingency, _valuecount,
    Domain, Variable, Storage, StringVariable, Unknown, Value, Instance,
    ContinuousVariable, DiscreteVariable, MISSING_VALUES
)
from Orange.data.util import SharedComputeValue, vstack, hstack, \
    assure_array_dense, assure_array_sparse, \
    assure_column_dense, assure_column_sparse
from Orange.statistics.util import bincount, countnans, contingency, \
    stats as fast_stats, sparse_has_implicit_zeros, sparse_count_implicit_zeros, \
    sparse_implicit_zero_weights
from Orange.util import flatten

__all__ = ["dataset_dirs", "get_sample_datasets_dir", "RowInstance", "Table"]


def get_sample_datasets_dir():
    orange_data_table = os.path.dirname(__file__)
    dataset_dir = os.path.join(orange_data_table, '..', 'datasets')
    return os.path.realpath(dataset_dir)


dataset_dirs = ['', get_sample_datasets_dir()]


"""Domain conversion cache used in Table.from_table. It is global so that
chaining of domain conversions also works with caching even with descendants
of Table."""
_conversion_cache = None
_conversion_cache_lock = RLock()


def pending_deprecation_resize(name):
    warnings.warn(f"Method Table.{name} will be removed in Orange 3.24",
                  PendingDeprecationWarning)


class DomainTransformationError(Exception):
    pass


class RowInstance(Instance):
    sparse_x = None
    sparse_y = None
    sparse_metas = None
    _weight = None

    def __init__(self, table, row_index):
        """
        Construct a data instance representing the given row of the table.
        """
        self.table = table
        self._domain = table.domain
        self.row_index = row_index
        self.id = table.ids[row_index]
        self._x = table.X[row_index]
        if sp.issparse(self._x):
            self.sparse_x = sp.csr_matrix(self._x)
            self._x = np.asarray(self._x.todense())[0]
        self._y = table._Y[row_index]
        if sp.issparse(self._y):
            self.sparse_y = sp.csr_matrix(self._y)
            self._y = np.asarray(self._y.todense())[0]
        self._metas = table.metas[row_index]
        if sp.issparse(self._metas):
            self.sparse_metas = sp.csr_matrix(self._metas)
            self._metas = np.asarray(self._metas.todense())[0]

    @property
    def weight(self):
        if not self.table.has_weights():
            return 1
        return self.table.W[self.row_index]

    @weight.setter
    def weight(self, weight):
        if not self.table.has_weights():
            self.table.set_weights()
        self.table.W[self.row_index] = weight

    def set_class(self, value):
        self._check_single_class()
        if not isinstance(value, Real):
            value = self.table.domain.class_var.to_val(value)
        self._y[0] = value
        if self.sparse_y:
            self.table._Y[self.row_index, 0] = value

    def __setitem__(self, key, value):
        if not isinstance(key, Integral):
            key = self._domain.index(key)
        if isinstance(value, str):
            var = self._domain[key]
            value = var.to_val(value)
        if key >= 0:
            if not isinstance(value, Real):
                raise TypeError("Expected primitive value, got '%s'" %
                                type(value).__name__)
            if key < len(self._x):
                self._x[key] = value
                if self.sparse_x is not None:
                    self.table.X[self.row_index, key] = value
            else:
                self._y[key - len(self._x)] = value
                if self.sparse_y is not None:
                    self.table._Y[self.row_index, key - len(self._x)] = value
        else:
            self._metas[-1 - key] = value
            if self.sparse_metas:
                self.table.metas[self.row_index, -1 - key] = value

    def _str(self, limit):
        def sp_values(matrix, variables):
            if not sp.issparse(matrix):
                if matrix.ndim == 1:
                    matrix = matrix[:, np.newaxis]
                return Instance.str_values(matrix[row], variables, limit)

            row_entries, idx = [], 0
            while idx < len(variables):
                # Make sure to stop printing variables if we limit the output
                if limit and len(row_entries) >= 5:
                    break

                var = variables[idx]
                if var.is_discrete or matrix[row, idx]:
                    row_entries.append("%s=%s" % (var.name, var.str_val(matrix[row, idx])))

                idx += 1

            s = ", ".join(row_entries)

            if limit and idx < len(variables):
                s += ", ..."

            return s

        table = self.table
        domain = table.domain
        row = self.row_index
        s = "[" + sp_values(table.X, domain.attributes)
        if domain.class_vars:
            s += " | " + sp_values(table.Y, domain.class_vars)
        s += "]"
        if self._domain.metas:
            s += " {" + sp_values(table.metas, domain.metas) + "}"
        return s

    def __str__(self):
        return self._str(False)

    def __repr__(self):
        return self._str(True)


class Columns:
    def __init__(self, domain):
        for v in chain(domain.variables, domain.metas):
            setattr(self, v.name.replace(" ", "_"), v)


# noinspection PyPep8Naming
class Table(MutableSequence, Storage):
    __file__ = None
    name = "untitled"

    @property
    def columns(self):
        """
        A class whose attributes contain attribute descriptors for columns.
        For a table `table`, setting `c = table.columns` will allow accessing
        the table's variables with, for instance `c.gender`, `c.age` ets.
        Spaces are replaced with underscores.
        """
        return Columns(self.domain)

    _next_instance_id = 0
    _next_instance_lock = Lock()

    @property
    def Y(self):
        if self._Y.shape[1] == 1:
            return self._Y[:, 0]
        return self._Y

    @Y.setter
    def Y(self, value):
        if len(value.shape) == 1:
            value = value[:, None]
        if sp.issparse(value) and len(self) != value.shape[0]:
            value = value.T
        self._Y = value

    def __new__(cls, *args, **kwargs):
        if not args and not kwargs:
            return super().__new__(cls)

        if 'filename' in kwargs:
            args = [kwargs.pop('filename')]

        if not args:
            raise TypeError(
                "Table takes at least 1 positional argument (0 given))")

        if isinstance(args[0], str):
            if args[0].startswith('https://') or args[0].startswith('http://'):
                return cls.from_url(args[0], **kwargs)
            else:
                return cls.from_file(args[0])
        elif isinstance(args[0], Table):
            return cls.from_table(args[0].domain, args[0])
        elif isinstance(args[0], Domain):
            domain, args = args[0], args[1:]
            if not args:
                return cls.from_domain(domain, **kwargs)
            if isinstance(args[0], Table):
                return cls.from_table(domain, *args)
            elif isinstance(args[0], list):
                return cls.from_list(domain, *args)
        else:
            domain = None

        return cls.from_numpy(domain, *args, **kwargs)

    def __init__(self, *args, **kwargs):
        # So subclasses can expect to call super without breakage; noop
        pass

    @classmethod
    def from_domain(cls, domain, n_rows=0, weights=False):
        """
        Construct a new `Table` with the given number of rows for the given
        domain. The optional vector of weights is initialized to 1's.

        :param domain: domain for the `Table`
        :type domain: Orange.data.Domain
        :param n_rows: number of rows in the new table
        :type n_rows: int
        :param weights: indicates whether to construct a vector of weights
        :type weights: bool
        :return: a new table
        :rtype: Orange.data.Table
        """
        self = cls()
        self.domain = domain
        self.n_rows = n_rows
        self.X = np.zeros((n_rows, len(domain.attributes)))
        self.Y = np.zeros((n_rows, len(domain.class_vars)))
        if weights:
            self.W = np.ones(n_rows)
        else:
            self.W = np.empty((n_rows, 0))
        self.metas = np.empty((n_rows, len(self.domain.metas)), object)
        cls._init_ids(self)
        self.attributes = {}
        return self

    @classmethod
    def from_table(cls, domain, source, row_indices=...):
        """
        Create a new table from selected columns and/or rows of an existing
        one. The columns are chosen using a domain. The domain may also include
        variables that do not appear in the source table; they are computed
        from source variables if possible.

        The resulting data may be a view or a copy of the existing data.

        :param domain: the domain for the new table
        :type domain: Orange.data.Domain
        :param source: the source table
        :type source: Orange.data.Table
        :param row_indices: indices of the rows to include
        :type row_indices: a slice or a sequence
        :return: a new table
        :rtype: Orange.data.Table
        """

        global _conversion_cache

        def get_columns(row_indices, src_cols, n_rows, dtype=np.float64, is_sparse=False):
            if not len(src_cols):
                if is_sparse:
                    return sp.csr_matrix((n_rows, 0), dtype=source.X.dtype)
                else:
                    return np.zeros((n_rows, 0), dtype=source.X.dtype)

            # match density for subarrays
            match_density = assure_array_sparse if is_sparse else assure_array_dense
            n_src_attrs = len(source.domain.attributes)
            if all(isinstance(x, Integral) and 0 <= x < n_src_attrs
                   for x in src_cols):
                return match_density(_subarray(source.X, row_indices, src_cols))
            if all(isinstance(x, Integral) and x < 0 for x in src_cols):
                arr = match_density(_subarray(source.metas, row_indices,
                                              [-1 - x for x in src_cols]))
                if arr.dtype != dtype:
                    return arr.astype(dtype)
                return arr
            if all(isinstance(x, Integral) and x >= n_src_attrs
                   for x in src_cols):
                return match_density(_subarray(
                    source._Y, row_indices,
                    [x - n_src_attrs for x in src_cols]))

            # initialize final array & set `match_density` for columns
            if is_sparse:
                a = sp.dok_matrix((n_rows, len(src_cols)), dtype=dtype)
                match_density = assure_column_sparse
            else:
                a = np.empty((n_rows, len(src_cols)), dtype=dtype)
                match_density = assure_column_dense

            shared_cache = _conversion_cache
            for i, col in enumerate(src_cols):
                if col is None:
                    a[:, i] = Unknown
                elif not isinstance(col, Integral):
                    if isinstance(col, SharedComputeValue):
                        if (id(col.compute_shared), id(source)) not in shared_cache:
                            shared_cache[id(col.compute_shared), id(source)] = \
                                col.compute_shared(source)
                        shared = shared_cache[id(col.compute_shared), id(source)]
                        if row_indices is not ...:
                            a[:, i] = match_density(
                                col(source, shared_data=shared)[row_indices])
                        else:
                            a[:, i] = match_density(
                                col(source, shared_data=shared))
                    else:
                        if row_indices is not ...:
                            a[:, i] = match_density(col(source)[row_indices])
                        else:
                            a[:, i] = match_density(col(source))
                elif col < 0:
                    a[:, i] = match_density(source.metas[row_indices, -1 - col])
                elif col < n_src_attrs:
                    a[:, i] = match_density(source.X[row_indices, col])
                else:
                    a[:, i] = match_density(
                        source._Y[row_indices, col - n_src_attrs])

            if is_sparse:
                a = a.tocsr()

            return a

        with _conversion_cache_lock:
            new_cache = _conversion_cache is None
            try:
                if new_cache:
                    _conversion_cache = {}
                else:
                    cached = _conversion_cache.get((id(domain), id(source)))
                    if cached:
                        return cached
                if domain == source.domain:
                    table = cls.from_table_rows(source, row_indices)
                    # assure resulting domain is the instance passed on input
                    table.domain = domain
                    # since sparse flags are not considered when checking for
                    # domain equality, fix manually.
                    table = assure_domain_conversion_sparsity(table, source)
                    return table

                if isinstance(row_indices, slice):
                    start, stop, stride = row_indices.indices(source.X.shape[0])
                    n_rows = (stop - start) // stride
                    if n_rows < 0:
                        n_rows = 0
                elif row_indices is ...:
                    n_rows = len(source)
                else:
                    n_rows = len(row_indices)

                self = cls()
                self.domain = domain
                conversion = domain.get_conversion(source.domain)
                self.X = get_columns(row_indices, conversion.attributes, n_rows,
                                     is_sparse=conversion.sparse_X)
                if self.X.ndim == 1:
                    self.X = self.X.reshape(-1, len(self.domain.attributes))

                self.Y = get_columns(row_indices, conversion.class_vars, n_rows,
                                     is_sparse=conversion.sparse_Y)

                dtype = np.float64
                if any(isinstance(var, StringVariable) for var in domain.metas):
                    dtype = np.object
                self.metas = get_columns(row_indices, conversion.metas,
                                         n_rows, dtype,
                                         is_sparse=conversion.sparse_metas)
                if self.metas.ndim == 1:
                    self.metas = self.metas.reshape(-1, len(self.domain.metas))
                if source.has_weights():
                    self.W = source.W[row_indices]
                else:
                    self.W = np.empty((n_rows, 0))
                self.name = getattr(source, 'name', '')
                if hasattr(source, 'ids'):
                    self.ids = source.ids[row_indices]
                else:
                    cls._init_ids(self)
                self.attributes = getattr(source, 'attributes', {})
                _conversion_cache[(id(domain), id(source))] = self
                return self
            finally:
                if new_cache:
                    _conversion_cache = None

    def transform(self, domain):
        """
        Construct a table with a different domain.

        The new table keeps the row ids and other information. If the table
        is a subclass of :obj:`Table`, the resulting table will be of the same
        type.

        In a typical scenario, an existing table is augmented with a new
        column by ::

            domain = Domain(old_domain.attributes + [new_attribute],
                            old_domain.class_vars,
                            old_domain.metas)
            table = data.transform(domain)
            table[:, new_attribute] = new_column

        Args:
            domain (Domain): new domain

        Returns:
            A new table
        """
        return type(self).from_table(domain, self)

    @classmethod
    def from_table_rows(cls, source, row_indices):
        """
        Construct a new table by selecting rows from the source table.

        :param source: an existing table
        :type source: Orange.data.Table
        :param row_indices: indices of the rows to include
        :type row_indices: a slice or a sequence
        :return: a new table
        :rtype: Orange.data.Table
        """
        self = cls()
        self.domain = source.domain
        self.X = source.X[row_indices]
        if self.X.ndim == 1:
            self.X = self.X.reshape(-1, len(self.domain.attributes))
        self.Y = source._Y[row_indices]
        self.metas = source.metas[row_indices]
        if self.metas.ndim == 1:
            self.metas = self.metas.reshape(-1, len(self.domain.metas))
        self.W = source.W[row_indices]
        self.name = getattr(source, 'name', '')
        self.ids = np.array(source.ids[row_indices])
        self.attributes = getattr(source, 'attributes', {})
        return self

    @classmethod
    def from_numpy(cls, domain, X, Y=None, metas=None, W=None):
        """
        Construct a table from numpy arrays with the given domain. The number
        of variables in the domain must match the number of columns in the
        corresponding arrays. All arrays must have the same number of rows.
        Arrays may be of different numpy types, and may be dense or sparse.

        :param domain: the domain for the new table
        :type domain: Orange.data.Domain
        :param X: array with attribute values
        :type X: np.array
        :param Y: array with class values
        :type Y: np.array
        :param metas: array with meta attributes
        :type metas: np.array
        :param W: array with weights
        :type W: np.array
        :return:
        """
        X, Y, W = _check_arrays(X, Y, W, dtype='float64')
        metas, = _check_arrays(metas, dtype=object)

        if Y is not None and Y.ndim == 1:
            Y = Y.reshape(Y.shape[0], 1)
        if domain is None:
            domain = Domain.from_numpy(X, Y, metas)

        if Y is None:
            if sp.issparse(X):
                Y = np.empty((X.shape[0], 0), dtype=np.float64)
            else:
                Y = X[:, len(domain.attributes):]
                X = X[:, :len(domain.attributes)]
        if metas is None:
            metas = np.empty((X.shape[0], 0), object)
        if W is None or W.size == 0:
            W = np.empty((X.shape[0], 0))
        else:
            W = W.reshape(W.size)

        if X.shape[1] != len(domain.attributes):
            raise ValueError(
                "Invalid number of variable columns ({} != {})".format(
                    X.shape[1], len(domain.attributes))
            )
        if Y.shape[1] != len(domain.class_vars):
            raise ValueError(
                "Invalid number of class columns ({} != {})".format(
                    Y.shape[1], len(domain.class_vars))
            )
        if metas.shape[1] != len(domain.metas):
            raise ValueError(
                "Invalid number of meta attribute columns ({} != {})".format(
                    metas.shape[1], len(domain.metas))
            )
        if not X.shape[0] == Y.shape[0] == metas.shape[0] == W.shape[0]:
            raise ValueError(
                "Parts of data contain different numbers of rows.")

        self = cls()
        self.domain = domain
        self.X = X
        self.Y = Y
        self.metas = metas
        self.W = W
        self.n_rows = self.X.shape[0]
        cls._init_ids(self)
        self.attributes = {}
        return self

    @classmethod
    def from_list(cls, domain, rows, weights=None):
        if weights is not None and len(rows) != len(weights):
            raise ValueError("mismatching number of instances and weights")
        self = cls.from_domain(domain, len(rows), weights is not None)
        attrs, classes = domain.attributes, domain.class_vars
        metas = domain.metas
        nattrs, ncls = len(domain.attributes), len(domain.class_vars)
        for i, row in enumerate(rows):
            if isinstance(row, Instance):
                row = row.list
            for j, (var, val) in enumerate(zip(attrs, row)):
                self.X[i, j] = var.to_val(val)
            for j, (var, val) in enumerate(zip(classes, row[nattrs:])):
                self._Y[i, j] = var.to_val(val)
            for j, (var, val) in enumerate(zip(metas, row[nattrs + ncls:])):
                self.metas[i, j] = var.to_val(val)
        if weights is not None:
            self.W = np.array(weights)
        self.attributes = {}
        return self

    @classmethod
    def _init_ids(cls, obj):
        with cls._next_instance_lock:
            obj.ids = np.array(range(cls._next_instance_id, cls._next_instance_id + obj.X.shape[0]))
            cls._next_instance_id += obj.X.shape[0]

    @classmethod
    def new_id(cls):
        with cls._next_instance_lock:
            id = cls._next_instance_id
            cls._next_instance_id += 1
            return id

    def save(self, filename):
        """
        Save a data table to a file. The path can be absolute or relative.

        :param filename: File name
        :type filename: str
        """
        ext = os.path.splitext(filename)[1]
        from Orange.data.io import FileFormat
        writer = FileFormat.writers.get(ext)
        if not writer:
            desc = FileFormat.names.get(ext)
            if desc:
                raise IOError(
                    "Writing of {}s is not supported".format(desc.lower()))
            else:
                raise IOError("Unknown file name extension.")
        writer.write_file(filename, self)

    @classmethod
    def from_file(cls, filename, sheet=None):
        """
        Read a data table from a file. The path can be absolute or relative.

        :param filename: File name
        :type filename: str
        :param sheet: Sheet in a file (optional)
        :type sheet: str
        :return: a new data table
        :rtype: Orange.data.Table
        """
        from Orange.data.io import FileFormat

        absolute_filename = FileFormat.locate(filename, dataset_dirs)
        reader = FileFormat.get_reader(absolute_filename)
        reader.select_sheet(sheet)
        data = reader.read()

        # Readers return plain table. Make sure to cast it to appropriate
        # (subclass) type
        if cls != data.__class__:
            data = cls(data)

        # no need to call _init_ids as fuctions from .io already
        # construct a table with .ids

        data.__file__ = absolute_filename
        return data

    @classmethod
    def from_url(cls, url):
        from Orange.data.io import UrlReader
        reader = UrlReader(url)
        data = reader.read()
        if cls != data.__class__:
            data = cls(data)
        return data

    # Helper function for __setitem__ and insert:
    # Set the row of table data matrices
    # noinspection PyProtectedMember
    def _set_row(self, example, row):
        domain = self.domain
        if isinstance(example, Instance):
            if example.domain == domain:
                if isinstance(example, RowInstance):
                    self.X[row] = example._x
                    self._Y[row] = example._y
                else:
                    self.X[row] = example._x
                    self._Y[row] = example._y
                self.metas[row] = example._metas
                return

            self.X[row], self._Y[row], self.metas[row] = \
                self.domain.convert(example)
            try:
                self.ids[row] = example.id
            except:
                with type(self)._next_instance_lock:
                    self.ids[row] = type(self)._next_instance_id
                    type(self)._next_instance_id += 1

        else:
            self.X[row] = [var.to_val(val)
                           for var, val in zip(domain.attributes, example)]
            self._Y[row] = [var.to_val(val)
                            for var, val in
                            zip(domain.class_vars,
                                example[len(domain.attributes):])]
            self.metas[row] = np.array([var.Unknown for var in domain.metas],
                                       dtype=object)

    def _check_all_dense(self):
        return all(x in (Storage.DENSE, Storage.MISSING)
                   for x in (self.X_density(), self.Y_density(),
                             self.metas_density()))

    # A helper function for extend and insert
    # Resize X, Y, metas and W.
    def _resize_all(self, new_length):
        old_length = self.X.shape[0]
        if old_length == new_length:
            return
        if not self._check_all_dense():
            raise ValueError("Tables with sparse data cannot be resized")
        try:
            self.X.resize(new_length, self.X.shape[1])
            self._Y.resize(new_length, self._Y.shape[1])
            self.metas.resize(new_length, self.metas.shape[1])
            if self.W.ndim == 2:
                self.W.resize((new_length, 0))
            else:
                self.W.resize(new_length)
            self.ids.resize(new_length)
        except Exception:
            if self.X.shape[0] == new_length:
                self.X.resize(old_length, self.X.shape[1])
            if self._Y.shape[0] == new_length:
                self._Y.resize(old_length, self._Y.shape[1])
            if self.metas.shape[0] == new_length:
                self.metas.resize(old_length, self.metas.shape[1])
            if self.W.shape[0] == new_length:
                if self.W.ndim == 2:
                    self.W.resize((old_length, 0))
                else:
                    self.W.resize(old_length)
            if self.ids.shape[0] == new_length:
                self.ids.resize(old_length)
            raise

    def __getitem__(self, key):
        if isinstance(key, Integral):
            return RowInstance(self, key)
        if not isinstance(key, tuple):
            return self.from_table_rows(self, key)

        if len(key) != 2:
            raise IndexError("Table indices must be one- or two-dimensional")

        row_idx, col_idx = key
        if isinstance(row_idx, Integral):
            if isinstance(col_idx, (str, Integral, Variable)):
                col_idx = self.domain.index(col_idx)
                var = self.domain[col_idx]
                if 0 <= col_idx < len(self.domain.attributes):
                    return Value(var, self.X[row_idx, col_idx])
                elif col_idx >= len(self.domain.attributes):
                    return Value(
                        var,
                        self._Y[row_idx,
                                col_idx - len(self.domain.attributes)])
                elif col_idx < 0:
                    return Value(var, self.metas[row_idx, -1 - col_idx])
            else:
                row_idx = [row_idx]

        # multiple rows OR single row but multiple columns:
        # construct a new table
        attributes, col_indices = self.domain._compute_col_indices(col_idx)
        if attributes is not None:
            n_attrs = len(self.domain.attributes)
            r_attrs = [attributes[i]
                       for i, col in enumerate(col_indices)
                       if 0 <= col < n_attrs]
            r_classes = [attributes[i]
                         for i, col in enumerate(col_indices)
                         if col >= n_attrs]
            r_metas = [attributes[i]
                       for i, col in enumerate(col_indices) if col < 0]
            domain = Domain(r_attrs, r_classes, r_metas)
        else:
            domain = self.domain
        return self.from_table(domain, self, row_idx)

    def __setitem__(self, key, value):
        if not isinstance(key, tuple):
            if isinstance(value, Real):
                self.X[key, :] = value
                return
            self._set_row(value, key)
            return

        if len(key) != 2:
            raise IndexError("Table indices must be one- or two-dimensional")
        row_idx, col_idx = key

        # single row
        if isinstance(row_idx, Integral):
            if isinstance(col_idx, slice):
                col_idx = range(*slice.indices(col_idx, self.X.shape[1]))
            if not isinstance(col_idx, str) and isinstance(col_idx, Iterable):
                col_idx = list(col_idx)
            if not isinstance(col_idx, str) and isinstance(col_idx, Sized):
                if isinstance(value, (Sequence, np.ndarray)):
                    values = value
                elif isinstance(value, Iterable):
                    values = list(value)
                else:
                    raise TypeError("Setting multiple values requires a "
                                    "sequence or numpy array")
                if len(values) != len(col_idx):
                    raise ValueError("Invalid number of values")
            else:
                col_idx, values = [col_idx], [value]
            for value, col_idx in zip(values, col_idx):
                if not isinstance(value, Integral):
                    value = self.domain[col_idx].to_val(value)
                if not isinstance(col_idx, Integral):
                    col_idx = self.domain.index(col_idx)
                if col_idx >= 0:
                    if col_idx < self.X.shape[1]:
                        self.X[row_idx, col_idx] = value
                    else:
                        self._Y[row_idx, col_idx - self.X.shape[1]] = value
                else:
                    self.metas[row_idx, -1 - col_idx] = value

        # multiple rows, multiple columns
        attributes, col_indices = self.domain._compute_col_indices(col_idx)
        if col_indices is ...:
            col_indices = range(len(self.domain))
        n_attrs = self.X.shape[1]
        if isinstance(value, str):
            if not attributes:
                attributes = self.domain.attributes
            for var, col in zip(attributes, col_indices):
                if 0 <= col < n_attrs:
                    self.X[row_idx, col] = var.to_val(value)
                elif col >= n_attrs:
                    self._Y[row_idx, col - n_attrs] = var.to_val(value)
                else:
                    self.metas[row_idx, -1 - col] = var.to_val(value)
        else:
            attr_cols = np.fromiter(
                (col for col in col_indices if 0 <= col < n_attrs), int)
            class_cols = np.fromiter(
                (col - n_attrs for col in col_indices if col >= n_attrs), int)
            meta_cols = np.fromiter(
                (-1 - col for col in col_indices if col < 0), int)
            if value is None:
                value = Unknown

            if not isinstance(value, (Real, np.ndarray)) and \
                    (len(attr_cols) or len(class_cols)):
                raise TypeError(
                    "Ordinary attributes can only have primitive values")
            if len(attr_cols):
                self.X[row_idx, attr_cols] = value
            if len(class_cols):
                self._Y[row_idx, class_cols] = value
            if len(meta_cols):
                self.metas[row_idx, meta_cols] = value

    def __delitem__(self, key):
        pending_deprecation_resize("__delitem__(key)")
        if not self._check_all_dense():
            raise ValueError("Rows of sparse data cannot be deleted")
        if key is ...:
            key = range(len(self))
        self.X = np.delete(self.X, key, axis=0)
        self.Y = np.delete(self._Y, key, axis=0)
        self.metas = np.delete(self.metas, key, axis=0)
        self.W = np.delete(self.W, key, axis=0)
        self.ids = np.delete(self.ids, key, axis=0)

    def __len__(self):
        return self.X.shape[0]

    def __str__(self):
        return "[" + ",\n ".join(str(ex) for ex in self) + "]"

    def __repr__(self):
        head = 5
        if self.is_sparse():
            head = min(self.X.shape[0], head)
        s = "[" + ",\n ".join(repr(ex) for ex in self[:head])
        if len(self) > head:
            s += ",\n ..."
        s += "\n]"
        return s

    def clear(self):
        """Remove all rows from the table."""
        pending_deprecation_resize("clear()")
        if not self._check_all_dense():
            raise ValueError("Tables with sparse data cannot be cleared")
        del self[...]

    def append(self, instance):
        """
        Append a data instance to the table.

        :param instance: a data instance
        :type instance: Orange.data.Instance or a sequence of values
        """
        pending_deprecation_resize("append(inst)")
        self.insert(len(self), instance)

    def insert(self, row, instance):
        """
        Insert a data instance into the table.

        :param row: row index
        :type row: int
        :param instance: a data instance
        :type instance: Orange.data.Instance or a sequence of values
        """
        pending_deprecation_resize("insert(i, inst)")
        if row < 0:
            row += len(self)
        if row < 0 or row > len(self):
            raise IndexError("Index out of range")
        self.ensure_copy()  # ensure that numpy arrays are single-segment for resize
        self._resize_all(len(self) + 1)
        if row < len(self):
            self.X[row + 1:] = self.X[row:-1]
            self._Y[row + 1:] = self._Y[row:-1]
            self.metas[row + 1:] = self.metas[row:-1]
            self.W[row + 1:] = self.W[row:-1]
            self.ids[row + 1:] = self.ids[row:-1]
        try:
            self._set_row(instance, row)
            if self.W.shape[-1]:
                self.W[row] = 1
        except Exception:
            self.X[row:-1] = self.X[row + 1:]
            self._Y[row:-1] = self._Y[row + 1:]
            self.metas[row:-1] = self.metas[row + 1:]
            self.W[row:-1] = self.W[row + 1:]
            self.ids[row:-1] = self.ids[row + 1:]
            self._resize_all(len(self) - 1)
            raise

    def extend(self, instances):
        """
        Extend the table with the given instances. The instances can be given
        as a table of the same or a different domain, or a sequence. In the
        latter case, each instances can be given as
        :obj:`~Orange.data.Instance` or a sequence of values (e.g. list,
        tuple, numpy.array).

        :param instances: additional instances
        :type instances: Orange.data.Table or a sequence of instances
        """
        pending_deprecation_resize("extend(insts)")
        if isinstance(instances, Table) and instances.domain == self.domain:
            self.X = vstack((self.X, instances.X))
            self._Y = vstack((self._Y, instances._Y))
            self.metas = vstack((self.metas, instances.metas))
            self.W = vstack((self.W, instances.W))
            self.ids = hstack((self.ids, instances.ids))
        else:
            try:
                old_length = len(self)
                self._resize_all(old_length + len(instances))
                for i, example in enumerate(instances):
                    self[old_length + i] = example
                    try:
                        self.ids[old_length + i] = example.id
                    except AttributeError:
                        self.ids[old_length + i] = self.new_id()
            except Exception:
                self._resize_all(old_length)
                raise

    @classmethod
    def concatenate(cls, tables, axis=1):
        """Return concatenation of `tables` by `axis`."""
        def vstack(arrs):
            return [np, sp][any(sp.issparse(arr) for arr in arrs)].vstack(arrs)

        def merge1d(arrs):
            arrs = list(arrs)
            ydims = {arr.ndim for arr in arrs}
            if ydims == {1}:
                return np.hstack(arrs)
            else:
                return vstack([
                    arr if arr.ndim == 2 else np.atleast_2d(arr).T
                    for arr in arrs
                ])

        def collect(attr):
            return [getattr(arr, attr) for arr in tables]

        if not tables:
            raise ValueError('need at least one table to concatenate')
        if len(tables) == 1:
            return tables[0].copy()
        CONCAT_ROWS, CONCAT_COLS = 0, 1
        if axis == CONCAT_ROWS:
            domain = tables[0].domain
            if any(table.domain != domain for table in tables):
                raise ValueError('concatenated tables must have the same domain')

            conc = cls.from_numpy(
                domain,
                vstack(collect("X")),
                merge1d(collect("Y")),
                vstack(collect("metas")),
                merge1d(collect("W"))
            )
            conc.ids = np.hstack([table.ids for table in tables])
            names = [table.name for table in tables if table.name != "untitled"]
            if names:
                conc.name = names[0]
            # TODO: Add attributes = {} to __init__
            conc.attributes = getattr(conc, "attributes", {})
            for table in reversed(tables):
                conc.attributes.update(table.attributes)
            return conc
        elif axis == CONCAT_COLS:
            pending_deprecation_resize("concatenate with axis=1")
            if reduce(operator.iand,
                      (set(map(operator.attrgetter('name'),
                               chain(t.domain.variables, t.domain.metas)))
                       for t in tables)):
                raise ValueError('Concatenating two domains with variables '
                                 'with same name is undefined')
            domain = Domain(flatten(t.domain.attributes for t in tables),
                            flatten(t.domain.class_vars for t in tables),
                            flatten(t.domain.metas for t in tables))

            def ndmin(A):
                return A if A.ndim > 1 else A.reshape(A.shape[0], 1)

            table = Table.from_numpy(domain,
                                     np.hstack(tuple(ndmin(t.X) for t in tables)),
                                     np.hstack(tuple(ndmin(t.Y) for t in tables)),
                                     np.hstack(tuple(ndmin(t.metas) for t in tables)),
                                     np.hstack(tuple(ndmin(t.W) for t in tables)))
            return table
        raise ValueError('axis {} out of bounds [0, 2)'.format(axis))

    def is_view(self):
        """
        Return `True` if all arrays represent a view referring to another table
        """
        return ((not self.X.shape[-1] or self.X.base is not None) and
                (not self._Y.shape[-1] or self._Y.base is not None) and
                (not self.metas.shape[-1] or self.metas.base is not None) and
                (not self._weights.shape[-1] or self.W.base is not None))

    def is_copy(self):
        """
        Return `True` if the table owns its data
        """
        return ((not self.X.shape[-1] or self.X.base is None) and
                (self._Y.base is None) and
                (self.metas.base is None) and
                (self.W.base is None))

    def is_sparse(self):
        """
        Return `True` if the table stores data in sparse format
        """
        return any(sp.issparse(i) for i in [self.X, self.Y, self.metas])

    def ensure_copy(self):
        """
        Ensure that the table owns its data; copy arrays when necessary.
        """
        def is_view(x):
            # Sparse matrices don't have views like numpy arrays. Since indexing on
            # them creates copies in constructor we can skip this check here.
            return not sp.issparse(x) and x.base is not None

        if is_view(self.X):
            self.X = self.X.copy()
        if is_view(self._Y):
            self._Y = self._Y.copy()
        if is_view(self.metas):
            self.metas = self.metas.copy()
        if is_view(self.W):
            self.W = self.W.copy()

    def copy(self):
        """
        Return a copy of the table
        """
        t = self.__class__(self)
        t.ensure_copy()
        return t

    @staticmethod
    def __determine_density(data):
        if data is None:
            return Storage.Missing
        if data is not None and sp.issparse(data):
            return Storage.SPARSE_BOOL if (data.data == 1).all() else Storage.SPARSE
        else:
            return Storage.DENSE

    def X_density(self):
        if not hasattr(self, "_X_density"):
            self._X_density = self.__determine_density(self.X)
        return self._X_density

    def Y_density(self):
        if not hasattr(self, "_Y_density"):
            self._Y_density = self.__determine_density(self._Y)
        return self._Y_density

    def metas_density(self):
        if not hasattr(self, "_metas_density"):
            self._metas_density = self.__determine_density(self.metas)
        return self._metas_density

    def set_weights(self, weight=1):
        """
        Set weights of data instances; create a vector of weights if necessary.
        """
        if not self.W.shape[-1]:
            self.W = np.empty(len(self))
        self.W[:] = weight

    def has_weights(self):
        """Return `True` if the data instances are weighed. """
        return self.W.shape[-1] != 0

    def total_weight(self):
        """
        Return the total weight of instances in the table, or their number if
        they are unweighted.
        """
        if self.W.shape[-1]:
            return sum(self.W)
        return len(self)

    def has_missing(self):
        """Return `True` if there are any missing attribute or class values."""
        missing_x = not sp.issparse(self.X) and bn.anynan(self.X)   # do not check for sparse X
        return missing_x or bn.anynan(self._Y)

    def has_missing_attribute(self):
        """Return `True` if there are any missing attribute values."""
        return not sp.issparse(self.X) and bn.anynan(self.X)    # do not check for sparse X

    def has_missing_class(self):
        """Return `True` if there are any missing class values."""
        return bn.anynan(self._Y)

    def get_nan_frequency_attribute(self):
        if self.X.size == 0:
            return 0
        return np.isnan(self.X).sum() / self.X.size

    def get_nan_frequency_class(self):
        if self.Y.size == 0:
            return 0
        return np.isnan(self._Y).sum() / self._Y.size

    def checksum(self, include_metas=True):
        # TODO: zlib.adler32 does not work for numpy arrays with dtype object
        # (after pickling and unpickling such arrays, checksum changes)
        # Why, and should we fix it or remove it?
        """Return a checksum over X, Y, metas and W."""
        cs = zlib.adler32(np.ascontiguousarray(self.X))
        cs = zlib.adler32(np.ascontiguousarray(self._Y), cs)
        if include_metas:
            cs = zlib.adler32(np.ascontiguousarray(self.metas), cs)
        cs = zlib.adler32(np.ascontiguousarray(self.W), cs)
        return cs

    def shuffle(self):
        """Randomly shuffle the rows of the table."""
        if not self._check_all_dense():
            raise ValueError("Rows of sparse data cannot be shuffled")
        ind = np.arange(self.X.shape[0])
        np.random.shuffle(ind)
        self.X = self.X[ind]
        self._Y = self._Y[ind]
        self.metas = self.metas[ind]
        self.W = self.W[ind]

    def get_column_view(self, index):
        """
        Return a vector - as a view, not a copy - with a column of the table,
        and a bool flag telling whether this column is sparse. Note that
        vertical slicing of sparse matrices is inefficient.

        :param index: the index of the column
        :type index: int, str or Orange.data.Variable
        :return: (one-dimensional numpy array, sparse)
        """

        def rx(M):
            if sp.issparse(M):
                return np.asarray(M.todense())[:, 0], True
            else:
                return M, False

        if not isinstance(index, Integral):
            index = self.domain.index(index)
        if index >= 0:
            if index < self.X.shape[1]:
                return rx(self.X[:, index])
            else:
                return rx(self._Y[:, index - self.X.shape[1]])
        else:
            return rx(self.metas[:, -1 - index])

    def _filter_is_defined(self, columns=None, negate=False):
        if columns is None:
            if sp.issparse(self.X):
                remove = (self.X.indptr[1:] !=
                          self.X.indptr[-1:] + self.X.shape[1])
            else:
                remove = bn.anynan(self.X, axis=1)
            if sp.issparse(self._Y):
                remove = np.logical_or(remove, self._Y.indptr[1:] !=
                                       self._Y.indptr[-1:] + self._Y.shape[1])
            else:
                remove = np.logical_or(remove, bn.anynan(self._Y, axis=1))
        else:
            remove = np.zeros(len(self), dtype=bool)
            for column in columns:
                col, sparse = self.get_column_view(column)
                if sparse:
                    remove = np.logical_or(remove, col == 0)
                else:
                    remove = np.logical_or(remove, bn.anynan([col], axis=0))
        retain = remove if negate else np.logical_not(remove)
        return self.from_table_rows(self, retain)

    def _filter_has_class(self, negate=False):
        if sp.issparse(self._Y):
            if negate:
                retain = (self._Y.indptr[1:] !=
                          self._Y.indptr[-1:] + self._Y.shape[1])
            else:
                retain = (self._Y.indptr[1:] ==
                          self._Y.indptr[-1:] + self._Y.shape[1])
        else:
            retain = bn.anynan(self._Y, axis=1)
            if not negate:
                retain = np.logical_not(retain)
        return self.from_table_rows(self, retain)

    def _filter_same_value(self, column, value, negate=False):
        if not isinstance(value, Real):
            value = self.domain[column].to_val(value)
        sel = self.get_column_view(column)[0] == value
        if negate:
            sel = np.logical_not(sel)
        return self.from_table_rows(self, sel)

    def _filter_values(self, filter):
        selection = self._values_filter_to_indicator(filter)
        return self.from_table(self.domain, self, selection)

    def _values_filter_to_indicator(self, filter):
        """Return selection of rows matching the filter conditions

        Handles conjunction/disjunction and negate modifiers

        Parameters
        ----------
        filter: Values object containing the conditions

        Returns
        -------
        A 1d bool array. len(result) == len(self)
        """
        from Orange.data.filter import Values

        if isinstance(filter, Values):
            conditions = filter.conditions
            conjunction = filter.conjunction
        else:
            conditions = [filter]
            conjunction = True
        if conjunction:
            sel = np.ones(len(self), dtype=bool)
        else:
            sel = np.zeros(len(self), dtype=bool)

        for f in conditions:
            selection = self._filter_to_indicator(f)

            if conjunction:
                sel *= selection
            else:
                sel += selection

        if filter.negate:
            sel = ~sel
        return sel

    def _filter_to_indicator(self, filter):
        """Return selection of rows that match the condition.

        Parameters
        ----------
        filter: ValueFilter describing the condition

        Returns
        -------
        A 1d bool array. len(result) == len(self)
        """
        from Orange.data.filter import (
            FilterContinuous, FilterDiscrete, FilterRegex, FilterString,
            FilterStringList, Values
        )
        if isinstance(filter, Values):
            return self._values_filter_to_indicator(filter)

        col = self.get_column_view(filter.column)[0]

        if isinstance(filter, FilterDiscrete):
            return self._discrete_filter_to_indicator(filter, col)

        if isinstance(filter, FilterContinuous):
            return self._continuous_filter_to_indicator(filter, col)

        if isinstance(filter, FilterString):
            return self._string_filter_to_indicator(filter, col)

        if isinstance(filter, FilterStringList):
            if not filter.case_sensitive:
                col = np.char.lower(np.array(col, dtype=str))
                vals = [val.lower() for val in filter.values]
            else:
                vals = filter.values
            return reduce(operator.add, (col == val for val in vals))

        if isinstance(filter, FilterRegex):
            return np.vectorize(filter)(col)

        raise TypeError("Invalid filter")

    def _discrete_filter_to_indicator(self, filter, col):
        """Return selection of rows matched by the given discrete filter.

        Parameters
        ----------
        filter: FilterDiscrete
        col: np.ndarray

        Returns
        -------
        A 1d bool array. len(result) == len(self)
        """
        if filter.values is None:  # <- is defined filter
            col = col.astype(float)
            return ~np.isnan(col)

        sel = np.zeros(len(self), dtype=bool)
        for val in filter.values:
            if not isinstance(val, Real):
                val = self.domain[filter.column].to_val(val)
            sel += (col == val)
        return sel

    def _continuous_filter_to_indicator(self, filter, col):
        """Return selection of rows matched by the given continuous filter.

        Parameters
        ----------
        filter: FilterContinuous
        col: np.ndarray

        Returns
        -------
        A 1d bool array. len(result) == len(self)
        """
        if filter.oper == filter.IsDefined:
            col = col.astype(float)
            return ~np.isnan(col)

        return self._range_filter_to_indicator(filter, col, filter.min, filter.max)

    def _string_filter_to_indicator(self, filter, col):
        """Return selection of rows matched by the given string filter.

        Parameters
        ----------
        filter: FilterString
        col: np.ndarray

        Returns
        -------
        A 1d bool array. len(result) == len(self)
        """
        if filter.oper == filter.IsDefined:
            return col.astype(bool)

        col = col.astype(str)
        fmin = filter.min or ""
        fmax = filter.max or ""

        if not filter.case_sensitive:
            # convert all to lower case
            col = np.char.lower(col)
            fmin = fmin.lower()
            fmax = fmax.lower()

        if filter.oper == filter.Contains:
            return np.fromiter((fmin in e for e in col),
                               dtype=bool)
        if filter.oper == filter.StartsWith:
            return np.fromiter((e.startswith(fmin) for e in col),
                               dtype=bool)
        if filter.oper == filter.EndsWith:
            return np.fromiter((e.endswith(fmin) for e in col),
                               dtype=bool)

        return self._range_filter_to_indicator(filter, col, fmin, fmax)

    @staticmethod
    def _range_filter_to_indicator(filter, col, fmin, fmax):
        if filter.oper == filter.Equal:
            return col == fmin
        if filter.oper == filter.NotEqual:
            return col != fmin
        if filter.oper == filter.Less:
            return col < fmin
        if filter.oper == filter.LessEqual:
            return col <= fmin
        if filter.oper == filter.Greater:
            return col > fmin
        if filter.oper == filter.GreaterEqual:
            return col >= fmin
        if filter.oper == filter.Between:
            return (col >= fmin) * (col <= fmax)
        if filter.oper == filter.Outside:
            return (col < fmin) + (col > fmax)

        raise TypeError("Invalid operator")

    def _compute_basic_stats(self, columns=None,
                             include_metas=False, compute_variance=False):
        if compute_variance:
            raise NotImplementedError("computation of variance is "
                                      "not implemented yet")
        W = self.W if self.has_weights() else None
        rr = []
        stats = []
        if not columns:
            if self.domain.attributes:
                rr.append(fast_stats(self.X, W))
            if self.domain.class_vars:
                rr.append(fast_stats(self._Y, W))
            if include_metas and self.domain.metas:
                rr.append(fast_stats(self.metas, W))
            if len(rr):
                stats = np.vstack(tuple(rr))
        else:
            nattrs = len(self.domain.attributes)
            for column in columns:
                c = self.domain.index(column)
                if 0 <= c < nattrs:
                    S = fast_stats(self.X[:, [c]], W and W[:, [c]])
                elif c >= nattrs:
                    S = fast_stats(self._Y[:, [c-nattrs]], W and W[:, [c-nattrs]])
                else:
                    S = fast_stats(self.metas[:, [-1-c]], W and W[:, [-1-c]])
                stats.append(S[0])
        return stats

    def _compute_distributions(self, columns=None):
        if columns is None:
            columns = range(len(self.domain.variables))
        else:
            columns = [self.domain.index(var) for var in columns]

        distributions = []
        if sp.issparse(self.X):
            self.X = self.X.tocsc()

        W = self.W.ravel() if self.has_weights() else None

        for col in columns:
            variable = self.domain[col]

            # Select the correct data column from X, Y or metas
            if 0 <= col < self.X.shape[1]:
                x = self.X[:, col]
            elif col < 0:
                x = self.metas[:, col * (-1) - 1]
                if np.issubdtype(x.dtype, np.dtype(object)):
                    x = x.astype(float)
            else:
                x = self._Y[:, col - self.X.shape[1]]

            if variable.is_discrete:
                dist, unknowns = bincount(x, weights=W, max_val=len(variable.values) - 1)
            elif not x.shape[0]:
                dist, unknowns = np.zeros((2, 0)), 0
            else:
                if W is not None:
                    if sp.issparse(x):
                        arg_sort = np.argsort(x.data)
                        ranks = x.indices[arg_sort]
                        vals = np.vstack((x.data[arg_sort], W[ranks]))
                    else:
                        ranks = np.argsort(x)
                        vals = np.vstack((x[ranks], W[ranks]))
                else:
                    x_values = x.data if sp.issparse(x) else x
                    vals = np.ones((2, x_values.shape[0]))
                    vals[0, :] = x_values
                    vals[0, :].sort()

                dist = np.array(_valuecount.valuecount(vals))
                # If sparse, then 0s will not be counted with `valuecount`, so
                # we have to add them to the result manually.
                if sp.issparse(x) and sparse_has_implicit_zeros(x):
                    if W is not None:
                        zero_weights = sparse_implicit_zero_weights(x, W).sum()
                    else:
                        zero_weights = sparse_count_implicit_zeros(x)
                    zero_vec = [0, zero_weights]
                    dist = np.insert(dist, np.searchsorted(dist[0], 0), zero_vec, axis=1)
                # Since `countnans` assumes vector shape to be (1, n) and `x`
                # shape is (n, 1), we pass the transpose
                unknowns = countnans(x.T, W)
            distributions.append((dist, unknowns))

        return distributions

    def _compute_contingency(self, col_vars=None, row_var=None):
        n_atts = self.X.shape[1]

        if col_vars is None:
            col_vars = range(len(self.domain.variables))
        else:
            col_vars = [self.domain.index(var) for var in col_vars]
        if row_var is None:
            row_var = self.domain.class_var
            if row_var is None:
                raise ValueError("No row variable")

        row_desc = self.domain[row_var]
        if not row_desc.is_discrete:
            raise TypeError("Row variable must be discrete")
        row_indi = self.domain.index(row_var)
        n_rows = len(row_desc.values)
        if 0 <= row_indi < n_atts:
            row_data = self.X[:, row_indi]
        elif row_indi < 0:
            row_data = self.metas[:, -1 - row_indi]
        else:
            row_data = self._Y[:, row_indi - n_atts]

        W = self.W if self.has_weights() else None
        nan_inds = None

        col_desc = [self.domain[var] for var in col_vars]
        col_indi = [self.domain.index(var) for var in col_vars]

        if any(not (var.is_discrete or var.is_continuous)
               for var in col_desc):
            raise ValueError("contingency can be computed only for discrete "
                             "and continuous values")

        if row_data.dtype.kind != "f": #meta attributes can be stored as type object
            row_data = row_data.astype(float)

        unknown_rows = countnans(row_data)
        if unknown_rows:
            nan_inds = np.isnan(row_data)
            row_data = row_data[~nan_inds]
            if W:
                W = W[~nan_inds]
                unknown_rows = np.sum(W[nan_inds])

        contingencies = [None] * len(col_desc)
        for arr, f_cond, f_ind in (
                (self.X, lambda i: 0 <= i < n_atts, lambda i: i),
                (self._Y, lambda i: i >= n_atts, lambda i: i - n_atts),
                (self.metas, lambda i: i < 0, lambda i: -1 - i)):

            if nan_inds is not None:
                arr = arr[~nan_inds]

            arr_indi = [e for e, ind in enumerate(col_indi) if f_cond(ind)]

            vars = [(e, f_ind(col_indi[e]), col_desc[e]) for e in arr_indi]
            disc_vars = [v for v in vars if v[2].is_discrete]
            if disc_vars:
                if sp.issparse(arr):
                    max_vals = max(len(v[2].values) for v in disc_vars)
                    disc_indi = {i for _, i, _ in disc_vars}
                    mask = [i in disc_indi for i in range(arr.shape[1])]
                    conts, nans = contingency(arr, row_data, max_vals - 1,
                                              n_rows - 1, W, mask)
                    for col_i, arr_i, var in disc_vars:
                        n_vals = len(var.values)
                        contingencies[col_i] = (conts[arr_i][:, :n_vals],
                                                nans[arr_i])
                else:
                    for col_i, arr_i, var in disc_vars:
                        contingencies[col_i] = contingency(
                            arr[:, arr_i].astype(float),
                            row_data, len(var.values) - 1, n_rows - 1, W)

            cont_vars = [v for v in vars if v[2].is_continuous]
            if cont_vars:

                classes = row_data.astype(dtype=np.intp)
                if W is not None:
                    W = W.astype(dtype=np.float64)
                if sp.issparse(arr):
                    arr = sp.csc_matrix(arr)

                for col_i, arr_i, _ in cont_vars:
                    if sp.issparse(arr):
                        col_data = arr.data[arr.indptr[arr_i]:arr.indptr[arr_i + 1]]
                        rows = arr.indices[arr.indptr[arr_i]:arr.indptr[arr_i + 1]]
                        W_ = None if W is None else W[rows]
                        classes_ = classes[rows]
                    else:
                        col_data, W_, classes_ = arr[:, arr_i], W, classes

                    col_data = col_data.astype(dtype=np.float64)
                    U, C, unknown = _contingency.contingency_floatarray(
                        col_data, classes_, n_rows, W_)
                    contingencies[col_i] = ([U, C], unknown)

        return contingencies, unknown_rows

    @classmethod
    def transpose(cls, table, feature_names_column="", meta_attr_name="Feature name",
                  feature_name="Feature"):
        """
        Transpose the table.

        :param table: Table - table to transpose
        :param feature_names_column: str - name of (String) meta attribute to
            use for feature names
        :param meta_attr_name: str - name of new meta attribute into which
            feature names are mapped
        :return: Table - transposed table
        """

        self = cls()
        n_cols, self.n_rows = table.X.shape
        old_domain = table.attributes.get("old_domain")

        # attributes
        # - classes and metas to attributes of attributes
        # - arbitrary meta column to feature names
        self.X = table.X.T
        attributes = [ContinuousVariable(str(row[feature_names_column]))
                      for row in table] if feature_names_column else \
            [ContinuousVariable(feature_name + " " + str(i + 1).zfill(
                int(np.ceil(np.log10(n_cols))))) for i in range(n_cols)]
        if old_domain is not None and feature_names_column:
            for i, _ in enumerate(attributes):
                if attributes[i].name in old_domain:
                    var = old_domain[attributes[i].name]
                    attr = ContinuousVariable(var.name) if var.is_continuous \
                        else DiscreteVariable(var.name, var.values)
                    attr.attributes = var.attributes.copy()
                    attributes[i] = attr

        def set_attributes_of_attributes(_vars, _table):
            for i, variable in enumerate(_vars):
                if variable.name == feature_names_column:
                    continue
                for j, row in enumerate(_table):
                    value = variable.repr_val(row) if np.isscalar(row) \
                        else row[i] if isinstance(row[i], str) \
                        else variable.repr_val(row[i])

                    if value not in MISSING_VALUES:
                        attributes[j].attributes[variable.name] = value

        set_attributes_of_attributes(table.domain.class_vars, table.Y)
        set_attributes_of_attributes(table.domain.metas, table.metas)

        # weights
        self.W = np.empty((self.n_rows, 0))

        def get_table_from_attributes_of_attributes(_vars, _dtype=float):
            T = np.empty((self.n_rows, len(_vars)), dtype=_dtype)
            for i, _attr in enumerate(table.domain.attributes):
                for j, _var in enumerate(_vars):
                    val = str(_attr.attributes.get(_var.name, ""))
                    if not _var.is_string:
                        val = np.nan if val in MISSING_VALUES else \
                            _var.values.index(val) if \
                                _var.is_discrete else float(val)
                    T[i, j] = val
            return T

        # class_vars - attributes of attributes to class - from old domain
        class_vars = []
        if old_domain is not None:
            class_vars = old_domain.class_vars
        self.Y = get_table_from_attributes_of_attributes(class_vars)

        # metas
        # - feature names and attributes of attributes to metas
        self.metas, metas = np.empty((self.n_rows, 0), dtype=object), []
        if meta_attr_name not in [m.name for m in table.domain.metas] and \
                table.domain.attributes:
            self.metas = np.array([[a.name] for a in table.domain.attributes],
                                  dtype=object)
            metas.append(StringVariable(meta_attr_name))

        names = chain.from_iterable(list(attr.attributes)
                                    for attr in table.domain.attributes)
        names = sorted(set(names) - {var.name for var in class_vars})

        def guessed_var(i, var_name):
            orig_vals = M[:, i]
            val_map, vals, var_type = Orange.data.io.guess_data_type(orig_vals)
            values, variable = Orange.data.io.sanitize_variable(
                val_map, vals, orig_vals, var_type, {}, name=var_name)
            M[:, i] = values
            return variable

        _metas = [StringVariable(n) for n in names]
        if old_domain is not None:
            _metas = [m for m in old_domain.metas if m.name != meta_attr_name]
        M = get_table_from_attributes_of_attributes(_metas, _dtype=object)
        if old_domain is None:
            _metas = [guessed_var(i, m.name) for i, m in enumerate(_metas)]
        if _metas:
            self.metas = np.hstack((self.metas, M))
            metas.extend(_metas)

        self.domain = Domain(attributes, class_vars, metas)
        cls._init_ids(self)
        self.attributes = table.attributes.copy()
        self.attributes["old_domain"] = table.domain
        return self

    def to_sparse(self, sparse_attributes=True, sparse_class=False,
                  sparse_metas=False):
        def sparsify(features):
            for f in features:
                f.sparse = True

        new_domain = self.domain.copy()

        if sparse_attributes:
            sparsify(new_domain.attributes)
        if sparse_class:
            sparsify(new_domain.class_vars)
        if sparse_metas:
            sparsify(new_domain.metas)
        return self.transform(new_domain)

    def to_dense(self, dense_attributes=True, dense_class=True,
                 dense_metas=True):
        def densify(features):
            for f in features:
                f.sparse = False

        new_domain = self.domain.copy()

        if dense_attributes:
            densify(new_domain.attributes)
        if dense_class:
            densify(new_domain.class_vars)
        if dense_metas:
            densify(new_domain.metas)
        t = self.transform(new_domain)
        t.ids = self.ids    # preserve indices
        return t


def _check_arrays(*arrays, dtype=None):
    checked = []
    if not len(arrays):
        return checked

    def ninstances(array):
        if hasattr(array, "shape"):
            return array.shape[0]
        else:
            return len(array) if array is not None else 0

    shape_1 = ninstances(arrays[0])

    for array in arrays:
        if array is None:
            checked.append(array)
            continue

        if ninstances(array) != shape_1:
            raise ValueError("Leading dimension mismatch (%d != %d)"
                             % (ninstances(array), shape_1))

        if sp.issparse(array):
            array.data = np.asarray(array.data)
            has_inf = _check_inf(array.data)
        else:
            if dtype is not None:
                array = np.asarray(array, dtype=dtype)
            else:
                array = np.asarray(array)
            has_inf = _check_inf(array)

        if has_inf:
            raise ValueError("Array contains infinity.")
        checked.append(array)

    return checked


def _check_inf(array):
    return array.dtype.char in np.typecodes['AllFloat'] and \
           np.isinf(array.data).any()


def _subarray(arr, rows, cols):
    rows = _optimize_indices(rows, arr.shape[0])
    cols = _optimize_indices(cols, arr.shape[1])
    return arr[_rxc_ix(rows, cols)]


def _optimize_indices(indices, maxlen):
    """
    Convert integer indices to slice if possible. It only converts increasing
    integer ranges with positive steps and valid starts and ends.
    Only convert valid ends so that invalid ranges will still raise
    an exception.

    Allows numpy to reuse the data array, because it defaults to copying
    if given indices.

    Parameters
    ----------
    indices : 1D sequence, slice or Ellipsis
    """
    if isinstance(indices, slice):
        return indices

    if indices is ...:
        return slice(None, None, 1)

    if len(indices) >= 1:
        indices = np.asarray(indices)
        if indices.dtype != np.bool:
            begin = indices[0]
            end = indices[-1]
            steps = np.diff(indices) if len(indices) > 1 else np.array([1])
            step = steps[0]

            # continuous ranges with constant step and valid start and stop index can be slices
            if np.all(steps == step) and step > 0 and begin >= 0 and end < maxlen:
                return slice(begin, end + step, step)

    return indices


def _rxc_ix(rows, cols):
    """
    Construct an index object to index the `rows` x `cols` cross product.

    Rows and columns can be a 1d bool or int sequence, or a slice.
    The later is a convenience and is interpreted the same
    as `slice(None, None, -1)`

    Parameters
    ----------
    rows : 1D sequence, slice
        Row indices.
    cols : 1D sequence, slice
        Column indices.

    See Also
    --------
    numpy.ix_

    Examples
    --------
    >>> import numpy as np
    >>> a = np.arange(10).reshape(2, 5)
    >>> a[_rxc_ix([0, 1], [3, 4])]
    array([[3, 4],
           [8, 9]])
    >>> a[_rxc_ix([False, True], slice(None, None, 1))]
    array([[5, 6, 7, 8, 9]])

    """
    isslice = (isinstance(rows, slice), isinstance(cols, slice))
    if isslice == (True, True):
        return rows, cols
    elif isslice == (True, False):
        return rows, np.asarray(np.ix_(cols), int).ravel()
    elif isslice == (False, True):
        return np.asarray(np.ix_(rows), int).ravel(), cols
    else:
        r, c = np.ix_(rows, cols)
        return np.asarray(r, int), np.asarray(c, int)


def assure_domain_conversion_sparsity(target, source):
    """
    Assure that the table obeys the domain conversion's suggestions about sparsity.

    Args:
        target (Table): the target table.
        source (Table): the source table.

    Returns:
        Table: with fixed sparsity. The sparsity is set as it is recommended by domain conversion
            for transformation from source to the target domain.
    """
    conversion = target.domain.get_conversion(source.domain)
    match_density = [assure_array_dense, assure_array_sparse]
    target.X = match_density[conversion.sparse_X](target.X)
    target.Y = match_density[conversion.sparse_Y](target.Y)
    target.metas = match_density[conversion.sparse_metas](target.metas)
    return target

```
--- 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