Example #1
0
    def defineFormInputs(self, myform):
        myform.add_input(
            form.Dropdown("top", Dialog.option_dict['app_options']))
        myform.add_input(
            form.Dropdown("series", Dialog.option_dict['series_options']))
        myform.add_input(
            form.Dropdown("label", Dialog.option_dict['label_options']))
        myform.add_input(
            form.Dropdown("command", Dialog.option_dict['cmd_options']))
        myform.add_input(form.Textbox("commandArgument"))
        myform.add_input(form.Textbox("files"))
        #myform.add_input(form.Textbox("contents"))

        #myform.add_input(form.Dropdown("container", ['dialog', 'page', 'all']))
        #myform.add_input(form.Checkbox('title', value="Y", checked=True))
        myform.add_input(
            form.Checkbox('commandButton',
                          value="Y",
                          checked=True,
                          disabled=True))
        myform.add_input(
            form.Checkbox('otherComponent', value="Y", checked=False))
        myform.add_input(form.Textbox("otherComponentName"))
        myform.add_input(
            form.Dropdown("processSize", [5, 10, 50, 100, 'All'], value='All'))
Example #2
0
def get_user_form_elements(identifier=0, user_name="", read_permission=True, write_permission=False,
                           modify_permission=False):
    """
    Get the user form elements used to set users in project upon creation
        :param identifier: The id of this element
        :param user_name: The current user
        :param read_permission: Permit user to read
        :param write_permission: Permit user to write
        :param modify_permission: Permit user to modify
        :type identifier: int
        :type user_name: str
        :type read_permission: bool
        :type write_permission: bool
        :type modify_permission: bool
        :return: The form elements to add users to a project
    """
    user_form_elements = (
        form.Textbox("user_name_" + str(identifier), description="User", value=user_name,
                     placeholder="Leave blank for open project"),
        form.Checkbox("read_permission_" + str(identifier), description="Read Permission", checked=read_permission,
                      value=True),
        form.Checkbox("write_permission_" + str(identifier), description="Write Permission", checked=write_permission,
                      value=True),
        form.Checkbox("modify_permission_" + str(identifier), description="Modify Permission",
                      checked=modify_permission, value=True)
    )
    return user_form_elements
Example #3
0
def get_apply_permissions_form(identifier=0, read_permission="TRUE", write_permission="FALSE",
                               modify_permission="FALSE", userid=None):
    """
    Get the form used to set permissions for each applicant
            :param identifier: The id of this element
            :param user_name: The current user
            :param read_permission: Permit user to read
            :param write_permission: Permit user to write
            :param modify_permission: Permit user to modify
            :type identifier: int
            :type user_name: str
            :type read_permission: bool
            :type write_permission: bool
            :type modify_permission: bool
            :return: A form object
    """
    user_permissions = form.Form(
        form.Button("remove_user", type="submit", description="User to remove", value=userid, html="X"),
        form.Hidden("user_" + str(identifier), description="User to apply for project", value=userid),
        form.Checkbox("read_permission_" + str(identifier), description="Read Permission",
                      checked=(read_permission == "TRUE"), value=True),
        form.Checkbox("write_permission_" + str(identifier), description="Write Permission",
                      checked=(write_permission == "TRUE"), value=True),
        form.Checkbox("modify_permission_" + str(identifier), description="Modify Permission",
                      checked=(modify_permission == "TRUE"), value=True)
    )
    return user_permissions
Example #4
0
    def reloadMyForm(self):

        apmode = True
        gridenable = True
        apmode_no_passwd = True
        create_logfile = True
        logappend = True

        if cm.getValueInsert(id_create_logfile, "True").lower() != "true":
            create_logfile = False
        if cm.getValueInsert(id_logappend, "True").lower() != "true":
            logappend = False

        myform = form.Form(
            form.Textbox(id_grid_port,
                         description=desc_grid_port,
                         value=cm.getValueInsert("cangrid_port", 4444),
                         id="cangripport"),
            form.Textbox(id_canid,
                         description=desc_canid,
                         value=cm.getValueInsert("canid", 100)),
            form.Textbox(id_start_event_id,
                         description=desc_start_event,
                         value=cm.getValueInsert(id_start_event_id, 1)),
            form.Dropdown(id_loglevel, ['INFO', 'WARN', 'DEBUG'],
                          value=cm.getValueInsert("loglevel", "INFO")),
            form.Checkbox(id_create_logfile,
                          description=desc_create_logfile,
                          checked=create_logfile,
                          value=id_create_logfile,
                          id="tcreate_logfile"),
            form.Checkbox(id_logappend,
                          description=desc_logappend,
                          checked=logappend,
                          value=id_logappend,
                          id="tlogappend"),
            form.Button(desc_btn_save,
                        id=id_btn_save,
                        value="save",
                        html="Save changes"),
            form.Button(desc_btn_stop,
                        id=id_btn_stop,
                        value="stop",
                        html="Stop throttle service"),
            form.Button(desc_btn_restart_all,
                        id=id_btn_restart_all,
                        value="stop",
                        html="Restart throttle and configuration page"),
            form.Button(desc_btn_restart,
                        id=id_btn_restart,
                        value="restart",
                        html="Restart throttle service"),
            form.Button(desc_btn_update_file,
                        id=id_btn_update_file,
                        value="upgrade",
                        html="Upload upgrade file"))

        return myform()
