예제 #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}")
예제 #2
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("你已经退出聊天室")
예제 #3
0
def demo():
    age = input("Enter your age: ", type=NUMBER)
    year_exp = input("Enter your years of experience: ", type=NUMBER)
    
    if (age >= 16 and age <=20) and (year_exp <=1):
        put_text("Your Expected Salary: {}".format(10000))
    elif (age >= 21 and age <=26) and (year_exp >= 2 and year_exp <5):
        put_text("Your Expected Salary: {}".format(40000))
    elif (age >= 27) and (year_exp >=5):
        put_text("Your Expected Salary: {}".format(90000))
    else:
        put_text("Not in scoped rules!")
예제 #4
0
def bmi():
    height = input("请输入你的身高(cm):", type=FLOAT)
    weight = input("请输入你的体重(kg):", type=FLOAT)

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

    top_status = [(14.9, '极瘦'), (18.4, '偏瘦'), (22.9, '正常'), (27.5, '过重'),
                  (40.0, '肥胖'), (float('inf'), '非常肥胖')]

    for top, status in top_status:
        if BMI <= top:
            put_text('你的 BMI 值: %.1f,身体状态:%s' % (BMI, status))
            break
예제 #5
0
def bmi():
    height = input("Your Height(cm):", type=FLOAT)
    weight = input("Your Weight(kg):", type=FLOAT)

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

    top_status = [(14.9, 'Severely underweight'), (18.4, 'Underweight'),
                  (22.9, 'Normal'), (27.5, 'Overweight'),
                  (40.0, '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
예제 #6
0
파일: bmi.py 프로젝트: MPGond/Welcome-India
def bmi():
    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
예제 #7
0
def hike():
    current_salary = input("Enter your current salary ($):", type=FLOAT)
    new_salary = input("Enter your new salary ($):", type=FLOAT)
    total_hike = (new_salary - current_salary)
    hike_per = (((new_salary - current_salary) / current_salary) * 100)
    put_markdown('# **Results**')
    put_html('<br><br>')
    put_markdown('Your Hike: %.1f. Hike percentage: %s' %
                 (total_hike, hike_per))
    put_html('<hr>')
    put_table([
        ['Hike($)', 'Hike (%)'],
        [total_hike, hike_per],
    ])
예제 #8
0
def todolist():
    tasks = []

    put_html(r"""<h1 align="center"><strong>📝 To-Do List</strong></h1>""")
    with use_scope('tasks'):
        while True:
            task = input(
                type=TEXT,
                required=True,
                label='🏃 What are you going to do today?',
                placeholder='Add a task...',
                help_text='Try: "Write an article"',
            )
            tasks.append(task)

            clear('tasks')
            put_table(
                tdata=[[
                    task,
                    put_buttons(['Complete'],
                                onclick=partial(complete_task,
                                                task=task,
                                                tasks=tasks))
                ] for task in tasks],
                header=[
                    '🤩 Your Awesome Tasks',
                    '✅ Have you completed your task?',
                ],
            )
예제 #9
0
def put_input(name,
              type='text',
              *,
              label='',
              value=None,
              placeholder=None,
              readonly=None,
              datalist=None,
              help_text=None,
              scope=None,
              position=OutputPosition.BOTTOM,
              **other_html_attrs) -> Output:
    """Output an input widget. Refer to: `pywebio.input.input()`"""
    from pywebio.input import input
    check_name(name)
    single_input_return = input(name=name,
                                label=label,
                                value=value,
                                type=type,
                                placeholder=placeholder,
                                readonly=readonly,
                                datalist=datalist,
                                help_text=help_text,
                                **other_html_attrs)
    return _pin_output(single_input_return, scope, position)
예제 #10
0
def play():
    word = get_word()
    # So'zdagi harflar
    word_letters = set(word)
    # Foydalanuvchi kiritgan harflar
    user_letters = ''
    print(f"Мен {len(word)} хонали сўз ўйладим. Топа оласизми?")
    # print(word)
    while word_letters:
        clear()
        print(display(user_letters,word))
        if user_letters:
            print(f"Шу вақтгача топган ҳарфларингиз: {user_letters}")
        
        letter = input("Ҳарф киритинг: ").upper()
        if letter in user_letters:
            print("Бу ҳарфни аввал киритгансиз. Бошқа ҳарф киритинг.")
            continue        
        elif letter in word:
            word_letters.remove(letter)
            print(f"{letter} ҳарфи тўғри.")
        else:
            print("Бундай ҳарф йўқ.")
        user_letters += letter
    print(f"Табриклайман! {word} сўзини {len(user_letters)} та уринишда топдингиз.")
예제 #11
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)
예제 #12
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!")
예제 #13
0
def bmi():
    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
예제 #14
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
예제 #15
0
def main():
    """BMI Calculation
    Simple application for calculating Body Mass Index.
    
    """

    put_markdown("""# Body Mass Index
    
    [Body mass index](https://en.wikipedia.org/wiki/Body_mass_index) (BMI) is a measure of body fat based on height and weight that applies to adult men and women. 
    
    BMI Categories:
    
    | Category             | BMI           |
    | -------------------- | ------------- |
    | Severely underweight | BMI<14.9      |
    | Underweight          | 14.9≤BMI<18.4 |
    | Normal               | 18.4≤BMI<22.9 |
    | Overweight           | 22.9≤BMI<27.5 |
    | Moderately obese     | 27.5≤BMI<40   |
    | Severely obese       | BMI≥40        |
    
    ## BMI calculation
    The source code of this application is [here](https://github.com/wang0618/PyWebIO/blob/dev/demos/bmi.py)
    """,
                 strip_indent=4)

    info = input_group('BMI calculation', [
        input("Your Height(cm)", name="height", type=FLOAT),
        input("Your Weight(kg)", name="weight", type=FLOAT),
    ])

    BMI = info['weight'] / (info['height'] / 100)**2

    top_status = [(14.9, 'Severely underweight'), (18.4, 'Underweight'),
                  (22.9, 'Normal'), (27.5, 'Overweight'),
                  (40.0, 'Moderately obese'), (float('inf'), 'Severely obese')]

    for top, status in top_status:
        if BMI <= top:
            put_markdown('Your BMI: `%.1f`, Category: `%s`' % (BMI, status))
            break
예제 #16
0
def get_consent(contract):
    key = contract.functions.get_hash().call()
    contract_old = w3.eth.contract(address=contract_data[str(key)][2],
                                   abi=contract_data[str(key)][0],
                                   bytecode=contract_data[str(key)][1])
    if (contract_old.functions.check_consent().call() == False):
        consent = input(
            "Please enter \"CONSENT\" to allow your physician to access your medical device data?"
        )
        if consent == "CONSENT":
            contract_old.functions.set_consent(True).transact()
            return True
예제 #17
0
def login(password):
    if get_localstorage("password") == str(password):
        return True
    pwd = input(label="Please login below.",
                type=PASSWORD,
                placeholder="PASSWORD")
    if str(pwd) == str(password):
        set_localstorage("password", str(pwd))
        return True
    else:
        toast("Wrong password!", color="error")
        return False
예제 #18
0
def login(password):
    if get_localstorage('password') == password:
        return True
    pwd = input(label='Please login below.',
                type=PASSWORD,
                placeholder='PASSWORD')
    if pwd == password:
        set_localstorage('password', pwd)
        return True
    else:
        toast('Wrong password!', color='error')
        return False
예제 #19
0
def sontop(x=10):
    pywebio.output.clear(scope=-1)
    tasodifiy_son = random.randint(1, x)
    while True:
        taxmin = int(
            input(f"Men 1 dan {x} gacha son o'yladim. Topa olasizmi?"))
        if taxmin < tasodifiy_son:
            put_text("Kattaroq son ayting!")
        elif taxmin > tasodifiy_son:
            put_text("Kichikroq son ayting!")
        else:
            put_text("Yutdingiz!")
            break
예제 #20
0
 def play(self):
     pywebio.output.clear(scope=- 1)
     tasodifiy_son = random.randint(1,self.x)
     while True:
         self.__taxminlar += 1
         taxmin = int(input(f"Men 1 dan {self.x} gacha son o'yladim. Topa olasizmi?"))
         if taxmin<tasodifiy_son:
             put_text("Kattaroq son ayting!")
         elif taxmin>tasodifiy_son:
             put_text("Kichikroq son ayting!")
         else:
             put_text("Yutdingiz!")
             break
예제 #21
0
def bmi():
    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_markdown('# **Results**')
            put_html('<br><br>')
            put_markdown('Your BMI: `%.1f`. Category: `%s`' % (BMI, status))
            put_html('<hr>')
            put_table([
                ['Your BMI', 'Category'],
                [BMI, status],
            ])

            break
예제 #22
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
예제 #23
0
def bmi4():
    datos=pd.read_csv("original.csv",header=0)
    X=datos[['resid_area','air_qual','room_num','age','dist1','dist2','dist3','dist4']]
    Y=datos["price"]
    X_train,X_test,Y_train,Y_test=train_test_split(X,Y,test_size=0.3,random_state=42)
    lr=LinearRegression()
    lr.fit(X_train,Y_train)
    prediccion=lr.predict(X_test)
    resi=input("Ingresa el area",type=FLOAT)
    air=input("Ingresa el air_qual",type=FLOAT)
    room=input("Ingresa el room_num",type=FLOAT)
    age=input("Ingresa la edad del producto",type=FLOAT)
    dist1=input("Ingresa la dist1: ",type=FLOAT)
    dist2=input("Ingresa la dist2: ",type=FLOAT)
    dist3=input("Ingresa la dist3: ",type=FLOAT)
    dist4=input("Ingresa la dist4: ",type=FLOAT)
    resp=lr.predict([[resi,air,room,age,dist1,dist2,dist3,dist4]])
    put_text("La respuesta es: " + str(resp))
#!/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)
예제 #25
0
def number_getter():
    put_text("Enter an integer")
    integer = input()
    collatz(integer)
예제 #26
0
파일: ui_webhook.py 프로젝트: pcn/resgate
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)))
예제 #27
0
def main():
    """BMI Calculation
    Simple application for calculating Body Mass Index.
    计算BMI指数的简单应用
    """

    put_markdown(t(
        """# Body Mass Index
    
    [Body mass index](https://en.wikipedia.org/wiki/Body_mass_index) (BMI) is a measure of body fat based on height and weight that applies to adult men and women. 
    
    BMI Categories:
    
    | Category             | BMI           |
    | -------------------- | ------------- |
    | Severely underweight | BMI<14.9      |
    | Underweight          | 14.9≤BMI<18.4 |
    | Normal               | 18.4≤BMI<22.9 |
    | Overweight           | 22.9≤BMI<27.5 |
    | Moderately obese     | 27.5≤BMI<40   |
    | Severely obese       | BMI≥40        |
    
    ## BMI calculation
    The source code of this application is [here](https://github.com/wang0618/PyWebIO/blob/dev/demos/bmi.py)
    """, """# BMI指数
    [`BMI指数`](https://baike.baidu.com/item/%E4%BD%93%E8%B4%A8%E6%8C%87%E6%95%B0/1455733)(Body Mass Index,BMI),是用体重千克数除以身高米数的平方得出的数字,是国际上常用的衡量人体胖瘦程度以及是否健康的一个标准。
    
    成年人的BMI值处于以下阶段
    
    | 体形分类 | BMI值范围 |
    | ------ | -------- |
    | 极瘦    | BMI<14.9    |
    | 偏瘦    | 14.9≤BMI<18.4     |
    | 正常    | 18.4≤BMI<22.9     |
    | 过重    |  22.9≤BMI<27.5  |
    | 肥胖    |  27.5≤BMI<40  |
    | 非常肥胖 |     BMI≥40      |
    
    ## BMI指数计算器
    本程序的源代码[链接](https://github.com/wang0618/PyWebIO/blob/dev/demos/bmi.py)
    
    """),
                 strip_indent=4)

    info = input_group(t('BMI calculation', '计算BMI:'), [
        input(t("Your Height(cm)", "请输入你的身高(cm)"), name="height", type=FLOAT),
        input(t("Your Weight(kg)", "请输入你的体重(kg)"), name="weight", type=FLOAT),
    ])

    BMI = info['weight'] / (info['height'] / 100)**2

    top_status = [(14.9, t('Severely underweight', '极瘦')),
                  (18.4, t('Underweight', '偏瘦')), (22.9, t('Normal', '正常')),
                  (27.5, t('Overweight', '过重')),
                  (40.0, t('Moderately obese', '肥胖')),
                  (float('inf'), t('Severely obese', '非常肥胖'))]

    for top, status in top_status:
        if BMI <= top:
            put_markdown(
                t('Your BMI: `%.1f`, Category: `%s`',
                  '你的 BMI 值: `%.1f`,身体状态: `%s`') % (BMI, status))
            break
