示例#1
0
async def serve(q: Q):
    if q.client.plot_added:  # Have we already added a plot?
        example = q.page['example']
        if q.args.to_log_scale:
            # Change to log scale
            example.items[0].text_l.content = 'Plot (Log Scale)'
            example.items[0].text_l.commands = [linear_scale_command]
            example.items[1].vega_visualization.specification = spec_log_scale
        else:
            # Change to linear scale
            example.items[0].text_l.content = 'Plot (Linear Scale)'
            example.items[0].text_l.commands = [log_scale_command]
            example.items[
                1].vega_visualization.specification = spec_linear_scale
    else:  # Add a new plot
        q.page['example'] = ui.form_card(
            box='1 1 2 8',
            items=[
                ui.text_l(content='Plot (Linear Scale)',
                          commands=[log_scale_command]),
                ui.vega_visualization(specification=spec_linear_scale,
                                      data=plot_data,
                                      height='300px'),
            ],
        )
        # Flag to indicate that we've added a plot
        q.client.plot_added = True

    await q.page.save()
示例#2
0
async def start_new_game(q: Q):
    q.client.game = Game(q.user.player.player_id)
    q.user.player.games[q.client.game.game_id] = q.client.game

    q.page['starting_game'] = ui.form_card(
        box='4 4 3 3',
        items=[
            ui.text_l('I am thinking of a number between 1 and 100'),
            ui.text_m('can you guess what it is?'),
            ui.text_xs('Рађ'),
            ui.slider(
                name='guess',
                label='your guess',
                min=1,
                max=100,
                value=100,
                trigger=True,
            ),
            ui.text_xs('Рађ'),
            ui.buttons(
                items=[
                    ui.button(name='quit_game', label='Quit', primary=True)
                ],
                justify='center',
            ),
        ],
    )
    await q.page.save()
示例#3
0
def get_user_input_items(sales_data, user_inputs, progress=False):
    return [
        ui.text_l('**Select Area of Interest**'),
        ui.dropdown(
            name='stores',
            label='Store IDs',
            values=[str(x) for x in user_inputs.stores],
            choices=[ui.choice(name=str(x), label=str(x)) for x in sales_data.stores_unique],
            tooltip='Select the Stores to include in the prediction',
            trigger=True,
        ),
        ui.text_xs('⠀'),
        ui.dropdown(
            name='departments',
            label='Product IDs',
            values=[str(x) for x in user_inputs.departments],
            choices=[ui.choice(name=str(x), label=str(x)) for x in sales_data.departments_unique],
            tooltip='Select the Products to include in the prediction',
            trigger=True,
        ),
        ui.frame(content=' ', height="40px"),
        ui.text_l('**Generate Sales Forecast**'),
        ui.slider(
            name='n_forecast_weeks',
            label='Number of Weeks',
            min=0,
            max=len(sales_data.prediction_dates) - 1,
            step=1,
            value=user_inputs.n_forecast_weeks,
            trigger=True,
            tooltip='Select the number of weeks into the future to predict'
        ),
        ui.text_xs('⠀'),
        ui.button(
            name='reset',
            label='Reset',
            primary=True,
            tooltip='Click to reset all values to defaults'
        ),
        ui.text_xs('⠀'),
        ui.progress(label='', caption='', visible=progress),
    ]
示例#4
0
async def show_todos(q: Q):
    # Get items for this user.
    db: WaveDB = q.app.db

    # Check if we have any updates, i.e. the user has checked/unchecked any item.
    updates = []
    for key, done in expando_to_dict(q.args).items():
        # We've named each todo item `todo_{id}' (e.g. todo_42, todo_43, and so on)
        # So identify the todo items from their 'todo_' prefix, then extract the ids from the names.
        if key.startswith('todo_'):
            _, id = key.split('_', 1)
            updates.append(('update todo set done=? where id=?',
                            1 if done else 0, int(id)))

    # If we have updates, update our database.
    if len(updates):
        _, err = await db.exec_many(*updates)
        if err:
            raise RuntimeError(f'Failed updating todos: {err}')

    # Fetch latest todos for our user
    rows, err = await db.exec('select id, label, done from todo where user=?',
                              q.auth.subject)
    if err:
        raise RuntimeError(f'Failed fetching todos: {err}')
    todos = [TodoItem(id, label, done) for id, label, done in rows]

    # Create done/not-done checkboxes.
    done = [
        ui.checkbox(name=f'todo_{todo.id}',
                    label=todo.label,
                    value=True,
                    trigger=True) for todo in todos if todo.done
    ]
    not_done = [
        ui.checkbox(name=f'todo_{todo.id}', label=todo.label, trigger=True)
        for todo in todos if not todo.done
    ]

    # Display list
    q.page['form'] = ui.form_card(
        box='1 1 4 10',
        items=[
            ui.text_l('To Do'),
            ui.button(name='new_todo', label='Add To Do...', primary=True),
            *not_done,
            *([ui.separator('Done')] if len(done) else []),
            *done,
        ])
    await q.page.save()