Example #5
0
 def getForm(self):
    return form.Form(
       form.Textbox("home",
          form.notnull,
          description="Home location",
          value=settings.get('location_home'),
       ),
       form.Textbox("work",
          form.notnull,
          description="Work location",
          value=settings.get('location_work'),
       ),
       form.Textbox("weatherloc",
          form.notnull,
          description="Weather location",
          value=settings.get('weather_location'),
       ),         
       form.Textbox("snooze",
          form.notnull,
          form.regexp('\d+', 'Must be a digit'),
          description="Snooze Length (minutes)",
          value=settings.getInt('snooze_length'),
       ),
       form.Textbox("wakeup",
          form.notnull,
          form.regexp('\d+', 'Must be a digit'),
          description="Time (mins) before event for alarm",
          value=settings.getInt('wakeup_time'),
       ),
       form.Textbox("precancel",
          form.notnull,
          form.regexp('\d+', 'Must be a digit'),
          description="Pre-empt cancel alarm allowed (secs)",
          value=settings.get('preempt_cancel'),
       ),
       form.Textbox("waketime",
          form.notnull,
          form.regexp('[0-2][0-9][0-5][0-9]', 'Must be a 24hr time'),
          description="Default wakeup time",
          value=settings.get('default_wake'),
       ),
       form.Checkbox("holidaymode",
          description="Holiday mode enabled",
          checked=(settings.getInt('holiday_mode')==1),
          value="holiday",
       ),
       form.Checkbox("weatheronalarm",
          description="Play weather after alarm",
          checked=(settings.getInt('weather_on_alarm')==1),
          value="weatheronalarm",
       ),
       form.Checkbox("sfx",
          description="SFX enabled",
          checked=(settings.getInt('sfx_enabled')==1),
           value="sfx",
       ),
    )
Example #6
0
class PageChangePrivacy(PageEditProfile):
    _form = form.Form(form.Checkbox('private'), )

    def POST(self, name=None):
        sess = session.get_session()
        force_login(sess)

        form = self._form()
        form.validates()

        # db.update('users', where='id = $id', vars={'id': sess.user_id}, **form.d)
        logintoken = convert_to_logintoken(sess.user_id)

        if logintoken:
            data = {
                "private": form.d.private,
                "logintoken": logintoken,
                "csid_from_client": "None"
            }

            data = api_request("api/profile/userinfo/set_privacy", "POST",
                               data)
            if data['status'] == 200:
                raise web.seeother('/privacy')
            else:
                msg = data['error_code']
                raise web.seeother('/privacy?msg=%s' % msg)
Example #7
0
 def GetCheckBox(self, session, name, isChecked):
     """
     required input
         .GetCheckBox(session, name, isChecked)
     """
     CheckBox = form.Checkbox(name, value=name+'-%s'%(str(session.rstrip())), checked=isChecked)
     self.CheckBoxList.append(name.rstrip())
     return CheckBox.render()
Example #8
0
    def GET(self):
        if GPIO.input(pin) == 0:
            element = form.Checkbox("toggleCtrl",
                                    id="toggleCtrl",
                                    value="YES",
                                    class_="on",
                                    checked="checked")
        else:
            element = form.Checkbox("toggleCtrl",
                                    id="toggleCtrl",
                                    value="YES",
                                    class_="on")

        my_form = form.Form(element)
        title = "Python Pi Garage Door"

        return render.index(my_form, title)
Example #9
0
 def POST(self, name=None):
     question_form = []
     qbank.qid = qbank.question(qbank.id)
     row = qbank.read_text(qbank.qid)
     print "qid %s row: %s" % (qbank.qid, row)
     if (qbank.qid > 0):
         for thing in row[1:]:
             question_form.insert(0, form.Checkbox(thing, value="on"))
         qform = form.Form(*question_form)
         return render.question(qform, row[0])
     else:
         raise web.seeother('/final_result')