예제 #28
0
def central():

###differantiation order
    dd=input("order of differentiation:", type=NUMBER)
    put_text('order of differentiation',(dd))
    put_html('<hr>')
###hex of smal step h is 
    hs=dd

#### order of error
    err=input("order of error must be even number 2 or 4 only:", type=NUMBER)
    put_text('order of error',(err))
    put_html('<hr>')
#total number of points in cosideration    
    put_text('please provide only integer number ')
    put_text('for error order result if its greter than this please relod web and try max limit integer number is equal or less than (in central diff scheme) in between ',int(-1*(dd+err-1)/2),'and ',int((dd+err-1)/2))
    put_html('<hr>') 
    put_text('if for example -3.5 to 3.5 is shown limit then take max_limit and min_limit as -3 to 3 only neglect 0.5') 
    put_text('take limits from -3 to 3 for example ,so points in cosiderations are -3,-2,-1,0,1,2,3 total n is 7')
    
    n = input("number of points in cosideration:", type=NUMBER)
    put_text('stencil number',(n))    
#take limits from -3 to 3 for example ,so points in cosiderations are -3,-2,-1,0,1,2,3 total n is 7

    
    put_text('-3 to 3 for example ,so points in cosiderations are -3,-2,-1,0,1,2,3 so min_limit as -3')
    min_limit = input("Input your minimum limit:", type=NUMBER)
    put_text('yor stencils max limit is ',(min_limit))
    put_html('<hr>')
    