示例#5
0
文件: app.py 项目: mjdhasan/wave-apps
def populate_dropdown_list(q: Q):
    filter_choices = [
        ui.choice(
            name=json.dumps({"id": q.client.filter_count + 1, "attr": column, "attr_val": None}),
            label=config.column_mapping[column]
        ) for column in config.filterable_columns
    ]
    items = [
        ui.text_l("Filter reviews"),
    ]

    for key, value in q.client.filters.items():
        for attr, attr_val in value.items():
            items.append(ui.dropdown(
                name="filter",
                label="Choose a review attribute",
                placeholder=config.column_mapping[attr],
                choices=[
                    ui.choice(
                        name=json.dumps({'id': key, 'attr': column, 'attr_val': None}),
                        label=config.column_mapping[column]
                    ) for column in config.filterable_columns
                ],
                trigger=True,
            ), )
            items.append(ui.dropdown(
                name="filter_value",
                label="Choose a value for selected review attribute",
                placeholder=attr_val,
                choices=[ui.choice(name=json.dumps({'id': key, 'attr': attr, 'attr_val': column}), label=column) for
                         column in config.dataset[attr].drop_duplicates()],
                trigger=True,
            ), )
            items.append(ui.separator())

    if (q.args.add_filter and all(q.client.filters.values())) or q.args.review_choice or q.args.reset_filters:
        items.append(ui.dropdown(
            name="filter",
            label="Choose a review attribute",
            placeholder="Please select a category to filter",
            choices=filter_choices,
            trigger=True
        ), )

    items.append(ui.button(name="compare_review_button", label="Compare Reviews", primary=True))

    return items
示例#6
0
文件: todo.py 项目: srisatish/wave
async def new_todo(q: Q):
    # Display an input form
    q.page['form'] = ui.form_card(box='1 1 4 10',
                                  items=[
                                      ui.text_l('Add To Do'),
                                      ui.textbox(
                                          name='label',
                                          label='What needs to be done?',
                                          multiline=True),
                                      ui.buttons([
                                          ui.button(name='add_todo',
                                                    label='Add',
                                                    primary=True),
                                          ui.button(name='show_todos',
                                                    label='Back'),
                                      ]),
                                  ])
    await q.page.save()
示例#7
0
async def make_welcome_card(q):
    q.page['hello'] = ui.form_card(
        box='4 4 3 3',
        items=[
            ui.text_l(f'Hello {q.user.player.first.title()},'),
            ui.text_xs('Рађ'),
            ui.text_m('Do you want to play a guessing game?'),
            ui.text_xs('Рађ'),
            ui.buttons(
                items=[
                    ui.button('start_game', label='Play', primary=True),
                    ui.button('leaderboard',
                              label='View Scores',
                              primary=False),
                ],
                justify='center',
            ),
        ],
    )
    await q.page.save()
示例#8
0
async def serve(q: Q):
    if not q.client.initialized:
        q.page['example'] = ui.form_card(
            box='1 1 4 10',
            items=[
                ui.text_xl(content='First text'),
                ui.text_l(content='Second text'),
                ui.text_m(content='Third text'),
                ui.text_s(content='Fourth text'),
                ui.inline([
                    ui.button(name='left1', label='Left1'),
                    ui.button(name='left2', label='Left2'),
                    ui.button(name='left3', label='Left3'),
                ]),
                ui.buttons(justify='end',
                           items=[
                               ui.button(name='right1', label='Right1'),
                               ui.button(name='right2', label='Right2'),
                               ui.button(name='right3', label='Right3'),
                           ]),
                ui.buttons(items=[
                    ui.button(name='show', label='Show'),
                    ui.button(name='hide', label='Hide')
                ])
            ])
        q.client.initialized = True
    items = q.page['example'].items
    items_to_hide = [
        items[0].text_xl,
        items[2].text_m,
        items[4].inline.items[0].button,
        items[5].buttons.items[2].button,
    ]
    if q.args.hide:
        for i in items_to_hide:
            i.visible = False
    if q.args.show:
        for i in items_to_hide:
            i.visible = True
    await q.page.save()
示例#9
0
def get_user_input_items(sales_data, user_inputs, progress=False):
    return [
        ui.text_l('**Prediction Configuration**'),
        ui.dropdown(
            name='stores',
            label='Store IDs',
            values=[str(x) for x in user_inputs.stores],
            choices=[
                ui.choice(name=str(x), label=str(x))
                for x in sales_data.stores_unique
            ],
            trigger=True,
        ),
        ui.dropdown(
            name='departments',
            label='Product IDs',
            values=[str(x) for x in user_inputs.departments],
            choices=[
                ui.choice(name=str(x), label=str(x))
                for x in sales_data.departments_unique
            ],
            trigger=True,
        ),
        ui.slider(
            name='n_forecast_weeks',
            label='Weeks to predict',
            min=0,
            max=len(sales_data.prediction_dates) - 1,
            step=1,
            value=user_inputs.n_forecast_weeks,
            trigger=True,
        ),
        ui.button(name='reset',
                  label='Reset',
                  primary=True,
                  tooltip='Click to reset all values to defaults'),
        ui.progress(label='', caption='', visible=progress),
    ]
示例#10
0
文件: todo.py 项目: srisatish/wave
async def show_todos(q: Q):
    # Get items for this user.
    todos: List[TodoItem] = q.user.todos

    # Create a sample list if we don't have any.
    if todos is None:
        q.user.todos = todos = [
            TodoItem('Do this'),
            TodoItem('Do that'),
            TodoItem('Do something else')
        ]

    # If the user checked/unchecked an item, update our list.
    for todo in todos:
        if todo.id in q.args:
            todo.done = q.args[todo.id]

    # Create done/not-done checkboxes.
    done = [
        ui.checkbox(name=todo.id, label=todo.label, value=True, trigger=True)
        for todo in todos if todo.done
    ]
    not_done = [
        ui.checkbox(name=todo.id, label=todo.label, trigger=True)
        for todo in todos if not todo.done
    ]

    # Display list
    q.page['form'] = ui.form_card(
        box='1 1 4 10',
        items=[
            ui.text_l('To Do'),
            ui.button(name='new_todo', label='Add To Do...', primary=True),
            *not_done,
            *([ui.separator('Done')] if len(done) else []),
            *done,
        ])
    await q.page.save()
