from unittest.mock import Mock, patch    import pytest    from src.taipy.gui_core._context import _GuiCoreContext, _SubmissionStatus  from taipy.core import Status      class MockJob:      def __init__(self, id: str, status):          self.status = status          self.id = id        def is_failed(self):          return self.status == Status.FAILED        def is_canceled(self):          return self.status == Status.CANCELED        def is_blocked(self):          return self.status == Status.BLOCKED        def is_pending(self):          return self.status == Status.PENDING        def is_running(self):          return self.status == Status.RUNNING        def is_completed(self):          return self.status == Status.COMPLETED        def is_skipped(self):          return self.status == Status.SKIPPED        def is_abandoned(self):          return self.status == Status.ABANDONED        def is_submitted(self):          return self.status == Status.SUBMITTED      def mock_core_get(entity_id):      jobs = {          "job0_submitted": MockJob("job0_submitted", Status.SUBMITTED),          "job1_failed": MockJob("job1_failed", Status.FAILED),          "job2_canceled": MockJob("job2_canceled", Status.CANCELED),          "job3_blocked": MockJob("job3_blocked", Status.BLOCKED),          "job4_pending": MockJob("job4_pending", Status.PENDING),          "job5_running": MockJob("job5_running", Status.RUNNING),          "job6_completed": MockJob("job6_completed", Status.COMPLETED),          "job7_skipped": MockJob("job7_skipped", Status.SKIPPED),          "job8_abandoned": MockJob("job8_abandoned", Status.ABANDONED),      }      return jobs[entity_id]      class TestGuiCoreContext_SubmissionStatus:      @pytest.mark.parametrize(          "job_ids, expected_status",          [              (["job1_failed"], _SubmissionStatus.FAILED),              (["job2_canceled"], _SubmissionStatus.CANCELED),              (["job3_blocked"], _SubmissionStatus.BLOCKED),              (["job4_pending"], _SubmissionStatus.WAITING),              (["job5_running"], _SubmissionStatus.RUNNING),              (["job6_completed"], _SubmissionStatus.COMPLETED),              (["job7_skipped"], _SubmissionStatus.COMPLETED),              (["job8_abandoned"], _SubmissionStatus.UNDEFINED),          ],      )      def test_single_job(self, job_ids, expected_status):          with patch("src.taipy.gui_core._context.core_get", side_effect=mock_core_get):              gui_core_context = _GuiCoreContext(Mock())              status = gui_core_context._get_submittable_status(job_ids)              assert status == expected_status        @pytest.mark.parametrize(          "job_ids, expected_status",          [              (["job1_failed", "job1_failed"], _SubmissionStatus.FAILED),              (["job1_failed", "job2_canceled"], _SubmissionStatus.FAILED),              (["job1_failed", "job3_blocked"], _SubmissionStatus.FAILED),              (["job1_failed", "job4_pending"], _SubmissionStatus.FAILED),              (["job1_failed", "job5_running"], _SubmissionStatus.FAILED),              (["job1_failed", "job6_completed"], _SubmissionStatus.FAILED),              (["job1_failed", "job7_skipped"], _SubmissionStatus.FAILED),              (["job1_failed", "job8_abandoned"], _SubmissionStatus.FAILED),              (["job2_canceled", "job1_failed"], _SubmissionStatus.FAILED),              (["job3_blocked", "job1_failed"], _SubmissionStatus.FAILED),              (["job4_pending", "job1_failed"], _SubmissionStatus.FAILED),              (["job5_running", "job1_failed"], _SubmissionStatus.FAILED),              (["job6_completed", "job1_failed"], _SubmissionStatus.FAILED),              (["job7_skipped", "job1_failed"], _SubmissionStatus.FAILED),              (["job8_abandoned", "job1_failed"], _SubmissionStatus.FAILED),          ],      )      def test_one_failed_job(self, job_ids, expected_status):          with patch("src.taipy.gui_core._context.core_get", side_effect=mock_core_get):              gui_core_context = _GuiCoreContext(Mock())              status = gui_core_context._get_submittable_status(job_ids)              assert status == expected_status        @pytest.mark.parametrize(          "job_ids, expected_status",          [              (["job2_canceled", "job2_canceled"], _SubmissionStatus.CANCELED),              (["job2_canceled", "job3_blocked"], _SubmissionStatus.CANCELED),              (["job2_canceled", "job4_pending"], _SubmissionStatus.CANCELED),              (["job2_canceled", "job5_running"], _SubmissionStatus.CANCELED),              (["job2_canceled", "job6_completed"], _SubmissionStatus.CANCELED),              (["job2_canceled", "job7_skipped"], _SubmissionStatus.CANCELED),              (["job2_canceled", "job8_abandoned"], _SubmissionStatus.CANCELED),              (["job3_blocked", "job2_canceled"], _SubmissionStatus.CANCELED),              (["job4_pending", "job2_canceled"], _SubmissionStatus.CANCELED),              (["job5_running", "job2_canceled"], _SubmissionStatus.CANCELED),              (["job6_completed", "job2_canceled"], _SubmissionStatus.CANCELED),              (["job7_skipped", "job2_canceled"], _SubmissionStatus.CANCELED),              (["job8_abandoned", "job2_canceled"], _SubmissionStatus.CANCELED),          ],      )      def test_no_failed_one_cancel(self, job_ids, expected_status):          with patch("src.taipy.gui_core._context.core_get", side_effect=mock_core_get):              gui_core_context = _GuiCoreContext(Mock())              status = gui_core_context._get_submittable_status(job_ids)              assert status == expected_status        @pytest.mark.parametrize(          "job_ids, expected_status",          [              (["job4_pending", "job3_blocked"], _SubmissionStatus.WAITING),              (["job4_pending", "job4_pending"], _SubmissionStatus.WAITING),              (["job4_pending", "job6_completed"], _SubmissionStatus.WAITING),              (["job4_pending", "job7_skipped"], _SubmissionStatus.WAITING),              (["job3_blocked", "job4_pending"], _SubmissionStatus.WAITING),              (["job6_completed", "job4_pending"], _SubmissionStatus.WAITING),              (["job7_skipped", "job4_pending"], _SubmissionStatus.WAITING),          ],      )      def test_no_failed_or_cancel_one_pending(self, job_ids, expected_status):          with patch("src.taipy.gui_core._context.core_get", side_effect=mock_core_get):              gui_core_context = _GuiCoreContext(Mock())              status = gui_core_context._get_submittable_status(job_ids)              assert status == expected_status        @pytest.mark.parametrize(          "job_ids, expected_status",          [              (["job5_running", "job3_blocked"], _SubmissionStatus.RUNNING),              (["job5_running", "job4_pending"], _SubmissionStatus.RUNNING),              (["job5_running", "job5_running"], _SubmissionStatus.RUNNING),              (["job5_running", "job6_completed"], _SubmissionStatus.RUNNING),              (["job5_running", "job7_skipped"], _SubmissionStatus.RUNNING),              (["job3_blocked", "job5_running"], _SubmissionStatus.RUNNING),              (["job4_pending", "job5_running"], _SubmissionStatus.RUNNING),              (["job6_completed", "job5_running"], _SubmissionStatus.RUNNING),              (["job7_skipped", "job5_running"], _SubmissionStatus.RUNNING),          ],      )      def test_no_failed_cancel_nor_pending_one_running(self, job_ids, expected_status):          with patch("src.taipy.gui_core._context.core_get", side_effect=mock_core_get):              gui_core_context = _GuiCoreContext(Mock())              status = gui_core_context._get_submittable_status(job_ids)              assert status == expected_status        @pytest.mark.parametrize(          "job_ids, expected_status",          [              (["job3_blocked", "job3_blocked"], _SubmissionStatus.BLOCKED),              (["job3_blocked", "job6_completed"], _SubmissionStatus.BLOCKED),              (["job3_blocked", "job7_skipped"], _SubmissionStatus.BLOCKED),              (["job6_completed", "job3_blocked"], _SubmissionStatus.BLOCKED),              (["job7_skipped", "job3_blocked"], _SubmissionStatus.BLOCKED),          ],      )      def test_no_failed_cancel_pending_nor_running_one_blocked(self, job_ids, expected_status):          with patch("src.taipy.gui_core._context.core_get", side_effect=mock_core_get):              gui_core_context = _GuiCoreContext(Mock())              status = gui_core_context._get_submittable_status(job_ids)              assert status == expected_status        @pytest.mark.parametrize(          "job_ids, expected_status",          [              (["job6_completed", "job6_completed"], _SubmissionStatus.COMPLETED),              (["job6_completed", "job7_skipped"], _SubmissionStatus.COMPLETED),              (["job7_skipped", "job6_completed"], _SubmissionStatus.COMPLETED),              (["job7_skipped", "job7_skipped"], _SubmissionStatus.COMPLETED),          ],      )      def test_only_completed_or_skipped(self, job_ids, expected_status):          with patch("src.taipy.gui_core._context.core_get", side_effect=mock_core_get):              gui_core_context = _GuiCoreContext(Mock())              status = gui_core_context._get_submittable_status(job_ids)              assert status == expected_status        @pytest.mark.parametrize(          "job_ids, expected_status",          [              (["job3_blocked", "job8_abandoned"], _SubmissionStatus.UNDEFINED),              (["job4_pending", "job8_abandoned"], _SubmissionStatus.UNDEFINED),              (["job5_running", "job8_abandoned"], _SubmissionStatus.UNDEFINED),              (["job6_completed", "job8_abandoned"], _SubmissionStatus.UNDEFINED),              (["job7_skipped", "job8_abandoned"], _SubmissionStatus.UNDEFINED),              (["job8_abandoned", "job8_abandoned"], _SubmissionStatus.UNDEFINED),              (["job8_abandoned", "job3_blocked"], _SubmissionStatus.UNDEFINED),              (["job8_abandoned", "job4_pending"], _SubmissionStatus.UNDEFINED),              (["job8_abandoned", "job5_running"], _SubmissionStatus.UNDEFINED),              (["job8_abandoned", "job6_completed"], _SubmissionStatus.UNDEFINED),              (["job8_abandoned", "job7_skipped"], _SubmissionStatus.UNDEFINED),          ],      )      def test_WRONG_CASE_abandoned_without_cancel_or_failed(self, job_ids, expected_status):          with patch("src.taipy.gui_core._context.core_get", side_effect=mock_core_get):              gui_core_context = _GuiCoreContext(Mock())              status = gui_core_context._get_submittable_status(job_ids)              assert status == expected_status        def test_no_job(self):          with patch("src.taipy.gui_core._context.core_get", side_effect=mock_core_get):              gui_core_context = _GuiCoreContext(Mock())              status = gui_core_context._get_submittable_status([])              assert status == _SubmissionStatus.UNDEFINED


