Beispiel #1
0
class SurveyForm(IndicoForm):
    _notification_fields = ('notifications_enabled', 'notify_participants', 'start_notification_emails',
                            'new_submission_emails')

    title = StringField(_("Title"), [DataRequired()], description=_("The title of the survey"))
    introduction = TextAreaField(_("Introduction"), description=_("An introduction to be displayed before the survey"))
    anonymous = BooleanField(_("Anonymous submissions"), widget=SwitchWidget(),
                             description=_("User information will not be attached to submissions"))
    require_user = BooleanField(_("Only logged-in users"), [HiddenUnless('anonymous')], widget=SwitchWidget(),
                                description=_("Still require users to be logged in for submitting the survey"))
    limit_submissions = BooleanField(_("Limit submissions"), widget=SwitchWidget(),
                                     description=_("Whether there is a submission cap"))
    submission_limit = IntegerField(_("Capacity"),
                                    [HiddenUnless('limit_submissions'), DataRequired(), NumberRange(min=1)],
                                    description=_("Maximum number of submissions accepted"))
    notifications_enabled = BooleanField(_('Enabled'), widget=SwitchWidget(),
                                         description=_('Send email notifications for specific events related to the '
                                                       'survey.'))
    notify_participants = BooleanField(_('Participants'), [HiddenUnless('notifications_enabled', preserve_data=True)],
                                       widget=SwitchWidget(),
                                       description=_('Notify participants of the event when this survey starts.'))
    start_notification_emails = EmailListField(_('Start notification recipients'),
                                               [HiddenUnless('notifications_enabled', preserve_data=True)],
                                               description=_('Email addresses to notify about the start of the survey'))
    new_submission_emails = EmailListField(_('New submission notification recipients'),
                                           [HiddenUnless('notifications_enabled', preserve_data=True)],
                                           description=_('Email addresses to notify when a new submission is made'))

    def __init__(self, *args, **kwargs):
        self.event = kwargs.pop('event')
        super(IndicoForm, self).__init__(*args, **kwargs)

    def validate_title(self, field):
        query = (Survey.query.with_parent(self.event)
                 .filter(db.func.lower(Survey.title) == field.data.lower(),
                         Survey.title != field.object_data,
                         ~Survey.is_deleted))
        if query.count():
            raise ValidationError(_('There is already a survey named "{}" on this event'.format(escape(field.data))))

    def post_validate(self):
        if not self.anonymous.data:
            self.require_user.data = True
class FormServo(FlaskForm):
    position = IntegerField('New position to look at (0-180)',
                            [NumberRange(min=0, max=180)])
    submit = SubmitField('Submit')
Beispiel #3
0
class AddLitForm(Form):
    refType = SelectField('Reference Type',
                          validators=[Required()],
                          choices=[('Book Section', 'Book Section'),
                                   ('Edited Book', 'Edited Book'),
                                   ('Journal Article', 'Journal Article'),
                                   ('Journal Issue', 'Journal Issue'),
                                   ('Magazine Article', 'Magazine Article'),
                                   ('Media', 'Media'),
                                   ('Newspaper Article', 'Newspaper Article'),
                                   ('Report', 'Report'), ('Thesis', 'Thesis'),
                                   ('Website', 'Website')])
    author = StringField('Author', validators=[Length(0, 120)])
    title = StringField('Title', validators=[Required(), Length(1, 150)])
    yrPublished = IntegerField(
        'Year Published',
        validators=[NumberRange(min=1800), Optional()
                    ])  # MUST ADD max_value!!! Limit it to THIS year!!
    sourceTitle = StringField('SourceTitle', validators=[Length(0, 200)])
    editor = StringField('Editor', validators=[Length(0, 150)])
    placePublished = StringField('Place Published',
                                 validators=[Length(0, 150)])
    publisher = StringField('Publisher', validators=[Length(0, 200)])
    volume = StringField('Volume', validators=[Length(0, 150)])
    number = StringField('Number', validators=[Length(0, 100)])
    pages = StringField('Pages', validators=[Length(0, 200)])
    keywords = StringField('Keywords', validators=[Length(0, 250)])
    abstract = TextAreaField('Abstract', validators=[Length(0, 2000)])
    notes = TextAreaField('Notes', validators=[Length(0, 500)])
    primaryField = SelectField(
        'Primary Field',
        validators=[Required()],
        choices=[('Philosophy/Ethics/Theology', 'Philosophy/Ethics/Theology'),
                 ('Anthropology/Psychology/Sociology',
                  'Anthropology/Psychology/Sociology'),
                 ('History/Politics/Law', 'History/Politics/Law'),
                 ('Agriculture/Energy/Industry',
                  'Agriculture/Energy/Industry'),
                 ('Animal Science/Welfare', 'Animal Science/Welfare'),
                 ('Ecology/Conservation', 'Ecology/Conservation'),
                 ('Nature Writing/Art/Literary Criticism',
                  'Nature Writing/Art/Literary Criticism'),
                 ('Education/Living', 'Education/Living')])
    secondaryField = SelectField(
        'Secondary Field',
        choices=[('', 'None'),
                 ('Philosophy/Ethics/Theology', 'Philosophy/Ethics/Theology'),
                 ('Anthropology/Psychology/Sociology',
                  'Anthropology/Psychology/Sociology'),
                 ('History/Politics/Law', 'History/Politics/Law'),
                 ('Agriculture/Energy/Industry',
                  'Agriculture/Energy/Industry'),
                 ('Animal Science/Welfare', 'Animal Science/Welfare'),
                 ('Ecology/Conservation', 'Ecology/Conservation'),
                 ('Nature Writing/Art/Literary Criticism',
                  'Nature Writing/Art/Literary Criticism'),
                 ('Education/Living', 'Education/Living')])
    link = StringField('Link',
                       validators=[URL(), Optional()],
                       filters=[lambda x: x or None])
    submit = SubmitField('Submit')
