import re  from typing import Dict, List, Set    from .._serializer._json_serializer import _JsonSerializer      class _ComparatorResult(dict):        ADDED_ITEMS_KEY = "added_items"      REMOVED_ITEMS_KEY = "removed_items"      MODIFIED_ITEMS_KEY = "modified_items"        CONFLICTED_SECTION_KEY = "conflicted_sections"      UNCONFLICTED_SECTION_KEY = "unconflicted_sections"        def __init__(self, unconflicted_sections: Set[str]):          super().__init__()            self._unconflicted_sections = unconflicted_sections        def _sort_by_section(self):          if self.get(self.CONFLICTED_SECTION_KEY):              for key in self[self.CONFLICTED_SECTION_KEY].keys():                  self[self.CONFLICTED_SECTION_KEY][key].sort(key=lambda x: x[0][0])            if self.get(self.UNCONFLICTED_SECTION_KEY):              for key in self[self.UNCONFLICTED_SECTION_KEY].keys():                  self[self.UNCONFLICTED_SECTION_KEY][key].sort(key=lambda x: x[0][0])        def _check_added_items(self, config_deepdiff, new_json_config):          if dictionary_item_added := config_deepdiff.get("dictionary_item_added"):              for item_added in dictionary_item_added:                  section_name, config_id, attribute = self.__get_changed_entity_attribute(item_added)                  diff_sections = self.__get_section(section_name)                    if attribute:                      value_added = new_json_config[section_name][config_id][attribute]                  elif config_id:                      value_added = new_json_config[section_name][config_id]                  else:                      value_added = new_json_config[section_name]                    section_name = self.__rename_global_node_name(section_name)                  self.__create_or_append_list(                      diff_sections,                      self.ADDED_ITEMS_KEY,                      ((section_name, config_id, attribute), (value_added)),                  )        def _check_removed_items(self, config_deepdiff, old_json_config):          if dictionary_item_removed := config_deepdiff.get("dictionary_item_removed"):              for item_removed in dictionary_item_removed:                  section_name, config_id, attribute = self.__get_changed_entity_attribute(item_removed)                  diff_sections = self.__get_section(section_name)                    if attribute:                      value_removed = old_json_config[section_name][config_id][attribute]                  elif config_id:                      value_removed = old_json_config[section_name][config_id]                  else:                      value_removed = old_json_config[section_name]                    section_name = self.__rename_global_node_name(section_name)                  self.__create_or_append_list(                      diff_sections,                      self.REMOVED_ITEMS_KEY,                      ((section_name, config_id, attribute), (value_removed)),                  )        def _check_modified_items(self, config_deepdiff, old_json_config, new_json_config):          if values_changed := config_deepdiff.get("values_changed"):              for item_changed, value_changed in values_changed.items():                  section_name, config_id, attribute = self.__get_changed_entity_attribute(item_changed)                  diff_sections = self.__get_section(section_name)                    section_name = self.__rename_global_node_name(section_name)                  self.__create_or_append_list(                      diff_sections,                      self.MODIFIED_ITEMS_KEY,                      ((section_name, config_id, attribute), (value_changed["old_value"], value_changed["new_value"])),                  )            # Iterable item added will be considered a modified item          if iterable_item_added := config_deepdiff.get("iterable_item_added"):              self.__check_modified_iterable(iterable_item_added, old_json_config, new_json_config)            # Iterable item removed will be considered a modified item          if iterable_item_removed := config_deepdiff.get("iterable_item_removed"):              self.__check_modified_iterable(iterable_item_removed, old_json_config, new_json_config)        def __check_modified_iterable(self, iterable_items, old_json_config, new_json_config):          for item in iterable_items:              section_name, config_id, attribute = self.__get_changed_entity_attribute(item)              diff_sections = self.__get_section(section_name)                if attribute:                  new_value = new_json_config[section_name][config_id][attribute]                  old_value = old_json_config[section_name][config_id][attribute]              else:                  new_value = new_json_config[section_name][config_id]                  old_value = old_json_config[section_name][config_id]                section_name = self.__rename_global_node_name(section_name)              modified_value = ((section_name, config_id, attribute), (old_value, new_value))                if (                  not diff_sections.get(self.MODIFIED_ITEMS_KEY)                  or modified_value not in diff_sections[self.MODIFIED_ITEMS_KEY]              ):                  self.__create_or_append_list(                      diff_sections,                      self.MODIFIED_ITEMS_KEY,                      modified_value,                  )        def __get_section(self, section_name: str) -> Dict[str, List]:          if section_name in self._unconflicted_sections:              if not self.get(self.UNCONFLICTED_SECTION_KEY):                  self[self.UNCONFLICTED_SECTION_KEY] = {}              return self[self.UNCONFLICTED_SECTION_KEY]            if not self.get(self.CONFLICTED_SECTION_KEY):              self[self.CONFLICTED_SECTION_KEY] = {}          return self[self.CONFLICTED_SECTION_KEY]        def __create_or_append_list(self, diff_dict, key, value):          if diff_dict.get(key):              diff_dict[key].append(value)          else:              diff_dict[key] = [value]        def __get_changed_entity_attribute(self, attribute_bracket_notation):          """Split the section name, the config id (if exists), and the attribute name (if exists)          from JSON bracket notation.          """          try:              section_name, config_id, attribute = re.findall(r"\[\'(.*?)\'\]", attribute_bracket_notation)          except ValueError:              try:                  section_name, config_id = re.findall(r"\[\'(.*?)\'\]", attribute_bracket_notation)                  attribute = None              except ValueError:                  section_name = re.findall(r"\[\'(.*?)\'\]", attribute_bracket_notation)[0]                  config_id = None                  attribute = None            return section_name, config_id, attribute        def __rename_global_node_name(self, node_name):          if node_name == _JsonSerializer._GLOBAL_NODE_NAME:              return "Global Configuration"          return node_name


#  # Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with  # the License. You may obtain a copy of the License at  #  #        http://www.apache.org/licenses/LICENSE-2.0  #  # Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on  # an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the  # specific language governing permissions and limitations under the License.


import json  from copy import copy  from typing import Optional, Set, Union    from deepdiff import DeepDiff    from ...logger._taipy_logger import _TaipyLogger  from .._config import _Config  from .._serializer._json_serializer import _JsonSerializer  from ._comparator_result import _ComparatorResult      class _ConfigComparator:      def __init__(self):          self._unconflicted_sections: Set[str] = set()          self.__logger = _TaipyLogger._get_logger()        def _add_unconflicted_section(self, section_name: Union[str, Set[str]]):          if isinstance(section_name, str):              section_name = {section_name}            self._unconflicted_sections.update(section_name)        def _find_conflict_config(          self,          old_config: _Config,          new_config: _Config,          old_version_number: Optional[str] = None,          new_version_number: Optional[str] = None,      ):          """Compare between 2 _Config object to check for compatibility.            Args:              old_config (_Config): The old _Config.              new_config (_Config): The new _Config.              old_version_number (str, optional): The old version number for logging. Defaults to None.              new_version_number (str, optional): The new version number for logging. Defaults to None.            Returns:              _ComparatorResult: Return a _ComparatorResult dictionary with the following format:          ```python          {              "added_items": [                  ((section_name_1, config_id_1, attribute_1), added_object_1),                  ((section_name_2, config_id_2, attribute_2), added_object_2),              ],              "removed_items": [                  ((section_name_1, config_id_1, attribute_1), removed_object_1),                  ((section_name_2, config_id_2, attribute_2), removed_object_2),              ],              "modified_items": [                  ((section_name_1, config_id_1, attribute_1), (old_value_1, new_value_1)),                  ((section_name_2, config_id_2, attribute_2), (old_value_2, new_value_2)),              ],          }          ```          """          comparator_result = self.__get_config_diff(old_config, new_config)          self.__log_find_conflict_message(comparator_result, old_version_number, new_version_number)          return comparator_result        def _compare(          self,          config_1: _Config,          config_2: _Config,          version_number_1: str,          version_number_2: str,      ):          """Compare between 2 _Config object to check for compatibility.            Args:              config_1 (_Config): The old _Config.              config_2 (_Config): The new _Config.              version_number_1 (str): The old version number for logging.              version_number_2 (str): The new version number for logging.          """          comparator_result = self.__get_config_diff(config_1, config_2)          self.__log_comparison_message(comparator_result, version_number_1, version_number_2)            return comparator_result        def __get_config_diff(self, config_1, config_2):          json_config_1 = json.loads(_JsonSerializer._serialize(config_1))          json_config_2 = json.loads(_JsonSerializer._serialize(config_2))            config_deepdiff = DeepDiff(json_config_1, json_config_2, ignore_order=True)            comparator_result = _ComparatorResult(copy(self._unconflicted_sections))            comparator_result._check_added_items(config_deepdiff, json_config_2)          comparator_result._check_removed_items(config_deepdiff, json_config_1)          comparator_result._check_modified_items(config_deepdiff, json_config_1, json_config_2)          comparator_result._sort_by_section()            return comparator_result        def __log_comparison_message(          self,          comparator_result: _ComparatorResult,          version_number_1: str,          version_number_2: str,      ):          config_str_1 = f"version {version_number_1} Configuration"          config_str_2 = f"version {version_number_2} Configuration"            diff_messages = []          for _, sections in comparator_result.items():              diff_messages = self.__get_messages(sections)            if diff_messages:              self.__logger.info(                  f"Differences between {config_str_1} and {config_str_2}:\n\t" + "\n\t".join(diff_messages)              )          else:              self.__logger.info(f"There is no difference between {config_str_1} and {config_str_2}.")        def __log_find_conflict_message(          self,          comparator_result: _ComparatorResult,          old_version_number: Optional[str] = None,          new_version_number: Optional[str] = None,      ):          old_config_str = (              f"configuration for version {old_version_number}" if old_version_number else "current configuration"          )          new_config_str = (              f"configuration for version {new_version_number}" if new_version_number else "current configuration"          )            if unconflicted_sections := comparator_result.get(_ComparatorResult.UNCONFLICTED_SECTION_KEY):              unconflicted_messages = self.__get_messages(unconflicted_sections)              self.__logger.info(                  f"There are non-conflicting changes between the {old_config_str}"                  f" and the {new_config_str}:\n\t" + "\n\t".join(unconflicted_messages)              )            if conflicted_sections := comparator_result.get(_ComparatorResult.CONFLICTED_SECTION_KEY):              conflicted_messages = self.__get_messages(conflicted_sections)              self.__logger.error(                  f"The {old_config_str} conflicts with the {new_config_str}:\n\t" + "\n\t".join(conflicted_messages)              )        def __get_messages(self, diff_sections):          dq = '"'          messages = []            if added_items := diff_sections.get(_ComparatorResult.ADDED_ITEMS_KEY):              for diff in added_items:                  ((section_name, config_id, attribute), added_object) = diff                  messages.append(                      f"{section_name} {dq}{config_id}{dq} "                      f"{f'has attribute {dq}{attribute}{dq}' if attribute else 'was'} added: {added_object}"                  )            if removed_items := diff_sections.get(_ComparatorResult.REMOVED_ITEMS_KEY):              for diff in removed_items:                  ((section_name, config_id, attribute), removed_object) = diff                  messages.append(                      f"{section_name} {dq}{config_id}{dq} "                      f"{f'has attribute {dq}{attribute}{dq}' if attribute else 'was'} removed"                  )            if modified_items := diff_sections.get(_ComparatorResult.MODIFIED_ITEMS_KEY):              for diff in modified_items:                  ((section_name, config_id, attribute), (old_value, new_value)) = diff                  messages.append(                      f"{section_name} {dq}{config_id}{dq} "                      f"{f'has attribute {dq}{attribute}{dq}' if attribute else 'was'} modified: "                      f"{old_value} -> {new_value}"                  )            return messages


