{
    "file_diffs": [
        {
            "old_file_content": "\"\"\"Widget Settings and Settings Handlers\n\nSettings are used to declare widget attributes that persist through sessions.\nWhen widget is removed or saved to a schema file, its settings are packed,\nserialized and stored. When a new widget is created, values of attributes\nmarked as settings are read from disk. When schema is loaded, attribute values\nare set to one stored in schema.\n\nEach widget has its own SettingsHandler that takes care of serializing and\nstoring of settings and SettingProvider that is incharge of reading and\nwriting the setting values.\n\nAll widgets extending from OWWidget use SettingsHandler, unless they\ndeclare otherwise. SettingsHandler ensures that setting attributes\nare replaced with default (last used) setting values when the widget is\ninitialized and stored when the widget is removed.\n\nWidgets with settings whose values depend on the widget inputs use\nsettings handlers based on ContextHandler. These handlers have two\nadditional methods, open_context and close_context.\n\nopen_context is called when widgets receives new data. It finds a suitable\ncontext and sets the widget attributes to the values stored in context.\nIf no suitable context exists, a new one is created and values from widget\nare copied to it.\n\nclose_context stores values that were last used on the widget to the context\nso they can be used alter. It should be called before widget starts modifying\n(initializing) the value of the setting attributes.\n\"\"\"\n\nimport sys\nimport copy\nimport itertools\nimport os\nimport logging\nimport pickle\nimport pprint\nimport time\nimport warnings\nfrom operator import itemgetter\nfrom typing import Any\n\nfrom Orange.data import Domain, Variable\nfrom Orange.misc.environ import widget_settings_dir\nfrom Orange.util import OrangeDeprecationWarning\nfrom Orange.widgets.utils import vartype\nfrom Orange.widgets.gui import OWComponent\n\nlog = logging.getLogger(__name__)\n\n__all__ = [\"Setting\", \"SettingsHandler\", \"SettingProvider\",\n           \"ContextSetting\", \"ContextHandler\",\n           \"DomainContextHandler\", \"PerfectDomainContextHandler\",\n           \"ClassValuesContextHandler\", \"widget_settings_dir\",\n           \"IncompatibleContext\"]\n\n_IMMUTABLES = (str, int, bytes, bool, float, tuple)\n\nVERSION_KEY = \"__version__\"\n\n\nclass Setting:\n    \"\"\"Description of a setting.\n    \"\"\"\n\n    # Settings are automatically persisted to disk\n    packable = True\n\n    # Setting is only persisted to schema (default value does not change)\n    schema_only = False\n\n    def __new__(cls, default, *args, **kwargs):\n        \"\"\"A misleading docstring for providing type hints for Settings\n\n        :type: default: T\n        :rtype: T\n        \"\"\"\n        return super().__new__(cls)\n\n    def __init__(self, default, **data):\n        self.name = None  # Name gets set in widget's meta class\n        self.default = default\n        self.__dict__.update(data)\n\n    def __str__(self):\n        return '{0} \"{1}\"'.format(self.__class__.__name__, self.name)\n\n    __repr__ = __str__\n\n    def __getnewargs__(self):\n        return (self.default, )\n\n\n# Pylint ignores type annotations in assignments. For\n#\n#    x: int = Setting(0)\n#\n# it ignores `int` and assumes x is of type `Setting`. Annotations in\n# comments ( # type: int) also don't work. The only way to annotate x is\n#\n#    x: int\n#    x = Setting(0)\n#\n# but we don't want to clutter the code with extra lines of annotations. Hence\n# we disable checking the type of `Setting` by confusing pylint with an extra\n# definition that is never executed.\nif 1 == 0:\n    class Setting:  # pylint: disable=function-redefined\n        pass\n\n\ndef _apply_setting(setting: Setting, instance: OWComponent, value: Any):\n    \"\"\"\n    Set `setting` of widget `instance` to the given `value`, in place if\n    possible.\n\n    If old and new values are of the same type, and the type is either a list\n    or has methods `clear` and `update`, setting is updated in place. Otherwise\n    the function calls `setattr`.\n    \"\"\"\n    target = getattr(instance, setting.name, None)\n    if type(target) is type(value):\n        if isinstance(value, list):\n            target[:] = value\n            return\n        elif hasattr(value, \"clear\") and hasattr(value, \"update\"):\n            target.clear()\n            target.update(value)\n            return\n    setattr(instance, setting.name, value)\n\n\nclass SettingProvider:\n    \"\"\"A hierarchical structure keeping track of settings belonging to\n    a class and child setting providers.\n\n    At instantiation, it creates a dict of all Setting and SettingProvider\n    members of the class. This dict is used to get/set values of settings\n    from/to the instances of the class this provider belongs to.\n    \"\"\"\n\n    def __init__(self, provider_class):\n        \"\"\" Construct a new instance of SettingProvider.\n\n        Traverse provider_class members and store all instances of\n        Setting and SettingProvider.\n\n        Parameters\n        ----------\n        provider_class : class\n            class containing settings definitions\n        \"\"\"\n        self.name = \"\"\n        self.provider_class = provider_class\n        self.providers = {}\n        \"\"\":type: dict[str, SettingProvider]\"\"\"\n        self.settings = {}\n        \"\"\":type: dict[str, Setting]\"\"\"\n        self.initialization_data = None\n\n        for name in dir(provider_class):\n            value = getattr(provider_class, name, None)\n            if isinstance(value, Setting):\n                value = copy.deepcopy(value)\n                value.name = name\n                self.settings[name] = value\n            if isinstance(value, SettingProvider):\n                value = copy.deepcopy(value)\n                value.name = name\n                self.providers[name] = value\n\n    def initialize(self, instance, data=None):\n        \"\"\"Initialize instance settings to their default values.\n\n        Mutable values are (shallow) copied before they are assigned to the\n        widget. Immutable are used as-is.\n\n        Parameters\n        ----------\n        instance : OWWidget\n            widget instance to initialize\n        data : Optional[dict]\n            optional data used to override the defaults\n            (used when settings are loaded from schema)\n        \"\"\"\n        if data is None and self.initialization_data is not None:\n            data = self.initialization_data\n\n        self._initialize_settings(instance, data)\n        self._initialize_providers(instance, data)\n\n    def _initialize_settings(self, instance, data):\n        if data is None:\n            data = {}\n        for name, setting in self.settings.items():\n            value = data.get(name, setting.default)\n            if isinstance(value, _IMMUTABLES):\n                setattr(instance, name, value)\n            else:\n                setattr(instance, name, copy.copy(value))\n\n    def _initialize_providers(self, instance, data):\n        if not data:\n            return\n\n        for name, provider in self.providers.items():\n            if name not in data:\n                continue\n\n            member = getattr(instance, name, None)\n            if member is None or isinstance(member, SettingProvider):\n                provider.store_initialization_data(data[name])\n            else:\n                provider.initialize(member, data[name])\n\n    def store_initialization_data(self, initialization_data):\n        \"\"\"Store initialization data for later use.\n\n        Used when settings handler is initialized, but member for this\n        provider does not exists yet (because handler.initialize is called in\n        __new__, but member will be created in __init__.\n\n        Parameters\n        ----------\n        initialization_data : dict\n            data to be used for initialization when the component is created\n        \"\"\"\n        self.initialization_data = initialization_data\n\n    @staticmethod\n    def _default_packer(setting, instance):\n        \"\"\"A simple packet that yields setting name and value.\n\n        Parameters\n        ----------\n        setting : Setting\n        instance : OWWidget\n        \"\"\"\n        if setting.packable:\n            if hasattr(instance, setting.name):\n                yield setting.name, getattr(instance, setting.name)\n            else:\n                warnings.warn(\"{0} is declared as setting on {1} \"\n                              \"but not present on instance.\"\n                              .format(setting.name, instance))\n\n    def pack(self, instance, packer=None):\n        \"\"\"Pack instance settings in a name:value dict.\n\n        Parameters\n        ----------\n        instance : OWWidget\n            widget instance\n        packer: callable (Setting, OWWidget) -> Generator[(str, object)]\n            optional packing function\n            it will be called with setting and instance parameters and\n            should yield (name, value) pairs that will be added to the\n            packed_settings.\n        \"\"\"\n        if packer is None:\n            packer = self._default_packer\n\n        packed_settings = dict(itertools.chain(\n            *(packer(setting, instance) for setting in self.settings.values())\n        ))\n\n        packed_settings.update({\n            name: provider.pack(getattr(instance, name), packer)\n            for name, provider in self.providers.items()\n            if hasattr(instance, name)\n        })\n        return packed_settings\n\n    def unpack(self, instance, data):\n        \"\"\"Restore settings from data to the instance.\n\n        Parameters\n        ----------\n        instance : OWWidget\n            instance to restore settings to\n        data : dict\n            packed data\n        \"\"\"\n        for setting, _data, inst in self.traverse_settings(data, instance):\n            if setting.name in _data and inst is not None:\n                _apply_setting(setting, inst, _data[setting.name])\n\n    def get_provider(self, provider_class):\n        \"\"\"Return provider for provider_class.\n\n        If this provider matches, return it, otherwise pass\n        the call to child providers.\n\n        Parameters\n        ----------\n        provider_class : class\n        \"\"\"\n        if issubclass(provider_class, self.provider_class):\n            return self\n\n        for subprovider in self.providers.values():\n            provider = subprovider.get_provider(provider_class)\n            if provider:\n                return provider\n        return None\n\n    def traverse_settings(self, data=None, instance=None):\n        \"\"\"Generator of tuples (setting, data, instance) for each setting\n        in this and child providers..\n\n        Parameters\n        ----------\n        data : dict\n            dictionary with setting values\n        instance : OWWidget\n            instance matching setting_provider\n        \"\"\"\n        data = data if data is not None else {}\n\n        for setting in self.settings.values():\n            yield setting, data, instance\n\n        for provider in self.providers.values():\n            data_ = data.get(provider.name, {})\n            instance_ = getattr(instance, provider.name, None)\n            for setting, component_data, component_instance in \\\n                    provider.traverse_settings(data_, instance_):\n                yield setting, component_data, component_instance\n\n\nclass SettingsHandler:\n    \"\"\"Reads widget setting files and passes them to appropriate providers.\"\"\"\n\n    def __init__(self):\n        \"\"\"Create a setting handler template.\n\n        Used in class definition. Bound instance will be created\n        when SettingsHandler.create is called.\n        \"\"\"\n        self.widget_class = None\n        self.provider = None\n        \"\"\":type: SettingProvider\"\"\"\n        self.defaults = {}\n        self.known_settings = {}\n\n    @staticmethod\n    def create(widget_class, template=None):\n        \"\"\"Create a new settings handler based on the template and bind it to\n        widget_class.\n\n        Parameters\n        ----------\n        widget_class : class\n        template : SettingsHandler\n            SettingsHandler to copy setup from\n\n        Returns\n        -------\n        SettingsHandler\n        \"\"\"\n\n        if template is None:\n            template = SettingsHandler()\n\n        setting_handler = copy.copy(template)\n        setting_handler.defaults = {}\n        setting_handler.bind(widget_class)\n        return setting_handler\n\n    def bind(self, widget_class):\n        \"\"\"Bind settings handler instance to widget_class.\n\n        Parameters\n        ----------\n        widget_class : class\n        \"\"\"\n        self.widget_class = widget_class\n        self.provider = SettingProvider(widget_class)\n        self.known_settings = {}\n        self.analyze_settings(self.provider, \"\")\n        self.read_defaults()\n\n    def analyze_settings(self, provider, prefix):\n        \"\"\"Traverse through all settings known to the provider\n        and analyze each of them.\n\n        Parameters\n        ----------\n        provider : SettingProvider\n        prefix : str\n            prefix the provider is registered to handle\n        \"\"\"\n        for setting in provider.settings.values():\n            self.analyze_setting(prefix, setting)\n\n        for name, sub_provider in provider.providers.items():\n            new_prefix = '{0}{1}.'.format(prefix or '', name)\n            self.analyze_settings(sub_provider, new_prefix)\n\n    def analyze_setting(self, prefix, setting):\n        \"\"\"Perform any initialization task related to setting.\n\n        Parameters\n        ----------\n        prefix : str\n        setting : Setting\n        \"\"\"\n        self.known_settings[prefix + setting.name] = setting\n\n    def read_defaults(self):\n        \"\"\"Read (global) defaults for this widget class from a file.\n        Opens a file and calls :obj:`read_defaults_file`. Derived classes\n        should overload the latter.\"\"\"\n        filename = self._get_settings_filename()\n        if os.path.isfile(filename):\n            settings_file = open(filename, \"rb\")\n            try:\n                self.read_defaults_file(settings_file)\n            # Unpickling exceptions can be of any type\n            # pylint: disable=broad-except\n            except Exception as ex:\n                warnings.warn(\"Could not read defaults for widget {0}\\n\"\n                              \"The following error occurred:\\n\\n{1}\"\n                              .format(self.widget_class, ex))\n            finally:\n                settings_file.close()\n\n    def read_defaults_file(self, settings_file):\n        \"\"\"Read (global) defaults for this widget class from a file.\n\n        Parameters\n        ----------\n        settings_file : file-like object\n        \"\"\"\n        defaults = pickle.load(settings_file)\n        self.defaults = {\n            key: value\n            for key, value in defaults.items()\n            if not isinstance(value, Setting)\n        }\n        self._migrate_settings(self.defaults)\n\n    def write_defaults(self):\n        \"\"\"Write (global) defaults for this widget class to a file.\n        Opens a file and calls :obj:`write_defaults_file`. Derived classes\n        should overload the latter.\"\"\"\n        filename = self._get_settings_filename()\n        os.makedirs(os.path.dirname(filename), exist_ok=True)\n        try:\n            settings_file = open(filename, \"wb\")\n            try:\n                self.write_defaults_file(settings_file)\n            except (EOFError, IOError, pickle.PicklingError) as ex:\n                log.error(\"Could not write default settings for %s (%s).\",\n                          self.widget_class, type(ex).__name__)\n                settings_file.close()\n                os.remove(filename)\n            else:\n                settings_file.close()\n        except PermissionError as ex:\n            log.error(\"Could not write default settings for %s (%s).\",\n                      self.widget_class, type(ex).__name__)\n\n    def write_defaults_file(self, settings_file):\n        \"\"\"Write defaults for this widget class to a file\n\n        Parameters\n        ----------\n        settings_file : file-like object\n        \"\"\"\n        defaults = dict(self.defaults)\n        defaults[VERSION_KEY] = self.widget_class.settings_version\n        pickle.dump(defaults, settings_file, -1)\n\n    def _get_settings_filename(self):\n        \"\"\"Return the name of the file with default settings for the widget\"\"\"\n        return os.path.join(widget_settings_dir(),\n                            \"{0.__module__}.{0.__qualname__}.pickle\"\n                            .format(self.widget_class))\n\n    def initialize(self, instance, data=None):\n        \"\"\"\n        Initialize widget's settings.\n\n        Replace all instance settings with their default values.\n\n        Parameters\n        ----------\n        instance : OWWidget\n        data : dict or bytes that unpickle into a dict\n            values used to override the defaults\n        \"\"\"\n        provider = self._select_provider(instance)\n\n        if isinstance(data, bytes):\n            data = pickle.loads(data)\n        self._migrate_settings(data)\n\n        if provider is self.provider:\n            data = self._add_defaults(data)\n\n        provider.initialize(instance, data)\n\n    def _migrate_settings(self, settings):\n        \"\"\"Ask widget to migrate settings to the latest version.\"\"\"\n        if settings:\n            try:\n                self.widget_class.migrate_settings(\n                    settings, settings.pop(VERSION_KEY, 0))\n            except Exception:  # pylint: disable=broad-except\n                sys.excepthook(*sys.exc_info())\n                settings.clear()\n\n    def _select_provider(self, instance):\n        provider = self.provider.get_provider(instance.__class__)\n        if provider is None:\n            message = \"{0} has not been declared as setting provider in {1}. \" \\\n                      \"Settings will not be saved/loaded properly. Defaults will be used instead.\" \\\n                      .format(instance.__class__, self.widget_class)\n            warnings.warn(message)\n            provider = SettingProvider(instance.__class__)\n        return provider\n\n    def _add_defaults(self, data):\n        if data is None:\n            return self.defaults\n\n        new_data = self.defaults.copy()\n        new_data.update(data)\n        return new_data\n\n    def _prepare_defaults(self, widget):\n        self.defaults = self.provider.pack(widget)\n        for setting, data, _ in self.provider.traverse_settings(data=self.defaults):\n            if setting.schema_only:\n                data.pop(setting.name, None)\n\n    def pack_data(self, widget):\n        \"\"\"\n        Pack the settings for the given widget. This method is used when\n        saving schema, so that when the schema is reloaded the widget is\n        initialized with its proper data and not the class-based defaults.\n        See :obj:`SettingsHandler.initialize` for detailed explanation of its\n        use.\n\n        Inherited classes add other data, in particular widget-specific\n        local contexts.\n\n        Parameters\n        ----------\n        widget : OWWidget\n        \"\"\"\n        widget.settingsAboutToBePacked.emit()\n        packed_settings = self.provider.pack(widget)\n        packed_settings[VERSION_KEY] = self.widget_class.settings_version\n        return packed_settings\n\n    def update_defaults(self, widget):\n        \"\"\"\n        Writes widget instance's settings to class defaults. Called when the\n        widget is deleted.\n\n        Parameters\n        ----------\n        widget : OWWidget\n        \"\"\"\n        widget.settingsAboutToBePacked.emit()\n        self._prepare_defaults(widget)\n        self.write_defaults()\n\n    def fast_save(self, widget, name, value):\n        \"\"\"Store the (changed) widget's setting immediately to the context.\n\n        Parameters\n        ----------\n        widget : OWWidget\n        name : str\n        value : object\n\n        \"\"\"\n        if name in self.known_settings:\n            setting = self.known_settings[name]\n            if not setting.schema_only:\n                setting.default = value\n\n    def reset_settings(self, instance):\n        \"\"\"Reset widget settings to defaults\n\n        Parameters\n        ----------\n        instance : OWWidget\n        \"\"\"\n        for setting, _, inst in self.provider.traverse_settings(instance=instance):\n            if setting.packable:\n                _apply_setting(setting, inst, setting.default)\n\n\nclass ContextSetting(Setting):\n    \"\"\"Description of a context dependent setting\"\"\"\n\n    OPTIONAL = 0\n    REQUIRED = 2\n\n    # Context settings are not persisted, but are stored in context instead.\n    packable = False\n\n    # These flags are not general - they assume that the setting has to do\n    # something with the attributes. Large majority does, so this greatly\n    # simplifies the declaration of settings in widget at no (visible)\n    # cost to those settings that don't need it\n    def __init__(self, default, *, required=2,\n                 exclude_attributes=False, exclude_metas=False, **data):\n        super().__init__(default, **data)\n        self.exclude_attributes = exclude_attributes\n        self.exclude_metas = exclude_metas\n        self.required = required\n\n\nclass Context:\n    \"\"\"Class for data thad defines context and\n    values that should be applied to widget if given context\n    is encountered.\"\"\"\n    def __init__(self, **argkw):\n        self.time = time.time()\n        self.values = {}\n        self.__dict__.update(argkw)\n\n    def __getstate__(self):\n        state = dict(self.__dict__)\n        for nc in getattr(self, \"no_copy\", []):\n            if nc in state:\n                del state[nc]\n        return state\n\n\nclass ContextHandler(SettingsHandler):\n    \"\"\"Base class for setting handlers that can handle contexts.\n\n    Classes deriving from it need to implement method `match`.\n    \"\"\"\n\n    NO_MATCH = 0\n    PERFECT_MATCH = 2\n\n    MAX_SAVED_CONTEXTS = 50\n\n    def __init__(self):\n        super().__init__()\n        self.global_contexts = []\n        self.known_settings = {}\n\n    def initialize(self, instance, data=None):\n        \"\"\"Initialize the widget: call the inherited initialization and\n        add an attribute 'context_settings' to the widget. This method\n        does not open a context.\"\"\"\n        instance.current_context = None\n        super().initialize(instance, data)\n        if data and \"context_settings\" in data:\n            instance.context_settings = data[\"context_settings\"]\n            self._migrate_contexts(instance.context_settings)\n        else:\n            instance.context_settings = []\n\n    def read_defaults_file(self, settings_file):\n        \"\"\"Call the inherited method, then read global context from the\n           pickle.\"\"\"\n        super().read_defaults_file(settings_file)\n        self.global_contexts = pickle.load(settings_file)\n        self._migrate_contexts(self.global_contexts)\n\n    def _migrate_contexts(self, contexts):\n        i = 0\n        while i < len(contexts):\n            context = contexts[i]\n            try:\n                self.widget_class.migrate_context(\n                    context, context.values.pop(VERSION_KEY, 0))\n            except IncompatibleContext:\n                del contexts[i]\n            except Exception:  # pylint: disable=broad-except\n                sys.excepthook(*sys.exc_info())\n                del contexts[i]\n            else:\n                i += 1\n\n    def write_defaults_file(self, settings_file):\n        \"\"\"Call the inherited method, then add global context to the pickle.\"\"\"\n        super().write_defaults_file(settings_file)\n\n        def add_version(context):\n            context = copy.copy(context)\n            context.values = dict(context.values)\n            context.values[VERSION_KEY] = self.widget_class.settings_version\n            return context\n\n        pickle.dump([add_version(context) for context in self.global_contexts],\n                    settings_file, -1)\n\n    def pack_data(self, widget):\n        \"\"\"Call the inherited method, then add local contexts to the dict.\"\"\"\n        data = super().pack_data(widget)\n        self.settings_from_widget(widget)\n        context_settings = [copy.copy(context) for context in\n                            widget.context_settings]\n        for context in context_settings:\n            context.values[VERSION_KEY] = self.widget_class.settings_version\n        data[\"context_settings\"] = context_settings\n        return data\n\n    def update_defaults(self, widget):\n        \"\"\"\n        Reimplemented from SettingsHandler\n\n        Merge the widgets local contexts into the global contexts and persist\n        the settings (including the contexts) to disk.\n        \"\"\"\n        widget.settingsAboutToBePacked.emit()\n        self.settings_from_widget(widget)\n        globs = self.global_contexts\n        assert widget.context_settings is not globs\n        ids = {id(c) for c in globs}\n        globs += (c for c in widget.context_settings if id(c) not in ids)\n        globs.sort(key=lambda c: -c.time)\n        del globs[self.MAX_SAVED_CONTEXTS:]\n\n        # Save non-context settings. Do not call super().update_defaults, so that\n        # settingsAboutToBePacked is emitted once.\n        self._prepare_defaults(widget)\n        self.write_defaults()\n\n    def new_context(self, *args):\n        \"\"\"Create a new context.\"\"\"\n        return Context()\n\n    def open_context(self, widget, *args):\n        \"\"\"Open a context by finding one and setting the widget data or\n        creating one and fill with the data from the widget.\"\"\"\n        widget.current_context, is_new = \\\n            self.find_or_create_context(widget, *args)\n        if is_new:\n            try:\n                self.settings_from_widget(widget, *args)\n            except TypeError:\n                warnings.warn(\"settings_from_widget in {} does not accept *args.\\n\"\n                              \"Support for this will be dropped in Orange 3.10\"\n                              .format(type(self)),\n                              DeprecationWarning)\n                self.settings_from_widget(widget)\n        else:\n            try:\n                self.settings_to_widget(widget, *args)\n            except TypeError:\n                warnings.warn(\"settings_to_widget {} does not accept *args.\\n\"\n                              \"Support for this will be dropped in Orange 3.10\"\n                              .format(type(self)),\n                              DeprecationWarning)\n                self.settings_to_widget(widget)\n\n    def match(self, context, *args):\n        \"\"\"Return the degree to which the stored `context` matches the data\n        passed in additional arguments).\n        When match returns 0 (ContextHandler.NO_MATCH), the context will not\n        be used. When it returns ContextHandler.PERFECT_MATCH, the context\n        is a perfect match so no further search is necessary.\n\n        If imperfect matching is not desired, match should only\n        return ContextHandler.NO_MATCH or ContextHandler.PERFECT_MATCH.\n\n        Derived classes must overload this method.\n        \"\"\"\n        raise NotImplementedError\n\n    def find_or_create_context(self, widget, *args):\n        \"\"\"Find the best matching context or create a new one if nothing\n        useful is found. The returned context is moved to or added to the top\n        of the context list.\"\"\"\n\n        # First search the contexts that were already used in this widget instance\n        best_context, best_score = self.find_context(widget.context_settings, args, move_up=True)\n        # If the exact data was used, reuse the context\n        if best_score == self.PERFECT_MATCH:\n            return best_context, False\n\n        # Otherwise check if a better match is available in global_contexts\n        best_context, best_score = self.find_context(self.global_contexts, args,\n                                                     best_score, best_context)\n        if best_context:\n            context = self.clone_context(best_context, *args)\n        else:\n            context = self.new_context(*args)\n        # Store context in widget instance. It will be pushed to global_contexts\n        # when (if) update defaults is called.\n        self.add_context(widget.context_settings, context)\n        return context, best_context is None\n\n    def find_context(self, known_contexts, args, best_score=0, best_context=None, move_up=False):\n        \"\"\"Search the given list of contexts and return the context\n         which best matches the given args.\n\n        best_score and best_context can be used to provide base_values.\n        \"\"\"\n\n        for i, context in enumerate(known_contexts):\n            score = self.match(context, *args)\n            if score == self.PERFECT_MATCH:\n                if move_up:\n                    self.move_context_up(known_contexts, i)\n                return context, score\n            if score > best_score:  # NO_MATCH is not OK!\n                best_context, best_score = context, score\n        return best_context, best_score\n\n    @staticmethod\n    def move_context_up(contexts, index):\n        \"\"\"Move the context to the top of the list and set\n        the timestamp to current.\"\"\"\n        setting = contexts.pop(index)\n        setting.time = time.time()\n        contexts.insert(0, setting)\n\n    def add_context(self, contexts, setting):\n        \"\"\"Add the context to the top of the list.\"\"\"\n        contexts.insert(0, setting)\n        del contexts[self.MAX_SAVED_CONTEXTS:]\n\n    def clone_context(self, old_context, *args):\n        \"\"\"Construct a copy of the context settings suitable for the context\n        described by additional arguments. The method is called by\n        find_or_create_context with the same arguments. A class that overloads\n        :obj:`match` to accept additional arguments must also overload\n        :obj:`clone_context`.\"\"\"\n        context = self.new_context(*args)\n        context.values = copy.deepcopy(old_context.values)\n\n        traverse = self.provider.traverse_settings\n        for setting, data, _ in traverse(data=context.values):\n            if not isinstance(setting, ContextSetting):\n                continue\n\n            self.filter_value(setting, data, *args)\n        return context\n\n    @staticmethod\n    def filter_value(setting, data, *args):\n        \"\"\"Remove values related to setting that are invalid given args.\"\"\"\n\n    def close_context(self, widget):\n        \"\"\"Close the context by calling :obj:`settings_from_widget` to write\n        any relevant widget settings to the context.\"\"\"\n        if widget.current_context is None:\n            return\n\n        self.settings_from_widget(widget)\n        widget.current_context = None\n\n    def settings_to_widget(self, widget, *args):\n        \"\"\"Apply context settings stored in currently opened context\n        to the widget.\n        \"\"\"\n        context = widget.current_context\n        if context is None:\n            return\n\n        widget.retrieveSpecificSettings()\n\n        for setting, data, instance in \\\n                self.provider.traverse_settings(data=context.values, instance=widget):\n            if not isinstance(setting, ContextSetting) or setting.name not in data:\n                continue\n            value = self.decode_setting(setting, data[setting.name])\n            _apply_setting(setting, instance, value)\n\n    def settings_from_widget(self, widget, *args):\n        \"\"\"Update the current context with the setting values from the widget.\n        \"\"\"\n\n        context = widget.current_context\n        if context is None:\n            return\n\n        widget.storeSpecificSettings()\n\n        def packer(setting, instance):\n            if isinstance(setting, ContextSetting) and hasattr(instance, setting.name):\n                value = getattr(instance, setting.name)\n                yield setting.name, self.encode_setting(context, setting, value)\n\n        context.values = self.provider.pack(widget, packer=packer)\n\n    def fast_save(self, widget, name, value):\n        \"\"\"Update value of `name` setting in the current context to `value`\n        \"\"\"\n        setting = self.known_settings.get(name)\n        if isinstance(setting, ContextSetting):\n            context = widget.current_context\n            if context is None:\n                return\n\n            value = self.encode_setting(context, setting, value)\n            self.update_packed_data(context.values, name, value)\n        else:\n            super().fast_save(widget, name, value)\n\n    @staticmethod\n    def update_packed_data(data, name, value):\n        \"\"\"Updates setting value stored in data dict\"\"\"\n\n        *prefixes, name = name.split('.')\n        for prefix in prefixes:\n            data = data.setdefault(prefix, {})\n        data[name] = value\n\n    def encode_setting(self, context, setting, value):\n        \"\"\"Encode value to be stored in settings dict\"\"\"\n        return copy.copy(value)\n\n    def decode_setting(self, setting, value):\n        \"\"\"Decode settings value from the setting dict format\"\"\"\n        return value\n\n\nclass DomainContextHandler(ContextHandler):\n    \"\"\"Context handler for widgets with settings that depend on\n    the input dataset. Suitable settings are selected based on the\n    data domain.\"\"\"\n\n    MATCH_VALUES_NONE, MATCH_VALUES_CLASS, MATCH_VALUES_ALL = range(3)\n\n    def __init__(self, *, match_values=0, **kwargs):\n        super().__init__()\n        self.match_values = match_values\n\n        for name in kwargs:\n            warnings.warn(\n                \"{} is not a valid parameter for DomainContextHandler\"\n                .format(name), OrangeDeprecationWarning\n            )\n\n    def encode_domain(self, domain):\n        \"\"\"\n        domain: Orange.data.domain to encode\n        return: dict mapping attribute name to type or list of values\n                (based on the value of self.match_values attribute)\n        \"\"\"\n\n        match = self.match_values\n        encode = self.encode_variables\n        if match == self.MATCH_VALUES_CLASS:\n            attributes = encode(domain.attributes, False)\n            attributes.update(encode(domain.class_vars, True))\n        else:\n            attributes = encode(domain.variables, match == self.MATCH_VALUES_ALL)\n\n        metas = encode(domain.metas, match == self.MATCH_VALUES_ALL)\n\n        return attributes, metas\n\n    @staticmethod\n    def encode_variables(attributes, encode_values):\n        \"\"\"Encode variables to a list mapping name to variable type\n        or a list of values.\"\"\"\n\n        if not encode_values:\n            return {v.name: vartype(v) for v in attributes}\n\n        return {v.name: v.values if v.is_discrete else vartype(v)\n                for v in attributes}\n\n    def new_context(self, domain, attributes, metas):\n        \"\"\"Create a new context.\"\"\"\n        context = super().new_context()\n        context.attributes = attributes\n        context.metas = metas\n        return context\n\n    def open_context(self, widget, domain):\n        if domain is None:\n            return None, False\n\n        if not isinstance(domain, Domain):\n            domain = domain.domain\n\n        super().open_context(widget, domain, *self.encode_domain(domain))\n\n    def filter_value(self, setting, data, domain, attrs, metas):\n        value = data.get(setting.name, None)\n        if isinstance(value, list):\n            new_value = [item for item in value\n                         if self.is_valid_item(setting, item, attrs, metas)]\n            data[setting.name] = new_value\n        elif value is not None:\n            if (value[1] >= 0 and\n                    not self._var_exists(setting, value, attrs, metas)):\n                del data[setting.name]\n\n    def settings_to_widget(self, widget, domain, *args):\n        context = widget.current_context\n        if context is None:\n            return\n\n        widget.retrieveSpecificSettings()\n\n        for setting, data, instance in \\\n                self.provider.traverse_settings(data=context.values, instance=widget):\n            if not isinstance(setting, ContextSetting) or setting.name not in data:\n                continue\n\n            value = self.decode_setting(setting, data[setting.name], domain)\n            _apply_setting(setting, instance, value)\n\n    @staticmethod\n    def encode_variable(var):\n        return var.name, 100 + vartype(var)\n\n    def encode_setting(self, context, setting, value):\n        if isinstance(value, list):\n            if all(e is None or isinstance(e, Variable) for e in value) \\\n                    and any(e is not None for e in value):\n                return [None if e is None else self.encode_variable(e)\n                        for e in value], -3\n            else:\n                return copy.copy(value)\n\n        if isinstance(setting, ContextSetting):\n            if isinstance(value, str):\n                if not setting.exclude_attributes and value in context.attributes:\n                    return value, context.attributes[value]\n                if not setting.exclude_metas and value in context.metas:\n                    return value, context.metas[value]\n            elif isinstance(value, Variable):\n                return self.encode_variable(value)\n\n        return copy.copy(value), -2\n\n    def decode_setting(self, setting, value, domain=None):\n        if isinstance(value, tuple):\n            if value[1] == -3:\n                return [None if e is None else domain[e[0]] for e in value[0]]\n            if value[1] >= 100:\n                if domain is None:\n                    raise ValueError(\"Cannot decode variable without domain\")\n                return domain[value[0]]\n            return value[0]\n        else:\n            return value\n\n    @staticmethod\n    def _var_exists(setting, value, attributes, metas):\n        if not isinstance(value, tuple) or len(value) != 2:\n            return False\n\n        attr_name, attr_type = value\n        if attr_type >= 100:\n            attr_type -= 100\n        return (not setting.exclude_attributes and\n                attributes.get(attr_name, -1) == attr_type or\n                not setting.exclude_metas and\n                metas.get(attr_name, -1) == attr_type)\n\n    def match(self, context, domain, attrs, metas):\n        if (attrs, metas) == (context.attributes, context.metas):\n            return self.PERFECT_MATCH\n\n        matches = []\n        try:\n            for setting, data, _ in \\\n                    self.provider.traverse_settings(data=context.values):\n                if not isinstance(setting, ContextSetting):\n                    continue\n                value = data.get(setting.name, None)\n\n                if isinstance(value, list):\n                    matches.append(\n                        self.match_list(setting, value, context, attrs, metas))\n                elif isinstance(value, tuple) \\\n                        and len(value) == 2 \\\n                        and isinstance(value[0], list) \\\n                        and value[1] == -3:\n                    matches.append(\n                        self.match_list(setting, value[0], context, attrs, metas))\n                elif value is not None:\n                    matches.append(\n                        self.match_value(setting, value, attrs, metas))\n        except IncompatibleContext:\n            return self.NO_MATCH\n\n        matches.append((0, 0))\n        matched, available = [sum(m) for m in zip(*matches)]\n\n        return matched / available if available else 0.1\n\n    def match_list(self, setting, value, context, attrs, metas):\n        \"\"\"Match a list of values with the given context.\n        returns a tuple containing number of matched and all values.\n        \"\"\"\n        matched = 0\n        for i, item in enumerate(value):\n            if self.is_valid_item(setting, item, attrs, metas):\n                matched += 1\n            elif setting.required == ContextSetting.REQUIRED:\n                raise IncompatibleContext()\n        return matched, len(value)\n\n    def match_value(self, setting, value, attrs, metas):\n        \"\"\"Match a single value \"\"\"\n        if value[1] < 0:\n            return 0, 0\n\n        if self._var_exists(setting, value, attrs, metas):\n            return 1, 1\n        elif setting.required == setting.OPTIONAL:\n            return 0, 1\n        else:\n            raise IncompatibleContext()\n\n    def is_valid_item(self, setting, item, attrs, metas):\n        \"\"\"Return True if given item can be used with attrs and metas\n\n        Subclasses can override this method to checks data in alternative\n        representations.\n        \"\"\"\n        if not isinstance(item, tuple):\n            return True\n        return self._var_exists(setting, item, attrs, metas)\n\n\nclass IncompatibleContext(Exception):\n    \"\"\"Raised when a required variable in context is not available in data.\"\"\"\n    pass\n\n\nclass ClassValuesContextHandler(ContextHandler):\n    \"\"\"Context handler used for widgets that work with\n    a single discrete variable\"\"\"\n\n    def open_context(self, widget, classes):\n        if isinstance(classes, Variable):\n            if classes.is_discrete:\n                classes = classes.values\n            else:\n                classes = None\n\n        super().open_context(widget, classes)\n\n    def new_context(self, classes):\n        context = super().new_context()\n        context.classes = classes\n        return context\n\n    def match(self, context, classes):\n        if isinstance(classes, Variable) and classes.is_continuous:\n            return (self.PERFECT_MATCH if context.classes is None\n                    else self.NO_MATCH)\n        else:\n            return (self.PERFECT_MATCH if context.classes == classes\n                    else self.NO_MATCH)\n\n\nclass PerfectDomainContextHandler(DomainContextHandler):\n    \"\"\"Context handler that matches a context only when\n    the same domain is available.\n\n    It uses a different encoding than the DomainContextHandler.\n    \"\"\"\n\n    def new_context(self, domain, attributes, class_vars, metas):\n        \"\"\"Same as DomainContextHandler, but also store class_vars\"\"\"\n        context = super().new_context(domain, attributes, metas)\n        context.class_vars = class_vars\n        return context\n\n    def clone_context(self, old_context, *args):\n        \"\"\"Copy of context is always valid, since widgets are using\n        the same domain.\"\"\"\n        context = self.new_context(*args)\n        context.values = copy.deepcopy(old_context.values)\n        return context\n\n    def encode_domain(self, domain):\n        \"\"\"Encode domain into tuples (name, type)\n        A tuple is returned for each of attributes, class_vars and metas.\n        \"\"\"\n\n        if self.match_values == self.MATCH_VALUES_ALL:\n            def _encode(attrs):\n                return tuple((v.name, list(v.values) if v.is_discrete else vartype(v))\n                             for v in attrs)\n        else:\n            def _encode(attrs):\n                return tuple((v.name, vartype(v)) for v in attrs)\n        return (_encode(domain.attributes),\n                _encode(domain.class_vars),\n                _encode(domain.metas))\n\n    def match(self, context, domain, attributes, class_vars, metas):\n        \"\"\"Context only matches when domains are the same\"\"\"\n\n        return (self.PERFECT_MATCH\n                if (context.attributes == attributes and\n                    context.class_vars == class_vars and\n                    context.metas == metas)\n                else self.NO_MATCH)\n\n    def encode_setting(self, context, setting, value):\n        \"\"\"Same as is domain context handler, but handles separately stored\n        class_vars.\"\"\"\n\n        if isinstance(setting, ContextSetting) and isinstance(value, str):\n\n            def _candidate_variables():\n                if not setting.exclude_attributes:\n                    yield from itertools.chain(context.attributes,\n                                               context.class_vars)\n                if not setting.exclude_metas:\n                    yield from context.metas\n\n            for aname, atype in _candidate_variables():\n                if aname == value:\n                    return value, atype\n\n            return value, -1\n        else:\n            return super().encode_setting(context, setting, value)\n\n\nclass SettingsPrinter(pprint.PrettyPrinter):\n    \"\"\"Pretty Printer that knows how to properly format Contexts.\"\"\"\n\n    def _format(self, obj, stream, indent, allowance, context, level):\n        if not isinstance(obj, Context):\n            return super()._format(obj, stream, indent,\n                                   allowance, context, level)\n\n        stream.write(\"Context(\")\n        for key, value in sorted(obj.__dict__.items(), key=itemgetter(0)):\n            if key == \"values\":\n                continue\n            stream.write(key)\n            stream.write(\"=\")\n            stream.write(self._repr(value, context, level + 1))\n            stream.write(\",\\n\")\n            stream.write(\" \" * (indent + 8))\n        stream.write(\"values=\")\n        stream.write(\" \")\n        self._format(obj.values, stream, indent+15,\n                     allowance+1, context, level + 1)\n        stream.write(\")\")\n\n\ndef rename_setting(settings, old_name, new_name):\n    \"\"\"\n    Rename setting from `old_name` to `new_name`. Used in migrations.\n\n    The argument `settings` can be `dict` or `Context`.\n    \"\"\"\n    if isinstance(settings, Context):\n        rename_setting(settings.values, old_name, new_name)\n    else:\n        settings[new_name] = settings.pop(old_name)\n\n\ndef migrate_str_to_variable(settings, names=None, none_placeholder=None):\n    \"\"\"\n    Change variables stored as `(str, int)` to `(Variable, int)`.\n\n    Args:\n        settings (Context): context that is being migrated\n        names (sequence): names of settings to be migrated. If omitted,\n            all settings with values `(str, int)` are migrated.\n    \"\"\"\n    def _fix(name):\n        var, vartype = settings.values[name]\n        if 0 <= vartype <= 100:\n            settings.values[name] = (var, 100 + vartype)\n        elif var == none_placeholder and vartype == -2:\n            settings.values[name] = None\n\n    if names is None:\n        for name, setting in settings.values.items():\n            if isinstance(setting, tuple) and len(setting) == 2 and \\\n                    isinstance(setting[0], str) and isinstance(setting[1], int):\n                _fix(name)\n    elif isinstance(names, str):\n        _fix(names)\n    else:\n        for name in names:\n            _fix(name)\n",
            "new_file_content": "\"\"\"Widget Settings and Settings Handlers\n\nSettings are used to declare widget attributes that persist through sessions.\nWhen widget is removed or saved to a schema file, its settings are packed,\nserialized and stored. When a new widget is created, values of attributes\nmarked as settings are read from disk. When schema is loaded, attribute values\nare set to one stored in schema.\n\nEach widget has its own SettingsHandler that takes care of serializing and\nstoring of settings and SettingProvider that is incharge of reading and\nwriting the setting values.\n\nAll widgets extending from OWWidget use SettingsHandler, unless they\ndeclare otherwise. SettingsHandler ensures that setting attributes\nare replaced with default (last used) setting values when the widget is\ninitialized and stored when the widget is removed.\n\nWidgets with settings whose values depend on the widget inputs use\nsettings handlers based on ContextHandler. These handlers have two\nadditional methods, open_context and close_context.\n\nopen_context is called when widgets receives new data. It finds a suitable\ncontext and sets the widget attributes to the values stored in context.\nIf no suitable context exists, a new one is created and values from widget\nare copied to it.\n\nclose_context stores values that were last used on the widget to the context\nso they can be used alter. It should be called before widget starts modifying\n(initializing) the value of the setting attributes.\n\"\"\"\n\nimport sys\nimport copy\nimport itertools\nimport os\nimport logging\nimport pickle\nimport pprint\nimport time\nimport warnings\nfrom operator import itemgetter\nfrom typing import Any\n\nfrom Orange.data import Domain, Variable\nfrom Orange.misc.environ import widget_settings_dir\nfrom Orange.util import OrangeDeprecationWarning\nfrom Orange.widgets.utils import vartype\nfrom Orange.widgets.gui import OWComponent\n\nlog = logging.getLogger(__name__)\n\n__all__ = [\"Setting\", \"SettingsHandler\", \"SettingProvider\",\n           \"ContextSetting\", \"ContextHandler\",\n           \"DomainContextHandler\", \"PerfectDomainContextHandler\",\n           \"ClassValuesContextHandler\", \"widget_settings_dir\",\n           \"IncompatibleContext\"]\n\n_IMMUTABLES = (str, int, bytes, bool, float, tuple)\n\nVERSION_KEY = \"__version__\"\n\n\nclass Setting:\n    \"\"\"Description of a setting.\n    \"\"\"\n\n    # Settings are automatically persisted to disk\n    packable = True\n\n    # Setting is only persisted to schema (default value does not change)\n    schema_only = False\n\n    def __new__(cls, default, *args, **kwargs):\n        \"\"\"A misleading docstring for providing type hints for Settings\n\n        :type: default: T\n        :rtype: T\n        \"\"\"\n        return super().__new__(cls)\n\n    def __init__(self, default, **data):\n        self.name = None  # Name gets set in widget's meta class\n        self.default = default\n        self.__dict__.update(data)\n\n    def __str__(self):\n        return '{0} \"{1}\"'.format(self.__class__.__name__, self.name)\n\n    __repr__ = __str__\n\n    def __getnewargs__(self):\n        return (self.default, )\n\n\n# Pylint ignores type annotations in assignments. For\n#\n#    x: int = Setting(0)\n#\n# it ignores `int` and assumes x is of type `Setting`. Annotations in\n# comments ( # type: int) also don't work. The only way to annotate x is\n#\n#    x: int\n#    x = Setting(0)\n#\n# but we don't want to clutter the code with extra lines of annotations. Hence\n# we disable checking the type of `Setting` by confusing pylint with an extra\n# definition that is never executed.\nif 1 == 0:\n    class Setting:  # pylint: disable=function-redefined\n        pass\n\n\ndef _apply_setting(setting: Setting, instance: OWComponent, value: Any):\n    \"\"\"\n    Set `setting` of widget `instance` to the given `value`, in place if\n    possible.\n\n    If old and new values are of the same type, and the type is either a list\n    or has methods `clear` and `update`, setting is updated in place. Otherwise\n    the function calls `setattr`.\n    \"\"\"\n    target = getattr(instance, setting.name, None)\n    if type(target) is type(value):\n        if isinstance(value, list):\n            target[:] = value\n            return\n        elif hasattr(value, \"clear\") and hasattr(value, \"update\"):\n            target.clear()\n            target.update(value)\n            return\n    setattr(instance, setting.name, value)\n\n\nclass SettingProvider:\n    \"\"\"A hierarchical structure keeping track of settings belonging to\n    a class and child setting providers.\n\n    At instantiation, it creates a dict of all Setting and SettingProvider\n    members of the class. This dict is used to get/set values of settings\n    from/to the instances of the class this provider belongs to.\n    \"\"\"\n\n    def __init__(self, provider_class):\n        \"\"\" Construct a new instance of SettingProvider.\n\n        Traverse provider_class members and store all instances of\n        Setting and SettingProvider.\n\n        Parameters\n        ----------\n        provider_class : class\n            class containing settings definitions\n        \"\"\"\n        self.name = \"\"\n        self.provider_class = provider_class\n        self.providers = {}\n        \"\"\":type: dict[str, SettingProvider]\"\"\"\n        self.settings = {}\n        \"\"\":type: dict[str, Setting]\"\"\"\n        self.initialization_data = None\n\n        for name in dir(provider_class):\n            value = getattr(provider_class, name, None)\n            if isinstance(value, Setting):\n                value = copy.deepcopy(value)\n                value.name = name\n                self.settings[name] = value\n            if isinstance(value, SettingProvider):\n                value = copy.deepcopy(value)\n                value.name = name\n                self.providers[name] = value\n\n    def initialize(self, instance, data=None):\n        \"\"\"Initialize instance settings to their default values.\n\n        Mutable values are (shallow) copied before they are assigned to the\n        widget. Immutable are used as-is.\n\n        Parameters\n        ----------\n        instance : OWWidget\n            widget instance to initialize\n        data : Optional[dict]\n            optional data used to override the defaults\n            (used when settings are loaded from schema)\n        \"\"\"\n        if data is None and self.initialization_data is not None:\n            data = self.initialization_data\n\n        self._initialize_settings(instance, data)\n        self._initialize_providers(instance, data)\n\n    def _initialize_settings(self, instance, data):\n        if data is None:\n            data = {}\n        for name, setting in self.settings.items():\n            value = data.get(name, setting.default)\n            if isinstance(value, _IMMUTABLES):\n                setattr(instance, name, value)\n            else:\n                setattr(instance, name, copy.copy(value))\n\n    def _initialize_providers(self, instance, data):\n        if not data:\n            return\n\n        for name, provider in self.providers.items():\n            if name not in data:\n                continue\n\n            member = getattr(instance, name, None)\n            if member is None or isinstance(member, SettingProvider):\n                provider.store_initialization_data(data[name])\n            else:\n                provider.initialize(member, data[name])\n\n    def store_initialization_data(self, initialization_data):\n        \"\"\"Store initialization data for later use.\n\n        Used when settings handler is initialized, but member for this\n        provider does not exists yet (because handler.initialize is called in\n        __new__, but member will be created in __init__.\n\n        Parameters\n        ----------\n        initialization_data : dict\n            data to be used for initialization when the component is created\n        \"\"\"\n        self.initialization_data = initialization_data\n\n    @staticmethod\n    def _default_packer(setting, instance):\n        \"\"\"A simple packet that yields setting name and value.\n\n        Parameters\n        ----------\n        setting : Setting\n        instance : OWWidget\n        \"\"\"\n        if setting.packable:\n            if hasattr(instance, setting.name):\n                yield setting.name, getattr(instance, setting.name)\n            else:\n                warnings.warn(\"{0} is declared as setting on {1} \"\n                              \"but not present on instance.\"\n                              .format(setting.name, instance))\n\n    def pack(self, instance, packer=None):\n        \"\"\"Pack instance settings in a name:value dict.\n\n        Parameters\n        ----------\n        instance : OWWidget\n            widget instance\n        packer: callable (Setting, OWWidget) -> Generator[(str, object)]\n            optional packing function\n            it will be called with setting and instance parameters and\n            should yield (name, value) pairs that will be added to the\n            packed_settings.\n        \"\"\"\n        if packer is None:\n            packer = self._default_packer\n\n        packed_settings = dict(itertools.chain(\n            *(packer(setting, instance) for setting in self.settings.values())\n        ))\n\n        packed_settings.update({\n            name: provider.pack(getattr(instance, name), packer)\n            for name, provider in self.providers.items()\n            if hasattr(instance, name)\n        })\n        return packed_settings\n\n    def unpack(self, instance, data):\n        \"\"\"Restore settings from data to the instance.\n\n        Parameters\n        ----------\n        instance : OWWidget\n            instance to restore settings to\n        data : dict\n            packed data\n        \"\"\"\n        for setting, _data, inst in self.traverse_settings(data, instance):\n            if setting.name in _data and inst is not None:\n                _apply_setting(setting, inst, _data[setting.name])\n\n    def get_provider(self, provider_class):\n        \"\"\"Return provider for provider_class.\n\n        If this provider matches, return it, otherwise pass\n        the call to child providers.\n\n        Parameters\n        ----------\n        provider_class : class\n        \"\"\"\n        if issubclass(provider_class, self.provider_class):\n            return self\n\n        for subprovider in self.providers.values():\n            provider = subprovider.get_provider(provider_class)\n            if provider:\n                return provider\n        return None\n\n    def traverse_settings(self, data=None, instance=None):\n        \"\"\"Generator of tuples (setting, data, instance) for each setting\n        in this and child providers..\n\n        Parameters\n        ----------\n        data : dict\n            dictionary with setting values\n        instance : OWWidget\n            instance matching setting_provider\n        \"\"\"\n        data = data if data is not None else {}\n\n        for setting in self.settings.values():\n            yield setting, data, instance\n\n        for provider in self.providers.values():\n            data_ = data.get(provider.name, {})\n            instance_ = getattr(instance, provider.name, None)\n            for setting, component_data, component_instance in \\\n                    provider.traverse_settings(data_, instance_):\n                yield setting, component_data, component_instance\n\n\nclass SettingsHandler:\n    \"\"\"Reads widget setting files and passes them to appropriate providers.\"\"\"\n\n    def __init__(self):\n        \"\"\"Create a setting handler template.\n\n        Used in class definition. Bound instance will be created\n        when SettingsHandler.create is called.\n        \"\"\"\n        self.widget_class = None\n        self.provider = None\n        \"\"\":type: SettingProvider\"\"\"\n        self.defaults = {}\n        self.known_settings = {}\n\n    @staticmethod\n    def create(widget_class, template=None):\n        \"\"\"Create a new settings handler based on the template and bind it to\n        widget_class.\n\n        Parameters\n        ----------\n        widget_class : class\n        template : SettingsHandler\n            SettingsHandler to copy setup from\n\n        Returns\n        -------\n        SettingsHandler\n        \"\"\"\n\n        if template is None:\n            template = SettingsHandler()\n\n        setting_handler = copy.copy(template)\n        setting_handler.defaults = {}\n        setting_handler.bind(widget_class)\n        return setting_handler\n\n    def bind(self, widget_class):\n        \"\"\"Bind settings handler instance to widget_class.\n\n        Parameters\n        ----------\n        widget_class : class\n        \"\"\"\n        self.widget_class = widget_class\n        self.provider = SettingProvider(widget_class)\n        self.known_settings = {}\n        self.analyze_settings(self.provider, \"\")\n        self.read_defaults()\n\n    def analyze_settings(self, provider, prefix):\n        \"\"\"Traverse through all settings known to the provider\n        and analyze each of them.\n\n        Parameters\n        ----------\n        provider : SettingProvider\n        prefix : str\n            prefix the provider is registered to handle\n        \"\"\"\n        for setting in provider.settings.values():\n            self.analyze_setting(prefix, setting)\n\n        for name, sub_provider in provider.providers.items():\n            new_prefix = '{0}{1}.'.format(prefix or '', name)\n            self.analyze_settings(sub_provider, new_prefix)\n\n    def analyze_setting(self, prefix, setting):\n        \"\"\"Perform any initialization task related to setting.\n\n        Parameters\n        ----------\n        prefix : str\n        setting : Setting\n        \"\"\"\n        self.known_settings[prefix + setting.name] = setting\n\n    def read_defaults(self):\n        \"\"\"Read (global) defaults for this widget class from a file.\n        Opens a file and calls :obj:`read_defaults_file`. Derived classes\n        should overload the latter.\"\"\"\n        filename = self._get_settings_filename()\n        if os.path.isfile(filename):\n            settings_file = open(filename, \"rb\")\n            try:\n                self.read_defaults_file(settings_file)\n            # Unpickling exceptions can be of any type\n            # pylint: disable=broad-except\n            except Exception as ex:\n                warnings.warn(\"Could not read defaults for widget {0}\\n\"\n                              \"The following error occurred:\\n\\n{1}\"\n                              .format(self.widget_class, ex))\n            finally:\n                settings_file.close()\n\n    def read_defaults_file(self, settings_file):\n        \"\"\"Read (global) defaults for this widget class from a file.\n\n        Parameters\n        ----------\n        settings_file : file-like object\n        \"\"\"\n        defaults = pickle.load(settings_file)\n        self.defaults = {\n            key: value\n            for key, value in defaults.items()\n            if not isinstance(value, Setting)\n        }\n        self._migrate_settings(self.defaults)\n\n    def write_defaults(self):\n        \"\"\"Write (global) defaults for this widget class to a file.\n        Opens a file and calls :obj:`write_defaults_file`. Derived classes\n        should overload the latter.\"\"\"\n        filename = self._get_settings_filename()\n        os.makedirs(os.path.dirname(filename), exist_ok=True)\n        try:\n            settings_file = open(filename, \"wb\")\n            try:\n                self.write_defaults_file(settings_file)\n            except (EOFError, IOError, pickle.PicklingError) as ex:\n                log.error(\"Could not write default settings for %s (%s).\",\n                          self.widget_class, type(ex).__name__)\n                settings_file.close()\n                os.remove(filename)\n            else:\n                settings_file.close()\n        except PermissionError as ex:\n            log.error(\"Could not write default settings for %s (%s).\",\n                      self.widget_class, type(ex).__name__)\n\n    def write_defaults_file(self, settings_file):\n        \"\"\"Write defaults for this widget class to a file\n\n        Parameters\n        ----------\n        settings_file : file-like object\n        \"\"\"\n        defaults = dict(self.defaults)\n        defaults[VERSION_KEY] = self.widget_class.settings_version\n        pickle.dump(defaults, settings_file, -1)\n\n    def _get_settings_filename(self):\n        \"\"\"Return the name of the file with default settings for the widget\"\"\"\n        return os.path.join(widget_settings_dir(),\n                            \"{0.__module__}.{0.__qualname__}.pickle\"\n                            .format(self.widget_class))\n\n    def initialize(self, instance, data=None):\n        \"\"\"\n        Initialize widget's settings.\n\n        Replace all instance settings with their default values.\n\n        Parameters\n        ----------\n        instance : OWWidget\n        data : dict or bytes that unpickle into a dict\n            values used to override the defaults\n        \"\"\"\n        provider = self._select_provider(instance)\n\n        if isinstance(data, bytes):\n            data = pickle.loads(data)\n        self._migrate_settings(data)\n\n        if provider is self.provider:\n            data = self._add_defaults(data)\n\n        provider.initialize(instance, data)\n\n    def _migrate_settings(self, settings):\n        \"\"\"Ask widget to migrate settings to the latest version.\"\"\"\n        if settings:\n            try:\n                self.widget_class.migrate_settings(\n                    settings, settings.pop(VERSION_KEY, 0))\n            except Exception:  # pylint: disable=broad-except\n                sys.excepthook(*sys.exc_info())\n                settings.clear()\n\n    def _select_provider(self, instance):\n        provider = self.provider.get_provider(instance.__class__)\n        if provider is None:\n            message = \"{0} has not been declared as setting provider in {1}. \" \\\n                      \"Settings will not be saved/loaded properly. Defaults will be used instead.\" \\\n                      .format(instance.__class__, self.widget_class)\n            warnings.warn(message)\n            provider = SettingProvider(instance.__class__)\n        return provider\n\n    def _add_defaults(self, data):\n        if data is None:\n            return self.defaults\n\n        new_data = self.defaults.copy()\n        new_data.update(data)\n        return new_data\n\n    def _prepare_defaults(self, widget):\n        self.defaults = self.provider.pack(widget)\n        for setting, data, _ in self.provider.traverse_settings(data=self.defaults):\n            if setting.schema_only:\n                data.pop(setting.name, None)\n\n    def pack_data(self, widget):\n        \"\"\"\n        Pack the settings for the given widget. This method is used when\n        saving schema, so that when the schema is reloaded the widget is\n        initialized with its proper data and not the class-based defaults.\n        See :obj:`SettingsHandler.initialize` for detailed explanation of its\n        use.\n\n        Inherited classes add other data, in particular widget-specific\n        local contexts.\n\n        Parameters\n        ----------\n        widget : OWWidget\n        \"\"\"\n        widget.settingsAboutToBePacked.emit()\n        packed_settings = self.provider.pack(widget)\n        packed_settings[VERSION_KEY] = self.widget_class.settings_version\n        return packed_settings\n\n    def update_defaults(self, widget):\n        \"\"\"\n        Writes widget instance's settings to class defaults. Called when the\n        widget is deleted.\n\n        Parameters\n        ----------\n        widget : OWWidget\n        \"\"\"\n        widget.settingsAboutToBePacked.emit()\n        self._prepare_defaults(widget)\n        self.write_defaults()\n\n    def fast_save(self, widget, name, value):\n        \"\"\"Store the (changed) widget's setting immediately to the context.\n\n        Parameters\n        ----------\n        widget : OWWidget\n        name : str\n        value : object\n\n        \"\"\"\n        if name in self.known_settings:\n            setting = self.known_settings[name]\n            if not setting.schema_only:\n                setting.default = value\n\n    def reset_settings(self, instance):\n        \"\"\"Reset widget settings to defaults\n\n        Parameters\n        ----------\n        instance : OWWidget\n        \"\"\"\n        for setting, _, inst in self.provider.traverse_settings(instance=instance):\n            if setting.packable:\n                _apply_setting(setting, inst, setting.default)\n\n\nclass ContextSetting(Setting):\n    \"\"\"Description of a context dependent setting\"\"\"\n\n    OPTIONAL = 0\n    REQUIRED = 2\n\n    # Context settings are not persisted, but are stored in context instead.\n    packable = False\n\n    # These flags are not general - they assume that the setting has to do\n    # something with the attributes. Large majority does, so this greatly\n    # simplifies the declaration of settings in widget at no (visible)\n    # cost to those settings that don't need it\n    def __init__(self, default, *, required=2,\n                 exclude_attributes=False, exclude_metas=False, **data):\n        super().__init__(default, **data)\n        self.exclude_attributes = exclude_attributes\n        self.exclude_metas = exclude_metas\n        self.required = required\n\n\nclass Context:\n    \"\"\"Class for data thad defines context and\n    values that should be applied to widget if given context\n    is encountered.\"\"\"\n    def __init__(self, **argkw):\n        self.time = time.time()\n        self.values = {}\n        self.__dict__.update(argkw)\n\n    def __getstate__(self):\n        state = dict(self.__dict__)\n        for nc in getattr(self, \"no_copy\", []):\n            if nc in state:\n                del state[nc]\n        return state\n\n\nclass ContextHandler(SettingsHandler):\n    \"\"\"Base class for setting handlers that can handle contexts.\n\n    Classes deriving from it need to implement method `match`.\n    \"\"\"\n\n    NO_MATCH = 0\n    PERFECT_MATCH = 2\n\n    MAX_SAVED_CONTEXTS = 50\n\n    def __init__(self):\n        super().__init__()\n        self.global_contexts = []\n        self.known_settings = {}\n\n    def initialize(self, instance, data=None):\n        \"\"\"Initialize the widget: call the inherited initialization and\n        add an attribute 'context_settings' to the widget. This method\n        does not open a context.\"\"\"\n        instance.current_context = None\n        super().initialize(instance, data)\n        if data and \"context_settings\" in data:\n            instance.context_settings = data[\"context_settings\"]\n            self._migrate_contexts(instance.context_settings)\n        else:\n            instance.context_settings = []\n\n    def read_defaults_file(self, settings_file):\n        \"\"\"Call the inherited method, then read global context from the\n           pickle.\"\"\"\n        super().read_defaults_file(settings_file)\n        self.global_contexts = pickle.load(settings_file)\n        self._migrate_contexts(self.global_contexts)\n\n    def _migrate_contexts(self, contexts):\n        i = 0\n        while i < len(contexts):\n            context = contexts[i]\n            try:\n                self.widget_class.migrate_context(\n                    context, context.values.pop(VERSION_KEY, 0))\n            except IncompatibleContext:\n                del contexts[i]\n            except Exception:  # pylint: disable=broad-except\n                sys.excepthook(*sys.exc_info())\n                del contexts[i]\n            else:\n                i += 1\n\n    def write_defaults_file(self, settings_file):\n        \"\"\"Call the inherited method, then add global context to the pickle.\"\"\"\n        super().write_defaults_file(settings_file)\n\n        def add_version(context):\n            context = copy.copy(context)\n            context.values = dict(context.values)\n            context.values[VERSION_KEY] = self.widget_class.settings_version\n            return context\n\n        pickle.dump([add_version(context) for context in self.global_contexts],\n                    settings_file, -1)\n\n    def pack_data(self, widget):\n        \"\"\"Call the inherited method, then add local contexts to the dict.\"\"\"\n        data = super().pack_data(widget)\n        self.settings_from_widget(widget)\n        context_settings = [copy.copy(context) for context in\n                            widget.context_settings]\n        for context in context_settings:\n            context.values[VERSION_KEY] = self.widget_class.settings_version\n        data[\"context_settings\"] = context_settings\n        return data\n\n    def update_defaults(self, widget):\n        \"\"\"\n        Reimplemented from SettingsHandler\n\n        Merge the widgets local contexts into the global contexts and persist\n        the settings (including the contexts) to disk.\n        \"\"\"\n        widget.settingsAboutToBePacked.emit()\n        self.settings_from_widget(widget)\n        globs = self.global_contexts\n        assert widget.context_settings is not globs\n        ids = {id(c) for c in globs}\n        globs += (c for c in widget.context_settings if id(c) not in ids)\n        globs.sort(key=lambda c: -c.time)\n        del globs[self.MAX_SAVED_CONTEXTS:]\n\n        # Save non-context settings. Do not call super().update_defaults, so that\n        # settingsAboutToBePacked is emitted once.\n        self._prepare_defaults(widget)\n        self.write_defaults()\n\n    def new_context(self, *args):\n        \"\"\"Create a new context.\"\"\"\n        return Context()\n\n    def open_context(self, widget, *args):\n        \"\"\"Open a context by finding one and setting the widget data or\n        creating one and fill with the data from the widget.\"\"\"\n        widget.current_context, is_new = \\\n            self.find_or_create_context(widget, *args)\n        if is_new:\n            try:\n                self.settings_from_widget(widget, *args)\n            except TypeError:\n                warnings.warn(\"settings_from_widget in {} does not accept *args.\\n\"\n                              \"Support for this will be dropped in Orange 3.10\"\n                              .format(type(self)),\n                              DeprecationWarning)\n                self.settings_from_widget(widget)\n        else:\n            try:\n                self.settings_to_widget(widget, *args)\n            except TypeError:\n                warnings.warn(\"settings_to_widget {} does not accept *args.\\n\"\n                              \"Support for this will be dropped in Orange 3.10\"\n                              .format(type(self)),\n                              DeprecationWarning)\n                self.settings_to_widget(widget)\n\n    def match(self, context, *args):\n        \"\"\"Return the degree to which the stored `context` matches the data\n        passed in additional arguments).\n        When match returns 0 (ContextHandler.NO_MATCH), the context will not\n        be used. When it returns ContextHandler.PERFECT_MATCH, the context\n        is a perfect match so no further search is necessary.\n\n        If imperfect matching is not desired, match should only\n        return ContextHandler.NO_MATCH or ContextHandler.PERFECT_MATCH.\n\n        Derived classes must overload this method.\n        \"\"\"\n        raise NotImplementedError\n\n    def find_or_create_context(self, widget, *args):\n        \"\"\"Find the best matching context or create a new one if nothing\n        useful is found. The returned context is moved to or added to the top\n        of the context list.\"\"\"\n\n        # First search the contexts that were already used in this widget instance\n        best_context, best_score = self.find_context(widget.context_settings, args, move_up=True)\n        # If the exact data was used, reuse the context\n        if best_score == self.PERFECT_MATCH:\n            return best_context, False\n\n        # Otherwise check if a better match is available in global_contexts\n        best_context, best_score = self.find_context(self.global_contexts, args,\n                                                     best_score, best_context)\n        if best_context:\n            context = self.clone_context(best_context, *args)\n        else:\n            context = self.new_context(*args)\n        # Store context in widget instance. It will be pushed to global_contexts\n        # when (if) update defaults is called.\n        self.add_context(widget.context_settings, context)\n        return context, best_context is None\n\n    def find_context(self, known_contexts, args, best_score=0, best_context=None, move_up=False):\n        \"\"\"Search the given list of contexts and return the context\n         which best matches the given args.\n\n        best_score and best_context can be used to provide base_values.\n        \"\"\"\n\n        for i, context in enumerate(known_contexts):\n            score = self.match(context, *args)\n            if score == self.PERFECT_MATCH:\n                if move_up:\n                    self.move_context_up(known_contexts, i)\n                return context, score\n            if score > best_score:  # NO_MATCH is not OK!\n                best_context, best_score = context, score\n        return best_context, best_score\n\n    @staticmethod\n    def move_context_up(contexts, index):\n        \"\"\"Move the context to the top of the list and set\n        the timestamp to current.\"\"\"\n        setting = contexts.pop(index)\n        setting.time = time.time()\n        contexts.insert(0, setting)\n\n    def add_context(self, contexts, setting):\n        \"\"\"Add the context to the top of the list.\"\"\"\n        contexts.insert(0, setting)\n        del contexts[self.MAX_SAVED_CONTEXTS:]\n\n    def clone_context(self, old_context, *args):\n        \"\"\"Construct a copy of the context settings suitable for the context\n        described by additional arguments. The method is called by\n        find_or_create_context with the same arguments. A class that overloads\n        :obj:`match` to accept additional arguments must also overload\n        :obj:`clone_context`.\"\"\"\n        context = self.new_context(*args)\n        context.values = copy.deepcopy(old_context.values)\n\n        traverse = self.provider.traverse_settings\n        for setting, data, _ in traverse(data=context.values):\n            if not isinstance(setting, ContextSetting):\n                continue\n\n            self.filter_value(setting, data, *args)\n        return context\n\n    @staticmethod\n    def filter_value(setting, data, *args):\n        \"\"\"Remove values related to setting that are invalid given args.\"\"\"\n\n    def close_context(self, widget):\n        \"\"\"Close the context by calling :obj:`settings_from_widget` to write\n        any relevant widget settings to the context.\"\"\"\n        if widget.current_context is None:\n            return\n\n        self.settings_from_widget(widget)\n        widget.current_context = None\n\n    def settings_to_widget(self, widget, *args):\n        \"\"\"Apply context settings stored in currently opened context\n        to the widget.\n        \"\"\"\n        context = widget.current_context\n        if context is None:\n            return\n\n        widget.retrieveSpecificSettings()\n\n        for setting, data, instance in \\\n                self.provider.traverse_settings(data=context.values, instance=widget):\n            if not isinstance(setting, ContextSetting) or setting.name not in data:\n                continue\n            value = self.decode_setting(setting, data[setting.name])\n            _apply_setting(setting, instance, value)\n\n    def settings_from_widget(self, widget, *args):\n        \"\"\"Update the current context with the setting values from the widget.\n        \"\"\"\n\n        context = widget.current_context\n        if context is None:\n            return\n\n        widget.storeSpecificSettings()\n\n        def packer(setting, instance):\n            if isinstance(setting, ContextSetting) and hasattr(instance, setting.name):\n                value = getattr(instance, setting.name)\n                yield setting.name, self.encode_setting(context, setting, value)\n\n        context.values = self.provider.pack(widget, packer=packer)\n\n    def fast_save(self, widget, name, value):\n        \"\"\"Update value of `name` setting in the current context to `value`\n        \"\"\"\n        setting = self.known_settings.get(name)\n        if isinstance(setting, ContextSetting):\n            context = widget.current_context\n            if context is None:\n                return\n\n            value = self.encode_setting(context, setting, value)\n            self.update_packed_data(context.values, name, value)\n        else:\n            super().fast_save(widget, name, value)\n\n    @staticmethod\n    def update_packed_data(data, name, value):\n        \"\"\"Updates setting value stored in data dict\"\"\"\n\n        *prefixes, name = name.split('.')\n        for prefix in prefixes:\n            data = data.setdefault(prefix, {})\n        data[name] = value\n\n    def encode_setting(self, context, setting, value):\n        \"\"\"Encode value to be stored in settings dict\"\"\"\n        return copy.copy(value)\n\n    def decode_setting(self, setting, value):\n        \"\"\"Decode settings value from the setting dict format\"\"\"\n        return value\n\n\nclass DomainContextHandler(ContextHandler):\n    \"\"\"Context handler for widgets with settings that depend on\n    the input dataset. Suitable settings are selected based on the\n    data domain.\"\"\"\n\n    MATCH_VALUES_NONE, MATCH_VALUES_CLASS, MATCH_VALUES_ALL = range(3)\n\n    def __init__(self, *, match_values=0, **kwargs):\n        super().__init__()\n        self.match_values = match_values\n\n        for name in kwargs:\n            warnings.warn(\n                \"{} is not a valid parameter for DomainContextHandler\"\n                .format(name), OrangeDeprecationWarning\n            )\n\n    @staticmethod\n    def _warn_about_str_var_settings(setting):\n        warnings.warn(\n            \"Storing variables as strings in settings is deprecated.\\n\"\n            \"Support for this will be dropped in Orange 3.26.\\n\"\n            f\"Change f{setting.name} to store an instance of `Variable`.\")\n\n    def encode_domain(self, domain):\n        \"\"\"\n        domain: Orange.data.domain to encode\n        return: dict mapping attribute name to type or list of values\n                (based on the value of self.match_values attribute)\n        \"\"\"\n\n        match = self.match_values\n        encode = self.encode_variables\n        if match == self.MATCH_VALUES_CLASS:\n            attributes = encode(domain.attributes, False)\n            attributes.update(encode(domain.class_vars, True))\n        else:\n            attributes = encode(domain.variables, match == self.MATCH_VALUES_ALL)\n\n        metas = encode(domain.metas, match == self.MATCH_VALUES_ALL)\n\n        return attributes, metas\n\n    @staticmethod\n    def encode_variables(attributes, encode_values):\n        \"\"\"Encode variables to a list mapping name to variable type\n        or a list of values.\"\"\"\n\n        if not encode_values:\n            return {v.name: vartype(v) for v in attributes}\n\n        return {v.name: v.values if v.is_discrete else vartype(v)\n                for v in attributes}\n\n    def new_context(self, domain, attributes, metas):\n        \"\"\"Create a new context.\"\"\"\n        context = super().new_context()\n        context.attributes = attributes\n        context.metas = metas\n        return context\n\n    def open_context(self, widget, domain):\n        if domain is None:\n            return None, False\n\n        if not isinstance(domain, Domain):\n            domain = domain.domain\n\n        super().open_context(widget, domain, *self.encode_domain(domain))\n\n    def filter_value(self, setting, data, domain, attrs, metas):\n        value = data.get(setting.name, None)\n        if isinstance(value, list):\n            new_value = [item for item in value\n                         if self.is_valid_item(setting, item, attrs, metas)]\n            data[setting.name] = new_value\n        elif value is not None:\n            if (value[1] >= 0 and\n                    not self._var_exists(setting, value, attrs, metas)):\n                del data[setting.name]\n\n    def settings_to_widget(self, widget, domain, *args):\n        context = widget.current_context\n        if context is None:\n            return\n\n        widget.retrieveSpecificSettings()\n\n        for setting, data, instance in \\\n                self.provider.traverse_settings(data=context.values, instance=widget):\n            if not isinstance(setting, ContextSetting) or setting.name not in data:\n                continue\n\n            value = self.decode_setting(setting, data[setting.name], domain)\n            _apply_setting(setting, instance, value)\n\n    @staticmethod\n    def encode_variable(var):\n        return var.name, 100 + vartype(var)\n\n    @classmethod\n    def encode_setting(cls, context, setting, value):\n        if isinstance(value, list):\n            if all(e is None or isinstance(e, Variable) for e in value) \\\n                    and any(e is not None for e in value):\n                return [None if e is None else cls.encode_variable(e)\n                        for e in value], -3\n            else:\n                return copy.copy(value)\n\n        if isinstance(setting, ContextSetting):\n            if isinstance(value, str):\n                variables = {\n                    **({} if setting.exclude_attributes else context.attributes),\n                    **({} if setting.exclude_metas else context.metas)}\n                if value in variables:\n                    cls._warn_about_str_var_settings(setting)\n                    return value, variables[value]\n            elif isinstance(value, Variable):\n                return cls.encode_variable(value)\n\n        return copy.copy(value), -2\n\n    def decode_setting(self, setting, value, domain=None):\n        if isinstance(value, tuple):\n            if value[1] == -3:\n                return [None if e is None else domain[e[0]] for e in value[0]]\n            if value[1] >= 100:\n                if domain is None:\n                    raise ValueError(\"Cannot decode variable without domain\")\n                return domain[value[0]]\n            return value[0]\n        else:\n            return value\n\n    @classmethod\n    def _var_exists(cls, setting, value, attributes, metas):\n        if not isinstance(value, tuple) or len(value) != 2:\n            return False\n\n        attr_name, attr_type = value\n        if attr_type >= 100:\n            attr_type -= 100\n        else:\n            cls._warn_about_str_var_settings(setting)\n        return (not setting.exclude_attributes and\n                attributes.get(attr_name, -1) == attr_type or\n                not setting.exclude_metas and\n                metas.get(attr_name, -1) == attr_type)\n\n    def match(self, context, domain, attrs, metas):\n        if (attrs, metas) == (context.attributes, context.metas):\n            return self.PERFECT_MATCH\n\n        matches = []\n        try:\n            for setting, data, _ in \\\n                    self.provider.traverse_settings(data=context.values):\n                if not isinstance(setting, ContextSetting):\n                    continue\n                value = data.get(setting.name, None)\n\n                if isinstance(value, list):\n                    matches.append(\n                        self.match_list(setting, value, context, attrs, metas))\n                elif isinstance(value, tuple) \\\n                        and len(value) == 2 \\\n                        and isinstance(value[0], list) \\\n                        and value[1] == -3:\n                    matches.append(\n                        self.match_list(setting, value[0], context, attrs, metas))\n                elif value is not None:\n                    matches.append(\n                        self.match_value(setting, value, attrs, metas))\n        except IncompatibleContext:\n            return self.NO_MATCH\n\n        matches.append((0, 0))\n        matched, available = [sum(m) for m in zip(*matches)]\n\n        return matched / available if available else 0.1\n\n    def match_list(self, setting, value, context, attrs, metas):\n        \"\"\"Match a list of values with the given context.\n        returns a tuple containing number of matched and all values.\n        \"\"\"\n        matched = 0\n        for i, item in enumerate(value):\n            if self.is_valid_item(setting, item, attrs, metas):\n                matched += 1\n            elif setting.required == ContextSetting.REQUIRED:\n                raise IncompatibleContext()\n        return matched, len(value)\n\n    def match_value(self, setting, value, attrs, metas):\n        \"\"\"Match a single value \"\"\"\n        if value[1] < 0:\n            return 0, 0\n\n        if self._var_exists(setting, value, attrs, metas):\n            return 1, 1\n        elif setting.required == setting.OPTIONAL:\n            return 0, 1\n        else:\n            raise IncompatibleContext()\n\n    def is_valid_item(self, setting, item, attrs, metas):\n        \"\"\"Return True if given item can be used with attrs and metas\n\n        Subclasses can override this method to checks data in alternative\n        representations.\n        \"\"\"\n        if not isinstance(item, tuple):\n            return True\n        return self._var_exists(setting, item, attrs, metas)\n\n\nclass IncompatibleContext(Exception):\n    \"\"\"Raised when a required variable in context is not available in data.\"\"\"\n    pass\n\n\nclass ClassValuesContextHandler(ContextHandler):\n    \"\"\"Context handler used for widgets that work with\n    a single discrete variable\"\"\"\n\n    def open_context(self, widget, classes):\n        if isinstance(classes, Variable):\n            if classes.is_discrete:\n                classes = classes.values\n            else:\n                classes = None\n\n        super().open_context(widget, classes)\n\n    def new_context(self, classes):\n        context = super().new_context()\n        context.classes = classes\n        return context\n\n    def match(self, context, classes):\n        if isinstance(classes, Variable) and classes.is_continuous:\n            return (self.PERFECT_MATCH if context.classes is None\n                    else self.NO_MATCH)\n        else:\n            return (self.PERFECT_MATCH if context.classes == classes\n                    else self.NO_MATCH)\n\n\nclass PerfectDomainContextHandler(DomainContextHandler):\n    \"\"\"Context handler that matches a context only when\n    the same domain is available.\n\n    It uses a different encoding than the DomainContextHandler.\n    \"\"\"\n\n    def new_context(self, domain, attributes, class_vars, metas):\n        \"\"\"Same as DomainContextHandler, but also store class_vars\"\"\"\n        context = super().new_context(domain, attributes, metas)\n        context.class_vars = class_vars\n        return context\n\n    def clone_context(self, old_context, *args):\n        \"\"\"Copy of context is always valid, since widgets are using\n        the same domain.\"\"\"\n        context = self.new_context(*args)\n        context.values = copy.deepcopy(old_context.values)\n        return context\n\n    def encode_domain(self, domain):\n        \"\"\"Encode domain into tuples (name, type)\n        A tuple is returned for each of attributes, class_vars and metas.\n        \"\"\"\n\n        if self.match_values == self.MATCH_VALUES_ALL:\n            def _encode(attrs):\n                return tuple((v.name, list(v.values) if v.is_discrete else vartype(v))\n                             for v in attrs)\n        else:\n            def _encode(attrs):\n                return tuple((v.name, vartype(v)) for v in attrs)\n        return (_encode(domain.attributes),\n                _encode(domain.class_vars),\n                _encode(domain.metas))\n\n    def match(self, context, domain, attributes, class_vars, metas):\n        \"\"\"Context only matches when domains are the same\"\"\"\n\n        return (self.PERFECT_MATCH\n                if (context.attributes == attributes and\n                    context.class_vars == class_vars and\n                    context.metas == metas)\n                else self.NO_MATCH)\n\n    def encode_setting(self, context, setting, value):\n        \"\"\"Same as is domain context handler, but handles separately stored\n        class_vars.\"\"\"\n\n        if isinstance(setting, ContextSetting) and isinstance(value, str):\n\n            def _candidate_variables():\n                if not setting.exclude_attributes:\n                    yield from itertools.chain(context.attributes,\n                                               context.class_vars)\n                if not setting.exclude_metas:\n                    yield from context.metas\n\n            for aname, atype in _candidate_variables():\n                if aname == value:\n                    return value, atype\n\n            return value, -1\n        else:\n            return super().encode_setting(context, setting, value)\n\n\nclass SettingsPrinter(pprint.PrettyPrinter):\n    \"\"\"Pretty Printer that knows how to properly format Contexts.\"\"\"\n\n    def _format(self, obj, stream, indent, allowance, context, level):\n        if not isinstance(obj, Context):\n            return super()._format(obj, stream, indent,\n                                   allowance, context, level)\n\n        stream.write(\"Context(\")\n        for key, value in sorted(obj.__dict__.items(), key=itemgetter(0)):\n            if key == \"values\":\n                continue\n            stream.write(key)\n            stream.write(\"=\")\n            stream.write(self._repr(value, context, level + 1))\n            stream.write(\",\\n\")\n            stream.write(\" \" * (indent + 8))\n        stream.write(\"values=\")\n        stream.write(\" \")\n        self._format(obj.values, stream, indent+15,\n                     allowance+1, context, level + 1)\n        stream.write(\")\")\n\n\ndef rename_setting(settings, old_name, new_name):\n    \"\"\"\n    Rename setting from `old_name` to `new_name`. Used in migrations.\n\n    The argument `settings` can be `dict` or `Context`.\n    \"\"\"\n    if isinstance(settings, Context):\n        rename_setting(settings.values, old_name, new_name)\n    else:\n        settings[new_name] = settings.pop(old_name)\n\n\ndef migrate_str_to_variable(settings, names=None, none_placeholder=None):\n    \"\"\"\n    Change variables stored as `(str, int)` to `(Variable, int)`.\n\n    Args:\n        settings (Context): context that is being migrated\n        names (sequence): names of settings to be migrated. If omitted,\n            all settings with values `(str, int)` are migrated.\n    \"\"\"\n    def _fix(name):\n        var, vartype = settings.values[name]\n        if 0 <= vartype <= 100:\n            settings.values[name] = (var, 100 + vartype)\n        elif var == none_placeholder and vartype == -2:\n            settings.values[name] = None\n\n    if names is None:\n        for name, setting in settings.values.items():\n            if isinstance(setting, tuple) and len(setting) == 2 and \\\n                    isinstance(setting[0], str) and isinstance(setting[1], int):\n                _fix(name)\n    elif isinstance(names, str):\n        _fix(names)\n    else:\n        for name in names:\n            _fix(name)\n",
            "header": {
                "file": {
                    "path": "Orange/widgets/settings.py"
                },
                "misc_line": null
            },
            "index_line": {
                "old_commit_hash": "1198a4f58",
                "new_commit_hash": "e8a535e7d",
                "mode": "100644"
            },
            "is_binary_file": false,
            "binary_line": null,
            "minus_file": {
                "path": "a/Orange/widgets/settings.py"
            },
            "plus_file": {
                "path": "b/Orange/widgets/settings.py"
            },
            "hunks": [
                {
                    "descriptor": {
                        "old_range": {
                            "start": 937,
                            "length": 6
                        },
                        "new_range": {
                            "start": 937,
                            "length": 13
                        },
                        "section": "class DomainContextHandler(ContextHandler):"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "                .format(name), OrangeDeprecationWarning",
                                "type": "context"
                            },
                            {
                                "content": "            )",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "    @staticmethod",
                                "type": "added"
                            },
                            {
                                "content": "    def _warn_about_str_var_settings(setting):",
                                "type": "added"
                            },
                            {
                                "content": "        warnings.warn(",
                                "type": "added"
                            },
                            {
                                "content": "            \"Storing variables as strings in settings is deprecated.\\n\"",
                                "type": "added"
                            },
                            {
                                "content": "            \"Support for this will be dropped in Orange 3.26.\\n\"",
                                "type": "added"
                            },
                            {
                                "content": "            f\"Change f{setting.name} to store an instance of `Variable`.\")",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "    def encode_domain(self, domain):",
                                "type": "context"
                            },
                            {
                                "content": "        \"\"\"",
                                "type": "context"
                            },
                            {
                                "content": "        domain: Orange.data.domain to encode",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [
                        {
                            "file_name": "Orange/widgets/settings.py",
                            "type": "class",
                            "name": "DomainContextHandler",
                            "content": "class DomainContextHandler(ContextHandler):\n    \"\"\"Context handler for widgets with settings that depend on\n    the input dataset. Suitable settings are selected based on the\n    data domain.\"\"\"\n\n    MATCH_VALUES_NONE, MATCH_VALUES_CLASS, MATCH_VALUES_ALL = range(3)\n\n    def __init__(self, *, match_values=0, **kwargs):\n        super().__init__()\n        self.match_values = match_values\n\n        for name in kwargs:\n            warnings.warn(\n                \"{} is not a valid parameter for DomainContextHandler\"\n                .format(name), OrangeDeprecationWarning\n            )\n\n    @staticmethod\n    def _warn_about_str_var_settings(setting):\n        warnings.warn(\n            \"Storing variables as strings in settings is deprecated.\\n\"\n            \"Support for this will be dropped in Orange 3.26.\\n\"\n            f\"Change f{setting.name} to store an instance of `Variable`.\")\n\n    def encode_domain(self, domain):\n        \"\"\"\n        domain: Orange.data.domain to encode\n        return: dict mapping attribute name to type or list of values\n                (based on the value of self.match_values attribute)\n        \"\"\"\n\n        match = self.match_values\n        encode = self.encode_variables\n        if match == self.MATCH_VALUES_CLASS:\n            attributes = encode(domain.attributes, False)\n            attributes.update(encode(domain.class_vars, True))\n        else:\n            attributes = encode(domain.variables, match == self.MATCH_VALUES_ALL)\n\n        metas = encode(domain.metas, match == self.MATCH_VALUES_ALL)\n\n        return attributes, metas\n\n    @staticmethod\n    def encode_variables(attributes, encode_values):\n        \"\"\"Encode variables to a list mapping name to variable type\n        or a list of values.\"\"\"\n\n        if not encode_values:\n            return {v.name: vartype(v) for v in attributes}\n\n        return {v.name: v.values if v.is_discrete else vartype(v)\n                for v in attributes}\n\n    def new_context(self, domain, attributes, metas):\n        \"\"\"Create a new context.\"\"\"\n        context = super().new_context()\n        context.attributes = attributes\n        context.metas = metas\n        return context\n\n    def open_context(self, widget, domain):\n        if domain is None:\n            return None, False\n\n        if not isinstance(domain, Domain):\n            domain = domain.domain\n\n        super().open_context(widget, domain, *self.encode_domain(domain))\n\n    def filter_value(self, setting, data, domain, attrs, metas):\n        value = data.get(setting.name, None)\n        if isinstance(value, list):\n            new_value = [item for item in value\n                         if self.is_valid_item(setting, item, attrs, metas)]\n            data[setting.name] = new_value\n        elif value is not None:\n            if (value[1] >= 0 and\n                    not self._var_exists(setting, value, attrs, metas)):\n                del data[setting.name]\n\n    def settings_to_widget(self, widget, domain, *args):\n        context = widget.current_context\n        if context is None:\n            return\n\n        widget.retrieveSpecificSettings()\n\n        for setting, data, instance in \\\n                self.provider.traverse_settings(data=context.values, instance=widget):\n            if not isinstance(setting, ContextSetting) or setting.name not in data:\n                continue\n\n            value = self.decode_setting(setting, data[setting.name], domain)\n            _apply_setting(setting, instance, value)\n\n    @staticmethod\n    def encode_variable(var):\n        return var.name, 100 + vartype(var)\n\n    @classmethod\n    def encode_setting(cls, context, setting, value):\n        if isinstance(value, list):\n            if all(e is None or isinstance(e, Variable) for e in value) \\\n                    and any(e is not None for e in value):\n                return [None if e is None else cls.encode_variable(e)\n                        for e in value], -3\n            else:\n                return copy.copy(value)\n\n        if isinstance(setting, ContextSetting):\n            if isinstance(value, str):\n                variables = {\n                    **({} if setting.exclude_attributes else context.attributes),\n                    **({} if setting.exclude_metas else context.metas)}\n                if value in variables:\n                    cls._warn_about_str_var_settings(setting)\n                    return value, variables[value]\n            elif isinstance(value, Variable):\n                return cls.encode_variable(value)\n\n        return copy.copy(value), -2\n\n    def decode_setting(self, setting, value, domain=None):\n        if isinstance(value, tuple):\n            if value[1] == -3:\n                return [None if e is None else domain[e[0]] for e in value[0]]\n            if value[1] >= 100:\n                if domain is None:\n                    raise ValueError(\"Cannot decode variable without domain\")\n                return domain[value[0]]\n            return value[0]\n        else:\n            return value\n\n    @classmethod\n    def _var_exists(cls, setting, value, attributes, metas):\n        if not isinstance(value, tuple) or len(value) != 2:\n            return False\n\n        attr_name, attr_type = value\n        if attr_type >= 100:\n            attr_type -= 100\n        else:\n            cls._warn_about_str_var_settings(setting)\n        return (not setting.exclude_attributes and\n                attributes.get(attr_name, -1) == attr_type or\n                not setting.exclude_metas and\n                metas.get(attr_name, -1) == attr_type)\n\n    def match(self, context, domain, attrs, metas):\n        if (attrs, metas) == (context.attributes, context.metas):\n            return self.PERFECT_MATCH\n\n        matches = []\n        try:\n            for setting, data, _ in \\\n                    self.provider.traverse_settings(data=context.values):\n                if not isinstance(setting, ContextSetting):\n                    continue\n                value = data.get(setting.name, None)\n\n                if isinstance(value, list):\n                    matches.append(\n                        self.match_list(setting, value, context, attrs, metas))\n                elif isinstance(value, tuple) \\\n                        and len(value) == 2 \\\n                        and isinstance(value[0], list) \\\n                        and value[1] == -3:\n                    matches.append(\n                        self.match_list(setting, value[0], context, attrs, metas))\n                elif value is not None:\n                    matches.append(\n                        self.match_value(setting, value, attrs, metas))\n        except IncompatibleContext:\n            return self.NO_MATCH\n\n        matches.append((0, 0))\n        matched, available = [sum(m) for m in zip(*matches)]\n\n        return matched / available if available else 0.1\n\n    def match_list(self, setting, value, context, attrs, metas):\n        \"\"\"Match a list of values with the given context.\n        returns a tuple containing number of matched and all values.\n        \"\"\"\n        matched = 0\n        for i, item in enumerate(value):\n            if self.is_valid_item(setting, item, attrs, metas):\n                matched += 1\n            elif setting.required == ContextSetting.REQUIRED:\n                raise IncompatibleContext()\n        return matched, len(value)\n\n    def match_value(self, setting, value, attrs, metas):\n        \"\"\"Match a single value \"\"\"\n        if value[1] < 0:\n            return 0, 0\n\n        if self._var_exists(setting, value, attrs, metas):\n            return 1, 1\n        elif setting.required == setting.OPTIONAL:\n            return 0, 1\n        else:\n            raise IncompatibleContext()\n\n    def is_valid_item(self, setting, item, attrs, metas):\n        \"\"\"Return True if given item can be used with attrs and metas\n\n        Subclasses can override this method to checks data in alternative\n        representations.\n        \"\"\"\n        if not isinstance(item, tuple):\n            return True\n        return self._var_exists(setting, item, attrs, metas)",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 923,
                            "end_lineno": 1137,
                            "parent": null
                        }
                    ],
                    "added_entities": [
                        {
                            "file_name": "Orange/widgets/settings.py",
                            "type": "method",
                            "name": "DomainContextHandler._warn_about_str_var_settings",
                            "content": "class DomainContextHandler(ContextHandler):\n    \"\"\"Context handler for widgets with settings that depend on\n    the input dataset. Suitable settings are selected based on the\n    data domain.\"\"\"\n\n    MATCH_VALUES_NONE, MATCH_VALUES_CLASS, MATCH_VALUES_ALL = range(3)\n\n    def __init__(self, *, match_values=0, **kwargs):\n        super().__init__()\n        self.match_values = match_values\n\n        for name in kwargs:\n            warnings.warn(\n                \"{} is not a valid parameter for DomainContextHandler\"\n                .format(name), OrangeDeprecationWarning\n            )\n\n    @staticmethod\n    def _warn_about_str_var_settings(setting):\n        warnings.warn(\n            \"Storing variables as strings in settings is deprecated.\\n\"\n            \"Support for this will be dropped in Orange 3.26.\\n\"\n            f\"Change f{setting.name} to store an instance of `Variable`.\")\n\n    def encode_domain(self, domain):\n        \"\"\"\n        domain: Orange.data.domain to encode\n        return: dict mapping attribute name to type or list of values\n                (based on the value of self.match_values attribute)\n        \"\"\"\n\n        match = self.match_values\n        encode = self.encode_variables\n        if match == self.MATCH_VALUES_CLASS:\n            attributes = encode(domain.attributes, False)\n            attributes.update(encode(domain.class_vars, True))\n        else:\n            attributes = encode(domain.variables, match == self.MATCH_VALUES_ALL)\n\n        metas = encode(domain.metas, match == self.MATCH_VALUES_ALL)\n\n        return attributes, metas\n\n    @staticmethod\n    def encode_variables(attributes, encode_values):\n        \"\"\"Encode variables to a list mapping name to variable type\n        or a list of values.\"\"\"\n\n        if not encode_values:\n            return {v.name: vartype(v) for v in attributes}\n\n        return {v.name: v.values if v.is_discrete else vartype(v)\n                for v in attributes}\n\n    def new_context(self, domain, attributes, metas):\n        \"\"\"Create a new context.\"\"\"\n        context = super().new_context()\n        context.attributes = attributes\n        context.metas = metas\n        return context\n\n    def open_context(self, widget, domain):\n        if domain is None:\n            return None, False\n\n        if not isinstance(domain, Domain):\n            domain = domain.domain\n\n        super().open_context(widget, domain, *self.encode_domain(domain))\n\n    def filter_value(self, setting, data, domain, attrs, metas):\n        value = data.get(setting.name, None)\n        if isinstance(value, list):\n            new_value = [item for item in value\n                         if self.is_valid_item(setting, item, attrs, metas)]\n            data[setting.name] = new_value\n        elif value is not None:\n            if (value[1] >= 0 and\n                    not self._var_exists(setting, value, attrs, metas)):\n                del data[setting.name]\n\n    def settings_to_widget(self, widget, domain, *args):\n        context = widget.current_context\n        if context is None:\n            return\n\n        widget.retrieveSpecificSettings()\n\n        for setting, data, instance in \\\n                self.provider.traverse_settings(data=context.values, instance=widget):\n            if not isinstance(setting, ContextSetting) or setting.name not in data:\n                continue\n\n            value = self.decode_setting(setting, data[setting.name], domain)\n            _apply_setting(setting, instance, value)\n\n    @staticmethod\n    def encode_variable(var):\n        return var.name, 100 + vartype(var)\n\n    @classmethod\n    def encode_setting(cls, context, setting, value):\n        if isinstance(value, list):\n            if all(e is None or isinstance(e, Variable) for e in value) \\\n                    and any(e is not None for e in value):\n                return [None if e is None else cls.encode_variable(e)\n                        for e in value], -3\n            else:\n                return copy.copy(value)\n\n        if isinstance(setting, ContextSetting):\n            if isinstance(value, str):\n                variables = {\n                    **({} if setting.exclude_attributes else context.attributes),\n                    **({} if setting.exclude_metas else context.metas)}\n                if value in variables:\n                    cls._warn_about_str_var_settings(setting)\n                    return value, variables[value]\n            elif isinstance(value, Variable):\n                return cls.encode_variable(value)\n\n        return copy.copy(value), -2\n\n    def decode_setting(self, setting, value, domain=None):\n        if isinstance(value, tuple):\n            if value[1] == -3:\n                return [None if e is None else domain[e[0]] for e in value[0]]\n            if value[1] >= 100:\n                if domain is None:\n                    raise ValueError(\"Cannot decode variable without domain\")\n                return domain[value[0]]\n            return value[0]\n        else:\n            return value\n\n    @classmethod\n    def _var_exists(cls, setting, value, attributes, metas):\n        if not isinstance(value, tuple) or len(value) != 2:\n            return False\n\n        attr_name, attr_type = value\n        if attr_type >= 100:\n            attr_type -= 100\n        else:\n            cls._warn_about_str_var_settings(setting)\n        return (not setting.exclude_attributes and\n                attributes.get(attr_name, -1) == attr_type or\n                not setting.exclude_metas and\n                metas.get(attr_name, -1) == attr_type)\n\n    def match(self, context, domain, attrs, metas):\n        if (attrs, metas) == (context.attributes, context.metas):\n            return self.PERFECT_MATCH\n\n        matches = []\n        try:\n            for setting, data, _ in \\\n                    self.provider.traverse_settings(data=context.values):\n                if not isinstance(setting, ContextSetting):\n                    continue\n                value = data.get(setting.name, None)\n\n                if isinstance(value, list):\n                    matches.append(\n                        self.match_list(setting, value, context, attrs, metas))\n                elif isinstance(value, tuple) \\\n                        and len(value) == 2 \\\n                        and isinstance(value[0], list) \\\n                        and value[1] == -3:\n                    matches.append(\n                        self.match_list(setting, value[0], context, attrs, metas))\n                elif value is not None:\n                    matches.append(\n                        self.match_value(setting, value, attrs, metas))\n        except IncompatibleContext:\n            return self.NO_MATCH\n\n        matches.append((0, 0))\n        matched, available = [sum(m) for m in zip(*matches)]\n\n        return matched / available if available else 0.1\n\n    def match_list(self, setting, value, context, attrs, metas):\n        \"\"\"Match a list of values with the given context.\n        returns a tuple containing number of matched and all values.\n        \"\"\"\n        matched = 0\n        for i, item in enumerate(value):\n            if self.is_valid_item(setting, item, attrs, metas):\n                matched += 1\n            elif setting.required == ContextSetting.REQUIRED:\n                raise IncompatibleContext()\n        return matched, len(value)\n\n    def match_value(self, setting, value, attrs, metas):\n        \"\"\"Match a single value \"\"\"\n        if value[1] < 0:\n            return 0, 0\n\n        if self._var_exists(setting, value, attrs, metas):\n            return 1, 1\n        elif setting.required == setting.OPTIONAL:\n            return 0, 1\n        else:\n            raise IncompatibleContext()\n\n    def is_valid_item(self, setting, item, attrs, metas):\n        \"\"\"Return True if given item can be used with attrs and metas\n\n        Subclasses can override this method to checks data in alternative\n        representations.\n        \"\"\"\n        if not isinstance(item, tuple):\n            return True\n        return self._var_exists(setting, item, attrs, metas)",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 941,
                            "end_lineno": 945,
                            "parent": {
                                "file_name": "Orange/widgets/settings.py",
                                "type": "class",
                                "name": "DomainContextHandler",
                                "content": "class DomainContextHandler(ContextHandler):\n    \"\"\"Context handler for widgets with settings that depend on\n    the input dataset. Suitable settings are selected based on the\n    data domain.\"\"\"\n\n    MATCH_VALUES_NONE, MATCH_VALUES_CLASS, MATCH_VALUES_ALL = range(3)\n\n    def __init__(self, *, match_values=0, **kwargs):\n        super().__init__()\n        self.match_values = match_values\n\n        for name in kwargs:\n            warnings.warn(\n                \"{} is not a valid parameter for DomainContextHandler\"\n                .format(name), OrangeDeprecationWarning\n            )\n\n    @staticmethod\n    def _warn_about_str_var_settings(setting):\n        warnings.warn(\n            \"Storing variables as strings in settings is deprecated.\\n\"\n            \"Support for this will be dropped in Orange 3.26.\\n\"\n            f\"Change f{setting.name} to store an instance of `Variable`.\")\n\n    def encode_domain(self, domain):\n        \"\"\"\n        domain: Orange.data.domain to encode\n        return: dict mapping attribute name to type or list of values\n                (based on the value of self.match_values attribute)\n        \"\"\"\n\n        match = self.match_values\n        encode = self.encode_variables\n        if match == self.MATCH_VALUES_CLASS:\n            attributes = encode(domain.attributes, False)\n            attributes.update(encode(domain.class_vars, True))\n        else:\n            attributes = encode(domain.variables, match == self.MATCH_VALUES_ALL)\n\n        metas = encode(domain.metas, match == self.MATCH_VALUES_ALL)\n\n        return attributes, metas\n\n    @staticmethod\n    def encode_variables(attributes, encode_values):\n        \"\"\"Encode variables to a list mapping name to variable type\n        or a list of values.\"\"\"\n\n        if not encode_values:\n            return {v.name: vartype(v) for v in attributes}\n\n        return {v.name: v.values if v.is_discrete else vartype(v)\n                for v in attributes}\n\n    def new_context(self, domain, attributes, metas):\n        \"\"\"Create a new context.\"\"\"\n        context = super().new_context()\n        context.attributes = attributes\n        context.metas = metas\n        return context\n\n    def open_context(self, widget, domain):\n        if domain is None:\n            return None, False\n\n        if not isinstance(domain, Domain):\n            domain = domain.domain\n\n        super().open_context(widget, domain, *self.encode_domain(domain))\n\n    def filter_value(self, setting, data, domain, attrs, metas):\n        value = data.get(setting.name, None)\n        if isinstance(value, list):\n            new_value = [item for item in value\n                         if self.is_valid_item(setting, item, attrs, metas)]\n            data[setting.name] = new_value\n        elif value is not None:\n            if (value[1] >= 0 and\n                    not self._var_exists(setting, value, attrs, metas)):\n                del data[setting.name]\n\n    def settings_to_widget(self, widget, domain, *args):\n        context = widget.current_context\n        if context is None:\n            return\n\n        widget.retrieveSpecificSettings()\n\n        for setting, data, instance in \\\n                self.provider.traverse_settings(data=context.values, instance=widget):\n            if not isinstance(setting, ContextSetting) or setting.name not in data:\n                continue\n\n            value = self.decode_setting(setting, data[setting.name], domain)\n            _apply_setting(setting, instance, value)\n\n    @staticmethod\n    def encode_variable(var):\n        return var.name, 100 + vartype(var)\n\n    @classmethod\n    def encode_setting(cls, context, setting, value):\n        if isinstance(value, list):\n            if all(e is None or isinstance(e, Variable) for e in value) \\\n                    and any(e is not None for e in value):\n                return [None if e is None else cls.encode_variable(e)\n                        for e in value], -3\n            else:\n                return copy.copy(value)\n\n        if isinstance(setting, ContextSetting):\n            if isinstance(value, str):\n                variables = {\n                    **({} if setting.exclude_attributes else context.attributes),\n                    **({} if setting.exclude_metas else context.metas)}\n                if value in variables:\n                    cls._warn_about_str_var_settings(setting)\n                    return value, variables[value]\n            elif isinstance(value, Variable):\n                return cls.encode_variable(value)\n\n        return copy.copy(value), -2\n\n    def decode_setting(self, setting, value, domain=None):\n        if isinstance(value, tuple):\n            if value[1] == -3:\n                return [None if e is None else domain[e[0]] for e in value[0]]\n            if value[1] >= 100:\n                if domain is None:\n                    raise ValueError(\"Cannot decode variable without domain\")\n                return domain[value[0]]\n            return value[0]\n        else:\n            return value\n\n    @classmethod\n    def _var_exists(cls, setting, value, attributes, metas):\n        if not isinstance(value, tuple) or len(value) != 2:\n            return False\n\n        attr_name, attr_type = value\n        if attr_type >= 100:\n            attr_type -= 100\n        else:\n            cls._warn_about_str_var_settings(setting)\n        return (not setting.exclude_attributes and\n                attributes.get(attr_name, -1) == attr_type or\n                not setting.exclude_metas and\n                metas.get(attr_name, -1) == attr_type)\n\n    def match(self, context, domain, attrs, metas):\n        if (attrs, metas) == (context.attributes, context.metas):\n            return self.PERFECT_MATCH\n\n        matches = []\n        try:\n            for setting, data, _ in \\\n                    self.provider.traverse_settings(data=context.values):\n                if not isinstance(setting, ContextSetting):\n                    continue\n                value = data.get(setting.name, None)\n\n                if isinstance(value, list):\n                    matches.append(\n                        self.match_list(setting, value, context, attrs, metas))\n                elif isinstance(value, tuple) \\\n                        and len(value) == 2 \\\n                        and isinstance(value[0], list) \\\n                        and value[1] == -3:\n                    matches.append(\n                        self.match_list(setting, value[0], context, attrs, metas))\n                elif value is not None:\n                    matches.append(\n                        self.match_value(setting, value, attrs, metas))\n        except IncompatibleContext:\n            return self.NO_MATCH\n\n        matches.append((0, 0))\n        matched, available = [sum(m) for m in zip(*matches)]\n\n        return matched / available if available else 0.1\n\n    def match_list(self, setting, value, context, attrs, metas):\n        \"\"\"Match a list of values with the given context.\n        returns a tuple containing number of matched and all values.\n        \"\"\"\n        matched = 0\n        for i, item in enumerate(value):\n            if self.is_valid_item(setting, item, attrs, metas):\n                matched += 1\n            elif setting.required == ContextSetting.REQUIRED:\n                raise IncompatibleContext()\n        return matched, len(value)\n\n    def match_value(self, setting, value, attrs, metas):\n        \"\"\"Match a single value \"\"\"\n        if value[1] < 0:\n            return 0, 0\n\n        if self._var_exists(setting, value, attrs, metas):\n            return 1, 1\n        elif setting.required == setting.OPTIONAL:\n            return 0, 1\n        else:\n            raise IncompatibleContext()\n\n    def is_valid_item(self, setting, item, attrs, metas):\n        \"\"\"Return True if given item can be used with attrs and metas\n\n        Subclasses can override this method to checks data in alternative\n        representations.\n        \"\"\"\n        if not isinstance(item, tuple):\n            return True\n        return self._var_exists(setting, item, attrs, metas)",
                                "ast_type_str": "ClassDef",
                                "start_lineno": 923,
                                "end_lineno": 1137,
                                "parent": null
                            }
                        }
                    ],
                    "deleted_entities": []
                },
                {
                    "descriptor": {
                        "old_range": {
                            "start": 1013,
                            "length": 23
                        },
                        "new_range": {
                            "start": 1020,
                            "length": 26
                        },
                        "section": "class DomainContextHandler(ContextHandler):"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "    def encode_variable(var):",
                                "type": "context"
                            },
                            {
                                "content": "        return var.name, 100 + vartype(var)",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "    def encode_setting(self, context, setting, value):",
                                "type": "deleted"
                            },
                            {
                                "content": "    @classmethod",
                                "type": "added"
                            },
                            {
                                "content": "    def encode_setting(cls, context, setting, value):",
                                "type": "added"
                            },
                            {
                                "content": "        if isinstance(value, list):",
                                "type": "context"
                            },
                            {
                                "content": "            if all(e is None or isinstance(e, Variable) for e in value) \\",
                                "type": "context"
                            },
                            {
                                "content": "                    and any(e is not None for e in value):",
                                "type": "context"
                            },
                            {
                                "content": "                return [None if e is None else self.encode_variable(e)",
                                "type": "deleted"
                            },
                            {
                                "content": "                return [None if e is None else cls.encode_variable(e)",
                                "type": "added"
                            },
                            {
                                "content": "                        for e in value], -3",
                                "type": "context"
                            },
                            {
                                "content": "            else:",
                                "type": "context"
                            },
                            {
                                "content": "                return copy.copy(value)",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "        if isinstance(setting, ContextSetting):",
                                "type": "context"
                            },
                            {
                                "content": "            if isinstance(value, str):",
                                "type": "context"
                            },
                            {
                                "content": "                if not setting.exclude_attributes and value in context.attributes:",
                                "type": "deleted"
                            },
                            {
                                "content": "                    return value, context.attributes[value]",
                                "type": "deleted"
                            },
                            {
                                "content": "                if not setting.exclude_metas and value in context.metas:",
                                "type": "deleted"
                            },
                            {
                                "content": "                    return value, context.metas[value]",
                                "type": "deleted"
                            },
                            {
                                "content": "                variables = {",
                                "type": "added"
                            },
                            {
                                "content": "                    **({} if setting.exclude_attributes else context.attributes),",
                                "type": "added"
                            },
                            {
                                "content": "                    **({} if setting.exclude_metas else context.metas)}",
                                "type": "added"
                            },
                            {
                                "content": "                if value in variables:",
                                "type": "added"
                            },
                            {
                                "content": "                    cls._warn_about_str_var_settings(setting)",
                                "type": "added"
                            },
                            {
                                "content": "                    return value, variables[value]",
                                "type": "added"
                            },
                            {
                                "content": "            elif isinstance(value, Variable):",
                                "type": "context"
                            },
                            {
                                "content": "                return self.encode_variable(value)",
                                "type": "deleted"
                            },
                            {
                                "content": "                return cls.encode_variable(value)",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "        return copy.copy(value), -2",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [
                        {
                            "file_name": "Orange/widgets/settings.py",
                            "type": "class",
                            "name": "DomainContextHandler",
                            "content": "class DomainContextHandler(ContextHandler):\n    \"\"\"Context handler for widgets with settings that depend on\n    the input dataset. Suitable settings are selected based on the\n    data domain.\"\"\"\n\n    MATCH_VALUES_NONE, MATCH_VALUES_CLASS, MATCH_VALUES_ALL = range(3)\n\n    def __init__(self, *, match_values=0, **kwargs):\n        super().__init__()\n        self.match_values = match_values\n\n        for name in kwargs:\n            warnings.warn(\n                \"{} is not a valid parameter for DomainContextHandler\"\n                .format(name), OrangeDeprecationWarning\n            )\n\n    def encode_domain(self, domain):\n        \"\"\"\n        domain: Orange.data.domain to encode\n        return: dict mapping attribute name to type or list of values\n                (based on the value of self.match_values attribute)\n        \"\"\"\n\n        match = self.match_values\n        encode = self.encode_variables\n        if match == self.MATCH_VALUES_CLASS:\n            attributes = encode(domain.attributes, False)\n            attributes.update(encode(domain.class_vars, True))\n        else:\n            attributes = encode(domain.variables, match == self.MATCH_VALUES_ALL)\n\n        metas = encode(domain.metas, match == self.MATCH_VALUES_ALL)\n\n        return attributes, metas\n\n    @staticmethod\n    def encode_variables(attributes, encode_values):\n        \"\"\"Encode variables to a list mapping name to variable type\n        or a list of values.\"\"\"\n\n        if not encode_values:\n            return {v.name: vartype(v) for v in attributes}\n\n        return {v.name: v.values if v.is_discrete else vartype(v)\n                for v in attributes}\n\n    def new_context(self, domain, attributes, metas):\n        \"\"\"Create a new context.\"\"\"\n        context = super().new_context()\n        context.attributes = attributes\n        context.metas = metas\n        return context\n\n    def open_context(self, widget, domain):\n        if domain is None:\n            return None, False\n\n        if not isinstance(domain, Domain):\n            domain = domain.domain\n\n        super().open_context(widget, domain, *self.encode_domain(domain))\n\n    def filter_value(self, setting, data, domain, attrs, metas):\n        value = data.get(setting.name, None)\n        if isinstance(value, list):\n            new_value = [item for item in value\n                         if self.is_valid_item(setting, item, attrs, metas)]\n            data[setting.name] = new_value\n        elif value is not None:\n            if (value[1] >= 0 and\n                    not self._var_exists(setting, value, attrs, metas)):\n                del data[setting.name]\n\n    def settings_to_widget(self, widget, domain, *args):\n        context = widget.current_context\n        if context is None:\n            return\n\n        widget.retrieveSpecificSettings()\n\n        for setting, data, instance in \\\n                self.provider.traverse_settings(data=context.values, instance=widget):\n            if not isinstance(setting, ContextSetting) or setting.name not in data:\n                continue\n\n            value = self.decode_setting(setting, data[setting.name], domain)\n            _apply_setting(setting, instance, value)\n\n    @staticmethod\n    def encode_variable(var):\n        return var.name, 100 + vartype(var)\n\n    def encode_setting(self, context, setting, value):\n        if isinstance(value, list):\n            if all(e is None or isinstance(e, Variable) for e in value) \\\n                    and any(e is not None for e in value):\n                return [None if e is None else self.encode_variable(e)\n                        for e in value], -3\n            else:\n                return copy.copy(value)\n\n        if isinstance(setting, ContextSetting):\n            if isinstance(value, str):\n                if not setting.exclude_attributes and value in context.attributes:\n                    return value, context.attributes[value]\n                if not setting.exclude_metas and value in context.metas:\n                    return value, context.metas[value]\n            elif isinstance(value, Variable):\n                return self.encode_variable(value)\n\n        return copy.copy(value), -2\n\n    def decode_setting(self, setting, value, domain=None):\n        if isinstance(value, tuple):\n            if value[1] == -3:\n                return [None if e is None else domain[e[0]] for e in value[0]]\n            if value[1] >= 100:\n                if domain is None:\n                    raise ValueError(\"Cannot decode variable without domain\")\n                return domain[value[0]]\n            return value[0]\n        else:\n            return value\n\n    @staticmethod\n    def _var_exists(setting, value, attributes, metas):\n        if not isinstance(value, tuple) or len(value) != 2:\n            return False\n\n        attr_name, attr_type = value\n        if attr_type >= 100:\n            attr_type -= 100\n        return (not setting.exclude_attributes and\n                attributes.get(attr_name, -1) == attr_type or\n                not setting.exclude_metas and\n                metas.get(attr_name, -1) == attr_type)\n\n    def match(self, context, domain, attrs, metas):\n        if (attrs, metas) == (context.attributes, context.metas):\n            return self.PERFECT_MATCH\n\n        matches = []\n        try:\n            for setting, data, _ in \\\n                    self.provider.traverse_settings(data=context.values):\n                if not isinstance(setting, ContextSetting):\n                    continue\n                value = data.get(setting.name, None)\n\n                if isinstance(value, list):\n                    matches.append(\n                        self.match_list(setting, value, context, attrs, metas))\n                elif isinstance(value, tuple) \\\n                        and len(value) == 2 \\\n                        and isinstance(value[0], list) \\\n                        and value[1] == -3:\n                    matches.append(\n                        self.match_list(setting, value[0], context, attrs, metas))\n                elif value is not None:\n                    matches.append(\n                        self.match_value(setting, value, attrs, metas))\n        except IncompatibleContext:\n            return self.NO_MATCH\n\n        matches.append((0, 0))\n        matched, available = [sum(m) for m in zip(*matches)]\n\n        return matched / available if available else 0.1\n\n    def match_list(self, setting, value, context, attrs, metas):\n        \"\"\"Match a list of values with the given context.\n        returns a tuple containing number of matched and all values.\n        \"\"\"\n        matched = 0\n        for i, item in enumerate(value):\n            if self.is_valid_item(setting, item, attrs, metas):\n                matched += 1\n            elif setting.required == ContextSetting.REQUIRED:\n                raise IncompatibleContext()\n        return matched, len(value)\n\n    def match_value(self, setting, value, attrs, metas):\n        \"\"\"Match a single value \"\"\"\n        if value[1] < 0:\n            return 0, 0\n\n        if self._var_exists(setting, value, attrs, metas):\n            return 1, 1\n        elif setting.required == setting.OPTIONAL:\n            return 0, 1\n        else:\n            raise IncompatibleContext()\n\n    def is_valid_item(self, setting, item, attrs, metas):\n        \"\"\"Return True if given item can be used with attrs and metas\n\n        Subclasses can override this method to checks data in alternative\n        representations.\n        \"\"\"\n        if not isinstance(item, tuple):\n            return True\n        return self._var_exists(setting, item, attrs, metas)",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 923,
                            "end_lineno": 1125,
                            "parent": null
                        },
                        {
                            "file_name": "Orange/widgets/settings.py",
                            "type": "method",
                            "name": "DomainContextHandler.encode_setting",
                            "content": "class DomainContextHandler(ContextHandler):\n    \"\"\"Context handler for widgets with settings that depend on\n    the input dataset. Suitable settings are selected based on the\n    data domain.\"\"\"\n\n    MATCH_VALUES_NONE, MATCH_VALUES_CLASS, MATCH_VALUES_ALL = range(3)\n\n    def __init__(self, *, match_values=0, **kwargs):\n        super().__init__()\n        self.match_values = match_values\n\n        for name in kwargs:\n            warnings.warn(\n                \"{} is not a valid parameter for DomainContextHandler\"\n                .format(name), OrangeDeprecationWarning\n            )\n\n    def encode_domain(self, domain):\n        \"\"\"\n        domain: Orange.data.domain to encode\n        return: dict mapping attribute name to type or list of values\n                (based on the value of self.match_values attribute)\n        \"\"\"\n\n        match = self.match_values\n        encode = self.encode_variables\n        if match == self.MATCH_VALUES_CLASS:\n            attributes = encode(domain.attributes, False)\n            attributes.update(encode(domain.class_vars, True))\n        else:\n            attributes = encode(domain.variables, match == self.MATCH_VALUES_ALL)\n\n        metas = encode(domain.metas, match == self.MATCH_VALUES_ALL)\n\n        return attributes, metas\n\n    @staticmethod\n    def encode_variables(attributes, encode_values):\n        \"\"\"Encode variables to a list mapping name to variable type\n        or a list of values.\"\"\"\n\n        if not encode_values:\n            return {v.name: vartype(v) for v in attributes}\n\n        return {v.name: v.values if v.is_discrete else vartype(v)\n                for v in attributes}\n\n    def new_context(self, domain, attributes, metas):\n        \"\"\"Create a new context.\"\"\"\n        context = super().new_context()\n        context.attributes = attributes\n        context.metas = metas\n        return context\n\n    def open_context(self, widget, domain):\n        if domain is None:\n            return None, False\n\n        if not isinstance(domain, Domain):\n            domain = domain.domain\n\n        super().open_context(widget, domain, *self.encode_domain(domain))\n\n    def filter_value(self, setting, data, domain, attrs, metas):\n        value = data.get(setting.name, None)\n        if isinstance(value, list):\n            new_value = [item for item in value\n                         if self.is_valid_item(setting, item, attrs, metas)]\n            data[setting.name] = new_value\n        elif value is not None:\n            if (value[1] >= 0 and\n                    not self._var_exists(setting, value, attrs, metas)):\n                del data[setting.name]\n\n    def settings_to_widget(self, widget, domain, *args):\n        context = widget.current_context\n        if context is None:\n            return\n\n        widget.retrieveSpecificSettings()\n\n        for setting, data, instance in \\\n                self.provider.traverse_settings(data=context.values, instance=widget):\n            if not isinstance(setting, ContextSetting) or setting.name not in data:\n                continue\n\n            value = self.decode_setting(setting, data[setting.name], domain)\n            _apply_setting(setting, instance, value)\n\n    @staticmethod\n    def encode_variable(var):\n        return var.name, 100 + vartype(var)\n\n    def encode_setting(self, context, setting, value):\n        if isinstance(value, list):\n            if all(e is None or isinstance(e, Variable) for e in value) \\\n                    and any(e is not None for e in value):\n                return [None if e is None else self.encode_variable(e)\n                        for e in value], -3\n            else:\n                return copy.copy(value)\n\n        if isinstance(setting, ContextSetting):\n            if isinstance(value, str):\n                if not setting.exclude_attributes and value in context.attributes:\n                    return value, context.attributes[value]\n                if not setting.exclude_metas and value in context.metas:\n                    return value, context.metas[value]\n            elif isinstance(value, Variable):\n                return self.encode_variable(value)\n\n        return copy.copy(value), -2\n\n    def decode_setting(self, setting, value, domain=None):\n        if isinstance(value, tuple):\n            if value[1] == -3:\n                return [None if e is None else domain[e[0]] for e in value[0]]\n            if value[1] >= 100:\n                if domain is None:\n                    raise ValueError(\"Cannot decode variable without domain\")\n                return domain[value[0]]\n            return value[0]\n        else:\n            return value\n\n    @staticmethod\n    def _var_exists(setting, value, attributes, metas):\n        if not isinstance(value, tuple) or len(value) != 2:\n            return False\n\n        attr_name, attr_type = value\n        if attr_type >= 100:\n            attr_type -= 100\n        return (not setting.exclude_attributes and\n                attributes.get(attr_name, -1) == attr_type or\n                not setting.exclude_metas and\n                metas.get(attr_name, -1) == attr_type)\n\n    def match(self, context, domain, attrs, metas):\n        if (attrs, metas) == (context.attributes, context.metas):\n            return self.PERFECT_MATCH\n\n        matches = []\n        try:\n            for setting, data, _ in \\\n                    self.provider.traverse_settings(data=context.values):\n                if not isinstance(setting, ContextSetting):\n                    continue\n                value = data.get(setting.name, None)\n\n                if isinstance(value, list):\n                    matches.append(\n                        self.match_list(setting, value, context, attrs, metas))\n                elif isinstance(value, tuple) \\\n                        and len(value) == 2 \\\n                        and isinstance(value[0], list) \\\n                        and value[1] == -3:\n                    matches.append(\n                        self.match_list(setting, value[0], context, attrs, metas))\n                elif value is not None:\n                    matches.append(\n                        self.match_value(setting, value, attrs, metas))\n        except IncompatibleContext:\n            return self.NO_MATCH\n\n        matches.append((0, 0))\n        matched, available = [sum(m) for m in zip(*matches)]\n\n        return matched / available if available else 0.1\n\n    def match_list(self, setting, value, context, attrs, metas):\n        \"\"\"Match a list of values with the given context.\n        returns a tuple containing number of matched and all values.\n        \"\"\"\n        matched = 0\n        for i, item in enumerate(value):\n            if self.is_valid_item(setting, item, attrs, metas):\n                matched += 1\n            elif setting.required == ContextSetting.REQUIRED:\n                raise IncompatibleContext()\n        return matched, len(value)\n\n    def match_value(self, setting, value, attrs, metas):\n        \"\"\"Match a single value \"\"\"\n        if value[1] < 0:\n            return 0, 0\n\n        if self._var_exists(setting, value, attrs, metas):\n            return 1, 1\n        elif setting.required == setting.OPTIONAL:\n            return 0, 1\n        else:\n            raise IncompatibleContext()\n\n    def is_valid_item(self, setting, item, attrs, metas):\n        \"\"\"Return True if given item can be used with attrs and metas\n\n        Subclasses can override this method to checks data in alternative\n        representations.\n        \"\"\"\n        if not isinstance(item, tuple):\n            return True\n        return self._var_exists(setting, item, attrs, metas)",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 1016,
                            "end_lineno": 1034,
                            "parent": {
                                "file_name": "Orange/widgets/settings.py",
                                "type": "class",
                                "name": "DomainContextHandler",
                                "content": "class DomainContextHandler(ContextHandler):\n    \"\"\"Context handler for widgets with settings that depend on\n    the input dataset. Suitable settings are selected based on the\n    data domain.\"\"\"\n\n    MATCH_VALUES_NONE, MATCH_VALUES_CLASS, MATCH_VALUES_ALL = range(3)\n\n    def __init__(self, *, match_values=0, **kwargs):\n        super().__init__()\n        self.match_values = match_values\n\n        for name in kwargs:\n            warnings.warn(\n                \"{} is not a valid parameter for DomainContextHandler\"\n                .format(name), OrangeDeprecationWarning\n            )\n\n    def encode_domain(self, domain):\n        \"\"\"\n        domain: Orange.data.domain to encode\n        return: dict mapping attribute name to type or list of values\n                (based on the value of self.match_values attribute)\n        \"\"\"\n\n        match = self.match_values\n        encode = self.encode_variables\n        if match == self.MATCH_VALUES_CLASS:\n            attributes = encode(domain.attributes, False)\n            attributes.update(encode(domain.class_vars, True))\n        else:\n            attributes = encode(domain.variables, match == self.MATCH_VALUES_ALL)\n\n        metas = encode(domain.metas, match == self.MATCH_VALUES_ALL)\n\n        return attributes, metas\n\n    @staticmethod\n    def encode_variables(attributes, encode_values):\n        \"\"\"Encode variables to a list mapping name to variable type\n        or a list of values.\"\"\"\n\n        if not encode_values:\n            return {v.name: vartype(v) for v in attributes}\n\n        return {v.name: v.values if v.is_discrete else vartype(v)\n                for v in attributes}\n\n    def new_context(self, domain, attributes, metas):\n        \"\"\"Create a new context.\"\"\"\n        context = super().new_context()\n        context.attributes = attributes\n        context.metas = metas\n        return context\n\n    def open_context(self, widget, domain):\n        if domain is None:\n            return None, False\n\n        if not isinstance(domain, Domain):\n            domain = domain.domain\n\n        super().open_context(widget, domain, *self.encode_domain(domain))\n\n    def filter_value(self, setting, data, domain, attrs, metas):\n        value = data.get(setting.name, None)\n        if isinstance(value, list):\n            new_value = [item for item in value\n                         if self.is_valid_item(setting, item, attrs, metas)]\n            data[setting.name] = new_value\n        elif value is not None:\n            if (value[1] >= 0 and\n                    not self._var_exists(setting, value, attrs, metas)):\n                del data[setting.name]\n\n    def settings_to_widget(self, widget, domain, *args):\n        context = widget.current_context\n        if context is None:\n            return\n\n        widget.retrieveSpecificSettings()\n\n        for setting, data, instance in \\\n                self.provider.traverse_settings(data=context.values, instance=widget):\n            if not isinstance(setting, ContextSetting) or setting.name not in data:\n                continue\n\n            value = self.decode_setting(setting, data[setting.name], domain)\n            _apply_setting(setting, instance, value)\n\n    @staticmethod\n    def encode_variable(var):\n        return var.name, 100 + vartype(var)\n\n    def encode_setting(self, context, setting, value):\n        if isinstance(value, list):\n            if all(e is None or isinstance(e, Variable) for e in value) \\\n                    and any(e is not None for e in value):\n                return [None if e is None else self.encode_variable(e)\n                        for e in value], -3\n            else:\n                return copy.copy(value)\n\n        if isinstance(setting, ContextSetting):\n            if isinstance(value, str):\n                if not setting.exclude_attributes and value in context.attributes:\n                    return value, context.attributes[value]\n                if not setting.exclude_metas and value in context.metas:\n                    return value, context.metas[value]\n            elif isinstance(value, Variable):\n                return self.encode_variable(value)\n\n        return copy.copy(value), -2\n\n    def decode_setting(self, setting, value, domain=None):\n        if isinstance(value, tuple):\n            if value[1] == -3:\n                return [None if e is None else domain[e[0]] for e in value[0]]\n            if value[1] >= 100:\n                if domain is None:\n                    raise ValueError(\"Cannot decode variable without domain\")\n                return domain[value[0]]\n            return value[0]\n        else:\n            return value\n\n    @staticmethod\n    def _var_exists(setting, value, attributes, metas):\n        if not isinstance(value, tuple) or len(value) != 2:\n            return False\n\n        attr_name, attr_type = value\n        if attr_type >= 100:\n            attr_type -= 100\n        return (not setting.exclude_attributes and\n                attributes.get(attr_name, -1) == attr_type or\n                not setting.exclude_metas and\n                metas.get(attr_name, -1) == attr_type)\n\n    def match(self, context, domain, attrs, metas):\n        if (attrs, metas) == (context.attributes, context.metas):\n            return self.PERFECT_MATCH\n\n        matches = []\n        try:\n            for setting, data, _ in \\\n                    self.provider.traverse_settings(data=context.values):\n                if not isinstance(setting, ContextSetting):\n                    continue\n                value = data.get(setting.name, None)\n\n                if isinstance(value, list):\n                    matches.append(\n                        self.match_list(setting, value, context, attrs, metas))\n                elif isinstance(value, tuple) \\\n                        and len(value) == 2 \\\n                        and isinstance(value[0], list) \\\n                        and value[1] == -3:\n                    matches.append(\n                        self.match_list(setting, value[0], context, attrs, metas))\n                elif value is not None:\n                    matches.append(\n                        self.match_value(setting, value, attrs, metas))\n        except IncompatibleContext:\n            return self.NO_MATCH\n\n        matches.append((0, 0))\n        matched, available = [sum(m) for m in zip(*matches)]\n\n        return matched / available if available else 0.1\n\n    def match_list(self, setting, value, context, attrs, metas):\n        \"\"\"Match a list of values with the given context.\n        returns a tuple containing number of matched and all values.\n        \"\"\"\n        matched = 0\n        for i, item in enumerate(value):\n            if self.is_valid_item(setting, item, attrs, metas):\n                matched += 1\n            elif setting.required == ContextSetting.REQUIRED:\n                raise IncompatibleContext()\n        return matched, len(value)\n\n    def match_value(self, setting, value, attrs, metas):\n        \"\"\"Match a single value \"\"\"\n        if value[1] < 0:\n            return 0, 0\n\n        if self._var_exists(setting, value, attrs, metas):\n            return 1, 1\n        elif setting.required == setting.OPTIONAL:\n            return 0, 1\n        else:\n            raise IncompatibleContext()\n\n    def is_valid_item(self, setting, item, attrs, metas):\n        \"\"\"Return True if given item can be used with attrs and metas\n\n        Subclasses can override this method to checks data in alternative\n        representations.\n        \"\"\"\n        if not isinstance(item, tuple):\n            return True\n        return self._var_exists(setting, item, attrs, metas)",
                                "ast_type_str": "ClassDef",
                                "start_lineno": 923,
                                "end_lineno": 1125,
                                "parent": null
                            }
                        }
                    ],
                    "added_entities": [],
                    "deleted_entities": []
                },
                {
                    "descriptor": {
                        "old_range": {
                            "start": 1045,
                            "length": 14
                        },
                        "new_range": {
                            "start": 1055,
                            "length": 16
                        },
                        "section": "class DomainContextHandler(ContextHandler):"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "        else:",
                                "type": "context"
                            },
                            {
                                "content": "            return value",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "    @staticmethod",
                                "type": "deleted"
                            },
                            {
                                "content": "    def _var_exists(setting, value, attributes, metas):",
                                "type": "deleted"
                            },
                            {
                                "content": "    @classmethod",
                                "type": "added"
                            },
                            {
                                "content": "    def _var_exists(cls, setting, value, attributes, metas):",
                                "type": "added"
                            },
                            {
                                "content": "        if not isinstance(value, tuple) or len(value) != 2:",
                                "type": "context"
                            },
                            {
                                "content": "            return False",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "        attr_name, attr_type = value",
                                "type": "context"
                            },
                            {
                                "content": "        if attr_type >= 100:",
                                "type": "context"
                            },
                            {
                                "content": "            attr_type -= 100",
                                "type": "context"
                            },
                            {
                                "content": "        else:",
                                "type": "added"
                            },
                            {
                                "content": "            cls._warn_about_str_var_settings(setting)",
                                "type": "added"
                            },
                            {
                                "content": "        return (not setting.exclude_attributes and",
                                "type": "context"
                            },
                            {
                                "content": "                attributes.get(attr_name, -1) == attr_type or",
                                "type": "context"
                            },
                            {
                                "content": "                not setting.exclude_metas and",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [
                        {
                            "file_name": "Orange/widgets/settings.py",
                            "type": "method",
                            "name": "DomainContextHandler._var_exists",
                            "content": "class DomainContextHandler(ContextHandler):\n    \"\"\"Context handler for widgets with settings that depend on\n    the input dataset. Suitable settings are selected based on the\n    data domain.\"\"\"\n\n    MATCH_VALUES_NONE, MATCH_VALUES_CLASS, MATCH_VALUES_ALL = range(3)\n\n    def __init__(self, *, match_values=0, **kwargs):\n        super().__init__()\n        self.match_values = match_values\n\n        for name in kwargs:\n            warnings.warn(\n                \"{} is not a valid parameter for DomainContextHandler\"\n                .format(name), OrangeDeprecationWarning\n            )\n\n    def encode_domain(self, domain):\n        \"\"\"\n        domain: Orange.data.domain to encode\n        return: dict mapping attribute name to type or list of values\n                (based on the value of self.match_values attribute)\n        \"\"\"\n\n        match = self.match_values\n        encode = self.encode_variables\n        if match == self.MATCH_VALUES_CLASS:\n            attributes = encode(domain.attributes, False)\n            attributes.update(encode(domain.class_vars, True))\n        else:\n            attributes = encode(domain.variables, match == self.MATCH_VALUES_ALL)\n\n        metas = encode(domain.metas, match == self.MATCH_VALUES_ALL)\n\n        return attributes, metas\n\n    @staticmethod\n    def encode_variables(attributes, encode_values):\n        \"\"\"Encode variables to a list mapping name to variable type\n        or a list of values.\"\"\"\n\n        if not encode_values:\n            return {v.name: vartype(v) for v in attributes}\n\n        return {v.name: v.values if v.is_discrete else vartype(v)\n                for v in attributes}\n\n    def new_context(self, domain, attributes, metas):\n        \"\"\"Create a new context.\"\"\"\n        context = super().new_context()\n        context.attributes = attributes\n        context.metas = metas\n        return context\n\n    def open_context(self, widget, domain):\n        if domain is None:\n            return None, False\n\n        if not isinstance(domain, Domain):\n            domain = domain.domain\n\n        super().open_context(widget, domain, *self.encode_domain(domain))\n\n    def filter_value(self, setting, data, domain, attrs, metas):\n        value = data.get(setting.name, None)\n        if isinstance(value, list):\n            new_value = [item for item in value\n                         if self.is_valid_item(setting, item, attrs, metas)]\n            data[setting.name] = new_value\n        elif value is not None:\n            if (value[1] >= 0 and\n                    not self._var_exists(setting, value, attrs, metas)):\n                del data[setting.name]\n\n    def settings_to_widget(self, widget, domain, *args):\n        context = widget.current_context\n        if context is None:\n            return\n\n        widget.retrieveSpecificSettings()\n\n        for setting, data, instance in \\\n                self.provider.traverse_settings(data=context.values, instance=widget):\n            if not isinstance(setting, ContextSetting) or setting.name not in data:\n                continue\n\n            value = self.decode_setting(setting, data[setting.name], domain)\n            _apply_setting(setting, instance, value)\n\n    @staticmethod\n    def encode_variable(var):\n        return var.name, 100 + vartype(var)\n\n    def encode_setting(self, context, setting, value):\n        if isinstance(value, list):\n            if all(e is None or isinstance(e, Variable) for e in value) \\\n                    and any(e is not None for e in value):\n                return [None if e is None else self.encode_variable(e)\n                        for e in value], -3\n            else:\n                return copy.copy(value)\n\n        if isinstance(setting, ContextSetting):\n            if isinstance(value, str):\n                if not setting.exclude_attributes and value in context.attributes:\n                    return value, context.attributes[value]\n                if not setting.exclude_metas and value in context.metas:\n                    return value, context.metas[value]\n            elif isinstance(value, Variable):\n                return self.encode_variable(value)\n\n        return copy.copy(value), -2\n\n    def decode_setting(self, setting, value, domain=None):\n        if isinstance(value, tuple):\n            if value[1] == -3:\n                return [None if e is None else domain[e[0]] for e in value[0]]\n            if value[1] >= 100:\n                if domain is None:\n                    raise ValueError(\"Cannot decode variable without domain\")\n                return domain[value[0]]\n            return value[0]\n        else:\n            return value\n\n    @staticmethod\n    def _var_exists(setting, value, attributes, metas):\n        if not isinstance(value, tuple) or len(value) != 2:\n            return False\n\n        attr_name, attr_type = value\n        if attr_type >= 100:\n            attr_type -= 100\n        return (not setting.exclude_attributes and\n                attributes.get(attr_name, -1) == attr_type or\n                not setting.exclude_metas and\n                metas.get(attr_name, -1) == attr_type)\n\n    def match(self, context, domain, attrs, metas):\n        if (attrs, metas) == (context.attributes, context.metas):\n            return self.PERFECT_MATCH\n\n        matches = []\n        try:\n            for setting, data, _ in \\\n                    self.provider.traverse_settings(data=context.values):\n                if not isinstance(setting, ContextSetting):\n                    continue\n                value = data.get(setting.name, None)\n\n                if isinstance(value, list):\n                    matches.append(\n                        self.match_list(setting, value, context, attrs, metas))\n                elif isinstance(value, tuple) \\\n                        and len(value) == 2 \\\n                        and isinstance(value[0], list) \\\n                        and value[1] == -3:\n                    matches.append(\n                        self.match_list(setting, value[0], context, attrs, metas))\n                elif value is not None:\n                    matches.append(\n                        self.match_value(setting, value, attrs, metas))\n        except IncompatibleContext:\n            return self.NO_MATCH\n\n        matches.append((0, 0))\n        matched, available = [sum(m) for m in zip(*matches)]\n\n        return matched / available if available else 0.1\n\n    def match_list(self, setting, value, context, attrs, metas):\n        \"\"\"Match a list of values with the given context.\n        returns a tuple containing number of matched and all values.\n        \"\"\"\n        matched = 0\n        for i, item in enumerate(value):\n            if self.is_valid_item(setting, item, attrs, metas):\n                matched += 1\n            elif setting.required == ContextSetting.REQUIRED:\n                raise IncompatibleContext()\n        return matched, len(value)\n\n    def match_value(self, setting, value, attrs, metas):\n        \"\"\"Match a single value \"\"\"\n        if value[1] < 0:\n            return 0, 0\n\n        if self._var_exists(setting, value, attrs, metas):\n            return 1, 1\n        elif setting.required == setting.OPTIONAL:\n            return 0, 1\n        else:\n            raise IncompatibleContext()\n\n    def is_valid_item(self, setting, item, attrs, metas):\n        \"\"\"Return True if given item can be used with attrs and metas\n\n        Subclasses can override this method to checks data in alternative\n        representations.\n        \"\"\"\n        if not isinstance(item, tuple):\n            return True\n        return self._var_exists(setting, item, attrs, metas)",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 1049,
                            "end_lineno": 1059,
                            "parent": {
                                "file_name": "Orange/widgets/settings.py",
                                "type": "class",
                                "name": "DomainContextHandler",
                                "content": "class DomainContextHandler(ContextHandler):\n    \"\"\"Context handler for widgets with settings that depend on\n    the input dataset. Suitable settings are selected based on the\n    data domain.\"\"\"\n\n    MATCH_VALUES_NONE, MATCH_VALUES_CLASS, MATCH_VALUES_ALL = range(3)\n\n    def __init__(self, *, match_values=0, **kwargs):\n        super().__init__()\n        self.match_values = match_values\n\n        for name in kwargs:\n            warnings.warn(\n                \"{} is not a valid parameter for DomainContextHandler\"\n                .format(name), OrangeDeprecationWarning\n            )\n\n    def encode_domain(self, domain):\n        \"\"\"\n        domain: Orange.data.domain to encode\n        return: dict mapping attribute name to type or list of values\n                (based on the value of self.match_values attribute)\n        \"\"\"\n\n        match = self.match_values\n        encode = self.encode_variables\n        if match == self.MATCH_VALUES_CLASS:\n            attributes = encode(domain.attributes, False)\n            attributes.update(encode(domain.class_vars, True))\n        else:\n            attributes = encode(domain.variables, match == self.MATCH_VALUES_ALL)\n\n        metas = encode(domain.metas, match == self.MATCH_VALUES_ALL)\n\n        return attributes, metas\n\n    @staticmethod\n    def encode_variables(attributes, encode_values):\n        \"\"\"Encode variables to a list mapping name to variable type\n        or a list of values.\"\"\"\n\n        if not encode_values:\n            return {v.name: vartype(v) for v in attributes}\n\n        return {v.name: v.values if v.is_discrete else vartype(v)\n                for v in attributes}\n\n    def new_context(self, domain, attributes, metas):\n        \"\"\"Create a new context.\"\"\"\n        context = super().new_context()\n        context.attributes = attributes\n        context.metas = metas\n        return context\n\n    def open_context(self, widget, domain):\n        if domain is None:\n            return None, False\n\n        if not isinstance(domain, Domain):\n            domain = domain.domain\n\n        super().open_context(widget, domain, *self.encode_domain(domain))\n\n    def filter_value(self, setting, data, domain, attrs, metas):\n        value = data.get(setting.name, None)\n        if isinstance(value, list):\n            new_value = [item for item in value\n                         if self.is_valid_item(setting, item, attrs, metas)]\n            data[setting.name] = new_value\n        elif value is not None:\n            if (value[1] >= 0 and\n                    not self._var_exists(setting, value, attrs, metas)):\n                del data[setting.name]\n\n    def settings_to_widget(self, widget, domain, *args):\n        context = widget.current_context\n        if context is None:\n            return\n\n        widget.retrieveSpecificSettings()\n\n        for setting, data, instance in \\\n                self.provider.traverse_settings(data=context.values, instance=widget):\n            if not isinstance(setting, ContextSetting) or setting.name not in data:\n                continue\n\n            value = self.decode_setting(setting, data[setting.name], domain)\n            _apply_setting(setting, instance, value)\n\n    @staticmethod\n    def encode_variable(var):\n        return var.name, 100 + vartype(var)\n\n    def encode_setting(self, context, setting, value):\n        if isinstance(value, list):\n            if all(e is None or isinstance(e, Variable) for e in value) \\\n                    and any(e is not None for e in value):\n                return [None if e is None else self.encode_variable(e)\n                        for e in value], -3\n            else:\n                return copy.copy(value)\n\n        if isinstance(setting, ContextSetting):\n            if isinstance(value, str):\n                if not setting.exclude_attributes and value in context.attributes:\n                    return value, context.attributes[value]\n                if not setting.exclude_metas and value in context.metas:\n                    return value, context.metas[value]\n            elif isinstance(value, Variable):\n                return self.encode_variable(value)\n\n        return copy.copy(value), -2\n\n    def decode_setting(self, setting, value, domain=None):\n        if isinstance(value, tuple):\n            if value[1] == -3:\n                return [None if e is None else domain[e[0]] for e in value[0]]\n            if value[1] >= 100:\n                if domain is None:\n                    raise ValueError(\"Cannot decode variable without domain\")\n                return domain[value[0]]\n            return value[0]\n        else:\n            return value\n\n    @staticmethod\n    def _var_exists(setting, value, attributes, metas):\n        if not isinstance(value, tuple) or len(value) != 2:\n            return False\n\n        attr_name, attr_type = value\n        if attr_type >= 100:\n            attr_type -= 100\n        return (not setting.exclude_attributes and\n                attributes.get(attr_name, -1) == attr_type or\n                not setting.exclude_metas and\n                metas.get(attr_name, -1) == attr_type)\n\n    def match(self, context, domain, attrs, metas):\n        if (attrs, metas) == (context.attributes, context.metas):\n            return self.PERFECT_MATCH\n\n        matches = []\n        try:\n            for setting, data, _ in \\\n                    self.provider.traverse_settings(data=context.values):\n                if not isinstance(setting, ContextSetting):\n                    continue\n                value = data.get(setting.name, None)\n\n                if isinstance(value, list):\n                    matches.append(\n                        self.match_list(setting, value, context, attrs, metas))\n                elif isinstance(value, tuple) \\\n                        and len(value) == 2 \\\n                        and isinstance(value[0], list) \\\n                        and value[1] == -3:\n                    matches.append(\n                        self.match_list(setting, value[0], context, attrs, metas))\n                elif value is not None:\n                    matches.append(\n                        self.match_value(setting, value, attrs, metas))\n        except IncompatibleContext:\n            return self.NO_MATCH\n\n        matches.append((0, 0))\n        matched, available = [sum(m) for m in zip(*matches)]\n\n        return matched / available if available else 0.1\n\n    def match_list(self, setting, value, context, attrs, metas):\n        \"\"\"Match a list of values with the given context.\n        returns a tuple containing number of matched and all values.\n        \"\"\"\n        matched = 0\n        for i, item in enumerate(value):\n            if self.is_valid_item(setting, item, attrs, metas):\n                matched += 1\n            elif setting.required == ContextSetting.REQUIRED:\n                raise IncompatibleContext()\n        return matched, len(value)\n\n    def match_value(self, setting, value, attrs, metas):\n        \"\"\"Match a single value \"\"\"\n        if value[1] < 0:\n            return 0, 0\n\n        if self._var_exists(setting, value, attrs, metas):\n            return 1, 1\n        elif setting.required == setting.OPTIONAL:\n            return 0, 1\n        else:\n            raise IncompatibleContext()\n\n    def is_valid_item(self, setting, item, attrs, metas):\n        \"\"\"Return True if given item can be used with attrs and metas\n\n        Subclasses can override this method to checks data in alternative\n        representations.\n        \"\"\"\n        if not isinstance(item, tuple):\n            return True\n        return self._var_exists(setting, item, attrs, metas)",
                                "ast_type_str": "ClassDef",
                                "start_lineno": 923,
                                "end_lineno": 1125,
                                "parent": null
                            }
                        },
                        {
                            "file_name": "Orange/widgets/settings.py",
                            "type": "class",
                            "name": "DomainContextHandler",
                            "content": "class DomainContextHandler(ContextHandler):\n    \"\"\"Context handler for widgets with settings that depend on\n    the input dataset. Suitable settings are selected based on the\n    data domain.\"\"\"\n\n    MATCH_VALUES_NONE, MATCH_VALUES_CLASS, MATCH_VALUES_ALL = range(3)\n\n    def __init__(self, *, match_values=0, **kwargs):\n        super().__init__()\n        self.match_values = match_values\n\n        for name in kwargs:\n            warnings.warn(\n                \"{} is not a valid parameter for DomainContextHandler\"\n                .format(name), OrangeDeprecationWarning\n            )\n\n    def encode_domain(self, domain):\n        \"\"\"\n        domain: Orange.data.domain to encode\n        return: dict mapping attribute name to type or list of values\n                (based on the value of self.match_values attribute)\n        \"\"\"\n\n        match = self.match_values\n        encode = self.encode_variables\n        if match == self.MATCH_VALUES_CLASS:\n            attributes = encode(domain.attributes, False)\n            attributes.update(encode(domain.class_vars, True))\n        else:\n            attributes = encode(domain.variables, match == self.MATCH_VALUES_ALL)\n\n        metas = encode(domain.metas, match == self.MATCH_VALUES_ALL)\n\n        return attributes, metas\n\n    @staticmethod\n    def encode_variables(attributes, encode_values):\n        \"\"\"Encode variables to a list mapping name to variable type\n        or a list of values.\"\"\"\n\n        if not encode_values:\n            return {v.name: vartype(v) for v in attributes}\n\n        return {v.name: v.values if v.is_discrete else vartype(v)\n                for v in attributes}\n\n    def new_context(self, domain, attributes, metas):\n        \"\"\"Create a new context.\"\"\"\n        context = super().new_context()\n        context.attributes = attributes\n        context.metas = metas\n        return context\n\n    def open_context(self, widget, domain):\n        if domain is None:\n            return None, False\n\n        if not isinstance(domain, Domain):\n            domain = domain.domain\n\n        super().open_context(widget, domain, *self.encode_domain(domain))\n\n    def filter_value(self, setting, data, domain, attrs, metas):\n        value = data.get(setting.name, None)\n        if isinstance(value, list):\n            new_value = [item for item in value\n                         if self.is_valid_item(setting, item, attrs, metas)]\n            data[setting.name] = new_value\n        elif value is not None:\n            if (value[1] >= 0 and\n                    not self._var_exists(setting, value, attrs, metas)):\n                del data[setting.name]\n\n    def settings_to_widget(self, widget, domain, *args):\n        context = widget.current_context\n        if context is None:\n            return\n\n        widget.retrieveSpecificSettings()\n\n        for setting, data, instance in \\\n                self.provider.traverse_settings(data=context.values, instance=widget):\n            if not isinstance(setting, ContextSetting) or setting.name not in data:\n                continue\n\n            value = self.decode_setting(setting, data[setting.name], domain)\n            _apply_setting(setting, instance, value)\n\n    @staticmethod\n    def encode_variable(var):\n        return var.name, 100 + vartype(var)\n\n    def encode_setting(self, context, setting, value):\n        if isinstance(value, list):\n            if all(e is None or isinstance(e, Variable) for e in value) \\\n                    and any(e is not None for e in value):\n                return [None if e is None else self.encode_variable(e)\n                        for e in value], -3\n            else:\n                return copy.copy(value)\n\n        if isinstance(setting, ContextSetting):\n            if isinstance(value, str):\n                if not setting.exclude_attributes and value in context.attributes:\n                    return value, context.attributes[value]\n                if not setting.exclude_metas and value in context.metas:\n                    return value, context.metas[value]\n            elif isinstance(value, Variable):\n                return self.encode_variable(value)\n\n        return copy.copy(value), -2\n\n    def decode_setting(self, setting, value, domain=None):\n        if isinstance(value, tuple):\n            if value[1] == -3:\n                return [None if e is None else domain[e[0]] for e in value[0]]\n            if value[1] >= 100:\n                if domain is None:\n                    raise ValueError(\"Cannot decode variable without domain\")\n                return domain[value[0]]\n            return value[0]\n        else:\n            return value\n\n    @staticmethod\n    def _var_exists(setting, value, attributes, metas):\n        if not isinstance(value, tuple) or len(value) != 2:\n            return False\n\n        attr_name, attr_type = value\n        if attr_type >= 100:\n            attr_type -= 100\n        return (not setting.exclude_attributes and\n                attributes.get(attr_name, -1) == attr_type or\n                not setting.exclude_metas and\n                metas.get(attr_name, -1) == attr_type)\n\n    def match(self, context, domain, attrs, metas):\n        if (attrs, metas) == (context.attributes, context.metas):\n            return self.PERFECT_MATCH\n\n        matches = []\n        try:\n            for setting, data, _ in \\\n                    self.provider.traverse_settings(data=context.values):\n                if not isinstance(setting, ContextSetting):\n                    continue\n                value = data.get(setting.name, None)\n\n                if isinstance(value, list):\n                    matches.append(\n                        self.match_list(setting, value, context, attrs, metas))\n                elif isinstance(value, tuple) \\\n                        and len(value) == 2 \\\n                        and isinstance(value[0], list) \\\n                        and value[1] == -3:\n                    matches.append(\n                        self.match_list(setting, value[0], context, attrs, metas))\n                elif value is not None:\n                    matches.append(\n                        self.match_value(setting, value, attrs, metas))\n        except IncompatibleContext:\n            return self.NO_MATCH\n\n        matches.append((0, 0))\n        matched, available = [sum(m) for m in zip(*matches)]\n\n        return matched / available if available else 0.1\n\n    def match_list(self, setting, value, context, attrs, metas):\n        \"\"\"Match a list of values with the given context.\n        returns a tuple containing number of matched and all values.\n        \"\"\"\n        matched = 0\n        for i, item in enumerate(value):\n            if self.is_valid_item(setting, item, attrs, metas):\n                matched += 1\n            elif setting.required == ContextSetting.REQUIRED:\n                raise IncompatibleContext()\n        return matched, len(value)\n\n    def match_value(self, setting, value, attrs, metas):\n        \"\"\"Match a single value \"\"\"\n        if value[1] < 0:\n            return 0, 0\n\n        if self._var_exists(setting, value, attrs, metas):\n            return 1, 1\n        elif setting.required == setting.OPTIONAL:\n            return 0, 1\n        else:\n            raise IncompatibleContext()\n\n    def is_valid_item(self, setting, item, attrs, metas):\n        \"\"\"Return True if given item can be used with attrs and metas\n\n        Subclasses can override this method to checks data in alternative\n        representations.\n        \"\"\"\n        if not isinstance(item, tuple):\n            return True\n        return self._var_exists(setting, item, attrs, metas)",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 923,
                            "end_lineno": 1125,
                            "parent": null
                        }
                    ],
                    "added_entities": [],
                    "deleted_entities": []
                }
            ]
        },
        {
            "old_file_content": "import warnings\nfrom unittest import TestCase\nfrom unittest.mock import Mock\nfrom Orange.data import Domain, DiscreteVariable\nfrom Orange.data import ContinuousVariable\nfrom Orange.util import OrangeDeprecationWarning\nfrom Orange.widgets.settings import DomainContextHandler, ContextSetting\nfrom Orange.widgets.utils import vartype\n\nContinuous = vartype(ContinuousVariable())\nDiscrete = vartype(DiscreteVariable())\n\n\nclass TestDomainContextHandler(TestCase):\n    def setUp(self):\n        self.domain = Domain(\n            attributes=[ContinuousVariable('c1'),\n                        DiscreteVariable('d1', values='abc'),\n                        DiscreteVariable('d2', values='def')],\n            class_vars=[DiscreteVariable('d3', values='ghi')],\n            metas=[ContinuousVariable('c2'),\n                   DiscreteVariable('d4', values='jkl')]\n        )\n        self.args = (self.domain,\n                     {'c1': Continuous, 'd1': Discrete,\n                      'd2': Discrete, 'd3': Discrete},\n                     {'c2': Continuous, 'd4': Discrete, })\n        self.handler = DomainContextHandler()\n        self.handler.read_defaults = lambda: None\n\n    def test_encode_domain_with_match_none(self):\n        handler = DomainContextHandler(\n            match_values=DomainContextHandler.MATCH_VALUES_NONE)\n\n        encoded_attributes, encoded_metas = handler.encode_domain(self.domain)\n\n        self.assertEqual(encoded_attributes,\n                         {'c1': Continuous, 'd1': Discrete,\n                          'd2': Discrete, 'd3': Discrete})\n        self.assertEqual(encoded_metas, {'c2': Continuous, 'd4': Discrete, })\n\n    def test_encode_domain_with_match_class(self):\n        handler = DomainContextHandler(\n            match_values=DomainContextHandler.MATCH_VALUES_CLASS)\n\n        encoded_attributes, encoded_metas = handler.encode_domain(self.domain)\n\n        self.assertEqual(encoded_attributes,\n                         {'c1': Continuous, 'd1': Discrete, 'd2': Discrete,\n                          'd3': list('ghi')})\n        self.assertEqual(encoded_metas, {'c2': Continuous, 'd4': Discrete})\n\n    def test_encode_domain_with_match_all(self):\n        handler = DomainContextHandler(\n            match_values=DomainContextHandler.MATCH_VALUES_ALL)\n\n        encoded_attributes, encoded_metas = handler.encode_domain(self.domain)\n\n        self.assertEqual(encoded_attributes,\n                         {'c1': Continuous, 'd1': list('abc'),\n                          'd2': list('def'), 'd3': list('ghi')})\n        self.assertEqual(encoded_metas,\n                         {'c2': Continuous, 'd4': list('jkl')})\n\n    def test_match_returns_2_on_perfect_match(self):\n        context = Mock(\n            attributes=self.args[1], metas=self.args[2], values={})\n        self.assertEqual(2., self.handler.match(context, *self.args))\n\n    def test_match_returns_1_if_everything_matches(self):\n        self.handler.bind(SimpleWidget)\n\n        # Attributes in values\n        context = Mock(values=dict(\n            with_metas=('d1', Discrete),\n            required=('d1', Discrete)))\n        self.assertEqual(1., self.handler.match(context, *self.args))\n\n        # Metas in values\n        context = Mock(values=dict(\n            with_metas=('d4', Discrete),\n            required=('d1', Discrete)))\n        self.assertEqual(1., self.handler.match(context, *self.args))\n\n        # Attributes in lists\n        context = Mock(values=dict(\n            with_metas=[(\"d1\", Discrete)]\n        ))\n        self.assertEqual(1., self.handler.match(context, *self.args))\n\n        # Metas in lists\n        context = Mock(values=dict(\n            with_metas=[(\"d4\", Discrete)]\n        ))\n        self.assertEqual(1., self.handler.match(context, *self.args))\n\n    def test_match_returns_point_1_when_nothing_to_match(self):\n        self.handler.bind(SimpleWidget)\n\n        context = Mock(values={})\n        self.assertEqual(0.1, self.handler.match(context, *self.args))\n\n    def test_match_returns_zero_on_incompatible_context(self):\n        self.handler.bind(SimpleWidget)\n\n        # required\n        context = Mock(values=dict(required=('u', Discrete),\n                                   with_metas=('d1', Discrete)))\n        self.assertEqual(0, self.handler.match(context, *self.args))\n\n    def test_clone_context(self):\n        self.handler.bind(SimpleWidget)\n        context = self.create_context(self.domain, dict(\n            text=('u', -2),\n            with_metas=[('d1', Discrete), ('d1', Continuous),\n                        ('c1', Continuous), ('c1', Discrete)],\n            required=('u', Continuous)\n        ))\n\n        new_values = self.handler.clone_context(context, *self.args).values\n\n        self.assertEqual(new_values['text'], ('u', -2))\n        self.assertEqual([('d1', Discrete), ('c1', Continuous)],\n                         new_values['with_metas'])\n        self.assertNotIn('required', new_values)\n\n    def test_open_context(self):\n        self.handler.bind(SimpleWidget)\n        context = self.create_context(self.domain, dict(\n            text=('u', -2),\n            with_metas=[('d1', Discrete), ('d2', Discrete)]\n        ))\n        self.handler.global_contexts = \\\n            [Mock(values={}), context, Mock(values={})]\n\n        widget = SimpleWidget()\n        self.handler.initialize(widget)\n        old_metas_list = widget.with_metas\n        self.handler.open_context(widget, self.args[0])\n\n        context = widget.current_context\n        self.assertEqual(context.attributes, self.args[1])\n        self.assertEqual(context.metas, self.args[2])\n        self.assertIs(old_metas_list, widget.with_metas)\n\n        self.assertEqual(widget.text, 'u')\n        self.assertEqual(widget.with_metas, [('d1', Discrete),\n                                             ('d2', Discrete)])\n\n    def test_open_context_with_imperfect_match(self):\n        self.handler.bind(SimpleWidget)\n        context = self.create_context(None, dict(\n            text=('u', -2),\n            with_metas=[('d1', Discrete), ('d1', Continuous),\n                        ('c1', Continuous), ('c1', Discrete)]\n        ))\n        self.handler.global_contexts = \\\n            [Mock(values={}), context, Mock(values={})]\n\n        widget = SimpleWidget()\n        self.handler.initialize(widget)\n        self.handler.open_context(widget, self.args[0])\n\n        context = widget.current_context\n        self.assertEqual(context.attributes, self.args[1])\n        self.assertEqual(context.metas, self.args[2])\n\n        self.assertEqual(widget.text, 'u')\n        self.assertEqual(widget.with_metas, [('d1', Discrete),\n                                             ('c1', Continuous)])\n\n    def test_open_context_with_no_match(self):\n        self.handler.bind(SimpleWidget)\n        widget = SimpleWidget()\n        self.handler.initialize(widget)\n        widget.text = 'u'\n\n        self.handler.open_context(widget, self.args[0])\n\n        self.assertEqual(widget.text, 'u')\n        self.assertEqual(widget.with_metas, [])\n        context = widget.current_context\n        self.assertEqual(context.attributes, self.args[1])\n        self.assertEqual(context.metas, self.args[2])\n        self.assertEqual(context.values['text'], ('u', -2))\n\n    def test_filter_value(self):\n        setting = ContextSetting([])\n        setting.name = \"value\"\n\n        def test_filter(before_value, after_value):\n            data = dict(value=before_value)\n            self.handler.filter_value(setting, data, *self.args)\n            self.assertEqual(data.get(\"value\", None), after_value)\n\n        # filter list values\n        test_filter([], [])\n        # When list contains attributes asa tuple of (name, type),\n        # Attributes not present in domain should be filtered out\n        test_filter([(\"d1\", Discrete), (\"d1\", Continuous),\n                     (\"c1\", Continuous), (\"c1\", Discrete)],\n                    [(\"d1\", Discrete), (\"c1\", Continuous)])\n        # All other values in list should remain\n        test_filter([0, [1, 2, 3], \"abcd\", 5.4], [0, [1, 2, 3], \"abcd\", 5.4])\n\n    def test_encode_setting(self):\n        setting = ContextSetting(None)\n\n        var = self.domain[0]\n        val = self.handler.encode_setting(None, setting, var)\n        self.assertEqual(val, (var.name, 100 + vartype(var)))\n\n        # Should not crash on anonymous variables\n        var.name = \"\"\n        val = self.handler.encode_setting(None, setting, var)\n        self.assertEqual(val, (var.name, 100 + vartype(var)))\n\n    def test_encode_list_settings(self):\n        setting = ContextSetting(None)\n\n        var1, var2 = self.domain[:2]\n        val = self.handler.encode_setting(None, setting, [None, var1, var2])\n        self.assertEqual(\n            val,\n            ([None,\n              (var1.name, 100 + vartype(var1)),\n              (var2.name, 100 + vartype(var2))], -3))\n\n        a_list = [1, 2, 3]\n        val = self.handler.encode_setting(None, setting, a_list)\n        self.assertEqual(val, [1, 2, 3])\n        self.assertIsNot(val, a_list)\n\n        a_list = []\n        val = self.handler.encode_setting(None, setting, a_list)\n        self.assertEqual(val, [])\n        self.assertIsNot(val, a_list)\n\n        a_list = [None, None]\n        val = self.handler.encode_setting(None, setting, a_list)\n        self.assertEqual(val, [None, None])\n        self.assertIsNot(val, a_list)\n\n    def test_decode_setting(self):\n        setting = ContextSetting(None)\n\n        var = self.domain[0]\n        val = self.handler.decode_setting(setting, (var.name, 100 + vartype(var)),\n                                          self.domain)\n        self.assertIs(val, var)\n\n        all_metas_domain = Domain([], metas=[var])\n        val = self.handler.decode_setting(setting, (var.name, 100 + vartype(var)),\n                                          all_metas_domain)\n        self.assertIs(val, var)\n\n    def test_decode_list_setting(self):\n        setting = ContextSetting(None)\n\n        var1, var2 = self.domain[:2]\n        val = self.handler.decode_setting(\n            setting,\n            ([None,\n              (var1.name, 100 + vartype(var1)),\n              (var2.name, 100 + vartype(var2))], -3),\n            self.domain)\n        self.assertEqual(val, [None, var1, var2])\n\n        val = self.handler.decode_setting(setting, [1, 2, 3], self.domain)\n        self.assertEqual(val, [1, 2, 3])\n\n    def test_backward_compatible_params(self):\n        with warnings.catch_warnings(record=True) as w:\n            warnings.simplefilter(\"always\")\n            DomainContextHandler(metas_in_res=True)\n            self.assertIn(OrangeDeprecationWarning,\n                          [x.category for x in w])\n\n    def create_context(self, domain, values):\n        if domain is None:\n            domain = Domain([])\n\n        context = self.handler.new_context(domain,\n                                           *self.handler.encode_domain(domain))\n        context.values = values\n        return context\n\n\nclass SimpleWidget:\n    text = ContextSetting(\"\")\n    with_metas = ContextSetting([], required=ContextSetting.OPTIONAL)\n    required = ContextSetting(\"\", required=ContextSetting.REQUIRED)\n\n    def retrieveSpecificSettings(self):\n        pass\n\n    def storeSpecificSettings(self):\n        pass\n",
            "new_file_content": "import warnings\nfrom distutils.version import LooseVersion\nfrom unittest import TestCase\nfrom unittest.mock import Mock\n\nimport Orange\nfrom Orange.data import Domain, DiscreteVariable\nfrom Orange.data import ContinuousVariable\nfrom Orange.util import OrangeDeprecationWarning\nfrom Orange.widgets.settings import DomainContextHandler, ContextSetting\nfrom Orange.widgets.utils import vartype\n\nContinuous = 100 + vartype(ContinuousVariable())\nDiscrete = 100 + vartype(DiscreteVariable())\n\n\nclass TestDomainContextHandler(TestCase):\n    def setUp(self):\n        self.domain = Domain(\n            attributes=[ContinuousVariable('c1'),\n                        DiscreteVariable('d1', values='abc'),\n                        DiscreteVariable('d2', values='def')],\n            class_vars=[DiscreteVariable('d3', values='ghi')],\n            metas=[ContinuousVariable('c2'),\n                   DiscreteVariable('d4', values='jkl')]\n        )\n        self.args = (self.domain,\n                     {'c1': Continuous - 100, 'd1': Discrete - 100,\n                      'd2': Discrete - 100, 'd3': Discrete - 100},\n                     {'c2': Continuous - 100, 'd4': Discrete - 100, })\n        self.handler = DomainContextHandler()\n        self.handler.read_defaults = lambda: None\n\n    def test_encode_domain_with_match_none(self):\n        handler = DomainContextHandler(\n            match_values=DomainContextHandler.MATCH_VALUES_NONE)\n\n        encoded_attributes, encoded_metas = handler.encode_domain(self.domain)\n\n        self.assertEqual(encoded_attributes,\n                         {'c1': Continuous - 100, 'd1': Discrete - 100,\n                          'd2': Discrete - 100, 'd3': Discrete - 100})\n        self.assertEqual(encoded_metas,\n                         {'c2': Continuous - 100, 'd4': Discrete - 100, })\n\n    def test_encode_domain_with_match_class(self):\n        handler = DomainContextHandler(\n            match_values=DomainContextHandler.MATCH_VALUES_CLASS)\n\n        encoded_attributes, encoded_metas = handler.encode_domain(self.domain)\n\n        self.assertEqual(encoded_attributes,\n                         {'c1': Continuous - 100, 'd1': Discrete - 100,\n                          'd2': Discrete - 100,\n                          'd3': list('ghi')})\n        self.assertEqual(encoded_metas,\n                         {'c2': Continuous - 100, 'd4': Discrete - 100})\n\n    def test_encode_domain_with_match_all(self):\n        handler = DomainContextHandler(\n            match_values=DomainContextHandler.MATCH_VALUES_ALL)\n\n        encoded_attributes, encoded_metas = handler.encode_domain(self.domain)\n\n        self.assertEqual(encoded_attributes,\n                         {'c1': Continuous - 100, 'd1': list('abc'),\n                          'd2': list('def'), 'd3': list('ghi')})\n        self.assertEqual(encoded_metas,\n                         {'c2': Continuous - 100, 'd4': list('jkl')})\n\n    def test_match_returns_2_on_perfect_match(self):\n        context = Mock(\n            attributes=self.args[1], metas=self.args[2], values={})\n        self.assertEqual(2., self.handler.match(context, *self.args))\n\n    def test_match_returns_1_if_everything_matches(self):\n        self.handler.bind(SimpleWidget)\n\n        # Attributes in values\n        context = Mock(values=dict(\n            with_metas=('d1', Discrete),\n            required=('d1', Discrete)))\n        self.assertEqual(1., self.handler.match(context, *self.args))\n\n        # Metas in values\n        context = Mock(values=dict(\n            with_metas=('d4', Discrete),\n            required=('d1', Discrete)))\n        self.assertEqual(1., self.handler.match(context, *self.args))\n\n        # Attributes in lists\n        context = Mock(values=dict(\n            with_metas=[(\"d1\", Discrete)]\n        ))\n        self.assertEqual(1., self.handler.match(context, *self.args))\n\n        # Metas in lists\n        context = Mock(values=dict(\n            with_metas=[(\"d4\", Discrete)]\n        ))\n        self.assertEqual(1., self.handler.match(context, *self.args))\n\n    def test_match_returns_point_1_when_nothing_to_match(self):\n        self.handler.bind(SimpleWidget)\n\n        context = Mock(values={})\n        self.assertEqual(0.1, self.handler.match(context, *self.args))\n\n    def test_match_returns_zero_on_incompatible_context(self):\n        self.handler.bind(SimpleWidget)\n\n        # required\n        context = Mock(values=dict(required=('u', Discrete),\n                                   with_metas=('d1', Discrete)))\n        self.assertEqual(0, self.handler.match(context, *self.args))\n\n    def test_clone_context(self):\n        self.handler.bind(SimpleWidget)\n        context = self.create_context(self.domain, dict(\n            text=('u', -2),\n            with_metas=[('d1', Discrete), ('d1', Continuous),\n                        ('c1', Continuous), ('c1', Discrete)],\n            required=('u', Continuous)\n        ))\n\n        new_values = self.handler.clone_context(context, *self.args).values\n\n        self.assertEqual(new_values['text'], ('u', -2))\n        self.assertEqual([('d1', Discrete), ('c1', Continuous)],\n                         new_values['with_metas'])\n        self.assertNotIn('required', new_values)\n\n    def test_open_context(self):\n        self.handler.bind(SimpleWidget)\n        context = self.create_context(self.domain, dict(\n            text=('u', -2),\n            with_metas=[('d1', Discrete), ('d2', Discrete)]\n        ))\n        self.handler.global_contexts = \\\n            [Mock(values={}), context, Mock(values={})]\n\n        widget = SimpleWidget()\n        self.handler.initialize(widget)\n        old_metas_list = widget.with_metas\n        self.handler.open_context(widget, self.args[0])\n\n        context = widget.current_context\n        self.assertEqual(context.attributes, self.args[1])\n        self.assertEqual(context.metas, self.args[2])\n        self.assertIs(old_metas_list, widget.with_metas)\n\n        self.assertEqual(widget.text, 'u')\n        self.assertEqual(widget.with_metas, [('d1', Discrete),\n                                             ('d2', Discrete)])\n\n    def test_open_context_with_imperfect_match(self):\n        self.handler.bind(SimpleWidget)\n        context = self.create_context(None, dict(\n            text=('u', -2),\n            with_metas=[('d1', Discrete), ('d1', Continuous),\n                        ('c1', Continuous), ('c1', Discrete)]\n        ))\n        self.handler.global_contexts = \\\n            [Mock(values={}), context, Mock(values={})]\n\n        widget = SimpleWidget()\n        self.handler.initialize(widget)\n        self.handler.open_context(widget, self.args[0])\n\n        context = widget.current_context\n        self.assertEqual(context.attributes, self.args[1])\n        self.assertEqual(context.metas, self.args[2])\n\n        self.assertEqual(widget.text, 'u')\n        self.assertEqual(widget.with_metas, [('d1', Discrete),\n                                             ('c1', Continuous)])\n\n    def test_open_context_with_no_match(self):\n        self.handler.bind(SimpleWidget)\n        widget = SimpleWidget()\n        self.handler.initialize(widget)\n        widget.text = 'u'\n\n        self.handler.open_context(widget, self.args[0])\n\n        self.assertEqual(widget.text, 'u')\n        self.assertEqual(widget.with_metas, [])\n        context = widget.current_context\n        self.assertEqual(context.attributes, self.args[1])\n        self.assertEqual(context.metas, self.args[2])\n        self.assertEqual(context.values['text'], ('u', -2))\n\n    def test_filter_value(self):\n        setting = ContextSetting([])\n        setting.name = \"value\"\n\n        def test_filter(before_value, after_value):\n            data = dict(value=before_value)\n            self.handler.filter_value(setting, data, *self.args)\n            self.assertEqual(data.get(\"value\", None), after_value)\n\n        # filter list values\n        test_filter([], [])\n        # When list contains attributes asa tuple of (name, type),\n        # Attributes not present in domain should be filtered out\n        test_filter([(\"d1\", Discrete), (\"d1\", Continuous),\n                     (\"c1\", Continuous), (\"c1\", Discrete)],\n                    [(\"d1\", Discrete), (\"c1\", Continuous)])\n        # All other values in list should remain\n        test_filter([0, [1, 2, 3], \"abcd\", 5.4], [0, [1, 2, 3], \"abcd\", 5.4])\n\n    def test_encode_setting(self):\n        setting = ContextSetting(None)\n\n        var = self.domain[0]\n        val = self.handler.encode_setting(None, setting, var)\n        self.assertEqual(val, (var.name, 100 + vartype(var)))\n\n        # Should not crash on anonymous variables\n        var.name = \"\"\n        val = self.handler.encode_setting(None, setting, var)\n        self.assertEqual(val, (var.name, 100 + vartype(var)))\n\n    def test_encode_list_settings(self):\n        setting = ContextSetting(None)\n\n        var1, var2 = self.domain[:2]\n        val = self.handler.encode_setting(None, setting, [None, var1, var2])\n        self.assertEqual(\n            val,\n            ([None,\n              (var1.name, 100 + vartype(var1)),\n              (var2.name, 100 + vartype(var2))], -3))\n\n        a_list = [1, 2, 3]\n        val = self.handler.encode_setting(None, setting, a_list)\n        self.assertEqual(val, [1, 2, 3])\n        self.assertIsNot(val, a_list)\n\n        a_list = []\n        val = self.handler.encode_setting(None, setting, a_list)\n        self.assertEqual(val, [])\n        self.assertIsNot(val, a_list)\n\n        a_list = [None, None]\n        val = self.handler.encode_setting(None, setting, a_list)\n        self.assertEqual(val, [None, None])\n        self.assertIsNot(val, a_list)\n\n    def test_decode_setting(self):\n        setting = ContextSetting(None)\n\n        var = self.domain[0]\n        val = self.handler.decode_setting(setting, (var.name, 100 + vartype(var)),\n                                          self.domain)\n        self.assertIs(val, var)\n\n        all_metas_domain = Domain([], metas=[var])\n        val = self.handler.decode_setting(setting, (var.name, 100 + vartype(var)),\n                                          all_metas_domain)\n        self.assertIs(val, var)\n\n    def test_decode_list_setting(self):\n        setting = ContextSetting(None)\n\n        var1, var2 = self.domain[:2]\n        val = self.handler.decode_setting(\n            setting,\n            ([None,\n              (var1.name, 100 + vartype(var1)),\n              (var2.name, 100 + vartype(var2))], -3),\n            self.domain)\n        self.assertEqual(val, [None, var1, var2])\n\n        val = self.handler.decode_setting(setting, [1, 2, 3], self.domain)\n        self.assertEqual(val, [1, 2, 3])\n\n    def test_backward_compatible_params(self):\n        with warnings.catch_warnings(record=True) as w:\n            warnings.simplefilter(\"always\")\n            DomainContextHandler(metas_in_res=True)\n            self.assertIn(OrangeDeprecationWarning,\n                          [x.category for x in w])\n\n    def test_deprecated_str_as_var(self):\n        if LooseVersion(Orange.__version__) >= LooseVersion(\"3.26\"):\n            # pragma: no cover\n            self.fail(\"Remove support for variables stored as string settings \"\n                      \"and this test.\")\n\n        context = Mock()\n        context.attributes = {\"foo\": 2}\n        context.metas = {}\n        setting = ContextSetting(\"\")\n        setting.name = \"setting_name\"\n        with warnings.catch_warnings(record=True) as w:\n            warnings.simplefilter(\"always\")\n            DomainContextHandler.encode_setting(context, setting, \"foo\")\n            self.assertIn(\"setting_name\", w[0].message.args[0])\n\n\n    def create_context(self, domain, values):\n        if domain is None:\n            domain = Domain([])\n\n        context = self.handler.new_context(domain,\n                                           *self.handler.encode_domain(domain))\n        context.values = values\n        return context\n\n\nclass SimpleWidget:\n    text = ContextSetting(\"\")\n    with_metas = ContextSetting([], required=ContextSetting.OPTIONAL)\n    required = ContextSetting(\"\", required=ContextSetting.REQUIRED)\n\n    def retrieveSpecificSettings(self):\n        pass\n\n    def storeSpecificSettings(self):\n        pass\n",
            "header": {
                "file": {
                    "path": "Orange/widgets/tests/test_domain_context_handler.py"
                },
                "misc_line": null
            },
            "index_line": {
                "old_commit_hash": "cb4c634ac",
                "new_commit_hash": "8188df754",
                "mode": "100644"
            },
            "is_binary_file": false,
            "binary_line": null,
            "minus_file": {
                "path": "a/Orange/widgets/tests/test_domain_context_handler.py"
            },
            "plus_file": {
                "path": "b/Orange/widgets/tests/test_domain_context_handler.py"
            },
            "hunks": [
                {
                    "descriptor": {
                        "old_range": {
                            "start": 1,
                            "length": 14
                        },
                        "new_range": {
                            "start": 1,
                            "length": 17
                        },
                        "section": ""
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "import warnings",
                                "type": "context"
                            },
                            {
                                "content": "from distutils.version import LooseVersion",
                                "type": "added"
                            },
                            {
                                "content": "from unittest import TestCase",
                                "type": "context"
                            },
                            {
                                "content": "from unittest.mock import Mock",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "import Orange",
                                "type": "added"
                            },
                            {
                                "content": "from Orange.data import Domain, DiscreteVariable",
                                "type": "context"
                            },
                            {
                                "content": "from Orange.data import ContinuousVariable",
                                "type": "context"
                            },
                            {
                                "content": "from Orange.util import OrangeDeprecationWarning",
                                "type": "context"
                            },
                            {
                                "content": "from Orange.widgets.settings import DomainContextHandler, ContextSetting",
                                "type": "context"
                            },
                            {
                                "content": "from Orange.widgets.utils import vartype",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "Continuous = vartype(ContinuousVariable())",
                                "type": "deleted"
                            },
                            {
                                "content": "Discrete = vartype(DiscreteVariable())",
                                "type": "deleted"
                            },
                            {
                                "content": "Continuous = 100 + vartype(ContinuousVariable())",
                                "type": "added"
                            },
                            {
                                "content": "Discrete = 100 + vartype(DiscreteVariable())",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "class TestDomainContextHandler(TestCase):",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [],
                    "added_entities": [
                        {
                            "file_name": "Orange/widgets/tests/test_domain_context_handler.py",
                            "type": "statement",
                            "name": "",
                            "content": "Continuous = 100 + vartype(ContinuousVariable())",
                            "ast_type_str": "Assign",
                            "start_lineno": 13,
                            "end_lineno": 13,
                            "parent": null
                        },
                        {
                            "file_name": "Orange/widgets/tests/test_domain_context_handler.py",
                            "type": "statement",
                            "name": "",
                            "content": "Discrete = 100 + vartype(DiscreteVariable())",
                            "ast_type_str": "Assign",
                            "start_lineno": 14,
                            "end_lineno": 14,
                            "parent": null
                        },
                        {
                            "file_name": "Orange/widgets/tests/test_domain_context_handler.py",
                            "type": "import",
                            "name": "Orange",
                            "content": "import Orange",
                            "ast_type_str": "Import",
                            "start_lineno": 6,
                            "end_lineno": 6,
                            "parent": null
                        },
                        {
                            "file_name": "Orange/widgets/tests/test_domain_context_handler.py",
                            "type": "statement",
                            "name": "",
                            "content": "from distutils.version import LooseVersion",
                            "ast_type_str": "ImportFrom",
                            "start_lineno": 2,
                            "end_lineno": 2,
                            "parent": null
                        }
                    ],
                    "deleted_entities": [
                        {
                            "file_name": "Orange/widgets/tests/test_domain_context_handler.py",
                            "type": "statement",
                            "name": "",
                            "content": "Discrete = vartype(DiscreteVariable())",
                            "ast_type_str": "Assign",
                            "start_lineno": 11,
                            "end_lineno": 11,
                            "parent": null
                        },
                        {
                            "file_name": "Orange/widgets/tests/test_domain_context_handler.py",
                            "type": "statement",
                            "name": "",
                            "content": "Continuous = vartype(ContinuousVariable())",
                            "ast_type_str": "Assign",
                            "start_lineno": 10,
                            "end_lineno": 10,
                            "parent": null
                        }
                    ]
                },
                {
                    "descriptor": {
                        "old_range": {
                            "start": 22,
                            "length": 9
                        },
                        "new_range": {
                            "start": 25,
                            "length": 9
                        },
                        "section": "class TestDomainContextHandler(TestCase):"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "                   DiscreteVariable('d4', values='jkl')]",
                                "type": "context"
                            },
                            {
                                "content": "        )",
                                "type": "context"
                            },
                            {
                                "content": "        self.args = (self.domain,",
                                "type": "context"
                            },
                            {
                                "content": "                     {'c1': Continuous, 'd1': Discrete,",
                                "type": "deleted"
                            },
                            {
                                "content": "                      'd2': Discrete, 'd3': Discrete},",
                                "type": "deleted"
                            },
                            {
                                "content": "                     {'c2': Continuous, 'd4': Discrete, })",
                                "type": "deleted"
                            },
                            {
                                "content": "                     {'c1': Continuous - 100, 'd1': Discrete - 100,",
                                "type": "added"
                            },
                            {
                                "content": "                      'd2': Discrete - 100, 'd3': Discrete - 100},",
                                "type": "added"
                            },
                            {
                                "content": "                     {'c2': Continuous - 100, 'd4': Discrete - 100, })",
                                "type": "added"
                            },
                            {
                                "content": "        self.handler = DomainContextHandler()",
                                "type": "context"
                            },
                            {
                                "content": "        self.handler.read_defaults = lambda: None",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [
                        {
                            "file_name": "Orange/widgets/tests/test_domain_context_handler.py",
                            "type": "class",
                            "name": "TestDomainContextHandler",
                            "content": "class TestDomainContextHandler(TestCase):\n    def setUp(self):\n        self.domain = Domain(\n            attributes=[ContinuousVariable('c1'),\n                        DiscreteVariable('d1', values='abc'),\n                        DiscreteVariable('d2', values='def')],\n            class_vars=[DiscreteVariable('d3', values='ghi')],\n            metas=[ContinuousVariable('c2'),\n                   DiscreteVariable('d4', values='jkl')]\n        )\n        self.args = (self.domain,\n                     {'c1': Continuous, 'd1': Discrete,\n                      'd2': Discrete, 'd3': Discrete},\n                     {'c2': Continuous, 'd4': Discrete, })\n        self.handler = DomainContextHandler()\n        self.handler.read_defaults = lambda: None\n\n    def test_encode_domain_with_match_none(self):\n        handler = DomainContextHandler(\n            match_values=DomainContextHandler.MATCH_VALUES_NONE)\n\n        encoded_attributes, encoded_metas = handler.encode_domain(self.domain)\n\n        self.assertEqual(encoded_attributes,\n                         {'c1': Continuous, 'd1': Discrete,\n                          'd2': Discrete, 'd3': Discrete})\n        self.assertEqual(encoded_metas, {'c2': Continuous, 'd4': Discrete, })\n\n    def test_encode_domain_with_match_class(self):\n        handler = DomainContextHandler(\n            match_values=DomainContextHandler.MATCH_VALUES_CLASS)\n\n        encoded_attributes, encoded_metas = handler.encode_domain(self.domain)\n\n        self.assertEqual(encoded_attributes,\n                         {'c1': Continuous, 'd1': Discrete, 'd2': Discrete,\n                          'd3': list('ghi')})\n        self.assertEqual(encoded_metas, {'c2': Continuous, 'd4': Discrete})\n\n    def test_encode_domain_with_match_all(self):\n        handler = DomainContextHandler(\n            match_values=DomainContextHandler.MATCH_VALUES_ALL)\n\n        encoded_attributes, encoded_metas = handler.encode_domain(self.domain)\n\n        self.assertEqual(encoded_attributes,\n                         {'c1': Continuous, 'd1': list('abc'),\n                          'd2': list('def'), 'd3': list('ghi')})\n        self.assertEqual(encoded_metas,\n                         {'c2': Continuous, 'd4': list('jkl')})\n\n    def test_match_returns_2_on_perfect_match(self):\n        context = Mock(\n            attributes=self.args[1], metas=self.args[2], values={})\n        self.assertEqual(2., self.handler.match(context, *self.args))\n\n    def test_match_returns_1_if_everything_matches(self):\n        self.handler.bind(SimpleWidget)\n\n        # Attributes in values\n        context = Mock(values=dict(\n            with_metas=('d1', Discrete),\n            required=('d1', Discrete)))\n        self.assertEqual(1., self.handler.match(context, *self.args))\n\n        # Metas in values\n        context = Mock(values=dict(\n            with_metas=('d4', Discrete),\n            required=('d1', Discrete)))\n        self.assertEqual(1., self.handler.match(context, *self.args))\n\n        # Attributes in lists\n        context = Mock(values=dict(\n            with_metas=[(\"d1\", Discrete)]\n        ))\n        self.assertEqual(1., self.handler.match(context, *self.args))\n\n        # Metas in lists\n        context = Mock(values=dict(\n            with_metas=[(\"d4\", Discrete)]\n        ))\n        self.assertEqual(1., self.handler.match(context, *self.args))\n\n    def test_match_returns_point_1_when_nothing_to_match(self):\n        self.handler.bind(SimpleWidget)\n\n        context = Mock(values={})\n        self.assertEqual(0.1, self.handler.match(context, *self.args))\n\n    def test_match_returns_zero_on_incompatible_context(self):\n        self.handler.bind(SimpleWidget)\n\n        # required\n        context = Mock(values=dict(required=('u', Discrete),\n                                   with_metas=('d1', Discrete)))\n        self.assertEqual(0, self.handler.match(context, *self.args))\n\n    def test_clone_context(self):\n        self.handler.bind(SimpleWidget)\n        context = self.create_context(self.domain, dict(\n            text=('u', -2),\n            with_metas=[('d1', Discrete), ('d1', Continuous),\n                        ('c1', Continuous), ('c1', Discrete)],\n            required=('u', Continuous)\n        ))\n\n        new_values = self.handler.clone_context(context, *self.args).values\n\n        self.assertEqual(new_values['text'], ('u', -2))\n        self.assertEqual([('d1', Discrete), ('c1', Continuous)],\n                         new_values['with_metas'])\n        self.assertNotIn('required', new_values)\n\n    def test_open_context(self):\n        self.handler.bind(SimpleWidget)\n        context = self.create_context(self.domain, dict(\n            text=('u', -2),\n            with_metas=[('d1', Discrete), ('d2', Discrete)]\n        ))\n        self.handler.global_contexts = \\\n            [Mock(values={}), context, Mock(values={})]\n\n        widget = SimpleWidget()\n        self.handler.initialize(widget)\n        old_metas_list = widget.with_metas\n        self.handler.open_context(widget, self.args[0])\n\n        context = widget.current_context\n        self.assertEqual(context.attributes, self.args[1])\n        self.assertEqual(context.metas, self.args[2])\n        self.assertIs(old_metas_list, widget.with_metas)\n\n        self.assertEqual(widget.text, 'u')\n        self.assertEqual(widget.with_metas, [('d1', Discrete),\n                                             ('d2', Discrete)])\n\n    def test_open_context_with_imperfect_match(self):\n        self.handler.bind(SimpleWidget)\n        context = self.create_context(None, dict(\n            text=('u', -2),\n            with_metas=[('d1', Discrete), ('d1', Continuous),\n                        ('c1', Continuous), ('c1', Discrete)]\n        ))\n        self.handler.global_contexts = \\\n            [Mock(values={}), context, Mock(values={})]\n\n        widget = SimpleWidget()\n        self.handler.initialize(widget)\n        self.handler.open_context(widget, self.args[0])\n\n        context = widget.current_context\n        self.assertEqual(context.attributes, self.args[1])\n        self.assertEqual(context.metas, self.args[2])\n\n        self.assertEqual(widget.text, 'u')\n        self.assertEqual(widget.with_metas, [('d1', Discrete),\n                                             ('c1', Continuous)])\n\n    def test_open_context_with_no_match(self):\n        self.handler.bind(SimpleWidget)\n        widget = SimpleWidget()\n        self.handler.initialize(widget)\n        widget.text = 'u'\n\n        self.handler.open_context(widget, self.args[0])\n\n        self.assertEqual(widget.text, 'u')\n        self.assertEqual(widget.with_metas, [])\n        context = widget.current_context\n        self.assertEqual(context.attributes, self.args[1])\n        self.assertEqual(context.metas, self.args[2])\n        self.assertEqual(context.values['text'], ('u', -2))\n\n    def test_filter_value(self):\n        setting = ContextSetting([])\n        setting.name = \"value\"\n\n        def test_filter(before_value, after_value):\n            data = dict(value=before_value)\n            self.handler.filter_value(setting, data, *self.args)\n            self.assertEqual(data.get(\"value\", None), after_value)\n\n        # filter list values\n        test_filter([], [])\n        # When list contains attributes asa tuple of (name, type),\n        # Attributes not present in domain should be filtered out\n        test_filter([(\"d1\", Discrete), (\"d1\", Continuous),\n                     (\"c1\", Continuous), (\"c1\", Discrete)],\n                    [(\"d1\", Discrete), (\"c1\", Continuous)])\n        # All other values in list should remain\n        test_filter([0, [1, 2, 3], \"abcd\", 5.4], [0, [1, 2, 3], \"abcd\", 5.4])\n\n    def test_encode_setting(self):\n        setting = ContextSetting(None)\n\n        var = self.domain[0]\n        val = self.handler.encode_setting(None, setting, var)\n        self.assertEqual(val, (var.name, 100 + vartype(var)))\n\n        # Should not crash on anonymous variables\n        var.name = \"\"\n        val = self.handler.encode_setting(None, setting, var)\n        self.assertEqual(val, (var.name, 100 + vartype(var)))\n\n    def test_encode_list_settings(self):\n        setting = ContextSetting(None)\n\n        var1, var2 = self.domain[:2]\n        val = self.handler.encode_setting(None, setting, [None, var1, var2])\n        self.assertEqual(\n            val,\n            ([None,\n              (var1.name, 100 + vartype(var1)),\n              (var2.name, 100 + vartype(var2))], -3))\n\n        a_list = [1, 2, 3]\n        val = self.handler.encode_setting(None, setting, a_list)\n        self.assertEqual(val, [1, 2, 3])\n        self.assertIsNot(val, a_list)\n\n        a_list = []\n        val = self.handler.encode_setting(None, setting, a_list)\n        self.assertEqual(val, [])\n        self.assertIsNot(val, a_list)\n\n        a_list = [None, None]\n        val = self.handler.encode_setting(None, setting, a_list)\n        self.assertEqual(val, [None, None])\n        self.assertIsNot(val, a_list)\n\n    def test_decode_setting(self):\n        setting = ContextSetting(None)\n\n        var = self.domain[0]\n        val = self.handler.decode_setting(setting, (var.name, 100 + vartype(var)),\n                                          self.domain)\n        self.assertIs(val, var)\n\n        all_metas_domain = Domain([], metas=[var])\n        val = self.handler.decode_setting(setting, (var.name, 100 + vartype(var)),\n                                          all_metas_domain)\n        self.assertIs(val, var)\n\n    def test_decode_list_setting(self):\n        setting = ContextSetting(None)\n\n        var1, var2 = self.domain[:2]\n        val = self.handler.decode_setting(\n            setting,\n            ([None,\n              (var1.name, 100 + vartype(var1)),\n              (var2.name, 100 + vartype(var2))], -3),\n            self.domain)\n        self.assertEqual(val, [None, var1, var2])\n\n        val = self.handler.decode_setting(setting, [1, 2, 3], self.domain)\n        self.assertEqual(val, [1, 2, 3])\n\n    def test_backward_compatible_params(self):\n        with warnings.catch_warnings(record=True) as w:\n            warnings.simplefilter(\"always\")\n            DomainContextHandler(metas_in_res=True)\n            self.assertIn(OrangeDeprecationWarning,\n                          [x.category for x in w])\n\n    def create_context(self, domain, values):\n        if domain is None:\n            domain = Domain([])\n\n        context = self.handler.new_context(domain,\n                                           *self.handler.encode_domain(domain))\n        context.values = values\n        return context",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 14,
                            "end_lineno": 286,
                            "parent": null
                        },
                        {
                            "file_name": "Orange/widgets/tests/test_domain_context_handler.py",
                            "type": "method",
                            "name": "TestDomainContextHandler.setUp",
                            "content": "class TestDomainContextHandler(TestCase):\n    def setUp(self):\n        self.domain = Domain(\n            attributes=[ContinuousVariable('c1'),\n                        DiscreteVariable('d1', values='abc'),\n                        DiscreteVariable('d2', values='def')],\n            class_vars=[DiscreteVariable('d3', values='ghi')],\n            metas=[ContinuousVariable('c2'),\n                   DiscreteVariable('d4', values='jkl')]\n        )\n        self.args = (self.domain,\n                     {'c1': Continuous, 'd1': Discrete,\n                      'd2': Discrete, 'd3': Discrete},\n                     {'c2': Continuous, 'd4': Discrete, })\n        self.handler = DomainContextHandler()\n        self.handler.read_defaults = lambda: None\n\n    def test_encode_domain_with_match_none(self):\n        handler = DomainContextHandler(\n            match_values=DomainContextHandler.MATCH_VALUES_NONE)\n\n        encoded_attributes, encoded_metas = handler.encode_domain(self.domain)\n\n        self.assertEqual(encoded_attributes,\n                         {'c1': Continuous, 'd1': Discrete,\n                          'd2': Discrete, 'd3': Discrete})\n        self.assertEqual(encoded_metas, {'c2': Continuous, 'd4': Discrete, })\n\n    def test_encode_domain_with_match_class(self):\n        handler = DomainContextHandler(\n            match_values=DomainContextHandler.MATCH_VALUES_CLASS)\n\n        encoded_attributes, encoded_metas = handler.encode_domain(self.domain)\n\n        self.assertEqual(encoded_attributes,\n                         {'c1': Continuous, 'd1': Discrete, 'd2': Discrete,\n                          'd3': list('ghi')})\n        self.assertEqual(encoded_metas, {'c2': Continuous, 'd4': Discrete})\n\n    def test_encode_domain_with_match_all(self):\n        handler = DomainContextHandler(\n            match_values=DomainContextHandler.MATCH_VALUES_ALL)\n\n        encoded_attributes, encoded_metas = handler.encode_domain(self.domain)\n\n        self.assertEqual(encoded_attributes,\n                         {'c1': Continuous, 'd1': list('abc'),\n                          'd2': list('def'), 'd3': list('ghi')})\n        self.assertEqual(encoded_metas,\n                         {'c2': Continuous, 'd4': list('jkl')})\n\n    def test_match_returns_2_on_perfect_match(self):\n        context = Mock(\n            attributes=self.args[1], metas=self.args[2], values={})\n        self.assertEqual(2., self.handler.match(context, *self.args))\n\n    def test_match_returns_1_if_everything_matches(self):\n        self.handler.bind(SimpleWidget)\n\n        # Attributes in values\n        context = Mock(values=dict(\n            with_metas=('d1', Discrete),\n            required=('d1', Discrete)))\n        self.assertEqual(1., self.handler.match(context, *self.args))\n\n        # Metas in values\n        context = Mock(values=dict(\n            with_metas=('d4', Discrete),\n            required=('d1', Discrete)))\n        self.assertEqual(1., self.handler.match(context, *self.args))\n\n        # Attributes in lists\n        context = Mock(values=dict(\n            with_metas=[(\"d1\", Discrete)]\n        ))\n        self.assertEqual(1., self.handler.match(context, *self.args))\n\n        # Metas in lists\n        context = Mock(values=dict(\n            with_metas=[(\"d4\", Discrete)]\n        ))\n        self.assertEqual(1., self.handler.match(context, *self.args))\n\n    def test_match_returns_point_1_when_nothing_to_match(self):\n        self.handler.bind(SimpleWidget)\n\n        context = Mock(values={})\n        self.assertEqual(0.1, self.handler.match(context, *self.args))\n\n    def test_match_returns_zero_on_incompatible_context(self):\n        self.handler.bind(SimpleWidget)\n\n        # required\n        context = Mock(values=dict(required=('u', Discrete),\n                                   with_metas=('d1', Discrete)))\n        self.assertEqual(0, self.handler.match(context, *self.args))\n\n    def test_clone_context(self):\n        self.handler.bind(SimpleWidget)\n        context = self.create_context(self.domain, dict(\n            text=('u', -2),\n            with_metas=[('d1', Discrete), ('d1', Continuous),\n                        ('c1', Continuous), ('c1', Discrete)],\n            required=('u', Continuous)\n        ))\n\n        new_values = self.handler.clone_context(context, *self.args).values\n\n        self.assertEqual(new_values['text'], ('u', -2))\n        self.assertEqual([('d1', Discrete), ('c1', Continuous)],\n                         new_values['with_metas'])\n        self.assertNotIn('required', new_values)\n\n    def test_open_context(self):\n        self.handler.bind(SimpleWidget)\n        context = self.create_context(self.domain, dict(\n            text=('u', -2),\n            with_metas=[('d1', Discrete), ('d2', Discrete)]\n        ))\n        self.handler.global_contexts = \\\n            [Mock(values={}), context, Mock(values={})]\n\n        widget = SimpleWidget()\n        self.handler.initialize(widget)\n        old_metas_list = widget.with_metas\n        self.handler.open_context(widget, self.args[0])\n\n        context = widget.current_context\n        self.assertEqual(context.attributes, self.args[1])\n        self.assertEqual(context.metas, self.args[2])\n        self.assertIs(old_metas_list, widget.with_metas)\n\n        self.assertEqual(widget.text, 'u')\n        self.assertEqual(widget.with_metas, [('d1', Discrete),\n                                             ('d2', Discrete)])\n\n    def test_open_context_with_imperfect_match(self):\n        self.handler.bind(SimpleWidget)\n        context = self.create_context(None, dict(\n            text=('u', -2),\n            with_metas=[('d1', Discrete), ('d1', Continuous),\n                        ('c1', Continuous), ('c1', Discrete)]\n        ))\n        self.handler.global_contexts = \\\n            [Mock(values={}), context, Mock(values={})]\n\n        widget = SimpleWidget()\n        self.handler.initialize(widget)\n        self.handler.open_context(widget, self.args[0])\n\n        context = widget.current_context\n        self.assertEqual(context.attributes, self.args[1])\n        self.assertEqual(context.metas, self.args[2])\n\n        self.assertEqual(widget.text, 'u')\n        self.assertEqual(widget.with_metas, [('d1', Discrete),\n                                             ('c1', Continuous)])\n\n    def test_open_context_with_no_match(self):\n        self.handler.bind(SimpleWidget)\n        widget = SimpleWidget()\n        self.handler.initialize(widget)\n        widget.text = 'u'\n\n        self.handler.open_context(widget, self.args[0])\n\n        self.assertEqual(widget.text, 'u')\n        self.assertEqual(widget.with_metas, [])\n        context = widget.current_context\n        self.assertEqual(context.attributes, self.args[1])\n        self.assertEqual(context.metas, self.args[2])\n        self.assertEqual(context.values['text'], ('u', -2))\n\n    def test_filter_value(self):\n        setting = ContextSetting([])\n        setting.name = \"value\"\n\n        def test_filter(before_value, after_value):\n            data = dict(value=before_value)\n            self.handler.filter_value(setting, data, *self.args)\n            self.assertEqual(data.get(\"value\", None), after_value)\n\n        # filter list values\n        test_filter([], [])\n        # When list contains attributes asa tuple of (name, type),\n        # Attributes not present in domain should be filtered out\n        test_filter([(\"d1\", Discrete), (\"d1\", Continuous),\n                     (\"c1\", Continuous), (\"c1\", Discrete)],\n                    [(\"d1\", Discrete), (\"c1\", Continuous)])\n        # All other values in list should remain\n        test_filter([0, [1, 2, 3], \"abcd\", 5.4], [0, [1, 2, 3], \"abcd\", 5.4])\n\n    def test_encode_setting(self):\n        setting = ContextSetting(None)\n\n        var = self.domain[0]\n        val = self.handler.encode_setting(None, setting, var)\n        self.assertEqual(val, (var.name, 100 + vartype(var)))\n\n        # Should not crash on anonymous variables\n        var.name = \"\"\n        val = self.handler.encode_setting(None, setting, var)\n        self.assertEqual(val, (var.name, 100 + vartype(var)))\n\n    def test_encode_list_settings(self):\n        setting = ContextSetting(None)\n\n        var1, var2 = self.domain[:2]\n        val = self.handler.encode_setting(None, setting, [None, var1, var2])\n        self.assertEqual(\n            val,\n            ([None,\n              (var1.name, 100 + vartype(var1)),\n              (var2.name, 100 + vartype(var2))], -3))\n\n        a_list = [1, 2, 3]\n        val = self.handler.encode_setting(None, setting, a_list)\n        self.assertEqual(val, [1, 2, 3])\n        self.assertIsNot(val, a_list)\n\n        a_list = []\n        val = self.handler.encode_setting(None, setting, a_list)\n        self.assertEqual(val, [])\n        self.assertIsNot(val, a_list)\n\n        a_list = [None, None]\n        val = self.handler.encode_setting(None, setting, a_list)\n        self.assertEqual(val, [None, None])\n        self.assertIsNot(val, a_list)\n\n    def test_decode_setting(self):\n        setting = ContextSetting(None)\n\n        var = self.domain[0]\n        val = self.handler.decode_setting(setting, (var.name, 100 + vartype(var)),\n                                          self.domain)\n        self.assertIs(val, var)\n\n        all_metas_domain = Domain([], metas=[var])\n        val = self.handler.decode_setting(setting, (var.name, 100 + vartype(var)),\n                                          all_metas_domain)\n        self.assertIs(val, var)\n\n    def test_decode_list_setting(self):\n        setting = ContextSetting(None)\n\n        var1, var2 = self.domain[:2]\n        val = self.handler.decode_setting(\n            setting,\n            ([None,\n              (var1.name, 100 + vartype(var1)),\n              (var2.name, 100 + vartype(var2))], -3),\n            self.domain)\n        self.assertEqual(val, [None, var1, var2])\n\n        val = self.handler.decode_setting(setting, [1, 2, 3], self.domain)\n        self.assertEqual(val, [1, 2, 3])\n\n    def test_backward_compatible_params(self):\n        with warnings.catch_warnings(record=True) as w:\n            warnings.simplefilter(\"always\")\n            DomainContextHandler(metas_in_res=True)\n            self.assertIn(OrangeDeprecationWarning,\n                          [x.category for x in w])\n\n    def create_context(self, domain, values):\n        if domain is None:\n            domain = Domain([])\n\n        context = self.handler.new_context(domain,\n                                           *self.handler.encode_domain(domain))\n        context.values = values\n        return context",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 15,
                            "end_lineno": 29,
                            "parent": {
                                "file_name": "Orange/widgets/tests/test_domain_context_handler.py",
                                "type": "class",
                                "name": "TestDomainContextHandler",
                                "content": "class TestDomainContextHandler(TestCase):\n    def setUp(self):\n        self.domain = Domain(\n            attributes=[ContinuousVariable('c1'),\n                        DiscreteVariable('d1', values='abc'),\n                        DiscreteVariable('d2', values='def')],\n            class_vars=[DiscreteVariable('d3', values='ghi')],\n            metas=[ContinuousVariable('c2'),\n                   DiscreteVariable('d4', values='jkl')]\n        )\n        self.args = (self.domain,\n                     {'c1': Continuous, 'd1': Discrete,\n                      'd2': Discrete, 'd3': Discrete},\n                     {'c2': Continuous, 'd4': Discrete, })\n        self.handler = DomainContextHandler()\n        self.handler.read_defaults = lambda: None\n\n    def test_encode_domain_with_match_none(self):\n        handler = DomainContextHandler(\n            match_values=DomainContextHandler.MATCH_VALUES_NONE)\n\n        encoded_attributes, encoded_metas = handler.encode_domain(self.domain)\n\n        self.assertEqual(encoded_attributes,\n                         {'c1': Continuous, 'd1': Discrete,\n                          'd2': Discrete, 'd3': Discrete})\n        self.assertEqual(encoded_metas, {'c2': Continuous, 'd4': Discrete, })\n\n    def test_encode_domain_with_match_class(self):\n        handler = DomainContextHandler(\n            match_values=DomainContextHandler.MATCH_VALUES_CLASS)\n\n        encoded_attributes, encoded_metas = handler.encode_domain(self.domain)\n\n        self.assertEqual(encoded_attributes,\n                         {'c1': Continuous, 'd1': Discrete, 'd2': Discrete,\n                          'd3': list('ghi')})\n        self.assertEqual(encoded_metas, {'c2': Continuous, 'd4': Discrete})\n\n    def test_encode_domain_with_match_all(self):\n        handler = DomainContextHandler(\n            match_values=DomainContextHandler.MATCH_VALUES_ALL)\n\n        encoded_attributes, encoded_metas = handler.encode_domain(self.domain)\n\n        self.assertEqual(encoded_attributes,\n                         {'c1': Continuous, 'd1': list('abc'),\n                          'd2': list('def'), 'd3': list('ghi')})\n        self.assertEqual(encoded_metas,\n                         {'c2': Continuous, 'd4': list('jkl')})\n\n    def test_match_returns_2_on_perfect_match(self):\n        context = Mock(\n            attributes=self.args[1], metas=self.args[2], values={})\n        self.assertEqual(2., self.handler.match(context, *self.args))\n\n    def test_match_returns_1_if_everything_matches(self):\n        self.handler.bind(SimpleWidget)\n\n        # Attributes in values\n        context = Mock(values=dict(\n            with_metas=('d1', Discrete),\n            required=('d1', Discrete)))\n        self.assertEqual(1., self.handler.match(context, *self.args))\n\n        # Metas in values\n        context = Mock(values=dict(\n            with_metas=('d4', Discrete),\n            required=('d1', Discrete)))\n        self.assertEqual(1., self.handler.match(context, *self.args))\n\n        # Attributes in lists\n        context = Mock(values=dict(\n            with_metas=[(\"d1\", Discrete)]\n        ))\n        self.assertEqual(1., self.handler.match(context, *self.args))\n\n        # Metas in lists\n        context = Mock(values=dict(\n            with_metas=[(\"d4\", Discrete)]\n        ))\n        self.assertEqual(1., self.handler.match(context, *self.args))\n\n    def test_match_returns_point_1_when_nothing_to_match(self):\n        self.handler.bind(SimpleWidget)\n\n        context = Mock(values={})\n        self.assertEqual(0.1, self.handler.match(context, *self.args))\n\n    def test_match_returns_zero_on_incompatible_context(self):\n        self.handler.bind(SimpleWidget)\n\n        # required\n        context = Mock(values=dict(required=('u', Discrete),\n                                   with_metas=('d1', Discrete)))\n        self.assertEqual(0, self.handler.match(context, *self.args))\n\n    def test_clone_context(self):\n        self.handler.bind(SimpleWidget)\n        context = self.create_context(self.domain, dict(\n            text=('u', -2),\n            with_metas=[('d1', Discrete), ('d1', Continuous),\n                        ('c1', Continuous), ('c1', Discrete)],\n            required=('u', Continuous)\n        ))\n\n        new_values = self.handler.clone_context(context, *self.args).values\n\n        self.assertEqual(new_values['text'], ('u', -2))\n        self.assertEqual([('d1', Discrete), ('c1', Continuous)],\n                         new_values['with_metas'])\n        self.assertNotIn('required', new_values)\n\n    def test_open_context(self):\n        self.handler.bind(SimpleWidget)\n        context = self.create_context(self.domain, dict(\n            text=('u', -2),\n            with_metas=[('d1', Discrete), ('d2', Discrete)]\n        ))\n        self.handler.global_contexts = \\\n            [Mock(values={}), context, Mock(values={})]\n\n        widget = SimpleWidget()\n        self.handler.initialize(widget)\n        old_metas_list = widget.with_metas\n        self.handler.open_context(widget, self.args[0])\n\n        context = widget.current_context\n        self.assertEqual(context.attributes, self.args[1])\n        self.assertEqual(context.metas, self.args[2])\n        self.assertIs(old_metas_list, widget.with_metas)\n\n        self.assertEqual(widget.text, 'u')\n        self.assertEqual(widget.with_metas, [('d1', Discrete),\n                                             ('d2', Discrete)])\n\n    def test_open_context_with_imperfect_match(self):\n        self.handler.bind(SimpleWidget)\n        context = self.create_context(None, dict(\n            text=('u', -2),\n            with_metas=[('d1', Discrete), ('d1', Continuous),\n                        ('c1', Continuous), ('c1', Discrete)]\n        ))\n        self.handler.global_contexts = \\\n            [Mock(values={}), context, Mock(values={})]\n\n        widget = SimpleWidget()\n        self.handler.initialize(widget)\n        self.handler.open_context(widget, self.args[0])\n\n        context = widget.current_context\n        self.assertEqual(context.attributes, self.args[1])\n        self.assertEqual(context.metas, self.args[2])\n\n        self.assertEqual(widget.text, 'u')\n        self.assertEqual(widget.with_metas, [('d1', Discrete),\n                                             ('c1', Continuous)])\n\n    def test_open_context_with_no_match(self):\n        self.handler.bind(SimpleWidget)\n        widget = SimpleWidget()\n        self.handler.initialize(widget)\n        widget.text = 'u'\n\n        self.handler.open_context(widget, self.args[0])\n\n        self.assertEqual(widget.text, 'u')\n        self.assertEqual(widget.with_metas, [])\n        context = widget.current_context\n        self.assertEqual(context.attributes, self.args[1])\n        self.assertEqual(context.metas, self.args[2])\n        self.assertEqual(context.values['text'], ('u', -2))\n\n    def test_filter_value(self):\n        setting = ContextSetting([])\n        setting.name = \"value\"\n\n        def test_filter(before_value, after_value):\n            data = dict(value=before_value)\n            self.handler.filter_value(setting, data, *self.args)\n            self.assertEqual(data.get(\"value\", None), after_value)\n\n        # filter list values\n        test_filter([], [])\n        # When list contains attributes asa tuple of (name, type),\n        # Attributes not present in domain should be filtered out\n        test_filter([(\"d1\", Discrete), (\"d1\", Continuous),\n                     (\"c1\", Continuous), (\"c1\", Discrete)],\n                    [(\"d1\", Discrete), (\"c1\", Continuous)])\n        # All other values in list should remain\n        test_filter([0, [1, 2, 3], \"abcd\", 5.4], [0, [1, 2, 3], \"abcd\", 5.4])\n\n    def test_encode_setting(self):\n        setting = ContextSetting(None)\n\n        var = self.domain[0]\n        val = self.handler.encode_setting(None, setting, var)\n        self.assertEqual(val, (var.name, 100 + vartype(var)))\n\n        # Should not crash on anonymous variables\n        var.name = \"\"\n        val = self.handler.encode_setting(None, setting, var)\n        self.assertEqual(val, (var.name, 100 + vartype(var)))\n\n    def test_encode_list_settings(self):\n        setting = ContextSetting(None)\n\n        var1, var2 = self.domain[:2]\n        val = self.handler.encode_setting(None, setting, [None, var1, var2])\n        self.assertEqual(\n            val,\n            ([None,\n              (var1.name, 100 + vartype(var1)),\n              (var2.name, 100 + vartype(var2))], -3))\n\n        a_list = [1, 2, 3]\n        val = self.handler.encode_setting(None, setting, a_list)\n        self.assertEqual(val, [1, 2, 3])\n        self.assertIsNot(val, a_list)\n\n        a_list = []\n        val = self.handler.encode_setting(None, setting, a_list)\n        self.assertEqual(val, [])\n        self.assertIsNot(val, a_list)\n\n        a_list = [None, None]\n        val = self.handler.encode_setting(None, setting, a_list)\n        self.assertEqual(val, [None, None])\n        self.assertIsNot(val, a_list)\n\n    def test_decode_setting(self):\n        setting = ContextSetting(None)\n\n        var = self.domain[0]\n        val = self.handler.decode_setting(setting, (var.name, 100 + vartype(var)),\n                                          self.domain)\n        self.assertIs(val, var)\n\n        all_metas_domain = Domain([], metas=[var])\n        val = self.handler.decode_setting(setting, (var.name, 100 + vartype(var)),\n                                          all_metas_domain)\n        self.assertIs(val, var)\n\n    def test_decode_list_setting(self):\n        setting = ContextSetting(None)\n\n        var1, var2 = self.domain[:2]\n        val = self.handler.decode_setting(\n            setting,\n            ([None,\n              (var1.name, 100 + vartype(var1)),\n              (var2.name, 100 + vartype(var2))], -3),\n            self.domain)\n        self.assertEqual(val, [None, var1, var2])\n\n        val = self.handler.decode_setting(setting, [1, 2, 3], self.domain)\n        self.assertEqual(val, [1, 2, 3])\n\n    def test_backward_compatible_params(self):\n        with warnings.catch_warnings(record=True) as w:\n            warnings.simplefilter(\"always\")\n            DomainContextHandler(metas_in_res=True)\n            self.assertIn(OrangeDeprecationWarning,\n                          [x.category for x in w])\n\n    def create_context(self, domain, values):\n        if domain is None:\n            domain = Domain([])\n\n        context = self.handler.new_context(domain,\n                                           *self.handler.encode_domain(domain))\n        context.values = values\n        return context",
                                "ast_type_str": "ClassDef",
                                "start_lineno": 14,
                                "end_lineno": 286,
                                "parent": null
                            }
                        }
                    ],
                    "added_entities": [],
                    "deleted_entities": []
                },
                {
                    "descriptor": {
                        "old_range": {
                            "start": 35,
                            "length": 9
                        },
                        "new_range": {
                            "start": 38,
                            "length": 10
                        },
                        "section": "class TestDomainContextHandler(TestCase):"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "        encoded_attributes, encoded_metas = handler.encode_domain(self.domain)",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "        self.assertEqual(encoded_attributes,",
                                "type": "context"
                            },
                            {
                                "content": "                         {'c1': Continuous, 'd1': Discrete,",
                                "type": "deleted"
                            },
                            {
                                "content": "                          'd2': Discrete, 'd3': Discrete})",
                                "type": "deleted"
                            },
                            {
                                "content": "        self.assertEqual(encoded_metas, {'c2': Continuous, 'd4': Discrete, })",
                                "type": "deleted"
                            },
                            {
                                "content": "                         {'c1': Continuous - 100, 'd1': Discrete - 100,",
                                "type": "added"
                            },
                            {
                                "content": "                          'd2': Discrete - 100, 'd3': Discrete - 100})",
                                "type": "added"
                            },
                            {
                                "content": "        self.assertEqual(encoded_metas,",
                                "type": "added"
                            },
                            {
                                "content": "                         {'c2': Continuous - 100, 'd4': Discrete - 100, })",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "    def test_encode_domain_with_match_class(self):",
                                "type": "context"
                            },
                            {
                                "content": "        handler = DomainContextHandler(",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [
                        {
                            "file_name": "Orange/widgets/tests/test_domain_context_handler.py",
                            "type": "class",
                            "name": "TestDomainContextHandler",
                            "content": "class TestDomainContextHandler(TestCase):\n    def setUp(self):\n        self.domain = Domain(\n            attributes=[ContinuousVariable('c1'),\n                        DiscreteVariable('d1', values='abc'),\n                        DiscreteVariable('d2', values='def')],\n            class_vars=[DiscreteVariable('d3', values='ghi')],\n            metas=[ContinuousVariable('c2'),\n                   DiscreteVariable('d4', values='jkl')]\n        )\n        self.args = (self.domain,\n                     {'c1': Continuous, 'd1': Discrete,\n                      'd2': Discrete, 'd3': Discrete},\n                     {'c2': Continuous, 'd4': Discrete, })\n        self.handler = DomainContextHandler()\n        self.handler.read_defaults = lambda: None\n\n    def test_encode_domain_with_match_none(self):\n        handler = DomainContextHandler(\n            match_values=DomainContextHandler.MATCH_VALUES_NONE)\n\n        encoded_attributes, encoded_metas = handler.encode_domain(self.domain)\n\n        self.assertEqual(encoded_attributes,\n                         {'c1': Continuous, 'd1': Discrete,\n                          'd2': Discrete, 'd3': Discrete})\n        self.assertEqual(encoded_metas, {'c2': Continuous, 'd4': Discrete, })\n\n    def test_encode_domain_with_match_class(self):\n        handler = DomainContextHandler(\n            match_values=DomainContextHandler.MATCH_VALUES_CLASS)\n\n        encoded_attributes, encoded_metas = handler.encode_domain(self.domain)\n\n        self.assertEqual(encoded_attributes,\n                         {'c1': Continuous, 'd1': Discrete, 'd2': Discrete,\n                          'd3': list('ghi')})\n        self.assertEqual(encoded_metas, {'c2': Continuous, 'd4': Discrete})\n\n    def test_encode_domain_with_match_all(self):\n        handler = DomainContextHandler(\n            match_values=DomainContextHandler.MATCH_VALUES_ALL)\n\n        encoded_attributes, encoded_metas = handler.encode_domain(self.domain)\n\n        self.assertEqual(encoded_attributes,\n                         {'c1': Continuous, 'd1': list('abc'),\n                          'd2': list('def'), 'd3': list('ghi')})\n        self.assertEqual(encoded_metas,\n                         {'c2': Continuous, 'd4': list('jkl')})\n\n    def test_match_returns_2_on_perfect_match(self):\n        context = Mock(\n            attributes=self.args[1], metas=self.args[2], values={})\n        self.assertEqual(2., self.handler.match(context, *self.args))\n\n    def test_match_returns_1_if_everything_matches(self):\n        self.handler.bind(SimpleWidget)\n\n        # Attributes in values\n        context = Mock(values=dict(\n            with_metas=('d1', Discrete),\n            required=('d1', Discrete)))\n        self.assertEqual(1., self.handler.match(context, *self.args))\n\n        # Metas in values\n        context = Mock(values=dict(\n            with_metas=('d4', Discrete),\n            required=('d1', Discrete)))\n        self.assertEqual(1., self.handler.match(context, *self.args))\n\n        # Attributes in lists\n        context = Mock(values=dict(\n            with_metas=[(\"d1\", Discrete)]\n        ))\n        self.assertEqual(1., self.handler.match(context, *self.args))\n\n        # Metas in lists\n        context = Mock(values=dict(\n            with_metas=[(\"d4\", Discrete)]\n        ))\n        self.assertEqual(1., self.handler.match(context, *self.args))\n\n    def test_match_returns_point_1_when_nothing_to_match(self):\n        self.handler.bind(SimpleWidget)\n\n        context = Mock(values={})\n        self.assertEqual(0.1, self.handler.match(context, *self.args))\n\n    def test_match_returns_zero_on_incompatible_context(self):\n        self.handler.bind(SimpleWidget)\n\n        # required\n        context = Mock(values=dict(required=('u', Discrete),\n                                   with_metas=('d1', Discrete)))\n        self.assertEqual(0, self.handler.match(context, *self.args))\n\n    def test_clone_context(self):\n        self.handler.bind(SimpleWidget)\n        context = self.create_context(self.domain, dict(\n            text=('u', -2),\n            with_metas=[('d1', Discrete), ('d1', Continuous),\n                        ('c1', Continuous), ('c1', Discrete)],\n            required=('u', Continuous)\n        ))\n\n        new_values = self.handler.clone_context(context, *self.args).values\n\n        self.assertEqual(new_values['text'], ('u', -2))\n        self.assertEqual([('d1', Discrete), ('c1', Continuous)],\n                         new_values['with_metas'])\n        self.assertNotIn('required', new_values)\n\n    def test_open_context(self):\n        self.handler.bind(SimpleWidget)\n        context = self.create_context(self.domain, dict(\n            text=('u', -2),\n            with_metas=[('d1', Discrete), ('d2', Discrete)]\n        ))\n        self.handler.global_contexts = \\\n            [Mock(values={}), context, Mock(values={})]\n\n        widget = SimpleWidget()\n        self.handler.initialize(widget)\n        old_metas_list = widget.with_metas\n        self.handler.open_context(widget, self.args[0])\n\n        context = widget.current_context\n        self.assertEqual(context.attributes, self.args[1])\n        self.assertEqual(context.metas, self.args[2])\n        self.assertIs(old_metas_list, widget.with_metas)\n\n        self.assertEqual(widget.text, 'u')\n        self.assertEqual(widget.with_metas, [('d1', Discrete),\n                                             ('d2', Discrete)])\n\n    def test_open_context_with_imperfect_match(self):\n        self.handler.bind(SimpleWidget)\n        context = self.create_context(None, dict(\n            text=('u', -2),\n            with_metas=[('d1', Discrete), ('d1', Continuous),\n                        ('c1', Continuous), ('c1', Discrete)]\n        ))\n        self.handler.global_contexts = \\\n            [Mock(values={}), context, Mock(values={})]\n\n        widget = SimpleWidget()\n        self.handler.initialize(widget)\n        self.handler.open_context(widget, self.args[0])\n\n        context = widget.current_context\n        self.assertEqual(context.attributes, self.args[1])\n        self.assertEqual(context.metas, self.args[2])\n\n        self.assertEqual(widget.text, 'u')\n        self.assertEqual(widget.with_metas, [('d1', Discrete),\n                                             ('c1', Continuous)])\n\n    def test_open_context_with_no_match(self):\n        self.handler.bind(SimpleWidget)\n        widget = SimpleWidget()\n        self.handler.initialize(widget)\n        widget.text = 'u'\n\n        self.handler.open_context(widget, self.args[0])\n\n        self.assertEqual(widget.text, 'u')\n        self.assertEqual(widget.with_metas, [])\n        context = widget.current_context\n        self.assertEqual(context.attributes, self.args[1])\n        self.assertEqual(context.metas, self.args[2])\n        self.assertEqual(context.values['text'], ('u', -2))\n\n    def test_filter_value(self):\n        setting = ContextSetting([])\n        setting.name = \"value\"\n\n        def test_filter(before_value, after_value):\n            data = dict(value=before_value)\n            self.handler.filter_value(setting, data, *self.args)\n            self.assertEqual(data.get(\"value\", None), after_value)\n\n        # filter list values\n        test_filter([], [])\n        # When list contains attributes asa tuple of (name, type),\n        # Attributes not present in domain should be filtered out\n        test_filter([(\"d1\", Discrete), (\"d1\", Continuous),\n                     (\"c1\", Continuous), (\"c1\", Discrete)],\n                    [(\"d1\", Discrete), (\"c1\", Continuous)])\n        # All other values in list should remain\n        test_filter([0, [1, 2, 3], \"abcd\", 5.4], [0, [1, 2, 3], \"abcd\", 5.4])\n\n    def test_encode_setting(self):\n        setting = ContextSetting(None)\n\n        var = self.domain[0]\n        val = self.handler.encode_setting(None, setting, var)\n        self.assertEqual(val, (var.name, 100 + vartype(var)))\n\n        # Should not crash on anonymous variables\n        var.name = \"\"\n        val = self.handler.encode_setting(None, setting, var)\n        self.assertEqual(val, (var.name, 100 + vartype(var)))\n\n    def test_encode_list_settings(self):\n        setting = ContextSetting(None)\n\n        var1, var2 = self.domain[:2]\n        val = self.handler.encode_setting(None, setting, [None, var1, var2])\n        self.assertEqual(\n            val,\n            ([None,\n              (var1.name, 100 + vartype(var1)),\n              (var2.name, 100 + vartype(var2))], -3))\n\n        a_list = [1, 2, 3]\n        val = self.handler.encode_setting(None, setting, a_list)\n        self.assertEqual(val, [1, 2, 3])\n        self.assertIsNot(val, a_list)\n\n        a_list = []\n        val = self.handler.encode_setting(None, setting, a_list)\n        self.assertEqual(val, [])\n        self.assertIsNot(val, a_list)\n\n        a_list = [None, None]\n        val = self.handler.encode_setting(None, setting, a_list)\n        self.assertEqual(val, [None, None])\n        self.assertIsNot(val, a_list)\n\n    def test_decode_setting(self):\n        setting = ContextSetting(None)\n\n        var = self.domain[0]\n        val = self.handler.decode_setting(setting, (var.name, 100 + vartype(var)),\n                                          self.domain)\n        self.assertIs(val, var)\n\n        all_metas_domain = Domain([], metas=[var])\n        val = self.handler.decode_setting(setting, (var.name, 100 + vartype(var)),\n                                          all_metas_domain)\n        self.assertIs(val, var)\n\n    def test_decode_list_setting(self):\n        setting = ContextSetting(None)\n\n        var1, var2 = self.domain[:2]\n        val = self.handler.decode_setting(\n            setting,\n            ([None,\n              (var1.name, 100 + vartype(var1)),\n              (var2.name, 100 + vartype(var2))], -3),\n            self.domain)\n        self.assertEqual(val, [None, var1, var2])\n\n        val = self.handler.decode_setting(setting, [1, 2, 3], self.domain)\n        self.assertEqual(val, [1, 2, 3])\n\n    def test_backward_compatible_params(self):\n        with warnings.catch_warnings(record=True) as w:\n            warnings.simplefilter(\"always\")\n            DomainContextHandler(metas_in_res=True)\n            self.assertIn(OrangeDeprecationWarning,\n                          [x.category for x in w])\n\n    def create_context(self, domain, values):\n        if domain is None:\n            domain = Domain([])\n\n        context = self.handler.new_context(domain,\n                                           *self.handler.encode_domain(domain))\n        context.values = values\n        return context",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 14,
                            "end_lineno": 286,
                            "parent": null
                        },
                        {
                            "file_name": "Orange/widgets/tests/test_domain_context_handler.py",
                            "type": "method",
                            "name": "TestDomainContextHandler.test_encode_domain_with_match_none",
                            "content": "class TestDomainContextHandler(TestCase):\n    def setUp(self):\n        self.domain = Domain(\n            attributes=[ContinuousVariable('c1'),\n                        DiscreteVariable('d1', values='abc'),\n                        DiscreteVariable('d2', values='def')],\n            class_vars=[DiscreteVariable('d3', values='ghi')],\n            metas=[ContinuousVariable('c2'),\n                   DiscreteVariable('d4', values='jkl')]\n        )\n        self.args = (self.domain,\n                     {'c1': Continuous, 'd1': Discrete,\n                      'd2': Discrete, 'd3': Discrete},\n                     {'c2': Continuous, 'd4': Discrete, })\n        self.handler = DomainContextHandler()\n        self.handler.read_defaults = lambda: None\n\n    def test_encode_domain_with_match_none(self):\n        handler = DomainContextHandler(\n            match_values=DomainContextHandler.MATCH_VALUES_NONE)\n\n        encoded_attributes, encoded_metas = handler.encode_domain(self.domain)\n\n        self.assertEqual(encoded_attributes,\n                         {'c1': Continuous, 'd1': Discrete,\n                          'd2': Discrete, 'd3': Discrete})\n        self.assertEqual(encoded_metas, {'c2': Continuous, 'd4': Discrete, })\n\n    def test_encode_domain_with_match_class(self):\n        handler = DomainContextHandler(\n            match_values=DomainContextHandler.MATCH_VALUES_CLASS)\n\n        encoded_attributes, encoded_metas = handler.encode_domain(self.domain)\n\n        self.assertEqual(encoded_attributes,\n                         {'c1': Continuous, 'd1': Discrete, 'd2': Discrete,\n                          'd3': list('ghi')})\n        self.assertEqual(encoded_metas, {'c2': Continuous, 'd4': Discrete})\n\n    def test_encode_domain_with_match_all(self):\n        handler = DomainContextHandler(\n            match_values=DomainContextHandler.MATCH_VALUES_ALL)\n\n        encoded_attributes, encoded_metas = handler.encode_domain(self.domain)\n\n        self.assertEqual(encoded_attributes,\n                         {'c1': Continuous, 'd1': list('abc'),\n                          'd2': list('def'), 'd3': list('ghi')})\n        self.assertEqual(encoded_metas,\n                         {'c2': Continuous, 'd4': list('jkl')})\n\n    def test_match_returns_2_on_perfect_match(self):\n        context = Mock(\n            attributes=self.args[1], metas=self.args[2], values={})\n        self.assertEqual(2., self.handler.match(context, *self.args))\n\n    def test_match_returns_1_if_everything_matches(self):\n        self.handler.bind(SimpleWidget)\n\n        # Attributes in values\n        context = Mock(values=dict(\n            with_metas=('d1', Discrete),\n            required=('d1', Discrete)))\n        self.assertEqual(1., self.handler.match(context, *self.args))\n\n        # Metas in values\n        context = Mock(values=dict(\n            with_metas=('d4', Discrete),\n            required=('d1', Discrete)))\n        self.assertEqual(1., self.handler.match(context, *self.args))\n\n        # Attributes in lists\n        context = Mock(values=dict(\n            with_metas=[(\"d1\", Discrete)]\n        ))\n        self.assertEqual(1., self.handler.match(context, *self.args))\n\n        # Metas in lists\n        context = Mock(values=dict(\n            with_metas=[(\"d4\", Discrete)]\n        ))\n        self.assertEqual(1., self.handler.match(context, *self.args))\n\n    def test_match_returns_point_1_when_nothing_to_match(self):\n        self.handler.bind(SimpleWidget)\n\n        context = Mock(values={})\n        self.assertEqual(0.1, self.handler.match(context, *self.args))\n\n    def test_match_returns_zero_on_incompatible_context(self):\n        self.handler.bind(SimpleWidget)\n\n        # required\n        context = Mock(values=dict(required=('u', Discrete),\n                                   with_metas=('d1', Discrete)))\n        self.assertEqual(0, self.handler.match(context, *self.args))\n\n    def test_clone_context(self):\n        self.handler.bind(SimpleWidget)\n        context = self.create_context(self.domain, dict(\n            text=('u', -2),\n            with_metas=[('d1', Discrete), ('d1', Continuous),\n                        ('c1', Continuous), ('c1', Discrete)],\n            required=('u', Continuous)\n        ))\n\n        new_values = self.handler.clone_context(context, *self.args).values\n\n        self.assertEqual(new_values['text'], ('u', -2))\n        self.assertEqual([('d1', Discrete), ('c1', Continuous)],\n                         new_values['with_metas'])\n        self.assertNotIn('required', new_values)\n\n    def test_open_context(self):\n        self.handler.bind(SimpleWidget)\n        context = self.create_context(self.domain, dict(\n            text=('u', -2),\n            with_metas=[('d1', Discrete), ('d2', Discrete)]\n        ))\n        self.handler.global_contexts = \\\n            [Mock(values={}), context, Mock(values={})]\n\n        widget = SimpleWidget()\n        self.handler.initialize(widget)\n        old_metas_list = widget.with_metas\n        self.handler.open_context(widget, self.args[0])\n\n        context = widget.current_context\n        self.assertEqual(context.attributes, self.args[1])\n        self.assertEqual(context.metas, self.args[2])\n        self.assertIs(old_metas_list, widget.with_metas)\n\n        self.assertEqual(widget.text, 'u')\n        self.assertEqual(widget.with_metas, [('d1', Discrete),\n                                             ('d2', Discrete)])\n\n    def test_open_context_with_imperfect_match(self):\n        self.handler.bind(SimpleWidget)\n        context = self.create_context(None, dict(\n            text=('u', -2),\n            with_metas=[('d1', Discrete), ('d1', Continuous),\n                        ('c1', Continuous), ('c1', Discrete)]\n        ))\n        self.handler.global_contexts = \\\n            [Mock(values={}), context, Mock(values={})]\n\n        widget = SimpleWidget()\n        self.handler.initialize(widget)\n        self.handler.open_context(widget, self.args[0])\n\n        context = widget.current_context\n        self.assertEqual(context.attributes, self.args[1])\n        self.assertEqual(context.metas, self.args[2])\n\n        self.assertEqual(widget.text, 'u')\n        self.assertEqual(widget.with_metas, [('d1', Discrete),\n                                             ('c1', Continuous)])\n\n    def test_open_context_with_no_match(self):\n        self.handler.bind(SimpleWidget)\n        widget = SimpleWidget()\n        self.handler.initialize(widget)\n        widget.text = 'u'\n\n        self.handler.open_context(widget, self.args[0])\n\n        self.assertEqual(widget.text, 'u')\n        self.assertEqual(widget.with_metas, [])\n        context = widget.current_context\n        self.assertEqual(context.attributes, self.args[1])\n        self.assertEqual(context.metas, self.args[2])\n        self.assertEqual(context.values['text'], ('u', -2))\n\n    def test_filter_value(self):\n        setting = ContextSetting([])\n        setting.name = \"value\"\n\n        def test_filter(before_value, after_value):\n            data = dict(value=before_value)\n            self.handler.filter_value(setting, data, *self.args)\n            self.assertEqual(data.get(\"value\", None), after_value)\n\n        # filter list values\n        test_filter([], [])\n        # When list contains attributes asa tuple of (name, type),\n        # Attributes not present in domain should be filtered out\n        test_filter([(\"d1\", Discrete), (\"d1\", Continuous),\n                     (\"c1\", Continuous), (\"c1\", Discrete)],\n                    [(\"d1\", Discrete), (\"c1\", Continuous)])\n        # All other values in list should remain\n        test_filter([0, [1, 2, 3], \"abcd\", 5.4], [0, [1, 2, 3], \"abcd\", 5.4])\n\n    def test_encode_setting(self):\n        setting = ContextSetting(None)\n\n        var = self.domain[0]\n        val = self.handler.encode_setting(None, setting, var)\n        self.assertEqual(val, (var.name, 100 + vartype(var)))\n\n        # Should not crash on anonymous variables\n        var.name = \"\"\n        val = self.handler.encode_setting(None, setting, var)\n        self.assertEqual(val, (var.name, 100 + vartype(var)))\n\n    def test_encode_list_settings(self):\n        setting = ContextSetting(None)\n\n        var1, var2 = self.domain[:2]\n        val = self.handler.encode_setting(None, setting, [None, var1, var2])\n        self.assertEqual(\n            val,\n            ([None,\n              (var1.name, 100 + vartype(var1)),\n              (var2.name, 100 + vartype(var2))], -3))\n\n        a_list = [1, 2, 3]\n        val = self.handler.encode_setting(None, setting, a_list)\n        self.assertEqual(val, [1, 2, 3])\n        self.assertIsNot(val, a_list)\n\n        a_list = []\n        val = self.handler.encode_setting(None, setting, a_list)\n        self.assertEqual(val, [])\n        self.assertIsNot(val, a_list)\n\n        a_list = [None, None]\n        val = self.handler.encode_setting(None, setting, a_list)\n        self.assertEqual(val, [None, None])\n        self.assertIsNot(val, a_list)\n\n    def test_decode_setting(self):\n        setting = ContextSetting(None)\n\n        var = self.domain[0]\n        val = self.handler.decode_setting(setting, (var.name, 100 + vartype(var)),\n                                          self.domain)\n        self.assertIs(val, var)\n\n        all_metas_domain = Domain([], metas=[var])\n        val = self.handler.decode_setting(setting, (var.name, 100 + vartype(var)),\n                                          all_metas_domain)\n        self.assertIs(val, var)\n\n    def test_decode_list_setting(self):\n        setting = ContextSetting(None)\n\n        var1, var2 = self.domain[:2]\n        val = self.handler.decode_setting(\n            setting,\n            ([None,\n              (var1.name, 100 + vartype(var1)),\n              (var2.name, 100 + vartype(var2))], -3),\n            self.domain)\n        self.assertEqual(val, [None, var1, var2])\n\n        val = self.handler.decode_setting(setting, [1, 2, 3], self.domain)\n        self.assertEqual(val, [1, 2, 3])\n\n    def test_backward_compatible_params(self):\n        with warnings.catch_warnings(record=True) as w:\n            warnings.simplefilter(\"always\")\n            DomainContextHandler(metas_in_res=True)\n            self.assertIn(OrangeDeprecationWarning,\n                          [x.category for x in w])\n\n    def create_context(self, domain, values):\n        if domain is None:\n            domain = Domain([])\n\n        context = self.handler.new_context(domain,\n                                           *self.handler.encode_domain(domain))\n        context.values = values\n        return context",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 31,
                            "end_lineno": 40,
                            "parent": {
                                "file_name": "Orange/widgets/tests/test_domain_context_handler.py",
                                "type": "class",
                                "name": "TestDomainContextHandler",
                                "content": "class TestDomainContextHandler(TestCase):\n    def setUp(self):\n        self.domain = Domain(\n            attributes=[ContinuousVariable('c1'),\n                        DiscreteVariable('d1', values='abc'),\n                        DiscreteVariable('d2', values='def')],\n            class_vars=[DiscreteVariable('d3', values='ghi')],\n            metas=[ContinuousVariable('c2'),\n                   DiscreteVariable('d4', values='jkl')]\n        )\n        self.args = (self.domain,\n                     {'c1': Continuous, 'd1': Discrete,\n                      'd2': Discrete, 'd3': Discrete},\n                     {'c2': Continuous, 'd4': Discrete, })\n        self.handler = DomainContextHandler()\n        self.handler.read_defaults = lambda: None\n\n    def test_encode_domain_with_match_none(self):\n        handler = DomainContextHandler(\n            match_values=DomainContextHandler.MATCH_VALUES_NONE)\n\n        encoded_attributes, encoded_metas = handler.encode_domain(self.domain)\n\n        self.assertEqual(encoded_attributes,\n                         {'c1': Continuous, 'd1': Discrete,\n                          'd2': Discrete, 'd3': Discrete})\n        self.assertEqual(encoded_metas, {'c2': Continuous, 'd4': Discrete, })\n\n    def test_encode_domain_with_match_class(self):\n        handler = DomainContextHandler(\n            match_values=DomainContextHandler.MATCH_VALUES_CLASS)\n\n        encoded_attributes, encoded_metas = handler.encode_domain(self.domain)\n\n        self.assertEqual(encoded_attributes,\n                         {'c1': Continuous, 'd1': Discrete, 'd2': Discrete,\n                          'd3': list('ghi')})\n        self.assertEqual(encoded_metas, {'c2': Continuous, 'd4': Discrete})\n\n    def test_encode_domain_with_match_all(self):\n        handler = DomainContextHandler(\n            match_values=DomainContextHandler.MATCH_VALUES_ALL)\n\n        encoded_attributes, encoded_metas = handler.encode_domain(self.domain)\n\n        self.assertEqual(encoded_attributes,\n                         {'c1': Continuous, 'd1': list('abc'),\n                          'd2': list('def'), 'd3': list('ghi')})\n        self.assertEqual(encoded_metas,\n                         {'c2': Continuous, 'd4': list('jkl')})\n\n    def test_match_returns_2_on_perfect_match(self):\n        context = Mock(\n            attributes=self.args[1], metas=self.args[2], values={})\n        self.assertEqual(2., self.handler.match(context, *self.args))\n\n    def test_match_returns_1_if_everything_matches(self):\n        self.handler.bind(SimpleWidget)\n\n        # Attributes in values\n        context = Mock(values=dict(\n            with_metas=('d1', Discrete),\n            required=('d1', Discrete)))\n        self.assertEqual(1., self.handler.match(context, *self.args))\n\n        # Metas in values\n        context = Mock(values=dict(\n            with_metas=('d4', Discrete),\n            required=('d1', Discrete)))\n        self.assertEqual(1., self.handler.match(context, *self.args))\n\n        # Attributes in lists\n        context = Mock(values=dict(\n            with_metas=[(\"d1\", Discrete)]\n        ))\n        self.assertEqual(1., self.handler.match(context, *self.args))\n\n        # Metas in lists\n        context = Mock(values=dict(\n            with_metas=[(\"d4\", Discrete)]\n        ))\n        self.assertEqual(1., self.handler.match(context, *self.args))\n\n    def test_match_returns_point_1_when_nothing_to_match(self):\n        self.handler.bind(SimpleWidget)\n\n        context = Mock(values={})\n        self.assertEqual(0.1, self.handler.match(context, *self.args))\n\n    def test_match_returns_zero_on_incompatible_context(self):\n        self.handler.bind(SimpleWidget)\n\n        # required\n        context = Mock(values=dict(required=('u', Discrete),\n                                   with_metas=('d1', Discrete)))\n        self.assertEqual(0, self.handler.match(context, *self.args))\n\n    def test_clone_context(self):\n        self.handler.bind(SimpleWidget)\n        context = self.create_context(self.domain, dict(\n            text=('u', -2),\n            with_metas=[('d1', Discrete), ('d1', Continuous),\n                        ('c1', Continuous), ('c1', Discrete)],\n            required=('u', Continuous)\n        ))\n\n        new_values = self.handler.clone_context(context, *self.args).values\n\n        self.assertEqual(new_values['text'], ('u', -2))\n        self.assertEqual([('d1', Discrete), ('c1', Continuous)],\n                         new_values['with_metas'])\n        self.assertNotIn('required', new_values)\n\n    def test_open_context(self):\n        self.handler.bind(SimpleWidget)\n        context = self.create_context(self.domain, dict(\n            text=('u', -2),\n            with_metas=[('d1', Discrete), ('d2', Discrete)]\n        ))\n        self.handler.global_contexts = \\\n            [Mock(values={}), context, Mock(values={})]\n\n        widget = SimpleWidget()\n        self.handler.initialize(widget)\n        old_metas_list = widget.with_metas\n        self.handler.open_context(widget, self.args[0])\n\n        context = widget.current_context\n        self.assertEqual(context.attributes, self.args[1])\n        self.assertEqual(context.metas, self.args[2])\n        self.assertIs(old_metas_list, widget.with_metas)\n\n        self.assertEqual(widget.text, 'u')\n        self.assertEqual(widget.with_metas, [('d1', Discrete),\n                                             ('d2', Discrete)])\n\n    def test_open_context_with_imperfect_match(self):\n        self.handler.bind(SimpleWidget)\n        context = self.create_context(None, dict(\n            text=('u', -2),\n            with_metas=[('d1', Discrete), ('d1', Continuous),\n                        ('c1', Continuous), ('c1', Discrete)]\n        ))\n        self.handler.global_contexts = \\\n            [Mock(values={}), context, Mock(values={})]\n\n        widget = SimpleWidget()\n        self.handler.initialize(widget)\n        self.handler.open_context(widget, self.args[0])\n\n        context = widget.current_context\n        self.assertEqual(context.attributes, self.args[1])\n        self.assertEqual(context.metas, self.args[2])\n\n        self.assertEqual(widget.text, 'u')\n        self.assertEqual(widget.with_metas, [('d1', Discrete),\n                                             ('c1', Continuous)])\n\n    def test_open_context_with_no_match(self):\n        self.handler.bind(SimpleWidget)\n        widget = SimpleWidget()\n        self.handler.initialize(widget)\n        widget.text = 'u'\n\n        self.handler.open_context(widget, self.args[0])\n\n        self.assertEqual(widget.text, 'u')\n        self.assertEqual(widget.with_metas, [])\n        context = widget.current_context\n        self.assertEqual(context.attributes, self.args[1])\n        self.assertEqual(context.metas, self.args[2])\n        self.assertEqual(context.values['text'], ('u', -2))\n\n    def test_filter_value(self):\n        setting = ContextSetting([])\n        setting.name = \"value\"\n\n        def test_filter(before_value, after_value):\n            data = dict(value=before_value)\n            self.handler.filter_value(setting, data, *self.args)\n            self.assertEqual(data.get(\"value\", None), after_value)\n\n        # filter list values\n        test_filter([], [])\n        # When list contains attributes asa tuple of (name, type),\n        # Attributes not present in domain should be filtered out\n        test_filter([(\"d1\", Discrete), (\"d1\", Continuous),\n                     (\"c1\", Continuous), (\"c1\", Discrete)],\n                    [(\"d1\", Discrete), (\"c1\", Continuous)])\n        # All other values in list should remain\n        test_filter([0, [1, 2, 3], \"abcd\", 5.4], [0, [1, 2, 3], \"abcd\", 5.4])\n\n    def test_encode_setting(self):\n        setting = ContextSetting(None)\n\n        var = self.domain[0]\n        val = self.handler.encode_setting(None, setting, var)\n        self.assertEqual(val, (var.name, 100 + vartype(var)))\n\n        # Should not crash on anonymous variables\n        var.name = \"\"\n        val = self.handler.encode_setting(None, setting, var)\n        self.assertEqual(val, (var.name, 100 + vartype(var)))\n\n    def test_encode_list_settings(self):\n        setting = ContextSetting(None)\n\n        var1, var2 = self.domain[:2]\n        val = self.handler.encode_setting(None, setting, [None, var1, var2])\n        self.assertEqual(\n            val,\n            ([None,\n              (var1.name, 100 + vartype(var1)),\n              (var2.name, 100 + vartype(var2))], -3))\n\n        a_list = [1, 2, 3]\n        val = self.handler.encode_setting(None, setting, a_list)\n        self.assertEqual(val, [1, 2, 3])\n        self.assertIsNot(val, a_list)\n\n        a_list = []\n        val = self.handler.encode_setting(None, setting, a_list)\n        self.assertEqual(val, [])\n        self.assertIsNot(val, a_list)\n\n        a_list = [None, None]\n        val = self.handler.encode_setting(None, setting, a_list)\n        self.assertEqual(val, [None, None])\n        self.assertIsNot(val, a_list)\n\n    def test_decode_setting(self):\n        setting = ContextSetting(None)\n\n        var = self.domain[0]\n        val = self.handler.decode_setting(setting, (var.name, 100 + vartype(var)),\n                                          self.domain)\n        self.assertIs(val, var)\n\n        all_metas_domain = Domain([], metas=[var])\n        val = self.handler.decode_setting(setting, (var.name, 100 + vartype(var)),\n                                          all_metas_domain)\n        self.assertIs(val, var)\n\n    def test_decode_list_setting(self):\n        setting = ContextSetting(None)\n\n        var1, var2 = self.domain[:2]\n        val = self.handler.decode_setting(\n            setting,\n            ([None,\n              (var1.name, 100 + vartype(var1)),\n              (var2.name, 100 + vartype(var2))], -3),\n            self.domain)\n        self.assertEqual(val, [None, var1, var2])\n\n        val = self.handler.decode_setting(setting, [1, 2, 3], self.domain)\n        self.assertEqual(val, [1, 2, 3])\n\n    def test_backward_compatible_params(self):\n        with warnings.catch_warnings(record=True) as w:\n            warnings.simplefilter(\"always\")\n            DomainContextHandler(metas_in_res=True)\n            self.assertIn(OrangeDeprecationWarning,\n                          [x.category for x in w])\n\n    def create_context(self, domain, values):\n        if domain is None:\n            domain = Domain([])\n\n        context = self.handler.new_context(domain,\n                                           *self.handler.encode_domain(domain))\n        context.values = values\n        return context",
                                "ast_type_str": "ClassDef",
                                "start_lineno": 14,
                                "end_lineno": 286,
                                "parent": null
                            }
                        }
                    ],
                    "added_entities": [],
                    "deleted_entities": []
                },
                {
                    "descriptor": {
                        "old_range": {
                            "start": 46,
                            "length": 9
                        },
                        "new_range": {
                            "start": 50,
                            "length": 11
                        },
                        "section": "class TestDomainContextHandler(TestCase):"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "        encoded_attributes, encoded_metas = handler.encode_domain(self.domain)",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "        self.assertEqual(encoded_attributes,",
                                "type": "context"
                            },
                            {
                                "content": "                         {'c1': Continuous, 'd1': Discrete, 'd2': Discrete,",
                                "type": "deleted"
                            },
                            {
                                "content": "                         {'c1': Continuous - 100, 'd1': Discrete - 100,",
                                "type": "added"
                            },
                            {
                                "content": "                          'd2': Discrete - 100,",
                                "type": "added"
                            },
                            {
                                "content": "                          'd3': list('ghi')})",
                                "type": "context"
                            },
                            {
                                "content": "        self.assertEqual(encoded_metas, {'c2': Continuous, 'd4': Discrete})",
                                "type": "deleted"
                            },
                            {
                                "content": "        self.assertEqual(encoded_metas,",
                                "type": "added"
                            },
                            {
                                "content": "                         {'c2': Continuous - 100, 'd4': Discrete - 100})",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "    def test_encode_domain_with_match_all(self):",
                                "type": "context"
                            },
                            {
                                "content": "        handler = DomainContextHandler(",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [
                        {
                            "file_name": "Orange/widgets/tests/test_domain_context_handler.py",
                            "type": "class",
                            "name": "TestDomainContextHandler",
                            "content": "class TestDomainContextHandler(TestCase):\n    def setUp(self):\n        self.domain = Domain(\n            attributes=[ContinuousVariable('c1'),\n                        DiscreteVariable('d1', values='abc'),\n                        DiscreteVariable('d2', values='def')],\n            class_vars=[DiscreteVariable('d3', values='ghi')],\n            metas=[ContinuousVariable('c2'),\n                   DiscreteVariable('d4', values='jkl')]\n        )\n        self.args = (self.domain,\n                     {'c1': Continuous, 'd1': Discrete,\n                      'd2': Discrete, 'd3': Discrete},\n                     {'c2': Continuous, 'd4': Discrete, })\n        self.handler = DomainContextHandler()\n        self.handler.read_defaults = lambda: None\n\n    def test_encode_domain_with_match_none(self):\n        handler = DomainContextHandler(\n            match_values=DomainContextHandler.MATCH_VALUES_NONE)\n\n        encoded_attributes, encoded_metas = handler.encode_domain(self.domain)\n\n        self.assertEqual(encoded_attributes,\n                         {'c1': Continuous, 'd1': Discrete,\n                          'd2': Discrete, 'd3': Discrete})\n        self.assertEqual(encoded_metas, {'c2': Continuous, 'd4': Discrete, })\n\n    def test_encode_domain_with_match_class(self):\n        handler = DomainContextHandler(\n            match_values=DomainContextHandler.MATCH_VALUES_CLASS)\n\n        encoded_attributes, encoded_metas = handler.encode_domain(self.domain)\n\n        self.assertEqual(encoded_attributes,\n                         {'c1': Continuous, 'd1': Discrete, 'd2': Discrete,\n                          'd3': list('ghi')})\n        self.assertEqual(encoded_metas, {'c2': Continuous, 'd4': Discrete})\n\n    def test_encode_domain_with_match_all(self):\n        handler = DomainContextHandler(\n            match_values=DomainContextHandler.MATCH_VALUES_ALL)\n\n        encoded_attributes, encoded_metas = handler.encode_domain(self.domain)\n\n        self.assertEqual(encoded_attributes,\n                         {'c1': Continuous, 'd1': list('abc'),\n                          'd2': list('def'), 'd3': list('ghi')})\n        self.assertEqual(encoded_metas,\n                         {'c2': Continuous, 'd4': list('jkl')})\n\n    def test_match_returns_2_on_perfect_match(self):\n        context = Mock(\n            attributes=self.args[1], metas=self.args[2], values={})\n        self.assertEqual(2., self.handler.match(context, *self.args))\n\n    def test_match_returns_1_if_everything_matches(self):\n        self.handler.bind(SimpleWidget)\n\n        # Attributes in values\n        context = Mock(values=dict(\n            with_metas=('d1', Discrete),\n            required=('d1', Discrete)))\n        self.assertEqual(1., self.handler.match(context, *self.args))\n\n        # Metas in values\n        context = Mock(values=dict(\n            with_metas=('d4', Discrete),\n            required=('d1', Discrete)))\n        self.assertEqual(1., self.handler.match(context, *self.args))\n\n        # Attributes in lists\n        context = Mock(values=dict(\n            with_metas=[(\"d1\", Discrete)]\n        ))\n        self.assertEqual(1., self.handler.match(context, *self.args))\n\n        # Metas in lists\n        context = Mock(values=dict(\n            with_metas=[(\"d4\", Discrete)]\n        ))\n        self.assertEqual(1., self.handler.match(context, *self.args))\n\n    def test_match_returns_point_1_when_nothing_to_match(self):\n        self.handler.bind(SimpleWidget)\n\n        context = Mock(values={})\n        self.assertEqual(0.1, self.handler.match(context, *self.args))\n\n    def test_match_returns_zero_on_incompatible_context(self):\n        self.handler.bind(SimpleWidget)\n\n        # required\n        context = Mock(values=dict(required=('u', Discrete),\n                                   with_metas=('d1', Discrete)))\n        self.assertEqual(0, self.handler.match(context, *self.args))\n\n    def test_clone_context(self):\n        self.handler.bind(SimpleWidget)\n        context = self.create_context(self.domain, dict(\n            text=('u', -2),\n            with_metas=[('d1', Discrete), ('d1', Continuous),\n                        ('c1', Continuous), ('c1', Discrete)],\n            required=('u', Continuous)\n        ))\n\n        new_values = self.handler.clone_context(context, *self.args).values\n\n        self.assertEqual(new_values['text'], ('u', -2))\n        self.assertEqual([('d1', Discrete), ('c1', Continuous)],\n                         new_values['with_metas'])\n        self.assertNotIn('required', new_values)\n\n    def test_open_context(self):\n        self.handler.bind(SimpleWidget)\n        context = self.create_context(self.domain, dict(\n            text=('u', -2),\n            with_metas=[('d1', Discrete), ('d2', Discrete)]\n        ))\n        self.handler.global_contexts = \\\n            [Mock(values={}), context, Mock(values={})]\n\n        widget = SimpleWidget()\n        self.handler.initialize(widget)\n        old_metas_list = widget.with_metas\n        self.handler.open_context(widget, self.args[0])\n\n        context = widget.current_context\n        self.assertEqual(context.attributes, self.args[1])\n        self.assertEqual(context.metas, self.args[2])\n        self.assertIs(old_metas_list, widget.with_metas)\n\n        self.assertEqual(widget.text, 'u')\n        self.assertEqual(widget.with_metas, [('d1', Discrete),\n                                             ('d2', Discrete)])\n\n    def test_open_context_with_imperfect_match(self):\n        self.handler.bind(SimpleWidget)\n        context = self.create_context(None, dict(\n            text=('u', -2),\n            with_metas=[('d1', Discrete), ('d1', Continuous),\n                        ('c1', Continuous), ('c1', Discrete)]\n        ))\n        self.handler.global_contexts = \\\n            [Mock(values={}), context, Mock(values={})]\n\n        widget = SimpleWidget()\n        self.handler.initialize(widget)\n        self.handler.open_context(widget, self.args[0])\n\n        context = widget.current_context\n        self.assertEqual(context.attributes, self.args[1])\n        self.assertEqual(context.metas, self.args[2])\n\n        self.assertEqual(widget.text, 'u')\n        self.assertEqual(widget.with_metas, [('d1', Discrete),\n                                             ('c1', Continuous)])\n\n    def test_open_context_with_no_match(self):\n        self.handler.bind(SimpleWidget)\n        widget = SimpleWidget()\n        self.handler.initialize(widget)\n        widget.text = 'u'\n\n        self.handler.open_context(widget, self.args[0])\n\n        self.assertEqual(widget.text, 'u')\n        self.assertEqual(widget.with_metas, [])\n        context = widget.current_context\n        self.assertEqual(context.attributes, self.args[1])\n        self.assertEqual(context.metas, self.args[2])\n        self.assertEqual(context.values['text'], ('u', -2))\n\n    def test_filter_value(self):\n        setting = ContextSetting([])\n        setting.name = \"value\"\n\n        def test_filter(before_value, after_value):\n            data = dict(value=before_value)\n            self.handler.filter_value(setting, data, *self.args)\n            self.assertEqual(data.get(\"value\", None), after_value)\n\n        # filter list values\n        test_filter([], [])\n        # When list contains attributes asa tuple of (name, type),\n        # Attributes not present in domain should be filtered out\n        test_filter([(\"d1\", Discrete), (\"d1\", Continuous),\n                     (\"c1\", Continuous), (\"c1\", Discrete)],\n                    [(\"d1\", Discrete), (\"c1\", Continuous)])\n        # All other values in list should remain\n        test_filter([0, [1, 2, 3], \"abcd\", 5.4], [0, [1, 2, 3], \"abcd\", 5.4])\n\n    def test_encode_setting(self):\n        setting = ContextSetting(None)\n\n        var = self.domain[0]\n        val = self.handler.encode_setting(None, setting, var)\n        self.assertEqual(val, (var.name, 100 + vartype(var)))\n\n        # Should not crash on anonymous variables\n        var.name = \"\"\n        val = self.handler.encode_setting(None, setting, var)\n        self.assertEqual(val, (var.name, 100 + vartype(var)))\n\n    def test_encode_list_settings(self):\n        setting = ContextSetting(None)\n\n        var1, var2 = self.domain[:2]\n        val = self.handler.encode_setting(None, setting, [None, var1, var2])\n        self.assertEqual(\n            val,\n            ([None,\n              (var1.name, 100 + vartype(var1)),\n              (var2.name, 100 + vartype(var2))], -3))\n\n        a_list = [1, 2, 3]\n        val = self.handler.encode_setting(None, setting, a_list)\n        self.assertEqual(val, [1, 2, 3])\n        self.assertIsNot(val, a_list)\n\n        a_list = []\n        val = self.handler.encode_setting(None, setting, a_list)\n        self.assertEqual(val, [])\n        self.assertIsNot(val, a_list)\n\n        a_list = [None, None]\n        val = self.handler.encode_setting(None, setting, a_list)\n        self.assertEqual(val, [None, None])\n        self.assertIsNot(val, a_list)\n\n    def test_decode_setting(self):\n        setting = ContextSetting(None)\n\n        var = self.domain[0]\n        val = self.handler.decode_setting(setting, (var.name, 100 + vartype(var)),\n                                          self.domain)\n        self.assertIs(val, var)\n\n        all_metas_domain = Domain([], metas=[var])\n        val = self.handler.decode_setting(setting, (var.name, 100 + vartype(var)),\n                                          all_metas_domain)\n        self.assertIs(val, var)\n\n    def test_decode_list_setting(self):\n        setting = ContextSetting(None)\n\n        var1, var2 = self.domain[:2]\n        val = self.handler.decode_setting(\n            setting,\n            ([None,\n              (var1.name, 100 + vartype(var1)),\n              (var2.name, 100 + vartype(var2))], -3),\n            self.domain)\n        self.assertEqual(val, [None, var1, var2])\n\n        val = self.handler.decode_setting(setting, [1, 2, 3], self.domain)\n        self.assertEqual(val, [1, 2, 3])\n\n    def test_backward_compatible_params(self):\n        with warnings.catch_warnings(record=True) as w:\n            warnings.simplefilter(\"always\")\n            DomainContextHandler(metas_in_res=True)\n            self.assertIn(OrangeDeprecationWarning,\n                          [x.category for x in w])\n\n    def create_context(self, domain, values):\n        if domain is None:\n            domain = Domain([])\n\n        context = self.handler.new_context(domain,\n                                           *self.handler.encode_domain(domain))\n        context.values = values\n        return context",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 14,
                            "end_lineno": 286,
                            "parent": null
                        },
                        {
                            "file_name": "Orange/widgets/tests/test_domain_context_handler.py",
                            "type": "method",
                            "name": "TestDomainContextHandler.test_encode_domain_with_match_class",
                            "content": "class TestDomainContextHandler(TestCase):\n    def setUp(self):\n        self.domain = Domain(\n            attributes=[ContinuousVariable('c1'),\n                        DiscreteVariable('d1', values='abc'),\n                        DiscreteVariable('d2', values='def')],\n            class_vars=[DiscreteVariable('d3', values='ghi')],\n            metas=[ContinuousVariable('c2'),\n                   DiscreteVariable('d4', values='jkl')]\n        )\n        self.args = (self.domain,\n                     {'c1': Continuous, 'd1': Discrete,\n                      'd2': Discrete, 'd3': Discrete},\n                     {'c2': Continuous, 'd4': Discrete, })\n        self.handler = DomainContextHandler()\n        self.handler.read_defaults = lambda: None\n\n    def test_encode_domain_with_match_none(self):\n        handler = DomainContextHandler(\n            match_values=DomainContextHandler.MATCH_VALUES_NONE)\n\n        encoded_attributes, encoded_metas = handler.encode_domain(self.domain)\n\n        self.assertEqual(encoded_attributes,\n                         {'c1': Continuous, 'd1': Discrete,\n                          'd2': Discrete, 'd3': Discrete})\n        self.assertEqual(encoded_metas, {'c2': Continuous, 'd4': Discrete, })\n\n    def test_encode_domain_with_match_class(self):\n        handler = DomainContextHandler(\n            match_values=DomainContextHandler.MATCH_VALUES_CLASS)\n\n        encoded_attributes, encoded_metas = handler.encode_domain(self.domain)\n\n        self.assertEqual(encoded_attributes,\n                         {'c1': Continuous, 'd1': Discrete, 'd2': Discrete,\n                          'd3': list('ghi')})\n        self.assertEqual(encoded_metas, {'c2': Continuous, 'd4': Discrete})\n\n    def test_encode_domain_with_match_all(self):\n        handler = DomainContextHandler(\n            match_values=DomainContextHandler.MATCH_VALUES_ALL)\n\n        encoded_attributes, encoded_metas = handler.encode_domain(self.domain)\n\n        self.assertEqual(encoded_attributes,\n                         {'c1': Continuous, 'd1': list('abc'),\n                          'd2': list('def'), 'd3': list('ghi')})\n        self.assertEqual(encoded_metas,\n                         {'c2': Continuous, 'd4': list('jkl')})\n\n    def test_match_returns_2_on_perfect_match(self):\n        context = Mock(\n            attributes=self.args[1], metas=self.args[2], values={})\n        self.assertEqual(2., self.handler.match(context, *self.args))\n\n    def test_match_returns_1_if_everything_matches(self):\n        self.handler.bind(SimpleWidget)\n\n        # Attributes in values\n        context = Mock(values=dict(\n            with_metas=('d1', Discrete),\n            required=('d1', Discrete)))\n        self.assertEqual(1., self.handler.match(context, *self.args))\n\n        # Metas in values\n        context = Mock(values=dict(\n            with_metas=('d4', Discrete),\n            required=('d1', Discrete)))\n        self.assertEqual(1., self.handler.match(context, *self.args))\n\n        # Attributes in lists\n        context = Mock(values=dict(\n            with_metas=[(\"d1\", Discrete)]\n        ))\n        self.assertEqual(1., self.handler.match(context, *self.args))\n\n        # Metas in lists\n        context = Mock(values=dict(\n            with_metas=[(\"d4\", Discrete)]\n        ))\n        self.assertEqual(1., self.handler.match(context, *self.args))\n\n    def test_match_returns_point_1_when_nothing_to_match(self):\n        self.handler.bind(SimpleWidget)\n\n        context = Mock(values={})\n        self.assertEqual(0.1, self.handler.match(context, *self.args))\n\n    def test_match_returns_zero_on_incompatible_context(self):\n        self.handler.bind(SimpleWidget)\n\n        # required\n        context = Mock(values=dict(required=('u', Discrete),\n                                   with_metas=('d1', Discrete)))\n        self.assertEqual(0, self.handler.match(context, *self.args))\n\n    def test_clone_context(self):\n        self.handler.bind(SimpleWidget)\n        context = self.create_context(self.domain, dict(\n            text=('u', -2),\n            with_metas=[('d1', Discrete), ('d1', Continuous),\n                        ('c1', Continuous), ('c1', Discrete)],\n            required=('u', Continuous)\n        ))\n\n        new_values = self.handler.clone_context(context, *self.args).values\n\n        self.assertEqual(new_values['text'], ('u', -2))\n        self.assertEqual([('d1', Discrete), ('c1', Continuous)],\n                         new_values['with_metas'])\n        self.assertNotIn('required', new_values)\n\n    def test_open_context(self):\n        self.handler.bind(SimpleWidget)\n        context = self.create_context(self.domain, dict(\n            text=('u', -2),\n            with_metas=[('d1', Discrete), ('d2', Discrete)]\n        ))\n        self.handler.global_contexts = \\\n            [Mock(values={}), context, Mock(values={})]\n\n        widget = SimpleWidget()\n        self.handler.initialize(widget)\n        old_metas_list = widget.with_metas\n        self.handler.open_context(widget, self.args[0])\n\n        context = widget.current_context\n        self.assertEqual(context.attributes, self.args[1])\n        self.assertEqual(context.metas, self.args[2])\n        self.assertIs(old_metas_list, widget.with_metas)\n\n        self.assertEqual(widget.text, 'u')\n        self.assertEqual(widget.with_metas, [('d1', Discrete),\n                                             ('d2', Discrete)])\n\n    def test_open_context_with_imperfect_match(self):\n        self.handler.bind(SimpleWidget)\n        context = self.create_context(None, dict(\n            text=('u', -2),\n            with_metas=[('d1', Discrete), ('d1', Continuous),\n                        ('c1', Continuous), ('c1', Discrete)]\n        ))\n        self.handler.global_contexts = \\\n            [Mock(values={}), context, Mock(values={})]\n\n        widget = SimpleWidget()\n        self.handler.initialize(widget)\n        self.handler.open_context(widget, self.args[0])\n\n        context = widget.current_context\n        self.assertEqual(context.attributes, self.args[1])\n        self.assertEqual(context.metas, self.args[2])\n\n        self.assertEqual(widget.text, 'u')\n        self.assertEqual(widget.with_metas, [('d1', Discrete),\n                                             ('c1', Continuous)])\n\n    def test_open_context_with_no_match(self):\n        self.handler.bind(SimpleWidget)\n        widget = SimpleWidget()\n        self.handler.initialize(widget)\n        widget.text = 'u'\n\n        self.handler.open_context(widget, self.args[0])\n\n        self.assertEqual(widget.text, 'u')\n        self.assertEqual(widget.with_metas, [])\n        context = widget.current_context\n        self.assertEqual(context.attributes, self.args[1])\n        self.assertEqual(context.metas, self.args[2])\n        self.assertEqual(context.values['text'], ('u', -2))\n\n    def test_filter_value(self):\n        setting = ContextSetting([])\n        setting.name = \"value\"\n\n        def test_filter(before_value, after_value):\n            data = dict(value=before_value)\n            self.handler.filter_value(setting, data, *self.args)\n            self.assertEqual(data.get(\"value\", None), after_value)\n\n        # filter list values\n        test_filter([], [])\n        # When list contains attributes asa tuple of (name, type),\n        # Attributes not present in domain should be filtered out\n        test_filter([(\"d1\", Discrete), (\"d1\", Continuous),\n                     (\"c1\", Continuous), (\"c1\", Discrete)],\n                    [(\"d1\", Discrete), (\"c1\", Continuous)])\n        # All other values in list should remain\n        test_filter([0, [1, 2, 3], \"abcd\", 5.4], [0, [1, 2, 3], \"abcd\", 5.4])\n\n    def test_encode_setting(self):\n        setting = ContextSetting(None)\n\n        var = self.domain[0]\n        val = self.handler.encode_setting(None, setting, var)\n        self.assertEqual(val, (var.name, 100 + vartype(var)))\n\n        # Should not crash on anonymous variables\n        var.name = \"\"\n        val = self.handler.encode_setting(None, setting, var)\n        self.assertEqual(val, (var.name, 100 + vartype(var)))\n\n    def test_encode_list_settings(self):\n        setting = ContextSetting(None)\n\n        var1, var2 = self.domain[:2]\n        val = self.handler.encode_setting(None, setting, [None, var1, var2])\n        self.assertEqual(\n            val,\n            ([None,\n              (var1.name, 100 + vartype(var1)),\n              (var2.name, 100 + vartype(var2))], -3))\n\n        a_list = [1, 2, 3]\n        val = self.handler.encode_setting(None, setting, a_list)\n        self.assertEqual(val, [1, 2, 3])\n        self.assertIsNot(val, a_list)\n\n        a_list = []\n        val = self.handler.encode_setting(None, setting, a_list)\n        self.assertEqual(val, [])\n        self.assertIsNot(val, a_list)\n\n        a_list = [None, None]\n        val = self.handler.encode_setting(None, setting, a_list)\n        self.assertEqual(val, [None, None])\n        self.assertIsNot(val, a_list)\n\n    def test_decode_setting(self):\n        setting = ContextSetting(None)\n\n        var = self.domain[0]\n        val = self.handler.decode_setting(setting, (var.name, 100 + vartype(var)),\n                                          self.domain)\n        self.assertIs(val, var)\n\n        all_metas_domain = Domain([], metas=[var])\n        val = self.handler.decode_setting(setting, (var.name, 100 + vartype(var)),\n                                          all_metas_domain)\n        self.assertIs(val, var)\n\n    def test_decode_list_setting(self):\n        setting = ContextSetting(None)\n\n        var1, var2 = self.domain[:2]\n        val = self.handler.decode_setting(\n            setting,\n            ([None,\n              (var1.name, 100 + vartype(var1)),\n              (var2.name, 100 + vartype(var2))], -3),\n            self.domain)\n        self.assertEqual(val, [None, var1, var2])\n\n        val = self.handler.decode_setting(setting, [1, 2, 3], self.domain)\n        self.assertEqual(val, [1, 2, 3])\n\n    def test_backward_compatible_params(self):\n        with warnings.catch_warnings(record=True) as w:\n            warnings.simplefilter(\"always\")\n            DomainContextHandler(metas_in_res=True)\n            self.assertIn(OrangeDeprecationWarning,\n                          [x.category for x in w])\n\n    def create_context(self, domain, values):\n        if domain is None:\n            domain = Domain([])\n\n        context = self.handler.new_context(domain,\n                                           *self.handler.encode_domain(domain))\n        context.values = values\n        return context",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 42,
                            "end_lineno": 51,
                            "parent": {
                                "file_name": "Orange/widgets/tests/test_domain_context_handler.py",
                                "type": "class",
                                "name": "TestDomainContextHandler",
                                "content": "class TestDomainContextHandler(TestCase):\n    def setUp(self):\n        self.domain = Domain(\n            attributes=[ContinuousVariable('c1'),\n                        DiscreteVariable('d1', values='abc'),\n                        DiscreteVariable('d2', values='def')],\n            class_vars=[DiscreteVariable('d3', values='ghi')],\n            metas=[ContinuousVariable('c2'),\n                   DiscreteVariable('d4', values='jkl')]\n        )\n        self.args = (self.domain,\n                     {'c1': Continuous, 'd1': Discrete,\n                      'd2': Discrete, 'd3': Discrete},\n                     {'c2': Continuous, 'd4': Discrete, })\n        self.handler = DomainContextHandler()\n        self.handler.read_defaults = lambda: None\n\n    def test_encode_domain_with_match_none(self):\n        handler = DomainContextHandler(\n            match_values=DomainContextHandler.MATCH_VALUES_NONE)\n\n        encoded_attributes, encoded_metas = handler.encode_domain(self.domain)\n\n        self.assertEqual(encoded_attributes,\n                         {'c1': Continuous, 'd1': Discrete,\n                          'd2': Discrete, 'd3': Discrete})\n        self.assertEqual(encoded_metas, {'c2': Continuous, 'd4': Discrete, })\n\n    def test_encode_domain_with_match_class(self):\n        handler = DomainContextHandler(\n            match_values=DomainContextHandler.MATCH_VALUES_CLASS)\n\n        encoded_attributes, encoded_metas = handler.encode_domain(self.domain)\n\n        self.assertEqual(encoded_attributes,\n                         {'c1': Continuous, 'd1': Discrete, 'd2': Discrete,\n                          'd3': list('ghi')})\n        self.assertEqual(encoded_metas, {'c2': Continuous, 'd4': Discrete})\n\n    def test_encode_domain_with_match_all(self):\n        handler = DomainContextHandler(\n            match_values=DomainContextHandler.MATCH_VALUES_ALL)\n\n        encoded_attributes, encoded_metas = handler.encode_domain(self.domain)\n\n        self.assertEqual(encoded_attributes,\n                         {'c1': Continuous, 'd1': list('abc'),\n                          'd2': list('def'), 'd3': list('ghi')})\n        self.assertEqual(encoded_metas,\n                         {'c2': Continuous, 'd4': list('jkl')})\n\n    def test_match_returns_2_on_perfect_match(self):\n        context = Mock(\n            attributes=self.args[1], metas=self.args[2], values={})\n        self.assertEqual(2., self.handler.match(context, *self.args))\n\n    def test_match_returns_1_if_everything_matches(self):\n        self.handler.bind(SimpleWidget)\n\n        # Attributes in values\n        context = Mock(values=dict(\n            with_metas=('d1', Discrete),\n            required=('d1', Discrete)))\n        self.assertEqual(1., self.handler.match(context, *self.args))\n\n        # Metas in values\n        context = Mock(values=dict(\n            with_metas=('d4', Discrete),\n            required=('d1', Discrete)))\n        self.assertEqual(1., self.handler.match(context, *self.args))\n\n        # Attributes in lists\n        context = Mock(values=dict(\n            with_metas=[(\"d1\", Discrete)]\n        ))\n        self.assertEqual(1., self.handler.match(context, *self.args))\n\n        # Metas in lists\n        context = Mock(values=dict(\n            with_metas=[(\"d4\", Discrete)]\n        ))\n        self.assertEqual(1., self.handler.match(context, *self.args))\n\n    def test_match_returns_point_1_when_nothing_to_match(self):\n        self.handler.bind(SimpleWidget)\n\n        context = Mock(values={})\n        self.assertEqual(0.1, self.handler.match(context, *self.args))\n\n    def test_match_returns_zero_on_incompatible_context(self):\n        self.handler.bind(SimpleWidget)\n\n        # required\n        context = Mock(values=dict(required=('u', Discrete),\n                                   with_metas=('d1', Discrete)))\n        self.assertEqual(0, self.handler.match(context, *self.args))\n\n    def test_clone_context(self):\n        self.handler.bind(SimpleWidget)\n        context = self.create_context(self.domain, dict(\n            text=('u', -2),\n            with_metas=[('d1', Discrete), ('d1', Continuous),\n                        ('c1', Continuous), ('c1', Discrete)],\n            required=('u', Continuous)\n        ))\n\n        new_values = self.handler.clone_context(context, *self.args).values\n\n        self.assertEqual(new_values['text'], ('u', -2))\n        self.assertEqual([('d1', Discrete), ('c1', Continuous)],\n                         new_values['with_metas'])\n        self.assertNotIn('required', new_values)\n\n    def test_open_context(self):\n        self.handler.bind(SimpleWidget)\n        context = self.create_context(self.domain, dict(\n            text=('u', -2),\n            with_metas=[('d1', Discrete), ('d2', Discrete)]\n        ))\n        self.handler.global_contexts = \\\n            [Mock(values={}), context, Mock(values={})]\n\n        widget = SimpleWidget()\n        self.handler.initialize(widget)\n        old_metas_list = widget.with_metas\n        self.handler.open_context(widget, self.args[0])\n\n        context = widget.current_context\n        self.assertEqual(context.attributes, self.args[1])\n        self.assertEqual(context.metas, self.args[2])\n        self.assertIs(old_metas_list, widget.with_metas)\n\n        self.assertEqual(widget.text, 'u')\n        self.assertEqual(widget.with_metas, [('d1', Discrete),\n                                             ('d2', Discrete)])\n\n    def test_open_context_with_imperfect_match(self):\n        self.handler.bind(SimpleWidget)\n        context = self.create_context(None, dict(\n            text=('u', -2),\n            with_metas=[('d1', Discrete), ('d1', Continuous),\n                        ('c1', Continuous), ('c1', Discrete)]\n        ))\n        self.handler.global_contexts = \\\n            [Mock(values={}), context, Mock(values={})]\n\n        widget = SimpleWidget()\n        self.handler.initialize(widget)\n        self.handler.open_context(widget, self.args[0])\n\n        context = widget.current_context\n        self.assertEqual(context.attributes, self.args[1])\n        self.assertEqual(context.metas, self.args[2])\n\n        self.assertEqual(widget.text, 'u')\n        self.assertEqual(widget.with_metas, [('d1', Discrete),\n                                             ('c1', Continuous)])\n\n    def test_open_context_with_no_match(self):\n        self.handler.bind(SimpleWidget)\n        widget = SimpleWidget()\n        self.handler.initialize(widget)\n        widget.text = 'u'\n\n        self.handler.open_context(widget, self.args[0])\n\n        self.assertEqual(widget.text, 'u')\n        self.assertEqual(widget.with_metas, [])\n        context = widget.current_context\n        self.assertEqual(context.attributes, self.args[1])\n        self.assertEqual(context.metas, self.args[2])\n        self.assertEqual(context.values['text'], ('u', -2))\n\n    def test_filter_value(self):\n        setting = ContextSetting([])\n        setting.name = \"value\"\n\n        def test_filter(before_value, after_value):\n            data = dict(value=before_value)\n            self.handler.filter_value(setting, data, *self.args)\n            self.assertEqual(data.get(\"value\", None), after_value)\n\n        # filter list values\n        test_filter([], [])\n        # When list contains attributes asa tuple of (name, type),\n        # Attributes not present in domain should be filtered out\n        test_filter([(\"d1\", Discrete), (\"d1\", Continuous),\n                     (\"c1\", Continuous), (\"c1\", Discrete)],\n                    [(\"d1\", Discrete), (\"c1\", Continuous)])\n        # All other values in list should remain\n        test_filter([0, [1, 2, 3], \"abcd\", 5.4], [0, [1, 2, 3], \"abcd\", 5.4])\n\n    def test_encode_setting(self):\n        setting = ContextSetting(None)\n\n        var = self.domain[0]\n        val = self.handler.encode_setting(None, setting, var)\n        self.assertEqual(val, (var.name, 100 + vartype(var)))\n\n        # Should not crash on anonymous variables\n        var.name = \"\"\n        val = self.handler.encode_setting(None, setting, var)\n        self.assertEqual(val, (var.name, 100 + vartype(var)))\n\n    def test_encode_list_settings(self):\n        setting = ContextSetting(None)\n\n        var1, var2 = self.domain[:2]\n        val = self.handler.encode_setting(None, setting, [None, var1, var2])\n        self.assertEqual(\n            val,\n            ([None,\n              (var1.name, 100 + vartype(var1)),\n              (var2.name, 100 + vartype(var2))], -3))\n\n        a_list = [1, 2, 3]\n        val = self.handler.encode_setting(None, setting, a_list)\n        self.assertEqual(val, [1, 2, 3])\n        self.assertIsNot(val, a_list)\n\n        a_list = []\n        val = self.handler.encode_setting(None, setting, a_list)\n        self.assertEqual(val, [])\n        self.assertIsNot(val, a_list)\n\n        a_list = [None, None]\n        val = self.handler.encode_setting(None, setting, a_list)\n        self.assertEqual(val, [None, None])\n        self.assertIsNot(val, a_list)\n\n    def test_decode_setting(self):\n        setting = ContextSetting(None)\n\n        var = self.domain[0]\n        val = self.handler.decode_setting(setting, (var.name, 100 + vartype(var)),\n                                          self.domain)\n        self.assertIs(val, var)\n\n        all_metas_domain = Domain([], metas=[var])\n        val = self.handler.decode_setting(setting, (var.name, 100 + vartype(var)),\n                                          all_metas_domain)\n        self.assertIs(val, var)\n\n    def test_decode_list_setting(self):\n        setting = ContextSetting(None)\n\n        var1, var2 = self.domain[:2]\n        val = self.handler.decode_setting(\n            setting,\n            ([None,\n              (var1.name, 100 + vartype(var1)),\n              (var2.name, 100 + vartype(var2))], -3),\n            self.domain)\n        self.assertEqual(val, [None, var1, var2])\n\n        val = self.handler.decode_setting(setting, [1, 2, 3], self.domain)\n        self.assertEqual(val, [1, 2, 3])\n\n    def test_backward_compatible_params(self):\n        with warnings.catch_warnings(record=True) as w:\n            warnings.simplefilter(\"always\")\n            DomainContextHandler(metas_in_res=True)\n            self.assertIn(OrangeDeprecationWarning,\n                          [x.category for x in w])\n\n    def create_context(self, domain, values):\n        if domain is None:\n            domain = Domain([])\n\n        context = self.handler.new_context(domain,\n                                           *self.handler.encode_domain(domain))\n        context.values = values\n        return context",
                                "ast_type_str": "ClassDef",
                                "start_lineno": 14,
                                "end_lineno": 286,
                                "parent": null
                            }
                        }
                    ],
                    "added_entities": [],
                    "deleted_entities": []
                },
                {
                    "descriptor": {
                        "old_range": {
                            "start": 57,
                            "length": 10
                        },
                        "new_range": {
                            "start": 63,
                            "length": 10
                        },
                        "section": "class TestDomainContextHandler(TestCase):"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "        encoded_attributes, encoded_metas = handler.encode_domain(self.domain)",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "        self.assertEqual(encoded_attributes,",
                                "type": "context"
                            },
                            {
                                "content": "                         {'c1': Continuous, 'd1': list('abc'),",
                                "type": "deleted"
                            },
                            {
                                "content": "                         {'c1': Continuous - 100, 'd1': list('abc'),",
                                "type": "added"
                            },
                            {
                                "content": "                          'd2': list('def'), 'd3': list('ghi')})",
                                "type": "context"
                            },
                            {
                                "content": "        self.assertEqual(encoded_metas,",
                                "type": "context"
                            },
                            {
                                "content": "                         {'c2': Continuous, 'd4': list('jkl')})",
                                "type": "deleted"
                            },
                            {
                                "content": "                         {'c2': Continuous - 100, 'd4': list('jkl')})",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "    def test_match_returns_2_on_perfect_match(self):",
                                "type": "context"
                            },
                            {
                                "content": "        context = Mock(",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [
                        {
                            "file_name": "Orange/widgets/tests/test_domain_context_handler.py",
                            "type": "class",
                            "name": "TestDomainContextHandler",
                            "content": "class TestDomainContextHandler(TestCase):\n    def setUp(self):\n        self.domain = Domain(\n            attributes=[ContinuousVariable('c1'),\n                        DiscreteVariable('d1', values='abc'),\n                        DiscreteVariable('d2', values='def')],\n            class_vars=[DiscreteVariable('d3', values='ghi')],\n            metas=[ContinuousVariable('c2'),\n                   DiscreteVariable('d4', values='jkl')]\n        )\n        self.args = (self.domain,\n                     {'c1': Continuous, 'd1': Discrete,\n                      'd2': Discrete, 'd3': Discrete},\n                     {'c2': Continuous, 'd4': Discrete, })\n        self.handler = DomainContextHandler()\n        self.handler.read_defaults = lambda: None\n\n    def test_encode_domain_with_match_none(self):\n        handler = DomainContextHandler(\n            match_values=DomainContextHandler.MATCH_VALUES_NONE)\n\n        encoded_attributes, encoded_metas = handler.encode_domain(self.domain)\n\n        self.assertEqual(encoded_attributes,\n                         {'c1': Continuous, 'd1': Discrete,\n                          'd2': Discrete, 'd3': Discrete})\n        self.assertEqual(encoded_metas, {'c2': Continuous, 'd4': Discrete, })\n\n    def test_encode_domain_with_match_class(self):\n        handler = DomainContextHandler(\n            match_values=DomainContextHandler.MATCH_VALUES_CLASS)\n\n        encoded_attributes, encoded_metas = handler.encode_domain(self.domain)\n\n        self.assertEqual(encoded_attributes,\n                         {'c1': Continuous, 'd1': Discrete, 'd2': Discrete,\n                          'd3': list('ghi')})\n        self.assertEqual(encoded_metas, {'c2': Continuous, 'd4': Discrete})\n\n    def test_encode_domain_with_match_all(self):\n        handler = DomainContextHandler(\n            match_values=DomainContextHandler.MATCH_VALUES_ALL)\n\n        encoded_attributes, encoded_metas = handler.encode_domain(self.domain)\n\n        self.assertEqual(encoded_attributes,\n                         {'c1': Continuous, 'd1': list('abc'),\n                          'd2': list('def'), 'd3': list('ghi')})\n        self.assertEqual(encoded_metas,\n                         {'c2': Continuous, 'd4': list('jkl')})\n\n    def test_match_returns_2_on_perfect_match(self):\n        context = Mock(\n            attributes=self.args[1], metas=self.args[2], values={})\n        self.assertEqual(2., self.handler.match(context, *self.args))\n\n    def test_match_returns_1_if_everything_matches(self):\n        self.handler.bind(SimpleWidget)\n\n        # Attributes in values\n        context = Mock(values=dict(\n            with_metas=('d1', Discrete),\n            required=('d1', Discrete)))\n        self.assertEqual(1., self.handler.match(context, *self.args))\n\n        # Metas in values\n        context = Mock(values=dict(\n            with_metas=('d4', Discrete),\n            required=('d1', Discrete)))\n        self.assertEqual(1., self.handler.match(context, *self.args))\n\n        # Attributes in lists\n        context = Mock(values=dict(\n            with_metas=[(\"d1\", Discrete)]\n        ))\n        self.assertEqual(1., self.handler.match(context, *self.args))\n\n        # Metas in lists\n        context = Mock(values=dict(\n            with_metas=[(\"d4\", Discrete)]\n        ))\n        self.assertEqual(1., self.handler.match(context, *self.args))\n\n    def test_match_returns_point_1_when_nothing_to_match(self):\n        self.handler.bind(SimpleWidget)\n\n        context = Mock(values={})\n        self.assertEqual(0.1, self.handler.match(context, *self.args))\n\n    def test_match_returns_zero_on_incompatible_context(self):\n        self.handler.bind(SimpleWidget)\n\n        # required\n        context = Mock(values=dict(required=('u', Discrete),\n                                   with_metas=('d1', Discrete)))\n        self.assertEqual(0, self.handler.match(context, *self.args))\n\n    def test_clone_context(self):\n        self.handler.bind(SimpleWidget)\n        context = self.create_context(self.domain, dict(\n            text=('u', -2),\n            with_metas=[('d1', Discrete), ('d1', Continuous),\n                        ('c1', Continuous), ('c1', Discrete)],\n            required=('u', Continuous)\n        ))\n\n        new_values = self.handler.clone_context(context, *self.args).values\n\n        self.assertEqual(new_values['text'], ('u', -2))\n        self.assertEqual([('d1', Discrete), ('c1', Continuous)],\n                         new_values['with_metas'])\n        self.assertNotIn('required', new_values)\n\n    def test_open_context(self):\n        self.handler.bind(SimpleWidget)\n        context = self.create_context(self.domain, dict(\n            text=('u', -2),\n            with_metas=[('d1', Discrete), ('d2', Discrete)]\n        ))\n        self.handler.global_contexts = \\\n            [Mock(values={}), context, Mock(values={})]\n\n        widget = SimpleWidget()\n        self.handler.initialize(widget)\n        old_metas_list = widget.with_metas\n        self.handler.open_context(widget, self.args[0])\n\n        context = widget.current_context\n        self.assertEqual(context.attributes, self.args[1])\n        self.assertEqual(context.metas, self.args[2])\n        self.assertIs(old_metas_list, widget.with_metas)\n\n        self.assertEqual(widget.text, 'u')\n        self.assertEqual(widget.with_metas, [('d1', Discrete),\n                                             ('d2', Discrete)])\n\n    def test_open_context_with_imperfect_match(self):\n        self.handler.bind(SimpleWidget)\n        context = self.create_context(None, dict(\n            text=('u', -2),\n            with_metas=[('d1', Discrete), ('d1', Continuous),\n                        ('c1', Continuous), ('c1', Discrete)]\n        ))\n        self.handler.global_contexts = \\\n            [Mock(values={}), context, Mock(values={})]\n\n        widget = SimpleWidget()\n        self.handler.initialize(widget)\n        self.handler.open_context(widget, self.args[0])\n\n        context = widget.current_context\n        self.assertEqual(context.attributes, self.args[1])\n        self.assertEqual(context.metas, self.args[2])\n\n        self.assertEqual(widget.text, 'u')\n        self.assertEqual(widget.with_metas, [('d1', Discrete),\n                                             ('c1', Continuous)])\n\n    def test_open_context_with_no_match(self):\n        self.handler.bind(SimpleWidget)\n        widget = SimpleWidget()\n        self.handler.initialize(widget)\n        widget.text = 'u'\n\n        self.handler.open_context(widget, self.args[0])\n\n        self.assertEqual(widget.text, 'u')\n        self.assertEqual(widget.with_metas, [])\n        context = widget.current_context\n        self.assertEqual(context.attributes, self.args[1])\n        self.assertEqual(context.metas, self.args[2])\n        self.assertEqual(context.values['text'], ('u', -2))\n\n    def test_filter_value(self):\n        setting = ContextSetting([])\n        setting.name = \"value\"\n\n        def test_filter(before_value, after_value):\n            data = dict(value=before_value)\n            self.handler.filter_value(setting, data, *self.args)\n            self.assertEqual(data.get(\"value\", None), after_value)\n\n        # filter list values\n        test_filter([], [])\n        # When list contains attributes asa tuple of (name, type),\n        # Attributes not present in domain should be filtered out\n        test_filter([(\"d1\", Discrete), (\"d1\", Continuous),\n                     (\"c1\", Continuous), (\"c1\", Discrete)],\n                    [(\"d1\", Discrete), (\"c1\", Continuous)])\n        # All other values in list should remain\n        test_filter([0, [1, 2, 3], \"abcd\", 5.4], [0, [1, 2, 3], \"abcd\", 5.4])\n\n    def test_encode_setting(self):\n        setting = ContextSetting(None)\n\n        var = self.domain[0]\n        val = self.handler.encode_setting(None, setting, var)\n        self.assertEqual(val, (var.name, 100 + vartype(var)))\n\n        # Should not crash on anonymous variables\n        var.name = \"\"\n        val = self.handler.encode_setting(None, setting, var)\n        self.assertEqual(val, (var.name, 100 + vartype(var)))\n\n    def test_encode_list_settings(self):\n        setting = ContextSetting(None)\n\n        var1, var2 = self.domain[:2]\n        val = self.handler.encode_setting(None, setting, [None, var1, var2])\n        self.assertEqual(\n            val,\n            ([None,\n              (var1.name, 100 + vartype(var1)),\n              (var2.name, 100 + vartype(var2))], -3))\n\n        a_list = [1, 2, 3]\n        val = self.handler.encode_setting(None, setting, a_list)\n        self.assertEqual(val, [1, 2, 3])\n        self.assertIsNot(val, a_list)\n\n        a_list = []\n        val = self.handler.encode_setting(None, setting, a_list)\n        self.assertEqual(val, [])\n        self.assertIsNot(val, a_list)\n\n        a_list = [None, None]\n        val = self.handler.encode_setting(None, setting, a_list)\n        self.assertEqual(val, [None, None])\n        self.assertIsNot(val, a_list)\n\n    def test_decode_setting(self):\n        setting = ContextSetting(None)\n\n        var = self.domain[0]\n        val = self.handler.decode_setting(setting, (var.name, 100 + vartype(var)),\n                                          self.domain)\n        self.assertIs(val, var)\n\n        all_metas_domain = Domain([], metas=[var])\n        val = self.handler.decode_setting(setting, (var.name, 100 + vartype(var)),\n                                          all_metas_domain)\n        self.assertIs(val, var)\n\n    def test_decode_list_setting(self):\n        setting = ContextSetting(None)\n\n        var1, var2 = self.domain[:2]\n        val = self.handler.decode_setting(\n            setting,\n            ([None,\n              (var1.name, 100 + vartype(var1)),\n              (var2.name, 100 + vartype(var2))], -3),\n            self.domain)\n        self.assertEqual(val, [None, var1, var2])\n\n        val = self.handler.decode_setting(setting, [1, 2, 3], self.domain)\n        self.assertEqual(val, [1, 2, 3])\n\n    def test_backward_compatible_params(self):\n        with warnings.catch_warnings(record=True) as w:\n            warnings.simplefilter(\"always\")\n            DomainContextHandler(metas_in_res=True)\n            self.assertIn(OrangeDeprecationWarning,\n                          [x.category for x in w])\n\n    def create_context(self, domain, values):\n        if domain is None:\n            domain = Domain([])\n\n        context = self.handler.new_context(domain,\n                                           *self.handler.encode_domain(domain))\n        context.values = values\n        return context",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 14,
                            "end_lineno": 286,
                            "parent": null
                        },
                        {
                            "file_name": "Orange/widgets/tests/test_domain_context_handler.py",
                            "type": "method",
                            "name": "TestDomainContextHandler.test_encode_domain_with_match_all",
                            "content": "class TestDomainContextHandler(TestCase):\n    def setUp(self):\n        self.domain = Domain(\n            attributes=[ContinuousVariable('c1'),\n                        DiscreteVariable('d1', values='abc'),\n                        DiscreteVariable('d2', values='def')],\n            class_vars=[DiscreteVariable('d3', values='ghi')],\n            metas=[ContinuousVariable('c2'),\n                   DiscreteVariable('d4', values='jkl')]\n        )\n        self.args = (self.domain,\n                     {'c1': Continuous, 'd1': Discrete,\n                      'd2': Discrete, 'd3': Discrete},\n                     {'c2': Continuous, 'd4': Discrete, })\n        self.handler = DomainContextHandler()\n        self.handler.read_defaults = lambda: None\n\n    def test_encode_domain_with_match_none(self):\n        handler = DomainContextHandler(\n            match_values=DomainContextHandler.MATCH_VALUES_NONE)\n\n        encoded_attributes, encoded_metas = handler.encode_domain(self.domain)\n\n        self.assertEqual(encoded_attributes,\n                         {'c1': Continuous, 'd1': Discrete,\n                          'd2': Discrete, 'd3': Discrete})\n        self.assertEqual(encoded_metas, {'c2': Continuous, 'd4': Discrete, })\n\n    def test_encode_domain_with_match_class(self):\n        handler = DomainContextHandler(\n            match_values=DomainContextHandler.MATCH_VALUES_CLASS)\n\n        encoded_attributes, encoded_metas = handler.encode_domain(self.domain)\n\n        self.assertEqual(encoded_attributes,\n                         {'c1': Continuous, 'd1': Discrete, 'd2': Discrete,\n                          'd3': list('ghi')})\n        self.assertEqual(encoded_metas, {'c2': Continuous, 'd4': Discrete})\n\n    def test_encode_domain_with_match_all(self):\n        handler = DomainContextHandler(\n            match_values=DomainContextHandler.MATCH_VALUES_ALL)\n\n        encoded_attributes, encoded_metas = handler.encode_domain(self.domain)\n\n        self.assertEqual(encoded_attributes,\n                         {'c1': Continuous, 'd1': list('abc'),\n                          'd2': list('def'), 'd3': list('ghi')})\n        self.assertEqual(encoded_metas,\n                         {'c2': Continuous, 'd4': list('jkl')})\n\n    def test_match_returns_2_on_perfect_match(self):\n        context = Mock(\n            attributes=self.args[1], metas=self.args[2], values={})\n        self.assertEqual(2., self.handler.match(context, *self.args))\n\n    def test_match_returns_1_if_everything_matches(self):\n        self.handler.bind(SimpleWidget)\n\n        # Attributes in values\n        context = Mock(values=dict(\n            with_metas=('d1', Discrete),\n            required=('d1', Discrete)))\n        self.assertEqual(1., self.handler.match(context, *self.args))\n\n        # Metas in values\n        context = Mock(values=dict(\n            with_metas=('d4', Discrete),\n            required=('d1', Discrete)))\n        self.assertEqual(1., self.handler.match(context, *self.args))\n\n        # Attributes in lists\n        context = Mock(values=dict(\n            with_metas=[(\"d1\", Discrete)]\n        ))\n        self.assertEqual(1., self.handler.match(context, *self.args))\n\n        # Metas in lists\n        context = Mock(values=dict(\n            with_metas=[(\"d4\", Discrete)]\n        ))\n        self.assertEqual(1., self.handler.match(context, *self.args))\n\n    def test_match_returns_point_1_when_nothing_to_match(self):\n        self.handler.bind(SimpleWidget)\n\n        context = Mock(values={})\n        self.assertEqual(0.1, self.handler.match(context, *self.args))\n\n    def test_match_returns_zero_on_incompatible_context(self):\n        self.handler.bind(SimpleWidget)\n\n        # required\n        context = Mock(values=dict(required=('u', Discrete),\n                                   with_metas=('d1', Discrete)))\n        self.assertEqual(0, self.handler.match(context, *self.args))\n\n    def test_clone_context(self):\n        self.handler.bind(SimpleWidget)\n        context = self.create_context(self.domain, dict(\n            text=('u', -2),\n            with_metas=[('d1', Discrete), ('d1', Continuous),\n                        ('c1', Continuous), ('c1', Discrete)],\n            required=('u', Continuous)\n        ))\n\n        new_values = self.handler.clone_context(context, *self.args).values\n\n        self.assertEqual(new_values['text'], ('u', -2))\n        self.assertEqual([('d1', Discrete), ('c1', Continuous)],\n                         new_values['with_metas'])\n        self.assertNotIn('required', new_values)\n\n    def test_open_context(self):\n        self.handler.bind(SimpleWidget)\n        context = self.create_context(self.domain, dict(\n            text=('u', -2),\n            with_metas=[('d1', Discrete), ('d2', Discrete)]\n        ))\n        self.handler.global_contexts = \\\n            [Mock(values={}), context, Mock(values={})]\n\n        widget = SimpleWidget()\n        self.handler.initialize(widget)\n        old_metas_list = widget.with_metas\n        self.handler.open_context(widget, self.args[0])\n\n        context = widget.current_context\n        self.assertEqual(context.attributes, self.args[1])\n        self.assertEqual(context.metas, self.args[2])\n        self.assertIs(old_metas_list, widget.with_metas)\n\n        self.assertEqual(widget.text, 'u')\n        self.assertEqual(widget.with_metas, [('d1', Discrete),\n                                             ('d2', Discrete)])\n\n    def test_open_context_with_imperfect_match(self):\n        self.handler.bind(SimpleWidget)\n        context = self.create_context(None, dict(\n            text=('u', -2),\n            with_metas=[('d1', Discrete), ('d1', Continuous),\n                        ('c1', Continuous), ('c1', Discrete)]\n        ))\n        self.handler.global_contexts = \\\n            [Mock(values={}), context, Mock(values={})]\n\n        widget = SimpleWidget()\n        self.handler.initialize(widget)\n        self.handler.open_context(widget, self.args[0])\n\n        context = widget.current_context\n        self.assertEqual(context.attributes, self.args[1])\n        self.assertEqual(context.metas, self.args[2])\n\n        self.assertEqual(widget.text, 'u')\n        self.assertEqual(widget.with_metas, [('d1', Discrete),\n                                             ('c1', Continuous)])\n\n    def test_open_context_with_no_match(self):\n        self.handler.bind(SimpleWidget)\n        widget = SimpleWidget()\n        self.handler.initialize(widget)\n        widget.text = 'u'\n\n        self.handler.open_context(widget, self.args[0])\n\n        self.assertEqual(widget.text, 'u')\n        self.assertEqual(widget.with_metas, [])\n        context = widget.current_context\n        self.assertEqual(context.attributes, self.args[1])\n        self.assertEqual(context.metas, self.args[2])\n        self.assertEqual(context.values['text'], ('u', -2))\n\n    def test_filter_value(self):\n        setting = ContextSetting([])\n        setting.name = \"value\"\n\n        def test_filter(before_value, after_value):\n            data = dict(value=before_value)\n            self.handler.filter_value(setting, data, *self.args)\n            self.assertEqual(data.get(\"value\", None), after_value)\n\n        # filter list values\n        test_filter([], [])\n        # When list contains attributes asa tuple of (name, type),\n        # Attributes not present in domain should be filtered out\n        test_filter([(\"d1\", Discrete), (\"d1\", Continuous),\n                     (\"c1\", Continuous), (\"c1\", Discrete)],\n                    [(\"d1\", Discrete), (\"c1\", Continuous)])\n        # All other values in list should remain\n        test_filter([0, [1, 2, 3], \"abcd\", 5.4], [0, [1, 2, 3], \"abcd\", 5.4])\n\n    def test_encode_setting(self):\n        setting = ContextSetting(None)\n\n        var = self.domain[0]\n        val = self.handler.encode_setting(None, setting, var)\n        self.assertEqual(val, (var.name, 100 + vartype(var)))\n\n        # Should not crash on anonymous variables\n        var.name = \"\"\n        val = self.handler.encode_setting(None, setting, var)\n        self.assertEqual(val, (var.name, 100 + vartype(var)))\n\n    def test_encode_list_settings(self):\n        setting = ContextSetting(None)\n\n        var1, var2 = self.domain[:2]\n        val = self.handler.encode_setting(None, setting, [None, var1, var2])\n        self.assertEqual(\n            val,\n            ([None,\n              (var1.name, 100 + vartype(var1)),\n              (var2.name, 100 + vartype(var2))], -3))\n\n        a_list = [1, 2, 3]\n        val = self.handler.encode_setting(None, setting, a_list)\n        self.assertEqual(val, [1, 2, 3])\n        self.assertIsNot(val, a_list)\n\n        a_list = []\n        val = self.handler.encode_setting(None, setting, a_list)\n        self.assertEqual(val, [])\n        self.assertIsNot(val, a_list)\n\n        a_list = [None, None]\n        val = self.handler.encode_setting(None, setting, a_list)\n        self.assertEqual(val, [None, None])\n        self.assertIsNot(val, a_list)\n\n    def test_decode_setting(self):\n        setting = ContextSetting(None)\n\n        var = self.domain[0]\n        val = self.handler.decode_setting(setting, (var.name, 100 + vartype(var)),\n                                          self.domain)\n        self.assertIs(val, var)\n\n        all_metas_domain = Domain([], metas=[var])\n        val = self.handler.decode_setting(setting, (var.name, 100 + vartype(var)),\n                                          all_metas_domain)\n        self.assertIs(val, var)\n\n    def test_decode_list_setting(self):\n        setting = ContextSetting(None)\n\n        var1, var2 = self.domain[:2]\n        val = self.handler.decode_setting(\n            setting,\n            ([None,\n              (var1.name, 100 + vartype(var1)),\n              (var2.name, 100 + vartype(var2))], -3),\n            self.domain)\n        self.assertEqual(val, [None, var1, var2])\n\n        val = self.handler.decode_setting(setting, [1, 2, 3], self.domain)\n        self.assertEqual(val, [1, 2, 3])\n\n    def test_backward_compatible_params(self):\n        with warnings.catch_warnings(record=True) as w:\n            warnings.simplefilter(\"always\")\n            DomainContextHandler(metas_in_res=True)\n            self.assertIn(OrangeDeprecationWarning,\n                          [x.category for x in w])\n\n    def create_context(self, domain, values):\n        if domain is None:\n            domain = Domain([])\n\n        context = self.handler.new_context(domain,\n                                           *self.handler.encode_domain(domain))\n        context.values = values\n        return context",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 53,
                            "end_lineno": 63,
                            "parent": {
                                "file_name": "Orange/widgets/tests/test_domain_context_handler.py",
                                "type": "class",
                                "name": "TestDomainContextHandler",
                                "content": "class TestDomainContextHandler(TestCase):\n    def setUp(self):\n        self.domain = Domain(\n            attributes=[ContinuousVariable('c1'),\n                        DiscreteVariable('d1', values='abc'),\n                        DiscreteVariable('d2', values='def')],\n            class_vars=[DiscreteVariable('d3', values='ghi')],\n            metas=[ContinuousVariable('c2'),\n                   DiscreteVariable('d4', values='jkl')]\n        )\n        self.args = (self.domain,\n                     {'c1': Continuous, 'd1': Discrete,\n                      'd2': Discrete, 'd3': Discrete},\n                     {'c2': Continuous, 'd4': Discrete, })\n        self.handler = DomainContextHandler()\n        self.handler.read_defaults = lambda: None\n\n    def test_encode_domain_with_match_none(self):\n        handler = DomainContextHandler(\n            match_values=DomainContextHandler.MATCH_VALUES_NONE)\n\n        encoded_attributes, encoded_metas = handler.encode_domain(self.domain)\n\n        self.assertEqual(encoded_attributes,\n                         {'c1': Continuous, 'd1': Discrete,\n                          'd2': Discrete, 'd3': Discrete})\n        self.assertEqual(encoded_metas, {'c2': Continuous, 'd4': Discrete, })\n\n    def test_encode_domain_with_match_class(self):\n        handler = DomainContextHandler(\n            match_values=DomainContextHandler.MATCH_VALUES_CLASS)\n\n        encoded_attributes, encoded_metas = handler.encode_domain(self.domain)\n\n        self.assertEqual(encoded_attributes,\n                         {'c1': Continuous, 'd1': Discrete, 'd2': Discrete,\n                          'd3': list('ghi')})\n        self.assertEqual(encoded_metas, {'c2': Continuous, 'd4': Discrete})\n\n    def test_encode_domain_with_match_all(self):\n        handler = DomainContextHandler(\n            match_values=DomainContextHandler.MATCH_VALUES_ALL)\n\n        encoded_attributes, encoded_metas = handler.encode_domain(self.domain)\n\n        self.assertEqual(encoded_attributes,\n                         {'c1': Continuous, 'd1': list('abc'),\n                          'd2': list('def'), 'd3': list('ghi')})\n        self.assertEqual(encoded_metas,\n                         {'c2': Continuous, 'd4': list('jkl')})\n\n    def test_match_returns_2_on_perfect_match(self):\n        context = Mock(\n            attributes=self.args[1], metas=self.args[2], values={})\n        self.assertEqual(2., self.handler.match(context, *self.args))\n\n    def test_match_returns_1_if_everything_matches(self):\n        self.handler.bind(SimpleWidget)\n\n        # Attributes in values\n        context = Mock(values=dict(\n            with_metas=('d1', Discrete),\n            required=('d1', Discrete)))\n        self.assertEqual(1., self.handler.match(context, *self.args))\n\n        # Metas in values\n        context = Mock(values=dict(\n            with_metas=('d4', Discrete),\n            required=('d1', Discrete)))\n        self.assertEqual(1., self.handler.match(context, *self.args))\n\n        # Attributes in lists\n        context = Mock(values=dict(\n            with_metas=[(\"d1\", Discrete)]\n        ))\n        self.assertEqual(1., self.handler.match(context, *self.args))\n\n        # Metas in lists\n        context = Mock(values=dict(\n            with_metas=[(\"d4\", Discrete)]\n        ))\n        self.assertEqual(1., self.handler.match(context, *self.args))\n\n    def test_match_returns_point_1_when_nothing_to_match(self):\n        self.handler.bind(SimpleWidget)\n\n        context = Mock(values={})\n        self.assertEqual(0.1, self.handler.match(context, *self.args))\n\n    def test_match_returns_zero_on_incompatible_context(self):\n        self.handler.bind(SimpleWidget)\n\n        # required\n        context = Mock(values=dict(required=('u', Discrete),\n                                   with_metas=('d1', Discrete)))\n        self.assertEqual(0, self.handler.match(context, *self.args))\n\n    def test_clone_context(self):\n        self.handler.bind(SimpleWidget)\n        context = self.create_context(self.domain, dict(\n            text=('u', -2),\n            with_metas=[('d1', Discrete), ('d1', Continuous),\n                        ('c1', Continuous), ('c1', Discrete)],\n            required=('u', Continuous)\n        ))\n\n        new_values = self.handler.clone_context(context, *self.args).values\n\n        self.assertEqual(new_values['text'], ('u', -2))\n        self.assertEqual([('d1', Discrete), ('c1', Continuous)],\n                         new_values['with_metas'])\n        self.assertNotIn('required', new_values)\n\n    def test_open_context(self):\n        self.handler.bind(SimpleWidget)\n        context = self.create_context(self.domain, dict(\n            text=('u', -2),\n            with_metas=[('d1', Discrete), ('d2', Discrete)]\n        ))\n        self.handler.global_contexts = \\\n            [Mock(values={}), context, Mock(values={})]\n\n        widget = SimpleWidget()\n        self.handler.initialize(widget)\n        old_metas_list = widget.with_metas\n        self.handler.open_context(widget, self.args[0])\n\n        context = widget.current_context\n        self.assertEqual(context.attributes, self.args[1])\n        self.assertEqual(context.metas, self.args[2])\n        self.assertIs(old_metas_list, widget.with_metas)\n\n        self.assertEqual(widget.text, 'u')\n        self.assertEqual(widget.with_metas, [('d1', Discrete),\n                                             ('d2', Discrete)])\n\n    def test_open_context_with_imperfect_match(self):\n        self.handler.bind(SimpleWidget)\n        context = self.create_context(None, dict(\n            text=('u', -2),\n            with_metas=[('d1', Discrete), ('d1', Continuous),\n                        ('c1', Continuous), ('c1', Discrete)]\n        ))\n        self.handler.global_contexts = \\\n            [Mock(values={}), context, Mock(values={})]\n\n        widget = SimpleWidget()\n        self.handler.initialize(widget)\n        self.handler.open_context(widget, self.args[0])\n\n        context = widget.current_context\n        self.assertEqual(context.attributes, self.args[1])\n        self.assertEqual(context.metas, self.args[2])\n\n        self.assertEqual(widget.text, 'u')\n        self.assertEqual(widget.with_metas, [('d1', Discrete),\n                                             ('c1', Continuous)])\n\n    def test_open_context_with_no_match(self):\n        self.handler.bind(SimpleWidget)\n        widget = SimpleWidget()\n        self.handler.initialize(widget)\n        widget.text = 'u'\n\n        self.handler.open_context(widget, self.args[0])\n\n        self.assertEqual(widget.text, 'u')\n        self.assertEqual(widget.with_metas, [])\n        context = widget.current_context\n        self.assertEqual(context.attributes, self.args[1])\n        self.assertEqual(context.metas, self.args[2])\n        self.assertEqual(context.values['text'], ('u', -2))\n\n    def test_filter_value(self):\n        setting = ContextSetting([])\n        setting.name = \"value\"\n\n        def test_filter(before_value, after_value):\n            data = dict(value=before_value)\n            self.handler.filter_value(setting, data, *self.args)\n            self.assertEqual(data.get(\"value\", None), after_value)\n\n        # filter list values\n        test_filter([], [])\n        # When list contains attributes asa tuple of (name, type),\n        # Attributes not present in domain should be filtered out\n        test_filter([(\"d1\", Discrete), (\"d1\", Continuous),\n                     (\"c1\", Continuous), (\"c1\", Discrete)],\n                    [(\"d1\", Discrete), (\"c1\", Continuous)])\n        # All other values in list should remain\n        test_filter([0, [1, 2, 3], \"abcd\", 5.4], [0, [1, 2, 3], \"abcd\", 5.4])\n\n    def test_encode_setting(self):\n        setting = ContextSetting(None)\n\n        var = self.domain[0]\n        val = self.handler.encode_setting(None, setting, var)\n        self.assertEqual(val, (var.name, 100 + vartype(var)))\n\n        # Should not crash on anonymous variables\n        var.name = \"\"\n        val = self.handler.encode_setting(None, setting, var)\n        self.assertEqual(val, (var.name, 100 + vartype(var)))\n\n    def test_encode_list_settings(self):\n        setting = ContextSetting(None)\n\n        var1, var2 = self.domain[:2]\n        val = self.handler.encode_setting(None, setting, [None, var1, var2])\n        self.assertEqual(\n            val,\n            ([None,\n              (var1.name, 100 + vartype(var1)),\n              (var2.name, 100 + vartype(var2))], -3))\n\n        a_list = [1, 2, 3]\n        val = self.handler.encode_setting(None, setting, a_list)\n        self.assertEqual(val, [1, 2, 3])\n        self.assertIsNot(val, a_list)\n\n        a_list = []\n        val = self.handler.encode_setting(None, setting, a_list)\n        self.assertEqual(val, [])\n        self.assertIsNot(val, a_list)\n\n        a_list = [None, None]\n        val = self.handler.encode_setting(None, setting, a_list)\n        self.assertEqual(val, [None, None])\n        self.assertIsNot(val, a_list)\n\n    def test_decode_setting(self):\n        setting = ContextSetting(None)\n\n        var = self.domain[0]\n        val = self.handler.decode_setting(setting, (var.name, 100 + vartype(var)),\n                                          self.domain)\n        self.assertIs(val, var)\n\n        all_metas_domain = Domain([], metas=[var])\n        val = self.handler.decode_setting(setting, (var.name, 100 + vartype(var)),\n                                          all_metas_domain)\n        self.assertIs(val, var)\n\n    def test_decode_list_setting(self):\n        setting = ContextSetting(None)\n\n        var1, var2 = self.domain[:2]\n        val = self.handler.decode_setting(\n            setting,\n            ([None,\n              (var1.name, 100 + vartype(var1)),\n              (var2.name, 100 + vartype(var2))], -3),\n            self.domain)\n        self.assertEqual(val, [None, var1, var2])\n\n        val = self.handler.decode_setting(setting, [1, 2, 3], self.domain)\n        self.assertEqual(val, [1, 2, 3])\n\n    def test_backward_compatible_params(self):\n        with warnings.catch_warnings(record=True) as w:\n            warnings.simplefilter(\"always\")\n            DomainContextHandler(metas_in_res=True)\n            self.assertIn(OrangeDeprecationWarning,\n                          [x.category for x in w])\n\n    def create_context(self, domain, values):\n        if domain is None:\n            domain = Domain([])\n\n        context = self.handler.new_context(domain,\n                                           *self.handler.encode_domain(domain))\n        context.values = values\n        return context",
                                "ast_type_str": "ClassDef",
                                "start_lineno": 14,
                                "end_lineno": 286,
                                "parent": null
                            }
                        }
                    ],
                    "added_entities": [],
                    "deleted_entities": []
                },
                {
                    "descriptor": {
                        "old_range": {
                            "start": 276,
                            "length": 6
                        },
                        "new_range": {
                            "start": 282,
                            "length": 23
                        },
                        "section": "class TestDomainContextHandler(TestCase):"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "            self.assertIn(OrangeDeprecationWarning,",
                                "type": "context"
                            },
                            {
                                "content": "                          [x.category for x in w])",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "    def test_deprecated_str_as_var(self):",
                                "type": "added"
                            },
                            {
                                "content": "        if LooseVersion(Orange.__version__) >= LooseVersion(\"3.26\"):",
                                "type": "added"
                            },
                            {
                                "content": "            # pragma: no cover",
                                "type": "added"
                            },
                            {
                                "content": "            self.fail(\"Remove support for variables stored as string settings \"",
                                "type": "added"
                            },
                            {
                                "content": "                      \"and this test.\")",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "        context = Mock()",
                                "type": "added"
                            },
                            {
                                "content": "        context.attributes = {\"foo\": 2}",
                                "type": "added"
                            },
                            {
                                "content": "        context.metas = {}",
                                "type": "added"
                            },
                            {
                                "content": "        setting = ContextSetting(\"\")",
                                "type": "added"
                            },
                            {
                                "content": "        setting.name = \"setting_name\"",
                                "type": "added"
                            },
                            {
                                "content": "        with warnings.catch_warnings(record=True) as w:",
                                "type": "added"
                            },
                            {
                                "content": "            warnings.simplefilter(\"always\")",
                                "type": "added"
                            },
                            {
                                "content": "            DomainContextHandler.encode_setting(context, setting, \"foo\")",
                                "type": "added"
                            },
                            {
                                "content": "            self.assertIn(\"setting_name\", w[0].message.args[0])",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "    def create_context(self, domain, values):",
                                "type": "context"
                            },
                            {
                                "content": "        if domain is None:",
                                "type": "context"
                            },
                            {
                                "content": "            domain = Domain([])",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [
                        {
                            "file_name": "Orange/widgets/tests/test_domain_context_handler.py",
                            "type": "class",
                            "name": "TestDomainContextHandler",
                            "content": "class TestDomainContextHandler(TestCase):\n    def setUp(self):\n        self.domain = Domain(\n            attributes=[ContinuousVariable('c1'),\n                        DiscreteVariable('d1', values='abc'),\n                        DiscreteVariable('d2', values='def')],\n            class_vars=[DiscreteVariable('d3', values='ghi')],\n            metas=[ContinuousVariable('c2'),\n                   DiscreteVariable('d4', values='jkl')]\n        )\n        self.args = (self.domain,\n                     {'c1': Continuous - 100, 'd1': Discrete - 100,\n                      'd2': Discrete - 100, 'd3': Discrete - 100},\n                     {'c2': Continuous - 100, 'd4': Discrete - 100, })\n        self.handler = DomainContextHandler()\n        self.handler.read_defaults = lambda: None\n\n    def test_encode_domain_with_match_none(self):\n        handler = DomainContextHandler(\n            match_values=DomainContextHandler.MATCH_VALUES_NONE)\n\n        encoded_attributes, encoded_metas = handler.encode_domain(self.domain)\n\n        self.assertEqual(encoded_attributes,\n                         {'c1': Continuous - 100, 'd1': Discrete - 100,\n                          'd2': Discrete - 100, 'd3': Discrete - 100})\n        self.assertEqual(encoded_metas,\n                         {'c2': Continuous - 100, 'd4': Discrete - 100, })\n\n    def test_encode_domain_with_match_class(self):\n        handler = DomainContextHandler(\n            match_values=DomainContextHandler.MATCH_VALUES_CLASS)\n\n        encoded_attributes, encoded_metas = handler.encode_domain(self.domain)\n\n        self.assertEqual(encoded_attributes,\n                         {'c1': Continuous - 100, 'd1': Discrete - 100,\n                          'd2': Discrete - 100,\n                          'd3': list('ghi')})\n        self.assertEqual(encoded_metas,\n                         {'c2': Continuous - 100, 'd4': Discrete - 100})\n\n    def test_encode_domain_with_match_all(self):\n        handler = DomainContextHandler(\n            match_values=DomainContextHandler.MATCH_VALUES_ALL)\n\n        encoded_attributes, encoded_metas = handler.encode_domain(self.domain)\n\n        self.assertEqual(encoded_attributes,\n                         {'c1': Continuous - 100, 'd1': list('abc'),\n                          'd2': list('def'), 'd3': list('ghi')})\n        self.assertEqual(encoded_metas,\n                         {'c2': Continuous - 100, 'd4': list('jkl')})\n\n    def test_match_returns_2_on_perfect_match(self):\n        context = Mock(\n            attributes=self.args[1], metas=self.args[2], values={})\n        self.assertEqual(2., self.handler.match(context, *self.args))\n\n    def test_match_returns_1_if_everything_matches(self):\n        self.handler.bind(SimpleWidget)\n\n        # Attributes in values\n        context = Mock(values=dict(\n            with_metas=('d1', Discrete),\n            required=('d1', Discrete)))\n        self.assertEqual(1., self.handler.match(context, *self.args))\n\n        # Metas in values\n        context = Mock(values=dict(\n            with_metas=('d4', Discrete),\n            required=('d1', Discrete)))\n        self.assertEqual(1., self.handler.match(context, *self.args))\n\n        # Attributes in lists\n        context = Mock(values=dict(\n            with_metas=[(\"d1\", Discrete)]\n        ))\n        self.assertEqual(1., self.handler.match(context, *self.args))\n\n        # Metas in lists\n        context = Mock(values=dict(\n            with_metas=[(\"d4\", Discrete)]\n        ))\n        self.assertEqual(1., self.handler.match(context, *self.args))\n\n    def test_match_returns_point_1_when_nothing_to_match(self):\n        self.handler.bind(SimpleWidget)\n\n        context = Mock(values={})\n        self.assertEqual(0.1, self.handler.match(context, *self.args))\n\n    def test_match_returns_zero_on_incompatible_context(self):\n        self.handler.bind(SimpleWidget)\n\n        # required\n        context = Mock(values=dict(required=('u', Discrete),\n                                   with_metas=('d1', Discrete)))\n        self.assertEqual(0, self.handler.match(context, *self.args))\n\n    def test_clone_context(self):\n        self.handler.bind(SimpleWidget)\n        context = self.create_context(self.domain, dict(\n            text=('u', -2),\n            with_metas=[('d1', Discrete), ('d1', Continuous),\n                        ('c1', Continuous), ('c1', Discrete)],\n            required=('u', Continuous)\n        ))\n\n        new_values = self.handler.clone_context(context, *self.args).values\n\n        self.assertEqual(new_values['text'], ('u', -2))\n        self.assertEqual([('d1', Discrete), ('c1', Continuous)],\n                         new_values['with_metas'])\n        self.assertNotIn('required', new_values)\n\n    def test_open_context(self):\n        self.handler.bind(SimpleWidget)\n        context = self.create_context(self.domain, dict(\n            text=('u', -2),\n            with_metas=[('d1', Discrete), ('d2', Discrete)]\n        ))\n        self.handler.global_contexts = \\\n            [Mock(values={}), context, Mock(values={})]\n\n        widget = SimpleWidget()\n        self.handler.initialize(widget)\n        old_metas_list = widget.with_metas\n        self.handler.open_context(widget, self.args[0])\n\n        context = widget.current_context\n        self.assertEqual(context.attributes, self.args[1])\n        self.assertEqual(context.metas, self.args[2])\n        self.assertIs(old_metas_list, widget.with_metas)\n\n        self.assertEqual(widget.text, 'u')\n        self.assertEqual(widget.with_metas, [('d1', Discrete),\n                                             ('d2', Discrete)])\n\n    def test_open_context_with_imperfect_match(self):\n        self.handler.bind(SimpleWidget)\n        context = self.create_context(None, dict(\n            text=('u', -2),\n            with_metas=[('d1', Discrete), ('d1', Continuous),\n                        ('c1', Continuous), ('c1', Discrete)]\n        ))\n        self.handler.global_contexts = \\\n            [Mock(values={}), context, Mock(values={})]\n\n        widget = SimpleWidget()\n        self.handler.initialize(widget)\n        self.handler.open_context(widget, self.args[0])\n\n        context = widget.current_context\n        self.assertEqual(context.attributes, self.args[1])\n        self.assertEqual(context.metas, self.args[2])\n\n        self.assertEqual(widget.text, 'u')\n        self.assertEqual(widget.with_metas, [('d1', Discrete),\n                                             ('c1', Continuous)])\n\n    def test_open_context_with_no_match(self):\n        self.handler.bind(SimpleWidget)\n        widget = SimpleWidget()\n        self.handler.initialize(widget)\n        widget.text = 'u'\n\n        self.handler.open_context(widget, self.args[0])\n\n        self.assertEqual(widget.text, 'u')\n        self.assertEqual(widget.with_metas, [])\n        context = widget.current_context\n        self.assertEqual(context.attributes, self.args[1])\n        self.assertEqual(context.metas, self.args[2])\n        self.assertEqual(context.values['text'], ('u', -2))\n\n    def test_filter_value(self):\n        setting = ContextSetting([])\n        setting.name = \"value\"\n\n        def test_filter(before_value, after_value):\n            data = dict(value=before_value)\n            self.handler.filter_value(setting, data, *self.args)\n            self.assertEqual(data.get(\"value\", None), after_value)\n\n        # filter list values\n        test_filter([], [])\n        # When list contains attributes asa tuple of (name, type),\n        # Attributes not present in domain should be filtered out\n        test_filter([(\"d1\", Discrete), (\"d1\", Continuous),\n                     (\"c1\", Continuous), (\"c1\", Discrete)],\n                    [(\"d1\", Discrete), (\"c1\", Continuous)])\n        # All other values in list should remain\n        test_filter([0, [1, 2, 3], \"abcd\", 5.4], [0, [1, 2, 3], \"abcd\", 5.4])\n\n    def test_encode_setting(self):\n        setting = ContextSetting(None)\n\n        var = self.domain[0]\n        val = self.handler.encode_setting(None, setting, var)\n        self.assertEqual(val, (var.name, 100 + vartype(var)))\n\n        # Should not crash on anonymous variables\n        var.name = \"\"\n        val = self.handler.encode_setting(None, setting, var)\n        self.assertEqual(val, (var.name, 100 + vartype(var)))\n\n    def test_encode_list_settings(self):\n        setting = ContextSetting(None)\n\n        var1, var2 = self.domain[:2]\n        val = self.handler.encode_setting(None, setting, [None, var1, var2])\n        self.assertEqual(\n            val,\n            ([None,\n              (var1.name, 100 + vartype(var1)),\n              (var2.name, 100 + vartype(var2))], -3))\n\n        a_list = [1, 2, 3]\n        val = self.handler.encode_setting(None, setting, a_list)\n        self.assertEqual(val, [1, 2, 3])\n        self.assertIsNot(val, a_list)\n\n        a_list = []\n        val = self.handler.encode_setting(None, setting, a_list)\n        self.assertEqual(val, [])\n        self.assertIsNot(val, a_list)\n\n        a_list = [None, None]\n        val = self.handler.encode_setting(None, setting, a_list)\n        self.assertEqual(val, [None, None])\n        self.assertIsNot(val, a_list)\n\n    def test_decode_setting(self):\n        setting = ContextSetting(None)\n\n        var = self.domain[0]\n        val = self.handler.decode_setting(setting, (var.name, 100 + vartype(var)),\n                                          self.domain)\n        self.assertIs(val, var)\n\n        all_metas_domain = Domain([], metas=[var])\n        val = self.handler.decode_setting(setting, (var.name, 100 + vartype(var)),\n                                          all_metas_domain)\n        self.assertIs(val, var)\n\n    def test_decode_list_setting(self):\n        setting = ContextSetting(None)\n\n        var1, var2 = self.domain[:2]\n        val = self.handler.decode_setting(\n            setting,\n            ([None,\n              (var1.name, 100 + vartype(var1)),\n              (var2.name, 100 + vartype(var2))], -3),\n            self.domain)\n        self.assertEqual(val, [None, var1, var2])\n\n        val = self.handler.decode_setting(setting, [1, 2, 3], self.domain)\n        self.assertEqual(val, [1, 2, 3])\n\n    def test_backward_compatible_params(self):\n        with warnings.catch_warnings(record=True) as w:\n            warnings.simplefilter(\"always\")\n            DomainContextHandler(metas_in_res=True)\n            self.assertIn(OrangeDeprecationWarning,\n                          [x.category for x in w])\n\n    def test_deprecated_str_as_var(self):\n        if LooseVersion(Orange.__version__) >= LooseVersion(\"3.26\"):\n            # pragma: no cover\n            self.fail(\"Remove support for variables stored as string settings \"\n                      \"and this test.\")\n\n        context = Mock()\n        context.attributes = {\"foo\": 2}\n        context.metas = {}\n        setting = ContextSetting(\"\")\n        setting.name = \"setting_name\"\n        with warnings.catch_warnings(record=True) as w:\n            warnings.simplefilter(\"always\")\n            DomainContextHandler.encode_setting(context, setting, \"foo\")\n            self.assertIn(\"setting_name\", w[0].message.args[0])\n\n\n    def create_context(self, domain, values):\n        if domain is None:\n            domain = Domain([])\n\n        context = self.handler.new_context(domain,\n                                           *self.handler.encode_domain(domain))\n        context.values = values\n        return context",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 17,
                            "end_lineno": 309,
                            "parent": null
                        }
                    ],
                    "added_entities": [
                        {
                            "file_name": "Orange/widgets/tests/test_domain_context_handler.py",
                            "type": "method",
                            "name": "TestDomainContextHandler.test_deprecated_str_as_var",
                            "content": "class TestDomainContextHandler(TestCase):\n    def setUp(self):\n        self.domain = Domain(\n            attributes=[ContinuousVariable('c1'),\n                        DiscreteVariable('d1', values='abc'),\n                        DiscreteVariable('d2', values='def')],\n            class_vars=[DiscreteVariable('d3', values='ghi')],\n            metas=[ContinuousVariable('c2'),\n                   DiscreteVariable('d4', values='jkl')]\n        )\n        self.args = (self.domain,\n                     {'c1': Continuous - 100, 'd1': Discrete - 100,\n                      'd2': Discrete - 100, 'd3': Discrete - 100},\n                     {'c2': Continuous - 100, 'd4': Discrete - 100, })\n        self.handler = DomainContextHandler()\n        self.handler.read_defaults = lambda: None\n\n    def test_encode_domain_with_match_none(self):\n        handler = DomainContextHandler(\n            match_values=DomainContextHandler.MATCH_VALUES_NONE)\n\n        encoded_attributes, encoded_metas = handler.encode_domain(self.domain)\n\n        self.assertEqual(encoded_attributes,\n                         {'c1': Continuous - 100, 'd1': Discrete - 100,\n                          'd2': Discrete - 100, 'd3': Discrete - 100})\n        self.assertEqual(encoded_metas,\n                         {'c2': Continuous - 100, 'd4': Discrete - 100, })\n\n    def test_encode_domain_with_match_class(self):\n        handler = DomainContextHandler(\n            match_values=DomainContextHandler.MATCH_VALUES_CLASS)\n\n        encoded_attributes, encoded_metas = handler.encode_domain(self.domain)\n\n        self.assertEqual(encoded_attributes,\n                         {'c1': Continuous - 100, 'd1': Discrete - 100,\n                          'd2': Discrete - 100,\n                          'd3': list('ghi')})\n        self.assertEqual(encoded_metas,\n                         {'c2': Continuous - 100, 'd4': Discrete - 100})\n\n    def test_encode_domain_with_match_all(self):\n        handler = DomainContextHandler(\n            match_values=DomainContextHandler.MATCH_VALUES_ALL)\n\n        encoded_attributes, encoded_metas = handler.encode_domain(self.domain)\n\n        self.assertEqual(encoded_attributes,\n                         {'c1': Continuous - 100, 'd1': list('abc'),\n                          'd2': list('def'), 'd3': list('ghi')})\n        self.assertEqual(encoded_metas,\n                         {'c2': Continuous - 100, 'd4': list('jkl')})\n\n    def test_match_returns_2_on_perfect_match(self):\n        context = Mock(\n            attributes=self.args[1], metas=self.args[2], values={})\n        self.assertEqual(2., self.handler.match(context, *self.args))\n\n    def test_match_returns_1_if_everything_matches(self):\n        self.handler.bind(SimpleWidget)\n\n        # Attributes in values\n        context = Mock(values=dict(\n            with_metas=('d1', Discrete),\n            required=('d1', Discrete)))\n        self.assertEqual(1., self.handler.match(context, *self.args))\n\n        # Metas in values\n        context = Mock(values=dict(\n            with_metas=('d4', Discrete),\n            required=('d1', Discrete)))\n        self.assertEqual(1., self.handler.match(context, *self.args))\n\n        # Attributes in lists\n        context = Mock(values=dict(\n            with_metas=[(\"d1\", Discrete)]\n        ))\n        self.assertEqual(1., self.handler.match(context, *self.args))\n\n        # Metas in lists\n        context = Mock(values=dict(\n            with_metas=[(\"d4\", Discrete)]\n        ))\n        self.assertEqual(1., self.handler.match(context, *self.args))\n\n    def test_match_returns_point_1_when_nothing_to_match(self):\n        self.handler.bind(SimpleWidget)\n\n        context = Mock(values={})\n        self.assertEqual(0.1, self.handler.match(context, *self.args))\n\n    def test_match_returns_zero_on_incompatible_context(self):\n        self.handler.bind(SimpleWidget)\n\n        # required\n        context = Mock(values=dict(required=('u', Discrete),\n                                   with_metas=('d1', Discrete)))\n        self.assertEqual(0, self.handler.match(context, *self.args))\n\n    def test_clone_context(self):\n        self.handler.bind(SimpleWidget)\n        context = self.create_context(self.domain, dict(\n            text=('u', -2),\n            with_metas=[('d1', Discrete), ('d1', Continuous),\n                        ('c1', Continuous), ('c1', Discrete)],\n            required=('u', Continuous)\n        ))\n\n        new_values = self.handler.clone_context(context, *self.args).values\n\n        self.assertEqual(new_values['text'], ('u', -2))\n        self.assertEqual([('d1', Discrete), ('c1', Continuous)],\n                         new_values['with_metas'])\n        self.assertNotIn('required', new_values)\n\n    def test_open_context(self):\n        self.handler.bind(SimpleWidget)\n        context = self.create_context(self.domain, dict(\n            text=('u', -2),\n            with_metas=[('d1', Discrete), ('d2', Discrete)]\n        ))\n        self.handler.global_contexts = \\\n            [Mock(values={}), context, Mock(values={})]\n\n        widget = SimpleWidget()\n        self.handler.initialize(widget)\n        old_metas_list = widget.with_metas\n        self.handler.open_context(widget, self.args[0])\n\n        context = widget.current_context\n        self.assertEqual(context.attributes, self.args[1])\n        self.assertEqual(context.metas, self.args[2])\n        self.assertIs(old_metas_list, widget.with_metas)\n\n        self.assertEqual(widget.text, 'u')\n        self.assertEqual(widget.with_metas, [('d1', Discrete),\n                                             ('d2', Discrete)])\n\n    def test_open_context_with_imperfect_match(self):\n        self.handler.bind(SimpleWidget)\n        context = self.create_context(None, dict(\n            text=('u', -2),\n            with_metas=[('d1', Discrete), ('d1', Continuous),\n                        ('c1', Continuous), ('c1', Discrete)]\n        ))\n        self.handler.global_contexts = \\\n            [Mock(values={}), context, Mock(values={})]\n\n        widget = SimpleWidget()\n        self.handler.initialize(widget)\n        self.handler.open_context(widget, self.args[0])\n\n        context = widget.current_context\n        self.assertEqual(context.attributes, self.args[1])\n        self.assertEqual(context.metas, self.args[2])\n\n        self.assertEqual(widget.text, 'u')\n        self.assertEqual(widget.with_metas, [('d1', Discrete),\n                                             ('c1', Continuous)])\n\n    def test_open_context_with_no_match(self):\n        self.handler.bind(SimpleWidget)\n        widget = SimpleWidget()\n        self.handler.initialize(widget)\n        widget.text = 'u'\n\n        self.handler.open_context(widget, self.args[0])\n\n        self.assertEqual(widget.text, 'u')\n        self.assertEqual(widget.with_metas, [])\n        context = widget.current_context\n        self.assertEqual(context.attributes, self.args[1])\n        self.assertEqual(context.metas, self.args[2])\n        self.assertEqual(context.values['text'], ('u', -2))\n\n    def test_filter_value(self):\n        setting = ContextSetting([])\n        setting.name = \"value\"\n\n        def test_filter(before_value, after_value):\n            data = dict(value=before_value)\n            self.handler.filter_value(setting, data, *self.args)\n            self.assertEqual(data.get(\"value\", None), after_value)\n\n        # filter list values\n        test_filter([], [])\n        # When list contains attributes asa tuple of (name, type),\n        # Attributes not present in domain should be filtered out\n        test_filter([(\"d1\", Discrete), (\"d1\", Continuous),\n                     (\"c1\", Continuous), (\"c1\", Discrete)],\n                    [(\"d1\", Discrete), (\"c1\", Continuous)])\n        # All other values in list should remain\n        test_filter([0, [1, 2, 3], \"abcd\", 5.4], [0, [1, 2, 3], \"abcd\", 5.4])\n\n    def test_encode_setting(self):\n        setting = ContextSetting(None)\n\n        var = self.domain[0]\n        val = self.handler.encode_setting(None, setting, var)\n        self.assertEqual(val, (var.name, 100 + vartype(var)))\n\n        # Should not crash on anonymous variables\n        var.name = \"\"\n        val = self.handler.encode_setting(None, setting, var)\n        self.assertEqual(val, (var.name, 100 + vartype(var)))\n\n    def test_encode_list_settings(self):\n        setting = ContextSetting(None)\n\n        var1, var2 = self.domain[:2]\n        val = self.handler.encode_setting(None, setting, [None, var1, var2])\n        self.assertEqual(\n            val,\n            ([None,\n              (var1.name, 100 + vartype(var1)),\n              (var2.name, 100 + vartype(var2))], -3))\n\n        a_list = [1, 2, 3]\n        val = self.handler.encode_setting(None, setting, a_list)\n        self.assertEqual(val, [1, 2, 3])\n        self.assertIsNot(val, a_list)\n\n        a_list = []\n        val = self.handler.encode_setting(None, setting, a_list)\n        self.assertEqual(val, [])\n        self.assertIsNot(val, a_list)\n\n        a_list = [None, None]\n        val = self.handler.encode_setting(None, setting, a_list)\n        self.assertEqual(val, [None, None])\n        self.assertIsNot(val, a_list)\n\n    def test_decode_setting(self):\n        setting = ContextSetting(None)\n\n        var = self.domain[0]\n        val = self.handler.decode_setting(setting, (var.name, 100 + vartype(var)),\n                                          self.domain)\n        self.assertIs(val, var)\n\n        all_metas_domain = Domain([], metas=[var])\n        val = self.handler.decode_setting(setting, (var.name, 100 + vartype(var)),\n                                          all_metas_domain)\n        self.assertIs(val, var)\n\n    def test_decode_list_setting(self):\n        setting = ContextSetting(None)\n\n        var1, var2 = self.domain[:2]\n        val = self.handler.decode_setting(\n            setting,\n            ([None,\n              (var1.name, 100 + vartype(var1)),\n              (var2.name, 100 + vartype(var2))], -3),\n            self.domain)\n        self.assertEqual(val, [None, var1, var2])\n\n        val = self.handler.decode_setting(setting, [1, 2, 3], self.domain)\n        self.assertEqual(val, [1, 2, 3])\n\n    def test_backward_compatible_params(self):\n        with warnings.catch_warnings(record=True) as w:\n            warnings.simplefilter(\"always\")\n            DomainContextHandler(metas_in_res=True)\n            self.assertIn(OrangeDeprecationWarning,\n                          [x.category for x in w])\n\n    def test_deprecated_str_as_var(self):\n        if LooseVersion(Orange.__version__) >= LooseVersion(\"3.26\"):\n            # pragma: no cover\n            self.fail(\"Remove support for variables stored as string settings \"\n                      \"and this test.\")\n\n        context = Mock()\n        context.attributes = {\"foo\": 2}\n        context.metas = {}\n        setting = ContextSetting(\"\")\n        setting.name = \"setting_name\"\n        with warnings.catch_warnings(record=True) as w:\n            warnings.simplefilter(\"always\")\n            DomainContextHandler.encode_setting(context, setting, \"foo\")\n            self.assertIn(\"setting_name\", w[0].message.args[0])\n\n\n    def create_context(self, domain, values):\n        if domain is None:\n            domain = Domain([])\n\n        context = self.handler.new_context(domain,\n                                           *self.handler.encode_domain(domain))\n        context.values = values\n        return context",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 285,
                            "end_lineno": 299,
                            "parent": {
                                "file_name": "Orange/widgets/tests/test_domain_context_handler.py",
                                "type": "class",
                                "name": "TestDomainContextHandler",
                                "content": "class TestDomainContextHandler(TestCase):\n    def setUp(self):\n        self.domain = Domain(\n            attributes=[ContinuousVariable('c1'),\n                        DiscreteVariable('d1', values='abc'),\n                        DiscreteVariable('d2', values='def')],\n            class_vars=[DiscreteVariable('d3', values='ghi')],\n            metas=[ContinuousVariable('c2'),\n                   DiscreteVariable('d4', values='jkl')]\n        )\n        self.args = (self.domain,\n                     {'c1': Continuous - 100, 'd1': Discrete - 100,\n                      'd2': Discrete - 100, 'd3': Discrete - 100},\n                     {'c2': Continuous - 100, 'd4': Discrete - 100, })\n        self.handler = DomainContextHandler()\n        self.handler.read_defaults = lambda: None\n\n    def test_encode_domain_with_match_none(self):\n        handler = DomainContextHandler(\n            match_values=DomainContextHandler.MATCH_VALUES_NONE)\n\n        encoded_attributes, encoded_metas = handler.encode_domain(self.domain)\n\n        self.assertEqual(encoded_attributes,\n                         {'c1': Continuous - 100, 'd1': Discrete - 100,\n                          'd2': Discrete - 100, 'd3': Discrete - 100})\n        self.assertEqual(encoded_metas,\n                         {'c2': Continuous - 100, 'd4': Discrete - 100, })\n\n    def test_encode_domain_with_match_class(self):\n        handler = DomainContextHandler(\n            match_values=DomainContextHandler.MATCH_VALUES_CLASS)\n\n        encoded_attributes, encoded_metas = handler.encode_domain(self.domain)\n\n        self.assertEqual(encoded_attributes,\n                         {'c1': Continuous - 100, 'd1': Discrete - 100,\n                          'd2': Discrete - 100,\n                          'd3': list('ghi')})\n        self.assertEqual(encoded_metas,\n                         {'c2': Continuous - 100, 'd4': Discrete - 100})\n\n    def test_encode_domain_with_match_all(self):\n        handler = DomainContextHandler(\n            match_values=DomainContextHandler.MATCH_VALUES_ALL)\n\n        encoded_attributes, encoded_metas = handler.encode_domain(self.domain)\n\n        self.assertEqual(encoded_attributes,\n                         {'c1': Continuous - 100, 'd1': list('abc'),\n                          'd2': list('def'), 'd3': list('ghi')})\n        self.assertEqual(encoded_metas,\n                         {'c2': Continuous - 100, 'd4': list('jkl')})\n\n    def test_match_returns_2_on_perfect_match(self):\n        context = Mock(\n            attributes=self.args[1], metas=self.args[2], values={})\n        self.assertEqual(2., self.handler.match(context, *self.args))\n\n    def test_match_returns_1_if_everything_matches(self):\n        self.handler.bind(SimpleWidget)\n\n        # Attributes in values\n        context = Mock(values=dict(\n            with_metas=('d1', Discrete),\n            required=('d1', Discrete)))\n        self.assertEqual(1., self.handler.match(context, *self.args))\n\n        # Metas in values\n        context = Mock(values=dict(\n            with_metas=('d4', Discrete),\n            required=('d1', Discrete)))\n        self.assertEqual(1., self.handler.match(context, *self.args))\n\n        # Attributes in lists\n        context = Mock(values=dict(\n            with_metas=[(\"d1\", Discrete)]\n        ))\n        self.assertEqual(1., self.handler.match(context, *self.args))\n\n        # Metas in lists\n        context = Mock(values=dict(\n            with_metas=[(\"d4\", Discrete)]\n        ))\n        self.assertEqual(1., self.handler.match(context, *self.args))\n\n    def test_match_returns_point_1_when_nothing_to_match(self):\n        self.handler.bind(SimpleWidget)\n\n        context = Mock(values={})\n        self.assertEqual(0.1, self.handler.match(context, *self.args))\n\n    def test_match_returns_zero_on_incompatible_context(self):\n        self.handler.bind(SimpleWidget)\n\n        # required\n        context = Mock(values=dict(required=('u', Discrete),\n                                   with_metas=('d1', Discrete)))\n        self.assertEqual(0, self.handler.match(context, *self.args))\n\n    def test_clone_context(self):\n        self.handler.bind(SimpleWidget)\n        context = self.create_context(self.domain, dict(\n            text=('u', -2),\n            with_metas=[('d1', Discrete), ('d1', Continuous),\n                        ('c1', Continuous), ('c1', Discrete)],\n            required=('u', Continuous)\n        ))\n\n        new_values = self.handler.clone_context(context, *self.args).values\n\n        self.assertEqual(new_values['text'], ('u', -2))\n        self.assertEqual([('d1', Discrete), ('c1', Continuous)],\n                         new_values['with_metas'])\n        self.assertNotIn('required', new_values)\n\n    def test_open_context(self):\n        self.handler.bind(SimpleWidget)\n        context = self.create_context(self.domain, dict(\n            text=('u', -2),\n            with_metas=[('d1', Discrete), ('d2', Discrete)]\n        ))\n        self.handler.global_contexts = \\\n            [Mock(values={}), context, Mock(values={})]\n\n        widget = SimpleWidget()\n        self.handler.initialize(widget)\n        old_metas_list = widget.with_metas\n        self.handler.open_context(widget, self.args[0])\n\n        context = widget.current_context\n        self.assertEqual(context.attributes, self.args[1])\n        self.assertEqual(context.metas, self.args[2])\n        self.assertIs(old_metas_list, widget.with_metas)\n\n        self.assertEqual(widget.text, 'u')\n        self.assertEqual(widget.with_metas, [('d1', Discrete),\n                                             ('d2', Discrete)])\n\n    def test_open_context_with_imperfect_match(self):\n        self.handler.bind(SimpleWidget)\n        context = self.create_context(None, dict(\n            text=('u', -2),\n            with_metas=[('d1', Discrete), ('d1', Continuous),\n                        ('c1', Continuous), ('c1', Discrete)]\n        ))\n        self.handler.global_contexts = \\\n            [Mock(values={}), context, Mock(values={})]\n\n        widget = SimpleWidget()\n        self.handler.initialize(widget)\n        self.handler.open_context(widget, self.args[0])\n\n        context = widget.current_context\n        self.assertEqual(context.attributes, self.args[1])\n        self.assertEqual(context.metas, self.args[2])\n\n        self.assertEqual(widget.text, 'u')\n        self.assertEqual(widget.with_metas, [('d1', Discrete),\n                                             ('c1', Continuous)])\n\n    def test_open_context_with_no_match(self):\n        self.handler.bind(SimpleWidget)\n        widget = SimpleWidget()\n        self.handler.initialize(widget)\n        widget.text = 'u'\n\n        self.handler.open_context(widget, self.args[0])\n\n        self.assertEqual(widget.text, 'u')\n        self.assertEqual(widget.with_metas, [])\n        context = widget.current_context\n        self.assertEqual(context.attributes, self.args[1])\n        self.assertEqual(context.metas, self.args[2])\n        self.assertEqual(context.values['text'], ('u', -2))\n\n    def test_filter_value(self):\n        setting = ContextSetting([])\n        setting.name = \"value\"\n\n        def test_filter(before_value, after_value):\n            data = dict(value=before_value)\n            self.handler.filter_value(setting, data, *self.args)\n            self.assertEqual(data.get(\"value\", None), after_value)\n\n        # filter list values\n        test_filter([], [])\n        # When list contains attributes asa tuple of (name, type),\n        # Attributes not present in domain should be filtered out\n        test_filter([(\"d1\", Discrete), (\"d1\", Continuous),\n                     (\"c1\", Continuous), (\"c1\", Discrete)],\n                    [(\"d1\", Discrete), (\"c1\", Continuous)])\n        # All other values in list should remain\n        test_filter([0, [1, 2, 3], \"abcd\", 5.4], [0, [1, 2, 3], \"abcd\", 5.4])\n\n    def test_encode_setting(self):\n        setting = ContextSetting(None)\n\n        var = self.domain[0]\n        val = self.handler.encode_setting(None, setting, var)\n        self.assertEqual(val, (var.name, 100 + vartype(var)))\n\n        # Should not crash on anonymous variables\n        var.name = \"\"\n        val = self.handler.encode_setting(None, setting, var)\n        self.assertEqual(val, (var.name, 100 + vartype(var)))\n\n    def test_encode_list_settings(self):\n        setting = ContextSetting(None)\n\n        var1, var2 = self.domain[:2]\n        val = self.handler.encode_setting(None, setting, [None, var1, var2])\n        self.assertEqual(\n            val,\n            ([None,\n              (var1.name, 100 + vartype(var1)),\n              (var2.name, 100 + vartype(var2))], -3))\n\n        a_list = [1, 2, 3]\n        val = self.handler.encode_setting(None, setting, a_list)\n        self.assertEqual(val, [1, 2, 3])\n        self.assertIsNot(val, a_list)\n\n        a_list = []\n        val = self.handler.encode_setting(None, setting, a_list)\n        self.assertEqual(val, [])\n        self.assertIsNot(val, a_list)\n\n        a_list = [None, None]\n        val = self.handler.encode_setting(None, setting, a_list)\n        self.assertEqual(val, [None, None])\n        self.assertIsNot(val, a_list)\n\n    def test_decode_setting(self):\n        setting = ContextSetting(None)\n\n        var = self.domain[0]\n        val = self.handler.decode_setting(setting, (var.name, 100 + vartype(var)),\n                                          self.domain)\n        self.assertIs(val, var)\n\n        all_metas_domain = Domain([], metas=[var])\n        val = self.handler.decode_setting(setting, (var.name, 100 + vartype(var)),\n                                          all_metas_domain)\n        self.assertIs(val, var)\n\n    def test_decode_list_setting(self):\n        setting = ContextSetting(None)\n\n        var1, var2 = self.domain[:2]\n        val = self.handler.decode_setting(\n            setting,\n            ([None,\n              (var1.name, 100 + vartype(var1)),\n              (var2.name, 100 + vartype(var2))], -3),\n            self.domain)\n        self.assertEqual(val, [None, var1, var2])\n\n        val = self.handler.decode_setting(setting, [1, 2, 3], self.domain)\n        self.assertEqual(val, [1, 2, 3])\n\n    def test_backward_compatible_params(self):\n        with warnings.catch_warnings(record=True) as w:\n            warnings.simplefilter(\"always\")\n            DomainContextHandler(metas_in_res=True)\n            self.assertIn(OrangeDeprecationWarning,\n                          [x.category for x in w])\n\n    def test_deprecated_str_as_var(self):\n        if LooseVersion(Orange.__version__) >= LooseVersion(\"3.26\"):\n            # pragma: no cover\n            self.fail(\"Remove support for variables stored as string settings \"\n                      \"and this test.\")\n\n        context = Mock()\n        context.attributes = {\"foo\": 2}\n        context.metas = {}\n        setting = ContextSetting(\"\")\n        setting.name = \"setting_name\"\n        with warnings.catch_warnings(record=True) as w:\n            warnings.simplefilter(\"always\")\n            DomainContextHandler.encode_setting(context, setting, \"foo\")\n            self.assertIn(\"setting_name\", w[0].message.args[0])\n\n\n    def create_context(self, domain, values):\n        if domain is None:\n            domain = Domain([])\n\n        context = self.handler.new_context(domain,\n                                           *self.handler.encode_domain(domain))\n        context.values = values\n        return context",
                                "ast_type_str": "ClassDef",
                                "start_lineno": 17,
                                "end_lineno": 309,
                                "parent": null
                            }
                        }
                    ],
                    "deleted_entities": []
                }
            ]
        }
    ],
    "old_commit_hash": "4828c557ac3c69073869ec78a9afe8bb39db32a5^",
    "new_commit_hash": "4828c557ac3c69073869ec78a9afe8bb39db32a5",
    "commit_message": "Settings: warn about deprecation of variables stored as string settings",
    "commit_date": "2019-04-05T22:58:25+02:00",
    "metadata": {}
}
{
    "repo_name": "orange3",
    "new_commit_hash": "4828c557ac3c69073869ec78a9afe8bb39db32a5",
    "test_file_codes": [
        "import warnings\nfrom distutils.version import LooseVersion\nfrom unittest import TestCase\nfrom unittest.mock import Mock\n\nimport Orange\nfrom Orange.data import Domain, DiscreteVariable\nfrom Orange.data import ContinuousVariable\nfrom Orange.util import OrangeDeprecationWarning\nfrom Orange.widgets.settings import DomainContextHandler, ContextSetting\nfrom Orange.widgets.utils import vartype\n\nContinuous = 100 + vartype(ContinuousVariable())\nDiscrete = 100 + vartype(DiscreteVariable())\n\n\nclass TestDomainContextHandler(TestCase):\n    def setUp(self):\n        self.domain = Domain(\n            attributes=[ContinuousVariable('c1'),\n                        DiscreteVariable('d1', values='abc'),\n                        DiscreteVariable('d2', values='def')],\n            class_vars=[DiscreteVariable('d3', values='ghi')],\n            metas=[ContinuousVariable('c2'),\n                   DiscreteVariable('d4', values='jkl')]\n        )\n        self.args = (self.domain,\n                     {'c1': Continuous - 100, 'd1': Discrete - 100,\n                      'd2': Discrete - 100, 'd3': Discrete - 100},\n                     {'c2': Continuous - 100, 'd4': Discrete - 100, })\n        self.handler = DomainContextHandler()\n        self.handler.read_defaults = lambda: None\n\n    def test_encode_domain_with_match_none(self):\n        handler = DomainContextHandler(\n            match_values=DomainContextHandler.MATCH_VALUES_NONE)\n\n        encoded_attributes, encoded_metas = handler.encode_domain(self.domain)\n\n        self.assertEqual(encoded_attributes,\n                         {'c1': Continuous - 100, 'd1': Discrete - 100,\n                          'd2': Discrete - 100, 'd3': Discrete - 100})\n        self.assertEqual(encoded_metas,\n                         {'c2': Continuous - 100, 'd4': Discrete - 100, })\n\n    def test_encode_domain_with_match_class(self):\n        handler = DomainContextHandler(\n            match_values=DomainContextHandler.MATCH_VALUES_CLASS)\n\n        encoded_attributes, encoded_metas = handler.encode_domain(self.domain)\n\n        self.assertEqual(encoded_attributes,\n                         {'c1': Continuous - 100, 'd1': Discrete - 100,\n                          'd2': Discrete - 100,\n                          'd3': list('ghi')})\n        self.assertEqual(encoded_metas,\n                         {'c2': Continuous - 100, 'd4': Discrete - 100})\n\n    def test_encode_domain_with_match_all(self):\n        handler = DomainContextHandler(\n            match_values=DomainContextHandler.MATCH_VALUES_ALL)\n\n        encoded_attributes, encoded_metas = handler.encode_domain(self.domain)\n\n        self.assertEqual(encoded_attributes,\n                         {'c1': Continuous - 100, 'd1': list('abc'),\n                          'd2': list('def'), 'd3': list('ghi')})\n        self.assertEqual(encoded_metas,\n                         {'c2': Continuous - 100, 'd4': list('jkl')})\n\n    def test_match_returns_2_on_perfect_match(self):\n        context = Mock(\n            attributes=self.args[1], metas=self.args[2], values={})\n        self.assertEqual(2., self.handler.match(context, *self.args))\n\n    def test_match_returns_1_if_everything_matches(self):\n        self.handler.bind(SimpleWidget)\n\n        # Attributes in values\n        context = Mock(values=dict(\n            with_metas=('d1', Discrete),\n            required=('d1', Discrete)))\n        self.assertEqual(1., self.handler.match(context, *self.args))\n\n        # Metas in values\n        context = Mock(values=dict(\n            with_metas=('d4', Discrete),\n            required=('d1', Discrete)))\n        self.assertEqual(1., self.handler.match(context, *self.args))\n\n        # Attributes in lists\n        context = Mock(values=dict(\n            with_metas=[(\"d1\", Discrete)]\n        ))\n        self.assertEqual(1., self.handler.match(context, *self.args))\n\n        # Metas in lists\n        context = Mock(values=dict(\n            with_metas=[(\"d4\", Discrete)]\n        ))\n        self.assertEqual(1., self.handler.match(context, *self.args))\n\n    def test_match_returns_point_1_when_nothing_to_match(self):\n        self.handler.bind(SimpleWidget)\n\n        context = Mock(values={})\n        self.assertEqual(0.1, self.handler.match(context, *self.args))\n\n    def test_match_returns_zero_on_incompatible_context(self):\n        self.handler.bind(SimpleWidget)\n\n        # required\n        context = Mock(values=dict(required=('u', Discrete),\n                                   with_metas=('d1', Discrete)))\n        self.assertEqual(0, self.handler.match(context, *self.args))\n\n    def test_clone_context(self):\n        self.handler.bind(SimpleWidget)\n        context = self.create_context(self.domain, dict(\n            text=('u', -2),\n            with_metas=[('d1', Discrete), ('d1', Continuous),\n                        ('c1', Continuous), ('c1', Discrete)],\n            required=('u', Continuous)\n        ))\n\n        new_values = self.handler.clone_context(context, *self.args).values\n\n        self.assertEqual(new_values['text'], ('u', -2))\n        self.assertEqual([('d1', Discrete), ('c1', Continuous)],\n                         new_values['with_metas'])\n        self.assertNotIn('required', new_values)\n\n    def test_open_context(self):\n        self.handler.bind(SimpleWidget)\n        context = self.create_context(self.domain, dict(\n            text=('u', -2),\n            with_metas=[('d1', Discrete), ('d2', Discrete)]\n        ))\n        self.handler.global_contexts = \\\n            [Mock(values={}), context, Mock(values={})]\n\n        widget = SimpleWidget()\n        self.handler.initialize(widget)\n        old_metas_list = widget.with_metas\n        self.handler.open_context(widget, self.args[0])\n\n        context = widget.current_context\n        self.assertEqual(context.attributes, self.args[1])\n        self.assertEqual(context.metas, self.args[2])\n        self.assertIs(old_metas_list, widget.with_metas)\n\n        self.assertEqual(widget.text, 'u')\n        self.assertEqual(widget.with_metas, [('d1', Discrete),\n                                             ('d2', Discrete)])\n\n    def test_open_context_with_imperfect_match(self):\n        self.handler.bind(SimpleWidget)\n        context = self.create_context(None, dict(\n            text=('u', -2),\n            with_metas=[('d1', Discrete), ('d1', Continuous),\n                        ('c1', Continuous), ('c1', Discrete)]\n        ))\n        self.handler.global_contexts = \\\n            [Mock(values={}), context, Mock(values={})]\n\n        widget = SimpleWidget()\n        self.handler.initialize(widget)\n        self.handler.open_context(widget, self.args[0])\n\n        context = widget.current_context\n        self.assertEqual(context.attributes, self.args[1])\n        self.assertEqual(context.metas, self.args[2])\n\n        self.assertEqual(widget.text, 'u')\n        self.assertEqual(widget.with_metas, [('d1', Discrete),\n                                             ('c1', Continuous)])\n\n    def test_open_context_with_no_match(self):\n        self.handler.bind(SimpleWidget)\n        widget = SimpleWidget()\n        self.handler.initialize(widget)\n        widget.text = 'u'\n\n        self.handler.open_context(widget, self.args[0])\n\n        self.assertEqual(widget.text, 'u')\n        self.assertEqual(widget.with_metas, [])\n        context = widget.current_context\n        self.assertEqual(context.attributes, self.args[1])\n        self.assertEqual(context.metas, self.args[2])\n        self.assertEqual(context.values['text'], ('u', -2))\n\n    def test_filter_value(self):\n        setting = ContextSetting([])\n        setting.name = \"value\"\n\n        def test_filter(before_value, after_value):\n            data = dict(value=before_value)\n            self.handler.filter_value(setting, data, *self.args)\n            self.assertEqual(data.get(\"value\", None), after_value)\n\n        # filter list values\n        test_filter([], [])\n        # When list contains attributes asa tuple of (name, type),\n        # Attributes not present in domain should be filtered out\n        test_filter([(\"d1\", Discrete), (\"d1\", Continuous),\n                     (\"c1\", Continuous), (\"c1\", Discrete)],\n                    [(\"d1\", Discrete), (\"c1\", Continuous)])\n        # All other values in list should remain\n        test_filter([0, [1, 2, 3], \"abcd\", 5.4], [0, [1, 2, 3], \"abcd\", 5.4])\n\n    def test_encode_setting(self):\n        setting = ContextSetting(None)\n\n        var = self.domain[0]\n        val = self.handler.encode_setting(None, setting, var)\n        self.assertEqual(val, (var.name, 100 + vartype(var)))\n\n        # Should not crash on anonymous variables\n        var.name = \"\"\n        val = self.handler.encode_setting(None, setting, var)\n        self.assertEqual(val, (var.name, 100 + vartype(var)))\n\n    def test_encode_list_settings(self):\n        setting = ContextSetting(None)\n\n        var1, var2 = self.domain[:2]\n        val = self.handler.encode_setting(None, setting, [None, var1, var2])\n        self.assertEqual(\n            val,\n            ([None,\n              (var1.name, 100 + vartype(var1)),\n              (var2.name, 100 + vartype(var2))], -3))\n\n        a_list = [1, 2, 3]\n        val = self.handler.encode_setting(None, setting, a_list)\n        self.assertEqual(val, [1, 2, 3])\n        self.assertIsNot(val, a_list)\n\n        a_list = []\n        val = self.handler.encode_setting(None, setting, a_list)\n        self.assertEqual(val, [])\n        self.assertIsNot(val, a_list)\n\n        a_list = [None, None]\n        val = self.handler.encode_setting(None, setting, a_list)\n        self.assertEqual(val, [None, None])\n        self.assertIsNot(val, a_list)\n\n    def test_decode_setting(self):\n        setting = ContextSetting(None)\n\n        var = self.domain[0]\n        val = self.handler.decode_setting(setting, (var.name, 100 + vartype(var)),\n                                          self.domain)\n        self.assertIs(val, var)\n\n        all_metas_domain = Domain([], metas=[var])\n        val = self.handler.decode_setting(setting, (var.name, 100 + vartype(var)),\n                                          all_metas_domain)\n        self.assertIs(val, var)\n\n    def test_decode_list_setting(self):\n        setting = ContextSetting(None)\n\n        var1, var2 = self.domain[:2]\n        val = self.handler.decode_setting(\n            setting,\n            ([None,\n              (var1.name, 100 + vartype(var1)),\n              (var2.name, 100 + vartype(var2))], -3),\n            self.domain)\n        self.assertEqual(val, [None, var1, var2])\n\n        val = self.handler.decode_setting(setting, [1, 2, 3], self.domain)\n        self.assertEqual(val, [1, 2, 3])\n\n    def test_backward_compatible_params(self):\n        with warnings.catch_warnings(record=True) as w:\n            warnings.simplefilter(\"always\")\n            DomainContextHandler(metas_in_res=True)\n            self.assertIn(OrangeDeprecationWarning,\n                          [x.category for x in w])\n\n    def test_deprecated_str_as_var(self):\n        if LooseVersion(Orange.__version__) >= LooseVersion(\"3.26\"):\n            # pragma: no cover\n            self.fail(\"Remove support for variables stored as string settings \"\n                      \"and this test.\")\n\n        context = Mock()\n        context.attributes = {\"foo\": 2}\n        context.metas = {}\n        setting = ContextSetting(\"\")\n        setting.name = \"setting_name\"\n        with warnings.catch_warnings(record=True) as w:\n            warnings.simplefilter(\"always\")\n            DomainContextHandler.encode_setting(context, setting, \"foo\")\n            self.assertIn(\"setting_name\", w[0].message.args[0])\n\n\n    def create_context(self, domain, values):\n        if domain is None:\n            domain = Domain([])\n\n        context = self.handler.new_context(domain,\n                                           *self.handler.encode_domain(domain))\n        context.values = values\n        return context\n\n\nclass SimpleWidget:\n    text = ContextSetting(\"\")\n    with_metas = ContextSetting([], required=ContextSetting.OPTIONAL)\n    required = ContextSetting(\"\", required=ContextSetting.REQUIRED)\n\n    def retrieveSpecificSettings(self):\n        pass\n\n    def storeSpecificSettings(self):\n        pass\n"
    ],
    "test_file_names": [
        "test_1.py"
    ],
    "setup_res_code": 0,
    "setup_res_stdout": "Starting Orange installation attempts...\nAttempting installation with Python 3.7...\nWarning: 'keywords' should be a list, got type 'tuple'\nWarning: 'classifiers' should be a list, got type 'tuple'\nWarning: 'keywords' should be a list, got type 'tuple'\nWarning: 'classifiers' should be a list, got type 'tuple'\nrunning build_ext\nrunning build_src\nbuild_src\nbuilding extension \"Orange.classification._simple_tree\" sources\nbuilding extension \"Orange.classification._tree_scorers\" sources\nbuilding extension \"Orange.data._valuecount\" sources\nbuilding extension \"Orange.data._contingency\" sources\nbuilding extension \"Orange.data._io\" sources\nbuilding extension \"Orange.data._variable\" sources\nbuilding extension \"Orange.distance._distance\" sources\nbuilding extension \"Orange.preprocess._discretize\" sources\nbuilding extension \"Orange.preprocess._relieff\" sources\nbuilding extension \"Orange.widgets.utils._grid_density\" sources\nbuild_src: building npy-pkg config files\ncustomize UnixCCompiler\nC compiler: cc -pthread -Wno-unused-result -Wsign-compare -Wunreachable-code -DNDEBUG -g -fwrapv -O3 -Wall -fPIC -I/tools/deps/include -I/tools/deps/include/ncursesw -fPIC\n\ncreating /tmp/tmpwz2w3kcy/tmp\ncreating /tmp/tmpwz2w3kcy/tmp/tmpwz2w3kcy\ncompile options: '-MMD -MF /tmp/tmpwz2w3kcy/file.c.d -c'\ncc: /tmp/tmpwz2w3kcy/file.c\ncustomize UnixCCompiler using build_ext\ncustomize UnixCCompiler\nC compiler: cc -pthread -Wno-unused-result -Wsign-compare -Wunreachable-code -DNDEBUG -g -fwrapv -O3 -Wall -fPIC -I/tools/deps/include -I/tools/deps/include/ncursesw -fPIC\n\ncreating /tmp/tmp8go4z_aq/tmp\ncreating /tmp/tmp8go4z_aq/tmp/tmp8go4z_aq\ncompile options: '-MMD -MF /tmp/tmp8go4z_aq/file.c.d -c'\ncc: /tmp/tmp8go4z_aq/file.c\ncustomize UnixCCompiler using build_ext\nbuilding 'Orange.classification._simple_tree' extension\ncompiling C sources\nC compiler: cc -pthread -Wno-unused-result -Wsign-compare -Wunreachable-code -DNDEBUG -g -fwrapv -O3 -Wall -fPIC -I/tools/deps/include -I/tools/deps/include/ncursesw -fPIC\n\ncreating build/temp.linux-x86_64-3.7/Orange\ncreating build/temp.linux-x86_64-3.7/Orange/classification\ncompile options: '-I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_4828c557ac3c69073869ec78a9afe8bb39db32a5/.venv/lib/python3.7/site-packages/numpy/core/include -I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_4828c557ac3c69073869ec78a9afe8bb39db32a5/.venv/include -I/home/gcpuser/.local/share/uv/python/cpython-3.7.9-linux-x86_64-gnu/include/python3.7m -c'\ncc: Orange/classification/_simple_tree.c\ncc -pthread -shared -L/tools/deps/lib build/temp.linux-x86_64-3.7/Orange/classification/_simple_tree.o -L/home/gcpuser/.local/share/uv/python/cpython-3.7.9-linux-x86_64-gnu/lib -lm -lpython3.7m -o Orange/classification/_simple_tree.cpython-37m-x86_64-linux-gnu.so\nbuilding 'Orange.classification._tree_scorers' extension\ncompiling C sources\nC compiler: cc -pthread -Wno-unused-result -Wsign-compare -Wunreachable-code -DNDEBUG -g -fwrapv -O3 -Wall -fPIC -I/tools/deps/include -I/tools/deps/include/ncursesw -fPIC\n\ncompile options: '-I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_4828c557ac3c69073869ec78a9afe8bb39db32a5/.venv/lib/python3.7/site-packages/numpy/core/include -I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_4828c557ac3c69073869ec78a9afe8bb39db32a5/.venv/lib/python3.7/site-packages/numpy/core/include -I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_4828c557ac3c69073869ec78a9afe8bb39db32a5/.venv/include -I/home/gcpuser/.local/share/uv/python/cpython-3.7.9-linux-x86_64-gnu/include/python3.7m -c'\ncc: Orange/classification/_tree_scorers.c\ncc -pthread -shared -L/tools/deps/lib build/temp.linux-x86_64-3.7/Orange/classification/_tree_scorers.o -L/home/gcpuser/.local/share/uv/python/cpython-3.7.9-linux-x86_64-gnu/lib -lm -lpython3.7m -o Orange/classification/_tree_scorers.cpython-37m-x86_64-linux-gnu.so\nbuilding 'Orange.data._valuecount' extension\ncompiling C sources\nC compiler: cc -pthread -Wno-unused-result -Wsign-compare -Wunreachable-code -DNDEBUG -g -fwrapv -O3 -Wall -fPIC -I/tools/deps/include -I/tools/deps/include/ncursesw -fPIC\n\ncreating build/temp.linux-x86_64-3.7/Orange/data\ncompile options: '-I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_4828c557ac3c69073869ec78a9afe8bb39db32a5/.venv/lib/python3.7/site-packages/numpy/core/include -I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_4828c557ac3c69073869ec78a9afe8bb39db32a5/.venv/lib/python3.7/site-packages/numpy/core/include -I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_4828c557ac3c69073869ec78a9afe8bb39db32a5/.venv/include -I/home/gcpuser/.local/share/uv/python/cpython-3.7.9-linux-x86_64-gnu/include/python3.7m -c'\ncc: Orange/data/_valuecount.c\ncc -pthread -shared -L/tools/deps/lib build/temp.linux-x86_64-3.7/Orange/data/_valuecount.o -L/home/gcpuser/.local/share/uv/python/cpython-3.7.9-linux-x86_64-gnu/lib -lm -lpython3.7m -o Orange/data/_valuecount.cpython-37m-x86_64-linux-gnu.so\nbuilding 'Orange.data._contingency' extension\ncompiling C sources\nC compiler: cc -pthread -Wno-unused-result -Wsign-compare -Wunreachable-code -DNDEBUG -g -fwrapv -O3 -Wall -fPIC -I/tools/deps/include -I/tools/deps/include/ncursesw -fPIC\n\ncompile options: '-I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_4828c557ac3c69073869ec78a9afe8bb39db32a5/.venv/lib/python3.7/site-packages/numpy/core/include -I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_4828c557ac3c69073869ec78a9afe8bb39db32a5/.venv/lib/python3.7/site-packages/numpy/core/include -I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_4828c557ac3c69073869ec78a9afe8bb39db32a5/.venv/include -I/home/gcpuser/.local/share/uv/python/cpython-3.7.9-linux-x86_64-gnu/include/python3.7m -c'\ncc: Orange/data/_contingency.c\ncc -pthread -shared -L/tools/deps/lib build/temp.linux-x86_64-3.7/Orange/data/_contingency.o -L/home/gcpuser/.local/share/uv/python/cpython-3.7.9-linux-x86_64-gnu/lib -lm -lpython3.7m -o Orange/data/_contingency.cpython-37m-x86_64-linux-gnu.so\nbuilding 'Orange.data._io' extension\ncompiling C sources\nC compiler: cc -pthread -Wno-unused-result -Wsign-compare -Wunreachable-code -DNDEBUG -g -fwrapv -O3 -Wall -fPIC -I/tools/deps/include -I/tools/deps/include/ncursesw -fPIC\n\ncompile options: '-I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_4828c557ac3c69073869ec78a9afe8bb39db32a5/.venv/lib/python3.7/site-packages/numpy/core/include -I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_4828c557ac3c69073869ec78a9afe8bb39db32a5/.venv/lib/python3.7/site-packages/numpy/core/include -I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_4828c557ac3c69073869ec78a9afe8bb39db32a5/.venv/include -I/home/gcpuser/.local/share/uv/python/cpython-3.7.9-linux-x86_64-gnu/include/python3.7m -c'\ncc: Orange/data/_io.c\ncc -pthread -shared -L/tools/deps/lib build/temp.linux-x86_64-3.7/Orange/data/_io.o -L/home/gcpuser/.local/share/uv/python/cpython-3.7.9-linux-x86_64-gnu/lib -lm -lpython3.7m -o Orange/data/_io.cpython-37m-x86_64-linux-gnu.so\nbuilding 'Orange.data._variable' extension\ncompiling C sources\nC compiler: cc -pthread -Wno-unused-result -Wsign-compare -Wunreachable-code -DNDEBUG -g -fwrapv -O3 -Wall -fPIC -I/tools/deps/include -I/tools/deps/include/ncursesw -fPIC\n\ncompile options: '-I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_4828c557ac3c69073869ec78a9afe8bb39db32a5/.venv/lib/python3.7/site-packages/numpy/core/include -I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_4828c557ac3c69073869ec78a9afe8bb39db32a5/.venv/lib/python3.7/site-packages/numpy/core/include -I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_4828c557ac3c69073869ec78a9afe8bb39db32a5/.venv/include -I/home/gcpuser/.local/share/uv/python/cpython-3.7.9-linux-x86_64-gnu/include/python3.7m -c'\ncc: Orange/data/_variable.c\ncc -pthread -shared -L/tools/deps/lib build/temp.linux-x86_64-3.7/Orange/data/_variable.o -L/home/gcpuser/.local/share/uv/python/cpython-3.7.9-linux-x86_64-gnu/lib -lm -lpython3.7m -o Orange/data/_variable.cpython-37m-x86_64-linux-gnu.so\nbuilding 'Orange.distance._distance' extension\ncompiling C sources\nC compiler: cc -pthread -Wno-unused-result -Wsign-compare -Wunreachable-code -DNDEBUG -g -fwrapv -O3 -Wall -fPIC -I/tools/deps/include -I/tools/deps/include/ncursesw -fPIC\n\ncreating build/temp.linux-x86_64-3.7/Orange/distance\ncompile options: '-I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_4828c557ac3c69073869ec78a9afe8bb39db32a5/.venv/lib/python3.7/site-packages/numpy/core/include -I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_4828c557ac3c69073869ec78a9afe8bb39db32a5/.venv/lib/python3.7/site-packages/numpy/core/include -I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_4828c557ac3c69073869ec78a9afe8bb39db32a5/.venv/include -I/home/gcpuser/.local/share/uv/python/cpython-3.7.9-linux-x86_64-gnu/include/python3.7m -c'\ncc: Orange/distance/_distance.c\ncc -pthread -shared -L/tools/deps/lib build/temp.linux-x86_64-3.7/Orange/distance/_distance.o -L/home/gcpuser/.local/share/uv/python/cpython-3.7.9-linux-x86_64-gnu/lib -lm -lpython3.7m -o Orange/distance/_distance.cpython-37m-x86_64-linux-gnu.so\nbuilding 'Orange.preprocess._discretize' extension\ncompiling C sources\nC compiler: cc -pthread -Wno-unused-result -Wsign-compare -Wunreachable-code -DNDEBUG -g -fwrapv -O3 -Wall -fPIC -I/tools/deps/include -I/tools/deps/include/ncursesw -fPIC\n\ncreating build/temp.linux-x86_64-3.7/Orange/preprocess\ncompile options: '-I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_4828c557ac3c69073869ec78a9afe8bb39db32a5/.venv/lib/python3.7/site-packages/numpy/core/include -I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_4828c557ac3c69073869ec78a9afe8bb39db32a5/.venv/lib/python3.7/site-packages/numpy/core/include -I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_4828c557ac3c69073869ec78a9afe8bb39db32a5/.venv/include -I/home/gcpuser/.local/share/uv/python/cpython-3.7.9-linux-x86_64-gnu/include/python3.7m -c'\ncc: Orange/preprocess/_discretize.c\ncc -pthread -shared -L/tools/deps/lib build/temp.linux-x86_64-3.7/Orange/preprocess/_discretize.o -L/home/gcpuser/.local/share/uv/python/cpython-3.7.9-linux-x86_64-gnu/lib -lm -lpython3.7m -o Orange/preprocess/_discretize.cpython-37m-x86_64-linux-gnu.so\nbuilding 'Orange.preprocess._relieff' extension\ncompiling C++ sources\nC compiler: c++ -pthread -Wno-unused-result -Wsign-compare -Wunreachable-code -DNDEBUG -g -fwrapv -O3 -Wall -fPIC -I/tools/deps/include -I/tools/deps/include/ncursesw -fPIC\n\ncompile options: '-I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_4828c557ac3c69073869ec78a9afe8bb39db32a5/.venv/lib/python3.7/site-packages/numpy/core/include -I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_4828c557ac3c69073869ec78a9afe8bb39db32a5/.venv/lib/python3.7/site-packages/numpy/core/include -I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_4828c557ac3c69073869ec78a9afe8bb39db32a5/.venv/include -I/home/gcpuser/.local/share/uv/python/cpython-3.7.9-linux-x86_64-gnu/include/python3.7m -c'\nc++: Orange/preprocess/_relieff.cpp\nc++ -pthread -shared -L/tools/deps/lib build/temp.linux-x86_64-3.7/Orange/preprocess/_relieff.o -L/home/gcpuser/.local/share/uv/python/cpython-3.7.9-linux-x86_64-gnu/lib -lm -lpython3.7m -o Orange/preprocess/_relieff.cpython-37m-x86_64-linux-gnu.so\nbuilding 'Orange.widgets.utils._grid_density' extension\ncompiling C++ sources\nC compiler: c++ -pthread -Wno-unused-result -Wsign-compare -Wunreachable-code -DNDEBUG -g -fwrapv -O3 -Wall -fPIC -I/tools/deps/include -I/tools/deps/include/ncursesw -fPIC\n\ncreating build/temp.linux-x86_64-3.7/Orange/widgets\ncreating build/temp.linux-x86_64-3.7/Orange/widgets/utils\ncompile options: '-I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_4828c557ac3c69073869ec78a9afe8bb39db32a5/.venv/lib/python3.7/site-packages/numpy/core/include -I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_4828c557ac3c69073869ec78a9afe8bb39db32a5/.venv/include -I/home/gcpuser/.local/share/uv/python/cpython-3.7.9-linux-x86_64-gnu/include/python3.7m -c'\nc++: Orange/widgets/utils/_grid_density.cpp\nc++ -pthread -shared -L/tools/deps/lib build/temp.linux-x86_64-3.7/Orange/widgets/utils/_grid_density.o -L/home/gcpuser/.local/share/uv/python/cpython-3.7.9-linux-x86_64-gnu/lib -lm -lpython3.7m -o Orange/widgets/utils/_grid_density.cpython-37m-x86_64-linux-gnu.so\nWarning: 'keywords' should be a list, got type 'tuple'\nWarning: 'classifiers' should be a list, got type 'tuple'\nWarning: 'keywords' should be a list, got type 'tuple'\nWarning: 'classifiers' should be a list, got type 'tuple'\nrunning develop\nrunning build_scripts\nrunning egg_info\nrunning build_src\nbuild_src\nbuilding extension \"Orange.classification._simple_tree\" sources\nbuilding extension \"Orange.classification._tree_scorers\" sources\nbuilding extension \"Orange.data._valuecount\" sources\nbuilding extension \"Orange.data._contingency\" sources\nbuilding extension \"Orange.data._io\" sources\nbuilding extension \"Orange.data._variable\" sources\nbuilding extension \"Orange.distance._distance\" sources\nbuilding extension \"Orange.preprocess._discretize\" sources\nbuilding extension \"Orange.preprocess._relieff\" sources\nbuilding extension \"Orange.widgets.utils._grid_density\" sources\nbuild_src: building npy-pkg config files\ncreating Orange3.egg-info\nwriting Orange3.egg-info/PKG-INFO\nwriting dependency_links to Orange3.egg-info/dependency_links.txt\nwriting entry points to Orange3.egg-info/entry_points.txt\nwriting requirements to Orange3.egg-info/requires.txt\nwriting top-level names to Orange3.egg-info/top_level.txt\nwriting manifest file 'Orange3.egg-info/SOURCES.txt'\nreading manifest file 'Orange3.egg-info/SOURCES.txt'\nreading manifest template 'MANIFEST.in'\nwarning: no files found matching 'README*' under directory 'Orange'\nwarning: no files found matching 'LICENSE' under directory 'Orange'\nwarning: no files found matching '*.basket' under directory 'Orange/datasets'\nwarning: no files found matching '*.html' under directory 'Orange/canvas'\nwarning: no files found matching '*.css' under directory 'Orange/widgets'\nwarning: no files found matching 'COPYING'\nadding license file 'LICENSE'\nwriting manifest file 'Orange3.egg-info/SOURCES.txt'\nrunning build_ext\ncustomize UnixCCompiler\nC compiler: cc -pthread -Wno-unused-result -Wsign-compare -Wunreachable-code -DNDEBUG -g -fwrapv -O3 -Wall -fPIC -I/tools/deps/include -I/tools/deps/include/ncursesw -fPIC\n\ncreating /tmp/tmpt8w84k02/tmp\ncreating /tmp/tmpt8w84k02/tmp/tmpt8w84k02\ncompile options: '-MMD -MF /tmp/tmpt8w84k02/file.c.d -c'\ncc: /tmp/tmpt8w84k02/file.c\ncustomize UnixCCompiler using build_ext\ncustomize UnixCCompiler\nC compiler: cc -pthread -Wno-unused-result -Wsign-compare -Wunreachable-code -DNDEBUG -g -fwrapv -O3 -Wall -fPIC -I/tools/deps/include -I/tools/deps/include/ncursesw -fPIC\n\ncreating /tmp/tmp8jxiirsn/tmp\ncreating /tmp/tmp8jxiirsn/tmp/tmp8jxiirsn\ncompile options: '-MMD -MF /tmp/tmp8jxiirsn/file.c.d -c'\ncc: /tmp/tmp8jxiirsn/file.c\ncustomize UnixCCompiler using build_ext\nCreating /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_4828c557ac3c69073869ec78a9afe8bb39db32a5/.venv/lib/python3.7/site-packages/Orange3.egg-link (link to .)\nAdding Orange3 3.21.0.dev0+4828c55 to easy-install.pth file\nInstalling orange-canvas script to /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_4828c557ac3c69073869ec78a9afe8bb39db32a5/.venv/bin\n\nInstalled /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_4828c557ac3c69073869ec78a9afe8bb39db32a5\nProcessing dependencies for Orange3==3.21.0.dev0+4828c55\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_4828c557ac3c69073869ec78a9afe8bb39db32a5/.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_4828c557ac3c69073869ec78a9afe8bb39db32a5/.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_4828c557ac3c69073869ec78a9afe8bb39db32a5/.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_4828c557ac3c69073869ec78a9afe8bb39db32a5/.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_4828c557ac3c69073869ec78a9afe8bb39db32a5/.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_4828c557ac3c69073869ec78a9afe8bb39db32a5/.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_4828c557ac3c69073869ec78a9afe8bb39db32a5/.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_4828c557ac3c69073869ec78a9afe8bb39db32a5/.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_4828c557ac3c69073869ec78a9afe8bb39db32a5/.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_4828c557ac3c69073869ec78a9afe8bb39db32a5/.venv/bin\nInstalling pip3 script to /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_4828c557ac3c69073869ec78a9afe8bb39db32a5/.venv/bin\nInstalling pip3.10 script to /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_4828c557ac3c69073869ec78a9afe8bb39db32a5/.venv/bin\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_4828c557ac3c69073869ec78a9afe8bb39db32a5/.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_4828c557ac3c69073869ec78a9afe8bb39db32a5/.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_4828c557ac3c69073869ec78a9afe8bb39db32a5/.venv/bin\nInstalling f2py3 script to /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_4828c557ac3c69073869ec78a9afe8bb39db32a5/.venv/bin\nInstalling f2py3.7 script to /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_4828c557ac3c69073869ec78a9afe8bb39db32a5/.venv/bin\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_4828c557ac3c69073869ec78a9afe8bb39db32a5/.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_4828c557ac3c69073869ec78a9afe8bb39db32a5/.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_4828c557ac3c69073869ec78a9afe8bb39db32a5/.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_4828c557ac3c69073869ec78a9afe8bb39db32a5/.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_4828c557ac3c69073869ec78a9afe8bb39db32a5/.venv/bin\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_4828c557ac3c69073869ec78a9afe8bb39db32a5/.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_4828c557ac3c69073869ec78a9afe8bb39db32a5/.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_4828c557ac3c69073869ec78a9afe8bb39db32a5/.venv/bin\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_4828c557ac3c69073869ec78a9afe8bb39db32a5/.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_4828c557ac3c69073869ec78a9afe8bb39db32a5/.venv/bin\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_4828c557ac3c69073869ec78a9afe8bb39db32a5/.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_4828c557ac3c69073869ec78a9afe8bb39db32a5/.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_4828c557ac3c69073869ec78a9afe8bb39db32a5/.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_4828c557ac3c69073869ec78a9afe8bb39db32a5/.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_4828c557ac3c69073869ec78a9afe8bb39db32a5/.venv/bin\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_4828c557ac3c69073869ec78a9afe8bb39db32a5/.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_4828c557ac3c69073869ec78a9afe8bb39db32a5/.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_4828c557ac3c69073869ec78a9afe8bb39db32a5/.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_4828c557ac3c69073869ec78a9afe8bb39db32a5/.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_4828c557ac3c69073869ec78a9afe8bb39db32a5/.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_4828c557ac3c69073869ec78a9afe8bb39db32a5/.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_4828c557ac3c69073869ec78a9afe8bb39db32a5/.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_4828c557ac3c69073869ec78a9afe8bb39db32a5/.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_4828c557ac3c69073869ec78a9afe8bb39db32a5/.venv/bin\nInstalling pyftmerge script to /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_4828c557ac3c69073869ec78a9afe8bb39db32a5/.venv/bin\nInstalling pyftsubset script to /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_4828c557ac3c69073869ec78a9afe8bb39db32a5/.venv/bin\nInstalling ttx script to /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_4828c557ac3c69073869ec78a9afe8bb39db32a5/.venv/bin\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_4828c557ac3c69073869ec78a9afe8bb39db32a5/.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_4828c557ac3c69073869ec78a9afe8bb39db32a5/.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_4828c557ac3c69073869ec78a9afe8bb39db32a5/.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_4828c557ac3c69073869ec78a9afe8bb39db32a5/.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_4828c557ac3c69073869ec78a9afe8bb39db32a5/.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_4828c557ac3c69073869ec78a9afe8bb39db32a5/.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_4828c557ac3c69073869ec78a9afe8bb39db32a5/.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_4828c557ac3c69073869ec78a9afe8bb39db32a5/.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_4828c557ac3c69073869ec78a9afe8bb39db32a5/.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_4828c557ac3c69073869ec78a9afe8bb39db32a5/.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_4828c557ac3c69073869ec78a9afe8bb39db32a5/.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_4828c557ac3c69073869ec78a9afe8bb39db32a5/.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_4828c557ac3c69073869ec78a9afe8bb39db32a5/.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_4828c557ac3c69073869ec78a9afe8bb39db32a5/.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_4828c557ac3c69073869ec78a9afe8bb39db32a5/.venv/lib/python3.7/site-packages\nFinished processing dependencies for Orange3==3.21.0.dev0+4828c55\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 60ms\nPrepared 18 packages in 1ms\nInstalled 18 packages in 485ms\n + cython==0.29.37\n + exceptiongroup==1.2.2\n + importlib-metadata==6.7.0\n + iniconfig==2.0.0\n + numpy==1.17.5\n + packaging==24.0\n + pluggy==1.2.0\n + pyqt5==5.15.10\n + pyqt5-qt5==5.15.16\n + pyqt5-sip==12.13.0\n + pyqtwebengine==5.15.6\n + pyqtwebengine-qt5==5.15.16\n + pytest==7.4.4\n + setuptools==59.8.0\n + tomli==2.0.1\n + typing-extensions==4.7.1\n + wheel==0.42.0\n + zipp==3.15.0\nResolved 33 packages in 152ms\nInstalled 28 packages in 494ms\n + bottleneck==1.4.0\n + certifi==2024.12.14\n + cffi==1.15.1\n + chardet==5.2.0\n + charset-normalizer==3.4.1\n + cryptography==44.0.0\n + idna==3.10\n + importlib-resources==5.12.0\n + jaraco-classes==3.2.3\n + jeepney==0.8.0\n + joblib==1.3.2\n + keyring==24.1.1\n + keyrings-alt==4.2.0\n + more-itertools==9.1.0\n + networkx==2.6.3\n + opentsne==1.0.1\n + pip==24.0\n + pycparser==2.21\n + python-louvain==0.16\n + requests==2.31.0\n + scikit-learn==1.0.2\n + scipy==1.7.3\n + secretstorage==3.3.3\n + serverfiles==0.3.1\n + threadpoolctl==3.1.0\n + urllib3==2.0.7\n + xlrd==2.0.1\n + xlsxwriter==3.2.0\nResolved 14 packages in 55ms\nInstalled 11 packages in 25ms\n + anyqt==0.2.0\n + cycler==0.11.0\n + docutils==0.20.1\n + fonttools==4.38.0\n + kiwisolver==1.4.5\n + matplotlib==3.5.3\n + pillow==9.5.0\n + pyparsing==3.1.4\n + pyqtgraph==0.12.4\n + python-dateutil==2.9.0.post0\n + six==1.17.0\nResolved 2 packages in 5ms\nInstalled 2 packages in 29ms\n + psycopg2==2.9.9\n + pymssql==2.3.2\nResolved 5 packages in 20ms\nInstalled 2 packages in 104ms\n + pandas==1.3.5\n + pytz==2024.2\nAudited 2 packages in 1ms\nOrange/classification/_simple_tree.c: In function ‘gain_ratio_c’:\nOrange/classification/_simple_tree.c:63:9: warning: implicit declaration of function ‘qsort_r’; did you mean ‘qsort’? [-Wimplicit-function-declaration]\n   63 |         qsort_r(base, nel, size, compar, thunk)\n      |         ^~~~~~~\nOrange/classification/_simple_tree.c:147:9: note: in expansion of macro ‘QSORT_R_FUNC’\n  147 |         QSORT_R_FUNC(examples, size, sizeof(struct Example), (void*) &compar_attr, compar_examples);\n      |         ^~~~~~~~~~~~\nIn file included from /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_4828c557ac3c69073869ec78a9afe8bb39db32a5/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/ndarraytypes.h:1830,\n                 from /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_4828c557ac3c69073869ec78a9afe8bb39db32a5/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/ndarrayobject.h:12,\n                 from /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_4828c557ac3c69073869ec78a9afe8bb39db32a5/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/arrayobject.h:4,\n                 from Orange/classification/_tree_scorers.c:567:\n/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_4828c557ac3c69073869ec78a9afe8bb39db32a5/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/npy_1_7_deprecated_api.h:17:2: warning: #warning \"Using deprecated NumPy API, disable it with \" \"#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION\" [-Wcpp]\n   17 | #warning \"Using deprecated NumPy API, disable it with \" \\\n      |  ^~~~~~~\nOrange/classification/_tree_scorers.c: In function ‘__pyx_pf_6Orange_14classification_13_tree_scorers_2find_threshold_entropy’:\nOrange/classification/_tree_scorers.c:3115:27: warning: comparison of integer expressions of different signedness: ‘unsigned int’ and ‘int’ [-Wsign-compare]\n 3115 |   __pyx_t_7 = ((__pyx_v_N <= __pyx_v_min_leaf) != 0);\n      |                           ^~\nOrange/classification/_tree_scorers.c: In function ‘__pyx_pf_6Orange_14classification_13_tree_scorers_6find_threshold_MSE’:\nOrange/classification/_tree_scorers.c:4619:27: warning: comparison of integer expressions of different signedness: ‘unsigned int’ and ‘int’ [-Wsign-compare]\n 4619 |   __pyx_t_1 = ((__pyx_v_N <= __pyx_v_min_leaf) != 0);\n      |                           ^~\nOrange/classification/_tree_scorers.c: In function ‘__pyx_pf_6Orange_14classification_13_tree_scorers_8find_binarization_MSE’:\nOrange/classification/_tree_scorers.c:5396:43: warning: comparison of integer expressions of different signedness: ‘unsigned int’ and ‘int’ [-Wsign-compare]\n 5396 |           for (__pyx_t_22 = 0; __pyx_t_22 < __pyx_t_21; __pyx_t_22+=1) {\n      |                                           ^\nOrange/classification/_tree_scorers.c:5517:39: warning: comparison of integer expressions of different signedness: ‘unsigned int’ and ‘int’ [-Wsign-compare]\n 5517 |           __pyx_t_27 = ((__pyx_v_left >= __pyx_v_min_leaf) != 0);\n      |                                       ^~\nOrange/classification/_tree_scorers.c:5523:53: warning: comparison of integer expressions of different signedness: ‘unsigned int’ and ‘int’ [-Wsign-compare]\n 5523 |           __pyx_t_27 = (((__pyx_v_N - __pyx_v_left) >= __pyx_v_min_leaf) != 0);\n      |                                                     ^~\nOrange/classification/_tree_scorers.c: In function ‘__pyx_pf_6Orange_14classification_13_tree_scorers_14compute_predictions_csr’:\nOrange/classification/_tree_scorers.c:7051:41: warning: comparison of integer expressions of different signedness: ‘unsigned int’ and ‘int’ [-Wsign-compare]\n 7051 |         for (__pyx_t_11 = 0; __pyx_t_11 < __pyx_t_10; __pyx_t_11+=1) {\n      |                                         ^\nOrange/classification/_tree_scorers.c: In function ‘__pyx_pf_6Orange_14classification_13_tree_scorers_16compute_predictions_csc’:\nOrange/classification/_tree_scorers.c:7741:41: warning: comparison of integer expressions of different signedness: ‘unsigned int’ and ‘int’ [-Wsign-compare]\n 7741 |         for (__pyx_t_11 = 0; __pyx_t_11 < __pyx_t_10; __pyx_t_11+=1) {\n      |                                         ^\nOrange/classification/_tree_scorers.c:7801:143: warning: comparison of integer expressions of different signedness: ‘__pyx_t_5numpy_int32_t’ {aka ‘int’} and ‘unsigned int’ [-Wsign-compare]\n 7801 |               __pyx_t_17 = (((*((__pyx_t_5numpy_int32_t *) ( /* dim=0 */ (__pyx_v_indices.data + __pyx_t_18 * __pyx_v_indices.strides[0]) ))) != __pyx_v_i) != 0);\n      |                                                                                                                                               ^~\nIn file included from /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_4828c557ac3c69073869ec78a9afe8bb39db32a5/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/ndarraytypes.h:1830,\n                 from /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_4828c557ac3c69073869ec78a9afe8bb39db32a5/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/ndarrayobject.h:12,\n                 from /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_4828c557ac3c69073869ec78a9afe8bb39db32a5/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/arrayobject.h:4,\n                 from Orange/data/_valuecount.c:567:\n/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_4828c557ac3c69073869ec78a9afe8bb39db32a5/.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_4828c557ac3c69073869ec78a9afe8bb39db32a5/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/ndarraytypes.h:1830,\n                 from /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_4828c557ac3c69073869ec78a9afe8bb39db32a5/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/ndarrayobject.h:12,\n                 from /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_4828c557ac3c69073869ec78a9afe8bb39db32a5/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/arrayobject.h:4,\n                 from Orange/data/_contingency.c:567:\n/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_4828c557ac3c69073869ec78a9afe8bb39db32a5/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/npy_1_7_deprecated_api.h:17:2: warning: #warning \"Using deprecated NumPy API, disable it with \" \"#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION\" [-Wcpp]\n   17 | #warning \"Using deprecated NumPy API, disable it with \" \\\n      |  ^~~~~~~\nOrange/data/_io.c: In function ‘__pyx_pf_6Orange_4data_3_io_sparse_read_float.constprop’:\nOrange/data/_io.c:3881:24: warning: ‘__pyx_v_decs’ may be used uninitialized in this function [-Wmaybe-uninitialized]\n 3881 |           __pyx_v_decs = (__pyx_v_decs / 10.0);\n      |           ~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~\nOrange/data/_io.c:4070:24: warning: ‘__pyx_v_value’ may be used uninitialized in this function [-Wmaybe-uninitialized]\n 4070 |           __pyx_t_10 = PyFloat_FromDouble(__pyx_v_value); if (unlikely(!__pyx_t_10)) __PYX_ERR(0, 221, __pyx_L5_error)\n      |                        ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\nOrange/data/_io.c:480:40: warning: ‘__pyx_v_attr_index’ may be used uninitialized in this function [-Wmaybe-uninitialized]\n  480 |   #define PyInt_FromLong               PyLong_FromLong\n      |                                        ^~~~~~~~~~~~~~~\nOrange/data/_io.c:1301:7: note: ‘__pyx_v_attr_index’ was declared here\n 1301 |   int __pyx_v_attr_index;\n      |       ^~~~~~~~~~~~~~~~~~\nOrange/data/_io.c:2935:25: warning: ‘__pyx_v_atomp’ may be used uninitialized in this function [-Wmaybe-uninitialized]\n 2935 |           __pyx_v_atomp = (__pyx_v_atomp + 1);\n      |           ~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~\nIn file included from /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_4828c557ac3c69073869ec78a9afe8bb39db32a5/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/ndarraytypes.h:1830,\n                 from /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_4828c557ac3c69073869ec78a9afe8bb39db32a5/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/ndarrayobject.h:12,\n                 from /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_4828c557ac3c69073869ec78a9afe8bb39db32a5/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/arrayobject.h:4,\n                 from Orange/distance/_distance.c:567:\n/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_4828c557ac3c69073869ec78a9afe8bb39db32a5/.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_4828c557ac3c69073869ec78a9afe8bb39db32a5/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/ndarraytypes.h:1830,\n                 from /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_4828c557ac3c69073869ec78a9afe8bb39db32a5/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/ndarrayobject.h:12,\n                 from /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_4828c557ac3c69073869ec78a9afe8bb39db32a5/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/arrayobject.h:4,\n                 from Orange/preprocess/_discretize.c:567:\n/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_4828c557ac3c69073869ec78a9afe8bb39db32a5/.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_4828c557ac3c69073869ec78a9afe8bb39db32a5/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/ndarraytypes.h:1830,\n                 from /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_4828c557ac3c69073869ec78a9afe8bb39db32a5/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/ndarrayobject.h:12,\n                 from /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_4828c557ac3c69073869ec78a9afe8bb39db32a5/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/arrayobject.h:4,\n                 from Orange/preprocess/_relieff.cpp:581:\n/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_4828c557ac3c69073869ec78a9afe8bb39db32a5/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/npy_1_7_deprecated_api.h:17:2: warning: #warning \"Using deprecated NumPy API, disable it with \" \"#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION\" [-Wcpp]\n   17 | #warning \"Using deprecated NumPy API, disable it with \" \\\n      |  ^~~~~~~\n/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_4828c557ac3c69073869ec78a9afe8bb39db32a5/.venv/lib/python3.7/site-packages/setuptools/command/install.py:37: SetuptoolsDeprecationWarning: setup.py install is deprecated. Use build and pip and other standards-based tools.\n  setuptools.SetuptoolsDeprecationWarning,\n/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_4828c557ac3c69073869ec78a9afe8bb39db32a5/.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_4828c557ac3c69073869ec78a9afe8bb39db32a5/.venv/lib/python3.7/site-packages/setuptools/command/install.py:37: SetuptoolsDeprecationWarning: setup.py install is deprecated. Use build and pip and other standards-based tools.\n  setuptools.SetuptoolsDeprecationWarning,\n/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_4828c557ac3c69073869ec78a9afe8bb39db32a5/.venv/lib/python3.7/site-packages/setuptools/command/egg_info.py:628: SetuptoolsDeprecationWarning: Custom 'build_py' does not implement 'get_data_files_without_manifest'.\nPlease extend command classes from setuptools instead of distutils.\n  SetuptoolsDeprecationWarning\n",
    "new_commit_res_code": 0,
    "new_commit_res_stdout": "============================= test session starts ==============================\nplatform linux -- Python 3.7.9, pytest-7.4.4, pluggy-1.2.0\nrootdir: /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_4828c557ac3c69073869ec78a9afe8bb39db32a5\ncollected 18 items\n\nr2e_tests/test_1.py ..................                                   [100%]\n\n==================================== PASSES ====================================\n=========================== short test summary info ============================\nPASSED r2e_tests/test_1.py::TestDomainContextHandler::test_backward_compatible_params\nPASSED r2e_tests/test_1.py::TestDomainContextHandler::test_clone_context\nPASSED r2e_tests/test_1.py::TestDomainContextHandler::test_decode_list_setting\nPASSED r2e_tests/test_1.py::TestDomainContextHandler::test_decode_setting\nPASSED r2e_tests/test_1.py::TestDomainContextHandler::test_deprecated_str_as_var\nPASSED r2e_tests/test_1.py::TestDomainContextHandler::test_encode_domain_with_match_all\nPASSED r2e_tests/test_1.py::TestDomainContextHandler::test_encode_domain_with_match_class\nPASSED r2e_tests/test_1.py::TestDomainContextHandler::test_encode_domain_with_match_none\nPASSED r2e_tests/test_1.py::TestDomainContextHandler::test_encode_list_settings\nPASSED r2e_tests/test_1.py::TestDomainContextHandler::test_encode_setting\nPASSED r2e_tests/test_1.py::TestDomainContextHandler::test_filter_value\nPASSED r2e_tests/test_1.py::TestDomainContextHandler::test_match_returns_1_if_everything_matches\nPASSED r2e_tests/test_1.py::TestDomainContextHandler::test_match_returns_2_on_perfect_match\nPASSED r2e_tests/test_1.py::TestDomainContextHandler::test_match_returns_point_1_when_nothing_to_match\nPASSED r2e_tests/test_1.py::TestDomainContextHandler::test_match_returns_zero_on_incompatible_context\nPASSED r2e_tests/test_1.py::TestDomainContextHandler::test_open_context\nPASSED r2e_tests/test_1.py::TestDomainContextHandler::test_open_context_with_imperfect_match\nPASSED r2e_tests/test_1.py::TestDomainContextHandler::test_open_context_with_no_match\n============================== 18 passed in 0.94s ==============================\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_4828c557ac3c69073869ec78a9afe8bb39db32a5\ncollected 18 items\n\nr2e_tests/test_1.py ....F.............                                   [100%]\n\n=================================== FAILURES ===================================\n_____________ TestDomainContextHandler.test_deprecated_str_as_var ______________\n\nself = <r2e_tests.test_1.TestDomainContextHandler testMethod=test_deprecated_str_as_var>\n\n    def test_deprecated_str_as_var(self):\n        if LooseVersion(Orange.__version__) >= LooseVersion(\"3.26\"):\n            # pragma: no cover\n            self.fail(\"Remove support for variables stored as string settings \"\n                      \"and this test.\")\n    \n        context = Mock()\n        context.attributes = {\"foo\": 2}\n        context.metas = {}\n        setting = ContextSetting(\"\")\n        setting.name = \"setting_name\"\n        with warnings.catch_warnings(record=True) as w:\n            warnings.simplefilter(\"always\")\n>           DomainContextHandler.encode_setting(context, setting, \"foo\")\nE           TypeError: encode_setting() missing 1 required positional argument: 'value'\n\nr2e_tests/test_1.py:298: TypeError\n==================================== PASSES ====================================\n=========================== short test summary info ============================\nPASSED r2e_tests/test_1.py::TestDomainContextHandler::test_backward_compatible_params\nPASSED r2e_tests/test_1.py::TestDomainContextHandler::test_clone_context\nPASSED r2e_tests/test_1.py::TestDomainContextHandler::test_decode_list_setting\nPASSED r2e_tests/test_1.py::TestDomainContextHandler::test_decode_setting\nPASSED r2e_tests/test_1.py::TestDomainContextHandler::test_encode_domain_with_match_all\nPASSED r2e_tests/test_1.py::TestDomainContextHandler::test_encode_domain_with_match_class\nPASSED r2e_tests/test_1.py::TestDomainContextHandler::test_encode_domain_with_match_none\nPASSED r2e_tests/test_1.py::TestDomainContextHandler::test_encode_list_settings\nPASSED r2e_tests/test_1.py::TestDomainContextHandler::test_encode_setting\nPASSED r2e_tests/test_1.py::TestDomainContextHandler::test_filter_value\nPASSED r2e_tests/test_1.py::TestDomainContextHandler::test_match_returns_1_if_everything_matches\nPASSED r2e_tests/test_1.py::TestDomainContextHandler::test_match_returns_2_on_perfect_match\nPASSED r2e_tests/test_1.py::TestDomainContextHandler::test_match_returns_point_1_when_nothing_to_match\nPASSED r2e_tests/test_1.py::TestDomainContextHandler::test_match_returns_zero_on_incompatible_context\nPASSED r2e_tests/test_1.py::TestDomainContextHandler::test_open_context\nPASSED r2e_tests/test_1.py::TestDomainContextHandler::test_open_context_with_imperfect_match\nPASSED r2e_tests/test_1.py::TestDomainContextHandler::test_open_context_with_no_match\nFAILED r2e_tests/test_1.py::TestDomainContextHandler::test_deprecated_str_as_var\n========================= 1 failed, 17 passed in 1.12s =========================\n",
    "old_commit_res_stderr": ""
}
Orange/widgets/settings.py Orange/widgets/tests/test_domain_context_handler.py
We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
[ISSUE]
**Title:** `encode_setting` Raises TypeError When Handling Deprecated String Variable Settings

**Description:**
When attempting to encode settings that use variables stored as strings, the `encode_setting` method raises a `TypeError` due to a missing required argument. This issue prevents the proper handling of deprecated string-based variable settings and disrupts the encoding process.

**Example Code:**
```python
from unittest.mock import Mock
from Orange.widgets.settings import DomainContextHandler, ContextSetting

context = Mock()
context.attributes = {"foo": 2}
context.metas = {}
setting = ContextSetting("")
setting.name = "setting_name"

DomainContextHandler.encode_setting(context, setting, "foo")
```

**Expected Behavior:**
Using string-based variable settings should trigger a deprecation warning and allow the settings to be encoded correctly without errors.

**Actual Behavior:**
Executing the encoding process raises the following error:
```
TypeError: encode_setting() missing 1 required positional argument: 'value'
```
This error occurs because the `encode_setting` method is not receiving all necessary arguments, preventing the encoding of deprecated string variable settings.

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

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

--- BEGIN FILE ---
```
### Orange/widgets/settings.py
"""Widget Settings and Settings Handlers

Settings are used to declare widget attributes that persist through sessions.
When widget is removed or saved to a schema file, its settings are packed,
serialized and stored. When a new widget is created, values of attributes
marked as settings are read from disk. When schema is loaded, attribute values
are set to one stored in schema.

Each widget has its own SettingsHandler that takes care of serializing and
storing of settings and SettingProvider that is incharge of reading and
writing the setting values.

All widgets extending from OWWidget use SettingsHandler, unless they
declare otherwise. SettingsHandler ensures that setting attributes
are replaced with default (last used) setting values when the widget is
initialized and stored when the widget is removed.

Widgets with settings whose values depend on the widget inputs use
settings handlers based on ContextHandler. These handlers have two
additional methods, open_context and close_context.

open_context is called when widgets receives new data. It finds a suitable
context and sets the widget attributes to the values stored in context.
If no suitable context exists, a new one is created and values from widget
are copied to it.

close_context stores values that were last used on the widget to the context
so they can be used alter. It should be called before widget starts modifying
(initializing) the value of the setting attributes.
"""

import sys
import copy
import itertools
import os
import logging
import pickle
import pprint
import time
import warnings
from operator import itemgetter
from typing import Any

from Orange.data import Domain, Variable
from Orange.misc.environ import widget_settings_dir
from Orange.util import OrangeDeprecationWarning
from Orange.widgets.utils import vartype
from Orange.widgets.gui import OWComponent

log = logging.getLogger(__name__)

__all__ = ["Setting", "SettingsHandler", "SettingProvider",
           "ContextSetting", "ContextHandler",
           "DomainContextHandler", "PerfectDomainContextHandler",
           "ClassValuesContextHandler", "widget_settings_dir",
           "IncompatibleContext"]

_IMMUTABLES = (str, int, bytes, bool, float, tuple)

VERSION_KEY = "__version__"


class Setting:
    """Description of a setting.
    """

    # Settings are automatically persisted to disk
    packable = True

    # Setting is only persisted to schema (default value does not change)
    schema_only = False

    def __new__(cls, default, *args, **kwargs):
        """A misleading docstring for providing type hints for Settings

        :type: default: T
        :rtype: T
        """
        return super().__new__(cls)

    def __init__(self, default, **data):
        self.name = None  # Name gets set in widget's meta class
        self.default = default
        self.__dict__.update(data)

    def __str__(self):
        return '{0} "{1}"'.format(self.__class__.__name__, self.name)

    __repr__ = __str__

    def __getnewargs__(self):
        return (self.default, )


# Pylint ignores type annotations in assignments. For
#
#    x: int = Setting(0)
#
# it ignores `int` and assumes x is of type `Setting`. Annotations in
# comments ( # type: int) also don't work. The only way to annotate x is
#
#    x: int
#    x = Setting(0)
#
# but we don't want to clutter the code with extra lines of annotations. Hence
# we disable checking the type of `Setting` by confusing pylint with an extra
# definition that is never executed.
if 1 == 0:
    class Setting:  # pylint: disable=function-redefined
        pass


def _apply_setting(setting: Setting, instance: OWComponent, value: Any):
    """
    Set `setting` of widget `instance` to the given `value`, in place if
    possible.

    If old and new values are of the same type, and the type is either a list
    or has methods `clear` and `update`, setting is updated in place. Otherwise
    the function calls `setattr`.
    """
    target = getattr(instance, setting.name, None)
    if type(target) is type(value):
        if isinstance(value, list):
            target[:] = value
            return
        elif hasattr(value, "clear") and hasattr(value, "update"):
            target.clear()
            target.update(value)
            return
    setattr(instance, setting.name, value)


class SettingProvider:
    """A hierarchical structure keeping track of settings belonging to
    a class and child setting providers.

    At instantiation, it creates a dict of all Setting and SettingProvider
    members of the class. This dict is used to get/set values of settings
    from/to the instances of the class this provider belongs to.
    """

    def __init__(self, provider_class):
        """ Construct a new instance of SettingProvider.

        Traverse provider_class members and store all instances of
        Setting and SettingProvider.

        Parameters
        ----------
        provider_class : class
            class containing settings definitions
        """
        self.name = ""
        self.provider_class = provider_class
        self.providers = {}
        """:type: dict[str, SettingProvider]"""
        self.settings = {}
        """:type: dict[str, Setting]"""
        self.initialization_data = None

        for name in dir(provider_class):
            value = getattr(provider_class, name, None)
            if isinstance(value, Setting):
                value = copy.deepcopy(value)
                value.name = name
                self.settings[name] = value
            if isinstance(value, SettingProvider):
                value = copy.deepcopy(value)
                value.name = name
                self.providers[name] = value

    def initialize(self, instance, data=None):
        """Initialize instance settings to their default values.

        Mutable values are (shallow) copied before they are assigned to the
        widget. Immutable are used as-is.

        Parameters
        ----------
        instance : OWWidget
            widget instance to initialize
        data : Optional[dict]
            optional data used to override the defaults
            (used when settings are loaded from schema)
        """
        if data is None and self.initialization_data is not None:
            data = self.initialization_data

        self._initialize_settings(instance, data)
        self._initialize_providers(instance, data)

    def _initialize_settings(self, instance, data):
        if data is None:
            data = {}
        for name, setting in self.settings.items():
            value = data.get(name, setting.default)
            if isinstance(value, _IMMUTABLES):
                setattr(instance, name, value)
            else:
                setattr(instance, name, copy.copy(value))

    def _initialize_providers(self, instance, data):
        if not data:
            return

        for name, provider in self.providers.items():
            if name not in data:
                continue

            member = getattr(instance, name, None)
            if member is None or isinstance(member, SettingProvider):
                provider.store_initialization_data(data[name])
            else:
                provider.initialize(member, data[name])

    def store_initialization_data(self, initialization_data):
        """Store initialization data for later use.

        Used when settings handler is initialized, but member for this
        provider does not exists yet (because handler.initialize is called in
        __new__, but member will be created in __init__.

        Parameters
        ----------
        initialization_data : dict
            data to be used for initialization when the component is created
        """
        self.initialization_data = initialization_data

    @staticmethod
    def _default_packer(setting, instance):
        """A simple packet that yields setting name and value.

        Parameters
        ----------
        setting : Setting
        instance : OWWidget
        """
        if setting.packable:
            if hasattr(instance, setting.name):
                yield setting.name, getattr(instance, setting.name)
            else:
                warnings.warn("{0} is declared as setting on {1} "
                              "but not present on instance."
                              .format(setting.name, instance))

    def pack(self, instance, packer=None):
        """Pack instance settings in a name:value dict.

        Parameters
        ----------
        instance : OWWidget
            widget instance
        packer: callable (Setting, OWWidget) -> Generator[(str, object)]
            optional packing function
            it will be called with setting and instance parameters and
            should yield (name, value) pairs that will be added to the
            packed_settings.
        """
        if packer is None:
            packer = self._default_packer

        packed_settings = dict(itertools.chain(
            *(packer(setting, instance) for setting in self.settings.values())
        ))

        packed_settings.update({
            name: provider.pack(getattr(instance, name), packer)
            for name, provider in self.providers.items()
            if hasattr(instance, name)
        })
        return packed_settings

    def unpack(self, instance, data):
        """Restore settings from data to the instance.

        Parameters
        ----------
        instance : OWWidget
            instance to restore settings to
        data : dict
            packed data
        """
        for setting, _data, inst in self.traverse_settings(data, instance):
            if setting.name in _data and inst is not None:
                _apply_setting(setting, inst, _data[setting.name])

    def get_provider(self, provider_class):
        """Return provider for provider_class.

        If this provider matches, return it, otherwise pass
        the call to child providers.

        Parameters
        ----------
        provider_class : class
        """
        if issubclass(provider_class, self.provider_class):
            return self

        for subprovider in self.providers.values():
            provider = subprovider.get_provider(provider_class)
            if provider:
                return provider
        return None

    def traverse_settings(self, data=None, instance=None):
        """Generator of tuples (setting, data, instance) for each setting
        in this and child providers..

        Parameters
        ----------
        data : dict
            dictionary with setting values
        instance : OWWidget
            instance matching setting_provider
        """
        data = data if data is not None else {}

        for setting in self.settings.values():
            yield setting, data, instance

        for provider in self.providers.values():
            data_ = data.get(provider.name, {})
            instance_ = getattr(instance, provider.name, None)
            for setting, component_data, component_instance in \
                    provider.traverse_settings(data_, instance_):
                yield setting, component_data, component_instance


class SettingsHandler:
    """Reads widget setting files and passes them to appropriate providers."""

    def __init__(self):
        """Create a setting handler template.

        Used in class definition. Bound instance will be created
        when SettingsHandler.create is called.
        """
        self.widget_class = None
        self.provider = None
        """:type: SettingProvider"""
        self.defaults = {}
        self.known_settings = {}

    @staticmethod
    def create(widget_class, template=None):
        """Create a new settings handler based on the template and bind it to
        widget_class.

        Parameters
        ----------
        widget_class : class
        template : SettingsHandler
            SettingsHandler to copy setup from

        Returns
        -------
        SettingsHandler
        """

        if template is None:
            template = SettingsHandler()

        setting_handler = copy.copy(template)
        setting_handler.defaults = {}
        setting_handler.bind(widget_class)
        return setting_handler

    def bind(self, widget_class):
        """Bind settings handler instance to widget_class.

        Parameters
        ----------
        widget_class : class
        """
        self.widget_class = widget_class
        self.provider = SettingProvider(widget_class)
        self.known_settings = {}
        self.analyze_settings(self.provider, "")
        self.read_defaults()

    def analyze_settings(self, provider, prefix):
        """Traverse through all settings known to the provider
        and analyze each of them.

        Parameters
        ----------
        provider : SettingProvider
        prefix : str
            prefix the provider is registered to handle
        """
        for setting in provider.settings.values():
            self.analyze_setting(prefix, setting)

        for name, sub_provider in provider.providers.items():
            new_prefix = '{0}{1}.'.format(prefix or '', name)
            self.analyze_settings(sub_provider, new_prefix)

    def analyze_setting(self, prefix, setting):
        """Perform any initialization task related to setting.

        Parameters
        ----------
        prefix : str
        setting : Setting
        """
        self.known_settings[prefix + setting.name] = setting

    def read_defaults(self):
        """Read (global) defaults for this widget class from a file.
        Opens a file and calls :obj:`read_defaults_file`. Derived classes
        should overload the latter."""
        filename = self._get_settings_filename()
        if os.path.isfile(filename):
            settings_file = open(filename, "rb")
            try:
                self.read_defaults_file(settings_file)
            # Unpickling exceptions can be of any type
            # pylint: disable=broad-except
            except Exception as ex:
                warnings.warn("Could not read defaults for widget {0}\n"
                              "The following error occurred:\n\n{1}"
                              .format(self.widget_class, ex))
            finally:
                settings_file.close()

    def read_defaults_file(self, settings_file):
        """Read (global) defaults for this widget class from a file.

        Parameters
        ----------
        settings_file : file-like object
        """
        defaults = pickle.load(settings_file)
        self.defaults = {
            key: value
            for key, value in defaults.items()
            if not isinstance(value, Setting)
        }
        self._migrate_settings(self.defaults)

    def write_defaults(self):
        """Write (global) defaults for this widget class to a file.
        Opens a file and calls :obj:`write_defaults_file`. Derived classes
        should overload the latter."""
        filename = self._get_settings_filename()
        os.makedirs(os.path.dirname(filename), exist_ok=True)
        try:
            settings_file = open(filename, "wb")
            try:
                self.write_defaults_file(settings_file)
            except (EOFError, IOError, pickle.PicklingError) as ex:
                log.error("Could not write default settings for %s (%s).",
                          self.widget_class, type(ex).__name__)
                settings_file.close()
                os.remove(filename)
            else:
                settings_file.close()
        except PermissionError as ex:
            log.error("Could not write default settings for %s (%s).",
                      self.widget_class, type(ex).__name__)

    def write_defaults_file(self, settings_file):
        """Write defaults for this widget class to a file

        Parameters
        ----------
        settings_file : file-like object
        """
        defaults = dict(self.defaults)
        defaults[VERSION_KEY] = self.widget_class.settings_version
        pickle.dump(defaults, settings_file, -1)

    def _get_settings_filename(self):
        """Return the name of the file with default settings for the widget"""
        return os.path.join(widget_settings_dir(),
                            "{0.__module__}.{0.__qualname__}.pickle"
                            .format(self.widget_class))

    def initialize(self, instance, data=None):
        """
        Initialize widget's settings.

        Replace all instance settings with their default values.

        Parameters
        ----------
        instance : OWWidget
        data : dict or bytes that unpickle into a dict
            values used to override the defaults
        """
        provider = self._select_provider(instance)

        if isinstance(data, bytes):
            data = pickle.loads(data)
        self._migrate_settings(data)

        if provider is self.provider:
            data = self._add_defaults(data)

        provider.initialize(instance, data)

    def _migrate_settings(self, settings):
        """Ask widget to migrate settings to the latest version."""
        if settings:
            try:
                self.widget_class.migrate_settings(
                    settings, settings.pop(VERSION_KEY, 0))
            except Exception:  # pylint: disable=broad-except
                sys.excepthook(*sys.exc_info())
                settings.clear()

    def _select_provider(self, instance):
        provider = self.provider.get_provider(instance.__class__)
        if provider is None:
            message = "{0} has not been declared as setting provider in {1}. " \
                      "Settings will not be saved/loaded properly. Defaults will be used instead." \
                      .format(instance.__class__, self.widget_class)
            warnings.warn(message)
            provider = SettingProvider(instance.__class__)
        return provider

    def _add_defaults(self, data):
        if data is None:
            return self.defaults

        new_data = self.defaults.copy()
        new_data.update(data)
        return new_data

    def _prepare_defaults(self, widget):
        self.defaults = self.provider.pack(widget)
        for setting, data, _ in self.provider.traverse_settings(data=self.defaults):
            if setting.schema_only:
                data.pop(setting.name, None)

    def pack_data(self, widget):
        """
        Pack the settings for the given widget. This method is used when
        saving schema, so that when the schema is reloaded the widget is
        initialized with its proper data and not the class-based defaults.
        See :obj:`SettingsHandler.initialize` for detailed explanation of its
        use.

        Inherited classes add other data, in particular widget-specific
        local contexts.

        Parameters
        ----------
        widget : OWWidget
        """
        widget.settingsAboutToBePacked.emit()
        packed_settings = self.provider.pack(widget)
        packed_settings[VERSION_KEY] = self.widget_class.settings_version
        return packed_settings

    def update_defaults(self, widget):
        """
        Writes widget instance's settings to class defaults. Called when the
        widget is deleted.

        Parameters
        ----------
        widget : OWWidget
        """
        widget.settingsAboutToBePacked.emit()
        self._prepare_defaults(widget)
        self.write_defaults()

    def fast_save(self, widget, name, value):
        """Store the (changed) widget's setting immediately to the context.

        Parameters
        ----------
        widget : OWWidget
        name : str
        value : object

        """
        if name in self.known_settings:
            setting = self.known_settings[name]
            if not setting.schema_only:
                setting.default = value

    def reset_settings(self, instance):
        """Reset widget settings to defaults

        Parameters
        ----------
        instance : OWWidget
        """
        for setting, _, inst in self.provider.traverse_settings(instance=instance):
            if setting.packable:
                _apply_setting(setting, inst, setting.default)


class ContextSetting(Setting):
    """Description of a context dependent setting"""

    OPTIONAL = 0
    REQUIRED = 2

    # Context settings are not persisted, but are stored in context instead.
    packable = False

    # These flags are not general - they assume that the setting has to do
    # something with the attributes. Large majority does, so this greatly
    # simplifies the declaration of settings in widget at no (visible)
    # cost to those settings that don't need it
    def __init__(self, default, *, required=2,
                 exclude_attributes=False, exclude_metas=False, **data):
        super().__init__(default, **data)
        self.exclude_attributes = exclude_attributes
        self.exclude_metas = exclude_metas
        self.required = required


class Context:
    """Class for data thad defines context and
    values that should be applied to widget if given context
    is encountered."""
    def __init__(self, **argkw):
        self.time = time.time()
        self.values = {}
        self.__dict__.update(argkw)

    def __getstate__(self):
        state = dict(self.__dict__)
        for nc in getattr(self, "no_copy", []):
            if nc in state:
                del state[nc]
        return state


class ContextHandler(SettingsHandler):
    """Base class for setting handlers that can handle contexts.

    Classes deriving from it need to implement method `match`.
    """

    NO_MATCH = 0
    PERFECT_MATCH = 2

    MAX_SAVED_CONTEXTS = 50

    def __init__(self):
        super().__init__()
        self.global_contexts = []
        self.known_settings = {}

    def initialize(self, instance, data=None):
        """Initialize the widget: call the inherited initialization and
        add an attribute 'context_settings' to the widget. This method
        does not open a context."""
        instance.current_context = None
        super().initialize(instance, data)
        if data and "context_settings" in data:
            instance.context_settings = data["context_settings"]
            self._migrate_contexts(instance.context_settings)
        else:
            instance.context_settings = []

    def read_defaults_file(self, settings_file):
        """Call the inherited method, then read global context from the
           pickle."""
        super().read_defaults_file(settings_file)
        self.global_contexts = pickle.load(settings_file)
        self._migrate_contexts(self.global_contexts)

    def _migrate_contexts(self, contexts):
        i = 0
        while i < len(contexts):
            context = contexts[i]
            try:
                self.widget_class.migrate_context(
                    context, context.values.pop(VERSION_KEY, 0))
            except IncompatibleContext:
                del contexts[i]
            except Exception:  # pylint: disable=broad-except
                sys.excepthook(*sys.exc_info())
                del contexts[i]
            else:
                i += 1

    def write_defaults_file(self, settings_file):
        """Call the inherited method, then add global context to the pickle."""
        super().write_defaults_file(settings_file)

        def add_version(context):
            context = copy.copy(context)
            context.values = dict(context.values)
            context.values[VERSION_KEY] = self.widget_class.settings_version
            return context

        pickle.dump([add_version(context) for context in self.global_contexts],
                    settings_file, -1)

    def pack_data(self, widget):
        """Call the inherited method, then add local contexts to the dict."""
        data = super().pack_data(widget)
        self.settings_from_widget(widget)
        context_settings = [copy.copy(context) for context in
                            widget.context_settings]
        for context in context_settings:
            context.values[VERSION_KEY] = self.widget_class.settings_version
        data["context_settings"] = context_settings
        return data

    def update_defaults(self, widget):
        """
        Reimplemented from SettingsHandler

        Merge the widgets local contexts into the global contexts and persist
        the settings (including the contexts) to disk.
        """
        widget.settingsAboutToBePacked.emit()
        self.settings_from_widget(widget)
        globs = self.global_contexts
        assert widget.context_settings is not globs
        ids = {id(c) for c in globs}
        globs += (c for c in widget.context_settings if id(c) not in ids)
        globs.sort(key=lambda c: -c.time)
        del globs[self.MAX_SAVED_CONTEXTS:]

        # Save non-context settings. Do not call super().update_defaults, so that
        # settingsAboutToBePacked is emitted once.
        self._prepare_defaults(widget)
        self.write_defaults()

    def new_context(self, *args):
        """Create a new context."""
        return Context()

    def open_context(self, widget, *args):
        """Open a context by finding one and setting the widget data or
        creating one and fill with the data from the widget."""
        widget.current_context, is_new = \
            self.find_or_create_context(widget, *args)
        if is_new:
            try:
                self.settings_from_widget(widget, *args)
            except TypeError:
                warnings.warn("settings_from_widget in {} does not accept *args.\n"
                              "Support for this will be dropped in Orange 3.10"
                              .format(type(self)),
                              DeprecationWarning)
                self.settings_from_widget(widget)
        else:
            try:
                self.settings_to_widget(widget, *args)
            except TypeError:
                warnings.warn("settings_to_widget {} does not accept *args.\n"
                              "Support for this will be dropped in Orange 3.10"
                              .format(type(self)),
                              DeprecationWarning)
                self.settings_to_widget(widget)

    def match(self, context, *args):
        """Return the degree to which the stored `context` matches the data
        passed in additional arguments).
        When match returns 0 (ContextHandler.NO_MATCH), the context will not
        be used. When it returns ContextHandler.PERFECT_MATCH, the context
        is a perfect match so no further search is necessary.

        If imperfect matching is not desired, match should only
        return ContextHandler.NO_MATCH or ContextHandler.PERFECT_MATCH.

        Derived classes must overload this method.
        """
        raise NotImplementedError

    def find_or_create_context(self, widget, *args):
        """Find the best matching context or create a new one if nothing
        useful is found. The returned context is moved to or added to the top
        of the context list."""

        # First search the contexts that were already used in this widget instance
        best_context, best_score = self.find_context(widget.context_settings, args, move_up=True)
        # If the exact data was used, reuse the context
        if best_score == self.PERFECT_MATCH:
            return best_context, False

        # Otherwise check if a better match is available in global_contexts
        best_context, best_score = self.find_context(self.global_contexts, args,
                                                     best_score, best_context)
        if best_context:
            context = self.clone_context(best_context, *args)
        else:
            context = self.new_context(*args)
        # Store context in widget instance. It will be pushed to global_contexts
        # when (if) update defaults is called.
        self.add_context(widget.context_settings, context)
        return context, best_context is None

    def find_context(self, known_contexts, args, best_score=0, best_context=None, move_up=False):
        """Search the given list of contexts and return the context
         which best matches the given args.

        best_score and best_context can be used to provide base_values.
        """

        for i, context in enumerate(known_contexts):
            score = self.match(context, *args)
            if score == self.PERFECT_MATCH:
                if move_up:
                    self.move_context_up(known_contexts, i)
                return context, score
            if score > best_score:  # NO_MATCH is not OK!
                best_context, best_score = context, score
        return best_context, best_score

    @staticmethod
    def move_context_up(contexts, index):
        """Move the context to the top of the list and set
        the timestamp to current."""
        setting = contexts.pop(index)
        setting.time = time.time()
        contexts.insert(0, setting)

    def add_context(self, contexts, setting):
        """Add the context to the top of the list."""
        contexts.insert(0, setting)
        del contexts[self.MAX_SAVED_CONTEXTS:]

    def clone_context(self, old_context, *args):
        """Construct a copy of the context settings suitable for the context
        described by additional arguments. The method is called by
        find_or_create_context with the same arguments. A class that overloads
        :obj:`match` to accept additional arguments must also overload
        :obj:`clone_context`."""
        context = self.new_context(*args)
        context.values = copy.deepcopy(old_context.values)

        traverse = self.provider.traverse_settings
        for setting, data, _ in traverse(data=context.values):
            if not isinstance(setting, ContextSetting):
                continue

            self.filter_value(setting, data, *args)
        return context

    @staticmethod
    def filter_value(setting, data, *args):
        """Remove values related to setting that are invalid given args."""

    def close_context(self, widget):
        """Close the context by calling :obj:`settings_from_widget` to write
        any relevant widget settings to the context."""
        if widget.current_context is None:
            return

        self.settings_from_widget(widget)
        widget.current_context = None

    def settings_to_widget(self, widget, *args):
        """Apply context settings stored in currently opened context
        to the widget.
        """
        context = widget.current_context
        if context is None:
            return

        widget.retrieveSpecificSettings()

        for setting, data, instance in \
                self.provider.traverse_settings(data=context.values, instance=widget):
            if not isinstance(setting, ContextSetting) or setting.name not in data:
                continue
            value = self.decode_setting(setting, data[setting.name])
            _apply_setting(setting, instance, value)

    def settings_from_widget(self, widget, *args):
        """Update the current context with the setting values from the widget.
        """

        context = widget.current_context
        if context is None:
            return

        widget.storeSpecificSettings()

        def packer(setting, instance):
            if isinstance(setting, ContextSetting) and hasattr(instance, setting.name):
                value = getattr(instance, setting.name)
                yield setting.name, self.encode_setting(context, setting, value)

        context.values = self.provider.pack(widget, packer=packer)

    def fast_save(self, widget, name, value):
        """Update value of `name` setting in the current context to `value`
        """
        setting = self.known_settings.get(name)
        if isinstance(setting, ContextSetting):
            context = widget.current_context
            if context is None:
                return

            value = self.encode_setting(context, setting, value)
            self.update_packed_data(context.values, name, value)
        else:
            super().fast_save(widget, name, value)

    @staticmethod
    def update_packed_data(data, name, value):
        """Updates setting value stored in data dict"""

        *prefixes, name = name.split('.')
        for prefix in prefixes:
            data = data.setdefault(prefix, {})
        data[name] = value

    def encode_setting(self, context, setting, value):
        """Encode value to be stored in settings dict"""
        return copy.copy(value)

    def decode_setting(self, setting, value):
        """Decode settings value from the setting dict format"""
        return value


class DomainContextHandler(ContextHandler):
    """Context handler for widgets with settings that depend on
    the input dataset. Suitable settings are selected based on the
    data domain."""

    MATCH_VALUES_NONE, MATCH_VALUES_CLASS, MATCH_VALUES_ALL = range(3)

    def __init__(self, *, match_values=0, **kwargs):
        super().__init__()
        self.match_values = match_values

        for name in kwargs:
            warnings.warn(
                "{} is not a valid parameter for DomainContextHandler"
                .format(name), OrangeDeprecationWarning
            )

    def encode_domain(self, domain):
        """
        domain: Orange.data.domain to encode
        return: dict mapping attribute name to type or list of values
                (based on the value of self.match_values attribute)
        """

        match = self.match_values
        encode = self.encode_variables
        if match == self.MATCH_VALUES_CLASS:
            attributes = encode(domain.attributes, False)
            attributes.update(encode(domain.class_vars, True))
        else:
            attributes = encode(domain.variables, match == self.MATCH_VALUES_ALL)

        metas = encode(domain.metas, match == self.MATCH_VALUES_ALL)

        return attributes, metas

    @staticmethod
    def encode_variables(attributes, encode_values):
        """Encode variables to a list mapping name to variable type
        or a list of values."""

        if not encode_values:
            return {v.name: vartype(v) for v in attributes}

        return {v.name: v.values if v.is_discrete else vartype(v)
                for v in attributes}

    def new_context(self, domain, attributes, metas):
        """Create a new context."""
        context = super().new_context()
        context.attributes = attributes
        context.metas = metas
        return context

    def open_context(self, widget, domain):
        if domain is None:
            return None, False

        if not isinstance(domain, Domain):
            domain = domain.domain

        super().open_context(widget, domain, *self.encode_domain(domain))

    def filter_value(self, setting, data, domain, attrs, metas):
        value = data.get(setting.name, None)
        if isinstance(value, list):
            new_value = [item for item in value
                         if self.is_valid_item(setting, item, attrs, metas)]
            data[setting.name] = new_value
        elif value is not None:
            if (value[1] >= 0 and
                    not self._var_exists(setting, value, attrs, metas)):
                del data[setting.name]

    def settings_to_widget(self, widget, domain, *args):
        context = widget.current_context
        if context is None:
            return

        widget.retrieveSpecificSettings()

        for setting, data, instance in \
                self.provider.traverse_settings(data=context.values, instance=widget):
            if not isinstance(setting, ContextSetting) or setting.name not in data:
                continue

            value = self.decode_setting(setting, data[setting.name], domain)
            _apply_setting(setting, instance, value)

    @staticmethod
    def encode_variable(var):
        return var.name, 100 + vartype(var)

    def encode_setting(self, context, setting, value):
        if isinstance(value, list):
            if all(e is None or isinstance(e, Variable) for e in value) \
                    and any(e is not None for e in value):
                return [None if e is None else self.encode_variable(e)
                        for e in value], -3
            else:
                return copy.copy(value)

        if isinstance(setting, ContextSetting):
            if isinstance(value, str):
                if not setting.exclude_attributes and value in context.attributes:
                    return value, context.attributes[value]
                if not setting.exclude_metas and value in context.metas:
                    return value, context.metas[value]
            elif isinstance(value, Variable):
                return self.encode_variable(value)

        return copy.copy(value), -2

    def decode_setting(self, setting, value, domain=None):
        if isinstance(value, tuple):
            if value[1] == -3:
                return [None if e is None else domain[e[0]] for e in value[0]]
            if value[1] >= 100:
                if domain is None:
                    raise ValueError("Cannot decode variable without domain")
                return domain[value[0]]
            return value[0]
        else:
            return value

    @staticmethod
    def _var_exists(setting, value, attributes, metas):
        if not isinstance(value, tuple) or len(value) != 2:
            return False

        attr_name, attr_type = value
        if attr_type >= 100:
            attr_type -= 100
        return (not setting.exclude_attributes and
                attributes.get(attr_name, -1) == attr_type or
                not setting.exclude_metas and
                metas.get(attr_name, -1) == attr_type)

    def match(self, context, domain, attrs, metas):
        if (attrs, metas) == (context.attributes, context.metas):
            return self.PERFECT_MATCH

        matches = []
        try:
            for setting, data, _ in \
                    self.provider.traverse_settings(data=context.values):
                if not isinstance(setting, ContextSetting):
                    continue
                value = data.get(setting.name, None)

                if isinstance(value, list):
                    matches.append(
                        self.match_list(setting, value, context, attrs, metas))
                elif isinstance(value, tuple) \
                        and len(value) == 2 \
                        and isinstance(value[0], list) \
                        and value[1] == -3:
                    matches.append(
                        self.match_list(setting, value[0], context, attrs, metas))
                elif value is not None:
                    matches.append(
                        self.match_value(setting, value, attrs, metas))
        except IncompatibleContext:
            return self.NO_MATCH

        matches.append((0, 0))
        matched, available = [sum(m) for m in zip(*matches)]

        return matched / available if available else 0.1

    def match_list(self, setting, value, context, attrs, metas):
        """Match a list of values with the given context.
        returns a tuple containing number of matched and all values.
        """
        matched = 0
        for i, item in enumerate(value):
            if self.is_valid_item(setting, item, attrs, metas):
                matched += 1
            elif setting.required == ContextSetting.REQUIRED:
                raise IncompatibleContext()
        return matched, len(value)

    def match_value(self, setting, value, attrs, metas):
        """Match a single value """
        if value[1] < 0:
            return 0, 0

        if self._var_exists(setting, value, attrs, metas):
            return 1, 1
        elif setting.required == setting.OPTIONAL:
            return 0, 1
        else:
            raise IncompatibleContext()

    def is_valid_item(self, setting, item, attrs, metas):
        """Return True if given item can be used with attrs and metas

        Subclasses can override this method to checks data in alternative
        representations.
        """
        if not isinstance(item, tuple):
            return True
        return self._var_exists(setting, item, attrs, metas)


class IncompatibleContext(Exception):
    """Raised when a required variable in context is not available in data."""
    pass


class ClassValuesContextHandler(ContextHandler):
    """Context handler used for widgets that work with
    a single discrete variable"""

    def open_context(self, widget, classes):
        if isinstance(classes, Variable):
            if classes.is_discrete:
                classes = classes.values
            else:
                classes = None

        super().open_context(widget, classes)

    def new_context(self, classes):
        context = super().new_context()
        context.classes = classes
        return context

    def match(self, context, classes):
        if isinstance(classes, Variable) and classes.is_continuous:
            return (self.PERFECT_MATCH if context.classes is None
                    else self.NO_MATCH)
        else:
            return (self.PERFECT_MATCH if context.classes == classes
                    else self.NO_MATCH)


class PerfectDomainContextHandler(DomainContextHandler):
    """Context handler that matches a context only when
    the same domain is available.

    It uses a different encoding than the DomainContextHandler.
    """

    def new_context(self, domain, attributes, class_vars, metas):
        """Same as DomainContextHandler, but also store class_vars"""
        context = super().new_context(domain, attributes, metas)
        context.class_vars = class_vars
        return context

    def clone_context(self, old_context, *args):
        """Copy of context is always valid, since widgets are using
        the same domain."""
        context = self.new_context(*args)
        context.values = copy.deepcopy(old_context.values)
        return context

    def encode_domain(self, domain):
        """Encode domain into tuples (name, type)
        A tuple is returned for each of attributes, class_vars and metas.
        """

        if self.match_values == self.MATCH_VALUES_ALL:
            def _encode(attrs):
                return tuple((v.name, list(v.values) if v.is_discrete else vartype(v))
                             for v in attrs)
        else:
            def _encode(attrs):
                return tuple((v.name, vartype(v)) for v in attrs)
        return (_encode(domain.attributes),
                _encode(domain.class_vars),
                _encode(domain.metas))

    def match(self, context, domain, attributes, class_vars, metas):
        """Context only matches when domains are the same"""

        return (self.PERFECT_MATCH
                if (context.attributes == attributes and
                    context.class_vars == class_vars and
                    context.metas == metas)
                else self.NO_MATCH)

    def encode_setting(self, context, setting, value):
        """Same as is domain context handler, but handles separately stored
        class_vars."""

        if isinstance(setting, ContextSetting) and isinstance(value, str):

            def _candidate_variables():
                if not setting.exclude_attributes:
                    yield from itertools.chain(context.attributes,
                                               context.class_vars)
                if not setting.exclude_metas:
                    yield from context.metas

            for aname, atype in _candidate_variables():
                if aname == value:
                    return value, atype

            return value, -1
        else:
            return super().encode_setting(context, setting, value)


class SettingsPrinter(pprint.PrettyPrinter):
    """Pretty Printer that knows how to properly format Contexts."""

    def _format(self, obj, stream, indent, allowance, context, level):
        if not isinstance(obj, Context):
            return super()._format(obj, stream, indent,
                                   allowance, context, level)

        stream.write("Context(")
        for key, value in sorted(obj.__dict__.items(), key=itemgetter(0)):
            if key == "values":
                continue
            stream.write(key)
            stream.write("=")
            stream.write(self._repr(value, context, level + 1))
            stream.write(",\n")
            stream.write(" " * (indent + 8))
        stream.write("values=")
        stream.write(" ")
        self._format(obj.values, stream, indent+15,
                     allowance+1, context, level + 1)
        stream.write(")")


def rename_setting(settings, old_name, new_name):
    """
    Rename setting from `old_name` to `new_name`. Used in migrations.

    The argument `settings` can be `dict` or `Context`.
    """
    if isinstance(settings, Context):
        rename_setting(settings.values, old_name, new_name)
    else:
        settings[new_name] = settings.pop(old_name)


def migrate_str_to_variable(settings, names=None, none_placeholder=None):
    """
    Change variables stored as `(str, int)` to `(Variable, int)`.

    Args:
        settings (Context): context that is being migrated
        names (sequence): names of settings to be migrated. If omitted,
            all settings with values `(str, int)` are migrated.
    """
    def _fix(name):
        var, vartype = settings.values[name]
        if 0 <= vartype <= 100:
            settings.values[name] = (var, 100 + vartype)
        elif var == none_placeholder and vartype == -2:
            settings.values[name] = None

    if names is None:
        for name, setting in settings.values.items():
            if isinstance(setting, tuple) and len(setting) == 2 and \
                    isinstance(setting[0], str) and isinstance(setting[1], int):
                _fix(name)
    elif isinstance(names, str):
        _fix(names)
    else:
        for name in names:
            _fix(name)

```
--- 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:** `encode_setting` Raises TypeError When Handling Deprecated String Variable Settings

**Description:**
When attempting to encode settings that use variables stored as strings, the `encode_setting` method raises a `TypeError` due to a missing required argument. This issue prevents the proper handling of deprecated string-based variable settings and disrupts the encoding process.

**Example Code:**
```python
from unittest.mock import Mock
from Orange.widgets.settings import DomainContextHandler, ContextSetting

context = Mock()
context.attributes = {"foo": 2}
context.metas = {}
setting = ContextSetting("")
setting.name = "setting_name"

DomainContextHandler.encode_setting(context, setting, "foo")
```

**Expected Behavior:**
Using string-based variable settings should trigger a deprecation warning and allow the settings to be encoded correctly without errors.

**Actual Behavior:**
Executing the encoding process raises the following error:
```
TypeError: encode_setting() missing 1 required positional argument: 'value'
```
This error occurs because the `encode_setting` method is not receiving all necessary arguments, preventing the encoding of deprecated string variable settings.

[/ISSUE]
{
    "TestDomainContextHandler.test_backward_compatible_params": "PASSED",
    "TestDomainContextHandler.test_clone_context": "PASSED",
    "TestDomainContextHandler.test_decode_list_setting": "PASSED",
    "TestDomainContextHandler.test_decode_setting": "PASSED",
    "TestDomainContextHandler.test_deprecated_str_as_var": "PASSED",
    "TestDomainContextHandler.test_encode_domain_with_match_all": "PASSED",
    "TestDomainContextHandler.test_encode_domain_with_match_class": "PASSED",
    "TestDomainContextHandler.test_encode_domain_with_match_none": "PASSED",
    "TestDomainContextHandler.test_encode_list_settings": "PASSED",
    "TestDomainContextHandler.test_encode_setting": "PASSED",
    "TestDomainContextHandler.test_filter_value": "PASSED",
    "TestDomainContextHandler.test_match_returns_1_if_everything_matches": "PASSED",
    "TestDomainContextHandler.test_match_returns_2_on_perfect_match": "PASSED",
    "TestDomainContextHandler.test_match_returns_point_1_when_nothing_to_match": "PASSED",
    "TestDomainContextHandler.test_match_returns_zero_on_incompatible_context": "PASSED",
    "TestDomainContextHandler.test_open_context": "PASSED",
    "TestDomainContextHandler.test_open_context_with_imperfect_match": "PASSED",
    "TestDomainContextHandler.test_open_context_with_no_match": "PASSED"
}
diff --git a/Orange/widgets/settings.py b/Orange/widgets/settings.py
index 1198a4f58..e8a535e7d 100644
--- a/Orange/widgets/settings.py
+++ b/Orange/widgets/settings.py
@@ -937,6 +937,13 @@ class DomainContextHandler(ContextHandler):
                 .format(name), OrangeDeprecationWarning
             )
 
+    @staticmethod
+    def _warn_about_str_var_settings(setting):
+        warnings.warn(
+            "Storing variables as strings in settings is deprecated.\n"
+            "Support for this will be dropped in Orange 3.26.\n"
+            f"Change f{setting.name} to store an instance of `Variable`.")
+
     def encode_domain(self, domain):
         """
         domain: Orange.data.domain to encode
@@ -1013,23 +1020,26 @@ class DomainContextHandler(ContextHandler):
     def encode_variable(var):
         return var.name, 100 + vartype(var)
 
-    def encode_setting(self, context, setting, value):
+    @classmethod
+    def encode_setting(cls, context, setting, value):
         if isinstance(value, list):
             if all(e is None or isinstance(e, Variable) for e in value) \
                     and any(e is not None for e in value):
-                return [None if e is None else self.encode_variable(e)
+                return [None if e is None else cls.encode_variable(e)
                         for e in value], -3
             else:
                 return copy.copy(value)
 
         if isinstance(setting, ContextSetting):
             if isinstance(value, str):
-                if not setting.exclude_attributes and value in context.attributes:
-                    return value, context.attributes[value]
-                if not setting.exclude_metas and value in context.metas:
-                    return value, context.metas[value]
+                variables = {
+                    **({} if setting.exclude_attributes else context.attributes),
+                    **({} if setting.exclude_metas else context.metas)}
+                if value in variables:
+                    cls._warn_about_str_var_settings(setting)
+                    return value, variables[value]
             elif isinstance(value, Variable):
-                return self.encode_variable(value)
+                return cls.encode_variable(value)
 
         return copy.copy(value), -2
 
@@ -1045,14 +1055,16 @@ class DomainContextHandler(ContextHandler):
         else:
             return value
 
-    @staticmethod
-    def _var_exists(setting, value, attributes, metas):
+    @classmethod
+    def _var_exists(cls, setting, value, attributes, metas):
         if not isinstance(value, tuple) or len(value) != 2:
             return False
 
         attr_name, attr_type = value
         if attr_type >= 100:
             attr_type -= 100
+        else:
+            cls._warn_about_str_var_settings(setting)
         return (not setting.exclude_attributes and
                 attributes.get(attr_name, -1) == attr_type or
                 not setting.exclude_metas and

{"Orange/widgets/settings.py": "\"\"\"Widget Settings and Settings Handlers\n\nSettings are used to declare widget attributes that persist through sessions.\nWhen widget is removed or saved to a schema file, its settings are packed,\nserialized and stored. When a new widget is created, values of attributes\nmarked as settings are read from disk. When schema is loaded, attribute values\nare set to one stored in schema.\n\nEach widget has its own SettingsHandler that takes care of serializing and\nstoring of settings and SettingProvider that is incharge of reading and\nwriting the setting values.\n\nAll widgets extending from OWWidget use SettingsHandler, unless they\ndeclare otherwise. SettingsHandler ensures that setting attributes\nare replaced with default (last used) setting values when the widget is\ninitialized and stored when the widget is removed.\n\nWidgets with settings whose values depend on the widget inputs use\nsettings handlers based on ContextHandler. These handlers have two\nadditional methods, open_context and close_context.\n\nopen_context is called when widgets receives new data. It finds a suitable\ncontext and sets the widget attributes to the values stored in context.\nIf no suitable context exists, a new one is created and values from widget\nare copied to it.\n\nclose_context stores values that were last used on the widget to the context\nso they can be used alter. It should be called before widget starts modifying\n(initializing) the value of the setting attributes.\n\"\"\"\n\nimport sys\nimport copy\nimport itertools\nimport os\nimport logging\nimport pickle\nimport pprint\nimport time\nimport warnings\nfrom operator import itemgetter\nfrom typing import Any\n\nfrom Orange.data import Domain, Variable\nfrom Orange.misc.environ import widget_settings_dir\nfrom Orange.util import OrangeDeprecationWarning\nfrom Orange.widgets.utils import vartype\nfrom Orange.widgets.gui import OWComponent\n\nlog = logging.getLogger(__name__)\n\n__all__ = [\"Setting\", \"SettingsHandler\", \"SettingProvider\",\n           \"ContextSetting\", \"ContextHandler\",\n           \"DomainContextHandler\", \"PerfectDomainContextHandler\",\n           \"ClassValuesContextHandler\", \"widget_settings_dir\",\n           \"IncompatibleContext\"]\n\n_IMMUTABLES = (str, int, bytes, bool, float, tuple)\n\nVERSION_KEY = \"__version__\"\n\n\nclass Setting:\n    \"\"\"Description of a setting.\n    \"\"\"\n\n    # Settings are automatically persisted to disk\n    packable = True\n\n    # Setting is only persisted to schema (default value does not change)\n    schema_only = False\n\n    def __new__(cls, default, *args, **kwargs):\n        \"\"\"A misleading docstring for providing type hints for Settings\n\n        :type: default: T\n        :rtype: T\n        \"\"\"\n        return super().__new__(cls)\n\n    def __init__(self, default, **data):\n        self.name = None  # Name gets set in widget's meta class\n        self.default = default\n        self.__dict__.update(data)\n\n    def __str__(self):\n        return '{0} \"{1}\"'.format(self.__class__.__name__, self.name)\n\n    __repr__ = __str__\n\n    def __getnewargs__(self):\n        return (self.default, )\n\n\n# Pylint ignores type annotations in assignments. For\n#\n#    x: int = Setting(0)\n#\n# it ignores `int` and assumes x is of type `Setting`. Annotations in\n# comments ( # type: int) also don't work. The only way to annotate x is\n#\n#    x: int\n#    x = Setting(0)\n#\n# but we don't want to clutter the code with extra lines of annotations. Hence\n# we disable checking the type of `Setting` by confusing pylint with an extra\n# definition that is never executed.\nif 1 == 0:\n    class Setting:  # pylint: disable=function-redefined\n        pass\n\n\ndef _apply_setting(setting: Setting, instance: OWComponent, value: Any):\n    \"\"\"\n    Set `setting` of widget `instance` to the given `value`, in place if\n    possible.\n\n    If old and new values are of the same type, and the type is either a list\n    or has methods `clear` and `update`, setting is updated in place. Otherwise\n    the function calls `setattr`.\n    \"\"\"\n    target = getattr(instance, setting.name, None)\n    if type(target) is type(value):\n        if isinstance(value, list):\n            target[:] = value\n            return\n        elif hasattr(value, \"clear\") and hasattr(value, \"update\"):\n            target.clear()\n            target.update(value)\n            return\n    setattr(instance, setting.name, value)\n\n\nclass SettingProvider:\n    \"\"\"A hierarchical structure keeping track of settings belonging to\n    a class and child setting providers.\n\n    At instantiation, it creates a dict of all Setting and SettingProvider\n    members of the class. This dict is used to get/set values of settings\n    from/to the instances of the class this provider belongs to.\n    \"\"\"\n\n    def __init__(self, provider_class):\n        \"\"\" Construct a new instance of SettingProvider.\n\n        Traverse provider_class members and store all instances of\n        Setting and SettingProvider.\n\n        Parameters\n        ----------\n        provider_class : class\n            class containing settings definitions\n        \"\"\"\n        self.name = \"\"\n        self.provider_class = provider_class\n        self.providers = {}\n        \"\"\":type: dict[str, SettingProvider]\"\"\"\n        self.settings = {}\n        \"\"\":type: dict[str, Setting]\"\"\"\n        self.initialization_data = None\n\n        for name in dir(provider_class):\n            value = getattr(provider_class, name, None)\n            if isinstance(value, Setting):\n                value = copy.deepcopy(value)\n                value.name = name\n                self.settings[name] = value\n            if isinstance(value, SettingProvider):\n                value = copy.deepcopy(value)\n                value.name = name\n                self.providers[name] = value\n\n    def initialize(self, instance, data=None):\n        \"\"\"Initialize instance settings to their default values.\n\n        Mutable values are (shallow) copied before they are assigned to the\n        widget. Immutable are used as-is.\n\n        Parameters\n        ----------\n        instance : OWWidget\n            widget instance to initialize\n        data : Optional[dict]\n            optional data used to override the defaults\n            (used when settings are loaded from schema)\n        \"\"\"\n        if data is None and self.initialization_data is not None:\n            data = self.initialization_data\n\n        self._initialize_settings(instance, data)\n        self._initialize_providers(instance, data)\n\n    def _initialize_settings(self, instance, data):\n        if data is None:\n            data = {}\n        for name, setting in self.settings.items():\n            value = data.get(name, setting.default)\n            if isinstance(value, _IMMUTABLES):\n                setattr(instance, name, value)\n            else:\n                setattr(instance, name, copy.copy(value))\n\n    def _initialize_providers(self, instance, data):\n        if not data:\n            return\n\n        for name, provider in self.providers.items():\n            if name not in data:\n                continue\n\n            member = getattr(instance, name, None)\n            if member is None or isinstance(member, SettingProvider):\n                provider.store_initialization_data(data[name])\n            else:\n                provider.initialize(member, data[name])\n\n    def store_initialization_data(self, initialization_data):\n        \"\"\"Store initialization data for later use.\n\n        Used when settings handler is initialized, but member for this\n        provider does not exists yet (because handler.initialize is called in\n        __new__, but member will be created in __init__.\n\n        Parameters\n        ----------\n        initialization_data : dict\n            data to be used for initialization when the component is created\n        \"\"\"\n        self.initialization_data = initialization_data\n\n    @staticmethod\n    def _default_packer(setting, instance):\n        \"\"\"A simple packet that yields setting name and value.\n\n        Parameters\n        ----------\n        setting : Setting\n        instance : OWWidget\n        \"\"\"\n        if setting.packable:\n            if hasattr(instance, setting.name):\n                yield setting.name, getattr(instance, setting.name)\n            else:\n                warnings.warn(\"{0} is declared as setting on {1} \"\n                              \"but not present on instance.\"\n                              .format(setting.name, instance))\n\n    def pack(self, instance, packer=None):\n        \"\"\"Pack instance settings in a name:value dict.\n\n        Parameters\n        ----------\n        instance : OWWidget\n            widget instance\n        packer: callable (Setting, OWWidget) -> Generator[(str, object)]\n            optional packing function\n            it will be called with setting and instance parameters and\n            should yield (name, value) pairs that will be added to the\n            packed_settings.\n        \"\"\"\n        if packer is None:\n            packer = self._default_packer\n\n        packed_settings = dict(itertools.chain(\n            *(packer(setting, instance) for setting in self.settings.values())\n        ))\n\n        packed_settings.update({\n            name: provider.pack(getattr(instance, name), packer)\n            for name, provider in self.providers.items()\n            if hasattr(instance, name)\n        })\n        return packed_settings\n\n    def unpack(self, instance, data):\n        \"\"\"Restore settings from data to the instance.\n\n        Parameters\n        ----------\n        instance : OWWidget\n            instance to restore settings to\n        data : dict\n            packed data\n        \"\"\"\n        for setting, _data, inst in self.traverse_settings(data, instance):\n            if setting.name in _data and inst is not None:\n                _apply_setting(setting, inst, _data[setting.name])\n\n    def get_provider(self, provider_class):\n        \"\"\"Return provider for provider_class.\n\n        If this provider matches, return it, otherwise pass\n        the call to child providers.\n\n        Parameters\n        ----------\n        provider_class : class\n        \"\"\"\n        if issubclass(provider_class, self.provider_class):\n            return self\n\n        for subprovider in self.providers.values():\n            provider = subprovider.get_provider(provider_class)\n            if provider:\n                return provider\n        return None\n\n    def traverse_settings(self, data=None, instance=None):\n        \"\"\"Generator of tuples (setting, data, instance) for each setting\n        in this and child providers..\n\n        Parameters\n        ----------\n        data : dict\n            dictionary with setting values\n        instance : OWWidget\n            instance matching setting_provider\n        \"\"\"\n        data = data if data is not None else {}\n\n        for setting in self.settings.values():\n            yield setting, data, instance\n\n        for provider in self.providers.values():\n            data_ = data.get(provider.name, {})\n            instance_ = getattr(instance, provider.name, None)\n            for setting, component_data, component_instance in \\\n                    provider.traverse_settings(data_, instance_):\n                yield setting, component_data, component_instance\n\n\nclass SettingsHandler:\n    \"\"\"Reads widget setting files and passes them to appropriate providers.\"\"\"\n\n    def __init__(self):\n        \"\"\"Create a setting handler template.\n\n        Used in class definition. Bound instance will be created\n        when SettingsHandler.create is called.\n        \"\"\"\n        self.widget_class = None\n        self.provider = None\n        \"\"\":type: SettingProvider\"\"\"\n        self.defaults = {}\n        self.known_settings = {}\n\n    @staticmethod\n    def create(widget_class, template=None):\n        \"\"\"Create a new settings handler based on the template and bind it to\n        widget_class.\n\n        Parameters\n        ----------\n        widget_class : class\n        template : SettingsHandler\n            SettingsHandler to copy setup from\n\n        Returns\n        -------\n        SettingsHandler\n        \"\"\"\n\n        if template is None:\n            template = SettingsHandler()\n\n        setting_handler = copy.copy(template)\n        setting_handler.defaults = {}\n        setting_handler.bind(widget_class)\n        return setting_handler\n\n    def bind(self, widget_class):\n        \"\"\"Bind settings handler instance to widget_class.\n\n        Parameters\n        ----------\n        widget_class : class\n        \"\"\"\n        self.widget_class = widget_class\n        self.provider = SettingProvider(widget_class)\n        self.known_settings = {}\n        self.analyze_settings(self.provider, \"\")\n        self.read_defaults()\n\n    def analyze_settings(self, provider, prefix):\n        \"\"\"Traverse through all settings known to the provider\n        and analyze each of them.\n\n        Parameters\n        ----------\n        provider : SettingProvider\n        prefix : str\n            prefix the provider is registered to handle\n        \"\"\"\n        for setting in provider.settings.values():\n            self.analyze_setting(prefix, setting)\n\n        for name, sub_provider in provider.providers.items():\n            new_prefix = '{0}{1}.'.format(prefix or '', name)\n            self.analyze_settings(sub_provider, new_prefix)\n\n    def analyze_setting(self, prefix, setting):\n        \"\"\"Perform any initialization task related to setting.\n\n        Parameters\n        ----------\n        prefix : str\n        setting : Setting\n        \"\"\"\n        self.known_settings[prefix + setting.name] = setting\n\n    def read_defaults(self):\n        \"\"\"Read (global) defaults for this widget class from a file.\n        Opens a file and calls :obj:`read_defaults_file`. Derived classes\n        should overload the latter.\"\"\"\n        filename = self._get_settings_filename()\n        if os.path.isfile(filename):\n            settings_file = open(filename, \"rb\")\n            try:\n                self.read_defaults_file(settings_file)\n            # Unpickling exceptions can be of any type\n            # pylint: disable=broad-except\n            except Exception as ex:\n                warnings.warn(\"Could not read defaults for widget {0}\\n\"\n                              \"The following error occurred:\\n\\n{1}\"\n                              .format(self.widget_class, ex))\n            finally:\n                settings_file.close()\n\n    def read_defaults_file(self, settings_file):\n        \"\"\"Read (global) defaults for this widget class from a file.\n\n        Parameters\n        ----------\n        settings_file : file-like object\n        \"\"\"\n        defaults = pickle.load(settings_file)\n        self.defaults = {\n            key: value\n            for key, value in defaults.items()\n            if not isinstance(value, Setting)\n        }\n        self._migrate_settings(self.defaults)\n\n    def write_defaults(self):\n        \"\"\"Write (global) defaults for this widget class to a file.\n        Opens a file and calls :obj:`write_defaults_file`. Derived classes\n        should overload the latter.\"\"\"\n        filename = self._get_settings_filename()\n        os.makedirs(os.path.dirname(filename), exist_ok=True)\n        try:\n            settings_file = open(filename, \"wb\")\n            try:\n                self.write_defaults_file(settings_file)\n            except (EOFError, IOError, pickle.PicklingError) as ex:\n                log.error(\"Could not write default settings for %s (%s).\",\n                          self.widget_class, type(ex).__name__)\n                settings_file.close()\n                os.remove(filename)\n            else:\n                settings_file.close()\n        except PermissionError as ex:\n            log.error(\"Could not write default settings for %s (%s).\",\n                      self.widget_class, type(ex).__name__)\n\n    def write_defaults_file(self, settings_file):\n        \"\"\"Write defaults for this widget class to a file\n\n        Parameters\n        ----------\n        settings_file : file-like object\n        \"\"\"\n        defaults = dict(self.defaults)\n        defaults[VERSION_KEY] = self.widget_class.settings_version\n        pickle.dump(defaults, settings_file, -1)\n\n    def _get_settings_filename(self):\n        \"\"\"Return the name of the file with default settings for the widget\"\"\"\n        return os.path.join(widget_settings_dir(),\n                            \"{0.__module__}.{0.__qualname__}.pickle\"\n                            .format(self.widget_class))\n\n    def initialize(self, instance, data=None):\n        \"\"\"\n        Initialize widget's settings.\n\n        Replace all instance settings with their default values.\n\n        Parameters\n        ----------\n        instance : OWWidget\n        data : dict or bytes that unpickle into a dict\n            values used to override the defaults\n        \"\"\"\n        provider = self._select_provider(instance)\n\n        if isinstance(data, bytes):\n            data = pickle.loads(data)\n        self._migrate_settings(data)\n\n        if provider is self.provider:\n            data = self._add_defaults(data)\n\n        provider.initialize(instance, data)\n\n    def _migrate_settings(self, settings):\n        \"\"\"Ask widget to migrate settings to the latest version.\"\"\"\n        if settings:\n            try:\n                self.widget_class.migrate_settings(\n                    settings, settings.pop(VERSION_KEY, 0))\n            except Exception:  # pylint: disable=broad-except\n                sys.excepthook(*sys.exc_info())\n                settings.clear()\n\n    def _select_provider(self, instance):\n        provider = self.provider.get_provider(instance.__class__)\n        if provider is None:\n            message = \"{0} has not been declared as setting provider in {1}. \" \\\n                      \"Settings will not be saved/loaded properly. Defaults will be used instead.\" \\\n                      .format(instance.__class__, self.widget_class)\n            warnings.warn(message)\n            provider = SettingProvider(instance.__class__)\n        return provider\n\n    def _add_defaults(self, data):\n        if data is None:\n            return self.defaults\n\n        new_data = self.defaults.copy()\n        new_data.update(data)\n        return new_data\n\n    def _prepare_defaults(self, widget):\n        self.defaults = self.provider.pack(widget)\n        for setting, data, _ in self.provider.traverse_settings(data=self.defaults):\n            if setting.schema_only:\n                data.pop(setting.name, None)\n\n    def pack_data(self, widget):\n        \"\"\"\n        Pack the settings for the given widget. This method is used when\n        saving schema, so that when the schema is reloaded the widget is\n        initialized with its proper data and not the class-based defaults.\n        See :obj:`SettingsHandler.initialize` for detailed explanation of its\n        use.\n\n        Inherited classes add other data, in particular widget-specific\n        local contexts.\n\n        Parameters\n        ----------\n        widget : OWWidget\n        \"\"\"\n        widget.settingsAboutToBePacked.emit()\n        packed_settings = self.provider.pack(widget)\n        packed_settings[VERSION_KEY] = self.widget_class.settings_version\n        return packed_settings\n\n    def update_defaults(self, widget):\n        \"\"\"\n        Writes widget instance's settings to class defaults. Called when the\n        widget is deleted.\n\n        Parameters\n        ----------\n        widget : OWWidget\n        \"\"\"\n        widget.settingsAboutToBePacked.emit()\n        self._prepare_defaults(widget)\n        self.write_defaults()\n\n    def fast_save(self, widget, name, value):\n        \"\"\"Store the (changed) widget's setting immediately to the context.\n\n        Parameters\n        ----------\n        widget : OWWidget\n        name : str\n        value : object\n\n        \"\"\"\n        if name in self.known_settings:\n            setting = self.known_settings[name]\n            if not setting.schema_only:\n                setting.default = value\n\n    def reset_settings(self, instance):\n        \"\"\"Reset widget settings to defaults\n\n        Parameters\n        ----------\n        instance : OWWidget\n        \"\"\"\n        for setting, _, inst in self.provider.traverse_settings(instance=instance):\n            if setting.packable:\n                _apply_setting(setting, inst, setting.default)\n\n\nclass ContextSetting(Setting):\n    \"\"\"Description of a context dependent setting\"\"\"\n\n    OPTIONAL = 0\n    REQUIRED = 2\n\n    # Context settings are not persisted, but are stored in context instead.\n    packable = False\n\n    # These flags are not general - they assume that the setting has to do\n    # something with the attributes. Large majority does, so this greatly\n    # simplifies the declaration of settings in widget at no (visible)\n    # cost to those settings that don't need it\n    def __init__(self, default, *, required=2,\n                 exclude_attributes=False, exclude_metas=False, **data):\n        super().__init__(default, **data)\n        self.exclude_attributes = exclude_attributes\n        self.exclude_metas = exclude_metas\n        self.required = required\n\n\nclass Context:\n    \"\"\"Class for data thad defines context and\n    values that should be applied to widget if given context\n    is encountered.\"\"\"\n    def __init__(self, **argkw):\n        self.time = time.time()\n        self.values = {}\n        self.__dict__.update(argkw)\n\n    def __getstate__(self):\n        state = dict(self.__dict__)\n        for nc in getattr(self, \"no_copy\", []):\n            if nc in state:\n                del state[nc]\n        return state\n\n\nclass ContextHandler(SettingsHandler):\n    \"\"\"Base class for setting handlers that can handle contexts.\n\n    Classes deriving from it need to implement method `match`.\n    \"\"\"\n\n    NO_MATCH = 0\n    PERFECT_MATCH = 2\n\n    MAX_SAVED_CONTEXTS = 50\n\n    def __init__(self):\n        super().__init__()\n        self.global_contexts = []\n        self.known_settings = {}\n\n    def initialize(self, instance, data=None):\n        \"\"\"Initialize the widget: call the inherited initialization and\n        add an attribute 'context_settings' to the widget. This method\n        does not open a context.\"\"\"\n        instance.current_context = None\n        super().initialize(instance, data)\n        if data and \"context_settings\" in data:\n            instance.context_settings = data[\"context_settings\"]\n            self._migrate_contexts(instance.context_settings)\n        else:\n            instance.context_settings = []\n\n    def read_defaults_file(self, settings_file):\n        \"\"\"Call the inherited method, then read global context from the\n           pickle.\"\"\"\n        super().read_defaults_file(settings_file)\n        self.global_contexts = pickle.load(settings_file)\n        self._migrate_contexts(self.global_contexts)\n\n    def _migrate_contexts(self, contexts):\n        i = 0\n        while i < len(contexts):\n            context = contexts[i]\n            try:\n                self.widget_class.migrate_context(\n                    context, context.values.pop(VERSION_KEY, 0))\n            except IncompatibleContext:\n                del contexts[i]\n            except Exception:  # pylint: disable=broad-except\n                sys.excepthook(*sys.exc_info())\n                del contexts[i]\n            else:\n                i += 1\n\n    def write_defaults_file(self, settings_file):\n        \"\"\"Call the inherited method, then add global context to the pickle.\"\"\"\n        super().write_defaults_file(settings_file)\n\n        def add_version(context):\n            context = copy.copy(context)\n            context.values = dict(context.values)\n            context.values[VERSION_KEY] = self.widget_class.settings_version\n            return context\n\n        pickle.dump([add_version(context) for context in self.global_contexts],\n                    settings_file, -1)\n\n    def pack_data(self, widget):\n        \"\"\"Call the inherited method, then add local contexts to the dict.\"\"\"\n        data = super().pack_data(widget)\n        self.settings_from_widget(widget)\n        context_settings = [copy.copy(context) for context in\n                            widget.context_settings]\n        for context in context_settings:\n            context.values[VERSION_KEY] = self.widget_class.settings_version\n        data[\"context_settings\"] = context_settings\n        return data\n\n    def update_defaults(self, widget):\n        \"\"\"\n        Reimplemented from SettingsHandler\n\n        Merge the widgets local contexts into the global contexts and persist\n        the settings (including the contexts) to disk.\n        \"\"\"\n        widget.settingsAboutToBePacked.emit()\n        self.settings_from_widget(widget)\n        globs = self.global_contexts\n        assert widget.context_settings is not globs\n        ids = {id(c) for c in globs}\n        globs += (c for c in widget.context_settings if id(c) not in ids)\n        globs.sort(key=lambda c: -c.time)\n        del globs[self.MAX_SAVED_CONTEXTS:]\n\n        # Save non-context settings. Do not call super().update_defaults, so that\n        # settingsAboutToBePacked is emitted once.\n        self._prepare_defaults(widget)\n        self.write_defaults()\n\n    def new_context(self, *args):\n        \"\"\"Create a new context.\"\"\"\n        return Context()\n\n    def open_context(self, widget, *args):\n        \"\"\"Open a context by finding one and setting the widget data or\n        creating one and fill with the data from the widget.\"\"\"\n        widget.current_context, is_new = \\\n            self.find_or_create_context(widget, *args)\n        if is_new:\n            try:\n                self.settings_from_widget(widget, *args)\n            except TypeError:\n                warnings.warn(\"settings_from_widget in {} does not accept *args.\\n\"\n                              \"Support for this will be dropped in Orange 3.10\"\n                              .format(type(self)),\n                              DeprecationWarning)\n                self.settings_from_widget(widget)\n        else:\n            try:\n                self.settings_to_widget(widget, *args)\n            except TypeError:\n                warnings.warn(\"settings_to_widget {} does not accept *args.\\n\"\n                              \"Support for this will be dropped in Orange 3.10\"\n                              .format(type(self)),\n                              DeprecationWarning)\n                self.settings_to_widget(widget)\n\n    def match(self, context, *args):\n        \"\"\"Return the degree to which the stored `context` matches the data\n        passed in additional arguments).\n        When match returns 0 (ContextHandler.NO_MATCH), the context will not\n        be used. When it returns ContextHandler.PERFECT_MATCH, the context\n        is a perfect match so no further search is necessary.\n\n        If imperfect matching is not desired, match should only\n        return ContextHandler.NO_MATCH or ContextHandler.PERFECT_MATCH.\n\n        Derived classes must overload this method.\n        \"\"\"\n        raise NotImplementedError\n\n    def find_or_create_context(self, widget, *args):\n        \"\"\"Find the best matching context or create a new one if nothing\n        useful is found. The returned context is moved to or added to the top\n        of the context list.\"\"\"\n\n        # First search the contexts that were already used in this widget instance\n        best_context, best_score = self.find_context(widget.context_settings, args, move_up=True)\n        # If the exact data was used, reuse the context\n        if best_score == self.PERFECT_MATCH:\n            return best_context, False\n\n        # Otherwise check if a better match is available in global_contexts\n        best_context, best_score = self.find_context(self.global_contexts, args,\n                                                     best_score, best_context)\n        if best_context:\n            context = self.clone_context(best_context, *args)\n        else:\n            context = self.new_context(*args)\n        # Store context in widget instance. It will be pushed to global_contexts\n        # when (if) update defaults is called.\n        self.add_context(widget.context_settings, context)\n        return context, best_context is None\n\n    def find_context(self, known_contexts, args, best_score=0, best_context=None, move_up=False):\n        \"\"\"Search the given list of contexts and return the context\n         which best matches the given args.\n\n        best_score and best_context can be used to provide base_values.\n        \"\"\"\n\n        for i, context in enumerate(known_contexts):\n            score = self.match(context, *args)\n            if score == self.PERFECT_MATCH:\n                if move_up:\n                    self.move_context_up(known_contexts, i)\n                return context, score\n            if score > best_score:  # NO_MATCH is not OK!\n                best_context, best_score = context, score\n        return best_context, best_score\n\n    @staticmethod\n    def move_context_up(contexts, index):\n        \"\"\"Move the context to the top of the list and set\n        the timestamp to current.\"\"\"\n        setting = contexts.pop(index)\n        setting.time = time.time()\n        contexts.insert(0, setting)\n\n    def add_context(self, contexts, setting):\n        \"\"\"Add the context to the top of the list.\"\"\"\n        contexts.insert(0, setting)\n        del contexts[self.MAX_SAVED_CONTEXTS:]\n\n    def clone_context(self, old_context, *args):\n        \"\"\"Construct a copy of the context settings suitable for the context\n        described by additional arguments. The method is called by\n        find_or_create_context with the same arguments. A class that overloads\n        :obj:`match` to accept additional arguments must also overload\n        :obj:`clone_context`.\"\"\"\n        context = self.new_context(*args)\n        context.values = copy.deepcopy(old_context.values)\n\n        traverse = self.provider.traverse_settings\n        for setting, data, _ in traverse(data=context.values):\n            if not isinstance(setting, ContextSetting):\n                continue\n\n            self.filter_value(setting, data, *args)\n        return context\n\n    @staticmethod\n    def filter_value(setting, data, *args):\n        \"\"\"Remove values related to setting that are invalid given args.\"\"\"\n\n    def close_context(self, widget):\n        \"\"\"Close the context by calling :obj:`settings_from_widget` to write\n        any relevant widget settings to the context.\"\"\"\n        if widget.current_context is None:\n            return\n\n        self.settings_from_widget(widget)\n        widget.current_context = None\n\n    def settings_to_widget(self, widget, *args):\n        \"\"\"Apply context settings stored in currently opened context\n        to the widget.\n        \"\"\"\n        context = widget.current_context\n        if context is None:\n            return\n\n        widget.retrieveSpecificSettings()\n\n        for setting, data, instance in \\\n                self.provider.traverse_settings(data=context.values, instance=widget):\n            if not isinstance(setting, ContextSetting) or setting.name not in data:\n                continue\n            value = self.decode_setting(setting, data[setting.name])\n            _apply_setting(setting, instance, value)\n\n    def settings_from_widget(self, widget, *args):\n        \"\"\"Update the current context with the setting values from the widget.\n        \"\"\"\n\n        context = widget.current_context\n        if context is None:\n            return\n\n        widget.storeSpecificSettings()\n\n        def packer(setting, instance):\n            if isinstance(setting, ContextSetting) and hasattr(instance, setting.name):\n                value = getattr(instance, setting.name)\n                yield setting.name, self.encode_setting(context, setting, value)\n\n        context.values = self.provider.pack(widget, packer=packer)\n\n    def fast_save(self, widget, name, value):\n        \"\"\"Update value of `name` setting in the current context to `value`\n        \"\"\"\n        setting = self.known_settings.get(name)\n        if isinstance(setting, ContextSetting):\n            context = widget.current_context\n            if context is None:\n                return\n\n            value = self.encode_setting(context, setting, value)\n            self.update_packed_data(context.values, name, value)\n        else:\n            super().fast_save(widget, name, value)\n\n    @staticmethod\n    def update_packed_data(data, name, value):\n        \"\"\"Updates setting value stored in data dict\"\"\"\n\n        *prefixes, name = name.split('.')\n        for prefix in prefixes:\n            data = data.setdefault(prefix, {})\n        data[name] = value\n\n    def encode_setting(self, context, setting, value):\n        \"\"\"Encode value to be stored in settings dict\"\"\"\n        return copy.copy(value)\n\n    def decode_setting(self, setting, value):\n        \"\"\"Decode settings value from the setting dict format\"\"\"\n        return value\n\n\nclass DomainContextHandler(ContextHandler):\n    \"\"\"Context handler for widgets with settings that depend on\n    the input dataset. Suitable settings are selected based on the\n    data domain.\"\"\"\n\n    MATCH_VALUES_NONE, MATCH_VALUES_CLASS, MATCH_VALUES_ALL = range(3)\n\n    def __init__(self, *, match_values=0, **kwargs):\n        super().__init__()\n        self.match_values = match_values\n\n        for name in kwargs:\n            warnings.warn(\n                \"{} is not a valid parameter for DomainContextHandler\"\n                .format(name), OrangeDeprecationWarning\n            )\n\n    def encode_domain(self, domain):\n        \"\"\"\n        domain: Orange.data.domain to encode\n        return: dict mapping attribute name to type or list of values\n                (based on the value of self.match_values attribute)\n        \"\"\"\n\n        match = self.match_values\n        encode = self.encode_variables\n        if match == self.MATCH_VALUES_CLASS:\n            attributes = encode(domain.attributes, False)\n            attributes.update(encode(domain.class_vars, True))\n        else:\n            attributes = encode(domain.variables, match == self.MATCH_VALUES_ALL)\n\n        metas = encode(domain.metas, match == self.MATCH_VALUES_ALL)\n\n        return attributes, metas\n\n    @staticmethod\n    def encode_variables(attributes, encode_values):\n        \"\"\"Encode variables to a list mapping name to variable type\n        or a list of values.\"\"\"\n\n        if not encode_values:\n            return {v.name: vartype(v) for v in attributes}\n\n        return {v.name: v.values if v.is_discrete else vartype(v)\n                for v in attributes}\n\n    def new_context(self, domain, attributes, metas):\n        \"\"\"Create a new context.\"\"\"\n        context = super().new_context()\n        context.attributes = attributes\n        context.metas = metas\n        return context\n\n    def open_context(self, widget, domain):\n        if domain is None:\n            return None, False\n\n        if not isinstance(domain, Domain):\n            domain = domain.domain\n\n        super().open_context(widget, domain, *self.encode_domain(domain))\n\n    def filter_value(self, setting, data, domain, attrs, metas):\n        value = data.get(setting.name, None)\n        if isinstance(value, list):\n            new_value = [item for item in value\n                         if self.is_valid_item(setting, item, attrs, metas)]\n            data[setting.name] = new_value\n        elif value is not None:\n            if (value[1] >= 0 and\n                    not self._var_exists(setting, value, attrs, metas)):\n                del data[setting.name]\n\n    def settings_to_widget(self, widget, domain, *args):\n        context = widget.current_context\n        if context is None:\n            return\n\n        widget.retrieveSpecificSettings()\n\n        for setting, data, instance in \\\n                self.provider.traverse_settings(data=context.values, instance=widget):\n            if not isinstance(setting, ContextSetting) or setting.name not in data:\n                continue\n\n            value = self.decode_setting(setting, data[setting.name], domain)\n            _apply_setting(setting, instance, value)\n\n    @staticmethod\n    def encode_variable(var):\n        return var.name, 100 + vartype(var)\n\n    def encode_setting(self, context, setting, value):\n        if isinstance(value, list):\n            if all(e is None or isinstance(e, Variable) for e in value) \\\n                    and any(e is not None for e in value):\n                return [None if e is None else self.encode_variable(e)\n                        for e in value], -3\n            else:\n                return copy.copy(value)\n\n        if isinstance(setting, ContextSetting):\n            if isinstance(value, str):\n                if not setting.exclude_attributes and value in context.attributes:\n                    return value, context.attributes[value]\n                if not setting.exclude_metas and value in context.metas:\n                    return value, context.metas[value]\n            elif isinstance(value, Variable):\n                return self.encode_variable(value)\n\n        return copy.copy(value), -2\n\n    def decode_setting(self, setting, value, domain=None):\n        if isinstance(value, tuple):\n            if value[1] == -3:\n                return [None if e is None else domain[e[0]] for e in value[0]]\n            if value[1] >= 100:\n                if domain is None:\n                    raise ValueError(\"Cannot decode variable without domain\")\n                return domain[value[0]]\n            return value[0]\n        else:\n            return value\n\n    @staticmethod\n    def _var_exists(setting, value, attributes, metas):\n        if not isinstance(value, tuple) or len(value) != 2:\n            return False\n\n        attr_name, attr_type = value\n        if attr_type >= 100:\n            attr_type -= 100\n        return (not setting.exclude_attributes and\n                attributes.get(attr_name, -1) == attr_type or\n                not setting.exclude_metas and\n                metas.get(attr_name, -1) == attr_type)\n\n    def match(self, context, domain, attrs, metas):\n        if (attrs, metas) == (context.attributes, context.metas):\n            return self.PERFECT_MATCH\n\n        matches = []\n        try:\n            for setting, data, _ in \\\n                    self.provider.traverse_settings(data=context.values):\n                if not isinstance(setting, ContextSetting):\n                    continue\n                value = data.get(setting.name, None)\n\n                if isinstance(value, list):\n                    matches.append(\n                        self.match_list(setting, value, context, attrs, metas))\n                elif isinstance(value, tuple) \\\n                        and len(value) == 2 \\\n                        and isinstance(value[0], list) \\\n                        and value[1] == -3:\n                    matches.append(\n                        self.match_list(setting, value[0], context, attrs, metas))\n                elif value is not None:\n                    matches.append(\n                        self.match_value(setting, value, attrs, metas))\n        except IncompatibleContext:\n            return self.NO_MATCH\n\n        matches.append((0, 0))\n        matched, available = [sum(m) for m in zip(*matches)]\n\n        return matched / available if available else 0.1\n\n    def match_list(self, setting, value, context, attrs, metas):\n        \"\"\"Match a list of values with the given context.\n        returns a tuple containing number of matched and all values.\n        \"\"\"\n        matched = 0\n        for i, item in enumerate(value):\n            if self.is_valid_item(setting, item, attrs, metas):\n                matched += 1\n            elif setting.required == ContextSetting.REQUIRED:\n                raise IncompatibleContext()\n        return matched, len(value)\n\n    def match_value(self, setting, value, attrs, metas):\n        \"\"\"Match a single value \"\"\"\n        if value[1] < 0:\n            return 0, 0\n\n        if self._var_exists(setting, value, attrs, metas):\n            return 1, 1\n        elif setting.required == setting.OPTIONAL:\n            return 0, 1\n        else:\n            raise IncompatibleContext()\n\n    def is_valid_item(self, setting, item, attrs, metas):\n        \"\"\"Return True if given item can be used with attrs and metas\n\n        Subclasses can override this method to checks data in alternative\n        representations.\n        \"\"\"\n        if not isinstance(item, tuple):\n            return True\n        return self._var_exists(setting, item, attrs, metas)\n\n\nclass IncompatibleContext(Exception):\n    \"\"\"Raised when a required variable in context is not available in data.\"\"\"\n    pass\n\n\nclass ClassValuesContextHandler(ContextHandler):\n    \"\"\"Context handler used for widgets that work with\n    a single discrete variable\"\"\"\n\n    def open_context(self, widget, classes):\n        if isinstance(classes, Variable):\n            if classes.is_discrete:\n                classes = classes.values\n            else:\n                classes = None\n\n        super().open_context(widget, classes)\n\n    def new_context(self, classes):\n        context = super().new_context()\n        context.classes = classes\n        return context\n\n    def match(self, context, classes):\n        if isinstance(classes, Variable) and classes.is_continuous:\n            return (self.PERFECT_MATCH if context.classes is None\n                    else self.NO_MATCH)\n        else:\n            return (self.PERFECT_MATCH if context.classes == classes\n                    else self.NO_MATCH)\n\n\nclass PerfectDomainContextHandler(DomainContextHandler):\n    \"\"\"Context handler that matches a context only when\n    the same domain is available.\n\n    It uses a different encoding than the DomainContextHandler.\n    \"\"\"\n\n    def new_context(self, domain, attributes, class_vars, metas):\n        \"\"\"Same as DomainContextHandler, but also store class_vars\"\"\"\n        context = super().new_context(domain, attributes, metas)\n        context.class_vars = class_vars\n        return context\n\n    def clone_context(self, old_context, *args):\n        \"\"\"Copy of context is always valid, since widgets are using\n        the same domain.\"\"\"\n        context = self.new_context(*args)\n        context.values = copy.deepcopy(old_context.values)\n        return context\n\n    def encode_domain(self, domain):\n        \"\"\"Encode domain into tuples (name, type)\n        A tuple is returned for each of attributes, class_vars and metas.\n        \"\"\"\n\n        if self.match_values == self.MATCH_VALUES_ALL:\n            def _encode(attrs):\n                return tuple((v.name, list(v.values) if v.is_discrete else vartype(v))\n                             for v in attrs)\n        else:\n            def _encode(attrs):\n                return tuple((v.name, vartype(v)) for v in attrs)\n        return (_encode(domain.attributes),\n                _encode(domain.class_vars),\n                _encode(domain.metas))\n\n    def match(self, context, domain, attributes, class_vars, metas):\n        \"\"\"Context only matches when domains are the same\"\"\"\n\n        return (self.PERFECT_MATCH\n                if (context.attributes == attributes and\n                    context.class_vars == class_vars and\n                    context.metas == metas)\n                else self.NO_MATCH)\n\n    def encode_setting(self, context, setting, value):\n        \"\"\"Same as is domain context handler, but handles separately stored\n        class_vars.\"\"\"\n\n        if isinstance(setting, ContextSetting) and isinstance(value, str):\n\n            def _candidate_variables():\n                if not setting.exclude_attributes:\n                    yield from itertools.chain(context.attributes,\n                                               context.class_vars)\n                if not setting.exclude_metas:\n                    yield from context.metas\n\n            for aname, atype in _candidate_variables():\n                if aname == value:\n                    return value, atype\n\n            return value, -1\n        else:\n            return super().encode_setting(context, setting, value)\n\n\nclass SettingsPrinter(pprint.PrettyPrinter):\n    \"\"\"Pretty Printer that knows how to properly format Contexts.\"\"\"\n\n    def _format(self, obj, stream, indent, allowance, context, level):\n        if not isinstance(obj, Context):\n            return super()._format(obj, stream, indent,\n                                   allowance, context, level)\n\n        stream.write(\"Context(\")\n        for key, value in sorted(obj.__dict__.items(), key=itemgetter(0)):\n            if key == \"values\":\n                continue\n            stream.write(key)\n            stream.write(\"=\")\n            stream.write(self._repr(value, context, level + 1))\n            stream.write(\",\\n\")\n            stream.write(\" \" * (indent + 8))\n        stream.write(\"values=\")\n        stream.write(\" \")\n        self._format(obj.values, stream, indent+15,\n                     allowance+1, context, level + 1)\n        stream.write(\")\")\n\n\ndef rename_setting(settings, old_name, new_name):\n    \"\"\"\n    Rename setting from `old_name` to `new_name`. Used in migrations.\n\n    The argument `settings` can be `dict` or `Context`.\n    \"\"\"\n    if isinstance(settings, Context):\n        rename_setting(settings.values, old_name, new_name)\n    else:\n        settings[new_name] = settings.pop(old_name)\n\n\ndef migrate_str_to_variable(settings, names=None, none_placeholder=None):\n    \"\"\"\n    Change variables stored as `(str, int)` to `(Variable, int)`.\n\n    Args:\n        settings (Context): context that is being migrated\n        names (sequence): names of settings to be migrated. If omitted,\n            all settings with values `(str, int)` are migrated.\n    \"\"\"\n    def _fix(name):\n        var, vartype = settings.values[name]\n        if 0 <= vartype <= 100:\n            settings.values[name] = (var, 100 + vartype)\n        elif var == none_placeholder and vartype == -2:\n            settings.values[name] = None\n\n    if names is None:\n        for name, setting in settings.values.items():\n            if isinstance(setting, tuple) and len(setting) == 2 and \\\n                    isinstance(setting[0], str) and isinstance(setting[1], int):\n                _fix(name)\n    elif isinstance(names, str):\n        _fix(names)\n    else:\n        for name in names:\n            _fix(name)\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:** `encode_setting` Raises TypeError When Handling Deprecated String Variable Settings

**Description:**
When attempting to encode settings that use variables stored as strings, the `encode_setting` method raises a `TypeError` due to a missing required argument. This issue prevents the proper handling of deprecated string-based variable settings and disrupts the encoding process.

**Example Code:**
```python
from unittest.mock import Mock
from Orange.widgets.settings import DomainContextHandler, ContextSetting

context = Mock()
context.attributes = {"foo": 2}
context.metas = {}
setting = ContextSetting("")
setting.name = "setting_name"

DomainContextHandler.encode_setting(context, setting, "foo")
```

**Expected Behavior:**
Using string-based variable settings should trigger a deprecation warning and allow the settings to be encoded correctly without errors.

**Actual Behavior:**
Executing the encoding process raises the following error:
```
TypeError: encode_setting() missing 1 required positional argument: 'value'
```
This error occurs because the `encode_setting` method is not receiving all necessary arguments, preventing the encoding of deprecated string variable settings.

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

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

--- BEGIN FILE ---
```
### Orange/widgets/settings.py
"""Widget Settings and Settings Handlers

Settings are used to declare widget attributes that persist through sessions.
When widget is removed or saved to a schema file, its settings are packed,
serialized and stored. When a new widget is created, values of attributes
marked as settings are read from disk. When schema is loaded, attribute values
are set to one stored in schema.

Each widget has its own SettingsHandler that takes care of serializing and
storing of settings and SettingProvider that is incharge of reading and
writing the setting values.

All widgets extending from OWWidget use SettingsHandler, unless they
declare otherwise. SettingsHandler ensures that setting attributes
are replaced with default (last used) setting values when the widget is
initialized and stored when the widget is removed.

Widgets with settings whose values depend on the widget inputs use
settings handlers based on ContextHandler. These handlers have two
additional methods, open_context and close_context.

open_context is called when widgets receives new data. It finds a suitable
context and sets the widget attributes to the values stored in context.
If no suitable context exists, a new one is created and values from widget
are copied to it.

close_context stores values that were last used on the widget to the context
so they can be used alter. It should be called before widget starts modifying
(initializing) the value of the setting attributes.
"""

import sys
import copy
import itertools
import os
import logging
import pickle
import pprint
import time
import warnings
from operator import itemgetter
from typing import Any

from Orange.data import Domain, Variable
from Orange.misc.environ import widget_settings_dir
from Orange.util import OrangeDeprecationWarning
from Orange.widgets.utils import vartype
from Orange.widgets.gui import OWComponent

log = logging.getLogger(__name__)

__all__ = ["Setting", "SettingsHandler", "SettingProvider",
           "ContextSetting", "ContextHandler",
           "DomainContextHandler", "PerfectDomainContextHandler",
           "ClassValuesContextHandler", "widget_settings_dir",
           "IncompatibleContext"]

_IMMUTABLES = (str, int, bytes, bool, float, tuple)

VERSION_KEY = "__version__"


class Setting:
    """Description of a setting.
    """

    # Settings are automatically persisted to disk
    packable = True

    # Setting is only persisted to schema (default value does not change)
    schema_only = False

    def __new__(cls, default, *args, **kwargs):
        """A misleading docstring for providing type hints for Settings

        :type: default: T
        :rtype: T
        """
        return super().__new__(cls)

    def __init__(self, default, **data):
        self.name = None  # Name gets set in widget's meta class
        self.default = default
        self.__dict__.update(data)

    def __str__(self):
        return '{0} "{1}"'.format(self.__class__.__name__, self.name)

    __repr__ = __str__

    def __getnewargs__(self):
        return (self.default, )


# Pylint ignores type annotations in assignments. For
#
#    x: int = Setting(0)
#
# it ignores `int` and assumes x is of type `Setting`. Annotations in
# comments ( # type: int) also don't work. The only way to annotate x is
#
#    x: int
#    x = Setting(0)
#
# but we don't want to clutter the code with extra lines of annotations. Hence
# we disable checking the type of `Setting` by confusing pylint with an extra
# definition that is never executed.
if 1 == 0:
    class Setting:  # pylint: disable=function-redefined
        pass


def _apply_setting(setting: Setting, instance: OWComponent, value: Any):
    """
    Set `setting` of widget `instance` to the given `value`, in place if
    possible.

    If old and new values are of the same type, and the type is either a list
    or has methods `clear` and `update`, setting is updated in place. Otherwise
    the function calls `setattr`.
    """
    target = getattr(instance, setting.name, None)
    if type(target) is type(value):
        if isinstance(value, list):
            target[:] = value
            return
        elif hasattr(value, "clear") and hasattr(value, "update"):
            target.clear()
            target.update(value)
            return
    setattr(instance, setting.name, value)


class SettingProvider:
    """A hierarchical structure keeping track of settings belonging to
    a class and child setting providers.

    At instantiation, it creates a dict of all Setting and SettingProvider
    members of the class. This dict is used to get/set values of settings
    from/to the instances of the class this provider belongs to.
    """

    def __init__(self, provider_class):
        """ Construct a new instance of SettingProvider.

        Traverse provider_class members and store all instances of
        Setting and SettingProvider.

        Parameters
        ----------
        provider_class : class
            class containing settings definitions
        """
        self.name = ""
        self.provider_class = provider_class
        self.providers = {}
        """:type: dict[str, SettingProvider]"""
        self.settings = {}
        """:type: dict[str, Setting]"""
        self.initialization_data = None

        for name in dir(provider_class):
            value = getattr(provider_class, name, None)
            if isinstance(value, Setting):
                value = copy.deepcopy(value)
                value.name = name
                self.settings[name] = value
            if isinstance(value, SettingProvider):
                value = copy.deepcopy(value)
                value.name = name
                self.providers[name] = value

    def initialize(self, instance, data=None):
        """Initialize instance settings to their default values.

        Mutable values are (shallow) copied before they are assigned to the
        widget. Immutable are used as-is.

        Parameters
        ----------
        instance : OWWidget
            widget instance to initialize
        data : Optional[dict]
            optional data used to override the defaults
            (used when settings are loaded from schema)
        """
        if data is None and self.initialization_data is not None:
            data = self.initialization_data

        self._initialize_settings(instance, data)
        self._initialize_providers(instance, data)

    def _initialize_settings(self, instance, data):
        if data is None:
            data = {}
        for name, setting in self.settings.items():
            value = data.get(name, setting.default)
            if isinstance(value, _IMMUTABLES):
                setattr(instance, name, value)
            else:
                setattr(instance, name, copy.copy(value))

    def _initialize_providers(self, instance, data):
        if not data:
            return

        for name, provider in self.providers.items():
            if name not in data:
                continue

            member = getattr(instance, name, None)
            if member is None or isinstance(member, SettingProvider):
                provider.store_initialization_data(data[name])
            else:
                provider.initialize(member, data[name])

    def store_initialization_data(self, initialization_data):
        """Store initialization data for later use.

        Used when settings handler is initialized, but member for this
        provider does not exists yet (because handler.initialize is called in
        __new__, but member will be created in __init__.

        Parameters
        ----------
        initialization_data : dict
            data to be used for initialization when the component is created
        """
        self.initialization_data = initialization_data

    @staticmethod
    def _default_packer(setting, instance):
        """A simple packet that yields setting name and value.

        Parameters
        ----------
        setting : Setting
        instance : OWWidget
        """
        if setting.packable:
            if hasattr(instance, setting.name):
                yield setting.name, getattr(instance, setting.name)
            else:
                warnings.warn("{0} is declared as setting on {1} "
                              "but not present on instance."
                              .format(setting.name, instance))

    def pack(self, instance, packer=None):
        """Pack instance settings in a name:value dict.

        Parameters
        ----------
        instance : OWWidget
            widget instance
        packer: callable (Setting, OWWidget) -> Generator[(str, object)]
            optional packing function
            it will be called with setting and instance parameters and
            should yield (name, value) pairs that will be added to the
            packed_settings.
        """
        if packer is None:
            packer = self._default_packer

        packed_settings = dict(itertools.chain(
            *(packer(setting, instance) for setting in self.settings.values())
        ))

        packed_settings.update({
            name: provider.pack(getattr(instance, name), packer)
            for name, provider in self.providers.items()
            if hasattr(instance, name)
        })
        return packed_settings

    def unpack(self, instance, data):
        """Restore settings from data to the instance.

        Parameters
        ----------
        instance : OWWidget
            instance to restore settings to
        data : dict
            packed data
        """
        for setting, _data, inst in self.traverse_settings(data, instance):
            if setting.name in _data and inst is not None:
                _apply_setting(setting, inst, _data[setting.name])

    def get_provider(self, provider_class):
        """Return provider for provider_class.

        If this provider matches, return it, otherwise pass
        the call to child providers.

        Parameters
        ----------
        provider_class : class
        """
        if issubclass(provider_class, self.provider_class):
            return self

        for subprovider in self.providers.values():
            provider = subprovider.get_provider(provider_class)
            if provider:
                return provider
        return None

    def traverse_settings(self, data=None, instance=None):
        """Generator of tuples (setting, data, instance) for each setting
        in this and child providers..

        Parameters
        ----------
        data : dict
            dictionary with setting values
        instance : OWWidget
            instance matching setting_provider
        """
        data = data if data is not None else {}

        for setting in self.settings.values():
            yield setting, data, instance

        for provider in self.providers.values():
            data_ = data.get(provider.name, {})
            instance_ = getattr(instance, provider.name, None)
            for setting, component_data, component_instance in \
                    provider.traverse_settings(data_, instance_):
                yield setting, component_data, component_instance


class SettingsHandler:
    """Reads widget setting files and passes them to appropriate providers."""

    def __init__(self):
        """Create a setting handler template.

        Used in class definition. Bound instance will be created
        when SettingsHandler.create is called.
        """
        self.widget_class = None
        self.provider = None
        """:type: SettingProvider"""
        self.defaults = {}
        self.known_settings = {}

    @staticmethod
    def create(widget_class, template=None):
        """Create a new settings handler based on the template and bind it to
        widget_class.

        Parameters
        ----------
        widget_class : class
        template : SettingsHandler
            SettingsHandler to copy setup from

        Returns
        -------
        SettingsHandler
        """

        if template is None:
            template = SettingsHandler()

        setting_handler = copy.copy(template)
        setting_handler.defaults = {}
        setting_handler.bind(widget_class)
        return setting_handler

    def bind(self, widget_class):
        """Bind settings handler instance to widget_class.

        Parameters
        ----------
        widget_class : class
        """
        self.widget_class = widget_class
        self.provider = SettingProvider(widget_class)
        self.known_settings = {}
        self.analyze_settings(self.provider, "")
        self.read_defaults()

    def analyze_settings(self, provider, prefix):
        """Traverse through all settings known to the provider
        and analyze each of them.

        Parameters
        ----------
        provider : SettingProvider
        prefix : str
            prefix the provider is registered to handle
        """
        for setting in provider.settings.values():
            self.analyze_setting(prefix, setting)

        for name, sub_provider in provider.providers.items():
            new_prefix = '{0}{1}.'.format(prefix or '', name)
            self.analyze_settings(sub_provider, new_prefix)

    def analyze_setting(self, prefix, setting):
        """Perform any initialization task related to setting.

        Parameters
        ----------
        prefix : str
        setting : Setting
        """
        self.known_settings[prefix + setting.name] = setting

    def read_defaults(self):
        """Read (global) defaults for this widget class from a file.
        Opens a file and calls :obj:`read_defaults_file`. Derived classes
        should overload the latter."""
        filename = self._get_settings_filename()
        if os.path.isfile(filename):
            settings_file = open(filename, "rb")
            try:
                self.read_defaults_file(settings_file)
            # Unpickling exceptions can be of any type
            # pylint: disable=broad-except
            except Exception as ex:
                warnings.warn("Could not read defaults for widget {0}\n"
                              "The following error occurred:\n\n{1}"
                              .format(self.widget_class, ex))
            finally:
                settings_file.close()

    def read_defaults_file(self, settings_file):
        """Read (global) defaults for this widget class from a file.

        Parameters
        ----------
        settings_file : file-like object
        """
        defaults = pickle.load(settings_file)
        self.defaults = {
            key: value
            for key, value in defaults.items()
            if not isinstance(value, Setting)
        }
        self._migrate_settings(self.defaults)

    def write_defaults(self):
        """Write (global) defaults for this widget class to a file.
        Opens a file and calls :obj:`write_defaults_file`. Derived classes
        should overload the latter."""
        filename = self._get_settings_filename()
        os.makedirs(os.path.dirname(filename), exist_ok=True)
        try:
            settings_file = open(filename, "wb")
            try:
                self.write_defaults_file(settings_file)
            except (EOFError, IOError, pickle.PicklingError) as ex:
                log.error("Could not write default settings for %s (%s).",
                          self.widget_class, type(ex).__name__)
                settings_file.close()
                os.remove(filename)
            else:
                settings_file.close()
        except PermissionError as ex:
            log.error("Could not write default settings for %s (%s).",
                      self.widget_class, type(ex).__name__)

    def write_defaults_file(self, settings_file):
        """Write defaults for this widget class to a file

        Parameters
        ----------
        settings_file : file-like object
        """
        defaults = dict(self.defaults)
        defaults[VERSION_KEY] = self.widget_class.settings_version
        pickle.dump(defaults, settings_file, -1)

    def _get_settings_filename(self):
        """Return the name of the file with default settings for the widget"""
        return os.path.join(widget_settings_dir(),
                            "{0.__module__}.{0.__qualname__}.pickle"
                            .format(self.widget_class))

    def initialize(self, instance, data=None):
        """
        Initialize widget's settings.

        Replace all instance settings with their default values.

        Parameters
        ----------
        instance : OWWidget
        data : dict or bytes that unpickle into a dict
            values used to override the defaults
        """
        provider = self._select_provider(instance)

        if isinstance(data, bytes):
            data = pickle.loads(data)
        self._migrate_settings(data)

        if provider is self.provider:
            data = self._add_defaults(data)

        provider.initialize(instance, data)

    def _migrate_settings(self, settings):
        """Ask widget to migrate settings to the latest version."""
        if settings:
            try:
                self.widget_class.migrate_settings(
                    settings, settings.pop(VERSION_KEY, 0))
            except Exception:  # pylint: disable=broad-except
                sys.excepthook(*sys.exc_info())
                settings.clear()

    def _select_provider(self, instance):
        provider = self.provider.get_provider(instance.__class__)
        if provider is None:
            message = "{0} has not been declared as setting provider in {1}. " \
                      "Settings will not be saved/loaded properly. Defaults will be used instead." \
                      .format(instance.__class__, self.widget_class)
            warnings.warn(message)
            provider = SettingProvider(instance.__class__)
        return provider

    def _add_defaults(self, data):
        if data is None:
            return self.defaults

        new_data = self.defaults.copy()
        new_data.update(data)
        return new_data

    def _prepare_defaults(self, widget):
        self.defaults = self.provider.pack(widget)
        for setting, data, _ in self.provider.traverse_settings(data=self.defaults):
            if setting.schema_only:
                data.pop(setting.name, None)

    def pack_data(self, widget):
        """
        Pack the settings for the given widget. This method is used when
        saving schema, so that when the schema is reloaded the widget is
        initialized with its proper data and not the class-based defaults.
        See :obj:`SettingsHandler.initialize` for detailed explanation of its
        use.

        Inherited classes add other data, in particular widget-specific
        local contexts.

        Parameters
        ----------
        widget : OWWidget
        """
        widget.settingsAboutToBePacked.emit()
        packed_settings = self.provider.pack(widget)
        packed_settings[VERSION_KEY] = self.widget_class.settings_version
        return packed_settings

    def update_defaults(self, widget):
        """
        Writes widget instance's settings to class defaults. Called when the
        widget is deleted.

        Parameters
        ----------
        widget : OWWidget
        """
        widget.settingsAboutToBePacked.emit()
        self._prepare_defaults(widget)
        self.write_defaults()

    def fast_save(self, widget, name, value):
        """Store the (changed) widget's setting immediately to the context.

        Parameters
        ----------
        widget : OWWidget
        name : str
        value : object

        """
        if name in self.known_settings:
            setting = self.known_settings[name]
            if not setting.schema_only:
                setting.default = value

    def reset_settings(self, instance):
        """Reset widget settings to defaults

        Parameters
        ----------
        instance : OWWidget
        """
        for setting, _, inst in self.provider.traverse_settings(instance=instance):
            if setting.packable:
                _apply_setting(setting, inst, setting.default)


class ContextSetting(Setting):
    """Description of a context dependent setting"""

    OPTIONAL = 0
    REQUIRED = 2

    # Context settings are not persisted, but are stored in context instead.
    packable = False

    # These flags are not general - they assume that the setting has to do
    # something with the attributes. Large majority does, so this greatly
    # simplifies the declaration of settings in widget at no (visible)
    # cost to those settings that don't need it
    def __init__(self, default, *, required=2,
                 exclude_attributes=False, exclude_metas=False, **data):
        super().__init__(default, **data)
        self.exclude_attributes = exclude_attributes
        self.exclude_metas = exclude_metas
        self.required = required


class Context:
    """Class for data thad defines context and
    values that should be applied to widget if given context
    is encountered."""
    def __init__(self, **argkw):
        self.time = time.time()
        self.values = {}
        self.__dict__.update(argkw)

    def __getstate__(self):
        state = dict(self.__dict__)
        for nc in getattr(self, "no_copy", []):
            if nc in state:
                del state[nc]
        return state


class ContextHandler(SettingsHandler):
    """Base class for setting handlers that can handle contexts.

    Classes deriving from it need to implement method `match`.
    """

    NO_MATCH = 0
    PERFECT_MATCH = 2

    MAX_SAVED_CONTEXTS = 50

    def __init__(self):
        super().__init__()
        self.global_contexts = []
        self.known_settings = {}

    def initialize(self, instance, data=None):
        """Initialize the widget: call the inherited initialization and
        add an attribute 'context_settings' to the widget. This method
        does not open a context."""
        instance.current_context = None
        super().initialize(instance, data)
        if data and "context_settings" in data:
            instance.context_settings = data["context_settings"]
            self._migrate_contexts(instance.context_settings)
        else:
            instance.context_settings = []

    def read_defaults_file(self, settings_file):
        """Call the inherited method, then read global context from the
           pickle."""
        super().read_defaults_file(settings_file)
        self.global_contexts = pickle.load(settings_file)
        self._migrate_contexts(self.global_contexts)

    def _migrate_contexts(self, contexts):
        i = 0
        while i < len(contexts):
            context = contexts[i]
            try:
                self.widget_class.migrate_context(
                    context, context.values.pop(VERSION_KEY, 0))
            except IncompatibleContext:
                del contexts[i]
            except Exception:  # pylint: disable=broad-except
                sys.excepthook(*sys.exc_info())
                del contexts[i]
            else:
                i += 1

    def write_defaults_file(self, settings_file):
        """Call the inherited method, then add global context to the pickle."""
        super().write_defaults_file(settings_file)

        def add_version(context):
            context = copy.copy(context)
            context.values = dict(context.values)
            context.values[VERSION_KEY] = self.widget_class.settings_version
            return context

        pickle.dump([add_version(context) for context in self.global_contexts],
                    settings_file, -1)

    def pack_data(self, widget):
        """Call the inherited method, then add local contexts to the dict."""
        data = super().pack_data(widget)
        self.settings_from_widget(widget)
        context_settings = [copy.copy(context) for context in
                            widget.context_settings]
        for context in context_settings:
            context.values[VERSION_KEY] = self.widget_class.settings_version
        data["context_settings"] = context_settings
        return data

    def update_defaults(self, widget):
        """
        Reimplemented from SettingsHandler

        Merge the widgets local contexts into the global contexts and persist
        the settings (including the contexts) to disk.
        """
        widget.settingsAboutToBePacked.emit()
        self.settings_from_widget(widget)
        globs = self.global_contexts
        assert widget.context_settings is not globs
        ids = {id(c) for c in globs}
        globs += (c for c in widget.context_settings if id(c) not in ids)
        globs.sort(key=lambda c: -c.time)
        del globs[self.MAX_SAVED_CONTEXTS:]

        # Save non-context settings. Do not call super().update_defaults, so that
        # settingsAboutToBePacked is emitted once.
        self._prepare_defaults(widget)
        self.write_defaults()

    def new_context(self, *args):
        """Create a new context."""
        return Context()

    def open_context(self, widget, *args):
        """Open a context by finding one and setting the widget data or
        creating one and fill with the data from the widget."""
        widget.current_context, is_new = \
            self.find_or_create_context(widget, *args)
        if is_new:
            try:
                self.settings_from_widget(widget, *args)
            except TypeError:
                warnings.warn("settings_from_widget in {} does not accept *args.\n"
                              "Support for this will be dropped in Orange 3.10"
                              .format(type(self)),
                              DeprecationWarning)
                self.settings_from_widget(widget)
        else:
            try:
                self.settings_to_widget(widget, *args)
            except TypeError:
                warnings.warn("settings_to_widget {} does not accept *args.\n"
                              "Support for this will be dropped in Orange 3.10"
                              .format(type(self)),
                              DeprecationWarning)
                self.settings_to_widget(widget)

    def match(self, context, *args):
        """Return the degree to which the stored `context` matches the data
        passed in additional arguments).
        When match returns 0 (ContextHandler.NO_MATCH), the context will not
        be used. When it returns ContextHandler.PERFECT_MATCH, the context
        is a perfect match so no further search is necessary.

        If imperfect matching is not desired, match should only
        return ContextHandler.NO_MATCH or ContextHandler.PERFECT_MATCH.

        Derived classes must overload this method.
        """
        raise NotImplementedError

    def find_or_create_context(self, widget, *args):
        """Find the best matching context or create a new one if nothing
        useful is found. The returned context is moved to or added to the top
        of the context list."""

        # First search the contexts that were already used in this widget instance
        best_context, best_score = self.find_context(widget.context_settings, args, move_up=True)
        # If the exact data was used, reuse the context
        if best_score == self.PERFECT_MATCH:
            return best_context, False

        # Otherwise check if a better match is available in global_contexts
        best_context, best_score = self.find_context(self.global_contexts, args,
                                                     best_score, best_context)
        if best_context:
            context = self.clone_context(best_context, *args)
        else:
            context = self.new_context(*args)
        # Store context in widget instance. It will be pushed to global_contexts
        # when (if) update defaults is called.
        self.add_context(widget.context_settings, context)
        return context, best_context is None

    def find_context(self, known_contexts, args, best_score=0, best_context=None, move_up=False):
        """Search the given list of contexts and return the context
         which best matches the given args.

        best_score and best_context can be used to provide base_values.
        """

        for i, context in enumerate(known_contexts):
            score = self.match(context, *args)
            if score == self.PERFECT_MATCH:
                if move_up:
                    self.move_context_up(known_contexts, i)
                return context, score
            if score > best_score:  # NO_MATCH is not OK!
                best_context, best_score = context, score
        return best_context, best_score

    @staticmethod
    def move_context_up(contexts, index):
        """Move the context to the top of the list and set
        the timestamp to current."""
        setting = contexts.pop(index)
        setting.time = time.time()
        contexts.insert(0, setting)

    def add_context(self, contexts, setting):
        """Add the context to the top of the list."""
        contexts.insert(0, setting)
        del contexts[self.MAX_SAVED_CONTEXTS:]

    def clone_context(self, old_context, *args):
        """Construct a copy of the context settings suitable for the context
        described by additional arguments. The method is called by
        find_or_create_context with the same arguments. A class that overloads
        :obj:`match` to accept additional arguments must also overload
        :obj:`clone_context`."""
        context = self.new_context(*args)
        context.values = copy.deepcopy(old_context.values)

        traverse = self.provider.traverse_settings
        for setting, data, _ in traverse(data=context.values):
            if not isinstance(setting, ContextSetting):
                continue

            self.filter_value(setting, data, *args)
        return context

    @staticmethod
    def filter_value(setting, data, *args):
        """Remove values related to setting that are invalid given args."""

    def close_context(self, widget):
        """Close the context by calling :obj:`settings_from_widget` to write
        any relevant widget settings to the context."""
        if widget.current_context is None:
            return

        self.settings_from_widget(widget)
        widget.current_context = None

    def settings_to_widget(self, widget, *args):
        """Apply context settings stored in currently opened context
        to the widget.
        """
        context = widget.current_context
        if context is None:
            return

        widget.retrieveSpecificSettings()

        for setting, data, instance in \
                self.provider.traverse_settings(data=context.values, instance=widget):
            if not isinstance(setting, ContextSetting) or setting.name not in data:
                continue
            value = self.decode_setting(setting, data[setting.name])
            _apply_setting(setting, instance, value)

    def settings_from_widget(self, widget, *args):
        """Update the current context with the setting values from the widget.
        """

        context = widget.current_context
        if context is None:
            return

        widget.storeSpecificSettings()

        def packer(setting, instance):
            if isinstance(setting, ContextSetting) and hasattr(instance, setting.name):
                value = getattr(instance, setting.name)
                yield setting.name, self.encode_setting(context, setting, value)

        context.values = self.provider.pack(widget, packer=packer)

    def fast_save(self, widget, name, value):
        """Update value of `name` setting in the current context to `value`
        """
        setting = self.known_settings.get(name)
        if isinstance(setting, ContextSetting):
            context = widget.current_context
            if context is None:
                return

            value = self.encode_setting(context, setting, value)
            self.update_packed_data(context.values, name, value)
        else:
            super().fast_save(widget, name, value)

    @staticmethod
    def update_packed_data(data, name, value):
        """Updates setting value stored in data dict"""

        *prefixes, name = name.split('.')
        for prefix in prefixes:
            data = data.setdefault(prefix, {})
        data[name] = value

    def encode_setting(self, context, setting, value):
        """Encode value to be stored in settings dict"""
        return copy.copy(value)

    def decode_setting(self, setting, value):
        """Decode settings value from the setting dict format"""
        return value


class DomainContextHandler(ContextHandler):
    """Context handler for widgets with settings that depend on
    the input dataset. Suitable settings are selected based on the
    data domain."""

    MATCH_VALUES_NONE, MATCH_VALUES_CLASS, MATCH_VALUES_ALL = range(3)

    def __init__(self, *, match_values=0, **kwargs):
        super().__init__()
        self.match_values = match_values

        for name in kwargs:
            warnings.warn(
                "{} is not a valid parameter for DomainContextHandler"
                .format(name), OrangeDeprecationWarning
            )

    def encode_domain(self, domain):
        """
        domain: Orange.data.domain to encode
        return: dict mapping attribute name to type or list of values
                (based on the value of self.match_values attribute)
        """

        match = self.match_values
        encode = self.encode_variables
        if match == self.MATCH_VALUES_CLASS:
            attributes = encode(domain.attributes, False)
            attributes.update(encode(domain.class_vars, True))
        else:
            attributes = encode(domain.variables, match == self.MATCH_VALUES_ALL)

        metas = encode(domain.metas, match == self.MATCH_VALUES_ALL)

        return attributes, metas

    @staticmethod
    def encode_variables(attributes, encode_values):
        """Encode variables to a list mapping name to variable type
        or a list of values."""

        if not encode_values:
            return {v.name: vartype(v) for v in attributes}

        return {v.name: v.values if v.is_discrete else vartype(v)
                for v in attributes}

    def new_context(self, domain, attributes, metas):
        """Create a new context."""
        context = super().new_context()
        context.attributes = attributes
        context.metas = metas
        return context

    def open_context(self, widget, domain):
        if domain is None:
            return None, False

        if not isinstance(domain, Domain):
            domain = domain.domain

        super().open_context(widget, domain, *self.encode_domain(domain))

    def filter_value(self, setting, data, domain, attrs, metas):
        value = data.get(setting.name, None)
        if isinstance(value, list):
            new_value = [item for item in value
                         if self.is_valid_item(setting, item, attrs, metas)]
            data[setting.name] = new_value
        elif value is not None:
            if (value[1] >= 0 and
                    not self._var_exists(setting, value, attrs, metas)):
                del data[setting.name]

    def settings_to_widget(self, widget, domain, *args):
        context = widget.current_context
        if context is None:
            return

        widget.retrieveSpecificSettings()

        for setting, data, instance in \
                self.provider.traverse_settings(data=context.values, instance=widget):
            if not isinstance(setting, ContextSetting) or setting.name not in data:
                continue

            value = self.decode_setting(setting, data[setting.name], domain)
            _apply_setting(setting, instance, value)

    @staticmethod
    def encode_variable(var):
        return var.name, 100 + vartype(var)

    def encode_setting(self, context, setting, value):
        if isinstance(value, list):
            if all(e is None or isinstance(e, Variable) for e in value) \
                    and any(e is not None for e in value):
                return [None if e is None else self.encode_variable(e)
                        for e in value], -3
            else:
                return copy.copy(value)

        if isinstance(setting, ContextSetting):
            if isinstance(value, str):
                if not setting.exclude_attributes and value in context.attributes:
                    return value, context.attributes[value]
                if not setting.exclude_metas and value in context.metas:
                    return value, context.metas[value]
            elif isinstance(value, Variable):
                return self.encode_variable(value)

        return copy.copy(value), -2

    def decode_setting(self, setting, value, domain=None):
        if isinstance(value, tuple):
            if value[1] == -3:
                return [None if e is None else domain[e[0]] for e in value[0]]
            if value[1] >= 100:
                if domain is None:
                    raise ValueError("Cannot decode variable without domain")
                return domain[value[0]]
            return value[0]
        else:
            return value

    @staticmethod
    def _var_exists(setting, value, attributes, metas):
        if not isinstance(value, tuple) or len(value) != 2:
            return False

        attr_name, attr_type = value
        if attr_type >= 100:
            attr_type -= 100
        return (not setting.exclude_attributes and
                attributes.get(attr_name, -1) == attr_type or
                not setting.exclude_metas and
                metas.get(attr_name, -1) == attr_type)

    def match(self, context, domain, attrs, metas):
        if (attrs, metas) == (context.attributes, context.metas):
            return self.PERFECT_MATCH

        matches = []
        try:
            for setting, data, _ in \
                    self.provider.traverse_settings(data=context.values):
                if not isinstance(setting, ContextSetting):
                    continue
                value = data.get(setting.name, None)

                if isinstance(value, list):
                    matches.append(
                        self.match_list(setting, value, context, attrs, metas))
                elif isinstance(value, tuple) \
                        and len(value) == 2 \
                        and isinstance(value[0], list) \
                        and value[1] == -3:
                    matches.append(
                        self.match_list(setting, value[0], context, attrs, metas))
                elif value is not None:
                    matches.append(
                        self.match_value(setting, value, attrs, metas))
        except IncompatibleContext:
            return self.NO_MATCH

        matches.append((0, 0))
        matched, available = [sum(m) for m in zip(*matches)]

        return matched / available if available else 0.1

    def match_list(self, setting, value, context, attrs, metas):
        """Match a list of values with the given context.
        returns a tuple containing number of matched and all values.
        """
        matched = 0
        for i, item in enumerate(value):
            if self.is_valid_item(setting, item, attrs, metas):
                matched += 1
            elif setting.required == ContextSetting.REQUIRED:
                raise IncompatibleContext()
        return matched, len(value)

    def match_value(self, setting, value, attrs, metas):
        """Match a single value """
        if value[1] < 0:
            return 0, 0

        if self._var_exists(setting, value, attrs, metas):
            return 1, 1
        elif setting.required == setting.OPTIONAL:
            return 0, 1
        else:
            raise IncompatibleContext()

    def is_valid_item(self, setting, item, attrs, metas):
        """Return True if given item can be used with attrs and metas

        Subclasses can override this method to checks data in alternative
        representations.
        """
        if not isinstance(item, tuple):
            return True
        return self._var_exists(setting, item, attrs, metas)


class IncompatibleContext(Exception):
    """Raised when a required variable in context is not available in data."""
    pass


class ClassValuesContextHandler(ContextHandler):
    """Context handler used for widgets that work with
    a single discrete variable"""

    def open_context(self, widget, classes):
        if isinstance(classes, Variable):
            if classes.is_discrete:
                classes = classes.values
            else:
                classes = None

        super().open_context(widget, classes)

    def new_context(self, classes):
        context = super().new_context()
        context.classes = classes
        return context

    def match(self, context, classes):
        if isinstance(classes, Variable) and classes.is_continuous:
            return (self.PERFECT_MATCH if context.classes is None
                    else self.NO_MATCH)
        else:
            return (self.PERFECT_MATCH if context.classes == classes
                    else self.NO_MATCH)


class PerfectDomainContextHandler(DomainContextHandler):
    """Context handler that matches a context only when
    the same domain is available.

    It uses a different encoding than the DomainContextHandler.
    """

    def new_context(self, domain, attributes, class_vars, metas):
        """Same as DomainContextHandler, but also store class_vars"""
        context = super().new_context(domain, attributes, metas)
        context.class_vars = class_vars
        return context

    def clone_context(self, old_context, *args):
        """Copy of context is always valid, since widgets are using
        the same domain."""
        context = self.new_context(*args)
        context.values = copy.deepcopy(old_context.values)
        return context

    def encode_domain(self, domain):
        """Encode domain into tuples (name, type)
        A tuple is returned for each of attributes, class_vars and metas.
        """

        if self.match_values == self.MATCH_VALUES_ALL:
            def _encode(attrs):
                return tuple((v.name, list(v.values) if v.is_discrete else vartype(v))
                             for v in attrs)
        else:
            def _encode(attrs):
                return tuple((v.name, vartype(v)) for v in attrs)
        return (_encode(domain.attributes),
                _encode(domain.class_vars),
                _encode(domain.metas))

    def match(self, context, domain, attributes, class_vars, metas):
        """Context only matches when domains are the same"""

        return (self.PERFECT_MATCH
                if (context.attributes == attributes and
                    context.class_vars == class_vars and
                    context.metas == metas)
                else self.NO_MATCH)

    def encode_setting(self, context, setting, value):
        """Same as is domain context handler, but handles separately stored
        class_vars."""

        if isinstance(setting, ContextSetting) and isinstance(value, str):

            def _candidate_variables():
                if not setting.exclude_attributes:
                    yield from itertools.chain(context.attributes,
                                               context.class_vars)
                if not setting.exclude_metas:
                    yield from context.metas

            for aname, atype in _candidate_variables():
                if aname == value:
                    return value, atype

            return value, -1
        else:
            return super().encode_setting(context, setting, value)


class SettingsPrinter(pprint.PrettyPrinter):
    """Pretty Printer that knows how to properly format Contexts."""

    def _format(self, obj, stream, indent, allowance, context, level):
        if not isinstance(obj, Context):
            return super()._format(obj, stream, indent,
                                   allowance, context, level)

        stream.write("Context(")
        for key, value in sorted(obj.__dict__.items(), key=itemgetter(0)):
            if key == "values":
                continue
            stream.write(key)
            stream.write("=")
            stream.write(self._repr(value, context, level + 1))
            stream.write(",\n")
            stream.write(" " * (indent + 8))
        stream.write("values=")
        stream.write(" ")
        self._format(obj.values, stream, indent+15,
                     allowance+1, context, level + 1)
        stream.write(")")


def rename_setting(settings, old_name, new_name):
    """
    Rename setting from `old_name` to `new_name`. Used in migrations.

    The argument `settings` can be `dict` or `Context`.
    """
    if isinstance(settings, Context):
        rename_setting(settings.values, old_name, new_name)
    else:
        settings[new_name] = settings.pop(old_name)


def migrate_str_to_variable(settings, names=None, none_placeholder=None):
    """
    Change variables stored as `(str, int)` to `(Variable, int)`.

    Args:
        settings (Context): context that is being migrated
        names (sequence): names of settings to be migrated. If omitted,
            all settings with values `(str, int)` are migrated.
    """
    def _fix(name):
        var, vartype = settings.values[name]
        if 0 <= vartype <= 100:
            settings.values[name] = (var, 100 + vartype)
        elif var == none_placeholder and vartype == -2:
            settings.values[name] = None

    if names is None:
        for name, setting in settings.values.items():
            if isinstance(setting, tuple) and len(setting) == 2 and \
                    isinstance(setting[0], str) and isinstance(setting[1], int):
                _fix(name)
    elif isinstance(names, str):
        _fix(names)
    else:
        for name in names:
            _fix(name)

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