Example #1
0
class UserAddress(BaseModel):
    longitude: confloat(gt=-180, lt=180)
    latitude: confloat(gt=-90, lt=90)
    complete_address: constr(min_length=5, max_length=300)
    tag: constr(min_length=1, max_length=30)
    floor: Optional[constr(min_length=1, max_length=50)]
    landmark: Optional[constr(min_length=1, max_length=100)]
Example #2
0
class ImageOut(BaseModel):
    height: Optional[Union[conint(gt=1), confloat(gt=0.0, le=1.0)]] = None
    width: Optional[Union[conint(gt=1), confloat(gt=0.0, le=1.0)]] = None
    length: Optional[Union[conint(gt=1), confloat(gt=0.0, le=1.0)]] = None

    class Config:
        fields = {
            "height": {
                "description":
                "Height of the thumbnail. Width is adjusted to preserve the "
                "aspect ratio. "
                "**Takes precedence over `width` and `length`.**"
            },
            "width": {
                "description":
                "Width of the thumbnail. Height is adjusted to preserve the "
                "aspect ratio. "
                "**Takes precedence over `length`.**"
            },
            "length": {
                "description":
                "Length of the largest side of the thumbnail. "
                "The other dimension is adjusted to preserve the aspect ratio. "
                "**Ignored if other size-related parameter such as `width` or "
                "`height` is present.** "
            }
        }
Example #3
0
class TownPercentiles(BaseModel):
    """Age percentiles for town."""

    town: str = Field(...)
    p50: confloat(ge=0) = Field(...)
    p75: confloat(ge=0) = Field(...)
    p99: confloat(ge=0) = Field(...)
Example #4
0
class ShopRegister(BaseModel):
    name: constr(min_length=3, max_length=50)
    longitude: confloat(gt=-180, lt=180)
    latitude: confloat(gt=-90, lt=90)
    address: constr(min_length=5, max_length=50)
    radius_metres: PositiveFloat
    phone_number: Optional[constr(min_length=10, max_length=15)]
Example #5
0
async def list_of_shops_for_users(
    *,
    longitude: Optional[confloat(gt=-180, lt=180)] = None,
    latitude: Optional[confloat(gt=-90, lt=90)] = None,
    address_id: Optional[PositiveInt] = None,
    page: PositiveInt = 1,
    page_size: PositiveInt = 10,
    db: Session = Depends(get_db),
):
    """
    Either provide `longitude` (float) and `latitude` (float) or `address_id` (int).
    Longitude and latitude pair will take precedence over `address_id`.
    """
    if longitude and latitude:
        shops = shops_for_users(db, longitude=longitude, latitude=latitude)
    elif address_id:
        if address := get_address_by_id(db, id=address_id):
            shops = shops_for_users(
                db, longitude=address.longitude, latitude=address.latitude
            )
        else:
            raise HTTPException(
                status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
                detail="NO_LOCATION: addess_id is invalid",
            )