import argparse  from typing import Dict      class _CLI:      """Argument parser for Taipy application."""        # The conflict_handler is set to "resolve" to override conflict arguments      _subparser_action = None      _parser = argparse.ArgumentParser(conflict_handler="resolve")        _sub_taipyparsers: Dict[str, argparse.ArgumentParser] = {}      _arg_groups: Dict[str, argparse._ArgumentGroup] = {}        @classmethod      def _add_subparser(cls, name: str, **kwargs) -> argparse.ArgumentParser:          """Create a new subparser and return a argparse handler."""          if subparser := cls._sub_taipyparsers.get(name):              return subparser            if not cls._subparser_action:              cls._subparser_action = cls._parser.add_subparsers()            subparser = cls._subparser_action.add_parser(              name=name,              conflict_handler="resolve",              **kwargs,          )          cls._sub_taipyparsers[name] = subparser          subparser.set_defaults(which=name)          return subparser        @classmethod      def _add_groupparser(cls, title: str, description: str = "") -> argparse._ArgumentGroup:          """Create a new group for arguments and return a argparser handler."""          if groupparser := cls._arg_groups.get(title):              return groupparser            groupparser = cls._parser.add_argument_group(title=title, description=description)          cls._arg_groups[title] = groupparser          return groupparser        @classmethod      def _parse(cls):          """Parse and return only known arguments."""          args, _ = cls._parser.parse_known_args()          return args        @classmethod      def _remove_argument(cls, arg: str):          """Remove an argument from the parser. Note that the `arg` must be without --.            Source: https://stackoverflow.com/questions/32807319/disable-remove-argument-in-argparse          """          for action in cls._parser._actions:              opts = action.option_strings              if (opts and opts[0] == arg) or action.dest == arg:                  cls._parser._remove_action(action)                  break            for argument_group in cls._parser._action_groups:              for group_action in argument_group._group_actions:                  opts = group_action.option_strings                  if (opts and opts[0] == arg) or group_action.dest == arg:                      argument_group._group_actions.remove(group_action)                      return


from ._cli import _CLI


"""The setup script."""    import json  import os    from setuptools import find_namespace_packages, find_packages, setup    with open("README.md", "rb") as readme_file:      readme = readme_file.read().decode("UTF-8")    with open(f"src{os.sep}taipy{os.sep}templates{os.sep}version.json") as version_file:      version = json.load(version_file)      version_string = f'{version.get("major", 0)}.{version.get("minor", 0)}.{version.get("patch", 0)}'      if vext := version.get("ext"):          version_string = f"{version_string}.{vext}"    test_requirements = ["pytest>=3.8"]    setup(      author="Avaiga",      author_email="dev@taipy.io",      python_requires=">=3.8",      classifiers=[          "Intended Audience :: Developers",          "License :: OSI Approved :: Apache Software License",          "Natural Language :: English",          "Programming Language :: Python :: 3",          "Programming Language :: Python :: 3.8",          "Programming Language :: Python :: 3.9",          "Programming Language :: Python :: 3.10",          "Programming Language :: Python :: 3.11",      ],      description="An open-source package holding Taipy application templates.",      license="Apache License 2.0",      long_description=readme,      long_description_content_type="text/markdown",      keywords="taipy-templates",      name="taipy-templates",      package_dir={"": "src"},      packages=find_namespace_packages(where="src") + find_packages(include=["taipy"]),      include_package_data=True,      test_suite="tests",      url="https://github.com/avaiga/taipy-templates",      version=version_string,      zip_safe=False,  )


import os    import pytest  from cookiecutter.exceptions import FailedHookException  from cookiecutter.main import cookiecutter    from .utils import _run_template      def test_default_answer(tmpdir):      cookiecutter(          template="src/taipy/templates/default",          output_dir=str(tmpdir),          no_input=True,      )        assert os.listdir(tmpdir) == ["taipy_application"]      assert (          os.listdir(os.path.join(tmpdir, "taipy_application")).sort() == ["requirements.txt", "main.py", "images"].sort()      )      with open(os.path.join(tmpdir, "taipy_application", "requirements.txt")) as requirements_file:          # Assert post_gen_project hook is successful          assert "taipy==" in requirements_file.read()        oldpwd = os.getcwd()      os.chdir(os.path.join(tmpdir, "taipy_application"))      stdout = _run_template("main.py")      os.chdir(oldpwd)        # Assert the message when the application is run successfully is in the stdout      assert "[Taipy][INFO]  * Server starting on" in str(stdout, "utf-8")      def test_main_file_with_and_without_extension(tmpdir):      cookiecutter(          template="src/taipy/templates/default",          output_dir=str(tmpdir),          no_input=True,          extra_context={              "Application main Python file": "app.py",          },      )      assert (          os.listdir(os.path.join(tmpdir, "taipy_application")).sort() == ["requirements.txt", "app.py", "images"].sort()      )        cookiecutter(          template="src/taipy/templates/default",          output_dir=str(tmpdir),          no_input=True,          extra_context={              "Application root folder name": "foo_app",              "Application main Python file": "app",          },      )      assert os.listdir(os.path.join(tmpdir, "foo_app")).sort() == ["requirements.txt", "app.py", "images"].sort()      def test_with_core_service(tmpdir):      cookiecutter(          template="src/taipy/templates/default",          output_dir=str(tmpdir),          no_input=True,          extra_context={              "Does the application use scenario management or version management?": "y",              "Does the application use Rest API?": "no",          },      )        assert (          os.listdir(os.path.join(tmpdir, "taipy_application")).sort()          == ["requirements.txt", "main.py", "images", "configuration", "algorithms"].sort()      )      with open(os.path.join(tmpdir, "taipy_application", "main.py")) as main_file:          assert "core = Core()" in main_file.read()        oldpwd = os.getcwd()      os.chdir(os.path.join(tmpdir, "taipy_application"))      stdout = _run_template("main.py")      os.chdir(oldpwd)        # Assert the message when the application is run successfully is in the stdout      assert "[Taipy][INFO]  * Server starting on" in str(stdout, "utf-8")      assert "[Taipy][INFO] Development mode: " in str(stdout, "utf-8")      def test_with_rest_service(tmpdir):      cookiecutter(          template="src/taipy/templates/default",          output_dir=str(tmpdir),          no_input=True,          extra_context={              "Does the application use scenario management or version management?": "n",              "Does the application use Rest API?": "yes",          },      )        assert (          os.listdir(os.path.join(tmpdir, "taipy_application")).sort() == ["requirements.txt", "main.py", "images"].sort()      )      with open(os.path.join(tmpdir, "taipy_application", "main.py")) as main_file:          assert "rest = Rest()" in main_file.read()        oldpwd = os.getcwd()      os.chdir(os.path.join(tmpdir, "taipy_application"))      stdout = _run_template("main.py")      os.chdir(oldpwd)        # Assert the message when the application is run successfully is in the stdout      assert "[Taipy][INFO]  * Server starting on" in str(stdout, "utf-8")      assert "[Taipy][INFO] Development mode: " in str(stdout, "utf-8")      def test_with_both_core_rest_services(tmpdir):      cookiecutter(          template="src/taipy/templates/default",          output_dir=str(tmpdir),          no_input=True,          extra_context={              "Does the application use scenario management or version management?": "n",              "Does the application use Rest API?": "yes",          },      )        assert (          os.listdir(os.path.join(tmpdir, "taipy_application")).sort()          == ["requirements.txt", "main.py", "images", "configuration", "algorithms"].sort()      )      with open(os.path.join(tmpdir, "taipy_application", "main.py")) as main_file:          assert "rest = Rest()" in main_file.read()          assert "core = Core()" not in main_file.read()        oldpwd = os.getcwd()      os.chdir(os.path.join(tmpdir, "taipy_application"))      stdout = _run_template("main.py")      os.chdir(oldpwd)        # Assert the message when the application is run successfully is in the stdout      assert "[Taipy][INFO]  * Server starting on" in str(stdout, "utf-8")      assert "[Taipy][INFO] Development mode: " in str(stdout, "utf-8")      def test_multipage_gui_template(tmpdir):      cookiecutter(          template="src/taipy/templates/default",          output_dir=str(tmpdir),          no_input=True,          extra_context={              "Application root folder name": "foo_app",              "Page names in multi-page application?": "name_1 name_2 name_3",          },      )        assert (          os.listdir(os.path.join(tmpdir, "foo_app")).sort() == ["requirements.txt", "main.py", "pages", "images"].sort()      )      assert (          os.listdir(os.path.join(tmpdir, "foo_app", "pages")).sort()          == ["name_1", "name_2", "name_3", "root.md", "root.py", "__init__.py"].sort()      )        oldpwd = os.getcwd()      os.chdir(os.path.join(tmpdir, "foo_app"))      stdout = _run_template("main.py")      os.chdir(oldpwd)      assert "[Taipy][INFO]  * Server starting on" in str(stdout, "utf-8")      def test_multipage_gui_template_with_invalid_page_name(tmpdir, capfd):      with pytest.raises(FailedHookException):          cookiecutter(              template="src/taipy/templates/default",              output_dir=str(tmpdir),              no_input=True,              extra_context={                  "Application root folder name": "foo_app",                  "Page names in multi-page application?": "valid_var_name 1_invalid_var_name",              },          )        _, stderr = capfd.readouterr()      assert 'Page name "1_invalid_var_name" is not a valid Python identifier' in stderr        assert not os.path.exists(os.path.join(tmpdir, "foo_app"))