示例#11
0
async def serve(q: Q):
    if not q.client.initialized:
        q.client.initialized = True
        q.page['table'] = ui.form_card(
            box='1 1 4 7',
            items=[
                ui.text_l('Airline Passenger Counts'),
                ui.text(
                    make_markdown_table(
                        fields=air_passengers_fields,
                        rows=add_links_to_cells(air_passengers_rows),
                    )),
            ],
        )
        q.page['message'] = ui.markdown_card(
            box='1 8 4 1',
            title='',
            content='Click on a cell in the table above!',
        )

    await handle_on(q)

    await q.page.save()
示例#12
0
async def showProducts(q: Q):
    global filter_product
    global filter_manufacturer
    global filter_supplier
    global unit_measure
    global gqty

    items = [ui.tabs(name='menu', value=q.args.menu, items=tabs)]

    print('---------------------------')
    print('== PRODUCT TAB == ')
    print('q.args.show_tables: ' + str(q.args.show_tables) +
          ', q.args.show_inputs: ' + str(q.args.show_inputs))

    ## the user have clicked 'Add' button but haven't clicked 'Submit' button yet
    if (q.args.show_tables == None or q.args.show_tables == False) and (
            q.args.show_inputs or q.args.product or q.args.manufacturer
            or q.args.supplier or q.args.qty):

        ## need to get manufacturer data first (later used for the dropdown when adding new supplier)
        df_m = pd.DataFrame(l_manufacturers,
                            columns=['manufacturer', 'product'])
        df_s = pd.DataFrame(l_suppliers,
                            columns=['supplier', 'manufacturer', 'product'])

        ## if there is no manufacturer data
        if len(df_m) == 0:
            items.extend([
                ui.message_bar(type='info',
                               text='Try adding manufacturer first'),
                ui.button(name='goto_manufacturer',
                          label='Close',
                          primary=True)
            ])

        ## if there is no supplier data
        elif len(df_s) == 0:
            items.extend([
                ui.message_bar(type='info', text='Try adding supplier first'),
                ui.button(name='goto_supplier', label='Close', primary=True)
            ])

        ## if there is data on manufacturer and supplier, when the user click 'Add Product' button
        else:
            items.append(ui.text_xl(content='Add Product'))
            print('q.args.product: ' + str(q.args.product) +
                  ', q.args.manufacturer: ' + str(q.args.manufacturer) +
                  ', q.args.supplier: ' + str(q.args.supplier))

            if q.args.product and (filter_product == None
                                   or q.args.product != filter_product):
                filter_product = q.args.product
                filter_manufacturer = None
                filter_supplier = None
                unit_measure = None
                # selling_price = None
                gqty = None
            elif q.args.manufacturer and (
                    filter_manufacturer == None
                    or q.args.manufacturer != filter_manufacturer):
                filter_manufacturer = q.args.manufacturer
                filter_supplier = None
                unit_measure = None
                # selling_price = None
                gqty = None
            elif q.args.supplier and (filter_supplier == None
                                      or q.args.supplier != filter_supplier):
                filter_supplier = q.args.supplier
                unit_measure = None
                # selling_price = None
                gqty = None
            if q.args.qty:
                gqty = q.args.qty

            print(filter_product, filter_manufacturer, filter_supplier)

            ## PRODUCT
            if filter_product != None:
                items.append(
                    ui.dropdown(name='product',
                                label='Product',
                                choices=[
                                    ui.choice(name=x, label=x)
                                    for x in df_m['product'].unique()
                                ],
                                trigger=True,
                                value=filter_product))
                tmp_m = df_m[df_m['product'] ==
                             q.args.product]['manufacturer'].unique()

            else:
                items.append(
                    ui.dropdown(name='product',
                                label='Product',
                                choices=[
                                    ui.choice(name=x, label=x)
                                    for x in df_m['product'].unique()
                                ],
                                trigger=True))
                tmp_m = df_m['manufacturer'].unique()

            ## MANUFACTURER
            if filter_manufacturer != None:
                items.append(
                    ui.dropdown(
                        name='manufacturer',
                        label='Manufacturer',
                        choices=[ui.choice(name=x, label=x) for x in tmp_m],
                        trigger=True,
                        value=filter_manufacturer))
                tmp_s = df_s[(df_s['product'] == filter_product)
                             & (df_s['manufacturer'] == filter_manufacturer
                                )]['supplier'].unique()

            else:
                items.append(
                    ui.dropdown(
                        name='manufacturer',
                        label='Manufacturer',
                        choices=[ui.choice(name=x, label=x) for x in tmp_m],
                        trigger=True))
                tmp_s = df_s['supplier'].unique()

            ## SUPPLIER
            if filter_supplier != None:
                items.append(
                    ui.dropdown(
                        name='supplier',
                        label='Supplier',
                        choices=[ui.choice(name=x, label=x) for x in tmp_s],
                        trigger=True,
                        value=filter_supplier))
                # selling_price = df_s[(df_s['product']==filter_product)&(df_s['manufacturer']==filter_manufacturer)
                #                   &(df_s['supplier']==filter_supplier)]['selling_price'].values[0]
                # unit_measure = df_s[(df_s['product']==filter_product)&(df_s['manufacturer']==filter_manufacturer)
                #                   &(df_s['supplier']==filter_supplier)]['uom'].values[0]

            else:
                items.append(
                    ui.dropdown(
                        name='supplier',
                        label='Supplier',
                        choices=[ui.choice(name=x, label=x) for x in tmp_s],
                        trigger=True))
                # selling_price = None

            # items.append(ui.date_picker(name='purchase_date', label='Purchase Date'))
            # items.append(ui.textbox(name='qty', label='Qty'))

            # ## SELLING PRICE
            # if selling_price!=None:
            #   items.append(ui.textbox(name='selling_price', label='Selling Price', value = str(selling_price)))
            # else:
            #   items.append(ui.textbox(name='selling_price', label='Selling Price'))

            # ## UOM
            # if unit_measure!=None:
            #   items.append(ui.textbox(name='uom', label='Unit of Measurement', value = unit_measure, readonly = True))
            # else:
            #   items.append(ui.dropdown(name='uom', label='Unit of Measurement', choices=[
            #       ui.choice(name=x, label=x) for x in uom
            #   ]))

            # items.extend([
            #   # ui.date_picker(name='mfg_date', label='Mfg Date'),
            #   # ui.date_picker(name='exp_date', label='Exp Date'),
            #   ui.textbox(name='selling_price', label='Selling Price'),
            #   # ui.textbox(name='operational_cost', label='Operational Cost'),
            #   # ui.textbox(name='lvl', label='Order Point by level(%)'),
            #   # ui.textbox(name='schedule', label='Order Point Schedule (days)'),
            #   # ui.textbox(name='schedule_qty', label='Scheduled Qty'),
            #   # ui.textbox(name='rate', label='Avg. Consumption'),
            #   # ui.dropdown(name='freq', label='Consumption Frequency', choices=[
            #   #     ui.choice(name=x, label=x, value='daily', readonly=True) for x in consumption
            #   # ]),
            #   ui.button(name='show_tables', label='Submit', primary=True)])

            items.extend([
                # ui.textbox(name='selling_price', label='Selling Price'),
                ui.button(name='show_tables', label='Submit', primary=True)
            ])

    else:  ## first iteration goes here
        filter_product = None
        filter_manufacturer = None
        filter_supplier = None
        unit_measure = None
        selling_price = None
        gqty = None

        ## if q.args.show_tables == True
        if q.args.show_tables:
            # l_products.append([q.args.product, q.args.manufacturer, q.args.supplier, q.args.purchase_date, q.args.qty,
            #             q.args.uom, q.args.selling_price, q.args.mfg_date, q.args.exp_date, q.args.selling_price,
            #             q.args.operational_cost, q.args.lvl, q.args.schedule, q.args.schedule_qty, q.args.rate])
            # p = Products(q.args.product, q.args.manufacturer, q.args.supplier, q.args.purchase_date, q.args.qty,
            #             q.args.uom, q.args.selling_price, q.args.mfg_date, q.args.exp_date, q.args.selling_price,
            #             q.args.operational_cost, q.args.lvl, q.args.schedule, q.args.schedule_qty, q.args.rate)

            # l_products.append([q.args.product, q.args.manufacturer, q.args.supplier,
            #             q.args.uom])
            l_products.append(
                [q.args.product, q.args.manufacturer, q.args.supplier])
            # p = Products(q.args.product, q.args.manufacturer, q.args.supplier,
            #             q.args.uom)
            p = Products(q.args.product, q.args.manufacturer, q.args.supplier)
            products.append(p)
            items.append(
                ui.message_bar(type='success',
                               text='You have successfully added a product'))

        ## if there is a product data
        if len(products) > 0:
            items.append(
                ui.table(
                    name='products',
                    columns=column_product_table,
                    rows=[
                        ui.table_row(
                            name=product.id,
                            # cells=[product.product, product.manufacturer, product.supplier, product.selling_price,
                            #     product.uom]
                            cells=[
                                product.product, product.manufacturer,
                                product.supplier
                            ]) for product in products
                    ],
                    groupable=True,
                    downloadable=True,
                    resettable=True,
                    height='500px'))
        else:  ## if there is no product data
            items.append(ui.text_l(content='No Product found'))

        # items.append(ui.button(name='show_inputs', label='Add Product', primary=True))

        items.append(
            ui.buttons([
                ui.button(name='show_inputs',
                          label='Add Product',
                          primary=True),
                ui.button(name='delete_button', label='Delete Product'),
                ui.button(name='edit_button', label='Edit Product'),
            ]))

    q.page['example'] = ui.form_card(box='1 2 -1 -1', items=items)
    await q.page.save()