Example #10
0
    def __init__(self):

        self.currentForm = form.Form(
            form.Textbox("Course_Par"),
            form.Textbox("Your_Score", form.notnull,
                         form.regexp('\d+', 'Must be a digit')),
            #form.Validator('Must be more than 5', lambda x:int(x)>5)),
            form.Checkbox('Pro'),
            form.Dropdown('Handicap: ', ['0-9', '10-19', '20-29', '30+']),
            form.Dropdown('Number of putts: ',
                          ['< 25', '26-30', '31-35', '36+']),
            form.Dropdown('Number of fairways hit: ', ['< 5', '5-10', '> 10']),
            form.Dropdown('Number of par 3 greens hit: ',
                          ['0', '1-2', ' > 2']),
        )
    def form(self):

        # vemail = form.regexp(r'.+@.+', 'Please enter a valid email address')

        return form.Form(
            form.Checkbox(
                'test_applicants',
                description='Send emails only to test applicants (mlssTest_)?',
                value='1'),
            form.Dropdown(
                'group', ('', 'Admitted First Message',
                          'Admitted Payment Message', 'Rejected',
                          'Attendee First Message', 'Attendee Second Message'),
                form.notnull,
                description='Send template emails to'),
            form.Button('submit', type='submit', value='Send emails'),
        )
    def form(self):

        # vemail = form.regexp(r'.+@.+', 'Please enter a valid email address')

        return form.Form(
            form.Checkbox(
                'test_applicants',
                description='Send emails only to test applicants (mlssTest_)?',
                value='1'),
            form.Dropdown(
                'group',
                ('', 'Admitted', 'Rejected',
                 'Scholarship recipients'),  # 'Pending', 'All'),
                form.notnull,
                description='Send emails to'),
            form.Textbox(
                'subject',
                form.notnull,
                description='Subject',
                pre=
                '<label class="help">E.g. [MLSS16] Decision Notification</label>'
            ),
            form.Textarea(
                'body',
                form.notnull,
                description='Body',
                pre=
                "<label class='help'>Take into account that it only the body, the full message starts with 'Dear ApplicantName, ...' and ends with 'Best wishes, ...' </label>"
            ),
            # form.Dropdown('email_template',
            #               ('', 'msg_to_admitted_applicant', 'msg_to_applicant',
            #                'msg_to_applicant_simple', 'msg_notify_applicant'),
            #               form.notnull,
            #               description='Email template'),
            # form.Textbox('subject',
            #              form.notnull,
            #              description='Subject'),
            # form.Textarea('email_body',
            #               form.notnull,
            #               description='Email body'),
            form.Button('submit', type='submit', value='Send emails'),
        )
Example #13
0
 def GET(self, name=None):
     id = web.websafe(name)
     question_form = []
     if (id == None):
         qbank.qid = qbank.question(qbank.id)
     elif (question_set.has_key(id)):
         qbank.total_answer = []
         qbank.id = id
         qbank.total_answer.append(str(qbank.id))
         qbank.qid = qbank.question(id)
         print "qbank id is:"
         print id
         print qbank.total_answer
     else:
         return json.dumps("Not a valid exam set")
     row = qbank.read_text(qbank.qid)
     print "qid %s row: %s" % (qbank.qid, row)
     if (qbank.qid > 0):
         for thing in row[1:]:
             question_form.insert(0, form.Checkbox(thing, value="on"))
         qform = form.Form(*question_form)
         return render.question(qform, row[0])
     else:
         raise web.seeother('/final_result')
Example #14
0
         ),
    ],
                  form.notnull,
                  description="Type de billet / Ticket type"),
    form.Radio(
        "noiz", ("oui", "non"),
        value="non",
        description="Spectacle NOIZ (vendredi soir) / NOIZ show (Friday night)",
        pre="20 $"),
    form.Dropdown("tshirt", [("X", "Aucun / None"), ("P", "Petit / Small"),
                             ("M", "Moyen / Medium"), ("G", "Grand / Large"),
                             ("TG", "Très grand / X-large")],
                  description="T-Shirt",
                  pre="20 $"),
    form.Checkbox("dvd",
                  description="DVD de la mascarade / Masquerade DVD",
                  pre="20 $"),
    form.Textarea("instructions_speciales",
                  rows=2,
                  cols=40,
                  description="Instructions spécial / Specials Instructions"))


