예제 #1
0
def ui_table_from_df(df: pd.DataFrame,
                     name: str = '',
                     sortables: list = None,
                     filterables: list = None,
                     searchables: list = None,
                     min_widths: dict = None,
                     max_widths: dict = None,
                     multiple: bool = False,
                     link_col: str = None,
                     height: str = '500px') -> ui.table:
    """
    Convert a dataframe into Q ui.table format.
    """
    if not sortables:
        sortables = []
    if not filterables:
        filterables = []
    if not searchables:
        searchables = []
    if not min_widths:
        min_widths = {}
    if not max_widths:
        max_widths = {}

    columns = [
        ui.table_column(
            name=str(x),
            label=str(x),
            sortable=True if x in sortables else False,
            filterable=True if x in filterables else False,
            searchable=True if x in searchables else False,
            min_width=min_widths[x] if x in min_widths.keys() else None,
            max_width=max_widths[x] if x in max_widths.keys() else None,
            link=True if x == link_col else False) for x in df.columns.values
    ]

    try:
        table = ui.table(name=name,
                         columns=columns,
                         rows=[
                             ui.table_row(name=str(i),
                                          cells=[
                                              str(df[col].values[i])
                                              for col in df.columns.values
                                          ]) for i in range(df.shape[0])
                         ],
                         multiple=multiple,
                         height=height)
    except Exception:
        table = ui.table(
            name=name,
            columns=[ui.table_column('x', 'x')],
            rows=[ui.table_row(name='ndf', cells=[str('No data found')])])

    return table
예제 #2
0
async def render_customer_selector(q: Q):

    clear_page(q)

    columns = [
        ui.table_column(name=column,
                        label=column,
                        sortable=True,
                        searchable=True)
        for column in q.app.customer_df.columns
    ]
    rows = [
        ui.table_row(name=str(index), cells=row.tolist())
        for index, row in q.app.customer_df.applymap(str).iterrows()
    ]
    q.client.cards.add('customer_table')
    q.page['customer_table'] = ui.form_card(
        box='customer_table',
        items=[
            ui.message_bar(text='Click "Status" to review a customer',
                           type='info'),
            ui.table(
                name='customer_table',
                columns=columns,
                rows=rows,
                groupable=True,
                multiple=False,
            )
        ])
def make_issue_table(allow_multiple_selection=False):
    return ui.table(
        name='issues',
        columns=columns,
        rows=[ui.table_row(name=issue.id, cells=[issue.text, issue.status, str(issue.views)]) for issue in issues],
        multiple=allow_multiple_selection
    )
예제 #4
0
def dai_instances_table(dai_instances: list):
    # dai instances in ui.table
    return ui.table(
        name='table_dai',
        columns=[
            ui.table_column(name='id',
                            label='Id',
                            min_width='50px',
                            max_width='51px',
                            link=False),
            ui.table_column(name='name', label='Name', link=False),
            ui.table_column(name='status',
                            label='Status',
                            cell_type=ui.icon_table_cell_type(color='#CDDD38'),
                            link=False),
            ui.table_column(name='description',
                            label='Description',
                            link=False),
            ui.table_column(name='version', label='Version', link=False)
        ],
        rows=[
            ui.table_row(str(i), [
                str(dai_instances[i]['id']), dai_instances[i]['name'],
                ICON_MAP[dai_instances[i]['status']],
                dai_instances[i]['status'], dai_instances[i]['version']
            ]) for i in range(len(dai_instances))
        ])
예제 #5
0
def render_customer_details_table(q: Q, df, row):
    q.page.add(
        'risk_table_row',
        ui.form_card(box='risk_table_selected',
                     items=[
                         ui.table(name='risk_table_row',
                                  columns=[
                                      ui.table_column(name="attribute",
                                                      label="Attribute",
                                                      sortable=False,
                                                      searchable=False,
                                                      max_width='100'),
                                      ui.table_column(name="value",
                                                      label="Value",
                                                      sortable=False,
                                                      searchable=False,
                                                      max_width='100')
                                  ],
                                  rows=get_transformed_df_rows(
                                      q, df.loc[[row]]),
                                  groupable=False,
                                  resettable=False,
                                  multiple=False,
                                  height='100%')
                     ]))
