Esempio n. 1
1
def edit_rules():
    """Edit rules

    Edit the rules that process inbound events"""
    my_rules = rules.get_all_rules()
    my_rules.append(DEFAULT_RULE)

    selected_rule_id = select(
        label="Existing rules",
        options=[{
            "label": rule["name"],
            "value": rule["id"]
        } for rule in my_rules],
    )
    # Rules have unique IDs from the database:
    logging.info(f"selected_rule: {selected_rule_id}")
    use_rule = [r for r in my_rules if r["id"] == int(selected_rule_id)][0]
    updated_rule = input_group(
        "Rule editing",
        [
            input("name",
                  type=TEXT,
                  name="name",
                  value=use_rule["name"],
                  required=True),  # Need ttextarea(
            textarea(
                "Rule names",
                name="rule",
                rows=10,
                code={
                    "mode": "python",  # code language
                    "theme":
                    "darcula",  # Codemirror theme. Visit https://codemirror.net/demo/theme.html#cobalt to get more themes
                },
                value=f"""{use_rule['rule']}\n""",
            ),
            actions(
                "actions",
                [
                    # {"label": "test", "value": "test"},
                    {
                        "label": "save",
                        "value": "save"
                    },
                ],
                name="action",
                help_text="Save",
            ),
        ],
    )
    if updated_rule is not None:
        rl = dict(updated_rule)
        if rl["action"] == "save":
            rule_info = rules.save_rule(rl["name"], rl["rule"],
                                        selected_rule_id)
            put_row(put_text("Rule"))
            put_row(put_code(pprint.pformat(rule_info, indent=1)))
            # Use webhook_info's ID to add/update the extractor

    put_text(f"The rule added is: {updated_rule}")
Esempio n. 2
0
def index():
    print("run")
    put_text("12345")
    out = output()
    put_scrollable(out, keep_bottom=True)

    while True:
        il = input_group("233", [input(name="aaa", value="23456")])
        outp(out, il)
Esempio n. 3
0
def main():
    """PyWebIO聊天室
    和当前所有在线的人聊天
    """
    global chat_msgs
    run_js("alert('233')")
    put_markdown(
        "## PyWebIO聊天室\n欢迎来到聊天室,你可以和当前所有在线的人聊天。你可以在浏览器的多个标签页中打开本页面来测试聊天效果。"
        "本应用使用不到80行代码实现,源代码[链接](https://github.com/wang0618/PyWebIO/blob/dev/demos/chat_room.py)",
        lstrip=True)

    msg_box = output()
    put_scrollable(msg_box, height=300, keep_bottom=True)
    nickname = input("请输入你的昵称",
                     required=True,
                     validate=lambda n: '昵称已被使用'
                     if n in online_users or n == '📢' else None)

    online_users.add(nickname)
    chat_msgs.append(
        ('📢', '`%s`加入聊天室. 当前在线人数 %s' % (nickname, len(online_users))))
    msg_box.append(
        put_markdown('`📢`: `%s`加入聊天室. 当前在线人数 %s' %
                     (nickname, len(online_users))))

    @defer_call
    def on_close():
        online_users.remove(nickname)
        chat_msgs.append(
            ('📢', '`%s`退出聊天室. 当前在线人数 %s' % (nickname, len(online_users))))

    refresh_task = run_async(refresh_msg(nickname, msg_box))

    while True:
        data = input_group('发送消息', [
            input(name='msg', help_text='消息内容支持行内Markdown语法'),
            actions(name='cmd',
                    buttons=['发送', '多行输入', {
                        'label': '退出',
                        'type': 'cancel'
                    }])
        ],
                           validate=lambda d: ('msg', '消息不为空')
                           if d['cmd'] == '发送' and not d['msg'] else None)
        if data is None:
            break
        if data['cmd'] == '多行输入':
            data['msg'] = '\n' + textarea('消息内容', help_text='消息内容支持Markdown语法')
        msg_box.append(
            put_markdown('`%s`: %s' % (nickname, data['msg']), sanitize=True))
        chat_msgs.append((nickname, data['msg']))

    refresh_task.close()
    toast("你已经退出聊天室")
