Skip to main content
import marimo

__generated_with = "0.17.8"
app = marimo.App(width="medium")


@app.cell
def _():
    import marimo as mo
    import pandas as pd
    import random
    import sqlalchemy
    return mo, pd, random, sqlalchemy


@app.cell
def _():
    x = 10
    return (x,)


@app.cell
def _(x):
    print(x)
    return


@app.cell
def _(x):
    y = x * 2
    y
    print(y)
    # change x to 15 what answer do we get?
    return


@app.cell
def _(mo):
    slider_value = mo.ui.slider(0, 100, value=50, label="Select a number")
    slider_value  # reactive output
    return


@app.cell
def _(mo):
    fruit = mo.ui.dropdown(["Apple", "Banana", "Cherry"], label="Pick a fruit")
    fruit
    return


@app.cell
def _(mo, pd):
    df = pd.DataFrame({
        "Name": ["Katie", "Carrie", "Wren"],
        "Score": [90, 80, 85]
    })
    mo.ui.table(df, label="Student Scores")
    return


@app.cell
def _(mo, random):
    array = mo.ui.array([mo.ui.text() for i in range(random.randint(1, 10))])
    array
    return


@app.cell
def _(mo, random):
    dictionary = mo.ui.dictionary({str(i): mo.ui.text() for i in range(random.randint(1, 10))})
    dictionary
    return (dictionary,)


@app.cell
def _(dictionary):
    # change to values
    dictionary.value
    return


@app.cell
def _(mo, random):
    n_items = random.randint(2, 5)

    # Create a dynamic number of elements using `mo.ui.dictionary` and
    # `mo.ui.array`
    elements = mo.ui.dictionary(
        {
            "checkboxes": mo.ui.array([mo.ui.checkbox() for _ in range(n_items)]),
            "texts": mo.ui.array(
                [mo.ui.text(placeholder="task ...") for _ in range(n_items)]
            ),
        }
    )

    mo.md(
        f"""
        Here's a TODO list of {n_items} items\n\n
        """
        + "\n\n".join(
            # Iterate over the elements and embed them in markdown
            [
                f"{checkbox} {text}"
                for checkbox, text in zip(
                    elements["checkboxes"], elements["texts"]
                )
            ]
        )
    )
    return (elements,)


@app.cell
def _(elements):
    elements.value

    return


@app.cell
def _(mo, random):


    # State Management: Track which button was clicked
    get_state, set_state = mo.state(None)

    # Generate dynamic button array
    # Note: mo.ui.array is required for reactivity - standard lists won't trigger updates
    num_buttons = random.randint(2, 5)

    buttons = mo.ui.array(
        [
            mo.ui.button(
                label=f"Action {i + 1}",
                on_change=lambda v, i=i: set_state(i)
                # The i=i binding captures the loop variable at each iteration
            )
            for i in range(num_buttons)
        ]
    )

    # Display interface
    table = mo.ui.table(
        {
            "Action": [f"Task {i + 1}" for i in range(len(buttons))],
            "Trigger": list(buttons),
            "Status": [
                "Active" if get_state() == i else "Inactive"
                for i in range(len(buttons))
            ]
        }
    )

    # State feedback
    if get_state() is None:
        feedback = mo.md("**State:** No button clicked yet")
    else:
        feedback = mo.md(f"""
    **State:** Button index `{get_state()}` clicked (Action {get_state() + 1})

    The state persists across cell re-renders and can be accessed by any component using `get_state()`.
    """)

    # Render
    mo.vstack([
        mo.md("## Interactive State Management"),
        table,
        feedback
    ])
    return


@app.cell
def _(mo):
    form = mo.md(
       r"""
       Choose your algorithm parameters:

       - $\epsilon$: {epsilon}
       - $\delta$: {delta}
       """
    ).batch(epsilon=mo.ui.slider(0.1, 1, step=0.1), delta=mo.ui.number(1, 10)).form()
    form
    return (form,)


@app.cell
def _(form):
    form.value
    return


@app.cell
def _(mo):
    examples = mo.ui.dropdown(
        options={
            "ex 1": {"t1": "hello", "t2": "world"},
            "ex 2": {"t1": "marimo", "t2": "notebook"},
        },
        value="ex 1",
        label="examples",
    )
    return (examples,)


@app.cell
def _(examples, mo):
    form_dropdown = (
        mo.md(
        """
        ### Your form

        {t1}
        {t2}
        """
        )
        .batch(
            t1=mo.ui.text(label="enter text", value=examples.value.get("t1", "")),
            t2=mo.ui.text(label="more text", value=examples.value.get("t2", "")),
        )
        .form(
            submit_button_label="go"
        )
    )
    return (form_dropdown,)