예제 #6
0
def make_ui_table(file_path: str,
                  name: str,
                  n_rows: int = 20,
                  first_col: str = None):
    """Creates a ui.table object from a csv file"""

    df = pd.read_csv(file_path)
    df = df.replace(np.nan, '', regex=True)
    n_rows = min(n_rows, df.shape[0])
    columns = [
        ui.table_column(name=str(x), label=str(x), sortable=True)
        for x in df.columns.values
    ]
    if first_col is not None:
        columns[0] = ui.table_column(name=first_col,
                                     label=first_col,
                                     sortable=True)
    table = ui.table(name=name,
                     columns=columns,
                     rows=[
                         ui.table_row(name=str(i),
                                      cells=[
                                          str(df[col].values[i])
                                          for col in df.columns.values
                                      ]) for i in range(n_rows)
                     ])
    return table
예제 #7
0
async def serve(q: Q):
    if not q.client.initialized:
        q.page['form'] = ui.form_card(
            box='1 1 -1 11',
            items=[
                ui.textbox(name='search',
                           label='Search',
                           placeholder='Enter a keyword...',
                           trigger=True),
                ui.table(name='issues',
                         columns=[
                             ui.table_column(name=name, label=name)
                             for name in column_names
                         ],
                         rows=df_to_rows(addresses))
            ])
        q.client.initialized = True
    else:
        items = q.page['form'].items
        search_box = items[0].textbox
        table = items[1].table
        term: str = q.args.search
        term = term.strip() if term else ''
        search_box.value = term
        table.rows = df_to_rows(
            search_df(addresses, term) if len(term) else addresses)

    await q.page.save()
예제 #8
0
async def serve(q: Q):
    q.page['example'] = ui.form_card(box='1 1 6 7', items=[
        ui.table(
            name='issues',
            columns=columns,
            rows=[ui.table_row(name=issue.id, cells=[issue.text, issue.tag]) for issue in issues],
        )
    ])
    await q.page.save()
예제 #9
0
async def serve(q: Q):
    q.page['form'] = ui.form_card(box='1 1 -1 11', items=[
        ui.table(
            name='issues',
            columns=columns,
            rows=[ui.table_row(
                name=issue.id,
                cells=[issue.text, issue.status, issue.notifications, issue.icon, str(issue.views),
                       str(issue.progress)]) for issue in issues],
        )
    ])
    await q.page.save()
예제 #10
0
def make_ui_table(file_path: str, n_rows: int, name: str):
    """Creates a ui.table object from a csv file"""

    df = pd.read_csv(file_path)
    n_rows = min(n_rows, df.shape[0])

    table = ui.table(
        name=name,
        columns=[ui.table_column(name=str(x), label=str(x), sortable=True) for x in df.columns.values],
        rows=[ui.table_row(name=str(i), cells=[str(df[col].values[i]) for col in df.columns.values])
              for i in range(n_rows)]
    )
    return table
예제 #11
0
async def serve(q: Q):
    if q.args.show_inputs:
        q.page['example'].items = [
            ui.text(f'selected={q.args.issues}'),
            ui.button(name='show_form', label='Back', primary=True),
        ]
    else:
        q.page['example'] = ui.form_card(box='1 1 -1 11', items=[
            ui.table(
                name='issues',
                columns=columns,
                rows=[ui.table_row(name=issue.id, cells=[issue.text]) for issue in issues],
                values=['I1', 'I2', 'I3']
            ),
            ui.button(name='show_inputs', label='Submit', primary=True)
        ])
    await q.page.save()
예제 #12
0
def render_leaderboard(q: Q):
    logger.debug("Creating leaderboard")

    for c in q.client.cards:
        del q.page[c]

    # Create columns for our issue table.
    columns = [
        ui.table_column(name="user", label="User"),
        ui.table_column(name="total",
                        label="Total Count",
                        sortable=True,
                        data_type="number"),
    ] + [
        ui.table_column(
            name=t.common_name,
            label=t.common_name.title(),
            sortable=True,
            data_type="number",
        ) for t in q.client.trees.trees
    ]

    rows = []
    for filename in os.listdir(q.user.user.user_dir):
        trees = Trees(file=os.path.join(q.user.user.user_dir, filename))
        rows += [
            ui.table_row(
                name="row",
                cells=[q.user.user.name,
                       str(trees.get_total_trees())] +
                [str(t.count) for t in trees.trees],
            )
        ]

    table = ui.table(
        name="tree_table",
        columns=columns,
        rows=rows,
        downloadable=True,
    )

    q.page["leaderboard"] = ui.form_card(box=ui.boxes(ui.box("body"),
                                                      ui.box("top"),
                                                      ui.box("top")),
                                         items=[table])
    q.client.cards.append("leaderboard")