import subprocess  import sys      def _run_template(main_path, time_out=30):      """Run the templates on a subprocess and get stdout after timeout"""      with subprocess.Popen([sys.executable, main_path], stdout=subprocess.PIPE, stderr=subprocess.PIPE) as proc:          try:              stdout, stderr = proc.communicate(timeout=time_out)          except subprocess.TimeoutExpired:              proc.kill()              stdout, stderr = proc.communicate()        # Print the eror if there is any (for debugging)      if stderr := str(stderr, "utf-8"):          print(stderr)        return stdout


import os    from cookiecutter.main import cookiecutter    from .utils import _run_template      def test_scenario_management_with_toml_config(tmpdir):      cookiecutter(          template="src/taipy/templates/scenario-management",          output_dir=tmpdir,          no_input=True,          extra_context={              "Application root folder name": "foo_app",              "Application main Python file": "main.py",              "Application title": "bar",              "Does the application use TOML Config?": "yes",          },      )        assert os.listdir(tmpdir) == ["foo_app"]      assert (          os.listdir(os.path.join(tmpdir, "foo_app")).sort()          == ["requirements.txt", "main.py", "algos", "config", "pages"].sort()      )        # Assert post_gen_project hook is successful      with open(os.path.join(tmpdir, "foo_app", "requirements.txt")) as requirements_file:          assert "taipy==" in requirements_file.read()      assert (          os.listdir(os.path.join(tmpdir, "foo_app", "config")).sort()          == ["__init__.py", "config.py", "config.toml"].sort()      )      with open(os.path.join(tmpdir, "foo_app", "config", "config.py")) as config_file:          assert 'Config.load("config/config.toml")' in config_file.read()        oldpwd = os.getcwd()      os.chdir(os.path.join(tmpdir, "foo_app"))      stdout = _run_template("main.py")      os.chdir(oldpwd)        # Assert the message when the application is run successfully is in the stdout      assert "[Taipy][INFO] Configuration 'config/config.toml' successfully loaded." in str(stdout, "utf-8")      assert "[Taipy][INFO]  * Server starting on" in str(stdout, "utf-8")      def test_scenario_management_without_toml_config(tmpdir):      cookiecutter(          template="src/taipy/templates/scenario-management",          output_dir=tmpdir,          no_input=True,          extra_context={              "Application root folder name": "foo_app",              "Application main Python file": "main.py",              "Application title": "bar",              "Does the application use TOML Config?": "no",          },      )        assert os.listdir(tmpdir) == ["foo_app"]      assert (          os.listdir(os.path.join(tmpdir, "foo_app")).sort()          == ["requirements.txt", "main.py", "algos", "config", "pages"].sort()      )        # Assert post_gen_project hook is successful      with open(os.path.join(tmpdir, "foo_app", "requirements.txt")) as requirements_file:          assert "taipy==" in requirements_file.read()      assert os.listdir(os.path.join(tmpdir, "foo_app", "config")).sort() == ["__init__.py", "config.py"].sort()      with open(os.path.join(tmpdir, "foo_app", "config", "config.py")) as config_file:          config_content = config_file.read()          assert 'Config.load("config/config.toml")' not in config_content          assert all([x in config_content for x in ["Config.configure_csv_data_node", "Config.configure_task"]])        oldpwd = os.getcwd()      os.chdir(os.path.join(tmpdir, "foo_app"))      stdout = _run_template("main.py")      os.chdir(oldpwd)        # Assert the message when the application is run successfully is in the stdout      assert "[Taipy][INFO]  * Server starting on" in str(stdout, "utf-8")


from config.config import configure  from pages import job_page, scenario_page  from pages.root import content, root, selected_data_node, selected_scenario    import taipy as tp  from taipy import Core, Gui      def on_init(state):      ...      def on_change(state, var, val):      if var == "selected_data_node" and val:          state["scenario"].manage_data_node_partial(state)      pages = {      "/": root,      "scenario": scenario_page,      "jobs": job_page,  }      if __name__ == "__main__":      # Instantiate, configure and run the Core      core = Core()      default_scenario_cfg = configure()      core.run()        # ##################################################################################################################      # PLACEHOLDER: Initialize your data application here                                                               #      #                                                                                #      # Example:                                                                                #      if len(tp.get_scenarios()) == 0:          tp.create_scenario(default_scenario_cfg, name="Default Scenario")      # Comment, remove or replace the previous lines with your own use case                                             #      # ##################################################################################################################        # Instantiate, configure and run the GUI      gui = Gui(pages=pages)      data_node_partial = gui.add_partial("")      gui.run(title="{{cookiecutter.__application_title}}", margin="0em")


from algos import clean_data    from taipy import Config, Frequency, Scope      def configure():      # ##################################################################################################################      # PLACEHOLDER: Add your scenario configurations here                                                               #      #                                                                                #      # Example:                                                                                #      initial_dataset_cfg = Config.configure_csv_data_node("initial_dataset", scope=Scope.CYCLE)      replacement_type_cfg = Config.configure_data_node("replacement_type", default_data="NO VALUE")      cleaned_dataset_cfg = Config.configure_csv_data_node("cleaned_dataset")      clean_data_cfg = Config.configure_task(          "clean_data",          function=clean_data,          input=[initial_dataset_cfg, replacement_type_cfg],          output=cleaned_dataset_cfg,      )      scenario_cfg = Config.configure_scenario(          "scenario_configuration", task_configs=[clean_data_cfg], frequency=Frequency.DAILY      )      return scenario_cfg      # Comment, remove or replace the previous lines with your own use case                                             #      # ##################################################################################################################


from taipy import Config      def configure():      Config.load("config/config.toml")      return Config.scenarios["scenario_configuration"]


def clean_data(df, replacement_type):      df = df.fillna(replacement_type)      return df


from .algos import clean_data


from .scenario_page import scenario_page  from .job_page import job_page


from taipy.gui import Markdown    selected_scenario = None  selected_data_node = None  content = ""    root = Markdown("pages/root.md")


from .job_page import job_page


from taipy.gui import Markdown      job_page = Markdown("pages/job_page/job_page.md")


from taipy.gui import Markdown, notify    from .data_node_management import manage_partial      def notify_on_submission(state, submitable, details):      if details['submission_status'] == 'COMPLETED':          notify(state, "success", "Submision completed!")      elif details['submission_status'] == 'FAILED':          notify(state, "error", "Submission failed!")      else:          notify(state, "info", "In progress...")    def manage_data_node_partial(state):      manage_partial(state)    scenario_page = Markdown("pages/scenario_page/scenario_page.md")


from .scenario_page import scenario_page


# build partial content for a specific data node  def build_dn_partial(dn, dn_label):      partial_content = "<|part|render={selected_scenario}|\n\n"        # ##################################################################################################################      # PLACEHOLDER: data node specific content before automatic content                                                 #      #                                                                                #      # Example:                                                                                #      if dn_label == "replacement_type":          partial_content += "All missing values will be replaced by the data node value."      # Comment, remove or replace the previous lines with your own use case                                             #      # ##################################################################################################################        # Automatic data node content      partial_content += "<|{selected_scenario.data_nodes['" + dn.config_id + "']}|data_node|scenario={selected_scenario}|>\n\n"        # ##################################################################################################################      # PLACEHOLDER: data node specific content after automatic content                                                  #      #                                                                                #      # Example:                                                                                #      if dn_label == "initial_dataset":          partial_content += "Select your CSV file: <|{selected_data_node.path}|file_selector|extensions=.csv|on_action={lambda s: s.refresh('selected_scenario')}|>\n\n"      # Comment, remove or replace the previous lines with your own use case                                             #      # ##################################################################################################################        partial_content += "|>\n\n"      return partial_content      def manage_partial(state):      dn = state.selected_data_node      dn_label = dn.get_simple_label()      partial_content = build_dn_partial(dn, dn_label)      state.data_node_partial.update_content(state, partial_content)


import os    import taipy    # Add taipy version to requirements.txt  with open(os.path.join(os.getcwd(), "requirements.txt"), "a") as requirement_file:      requirement_file.write(f"taipy=={taipy.version._get_version()}\n")    # Use TOML config file or not  use_toml_config = "{{ cookiecutter.__use_toml_config }}".upper()  if use_toml_config == "YES" or use_toml_config == "Y":      os.remove(os.path.join(os.getcwd(), "config", "config.py"))      os.rename(          os.path.join(os.getcwd(), "config", "config_with_toml.py"), os.path.join(os.getcwd(), "config", "config.py")      )  else:      os.remove(os.path.join(os.getcwd(), "config", "config_with_toml.py"))      os.remove(os.path.join(os.getcwd(), "config", "config.toml"))    main_file_name = "{{cookiecutter.__main_file}}.py"  print(      f"New Taipy application has been created at {os.path.join(os.getcwd())}"      f"\n\nTo start the application, change directory to the newly created folder:"      f"\n\tcd {os.path.join(os.getcwd())}"      f"\nand run the application as follows:"      f"\n\ttaipy run {main_file_name}"  )


"""  Contain the application's configuration including the scenario configurations.    The configuration is run by the Core service.  """    from algorithms import *    from taipy import Config    # #############################################################################  # PLACEHOLDER: Put your application's configurations here                     #  #                                                                             #  # Example:                                                                    #  # scenario_config = Config.configure_scenario("placeholder_scenario", [])     #  # Comment, remove or replace the previous lines with your own use case        #  # #############################################################################


from .config import *


"""  This file is designed to contain the various Python functions used to configure tasks.    The functions will be imported by the __init__.py file in this folder.  """    # ##################################################################################################################  # PLACEHOLDER: Put your Python functions here                                                                      #  #                                                                                #  # Example:                                                                                #  # def place_holder_algorithm():                                                                                #  #     pass                                                                                #  # Comment, remove or replace the previous lines with your own use case                                             #  # ##################################################################################################################


from algorithms import *


from .root import root_page


"""  The root page of the application.  Page content is imported from the root.md file.    Please refer to https://docs.taipy.io/en/latest/manuals/gui/pages for more details.  """    from taipy.gui import Markdown    root_page = Markdown("pages/root.md")


"""  A page of the application.  Page content is imported from the page_example.md file.    Please refer to https://docs.taipy.io/en/latest/manuals/gui/pages for more details.  """    from taipy.gui import Markdown    page_example = Markdown("pages/page_example/page_example.md")


import sys    pages = "{{ cookiecutter.__pages }}".split(" ")  # Remove empty string from pages list  pages = [page for page in pages if page != ""]    for page in pages:      if not page.isidentifier():          sys.exit(f'Page name "{page}" is not a valid Python identifier. Please choose another name.')