@app.cell
def _(examples, form_dropdown):
    output = (
        "" .join(form_dropdown.value.values()).upper()
        if form_dropdown.value is not None
        else "".join(examples.value.values()).upper()
    )
    return


@app.cell
def _(mo, random):
    button = mo.ui.run_button()
    random.randint(0, 1000)
    button
    return


@app.cell
def _(mo):
    button_2 = mo.ui.button(value=0, on_click=lambda count: count + 1, label="Count Me")
    return (button_2,)


@app.cell
def _(button_2, mo):
    mo.md(f"**Counter Button:** {button_2} | Current count: {button_2.value}")

    return


@app.cell
def _(mo):
    toggle_button = mo.ui.button(value=True, on_click=lambda value: not value)
    toggle_button
    return (toggle_button,)



@app.cell
def _(mo, toggle_button):
    mo.md("True!") if toggle_button.value else mo.md("False!")
    return


@app.cell
def _(mo):
    counter_button = mo.ui.button(value=0, on_click=lambda count: count + 1)
    # add , tooltip="click to count"
    counter_button
    return (counter_button,)


@app.cell
def _(counter_button, mo):
    mo.stop(counter_button.value == 0)
    mo.md(f"The button was clicked {counter_button.value} times")
    return


@app.cell
def _(mo):
    after_button = mo.ui.button(value=0, on_click=lambda count: count + 1)
    after_button
    return (after_button,)


@app.cell
def _(after_button, mo):
    mo.md("#" + "🍃" * after_button.value) if after_button.value > 0 else None
    return


@app.cell
def _():
    condition = True
    "condition is True" if condition else None
    return


@app.cell
def _(mo):
    movie_form = mo.ui.text(label="Your Favorite Movie").form()
    movie_form
    return


@app.cell
def _(mo):
    name = mo.ui.text(placeholder="Your name here")
    mo.md(
      f"""
      Hi! What's your name?

      {name}
      """
    )
    return (name,)


@app.cell
def _(mo, name):
    mo.md(
      f"""
      Hello, {name.value}!
      """
    )
    return


@app.cell(hide_code=True)
def _(mo):
    mo.md(r"""
    /// details | Info details
        type: info

    Some additional content. This is written using the 'Markdown block feature'
    ///

    /// details | Warning details
        type: warn

    This highlights something to watch out for. Use other components like 'Danger' or 'Success'

    next we will move to sql integration
    ///
    """)
    return


@app.cell
def _(pd, random):
    df_2 = pd.DataFrame(
        {
            "category": [random.choice(["A", "B", "C"]) for _ in range(20)],
            "value": list(range(20)),
        }
    )

    df_2
    return (df_2,)


@app.cell
def _(df_2, mo):
    _df = mo.sql(
        f"""
        SELECT category, MEAN(value) as mean FROM df_2 GROUP BY category ORDER BY mean;
        """
    )
    return


@app.cell
def _(sqlalchemy):
    sql_engine = sqlalchemy.create_engine("sqlite:///:memory:")
    return


@app.cell
def _(df_2, mo):
    _df = mo.sql(
        f"""
        SELECT * FROM df_2
        """
    )
    return


@app.cell
def _():
    from vega_datasets import data

    data.list_datasets()
    return (data,)


@app.cell
def _(data):
    #about iris

    df_iris = data.iris()

    df_iris

    return (df_iris,)


@app.cell
def _(mo):
    species_dropdown = mo.ui.dropdown(["setosa", "versicolor", "virginica"])
    species_dropdown
    return (species_dropdown,)


@app.cell
def _(mo):
    mo.accordion(
            {
                "Tip: Creating SQL Cells": mo.md(
                    f"""
                    Create a SQL cell in one of two ways:

                    1. Click the {mo.icon("lucide:database")} `SQL` button at the **bottom of your notebook**
                    2. **Right-click** the {mo.icon("lucide:circle-plus")} button to the **left of a cell**, and choose `SQL`.

                    In the SQL cell, you can query dataframes in your notebook as if
                    they were tables — just reference them by name.
                    """
                )
            }
        )
    return


@app.cell
def _(df_iris, mo, species_dropdown):
    result = mo.sql(
            f"""
            SELECT * FROM df_iris where species == '{species_dropdown.value}'
            """, output=False
        )
    result
    return


@app.cell
def _(df_iris, mo):
    _df = mo.sql(
        f"""
        SELECT
            *
        FROM
            df_iris
        """
    )
    return


if __name__ == "__main__":
    app.run()