Example #6
0
class Model(BaseModel):
    cos_function: PyObject = None

    path_to_something: Path = None
    path_to_file: FilePath = None
    path_to_directory: DirectoryPath = None

    short_bytes: conbytes(min_length=2, max_length=10) = None
    strip_bytes: conbytes(strip_whitespace=True)

    short_str: constr(min_length=2, max_length=10) = None
    regex_str: constr(regex='apple (pie|tart|sandwich)') = None
    strip_str: constr(strip_whitespace=True)

    big_int: conint(gt=1000, lt=1024) = None
    mod_int: conint(multiple_of=5) = None
    pos_int: PositiveInt = None
    neg_int: NegativeInt = None

    big_float: confloat(gt=1000, lt=1024) = None
    unit_interval: confloat(ge=0, le=1) = None
    mod_float: confloat(multiple_of=0.5) = None
    pos_float: PositiveFloat = None
    neg_float: NegativeFloat = None

    email_address: EmailStr = None
    email_and_name: NameEmail = None

    url: UrlStr = None

    password: SecretStr = None
    password_bytes: SecretBytes = None

    db_name = 'foobar'
    db_user = '******'
    db_password: str = None
    db_host = 'localhost'
    db_port = '5432'
    db_driver = 'postgres'
    db_query: dict = None
    dsn: DSN = None
    decimal: Decimal = None
    decimal_positive: condecimal(gt=0) = None
    decimal_negative: condecimal(lt=0) = None
    decimal_max_digits_and_places: condecimal(max_digits=2, decimal_places=2) = None
    mod_decimal: condecimal(multiple_of=Decimal('0.25')) = None
    uuid_any: UUID = None
    uuid_v1: UUID1 = None
    uuid_v3: UUID3 = None
    uuid_v4: UUID4 = None
    uuid_v5: UUID5 = None
    ipvany: IPvAnyAddress = None
    ipv4: IPv4Address = None
    ipv6: IPv6Address = None
    ip_vany_network: IPvAnyNetwork = None
    ip_v4_network: IPv4Network = None
    ip_v6_network: IPv6Network = None
    ip_vany_interface: IPvAnyInterface = None
    ip_v4_interface: IPv4Interface = None
    ip_v6_interface: IPv6Interface = None
class Location(BaseModel):
    search_field: Optional[str] = Field(
        None,
        description="content of original search field\n",
        example="8232JN")
    latitude: Optional[confloat(ge=-90.0, le=90.0)] = Field(
        None, description="geocoded location\n", example=52.5066973961792)
    longitude: Optional[confloat(ge=0.0, le=360.0)] = Field(
        None,
        description="geocoded location longitude\n",
        example=5.46887674785145)
    rd_x: Optional[float] = Field(
        None,
        description=
        "x coordinate in meters, geocoded location longitude transformed into EPSG:28992 \n",
        example=160544.902,
    )
    rd_y: Optional[float] = Field(
        None,
        description=
        "y coordinate in meters, geocoded location latitude transformed into EPSG:28992\n",
        example=502115.495,
    )
    address: Optional[str] = Field(
        None,
        description="geocoded adress (street/house number)\n",
        example="Botter 11")
    municipality: Optional[str] = Field(
        None,
        description="geocoded adress (municipality)\n",
        example="Lelystad")
    zipcode: Optional[constr(regex="\d{4}[A-Z]{2}")] = Field(
        None, description="geocoded zipcode \n", example="8232JN")
Example #8
0
class Address(BaseModel):
    address_str: str
    address_lat: confloat(strict=True, ge=-90.0, le=90.0)
    address_lng: confloat(strict=True, ge=-180.0, le=180.0)

    def to_dict(self):
        return self.dict()
Example #9
0
class ConsumerResponse(BaseModel):
    topic: StrictStr
    timestamp: str
    name: StrictStr
    message_id: StrictStr
    lat: confloat(gt=-90, lt=90)
    lon: confloat(gt=-180, lt=180)
Example #10
0
class Model(BaseModel):
    short_bytes: conbytes(min_length=2, max_length=10)
    strip_bytes: conbytes(strip_whitespace=True)

    short_str: constr(min_length=2, max_length=10)
    regex_str: constr(regex='apple (pie|tart|sandwich)')
    strip_str: constr(strip_whitespace=True)

    big_int: conint(gt=1000, lt=1024)
    mod_int: conint(multiple_of=5)
    pos_int: PositiveInt
    neg_int: NegativeInt

    big_float: confloat(gt=1000, lt=1024)
    unit_interval: confloat(ge=0, le=1)
    mod_float: confloat(multiple_of=0.5)
    pos_float: PositiveFloat
    neg_float: NegativeFloat

    short_list: conlist(int, min_items=1, max_items=4)

    decimal_positive: condecimal(gt=0)
    decimal_negative: condecimal(lt=0)
    decimal_max_digits_and_places: condecimal(max_digits=2, decimal_places=2)
    mod_decimal: condecimal(multiple_of=Decimal('0.25'))