import os  import shutil    import taipy      def handle_services(use_rest, use_core):      if use_core or use_rest:          # Write "import taipy as tp" at the third line of the import.txt file          with open(os.path.join(os.getcwd(), "sections", "import.txt"), "r") as import_file:              import_lines = import_file.readlines()              import_lines[0] = "import taipy as tp\n" + import_lines[0] + "\n"          with open(os.path.join(os.getcwd(), "sections", "import.txt"), "w") as import_file:              import_file.writelines(import_lines)        # Import the necessary services      if use_core and use_rest:          with open(os.path.join(os.getcwd(), "sections", "import.txt"), "a") as import_file:              import_file.write("from taipy import Core, Rest\n")      elif use_core:          with open(os.path.join(os.getcwd(), "sections", "import.txt"), "a") as import_file:              import_file.write("from taipy import Core\n")      elif use_rest:          with open(os.path.join(os.getcwd(), "sections", "import.txt"), "a") as import_file:              import_file.write("from taipy import Rest\n")        # Start the Rest service      if use_rest:          with open(os.path.join(os.getcwd(), "sections", "main.txt"), "a") as main_file:              main_file.write("    rest = Rest()\n")        if use_core:          # Create and submit the placeholder scenario          with open(os.path.join(os.getcwd(), "sections", "main.txt"), "a") as main_file:              main_file.write("    core = Core()\n")              main_file.write("    core.run()\n")              main_file.write("    # #############################################################################\n")              main_file.write("    # PLACEHOLDER: Create and submit your scenario here                           #\n")              main_file.write("    #                                                                             #\n")              main_file.write("    # Example:                                                                    #\n")              main_file.write("    # from configuration import scenario_config                                   #\n")              main_file.write("    # scenario = tp.create_scenario(scenario_config)                              #\n")              main_file.write("    # scenario.submit()                                                           #\n")              main_file.write("    # Comment, remove or replace the previous lines with your own use case        #\n")              main_file.write("    # #############################################################################\n")      else:          shutil.rmtree(os.path.join(os.getcwd(), "algorithms"))          shutil.rmtree(os.path.join(os.getcwd(), "configuration"))      def handle_run_service():      with open(os.path.join(os.getcwd(), "sections", "main.txt"), "a+") as main_file:          main_file.seek(0)          main_content = main_file.read()          # Run Rest service along with the GUI service          if "rest = Rest()" in main_content:              main_file.write('    tp.run(gui, rest, title="{{cookiecutter.__application_title}}")\n')          else:              main_file.write('    gui.run(title="{{cookiecutter.__application_title}}")\n')      def handle_single_page_app():      shutil.rmtree(os.path.join(os.getcwd(), "pages"))        with open(os.path.join(os.getcwd(), "sections", "main.txt"), "a") as main_file:          main_file.write("\n")          main_file.write("    gui = Gui(page=page)\n")        handle_run_service()        with open(os.path.join(os.getcwd(), "sections", "page_content.txt"), "a") as page_content_file:          page_content_file.write(              '''  page = """  <center>  <|navbar|lov={[("home", "Homepage")]}|>  </center>    """  '''          )      def handle_multi_page_app(pages):      for page_name in pages:          os.mkdir(os.path.join(os.getcwd(), "pages", page_name))          with open(os.path.join(os.getcwd(), "pages", "page_example", "page_example.md"), "r") as page_md_file:              page_md_content = page_md_file.read()          page_md_content = page_md_content.replace("Page example", page_name.replace("_", " ").title())          with open(os.path.join(os.getcwd(), "pages", page_name, page_name + ".md"), "w") as page_md_file:              page_md_file.write(page_md_content)            with open(os.path.join(os.getcwd(), "pages", "page_example", "page_example.py"), "r") as page_content_file:              page_py_content = page_content_file.read()          page_py_content = page_py_content.replace("page_example", page_name)          with open(os.path.join(os.getcwd(), "pages", page_name, page_name + ".py"), "w") as page_content_file:              page_content_file.write(page_py_content)        with open(os.path.join(os.getcwd(), "pages", "__init__.py"), "a") as page_init_file:          for page_name in pages:              page_init_file.write(f"from .{page_name}.{page_name} import {page_name}\n")        shutil.rmtree(os.path.join(os.getcwd(), "pages", "page_example"))        newline = ",\n\t"      user_page_dict = newline.join(f'"{page_name}": {page_name}' for page_name in pages)      page_dict = """  pages = {      "/": root_page,      {pages}  }  """      with open(os.path.join(os.getcwd(), "sections", "page_content.txt"), "a") as page_content_file:          page_content_file.write(page_dict.replace("{pages}", user_page_dict))        with open(os.path.join(os.getcwd(), "sections", "import.txt"), "a") as import_file:          import_file.write("from pages import *\n")        with open(os.path.join(os.getcwd(), "sections", "main.txt"), "a") as main_file:          main_file.write("\n")          main_file.write("    gui = Gui(pages=pages)\n")        handle_run_service()      def generate_main_file():      with open(os.path.join(os.getcwd(), "sections", "import.txt"), "r") as import_file:          import_lines = import_file.read()      with open(os.path.join(os.getcwd(), "sections", "page_content.txt"), "r") as page_content_file:          page_content = page_content_file.read()      with open(os.path.join(os.getcwd(), "sections", "main.txt"), "r") as main_file:          main_lines = main_file.read()        with open(os.path.join(os.getcwd(), "{{cookiecutter.__main_file}}.py"), "a") as app_main_file:          app_main_file.write(import_lines)          app_main_file.write("\n")          app_main_file.write(page_content)          app_main_file.write("\n\n")          app_main_file.write(main_lines)      with open(os.path.join(os.getcwd(), "requirements.txt"), "a") as requirement_file:      requirement_file.write(f"taipy=={taipy.version._get_version()}\n")    use_core = "{{ cookiecutter.__core }}".upper()  use_rest = "{{ cookiecutter.__rest }}".upper()  handle_services(use_rest in ["YES", "Y"], use_core in ["YES", "Y"])    pages = "{{ cookiecutter.__pages }}".split(" ")  # Remove empty string from pages list  pages = [page for page in pages if page != ""]  if len(pages) == 0:      handle_single_page_app()  else:      handle_multi_page_app(pages)    generate_main_file()    # Remove the sections folder  shutil.rmtree(os.path.join(os.getcwd(), "sections"))    main_file_name = "{{cookiecutter.__main_file}}.py"  print(      f"New Taipy application has been created at {os.path.join(os.getcwd())}"      f"\n\nTo start the application, change directory to the newly created folder:"      f"\n\tcd {os.path.join(os.getcwd())}"      f"\nand run the application as follows:"      f"\n\ttaipy run {main_file_name}"  )


import os  import threading    from flask import Flask  from pyngrok import ngrok  from hf_hub_ctranslate2 import GeneratorCT2fromHfHub    from flask import request, jsonify    model_name = "taipy5-ct2" # note this is local folder model, the model uploaded to huggingface did not response correctly  #model_name = "michaelfeil/ct2fast-starchat-alpha"  #model_name = "michaelfeil/ct2fast-starchat-beta"  model = GeneratorCT2fromHfHub(          # load in int8 on CUDA          model_name_or_path=model_name,          device="cuda",          compute_type="int8_float16",          # tokenizer=AutoTokenizer.from_pretrained("{ORG}/{NAME}")  )    def generate_text_batch(prompt_texts, max_length=64):      outputs = model.generate(prompt_texts, max_length=max_length, include_prompt_in_result=False)      return outputs    app = Flask(__name__)  port = "5000"    # Open a ngrok tunnel to the HTTP server  public_url = ngrok.connect(port).public_url  print(" * ngrok tunnel \"{}\" -> \"http://127.0.0.1:{}\"".format(public_url, port))    # Update any base URLs to use the public ngrok URL  app.config["BASE_URL"] = public_url    # ... Update inbound traffic via APIs to use the public-facing ngrok URL  # Define Flask routes  @app.route("/")  def index():      return "Hello from Colab!"    @app.route("/api/generate", methods=["POST"])  def generate_code():      try:          # Get the JSON data from the request body          data = request.get_json()                    # Extract 'inputs' and 'parameters' from the JSON data          inputs = data.get('inputs', "")          parameters = data.get('parameters', {})                    # Extract the 'max_new_tokens' parameter          max_new_tokens = parameters.get('max_new_tokens', 64)            # Call the generate_text_batch function with inputs and max_new_tokens          generated_text = generate_text_batch([inputs], max_new_tokens)[0]            return jsonify({          "generated_text": generated_text,          "status": 200          })        except Exception as e:          return jsonify({"error": str(e)})      # Start the Flask server in a new thread  threading.Thread(target=app.run, kwargs={"use_reloader": False}).start()


import os  import json    def tokenize_code(code, max_characters=256):      """      Tokenize code into snippets of specified max_characters, breaking at new lines.      """      lines = code.split('\n')      snippets = []      current_snippet = ""        for line in lines:          if len(current_snippet) + len(line) + 1 <= max_characters:              current_snippet += line + '\n'          else:              snippets.append(current_snippet.strip())              current_snippet = line + '\n'        if current_snippet:          snippets.append(current_snippet.strip())        return snippets    def process_file(file_path):      """      Read a file, tokenize the code, and create snippets.      """      with open(file_path, 'r', encoding='utf-8') as file:          content = file.read()        # Tokenize code into snippets of 128 characters at new lines      snippets = tokenize_code(content)        return snippets    def escape_string(s):      """      Do not escape triple quotes, double quotes, single quotes, and new lines.      """      return s    def main(input_folder, output_file):      snippets_list = []        for root, dirs, files in os.walk(input_folder):          for file in files:              if file.endswith(('.py', '.md')):                  file_path = os.path.join(root, file)                  snippets = process_file(file_path)                  for snippet in snippets:                      escaped_snippet = escape_string(snippet)                      snippets_list.append({'text': escaped_snippet})        # Write snippets to a JSONL file      with open(output_file, 'w', encoding='utf-8') as jsonl_file:          for snippet in snippets_list:              jsonl_file.write(json.dumps(snippet) + '\n')    if __name__ == "__main__":      input_folder = 'taipy'  # replace with your folder path      output_file = 'snippets.jsonl'  # replace with your desired output file path      main(input_folder, output_file)