예제 #13
0
    async def render(self, q: Q):
        """
        Render card in Wave.

        Args:
            q: Wave server
        """
        card = ui.form_card(box=self.box,
                            items=[
                                ui.table(name='table_tokens',
                                         columns=self.get_wave_table_columns(),
                                         rows=self.get_wave_table_rows(),
                                         downloadable=True,
                                         resettable=True)
                            ],
                            title=self.title,
                            commands=self.commands)

        q.page[self.name] = card
예제 #14
0
def render_home(q: Q):
    init(q)

    df = predictor.get_testing_data_as_pd_frame()
    predicted_df = predictor.get_predict_data_as_pd_frame()
    drop_column_from_df(df, 'default.payment.next.month')
    add_column_to_df(df, predicted_df, 'Default Prediction Rate', 'predict')
    df = round_df_column(df, 'Default Prediction Rate', 4)

    q.page["risk_table"] = ui.form_card(
        box='risk_table',
        items=[
            ui.message_bar(text='Double click to review a customer',
                           type='info'),
            ui.table(name='risk_table',
                     columns=get_column_headers_for_df(df, True),
                     rows=get_rows(q, df),
                     groupable=True,
                     multiple=False,
                     height="800px")
        ])
예제 #15
0
async def serve(q: Q):
    q.page['form'] = ui.form_card(
        box='1 1 -1 11',
        items=[
            ui.table(name='issues',
                     columns=columns,
                     rows=[
                         ui.table_row(name=issue.id,
                                      cells=[
                                          issue.text, issue.status,
                                          issue.notifications, issue.icon,
                                          str(issue.views), issue.progress,
                                          issue.created
                                      ]) for issue in issues
                     ],
                     groupable=True,
                     downloadable=True,
                     resettable=True,
                     height='800px')
        ])
    await q.page.save()
예제 #16
0
def make_table(q: Q):
    n = 10
    q.client.df = pd.DataFrame({
        'length':
        np.random.rand(n),
        'width':
        np.random.rand(n),
        'data_type':
        np.random.choice(a=['Train', 'Test'], size=n, p=[0.8, 0.2])
    })

    table = ui.table(name='my_table',
                     columns=[
                         ui.table_column(name=x, label=x)
                         for x in q.client.df.columns.tolist()
                     ],
                     rows=[
                         ui.table_row(name=i,
                                      cells=q.client.df.values[i].tolist())
                         for i in range(n)
                     ])

    q.page['show_table'] = ui.form_card(box='1 1 6 6', items=[table])
예제 #17
0
async def serve(q: Q):
    hash = q.args['#']

    if hash == 'form':
        q.page['navigation'] = ui.form_card(box='1 1 -1 11', items=[
                                        ui.table(
                                            name='issues',
                                            columns=columns,
                                            rows=[ui.table_row(
                                                name=issue.id,
                                                cells=[issue.to_sid, issue.from_sid, issue.quote, issue.author,
                                                    issue.quote_category, issue.vote, str(issue.quote_length), str(issue.num_unique_words)]
                                            ) for issue in issues],
                                            groupable=True,
                                            downloadable=False,
                                            resettable=True,
                                            height='800px'
                                        ),
                                           ui.button(name='show_tabs', label='Back', primary=True),
                                    ])
    elif hash == 'home':
        q.page['navigation'] = ui.form_card(box='1 1 4 -1', items=[
            ui.text(sample_markdown),
            ui.button(name='show_tabs', label='Back', primary=True),
        ])
    else:
        q.page['navigation'] = ui.tab_card(
            box='1 1 4 1',
            items=[
                ui.tab(name='#home', label='Home'), 
                ui.tab(name='#form', label='Quote Table')
            ],
            link = True,
        )

    await q.page.save()