Example #11
0
class AdamProperty(OptimizerPropertyBase):
    betas: Optional[Tuple[PositiveFloat, PositiveFloat]]
    eps: Optional[confloat(ge=0)]
    weight_decay: Optional[confloat(ge=0)]
    amsgrad: Optional[bool]

    __required_type__ = OptimizerType.ADAM
Example #12
0
def get_directions_with_coordinates(
        # URL values
        f_lon: confloat(ge=-180,
                        le=180) = Path(..., title="Origin point longitude"),
        f_lat: confloat(ge=-90, le=90) = Path(...,
                                              title="Origin point latitude"),
        t_lon: confloat(ge=-180,
                        le=180) = Path(...,
                                       title="Destination point longitude"),
        t_lat: confloat(ge=-90,
                        le=90) = Path(..., title="Destination point latitude"),
        # Query parameters
        type: str = Query(..., description="Transport mode"),
        language: str = "en",
        # Request
        request: Request = Depends(directions_request),
):
    """Get directions to get from a point to another."""
    from_place = Latlon(f_lat, f_lon)
    to_place = Latlon(t_lat, t_lon)
    if not type:
        raise HTTPException(status_code=400,
                            detail='"type" query param is required')
    return directions_client.get_directions(from_place,
                                            to_place,
                                            type,
                                            language,
                                            params=request.query_params)
Example #13
0
class KfilterParams(BaseModel):
    min_cov: confloat(ge=0, le=1)
    min_map: Dict[int, confloat(ge=0, le=1)]
    max_map: Dict[int, confloat(ge=0, le=1)]
    min_map_canon: Dict[int, confloat(ge=0, le=1)]
    trait_0: List[str] = Field(None)
    trait_1: List[str] = Field(None)
Example #14
0
class Location(BaseModel):
    uid: str = None
    name: constr(min_length=3, max_length=120)
    description: constr(min_length=10, max_length=4096)
    latitude: confloat(ge=-90, le=90)
    longitude: confloat(ge=-180, le=180)
    photos: List[AnyUrl]
Example #15
0
class TimeZone(base.Record):
    row_num: int
    country_code_alpha2: constr(min_length=2, max_length=2)
    name: str
    dst_offset: confloat(ge=-12, le=14)
    raw_offset: confloat(ge=-12, le=14)
    gmt_offset: confloat(ge=-12, le=14)
Example #16
0
class DiskUsage(BaseModel):
    mount_point: Optional[str] = Field(
        None,
        description=
        'The mounting point of the file system having the directory.')
    mount_available_size: conint(ge=0) = Field(
        ...,
        description=
        'Available space on the mounted file system having the directory, in bytes.',
    )
    mount_total_size: conint(ge=0) = Field(
        ...,
        description=
        'Total space on the mounted file system having the directory, in bytes.',
    )
    mount_used_size: conint(ge=0) = Field(
        ...,
        description=
        'Used space on the mounted file system having the directory, in bytes',
    )
    mount_used_size_percentage: confloat(ge=0.0, le=100.0) = Field(
        ...,
        description=
        'Percentage of used space regarding total space of the mounted file system',
    )
    used_size: conint(ge=0) = Field(
        ..., description='Used space by the directory, in bytes.')
    used_size_percentage: confloat(ge=0.0, le=100.0) = Field(
        ...,
        description=
        'Percentage of directory used space regarding total space of the mounted '
        'file system',
    )