class FormBackwardCms(FlaskForm):
    backward_distance = IntegerField('Move back (cms)',
                                     [NumberRange(min=0, max=500)])
    backward_submit = SubmitField('Submit')
class FormRightTurnDegrees(FlaskForm):
    rturn_degrees = IntegerField('Turn right (degrees)',
                                 [NumberRange(min=0, max=360)])
    rturn_submit = SubmitField('Submit')
Beispiel #6
0
class VCRoomListFilterForm(IndicoForm):
    direction = SelectField(_('Sort direction'), [DataRequired()],
                            choices=[('asc', _('Ascending')), ('desc', _('Descending'))])
    abs_start_date = IndicoDateField(_('Start Date'), [Optional(), Exclusive('rel_start_date')])
    abs_end_date = IndicoDateField(_('End Date'), [Optional(), Exclusive('rel_end_date')])
    rel_start_date = IntegerField(_('Days in the past'), [Optional(), Exclusive('abs_start_date'), NumberRange(min=0)],
                                  default=0)
    rel_end_date = IntegerField(_('Days in the future'), [Optional(), Exclusive('abs_end_date'), NumberRange(min=0)],
                                default=7)

    @generated_data
    def start_date(self):
        if self.abs_start_date.data is None and self.rel_start_date.data is None:
            return None
        return self.abs_start_date.data or (date.today() - timedelta(days=self.rel_start_date.data))

    @generated_data
    def end_date(self):
        if self.abs_end_date.data is None and self.rel_end_date.data is None:
            return None
        return self.abs_end_date.data or (date.today() + timedelta(days=self.rel_end_date.data))
Beispiel #7
0
class SimpleForm(FlaskForm):
    id = IntegerField('', validators=[DataRequired(), NumberRange(min=0)])
Beispiel #8
0
class GroupsIntsForm(BaseForm):
    """Form validation for the groups_integrations tool"""
    # Form submits
    calculate_submit = SubmitField('Calculate Groups and Integrations')

    # Stellar Parameters
    kmag = DecimalField(
        'kmag',
        default=10.5,
        validators=[
            InputRequired('A K-band magnitude is required!'),
            NumberRange(
                min=5.1,
                max=11.9,
                message='K-band mag must be between 5-12, non-inclusive.')
        ])
    obs_duration = DecimalField(
        'obs_duration',
        default=3,
        validators=[
            InputRequired('An observation duration is required!'),
            NumberRange(
                min=0,
                message='Observation duration must be a positive number')
        ])
    time_unit = SelectField('time_unit',
                            default='hour',
                            choices=[('hour', 'hours'), ('day', 'days')])
    models = [('a0i', 'A0I 9750 2.0'), ('aov', 'A0V 9500 2.0'),
              ('a1v', 'A1V 9250 4.0'), ('a5i', 'A5I 8500 2.0'),
              ('a3v', 'A3V 8250 4.0'), ('a5v', 'A5V 8250 4.0'),
              ('f0i', 'F0I 7750 2.0'), ('f0v', 'F0V 7250 1.5'),
              ('f5i', 'F5I 7000 4.0'), ('f2v', 'F2V 7000 4.0'),
              ('f5v', 'F5V 6500 4.0'), ('f8v', 'F8V 6250 4.5'),
              ('g0v', 'G0V 6000 4.5'), ('g0iii', 'G0III 5750 3.0'),
              ('g2v', 'G2V 5750 4.5'), ('g5v', 'G5V 5750 4.5'),
              ('g0i', 'G0I 5500 1.5'), ('g8v', 'G8V 5500 4.5'),
              ('g5iii', 'G5III 5250 2.5'), ('g5i', 'G5I 4740 1.0'),
              ('k0v', 'K0V 5250 4.5'), ('k0iii', 'K0III 4750 2.0'),
              ('k2v', 'K2V 4750 4.5'), ('k0i', 'K0I 4500 1.0'),
              ('k5v', 'K5V 4250 1.5'), ('k5iii', 'K5III 4000 1.5'),
              ('k7v', 'K7V 4000 4.5'), ('k5i', 'K5I 3750 0.5'),
              ('m0i', 'M0I 3750 0.0'), ('m0iii', 'M0III 3750 1.5'),
              ('m0v', 'M0V 3750 4.5'), ('m2i', 'M2I 3500 0.0'),
              ('m2v', 'M2V 3500 4.5'), ('m5v', 'M5V 3500 5.0')]
    mod = SelectField('mod', choices=models)
    n_group = IntegerField('n_group', default=0)
    ins = SelectField('ins',
                      default='miri',
                      choices=[('niriss', 'NIRISS'), ('nircam', 'NIRCam'),
                               ('nirspec', 'NIRSpec'), ('miri', 'MIRI')])

    # Filter selects
    miri_filt = SelectField('miri_filt', choices=[('lrs', 'LRS')])
    nirspec_filt = SelectField('nirspec_filt',
                               choices=[('f070lp_g140h', 'F070LP/G140H'),
                                        ('f100lp_g140h', 'F100LP/G140H'),
                                        ('f070lp_g140m', 'F070LP/G140M'),
                                        ('f100lp_g140m', 'F100LP/G140M'),
                                        ('f170lp_g235h', 'F170LP/G235H'),
                                        ('f170lp_g235m', 'F170LP/G235M'),
                                        ('f290lp_g395h', 'F290LP/G395H'),
                                        ('f290lp_g395m', 'F290LP/G395M')])
    niriss_filt = SelectField('niriss_filt', choices=[('soss', 'SOSS')])
    nircam_filt = SelectField('nircam_filt',
                              choices=[('f322w2', 'F322W2'),
                                       ('f444w', 'F444W'), ('f277w', 'F277W')])

    # TA filter selects
    miri_filt_ta = SelectField('miri_filt_ta',
                               choices=[('f560w', 'F560W'), ('f100w', 'F100W'),
                                        ('f1500w', 'F1500W')])
    nirspec_filt_ta = SelectField('nirspec_filt_ta',
                                  choices=[('f110w', 'F110W'),
                                           ('f140x', 'F140X'),
                                           ('clear', 'CLEAR')])
    niriss_filt_ta = SelectField('niriss_filt_ta',
                                 choices=[('f480m', 'F480M')])
    nircam_filt_ta = SelectField('nircam_filt_ta',
                                 choices=[('f335m', 'F335M')])

    # Subarray selects
    miri_subarray = SelectField('miri_subarray',
                                choices=[('slitlessprism', 'SLITLESSPRISM')])
    nirspec_subarray = SelectField('nirspec_subarray',
                                   choices=[('sub2048', 'SUB2048'),
                                            ('sub1024a', 'SUB1024A'),
                                            ('sub1024b', 'SUB1024B'),
                                            ('sub512', 'SUB512')])
    niriss_subarray = SelectField('niriss_subarray',
                                  choices=[('substrip256', 'SUBSTRIP256'),
                                           ('substrip96', 'SUBSTRIP96')])
    nircam_subarray = SelectField('nircam_subarray',
                                  choices=[('full', 'FULL FRAME'),
                                           ('subgrism256', 'SUBGRISM256'),
                                           ('subgrism128', 'SUBGRISM128'),
                                           ('subgrism64', 'SUBGRISM64')])

    # TA subarray selects
    miri_subarray_ta = SelectField('miri_subarray_ta',
                                   choices=[('slitlessprism', 'SLITLESSPRISM')
                                            ])
    nirspec_subarray_ta = SelectField('nirspec_subarray_ta',
                                      choices=[('full', 'FULL'),
                                               ('sub32', 'SUB32'),
                                               ('sub2048', 'SUB2048')])
    niriss_subarray_ta = SelectField('niriss_subarray_ta',
                                     choices=[('nrm', 'SUBTASOSS -- BRIGHT'),
                                              ('im', 'SUBTASOSS -- FAINT')])
    nircam_subarray_ta = SelectField('nircam_subarray_ta',
                                     choices=[('sub32tats', 'SUB32TATS')])

    # Saturation
    sat_mode = RadioField('sat_mode',
                          default='well',
                          choices=[('counts', 'Counts'),
                                   ('well', 'Full well fraction')])
    sat_max = DecimalField(
        'sat_max',
        default=0.95,
        validators=[
            InputRequired('A saturation level is required!'),
            NumberRange(min=0.0, message='Saturation level must be positive.')
        ])