class create:
    """Display and process a badge form"""
    def GET(self):
        cart_id = web.cookies().get(config.cookieName)
        if cart_id:
            f = badgeForm()
            return render.base(render.badge(f), "Nouvel insigne ~ New badge",
                               True)
    form.Textbox("firstname", form.notnull),
    form.Textbox("lastname", form.notnull),
    form.Textbox(
        "email", form.notnull,
        form.regexp(
            r'^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$',
            'Debe ser un email')),
    form.Password(
        "password",
        form.notnull,
        form.regexp(r'^.{8,}$', "debe ser mayor de 7")  #
        # form.Validator("Debe ser de minimo 7 caracteres", lambda i: len(i) > 7)
    ),
    form.Password("re_password", form.notnull),
    form.Checkbox("accept_license",
                  form.Validator("Acepta las clausulas",
                                 lambda i: i == 'true'),
                  value='true'),
    form.Button("submit"),
    validators=[
        form.Validator("Los passwords no coinciden",
                       lambda i: i.password == i.re_password)
    ])


class index:
    def GET(self2):

        user = ''
        if ses._initializer['logged_in'] == True:
            user = ses._initializer['user']
Example #16
0
#Button Press Config
SHORT_PRESS = 300 #milliseconds
LONG_PRESS = 1500 
#Software GPIO for Button Inputs
print(GPIO.VERSION)
GPIO.setmode(GPIO.BCM)
GPIO.setup(24, GPIO.IN, pull_up_down = GPIO.PUD_UP)

myform = form.Form(
    form.Radio(name='Style', args=['Increase', 'Decrease'],value='Increase'),
    form.Radio(name='Brightness', args=['Low', 'Medium', 'High'],value='Medium'),
    form.Dropdown(name='Hour', args=['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12'],value='6'),
    form.Dropdown(name='Minute', args=['00', '05', '10', '15', '20', '25', '30', '35', '40', '45', '50', '55'], value='30'),
    form.Radio(name='AM/PM', args=['AM', 'PM'],value='AM'),
    form.Checkbox('Now', id='Now', value='True'),
    form.Textbox("Length",
        form.notnull,
        form.regexp('\d+', 'Need a numerical length here...')))

print("Welcome to the prototype sunrise alarm clock. Follow the online prompts to decide on a color, fade in time, blink rate, etc")
def button():
    global running
    global reset
    global red
    global green
    global blue
    override = 0
    presstime = 0
    while True:
	try:
Example #17
0
# this line creates the application object
# just no better place to put it, in a big app we'd 
# have better code structure
app = web.application(urls, globals(), autoreload=False)

#
# This is the form object that is renderdd on the webpage
# Here is an example of the form we used as a guide: http://webpy.org/form#example
#
form_comparators=['Psychiatry','Cognition','Other Neurologic','Fall Risk','Bleeding']

myform = form.Form(
    form.Textbox('Index_drug',form.Validator('Field cannot be empty', lambda x: not x=="hello")),
    form.Dropdown('Comparator',form_comparators,value=0),
    form.Textarea('Druglist',value='None'),
    form.Checkbox('Option_1',value="0"),
    form.Checkbox('Option_2',value="0"),
  ) 

# this is one "view"
# it has GET and POST methods, which do different things
# GET is for just viewing the form, and POST is for submitting data
class index: 
    def GET(self): 

        # on a get request, 1) create the form object 
        # 2) render the page, passing the form object to the template
        # (it infers the basicform.html from the name of the basicform method) 
        form = myform()
        return render.basicform(form)        
        #if not form.validates():
Example #18
0
vemail = form.regexp(r".*@.*", "- Must be a valid email address")
vpass = form.regexp(r".{8,100}$", '- Must be atleast 8 characters long')
number = form.regexp(r"^[0-9]+$", "- Must be a number")
not_empty = form.regexp(r".+", "- This field is required")

# Verify form
qr_verify_form = form.Form(
    form.Textbox("key", description=""),
    form.Button("Authenticate", type="submit", description="Authenticate"),
)

# Define the login form 
login_form = form.Form(
    form.Textbox("username", description="Username"),
    form.Password("password", description="Password"),
    form.Checkbox("remember", description="Remember me", checked=True, value=False),
    form.Button("Log In", type="submit", description="Login"),
)