Example #17
0
class Block(BaseModel):
    id: conint(ge=0) = Field(...,
                             description="The unique identifier for a block")
    displayName: str = Field(..., description="The display name of a block")
    name: constr(regex=r"\S+") = Field(..., description="The name of a block")
    hardness: Optional[confloat(ge=0.0)] = Field(
        None, description="Hardness of a block")
    stackSize: conint(ge=0) = Field(..., description="Stack size for a block")
    diggable: bool = Field(..., description="true if a block is diggable")
    boundingBox: BoundingBox = Field(..., description="BoundingBox of a block")
    material: Optional[str] = Field(None, description="Material of a block")
    harvestTools: Optional[Dict[str, Any]] = Field(
        None,
        description=
        "Using one of these tools is required to harvest a block, without that you get a 3.33x time penalty.",
    )
    variations: Optional[List[BlockVariation]] = None
    states: Optional[List[State]] = None
    drops: List[Union[int, Drop]]
    transparent: bool = Field(...,
                              description="true if a block is transparent")
    emitLight: conint(ge=0,
                      le=15) = Field(...,
                                     description="Light emitted by that block")
    filterLight: conint(ge=0, le=15) = Field(
        ..., description="Light filtered by that block")
    minStateId: Optional[conint(ge=0)] = Field(None,
                                               description="Minimum state id")
    maxStateId: Optional[conint(ge=0)] = Field(None,
                                               description="Maximum state id")
    defaultState: Optional[conint(ge=0)] = Field(
        None, description="Default state id")
    resistance: Optional[Optional[confloat(ge=-1.0)]] = Field(
        None, description="Blast resistance")
Example #18
0
 class ConstrainedNumbersModel(pydantic.BaseModel):
     conintt: pydantic.conint(gt=10, lt=100)
     coninte: pydantic.conint(ge=10, le=100)
     conintmul: pydantic.conint(ge=10, le=100, multiple_of=7)
     confloatt: pydantic.confloat(gt=10, lt=100)
     confloate: pydantic.confloat(ge=10, le=100)
     condecimalt: pydantic.condecimal(gt=10, lt=100)
     condecimale: pydantic.condecimal(ge=10, le=100)
Example #19
0
class QueryModel(BaseModel):
    lat: confloat(ge=-85, le=85)
    lng: confloat(ge=-180, le=180)
    zoom: conint(gt=0, lt=20) = 10
    width: conint(ge=95, le=1000) = 600
    height: conint(ge=60, le=1000) = 400
    marker: bool = True
    scale: conint(ge=1, le=2) = 1
Example #20
0
class Penguin(BaseModel):
    """Parse & validate penguin measurements"""
    bill_length_mm: confloat(gt=32, lt=60)
    bill_depth_mm: confloat(gt=13, lt=22)

    def to_df(self):
        """Convert to pandas dataframe with 1 row."""
        return pd.DataFrame([dict(self)])
Example #21
0
class UserInfo(pydantic.BaseModel):
    age: pydantic.confloat(ge=0)
    dependents: pydantic.confloat(ge=0)
    houses: typing.List[HouseInfo]
    income: pydantic.confloat(ge=0)
    marital_status: EnumMaritalStatus
    risk_questions: typing.Tuple[EnumBool, EnumBool, EnumBool]
    vehicles: typing.List[VehicleInfo]
Example #22
0
class Hotel(BaseModel):
    uid: str = None
    name: constr(max_length=120)
    price: PositiveInt
    description: constr(max_length=4096)
    photos: List[AnyUrl]
    address: constr(max_length=1024)
    latitude: confloat(ge=-90, le=90)
    longitude: confloat(ge=-180, le=180)
class TextField(BaseModel):
    value: Optional[str] = ""
    order: conint(ge=0)
    width: confloat(ge=0, le=1)
    height: confloat(ge=0, le=1)
    distance_to_left: confloat(ge=0, le=1)
    distance_to_bottom: confloat(ge=0, le=1)
    rotation: confloat(ge=0, le=1)
    text_style: Literal["normal", "shadowed"]
Example #24
0
class DtnBasicRadioParser(DtnAbstractParser):
    """ Validator for YAML configuration parameters of DtnBasicRadio """
    # Data rate in [bps]
    rate : PositiveFloat

    # Bit error rate
    BER : confloat(gt=-0.000000001, lt=1) = 0.0

    # Joules/bit in the link
    J_bit : confloat(gt=-0.0000001) = 0.0