Beispiel #9
0
class LimbDarkeningForm(BaseForm):
    """Form validation for the limb_darkening tool"""
    # Model grid
    modelgrid_dir = get_env_variables()['modelgrid_dir']
    default_modelgrid = os.path.join(modelgrid_dir, 'ATLAS9/')
    mg = ModelGrid(default_modelgrid, resolution=500)
    teff_rng = mg.Teff_vals.min(), mg.Teff_vals.max()
    logg_rng = mg.logg_vals.min(), mg.logg_vals.max()
    feh_rng = mg.FeH_vals.min(), mg.FeH_vals.max()
    modeldir = RadioField(
        'modeldir',
        default=default_modelgrid,
        choices=[(os.path.join(modelgrid_dir, 'ATLAS9/'), 'Kurucz ATLAS9'),
                 (os.path.join(modelgrid_dir, 'ACES/'), 'Phoenix ACES')],
        validators=[InputRequired('A model grid is required!')])

    # Stellar parameters
    teff = DecimalField(
        'teff',
        default=3500,
        validators=[
            InputRequired('An effective temperature is required!'),
            NumberRange(
                min=float(teff_rng[0]),
                max=float(teff_rng[1]),
                message=
                'Effective temperature must be between {} and {} for this model grid'
                .format(*teff_rng))
        ])
    logg = DecimalField(
        'logg',
        default=4.5,
        validators=[
            InputRequired('A surface gravity is required!'),
            NumberRange(
                min=float(logg_rng[0]),
                max=float(logg_rng[1]),
                message=
                'Surface gravity must be between {} and {} for this model grid'
                .format(*logg_rng))
        ])
    feh = DecimalField(
        'feh',
        default=0.0,
        validators=[
            InputRequired('A surface gravity is required!'),
            NumberRange(
                min=float(feh_rng[0]),
                max=float(feh_rng[1]),
                message=
                'Metallicity must be between {} and {} for this model grid'.
                format(*feh_rng))
        ])
    mu_min = DecimalField('mu_min',
                          default=0.1,
                          validators=[
                              InputRequired('A minimum mu value is required!'),
                              NumberRange(
                                  min=0.0,
                                  max=1.0,
                                  message='Minimum mu must be between 0 and 1')
                          ])

    # Planet parameters
    td_rng = [0, 50]
    transit_duration = DecimalField(
        'transit_duration',
        default='',
        validators=[
            Optional(),
            NumberRange(
                min=int(td_rng[0]),
                max=int(td_rng[1]),
                message='Transit duration must be between {} and {}'.format(
                    *td_rng))
        ])
    op_rng = [0, 1000]
    orbital_period = DecimalField(
        'orbital_period',
        default='',
        validators=[
            Optional(),
            NumberRange(
                min=int(op_rng[0]),
                max=int(op_rng[1]),
                message='Orbital period must be between {} and {}'.format(
                    *op_rng))
        ])
    rp_rng = [0, 1]
    rp_rs = DecimalField(
        'rp_rs',
        default='',
        validators=[
            Optional(),
            NumberRange(
                min=int(rp_rng[0]),
                max=int(rp_rng[1]),
                message='Planet radius must be between {} and {}'.format(
                    *rp_rng))
        ])
    a_rng = [0, 100]
    a_rs = DecimalField(
        'a_rs',
        default='',
        validators=[
            Optional(),
            NumberRange(
                min=int(a_rng[0]),
                max=int(a_rng[1]),
                message='Semi-major axis must be between {} and {}'.format(
                    *a_rng))
        ])
    inc_rng = [0, 180]
    inclination = DecimalField(
        'inclination',
        default='',
        validators=[
            Optional(),
            NumberRange(min=int(inc_rng[0]),
                        max=int(inc_rng[1]),
                        message='Inclination must be between {} and {}'.format(
                            *inc_rng))
        ])
    ecc_rng = [0, 1]
    eccentricity = DecimalField(
        'eccentricity',
        default='',
        validators=[
            Optional(),
            NumberRange(
                min=int(ecc_rng[0]),
                max=int(ecc_rng[1]),
                message='Eccentricity must be between {} and {}'.format(
                    *ecc_rng))
        ])
    w_rng = [0, 360]
    omega = DecimalField(
        'omega',
        default='',
        validators=[
            Optional(),
            NumberRange(
                min=int(w_rng[0]),
                max=int(w_rng[1]),
                message='Omega must be between {} and {}'.format(*w_rng))
        ])

    # LD profile
    profiles = MultiCheckboxField(
        'profiles',
        choices=[(x, x) for x in PROFILES],
        validators=[InputRequired('At least one profile is required!')])

    # Bandpass
    default_filter = 'NIRSpec.CLEAR.PRISM.S200A1'
    defilt = Throughput(default_filter)
    bandpass = SelectField('bandpass',
                           default=default_filter,
                           choices=[('tophat', 'Top Hat')] +
                           [(filt, filt) for filt in FILTERS_LIST],
                           validators=[InputRequired('A filter is required!')])
    wave_min = DecimalField(
        'wave_min',
        default=defilt.wave_min.value,
        validators=[
            NumberRange(
                min=0,
                max=30,
                message='Minimum wavelength must be between 0 and 30 microns!')
        ])
    wave_max = DecimalField(
        'wave_max',
        default=defilt.wave_max.value,
        validators=[
            NumberRange(
                min=0,
                max=30,
                message='Maximum wavelength must be between 0 and 30 microns!')
        ])
    n_bins = IntegerField('n_bins', default=30)

    # Form submits
    calculate_submit = SubmitField('Calculate Coefficients')
    filter_submit = SubmitField('Filter Selected')
    modelgrid_submit = SubmitField('Model Grid Selected')
