#  # 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    # Initial data set. y = count_of(x)  samples = {"x": ["Apples", "Apples", "Apples", "Oranges", "Bananas", "Oranges"], "y": [5, 10, 3, 8, 5, 2]}    # Create a data set array to allow for two traces  data = [samples, samples]    # Gather those settings in a single dictionary  properties = {      # 'x' of the first trace is the 'x' data from the first element of data      "x[1]": "0/x",      # 'y' of the first trace is the 'y' data from the first element of data      "y[1]": "0/y",      # 'x' of the second trace is the 'x' data from the second element of data      "x[2]": "1/x",      # 'y' of the second trace is the 'y' data from the second element of data      "y[2]": "1/y",      # Data set colors      "color": ["#cd5c5c", "#505070"],      # Data set names (for the legend)      "name": ["Count", "Sum"],      # Configure the binning functions      "options": [          # First trace: count the bins          {"histfunc": "count"},          # Second trace: sum the bin occurences          {"histfunc": "sum"},      ],      # Set x axis name      "layout": {"xaxis": {"title": "Fruit"}},  }    page = """  # Histogram - Binning function    <|{data}|chart|type=histogram|properties={properties}|>  """    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    # Skill categories  skills = ["HTML", "CSS", "Java", "Python", "PHP", "JavaScript", "Photoshop"]  data = [      # Proportion of skills used for Backend development      {"Backend": [10, 10, 80, 70, 90, 30, 0], "Skills": skills},      # Proportion of skills used for Frontend development      {"Frontend": [90, 90, 0, 10, 20, 80, 60], "Skills": skills},  ]    # Append first elements to all arrays for a nice stroke  skills.append(skills[0])  data[0]["Backend"].append(data[0]["Backend"][0])  data[1]["Frontend"].append(data[1]["Frontend"][0])    layout = {      # Force the radial axis displayed range      "polar": {"radialaxis": {"range": [0, 100]}}  }    # Fill the trace  options = {"fill": "toself"}    # Reflected in the legend  names = ["Backend", "Frontend"]    # To shorten the chart control definition  r = ["0/Backend", "1/Frontend"]  theta = ["0/Skills", "1/Skills"]    page = """  # Radar - Multiple    <|{data}|chart|type=scatterpolar|name={names}|r={r}|theta={theta}|options={options}|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 holds the _x_ series and two distinct series for _y_  data = {      "x": x_range,      # y1 = x*x      "y1": [x * x for x in x_range],      # y2 = 2-x*x/50      "y2": [(100 - x * x) / 50 for x in x_range],  }    layout = {      "yaxis2": {          # Second axis overlays with the first y axis          "overlaying": "y",          # Place the second axis on the right          "side": "right",          # and give it a title          "title": "Second y axis",      },      "legend": {          # Place the legend above chart          "yanchor": "bottom"      },  }    page = """  # Basics - Multiple axis    Shared axis:  <|{data}|chart|x=x|y[1]=y1|y[2]=y2|height=300px|>    With two axis:  <|{data}|chart|x=x|y[1]=y1|y[2]=y2|yaxis[2]=y2|layout={layout}|height=300px|>    """    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    # Source https://www.fao.org/faostat/en/#data/SDGB  data = {      "Country": [          "Rest of the world",          "Russian Federation",          "Brazil",          "Canada",          "United States of America",          "China",          "Australia",          "Democratic Republic of the Congo",          "Indonesia",          "Peru",      ],      "Area": [1445674.66, 815312, 496620, 346928, 309795, 219978, 134005, 126155, 92133.2, 72330.4],  }    page = """  # Pie - Simple    <|{data}|chart|type=pie|values=Area|label=Country|>  """    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>  # You may need to install the scikit-learn package as well.  # -----------------------------------------------------------------------------------------  from os.path import exists    from sklearn.datasets import make_regression  from sklearn.linear_model import LinearRegression    from taipy.gui import Gui    # Let scikit-learn generate a random regression problem  n_samples = 300  X, y, coef = make_regression(n_samples=n_samples, n_features=1, n_informative=1, n_targets=1, noise=25, coef=True)    model = LinearRegression().fit(X, y)    x_data = X.flatten()  y_data = y.flatten()  predict = model.predict(X)    data = {"x": x_data, "y": y_data, "Regression": predict}    page = """  # Scatter - Regression    <|{data}|chart|x=x|y[1]=y|mode[1]=markers|y[2]=Regression|mode[2]=line|>  """    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