#  # 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 unittest.mock import Mock, patch    import pytest    from src.taipy.gui_core._context import _GuiCoreContext  from taipy.config.common.scope import Scope  from taipy.core import Job, Scenario, Task  from taipy.core.data.pickle import PickleDataNode  from taipy.gui import Gui    a_scenario = Scenario("scenario_config_id", [], {}, sequences={"sequence": {}})  a_task = Task("task_config_id", {}, print)  a_job = Job("JOB_job_id", a_task, "submit_id", a_scenario.id)  a_job.isfinished = lambda s: True  a_datanode = PickleDataNode("data_node_config_id", Scope.SCENARIO)      def mock_is_readable_false(entity_id):      return False      def mock_is_true(entity_id):      return True      def mock_core_get(entity_id):      if entity_id == a_scenario.id:          return a_scenario      if entity_id == a_job.id:          return a_job      if entity_id == a_datanode.id:          return a_datanode      return a_task      class MockState:      def __init__(self, **kwargs) -> None:          self.assign = kwargs.get("assign")      class TestGuiCoreContext_is_readable:      def test_scenario_adapter(self):          with patch("src.taipy.gui_core._context.core_get", side_effect=mock_core_get):              gui_core_context = _GuiCoreContext(Mock())              outcome = gui_core_context.scenario_adapter(a_scenario)              assert isinstance(outcome, tuple)              assert outcome[0] == a_scenario.id                with patch("src.taipy.gui_core._context.is_readable", side_effect=mock_is_readable_false):                  outcome = gui_core_context.scenario_adapter(a_scenario)                  assert outcome is None        def test_get_scenario_by_id(self):          with patch("src.taipy.gui_core._context.core_get", side_effect=mock_core_get):              gui_core_context = _GuiCoreContext(Mock())              outcome = gui_core_context.get_scenario_by_id(a_scenario.id)              assert outcome is not None                with patch("src.taipy.gui_core._context.is_readable", side_effect=mock_is_readable_false):                  outcome = gui_core_context.get_scenario_by_id(a_scenario.id)                  assert outcome is None        def test_crud_scenario(self):          with patch("src.taipy.gui_core._context.core_get", side_effect=mock_core_get):              gui_core_context = _GuiCoreContext(Mock())              assign = Mock()              gui_core_context.crud_scenario(                  MockState(assign=assign),                  "",                  {                      "args": [                          True,                          False,                          {"name": "name", "id": a_scenario.id},                      ]                  },              )              assign.assert_not_called()                with patch("src.taipy.gui_core._context.is_readable", side_effect=mock_is_readable_false):                  assign.reset_mock()                  gui_core_context.crud_scenario(                      MockState(assign=assign),                      "",                      {                          "args": [                              True,                              False,                              {"name": "name", "id": a_scenario.id},                          ]                      },                  )                  assign.assert_called_once()                  assert assign.call_args.args[0] == "gui_core_sc_error"                  assert str(assign.call_args.args[1]).endswith("is not readable.")        def test_edit_entity(self):          with patch("src.taipy.gui_core._context.core_get", side_effect=mock_core_get):              gui_core_context = _GuiCoreContext(Mock())              assign = Mock()              gui_core_context.edit_entity(                  MockState(assign=assign),                  "",                  {                      "args": [                          {"name": "name", "id": a_scenario.id},                      ]                  },              )              assign.assert_called_once()              assert assign.call_args.args[0] == "gui_core_sv_error"              assert assign.call_args.args[1] == ""                with patch("src.taipy.gui_core._context.is_readable", side_effect=mock_is_readable_false):                  assign.reset_mock()                  gui_core_context.edit_entity(                      MockState(assign=assign),                      "",                      {                          "args": [                              {"name": "name", "id": a_scenario.id},                          ]                      },                  )                  assign.assert_called_once()                  assert assign.call_args.args[0] == "gui_core_sv_error"                  assert str(assign.call_args.args[1]).endswith("is not readable.")        def test_scenario_status_callback(self):          with patch("src.taipy.gui_core._context.core_get", side_effect=mock_core_get) as mockget:              mockget.reset_mock()              gui_core_context = _GuiCoreContext(Mock())              gui_core_context.scenario_status_callback(a_job.id)              mockget.assert_called()              found = False              for call in mockget.call_args_list:                  if call.args[0] == a_job.id:                      found = True                      break              assert found is True              mockget.reset_mock()                with patch("src.taipy.gui_core._context.is_readable", side_effect=mock_is_readable_false):                  gui_core_context.scenario_status_callback(a_job.id)                  mockget.assert_not_called()        def test_data_node_adapter(self):          with patch("src.taipy.gui_core._context.core_get", side_effect=mock_core_get):              gui_core_context = _GuiCoreContext(Mock())              outcome = gui_core_context.data_node_adapter(a_datanode)              assert isinstance(outcome, tuple)              assert outcome[0] == a_datanode.id                with patch("src.taipy.gui_core._context.is_readable", side_effect=mock_is_readable_false):                  outcome = gui_core_context.data_node_adapter(a_datanode)                  assert outcome is None        def test_job_adapter(self):          with patch("src.taipy.gui_core._context.core_get", side_effect=mock_core_get):              gui_core_context = _GuiCoreContext(Mock())              outcome = gui_core_context.job_adapter(a_job)              assert isinstance(outcome, tuple)              assert outcome[0] == a_job.id                with patch("src.taipy.gui_core._context.is_readable", side_effect=mock_is_readable_false):                  outcome = gui_core_context.job_adapter(a_job)                  assert outcome is None        def test_act_on_jobs(self):          with patch("src.taipy.gui_core._context.core_get", side_effect=mock_core_get), patch(              "src.taipy.gui_core._context.is_deletable", side_effect=mock_is_true          ):              gui_core_context = _GuiCoreContext(Mock())              assign = Mock()              gui_core_context.act_on_jobs(                  MockState(assign=assign),                  "",                  {                      "args": [                          {"id": [a_job.id], "action": "delete"},                      ]                  },              )              assign.assert_called_once()              assert assign.call_args.args[0] == "gui_core_js_error"              assert str(assign.call_args.args[1]).find("is not readable.") == -1              assign.reset_mock()                gui_core_context.act_on_jobs(                  MockState(assign=assign),                  "",                  {                      "args": [                          {"id": [a_job.id], "action": "cancel"},                      ]                  },              )              assign.assert_called_once()              assert assign.call_args.args[0] == "gui_core_js_error"              assert str(assign.call_args.args[1]).find("is not readable.") == -1              assign.reset_mock()                with patch("src.taipy.gui_core._context.is_readable", side_effect=mock_is_readable_false):                  gui_core_context.act_on_jobs(                      MockState(assign=assign),                      "",                      {                          "args": [                              {"id": [a_job.id], "action": "delete"},                          ]                      },                  )                  assign.assert_called_once()                  assert assign.call_args.args[0] == "gui_core_js_error"                  assert str(assign.call_args.args[1]).endswith("is not readable.")                  assign.reset_mock()                    gui_core_context.act_on_jobs(                      MockState(assign=assign),                      "",                      {                          "args": [                              {"id": [a_job.id], "action": "cancel"},                          ]                      },                  )                  assign.assert_called_once()                  assert assign.call_args.args[0] == "gui_core_js_error"                  assert str(assign.call_args.args[1]).endswith("is not readable.")        def test_edit_data_node(self):          with patch("src.taipy.gui_core._context.core_get", side_effect=mock_core_get):              gui_core_context = _GuiCoreContext(Mock())              assign = Mock()              gui_core_context.edit_data_node(                  MockState(assign=assign),                  "",                  {                      "args": [                          {"id": a_datanode.id},                      ]                  },              )              assign.assert_called_once()              assert assign.call_args.args[0] == "gui_core_dv_error"              assert assign.call_args.args[1] == ""                with patch("src.taipy.gui_core._context.is_readable", side_effect=mock_is_readable_false):                  assign.reset_mock()                  gui_core_context.edit_data_node(                      MockState(assign=assign),                      "",                      {                          "args": [                              {"id": a_datanode.id},                          ]                      },                  )                  assign.assert_called_once()                  assert assign.call_args.args[0] == "gui_core_dv_error"                  assert str(assign.call_args.args[1]).endswith("is not readable.")        def test_lock_datanode_for_edit(self):          with patch("src.taipy.gui_core._context.core_get", side_effect=mock_core_get):              mockGui = Mock(Gui)              mockGui._get_client_id = lambda: "a_client_id"              gui_core_context = _GuiCoreContext(mockGui)              assign = Mock()              gui_core_context.lock_datanode_for_edit(                  MockState(assign=assign),                  "",                  {                      "args": [                          {"id": a_datanode.id},                      ]                  },              )              assign.assert_called_once()              assert assign.call_args.args[0] == "gui_core_dv_error"              assert assign.call_args.args[1] == ""                with patch("src.taipy.gui_core._context.is_readable", side_effect=mock_is_readable_false):                  assign.reset_mock()                  gui_core_context.lock_datanode_for_edit(                      MockState(assign=assign),                      "",                      {                          "args": [                              {"id": a_datanode.id},                          ]                      },                  )                  assign.assert_called_once()                  assert assign.call_args.args[0] == "gui_core_dv_error"                  assert str(assign.call_args.args[1]).endswith("is not readable.")        def test_get_scenarios_for_owner(self):          with patch("src.taipy.gui_core._context.core_get", side_effect=mock_core_get) as mockget:              gui_core_context = _GuiCoreContext(Mock())              gui_core_context.get_scenarios_for_owner(a_scenario.id)              mockget.assert_called_once()              mockget.reset_mock()                with patch("src.taipy.gui_core._context.is_readable", side_effect=mock_is_readable_false):                  gui_core_context.scenario_status_callback(a_scenario.id)                  mockget.assert_not_called()        def test_update_data(self):          with patch("src.taipy.gui_core._context.core_get", side_effect=mock_core_get):              mockGui = Mock(Gui)              mockGui._get_client_id = lambda: "a_client_id"              gui_core_context = _GuiCoreContext(mockGui)              assign = Mock()              gui_core_context.update_data(                  MockState(assign=assign),                  "",                  {                      "args": [                          {"id": a_datanode.id},                      ]                  },              )              assign.assert_called()              assert assign.call_args_list[0].args[0] == "gui_core_dv_error"              assert assign.call_args_list[0].args[1] == ""              assign.reset_mock()                with patch("src.taipy.gui_core._context.is_readable", side_effect=mock_is_readable_false):                  gui_core_context.update_data(                      MockState(assign=assign),                      "",                      {                          "args": [                              {"id": a_datanode.id},                          ]                      },                  )                  assign.assert_called_once()                  assert assign.call_args.args[0] == "gui_core_dv_error"                  assert str(assign.call_args.args[1]).endswith("is not readable.")        def test_tabular_data_edit(self):          with patch("src.taipy.gui_core._context.core_get", side_effect=mock_core_get):              mockGui = Mock(Gui)              mockGui._get_client_id = lambda: "a_client_id"              gui_core_context = _GuiCoreContext(mockGui)              assign = Mock()              gui_core_context.tabular_data_edit(                  MockState(assign=assign),                  "",                  {                      "user_data": {"dn_id": a_datanode.id},                  },              )              assign.assert_called_once()              assert assign.call_args_list[0].args[0] == "gui_core_dv_error"              assert (                  assign.call_args_list[0].args[1]                  == "Error updating Datanode tabular value: type does not support at[] indexer."              )              assign.reset_mock()                with patch("src.taipy.gui_core._context.is_readable", side_effect=mock_is_readable_false):                  gui_core_context.tabular_data_edit(                      MockState(assign=assign),                      "",                      {                          "user_data": {"dn_id": a_datanode.id},                      },                  )                  assign.assert_called_once()                  assert assign.call_args.args[0] == "gui_core_dv_error"                  assert str(assign.call_args.args[1]).endswith("is not readable.")        def test_get_data_node_tabular_data(self):          with patch("src.taipy.gui_core._context.core_get", side_effect=mock_core_get) as mockget:              gui_core_context = _GuiCoreContext(Mock())              gui_core_context.get_data_node_tabular_data(a_datanode, a_datanode.id)              mockget.assert_called_once()              mockget.reset_mock()                with patch("src.taipy.gui_core._context.is_readable", side_effect=mock_is_readable_false):                  gui_core_context.get_data_node_tabular_data(a_datanode, a_datanode.id)                  mockget.assert_not_called()        def test_get_data_node_tabular_columns(self):          with patch("src.taipy.gui_core._context.core_get", side_effect=mock_core_get) as mockget:              gui_core_context = _GuiCoreContext(Mock())              gui_core_context.get_data_node_tabular_columns(a_datanode, a_datanode.id)              mockget.assert_called_once()              mockget.reset_mock()                with patch("src.taipy.gui_core._context.is_readable", side_effect=mock_is_readable_false):                  gui_core_context.get_data_node_tabular_columns(a_datanode, a_datanode.id)                  mockget.assert_not_called()        def test_get_data_node_chart_config(self):          with patch("src.taipy.gui_core._context.core_get", side_effect=mock_core_get) as mockget:              gui_core_context = _GuiCoreContext(Mock())              gui_core_context.get_data_node_chart_config(a_datanode, a_datanode.id)              mockget.assert_called_once()              mockget.reset_mock()                with patch("src.taipy.gui_core._context.is_readable", side_effect=mock_is_readable_false):                  gui_core_context.get_data_node_chart_config(a_datanode, a_datanode.id)                  mockget.assert_not_called()