# Define the register form 
register_form = form.Form(
    form.Textbox("username", not_empty, description="Username"),
    form.Textbox("full_name", not_empty, description="Full name"),
    form.Textbox("company", description="Company"),
    form.Textbox("email", vemail, description="Email Address"),
    form.Textbox("street_address", description="Street address"),
    form.Textbox("city", description="City"),
    form.Textbox("state", description="State"),
    form.Textbox("postal_code", number, description="Postal code"),
    form.Textbox("country", description="Country"),
    form.Password("password", vpass, description="Password"),
Example #19
0
import web
from web import form

render = web.template.render('templates/')

urls = ('/', 'index')
app = web.application(urls, globals())

myform = form.Form(
    form.Textbox("boe"),
    form.Textbox("bax", form.notnull, form.regexp('\d+', 'Must be a digit'),
                 form.Validator('Must be more than 5', lambda x: int(x) > 5)),
    form.Textarea('moe'), form.Checkbox('curly'),
    form.Dropdown('french', ['mustard', 'fries', 'wine']))


class index:
    def GET(self):
        form = myform()
        # make sure you create a copy of the form by calling it (line above)
        # Otherwise changes will appear globally
        return render.formtest(form)

    def POST(self):
        form = myform()
        if not form.validates():
            return render.formtest(form)
        else:
            # form.d.boe and form['boe'].value are equivalent ways of
            # extracting the validated arguments from the form.
            return "Grrreat success! boe: %s, bax: %s , boe: %s" % (
    form.Textbox('poster_title', 
        description='Poster Title (optional)',
        pre='<label class="help">We will probably have a poster session for students to present their work. Tentative title of your poster if you were able to present at the MLSS.</label>'),
    form.Textarea('abstract', 
        description='Poster abstract (optional)',
    pre='<label class="help">If you plan to present a poster, please include in this box the <strong>abstract of your poster</strong>.</label>'),
    

    form.Textarea('cover_letter', 
         description='Comments (optional)',
     pre='<label class="help">Additional comments in support of your application (max 200 words) -- You can use this box to highlight reasons why the MLSS is appropriate for you and any specific achievements you feel are relevant.</label>'),
    
    
    form.Checkbox('travel_support', 
        description='Financial support (optional)',
        value='1',
        post='<span>I wish to apply for financial support.</span>'),

    form.Textbox('travel_support_budget',
        form.Validator('Please enter your financial support budget estimate, rounded to the nearest dollars.', 
        lambda x: not x or isinstance(int(x), int)),
        description='Budget (in dollars)'),
    

    
    form.Button('submit', type='submit', value='Apply'),
    validators = [
        form.Validator('If you are applying for financial support, make sure you complete all the fields.', 
            lambda i: check_travel_support(i)),
        form.Validator('Your email addresses did not match!', 
            lambda i: i.email == i.email_again),
Example #21
0
        '/camera/(.*)','Camera_angle',
       # '/','',
     #   '/','',
        '/(.*)','Error_page'
)

app = web.application(urls, globals())

loginform = form.Form(
    form.Textbox("USERNAME",
        form.notnull,
        form.Validator('wrong', lambda x: x == "martin")),
    form.Textbox("PASSWORD",
        form.notnull,
        form.Validator('wrong', lambda x: x == "12341234")),
    form.Checkbox('I am not a robot')
)

routeform = form.Form(

)

render = web.template.render('templates/')

def gpio_startup():
    global a1,a2,b1,b2,gpiodidstartup,p,servomotor_camera,p1
    GPIO.setmode(GPIO.BOARD)
    inputpin = [infrared,ultrasonic]
    outputpin = [servomotor,motor_L1,motor_L2,motor_R1,motor_R2,servomotor_camera,light_red,light_yellow_left,light_yellow_right,light_green,light_signal_ready]
    GPIO.setup(inputpin,GPIO.IN)
    GPIO.setup(outputpin,GPIO.OUT,initial = GPIO.LOW)
Example #22
0
from web import form

render = web.template.render('templates/')

urls = ('/', 'index')
app = web.application(urls, globals())

#表格
myform = form.Form( 
    form.Textbox("boe"), 
    form.Textbox("bax", 
        form.notnull,
        form.regexp('\d+', 'Must be a digit'),#必须为数字
        form.Validator('Must be more than 5', lambda x:int(x)>5)),#必须大于5
    form.Textarea('moe'),
    form.Checkbox('curly'), 
    form.Dropdown('french', ['mustard', 'fries', 'wine'])) 

class index:
    # GET直接显示表格
    def GET(self): 
        form = myform()
        return render.formtest(form)

    #
    def POST(self): 
        form = myform() 
        if not form.validates(): #数据有效性检查
            return render.formtest(form)
            #无效数据的显示页面
            #将form作为参数,传入到模版formtest里去处理。
Example #23
0
 form.Dropdown('dias', dias, description="Dia"),
 form.Dropdown('meses', meses, description="Mes"),
 form.Dropdown('anios', anios, description="Anio"),
 form.Textarea('direccion', form.notnull, description="Dirección"),
 form.Password('clave', form.notnull, description="Contraseña"),
 form.Password('clave2', form.notnull, description="Repetir contraseña"),
 form.Radio('pago', ['Contra reembolso', 'Tarjeta VISA'],
            description="Forma de pago"),
 form.Textbox('visa',
              form.regexp(
                  '((\d{4})[\-,\s](\d{4})[\-,\s](\d{4})[\-,\s](\d{4}))',
                  'Introduzca un número de tarjeta VISA válido'),
              description="Tarjeta VISA"),
 form.Checkbox('clausula',
               form.Validator("Acepta las clausulas",
                              lambda i: i == 'true'),
               value='true',
               description="¿Nos vende su alma?"),
 form.Button('Registrarse'),
 validators=[
     form.Validator(
         "Fecha de nacimiento no válida.", lambda i:
         (((int(i.meses) == 2) and ((int(i.dias) <= 28) and (
             (int(i.anios) % 4) != 0) or (int(i.dias) <= 29) and (
                 (int(i.anios) % 4) == 0))) or ((int(i.dias) <= 31) and (
                     (int(i.meses) == 1) or (int(i.meses) == 3) or
                     (int(i.meses) == 5) or (int(i.meses) == 7) or
                     (int(i.meses) == 8) or (int(i.meses) == 10) or
                     (int(i.meses) == 12))) or ((int(i.dias) <= 30) and (
                         (int(i.meses) == 4) or (int(i.meses) == 6) or
                         (int(i.meses) == 9) or (int(i.meses) == 11))))),
Example #24
0
                                   form.notnull))

smoke_form = form.Form(
    form.Radio('Smoking:', ['Never Smoker', 'Past Smoker', 'Current Smoker'],
               form.notnull))

sex_form = form.Form(
    form.Radio('Sexually Active?:', [
        'Yes',
        'No',
    ], form.notnull))

highrisk_form = form.Form(
    form.Checkbox(
        'High Risk Sexual Activity?:',
        value=True,
        post=
        "<em>  High risk history includes having a history of STI, new or multiple sex partners, inconsistent condom use, exchanging sex for money or drugs.</em>"
    ))

drug_form = form.Form(
    form.Checkbox('Past or current IV or intranasal drug use?:', value=True))

pneumo_form = form.Form(
    form.Checkbox(
        'Chronic Disease?:',
        value=True,
        post=
        "<em>  Any lung, CVD, DM, CKD, nephrotic syndrome, liver, alcoholism, cochlear implants, CSF leaks, immunocompromise, spleen issues, and nursing home residents.</em>"
    ))

#A function that takes the input from the forms and gives a sentence
Example #25
0
from web import form

render = web.template.render('templates/', base='base')

urls = ('/', 'index')
app = web.application(urls, globals())

myform = form.Form(
    form.Textbox("Nombre"),
    form.Textbox("Telefono", form.notnull, form.regexp('\d+',
                                                       'Must be a digit'),
                 form.Validator('Must be more than 5', lambda x: int(x) > 5)),
    form.Textbox(
        "Nacimiento", form.notnull, form.regexp('\d+', 'Must be a digit'),
        form.Validator('No puede ser mayor a 2016', lambda x: int(x) < 2016)),
    form.Textarea('Email'), form.Checkbox('INE', value='INE'),
    form.Dropdown('Genero', ['Macho Alfa', 'Mujer']))


class index:
    def GET(self):
        form = myform()
        # make sure you create a copy of the form by calling it (line above)
        # Otherwise changes will appear globally
        return render.formtest(form)

    def POST(self):
        form = myform()
        if not form.validates():
            return render.formtest(form)
        else:
Example #26
0
RUNTIME_PERL = "Perl"
RUNTIME_LUA = "Lua"
RUNTIME_SWIFT = "Swift"
RUNTIME_OBJECTIVEC = "Objective-c"
RUNTIME_ELIXIR = "Elixir"
RUNTIME_RUST = "Rust"
RUNTIME_TENSORFLOW = "TensorFlow"

myform = form.Form(
    form.Dropdown("Runtime", [
        RUNTIME_PYTHON27, RUNTIME_PYTHON35, RUNTIME_GOLANG, RUNTIME_UBUNTU,
        RUNTIME_CENTOS, RUNTIME_C, RUNTIME_CPP, RUNTIME_RUBY, RUNTIME_ERLANG,
        RUNTIME_NODE, RUNTIME_PHP, RUNTIME_JAVA9, RUNTIME_JAVAOPENJDK9,
        RUNTIME_R, RUNTIME_HASKELL, RUNTIME_PERL, RUNTIME_LUA, RUNTIME_SWIFT,
        RUNTIME_OBJECTIVEC, RUNTIME_ELIXIR, RUNTIME_RUST, RUNTIME_TENSORFLOW
    ]), form.Textbox("Load local file"), form.Checkbox("Edit online code"),
    form.Textarea("Online code"))

urls = ('/', 'index')


class index:
    '''
    Return web form to trigger lambda service.
    '''
    def GET(self):
        form = myform()

        return render.index(form)

    '''
Example #27
0
                 form.Validator("Title can't be blank", bool),
                 description="Title:",
                 size='80'),
    form.Textbox('pid',
                 form.Validator("Address can't be blank", bool),
                 form.Validator('ID already exists, Choose a different one.',
                                petitionnotexists),
                 pre='http://watchdog.net/c/',
                 description='URL:',
                 size='30'),
    form.Textarea('msg',
                  form.Validator("Description can't be blank", bool),
                  description="Description:",
                  rows='15',
                  cols='80'),
    form.Checkbox('tocongress', value='', description="Petition to Congress?"),
    form.Hidden('userid'))

wyrform = form.Form(
    form.Dropdown('prefix', ['Mr.', 'Mrs.', 'Dr.', 'Ms.', 'Miss'],
                  description='Prefix'),
    form.Textbox('lname',
                 form.Validator("Last name can't be blank", bool),
                 size='16',
                 description='Last Name'),
    form.Textbox('fname',
                 form.Validator("First name can't be blank", bool),
                 size='16',
                 description='First Name'),
    form.Textbox('email',
                 form.notnull,
Example #28
0
def buildform(key, config):
    if not key in config['forms']: raise Exception("Form not found")
    inputs = []
    for i in config['forms'][key]:
        if not 'name' in i: raise Exception("Needs a name")
        if not 'type' in i: raise Exception("Needs a type")
        k = i['name']
        if i['type'] == "text":
            opts = {}
            opts['description'] = _(k)
            opts['post'] = helplink(i.get('help'))
            if 'disabled' in i or 'readonly' in i:
                opts['readonly'] = True
            if 'url' in i:
                opts['data-url'] = i['url']
            if 'pick' in i:
                opts['data-pick'] = i['pick'] = json.dumps(i['pick'])  # ???
            inputs.append(form.Textbox(k, **opts))
        elif i['type'] == "hidden":
            inputs.append(form.Hidden(k, description=_(k)))
        elif i['type'] == "checkbox":
            inputs.append(
                form.Checkbox(k,
                              value="y",
                              description=_(k),
                              post=helplink(i.get('help'))))
        elif i['type'] == 'select':
            default = i.get('default', '')
            if 'options' in i:
                options = [''] + i['options']
                inputs.append(form.Dropdown(k, options, description=_(k)))
            elif 'sql' in i:
                db = web.database(dbn='sqlite',
                                  db=config['source']['database'])
                data = web.input()
                if 'match' in i:
                    wheres = []
                    for m in i['match']:
                        if data.get(m):
                            wheres.append("WHERE %s = %s" %
                                          (m, web.sqlquote(data[m])))
                    query = i['sql'] % (" AND ".join(wheres))
                else:
                    query = i['sql'] % ""
                results = [v.values()[0] for v in db.query(query)]
                results = filter(None, results)
                results = [(v, _(v)) for v in results]
                results.insert(0, default)
                inputs.append(form.Dropdown(k, results, description=_(k)))
            elif 'source' in i:
                key = i['source'] + "-" + i['name']
                source = json.loads(web.ctx.metadata.get(key))
                options = [''] + [d['label'] for d in sorted(source)]
                inputs.append(form.Dropdown(k, options, description=_(k)))
        elif i['type'] == 'textfield':
            inputs.append(
                form.Textarea(k,
                              description=_(k),
                              post=helplink(i.get('help'))))
        elif i['type'] == 'date':
            inputs.append(
                form.Textbox("year",
                             description=_('year'),
                             post=helplink('help-year')))
            inputs.append(
                form.Textbox("month",
                             description=_('month'),
                             post=helplink('help-month')))
            inputs.append(
                form.Textbox("day",
                             description=_('day'),
                             post=helplink('help-day')))
        elif i['type'] == 'location':
            inputs.append(
                form.Textbox("county", description=_('county'), readonly=True))
            inputs.append(
                form.Textarea("locality",
                              description=_('locality'),
                              readonly=True))
            inputs.append(
                form.Textbox("verbatimCoordinates",
                             description=_('verbatimCoordinates'),
                             readonly=True))
            inputs.append(
                form.Hidden("verbatimWKT",
                            description=_('verbatimWKT'),
                            readonly=True))
            inputs.append(
                form.Hidden("verbatimLatitude",
                            description=_('verbatimLatitude'),
                            readonly=True))
            inputs.append(
                form.Hidden("verbatimUncertaintyInMeters",
                            description=_('verbatimUncertaintyInMeters'),
                            readonly=True))
            inputs.append(
                form.Hidden("verbatimLongitude",
                            description=_('verbatimLongitude'),
                            readonly=True))
        elif i['type'] == "annotation":
            inputs.append(form.Hidden(k))
            inputs.append(
                form.Textbox(_('marked-pages'),
                             readonly=True,
                             id="marked-pages"))
            inputs.append(form.Button(_("mark-page"), id="mark-page"))
        else:
            raise Exception("Unknown type %s" % i['type'])
    return form.Form(*inputs)
Example #29
0
visa = re.compile(r'[0-9]{4}([\ \-]?)[0-9]{4}([\ \-]?)[0-9]{4}([\ \-]?)[0-9]{4}')

myform = form.Form( 
    form.Textbox('nombre', maxlength="40", description="Nombre:"),
	form.Textbox('apellidos', maxlength="50", description="Apellidos:"),
	form.Textbox('dni', maxlength="9", size="9", description="DNI:"),
	form.Textbox('correo', maxlength="50", size="15", description="Correo Electronico:"),
	form.Dropdown('dia', range(1,32), description="Dia:"),
	form.Dropdown('mes', range(1,13), description="Mes:"),
	form.Dropdown('anio', range(1940,2014), description="Anio:"),
	form.Textarea('direccion', maxlength="55", size="35", description="Direccion:"),	
	form.Password('passw', maxlength="10", size="12", description="Password:"******"10", size="12", description="Repetir:"),
	form.Radio('forma_pago', ['contra reembolso', 'tarjeta visa'], description="Forma de pago:"),
	form.Textbox('numero_visa', maxlength="19", size="20", description="Numero Visa"),
    form.Checkbox('check',
		form.Validator("Debe aceptar las clausulas.", lambda i: "check" not in i), description="Acepto las clausulas"), 
	form.Button('Aceptar'),
	
	
    validators = [
    	form.Validator('El campo nombre no puede estar vacio.', lambda i: len(str(i.nombre))>0),
		form.Validator('El campo apellidos no puede estar vacio.', lambda i: len(str(i.apellidos))>0),
		form.Validator('El campo dni no puede estar vacio.', lambda i: len(str(i.dni))>0),
		form.Validator('El campo correo no puede estar vacio.', lambda i: len(str(i.correo))>0),
		form.Validator('El campo direccion no puede estar vacio.', lambda i: len(str(i.direccion))>0),
		form.Validator('El campo numero visa no puede estar vacio.', lambda i: len(str(i.numero_visa))>0),
		form.Validator('Fecha Incorrecta.', lambda x: not(
			(int(x.dia)==31 and int(x.mes)==2) or 
			(int(x.dia)==30 and int(x.mes)==2) or 
			(int(x.dia)==29 and int(x.mes)==2 and int(x.anio)%4!=0) or 
			(int(x.dia)==31 and (int(x.mes)==4 or int(x.mes)==6 or int(x.mes)==9 or int(x.mes)==11))
Example #30
0
    return set_of_known_codes


SET_OF_KNOWN_CODES = get_set_of_known_codes()

myform = form.Form(
    # form.Textbox('isocode'),
    form.Dropdown('isocode', get_code_lang_tuples()),
    form.Textbox('OR lang name'),
    form.Dropdown('sort by', get_dist_drop_down()),
    form.Dropdown('second sort', get_dist_drop_down(True)),
    form.Textbox('# returned', form.regexp('\d*', 'Must be a digit')),
    form.Textbox('max # Nones', form.regexp('\d*', 'Must be a digit')),
    form.Textbox('min # named entity pairs',
                 form.regexp('\d*', 'Must be a digit')),
    form.Checkbox('wikipedia', value='blah'),
    form.Checkbox('europarl', value='blah'),
    form.Checkbox('same alphabet', value='blah'),
    form.Checkbox('print all values', value='blah', checked=True),
    form.Button('go!', type='submit'),
)


class index:
    def GET(self):
        f = myform()
        return render.formtest(f, "", "", "")

    def POST(self):
        f = myform()
        f.validates()