#  # 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 = {      "Temperatures": [          [17.2, 27.4, 28.6, 21.5],          [5.6, 15.1, 20.2, 8.1],          [26.6, 22.8, 21.8, 24.0],          [22.3, 15.5, 13.4, 19.6],      ],      "Cities": ["Hanoi", "Paris", "Rio", "Sydney"],      "Seasons": ["Winter", "Spring", "Summer", "Autumn"],  }    layout = {      # This array contains the information we want to display in the cells      # These are filled later      "annotations": [],      # No ticks on the x axis, show labels on top the of the chart      "xaxis": {"ticks": "", "side": "top"},      # No ticks on the y axis      # Add a space character for a small margin with the text      "yaxis": {"ticks": "", "ticksuffix": " "},  }    seasons = data["Seasons"]  cities = data["Cities"]  # Iterate over all cities  for city in range(len(cities)):      # Iterate over all seasons      for season in range(len(seasons)):          temperature = data["Temperatures"][city][season]          # Create the annotation          annotation = {              # The name of the season              "x": seasons[season],              # The name of the city              "y": cities[city],              # The temperature, as a formatted string              "text": f"{temperature}\N{DEGREE SIGN}C",              # Change the text color depending on the temperature              # so it results in a better contrast              "font": {"color": "white" if temperature < 14 else "black"},              # Remove the annotation arrow              "showarrow": False,          }          # Add the annotation to the layout's annotations array          layout["annotations"].append(annotation)    page = """  ## Heatmap - Annotated    <|{data}|chart|type=heatmap|z=Temperatures|x=Seasons|y=Cities|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 = {      "Types": ["Website visit", "Downloads", "Prospects", "Invoice sent", "Closed"],      "Visits_us": [13873, 10533, 5443, 2703, 908],      "Visits_eu": [7063, 4533, 3443, 1003, 1208],      "Visits_ap": [6873, 2533, 3443, 1703, 508],  }    # Columns for each trace  x = ["Visits_us", "Visits_eu", "Visits_ap"]    # Legend text for each trace  names = ["US", "EU", "AP"]    page = """  # Funnel - Multiple traces    <|{data}|chart|type=funnel|x={x}|y=Types|name={names}|>  """    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 = {      "Temperatures": [          [17.2, 27.4, 28.6, 21.5],          [5.6, 15.1, 20.2, 8.1],          [26.6, 22.8, 21.8, 24.0],          [22.3, 15.5, 13.4, 19.6],      ],      "Cities": ["Hanoi", "Paris", "Rio", "Sydney"],      "Seasons": ["Winter", "Spring", "Summer", "Autumn"],  }    page = """  # Heatmap - Basic    <|{data}|chart|type=heatmap|z=Temperatures|x=Seasons|y=Cities|>  """    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>  # -----------------------------------------------------------------------------------------  # Face-to-face bar charts example  import numpy    from taipy.gui import Gui    n_years = 10    proportions_female = numpy.zeros(n_years)  proportions_male = numpy.zeros(n_years)    # Prepare the data set with random variations  proportions_female[0] = 0.4  proportions_male[0] = proportions_female[0] * (1 + numpy.random.normal(0, 0.1))    for i in range(1, n_years):      mean_i = (0.5 - proportions_female[i - 1]) / 5      new_value = proportions_female[i - 1] + numpy.random.normal(mean_i, 0.1)        new_value = min(max(0, new_value), 1)      proportions_female[i] = new_value      proportions_male[i] = proportions_female[i] * (1 + numpy.random.normal(0, 0.1))      data = {      "Hobbies": [          "Archery",          "Tennis",          "Football",          "Basket",          "Volley",          "Golf",          "Video-Games",          "Reading",          "Singing",          "Music",      ],      "Female": proportions_female,      # Negate these values so they appear to the left side      "Male": -proportions_male,  }    properties = {      # Shared y values      "y": "Hobbies",      # Bars for the female data set      "x[1]": "Female",      "color[1]": "#c26391",      # Bars for the male data set      "x[2]": "Male",      "color[2]": "#5c91de",      # Both data sets are represented with an horizontal orientation      "orientation": "h",      #      "layout": {          # This makes left and right bars aligned on the same y value          "barmode": "overlay",          # Set a relevant title for the x axis          "xaxis": {"title": "Gender"},          # Hide the legend          "showlegend": False,          "margin": {"l": 100},      },  }    page = """  # Bar - Facing    <|{data}|chart|type=bar|properties={properties}|>  """    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    # Random data set  data = [random.random() for i in range(100)]    # Normalize to show bin probabilities  options = {"histnorm": "probability"}    page = """  # Histogram - Normalized    <|{data}|chart|type=histogram|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>  # You may need to install the scikit-learn package as well.  # -----------------------------------------------------------------------------------------  import numpy  import pandas  from sklearn.datasets import make_classification    from taipy.gui import Gui    # Let scikit-learn generate a random 2-class classification problem  features, label = make_classification(n_samples=1000, n_features=2, n_informative=2, n_redundant=0)    random_data = pandas.DataFrame({"x": features[:, 0], "y": features[:, 1], "label": label})    data_x = random_data["x"]  class_A = [random_data.loc[i, "y"] if random_data.loc[i, "label"] == 0 else numpy.nan for i in range(len(random_data))]  class_B = [random_data.loc[i, "y"] if random_data.loc[i, "label"] == 1 else numpy.nan for i in range(len(random_data))]    data = {"x": random_data["x"], "Class A": class_A, "Class B": class_B}    page = """  # Scatter - Classification    <|{data}|chart|mode=markers|x=x|y[1]=Class A|y[2]=Class B|width=60%|>  """    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 itertools import accumulate    import numpy as np    from taipy.gui import Gui    grid_size = 10  data = [      {          # z is set to:          # - 0 if row+col is a multiple of 4          # - 1 if row+col is a multiple of 2          # - 0.5 otherwise          "z": [              [0.0 if (row + col) % 4 == 0 else 1 if (row + col) % 2 == 0 else 0.5 for col in range(grid_size)]              for row in range(grid_size)          ]      },      {          # A series of coordinates, growing exponentially          "x": [0] + list(accumulate(np.logspace(0, 1, grid_size))),          # A series of coordinates, shrinking exponentially          "y": [0] + list(accumulate(np.logspace(1, 0, grid_size))),      },  ]    # Axis template used in the layout object  axis_template = {      # Don't show any line or tick or label      "showgrid": False,      "zeroline": False,      "ticks": "",      "showticklabels": False,      "visible": False,  }    layout = {"xaxis": axis_template, "yaxis": axis_template}    options = {      # Remove the color scale display      "showscale": False  }    page = """  ## Heatmap - Unequal block sizes    <|{data}|chart|type=heatmap|z=0/z|x=1/x|y=1/y|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>  # -----------------------------------------------------------------------------------------  from taipy.gui import Gui    # 9-hole course  n_holes = 9    # Data set  # Each entry holds an array of values. One for each hole, plus one for th  data = {      # ["Hole1", "Hole2", ..., "Hole9"]      "Hole": [f"Hole{h}" for h in range(1, n_holes + 1)] + ["Score"],      # Par for each hole      "Par": [3, 4, 4, 5, 3, 5, 4, 5, 3] + [None],      # Score for each hole      "Score": [4, 4, 5, 4, 4, 5, 4, 5, 4] + [None],      # Represented as relative values except for the last one      "M": n_holes * ["relative"] + ["total"],  }    # Compute difference (Score-Par)  data["Diff"] = [data["Score"][i] - data["Par"][i] for i in range(0, n_holes)] + [None]    # Show positive values in red, and negative values in green  options = {"decreasing": {"marker": {"color": "green"}}, "increasing": {"marker": {"color": "red"}}}    page = """  # Waterfall - Styling    <|{data}|chart|type=waterfall|x=Hole|y=Diff|measure=M|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    # Common axis for all data: [1..10]  x = list(range(1, 11))  # Sample data  samples = [5, 7, 8, 4, 5, 9, 8, 8, 6, 5]    # Generate error data  # Error that adds to the input data  error_plus = [3 * random.random() + 0.5 for _ in x]  # Error substracted from to the input data  error_minus = [3 * random.random() + 0.5 for _ in x]    # Upper bound (y + error_plus)  error_upper = [y + e for (y, e) in zip(samples, error_plus)]  # Lower bound (y - error_minus)  error_lower = [y - e for (y, e) in zip(samples, error_minus)]    data = [      # Trace for samples      {"x": x, "y": samples},      # Trace for error range      {          # Roundtrip around the error bounds: onward then return          "x": x + list(reversed(x)),          # The two error bounds, with lower bound reversed          "y": error_upper + list(reversed(error_lower)),      },  ]    properties = {      # Error data      "x[1]": "1/x",      "y[1]": "1/y",      "options[1]": {          # Shows as filled area          "fill": "toself",          "fillcolor": "rgba(70,70,240,0.6)",          "showlegend": False,      },      # Don't show surrounding stroke      "color[1]": "transparent",      # Raw data (displayed on top of the error band)      "x[2]": "0/x",      "y[2]": "0/y",      "color[2]": "rgb(140,50,50)",      # Shown in the legend      "name[2]": "Input",  }    page = """  # Continuous Error - Simple    <|{data}|chart|properties={properties}|>  """    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 = {      "Products": [          "Nail polish",          "Eyebrow pencil",          "Rouge",          "Lipstick",          "Eyeshadows",          "Eyeliner",          "Foundation",          "Lip gloss",          "Mascara",      ],      "USA": [12814, 13012, 11624, 8814, 12998, 12321, 10342, 22998, 11261],      "China": [3054, 5067, 7004, 9054, 12043, 15067, 10119, 12043, 10419],      "EU": [4376, 3987, 3574, 4376, 4572, 3417, 5231, 4572, 6134],      "Africa": [4229, 3932, 5221, 9256, 3308, 5432, 13701, 4008, 18712],  }    # Order the different traces  ys = ["USA", "China", "EU", "Africa"]    options = [      # For the USA      {"stackgroup": "one", "groupnorm": "percent"},      # For China      {"stackgroup": "one"},      # For the EU      {"stackgroup": "one"},      # For Africa      {"stackgroup": "one"},  ]    layout = {      # Show all values when hovering on a data point      "hovermode": "x unified"  }    page = """  # Filled Area - Stacked Normalized    <|{data}|chart|mode=none|x=Products|y={ys}|options={options}|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 math    from taipy.gui import Gui    # One data point for each degree  theta = range(0, 360)      # Create a rose-like shaped radius-array  def create_rose(n_petals):      return [math.cos(math.radians(n_petals * angle)) for angle in theta]      data = {"theta": theta, "r1": create_rose(2), "r2": create_rose(3), "r3": create_rose(4)}    # We want three traces in the same chart  r = ["r1", "r2", "r3"]    layout = {      # Hide the legend      "showlegend": False,      "polar": {          # Hide the angular axis          "angularaxis": {"visible": False},          # Hide the radial axis          "radialaxis": {"visible": False},      },  }    page = """  # Polar - Multiple    <|{data}|chart|type=scatterpolar|mode=lines|r={r}|theta=theta|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>  # You may need to install the yfinance package as well.  # -----------------------------------------------------------------------------------------  from taipy.gui import Gui    data = {      "x": [1, 2, 3, 4, 5],      "y": [10, 7, 4, 1, 5],      "Sizes": [20, 30, 40, 50, 30],      "Symbols": ["circle-open", "triangle-up", "hexagram", "star-diamond", "circle-cross"],  }    marker = {      "color": "#77A",      "size": "Sizes",      "symbol": "Symbols",  }    page = """  # Bubble - Symbols    <|{data}|chart|mode=markers|x=x|y=y|marker={marker}|>  """    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>  # You may need to install the yfinance package as well.  # -----------------------------------------------------------------------------------------  import yfinance    from taipy.gui import Gui    # Extraction of a few days of stock historical data for AAPL using  # the yfinance package (see https://pypi.org/project/yfinance/).  # The returned value is a Pandas DataFrame.  ticker = yfinance.Ticker("AAPL")  stock = ticker.history(interval="1d", start="2018-08-18", end="2018-09-10")  # Copy the DataFrame index to a new column  stock["Date"] = stock.index    options = {      # Candlesticks that show decreasing values are orange      "decreasing": {"line": {"color": "orange"}},      # Candlesticks that show decreasing values are blue      "increasing": {"line": {"color": "blue"}},  }    layout = {      "xaxis": {          # Hide the range slider          "rangeslider": {"visible": False}      }  }    page = """  # Candlestick - Styling    <|{stock}|chart|type=candlestick|x=Date|open=Open|close=Close|low=Low|high=High|options={options}|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 = {      "Types": ["Website visit", "Downloads", "Prospects", "Invoice sent", "Closed"],      "Visits": [13873, 10533, 5443, 2703, 908],  }    marker = {      # Boxes are filled with a blue gradient color      "color": ["hsl(210,50%,50%)", "hsl(210,60%,60%)", "hsl(210,70%,70%)", "hsl(210,80%,80%)", "hsl(210,90%,90%)"],      # Lines get thicker, with an orange-to-green gradient color      "line": {"width": [1, 1, 2, 3, 4], "color": ["f5720a", "f39c1d", "f0cc3d", "aadb12", "8cb709"]},  }    options = {      # Lines connecting boxes are thick, dotted and green      "connector": {"line": {"color": "green", "dash": "dot", "width": 4}}  }    page = """  # Funnel Chart - Custom markers    <|{data}|chart|type=funnel|x=Visits|y=Types|marker={marker}|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    # Random data set  data = [random.random() for i in range(500)]    options = {      # Enable the cumulative histogram      "cumulative": {"enabled": True}  }    page = """  # Histogram - Cumulative    <|{data}|chart|type=histogram|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>  # -----------------------------------------------------------------------------------------  from taipy.gui import Gui    # Create a star shape  data = {"r": [3, 1] * 5 + [3], "theta": list(range(0, 360, 36)) + [0]}    options = [      # First plot is filled with a yellow-ish color      {"subplot": "polar", "fill": "toself", "fillcolor": "#E4FF87"},      # Second plot is filled with a blue-ish color      {"fill": "toself", "subplot": "polar2", "fillcolor": "#709BFF"},  ]    layout = {      "polar": {          # This actually is the default value          "angularaxis": {              "direction": "counterclockwise",          },      },      "polar2": {          "angularaxis": {              # Rotate the axis 180° (0 is on the left)              "rotation": 180,              # Orient the axis clockwise              "direction": "clockwise",              # Show the angles as radians              "thetaunit": "radians",          },      },      # Hide the legend      "showlegend": False,  }    page = """  # Polar Charts - Direction    <|{data}|chart|type=scatterpolar|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>  # -----------------------------------------------------------------------------------------  from taipy.gui import Gui    value = "XS"    page = """  # Slider - List of values    <|{value}|slider|lov=XXS;XS;S;M;L;XL;XXL|>  """    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 io  from decimal import Decimal, getcontext    from taipy.gui import Gui, download    # Initial precision  precision = 10      def pi(precision: int) -> list[int]:      """Compute Pi to the required precision.        Adapted from https://docs.python.org/3/library/decimal.html      """      saved_precision = getcontext().prec  # Save precision      getcontext().prec = precision      three = Decimal(3)  # substitute "three=3.0" for regular floats      lasts, t, s, n, na, d, da = 0, three, 3, 1, 0, 0, 24      while s != lasts:          lasts = s          n, na = n + na, na + 8          d, da = d + da, da + 32          t = (t * n) / d          s += t      digits = []      while s != 0:          integral = int(s)          digits.append(integral)          s = (s - integral) * 10      getcontext().prec = saved_precision      return digits      # Generate the digits, save them in a CSV file content, and trigger a download action  # so the user can retrieve them  def download_pi(state):      digits = pi(state.precision)      buffer = io.StringIO()      buffer.write("index,digit\n")      for i, d in enumerate(digits):          buffer.write(f"{i},{d}\n")      download(state, content=bytes(buffer.getvalue(), "UTF-8"), name="pi.csv")      page = """  # File Download - Dynamic content    Precision:    <|{precision}|slider|min=2|max=10000|>    <|{None}|file_download|on_action=download_pi|label=Download Pi digits|>  """    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    value = 9    page = """  # Slider - Custom range    <|{value}|slider|min=1|max=10|>    Value: <|{value}|>  """    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 datetime import date, timedelta    from taipy.gui import Gui    # Create the list of dates (all year 2000)  all_dates = {}  all_dates_str = []  start_date = date(2000, 1, 1)  end_date = date(2001, 1, 1)  a_date = start_date  while a_date < end_date:      date_str = a_date.strftime("%Y/%m/%d")      all_dates_str.append(date_str)      all_dates[date_str] = a_date      a_date += timedelta(days=1)    # Initial selection: first and last day  dates = [all_dates_str[1], all_dates_str[-1]]  # These two variables are used in text controls  start_sel = all_dates[dates[0]]  end_sel = all_dates[dates[1]]      def on_change(state, _, var_value):      # Update the text controls      state.start_sel = all_dates[var_value[0]]      state.end_sel = all_dates[var_value[1]]      page = """  # Slider - Date range    <|{dates}|slider|lov={all_dates_str}|>    Start: <|{start_sel}|text|format=d MMM|>    End: <|{end_sel}|text|format=d MMM|>  """    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 os  from decimal import Decimal, getcontext  from tempfile import NamedTemporaryFile    from taipy.gui import Gui, download    # Initial precision  precision = 10  # Stores the path to the temporary file  temp_path = None      def pi(precision: int) -> list[int]:      """Compute Pi to the required precision.        Adapted from https://docs.python.org/3/library/decimal.html      """      saved_precision = getcontext().prec  # Save precision      getcontext().prec = precision      three = Decimal(3)  # substitute "three=3.0" for regular floats      lasts, t, s, n, na, d, da = 0, three, 3, 1, 0, 0, 24      while s != lasts:          lasts = s          n, na = n + na, na + 8          d, da = d + da, da + 32          t = (t * n) / d          s += t      digits = []      while s != 0:          integral = int(s)          digits.append(integral)          s = (s - integral) * 10      getcontext().prec = saved_precision      return digits      # Remove the temporary file  def clean_up(state):      os.remove(state.temp_path)      # Generate the digits, save them in a CSV temporary file, then trigger a download action  # for that file.  def download_pi(state):      digits = pi(state.precision)      with NamedTemporaryFile("r+t", suffix=".csv", delete=False) as temp_file:          state.temp_path = temp_file.name          temp_file.write("index,digit\n")          for i, d in enumerate(digits):              temp_file.write(f"{i},{d}\n")      download(state, content=temp_file.name, name="pi.csv", on_action=clean_up)      page = """  # File Download - Dynamic content    Precision:    <|{precision}|slider|min=2|max=10000|>    <|{None}|file_download|on_action=download_pi|label=Download Pi digits|>  """    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    value = 50    page = """  # Slider - Simple    <|{value}|slider|>    Value: <|{value}|>  """    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    value = 40    page = """  # Slider - Vertical    <|{value}|slider|orientation=v|>    Value: <|{value}|>  """    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    # Initial values  values = [20, 40, 80]    page = """  # Slider - Range    <|{values}|slider|>    Selection: <|{values}|>  """    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.


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