from unittest.mock import Mock, patch    import pytest    from src.taipy.gui_core._context import _GuiCoreContext  from taipy.config.common.scope import Scope  from taipy.core import Job, Scenario, Task  from taipy.core.data.pickle import PickleDataNode    a_scenario = Scenario("scenario_config_id", [], {}, sequences={"sequence": {}})  a_task = Task("task_config_id", {}, print)  a_job = Job("JOB_job_id", a_task, "submit_id", a_scenario.id)  a_job.isfinished = lambda s: True  a_datanode = PickleDataNode("data_node_config_id", Scope.SCENARIO)      def mock_core_get(entity_id):      if entity_id == a_scenario.id:          return a_scenario      if entity_id == a_job.id:          return a_job      if entity_id == a_datanode.id:          return a_datanode      return a_task      def mock_is_deletable_false(entity_id):      return False      def mock_is_true(entity_id):      return True      class MockState:      def __init__(self, **kwargs) -> None:          self.assign = kwargs.get("assign")      class TestGuiCoreContext_is_deletable:      def test_crud_scenario(self):          with patch("src.taipy.gui_core._context.core_get", side_effect=mock_core_get), patch(              "src.taipy.gui_core._context.is_deletable", side_effect=mock_is_true          ):              gui_core_context = _GuiCoreContext(Mock())              assign = Mock()              gui_core_context.crud_scenario(                  MockState(assign=assign),                  "",                  {                      "args": [                          True,                          True,                          {"name": "name", "id": a_scenario.id},                      ]                  },              )              assign.assert_called_once()              assert assign.call_args.args[0] == "gui_core_sc_error"              assert str(assign.call_args.args[1]).startswith("Error deleting Scenario.")                with patch("src.taipy.gui_core._context.is_deletable", side_effect=mock_is_deletable_false):                  assign.reset_mock()                  gui_core_context.crud_scenario(                      MockState(assign=assign),                      "",                      {                          "args": [                              True,                              True,                              {"name": "name", "id": a_scenario.id},                          ]                      },                  )                  assign.assert_called_once()                  assert assign.call_args.args[0] == "gui_core_sc_error"                  assert str(assign.call_args.args[1]).endswith("is not deletable.")        def test_act_on_jobs(self):          with patch("src.taipy.gui_core._context.core_get", side_effect=mock_core_get), patch(              "src.taipy.gui_core._context.is_deletable", side_effect=mock_is_true          ):              gui_core_context = _GuiCoreContext(Mock())              assign = Mock()              gui_core_context.act_on_jobs(                  MockState(assign=assign),                  "",                  {                      "args": [                          {"id": [a_job.id], "action": "delete"},                      ]                  },              )              assign.assert_called_once()              assert assign.call_args.args[0] == "gui_core_js_error"              assert str(assign.call_args.args[1]).find("is not deletable.") == -1              assign.reset_mock()                with patch("src.taipy.gui_core._context.is_readable", side_effect=mock_is_deletable_false):                  gui_core_context.act_on_jobs(                      MockState(assign=assign),                      "",                      {                          "args": [                              {"id": [a_job.id], "action": "delete"},                          ]                      },                  )                  assign.assert_called_once()                  assert assign.call_args.args[0] == "gui_core_js_error"                  assert str(assign.call_args.args[1]).endswith("is not readable.")


