text
stringlengths
0
5.92k
import os import re from collections import UserDict from datetime import datetime, timedelta from importlib import import_module from operator import attrgetter from pydoc import locate from ..exceptions.exceptions import InconsistentEnvVariableError, MissingEnvVariableError from .frequency import Frequency ...
from __future__ import annotations from typing import Any, Dict, Optional, Union from ..common._config_blocker import _ConfigBlocker from ..common._template_handler import _TemplateHandler as _tpl class GlobalAppConfig: """ Configuration fields related to the global application. Attributes:...
# # 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 u...
import pathlib import sys from cookiecutter.main import cookiecutter import taipy from taipy._cli._base_cli import _CLI class _ScaffoldCLI: __TAIPY_PATH = pathlib.Path(taipy.__file__).parent.resolve() / "templates" _TEMPLATE_MAP = {str(x.name): str(x) for x in __TAIPY_PATH.iterdir() if x.is_dir...
import subprocess import sys from taipy._cli._base_cli import _CLI class _RunCLI: @classmethod def create_parser(cls): run_parser = _CLI._add_subparser("run", help="Run a Taipy application.") run_parser.add_argument( "application_main_file", ) sub_ru...
# # 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 u...
import sys from taipy._cli._base_cli import _CLI from taipy.logger._taipy_logger import _TaipyLogger class _HelpCLI: __logger = _TaipyLogger._get_logger() @classmethod def create_parser(cls): create_parser = _CLI._add_subparser("help", help="Show the Taipy help message.", add_help=Fal...
import argparse from typing import Dict class _CLI: """Argument parser for Taipy application.""" # The conflict_handler is set to "resolve" to override conflict arguments _subparser_action = None _parser = argparse.ArgumentParser(conflict_handler="resolve") _sub_taipyparsers: Dict[str...
from ._cli import _CLI
import typing as t class Icon: """Small image in the User Interface. Icons are typically used in controls like [button](../gui/viselements/button.md) or items in a [menu](../gui/viselements/menu.md). Attributes: path (str): The path to the image file. text (Optional[str]):...
from .gui import Gui
import typing as t from enum import Enum from inspect import isclass from .data import Decimator from .utils import ( _TaipyBase, _TaipyBool, _TaipyContent, _TaipyContentHtml, _TaipyContentImage, _TaipyData, _TaipyDate, _TaipyDateRange, _TaipyDict, _TaipyLoNumbers...
"""# Taipy Graphical User Interface generator The Taipy GUI package provides User Interface generation based on page templates. It can run a web server that a web browser can connect to. The pages are generated by a web server that allows web clients to connect, display and interact with the page content throug...
from __future__ import annotations import inspect import typing as t from types import FrameType from .utils import _filter_locals, _get_module_name_from_frame if t.TYPE_CHECKING: from ._renderers import _Element class Page: """Generic page generator. The `Page` class transforms templat...
import sys import traceback import typing as t import warnings class TaipyGuiWarning(UserWarning): """NOT DOCUMENTED Warning category for Taipy warnings generated in user code. """ _tp_debug_mode = False @staticmethod def set_debug_mode(debug_mode: bool): TaipyGuiWar...
import typing as t from copy import copy from taipy.config import Config as TaipyConfig from taipy.config import UniqueSection from ._default_config import default_config class _GuiSection(UniqueSection): name = "gui" def __init__(self, property_list: t.Optional[t.List] = None, **properties): ...
# _Page for multipage support from __future__ import annotations import logging import typing as t import warnings if t.TYPE_CHECKING: from ._renderers import Page from .gui import Gui class _Page(object): def __init__(self): self._rendered_jsx: t.Optional[str] = None self...
#!/usr/bin/env python """The setup script.""" import json import os from pathlib import Path from setuptools import find_namespace_packages, find_packages, setup from setuptools.command.build_py import build_py readme = Path("README.md").read_text() with open(f"src{os.sep}taipy{os.sep}gui{os.sep}versi...
from .config import Config, Stylekit _default_stylekit: Stylekit = { # Primary and secondary colors "color_primary": "#ff6049", "color_secondary": "#293ee7", # Contextual color "color_error": "#FF595E", "color_warning": "#FAA916", "color_success": "#96E6B3", # Background and e...
from __future__ import annotations import typing as t from ._page import _Page from ._warnings import _warn from .state import State if t.TYPE_CHECKING: from .page import Page class Partial(_Page): """Re-usable Page content. Partials are used when you need to use a partial page content ...
from typing import Dict, Tuple from taipy._cli._base_cli import _CLI class _GuiCLI: """Command-line interface of GUI.""" __GUI_ARGS: Dict[Tuple, Dict] = { ("--port", "-P"): { "dest": "taipy_port", "metavar": "PORT", "nargs": "?", "default"...
from ..gui_types import PropertyType from .library import Element, ElementLibrary, ElementProperty
from __future__ import annotations import typing as t class _MapDict(object): """ Provide class binding, can utilize getattr, setattr functionality Also perform update operation """ __local_vars = ("_dict", "_update_var") def __init__(self, dict_import: dict, app_update_var=Non...
import re import typing as t _RE_MODULE = re.compile(r"^__(.*?)__$") def _filter_locals(locals_dict: t.Dict[str, t.Any]) -> t.Dict[str, t.Any]: return {k: v for k, v in locals_dict.items() if (not _RE_MODULE.match(k) or k == "__name__")}
import typing as t from .singleton import _Singleton if t.TYPE_CHECKING: from ..gui import Gui class _RuntimeManager(object, metaclass=_Singleton): def __init__(self): self.__port_gui: t.Dict[int, "Gui"] = {} def add_gui(self, gui: "Gui", port: int): if port in self.__port_...
import inspect import sys import typing as t from types import FrameType, ModuleType def _get_module_name_from_frame(frame: FrameType): return frame.f_globals["__name__"] if "__name__" in frame.f_globals else None def _get_module_name_from_imported_var(var_name: str, value: t.Any, sub_module_name: str...
import contextlib import typing as t import warnings from threading import Thread from urllib.parse import quote as urlquote from urllib.parse import urlparse from twisted.internet import reactor from twisted.web.proxy import ProxyClient, ProxyClientFactory from twisted.web.resource import Resource from twis...
import typing as t from operator import attrgetter if t.TYPE_CHECKING: from ..gui import Gui def _getscopeattr(gui: "Gui", name: str, *more) -> t.Any: if more: return getattr(gui._get_data_scope(), name, more[0]) return getattr(gui._get_data_scope(), name) def _getscopeattr_drill(g...
import typing as t def _get_css_var_value(value: t.Any) -> str: if isinstance(value, str): if " " in value: return f'"{value}"' return value if isinstance(value, int): return f"{value}px" return f"{value}"
import typing as t from types import ModuleType from ..page import Page def _get_page_from_module(module: ModuleType) -> t.Optional[Page]: return next((v for v in vars(module).values() if isinstance(v, Page)), None)
from __future__ import annotations import typing as t if t.TYPE_CHECKING: from ..gui import Gui def _varname_from_content(gui: Gui, content: str) -> t.Optional[str]: return next((k for k, v in gui._get_locals_bind().items() if isinstance(v, str) and v == content), None)
from __future__ import annotations import contextlib import typing as t from flask import g class _LocalsContext: __ctx_g_name = "locals_context" def __init__(self) -> None: self.__default_module: str = "" self._lc_stack: t.List[str] = [] self._locals_map: t.Dict[str, ...
from ._attributes import ( _delscopeattr, _getscopeattr, _getscopeattr_drill, _hasscopeattr, _setscopeattr, _setscopeattr_drill, ) from ._locals_context import _LocalsContext from ._map_dict import _MapDict from ._runtime_manager import _RuntimeManager from ._variable_directory import...
import re import typing as t __expr_var_name_index: t.Dict[str, int] = {} _RE_NOT_IN_VAR_NAME = r"[^A-Za-z0-9]+" def _get_expr_var_name(expr: str) -> str: var_name = re.sub(_RE_NOT_IN_VAR_NAME, "_", expr) index = 0 if var_name in __expr_var_name_index.keys(): index = __expr_var_name_in...
import socket def _is_port_open(host, port) -> bool: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) result = sock.connect_ex((host, port)) sock.close() return result == 0
import json import typing as t from abc import ABC from datetime import datetime from .._warnings import _warn from . import _date_to_string, _MapDict, _string_to_date, _variable_decode class _TaipyBase(ABC): __HOLDER_PREFIXES: t.Optional[t.List[str]] = None _HOLDER_PREFIX = "_Tp" def __ini...
import sys def is_debugging() -> bool: """NOT DOCUMENTED""" return hasattr(sys, "gettrace") and sys.gettrace() is not None
import typing as t def _is_boolean_true(s: t.Union[bool, str]) -> bool: return ( s if isinstance(s, bool) else s.lower() in ["true", "1", "t", "y", "yes", "yeah", "sure"] if isinstance(s, str) else False ) def _is_boolean(s: t.Any) -> bool: if isinst...
_replace_dict = {".": "__", "[": "_SqrOp_", "]": "_SqrCl_"} def _get_client_var_name(var_name: str) -> str: for k, v in _replace_dict.items(): var_name = var_name.replace(k, v) return var_name def _to_camel_case(value: str, upcase_first=False) -> str: if not isinstance(value, str): ...
import re import typing as t from .._warnings import _warn from .boolean import _is_boolean, _is_boolean_true from .clientvarname import _to_camel_case def _get_column_desc(columns: t.Dict[str, t.Any], key: str) -> t.Optional[t.Dict[str, t.Any]]: return next((x for x in columns.values() if x.get("dfid")...
import typing as t from datetime import datetime from random import random from ..data.data_scope import _DataScopes from ._map_dict import _MapDict if t.TYPE_CHECKING: from ..gui import Gui class _Bindings: def __init__(self, gui: "Gui") -> None: self.__gui = gui self.__scopes...
import re import typing as t from types import FrameType from ._locals_context import _LocalsContext from .get_imported_var import _get_imported_var from .get_module_name import _get_module_name_from_frame, _get_module_name_from_imported_var class _VariableDirectory: def __init__(self, locals_context: ...
from typing import Dict class _Singleton(type): _instances: Dict = {} def __call__(self, *args, **kwargs): if self not in self._instances: self._instances[self] = super(_Singleton, self).__call__(*args, **kwargs) return self._instances[self]
import re import pandas as pd def _get_data_type(value): if pd.api.types.is_bool_dtype(value): return "bool" elif pd.api.types.is_integer_dtype(value): return "int" elif pd.api.types.is_float_dtype(value): return "float" return re.match(r"^<class '(.*\.)?(.*?)(\d\d...
import ast import inspect import typing as t from types import FrameType def _get_imported_var(frame: FrameType) -> t.List[t.Tuple[str, str, str]]: st = ast.parse(inspect.getsource(frame)) var_list: t.List[t.Tuple[str, str, str]] = [] for node in ast.walk(st): if isinstance(node, ast.Imp...
import re import typing as t from datetime import date, datetime, time from dateutil import parser from pytz import utc from .._warnings import _warn def _date_to_string(date_val: t.Union[datetime, date, time]) -> str: if isinstance(date_val, datetime): # return date.isoformat() + 'Z', if po...
from importlib import util def _is_in_notebook(): # pragma: no cover try: if not util.find_spec("IPython"): return False from IPython import get_ipython ipython = get_ipython() if ipython is None or "IPKernelApp" not in ipython.config: retur...
import typing as t from pathlib import Path def _get_non_existent_file_path(dir_path: Path, file_name: str) -> Path: if not file_name: file_name = "taipy_file.bin" file_path = dir_path / file_name index = 0 file_stem = file_path.stem file_suffix = file_path.suffix while file...
import re import typing as t _RE_PD_TYPE = re.compile(r"^([^\s\d\[]+)(\d+)(\[(.*,\s(\S+))\])?") def _get_date_col_str_name(columns: t.List[str], col: str) -> str: suffix = "_str" while col + suffix in columns: suffix += "_" return col + suffix
import typing as t import numpy import pandas as pd from ..gui import Gui from .data_format import _DataFormat from .pandas_data_accessor import _PandasDataAccessor class _NumpyDataAccessor(_PandasDataAccessor): __types = (numpy.ndarray,) @staticmethod def get_supported_classes() -> t.Lis...
import typing as t import pandas as pd from ..gui import Gui from ..utils import _MapDict from .data_format import _DataFormat from .pandas_data_accessor import _PandasDataAccessor class _ArrayDictDataAccessor(_PandasDataAccessor): __types = (dict, list, tuple, _MapDict) @staticmethod def...
from .data_accessor import _DataAccessor from .decimator import LTTB, RDP, MinMaxDecimator, ScatterDecimator from .utils import Decimator
import inspect import typing as t from abc import ABC, abstractmethod from .._warnings import _warn from ..utils import _TaipyData from .data_format import _DataFormat class _DataAccessor(ABC): _WS_DATE_FORMAT = "%Y-%m-%dT%H:%M:%S.%fZ" @staticmethod @abstractmethod def get_supported_cl...
from __future__ import annotations import typing as t from abc import ABC, abstractmethod import numpy as np from .._warnings import _warn if t.TYPE_CHECKING: import pandas as pd class Decimator(ABC): """Base class for decimating chart data. *Decimating* is the term used to name the p...
from enum import Enum class _DataFormat(Enum): JSON = "JSON" APACHE_ARROW = "ARROW"
import base64 import pathlib import tempfile import typing as t import urllib.parse from importlib import util from pathlib import Path from sys import getsizeof from .._warnings import _warn from ..utils import _get_non_existent_file_path, _variable_decode _has_magic_module = False if util.find_spec("...
from __future__ import annotations import typing as t from types import SimpleNamespace from .._warnings import _warn class _DataScopes: _GLOBAL_ID = "global" def __init__(self) -> None: self.__scopes: t.Dict[str, SimpleNamespace] = {_DataScopes._GLOBAL_ID: SimpleNamespace()} s...
import typing as t import numpy as np from ..utils import Decimator class ScatterDecimator(Decimator): """A decimator designed for scatter charts. This algorithm fits the data points into a grid. If multiple points are in the same grid cell, depending on the chart configuration, some points ...
from .lttb import LTTB from .minmax import MinMaxDecimator from .rdp import RDP from .scatter_decimator import ScatterDecimator
import typing as t import numpy as np from ..utils import Decimator class MinMaxDecimator(Decimator): """A decimator using the MinMax algorithm. The MinMax algorithm is an efficient algorithm that preserves the peaks within the data. It can work very well with noisy signal data where data pe...
import typing as t import numpy as np from ..utils import Decimator class LTTB(Decimator): """A decimator using the LTTB algorithm. The LTTB algorithm is an high performance algorithm that significantly reduces the number of data points. It can work very well with time-series data to show tr...
import typing as t import numpy as np from ..utils import Decimator class RDP(Decimator): """A decimator using the RDP algorithm. The RDP algorithm reduces a shape made of line segments into a similar shape with less points. This algorithm should be used if the final visual representation is...
import typing as t from ..utils.singleton import _Singleton if t.TYPE_CHECKING: from ._element import _Block class _BuilderContextManager(object, metaclass=_Singleton): def __init__(self): self.__blocks: t.List["_Block"] = [] def push(self, element: "_Block") -> None: self....
from ._api_generator import _ElementApiGenerator from ._element import html # separate import for "Page" class so stubgen can properly generate pyi file from .page import Page _ElementApiGenerator().add_default()
import typing as t from .._renderers import _Renderer from ._context_manager import _BuilderContextManager from ._element import _Block, _DefaultBlock, _Element class Page(_Renderer): """Page generator for the Builder API. This class is used to create a page created with the Builder API.<br/> ...
import typing as t from .._renderers.factory import _Factory class _BuilderFactory(_Factory): @staticmethod def create_element(gui, element_type: str, properties: t.Dict[str, t.Any]) -> t.Tuple[str, str]: builder_html = _Factory.call_builder(gui, element_type, properties, True) if bu...
from __future__ import annotations import copy import typing as t from abc import ABC, abstractmethod from collections.abc import Iterable from ._context_manager import _BuilderContextManager from ._factory import _BuilderFactory if t.TYPE_CHECKING: from ..gui import Gui class _Element(ABC): ...
import inspect import json import os import sys import types import typing as t from taipy.logger._taipy_logger import _TaipyLogger from ..utils.singleton import _Singleton from ._element import _Block, _Control if t.TYPE_CHECKING: from ..extension.library import ElementLibrary class _ElementAp...
import typing as t from abc import ABC, abstractmethod from os import path from ..page import Page from ..utils import _is_in_notebook, _varname_from_content from ._html import _TaipyHTMLParser if t.TYPE_CHECKING: from ..builder._element import _Element from ..gui import Gui class _Renderer(Pag...
import typing as t from .._warnings import _warn from ..gui_types import NumberTypes from ..utils import _RE_PD_TYPE, _get_date_col_str_name, _MapDict def _add_to_dict_and_get(dico: t.Dict[str, t.Any], key: str, value: t.Any) -> t.Any: if key not in dico.keys(): dico[key] = value return dic...
# # 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 u...
from markdown.treeprocessors import Treeprocessor from ..builder import _Builder class _Postprocessor(Treeprocessor): @staticmethod def extend(md, gui, priority): instance = _Postprocessor(md) md.treeprocessors.register(instance, "taipy", priority) instance._gui = gui ...
from markdown.inlinepatterns import InlineProcessor from .factory import _MarkdownFactory class _ControlPattern(InlineProcessor): __PATTERN = _MarkdownFactory._TAIPY_START + r"([a-zA-Z][\.a-zA-Z_$0-9]*)(.*?)" + _MarkdownFactory._TAIPY_END @staticmethod def extend(md, gui, priority): in...
import re from markdown.blockprocessors import BlockProcessor from .factory import _MarkdownFactory class _StartBlockProcessor(BlockProcessor): __RE_FENCE_START = re.compile( _MarkdownFactory._TAIPY_START + r"([a-zA-Z][\.a-zA-Z_$0-9]*)\.start(.*?)" + _MarkdownFactory._TAIPY_END ) # start ...
from typing import Any from markdown.extensions import Extension from .blocproc import _StartBlockProcessor from .control import _ControlPattern from .postproc import _Postprocessor from .preproc import _Preprocessor class _TaipyMarkdownExtension(Extension): config = {"gui": ["", "Gui object for exte...
import typing as t from ..factory import _Factory class _MarkdownFactory(_Factory): # Taipy Markdown tags _TAIPY_START = "TaIpY:" _TAIPY_END = ":tAiPy" _TAIPY_BLOCK_TAGS = ["layout", "part", "expandable", "dialog", "pane"] @staticmethod def create_element(gui, control_type: str...
from .parser import _TaipyHTMLParser
import typing as t from ..factory import _Factory class _HtmlFactory(_Factory): @staticmethod def create_element(gui, namespace: str, control_type: str, all_properties: t.Dict[str, str]) -> t.Tuple[str, str]: builder_html = _Factory.call_builder(gui, f"{namespace}.{control_type}", all_propert...
import re import typing as t from html.parser import HTMLParser from ..._warnings import _warn from .factory import _HtmlFactory class _TaipyHTMLParser(HTMLParser): __TAIPY_NAMESPACE_RE = re.compile(r"([a-zA-Z\_]+):([a-zA-Z\_]*)") def __init__(self, gui): super().__init__() self...
"""The setup script.""" import json import os from setuptools import find_namespace_packages, find_packages, setup with open("README.md", "rb") as readme_file: readme = readme_file.read().decode("UTF-8") with open(f"src{os.sep}taipy{os.sep}templates{os.sep}version.json") as version_file: version ...
from config.config import configure from pages import job_page, scenario_page from pages.root import content, root, selected_data_node, selected_scenario import taipy as tp from taipy import Core, Gui def on_init(state): ... def on_change(state, var, val): if var == "selected_data_node" and va...
from algos import clean_data from taipy import Config, Frequency, Scope def configure(): # ################################################################################################################## # PLACEHOLDER: Add your scenario configurations here ...
from taipy import Config def configure(): Config.load("config/config.toml") return Config.scenarios["scenario_configuration"]
def clean_data(df, replacement_type): df = df.fillna(replacement_type) return df
from .algos import clean_data
from .job_page import job_page from .scenario_page import scenario_page
from taipy.gui import Markdown selected_scenario = None selected_data_node = None content = "" root = Markdown("pages/root.md")
from .job_page import job_page
from taipy.gui import Markdown job_page = Markdown("pages/job_page/job_page.md")
from taipy.gui import Markdown, notify from .data_node_management import manage_partial def notify_on_submission(state, submitable, details): if details["submission_status"] == "COMPLETED": notify(state, "success", "Submision completed!") elif details["submission_status"] == "FAILED": ...
from .scenario_page import scenario_page
# build partial content for a specific data node def build_dn_partial(dn, dn_label): partial_content = "<|part|render={selected_scenario}|\n\n" # ################################################################################################################## # PLACEHOLDER: data node specific content...
import os import taipy # Add taipy version to requirements.txt with open(os.path.join(os.getcwd(), "requirements.txt"), "a") as requirement_file: requirement_file.write(f"taipy=={taipy.version._get_version()}\n") # Use TOML config file or not use_toml_config = "{{ cookiecutter.__use_toml_config }}".uppe...
# # 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 u...
import subprocess import sys def _run_template(main_path, time_out=30): """Run the templates on a subprocess and get stdout after timeout""" with subprocess.Popen([sys.executable, main_path], stdout=subprocess.PIPE, stderr=subprocess.PIPE) as proc: try: stdout, stderr = proc.commun...
import os from cookiecutter.main import cookiecutter from .utils import _run_template def test_scenario_management_with_toml_config(tmpdir): cookiecutter( template="src/taipy/templates/scenario-management", output_dir=tmpdir, no_input=True, extra_context={ ...
""" Contain the application's configuration including the scenario configurations. The configuration is run by the Core service. """ from algorithms import * from taipy import Config # ############################################################################# # PLACEHOLDER: Put your application's conf...