Esempio n. 4
0
def demo():

    inputs = input_group("Salary Prediction", [
        input("Enter your age: ", type=NUMBER, name='age'),
        input("Enter your years of experience: ", type=NUMBER, name="year_exp")
    ])

    if (inputs["age"] >= 16
            and inputs["age"] <= 20) and (inputs["year_exp"] <= 1):
        put_text("Your Expected Salary: {}".format(10000))
    elif (inputs["age"] >= 21
          and inputs["age"] <= 26) and (inputs["year_exp"] >= 2
                                        and inputs["year_exp"] < 5):
        put_text("Your Expected Salary: {}".format(40000))
    elif (inputs["age"] >= 27) and (inputs["year_exp"] >= 5):
        put_text("Your Expected Salary: {}".format(90000))
    else:
        put_text("Not in scoped rules!")
Esempio n. 5
0
def getInfo():
    info = input_group("Fuqaro haqida ma'lumot", [
        input('Ism', name='ism'),
        input(
            'Familiya',
            name='familiya',
        ),
        input(
            'Otasining ismi',
            name='otasi',
        ),
        input(
            "Tug'ilgan yil",
            name='tyil',
        ),
        input(
            "Tug'ilgan kun",
            name='tkun',
        ),
        input(
            "Tug'ilgan oy",
            name='toy',
        ),
        input(
            'Telefon raqami',
            name='telefon',
        ),
        input(
            'Pasport seriyasi',
            name='seriya',
        ),
        input(
            'Pasport raqami',
            name='pass_raqam',
        ),
        input(
            'Passport berilgan sana',
            name='pass_sana',
        )
    ])
    return info
Esempio n. 6
0
    def loop():
        while True:
            data = input_group(inputs=get_inputs())
            if data is None:
                save()
                break

            if data['action'] == 'Next':

                modified[V.lang][f'{V.group}.{V.arg}.{V.key}'] = data[
                    V.lang].replace("\\n", "\n")
                deep_set(dict_lang[V.lang], f'{V.group}.{V.arg}.{V.key}',
                         data[V.lang].replace("\\n", "\n"))
                next_key()
            if data['action'] == 'Skip':
                next_key()
            elif data['action'] == 'Submit':

                modified[V.lang][f'{V.group}.{V.arg}.{V.key}'] = data[
                    V.lang].replace("\\n", "\n")
                deep_set(dict_lang[V.lang], f'{V.group}.{V.arg}.{V.key}',
                         data[V.lang].replace("\\n", "\n"))
                continue
Esempio n. 7
0
def bmi_app():
    name=input("Whats Your name")
    put_text('Hi, welcome to our website', name)

    user_info=input_group("User_info",[input('Whats Your age?',name='age',type=FLOAT)
                                ])
    if user_info['age']<16:
        put_warning('Sorry You cant access our website')
    else:
        put_success('Congrats, You can use our website!')
        
        height = input("Input your height(cm):", type=FLOAT)
        weight = input("Input your weight(kg):", type=FLOAT)

        BMI = weight / (height / 100) ** 2

        top_status = [(16, 'Severely underweight'), (18.5, 'Underweight'),
                  (25, 'Normal'), (30, 'Overweight'),
                  (35, 'Moderately obese'), (float('inf'), 'Severely obese')]

        for top, status in top_status:
            if BMI <= top:
                put_text('Your BMI: %.1f. Category: %s' % (BMI, status))
                break
Esempio n. 8
0
 def setting():
     data = input_group(inputs=[
         select(name='language',
                label='Language',
                options=LANGUAGES,
                value=V.lang,
                required=True),
         checkbox(
             name='check',
             label='Other settings',
             options=[{
                 "label": 'Button [Next] only shows untranslated key',
                 'value': 'untranslated',
                 'selected': V.untranslated_only
             }, {
                 "label":
                 'Do not fill input with old value (only effect the language you selected)',
                 "value": "clear",
                 "selected": V.clear
             }])
     ])
     V.lang = data['language']
     V.untranslated_only = True if 'untranslated' in data['check'] else False
     V.clear = True if 'clear' in data['check'] else False