from unittest.mock import Mock, patch    import pytest    from src.taipy.gui_core._context import _GuiCoreContext  from taipy.config.common.scope import Scope  from taipy.core import Job, Scenario, Task  from taipy.core.data.pickle import PickleDataNode    a_scenario = Scenario("scenario_config_id", [], {}, sequences={"sequence": {}})  a_task = Task("task_config_id", {}, print)  a_job = Job("JOB_job_id", a_task, "submit_id", a_scenario.id)  a_job.isfinished = lambda s: True  a_datanode = PickleDataNode("data_node_config_id", Scope.SCENARIO)      def mock_core_get(entity_id):      if entity_id == a_scenario.id:          return a_scenario      if entity_id == a_job.id:          return a_job      if entity_id == a_datanode.id:          return a_datanode      return a_task      def mock_is_promotable_false(entity_id):      return False      def mock_is_true(entity_id):      return True      class MockState:      def __init__(self, **kwargs) -> None:          self.assign = kwargs.get("assign")      class TestGuiCoreContext_is_promotable:      def test_edit_entity(self):          with patch("src.taipy.gui_core._context.core_get", side_effect=mock_core_get), patch(              "src.taipy.gui_core._context.is_promotable", side_effect=mock_is_true          ):              gui_core_context = _GuiCoreContext(Mock())              assign = Mock()              gui_core_context.edit_entity(                  MockState(assign=assign),                  "",                  {                      "args": [                          {"name": "name", "id": a_scenario.id, "primary": True},                      ]                  },              )              assign.assert_called_once()              assert assign.call_args.args[0] == "gui_core_sv_error"              assert str(assign.call_args.args[1]).endswith("to primary because it doesn't belong to a cycle.")              assign.reset_mock()                with patch("src.taipy.gui_core._context.is_promotable", side_effect=mock_is_promotable_false):                  gui_core_context.edit_entity(                      MockState(assign=assign),                      "",                      {                          "args": [                              {"name": "name", "id": a_scenario.id, "primary": True},                          ]                      },                  )                  assign.assert_called_once()                  assert assign.call_args.args[0] == "gui_core_sv_error"                  assert str(assign.call_args.args[1]).endswith("is not promotable.")