from taipy.gui import Gui  from tensorflow.keras import models  from PIL import Image  import numpy as np    model = models.load_model("assets/baseline.keras")      class_names = {      0: "airplane",      1: "automobile",      2: "bird",      3: "cat",      4: "deer",      5: "dog",      6: "frog",      7: "horse",      8: "ship",      9: "truck",  }      def predict_image(model, path_to_image):      img = Image.open(path_to_image)      img = img.convert("RGB").resize((32, 32))        # Normalizing image      data = np.asarray(img)      print("Before: ", data[0][0])  # Printing color of very first pixel      data = data / 255        # Comparing stuff to see if we broke something      print("After: ", data[0][0])  # Printing color of very first pixel        # Tricking model into thinking it is looking at an array of sample images and not a single image      probability = model.predict(np.array([data])[:1])      probes = probability.max()      prediction = class_names[np.argmax(probability)]      return (probes, prediction)      image_path = "assets/placeholder_image.png"  prediction, prob, content = "", "", ""      image_control_component = """  <|text-center|  <|{"assets/logo.png"}|image|width=10vw|height=25vh|>    <|{content}|file_selector|extensions=.png|>    Select an image!      <|{prediction}|>        <|{image_path}|image|>    <|{prob}|indicator|value={prob}|min=0|max=100|width=25vw|>  >  """      index = image_control_component      def on_change(state, variable_name, variable_value):      if variable_name == "content":          state.image_path = variable_value          probes, prediction = predict_image(model, variable_value)          state.prob = round(probes * 100)  # Converting decimal to percentage          state.prediction = f"This is a : {prediction}"      app = Gui(page=index)  if __name__ == "__main__":      app.run(use_reloader=True)


from taipy.gui import Gui  from tensorflow.keras import models  from PIL import Image  import numpy as np    model = models.load_model("baseline_mariya.keras")      class_names = {      0: "airplane",      1: "automobile",      2: "bird",      3: "cat",      4: "deer",      5: "dog",      6: "frog",      7: "horse",      8: "ship",      9: "truck",  }      def predict_image(model, path_to_image):      img = Image.open(path_to_image)      img = img.convert("RGB").resize((32, 32))        # Normalizing image      data = np.asarray(img)      print("Before: ", data[0][0])  # Printing color of very first pixel      data = data / 255        # Comparing stuff to see if we broke something      print("After: ", data[0][0])  # Printing color of very first pixel        # Tricking model into thinking it is looking at an array of sample images and not a single image      probability = model.predict(np.array([data])[:1])      print(probability)      probes = probability.max()      prediction = class_names[np.argmax(probability)]      return (probes, prediction)      image_path = "placeholder_image.png"  prediction, prob, content = "", "", ""      image_control_component = """  <|text-center|  <|{"logo.png"}|image|width=25vw|>    <|{content}|file_selector|extensions=.png|>    Select an image!      <|{prediction}|>        <|{image_path}|image|>    <|{prob}|indicator|value={prob}|min=0|max=100|width=25vw|>  >  """      index = image_control_component      def on_change(state, variable_name, variable_value):      if variable_name == "content":          state.image_path = variable_value          probes, prediction = predict_image(model, variable_value)          state.prob = round(probes * 100)  # Converting decimal to percentage          state.prediction = f"This is a : {prediction}"      app = Gui(page=index)  if __name__ == "__main__":      app.run(use_reloader=True)


print("Hello, World!")  print("Hi Taipy!")


#  # Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with  # the License. You may obtain a copy of the License at  #  #        http://www.apache.org/licenses/LICENSE-2.0  #  # Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on  # an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the  # specific language governing permissions and limitations under the License.  import json  import os    from setuptools import find_namespace_packages, find_packages, setup    with open("README.md") as readme_file:      readme = readme_file.read()    with open(f"src{os.sep}taipy{os.sep}rest{os.sep}version.json") as version_file:      version = json.load(version_file)      version_string = f'{version.get("major", 0)}.{version.get("minor", 0)}.{version.get("patch", 0)}'      if vext := version.get("ext"):          version_string = f"{version_string}.{vext}"    setup(      author="Avaiga",      name="taipy-rest",      keywords="taipy-rest",      python_requires=">=3.8",      version=version_string,      author_email="dev@taipy.io",      packages=find_namespace_packages(where="src") + find_packages(include=["taipy", "taipy.rest"]),      package_dir={"": "src"},      include_package_data=True,      long_description=readme,      long_description_content_type="text/markdown",      description="Library to expose taipy-core REST APIs.",      license="Apache License 2.0",      classifiers=[          "Intended Audience :: Developers",          "License :: OSI Approved :: Apache Software License",          "Natural Language :: English",          "Programming Language :: Python :: 3",          "Programming Language :: Python :: 3.8",          "Programming Language :: Python :: 3.9",          "Programming Language :: Python :: 3.10",          "Programming Language :: Python :: 3.11",      ],      install_requires=[          "flask>=3.0.0,<3.1",          "flask-restful>=0.3.9,<0.4",          "passlib>=1.7.4,<1.8",          "marshmallow>=3.20.1,<3.30",          "apispec[yaml]>=6.3,<7.0",          "apispec-webframeworks>=0.5.2,<0.6",          "taipy-core@git+https://git@github.com/Avaiga/taipy-core.git@develop",      ],  )


from unittest import mock    import pytest  from flask import url_for    from src.taipy.rest.api.exceptions.exceptions import ScenarioIdMissingException, SequenceNameMissingException  from taipy.core.exceptions.exceptions import NonExistingScenario  from taipy.core.scenario._scenario_manager_factory import _ScenarioManagerFactory      def test_get_sequence(client, default_sequence):      # test 404      user_url = url_for("api.sequence_by_id", sequence_id="foo")      rep = client.get(user_url)      assert rep.status_code == 404        with mock.patch("taipy.core.sequence._sequence_manager._SequenceManager._get") as manager_mock:          manager_mock.return_value = default_sequence            # test get_sequence          rep = client.get(url_for("api.sequence_by_id", sequence_id="foo"))          assert rep.status_code == 200      def test_delete_sequence(client):      # test 404      user_url = url_for("api.sequence_by_id", sequence_id="foo")      rep = client.get(user_url)      assert rep.status_code == 404        with mock.patch("taipy.core.sequence._sequence_manager._SequenceManager._delete"), mock.patch(          "taipy.core.sequence._sequence_manager._SequenceManager._get"      ):          # test get_sequence          rep = client.delete(url_for("api.sequence_by_id", sequence_id="foo"))          assert rep.status_code == 200      def test_create_sequence(client, default_scenario):      sequences_url = url_for("api.sequences")      rep = client.post(sequences_url, json={})      assert rep.status_code == 400      assert rep.json == {"message": "Scenario id is missing."}        sequences_url = url_for("api.sequences")      rep = client.post(sequences_url, json={"scenario_id": "SCENARIO_scenario_id"})      assert rep.status_code == 400      assert rep.json == {"message": "Sequence name is missing."}        sequences_url = url_for("api.sequences")      rep = client.post(sequences_url, json={"scenario_id": "SCENARIO_scenario_id", "sequence_name": "sequence"})      assert rep.status_code == 404        _ScenarioManagerFactory._build_manager()._set(default_scenario)      with mock.patch("taipy.core.scenario._scenario_manager._ScenarioManager._get") as config_mock:          config_mock.return_value = default_scenario          sequences_url = url_for("api.sequences")          rep = client.post(              sequences_url, json={"scenario_id": default_scenario.id, "sequence_name": "sequence", "tasks": []}          )          assert rep.status_code == 201      def test_get_all_sequences(client, default_scenario_config_list):      for ds in range(10):          with mock.patch("src.taipy.rest.api.resources.scenario.ScenarioList.fetch_config") as config_mock:              config_mock.return_value = default_scenario_config_list[ds]              scenario_url = url_for("api.scenarios", config_id=config_mock.name)              client.post(scenario_url)        sequences_url = url_for("api.sequences")      rep = client.get(sequences_url)      assert rep.status_code == 200        results = rep.get_json()      assert len(results) == 10      @pytest.mark.xfail()  def test_execute_sequence(client, default_sequence):      # test 404      user_url = url_for("api.sequence_submit", sequence_id="foo")      rep = client.post(user_url)      assert rep.status_code == 404        with mock.patch("taipy.core.sequence._sequence_manager._SequenceManager._get") as manager_mock:          manager_mock.return_value = default_sequence            # test get_sequence          rep = client.post(url_for("api.sequence_submit", sequence_id="foo"))          assert rep.status_code == 200


from unittest import mock    from flask import url_for      def test_get_job(client, default_job):      # test 404      user_url = url_for("api.job_by_id", job_id="foo")      rep = client.get(user_url)      assert rep.status_code == 404        with mock.patch("taipy.core.job._job_manager._JobManager._get") as manager_mock:          manager_mock.return_value = default_job            # test get_job          rep = client.get(url_for("api.job_by_id", job_id="foo"))          assert rep.status_code == 200      def test_delete_job(client):      # test 404      user_url = url_for("api.job_by_id", job_id="foo")      rep = client.get(user_url)      assert rep.status_code == 404        with mock.patch("taipy.core.job._job_manager._JobManager._delete"), mock.patch(          "taipy.core.job._job_manager._JobManager._get"      ):          # test get_job          rep = client.delete(url_for("api.job_by_id", job_id="foo"))          assert rep.status_code == 200      def test_create_job(client, default_task_config):      # without config param      jobs_url = url_for("api.jobs")      rep = client.post(jobs_url)      assert rep.status_code == 400        with mock.patch("src.taipy.rest.api.resources.job.JobList.fetch_config") as config_mock:          config_mock.return_value = default_task_config          jobs_url = url_for("api.jobs", task_id="foo")          rep = client.post(jobs_url)          assert rep.status_code == 201      def test_get_all_jobs(client, create_job_list):      jobs_url = url_for("api.jobs")      rep = client.get(jobs_url)      assert rep.status_code == 200        results = rep.get_json()      assert len(results) == 10      def test_cancel_job(client, default_job):      # test 404      from taipy.core._orchestrator._orchestrator_factory import _OrchestratorFactory        _OrchestratorFactory._build_orchestrator()      _OrchestratorFactory._build_dispatcher()        user_url = url_for("api.job_cancel", job_id="foo")      rep = client.post(user_url)      assert rep.status_code == 404        with mock.patch("taipy.core.job._job_manager._JobManager._get") as manager_mock:          manager_mock.return_value = default_job            # test get_job          rep = client.post(url_for("api.job_cancel", job_id="foo"))          assert rep.status_code == 200