예제 #18
0
async def show_private_leaderboard(q: Q):
    columns = [
        ui.table_column(
            name='game_id',
            label='Game #',
            sortable=False,
            searchable=False,
            max_width='150',
            data_type='string',
            link=False,
        ),
        ui.table_column(
            name='number',
            label='Number',
            sortable=True,
            max_width='90',
            data_type='number',
        ),
        ui.table_column(
            name='num_of_guesses',
            label='# of Guesses',
            sortable=True,
            max_width='120',
            data_type='number',
        ),
        ui.table_column(
            name='status',
            label='Status',
            sortable=False,
            filterable=True,
            max_width='90',
            data_type='string',
            cell_type=ui.icon_table_cell_type(),
        ),
        ui.table_column(
            name='game_time',
            label='Time (s)',
            sortable=True,
            max_width='150',
            data_type='number',
        ),
    ]
    scores = [
        ui.table_row(
            name=game.game_id,
            cells=[
                str(idx),
                str(game.number),
                str(len(game.guesses)),
                'MedalSolid' if game.status == 'done' else 'Running',
                str(game.time_seconds()),
            ],
        ) for idx, game in enumerate(q.user.player.games.values(), 1)
    ]
    leaderboard = ui.table(
        name='leaderboard',
        columns=columns,
        rows=scores,
        groupable=False,
        downloadable=False,
        resettable=False,
        height='600px',
    )
    del q.page['starting_game']
    q.page['leaderboard'] = ui.form_card(
        box='3 2 5 9',
        items=[
            ui.label('Scores from your games'),
            leaderboard,
            ui.text_xs('Рађ'),
            ui.buttons(
                items=[
                    ui.button(name='start_game', label='Play', primary=True),
                    ui.button(name='leaderboard',
                              label='Show all games',
                              primary=True),
                ],
                justify='center',
            ),
        ],
    )
    await q.page.save()
예제 #19
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()
예제 #20
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()
예제 #21
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()
예제 #22
0
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()
예제 #23
0
async def render_customer_page(q: Q):

    clear_page(q)

    row_index = int(q.args.customer_table[0])
    customer_row = q.app.customer_df.loc[row_index]
    score = q.app.predictions_df.loc[row_index]
    approve = bool(score < APPROVAL_THRESHOLD)
    contribs = q.app.contributions_df.loc[row_index].drop('BiasTerm')

    q.client.selected_customer_id = customer_row['ID']

    # details
    q.client.cards.add('customer_features')
    q.page['customer_features'] = ui.form_card(
        box='customer_features',
        items=[
            ui.table(name='customer_features',
                     columns=[
                         ui.table_column(name='attribute',
                                         label='Attribute',
                                         sortable=False,
                                         searchable=False,
                                         max_width='100'),
                         ui.table_column(name='value',
                                         label='Value',
                                         sortable=False,
                                         searchable=False,
                                         max_width='100')
                     ],
                     rows=[
                         ui.table_row(name=index, cells=[index, row])
                         for index, row in customer_row.map(str).iteritems()
                     ],
                     groupable=False,
                     resettable=False,
                     multiple=False,
                     height='525px')
        ])

    # summary
    top_feature = contribs.idxmin(axis=1) if approve else contribs.idxmax(
        axis=1)
    explanation_data = {
        'will_or_will_not': 'will' if approve else 'will not',
        'top_contributing_feature': top_feature,
        'value_of_top_contributing_feature': str(customer_row[top_feature]),
        'accept_or_reject': 'approve' if approve else 'reject',
    }
    explanation = (
        "- This customer **{{will_or_will_not}}** most probably settle the next month credit card balance.\n"
        "- Having a **{{top_contributing_feature}}** of **{{value_of_top_contributing_feature}}** is the top reason for that.\n"
        "- It's recommended to **{{accept_or_reject}}** this customer.")
    q.client.cards.add('customer_risk_explanation')
    q.page['customer_risk_explanation'] = ui.markdown_card(
        box='customer_risk_explanation',
        title='Summary on Customer',
        content='=' + explanation,
        data=explanation_data,
    )

    # shap plot
    shap_values = list(zip(contribs.index, contribs))
    shap_values.sort(key=lambda x: x[1])
    q.client.cards.add('customer_shap_plot')
    q.page['customer_shap_plot'] = ui.plot_card(
        box='customer_shap_plot',
        title='Effectiveness of each attribute on defaulting next payment',
        data=data(['label', 'value'], rows=shap_values),
        plot=ui.plot([
            ui.mark(type='interval',
                    x='=value',
                    x_title='Feature Contributions',
                    y='=label')
        ]))

    # approve/reject buttons
    q.client.cards.add('button_group')
    q.page['button_group'] = ui.form_card(box='button_group',
                                          items=[
                                              ui.buttons([
                                                  ui.button(name='approve',
                                                            label='Approve',
                                                            primary=approve),
                                                  ui.button(
                                                      name='reject',
                                                      label='Reject',
                                                      primary=not approve),
                                              ])
                                          ])