示例#13
0
async def showSuppliers(q: Q):
    items = [ui.tabs(name='menu', value=q.args.menu, items=tabs)]
    print('items in supplier: ' + str(items))

    ## if user clicks 'Add Supplier'
    if q.args.show_inputs:
        ## need to get manufacturer data first (later used for the dropdown when addiing new supplier)
        df_m = pd.DataFrame(l_manufacturers,
                            columns=['manufacturer', 'product'])

        ## if there is no Manufacter data, then the user should add manufacturer data first
        if len(df_m) == 0:
            items.extend([
                ui.message_bar(type='info',
                               text='Try adding manufacturer first'),
                ui.button(name='goto_manufacturer',
                          label='Close',
                          primary=True)
            ])

        ## there's a manufacturer data, then go here
        else:
            items.extend([
                ui.text_xl(content='Add Supplier'),
                ui.textbox(name='supplier', label='Supplier'),
                ui.dropdown(
                    name='manufacturer',
                    label='Manufacturer',
                    choices=[  ## dropdown existing manufacturers
                        ui.choice(name=x, label=x)
                        for x in df_m['manufacturer'].unique()
                    ]),
                ui.dropdown(
                    name='product',
                    label='Product',
                    choices=[  ## dropdown existing items
                        ui.choice(name=x, label=x)
                        for x in df_m['product'].unique()
                    ]),  ## product should based on the what manufacturer have
                # ui.dropdown(name='uom', label='Unit of Measurement', choices=[ ## dropdown unit of measurement based on UOM variable above
                #     ui.choice(name=x, label=x) for x in uom
                # ]),
                # ui.textbox(name='selling_price', label='Price'),
                # ui.textbox(name='lead_time', label='Lead Time(days)'),
                # ui.textbox(name='delivery_time', label='Delivery Time(days)'),
                ui.button(name='show_tables', label='Submit',
                          primary=True)  ## submit button
            ])

    ## user hasn't clicked 'Add suppliers' button
    else:
        ## user have click has clicked 'Submit' button after adding supplier
        if q.args.show_tables:
            l_suppliers.append(
                [q.args.supplier, q.args.manufacturer, q.args.product])  ## !!!
            s = Suppliers(q.args.supplier, q.args.manufacturer, q.args.product)
            suppliers.append(s)
            items.append(
                ui.message_bar(type='success',
                               text='You have successfully added a supplier'))

        ## default view (if there's suppliers data)
        if len(suppliers) > 0:
            items.append(
                ui.table(name='suppliers',
                         columns=column_supplier_table,
                         rows=[
                             ui.table_row(name=supplier.id,
                                          cells=[
                                              supplier.supplier,
                                              supplier.manufacturer,
                                              supplier.product
                                          ]) for supplier in suppliers
                         ],
                         groupable=True,
                         downloadable=True,
                         resettable=True,
                         height='500px'))

        ## default view (if there's a supplier data)
        else:
            items.append(ui.text_l(content='No Supplier found'))

        # items.append(ui.button(name='show_inputs', label='Add Supplier', primary=True))

        items.append(
            ui.buttons([
                ui.button(name='show_inputs',
                          label='Add Supplier',
                          primary=True),
                ui.button(name='delete_button', label='Delete Supplier'),
                ui.button(name='edit_button', label='Edit Supplier'),
            ]))

    q.page['example'] = ui.form_card(box='1 2 -1 -1', items=items)
    await q.page.save()
