class TruckAvailabilitySchema(Schema):
    """
    The required contents of the truck availability sheet.

    On top of type checking, the schema will also validate that
    the truck_type string is one of 'terminal', 'regional' or 'port' and
    that the terminal string is one of 'ITV', 'KAT' or 'OSS'.

    Any additional columns in the data will also be parsed,
    but will not be tested against a type.
    """

    truck_id = String(data_key='Truck ID', required=True)
    availability = Boolean(data_key='Availability of truck', required=True)
    truck_type = String(data_key='Truck type',
                        required=True,
                        validate=validate_truck_type)
    business_type = String(data_key='business Type')
    terminal = String(data_key='Terminal Base',
                      required=True,
                      validate=validate_terminal)
    hierarchy = Float(data_key='Truck Hierarchy', required=True)
    use_cost = Float(data_key='Truck Use Cost', required=True)
    date = Date(data_key='Date', required=True)
    starting_time = Time(data_key='Starting time', required=True)

    class Meta:
        """
        Defines that columns which are not defined are included.
        """
        unknown = INCLUDE
class ClienteUnidadeConsumidoraSchema(Schema):
    codClienteUnidadeConsumidora = Int()
    codCliente = Int()
    numeroUC = Str(required=True,
                   error_messages={'required': MSG_FIELD_REQUIRED})
    endereco = Str()
    numero = Str()
    codCidade = Int()
    bairro = Str()
    consumoMedioMensal = Float()
    taxaDisponibilidade = Float()
    classe = EnumField(ClassesEnum, by_value=True)
    fase = EnumField(FasesEnum, by_value=True)
    seq = Int()

    def getClasse(self, obj):
        print(obj.classe.value)
        return obj.classe.value

    def getFase(self, obj):
        print(obj.fase.value)
        return obj.fase.value

    @post_load
    def make_clienteUnidadeConsumidora(self, data, **kwargs):
        return ClienteUnidadeConsumidora(**data)
Exemple #3
0
class TradeDocument(Thing):
    __doc__ = m.TradeDocument.__doc__
    id = Integer(description=m.TradeDocument.id.comment, dump_only=True)
    date = DateTime(required=False, description=m.TradeDocument.date.comment)
    id_document = SanitizedStr(data_key='documentId',
                               default='',
                               description=m.TradeDocument.id_document.comment)
    description = SanitizedStr(default='',
                               description=m.TradeDocument.description.comment,
                               validate=validate.Length(max=500))
    file_name = SanitizedStr(data_key='filename',
                             default='',
                             description=m.TradeDocument.file_name.comment,
                             validate=validate.Length(max=100))
    file_hash = SanitizedStr(data_key='hash',
                             default='',
                             description=m.TradeDocument.file_hash.comment,
                             validate=validate.Length(max=64))
    url = URL(description=m.TradeDocument.url.comment)
    lot = NestedOn('Lot',
                   only_query='id',
                   description=m.TradeDocument.lot.__doc__)
    trading = SanitizedStr(dump_only=True, description='')
    weight = Float(required=False, description=m.TradeDocument.weight.comment)
    total_weight = Float(required=False,
                         description=m.TradeDocument.weight.comment)
Exemple #4
0
class AccountCreationSchema(ma.Schema):
    equity_amount = Float(default=float(0.00),
                          validate=validate.Range(min=500))
    initial_amount = Float(required=True, validate=validate.Range(min=500))

    @post_load
    def set_cash_amount(self, data, **kwargs):
        data['cash_amount'] = data['initial_amount']
        return data
Exemple #5
0
class TransactionSendRequest(SPSchema):
    """Validator for POST /rpc/<rpc_client_id>/transactions requests"""

    # Serialization fields.
    to = BytesField(required=True, load_only=True)
    startgas = Float(required=True, load_only=True)
    value = Float(required=True, load_only=True, as_string=False)

    # Deserialization fields.
    tx_hash = BytesField(required=True, dump_only=True)