import os  import shutil  import uuid  from datetime import datetime, timedelta    import pandas as pd  import pytest  from dotenv import load_dotenv    from src.taipy.rest.app import create_app  from taipy.config import Config  from taipy.config.common.frequency import Frequency  from taipy.config.common.scope import Scope  from taipy.core import Cycle, DataNodeId, Job, JobId, Scenario, Sequence, Task  from taipy.core.cycle._cycle_manager import _CycleManager  from taipy.core.data.in_memory import InMemoryDataNode  from taipy.core.job._job_manager import _JobManager  from taipy.core.task._task_manager import _TaskManager    from .setup.shared.algorithms import evaluate, forecast      @pytest.fixture  def setup_end_to_end():      model_cfg = Config.configure_data_node("model", path="setup/my_model.p", storage_type="pickle")        day_cfg = Config.configure_data_node(id="day")      forecasts_cfg = Config.configure_data_node(id="forecasts")      forecast_task_cfg = Config.configure_task(          id="forecast_task",          input=[model_cfg, day_cfg],          function=forecast,          output=forecasts_cfg,      )        historical_temperature_cfg = Config.configure_data_node(          "historical_temperature",          storage_type="csv",          path="setup/historical_temperature.csv",          has_header=True,      )      evaluation_cfg = Config.configure_data_node("evaluation")      evaluate_task_cfg = Config.configure_task(          "evaluate_task",          input=[historical_temperature_cfg, forecasts_cfg, day_cfg],          function=evaluate,          output=evaluation_cfg,      )        scenario_config = Config.configure_scenario(          "scenario", [forecast_task_cfg, evaluate_task_cfg], frequency=Frequency.DAILY      )      scenario_config.add_sequences({"sequence": [forecast_task_cfg, evaluate_task_cfg]})      @pytest.fixture()  def app():      load_dotenv(".testenv")      app = create_app(testing=True)      app.config.update(          {              "TESTING": True,          }      )      with app.app_context(), app.test_request_context():          yield app      @pytest.fixture()  def client(app):      return app.test_client()      @pytest.fixture  def datanode_data():      return {          "name": "foo",          "storage_type": "in_memory",          "scope": "scenario",          "default_data": ["1991-01-01T00:00:00"],      }      @pytest.fixture  def task_data():      return {          "config_id": "foo",          "input_ids": ["DATASOURCE_foo_3b888e17-1974-4a56-a42c-c7c96bc9cd54"],          "function_name": "print",          "function_module": "builtins",          "output_ids": ["DATASOURCE_foo_4d9923b8-eb9f-4f3c-8055-3a1ce8bee309"],      }      @pytest.fixture  def sequence_data():      return {          "name": "foo",          "task_ids": ["TASK_foo_3b888e17-1974-4a56-a42c-c7c96bc9cd54"],      }      @pytest.fixture  def scenario_data():      return {          "name": "foo",          "sequence_ids": ["SEQUENCE_foo_3b888e17-1974-4a56-a42c-c7c96bc9cd54"],          "properties": {},      }      @pytest.fixture  def default_datanode():      return InMemoryDataNode(          "input_ds",          Scope.SCENARIO,          DataNodeId("f"),          "my name",          "owner_id",          properties={"default_data": [1, 2, 3, 4, 5, 6]},      )      @pytest.fixture  def default_df_datanode():      return InMemoryDataNode(          "input_ds",          Scope.SCENARIO,          DataNodeId("id_uio2"),          "my name",          "owner_id",          properties={"default_data": pd.DataFrame([{"a": 1, "b": 2}, {"a": 3, "b": 4}, {"a": 5, "b": 6}])},      )      @pytest.fixture  def default_datanode_config():      return Config.configure_data_node(f"taipy_{uuid.uuid4().hex}", "in_memory", Scope.SCENARIO)      @pytest.fixture  def default_datanode_config_list():      configs = []      for i in range(10):          configs.append(Config.configure_data_node(id=f"ds_{i}", storage_type="in_memory", scope=Scope.SCENARIO))      return configs      def __default_task():      input_ds = InMemoryDataNode(          "input_ds",          Scope.SCENARIO,          DataNodeId("id_uio"),          "my name",          "owner_id",          properties={"default_data": "In memory Data Source"},      )        output_ds = InMemoryDataNode(          "output_ds",          Scope.SCENARIO,          DataNodeId("id_uio"),          "my name",          "owner_id",          properties={"default_data": "In memory Data Source"},      )      return Task(          config_id="foo",          properties={},          function=print,          input=[input_ds],          output=[output_ds],          id=None,      )      @pytest.fixture  def default_task():      return __default_task()      @pytest.fixture  def default_task_config():      return Config.configure_task("task1", print, [], [])      @pytest.fixture  def default_task_config_list():      configs = []      for i in range(10):          configs.append(Config.configure_task(f"task_{i}", print, [], []))      return configs      def __default_sequence():      return Sequence(properties={"name": "foo"}, tasks=[__default_task()], sequence_id="SEQUENCE_foo_SCENARIO_acb")      def __task_config():      return Config.configure_task("task1", print, [], [])      @pytest.fixture  def default_sequence():      return __default_sequence()      @pytest.fixture  def default_scenario_config():      task_config = __task_config()      scenario_config = Config.configure_scenario(          f"taipy_{uuid.uuid4().hex}",          [task_config],      )      scenario_config.add_sequences({"sequence": [task_config]})      return scenario_config      @pytest.fixture  def default_scenario_config_list():      configs = []      for _ in range(10):          task_config = Config.configure_task(f"taipy_{uuid.uuid4().hex}", print)          scenario_config = Config.configure_scenario(              f"taipy_{uuid.uuid4().hex}",              [task_config],          )          scenario_config.add_sequences({"sequence": [task_config]})          configs.append(scenario_config)      return configs      @pytest.fixture  def default_scenario():      return Scenario(config_id="foo", properties={}, tasks=[__default_task()], scenario_id="SCENARIO_scenario_id")      def __create_cycle(name="foo"):      now = datetime.now()      return Cycle(          name=name,          frequency=Frequency.DAILY,          properties={},          creation_date=now,          start_date=now,          end_date=now + timedelta(days=5),      )      @pytest.fixture  def create_cycle_list():      cycles = []      manager = _CycleManager      for i in range(10):          c = __create_cycle(f"cycle_{1}")      return cycles      @pytest.fixture  def cycle_data():      return {          "name": "foo",          "frequency": "daily",          "properties": {},          "creation_date": "2022-02-03T22:17:27.317114",          "start_date": "2022-02-03T22:17:27.317114",          "end_date": "2022-02-08T22:17:27.317114",      }      @pytest.fixture  def default_cycle():      return __create_cycle()      def __create_job():      task_manager = _TaskManager      task = __default_task()      task_manager._set(task)      submit_id = f"SUBMISSION_{str(uuid.uuid4())}"      return Job(id=JobId(f"JOB_{uuid.uuid4()}"), task=task, submit_id=submit_id, submit_entity_id=task.id)      @pytest.fixture  def default_job():      return __create_job()      @pytest.fixture  def create_job_list():      jobs = []      manager = _JobManager      for i in range(10):          c = __create_job()      return jobs      @pytest.fixture(scope="function", autouse=True)  def cleanup_files():      Config.unblock_update()      if os.path.exists(".data"):          shutil.rmtree(".data")


from unittest import mock    from flask import url_for      def test_get_task(client, default_task):      # test 404      user_url = url_for("api.task_by_id", task_id="foo")      rep = client.get(user_url)      assert rep.status_code == 404        with mock.patch("taipy.core.task._task_manager._TaskManager._get") as manager_mock:          manager_mock.return_value = default_task            # test get_task          rep = client.get(url_for("api.task_by_id", task_id="foo"))          assert rep.status_code == 200      def test_delete_task(client):      # test 404      user_url = url_for("api.task_by_id", task_id="foo")      rep = client.get(user_url)      assert rep.status_code == 404        with mock.patch("taipy.core.task._task_manager._TaskManager._delete"), mock.patch(          "taipy.core.task._task_manager._TaskManager._get"      ):          # test get_task          rep = client.delete(url_for("api.task_by_id", task_id="foo"))          assert rep.status_code == 200      def test_create_task(client, default_task_config):      # without config param      tasks_url = url_for("api.tasks")      rep = client.post(tasks_url)      assert rep.status_code == 400        # config does not exist      tasks_url = url_for("api.tasks", config_id="foo")      rep = client.post(tasks_url)      assert rep.status_code == 404        with mock.patch("src.taipy.rest.api.resources.task.TaskList.fetch_config") as config_mock:          config_mock.return_value = default_task_config          tasks_url = url_for("api.tasks", config_id="bar")          rep = client.post(tasks_url)          assert rep.status_code == 201      def test_get_all_tasks(client, task_data, default_task_config_list):      for ds in range(10):          with mock.patch("src.taipy.rest.api.resources.task.TaskList.fetch_config") as config_mock:              config_mock.return_value = default_task_config_list[ds]              tasks_url = url_for("api.tasks", config_id=config_mock.name)              client.post(tasks_url)        rep = client.get(tasks_url)      assert rep.status_code == 200        results = rep.get_json()      assert len(results) == 10      def test_execute_task(client, default_task):      # test 404      user_url = url_for("api.task_submit", task_id="foo")      rep = client.post(user_url)      assert rep.status_code == 404        with mock.patch("taipy.core.task._task_manager._TaskManager._get") as manager_mock:          manager_mock.return_value = default_task            # test get_task          rep = client.post(url_for("api.task_submit", task_id="foo"))          assert rep.status_code == 200


from functools import wraps  from unittest.mock import MagicMock, patch    from src.taipy.rest.api.middlewares._middleware import _middleware      def mock_enterprise_middleware(f):      @wraps(f)      def wrapper(*args, **kwargs):          return f(*args, **kwargs)        return wrapper      @patch("src.taipy.rest.api.middlewares._middleware._using_enterprise")  @patch("src.taipy.rest.api.middlewares._middleware._enterprise_middleware")  def test_enterprise_middleware_applied_when_enterprise_is_installed(      enterprise_middleware: MagicMock, using_enterprise: MagicMock  ):      enterprise_middleware.return_value = mock_enterprise_middleware      using_enterprise.return_value = True        @_middleware      def f():          return "f"        rv = f()      assert rv == "f"      using_enterprise.assert_called_once()      enterprise_middleware.assert_called_once()      @patch("src.taipy.rest.api.middlewares._middleware._using_enterprise")  @patch("src.taipy.rest.api.middlewares._middleware._enterprise_middleware")  def test_enterprise_middleware_not_applied_when_enterprise_is_not_installed(      enterprise_middleware: MagicMock, using_enterprise: MagicMock  ):      enterprise_middleware.return_value = mock_enterprise_middleware      using_enterprise.return_value = False        @_middleware      def f():          return "f"        rv = f()      assert rv == "f"      using_enterprise.assert_called_once()      enterprise_middleware.assert_not_called()