示例#14
0
async def showManufacturers(q: Q):
    items = [ui.tabs(name='menu', value=q.args.menu, items=tabs)]

    print('---------------------------')
    print('== MANUFACTURER TAB == ')

    ## when user is adding new manufacturer
    if q.args.show_inputs:
        items.extend([
            ui.text_xl(content='Add Manufacturer'),
            ui.textbox(name='manufacturer', label='Manufacturer'),
            ui.textbox(name='product', label='Product'),
            # ui.dropdown(name='uom', label='Unit of Measurement', choices=[
            #     ui.choice(name=x, label=x) for x in uom
            # ]),
            ui.button(name='show_tables', label='Submit', primary=True)
        ])

    # ## when user is editing existing manufacturer
    # elif q.args.edit_button:
    #   items.extend([ui.text_xl(content='Edit Manufacturer'),
    #   ui.textbox(name='manufacturer', label='Manufacturer'),
    #   # ui.textbox(name='product', label='Product'),
    #   # ui.dropdown(name='uom', label='Unit of Measurement', choices=[
    #   #     ui.choice(name=x, label=x) for x in uom
    #   # ]),
    #   ui.button(name='show_tables', label='Submit', primary=True)])

    ## default goes here
    else:

        ## user have click has clicked 'Submit' button after adding supplier
        if q.args.show_tables:
            l_manufacturers.append([q.args.manufacturer, q.args.product])
            m = Manufacturers(q.args.manufacturer, q.args.product)
            manufacturers.append(m)

            items.append(
                ui.message_bar(type='success',
                               text='You have successfully added a product'))

            ## GET ALL MANUFACTURERS DATA

        ## default view (if there's a manufacturer data)
        if len(manufacturers) > 0:
            items.append(
                ui.table(name='manufacturers',
                         columns=column_manufacturer_table,
                         rows=[
                             ui.table_row(name=manufacturer.id,
                                          cells=[
                                              manufacturer.manufacturer,
                                              manufacturer.product
                                          ]) for manufacturer in manufacturers
                         ],
                         groupable=True,
                         downloadable=True,
                         resettable=True,
                         height='500px'))

        ## GET ALL MANUFACTURERS DATA

        ## default view (if there's no manufacturer data)
        else:
            items.append(ui.text_l(content='No Manufacturer found'))

        # items.append(ui.button(name='show_inputs', label='Add Manufacturer', primary=True))
        items.append(
            ui.buttons([
                ui.button(name='show_inputs',
                          label='Add Manufacturer',
                          primary=True),
                ui.button(name='delete_button', label='Delete Manufacturer'),
                ui.button(name='edit_button', label='Edit Manufacturer'),
            ]))

    q.page['example'] = ui.form_card(box='1 2 -1 -1', items=items)
    await q.page.save()
示例#15
0
async def run_app(q: Q):
    if q.args.start_game:
        if q.args.submit_game:
            q.client.game.is_public = True
            q.app.games[q.client.game.game_id] = q.client.game
        del q.page['leaderboard']
        del q.page['hello']
        await start_new_game(q)
    elif q.args.quit_game:
        del q.page['starting_game']
        await make_welcome_card(q)
    elif q.args.guess:
        message = q.client.game.guess(q.args.guess)
        if message == 'You Got It!':
            q.page['starting_game'].items = [
                ui.text_l(
                    f'­ЪЈЁ ­ЪјЅ ­Ъјѓ You Got It, The number is **{q.client.game.number}**'
                ),
                ui.text_m(
                    f'You made **{len(q.client.game.guesses)}** guesses in'),
                ui.text_m(f'{q.client.game.game_time()}.'),
                ui.toggle(
                    name='submit_game',
                    label='Submit your game to Public Scoreboard',
                    trigger=False,
                ),
                ui.text_xs('Рађ'),
                ui.buttons(
                    items=[
                        ui.button(
                            name='leaderboard',
                            label='View Scores',
                            primary=True,
                        ),
                        ui.button(
                            name='start_game',
                            label='Play Again',
                            primary=False,
                        ),
                    ],
                    justify='center',
                ),
            ]
        else:
            previous_guesses = [str(x) for x in q.client.game.guesses]
            if len(previous_guesses) > 16:
                previous_guesses = previous_guesses[-16:]
                previous_guesses[0] = '...'
            guesses_str = ", ".join(previous_guesses)
            q.page['starting_game'].items = [
                ui.text_l(message),
                ui.text_m(guesses_str),
                ui.text_xs('Рађ'),
                ui.slider(
                    name='guess',
                    label='your guess',
                    min=1,
                    max=100,
                    value=q.args.guess,
                    trigger=True,
                ),
                ui.text_xs('Рађ'),
                ui.buttons(
                    items=[
                        ui.button(name='quit_game', label='Quit', primary=True)
                    ],
                    justify='center',
                ),
            ]
    elif q.args.leaderboard:
        if q.args.submit_game:
            q.client.game.is_public = True
            q.app.games[q.client.game.game_id] = q.client.game
        del q.page['starting_game']
        await show_leaderboard(q)
    elif q.args.private_leaderboard:
        await show_private_leaderboard(q)

    await q.page.save()