#max limit 
    put_text('-3 to 3 for example ,so points in cosiderations are -3,-2,-1,0,1,2,3 so max_limit as 3')   
    max_limit = input("Input your max_limit:", type=NUMBER)
    put_text('yor stencils max limit is ',(max_limit))
    put_html('<hr>')   



  
####makiuing array
    a0 = np.linspace(min_limit,max_limit,n)
    a0= np. array(a0)

# making n*n matrix
    a=np.tile(a0, (n,1))
#print(a)
    a=np.array(a) 

### making indices 
    b=np.linspace(0,n-1)
    b=np.arange(0, n).reshape(n,1) 

    it = np.nditer([a, b, None], flags=['external_loop'])
    
    with it:
        for x, y, z in it:
            z[...] = x**y
        result = it.operands[2]

#result
    bb=result

########Inserting whre one is going to come
    az=np.zeros(n-1) 
    yy=np.insert(az,dd, 1) 

#output capture from print
    old_stdout = sys.stdout
    new_stdout = io.StringIO()
    sys.stdout = new_stdout

    for i in np.nditer(a0):
            print(sp.symbols('f(x+({}*h))'.format(i)))
    
    output = new_stdout.getvalue()

    sys.stdout = old_stdout

    j=output 

############solving matrix
    hh = np.linalg.solve(bb, yy)

    a = hh*np.math.factorial(dd)