from unittest import mock    import pytest  from flask import url_for      def test_get_datanode(client, default_datanode):      # test 404      user_url = url_for("api.datanode_by_id", datanode_id="foo")      rep = client.get(user_url)      assert rep.status_code == 404        with mock.patch("taipy.core.data._data_manager._DataManager._get") as manager_mock:          manager_mock.return_value = default_datanode          # test get_datanode          rep = client.get(url_for("api.datanode_by_id", datanode_id="foo"))          assert rep.status_code == 200      def test_delete_datanode(client):      # test 404      user_url = url_for("api.datanode_by_id", datanode_id="foo")      rep = client.get(user_url)      assert rep.status_code == 404        with mock.patch("taipy.core.data._data_manager._DataManager._delete"), mock.patch(          "taipy.core.data._data_manager._DataManager._get"      ):          # test get_datanode          rep = client.delete(url_for("api.datanode_by_id", datanode_id="foo"))          assert rep.status_code == 200      def test_create_datanode(client, default_datanode_config):      # without config param      datanodes_url = url_for("api.datanodes")      rep = client.post(datanodes_url)      assert rep.status_code == 400        # config does not exist      datanodes_url = url_for("api.datanodes", config_id="foo")      rep = client.post(datanodes_url)      assert rep.status_code == 404        with mock.patch("src.taipy.rest.api.resources.datanode.DataNodeList.fetch_config") as config_mock:          config_mock.return_value = default_datanode_config          datanodes_url = url_for("api.datanodes", config_id="bar")          rep = client.post(datanodes_url)          assert rep.status_code == 201      def test_get_all_datanodes(client, default_datanode_config_list):      for ds in range(10):          with mock.patch("src.taipy.rest.api.resources.datanode.DataNodeList.fetch_config") as config_mock:              config_mock.return_value = default_datanode_config_list[ds]              datanodes_url = url_for("api.datanodes", config_id=config_mock.name)              client.post(datanodes_url)        rep = client.get(datanodes_url)      assert rep.status_code == 200        results = rep.get_json()      assert len(results) == 10      def test_read_datanode(client, default_df_datanode):      with mock.patch("taipy.core.data._data_manager._DataManager._get") as config_mock:          config_mock.return_value = default_df_datanode            # without operators          datanodes_url = url_for("api.datanode_reader", datanode_id="foo")          rep = client.get(datanodes_url, json={})          assert rep.status_code == 200            # Without operators and body          rep = client.get(datanodes_url)          assert rep.status_code == 200            # TODO: Revisit filter test          # operators = {"operators": [{"key": "a", "value": 5, "operator": "LESS_THAN"}]}          # rep = client.get(datanodes_url, json=operators)          # assert rep.status_code == 200      def test_write_datanode(client, default_datanode):      with mock.patch("taipy.core.data._data_manager._DataManager._get") as config_mock:          config_mock.return_value = default_datanode          # Get DataNode          datanodes_read_url = url_for("api.datanode_reader", datanode_id=default_datanode.id)          rep = client.get(datanodes_read_url, json={})          assert rep.status_code == 200          assert rep.json == {"data": [1, 2, 3, 4, 5, 6]}            datanodes_write_url = url_for("api.datanode_writer", datanode_id=default_datanode.id)          rep = client.put(datanodes_write_url, json=[1, 2, 3])          assert rep.status_code == 200            rep = client.get(datanodes_read_url, json={})          assert rep.status_code == 200          assert rep.json == {"data": [1, 2, 3]}


#  # Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with  # the License. You may obtain a copy of the License at  #  #        http://www.apache.org/licenses/LICENSE-2.0  #  # Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on  # an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the  # specific language governing permissions and limitations under the License.


import json  from typing import Dict    from flask import url_for      def create_and_submit_scenario(config_id: str, client) -> Dict:      response = client.post(url_for("api.scenarios", config_id=config_id))      assert response.status_code == 201        scenario = response.json.get("scenario")      assert (set(scenario) - set(json.load(open("tests/json/expected/scenario.json")))) == set()        response = client.post(url_for("api.scenario_submit", scenario_id=scenario.get("id")))      assert response.status_code == 200        return scenario      def get(url, name, client) -> Dict:      response = client.get(url)      returned_data = response.json.get(name)        assert (set(returned_data) - set(json.load(open(f"tests/json/expected/{name}.json")))) == set()        return returned_data      def get_assert_status(url, client, status_code) -> None:      response = client.get(url)      assert response.status_code == status_code      def get_all(url, expected_quantity, client):      response = client.get(url)        assert len(response.json) == expected_quantity      def delete(url, client):      response = client.delete(url)        assert response.status_code == 200      def test_end_to_end(client, setup_end_to_end):      # Create Scenario: Should also create all of its dependencies(sequences, tasks, datanodes, etc)      scenario = create_and_submit_scenario("scenario", client)        # Get other models and verify if they return the necessary fields      cycle = get(url_for("api.cycle_by_id", cycle_id=scenario.get("cycle")), "cycle", client)      sequence = get(          url_for("api.sequence_by_id", sequence_id=f"SEQUENCE_sequence_{scenario['id']}"),          "sequence",          client,      )      task = get(url_for("api.task_by_id", task_id=sequence.get("tasks")[0]), "task", client)      datanode = get(          url_for("api.datanode_by_id", datanode_id=task.get("input_ids")[0]),          "datanode",          client,      )      # Get All      get_all(url_for("api.scenarios"), 1, client)      get_all(url_for("api.cycles"), 1, client)      get_all(url_for("api.sequences"), 1, client)      get_all(url_for("api.tasks"), 2, client)      get_all(url_for("api.datanodes"), 5, client)      get_all(url_for("api.jobs"), 2, client)        # Delete entities      delete(url_for("api.cycle_by_id", cycle_id=cycle.get("id")), client)      delete(url_for("api.sequence_by_id", sequence_id=sequence.get("id")), client)      delete(url_for("api.task_by_id", task_id=task.get("id")), client)      delete(url_for("api.datanode_by_id", datanode_id=datanode.get("id")), client)        # Check status code      # Non-existing entities should return 404      get_assert_status(url_for("api.cycle_by_id", cycle_id=9999999), client, 404)      get_assert_status(url_for("api.scenario_by_id", scenario_id=9999999), client, 404)      get_assert_status(url_for("api.sequence_by_id", sequence_id=9999999), client, 404)      get_assert_status(url_for("api.task_by_id", task_id=9999999), client, 404)      get_assert_status(url_for("api.datanode_by_id", datanode_id=9999999), client, 404)        # Check URL with and without trailing slashes      url_with_slash = url_for("api.scenarios")      url_without_slash = url_for("api.scenarios")[:-1]      get_all(url_with_slash, 1, client)      get_all(url_without_slash, 1, client)


from unittest import mock    from flask import url_for      def test_get_cycle(client, default_cycle):      # test 404      cycle_url = url_for("api.cycle_by_id", cycle_id="foo")      rep = client.get(cycle_url)      assert rep.status_code == 404        with mock.patch("taipy.core.cycle._cycle_manager._CycleManager._get") as manager_mock:          manager_mock.return_value = default_cycle            # test get_cycle          rep = client.get(url_for("api.cycle_by_id", cycle_id="foo"))          assert rep.status_code == 200      def test_delete_cycle(client):      # test 404      cycle_url = url_for("api.cycle_by_id", cycle_id="foo")      rep = client.get(cycle_url)      assert rep.status_code == 404        with mock.patch("taipy.core.cycle._cycle_manager._CycleManager._delete"), mock.patch(          "taipy.core.cycle._cycle_manager._CycleManager._get"      ):          # test get_cycle          rep = client.delete(url_for("api.cycle_by_id", cycle_id="foo"))          assert rep.status_code == 200      def test_create_cycle(client, cycle_data):      # without config param      cycles_url = url_for("api.cycles")      data = {"bad": "data"}      rep = client.post(cycles_url, json=data)      assert rep.status_code == 400        rep = client.post(cycles_url, json=cycle_data)      assert rep.status_code == 201      def test_get_all_cycles(client, create_cycle_list):      cycles_url = url_for("api.cycles")      rep = client.get(cycles_url)      assert rep.status_code == 200        results = rep.get_json()      assert len(results) == 10


from unittest import mock    import pytest  from flask import url_for      def test_get_scenario(client, default_scenario):      # test 404      user_url = url_for("api.scenario_by_id", scenario_id="foo")      rep = client.get(user_url)      assert rep.status_code == 404        with mock.patch("taipy.core.scenario._scenario_manager._ScenarioManager._get") as manager_mock:          manager_mock.return_value = default_scenario            # test get_scenario          rep = client.get(url_for("api.scenario_by_id", scenario_id="foo"))          assert rep.status_code == 200      def test_delete_scenario(client):      # test 404      user_url = url_for("api.scenario_by_id", scenario_id="foo")      rep = client.get(user_url)      assert rep.status_code == 404        with mock.patch("taipy.core.scenario._scenario_manager._ScenarioManager._delete"), mock.patch(          "taipy.core.scenario._scenario_manager._ScenarioManager._get"      ):          # test get_scenario          rep = client.delete(url_for("api.scenario_by_id", scenario_id="foo"))          assert rep.status_code == 200      def test_create_scenario(client, default_scenario_config):      # without config param      scenarios_url = url_for("api.scenarios")      rep = client.post(scenarios_url)      assert rep.status_code == 400        # config does not exist      scenarios_url = url_for("api.scenarios", config_id="foo")      rep = client.post(scenarios_url)      assert rep.status_code == 404        with mock.patch("src.taipy.rest.api.resources.scenario.ScenarioList.fetch_config") as config_mock:          config_mock.return_value = default_scenario_config          scenarios_url = url_for("api.scenarios", config_id="bar")          rep = client.post(scenarios_url)          assert rep.status_code == 201      def test_get_all_scenarios(client, default_sequence, default_scenario_config_list):      for ds in range(10):          with mock.patch("src.taipy.rest.api.resources.scenario.ScenarioList.fetch_config") as config_mock:              config_mock.return_value = default_scenario_config_list[ds]              scenarios_url = url_for("api.scenarios", config_id=config_mock.name)              client.post(scenarios_url)        rep = client.get(scenarios_url)      assert rep.status_code == 200        results = rep.get_json()      assert len(results) == 10      @pytest.mark.xfail()  def test_execute_scenario(client, default_scenario):      # test 404      user_url = url_for("api.scenario_submit", scenario_id="foo")      rep = client.post(user_url)      assert rep.status_code == 404        with mock.patch("taipy.core.scenario._scenario_manager._ScenarioManager._get") as manager_mock:          manager_mock.return_value = default_scenario            # test get_scenario          rep = client.post(url_for("api.scenario_submit", scenario_id="foo"))          assert rep.status_code == 200