async def serve(q: Q):
    q.page['example'] = ui.form_card(box='1 1 4 10', items=[
        ui.text_xl(content='Extra-large text, for headings.'),
        ui.text_l(content='Large text, for sub-headings.'),
        ui.text_m(content='Body text, for paragraphs and other content.'),
        ui.text_s(content='Small text, for small print.'),
        ui.text_xs(content='Extra-small text, for really small print.'),
        ui.separator(label='A separator sections forms'),
        ui.progress(label='A progress bar'),
        ui.progress(label='A progress bar'),
        ui.message_bar(type='success', text='Message bar'),
        ui.textbox(name='textbox', label='Textbox'),
        ui.label(label='Checkboxes'),
        ui.checkbox(name='checkbox1', label='A checkbox'),
        ui.checkbox(name='checkbox1', label='Another checkbox'),
        ui.checkbox(name='checkbox1', label='Yet another checkbox'),
        ui.toggle(name='toggle', label='Toggle'),
        ui.choice_group(name='choice_group', label='Choice group', choices=[
            ui.choice(name=x, label=x) for x in ['Egg', 'Bacon', 'Spam']
        ]),
        ui.checklist(name='checklist', label='Checklist', choices=[
            ui.choice(name=x, label=x) for x in ['Egg', 'Bacon', 'Spam']
        ]),
        ui.dropdown(name='dropdown', label='Dropdown', choices=[
            ui.choice(name=x, label=x) for x in ['Egg', 'Bacon', 'Spam']
        ]),
        ui.dropdown(name='dropdown', label='Multi-valued Dropdown', values=[], choices=[
            ui.choice(name=x, label=x) for x in ['Egg', 'Bacon', 'Spam']
        ]),
        ui.combobox(name='combobox', label='Combobox', choices=['Choice 1', 'Choice 2', 'Choice 3']),
        ui.slider(name='slider', label='Slider'),
        ui.range_slider(name='range_slider', label='Range slider', max=99),
        ui.spinbox(name='spinbox', label='Spinbox'),
        ui.date_picker(name='date_picker', label='Date picker'),
        ui.color_picker(name='color_picker', label='Color picker'),
        ui.buttons([
            ui.button(name='primary_button', label='Primary', primary=True),
            ui.button(name='standard_button', label='Standard'),
            ui.button(name='standard_disabled_button', label='Standard', disabled=True),
        ]),
        ui.file_upload(name='file_upload', label='File upload'),
        ui.table(name='table', columns=[
            ui.table_column(name='col1', label='Column 1'),
            ui.table_column(name='col2', label='Column 2'),
        ], rows=[
            ui.table_row(name='row1', cells=['Text A', 'Text B']),
            ui.table_row(name='row2', cells=['Text C', 'Text D']),
            ui.table_row(name='row3', cells=['Text E', 'Text F']),
        ]),
        ui.link(label='Link'),
        ui.tabs(name='tabs', items=[
            ui.tab(name='email', label='Mail', icon='Mail'),
            ui.tab(name='events', label='Events', icon='Calendar'),
            ui.tab(name='spam', label='Spam'),
        ]),
        ui.expander(name='expander', label='Expander'),
        ui.frame(path='https://example.com'),
        ui.markup(content=html),
        ui.template(
            content=menu,
            data=pack(dict(dishes=[
                dict(name='Spam', price='$2.00'),
                dict(name='Ham', price='$3.45'),
                dict(name='Eggs', price='$1.75'),
            ]))
        ),
        ui.picker(name='picker', label='Picker', choices=[
            ui.choice('choice1', label='Choice 1'),
            ui.choice('choice2', label='Choice 2'),
            ui.choice('choice3', label='Choice 3'),
        ]),
        ui.stepper(name='stepper', items=[
            ui.step(label='Step 1', icon='MailLowImportance'),
            ui.step(label='Step 2', icon='TaskManagerMirrored'),
            ui.step(label='Step 3', icon='Cafe'),
        ]),
        ui.visualization(
            plot=ui.plot([ui.mark(type='interval', x='=product', y='=price', y_min=0)]),
            data=data(fields='product price', rows=[(c, x) for c, x, _ in [f.next() for _ in range(n)]], pack=True),
        ),
        ui.vega_visualization(
            specification=spec,
            data=data(fields=["a", "b"], rows=[
                ["A", rnd()], ["B", rnd()], ["C", rnd()],
                ["D", rnd()], ["E", rnd()], ["F", rnd()],
                ["G", rnd()], ["H", rnd()], ["I", rnd()]
            ], pack=True),
        ),
        ui.button(name='show_inputs', label='Submit', primary=True),
    ])
    await q.page.save()