#print(a) 


############ symbols manupalation and list to symbols conversion
##print(type(j))
    d = [x.replace('\n', '  ') for x in j]
# Original Array
    array = np.array(j, dtype=np.str)

#print(array)
  
# Split the element of the said array 
# with spaces
    sparr = np.char.split(array)      # imp step str to array numpy

#print(sparr)                        

    d=np.asarray(sparr,dtype=object)

    d = d.tolist()                    # convert to list
#print(d)

    d=sp.symbols(d)
    d=np.array(d)
#print(d)


######multiplyer
    B=np.array(a)
#B=B.astype(str)
#c = B.tolist()
    c=B.astype(object)
#print(c)



    re.sub(r' *\n *', '\t',np.array_str(np.c_[c,d]).replace('[', '(').replace(']', ')').strip())
             

    res = "\t".join("({}*{})+".format(x, y) for x, y in zip(c, d))


    name = res.rstrip(res[-1])



#print('(',name,')','*','*1/h**',hs)

######captiring print
    old_stdout = sys.stdout
    new_stdout = io.StringIO()
    sys.stdout = new_stdout

    print('(',name,')','*','1/h**',hs)

    kj = new_stdout.getvalue()

    sys.stdout = old_stdout

    def remove(string):
        pattern = re.compile(r'\s+')
        return re.sub(pattern, '', string)
      