import 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]): The text associated to the image or None if there is none.          svg (Optional[bool]): True if the image is svg.        If a text is associated to an icon, it is rendered by the visual elements that      uses this Icon.      """        @staticmethod      def get_dict_or(value: t.Union[str, t.Any]) -> t.Union[str, dict]:          return value._to_dict() if isinstance(value, Icon) else value        def __init__(          self,          path: str,          text: t.Optional[str] = None,          light_path: t.Optional[bool] = None,          dark_path: t.Optional[bool] = None,      ) -> None:          """Initialize a new Icon.            Arguments:              path (str): The path to an image file.
                  This path must be relative to and inside the root directory of the                  application (where the Python file that created the `Gui` instance                  is located).
                  In situations where the image file is located outside the application                  directory, a _path mapping_ must be used: the _path_mapping_ parameter                  of the `Gui^` constructor makes it possible to access a resource anywhere                  on the server filesystem, as if it were located in a subdirectory of                  the application directory.              text (Optional[str]): The text associated to the image. If *text* is None,                  there is no text associated to this image.              light_path (Optional[str]): The path to the light theme image (fallback to *path* if not defined).              dark_path (Optional[str]): The path to the dark theme image (fallback to *path* if not defined).          """          self.path = path          self.text = text          if light_path is not None:              self.light_path = light_path          if dark_path is not None:              self.dark_path = dark_path        def _to_dict(self, a_dict: t.Optional[dict] = None) -> dict:          if a_dict is None:              a_dict = {}          a_dict["path"] = self.path          if self.text is not None:              a_dict["text"] = self.text          if hasattr(self, "light_path") and self.light_path is not None:              a_dict["lightPath"] = self.light_path          if hasattr(self, "dark_path") and self.dark_path is not None:              a_dict["darkPath"] = self.dark_path          return a_dict


from .gui import Gui


"""# 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 through visual elements.    Each page can contain regular text and images, as well as Taipy controls that are  typically linked to some value that is managed by the whole Taipy application.    Here is how you can create your first Taipy User Interface:       - Create a Python source file.       Copy these two lines into a file called *taipy_app.py*.       ```py title="taipy_app.py"       from taipy import Gui       Gui("# Hello Taipy!").run()       ```     - Install Taipy:       ```       pip install taipy       ```     - Run your application:       ```       python taipy_app.py       ```    Your browser opens a new page, showing the content of your graphical  application.    !!! Note "Optional packages"        There are Python packages that you can install in your environment to      add functionality to Taipy GUI:        - [`python-magic`](https://pypi.org/project/python-magic/): identifies image format        from byte buffers so the [`image`](../../gui/viselements/image.md) control can        display them, and so that [`file_download`](../../gui/viselements/file_download.md)        can request the browser to display the image content when relevant.
        You can install that package with the regular `pip install python-magic` command        (then potentially `pip install python-magic` on Windows),        or install Taipy GUI using: `pip install taipy-gui[image]`.      - [`pyarrow`](https://pypi.org/project/pyarrow/): can improve the performance of your        application by reducing the volume of data transferred between the web server and the        clients. This is relevant if your application uses large tabular data.
        You can install that package with the regular `pip install pyarrow` command,        or install Taipy GUI using: `pip install taipy-gui[arrow]`.      - [`simple-websocket`](https://pypi.org/project/simple-websocket/): enables the        debugging of the WebSocket part of the server execution.
        You can install that package with the regular `pip install simple-websocket` command,        or install Taipy GUI using: `pip install taipy-gui[simple-websocket]`.      - [`pyngrok`](https://pypi.org/project/pyngrok/): enables use of [Ngrok](https://ngrok.com/)        to access Taipy GUI application from the internet.
        You can install that package with the regular `pip install pyngrok` command,        or install Taipy GUI using: `pip install taipy-gui[pyngrok]`.    """    from importlib.util import find_spec    from ._init import *  from ._renderers import Html, Markdown  from .gui_actions import (      broadcast_callback,      download,      get_module_context,      get_module_name_from_state,      get_state_id,      get_user_content_url,      hold_control,      invoke_callback,      invoke_long_callback,      navigate,      notify,      resume_control,  )  from .icon import Icon  from .page import Page  from .partial import Partial  from .state import State  from .utils import is_debugging    if find_spec("taipy") and find_spec("taipy.config"):      from taipy.config import _inject_section        from ._default_config import default_config      from ._gui_section import _GuiSection        _inject_section(          _GuiSection,          "gui_config",          _GuiSection(property_list=list(default_config)),          [("configure_gui", _GuiSection._configure)],          add_to_unconflicted_sections=True,      )


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 template text into actual pages that can be displayed      on a web browser.        When a page is requested to be displayed, it is converted into HTML      code that can be sent to the client. All control placeholders are      replaced by their respective graphical component so you can show      your application variables and interact with them.      """        def __init__(self, **kwargs) -> None:          self._class_module_name = ""          self._class_locals: t.Dict[str, t.Any] = {}          self._frame: t.Optional[FrameType] = None          self._renderer: t.Optional[Page] = self.create_page()          if "frame" in kwargs:              self._frame = kwargs.get("frame")          elif self._renderer:              self._frame = self._renderer._frame          elif len(inspect.stack()) < 4:              raise RuntimeError(f"Can't resolve module. Page '{type(self).__name__}' is not registered.")          else:              self._frame = t.cast(FrameType, t.cast(FrameType, inspect.stack()[3].frame))          if self._renderer:              # Extract the page module's attributes and methods              cls = type(self)              cls_locals = dict(vars(self))              funcs = [                  i[0]                  for i in inspect.getmembers(cls)                  if not i[0].startswith("_") and (inspect.ismethod(i[1]) or inspect.isfunction(i[1]))              ]              for f in funcs:                  func = getattr(self, f)                  if hasattr(func, "__func__") and func.__func__ is not None:                      cls_locals[f] = func.__func__              self._class_module_name = cls.__name__              self._class_locals = cls_locals        def create_page(self) -> t.Optional[Page]:          """Create the page content for page modules.            If this page is a page module, this method must be overloaded and return the page content.            This method should never be called directly: only the Taipy GUI internals will.            The default implementation returns None, indicating that this class does not implement          a page module.            Returns:              The page content for this Page subclass, making it a page module.          """          return None        def _get_locals(self) -> t.Optional[t.Dict[str, t.Any]]:          return (              self._class_locals              if self._is_class_module()              else None              if (frame := self._get_frame()) is None              else _filter_locals(frame.f_locals)          )        def _is_class_module(self):          return self._class_module_name != ""        def _get_frame(self):          if not hasattr(self, "_frame"):              raise RuntimeError(f"Page '{type(self).__name__}' was not registered correctly.")          return self._frame        def _get_module_name(self) -> t.Optional[str]:          return (              None              if (frame := self._get_frame()) is None              else f"{_get_module_name_from_frame(frame)}{'.' if self._class_module_name else ''}{self._class_module_name}"          )        def _get_content_detail(self, gui) -> str:          return f"in class {type(self).__name__}"        def render(self, gui) -> str:          if self._renderer is not None:              return self._renderer.render(gui)          return "
No renderer found for page
"


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):          TaipyGuiWarning._tp_debug_mode = (              debug_mode if debug_mode else hasattr(sys, "gettrace") and sys.gettrace() is not None          )      def _warn(message: str, e: t.Optional[BaseException] = None):      warnings.warn(          f"{message}:\n{''.join(traceback.format_exception(type(e), e, e.__traceback__))}"          if e and TaipyGuiWarning._tp_debug_mode          else f"{message}:\n{e}"          if e          else message,          TaipyGuiWarning,          stacklevel=2,      )


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):          self._property_list = property_list          super().__init__(**properties)        def __copy__(self):          return _GuiSection(property_list=copy(self._property_list), **copy(self._properties))        def _clean(self):          self._properties.clear()        def _to_dict(self):          as_dict = {}          as_dict.update(self._properties)          return as_dict        @classmethod      def _from_dict(cls, as_dict: t.Dict[str, t.Any], *_):          return _GuiSection(property_list=list(default_config), **as_dict)        def _update(self, as_dict: t.Dict[str, t.Any]):          if self._property_list:              as_dict = {k: v for k, v in as_dict.items() if k in self._property_list}          self._properties.update(as_dict)        @staticmethod      def _configure(**properties) -> "_GuiSection":          """NOT DOCUMENTED          Configure the Graphical User Interface.            Parameters:              **properties (dict[str, any]): Keyword arguments that configure the behavior of the `Gui^` instances.<br/>                  Please refer to the                  [Configuration section](../gui/configuration.md#configuring-the-gui-instance)                  of the User Manual for more information on the accepted arguments.          Returns:              The GUI configuration.            """          section = _GuiSection(property_list=list(default_config), **properties)          TaipyConfig._register(section)          return TaipyConfig.unique_sections[_GuiSection.name]


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,      _TaipyLov,      _TaipyLovValue,      _TaipyNumber,  )      class _WsType(Enum):      ACTION = "A"      MULTIPLE_UPDATE = "MU"      REQUEST_UPDATE = "RU"      DATA_UPDATE = "DU"      UPDATE = "U"      ALERT = "AL"      BLOCK = "BL"      NAVIGATE = "NA"      CLIENT_ID = "ID"      MULTIPLE_MESSAGE = "MS"      DOWNLOAD_FILE = "DF"      PARTIAL = "PR"      ACKNOWLEDGEMENT = "ACK"      NumberTypes = {"int", "int64", "float", "float64"}      class PropertyType(Enum):      """      All the possible element property types.        This is used when creating custom visual elements, where you have      to indicate the type of each property.        Some types are 'dynamic', meaning that if the property value is modified, it      is automatically handled by Taipy and propagated to the entire application.        See `ElementProperty^` for more details.      """        boolean = "boolean"      """      The property holds a Boolean value.      """      toHtmlContent = _TaipyContentHtml      content = _TaipyContent      data = _TaipyData      date = _TaipyDate      date_range = _TaipyDateRange      dict = "dict"      """      The property holds a dictionary.      """      dynamic_dict = _TaipyDict      """      The property holds a dynamic dictionary.      """      dynamic_number = _TaipyNumber      """      The property holds a dynamic number.      """      dynamic_lo_numbers = _TaipyLoNumbers      """      The property holds a dynamic list of numbers.      """      dynamic_boolean = _TaipyBool      """      The property holds a dynamic Boolean value.      """      dynamic_list = "dynamiclist"      dynamic_string = "dynamicstring"      """      The property holds a dynamic string.      """      function = "function"      """      The property holds a reference to a function.      """      image = _TaipyContentImage      json = "json"      lov = _TaipyLov      """      The property holds a LoV (list of values).      """      lov_value = _TaipyLovValue      """      The property holds a value in a LoV (list of values).      """      number = "number"      """      The property holds a number.      """      react = "react"      broadcast = "broadcast"      string = "string"      """      The property holds a string.      """      string_or_number = "string|number"      """      The property holds a string or a number.        This is typically used to handle CSS dimension values, where a unit can be used.      """      boolean_or_list = "boolean|list"      slider_value = "number|number[]|lovValue"      string_list = "stringlist"      decimator = Decimator      """      The property holds an inner attributes that is defined by a library and cannot be overridden by the user.      """      inner = "inner"      @t.overload  def _get_taipy_type(a_type: None) -> None:      ...      @t.overload  def _get_taipy_type(a_type: t.Type[_TaipyBase]) -> t.Type[_TaipyBase]:      ...      @t.overload  def _get_taipy_type(a_type: PropertyType) -> t.Type[_TaipyBase]:      ...      @t.overload  def _get_taipy_type(      a_type: t.Optional[t.Union[t.Type[_TaipyBase], t.Type[Decimator], PropertyType]]  ) -> t.Optional[t.Union[t.Type[_TaipyBase], t.Type[Decimator], PropertyType]]:      ...      def _get_taipy_type(      a_type: t.Optional[t.Union[t.Type[_TaipyBase], t.Type[Decimator], PropertyType]]  ) -> t.Optional[t.Union[t.Type[_TaipyBase], t.Type[Decimator], PropertyType]]:      if a_type is None:          return None      if isinstance(a_type, PropertyType) and not isinstance(a_type.value, str):          return a_type.value      if isclass(a_type) and not isinstance(a_type, PropertyType) and issubclass(a_type, _TaipyBase):          return a_type      if a_type == PropertyType.boolean:          return _TaipyBool      elif a_type == PropertyType.number:          return _TaipyNumber      return None