Example #25
0
class RestrictedAudience(BaseModel):
    lang: Optional[List[Dict[str, RestrictedAudienceScore]]]
    country: Optional[List[Dict[str, RestrictedAudienceScore]]]
    sitekey: Optional[List[Dict[str, RestrictedAudienceScore]]]
    serverdomain: Optional[List[Dict[str, RestrictedAudienceScore]]]
    browser: Optional[List[Dict[RestrictedAudienceBrowserEnum,
                                RestrictedAudienceScore]]]
    confidence: Optional[List[Dict[RestrictedAudienceConfidenceEnum,
                                   RestrictedAudienceScore]]]
    reason: Optional[List[Dict[str, RestrictedAudienceScore]]]

    min_difficulty: Optional[conint(ge=0, le=4, strict=True)]
    min_user_score: Optional[confloat(ge=0, le=1)]
    max_user_score: Optional[confloat(ge=0, le=1)]

    launch_group_id: Optional[conint(ge=0, strict=True)]

    def dict(self, **kwargs):
        kwargs["exclude_unset"] = True
        return super().dict(**kwargs)

    def json(self, **kwargs):
        kwargs["exclude_unset"] = True
        return super().json(**kwargs)

    @root_validator()
    def validate_score_fields(cls, values: Dict[str, Any]) -> Dict[str, Any]:
        for entry, value in values.items():
            if value is None:
                continue
            if entry in [
                    "lang", "country", "browser", "sitekey", "serverdomain",
                    "confidence"
            ]:
                if isinstance(value, list):
                    for restriction in value:
                        if len(restriction) > 1:
                            raise ValueError(
                                "only 1 element per list item is allowed")
                        key = next(iter(restriction))
                        if entry in ["lang", "country", "sitekey"]:
                            if str(key) != str(key).lower():
                                raise ValueError("use lowercase")
        return values

    @validator("sitekey")
    def validate_sitekey(cls, value):
        if value is not None:
            for restriction in value:
                for sitekey in restriction:
                    try:
                        UUID(sitekey)
                    except:
                        raise ValidationError("invalid sitekey")
        return value
Example #26
0
class DnsTest(BaseModel):
    dns1_android: Optional[IPvAnyAddress]
    dns2_android: Optional[IPvAnyAddress]
    ns_akamai: Optional[IPvAnyAddress]
    ecs_akamai: Optional[IPvAnyAddress]
    ip_akamai: Optional[IPvAnyAddress]
    do_flag: Optional[bool]
    ad_flag: Optional[bool]
    rrsig: Optional[bool]
    resolver_ip_oarc: Optional[IPvAnyAddress]
    rating_source_port: Optional[models.RatingOarcEnum]
    rating_transaction_id: Optional[models.RatingOarcEnum]
    std_source_port: Optional[conint(ge=0)]
    std_transaction_id:  Optional[conint(ge=0)]
    bits_of_entropy_source_port: Optional[confloat(ge=0)]
    bits_of_entropy_transaction_id: Optional[confloat(ge=0)]
    
    @classmethod
    @root_validator(pre=True)
    def check_resolver_ip(cls, values):
        dns_android, dns_akami = values.get('dns1_android'), values.get('ns')
        if dns_android is None and dns_akami is None:
            raise ValueError('at least one resolver ip')
        return values
    
    @classmethod
    @root_validator
    def check_dnssec(cls, values):
        do_flag, ad_flag, rrsig = values.get('do_flag'), values.get('ad_flag'), values.get('rrsig')
        if (do_flag is not None and (ad_flag is None or rrsig is None)) or (do_flag is None and (ad_flag is not None or rrsig is not None)):
            raise ValueError('some dnssec values are missing')
        return values
    
    @classmethod
    @root_validator
    def check_oarc(cls, values):
        resolver_ip_oarc = values.get('resolver_ip_oarc')
        rating_source_port = values.get('rating_source_port')
        rating_transaction_id = values.get('rating_transaction_id')
        std_source_port = values.get('std_source_port')
        std_transaction_id = values.get('std_transaction_id')

        if (resolver_ip_oarc is not None):
            if((rating_transaction_id is not None and std_transaction_id is None) or (rating_transaction_id is None and std_transaction_id is not None)):
                raise ValueError('some oarc values of transaction_id are missing')
            elif((rating_source_port is not None and std_source_port is None) or (rating_source_port is None and std_source_port is not None)):
                raise ValueError('some oarc values of source_port are missing')
            elif(rating_source_port is None and std_source_port is None and rating_transaction_id is None and std_transaction_id is None):
                raise ValueError('some oarc values are missing')
        elif (rating_source_port is not None or std_source_port is not None or rating_transaction_id is not None or std_transaction_id is not None):
            raise ValueError('resolver_ip_oarc is missing')
        return values

    class Config:
        orm_mode = True