예제 #24
0
async def show_leaderboard(q: Q):
    columns = [
        ui.table_column(
            name='name',
            label='Name',
            sortable=True,
            searchable=False,
            max_width='230',
            data_type='string',
            link=False,
        ),
        ui.table_column(
            name='number',
            label='Number',
            sortable=True,
            max_width='100',
            data_type='number',
        ),
        ui.table_column(
            name='num_of_guesses',
            label='# of Guesses',
            sortable=True,
            max_width='120',
            data_type='number',
        ),
        ui.table_column(
            name='game_time',
            label='Time (s)',
            sortable=True,
            max_width='160',
            data_type='number',
        ),
    ]
    scores = [
        ui.table_row(
            name=game.game_id,
            cells=[
                q.app.players[game.player_id].name,
                str(game.number),
                str(len(game.guesses)),
                str(game.time_seconds()),
            ],
        ) for game in q.app.games.values()
    ]
    leaderboard = ui.table(
        name='leaderboard',
        columns=columns,
        rows=scores,
        groupable=False,
        downloadable=False,
        resettable=False,
        height='600px',
    )
    del q.page['starting_game']
    q.page['leaderboard'] = ui.form_card(
        box='3 2 5 9',
        items=[
            ui.label('Scores'),
            leaderboard,
            ui.text_xs('Рађ'),
            ui.buttons(
                items=[
                    ui.button(name='start_game', label='Play', primary=True),
                    ui.button(name='leaderboard',
                              label='Refresh',
                              primary=True),
                    ui.button(
                        name='private_leaderboard',
                        label='Show my games only',
                        primary=True,
                    ),
                ],
                justify='center',
            ),
        ],
    )
    await q.page.save()
