Instruction:
rx.var
    def remaining_budget_percentage(self) -> float:
        """Calculates the remaining budget percentage."""
        if self.total_budget == 0:
            return 0.0
        percentage = self.remaining_budget_value / self.total_budget * 100
        return round(percentage * 10) / 10

    @rx.var
    def total_cost_percentage(self) -> float:
        """Calculates the total percentage used based on cost items."""
        return sum((item["percentage"] for item in self.billing_costs_items))

    @rx.var
    def visible_overview_metrics(
        self,
    ) -> List[OverviewMetric]:
        """Returns the list of overview metrics that are marked as visible."""
        return [
            metric
            for metric in self.overview_metrics
            if self.chart_visibility.get(metric["id"], False)
        ]

    @rx.event
    def set_active_nav(self, item_name: str):
        new_nav_items = []
        for item in self.nav_items:
            new_item = item.copy()

Input:
            new_nav_items.append(new_item)
        self.nav_items = new_nav_items

    @rx.event
    def toggle_customize_dialog(self):
        """Toggles the customize charts dialog and initializes temporary visibility."""
        self.show_customize_dialog = not self.show_customize_dialog
        if self.show_customize_dialog:
            self.temp_chart_visibility = self.chart_visibility.copy()

    @rx.event
    def toggle_temp_chart_visibility(self, chart_id: str):
        """Toggles the visibility of a specific chart in the temporary state."""
        if chart_id in self.temp_chart_visibility:
            self.temp_chart_visibility[chart_id] = not self.temp_chart_visibility[
                chart_id
            ]

    @rx.event
    def apply_chart_visibility(self):
        """Applies the temporary visibility settings to the actual state and closes the dialog."""
        self.chart_visibility = self.temp_chart_visibility.copy()
        self.show_customize_dialog = False

    @rx.

Output: new_item["active"] = item["name"] == item_name


Instruction:
 self.nav_items:
            new_item = item.copy()
            new_item["active"] = item["name"] == item_name
            new_nav_items.append(new_item)
        self.nav_items = new_nav_items

    @rx.event
    def toggle_customize_dialog(self):
        """Toggles the customize charts dialog and initializes temporary visibility."""
        self.show_customize_dialog = not self.show_customize_dialog
        if self.show_customize_dialog:
            self.temp_chart_visibility = self.chart_visibility.copy()

    @rx.event
    def toggle_temp_chart_visibility(self, chart_id: str):
        """Toggles the visibility of a specific chart in the temporary state."""
        if chart_id in self.temp_chart_visibility:
            self.temp_chart_visibility[chart_id] = not self.temp_chart_visibility[
                chart_id
            ]

    @rx.event
    def apply_chart_visibility(self):
        """Applies the temporary visibility settings to the actual state and closes the dialog."""

Input:
        self.show_customize_dialog = False

    @rx.event
    def cancel_chart_visibility(self):
        """Closes the dialog without applying changes."""
        self.show_customize_dialog = False

Output: self.chart_visibility = self.temp_chart_visibility.copy()


Instruction:
em["costs"]
        except ValueError:
            return None

    @rx.var
    def total_entries_count(self) -> int:
        """Total number of entries in the raw data."""
        return len(self._data)

    @rx.var
    def live_entries_count(self) -> int:
        """Count of 'Live' entries."""
        return sum((1 for item in self._data if item["status"] == "Live"))

    @rx.var
    def inactive_entries_count(self) -> int:
        """Count of 'Inactive' entries."""
        return sum((1 for item in self._data if item["status"] == "Inactive"))

    @rx.var
    def archived_entries_count(self) -> int:
        """Count of 'Archived' entries."""
        return sum((1 for item in self._data if item["status"] == "Archived"))

    @rx.var
    def costs_trend_data(
        self,
    ) -> List[Dict[str, str | float]]:
        """Data for the costs trend line chart."""
        daily_costs = defaultdict(float)

        input_format = "%d/%m/%Y %H:%M"
        output_format = "%Y-%m-%d"