Example #27
0
 def __init__(
     self,
     height: Optional[Union[conint(gt=1),
                            confloat(gt=0.0, le=1.0)]] = Query(None),
     width: Optional[Union[conint(gt=1),
                           confloat(gt=0.0, le=1.0)]] = Query(None),
     length: Optional[Union[conint(gt=1),
                            confloat(gt=0.0, le=1.0)]] = Query(256)):
     self.length = length
     self.width = width
     self.height = height
Example #28
0
class Project_Settings(BaseModel):
    start_time: str
    end_time: str
    time_step_min: confloat(gt=0)
    max_iter: conint(ge=1, le=1000)
    error_tolerance: confloat(gt=0)
    simulation_type: SIMULATION_TYPE
    project_path: str
    mdb_file: str
    sxst_file: str
    cyme_installation_directory: str

    @validator('start_time')
    def validate_start_time(cls, v):
        try:
            Date = datetime.strptime(v, DATE_FORMAT)
        except:
            raise ValueError(
                "'start_time' should be a datetime string with format {}".
                format(DATE_FORMAT))
        pass

    @validator('end_time')
    def validate_end_time(cls, v):
        try:
            Date = datetime.strptime(v, DATE_FORMAT)
        except:
            raise ValueError(
                "'end_time' should be a datetime string with format {}".format(
                    DATE_FORMAT))
        pass

    @validator('cyme_installation_directory')
    def validate_cyme_installation_directory(cls, v):
        if not os.path.exists(v):
            raise Exception(f"Project path: {v} does not exist")

    @validator('project_path')
    def validate_project_path(cls, v):
        if not v:
            raise Exception(f"Please provide a valid project path")
        if not os.path.exists(v):
            raise Exception(f"Cyme installation path: {v} does not exist")
        else:
            for fldr in CYMEPY_FOLDER_STRUCTURE:
                if not os.path.exists(os.path.join(v, fldr)):
                    raise Exception(
                        f"A valid cymepy project should have a '{fldr}' folder"
                    )
            for file in CORE_CYMEPY_PROJECT_FILES:
                if not os.path.exists(os.path.join(v, file.value)):
                    raise Exception(
                        f"A valid cymepy project should have a '{file.value}' file in the base path"
                    )
class User(BaseModel):
    id: conint(ge=0)
    name: constr(max_length=256)
    tag: Optional[constr(max_length=64)] = None
    uid: UID
    phones: Optional[List[Phone]] = Field(None, max_items=10)
    fax: Optional[List[constr(min_length=3)]] = None
    height: Optional[Union[conint(ge=1, le=300),
                           confloat(ge=1.0, le=300.0)]] = None
    weight: Optional[Union[confloat(ge=1.0, le=1000.0),
                           conint(ge=1, le=1000)]] = None
class User(BaseModel):
    name: Optional[str] = Field(None, example='ken')
    age: Optional[int] = None
    salary: Optional[conint(ge=0)] = None
    debt: Optional[conint(le=0)] = None
    loan: Optional[confloat(le=0.0)] = None
    tel: Optional[constr(regex=r'^(\([0-9]{3}\))?[0-9]{3}-[0-9]{4}$')] = None
    height: Optional[confloat(ge=0.0)] = None
    weight: Optional[confloat(ge=0.0)] = None
    active: Optional[bool] = None
    photo: Optional[conbytes(min_length=100)] = None