예제 #25
0
async def serve(q: Q):
    if not q.client.initialized:
        image = 'https://images.pexels.com/photos/220453/pexels-photo-220453.jpeg?auto=compress&h=750&w=1260'
        f = FakeCategoricalSeries()
        q.client.primary = '#000000'
        q.client.page = '#e2e2e2'
        q.client.card = '#ffffff'
        q.client.text = '#000000'
        q.page['meta'] = ui.meta_card(
            box='',
            theme='custom',
            layouts=[
                ui.layout(breakpoint='xs',
                          zones=[
                              ui.zone('header'),
                              ui.zone('content',
                                      direction=ui.ZoneDirection.ROW,
                                      zones=[
                                          ui.zone('colors', size='340px'),
                                          ui.zone('preview')
                                      ]),
                              ui.zone('footer')
                          ])
            ])
        q.page['header'] = ui.header_card(box='header',
                                          title='Theme generator',
                                          subtitle='Color your app easily',
                                          icon='Color',
                                          icon_color='$card')
        q.page['form'] = ui.form_card(box='colors',
                                      items=[
                                          ui.color_picker(
                                              name='primary',
                                              label='Primary',
                                              trigger=True,
                                              alpha=False,
                                              inline=True,
                                              value=q.client.primary),
                                          ui.color_picker(name='text',
                                                          label='Text',
                                                          trigger=True,
                                                          alpha=False,
                                                          inline=True,
                                                          value=q.client.text),
                                          ui.color_picker(name='card',
                                                          label='Card',
                                                          trigger=True,
                                                          alpha=False,
                                                          inline=True,
                                                          value=q.client.card),
                                          ui.color_picker(name='page',
                                                          label='Page',
                                                          trigger=True,
                                                          alpha=False,
                                                          inline=True,
                                                          value=q.client.page),
                                          ui.text_xl('Check contrast'),
                                          get_contrast('text', 'card', q),
                                          get_contrast('card', 'primary', q),
                                          get_contrast('text', 'page', q),
                                          get_contrast('page', 'primary', q),
                                          ui.text_xl('Copy code'),
                                          ui.frame(content=get_theme_code(q),
                                                   height='180px'),
                                      ])
        q.page['sample'] = ui.form_card(
            box='preview',
            items=[
                ui.text_xl(content='Sample App to show colors'),
                ui.progress(label='A progress bar'),
                ui.inline([
                    ui.checkbox(name='checkbox1',
                                label='A checkbox',
                                value=True),
                    ui.checkbox(name='checkbox2', label='Another checkbox'),
                    ui.checkbox(name='checkbox3',
                                label='Yet another checkbox'),
                    ui.toggle(name='toggle', label='Toggle', value=True),
                ]),
                ui.inline([
                    ui.date_picker(name='date_picker', label='Date picker'),
                    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.combobox(name='combobox',
                                label='Combobox',
                                choices=['Choice 1', 'Choice 2', 'Choice 3']),
                    ui.persona(title='John Doe',
                               subtitle='Data Scientist',
                               size='s',
                               image=image),
                ]),
                ui.slider(name='slider', label='Slider', value=70),
                ui.link(label='Link'),
                ui.inline(justify='between',
                          items=[
                              ui.stepper(name='stepper',
                                         width='500px',
                                         items=[
                                             ui.step(label='Step 1',
                                                     icon='MailLowImportance'),
                                             ui.step(
                                                 label='Step 2',
                                                 icon='TaskManagerMirrored'),
                                             ui.step(label='Step 3',
                                                     icon='Cafe'),
                                         ]),
                              ui.tabs(name='menu',
                                      value='email',
                                      items=[
                                          ui.tab(name='email',
                                                 label='Mail',
                                                 icon='Mail'),
                                          ui.tab(name='events',
                                                 label='Events',
                                                 icon='Calendar'),
                                          ui.tab(name='spam', label='Spam'),
                                      ]),
                          ]),
                ui.inline(items=[
                    ui.table(
                        name='table',
                        width='50%',
                        columns=[
                            ui.table_column(
                                name='name', label='Name', min_width='80px'),
                            ui.table_column(name='surname',
                                            label='Surname',
                                            filterable=True),
                            ui.table_column(name='age',
                                            label='Age',
                                            sortable=True),
                            ui.table_column(
                                name='progress',
                                label='Progress',
                                cell_type=ui.progress_table_cell_type(
                                    color='$themePrimary')),
                        ],
                        rows=[
                            ui.table_row(name='row1',
                                         cells=['John', 'Doe', '25', '0.90']),
                            ui.table_row(name='row2',
                                         cells=['Ann', 'Doe', '35', '0.75']),
                            ui.table_row(
                                name='row3',
                                cells=['Casey', 'Smith', '40', '0.33']),
                        ],
                        height='330px',
                    ),
                    ui.visualization(
                        width='50%',
                        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(20)]],
                                  pack=True),
                    ),
                ]),
                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='Disabled',
                              disabled=True),
                    ui.button(name='icon_button',
                              icon='Heart',
                              caption='Tooltip text'),
                ]),
            ])
        q.page['footer'] = ui.footer_card(
            box='footer', caption='(c) 2021 H2O.ai. All rights reserved.')
        q.client.themes = [
            ui.theme(name='custom',
                     text=q.client.text,
                     card=q.client.card,
                     page=q.client.page,
                     primary=q.client.primary)
        ]
        q.client.initialized = True

    if q.args.primary:
        q.client.themes[0].primary = q.args.primary
        q.client.primary = q.args.primary
    if q.args.text:
        q.client.themes[0].text = q.args.text
        q.client.text = q.args.text
    if q.args.card:
        q.client.themes[0].card = q.args.card
        q.client.card = q.args.card
    if q.args.page:
        q.client.themes[0].page = q.args.page
        q.client.page = q.args.page

    q.page['meta'].themes = q.client.themes
    q.page['form'].items[5] = get_contrast('text', 'card', q)
    q.page['form'].items[6] = get_contrast('card', 'primary', q)
    q.page['form'].items[7] = get_contrast('text', 'page', q)
    q.page['form'].items[8] = get_contrast('page', 'primary', q)
    q.page['form'].items[10].frame.content = get_theme_code(q)
    await q.page.save()
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 ')