import pickle  import random  from datetime import datetime, timedelta  from typing import Any, Dict    import pandas as pd    n_predictions = 14      def forecast(model, date: datetime):      dates = [date + timedelta(days=i) for i in range(n_predictions)]      forecasts = [f + random.uniform(0, 2) for f in model.forecast(len(dates))]      days = [str(dt.date()) for dt in dates]      res = {"Date": days, "Forecast": forecasts}      return pd.DataFrame.from_dict(res)      def evaluate(cleaned: pd.DataFrame, forecasts: pd.DataFrame, date: datetime) -> Dict[str, Any]:      cleaned = cleaned[cleaned["Date"].isin(forecasts["Date"].tolist())]      forecasts_as_series = pd.Series(forecasts["Forecast"].tolist(), name="Forecast")      res = pd.concat([cleaned.reset_index(), forecasts_as_series], axis=1)      res["Delta"] = abs(res["Forecast"] - res["Value"])        return {          "Date": date,          "Dataframe": res,          "Mean_absolute_error": res["Delta"].mean(),          "Relative_error": (res["Delta"].mean() * 100) / res["Value"].mean(),      }      if __name__ == "__main__":      model = pickle.load(open("../my_model.p", "rb"))      day = datetime(2020, 1, 25)      forecasts = forecast(model, day)        historical_temperature = pd.read_csv("../historical_temperature.csv")      evaluation = evaluate(historical_temperature, forecasts, day)        print(evaluation["Dataframe"])      print()      print(f'Mean absolute error : {evaluation["Mean_absolute_error"]}')      print(f'Relative error in %: {evaluation["Relative_error"]}')


from taipy.core import Config, Frequency    from .algorithms import evaluate, forecast    model_cfg = Config.configure_data_node("model", path="my_model.p", storage_type="pickle")    day_cfg = Config.configure_data_node(id="day")  forecasts_cfg = Config.configure_data_node(id="forecasts")  forecast_task_cfg = Config.configure_task(      id="forecast_task",      input=[model_cfg, day_cfg],      function=forecast,      output=forecasts_cfg,  )    historical_temperature_cfg = Config.configure_data_node(      "historical_temperature",      storage_type="csv",      path="historical_temperature.csv",      has_header=True,  )  evaluation_cfg = Config.configure_data_node("evaluation")  evaluate_task_cfg = Config.configure_task(      "evaluate_task",      input=[historical_temperature_cfg, forecasts_cfg, day_cfg],      function=evaluate,      output=evaluation_cfg,  )    scenario_cfg = Config.configure_scenario("scenario", [forecast_task_cfg, evaluate_task_cfg], frequency=Frequency.DAILY)  scenario_cfg.add_sequences({"sequence": [forecast_task_cfg, evaluate_task_cfg]})


from importlib.util import find_spec    if find_spec("taipy"):      if find_spec("taipy.config"):          from taipy.config._init import *  # type: ignore        if find_spec("taipy.gui"):          from taipy.gui._init import *  # type: ignore        if find_spec("taipy.core"):          from taipy.core._init import *  # type: ignore        if find_spec("taipy.rest"):          from taipy.rest._init import *  # type: ignore        if find_spec("taipy.gui_core"):          from taipy.gui_core._init import *  # type: ignore        if find_spec("taipy.enterprise"):          from taipy.enterprise._init import *  # type: ignore        if find_spec("taipy._run"):          from taipy._run import _run as run  # type: ignore


import json  import os      def _get_version():      with open(f"{os.path.dirname(os.path.abspath(__file__))}{os.sep}version.json") as version_file:          version = json.load(version_file)          version_string = f'{version.get("major", 0)}.{version.get("minor", 0)}.{version.get("patch", 0)}'          if vext := version.get("ext"):              version_string = f"{version_string}.{vext}"      return version_string


from .rest import Rest


#  # Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with  # the License. You may obtain a copy of the License at  #  #        http://www.apache.org/licenses/LICENSE-2.0  #  # Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on  # an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the  # specific language governing permissions and limitations under the License.  from taipy.config import Config    from .app import create_app as _create_app      class Rest:      """      Runnable Rest application serving REST APIs on top of Taipy Core functionalities.      """        def __init__(self):          """          Initialize a REST API server.            A Flask application is instantiated and configured using three parameters from the global          config.              - Config.global_config.testing (bool): Run the application on testing mode.              - Config.global_config.env (Optional[str]): The application environment.              - Config.global_config.secret_key (Optional[str]): Application server secret key.            However, editing these parameters is only recommended for advanced users. Indeed, the default behavior of the          REST server without any required configuration satisfies all the standard and basic needs.          """          self._app = _create_app(Config.global_config.testing or False, Config.global_config.env,                                  Config.global_config.secret_key)        def run(self, **kwargs):          """          Start a REST API server. This method is blocking.            Parameters:              **kwargs : Options to provide to the application server.          """          self._app.run(**kwargs)


"""# Taipy Rest    The Taipy Rest package exposes the Runnable `Rest^` service to provide REST APIs on top of Taipy Core. (more details  on Taipy Core functionalities in the [user manual](../../../manuals/core/)).    Once the `Rest^` service runs, users can call REST APIs to create, read, update, submit and remove Taipy entities  (including cycles, scenarios, sequences, tasks, jobs, and data nodes). It is handy when it comes to integrating a  Taipy application in a more complex IT ecosystem.    Please refer to [REST API](../../reference_rest/) page to get the exhaustive list of available APIs."""    from ._init import *  from .version import _get_version    __version__ = _get_version()


"""Extensions registry    All extensions here are used as singletons and  initialized in application factory  """    from .commons.apispec import APISpecExt    apispec = APISpecExt()


import os    from flask import Flask    from . import api  from .commons.encoder import _CustomEncoder  from .extensions import apispec      def create_app(testing=False, flask_env=None, secret_key=None):      """Application factory, used to create application"""      app = Flask(__name__)      app.config.update(          ENV=os.getenv("FLASK_ENV", flask_env),          TESTING=os.getenv("TESTING", testing),          SECRET_KEY=os.getenv("SECRET_KEY", secret_key),      )      app.url_map.strict_slashes = False      app.config["RESTFUL_JSON"] = {"cls": _CustomEncoder}        configure_apispec(app)      register_blueprints(app)      with app.app_context():          api.views.register_views()        return app      def configure_apispec(app):      """Configure APISpec for swagger support"""      apispec.init_app(app)        apispec.spec.components.schema(          "PaginatedResult",          {              "properties": {                  "total": {"type": "integer"},                  "pages": {"type": "integer"},                  "next": {"type": "string"},                  "prev": {"type": "string"},              }          },      )      def register_blueprints(app):      """Register all blueprints for application"""      app.register_blueprint(api.views.blueprint)


from taipy.core.cycle._cycle_converter import _CycleConverter  from taipy.core.data._data_converter import _DataNodeConverter  from taipy.core.scenario._scenario_converter import _ScenarioConverter  from taipy.core.sequence._sequence_converter import _SequenceConverter  from taipy.core.task._task_converter import _TaskConverter    entity_to_models = {      "scenario": _ScenarioConverter._entity_to_model,      "sequence": _SequenceConverter._entity_to_model,      "task": _TaskConverter._entity_to_model,      "data": _DataNodeConverter._entity_to_model,      "cycle": _CycleConverter._entity_to_model,  }      def _to_model(repository, entity, **kwargs):      return entity_to_models[repository](entity)


from apispec import APISpec  from apispec.exceptions import APISpecError  from apispec.ext.marshmallow import MarshmallowPlugin  from apispec_webframeworks.flask import FlaskPlugin  from flask import Blueprint, jsonify, render_template      class FlaskRestfulPlugin(FlaskPlugin):      """Small plugin override to handle flask-restful resources"""        @staticmethod      def _rule_for_view(view, app=None):          view_funcs = app.view_functions          endpoint = None            for ept, view_func in view_funcs.items():              if hasattr(view_func, "view_class"):                  view_func = view_func.view_class                if view_func == view:                  endpoint = ept            if not endpoint:              raise APISpecError("Could not find endpoint for view {0}".format(view))            # WARNING: Assume 1 rule per view function for now          rule = app.url_map._rules_by_endpoint[endpoint][0]          return rule      class APISpecExt:      """Very simple and small extension to use apispec with this API as a flask extension"""        def __init__(self, app=None, **kwargs):          self.spec = None            if app is not None:              self.init_app(app, **kwargs)        def init_app(self, app, **kwargs):          app.config.setdefault("APISPEC_TITLE", "Taipy Rest")          app.config.setdefault("APISPEC_VERSION", "1.0.0")          app.config.setdefault("OPENAPI_VERSION", "3.0.2")          app.config.setdefault("SWAGGER_JSON_URL", "/swagger.json")          app.config.setdefault("SWAGGER_UI_URL", "/swagger-ui")          app.config.setdefault("OPENAPI_YAML_URL", "/openapi.yaml")          app.config.setdefault("REDOC_UI_URL", "/redoc-ui")          app.config.setdefault("SWAGGER_URL_PREFIX", None)            self.spec = APISpec(              title=app.config["APISPEC_TITLE"],              version=app.config["APISPEC_VERSION"],              openapi_version=app.config["OPENAPI_VERSION"],              plugins=[MarshmallowPlugin(), FlaskRestfulPlugin()],              **kwargs          )            blueprint = Blueprint(              "swagger",              __name__,              template_folder="./templates",              url_prefix=app.config["SWAGGER_URL_PREFIX"],          )            blueprint.add_url_rule(app.config["SWAGGER_JSON_URL"], "swagger_json", self.swagger_json)          blueprint.add_url_rule(app.config["SWAGGER_UI_URL"], "swagger_ui", self.swagger_ui)          blueprint.add_url_rule(app.config["OPENAPI_YAML_URL"], "openapi_yaml", self.openapi_yaml)          blueprint.add_url_rule(app.config["REDOC_UI_URL"], "redoc_ui", self.redoc_ui)            app.register_blueprint(blueprint)        def swagger_json(self):          return jsonify(self.spec.to_dict())        def swagger_ui(self):          return render_template("swagger.j2")        def openapi_yaml(self):          # Manually inject ReDoc's Authentication legend, then remove it          self.spec.tag(              {                  "name": "authentication",                  "x-displayName": "Authentication",                  "description": "<SecurityDefinitions />",              }          )          redoc_spec = self.spec.to_yaml()          self.spec._tags.pop(0)          return redoc_spec        def redoc_ui(self):          return render_template("redoc.j2")


import json  from typing import Any, Union  from datetime import datetime  from enum import Enum        Json = Union[dict, list, str, int, float, bool, None]    class _CustomEncoder(json.JSONEncoder):      def default(self, o: Any) -> Json:          if isinstance(o, Enum):              result = o.value          elif isinstance(o, datetime):              result = {"__type__": "Datetime", "__value__": o.isoformat()}          else:              result = json.JSONEncoder.default(self, o)          return result