class Form(FlaskForm):
    gold = Findfile()  # import gold folder

    name = StringField('*1. 影片名稱(Film Name):',
                       validators=[
                           DataRequired(message='*Film Name is required.'),
                           Length(2, 64)
                       ],
                       default='H264_1080p.mp4')

    dirnames = gold.goldfold  # gold folders at a list
    dir_form = []
    for dirname in gold.goldfold:
        dir_form.append(
            (dirname, dirname))  # set gold folder for SelectField form
    gd_folder = SelectField(
        '*2. 比對資料夾名稱(Golden Folder Name):',
        validators=[DataRequired(message='*Golden Folder Name is required.')],
        choices=dir_form)

    test_time = FloatField(
        '3. 測試時間(Test Time(second)):',
        validators=[
            NumberRange(0.1, 1800,
                        "The time should be between %(min)s and %(max)s")
        ],
        default='5')

    core_num = SelectField('4. 執行核心數量(Number of Execution Cores):',
                           choices=[('1', '1'), ('2', '2'), ('3', '3'),
                                    ('4', '4'), ('5', '5'), ('6', '6'),
                                    ('7', '7'), ('8', '8')],
                           default='1')

    res = SelectField('5. 影像解析度(Image Resolution):',
                      choices=[('640x480', '640x480'), ('800X600', '800X600'),
                               ('1024x768', '1024x768'),
                               ('1024x800', '1024x800'),
                               ('1280X720', '1280X720'),
                               ('1280X800', '1280X800'),
                               ('1336x768', '1336x768'),
                               ('1920X1080', '1920X1080'),
                               ('1920X1440', '1920X1440')],
                      default='1920X1080')

    PSNR_type = SelectField('6. 影像格式(Image Format):',
                            choices=[('RGB', 'RGB'), ('YUV', 'YUV')],
                            default='YUV')

    IDLB = FloatField(
        '7. 判斷標準--成功率臨界值(Identification Rate--The Proportion of Image recognition success rate):',
        validators=[
            NumberRange(0, 1, "The time should be between %(min)s and %(max)s")
        ],
        default='0.8')

    PSNR_LB = FloatField(
        '8. PSNR數值最低標準(The Lower Bound of PSNR Value(dB)):',
        validators=[
            NumberRange(1, 100,
                        "The time should be between %(min)s and %(max)s")
        ],
        default='30')

    con_fail = IntegerField(
        '9. 連續判斷失敗擷取影像數量(Number of Continuous Images Identified Fail):',
        validators=[
            NumberRange(1, 25,
                        "The time should be between %(min)s and %(max)s")
        ],
        default='5')

    submit = SubmitField('Submit')