Exemple #6
0
class WcsCalibrationSettingsSchema(AfterglowSchema):
    ra_hours: Optional[float] = Float(default=None)
    dec_degs: Optional[float] = Float(default=None)
    radius: float = Float(default=180)
    min_scale: float = Float(default=0.1)
    max_scale: float = Float(default=60)
    parity: Optional[bool] = Boolean(truthy={True, 1, 'negative'},
                                     falsy={False, 0, 'positive'},
                                     default=None)
    sip_order: int = Integer(default=3)
    crpix_center: bool = Boolean(default=True)
    max_sources: Optional[int] = Integer(default=100)
Exemple #7
0
class Device(Thing):
    # todo id is dump_only except when in Snapshot
    id = Integer(description='The identifier of the device for this database.')
    hid = Str(
        dump_only=True,
        description='The Hardware ID is the unique ID traceability systems '
        'use to ID a device globally.')
    tags = NestedOn('Tag', many=True, collection_class=OrderedSet)
    model = Str(validate=Length(max=STR_BIG_SIZE))
    manufacturer = Str(validate=Length(max=STR_SIZE))
    serial_number = Str(data_key='serialNumber')
    product_id = Str(data_key='productId')
    weight = Float(validate=Range(0.1, 3),
                   unit=UnitCodes.kgm,
                   description='The weight of the device in Kgm.')
    width = Float(validate=Range(0.1, 3),
                  unit=UnitCodes.m,
                  description='The width of the device in meters.')
    height = Float(validate=Range(0.1, 3),
                   unit=UnitCodes.m,
                   description='The height of the device in meters.')
    events = NestedOn('Event', many=True, dump_only=True)
    events_one = NestedOn('Event',
                          many=True,
                          load_only=True,
                          collection_class=OrderedSet)

    @pre_load
    def from_events_to_events_one(self, data: dict):
        """
        Not an elegant way of allowing submitting events to a device
        (in the context of Snapshots) without creating an ``events``
        field at the model (which is not possible).
        :param data:
        :return:
        """
        # Note that it is secure to allow uploading events_one
        # as the only time an user can send a device object is
        # in snapshots.
        data['events_one'] = data.pop('events', [])
        return data

    @post_load
    def validate_snapshot_events(self, data):
        """Validates that only snapshot-related events can be uploaded."""
        from ereuse_devicehub.resources.event.models import EraseBasic, Test, Rate, Install, \
            Benchmark
        for event in data['events_one']:
            if not isinstance(event,
                              (Install, EraseBasic, Rate, Test, Benchmark)):
                raise ValidationError('You cannot upload {}'.format(event),
                                      field_names=['events'])
Exemple #8
0
class SweepRecord(Schema):
    pre_vm_mv = Float()
    bridge_balance_mohm = Float()
    stimulus_units = Str()
    stimulus_code = Str()
    stimulus_amplitude = Float()
    sweep_number = Integer()
    stimulus_name = Str()
    passed = Boolean()
    leak_pa = Float(allow_none=True)
    clamp_mode = Str()
    peak_deflection = Float(allow_none=True)
    num_spikes = Integer()
Exemple #9
0
class IAperture(AfterglowSchema):
    aper_a: float = Float()
    aper_b: float = Float()
    aper_theta: float = Float()
    annulus_a_in: float = Float()
    annulus_b_in: float = Float()
    annulus_theta_in: float = Float()
    annulus_a_out: float = Float()
    annulus_b_out: float = Float()
    annulus_theta_out: float = Float()
Exemple #10
0
class SweepParameters(Schema):
    stimulus_code = Str(description="stimulus code", required=True)
    stimulus_name = Str(description="index of sweep in order of presentation",
                        required=True)
    stimulus_amplitude = Float(description="amplitude of stimulus",
                               required=True,
                               allow_none=True)
    sweep_number = Integer(
        description="index of sweep in order of presentation", required=True)
    stimulus_units = Str(desription="stimulus units", required=True)
    bridge_balance_mohm = Float(description="bridge balance", allow_none=True)
    pre_vm_mv = Float(allow_none=True)
    leak_pa = Float(allow_none=True)
    passed = Boolean(description="qc passed or failed", required=True)