Input:
        valid_items = []
        for item in self._data:
            parsed_item = self._parse_datetime_for_costs(item, input_format)
            if parsed_item:
                valid_items.append(parsed_item)

        for dt_obj, cost in valid_items:
            date_str = dt_obj.strftime(output_format)
            daily_costs[date_str] += cost

        sorted_dates = sorted(daily_costs.keys())
        chart_data: List[Dict[str, str | float]] = [
            {
                "date": datetime.datetime.strptime(date_str, output_format).strftime(
                    display_format
                ),
                "total_costs": round(daily_costs[date_str], 2),
            }
            for date_str in sorted_dates
        ]
        return chart_data

    @rx.var
    def recent_activities(self) -> List[DetailEntry]:
        """Get the 5 most recent activities based on last_edited date."""
        # Precompute sort keys to move try-except out of the sorting process itself
        item

Output: display_format = "%b %d"


Input:
import reflex as rx

class ChartData(TypedDict):
    name: str
    value: int
    percentage: float
    fill: str

class WorkflowState(rx.State):
    """State for the Workflow tab."""

    test_quota: int = 34
    departments: List[str] = [
        "Customer Service",
        "Technical Support",
        "Billing Support",
        "Claims Processing",
        "Account Management",
        "Sales Support",
    ]
    excluded_departments: Dict[str, bool] = {dept: False for dept in departments}
    completed_cases_data: list[ChartData] = [
        {
            "name": "Completed",
            "value": 11327,
            "percentage": 100.0,
            "fill": "#3b82f6",
        }
    ]
    test_results_data_tested: list[ChartData] = [
        {
            "name": "Tested",
            "value": 3874,
            "percentage": 34.2,
            "fill": "#3b82f6",
        }
    ]
    test_results_data_untested: list[ChartData] = [
        {
            "name": "Untested",

Output: from typing import Dict, List, TypedDict


Instruction:
": 11327,
            "percentage": 100.0,
            "fill": "#3b82f6",
        }
    ]
    test_results_data_tested: list[ChartData] = [
        {
            "name": "Tested",
            "value": 3874,
            "percentage": 34.2,
            "fill": "#3b82f6",
        }
    ]
    test_results_data_untested: list[ChartData] = [
        {
            "name": "Untested",
            "value": 7453,
            "percentage": 65.8,
            "fill": "#d1d5db",
        }
    ]
    impact_data_error_free: list[ChartData] = [
        {
            "name": "Error-free",
            "value": 3413,
            "percentage": 30.1,
            "fill": "#10b981",
        }
    ]
    impact_data_corrected: list[ChartData] = [
        {
            "name": "Corrected",
            "value": 461,
            "percentage": 4.1,
            "fill": "#ef4444",
        }
    ]

    @rx.event
    def set_test_quota(self, value: str):
        """Sets the test quota value from the slider."""

Input:
    @rx.event
    def toggle_department(self, dept_name: str):
        """Toggles the exclusion status of a department."""
        self.excluded_departments[dept_name] = not self.excluded_departments[dept_name]

Output: self.test_quota = int(value)


Input:
from space_dashboard.components.section_wrapper import section_wrapper
from space_dashboard.states.dashboard_state import (
    ComData,
    DashboardState,
)

def hq_com_item(data: ComData) -> rx.Component:
    """Displays a single HQ Coms channel."""
    return rx.el.div(
        rx.el.p(
            f"{data['channel']} [{data['value'].to_string()}]",
            class_name="text-sm text-cyan-300 font-mono",
        ),
        class_name="p-1",
    )

def hq_coms_section() -> rx.Component:
    """The HQ Communications section."""
    return section_wrapper(
        "HQ_COMS",
        rx.el.div(
            rx.foreach(DashboardState.hq_coms_data, hq_com_item),
            class_name="grid grid-cols-2 gap-x-4 gap-y-1",
        ),
    )

Output: import reflex as rx


Instruction:
n " · ".join(filter(None, display_parts))

    @rx.var
    def current_price_display_val(self) -> str:
        price = self.company_info.get("currentPrice") or self.company_info.get(
            "regularMarketPrice"
        )
        if price is not None:
            return f"{price:.2f}"
        return "N/A"

    @rx.var
    def market_cap_display_val(self) -> str:
        return format_market_cap(self.company_info.get("marketCap"))

    @rx.var
    def is_market_currently_active(self) -> bool:
        """Determines if the market is currently in an active trading session (regular, pre, or post)."""
        market_state = self.company_info.get("marketState", "").upper()
        # Active states include regular market, pre-market, and post-market trading
        active_states = ["REGULAR", "PRE", "POST", "POSTPOST"]
        return market_state in active_states

    @rx.var
    def _after_hours_data(self) -> tuple[float | None, float | None, str]:
        info = self.company_info