from unittest.mock import Mock, patch    import pytest    from src.taipy.gui_core._context import _GuiCoreContext  from taipy.config.common.scope import Scope  from taipy.core import Job, Scenario, Task  from taipy.core.data.pickle import PickleDataNode  from taipy.gui import Gui    a_scenario = Scenario("scenario_config_id", [], {}, sequences={"sequence": {}})  a_task = Task("task_config_id", {}, print)  a_job = Job("JOB_job_id", a_task, "submit_id", a_scenario.id)  a_job.isfinished = lambda s: True  a_datanode = PickleDataNode("data_node_config_id", Scope.SCENARIO)      def mock_core_get(entity_id):      if entity_id == a_scenario.id:          return a_scenario      if entity_id == a_job.id:          return a_job      if entity_id == a_datanode.id:          return a_datanode      return a_task      def mock_is_editable_false(entity_id):      return False      def mock_is_true(entity_id):      return True      class MockState:      def __init__(self, **kwargs) -> None:          self.assign = kwargs.get("assign")      class TestGuiCoreContext_is_editable:      def test_crud_scenario(self):          with patch("src.taipy.gui_core._context.core_get", side_effect=mock_core_get):              gui_core_context = _GuiCoreContext(Mock())              assign = Mock()              gui_core_context.crud_scenario(                  MockState(assign=assign),                  "",                  {                      "args": [                          True,                          False,                          {"name": "name", "id": a_scenario.id},                      ]                  },              )              assign.assert_not_called()                with patch("src.taipy.gui_core._context.is_editable", side_effect=mock_is_editable_false):                  assign.reset_mock()                  gui_core_context.crud_scenario(                      MockState(assign=assign),                      "",                      {                          "args": [                              True,                              False,                              {"name": "name", "id": a_scenario.id},                          ]                      },                  )                  assign.assert_called_once()                  assert assign.call_args.args[0] == "gui_core_sc_error"                  assert str(assign.call_args.args[1]).endswith("is not editable.")        def test_edit_entity(self):          with patch("src.taipy.gui_core._context.core_get", side_effect=mock_core_get):              gui_core_context = _GuiCoreContext(Mock())              assign = Mock()              gui_core_context.edit_entity(                  MockState(assign=assign),                  "",                  {                      "args": [                          {"name": "name", "id": a_scenario.id},                      ]                  },              )              assign.assert_called_once()              assert assign.call_args.args[0] == "gui_core_sv_error"              assert assign.call_args.args[1] == ""                with patch("src.taipy.gui_core._context.is_editable", side_effect=mock_is_editable_false):                  assign.reset_mock()                  gui_core_context.edit_entity(                      MockState(assign=assign),                      "",                      {                          "args": [                              {"name": "name", "id": a_scenario.id},                          ]                      },                  )                  assign.assert_called_once()                  assert assign.call_args.args[0] == "gui_core_sv_error"                  assert str(assign.call_args.args[1]).endswith("is not editable.")        def test_act_on_jobs(self):          with patch("src.taipy.gui_core._context.core_get", side_effect=mock_core_get), patch(              "src.taipy.gui_core._context.is_deletable", side_effect=mock_is_true          ):              gui_core_context = _GuiCoreContext(Mock())              assign = Mock()              gui_core_context.act_on_jobs(                  MockState(assign=assign),                  "",                  {                      "args": [                          {"id": [a_job.id], "action": "cancel"},                      ]                  },              )              assign.assert_called_once()              assert assign.call_args.args[0] == "gui_core_js_error"              assert str(assign.call_args.args[1]).find("is not editable.") == -1              assign.reset_mock()                with patch("src.taipy.gui_core._context.is_readable", side_effect=mock_is_editable_false):                  gui_core_context.act_on_jobs(                      MockState(assign=assign),                      "",                      {                          "args": [                              {"id": [a_job.id], "action": "cancel"},                          ]                      },                  )                  assign.assert_called_once()                  assert assign.call_args.args[0] == "gui_core_js_error"                  assert str(assign.call_args.args[1]).endswith("is not readable.")        def test_edit_data_node(self):          with patch("src.taipy.gui_core._context.core_get", side_effect=mock_core_get):              gui_core_context = _GuiCoreContext(Mock())              assign = Mock()              gui_core_context.edit_data_node(                  MockState(assign=assign),                  "",                  {                      "args": [                          {"id": a_datanode.id},                      ]                  },              )              assign.assert_called_once()              assert assign.call_args.args[0] == "gui_core_dv_error"              assert assign.call_args.args[1] == ""                with patch("src.taipy.gui_core._context.is_editable", side_effect=mock_is_editable_false):                  assign.reset_mock()                  gui_core_context.edit_data_node(                      MockState(assign=assign),                      "",                      {                          "args": [                              {"id": a_datanode.id},                          ]                      },                  )                  assign.assert_called_once()                  assert assign.call_args.args[0] == "gui_core_dv_error"                  assert str(assign.call_args.args[1]).endswith("is not editable.")        def test_lock_datanode_for_edit(self):          with patch("src.taipy.gui_core._context.core_get", side_effect=mock_core_get):              mockGui = Mock(Gui)              mockGui._get_client_id = lambda: "a_client_id"              gui_core_context = _GuiCoreContext(mockGui)              assign = Mock()              gui_core_context.lock_datanode_for_edit(                  MockState(assign=assign),                  "",                  {                      "args": [                          {"id": a_datanode.id},                      ]                  },              )              assign.assert_called_once()              assert assign.call_args.args[0] == "gui_core_dv_error"              assert assign.call_args.args[1] == ""                with patch("src.taipy.gui_core._context.is_editable", side_effect=mock_is_editable_false):                  assign.reset_mock()                  gui_core_context.lock_datanode_for_edit(                      MockState(assign=assign),                      "",                      {                          "args": [                              {"id": a_datanode.id},                          ]                      },                  )                  assign.assert_called_once()                  assert assign.call_args.args[0] == "gui_core_dv_error"                  assert str(assign.call_args.args[1]).endswith("is not editable.")        def test_update_data(self):          with patch("src.taipy.gui_core._context.core_get", side_effect=mock_core_get):              mockGui = Mock(Gui)              mockGui._get_client_id = lambda: "a_client_id"              gui_core_context = _GuiCoreContext(mockGui)              assign = Mock()              gui_core_context.update_data(                  MockState(assign=assign),                  "",                  {                      "args": [                          {"id": a_datanode.id},                      ]                  },              )              assign.assert_called()              assert assign.call_args_list[0].args[0] == "gui_core_dv_error"              assert assign.call_args_list[0].args[1] == ""              assign.reset_mock()                with patch("src.taipy.gui_core._context.is_editable", side_effect=mock_is_editable_false):                  gui_core_context.update_data(                      MockState(assign=assign),                      "",                      {                          "args": [                              {"id": a_datanode.id},                          ]                      },                  )                  assign.assert_called_once()                  assert assign.call_args.args[0] == "gui_core_dv_error"                  assert str(assign.call_args.args[1]).endswith("is not editable.")        def test_tabular_data_edit(self):          with patch("src.taipy.gui_core._context.core_get", side_effect=mock_core_get):              mockGui = Mock(Gui)              mockGui._get_client_id = lambda: "a_client_id"              gui_core_context = _GuiCoreContext(mockGui)              assign = Mock()              gui_core_context.tabular_data_edit(                  MockState(assign=assign),                  "",                  {                      "user_data": {"dn_id": a_datanode.id},                  },              )              assign.assert_called_once()              assert assign.call_args_list[0].args[0] == "gui_core_dv_error"              assert (                  assign.call_args_list[0].args[1]                  == "Error updating Datanode tabular value: type does not support at[] indexer."              )              assign.reset_mock()                with patch("src.taipy.gui_core._context.is_editable", side_effect=mock_is_editable_false):                  gui_core_context.tabular_data_edit(                      MockState(assign=assign),                      "",                      {                          "user_data": {"dn_id": a_datanode.id},                      },                  )                  assign.assert_called_once()                  assert assign.call_args.args[0] == "gui_core_dv_error"                  assert str(assign.call_args.args[1]).endswith("is not editable.")


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()      Config.configure_core(repository_type="filesystem")        if os.path.exists(".data"):          shutil.rmtree(".data", ignore_errors=True)      if os.path.exists(".my_data"):          shutil.rmtree(".my_data", ignore_errors=True)


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]}


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/rest/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/rest/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]})