Esempio n. 9
0
def edit_webhook():
    """Edit webhook and its extractor

    This should be changed to work with a programattically named
    webhook that has a randmoly named inbound address. For now, we
    name it I guess

    """
    my_hooks = extractions.get_all_webhooks()
    my_hooks.append({
        "id": 0,
        "name": "Your new webhook could go here!",
        "path": "Enter the path that this will be matched on",
        "queue_name": "base name for the queue",
    })

    selected_hook_id = select(
        label="Existing webhooks",
        options=[{
            "label": hook.get("name", "No hook name found"),
            "value": hook.get("id", 0),
        } for hook in my_hooks],
    )
    # Rules have unique IDs from the database:
    logging.info(f"selected_hook: {selected_hook_id}")

    my_hook = dict()
    my_extractor = dict()
    my_hook.update(DEFAULT_HOOK)
    my_extractor.update(DEFAULT_EXTRACTOR)
    if selected_hook_id != 0:
        my_hook = extractions.get_webhook(selected_hook_id)
        my_extractor = extractions.get_hook_extractor(selected_hook_id)

    # TODO: update validator to avoid default hook 0 names
    updated_extractor = input_group(
        "Hook data and hook extractor",
        [
            input("name",
                  type=TEXT,
                  name="name",
                  value=my_hook["name"],
                  required=True),  # Need to get a way to carry around the IDs
            input("path",
                  type=TEXT,
                  name="path",
                  value=my_hook["path"],
                  required=True),  # Need to get a way to carry around the IDs
            input(
                "queue_name",
                type=TEXT,
                name="queue_name",
                value=my_hook["queue_name"],
                required=True,
            ),  # Need to get a way to carry around the IDs
            textarea(
                "Example message",
                name="example",
                rows=10,
                code={
                    "mode": "python",  # code language
                    "theme":
                    "darcula",  # Codemirror theme. Visit https://codemirror.net/demo/theme.html#cobalt to get more themes
                },
                value=my_extractor["example"],
            ),
            textarea(
                "Edit an extraction rule",
                name="extractor",
                rows=10,
                code={
                    "mode": "python",  # code language
                    "theme":
                    "darcula",  # Codemirror theme. Visit https://codemirror.net/demo/theme.html#cobalt to get more themes
                },
                value=my_extractor["extractor"],
            ),
            actions(
                "actions",
                [
                    {
                        "label": "test",
                        "value": "test"
                    },
                    {
                        "label": "save",
                        "value": "save"
                    },
                ],
                name="action",
                help_text="Save or test",
            ),
        ],
        validate=test_extractor,
    )
    # Pretty much can't be none, but let's follow the example from
    # https://pywebio.readthedocs.io/en/latest/input.html#pywebio.input.actions
    if updated_extractor is not None:
        uex = dict(updated_extractor)
        if uex["action"] == "save":
            webhook_info = extractions.save_webhook(selected_hook_id,
                                                    uex["name"], uex["path"],
                                                    uex["queue_name"])
            extractor_info = extractions.save_extractor(
                uex["name"], webhook_info["id"], uex["extractor"],
                uex["example"])
            put_row(put_text("Webhook"))
            put_row(put_code(pprint.pformat(webhook_info, indent=1)))
            put_row(put_text("Extractor"))
            put_row(put_code(pprint.pformat(extractor_info, indent=1)))
#!/usr/bin/env python3
# vim: set fileencoding=utf-8

import pywebio.input as inp
import pywebio.output as out

# Body Mass Index calculator

info = inp.input_group("Entry", [
    inp.input("Mass (kg)", name="mass", type=inp.NUMBER, required=True),
    inp.input("Height (cm)", name="height", type=inp.NUMBER, required=True)
])

mass = info["mass"]
height = info["height"]

# převod výšky na metry
height = height / 100.0

# výpočet (bez jakýchkoli kontrol)
bmi = mass / (height * height)

# výpis výsledku
out.put_info("BMI = ", bmi)
Esempio n. 11
0
#!/usr/bin/env python3
# vim: set fileencoding=utf-8

import pywebio.input as inp
import pywebio.output as out

# Body Mass Index calculator

info = inp.input_group("Entry", [
    inp.input("Mass (kg)", name="mass"),
    inp.input("Height (cm)", name="height")
])

mass = float(info["mass"])
height = float(info["height"])

# převod výšky na metry
height = height / 100.0

# výpočet (bez jakýchkoli kontrol)
bmi = mass / (height * height)

# výpis výsledku
out.put_info("BMI = ", bmi)