Beispiel #11
0
class CupcakeForm(FlaskForm):
    flavor = StringField('Flavor', validators=[InputRequired()])
    size = SelectField('Size', choices=[('small', 'small'), ('medium', 'medium'), ('large', 'large'), ('huge', 'huge'), ('massive', 'massive')])
    rating = FloatField('Rating', validators=[NumberRange(min=0, max=10), InputRequired()])
    image = StringField('Image URL', validators=[URL()])
Beispiel #12
0
class SearchForm(Form):
    q = StringField(validators=[Length(min=1, max=30)])
    page = IntegerField(validators=[NumberRange(min=1, max=99)], default=1)
Beispiel #13
0
class MessageListForm(BaseForm):
    page = fields.IntegerField(validators=[NumberRange(min=1)], default=1)
Beispiel #14
0
class AddProductForm(FlaskForm):

    selectproduct = QuerySelectField(query_factory=lambda: Product.query.all())
    qty = IntegerField('Quantity', [NumberRange(min=1)])
    submit = SubmitField('Submit')
Beispiel #15
0
class PurchasePointsForm(FlaskForm):
    points = IntegerField(
        "Points", validators=[InputRequired(),
                              NumberRange(min=0, max=50)])
Beispiel #16
0
class FortneyModelForm(BaseForm):
    """Form validation for the forward model tools"""
    # Parameters
    planet_teff = SelectField(
        'planet_teff',
        choices=[(500, '500'), (750, '750'), (1000, '1000'), (1250, '1250'),
                 (1500, '1500'), (1750, '1750'), (2000, '2000'),
                 (2250, '2250'), (2500, '2500')],
        validators=[InputRequired('An effective temperature is required')])
    planet_mass = DecimalField('planet_mass',
                               default=1.5,
                               validators=[
                                   InputRequired('A planet mass is required!'),
                                   NumberRange(
                                       min=0.0,
                                       message='Planet mass must be positive')
                               ])
    planet_mass_unit = SelectField(
        'planet_mass_unit',
        choices=[('M_jup', 'Jupiter Mass'), ('kilogram', 'kilogram'),
                 ('g', 'gram'), ('M_earth', 'Earth Mass'),
                 ('M_sun', 'Solar Mass')],
        validators=[InputRequired('A mass unit is required')])
    planet_radius = DecimalField(
        'planet_radius',
        default=1.25,
        validators=[
            InputRequired('A planet radius is required!'),
            NumberRange(min=0, message='Planet radius must be positive')
        ])
    planet_radius_unit = SelectField(
        'planet_radius_unit',
        choices=[('R_jup', 'Jupiter Radius'), ('kilometer', 'kilometer'),
                 ('m', 'meter'), ('R_earth', 'Earth Radius'),
                 ('R_sun', 'Solar Radius')],
        validators=[InputRequired('A planet radius unit is required')])
    stellar_radius = DecimalField(
        'stellar_radius',
        default=1.0,
        validators=[
            InputRequired('A stellar radius is required!'),
            NumberRange(min=0, message='Stellar radius must be positive')
        ])
    stellar_radius_unit = SelectField(
        'stellar_radius_unit',
        choices=[('R_sun', 'Solar Radius'), ('R_jup', 'Jupiter Radius'),
                 ('kilometer', 'kilometer'), ('m', 'meter'),
                 ('R_earth', 'Earth Radius')],
        validators=[InputRequired('A stellar radius unit is required')])
    chemistry = SelectField(
        'chemistry',
        choices=[('noTiO', '500'), ('eqchem', '750'), (1000, '1000'),
                 (1250, '1250'), (1500, '1500'), (1750, '1750'),
                 (2000, '2000'), (2250, '2250'), (2500, '2500')],
        validators=[InputRequired('A chemistry type is required')])
    clouds = SelectField(
        'clouds',
        choices=[('0', 'Nothing'), ('ray10', 'Weak Rayleigh'),
                 ('ray100', 'Medium Rayleigh'), ('ray1000', 'Strong Rayleigh'),
                 ('flat10', 'Weak Cloud'), ('flat100', 'Medium Cloud'),
                 ('flat1000', 'Strong Cloud')],
        validators=[InputRequired('A cloud model is required')])

    # Form submits
    calculate_submit = SubmitField('Calculate Forward Model')
Beispiel #17
0
class TickerSearch(Form):
    ticker = IntegerField(
        u'Ticker',
        validators=[NumberRange(min=1, max=99999, message=u'Invalid ticker')])