import random  import string    from example_library import ExampleLibrary  from taipy.gui import Gui    # Initial value  label = "Here is some text"    page = """  # Custom elements example    ## Fraction:    No denominator: <|123|example.fraction|>    Denominator is 0: <|321|example.fraction|denominator=0|>    Regular: <|355|example.fraction|denominator=113|>    ## Custom label:    Colored text: <|{label}|example.label|>    <|Add a character|button|id=addChar|>  <|Remove a character|button|id=removeChar|>  """      def on_action(state, id):      if id == "addChar":          # Add a random character to the end of 'label'          state.label += random.choice(string.ascii_letters)      elif id == "removeChar":          # Remove the first character of 'label'          if len(state.label) > 0:              state.label = state.label[1:]      Gui(page, libraries=[ExampleLibrary()]).run(debug=True)


from .example_library import ExampleLibrary


from taipy.gui.extension import Element, ElementLibrary, ElementProperty, PropertyType      class ExampleLibrary(ElementLibrary):      def __init__(self) -> None:          # Initialize the set of visual elements for this extension library          self.elements = {              # A static element that displays its properties in a fraction              "fraction": Element(                  "numerator",                  {                      "numerator": ElementProperty(PropertyType.number),                      "denominator": ElementProperty(PropertyType.number),                  },                  render_xhtml=ExampleLibrary._fraction_render,              ),              # A dynamic element that decorates its value              "label": Element(                  "value",                  {"value": ElementProperty(PropertyType.dynamic_string)},                  # The name of the React component (ColoredLabel) that implements this custom                  # element, exported as ExampleLabel in front-end/src/index.ts                  react_component="ExampleLabel",              ),          }        # The implementation of the rendering for the "fraction" static element      @staticmethod      def _fraction_render(props: dict) -> str:          # Get the property values          numerator = props.get("numerator")          denominator = props.get("denominator")          # No denominator or numerator is 0: display the numerator          if denominator is None or int(numerator) == 0:              return f"{numerator}"          # Denominator is zero: display infinity          if int(denominator) == 0:              return '∞'          # 'Normal' case          return f"{numerator}/{denominator}"        def get_name(self) -> str:          return "example"        def get_elements(self) -> dict:          return self.elements        def get_scripts(self) -> list[str]:          # Only one JavaScript bundle for this library.          return ["front-end/dist/exampleLibrary.js"]