示例#17
0
def add_text_card(box, text):
    return ui.form_card(box=box, items=[ui.text_l(text)])
async def responsive_layout(q: Q):
    if not q.user.columns:
        q.user.columns = [
            ui.table_column(name='Index',
                            label='Index',
                            searchable=True,
                            sortable=True,
                            data_type='number'),
            ui.table_column(name='Started', label='Started', searchable=True),
            ui.table_column(name='Ended', label='Ended', searchable=True),
            ui.table_column(name='Duration',
                            label='Duration (mins)',
                            data_type='number'),
            ui.table_column(name='Scores', label='Scores', data_type='number'),
        ]

    if not q.client.LB_columns:
        q.client.LB_columns = [
            ui.table_column(name='User',
                            label='User',
                            searchable=True,
                            max_width='100px'),
            ui.table_column(name='Scores',
                            label='Scores',
                            searchable=True,
                            max_width='100px',
                            sortable=True),
        ]

    q.page['meta'] = ui.meta_card(
        box='',
        title='Streak Counter',
        layouts=[
            ui.layout(
                # If the viewport width >= 0:
                breakpoint='xs',
                zones=[
                    # 80px high header
                    ui.zone('header', size='80px'),
                    # Use remaining space for content
                    ui.zone('content')
                ]),
            ui.layout(
                # If the viewport width >= 768:
                breakpoint='m',
                zones=[
                    # 80px high header
                    ui.zone('header', size='80px'),
                    # Use remaining space for body
                    ui.zone(
                        'body',
                        direction=ui.ZoneDirection.ROW,
                        zones=[
                            # 250px wide sidebar
                            ui.zone('sidebar', size='250px'),
                            # Use remaining space for content
                            ui.zone('content'),
                        ]),
                    ui.zone('footer'),
                ]),
            ui.layout(
                # If the viewport width >= 1200:
                breakpoint='xl',
                width='1200px',
                zones=[
                    # 80px high header
                    ui.zone('header', size='80px'),
                    # Use remaining space for body
                    ui.zone(
                        'body',
                        direction=ui.ZoneDirection.ROW,
                        zones=[
                            # 300px wide sidebar
                            ui.zone('sidebar', size='300px'),
                            # Use remaining space for other widgets
                            ui.zone(
                                'other',
                                zones=[
                                    # Use one half for charts
                                    ui.zone('charts',
                                            direction=ui.ZoneDirection.ROW),
                                    # Use other half for content
                                    ui.zone('content', size='500px'),
                                ]),
                        ]),
                    ui.zone('footer'),
                ])
        ])

    q.page['header'] = ui.header_card(
        # Place card in the header zone, regardless of viewport size.
        box='header',
        title='Code Streak Counter',
        subtitle='Count your programming Streak while staying healthy !!!',
    )
    q.page['LeaderBoard'] = ui.form_card(
        # If the viewport width >= 0, place in content zone.
        # If the viewport width >= 768, place in sidebar zone.
        # If the viewport width >= 1200, place in sidebar zone.
        box=ui.boxes('content', 'sidebar', 'sidebar'),
        # title='Leader Board',
        items=[
            ui.text_l(content=f"Hi {q.auth.username.capitalize()}..!"),
            ui.text_xl(
                content=
                f"Your Total Score: {q.user.stop_watch.df['Scores'].sum()}"),
            ui.table(
                name='leaderboard',
                columns=q.client.LB_columns,
                rows=[
                    ui.table_row(name=user, cells=[user, str(score)])
                    for user, score in q.app.lb_dict.items()
                ],
                groupable=False,
                downloadable=True,
                resettable=False,
                height='425px',
            ),
            ui.link(name='logout',
                    label='Log Out',
                    button=True,
                    path=f'/_logout',
                    target='_current')
        ],
    )
    q.page['stopwatch'] = ui.form_card(
        box=ui.boxes(
            # If the viewport width >= 0, place as second item in content zone.
            ui.box(zone='content', order=2),
            # If the viewport width >= 768, place in content zone.
            'content',
            # If the viewport width >= 1200, place as first item in charts zone, use 2 parts of available space.
            ui.box(zone='charts', order=1, size=2),
        ),
        items=[
            ui.text_xl(
                content=
                f"<h1><center>{str(q.user.stop_watch.minutes).zfill(2)} : {str(q.user.stop_watch.seconds).zfill(2)}</center></h1>"
            ),
            ui.text_l(content=f"<center>Lets crack some code!</center>"),
            ui.buttons([
                ui.button(name='start', label='Start', primary=True),
                ui.button(name='stop', label='Stop', primary=False)
            ],
                       justify='center')
        ],
    )
    q.page['UserStreaks'] = ui.markdown_card(
        box=ui.boxes(
            # If the viewport width >= 0, place as third item in content zone.
            ui.box(zone='content', order=3),
            # If the viewport width >= 768, place as second item in content zone.
            ui.box(zone='content', order=2),
            # If the viewport width >= 1200, place as second item in charts zone, use 1 part of available space.
            ui.box(zone='charts', order=2, size=1),
        ),
        title='User Streaks',
        content="""=Last Streak Started: {{streak_start}}

<p data-test='UserStreaks_Last_Ended'>Last Streak Ended: {{streak_end}}</p>

<p data-test='UserStreaks_Total_Streaks'>Total Streaks: {{total_streaks}}</p>

Total Coding Time: {{total_time}}
""",
        data=dict(streak_start=q.user.stop_watch.last_start,
                  streak_end=q.user.stop_watch.last_stop,
                  total_streaks=q.user.stop_watch.total_streaks,
                  total_time=f"{str(q.user.stop_watch.total_hours).zfill(2)} :\
                            {str(q.user.stop_watch.total_minutes).zfill(2)} : \
                            {str(q.user.stop_watch.total_seconds).zfill(2)}"))
    q.page['history'] = ui.form_card(
        box=ui.boxes(
            # If the viewport width >= 0, place as fourth item in content zone.
            ui.box(zone='content', order=4),
            # If the viewport width >= 768, place as third item in content zone.
            ui.box(zone='content', order=3),
            # If the viewport width >= 1200, place in content zone.
            'content'),
        items=[
            ui.table(name='streaks_table',
                     columns=q.user.columns,
                     rows=[
                         ui.table_row(name=str(row.Index + 1),
                                      cells=[
                                          str(row.Index + 1), row.Started,
                                          row.Ended,
                                          str(row.Duration),
                                          str(row.Scores)
                                      ])
                         for row in q.user.stop_watch.df.itertuples()
                     ],
                     groupable=False,
                     downloadable=True,
                     resettable=False,
                     height='425px')
        ],
        title='History',
    )
    q.page['footer'] = ui.footer_card(box='footer', caption='(c) 2021 H2O.ai ')
