element when nested.\"\"\"\n\n tag = \"NavigationMenu.Root\"\n\n # The controlled value of the navigation menu item that should be currently open. When non-nullish, the menu will be open. When nullish, the menu will be closed. To render an uncontrolled navigation menu, use the defaultValue prop instead.\n value: Var[str]\n\n # The uncontrolled value of the item that should be initially selected. To render a controlled navigation menu, use the value prop instead.\n default_value: Var[str]\n\n # Callback fired when the value changes.\n on_value_change: EventHandler[passthrough_event_spec(str, dict)]\n\n # The orientation of the navigation menu.\n orientation: Var[LiteralNavigationMenuOrientation]\n\n # How long to wait before opening the navigation menu. Specified in milliseconds. Defaults to 50.\n delay: Var[int]\n\n # How lo", "output": "def import_var(self):\n \"\"\"Return the import variable for the navigation menu component.\"\"\"\n return ImportVar(tag=\"NavigationMenu\", package_path=\"\", install=False)"}
{"instruction": "\"\"\"Custom popover component.\"\"\"\n\nfrom typing import Literal\n\nfrom reflex.components.component import Component, ComponentNamespace\nfrom reflex.event import EventHandler, passthrough_event_spec\nfrom reflex.utils.imports import ImportVar\nfrom reflex.vars.base import Var\n\nfrom reflex_ui.components.base_ui import PACKAGE_NAME, BaseUIComponent\nfrom reflex_ui.utils.twmerge import cn\n\nLiteralAlign = Literal[\"start\", \"center\", \"end\"]\n", "input": "\nLiteralPosition = Literal[\"absolute\", \"fixed\"]\n\n\nclass ClassNames:\n \"\"\"Class names for popover components.\"\"\"\n\n ROOT = \"\"\n TRIGGER = \"\"\n BACKDROP = \"\"\n PORTAL = \"\"\n POSITIONER = \"\"\n POPUP = \"origin-(--transform-origin) rounded-ui-xl p-1 border border-secondary-a4 bg-secondary-1 shadow-large transition-[transform,scale,opacity] data-[ending-style]:scale-95 data-[starting-style]:scale-95 data-[ending-style]:opacity-0 data-[starting-style]:opacity-0 outline-none min-w-36 flex flex-col gap-2\"\n ARROW = \"data-[side=bottom]:top-[-8px] data-[side=left]:right-[-13px] data-[side=left]:rotate-90 data-[side=right]:left-[-13px] data-[side=right]:-rotate-90 data-[side=top]:bottom-[-8px] data-[side=top]:rotate-180\"\n TITLE = \"text-lg font-semibold text-secondary-12\"\n DESCRIPTION = \"text-sm text-secondary-11 font-[450]\"\n CLOSE = \"\"\n\n\nclass PopoverBaseComponent(BaseUIComponent):\n \"\"\"Base component for popover components.\"\"\"\n\n library = f\"{PACKAGE_NAME}/popover\"\n\n ", "output": "LiteralSide = Literal[\"bottom\", \"inline-end\", \"inline-start\", \"left\", \"right\", \"top\"]"}
{"instruction": "erTitle.create(title) if title is not None else None,\n (\n PopoverDescription.create(description)\n if description is not None\n else None\n ),\n content,\n *children,\n class_name=cn(ClassNames.POPUP, class_name),\n ),\n **positioner_props,\n ),\n **portal_props,\n ),\n **props,\n )\n\n def _exclude_props(self) -> list[str]:\n return [\n *super()._exclude_props(),\n \"trigger\",\n \"content\",\n \"title\",\n \"description\",\n ]\n\n\nclass Popover(ComponentNamespace):\n \"\"\"Namespace for Popover components.\"\"\"\n\n root = staticmethod(PopoverRoot.create)\n trigger = staticmethod(PopoverTrigger.create)\n backdrop = staticmethod(PopoverBackdrop.create)\n ", "input": "\n positioner = staticmethod(PopoverPositioner.create)\n popup = staticmethod(PopoverPopup.create)\n arrow = staticmethod(PopoverArrow.create)\n title = staticmethod(PopoverTitle.create)\n description = staticmethod(PopoverDescription.create)\n close = staticmethod(PopoverClose.create)\n class_names = ClassNames\n __call__ = staticmethod(HighLevelPopover.create)\n\n\npopover = Popover()\n", "output": "portal = staticmethod(PopoverPortal.create)"}
{"instruction": "s_name(ClassNames.VIEWPORT, props)\n return super().create(*children, **props)\n\n\nclass ScrollAreaContent(ScrollAreaBaseComponent):\n \"\"\"A container for the content of the scroll area.\"\"\"\n\n tag = \"ScrollArea.Content\"\n\n # Render prop\n render_: Var[Component]\n\n @classmethod\n def create(cls, *children, **props) -> BaseUIComponent:\n \"\"\"Create the scroll area content component.\"\"\"\n props[\"data-slot\"] = \"scroll-area-content\"\n cls.set_class_name(ClassNames.CONTENT, props)\n return super().create(*children, **props)\n\n\nclass ScrollAreaScrollbar(ScrollAreaBaseComponent):\n \"\"\"The scrollbar of the scroll area.\"\"\"\n\n tag = \"ScrollArea.Scrollbar\"\n\n # Orientation of the scrollbar\n orientation: Var[LiteralOrientation] = Var.create(\"vertical\")\n\n # Whether to keep the HTML element in the DOM when the viewport isn't scrollable\n keep_mounted: Var[bool] = Var.create(False)\n\n # Render prop\n render_: Var[Component]\n\n @classmethod\n ", "input": "\n\n\nclass ScrollAreaThumb(ScrollAreaBaseComponent):\n \"\"\"The thumb of the scrollbar.\"\"\"\n\n tag = \"ScrollArea.Thumb\"\n\n # Render prop\n render_: Var[Component]\n\n @classmethod\n def create(cls, *children, **props) -> BaseUIComponent:\n \"\"\"Create the scroll area thumb component.\"\"\"\n props[\"data-slot\"] = \"scroll-area-thumb\"\n cls.set_class_name(ClassNames.THUMB, props)\n return super().create(*children, **props)\n\n\nclass ScrollAreaCorner(ScrollAreaBaseComponent):\n \"\"\"A small rectangular area that appears at the intersection of horizontal and vertical scrollbars.\"\"\"\n\n tag = \"ScrollArea.Corner\"\n\n # Render prop\n render_: Var[Component]\n\n @classmethod\n def create(cls, *children, **props) -> BaseUIComponent:\n \"\"\"Create the scroll area corner component.\"\"\"\n props[\"data-slot\"] = \"scroll-area-corner\"\n cls.set_class_name(ClassNames.CORNER, props)\n return super().create(*children, **props)\n\n\nclass HighLevelScrollArea(S", "output": "def create(cls, *children, **props) -> BaseUIComponent:\n \"\"\"Create the scroll area scrollbar component.\"\"\"\n props[\"data-slot\"] = \"scroll-area-scrollbar\"\n orientation = props.get(\"orientation\", \"vertical\")\n\n scrollbar_classes = cn(\n ClassNames.SCROLLBAR_BASE,\n cond(\n orientation == \"vertical\",\n ClassNames.SCROLLBAR_VERTICAL,\n ClassNames.SCROLLBAR_HORIZONTAL,\n ),\n )\n\n cls.set_class_name(scrollbar_classes, props)\n return super().create(*children, **props)"}
{"instruction": "ethod\n def create(cls, *children, **props) -> BaseUIComponent:\n \"\"\"Create the dialog trigger component.\"\"\"\n props[\"data-slot\"] = \"select-item-text\"\n cls.set_class_name(ClassNames.ITEM_TEXT, props)\n return super().create(*children, **props)\n\n\nclass SelectItemIndicator(SelectBaseComponent):\n \"\"\"Indicates whether the select item is selected.\"\"\"\n\n tag = \"Select.ItemIndicator\"\n\n # Whether to keep the HTML element in the DOM when the item is not selected. Defaults to False.\n keep_mounted: Var[bool]\n\n # The render prop\n render_: Var[Component]\n\n @classmethod\n def create(cls, *children, **props) -> BaseUIComponent:\n \"\"\"Create the dialog trigger component.\"\"\"\n props[\"data-slot\"] = \"select-item-indicator\"\n cls.set_class_name(ClassNames.ITEM_INDICATOR, props)\n return super().create(*children, **props)\n\n\nclass SelectGroup(SelectBaseComponent):\n \"\"\"Groups related select items with the corresponding label.\"\"\"\n\n ", "input": "\n\n # The render prop\n render_: Var[Component]\n\n @classmethod\n def create(cls, *children, **props) -> BaseUIComponent:\n \"\"\"Create the dialog trigger component.\"\"\"\n props[\"data-slot\"] = \"select-group\"\n cls.set_class_name(ClassNames.GROUP, props)\n return super().create(*children, **props)\n\n\nclass SelectGroupLabel(SelectBaseComponent):\n \"\"\"An accessible label that is automatically associated with its parent group.\"\"\"\n\n tag = \"Select.GroupLabel\"\n\n # The render prop\n render_: Var[Component]\n\n @classmethod\n def create(cls, *children, **props) -> BaseUIComponent:\n \"\"\"Create the dialog trigger component.\"\"\"\n props[\"data-slot\"] = \"select-group-label\"\n cls.set_class_name(ClassNames.GROUP_LABEL, props)\n return super().create(*children, **props)\n\n\nclass SelectSeparator(SelectBaseComponent):\n \"\"\"A separator element accessible to screen readers.\"\"\"\n\n tag = \"Select.Separator\"\n\n # The orientation of the separ", "output": "tag = \"Select.Group\""}
{"instruction": "r prop\n render_: Var[Component]\n\n @classmethod\n def create(cls, *children, **props) -> BaseUIComponent:\n \"\"\"Create the dialog trigger component.\"\"\"\n props[\"data-slot\"] = \"select-separator\"\n cls.set_class_name(ClassNames.SEPARATOR, props)\n return super().create(*children, **props)\n\n\nclass SelectIcon(SelectBaseComponent):\n \"\"\"An icon that indicates that the trigger button opens a select menu.\"\"\"\n\n tag = \"Select.Icon\"\n\n # The render prop\n render_: Var[Component]\n\n @classmethod\n def create(cls, *children, **props) -> BaseUIComponent:\n \"\"\"Create the dialog trigger component.\"\"\"\n props[\"data-slot\"] = \"select-icon\"\n cls.set_class_name(ClassNames.ICON, props)\n return super().create(*children, **props)\n\n\nclass SelectArrow(SelectBaseComponent):\n \"\"\"Displays an element positioned against the select menu anchor.\"\"\"\n\n tag = \"Select.Arrow\"\n\n # The render prop\n render_: Var[Component]\n\n @classmethod\n ", "input": "\n\n\nclass SelectScrollUpArrow(SelectBaseComponent):\n \"\"\"An element that scrolls the select menu up when hovered.\"\"\"\n\n tag = \"Select.ScrollUpArrow\"\n\n # Whether to keep the component mounted when not visible. Defaults to False.\n keep_mounted: Var[bool]\n\n # The render prop\n render_: Var[Component]\n\n @classmethod\n def create(cls, *children, **props) -> BaseUIComponent:\n \"\"\"Create the dialog trigger component.\"\"\"\n props[\"data-slot\"] = \"select-scroll-up-arrow\"\n cls.set_class_name(ClassNames.SCROLL_ARROW_UP, props)\n return super().create(*children, **props)\n\n\nclass SelectScrollDownArrow(SelectBaseComponent):\n \"\"\"An element that scrolls the select menu down when hovered.\"\"\"\n\n tag = \"Select.ScrollDownArrow\"\n\n # Whether to keep the component mounted when not visible. Defaults to False.\n keep_mounted: Var[bool]\n\n # The render prop\n render_: Var[Component]\n\n @classmethod\n def create(cls, *children, **props) -> BaseUICompone", "output": "def create(cls, *children, **props) -> BaseUIComponent:\n \"\"\"Create the dialog trigger component.\"\"\"\n props[\"data-slot\"] = \"select-arrow\"\n cls.set_class_name(ClassNames.ARROW, props)\n return super().create(*children, **props)"}
{"instruction": "Literal[\"horizontal\", \"vertical\"]\n\non_value_event_spec = (\n passthrough_event_spec(int),\n passthrough_event_spec(float),\n passthrough_event_spec(list[int | float]),\n passthrough_event_spec(list[int]),\n passthrough_event_spec(list[float]),\n)\n\n\nclass ClassNames:\n \"\"\"Class names for slider components.\"\"\"\n\n ROOT = \"flex max-w-64 w-full touch-none items-center select-none\"\n VALUE = \"text-sm text-primary-11 font-medium\"\n CONTROL = \"flex items-center justify-center w-full\"\n TRACK = \"h-2 w-full rounded-full bg-secondary-4 select-none\"\n INDICATOR = \"absolute h-full rounded-full bg-primary-9 select-none\"\n THUMB = \"h-4 w-[0.575rem] rounded-[2px] bg-white outline outline-black/30 select-none box-shadow:[0_0_0_1px_rgba(0,0,0,1),0_1px_2px_rgba(0,0,0,.04)] data-[dragging]:h-5 transition-[height,scale] hover:h-4.5\"\n\n\nclass SliderBaseComponent(BaseUIComponent):\n \"\"\"Base component for slider components.\"\"\"\n\n library = f\"{PACKAGE_NAME}/slider\"\n\n @property\n ", "input": "\n\n\nclass SliderRoot(SliderBaseComponent):\n \"\"\"Groups all parts of the slider. Renders a div element.\"\"\"\n\n tag = \"Slider.Root\"\n\n # Identifies the field when a form is submitted.\n name: Var[str]\n\n # The uncontrolled value of the slider when it's initially rendered. To render a controlled slider, use the value prop instead.\n default_value: Var[int | float | list[int | float]]\n\n # The value of the slider. For ranged sliders, provide an array with two values.\n value: Var[int | float | list[int | float]]\n\n # Callback function that is fired when the slider's value changed.\n on_value_change: EventHandler[on_value_event_spec]\n\n # Callback function that is fired when the pointerup is triggered.\n on_value_committed: EventHandler[on_value_event_spec]\n\n # Locale information for formatting.\n locale: Var[str]\n\n # The granularity with which the slider can step through values. (A \"discrete\" slider.) The min prop serves as the origin for the valid values. We ", "output": "def import_var(self):\n \"\"\"Return the import variable for the slider component.\"\"\"\n return ImportVar(tag=\"Slider\", package_path=\"\", install=False)"}
{"instruction": ".\"\"\"\n props[\"data-slot\"] = \"slider-control\"\n cls.set_class_name(ClassNames.CONTROL, props)\n return super().create(*children, **props)\n\n\nclass SliderTrack(SliderBaseComponent):\n \"\"\"Contains the slider indicator and represents the entire range of the slider. Renders a div element.\"\"\"\n\n tag = \"Slider.Track\"\n\n # The render prop\n render_: Var[Component]\n\n @classmethod\n def create(cls, *children, **props) -> BaseUIComponent:\n \"\"\"Create the slider track component.\"\"\"\n props[\"data-slot\"] = \"slider-track\"\n cls.set_class_name(ClassNames.TRACK, props)\n return super().create(*children, **props)\n\n\nclass SliderIndicator(SliderBaseComponent):\n \"\"\"Visualizes the current value of the slider. Renders a div element.\"\"\"\n\n tag = \"Slider.Indicator\"\n\n # The render prop\n render_: Var[Component]\n\n @classmethod\n def create(cls, *children, **props) -> BaseUIComponent:\n \"\"\"Create the slider indicator component.\"\"\"\n ", "input": "\n cls.set_class_name(ClassNames.INDICATOR, props)\n return super().create(*children, **props)\n\n\nclass SliderThumb(SliderBaseComponent):\n \"\"\"The draggable part of the slider at the tip of the indicator. Renders a div element.\"\"\"\n\n tag = \"Slider.Thumb\"\n\n # Accepts a function which returns a string value that provides a user-friendly name for the input associated with the thumb.\n get_aria_label: Var[str]\n\n # Accepts a function which returns a string value that provides a user-friendly name for the current value of the slider. This is important for screen reader users.\n get_aria_value_text: Var[str]\n\n # Whether the thumb should ignore user interaction.\n disabled: Var[bool]\n\n # The render prop\n render_: Var[Component]\n\n @classmethod\n def create(cls, *children, **props) -> BaseUIComponent:\n \"\"\"Create the slider thumb component.\"\"\"\n props[\"data-slot\"] = \"slider-thumb\"\n cls.set_class_name(ClassNames.THUMB, props)\n ret", "output": "props[\"data-slot\"] = \"slider-indicator\""}
{"instruction": "rt of the switch that indicates whether the switch is on or off. Renders a span.\"\"\"\n\n tag = \"Switch.Thumb\"\n\n # The render prop\n render_: Var[Component]\n\n @classmethod\n def create(cls, *children, **props) -> BaseUIComponent:\n \"\"\"Create the switch thumb component.\"\"\"\n props[\"data-slot\"] = \"switch-thumb\"\n cls.set_class_name(ClassNames.THUMB, props)\n return super().create(*children, **props)\n\n\nclass HighLevelSwitch(SwitchRoot):\n \"\"\"High-level wrapper for the Switch component.\"\"\"\n\n @classmethod\n def create(cls, *children, **props) -> BaseUIComponent:\n \"\"\"Create a complete switch component.\n\n Args:\n *children: Additional children to include in the switch.\n **props: Additional properties to apply to the switch component.\n\n Returns:\n The switch component.\n \"\"\"\n return SwitchRoot.create(\n SwitchThumb.create(),\n *children,\n **props,\n )\n\n\n", "input": "\n\n\nswitch = Switch()\n", "output": "class Switch(ComponentNamespace):\n \"\"\"Namespace for Switch components.\"\"\"\n\n root = staticmethod(SwitchRoot.create)\n thumb = staticmethod(SwitchThumb.create)\n class_names = ClassNames\n __call__ = staticmethod(HighLevelSwitch.create)"}
{"instruction": "er prop\n render_: Var[Component]\n\n @classmethod\n def create(cls, *children, **props) -> BaseUIComponent:\n \"\"\"Create the switch thumb component.\"\"\"\n props[\"data-slot\"] = \"switch-thumb\"\n cls.set_class_name(ClassNames.THUMB, props)\n return super().create(*children, **props)\n\n\nclass HighLevelSwitch(SwitchRoot):\n \"\"\"High-level wrapper for the Switch component.\"\"\"\n\n @classmethod\n def create(cls, *children, **props) -> BaseUIComponent:\n \"\"\"Create a complete switch component.\n\n Args:\n *children: Additional children to include in the switch.\n **props: Additional properties to apply to the switch component.\n\n Returns:\n The switch component.\n \"\"\"\n return SwitchRoot.create(\n SwitchThumb.create(),\n *children,\n **props,\n )\n\n\nclass Switch(ComponentNamespace):\n \"\"\"Namespace for Switch components.\"\"\"\n\n root = staticmethod(SwitchRoot.create)\n ", "input": "\n class_names = ClassNames\n __call__ = staticmethod(HighLevelSwitch.create)\n\n\nswitch = Switch()\n", "output": "thumb = staticmethod(SwitchThumb.create)"}
{"instruction": "\"\"\"Theme switcher component.\"\"\"\n\nfrom reflex.components.component import Component, memo\nfrom reflex.components.core.cond import cond\nfrom reflex.components.el import Button, Div\nfrom reflex.style import LiteralColorMode, color_mode, set_color_mode\n\nfrom reflex_ui.components.icons.hugeicon import hi\n", "input": "\n\n\ndef theme_switcher_item(mode: LiteralColorMode, icon: str) -> Component:\n \"\"\"Create a theme switcher item button for a specific mode.\"\"\"\n active_cn = \"text-secondary-11 shadow-small bg-secondary-1\"\n unactive_cn = \"hover:text-secondary-11 text-secondary-9\"\n return Button.create(\n hi(icon, class_name=\"shrink-0\", size=14),\n on_click=set_color_mode(mode),\n class_name=(\n \"flex items-center cursor-pointer justify-center rounded-ui-xs transition-color size-6\",\n cond(mode == color_mode, active_cn, unactive_cn),\n ),\n aria_label=f\"Switch to {mode} mode\",\n )\n\n\ndef theme_switcher(class_name: str = \"\") -> Component:\n \"\"\"Theme switcher component.\"\"\"\n return Div.create(\n theme_switcher_item(\"system\", \"ComputerIcon\"),\n theme_switcher_item(\"light\", \"Sun01Icon\"),\n theme_switcher_item(\"dark\", \"Moon02Icon\"),\n class_name=cn(\n \"flex flex-row items-center bg-secondary-3 p-1 rounded-ui-md w-", "output": "from reflex_ui.utils.twmerge import cn"}
{"instruction": "\"\"\"Tooltip component from base-ui components.\"\"\"\n\nfrom typing import Literal\n\nfrom reflex.components.component import Component, ComponentNamespace\n", "input": "\nfrom reflex.utils.imports import ImportVar\nfrom reflex.vars.base import Var\n\nfrom reflex_ui.components.base_ui import PACKAGE_NAME, BaseUIComponent\nfrom reflex_ui.components.icons.others import arrow_svg\n\nLiteralSide = Literal[\"top\", \"right\", \"bottom\", \"left\", \"inline-end\", \"inline-start\"]\nLiteralAlign = Literal[\"start\", \"center\", \"end\"]\nLiteralPositionMethod = Literal[\"absolute\", \"fixed\"]\nLiteralTrackCursorAxis = Literal[\"none\", \"bottom\", \"x\", \"y\"]\n\n\n# Constants for default class names\nclass ClassNames:\n \"\"\"Class names for tooltip components.\"\"\"\n\n TRIGGER = \"inline-flex items-center justify-center\"\n POPUP = \"rounded-ui-sm bg-secondary-12 px-2.5 py-1.5 text-balance text-sm font-medium text-secondary-1 shadow-small transition-all duration-150 data-[ending-style]:scale-90 data-[ending-style]:opacity-0 data-[starting-style]:scale-90 data-[starting-style]:opacity-0\"\n ARROW = \"data-[side=bottom]:top-[-7.5px] data-[side=left]:right-[-12.5px] data-[side=left]:rotate-90 data-[side", "output": "from reflex.event import EventHandler, passthrough_event_spec"}
{"instruction": "(\"content\")\n\n # Extract props for different parts\n root_props = {k: props.pop(k) for k in cls._root_props & props.keys()}\n portal_props = {k: props.pop(k) for k in cls._portal_props & props.keys()}\n positioner_props = {\n k: props.pop(k) for k in cls._positioner_props & props.keys()\n }\n\n # Set default values\n positioner_props.setdefault(\"side_offset\", 8)\n root_props.setdefault(\"delay\", 0)\n root_props.setdefault(\"close_delay\", 0)\n\n return TooltipRoot.create(\n TooltipTrigger.create(\n render_=trigger,\n ),\n TooltipPortal.create(\n TooltipPositioner.create(\n TooltipPopup.create(\n TooltipArrow.create(arrow_svg()),\n content,\n ),\n **positioner_props,\n ),\n **portal_props,\n ),\n **root_props,\n )\n\n\n", "input": "\n\n\ntooltip = Tooltip()\n", "output": "class Tooltip(ComponentNamespace):\n \"\"\"Namespace for Tooltip components.\"\"\"\n\n provider = staticmethod(TooltipProvider.create)\n root = staticmethod(TooltipRoot.create)\n trigger = staticmethod(TooltipTrigger.create)\n portal = staticmethod(TooltipPortal.create)\n positioner = staticmethod(TooltipPositioner.create)\n popup = staticmethod(TooltipPopup.create)\n arrow = staticmethod(TooltipArrow.create)\n class_names = ClassNames\n __call__ = staticmethod(HighLevelTooltip.create)"}
{"instruction": "FILE) not in changed_files:\n return changed_files\n logger.info(\"make_pyi.py has changed, checking diff now\")\n diff = \"\".join(_git_diff([GENERATOR_FILE.as_posix()]).splitlines()[2:])\n\n try:\n last_diff = GENERATOR_DIFF_FILE.read_text()\n if diff != last_diff:\n logger.info(\"make_pyi.py has changed, regenerating all .pyi files\")\n changed_files = None\n else:\n logger.info(\"make_pyi.py has not changed, only regenerating changed files\")\n except FileNotFoundError:\n logger.info(\n \"make_pyi.py diff could not be determined, regenerating all .pyi files\"\n )\n changed_files = None\n\n GENERATOR_DIFF_FILE.write_text(diff)\n\n return changed_files\n\n\nif __name__ == \"__main__\":\n targets = (\n [arg for arg in sys.argv[1:] if not arg.startswith(\"tests\")]\n if len(sys.argv) > 1\n else DEFAULT_TARGETS\n )\n\n # Only include targets that have a prefix in the default target list\n ", "input": "\n\n logger.info(f\"Running .pyi generator for {targets}\")\n\n changed_files = _get_changed_files()\n if changed_files is None:\n logger.info(\"Changed files could not be detected, regenerating all .pyi files\")\n else:\n logger.info(f\"Detected changed files: {changed_files}\")\n\n gen = PyiGenerator()\n gen.scan_all(targets, changed_files)\n\n current_commit_sha = subprocess.run(\n [\"git\", \"rev-parse\", \"HEAD\"], capture_output=True, encoding=\"utf-8\"\n ).stdout.strip()\n LAST_RUN_COMMIT_SHA_FILE.write_text(current_commit_sha)\n", "output": "targets = [\n target\n for target in targets\n if any(str(target).startswith(prefix) for prefix in DEFAULT_TARGETS)\n ]"}
{"instruction": "from __future__ import annotations\n\nfrom logging.config import fileConfig\n\nfrom sqlalchemy import engine_from_config, pool\n\n", "input": "\n\n# this is the Alembic Config object, which provides\n# access to the values within the .ini file in use.\nconfig = context.config\n\n# Interpret the config file for Python logging.\n# This line sets up loggers basically.\nif config.config_file_name is not None:\n fileConfig(config.config_file_name)\n\n# add your model's MetaData object here\n# for 'autogenerate' support\n# from myapp import mymodel\n# target_metadata = mymodel.Base.metadata\ntarget_metadata = None\n\n# other values from the config, defined by the needs of env.py,\n# can be acquired:\n# my_important_option = config.get_main_option(\"my_important_option\")\n# ... etc.\n\n\ndef run_migrations_offline() -> None:\n \"\"\"Run migrations in 'offline' mode.\n\n This configures the context with just a URL\n and not an Engine, though an Engine is acceptable\n here as well. By skipping the Engine creation\n we don't even need a DBAPI to be available.\n\n Calls to context.execute() here emit the given string to the\n script output.\n\n \"", "output": "from alembic import context"}
{"instruction": "from __future__ import annotations\n\nimport os\n\nimport openai\nimport reflex as rx\n\nOPENAI_API_KEY = os.environ.get(\"OPENAI_API_KEY\")\n\n\nclass ChatappState(rx.State):\n # The current question being asked.\n question: str\n\n # Keep track of the chat history as a list of (question, answer) tuples.\n chat_history: list[tuple[str, str]]\n\n def set_question(self, q: str):\n self.question = q\n\n def set_question1(self, q: str):\n ", "input": "\n\n def set_question2(self, q: str):\n self.question = q\n\n def set_question3(self, q: str):\n self.question = q\n\n def answer(self) -> None:\n # Our chatbot is not very smart right now...\n answer = \"I don't know!\"\n self.chat_history.append((self.question, answer))\n\n def answer2(self) -> None:\n # Our chatbot is not very smart right now...\n answer = \"I don't know!\"\n self.chat_history.append((self.question, answer))\n # Clear the question input.\n self.question = \"\"\n\n async def answer3(self):\n import asyncio\n\n # Our chatbot is not very smart right now...\n answer = \"I don't know!\"\n self.chat_history.append((self.question, \"\"))\n\n # Clear the question input.\n self.question = \"\"\n # Yield here to clear the frontend input before continuing.\n yield\n\n for i in range(len(answer)):\n await asyncio.sleep(0.1)\n self.chat_history[-1] = (self.", "output": "self.question = q"}
{"instruction": "rt right now...\n answer = \"I don't know!\"\n self.chat_history.append((self.question, answer))\n\n def answer2(self) -> None:\n # Our chatbot is not very smart right now...\n answer = \"I don't know!\"\n self.chat_history.append((self.question, answer))\n # Clear the question input.\n self.question = \"\"\n\n async def answer3(self):\n import asyncio\n\n # Our chatbot is not very smart right now...\n answer = \"I don't know!\"\n self.chat_history.append((self.question, \"\"))\n\n # Clear the question input.\n self.question = \"\"\n # Yield here to clear the frontend input before continuing.\n yield\n\n for i in range(len(answer)):\n await asyncio.sleep(0.1)\n self.chat_history[-1] = (self.chat_history[-1][0], answer[: i + 1])\n yield\n\n async def answer4(self):\n # Our chatbot has some brains now!\n client = openai.AsyncOpenAI(api_key=OPENAI_API_KEY)\n ", "input": "\n\n # Add to the answer as the chatbot responds.\n answer = \"\"\n self.chat_history.append((self.question, answer))\n\n # Clear the question input.\n self.question = \"\"\n # Yield here to clear the frontend input before continuing.\n yield\n\n async for item in session:\n if hasattr(item.choices[0].delta, \"content\"):\n if item.choices[0].delta.content is None:\n # presence of 'None' indicates the end of the response\n break\n answer += item.choices[0].delta.content\n self.chat_history[-1] = (self.chat_history[-1][0], answer)\n yield\n", "output": "session = await client.chat.completions.create(\n model=\"gpt-4o-mini\",\n messages=[{\"role\": \"user\", \"content\": self.question}],\n stop=None,\n temperature=0.7,\n stream=True,\n )"}
{"instruction": "comp_xd,\n h3_comp_xd,\n h4_comp_xd,\n list_comp,\n ordered_list_comp,\n text_comp,\n unordered_list_comp,\n)\n\n\ndef get_code_style(color: str):\n return {\n \"p\": {\"margin_y\": \"0px\"},\n \"code\": {\n \"color\": rx.color(color, 11),\n \"border_radius\": \"4px\",\n \"border\": f\"1px solid {rx.color(color, 5)}\",\n \"background\": rx.color(color, 4),\n **code,\n },\n **base,\n }\n\n\nclass AlertBlock(flexdown.blocks.MarkdownBlock):\n \"\"\"A block that displays a component along with its code.\"\"\"\n\n starting_indicator = \"```md alert\"\n ending_indicator = \"```\"\n\n include_indicators = True\n\n def render(self, env) -> rx.Component:\n lines = self.get_lines(env)\n\n args = lines[0].removeprefix(self.starting_indicator).split()\n\n if len(args) == 0:\n args = [\"info\"]\n status = args[0]\n\n if lines[1].startswith(\"#\"):\n title = lines[1].strip(\"#\").strip()\n ", "input": "\n else:\n title = \"\"\n content = \"\\n\".join(lines[1:-1])\n\n colors = {\n \"info\": \"accent\",\n \"success\": \"grass\",\n \"warning\": \"amber\",\n \"error\": \"red\",\n }\n\n color = colors.get(status, \"blue\")\n\n has_content = bool(content.strip())\n\n if has_content:\n return rx.box(\n rx.accordion.root(\n rx.accordion.item(\n rx.accordion.header(\n rx.accordion.trigger(\n rx.hstack(\n rx.box(\n rx.match(\n status,\n (\n \"info\",\n rx.icon(\n tag=\"info\",\n ", "output": "content = \"\\n\".join(lines[2:-1])"}
{"instruction": " for the home page.\"\"\"\n\n # Whether the user signed up for the newsletter.\n signed_up: bool = False\n\n # Whether to show the confetti.\n show_confetti: bool = False\n\n @rx.event(background=True)\n async def send_contact_to_webhook(\n self,\n email: str,\n ) -> None:\n with contextlib.suppress(httpx.HTTPError):\n async with httpx.AsyncClient() as client:\n response = await client.post(\n REFLEX_DEV_WEB_NEWSLETTER_FORM_WEBHOOK_URL,\n json={\n \"email\": email,\n },\n )\n response.raise_for_status()\n\n @rx.event(background=True)\n async def add_contact_to_loops(\n self,\n email: str,\n ):\n url: str = f\"{API_BASE_URL_LOOPS}/contacts/create\"\n loops_api_key: str | None = os.getenv(\"LOOPS_API_KEY\")\n if loops_api_key is None:\n print(\"Loops API key does not exist\")\n return\n\n ", "input": "\n try:\n async with httpx.AsyncClient() as client:\n response = await client.post(\n url,\n headers=headers,\n json={\n \"email\": email,\n },\n )\n response.raise_for_status() # Raise an exception for HTTP errors (4xx and 5xx)\n\n except httpx.HTTPError as e:\n print(f\"An error occurred: {e}\")\n\n @rx.event\n def signup_for_another_user(self):\n self.signed_up = False\n\n @rx.event(background=True)\n async def signup(\n self,\n form_data: dict[str, Any],\n ):\n \"\"\"Sign the user up for the newsletter.\"\"\"\n email: str | None = None\n if email_to_validate := form_data.get(\"input_email\"):\n try:\n validated_email: ValidatedEmail = validate_email(\n email_to_validate,\n check_deliverability=True,\n )\n ", "output": "headers = {\n \"Accept\": \"application/json\",\n \"Authorization\": f\"Bearer {loops_api_key}\",\n }"}
{"instruction": " text: str = \"\",\n variant: LiteralButtonVariant = \"primary\",\n size: LiteralButtonSize = \"sm\",\n style: Dict[str, Any] | None = None,\n class_name: str = \"\",\n icon: Optional[rx.Component] = None,\n **props,\n) -> rx.Component:\n \"\"\"Create a button component.\n\n Args:\n text (str): The text to display on the button.\n variant (LiteralButtonVariant, optional): The button variant. Defaults to \"primary\".\n size (LiteralButtonSize, optional): The button size. Defaults to \"sm\".\n style (Dict[str, Any], optional): Additional styles to apply to the button. Defaults to {}.\n class_name (str, optional): Additional CSS classes to apply to the button. Defaults to \"\".\n icon (Optional[rx.Component], optional): An optional icon component to display before the text. Defaults to None.\n **props: Additional props to pass to the button element.\n\n Returns:\n rx.Component: A button component with the specified properties.\n\n \"\"\"\n ", "input": "\n variant_class = BUTTON_STYLES[\"variant\"][variant]\n variant_class = variant_class() if callable(variant_class) else variant_class\n\n classes = [\n DEFAULT_CLASS_NAME,\n BUTTON_STYLES[\"size\"][size],\n variant_class,\n class_name,\n ]\n\n content = [icon, text] if icon else [text]\n\n return rx.el.button(\n *content,\n style=style,\n class_name=cn(*classes),\n **props,\n )\n", "output": "if style is None:\n style = {}"}
{"instruction": "\"\"\"The state for the navbar component.\"\"\"\n\nimport reflex as rx\n\n\nclass NavbarState(rx.State):\n \"\"\"The state for the navbar component.\"\"\"\n\n # Whether the sidebar is open.\n sidebar_open: bool = False\n\n search_input: str = \"\"\n\n enter: bool = False\n\n banner: bool = True\n\n ai_chat: bool = True\n\n current_category = \"All\"\n\n @rx.event\n def set_sidebar_open(self, value: bool):\n ", "input": "\n\n def toggle_banner(self):\n self.banner = not self.banner\n\n def toggle_sidebar(self):\n self.sidebar_open = not self.sidebar_open\n\n def toggle_ai_chat(self):\n self.ai_chat = not self.ai_chat\n\n def update_category(self, tag):\n self.current_category = tag\n", "output": "self.sidebar_open = value"}
{"instruction": " \"url\": doc.get(\"url\", \"\"),\n \"image\": doc.get(\"path\", \"\"),\n \"cluster\": self._get_cluster_from_section(doc.get(\"section\", \"\")),\n \"description\": self._get_highlighted_content(doc, highlights),\n }\n\n else:\n return {\n \"title\": doc.get(\"title\", \"\"),\n \"url\": doc.get(\"url\", \"\"),\n \"author\": doc.get(\"author\", \"\"),\n \"date\": doc.get(\"date\", \"\"),\n \"description\": self._truncate_content(doc.get(\"content\", \"\")),\n \"image\": doc.get(\"image\", \"\"),\n }\n\n def _get_cluster_from_section(self, section: str) -> str:\n \"\"\"Map section back to cluster name.\"\"\"\n for cluster, sections in CLUSTERS.items():\n if section in sections:\n return cluster\n return \"Docs\"\n\n def _truncate_content(self, content: str, max_length: int = 200) -> str:\n \"\"\"Truncate content for description.\"\"\"\n ", "input": "\n return content[:max_length].rstrip() + \"...\"\n\n\ndef keyboard_shortcut_script() -> rx.Component:\n \"\"\"Add keyboard shortcut support for opening search.\"\"\"\n return rx.script(\n \"\"\"\n document.addEventListener('keydown', function(e) {\n if ((e.metaKey || e.ctrlKey) && e.key === 'k') {\n e.preventDefault();\n document.getElementById('search-trigger').click();\n }\n });\n \"\"\"\n )\n\n\ndef search_trigger() -> rx.Component:\n \"\"\"Render the search trigger button.\"\"\"\n return ui.button(\n rx.html(\n \"\"\"
\n rx.Component:\n return rx.link(\n get_icon(icon=icon, class_name=\"!text-slate-9\"),\n class_name=\"flex justify-center items-center gap-2 hover:bg-slate-3 px-4 py-[0.875rem] w-full h-[47px] transition-bg overflow-hidden\"\n + (\" border-slate-4 border-x border-solid border-y-0\" if border else \"\"),\n href=url,\n is_external=True,\n )\n\n\ndef drawer_socials() -> rx.Component:\n return rx.box(\n social_menu_item(\"github\", GITHUB_URL),\n so", "output": "import reflex as rx"}
{"instruction": " children=[\n hosting.app_management,\n hosting.machine_types,\n hosting.regions,\n hosting.logs,\n hosting.secrets_environment_vars,\n hosting.custom_domains,\n hosting.config_file,\n hosting.tokens,\n hosting.deploy_with_github_actions,\n ],\n ),\n create_item(\n \"Usage\",\n children=[\n hosting.billing,\n hosting.compute,\n ],\n ),\n create_item(\"CLI Reference\", children=cloud_cliref.pages),\n create_item(\n \"Self Hosting\",\n children=[\n hosting.self_hosting,\n hosting.databricks,\n ],\n ),\n ]\n return items\n\n\ndef get_sidebar_items_hosting_cli_ref():\n items = [\n create_item(\"CLI Reference\", children=cloud_cliref.pages),\n ]\n return items\n\n\nlearn = get_sidebar_items_learn()\n", "input": "\nbackend = get_sidebar_items_backend()\nhosting = get_sidebar_items_hosting()\ncli_ref = get_sidebar_items_hosting_cli_ref()\n", "output": "frontend = get_sidebar_items_frontend()"}
{"instruction": "vg>\n\"\"\"\n\nnew_tab = \"\"\"\n\n\n \n \n\"\"\"\n\n", "input": "\n\neye = \"\"\"\n\n\n \n\"\"\"\n\ntwitter = \"\"\"\n\n\n\n \n \n\"\"\""}
{"instruction": "6.8678 12.0296 17.3957 12.9833C17.6187 13.386 17.4729 13.8931 17.0702 14.116C16.6677 14.3389 16.1605 14.1932 15.9376 13.7905C15.6197 13.2163 15.08 12.7692 14.3971 12.5862C13.0632 12.2289 11.6925 13.0203 11.3352 14.3534C11.2532 14.6592 11.0052 14.8921 10.6949 14.9546C10.3846 15.0172 10.0657 14.8985 9.87174 14.6483L8.92482 13.4273C8.64282 13.0635 8.70899 12.54 9.07274 12.258C9.43641 11.976 9.95991 12.0422 10.2419 12.4059L10.3667 12.5668ZM16.8048 15.0458C16.4947 15.1085 16.2467 15.3413 16.1648 15.647C15.8076 16.9801 14.4367 17.7715 13.1029 17.4142C12.4358 17.2355 11.9054 16.8048 11.5849 16.2497C11.3547 15.8512 10.8451 15.7147 10.4465 15.9448C10.048 16.1749 9.91141 16.6847 10.1416 17.0832C10.6742 18.0054 11.5605 18.7264 12.6717 19.0241C14.3929 19.4852 16.1515 18.7984 17.1339 17.4328L17.2585 17.5933C17.5407 17.9568 18.0643 18.0227 18.4278 17.7404C18.7913 17.4581 18.8572 16.9346 18.5749 16.5711L17.628 15.3516C17.4339 15.1017 17.115 14.9833 16.8048 15.0458Z\" fill=\"currentColor\"/>\n \n\"\"\"\n\n", "input": "\n\nbackend_compatible = \"\"\"
\n \n \n \n \n\"\"\""}
{"instruction": "", "input": "\n\nfrom pcweb.components.hosting_banner import HostingBannerState\nfrom pcweb.components.icons.icons import get_icon\n\n\ndef create_pattern(\n pattern: str,\n class_name: str,\n) -> rx.Component:\n return get_icon(\n pattern,\n class_name=\"z-[-1] absolute w-[1111.528px] h-[1094.945px] overflow-hidden pointer-events-none shrink-0\"\n + \" \"\n + class_name,\n )\n\n\ndef default_patterns() -> rx.Component:\n return [\n # Left\n create_pattern(\n \"radial_small\",\n class_name=\"top-0 mt-[-80px] mr-[725px] translate-y-0\",\n ),\n create_pattern(\n \"radial_big\",\n class_name=\"top-0 mt-[90px] mr-[700px] translate-y-0 rotate-180 scale-x-[-1] scale-y-[-1]\",\n ),\n # Right\n create_pattern(\n \"radial_small\",\n class_name=\"top-0 mt-[-80px] ml-[725px] scale-x-[-1]\",\n ),\n create_pattern(\n \"radial_big\",\n class_name=\"top-0 mt-[90px] ml-[700px] ", "output": "import reflex as rx"}
{"instruction": "ucide_icon(node[0], node[1])\n for node in icon_nodes[icon_name]\n ],\n ),\n \"path\": f\"https://lucide.dev/api/icons/{icon_name}\",\n \"component\": f\"<{icon_name.replace('-', '').title()} />\",\n \"keywords\": icon_tags.get(icon_name, [])\n + icon_categories.get(icon_name, []),\n }\n for icon_name in LUCIDE_ICON_LIST\n if icon_name in icon_categories\n ]\n\n self.filtered_icons = self.icons\n\n def filter_icons(self):\n if not self.search_query:\n self.filtered_icons = self.icons\n else:\n query = self.search_query.lower().strip()\n self.filtered_icons = [\n icon\n for icon in self.icons\n if self._is_similar(query, icon[\"name\"].lower())\n or any(self._is_similar(query, kw.lower()) for kw in icon[\"keywords\"])\n ]\n\n @staticmethod\n ", "input": "\n\n @rx.event\n def update_search(self, value: str):\n self.search_query = value\n self.filter_icons()\n\n @rx.event\n def copy_icon_name(self, name: str):\n yield rx.set_clipboard(name)\n return rx.toast(f'Copied \"{name}\" to clipboard')\n\n\ndef lucide_icons():\n return rx.box(\n rx.box(\n rx.box(\n rx.icon(\n tag=\"search\",\n size=20,\n class_name=\"shrink-0 !text-slate-11\",\n ),\n class_name=\"absolute left-2 top-1/2 transform -translate-y-1/2 z-[1] shrink-0 flex items-center justify-center pb-2\",\n ),\n rx.el.input(\n placeholder=\"Search icons...\",\n on_change=IconState.update_search.debounce(250),\n class_name=\"relative box-border border-slate-4 focus:border-violet-9 focus:border-1 bg-slate-2 p-[0.5rem_0.75rem] border rounded-xl font-base text-slate-11 placeholder:text-slate-9 outlin", "output": "def _is_similar(query: str, target: str) -> bool:\n # Exact match\n if query == target:\n return True\n\n # Start of word match\n if target.startswith(query):\n return True\n\n # Word boundary match\n if f\" {query}\" in f\" {target} \":\n return True\n\n # Acronym match\n if query == \"\".join(word[0] for word in target.split() if word):\n return True\n\n # Substring match with minimum length\n return len(query) >= 3 and query in target"}
{"instruction": "').title()} />\",\n \"keywords\": icon_tags.get(icon_name, [])\n + icon_categories.get(icon_name, []),\n }\n for icon_name in LUCIDE_ICON_LIST\n if icon_name in icon_categories\n ]\n\n self.filtered_icons = self.icons\n\n def filter_icons(self):\n if not self.search_query:\n self.filtered_icons = self.icons\n else:\n query = self.search_query.lower().strip()\n self.filtered_icons = [\n icon\n for icon in self.icons\n if self._is_similar(query, icon[\"name\"].lower())\n or any(self._is_similar(query, kw.lower()) for kw in icon[\"keywords\"])\n ]\n\n @staticmethod\n def _is_similar(query: str, target: str) -> bool:\n # Exact match\n if query == target:\n return True\n\n # Start of word match\n if target.startswith(query):\n return True\n\n # Word boundary match\n ", "input": "\n\n # Acronym match\n if query == \"\".join(word[0] for word in target.split() if word):\n return True\n\n # Substring match with minimum length\n return len(query) >= 3 and query in target\n\n @rx.event\n def update_search(self, value: str):\n self.search_query = value\n self.filter_icons()\n\n @rx.event\n def copy_icon_name(self, name: str):\n yield rx.set_clipboard(name)\n return rx.toast(f'Copied \"{name}\" to clipboard')\n\n\ndef lucide_icons():\n return rx.box(\n rx.box(\n rx.box(\n rx.icon(\n tag=\"search\",\n size=20,\n class_name=\"shrink-0 !text-slate-11\",\n ),\n class_name=\"absolute left-2 top-1/2 transform -translate-y-1/2 z-[1] shrink-0 flex items-center justify-center pb-2\",\n ),\n rx.el.input(\n placeholder=\"Search icons...\",\n on_change=IconState.update_searc", "output": "if f\" {query}\" in f\" {target} \":\n return True"}
{"instruction": "import reflex as rx\nfrom reflex.utils.imports import ImportVar\n\nfrom pcweb.templates.docpage import docpage\n\nfrom .source import Source, generate_docs\n\nmodules = [\n rx.App,\n rx.Base,\n rx.Component,\n rx.ComponentState,\n (rx.Config, rx.config.BaseConfig),\n rx.event.Event,\n rx.event.EventHandler,\n rx.event.EventSpec,\n rx.Model,\n # rx.testing.AppHarness,\n rx.state.StateManager,\n # rx.state.BaseState,\n rx.State,\n ImportVar,\n rx.Var,\n]\n\nfrom .env_vars import env_vars_doc\n\npages = []\nfor module in modules:\n if isinstance(module, tuple):\n module, *extra_modules = module\n extra_fields = []\n for extra_module in extra_modules:\n s_extra = Source(module=extra_module)\n extra_fields.extend(s_extra.get_fields())\n else:\n extra_fields = None\n s = Source(module=module)\n ", "input": "\n docs = generate_docs(name, s, extra_fields=extra_fields)\n title = name.replace(\"_\", \" \").title()\n page_data = docpage(f\"/docs/api-reference/{name}/\", title)(docs)\n page_data.title = page_data.title.split(\"ยท\")[0].strip()\n pages.append(page_data)\n\npages.append(env_vars_doc)\n", "output": "name = module.__name__.lower()"}
{"instruction": "import reflex as rx\nfrom reflex.utils.imports import ImportVar\n\nfrom pcweb.templates.docpage import docpage\n\nfrom .source import Source, generate_docs\n\nmodules = [\n rx.App,\n rx.Base,\n rx.Component,\n rx.ComponentState,\n (rx.Config, rx.config.BaseConfig),\n rx.event.Event,\n rx.event.EventHandler,\n rx.event.EventSpec,\n rx.Model,\n # rx.testing.AppHarness,\n rx.state.StateManager,\n # rx.state.BaseState,\n rx.State,\n ImportVar,\n rx.Var,\n]\n\nfrom .env_vars import env_vars_doc\n\npages = []\nfor module in modules:\n if isinstance(module, tuple):\n module, *extra_modules = module\n extra_fields = []\n for extra_module in extra_modules:\n s_extra = Source(module=extra_module)\n extra_fields.extend(s_extra.get_fields())\n else:\n extra_fields = None\n s = Source(module=module)\n name = module.__name__.lower()\n ", "input": "\n title = name.replace(\"_\", \" \").title()\n page_data = docpage(f\"/docs/api-reference/{name}/\", title)(docs)\n page_data.title = page_data.title.split(\"ยท\")[0].strip()\n pages.append(page_data)\n\npages.append(env_vars_doc)\n", "output": "docs = generate_docs(name, s, extra_fields=extra_fields)"}
{"instruction": "lex as rx\nfrom reflex.reflex import cli\n\nfrom pcweb.flexdown import markdown\nfrom pcweb.templates.docpage import docpage\n\n\n@dataclasses.dataclass(frozen=True)\nclass Element:\n def into_text(self) -> str:\n \"\"\"Convert the element into a text representation.\"\"\"\n raise NotImplementedError(\"Subclasses must implement this method.\")\n\n\n@dataclasses.dataclass(frozen=True)\nclass InlineElement(Element): ...\n\n\n@dataclasses.dataclass(frozen=True)\nclass InlineTextCollection(InlineElement):\n elements: tuple[InlineElement, ...]\n\n def into_text(self) -> str:\n return \"\".join(element.into_text() for element in self.elements)\n\n\n@dataclasses.dataclass(frozen=True)\nclass InlineText(InlineElement):\n text: str\n\n def into_text(self) -> str:\n import html\n\n return html.escape(self.text)\n\n\n@dataclasses.dataclass(frozen=True)\nclass InlineCode(InlineText):\n def into_text(self) -> str:\n return f\"`{super().into_text()}`\"\n\n\n@dataclasses.dataclass(frozen=True)\n", "input": "\n\n\n@dataclasses.dataclass(frozen=True)\nclass Header(Element):\n level: int\n text: InlineElement\n\n def into_text(self) -> str:\n return f\"{'#' * self.level} {self.text.into_text()}\\n\"\n\n\n@dataclasses.dataclass(frozen=True)\nclass List(Element):\n items: tuple[InlineElement, ...]\n ordered: bool = False\n\n def into_text(self) -> str:\n prefix = \"1. \" if self.ordered else \"* \"\n return \"\\n\".join(f\"{prefix}{item.into_text()}\" for item in self.items) + \"\\n\\n\"\n\n\n@dataclasses.dataclass(frozen=True)\nclass CodeBlock(Element):\n code: str\n language: str | None = None\n\n def into_text(self) -> str:\n if self.language:\n return f\"```{self.language}\\n{self.code}\\n```\\n\\n\"\n return f\"```\\n{self.code}\\n```\\n\\n\"\n\n\n@dataclasses.dataclass(frozen=True)\nclass Empty(Element):\n def into_text(self) -> str:\n return \"\"\n\n\n@dataclasses.dataclass(frozen=True)\nclass Section(Element):\n sub_elements: tuple[Element, ...]\n\n def into_text(self) ", "output": "class Paragraph(Element):\n text: InlineElement\n\n def into_text(self) -> str:\n return f\"{self.text.into_text()}\\n\\n\""}
{"instruction": "dig[:8]\n\n\nclass PropDocsState(rx.State):\n \"\"\"Container for dynamic vars used by the prop docs.\"\"\"\n\n\nEXCLUDED_COMPONENTS = [\n \"Theme\",\n \"ThemePanel\",\n \"DrawerRoot\",\n \"DrawerTrigger\",\n \"DrawerOverlay\",\n \"DrawerPortal\",\n \"DrawerContent\",\n \"DrawerClose\",\n]\n\n\ndef render_select(prop, component, prop_dict):\n if (\n not rx.utils.types._issubclass(\n component, (RadixThemesComponent, RadixPrimitiveComponent)\n )\n or component.__name__ in EXCLUDED_COMPONENTS\n ):\n return rx.fragment()\n try:\n type_ = rx.utils.types.get_args(prop.type_)[0]\n except Exception:\n return rx.fragment()\n\n try:\n if issubclass(type_, bool) and prop.name not in [\n \"open\",\n \"checked\",\n \"as_child\",\n \"default_open\",\n \"default_checked\",\n ]:\n name = get_id(f\"{component.__qualname__}_{prop.name}\")\n PropDocsState.add_var(name, bool, False)\n ", "input": "\n setter = getattr(PropDocsState, f\"set_{name}\")\n prop_dict[prop.name] = var\n return rx.checkbox(\n var,\n on_change=setter,\n )\n except TypeError:\n pass\n\n if not isinstance(type_, _GenericAlias) or (\n type_.__origin__ not in (Literal, Union)\n ):\n return rx.fragment()\n # For the Union[Literal, Breakpoints] type\n if type_.__origin__ is Union:\n if not all(\n arg.__name__ in [\"Literal\", \"Breakpoints\"] for arg in type_.__args__\n ):\n return rx.fragment()\n else:\n # Get the literal values\n literal_values = [\n str(lit_arg)\n for arg in type_.__args__\n if get_origin(arg) is Literal\n for lit_arg in arg.__args__\n ]\n option = literal_values[0]\n name = get_id(f\"{component.__qualname__}_{prop.name}\")\n PropDocsState.add_var(name, s", "output": "var = getattr(PropDocsState, name)"}
{"instruction": "omponents_list: list[dict[str, str]] = []\n paginated_data: list[dict[str, str]] = []\n\n selected_filter: str = \"\"\n original_components_list: list[dict[str, str]] = []\n\n current_page: int = 1\n current_limit: int = 50 # Default number of items per page\n total_pages: int = 1\n offset: int = 0\n number_of_rows: int = 0\n\n # Added available limits for the number of items per page\n limits: list[str] = [\"10\", \"20\", \"50\", \"100\"]\n\n @rx.event(background=True)\n async def fetch_components_list(self):\n try:\n async with httpx.AsyncClient() as client:\n response = await client.get(\n f\"{os.getenv('RCC_ENDPOINT')}/custom-components/gallery\"\n )\n response.raise_for_status()\n component_list = response.json()\n except (httpx.HTTPError, json.JSONDecodeError) as ex:\n print(f\"Internal error: failed to fetch components list due to: {ex}\")\n return\n\n ", "input": "\n\n async with self:\n self.original_components_list = component_list\n self.number_of_rows = len(component_list)\n self.total_pages = (\n self.number_of_rows + self.current_limit - 1\n ) // self.current_limit\n yield CustomComponentGalleryState.paginate()\n\n @rx.event\n def paginate(self) -> None:\n start = self.offset\n end = start + self.current_limit\n self.paginated_data = self.original_components_list[start:end]\n self.current_page = (self.offset // self.current_limit) + 1\n\n @rx.event\n def delta_limit(self, limit: str) -> None:\n self.current_limit = int(limit)\n self.offset = 0\n self.total_pages = (\n self.number_of_rows + self.current_limit - 1\n ) // self.current_limit\n self.paginate()\n\n @rx.event\n def previous(self) -> None:\n if self.offset >= self.current_limit:\n self.offset -= self.current_limit\n els", "output": "for c in component_list:\n c[\"downloads_last_month\"] = c[\"downloads\"][\"last_month\"]\n c[\"keywords\"] = [\n keyword\n for keyword in c[\"keywords\"] or []\n if \"reflex\" not in keyword.lower()\n ]\n c[\"download_url\"] = package_url(c[\"package_name\"])"}
{"instruction": "iled to fetch components list due to: {ex}\")\n return\n\n for c in component_list:\n c[\"downloads_last_month\"] = c[\"downloads\"][\"last_month\"]\n c[\"keywords\"] = [\n keyword\n for keyword in c[\"keywords\"] or []\n if \"reflex\" not in keyword.lower()\n ]\n c[\"download_url\"] = package_url(c[\"package_name\"])\n\n async with self:\n self.original_components_list = component_list\n self.number_of_rows = len(component_list)\n self.total_pages = (\n self.number_of_rows + self.current_limit - 1\n ) // self.current_limit\n yield CustomComponentGalleryState.paginate()\n\n @rx.event\n def paginate(self) -> None:\n start = self.offset\n end = start + self.current_limit\n self.paginated_data = self.original_components_list[start:end]\n self.current_page = (self.offset // self.current_limit) + 1\n\n @rx.event\n ", "input": "\n\n @rx.event\n def previous(self) -> None:\n if self.offset >= self.current_limit:\n self.offset -= self.current_limit\n else:\n self.offset = 0\n self.paginate()\n\n @rx.event\n def next(self) -> None:\n if self.offset + self.current_limit < self.number_of_rows:\n self.offset += self.current_limit\n self.paginate()\n\n @rx.event\n def sort_components(self):\n # Get the sorting function based on the selected filter\n sorting_function = SORTING_CRITERIA.get(\n self.selected_filter, lambda x: x[\"updated_at\"]\n )\n\n # Both \"Recent\" and \"Downloads\" should be sorted in reverse order (newest/highest first)\n if self.selected_filter in [\"Recent\", \"Downloads\"]:\n self.original_components_list.sort(key=sorting_function, reverse=True)\n else:\n # Default sorting behavior, if no filter selected\n self.original_components_list.sort(key=sorting_function,", "output": "def delta_limit(self, limit: str) -> None:\n self.current_limit = int(limit)\n self.offset = 0\n self.total_pages = (\n self.number_of_rows + self.current_limit - 1\n ) // self.current_limit\n self.paginate()"}
{"instruction": "\"\"\"Module for documenting Reflex environment variables.\"\"\"\n\nfrom __future__ import annotations\n\nimport inspect\nfrom typing import Any, List, Optional, Tuple\n\nimport reflex as rx\nfrom reflex.config import EnvironmentVariables\n\nfrom pcweb.flexdown import markdown\nfrom pcweb.templates.docpage import docpage, h1_comp, h2_comp\n\n\nclass EnvVarDocs:\n \"\"\"Documentation for Reflex environment variables.\"\"\"\n\n @classmethod\n def get_all_env_vars(cls) -> List[Tuple[str, Any]]:\n \"\"\"Get all environment variables from the environment class.\n\n Returns:\n A list of tuples containing the environment variable name and its EnvVar instance.\n \"\"\"\n env_vars = []\n for name, attr in inspect.getmembers(EnvironmentVariables):\n ", "input": "\n env_vars.append((name, attr))\n return env_vars\n\n @classmethod\n def get_env_var_docstring(cls, name: str) -> Optional[str]:\n \"\"\"Get the docstring for an environment variable.\n\n Args:\n name: The name of the environment variable.\n\n Returns:\n The docstring for the environment variable, or None if not found.\n \"\"\"\n source_code = inspect.getsource(EnvironmentVariables)\n lines = source_code.splitlines()\n\n for i, line in enumerate(lines):\n if f\"{name}:\" in line and \"EnvVar\" in line:\n j = i - 1\n comments = []\n while j >= 0 and lines[j].strip().startswith(\"#\"):\n comments.insert(0, lines[j].strip()[1:].strip())\n j -= 1\n if comments:\n return \"\\n\".join(comments)\n return None\n\n @classmethod\n def generate_env_var_table(cls, include_internal: bool = False) -> rx.Compon", "output": "if name.startswith(\"_\") or not hasattr(attr, \"name\"):\n continue"}
{"instruction": " if line.strip().startswith(\"#\"):\n comments.append(line)\n continue\n\n # Check if this line has a prop.\n match = re.search(\"\\\\w+:\", line)\n if match is None:\n # This line doesn't have a var, so continue.\n continue\n\n # Get the prop.\n prop = match.group(0).strip(\":\")\n if prop not in props or prop.startswith(\"_\"):\n # This isn't a prop, so continue.\n comments.clear()\n continue\n\n prop = props[prop]\n # redundant check just to double-check line above prop is a comment\n assert self.code[i - 1].strip().startswith(\"#\"), (\n f\"Expected comment, got {self.code[i - 1]}\"\n )\n\n # Get the comment for this prop.\n comment = Source.get_comment(comments)\n # reset comments\n comments.clear()\n\n # Skip private props.\n ", "input": "\n\n # Add the prop to the output.\n out.append(\n {\n \"prop\": prop,\n \"description\": comment,\n }\n )\n\n # Return the output.\n return out\n\n\ndef format_field(field):\n prop = field[\"prop\"]\n try:\n type_ = prop.type_\n except AttributeError:\n type_ = prop.type\n default = field[\"prop\"].default\n default = None if default is dataclasses.MISSING else repr(default)\n type_str = type_.__name__ if hasattr(type_, \"__name__\") else str(type_)\n if default:\n type_str += f\" = {default}\"\n return rx.code(field[\"prop\"].name, \": \", type_str, class_name=\"code-style\")\n\n\ntable_header_class_name = (\n \"font-small text-slate-12 text-normal w-auto justify-start pl-4 font-bold\"\n)\n\n\ndef format_fields(headers, fields):\n return (\n rx.scroll_area(\n rx.table.root(\n rx.table.header(\n rx.table.row(\n ", "output": "if \"PRIVATE\" in comment:\n continue"}
{"instruction": "rview.md\": \"Client Storage Overview\",\n \"docs/state_structure/overview.md\": \"State Structure Overview\",\n \"docs/state/overview.md\": \"State Overview\",\n \"docs/styling/overview.md\": \"Styling Overview\",\n \"docs/ui/overview.md\": \"UI Overview\",\n \"docs/wrapping-react/overview.md\": \"Wrapping React Overview\",\n \"docs/library/html/html.md\": \"HTML Elements\",\n \"docs/recipes-overview.md\": \"Recipes Overview\",\n \"docs/events/special_events.md\": \"Special Events Docs\",\n \"docs/library/graphing/general/tooltip.md\": \"Graphing Tooltip\",\n \"docs/recipes/content/grid.md\": \"Grid Recipe\",\n}\n\n\ndef get_component(doc: str, title: str):\n if doc.endswith(\"-style.md\"):\n return\n\n if doc.endswith(\"-ll.md\"):\n return\n\n # Get the docpage component.\n doc = doc.replace(\"\\\\\", \"/\")\n route = rx.utils.format.to_kebab_case(f\"/{doc.replace('.md', '/')}\")\n # Handle index files: /folder/index/ -> /folder/\n if route.endswith(\"/index/\"):\n route = route[:-7] + \"/\"\n ", "input": "\n category = os.path.basename(os.path.dirname(doc)).title()\n\n if not _check_whitelisted_path(route):\n return\n\n d = Document.from_file(doc)\n\n if doc.startswith(\"docs/library/graphing\"):\n if should_skip_compile(doc):\n outblocks.append((d, route))\n return\n clist = [title, *get_components_from_metadata(d)]\n graphing_components[category].append(clist)\n return multi_docs(path=route, comp=d, component_list=clist, title=title2)\n if doc.startswith(\"docs/library\"):\n clist = [title, *get_components_from_metadata(d)]\n component_list[category].append(clist)\n if should_skip_compile(doc):\n outblocks.append((d, route))\n return\n return multi_docs(path=route, comp=d, component_list=clist, title=title2)\n\n if should_skip_compile(doc):\n outblocks.append((d, route))\n return\n\n def comp():\n return (get_toc(d, doc), xd.render(d, doc))\n\n doc_path = Path(doc)\n ", "output": "title2 = manual_titles[doc] if doc in manual_titles else to_title_case(title)"}
{"instruction": "\"\"\"Plugins API reference page.\"\"\"\n\n", "input": "\n\nfrom pcweb.templates.docpage import docpage\n\n\n@docpage(\"/docs/api-reference/plugins/\")\ndef plugins():\n \"\"\"Plugins API reference page.\"\"\"\n with open(\"docs/api-reference/plugins.md\", encoding=\"utf-8\") as f:\n content = f.read()\n return rx.markdown(content)\n", "output": "import reflex as rx"}
{"instruction": "\"\"\"Utils API reference page.\"\"\"\n\n", "input": "\n\nfrom pcweb.templates.docpage import docpage\n\n\n@docpage(\"/docs/api-reference/utils/\")\ndef utils():\n \"\"\"Utils API reference page.\"\"\"\n with open(\"docs/api-reference/utils.md\", encoding=\"utf-8\") as f:\n content = f.read()\n return rx.markdown(content)\n", "output": "import reflex as rx"}
{"instruction": " # Tag filtering\n if self.checked_tags and not (set(app_tags) & self.checked_tags):\n continue\n\n filtered.append(app_title)\n\n return filtered\n\n @rx.event\n def clear_filters(self):\n self.checked_tags = set()\n self.page = 1\n\n @rx.var\n def filtered_templates(self) -> list[str]:\n all_filtered = self._get_all_filtered_templates()\n self.total_pages = (\n (len(all_filtered) + ITEMS_PER_PAGE - 1) // ITEMS_PER_PAGE\n if all_filtered\n else 1\n )\n start = (self.page - 1) * ITEMS_PER_PAGE\n end = start + ITEMS_PER_PAGE\n return all_filtered[start:end]\n\n @rx.event\n def set_query(self, value: str):\n self.query = value\n self.page = 1\n\n @rx.event\n def toggle_template(self, value: str):\n if value in self.checked_tags:\n self.checked_tags.remove(value)\n else:\n self.checked_tags.add(value)\n ", "input": "\n\n @rx.event\n def prev_page(self):\n if self.page > 1:\n self.page -= 1\n\n @rx.event\n def next_page(self):\n if self.page < self.total_pages:\n self.page += 1\n\n\ndef pagination() -> rx.Component:\n return rx.box(\n rx.box(\n button(\n icon=rx.icon(tag=\"chevron-left\", size=16, class_name=\"!text-slate-10\"),\n disabled=TemplatesState.page == 1,\n variant=\"secondary\",\n size=\"icon-sm\",\n on_click=TemplatesState.prev_page,\n ),\n button(\n icon=rx.icon(tag=\"chevron-right\", size=16, class_name=\"!text-slate-10\"),\n disabled=TemplatesState.page == TemplatesState.total_pages,\n variant=\"secondary\",\n size=\"icon-sm\",\n on_click=TemplatesState.next_page,\n ),\n class_name=\"flex flex-row items-center gap-2\",\n ),\n rx.text(\n f\"{TemplatesSt", "output": "self.page = 1"}
{"instruction": "import reflex as rx\n\nfrom pcweb.components.hosting_banner import HostingBannerState\nfrom pcweb.components.new_button import button\n", "input": "\n\n\ndef hero() -> rx.Component:\n \"\"\"Render the hero section of the landing page.\"\"\"\n return rx.el.section(\n # Headings\n rx.el.h1(\n \"Deploy with a single command\",\n class_name=\"max-w-full inline-block bg-clip-text bg-gradient-to-r from-slate-12 to-slate-11 w-full text-4xl lg:text-5xl text-center text-transparent text-balance mx-auto break-words font-semibold\",\n ),\n # TODO: Change this wording\n rx.el.h2(\n \"\"\"A unified platform to build and manage your Reflex apps\"\"\",\n class_name=\"max-w-full w-full font-large text-center text-slate-11 -mt-2 font-normal text-[1.25rem] mx-auto text-balance word-wrap break-words md:whitespace-pre\",\n ),\n # Buttons\n rx.box(\n rx.link(\n button(\n \"Start deploying\",\n size=\"xl\",\n class_name=\"w-full lg:w-fit\",\n ),\n underline=\"none\",\n hre", "output": "from pcweb.pages.docs import hosting"}
{"instruction": "import reflex as rx\nimport reflex_ui as ui\nfrom reflex.experimental import ClientStateVar\n\nfrom .integration_list import get_integration_path\n", "input": "\n\nselected_filter = ClientStateVar.create(\"selected_filter\", \"All\")\n\nFilterOptions = [\n {\"name\": \"AI\", \"icon\": \"BotIcon\"},\n {\"name\": \"DevTools\", \"icon\": \"WorkflowSquare10Icon\"},\n {\"name\": \"Data Infrastructure\", \"icon\": \"DatabaseAddIcon\"},\n {\"name\": \"Authentication\", \"icon\": \"LockPasswordIcon\"},\n {\"name\": \"Communication\", \"icon\": \"SentIcon\"},\n {\"name\": \"All\", \"icon\": \"CellsIcon\"},\n]\n\n\ndef integration_filter_button(data: dict):\n active_pill = \"border border-violet-8 bg-violet-3 hover:bg-violet-3 !text-violet-10\"\n\n return ui.button(\n ui.icon(icon=data[\"icon\"]),\n rx.el.p(data[\"name\"], class_name=\"text-sm\"),\n variant=\"outline\",\n class_name=\"flex flex-row items-center \"\n + rx.cond(selected_filter.value == data[\"name\"], active_pill, \"\").to(str),\n on_click=selected_filter.set_value(data[\"name\"]),\n )\n\n\ndef integration_filters():\n return rx.el.div(\n rx.el.div(\n *[integration_filter_button(data) for data in ", "output": "from .integration_request import request_integration_dialog"}
{"instruction": "import reflex as rx\nimport reflex_ui as ui\nfrom reflex.experimental import ClientStateVar\n\nfrom pcweb.components.icons.icons import get_icon\n", "input": "\n\ncompany_cs = ClientStateVar.create(\"company\", \"\")\narea_x_pos = ClientStateVar.create(var_name=\"area_x_pos\", default=0)\narea_y_pos = ClientStateVar.create(var_name=\"area_y_pos\", default=0)\narea_opacity = ClientStateVar.create(var_name=\"area_opacity\", default=0)\n\ncompanies_list = [\n \"apple\",\n \"microsoft\",\n \"amazon\",\n \"fastly\",\n \"accenture\",\n \"ibm\",\n \"unicef\",\n \"autodesk\",\n \"STATS\",\n \"sellerx\",\n \"ford\",\n \"paloalto\",\n \"bosch\",\n \"dell\",\n \"twilio\",\n \"rappi\",\n \"nike\",\n]\n\ncompanies_case_studies = {\n \"dell\": {\n \"company_name\": \"Dell\",\n \"quote\": \"\"\"Reflex has been a game changer.\n In just a week, I had a demo up and running with excellent performance.\n It made the project feasible for my support team, helping us build a smooth, efficient interface.\"\"\",\n \"person\": \"JL\",\n \"picture\": \"/favicon.ico\",\n \"role\": \"Principal Engineer\",\n },\n \"autodesk\": {\n \"company_name\": \"Autodesk\",\n ", "output": "from pcweb.pages.framework.views.companies import companies as index_companies"}
{"instruction": "import base64\nimport uuid\nfrom typing import TypedDict\n\nimport httpx\nimport reflex as rx\nimport reflex_ui as ui\nfrom reflex.experimental import ClientStateVar\n\nfrom pcweb.components.numbers_pattern import numbers_pattern\nfrom pcweb.constants import (\n MAX_FILE_SIZE_BYTES,\n MAX_FILE_SIZE_MB,\n MAX_IMAGES_COUNT,\n PROMPT_MAP,\n REFLEX_BUILD_URL,\n RX_BUILD_BACKEND,\n)\n\n\ndef is_content_type_valid(content_type: str) -> bool:\n \"\"\"Check if the content type is valid.\"\"\"\n return content_type.startswith(\"image/\")\n\n\n", "input": "\ntextarea_y_pos = ClientStateVar.create(var_name=\"textarea_y_pos\", default=0)\ntextarea_opacity = ClientStateVar.create(var_name=\"textarea_opacity\", default=0)\nshow_default_prompt = ClientStateVar.create(\n var_name=\"show_default_prompt\", default=True\n)\n\n\nclass ImageData(TypedDict):\n data: bytes\n mime_type: str\n\n\nclass SubmitPromptState(rx.State):\n _images: list[ImageData] | None = None\n is_uploading: rx.Field[bool] = rx.field(False)\n is_processing: rx.Field[bool] = rx.field(False)\n\n @rx.event(background=True, temporal=True)\n async def redirect_to_ai_builder(self, form_data: dict):\n if prompt := form_data.get(\"prompt\"):\n if len(prompt) < 5:\n return rx.toast.warning(\n \"Your prompt needs at least 5 characters. Please add more details.\",\n )\n random_uuid = uuid.uuid4()\n async with httpx.AsyncClient() as client:\n response = await client.post(\n RX_B", "output": "textarea_x_pos = ClientStateVar.create(var_name=\"textarea_x_pos\", default=0)"}
{"instruction": "tics\",\n \"Get alerts and metrics\",\n \"Get alerts and metrics for your Reflex app to help you monitor and optimize your app.\",\n ),\n class_name=\"flex flex-col max-w-full lg:max-w-[21.4375rem] divide-y divide-slate-3\",\n ),\n rx.box(\n rx.image(\n src=\"/landing/hosting_features/light/card.webp\",\n class_name=\"absolute top-0 left-0 w-full h-full object-cover pointer-events-none dark:hidden\",\n ),\n rx.image(\n src=\"/landing/hosting_features/dark/card.webp\",\n class_name=\"absolute top-0 left-0 w-full h-full object-cover pointer-events-none dark:block hidden\",\n ),\n class_name=\"justify-center items-center relative overflow-hidden w-full lg:flex hidden\",\n ),\n class_name=\"flex flex-col lg:flex-row max-w-[64.19rem] mx-auto w-full border-x-0 lg:border-x border-slate-3 divide-x-0 lg:divide-x divide-slate-3\",\n )\n\n\n", "input": "\n\n\ndef hosting_section() -> rx.Component:\n return rx.el.section(\n header(),\n # graph(),\n content(),\n class_name=\"flex flex-col mx-auto w-full max-w-[84.19rem] relative\",\n )\n", "output": "def graph() -> rx.Component:\n return rx.box(\n rx.image(\n src=\"/hosting_graphing.svg\",\n class_name=\"w-full h-[10rem]\",\n ),\n class_name=\"flex flex-col lg:flex-row max-w-[64.19rem] mx-auto w-full border-x-0 lg:border-x border-slate-3 divide-x-0 lg:divide-x divide-slate-3 p-10\",\n )"}
{"instruction": " line_svg(class_name=\"right-[12rem] top-1/2 -translate-y-1/2 scale-x-[-1]\"),\n class_name=\"relative overflow-hidden\",\n ),\n class_name=\"grid grid-cols-2 absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 lg:w-[43.5rem] w-[36rem] z-[0] overflow-hidden h-[20rem]\",\n )\n\n\ndef integrations_row() -> rx.Component:\n return rx.el.div(\n lines(),\n rx.el.div(\n intregation_card(\"supabase\", \"langchain\"),\n intregation_card(\"openai\", \"databricks\"),\n intregation_card(\"stripe\", \"anthropic\"),\n class_name=\"flex flex-col gap-10\",\n ),\n r_logo_card(),\n rx.el.div(\n intregation_card(\"aws\", \"gcp\"),\n intregation_card(\"azure\", \"oracle\"),\n intregation_card(\"databricks\", \"reflex\"),\n class_name=\"flex flex-col gap-10\",\n ),\n class_name=\"flex flex-row items-center lg:gap-[7.5rem] gap-14 mt-10 relative max-lg:w-full justify-center\",\n )\n\n\n", "input": "\n", "output": "def integrations() -> rx.Component:\n return rx.el.section(\n numbers_pattern(side=\"left\", class_name=\"left-0 top-0\"),\n numbers_pattern(side=\"right\", class_name=\"right-0 top-0\"),\n header(),\n integrations_row(),\n class_name=\"flex flex-col items-center mx-auto w-full max-w-[64.19rem] lg:border-x border-slate-3 relative overflow-hidden lg:border-t lg:pb-26 pb-20 pt-20\",\n )"}
{"instruction": "from typing import List\n\nimport reflex as rx\n\n", "input": "\nfrom pcweb.components.new_button import button\n\n# Outcomes features data\nOUTCOMES_FEATURES = [\n {\n \"title\": \"Dedicated Engineer\",\n \"description\": \"An expert engineer is assigned to your team to build your first app.\",\n \"icon\": \"backend_auth\",\n },\n {\n \"title\": \"Fast Time to Launch\",\n \"description\": \"Get your first app up and running quickly with expert guidance.\",\n \"icon\": \"zap\",\n },\n {\n \"title\": \"Guaranteed Success\",\n \"description\": \"We ensure your app reaches a successful state before handoff.\",\n \"icon\": \"star\",\n },\n {\n \"title\": \"Training and Enablement\",\n \"description\": \"Hands-on training so your team can maintain and extend your app.\",\n \"icon\": \"document_code\",\n },\n]\n\n\ndef header() -> rx.Component:\n return rx.box(\n rx.el.h3(\n \"Deliver Outcomes\",\n class_name=\"lg:text-3xl text-xl font-semibold text-slate-12 text-balance\",\n ),\n rx.el", "output": "from pcweb.components.icons import get_icon"}
{"instruction": "import reflex as rx\nimport reflex_ui as ui\nfrom reflex.experimental.client_state import ClientStateVar\n\n", "input": "\n\ncollapsed_calculator_cs = ClientStateVar.create(\"collapsed_calculator\", default=True)\n\nCREDITS_PER_HOUR_CPU = 0.2\nCREDITS_PER_HOUR_GB = 0.5\n\nCOMPUTE_TABLE = {\n \"c1m.5\": {\"vcpu\": 1, \"ram\": 0.5},\n \"c1m1\": {\"vcpu\": 1, \"ram\": 1},\n \"c1m2\": {\"vcpu\": 1, \"ram\": 2},\n \"c2m2\": {\"vcpu\": 2, \"ram\": 2},\n \"c2m4\": {\"vcpu\": 2, \"ram\": 4},\n \"c4m4\": {\"vcpu\": 4, \"ram\": 4},\n \"c4m8\": {\"vcpu\": 4, \"ram\": 8},\n}\n\n\ndef table_header(cost_text: str) -> rx.Component:\n return rx.box(\n rx.text(\"Machine\", class_name=\"text-sm font-semibold text-slate-12\"),\n rx.text(\"vCPU\", class_name=\"text-sm font-semibold text-slate-12\"),\n rx.text(\"GB RAM\", class_name=\"text-sm font-semibold text-slate-12\"),\n rx.el.div(\n ui.icon(\"TokenCircleIcon\", class_name=\"text-slate-9 size-4\"),\n rx.text(\n cost_text, class_name=\"text-sm font-semibold text-slate-12 text-end\"\n ),\n class_name=\"flex flex-row gap-1 items-center justify-end\",\n ", "output": "from pcweb.components.tabs import tabs"}
{"instruction": "# FONT STYLES\n\nfont_family = \"Instrument Sans\"\n\nsmall = {\n \"font-family\": font_family,\n \"font-style\": \"normal\",\n \"font-weight\": \"500\",\n \"font-size\": \"14px\",\n \"line-height\": \"20px\",\n \"letter-spacing\": \"-0.0125em\",\n}\n\nsmall_semibold = {\n \"font-family\": font_family,\n \"font-size\": \"14px\",\n \"font-style\": \"normal\",\n \"font-weight\": \"600\",\n \"line-height\": \"20px\",\n \"letter-spacing\": \"-0.0125em\",\n}\n\n", "input": "\n\nbase_semibold = {\n \"font-family\": font_family,\n \"font-style\": \"normal\",\n \"font-weight\": \"600\",\n \"font-size\": \"16px\",\n \"line-height\": \"24px\",\n \"letter-spacing\": \"-0.015em\",\n}\n\nmedium = {\n \"font-family\": font_family,\n \"font-style\": \"normal\",\n \"font-weight\": \"500\",\n \"font-size\": \"18px\",\n \"line-height\": \"26px\",\n \"letter-spacing\": \"-0.015em\",\n}\n\nmedium_leading_5 = {\n \"font-family\": font_family,\n \"font-style\": \"normal\",\n \"font-weight\": \"500\",\n \"font-size\": \"18px\",\n \"line-height\": \"20px\",\n \"letter-spacing\": \"-0.015em\",\n}\n\nlarge = {\n \"font-family\": font_family,\n \"font-style\": \"normal\",\n \"font-weight\": \"600\",\n \"font-size\": \"24px\",\n \"line-height\": \"32px\",\n \"letter-spacing\": \"-0.015em\",\n}\n\nx_large = {\n \"font-family\": font_family,\n \"font-style\": \"normal\",\n \"font-weight\": \"600\",\n \"font-size\": [\"24px\", \"32px\"],\n \"line-height\": [\"32px\", \"40px\"],\n \"letter-spacing\": [\"-0.02em\", \"-0.03em\"],\n}\n\n\nxx_large = {\n \"", "output": "base = {\n \"font-family\": font_family,\n \"font-style\": \"normal\",\n \"font-weight\": \"500\",\n \"font-size\": [\"14px\", \"16px\"],\n \"line-height\": [\"20px\", \"24px\"],\n \"letter-spacing\": \"-0.015em\",\n}"}
{"instruction": "import functools\nfrom typing import Callable\n\nimport reflex as rx\n\n", "input": "\nfrom pcweb.route import Route\n\n\ndef gallery_app_page(\n path: str,\n title: str,\n description: str,\n image: str,\n demo: str,\n meta: list[dict[str, str]] | None = None,\n props=None,\n add_as_page=True,\n) -> Callable:\n \"\"\"A template that most pages on the reflex.dev site should use.\n\n This template wraps the webpage with the navbar and footer.\n\n Args:\n path: The path of the page.\n title: The title of the page.\n description: The description of the page.\n image: The image of the page.\n demo: The demo link of the app.\n meta: The meta tags of the page.\n props: Props to apply to the template.\n add_as_page: whether to add the route to the app pages.\n\n Returns:\n A wrapper function that returns the full webpage.\n \"\"\"\n props = props or {}\n\n def webpage(contents: Callable[[], Route]) -> Route:\n \"\"\"Wrapper to create a templated route.\n\n Args:\n contents: The function to ", "output": "from pcweb.pages.framework.index_colors import index_colors"}
{"instruction": "from typing import Callable\n\nimport reflex as rx\n\n", "input": "\nfrom pcweb.route import Route\n\nDEFAULT_TITLE = \"Web Apps in Pure Python\"\n\n\ndef mainpage(\n path: str,\n title: str = DEFAULT_TITLE,\n description: str | None = None,\n image: str | None = None,\n meta: list[dict[str, str]] = meta_tags,\n props=None,\n add_as_page=True,\n) -> Callable:\n \"\"\"A template that most pages on the reflex.dev site should use.\n\n This template wraps the webpage with the navbar and footer.\n\n Args:\n path: The path of the page.\n title: The title of the page.\n description: The description of the page.\n image: The image of the page.\n meta: The meta tags of the page.\n props: Props to apply to the template.\n add_as_page: whether to add the route to the app pages.\n\n Returns:\n A wrapper function that returns the full webpage.\n \"\"\"\n props = props or {}\n\n def mainpage(contents: Callable[[], Route]) -> Route:\n \"\"\"Wrapper to create a templated route.\n\n Args:\n con", "output": "from pcweb.meta.meta import meta_tags"}
{"instruction": "\"\"\"Template for documentation pages.\"\"\"\n\nimport functools\nfrom datetime import datetime\nfrom typing import Callable\n\nimport flexdown\nimport mistletoe\nimport reflex as rx\nfrom reflex.components.radix.themes.base import LiteralAccentColor\nfrom reflex.utils.format import to_snake_case, to_title_case\n\nfrom pcweb.components.button import button\n", "input": "\nfrom pcweb.route import Route, get_path\nfrom pcweb.styles.colors import c_color\n\nfrom .blocks import *\nfrom .state import FeedbackState\n\n\ndef right_sidebar_item_highlight():\n return r\"\"\"\n function setupTableOfContentsHighlight() {\n // Delay to ensure DOM is fully loaded\n setTimeout(() => {\n const tocLinks = document.querySelectorAll('#toc-navigation a');\n const activeClass = 'text-violet-9';\n const defaultClass = 'text-slate-9';\n\n function normalizeId(id) {\n return id.toLowerCase().replace(/\\s+/g, '-');\n }\n\n function highlightTocLink() {\n // Get the current hash from the URL\n const currentHash = window.location.hash.substring(1);\n\n // Reset all links\n tocLinks.forEach(link => {\n link.classList.remove(activeClass);\n link.classList.add(defaultClass);\n });\n\n // If there's a hash, find and highlight the corresponding link\n ", "output": "from pcweb.components.icons.icons import get_icon"}
{"instruction": " parts\n formatted_parts = []\n\n # Iterate over dictionary items\n for key, value in input_dict.items():\n # Format each key-value pair\n if isinstance(value, str):\n formatted_part = f'{key}=\"{value}\"' # Enclose string values in quotes\n else:\n formatted_part = f\"{key}={value}\" # Non-string values as is\n\n # Append the formatted part to the list\n formatted_parts.append(formatted_part)\n\n # Join all parts with a comma and a space\n return \", \".join(formatted_parts)\n\n\ndef used_component(\n component_used: rx.Component,\n components_passed: rx.Component | str | None,\n color_scheme: str,\n variant: str,\n high_contrast: bool,\n disabled: bool = False,\n **kwargs,\n) -> rx.Component:\n if components_passed is None and disabled is False:\n return component_used(\n color_scheme=color_scheme,\n variant=variant,\n high_contrast=high_contrast,\n **kwargs,\n )\n\n ", "input": "\n\n\ndef style_grid(\n component_used: rx.Component,\n component_used_str: str,\n variants: list,\n components_passed: rx.Component | str | None = None,\n disabled: bool = False,\n **kwargs,\n) -> rx.Component:\n text_cn = \"text-nowrap font-md flex items-center\"\n return rx.box(\n rx.grid(\n rx.text(\"\", size=\"5\"),\n *[\n rx.text(variant, class_name=text_cn + \" text-slate-11\")\n for variant in variants\n ],\n rx.text(\n \"Accent\",\n color=f\"var(--{RadixDocState.color}-10)\",\n class_name=text_cn,\n ),\n *[\n hover_item(\n component=used_component(\n component_used=component_used,\n components_passed=components_passed,\n color_scheme=RadixDocState.color,\n variant=variant,\n high_contrast=False,\n ", "output": "elif components_passed is not None and disabled is False:\n return component_used(\n components_passed,\n color_scheme=color_scheme,\n variant=variant,\n high_contrast=high_contrast,\n **kwargs,\n )\n\n elif components_passed is None and disabled is True:\n return component_used(\n color_scheme=color_scheme,\n variant=variant,\n high_contrast=high_contrast,\n disabled=True,\n **kwargs,\n )\n\n else:\n return component_used(\n components_passed,\n color_scheme=color_scheme,\n variant=variant,\n high_contrast=high_contrast,\n disabled=True,\n **kwargs,\n )"}
{"instruction": "ode = textwrap.dedent(\n \"\\n\".join(code.strip().splitlines()[lines[0] : lines[1]])\n ).strip()\n\n # Create the code snippet.\n cb = code_block_dark if theme == \"dark\" else code_block\n return cb(\n code=code,\n language=language,\n )\n\n\ndef docdemo(\n code: str,\n state: str | None = None,\n comp: rx.Component | None = None,\n context: bool = False,\n demobox_props: dict[str, Any] | None = None,\n theme: str | None = None,\n **props,\n) -> rx.Component:\n \"\"\"Create a documentation demo with code and output.\n\n Args:\n code: The code to render the component.\n state: Code for any state needed for the component.\n comp: The pre-rendered component.\n context: Whether to wrap the render code in a function.\n demobox_props: Props to apply to the demo box.\n theme: The theme for the code snippet.\n props: Additional props to apply to the component.\n\n Returns:\n The styled demo.\n \"\"\"\n ", "input": "\n # Render the component if necessary.\n if comp is None:\n comp = eval(code)\n\n # Wrap the render code in a function if needed.\n if context:\n code = f\"\"\"def index():\n return {code}\n \"\"\"\n\n # Add the state code\n if state is not None:\n code = state + code\n\n if demobox_props.pop(\"toggle\", False):\n return rx.tabs.root(\n rx.tabs.list(\n rx.tabs.trigger(\n rx.box(\n \"UI\",\n ),\n value=\"tab1\",\n class_name=\"tab-style\",\n ),\n rx.tabs.trigger(\n rx.box(\n \"Code\",\n ),\n value=\"tab2\",\n class_name=\"tab-style\",\n ),\n class_name=\"justify-end\",\n ),\n rx.tabs.content(\n rx.box(docdemobox(comp, **(demobox_props or {})), class_name=\"my-4\"),\n ", "output": "demobox_props = demobox_props or {}"}
{"instruction": "from datetime import datetime\n\nimport reflex as rx\n\nfrom pcweb.components.icons.icons import get_icon\n", "input": "\nfrom pcweb.pages.blog import blogs\nfrom pcweb.pages.docs import getting_started, hosting\nfrom pcweb.pages.docs.library import library\nfrom pcweb.pages.errors import errors\nfrom pcweb.pages.faq import faq\nfrom pcweb.pages.gallery import gallery\nfrom pcweb.pages.use_cases.use_cases import use_cases_page\nfrom pcweb.signup import IndexState\n\n\ndef footer_link(text: str, href: str) -> rx.Component:\n return rx.link(\n text,\n href=href,\n class_name=\"font-small text-slate-9 hover:!text-slate-11 no-underline transition-color\",\n )\n\n\ndef footer_link_flex(heading: str, links: list[rx.Component]) -> rx.Component:\n return rx.box(\n rx.el.h4(\n heading,\n class_name=\"font-smbold text-slate-12\",\n ),\n *links,\n class_name=\"flex flex-col gap-4\",\n )\n\n\ndef social_menu_item(icon: str, url: str = \"/\", class_name: str = \"\") -> rx.Component:\n return rx.link(\n get_icon(icon=icon),\n class_name=\"flex justify-center ite", "output": "from pcweb.constants import (\n DISCORD_URL,\n FORUM_URL,\n GITHUB_URL,\n LINKEDIN_URL,\n ROADMAP_URL,\n TWITTER_URL,\n)"}
{"instruction": "#!/usr/bin/env python3\n\"\"\"Dead link checker for the Reflex website.\nCrawls the deployed site and checks for broken links.\n\"\"\"\n\nimport argparse\nimport sys\n", "input": "\nimport xml.etree.ElementTree as ET\nfrom collections import deque\nfrom urllib.parse import urljoin, urlparse\n\nimport requests\nfrom bs4 import BeautifulSoup\n\n\nclass DeadLinkChecker:\n def __init__(self, base_url, max_pages=None, timeout=10, delay=0.5):\n self.base_url = base_url.rstrip(\"/\")\n self.domain = urlparse(base_url).netloc\n self.max_pages = max_pages\n self.timeout = timeout\n self.delay = delay\n\n self.visited_pages = set()\n self.checked_links = set()\n self.dead_links = []\n self.pages_to_visit = deque([base_url])\n\n self.session = requests.Session()\n self.session.headers.update(\n {\"User-Agent\": \"Mozilla/5.0 (compatible; DeadLinkChecker/1.0)\"}\n )\n\n def is_internal_url(self, url):\n \"\"\"Check if URL is internal to our domain.\"\"\"\n parsed = urlparse(url)\n return parsed.netloc == self.domain or parsed.netloc == \"\"\n\n def normalize_url(self, url):\n \"\"\"Normalize U", "output": "import time"}
{"instruction": "elf.delay = delay\n\n self.visited_pages = set()\n self.checked_links = set()\n self.dead_links = []\n self.pages_to_visit = deque([base_url])\n\n self.session = requests.Session()\n self.session.headers.update(\n {\"User-Agent\": \"Mozilla/5.0 (compatible; DeadLinkChecker/1.0)\"}\n )\n\n def is_internal_url(self, url):\n \"\"\"Check if URL is internal to our domain.\"\"\"\n parsed = urlparse(url)\n return parsed.netloc == self.domain or parsed.netloc == \"\"\n\n def normalize_url(self, url):\n \"\"\"Normalize URL for comparison.\"\"\"\n parsed = urlparse(url)\n normalized = f\"{parsed.scheme}://{parsed.netloc}{parsed.path}\"\n if parsed.query:\n normalized += f\"?{parsed.query}\"\n return normalized\n\n def check_link(self, url, source_page):\n \"\"\"Check if a single link is working.\"\"\"\n if url in self.checked_links:\n return True\n\n self.checked_links.add(url)\n\n ", "input": "\n if parsed.netloc in [\"fonts.googleapis.com\", \"fonts.gstatic.com\"]:\n return True\n\n try:\n response = self.session.head(\n url, timeout=self.timeout, allow_redirects=True\n )\n\n if response.status_code == 405:\n response = self.session.get(\n url, timeout=self.timeout, allow_redirects=True\n )\n\n if response.status_code == 403 and parsed.netloc in [\n \"twitter.com\",\n \"www.twitter.com\",\n \"x.com\",\n \"www.x.com\",\n ]:\n print(f\"Warning: Twitter/X link may be blocked by bot detection: {url}\")\n return True\n\n if response.status_code >= 400:\n self.dead_links.append(\n {\n \"url\": url,\n \"status_code\": response.status_code,\n \"source_page\": source_page,\n ", "output": "parsed = urlparse(url)"}
{"instruction": ")\n text = re.sub(r\"\\[([^\\]]+)\\]\\([^)]+\\)\", r\"\\1\", text)\n text = re.sub(r\"\", \"\", text, flags=re.DOTALL)\n text = re.sub(r\"\\n\\s*\\n+\", \"\\n\\n\", text)\n return text.strip()\n\n def extract_headings(self, content: str) -> List[str]:\n \"\"\"Extract headings from markdown content.\"\"\"\n headings = []\n lines = content.split(\"\\n\")\n\n for line in lines:\n line = line.strip()\n if line.startswith(\"#\"):\n heading_text = re.sub(r\"^#+\\s*\", \"\", line)\n heading_text = re.sub(r\"\\{[^}]*\\}\", \"\", heading_text)\n if heading_text:\n headings.append(heading_text.strip())\n\n return headings\n\n def summarize_markdown(self, md_path: str, max_lines: int = 100) -> str:\n \"\"\"Your existing summarize function - simplified.\"\"\"\n with open(md_path, \"r\", encoding=\"utf-8\") as f:\n content = f.read()\n\n cleaned = self.clean_markdown(content)\n ", "input": "\n truncated_lines = lines[:max_lines]\n truncated_text = \"\\n\".join(truncated_lines).strip()\n\n if len(truncated_lines) < max_lines:\n return truncated_text\n\n return truncated_text\n\n def name_from_url(self, url: str) -> str:\n parts = url.strip(\"/\").split(\"/\")\n if parts[0] == \"docs\":\n parts = parts[1:]\n if parts and parts[-1] == \"low\":\n parts[-1] = \"low-level\"\n readable = \" \".join(part.replace(\"-\", \" \") for part in parts)\n return self.smart_title_case(readable)\n\n def extract_components(self, file_path: str) -> List[str]:\n \"\"\"Extract components from raw markdown file content.\"\"\"\n with open(file_path, \"r\", encoding=\"utf-8\") as f:\n content = f.read()\n\n patterns = [\n r\"(?:rx|reflex)\\.([A-Z][a-zA-Z0-9_]*)\",\n r\"\\b([A-Z][a-z]+(?:[A-Z][a-z]*)*Component?)\\b\",\n ]\n components = set()\n for pattern in patterns:\n matche", "output": "lines = cleaned.splitlines()"}
{"instruction": "ng_text)\n if heading_text:\n headings.append(heading_text.strip())\n\n return headings\n\n def summarize_markdown(self, md_path: str, max_lines: int = 100) -> str:\n \"\"\"Your existing summarize function - simplified.\"\"\"\n with open(md_path, \"r\", encoding=\"utf-8\") as f:\n content = f.read()\n\n cleaned = self.clean_markdown(content)\n lines = cleaned.splitlines()\n truncated_lines = lines[:max_lines]\n truncated_text = \"\\n\".join(truncated_lines).strip()\n\n if len(truncated_lines) < max_lines:\n return truncated_text\n\n return truncated_text\n\n def name_from_url(self, url: str) -> str:\n parts = url.strip(\"/\").split(\"/\")\n if parts[0] == \"docs\":\n parts = parts[1:]\n if parts and parts[-1] == \"low\":\n parts[-1] = \"low-level\"\n readable = \" \".join(part.replace(\"-\", \" \") for part in parts)\n return self.smart_title_case(readable)\n\n ", "input": "\n\n def process_doc_file(self, docs_path: str, file: str, root: str) -> Optional[dict]:\n \"\"\"Your existing process_file function adapted for Typesense.\"\"\"\n file_path = os.path.join(root, file)\n rel_path = os.path.relpath(file_path, docs_path)\n parts = pathlib.Path(rel_path).parts\n\n filename_no_ext = file.rsplit(\".\", 1)[0]\n\n parts_clean = []\n for i, p in enumerate(parts):\n is_last = i == len(parts) - 1\n if is_last:\n if filename_no_ext.lower().endswith(\"-ll\"):\n parts_clean.append(\"Low Level\")\n else:\n parts_clean.append(self.clean_name(filename_no_ext))\n else:\n parts_clean.append(self.clean_name(p))\n\n url_parts = [p.replace(\"_\", \"-\").rsplit(\".\", 1)[0] for p in parts]\n if url_parts and url_parts[-1].endswith(\"-ll\"):\n url_parts[-1] = url_parts[-1].replace(\"-ll\", \"/low\")\n\n url = \"/\" + \"/\".join(url", "output": "def extract_components(self, file_path: str) -> List[str]:\n \"\"\"Extract components from raw markdown file content.\"\"\"\n with open(file_path, \"r\", encoding=\"utf-8\") as f:\n content = f.read()\n\n patterns = [\n r\"(?:rx|reflex)\\.([A-Z][a-zA-Z0-9_]*)\",\n r\"\\b([A-Z][a-z]+(?:[A-Z][a-z]*)*Component?)\\b\",\n ]\n components = set()\n for pattern in patterns:\n matches = re.findall(pattern, content)\n components.update(matches)\n return list(components)"}
{"instruction": "ttern, content)\n components.update(matches)\n return list(components)\n\n def process_doc_file(self, docs_path: str, file: str, root: str) -> Optional[dict]:\n \"\"\"Your existing process_file function adapted for Typesense.\"\"\"\n file_path = os.path.join(root, file)\n rel_path = os.path.relpath(file_path, docs_path)\n parts = pathlib.Path(rel_path).parts\n\n filename_no_ext = file.rsplit(\".\", 1)[0]\n\n parts_clean = []\n for i, p in enumerate(parts):\n is_last = i == len(parts) - 1\n if is_last:\n if filename_no_ext.lower().endswith(\"-ll\"):\n parts_clean.append(\"Low Level\")\n else:\n parts_clean.append(self.clean_name(filename_no_ext))\n else:\n parts_clean.append(self.clean_name(p))\n\n url_parts = [p.replace(\"_\", \"-\").rsplit(\".\", 1)[0] for p in parts]\n if url_parts and url_parts[-1].endswith(\"-ll\"):\n ", "input": "\n\n url = \"/\" + \"/\".join(url_parts)\n name = \" \".join(parts_clean)\n\n full_content = self.summarize_markdown(file_path, max_lines=100)\n components = self.extract_components(file_path)\n headings = self.extract_headings(open(file_path, \"r\", encoding=\"utf-8\").read())\n\n parent = parts[0] if parts else \"\"\n cluster = \"Uncategorized\"\n for cluster_name, folder_list in CLUSTERS.items():\n if parent in folder_list:\n cluster = cluster_name\n break\n\n return {\n \"id\": str(rel_path),\n \"title\": name,\n \"content\": full_content,\n \"components\": components,\n \"headings\": headings,\n \"path\": str(rel_path),\n \"url\": f\"docs{url}\",\n \"section\": parent,\n \"subsection\": parts[1] if len(parts) > 1 else None,\n \"cluster\": cluster,\n \"is_blog\": False,\n \"parts\": parts_clean,\n }\n\n def _i", "output": "url_parts[-1] = url_parts[-1].replace(\"-ll\", \"/low\")"}
{"instruction": "\"\"\"Integration tests for all titles in Reflex.\"\"\"\n\nimport sys\nfrom collections import Counter\nfrom pathlib import Path\n\n", "input": "\n\nsys.path.append(str(Path(__file__).resolve().parent.parent))\n\n\n@pytest.fixture\ndef routes_fixture():\n from pcweb.pages import routes\n\n yield routes\n\n\ndef test_unique_titles(routes_fixture):\n assert routes_fixture is not None\n\n titles = [route for route in routes_fixture if hasattr(route, \"title\")]\n\n # Count occurrences of each title\n title_counts = Counter(titles)\n # Find duplicate titles\n duplicates = [title for title, count in title_counts.items() if count > 1]\n\n # Assert that there are no duplicates\n assert len(duplicates) == 0, f\"Duplicate titles found: {duplicates}\"\n\n print(f\"Test passed. All {len(titles)} titles are unique.\")\n", "output": "import pytest"}
{"instruction": "_raw_date.strftime(\"%b %Y\")\n else:\n filtered_data[-1][\"date\"] = last_raw_date.strftime(\"%b %d\")\n if filtered_data[-1][\"value\"] != self._raw_net_worth_data[-1][\"value\"]:\n filtered_data.append(\n {\n \"date\": filtered_data[-1][\"date\"],\n \"value\": self._raw_net_worth_data[-1][\"value\"],\n }\n )\n return filtered_data\n\n @rx.var\n def total_assets(self) -> float:\n \"\"\"Calculate total assets.\"\"\"\n return round(\n sum((item[\"value\"] for item in self.assets_summary)),\n 2,\n )\n\n @rx.var\n def total_liabilities(self) -> float:\n \"\"\"Calculate total liabilities.\"\"\"\n cc_balance = next(\n (\n cat[\"total_balance\"]\n for cat in self.account_categories\n if cat[\"category_name\"] == \"Credit Cards\"\n ),\n 0,\n )\n ", "input": "\n return round(other_liabilities + abs(cc_balance), 2)\n\n @rx.var\n def asset_percentages(\n self,\n ) -> List[AssetLiabilitySummaryItem]:\n \"\"\"Calculate asset percentages.\"\"\"\n total = self.total_assets\n if total == 0:\n return [\n {\n \"name\": item[\"name\"],\n \"value\": 0.0,\n \"color\": item[\"color\"],\n }\n for item in self.assets_summary\n ]\n return [\n {\n \"name\": item[\"name\"],\n \"value\": round(item[\"value\"] / total * 100, 1),\n \"color\": item[\"color\"],\n }\n for item in self.assets_summary\n ]\n\n @rx.var\n def liability_percentages(\n self,\n ) -> List[AssetLiabilitySummaryItem]:\n \"\"\"Calculate liability percentages.\"\"\"\n total = self.total_liabilities\n if total == 0:\n return [\n {\n ", "output": "other_liabilities = sum(\n (\n item[\"value\"]\n for item in self.liabilities_summary\n if item[\"name\"] != \"Credit Cards\"\n )\n )"}
{"instruction": "icon_base_class} text-gray-700\"\n inactive_icon_class = f\"{icon_base_class} text-gray-400 group-hover:text-gray-600\"\n is_active_column = DashboardState.sort_column == column_key\n return rx.cond(\n is_active_column,\n rx.cond(\n DashboardState.sort_order == \"asc\",\n rx.icon(\n \"arrow-up\",\n size=12,\n class_name=active_icon_class,\n ),\n rx.icon(\n \"arrow-down\",\n size=12,\n class_name=active_icon_class,\n ),\n ),\n rx.icon(\n \"chevrons-up-down\",\n size=12,\n class_name=inactive_icon_class,\n ),\n )\n\n\ndef sortable_table_header(col_name: str, column_key: SortColumn) -> rx.Component:\n \"\"\"Renders a sortable table header cell.\"\"\"\n base_class = \"px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider group\"\n sortable_class = f\"{base_class} cursor-pointer\"\n ", "input": "\n justify_content_val = rx.match(\n col_name,\n (\"Revenue\", \"flex-end\"),\n (\"Licenses\", \"center\"),\n (\"Active licenses\", \"center\"),\n \"flex-start\",\n )\n combined_class = f\"{sortable_class} {text_align_class}\"\n header_content_inner = rx.el.div(\n col_name,\n sort_icon(column_key),\n class_name=\"flex items-center group-hover:text-gray-700 transition-colors duration-150 ease-in-out\",\n style={\"justify_content\": justify_content_val},\n )\n return rx.el.th(\n header_content_inner,\n scope=\"col\",\n class_name=combined_class,\n on_click=lambda: DashboardState.sort_by(column_key),\n )\n\n\ndef non_sortable_table_header(\n col_name: str,\n) -> rx.Component:\n \"\"\"Renders a non-sortable table header cell.\"\"\"\n base_class = (\n \"px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider\"\n )\n text_align_class = rx.match(\n col_name,\n (\"Revenue\", \"text-right\")", "output": "text_align_class = rx.match(\n col_name,\n (\"Revenue\", \"text-right\"),\n (\"Licenses\", \"text-center\"),\n (\"Active licenses\", \"text-center\"),\n \"text-left\",\n )"}
{"instruction": "from datetime import datetime\nfrom typing import (\n List,\n Literal,\n Optional,\n Tuple,\n)\n\nimport reflex as rx\n\nfrom admin_dashboard.models.models import CustomerData\nfrom admin_dashboard.states.data import initial_customer_data_raw\nfrom admin_dashboard.states.utils import parse_date\n\nSortColumn = Literal[\n \"id\",\n \"next_renewal\",\n \"revenue\",\n \"licenses\",\n \"active_licenses\",\n]\n", "input": "\n\nprocessed_customers: List[CustomerData] = [\n {\n **customer,\n \"next_renewal_date\": parse_date(customer[\"next_renewal\"]),\n }\n for customer in initial_customer_data_raw\n]\n\nCOLUMN_MAPPING: List[Tuple[str, Optional[SortColumn]]] = [\n (\"ID\", \"id\"),\n (\"Customer name\", None),\n (\"Next renewal\", \"next_renewal\"),\n (\"Revenue\", \"revenue\"),\n (\"Licenses\", \"licenses\"),\n (\"Active licenses\", \"active_licenses\"),\n (\"Active license growth\", None),\n (\"Industry\", None),\n (\"Platform\", None),\n]\n\n\nclass DashboardState(rx.State):\n \"\"\"State class managing the customer dashboard data and UI interactions.\"\"\"\n\n customers: List[CustomerData] = processed_customers\n selected_customer_id: Optional[int] = None\n search_term: str = \"\"\n sort_column: Optional[SortColumn] = \"id\"\n sort_order: SortOrder = \"asc\"\n\n @rx.var\n def column_data(\n self,\n ) -> List[Tuple[str, Optional[SortColumn]]]:\n \"\"\"Returns the master list of column configur", "output": "SortOrder = Literal[\"asc\", \"desc\"]"}
{"instruction": "ist[str] = [\n \"Collaboration\",\n \"Leadership\",\n \"Innovation\",\n \"Creativity\",\n \"Feedback\",\n \"Coaching\",\n \"Mentoring\",\n \"Delegation\",\n ]\n sort_column: str = \"name\"\n sort_order: str = \"asc\"\n current_page: int = 1\n items_per_page: int = 10\n total_db_customers: int = 0\n _target_customer_email_for_tags: str | None = None\n _target_customer_tag_str: str | None = None\n _target_customer_role: str | None = None\n _next_customer_id: int = 1\n search_query: str = \"\"\n\n @rx.var\n def total_users(self) -> int:\n return len(self._processed_customers)\n\n @rx.var\n def total_pages(self) -> int:\n num_items = len(self._processed_customers)\n if (\n self.items_per_page <= 0\n ): # Guard against division by zero or invalid items_per_page\n return 0\n if num_items == 0:\n return 0\n return math.ceil(num_items / self.items_per_page)\n\n @rx.var\n ", "input": "\n\n @rx.var\n def customers(self) -> List[CustomerData]:\n data_for_page = self._processed_customers\n start_index = (self.current_page - 1) * self.items_per_page\n end_index = start_index + self.items_per_page\n return data_for_page[start_index:end_index]\n\n def _parse_tags_string(self, tags_str: str | None) -> List[str]:\n if not tags_str:\n return []\n tag_names_from_input = [\n name.strip() for name in tags_str.split(\",\") if name.strip()\n ]\n unique_tags: List[str] = []\n seen_tags: Set[str] = set()\n for tag in tag_names_from_input:\n if tag not in seen_tags:\n unique_tags.append(tag)\n seen_tags.add(tag)\n return unique_tags\n\n def _format_tags_list_to_string(self, tags_list: List[str]) -> str:\n return \", \".join(tags_list)\n\n @rx.event\n def sort_by_column(self, column_name: str):\n if self.sort_column == column_name:\n se", "output": "def _processed_customers(self) -> List[CustomerData]:\n data_to_process = list(\n self._all_customers_data\n ) # Make a copy to avoid modifying the original list if needed elsewhere\n\n # Apply search filter\n if self.search_query and self.search_query.strip():\n query_lower = self.search_query.lower().strip()\n data_to_process = [\n c\n for c in data_to_process\n if query_lower\n in f\"{c.get('first_name', '')} {c.get('last_name', '')}\".lower()\n ]\n\n # Apply sorting\n def get_sort_value(customer_data_item: CustomerData):\n if self.sort_column == \"name\":\n first = customer_data_item.get(\"first_name\", \"\")\n last = customer_data_item.get(\"last_name\", \"\")\n return (first.lower(), last.lower())\n\n sort_val = customer_data_item.get(self.sort_column)\n if isinstance(sort_val, str):\n return sort_val.lower()\n return sort_val\n\n sorted_data = sorted(\n data_to_process,\n key=get_sort_value,\n reverse=self.sort_order == \"desc\",\n )\n return sorted_data"}
{"instruction": "= (self.current_page - 1) * self.items_per_page\n end_index = start_index + self.items_per_page\n return data_for_page[start_index:end_index]\n\n def _parse_tags_string(self, tags_str: str | None) -> List[str]:\n if not tags_str:\n return []\n tag_names_from_input = [\n name.strip() for name in tags_str.split(\",\") if name.strip()\n ]\n unique_tags: List[str] = []\n seen_tags: Set[str] = set()\n for tag in tag_names_from_input:\n if tag not in seen_tags:\n unique_tags.append(tag)\n seen_tags.add(tag)\n return unique_tags\n\n def _format_tags_list_to_string(self, tags_list: List[str]) -> str:\n return \", \".join(tags_list)\n\n @rx.event\n def sort_by_column(self, column_name: str):\n if self.sort_column == column_name:\n self.sort_order = \"desc\" if self.sort_order == \"asc\" else \"asc\"\n else:\n self.sort_column = column_name\n ", "input": "\n self.current_page = 1\n\n @rx.event\n async def fetch_customers(self):\n self.loading = True\n self.error_message = \"\"\n self.all_selected = False\n target_email = self._target_customer_email_for_tags\n target_tag_str = self._target_customer_tag_str\n target_role = self._target_customer_role\n self._target_customer_email_for_tags = None\n self._target_customer_tag_str = None\n self._target_customer_role = None\n\n if not self._all_customers_data:\n fake_customers_temp: List[CustomerData] = []\n first_names = [\n \"John\",\n \"Jane\",\n \"Alice\",\n \"Bob\",\n \"Charlie\",\n \"David\",\n \"Eve\",\n \"Fiona\",\n \"George\",\n \"Hannah\",\n ]\n last_names = [\n \"Doe\",\n \"Smith\",\n \"Johnson\",\n \"Brown\",\n ", "output": "self.sort_order = \"asc\""}
{"instruction": "s = email_from_form\n self._target_customer_tag_str = tags_str_from_form\n self._target_customer_role = role_from_form\n\n self.show_edit_dialog = False\n self._reset_form_fields()\n self.total_db_customers = len(self._all_customers_data)\n\n yield CustomerState.fetch_customers\n yield rx.toast(toast_message, duration=3000)\n\n @rx.event\n def set_form_status(self, status: str):\n self.form_status = status\n\n @rx.event\n def set_form_tags(self, tags: str):\n self.form_tags = tags\n\n @rx.event\n def set_form_role(self, role: str):\n self.form_role = role\n\n @rx.event\n def toggle_select_all(self):\n self.all_selected = not self.all_selected\n for i in range(len(self._all_customers_data)):\n self._all_customers_data[i][\"selected\"] = self.all_selected\n\n @rx.event\n def toggle_select_customer(self, customer_id: int):\n all_are_selected_after_toggle = True\n found = False\n ", "input": "\n if found:\n self.all_selected = all_are_selected_after_toggle\n\n @rx.event(background=True)\n async def download_csv(self):\n async with self:\n if not self._all_customers_data:\n self.error_message = \"No customer data available to download. Please fetch customers first.\"\n yield rx.toast(\n \"No customer data to download.\",\n duration=3000,\n )\n return\n self.loading = True\n self.error_message = \"\"\n try:\n df_export_data = []\n for cust_data_item in self._all_customers_data:\n tags_str_repr = \", \".join(cust_data_item[\"tags\"])\n df_export_data.append(\n {\n \"ID\": cust_data_item[\"customer_id\"],\n \"First Name\": cust_data_item[\"first_name\"],\n \"Last Name\": cust_data_item[\"last_name\"],\n ", "output": "for i in range(len(self._all_customers_data)):\n if self._all_customers_data[i][\"customer_id\"] == customer_id:\n self._all_customers_data[i][\"selected\"] = not self._all_customers_data[\n i\n ][\"selected\"]\n found = True\n if not self._all_customers_data[i][\"selected\"]:\n all_are_selected_after_toggle = False"}
{"instruction": "import reflex as rx\n\n", "input": "\nborder = f\"1.5px solid {rx.color('gray', 5, True)}\"\ncontent_max_width = \"1280px\"\nsidebar_bg = rx.color(\"gray\", 2)\ncontent_bg_color = rx.color(\"gray\", 1)\n\nimage_style = {\n \"decoding\": \"auto\",\n \"loading\": \"eager\",\n \"vertical_align\": \"middle\",\n \"object_fit\": \"contain\",\n \"width\": \"auto\",\n}\n\nimage_height = [\"400px\", \"500px\", \"650px\", \"850px\"]\n\nimage_props = {\n \"style\": image_style,\n \"width\": \"100%\",\n \"height\": image_height,\n}\n\nbutton_props = {\n \"size\": \"2\",\n \"cursor\": \"pointer\",\n \"variant\": \"outline\",\n}\n\nbox_shadow = \"0 1px 3px 0 rgb(0 0 0 / 0.1), 0 1px 2px -1px rgb(0 0 0 / 0.1)\"\n\nbase_stylesheets = [\n \"https://fonts.googleapis.com/css2?family=Roboto+Flex:wght@400;500;600;700;800&display=swap\",\n \"react-zoom.css\",\n]\n\nbase_style = {\n \"font_family\": \"Roboto Flex\",\n rx.icon: {\n \"stroke_width\": \"1.75px\",\n },\n}\n", "output": "sidebar_width = [\"100%\", \"100%\", \"100%\", \"375px\", \"450px\"]"}
{"instruction": "import reflex as rx\n\nsidebar_width = [\"100%\", \"100%\", \"100%\", \"375px\", \"450px\"]\n", "input": "\ncontent_max_width = \"1280px\"\nsidebar_bg = rx.color(\"gray\", 2)\ncontent_bg_color = rx.color(\"gray\", 1)\n\nimage_style = {\n \"decoding\": \"auto\",\n \"loading\": \"eager\",\n \"vertical_align\": \"middle\",\n \"object_fit\": \"contain\",\n \"width\": \"auto\",\n}\n\nimage_height = [\"400px\", \"500px\", \"650px\", \"850px\"]\n\nimage_props = {\n \"style\": image_style,\n \"width\": \"100%\",\n \"height\": image_height,\n}\n\nbutton_props = {\n \"size\": \"2\",\n \"cursor\": \"pointer\",\n \"variant\": \"outline\",\n}\n\nbox_shadow = \"0 1px 3px 0 rgb(0 0 0 / 0.1), 0 1px 2px -1px rgb(0 0 0 / 0.1)\"\n\nbase_stylesheets = [\n \"https://fonts.googleapis.com/css2?family=Roboto+Flex:wght@400;500;600;700;800&display=swap\",\n \"react-zoom.css\",\n]\n\nbase_style = {\n \"font_family\": \"Roboto Flex\",\n rx.icon: {\n \"stroke_width\": \"1.75px\",\n },\n}\n", "output": "border = f\"1.5px solid {rx.color('gray', 5, True)}\""}
{"instruction": "import asyncio\nimport datetime\nimport os\nfrom enum import Enum\n\nimport reflex as rx\nimport replicate\n", "input": "\n\nfrom .options import OptionsState\n\nDEFAULT_IMAGE = \"/default.webp\"\nAPI_TOKEN_ENV_VAR = \"REPLICATE_API_TOKEN\"\n\nCopyLocalState = rx._x.client_state(default=False, var_name=\"copying\")\n\n\nclass ResponseStatus(Enum):\n STARTING = \"starting\"\n PROCESSING = \"processing\"\n SUCCEEDED = \"succeeded\"\n FAILED = \"failed\"\n CANCELED = \"canceled\"\n\n\nclass GeneratorState(rx.State):\n is_generating: bool = False\n is_upscaling: bool = False\n _request_id: str = None\n output_image: str = DEFAULT_IMAGE\n output_list: list[str] = []\n upscaled_image: str = \"\"\n is_downloading: bool = False\n\n @rx.event\n def set_output_image(self, value: str):\n self.output_image = value\n\n @rx.event(background=True)\n async def generate_image(self):\n try:\n # Check if the env variable is set\n if not self._check_api_token():\n return\n if self.is_upscaling:\n yield rx.toast.warning(\"Wait for the image to upscale first\"", "output": "import requests"}
{"instruction": "= \"\"\n self.output_image = response.output[0]\n self.output_list = [] if len(response.output) == 1 else response.output\n self._reset_state()\n\n except Exception as e:\n async with self:\n self._reset_state()\n yield rx.toast.error(f\"Error, please try again: {e}\")\n\n @rx.event(background=True)\n async def upscale_image(self):\n try:\n # Check if the env variable is set\n if not self._check_api_token():\n return\n if self.is_generating:\n yield rx.toast.warning(\"Wait for the image to generate first\")\n return\n if self.output_image == DEFAULT_IMAGE:\n yield rx.toast.warning(\"Please generate an image first\")\n return\n if self.upscaled_image != \"\":\n yield rx.toast.warning(\"Image already upscaled\")\n return\n async with self:\n ", "input": "\n input = {\n \"prompt\": \"masterpiece, best quality, highres,
\",\n \"negative_prompt\": \"(worst quality, low quality, normal quality:2) JuggernautNegative-neg\",\n \"num_inference_steps\": 18,\n \"scheduler\": \"DPM++ 3M SDE Karras\",\n \"image\": self.output_image,\n \"dynamic\": 6,\n \"handfix\": \"disabled\",\n \"sharpen\": 0,\n \"sd_model\": \"juggernaut_reborn.safetensors [338b85bc4f]\",\n \"creativity\": 0.35,\n \"lora_links\": \"\",\n \"downscaling\": False,\n \"resemblance\": 0.6,\n \"scale_factor\": 2,\n \"tiling_width\": 112,\n \"output_format\": \"png\",\n \"tiling_height\": 144,\n \"custom_sd_model\": \"\",\n \"downscaling_resolution\": 768,\n }\n # Add \"seed\" to the input if it is no", "output": "Options = await self.get_state(OptionsState)"}
{"instruction": "TARTING.value or not response:\n async with self:\n self._request_id, self.is_upscaling = None, False\n yield rx.toast.error(\"Error starting upscaling\")\n return\n\n async with self:\n self.is_upscaling = True\n self._request_id = response.id\n yield\n\n while True:\n response = await replicate.predictions.async_get(response.id)\n async with self:\n if response.status in (\n ResponseStatus.CANCELED.value,\n ResponseStatus.FAILED.value,\n ):\n self._reset_state()\n if response.status == ResponseStatus.FAILED.value:\n yield rx.toast.warning(\n f\"Error upscaling image: {response.error}\"\n )\n return\n ", "input": "\n await asyncio.sleep(0.15)\n async with self:\n self.upscaled_image = response.output[0]\n self.output_list = []\n self._request_id, self.is_upscaling = None, False\n\n except Exception as e:\n async with self:\n self._reset_state()\n yield rx.toast.error(f\"Error, please try again: {e}\")\n\n def cancel_generation(self):\n if self._request_id is None:\n return\n try:\n response = replicate.predictions.cancel(self._request_id)\n if response.status != ResponseStatus.CANCELED.value:\n raise Exception(\"Error cancelling generation\")\n except Exception as e:\n yield rx.toast.error(f\"Error cancelling generation: {e}\")\n finally:\n self._reset_state()\n\n def _reset_state(self):\n self._request_id = None\n self.is_generating = False\n self.is_upscaling = False\n\n def _check_api_tok", "output": "elif response.status == ResponseStatus.SUCCEEDED.value:\n break"}
{"instruction": "import random\n\nimport reflex as rx\n\n", "input": "\nfrom ..components.styles_preset import styles_preset\n\n\nclass OptionsState(rx.State):\n dimensions: list[tuple[int, int]] = [\n (1728, 576),\n (1664, 576),\n (1600, 640),\n (1536, 640),\n (1472, 704),\n (1408, 704),\n (1344, 704),\n (1344, 768),\n (1280, 768),\n (1216, 832),\n (1152, 832),\n (1152, 896),\n (1088, 896),\n (1088, 960),\n (1024, 960),\n (1024, 1024),\n (960, 1024),\n (960, 1088),\n (896, 1088),\n (896, 1152),\n (832, 1152),\n (832, 1216),\n (768, 1280),\n (768, 1344),\n (704, 1344),\n (704, 1408),\n (704, 1472),\n (640, 1536),\n (640, 1600),\n (576, 1664),\n (576, 1728),\n ]\n slider_tick: int = len(dimensions) // 2\n selected_dimensions: tuple[int, int] = dimensions[slider_tick]\n hover: bool = False\n styles_preset: dict[str, dict[str, str]] = styles_preset\n selected_style", "output": "from ..components.prompt_list import prompt_list"}
{"instruction": "ist[dict[str, str]]\n get_table_headers: list[str]\n paginated_data: list[dict[str, str]]\n\n # vars for pagination ...\n number_of_rows: int\n limits: list[str] = [\"10\", \"20\", \"50\"]\n current_limit: int = 10\n offset: int = 0\n current_page: int = 1\n total_pages: int = 1\n formatted_headers: dict\n\n @rx.event\n def set_req_url(self, url: str):\n self.req_url = url\n\n @rx.event\n def get_request(self, method: str):\n self.current_req = method\n\n @rx.event\n def add_header(self):\n self.headers.append(\n {\"id\": str(uuid.uuid4()), \"identifier\": \"headers\", \"key\": \"\", \"value\": \"\"}\n )\n\n @rx.event\n def add_body(self):\n self.body.append(\n {\"id\": str(uuid.uuid4()), \"identifier\": \"body\", \"key\": \"\", \"value\": \"\"}\n )\n\n @rx.event\n def add_cookies(self):\n self.cookies.append(\n {\"id\": str(uuid.uuid4()), \"identifier\": \"cookies\", \"key\": \"\", \"value\": \"\"}\n )\n\n @rx.event\n ", "input": "\n\n @rx.event\n async def update_attribute(self, data: dict[str, str], attribute: str, value: str):\n data[attribute] = value\n\n if data[\"identifier\"] == \"headers\":\n self.headers = [\n data if item[\"id\"] == data[\"id\"] else item for item in self.headers\n ]\n\n if data[\"identifier\"] == \"body\":\n self.body = [\n data if item[\"id\"] == data[\"id\"] else item for item in self.body\n ]\n\n if data[\"identifier\"] == \"cookies\":\n self.cookies = [\n data if item[\"id\"] == data[\"id\"] else item for item in self.cookies\n ]\n\n @rx.event\n async def update_keyy(self, key: str, data: dict[str, str]):\n await self.update_attribute(data, \"key\", key)\n\n @rx.event\n async def update_value(self, value: str, data: dict[str, str]):\n await self.update_attribute(data, \"value\", value)\n\n\nclass QueryAPI(QueryState):\n # vars to update row entries ...\n is_open: bo", "output": "def remove_entry(self, data: dict[str, str]):\n if data[\"identifier\"] == \"headers\":\n self.headers = [item for item in self.headers if item[\"id\"] != data[\"id\"]]\n\n if data[\"identifier\"] == \"body\":\n self.body = [item for item in self.body if item[\"id\"] != data[\"id\"]]\n\n if data[\"identifier\"] == \"cookies\":\n self.cookies = [item for item in self.cookies if item[\"id\"] != data[\"id\"]]"}
{"instruction": "ns import Counter, defaultdict\nfrom typing import Dict, List, TypedDict\n\nimport reflex as rx\nfrom faker import Faker\n\nfrom business_analytics_dashboard.models.employee import Employee\n\nfake = Faker()\n\n\nclass DepartmentData(TypedDict):\n name: str\n value: int\n\n\nclass AverageSalaryData(TypedDict):\n department: str\n average_salary: float\n\n\nclass DashboardState(rx.State):\n \"\"\"State for the dashboard.\"\"\"\n\n employees: List[Employee] = []\n search_query: str = \"\"\n selected_department: str = \"All\"\n loading: bool = False\n _base_department_colors: list[str] = [\n \"#FF6347\",\n \"#4CAF50\",\n \"#FFEB3B\",\n \"#2196F3\",\n \"#9C27B0\",\n \"#FFC107\",\n \"#8BC34A\",\n \"#FF9800\",\n \"#F44336\",\n \"#00BCD4\",\n ]\n current_page: int = 1\n items_per_page: int = 10\n\n @rx.event(background=True)\n async def fetch_dashboard_data(self):\n \"\"\"Generate fake data for the dashboard.\"\"\"\n async with self:\n ", "input": "\n self.current_page = 1\n await asyncio.sleep(0.5)\n await self._generate_fake_data()\n async with self:\n self.loading = False\n\n async def _generate_fake_data(self):\n \"\"\"Helper method to generate fake employee data.\"\"\"\n departments = [\n \"Sales\",\n \"Marketing\",\n \"Engineering\",\n \"Support\",\n \"HR\",\n \"Finance\",\n \"Product\",\n \"Design\",\n \"Operations\",\n \"Legal\",\n ]\n employees_data = []\n for i in range(1, 101):\n first_name = fake.first_name()\n last_name = fake.last_name()\n department = random.choice(departments)\n employees_data.append(\n Employee(\n employee_id=1000 + i,\n first_name=first_name,\n last_name=last_name,\n email=fake.email(),\n department=department,\n ", "output": "self.loading = True"}
{"instruction": "ict):\n department: str\n average_salary: float\n\n\nclass DashboardState(rx.State):\n \"\"\"State for the dashboard.\"\"\"\n\n employees: List[Employee] = []\n search_query: str = \"\"\n selected_department: str = \"All\"\n loading: bool = False\n _base_department_colors: list[str] = [\n \"#FF6347\",\n \"#4CAF50\",\n \"#FFEB3B\",\n \"#2196F3\",\n \"#9C27B0\",\n \"#FFC107\",\n \"#8BC34A\",\n \"#FF9800\",\n \"#F44336\",\n \"#00BCD4\",\n ]\n current_page: int = 1\n items_per_page: int = 10\n\n @rx.event(background=True)\n async def fetch_dashboard_data(self):\n \"\"\"Generate fake data for the dashboard.\"\"\"\n async with self:\n self.loading = True\n self.current_page = 1\n await asyncio.sleep(0.5)\n await self._generate_fake_data()\n async with self:\n self.loading = False\n\n async def _generate_fake_data(self):\n \"\"\"Helper method to generate fake employee data.\"\"\"\n ", "input": "\n employees_data = []\n for i in range(1, 101):\n first_name = fake.first_name()\n last_name = fake.last_name()\n department = random.choice(departments)\n employees_data.append(\n Employee(\n employee_id=1000 + i,\n first_name=first_name,\n last_name=last_name,\n email=fake.email(),\n department=department,\n salary=random.randint(50000, 150000),\n projects_closed=random.randint(0, 20),\n pending_projects=random.randint(0, 5),\n )\n )\n async with self:\n self.employees = employees_data\n\n @rx.var\n def available_departments(self) -> list[str]:\n \"\"\"Get a sorted list of unique departments including 'All'.\"\"\"\n if not self.employees:\n return [\"All\"]\n departments = sorted({emp[\"department\"] for emp in self.", "output": "departments = [\n \"Sales\",\n \"Marketing\",\n \"Engineering\",\n \"Support\",\n \"HR\",\n \"Finance\",\n \"Product\",\n \"Design\",\n \"Operations\",\n \"Legal\",\n ]"}
{"instruction": " \"#9C27B0\",\n \"#FFC107\",\n \"#8BC34A\",\n \"#FF9800\",\n \"#F44336\",\n \"#00BCD4\",\n ]\n current_page: int = 1\n items_per_page: int = 10\n\n @rx.event(background=True)\n async def fetch_dashboard_data(self):\n \"\"\"Generate fake data for the dashboard.\"\"\"\n async with self:\n self.loading = True\n self.current_page = 1\n await asyncio.sleep(0.5)\n await self._generate_fake_data()\n async with self:\n self.loading = False\n\n async def _generate_fake_data(self):\n \"\"\"Helper method to generate fake employee data.\"\"\"\n departments = [\n \"Sales\",\n \"Marketing\",\n \"Engineering\",\n \"Support\",\n \"HR\",\n \"Finance\",\n \"Product\",\n \"Design\",\n \"Operations\",\n \"Legal\",\n ]\n employees_data = []\n for i in range(1, 101):\n first_name = fake.first_name()\n ", "input": "\n department = random.choice(departments)\n employees_data.append(\n Employee(\n employee_id=1000 + i,\n first_name=first_name,\n last_name=last_name,\n email=fake.email(),\n department=department,\n salary=random.randint(50000, 150000),\n projects_closed=random.randint(0, 20),\n pending_projects=random.randint(0, 5),\n )\n )\n async with self:\n self.employees = employees_data\n\n @rx.var\n def available_departments(self) -> list[str]:\n \"\"\"Get a sorted list of unique departments including 'All'.\"\"\"\n if not self.employees:\n return [\"All\"]\n departments = sorted({emp[\"department\"] for emp in self.employees})\n return [\"All\", *departments]\n\n @rx.var\n def departments_for_filter(self) -> list[str]:\n \"\"\"Get a sorted list of", "output": "last_name = fake.last_name()"}
{"instruction": "import asyncio\nimport os\nfrom typing import List, TypedDict\n\nimport reflex as rx\n\n\nclass Message(TypedDict):\n text: str\n is_ai: bool\n\n\nclass ChatState(rx.State):\n messages: List[Message] = []\n typing: bool = False\n has_openai_key: bool = \"OPENAI_API_KEY\" in os.environ\n\n @rx.event\n def clear_messages(self):\n \"\"\"Clears all chat messages and resets typing status.\"\"\"\n self.typing = False\n ", "input": "\n\n @rx.event\n def send_message(self, form_data: dict):\n \"\"\"Adds a user message and triggers AI response generation.\"\"\"\n if self.typing:\n return\n message = form_data[\"message\"].strip()\n if message:\n self.messages.append({\"text\": message, \"is_ai\": False})\n self.messages.append({\"text\": \"\", \"is_ai\": True})\n self.typing = True\n yield ChatState.generate_response\n\n @rx.event(background=True)\n async def generate_response(self):\n \"\"\"Generates a response (mock or OpenAI).\"\"\"\n if not self.has_openai_key:\n await asyncio.sleep(1)\n response = \"This is a mock response as the OPENAI_API_KEY is not set. Please set the environment variable to use the actual LLM.\"\n current_text = \"\"\n async with self:\n if not self.messages:\n self.typing = False\n return\n for char in response:\n ", "output": "self.messages = []"}
{"instruction": " \"pipeline\",\n \"status\",\n \"workflow\",\n \"timestamp\",\n \"duration\",\n ]\n )\n ]\n\n return items\n\n @rx.var(cache=True)\n def page_number(self) -> int:\n return (self.offset // self.limit) + 1\n\n @rx.var(cache=True)\n def total_pages(self) -> int:\n return (self.total_items // self.limit) + (\n 1 if self.total_items % self.limit else 0\n )\n\n @rx.var(cache=True, initial_value=[])\n def get_current_page(self) -> list[Item]:\n start_index = self.offset\n end_index = start_index + self.limit\n return self.filtered_sorted_items[start_index:end_index]\n\n def prev_page(self):\n if self.page_number > 1:\n self.offset -= self.limit\n\n def next_page(self):\n if self.page_number < self.total_pages:\n self.offset += self.limit\n\n def first_page(self):\n ", "input": "\n\n def last_page(self):\n self.offset = (self.total_pages - 1) * self.limit\n\n def load_entries(self):\n with Path(\"data.csv\").open(encoding=\"utf-8\") as file:\n reader = csv.DictReader(file)\n self.items = [Item(**row) for row in reader]\n self.total_items = len(self.items)\n\n def toggle_sort(self):\n self.sort_reverse = not self.sort_reverse\n self.load_entries()\n", "output": "self.offset = 0"}
{"instruction": "\"\"\"The about page of the app.\"\"\"\n\nfrom pathlib import Path\n\nimport reflex as rx\n\n", "input": "\nfrom ..templates import template\n\n\n@template(route=\"/about\", title=\"About\")\ndef about() -> rx.Component:\n \"\"\"The about page.\n\n Returns:\n The UI for the about page.\n\n \"\"\"\n with Path(\"README.md\").open(encoding=\"utf-8\") as readme:\n content = readme.read()\n return rx.markdown(content, component_map=styles.markdown_style)\n", "output": "from .. import styles"}
{"instruction": "", "input": "\nfrom reflex.components.radix.themes.base import LiteralAccentColor, LiteralGrayColor\n\nfrom .. import styles\nfrom ..templates.template import ThemeState\n\nprimary_color_dict: dict[str, str] = {\n color.capitalize(): f\"linear-gradient(45deg, {rx.color(color, 10)}, {rx.color(color, 8)})\"\n for color in LiteralAccentColor.__args__\n}\n\nsecondary_color_dict: dict[str, str] = {\n color.capitalize(): f\"linear-gradient(45deg, {rx.color(color, 10)}, {rx.color(color, 8)})\"\n for color in LiteralGrayColor.__args__\n if color != \"auto\" # Remove auto from the list\n}\n\n\nclass ColorPickerState(rx.State):\n primary_color_options: dict[str, str] = primary_color_dict\n secondary_color_options: dict[str, str] = secondary_color_dict\n\n\ndef _display_primary_color(color: list) -> rx.Component:\n return rx.tooltip(\n rx.box(\n rx.cond(\n color[0].lower() == ThemeState.accent_color.lower(),\n rx.box(\n rx.icon(\"check\", color=rx.color(\"", "output": "import reflex as rx"}
{"instruction": "er\": \"Executive summary\",\n \"section_type\": \"Narrative\",\n \"status\": \"Done\",\n \"target\": 10,\n \"limit\": 13,\n \"reviewer\": \"Eddie Lake\",\n }\n )\n self.document_data[3].update(\n {\n \"header\": \"Technical approach\",\n \"section_type\": \"Narrative\",\n \"status\": \"Done\",\n \"target\": 27,\n \"limit\": 23,\n \"reviewer\": \"Jamik Tashpulatov\",\n }\n )\n\n @rx.event\n def load_initial_data(self):\n \"\"\"Load initial fake data if not already loaded.\"\"\"\n if (\n not self.key_metrics\n and (not self.visitor_data)\n and (not self.document_data)\n ):\n self._generate_fake_data()\n\n @rx.event\n def set_visitor_timeframe(self, timeframe: str):\n self.selected_visitor_timeframe = timeframe\n\n if timeframe == \"Last 3 months\":\n ", "input": "\n\n if timeframe == \"Last 30 days\":\n self.displayed_visitor_data = self.visitor_data[-30:]\n\n if timeframe == \"Last 7 days\":\n self.displayed_visitor_data = self.visitor_data[-7:]\n\n @rx.event\n def set_document_tab(self, tab: str):\n self.selected_document_tab = tab\n\n\nTOOLTIP_PROPS = {\n \"separator\": \": \",\n \"cursor\": False,\n \"is_animation_active\": False,\n \"label_style\": {\"fontWeight\": \"500\"},\n \"item_style\": {\n \"color\": \"currentColor\",\n \"display\": \"flex\",\n \"paddingBottom\": \"0px\",\n \"justifyContent\": \"space-between\",\n \"textTransform\": \"capitalize\",\n },\n \"content_style\": {\n \"borderRadius\": \"5px\",\n \"boxShadow\": \"0px 2px 6px 0px rgba(0, 0, 0, 0.1)\",\n \"fontSize\": \"0.75rem\",\n \"lineHeight\": \"1rem\",\n \"fontWeight\": \"500\",\n \"minWidth\": \"8rem\",\n \"width\": \"auto\",\n \"padding\": \"0.375rem 0.625rem\",\n \"backgroundColor\": \"white\",\n \"border\"", "output": "self.displayed_visitor_data = self.visitor_data"}
{"instruction": "import os\n\n", "input": "\n\ndatabase_url = os.getenv(\"DATABASE_URL\", \"sqlite:///reflex.db\")\n\nconfig = rx.Config(\n app_name=\"customer_data\",\n db_url=database_url,\n plugins=[rx.plugins.SitemapPlugin()],\n)\n", "output": "import reflex as rx"}
{"instruction": "\"\"\"Welcome to Reflex! This file outlines the steps to create a basic app.\"\"\"\n\nimport os\n\nimport openai\nimport reflex as rx\n\n_client = None\n\n\ndef get_openai_client():\n global _client\n if _client is None:\n _client = openai.OpenAI(api_key=os.getenv(\"OPENAI_API_KEY\"))\n\n return _client\n\n\nclass State(rx.State):\n \"\"\"The app state.\"\"\"\n\n ", "input": "\n image_processing = False\n image_made = False\n\n def get_dalle_result(self, form_data: dict[str, str]):\n prompt_text: str = form_data[\"prompt_text\"]\n self.image_made = False\n self.image_processing = True\n # Yield here so the image_processing take effects and the circular progress is shown.\n yield\n try:\n response = get_openai_client().images.generate(\n prompt=prompt_text, n=1, size=\"1024x1024\"\n )\n self.image_url = response.data[0].url\n self.image_processing = False\n self.image_made = True\n yield\n except Exception as ex:\n self.image_processing = False\n yield rx.window_alert(f\"Error with OpenAI Execution. {ex}\")\n\n\ndef index():\n return rx.center(\n rx.vstack(\n rx.heading(\"DALL-E\", font_size=\"1.5em\"),\n rx.form(\n rx.vstack(\n rx.input(\n id=\"prompt_", "output": "image_url = \"\""}
{"instruction": "", "input": "\nfrom pathlib import Path\nfrom typing import List\n\nimport reflex as rx\n\n\nclass Item(rx.Base):\n \"\"\"The item class.\"\"\"\n\n name: str\n payment: float\n date: str\n status: str\n\n\nclass TableState(rx.State):\n \"\"\"The state class.\"\"\"\n\n items: List[Item] = []\n\n search_value: str = \"\"\n sort_value: str = \"\"\n sort_reverse: bool = False\n\n total_items: int = 0\n offset: int = 0\n limit: int = 12 # Number of rows per page\n\n @rx.event\n def set_search_value(self, value: str):\n self.search_value = value\n\n @rx.event\n def set_sort_value(self, value: str):\n self.sort_value = value\n\n @rx.var(cache=True)\n def filtered_sorted_items(self) -> List[Item]:\n items = self.items\n\n # Filter items based on selected item\n if self.sort_value:\n if self.sort_value in [\"payment\"]:\n items = sorted(\n items,\n key=lambda item: float(getattr(item, self.sort_value)),\n ", "output": "import csv"}
{"instruction": " item\n for item in items\n if any(\n search_value in str(getattr(item, attr)).lower()\n for attr in [\n \"name\",\n \"payment\",\n \"date\",\n \"status\",\n ]\n )\n ]\n\n return items\n\n @rx.var(cache=True)\n def page_number(self) -> int:\n return (self.offset // self.limit) + 1\n\n @rx.var(cache=True)\n def total_pages(self) -> int:\n return (self.total_items // self.limit) + (\n 1 if self.total_items % self.limit else 1\n )\n\n @rx.var(cache=True, initial_value=[])\n def get_current_page(self) -> list[Item]:\n start_index = self.offset\n end_index = start_index + self.limit\n return self.filtered_sorted_items[start_index:end_index]\n\n def prev_page(self):\n if self.page_number > 1:\n self.offset -= self.limit\n\n ", "input": "\n\n def first_page(self):\n self.offset = 0\n\n def last_page(self):\n self.offset = (self.total_pages - 1) * self.limit\n\n def load_entries(self):\n with Path(\"items.csv\").open(mode=\"r\", encoding=\"utf-8\") as file:\n reader = csv.DictReader(file)\n self.items = [Item(**row) for row in reader]\n self.total_items = len(self.items)\n\n def toggle_sort(self):\n self.sort_reverse = not self.sort_reverse\n self.load_entries()\n", "output": "def next_page(self):\n if self.page_number < self.total_pages:\n self.offset += self.limit"}
{"instruction": "\"\"\"Common templates used between pages in the app.\"\"\"\n\nfrom __future__ import annotations\n\nfrom typing import Callable\n\nimport reflex as rx\n\nfrom .. import styles\nfrom ..components.navbar import navbar\nfrom ..components.sidebar import sidebar\n\n# Meta tags for the app.\ndefault_meta = [\n {\n \"name\": \"viewport\",\n \"content\": \"width=device-width, shrink-to-fit=no, initial-scale=1\",\n },\n]\n\n\n", "input": "\n\n\nclass ThemeState(rx.State):\n \"\"\"The state for the theme of the app.\"\"\"\n\n accent_color: str = \"crimson\"\n\n gray_color: str = \"gray\"\n\n radius: str = \"large\"\n\n scaling: str = \"100%\"\n\n @rx.event\n def set_scaling(self, value: str):\n self.scaling = value\n\n @rx.event\n def set_radius(self, value: str):\n self.radius = value\n\n @rx.event\n def set_accent_color(self, value: str):\n self.accent_color = value\n\n @rx.event\n def set_gray_color(self, value: str):\n self.gray_color = value\n\n\nALL_PAGES = []\n\n\ndef template(\n route: str | None = None,\n title: str | None = None,\n description: str | None = None,\n meta: str | None = None,\n script_tags: list[rx.Component] | None = None,\n on_load: rx.event.EventType[()] | None = None,\n) -> Callable[[Callable[[], rx.Component]], rx.Component]:\n \"\"\"The template for each page of the app.\n\n Args:\n route: The route to reach the page.\n title: The title of the page.\n", "output": "def menu_item_link(text, href):\n return rx.menu.item(\n rx.link(\n text,\n href=href,\n width=\"100%\",\n color=\"inherit\",\n ),\n _hover={\n \"color\": styles.accent_color,\n \"background_color\": styles.accent_text_color,\n },\n )"}
{"instruction": "", "input": "\n\nfrom ..templates.template import ThemeState\n\n\ndef radius_picker() -> rx.Component:\n return (\n rx.vstack(\n rx.hstack(\n rx.icon(\"radius\"),\n rx.heading(\"Radius\", size=\"6\"),\n align=\"center\",\n ),\n rx.select(\n [\n \"none\",\n \"small\",\n \"medium\",\n \"large\",\n \"full\",\n ],\n size=\"3\",\n value=ThemeState.radius,\n on_change=ThemeState.set_radius,\n ),\n width=\"100%\",\n ),\n )\n", "output": "import reflex as rx"}
{"instruction": "import reflex as rx\n\nfrom manufacturing_dashboard.states.dashboard_state import DashboardState\n\n\ndef time_completion_circle() -> rx.Component:\n \"\"\"Renders the circular progress indicator for time to completion.\"\"\"\n ", "input": "\n return rx.el.svg(\n rx.el.circle(\n cx=\"50\",\n cy=\"50\",\n r=str(radius),\n stroke=\"#334155\",\n stroke_width=\"8\",\n fill=\"none\",\n class_name=\"text-slate-700\",\n ),\n rx.el.circle(\n cx=\"50\",\n cy=\"50\",\n r=str(radius),\n stroke=\"#06b6d4\",\n stroke_width=\"8\",\n fill=\"none\",\n stroke_dasharray=DashboardState.get_time_stroke_dasharray,\n stroke_linecap=\"round\",\n transform=\"rotate(-90 50 50)\",\n class_name=\"transition-all duration-300 ease-linear\",\n ),\n rx.el.text(\n DashboardState.time_to_completion.to(int).to_string() + \"%\",\n x=\"50\",\n y=\"50\",\n text_anchor=\"middle\",\n dominant_baseline=\"middle\",\n font_size=\"18\",\n font_weight=\"bold\",\n fill=\"#cbd5e1\",\n ),\n view_box=\"0 0 100 100\",\n ", "output": "radius = 40"}
{"instruction": " \"value\": metric[\"ooc_percent\"],\n \"fill\": fill_color,\n }\n )\n if not pie_data:\n default_low_ooc = [\n (\"Diameter\", 0.5),\n (\"Etch1\", 0.3),\n ]\n for name, value in default_low_ooc:\n pie_data.append(\n {\n \"name\": name,\n \"value\": value,\n \"fill\": colors_pass[color_index_pass % len(colors_pass)],\n }\n )\n color_index_pass += 1\n return pie_data\n\n\ndef _generate_distribution_data(\n spc_data: List[SpcDataPoint], num_bins=8\n) -> List[DistributionPoint]:\n \"\"\"Generates histogram-like data from SPC points.\"\"\"\n if not spc_data:\n return []\n values = [p[\"value\"] for p in spc_data]\n min_val, max_val = (min(values), max(values))\n if min_val == max_val:\n return [{\"name\": f\"{min_val:.3f}\", \"value\": len(values)}]\n bin_width = (max_val - min_val) / num_bins\n ", "input": "\n for val in values:\n bin_index = min(int((val - min_val) / bin_width), num_bins - 1)\n if val == max_val:\n bin_index = num_bins - 1\n bins[bin_index] += 1\n dist_data = []\n for i in range(num_bins):\n bin_start = min_val + i * bin_width\n bin_name = f\"{bin_start:.3f}\"\n dist_data.append({\"name\": bin_name, \"value\": bins[i]})\n return dist_data\n\n\ninitial_process_metrics = _generate_process_metrics()\ninitial_spc_data = _generate_spc_data(base_min=0.415, base_max=0.424)\ninitial_pie_data = _generate_pie_data(initial_process_metrics)\ninitial_distribution_data = _generate_distribution_data(initial_spc_data)\n\n\nclass DashboardState(rx.State):\n \"\"\"Handles the state and logic for the dashboard application.\"\"\"\n\n operator_id: str = fake.bothify(text=\"OP-####\")\n time_to_completion: float = 0.0\n is_running: bool = False\n ucl: float = 0.432\n lcl: float = 0.407\n target_mean: float = 0.42\n usl: float = 0.424\n lsl: floa", "output": "bins = [0] * num_bins"}
{"instruction": " = False\n ucl: float = 0.432\n lcl: float = 0.407\n target_mean: float = 0.42\n usl: float = 0.424\n lsl: float = 0.415\n process_metrics: List[MetricData] = initial_process_metrics\n spc_chart_data: List[SpcDataPoint] = initial_spc_data\n pie_data: List[PieChartData] = initial_pie_data\n distribution_data: List[DistributionPoint] = initial_distribution_data\n\n def _reset_to_initial(self):\n \"\"\"Resets data to a new initial state.\"\"\"\n self.process_metrics = _generate_process_metrics()\n self.spc_chart_data = _generate_spc_data(base_min=self.lsl, base_max=self.usl)\n self.pie_data = _generate_pie_data(self.process_metrics)\n self.distribution_data = _generate_distribution_data(self.spc_chart_data)\n\n @rx.event(background=True)\n async def start_process(self):\n \"\"\"Simulates starting a process and updating data over time using Faker.\"\"\"\n async with self:\n if self.is_running:\n return\n ", "input": "\n self.time_to_completion = 0.0\n update_interval = 0.1\n data_gen_interval = 10\n metrics_update_interval = 30\n for i in range(101):\n async with self:\n self.time_to_completion = float(i)\n if i > 0 and i % data_gen_interval == 0:\n last_name = (\n self.spc_chart_data[-1][\"name\"] if self.spc_chart_data else -1\n )\n new_name = last_name + 1\n new_value_base = fake.pyfloat(\n left_digits=0,\n right_digits=4,\n positive=True,\n min_value=self.lsl - 0.002,\n max_value=self.usl + 0.002,\n )\n if self.spc_chart_data:\n drift = random.uniform(-0.001, 0.001)\n new_value_base = self.spc_chart_data[-1][\"value\"] + drift\n if", "output": "self.is_running = True"}
{"instruction": " = _generate_process_metrics()\n self.spc_chart_data = _generate_spc_data(base_min=self.lsl, base_max=self.usl)\n self.pie_data = _generate_pie_data(self.process_metrics)\n self.distribution_data = _generate_distribution_data(self.spc_chart_data)\n\n @rx.event(background=True)\n async def start_process(self):\n \"\"\"Simulates starting a process and updating data over time using Faker.\"\"\"\n async with self:\n if self.is_running:\n return\n self.is_running = True\n self.time_to_completion = 0.0\n update_interval = 0.1\n data_gen_interval = 10\n metrics_update_interval = 30\n for i in range(101):\n async with self:\n self.time_to_completion = float(i)\n if i > 0 and i % data_gen_interval == 0:\n last_name = (\n self.spc_chart_data[-1][\"name\"] if self.spc_chart_data else -1\n )\n ", "input": "\n new_value_base = fake.pyfloat(\n left_digits=0,\n right_digits=4,\n positive=True,\n min_value=self.lsl - 0.002,\n max_value=self.usl + 0.002,\n )\n if self.spc_chart_data:\n drift = random.uniform(-0.001, 0.001)\n new_value_base = self.spc_chart_data[-1][\"value\"] + drift\n if random.random() < 0.08:\n new_value_base += random.uniform(0.003, 0.008)\n elif random.random() < 0.08:\n new_value_base -= random.uniform(0.003, 0.008)\n new_value = round(\n max(\n self.lcl - 0.01,\n min(\n self.ucl + 0.01,\n new_value_base,\n ),\n ", "output": "new_name = last_name + 1"}
{"instruction": " 4,\n )\n new_point: SpcDataPoint = {\n \"name\": new_name,\n \"value\": new_value,\n }\n self.spc_chart_data = ([*self.spc_chart_data, new_point])[-50:]\n self.distribution_data = _generate_distribution_data(\n self.spc_chart_data\n )\n if i > 0 and i % metrics_update_interval == 0:\n self.process_metrics = _generate_process_metrics()\n self.pie_data = _generate_pie_data(self.process_metrics)\n await asyncio.sleep(update_interval)\n yield\n async with self:\n self.is_running = False\n self._reset_to_initial()\n\n @rx.var\n def get_time_stroke_dasharray(self) -> str:\n \"\"\"Calculates the stroke-dasharray for the time completion circle.\"\"\"\n percentage = self.time_to_completion\n radius = 40\n ", "input": "\n clamped_percentage = max(0, min(percentage, 100))\n dash_length = clamped_percentage / 100 * circumference\n dash_length = max(0, dash_length)\n gap_length = max(0, circumference - dash_length)\n return f\"{dash_length:.2f} {gap_length:.2f}\"\n\n @rx.var\n def ooc_points(self) -> List[SpcDataPoint]:\n \"\"\"Filters SPC data to find points outside control limits (OOC).\"\"\"\n ooc = []\n if not self.spc_chart_data:\n return []\n ooc = [\n point\n for point in self.spc_chart_data\n if isinstance(point.get(\"value\"), (int, float))\n and (point[\"value\"] < self.lcl or point[\"value\"] > self.ucl)\n ]\n\n return ooc\n", "output": "circumference = 2 * 3.14159 * radius"}
{"instruction": "from typing import Dict, List\n\nimport numpy as np\nimport pandas as pd\nimport reflex as rx\n\nfrom .data_items import all_items\n", "input": "\n\nnba_csv = \"nbastats.csv\"\n\n\nclass State(rx.State):\n \"\"\"The app state.\"\"\"\n\n players: list[Player] = []\n\n search_value: str = \"\"\n sort_value: str = \"\"\n sort_reverse: bool = False\n\n total_items: int = 0\n offset: int = 0\n limit: int = 12 # Number of rows per page\n\n selected_items: Dict[str, List] = (\n all_items # We add all items to the selected items by default\n )\n age: tuple[int, int] = (19, 40)\n salary: tuple[int, int] = (0, 25000000)\n\n @rx.event\n def set_age(self, value: list[int | float]):\n self.age = (int(value[0]), int(value[1]))\n\n @rx.event\n def set_salary(self, value: list[int | float]):\n self.salary = (int(value[0]), int(value[1]))\n\n @rx.event\n def set_sort_value(self, value: str):\n self.sort_value = value\n\n @rx.event\n def set_search_value(self, value: str):\n self.search_value = value\n\n @rx.var(cache=True)\n def filtered_sorted_players(self) -> list[Player]:\n players = se", "output": "from .player import Player"}
{"instruction": "lleges\"]\n and player.position in self.selected_items[\"positions\"]\n and self.age[0] <= player.age <= self.age[1]\n and self.salary[0] <= float(player.salary) <= self.salary[1]\n ):\n age = player.age\n if age not in age_salary_data:\n age_salary_data[age] = 0\n age_count[age] = 0\n\n age_salary_data[age] += float(player.salary)\n age_count[age] += 1\n\n return [\n {\n \"age\": age,\n \"average salary\": round(\n age_salary_data.get(age, 0) / age_count.get(age, 1), 2\n ),\n }\n for age in range(self.age[0], self.age[1] + 1) # Ensure we include all ages\n ]\n\n @rx.var(cache=True)\n def get_position_salary_chart_data(self) -> list[dict]:\n position_salary_data = {}\n position_count = {}\n\n for player in self.players:\n ", "input": "\n\n return [\n {\n \"position\": position,\n \"average salary\": round(\n position_salary_data[position] / position_count[position], 2\n ),\n }\n for position in position_salary_data\n ]\n\n @rx.var(cache=True)\n def get_team_salary_chart_data(self) -> list[dict]:\n team_salary_data = {}\n team_count = {}\n\n for player in self.players:\n if (\n not pd.isna(player.team)\n and not pd.isna(player.salary)\n and player.team in self.selected_items[\"teams\"]\n and player.college in self.selected_items[\"colleges\"]\n and player.position in self.selected_items[\"positions\"]\n and self.age[0] <= player.age <= self.age[1]\n and self.salary[0] <= float(player.salary) <= self.salary[1]\n ):\n team = player.team\n if team not in team_salary_d", "output": "if (\n not pd.isna(player.position)\n and not pd.isna(player.salary)\n and player.team in self.selected_items[\"teams\"]\n and player.college in self.selected_items[\"colleges\"]\n and player.position in self.selected_items[\"positions\"]\n and self.age[0] <= player.age <= self.age[1]\n and self.salary[0] <= float(player.salary) <= self.salary[1]\n ):\n position = player.position\n if position not in position_salary_data:\n position_salary_data[position] = 0\n position_count[position] = 0\n\n position_salary_data[position] += float(player.salary)\n position_count[position] += 1"}
{"instruction": "lleges\"]\n and player.position in self.selected_items[\"positions\"]\n and self.age[0] <= player.age <= self.age[1]\n and self.salary[0] <= float(player.salary) <= self.salary[1]\n ):\n position = player.position\n if position not in position_age_data:\n position_age_data[position] = []\n position_count[position] = 0\n\n position_age_data[position].append(player.age)\n position_count[position] += 1\n\n return [\n {\n \"position\": position,\n \"average age\": round(sum(ages) / position_count[position], 2),\n }\n for position, ages in position_age_data.items()\n ]\n\n def add_selected(self, list_name: str, item: str):\n self.selected_items[list_name].append(item)\n\n def remove_selected(self, list_name: str, item: str):\n self.selected_items[list_name].remove(item)\n\n ", "input": "\n\n def clear_selected(self, list_name: str):\n self.selected_items[list_name].clear()\n\n def random_selected(self, list_name: str):\n self.selected_items[list_name] = np.random.choice(\n all_items[list_name],\n size=np.random.randint(1, len(all_items[list_name]) + 1),\n replace=False,\n ).tolist()\n", "output": "def add_all_selected(self, list_name: str):\n self.selected_items[list_name] = list(all_items[list_name])"}
{"instruction": "alue\": \"$200\",\n \"value_num\": 200.0,\n \"percentage\": 68.1,\n \"color\": \"bg-indigo-600\",\n },\n {\n \"label\": \"On-demand charges\",\n \"value\": \"$61.1\",\n \"value_num\": 61.1,\n \"percentage\": 20.8,\n \"color\": \"bg-purple-600\",\n },\n {\n \"label\": \"Caching\",\n \"value\": \"$31.9\",\n \"value_num\": 31.9,\n \"percentage\": 11.1,\n \"color\": \"bg-gray-400\",\n },\n ]\n overview_metrics: List[OverviewMetric] = overview_metrics_data\n chart_visibility: Dict[str, bool] = {\n metric[\"id\"]: True for metric in overview_metrics_data\n }\n temp_chart_visibility: Dict[str, bool] = {}\n show_customize_dialog: bool = False\n\n @rx.var\n def current_total_cost(self) -> float:\n \"\"\"Calculates the current total cost from the breakdown items.\"\"\"\n return sum((item[\"value_num\"] for item in self.billing_costs_items))\n\n @rx.var\n ", "input": "\n\n @rx.var\n def remaining_budget_percentage(self) -> float:\n \"\"\"Calculates the remaining budget percentage.\"\"\"\n if self.total_budget == 0:\n return 0.0\n percentage = self.remaining_budget_value / self.total_budget * 100\n return round(percentage * 10) / 10\n\n @rx.var\n def total_cost_percentage(self) -> float:\n \"\"\"Calculates the total percentage used based on cost items.\"\"\"\n return sum((item[\"percentage\"] for item in self.billing_costs_items))\n\n @rx.var\n def visible_overview_metrics(\n self,\n ) -> List[OverviewMetric]:\n \"\"\"Returns the list of overview metrics that are marked as visible.\"\"\"\n return [\n metric\n for metric in self.overview_metrics\n if self.chart_visibility.get(metric[\"id\"], False)\n ]\n\n @rx.event\n def set_active_nav(self, item_name: str):\n new_nav_items = []\n for item in self.nav_items:\n new_item = item.copy()\n ", "output": "def remaining_budget_value(self) -> float:\n \"\"\"Calculates the remaining budget value.\"\"\"\n return self.total_budget - self.current_total_cost"}
{"instruction": "rx.var\n def remaining_budget_percentage(self) -> float:\n \"\"\"Calculates the remaining budget percentage.\"\"\"\n if self.total_budget == 0:\n return 0.0\n percentage = self.remaining_budget_value / self.total_budget * 100\n return round(percentage * 10) / 10\n\n @rx.var\n def total_cost_percentage(self) -> float:\n \"\"\"Calculates the total percentage used based on cost items.\"\"\"\n return sum((item[\"percentage\"] for item in self.billing_costs_items))\n\n @rx.var\n def visible_overview_metrics(\n self,\n ) -> List[OverviewMetric]:\n \"\"\"Returns the list of overview metrics that are marked as visible.\"\"\"\n return [\n metric\n for metric in self.overview_metrics\n if self.chart_visibility.get(metric[\"id\"], False)\n ]\n\n @rx.event\n def set_active_nav(self, item_name: str):\n new_nav_items = []\n for item in self.nav_items:\n new_item = item.copy()\n ", "input": "\n new_nav_items.append(new_item)\n self.nav_items = new_nav_items\n\n @rx.event\n def toggle_customize_dialog(self):\n \"\"\"Toggles the customize charts dialog and initializes temporary visibility.\"\"\"\n self.show_customize_dialog = not self.show_customize_dialog\n if self.show_customize_dialog:\n self.temp_chart_visibility = self.chart_visibility.copy()\n\n @rx.event\n def toggle_temp_chart_visibility(self, chart_id: str):\n \"\"\"Toggles the visibility of a specific chart in the temporary state.\"\"\"\n if chart_id in self.temp_chart_visibility:\n self.temp_chart_visibility[chart_id] = not self.temp_chart_visibility[\n chart_id\n ]\n\n @rx.event\n def apply_chart_visibility(self):\n \"\"\"Applies the temporary visibility settings to the actual state and closes the dialog.\"\"\"\n self.chart_visibility = self.temp_chart_visibility.copy()\n self.show_customize_dialog = False\n\n @rx.", "output": "new_item[\"active\"] = item[\"name\"] == item_name"}
{"instruction": " self.nav_items:\n new_item = item.copy()\n new_item[\"active\"] = item[\"name\"] == item_name\n new_nav_items.append(new_item)\n self.nav_items = new_nav_items\n\n @rx.event\n def toggle_customize_dialog(self):\n \"\"\"Toggles the customize charts dialog and initializes temporary visibility.\"\"\"\n self.show_customize_dialog = not self.show_customize_dialog\n if self.show_customize_dialog:\n self.temp_chart_visibility = self.chart_visibility.copy()\n\n @rx.event\n def toggle_temp_chart_visibility(self, chart_id: str):\n \"\"\"Toggles the visibility of a specific chart in the temporary state.\"\"\"\n if chart_id in self.temp_chart_visibility:\n self.temp_chart_visibility[chart_id] = not self.temp_chart_visibility[\n chart_id\n ]\n\n @rx.event\n def apply_chart_visibility(self):\n \"\"\"Applies the temporary visibility settings to the actual state and closes the dialog.\"\"\"\n ", "input": "\n self.show_customize_dialog = False\n\n @rx.event\n def cancel_chart_visibility(self):\n \"\"\"Closes the dialog without applying changes.\"\"\"\n self.show_customize_dialog = False\n", "output": "self.chart_visibility = self.temp_chart_visibility.copy()"}
{"instruction": "em[\"costs\"]\n except ValueError:\n return None\n\n @rx.var\n def total_entries_count(self) -> int:\n \"\"\"Total number of entries in the raw data.\"\"\"\n return len(self._data)\n\n @rx.var\n def live_entries_count(self) -> int:\n \"\"\"Count of 'Live' entries.\"\"\"\n return sum((1 for item in self._data if item[\"status\"] == \"Live\"))\n\n @rx.var\n def inactive_entries_count(self) -> int:\n \"\"\"Count of 'Inactive' entries.\"\"\"\n return sum((1 for item in self._data if item[\"status\"] == \"Inactive\"))\n\n @rx.var\n def archived_entries_count(self) -> int:\n \"\"\"Count of 'Archived' entries.\"\"\"\n return sum((1 for item in self._data if item[\"status\"] == \"Archived\"))\n\n @rx.var\n def costs_trend_data(\n self,\n ) -> List[Dict[str, str | float]]:\n \"\"\"Data for the costs trend line chart.\"\"\"\n daily_costs = defaultdict(float)\n\n input_format = \"%d/%m/%Y %H:%M\"\n output_format = \"%Y-%m-%d\"\n ", "input": "\n\n valid_items = []\n for item in self._data:\n parsed_item = self._parse_datetime_for_costs(item, input_format)\n if parsed_item:\n valid_items.append(parsed_item)\n\n for dt_obj, cost in valid_items:\n date_str = dt_obj.strftime(output_format)\n daily_costs[date_str] += cost\n\n sorted_dates = sorted(daily_costs.keys())\n chart_data: List[Dict[str, str | float]] = [\n {\n \"date\": datetime.datetime.strptime(date_str, output_format).strftime(\n display_format\n ),\n \"total_costs\": round(daily_costs[date_str], 2),\n }\n for date_str in sorted_dates\n ]\n return chart_data\n\n @rx.var\n def recent_activities(self) -> List[DetailEntry]:\n \"\"\"Get the 5 most recent activities based on last_edited date.\"\"\"\n # Precompute sort keys to move try-except out of the sorting process itself\n item", "output": "display_format = \"%b %d\""}
{"instruction": "", "input": "\n\nimport reflex as rx\n\n\nclass ChartData(TypedDict):\n name: str\n value: int\n percentage: float\n fill: str\n\n\nclass WorkflowState(rx.State):\n \"\"\"State for the Workflow tab.\"\"\"\n\n test_quota: int = 34\n departments: List[str] = [\n \"Customer Service\",\n \"Technical Support\",\n \"Billing Support\",\n \"Claims Processing\",\n \"Account Management\",\n \"Sales Support\",\n ]\n excluded_departments: Dict[str, bool] = {dept: False for dept in departments}\n completed_cases_data: list[ChartData] = [\n {\n \"name\": \"Completed\",\n \"value\": 11327,\n \"percentage\": 100.0,\n \"fill\": \"#3b82f6\",\n }\n ]\n test_results_data_tested: list[ChartData] = [\n {\n \"name\": \"Tested\",\n \"value\": 3874,\n \"percentage\": 34.2,\n \"fill\": \"#3b82f6\",\n }\n ]\n test_results_data_untested: list[ChartData] = [\n {\n \"name\": \"Untested\",\n ", "output": "from typing import Dict, List, TypedDict"}
{"instruction": "\": 11327,\n \"percentage\": 100.0,\n \"fill\": \"#3b82f6\",\n }\n ]\n test_results_data_tested: list[ChartData] = [\n {\n \"name\": \"Tested\",\n \"value\": 3874,\n \"percentage\": 34.2,\n \"fill\": \"#3b82f6\",\n }\n ]\n test_results_data_untested: list[ChartData] = [\n {\n \"name\": \"Untested\",\n \"value\": 7453,\n \"percentage\": 65.8,\n \"fill\": \"#d1d5db\",\n }\n ]\n impact_data_error_free: list[ChartData] = [\n {\n \"name\": \"Error-free\",\n \"value\": 3413,\n \"percentage\": 30.1,\n \"fill\": \"#10b981\",\n }\n ]\n impact_data_corrected: list[ChartData] = [\n {\n \"name\": \"Corrected\",\n \"value\": 461,\n \"percentage\": 4.1,\n \"fill\": \"#ef4444\",\n }\n ]\n\n @rx.event\n def set_test_quota(self, value: str):\n \"\"\"Sets the test quota value from the slider.\"\"\"\n ", "input": "\n\n @rx.event\n def toggle_department(self, dept_name: str):\n \"\"\"Toggles the exclusion status of a department.\"\"\"\n self.excluded_departments[dept_name] = not self.excluded_departments[dept_name]\n", "output": "self.test_quota = int(value)"}
{"instruction": "", "input": "\n\nfrom space_dashboard.components.section_wrapper import section_wrapper\nfrom space_dashboard.states.dashboard_state import (\n ComData,\n DashboardState,\n)\n\n\ndef hq_com_item(data: ComData) -> rx.Component:\n \"\"\"Displays a single HQ Coms channel.\"\"\"\n return rx.el.div(\n rx.el.p(\n f\"{data['channel']} [{data['value'].to_string()}]\",\n class_name=\"text-sm text-cyan-300 font-mono\",\n ),\n class_name=\"p-1\",\n )\n\n\ndef hq_coms_section() -> rx.Component:\n \"\"\"The HQ Communications section.\"\"\"\n return section_wrapper(\n \"HQ_COMS\",\n rx.el.div(\n rx.foreach(DashboardState.hq_coms_data, hq_com_item),\n class_name=\"grid grid-cols-2 gap-x-4 gap-y-1\",\n ),\n )\n", "output": "import reflex as rx"}
{"instruction": "n \" ยท \".join(filter(None, display_parts))\n\n @rx.var\n def current_price_display_val(self) -> str:\n price = self.company_info.get(\"currentPrice\") or self.company_info.get(\n \"regularMarketPrice\"\n )\n if price is not None:\n return f\"{price:.2f}\"\n return \"N/A\"\n\n @rx.var\n def market_cap_display_val(self) -> str:\n return format_market_cap(self.company_info.get(\"marketCap\"))\n\n @rx.var\n def is_market_currently_active(self) -> bool:\n \"\"\"Determines if the market is currently in an active trading session (regular, pre, or post).\"\"\"\n market_state = self.company_info.get(\"marketState\", \"\").upper()\n # Active states include regular market, pre-market, and post-market trading\n active_states = [\"REGULAR\", \"PRE\", \"POST\", \"POSTPOST\"]\n return market_state in active_states\n\n @rx.var\n def _after_hours_data(self) -> tuple[float | None, float | None, str]:\n info = self.company_info\n ", "input": "\n\n if market_state == \"PRE\":\n price = info.get(\"preMarketPrice\")\n change = info.get(\"preMarketChange\")\n if price is not None and change is not None:\n return price, change, \"Pre-Market\"\n elif market_state in [\"POST\", \"POSTPOST\", \"CLOSED\"]:\n price = info.get(\"postMarketPrice\")\n change = info.get(\"postMarketChange\")\n if price is not None and change is not None:\n return price, change, \"After Hours\"\n\n return None, None, \"\"\n\n @rx.var\n def after_hours_price_display_val(self) -> str:\n price, _, _ = self._after_hours_data\n if price is not None:\n return f\"{price:.2f}\"\n return \"\"\n\n @rx.var\n def after_hours_change_display_val(self) -> str:\n _, change, _ = self._after_hours_data\n if change is not None:\n sign = \"+\" if change > 0 else \"\"\n return f\"{sign}{change:.2f}\"\n return \"\"\n\n @rx.var\n def a", "output": "market_state = info.get(\"marketState\")"}
{"instruction": "trading_state import TradingState\n\n\ndef options_header(\n stock_symbol: str,\n price: rx.Var[float],\n change: rx.Var[float],\n change_percent: rx.Var[float],\n) -> rx.Component:\n return rx.el.div(\n rx.el.span(\n f\"{stock_symbol}\",\n class_name=\"text-sm font-bold text-white mr-2\",\n ),\n rx.el.span(\n price.to_string(),\n class_name=\"text-sm font-semibold text-white mr-1\",\n ),\n rx.el.span(\n change.to_string(),\n class_name=rx.cond(\n change >= 0,\n \"text-green-400 text-xs\",\n \"text-red-400 text-xs\",\n ),\n ),\n rx.el.span(\n change_percent.to_string(),\n class_name=rx.cond(\n change >= 0,\n \"text-green-400 text-xs ml-1\",\n \"text-red-400 text-xs ml-1\",\n ),\n ),\n class_name=\"mb-2 px-2\",\n )\n\n\ndef options_sub_tabs() -> rx.Component:\n ", "input": "\n return rx.el.div(\n rx.foreach(\n tabs,\n lambda tab: rx.el.button(\n tab,\n on_click=TradingState.set_active_sub_tab(tab),\n class_name=rx.cond(\n TradingState.active_sub_tab == tab,\n \"text-xs text-white bg-gray-700 px-3 py-1 rounded\",\n \"text-xs text-gray-400 hover:text-white px-3 py-1\",\n ),\n ),\n ),\n class_name=\"flex space-x-2 border-b border-gray-700 mb-2 pb-1 px-2 overflow-x-auto\",\n )\n\n\ndef render_option_cell(\n value: rx.Var,\n class_name: str,\n is_numeric: bool = True,\n format_spec: str = \".2f\",\n prefix: str = \"\",\n suffix: str = \"\",\n) -> rx.Component:\n formatted_value = rx.cond(value, value.to_string(), \"-\")\n return rx.el.td(formatted_value, class_name=class_name)\n\n\ndef render_combined_option_row(\n item: rx.Var[dict[str, dict[str, int]]],\n) -> rx.Component:\n call_option = item[\"call\"]", "output": "tabs = [\n \"4D Fri Oct 18\",\n \"11D Fri Oct 25\",\n \"18D Fri Nov 1\",\n \"25D Fri Nov 8\",\n \"32D Fri Nov 15\",\n ]"}
{"instruction": " ]\n ),\n ),\n rx.el.td(\n strike.to_string(),\n class_name=rx.cond(\n is_near_the_money,\n \"px-3 py-1 text-xs text-center font-bold text-white bg-yellow-700\",\n \"px-3 py-1 text-xs text-center font-bold text-white bg-gray-600\",\n ),\n ),\n rx.cond(\n put_option,\n rx.fragment(\n *[\n render_option_cell(put_option[key], cn, *fmt)\n for key, cn, *fmt in put_headers_config\n ]\n ),\n rx.fragment(\n *[\n rx.el.td(\n \"-\",\n class_name=\"px-2 py-1 text-xs text-gray-500 text-left\",\n )\n for _ in put_headers_config\n ]\n ),\n ),\n class_name=\"border-b border-gray-700 hover:bg-gray-700\",\n )\n\n\ndef options_table() -> rx.Component:\n ", "input": "\n put_headers = [\n \"Bid\",\n \"Ask\",\n \"Delta\",\n \"OI\",\n \"Volume\",\n \"IV\",\n \"Change % to\",\n \"Mark\",\n \"Gamma\",\n ]\n return rx.el.div(\n options_header(\n TradingState.stock_info[\"symbol\"],\n TradingState.stock_info[\"price\"],\n TradingState.stock_info[\"change\"],\n TradingState.stock_info[\"change_percent\"],\n ),\n options_sub_tabs(),\n rx.el.div(\n rx.el.table(\n rx.el.thead(\n rx.el.tr(\n rx.el.th(\n \"Calls\",\n col_span=len(call_headers),\n 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\",\n ),\n rx.el.th(\n \"Strike\",\n class_name=\"text-sm font-semibold tex", "output": "call_headers = [\n \"Mark\",\n \"% to\",\n \"Delta\",\n \"OI\",\n \"Volume\",\n \"IV\",\n \"Low\",\n \"High\",\n \"Bid\",\n \"Ask\",\n ]"}
{"instruction": "", "input": "\n\nfrom table_dashboard.components.details_table import details_table\nfrom table_dashboard.components.header import header\nfrom table_dashboard.components.sidebar import sidebar\nfrom table_dashboard.states.dashboard_state import DashboardState\n\n\ndef index() -> rx.Component:\n \"\"\"The main dashboard page.\"\"\"\n return rx.el.div(\n sidebar(),\n rx.el.main(\n rx.el.div(\n header(),\n details_table(),\n class_name=\"p-6 space-y-6\",\n ),\n class_name=\"flex-1 overflow-y-auto\",\n ),\n rx.el.div(\n class_name=rx.cond(\n DashboardState.show_status_filter\n | DashboardState.show_region_filter\n | DashboardState.show_costs_filter,\n \"fixed inset-0 z-5\",\n \"hidden\",\n ),\n on_click=DashboardState.close_filter_dropdowns,\n ),\n class_name=\"flex h-screen\",\n )\n\n\napp = rx.App(theme=rx.theme(app", "output": "import reflex as rx"}
{"instruction": "import reflex as rx\n\n", "input": "\n\n\ndef status_badge(status: rx.Var[str]) -> rx.Component:\n \"\"\"Creates a colored status badge.\"\"\"\n return rx.el.span(\n status,\n class_name=rx.match(\n status,\n (\n \"Live\",\n \"px-2 py-0.5 rounded-full text-xs font-medium bg-green-100 text-green-800\",\n ),\n (\n \"Inactive\",\n \"px-2 py-0.5 rounded-full text-xs font-medium bg-yellow-100 text-yellow-800\",\n ),\n (\n \"Archived\",\n \"px-2 py-0.5 rounded-full text-xs font-medium bg-gray-100 text-gray-800\",\n ),\n \"px-2 py-0.5 rounded-full text-xs font-medium bg-gray-100 text-gray-800\",\n ),\n )\n\n\ndef table_header_cell(name: str, is_sortable: bool = True) -> rx.Component:\n \"\"\"Creates a table header cell with optional sorting.\"\"\"\n return rx.el.th(\n rx.el.div(\n name,\n rx.cond(\n is_sortable,\n rx.", "output": "from table_dashboard.states.dashboard_state import (\n DashboardState,\n)"}
{"instruction": "ar\n def page_item_ids(self) -> Set[int]:\n \"\"\"Get the set of IDs for items on the current page.\"\"\"\n return {item[\"id\"] for item in self.paginated_data}\n\n @rx.var\n def all_rows_on_page_selected(self) -> bool:\n \"\"\"Check if all rows on the current page are selected.\"\"\"\n if not self.paginated_data:\n return False\n return self.page_item_ids.issubset(self.selected_rows)\n\n @rx.event\n def set_search_owner(self, value: str):\n \"\"\"Update the search owner filter.\"\"\"\n self.search_owner = value\n self.current_page = 1\n\n @rx.event\n def toggle_sort(self, column_name: str):\n \"\"\"Toggle sorting for a column.\"\"\"\n if self.sort_column == column_name:\n self.sort_ascending = not self.sort_ascending\n else:\n self.sort_column = column_name\n self.sort_ascending = True\n\n @rx.event\n def go_to_page(self, page_number: int):\n \"\"\"Navigate to a specific page.\"\"\"\n ", "input": "\n\n @rx.event\n def next_page(self):\n \"\"\"Go to the next page.\"\"\"\n if self.current_page < self.total_pages:\n self.current_page += 1\n\n @rx.event\n def previous_page(self):\n \"\"\"Go to the previous page.\"\"\"\n if self.current_page > 1:\n self.current_page -= 1\n\n @rx.event\n def toggle_row_selection(self, row_id: int):\n \"\"\"Toggle selection state for a single row using its ID.\"\"\"\n if row_id in self.selected_rows:\n self.selected_rows.remove(row_id)\n else:\n self.selected_rows.add(row_id)\n\n @rx.event\n def toggle_select_all_on_page(self):\n \"\"\"Select or deselect all rows on the current page.\"\"\"\n page_ids = self.page_item_ids\n if self.all_rows_on_page_selected:\n self.selected_rows -= page_ids\n else:\n self.selected_rows.update(page_ids)\n\n @rx.event\n def toggle_status_filter(self):\n is_opening = not self.show_status_filter\n ", "output": "if 1 <= page_number <= self.total_pages:\n self.current_page = page_number"}
{"instruction": " > 1:\n self.current_page -= 1\n\n @rx.event\n def toggle_row_selection(self, row_id: int):\n \"\"\"Toggle selection state for a single row using its ID.\"\"\"\n if row_id in self.selected_rows:\n self.selected_rows.remove(row_id)\n else:\n self.selected_rows.add(row_id)\n\n @rx.event\n def toggle_select_all_on_page(self):\n \"\"\"Select or deselect all rows on the current page.\"\"\"\n page_ids = self.page_item_ids\n if self.all_rows_on_page_selected:\n self.selected_rows -= page_ids\n else:\n self.selected_rows.update(page_ids)\n\n @rx.event\n def toggle_status_filter(self):\n is_opening = not self.show_status_filter\n self.show_status_filter = is_opening\n self.show_region_filter = False\n self.show_costs_filter = False\n if is_opening:\n self.temp_selected_statuses = self.selected_statuses.copy()\n\n @rx.event\n def toggle_region_filter(self):\n ", "input": "\n self.show_region_filter = is_opening\n self.show_status_filter = False\n self.show_costs_filter = False\n if is_opening:\n self.temp_selected_regions = self.selected_regions.copy()\n\n @rx.event\n def toggle_costs_filter(self):\n is_opening = not self.show_costs_filter\n self.show_costs_filter = is_opening\n self.show_status_filter = False\n self.show_region_filter = False\n if is_opening:\n self.temp_min_cost_str = (\n str(self.min_cost) if self.min_cost is not None else \"\"\n )\n self.temp_max_cost_str = (\n str(self.max_cost) if self.max_cost is not None else \"\"\n )\n\n @rx.event\n def toggle_temp_status(self, status: str):\n if status in self.temp_selected_statuses:\n self.temp_selected_statuses.remove(status)\n else:\n self.temp_selected_statuses.add(status)\n\n @rx.event\n def toggle_temp_region(self, region", "output": "is_opening = not self.show_region_filter"}
{"instruction": "\n\n @rx.event\n def toggle_select_all_on_page(self):\n \"\"\"Select or deselect all rows on the current page.\"\"\"\n page_ids = self.page_item_ids\n if self.all_rows_on_page_selected:\n self.selected_rows -= page_ids\n else:\n self.selected_rows.update(page_ids)\n\n @rx.event\n def toggle_status_filter(self):\n is_opening = not self.show_status_filter\n self.show_status_filter = is_opening\n self.show_region_filter = False\n self.show_costs_filter = False\n if is_opening:\n self.temp_selected_statuses = self.selected_statuses.copy()\n\n @rx.event\n def toggle_region_filter(self):\n is_opening = not self.show_region_filter\n self.show_region_filter = is_opening\n self.show_status_filter = False\n self.show_costs_filter = False\n if is_opening:\n self.temp_selected_regions = self.selected_regions.copy()\n\n @rx.event\n def toggle_costs_filter(self):\n ", "input": "\n self.show_costs_filter = is_opening\n self.show_status_filter = False\n self.show_region_filter = False\n if is_opening:\n self.temp_min_cost_str = (\n str(self.min_cost) if self.min_cost is not None else \"\"\n )\n self.temp_max_cost_str = (\n str(self.max_cost) if self.max_cost is not None else \"\"\n )\n\n @rx.event\n def toggle_temp_status(self, status: str):\n if status in self.temp_selected_statuses:\n self.temp_selected_statuses.remove(status)\n else:\n self.temp_selected_statuses.add(status)\n\n @rx.event\n def toggle_temp_region(self, region: str):\n if region in self.temp_selected_regions:\n self.temp_selected_regions.remove(region)\n else:\n self.temp_selected_regions.add(region)\n\n @rx.event\n def set_temp_min_cost(self, value: str):\n self.temp_min_cost_str = value\n\n @rx.event\n def set_temp_max_cost", "output": "is_opening = not self.show_costs_filter"}
{"instruction": " ),\n class_name=\"flex flex-wrap gap-2 p-4 items-center\",\n ),\n )\n ),\n add_label_form(),\n class_name=\"bg-gray-100 border-b border-gray-300 rounded-t-lg shadow-sm sticky top-0 z-10\",\n )\n\n\ndef render_segment(segment: Segment) -> rx.Component:\n \"\"\"Renders a single text segment, making it clickable if a label is selected.\"\"\"\n is_label_selected = NerState.selected_label_name is not None\n is_whitespace = segment[\"text\"].strip() == \"\"\n base_component = rx.el.span(segment[\"text\"])\n labeled_class = (\n segment[\"bg_color\"]\n + \" \"\n + segment[\"text_color\"]\n + \" py-0.5 rounded-sm cursor-pointer\"\n )\n labeled_component = rx.el.span(\n segment[\"text\"],\n rx.el.span(\n segment[\"label_name\"],\n class_name=\"text-[0.6rem] font-bold opacity-70 align-super\",\n ),\n class_name=labeled_class,\n title=segment[\"label_name\"],\n )\n ", "input": "\n styled_component = rx.cond(\n segment[\"label_name\"] is not None,\n labeled_component,\n rx.cond(\n is_label_selected & ~is_whitespace,\n hoverable_component,\n base_component,\n ),\n )\n on_click_event = rx.cond(\n is_label_selected & ~is_whitespace,\n NerState.apply_label(segment[\"id\"]),\n rx.noop(),\n )\n clickable_component = rx.el.span(\n styled_component,\n on_click=on_click_event,\n class_name=rx.cond(segment[\"label_name\"] is not None, \"\", \"inline\"),\n )\n return clickable_component\n\n\ndef text_display() -> rx.Component:\n \"\"\"Displays the processed text with highlighted entities.\"\"\"\n return rx.el.div(\n rx.el.p(\n rx.foreach(NerState.display_segments, render_segment),\n class_name=\"text-lg text-gray-800 whitespace-pre-wrap\",\n ),\n class_name=\"p-6 bg-white border border-gray-300 border-t-0 rounded-b-lg shadow-inner\",\n )\n\n\ndef ner_", "output": "hoverable_component = rx.el.span(\n segment[\"text\"],\n class_name=\"hover:bg-gray-200 rounded-sm cursor-pointer transition-colors\",\n )"}
{"instruction": "h = False\n break\n if (\n initial_segments[current_seg_idx][\"text\"]\n != keyword_words[current_kw_idx]\n ):\n match = False\n break\n temp_indices.append(current_seg_idx)\n current_kw_idx += 1\n current_seg_idx += 1\n if match:\n applied_label = False\n can_apply = all(\n (\n initial_segments[idx][\"label_name\"] is None\n for idx in temp_indices\n )\n )\n if can_apply:\n for idx in temp_indices:\n initial_segments[idx][\"label_name\"] = entity[\"name\"]\n ", "input": "\n initial_segments[idx][\"text_color\"] = entity[\n \"text_color\"\n ]\n applied_label = True\n if applied_label:\n i = temp_indices[-1] + 1\n else:\n next_word_idx = i + 1\n while next_word_idx < len(initial_segments) and (\n not initial_segments[next_word_idx][\"text\"].strip()\n ):\n next_word_idx += 1\n i = next_word_idx\n else:\n next_word_idx = i + 1\n while next_word_idx < len(initial_segments) and (\n not initial_segments[next_word_idx][\"text\"].strip()\n ):\n next_word_idx += 1\n ", "output": "initial_segments[idx][\"bg_color\"] = entity[\"color\"]"}
{"instruction": "\n\n @rx.event\n def select_label(self, label_name: Optional[str]):\n \"\"\"Selects a label to apply or deselects if the same label is clicked again.\"\"\"\n if self.selected_label_name == label_name:\n self.selected_label_name = None\n else:\n self.selected_label_name = label_name\n\n @rx.event\n def apply_label(self, segment_id: int):\n \"\"\"Applies the selected label to the clicked segment or removes it.\"\"\"\n if self.selected_label_name is None:\n return rx.toast(\"Select a label first!\", duration=2000)\n target_segment_index = -1\n for i, seg in enumerate(self.display_segments):\n if seg[\"id\"] == segment_id:\n target_segment_index = i\n break\n if target_segment_index == -1:\n return rx.toast(\"Segment not found.\", duration=2000)\n if not self.display_segments[target_segment_index][\"text\"].strip():\n return\n selected_entity = None\n ", "input": "\n if selected_entity:\n current_label = self.display_segments[target_segment_index][\"label_name\"]\n if current_label == self.selected_label_name:\n self.display_segments[target_segment_index][\"label_name\"] = None\n self.display_segments[target_segment_index][\"bg_color\"] = None\n self.display_segments[target_segment_index][\"text_color\"] = None\n else:\n self.display_segments[target_segment_index][\"label_name\"] = (\n selected_entity[\"name\"]\n )\n self.display_segments[target_segment_index][\"bg_color\"] = (\n selected_entity[\"color\"]\n )\n self.display_segments[target_segment_index][\"text_color\"] = (\n selected_entity[\"text_color\"]\n )\n else:\n return rx.toast(\n f\"Label '{self.selected_label_name}' definition not found.\",\n duratio", "output": "for entity in self.entities:\n if entity[\"name\"] == self.selected_label_name:\n selected_entity = entity\n break"}