Beispiel #18
0
class ApplySurveyForm(FlaskForm):
    recaptcha = RecaptchaField()
    name = \
        fields.StringField('Name*',
                           validators=[DataRequired(),
                                       Length(max=100)])
    address_line = \
        fields.StringField('Address line*',
                            validators=[DataRequired(),
                                        Length(max=100)])
    postcode = \
        fields.StringField('Post code*',
                           validators=[DataRequired(),
                                       Length(max=10)])
    email = \
        EmailField('Email address*',
                   validators=[DataRequired(),
                               validators.Email(),
                               Length(max=100)])
    telephone = \
        fields.StringField('Main contact telephone number*',
                           validators=[DataRequired(),
                                       Length(max=20)])
    mobile = \
        fields.StringField('Secondary contact telephone number',
                           validators=[Optional(),
                                       Length(max=20)])
    num_main_rooms = \
        fields.IntegerField('Number of bedrooms* ' \
                            +'(please see <a href="/home-surveys#pricing">pricing details</a>' \
                            +', this will be confirmed prior to the survey)*',
                            validators=[DataRequired(),
                                        NumberRange(min=1, max=100)])
    can_heat_comfortably = \
        fields.BooleanField('(tick for yes) Can you heat your home to a comfortable ' \
                            +'temperature in the winter?',
                            validators=[Optional()])
    expected_benefit = \
        fields.TextAreaField('How do you think you will benefit from a survey?*',
                             validators=[DataRequired()])
    has_asbestos = \
        fields.BooleanField('(tick for yes) Are you aware of any asbestos, exposed or not exposed, in the building?',
                            validators=[Optional()])
    asbestos_details = \
        fields.TextAreaField('If yes, please give details',
                             validators=[RequiredIf('has_asbestos')])
    availability = \
        fields.TextAreaField('What is your availability to schedule the survey?*',
                             description='Please see the <a href="/home-surveys">survey information</a> for the expected duration of your survey.',
                             validators=[DataRequired()])
    referral = \
        fields.StringField('How did you hear about C.H.E.E.S.E. thermal-imaging surveys?',
                           validators=[Optional(),
                                       Length(max=250)])
    free_survey_consideration = \
        fields.BooleanField('(tick for yes) I would like to be considered for a free survey. ' \
                              +' We are working with partners to make free surveys' \
                              +' available to people in poor housing conditions ' \
                              +' and / or fuel poverty. Please tick the box if ' \
                              +' you think this applies to your situation. You can talk this ' \
                              +' through with our survey manager when they contact you.',
                            validators=[Optional()])
    special_considerations = \
        fields.TextAreaField('Do you have any special requirements that we need to be aware of during the survey?',
                             description='<ul class="text-muted">' \
                                         +'<li>Do you have any illnesses or disabilities?</li>' \
                                         +'<li>Will you be able to accompany the surveyor around your home for two to three hours during the survey?</li>' \
                                         +'<li>Do you have any pets that will be present in your home during the survey?</li>' \
                                         +'</ul>',
                             validators=[Optional()])
    agree_to_requirements = \
        fields.BooleanField(
        """ I <strong>agree</strong> to make the <a
href="/pre-survey-guide#preparation" target="_blank"> necessary
preparations</a> for the survey, and I am <strong>happy</strong> to <a
href="/pre-survey-guide#follow-ups" target="_blank">report my progress</a>
after one month, and after one and two years after the survey. """,
            validators=[DataRequired()])
    agree_to_cancellation = \
        fields.BooleanField(
        """ I have <strong>read and understood</strong> the <a
href="/home-surveys#cancellation" target="_blank">cancellation policy</a>: if
your survey is cancelled less than 72 hours (3 days) prior to your survey there
will be a &pound;100 cancellation fee. If you rebook your survey for a
different date in the same season, &pound;50 of this will be credited against
your new booking. """,
            validators=[DataRequired()])
    photo_release = \
        fields.BooleanField('I <strong>agree</strong> to any of the ' \
            +'still photos to be taken during my survey that do not ' \
            +'clearly identify a specific person or place to be used in a ' \
            +'publicly-accessible record on thermal faults and energy ' \
            +'efficiency.')
Beispiel #19
0
def test_number_range_nan(nan, dummy_form, dummy_field):
    validator = NumberRange(0, 10)
    dummy_field.data = nan
    with pytest.raises(ValidationError):
        validator(dummy_form, dummy_field)
Beispiel #20
0
class PreSurveyDetailsForm(FlaskForm):
    recaptcha = RecaptchaField()
    year_of_construction = \
        fields.IntegerField('Year of construction',
                            validators=[Optional(),
                                        NumberRange(min=1000,
                                                    max=datetime.datetime.now().year)])
    depth_loft_insulation = \
        fields.TextField('Depth of loft insulation (mm)',
                         validators=[Optional(),
                                     Length(max=150)])
    number_open_fireplaces = \
        fields.TextField('Number of open fireplaces',
                         validators=[Optional(),
                                     Length(max=150)])
    double_glazing = \
        fields.TextField('Amount of double glazing (%)',
                         validators=[Optional(),
                                     Length(max=150)])
    num_occupants = \
        fields.IntegerField('Number of occupants',
                            validators=[Optional(),
                                        NumberRange(min=1, max=100)])
    #annual_gas_kwh = \
    #    fields.DecimalField('Annual consumption (kWh',
    #                        validators=[Optional()])
    #annual_gas_estimated = \
    #    fields.BooleanField('(tick for yes) Is the value based on estimated use?',
    #                        validators=[Optional()])
    #annual_gas_start_date = \
    #    fields.DateField('Start date (dd/mm/yyyy)',
    #                     format='%d/%m/%Y',
    #                     validators=[Optional(),
    #                     validate_date],
    #                     widget=DatePickerWidget())
    #annual_gas_end_date = \
    #    fields.DateField('End date (dd/mm/yyyy)',
    #                     format='%d/%m/%Y',
    #                     validators=[Optional(),
    #                     validate_date],
    #                     widget=DatePickerWidget())
    #annual_elec_kwh = \
    #    fields.DecimalField('Annual consumption (kWh',
    #                        validators=[Optional()])
    #annual_elec_estimated = \
    #    fields.BooleanField('(tick for yes) Is the value based on estimated use?',
    #                        validators=[Optional()])
    #annual_elec_start_date = \
    #    fields.DateField('Start date (dd/mm/yyyy)',
    #                     format='%d/%m/%Y',
    #                     validators=[Optional(),
    #                     validate_date],
    #                     widget=DatePickerWidget())
    #annual_elec_end_date = \
    #    fields.DateField('End date (dd/mm/yyyy)',
    #                     format='%d/%m/%Y',
    #                     validators=[Optional(),
    #                     validate_date],
    #                     widget=DatePickerWidget())
    #annual_solid_spend = \
    #    fields.DecimalField('Annual spend on solid fuels (&pound;)',
    #                        validators=[Optional()])
    #renewable_contribution_kwh = \
    #    fields.DecimalField('Annual contribution from renewable generation (kWh)',
    #                        validators=[Optional()])
    notes = \
          fields.TextAreaField('Notes (any other relevant information)',
                               validators=[Optional()])