示例#19
0
# Form / Links
# Use links to allow #navigation to multiple internal and external URLs.
# #form #link
# ---
from h2o_wave import site, ui

page = site['/demo']

page['example'] = ui.form_card(
    box='1 1 3 3',
    items=[
        ui.text_l(content='**Vertical set of links with a label**'),
        ui.links(label='Second Column',
                 items=[
                     ui.link(label='Sample link',
                             path='https://www.h2o.ai/',
                             target='_blank'),
                     ui.link(label='Sample link',
                             path='https://www.h2o.ai/',
                             target='_blank'),
                     ui.link(label='Sample link',
                             path='https://www.h2o.ai/',
                             target='_blank'),
                 ]),
        ui.text_l(content='**Horizontal set of links**'),
        ui.links(inline=True,
                 items=[
                     ui.link(label='Sample link',
                             path='https://www.h2o.ai/',
                             target='_blank'),
                     ui.link(label='Sample link',
# Form / Text / Sizes
# Use text size variants to display formatted text using predefined font sizes.
# ---
from h2o_wave import site, ui

page = site['/demo']

page['example'] = ui.form_card(
    box='1 1 4 -1',
    items=[
        ui.separator('Separator'),
        ui.text_xl('Extra large text'),
        ui.text_l('Large text'),
        ui.text('Normal text'),
        ui.text_m('Medium text'),
        ui.text_s('Small text'),
        ui.text_xs('Extra small text'),

        # Using `ui.text()` with a `size` argument produces similar results:
        ui.separator('Separator'),
        ui.text('Extra large text', size=ui.TextSize.XL),
        ui.text('Large text', size=ui.TextSize.L),
        ui.text('Normal text'),
        ui.text('Medium text', size=ui.TextSize.M),
        ui.text('Small text', size=ui.TextSize.S),
        ui.text('Extra small text', size=ui.TextSize.XS),
    ],
)
page.save()
示例#21
0
def show_form(q: Q):
    q.page["meta"] = ui.meta_card(
        box="",
        title="Tennis Match Prediction",
        refresh=1,
        layouts=[
            ui.layout(
                breakpoint="xs",
                width="1200px",
                zones=[
                    ui.zone("header"),
                    ui.zone("tournament"),
                    ui.zone(
                        "players",
                        direction=ui.ZoneDirection.ROW,
                        zones=[
                            ui.zone("player1", size="50%"),
                            ui.zone("player2", size="50%"),
                        ],
                    ),
                    ui.zone("submit", size="50%"),
                    ui.zone("result", size="50%"),
                ],
            )
        ],
    )

    q.page["header"] = ui.header_card(
        box="header", title="Tennis Match Prediction", subtitle=""
    )

    q.page["tournament"] = ui.form_card(
        box="tournament",
        items=[
            # Tournament name
            ui.dropdown(
                name="t_name",
                label="Tournament Name",
                placeholder="Wimbledon",
                choices=[
                    ui.choice(name=t_name, label=t_name) for t_name in tourn_ids.keys()
                ],
                trigger=False,
            ),
            # Round
            ui.dropdown(
                name="t_round",
                label="Round",
                placeholder="Final",
                choices=[
                    ui.choice(name=t_round, label=t_round) for t_round in round_list
                ],
                trigger=False,
            ),
        ],
    )

    q.page["p1"] = ui.form_card(
        box="player1",
        items=[
            ui.text_l("Player 1"),
            ui.dropdown(
                name="p1_name",
                label="Name",
                placeholder="Roger Federer",
                choices=[
                    ui.choice(name=p_name, label=p_name) for p_name in player_ids.keys()
                ],
                trigger=False,
            ),
            ui.textbox(name="p1_rank", label="Rank"),
            ui.textbox(name="p1_age", label="Age"),
        ],
    )

    q.page["player2"] = ui.form_card(
        box="player2",
        items=[
            ui.text_l("Player 2"),
            ui.dropdown(
                name="p2_name",
                label="Name",
                placeholder="Rafael Nadal",
                choices=[
                    ui.choice(name=p_name, label=p_name) for p_name in player_ids.keys()
                ],
                trigger=False,
            ),
            ui.textbox(name="p2_rank", label="Rank"),
            ui.textbox(name="p2_age", label="Age"),
        ],
    )

    q.page["submit"] = ui.form_card(
        box="submit",
        items=[
            ui.buttons(
                items=[ui.button(name="submit", label="Submit", primary=True)],
                justify="center",
            )
        ],
    )

    result_str = "" if not q.client.result_str else q.client.result_str

    q.page["result"] = ui.markdown_card(
        box="result",
        title="Results",
        content=result_str,
    )