{
    "file_diffs": [
        {
            "old_file_content": "# This module defines abstract base classes; derived classes are abstract, too\n# pylint: disable=abstract-method\n\nimport numpy as np\nimport sklearn.metrics as skl_metrics\n\nfrom Orange.data import Table, Domain, Instance, RowInstance\nfrom Orange.misc import DistMatrix\nfrom Orange.preprocess import SklImpute\nfrom Orange.statistics import util\n\n\n# TODO: When we upgrade to numpy 1.13, change use argument copy=False in\n# nan_to_num instead of assignment\n\n# TODO this *private* function is called from several widgets to prepare\n# data for calling the below classes. After we (mostly) stopped relying\n# on sklearn.metrics, this is (mostly) unnecessary\n# Afterwards, also remove the following line:\n# pylint: disable=redefined-outer-name\ndef _preprocess(table, impute=True):\n    \"\"\"Remove categorical attributes and impute missing values.\"\"\"\n    if not len(table):  # this can be an array, pylint: disable=len-as-condition\n        return table\n    new_domain = Domain(\n        [a for a in table.domain.attributes if a.is_continuous],\n        table.domain.class_vars,\n        table.domain.metas)\n    new_data = table.transform(new_domain)\n    if impute:\n        new_data = SklImpute()(new_data)\n    return new_data\n\n\n# TODO I have put this function here as a substitute the above `_preprocess`.\n# None of them really belongs here; (re?)move them, eventually.\ndef remove_discrete_features(data):\n    \"\"\"Remove discrete columns from the data.\"\"\"\n    new_domain = Domain(\n        [a for a in data.domain.attributes if a.is_continuous],\n        data.domain.class_vars,\n        data.domain.metas)\n    return data.transform(new_domain)\n\n\ndef remove_nonbinary_features(data):\n    \"\"\"Remove non-binary columns from the data.\"\"\"\n    new_domain = Domain(\n        [a for a in data.domain.attributes\n         if a.is_discrete and len(a.values) == 2],\n        data.domain.class_vars,\n        data.domain.metas)\n    return data.transform(new_domain)\n\ndef impute(data):\n    \"\"\"Impute missing values.\"\"\"\n    return SklImpute()(data)\n\n\ndef _orange_to_numpy(x):\n    \"\"\"\n    Return :class:`numpy.ndarray` (dense or sparse) with attribute data\n    from the given instance of :class:`Orange.data.Table`,\n    :class:`Orange.data.RowInstance` or :class:`Orange.data.Instance`.\n    \"\"\"\n    if isinstance(x, Table):\n        return x.X\n    elif isinstance(x, Instance):\n        return np.atleast_2d(x.x)\n    elif isinstance(x, np.ndarray):\n        return np.atleast_2d(x)\n    else:\n        return x  # e.g. None\n\n\nclass Distance:\n    \"\"\"\n    Base class for construction of distances models (:obj:`DistanceModel`).\n\n    Distances can be computed between all pairs of rows in one table, or\n    between pairs where one row is from one table and one from another.\n\n    If `axis` is set to `0`, the class computes distances between all pairs\n    of columns in a table. Distances between columns from separate tables are\n    probably meaningless, thus unsupported.\n\n    The class can be used as follows:\n\n    - Constructor is called only with keyword argument `axis` that\n      specifies the axis over which the distances are computed, and with other\n      subclass-specific keyword arguments.\n    - Next, we call the method `fit(data)` to produce an instance of\n      :obj:`DistanceModel`; the instance stores any parameters needed for\n      computation of distances, such as statistics for normalization and\n      handling of missing data.\n    - We can then call the :obj:`DistanceModel` with data to compute the\n      distance between its rows or columns, or with two data tables to\n      compute distances between all pairs of rows.\n\n    The second, shorter way to use this class is to call the constructor with\n    one or two data tables and any additional keyword arguments. Constructor\n    will execute the above steps and return :obj:`~Orange.misc.DistMatrix`.\n    Such usage is here for backward compatibility, practicality and efficiency.\n\n    Args:\n        e1 (:obj:`~Orange.data.Table` or :obj:`~Orange.data.Instance` or \\\n                :obj:`np.ndarray` or `None`):\n            data on which to train the model and compute the distances\n        e2 (:obj:`~Orange.data.Table` or :obj:`~Orange.data.Instance` or \\\n                :obj:`np.ndarray` or `None`):\n            if present, the class computes distances with pairs coming from\n            the two tables\n        axis (int):\n            axis over which the distances are computed, 1 (default) for\n            rows, 0 for columns\n        impute (bool):\n            if `True` (default is `False`), nans in the computed distances\n            are replaced with zeros, and infs with very large numbers.\n        callback (callable or None):\n            callback function\n\n    Attributes:\n        axis (int):\n            axis over which the distances are computed, 1 (default) for\n            rows, 0 for columns\n        impute (bool):\n            if `True` (default is `False`), nans in the computed distances\n            are replaced with zeros, and infs with very large numbers.\n        normalize (bool):\n            if `True`, columns are normalized before computation. This attribute\n            applies only if the distance supports normalization.\n\n    The capabilities of the metrics are described with class attributes.\n\n    If class attribute `supports_discrete` is `True`, the distance\n    also uses discrete attributes to compute row distances. The use of discrete\n    attributes depends upon the type of distance; e.g. Jaccard distance observes\n    whether the value is zero or non-zero, while Euclidean and Manhattan\n    distance observes whether a pair of values is same or different.\n\n    Class attribute `supports_missing` indicates that the distance can cope\n    with missing data. In such cases, letting the distance handle it should\n    be preferred over pre-imputation of missing values.\n\n    Class attribute `supports_normalization` indicates that the constructor\n    accepts an argument `normalize`. If set to `True`, the metric will attempt\n    to normalize the values in a sense that each attribute will have equal\n    influence. For instance, the Euclidean distance subtract the mean and\n    divides the result by the deviation, while Manhattan distance uses the\n    median and MAD.\n\n    If class attribute `supports_sparse` is `True`, the class will handle\n    sparse data. Currently, all classes that do handle it rely on fallbacks to\n    SKL metrics. These, however, do not support discrete data and missing\n    values, and will fail silently.\n    \"\"\"\n    supports_sparse = False\n    supports_discrete = False\n    supports_normalization = False\n    supports_missing = True\n\n    # Predefined here to silence pylint, which doesn't look into __new__\n    normalize = False\n    axis = 1\n    impute = False\n\n    def __new__(cls, e1=None, e2=None, axis=1, impute=False,\n                callback=None, **kwargs):\n        self = super().__new__(cls)\n        self.axis = axis\n        self.impute = impute\n        self.callback = callback\n        # Ugly, but needed to allow allow setting subclass-specific parameters\n        # (such as normalize) when `e1` is not `None` and the `__new__` in the\n        # subclass is skipped\n        self.__dict__.update(**kwargs)\n        if e1 is None:\n            return self\n\n        # Fallbacks for sparse data and numpy tables. Remove when subclasses\n        # no longer use fallbacks for sparse data, and handling numpy tables\n        # becomes obsolete (or handled elsewhere)\n        if (not hasattr(e1, \"domain\")\n                or hasattr(e1, \"is_sparse\") and e1.is_sparse()):\n            fallback = getattr(self, \"fallback\", None)\n            if fallback is not None:\n                # pylint: disable=not-callable\n                return fallback(e1, e2, axis, impute)\n\n        # Magic constructor\n        model = self.fit(e1)\n        return model(e1, e2)\n\n    def fit(self, data):\n        \"\"\"\n        Abstract method returning :obj:`DistanceModel` fit to the data\n\n        Args:\n            e1 (Orange.data.Table, Orange.data.Instance, np.ndarray):\n                data for fitting the distance model\n\n        Returns:\n            model (DistanceModel)\n        \"\"\"\n        raise NotImplementedError\n\n    @staticmethod\n    def check_no_discrete(n_vals):\n        \"\"\"\n        Raise an exception if there are any discrete attributes.\n\n        Args:\n            n_vals (list of int): number of attributes values, 0 for continuous\n        \"\"\"\n        if any(n_vals):\n            raise ValueError(\"columns with discrete values are incommensurable\")\n\n\nclass DistanceModel:\n    \"\"\"\n    Base class for classes that compute distances between data rows or columns.\n    Instances of these classes are not constructed directly but returned by\n    the corresponding instances of :obj:`Distance`.\n\n    Attributes:\n        axis (int, readonly):\n            axis over which the distances are computed, 1 (default) for\n            rows, 0 for columns\n        impute (bool):\n            if `True` (default is `False`), nans in the computed distances\n            are replaced with zeros, and infs with very large numbers\n        callback (callable or None):\n            callback function\n\n    \"\"\"\n    def __init__(self, axis, impute=False, callback=None):\n        self._axis = axis\n        self.impute = impute\n        self.callback = callback\n\n    @property\n    def axis(self):\n        return self._axis\n\n    def __call__(self, e1, e2=None):\n        \"\"\"\n        If e2 is omitted, calculate distances between all rows (axis=1) or\n        columns (axis=2) of e1. If e2 is present, calculate distances between\n        all pairs if rows from e1 and e2.\n\n        This method converts the data into numpy arrays, calls the method\n        `compute_data` and packs the result into `DistMatrix`. Subclasses are\n        expected to define the `compute_data` and not the `__call__` method.\n\n        Args:\n            e1 (Orange.data.Table or Orange.data.Instance or numpy.ndarray):\n                input data\n            e2 (Orange.data.Table or Orange.data.Instance or numpy.ndarray):\n                secondary data\n\n        Returns:\n            A distance matrix (Orange.misc.distmatrix.DistMatrix)\n        \"\"\"\n        if self.axis == 0 and e2 is not None:\n            # Backward compatibility fix\n            if e2 is e1:\n                e2 = None\n            else:\n                raise ValueError(\"Two tables cannot be compared by columns\")\n\n        x1 = _orange_to_numpy(e1)\n        x2 = _orange_to_numpy(e2)\n        with np.errstate(invalid=\"ignore\"):  # nans are handled below\n            dist = self.compute_distances(x1, x2)\n            if self.impute and np.isnan(dist).any():\n                dist = np.nan_to_num(dist)\n            if isinstance(e1, (Table, RowInstance)):\n                dist = DistMatrix(dist, e1, e2, self.axis)\n            else:\n                dist = DistMatrix(dist)\n            return dist\n\n    def compute_distances(self, x1, x2):\n        \"\"\"\n        Abstract method for computation of distances between rows or columns of\n        `x1`, or between rows of `x1` and `x2`. Do not call directly.\"\"\"\n        raise NotImplementedError\n\n\nclass FittedDistanceModel(DistanceModel):\n    \"\"\"\n    Base class for models that store attribute-related data for normalization\n    and imputation, and that treat discrete and continuous columns separately.\n\n    Attributes:\n        attributes (list of `Variable`): attributes on which the model was fit\n        discrete (np.ndarray): bool array indicating discrete attributes\n        continuous (np.ndarray): bool array indicating continuous attributes\n        normalize (bool):\n            if `True` (default is `False`) continuous columns are normalized\n        callback (callable or None): callback function\n    \"\"\"\n    def __init__(self, attributes, axis=1, impute=False, callback=None):\n        super().__init__(axis, impute, callback)\n        self.attributes = attributes\n        self.discrete = None\n        self.continuous = None\n        self.normalize = False\n\n    def __call__(self, e1, e2=None):\n        if self.attributes is not None and (\n                e1.domain.attributes != self.attributes\n                or e2 is not None and e2.domain.attributes != self.attributes):\n            raise ValueError(\"mismatching domains\")\n        return super().__call__(e1, e2)\n\n    def continuous_columns(self, x1, x2, offset, scale):\n        \"\"\"\n        Extract and scale continuous columns from data tables.\n        If the second table is None, it defaults to the first table.\n\n        Values are scaled if `self.normalize` is `True`.\n\n        Args:\n            x1 (np.ndarray): first table\n            x2 (np.ndarray or None): second table\n            offset (float): a constant (e.g. mean, median) subtracted from data\n            scale: (float): divider (e.g. deviation)\n\n        Returns:\n            data1 (np.ndarray): scaled continuous columns from `x1`\n            data2 (np.ndarray): scaled continuous columns from `x2` or `x1`\n        \"\"\"\n        if self.continuous.all() and not self.normalize:\n            data1, data2 = x1, x2\n        else:\n            data1 = x1[:, self.continuous]\n            if x2 is not None:\n                data2 = x2[:, self.continuous]\n            if self.normalize:\n                data1 = x1[:, self.continuous]\n                data1 -= offset\n                data1 /= scale\n                if x2 is not None:\n                    data2 = x2[:, self.continuous]\n                    data2 -= offset\n                    data2 /= scale\n        if x2 is None:\n            data2 = data1\n        return data1, data2\n\n    def discrete_columns(self, x1, x2):\n        \"\"\"\n        Return discrete columns from the given tables.\n        If the second table is None, it defaults to the first table.\n        \"\"\"\n        if self.discrete.all():\n            data1, data2 = x1, x1 if x2 is None else x2\n        else:\n            data1 = x1[:, self.discrete]\n            data2 = data1 if x2 is None else x2[:, self.discrete]\n        return data1, data2\n\n\nclass FittedDistance(Distance):\n    \"\"\"\n    Base class for fitting models that store attribute-related data for\n    normalization and imputation, and that treat discrete and continuous\n    columns separately.\n\n    The class implements a method `fit` that calls either `fit_columns`\n    or `fit_rows` with the data and the number of values for discrete\n    attributes. The provided method `fit_rows` calls methods\n    `get_discrete_stats` and `get_continuous_stats` that can be implemented\n    in derived classes.\n\n    Class attribute `rows_model_type` contains the type of the model returned by\n    `fit_rows`.\n    \"\"\"\n    rows_model_type = None  #: Option[FittedDistanceModel]\n\n    def fit(self, data):\n        \"\"\"\n        Prepare the data on attributes, call `fit_cols` or `fit_rows` and\n        return the resulting model.\n        \"\"\"\n        x = _orange_to_numpy(data)\n        if hasattr(data, \"domain\"):\n            attributes = data.domain.attributes\n            n_vals = np.fromiter(\n                (len(attr.values) if attr.is_discrete else 0\n                 for attr in attributes),\n                dtype=np.int32, count=len(attributes))\n        else:\n            assert isinstance(x, np.ndarray)\n            attributes = None\n            n_vals = np.zeros(x.shape[1], dtype=np.int32)\n        return [self.fit_cols, self.fit_rows][self.axis](attributes, x, n_vals)\n\n    def fit_cols(self, attributes, x, n_vals):\n        \"\"\"\n        Return DistanceModel for computation of distances between columns.\n        Derived classes must define this method.\n\n        Args:\n            attributes (list of Orange.data.Variable): list of attributes\n            x (np.ndarray): data\n            n_vals (np.ndarray): number of attribute values, 0 for continuous\n        \"\"\"\n        raise NotImplementedError\n\n    def fit_rows(self, attributes, x, n_vals):\n        \"\"\"\n        Return a DistanceModel for computation of distances between rows.\n\n        The model type is `self.row_distance_model`. It stores the data for\n        imputation of discrete and continuous values, and for normalization\n        of continuous values. Typical examples are the Euclidean and Manhattan\n        distance, for which the following data is stored:\n\n        For continuous columns:\n\n        - offsets[col] is the number subtracted from values in column `col`\n        - scales[col] is the divisor for values in columns `col`\n        - dist_missing2_cont[col]: the value used for distance between two\n            missing values in column `col`\n\n        For discrete values:\n\n        - dist_missing_disc[col, value] is the distance added for the given\n            `value` in the column `col` if the value for the other row is\n            missing\n        - dist_missing2_disc[col]: the distance between two missing values in\n            column `col`\n        \"\"\"\n        n_cols = len(n_vals)\n\n        discrete = n_vals > 0\n        n_bins = max(n_vals, default=0)\n        n_discrete = sum(discrete)\n        dist_missing_disc = np.zeros((n_discrete, n_bins), dtype=float)\n        dist_missing2_disc = np.zeros(n_discrete, dtype=float)\n\n        continuous = ~discrete\n        n_continuous = sum(continuous)\n        offsets = np.zeros(n_continuous, dtype=float)\n        scales = np.empty(n_continuous, dtype=float)\n        dist_missing2_cont = np.zeros(n_continuous, dtype=float)\n\n        curr_disc = curr_cont = 0\n        for col in range(n_cols):\n            column = x[:, col]\n            if np.isnan(column).all():\n                continuous[col] = discrete[col] = False\n            elif discrete[col]:\n                discrete_stats = self.get_discrete_stats(column, n_bins)\n                if discrete_stats is not None:\n                    dist_missing_disc[curr_disc], \\\n                    dist_missing2_disc[curr_disc] = discrete_stats\n                    curr_disc += 1\n            else:\n                continuous_stats = self.get_continuous_stats(column)\n                if continuous_stats is not None:\n                    offsets[curr_cont], scales[curr_cont],\\\n                    dist_missing2_cont[curr_cont] = continuous_stats\n                    curr_cont += 1\n                else:\n                    continuous[col] = False\n        # pylint: disable=not-callable\n        return self.rows_model_type(\n            attributes, impute, getattr(self, \"normalize\", False),\n            continuous, discrete,\n            offsets[:curr_cont], scales[:curr_cont],\n            dist_missing2_cont[:curr_cont],\n            dist_missing_disc, dist_missing2_disc,\n            self.callback)\n\n    @staticmethod\n    def get_discrete_stats(column, n_bins):\n        \"\"\"\n        Return tables used computing distance between missing discrete values.\n\n        Args:\n            column (np.ndarray): column data\n            n_bins (int): maximal number of bins in the dataset\n\n        Returns:\n            dist_missing_disc (np.ndarray): `dist_missing_disc[value]` is\n                1 - probability of `value`, which is used as the distance added\n                for the given `value` in the column `col` if the value for the\n                other row is missing\n            dist_missing2_disc (float): the distance between two missing\n                values in this columns\n        \"\"\"\n        dist = util.bincount(column, minlength=n_bins)[0]\n        dist /= max(1, sum(dist))\n        return 1 - dist, 1 - np.sum(dist ** 2)\n\n    def get_continuous_stats(self, column):\n        \"\"\"\n        Compute statistics for imputation and normalization of continuous data.\n        Derived classes must define this method.\n\n        Args:\n            column (np.ndarray): column data\n\n        Returns:\n            offset (float): the number subtracted from values in column\n            scales (float): the divisor for values in column\n            dist_missing2_cont (float): the value used for distance between two\n                missing values in column\n        \"\"\"\n        raise NotImplementedError\n\n\n# Fallbacks for distances in sparse data\n# To be removed as the corresponding functionality is implemented properly\n\nclass SklDistance:\n    \"\"\"\n    Wrapper for functions sklearn's metrics. Used only as temporary fallbacks\n    when `Euclidean`, `Manhattan`, `Cosine` or `Jaccard` are given sparse data\n    or raw numpy arrays. These classes can't handle discrete or missing data\n    and normalization. Do not use for wrapping new classes.\n    \"\"\"\n    def __init__(self, metric):\n        self.metric = metric\n\n    def __call__(self, e1, e2=None, axis=1, impute=False):\n        x1 = _orange_to_numpy(e1)\n        x2 = _orange_to_numpy(e2)\n        if axis == 0:\n            x1 = x1.T\n            if x2 is not None:\n                x2 = x2.T\n        dist = skl_metrics.pairwise.pairwise_distances(\n            x1, x2, metric=self.metric)\n        if impute and np.isnan(dist).any():\n            dist = np.nan_to_num(dist)\n        if isinstance(e1, (Table, RowInstance)):\n            dist_matrix = DistMatrix(dist, e1, e2, axis)\n        else:\n            dist_matrix = DistMatrix(dist)\n        return dist_matrix\n",
            "new_file_content": "# This module defines abstract base classes; derived classes are abstract, too\n# pylint: disable=abstract-method\n\nimport numpy as np\nimport sklearn.metrics as skl_metrics\n\nfrom Orange.data import Table, Domain, Instance, RowInstance\nfrom Orange.misc import DistMatrix\nfrom Orange.preprocess import SklImpute\nfrom Orange.statistics import util\n\n\n# TODO: When we upgrade to numpy 1.13, change use argument copy=False in\n# nan_to_num instead of assignment\n\n# TODO this *private* function is called from several widgets to prepare\n# data for calling the below classes. After we (mostly) stopped relying\n# on sklearn.metrics, this is (mostly) unnecessary\n# Afterwards, also remove the following line:\n# pylint: disable=redefined-outer-name\ndef _preprocess(table, impute=True):\n    \"\"\"Remove categorical attributes and impute missing values.\"\"\"\n    if not len(table):  # this can be an array, pylint: disable=len-as-condition\n        return table\n    new_domain = Domain(\n        [a for a in table.domain.attributes if a.is_continuous],\n        table.domain.class_vars,\n        table.domain.metas)\n    new_data = table.transform(new_domain)\n    if impute:\n        new_data = SklImpute()(new_data)\n    return new_data\n\n\n# TODO I have put this function here as a substitute the above `_preprocess`.\n# None of them really belongs here; (re?)move them, eventually.\ndef remove_discrete_features(data, to_metas=False):\n    \"\"\"Remove discrete columns from the data.\"\"\"\n    new_domain = Domain(\n        [a for a in data.domain.attributes if a.is_continuous],\n        data.domain.class_vars,\n        data.domain.metas\n        + (() if not to_metas\n           else tuple(a for a in data.domain.attributes if not a.is_continuous))\n    )\n    return data.transform(new_domain)\n\n\ndef remove_nonbinary_features(data, to_metas=False):\n    \"\"\"Remove non-binary columns from the data.\"\"\"\n    new_domain = Domain(\n        [a for a in data.domain.attributes\n         if a.is_discrete and len(a.values) == 2],\n        data.domain.class_vars,\n        data.domain.metas +\n        (() if not to_metas\n         else tuple(a for a in data.domain.attributes\n               if not (a.is_discrete and len(a.values) == 2))\n         if to_metas else ()))\n    return data.transform(new_domain)\n\ndef impute(data):\n    \"\"\"Impute missing values.\"\"\"\n    return SklImpute()(data)\n\n\ndef _orange_to_numpy(x):\n    \"\"\"\n    Return :class:`numpy.ndarray` (dense or sparse) with attribute data\n    from the given instance of :class:`Orange.data.Table`,\n    :class:`Orange.data.RowInstance` or :class:`Orange.data.Instance`.\n    \"\"\"\n    if isinstance(x, Table):\n        return x.X\n    elif isinstance(x, Instance):\n        return np.atleast_2d(x.x)\n    elif isinstance(x, np.ndarray):\n        return np.atleast_2d(x)\n    else:\n        return x  # e.g. None\n\n\nclass Distance:\n    \"\"\"\n    Base class for construction of distances models (:obj:`DistanceModel`).\n\n    Distances can be computed between all pairs of rows in one table, or\n    between pairs where one row is from one table and one from another.\n\n    If `axis` is set to `0`, the class computes distances between all pairs\n    of columns in a table. Distances between columns from separate tables are\n    probably meaningless, thus unsupported.\n\n    The class can be used as follows:\n\n    - Constructor is called only with keyword argument `axis` that\n      specifies the axis over which the distances are computed, and with other\n      subclass-specific keyword arguments.\n    - Next, we call the method `fit(data)` to produce an instance of\n      :obj:`DistanceModel`; the instance stores any parameters needed for\n      computation of distances, such as statistics for normalization and\n      handling of missing data.\n    - We can then call the :obj:`DistanceModel` with data to compute the\n      distance between its rows or columns, or with two data tables to\n      compute distances between all pairs of rows.\n\n    The second, shorter way to use this class is to call the constructor with\n    one or two data tables and any additional keyword arguments. Constructor\n    will execute the above steps and return :obj:`~Orange.misc.DistMatrix`.\n    Such usage is here for backward compatibility, practicality and efficiency.\n\n    Args:\n        e1 (:obj:`~Orange.data.Table` or :obj:`~Orange.data.Instance` or \\\n                :obj:`np.ndarray` or `None`):\n            data on which to train the model and compute the distances\n        e2 (:obj:`~Orange.data.Table` or :obj:`~Orange.data.Instance` or \\\n                :obj:`np.ndarray` or `None`):\n            if present, the class computes distances with pairs coming from\n            the two tables\n        axis (int):\n            axis over which the distances are computed, 1 (default) for\n            rows, 0 for columns\n        impute (bool):\n            if `True` (default is `False`), nans in the computed distances\n            are replaced with zeros, and infs with very large numbers.\n        callback (callable or None):\n            callback function\n\n    Attributes:\n        axis (int):\n            axis over which the distances are computed, 1 (default) for\n            rows, 0 for columns\n        impute (bool):\n            if `True` (default is `False`), nans in the computed distances\n            are replaced with zeros, and infs with very large numbers.\n        normalize (bool):\n            if `True`, columns are normalized before computation. This attribute\n            applies only if the distance supports normalization.\n\n    The capabilities of the metrics are described with class attributes.\n\n    If class attribute `supports_discrete` is `True`, the distance\n    also uses discrete attributes to compute row distances. The use of discrete\n    attributes depends upon the type of distance; e.g. Jaccard distance observes\n    whether the value is zero or non-zero, while Euclidean and Manhattan\n    distance observes whether a pair of values is same or different.\n\n    Class attribute `supports_missing` indicates that the distance can cope\n    with missing data. In such cases, letting the distance handle it should\n    be preferred over pre-imputation of missing values.\n\n    Class attribute `supports_normalization` indicates that the constructor\n    accepts an argument `normalize`. If set to `True`, the metric will attempt\n    to normalize the values in a sense that each attribute will have equal\n    influence. For instance, the Euclidean distance subtract the mean and\n    divides the result by the deviation, while Manhattan distance uses the\n    median and MAD.\n\n    If class attribute `supports_sparse` is `True`, the class will handle\n    sparse data. Currently, all classes that do handle it rely on fallbacks to\n    SKL metrics. These, however, do not support discrete data and missing\n    values, and will fail silently.\n    \"\"\"\n    supports_sparse = False\n    supports_discrete = False\n    supports_normalization = False\n    supports_missing = True\n\n    # Predefined here to silence pylint, which doesn't look into __new__\n    normalize = False\n    axis = 1\n    impute = False\n\n    def __new__(cls, e1=None, e2=None, axis=1, impute=False,\n                callback=None, **kwargs):\n        self = super().__new__(cls)\n        self.axis = axis\n        self.impute = impute\n        self.callback = callback\n        # Ugly, but needed to allow allow setting subclass-specific parameters\n        # (such as normalize) when `e1` is not `None` and the `__new__` in the\n        # subclass is skipped\n        self.__dict__.update(**kwargs)\n        if e1 is None:\n            return self\n\n        # Fallbacks for sparse data and numpy tables. Remove when subclasses\n        # no longer use fallbacks for sparse data, and handling numpy tables\n        # becomes obsolete (or handled elsewhere)\n        if (not hasattr(e1, \"domain\")\n                or hasattr(e1, \"is_sparse\") and e1.is_sparse()):\n            fallback = getattr(self, \"fallback\", None)\n            if fallback is not None:\n                # pylint: disable=not-callable\n                return fallback(e1, e2, axis, impute)\n\n        # Magic constructor\n        model = self.fit(e1)\n        return model(e1, e2)\n\n    def fit(self, data):\n        \"\"\"\n        Abstract method returning :obj:`DistanceModel` fit to the data\n\n        Args:\n            e1 (Orange.data.Table, Orange.data.Instance, np.ndarray):\n                data for fitting the distance model\n\n        Returns:\n            model (DistanceModel)\n        \"\"\"\n        raise NotImplementedError\n\n    @staticmethod\n    def check_no_discrete(n_vals):\n        \"\"\"\n        Raise an exception if there are any discrete attributes.\n\n        Args:\n            n_vals (list of int): number of attributes values, 0 for continuous\n        \"\"\"\n        if any(n_vals):\n            raise ValueError(\"columns with discrete values are incommensurable\")\n\n\nclass DistanceModel:\n    \"\"\"\n    Base class for classes that compute distances between data rows or columns.\n    Instances of these classes are not constructed directly but returned by\n    the corresponding instances of :obj:`Distance`.\n\n    Attributes:\n        axis (int, readonly):\n            axis over which the distances are computed, 1 (default) for\n            rows, 0 for columns\n        impute (bool):\n            if `True` (default is `False`), nans in the computed distances\n            are replaced with zeros, and infs with very large numbers\n        callback (callable or None):\n            callback function\n\n    \"\"\"\n    def __init__(self, axis, impute=False, callback=None):\n        self._axis = axis\n        self.impute = impute\n        self.callback = callback\n\n    @property\n    def axis(self):\n        return self._axis\n\n    def __call__(self, e1, e2=None):\n        \"\"\"\n        If e2 is omitted, calculate distances between all rows (axis=1) or\n        columns (axis=2) of e1. If e2 is present, calculate distances between\n        all pairs if rows from e1 and e2.\n\n        This method converts the data into numpy arrays, calls the method\n        `compute_data` and packs the result into `DistMatrix`. Subclasses are\n        expected to define the `compute_data` and not the `__call__` method.\n\n        Args:\n            e1 (Orange.data.Table or Orange.data.Instance or numpy.ndarray):\n                input data\n            e2 (Orange.data.Table or Orange.data.Instance or numpy.ndarray):\n                secondary data\n\n        Returns:\n            A distance matrix (Orange.misc.distmatrix.DistMatrix)\n        \"\"\"\n        if self.axis == 0 and e2 is not None:\n            # Backward compatibility fix\n            if e2 is e1:\n                e2 = None\n            else:\n                raise ValueError(\"Two tables cannot be compared by columns\")\n\n        x1 = _orange_to_numpy(e1)\n        x2 = _orange_to_numpy(e2)\n        with np.errstate(invalid=\"ignore\"):  # nans are handled below\n            dist = self.compute_distances(x1, x2)\n            if self.impute and np.isnan(dist).any():\n                dist = np.nan_to_num(dist)\n            if isinstance(e1, (Table, RowInstance)):\n                dist = DistMatrix(dist, e1, e2, self.axis)\n            else:\n                dist = DistMatrix(dist)\n            return dist\n\n    def compute_distances(self, x1, x2):\n        \"\"\"\n        Abstract method for computation of distances between rows or columns of\n        `x1`, or between rows of `x1` and `x2`. Do not call directly.\"\"\"\n        raise NotImplementedError\n\n\nclass FittedDistanceModel(DistanceModel):\n    \"\"\"\n    Base class for models that store attribute-related data for normalization\n    and imputation, and that treat discrete and continuous columns separately.\n\n    Attributes:\n        attributes (list of `Variable`): attributes on which the model was fit\n        discrete (np.ndarray): bool array indicating discrete attributes\n        continuous (np.ndarray): bool array indicating continuous attributes\n        normalize (bool):\n            if `True` (default is `False`) continuous columns are normalized\n        callback (callable or None): callback function\n    \"\"\"\n    def __init__(self, attributes, axis=1, impute=False, callback=None):\n        super().__init__(axis, impute, callback)\n        self.attributes = attributes\n        self.discrete = None\n        self.continuous = None\n        self.normalize = False\n\n    def __call__(self, e1, e2=None):\n        if self.attributes is not None and (\n                e1.domain.attributes != self.attributes\n                or e2 is not None and e2.domain.attributes != self.attributes):\n            raise ValueError(\"mismatching domains\")\n        return super().__call__(e1, e2)\n\n    def continuous_columns(self, x1, x2, offset, scale):\n        \"\"\"\n        Extract and scale continuous columns from data tables.\n        If the second table is None, it defaults to the first table.\n\n        Values are scaled if `self.normalize` is `True`.\n\n        Args:\n            x1 (np.ndarray): first table\n            x2 (np.ndarray or None): second table\n            offset (float): a constant (e.g. mean, median) subtracted from data\n            scale: (float): divider (e.g. deviation)\n\n        Returns:\n            data1 (np.ndarray): scaled continuous columns from `x1`\n            data2 (np.ndarray): scaled continuous columns from `x2` or `x1`\n        \"\"\"\n        if self.continuous.all() and not self.normalize:\n            data1, data2 = x1, x2\n        else:\n            data1 = x1[:, self.continuous]\n            if x2 is not None:\n                data2 = x2[:, self.continuous]\n            if self.normalize:\n                data1 = x1[:, self.continuous]\n                data1 -= offset\n                data1 /= scale\n                if x2 is not None:\n                    data2 = x2[:, self.continuous]\n                    data2 -= offset\n                    data2 /= scale\n        if x2 is None:\n            data2 = data1\n        return data1, data2\n\n    def discrete_columns(self, x1, x2):\n        \"\"\"\n        Return discrete columns from the given tables.\n        If the second table is None, it defaults to the first table.\n        \"\"\"\n        if self.discrete.all():\n            data1, data2 = x1, x1 if x2 is None else x2\n        else:\n            data1 = x1[:, self.discrete]\n            data2 = data1 if x2 is None else x2[:, self.discrete]\n        return data1, data2\n\n\nclass FittedDistance(Distance):\n    \"\"\"\n    Base class for fitting models that store attribute-related data for\n    normalization and imputation, and that treat discrete and continuous\n    columns separately.\n\n    The class implements a method `fit` that calls either `fit_columns`\n    or `fit_rows` with the data and the number of values for discrete\n    attributes. The provided method `fit_rows` calls methods\n    `get_discrete_stats` and `get_continuous_stats` that can be implemented\n    in derived classes.\n\n    Class attribute `rows_model_type` contains the type of the model returned by\n    `fit_rows`.\n    \"\"\"\n    rows_model_type = None  #: Option[FittedDistanceModel]\n\n    def fit(self, data):\n        \"\"\"\n        Prepare the data on attributes, call `fit_cols` or `fit_rows` and\n        return the resulting model.\n        \"\"\"\n        x = _orange_to_numpy(data)\n        if hasattr(data, \"domain\"):\n            attributes = data.domain.attributes\n            n_vals = np.fromiter(\n                (len(attr.values) if attr.is_discrete else 0\n                 for attr in attributes),\n                dtype=np.int32, count=len(attributes))\n        else:\n            assert isinstance(x, np.ndarray)\n            attributes = None\n            n_vals = np.zeros(x.shape[1], dtype=np.int32)\n        return [self.fit_cols, self.fit_rows][self.axis](attributes, x, n_vals)\n\n    def fit_cols(self, attributes, x, n_vals):\n        \"\"\"\n        Return DistanceModel for computation of distances between columns.\n        Derived classes must define this method.\n\n        Args:\n            attributes (list of Orange.data.Variable): list of attributes\n            x (np.ndarray): data\n            n_vals (np.ndarray): number of attribute values, 0 for continuous\n        \"\"\"\n        raise NotImplementedError\n\n    def fit_rows(self, attributes, x, n_vals):\n        \"\"\"\n        Return a DistanceModel for computation of distances between rows.\n\n        The model type is `self.row_distance_model`. It stores the data for\n        imputation of discrete and continuous values, and for normalization\n        of continuous values. Typical examples are the Euclidean and Manhattan\n        distance, for which the following data is stored:\n\n        For continuous columns:\n\n        - offsets[col] is the number subtracted from values in column `col`\n        - scales[col] is the divisor for values in columns `col`\n        - dist_missing2_cont[col]: the value used for distance between two\n            missing values in column `col`\n\n        For discrete values:\n\n        - dist_missing_disc[col, value] is the distance added for the given\n            `value` in the column `col` if the value for the other row is\n            missing\n        - dist_missing2_disc[col]: the distance between two missing values in\n            column `col`\n        \"\"\"\n        n_cols = len(n_vals)\n\n        discrete = n_vals > 0\n        n_bins = max(n_vals, default=0)\n        n_discrete = sum(discrete)\n        dist_missing_disc = np.zeros((n_discrete, n_bins), dtype=float)\n        dist_missing2_disc = np.zeros(n_discrete, dtype=float)\n\n        continuous = ~discrete\n        n_continuous = sum(continuous)\n        offsets = np.zeros(n_continuous, dtype=float)\n        scales = np.empty(n_continuous, dtype=float)\n        dist_missing2_cont = np.zeros(n_continuous, dtype=float)\n\n        curr_disc = curr_cont = 0\n        for col in range(n_cols):\n            column = x[:, col]\n            if np.isnan(column).all():\n                continuous[col] = discrete[col] = False\n            elif discrete[col]:\n                discrete_stats = self.get_discrete_stats(column, n_bins)\n                if discrete_stats is not None:\n                    dist_missing_disc[curr_disc], \\\n                    dist_missing2_disc[curr_disc] = discrete_stats\n                    curr_disc += 1\n            else:\n                continuous_stats = self.get_continuous_stats(column)\n                if continuous_stats is not None:\n                    offsets[curr_cont], scales[curr_cont],\\\n                    dist_missing2_cont[curr_cont] = continuous_stats\n                    curr_cont += 1\n                else:\n                    continuous[col] = False\n        # pylint: disable=not-callable\n        return self.rows_model_type(\n            attributes, impute, getattr(self, \"normalize\", False),\n            continuous, discrete,\n            offsets[:curr_cont], scales[:curr_cont],\n            dist_missing2_cont[:curr_cont],\n            dist_missing_disc, dist_missing2_disc,\n            self.callback)\n\n    @staticmethod\n    def get_discrete_stats(column, n_bins):\n        \"\"\"\n        Return tables used computing distance between missing discrete values.\n\n        Args:\n            column (np.ndarray): column data\n            n_bins (int): maximal number of bins in the dataset\n\n        Returns:\n            dist_missing_disc (np.ndarray): `dist_missing_disc[value]` is\n                1 - probability of `value`, which is used as the distance added\n                for the given `value` in the column `col` if the value for the\n                other row is missing\n            dist_missing2_disc (float): the distance between two missing\n                values in this columns\n        \"\"\"\n        dist = util.bincount(column, minlength=n_bins)[0]\n        dist /= max(1, sum(dist))\n        return 1 - dist, 1 - np.sum(dist ** 2)\n\n    def get_continuous_stats(self, column):\n        \"\"\"\n        Compute statistics for imputation and normalization of continuous data.\n        Derived classes must define this method.\n\n        Args:\n            column (np.ndarray): column data\n\n        Returns:\n            offset (float): the number subtracted from values in column\n            scales (float): the divisor for values in column\n            dist_missing2_cont (float): the value used for distance between two\n                missing values in column\n        \"\"\"\n        raise NotImplementedError\n\n\n# Fallbacks for distances in sparse data\n# To be removed as the corresponding functionality is implemented properly\n\nclass SklDistance:\n    \"\"\"\n    Wrapper for functions sklearn's metrics. Used only as temporary fallbacks\n    when `Euclidean`, `Manhattan`, `Cosine` or `Jaccard` are given sparse data\n    or raw numpy arrays. These classes can't handle discrete or missing data\n    and normalization. Do not use for wrapping new classes.\n    \"\"\"\n    def __init__(self, metric):\n        self.metric = metric\n\n    def __call__(self, e1, e2=None, axis=1, impute=False):\n        x1 = _orange_to_numpy(e1)\n        x2 = _orange_to_numpy(e2)\n        if axis == 0:\n            x1 = x1.T\n            if x2 is not None:\n                x2 = x2.T\n        dist = skl_metrics.pairwise.pairwise_distances(\n            x1, x2, metric=self.metric)\n        if impute and np.isnan(dist).any():\n            dist = np.nan_to_num(dist)\n        if isinstance(e1, (Table, RowInstance)):\n            dist_matrix = DistMatrix(dist, e1, e2, axis)\n        else:\n            dist_matrix = DistMatrix(dist)\n        return dist_matrix\n",
            "header": {
                "file": {
                    "path": "Orange/distance/base.py"
                },
                "misc_line": null
            },
            "index_line": {
                "old_commit_hash": "7205e1cbc",
                "new_commit_hash": "112f9b1b4",
                "mode": "100644"
            },
            "is_binary_file": false,
            "binary_line": null,
            "minus_file": {
                "path": "a/Orange/distance/base.py"
            },
            "plus_file": {
                "path": "b/Orange/distance/base.py"
            },
            "hunks": [
                {
                    "descriptor": {
                        "old_range": {
                            "start": 34,
                            "length": 22
                        },
                        "new_range": {
                            "start": 34,
                            "length": 29
                        },
                        "section": "def _preprocess(table, impute=True):"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "# TODO I have put this function here as a substitute the above `_preprocess`.",
                                "type": "context"
                            },
                            {
                                "content": "# None of them really belongs here; (re?)move them, eventually.",
                                "type": "context"
                            },
                            {
                                "content": "def remove_discrete_features(data):",
                                "type": "deleted"
                            },
                            {
                                "content": "def remove_discrete_features(data, to_metas=False):",
                                "type": "added"
                            },
                            {
                                "content": "    \"\"\"Remove discrete columns from the data.\"\"\"",
                                "type": "context"
                            },
                            {
                                "content": "    new_domain = Domain(",
                                "type": "context"
                            },
                            {
                                "content": "        [a for a in data.domain.attributes if a.is_continuous],",
                                "type": "context"
                            },
                            {
                                "content": "        data.domain.class_vars,",
                                "type": "context"
                            },
                            {
                                "content": "        data.domain.metas)",
                                "type": "deleted"
                            },
                            {
                                "content": "        data.domain.metas",
                                "type": "added"
                            },
                            {
                                "content": "        + (() if not to_metas",
                                "type": "added"
                            },
                            {
                                "content": "           else tuple(a for a in data.domain.attributes if not a.is_continuous))",
                                "type": "added"
                            },
                            {
                                "content": "    )",
                                "type": "added"
                            },
                            {
                                "content": "    return data.transform(new_domain)",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "def remove_nonbinary_features(data):",
                                "type": "deleted"
                            },
                            {
                                "content": "def remove_nonbinary_features(data, to_metas=False):",
                                "type": "added"
                            },
                            {
                                "content": "    \"\"\"Remove non-binary columns from the data.\"\"\"",
                                "type": "context"
                            },
                            {
                                "content": "    new_domain = Domain(",
                                "type": "context"
                            },
                            {
                                "content": "        [a for a in data.domain.attributes",
                                "type": "context"
                            },
                            {
                                "content": "         if a.is_discrete and len(a.values) == 2],",
                                "type": "context"
                            },
                            {
                                "content": "        data.domain.class_vars,",
                                "type": "context"
                            },
                            {
                                "content": "        data.domain.metas)",
                                "type": "deleted"
                            },
                            {
                                "content": "        data.domain.metas +",
                                "type": "added"
                            },
                            {
                                "content": "        (() if not to_metas",
                                "type": "added"
                            },
                            {
                                "content": "         else tuple(a for a in data.domain.attributes",
                                "type": "added"
                            },
                            {
                                "content": "               if not (a.is_discrete and len(a.values) == 2))",
                                "type": "added"
                            },
                            {
                                "content": "         if to_metas else ()))",
                                "type": "added"
                            },
                            {
                                "content": "    return data.transform(new_domain)",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "def impute(data):",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [
                        {
                            "file_name": "Orange/distance/base.py",
                            "type": "function",
                            "name": "remove_discrete_features",
                            "content": "def remove_discrete_features(data):\n    \"\"\"Remove discrete columns from the data.\"\"\"\n    new_domain = Domain(\n        [a for a in data.domain.attributes if a.is_continuous],\n        data.domain.class_vars,\n        data.domain.metas)\n    return data.transform(new_domain)",
                            "ast_type_str": "FunctionDef",
                            "start_lineno": 37,
                            "end_lineno": 43,
                            "parent": null
                        },
                        {
                            "file_name": "Orange/distance/base.py",
                            "type": "function",
                            "name": "remove_nonbinary_features",
                            "content": "def remove_nonbinary_features(data):\n    \"\"\"Remove non-binary columns from the data.\"\"\"\n    new_domain = Domain(\n        [a for a in data.domain.attributes\n         if a.is_discrete and len(a.values) == 2],\n        data.domain.class_vars,\n        data.domain.metas)\n    return data.transform(new_domain)",
                            "ast_type_str": "FunctionDef",
                            "start_lineno": 46,
                            "end_lineno": 53,
                            "parent": null
                        }
                    ],
                    "added_entities": [],
                    "deleted_entities": []
                }
            ]
        },
        {
            "old_file_content": "import unittest\nfrom unittest.mock import patch\nfrom math import sqrt\n\nimport numpy as np\nfrom scipy.sparse import csr_matrix\n\nfrom Orange.data import ContinuousVariable, DiscreteVariable, Domain, Table\nfrom Orange import distance\n\n\nclass CommonTests:\n    \"\"\"Tests applicable to all distance measures\"\"\"\n\n    def test_no_data(self):\n        \"\"\"distances return zero-dimensional matrices when no data\"\"\"\n        n = len(self.data)\n        np.testing.assert_almost_equal(\n            self.Distance(Table.from_domain(self.domain)),\n            np.zeros((0, 0)))\n        np.testing.assert_almost_equal(\n            self.Distance(self.data, Table.from_domain(self.domain)),\n            np.zeros((n, 0)))\n        np.testing.assert_almost_equal(\n            self.Distance(Table.from_domain(self.domain), self.data),\n            np.zeros((0, n)))\n\n    def test_sparse(self):\n        \"\"\"Test sparse support in distances.\"\"\"\n        domain = Domain([ContinuousVariable(c) for c in \"abc\"])\n        dense_data = Table.from_list(\n            domain, [[1, 0, 2], [-1, 5, 0], [0, 1, 1], [7, 0, 0]])\n        sparse_data = Table(domain, csr_matrix(dense_data.X))\n\n        if not self.Distance.supports_sparse:\n            self.assertRaises(TypeError, self.Distance, sparse_data)\n        else:\n            # check the result is the same for sparse and dense\n            dist_dense = self.Distance(dense_data)\n            dist_sparse = self.Distance(sparse_data)\n            np.testing.assert_allclose(dist_sparse, dist_dense)\n\n\nclass CommonFittedTests(CommonTests):\n    \"\"\"Tests applicable to all distances with fitting\"\"\"\n    def test_mismatching_attributes(self):\n        \"\"\"distances can't be computed if fit from other attributes\"\"\"\n        def new_table(name):\n            return Table.from_list(Domain([ContinuousVariable(name)]), [[1]])\n\n        table1 = new_table(\"a\")\n        model = self.Distance().fit(table1)\n        self.assertRaises(ValueError, model, new_table(\"b\"))\n        self.assertRaises(ValueError, model, table1, new_table(\"c\"))\n        self.assertRaises(ValueError, model, new_table(\"d\"), table1)\n\n\nclass CommonNormalizedTests(CommonFittedTests):\n    \"\"\"Tests applicable to distances the have normalization\"\"\"\n\n    def test_zero_variance(self):\n        \"\"\"zero-variance columns have no effect on row distance\"\"\"\n        assert_almost_equal = np.testing.assert_almost_equal\n        normalized = self.Distance(axis=1, normalize=True)\n        nonnormalized = self.Distance(axis=1, normalize=False)\n\n        def is_same(d1, d2, fit1=None, fit2=None):\n            if fit1 is None:\n                fit1 = d1\n            if fit2 is None:\n                fit2 = d2\n            assert_almost_equal(normalized.fit(fit1)(d1),\n                                normalized.fit(fit2)(d2))\n            assert_almost_equal(nonnormalized.fit(fit1)(d1),\n                                nonnormalized.fit(fit2)(d2))\n\n        data = self.cont_data\n        n = len(data)\n        X = data.X\n        domain = Domain(data.domain.attributes + (ContinuousVariable(\"d\"),))\n        data_const = Table(domain, np.hstack((X, np.ones((n, 1)))))\n        data_nan = Table(domain, np.hstack((X, np.full((n, 1), np.nan))))\n        data_nan_1 = Table(domain, np.hstack((X, np.full((n, 1), np.nan))))\n        data_nan_1.X[0, -1] = 1\n        is_same(data, data_const)\n        is_same(data, data_nan)\n        is_same(data, data_nan_1)\n\n        # Test whether it's possible to fit with singular data and use the\n        # parameters on data where the same column is defined\n        is_same(data_nan, data_const, data_const)\n        is_same(data_const, data_const, data_nan)\n\n        self.assertRaises(ValueError, self.Distance,\n                          data_const, axis=0, normalize=True)\n        self.assertRaises(ValueError, self.Distance,\n                          data_nan, axis=0, normalize=True)\n        self.assertRaises(ValueError, self.Distance,\n                          data_nan_1, axis=0, normalize=True)\n\n    def test_mixed_cols(self):\n        \"\"\"distance over columns raises exception for discrete columns\"\"\"\n        self.assertRaises(ValueError, self.Distance, self.mixed_data, axis=0)\n        self.assertRaises(ValueError,\n                          self.Distance(axis=0).fit, self.mixed_data)\n\n\nclass FittedDistanceTest(unittest.TestCase):\n    @classmethod\n    def setUpClass(cls):\n        cls.attributes = (\n            ContinuousVariable(\"c1\"),\n            ContinuousVariable(\"c2\"),\n            ContinuousVariable(\"c3\"),\n            DiscreteVariable(\"d1\", values=(\"a\", \"b\")),\n            DiscreteVariable(\"d2\", values=(\"a\", \"b\", \"c\", \"d\")),\n            DiscreteVariable(\"d3\", values=(\"a\", \"b\", \"c\")))\n        cls.domain = Domain(cls.attributes)\n        cls.cont_domain = Domain(cls.attributes[:3])\n        cls.disc_domain = Domain(cls.attributes[3:])\n\n    def setUp(self):\n        self.cont_data = Table.from_list(\n            self.cont_domain,\n            [[1, 3, 2],\n             [-1, 5, 0],\n             [1, 1, 1],\n             [7, 2, 3]])\n\n        self.cont_data2 = Table.from_list(\n            self.cont_domain,\n            [[2, 1, 3],\n             [1, 2, 2]]\n        )\n\n        self.disc_data = Table.from_list(\n            self.disc_domain,\n            [[0, 0, 0],\n             [0, 1, 1],\n             [1, 3, 1]]\n        )\n\n        self.disc_data4 = Table.from_list(\n            self.disc_domain,\n            [[0, 0, 0],\n             [0, 1, 1],\n             [0, 1, 1],\n             [1, 3, 1]]\n        )\n\n        self.mixed_data = self.data = Table.from_numpy(\n            self.domain, np.hstack((self.cont_data.X[:3], self.disc_data.X)))\n\n\n\n# Correct results in these tests were computed manually or with Excel;\n# these are not regression tests\nclass EuclideanDistanceTest(FittedDistanceTest, CommonNormalizedTests):\n    Distance = distance.Euclidean\n\n    def test_euclidean_disc(self):\n        assert_almost_equal = np.testing.assert_almost_equal\n        data = self.disc_data\n\n        model = distance.Euclidean().fit(data)\n        assert_almost_equal(model.dist_missing_disc,\n                            [[1/3, 2/3, 1, 1],\n                             [2/3, 2/3, 1, 2/3],\n                             [2/3, 1/3, 1, 1]])\n        assert_almost_equal(model.dist_missing2_disc,\n                            [1 - 5/9, 1 - 3/9, 1 - 5/9])\n\n        dist = model(data)\n        assert_almost_equal(dist,\n                            np.sqrt(np.array([[0, 2, 3],\n                                              [2, 0, 2],\n                                              [3, 2, 0]])))\n\n        data.X[1, 0] = np.nan\n        model = distance.Euclidean().fit(data)\n        assert_almost_equal(model.dist_missing_disc,\n                            [[1/2, 1/2, 1, 1],\n                             [2/3, 2/3, 1, 2/3],\n                             [2/3, 1/3, 1, 1]\n                            ])\n        assert_almost_equal(model.dist_missing2_disc,\n                            [1 - 2/4, 1 - 3/9, 1 - 5/9])\n\n        dist = model(data)\n        assert_almost_equal(dist,\n                            np.sqrt(np.array([[0, 2.5, 3],\n                                              [2.5, 0, 1.5],\n                                              [3, 1.5, 0]])))\n\n        data.X[0, 0] = np.nan\n        model = distance.Euclidean().fit(data)\n        assert_almost_equal(model.dist_missing_disc,\n                            [[1, 0, 1, 1],\n                             [2/3, 2/3, 1, 2/3],\n                             [2/3, 1/3, 1, 1]])\n        assert_almost_equal(model.dist_missing2_disc,\n                            [1 - 1, 1 - 3/9, 1 - 5/9])\n\n        dist = model(data)\n        assert_almost_equal(dist,\n                            np.sqrt(np.array([[0, 2, 2],\n                                              [2, 0, 1],\n                                              [2, 1, 0]])))\n\n        data = self.disc_data4\n        data.X[:2, 0] = np.nan\n        model = distance.Euclidean().fit(data)\n\n        assert_almost_equal(model.dist_missing_disc,\n                            [[1/2, 1/2, 1, 1],\n                             [3/4, 2/4, 1, 3/4],\n                             [3/4, 1/4, 1, 1]])\n        assert_almost_equal(model.dist_missing2_disc,\n                            [1 - 2/4, 1 - 6/16, 1 - 10/16])\n\n        dist = model(data)\n        assert_almost_equal(dist,\n                            np.sqrt(np.array([[0, 2.5, 2.5, 2.5],\n                                              [2.5, 0, 0.5, 1.5],\n                                              [2.5, 0.5, 0, 2],\n                                              [2.5, 1.5, 2, 0]])))\n\n    def test_euclidean_cont(self):\n        assert_almost_equal = np.testing.assert_almost_equal\n        data = self.cont_data\n\n        dist = distance.Euclidean(data, axis=1, normalize=False)\n        assert_almost_equal(\n            dist,\n            np.sqrt(np.array([[0, 12, 5, 38],\n                              [12, 0, 21, 82],\n                              [5, 21, 0, 41],\n                              [38, 82, 41, 0]])))\n\n        data.X[1, 0] = np.nan\n        dist = distance.Euclidean(data, axis=1, normalize=False)\n        assert_almost_equal(\n            dist,\n            [[0, 4.472135955, 2.236067977, 6.164414003],\n             [4.472135955, 0, 5.385164807, 6.480740698],\n             [2.236067977, 5.385164807, 0, 6.403124237],\n             [6.164414003, 6.480740698, 6.403124237, 0]])\n\n        data.X[0, 0] = np.nan\n        dist = distance.Euclidean(data, axis=1, normalize=False)\n        assert_almost_equal(\n            dist,\n            [[0, 5.099019514, 4.795831523, 4.472135955],\n             [5.099019514, 0, 5.916079783, 6],\n             [4.795831523, 5.916079783, 0, 6.403124237],\n             [4.472135955, 6, 6.403124237, 0]])\n\n    def test_euclidean_cont_normalized(self):\n        assert_almost_equal = np.testing.assert_almost_equal\n        data = self.cont_data\n\n        model = distance.Euclidean(axis=1, normalize=True).fit(data)\n        assert_almost_equal(model.means, [2, 2.75, 1.5])\n        assert_almost_equal(model.vars, [9, 2.1875, 1.25])\n        assert_almost_equal(model.dist_missing2_cont, [1, 1, 1])\n\n        dist = model(data)\n        assert_almost_equal(\n            dist,\n            [[0, 1.654239383, 1.146423008, 1.621286967],\n             [1.654239383, 0, 2.068662631, 3.035242727],\n             [1.146423008, 2.068662631, 0, 1.956673562],\n             [1.621286967, 3.035242727, 1.956673562, 0]])\n\n        dist = distance.Euclidean(data, axis=1, normalize=True)\n        assert_almost_equal(\n            dist,\n            [[0, 1.654239383, 1.146423008, 1.621286967],\n             [1.654239383, 0, 2.068662631, 3.035242727],\n             [1.146423008, 2.068662631, 0, 1.956673562],\n             [1.621286967, 3.035242727, 1.956673562, 0]])\n\n        data.X[1, 0] = np.nan\n        model = distance.Euclidean(axis=1, normalize=True).fit(data)\n        assert_almost_equal(model.means, [3, 2.75, 1.5])\n        assert_almost_equal(model.vars, [8, 2.1875, 1.25])\n        dist = model(data)\n        assert_almost_equal(\n            dist,\n            [[0, 1.806733438, 1.146423008, 1.696635326],\n             [1.806733438, 0, 2.192519751, 2.675283697],\n             [1.146423008, 2.192519751, 0, 2.019547333],\n             [1.696635326, 2.675283697, 2.019547333, 0]])\n\n        data.X[0, 0] = np.nan\n        model = distance.Euclidean(axis=1, normalize=True).fit(data)\n        assert_almost_equal(model.means, [4, 2.75, 1.5])\n        assert_almost_equal(model.vars, [9, 2.1875, 1.25])\n        dist = model(data)\n        assert_almost_equal(\n            dist,\n            [[0, 1.874642823, 1.521277659, 1.276154939],\n             [1.874642823, 0, 2.248809209, 2.580143961],\n             [1.521277659, 2.248809209, 0, 1.956673562],\n             [1.276154939, 2.580143961, 1.956673562, 0]])\n\n    def test_euclidean_cols(self):\n        assert_almost_equal = np.testing.assert_almost_equal\n        data = self.cont_data\n\n        dist = distance.Euclidean(data, axis=0, normalize=False)\n        assert_almost_equal(\n            dist,\n            [[0, 8.062257748, 4.242640687],\n             [8.062257748, 0, 5.196152423],\n             [4.242640687, 5.196152423, 0]])\n\n        data.X[1, 1] = np.nan\n        dist = distance.Euclidean(data, axis=0, normalize=False)\n        assert_almost_equal(\n            dist,\n            [[0, 6.218252702, 4.242640687],\n             [6.218252702, 0, 2.581988897],\n             [4.242640687, 2.581988897, 0]])\n\n        data.X[1, 0] = np.nan\n        dist = distance.Euclidean(data, axis=0, normalize=False)\n        assert_almost_equal(\n            dist,\n            [[0, 6.218252702, 5.830951895],\n             [6.218252702, 0, 2.581988897],\n             [5.830951895, 2.581988897, 0]])\n\n    def test_euclidean_cols_normalized(self):\n        assert_almost_equal = np.testing.assert_almost_equal\n        data = self.cont_data\n\n        dist = distance.Euclidean(data, axis=0, normalize=True)\n        assert_almost_equal(\n            dist,\n            [[0, 2.455273959, 0.649839392],\n             [2.455273959, 0, 2.473176308],\n             [0.649839392, 2.473176308, 0]])\n\n        data.X[1, 1] = np.nan\n        dist = distance.Euclidean(data, axis=0, normalize=True)\n        assert_almost_equal(\n            dist,\n            [[0, 2, 0.649839392],\n             [2, 0, 1.704275472],\n             [0.649839392, 1.704275472, 0]])\n\n        data.X[1, 0] = np.nan\n        dist = distance.Euclidean(data, axis=0, normalize=True)\n        assert_almost_equal(\n            dist,\n            [[0, 2, 1.450046001],\n             [2, 0, 1.704275472],\n             [1.450046001, 1.704275472, 0]])\n\n    def test_euclidean_mixed(self):\n        assert_almost_equal = np.testing.assert_almost_equal\n        data = self.mixed_data\n\n        model = distance.Euclidean(axis=1, normalize=True).fit(data)\n\n        assert_almost_equal(model.means, [1/3, 3, 1])\n        assert_almost_equal(model.vars, [8/9, 8/3, 2/3])\n        assert_almost_equal(model.dist_missing_disc,\n                            [[1/3, 2/3, 1, 1],\n                             [2/3, 2/3, 1, 2/3],\n                             [2/3, 1/3, 1, 1]])\n        assert_almost_equal(model.dist_missing2_cont, [1, 1, 1])\n        assert_almost_equal(model.dist_missing2_disc,\n                            [1 - 5/9, 1 - 3/9, 1 - 5/9])\n        dist = model(data)\n        assert_almost_equal(\n            dist,\n            [[0, 2.828427125, 2.121320344],\n             [2.828427125, 0, 2.828427125],\n             [2.121320344, 2.828427125, 0]])\n\n    def test_two_tables(self):\n        assert_almost_equal = np.testing.assert_almost_equal\n\n        dist = distance.Euclidean(self.cont_data, self.cont_data2,\n                                  normalize=True)\n        assert_almost_equal(\n            dist,\n            [[1.17040218, 0.47809144],\n             [2.78516478, 1.96961039],\n             [1.28668394, 0.79282497],\n             [1.27179413, 1.54919334]])\n\n        model = distance.Euclidean(normalize=True).fit(self.cont_data)\n        dist = model(self.cont_data, self.cont_data2)\n        assert_almost_equal(\n            dist,\n            [[1.17040218, 0.47809144],\n             [2.78516478, 1.96961039],\n             [1.28668394, 0.79282497],\n             [1.27179413, 1.54919334]])\n\n        dist = model(self.cont_data2)\n        assert_almost_equal(dist, [[0, 0.827119692], [0.827119692, 0]])\n\n\nclass ManhattanDistanceTest(FittedDistanceTest, CommonNormalizedTests):\n    Distance = distance.Euclidean\n\n    # The data used for testing Euclidean distances unfortunately yields\n    # mads = 1, so we change it a bit\n    def setUp(self):\n        super().setUp()\n        self.cont_data = Table.from_list(\n            self.cont_domain,\n            [[1, 3, 2],\n             [-1, 6, 0],\n             [2, 7, 1],\n             [7, 1, 3]])\n\n    def test_manhattan_no_data(self):\n        np.testing.assert_almost_equal(\n            distance.Manhattan(Table.from_domain(self.domain)),\n            np.zeros((0, 0)))\n        np.testing.assert_almost_equal(\n            distance.Manhattan(self.mixed_data, Table.from_domain(self.domain)),\n            np.zeros((3, 0)))\n        np.testing.assert_almost_equal(\n            distance.Manhattan(Table.from_domain(self.domain), self.mixed_data),\n            np.zeros((0, 3)))\n        self.assertRaises(\n            ValueError,\n            distance.Manhattan, Table.from_domain(self.cont_domain),\n            axis=0, normalize=True)\n\n    def test_manhattan_disc(self):\n        assert_almost_equal = np.testing.assert_almost_equal\n        data = self.disc_data\n\n        model = distance.Manhattan().fit(data)\n        assert_almost_equal(model.dist_missing_disc,\n                            [[1/3, 2/3, 1, 1],\n                             [2/3, 2/3, 1, 2/3],\n                             [2/3, 1/3, 1, 1]])\n        assert_almost_equal(model.dist_missing2_disc,\n                            [1 - 5/9, 1 - 3/9, 1 - 5/9])\n        dist = model(data)\n        assert_almost_equal(dist,\n                            [[0, 2, 3],\n                             [2, 0, 2],\n                             [3, 2, 0]])\n\n        data.X[1, 0] = np.nan\n        model = distance.Manhattan().fit(data)\n        assert_almost_equal(model.dist_missing_disc,\n                            [[1/2, 1/2, 1, 1],\n                             [2/3, 2/3, 1, 2/3],\n                             [2/3, 1/3, 1, 1]])\n        assert_almost_equal(model.dist_missing2_disc,\n                            [1 - 2/4, 1 - 3/9, 1 - 5/9])\n\n        dist = model(data)\n        assert_almost_equal(dist,\n                            [[0, 2.5, 3],\n                             [2.5, 0, 1.5],\n                             [3, 1.5, 0]])\n\n        data.X[0, 0] = np.nan\n        model = distance.Manhattan().fit(data)\n        assert_almost_equal(model.dist_missing_disc,\n                            [[1, 0, 1, 1],\n                             [2/3, 2/3, 1, 2/3],\n                             [2/3, 1/3, 1, 1]])\n        assert_almost_equal(model.dist_missing2_disc,\n                            [1 - 1, 1 - 3/9, 1 - 5/9])\n\n        dist = model(data)\n        assert_almost_equal(dist,\n                            [[0, 2, 2],\n                             [2, 0, 1],\n                             [2, 1, 0]])\n\n        data = self.disc_data4\n        data.X[:2, 0] = np.nan\n        model = distance.Manhattan().fit(data)\n        assert_almost_equal(model.dist_missing_disc,\n                            [[1/2, 1/2, 1, 1],\n                             [3/4, 2/4, 1, 3/4],\n                             [3/4, 1/4, 1, 1]])\n        assert_almost_equal(model.dist_missing2_disc,\n                            [1 - 2/4, 1 - 6/16, 1 - 10/16])\n\n        dist = model(data)\n        assert_almost_equal(dist,\n                            [[0, 2.5, 2.5, 2.5],\n                             [2.5, 0, 0.5, 1.5],\n                             [2.5, 0.5, 0, 2],\n                             [2.5, 1.5, 2, 0]])\n\n    def test_manhattan_cont(self):\n        assert_almost_equal = np.testing.assert_almost_equal\n        data = self.cont_data\n\n        dist = distance.Manhattan(data, axis=1, normalize=False)\n        assert_almost_equal(\n            dist,\n            [[0, 7, 6, 9],\n             [7, 0, 5, 16],\n             [6, 5, 0, 13],\n             [9, 16, 13, 0]])\n\n        data.X[1, 0] = np.nan\n        dist = distance.Manhattan(data, axis=1, normalize=False)\n        assert_almost_equal(\n            dist,\n            [[0, 7, 6, 9],\n             [7, 0, 3, 14],\n             [6, 3, 0, 13],\n             [9, 14, 13, 0]])\n\n        data.X[0, 0] = np.nan\n        dist = distance.Manhattan(data, axis=1, normalize=False)\n        assert_almost_equal(\n            dist,\n            [[0, 10, 10, 8],\n             [10, 0, 7, 13],\n             [10, 7, 0, 13],\n             [8, 13, 13, 0]])\n\n    def test_manhattan_cont_normalized(self):\n        assert_almost_equal = np.testing.assert_almost_equal\n        data = self.cont_data\n\n        model = distance.Manhattan(axis=1, normalize=True).fit(data)\n        assert_almost_equal(model.medians, [1.5, 4.5, 1.5])\n        assert_almost_equal(model.mads, [1.5, 2, 1])\n        assert_almost_equal(model.dist_missing2_cont, np.ones(3))\n\n        dist = model(data)\n        assert_almost_equal(\n            dist,\n            [[0, 2.416666667, 1.833333333, 3],\n             [2.416666667, 0, 1.75, 5.416666667],\n             [1.833333333, 1.75, 0, 4.166666667],\n             [3, 5.416666667, 4.166666667, 0]])\n\n        dist = distance.Manhattan(data, axis=1, normalize=True)\n        assert_almost_equal(\n            dist,\n            [[0, 2.416666667, 1.833333333, 3],\n             [2.416666667, 0, 1.75, 5.416666667],\n             [1.833333333, 1.75, 0, 4.166666667],\n             [3, 5.416666667, 4.166666667, 0]])\n\n        data.X[1, 0] = np.nan\n        model = distance.Manhattan(axis=1, normalize=True).fit(data)\n        assert_almost_equal(model.medians, [2, 4.5, 1.5])\n        assert_almost_equal(model.mads, [1, 2, 1])\n\n        dist = model(data)\n        assert_almost_equal(\n            dist,\n            [[0, 2.75, 2, 4],\n             [2.75, 0, 1.25, 5.75],\n             [2, 1.25, 0, 5],\n             [4, 5.75, 5, 0]])\n\n        data.X[0, 0] = np.nan\n        model = distance.Manhattan(axis=1, normalize=True).fit(data)\n        assert_almost_equal(model.medians, [4.5, 4.5, 1.5])\n        assert_almost_equal(model.mads, [2.5, 2, 1])\n\n        dist = model(data)\n        assert_almost_equal(\n            dist,\n            [[0, 2.75, 2.5, 2],\n             [2.75, 0, 1.75, 3.75],\n             [2.5, 1.75, 0, 3.5],\n             [2, 3.75, 3.5, 0]])\n\n    def test_manhattan_cols(self):\n        assert_almost_equal = np.testing.assert_almost_equal\n        data = self.cont_data\n\n        dist = distance.Manhattan(data, axis=0, normalize=False)\n        assert_almost_equal(\n            dist,\n            [[0, 20, 7],\n             [20, 0, 15],\n             [7, 15, 0]])\n\n        data.X[1, 1] = np.nan\n        dist = distance.Manhattan(data, axis=0, normalize=False)\n        assert_almost_equal(\n            dist,\n            [[0, 19, 7],\n             [19, 0, 14],\n             [7, 14, 0]])\n\n        data.X[1, 0] = np.nan\n        dist = distance.Manhattan(data, axis=0, normalize=False)\n        assert_almost_equal(\n            dist,\n            [[0, 17, 9],\n             [17, 0, 14],\n             [9, 14, 0]])\n\n\n    def test_manhattan_cols_normalized(self):\n        assert_almost_equal = np.testing.assert_almost_equal\n        data = self.cont_data\n\n        dist = distance.Manhattan(data, axis=0, normalize=True)\n        assert_almost_equal(\n            dist,\n            [[0, 4.5833333, 2],\n             [4.5833333, 0, 4.25],\n             [2, 4.25, 0]])\n\n        data.X[1, 1] = np.nan\n        dist = distance.Manhattan(data, axis=0, normalize=True)\n        assert_almost_equal(\n            dist,\n            [[0, 4.6666667, 2],\n             [4.6666667, 0, 4],\n             [2, 4, 0]])\n\n        data.X[1, 0] = np.nan\n        dist = distance.Manhattan(data, axis=0, normalize=True)\n        assert_almost_equal(\n            dist,\n            [[0, 5.5, 4],\n             [5.5, 0, 4],\n             [4, 4, 0]])\n\n    def test_manhattan_mixed(self):\n        assert_almost_equal = np.testing.assert_almost_equal\n        data = self.mixed_data\n\n        data.X[2, 0] = 2  # prevent mads[0] = 0\n        model = distance.Manhattan(axis=1, normalize=True).fit(data)\n        assert_almost_equal(model.medians, [1, 3, 1])\n        assert_almost_equal(model.mads, [1, 2, 1])\n        assert_almost_equal(model.dist_missing_disc,\n                            [[1/3, 2/3, 1, 1],\n                             [2/3, 2/3, 1, 2/3],\n                             [2/3, 1/3, 1, 1]])\n        assert_almost_equal(model.dist_missing2_disc,\n                            [1 - 5/9, 1 - 3/9, 1 - 5/9])\n\n        dist = model(data)\n        assert_almost_equal(\n            dist,\n            [[0, 4.5, 4.5],\n             [4.5, 0, 5],\n             [4.5, 5, 0]])\n\n    def test_two_tables(self):\n        assert_almost_equal = np.testing.assert_almost_equal\n\n        dist = distance.Manhattan(self.cont_data, self.cont_data2,\n                                  normalize=True)\n        assert_almost_equal(\n            dist,\n            [[1.3333333, 0.25],\n             [3.75, 2.6666667],\n             [2.5, 2.0833333],\n             [1.6666667, 2.75]])\n\n        model = distance.Manhattan(normalize=True).fit(self.cont_data)\n        dist = model(self.cont_data, self.cont_data2)\n        assert_almost_equal(\n            dist,\n            [[1.3333333, 0.25],\n             [3.75, 2.6666667],\n             [2.5, 2.0833333],\n             [1.6666667, 2.75]])\n\n        dist = model(self.cont_data2)\n        assert_almost_equal(dist, [[0, 1.083333333], [1.083333333, 0]])\n\n    def test_manhattan_mixed_cols(self):\n        self.assertRaises(ValueError,\n                          distance.Manhattan, self.mixed_data, axis=0)\n        self.assertRaises(ValueError,\n                          distance.Manhattan(axis=0).fit, self.mixed_data)\n\n\nclass CosineDistanceTest(FittedDistanceTest, CommonFittedTests):\n    Distance = distance.Cosine\n\n    def test_no_data(self):\n        with patch(\"warnings.warn\") as warn:\n            super().test_no_data()\n            self.assertEqual(warn.call_args[0],\n                             (\"Mean of empty slice\", RuntimeWarning))\n\n    def test_cosine_disc(self):\n        assert_almost_equal = np.testing.assert_almost_equal\n        data = self.disc_data\n        data.X = np.array([[1, 0, 0],\n                           [0, 1, 1],\n                           [1, 3, 0]], dtype=float)\n\n        model = distance.Cosine().fit(data)\n        assert_almost_equal(model.means, [2 / 3, 2 / 3, 1 / 3])\n\n        dist = model(data)\n        assert_almost_equal(dist, 1 - np.array([[1, 0, 1 / sqrt(2)],\n                                                [0, 1, 0.5],\n                                                [1 / sqrt(2), 0.5, 1]]))\n\n        data.X[1, 1] = np.nan\n        model = distance.Cosine().fit(data)\n        assert_almost_equal(model.means, [2 / 3, 1 / 2, 1 / 3])\n        dist = model(data)\n        assert_almost_equal(\n            dist,\n            1 - np.array([[1, 0, 1 / sqrt(2)],\n                          [0, 1, 0.5 / sqrt(1.25) / sqrt(2)],\n                          [1 / sqrt(2), 0.5 / sqrt(1.25) / sqrt(2), 1]]))\n\n        data.X = np.array([[1, 0, 0],\n                           [0, np.nan, 1],\n                           [1, np.nan, 1],\n                           [1, 3, 1]])\n        model = distance.Cosine().fit(data)\n        dist = model(data)\n        assert_almost_equal(model.means, [0.75, 0.5, 0.75])\n        assert_almost_equal(dist, [[0, 1, 0.333333333, 0.422649731],\n                                   [1, 0, 0.254644008, 0.225403331],\n                                   [0.333333333, 0.254644008, 0, 0.037749551],\n                                   [0.422649731, 0.225403331, 0.037749551, 0]])\n\n    def test_cosine_cont(self):\n        assert_almost_equal = np.testing.assert_almost_equal\n        data = self.cont_data\n\n        dist = distance.Cosine(data, axis=1)\n        assert_almost_equal(\n            dist,\n            [[0, 0.266200614, 0.0741799, 0.355097978],\n             [0.266200614, 0, 0.547089186, 0.925279678],\n             [0.0741799, 0.547089186, 0, 0.12011731],\n             [0.355097978, 0.925279678, 0.12011731, 0]]\n        )\n\n        data.X[1, 0] = np.nan\n        dist = distance.Cosine(data, axis=1)\n        assert_almost_equal(\n            dist,\n            [[0, 0.174971353, 0.0741799, 0.355097978],\n             [0.174971353, 0, 0.207881966, 0.324809395],\n             [0.0741799, 0.207881966, 0, 0.12011731],\n             [0.355097978, 0.324809395, 0.12011731, 0]])\n\n        data.X[0, 0] = np.nan\n        dist = distance.Cosine(data, axis=1)\n        assert_almost_equal(\n            dist,\n            [[0, 0.100977075, 0.035098719, 0.056666739],\n             [0.100977075, 0, 0.188497329, 0.246304671],\n             [0.035098719, 0.188497329, 0, 0.12011731],\n             [0.056666739, 0.246304671, 0.12011731, 0]])\n\n    def test_cosine_mixed(self):\n        assert_almost_equal = np.testing.assert_almost_equal\n        data = self.mixed_data\n        data.X = np.array([[1, 3, 2, 1, 0, 0],\n                           [-1, 5, 0, 0, 1, 1],\n                           [1, 1, 1, 1, 3, 0]], dtype=float)\n\n        model = distance.Cosine(axis=1).fit(data)\n        assert_almost_equal(model.means, [1/3, 3, 1, 2/3, 2/3, 1/3])\n        dist = model(data)\n        assert_almost_equal(\n            dist,\n            [[0, 0.316869949, 0.191709623],\n             [0.316869949, 0, 0.577422873],\n             [0.191709623, 0.577422873, 0]])\n\n    def test_two_tables(self):\n        assert_almost_equal = np.testing.assert_almost_equal\n        self.cont_data.X[1, 0] = np.nan\n        self.cont_data2.X[1, 0] = np.nan\n\n        dist = distance.Cosine(self.cont_data, self.cont_data2)\n        assert_almost_equal(\n            dist,\n            [[0.2142857, 0.1573352],\n             [0.4958158, 0.2097042],\n             [0.0741799, 0.0198039],\n             [0.1514447, 0.0451363]])\n\n        model = distance.Cosine().fit(self.cont_data)\n        dist = model(self.cont_data, self.cont_data2)\n        assert_almost_equal(\n            dist,\n            [[0.2142857, 0.1573352],\n             [0.4958158, 0.2097042],\n             [0.0741799, 0.0198039],\n             [0.1514447, 0.0451363]])\n\n        dist = model(self.cont_data2)\n        assert_almost_equal(dist, [[0, 0.092514787], [0.092514787, 0]])\n\n    def test_cosine_cols(self):\n        assert_almost_equal = np.testing.assert_almost_equal\n        data = self.cont_data\n\n        dist = distance.Cosine(data, axis=0, normalize=False)\n        assert_almost_equal(\n            dist,\n            [[0, 0.711324865, 0.11050082],\n             [0.711324865, 0, 0.44365136],\n             [0.11050082, 0.44365136, 0]])\n\n        data.X[1, 1] = np.nan\n        dist = distance.Cosine(data, axis=0, normalize=False)\n        assert_almost_equal(\n            dist,\n            [[0, 0.47702364, 0.11050082],\n             [0.47702364, 0, 0.181076975],\n             [0.11050082, 0.181076975, 0]])\n\n        data.X[1, 0] = np.nan\n        data.X[1, 2] = 2\n        dist = distance.Cosine(data, axis=0, normalize=False)\n        assert_almost_equal(\n            dist,\n            [[0, 0.269703257, 0.087129071],\n             [0.269703257, 0, 0.055555556],\n             [0.087129071, 0.055555556, 0]])\n\n\nclass JaccardDistanceTest(unittest.TestCase, CommonFittedTests):\n    Distance = distance.Jaccard\n\n    def setUp(self):\n        self.domain = Domain([DiscreteVariable(c) for c in \"abc\"])\n        self.data = Table.from_list(\n            self.domain,\n            [[0, 1, 1],\n             [1, 1, 1],\n             [1, 0, 1],\n             [1, 0, 0]])\n\n    def test_jaccard_rows(self):\n        assert_almost_equal = np.testing.assert_almost_equal\n\n        model = distance.Jaccard().fit(self.data)\n        assert_almost_equal(model.ps, [0.75, 0.5, 0.75])\n        assert_almost_equal(\n            model(self.data),\n            1 - np.array([[1, 2/3, 1/3, 0],\n                          [2/3, 1, 2/3, 1/3],\n                          [1/3, 2/3, 1, 1/2],\n                          [0, 1/3, 1/2, 1]]))\n\n        X = self.data.X\n        X[1, 0] = X[2, 0] = X[3, 1] = np.nan\n        model = distance.Jaccard().fit(self.data)\n        assert_almost_equal(model.ps, np.array([0.5, 2/3, 0.75]))\n\n        # pylint: disable=bad-whitespace\n        assert_almost_equal(\n            model(self.data),\n            1 - np.array([[      1,        2 / 2.5,        1 / 2.5,        2/3 / 3],\n                          [2 / 2.5,              1,    1.25 / 2.75,  (1/2+2/3) / 3],\n                          [1 / 2.5,    1.25 / 2.75,              1,  0.5 / (2+2/3)],\n                          [2/3 / 3,  (1/2+2/3) / 3,  0.5 / (2+2/3),            1]]))\n\n    def test_jaccard_cols(self):\n        assert_almost_equal = np.testing.assert_almost_equal\n        model = distance.Jaccard(axis=0).fit(self.data)\n        assert_almost_equal(model.ps, [0.75, 0.5, 0.75])\n        assert_almost_equal(\n            model(self.data),\n            1 - np.array([[1, 1/4, 1/2],\n                          [1/4, 1, 2/3],\n                          [1/2, 2/3, 1]]))\n\n        self.data.X = np.array([[0, 1, 1],\n                                [np.nan, np.nan, 1],\n                                [np.nan, 0, 1],\n                                [1, 1, 0]])\n        model = distance.Jaccard(axis=0).fit(self.data)\n        assert_almost_equal(model.ps, [0.5, 2/3, 0.75])\n        assert_almost_equal(\n            model(self.data),\n            1 - np.array([[1, 0.4, 0.25],\n                          [0.4, 1, 5/12],\n                          [0.25, 5/12, 1]]))\n\n    def test_zero_instances(self):\n        \"Test all zero instances\"\n        domain = Domain([ContinuousVariable(c) for c in \"abc\"])\n        dense_data = Table.from_list(\n            domain, [[0, 0, 0], [0, 0, 0], [0, 0, 1]])\n        sparse_data = Table(domain, csr_matrix(dense_data.X))\n        dist_dense = self.Distance(dense_data)\n        dist_sparse = self.Distance(sparse_data)\n\n        self.assertEqual(dist_dense[0][1], 0)\n        self.assertEqual(dist_sparse[0][1], 0)\n        self.assertEqual(dist_dense[0][2], 1)\n        self.assertEqual(dist_sparse[0][2], 1)\n\n\nclass HammingDistanceTest(FittedDistanceTest):\n    Distance = distance.Hamming\n\n    def test_hamming_col(self):\n        np.testing.assert_almost_equal(\n            self.Distance(self.disc_data, axis=0),\n            [[0, 2 / 3, 1 / 3],\n             [2 / 3, 0, 1 / 3],\n             [1 / 3, 1 / 3, 0]])\n\n    def test_hamming_row(self):\n        np.testing.assert_almost_equal(\n            self.Distance(self.disc_data),\n            [[0, 2 / 3, 1],\n             [2 / 3, 0, 2 / 3],\n             [1, 2 / 3, 0]]\n        )\n\n    def test_hamming_row_secondary_data(self):\n        np.testing.assert_almost_equal(\n            self.Distance(self.disc_data, self.disc_data[:2]),\n            [[0, 2 / 3],\n             [2 / 3, 0],\n             [1, 2 / 3]])\n\n\nclass TestHelperFunctions(unittest.TestCase):\n    # pylint: disable=protected-access, no-self-use\n    def test_interruptable_dot(self):\n        dot = distance.distance._interruptible_dot\n        k, m, n = 20, 30, 40\n        a = np.random.randint(10, size=(m, n))\n        b = np.random.randint(10, size=(n, k))\n\n        c = dot(a, b, step=10)\n        np.testing.assert_array_equal(c, np.dot(a, b))\n\n    def test_interruptable_dot_list(self):\n        dot = distance.distance._interruptible_dot\n        a = [[1, 2, 3], [1, 2, 3]]\n        b = [3, 2, 1]\n        c = dot(a, b, step=10)\n        np.testing.assert_array_equal(c, np.dot(a, b))\n\n    def test_interruptable_dot_scalar(self):\n        dot = distance.distance._interruptible_dot\n        a = 2\n        b = 3\n        c = dot(a, b, step=10)\n        np.testing.assert_array_equal(c, np.dot(a, b))\n\n    def test_interruptable_sqrt(self):\n        sqrt_ = distance.distance._interruptible_sqrt\n        n = 100\n        a = np.random.randint(10, size=(n, n))\n\n        new_a = sqrt_(a, step=10)\n        np.testing.assert_array_equal(new_a, np.sqrt(a))\n\n    def test_interruptable_sqrt_list(self):\n        sqrt_ = distance.distance._interruptible_sqrt\n        l = [1, 2, 3]\n        new_l = sqrt_(l, step=10)\n        np.testing.assert_array_equal(new_l, np.sqrt(l))\n\n    def test_interruptable_sqrt_scalar(self):\n        sqrt_ = distance.distance._interruptible_sqrt\n        i = 9\n        new_i = sqrt_(i, step=10)\n        np.testing.assert_array_equal(new_i, np.sqrt(i))\n\n\nif __name__ == \"__main__\":\n    unittest.main()\n",
            "new_file_content": "import unittest\nfrom unittest.mock import patch\nfrom math import sqrt\n\nimport numpy as np\nfrom scipy.sparse import csr_matrix\n\nfrom Orange.data import ContinuousVariable, DiscreteVariable, StringVariable,\\\n    Domain, Table\nfrom Orange import distance\n\n\nclass CommonTests:\n    \"\"\"Tests applicable to all distance measures\"\"\"\n\n    def test_no_data(self):\n        \"\"\"distances return zero-dimensional matrices when no data\"\"\"\n        n = len(self.data)\n        np.testing.assert_almost_equal(\n            self.Distance(Table.from_domain(self.domain)),\n            np.zeros((0, 0)))\n        np.testing.assert_almost_equal(\n            self.Distance(self.data, Table.from_domain(self.domain)),\n            np.zeros((n, 0)))\n        np.testing.assert_almost_equal(\n            self.Distance(Table.from_domain(self.domain), self.data),\n            np.zeros((0, n)))\n\n    def test_sparse(self):\n        \"\"\"Test sparse support in distances.\"\"\"\n        domain = Domain([ContinuousVariable(c) for c in \"abc\"])\n        dense_data = Table.from_list(\n            domain, [[1, 0, 2], [-1, 5, 0], [0, 1, 1], [7, 0, 0]])\n        sparse_data = Table(domain, csr_matrix(dense_data.X))\n\n        if not self.Distance.supports_sparse:\n            self.assertRaises(TypeError, self.Distance, sparse_data)\n        else:\n            # check the result is the same for sparse and dense\n            dist_dense = self.Distance(dense_data)\n            dist_sparse = self.Distance(sparse_data)\n            np.testing.assert_allclose(dist_sparse, dist_dense)\n\n\nclass CommonFittedTests(CommonTests):\n    \"\"\"Tests applicable to all distances with fitting\"\"\"\n    def test_mismatching_attributes(self):\n        \"\"\"distances can't be computed if fit from other attributes\"\"\"\n        def new_table(name):\n            return Table.from_list(Domain([ContinuousVariable(name)]), [[1]])\n\n        table1 = new_table(\"a\")\n        model = self.Distance().fit(table1)\n        self.assertRaises(ValueError, model, new_table(\"b\"))\n        self.assertRaises(ValueError, model, table1, new_table(\"c\"))\n        self.assertRaises(ValueError, model, new_table(\"d\"), table1)\n\n\nclass CommonNormalizedTests(CommonFittedTests):\n    \"\"\"Tests applicable to distances the have normalization\"\"\"\n\n    def test_zero_variance(self):\n        \"\"\"zero-variance columns have no effect on row distance\"\"\"\n        assert_almost_equal = np.testing.assert_almost_equal\n        normalized = self.Distance(axis=1, normalize=True)\n        nonnormalized = self.Distance(axis=1, normalize=False)\n\n        def is_same(d1, d2, fit1=None, fit2=None):\n            if fit1 is None:\n                fit1 = d1\n            if fit2 is None:\n                fit2 = d2\n            assert_almost_equal(normalized.fit(fit1)(d1),\n                                normalized.fit(fit2)(d2))\n            assert_almost_equal(nonnormalized.fit(fit1)(d1),\n                                nonnormalized.fit(fit2)(d2))\n\n        data = self.cont_data\n        n = len(data)\n        X = data.X\n        domain = Domain(data.domain.attributes + (ContinuousVariable(\"d\"),))\n        data_const = Table(domain, np.hstack((X, np.ones((n, 1)))))\n        data_nan = Table(domain, np.hstack((X, np.full((n, 1), np.nan))))\n        data_nan_1 = Table(domain, np.hstack((X, np.full((n, 1), np.nan))))\n        data_nan_1.X[0, -1] = 1\n        is_same(data, data_const)\n        is_same(data, data_nan)\n        is_same(data, data_nan_1)\n\n        # Test whether it's possible to fit with singular data and use the\n        # parameters on data where the same column is defined\n        is_same(data_nan, data_const, data_const)\n        is_same(data_const, data_const, data_nan)\n\n        self.assertRaises(ValueError, self.Distance,\n                          data_const, axis=0, normalize=True)\n        self.assertRaises(ValueError, self.Distance,\n                          data_nan, axis=0, normalize=True)\n        self.assertRaises(ValueError, self.Distance,\n                          data_nan_1, axis=0, normalize=True)\n\n    def test_mixed_cols(self):\n        \"\"\"distance over columns raises exception for discrete columns\"\"\"\n        self.assertRaises(ValueError, self.Distance, self.mixed_data, axis=0)\n        self.assertRaises(ValueError,\n                          self.Distance(axis=0).fit, self.mixed_data)\n\n\nclass FittedDistanceTest(unittest.TestCase):\n    @classmethod\n    def setUpClass(cls):\n        cls.attributes = (\n            ContinuousVariable(\"c1\"),\n            ContinuousVariable(\"c2\"),\n            ContinuousVariable(\"c3\"),\n            DiscreteVariable(\"d1\", values=(\"a\", \"b\")),\n            DiscreteVariable(\"d2\", values=(\"a\", \"b\", \"c\", \"d\")),\n            DiscreteVariable(\"d3\", values=(\"a\", \"b\", \"c\")))\n        cls.domain = Domain(cls.attributes)\n        cls.cont_domain = Domain(cls.attributes[:3])\n        cls.disc_domain = Domain(cls.attributes[3:])\n\n    def setUp(self):\n        self.cont_data = Table.from_list(\n            self.cont_domain,\n            [[1, 3, 2],\n             [-1, 5, 0],\n             [1, 1, 1],\n             [7, 2, 3]])\n\n        self.cont_data2 = Table.from_list(\n            self.cont_domain,\n            [[2, 1, 3],\n             [1, 2, 2]]\n        )\n\n        self.disc_data = Table.from_list(\n            self.disc_domain,\n            [[0, 0, 0],\n             [0, 1, 1],\n             [1, 3, 1]]\n        )\n\n        self.disc_data4 = Table.from_list(\n            self.disc_domain,\n            [[0, 0, 0],\n             [0, 1, 1],\n             [0, 1, 1],\n             [1, 3, 1]]\n        )\n\n        self.mixed_data = self.data = Table.from_numpy(\n            self.domain, np.hstack((self.cont_data.X[:3], self.disc_data.X)))\n\n\n\n# Correct results in these tests were computed manually or with Excel;\n# these are not regression tests\nclass EuclideanDistanceTest(FittedDistanceTest, CommonNormalizedTests):\n    Distance = distance.Euclidean\n\n    def test_euclidean_disc(self):\n        assert_almost_equal = np.testing.assert_almost_equal\n        data = self.disc_data\n\n        model = distance.Euclidean().fit(data)\n        assert_almost_equal(model.dist_missing_disc,\n                            [[1/3, 2/3, 1, 1],\n                             [2/3, 2/3, 1, 2/3],\n                             [2/3, 1/3, 1, 1]])\n        assert_almost_equal(model.dist_missing2_disc,\n                            [1 - 5/9, 1 - 3/9, 1 - 5/9])\n\n        dist = model(data)\n        assert_almost_equal(dist,\n                            np.sqrt(np.array([[0, 2, 3],\n                                              [2, 0, 2],\n                                              [3, 2, 0]])))\n\n        data.X[1, 0] = np.nan\n        model = distance.Euclidean().fit(data)\n        assert_almost_equal(model.dist_missing_disc,\n                            [[1/2, 1/2, 1, 1],\n                             [2/3, 2/3, 1, 2/3],\n                             [2/3, 1/3, 1, 1]\n                            ])\n        assert_almost_equal(model.dist_missing2_disc,\n                            [1 - 2/4, 1 - 3/9, 1 - 5/9])\n\n        dist = model(data)\n        assert_almost_equal(dist,\n                            np.sqrt(np.array([[0, 2.5, 3],\n                                              [2.5, 0, 1.5],\n                                              [3, 1.5, 0]])))\n\n        data.X[0, 0] = np.nan\n        model = distance.Euclidean().fit(data)\n        assert_almost_equal(model.dist_missing_disc,\n                            [[1, 0, 1, 1],\n                             [2/3, 2/3, 1, 2/3],\n                             [2/3, 1/3, 1, 1]])\n        assert_almost_equal(model.dist_missing2_disc,\n                            [1 - 1, 1 - 3/9, 1 - 5/9])\n\n        dist = model(data)\n        assert_almost_equal(dist,\n                            np.sqrt(np.array([[0, 2, 2],\n                                              [2, 0, 1],\n                                              [2, 1, 0]])))\n\n        data = self.disc_data4\n        data.X[:2, 0] = np.nan\n        model = distance.Euclidean().fit(data)\n\n        assert_almost_equal(model.dist_missing_disc,\n                            [[1/2, 1/2, 1, 1],\n                             [3/4, 2/4, 1, 3/4],\n                             [3/4, 1/4, 1, 1]])\n        assert_almost_equal(model.dist_missing2_disc,\n                            [1 - 2/4, 1 - 6/16, 1 - 10/16])\n\n        dist = model(data)\n        assert_almost_equal(dist,\n                            np.sqrt(np.array([[0, 2.5, 2.5, 2.5],\n                                              [2.5, 0, 0.5, 1.5],\n                                              [2.5, 0.5, 0, 2],\n                                              [2.5, 1.5, 2, 0]])))\n\n    def test_euclidean_cont(self):\n        assert_almost_equal = np.testing.assert_almost_equal\n        data = self.cont_data\n\n        dist = distance.Euclidean(data, axis=1, normalize=False)\n        assert_almost_equal(\n            dist,\n            np.sqrt(np.array([[0, 12, 5, 38],\n                              [12, 0, 21, 82],\n                              [5, 21, 0, 41],\n                              [38, 82, 41, 0]])))\n\n        data.X[1, 0] = np.nan\n        dist = distance.Euclidean(data, axis=1, normalize=False)\n        assert_almost_equal(\n            dist,\n            [[0, 4.472135955, 2.236067977, 6.164414003],\n             [4.472135955, 0, 5.385164807, 6.480740698],\n             [2.236067977, 5.385164807, 0, 6.403124237],\n             [6.164414003, 6.480740698, 6.403124237, 0]])\n\n        data.X[0, 0] = np.nan\n        dist = distance.Euclidean(data, axis=1, normalize=False)\n        assert_almost_equal(\n            dist,\n            [[0, 5.099019514, 4.795831523, 4.472135955],\n             [5.099019514, 0, 5.916079783, 6],\n             [4.795831523, 5.916079783, 0, 6.403124237],\n             [4.472135955, 6, 6.403124237, 0]])\n\n    def test_euclidean_cont_normalized(self):\n        assert_almost_equal = np.testing.assert_almost_equal\n        data = self.cont_data\n\n        model = distance.Euclidean(axis=1, normalize=True).fit(data)\n        assert_almost_equal(model.means, [2, 2.75, 1.5])\n        assert_almost_equal(model.vars, [9, 2.1875, 1.25])\n        assert_almost_equal(model.dist_missing2_cont, [1, 1, 1])\n\n        dist = model(data)\n        assert_almost_equal(\n            dist,\n            [[0, 1.654239383, 1.146423008, 1.621286967],\n             [1.654239383, 0, 2.068662631, 3.035242727],\n             [1.146423008, 2.068662631, 0, 1.956673562],\n             [1.621286967, 3.035242727, 1.956673562, 0]])\n\n        dist = distance.Euclidean(data, axis=1, normalize=True)\n        assert_almost_equal(\n            dist,\n            [[0, 1.654239383, 1.146423008, 1.621286967],\n             [1.654239383, 0, 2.068662631, 3.035242727],\n             [1.146423008, 2.068662631, 0, 1.956673562],\n             [1.621286967, 3.035242727, 1.956673562, 0]])\n\n        data.X[1, 0] = np.nan\n        model = distance.Euclidean(axis=1, normalize=True).fit(data)\n        assert_almost_equal(model.means, [3, 2.75, 1.5])\n        assert_almost_equal(model.vars, [8, 2.1875, 1.25])\n        dist = model(data)\n        assert_almost_equal(\n            dist,\n            [[0, 1.806733438, 1.146423008, 1.696635326],\n             [1.806733438, 0, 2.192519751, 2.675283697],\n             [1.146423008, 2.192519751, 0, 2.019547333],\n             [1.696635326, 2.675283697, 2.019547333, 0]])\n\n        data.X[0, 0] = np.nan\n        model = distance.Euclidean(axis=1, normalize=True).fit(data)\n        assert_almost_equal(model.means, [4, 2.75, 1.5])\n        assert_almost_equal(model.vars, [9, 2.1875, 1.25])\n        dist = model(data)\n        assert_almost_equal(\n            dist,\n            [[0, 1.874642823, 1.521277659, 1.276154939],\n             [1.874642823, 0, 2.248809209, 2.580143961],\n             [1.521277659, 2.248809209, 0, 1.956673562],\n             [1.276154939, 2.580143961, 1.956673562, 0]])\n\n    def test_euclidean_cols(self):\n        assert_almost_equal = np.testing.assert_almost_equal\n        data = self.cont_data\n\n        dist = distance.Euclidean(data, axis=0, normalize=False)\n        assert_almost_equal(\n            dist,\n            [[0, 8.062257748, 4.242640687],\n             [8.062257748, 0, 5.196152423],\n             [4.242640687, 5.196152423, 0]])\n\n        data.X[1, 1] = np.nan\n        dist = distance.Euclidean(data, axis=0, normalize=False)\n        assert_almost_equal(\n            dist,\n            [[0, 6.218252702, 4.242640687],\n             [6.218252702, 0, 2.581988897],\n             [4.242640687, 2.581988897, 0]])\n\n        data.X[1, 0] = np.nan\n        dist = distance.Euclidean(data, axis=0, normalize=False)\n        assert_almost_equal(\n            dist,\n            [[0, 6.218252702, 5.830951895],\n             [6.218252702, 0, 2.581988897],\n             [5.830951895, 2.581988897, 0]])\n\n    def test_euclidean_cols_normalized(self):\n        assert_almost_equal = np.testing.assert_almost_equal\n        data = self.cont_data\n\n        dist = distance.Euclidean(data, axis=0, normalize=True)\n        assert_almost_equal(\n            dist,\n            [[0, 2.455273959, 0.649839392],\n             [2.455273959, 0, 2.473176308],\n             [0.649839392, 2.473176308, 0]])\n\n        data.X[1, 1] = np.nan\n        dist = distance.Euclidean(data, axis=0, normalize=True)\n        assert_almost_equal(\n            dist,\n            [[0, 2, 0.649839392],\n             [2, 0, 1.704275472],\n             [0.649839392, 1.704275472, 0]])\n\n        data.X[1, 0] = np.nan\n        dist = distance.Euclidean(data, axis=0, normalize=True)\n        assert_almost_equal(\n            dist,\n            [[0, 2, 1.450046001],\n             [2, 0, 1.704275472],\n             [1.450046001, 1.704275472, 0]])\n\n    def test_euclidean_mixed(self):\n        assert_almost_equal = np.testing.assert_almost_equal\n        data = self.mixed_data\n\n        model = distance.Euclidean(axis=1, normalize=True).fit(data)\n\n        assert_almost_equal(model.means, [1/3, 3, 1])\n        assert_almost_equal(model.vars, [8/9, 8/3, 2/3])\n        assert_almost_equal(model.dist_missing_disc,\n                            [[1/3, 2/3, 1, 1],\n                             [2/3, 2/3, 1, 2/3],\n                             [2/3, 1/3, 1, 1]])\n        assert_almost_equal(model.dist_missing2_cont, [1, 1, 1])\n        assert_almost_equal(model.dist_missing2_disc,\n                            [1 - 5/9, 1 - 3/9, 1 - 5/9])\n        dist = model(data)\n        assert_almost_equal(\n            dist,\n            [[0, 2.828427125, 2.121320344],\n             [2.828427125, 0, 2.828427125],\n             [2.121320344, 2.828427125, 0]])\n\n    def test_two_tables(self):\n        assert_almost_equal = np.testing.assert_almost_equal\n\n        dist = distance.Euclidean(self.cont_data, self.cont_data2,\n                                  normalize=True)\n        assert_almost_equal(\n            dist,\n            [[1.17040218, 0.47809144],\n             [2.78516478, 1.96961039],\n             [1.28668394, 0.79282497],\n             [1.27179413, 1.54919334]])\n\n        model = distance.Euclidean(normalize=True).fit(self.cont_data)\n        dist = model(self.cont_data, self.cont_data2)\n        assert_almost_equal(\n            dist,\n            [[1.17040218, 0.47809144],\n             [2.78516478, 1.96961039],\n             [1.28668394, 0.79282497],\n             [1.27179413, 1.54919334]])\n\n        dist = model(self.cont_data2)\n        assert_almost_equal(dist, [[0, 0.827119692], [0.827119692, 0]])\n\n\nclass ManhattanDistanceTest(FittedDistanceTest, CommonNormalizedTests):\n    Distance = distance.Euclidean\n\n    # The data used for testing Euclidean distances unfortunately yields\n    # mads = 1, so we change it a bit\n    def setUp(self):\n        super().setUp()\n        self.cont_data = Table.from_list(\n            self.cont_domain,\n            [[1, 3, 2],\n             [-1, 6, 0],\n             [2, 7, 1],\n             [7, 1, 3]])\n\n    def test_manhattan_no_data(self):\n        np.testing.assert_almost_equal(\n            distance.Manhattan(Table.from_domain(self.domain)),\n            np.zeros((0, 0)))\n        np.testing.assert_almost_equal(\n            distance.Manhattan(self.mixed_data, Table.from_domain(self.domain)),\n            np.zeros((3, 0)))\n        np.testing.assert_almost_equal(\n            distance.Manhattan(Table.from_domain(self.domain), self.mixed_data),\n            np.zeros((0, 3)))\n        self.assertRaises(\n            ValueError,\n            distance.Manhattan, Table.from_domain(self.cont_domain),\n            axis=0, normalize=True)\n\n    def test_manhattan_disc(self):\n        assert_almost_equal = np.testing.assert_almost_equal\n        data = self.disc_data\n\n        model = distance.Manhattan().fit(data)\n        assert_almost_equal(model.dist_missing_disc,\n                            [[1/3, 2/3, 1, 1],\n                             [2/3, 2/3, 1, 2/3],\n                             [2/3, 1/3, 1, 1]])\n        assert_almost_equal(model.dist_missing2_disc,\n                            [1 - 5/9, 1 - 3/9, 1 - 5/9])\n        dist = model(data)\n        assert_almost_equal(dist,\n                            [[0, 2, 3],\n                             [2, 0, 2],\n                             [3, 2, 0]])\n\n        data.X[1, 0] = np.nan\n        model = distance.Manhattan().fit(data)\n        assert_almost_equal(model.dist_missing_disc,\n                            [[1/2, 1/2, 1, 1],\n                             [2/3, 2/3, 1, 2/3],\n                             [2/3, 1/3, 1, 1]])\n        assert_almost_equal(model.dist_missing2_disc,\n                            [1 - 2/4, 1 - 3/9, 1 - 5/9])\n\n        dist = model(data)\n        assert_almost_equal(dist,\n                            [[0, 2.5, 3],\n                             [2.5, 0, 1.5],\n                             [3, 1.5, 0]])\n\n        data.X[0, 0] = np.nan\n        model = distance.Manhattan().fit(data)\n        assert_almost_equal(model.dist_missing_disc,\n                            [[1, 0, 1, 1],\n                             [2/3, 2/3, 1, 2/3],\n                             [2/3, 1/3, 1, 1]])\n        assert_almost_equal(model.dist_missing2_disc,\n                            [1 - 1, 1 - 3/9, 1 - 5/9])\n\n        dist = model(data)\n        assert_almost_equal(dist,\n                            [[0, 2, 2],\n                             [2, 0, 1],\n                             [2, 1, 0]])\n\n        data = self.disc_data4\n        data.X[:2, 0] = np.nan\n        model = distance.Manhattan().fit(data)\n        assert_almost_equal(model.dist_missing_disc,\n                            [[1/2, 1/2, 1, 1],\n                             [3/4, 2/4, 1, 3/4],\n                             [3/4, 1/4, 1, 1]])\n        assert_almost_equal(model.dist_missing2_disc,\n                            [1 - 2/4, 1 - 6/16, 1 - 10/16])\n\n        dist = model(data)\n        assert_almost_equal(dist,\n                            [[0, 2.5, 2.5, 2.5],\n                             [2.5, 0, 0.5, 1.5],\n                             [2.5, 0.5, 0, 2],\n                             [2.5, 1.5, 2, 0]])\n\n    def test_manhattan_cont(self):\n        assert_almost_equal = np.testing.assert_almost_equal\n        data = self.cont_data\n\n        dist = distance.Manhattan(data, axis=1, normalize=False)\n        assert_almost_equal(\n            dist,\n            [[0, 7, 6, 9],\n             [7, 0, 5, 16],\n             [6, 5, 0, 13],\n             [9, 16, 13, 0]])\n\n        data.X[1, 0] = np.nan\n        dist = distance.Manhattan(data, axis=1, normalize=False)\n        assert_almost_equal(\n            dist,\n            [[0, 7, 6, 9],\n             [7, 0, 3, 14],\n             [6, 3, 0, 13],\n             [9, 14, 13, 0]])\n\n        data.X[0, 0] = np.nan\n        dist = distance.Manhattan(data, axis=1, normalize=False)\n        assert_almost_equal(\n            dist,\n            [[0, 10, 10, 8],\n             [10, 0, 7, 13],\n             [10, 7, 0, 13],\n             [8, 13, 13, 0]])\n\n    def test_manhattan_cont_normalized(self):\n        assert_almost_equal = np.testing.assert_almost_equal\n        data = self.cont_data\n\n        model = distance.Manhattan(axis=1, normalize=True).fit(data)\n        assert_almost_equal(model.medians, [1.5, 4.5, 1.5])\n        assert_almost_equal(model.mads, [1.5, 2, 1])\n        assert_almost_equal(model.dist_missing2_cont, np.ones(3))\n\n        dist = model(data)\n        assert_almost_equal(\n            dist,\n            [[0, 2.416666667, 1.833333333, 3],\n             [2.416666667, 0, 1.75, 5.416666667],\n             [1.833333333, 1.75, 0, 4.166666667],\n             [3, 5.416666667, 4.166666667, 0]])\n\n        dist = distance.Manhattan(data, axis=1, normalize=True)\n        assert_almost_equal(\n            dist,\n            [[0, 2.416666667, 1.833333333, 3],\n             [2.416666667, 0, 1.75, 5.416666667],\n             [1.833333333, 1.75, 0, 4.166666667],\n             [3, 5.416666667, 4.166666667, 0]])\n\n        data.X[1, 0] = np.nan\n        model = distance.Manhattan(axis=1, normalize=True).fit(data)\n        assert_almost_equal(model.medians, [2, 4.5, 1.5])\n        assert_almost_equal(model.mads, [1, 2, 1])\n\n        dist = model(data)\n        assert_almost_equal(\n            dist,\n            [[0, 2.75, 2, 4],\n             [2.75, 0, 1.25, 5.75],\n             [2, 1.25, 0, 5],\n             [4, 5.75, 5, 0]])\n\n        data.X[0, 0] = np.nan\n        model = distance.Manhattan(axis=1, normalize=True).fit(data)\n        assert_almost_equal(model.medians, [4.5, 4.5, 1.5])\n        assert_almost_equal(model.mads, [2.5, 2, 1])\n\n        dist = model(data)\n        assert_almost_equal(\n            dist,\n            [[0, 2.75, 2.5, 2],\n             [2.75, 0, 1.75, 3.75],\n             [2.5, 1.75, 0, 3.5],\n             [2, 3.75, 3.5, 0]])\n\n    def test_manhattan_cols(self):\n        assert_almost_equal = np.testing.assert_almost_equal\n        data = self.cont_data\n\n        dist = distance.Manhattan(data, axis=0, normalize=False)\n        assert_almost_equal(\n            dist,\n            [[0, 20, 7],\n             [20, 0, 15],\n             [7, 15, 0]])\n\n        data.X[1, 1] = np.nan\n        dist = distance.Manhattan(data, axis=0, normalize=False)\n        assert_almost_equal(\n            dist,\n            [[0, 19, 7],\n             [19, 0, 14],\n             [7, 14, 0]])\n\n        data.X[1, 0] = np.nan\n        dist = distance.Manhattan(data, axis=0, normalize=False)\n        assert_almost_equal(\n            dist,\n            [[0, 17, 9],\n             [17, 0, 14],\n             [9, 14, 0]])\n\n\n    def test_manhattan_cols_normalized(self):\n        assert_almost_equal = np.testing.assert_almost_equal\n        data = self.cont_data\n\n        dist = distance.Manhattan(data, axis=0, normalize=True)\n        assert_almost_equal(\n            dist,\n            [[0, 4.5833333, 2],\n             [4.5833333, 0, 4.25],\n             [2, 4.25, 0]])\n\n        data.X[1, 1] = np.nan\n        dist = distance.Manhattan(data, axis=0, normalize=True)\n        assert_almost_equal(\n            dist,\n            [[0, 4.6666667, 2],\n             [4.6666667, 0, 4],\n             [2, 4, 0]])\n\n        data.X[1, 0] = np.nan\n        dist = distance.Manhattan(data, axis=0, normalize=True)\n        assert_almost_equal(\n            dist,\n            [[0, 5.5, 4],\n             [5.5, 0, 4],\n             [4, 4, 0]])\n\n    def test_manhattan_mixed(self):\n        assert_almost_equal = np.testing.assert_almost_equal\n        data = self.mixed_data\n\n        data.X[2, 0] = 2  # prevent mads[0] = 0\n        model = distance.Manhattan(axis=1, normalize=True).fit(data)\n        assert_almost_equal(model.medians, [1, 3, 1])\n        assert_almost_equal(model.mads, [1, 2, 1])\n        assert_almost_equal(model.dist_missing_disc,\n                            [[1/3, 2/3, 1, 1],\n                             [2/3, 2/3, 1, 2/3],\n                             [2/3, 1/3, 1, 1]])\n        assert_almost_equal(model.dist_missing2_disc,\n                            [1 - 5/9, 1 - 3/9, 1 - 5/9])\n\n        dist = model(data)\n        assert_almost_equal(\n            dist,\n            [[0, 4.5, 4.5],\n             [4.5, 0, 5],\n             [4.5, 5, 0]])\n\n    def test_two_tables(self):\n        assert_almost_equal = np.testing.assert_almost_equal\n\n        dist = distance.Manhattan(self.cont_data, self.cont_data2,\n                                  normalize=True)\n        assert_almost_equal(\n            dist,\n            [[1.3333333, 0.25],\n             [3.75, 2.6666667],\n             [2.5, 2.0833333],\n             [1.6666667, 2.75]])\n\n        model = distance.Manhattan(normalize=True).fit(self.cont_data)\n        dist = model(self.cont_data, self.cont_data2)\n        assert_almost_equal(\n            dist,\n            [[1.3333333, 0.25],\n             [3.75, 2.6666667],\n             [2.5, 2.0833333],\n             [1.6666667, 2.75]])\n\n        dist = model(self.cont_data2)\n        assert_almost_equal(dist, [[0, 1.083333333], [1.083333333, 0]])\n\n    def test_manhattan_mixed_cols(self):\n        self.assertRaises(ValueError,\n                          distance.Manhattan, self.mixed_data, axis=0)\n        self.assertRaises(ValueError,\n                          distance.Manhattan(axis=0).fit, self.mixed_data)\n\n\nclass CosineDistanceTest(FittedDistanceTest, CommonFittedTests):\n    Distance = distance.Cosine\n\n    def test_no_data(self):\n        with patch(\"warnings.warn\") as warn:\n            super().test_no_data()\n            self.assertEqual(warn.call_args[0],\n                             (\"Mean of empty slice\", RuntimeWarning))\n\n    def test_cosine_disc(self):\n        assert_almost_equal = np.testing.assert_almost_equal\n        data = self.disc_data\n        data.X = np.array([[1, 0, 0],\n                           [0, 1, 1],\n                           [1, 3, 0]], dtype=float)\n\n        model = distance.Cosine().fit(data)\n        assert_almost_equal(model.means, [2 / 3, 2 / 3, 1 / 3])\n\n        dist = model(data)\n        assert_almost_equal(dist, 1 - np.array([[1, 0, 1 / sqrt(2)],\n                                                [0, 1, 0.5],\n                                                [1 / sqrt(2), 0.5, 1]]))\n\n        data.X[1, 1] = np.nan\n        model = distance.Cosine().fit(data)\n        assert_almost_equal(model.means, [2 / 3, 1 / 2, 1 / 3])\n        dist = model(data)\n        assert_almost_equal(\n            dist,\n            1 - np.array([[1, 0, 1 / sqrt(2)],\n                          [0, 1, 0.5 / sqrt(1.25) / sqrt(2)],\n                          [1 / sqrt(2), 0.5 / sqrt(1.25) / sqrt(2), 1]]))\n\n        data.X = np.array([[1, 0, 0],\n                           [0, np.nan, 1],\n                           [1, np.nan, 1],\n                           [1, 3, 1]])\n        model = distance.Cosine().fit(data)\n        dist = model(data)\n        assert_almost_equal(model.means, [0.75, 0.5, 0.75])\n        assert_almost_equal(dist, [[0, 1, 0.333333333, 0.422649731],\n                                   [1, 0, 0.254644008, 0.225403331],\n                                   [0.333333333, 0.254644008, 0, 0.037749551],\n                                   [0.422649731, 0.225403331, 0.037749551, 0]])\n\n    def test_cosine_cont(self):\n        assert_almost_equal = np.testing.assert_almost_equal\n        data = self.cont_data\n\n        dist = distance.Cosine(data, axis=1)\n        assert_almost_equal(\n            dist,\n            [[0, 0.266200614, 0.0741799, 0.355097978],\n             [0.266200614, 0, 0.547089186, 0.925279678],\n             [0.0741799, 0.547089186, 0, 0.12011731],\n             [0.355097978, 0.925279678, 0.12011731, 0]]\n        )\n\n        data.X[1, 0] = np.nan\n        dist = distance.Cosine(data, axis=1)\n        assert_almost_equal(\n            dist,\n            [[0, 0.174971353, 0.0741799, 0.355097978],\n             [0.174971353, 0, 0.207881966, 0.324809395],\n             [0.0741799, 0.207881966, 0, 0.12011731],\n             [0.355097978, 0.324809395, 0.12011731, 0]])\n\n        data.X[0, 0] = np.nan\n        dist = distance.Cosine(data, axis=1)\n        assert_almost_equal(\n            dist,\n            [[0, 0.100977075, 0.035098719, 0.056666739],\n             [0.100977075, 0, 0.188497329, 0.246304671],\n             [0.035098719, 0.188497329, 0, 0.12011731],\n             [0.056666739, 0.246304671, 0.12011731, 0]])\n\n    def test_cosine_mixed(self):\n        assert_almost_equal = np.testing.assert_almost_equal\n        data = self.mixed_data\n        data.X = np.array([[1, 3, 2, 1, 0, 0],\n                           [-1, 5, 0, 0, 1, 1],\n                           [1, 1, 1, 1, 3, 0]], dtype=float)\n\n        model = distance.Cosine(axis=1).fit(data)\n        assert_almost_equal(model.means, [1/3, 3, 1, 2/3, 2/3, 1/3])\n        dist = model(data)\n        assert_almost_equal(\n            dist,\n            [[0, 0.316869949, 0.191709623],\n             [0.316869949, 0, 0.577422873],\n             [0.191709623, 0.577422873, 0]])\n\n    def test_two_tables(self):\n        assert_almost_equal = np.testing.assert_almost_equal\n        self.cont_data.X[1, 0] = np.nan\n        self.cont_data2.X[1, 0] = np.nan\n\n        dist = distance.Cosine(self.cont_data, self.cont_data2)\n        assert_almost_equal(\n            dist,\n            [[0.2142857, 0.1573352],\n             [0.4958158, 0.2097042],\n             [0.0741799, 0.0198039],\n             [0.1514447, 0.0451363]])\n\n        model = distance.Cosine().fit(self.cont_data)\n        dist = model(self.cont_data, self.cont_data2)\n        assert_almost_equal(\n            dist,\n            [[0.2142857, 0.1573352],\n             [0.4958158, 0.2097042],\n             [0.0741799, 0.0198039],\n             [0.1514447, 0.0451363]])\n\n        dist = model(self.cont_data2)\n        assert_almost_equal(dist, [[0, 0.092514787], [0.092514787, 0]])\n\n    def test_cosine_cols(self):\n        assert_almost_equal = np.testing.assert_almost_equal\n        data = self.cont_data\n\n        dist = distance.Cosine(data, axis=0, normalize=False)\n        assert_almost_equal(\n            dist,\n            [[0, 0.711324865, 0.11050082],\n             [0.711324865, 0, 0.44365136],\n             [0.11050082, 0.44365136, 0]])\n\n        data.X[1, 1] = np.nan\n        dist = distance.Cosine(data, axis=0, normalize=False)\n        assert_almost_equal(\n            dist,\n            [[0, 0.47702364, 0.11050082],\n             [0.47702364, 0, 0.181076975],\n             [0.11050082, 0.181076975, 0]])\n\n        data.X[1, 0] = np.nan\n        data.X[1, 2] = 2\n        dist = distance.Cosine(data, axis=0, normalize=False)\n        assert_almost_equal(\n            dist,\n            [[0, 0.269703257, 0.087129071],\n             [0.269703257, 0, 0.055555556],\n             [0.087129071, 0.055555556, 0]])\n\n\nclass JaccardDistanceTest(unittest.TestCase, CommonFittedTests):\n    Distance = distance.Jaccard\n\n    def setUp(self):\n        self.domain = Domain([DiscreteVariable(c) for c in \"abc\"])\n        self.data = Table.from_list(\n            self.domain,\n            [[0, 1, 1],\n             [1, 1, 1],\n             [1, 0, 1],\n             [1, 0, 0]])\n\n    def test_jaccard_rows(self):\n        assert_almost_equal = np.testing.assert_almost_equal\n\n        model = distance.Jaccard().fit(self.data)\n        assert_almost_equal(model.ps, [0.75, 0.5, 0.75])\n        assert_almost_equal(\n            model(self.data),\n            1 - np.array([[1, 2/3, 1/3, 0],\n                          [2/3, 1, 2/3, 1/3],\n                          [1/3, 2/3, 1, 1/2],\n                          [0, 1/3, 1/2, 1]]))\n\n        X = self.data.X\n        X[1, 0] = X[2, 0] = X[3, 1] = np.nan\n        model = distance.Jaccard().fit(self.data)\n        assert_almost_equal(model.ps, np.array([0.5, 2/3, 0.75]))\n\n        assert_almost_equal(\n            model(self.data),\n            1 - np.array([[      1,        2 / 2.5,        1 / 2.5,        2/3 / 3],\n                          [2 / 2.5,              1,    1.25 / 2.75,  (1/2+2/3) / 3],\n                          [1 / 2.5,    1.25 / 2.75,              1,  0.5 / (2+2/3)],\n                          [2/3 / 3,  (1/2+2/3) / 3,  0.5 / (2+2/3),            1]]))\n\n    def test_jaccard_cols(self):\n        assert_almost_equal = np.testing.assert_almost_equal\n        model = distance.Jaccard(axis=0).fit(self.data)\n        assert_almost_equal(model.ps, [0.75, 0.5, 0.75])\n        assert_almost_equal(\n            model(self.data),\n            1 - np.array([[1, 1/4, 1/2],\n                          [1/4, 1, 2/3],\n                          [1/2, 2/3, 1]]))\n\n        self.data.X = np.array([[0, 1, 1],\n                                [np.nan, np.nan, 1],\n                                [np.nan, 0, 1],\n                                [1, 1, 0]])\n        model = distance.Jaccard(axis=0).fit(self.data)\n        assert_almost_equal(model.ps, [0.5, 2/3, 0.75])\n        assert_almost_equal(\n            model(self.data),\n            1 - np.array([[1, 0.4, 0.25],\n                          [0.4, 1, 5/12],\n                          [0.25, 5/12, 1]]))\n\n    def test_zero_instances(self):\n        \"Test all zero instances\"\n        domain = Domain([ContinuousVariable(c) for c in \"abc\"])\n        dense_data = Table.from_list(\n            domain, [[0, 0, 0], [0, 0, 0], [0, 0, 1]])\n        sparse_data = Table(domain, csr_matrix(dense_data.X))\n        dist_dense = self.Distance(dense_data)\n        dist_sparse = self.Distance(sparse_data)\n\n        # false positive, pylint: disable=unsubscriptable-object\n        self.assertEqual(dist_dense[0][1], 0)\n        self.assertEqual(dist_sparse[0][1], 0)\n        self.assertEqual(dist_dense[0][2], 1)\n        self.assertEqual(dist_sparse[0][2], 1)\n\n\nclass HammingDistanceTest(FittedDistanceTest):\n    Distance = distance.Hamming\n\n    def test_hamming_col(self):\n        np.testing.assert_almost_equal(\n            self.Distance(self.disc_data, axis=0),\n            [[0, 2 / 3, 1 / 3],\n             [2 / 3, 0, 1 / 3],\n             [1 / 3, 1 / 3, 0]])\n\n    def test_hamming_row(self):\n        np.testing.assert_almost_equal(\n            self.Distance(self.disc_data),\n            [[0, 2 / 3, 1],\n             [2 / 3, 0, 2 / 3],\n             [1, 2 / 3, 0]]\n        )\n\n    def test_hamming_row_secondary_data(self):\n        np.testing.assert_almost_equal(\n            self.Distance(self.disc_data, self.disc_data[:2]),\n            [[0, 2 / 3],\n             [2 / 3, 0],\n             [1, 2 / 3]])\n\n\nclass TestHelperFunctions(unittest.TestCase):\n    # pylint: disable=protected-access, no-self-use\n    def test_interruptable_dot(self):\n        dot = distance.distance._interruptible_dot\n        k, m, n = 20, 30, 40\n        a = np.random.randint(10, size=(m, n))\n        b = np.random.randint(10, size=(n, k))\n\n        c = dot(a, b, step=10)\n        np.testing.assert_array_equal(c, np.dot(a, b))\n\n    def test_interruptable_dot_list(self):\n        dot = distance.distance._interruptible_dot\n        a = [[1, 2, 3], [1, 2, 3]]\n        b = [3, 2, 1]\n        c = dot(a, b, step=10)\n        np.testing.assert_array_equal(c, np.dot(a, b))\n\n    def test_interruptable_dot_scalar(self):\n        dot = distance.distance._interruptible_dot\n        a = 2\n        b = 3\n        c = dot(a, b, step=10)\n        np.testing.assert_array_equal(c, np.dot(a, b))\n\n    def test_interruptable_sqrt(self):\n        sqrt_ = distance.distance._interruptible_sqrt\n        n = 100\n        a = np.random.randint(10, size=(n, n))\n\n        new_a = sqrt_(a, step=10)\n        np.testing.assert_array_equal(new_a, np.sqrt(a))\n\n    def test_interruptable_sqrt_list(self):\n        sqrt_ = distance.distance._interruptible_sqrt\n        l = [1, 2, 3]\n        new_l = sqrt_(l, step=10)\n        np.testing.assert_array_equal(new_l, np.sqrt(l))\n\n    def test_interruptable_sqrt_scalar(self):\n        sqrt_ = distance.distance._interruptible_sqrt\n        i = 9\n        new_i = sqrt_(i, step=10)\n        np.testing.assert_array_equal(new_i, np.sqrt(i))\n\n\nclass TestDataUtilities(unittest.TestCase):\n    def test_remove_discrete(self):\n        d1, d2, d3 = (DiscreteVariable(c, values=tuple(\"123\")) for c in \"abc\")\n        c1, c2 = (ContinuousVariable(c) for c in \"xy\")\n        t = StringVariable(\"t\")\n        domain = Domain([d1, c1], d2, [c2, d3, t])\n        data = Table.from_domain(domain, 5)\n\n        reduced = distance.remove_discrete_features(data)\n        self.assertEqual(reduced.domain.attributes, (c1, ))\n        self.assertEqual(reduced.domain.class_var, d2)\n        self.assertEqual(reduced.domain.metas, (c2, d3, t))\n\n        reduced = distance.remove_discrete_features(data, to_metas=True)\n        self.assertEqual(reduced.domain.attributes, (c1, ))\n        self.assertEqual(reduced.domain.class_var, d2)\n        self.assertEqual(reduced.domain.metas, (c2, d3, t, d1))\n\n    def test_remove_non_binary(self):\n        b1, b2, b3 = (DiscreteVariable(c, values=tuple(\"12\")) for c in \"abc\")\n        d1, d2, d3 = (DiscreteVariable(c, values=tuple(\"123\")) for c in \"def\")\n        c1, c2 = (ContinuousVariable(c) for c in \"xy\")\n        t = StringVariable(\"t\")\n        domain = Domain([d1, b1, b2, c1], d2, [c2, d3, t, b3])\n        data = Table.from_domain(domain, 5)\n\n        reduced = distance.remove_nonbinary_features(data)\n        self.assertEqual(reduced.domain.attributes, (b1, b2))\n        self.assertEqual(reduced.domain.class_var, d2)\n        self.assertEqual(reduced.domain.metas, (c2, d3, t, b3))\n\n        reduced = distance.remove_nonbinary_features(data, to_metas=True)\n        self.assertEqual(reduced.domain.attributes, (b1, b2))\n        self.assertEqual(reduced.domain.class_var, d2)\n        self.assertEqual(reduced.domain.metas, (c2, d3, t, b3, d1, c1))\n\n\nif __name__ == \"__main__\":\n    unittest.main()\n",
            "header": {
                "file": {
                    "path": "Orange/distance/tests/test_distance.py"
                },
                "misc_line": null
            },
            "index_line": {
                "old_commit_hash": "2ff10ce56",
                "new_commit_hash": "431635f57",
                "mode": "100644"
            },
            "is_binary_file": false,
            "binary_line": null,
            "minus_file": {
                "path": "a/Orange/distance/tests/test_distance.py"
            },
            "plus_file": {
                "path": "b/Orange/distance/tests/test_distance.py"
            },
            "hunks": [
                {
                    "descriptor": {
                        "old_range": {
                            "start": 5,
                            "length": 7
                        },
                        "new_range": {
                            "start": 5,
                            "length": 8
                        },
                        "section": "from math import sqrt"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "import numpy as np",
                                "type": "context"
                            },
                            {
                                "content": "from scipy.sparse import csr_matrix",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "from Orange.data import ContinuousVariable, DiscreteVariable, Domain, Table",
                                "type": "deleted"
                            },
                            {
                                "content": "from Orange.data import ContinuousVariable, DiscreteVariable, StringVariable,\\",
                                "type": "added"
                            },
                            {
                                "content": "    Domain, Table",
                                "type": "added"
                            },
                            {
                                "content": "from Orange import distance",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [],
                    "added_entities": [
                        {
                            "file_name": "Orange/distance/tests/test_distance.py",
                            "type": "statement",
                            "name": "",
                            "content": "from Orange.data import ContinuousVariable, DiscreteVariable, StringVariable,\\\n    Domain, Table",
                            "ast_type_str": "ImportFrom",
                            "start_lineno": 8,
                            "end_lineno": 9,
                            "parent": null
                        }
                    ],
                    "deleted_entities": [
                        {
                            "file_name": "Orange/distance/tests/test_distance.py",
                            "type": "statement",
                            "name": "",
                            "content": "from Orange.data import ContinuousVariable, DiscreteVariable, Domain, Table",
                            "ast_type_str": "ImportFrom",
                            "start_lineno": 8,
                            "end_lineno": 8,
                            "parent": null
                        }
                    ]
                },
                {
                    "descriptor": {
                        "old_range": {
                            "start": 863,
                            "length": 7
                        },
                        "new_range": {
                            "start": 864,
                            "length": 6
                        },
                        "section": "class JaccardDistanceTest(unittest.TestCase, CommonFittedTests):"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "        model = distance.Jaccard().fit(self.data)",
                                "type": "context"
                            },
                            {
                                "content": "        assert_almost_equal(model.ps, np.array([0.5, 2/3, 0.75]))",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "        # pylint: disable=bad-whitespace",
                                "type": "deleted"
                            },
                            {
                                "content": "        assert_almost_equal(",
                                "type": "context"
                            },
                            {
                                "content": "            model(self.data),",
                                "type": "context"
                            },
                            {
                                "content": "            1 - np.array([[      1,        2 / 2.5,        1 / 2.5,        2/3 / 3],",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [
                        {
                            "file_name": "Orange/distance/tests/test_distance.py",
                            "type": "method",
                            "name": "JaccardDistanceTest.test_jaccard_rows",
                            "content": "class JaccardDistanceTest(unittest.TestCase, CommonFittedTests):\n    Distance = distance.Jaccard\n\n    def setUp(self):\n        self.domain = Domain([DiscreteVariable(c) for c in \"abc\"])\n        self.data = Table.from_list(\n            self.domain,\n            [[0, 1, 1],\n             [1, 1, 1],\n             [1, 0, 1],\n             [1, 0, 0]])\n\n    def test_jaccard_rows(self):\n        assert_almost_equal = np.testing.assert_almost_equal\n\n        model = distance.Jaccard().fit(self.data)\n        assert_almost_equal(model.ps, [0.75, 0.5, 0.75])\n        assert_almost_equal(\n            model(self.data),\n            1 - np.array([[1, 2/3, 1/3, 0],\n                          [2/3, 1, 2/3, 1/3],\n                          [1/3, 2/3, 1, 1/2],\n                          [0, 1/3, 1/2, 1]]))\n\n        X = self.data.X\n        X[1, 0] = X[2, 0] = X[3, 1] = np.nan\n        model = distance.Jaccard().fit(self.data)\n        assert_almost_equal(model.ps, np.array([0.5, 2/3, 0.75]))\n\n        # pylint: disable=bad-whitespace\n        assert_almost_equal(\n            model(self.data),\n            1 - np.array([[      1,        2 / 2.5,        1 / 2.5,        2/3 / 3],\n                          [2 / 2.5,              1,    1.25 / 2.75,  (1/2+2/3) / 3],\n                          [1 / 2.5,    1.25 / 2.75,              1,  0.5 / (2+2/3)],\n                          [2/3 / 3,  (1/2+2/3) / 3,  0.5 / (2+2/3),            1]]))\n\n    def test_jaccard_cols(self):\n        assert_almost_equal = np.testing.assert_almost_equal\n        model = distance.Jaccard(axis=0).fit(self.data)\n        assert_almost_equal(model.ps, [0.75, 0.5, 0.75])\n        assert_almost_equal(\n            model(self.data),\n            1 - np.array([[1, 1/4, 1/2],\n                          [1/4, 1, 2/3],\n                          [1/2, 2/3, 1]]))\n\n        self.data.X = np.array([[0, 1, 1],\n                                [np.nan, np.nan, 1],\n                                [np.nan, 0, 1],\n                                [1, 1, 0]])\n        model = distance.Jaccard(axis=0).fit(self.data)\n        assert_almost_equal(model.ps, [0.5, 2/3, 0.75])\n        assert_almost_equal(\n            model(self.data),\n            1 - np.array([[1, 0.4, 0.25],\n                          [0.4, 1, 5/12],\n                          [0.25, 5/12, 1]]))\n\n    def test_zero_instances(self):\n        \"Test all zero instances\"\n        domain = Domain([ContinuousVariable(c) for c in \"abc\"])\n        dense_data = Table.from_list(\n            domain, [[0, 0, 0], [0, 0, 0], [0, 0, 1]])\n        sparse_data = Table(domain, csr_matrix(dense_data.X))\n        dist_dense = self.Distance(dense_data)\n        dist_sparse = self.Distance(sparse_data)\n\n        self.assertEqual(dist_dense[0][1], 0)\n        self.assertEqual(dist_sparse[0][1], 0)\n        self.assertEqual(dist_dense[0][2], 1)\n        self.assertEqual(dist_sparse[0][2], 1)",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 849,
                            "end_lineno": 872,
                            "parent": {
                                "file_name": "Orange/distance/tests/test_distance.py",
                                "type": "class",
                                "name": "JaccardDistanceTest",
                                "content": "class JaccardDistanceTest(unittest.TestCase, CommonFittedTests):\n    Distance = distance.Jaccard\n\n    def setUp(self):\n        self.domain = Domain([DiscreteVariable(c) for c in \"abc\"])\n        self.data = Table.from_list(\n            self.domain,\n            [[0, 1, 1],\n             [1, 1, 1],\n             [1, 0, 1],\n             [1, 0, 0]])\n\n    def test_jaccard_rows(self):\n        assert_almost_equal = np.testing.assert_almost_equal\n\n        model = distance.Jaccard().fit(self.data)\n        assert_almost_equal(model.ps, [0.75, 0.5, 0.75])\n        assert_almost_equal(\n            model(self.data),\n            1 - np.array([[1, 2/3, 1/3, 0],\n                          [2/3, 1, 2/3, 1/3],\n                          [1/3, 2/3, 1, 1/2],\n                          [0, 1/3, 1/2, 1]]))\n\n        X = self.data.X\n        X[1, 0] = X[2, 0] = X[3, 1] = np.nan\n        model = distance.Jaccard().fit(self.data)\n        assert_almost_equal(model.ps, np.array([0.5, 2/3, 0.75]))\n\n        # pylint: disable=bad-whitespace\n        assert_almost_equal(\n            model(self.data),\n            1 - np.array([[      1,        2 / 2.5,        1 / 2.5,        2/3 / 3],\n                          [2 / 2.5,              1,    1.25 / 2.75,  (1/2+2/3) / 3],\n                          [1 / 2.5,    1.25 / 2.75,              1,  0.5 / (2+2/3)],\n                          [2/3 / 3,  (1/2+2/3) / 3,  0.5 / (2+2/3),            1]]))\n\n    def test_jaccard_cols(self):\n        assert_almost_equal = np.testing.assert_almost_equal\n        model = distance.Jaccard(axis=0).fit(self.data)\n        assert_almost_equal(model.ps, [0.75, 0.5, 0.75])\n        assert_almost_equal(\n            model(self.data),\n            1 - np.array([[1, 1/4, 1/2],\n                          [1/4, 1, 2/3],\n                          [1/2, 2/3, 1]]))\n\n        self.data.X = np.array([[0, 1, 1],\n                                [np.nan, np.nan, 1],\n                                [np.nan, 0, 1],\n                                [1, 1, 0]])\n        model = distance.Jaccard(axis=0).fit(self.data)\n        assert_almost_equal(model.ps, [0.5, 2/3, 0.75])\n        assert_almost_equal(\n            model(self.data),\n            1 - np.array([[1, 0.4, 0.25],\n                          [0.4, 1, 5/12],\n                          [0.25, 5/12, 1]]))\n\n    def test_zero_instances(self):\n        \"Test all zero instances\"\n        domain = Domain([ContinuousVariable(c) for c in \"abc\"])\n        dense_data = Table.from_list(\n            domain, [[0, 0, 0], [0, 0, 0], [0, 0, 1]])\n        sparse_data = Table(domain, csr_matrix(dense_data.X))\n        dist_dense = self.Distance(dense_data)\n        dist_sparse = self.Distance(sparse_data)\n\n        self.assertEqual(dist_dense[0][1], 0)\n        self.assertEqual(dist_sparse[0][1], 0)\n        self.assertEqual(dist_dense[0][2], 1)\n        self.assertEqual(dist_sparse[0][2], 1)",
                                "ast_type_str": "ClassDef",
                                "start_lineno": 837,
                                "end_lineno": 908,
                                "parent": null
                            }
                        },
                        {
                            "file_name": "Orange/distance/tests/test_distance.py",
                            "type": "class",
                            "name": "JaccardDistanceTest",
                            "content": "class JaccardDistanceTest(unittest.TestCase, CommonFittedTests):\n    Distance = distance.Jaccard\n\n    def setUp(self):\n        self.domain = Domain([DiscreteVariable(c) for c in \"abc\"])\n        self.data = Table.from_list(\n            self.domain,\n            [[0, 1, 1],\n             [1, 1, 1],\n             [1, 0, 1],\n             [1, 0, 0]])\n\n    def test_jaccard_rows(self):\n        assert_almost_equal = np.testing.assert_almost_equal\n\n        model = distance.Jaccard().fit(self.data)\n        assert_almost_equal(model.ps, [0.75, 0.5, 0.75])\n        assert_almost_equal(\n            model(self.data),\n            1 - np.array([[1, 2/3, 1/3, 0],\n                          [2/3, 1, 2/3, 1/3],\n                          [1/3, 2/3, 1, 1/2],\n                          [0, 1/3, 1/2, 1]]))\n\n        X = self.data.X\n        X[1, 0] = X[2, 0] = X[3, 1] = np.nan\n        model = distance.Jaccard().fit(self.data)\n        assert_almost_equal(model.ps, np.array([0.5, 2/3, 0.75]))\n\n        # pylint: disable=bad-whitespace\n        assert_almost_equal(\n            model(self.data),\n            1 - np.array([[      1,        2 / 2.5,        1 / 2.5,        2/3 / 3],\n                          [2 / 2.5,              1,    1.25 / 2.75,  (1/2+2/3) / 3],\n                          [1 / 2.5,    1.25 / 2.75,              1,  0.5 / (2+2/3)],\n                          [2/3 / 3,  (1/2+2/3) / 3,  0.5 / (2+2/3),            1]]))\n\n    def test_jaccard_cols(self):\n        assert_almost_equal = np.testing.assert_almost_equal\n        model = distance.Jaccard(axis=0).fit(self.data)\n        assert_almost_equal(model.ps, [0.75, 0.5, 0.75])\n        assert_almost_equal(\n            model(self.data),\n            1 - np.array([[1, 1/4, 1/2],\n                          [1/4, 1, 2/3],\n                          [1/2, 2/3, 1]]))\n\n        self.data.X = np.array([[0, 1, 1],\n                                [np.nan, np.nan, 1],\n                                [np.nan, 0, 1],\n                                [1, 1, 0]])\n        model = distance.Jaccard(axis=0).fit(self.data)\n        assert_almost_equal(model.ps, [0.5, 2/3, 0.75])\n        assert_almost_equal(\n            model(self.data),\n            1 - np.array([[1, 0.4, 0.25],\n                          [0.4, 1, 5/12],\n                          [0.25, 5/12, 1]]))\n\n    def test_zero_instances(self):\n        \"Test all zero instances\"\n        domain = Domain([ContinuousVariable(c) for c in \"abc\"])\n        dense_data = Table.from_list(\n            domain, [[0, 0, 0], [0, 0, 0], [0, 0, 1]])\n        sparse_data = Table(domain, csr_matrix(dense_data.X))\n        dist_dense = self.Distance(dense_data)\n        dist_sparse = self.Distance(sparse_data)\n\n        self.assertEqual(dist_dense[0][1], 0)\n        self.assertEqual(dist_sparse[0][1], 0)\n        self.assertEqual(dist_dense[0][2], 1)\n        self.assertEqual(dist_sparse[0][2], 1)",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 837,
                            "end_lineno": 908,
                            "parent": null
                        }
                    ],
                    "added_entities": [],
                    "deleted_entities": []
                },
                {
                    "descriptor": {
                        "old_range": {
                            "start": 902,
                            "length": 6
                        },
                        "new_range": {
                            "start": 902,
                            "length": 7
                        },
                        "section": "class JaccardDistanceTest(unittest.TestCase, CommonFittedTests):"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "        dist_dense = self.Distance(dense_data)",
                                "type": "context"
                            },
                            {
                                "content": "        dist_sparse = self.Distance(sparse_data)",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "        # false positive, pylint: disable=unsubscriptable-object",
                                "type": "added"
                            },
                            {
                                "content": "        self.assertEqual(dist_dense[0][1], 0)",
                                "type": "context"
                            },
                            {
                                "content": "        self.assertEqual(dist_sparse[0][1], 0)",
                                "type": "context"
                            },
                            {
                                "content": "        self.assertEqual(dist_dense[0][2], 1)",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [
                        {
                            "file_name": "Orange/distance/tests/test_distance.py",
                            "type": "method",
                            "name": "JaccardDistanceTest.test_zero_instances",
                            "content": "class JaccardDistanceTest(unittest.TestCase, CommonFittedTests):\n    Distance = distance.Jaccard\n\n    def setUp(self):\n        self.domain = Domain([DiscreteVariable(c) for c in \"abc\"])\n        self.data = Table.from_list(\n            self.domain,\n            [[0, 1, 1],\n             [1, 1, 1],\n             [1, 0, 1],\n             [1, 0, 0]])\n\n    def test_jaccard_rows(self):\n        assert_almost_equal = np.testing.assert_almost_equal\n\n        model = distance.Jaccard().fit(self.data)\n        assert_almost_equal(model.ps, [0.75, 0.5, 0.75])\n        assert_almost_equal(\n            model(self.data),\n            1 - np.array([[1, 2/3, 1/3, 0],\n                          [2/3, 1, 2/3, 1/3],\n                          [1/3, 2/3, 1, 1/2],\n                          [0, 1/3, 1/2, 1]]))\n\n        X = self.data.X\n        X[1, 0] = X[2, 0] = X[3, 1] = np.nan\n        model = distance.Jaccard().fit(self.data)\n        assert_almost_equal(model.ps, np.array([0.5, 2/3, 0.75]))\n\n        assert_almost_equal(\n            model(self.data),\n            1 - np.array([[      1,        2 / 2.5,        1 / 2.5,        2/3 / 3],\n                          [2 / 2.5,              1,    1.25 / 2.75,  (1/2+2/3) / 3],\n                          [1 / 2.5,    1.25 / 2.75,              1,  0.5 / (2+2/3)],\n                          [2/3 / 3,  (1/2+2/3) / 3,  0.5 / (2+2/3),            1]]))\n\n    def test_jaccard_cols(self):\n        assert_almost_equal = np.testing.assert_almost_equal\n        model = distance.Jaccard(axis=0).fit(self.data)\n        assert_almost_equal(model.ps, [0.75, 0.5, 0.75])\n        assert_almost_equal(\n            model(self.data),\n            1 - np.array([[1, 1/4, 1/2],\n                          [1/4, 1, 2/3],\n                          [1/2, 2/3, 1]]))\n\n        self.data.X = np.array([[0, 1, 1],\n                                [np.nan, np.nan, 1],\n                                [np.nan, 0, 1],\n                                [1, 1, 0]])\n        model = distance.Jaccard(axis=0).fit(self.data)\n        assert_almost_equal(model.ps, [0.5, 2/3, 0.75])\n        assert_almost_equal(\n            model(self.data),\n            1 - np.array([[1, 0.4, 0.25],\n                          [0.4, 1, 5/12],\n                          [0.25, 5/12, 1]]))\n\n    def test_zero_instances(self):\n        \"Test all zero instances\"\n        domain = Domain([ContinuousVariable(c) for c in \"abc\"])\n        dense_data = Table.from_list(\n            domain, [[0, 0, 0], [0, 0, 0], [0, 0, 1]])\n        sparse_data = Table(domain, csr_matrix(dense_data.X))\n        dist_dense = self.Distance(dense_data)\n        dist_sparse = self.Distance(sparse_data)\n\n        # false positive, pylint: disable=unsubscriptable-object\n        self.assertEqual(dist_dense[0][1], 0)\n        self.assertEqual(dist_sparse[0][1], 0)\n        self.assertEqual(dist_dense[0][2], 1)\n        self.assertEqual(dist_sparse[0][2], 1)",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 896,
                            "end_lineno": 909,
                            "parent": {
                                "file_name": "Orange/distance/tests/test_distance.py",
                                "type": "class",
                                "name": "JaccardDistanceTest",
                                "content": "class JaccardDistanceTest(unittest.TestCase, CommonFittedTests):\n    Distance = distance.Jaccard\n\n    def setUp(self):\n        self.domain = Domain([DiscreteVariable(c) for c in \"abc\"])\n        self.data = Table.from_list(\n            self.domain,\n            [[0, 1, 1],\n             [1, 1, 1],\n             [1, 0, 1],\n             [1, 0, 0]])\n\n    def test_jaccard_rows(self):\n        assert_almost_equal = np.testing.assert_almost_equal\n\n        model = distance.Jaccard().fit(self.data)\n        assert_almost_equal(model.ps, [0.75, 0.5, 0.75])\n        assert_almost_equal(\n            model(self.data),\n            1 - np.array([[1, 2/3, 1/3, 0],\n                          [2/3, 1, 2/3, 1/3],\n                          [1/3, 2/3, 1, 1/2],\n                          [0, 1/3, 1/2, 1]]))\n\n        X = self.data.X\n        X[1, 0] = X[2, 0] = X[3, 1] = np.nan\n        model = distance.Jaccard().fit(self.data)\n        assert_almost_equal(model.ps, np.array([0.5, 2/3, 0.75]))\n\n        assert_almost_equal(\n            model(self.data),\n            1 - np.array([[      1,        2 / 2.5,        1 / 2.5,        2/3 / 3],\n                          [2 / 2.5,              1,    1.25 / 2.75,  (1/2+2/3) / 3],\n                          [1 / 2.5,    1.25 / 2.75,              1,  0.5 / (2+2/3)],\n                          [2/3 / 3,  (1/2+2/3) / 3,  0.5 / (2+2/3),            1]]))\n\n    def test_jaccard_cols(self):\n        assert_almost_equal = np.testing.assert_almost_equal\n        model = distance.Jaccard(axis=0).fit(self.data)\n        assert_almost_equal(model.ps, [0.75, 0.5, 0.75])\n        assert_almost_equal(\n            model(self.data),\n            1 - np.array([[1, 1/4, 1/2],\n                          [1/4, 1, 2/3],\n                          [1/2, 2/3, 1]]))\n\n        self.data.X = np.array([[0, 1, 1],\n                                [np.nan, np.nan, 1],\n                                [np.nan, 0, 1],\n                                [1, 1, 0]])\n        model = distance.Jaccard(axis=0).fit(self.data)\n        assert_almost_equal(model.ps, [0.5, 2/3, 0.75])\n        assert_almost_equal(\n            model(self.data),\n            1 - np.array([[1, 0.4, 0.25],\n                          [0.4, 1, 5/12],\n                          [0.25, 5/12, 1]]))\n\n    def test_zero_instances(self):\n        \"Test all zero instances\"\n        domain = Domain([ContinuousVariable(c) for c in \"abc\"])\n        dense_data = Table.from_list(\n            domain, [[0, 0, 0], [0, 0, 0], [0, 0, 1]])\n        sparse_data = Table(domain, csr_matrix(dense_data.X))\n        dist_dense = self.Distance(dense_data)\n        dist_sparse = self.Distance(sparse_data)\n\n        # false positive, pylint: disable=unsubscriptable-object\n        self.assertEqual(dist_dense[0][1], 0)\n        self.assertEqual(dist_sparse[0][1], 0)\n        self.assertEqual(dist_dense[0][2], 1)\n        self.assertEqual(dist_sparse[0][2], 1)",
                                "ast_type_str": "ClassDef",
                                "start_lineno": 838,
                                "end_lineno": 909,
                                "parent": null
                            }
                        },
                        {
                            "file_name": "Orange/distance/tests/test_distance.py",
                            "type": "class",
                            "name": "JaccardDistanceTest",
                            "content": "class JaccardDistanceTest(unittest.TestCase, CommonFittedTests):\n    Distance = distance.Jaccard\n\n    def setUp(self):\n        self.domain = Domain([DiscreteVariable(c) for c in \"abc\"])\n        self.data = Table.from_list(\n            self.domain,\n            [[0, 1, 1],\n             [1, 1, 1],\n             [1, 0, 1],\n             [1, 0, 0]])\n\n    def test_jaccard_rows(self):\n        assert_almost_equal = np.testing.assert_almost_equal\n\n        model = distance.Jaccard().fit(self.data)\n        assert_almost_equal(model.ps, [0.75, 0.5, 0.75])\n        assert_almost_equal(\n            model(self.data),\n            1 - np.array([[1, 2/3, 1/3, 0],\n                          [2/3, 1, 2/3, 1/3],\n                          [1/3, 2/3, 1, 1/2],\n                          [0, 1/3, 1/2, 1]]))\n\n        X = self.data.X\n        X[1, 0] = X[2, 0] = X[3, 1] = np.nan\n        model = distance.Jaccard().fit(self.data)\n        assert_almost_equal(model.ps, np.array([0.5, 2/3, 0.75]))\n\n        assert_almost_equal(\n            model(self.data),\n            1 - np.array([[      1,        2 / 2.5,        1 / 2.5,        2/3 / 3],\n                          [2 / 2.5,              1,    1.25 / 2.75,  (1/2+2/3) / 3],\n                          [1 / 2.5,    1.25 / 2.75,              1,  0.5 / (2+2/3)],\n                          [2/3 / 3,  (1/2+2/3) / 3,  0.5 / (2+2/3),            1]]))\n\n    def test_jaccard_cols(self):\n        assert_almost_equal = np.testing.assert_almost_equal\n        model = distance.Jaccard(axis=0).fit(self.data)\n        assert_almost_equal(model.ps, [0.75, 0.5, 0.75])\n        assert_almost_equal(\n            model(self.data),\n            1 - np.array([[1, 1/4, 1/2],\n                          [1/4, 1, 2/3],\n                          [1/2, 2/3, 1]]))\n\n        self.data.X = np.array([[0, 1, 1],\n                                [np.nan, np.nan, 1],\n                                [np.nan, 0, 1],\n                                [1, 1, 0]])\n        model = distance.Jaccard(axis=0).fit(self.data)\n        assert_almost_equal(model.ps, [0.5, 2/3, 0.75])\n        assert_almost_equal(\n            model(self.data),\n            1 - np.array([[1, 0.4, 0.25],\n                          [0.4, 1, 5/12],\n                          [0.25, 5/12, 1]]))\n\n    def test_zero_instances(self):\n        \"Test all zero instances\"\n        domain = Domain([ContinuousVariable(c) for c in \"abc\"])\n        dense_data = Table.from_list(\n            domain, [[0, 0, 0], [0, 0, 0], [0, 0, 1]])\n        sparse_data = Table(domain, csr_matrix(dense_data.X))\n        dist_dense = self.Distance(dense_data)\n        dist_sparse = self.Distance(sparse_data)\n\n        # false positive, pylint: disable=unsubscriptable-object\n        self.assertEqual(dist_dense[0][1], 0)\n        self.assertEqual(dist_sparse[0][1], 0)\n        self.assertEqual(dist_dense[0][2], 1)\n        self.assertEqual(dist_sparse[0][2], 1)",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 838,
                            "end_lineno": 909,
                            "parent": null
                        }
                    ],
                    "added_entities": [],
                    "deleted_entities": []
                },
                {
                    "descriptor": {
                        "old_range": {
                            "start": 980,
                            "length": 5
                        },
                        "new_range": {
                            "start": 981,
                            "length": 42
                        },
                        "section": "class TestHelperFunctions(unittest.TestCase):"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "        np.testing.assert_array_equal(new_i, np.sqrt(i))",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "class TestDataUtilities(unittest.TestCase):",
                                "type": "added"
                            },
                            {
                                "content": "    def test_remove_discrete(self):",
                                "type": "added"
                            },
                            {
                                "content": "        d1, d2, d3 = (DiscreteVariable(c, values=tuple(\"123\")) for c in \"abc\")",
                                "type": "added"
                            },
                            {
                                "content": "        c1, c2 = (ContinuousVariable(c) for c in \"xy\")",
                                "type": "added"
                            },
                            {
                                "content": "        t = StringVariable(\"t\")",
                                "type": "added"
                            },
                            {
                                "content": "        domain = Domain([d1, c1], d2, [c2, d3, t])",
                                "type": "added"
                            },
                            {
                                "content": "        data = Table.from_domain(domain, 5)",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "        reduced = distance.remove_discrete_features(data)",
                                "type": "added"
                            },
                            {
                                "content": "        self.assertEqual(reduced.domain.attributes, (c1, ))",
                                "type": "added"
                            },
                            {
                                "content": "        self.assertEqual(reduced.domain.class_var, d2)",
                                "type": "added"
                            },
                            {
                                "content": "        self.assertEqual(reduced.domain.metas, (c2, d3, t))",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "        reduced = distance.remove_discrete_features(data, to_metas=True)",
                                "type": "added"
                            },
                            {
                                "content": "        self.assertEqual(reduced.domain.attributes, (c1, ))",
                                "type": "added"
                            },
                            {
                                "content": "        self.assertEqual(reduced.domain.class_var, d2)",
                                "type": "added"
                            },
                            {
                                "content": "        self.assertEqual(reduced.domain.metas, (c2, d3, t, d1))",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "    def test_remove_non_binary(self):",
                                "type": "added"
                            },
                            {
                                "content": "        b1, b2, b3 = (DiscreteVariable(c, values=tuple(\"12\")) for c in \"abc\")",
                                "type": "added"
                            },
                            {
                                "content": "        d1, d2, d3 = (DiscreteVariable(c, values=tuple(\"123\")) for c in \"def\")",
                                "type": "added"
                            },
                            {
                                "content": "        c1, c2 = (ContinuousVariable(c) for c in \"xy\")",
                                "type": "added"
                            },
                            {
                                "content": "        t = StringVariable(\"t\")",
                                "type": "added"
                            },
                            {
                                "content": "        domain = Domain([d1, b1, b2, c1], d2, [c2, d3, t, b3])",
                                "type": "added"
                            },
                            {
                                "content": "        data = Table.from_domain(domain, 5)",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "        reduced = distance.remove_nonbinary_features(data)",
                                "type": "added"
                            },
                            {
                                "content": "        self.assertEqual(reduced.domain.attributes, (b1, b2))",
                                "type": "added"
                            },
                            {
                                "content": "        self.assertEqual(reduced.domain.class_var, d2)",
                                "type": "added"
                            },
                            {
                                "content": "        self.assertEqual(reduced.domain.metas, (c2, d3, t, b3))",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "        reduced = distance.remove_nonbinary_features(data, to_metas=True)",
                                "type": "added"
                            },
                            {
                                "content": "        self.assertEqual(reduced.domain.attributes, (b1, b2))",
                                "type": "added"
                            },
                            {
                                "content": "        self.assertEqual(reduced.domain.class_var, d2)",
                                "type": "added"
                            },
                            {
                                "content": "        self.assertEqual(reduced.domain.metas, (c2, d3, t, b3, d1, c1))",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "if __name__ == \"__main__\":",
                                "type": "context"
                            },
                            {
                                "content": "    unittest.main()",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [],
                    "added_entities": [
                        {
                            "file_name": "Orange/distance/tests/test_distance.py",
                            "type": "class",
                            "name": "TestDataUtilities",
                            "content": "class TestDataUtilities(unittest.TestCase):\n    def test_remove_discrete(self):\n        d1, d2, d3 = (DiscreteVariable(c, values=tuple(\"123\")) for c in \"abc\")\n        c1, c2 = (ContinuousVariable(c) for c in \"xy\")\n        t = StringVariable(\"t\")\n        domain = Domain([d1, c1], d2, [c2, d3, t])\n        data = Table.from_domain(domain, 5)\n\n        reduced = distance.remove_discrete_features(data)\n        self.assertEqual(reduced.domain.attributes, (c1, ))\n        self.assertEqual(reduced.domain.class_var, d2)\n        self.assertEqual(reduced.domain.metas, (c2, d3, t))\n\n        reduced = distance.remove_discrete_features(data, to_metas=True)\n        self.assertEqual(reduced.domain.attributes, (c1, ))\n        self.assertEqual(reduced.domain.class_var, d2)\n        self.assertEqual(reduced.domain.metas, (c2, d3, t, d1))\n\n    def test_remove_non_binary(self):\n        b1, b2, b3 = (DiscreteVariable(c, values=tuple(\"12\")) for c in \"abc\")\n        d1, d2, d3 = (DiscreteVariable(c, values=tuple(\"123\")) for c in \"def\")\n        c1, c2 = (ContinuousVariable(c) for c in \"xy\")\n        t = StringVariable(\"t\")\n        domain = Domain([d1, b1, b2, c1], d2, [c2, d3, t, b3])\n        data = Table.from_domain(domain, 5)\n\n        reduced = distance.remove_nonbinary_features(data)\n        self.assertEqual(reduced.domain.attributes, (b1, b2))\n        self.assertEqual(reduced.domain.class_var, d2)\n        self.assertEqual(reduced.domain.metas, (c2, d3, t, b3))\n\n        reduced = distance.remove_nonbinary_features(data, to_metas=True)\n        self.assertEqual(reduced.domain.attributes, (b1, b2))\n        self.assertEqual(reduced.domain.class_var, d2)\n        self.assertEqual(reduced.domain.metas, (c2, d3, t, b3, d1, c1))",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 984,
                            "end_lineno": 1018,
                            "parent": null
                        },
                        {
                            "file_name": "Orange/distance/tests/test_distance.py",
                            "type": "method",
                            "name": "TestDataUtilities.test_remove_discrete",
                            "content": "class TestDataUtilities(unittest.TestCase):\n    def test_remove_discrete(self):\n        d1, d2, d3 = (DiscreteVariable(c, values=tuple(\"123\")) for c in \"abc\")\n        c1, c2 = (ContinuousVariable(c) for c in \"xy\")\n        t = StringVariable(\"t\")\n        domain = Domain([d1, c1], d2, [c2, d3, t])\n        data = Table.from_domain(domain, 5)\n\n        reduced = distance.remove_discrete_features(data)\n        self.assertEqual(reduced.domain.attributes, (c1, ))\n        self.assertEqual(reduced.domain.class_var, d2)\n        self.assertEqual(reduced.domain.metas, (c2, d3, t))\n\n        reduced = distance.remove_discrete_features(data, to_metas=True)\n        self.assertEqual(reduced.domain.attributes, (c1, ))\n        self.assertEqual(reduced.domain.class_var, d2)\n        self.assertEqual(reduced.domain.metas, (c2, d3, t, d1))\n\n    def test_remove_non_binary(self):\n        b1, b2, b3 = (DiscreteVariable(c, values=tuple(\"12\")) for c in \"abc\")\n        d1, d2, d3 = (DiscreteVariable(c, values=tuple(\"123\")) for c in \"def\")\n        c1, c2 = (ContinuousVariable(c) for c in \"xy\")\n        t = StringVariable(\"t\")\n        domain = Domain([d1, b1, b2, c1], d2, [c2, d3, t, b3])\n        data = Table.from_domain(domain, 5)\n\n        reduced = distance.remove_nonbinary_features(data)\n        self.assertEqual(reduced.domain.attributes, (b1, b2))\n        self.assertEqual(reduced.domain.class_var, d2)\n        self.assertEqual(reduced.domain.metas, (c2, d3, t, b3))\n\n        reduced = distance.remove_nonbinary_features(data, to_metas=True)\n        self.assertEqual(reduced.domain.attributes, (b1, b2))\n        self.assertEqual(reduced.domain.class_var, d2)\n        self.assertEqual(reduced.domain.metas, (c2, d3, t, b3, d1, c1))",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 985,
                            "end_lineno": 1000,
                            "parent": {
                                "file_name": "Orange/distance/tests/test_distance.py",
                                "type": "class",
                                "name": "TestDataUtilities",
                                "content": "class TestDataUtilities(unittest.TestCase):\n    def test_remove_discrete(self):\n        d1, d2, d3 = (DiscreteVariable(c, values=tuple(\"123\")) for c in \"abc\")\n        c1, c2 = (ContinuousVariable(c) for c in \"xy\")\n        t = StringVariable(\"t\")\n        domain = Domain([d1, c1], d2, [c2, d3, t])\n        data = Table.from_domain(domain, 5)\n\n        reduced = distance.remove_discrete_features(data)\n        self.assertEqual(reduced.domain.attributes, (c1, ))\n        self.assertEqual(reduced.domain.class_var, d2)\n        self.assertEqual(reduced.domain.metas, (c2, d3, t))\n\n        reduced = distance.remove_discrete_features(data, to_metas=True)\n        self.assertEqual(reduced.domain.attributes, (c1, ))\n        self.assertEqual(reduced.domain.class_var, d2)\n        self.assertEqual(reduced.domain.metas, (c2, d3, t, d1))\n\n    def test_remove_non_binary(self):\n        b1, b2, b3 = (DiscreteVariable(c, values=tuple(\"12\")) for c in \"abc\")\n        d1, d2, d3 = (DiscreteVariable(c, values=tuple(\"123\")) for c in \"def\")\n        c1, c2 = (ContinuousVariable(c) for c in \"xy\")\n        t = StringVariable(\"t\")\n        domain = Domain([d1, b1, b2, c1], d2, [c2, d3, t, b3])\n        data = Table.from_domain(domain, 5)\n\n        reduced = distance.remove_nonbinary_features(data)\n        self.assertEqual(reduced.domain.attributes, (b1, b2))\n        self.assertEqual(reduced.domain.class_var, d2)\n        self.assertEqual(reduced.domain.metas, (c2, d3, t, b3))\n\n        reduced = distance.remove_nonbinary_features(data, to_metas=True)\n        self.assertEqual(reduced.domain.attributes, (b1, b2))\n        self.assertEqual(reduced.domain.class_var, d2)\n        self.assertEqual(reduced.domain.metas, (c2, d3, t, b3, d1, c1))",
                                "ast_type_str": "ClassDef",
                                "start_lineno": 984,
                                "end_lineno": 1018,
                                "parent": null
                            }
                        },
                        {
                            "file_name": "Orange/distance/tests/test_distance.py",
                            "type": "method",
                            "name": "TestDataUtilities.test_remove_non_binary",
                            "content": "class TestDataUtilities(unittest.TestCase):\n    def test_remove_discrete(self):\n        d1, d2, d3 = (DiscreteVariable(c, values=tuple(\"123\")) for c in \"abc\")\n        c1, c2 = (ContinuousVariable(c) for c in \"xy\")\n        t = StringVariable(\"t\")\n        domain = Domain([d1, c1], d2, [c2, d3, t])\n        data = Table.from_domain(domain, 5)\n\n        reduced = distance.remove_discrete_features(data)\n        self.assertEqual(reduced.domain.attributes, (c1, ))\n        self.assertEqual(reduced.domain.class_var, d2)\n        self.assertEqual(reduced.domain.metas, (c2, d3, t))\n\n        reduced = distance.remove_discrete_features(data, to_metas=True)\n        self.assertEqual(reduced.domain.attributes, (c1, ))\n        self.assertEqual(reduced.domain.class_var, d2)\n        self.assertEqual(reduced.domain.metas, (c2, d3, t, d1))\n\n    def test_remove_non_binary(self):\n        b1, b2, b3 = (DiscreteVariable(c, values=tuple(\"12\")) for c in \"abc\")\n        d1, d2, d3 = (DiscreteVariable(c, values=tuple(\"123\")) for c in \"def\")\n        c1, c2 = (ContinuousVariable(c) for c in \"xy\")\n        t = StringVariable(\"t\")\n        domain = Domain([d1, b1, b2, c1], d2, [c2, d3, t, b3])\n        data = Table.from_domain(domain, 5)\n\n        reduced = distance.remove_nonbinary_features(data)\n        self.assertEqual(reduced.domain.attributes, (b1, b2))\n        self.assertEqual(reduced.domain.class_var, d2)\n        self.assertEqual(reduced.domain.metas, (c2, d3, t, b3))\n\n        reduced = distance.remove_nonbinary_features(data, to_metas=True)\n        self.assertEqual(reduced.domain.attributes, (b1, b2))\n        self.assertEqual(reduced.domain.class_var, d2)\n        self.assertEqual(reduced.domain.metas, (c2, d3, t, b3, d1, c1))",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 1002,
                            "end_lineno": 1018,
                            "parent": {
                                "file_name": "Orange/distance/tests/test_distance.py",
                                "type": "class",
                                "name": "TestDataUtilities",
                                "content": "class TestDataUtilities(unittest.TestCase):\n    def test_remove_discrete(self):\n        d1, d2, d3 = (DiscreteVariable(c, values=tuple(\"123\")) for c in \"abc\")\n        c1, c2 = (ContinuousVariable(c) for c in \"xy\")\n        t = StringVariable(\"t\")\n        domain = Domain([d1, c1], d2, [c2, d3, t])\n        data = Table.from_domain(domain, 5)\n\n        reduced = distance.remove_discrete_features(data)\n        self.assertEqual(reduced.domain.attributes, (c1, ))\n        self.assertEqual(reduced.domain.class_var, d2)\n        self.assertEqual(reduced.domain.metas, (c2, d3, t))\n\n        reduced = distance.remove_discrete_features(data, to_metas=True)\n        self.assertEqual(reduced.domain.attributes, (c1, ))\n        self.assertEqual(reduced.domain.class_var, d2)\n        self.assertEqual(reduced.domain.metas, (c2, d3, t, d1))\n\n    def test_remove_non_binary(self):\n        b1, b2, b3 = (DiscreteVariable(c, values=tuple(\"12\")) for c in \"abc\")\n        d1, d2, d3 = (DiscreteVariable(c, values=tuple(\"123\")) for c in \"def\")\n        c1, c2 = (ContinuousVariable(c) for c in \"xy\")\n        t = StringVariable(\"t\")\n        domain = Domain([d1, b1, b2, c1], d2, [c2, d3, t, b3])\n        data = Table.from_domain(domain, 5)\n\n        reduced = distance.remove_nonbinary_features(data)\n        self.assertEqual(reduced.domain.attributes, (b1, b2))\n        self.assertEqual(reduced.domain.class_var, d2)\n        self.assertEqual(reduced.domain.metas, (c2, d3, t, b3))\n\n        reduced = distance.remove_nonbinary_features(data, to_metas=True)\n        self.assertEqual(reduced.domain.attributes, (b1, b2))\n        self.assertEqual(reduced.domain.class_var, d2)\n        self.assertEqual(reduced.domain.metas, (c2, d3, t, b3, d1, c1))",
                                "ast_type_str": "ClassDef",
                                "start_lineno": 984,
                                "end_lineno": 1018,
                                "parent": null
                            }
                        }
                    ],
                    "deleted_entities": []
                }
            ]
        },
        {
            "old_file_content": "from scipy.sparse import issparse\nimport bottleneck as bn\n\nfrom AnyQt.QtCore import Qt\n\nimport Orange.data\nimport Orange.misc\nfrom Orange import distance\nfrom Orange.widgets import gui\nfrom Orange.widgets.settings import Setting\nfrom Orange.widgets.utils.concurrent import TaskState, ConcurrentWidgetMixin\nfrom Orange.widgets.utils.sql import check_sql_input\nfrom Orange.widgets.utils.widgetpreview import WidgetPreview\nfrom Orange.widgets.widget import OWWidget, Msg, Input, Output\n\n\nMETRICS = [\n    (\"Euclidean\", distance.Euclidean),\n    (\"Manhattan\", distance.Manhattan),\n    (\"Cosine\", distance.Cosine),\n    (\"Jaccard\", distance.Jaccard),\n    (\"Spearman\", distance.SpearmanR),\n    (\"Absolute Spearman\", distance.SpearmanRAbsolute),\n    (\"Pearson\", distance.PearsonR),\n    (\"Absolute Pearson\", distance.PearsonRAbsolute),\n    (\"Hamming\", distance.Hamming),\n    (\"Mahalanobis\", distance.Mahalanobis),\n    ('Bhattacharyya', distance.Bhattacharyya)\n]\n\n\nclass InterruptException(Exception):\n    pass\n\n\nclass DistanceRunner:\n    @staticmethod\n    def run(data: Orange.data.Table, metric: distance, normalized_dist: bool,\n            axis: int, state: TaskState) -> Orange.misc.DistMatrix:\n        if data is None:\n            return None\n\n        def callback(i: float) -> bool:\n            state.set_progress_value(i)\n            if state.is_interruption_requested():\n                raise InterruptException\n\n        state.set_status(\"Calculating...\")\n        kwargs = {\"axis\": 1 - axis, \"impute\": True, \"callback\": callback}\n        if metric.supports_normalization and normalized_dist:\n            kwargs[\"normalize\"] = True\n        return metric(data, **kwargs)\n\n\nclass OWDistances(OWWidget, ConcurrentWidgetMixin):\n    name = \"Distances\"\n    description = \"Compute a matrix of pairwise distances.\"\n    icon = \"icons/Distance.svg\"\n    keywords = []\n\n    class Inputs:\n        data = Input(\"Data\", Orange.data.Table)\n\n    class Outputs:\n        distances = Output(\"Distances\", Orange.misc.DistMatrix, dynamic=False)\n\n    settings_version = 3\n\n    axis = Setting(0)        # type: int\n    metric_idx = Setting(0)  # type: int\n\n    #: Use normalized distances if the metric supports it.\n    #: The default is `True`, expect when restoring from old pre v2 settings\n    #: (see `migrate_settings`).\n    normalized_dist = Setting(True)  # type: bool\n    autocommit = Setting(True)       # type: bool\n\n    want_main_area = False\n    resizing_enabled = False\n\n    class Error(OWWidget.Error):\n        no_continuous_features = Msg(\"No numeric features\")\n        no_binary_features = Msg(\"No binary features\")\n        dense_metric_sparse_data = Msg(\"{} requires dense data.\")\n        distances_memory_error = Msg(\"Not enough memory\")\n        distances_value_error = Msg(\"Problem in calculation:\\n{}\")\n        data_too_large_for_mahalanobis = Msg(\n            \"Mahalanobis handles up to 1000 {}.\")\n\n    class Warning(OWWidget.Warning):\n        ignoring_discrete = Msg(\"Ignoring categorical features\")\n        ignoring_nonbinary = Msg(\"Ignoring non-binary features\")\n        imputing_data = Msg(\"Missing values were imputed\")\n\n    def __init__(self):\n        OWWidget.__init__(self)\n        ConcurrentWidgetMixin.__init__(self)\n\n        self.data = None\n\n        gui.radioButtons(\n            self.controlArea, self, \"axis\", [\"Rows\", \"Columns\"],\n            box=\"Distances between\", callback=self._invalidate\n        )\n        box = gui.widgetBox(self.controlArea, \"Distance Metric\")\n        self.metrics_combo = gui.comboBox(\n            box, self, \"metric_idx\",\n            items=[m[0] for m in METRICS],\n            callback=self._metric_changed\n        )\n        self.normalization_check = gui.checkBox(\n            box, self, \"normalized_dist\", \"Normalized\",\n            callback=self._invalidate,\n            tooltip=(\"All dimensions are (implicitly) scaled to a common\"\n                     \"scale to normalize the influence across the domain.\"),\n            stateWhenDisabled=False, attribute=Qt.WA_LayoutUsesWidgetRect\n        )\n        _, metric = METRICS[self.metric_idx]\n        self.normalization_check.setEnabled(metric.supports_normalization)\n\n        gui.auto_apply(self.buttonsArea, self, \"autocommit\")\n\n    @Inputs.data\n    @check_sql_input\n    def set_data(self, data):\n        self.cancel()\n        self.data = data\n        self.refresh_metrics()\n        self.unconditional_commit()\n\n    def refresh_metrics(self):\n        sparse = self.data is not None and issparse(self.data.X)\n        for i, metric in enumerate(METRICS):\n            item = self.metrics_combo.model().item(i)\n            item.setEnabled(not sparse or metric[1].supports_sparse)\n\n    def commit(self):\n        # pylint: disable=invalid-sequence-index\n        metric = METRICS[self.metric_idx][1]\n        self.compute_distances(metric, self.data)\n\n    def compute_distances(self, metric, data):\n        def _check_sparse():\n            # pylint: disable=invalid-sequence-index\n            if issparse(data.X) and not metric.supports_sparse:\n                self.Error.dense_metric_sparse_data(METRICS[self.metric_idx][0])\n                return False\n            return True\n\n        def _fix_discrete():\n            nonlocal data\n            if data.domain.has_discrete_attributes() \\\n                    and metric is not distance.Jaccard \\\n                    and (issparse(data.X) and getattr(metric, \"fallback\", None)\n                         or not metric.supports_discrete\n                         or self.axis == 1):\n                if not data.domain.has_continuous_attributes():\n                    self.Error.no_continuous_features()\n                    return False\n                self.Warning.ignoring_discrete()\n                data = distance.remove_discrete_features(data)\n            return True\n\n        def _fix_nonbinary():\n            nonlocal data\n            if metric is distance.Jaccard and not issparse(data.X):\n                nbinary = sum(a.is_discrete and len(a.values) == 2\n                              for a in data.domain.attributes)\n                if not nbinary:\n                    self.Error.no_binary_features()\n                    return False\n                elif nbinary < len(data.domain.attributes):\n                    self.Warning.ignoring_nonbinary()\n                    data = distance.remove_nonbinary_features(data)\n            return True\n\n        def _fix_missing():\n            nonlocal data\n            if not metric.supports_missing and bn.anynan(data.X):\n                self.Warning.imputing_data()\n                data = distance.impute(data)\n            return True\n\n        def _check_tractability():\n            if metric is distance.Mahalanobis:\n                if self.axis == 1:\n                    # when computing distances by columns, we want < 100 rows\n                    if len(data) > 1000:\n                        self.Error.data_too_large_for_mahalanobis(\"rows\")\n                        return False\n                else:\n                    if len(data.domain.attributes) > 1000:\n                        self.Error.data_too_large_for_mahalanobis(\"columns\")\n                        return False\n            return True\n\n        self.clear_messages()\n        if data is not None:\n            for check in (_check_sparse, _check_tractability,\n                          _fix_discrete, _fix_missing, _fix_nonbinary):\n                if not check():\n                    data = None\n                    break\n\n        self.start(DistanceRunner.run, data, metric,\n                   self.normalized_dist, self.axis)\n\n    def on_partial_result(self, _):\n        pass\n\n    def on_done(self, result: Orange.misc.DistMatrix):\n        assert isinstance(result, Orange.misc.DistMatrix) or result is None\n        self.Outputs.distances.send(result)\n\n    def on_exception(self, ex):\n        if isinstance(ex, ValueError):\n            self.Error.distances_value_error(ex)\n        elif isinstance(ex, MemoryError):\n            self.Error.distances_memory_error()\n        elif isinstance(ex, InterruptException):\n            pass\n        else:\n            raise ex\n\n    def onDeleteWidget(self):\n        self.shutdown()\n        super().onDeleteWidget()\n\n    def _invalidate(self):\n        self.commit()\n\n    def _metric_changed(self):\n        metric = METRICS[self.metric_idx][1]\n        self.normalization_check.setEnabled(metric.supports_normalization)\n        self._invalidate()\n\n    def send_report(self):\n        # pylint: disable=invalid-sequence-index\n        self.report_items((\n            (\"Distances Between\", [\"Rows\", \"Columns\"][self.axis]),\n            (\"Metric\", METRICS[self.metric_idx][0])\n        ))\n\n    @classmethod\n    def migrate_settings(cls, settings, version):\n        if version is None or version < 2 and \"normalized_dist\" not in settings:\n            # normalize_dist is set to False when restoring settings from\n            # an older version to preserve old semantics.\n            settings[\"normalized_dist\"] = False\n        if version is None or version < 3:\n            # Mahalanobis was moved from idx = 2 to idx = 9\n            metric_idx = settings[\"metric_idx\"]\n            if metric_idx == 2:\n                settings[\"metric_idx\"] = 9\n            elif 2 < metric_idx <= 9:\n                settings[\"metric_idx\"] -= 1\n\n\nif __name__ == \"__main__\":  # pragma: no cover\n    WidgetPreview(OWDistances).run(Orange.data.Table(\"iris\"))\n",
            "new_file_content": "from scipy.sparse import issparse\nimport bottleneck as bn\n\nfrom AnyQt.QtCore import Qt\n\nimport Orange.data\nimport Orange.misc\nfrom Orange import distance\nfrom Orange.widgets import gui\nfrom Orange.widgets.settings import Setting\nfrom Orange.widgets.utils.concurrent import TaskState, ConcurrentWidgetMixin\nfrom Orange.widgets.utils.sql import check_sql_input\nfrom Orange.widgets.utils.widgetpreview import WidgetPreview\nfrom Orange.widgets.widget import OWWidget, Msg, Input, Output\n\n\nMETRICS = [\n    (\"Euclidean\", distance.Euclidean),\n    (\"Manhattan\", distance.Manhattan),\n    (\"Cosine\", distance.Cosine),\n    (\"Jaccard\", distance.Jaccard),\n    (\"Spearman\", distance.SpearmanR),\n    (\"Absolute Spearman\", distance.SpearmanRAbsolute),\n    (\"Pearson\", distance.PearsonR),\n    (\"Absolute Pearson\", distance.PearsonRAbsolute),\n    (\"Hamming\", distance.Hamming),\n    (\"Mahalanobis\", distance.Mahalanobis),\n    ('Bhattacharyya', distance.Bhattacharyya)\n]\n\n\nclass InterruptException(Exception):\n    pass\n\n\nclass DistanceRunner:\n    @staticmethod\n    def run(data: Orange.data.Table, metric: distance, normalized_dist: bool,\n            axis: int, state: TaskState) -> Orange.misc.DistMatrix:\n        if data is None:\n            return None\n\n        def callback(i: float) -> bool:\n            state.set_progress_value(i)\n            if state.is_interruption_requested():\n                raise InterruptException\n\n        state.set_status(\"Calculating...\")\n        kwargs = {\"axis\": 1 - axis, \"impute\": True, \"callback\": callback}\n        if metric.supports_normalization and normalized_dist:\n            kwargs[\"normalize\"] = True\n        return metric(data, **kwargs)\n\n\nclass OWDistances(OWWidget, ConcurrentWidgetMixin):\n    name = \"Distances\"\n    description = \"Compute a matrix of pairwise distances.\"\n    icon = \"icons/Distance.svg\"\n    keywords = []\n\n    class Inputs:\n        data = Input(\"Data\", Orange.data.Table)\n\n    class Outputs:\n        distances = Output(\"Distances\", Orange.misc.DistMatrix, dynamic=False)\n\n    settings_version = 3\n\n    axis = Setting(0)        # type: int\n    metric_idx = Setting(0)  # type: int\n\n    #: Use normalized distances if the metric supports it.\n    #: The default is `True`, expect when restoring from old pre v2 settings\n    #: (see `migrate_settings`).\n    normalized_dist = Setting(True)  # type: bool\n    autocommit = Setting(True)       # type: bool\n\n    want_main_area = False\n    resizing_enabled = False\n\n    class Error(OWWidget.Error):\n        no_continuous_features = Msg(\"No numeric features\")\n        no_binary_features = Msg(\"No binary features\")\n        dense_metric_sparse_data = Msg(\"{} requires dense data.\")\n        distances_memory_error = Msg(\"Not enough memory\")\n        distances_value_error = Msg(\"Problem in calculation:\\n{}\")\n        data_too_large_for_mahalanobis = Msg(\n            \"Mahalanobis handles up to 1000 {}.\")\n\n    class Warning(OWWidget.Warning):\n        ignoring_discrete = Msg(\"Ignoring categorical features\")\n        ignoring_nonbinary = Msg(\"Ignoring non-binary features\")\n        imputing_data = Msg(\"Missing values were imputed\")\n\n    def __init__(self):\n        OWWidget.__init__(self)\n        ConcurrentWidgetMixin.__init__(self)\n\n        self.data = None\n\n        gui.radioButtons(\n            self.controlArea, self, \"axis\", [\"Rows\", \"Columns\"],\n            box=\"Distances between\", callback=self._invalidate\n        )\n        box = gui.widgetBox(self.controlArea, \"Distance Metric\")\n        self.metrics_combo = gui.comboBox(\n            box, self, \"metric_idx\",\n            items=[m[0] for m in METRICS],\n            callback=self._metric_changed\n        )\n        self.normalization_check = gui.checkBox(\n            box, self, \"normalized_dist\", \"Normalized\",\n            callback=self._invalidate,\n            tooltip=(\"All dimensions are (implicitly) scaled to a common\"\n                     \"scale to normalize the influence across the domain.\"),\n            stateWhenDisabled=False, attribute=Qt.WA_LayoutUsesWidgetRect\n        )\n        _, metric = METRICS[self.metric_idx]\n        self.normalization_check.setEnabled(metric.supports_normalization)\n\n        gui.auto_apply(self.buttonsArea, self, \"autocommit\")\n\n    @Inputs.data\n    @check_sql_input\n    def set_data(self, data):\n        self.cancel()\n        self.data = data\n        self.refresh_metrics()\n        self.unconditional_commit()\n\n    def refresh_metrics(self):\n        sparse = self.data is not None and issparse(self.data.X)\n        for i, metric in enumerate(METRICS):\n            item = self.metrics_combo.model().item(i)\n            item.setEnabled(not sparse or metric[1].supports_sparse)\n\n    def commit(self):\n        # pylint: disable=invalid-sequence-index\n        metric = METRICS[self.metric_idx][1]\n        self.compute_distances(metric, self.data)\n\n    def compute_distances(self, metric, data):\n        def _check_sparse():\n            # pylint: disable=invalid-sequence-index\n            if issparse(data.X) and not metric.supports_sparse:\n                self.Error.dense_metric_sparse_data(METRICS[self.metric_idx][0])\n                return False\n            return True\n\n        def _fix_discrete():\n            nonlocal data\n            if data.domain.has_discrete_attributes() \\\n                    and metric is not distance.Jaccard \\\n                    and (issparse(data.X) and getattr(metric, \"fallback\", None)\n                         or not metric.supports_discrete\n                         or self.axis == 1):\n                if not data.domain.has_continuous_attributes():\n                    self.Error.no_continuous_features()\n                    return False\n                self.Warning.ignoring_discrete()\n                data = distance.remove_discrete_features(data, to_metas=True)\n            return True\n\n        def _fix_nonbinary():\n            nonlocal data\n            if metric is distance.Jaccard and not issparse(data.X):\n                nbinary = sum(a.is_discrete and len(a.values) == 2\n                              for a in data.domain.attributes)\n                if not nbinary:\n                    self.Error.no_binary_features()\n                    return False\n                elif nbinary < len(data.domain.attributes):\n                    self.Warning.ignoring_nonbinary()\n                    data = distance.remove_nonbinary_features(data,\n                                                              to_metas=True)\n            return True\n\n        def _fix_missing():\n            nonlocal data\n            if not metric.supports_missing and bn.anynan(data.X):\n                self.Warning.imputing_data()\n                data = distance.impute(data)\n            return True\n\n        def _check_tractability():\n            if metric is distance.Mahalanobis:\n                if self.axis == 1:\n                    # when computing distances by columns, we want < 100 rows\n                    if len(data) > 1000:\n                        self.Error.data_too_large_for_mahalanobis(\"rows\")\n                        return False\n                else:\n                    if len(data.domain.attributes) > 1000:\n                        self.Error.data_too_large_for_mahalanobis(\"columns\")\n                        return False\n            return True\n\n        self.clear_messages()\n        if data is not None:\n            for check in (_check_sparse, _check_tractability,\n                          _fix_discrete, _fix_missing, _fix_nonbinary):\n                if not check():\n                    data = None\n                    break\n\n        self.start(DistanceRunner.run, data, metric,\n                   self.normalized_dist, self.axis)\n\n    def on_partial_result(self, _):\n        pass\n\n    def on_done(self, result: Orange.misc.DistMatrix):\n        assert isinstance(result, Orange.misc.DistMatrix) or result is None\n        self.Outputs.distances.send(result)\n\n    def on_exception(self, ex):\n        if isinstance(ex, ValueError):\n            self.Error.distances_value_error(ex)\n        elif isinstance(ex, MemoryError):\n            self.Error.distances_memory_error()\n        elif isinstance(ex, InterruptException):\n            pass\n        else:\n            raise ex\n\n    def onDeleteWidget(self):\n        self.shutdown()\n        super().onDeleteWidget()\n\n    def _invalidate(self):\n        self.commit()\n\n    def _metric_changed(self):\n        metric = METRICS[self.metric_idx][1]\n        self.normalization_check.setEnabled(metric.supports_normalization)\n        self._invalidate()\n\n    def send_report(self):\n        # pylint: disable=invalid-sequence-index\n        self.report_items((\n            (\"Distances Between\", [\"Rows\", \"Columns\"][self.axis]),\n            (\"Metric\", METRICS[self.metric_idx][0])\n        ))\n\n    @classmethod\n    def migrate_settings(cls, settings, version):\n        if version is None or version < 2 and \"normalized_dist\" not in settings:\n            # normalize_dist is set to False when restoring settings from\n            # an older version to preserve old semantics.\n            settings[\"normalized_dist\"] = False\n        if version is None or version < 3:\n            # Mahalanobis was moved from idx = 2 to idx = 9\n            metric_idx = settings[\"metric_idx\"]\n            if metric_idx == 2:\n                settings[\"metric_idx\"] = 9\n            elif 2 < metric_idx <= 9:\n                settings[\"metric_idx\"] -= 1\n\n\nif __name__ == \"__main__\":  # pragma: no cover\n    WidgetPreview(OWDistances).run(Orange.data.Table(\"iris\"))\n",
            "header": {
                "file": {
                    "path": "Orange/widgets/unsupervised/owdistances.py"
                },
                "misc_line": null
            },
            "index_line": {
                "old_commit_hash": "1676d9c51",
                "new_commit_hash": "4ad05e44c",
                "mode": "100644"
            },
            "is_binary_file": false,
            "binary_line": null,
            "minus_file": {
                "path": "a/Orange/widgets/unsupervised/owdistances.py"
            },
            "plus_file": {
                "path": "b/Orange/widgets/unsupervised/owdistances.py"
            },
            "hunks": [
                {
                    "descriptor": {
                        "old_range": {
                            "start": 158,
                            "length": 7
                        },
                        "new_range": {
                            "start": 158,
                            "length": 7
                        },
                        "section": "class OWDistances(OWWidget, ConcurrentWidgetMixin):"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "                    self.Error.no_continuous_features()",
                                "type": "context"
                            },
                            {
                                "content": "                    return False",
                                "type": "context"
                            },
                            {
                                "content": "                self.Warning.ignoring_discrete()",
                                "type": "context"
                            },
                            {
                                "content": "                data = distance.remove_discrete_features(data)",
                                "type": "deleted"
                            },
                            {
                                "content": "                data = distance.remove_discrete_features(data, to_metas=True)",
                                "type": "added"
                            },
                            {
                                "content": "            return True",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "        def _fix_nonbinary():",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [
                        {
                            "file_name": "Orange/widgets/unsupervised/owdistances.py",
                            "type": "method",
                            "name": "OWDistances.compute_distances",
                            "content": "class OWDistances(OWWidget, ConcurrentWidgetMixin):\n    name = \"Distances\"\n    description = \"Compute a matrix of pairwise distances.\"\n    icon = \"icons/Distance.svg\"\n    keywords = []\n\n    class Inputs:\n        data = Input(\"Data\", Orange.data.Table)\n\n    class Outputs:\n        distances = Output(\"Distances\", Orange.misc.DistMatrix, dynamic=False)\n\n    settings_version = 3\n\n    axis = Setting(0)        # type: int\n    metric_idx = Setting(0)  # type: int\n\n    #: Use normalized distances if the metric supports it.\n    #: The default is `True`, expect when restoring from old pre v2 settings\n    #: (see `migrate_settings`).\n    normalized_dist = Setting(True)  # type: bool\n    autocommit = Setting(True)       # type: bool\n\n    want_main_area = False\n    resizing_enabled = False\n\n    class Error(OWWidget.Error):\n        no_continuous_features = Msg(\"No numeric features\")\n        no_binary_features = Msg(\"No binary features\")\n        dense_metric_sparse_data = Msg(\"{} requires dense data.\")\n        distances_memory_error = Msg(\"Not enough memory\")\n        distances_value_error = Msg(\"Problem in calculation:\\n{}\")\n        data_too_large_for_mahalanobis = Msg(\n            \"Mahalanobis handles up to 1000 {}.\")\n\n    class Warning(OWWidget.Warning):\n        ignoring_discrete = Msg(\"Ignoring categorical features\")\n        ignoring_nonbinary = Msg(\"Ignoring non-binary features\")\n        imputing_data = Msg(\"Missing values were imputed\")\n\n    def __init__(self):\n        OWWidget.__init__(self)\n        ConcurrentWidgetMixin.__init__(self)\n\n        self.data = None\n\n        gui.radioButtons(\n            self.controlArea, self, \"axis\", [\"Rows\", \"Columns\"],\n            box=\"Distances between\", callback=self._invalidate\n        )\n        box = gui.widgetBox(self.controlArea, \"Distance Metric\")\n        self.metrics_combo = gui.comboBox(\n            box, self, \"metric_idx\",\n            items=[m[0] for m in METRICS],\n            callback=self._metric_changed\n        )\n        self.normalization_check = gui.checkBox(\n            box, self, \"normalized_dist\", \"Normalized\",\n            callback=self._invalidate,\n            tooltip=(\"All dimensions are (implicitly) scaled to a common\"\n                     \"scale to normalize the influence across the domain.\"),\n            stateWhenDisabled=False, attribute=Qt.WA_LayoutUsesWidgetRect\n        )\n        _, metric = METRICS[self.metric_idx]\n        self.normalization_check.setEnabled(metric.supports_normalization)\n\n        gui.auto_apply(self.buttonsArea, self, \"autocommit\")\n\n    @Inputs.data\n    @check_sql_input\n    def set_data(self, data):\n        self.cancel()\n        self.data = data\n        self.refresh_metrics()\n        self.unconditional_commit()\n\n    def refresh_metrics(self):\n        sparse = self.data is not None and issparse(self.data.X)\n        for i, metric in enumerate(METRICS):\n            item = self.metrics_combo.model().item(i)\n            item.setEnabled(not sparse or metric[1].supports_sparse)\n\n    def commit(self):\n        # pylint: disable=invalid-sequence-index\n        metric = METRICS[self.metric_idx][1]\n        self.compute_distances(metric, self.data)\n\n    def compute_distances(self, metric, data):\n        def _check_sparse():\n            # pylint: disable=invalid-sequence-index\n            if issparse(data.X) and not metric.supports_sparse:\n                self.Error.dense_metric_sparse_data(METRICS[self.metric_idx][0])\n                return False\n            return True\n\n        def _fix_discrete():\n            nonlocal data\n            if data.domain.has_discrete_attributes() \\\n                    and metric is not distance.Jaccard \\\n                    and (issparse(data.X) and getattr(metric, \"fallback\", None)\n                         or not metric.supports_discrete\n                         or self.axis == 1):\n                if not data.domain.has_continuous_attributes():\n                    self.Error.no_continuous_features()\n                    return False\n                self.Warning.ignoring_discrete()\n                data = distance.remove_discrete_features(data)\n            return True\n\n        def _fix_nonbinary():\n            nonlocal data\n            if metric is distance.Jaccard and not issparse(data.X):\n                nbinary = sum(a.is_discrete and len(a.values) == 2\n                              for a in data.domain.attributes)\n                if not nbinary:\n                    self.Error.no_binary_features()\n                    return False\n                elif nbinary < len(data.domain.attributes):\n                    self.Warning.ignoring_nonbinary()\n                    data = distance.remove_nonbinary_features(data)\n            return True\n\n        def _fix_missing():\n            nonlocal data\n            if not metric.supports_missing and bn.anynan(data.X):\n                self.Warning.imputing_data()\n                data = distance.impute(data)\n            return True\n\n        def _check_tractability():\n            if metric is distance.Mahalanobis:\n                if self.axis == 1:\n                    # when computing distances by columns, we want < 100 rows\n                    if len(data) > 1000:\n                        self.Error.data_too_large_for_mahalanobis(\"rows\")\n                        return False\n                else:\n                    if len(data.domain.attributes) > 1000:\n                        self.Error.data_too_large_for_mahalanobis(\"columns\")\n                        return False\n            return True\n\n        self.clear_messages()\n        if data is not None:\n            for check in (_check_sparse, _check_tractability,\n                          _fix_discrete, _fix_missing, _fix_nonbinary):\n                if not check():\n                    data = None\n                    break\n\n        self.start(DistanceRunner.run, data, metric,\n                   self.normalized_dist, self.axis)\n\n    def on_partial_result(self, _):\n        pass\n\n    def on_done(self, result: Orange.misc.DistMatrix):\n        assert isinstance(result, Orange.misc.DistMatrix) or result is None\n        self.Outputs.distances.send(result)\n\n    def on_exception(self, ex):\n        if isinstance(ex, ValueError):\n            self.Error.distances_value_error(ex)\n        elif isinstance(ex, MemoryError):\n            self.Error.distances_memory_error()\n        elif isinstance(ex, InterruptException):\n            pass\n        else:\n            raise ex\n\n    def onDeleteWidget(self):\n        self.shutdown()\n        super().onDeleteWidget()\n\n    def _invalidate(self):\n        self.commit()\n\n    def _metric_changed(self):\n        metric = METRICS[self.metric_idx][1]\n        self.normalization_check.setEnabled(metric.supports_normalization)\n        self._invalidate()\n\n    def send_report(self):\n        # pylint: disable=invalid-sequence-index\n        self.report_items((\n            (\"Distances Between\", [\"Rows\", \"Columns\"][self.axis]),\n            (\"Metric\", METRICS[self.metric_idx][0])\n        ))\n\n    @classmethod\n    def migrate_settings(cls, settings, version):\n        if version is None or version < 2 and \"normalized_dist\" not in settings:\n            # normalize_dist is set to False when restoring settings from\n            # an older version to preserve old semantics.\n            settings[\"normalized_dist\"] = False\n        if version is None or version < 3:\n            # Mahalanobis was moved from idx = 2 to idx = 9\n            metric_idx = settings[\"metric_idx\"]\n            if metric_idx == 2:\n                settings[\"metric_idx\"] = 9\n            elif 2 < metric_idx <= 9:\n                settings[\"metric_idx\"] -= 1",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 142,
                            "end_lineno": 206,
                            "parent": {
                                "file_name": "Orange/widgets/unsupervised/owdistances.py",
                                "type": "class",
                                "name": "OWDistances",
                                "content": "class OWDistances(OWWidget, ConcurrentWidgetMixin):\n    name = \"Distances\"\n    description = \"Compute a matrix of pairwise distances.\"\n    icon = \"icons/Distance.svg\"\n    keywords = []\n\n    class Inputs:\n        data = Input(\"Data\", Orange.data.Table)\n\n    class Outputs:\n        distances = Output(\"Distances\", Orange.misc.DistMatrix, dynamic=False)\n\n    settings_version = 3\n\n    axis = Setting(0)        # type: int\n    metric_idx = Setting(0)  # type: int\n\n    #: Use normalized distances if the metric supports it.\n    #: The default is `True`, expect when restoring from old pre v2 settings\n    #: (see `migrate_settings`).\n    normalized_dist = Setting(True)  # type: bool\n    autocommit = Setting(True)       # type: bool\n\n    want_main_area = False\n    resizing_enabled = False\n\n    class Error(OWWidget.Error):\n        no_continuous_features = Msg(\"No numeric features\")\n        no_binary_features = Msg(\"No binary features\")\n        dense_metric_sparse_data = Msg(\"{} requires dense data.\")\n        distances_memory_error = Msg(\"Not enough memory\")\n        distances_value_error = Msg(\"Problem in calculation:\\n{}\")\n        data_too_large_for_mahalanobis = Msg(\n            \"Mahalanobis handles up to 1000 {}.\")\n\n    class Warning(OWWidget.Warning):\n        ignoring_discrete = Msg(\"Ignoring categorical features\")\n        ignoring_nonbinary = Msg(\"Ignoring non-binary features\")\n        imputing_data = Msg(\"Missing values were imputed\")\n\n    def __init__(self):\n        OWWidget.__init__(self)\n        ConcurrentWidgetMixin.__init__(self)\n\n        self.data = None\n\n        gui.radioButtons(\n            self.controlArea, self, \"axis\", [\"Rows\", \"Columns\"],\n            box=\"Distances between\", callback=self._invalidate\n        )\n        box = gui.widgetBox(self.controlArea, \"Distance Metric\")\n        self.metrics_combo = gui.comboBox(\n            box, self, \"metric_idx\",\n            items=[m[0] for m in METRICS],\n            callback=self._metric_changed\n        )\n        self.normalization_check = gui.checkBox(\n            box, self, \"normalized_dist\", \"Normalized\",\n            callback=self._invalidate,\n            tooltip=(\"All dimensions are (implicitly) scaled to a common\"\n                     \"scale to normalize the influence across the domain.\"),\n            stateWhenDisabled=False, attribute=Qt.WA_LayoutUsesWidgetRect\n        )\n        _, metric = METRICS[self.metric_idx]\n        self.normalization_check.setEnabled(metric.supports_normalization)\n\n        gui.auto_apply(self.buttonsArea, self, \"autocommit\")\n\n    @Inputs.data\n    @check_sql_input\n    def set_data(self, data):\n        self.cancel()\n        self.data = data\n        self.refresh_metrics()\n        self.unconditional_commit()\n\n    def refresh_metrics(self):\n        sparse = self.data is not None and issparse(self.data.X)\n        for i, metric in enumerate(METRICS):\n            item = self.metrics_combo.model().item(i)\n            item.setEnabled(not sparse or metric[1].supports_sparse)\n\n    def commit(self):\n        # pylint: disable=invalid-sequence-index\n        metric = METRICS[self.metric_idx][1]\n        self.compute_distances(metric, self.data)\n\n    def compute_distances(self, metric, data):\n        def _check_sparse():\n            # pylint: disable=invalid-sequence-index\n            if issparse(data.X) and not metric.supports_sparse:\n                self.Error.dense_metric_sparse_data(METRICS[self.metric_idx][0])\n                return False\n            return True\n\n        def _fix_discrete():\n            nonlocal data\n            if data.domain.has_discrete_attributes() \\\n                    and metric is not distance.Jaccard \\\n                    and (issparse(data.X) and getattr(metric, \"fallback\", None)\n                         or not metric.supports_discrete\n                         or self.axis == 1):\n                if not data.domain.has_continuous_attributes():\n                    self.Error.no_continuous_features()\n                    return False\n                self.Warning.ignoring_discrete()\n                data = distance.remove_discrete_features(data)\n            return True\n\n        def _fix_nonbinary():\n            nonlocal data\n            if metric is distance.Jaccard and not issparse(data.X):\n                nbinary = sum(a.is_discrete and len(a.values) == 2\n                              for a in data.domain.attributes)\n                if not nbinary:\n                    self.Error.no_binary_features()\n                    return False\n                elif nbinary < len(data.domain.attributes):\n                    self.Warning.ignoring_nonbinary()\n                    data = distance.remove_nonbinary_features(data)\n            return True\n\n        def _fix_missing():\n            nonlocal data\n            if not metric.supports_missing and bn.anynan(data.X):\n                self.Warning.imputing_data()\n                data = distance.impute(data)\n            return True\n\n        def _check_tractability():\n            if metric is distance.Mahalanobis:\n                if self.axis == 1:\n                    # when computing distances by columns, we want < 100 rows\n                    if len(data) > 1000:\n                        self.Error.data_too_large_for_mahalanobis(\"rows\")\n                        return False\n                else:\n                    if len(data.domain.attributes) > 1000:\n                        self.Error.data_too_large_for_mahalanobis(\"columns\")\n                        return False\n            return True\n\n        self.clear_messages()\n        if data is not None:\n            for check in (_check_sparse, _check_tractability,\n                          _fix_discrete, _fix_missing, _fix_nonbinary):\n                if not check():\n                    data = None\n                    break\n\n        self.start(DistanceRunner.run, data, metric,\n                   self.normalized_dist, self.axis)\n\n    def on_partial_result(self, _):\n        pass\n\n    def on_done(self, result: Orange.misc.DistMatrix):\n        assert isinstance(result, Orange.misc.DistMatrix) or result is None\n        self.Outputs.distances.send(result)\n\n    def on_exception(self, ex):\n        if isinstance(ex, ValueError):\n            self.Error.distances_value_error(ex)\n        elif isinstance(ex, MemoryError):\n            self.Error.distances_memory_error()\n        elif isinstance(ex, InterruptException):\n            pass\n        else:\n            raise ex\n\n    def onDeleteWidget(self):\n        self.shutdown()\n        super().onDeleteWidget()\n\n    def _invalidate(self):\n        self.commit()\n\n    def _metric_changed(self):\n        metric = METRICS[self.metric_idx][1]\n        self.normalization_check.setEnabled(metric.supports_normalization)\n        self._invalidate()\n\n    def send_report(self):\n        # pylint: disable=invalid-sequence-index\n        self.report_items((\n            (\"Distances Between\", [\"Rows\", \"Columns\"][self.axis]),\n            (\"Metric\", METRICS[self.metric_idx][0])\n        ))\n\n    @classmethod\n    def migrate_settings(cls, settings, version):\n        if version is None or version < 2 and \"normalized_dist\" not in settings:\n            # normalize_dist is set to False when restoring settings from\n            # an older version to preserve old semantics.\n            settings[\"normalized_dist\"] = False\n        if version is None or version < 3:\n            # Mahalanobis was moved from idx = 2 to idx = 9\n            metric_idx = settings[\"metric_idx\"]\n            if metric_idx == 2:\n                settings[\"metric_idx\"] = 9\n            elif 2 < metric_idx <= 9:\n                settings[\"metric_idx\"] -= 1",
                                "ast_type_str": "ClassDef",
                                "start_lineno": 55,
                                "end_lineno": 256,
                                "parent": null
                            }
                        },
                        {
                            "file_name": "Orange/widgets/unsupervised/owdistances.py",
                            "type": "class",
                            "name": "OWDistances",
                            "content": "class OWDistances(OWWidget, ConcurrentWidgetMixin):\n    name = \"Distances\"\n    description = \"Compute a matrix of pairwise distances.\"\n    icon = \"icons/Distance.svg\"\n    keywords = []\n\n    class Inputs:\n        data = Input(\"Data\", Orange.data.Table)\n\n    class Outputs:\n        distances = Output(\"Distances\", Orange.misc.DistMatrix, dynamic=False)\n\n    settings_version = 3\n\n    axis = Setting(0)        # type: int\n    metric_idx = Setting(0)  # type: int\n\n    #: Use normalized distances if the metric supports it.\n    #: The default is `True`, expect when restoring from old pre v2 settings\n    #: (see `migrate_settings`).\n    normalized_dist = Setting(True)  # type: bool\n    autocommit = Setting(True)       # type: bool\n\n    want_main_area = False\n    resizing_enabled = False\n\n    class Error(OWWidget.Error):\n        no_continuous_features = Msg(\"No numeric features\")\n        no_binary_features = Msg(\"No binary features\")\n        dense_metric_sparse_data = Msg(\"{} requires dense data.\")\n        distances_memory_error = Msg(\"Not enough memory\")\n        distances_value_error = Msg(\"Problem in calculation:\\n{}\")\n        data_too_large_for_mahalanobis = Msg(\n            \"Mahalanobis handles up to 1000 {}.\")\n\n    class Warning(OWWidget.Warning):\n        ignoring_discrete = Msg(\"Ignoring categorical features\")\n        ignoring_nonbinary = Msg(\"Ignoring non-binary features\")\n        imputing_data = Msg(\"Missing values were imputed\")\n\n    def __init__(self):\n        OWWidget.__init__(self)\n        ConcurrentWidgetMixin.__init__(self)\n\n        self.data = None\n\n        gui.radioButtons(\n            self.controlArea, self, \"axis\", [\"Rows\", \"Columns\"],\n            box=\"Distances between\", callback=self._invalidate\n        )\n        box = gui.widgetBox(self.controlArea, \"Distance Metric\")\n        self.metrics_combo = gui.comboBox(\n            box, self, \"metric_idx\",\n            items=[m[0] for m in METRICS],\n            callback=self._metric_changed\n        )\n        self.normalization_check = gui.checkBox(\n            box, self, \"normalized_dist\", \"Normalized\",\n            callback=self._invalidate,\n            tooltip=(\"All dimensions are (implicitly) scaled to a common\"\n                     \"scale to normalize the influence across the domain.\"),\n            stateWhenDisabled=False, attribute=Qt.WA_LayoutUsesWidgetRect\n        )\n        _, metric = METRICS[self.metric_idx]\n        self.normalization_check.setEnabled(metric.supports_normalization)\n\n        gui.auto_apply(self.buttonsArea, self, \"autocommit\")\n\n    @Inputs.data\n    @check_sql_input\n    def set_data(self, data):\n        self.cancel()\n        self.data = data\n        self.refresh_metrics()\n        self.unconditional_commit()\n\n    def refresh_metrics(self):\n        sparse = self.data is not None and issparse(self.data.X)\n        for i, metric in enumerate(METRICS):\n            item = self.metrics_combo.model().item(i)\n            item.setEnabled(not sparse or metric[1].supports_sparse)\n\n    def commit(self):\n        # pylint: disable=invalid-sequence-index\n        metric = METRICS[self.metric_idx][1]\n        self.compute_distances(metric, self.data)\n\n    def compute_distances(self, metric, data):\n        def _check_sparse():\n            # pylint: disable=invalid-sequence-index\n            if issparse(data.X) and not metric.supports_sparse:\n                self.Error.dense_metric_sparse_data(METRICS[self.metric_idx][0])\n                return False\n            return True\n\n        def _fix_discrete():\n            nonlocal data\n            if data.domain.has_discrete_attributes() \\\n                    and metric is not distance.Jaccard \\\n                    and (issparse(data.X) and getattr(metric, \"fallback\", None)\n                         or not metric.supports_discrete\n                         or self.axis == 1):\n                if not data.domain.has_continuous_attributes():\n                    self.Error.no_continuous_features()\n                    return False\n                self.Warning.ignoring_discrete()\n                data = distance.remove_discrete_features(data)\n            return True\n\n        def _fix_nonbinary():\n            nonlocal data\n            if metric is distance.Jaccard and not issparse(data.X):\n                nbinary = sum(a.is_discrete and len(a.values) == 2\n                              for a in data.domain.attributes)\n                if not nbinary:\n                    self.Error.no_binary_features()\n                    return False\n                elif nbinary < len(data.domain.attributes):\n                    self.Warning.ignoring_nonbinary()\n                    data = distance.remove_nonbinary_features(data)\n            return True\n\n        def _fix_missing():\n            nonlocal data\n            if not metric.supports_missing and bn.anynan(data.X):\n                self.Warning.imputing_data()\n                data = distance.impute(data)\n            return True\n\n        def _check_tractability():\n            if metric is distance.Mahalanobis:\n                if self.axis == 1:\n                    # when computing distances by columns, we want < 100 rows\n                    if len(data) > 1000:\n                        self.Error.data_too_large_for_mahalanobis(\"rows\")\n                        return False\n                else:\n                    if len(data.domain.attributes) > 1000:\n                        self.Error.data_too_large_for_mahalanobis(\"columns\")\n                        return False\n            return True\n\n        self.clear_messages()\n        if data is not None:\n            for check in (_check_sparse, _check_tractability,\n                          _fix_discrete, _fix_missing, _fix_nonbinary):\n                if not check():\n                    data = None\n                    break\n\n        self.start(DistanceRunner.run, data, metric,\n                   self.normalized_dist, self.axis)\n\n    def on_partial_result(self, _):\n        pass\n\n    def on_done(self, result: Orange.misc.DistMatrix):\n        assert isinstance(result, Orange.misc.DistMatrix) or result is None\n        self.Outputs.distances.send(result)\n\n    def on_exception(self, ex):\n        if isinstance(ex, ValueError):\n            self.Error.distances_value_error(ex)\n        elif isinstance(ex, MemoryError):\n            self.Error.distances_memory_error()\n        elif isinstance(ex, InterruptException):\n            pass\n        else:\n            raise ex\n\n    def onDeleteWidget(self):\n        self.shutdown()\n        super().onDeleteWidget()\n\n    def _invalidate(self):\n        self.commit()\n\n    def _metric_changed(self):\n        metric = METRICS[self.metric_idx][1]\n        self.normalization_check.setEnabled(metric.supports_normalization)\n        self._invalidate()\n\n    def send_report(self):\n        # pylint: disable=invalid-sequence-index\n        self.report_items((\n            (\"Distances Between\", [\"Rows\", \"Columns\"][self.axis]),\n            (\"Metric\", METRICS[self.metric_idx][0])\n        ))\n\n    @classmethod\n    def migrate_settings(cls, settings, version):\n        if version is None or version < 2 and \"normalized_dist\" not in settings:\n            # normalize_dist is set to False when restoring settings from\n            # an older version to preserve old semantics.\n            settings[\"normalized_dist\"] = False\n        if version is None or version < 3:\n            # Mahalanobis was moved from idx = 2 to idx = 9\n            metric_idx = settings[\"metric_idx\"]\n            if metric_idx == 2:\n                settings[\"metric_idx\"] = 9\n            elif 2 < metric_idx <= 9:\n                settings[\"metric_idx\"] -= 1",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 55,
                            "end_lineno": 256,
                            "parent": null
                        }
                    ],
                    "added_entities": [],
                    "deleted_entities": []
                },
                {
                    "descriptor": {
                        "old_range": {
                            "start": 171,
                            "length": 7
                        },
                        "new_range": {
                            "start": 171,
                            "length": 8
                        },
                        "section": "class OWDistances(OWWidget, ConcurrentWidgetMixin):"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "                    return False",
                                "type": "context"
                            },
                            {
                                "content": "                elif nbinary < len(data.domain.attributes):",
                                "type": "context"
                            },
                            {
                                "content": "                    self.Warning.ignoring_nonbinary()",
                                "type": "context"
                            },
                            {
                                "content": "                    data = distance.remove_nonbinary_features(data)",
                                "type": "deleted"
                            },
                            {
                                "content": "                    data = distance.remove_nonbinary_features(data,",
                                "type": "added"
                            },
                            {
                                "content": "                                                              to_metas=True)",
                                "type": "added"
                            },
                            {
                                "content": "            return True",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "        def _fix_missing():",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [
                        {
                            "file_name": "Orange/widgets/unsupervised/owdistances.py",
                            "type": "method",
                            "name": "OWDistances.compute_distances",
                            "content": "class OWDistances(OWWidget, ConcurrentWidgetMixin):\n    name = \"Distances\"\n    description = \"Compute a matrix of pairwise distances.\"\n    icon = \"icons/Distance.svg\"\n    keywords = []\n\n    class Inputs:\n        data = Input(\"Data\", Orange.data.Table)\n\n    class Outputs:\n        distances = Output(\"Distances\", Orange.misc.DistMatrix, dynamic=False)\n\n    settings_version = 3\n\n    axis = Setting(0)        # type: int\n    metric_idx = Setting(0)  # type: int\n\n    #: Use normalized distances if the metric supports it.\n    #: The default is `True`, expect when restoring from old pre v2 settings\n    #: (see `migrate_settings`).\n    normalized_dist = Setting(True)  # type: bool\n    autocommit = Setting(True)       # type: bool\n\n    want_main_area = False\n    resizing_enabled = False\n\n    class Error(OWWidget.Error):\n        no_continuous_features = Msg(\"No numeric features\")\n        no_binary_features = Msg(\"No binary features\")\n        dense_metric_sparse_data = Msg(\"{} requires dense data.\")\n        distances_memory_error = Msg(\"Not enough memory\")\n        distances_value_error = Msg(\"Problem in calculation:\\n{}\")\n        data_too_large_for_mahalanobis = Msg(\n            \"Mahalanobis handles up to 1000 {}.\")\n\n    class Warning(OWWidget.Warning):\n        ignoring_discrete = Msg(\"Ignoring categorical features\")\n        ignoring_nonbinary = Msg(\"Ignoring non-binary features\")\n        imputing_data = Msg(\"Missing values were imputed\")\n\n    def __init__(self):\n        OWWidget.__init__(self)\n        ConcurrentWidgetMixin.__init__(self)\n\n        self.data = None\n\n        gui.radioButtons(\n            self.controlArea, self, \"axis\", [\"Rows\", \"Columns\"],\n            box=\"Distances between\", callback=self._invalidate\n        )\n        box = gui.widgetBox(self.controlArea, \"Distance Metric\")\n        self.metrics_combo = gui.comboBox(\n            box, self, \"metric_idx\",\n            items=[m[0] for m in METRICS],\n            callback=self._metric_changed\n        )\n        self.normalization_check = gui.checkBox(\n            box, self, \"normalized_dist\", \"Normalized\",\n            callback=self._invalidate,\n            tooltip=(\"All dimensions are (implicitly) scaled to a common\"\n                     \"scale to normalize the influence across the domain.\"),\n            stateWhenDisabled=False, attribute=Qt.WA_LayoutUsesWidgetRect\n        )\n        _, metric = METRICS[self.metric_idx]\n        self.normalization_check.setEnabled(metric.supports_normalization)\n\n        gui.auto_apply(self.buttonsArea, self, \"autocommit\")\n\n    @Inputs.data\n    @check_sql_input\n    def set_data(self, data):\n        self.cancel()\n        self.data = data\n        self.refresh_metrics()\n        self.unconditional_commit()\n\n    def refresh_metrics(self):\n        sparse = self.data is not None and issparse(self.data.X)\n        for i, metric in enumerate(METRICS):\n            item = self.metrics_combo.model().item(i)\n            item.setEnabled(not sparse or metric[1].supports_sparse)\n\n    def commit(self):\n        # pylint: disable=invalid-sequence-index\n        metric = METRICS[self.metric_idx][1]\n        self.compute_distances(metric, self.data)\n\n    def compute_distances(self, metric, data):\n        def _check_sparse():\n            # pylint: disable=invalid-sequence-index\n            if issparse(data.X) and not metric.supports_sparse:\n                self.Error.dense_metric_sparse_data(METRICS[self.metric_idx][0])\n                return False\n            return True\n\n        def _fix_discrete():\n            nonlocal data\n            if data.domain.has_discrete_attributes() \\\n                    and metric is not distance.Jaccard \\\n                    and (issparse(data.X) and getattr(metric, \"fallback\", None)\n                         or not metric.supports_discrete\n                         or self.axis == 1):\n                if not data.domain.has_continuous_attributes():\n                    self.Error.no_continuous_features()\n                    return False\n                self.Warning.ignoring_discrete()\n                data = distance.remove_discrete_features(data)\n            return True\n\n        def _fix_nonbinary():\n            nonlocal data\n            if metric is distance.Jaccard and not issparse(data.X):\n                nbinary = sum(a.is_discrete and len(a.values) == 2\n                              for a in data.domain.attributes)\n                if not nbinary:\n                    self.Error.no_binary_features()\n                    return False\n                elif nbinary < len(data.domain.attributes):\n                    self.Warning.ignoring_nonbinary()\n                    data = distance.remove_nonbinary_features(data)\n            return True\n\n        def _fix_missing():\n            nonlocal data\n            if not metric.supports_missing and bn.anynan(data.X):\n                self.Warning.imputing_data()\n                data = distance.impute(data)\n            return True\n\n        def _check_tractability():\n            if metric is distance.Mahalanobis:\n                if self.axis == 1:\n                    # when computing distances by columns, we want < 100 rows\n                    if len(data) > 1000:\n                        self.Error.data_too_large_for_mahalanobis(\"rows\")\n                        return False\n                else:\n                    if len(data.domain.attributes) > 1000:\n                        self.Error.data_too_large_for_mahalanobis(\"columns\")\n                        return False\n            return True\n\n        self.clear_messages()\n        if data is not None:\n            for check in (_check_sparse, _check_tractability,\n                          _fix_discrete, _fix_missing, _fix_nonbinary):\n                if not check():\n                    data = None\n                    break\n\n        self.start(DistanceRunner.run, data, metric,\n                   self.normalized_dist, self.axis)\n\n    def on_partial_result(self, _):\n        pass\n\n    def on_done(self, result: Orange.misc.DistMatrix):\n        assert isinstance(result, Orange.misc.DistMatrix) or result is None\n        self.Outputs.distances.send(result)\n\n    def on_exception(self, ex):\n        if isinstance(ex, ValueError):\n            self.Error.distances_value_error(ex)\n        elif isinstance(ex, MemoryError):\n            self.Error.distances_memory_error()\n        elif isinstance(ex, InterruptException):\n            pass\n        else:\n            raise ex\n\n    def onDeleteWidget(self):\n        self.shutdown()\n        super().onDeleteWidget()\n\n    def _invalidate(self):\n        self.commit()\n\n    def _metric_changed(self):\n        metric = METRICS[self.metric_idx][1]\n        self.normalization_check.setEnabled(metric.supports_normalization)\n        self._invalidate()\n\n    def send_report(self):\n        # pylint: disable=invalid-sequence-index\n        self.report_items((\n            (\"Distances Between\", [\"Rows\", \"Columns\"][self.axis]),\n            (\"Metric\", METRICS[self.metric_idx][0])\n        ))\n\n    @classmethod\n    def migrate_settings(cls, settings, version):\n        if version is None or version < 2 and \"normalized_dist\" not in settings:\n            # normalize_dist is set to False when restoring settings from\n            # an older version to preserve old semantics.\n            settings[\"normalized_dist\"] = False\n        if version is None or version < 3:\n            # Mahalanobis was moved from idx = 2 to idx = 9\n            metric_idx = settings[\"metric_idx\"]\n            if metric_idx == 2:\n                settings[\"metric_idx\"] = 9\n            elif 2 < metric_idx <= 9:\n                settings[\"metric_idx\"] -= 1",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 142,
                            "end_lineno": 206,
                            "parent": {
                                "file_name": "Orange/widgets/unsupervised/owdistances.py",
                                "type": "class",
                                "name": "OWDistances",
                                "content": "class OWDistances(OWWidget, ConcurrentWidgetMixin):\n    name = \"Distances\"\n    description = \"Compute a matrix of pairwise distances.\"\n    icon = \"icons/Distance.svg\"\n    keywords = []\n\n    class Inputs:\n        data = Input(\"Data\", Orange.data.Table)\n\n    class Outputs:\n        distances = Output(\"Distances\", Orange.misc.DistMatrix, dynamic=False)\n\n    settings_version = 3\n\n    axis = Setting(0)        # type: int\n    metric_idx = Setting(0)  # type: int\n\n    #: Use normalized distances if the metric supports it.\n    #: The default is `True`, expect when restoring from old pre v2 settings\n    #: (see `migrate_settings`).\n    normalized_dist = Setting(True)  # type: bool\n    autocommit = Setting(True)       # type: bool\n\n    want_main_area = False\n    resizing_enabled = False\n\n    class Error(OWWidget.Error):\n        no_continuous_features = Msg(\"No numeric features\")\n        no_binary_features = Msg(\"No binary features\")\n        dense_metric_sparse_data = Msg(\"{} requires dense data.\")\n        distances_memory_error = Msg(\"Not enough memory\")\n        distances_value_error = Msg(\"Problem in calculation:\\n{}\")\n        data_too_large_for_mahalanobis = Msg(\n            \"Mahalanobis handles up to 1000 {}.\")\n\n    class Warning(OWWidget.Warning):\n        ignoring_discrete = Msg(\"Ignoring categorical features\")\n        ignoring_nonbinary = Msg(\"Ignoring non-binary features\")\n        imputing_data = Msg(\"Missing values were imputed\")\n\n    def __init__(self):\n        OWWidget.__init__(self)\n        ConcurrentWidgetMixin.__init__(self)\n\n        self.data = None\n\n        gui.radioButtons(\n            self.controlArea, self, \"axis\", [\"Rows\", \"Columns\"],\n            box=\"Distances between\", callback=self._invalidate\n        )\n        box = gui.widgetBox(self.controlArea, \"Distance Metric\")\n        self.metrics_combo = gui.comboBox(\n            box, self, \"metric_idx\",\n            items=[m[0] for m in METRICS],\n            callback=self._metric_changed\n        )\n        self.normalization_check = gui.checkBox(\n            box, self, \"normalized_dist\", \"Normalized\",\n            callback=self._invalidate,\n            tooltip=(\"All dimensions are (implicitly) scaled to a common\"\n                     \"scale to normalize the influence across the domain.\"),\n            stateWhenDisabled=False, attribute=Qt.WA_LayoutUsesWidgetRect\n        )\n        _, metric = METRICS[self.metric_idx]\n        self.normalization_check.setEnabled(metric.supports_normalization)\n\n        gui.auto_apply(self.buttonsArea, self, \"autocommit\")\n\n    @Inputs.data\n    @check_sql_input\n    def set_data(self, data):\n        self.cancel()\n        self.data = data\n        self.refresh_metrics()\n        self.unconditional_commit()\n\n    def refresh_metrics(self):\n        sparse = self.data is not None and issparse(self.data.X)\n        for i, metric in enumerate(METRICS):\n            item = self.metrics_combo.model().item(i)\n            item.setEnabled(not sparse or metric[1].supports_sparse)\n\n    def commit(self):\n        # pylint: disable=invalid-sequence-index\n        metric = METRICS[self.metric_idx][1]\n        self.compute_distances(metric, self.data)\n\n    def compute_distances(self, metric, data):\n        def _check_sparse():\n            # pylint: disable=invalid-sequence-index\n            if issparse(data.X) and not metric.supports_sparse:\n                self.Error.dense_metric_sparse_data(METRICS[self.metric_idx][0])\n                return False\n            return True\n\n        def _fix_discrete():\n            nonlocal data\n            if data.domain.has_discrete_attributes() \\\n                    and metric is not distance.Jaccard \\\n                    and (issparse(data.X) and getattr(metric, \"fallback\", None)\n                         or not metric.supports_discrete\n                         or self.axis == 1):\n                if not data.domain.has_continuous_attributes():\n                    self.Error.no_continuous_features()\n                    return False\n                self.Warning.ignoring_discrete()\n                data = distance.remove_discrete_features(data)\n            return True\n\n        def _fix_nonbinary():\n            nonlocal data\n            if metric is distance.Jaccard and not issparse(data.X):\n                nbinary = sum(a.is_discrete and len(a.values) == 2\n                              for a in data.domain.attributes)\n                if not nbinary:\n                    self.Error.no_binary_features()\n                    return False\n                elif nbinary < len(data.domain.attributes):\n                    self.Warning.ignoring_nonbinary()\n                    data = distance.remove_nonbinary_features(data)\n            return True\n\n        def _fix_missing():\n            nonlocal data\n            if not metric.supports_missing and bn.anynan(data.X):\n                self.Warning.imputing_data()\n                data = distance.impute(data)\n            return True\n\n        def _check_tractability():\n            if metric is distance.Mahalanobis:\n                if self.axis == 1:\n                    # when computing distances by columns, we want < 100 rows\n                    if len(data) > 1000:\n                        self.Error.data_too_large_for_mahalanobis(\"rows\")\n                        return False\n                else:\n                    if len(data.domain.attributes) > 1000:\n                        self.Error.data_too_large_for_mahalanobis(\"columns\")\n                        return False\n            return True\n\n        self.clear_messages()\n        if data is not None:\n            for check in (_check_sparse, _check_tractability,\n                          _fix_discrete, _fix_missing, _fix_nonbinary):\n                if not check():\n                    data = None\n                    break\n\n        self.start(DistanceRunner.run, data, metric,\n                   self.normalized_dist, self.axis)\n\n    def on_partial_result(self, _):\n        pass\n\n    def on_done(self, result: Orange.misc.DistMatrix):\n        assert isinstance(result, Orange.misc.DistMatrix) or result is None\n        self.Outputs.distances.send(result)\n\n    def on_exception(self, ex):\n        if isinstance(ex, ValueError):\n            self.Error.distances_value_error(ex)\n        elif isinstance(ex, MemoryError):\n            self.Error.distances_memory_error()\n        elif isinstance(ex, InterruptException):\n            pass\n        else:\n            raise ex\n\n    def onDeleteWidget(self):\n        self.shutdown()\n        super().onDeleteWidget()\n\n    def _invalidate(self):\n        self.commit()\n\n    def _metric_changed(self):\n        metric = METRICS[self.metric_idx][1]\n        self.normalization_check.setEnabled(metric.supports_normalization)\n        self._invalidate()\n\n    def send_report(self):\n        # pylint: disable=invalid-sequence-index\n        self.report_items((\n            (\"Distances Between\", [\"Rows\", \"Columns\"][self.axis]),\n            (\"Metric\", METRICS[self.metric_idx][0])\n        ))\n\n    @classmethod\n    def migrate_settings(cls, settings, version):\n        if version is None or version < 2 and \"normalized_dist\" not in settings:\n            # normalize_dist is set to False when restoring settings from\n            # an older version to preserve old semantics.\n            settings[\"normalized_dist\"] = False\n        if version is None or version < 3:\n            # Mahalanobis was moved from idx = 2 to idx = 9\n            metric_idx = settings[\"metric_idx\"]\n            if metric_idx == 2:\n                settings[\"metric_idx\"] = 9\n            elif 2 < metric_idx <= 9:\n                settings[\"metric_idx\"] -= 1",
                                "ast_type_str": "ClassDef",
                                "start_lineno": 55,
                                "end_lineno": 256,
                                "parent": null
                            }
                        },
                        {
                            "file_name": "Orange/widgets/unsupervised/owdistances.py",
                            "type": "class",
                            "name": "OWDistances",
                            "content": "class OWDistances(OWWidget, ConcurrentWidgetMixin):\n    name = \"Distances\"\n    description = \"Compute a matrix of pairwise distances.\"\n    icon = \"icons/Distance.svg\"\n    keywords = []\n\n    class Inputs:\n        data = Input(\"Data\", Orange.data.Table)\n\n    class Outputs:\n        distances = Output(\"Distances\", Orange.misc.DistMatrix, dynamic=False)\n\n    settings_version = 3\n\n    axis = Setting(0)        # type: int\n    metric_idx = Setting(0)  # type: int\n\n    #: Use normalized distances if the metric supports it.\n    #: The default is `True`, expect when restoring from old pre v2 settings\n    #: (see `migrate_settings`).\n    normalized_dist = Setting(True)  # type: bool\n    autocommit = Setting(True)       # type: bool\n\n    want_main_area = False\n    resizing_enabled = False\n\n    class Error(OWWidget.Error):\n        no_continuous_features = Msg(\"No numeric features\")\n        no_binary_features = Msg(\"No binary features\")\n        dense_metric_sparse_data = Msg(\"{} requires dense data.\")\n        distances_memory_error = Msg(\"Not enough memory\")\n        distances_value_error = Msg(\"Problem in calculation:\\n{}\")\n        data_too_large_for_mahalanobis = Msg(\n            \"Mahalanobis handles up to 1000 {}.\")\n\n    class Warning(OWWidget.Warning):\n        ignoring_discrete = Msg(\"Ignoring categorical features\")\n        ignoring_nonbinary = Msg(\"Ignoring non-binary features\")\n        imputing_data = Msg(\"Missing values were imputed\")\n\n    def __init__(self):\n        OWWidget.__init__(self)\n        ConcurrentWidgetMixin.__init__(self)\n\n        self.data = None\n\n        gui.radioButtons(\n            self.controlArea, self, \"axis\", [\"Rows\", \"Columns\"],\n            box=\"Distances between\", callback=self._invalidate\n        )\n        box = gui.widgetBox(self.controlArea, \"Distance Metric\")\n        self.metrics_combo = gui.comboBox(\n            box, self, \"metric_idx\",\n            items=[m[0] for m in METRICS],\n            callback=self._metric_changed\n        )\n        self.normalization_check = gui.checkBox(\n            box, self, \"normalized_dist\", \"Normalized\",\n            callback=self._invalidate,\n            tooltip=(\"All dimensions are (implicitly) scaled to a common\"\n                     \"scale to normalize the influence across the domain.\"),\n            stateWhenDisabled=False, attribute=Qt.WA_LayoutUsesWidgetRect\n        )\n        _, metric = METRICS[self.metric_idx]\n        self.normalization_check.setEnabled(metric.supports_normalization)\n\n        gui.auto_apply(self.buttonsArea, self, \"autocommit\")\n\n    @Inputs.data\n    @check_sql_input\n    def set_data(self, data):\n        self.cancel()\n        self.data = data\n        self.refresh_metrics()\n        self.unconditional_commit()\n\n    def refresh_metrics(self):\n        sparse = self.data is not None and issparse(self.data.X)\n        for i, metric in enumerate(METRICS):\n            item = self.metrics_combo.model().item(i)\n            item.setEnabled(not sparse or metric[1].supports_sparse)\n\n    def commit(self):\n        # pylint: disable=invalid-sequence-index\n        metric = METRICS[self.metric_idx][1]\n        self.compute_distances(metric, self.data)\n\n    def compute_distances(self, metric, data):\n        def _check_sparse():\n            # pylint: disable=invalid-sequence-index\n            if issparse(data.X) and not metric.supports_sparse:\n                self.Error.dense_metric_sparse_data(METRICS[self.metric_idx][0])\n                return False\n            return True\n\n        def _fix_discrete():\n            nonlocal data\n            if data.domain.has_discrete_attributes() \\\n                    and metric is not distance.Jaccard \\\n                    and (issparse(data.X) and getattr(metric, \"fallback\", None)\n                         or not metric.supports_discrete\n                         or self.axis == 1):\n                if not data.domain.has_continuous_attributes():\n                    self.Error.no_continuous_features()\n                    return False\n                self.Warning.ignoring_discrete()\n                data = distance.remove_discrete_features(data)\n            return True\n\n        def _fix_nonbinary():\n            nonlocal data\n            if metric is distance.Jaccard and not issparse(data.X):\n                nbinary = sum(a.is_discrete and len(a.values) == 2\n                              for a in data.domain.attributes)\n                if not nbinary:\n                    self.Error.no_binary_features()\n                    return False\n                elif nbinary < len(data.domain.attributes):\n                    self.Warning.ignoring_nonbinary()\n                    data = distance.remove_nonbinary_features(data)\n            return True\n\n        def _fix_missing():\n            nonlocal data\n            if not metric.supports_missing and bn.anynan(data.X):\n                self.Warning.imputing_data()\n                data = distance.impute(data)\n            return True\n\n        def _check_tractability():\n            if metric is distance.Mahalanobis:\n                if self.axis == 1:\n                    # when computing distances by columns, we want < 100 rows\n                    if len(data) > 1000:\n                        self.Error.data_too_large_for_mahalanobis(\"rows\")\n                        return False\n                else:\n                    if len(data.domain.attributes) > 1000:\n                        self.Error.data_too_large_for_mahalanobis(\"columns\")\n                        return False\n            return True\n\n        self.clear_messages()\n        if data is not None:\n            for check in (_check_sparse, _check_tractability,\n                          _fix_discrete, _fix_missing, _fix_nonbinary):\n                if not check():\n                    data = None\n                    break\n\n        self.start(DistanceRunner.run, data, metric,\n                   self.normalized_dist, self.axis)\n\n    def on_partial_result(self, _):\n        pass\n\n    def on_done(self, result: Orange.misc.DistMatrix):\n        assert isinstance(result, Orange.misc.DistMatrix) or result is None\n        self.Outputs.distances.send(result)\n\n    def on_exception(self, ex):\n        if isinstance(ex, ValueError):\n            self.Error.distances_value_error(ex)\n        elif isinstance(ex, MemoryError):\n            self.Error.distances_memory_error()\n        elif isinstance(ex, InterruptException):\n            pass\n        else:\n            raise ex\n\n    def onDeleteWidget(self):\n        self.shutdown()\n        super().onDeleteWidget()\n\n    def _invalidate(self):\n        self.commit()\n\n    def _metric_changed(self):\n        metric = METRICS[self.metric_idx][1]\n        self.normalization_check.setEnabled(metric.supports_normalization)\n        self._invalidate()\n\n    def send_report(self):\n        # pylint: disable=invalid-sequence-index\n        self.report_items((\n            (\"Distances Between\", [\"Rows\", \"Columns\"][self.axis]),\n            (\"Metric\", METRICS[self.metric_idx][0])\n        ))\n\n    @classmethod\n    def migrate_settings(cls, settings, version):\n        if version is None or version < 2 and \"normalized_dist\" not in settings:\n            # normalize_dist is set to False when restoring settings from\n            # an older version to preserve old semantics.\n            settings[\"normalized_dist\"] = False\n        if version is None or version < 3:\n            # Mahalanobis was moved from idx = 2 to idx = 9\n            metric_idx = settings[\"metric_idx\"]\n            if metric_idx == 2:\n                settings[\"metric_idx\"] = 9\n            elif 2 < metric_idx <= 9:\n                settings[\"metric_idx\"] -= 1",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 55,
                            "end_lineno": 256,
                            "parent": null
                        }
                    ],
                    "added_entities": [],
                    "deleted_entities": []
                }
            ]
        },
        {
            "old_file_content": "# Test methods with long descriptive names can omit docstrings\n# pylint: disable=missing-docstring, protected-access\nimport unittest\nfrom unittest.mock import Mock\n\nimport numpy as np\n\nfrom Orange import distance\nfrom Orange.data import Table, Domain, ContinuousVariable\nfrom Orange.misc import DistMatrix\nfrom Orange.widgets.unsupervised.owdistances import OWDistances, METRICS, \\\n    DistanceRunner\nfrom Orange.widgets.tests.base import WidgetTest\n\n\nclass TestDistanceRunner(unittest.TestCase):\n    @classmethod\n    def setUpClass(cls):\n        super().setUpClass()\n        cls.iris = Table(\"iris\")[::5]\n        cls.iris.X[0, 2] = np.nan\n        cls.iris.X[1, 3] = np.nan\n        cls.iris.X[2, 1] = np.nan\n        cls.zoo = Table(\"zoo\")[::5]\n        cls.zoo.X[0, 2] = np.nan\n        cls.zoo.X[1, 3] = np.nan\n        cls.zoo.X[2, 1] = np.nan\n\n    def test_run(self):\n        state = Mock()\n        state.is_interruption_requested = Mock(return_value=False)\n        for name, metric in METRICS:\n            data = self.iris\n            if not metric.supports_missing or name == \"Bhattacharyya\":\n                data = distance.impute(data)\n            elif name == \"Jaccard\":\n                data = self.zoo\n\n            # between rows, normalized\n            dist1 = DistanceRunner.run(data, metric, True, 0, state)\n            dist2 = metric(data, axis=1, impute=True, normalize=True)\n            self.assertDistMatrixEqual(dist1, dist2)\n\n            # between rows, not normalized\n            dist1 = DistanceRunner.run(data, metric, False, 0, state)\n            dist2 = metric(data, axis=1, impute=True, normalize=False)\n            self.assertDistMatrixEqual(dist1, dist2)\n\n            # between columns, normalized\n            dist1 = DistanceRunner.run(data, metric, True, 1, state)\n            dist2 = metric(data, axis=0, impute=True, normalize=True)\n            self.assertDistMatrixEqual(dist1, dist2)\n\n            # between columns, not normalized\n            dist1 = DistanceRunner.run(data, metric, False, 1, state)\n            dist2 = metric(data, axis=0, impute=True, normalize=False)\n            self.assertDistMatrixEqual(dist1, dist2)\n\n    def assertDistMatrixEqual(self, dist1, dist2):\n        self.assertIsInstance(dist1, DistMatrix)\n        self.assertIsInstance(dist2, DistMatrix)\n        self.assertEqual(dist1.axis, dist2.axis)\n        self.assertEqual(dist1.row_items, dist2.row_items)\n        self.assertEqual(dist1.col_items, dist2.col_items)\n        np.testing.assert_array_almost_equal(dist1, dist2)\n\n\nclass TestOWDistances(WidgetTest):\n    @classmethod\n    def setUpClass(cls):\n        super().setUpClass()\n        cls.iris = Table(\"iris\")[::5]\n        cls.titanic = Table(\"titanic\")[::10]\n\n    def setUp(self):\n        self.widget = self.create_widget(OWDistances)\n\n    def test_distance_combo(self):\n        \"\"\"Check distances when the metric changes\"\"\"\n        self.assertEqual(self.widget.metrics_combo.count(), len(METRICS))\n        self.send_signal(self.widget.Inputs.data, self.iris)\n        for i, (_, metric) in enumerate(METRICS):\n            self.widget.metrics_combo.activated.emit(i)\n            self.widget.metrics_combo.setCurrentIndex(i)\n            self.wait_until_stop_blocking()\n            if metric.supports_normalization:\n                expected = metric(self.iris, normalize=self.widget.normalized_dist)\n            else:\n                expected = metric(self.iris)\n\n            if metric is not distance.Jaccard:\n                np.testing.assert_array_almost_equal(\n                    expected, self.get_output(self.widget.Outputs.distances))\n\n    def test_error_message(self):\n        \"\"\"Check if error message appears and then disappears when\n        data is removed from input\"\"\"\n        self.widget.metric_idx = 2\n        self.send_signal(self.widget.Inputs.data, self.iris)\n        self.wait_until_stop_blocking()\n        self.assertFalse(self.widget.Error.no_continuous_features.is_shown())\n        self.send_signal(self.widget.Inputs.data, self.titanic)\n        self.wait_until_stop_blocking()\n        self.assertTrue(self.widget.Error.no_continuous_features.is_shown())\n        self.send_signal(self.widget.Inputs.data, None)\n        self.assertFalse(self.widget.Error.no_continuous_features.is_shown())\n\n    def test_jaccard_messages(self):\n        for self.widget.metric_idx, (name, _) in enumerate(METRICS):\n            if name == \"Jaccard\":\n                break\n        self.send_signal(self.widget.Inputs.data, self.iris)\n        self.wait_until_stop_blocking()\n        self.assertTrue(self.widget.Error.no_binary_features.is_shown())\n        self.assertFalse(self.widget.Warning.ignoring_nonbinary.is_shown())\n\n        self.send_signal(self.widget.Inputs.data, None)\n        self.wait_until_stop_blocking()\n        self.assertFalse(self.widget.Error.no_binary_features.is_shown())\n        self.assertFalse(self.widget.Warning.ignoring_nonbinary.is_shown())\n\n        self.send_signal(self.widget.Inputs.data, self.titanic)\n        self.wait_until_stop_blocking()\n        self.assertFalse(self.widget.Error.no_binary_features.is_shown())\n        self.assertTrue(self.widget.Warning.ignoring_nonbinary.is_shown())\n\n        self.send_signal(self.widget.Inputs.data, None)\n        self.wait_until_stop_blocking()\n        self.assertFalse(self.widget.Error.no_binary_features.is_shown())\n        self.assertFalse(self.widget.Warning.ignoring_nonbinary.is_shown())\n\n        self.send_signal(self.widget.Inputs.data, self.titanic)\n        self.wait_until_stop_blocking()\n        self.assertFalse(self.widget.Error.no_binary_features.is_shown())\n        self.assertTrue(self.widget.Warning.ignoring_nonbinary.is_shown())\n\n        dom = self.titanic.domain\n        dom = Domain(dom.attributes[1:], dom.class_var)\n        self.send_signal(self.widget.Inputs.data, self.titanic.transform(dom))\n        self.wait_until_stop_blocking()\n        self.assertFalse(self.widget.Error.no_binary_features.is_shown())\n        self.assertFalse(self.widget.Warning.ignoring_nonbinary.is_shown())\n\n        self.send_signal(self.widget.Inputs.data, Table(\"heart_disease\"))\n        self.wait_until_stop_blocking()\n        self.assertFalse(self.widget.Error.no_binary_features.is_shown())\n        self.assertFalse(self.widget.Warning.ignoring_discrete.is_shown())\n\n    def test_too_big_array(self):\n        \"\"\"\n        Users sees an error message when calculating too large arrays and Orange\n        does not crash.\n        GH-2315\n        \"\"\"\n        self.assertEqual(len(self.widget.Error.active), 0)\n        self.send_signal(self.widget.Inputs.data, self.iris)\n\n        mock = Mock(side_effect=ValueError)\n        self.widget.compute_distances(mock, self.iris)\n        self.wait_until_finished()\n        self.assertTrue(self.widget.Error.distances_value_error.is_shown())\n\n        mock = Mock(side_effect=MemoryError)\n        self.widget.compute_distances(mock, self.iris)\n        self.wait_until_finished()\n        self.assertEqual(len(self.widget.Error.active), 1)\n        self.assertTrue(self.widget.Error.distances_memory_error.is_shown())\n\n    def test_migrates_normalized_dist(self):\n        w = self.create_widget(OWDistances, stored_settings={\"metric_idx\": 0})\n        self.assertFalse(w.normalized_dist)\n\n    def test_negative_values_bhattacharyya(self):\n        self.iris.X[0, 0] *= -1\n        for self.widget.metric_idx, (_, metric) in enumerate(METRICS):\n            if metric == distance.Bhattacharyya:\n                break\n        self.send_signal(self.widget.Inputs.data, self.iris)\n        self.wait_until_finished()\n        self.assertTrue(self.widget.Error.distances_value_error.is_shown())\n        self.iris.X[0, 0] *= -1\n\n    def test_limit_mahalanobis(self):\n        def assert_error_shown():\n            self.assertTrue(\n                self.widget.Error.data_too_large_for_mahalanobis.is_shown())\n\n        def assert_no_error():\n            self.assertFalse(\n                self.widget.Error.data_too_large_for_mahalanobis.is_shown())\n\n        widget = self.widget\n        axis_buttons = widget.controls.axis.buttons\n\n        self.assertEqual(widget.metrics_combo.count(), len(METRICS))\n        for i, (_, metric) in enumerate(METRICS):\n            if metric == distance.Mahalanobis:\n                widget.metrics_combo.setCurrentIndex(i)\n                widget.metrics_combo.activated.emit(i)\n                break\n\n        X = np.random.random((1010, 4))\n        bigrows = Table.from_numpy(Domain(self.iris.domain.attributes), X)\n        bigcols = Table.from_numpy(\n            Domain([ContinuousVariable(f\"{i}\") for i in range(1010)]), X.T)\n\n        self.send_signal(widget.Inputs.data, self.iris)\n        assert_no_error()\n\n        axis_buttons[0].click()\n        assert_no_error()\n        axis_buttons[1].click()\n        assert_no_error()\n\n        # by columns -- cannot handle too many rows\n        self.send_signal(self.widget.Inputs.data, bigrows)\n        assert_error_shown()\n        axis_buttons[0].click()\n        assert_no_error()\n        axis_buttons[1].click()\n        assert_error_shown()\n\n        self.send_signal(self.widget.Inputs.data, bigcols)\n        assert_no_error()\n        axis_buttons[0].click()\n        assert_error_shown()\n\n        self.send_signal(widget.Inputs.data, self.iris)\n        assert_no_error()\n\n\nif __name__ == \"__main__\":\n    unittest.main()\n",
            "new_file_content": "# Test methods with long descriptive names can omit docstrings\n# pylint: disable=missing-docstring, protected-access\nimport unittest\nfrom unittest.mock import Mock\n\nimport numpy as np\n\nfrom Orange import distance\nfrom Orange.data import Table, Domain, ContinuousVariable\nfrom Orange.misc import DistMatrix\nfrom Orange.widgets.unsupervised.owdistances import OWDistances, METRICS, \\\n    DistanceRunner\nfrom Orange.widgets.tests.base import WidgetTest\n\n\nclass TestDistanceRunner(unittest.TestCase):\n    @classmethod\n    def setUpClass(cls):\n        super().setUpClass()\n        cls.iris = Table(\"iris\")[::5]\n        cls.iris.X[0, 2] = np.nan\n        cls.iris.X[1, 3] = np.nan\n        cls.iris.X[2, 1] = np.nan\n        cls.zoo = Table(\"zoo\")[::5]\n        cls.zoo.X[0, 2] = np.nan\n        cls.zoo.X[1, 3] = np.nan\n        cls.zoo.X[2, 1] = np.nan\n\n    def test_run(self):\n        state = Mock()\n        state.is_interruption_requested = Mock(return_value=False)\n        for name, metric in METRICS:\n            data = self.iris\n            if not metric.supports_missing or name == \"Bhattacharyya\":\n                data = distance.impute(data)\n            elif name == \"Jaccard\":\n                data = self.zoo\n\n            # between rows, normalized\n            dist1 = DistanceRunner.run(data, metric, True, 0, state)\n            dist2 = metric(data, axis=1, impute=True, normalize=True)\n            self.assertDistMatrixEqual(dist1, dist2)\n\n            # between rows, not normalized\n            dist1 = DistanceRunner.run(data, metric, False, 0, state)\n            dist2 = metric(data, axis=1, impute=True, normalize=False)\n            self.assertDistMatrixEqual(dist1, dist2)\n\n            # between columns, normalized\n            dist1 = DistanceRunner.run(data, metric, True, 1, state)\n            dist2 = metric(data, axis=0, impute=True, normalize=True)\n            self.assertDistMatrixEqual(dist1, dist2)\n\n            # between columns, not normalized\n            dist1 = DistanceRunner.run(data, metric, False, 1, state)\n            dist2 = metric(data, axis=0, impute=True, normalize=False)\n            self.assertDistMatrixEqual(dist1, dist2)\n\n    def assertDistMatrixEqual(self, dist1, dist2):\n        self.assertIsInstance(dist1, DistMatrix)\n        self.assertIsInstance(dist2, DistMatrix)\n        self.assertEqual(dist1.axis, dist2.axis)\n        self.assertEqual(dist1.row_items, dist2.row_items)\n        self.assertEqual(dist1.col_items, dist2.col_items)\n        np.testing.assert_array_almost_equal(dist1, dist2)\n\n\nclass TestOWDistances(WidgetTest):\n    @classmethod\n    def setUpClass(cls):\n        super().setUpClass()\n        cls.iris = Table(\"iris\")[::5]\n        cls.titanic = Table(\"titanic\")[::10]\n\n    def setUp(self):\n        self.widget = self.create_widget(OWDistances)\n\n    def test_distance_combo(self):\n        \"\"\"Check distances when the metric changes\"\"\"\n        self.assertEqual(self.widget.metrics_combo.count(), len(METRICS))\n        self.send_signal(self.widget.Inputs.data, self.iris)\n        for i, (_, metric) in enumerate(METRICS):\n            self.widget.metrics_combo.activated.emit(i)\n            self.widget.metrics_combo.setCurrentIndex(i)\n            self.wait_until_stop_blocking()\n            if metric.supports_normalization:\n                expected = metric(self.iris, normalize=self.widget.normalized_dist)\n            else:\n                expected = metric(self.iris)\n\n            if metric is not distance.Jaccard:\n                np.testing.assert_array_almost_equal(\n                    expected, self.get_output(self.widget.Outputs.distances))\n\n    def test_error_message(self):\n        \"\"\"Check if error message appears and then disappears when\n        data is removed from input\"\"\"\n        self.widget.metric_idx = 2\n        self.send_signal(self.widget.Inputs.data, self.iris)\n        self.wait_until_stop_blocking()\n        self.assertFalse(self.widget.Error.no_continuous_features.is_shown())\n        self.send_signal(self.widget.Inputs.data, self.titanic)\n        self.wait_until_stop_blocking()\n        self.assertTrue(self.widget.Error.no_continuous_features.is_shown())\n        self.send_signal(self.widget.Inputs.data, None)\n        self.assertFalse(self.widget.Error.no_continuous_features.is_shown())\n\n    def test_jaccard_messages(self):\n        for self.widget.metric_idx, (name, _) in enumerate(METRICS):\n            if name == \"Jaccard\":\n                break\n        self.send_signal(self.widget.Inputs.data, self.iris)\n        self.wait_until_stop_blocking()\n        self.assertTrue(self.widget.Error.no_binary_features.is_shown())\n        self.assertFalse(self.widget.Warning.ignoring_nonbinary.is_shown())\n\n        self.send_signal(self.widget.Inputs.data, None)\n        self.wait_until_stop_blocking()\n        self.assertFalse(self.widget.Error.no_binary_features.is_shown())\n        self.assertFalse(self.widget.Warning.ignoring_nonbinary.is_shown())\n\n        self.send_signal(self.widget.Inputs.data, self.titanic)\n        self.wait_until_stop_blocking()\n        self.assertFalse(self.widget.Error.no_binary_features.is_shown())\n        self.assertTrue(self.widget.Warning.ignoring_nonbinary.is_shown())\n\n        self.send_signal(self.widget.Inputs.data, None)\n        self.wait_until_stop_blocking()\n        self.assertFalse(self.widget.Error.no_binary_features.is_shown())\n        self.assertFalse(self.widget.Warning.ignoring_nonbinary.is_shown())\n\n        self.send_signal(self.widget.Inputs.data, self.titanic)\n        self.wait_until_stop_blocking()\n        self.assertFalse(self.widget.Error.no_binary_features.is_shown())\n        self.assertTrue(self.widget.Warning.ignoring_nonbinary.is_shown())\n\n        dom = self.titanic.domain\n        dom = Domain(dom.attributes[1:], dom.class_var)\n        self.send_signal(self.widget.Inputs.data, self.titanic.transform(dom))\n        self.wait_until_stop_blocking()\n        self.assertFalse(self.widget.Error.no_binary_features.is_shown())\n        self.assertFalse(self.widget.Warning.ignoring_nonbinary.is_shown())\n\n        self.send_signal(self.widget.Inputs.data, Table(\"heart_disease\"))\n        self.wait_until_stop_blocking()\n        self.assertFalse(self.widget.Error.no_binary_features.is_shown())\n        self.assertFalse(self.widget.Warning.ignoring_discrete.is_shown())\n\n    def test_too_big_array(self):\n        \"\"\"\n        Users sees an error message when calculating too large arrays and Orange\n        does not crash.\n        GH-2315\n        \"\"\"\n        self.assertEqual(len(self.widget.Error.active), 0)\n        self.send_signal(self.widget.Inputs.data, self.iris)\n\n        mock = Mock(side_effect=ValueError)\n        self.widget.compute_distances(mock, self.iris)\n        self.wait_until_finished()\n        self.assertTrue(self.widget.Error.distances_value_error.is_shown())\n\n        mock = Mock(side_effect=MemoryError)\n        self.widget.compute_distances(mock, self.iris)\n        self.wait_until_finished()\n        self.assertEqual(len(self.widget.Error.active), 1)\n        self.assertTrue(self.widget.Error.distances_memory_error.is_shown())\n\n    def test_migrates_normalized_dist(self):\n        w = self.create_widget(OWDistances, stored_settings={\"metric_idx\": 0})\n        self.assertFalse(w.normalized_dist)\n\n    def test_negative_values_bhattacharyya(self):\n        self.iris.X[0, 0] *= -1\n        for self.widget.metric_idx, (_, metric) in enumerate(METRICS):\n            if metric == distance.Bhattacharyya:\n                break\n        self.send_signal(self.widget.Inputs.data, self.iris)\n        self.wait_until_finished()\n        self.assertTrue(self.widget.Error.distances_value_error.is_shown())\n        self.iris.X[0, 0] *= -1\n\n    def test_limit_mahalanobis(self):\n        def assert_error_shown():\n            self.assertTrue(\n                self.widget.Error.data_too_large_for_mahalanobis.is_shown())\n\n        def assert_no_error():\n            self.assertFalse(\n                self.widget.Error.data_too_large_for_mahalanobis.is_shown())\n\n        widget = self.widget\n        axis_buttons = widget.controls.axis.buttons\n\n        self.assertEqual(widget.metrics_combo.count(), len(METRICS))\n        for i, (_, metric) in enumerate(METRICS):\n            if metric == distance.Mahalanobis:\n                widget.metrics_combo.setCurrentIndex(i)\n                widget.metrics_combo.activated.emit(i)\n                break\n\n        X = np.random.random((1010, 4))\n        bigrows = Table.from_numpy(Domain(self.iris.domain.attributes), X)\n        bigcols = Table.from_numpy(\n            Domain([ContinuousVariable(f\"{i}\") for i in range(1010)]), X.T)\n\n        self.send_signal(widget.Inputs.data, self.iris)\n        assert_no_error()\n\n        axis_buttons[0].click()\n        assert_no_error()\n        axis_buttons[1].click()\n        assert_no_error()\n\n        # by columns -- cannot handle too many rows\n        self.send_signal(self.widget.Inputs.data, bigrows)\n        assert_error_shown()\n        axis_buttons[0].click()\n        assert_no_error()\n        axis_buttons[1].click()\n        assert_error_shown()\n\n        self.send_signal(self.widget.Inputs.data, bigcols)\n        assert_no_error()\n        axis_buttons[0].click()\n        assert_error_shown()\n\n        self.send_signal(widget.Inputs.data, self.iris)\n        assert_no_error()\n\n    def test_discrete_in_metas(self):\n        domain = self.iris.domain\n        data = self.iris.transform(\n            Domain(domain.attributes[:-1] + (domain.class_var, ),\n                   [],\n                   domain.attributes[-1:])\n        )\n        for self.widget.metric_idx, (_, metric) in enumerate(METRICS):\n            if metric == distance.Cosine:\n                break\n        self.send_signal(self.widget.Inputs.data, data)\n        self.wait_until_finished()\n        out = self.get_output(self.widget.Outputs.distances)\n        out_domain = out.row_items.domain\n        self.assertEqual(out_domain.attributes, domain.attributes[:-1])\n        self.assertEqual(out_domain.metas,\n                         (domain.attributes[-1], domain.class_var))\n\n    def test_non_binary_in_metas(self):\n        for self.widget.metric_idx, (_, metric) in enumerate(METRICS):\n            if metric == distance.Jaccard:\n                break\n        zoo = Table(\"zoo\")[:20]\n        self.send_signal(self.widget.Inputs.data, zoo)\n        self.wait_until_finished()\n        out = self.get_output(self.widget.Outputs.distances)\n        domain = zoo.domain\n        out_domain = out.row_items.domain\n        self.assertEqual(out_domain.metas, (domain[\"name\"], domain[\"legs\"]))\n\n\nif __name__ == \"__main__\":\n    unittest.main()\n",
            "header": {
                "file": {
                    "path": "Orange/widgets/unsupervised/tests/test_owdistances.py"
                },
                "misc_line": null
            },
            "index_line": {
                "old_commit_hash": "7935fc73c",
                "new_commit_hash": "44be93a33",
                "mode": "100644"
            },
            "is_binary_file": false,
            "binary_line": null,
            "minus_file": {
                "path": "a/Orange/widgets/unsupervised/tests/test_owdistances.py"
            },
            "plus_file": {
                "path": "b/Orange/widgets/unsupervised/tests/test_owdistances.py"
            },
            "hunks": [
                {
                    "descriptor": {
                        "old_range": {
                            "start": 228,
                            "length": 6
                        },
                        "new_range": {
                            "start": 228,
                            "length": 36
                        },
                        "section": "class TestOWDistances(WidgetTest):"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "        self.send_signal(widget.Inputs.data, self.iris)",
                                "type": "context"
                            },
                            {
                                "content": "        assert_no_error()",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "    def test_discrete_in_metas(self):",
                                "type": "added"
                            },
                            {
                                "content": "        domain = self.iris.domain",
                                "type": "added"
                            },
                            {
                                "content": "        data = self.iris.transform(",
                                "type": "added"
                            },
                            {
                                "content": "            Domain(domain.attributes[:-1] + (domain.class_var, ),",
                                "type": "added"
                            },
                            {
                                "content": "                   [],",
                                "type": "added"
                            },
                            {
                                "content": "                   domain.attributes[-1:])",
                                "type": "added"
                            },
                            {
                                "content": "        )",
                                "type": "added"
                            },
                            {
                                "content": "        for self.widget.metric_idx, (_, metric) in enumerate(METRICS):",
                                "type": "added"
                            },
                            {
                                "content": "            if metric == distance.Cosine:",
                                "type": "added"
                            },
                            {
                                "content": "                break",
                                "type": "added"
                            },
                            {
                                "content": "        self.send_signal(self.widget.Inputs.data, data)",
                                "type": "added"
                            },
                            {
                                "content": "        self.wait_until_finished()",
                                "type": "added"
                            },
                            {
                                "content": "        out = self.get_output(self.widget.Outputs.distances)",
                                "type": "added"
                            },
                            {
                                "content": "        out_domain = out.row_items.domain",
                                "type": "added"
                            },
                            {
                                "content": "        self.assertEqual(out_domain.attributes, domain.attributes[:-1])",
                                "type": "added"
                            },
                            {
                                "content": "        self.assertEqual(out_domain.metas,",
                                "type": "added"
                            },
                            {
                                "content": "                         (domain.attributes[-1], domain.class_var))",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "    def test_non_binary_in_metas(self):",
                                "type": "added"
                            },
                            {
                                "content": "        for self.widget.metric_idx, (_, metric) in enumerate(METRICS):",
                                "type": "added"
                            },
                            {
                                "content": "            if metric == distance.Jaccard:",
                                "type": "added"
                            },
                            {
                                "content": "                break",
                                "type": "added"
                            },
                            {
                                "content": "        zoo = Table(\"zoo\")[:20]",
                                "type": "added"
                            },
                            {
                                "content": "        self.send_signal(self.widget.Inputs.data, zoo)",
                                "type": "added"
                            },
                            {
                                "content": "        self.wait_until_finished()",
                                "type": "added"
                            },
                            {
                                "content": "        out = self.get_output(self.widget.Outputs.distances)",
                                "type": "added"
                            },
                            {
                                "content": "        domain = zoo.domain",
                                "type": "added"
                            },
                            {
                                "content": "        out_domain = out.row_items.domain",
                                "type": "added"
                            },
                            {
                                "content": "        self.assertEqual(out_domain.metas, (domain[\"name\"], domain[\"legs\"]))",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "if __name__ == \"__main__\":",
                                "type": "context"
                            },
                            {
                                "content": "    unittest.main()",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [
                        {
                            "file_name": "Orange/widgets/unsupervised/tests/test_owdistances.py",
                            "type": "class",
                            "name": "TestOWDistances",
                            "content": "class TestOWDistances(WidgetTest):\n    @classmethod\n    def setUpClass(cls):\n        super().setUpClass()\n        cls.iris = Table(\"iris\")[::5]\n        cls.titanic = Table(\"titanic\")[::10]\n\n    def setUp(self):\n        self.widget = self.create_widget(OWDistances)\n\n    def test_distance_combo(self):\n        \"\"\"Check distances when the metric changes\"\"\"\n        self.assertEqual(self.widget.metrics_combo.count(), len(METRICS))\n        self.send_signal(self.widget.Inputs.data, self.iris)\n        for i, (_, metric) in enumerate(METRICS):\n            self.widget.metrics_combo.activated.emit(i)\n            self.widget.metrics_combo.setCurrentIndex(i)\n            self.wait_until_stop_blocking()\n            if metric.supports_normalization:\n                expected = metric(self.iris, normalize=self.widget.normalized_dist)\n            else:\n                expected = metric(self.iris)\n\n            if metric is not distance.Jaccard:\n                np.testing.assert_array_almost_equal(\n                    expected, self.get_output(self.widget.Outputs.distances))\n\n    def test_error_message(self):\n        \"\"\"Check if error message appears and then disappears when\n        data is removed from input\"\"\"\n        self.widget.metric_idx = 2\n        self.send_signal(self.widget.Inputs.data, self.iris)\n        self.wait_until_stop_blocking()\n        self.assertFalse(self.widget.Error.no_continuous_features.is_shown())\n        self.send_signal(self.widget.Inputs.data, self.titanic)\n        self.wait_until_stop_blocking()\n        self.assertTrue(self.widget.Error.no_continuous_features.is_shown())\n        self.send_signal(self.widget.Inputs.data, None)\n        self.assertFalse(self.widget.Error.no_continuous_features.is_shown())\n\n    def test_jaccard_messages(self):\n        for self.widget.metric_idx, (name, _) in enumerate(METRICS):\n            if name == \"Jaccard\":\n                break\n        self.send_signal(self.widget.Inputs.data, self.iris)\n        self.wait_until_stop_blocking()\n        self.assertTrue(self.widget.Error.no_binary_features.is_shown())\n        self.assertFalse(self.widget.Warning.ignoring_nonbinary.is_shown())\n\n        self.send_signal(self.widget.Inputs.data, None)\n        self.wait_until_stop_blocking()\n        self.assertFalse(self.widget.Error.no_binary_features.is_shown())\n        self.assertFalse(self.widget.Warning.ignoring_nonbinary.is_shown())\n\n        self.send_signal(self.widget.Inputs.data, self.titanic)\n        self.wait_until_stop_blocking()\n        self.assertFalse(self.widget.Error.no_binary_features.is_shown())\n        self.assertTrue(self.widget.Warning.ignoring_nonbinary.is_shown())\n\n        self.send_signal(self.widget.Inputs.data, None)\n        self.wait_until_stop_blocking()\n        self.assertFalse(self.widget.Error.no_binary_features.is_shown())\n        self.assertFalse(self.widget.Warning.ignoring_nonbinary.is_shown())\n\n        self.send_signal(self.widget.Inputs.data, self.titanic)\n        self.wait_until_stop_blocking()\n        self.assertFalse(self.widget.Error.no_binary_features.is_shown())\n        self.assertTrue(self.widget.Warning.ignoring_nonbinary.is_shown())\n\n        dom = self.titanic.domain\n        dom = Domain(dom.attributes[1:], dom.class_var)\n        self.send_signal(self.widget.Inputs.data, self.titanic.transform(dom))\n        self.wait_until_stop_blocking()\n        self.assertFalse(self.widget.Error.no_binary_features.is_shown())\n        self.assertFalse(self.widget.Warning.ignoring_nonbinary.is_shown())\n\n        self.send_signal(self.widget.Inputs.data, Table(\"heart_disease\"))\n        self.wait_until_stop_blocking()\n        self.assertFalse(self.widget.Error.no_binary_features.is_shown())\n        self.assertFalse(self.widget.Warning.ignoring_discrete.is_shown())\n\n    def test_too_big_array(self):\n        \"\"\"\n        Users sees an error message when calculating too large arrays and Orange\n        does not crash.\n        GH-2315\n        \"\"\"\n        self.assertEqual(len(self.widget.Error.active), 0)\n        self.send_signal(self.widget.Inputs.data, self.iris)\n\n        mock = Mock(side_effect=ValueError)\n        self.widget.compute_distances(mock, self.iris)\n        self.wait_until_finished()\n        self.assertTrue(self.widget.Error.distances_value_error.is_shown())\n\n        mock = Mock(side_effect=MemoryError)\n        self.widget.compute_distances(mock, self.iris)\n        self.wait_until_finished()\n        self.assertEqual(len(self.widget.Error.active), 1)\n        self.assertTrue(self.widget.Error.distances_memory_error.is_shown())\n\n    def test_migrates_normalized_dist(self):\n        w = self.create_widget(OWDistances, stored_settings={\"metric_idx\": 0})\n        self.assertFalse(w.normalized_dist)\n\n    def test_negative_values_bhattacharyya(self):\n        self.iris.X[0, 0] *= -1\n        for self.widget.metric_idx, (_, metric) in enumerate(METRICS):\n            if metric == distance.Bhattacharyya:\n                break\n        self.send_signal(self.widget.Inputs.data, self.iris)\n        self.wait_until_finished()\n        self.assertTrue(self.widget.Error.distances_value_error.is_shown())\n        self.iris.X[0, 0] *= -1\n\n    def test_limit_mahalanobis(self):\n        def assert_error_shown():\n            self.assertTrue(\n                self.widget.Error.data_too_large_for_mahalanobis.is_shown())\n\n        def assert_no_error():\n            self.assertFalse(\n                self.widget.Error.data_too_large_for_mahalanobis.is_shown())\n\n        widget = self.widget\n        axis_buttons = widget.controls.axis.buttons\n\n        self.assertEqual(widget.metrics_combo.count(), len(METRICS))\n        for i, (_, metric) in enumerate(METRICS):\n            if metric == distance.Mahalanobis:\n                widget.metrics_combo.setCurrentIndex(i)\n                widget.metrics_combo.activated.emit(i)\n                break\n\n        X = np.random.random((1010, 4))\n        bigrows = Table.from_numpy(Domain(self.iris.domain.attributes), X)\n        bigcols = Table.from_numpy(\n            Domain([ContinuousVariable(f\"{i}\") for i in range(1010)]), X.T)\n\n        self.send_signal(widget.Inputs.data, self.iris)\n        assert_no_error()\n\n        axis_buttons[0].click()\n        assert_no_error()\n        axis_buttons[1].click()\n        assert_no_error()\n\n        # by columns -- cannot handle too many rows\n        self.send_signal(self.widget.Inputs.data, bigrows)\n        assert_error_shown()\n        axis_buttons[0].click()\n        assert_no_error()\n        axis_buttons[1].click()\n        assert_error_shown()\n\n        self.send_signal(self.widget.Inputs.data, bigcols)\n        assert_no_error()\n        axis_buttons[0].click()\n        assert_error_shown()\n\n        self.send_signal(widget.Inputs.data, self.iris)\n        assert_no_error()\n\n    def test_discrete_in_metas(self):\n        domain = self.iris.domain\n        data = self.iris.transform(\n            Domain(domain.attributes[:-1] + (domain.class_var, ),\n                   [],\n                   domain.attributes[-1:])\n        )\n        for self.widget.metric_idx, (_, metric) in enumerate(METRICS):\n            if metric == distance.Cosine:\n                break\n        self.send_signal(self.widget.Inputs.data, data)\n        self.wait_until_finished()\n        out = self.get_output(self.widget.Outputs.distances)\n        out_domain = out.row_items.domain\n        self.assertEqual(out_domain.attributes, domain.attributes[:-1])\n        self.assertEqual(out_domain.metas,\n                         (domain.attributes[-1], domain.class_var))\n\n    def test_non_binary_in_metas(self):\n        for self.widget.metric_idx, (_, metric) in enumerate(METRICS):\n            if metric == distance.Jaccard:\n                break\n        zoo = Table(\"zoo\")[:20]\n        self.send_signal(self.widget.Inputs.data, zoo)\n        self.wait_until_finished()\n        out = self.get_output(self.widget.Outputs.distances)\n        domain = zoo.domain\n        out_domain = out.row_items.domain\n        self.assertEqual(out_domain.metas, (domain[\"name\"], domain[\"legs\"]))",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 68,
                            "end_lineno": 259,
                            "parent": null
                        }
                    ],
                    "added_entities": [
                        {
                            "file_name": "Orange/widgets/unsupervised/tests/test_owdistances.py",
                            "type": "method",
                            "name": "TestOWDistances.test_discrete_in_metas",
                            "content": "class TestOWDistances(WidgetTest):\n    @classmethod\n    def setUpClass(cls):\n        super().setUpClass()\n        cls.iris = Table(\"iris\")[::5]\n        cls.titanic = Table(\"titanic\")[::10]\n\n    def setUp(self):\n        self.widget = self.create_widget(OWDistances)\n\n    def test_distance_combo(self):\n        \"\"\"Check distances when the metric changes\"\"\"\n        self.assertEqual(self.widget.metrics_combo.count(), len(METRICS))\n        self.send_signal(self.widget.Inputs.data, self.iris)\n        for i, (_, metric) in enumerate(METRICS):\n            self.widget.metrics_combo.activated.emit(i)\n            self.widget.metrics_combo.setCurrentIndex(i)\n            self.wait_until_stop_blocking()\n            if metric.supports_normalization:\n                expected = metric(self.iris, normalize=self.widget.normalized_dist)\n            else:\n                expected = metric(self.iris)\n\n            if metric is not distance.Jaccard:\n                np.testing.assert_array_almost_equal(\n                    expected, self.get_output(self.widget.Outputs.distances))\n\n    def test_error_message(self):\n        \"\"\"Check if error message appears and then disappears when\n        data is removed from input\"\"\"\n        self.widget.metric_idx = 2\n        self.send_signal(self.widget.Inputs.data, self.iris)\n        self.wait_until_stop_blocking()\n        self.assertFalse(self.widget.Error.no_continuous_features.is_shown())\n        self.send_signal(self.widget.Inputs.data, self.titanic)\n        self.wait_until_stop_blocking()\n        self.assertTrue(self.widget.Error.no_continuous_features.is_shown())\n        self.send_signal(self.widget.Inputs.data, None)\n        self.assertFalse(self.widget.Error.no_continuous_features.is_shown())\n\n    def test_jaccard_messages(self):\n        for self.widget.metric_idx, (name, _) in enumerate(METRICS):\n            if name == \"Jaccard\":\n                break\n        self.send_signal(self.widget.Inputs.data, self.iris)\n        self.wait_until_stop_blocking()\n        self.assertTrue(self.widget.Error.no_binary_features.is_shown())\n        self.assertFalse(self.widget.Warning.ignoring_nonbinary.is_shown())\n\n        self.send_signal(self.widget.Inputs.data, None)\n        self.wait_until_stop_blocking()\n        self.assertFalse(self.widget.Error.no_binary_features.is_shown())\n        self.assertFalse(self.widget.Warning.ignoring_nonbinary.is_shown())\n\n        self.send_signal(self.widget.Inputs.data, self.titanic)\n        self.wait_until_stop_blocking()\n        self.assertFalse(self.widget.Error.no_binary_features.is_shown())\n        self.assertTrue(self.widget.Warning.ignoring_nonbinary.is_shown())\n\n        self.send_signal(self.widget.Inputs.data, None)\n        self.wait_until_stop_blocking()\n        self.assertFalse(self.widget.Error.no_binary_features.is_shown())\n        self.assertFalse(self.widget.Warning.ignoring_nonbinary.is_shown())\n\n        self.send_signal(self.widget.Inputs.data, self.titanic)\n        self.wait_until_stop_blocking()\n        self.assertFalse(self.widget.Error.no_binary_features.is_shown())\n        self.assertTrue(self.widget.Warning.ignoring_nonbinary.is_shown())\n\n        dom = self.titanic.domain\n        dom = Domain(dom.attributes[1:], dom.class_var)\n        self.send_signal(self.widget.Inputs.data, self.titanic.transform(dom))\n        self.wait_until_stop_blocking()\n        self.assertFalse(self.widget.Error.no_binary_features.is_shown())\n        self.assertFalse(self.widget.Warning.ignoring_nonbinary.is_shown())\n\n        self.send_signal(self.widget.Inputs.data, Table(\"heart_disease\"))\n        self.wait_until_stop_blocking()\n        self.assertFalse(self.widget.Error.no_binary_features.is_shown())\n        self.assertFalse(self.widget.Warning.ignoring_discrete.is_shown())\n\n    def test_too_big_array(self):\n        \"\"\"\n        Users sees an error message when calculating too large arrays and Orange\n        does not crash.\n        GH-2315\n        \"\"\"\n        self.assertEqual(len(self.widget.Error.active), 0)\n        self.send_signal(self.widget.Inputs.data, self.iris)\n\n        mock = Mock(side_effect=ValueError)\n        self.widget.compute_distances(mock, self.iris)\n        self.wait_until_finished()\n        self.assertTrue(self.widget.Error.distances_value_error.is_shown())\n\n        mock = Mock(side_effect=MemoryError)\n        self.widget.compute_distances(mock, self.iris)\n        self.wait_until_finished()\n        self.assertEqual(len(self.widget.Error.active), 1)\n        self.assertTrue(self.widget.Error.distances_memory_error.is_shown())\n\n    def test_migrates_normalized_dist(self):\n        w = self.create_widget(OWDistances, stored_settings={\"metric_idx\": 0})\n        self.assertFalse(w.normalized_dist)\n\n    def test_negative_values_bhattacharyya(self):\n        self.iris.X[0, 0] *= -1\n        for self.widget.metric_idx, (_, metric) in enumerate(METRICS):\n            if metric == distance.Bhattacharyya:\n                break\n        self.send_signal(self.widget.Inputs.data, self.iris)\n        self.wait_until_finished()\n        self.assertTrue(self.widget.Error.distances_value_error.is_shown())\n        self.iris.X[0, 0] *= -1\n\n    def test_limit_mahalanobis(self):\n        def assert_error_shown():\n            self.assertTrue(\n                self.widget.Error.data_too_large_for_mahalanobis.is_shown())\n\n        def assert_no_error():\n            self.assertFalse(\n                self.widget.Error.data_too_large_for_mahalanobis.is_shown())\n\n        widget = self.widget\n        axis_buttons = widget.controls.axis.buttons\n\n        self.assertEqual(widget.metrics_combo.count(), len(METRICS))\n        for i, (_, metric) in enumerate(METRICS):\n            if metric == distance.Mahalanobis:\n                widget.metrics_combo.setCurrentIndex(i)\n                widget.metrics_combo.activated.emit(i)\n                break\n\n        X = np.random.random((1010, 4))\n        bigrows = Table.from_numpy(Domain(self.iris.domain.attributes), X)\n        bigcols = Table.from_numpy(\n            Domain([ContinuousVariable(f\"{i}\") for i in range(1010)]), X.T)\n\n        self.send_signal(widget.Inputs.data, self.iris)\n        assert_no_error()\n\n        axis_buttons[0].click()\n        assert_no_error()\n        axis_buttons[1].click()\n        assert_no_error()\n\n        # by columns -- cannot handle too many rows\n        self.send_signal(self.widget.Inputs.data, bigrows)\n        assert_error_shown()\n        axis_buttons[0].click()\n        assert_no_error()\n        axis_buttons[1].click()\n        assert_error_shown()\n\n        self.send_signal(self.widget.Inputs.data, bigcols)\n        assert_no_error()\n        axis_buttons[0].click()\n        assert_error_shown()\n\n        self.send_signal(widget.Inputs.data, self.iris)\n        assert_no_error()\n\n    def test_discrete_in_metas(self):\n        domain = self.iris.domain\n        data = self.iris.transform(\n            Domain(domain.attributes[:-1] + (domain.class_var, ),\n                   [],\n                   domain.attributes[-1:])\n        )\n        for self.widget.metric_idx, (_, metric) in enumerate(METRICS):\n            if metric == distance.Cosine:\n                break\n        self.send_signal(self.widget.Inputs.data, data)\n        self.wait_until_finished()\n        out = self.get_output(self.widget.Outputs.distances)\n        out_domain = out.row_items.domain\n        self.assertEqual(out_domain.attributes, domain.attributes[:-1])\n        self.assertEqual(out_domain.metas,\n                         (domain.attributes[-1], domain.class_var))\n\n    def test_non_binary_in_metas(self):\n        for self.widget.metric_idx, (_, metric) in enumerate(METRICS):\n            if metric == distance.Jaccard:\n                break\n        zoo = Table(\"zoo\")[:20]\n        self.send_signal(self.widget.Inputs.data, zoo)\n        self.wait_until_finished()\n        out = self.get_output(self.widget.Outputs.distances)\n        domain = zoo.domain\n        out_domain = out.row_items.domain\n        self.assertEqual(out_domain.metas, (domain[\"name\"], domain[\"legs\"]))",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 231,
                            "end_lineno": 247,
                            "parent": {
                                "file_name": "Orange/widgets/unsupervised/tests/test_owdistances.py",
                                "type": "class",
                                "name": "TestOWDistances",
                                "content": "class TestOWDistances(WidgetTest):\n    @classmethod\n    def setUpClass(cls):\n        super().setUpClass()\n        cls.iris = Table(\"iris\")[::5]\n        cls.titanic = Table(\"titanic\")[::10]\n\n    def setUp(self):\n        self.widget = self.create_widget(OWDistances)\n\n    def test_distance_combo(self):\n        \"\"\"Check distances when the metric changes\"\"\"\n        self.assertEqual(self.widget.metrics_combo.count(), len(METRICS))\n        self.send_signal(self.widget.Inputs.data, self.iris)\n        for i, (_, metric) in enumerate(METRICS):\n            self.widget.metrics_combo.activated.emit(i)\n            self.widget.metrics_combo.setCurrentIndex(i)\n            self.wait_until_stop_blocking()\n            if metric.supports_normalization:\n                expected = metric(self.iris, normalize=self.widget.normalized_dist)\n            else:\n                expected = metric(self.iris)\n\n            if metric is not distance.Jaccard:\n                np.testing.assert_array_almost_equal(\n                    expected, self.get_output(self.widget.Outputs.distances))\n\n    def test_error_message(self):\n        \"\"\"Check if error message appears and then disappears when\n        data is removed from input\"\"\"\n        self.widget.metric_idx = 2\n        self.send_signal(self.widget.Inputs.data, self.iris)\n        self.wait_until_stop_blocking()\n        self.assertFalse(self.widget.Error.no_continuous_features.is_shown())\n        self.send_signal(self.widget.Inputs.data, self.titanic)\n        self.wait_until_stop_blocking()\n        self.assertTrue(self.widget.Error.no_continuous_features.is_shown())\n        self.send_signal(self.widget.Inputs.data, None)\n        self.assertFalse(self.widget.Error.no_continuous_features.is_shown())\n\n    def test_jaccard_messages(self):\n        for self.widget.metric_idx, (name, _) in enumerate(METRICS):\n            if name == \"Jaccard\":\n                break\n        self.send_signal(self.widget.Inputs.data, self.iris)\n        self.wait_until_stop_blocking()\n        self.assertTrue(self.widget.Error.no_binary_features.is_shown())\n        self.assertFalse(self.widget.Warning.ignoring_nonbinary.is_shown())\n\n        self.send_signal(self.widget.Inputs.data, None)\n        self.wait_until_stop_blocking()\n        self.assertFalse(self.widget.Error.no_binary_features.is_shown())\n        self.assertFalse(self.widget.Warning.ignoring_nonbinary.is_shown())\n\n        self.send_signal(self.widget.Inputs.data, self.titanic)\n        self.wait_until_stop_blocking()\n        self.assertFalse(self.widget.Error.no_binary_features.is_shown())\n        self.assertTrue(self.widget.Warning.ignoring_nonbinary.is_shown())\n\n        self.send_signal(self.widget.Inputs.data, None)\n        self.wait_until_stop_blocking()\n        self.assertFalse(self.widget.Error.no_binary_features.is_shown())\n        self.assertFalse(self.widget.Warning.ignoring_nonbinary.is_shown())\n\n        self.send_signal(self.widget.Inputs.data, self.titanic)\n        self.wait_until_stop_blocking()\n        self.assertFalse(self.widget.Error.no_binary_features.is_shown())\n        self.assertTrue(self.widget.Warning.ignoring_nonbinary.is_shown())\n\n        dom = self.titanic.domain\n        dom = Domain(dom.attributes[1:], dom.class_var)\n        self.send_signal(self.widget.Inputs.data, self.titanic.transform(dom))\n        self.wait_until_stop_blocking()\n        self.assertFalse(self.widget.Error.no_binary_features.is_shown())\n        self.assertFalse(self.widget.Warning.ignoring_nonbinary.is_shown())\n\n        self.send_signal(self.widget.Inputs.data, Table(\"heart_disease\"))\n        self.wait_until_stop_blocking()\n        self.assertFalse(self.widget.Error.no_binary_features.is_shown())\n        self.assertFalse(self.widget.Warning.ignoring_discrete.is_shown())\n\n    def test_too_big_array(self):\n        \"\"\"\n        Users sees an error message when calculating too large arrays and Orange\n        does not crash.\n        GH-2315\n        \"\"\"\n        self.assertEqual(len(self.widget.Error.active), 0)\n        self.send_signal(self.widget.Inputs.data, self.iris)\n\n        mock = Mock(side_effect=ValueError)\n        self.widget.compute_distances(mock, self.iris)\n        self.wait_until_finished()\n        self.assertTrue(self.widget.Error.distances_value_error.is_shown())\n\n        mock = Mock(side_effect=MemoryError)\n        self.widget.compute_distances(mock, self.iris)\n        self.wait_until_finished()\n        self.assertEqual(len(self.widget.Error.active), 1)\n        self.assertTrue(self.widget.Error.distances_memory_error.is_shown())\n\n    def test_migrates_normalized_dist(self):\n        w = self.create_widget(OWDistances, stored_settings={\"metric_idx\": 0})\n        self.assertFalse(w.normalized_dist)\n\n    def test_negative_values_bhattacharyya(self):\n        self.iris.X[0, 0] *= -1\n        for self.widget.metric_idx, (_, metric) in enumerate(METRICS):\n            if metric == distance.Bhattacharyya:\n                break\n        self.send_signal(self.widget.Inputs.data, self.iris)\n        self.wait_until_finished()\n        self.assertTrue(self.widget.Error.distances_value_error.is_shown())\n        self.iris.X[0, 0] *= -1\n\n    def test_limit_mahalanobis(self):\n        def assert_error_shown():\n            self.assertTrue(\n                self.widget.Error.data_too_large_for_mahalanobis.is_shown())\n\n        def assert_no_error():\n            self.assertFalse(\n                self.widget.Error.data_too_large_for_mahalanobis.is_shown())\n\n        widget = self.widget\n        axis_buttons = widget.controls.axis.buttons\n\n        self.assertEqual(widget.metrics_combo.count(), len(METRICS))\n        for i, (_, metric) in enumerate(METRICS):\n            if metric == distance.Mahalanobis:\n                widget.metrics_combo.setCurrentIndex(i)\n                widget.metrics_combo.activated.emit(i)\n                break\n\n        X = np.random.random((1010, 4))\n        bigrows = Table.from_numpy(Domain(self.iris.domain.attributes), X)\n        bigcols = Table.from_numpy(\n            Domain([ContinuousVariable(f\"{i}\") for i in range(1010)]), X.T)\n\n        self.send_signal(widget.Inputs.data, self.iris)\n        assert_no_error()\n\n        axis_buttons[0].click()\n        assert_no_error()\n        axis_buttons[1].click()\n        assert_no_error()\n\n        # by columns -- cannot handle too many rows\n        self.send_signal(self.widget.Inputs.data, bigrows)\n        assert_error_shown()\n        axis_buttons[0].click()\n        assert_no_error()\n        axis_buttons[1].click()\n        assert_error_shown()\n\n        self.send_signal(self.widget.Inputs.data, bigcols)\n        assert_no_error()\n        axis_buttons[0].click()\n        assert_error_shown()\n\n        self.send_signal(widget.Inputs.data, self.iris)\n        assert_no_error()\n\n    def test_discrete_in_metas(self):\n        domain = self.iris.domain\n        data = self.iris.transform(\n            Domain(domain.attributes[:-1] + (domain.class_var, ),\n                   [],\n                   domain.attributes[-1:])\n        )\n        for self.widget.metric_idx, (_, metric) in enumerate(METRICS):\n            if metric == distance.Cosine:\n                break\n        self.send_signal(self.widget.Inputs.data, data)\n        self.wait_until_finished()\n        out = self.get_output(self.widget.Outputs.distances)\n        out_domain = out.row_items.domain\n        self.assertEqual(out_domain.attributes, domain.attributes[:-1])\n        self.assertEqual(out_domain.metas,\n                         (domain.attributes[-1], domain.class_var))\n\n    def test_non_binary_in_metas(self):\n        for self.widget.metric_idx, (_, metric) in enumerate(METRICS):\n            if metric == distance.Jaccard:\n                break\n        zoo = Table(\"zoo\")[:20]\n        self.send_signal(self.widget.Inputs.data, zoo)\n        self.wait_until_finished()\n        out = self.get_output(self.widget.Outputs.distances)\n        domain = zoo.domain\n        out_domain = out.row_items.domain\n        self.assertEqual(out_domain.metas, (domain[\"name\"], domain[\"legs\"]))",
                                "ast_type_str": "ClassDef",
                                "start_lineno": 68,
                                "end_lineno": 259,
                                "parent": null
                            }
                        },
                        {
                            "file_name": "Orange/widgets/unsupervised/tests/test_owdistances.py",
                            "type": "method",
                            "name": "TestOWDistances.test_non_binary_in_metas",
                            "content": "class TestOWDistances(WidgetTest):\n    @classmethod\n    def setUpClass(cls):\n        super().setUpClass()\n        cls.iris = Table(\"iris\")[::5]\n        cls.titanic = Table(\"titanic\")[::10]\n\n    def setUp(self):\n        self.widget = self.create_widget(OWDistances)\n\n    def test_distance_combo(self):\n        \"\"\"Check distances when the metric changes\"\"\"\n        self.assertEqual(self.widget.metrics_combo.count(), len(METRICS))\n        self.send_signal(self.widget.Inputs.data, self.iris)\n        for i, (_, metric) in enumerate(METRICS):\n            self.widget.metrics_combo.activated.emit(i)\n            self.widget.metrics_combo.setCurrentIndex(i)\n            self.wait_until_stop_blocking()\n            if metric.supports_normalization:\n                expected = metric(self.iris, normalize=self.widget.normalized_dist)\n            else:\n                expected = metric(self.iris)\n\n            if metric is not distance.Jaccard:\n                np.testing.assert_array_almost_equal(\n                    expected, self.get_output(self.widget.Outputs.distances))\n\n    def test_error_message(self):\n        \"\"\"Check if error message appears and then disappears when\n        data is removed from input\"\"\"\n        self.widget.metric_idx = 2\n        self.send_signal(self.widget.Inputs.data, self.iris)\n        self.wait_until_stop_blocking()\n        self.assertFalse(self.widget.Error.no_continuous_features.is_shown())\n        self.send_signal(self.widget.Inputs.data, self.titanic)\n        self.wait_until_stop_blocking()\n        self.assertTrue(self.widget.Error.no_continuous_features.is_shown())\n        self.send_signal(self.widget.Inputs.data, None)\n        self.assertFalse(self.widget.Error.no_continuous_features.is_shown())\n\n    def test_jaccard_messages(self):\n        for self.widget.metric_idx, (name, _) in enumerate(METRICS):\n            if name == \"Jaccard\":\n                break\n        self.send_signal(self.widget.Inputs.data, self.iris)\n        self.wait_until_stop_blocking()\n        self.assertTrue(self.widget.Error.no_binary_features.is_shown())\n        self.assertFalse(self.widget.Warning.ignoring_nonbinary.is_shown())\n\n        self.send_signal(self.widget.Inputs.data, None)\n        self.wait_until_stop_blocking()\n        self.assertFalse(self.widget.Error.no_binary_features.is_shown())\n        self.assertFalse(self.widget.Warning.ignoring_nonbinary.is_shown())\n\n        self.send_signal(self.widget.Inputs.data, self.titanic)\n        self.wait_until_stop_blocking()\n        self.assertFalse(self.widget.Error.no_binary_features.is_shown())\n        self.assertTrue(self.widget.Warning.ignoring_nonbinary.is_shown())\n\n        self.send_signal(self.widget.Inputs.data, None)\n        self.wait_until_stop_blocking()\n        self.assertFalse(self.widget.Error.no_binary_features.is_shown())\n        self.assertFalse(self.widget.Warning.ignoring_nonbinary.is_shown())\n\n        self.send_signal(self.widget.Inputs.data, self.titanic)\n        self.wait_until_stop_blocking()\n        self.assertFalse(self.widget.Error.no_binary_features.is_shown())\n        self.assertTrue(self.widget.Warning.ignoring_nonbinary.is_shown())\n\n        dom = self.titanic.domain\n        dom = Domain(dom.attributes[1:], dom.class_var)\n        self.send_signal(self.widget.Inputs.data, self.titanic.transform(dom))\n        self.wait_until_stop_blocking()\n        self.assertFalse(self.widget.Error.no_binary_features.is_shown())\n        self.assertFalse(self.widget.Warning.ignoring_nonbinary.is_shown())\n\n        self.send_signal(self.widget.Inputs.data, Table(\"heart_disease\"))\n        self.wait_until_stop_blocking()\n        self.assertFalse(self.widget.Error.no_binary_features.is_shown())\n        self.assertFalse(self.widget.Warning.ignoring_discrete.is_shown())\n\n    def test_too_big_array(self):\n        \"\"\"\n        Users sees an error message when calculating too large arrays and Orange\n        does not crash.\n        GH-2315\n        \"\"\"\n        self.assertEqual(len(self.widget.Error.active), 0)\n        self.send_signal(self.widget.Inputs.data, self.iris)\n\n        mock = Mock(side_effect=ValueError)\n        self.widget.compute_distances(mock, self.iris)\n        self.wait_until_finished()\n        self.assertTrue(self.widget.Error.distances_value_error.is_shown())\n\n        mock = Mock(side_effect=MemoryError)\n        self.widget.compute_distances(mock, self.iris)\n        self.wait_until_finished()\n        self.assertEqual(len(self.widget.Error.active), 1)\n        self.assertTrue(self.widget.Error.distances_memory_error.is_shown())\n\n    def test_migrates_normalized_dist(self):\n        w = self.create_widget(OWDistances, stored_settings={\"metric_idx\": 0})\n        self.assertFalse(w.normalized_dist)\n\n    def test_negative_values_bhattacharyya(self):\n        self.iris.X[0, 0] *= -1\n        for self.widget.metric_idx, (_, metric) in enumerate(METRICS):\n            if metric == distance.Bhattacharyya:\n                break\n        self.send_signal(self.widget.Inputs.data, self.iris)\n        self.wait_until_finished()\n        self.assertTrue(self.widget.Error.distances_value_error.is_shown())\n        self.iris.X[0, 0] *= -1\n\n    def test_limit_mahalanobis(self):\n        def assert_error_shown():\n            self.assertTrue(\n                self.widget.Error.data_too_large_for_mahalanobis.is_shown())\n\n        def assert_no_error():\n            self.assertFalse(\n                self.widget.Error.data_too_large_for_mahalanobis.is_shown())\n\n        widget = self.widget\n        axis_buttons = widget.controls.axis.buttons\n\n        self.assertEqual(widget.metrics_combo.count(), len(METRICS))\n        for i, (_, metric) in enumerate(METRICS):\n            if metric == distance.Mahalanobis:\n                widget.metrics_combo.setCurrentIndex(i)\n                widget.metrics_combo.activated.emit(i)\n                break\n\n        X = np.random.random((1010, 4))\n        bigrows = Table.from_numpy(Domain(self.iris.domain.attributes), X)\n        bigcols = Table.from_numpy(\n            Domain([ContinuousVariable(f\"{i}\") for i in range(1010)]), X.T)\n\n        self.send_signal(widget.Inputs.data, self.iris)\n        assert_no_error()\n\n        axis_buttons[0].click()\n        assert_no_error()\n        axis_buttons[1].click()\n        assert_no_error()\n\n        # by columns -- cannot handle too many rows\n        self.send_signal(self.widget.Inputs.data, bigrows)\n        assert_error_shown()\n        axis_buttons[0].click()\n        assert_no_error()\n        axis_buttons[1].click()\n        assert_error_shown()\n\n        self.send_signal(self.widget.Inputs.data, bigcols)\n        assert_no_error()\n        axis_buttons[0].click()\n        assert_error_shown()\n\n        self.send_signal(widget.Inputs.data, self.iris)\n        assert_no_error()\n\n    def test_discrete_in_metas(self):\n        domain = self.iris.domain\n        data = self.iris.transform(\n            Domain(domain.attributes[:-1] + (domain.class_var, ),\n                   [],\n                   domain.attributes[-1:])\n        )\n        for self.widget.metric_idx, (_, metric) in enumerate(METRICS):\n            if metric == distance.Cosine:\n                break\n        self.send_signal(self.widget.Inputs.data, data)\n        self.wait_until_finished()\n        out = self.get_output(self.widget.Outputs.distances)\n        out_domain = out.row_items.domain\n        self.assertEqual(out_domain.attributes, domain.attributes[:-1])\n        self.assertEqual(out_domain.metas,\n                         (domain.attributes[-1], domain.class_var))\n\n    def test_non_binary_in_metas(self):\n        for self.widget.metric_idx, (_, metric) in enumerate(METRICS):\n            if metric == distance.Jaccard:\n                break\n        zoo = Table(\"zoo\")[:20]\n        self.send_signal(self.widget.Inputs.data, zoo)\n        self.wait_until_finished()\n        out = self.get_output(self.widget.Outputs.distances)\n        domain = zoo.domain\n        out_domain = out.row_items.domain\n        self.assertEqual(out_domain.metas, (domain[\"name\"], domain[\"legs\"]))",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 249,
                            "end_lineno": 259,
                            "parent": {
                                "file_name": "Orange/widgets/unsupervised/tests/test_owdistances.py",
                                "type": "class",
                                "name": "TestOWDistances",
                                "content": "class TestOWDistances(WidgetTest):\n    @classmethod\n    def setUpClass(cls):\n        super().setUpClass()\n        cls.iris = Table(\"iris\")[::5]\n        cls.titanic = Table(\"titanic\")[::10]\n\n    def setUp(self):\n        self.widget = self.create_widget(OWDistances)\n\n    def test_distance_combo(self):\n        \"\"\"Check distances when the metric changes\"\"\"\n        self.assertEqual(self.widget.metrics_combo.count(), len(METRICS))\n        self.send_signal(self.widget.Inputs.data, self.iris)\n        for i, (_, metric) in enumerate(METRICS):\n            self.widget.metrics_combo.activated.emit(i)\n            self.widget.metrics_combo.setCurrentIndex(i)\n            self.wait_until_stop_blocking()\n            if metric.supports_normalization:\n                expected = metric(self.iris, normalize=self.widget.normalized_dist)\n            else:\n                expected = metric(self.iris)\n\n            if metric is not distance.Jaccard:\n                np.testing.assert_array_almost_equal(\n                    expected, self.get_output(self.widget.Outputs.distances))\n\n    def test_error_message(self):\n        \"\"\"Check if error message appears and then disappears when\n        data is removed from input\"\"\"\n        self.widget.metric_idx = 2\n        self.send_signal(self.widget.Inputs.data, self.iris)\n        self.wait_until_stop_blocking()\n        self.assertFalse(self.widget.Error.no_continuous_features.is_shown())\n        self.send_signal(self.widget.Inputs.data, self.titanic)\n        self.wait_until_stop_blocking()\n        self.assertTrue(self.widget.Error.no_continuous_features.is_shown())\n        self.send_signal(self.widget.Inputs.data, None)\n        self.assertFalse(self.widget.Error.no_continuous_features.is_shown())\n\n    def test_jaccard_messages(self):\n        for self.widget.metric_idx, (name, _) in enumerate(METRICS):\n            if name == \"Jaccard\":\n                break\n        self.send_signal(self.widget.Inputs.data, self.iris)\n        self.wait_until_stop_blocking()\n        self.assertTrue(self.widget.Error.no_binary_features.is_shown())\n        self.assertFalse(self.widget.Warning.ignoring_nonbinary.is_shown())\n\n        self.send_signal(self.widget.Inputs.data, None)\n        self.wait_until_stop_blocking()\n        self.assertFalse(self.widget.Error.no_binary_features.is_shown())\n        self.assertFalse(self.widget.Warning.ignoring_nonbinary.is_shown())\n\n        self.send_signal(self.widget.Inputs.data, self.titanic)\n        self.wait_until_stop_blocking()\n        self.assertFalse(self.widget.Error.no_binary_features.is_shown())\n        self.assertTrue(self.widget.Warning.ignoring_nonbinary.is_shown())\n\n        self.send_signal(self.widget.Inputs.data, None)\n        self.wait_until_stop_blocking()\n        self.assertFalse(self.widget.Error.no_binary_features.is_shown())\n        self.assertFalse(self.widget.Warning.ignoring_nonbinary.is_shown())\n\n        self.send_signal(self.widget.Inputs.data, self.titanic)\n        self.wait_until_stop_blocking()\n        self.assertFalse(self.widget.Error.no_binary_features.is_shown())\n        self.assertTrue(self.widget.Warning.ignoring_nonbinary.is_shown())\n\n        dom = self.titanic.domain\n        dom = Domain(dom.attributes[1:], dom.class_var)\n        self.send_signal(self.widget.Inputs.data, self.titanic.transform(dom))\n        self.wait_until_stop_blocking()\n        self.assertFalse(self.widget.Error.no_binary_features.is_shown())\n        self.assertFalse(self.widget.Warning.ignoring_nonbinary.is_shown())\n\n        self.send_signal(self.widget.Inputs.data, Table(\"heart_disease\"))\n        self.wait_until_stop_blocking()\n        self.assertFalse(self.widget.Error.no_binary_features.is_shown())\n        self.assertFalse(self.widget.Warning.ignoring_discrete.is_shown())\n\n    def test_too_big_array(self):\n        \"\"\"\n        Users sees an error message when calculating too large arrays and Orange\n        does not crash.\n        GH-2315\n        \"\"\"\n        self.assertEqual(len(self.widget.Error.active), 0)\n        self.send_signal(self.widget.Inputs.data, self.iris)\n\n        mock = Mock(side_effect=ValueError)\n        self.widget.compute_distances(mock, self.iris)\n        self.wait_until_finished()\n        self.assertTrue(self.widget.Error.distances_value_error.is_shown())\n\n        mock = Mock(side_effect=MemoryError)\n        self.widget.compute_distances(mock, self.iris)\n        self.wait_until_finished()\n        self.assertEqual(len(self.widget.Error.active), 1)\n        self.assertTrue(self.widget.Error.distances_memory_error.is_shown())\n\n    def test_migrates_normalized_dist(self):\n        w = self.create_widget(OWDistances, stored_settings={\"metric_idx\": 0})\n        self.assertFalse(w.normalized_dist)\n\n    def test_negative_values_bhattacharyya(self):\n        self.iris.X[0, 0] *= -1\n        for self.widget.metric_idx, (_, metric) in enumerate(METRICS):\n            if metric == distance.Bhattacharyya:\n                break\n        self.send_signal(self.widget.Inputs.data, self.iris)\n        self.wait_until_finished()\n        self.assertTrue(self.widget.Error.distances_value_error.is_shown())\n        self.iris.X[0, 0] *= -1\n\n    def test_limit_mahalanobis(self):\n        def assert_error_shown():\n            self.assertTrue(\n                self.widget.Error.data_too_large_for_mahalanobis.is_shown())\n\n        def assert_no_error():\n            self.assertFalse(\n                self.widget.Error.data_too_large_for_mahalanobis.is_shown())\n\n        widget = self.widget\n        axis_buttons = widget.controls.axis.buttons\n\n        self.assertEqual(widget.metrics_combo.count(), len(METRICS))\n        for i, (_, metric) in enumerate(METRICS):\n            if metric == distance.Mahalanobis:\n                widget.metrics_combo.setCurrentIndex(i)\n                widget.metrics_combo.activated.emit(i)\n                break\n\n        X = np.random.random((1010, 4))\n        bigrows = Table.from_numpy(Domain(self.iris.domain.attributes), X)\n        bigcols = Table.from_numpy(\n            Domain([ContinuousVariable(f\"{i}\") for i in range(1010)]), X.T)\n\n        self.send_signal(widget.Inputs.data, self.iris)\n        assert_no_error()\n\n        axis_buttons[0].click()\n        assert_no_error()\n        axis_buttons[1].click()\n        assert_no_error()\n\n        # by columns -- cannot handle too many rows\n        self.send_signal(self.widget.Inputs.data, bigrows)\n        assert_error_shown()\n        axis_buttons[0].click()\n        assert_no_error()\n        axis_buttons[1].click()\n        assert_error_shown()\n\n        self.send_signal(self.widget.Inputs.data, bigcols)\n        assert_no_error()\n        axis_buttons[0].click()\n        assert_error_shown()\n\n        self.send_signal(widget.Inputs.data, self.iris)\n        assert_no_error()\n\n    def test_discrete_in_metas(self):\n        domain = self.iris.domain\n        data = self.iris.transform(\n            Domain(domain.attributes[:-1] + (domain.class_var, ),\n                   [],\n                   domain.attributes[-1:])\n        )\n        for self.widget.metric_idx, (_, metric) in enumerate(METRICS):\n            if metric == distance.Cosine:\n                break\n        self.send_signal(self.widget.Inputs.data, data)\n        self.wait_until_finished()\n        out = self.get_output(self.widget.Outputs.distances)\n        out_domain = out.row_items.domain\n        self.assertEqual(out_domain.attributes, domain.attributes[:-1])\n        self.assertEqual(out_domain.metas,\n                         (domain.attributes[-1], domain.class_var))\n\n    def test_non_binary_in_metas(self):\n        for self.widget.metric_idx, (_, metric) in enumerate(METRICS):\n            if metric == distance.Jaccard:\n                break\n        zoo = Table(\"zoo\")[:20]\n        self.send_signal(self.widget.Inputs.data, zoo)\n        self.wait_until_finished()\n        out = self.get_output(self.widget.Outputs.distances)\n        domain = zoo.domain\n        out_domain = out.row_items.domain\n        self.assertEqual(out_domain.metas, (domain[\"name\"], domain[\"legs\"]))",
                                "ast_type_str": "ClassDef",
                                "start_lineno": 68,
                                "end_lineno": 259,
                                "parent": null
                            }
                        }
                    ],
                    "deleted_entities": []
                }
            ]
        }
    ],
    "old_commit_hash": "0aa1714905af5673407e326867870ea8946d262f^",
    "new_commit_hash": "0aa1714905af5673407e326867870ea8946d262f",
    "commit_message": "Distances: Move ignored attributes to metas",
    "commit_date": "2021-10-08T14:50:46+02:00",
    "metadata": {}
}
{
    "repo_name": "orange3",
    "new_commit_hash": "0aa1714905af5673407e326867870ea8946d262f",
    "test_file_codes": [
        "import unittest\nfrom unittest.mock import patch\nfrom math import sqrt\n\nimport numpy as np\nfrom scipy.sparse import csr_matrix\n\nfrom Orange.data import ContinuousVariable, DiscreteVariable, StringVariable,\\\n    Domain, Table\nfrom Orange import distance\n\n\nclass CommonTests:\n    \"\"\"Tests applicable to all distance measures\"\"\"\n\n    def test_no_data(self):\n        \"\"\"distances return zero-dimensional matrices when no data\"\"\"\n        n = len(self.data)\n        np.testing.assert_almost_equal(\n            self.Distance(Table.from_domain(self.domain)),\n            np.zeros((0, 0)))\n        np.testing.assert_almost_equal(\n            self.Distance(self.data, Table.from_domain(self.domain)),\n            np.zeros((n, 0)))\n        np.testing.assert_almost_equal(\n            self.Distance(Table.from_domain(self.domain), self.data),\n            np.zeros((0, n)))\n\n    def test_sparse(self):\n        \"\"\"Test sparse support in distances.\"\"\"\n        domain = Domain([ContinuousVariable(c) for c in \"abc\"])\n        dense_data = Table.from_list(\n            domain, [[1, 0, 2], [-1, 5, 0], [0, 1, 1], [7, 0, 0]])\n        sparse_data = Table(domain, csr_matrix(dense_data.X))\n\n        if not self.Distance.supports_sparse:\n            self.assertRaises(TypeError, self.Distance, sparse_data)\n        else:\n            # check the result is the same for sparse and dense\n            dist_dense = self.Distance(dense_data)\n            dist_sparse = self.Distance(sparse_data)\n            np.testing.assert_allclose(dist_sparse, dist_dense)\n\n\nclass CommonFittedTests(CommonTests):\n    \"\"\"Tests applicable to all distances with fitting\"\"\"\n    def test_mismatching_attributes(self):\n        \"\"\"distances can't be computed if fit from other attributes\"\"\"\n        def new_table(name):\n            return Table.from_list(Domain([ContinuousVariable(name)]), [[1]])\n\n        table1 = new_table(\"a\")\n        model = self.Distance().fit(table1)\n        self.assertRaises(ValueError, model, new_table(\"b\"))\n        self.assertRaises(ValueError, model, table1, new_table(\"c\"))\n        self.assertRaises(ValueError, model, new_table(\"d\"), table1)\n\n\nclass CommonNormalizedTests(CommonFittedTests):\n    \"\"\"Tests applicable to distances the have normalization\"\"\"\n\n    def test_zero_variance(self):\n        \"\"\"zero-variance columns have no effect on row distance\"\"\"\n        assert_almost_equal = np.testing.assert_almost_equal\n        normalized = self.Distance(axis=1, normalize=True)\n        nonnormalized = self.Distance(axis=1, normalize=False)\n\n        def is_same(d1, d2, fit1=None, fit2=None):\n            if fit1 is None:\n                fit1 = d1\n            if fit2 is None:\n                fit2 = d2\n            assert_almost_equal(normalized.fit(fit1)(d1),\n                                normalized.fit(fit2)(d2))\n            assert_almost_equal(nonnormalized.fit(fit1)(d1),\n                                nonnormalized.fit(fit2)(d2))\n\n        data = self.cont_data\n        n = len(data)\n        X = data.X\n        domain = Domain(data.domain.attributes + (ContinuousVariable(\"d\"),))\n        data_const = Table(domain, np.hstack((X, np.ones((n, 1)))))\n        data_nan = Table(domain, np.hstack((X, np.full((n, 1), np.nan))))\n        data_nan_1 = Table(domain, np.hstack((X, np.full((n, 1), np.nan))))\n        data_nan_1.X[0, -1] = 1\n        is_same(data, data_const)\n        is_same(data, data_nan)\n        is_same(data, data_nan_1)\n\n        # Test whether it's possible to fit with singular data and use the\n        # parameters on data where the same column is defined\n        is_same(data_nan, data_const, data_const)\n        is_same(data_const, data_const, data_nan)\n\n        self.assertRaises(ValueError, self.Distance,\n                          data_const, axis=0, normalize=True)\n        self.assertRaises(ValueError, self.Distance,\n                          data_nan, axis=0, normalize=True)\n        self.assertRaises(ValueError, self.Distance,\n                          data_nan_1, axis=0, normalize=True)\n\n    def test_mixed_cols(self):\n        \"\"\"distance over columns raises exception for discrete columns\"\"\"\n        self.assertRaises(ValueError, self.Distance, self.mixed_data, axis=0)\n        self.assertRaises(ValueError,\n                          self.Distance(axis=0).fit, self.mixed_data)\n\n\nclass FittedDistanceTest(unittest.TestCase):\n    @classmethod\n    def setUpClass(cls):\n        cls.attributes = (\n            ContinuousVariable(\"c1\"),\n            ContinuousVariable(\"c2\"),\n            ContinuousVariable(\"c3\"),\n            DiscreteVariable(\"d1\", values=(\"a\", \"b\")),\n            DiscreteVariable(\"d2\", values=(\"a\", \"b\", \"c\", \"d\")),\n            DiscreteVariable(\"d3\", values=(\"a\", \"b\", \"c\")))\n        cls.domain = Domain(cls.attributes)\n        cls.cont_domain = Domain(cls.attributes[:3])\n        cls.disc_domain = Domain(cls.attributes[3:])\n\n    def setUp(self):\n        self.cont_data = Table.from_list(\n            self.cont_domain,\n            [[1, 3, 2],\n             [-1, 5, 0],\n             [1, 1, 1],\n             [7, 2, 3]])\n\n        self.cont_data2 = Table.from_list(\n            self.cont_domain,\n            [[2, 1, 3],\n             [1, 2, 2]]\n        )\n\n        self.disc_data = Table.from_list(\n            self.disc_domain,\n            [[0, 0, 0],\n             [0, 1, 1],\n             [1, 3, 1]]\n        )\n\n        self.disc_data4 = Table.from_list(\n            self.disc_domain,\n            [[0, 0, 0],\n             [0, 1, 1],\n             [0, 1, 1],\n             [1, 3, 1]]\n        )\n\n        self.mixed_data = self.data = Table.from_numpy(\n            self.domain, np.hstack((self.cont_data.X[:3], self.disc_data.X)))\n\n\n\n# Correct results in these tests were computed manually or with Excel;\n# these are not regression tests\nclass EuclideanDistanceTest(FittedDistanceTest, CommonNormalizedTests):\n    Distance = distance.Euclidean\n\n    def test_euclidean_disc(self):\n        assert_almost_equal = np.testing.assert_almost_equal\n        data = self.disc_data\n\n        model = distance.Euclidean().fit(data)\n        assert_almost_equal(model.dist_missing_disc,\n                            [[1/3, 2/3, 1, 1],\n                             [2/3, 2/3, 1, 2/3],\n                             [2/3, 1/3, 1, 1]])\n        assert_almost_equal(model.dist_missing2_disc,\n                            [1 - 5/9, 1 - 3/9, 1 - 5/9])\n\n        dist = model(data)\n        assert_almost_equal(dist,\n                            np.sqrt(np.array([[0, 2, 3],\n                                              [2, 0, 2],\n                                              [3, 2, 0]])))\n\n        data.X[1, 0] = np.nan\n        model = distance.Euclidean().fit(data)\n        assert_almost_equal(model.dist_missing_disc,\n                            [[1/2, 1/2, 1, 1],\n                             [2/3, 2/3, 1, 2/3],\n                             [2/3, 1/3, 1, 1]\n                            ])\n        assert_almost_equal(model.dist_missing2_disc,\n                            [1 - 2/4, 1 - 3/9, 1 - 5/9])\n\n        dist = model(data)\n        assert_almost_equal(dist,\n                            np.sqrt(np.array([[0, 2.5, 3],\n                                              [2.5, 0, 1.5],\n                                              [3, 1.5, 0]])))\n\n        data.X[0, 0] = np.nan\n        model = distance.Euclidean().fit(data)\n        assert_almost_equal(model.dist_missing_disc,\n                            [[1, 0, 1, 1],\n                             [2/3, 2/3, 1, 2/3],\n                             [2/3, 1/3, 1, 1]])\n        assert_almost_equal(model.dist_missing2_disc,\n                            [1 - 1, 1 - 3/9, 1 - 5/9])\n\n        dist = model(data)\n        assert_almost_equal(dist,\n                            np.sqrt(np.array([[0, 2, 2],\n                                              [2, 0, 1],\n                                              [2, 1, 0]])))\n\n        data = self.disc_data4\n        data.X[:2, 0] = np.nan\n        model = distance.Euclidean().fit(data)\n\n        assert_almost_equal(model.dist_missing_disc,\n                            [[1/2, 1/2, 1, 1],\n                             [3/4, 2/4, 1, 3/4],\n                             [3/4, 1/4, 1, 1]])\n        assert_almost_equal(model.dist_missing2_disc,\n                            [1 - 2/4, 1 - 6/16, 1 - 10/16])\n\n        dist = model(data)\n        assert_almost_equal(dist,\n                            np.sqrt(np.array([[0, 2.5, 2.5, 2.5],\n                                              [2.5, 0, 0.5, 1.5],\n                                              [2.5, 0.5, 0, 2],\n                                              [2.5, 1.5, 2, 0]])))\n\n    def test_euclidean_cont(self):\n        assert_almost_equal = np.testing.assert_almost_equal\n        data = self.cont_data\n\n        dist = distance.Euclidean(data, axis=1, normalize=False)\n        assert_almost_equal(\n            dist,\n            np.sqrt(np.array([[0, 12, 5, 38],\n                              [12, 0, 21, 82],\n                              [5, 21, 0, 41],\n                              [38, 82, 41, 0]])))\n\n        data.X[1, 0] = np.nan\n        dist = distance.Euclidean(data, axis=1, normalize=False)\n        assert_almost_equal(\n            dist,\n            [[0, 4.472135955, 2.236067977, 6.164414003],\n             [4.472135955, 0, 5.385164807, 6.480740698],\n             [2.236067977, 5.385164807, 0, 6.403124237],\n             [6.164414003, 6.480740698, 6.403124237, 0]])\n\n        data.X[0, 0] = np.nan\n        dist = distance.Euclidean(data, axis=1, normalize=False)\n        assert_almost_equal(\n            dist,\n            [[0, 5.099019514, 4.795831523, 4.472135955],\n             [5.099019514, 0, 5.916079783, 6],\n             [4.795831523, 5.916079783, 0, 6.403124237],\n             [4.472135955, 6, 6.403124237, 0]])\n\n    def test_euclidean_cont_normalized(self):\n        assert_almost_equal = np.testing.assert_almost_equal\n        data = self.cont_data\n\n        model = distance.Euclidean(axis=1, normalize=True).fit(data)\n        assert_almost_equal(model.means, [2, 2.75, 1.5])\n        assert_almost_equal(model.vars, [9, 2.1875, 1.25])\n        assert_almost_equal(model.dist_missing2_cont, [1, 1, 1])\n\n        dist = model(data)\n        assert_almost_equal(\n            dist,\n            [[0, 1.654239383, 1.146423008, 1.621286967],\n             [1.654239383, 0, 2.068662631, 3.035242727],\n             [1.146423008, 2.068662631, 0, 1.956673562],\n             [1.621286967, 3.035242727, 1.956673562, 0]])\n\n        dist = distance.Euclidean(data, axis=1, normalize=True)\n        assert_almost_equal(\n            dist,\n            [[0, 1.654239383, 1.146423008, 1.621286967],\n             [1.654239383, 0, 2.068662631, 3.035242727],\n             [1.146423008, 2.068662631, 0, 1.956673562],\n             [1.621286967, 3.035242727, 1.956673562, 0]])\n\n        data.X[1, 0] = np.nan\n        model = distance.Euclidean(axis=1, normalize=True).fit(data)\n        assert_almost_equal(model.means, [3, 2.75, 1.5])\n        assert_almost_equal(model.vars, [8, 2.1875, 1.25])\n        dist = model(data)\n        assert_almost_equal(\n            dist,\n            [[0, 1.806733438, 1.146423008, 1.696635326],\n             [1.806733438, 0, 2.192519751, 2.675283697],\n             [1.146423008, 2.192519751, 0, 2.019547333],\n             [1.696635326, 2.675283697, 2.019547333, 0]])\n\n        data.X[0, 0] = np.nan\n        model = distance.Euclidean(axis=1, normalize=True).fit(data)\n        assert_almost_equal(model.means, [4, 2.75, 1.5])\n        assert_almost_equal(model.vars, [9, 2.1875, 1.25])\n        dist = model(data)\n        assert_almost_equal(\n            dist,\n            [[0, 1.874642823, 1.521277659, 1.276154939],\n             [1.874642823, 0, 2.248809209, 2.580143961],\n             [1.521277659, 2.248809209, 0, 1.956673562],\n             [1.276154939, 2.580143961, 1.956673562, 0]])\n\n    def test_euclidean_cols(self):\n        assert_almost_equal = np.testing.assert_almost_equal\n        data = self.cont_data\n\n        dist = distance.Euclidean(data, axis=0, normalize=False)\n        assert_almost_equal(\n            dist,\n            [[0, 8.062257748, 4.242640687],\n             [8.062257748, 0, 5.196152423],\n             [4.242640687, 5.196152423, 0]])\n\n        data.X[1, 1] = np.nan\n        dist = distance.Euclidean(data, axis=0, normalize=False)\n        assert_almost_equal(\n            dist,\n            [[0, 6.218252702, 4.242640687],\n             [6.218252702, 0, 2.581988897],\n             [4.242640687, 2.581988897, 0]])\n\n        data.X[1, 0] = np.nan\n        dist = distance.Euclidean(data, axis=0, normalize=False)\n        assert_almost_equal(\n            dist,\n            [[0, 6.218252702, 5.830951895],\n             [6.218252702, 0, 2.581988897],\n             [5.830951895, 2.581988897, 0]])\n\n    def test_euclidean_cols_normalized(self):\n        assert_almost_equal = np.testing.assert_almost_equal\n        data = self.cont_data\n\n        dist = distance.Euclidean(data, axis=0, normalize=True)\n        assert_almost_equal(\n            dist,\n            [[0, 2.455273959, 0.649839392],\n             [2.455273959, 0, 2.473176308],\n             [0.649839392, 2.473176308, 0]])\n\n        data.X[1, 1] = np.nan\n        dist = distance.Euclidean(data, axis=0, normalize=True)\n        assert_almost_equal(\n            dist,\n            [[0, 2, 0.649839392],\n             [2, 0, 1.704275472],\n             [0.649839392, 1.704275472, 0]])\n\n        data.X[1, 0] = np.nan\n        dist = distance.Euclidean(data, axis=0, normalize=True)\n        assert_almost_equal(\n            dist,\n            [[0, 2, 1.450046001],\n             [2, 0, 1.704275472],\n             [1.450046001, 1.704275472, 0]])\n\n    def test_euclidean_mixed(self):\n        assert_almost_equal = np.testing.assert_almost_equal\n        data = self.mixed_data\n\n        model = distance.Euclidean(axis=1, normalize=True).fit(data)\n\n        assert_almost_equal(model.means, [1/3, 3, 1])\n        assert_almost_equal(model.vars, [8/9, 8/3, 2/3])\n        assert_almost_equal(model.dist_missing_disc,\n                            [[1/3, 2/3, 1, 1],\n                             [2/3, 2/3, 1, 2/3],\n                             [2/3, 1/3, 1, 1]])\n        assert_almost_equal(model.dist_missing2_cont, [1, 1, 1])\n        assert_almost_equal(model.dist_missing2_disc,\n                            [1 - 5/9, 1 - 3/9, 1 - 5/9])\n        dist = model(data)\n        assert_almost_equal(\n            dist,\n            [[0, 2.828427125, 2.121320344],\n             [2.828427125, 0, 2.828427125],\n             [2.121320344, 2.828427125, 0]])\n\n    def test_two_tables(self):\n        assert_almost_equal = np.testing.assert_almost_equal\n\n        dist = distance.Euclidean(self.cont_data, self.cont_data2,\n                                  normalize=True)\n        assert_almost_equal(\n            dist,\n            [[1.17040218, 0.47809144],\n             [2.78516478, 1.96961039],\n             [1.28668394, 0.79282497],\n             [1.27179413, 1.54919334]])\n\n        model = distance.Euclidean(normalize=True).fit(self.cont_data)\n        dist = model(self.cont_data, self.cont_data2)\n        assert_almost_equal(\n            dist,\n            [[1.17040218, 0.47809144],\n             [2.78516478, 1.96961039],\n             [1.28668394, 0.79282497],\n             [1.27179413, 1.54919334]])\n\n        dist = model(self.cont_data2)\n        assert_almost_equal(dist, [[0, 0.827119692], [0.827119692, 0]])\n\n\nclass ManhattanDistanceTest(FittedDistanceTest, CommonNormalizedTests):\n    Distance = distance.Euclidean\n\n    # The data used for testing Euclidean distances unfortunately yields\n    # mads = 1, so we change it a bit\n    def setUp(self):\n        super().setUp()\n        self.cont_data = Table.from_list(\n            self.cont_domain,\n            [[1, 3, 2],\n             [-1, 6, 0],\n             [2, 7, 1],\n             [7, 1, 3]])\n\n    def test_manhattan_no_data(self):\n        np.testing.assert_almost_equal(\n            distance.Manhattan(Table.from_domain(self.domain)),\n            np.zeros((0, 0)))\n        np.testing.assert_almost_equal(\n            distance.Manhattan(self.mixed_data, Table.from_domain(self.domain)),\n            np.zeros((3, 0)))\n        np.testing.assert_almost_equal(\n            distance.Manhattan(Table.from_domain(self.domain), self.mixed_data),\n            np.zeros((0, 3)))\n        self.assertRaises(\n            ValueError,\n            distance.Manhattan, Table.from_domain(self.cont_domain),\n            axis=0, normalize=True)\n\n    def test_manhattan_disc(self):\n        assert_almost_equal = np.testing.assert_almost_equal\n        data = self.disc_data\n\n        model = distance.Manhattan().fit(data)\n        assert_almost_equal(model.dist_missing_disc,\n                            [[1/3, 2/3, 1, 1],\n                             [2/3, 2/3, 1, 2/3],\n                             [2/3, 1/3, 1, 1]])\n        assert_almost_equal(model.dist_missing2_disc,\n                            [1 - 5/9, 1 - 3/9, 1 - 5/9])\n        dist = model(data)\n        assert_almost_equal(dist,\n                            [[0, 2, 3],\n                             [2, 0, 2],\n                             [3, 2, 0]])\n\n        data.X[1, 0] = np.nan\n        model = distance.Manhattan().fit(data)\n        assert_almost_equal(model.dist_missing_disc,\n                            [[1/2, 1/2, 1, 1],\n                             [2/3, 2/3, 1, 2/3],\n                             [2/3, 1/3, 1, 1]])\n        assert_almost_equal(model.dist_missing2_disc,\n                            [1 - 2/4, 1 - 3/9, 1 - 5/9])\n\n        dist = model(data)\n        assert_almost_equal(dist,\n                            [[0, 2.5, 3],\n                             [2.5, 0, 1.5],\n                             [3, 1.5, 0]])\n\n        data.X[0, 0] = np.nan\n        model = distance.Manhattan().fit(data)\n        assert_almost_equal(model.dist_missing_disc,\n                            [[1, 0, 1, 1],\n                             [2/3, 2/3, 1, 2/3],\n                             [2/3, 1/3, 1, 1]])\n        assert_almost_equal(model.dist_missing2_disc,\n                            [1 - 1, 1 - 3/9, 1 - 5/9])\n\n        dist = model(data)\n        assert_almost_equal(dist,\n                            [[0, 2, 2],\n                             [2, 0, 1],\n                             [2, 1, 0]])\n\n        data = self.disc_data4\n        data.X[:2, 0] = np.nan\n        model = distance.Manhattan().fit(data)\n        assert_almost_equal(model.dist_missing_disc,\n                            [[1/2, 1/2, 1, 1],\n                             [3/4, 2/4, 1, 3/4],\n                             [3/4, 1/4, 1, 1]])\n        assert_almost_equal(model.dist_missing2_disc,\n                            [1 - 2/4, 1 - 6/16, 1 - 10/16])\n\n        dist = model(data)\n        assert_almost_equal(dist,\n                            [[0, 2.5, 2.5, 2.5],\n                             [2.5, 0, 0.5, 1.5],\n                             [2.5, 0.5, 0, 2],\n                             [2.5, 1.5, 2, 0]])\n\n    def test_manhattan_cont(self):\n        assert_almost_equal = np.testing.assert_almost_equal\n        data = self.cont_data\n\n        dist = distance.Manhattan(data, axis=1, normalize=False)\n        assert_almost_equal(\n            dist,\n            [[0, 7, 6, 9],\n             [7, 0, 5, 16],\n             [6, 5, 0, 13],\n             [9, 16, 13, 0]])\n\n        data.X[1, 0] = np.nan\n        dist = distance.Manhattan(data, axis=1, normalize=False)\n        assert_almost_equal(\n            dist,\n            [[0, 7, 6, 9],\n             [7, 0, 3, 14],\n             [6, 3, 0, 13],\n             [9, 14, 13, 0]])\n\n        data.X[0, 0] = np.nan\n        dist = distance.Manhattan(data, axis=1, normalize=False)\n        assert_almost_equal(\n            dist,\n            [[0, 10, 10, 8],\n             [10, 0, 7, 13],\n             [10, 7, 0, 13],\n             [8, 13, 13, 0]])\n\n    def test_manhattan_cont_normalized(self):\n        assert_almost_equal = np.testing.assert_almost_equal\n        data = self.cont_data\n\n        model = distance.Manhattan(axis=1, normalize=True).fit(data)\n        assert_almost_equal(model.medians, [1.5, 4.5, 1.5])\n        assert_almost_equal(model.mads, [1.5, 2, 1])\n        assert_almost_equal(model.dist_missing2_cont, np.ones(3))\n\n        dist = model(data)\n        assert_almost_equal(\n            dist,\n            [[0, 2.416666667, 1.833333333, 3],\n             [2.416666667, 0, 1.75, 5.416666667],\n             [1.833333333, 1.75, 0, 4.166666667],\n             [3, 5.416666667, 4.166666667, 0]])\n\n        dist = distance.Manhattan(data, axis=1, normalize=True)\n        assert_almost_equal(\n            dist,\n            [[0, 2.416666667, 1.833333333, 3],\n             [2.416666667, 0, 1.75, 5.416666667],\n             [1.833333333, 1.75, 0, 4.166666667],\n             [3, 5.416666667, 4.166666667, 0]])\n\n        data.X[1, 0] = np.nan\n        model = distance.Manhattan(axis=1, normalize=True).fit(data)\n        assert_almost_equal(model.medians, [2, 4.5, 1.5])\n        assert_almost_equal(model.mads, [1, 2, 1])\n\n        dist = model(data)\n        assert_almost_equal(\n            dist,\n            [[0, 2.75, 2, 4],\n             [2.75, 0, 1.25, 5.75],\n             [2, 1.25, 0, 5],\n             [4, 5.75, 5, 0]])\n\n        data.X[0, 0] = np.nan\n        model = distance.Manhattan(axis=1, normalize=True).fit(data)\n        assert_almost_equal(model.medians, [4.5, 4.5, 1.5])\n        assert_almost_equal(model.mads, [2.5, 2, 1])\n\n        dist = model(data)\n        assert_almost_equal(\n            dist,\n            [[0, 2.75, 2.5, 2],\n             [2.75, 0, 1.75, 3.75],\n             [2.5, 1.75, 0, 3.5],\n             [2, 3.75, 3.5, 0]])\n\n    def test_manhattan_cols(self):\n        assert_almost_equal = np.testing.assert_almost_equal\n        data = self.cont_data\n\n        dist = distance.Manhattan(data, axis=0, normalize=False)\n        assert_almost_equal(\n            dist,\n            [[0, 20, 7],\n             [20, 0, 15],\n             [7, 15, 0]])\n\n        data.X[1, 1] = np.nan\n        dist = distance.Manhattan(data, axis=0, normalize=False)\n        assert_almost_equal(\n            dist,\n            [[0, 19, 7],\n             [19, 0, 14],\n             [7, 14, 0]])\n\n        data.X[1, 0] = np.nan\n        dist = distance.Manhattan(data, axis=0, normalize=False)\n        assert_almost_equal(\n            dist,\n            [[0, 17, 9],\n             [17, 0, 14],\n             [9, 14, 0]])\n\n\n    def test_manhattan_cols_normalized(self):\n        assert_almost_equal = np.testing.assert_almost_equal\n        data = self.cont_data\n\n        dist = distance.Manhattan(data, axis=0, normalize=True)\n        assert_almost_equal(\n            dist,\n            [[0, 4.5833333, 2],\n             [4.5833333, 0, 4.25],\n             [2, 4.25, 0]])\n\n        data.X[1, 1] = np.nan\n        dist = distance.Manhattan(data, axis=0, normalize=True)\n        assert_almost_equal(\n            dist,\n            [[0, 4.6666667, 2],\n             [4.6666667, 0, 4],\n             [2, 4, 0]])\n\n        data.X[1, 0] = np.nan\n        dist = distance.Manhattan(data, axis=0, normalize=True)\n        assert_almost_equal(\n            dist,\n            [[0, 5.5, 4],\n             [5.5, 0, 4],\n             [4, 4, 0]])\n\n    def test_manhattan_mixed(self):\n        assert_almost_equal = np.testing.assert_almost_equal\n        data = self.mixed_data\n\n        data.X[2, 0] = 2  # prevent mads[0] = 0\n        model = distance.Manhattan(axis=1, normalize=True).fit(data)\n        assert_almost_equal(model.medians, [1, 3, 1])\n        assert_almost_equal(model.mads, [1, 2, 1])\n        assert_almost_equal(model.dist_missing_disc,\n                            [[1/3, 2/3, 1, 1],\n                             [2/3, 2/3, 1, 2/3],\n                             [2/3, 1/3, 1, 1]])\n        assert_almost_equal(model.dist_missing2_disc,\n                            [1 - 5/9, 1 - 3/9, 1 - 5/9])\n\n        dist = model(data)\n        assert_almost_equal(\n            dist,\n            [[0, 4.5, 4.5],\n             [4.5, 0, 5],\n             [4.5, 5, 0]])\n\n    def test_two_tables(self):\n        assert_almost_equal = np.testing.assert_almost_equal\n\n        dist = distance.Manhattan(self.cont_data, self.cont_data2,\n                                  normalize=True)\n        assert_almost_equal(\n            dist,\n            [[1.3333333, 0.25],\n             [3.75, 2.6666667],\n             [2.5, 2.0833333],\n             [1.6666667, 2.75]])\n\n        model = distance.Manhattan(normalize=True).fit(self.cont_data)\n        dist = model(self.cont_data, self.cont_data2)\n        assert_almost_equal(\n            dist,\n            [[1.3333333, 0.25],\n             [3.75, 2.6666667],\n             [2.5, 2.0833333],\n             [1.6666667, 2.75]])\n\n        dist = model(self.cont_data2)\n        assert_almost_equal(dist, [[0, 1.083333333], [1.083333333, 0]])\n\n    def test_manhattan_mixed_cols(self):\n        self.assertRaises(ValueError,\n                          distance.Manhattan, self.mixed_data, axis=0)\n        self.assertRaises(ValueError,\n                          distance.Manhattan(axis=0).fit, self.mixed_data)\n\n\nclass CosineDistanceTest(FittedDistanceTest, CommonFittedTests):\n    Distance = distance.Cosine\n\n    def test_no_data(self):\n        with patch(\"warnings.warn\") as warn:\n            super().test_no_data()\n            self.assertEqual(warn.call_args[0],\n                             (\"Mean of empty slice\", RuntimeWarning))\n\n    def test_cosine_disc(self):\n        assert_almost_equal = np.testing.assert_almost_equal\n        data = self.disc_data\n        data.X = np.array([[1, 0, 0],\n                           [0, 1, 1],\n                           [1, 3, 0]], dtype=float)\n\n        model = distance.Cosine().fit(data)\n        assert_almost_equal(model.means, [2 / 3, 2 / 3, 1 / 3])\n\n        dist = model(data)\n        assert_almost_equal(dist, 1 - np.array([[1, 0, 1 / sqrt(2)],\n                                                [0, 1, 0.5],\n                                                [1 / sqrt(2), 0.5, 1]]))\n\n        data.X[1, 1] = np.nan\n        model = distance.Cosine().fit(data)\n        assert_almost_equal(model.means, [2 / 3, 1 / 2, 1 / 3])\n        dist = model(data)\n        assert_almost_equal(\n            dist,\n            1 - np.array([[1, 0, 1 / sqrt(2)],\n                          [0, 1, 0.5 / sqrt(1.25) / sqrt(2)],\n                          [1 / sqrt(2), 0.5 / sqrt(1.25) / sqrt(2), 1]]))\n\n        data.X = np.array([[1, 0, 0],\n                           [0, np.nan, 1],\n                           [1, np.nan, 1],\n                           [1, 3, 1]])\n        model = distance.Cosine().fit(data)\n        dist = model(data)\n        assert_almost_equal(model.means, [0.75, 0.5, 0.75])\n        assert_almost_equal(dist, [[0, 1, 0.333333333, 0.422649731],\n                                   [1, 0, 0.254644008, 0.225403331],\n                                   [0.333333333, 0.254644008, 0, 0.037749551],\n                                   [0.422649731, 0.225403331, 0.037749551, 0]])\n\n    def test_cosine_cont(self):\n        assert_almost_equal = np.testing.assert_almost_equal\n        data = self.cont_data\n\n        dist = distance.Cosine(data, axis=1)\n        assert_almost_equal(\n            dist,\n            [[0, 0.266200614, 0.0741799, 0.355097978],\n             [0.266200614, 0, 0.547089186, 0.925279678],\n             [0.0741799, 0.547089186, 0, 0.12011731],\n             [0.355097978, 0.925279678, 0.12011731, 0]]\n        )\n\n        data.X[1, 0] = np.nan\n        dist = distance.Cosine(data, axis=1)\n        assert_almost_equal(\n            dist,\n            [[0, 0.174971353, 0.0741799, 0.355097978],\n             [0.174971353, 0, 0.207881966, 0.324809395],\n             [0.0741799, 0.207881966, 0, 0.12011731],\n             [0.355097978, 0.324809395, 0.12011731, 0]])\n\n        data.X[0, 0] = np.nan\n        dist = distance.Cosine(data, axis=1)\n        assert_almost_equal(\n            dist,\n            [[0, 0.100977075, 0.035098719, 0.056666739],\n             [0.100977075, 0, 0.188497329, 0.246304671],\n             [0.035098719, 0.188497329, 0, 0.12011731],\n             [0.056666739, 0.246304671, 0.12011731, 0]])\n\n    def test_cosine_mixed(self):\n        assert_almost_equal = np.testing.assert_almost_equal\n        data = self.mixed_data\n        data.X = np.array([[1, 3, 2, 1, 0, 0],\n                           [-1, 5, 0, 0, 1, 1],\n                           [1, 1, 1, 1, 3, 0]], dtype=float)\n\n        model = distance.Cosine(axis=1).fit(data)\n        assert_almost_equal(model.means, [1/3, 3, 1, 2/3, 2/3, 1/3])\n        dist = model(data)\n        assert_almost_equal(\n            dist,\n            [[0, 0.316869949, 0.191709623],\n             [0.316869949, 0, 0.577422873],\n             [0.191709623, 0.577422873, 0]])\n\n    def test_two_tables(self):\n        assert_almost_equal = np.testing.assert_almost_equal\n        self.cont_data.X[1, 0] = np.nan\n        self.cont_data2.X[1, 0] = np.nan\n\n        dist = distance.Cosine(self.cont_data, self.cont_data2)\n        assert_almost_equal(\n            dist,\n            [[0.2142857, 0.1573352],\n             [0.4958158, 0.2097042],\n             [0.0741799, 0.0198039],\n             [0.1514447, 0.0451363]])\n\n        model = distance.Cosine().fit(self.cont_data)\n        dist = model(self.cont_data, self.cont_data2)\n        assert_almost_equal(\n            dist,\n            [[0.2142857, 0.1573352],\n             [0.4958158, 0.2097042],\n             [0.0741799, 0.0198039],\n             [0.1514447, 0.0451363]])\n\n        dist = model(self.cont_data2)\n        assert_almost_equal(dist, [[0, 0.092514787], [0.092514787, 0]])\n\n    def test_cosine_cols(self):\n        assert_almost_equal = np.testing.assert_almost_equal\n        data = self.cont_data\n\n        dist = distance.Cosine(data, axis=0, normalize=False)\n        assert_almost_equal(\n            dist,\n            [[0, 0.711324865, 0.11050082],\n             [0.711324865, 0, 0.44365136],\n             [0.11050082, 0.44365136, 0]])\n\n        data.X[1, 1] = np.nan\n        dist = distance.Cosine(data, axis=0, normalize=False)\n        assert_almost_equal(\n            dist,\n            [[0, 0.47702364, 0.11050082],\n             [0.47702364, 0, 0.181076975],\n             [0.11050082, 0.181076975, 0]])\n\n        data.X[1, 0] = np.nan\n        data.X[1, 2] = 2\n        dist = distance.Cosine(data, axis=0, normalize=False)\n        assert_almost_equal(\n            dist,\n            [[0, 0.269703257, 0.087129071],\n             [0.269703257, 0, 0.055555556],\n             [0.087129071, 0.055555556, 0]])\n\n\nclass JaccardDistanceTest(unittest.TestCase, CommonFittedTests):\n    Distance = distance.Jaccard\n\n    def setUp(self):\n        self.domain = Domain([DiscreteVariable(c) for c in \"abc\"])\n        self.data = Table.from_list(\n            self.domain,\n            [[0, 1, 1],\n             [1, 1, 1],\n             [1, 0, 1],\n             [1, 0, 0]])\n\n    def test_jaccard_rows(self):\n        assert_almost_equal = np.testing.assert_almost_equal\n\n        model = distance.Jaccard().fit(self.data)\n        assert_almost_equal(model.ps, [0.75, 0.5, 0.75])\n        assert_almost_equal(\n            model(self.data),\n            1 - np.array([[1, 2/3, 1/3, 0],\n                          [2/3, 1, 2/3, 1/3],\n                          [1/3, 2/3, 1, 1/2],\n                          [0, 1/3, 1/2, 1]]))\n\n        X = self.data.X\n        X[1, 0] = X[2, 0] = X[3, 1] = np.nan\n        model = distance.Jaccard().fit(self.data)\n        assert_almost_equal(model.ps, np.array([0.5, 2/3, 0.75]))\n\n        assert_almost_equal(\n            model(self.data),\n            1 - np.array([[      1,        2 / 2.5,        1 / 2.5,        2/3 / 3],\n                          [2 / 2.5,              1,    1.25 / 2.75,  (1/2+2/3) / 3],\n                          [1 / 2.5,    1.25 / 2.75,              1,  0.5 / (2+2/3)],\n                          [2/3 / 3,  (1/2+2/3) / 3,  0.5 / (2+2/3),            1]]))\n\n    def test_jaccard_cols(self):\n        assert_almost_equal = np.testing.assert_almost_equal\n        model = distance.Jaccard(axis=0).fit(self.data)\n        assert_almost_equal(model.ps, [0.75, 0.5, 0.75])\n        assert_almost_equal(\n            model(self.data),\n            1 - np.array([[1, 1/4, 1/2],\n                          [1/4, 1, 2/3],\n                          [1/2, 2/3, 1]]))\n\n        self.data.X = np.array([[0, 1, 1],\n                                [np.nan, np.nan, 1],\n                                [np.nan, 0, 1],\n                                [1, 1, 0]])\n        model = distance.Jaccard(axis=0).fit(self.data)\n        assert_almost_equal(model.ps, [0.5, 2/3, 0.75])\n        assert_almost_equal(\n            model(self.data),\n            1 - np.array([[1, 0.4, 0.25],\n                          [0.4, 1, 5/12],\n                          [0.25, 5/12, 1]]))\n\n    def test_zero_instances(self):\n        \"Test all zero instances\"\n        domain = Domain([ContinuousVariable(c) for c in \"abc\"])\n        dense_data = Table.from_list(\n            domain, [[0, 0, 0], [0, 0, 0], [0, 0, 1]])\n        sparse_data = Table(domain, csr_matrix(dense_data.X))\n        dist_dense = self.Distance(dense_data)\n        dist_sparse = self.Distance(sparse_data)\n\n        # false positive, pylint: disable=unsubscriptable-object\n        self.assertEqual(dist_dense[0][1], 0)\n        self.assertEqual(dist_sparse[0][1], 0)\n        self.assertEqual(dist_dense[0][2], 1)\n        self.assertEqual(dist_sparse[0][2], 1)\n\n\nclass HammingDistanceTest(FittedDistanceTest):\n    Distance = distance.Hamming\n\n    def test_hamming_col(self):\n        np.testing.assert_almost_equal(\n            self.Distance(self.disc_data, axis=0),\n            [[0, 2 / 3, 1 / 3],\n             [2 / 3, 0, 1 / 3],\n             [1 / 3, 1 / 3, 0]])\n\n    def test_hamming_row(self):\n        np.testing.assert_almost_equal(\n            self.Distance(self.disc_data),\n            [[0, 2 / 3, 1],\n             [2 / 3, 0, 2 / 3],\n             [1, 2 / 3, 0]]\n        )\n\n    def test_hamming_row_secondary_data(self):\n        np.testing.assert_almost_equal(\n            self.Distance(self.disc_data, self.disc_data[:2]),\n            [[0, 2 / 3],\n             [2 / 3, 0],\n             [1, 2 / 3]])\n\n\nclass TestHelperFunctions(unittest.TestCase):\n    # pylint: disable=protected-access, no-self-use\n    def test_interruptable_dot(self):\n        dot = distance.distance._interruptible_dot\n        k, m, n = 20, 30, 40\n        a = np.random.randint(10, size=(m, n))\n        b = np.random.randint(10, size=(n, k))\n\n        c = dot(a, b, step=10)\n        np.testing.assert_array_equal(c, np.dot(a, b))\n\n    def test_interruptable_dot_list(self):\n        dot = distance.distance._interruptible_dot\n        a = [[1, 2, 3], [1, 2, 3]]\n        b = [3, 2, 1]\n        c = dot(a, b, step=10)\n        np.testing.assert_array_equal(c, np.dot(a, b))\n\n    def test_interruptable_dot_scalar(self):\n        dot = distance.distance._interruptible_dot\n        a = 2\n        b = 3\n        c = dot(a, b, step=10)\n        np.testing.assert_array_equal(c, np.dot(a, b))\n\n    def test_interruptable_sqrt(self):\n        sqrt_ = distance.distance._interruptible_sqrt\n        n = 100\n        a = np.random.randint(10, size=(n, n))\n\n        new_a = sqrt_(a, step=10)\n        np.testing.assert_array_equal(new_a, np.sqrt(a))\n\n    def test_interruptable_sqrt_list(self):\n        sqrt_ = distance.distance._interruptible_sqrt\n        l = [1, 2, 3]\n        new_l = sqrt_(l, step=10)\n        np.testing.assert_array_equal(new_l, np.sqrt(l))\n\n    def test_interruptable_sqrt_scalar(self):\n        sqrt_ = distance.distance._interruptible_sqrt\n        i = 9\n        new_i = sqrt_(i, step=10)\n        np.testing.assert_array_equal(new_i, np.sqrt(i))\n\n\nclass TestDataUtilities(unittest.TestCase):\n    def test_remove_discrete(self):\n        d1, d2, d3 = (DiscreteVariable(c, values=tuple(\"123\")) for c in \"abc\")\n        c1, c2 = (ContinuousVariable(c) for c in \"xy\")\n        t = StringVariable(\"t\")\n        domain = Domain([d1, c1], d2, [c2, d3, t])\n        data = Table.from_domain(domain, 5)\n\n        reduced = distance.remove_discrete_features(data)\n        self.assertEqual(reduced.domain.attributes, (c1, ))\n        self.assertEqual(reduced.domain.class_var, d2)\n        self.assertEqual(reduced.domain.metas, (c2, d3, t))\n\n        reduced = distance.remove_discrete_features(data, to_metas=True)\n        self.assertEqual(reduced.domain.attributes, (c1, ))\n        self.assertEqual(reduced.domain.class_var, d2)\n        self.assertEqual(reduced.domain.metas, (c2, d3, t, d1))\n\n    def test_remove_non_binary(self):\n        b1, b2, b3 = (DiscreteVariable(c, values=tuple(\"12\")) for c in \"abc\")\n        d1, d2, d3 = (DiscreteVariable(c, values=tuple(\"123\")) for c in \"def\")\n        c1, c2 = (ContinuousVariable(c) for c in \"xy\")\n        t = StringVariable(\"t\")\n        domain = Domain([d1, b1, b2, c1], d2, [c2, d3, t, b3])\n        data = Table.from_domain(domain, 5)\n\n        reduced = distance.remove_nonbinary_features(data)\n        self.assertEqual(reduced.domain.attributes, (b1, b2))\n        self.assertEqual(reduced.domain.class_var, d2)\n        self.assertEqual(reduced.domain.metas, (c2, d3, t, b3))\n\n        reduced = distance.remove_nonbinary_features(data, to_metas=True)\n        self.assertEqual(reduced.domain.attributes, (b1, b2))\n        self.assertEqual(reduced.domain.class_var, d2)\n        self.assertEqual(reduced.domain.metas, (c2, d3, t, b3, d1, c1))\n\n\nif __name__ == \"__main__\":\n    unittest.main()\n",
        "# Test methods with long descriptive names can omit docstrings\n# pylint: disable=missing-docstring, protected-access\nimport unittest\nfrom unittest.mock import Mock\n\nimport numpy as np\n\nfrom Orange import distance\nfrom Orange.data import Table, Domain, ContinuousVariable\nfrom Orange.misc import DistMatrix\nfrom Orange.widgets.unsupervised.owdistances import OWDistances, METRICS, \\\n    DistanceRunner\nfrom Orange.widgets.tests.base import WidgetTest\n\n\nclass TestDistanceRunner(unittest.TestCase):\n    @classmethod\n    def setUpClass(cls):\n        super().setUpClass()\n        cls.iris = Table(\"iris\")[::5]\n        cls.iris.X[0, 2] = np.nan\n        cls.iris.X[1, 3] = np.nan\n        cls.iris.X[2, 1] = np.nan\n        cls.zoo = Table(\"zoo\")[::5]\n        cls.zoo.X[0, 2] = np.nan\n        cls.zoo.X[1, 3] = np.nan\n        cls.zoo.X[2, 1] = np.nan\n\n    def test_run(self):\n        state = Mock()\n        state.is_interruption_requested = Mock(return_value=False)\n        for name, metric in METRICS:\n            data = self.iris\n            if not metric.supports_missing or name == \"Bhattacharyya\":\n                data = distance.impute(data)\n            elif name == \"Jaccard\":\n                data = self.zoo\n\n            # between rows, normalized\n            dist1 = DistanceRunner.run(data, metric, True, 0, state)\n            dist2 = metric(data, axis=1, impute=True, normalize=True)\n            self.assertDistMatrixEqual(dist1, dist2)\n\n            # between rows, not normalized\n            dist1 = DistanceRunner.run(data, metric, False, 0, state)\n            dist2 = metric(data, axis=1, impute=True, normalize=False)\n            self.assertDistMatrixEqual(dist1, dist2)\n\n            # between columns, normalized\n            dist1 = DistanceRunner.run(data, metric, True, 1, state)\n            dist2 = metric(data, axis=0, impute=True, normalize=True)\n            self.assertDistMatrixEqual(dist1, dist2)\n\n            # between columns, not normalized\n            dist1 = DistanceRunner.run(data, metric, False, 1, state)\n            dist2 = metric(data, axis=0, impute=True, normalize=False)\n            self.assertDistMatrixEqual(dist1, dist2)\n\n    def assertDistMatrixEqual(self, dist1, dist2):\n        self.assertIsInstance(dist1, DistMatrix)\n        self.assertIsInstance(dist2, DistMatrix)\n        self.assertEqual(dist1.axis, dist2.axis)\n        self.assertEqual(dist1.row_items, dist2.row_items)\n        self.assertEqual(dist1.col_items, dist2.col_items)\n        np.testing.assert_array_almost_equal(dist1, dist2)\n\n\nclass TestOWDistances(WidgetTest):\n    @classmethod\n    def setUpClass(cls):\n        super().setUpClass()\n        cls.iris = Table(\"iris\")[::5]\n        cls.titanic = Table(\"titanic\")[::10]\n\n    def setUp(self):\n        self.widget = self.create_widget(OWDistances)\n\n    def test_distance_combo(self):\n        \"\"\"Check distances when the metric changes\"\"\"\n        self.assertEqual(self.widget.metrics_combo.count(), len(METRICS))\n        self.send_signal(self.widget.Inputs.data, self.iris)\n        for i, (_, metric) in enumerate(METRICS):\n            self.widget.metrics_combo.activated.emit(i)\n            self.widget.metrics_combo.setCurrentIndex(i)\n            self.wait_until_stop_blocking()\n            if metric.supports_normalization:\n                expected = metric(self.iris, normalize=self.widget.normalized_dist)\n            else:\n                expected = metric(self.iris)\n\n            if metric is not distance.Jaccard:\n                np.testing.assert_array_almost_equal(\n                    expected, self.get_output(self.widget.Outputs.distances))\n\n    def test_error_message(self):\n        \"\"\"Check if error message appears and then disappears when\n        data is removed from input\"\"\"\n        self.widget.metric_idx = 2\n        self.send_signal(self.widget.Inputs.data, self.iris)\n        self.wait_until_stop_blocking()\n        self.assertFalse(self.widget.Error.no_continuous_features.is_shown())\n        self.send_signal(self.widget.Inputs.data, self.titanic)\n        self.wait_until_stop_blocking()\n        self.assertTrue(self.widget.Error.no_continuous_features.is_shown())\n        self.send_signal(self.widget.Inputs.data, None)\n        self.assertFalse(self.widget.Error.no_continuous_features.is_shown())\n\n    def test_jaccard_messages(self):\n        for self.widget.metric_idx, (name, _) in enumerate(METRICS):\n            if name == \"Jaccard\":\n                break\n        self.send_signal(self.widget.Inputs.data, self.iris)\n        self.wait_until_stop_blocking()\n        self.assertTrue(self.widget.Error.no_binary_features.is_shown())\n        self.assertFalse(self.widget.Warning.ignoring_nonbinary.is_shown())\n\n        self.send_signal(self.widget.Inputs.data, None)\n        self.wait_until_stop_blocking()\n        self.assertFalse(self.widget.Error.no_binary_features.is_shown())\n        self.assertFalse(self.widget.Warning.ignoring_nonbinary.is_shown())\n\n        self.send_signal(self.widget.Inputs.data, self.titanic)\n        self.wait_until_stop_blocking()\n        self.assertFalse(self.widget.Error.no_binary_features.is_shown())\n        self.assertTrue(self.widget.Warning.ignoring_nonbinary.is_shown())\n\n        self.send_signal(self.widget.Inputs.data, None)\n        self.wait_until_stop_blocking()\n        self.assertFalse(self.widget.Error.no_binary_features.is_shown())\n        self.assertFalse(self.widget.Warning.ignoring_nonbinary.is_shown())\n\n        self.send_signal(self.widget.Inputs.data, self.titanic)\n        self.wait_until_stop_blocking()\n        self.assertFalse(self.widget.Error.no_binary_features.is_shown())\n        self.assertTrue(self.widget.Warning.ignoring_nonbinary.is_shown())\n\n        dom = self.titanic.domain\n        dom = Domain(dom.attributes[1:], dom.class_var)\n        self.send_signal(self.widget.Inputs.data, self.titanic.transform(dom))\n        self.wait_until_stop_blocking()\n        self.assertFalse(self.widget.Error.no_binary_features.is_shown())\n        self.assertFalse(self.widget.Warning.ignoring_nonbinary.is_shown())\n\n        self.send_signal(self.widget.Inputs.data, Table(\"heart_disease\"))\n        self.wait_until_stop_blocking()\n        self.assertFalse(self.widget.Error.no_binary_features.is_shown())\n        self.assertFalse(self.widget.Warning.ignoring_discrete.is_shown())\n\n    def test_too_big_array(self):\n        \"\"\"\n        Users sees an error message when calculating too large arrays and Orange\n        does not crash.\n        GH-2315\n        \"\"\"\n        self.assertEqual(len(self.widget.Error.active), 0)\n        self.send_signal(self.widget.Inputs.data, self.iris)\n\n        mock = Mock(side_effect=ValueError)\n        self.widget.compute_distances(mock, self.iris)\n        self.wait_until_finished()\n        self.assertTrue(self.widget.Error.distances_value_error.is_shown())\n\n        mock = Mock(side_effect=MemoryError)\n        self.widget.compute_distances(mock, self.iris)\n        self.wait_until_finished()\n        self.assertEqual(len(self.widget.Error.active), 1)\n        self.assertTrue(self.widget.Error.distances_memory_error.is_shown())\n\n    def test_migrates_normalized_dist(self):\n        w = self.create_widget(OWDistances, stored_settings={\"metric_idx\": 0})\n        self.assertFalse(w.normalized_dist)\n\n    def test_negative_values_bhattacharyya(self):\n        self.iris.X[0, 0] *= -1\n        for self.widget.metric_idx, (_, metric) in enumerate(METRICS):\n            if metric == distance.Bhattacharyya:\n                break\n        self.send_signal(self.widget.Inputs.data, self.iris)\n        self.wait_until_finished()\n        self.assertTrue(self.widget.Error.distances_value_error.is_shown())\n        self.iris.X[0, 0] *= -1\n\n    def test_limit_mahalanobis(self):\n        def assert_error_shown():\n            self.assertTrue(\n                self.widget.Error.data_too_large_for_mahalanobis.is_shown())\n\n        def assert_no_error():\n            self.assertFalse(\n                self.widget.Error.data_too_large_for_mahalanobis.is_shown())\n\n        widget = self.widget\n        axis_buttons = widget.controls.axis.buttons\n\n        self.assertEqual(widget.metrics_combo.count(), len(METRICS))\n        for i, (_, metric) in enumerate(METRICS):\n            if metric == distance.Mahalanobis:\n                widget.metrics_combo.setCurrentIndex(i)\n                widget.metrics_combo.activated.emit(i)\n                break\n\n        X = np.random.random((1010, 4))\n        bigrows = Table.from_numpy(Domain(self.iris.domain.attributes), X)\n        bigcols = Table.from_numpy(\n            Domain([ContinuousVariable(f\"{i}\") for i in range(1010)]), X.T)\n\n        self.send_signal(widget.Inputs.data, self.iris)\n        assert_no_error()\n\n        axis_buttons[0].click()\n        assert_no_error()\n        axis_buttons[1].click()\n        assert_no_error()\n\n        # by columns -- cannot handle too many rows\n        self.send_signal(self.widget.Inputs.data, bigrows)\n        assert_error_shown()\n        axis_buttons[0].click()\n        assert_no_error()\n        axis_buttons[1].click()\n        assert_error_shown()\n\n        self.send_signal(self.widget.Inputs.data, bigcols)\n        assert_no_error()\n        axis_buttons[0].click()\n        assert_error_shown()\n\n        self.send_signal(widget.Inputs.data, self.iris)\n        assert_no_error()\n\n    def test_discrete_in_metas(self):\n        domain = self.iris.domain\n        data = self.iris.transform(\n            Domain(domain.attributes[:-1] + (domain.class_var, ),\n                   [],\n                   domain.attributes[-1:])\n        )\n        for self.widget.metric_idx, (_, metric) in enumerate(METRICS):\n            if metric == distance.Cosine:\n                break\n        self.send_signal(self.widget.Inputs.data, data)\n        self.wait_until_finished()\n        out = self.get_output(self.widget.Outputs.distances)\n        out_domain = out.row_items.domain\n        self.assertEqual(out_domain.attributes, domain.attributes[:-1])\n        self.assertEqual(out_domain.metas,\n                         (domain.attributes[-1], domain.class_var))\n\n    def test_non_binary_in_metas(self):\n        for self.widget.metric_idx, (_, metric) in enumerate(METRICS):\n            if metric == distance.Jaccard:\n                break\n        zoo = Table(\"zoo\")[:20]\n        self.send_signal(self.widget.Inputs.data, zoo)\n        self.wait_until_finished()\n        out = self.get_output(self.widget.Outputs.distances)\n        domain = zoo.domain\n        out_domain = out.row_items.domain\n        self.assertEqual(out_domain.metas, (domain[\"name\"], domain[\"legs\"]))\n\n\nif __name__ == \"__main__\":\n    unittest.main()\n"
    ],
    "test_file_names": [
        "test_1.py",
        "test_2.py"
    ],
    "setup_res_code": 0,
    "setup_res_stdout": "Starting Orange installation attempts...\nAttempting installation with Python 3.7...\nrunning build_ext\nCompiling Orange/classification/_tree_scorers.pyx because it changed.\nCompiling Orange/data/_contingency.pyx because it changed.\nCompiling Orange/data/_io.pyx because it changed.\nCompiling Orange/data/_valuecount.pyx because it changed.\nCompiling Orange/data/_variable.pyx because it changed.\nCompiling Orange/distance/_distance.pyx because it changed.\nCompiling Orange/preprocess/_discretize.pyx because it changed.\nCompiling Orange/preprocess/_relieff.pyx because it changed.\nCompiling Orange/projection/_som.pyx because it changed.\n[1/9] Cythonizing Orange/classification/_tree_scorers.pyx\n[2/9] Cythonizing Orange/data/_contingency.pyx\n[3/9] Cythonizing Orange/data/_io.pyx\n[4/9] Cythonizing Orange/data/_valuecount.pyx\n[5/9] Cythonizing Orange/data/_variable.pyx\n[6/9] Cythonizing Orange/distance/_distance.pyx\n[7/9] Cythonizing Orange/preprocess/_discretize.pyx\n[8/9] Cythonizing Orange/preprocess/_relieff.pyx\n[9/9] Cythonizing Orange/projection/_som.pyx\nbuilding 'Orange.classification._tree_scorers' extension\ncreating build\ncreating build/temp.linux-x86_64-3.7\ncreating build/temp.linux-x86_64-3.7/Orange\ncreating build/temp.linux-x86_64-3.7/Orange/classification\ncc -pthread -Wno-unused-result -Wsign-compare -Wunreachable-code -DNDEBUG -g -fwrapv -O3 -Wall -fPIC -I/tools/deps/include -I/tools/deps/include/ncursesw -fPIC -I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_0aa1714905af5673407e326867870ea8946d262f/.venv/lib/python3.7/site-packages/numpy/core/include -I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_0aa1714905af5673407e326867870ea8946d262f/.venv/include -I/home/gcpuser/.local/share/uv/python/cpython-3.7.9-linux-x86_64-gnu/include/python3.7m -c Orange/classification/_tree_scorers.c -o build/temp.linux-x86_64-3.7/Orange/classification/_tree_scorers.o\ncreating build/lib.linux-x86_64-3.7\ncreating build/lib.linux-x86_64-3.7/Orange\ncreating build/lib.linux-x86_64-3.7/Orange/classification\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 build/lib.linux-x86_64-3.7/Orange/classification/_tree_scorers.cpython-37m-x86_64-linux-gnu.so\nbuilding 'Orange.data._contingency' extension\ncreating build/temp.linux-x86_64-3.7/Orange/data\ncc -pthread -Wno-unused-result -Wsign-compare -Wunreachable-code -DNDEBUG -g -fwrapv -O3 -Wall -fPIC -I/tools/deps/include -I/tools/deps/include/ncursesw -fPIC -I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_0aa1714905af5673407e326867870ea8946d262f/.venv/lib/python3.7/site-packages/numpy/core/include -I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_0aa1714905af5673407e326867870ea8946d262f/.venv/include -I/home/gcpuser/.local/share/uv/python/cpython-3.7.9-linux-x86_64-gnu/include/python3.7m -c Orange/data/_contingency.c -o build/temp.linux-x86_64-3.7/Orange/data/_contingency.o\ncreating build/lib.linux-x86_64-3.7/Orange/data\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 build/lib.linux-x86_64-3.7/Orange/data/_contingency.cpython-37m-x86_64-linux-gnu.so\nbuilding 'Orange.data._io' extension\ncc -pthread -Wno-unused-result -Wsign-compare -Wunreachable-code -DNDEBUG -g -fwrapv -O3 -Wall -fPIC -I/tools/deps/include -I/tools/deps/include/ncursesw -fPIC -I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_0aa1714905af5673407e326867870ea8946d262f/.venv/lib/python3.7/site-packages/numpy/core/include -I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_0aa1714905af5673407e326867870ea8946d262f/.venv/include -I/home/gcpuser/.local/share/uv/python/cpython-3.7.9-linux-x86_64-gnu/include/python3.7m -c Orange/data/_io.c -o build/temp.linux-x86_64-3.7/Orange/data/_io.o\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 build/lib.linux-x86_64-3.7/Orange/data/_io.cpython-37m-x86_64-linux-gnu.so\nbuilding 'Orange.data._valuecount' extension\ncc -pthread -Wno-unused-result -Wsign-compare -Wunreachable-code -DNDEBUG -g -fwrapv -O3 -Wall -fPIC -I/tools/deps/include -I/tools/deps/include/ncursesw -fPIC -I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_0aa1714905af5673407e326867870ea8946d262f/.venv/lib/python3.7/site-packages/numpy/core/include -I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_0aa1714905af5673407e326867870ea8946d262f/.venv/include -I/home/gcpuser/.local/share/uv/python/cpython-3.7.9-linux-x86_64-gnu/include/python3.7m -c Orange/data/_valuecount.c -o build/temp.linux-x86_64-3.7/Orange/data/_valuecount.o\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 build/lib.linux-x86_64-3.7/Orange/data/_valuecount.cpython-37m-x86_64-linux-gnu.so\nbuilding 'Orange.data._variable' extension\ncc -pthread -Wno-unused-result -Wsign-compare -Wunreachable-code -DNDEBUG -g -fwrapv -O3 -Wall -fPIC -I/tools/deps/include -I/tools/deps/include/ncursesw -fPIC -I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_0aa1714905af5673407e326867870ea8946d262f/.venv/lib/python3.7/site-packages/numpy/core/include -I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_0aa1714905af5673407e326867870ea8946d262f/.venv/include -I/home/gcpuser/.local/share/uv/python/cpython-3.7.9-linux-x86_64-gnu/include/python3.7m -c Orange/data/_variable.c -o build/temp.linux-x86_64-3.7/Orange/data/_variable.o\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 build/lib.linux-x86_64-3.7/Orange/data/_variable.cpython-37m-x86_64-linux-gnu.so\nbuilding 'Orange.distance._distance' extension\ncreating build/temp.linux-x86_64-3.7/Orange/distance\ncc -pthread -Wno-unused-result -Wsign-compare -Wunreachable-code -DNDEBUG -g -fwrapv -O3 -Wall -fPIC -I/tools/deps/include -I/tools/deps/include/ncursesw -fPIC -I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_0aa1714905af5673407e326867870ea8946d262f/.venv/lib/python3.7/site-packages/numpy/core/include -I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_0aa1714905af5673407e326867870ea8946d262f/.venv/include -I/home/gcpuser/.local/share/uv/python/cpython-3.7.9-linux-x86_64-gnu/include/python3.7m -c Orange/distance/_distance.c -o build/temp.linux-x86_64-3.7/Orange/distance/_distance.o\ncreating build/lib.linux-x86_64-3.7/Orange/distance\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 build/lib.linux-x86_64-3.7/Orange/distance/_distance.cpython-37m-x86_64-linux-gnu.so\nbuilding 'Orange.preprocess._discretize' extension\ncreating build/temp.linux-x86_64-3.7/Orange/preprocess\ncc -pthread -Wno-unused-result -Wsign-compare -Wunreachable-code -DNDEBUG -g -fwrapv -O3 -Wall -fPIC -I/tools/deps/include -I/tools/deps/include/ncursesw -fPIC -I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_0aa1714905af5673407e326867870ea8946d262f/.venv/lib/python3.7/site-packages/numpy/core/include -I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_0aa1714905af5673407e326867870ea8946d262f/.venv/include -I/home/gcpuser/.local/share/uv/python/cpython-3.7.9-linux-x86_64-gnu/include/python3.7m -c Orange/preprocess/_discretize.c -o build/temp.linux-x86_64-3.7/Orange/preprocess/_discretize.o\ncreating build/lib.linux-x86_64-3.7/Orange/preprocess\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 build/lib.linux-x86_64-3.7/Orange/preprocess/_discretize.cpython-37m-x86_64-linux-gnu.so\nbuilding 'Orange.preprocess._relieff' extension\ncc -pthread -Wno-unused-result -Wsign-compare -Wunreachable-code -DNDEBUG -g -fwrapv -O3 -Wall -fPIC -I/tools/deps/include -I/tools/deps/include/ncursesw -fPIC -I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_0aa1714905af5673407e326867870ea8946d262f/.venv/lib/python3.7/site-packages/numpy/core/include -I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_0aa1714905af5673407e326867870ea8946d262f/.venv/include -I/home/gcpuser/.local/share/uv/python/cpython-3.7.9-linux-x86_64-gnu/include/python3.7m -c Orange/preprocess/_relieff.cpp -o build/temp.linux-x86_64-3.7/Orange/preprocess/_relieff.o\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 build/lib.linux-x86_64-3.7/Orange/preprocess/_relieff.cpython-37m-x86_64-linux-gnu.so\nbuilding 'Orange.projection._som' extension\ncreating build/temp.linux-x86_64-3.7/Orange/projection\ncc -pthread -Wno-unused-result -Wsign-compare -Wunreachable-code -DNDEBUG -g -fwrapv -O3 -Wall -fPIC -I/tools/deps/include -I/tools/deps/include/ncursesw -fPIC -I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_0aa1714905af5673407e326867870ea8946d262f/.venv/lib/python3.7/site-packages/numpy/core/include -I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_0aa1714905af5673407e326867870ea8946d262f/.venv/include -I/home/gcpuser/.local/share/uv/python/cpython-3.7.9-linux-x86_64-gnu/include/python3.7m -c Orange/projection/_som.c -o build/temp.linux-x86_64-3.7/Orange/projection/_som.o\ncreating build/lib.linux-x86_64-3.7/Orange/projection\ncc -pthread -shared -L/tools/deps/lib build/temp.linux-x86_64-3.7/Orange/projection/_som.o -L/home/gcpuser/.local/share/uv/python/cpython-3.7.9-linux-x86_64-gnu/lib -lm -lpython3.7m -o build/lib.linux-x86_64-3.7/Orange/projection/_som.cpython-37m-x86_64-linux-gnu.so\nbuilding 'Orange.classification._simple_tree' extension\ncc -pthread -Wno-unused-result -Wsign-compare -Wunreachable-code -DNDEBUG -g -fwrapv -O3 -Wall -fPIC -I/tools/deps/include -I/tools/deps/include/ncursesw -fPIC -I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_0aa1714905af5673407e326867870ea8946d262f/.venv/lib/python3.7/site-packages/numpy/core/include -I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_0aa1714905af5673407e326867870ea8946d262f/.venv/include -I/home/gcpuser/.local/share/uv/python/cpython-3.7.9-linux-x86_64-gnu/include/python3.7m -c Orange/classification/_simple_tree.c -o build/temp.linux-x86_64-3.7/Orange/classification/_simple_tree.o\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 build/lib.linux-x86_64-3.7/Orange/classification/_simple_tree.cpython-37m-x86_64-linux-gnu.so\nbuilding 'Orange.widgets.utils._grid_density' extension\ncreating build/temp.linux-x86_64-3.7/Orange/widgets\ncreating build/temp.linux-x86_64-3.7/Orange/widgets/utils\ncc -pthread -Wno-unused-result -Wsign-compare -Wunreachable-code -DNDEBUG -g -fwrapv -O3 -Wall -fPIC -I/tools/deps/include -I/tools/deps/include/ncursesw -fPIC -I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_0aa1714905af5673407e326867870ea8946d262f/.venv/lib/python3.7/site-packages/numpy/core/include -I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_0aa1714905af5673407e326867870ea8946d262f/.venv/include -I/home/gcpuser/.local/share/uv/python/cpython-3.7.9-linux-x86_64-gnu/include/python3.7m -c Orange/widgets/utils/_grid_density.cpp -o build/temp.linux-x86_64-3.7/Orange/widgets/utils/_grid_density.o\ncreating build/lib.linux-x86_64-3.7/Orange/widgets\ncreating build/lib.linux-x86_64-3.7/Orange/widgets/utils\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 build/lib.linux-x86_64-3.7/Orange/widgets/utils/_grid_density.cpython-37m-x86_64-linux-gnu.so\ncopying build/lib.linux-x86_64-3.7/Orange/classification/_tree_scorers.cpython-37m-x86_64-linux-gnu.so -> Orange/classification\ncopying build/lib.linux-x86_64-3.7/Orange/data/_contingency.cpython-37m-x86_64-linux-gnu.so -> Orange/data\ncopying build/lib.linux-x86_64-3.7/Orange/data/_io.cpython-37m-x86_64-linux-gnu.so -> Orange/data\ncopying build/lib.linux-x86_64-3.7/Orange/data/_valuecount.cpython-37m-x86_64-linux-gnu.so -> Orange/data\ncopying build/lib.linux-x86_64-3.7/Orange/data/_variable.cpython-37m-x86_64-linux-gnu.so -> Orange/data\ncopying build/lib.linux-x86_64-3.7/Orange/distance/_distance.cpython-37m-x86_64-linux-gnu.so -> Orange/distance\ncopying build/lib.linux-x86_64-3.7/Orange/preprocess/_discretize.cpython-37m-x86_64-linux-gnu.so -> Orange/preprocess\ncopying build/lib.linux-x86_64-3.7/Orange/preprocess/_relieff.cpython-37m-x86_64-linux-gnu.so -> Orange/preprocess\ncopying build/lib.linux-x86_64-3.7/Orange/projection/_som.cpython-37m-x86_64-linux-gnu.so -> Orange/projection\ncopying build/lib.linux-x86_64-3.7/Orange/classification/_simple_tree.cpython-37m-x86_64-linux-gnu.so -> Orange/classification\ncopying build/lib.linux-x86_64-3.7/Orange/widgets/utils/_grid_density.cpython-37m-x86_64-linux-gnu.so -> Orange/widgets/utils\nrunning develop\nrunning egg_info\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'\nadding license file 'LICENSE'\nwriting manifest file 'Orange3.egg-info/SOURCES.txt'\nrunning build_ext\ncopying build/lib.linux-x86_64-3.7/Orange/classification/_tree_scorers.cpython-37m-x86_64-linux-gnu.so -> Orange/classification\ncopying build/lib.linux-x86_64-3.7/Orange/data/_contingency.cpython-37m-x86_64-linux-gnu.so -> Orange/data\ncopying build/lib.linux-x86_64-3.7/Orange/data/_io.cpython-37m-x86_64-linux-gnu.so -> Orange/data\ncopying build/lib.linux-x86_64-3.7/Orange/data/_valuecount.cpython-37m-x86_64-linux-gnu.so -> Orange/data\ncopying build/lib.linux-x86_64-3.7/Orange/data/_variable.cpython-37m-x86_64-linux-gnu.so -> Orange/data\ncopying build/lib.linux-x86_64-3.7/Orange/distance/_distance.cpython-37m-x86_64-linux-gnu.so -> Orange/distance\ncopying build/lib.linux-x86_64-3.7/Orange/preprocess/_discretize.cpython-37m-x86_64-linux-gnu.so -> Orange/preprocess\ncopying build/lib.linux-x86_64-3.7/Orange/preprocess/_relieff.cpython-37m-x86_64-linux-gnu.so -> Orange/preprocess\ncopying build/lib.linux-x86_64-3.7/Orange/projection/_som.cpython-37m-x86_64-linux-gnu.so -> Orange/projection\ncopying build/lib.linux-x86_64-3.7/Orange/classification/_simple_tree.cpython-37m-x86_64-linux-gnu.so -> Orange/classification\ncopying build/lib.linux-x86_64-3.7/Orange/widgets/utils/_grid_density.cpython-37m-x86_64-linux-gnu.so -> Orange/widgets/utils\nCreating /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_0aa1714905af5673407e326867870ea8946d262f/.venv/lib/python3.7/site-packages/Orange3.egg-link (link to .)\nAdding Orange3 3.31.0.dev0+0aa1714 to easy-install.pth file\nInstalling orange-canvas script to /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_0aa1714905af5673407e326867870ea8946d262f/.venv/bin\n\nInstalled /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_0aa1714905af5673407e326867870ea8946d262f\nProcessing dependencies for Orange3==3.31.0.dev0+0aa1714\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_0aa1714905af5673407e326867870ea8946d262f/.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_0aa1714905af5673407e326867870ea8946d262f/.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_0aa1714905af5673407e326867870ea8946d262f/.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_0aa1714905af5673407e326867870ea8946d262f/.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_0aa1714905af5673407e326867870ea8946d262f/.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_0aa1714905af5673407e326867870ea8946d262f/.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_0aa1714905af5673407e326867870ea8946d262f/.venv/lib/python3.7/site-packages\nSearching for qtconsole==5.4.4\nBest match: qtconsole 5.4.4\nAdding qtconsole 5.4.4 to easy-install.pth file\nInstalling jupyter-qtconsole script to /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_0aa1714905af5673407e326867870ea8946d262f/.venv/bin\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_0aa1714905af5673407e326867870ea8946d262f/.venv/lib/python3.7/site-packages\nSearching for PyYAML==6.0.1\nBest match: PyYAML 6.0.1\nAdding PyYAML 6.0.1 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_0aa1714905af5673407e326867870ea8946d262f/.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_0aa1714905af5673407e326867870ea8946d262f/.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_0aa1714905af5673407e326867870ea8946d262f/.venv/lib/python3.7/site-packages\nSearching for pygments==2.17.2\nBest match: pygments 2.17.2\nAdding pygments 2.17.2 to easy-install.pth file\nInstalling pygmentize script to /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_0aa1714905af5673407e326867870ea8946d262f/.venv/bin\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_0aa1714905af5673407e326867870ea8946d262f/.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_0aa1714905af5673407e326867870ea8946d262f/.venv/bin\nInstalling pip3 script to /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_0aa1714905af5673407e326867870ea8946d262f/.venv/bin\nInstalling pip3.10 script to /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_0aa1714905af5673407e326867870ea8946d262f/.venv/bin\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_0aa1714905af5673407e326867870ea8946d262f/.venv/lib/python3.7/site-packages\nSearching for pandas==1.3.5\nBest match: pandas 1.3.5\nAdding pandas 1.3.5 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_0aa1714905af5673407e326867870ea8946d262f/.venv/lib/python3.7/site-packages\nSearching for orange-widget-base==4.22.0\nBest match: orange-widget-base 4.22.0\nAdding orange-widget-base 4.22.0 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_0aa1714905af5673407e326867870ea8946d262f/.venv/lib/python3.7/site-packages\nSearching for orange-canvas-core==0.1.35\nBest match: orange-canvas-core 0.1.35\nAdding orange-canvas-core 0.1.35 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_0aa1714905af5673407e326867870ea8946d262f/.venv/lib/python3.7/site-packages\nSearching for openpyxl==3.1.3\nBest match: openpyxl 3.1.3\nAdding openpyxl 3.1.3 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_0aa1714905af5673407e326867870ea8946d262f/.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_0aa1714905af5673407e326867870ea8946d262f/.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_0aa1714905af5673407e326867870ea8946d262f/.venv/bin\nInstalling f2py3 script to /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_0aa1714905af5673407e326867870ea8946d262f/.venv/bin\nInstalling f2py3.7 script to /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_0aa1714905af5673407e326867870ea8946d262f/.venv/bin\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_0aa1714905af5673407e326867870ea8946d262f/.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_0aa1714905af5673407e326867870ea8946d262f/.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_0aa1714905af5673407e326867870ea8946d262f/.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_0aa1714905af5673407e326867870ea8946d262f/.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_0aa1714905af5673407e326867870ea8946d262f/.venv/bin\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_0aa1714905af5673407e326867870ea8946d262f/.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_0aa1714905af5673407e326867870ea8946d262f/.venv/lib/python3.7/site-packages\nSearching for httpx==0.19.0\nBest match: httpx 0.19.0\nAdding httpx 0.19.0 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_0aa1714905af5673407e326867870ea8946d262f/.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_0aa1714905af5673407e326867870ea8946d262f/.venv/bin\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_0aa1714905af5673407e326867870ea8946d262f/.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_0aa1714905af5673407e326867870ea8946d262f/.venv/lib/python3.7/site-packages\nSearching for baycomp==1.0.3\nBest match: baycomp 1.0.3\nAdding baycomp 1.0.3 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_0aa1714905af5673407e326867870ea8946d262f/.venv/lib/python3.7/site-packages\nSearching for PyQtWebEngine==5.15.6\nBest match: PyQtWebEngine 5.15.6\nAdding PyQtWebEngine 5.15.6 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_0aa1714905af5673407e326867870ea8946d262f/.venv/lib/python3.7/site-packages\nSearching for PyQt5==5.15.10\nBest match: PyQt5 5.15.10\nAdding PyQt5 5.15.10 to easy-install.pth file\nInstalling pylupdate5 script to /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_0aa1714905af5673407e326867870ea8946d262f/.venv/bin\nInstalling pyrcc5 script to /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_0aa1714905af5673407e326867870ea8946d262f/.venv/bin\nInstalling pyuic5 script to /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_0aa1714905af5673407e326867870ea8946d262f/.venv/bin\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_0aa1714905af5673407e326867870ea8946d262f/.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_0aa1714905af5673407e326867870ea8946d262f/.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_0aa1714905af5673407e326867870ea8946d262f/.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_0aa1714905af5673407e326867870ea8946d262f/.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_0aa1714905af5673407e326867870ea8946d262f/.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_0aa1714905af5673407e326867870ea8946d262f/.venv/bin\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_0aa1714905af5673407e326867870ea8946d262f/.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_0aa1714905af5673407e326867870ea8946d262f/.venv/lib/python3.7/site-packages\nSearching for ipykernel==6.16.2\nBest match: ipykernel 6.16.2\nAdding ipykernel 6.16.2 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_0aa1714905af5673407e326867870ea8946d262f/.venv/lib/python3.7/site-packages\nSearching for jupyter-client==7.4.9\nBest match: jupyter-client 7.4.9\nAdding jupyter-client 7.4.9 to easy-install.pth file\nInstalling jupyter-kernel script to /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_0aa1714905af5673407e326867870ea8946d262f/.venv/bin\nInstalling jupyter-kernelspec script to /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_0aa1714905af5673407e326867870ea8946d262f/.venv/bin\nInstalling jupyter-run script to /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_0aa1714905af5673407e326867870ea8946d262f/.venv/bin\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_0aa1714905af5673407e326867870ea8946d262f/.venv/lib/python3.7/site-packages\nSearching for jupyter-core==4.12.0\nBest match: jupyter-core 4.12.0\nAdding jupyter-core 4.12.0 to easy-install.pth file\nInstalling jupyter script to /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_0aa1714905af5673407e326867870ea8946d262f/.venv/bin\nInstalling jupyter-migrate script to /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_0aa1714905af5673407e326867870ea8946d262f/.venv/bin\nInstalling jupyter-troubleshoot script to /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_0aa1714905af5673407e326867870ea8946d262f/.venv/bin\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_0aa1714905af5673407e326867870ea8946d262f/.venv/lib/python3.7/site-packages\nSearching for ipython-genutils==0.2.0\nBest match: ipython-genutils 0.2.0\nAdding ipython-genutils 0.2.0 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_0aa1714905af5673407e326867870ea8946d262f/.venv/lib/python3.7/site-packages\nSearching for pyzmq==26.2.0\nBest match: pyzmq 26.2.0\nAdding pyzmq 26.2.0 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_0aa1714905af5673407e326867870ea8946d262f/.venv/lib/python3.7/site-packages\nSearching for traitlets==5.9.0\nBest match: traitlets 5.9.0\nAdding traitlets 5.9.0 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_0aa1714905af5673407e326867870ea8946d262f/.venv/lib/python3.7/site-packages\nSearching for QtPy==2.4.2\nBest match: QtPy 2.4.2\nAdding QtPy 2.4.2 to easy-install.pth file\nInstalling qtpy script to /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_0aa1714905af5673407e326867870ea8946d262f/.venv/bin\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_0aa1714905af5673407e326867870ea8946d262f/.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_0aa1714905af5673407e326867870ea8946d262f/.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_0aa1714905af5673407e326867870ea8946d262f/.venv/lib/python3.7/site-packages\nSearching for pytz==2024.2\nBest match: pytz 2024.2\nAdding pytz 2024.2 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_0aa1714905af5673407e326867870ea8946d262f/.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_0aa1714905af5673407e326867870ea8946d262f/.venv/lib/python3.7/site-packages\nSearching for qasync==0.25.0\nBest match: qasync 0.25.0\nAdding qasync 0.25.0 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_0aa1714905af5673407e326867870ea8946d262f/.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_0aa1714905af5673407e326867870ea8946d262f/.venv/lib/python3.7/site-packages\nSearching for requests-cache==1.1.1\nBest match: requests-cache 1.1.1\nAdding requests-cache 1.1.1 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_0aa1714905af5673407e326867870ea8946d262f/.venv/lib/python3.7/site-packages\nSearching for dictdiffer==0.9.0\nBest match: dictdiffer 0.9.0\nAdding dictdiffer 0.9.0 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_0aa1714905af5673407e326867870ea8946d262f/.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_0aa1714905af5673407e326867870ea8946d262f/.venv/bin\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_0aa1714905af5673407e326867870ea8946d262f/.venv/lib/python3.7/site-packages\nSearching for commonmark==0.9.1\nBest match: commonmark 0.9.1\nAdding commonmark 0.9.1 to easy-install.pth file\nInstalling cmark script to /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_0aa1714905af5673407e326867870ea8946d262f/.venv/bin\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_0aa1714905af5673407e326867870ea8946d262f/.venv/lib/python3.7/site-packages\nSearching for et-xmlfile==1.1.0\nBest match: et-xmlfile 1.1.0\nAdding et-xmlfile 1.1.0 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_0aa1714905af5673407e326867870ea8946d262f/.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_0aa1714905af5673407e326867870ea8946d262f/.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_0aa1714905af5673407e326867870ea8946d262f/.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_0aa1714905af5673407e326867870ea8946d262f/.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_0aa1714905af5673407e326867870ea8946d262f/.venv/bin\nInstalling pyftmerge script to /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_0aa1714905af5673407e326867870ea8946d262f/.venv/bin\nInstalling pyftsubset script to /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_0aa1714905af5673407e326867870ea8946d262f/.venv/bin\nInstalling ttx script to /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_0aa1714905af5673407e326867870ea8946d262f/.venv/bin\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_0aa1714905af5673407e326867870ea8946d262f/.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_0aa1714905af5673407e326867870ea8946d262f/.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_0aa1714905af5673407e326867870ea8946d262f/.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_0aa1714905af5673407e326867870ea8946d262f/.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_0aa1714905af5673407e326867870ea8946d262f/.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_0aa1714905af5673407e326867870ea8946d262f/.venv/lib/python3.7/site-packages\nSearching for rfc3986==1.5.0\nBest match: rfc3986 1.5.0\nAdding rfc3986 1.5.0 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_0aa1714905af5673407e326867870ea8946d262f/.venv/lib/python3.7/site-packages\nSearching for httpcore==0.13.7\nBest match: httpcore 0.13.7\nAdding httpcore 0.13.7 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_0aa1714905af5673407e326867870ea8946d262f/.venv/lib/python3.7/site-packages\nSearching for sniffio==1.3.1\nBest match: sniffio 1.3.1\nAdding sniffio 1.3.1 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_0aa1714905af5673407e326867870ea8946d262f/.venv/lib/python3.7/site-packages\nSearching for PyQtWebEngine-Qt5==5.15.16\nBest match: PyQtWebEngine-Qt5 5.15.16\nAdding PyQtWebEngine-Qt5 5.15.16 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_0aa1714905af5673407e326867870ea8946d262f/.venv/lib/python3.7/site-packages\nSearching for PyQt5-sip==12.13.0\nBest match: PyQt5-sip 12.13.0\nAdding PyQt5-sip 12.13.0 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_0aa1714905af5673407e326867870ea8946d262f/.venv/lib/python3.7/site-packages\nSearching for PyQt5-Qt5==5.15.16\nBest match: PyQt5-Qt5 5.15.16\nAdding PyQt5-Qt5 5.15.16 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_0aa1714905af5673407e326867870ea8946d262f/.venv/lib/python3.7/site-packages\nSearching for tornado==6.2\nBest match: tornado 6.2\nAdding tornado 6.2 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_0aa1714905af5673407e326867870ea8946d262f/.venv/lib/python3.7/site-packages\nSearching for debugpy==1.7.0\nBest match: debugpy 1.7.0\nAdding debugpy 1.7.0 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_0aa1714905af5673407e326867870ea8946d262f/.venv/lib/python3.7/site-packages\nSearching for nest-asyncio==1.6.0\nBest match: nest-asyncio 1.6.0\nAdding nest-asyncio 1.6.0 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_0aa1714905af5673407e326867870ea8946d262f/.venv/lib/python3.7/site-packages\nSearching for ipython==7.34.0\nBest match: ipython 7.34.0\nAdding ipython 7.34.0 to easy-install.pth file\nInstalling iptest script to /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_0aa1714905af5673407e326867870ea8946d262f/.venv/bin\nInstalling iptest3 script to /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_0aa1714905af5673407e326867870ea8946d262f/.venv/bin\nInstalling ipython script to /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_0aa1714905af5673407e326867870ea8946d262f/.venv/bin\nInstalling ipython3 script to /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_0aa1714905af5673407e326867870ea8946d262f/.venv/bin\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_0aa1714905af5673407e326867870ea8946d262f/.venv/lib/python3.7/site-packages\nSearching for psutil==6.1.1\nBest match: psutil 6.1.1\nAdding psutil 6.1.1 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_0aa1714905af5673407e326867870ea8946d262f/.venv/lib/python3.7/site-packages\nSearching for matplotlib-inline==0.1.6\nBest match: matplotlib-inline 0.1.6\nAdding matplotlib-inline 0.1.6 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_0aa1714905af5673407e326867870ea8946d262f/.venv/lib/python3.7/site-packages\nSearching for entrypoints==0.4\nBest match: entrypoints 0.4\nAdding entrypoints 0.4 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_0aa1714905af5673407e326867870ea8946d262f/.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_0aa1714905af5673407e326867870ea8946d262f/.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_0aa1714905af5673407e326867870ea8946d262f/.venv/lib/python3.7/site-packages\nSearching for attrs==24.2.0\nBest match: attrs 24.2.0\nAdding attrs 24.2.0 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_0aa1714905af5673407e326867870ea8946d262f/.venv/lib/python3.7/site-packages\nSearching for url-normalize==1.4.3\nBest match: url-normalize 1.4.3\nAdding url-normalize 1.4.3 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_0aa1714905af5673407e326867870ea8946d262f/.venv/lib/python3.7/site-packages\nSearching for platformdirs==4.0.0\nBest match: platformdirs 4.0.0\nAdding platformdirs 4.0.0 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_0aa1714905af5673407e326867870ea8946d262f/.venv/lib/python3.7/site-packages\nSearching for cattrs==23.1.2\nBest match: cattrs 23.1.2\nAdding cattrs 23.1.2 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_0aa1714905af5673407e326867870ea8946d262f/.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_0aa1714905af5673407e326867870ea8946d262f/.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_0aa1714905af5673407e326867870ea8946d262f/.venv/lib/python3.7/site-packages\nSearching for h11==0.12.0\nBest match: h11 0.12.0\nAdding h11 0.12.0 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_0aa1714905af5673407e326867870ea8946d262f/.venv/lib/python3.7/site-packages\nSearching for anyio==3.7.1\nBest match: anyio 3.7.1\nAdding anyio 3.7.1 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_0aa1714905af5673407e326867870ea8946d262f/.venv/lib/python3.7/site-packages\nSearching for backcall==0.2.0\nBest match: backcall 0.2.0\nAdding backcall 0.2.0 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_0aa1714905af5673407e326867870ea8946d262f/.venv/lib/python3.7/site-packages\nSearching for jedi==0.19.2\nBest match: jedi 0.19.2\nAdding jedi 0.19.2 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_0aa1714905af5673407e326867870ea8946d262f/.venv/lib/python3.7/site-packages\nSearching for pexpect==4.9.0\nBest match: pexpect 4.9.0\nAdding pexpect 4.9.0 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_0aa1714905af5673407e326867870ea8946d262f/.venv/lib/python3.7/site-packages\nSearching for pickleshare==0.7.5\nBest match: pickleshare 0.7.5\nAdding pickleshare 0.7.5 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_0aa1714905af5673407e326867870ea8946d262f/.venv/lib/python3.7/site-packages\nSearching for prompt-toolkit==3.0.48\nBest match: prompt-toolkit 3.0.48\nAdding prompt-toolkit 3.0.48 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_0aa1714905af5673407e326867870ea8946d262f/.venv/lib/python3.7/site-packages\nSearching for decorator==5.1.1\nBest match: decorator 5.1.1\nAdding decorator 5.1.1 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_0aa1714905af5673407e326867870ea8946d262f/.venv/lib/python3.7/site-packages\nSearching for exceptiongroup==1.2.2\nBest match: exceptiongroup 1.2.2\nAdding exceptiongroup 1.2.2 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_0aa1714905af5673407e326867870ea8946d262f/.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_0aa1714905af5673407e326867870ea8946d262f/.venv/lib/python3.7/site-packages\nSearching for parso==0.8.4\nBest match: parso 0.8.4\nAdding parso 0.8.4 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_0aa1714905af5673407e326867870ea8946d262f/.venv/lib/python3.7/site-packages\nSearching for ptyprocess==0.7.0\nBest match: ptyprocess 0.7.0\nAdding ptyprocess 0.7.0 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_0aa1714905af5673407e326867870ea8946d262f/.venv/lib/python3.7/site-packages\nSearching for wcwidth==0.2.13\nBest match: wcwidth 0.2.13\nAdding wcwidth 0.2.13 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_0aa1714905af5673407e326867870ea8946d262f/.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_0aa1714905af5673407e326867870ea8946d262f/.venv/lib/python3.7/site-packages\nFinished processing dependencies for Orange3==3.31.0.dev0+0aa1714\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 122ms\nPrepared 18 packages in 5ms\nInstalled 18 packages in 84ms\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 55 packages in 343ms\nInstalled 48 packages in 790ms\n + anyio==3.7.1\n + baycomp==1.0.3\n + bottleneck==1.4.0\n + certifi==2024.12.14\n + cffi==1.15.1\n + chardet==5.2.0\n + charset-normalizer==3.4.1\n + cryptography==44.0.0\n + cycler==0.11.0\n + et-xmlfile==1.1.0\n + fonttools==4.38.0\n + h11==0.12.0\n + httpcore==0.13.7\n + httpx==0.19.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 + kiwisolver==1.4.5\n + matplotlib==3.5.3\n + more-itertools==9.1.0\n + networkx==2.6.3\n + openpyxl==3.1.3\n + opentsne==1.0.1\n + pandas==1.3.5\n + pillow==9.5.0\n + pip==24.0\n + pycparser==2.21\n + pyparsing==3.1.4\n + python-dateutil==2.9.0.post0\n + python-louvain==0.16\n + pytz==2024.2\n + pyyaml==6.0.1\n + requests==2.31.0\n + rfc3986==1.5.0\n + scikit-learn==1.0.2\n + scipy==1.7.3\n + secretstorage==3.3.3\n + serverfiles==0.3.1\n + six==1.17.0\n + sniffio==1.3.1\n + threadpoolctl==3.1.0\n + urllib3==2.0.7\n + xlrd==2.0.1\n + xlsxwriter==3.2.0\nResolved 59 packages in 283ms\nInstalled 38 packages in 675ms\n + anyqt==0.2.0\n + attrs==24.2.0\n + backcall==0.2.0\n + cattrs==23.1.2\n + commonmark==0.9.1\n + debugpy==1.7.0\n + decorator==5.1.1\n + dictdiffer==0.9.0\n + docutils==0.20.1\n + entrypoints==0.4\n + ipykernel==6.16.2\n + ipython==7.34.0\n + ipython-genutils==0.2.0\n + jedi==0.19.2\n + jupyter-client==7.4.9\n + jupyter-core==4.12.0\n + matplotlib-inline==0.1.6\n + nest-asyncio==1.6.0\n + orange-canvas-core==0.1.35\n + orange-widget-base==4.22.0\n + parso==0.8.4\n + pexpect==4.9.0\n + pickleshare==0.7.5\n + platformdirs==4.0.0\n + prompt-toolkit==3.0.48\n + psutil==6.1.1\n + ptyprocess==0.7.0\n + pygments==2.17.2\n + pyqtgraph==0.12.4\n + pyzmq==26.2.0\n + qasync==0.25.0\n + qtconsole==5.4.4\n + qtpy==2.4.2\n + requests-cache==1.1.1\n + tornado==6.2\n + traitlets==5.9.0\n + url-normalize==1.4.3\n + wcwidth==0.2.13\nResolved 2 packages in 4ms\nInstalled 2 packages in 23ms\n + psycopg2==2.9.9\n + pymssql==2.3.2\nResolved 19 packages in 36ms\nInstalled 5 packages in 1.04s\n + catboost==1.2.7\n + graphviz==0.20.1\n + plotly==5.18.0\n + tenacity==8.2.3\n + xgboost==1.6.2\nAudited 2 packages in 3ms\nIn file included from /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_0aa1714905af5673407e326867870ea8946d262f/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/ndarraytypes.h:1830,\n                 from /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_0aa1714905af5673407e326867870ea8946d262f/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/ndarrayobject.h:12,\n                 from /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_0aa1714905af5673407e326867870ea8946d262f/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/arrayobject.h:4,\n                 from Orange/classification/_tree_scorers.c:775:\n/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_0aa1714905af5673407e326867870ea8946d262f/.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:3413:27: warning: comparison of integer expressions of different signedness: ‘unsigned int’ and ‘int’ [-Wsign-compare]\n 3413 |   __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:4869:27: warning: comparison of integer expressions of different signedness: ‘unsigned int’ and ‘int’ [-Wsign-compare]\n 4869 |   __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:5615:43: warning: comparison of integer expressions of different signedness: ‘unsigned int’ and ‘int’ [-Wsign-compare]\n 5615 |           for (__pyx_t_19 = 0; __pyx_t_19 < __pyx_t_18; __pyx_t_19+=1) {\n      |                                           ^\nOrange/classification/_tree_scorers.c:5736:39: warning: comparison of integer expressions of different signedness: ‘unsigned int’ and ‘int’ [-Wsign-compare]\n 5736 |           __pyx_t_20 = ((__pyx_v_left >= __pyx_v_min_leaf) != 0);\n      |                                       ^~\nOrange/classification/_tree_scorers.c:5742:53: warning: comparison of integer expressions of different signedness: ‘unsigned int’ and ‘int’ [-Wsign-compare]\n 5742 |           __pyx_t_20 = (((__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:7202:41: warning: comparison of integer expressions of different signedness: ‘unsigned int’ and ‘int’ [-Wsign-compare]\n 7202 |         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:7857:41: warning: comparison of integer expressions of different signedness: ‘unsigned int’ and ‘int’ [-Wsign-compare]\n 7857 |         for (__pyx_t_11 = 0; __pyx_t_11 < __pyx_t_10; __pyx_t_11+=1) {\n      |                                         ^\nOrange/classification/_tree_scorers.c:7917:143: warning: comparison of integer expressions of different signedness: ‘__pyx_t_5numpy_int32_t’ {aka ‘int’} and ‘unsigned int’ [-Wsign-compare]\n 7917 |               __pyx_t_15 = (((*((__pyx_t_5numpy_int32_t *) ( /* dim=0 */ (__pyx_v_indices.data + __pyx_t_14 * __pyx_v_indices.strides[0]) ))) != __pyx_v_i) != 0);\n      |                                                                                                                                               ^~\nIn file included from /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_0aa1714905af5673407e326867870ea8946d262f/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/ndarraytypes.h:1830,\n                 from /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_0aa1714905af5673407e326867870ea8946d262f/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/ndarrayobject.h:12,\n                 from /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_0aa1714905af5673407e326867870ea8946d262f/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/arrayobject.h:4,\n                 from Orange/data/_contingency.c:775:\n/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_0aa1714905af5673407e326867870ea8946d262f/.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:4120:43: warning: ‘__pyx_v_decs’ may be used uninitialized in this function [-Wmaybe-uninitialized]\n 4120 |           __pyx_v_value = ((__pyx_v_value * __pyx_v_decs) + (__pyx_v_c & 0xf));\n      |                            ~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~\nOrange/data/_io.c:4318:24: warning: ‘__pyx_v_value’ may be used uninitialized in this function [-Wmaybe-uninitialized]\n 4318 |           __pyx_t_10 = PyFloat_FromDouble(__pyx_v_value); if (unlikely(!__pyx_t_10)) __PYX_ERR(0, 223, __pyx_L5_error)\n      |                        ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\nOrange/data/_io.c:683:40: warning: ‘__pyx_v_attr_index’ may be used uninitialized in this function [-Wmaybe-uninitialized]\n  683 |   #define PyInt_FromLong               PyLong_FromLong\n      |                                        ^~~~~~~~~~~~~~~\nOrange/data/_io.c:1590:7: note: ‘__pyx_v_attr_index’ was declared here\n 1590 |   int __pyx_v_attr_index;\n      |       ^~~~~~~~~~~~~~~~~~\nOrange/data/_io.c:3183:25: warning: ‘__pyx_v_atomp’ may be used uninitialized in this function [-Wmaybe-uninitialized]\n 3183 |           __pyx_v_atomp = (__pyx_v_atomp + 1);\n      |           ~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~\nIn file included from /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_0aa1714905af5673407e326867870ea8946d262f/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/ndarraytypes.h:1830,\n                 from /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_0aa1714905af5673407e326867870ea8946d262f/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/ndarrayobject.h:12,\n                 from /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_0aa1714905af5673407e326867870ea8946d262f/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/arrayobject.h:4,\n                 from Orange/data/_valuecount.c:775:\n/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_0aa1714905af5673407e326867870ea8946d262f/.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_0aa1714905af5673407e326867870ea8946d262f/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/ndarraytypes.h:1830,\n                 from /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_0aa1714905af5673407e326867870ea8946d262f/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/ndarrayobject.h:12,\n                 from /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_0aa1714905af5673407e326867870ea8946d262f/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/arrayobject.h:4,\n                 from Orange/distance/_distance.c:775:\n/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_0aa1714905af5673407e326867870ea8946d262f/.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_0aa1714905af5673407e326867870ea8946d262f/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/ndarraytypes.h:1830,\n                 from /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_0aa1714905af5673407e326867870ea8946d262f/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/ndarrayobject.h:12,\n                 from /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_0aa1714905af5673407e326867870ea8946d262f/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/arrayobject.h:4,\n                 from Orange/preprocess/_discretize.c:774:\n/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_0aa1714905af5673407e326867870ea8946d262f/.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_0aa1714905af5673407e326867870ea8946d262f/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/ndarraytypes.h:1830,\n                 from /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_0aa1714905af5673407e326867870ea8946d262f/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/ndarrayobject.h:12,\n                 from /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_0aa1714905af5673407e326867870ea8946d262f/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/arrayobject.h:4,\n                 from Orange/preprocess/_relieff.cpp:790:\n/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_0aa1714905af5673407e326867870ea8946d262f/.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_0aa1714905af5673407e326867870ea8946d262f/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/ndarraytypes.h:1830,\n                 from /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_0aa1714905af5673407e326867870ea8946d262f/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/ndarrayobject.h:12,\n                 from /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_0aa1714905af5673407e326867870ea8946d262f/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/arrayobject.h:4,\n                 from Orange/projection/_som.c:775:\n/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_0aa1714905af5673407e326867870ea8946d262f/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/npy_1_7_deprecated_api.h:17:2: warning: #warning \"Using deprecated NumPy API, disable it with \" \"#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION\" [-Wcpp]\n   17 | #warning \"Using deprecated NumPy API, disable it with \" \\\n      |  ^~~~~~~\nOrange/projection/_som.c: In function ‘__pyx_pw_6Orange_10projection_4_som_5update_hex’:\nOrange/projection/_som.c:3863:7: warning: ‘__pyx_v_win_y’ may be used uninitialized in this function [-Wmaybe-uninitialized]\n 3863 |   int __pyx_v_win_y;\n      |       ^~~~~~~~~~~~~\nOrange/projection/_som.c:3862:7: warning: ‘__pyx_v_win_x’ may be used uninitialized in this function [-Wmaybe-uninitialized]\n 3862 |   int __pyx_v_win_x;\n      |       ^~~~~~~~~~~~~\nOrange/projection/_som.c: In function ‘__pyx_pf_6Orange_10projection_4_som_8update_sparse.constprop’:\nOrange/projection/_som.c:4934:7: warning: ‘__pyx_v_win_y’ may be used uninitialized in this function [-Wmaybe-uninitialized]\n 4934 |   int __pyx_v_win_y;\n      |       ^~~~~~~~~~~~~\nOrange/projection/_som.c:4933:7: warning: ‘__pyx_v_win_x’ may be used uninitialized in this function [-Wmaybe-uninitialized]\n 4933 |   int __pyx_v_win_x;\n      |       ^~~~~~~~~~~~~\nOrange/projection/_som.c: In function ‘__pyx_pw_6Orange_10projection_4_som_7get_winners_sparse’:\nOrange/projection/_som.c:4732:223: warning: ‘__pyx_v_win_y’ may be used uninitialized in this function [-Wmaybe-uninitialized]\n 4732 |           *__Pyx_BufPtrStrided2d(__pyx_t_5numpy_int16_t *, __pyx_pybuffernd_winners.rcbuffer->pybuffer.buf, __pyx_t_26, __pyx_pybuffernd_winners.diminfo[0].strides, __pyx_t_27, __pyx_pybuffernd_winners.diminfo[1].strides) = __pyx_v_win_y;\n      |           ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~\nOrange/projection/_som.c:4307:7: note: ‘__pyx_v_win_y’ was declared here\n 4307 |   int __pyx_v_win_y;\n      |       ^~~~~~~~~~~~~\nOrange/projection/_som.c:4721:223: warning: ‘__pyx_v_win_x’ may be used uninitialized in this function [-Wmaybe-uninitialized]\n 4721 |           *__Pyx_BufPtrStrided2d(__pyx_t_5numpy_int16_t *, __pyx_pybuffernd_winners.rcbuffer->pybuffer.buf, __pyx_t_27, __pyx_pybuffernd_winners.diminfo[0].strides, __pyx_t_26, __pyx_pybuffernd_winners.diminfo[1].strides) = __pyx_v_win_x;\n      |           ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~\nOrange/projection/_som.c:4306:7: note: ‘__pyx_v_win_x’ was declared here\n 4306 |   int __pyx_v_win_x;\n      |       ^~~~~~~~~~~~~\nOrange/projection/_som.c: In function ‘__pyx_pf_6Orange_10projection_4_som_10update_sparse_hex.constprop’:\nOrange/projection/_som.c:5682:7: warning: ‘__pyx_v_win_y’ may be used uninitialized in this function [-Wmaybe-uninitialized]\n 5682 |   int __pyx_v_win_y;\n      |       ^~~~~~~~~~~~~\nOrange/projection/_som.c:5681:7: warning: ‘__pyx_v_win_x’ may be used uninitialized in this function [-Wmaybe-uninitialized]\n 5681 |   int __pyx_v_win_x;\n      |       ^~~~~~~~~~~~~\nOrange/projection/_som.c: In function ‘__pyx_pw_6Orange_10projection_4_som_1get_winners’:\nOrange/projection/_som.c:3184:223: warning: ‘__pyx_v_win_y’ may be used uninitialized in this function [-Wmaybe-uninitialized]\n 3184 |           *__Pyx_BufPtrStrided2d(__pyx_t_5numpy_int16_t *, __pyx_pybuffernd_winners.rcbuffer->pybuffer.buf, __pyx_t_22, __pyx_pybuffernd_winners.diminfo[0].strides, __pyx_t_23, __pyx_pybuffernd_winners.diminfo[1].strides) = __pyx_v_win_y;\n      |           ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~\nOrange/projection/_som.c:2887:7: note: ‘__pyx_v_win_y’ was declared here\n 2887 |   int __pyx_v_win_y;\n      |       ^~~~~~~~~~~~~\nOrange/projection/_som.c:3173:223: warning: ‘__pyx_v_win_x’ may be used uninitialized in this function [-Wmaybe-uninitialized]\n 3173 |           *__Pyx_BufPtrStrided2d(__pyx_t_5numpy_int16_t *, __pyx_pybuffernd_winners.rcbuffer->pybuffer.buf, __pyx_t_23, __pyx_pybuffernd_winners.diminfo[0].strides, __pyx_t_22, __pyx_pybuffernd_winners.diminfo[1].strides) = __pyx_v_win_x;\n      |           ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~\nOrange/projection/_som.c:2886:7: note: ‘__pyx_v_win_x’ was declared here\n 2886 |   int __pyx_v_win_x;\n      |       ^~~~~~~~~~~~~\nOrange/projection/_som.c: In function ‘__pyx_pw_6Orange_10projection_4_som_3update’:\nOrange/projection/_som.c:3357:7: warning: ‘__pyx_v_win_y’ may be used uninitialized in this function [-Wmaybe-uninitialized]\n 3357 |   int __pyx_v_win_y;\n      |       ^~~~~~~~~~~~~\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      |         ^~~~~~~~~~~~\n/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_0aa1714905af5673407e326867870ea8946d262f/.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_0aa1714905af5673407e326867870ea8946d262f/.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,\nwarning: no files found matching 'README*' under directory 'Orange'\nwarning: no files found matching 'LICENSE' under directory 'Orange'\nwarning: no files found matching '*.basket' under directory 'Orange/datasets'\nwarning: no files found matching '*.js' under directory 'Orange/widgets'\nwarning: no files found matching '*.css' under directory 'Orange/widgets'\nwarning: no files found matching '*.html' under directory 'Orange/widgets'\nwarning: no files found matching 'COPYING'\n",
    "new_commit_res_code": 0,
    "new_commit_res_stdout": "============================= test session starts ==============================\nplatform linux -- Python 3.7.9, pytest-7.4.4, pluggy-1.2.0\nrootdir: /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_0aa1714905af5673407e326867870ea8946d262f\nplugins: anyio-3.7.1\ncollected 67 items\n\nr2e_tests/test_1.py ...................................................  [ 76%]\nr2e_tests/test_2.py sss.............                                     [100%]\n\n==================================== PASSES ====================================\n=========================== short test summary info ============================\nPASSED r2e_tests/test_1.py::EuclideanDistanceTest::test_euclidean_cols\nPASSED r2e_tests/test_1.py::EuclideanDistanceTest::test_euclidean_cols_normalized\nPASSED r2e_tests/test_1.py::EuclideanDistanceTest::test_euclidean_cont\nPASSED r2e_tests/test_1.py::EuclideanDistanceTest::test_euclidean_cont_normalized\nPASSED r2e_tests/test_1.py::EuclideanDistanceTest::test_euclidean_disc\nPASSED r2e_tests/test_1.py::EuclideanDistanceTest::test_euclidean_mixed\nPASSED r2e_tests/test_1.py::EuclideanDistanceTest::test_mismatching_attributes\nPASSED r2e_tests/test_1.py::EuclideanDistanceTest::test_mixed_cols\nPASSED r2e_tests/test_1.py::EuclideanDistanceTest::test_no_data\nPASSED r2e_tests/test_1.py::EuclideanDistanceTest::test_sparse\nPASSED r2e_tests/test_1.py::EuclideanDistanceTest::test_two_tables\nPASSED r2e_tests/test_1.py::EuclideanDistanceTest::test_zero_variance\nPASSED r2e_tests/test_1.py::ManhattanDistanceTest::test_manhattan_cols\nPASSED r2e_tests/test_1.py::ManhattanDistanceTest::test_manhattan_cols_normalized\nPASSED r2e_tests/test_1.py::ManhattanDistanceTest::test_manhattan_cont\nPASSED r2e_tests/test_1.py::ManhattanDistanceTest::test_manhattan_cont_normalized\nPASSED r2e_tests/test_1.py::ManhattanDistanceTest::test_manhattan_disc\nPASSED r2e_tests/test_1.py::ManhattanDistanceTest::test_manhattan_mixed\nPASSED r2e_tests/test_1.py::ManhattanDistanceTest::test_manhattan_mixed_cols\nPASSED r2e_tests/test_1.py::ManhattanDistanceTest::test_manhattan_no_data\nPASSED r2e_tests/test_1.py::ManhattanDistanceTest::test_mismatching_attributes\nPASSED r2e_tests/test_1.py::ManhattanDistanceTest::test_mixed_cols\nPASSED r2e_tests/test_1.py::ManhattanDistanceTest::test_no_data\nPASSED r2e_tests/test_1.py::ManhattanDistanceTest::test_sparse\nPASSED r2e_tests/test_1.py::ManhattanDistanceTest::test_two_tables\nPASSED r2e_tests/test_1.py::ManhattanDistanceTest::test_zero_variance\nPASSED r2e_tests/test_1.py::CosineDistanceTest::test_cosine_cols\nPASSED r2e_tests/test_1.py::CosineDistanceTest::test_cosine_cont\nPASSED r2e_tests/test_1.py::CosineDistanceTest::test_cosine_disc\nPASSED r2e_tests/test_1.py::CosineDistanceTest::test_cosine_mixed\nPASSED r2e_tests/test_1.py::CosineDistanceTest::test_mismatching_attributes\nPASSED r2e_tests/test_1.py::CosineDistanceTest::test_no_data\nPASSED r2e_tests/test_1.py::CosineDistanceTest::test_sparse\nPASSED r2e_tests/test_1.py::CosineDistanceTest::test_two_tables\nPASSED r2e_tests/test_1.py::JaccardDistanceTest::test_jaccard_cols\nPASSED r2e_tests/test_1.py::JaccardDistanceTest::test_jaccard_rows\nPASSED r2e_tests/test_1.py::JaccardDistanceTest::test_mismatching_attributes\nPASSED r2e_tests/test_1.py::JaccardDistanceTest::test_no_data\nPASSED r2e_tests/test_1.py::JaccardDistanceTest::test_sparse\nPASSED r2e_tests/test_1.py::JaccardDistanceTest::test_zero_instances\nPASSED r2e_tests/test_1.py::HammingDistanceTest::test_hamming_col\nPASSED r2e_tests/test_1.py::HammingDistanceTest::test_hamming_row\nPASSED r2e_tests/test_1.py::HammingDistanceTest::test_hamming_row_secondary_data\nPASSED r2e_tests/test_1.py::TestHelperFunctions::test_interruptable_dot\nPASSED r2e_tests/test_1.py::TestHelperFunctions::test_interruptable_dot_list\nPASSED r2e_tests/test_1.py::TestHelperFunctions::test_interruptable_dot_scalar\nPASSED r2e_tests/test_1.py::TestHelperFunctions::test_interruptable_sqrt\nPASSED r2e_tests/test_1.py::TestHelperFunctions::test_interruptable_sqrt_list\nPASSED r2e_tests/test_1.py::TestHelperFunctions::test_interruptable_sqrt_scalar\nPASSED r2e_tests/test_1.py::TestDataUtilities::test_remove_discrete\nPASSED r2e_tests/test_1.py::TestDataUtilities::test_remove_non_binary\nPASSED r2e_tests/test_2.py::TestDistanceRunner::test_run\nPASSED r2e_tests/test_2.py::TestOWDistances::test_discrete_in_metas\nPASSED r2e_tests/test_2.py::TestOWDistances::test_distance_combo\nPASSED r2e_tests/test_2.py::TestOWDistances::test_error_message\nPASSED r2e_tests/test_2.py::TestOWDistances::test_image_export\nPASSED r2e_tests/test_2.py::TestOWDistances::test_jaccard_messages\nPASSED r2e_tests/test_2.py::TestOWDistances::test_limit_mahalanobis\nPASSED r2e_tests/test_2.py::TestOWDistances::test_migrates_normalized_dist\nPASSED r2e_tests/test_2.py::TestOWDistances::test_minimum_size\nPASSED r2e_tests/test_2.py::TestOWDistances::test_msg_base_class\nPASSED r2e_tests/test_2.py::TestOWDistances::test_negative_values_bhattacharyya\nPASSED r2e_tests/test_2.py::TestOWDistances::test_non_binary_in_metas\nPASSED r2e_tests/test_2.py::TestOWDistances::test_too_big_array\nSKIPPED [1] .venv/lib/python3.7/site-packages/orangewidget/tests/base.py:244: image exporting not tested as .widget was not set\nSKIPPED [1] .venv/lib/python3.7/site-packages/orangewidget/tests/base.py:238: minimum size not tested as .widget was not set\nSKIPPED [1] .venv/lib/python3.7/site-packages/orangewidget/tests/base.py:250: msg base class not tested as .widget was not set\n======================== 64 passed, 3 skipped in 5.38s =========================\nWidgets left: 0    Max widgets: 689 \n\n",
    "new_commit_res_stderr": "",
    "old_commit_res_code": 1,
    "old_commit_res_stdout": "============================= test session starts ==============================\nplatform linux -- Python 3.7.9, pytest-7.4.4, pluggy-1.2.0\nrootdir: /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_0aa1714905af5673407e326867870ea8946d262f\nplugins: anyio-3.7.1\ncollected 67 items\n\nr2e_tests/test_1.py .................................................FF  [ 76%]\nr2e_tests/test_2.py sss.F.........F.                                     [100%]\n\n=================================== FAILURES ===================================\n____________________ TestDataUtilities.test_remove_discrete ____________________\n\nself = <r2e_tests.test_1.TestDataUtilities testMethod=test_remove_discrete>\n\n    def test_remove_discrete(self):\n        d1, d2, d3 = (DiscreteVariable(c, values=tuple(\"123\")) for c in \"abc\")\n        c1, c2 = (ContinuousVariable(c) for c in \"xy\")\n        t = StringVariable(\"t\")\n        domain = Domain([d1, c1], d2, [c2, d3, t])\n        data = Table.from_domain(domain, 5)\n    \n        reduced = distance.remove_discrete_features(data)\n        self.assertEqual(reduced.domain.attributes, (c1, ))\n        self.assertEqual(reduced.domain.class_var, d2)\n        self.assertEqual(reduced.domain.metas, (c2, d3, t))\n    \n>       reduced = distance.remove_discrete_features(data, to_metas=True)\nE       TypeError: remove_discrete_features() got an unexpected keyword argument 'to_metas'\n\nr2e_tests/test_1.py:997: TypeError\n___________________ TestDataUtilities.test_remove_non_binary ___________________\n\nself = <r2e_tests.test_1.TestDataUtilities testMethod=test_remove_non_binary>\n\n    def test_remove_non_binary(self):\n        b1, b2, b3 = (DiscreteVariable(c, values=tuple(\"12\")) for c in \"abc\")\n        d1, d2, d3 = (DiscreteVariable(c, values=tuple(\"123\")) for c in \"def\")\n        c1, c2 = (ContinuousVariable(c) for c in \"xy\")\n        t = StringVariable(\"t\")\n        domain = Domain([d1, b1, b2, c1], d2, [c2, d3, t, b3])\n        data = Table.from_domain(domain, 5)\n    \n        reduced = distance.remove_nonbinary_features(data)\n        self.assertEqual(reduced.domain.attributes, (b1, b2))\n        self.assertEqual(reduced.domain.class_var, d2)\n        self.assertEqual(reduced.domain.metas, (c2, d3, t, b3))\n    \n>       reduced = distance.remove_nonbinary_features(data, to_metas=True)\nE       TypeError: remove_nonbinary_features() got an unexpected keyword argument 'to_metas'\n\nr2e_tests/test_1.py:1015: TypeError\n____________________ TestOWDistances.test_discrete_in_metas ____________________\n\nself = <r2e_tests.test_2.TestOWDistances testMethod=test_discrete_in_metas>\n\n    def test_discrete_in_metas(self):\n        domain = self.iris.domain\n        data = self.iris.transform(\n            Domain(domain.attributes[:-1] + (domain.class_var, ),\n                   [],\n                   domain.attributes[-1:])\n        )\n        for self.widget.metric_idx, (_, metric) in enumerate(METRICS):\n            if metric == distance.Cosine:\n                break\n        self.send_signal(self.widget.Inputs.data, data)\n        self.wait_until_finished()\n        out = self.get_output(self.widget.Outputs.distances)\n        out_domain = out.row_items.domain\n        self.assertEqual(out_domain.attributes, domain.attributes[:-1])\n        self.assertEqual(out_domain.metas,\n>                        (domain.attributes[-1], domain.class_var))\nE       AssertionError: Tuples differ: (Cont[52 chars]s=1),) != (Cont[52 chars]s=1), DiscreteVariable(name='iris', values=('I[46 chars]a')))\nE       \nE       Second tuple contains 1 additional elements.\nE       First extra element 1:\nE       DiscreteVariable(name='iris', values=('Iris-setosa', 'Iris-versicolor', 'Iris-virginica'))\nE       \nE       - (ContinuousVariable(name='petal width', number_of_decimals=1),)\nE       ?                                                               -\nE       \nE       + (ContinuousVariable(name='petal width', number_of_decimals=1),\nE       +  DiscreteVariable(name='iris', values=('Iris-setosa', 'Iris-versicolor', 'Iris-virginica')))\n\nr2e_tests/test_2.py:247: AssertionError\n___________________ TestOWDistances.test_non_binary_in_metas ___________________\n\nself = <r2e_tests.test_2.TestOWDistances testMethod=test_non_binary_in_metas>\n\n    def test_non_binary_in_metas(self):\n        for self.widget.metric_idx, (_, metric) in enumerate(METRICS):\n            if metric == distance.Jaccard:\n                break\n        zoo = Table(\"zoo\")[:20]\n        self.send_signal(self.widget.Inputs.data, zoo)\n        self.wait_until_finished()\n        out = self.get_output(self.widget.Outputs.distances)\n        domain = zoo.domain\n        out_domain = out.row_items.domain\n>       self.assertEqual(out_domain.metas, (domain[\"name\"], domain[\"legs\"]))\nE       AssertionError: Tuples differ: (Stri[19 chars]me'),) != (Stri[19 chars]me'), DiscreteVariable(name='legs', values=('0[24 chars]8')))\nE       \nE       Second tuple contains 1 additional elements.\nE       First extra element 1:\nE       DiscreteVariable(name='legs', values=('0', '2', '4', '5', '6', '8'))\nE       \nE       - (StringVariable(name='name'),)\nE       ?                              -\nE       \nE       + (StringVariable(name='name'),\nE       +  DiscreteVariable(name='legs', values=('0', '2', '4', '5', '6', '8')))\n\nr2e_tests/test_2.py:259: AssertionError\n==================================== PASSES ====================================\n=========================== short test summary info ============================\nPASSED r2e_tests/test_1.py::EuclideanDistanceTest::test_euclidean_cols\nPASSED r2e_tests/test_1.py::EuclideanDistanceTest::test_euclidean_cols_normalized\nPASSED r2e_tests/test_1.py::EuclideanDistanceTest::test_euclidean_cont\nPASSED r2e_tests/test_1.py::EuclideanDistanceTest::test_euclidean_cont_normalized\nPASSED r2e_tests/test_1.py::EuclideanDistanceTest::test_euclidean_disc\nPASSED r2e_tests/test_1.py::EuclideanDistanceTest::test_euclidean_mixed\nPASSED r2e_tests/test_1.py::EuclideanDistanceTest::test_mismatching_attributes\nPASSED r2e_tests/test_1.py::EuclideanDistanceTest::test_mixed_cols\nPASSED r2e_tests/test_1.py::EuclideanDistanceTest::test_no_data\nPASSED r2e_tests/test_1.py::EuclideanDistanceTest::test_sparse\nPASSED r2e_tests/test_1.py::EuclideanDistanceTest::test_two_tables\nPASSED r2e_tests/test_1.py::EuclideanDistanceTest::test_zero_variance\nPASSED r2e_tests/test_1.py::ManhattanDistanceTest::test_manhattan_cols\nPASSED r2e_tests/test_1.py::ManhattanDistanceTest::test_manhattan_cols_normalized\nPASSED r2e_tests/test_1.py::ManhattanDistanceTest::test_manhattan_cont\nPASSED r2e_tests/test_1.py::ManhattanDistanceTest::test_manhattan_cont_normalized\nPASSED r2e_tests/test_1.py::ManhattanDistanceTest::test_manhattan_disc\nPASSED r2e_tests/test_1.py::ManhattanDistanceTest::test_manhattan_mixed\nPASSED r2e_tests/test_1.py::ManhattanDistanceTest::test_manhattan_mixed_cols\nPASSED r2e_tests/test_1.py::ManhattanDistanceTest::test_manhattan_no_data\nPASSED r2e_tests/test_1.py::ManhattanDistanceTest::test_mismatching_attributes\nPASSED r2e_tests/test_1.py::ManhattanDistanceTest::test_mixed_cols\nPASSED r2e_tests/test_1.py::ManhattanDistanceTest::test_no_data\nPASSED r2e_tests/test_1.py::ManhattanDistanceTest::test_sparse\nPASSED r2e_tests/test_1.py::ManhattanDistanceTest::test_two_tables\nPASSED r2e_tests/test_1.py::ManhattanDistanceTest::test_zero_variance\nPASSED r2e_tests/test_1.py::CosineDistanceTest::test_cosine_cols\nPASSED r2e_tests/test_1.py::CosineDistanceTest::test_cosine_cont\nPASSED r2e_tests/test_1.py::CosineDistanceTest::test_cosine_disc\nPASSED r2e_tests/test_1.py::CosineDistanceTest::test_cosine_mixed\nPASSED r2e_tests/test_1.py::CosineDistanceTest::test_mismatching_attributes\nPASSED r2e_tests/test_1.py::CosineDistanceTest::test_no_data\nPASSED r2e_tests/test_1.py::CosineDistanceTest::test_sparse\nPASSED r2e_tests/test_1.py::CosineDistanceTest::test_two_tables\nPASSED r2e_tests/test_1.py::JaccardDistanceTest::test_jaccard_cols\nPASSED r2e_tests/test_1.py::JaccardDistanceTest::test_jaccard_rows\nPASSED r2e_tests/test_1.py::JaccardDistanceTest::test_mismatching_attributes\nPASSED r2e_tests/test_1.py::JaccardDistanceTest::test_no_data\nPASSED r2e_tests/test_1.py::JaccardDistanceTest::test_sparse\nPASSED r2e_tests/test_1.py::JaccardDistanceTest::test_zero_instances\nPASSED r2e_tests/test_1.py::HammingDistanceTest::test_hamming_col\nPASSED r2e_tests/test_1.py::HammingDistanceTest::test_hamming_row\nPASSED r2e_tests/test_1.py::HammingDistanceTest::test_hamming_row_secondary_data\nPASSED r2e_tests/test_1.py::TestHelperFunctions::test_interruptable_dot\nPASSED r2e_tests/test_1.py::TestHelperFunctions::test_interruptable_dot_list\nPASSED r2e_tests/test_1.py::TestHelperFunctions::test_interruptable_dot_scalar\nPASSED r2e_tests/test_1.py::TestHelperFunctions::test_interruptable_sqrt\nPASSED r2e_tests/test_1.py::TestHelperFunctions::test_interruptable_sqrt_list\nPASSED r2e_tests/test_1.py::TestHelperFunctions::test_interruptable_sqrt_scalar\nPASSED r2e_tests/test_2.py::TestDistanceRunner::test_run\nPASSED r2e_tests/test_2.py::TestOWDistances::test_distance_combo\nPASSED r2e_tests/test_2.py::TestOWDistances::test_error_message\nPASSED r2e_tests/test_2.py::TestOWDistances::test_image_export\nPASSED r2e_tests/test_2.py::TestOWDistances::test_jaccard_messages\nPASSED r2e_tests/test_2.py::TestOWDistances::test_limit_mahalanobis\nPASSED r2e_tests/test_2.py::TestOWDistances::test_migrates_normalized_dist\nPASSED r2e_tests/test_2.py::TestOWDistances::test_minimum_size\nPASSED r2e_tests/test_2.py::TestOWDistances::test_msg_base_class\nPASSED r2e_tests/test_2.py::TestOWDistances::test_negative_values_bhattacharyya\nPASSED r2e_tests/test_2.py::TestOWDistances::test_too_big_array\nSKIPPED [1] .venv/lib/python3.7/site-packages/orangewidget/tests/base.py:244: image exporting not tested as .widget was not set\nSKIPPED [1] .venv/lib/python3.7/site-packages/orangewidget/tests/base.py:238: minimum size not tested as .widget was not set\nSKIPPED [1] .venv/lib/python3.7/site-packages/orangewidget/tests/base.py:250: msg base class not tested as .widget was not set\nFAILED r2e_tests/test_1.py::TestDataUtilities::test_remove_discrete - TypeErr...\nFAILED r2e_tests/test_1.py::TestDataUtilities::test_remove_non_binary - TypeE...\nFAILED r2e_tests/test_2.py::TestOWDistances::test_discrete_in_metas - Asserti...\nFAILED r2e_tests/test_2.py::TestOWDistances::test_non_binary_in_metas - Asser...\n=================== 4 failed, 60 passed, 3 skipped in 3.97s ====================\nWidgets left: 0    Max widgets: 689 \n\n",
    "old_commit_res_stderr": ""
}
Orange/distance/base.py Orange/distance/tests/test_distance.py Orange/widgets/unsupervised/owdistances.py Orange/widgets/unsupervised/tests/test_owdistances.py
We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
[ISSUE]
**Title:** `remove_discrete_features` and `remove_nonbinary_features` Functions Do Not Support `to_metas` Parameter

**Description:**
The functions `remove_discrete_features` and `remove_nonbinary_features` are intended to move ignored attributes to metas when the `to_metas` parameter is set to `True`. However, currently, these functions do not accept the `to_metas` argument, causing errors when this parameter is used.

**Example Buggy Code:**
```python
from Orange.data import Table
from Orange.distance import remove_discrete_features, remove_nonbinary_features

data = Table("sample_data")
# Attempting to move ignored attributes to metas
reduced_discrete = remove_discrete_features(data, to_metas=True)  # Raises TypeError
reduced_nonbinary = remove_nonbinary_features(data, to_metas=True)  # Raises TypeError
```

**Expected Behavior:**
When the `to_metas` parameter is set to `True`, the functions should successfully move the ignored discrete or non-binary attributes to the metas of the data, modifying the domain accordingly without raising any errors.

**Actual Behavior:**
Passing the `to_metas=True` argument results in a `TypeError` because the functions do not recognize the `to_metas` keyword argument. The error messages are as follows:
```
TypeError: remove_discrete_features() got an unexpected keyword argument 'to_metas'
TypeError: remove_nonbinary_features() got an unexpected keyword argument 'to_metas'
```
This prevents the intended functionality of moving attributes to metas and causes related tests to fail.

[/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/distance/base.py
# This module defines abstract base classes; derived classes are abstract, too
# pylint: disable=abstract-method

import numpy as np
import sklearn.metrics as skl_metrics

from Orange.data import Table, Domain, Instance, RowInstance
from Orange.misc import DistMatrix
from Orange.preprocess import SklImpute
from Orange.statistics import util


# TODO: When we upgrade to numpy 1.13, change use argument copy=False in
# nan_to_num instead of assignment

# TODO this *private* function is called from several widgets to prepare
# data for calling the below classes. After we (mostly) stopped relying
# on sklearn.metrics, this is (mostly) unnecessary
# Afterwards, also remove the following line:
# pylint: disable=redefined-outer-name
def _preprocess(table, impute=True):
    """Remove categorical attributes and impute missing values."""
    if not len(table):  # this can be an array, pylint: disable=len-as-condition
        return table
    new_domain = Domain(
        [a for a in table.domain.attributes if a.is_continuous],
        table.domain.class_vars,
        table.domain.metas)
    new_data = table.transform(new_domain)
    if impute:
        new_data = SklImpute()(new_data)
    return new_data


# TODO I have put this function here as a substitute the above `_preprocess`.
# None of them really belongs here; (re?)move them, eventually.
def remove_discrete_features(data):
    """Remove discrete columns from the data."""
    new_domain = Domain(
        [a for a in data.domain.attributes if a.is_continuous],
        data.domain.class_vars,
        data.domain.metas)
    return data.transform(new_domain)


def remove_nonbinary_features(data):
    """Remove non-binary columns from the data."""
    new_domain = Domain(
        [a for a in data.domain.attributes
         if a.is_discrete and len(a.values) == 2],
        data.domain.class_vars,
        data.domain.metas)
    return data.transform(new_domain)

def impute(data):
    """Impute missing values."""
    return SklImpute()(data)


def _orange_to_numpy(x):
    """
    Return :class:`numpy.ndarray` (dense or sparse) with attribute data
    from the given instance of :class:`Orange.data.Table`,
    :class:`Orange.data.RowInstance` or :class:`Orange.data.Instance`.
    """
    if isinstance(x, Table):
        return x.X
    elif isinstance(x, Instance):
        return np.atleast_2d(x.x)
    elif isinstance(x, np.ndarray):
        return np.atleast_2d(x)
    else:
        return x  # e.g. None


class Distance:
    """
    Base class for construction of distances models (:obj:`DistanceModel`).

    Distances can be computed between all pairs of rows in one table, or
    between pairs where one row is from one table and one from another.

    If `axis` is set to `0`, the class computes distances between all pairs
    of columns in a table. Distances between columns from separate tables are
    probably meaningless, thus unsupported.

    The class can be used as follows:

    - Constructor is called only with keyword argument `axis` that
      specifies the axis over which the distances are computed, and with other
      subclass-specific keyword arguments.
    - Next, we call the method `fit(data)` to produce an instance of
      :obj:`DistanceModel`; the instance stores any parameters needed for
      computation of distances, such as statistics for normalization and
      handling of missing data.
    - We can then call the :obj:`DistanceModel` with data to compute the
      distance between its rows or columns, or with two data tables to
      compute distances between all pairs of rows.

    The second, shorter way to use this class is to call the constructor with
    one or two data tables and any additional keyword arguments. Constructor
    will execute the above steps and return :obj:`~Orange.misc.DistMatrix`.
    Such usage is here for backward compatibility, practicality and efficiency.

    Args:
        e1 (:obj:`~Orange.data.Table` or :obj:`~Orange.data.Instance` or \
                :obj:`np.ndarray` or `None`):
            data on which to train the model and compute the distances
        e2 (:obj:`~Orange.data.Table` or :obj:`~Orange.data.Instance` or \
                :obj:`np.ndarray` or `None`):
            if present, the class computes distances with pairs coming from
            the two tables
        axis (int):
            axis over which the distances are computed, 1 (default) for
            rows, 0 for columns
        impute (bool):
            if `True` (default is `False`), nans in the computed distances
            are replaced with zeros, and infs with very large numbers.
        callback (callable or None):
            callback function

    Attributes:
        axis (int):
            axis over which the distances are computed, 1 (default) for
            rows, 0 for columns
        impute (bool):
            if `True` (default is `False`), nans in the computed distances
            are replaced with zeros, and infs with very large numbers.
        normalize (bool):
            if `True`, columns are normalized before computation. This attribute
            applies only if the distance supports normalization.

    The capabilities of the metrics are described with class attributes.

    If class attribute `supports_discrete` is `True`, the distance
    also uses discrete attributes to compute row distances. The use of discrete
    attributes depends upon the type of distance; e.g. Jaccard distance observes
    whether the value is zero or non-zero, while Euclidean and Manhattan
    distance observes whether a pair of values is same or different.

    Class attribute `supports_missing` indicates that the distance can cope
    with missing data. In such cases, letting the distance handle it should
    be preferred over pre-imputation of missing values.

    Class attribute `supports_normalization` indicates that the constructor
    accepts an argument `normalize`. If set to `True`, the metric will attempt
    to normalize the values in a sense that each attribute will have equal
    influence. For instance, the Euclidean distance subtract the mean and
    divides the result by the deviation, while Manhattan distance uses the
    median and MAD.

    If class attribute `supports_sparse` is `True`, the class will handle
    sparse data. Currently, all classes that do handle it rely on fallbacks to
    SKL metrics. These, however, do not support discrete data and missing
    values, and will fail silently.
    """
    supports_sparse = False
    supports_discrete = False
    supports_normalization = False
    supports_missing = True

    # Predefined here to silence pylint, which doesn't look into __new__
    normalize = False
    axis = 1
    impute = False

    def __new__(cls, e1=None, e2=None, axis=1, impute=False,
                callback=None, **kwargs):
        self = super().__new__(cls)
        self.axis = axis
        self.impute = impute
        self.callback = callback
        # Ugly, but needed to allow allow setting subclass-specific parameters
        # (such as normalize) when `e1` is not `None` and the `__new__` in the
        # subclass is skipped
        self.__dict__.update(**kwargs)
        if e1 is None:
            return self

        # Fallbacks for sparse data and numpy tables. Remove when subclasses
        # no longer use fallbacks for sparse data, and handling numpy tables
        # becomes obsolete (or handled elsewhere)
        if (not hasattr(e1, "domain")
                or hasattr(e1, "is_sparse") and e1.is_sparse()):
            fallback = getattr(self, "fallback", None)
            if fallback is not None:
                # pylint: disable=not-callable
                return fallback(e1, e2, axis, impute)

        # Magic constructor
        model = self.fit(e1)
        return model(e1, e2)

    def fit(self, data):
        """
        Abstract method returning :obj:`DistanceModel` fit to the data

        Args:
            e1 (Orange.data.Table, Orange.data.Instance, np.ndarray):
                data for fitting the distance model

        Returns:
            model (DistanceModel)
        """
        raise NotImplementedError

    @staticmethod
    def check_no_discrete(n_vals):
        """
        Raise an exception if there are any discrete attributes.

        Args:
            n_vals (list of int): number of attributes values, 0 for continuous
        """
        if any(n_vals):
            raise ValueError("columns with discrete values are incommensurable")


class DistanceModel:
    """
    Base class for classes that compute distances between data rows or columns.
    Instances of these classes are not constructed directly but returned by
    the corresponding instances of :obj:`Distance`.

    Attributes:
        axis (int, readonly):
            axis over which the distances are computed, 1 (default) for
            rows, 0 for columns
        impute (bool):
            if `True` (default is `False`), nans in the computed distances
            are replaced with zeros, and infs with very large numbers
        callback (callable or None):
            callback function

    """
    def __init__(self, axis, impute=False, callback=None):
        self._axis = axis
        self.impute = impute
        self.callback = callback

    @property
    def axis(self):
        return self._axis

    def __call__(self, e1, e2=None):
        """
        If e2 is omitted, calculate distances between all rows (axis=1) or
        columns (axis=2) of e1. If e2 is present, calculate distances between
        all pairs if rows from e1 and e2.

        This method converts the data into numpy arrays, calls the method
        `compute_data` and packs the result into `DistMatrix`. Subclasses are
        expected to define the `compute_data` and not the `__call__` method.

        Args:
            e1 (Orange.data.Table or Orange.data.Instance or numpy.ndarray):
                input data
            e2 (Orange.data.Table or Orange.data.Instance or numpy.ndarray):
                secondary data

        Returns:
            A distance matrix (Orange.misc.distmatrix.DistMatrix)
        """
        if self.axis == 0 and e2 is not None:
            # Backward compatibility fix
            if e2 is e1:
                e2 = None
            else:
                raise ValueError("Two tables cannot be compared by columns")

        x1 = _orange_to_numpy(e1)
        x2 = _orange_to_numpy(e2)
        with np.errstate(invalid="ignore"):  # nans are handled below
            dist = self.compute_distances(x1, x2)
            if self.impute and np.isnan(dist).any():
                dist = np.nan_to_num(dist)
            if isinstance(e1, (Table, RowInstance)):
                dist = DistMatrix(dist, e1, e2, self.axis)
            else:
                dist = DistMatrix(dist)
            return dist

    def compute_distances(self, x1, x2):
        """
        Abstract method for computation of distances between rows or columns of
        `x1`, or between rows of `x1` and `x2`. Do not call directly."""
        raise NotImplementedError


class FittedDistanceModel(DistanceModel):
    """
    Base class for models that store attribute-related data for normalization
    and imputation, and that treat discrete and continuous columns separately.

    Attributes:
        attributes (list of `Variable`): attributes on which the model was fit
        discrete (np.ndarray): bool array indicating discrete attributes
        continuous (np.ndarray): bool array indicating continuous attributes
        normalize (bool):
            if `True` (default is `False`) continuous columns are normalized
        callback (callable or None): callback function
    """
    def __init__(self, attributes, axis=1, impute=False, callback=None):
        super().__init__(axis, impute, callback)
        self.attributes = attributes
        self.discrete = None
        self.continuous = None
        self.normalize = False

    def __call__(self, e1, e2=None):
        if self.attributes is not None and (
                e1.domain.attributes != self.attributes
                or e2 is not None and e2.domain.attributes != self.attributes):
            raise ValueError("mismatching domains")
        return super().__call__(e1, e2)

    def continuous_columns(self, x1, x2, offset, scale):
        """
        Extract and scale continuous columns from data tables.
        If the second table is None, it defaults to the first table.

        Values are scaled if `self.normalize` is `True`.

        Args:
            x1 (np.ndarray): first table
            x2 (np.ndarray or None): second table
            offset (float): a constant (e.g. mean, median) subtracted from data
            scale: (float): divider (e.g. deviation)

        Returns:
            data1 (np.ndarray): scaled continuous columns from `x1`
            data2 (np.ndarray): scaled continuous columns from `x2` or `x1`
        """
        if self.continuous.all() and not self.normalize:
            data1, data2 = x1, x2
        else:
            data1 = x1[:, self.continuous]
            if x2 is not None:
                data2 = x2[:, self.continuous]
            if self.normalize:
                data1 = x1[:, self.continuous]
                data1 -= offset
                data1 /= scale
                if x2 is not None:
                    data2 = x2[:, self.continuous]
                    data2 -= offset
                    data2 /= scale
        if x2 is None:
            data2 = data1
        return data1, data2

    def discrete_columns(self, x1, x2):
        """
        Return discrete columns from the given tables.
        If the second table is None, it defaults to the first table.
        """
        if self.discrete.all():
            data1, data2 = x1, x1 if x2 is None else x2
        else:
            data1 = x1[:, self.discrete]
            data2 = data1 if x2 is None else x2[:, self.discrete]
        return data1, data2


class FittedDistance(Distance):
    """
    Base class for fitting models that store attribute-related data for
    normalization and imputation, and that treat discrete and continuous
    columns separately.

    The class implements a method `fit` that calls either `fit_columns`
    or `fit_rows` with the data and the number of values for discrete
    attributes. The provided method `fit_rows` calls methods
    `get_discrete_stats` and `get_continuous_stats` that can be implemented
    in derived classes.

    Class attribute `rows_model_type` contains the type of the model returned by
    `fit_rows`.
    """
    rows_model_type = None  #: Option[FittedDistanceModel]

    def fit(self, data):
        """
        Prepare the data on attributes, call `fit_cols` or `fit_rows` and
        return the resulting model.
        """
        x = _orange_to_numpy(data)
        if hasattr(data, "domain"):
            attributes = data.domain.attributes
            n_vals = np.fromiter(
                (len(attr.values) if attr.is_discrete else 0
                 for attr in attributes),
                dtype=np.int32, count=len(attributes))
        else:
            assert isinstance(x, np.ndarray)
            attributes = None
            n_vals = np.zeros(x.shape[1], dtype=np.int32)
        return [self.fit_cols, self.fit_rows][self.axis](attributes, x, n_vals)

    def fit_cols(self, attributes, x, n_vals):
        """
        Return DistanceModel for computation of distances between columns.
        Derived classes must define this method.

        Args:
            attributes (list of Orange.data.Variable): list of attributes
            x (np.ndarray): data
            n_vals (np.ndarray): number of attribute values, 0 for continuous
        """
        raise NotImplementedError

    def fit_rows(self, attributes, x, n_vals):
        """
        Return a DistanceModel for computation of distances between rows.

        The model type is `self.row_distance_model`. It stores the data for
        imputation of discrete and continuous values, and for normalization
        of continuous values. Typical examples are the Euclidean and Manhattan
        distance, for which the following data is stored:

        For continuous columns:

        - offsets[col] is the number subtracted from values in column `col`
        - scales[col] is the divisor for values in columns `col`
        - dist_missing2_cont[col]: the value used for distance between two
            missing values in column `col`

        For discrete values:

        - dist_missing_disc[col, value] is the distance added for the given
            `value` in the column `col` if the value for the other row is
            missing
        - dist_missing2_disc[col]: the distance between two missing values in
            column `col`
        """
        n_cols = len(n_vals)

        discrete = n_vals > 0
        n_bins = max(n_vals, default=0)
        n_discrete = sum(discrete)
        dist_missing_disc = np.zeros((n_discrete, n_bins), dtype=float)
        dist_missing2_disc = np.zeros(n_discrete, dtype=float)

        continuous = ~discrete
        n_continuous = sum(continuous)
        offsets = np.zeros(n_continuous, dtype=float)
        scales = np.empty(n_continuous, dtype=float)
        dist_missing2_cont = np.zeros(n_continuous, dtype=float)

        curr_disc = curr_cont = 0
        for col in range(n_cols):
            column = x[:, col]
            if np.isnan(column).all():
                continuous[col] = discrete[col] = False
            elif discrete[col]:
                discrete_stats = self.get_discrete_stats(column, n_bins)
                if discrete_stats is not None:
                    dist_missing_disc[curr_disc], \
                    dist_missing2_disc[curr_disc] = discrete_stats
                    curr_disc += 1
            else:
                continuous_stats = self.get_continuous_stats(column)
                if continuous_stats is not None:
                    offsets[curr_cont], scales[curr_cont],\
                    dist_missing2_cont[curr_cont] = continuous_stats
                    curr_cont += 1
                else:
                    continuous[col] = False
        # pylint: disable=not-callable
        return self.rows_model_type(
            attributes, impute, getattr(self, "normalize", False),
            continuous, discrete,
            offsets[:curr_cont], scales[:curr_cont],
            dist_missing2_cont[:curr_cont],
            dist_missing_disc, dist_missing2_disc,
            self.callback)

    @staticmethod
    def get_discrete_stats(column, n_bins):
        """
        Return tables used computing distance between missing discrete values.

        Args:
            column (np.ndarray): column data
            n_bins (int): maximal number of bins in the dataset

        Returns:
            dist_missing_disc (np.ndarray): `dist_missing_disc[value]` is
                1 - probability of `value`, which is used as the distance added
                for the given `value` in the column `col` if the value for the
                other row is missing
            dist_missing2_disc (float): the distance between two missing
                values in this columns
        """
        dist = util.bincount(column, minlength=n_bins)[0]
        dist /= max(1, sum(dist))
        return 1 - dist, 1 - np.sum(dist ** 2)

    def get_continuous_stats(self, column):
        """
        Compute statistics for imputation and normalization of continuous data.
        Derived classes must define this method.

        Args:
            column (np.ndarray): column data

        Returns:
            offset (float): the number subtracted from values in column
            scales (float): the divisor for values in column
            dist_missing2_cont (float): the value used for distance between two
                missing values in column
        """
        raise NotImplementedError


# Fallbacks for distances in sparse data
# To be removed as the corresponding functionality is implemented properly

class SklDistance:
    """
    Wrapper for functions sklearn's metrics. Used only as temporary fallbacks
    when `Euclidean`, `Manhattan`, `Cosine` or `Jaccard` are given sparse data
    or raw numpy arrays. These classes can't handle discrete or missing data
    and normalization. Do not use for wrapping new classes.
    """
    def __init__(self, metric):
        self.metric = metric

    def __call__(self, e1, e2=None, axis=1, impute=False):
        x1 = _orange_to_numpy(e1)
        x2 = _orange_to_numpy(e2)
        if axis == 0:
            x1 = x1.T
            if x2 is not None:
                x2 = x2.T
        dist = skl_metrics.pairwise.pairwise_distances(
            x1, x2, metric=self.metric)
        if impute and np.isnan(dist).any():
            dist = np.nan_to_num(dist)
        if isinstance(e1, (Table, RowInstance)):
            dist_matrix = DistMatrix(dist, e1, e2, axis)
        else:
            dist_matrix = DistMatrix(dist)
        return dist_matrix


### Orange/widgets/unsupervised/owdistances.py
from scipy.sparse import issparse
import bottleneck as bn

from AnyQt.QtCore import Qt

import Orange.data
import Orange.misc
from Orange import distance
from Orange.widgets import gui
from Orange.widgets.settings import Setting
from Orange.widgets.utils.concurrent import TaskState, ConcurrentWidgetMixin
from Orange.widgets.utils.sql import check_sql_input
from Orange.widgets.utils.widgetpreview import WidgetPreview
from Orange.widgets.widget import OWWidget, Msg, Input, Output


METRICS = [
    ("Euclidean", distance.Euclidean),
    ("Manhattan", distance.Manhattan),
    ("Cosine", distance.Cosine),
    ("Jaccard", distance.Jaccard),
    ("Spearman", distance.SpearmanR),
    ("Absolute Spearman", distance.SpearmanRAbsolute),
    ("Pearson", distance.PearsonR),
    ("Absolute Pearson", distance.PearsonRAbsolute),
    ("Hamming", distance.Hamming),
    ("Mahalanobis", distance.Mahalanobis),
    ('Bhattacharyya', distance.Bhattacharyya)
]


class InterruptException(Exception):
    pass


class DistanceRunner:
    @staticmethod
    def run(data: Orange.data.Table, metric: distance, normalized_dist: bool,
            axis: int, state: TaskState) -> Orange.misc.DistMatrix:
        if data is None:
            return None

        def callback(i: float) -> bool:
            state.set_progress_value(i)
            if state.is_interruption_requested():
                raise InterruptException

        state.set_status("Calculating...")
        kwargs = {"axis": 1 - axis, "impute": True, "callback": callback}
        if metric.supports_normalization and normalized_dist:
            kwargs["normalize"] = True
        return metric(data, **kwargs)


class OWDistances(OWWidget, ConcurrentWidgetMixin):
    name = "Distances"
    description = "Compute a matrix of pairwise distances."
    icon = "icons/Distance.svg"
    keywords = []

    class Inputs:
        data = Input("Data", Orange.data.Table)

    class Outputs:
        distances = Output("Distances", Orange.misc.DistMatrix, dynamic=False)

    settings_version = 3

    axis = Setting(0)        # type: int
    metric_idx = Setting(0)  # type: int

    #: Use normalized distances if the metric supports it.
    #: The default is `True`, expect when restoring from old pre v2 settings
    #: (see `migrate_settings`).
    normalized_dist = Setting(True)  # type: bool
    autocommit = Setting(True)       # type: bool

    want_main_area = False
    resizing_enabled = False

    class Error(OWWidget.Error):
        no_continuous_features = Msg("No numeric features")
        no_binary_features = Msg("No binary features")
        dense_metric_sparse_data = Msg("{} requires dense data.")
        distances_memory_error = Msg("Not enough memory")
        distances_value_error = Msg("Problem in calculation:\n{}")
        data_too_large_for_mahalanobis = Msg(
            "Mahalanobis handles up to 1000 {}.")

    class Warning(OWWidget.Warning):
        ignoring_discrete = Msg("Ignoring categorical features")
        ignoring_nonbinary = Msg("Ignoring non-binary features")
        imputing_data = Msg("Missing values were imputed")

    def __init__(self):
        OWWidget.__init__(self)
        ConcurrentWidgetMixin.__init__(self)

        self.data = None

        gui.radioButtons(
            self.controlArea, self, "axis", ["Rows", "Columns"],
            box="Distances between", callback=self._invalidate
        )
        box = gui.widgetBox(self.controlArea, "Distance Metric")
        self.metrics_combo = gui.comboBox(
            box, self, "metric_idx",
            items=[m[0] for m in METRICS],
            callback=self._metric_changed
        )
        self.normalization_check = gui.checkBox(
            box, self, "normalized_dist", "Normalized",
            callback=self._invalidate,
            tooltip=("All dimensions are (implicitly) scaled to a common"
                     "scale to normalize the influence across the domain."),
            stateWhenDisabled=False, attribute=Qt.WA_LayoutUsesWidgetRect
        )
        _, metric = METRICS[self.metric_idx]
        self.normalization_check.setEnabled(metric.supports_normalization)

        gui.auto_apply(self.buttonsArea, self, "autocommit")

    @Inputs.data
    @check_sql_input
    def set_data(self, data):
        self.cancel()
        self.data = data
        self.refresh_metrics()
        self.unconditional_commit()

    def refresh_metrics(self):
        sparse = self.data is not None and issparse(self.data.X)
        for i, metric in enumerate(METRICS):
            item = self.metrics_combo.model().item(i)
            item.setEnabled(not sparse or metric[1].supports_sparse)

    def commit(self):
        # pylint: disable=invalid-sequence-index
        metric = METRICS[self.metric_idx][1]
        self.compute_distances(metric, self.data)

    def compute_distances(self, metric, data):
        def _check_sparse():
            # pylint: disable=invalid-sequence-index
            if issparse(data.X) and not metric.supports_sparse:
                self.Error.dense_metric_sparse_data(METRICS[self.metric_idx][0])
                return False
            return True

        def _fix_discrete():
            nonlocal data
            if data.domain.has_discrete_attributes() \
                    and metric is not distance.Jaccard \
                    and (issparse(data.X) and getattr(metric, "fallback", None)
                         or not metric.supports_discrete
                         or self.axis == 1):
                if not data.domain.has_continuous_attributes():
                    self.Error.no_continuous_features()
                    return False
                self.Warning.ignoring_discrete()
                data = distance.remove_discrete_features(data)
            return True

        def _fix_nonbinary():
            nonlocal data
            if metric is distance.Jaccard and not issparse(data.X):
                nbinary = sum(a.is_discrete and len(a.values) == 2
                              for a in data.domain.attributes)
                if not nbinary:
                    self.Error.no_binary_features()
                    return False
                elif nbinary < len(data.domain.attributes):
                    self.Warning.ignoring_nonbinary()
                    data = distance.remove_nonbinary_features(data)
            return True

        def _fix_missing():
            nonlocal data
            if not metric.supports_missing and bn.anynan(data.X):
                self.Warning.imputing_data()
                data = distance.impute(data)
            return True

        def _check_tractability():
            if metric is distance.Mahalanobis:
                if self.axis == 1:
                    # when computing distances by columns, we want < 100 rows
                    if len(data) > 1000:
                        self.Error.data_too_large_for_mahalanobis("rows")
                        return False
                else:
                    if len(data.domain.attributes) > 1000:
                        self.Error.data_too_large_for_mahalanobis("columns")
                        return False
            return True

        self.clear_messages()
        if data is not None:
            for check in (_check_sparse, _check_tractability,
                          _fix_discrete, _fix_missing, _fix_nonbinary):
                if not check():
                    data = None
                    break

        self.start(DistanceRunner.run, data, metric,
                   self.normalized_dist, self.axis)

    def on_partial_result(self, _):
        pass

    def on_done(self, result: Orange.misc.DistMatrix):
        assert isinstance(result, Orange.misc.DistMatrix) or result is None
        self.Outputs.distances.send(result)

    def on_exception(self, ex):
        if isinstance(ex, ValueError):
            self.Error.distances_value_error(ex)
        elif isinstance(ex, MemoryError):
            self.Error.distances_memory_error()
        elif isinstance(ex, InterruptException):
            pass
        else:
            raise ex

    def onDeleteWidget(self):
        self.shutdown()
        super().onDeleteWidget()

    def _invalidate(self):
        self.commit()

    def _metric_changed(self):
        metric = METRICS[self.metric_idx][1]
        self.normalization_check.setEnabled(metric.supports_normalization)
        self._invalidate()

    def send_report(self):
        # pylint: disable=invalid-sequence-index
        self.report_items((
            ("Distances Between", ["Rows", "Columns"][self.axis]),
            ("Metric", METRICS[self.metric_idx][0])
        ))

    @classmethod
    def migrate_settings(cls, settings, version):
        if version is None or version < 2 and "normalized_dist" not in settings:
            # normalize_dist is set to False when restoring settings from
            # an older version to preserve old semantics.
            settings["normalized_dist"] = False
        if version is None or version < 3:
            # Mahalanobis was moved from idx = 2 to idx = 9
            metric_idx = settings["metric_idx"]
            if metric_idx == 2:
                settings["metric_idx"] = 9
            elif 2 < metric_idx <= 9:
                settings["metric_idx"] -= 1


if __name__ == "__main__":  # pragma: no cover
    WidgetPreview(OWDistances).run(Orange.data.Table("iris"))

```
--- END FILE ---

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

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

Here is an example:

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

Please note that the *SEARCH/REPLACE* edit REQUIRES PROPER INDENTATION. If you would like to add the line '        print(x)', you must fully write that out, with all those spaces before the code!
Wrap each *SEARCH/REPLACE* edit in a code block as shown in the example above. If you have multiple *SEARCH/REPLACE* edits, use a separate code block for each one.
[ISSUE]
**Title:** `remove_discrete_features` and `remove_nonbinary_features` Functions Do Not Support `to_metas` Parameter

**Description:**
The functions `remove_discrete_features` and `remove_nonbinary_features` are intended to move ignored attributes to metas when the `to_metas` parameter is set to `True`. However, currently, these functions do not accept the `to_metas` argument, causing errors when this parameter is used.

**Example Buggy Code:**
```python
from Orange.data import Table
from Orange.distance import remove_discrete_features, remove_nonbinary_features

data = Table("sample_data")
# Attempting to move ignored attributes to metas
reduced_discrete = remove_discrete_features(data, to_metas=True)  # Raises TypeError
reduced_nonbinary = remove_nonbinary_features(data, to_metas=True)  # Raises TypeError
```

**Expected Behavior:**
When the `to_metas` parameter is set to `True`, the functions should successfully move the ignored discrete or non-binary attributes to the metas of the data, modifying the domain accordingly without raising any errors.

**Actual Behavior:**
Passing the `to_metas=True` argument results in a `TypeError` because the functions do not recognize the `to_metas` keyword argument. The error messages are as follows:
```
TypeError: remove_discrete_features() got an unexpected keyword argument 'to_metas'
TypeError: remove_nonbinary_features() got an unexpected keyword argument 'to_metas'
```
This prevents the intended functionality of moving attributes to metas and causes related tests to fail.

[/ISSUE]
{
    "EuclideanDistanceTest.test_euclidean_cols": "PASSED",
    "EuclideanDistanceTest.test_euclidean_cols_normalized": "PASSED",
    "EuclideanDistanceTest.test_euclidean_cont": "PASSED",
    "EuclideanDistanceTest.test_euclidean_cont_normalized": "PASSED",
    "EuclideanDistanceTest.test_euclidean_disc": "PASSED",
    "EuclideanDistanceTest.test_euclidean_mixed": "PASSED",
    "EuclideanDistanceTest.test_mismatching_attributes": "PASSED",
    "EuclideanDistanceTest.test_mixed_cols": "PASSED",
    "EuclideanDistanceTest.test_no_data": "PASSED",
    "EuclideanDistanceTest.test_sparse": "PASSED",
    "EuclideanDistanceTest.test_two_tables": "PASSED",
    "EuclideanDistanceTest.test_zero_variance": "PASSED",
    "ManhattanDistanceTest.test_manhattan_cols": "PASSED",
    "ManhattanDistanceTest.test_manhattan_cols_normalized": "PASSED",
    "ManhattanDistanceTest.test_manhattan_cont": "PASSED",
    "ManhattanDistanceTest.test_manhattan_cont_normalized": "PASSED",
    "ManhattanDistanceTest.test_manhattan_disc": "PASSED",
    "ManhattanDistanceTest.test_manhattan_mixed": "PASSED",
    "ManhattanDistanceTest.test_manhattan_mixed_cols": "PASSED",
    "ManhattanDistanceTest.test_manhattan_no_data": "PASSED",
    "ManhattanDistanceTest.test_mismatching_attributes": "PASSED",
    "ManhattanDistanceTest.test_mixed_cols": "PASSED",
    "ManhattanDistanceTest.test_no_data": "PASSED",
    "ManhattanDistanceTest.test_sparse": "PASSED",
    "ManhattanDistanceTest.test_two_tables": "PASSED",
    "ManhattanDistanceTest.test_zero_variance": "PASSED",
    "CosineDistanceTest.test_cosine_cols": "PASSED",
    "CosineDistanceTest.test_cosine_cont": "PASSED",
    "CosineDistanceTest.test_cosine_disc": "PASSED",
    "CosineDistanceTest.test_cosine_mixed": "PASSED",
    "CosineDistanceTest.test_mismatching_attributes": "PASSED",
    "CosineDistanceTest.test_no_data": "PASSED",
    "CosineDistanceTest.test_sparse": "PASSED",
    "CosineDistanceTest.test_two_tables": "PASSED",
    "JaccardDistanceTest.test_jaccard_cols": "PASSED",
    "JaccardDistanceTest.test_jaccard_rows": "PASSED",
    "JaccardDistanceTest.test_mismatching_attributes": "PASSED",
    "JaccardDistanceTest.test_no_data": "PASSED",
    "JaccardDistanceTest.test_sparse": "PASSED",
    "JaccardDistanceTest.test_zero_instances": "PASSED",
    "HammingDistanceTest.test_hamming_col": "PASSED",
    "HammingDistanceTest.test_hamming_row": "PASSED",
    "HammingDistanceTest.test_hamming_row_secondary_data": "PASSED",
    "TestHelperFunctions.test_interruptable_dot": "PASSED",
    "TestHelperFunctions.test_interruptable_dot_list": "PASSED",
    "TestHelperFunctions.test_interruptable_dot_scalar": "PASSED",
    "TestHelperFunctions.test_interruptable_sqrt": "PASSED",
    "TestHelperFunctions.test_interruptable_sqrt_list": "PASSED",
    "TestHelperFunctions.test_interruptable_sqrt_scalar": "PASSED",
    "TestDataUtilities.test_remove_discrete": "PASSED",
    "TestDataUtilities.test_remove_non_binary": "PASSED",
    "TestDistanceRunner.test_run": "PASSED",
    "TestOWDistances.test_discrete_in_metas": "PASSED",
    "TestOWDistances.test_distance_combo": "PASSED",
    "TestOWDistances.test_error_message": "PASSED",
    "TestOWDistances.test_image_export": "PASSED",
    "TestOWDistances.test_jaccard_messages": "PASSED",
    "TestOWDistances.test_limit_mahalanobis": "PASSED",
    "TestOWDistances.test_migrates_normalized_dist": "PASSED",
    "TestOWDistances.test_minimum_size": "PASSED",
    "TestOWDistances.test_msg_base_class": "PASSED",
    "TestOWDistances.test_negative_values_bhattacharyya": "PASSED",
    "TestOWDistances.test_non_binary_in_metas": "PASSED",
    "TestOWDistances.test_too_big_array": "PASSED"
}
diff --git a/Orange/distance/base.py b/Orange/distance/base.py
index 7205e1cbc..112f9b1b4 100644
--- a/Orange/distance/base.py
+++ b/Orange/distance/base.py
@@ -34,22 +34,29 @@ def _preprocess(table, impute=True):
 
 # TODO I have put this function here as a substitute the above `_preprocess`.
 # None of them really belongs here; (re?)move them, eventually.
-def remove_discrete_features(data):
+def remove_discrete_features(data, to_metas=False):
     """Remove discrete columns from the data."""
     new_domain = Domain(
         [a for a in data.domain.attributes if a.is_continuous],
         data.domain.class_vars,
-        data.domain.metas)
+        data.domain.metas
+        + (() if not to_metas
+           else tuple(a for a in data.domain.attributes if not a.is_continuous))
+    )
     return data.transform(new_domain)
 
 
-def remove_nonbinary_features(data):
+def remove_nonbinary_features(data, to_metas=False):
     """Remove non-binary columns from the data."""
     new_domain = Domain(
         [a for a in data.domain.attributes
          if a.is_discrete and len(a.values) == 2],
         data.domain.class_vars,
-        data.domain.metas)
+        data.domain.metas +
+        (() if not to_metas
+         else tuple(a for a in data.domain.attributes
+               if not (a.is_discrete and len(a.values) == 2))
+         if to_metas else ()))
     return data.transform(new_domain)
 
 def impute(data):
diff --git a/Orange/widgets/unsupervised/owdistances.py b/Orange/widgets/unsupervised/owdistances.py
index 1676d9c51..4ad05e44c 100644
--- a/Orange/widgets/unsupervised/owdistances.py
+++ b/Orange/widgets/unsupervised/owdistances.py
@@ -158,7 +158,7 @@ class OWDistances(OWWidget, ConcurrentWidgetMixin):
                     self.Error.no_continuous_features()
                     return False
                 self.Warning.ignoring_discrete()
-                data = distance.remove_discrete_features(data)
+                data = distance.remove_discrete_features(data, to_metas=True)
             return True
 
         def _fix_nonbinary():
@@ -171,7 +171,8 @@ class OWDistances(OWWidget, ConcurrentWidgetMixin):
                     return False
                 elif nbinary < len(data.domain.attributes):
                     self.Warning.ignoring_nonbinary()
-                    data = distance.remove_nonbinary_features(data)
+                    data = distance.remove_nonbinary_features(data,
+                                                              to_metas=True)
             return True
 
         def _fix_missing():

{"Orange/distance/base.py": "# This module defines abstract base classes; derived classes are abstract, too\n# pylint: disable=abstract-method\n\nimport numpy as np\nimport sklearn.metrics as skl_metrics\n\nfrom Orange.data import Table, Domain, Instance, RowInstance\nfrom Orange.misc import DistMatrix\nfrom Orange.preprocess import SklImpute\nfrom Orange.statistics import util\n\n\n# TODO: When we upgrade to numpy 1.13, change use argument copy=False in\n# nan_to_num instead of assignment\n\n# TODO this *private* function is called from several widgets to prepare\n# data for calling the below classes. After we (mostly) stopped relying\n# on sklearn.metrics, this is (mostly) unnecessary\n# Afterwards, also remove the following line:\n# pylint: disable=redefined-outer-name\ndef _preprocess(table, impute=True):\n    \"\"\"Remove categorical attributes and impute missing values.\"\"\"\n    if not len(table):  # this can be an array, pylint: disable=len-as-condition\n        return table\n    new_domain = Domain(\n        [a for a in table.domain.attributes if a.is_continuous],\n        table.domain.class_vars,\n        table.domain.metas)\n    new_data = table.transform(new_domain)\n    if impute:\n        new_data = SklImpute()(new_data)\n    return new_data\n\n\n# TODO I have put this function here as a substitute the above `_preprocess`.\n# None of them really belongs here; (re?)move them, eventually.\ndef remove_discrete_features(data):\n    \"\"\"Remove discrete columns from the data.\"\"\"\n    new_domain = Domain(\n        [a for a in data.domain.attributes if a.is_continuous],\n        data.domain.class_vars,\n        data.domain.metas)\n    return data.transform(new_domain)\n\n\ndef remove_nonbinary_features(data):\n    \"\"\"Remove non-binary columns from the data.\"\"\"\n    new_domain = Domain(\n        [a for a in data.domain.attributes\n         if a.is_discrete and len(a.values) == 2],\n        data.domain.class_vars,\n        data.domain.metas)\n    return data.transform(new_domain)\n\ndef impute(data):\n    \"\"\"Impute missing values.\"\"\"\n    return SklImpute()(data)\n\n\ndef _orange_to_numpy(x):\n    \"\"\"\n    Return :class:`numpy.ndarray` (dense or sparse) with attribute data\n    from the given instance of :class:`Orange.data.Table`,\n    :class:`Orange.data.RowInstance` or :class:`Orange.data.Instance`.\n    \"\"\"\n    if isinstance(x, Table):\n        return x.X\n    elif isinstance(x, Instance):\n        return np.atleast_2d(x.x)\n    elif isinstance(x, np.ndarray):\n        return np.atleast_2d(x)\n    else:\n        return x  # e.g. None\n\n\nclass Distance:\n    \"\"\"\n    Base class for construction of distances models (:obj:`DistanceModel`).\n\n    Distances can be computed between all pairs of rows in one table, or\n    between pairs where one row is from one table and one from another.\n\n    If `axis` is set to `0`, the class computes distances between all pairs\n    of columns in a table. Distances between columns from separate tables are\n    probably meaningless, thus unsupported.\n\n    The class can be used as follows:\n\n    - Constructor is called only with keyword argument `axis` that\n      specifies the axis over which the distances are computed, and with other\n      subclass-specific keyword arguments.\n    - Next, we call the method `fit(data)` to produce an instance of\n      :obj:`DistanceModel`; the instance stores any parameters needed for\n      computation of distances, such as statistics for normalization and\n      handling of missing data.\n    - We can then call the :obj:`DistanceModel` with data to compute the\n      distance between its rows or columns, or with two data tables to\n      compute distances between all pairs of rows.\n\n    The second, shorter way to use this class is to call the constructor with\n    one or two data tables and any additional keyword arguments. Constructor\n    will execute the above steps and return :obj:`~Orange.misc.DistMatrix`.\n    Such usage is here for backward compatibility, practicality and efficiency.\n\n    Args:\n        e1 (:obj:`~Orange.data.Table` or :obj:`~Orange.data.Instance` or \\\n                :obj:`np.ndarray` or `None`):\n            data on which to train the model and compute the distances\n        e2 (:obj:`~Orange.data.Table` or :obj:`~Orange.data.Instance` or \\\n                :obj:`np.ndarray` or `None`):\n            if present, the class computes distances with pairs coming from\n            the two tables\n        axis (int):\n            axis over which the distances are computed, 1 (default) for\n            rows, 0 for columns\n        impute (bool):\n            if `True` (default is `False`), nans in the computed distances\n            are replaced with zeros, and infs with very large numbers.\n        callback (callable or None):\n            callback function\n\n    Attributes:\n        axis (int):\n            axis over which the distances are computed, 1 (default) for\n            rows, 0 for columns\n        impute (bool):\n            if `True` (default is `False`), nans in the computed distances\n            are replaced with zeros, and infs with very large numbers.\n        normalize (bool):\n            if `True`, columns are normalized before computation. This attribute\n            applies only if the distance supports normalization.\n\n    The capabilities of the metrics are described with class attributes.\n\n    If class attribute `supports_discrete` is `True`, the distance\n    also uses discrete attributes to compute row distances. The use of discrete\n    attributes depends upon the type of distance; e.g. Jaccard distance observes\n    whether the value is zero or non-zero, while Euclidean and Manhattan\n    distance observes whether a pair of values is same or different.\n\n    Class attribute `supports_missing` indicates that the distance can cope\n    with missing data. In such cases, letting the distance handle it should\n    be preferred over pre-imputation of missing values.\n\n    Class attribute `supports_normalization` indicates that the constructor\n    accepts an argument `normalize`. If set to `True`, the metric will attempt\n    to normalize the values in a sense that each attribute will have equal\n    influence. For instance, the Euclidean distance subtract the mean and\n    divides the result by the deviation, while Manhattan distance uses the\n    median and MAD.\n\n    If class attribute `supports_sparse` is `True`, the class will handle\n    sparse data. Currently, all classes that do handle it rely on fallbacks to\n    SKL metrics. These, however, do not support discrete data and missing\n    values, and will fail silently.\n    \"\"\"\n    supports_sparse = False\n    supports_discrete = False\n    supports_normalization = False\n    supports_missing = True\n\n    # Predefined here to silence pylint, which doesn't look into __new__\n    normalize = False\n    axis = 1\n    impute = False\n\n    def __new__(cls, e1=None, e2=None, axis=1, impute=False,\n                callback=None, **kwargs):\n        self = super().__new__(cls)\n        self.axis = axis\n        self.impute = impute\n        self.callback = callback\n        # Ugly, but needed to allow allow setting subclass-specific parameters\n        # (such as normalize) when `e1` is not `None` and the `__new__` in the\n        # subclass is skipped\n        self.__dict__.update(**kwargs)\n        if e1 is None:\n            return self\n\n        # Fallbacks for sparse data and numpy tables. Remove when subclasses\n        # no longer use fallbacks for sparse data, and handling numpy tables\n        # becomes obsolete (or handled elsewhere)\n        if (not hasattr(e1, \"domain\")\n                or hasattr(e1, \"is_sparse\") and e1.is_sparse()):\n            fallback = getattr(self, \"fallback\", None)\n            if fallback is not None:\n                # pylint: disable=not-callable\n                return fallback(e1, e2, axis, impute)\n\n        # Magic constructor\n        model = self.fit(e1)\n        return model(e1, e2)\n\n    def fit(self, data):\n        \"\"\"\n        Abstract method returning :obj:`DistanceModel` fit to the data\n\n        Args:\n            e1 (Orange.data.Table, Orange.data.Instance, np.ndarray):\n                data for fitting the distance model\n\n        Returns:\n            model (DistanceModel)\n        \"\"\"\n        raise NotImplementedError\n\n    @staticmethod\n    def check_no_discrete(n_vals):\n        \"\"\"\n        Raise an exception if there are any discrete attributes.\n\n        Args:\n            n_vals (list of int): number of attributes values, 0 for continuous\n        \"\"\"\n        if any(n_vals):\n            raise ValueError(\"columns with discrete values are incommensurable\")\n\n\nclass DistanceModel:\n    \"\"\"\n    Base class for classes that compute distances between data rows or columns.\n    Instances of these classes are not constructed directly but returned by\n    the corresponding instances of :obj:`Distance`.\n\n    Attributes:\n        axis (int, readonly):\n            axis over which the distances are computed, 1 (default) for\n            rows, 0 for columns\n        impute (bool):\n            if `True` (default is `False`), nans in the computed distances\n            are replaced with zeros, and infs with very large numbers\n        callback (callable or None):\n            callback function\n\n    \"\"\"\n    def __init__(self, axis, impute=False, callback=None):\n        self._axis = axis\n        self.impute = impute\n        self.callback = callback\n\n    @property\n    def axis(self):\n        return self._axis\n\n    def __call__(self, e1, e2=None):\n        \"\"\"\n        If e2 is omitted, calculate distances between all rows (axis=1) or\n        columns (axis=2) of e1. If e2 is present, calculate distances between\n        all pairs if rows from e1 and e2.\n\n        This method converts the data into numpy arrays, calls the method\n        `compute_data` and packs the result into `DistMatrix`. Subclasses are\n        expected to define the `compute_data` and not the `__call__` method.\n\n        Args:\n            e1 (Orange.data.Table or Orange.data.Instance or numpy.ndarray):\n                input data\n            e2 (Orange.data.Table or Orange.data.Instance or numpy.ndarray):\n                secondary data\n\n        Returns:\n            A distance matrix (Orange.misc.distmatrix.DistMatrix)\n        \"\"\"\n        if self.axis == 0 and e2 is not None:\n            # Backward compatibility fix\n            if e2 is e1:\n                e2 = None\n            else:\n                raise ValueError(\"Two tables cannot be compared by columns\")\n\n        x1 = _orange_to_numpy(e1)\n        x2 = _orange_to_numpy(e2)\n        with np.errstate(invalid=\"ignore\"):  # nans are handled below\n            dist = self.compute_distances(x1, x2)\n            if self.impute and np.isnan(dist).any():\n                dist = np.nan_to_num(dist)\n            if isinstance(e1, (Table, RowInstance)):\n                dist = DistMatrix(dist, e1, e2, self.axis)\n            else:\n                dist = DistMatrix(dist)\n            return dist\n\n    def compute_distances(self, x1, x2):\n        \"\"\"\n        Abstract method for computation of distances between rows or columns of\n        `x1`, or between rows of `x1` and `x2`. Do not call directly.\"\"\"\n        raise NotImplementedError\n\n\nclass FittedDistanceModel(DistanceModel):\n    \"\"\"\n    Base class for models that store attribute-related data for normalization\n    and imputation, and that treat discrete and continuous columns separately.\n\n    Attributes:\n        attributes (list of `Variable`): attributes on which the model was fit\n        discrete (np.ndarray): bool array indicating discrete attributes\n        continuous (np.ndarray): bool array indicating continuous attributes\n        normalize (bool):\n            if `True` (default is `False`) continuous columns are normalized\n        callback (callable or None): callback function\n    \"\"\"\n    def __init__(self, attributes, axis=1, impute=False, callback=None):\n        super().__init__(axis, impute, callback)\n        self.attributes = attributes\n        self.discrete = None\n        self.continuous = None\n        self.normalize = False\n\n    def __call__(self, e1, e2=None):\n        if self.attributes is not None and (\n                e1.domain.attributes != self.attributes\n                or e2 is not None and e2.domain.attributes != self.attributes):\n            raise ValueError(\"mismatching domains\")\n        return super().__call__(e1, e2)\n\n    def continuous_columns(self, x1, x2, offset, scale):\n        \"\"\"\n        Extract and scale continuous columns from data tables.\n        If the second table is None, it defaults to the first table.\n\n        Values are scaled if `self.normalize` is `True`.\n\n        Args:\n            x1 (np.ndarray): first table\n            x2 (np.ndarray or None): second table\n            offset (float): a constant (e.g. mean, median) subtracted from data\n            scale: (float): divider (e.g. deviation)\n\n        Returns:\n            data1 (np.ndarray): scaled continuous columns from `x1`\n            data2 (np.ndarray): scaled continuous columns from `x2` or `x1`\n        \"\"\"\n        if self.continuous.all() and not self.normalize:\n            data1, data2 = x1, x2\n        else:\n            data1 = x1[:, self.continuous]\n            if x2 is not None:\n                data2 = x2[:, self.continuous]\n            if self.normalize:\n                data1 = x1[:, self.continuous]\n                data1 -= offset\n                data1 /= scale\n                if x2 is not None:\n                    data2 = x2[:, self.continuous]\n                    data2 -= offset\n                    data2 /= scale\n        if x2 is None:\n            data2 = data1\n        return data1, data2\n\n    def discrete_columns(self, x1, x2):\n        \"\"\"\n        Return discrete columns from the given tables.\n        If the second table is None, it defaults to the first table.\n        \"\"\"\n        if self.discrete.all():\n            data1, data2 = x1, x1 if x2 is None else x2\n        else:\n            data1 = x1[:, self.discrete]\n            data2 = data1 if x2 is None else x2[:, self.discrete]\n        return data1, data2\n\n\nclass FittedDistance(Distance):\n    \"\"\"\n    Base class for fitting models that store attribute-related data for\n    normalization and imputation, and that treat discrete and continuous\n    columns separately.\n\n    The class implements a method `fit` that calls either `fit_columns`\n    or `fit_rows` with the data and the number of values for discrete\n    attributes. The provided method `fit_rows` calls methods\n    `get_discrete_stats` and `get_continuous_stats` that can be implemented\n    in derived classes.\n\n    Class attribute `rows_model_type` contains the type of the model returned by\n    `fit_rows`.\n    \"\"\"\n    rows_model_type = None  #: Option[FittedDistanceModel]\n\n    def fit(self, data):\n        \"\"\"\n        Prepare the data on attributes, call `fit_cols` or `fit_rows` and\n        return the resulting model.\n        \"\"\"\n        x = _orange_to_numpy(data)\n        if hasattr(data, \"domain\"):\n            attributes = data.domain.attributes\n            n_vals = np.fromiter(\n                (len(attr.values) if attr.is_discrete else 0\n                 for attr in attributes),\n                dtype=np.int32, count=len(attributes))\n        else:\n            assert isinstance(x, np.ndarray)\n            attributes = None\n            n_vals = np.zeros(x.shape[1], dtype=np.int32)\n        return [self.fit_cols, self.fit_rows][self.axis](attributes, x, n_vals)\n\n    def fit_cols(self, attributes, x, n_vals):\n        \"\"\"\n        Return DistanceModel for computation of distances between columns.\n        Derived classes must define this method.\n\n        Args:\n            attributes (list of Orange.data.Variable): list of attributes\n            x (np.ndarray): data\n            n_vals (np.ndarray): number of attribute values, 0 for continuous\n        \"\"\"\n        raise NotImplementedError\n\n    def fit_rows(self, attributes, x, n_vals):\n        \"\"\"\n        Return a DistanceModel for computation of distances between rows.\n\n        The model type is `self.row_distance_model`. It stores the data for\n        imputation of discrete and continuous values, and for normalization\n        of continuous values. Typical examples are the Euclidean and Manhattan\n        distance, for which the following data is stored:\n\n        For continuous columns:\n\n        - offsets[col] is the number subtracted from values in column `col`\n        - scales[col] is the divisor for values in columns `col`\n        - dist_missing2_cont[col]: the value used for distance between two\n            missing values in column `col`\n\n        For discrete values:\n\n        - dist_missing_disc[col, value] is the distance added for the given\n            `value` in the column `col` if the value for the other row is\n            missing\n        - dist_missing2_disc[col]: the distance between two missing values in\n            column `col`\n        \"\"\"\n        n_cols = len(n_vals)\n\n        discrete = n_vals > 0\n        n_bins = max(n_vals, default=0)\n        n_discrete = sum(discrete)\n        dist_missing_disc = np.zeros((n_discrete, n_bins), dtype=float)\n        dist_missing2_disc = np.zeros(n_discrete, dtype=float)\n\n        continuous = ~discrete\n        n_continuous = sum(continuous)\n        offsets = np.zeros(n_continuous, dtype=float)\n        scales = np.empty(n_continuous, dtype=float)\n        dist_missing2_cont = np.zeros(n_continuous, dtype=float)\n\n        curr_disc = curr_cont = 0\n        for col in range(n_cols):\n            column = x[:, col]\n            if np.isnan(column).all():\n                continuous[col] = discrete[col] = False\n            elif discrete[col]:\n                discrete_stats = self.get_discrete_stats(column, n_bins)\n                if discrete_stats is not None:\n                    dist_missing_disc[curr_disc], \\\n                    dist_missing2_disc[curr_disc] = discrete_stats\n                    curr_disc += 1\n            else:\n                continuous_stats = self.get_continuous_stats(column)\n                if continuous_stats is not None:\n                    offsets[curr_cont], scales[curr_cont],\\\n                    dist_missing2_cont[curr_cont] = continuous_stats\n                    curr_cont += 1\n                else:\n                    continuous[col] = False\n        # pylint: disable=not-callable\n        return self.rows_model_type(\n            attributes, impute, getattr(self, \"normalize\", False),\n            continuous, discrete,\n            offsets[:curr_cont], scales[:curr_cont],\n            dist_missing2_cont[:curr_cont],\n            dist_missing_disc, dist_missing2_disc,\n            self.callback)\n\n    @staticmethod\n    def get_discrete_stats(column, n_bins):\n        \"\"\"\n        Return tables used computing distance between missing discrete values.\n\n        Args:\n            column (np.ndarray): column data\n            n_bins (int): maximal number of bins in the dataset\n\n        Returns:\n            dist_missing_disc (np.ndarray): `dist_missing_disc[value]` is\n                1 - probability of `value`, which is used as the distance added\n                for the given `value` in the column `col` if the value for the\n                other row is missing\n            dist_missing2_disc (float): the distance between two missing\n                values in this columns\n        \"\"\"\n        dist = util.bincount(column, minlength=n_bins)[0]\n        dist /= max(1, sum(dist))\n        return 1 - dist, 1 - np.sum(dist ** 2)\n\n    def get_continuous_stats(self, column):\n        \"\"\"\n        Compute statistics for imputation and normalization of continuous data.\n        Derived classes must define this method.\n\n        Args:\n            column (np.ndarray): column data\n\n        Returns:\n            offset (float): the number subtracted from values in column\n            scales (float): the divisor for values in column\n            dist_missing2_cont (float): the value used for distance between two\n                missing values in column\n        \"\"\"\n        raise NotImplementedError\n\n\n# Fallbacks for distances in sparse data\n# To be removed as the corresponding functionality is implemented properly\n\nclass SklDistance:\n    \"\"\"\n    Wrapper for functions sklearn's metrics. Used only as temporary fallbacks\n    when `Euclidean`, `Manhattan`, `Cosine` or `Jaccard` are given sparse data\n    or raw numpy arrays. These classes can't handle discrete or missing data\n    and normalization. Do not use for wrapping new classes.\n    \"\"\"\n    def __init__(self, metric):\n        self.metric = metric\n\n    def __call__(self, e1, e2=None, axis=1, impute=False):\n        x1 = _orange_to_numpy(e1)\n        x2 = _orange_to_numpy(e2)\n        if axis == 0:\n            x1 = x1.T\n            if x2 is not None:\n                x2 = x2.T\n        dist = skl_metrics.pairwise.pairwise_distances(\n            x1, x2, metric=self.metric)\n        if impute and np.isnan(dist).any():\n            dist = np.nan_to_num(dist)\n        if isinstance(e1, (Table, RowInstance)):\n            dist_matrix = DistMatrix(dist, e1, e2, axis)\n        else:\n            dist_matrix = DistMatrix(dist)\n        return dist_matrix\n", "Orange/widgets/unsupervised/owdistances.py": "from scipy.sparse import issparse\nimport bottleneck as bn\n\nfrom AnyQt.QtCore import Qt\n\nimport Orange.data\nimport Orange.misc\nfrom Orange import distance\nfrom Orange.widgets import gui\nfrom Orange.widgets.settings import Setting\nfrom Orange.widgets.utils.concurrent import TaskState, ConcurrentWidgetMixin\nfrom Orange.widgets.utils.sql import check_sql_input\nfrom Orange.widgets.utils.widgetpreview import WidgetPreview\nfrom Orange.widgets.widget import OWWidget, Msg, Input, Output\n\n\nMETRICS = [\n    (\"Euclidean\", distance.Euclidean),\n    (\"Manhattan\", distance.Manhattan),\n    (\"Cosine\", distance.Cosine),\n    (\"Jaccard\", distance.Jaccard),\n    (\"Spearman\", distance.SpearmanR),\n    (\"Absolute Spearman\", distance.SpearmanRAbsolute),\n    (\"Pearson\", distance.PearsonR),\n    (\"Absolute Pearson\", distance.PearsonRAbsolute),\n    (\"Hamming\", distance.Hamming),\n    (\"Mahalanobis\", distance.Mahalanobis),\n    ('Bhattacharyya', distance.Bhattacharyya)\n]\n\n\nclass InterruptException(Exception):\n    pass\n\n\nclass DistanceRunner:\n    @staticmethod\n    def run(data: Orange.data.Table, metric: distance, normalized_dist: bool,\n            axis: int, state: TaskState) -> Orange.misc.DistMatrix:\n        if data is None:\n            return None\n\n        def callback(i: float) -> bool:\n            state.set_progress_value(i)\n            if state.is_interruption_requested():\n                raise InterruptException\n\n        state.set_status(\"Calculating...\")\n        kwargs = {\"axis\": 1 - axis, \"impute\": True, \"callback\": callback}\n        if metric.supports_normalization and normalized_dist:\n            kwargs[\"normalize\"] = True\n        return metric(data, **kwargs)\n\n\nclass OWDistances(OWWidget, ConcurrentWidgetMixin):\n    name = \"Distances\"\n    description = \"Compute a matrix of pairwise distances.\"\n    icon = \"icons/Distance.svg\"\n    keywords = []\n\n    class Inputs:\n        data = Input(\"Data\", Orange.data.Table)\n\n    class Outputs:\n        distances = Output(\"Distances\", Orange.misc.DistMatrix, dynamic=False)\n\n    settings_version = 3\n\n    axis = Setting(0)        # type: int\n    metric_idx = Setting(0)  # type: int\n\n    #: Use normalized distances if the metric supports it.\n    #: The default is `True`, expect when restoring from old pre v2 settings\n    #: (see `migrate_settings`).\n    normalized_dist = Setting(True)  # type: bool\n    autocommit = Setting(True)       # type: bool\n\n    want_main_area = False\n    resizing_enabled = False\n\n    class Error(OWWidget.Error):\n        no_continuous_features = Msg(\"No numeric features\")\n        no_binary_features = Msg(\"No binary features\")\n        dense_metric_sparse_data = Msg(\"{} requires dense data.\")\n        distances_memory_error = Msg(\"Not enough memory\")\n        distances_value_error = Msg(\"Problem in calculation:\\n{}\")\n        data_too_large_for_mahalanobis = Msg(\n            \"Mahalanobis handles up to 1000 {}.\")\n\n    class Warning(OWWidget.Warning):\n        ignoring_discrete = Msg(\"Ignoring categorical features\")\n        ignoring_nonbinary = Msg(\"Ignoring non-binary features\")\n        imputing_data = Msg(\"Missing values were imputed\")\n\n    def __init__(self):\n        OWWidget.__init__(self)\n        ConcurrentWidgetMixin.__init__(self)\n\n        self.data = None\n\n        gui.radioButtons(\n            self.controlArea, self, \"axis\", [\"Rows\", \"Columns\"],\n            box=\"Distances between\", callback=self._invalidate\n        )\n        box = gui.widgetBox(self.controlArea, \"Distance Metric\")\n        self.metrics_combo = gui.comboBox(\n            box, self, \"metric_idx\",\n            items=[m[0] for m in METRICS],\n            callback=self._metric_changed\n        )\n        self.normalization_check = gui.checkBox(\n            box, self, \"normalized_dist\", \"Normalized\",\n            callback=self._invalidate,\n            tooltip=(\"All dimensions are (implicitly) scaled to a common\"\n                     \"scale to normalize the influence across the domain.\"),\n            stateWhenDisabled=False, attribute=Qt.WA_LayoutUsesWidgetRect\n        )\n        _, metric = METRICS[self.metric_idx]\n        self.normalization_check.setEnabled(metric.supports_normalization)\n\n        gui.auto_apply(self.buttonsArea, self, \"autocommit\")\n\n    @Inputs.data\n    @check_sql_input\n    def set_data(self, data):\n        self.cancel()\n        self.data = data\n        self.refresh_metrics()\n        self.unconditional_commit()\n\n    def refresh_metrics(self):\n        sparse = self.data is not None and issparse(self.data.X)\n        for i, metric in enumerate(METRICS):\n            item = self.metrics_combo.model().item(i)\n            item.setEnabled(not sparse or metric[1].supports_sparse)\n\n    def commit(self):\n        # pylint: disable=invalid-sequence-index\n        metric = METRICS[self.metric_idx][1]\n        self.compute_distances(metric, self.data)\n\n    def compute_distances(self, metric, data):\n        def _check_sparse():\n            # pylint: disable=invalid-sequence-index\n            if issparse(data.X) and not metric.supports_sparse:\n                self.Error.dense_metric_sparse_data(METRICS[self.metric_idx][0])\n                return False\n            return True\n\n        def _fix_discrete():\n            nonlocal data\n            if data.domain.has_discrete_attributes() \\\n                    and metric is not distance.Jaccard \\\n                    and (issparse(data.X) and getattr(metric, \"fallback\", None)\n                         or not metric.supports_discrete\n                         or self.axis == 1):\n                if not data.domain.has_continuous_attributes():\n                    self.Error.no_continuous_features()\n                    return False\n                self.Warning.ignoring_discrete()\n                data = distance.remove_discrete_features(data)\n            return True\n\n        def _fix_nonbinary():\n            nonlocal data\n            if metric is distance.Jaccard and not issparse(data.X):\n                nbinary = sum(a.is_discrete and len(a.values) == 2\n                              for a in data.domain.attributes)\n                if not nbinary:\n                    self.Error.no_binary_features()\n                    return False\n                elif nbinary < len(data.domain.attributes):\n                    self.Warning.ignoring_nonbinary()\n                    data = distance.remove_nonbinary_features(data)\n            return True\n\n        def _fix_missing():\n            nonlocal data\n            if not metric.supports_missing and bn.anynan(data.X):\n                self.Warning.imputing_data()\n                data = distance.impute(data)\n            return True\n\n        def _check_tractability():\n            if metric is distance.Mahalanobis:\n                if self.axis == 1:\n                    # when computing distances by columns, we want < 100 rows\n                    if len(data) > 1000:\n                        self.Error.data_too_large_for_mahalanobis(\"rows\")\n                        return False\n                else:\n                    if len(data.domain.attributes) > 1000:\n                        self.Error.data_too_large_for_mahalanobis(\"columns\")\n                        return False\n            return True\n\n        self.clear_messages()\n        if data is not None:\n            for check in (_check_sparse, _check_tractability,\n                          _fix_discrete, _fix_missing, _fix_nonbinary):\n                if not check():\n                    data = None\n                    break\n\n        self.start(DistanceRunner.run, data, metric,\n                   self.normalized_dist, self.axis)\n\n    def on_partial_result(self, _):\n        pass\n\n    def on_done(self, result: Orange.misc.DistMatrix):\n        assert isinstance(result, Orange.misc.DistMatrix) or result is None\n        self.Outputs.distances.send(result)\n\n    def on_exception(self, ex):\n        if isinstance(ex, ValueError):\n            self.Error.distances_value_error(ex)\n        elif isinstance(ex, MemoryError):\n            self.Error.distances_memory_error()\n        elif isinstance(ex, InterruptException):\n            pass\n        else:\n            raise ex\n\n    def onDeleteWidget(self):\n        self.shutdown()\n        super().onDeleteWidget()\n\n    def _invalidate(self):\n        self.commit()\n\n    def _metric_changed(self):\n        metric = METRICS[self.metric_idx][1]\n        self.normalization_check.setEnabled(metric.supports_normalization)\n        self._invalidate()\n\n    def send_report(self):\n        # pylint: disable=invalid-sequence-index\n        self.report_items((\n            (\"Distances Between\", [\"Rows\", \"Columns\"][self.axis]),\n            (\"Metric\", METRICS[self.metric_idx][0])\n        ))\n\n    @classmethod\n    def migrate_settings(cls, settings, version):\n        if version is None or version < 2 and \"normalized_dist\" not in settings:\n            # normalize_dist is set to False when restoring settings from\n            # an older version to preserve old semantics.\n            settings[\"normalized_dist\"] = False\n        if version is None or version < 3:\n            # Mahalanobis was moved from idx = 2 to idx = 9\n            metric_idx = settings[\"metric_idx\"]\n            if metric_idx == 2:\n                settings[\"metric_idx\"] = 9\n            elif 2 < metric_idx <= 9:\n                settings[\"metric_idx\"] -= 1\n\n\nif __name__ == \"__main__\":  # pragma: no cover\n    WidgetPreview(OWDistances).run(Orange.data.Table(\"iris\"))\n"}
A user will ask you to solve a task. You should first draft your thinking process (inner monologue). Then, generate the solution.

Your response format must follow the template below:
<think>
Your thoughts or/and draft, like working through an exercise on scratch paper. Be as casual and as long as you want until you are confident to generate a correct solution.
</think>
<solution>
Final solution presented to the user.
</solution>
system
We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
[ISSUE]
**Title:** `remove_discrete_features` and `remove_nonbinary_features` Functions Do Not Support `to_metas` Parameter

**Description:**
The functions `remove_discrete_features` and `remove_nonbinary_features` are intended to move ignored attributes to metas when the `to_metas` parameter is set to `True`. However, currently, these functions do not accept the `to_metas` argument, causing errors when this parameter is used.

**Example Buggy Code:**
```python
from Orange.data import Table
from Orange.distance import remove_discrete_features, remove_nonbinary_features

data = Table("sample_data")
# Attempting to move ignored attributes to metas
reduced_discrete = remove_discrete_features(data, to_metas=True)  # Raises TypeError
reduced_nonbinary = remove_nonbinary_features(data, to_metas=True)  # Raises TypeError
```

**Expected Behavior:**
When the `to_metas` parameter is set to `True`, the functions should successfully move the ignored discrete or non-binary attributes to the metas of the data, modifying the domain accordingly without raising any errors.

**Actual Behavior:**
Passing the `to_metas=True` argument results in a `TypeError` because the functions do not recognize the `to_metas` keyword argument. The error messages are as follows:
```
TypeError: remove_discrete_features() got an unexpected keyword argument 'to_metas'
TypeError: remove_nonbinary_features() got an unexpected keyword argument 'to_metas'
```
This prevents the intended functionality of moving attributes to metas and causes related tests to fail.

[/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/distance/base.py
# This module defines abstract base classes; derived classes are abstract, too
# pylint: disable=abstract-method

import numpy as np
import sklearn.metrics as skl_metrics

from Orange.data import Table, Domain, Instance, RowInstance
from Orange.misc import DistMatrix
from Orange.preprocess import SklImpute
from Orange.statistics import util


# TODO: When we upgrade to numpy 1.13, change use argument copy=False in
# nan_to_num instead of assignment

# TODO this *private* function is called from several widgets to prepare
# data for calling the below classes. After we (mostly) stopped relying
# on sklearn.metrics, this is (mostly) unnecessary
# Afterwards, also remove the following line:
# pylint: disable=redefined-outer-name
def _preprocess(table, impute=True):
    """Remove categorical attributes and impute missing values."""
    if not len(table):  # this can be an array, pylint: disable=len-as-condition
        return table
    new_domain = Domain(
        [a for a in table.domain.attributes if a.is_continuous],
        table.domain.class_vars,
        table.domain.metas)
    new_data = table.transform(new_domain)
    if impute:
        new_data = SklImpute()(new_data)
    return new_data


# TODO I have put this function here as a substitute the above `_preprocess`.
# None of them really belongs here; (re?)move them, eventually.
def remove_discrete_features(data):
    """Remove discrete columns from the data."""
    new_domain = Domain(
        [a for a in data.domain.attributes if a.is_continuous],
        data.domain.class_vars,
        data.domain.metas)
    return data.transform(new_domain)


def remove_nonbinary_features(data):
    """Remove non-binary columns from the data."""
    new_domain = Domain(
        [a for a in data.domain.attributes
         if a.is_discrete and len(a.values) == 2],
        data.domain.class_vars,
        data.domain.metas)
    return data.transform(new_domain)

def impute(data):
    """Impute missing values."""
    return SklImpute()(data)


def _orange_to_numpy(x):
    """
    Return :class:`numpy.ndarray` (dense or sparse) with attribute data
    from the given instance of :class:`Orange.data.Table`,
    :class:`Orange.data.RowInstance` or :class:`Orange.data.Instance`.
    """
    if isinstance(x, Table):
        return x.X
    elif isinstance(x, Instance):
        return np.atleast_2d(x.x)
    elif isinstance(x, np.ndarray):
        return np.atleast_2d(x)
    else:
        return x  # e.g. None


class Distance:
    """
    Base class for construction of distances models (:obj:`DistanceModel`).

    Distances can be computed between all pairs of rows in one table, or
    between pairs where one row is from one table and one from another.

    If `axis` is set to `0`, the class computes distances between all pairs
    of columns in a table. Distances between columns from separate tables are
    probably meaningless, thus unsupported.

    The class can be used as follows:

    - Constructor is called only with keyword argument `axis` that
      specifies the axis over which the distances are computed, and with other
      subclass-specific keyword arguments.
    - Next, we call the method `fit(data)` to produce an instance of
      :obj:`DistanceModel`; the instance stores any parameters needed for
      computation of distances, such as statistics for normalization and
      handling of missing data.
    - We can then call the :obj:`DistanceModel` with data to compute the
      distance between its rows or columns, or with two data tables to
      compute distances between all pairs of rows.

    The second, shorter way to use this class is to call the constructor with
    one or two data tables and any additional keyword arguments. Constructor
    will execute the above steps and return :obj:`~Orange.misc.DistMatrix`.
    Such usage is here for backward compatibility, practicality and efficiency.

    Args:
        e1 (:obj:`~Orange.data.Table` or :obj:`~Orange.data.Instance` or \
                :obj:`np.ndarray` or `None`):
            data on which to train the model and compute the distances
        e2 (:obj:`~Orange.data.Table` or :obj:`~Orange.data.Instance` or \
                :obj:`np.ndarray` or `None`):
            if present, the class computes distances with pairs coming from
            the two tables
        axis (int):
            axis over which the distances are computed, 1 (default) for
            rows, 0 for columns
        impute (bool):
            if `True` (default is `False`), nans in the computed distances
            are replaced with zeros, and infs with very large numbers.
        callback (callable or None):
            callback function

    Attributes:
        axis (int):
            axis over which the distances are computed, 1 (default) for
            rows, 0 for columns
        impute (bool):
            if `True` (default is `False`), nans in the computed distances
            are replaced with zeros, and infs with very large numbers.
        normalize (bool):
            if `True`, columns are normalized before computation. This attribute
            applies only if the distance supports normalization.

    The capabilities of the metrics are described with class attributes.

    If class attribute `supports_discrete` is `True`, the distance
    also uses discrete attributes to compute row distances. The use of discrete
    attributes depends upon the type of distance; e.g. Jaccard distance observes
    whether the value is zero or non-zero, while Euclidean and Manhattan
    distance observes whether a pair of values is same or different.

    Class attribute `supports_missing` indicates that the distance can cope
    with missing data. In such cases, letting the distance handle it should
    be preferred over pre-imputation of missing values.

    Class attribute `supports_normalization` indicates that the constructor
    accepts an argument `normalize`. If set to `True`, the metric will attempt
    to normalize the values in a sense that each attribute will have equal
    influence. For instance, the Euclidean distance subtract the mean and
    divides the result by the deviation, while Manhattan distance uses the
    median and MAD.

    If class attribute `supports_sparse` is `True`, the class will handle
    sparse data. Currently, all classes that do handle it rely on fallbacks to
    SKL metrics. These, however, do not support discrete data and missing
    values, and will fail silently.
    """
    supports_sparse = False
    supports_discrete = False
    supports_normalization = False
    supports_missing = True

    # Predefined here to silence pylint, which doesn't look into __new__
    normalize = False
    axis = 1
    impute = False

    def __new__(cls, e1=None, e2=None, axis=1, impute=False,
                callback=None, **kwargs):
        self = super().__new__(cls)
        self.axis = axis
        self.impute = impute
        self.callback = callback
        # Ugly, but needed to allow allow setting subclass-specific parameters
        # (such as normalize) when `e1` is not `None` and the `__new__` in the
        # subclass is skipped
        self.__dict__.update(**kwargs)
        if e1 is None:
            return self

        # Fallbacks for sparse data and numpy tables. Remove when subclasses
        # no longer use fallbacks for sparse data, and handling numpy tables
        # becomes obsolete (or handled elsewhere)
        if (not hasattr(e1, "domain")
                or hasattr(e1, "is_sparse") and e1.is_sparse()):
            fallback = getattr(self, "fallback", None)
            if fallback is not None:
                # pylint: disable=not-callable
                return fallback(e1, e2, axis, impute)

        # Magic constructor
        model = self.fit(e1)
        return model(e1, e2)

    def fit(self, data):
        """
        Abstract method returning :obj:`DistanceModel` fit to the data

        Args:
            e1 (Orange.data.Table, Orange.data.Instance, np.ndarray):
                data for fitting the distance model

        Returns:
            model (DistanceModel)
        """
        raise NotImplementedError

    @staticmethod
    def check_no_discrete(n_vals):
        """
        Raise an exception if there are any discrete attributes.

        Args:
            n_vals (list of int): number of attributes values, 0 for continuous
        """
        if any(n_vals):
            raise ValueError("columns with discrete values are incommensurable")


class DistanceModel:
    """
    Base class for classes that compute distances between data rows or columns.
    Instances of these classes are not constructed directly but returned by
    the corresponding instances of :obj:`Distance`.

    Attributes:
        axis (int, readonly):
            axis over which the distances are computed, 1 (default) for
            rows, 0 for columns
        impute (bool):
            if `True` (default is `False`), nans in the computed distances
            are replaced with zeros, and infs with very large numbers
        callback (callable or None):
            callback function

    """
    def __init__(self, axis, impute=False, callback=None):
        self._axis = axis
        self.impute = impute
        self.callback = callback

    @property
    def axis(self):
        return self._axis

    def __call__(self, e1, e2=None):
        """
        If e2 is omitted, calculate distances between all rows (axis=1) or
        columns (axis=2) of e1. If e2 is present, calculate distances between
        all pairs if rows from e1 and e2.

        This method converts the data into numpy arrays, calls the method
        `compute_data` and packs the result into `DistMatrix`. Subclasses are
        expected to define the `compute_data` and not the `__call__` method.

        Args:
            e1 (Orange.data.Table or Orange.data.Instance or numpy.ndarray):
                input data
            e2 (Orange.data.Table or Orange.data.Instance or numpy.ndarray):
                secondary data

        Returns:
            A distance matrix (Orange.misc.distmatrix.DistMatrix)
        """
        if self.axis == 0 and e2 is not None:
            # Backward compatibility fix
            if e2 is e1:
                e2 = None
            else:
                raise ValueError("Two tables cannot be compared by columns")

        x1 = _orange_to_numpy(e1)
        x2 = _orange_to_numpy(e2)
        with np.errstate(invalid="ignore"):  # nans are handled below
            dist = self.compute_distances(x1, x2)
            if self.impute and np.isnan(dist).any():
                dist = np.nan_to_num(dist)
            if isinstance(e1, (Table, RowInstance)):
                dist = DistMatrix(dist, e1, e2, self.axis)
            else:
                dist = DistMatrix(dist)
            return dist

    def compute_distances(self, x1, x2):
        """
        Abstract method for computation of distances between rows or columns of
        `x1`, or between rows of `x1` and `x2`. Do not call directly."""
        raise NotImplementedError


class FittedDistanceModel(DistanceModel):
    """
    Base class for models that store attribute-related data for normalization
    and imputation, and that treat discrete and continuous columns separately.

    Attributes:
        attributes (list of `Variable`): attributes on which the model was fit
        discrete (np.ndarray): bool array indicating discrete attributes
        continuous (np.ndarray): bool array indicating continuous attributes
        normalize (bool):
            if `True` (default is `False`) continuous columns are normalized
        callback (callable or None): callback function
    """
    def __init__(self, attributes, axis=1, impute=False, callback=None):
        super().__init__(axis, impute, callback)
        self.attributes = attributes
        self.discrete = None
        self.continuous = None
        self.normalize = False

    def __call__(self, e1, e2=None):
        if self.attributes is not None and (
                e1.domain.attributes != self.attributes
                or e2 is not None and e2.domain.attributes != self.attributes):
            raise ValueError("mismatching domains")
        return super().__call__(e1, e2)

    def continuous_columns(self, x1, x2, offset, scale):
        """
        Extract and scale continuous columns from data tables.
        If the second table is None, it defaults to the first table.

        Values are scaled if `self.normalize` is `True`.

        Args:
            x1 (np.ndarray): first table
            x2 (np.ndarray or None): second table
            offset (float): a constant (e.g. mean, median) subtracted from data
            scale: (float): divider (e.g. deviation)

        Returns:
            data1 (np.ndarray): scaled continuous columns from `x1`
            data2 (np.ndarray): scaled continuous columns from `x2` or `x1`
        """
        if self.continuous.all() and not self.normalize:
            data1, data2 = x1, x2
        else:
            data1 = x1[:, self.continuous]
            if x2 is not None:
                data2 = x2[:, self.continuous]
            if self.normalize:
                data1 = x1[:, self.continuous]
                data1 -= offset
                data1 /= scale
                if x2 is not None:
                    data2 = x2[:, self.continuous]
                    data2 -= offset
                    data2 /= scale
        if x2 is None:
            data2 = data1
        return data1, data2

    def discrete_columns(self, x1, x2):
        """
        Return discrete columns from the given tables.
        If the second table is None, it defaults to the first table.
        """
        if self.discrete.all():
            data1, data2 = x1, x1 if x2 is None else x2
        else:
            data1 = x1[:, self.discrete]
            data2 = data1 if x2 is None else x2[:, self.discrete]
        return data1, data2


class FittedDistance(Distance):
    """
    Base class for fitting models that store attribute-related data for
    normalization and imputation, and that treat discrete and continuous
    columns separately.

    The class implements a method `fit` that calls either `fit_columns`
    or `fit_rows` with the data and the number of values for discrete
    attributes. The provided method `fit_rows` calls methods
    `get_discrete_stats` and `get_continuous_stats` that can be implemented
    in derived classes.

    Class attribute `rows_model_type` contains the type of the model returned by
    `fit_rows`.
    """
    rows_model_type = None  #: Option[FittedDistanceModel]

    def fit(self, data):
        """
        Prepare the data on attributes, call `fit_cols` or `fit_rows` and
        return the resulting model.
        """
        x = _orange_to_numpy(data)
        if hasattr(data, "domain"):
            attributes = data.domain.attributes
            n_vals = np.fromiter(
                (len(attr.values) if attr.is_discrete else 0
                 for attr in attributes),
                dtype=np.int32, count=len(attributes))
        else:
            assert isinstance(x, np.ndarray)
            attributes = None
            n_vals = np.zeros(x.shape[1], dtype=np.int32)
        return [self.fit_cols, self.fit_rows][self.axis](attributes, x, n_vals)

    def fit_cols(self, attributes, x, n_vals):
        """
        Return DistanceModel for computation of distances between columns.
        Derived classes must define this method.

        Args:
            attributes (list of Orange.data.Variable): list of attributes
            x (np.ndarray): data
            n_vals (np.ndarray): number of attribute values, 0 for continuous
        """
        raise NotImplementedError

    def fit_rows(self, attributes, x, n_vals):
        """
        Return a DistanceModel for computation of distances between rows.

        The model type is `self.row_distance_model`. It stores the data for
        imputation of discrete and continuous values, and for normalization
        of continuous values. Typical examples are the Euclidean and Manhattan
        distance, for which the following data is stored:

        For continuous columns:

        - offsets[col] is the number subtracted from values in column `col`
        - scales[col] is the divisor for values in columns `col`
        - dist_missing2_cont[col]: the value used for distance between two
            missing values in column `col`

        For discrete values:

        - dist_missing_disc[col, value] is the distance added for the given
            `value` in the column `col` if the value for the other row is
            missing
        - dist_missing2_disc[col]: the distance between two missing values in
            column `col`
        """
        n_cols = len(n_vals)

        discrete = n_vals > 0
        n_bins = max(n_vals, default=0)
        n_discrete = sum(discrete)
        dist_missing_disc = np.zeros((n_discrete, n_bins), dtype=float)
        dist_missing2_disc = np.zeros(n_discrete, dtype=float)

        continuous = ~discrete
        n_continuous = sum(continuous)
        offsets = np.zeros(n_continuous, dtype=float)
        scales = np.empty(n_continuous, dtype=float)
        dist_missing2_cont = np.zeros(n_continuous, dtype=float)

        curr_disc = curr_cont = 0
        for col in range(n_cols):
            column = x[:, col]
            if np.isnan(column).all():
                continuous[col] = discrete[col] = False
            elif discrete[col]:
                discrete_stats = self.get_discrete_stats(column, n_bins)
                if discrete_stats is not None:
                    dist_missing_disc[curr_disc], \
                    dist_missing2_disc[curr_disc] = discrete_stats
                    curr_disc += 1
            else:
                continuous_stats = self.get_continuous_stats(column)
                if continuous_stats is not None:
                    offsets[curr_cont], scales[curr_cont],\
                    dist_missing2_cont[curr_cont] = continuous_stats
                    curr_cont += 1
                else:
                    continuous[col] = False
        # pylint: disable=not-callable
        return self.rows_model_type(
            attributes, impute, getattr(self, "normalize", False),
            continuous, discrete,
            offsets[:curr_cont], scales[:curr_cont],
            dist_missing2_cont[:curr_cont],
            dist_missing_disc, dist_missing2_disc,
            self.callback)

    @staticmethod
    def get_discrete_stats(column, n_bins):
        """
        Return tables used computing distance between missing discrete values.

        Args:
            column (np.ndarray): column data
            n_bins (int): maximal number of bins in the dataset

        Returns:
            dist_missing_disc (np.ndarray): `dist_missing_disc[value]` is
                1 - probability of `value`, which is used as the distance added
                for the given `value` in the column `col` if the value for the
                other row is missing
            dist_missing2_disc (float): the distance between two missing
                values in this columns
        """
        dist = util.bincount(column, minlength=n_bins)[0]
        dist /= max(1, sum(dist))
        return 1 - dist, 1 - np.sum(dist ** 2)

    def get_continuous_stats(self, column):
        """
        Compute statistics for imputation and normalization of continuous data.
        Derived classes must define this method.

        Args:
            column (np.ndarray): column data

        Returns:
            offset (float): the number subtracted from values in column
            scales (float): the divisor for values in column
            dist_missing2_cont (float): the value used for distance between two
                missing values in column
        """
        raise NotImplementedError


# Fallbacks for distances in sparse data
# To be removed as the corresponding functionality is implemented properly

class SklDistance:
    """
    Wrapper for functions sklearn's metrics. Used only as temporary fallbacks
    when `Euclidean`, `Manhattan`, `Cosine` or `Jaccard` are given sparse data
    or raw numpy arrays. These classes can't handle discrete or missing data
    and normalization. Do not use for wrapping new classes.
    """
    def __init__(self, metric):
        self.metric = metric

    def __call__(self, e1, e2=None, axis=1, impute=False):
        x1 = _orange_to_numpy(e1)
        x2 = _orange_to_numpy(e2)
        if axis == 0:
            x1 = x1.T
            if x2 is not None:
                x2 = x2.T
        dist = skl_metrics.pairwise.pairwise_distances(
            x1, x2, metric=self.metric)
        if impute and np.isnan(dist).any():
            dist = np.nan_to_num(dist)
        if isinstance(e1, (Table, RowInstance)):
            dist_matrix = DistMatrix(dist, e1, e2, axis)
        else:
            dist_matrix = DistMatrix(dist)
        return dist_matrix


### Orange/widgets/unsupervised/owdistances.py
from scipy.sparse import issparse
import bottleneck as bn

from AnyQt.QtCore import Qt

import Orange.data
import Orange.misc
from Orange import distance
from Orange.widgets import gui
from Orange.widgets.settings import Setting
from Orange.widgets.utils.concurrent import TaskState, ConcurrentWidgetMixin
from Orange.widgets.utils.sql import check_sql_input
from Orange.widgets.utils.widgetpreview import WidgetPreview
from Orange.widgets.widget import OWWidget, Msg, Input, Output


METRICS = [
    ("Euclidean", distance.Euclidean),
    ("Manhattan", distance.Manhattan),
    ("Cosine", distance.Cosine),
    ("Jaccard", distance.Jaccard),
    ("Spearman", distance.SpearmanR),
    ("Absolute Spearman", distance.SpearmanRAbsolute),
    ("Pearson", distance.PearsonR),
    ("Absolute Pearson", distance.PearsonRAbsolute),
    ("Hamming", distance.Hamming),
    ("Mahalanobis", distance.Mahalanobis),
    ('Bhattacharyya', distance.Bhattacharyya)
]


class InterruptException(Exception):
    pass


class DistanceRunner:
    @staticmethod
    def run(data: Orange.data.Table, metric: distance, normalized_dist: bool,
            axis: int, state: TaskState) -> Orange.misc.DistMatrix:
        if data is None:
            return None

        def callback(i: float) -> bool:
            state.set_progress_value(i)
            if state.is_interruption_requested():
                raise InterruptException

        state.set_status("Calculating...")
        kwargs = {"axis": 1 - axis, "impute": True, "callback": callback}
        if metric.supports_normalization and normalized_dist:
            kwargs["normalize"] = True
        return metric(data, **kwargs)


class OWDistances(OWWidget, ConcurrentWidgetMixin):
    name = "Distances"
    description = "Compute a matrix of pairwise distances."
    icon = "icons/Distance.svg"
    keywords = []

    class Inputs:
        data = Input("Data", Orange.data.Table)

    class Outputs:
        distances = Output("Distances", Orange.misc.DistMatrix, dynamic=False)

    settings_version = 3

    axis = Setting(0)        # type: int
    metric_idx = Setting(0)  # type: int

    #: Use normalized distances if the metric supports it.
    #: The default is `True`, expect when restoring from old pre v2 settings
    #: (see `migrate_settings`).
    normalized_dist = Setting(True)  # type: bool
    autocommit = Setting(True)       # type: bool

    want_main_area = False
    resizing_enabled = False

    class Error(OWWidget.Error):
        no_continuous_features = Msg("No numeric features")
        no_binary_features = Msg("No binary features")
        dense_metric_sparse_data = Msg("{} requires dense data.")
        distances_memory_error = Msg("Not enough memory")
        distances_value_error = Msg("Problem in calculation:\n{}")
        data_too_large_for_mahalanobis = Msg(
            "Mahalanobis handles up to 1000 {}.")

    class Warning(OWWidget.Warning):
        ignoring_discrete = Msg("Ignoring categorical features")
        ignoring_nonbinary = Msg("Ignoring non-binary features")
        imputing_data = Msg("Missing values were imputed")

    def __init__(self):
        OWWidget.__init__(self)
        ConcurrentWidgetMixin.__init__(self)

        self.data = None

        gui.radioButtons(
            self.controlArea, self, "axis", ["Rows", "Columns"],
            box="Distances between", callback=self._invalidate
        )
        box = gui.widgetBox(self.controlArea, "Distance Metric")
        self.metrics_combo = gui.comboBox(
            box, self, "metric_idx",
            items=[m[0] for m in METRICS],
            callback=self._metric_changed
        )
        self.normalization_check = gui.checkBox(
            box, self, "normalized_dist", "Normalized",
            callback=self._invalidate,
            tooltip=("All dimensions are (implicitly) scaled to a common"
                     "scale to normalize the influence across the domain."),
            stateWhenDisabled=False, attribute=Qt.WA_LayoutUsesWidgetRect
        )
        _, metric = METRICS[self.metric_idx]
        self.normalization_check.setEnabled(metric.supports_normalization)

        gui.auto_apply(self.buttonsArea, self, "autocommit")

    @Inputs.data
    @check_sql_input
    def set_data(self, data):
        self.cancel()
        self.data = data
        self.refresh_metrics()
        self.unconditional_commit()

    def refresh_metrics(self):
        sparse = self.data is not None and issparse(self.data.X)
        for i, metric in enumerate(METRICS):
            item = self.metrics_combo.model().item(i)
            item.setEnabled(not sparse or metric[1].supports_sparse)

    def commit(self):
        # pylint: disable=invalid-sequence-index
        metric = METRICS[self.metric_idx][1]
        self.compute_distances(metric, self.data)

    def compute_distances(self, metric, data):
        def _check_sparse():
            # pylint: disable=invalid-sequence-index
            if issparse(data.X) and not metric.supports_sparse:
                self.Error.dense_metric_sparse_data(METRICS[self.metric_idx][0])
                return False
            return True

        def _fix_discrete():
            nonlocal data
            if data.domain.has_discrete_attributes() \
                    and metric is not distance.Jaccard \
                    and (issparse(data.X) and getattr(metric, "fallback", None)
                         or not metric.supports_discrete
                         or self.axis == 1):
                if not data.domain.has_continuous_attributes():
                    self.Error.no_continuous_features()
                    return False
                self.Warning.ignoring_discrete()
                data = distance.remove_discrete_features(data)
            return True

        def _fix_nonbinary():
            nonlocal data
            if metric is distance.Jaccard and not issparse(data.X):
                nbinary = sum(a.is_discrete and len(a.values) == 2
                              for a in data.domain.attributes)
                if not nbinary:
                    self.Error.no_binary_features()
                    return False
                elif nbinary < len(data.domain.attributes):
                    self.Warning.ignoring_nonbinary()
                    data = distance.remove_nonbinary_features(data)
            return True

        def _fix_missing():
            nonlocal data
            if not metric.supports_missing and bn.anynan(data.X):
                self.Warning.imputing_data()
                data = distance.impute(data)
            return True

        def _check_tractability():
            if metric is distance.Mahalanobis:
                if self.axis == 1:
                    # when computing distances by columns, we want < 100 rows
                    if len(data) > 1000:
                        self.Error.data_too_large_for_mahalanobis("rows")
                        return False
                else:
                    if len(data.domain.attributes) > 1000:
                        self.Error.data_too_large_for_mahalanobis("columns")
                        return False
            return True

        self.clear_messages()
        if data is not None:
            for check in (_check_sparse, _check_tractability,
                          _fix_discrete, _fix_missing, _fix_nonbinary):
                if not check():
                    data = None
                    break

        self.start(DistanceRunner.run, data, metric,
                   self.normalized_dist, self.axis)

    def on_partial_result(self, _):
        pass

    def on_done(self, result: Orange.misc.DistMatrix):
        assert isinstance(result, Orange.misc.DistMatrix) or result is None
        self.Outputs.distances.send(result)

    def on_exception(self, ex):
        if isinstance(ex, ValueError):
            self.Error.distances_value_error(ex)
        elif isinstance(ex, MemoryError):
            self.Error.distances_memory_error()
        elif isinstance(ex, InterruptException):
            pass
        else:
            raise ex

    def onDeleteWidget(self):
        self.shutdown()
        super().onDeleteWidget()

    def _invalidate(self):
        self.commit()

    def _metric_changed(self):
        metric = METRICS[self.metric_idx][1]
        self.normalization_check.setEnabled(metric.supports_normalization)
        self._invalidate()

    def send_report(self):
        # pylint: disable=invalid-sequence-index
        self.report_items((
            ("Distances Between", ["Rows", "Columns"][self.axis]),
            ("Metric", METRICS[self.metric_idx][0])
        ))

    @classmethod
    def migrate_settings(cls, settings, version):
        if version is None or version < 2 and "normalized_dist" not in settings:
            # normalize_dist is set to False when restoring settings from
            # an older version to preserve old semantics.
            settings["normalized_dist"] = False
        if version is None or version < 3:
            # Mahalanobis was moved from idx = 2 to idx = 9
            metric_idx = settings["metric_idx"]
            if metric_idx == 2:
                settings["metric_idx"] = 9
            elif 2 < metric_idx <= 9:
                settings["metric_idx"] -= 1


if __name__ == "__main__":  # pragma: no cover
    WidgetPreview(OWDistances).run(Orange.data.Table("iris"))

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