class FormForwardCms(FlaskForm):
    forward_distance = IntegerField('Move fwd (cms)',
                                    [NumberRange(min=0, max=500)])
    forward_submit = SubmitField('Submit')
Beispiel #22
0
class RegistForm(FlaskForm):
    user_name = StringField(label="用户名",
                            validators=[
                                DataRequired(message="用户名不能为空!"),
                                Length(min=3,
                                       max=15,
                                       message="用户名长度在3到15个字符之间!")
                            ],
                            render_kw={
                                "id": "user_name",
                                "class": "form-control",
                                "placeholder": "输入用户名",
                            })
    user_pwd = PasswordField(label="用户密码",
                             validators=[
                                 DataRequired(message="用户密码不能为空!"),
                                 Length(min=3,
                                        max=5,
                                        message="用户密码长度在3到5个字符之间!")
                             ],
                             render_kw={
                                 "id": "user_pwd",
                                 "class": "form-control",
                                 "placeholder": "输入用户密码"
                             })
    user_email = StringField(label="用户邮箱",
                             validators=[
                                 DataRequired(message="用户邮箱不能为空!"),
                                 Email(message="用户邮箱格式不对!")
                             ],
                             render_kw={
                                 "id": "user_email",
                                 "class": "form-control",
                                 "placeholder": "输入用户邮箱"
                             })
    user_edge = IntegerField(label="用户年龄",
                             validators=[
                                 DataRequired(message="用户年龄不能为空!"),
                                 NumberRange(min=18,
                                             max=70,
                                             message="用户年龄在18到70之间!")
                             ],
                             render_kw={
                                 "id": "user_edge",
                                 "class": "form-control",
                                 "placeholder": "输入用户年龄"
                             })
    user_birthday = StringField(label="用户生日",
                                validators=[DataRequired(message="用户生日不能为空!")],
                                render_kw={
                                    "id": "user_birthday",
                                    "class": "form-control",
                                    "placeholder": "输入用户生日"
                                })
    user_face = FileField(label="用户头像",
                          validators=[DataRequired(message="用户头像不能为空!")],
                          render_kw={
                              "id": "user_face",
                              "class": "form-control",
                              "placeholder": "输入用户头像"
                          })
    submit = SubmitField(label="提交表单",
                         render_kw={
                             "class": "btn btn-success",
                             "value": "注册"
                         })
class FormLeftTurnDegrees(FlaskForm):
    lturn_degrees = IntegerField('Turn left (degrees)',
                                 [NumberRange(min=0, max=360)])
    lturn_submit = SubmitField('Submit')
Beispiel #24
0
class CloneRepeatPatternForm(CloneRepeatUntilFormBase):
    week_day = IndicoWeekDayRepetitionField(_('Every'))
    num_months = IntegerField(
        _('Months'), [DataRequired(), NumberRange(min=1)],
        default=1,
        description=_("Number of months between repetitions"))
class FormSettings(FlaskForm):
    camera_res = SelectField('Camera Resolution (horizontal)',
                             choices=Config.CAMERA_RES_LIST)
    camera_sharpness = IntegerField('Camera Sharpness (-100 to 100)',
                                    [NumberRange(min=-100, max=100)])
    submit = SubmitField('Submit')
Beispiel #26
0
class ItemMixin():
    category = StringField('Category', validators=[DataRequired()])
    description = TextAreaField('Description', validators=[DataRequired()])
    unit_price = IntegerField('Unit Price', validators=[DataRequired(), NumberRange(min=100, max=10000)])