Exemple #11
0
class RentalSchema(Schema):
    id = Integer(required=True)

    user = Nested(UserSchema())
    user_id = Integer()
    user_url = Url(relative=True)

    bike = Nested(BikeSchema())
    bike_identifier = BytesField(as_string=True)
    bike_url = Url(relative=True)

    events = Nested(RentalUpdateSchema(), many=True)
    start_time = DateTime(required=True)
    end_time = DateTime()
    cancel_time = DateTime()

    is_active = Boolean(required=True)
    price = Float()
    distance = Float()

    @validates_schema
    def assert_end_time_with_price(self, data, **kwargs):
        """
        Asserts that when a rental is complete both the price and end time are included.
        """
        if "price" in data and "end_time" not in data:
            raise ValidationError(
                "If the price is included, you must also include the end time."
            )
        elif "price" not in data and "end_time" in data:
            raise ValidationError(
                "If the end time is included, you must also include the price."
            )
        if "price" in data and "estimated_price" in data:
            raise ValidationError(
                "Rental should have one of either price or estimated_price.")

    @validates_schema
    def assert_url_included_with_foreign_key(self, data, **kwargs):
        """
        Asserts that when a user_id or bike_id is sent that a user_url or bike_url is sent with it.
        """
        if "user_id" in data and "user_url" not in data:
            raise ValidationError(
                "User ID was included, but User URL was not.")
        if "bike_id" in data and "bike_url" not in data:
            raise ValidationError(
                "Bike ID was included, but Bike URL was not.")
Exemple #12
0
class NestedInputData(Schema):  # Defines valid entries in data
    class Meta:
        unknown = EXCLUDE

    tags = Dict(required=False)
    fields = Dict(required=True, validate=FieldValidator())
    timestamp = Float(required=False, validate=UnixEpoch())
Exemple #13
0
class Mobile(Device):
    __doc__ = m.Mobile.__doc__

    imei = Integer(description=m.Mobile.imei.comment)
    meid = Str(description=m.Mobile.meid.comment)
    ram_size = Integer(validate=Range(min=128, max=36000),
                       data_key='ramSize',
                       unit=UnitCodes.mbyte,
                       description=m.Mobile.ram_size.comment)
    data_storage_size = Integer(validate=Range(0, 10**8),
                                data_key='dataStorageSize',
                                description=m.Mobile.data_storage_size)
    display_size = Float(validate=Range(min=0.1, max=30.0),
                         data_key='displaySize',
                         description=m.Mobile.display_size.comment)

    @pre_load
    def convert_check_imei(self, data):
        if data.get('imei', None):
            data['imei'] = int(imei.validate(data['imei']))
        return data

    @pre_load
    def convert_check_meid(self, data: dict):
        if data.get('meid', None):
            data['meid'] = meid.compact(data['meid'])
        return data
Exemple #14
0
class GrsSchemaForm(ModelSchema):
    """Form definition for the model GrsSchema."""

    id = String(dump_only=True)
    name = String(required=True, load_only=True)
    projection = String(required=True, load_only=True)
    meridian = Integer(required=True, load_only=True)
    degreesx = Float(required=True, load_only=True)
    degreesy = Float(required=True, load_only=True)
    bbox = String(required=True, load_only=True)

    class Meta:
        """Internal meta information of form interface."""

        model = GrsSchema
        sqla_session = db.session
class OrderListSchema(Schema):
    """
    The required contents of the order list sheet.

    On top of type checking, the schema will also validate that
    the truck_type string is one of 'terminal', 'regional' or 'port' and
    that the inl_terminal string is one of 'ITV', 'KAT' or 'OSS'.

    Any additional columns in the data will also be parsed,
    but will not be tested against a type.
    """
    inl_terminal = String(data_key='Inl* ter*',
                          required=True,
                          validate=validate_terminal)
    truck_type = String(data_key='truck type',
                        required=True,
                        validate=validate_truck_type)
    hierarchy = Float(data_key='Hierarchy', required=True)
    delivery_deadline = Time(data_key='Delivery Deadline', required=True)
    driving_time = Integer(data_key='driving time', required=True)
    process_time = Integer(data_key='proces time', required=True)

    class Meta:
        """
        Defines that columns which are not defined are included.
        """
        unknown = INCLUDE
