### Install ipyautoui with pixi Source: https://github.com/jupyter-widgets-contrib/ipyautoui/blob/main/README.md Install the ipyautoui library using pixi. ```sh pixi add ipyautoui ``` -------------------------------- ### Install ipyautoui with uv Source: https://github.com/jupyter-widgets-contrib/ipyautoui/blob/main/README.md Install the ipyautoui library using uv. ```sh uv add ipyautoui ``` -------------------------------- ### Install ipyautoui with pip Source: https://github.com/jupyter-widgets-contrib/ipyautoui/blob/main/README.md Install the ipyautoui library using pip. ```sh pip install ipyautoui ``` -------------------------------- ### Install ipyautoui with mamba Source: https://github.com/jupyter-widgets-contrib/ipyautoui/blob/main/README.md Install the ipyautoui library using mamba. ```sh mamba install ipyautoui -c conda-forge ``` -------------------------------- ### Install ipyautoui with micromamba Source: https://github.com/jupyter-widgets-contrib/ipyautoui/blob/main/README.md Install the ipyautoui library using micromamba. ```sh micromamba install ipyautoui -c conda-forge ``` -------------------------------- ### Install and Run Tests with Pixi Source: https://github.com/jupyter-widgets-contrib/ipyautoui/blob/main/CONTRIBUTING.md Clone the repository and use pixi to run the project's tests. Ensure pixi is installed before proceeding. ```sh $ git clone https://github.com/maxfordham/ipyautoui $ cd ipyautoui # assuming that you have `pixi` installed: $ pixi run tests # view other pixi commands $ pixi run list ``` -------------------------------- ### Install ipyautoui with conda Source: https://github.com/jupyter-widgets-contrib/ipyautoui/blob/main/README.md Install the ipyautoui library using conda. ```sh conda install ipyautoui -c conda-forge ``` -------------------------------- ### Install Miniconda on Linux Source: https://github.com/jupyter-widgets-contrib/ipyautoui/blob/main/tests/filetypes/eg_txt.txt Steps to download and install the Miniconda shell script within a WSL Linux environment. ```bash sudo wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh ``` ```bash chmod +x Miniconda3-latest-Linux-x86_64.sh ``` ```bash ./Miniconda3-latest-Linux-x86_64.sh ``` -------------------------------- ### Initialize AutoGrid Source: https://github.com/jupyter-widgets-contrib/ipyautoui/blob/main/docs/issue-334.ipynb Imports necessary libraries and initializes an AutoGrid instance. This is the basic setup for using AutoGrid. ```python import typing as ty import pandas as pd from pydantic import BaseModel, RootModel, Field from ipyautoui.custom.autogrid import AutoGrid from ipyautoui.custom.editgrid import EditGrid, UiDelete ``` ```python autogrid = AutoGrid() autogrid ``` -------------------------------- ### Create and Activate Conda Environment Source: https://github.com/jupyter-widgets-contrib/ipyautoui/blob/main/tests/filetypes/eg_txt.txt Installs mamba, creates a new conda environment named 'base_mf' with specified packages, and then activates it. Includes pip installs for additional tools. ```bash # install mamba conda install mamba -n base -c conda-forge -y # create env mamba create -n base_mf -c conda-forge jupyterlab voila xeus-python pandas numpy markdown pydantic dacite ipysheet ipyfilechooser xmltodict plotly altair halo pyyaml jupytext click nodejs openpyxl xlsxwriter pip xlsxtemplater mf_file_utilities -y # activate conda activate base_mf # add pip only installs pip install mydocstring pipreqs ``` -------------------------------- ### Install JupyterLab Extensions Source: https://github.com/jupyter-widgets-contrib/ipyautoui/blob/main/tests/filetypes/eg_txt.txt Installs essential JupyterLab extensions for enhanced functionality, including widgets, Voila preview, ipysheet, and plotting capabilities. Note that some extensions may not support newer JupyterLab versions. ```bash # all deps below jupyter labextension install @jupyter-widgets/jupyterlab-manager @jupyter-voila/jupyterlab-preview ipysheet ipytree jupyter-matplotlib @krassowski/jupyterlab_go_to_definition jupyterlab-spreadsheet jupyterlab-plotly plotlywidget # but many don't support new version... jupyter labextension install @jupyter-widgets/jupyterlab-manager ipysheet jupyter-matplotlib @krassowski/jupyterlab_go_to_definition jupyterlab-spreadsheet jupyterlab-plotly plotlywidget ``` -------------------------------- ### Define a Pydantic model for AutoUi Source: https://github.com/jupyter-widgets-contrib/ipyautoui/blob/main/README.md Define a Pydantic model with type hints and field descriptions to be used with AutoUi. This example shows how to set default values, ranges, and descriptions for form fields. ```python from pydantic import BaseModel, Field from ipyautoui import AutoUi class LineGraph(BaseModel): """parameters to define a simple `y=m*x + c` line graph""" title: str = Field(default='line equation', description='add chart title') m: float = Field(default=2, description='gradient') c: float = Field(default=5, ge=0, le=10, description='intercept') x_range: tuple[int, int] = Field( default=(0,5), ge=0, le=50, description='x-range for chart') y_range: tuple[int, int] = Field( default=(0,5), ge=0, le=50, description='y-range for chart') ui = AutoUi(schema=LineGraph) ui ``` -------------------------------- ### Iterating jsonschema Validation Errors Source: https://github.com/jupyter-widgets-contrib/ipyautoui/blob/main/docs/validation.ipynb Use `Draft202012Validator.iter_errors` to get an iterator of validation errors. This is useful for detailed error reporting. ```python schema = { "items": { "anyOf": [{"type": "string", "maxLength": 2}, {"type": "integer", "minimum": 5}] } } instance = [{}, 3, "foo"] v = Draft202012Validator(schema) errors = sorted(v.iter_errors(instance), key=lambda e: e.path) errors ``` -------------------------------- ### Instantiate and Observe FileChooser Source: https://github.com/jupyter-widgets-contrib/ipyautoui/blob/main/docs/issue-336.ipynb Instantiates a FileChooser, sets up an observer to print changes to its value, and then programmatically sets the value. ```python from pathlib import Path from ipyautoui.custom import FileChooser # Make a file so that we can set the value of FileChooser p = Path("./dummy.txt") p.touch() # Make a FileChooser fc = FileChooser() # Define an observer that just prints the state of the FileChooser def print_status(change): print(f"{change['new']=}") print(f"{fc._value=}") print(f"{fc.selected_path=}") print(f"{fc.selected_filename=}") display(fc) # Observe the _value traitlet fc.observe(print_status, "_value") # set the value fc.value = str(p) ``` -------------------------------- ### Build and Publish Package Source: https://github.com/jupyter-widgets-contrib/ipyautoui/blob/main/CONTRIBUTING.md Commands for building the project and publishing it to PyPI. Note that publishing is restricted to core maintainers. ```sh # NOTE: restricted to core-maintainers only pixi run build hatch publish -u __token__ -a # publishes to pypi ``` -------------------------------- ### Import and demo ipyautoui components Source: https://github.com/jupyter-widgets-contrib/ipyautoui/blob/main/README.md Import core classes and the demo function from the ipyautoui library. ```python from ipyautoui import AutoUi, AutoVjsf, AutoDisplay, demo demo() ``` -------------------------------- ### Initialize and Display EditGrid Source: https://github.com/jupyter-widgets-contrib/ipyautoui/blob/main/docs/issue-334.ipynb Initializes an EditGrid with the custom delete UI and grid style, then displays the EditGrid widget. ```python editgrid = EditGrid(ui_delete=TestDelete, grid_style=GRID_STYLE) display(editgrid) ``` -------------------------------- ### Create Symbolic Link to C Drive Source: https://github.com/jupyter-widgets-contrib/ipyautoui/blob/main/tests/filetypes/eg_txt.txt Creates a symbolic link in the Ubuntu home directory pointing to the Windows C drive, allowing easier access to Windows files from within WSL. ```bash ln -s /mnt/c/engDev/ ~ ``` -------------------------------- ### Run ipyautoui Demo Source: https://github.com/jupyter-widgets-contrib/ipyautoui/blob/main/docs/demo.ipynb Imports and runs the demo function from the ipyautoui library. This is the primary entry point for exploring the library's features. ```python from ipyautoui import demo demo() ``` -------------------------------- ### Create and display AutoObject UI Source: https://github.com/jupyter-widgets-contrib/ipyautoui/blob/main/docs/issue-330.ipynb Creates an AutoObject UI from the JSON schema of the 'Test' model, pre-populating the 'text' field. The UI is then displayed. ```python ui = AutoObject.from_jsonschema(Test.model_json_schema(), value={"text": "text"}) display(ui) ``` -------------------------------- ### Import necessary libraries Source: https://github.com/jupyter-widgets-contrib/ipyautoui/blob/main/docs/issue-330.ipynb Imports BaseModel from pydantic and AutoObject from ipyautoui.autoobject. These are required for creating and displaying the UI. ```python from pydantic import BaseModel from ipyautoui.autoobject import AutoObject ``` -------------------------------- ### Import necessary libraries Source: https://github.com/jupyter-widgets-contrib/ipyautoui/blob/main/docs/buttonbar_extended.ipynb Imports required modules from ipywidgets, traitlets, and ipyautoui for creating custom widgets. ```python import ipywidgets as w import traitlets as tr from ipyautoui.constants import IMAGE_BUTTON_KWARGS from ipyautoui.custom.buttonbars import CrudButtonBar, CrudOptions, CrudView ``` -------------------------------- ### Create and Observe AutoUi Widget Source: https://github.com/jupyter-widgets-contrib/ipyautoui/blob/main/docs/issue-178.ipynb Creates an `AutoUi` widget from the `ApertureSettings` model and sets up an observer to print validation status on value changes. The observer checks if the current UI value conforms to the Pydantic model. ```python ui = AutoUi(ApertureSettings) counter = 0 def my_observer(change): global counter counter += 1 print(f"My observer call {counter}") print(ui.value) try: ApertureSettings(**ui.value) except ValidationError: print(" Bad state") else: print(" Good state") ui.observe(my_observer, names="_value") ``` -------------------------------- ### AutoUi methods and stored values Source: https://github.com/jupyter-widgets-contrib/ipyautoui/blob/main/README.md Overview of available methods and stored values for an AutoUi instance, including file handling, value access, and model/schema retrieval. ```python # methods / stored values ui.file(path) # file data to .json file ui.value # input form value dict ui.model # pydantic model (if given as input, AutoUi can be called from a jsonschema only also) ui.schema # jsonschema AutoUi.create_autoui_renderer # creates a json-serializable pointer AutoUi.parse_file # init ui with data from .json file ``` -------------------------------- ### Import necessary libraries Source: https://github.com/jupyter-widgets-contrib/ipyautoui/blob/main/docs/issue-332.ipynb Imports required modules for Pydantic models, pandas, and ipyautoui components. ```python import typing as ty import pandas as pd from pydantic import BaseModel, RootModel, Field import ipyautoui.automapschema as asch from ipyautoui.custom.autogrid import AutoGrid, GridSchema from ipyautoui.custom.editgrid import EditGrid from ipyautoui.custom.iterable import AutoArrayForm from ipyautoui.autoobject import AutoObject ``` -------------------------------- ### Uninstall Ubuntu Distribution Source: https://github.com/jupyter-widgets-contrib/ipyautoui/blob/main/tests/filetypes/eg_txt.txt Use this command to unregister and remove an Ubuntu distribution from WSL. ```bash wsl --unregister Ubuntu-20.04 ``` -------------------------------- ### Copy Environment Variable Script Source: https://github.com/jupyter-widgets-contrib/ipyautoui/blob/main/tests/filetypes/eg_txt.txt Copies a shell script to '/etc/profile.d/' to set environment variables upon system startup. This is crucial for importing custom modules. ```bash sudo cp /mnt/c/engDev/git_mf/engDevSetup/dev/installers/wsl2_Ubuntu2004/Current/mf_root.sh /etc/profile.d ``` -------------------------------- ### Initialize and coerce DataFrame data Source: https://github.com/jupyter-widgets-contrib/ipyautoui/blob/main/docs/issue-332.ipynb Initializes a model and schema from the Pydantic model, then uses GridSchema to coerce data from a pandas DataFrame. ```python model, schema = asch._init_model_schema(TestDataFrame) gridschema = GridSchema(schema) gridschema.coerce_data(pd.DataFrame([{"number": 2}])) ``` -------------------------------- ### AutoArray with Pydantic RootModel for list of objects Source: https://github.com/jupyter-widgets-contrib/ipyautoui/blob/main/docs/issue-17.ipynb Demonstrates creating an AutoArray from a Pydantic RootModel that defines a list of custom objects. Note that defaults are not being added to the AutoArray. ```python class TestListCol(BaseModel): li_col: list[str] = ["a"] stringy: str = "as" num: int = 1 class Test(RootModel): root: list[TestListCol] = [TestListCol(li_col=["a", "b"], stringy="asdfsadf", num=3)] AutoArray.from_jsonschema(Test.model_json_schema()) # Defaults not being added ``` -------------------------------- ### Create Pandas DataFrame from Schema Mappings Source: https://github.com/jupyter-widgets-contrib/ipyautoui/blob/main/docs/reference/pydantic-jsonschema-mapping.ipynb This snippet demonstrates how to create a Pandas DataFrame from the schema mapping table. It adds a 'Notes' column and displays the DataFrame using Pandas Styler. ```python import pandas as pd headings_ = headings + ['Notes'] pd.DataFrame(table, columns=headings_).style ``` -------------------------------- ### Display AutoUi Widget Source: https://github.com/jupyter-widgets-contrib/ipyautoui/blob/main/docs/issue-178.ipynb Renders the `AutoUi` widget in the output. This will display the interactive form based on the `ApertureSettings` model. ```python ui ``` -------------------------------- ### AutoObject with Pydantic BaseModel for list of objects Source: https://github.com/jupyter-widgets-contrib/ipyautoui/blob/main/docs/issue-17.ipynb Demonstrates creating an AutoObject from a Pydantic BaseModel that contains a list of custom objects. Similar to AutoArray, defaults are not being added. ```python class TestListCol(BaseModel): li_col: list[str] = ["a"] stringy: str = "as" num: int = 1 class Test(BaseModel): li_test_list: list[TestListCol] = [TestListCol(li_col=["a", "b"], stringy="asdfsadf", num=3)] AutoObject.from_jsonschema(Test.model_json_schema()) # Defaults not being added ``` -------------------------------- ### Custom Delete UI for EditGrid Source: https://github.com/jupyter-widgets-contrib/ipyautoui/blob/main/docs/issue-334.ipynb Defines a custom UIDelete class for EditGrid to provide a custom confirmation message before deletion. Sets a header background color for the grid style. ```python class TestDelete(UiDelete): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.message.value = ( "⚠️Are you sure you want to delete the following Types and Instances?⚠️
Pressing the DELETE button will" " permanently delete the selected Types and Instances!" ) HEADER_BACKGROUND_COLOUR = "rgb(207, 212, 252)" GRID_STYLE = {"header_background_color": HEADER_BACKGROUND_COLOUR} ``` -------------------------------- ### Import necessary libraries Source: https://github.com/jupyter-widgets-contrib/ipyautoui/blob/main/docs/issue-17.ipynb Imports common libraries used in ipyautoui development, including typing, pandas, pydantic, and various ipyautoui modules. ```python import typing as ty import pandas as pd from pydantic import BaseModel, RootModel, Field import ipyautoui.automapschema as asch from ipyautoui import AutoUi from ipyautoui.custom.autogrid import AutoGrid, GridSchema from ipyautoui.custom.editgrid import EditGrid from ipyautoui.custom.iterable import AutoArray from ipyautoui.autoobject import AutoObject ``` -------------------------------- ### Create Extended CrudButtonBar Class Source: https://github.com/jupyter-widgets-contrib/ipyautoui/blob/main/docs/buttonbar_extended.ipynb Subclasses CrudButtonBar to add an 'images' button functionality. It includes a callable traitlet for image handling and overrides the __init__ method to include the new button and apply the extended configuration. ```python class CrudButtonBarExtended(CrudButtonBar): fn_images = tr.Callable(default_value=lambda: print("add image")) def __init__(self, **kwargs): self.images = w.ToggleButton(**IMAGE_BUTTON_KWARGS) self.images.observe(self._images, "value") super().__init__(**kwargs | {"crud_view": EXTENDED_BUTTONBAR_CONFIG}) self.children = [ self.images, self.add, self.edit, self.copy, self.delete, self.reload, self.message, ] def _images(self, onchange): self._onclick("images") ``` -------------------------------- ### Configure Conda Channels Source: https://github.com/jupyter-widgets-contrib/ipyautoui/blob/main/tests/filetypes/eg_txt.txt Adds a local build directory and the conda-forge channel to your conda configuration. This is useful for accessing internal or specific package versions. ```bash mkdir /mnt/conda-bld sudo mount -t drvfs '\barbados\apps\conda\conda-bld' /mnt/conda-bld conda config --add channels file:///mnt/conda-bld conda config --add channels conda-forge ``` -------------------------------- ### Generate HTML Table for Schema Mappings Source: https://github.com/jupyter-widgets-contrib/ipyautoui/blob/main/docs/reference/pydantic-jsonschema-mapping.ipynb This function generates an HTML table representing the mapping between Pydantic types and JSON Schema. It processes a predefined table of mappings and writes the output to a temporary HTML file. ```python import re import json from pathlib import Path table = [ ( 'conint(gt=1, ge=2, lt=6, le=5, multiple_of=2)', 'integer', {'maximum': 5, 'exclusiveMaximum': 6, 'minimum': 2, 'exclusiveMinimum': 1, 'multipleOf': 2}, 'JSON Schema Validation', 'Any argument not passed to the function (not defined) will not be included in the schema.', ), ( 'PositiveInt', 'integer', {'exclusiveMinimum': 0}, 'JSON Schema Validation', '', ), ( 'NegativeInt', 'integer', {'exclusiveMaximum': 0}, 'JSON Schema Validation', '', ), ( 'NonNegativeInt', 'integer', {'minimum': 0}, 'JSON Schema Validation', '', ), ( 'NonPositiveInt', 'integer', {'maximum': 0}, 'JSON Schema Validation', '', ), ( 'confloat(gt=1, ge=2, lt=6, le=5, multiple_of=2)', 'number', {'maximum': 5, 'exclusiveMaximum': 6, 'minimum': 2, 'exclusiveMinimum': 1, 'multipleOf': 2}, 'JSON Schema Validation', 'Any argument not passed to the function (not defined) will not be included in the schema.', ), ( 'PositiveFloat', 'number', {'exclusiveMinimum': 0}, 'JSON Schema Validation', '', ), ( 'NegativeFloat', 'number', {'exclusiveMaximum': 0}, 'JSON Schema Validation', '', ), ( 'NonNegativeFloat', 'number', {'minimum': 0}, 'JSON Schema Validation', '', ), ( 'NonPositiveFloat', 'number', {'maximum': 0}, 'JSON Schema Validation', '', ), ( 'ConstrainedDecimal', 'number', '', 'JSON Schema Core', ( 'If the type has values declared for the constraints, they are included as validations. ' 'See the mapping for `condecimal` below.' ), ), ( 'condecimal(gt=1, ge=2, lt=6, le=5, multiple_of=2)', 'number', {'maximum': 5, 'exclusiveMaximum': 6, 'minimum': 2, 'exclusiveMinimum': 1, 'multipleOf': 2}, 'JSON Schema Validation', 'Any argument not passed to the function (not defined) will not be included in the schema.', ), ( 'BaseModel', 'object', '', 'JSON Schema Core', 'All the properties defined will be defined with standard JSON Schema, including submodels.', ), ( 'Color', 'string', {'format': 'color'}, 'Pydantic standard "format" extension', '', ), ] headings = [ 'Python type', 'JSON Schema Type', 'Additional JSON Schema', 'Defined in', ] def md2html(s: str) -> str: return re.sub(r'`(.+?)`', r'\1', s) def build_schema_mappings() -> None: rows = [] for py_type, json_type, additional, defined_in, notes in table: if additional and not isinstance(additional, str): additional = json.dumps(additional) cols = [ f'{py_type}', f'{json_type}', f'{additional}' if additional else '', md2html(defined_in) ] rows.append('\n'.join(f' \n {c}\n ' for c in cols)) if notes: rows.append( f' ' f' {md2html(notes)} ' f' ' ) heading = '\n'.join(f' {h}' for h in headings) body = '\n\n\n'.join(rows) text = f"""\ {heading} {body}
""" (Path("").parent / '..' / '.tmp_schema_mappings.html').write_text(text) if __name__ == '__main__': build_schema_mappings() ``` -------------------------------- ### Basic jsonschema Validation Source: https://github.com/jupyter-widgets-contrib/ipyautoui/blob/main/docs/validation.ipynb Use `jsonschema.validate` to check if an instance conforms to a schema. An exception is raised if validation fails. ```python from jsonschema import validate, Draft202012Validator, ErrorTree # A sample schema, like what we'd get from json.load() schema = { "type" : "object", "properties" : { "price" : {"type" : "number"}, "name" : {"type" : "string"}, }, } # If no exception is raised by validate(), the instance is valid. validate(instance={"name" : "Eggs", "price" : 34.99}, schema=schema) validate( instance={"name" : "Eggs", "price" : "Invalid"}, schema=schema, ) ``` -------------------------------- ### Update EditGrid with Schema and Data Source: https://github.com/jupyter-widgets-contrib/ipyautoui/blob/main/docs/issue-334.ipynb Updates the EditGrid with a Pydantic schema and sample data, including the custom delete UI. This prepares the grid for user interaction. ```python class DataFrameCols(BaseModel): string: str = Field( "string", json_schema_extra=dict(column_width=400, section="a") ) class TestDataFrame(RootModel): """a description of TestDataFrame""" root: ty.List[DataFrameCols] = Field( json_schema_extra=dict( format="dataframe", datagrid_index_name=("section", "title") ), ) editgrid.update_from_schema(TestDataFrame, value=[{"string": "Test"}]*10, ui_delete=TestDelete) ``` -------------------------------- ### Define Extended Button Bar Configuration Source: https://github.com/jupyter-widgets-contrib/ipyautoui/blob/main/docs/buttonbar_extended.ipynb Defines a custom configuration for the button bar, specifying options for image, add, edit, copy, and delete actions. This configuration is used to customize tooltips, button styles, and messages displayed to the user. ```python EXTENDED_BUTTONBAR_CONFIG = CrudView( images=CrudOptions( tooltip="Add image", tooltip_clicked="Go back to table", button_style="info", message="📷 Adding image", ), add=CrudOptions( tooltip="Add item", tooltip_clicked="Go back to table", button_style="success", message="➕ Adding data", ), edit=CrudOptions( tooltip="Edit item", tooltip_clicked="Go back to table", button_style="warning", message="✏️ Editing data", ), copy=CrudOptions( tooltip="Copy item", tooltip_clicked="Go back to table", button_style="primary", message="📝 Copying data", ), delete=CrudOptions( tooltip="Delete item", tooltip_clicked="Go back to table", button_style="danger", message="🗑️ Deleting data", ), ) ``` -------------------------------- ### EditGrid with Pydantic RootModel for dataframe format Source: https://github.com/jupyter-widgets-contrib/ipyautoui/blob/main/docs/issue-17.ipynb Shows how to use EditGrid with a Pydantic RootModel that specifies 'dataframe' format. The EditGrid component correctly handles the default row from the RootModel and defaults from nested models. ```python class TestListCol(BaseModel): li_col: list[str] = ["a"] stringy: str = "as" num: int = 1 class Test(RootModel): root: list[TestListCol] = Field([TestListCol(li_col=["a", "b"], stringy="asdfsadf", num=3)], format="dataframe") EditGrid(schema=Test) # Currently works for dataframe format (with EditGrid). Default row is added from Test RootModel, and AutoObjectForm shows defaults from TestListCol ``` -------------------------------- ### Define a Pydantic model Source: https://github.com/jupyter-widgets-contrib/ipyautoui/blob/main/docs/issue-330.ipynb Defines a simple Pydantic model 'Test' with a string and a float field. This model's schema will be used to generate the UI. ```python class Test(BaseModel): text: str number: float ``` -------------------------------- ### Define Pydantic Model with Validation Source: https://github.com/jupyter-widgets-contrib/ipyautoui/blob/main/docs/issue-178.ipynb Defines a Pydantic model `ApertureSettings` with constraints and custom validation logic for annuli. Ensure `validate_assignment` and `validate_default` are set to True for immediate validation. ```python from pydantic import BaseModel, Field, conint, model_validator, ValidationError from ipyautoui import AutoUi class ApertureSettings(BaseModel): radius : conint(ge=1) = Field(default=1) inner_annulus : conint(ge=1) = Field(default=2) outer_annulus : conint(ge=1) = Field(default=3) class Config: validate_assignment = True validate_default = True @model_validator(mode="after") def check_annuli(cls, values): if values.inner_annulus >= values.outer_annulus: raise ValueError('inner_annulus must be smaller than outer_annulus') if values.radius >= values.inner_annulus: raise ValueError('radius must be smaller than inner_annulus') return values ``` -------------------------------- ### Display Extended Button Bar Source: https://github.com/jupyter-widgets-contrib/ipyautoui/blob/main/docs/buttonbar_extended.ipynb Instantiates and displays the CrudButtonBarExtended widget when the script is run directly. This allows for immediate visualization and interaction with the extended button bar. ```python if __name__ == "__main__": display(CrudButtonBarExtended()) ``` -------------------------------- ### Update EditGrid with New Schema Source: https://github.com/jupyter-widgets-contrib/ipyautoui/blob/main/docs/issue-334.ipynb Updates the EditGrid with a new Pydantic schema defining an integer column. This demonstrates changing the data structure of the EditGrid. ```python class DataFrameCols(BaseModel): integer: int = Field( 10, json_schema_extra=dict(column_width=400, section="a") ) class TestDataFrame(RootModel): """a description of TestDataFrame""" root: ty.List[DataFrameCols] = Field( json_schema_extra=dict( format="dataframe", datagrid_index_name=("section", "title") ), ) editgrid.update_from_schema(TestDataFrame) ``` -------------------------------- ### Update AutoGrid with DataFrame Schema Source: https://github.com/jupyter-widgets-contrib/ipyautoui/blob/main/docs/issue-334.ipynb Defines Pydantic models for DataFrame columns and the root DataFrame structure. Updates the AutoGrid with a schema and sample Pandas DataFrame. ```python class DataFrameCols(BaseModel): string: str = Field( "string", json_schema_extra=dict(column_width=400, section="a") ) class TestDataFrame(RootModel): """a description of TestDataFrame""" root: ty.List[DataFrameCols] = Field( json_schema_extra=dict( format="dataframe", datagrid_index_name=("section", "title") ), ) autogrid.update_from_schema(TestDataFrame, data=pd.DataFrame([{"string": "Test"}]*10)) ``` -------------------------------- ### Update AutoObject value Source: https://github.com/jupyter-widgets-contrib/ipyautoui/blob/main/docs/issue-330.ipynb Updates the 'number' field of the displayed AutoObject UI to 4. This demonstrates how to programmatically change the UI's values. ```python ui.value = {"number": 4} ``` -------------------------------- ### Extracting Pydantic Schema for Simple Table Rows Source: https://github.com/jupyter-widgets-contrib/ipyautoui/blob/main/docs/row-validation.ipynb Extracts the Pydantic model class used for rows in a simple root model table. This is useful for direct validation of individual rows. ```python from pydantic import RootModel, BaseModel class Sub(BaseModel): a: str = "a" b: int = 1 class Table(RootModel): root: list[Sub] class NestedTable(BaseModel): table: list[Sub] # for simple root tables it is simple to extract the pydantic model for the row RowSchema = Table.__pydantic_core_schema__["schema"]["items_schema"]["cls"] print(RowSchema) ``` -------------------------------- ### Update AutoUi Widget Value Source: https://github.com/jupyter-widgets-contrib/ipyautoui/blob/main/docs/issue-178.ipynb Programmatically sets the value of the `AutoUi` widget. This will trigger the observer and update the UI, demonstrating how to modify the widget's state. ```python ui.value = dict(radius=2, inner_annulus=7, outer_annulus=8) ``` -------------------------------- ### Define Pydantic models for DataFrame Source: https://github.com/jupyter-widgets-contrib/ipyautoui/blob/main/docs/issue-332.ipynb Defines a Pydantic BaseModel for individual rows and a RootModel to represent a list of these rows as a DataFrame. ```python class Test(BaseModel): text: str = "" number: float class TestDataFrame(RootModel): root: ty.List[Test] = Field(format="dataframe") ``` -------------------------------- ### Access AutoUi value Source: https://github.com/jupyter-widgets-contrib/ipyautoui/blob/main/README.md Access the current value of the AutoUi widget, which is kept in sync with the input form. The value is returned as a dictionary. ```python ui.value # there is a `value` trait that is always kept in-sync with the widget input form # {'title': 'line equation', # 'm': 2, # 'c': 5, # 'x_range': (0, 5), # 'y_range': (0, 5)} ``` -------------------------------- ### Extracting Pydantic Schema for Nested Table Rows Source: https://github.com/jupyter-widgets-contrib/ipyautoui/blob/main/docs/row-validation.ipynb Extracts the Pydantic model class for rows within a nested table structure. This is necessary when dealing with more complex, nested data models. ```python # more difficult for nested rows NestedRowSchema = NestedTable.__pydantic_core_schema__["schema"]["fields"]["table"]["schema"]["items_schema"]["cls"] print(NestedRowSchema) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.