#  # 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.  # -----------------------------------------------------------------------------------------  # To execute this script, make sure that the taipy-gui package is installed in your  # Python environment and run:  #     python <script>  # -----------------------------------------------------------------------------------------  # Demonstrate how to share variable values across multiple clients.  # This application creates a thread that increments a value every few seconds.  # The value is updated for every client using the state.broadcast() method.  # The text of the button that starts or stops the thread is updated on every client's browser  # using a direct assignment of the state property because the variable is declared 'shared'.  # -----------------------------------------------------------------------------------------  from threading import Event, Thread  from time import sleep    from taipy.gui import Gui, State, broadcast_callback    counter = 0    # Thread management  thread = None  thread_event = Event()    button_texts = ["Start", "Stop"]  # Text in the start/stop button (initially "Start")  button_text = button_texts[0]      # Invoked by the timer  def update_counter(state: State, c):      # Update all clients      state.broadcast("counter", c)      def count(event, gui):      while not event.is_set():          global counter          counter = counter + 1          broadcast_callback(gui, update_counter, [counter])          sleep(2)      # Start or stop the timer when the button is pressed  def start_or_stop(state):      global thread      if thread:  # Timer is running          thread_event.set()          thread = None      else:  # Timer is stopped          thread_event.clear()          thread = Thread(target=count, args=[thread_event, state.get_gui()])          thread.start()      # Update button status.      # Because "button_text" is shared, all clients are updated      state.button_text = button_texts[1 if thread else 0]      page = """# Broadcasting values    Counter: <|{counter}|>    Timer: <|{button_text}|button|on_action=start_or_stop|>  """    # Declare "button_text" as a shared variable.  # Assigning a value to a state's 'button_text' property is propagated to all clients  Gui.add_shared_variable("button_text")    Gui(page).run()


#  # 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.  # -----------------------------------------------------------------------------------------  # To execute this script, make sure that the taipy-gui package is installed in your  # Python environment and run:  #     python <script>  # -----------------------------------------------------------------------------------------  # Demonstrates the use of the 'rebuild' property of the 'chart' control  # -----------------------------------------------------------------------------------------  from taipy.gui import Gui    # x values: [-10..10]  x_range = range(-10, 11)  data = {"X": x_range, "Y": [x * x for x in x_range]}    types = [("bar", "Bar"), ("line", "Line")]  selected_type = types[0]    page = """  <|{data}|chart|type={selected_type[0]}|x=X|y=Y|rebuild|>    <|{selected_type}|toggle|lov={types}|>  """    Gui(page).run()