Exemple #16
0
class DisplayMixin:
    __doc__ = m.DisplayMixin.__doc__
    size = Float(description=m.DisplayMixin.size.comment,
                 validate=Range(2, 150),
                 required=True)
    technology = EnumField(enums.DisplayTech,
                           description=m.DisplayMixin.technology.comment)
    resolution_width = Integer(
        data_key='resolutionWidth',
        validate=Range(10, 20000),
        description=m.DisplayMixin.resolution_width.comment,
        required=True)
    resolution_height = Integer(
        data_key='resolutionHeight',
        validate=Range(10, 20000),
        description=m.DisplayMixin.resolution_height.comment,
        required=True)
    refresh_rate = Integer(data_key='refreshRate', validate=Range(10, 1000))
    contrast_ratio = Integer(data_key='contrastRatio',
                             validate=Range(100, 100000))
    touchable = Boolean(description=m.DisplayMixin.touchable.comment)
    aspect_ratio = String(dump_only=True,
                          description=m.DisplayMixin.aspect_ratio.__doc__)
    widescreen = Boolean(dump_only=True,
                         description=m.DisplayMixin.widescreen.__doc__)
Exemple #17
0
class Config_Action_Response_Schema(Config_Response_Schema):
    """Action part in a single item of the config response."""

    stdout = Raw(description='Standard output of the execution.')
    stderr = Raw(description='Standard error output of the execution.')
    duration = Float(description='Execution time of the action (in seconds')
    return_code = Integer(required=True, example=0, description='Exit code of the execution (0: no error).')
Exemple #18
0
class LicenseSwitchScheme(BaseModelScheme):
    user_email = Str(validate=[validate.Length(max=128)])
    type = Int()
    ip = Str(required=True,
             allow_none=False,
             validate=[validate.Length(max=16),
                       validate.Regexp(IP_REGEXP)])
    switch_port = Int()
    minute_count = Int()
    amount = Int()
    license_switch_uuid = Str(validate=[validate.Length(max=36)])
    package_switch_uuid = Str(validate=[
        validate.Length(max=36),
        lambda value: _valid('PackageSwitch', 'package_switch_uuid', value)
    ])
    user_uuid = Str(validate=[
        validate.Length(
            max=36), lambda value: _valid('User', 'user_uuid', value)
    ])
    start_time = DateTime()
    end_time = DateTime()
    duration = Choice()
    ordered_amount = Int()
    cost = Float()
    package = Nested('PackageSwitchScheme', many=False)
    enabled = Bool()
    switch_uuid = Str(validate=[
        validate.Length(
            max=64), lambda value: _valid('DnlLicenseInfo', 'uuid', value)
    ])

    class Meta:
        model = model.LicenseSwitch
        fields = ('package_switch_uuid', 'ip', 'start_time', 'duration',
                  'switch_uuid')
Exemple #19
0
class AbstractSchema(mm.ModelSchema):
    submitter = Nested(UserSchema)
    judge = Nested(UserSchema)
    modified_by = Nested(UserSchema)
    duplicate_of = Nested('self', only=_basic_abstract_fields)
    merged_into = Nested('self', only=_basic_abstract_fields)
    submitted_contrib_type = Nested(contribution_type_schema_basic)
    accepted_contrib_type = Nested(contribution_type_schema_basic)
    accepted_track = Nested(track_schema_basic)
    submitted_for_tracks = Nested(track_schema_basic, many=True)
    reviewed_for_tracks = Nested(track_schema_basic, many=True)
    persons = Nested(PersonLinkSchema, attribute='person_links', many=True)
    custom_fields = Nested(ContributionFieldValueSchema,
                           attribute='field_values',
                           many=True)
    score = Float()

    # XXX: should we add comments and reviews too at some point?

    class Meta:
        model = Abstract
        fields = ('id', 'friendly_id', 'title', 'content', 'submitted_dt',
                  'modified_dt', 'judgment_dt', 'state', 'submitter',
                  'modified_by', 'judge', 'submission_comment',
                  'judgment_comment', 'submitted_contrib_type',
                  'accepted_contrib_type', 'accepted_track',
                  'submitted_for_tracks', 'reviewed_for_tracks',
                  'duplicate_of', 'merged_into', 'persons', 'custom_fields',
                  'score')