Input:
        if market_state == "PRE":
            price = info.get("preMarketPrice")
            change = info.get("preMarketChange")
            if price is not None and change is not None:
                return price, change, "Pre-Market"
        elif market_state in ["POST", "POSTPOST", "CLOSED"]:
            price = info.get("postMarketPrice")
            change = info.get("postMarketChange")
            if price is not None and change is not None:
                return price, change, "After Hours"

        return None, None, ""

    @rx.var
    def after_hours_price_display_val(self) -> str:
        price, _, _ = self._after_hours_data
        if price is not None:
            return f"{price:.2f}"
        return ""

    @rx.var
    def after_hours_change_display_val(self) -> str:
        _, change, _ = self._after_hours_data
        if change is not None:
            sign = "+" if change > 0 else ""
            return f"{sign}{change:.2f}"
        return ""

    @rx.var
    def a

Output: market_state = info.get("marketState")


Instruction:
trading_state import TradingState

def options_header(
    stock_symbol: str,
    price: rx.Var[float],
    change: rx.Var[float],
    change_percent: rx.Var[float],
) -> rx.Component:
    return rx.el.div(
        rx.el.span(
            f"{stock_symbol}",
            class_name="text-sm font-bold text-white mr-2",
        ),
        rx.el.span(
            price.to_string(),
            class_name="text-sm font-semibold text-white mr-1",
        ),
        rx.el.span(
            change.to_string(),
            class_name=rx.cond(
                change >= 0,
                "text-green-400 text-xs",
                "text-red-400 text-xs",
            ),
        ),
        rx.el.span(
            change_percent.to_string(),
            class_name=rx.cond(
                change >= 0,
                "text-green-400 text-xs ml-1",
                "text-red-400 text-xs ml-1",
            ),
        ),
        class_name="mb-2 px-2",
    )

def options_sub_tabs() -> rx.Component:

Input:
    return rx.el.div(
        rx.foreach(
            tabs,
            lambda tab: rx.el.button(
                tab,
                on_click=TradingState.set_active_sub_tab(tab),
                class_name=rx.cond(
                    TradingState.active_sub_tab == tab,
                    "text-xs text-white bg-gray-700 px-3 py-1 rounded",
                    "text-xs text-gray-400 hover:text-white px-3 py-1",
                ),
            ),
        ),
        class_name="flex space-x-2 border-b border-gray-700 mb-2 pb-1 px-2 overflow-x-auto",
    )

def render_option_cell(
    value: rx.Var,
    class_name: str,
    is_numeric: bool = True,
    format_spec: str = ".2f",
    prefix: str = "",
    suffix: str = "",
) -> rx.Component:
    formatted_value = rx.cond(value, value.to_string(), "-")
    return rx.el.td(formatted_value, class_name=class_name)

def render_combined_option_row(
    item: rx.Var[dict[str, dict[str, int]]],
) -> rx.Component:
    call_option = item["call"]

Output:
tabs = [
        "4D Fri Oct 18",
        "11D Fri Oct 25",
        "18D Fri Nov 1",
        "25D Fri Nov 8",
        "32D Fri Nov 15",
    ]


Instruction:
        ]
            ),
        ),
        rx.el.td(
            strike.to_string(),
            class_name=rx.cond(
                is_near_the_money,
                "px-3 py-1 text-xs text-center font-bold text-white bg-yellow-700",
                "px-3 py-1 text-xs text-center font-bold text-white bg-gray-600",
            ),
        ),
        rx.cond(
            put_option,
            rx.fragment(
                *[
                    render_option_cell(put_option[key], cn, *fmt)
                    for key, cn, *fmt in put_headers_config
                ]
            ),
            rx.fragment(
                *[
                    rx.el.td(
                        "-",
                        class_name="px-2 py-1 text-xs text-gray-500 text-left",
                    )
                    for _ in put_headers_config
                ]
            ),
        ),
        class_name="border-b border-gray-700 hover:bg-gray-700",
    )

def options_table() -> rx.Component:

Input:
    put_headers = [
        "Bid",
        "Ask",
        "Delta",
        "OI",
        "Volume",
        "IV",
        "Change % to",
        "Mark",
        "Gamma",
    ]
    return rx.el.div(
        options_header(
            TradingState.stock_info["symbol"],
            TradingState.stock_info["price"],
            TradingState.stock_info["change"],
            TradingState.stock_info["change_percent"],
        ),
        options_sub_tabs(),
        rx.el.div(
            rx.el.table(
                rx.el.thead(
                    rx.el.tr(
                        rx.el.th(
                            "Calls",
                            col_span=len(call_headers),
                            class_name="text-sm font-semibold text-white pb-2 text-center border-b-2 border-green-500 sticky top-0 bg-gray-800 z-20",
                        ),
                        rx.el.th(
                            "Strike",
                            class_name="text-sm font-semibold tex

Output:
call_headers = [
        "Mark",
        "% to",
        "Delta",
        "OI",
        "Volume",
        "IV",
        "Low",
        "High",
        "Bid",
        "Ask",
    ]


Input:
from table_dashboard.components.details_table import details_table
from table_dashboard.components.header import header
from table_dashboard.components.sidebar import sidebar
from table_dashboard.states.dashboard_state import DashboardState

def index() -> rx.Component:
    """The main dashboard page."""
    return rx.el.div(
        sidebar(),
        rx.el.main(
            rx.el.div(
                header(),
                details_table(),
                class_name="p-6 space-y-6",
            ),
            class_name="flex-1 overflow-y-auto",
        ),
        rx.el.div(
            class_name=rx.cond(
                DashboardState.show_status_filter
                | DashboardState.show_region_filter
                | DashboardState.show_costs_filter,
                "fixed inset-0 z-5",
                "hidden",
            ),
            on_click=DashboardState.close_filter_dropdowns,
        ),
        class_name="flex h-screen",
    )

app = rx.App(theme=rx.theme(app

Output: import reflex as rx


Instruction: import reflex as rx

Input:
def status_badge(status: rx.Var[str]) -> rx.Component:
    """Creates a colored status badge."""
    return rx.el.span(
        status,
        class_name=rx.match(
            status,
            (
                "Live",
                "px-2 py-0.5 rounded-full text-xs font-medium bg-green-100 text-green-800",
            ),
            (
                "Inactive",
                "px-2 py-0.5 rounded-full text-xs font-medium bg-yellow-100 text-yellow-800",
            ),
            (
                "Archived",
                "px-2 py-0.5 rounded-full text-xs font-medium bg-gray-100 text-gray-800",
            ),
            "px-2 py-0.5 rounded-full text-xs font-medium bg-gray-100 text-gray-800",
        ),
    )

def table_header_cell(name: str, is_sortable: bool = True) -> rx.Component:
    """Creates a table header cell with optional sorting."""
    return rx.el.th(
        rx.el.div(
            name,
            rx.cond(
                is_sortable,
                rx.

Output:
from table_dashboard.states.dashboard_state import (
    DashboardState,
)


Instruction:
ar
    def page_item_ids(self) -> Set[int]:
        """Get the set of IDs for items on the current page."""
        return {item["id"] for item in self.paginated_data}

    @rx.var
    def all_rows_on_page_selected(self) -> bool:
        """Check if all rows on the current page are selected."""
        if not self.paginated_data:
            return False
        return self.page_item_ids.issubset(self.selected_rows)

    @rx.event
    def set_search_owner(self, value: str):
        """Update the search owner filter."""
        self.search_owner = value
        self.current_page = 1

    @rx.event
    def toggle_sort(self, column_name: str):
        """Toggle sorting for a column."""
        if self.sort_column == column_name:
            self.sort_ascending = not self.sort_ascending
        else:
            self.sort_column = column_name
            self.sort_ascending = True

    @rx.event
    def go_to_page(self, page_number: int):
        """Navigate to a specific page."""

Input:
    @rx.event
    def next_page(self):
        """Go to the next page."""
        if self.current_page < self.total_pages:
            self.current_page += 1

    @rx.event
    def previous_page(self):
        """Go to the previous page."""
        if self.current_page > 1:
            self.current_page -= 1

    @rx.event
    def toggle_row_selection(self, row_id: int):
        """Toggle selection state for a single row using its ID."""
        if row_id in self.selected_rows:
            self.selected_rows.remove(row_id)
        else:
            self.selected_rows.add(row_id)

    @rx.event
    def toggle_select_all_on_page(self):
        """Select or deselect all rows on the current page."""
        page_ids = self.page_item_ids
        if self.all_rows_on_page_selected:
            self.selected_rows -= page_ids
        else:
            self.selected_rows.update(page_ids)

    @rx.event
    def toggle_status_filter(self):
        is_opening = not self.show_status_filter

Output:
if 1 <= page_number <= self.total_pages:
            self.current_page = page_number


Instruction:
 > 1:
            self.current_page -= 1

    @rx.event
    def toggle_row_selection(self, row_id: int):
        """Toggle selection state for a single row using its ID."""
        if row_id in self.selected_rows:
            self.selected_rows.remove(row_id)
        else:
            self.selected_rows.add(row_id)

    @rx.event
    def toggle_select_all_on_page(self):
        """Select or deselect all rows on the current page."""
        page_ids = self.page_item_ids
        if self.all_rows_on_page_selected:
            self.selected_rows -= page_ids
        else:
            self.selected_rows.update(page_ids)

    @rx.event
    def toggle_status_filter(self):
        is_opening = not self.show_status_filter
        self.show_status_filter = is_opening
        self.show_region_filter = False
        self.show_costs_filter = False
        if is_opening:
            self.temp_selected_statuses = self.selected_statuses.copy()

    @rx.event
    def toggle_region_filter(self):

Input:
        self.show_region_filter = is_opening
        self.show_status_filter = False
        self.show_costs_filter = False
        if is_opening:
            self.temp_selected_regions = self.selected_regions.copy()

    @rx.event
    def toggle_costs_filter(self):
        is_opening = not self.show_costs_filter
        self.show_costs_filter = is_opening
        self.show_status_filter = False
        self.show_region_filter = False
        if is_opening:
            self.temp_min_cost_str = (
                str(self.min_cost) if self.min_cost is not None else ""
            )
            self.temp_max_cost_str = (
                str(self.max_cost) if self.max_cost is not None else ""
            )

    @rx.event
    def toggle_temp_status(self, status: str):
        if status in self.temp_selected_statuses:
            self.temp_selected_statuses.remove(status)
        else:
            self.temp_selected_statuses.add(status)

    @rx.event
    def toggle_temp_region(self, region

Output: is_opening = not self.show_region_filter


Instruction:
    @rx.event
    def toggle_select_all_on_page(self):
        """Select or deselect all rows on the current page."""
        page_ids = self.page_item_ids
        if self.all_rows_on_page_selected:
            self.selected_rows -= page_ids
        else:
            self.selected_rows.update(page_ids)

    @rx.event
    def toggle_status_filter(self):
        is_opening = not self.show_status_filter
        self.show_status_filter = is_opening
        self.show_region_filter = False
        self.show_costs_filter = False
        if is_opening:
            self.temp_selected_statuses = self.selected_statuses.copy()

    @rx.event
    def toggle_region_filter(self):
        is_opening = not self.show_region_filter
        self.show_region_filter = is_opening
        self.show_status_filter = False
        self.show_costs_filter = False
        if is_opening:
            self.temp_selected_regions = self.selected_regions.copy()

    @rx.event
    def toggle_costs_filter(self):

Input:
        self.show_costs_filter = is_opening
        self.show_status_filter = False
        self.show_region_filter = False
        if is_opening:
            self.temp_min_cost_str = (
                str(self.min_cost) if self.min_cost is not None else ""
            )
            self.temp_max_cost_str = (
                str(self.max_cost) if self.max_cost is not None else ""
            )

    @rx.event
    def toggle_temp_status(self, status: str):
        if status in self.temp_selected_statuses:
            self.temp_selected_statuses.remove(status)
        else:
            self.temp_selected_statuses.add(status)

    @rx.event
    def toggle_temp_region(self, region: str):
        if region in self.temp_selected_regions:
            self.temp_selected_regions.remove(region)
        else:
            self.temp_selected_regions.add(region)

    @rx.event
    def set_temp_min_cost(self, value: str):
        self.temp_min_cost_str = value

    @rx.event
    def set_temp_max_cost

Output: is_opening = not self.show_costs_filter


Instruction:
               ),
                    class_name="flex flex-wrap gap-2 p-4 items-center",
                ),
            )
        ),
        add_label_form(),
        class_name="bg-gray-100 border-b border-gray-300 rounded-t-lg shadow-sm sticky top-0 z-10",
    )

def render_segment(segment: Segment) -> rx.Component:
    """Renders a single text segment, making it clickable if a label is selected."""
    is_label_selected = NerState.selected_label_name is not None
    is_whitespace = segment["text"].strip() == ""
    base_component = rx.el.span(segment["text"])
    labeled_class = (
        segment["bg_color"]
        + " "
        + segment["text_color"]
        + " py-0.5 rounded-sm cursor-pointer"
    )
    labeled_component = rx.el.span(
        segment["text"],
        rx.el.span(
            segment["label_name"],
            class_name="text-[0.6rem] font-bold opacity-70 align-super",
        ),
        class_name=labeled_class,
        title=segment["label_name"],
    )

Input:
    styled_component = rx.cond(
        segment["label_name"] is not None,
        labeled_component,
        rx.cond(
            is_label_selected & ~is_whitespace,
            hoverable_component,
            base_component,
        ),
    )
    on_click_event = rx.cond(
        is_label_selected & ~is_whitespace,
        NerState.apply_label(segment["id"]),
        rx.noop(),
    )
    clickable_component = rx.el.span(
        styled_component,
        on_click=on_click_event,
        class_name=rx.cond(segment["label_name"] is not None, "", "inline"),
    )
    return clickable_component

def text_display() -> rx.Component:
    """Displays the processed text with highlighted entities."""
    return rx.el.div(
        rx.el.p(
            rx.foreach(NerState.display_segments, render_segment),
            class_name="text-lg text-gray-800 whitespace-pre-wrap",
        ),
        class_name="p-6 bg-white border border-gray-300 border-t-0 rounded-b-lg shadow-inner",
    )

def ner_

Output:
hoverable_component = rx.el.span(
        segment["text"],
        class_name="hover:bg-gray-200 rounded-sm cursor-pointer transition-colors",
    )


Instruction:
h = False
                            break
                        if (
                            initial_segments[current_seg_idx]["text"]
                            != keyword_words[current_kw_idx]
                        ):
                            match = False
                            break
                        temp_indices.append(current_seg_idx)
                        current_kw_idx += 1
                        current_seg_idx += 1
                    if match:
                        applied_label = False
                        can_apply = all(
                            (
                                initial_segments[idx]["label_name"] is None
                                for idx in temp_indices
                            )
                        )
                        if can_apply:
                            for idx in temp_indices:
                                initial_segments[idx]["label_name"] = entity["name"]

Input:
                                initial_segments[idx]["text_color"] = entity[
                                    "text_color"
                                ]
                            applied_label = True
                        if applied_label:
                            i = temp_indices[-1] + 1
                        else:
                            next_word_idx = i + 1
                            while next_word_idx < len(initial_segments) and (
                                not initial_segments[next_word_idx]["text"].strip()
                            ):
                                next_word_idx += 1
                            i = next_word_idx
                    else:
                        next_word_idx = i + 1
                        while next_word_idx < len(initial_segments) and (
                            not initial_segments[next_word_idx]["text"].strip()
                        ):
                            next_word_idx += 1

Output: initial_segments[idx]["bg_color"] = entity["color"]


Instruction:
    @rx.event
    def select_label(self, label_name: Optional[str]):
        """Selects a label to apply or deselects if the same label is clicked again."""
        if self.selected_label_name == label_name:
            self.selected_label_name = None
        else:
            self.selected_label_name = label_name

    @rx.event
    def apply_label(self, segment_id: int):
        """Applies the selected label to the clicked segment or removes it."""
        if self.selected_label_name is None:
            return rx.toast("Select a label first!", duration=2000)
        target_segment_index = -1
        for i, seg in enumerate(self.display_segments):
            if seg["id"] == segment_id:
                target_segment_index = i
                break
        if target_segment_index == -1:
            return rx.toast("Segment not found.", duration=2000)
        if not self.display_segments[target_segment_index]["text"].strip():
            return
        selected_entity = None

Input:
        if selected_entity:
            current_label = self.display_segments[target_segment_index]["label_name"]
            if current_label == self.selected_label_name:
                self.display_segments[target_segment_index]["label_name"] = None
                self.display_segments[target_segment_index]["bg_color"] = None
                self.display_segments[target_segment_index]["text_color"] = None
            else:
                self.display_segments[target_segment_index]["label_name"] = (
                    selected_entity["name"]
                )
                self.display_segments[target_segment_index]["bg_color"] = (
                    selected_entity["color"]
                )
                self.display_segments[target_segment_index]["text_color"] = (
                    selected_entity["text_color"]
                )
        else:
            return rx.toast(
                f"Label '{self.selected_label_name}' definition not found.",
                duratio

Output:
for entity in self.entities:
            if entity["name"] == self.selected_label_name:
                selected_entity = entity
                break