# _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._renderer: t.Optional[Page] = None          self._style: t.Optional[str] = None          self._route: t.Optional[str] = None          self._head: t.Optional[list] = None        def render(self, gui: Gui):          if self._renderer is None:              raise RuntimeError(f"Can't render page {self._route}: no renderer found")          with warnings.catch_warnings(record=True) as w:              warnings.resetwarnings()              with gui._set_locals_context(self._renderer._get_module_name()):                  self._rendered_jsx = self._renderer.render(gui)              if w:                  s = "\033[1;31m\n"                  s += (                      message := f"--- {len(w)} warning(s) were found for page '{'/' if self._route == gui._get_root_page_name() else self._route}' {self._renderer._get_content_detail(gui)} ---\n"                  )                  for i, wm in enumerate(w):                      s += f" - Warning {i + 1}: {wm.message}\n"                  s += "-" * len(message)                  s += "\033[0m\n"                  logging.warn(s)          if hasattr(self._renderer, "head"):              self._head = list(self._renderer.head)  # type: ignore          # return renderer module_name from frame          return self._renderer._get_module_name()


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 elevation color for LIGHT MODE      "color_background_light": "#f0f5f7",      "color_paper_light": "#ffffff",      # Background and elevation color for DARK MODE      "color_background_dark": "#152335",      "color_paper_dark": "#1f2f44",      # DEFINING FONTS      # Set main font family      "font_family": "Lato, Arial, sans-serif",      # DEFINING ROOT STYLES      # Set root margin      "root_margin": "1rem",      # DEFINING SHAPES      # Base border radius in px      "border_radius": 8,      # DEFINING MUI COMPONENTS STYLES      # Matching input and button height in css size unit      "input_button_height": "48px",  }    # Default config loaded by app.py  default_config: Config = {      "allow_unsafe_werkzeug": False,      "async_mode": "gevent",      "change_delay": None,      "chart_dark_template": None,      "base_url": "/",      "dark_mode": True,      "dark_theme": None,      "debug": False,      "extended_status": False,      "favicon": None,      "flask_log": False,      "host": "127.0.0.1",      "light_theme": None,      "margin": "1em",      "ngrok_token": "",      "notebook_proxy": True,      "notification_duration": 3000,      "propagate": True,      "run_browser": True,      "run_in_thread": False,      "run_server": True,      "server_config": None,      "single_client": False,      "system_notification": False,      "theme": None,      "time_zone": None,      "title": None,      "stylekit": _default_stylekit.copy(),      "upload_folder": None,      "use_arrow": False,      "use_reloader": False,      "watermark": "Taipy inside",      "webapp_path": None,      "port": 5000,  }


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 in different      and not related pages. This allows not to have to repeat yourself when      creating your page templates.        Visual elements such as [`part`](../gui/viselements/part.md),      [`dialog`](../gui/viselements/dialog.md) or      [`pane`](../gui/viselements/pane.md) can use Partials.        Note that `Partial` has no constructor (no `__init__()` method): to create a      `Partial`, you must call the `Gui.add_partial()^` function.        Partials can be really handy if you want to modify a section of a page:      the `update_content()` method dynamically update pages that make use      of this `Partial` therefore making it easy to change the content of      any page, at any moment.      """        _PARTIALS = "__partials"        __partials: t.Dict[str, Partial] = {}        def __init__(self, route: t.Optional[str] = None):          super().__init__()          if route is None:              self._route = f"TaiPy_partials_{len(Partial.__partials)}"              Partial.__partials[self._route] = self          else:              self._route = route        def update_content(self, state: State, content: str | "Page"):          """Update partial content.            Arguments:              state (State^): The current user state as received in any callback.              content (str): The new content to use and display.          """          if state and state._gui and callable(state._gui._update_partial):              state._gui._update_partial(self.__copy(content))          else:              _warn("'Partial.update_content()' must be called in the context of a callback.")        def __copy(self, content: str | "Page") -> Partial:          new_partial = Partial(self._route)          from .page import Page            if isinstance(content, Page):              new_partial._renderer = content          else:              new_partial._renderer = type(self._renderer)(content=content) if self._renderer is not None else None          return new_partial


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": "",              "const": "",              "help": "Specify server port",          },          ("--host", "-H"): {              "dest": "taipy_host",              "metavar": "HOST",              "nargs": "?",              "default": "",              "const": "",              "help": "Specify server host",          },          ("--ngrok-token",): {              "dest": "taipy_ngrok_token",              "metavar": "NGROK_TOKEN",              "nargs": "?",              "default": "",              "const": "",              "help": "Specify NGROK Authtoken",          },          ("--webapp-path",): {              "dest": "taipy_webapp_path",              "metavar": "WEBAPP_PATH",              "nargs": "?",              "default": "",              "const": "",              "help": "The path to the web app to be used. The default is the webapp directory under gui in the Taipy GUI package directory.",          },      }        __DEBUG_ARGS: Dict[str, Dict] = {          "--debug": {"dest": "taipy_debug", "help": "Turn on debug", "action": "store_true"},          "--no-debug": {"dest": "taipy_no_debug", "help": "Turn off debug", "action": "store_true"},      }        __RELOADER_ARGS: Dict[str, Dict] = {          "--use-reloader": {"dest": "taipy_use_reloader", "help": "Auto reload on code changes", "action": "store_true"},          "--no-reloader": {"dest": "taipy_no_reloader", "help": "No reload on code changes", "action": "store_true"},      }        @classmethod      def create_parser(cls):          gui_parser = _CLI._add_groupparser("Taipy GUI", "Optional arguments for Taipy GUI service")            for args, arg_dict in cls.__GUI_ARGS.items():              taipy_arg = (args[0], cls.__add_taipy_prefix(args[0]), *args[1:])              gui_parser.add_argument(*taipy_arg, **arg_dict)            debug_group = gui_parser.add_mutually_exclusive_group()          for debug_arg, debug_arg_dict in cls.__DEBUG_ARGS.items():              debug_group.add_argument(debug_arg, cls.__add_taipy_prefix(debug_arg), **debug_arg_dict)            reloader_group = gui_parser.add_mutually_exclusive_group()          for reloader_arg, reloader_arg_dict in cls.__RELOADER_ARGS.items():              reloader_group.add_argument(reloader_arg, cls.__add_taipy_prefix(reloader_arg), **reloader_arg_dict)        @classmethod      def create_run_parser(cls):          run_parser = _CLI._add_subparser("run", help="Run a Taipy application.")          for args, arg_dict in cls.__GUI_ARGS.items():              run_parser.add_argument(*args, **arg_dict)            debug_group = run_parser.add_mutually_exclusive_group()          for debug_arg, debug_arg_dict in cls.__DEBUG_ARGS.items():              debug_group.add_argument(debug_arg, **debug_arg_dict)            reloader_group = run_parser.add_mutually_exclusive_group()          for reloader_arg, reloader_arg_dict in cls.__RELOADER_ARGS.items():              reloader_group.add_argument(reloader_arg, **reloader_arg_dict)        @classmethod      def parse_arguments(cls):          return _CLI._parse()        @classmethod      def __add_taipy_prefix(cls, key: str):          if key.startswith("--no-"):              return key[:5] + "taipy-" + key[5:]            return key[:2] + "taipy-" + key[2:]


from ..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=None):          self._dict = dict_import          # Bind app update var function          self._update_var = app_update_var        def __len__(self):          return self._dict.__len__()        def __length_hint__(self):          return self._dict.__length_hint__()        def __getitem__(self, key):          value = self._dict.__getitem__(key)          if isinstance(value, dict):              if self._update_var:                  return _MapDict(value, lambda s, v: self._update_var(f"{key}.{s}", v))              else:                  return _MapDict(value)          return value        def __setitem__(self, key, value):          if self._update_var:              self._update_var(key, value)          else:              self._dict.__setitem__(key, value)        def __delitem__(self, key):          self._dict.__delitem__(key)        def __missing__(self, key):          return self._dict.__missing__(key)        def __iter__(self):          return self._dict.__iter__()        def __reversed__(self):          return self._dict.__reversed__()        def __contains__(self, item):          return self._dict.__contains__(item)        # to be able to use getattr      def __getattr__(self, attr):          value = self._dict.__getitem__(attr)          if isinstance(value, dict):              if self._update_var:                  return _MapDict(value, lambda s, v: self._update_var(f"{attr}.{s}", v))              else:                  return _MapDict(value)          return value        def __setattr__(self, attr, value):          if attr in _MapDict.__local_vars:              super().__setattr__(attr, value)          else:              self.__setitem__(attr, value)        def keys(self):          return self._dict.keys()        def values(self):          return self._dict.values()        def items(self):          return self._dict.items()        def get(self, key: t.Any, default_value: t.Optional[str] = None) -> t.Optional[t.Any]:          return self._dict.get(key, default_value)        def clear(self) -> None:          self._dict.clear()        def setdefault(self, key, value=None) -> t.Optional[t.Any]:          return self._dict.setdefault(key, value)        def pop(self, key, default=None) -> t.Any:          return self._dict.pop(key, default)        def popitem(self) -> tuple:          return self._dict.popitem()        def copy(self) -> _MapDict:          return _MapDict(self._dict.copy(), self._update_var)        def update(self, d: dict) -> None:          current_keys = self.keys()          for k, v in d.items():              if k not in current_keys or self[k] != v:                  self.__setitem__(k, v)


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_gui:              self.__port_gui[port].stop()          self.__port_gui[port] = gui        def get_used_port(self):          return list(self.__port_gui.keys())


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) -> str:      module_list = sys.modules.copy()      # the provided sub_module_name are expected to contain only part of the full module_name provided by sys.modules      # --> we can find potential matched modules based on the sub_module_name      potential_matched_module = [m for m in module_list.keys() if m.endswith(sub_module_name)]      for m in potential_matched_module:          module = module_list[m]          if hasattr(module, var_name) and getattr(module, var_name) is value:              return m      # failed fetching any matched module with variable and value      return sub_module_name


# flake8: noqa: E402  import contextlib  import typing as t  import warnings  from threading import Thread  from urllib.parse import quote as urlquote  from urllib.parse import urlparse    warnings.filterwarnings(      "ignore",      category=UserWarning,      message="You do not have a working installation of the service_identity module: 'No module named 'service_identity''.*",  )  from twisted.internet import reactor  from twisted.web.proxy import ProxyClient, ProxyClientFactory  from twisted.web.resource import Resource  from twisted.web.server import NOT_DONE_YET, Site    from .is_port_open import _is_port_open  from .singleton import _Singleton    if t.TYPE_CHECKING:      from ..gui import Gui      def _modifiedHandleResponseEnd(self):      if self._finished:          return      self._finished = True      with contextlib.suppress(Exception):          self.father.finish()      self.transport.loseConnection()      setattr(ProxyClient, "handleResponseEnd", _modifiedHandleResponseEnd)      class _TaipyReverseProxyResource(Resource):      proxyClientFactoryClass = ProxyClientFactory        def __init__(self, host, path, gui: "Gui", reactor=reactor):          Resource.__init__(self)          self.host = host          self.path = path          self.reactor = reactor          self._gui = gui        def getChild(self, path, request):          return _TaipyReverseProxyResource(              self.host,              self.path + b"/" + urlquote(path, safe=b"").encode("utf-8"),              self._gui,              self.reactor,          )        def _get_port(self):          return self._gui._server._port        def render(self, request):          port = self._get_port()          host = self.host if port == 80 else "%s:%d" % (self.host, port)          request.requestHeaders.setRawHeaders(b"host", [host.encode("ascii")])          request.content.seek(0, 0)          rest = self.path + b"?" + qs if (qs := urlparse(request.uri)[4]) else self.path          clientFactory = self.proxyClientFactoryClass(              request.method,              rest,              request.clientproto,              request.getAllHeaders(),              request.content.read(),              request,          )          self.reactor.connectTCP(self.host, port, clientFactory)          return NOT_DONE_YET      class NotebookProxy(object, metaclass=_Singleton):      def __init__(self, gui: "Gui", listening_port: int) -> None:          self._listening_port = listening_port          self._gui = gui          self._is_running = False        def run(self):          if self._is_running:              return          host = self._gui._get_config("host", "127.0.0.1")          port = self._listening_port          if _is_port_open(host, port):              raise ConnectionError(                  f"Port {port} is already opened on {host}. You have another server application running on the same port."              )          site = Site(_TaipyReverseProxyResource(host, b"", self._gui))          reactor.listenTCP(port, site)          Thread(target=reactor.run, args=(False,)).start()          self._is_running = True        def stop(self):          if not self._is_running:              return          self._is_running = False          reactor.stop()


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(gui: "Gui", name: str) -> t.Any:      return attrgetter(name)(gui._get_data_scope())      def _setscopeattr(gui: "Gui", name: str, value: t.Any):      if gui._is_broadcasting():          for scope in gui._get_all_data_scopes().values():              setattr(scope, name, value)      else:          setattr(gui._get_data_scope(), name, value)      def _setscopeattr_drill(gui: "Gui", name: str, value: t.Any):      if gui._is_broadcasting():          for scope in gui._get_all_data_scopes().values():              _attrsetter(scope, name, value)      else:          _attrsetter(gui._get_data_scope(), name, value)      def _hasscopeattr(gui: "Gui", name: str) -> bool:      return hasattr(gui._get_data_scope(), name)      def _delscopeattr(gui: "Gui", name: str):      delattr(gui._get_data_scope(), name)      def _attrsetter(obj: object, attr_str: str, value: object) -> None:      var_name_split = attr_str.split(sep=".")      for i in range(len(var_name_split) - 1):          sub_name = var_name_split[i]          obj = getattr(obj, sub_name)      setattr(obj, var_name_split[-1], value)


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, t.Dict[str, t.Any]] = {}        def set_default(self, default: t.Dict[str, t.Any], default_module_name: str = "") -> None:          self.__default_module = default_module_name          self._locals_map[self.__default_module] = default        def get_default(self) -> t.Dict[str, t.Any]:          return self._locals_map[self.__default_module]        def get_all_keys(self) -> t.Set[str]:          keys = set()          for v in self._locals_map.values():              for i in v.keys():                  keys.add(i)          return keys        def get_all_context(self):          return self._locals_map.keys()        def add(self, context: t.Optional[str], locals_dict: t.Optional[t.Dict[str, t.Any]]):          if context is not None and locals_dict is not None and context not in self._locals_map:              self._locals_map[context] = locals_dict        @contextlib.contextmanager      def set_locals_context(self, context: t.Optional[str]) -> t.Iterator[None]:          try:              if context in self._locals_map:                  if hasattr(g, _LocalsContext.__ctx_g_name):                      self._lc_stack.append(getattr(g, _LocalsContext.__ctx_g_name))                  setattr(g, _LocalsContext.__ctx_g_name, context)              yield          finally:              if hasattr(g, _LocalsContext.__ctx_g_name):                  if len(self._lc_stack) > 0:                      setattr(g, _LocalsContext.__ctx_g_name, self._lc_stack.pop())                  else:                      delattr(g, _LocalsContext.__ctx_g_name)        def get_locals(self) -> t.Dict[str, t.Any]:          return self.get_default() if (context := self.get_context()) is None else self._locals_map[context]        def get_context(self) -> t.Optional[str]:          return getattr(g, _LocalsContext.__ctx_g_name) if hasattr(g, _LocalsContext.__ctx_g_name) else None        def is_default(self) -> bool:          return self.get_default() == self.get_locals()        def _get_locals_bind_from_context(self, context: t.Optional[str]):          if context is None:              context = self.__default_module          return self._locals_map[context]


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 _variable_decode, _variable_encode, _VariableDirectory  from .boolean import _is_boolean, _is_boolean_true  from .clientvarname import _get_broadcast_var_name, _get_client_var_name, _to_camel_case  from .datatype import _get_data_type  from .date import _date_to_string, _string_to_date  from .expr_var_name import _get_expr_var_name  from .filename import _get_non_existent_file_path  from .filter_locals import _filter_locals  from .get_imported_var import _get_imported_var  from .get_module_name import _get_module_name_from_frame, _get_module_name_from_imported_var  from .get_page_from_module import _get_page_from_module  from .getdatecolstrname import _RE_PD_TYPE, _get_date_col_str_name  from .html import _get_css_var_value  from .is_debugging import is_debugging  from .is_port_open import _is_port_open  from .isnotebook import _is_in_notebook  from .types import (      _TaipyBase,      _TaipyBool,      _TaipyContent,      _TaipyContentHtml,      _TaipyContentImage,      _TaipyData,      _TaipyDate,      _TaipyDateRange,      _TaipyDict,      _TaipyLoNumbers,      _TaipyLov,      _TaipyLovValue,      _TaipyNumber,  )  from .varnamefromcontent import _varname_from_content


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_index[var_name]      __expr_var_name_index[var_name] = index + 1      return f"tp_{var_name}_{index}"      def _reset_expr_var_name():      __expr_var_name_index.clear()


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 __init__(self, data: t.Any, hash_name: str) -> None:          self.__data = data          self.__hash_name = hash_name        def get(self):          return self.__data        def get_name(self):          return self.__hash_name        def set(self, data: t.Any):          self.__data = data        def cast_value(self, value: t.Any):          return value        def _get_readable_name(self):          try:              name, mod = _variable_decode(                  self.__hash_name[5:] if self.__hash_name.startswith("tpec_") else self.__hash_name              )              return name if mod is None or mod == "__main__" else f"{mod}.{name}"          except:              return self.__hash_name        @staticmethod      def get_hash():          return NotImplementedError        @staticmethod      def _get_holder_prefixes() -> t.List[str]:          if _TaipyBase.__HOLDER_PREFIXES is None:              _TaipyBase.__HOLDER_PREFIXES = [cls.get_hash() + "_" for cls in _TaipyBase.__subclasses__()]          return _TaipyBase.__HOLDER_PREFIXES      class _TaipyData(_TaipyBase):      @staticmethod      def get_hash():          return _TaipyBase._HOLDER_PREFIX + "D"      class _TaipyBool(_TaipyBase):      def get(self):          return self.cast_value(super().get())        def cast_value(self, value: t.Any):          return bool(value)        @staticmethod      def get_hash():          return _TaipyBase._HOLDER_PREFIX + "B"      class _TaipyNumber(_TaipyBase):      def get(self):          try:              return float(super().get())          except Exception as e:              raise TypeError(f"Variable '{self._get_readable_name()}' should hold a number: {e}")        def cast_value(self, value: t.Any):          if isinstance(value, str):              try:                  return float(value) if value else 0.0              except Exception as e:                  _warn(f"{self._get_readable_name()}: Parsing {value} as float", e)                  return 0.0          return super().cast_value(value)        @staticmethod      def get_hash():          return _TaipyBase._HOLDER_PREFIX + "N"      class _TaipyLoNumbers(_TaipyBase):      def cast_value(self, value: t.Any):          if isinstance(value, str):              try:                  return list(map(lambda f: float(f), value[1:-1].split(",")))              except Exception as e:                  _warn(f"{self._get_readable_name()}: Parsing {value} as an array of numbers", e)                  return []          return super().cast_value(value)        @staticmethod      def get_hash():          return _TaipyBase._HOLDER_PREFIX + "Ln"      class _TaipyDate(_TaipyBase):      def get(self):          val = super().get()          if isinstance(val, datetime):              val = _date_to_string(val)          elif val is not None:              val = str(val)          return val        def cast_value(self, value: t.Any):          if isinstance(value, str):              return _string_to_date(value)          return super().cast_value(value)        @staticmethod      def get_hash():          return _TaipyBase._HOLDER_PREFIX + "Dt"      class _TaipyDateRange(_TaipyBase):      def get(self):          val = super().get()          if isinstance(val, list):              return [_date_to_string(v) if isinstance(v, datetime) else None if v is None else str(v) for v in val]          return val        def cast_value(self, value: t.Any):          if isinstance(value, list):              return [_string_to_date(v) if isinstance(v, str) else str(v) for v in value]          return super().cast_value(value)        @staticmethod      def get_hash():          return _TaipyBase._HOLDER_PREFIX + "Dr"      class _TaipyLovValue(_TaipyBase):      @staticmethod      def get_hash():          return _TaipyBase._HOLDER_PREFIX + "Lv"      class _TaipyLov(_TaipyBase):      @staticmethod      def get_hash():          return _TaipyBase._HOLDER_PREFIX + "L"      class _TaipyContent(_TaipyBase):      @staticmethod      def get_hash():          return _TaipyBase._HOLDER_PREFIX + "C"      class _TaipyContentImage(_TaipyBase):      @staticmethod      def get_hash():          return _TaipyBase._HOLDER_PREFIX + "Ci"      class _TaipyContentHtml(_TaipyBase):      @staticmethod      def get_hash():          return _TaipyBase._HOLDER_PREFIX + "Ch"      class _TaipyDict(_TaipyBase):      def get(self):          val = super().get()          return json.dumps(val._dict if isinstance(val, _MapDict) else val)        @staticmethod      def get_hash():          return _TaipyBase._HOLDER_PREFIX + "Di"


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 isinstance(s, bool):          return True      elif isinstance(s, str):          return s.lower() in ["true", "1", "t", "y", "yes", "yeah", "sure", "false", "0", "f", "no"]      else:          return False


_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):          raise Exception("_to_camel_case allows only string parameter")        if len(value) <= 1:          return value.lower()      value = value.replace("_", " ").title().replace(" ", "").replace("[", "_").replace("]", "_")      return value[0].lower() + value[1:] if not upcase_first else value      def _get_broadcast_var_name(s: str) -> str:      return _get_client_var_name(f"_bc_{s}")