Exemple #20
0
class ClosestBikeView(BaseView):
    """
    Gets or updates a single bike.
    """
    url = f"/bikes/closest"
    name = "closest_bike"

    @docs(summary="Get The Closest Bike")
    @returns(
        JSendSchema.of(bike=BikeSchema(exclude=("public_key", )),
                       distance=Float()))
    async def get(self):
        """Gets a single bike by its id."""
        lat = self.request.query["lat"]
        long = self.request.query["lng"]
        user_location = Point(float(long), float(lat))
        bike, distance = await self.bike_connection_manager.closest_available_bike(
            user_location, self.rental_manager, self.reservation_manager)

        if bike is None:
            raise web.HTTPNotFound
        else:
            return {
                "status": JSendStatus.SUCCESS,
                "data": {
                    "bike":
                    bike.serialize(self.bike_connection_manager,
                                   self.rental_manager,
                                   self.reservation_manager),
                    "distance":
                    distance
                }
            }
Exemple #21
0
class AbstractSchema(mm.SQLAlchemyAutoSchema):
    submitter = Nested(UserSchema)
    judge = Nested(UserSchema)
    modified_by = Nested(UserSchema)
    duplicate_of = Nested(lambda: AbstractSchema, only=_basic_abstract_fields)
    merged_into = Nested(lambda: AbstractSchema, only=_basic_abstract_fields)
    submitted_contrib_type = Nested(contribution_type_schema_basic)
    accepted_contrib_type = Nested(contribution_type_schema_basic)
    accepted_track = Nested(track_schema_basic)
    submitted_for_tracks = Nested(track_schema_basic, many=True)
    reviewed_for_tracks = Nested(track_schema_basic, many=True)
    persons = Nested(AbstractPersonLinkSchema, attribute='person_links', many=True)
    custom_fields = Nested(ContributionFieldValueSchema, attribute='field_values', many=True)
    score = Float()
    comments = Nested(AbstractCommentSchema, many=True)
    reviews = Nested(AbstractReviewSchema, many=True)

    class Meta:
        model = Abstract
        fields = ('id', 'friendly_id',
                  'title', 'content',
                  'submitted_dt', 'modified_dt', 'judgment_dt',
                  'state',
                  'submitter', 'modified_by', 'judge',
                  'submission_comment', 'judgment_comment',
                  'submitted_contrib_type', 'accepted_contrib_type',
                  'accepted_track', 'submitted_for_tracks', 'reviewed_for_tracks',
                  'duplicate_of', 'merged_into',
                  'persons', 'custom_fields',
                  'score', 'comments', 'reviews')
Exemple #22
0
class Product(Schema):
    class Meta:
        ordered = True

    _id = UUID(required=False, allow_none=False, missing=uuid.uuid4)
    name = String(required=True,
                  description='Nome do produto.',
                  validate=Length(min=1, max=1000))
    description = String(required=True,
                         description='Descrição do produto.',
                         validate=Length(min=1, max=1000))
    price = Float(required=True, description='Valor do produto.')
    enabled = Bool(required=False,
                   description='Se o produto está ativado ou desativado.',
                   missing=True)
    created_at = DateTime(required=False,
                          allow_none=True,
                          description='Criado em.',
                          missing=datetime.now,
                          format=DATETIME_FORMAT)
    updated_at = DateTime(required=False,
                          allow_none=True,
                          description='Atualizado em.',
                          format=DATETIME_FORMAT)
    deleted_at = DateTime(required=False,
                          allow_none=True,
                          description='Deletado em.',
                          format=DATETIME_FORMAT)