# Driver Program
    string = kj
#remove will remove all spaces 
    yy=remove(string)


    #put_text('%s' % (remove(string)))
    
#making variable to latex plote    
    y=py2tex(yy,print_latex=False, print_formula=False)
    o=y.replace('+-','-')
    #put_text('%s' % o)
    def org(o):
        w=o
        p=w
        pp=p.replace('$$',' ')
        tt=" ' "
        #string="r"
        #pg=string+pp
        #tg=" ' "
        pg=tt+pp+tt
        return pg

    t=org(o)


                                                                  
###matplotlib
                                         
    lat = t                                                            

# #add text                                 
#     ax = plt.axes([1,0,0.1,0.1]) #left,bottom,width,height
#     ax.set_xticks([])
#     ax.set_yticks([])
#     ax.axis('off')
#     plt.text(0.2,0.2,r'$%s$' % lat ,size=500,color="red",fontsize=100)
# #hide axes 
#     fig = plt.gca()                                                                 
#     fig.axes.get_xaxis().set_visible(False)                                         
#     fig.axes.get_yaxis().set_visible(False)                                         
#     plt.savefig('images/out.jpeg', bbox_inches='tight', pad_inches=0)                                                                                                                                                                                
#     plt.close()
    
#save image

    # img = open('images/out.jpeg', 'rb').read()  
    # put_image(img, width='500000000px')
    
    put_html('<hr>')
    put_text('this is python output  %s'  % yy)
    

    
    put_html('<hr>')
    
    #visualize equation
    tpl = '''<!DOCTYPE html><html><head>  <meta charset="utf-8">  <meta name="viewport" content="width=device-width">  <title>MathJax example</title>  <script src="https://polyfill.io/v3/polyfill.min.js?features=es6"></script>  <script id="MathJax-script" async          src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js">  </script></head><body><p>{{#contents}}{{& pywebio_output_parse}}{{/contents}}</p></body></html>'''
    # tpl = '''<!DOCTYPE html>
    # <html><head>  <meta charset="utf-8">  
    # <meta name="viewport" content="width=device-width"> 
    # <title> </title>  
    # <script src="https://polyfill.io/v3/polyfill.min.js?features=es6"></script> 
    # <script id="MathJax-script" async          src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js">  </script>
    # </head>
    # <body>
    # <p>{{#contents}}{{& pywebio_output_parse}}{{/contents}}
    #      </p>
    #      </body>
    #      </html>'''    
    put_widget(tpl, {"contents": [put_text((lat))]})
    
    #for latex output
    put_html('<hr>')
    put_text('upper is latex out put %s'   % o)
예제 #29
0
'''from pywebio.input import *
from pywebio.output import *
def linear_Search(list,key):
    for i in range(len(list)):
        if(key==list[i]):
            print("element found in the list at index:", i)
            break
    else:
        print("required element not found in the list")
list=[1,2,3,4,5,6]
key=int(input("enter the value of key:\t"))
linear_Search(list,key)'''
#Linear Search without Function
from pywebio.input import input, FLOAT
from pywebio.output import put_text
num = input("enter the desired element :", type=FLOAT)
list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
for i in range(len(list)):
    if num == list[i]:
        put_text("element is found")
        break
else:
    put_text("required element is not found")
예제 #30
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", type=inp.NUMBER),
    inp.input("Height (cm)", name="height", type=inp.NUMBER)
])

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)