#  # 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.  # -----------------------------------------------------------------------------------------  # To execute this script, make sure that the taipy-gui package is installed in your  # Python environment and run:  #     python <script>  # -----------------------------------------------------------------------------------------  import datetime    from taipy.gui import Gui    # Tasks definitions  tasks = ["Plan", "Research", "Design", "Implement", "Test", "Deliver"]  # Task durations, in days  durations = [50, 30, 30, 40, 15, 10]  # Planned start dates of tasks  start_dates = [      datetime.date(2022, 10, 15),  # Plan      datetime.date(2022, 11, 7),  # Research      datetime.date(2022, 12, 1),  # Design      datetime.date(2022, 12, 20),  # Implement      datetime.date(2023, 1, 15),  # Test      datetime.date(2023, 2, 1),  # Deliver  ]    epoch = datetime.date(1970, 1, 1)    data = {      "start": start_dates,      "Task": tasks,      # Compute the time span as adatetime (relative to January 1st, 1970)      "Date": [epoch + datetime.timedelta(days=duration) for duration in durations],  }    layout = {      "yaxis": {          # Sort tasks from top to bottom          "autorange": "reversed",          # Remove title          "title": {"text": ""},      },  }    page = """  # Gantt - Simple    <|{data}|chart|type=bar|orientation=h|y=Task|x=Date|base=start|layout={layout}|>  """    Gui(page).run()


#  # 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.  # -----------------------------------------------------------------------------------------  # To execute this script, make sure that the taipy-gui package is installed in your  # Python environment and run:  #     python <script>  # -----------------------------------------------------------------------------------------  from taipy.gui import Gui    # x values are [-10..10]  x_range = range(-10, 11)    # The data set that holds both the x and the y values  data = {"X": x_range, "Y": [x * x for x in x_range]}    page = """  # Basics - X range    <|{data}|chart|x=X|y=Y|>  """    Gui(page).run()


#  # 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.  # -----------------------------------------------------------------------------------------  # To execute this script, make sure that the taipy-gui package is installed in your  # Python environment and run:  #     python <script>  # -----------------------------------------------------------------------------------------  from taipy.gui import Gui      # Function to plot: x^3/3-x  def f(x):      return x * x * x / 3 - x      # x values: [-2.2, ..., 2.2]  x = [(x - 10) / 4.5 for x in range(0, 21)]    data = {      "x": x,      # y: [f(-2.2), ..., f(2.2)]      "y": [f(x) for x in x],  }    shape_size = 0.1    layout = {      "shapes": [          # Shape for local maximum (x = -1)          {              "x0": -1 - shape_size,              "y0": f(-1) - 2 * shape_size,              "x1": -1 + shape_size,              "y1": f(-1) + 2 * shape_size,              "fillcolor": "green",              "opacity": 0.5,          },          # Shape for local minimum (x = 1)          {              "x0": 1 - shape_size,              "y0": f(1) - 2 * shape_size,              "x1": 1 + shape_size,              "y1": f(1) + 2 * shape_size,              "fillcolor": "red",              "opacity": 0.5,          },      ]  }    page = """  # Advanced - Annotations    <|{data}|chart|layout={layout}|>  """    Gui(page).run()


#  # 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.  # -----------------------------------------------------------------------------------------  # To execute this script, make sure that the taipy-gui package is installed in your  # Python environment and run:  #     python <script>  # -----------------------------------------------------------------------------------------  import numpy    from taipy.gui import Gui      # Return the x and y coordinates of the spiral for the given angle  def spiral(th):      a = 1.120529      b = 0.306349      r = a * numpy.exp(-b * th)      return (r * numpy.cos(th), r * numpy.sin(th))      # Prepare Golden spiral data as a parametric curve  (x, y) = spiral(numpy.linspace(-numpy.pi / 13, 4 * numpy.pi, 1000))    # Prepare the heatmap x and y cell sizes along the axes  golden_ratio = (1 + numpy.sqrt(5)) / 2.0  # Golden ratio  grid_x = [0, 1, 1 + (1 / (golden_ratio ** 4)), 1 + (1 / (golden_ratio ** 3)), golden_ratio]  grid_y = [0, 1 / (golden_ratio ** 3), 1 / golden_ratio ** 3 + 1 / golden_ratio ** 4, 1 / (golden_ratio ** 2), 1]    # Main value is based on the Fibonacci sequence  z = [[13, 3, 3, 5], [13, 2, 1, 5], [13, 10, 11, 12], [13, 8, 8, 8]]    # Group all data sets in a single array  data = [      {          "z": z,      },      {"x": numpy.sort(grid_x), "y": numpy.sort(grid_y)},      {          "xSpiral": -x + x[0],          "ySpiral": y - y[0],      },  ]    # Axis template: hide all ticks, lines and labels  axis = {"range": [0, 2.0], "showgrid": False, "zeroline": False, "showticklabels": False, "ticks": "", "title": ""}    layout = {      # Use the axis template for both x and y axes      "xaxis": axis,      "yaxis": axis,  }    options = {      # Hide the color scale of the heatmap      "showscale": False  }    # Chart holds two traces, with different types  types = ["heatmap", "scatter"]  # x and y values for both traces  xs = ["1/x", "2/xSpiral"]  ys = ["1/y", "2/ySpiral"]    page = """  ## Heatmap - Drawing on top    <|{data}|chart|type={types}|z[1]=0/z|x={xs}|y={ys}|layout={layout}|options={options}|>  """    Gui(page).run()


#  # 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.  # -----------------------------------------------------------------------------------------  # To execute this script, make sure that the taipy-gui package is installed in your  # Python environment and run:  #     python <script>  # -----------------------------------------------------------------------------------------  import random    from taipy.gui import Gui    # Data set made of two series of random numbers  data = {"A": [random.random() for i in range(200)], "B": [random.random() for i in range(200)]}    # Names of the two traces  names = ["A samples", "B samples"]    layout = {      # Make the histogram stack the data sets      "barmode": "stack"  }    page = """  # Histogram - Stacked    <|{data}|chart|type=histogram|x[1]=A|x[2]=B|name={names}|layout={layout}|>  """    Gui(page).run()


#  # 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.  # -----------------------------------------------------------------------------------------  # To execute this script, make sure that the taipy-gui package is installed in your  # Python environment and run:  #     python <script>  # -----------------------------------------------------------------------------------------  from taipy.gui import Gui    # Data set  data = {      "Day": ["Mon", "Tue", "Wed", "Thu", "Fri"],      "Values": [10, -5, 20, -10, 30],      "Measure": ["absolute", "relative", "relative", "relative", "relative"],  }    page = """  # Waterfall - Simple    <|{data}|chart|type=waterfall|x=Day|y=Values|measure=Measure|>  """    Gui(page).run()