class DenseROISchema(Schema):
    """This ROI format is the expected output of Segmentation/Binarization
    and the expected input of Feature_extraction/Classification.
    """

    id = Int(required=True,
             description=("Unique ID of the ROI, gets overwritten writting "
                          "to LIMS"))
    x = Int(required=True,
            description="X location of top left corner of ROI in pixels")
    y = Int(required=True,
            description="Y location of top left corner of ROI in pixels")
    width = Int(required=True, description="Width of the ROI in pixels")
    height = Int(required=True, description="Height of the ROI in pixels")
    valid_roi = Bool(required=True,
                     description=("Boolean indicating if the ROI is a valid "
                                  "cell or not"))
    mask_matrix = List(List(Bool),
                       required=True,
                       description=("Bool nested list describing which pixels "
                                    "in the ROI area are part of the cell"))
    max_correction_up = Float(required=True,
                              description=("Max correction in pixels in the "
                                           "up direction"))
    max_correction_down = Float(required=True,
                                description=("Max correction in pixels in the "
                                             "down direction"))
    max_correction_left = Float(required=True,
                                description=("Max correction in pixels in the "
                                             "left direction"))
    max_correction_right = Float(required=True,
                                 description="Max correction in the pixels in "
                                 "the right direction")
    mask_image_plane = Int(required=True,
                           description=("The old segmentation pipeline stored "
                                        "overlapping ROIs on separate image "
                                        "planes. For compatibility purposes, "
                                        "this field must be kept, but will "
                                        "always be set to zero for the new "
                                        "updated pipeline"))
    exclusion_labels = List(Str,
                            required=True,
                            description=("LIMS ExclusionLabel names used to "
                                         "track why a given ROI is not "
                                         "considered a valid_roi. (examples: "
                                         "motion_border, "
                                         "classified_as_not_cell)"))
Exemple #24
0
class DocumentSchema(ma.ModelSchema):
    consideration = Float()
    doc_type = SmartNested(SiteDocTypeSchema, exclude=('documents',))
    site = SmartNested(SiteSchema, exclude=('doctypes', 'scrape_logs', 'schedules'))

    class Meta:
        model = m.Document
        sqla_session = db.session
Exemple #25
0
class ProdutoSchema(Schema):
    codProduto = Int()
    nome = Str(required=True, error_messages={'required': MSG_FIELD_REQUIRED})
    marca = Str(allow_none=True)
    potencia = Float(allow_none=True)
    custoMedioMensal = Float(allow_none=True)
    custoUltimaCompra = Float(allow_none=True)
    tipoProduto = EnumField(TiposProdutoEnum, by_value=True, allow_none=True)
    tipoModulo = EnumField(TiposModuloEnum, by_value=True, allow_none=True)
    tipoInversor = EnumField(TiposInversorEnum, by_value=True, allow_none=True)
    tipoEstrutura = EnumField(TiposEstruturaEnum,
                              by_value=True,
                              allow_none=True)

    @post_load
    def make_produto(self, data, **kwargs):
        return Produto(**data)
Exemple #26
0
class MetadataSchema(Schema):
    type = Integer()
    id = Integer()
    origin_id = Integer()
    public_key = String()
    name = String()
    category = String()
    progress = Float(required=False)
Exemple #27
0
class ResellerPurchaseUpdateSchema(Schema):
    code = Str(required=True, error_messages=SCHEMA_MESSAGE_REQUIRED)
    value = Float(required=True, error_messages=SCHEMA_MESSAGE_REQUIRED)
    date = DateTime(format='%Y-%m-%d %H:%M:%S',
                    required=True,
                    error_messages=SCHEMA_MESSAGE_REQUIRED)
    status_code = Int(required=True)
    status_description = Str(required=True)
Exemple #28
0
class FileSchema(ContentSchema):
    ''' Schema for the File model '''

    content_id = Integer()
    mime_id = Integer(dump_only=True)
    original_name = String(dump_only=True)
    file_size = Float(dump_only=True)
    content = Raw(load_only=True)
Exemple #29
0
class CommonInput(Schema):
    class Meta:
        unknown = EXCLUDE

    collector = String(required=True)
    data = List(
        Dict, required=True
    )  # Rather than validating NestedInputData, assume the processor will do that.
    data_tags = Dict(required=False)
    destination = String(required=True)
    language = String(required=True)
    messages = Int(required=False)
    meta_tags = Dict(required=False)
    platform = String(required=True)
    timestamp = Float(required=False, validate=UnixEpoch())
    uptime = Float(required=False)
    version = String(required=True)
Exemple #30
0
class BaseSchema(ExpandableSchema):
    id = String(dump_only=True)
    score = Float(dump_only=True)
    highlight = String(dump_only=True)

    # these are raw because dumping fails if the dates are already strings, as
    # in the case of data coming from the ES index.
    created_at = Raw(dump_only=True)
    updated_at = Raw(dump_only=True)