Beispiel #27
0
class CampaignForm(FlaskForm):
    next = HiddenField()
    name = TextField(_('Campaign Name'), [
        Required(),
        Unique(Campaign.name, message="Campaign with that name already exists")
    ])
    campaign_country = DisabledSelectField(_('Country'), [Optional()],
                                           choices=COUNTRY_CHOICES)
    campaign_type = DisabledSelectField(_('Type'), [Optional()])
    campaign_state = SelectField(_('State'), [Optional()])
    campaign_subtype = SelectField(_('Subtype'), [Optional()])
    # nested_type passed to data-field in template, but starts empty

    segment_by = RadioField(_('Segment By'), [Required()],
                            choices=choice_items(SEGMENT_BY_CHOICES),
                            description=True,
                            default=SEGMENT_BY_CHOICES[0][0])
    locate_by = RadioField(_('Locate By'), [Optional()],
                           choices=choice_items(LOCATION_CHOICES),
                           description=True,
                           default=None)
    show_special = BooleanField(_('Include Special Targets'), [Optional()],
                                default=False)
    include_special = SelectField(
        _('User\'s Representatives'), [Optional()],
        choices=choice_items(INCLUDE_SPECIAL_CHOCIES),
        description=True,
        default=INCLUDE_SPECIAL_CHOCIES[0][0])
    target_set = FieldList(FormField(TargetForm, _('Choose Targets')),
                           validators=[Optional()])
    target_ordering = RadioField(_('Target Order'), [Optional()],
                                 description=True)
    target_shuffle_chamber = BooleanField(_('Shuffle within Chamber'),
                                          [Optional()],
                                          default=True,
                                          description=True)
    target_offices = RadioField(_('Target Offices'), [Optional()],
                                choices=choice_items(TARGET_OFFICE_CHOICES),
                                description=True,
                                default=TARGET_OFFICE_CHOICES[0][0])

    call_limit = BooleanField(_('Limit Maximum Calls'), [Optional()],
                              default=False)
    call_maximum = IntegerField(_('Call Maximum'),
                                [Optional(), NumberRange(min=0)])

    phone_number_set = QuerySelectMultipleField(
        _('Select Phone Numbers'),
        query_factory=TwilioPhoneNumber.available_numbers,
        description=True,
        validators=[Required()])
    allow_call_in = BooleanField(_('Allow Call In'))
    allow_intl_calls = BooleanField(_('Allow International Calls'))
    prompt_schedule = BooleanField(_('Prompt to Schedule Recurring Calls'))

    submit = SubmitField(_('Edit Audio'))
    submit_skip_audio = SubmitField(_('Save and Test'))

    def __init__(self, campaign_data, *args, **kwargs):
        super(CampaignForm, self).__init__(*args, **kwargs)

        read_only(self.campaign_country)
        read_only(self.campaign_type)

        self.campaign_type.choices = choice_items(
            campaign_data.data_provider.campaign_type_choices)
        self.campaign_state.choices = choice_items(
            campaign_data.region_choices)
        self.campaign_subtype.choices = choice_items(
            campaign_data.subtype_choices)
        self.target_ordering.choices = choice_items(
            campaign_data.target_order_choices)

    def validate(self):
        # check default validation
        if not FlaskForm.validate(self):
            return False

        # check nested forms
        for t in self.target_set:
            if not t.form.validate():
                error_fields = ','.join(t.form.errors.keys())
                self.target_set.errors.append({
                    'target':
                    t.name,
                    'message':
                    'Invalid target ' + error_fields
                })
                return False

        return True
Beispiel #28
0
class AddInventoryForm(FlaskForm):
    name = StringField("Name", validators=[InputRequired(), Length(max=32)])
    points = IntegerField(
        "Points", validators=[InputRequired(),
                              NumberRange(min=0, max=1000)])
Beispiel #29
0
class CompanySearchForm(FlaskForm):
    """
    This form is used only for rendering, not for validation.
    """

    HEADCOUNT_CHOICES = (
        ('1', 'Toutes tailles'),
        ('2', 'Moins de 50 salariés'),
        ('3', 'Plus de 50 salariés'),
    )

    NAF_CHOICES = [('', 'Tous les secteurs')
                   ] + [(k, v) for k, v in list(settings.NAF_CODES.items())]

    DISTANCE_CHOICES = (
        ('5', '5 km'),
        ('10', '10 km'),
        ('30', '30 km'),
        ('50', '50 km'),
        ('100', '100 km'),
        ('3000', '+ de 100 km'),
    )

    class Meta:
        # CSRF validation is enabled globally but we don't want the CSRF token
        # to be included in this form.
        # The token can be removed safely here because this form is always submitted in GET.
        # See http://goo.gl/QxWXBH for CSRF token with the GET method: server-side actions
        # that have state changing affect should only respond to POST requests.
        csrf = False

    # Typed job
    j = StringField('Métier recherché', validators=[DataRequired()])
    ij = HiddenField(validators=[Optional()])

    # Corresponding occupation found by autocomplete
    occupation = HiddenField('', validators=[DataRequired()])

    # Typed location
    l = StringField('Lieu de recherche', validators=[DataRequired()])
    # Corresponding coordinates found by autocomplete
    lat = DecimalField(widget=HiddenInput(),
                       validators=[Optional(),
                                   NumberRange(-90, 90)])
    lon = DecimalField(widget=HiddenInput(),
                       validators=[Optional(),
                                   NumberRange(-180, 180)])
    departments = StringField(widget=HiddenInput(),
                              validators=[Optional(),
                                          Regexp('([0-9]+,?)+')])

    # Headcount
    h = RadioField('Taille de l\'entreprise',
                   default=1,
                   choices=HEADCOUNT_CHOICES,
                   validators=[Optional()])

    sort = RadioField('Classement par',
                      choices=sorting.SORTING_CHOICES,
                      default=sorting.SORT_FILTER_DEFAULT,
                      validators=[Optional()])

    naf = SelectField('Secteur d\'activité',
                      choices=NAF_CHOICES,
                      default='',
                      validators=[Optional()])

    d = RadioField('Rayon de recherche',
                   choices=DISTANCE_CHOICES,
                   default=settings.DISTANCE_FILTER_DEFAULT,
                   validators=[Optional()])

    def validate(self):
        """
            Custom validators
        """
        if not super(CompanySearchForm, self).validate():
            return False
        if not self.departments.data and (not self.lon.data
                                          or not self.lat.data):
            return False
        return True

    def set_auto_focus_on_searched_job(self):
        if not self.j.render_kw:
            self.j.render_kw = {}
        self.j.render_kw['autofocus'] = True
Beispiel #30
0
class PostForm(FlaskForm):
    number = IntegerField(
        'Загаданное число',
        validators=[DataRequired(), NumberRange(min=0, max=99)])
    submit = SubmitField('Отправить число')