class NestedDichotomousDataset(DatasetValidator): dataset_options: conlist(NestedDichotomousModelOptions, min_items=1, max_items=10) datasets: conlist(NestedDichotomousDatasetSchema, min_items=1, max_items=10)
class Face3D(NoExtraBaseModel): """A single planar face in 3D space.""" type: constr(regex='^Face3D$') = 'Face3D' boundary: List[conlist(float, min_items=3, max_items=3)] = Field( ..., min_items=3, description= 'A list of points representing the outer boundary vertices of ' 'the face. The list should include at least 3 points and each point ' 'should be a list of 3 (x, y, z) values.') holes: List[conlist( conlist(float, min_items=3, max_items=3), min_items=3 )] = Field( default=None, description= 'Optional list of lists with one list for each hole in the face.' 'Each hole should be a list of at least 3 points and each point a list ' 'of 3 (x, y, z) values. If None, it will be assumed that there are no ' 'holes in the face.') plane: Plane = Field( default=None, description= 'Optional Plane indicating the plane in which the face exists.' 'If None, the plane will usually be derived from the boundary points.')
class Observable(BaseModel): """ An observable. If given list is more than one element, this is the tensor product of each operator in the list. Attributes: observable (List[Union[str, List[List[List[float]]]]): A list with at least one item and items are strings matching the observable regex or a two dimensional hermitian matrix with complex entries. Each complex number is represented using a List[float] of size 2, with element[0] being the real part and element[1] imaginary. inf, -inf, and NaN are not allowable inputs for the element. Examples: >>> Observable(observable=["x"]) >>> Observable(observable=[[[0, 0], [1, 0]], [[1, 0], [0, 0]]]) """ observable: conlist( Union[constr(regex="(x|y|z|h|i)"), conlist( conlist( conlist(confloat(gt=float("-inf"), lt=float("inf")), min_items=2, max_items=2), min_items=2, ), min_items=2, ), ], min_items=1, )
class PatientRequest(BaseModel): data: conlist( conlist(Union[float, int], min_items=N_FEATURES, max_items=N_FEATURES), min_items=1, ) features: conlist(str, min_items=N_FEATURES, max_items=N_FEATURES) @validator("data") def data_consistency(cls, data): for sample in data: for val, (_, v_min, v_max) in zip(sample, FEATURES_MIN_MAX): if v_min is None and v_max is None: continue if not (v_min <= val <= v_max): raise ValueError(OUT_OF_RANGE_ERROR) return data @validator("features") def feature_consistency(cls, features): if features != FEATURE_NAMES: raise ValueError(INCORRECT_FEATURE_ORDER) return features
class ContainerDocument(Base): id: ObjectID = Field(default_factory=ObjectID, alias='_id') name: str = Field(...) scenes: conlist(ResourceDocument, min_items=1) images: conlist(ResourceDocument, min_items=1) created_at: datetime = Field(default_factory=utils.utc_now) updated_at: datetime = Field(default_factory=utils.utc_now)
class ContainerResponse(Base): id: ObjectID = Field(...) name: str = Field(...) scenes: conlist(ResourceDocument, min_items=1) images: conlist(ResourceDocument, min_items=1) created_at: datetime = Field(...) updated_at: datetime = Field(...)
class Restaurant: name: constr(regex=r'^[a-zA-Z0-9 ]*$', min_length=1, max_length=16) owner: constr(min_length=1) address: constr(min_length=1) employees: conlist(Employee, min_items=2) dishes: conlist(Dish, min_items=3) number_of_seats: PositiveInt to_go: bool delivery: bool
class ConfigHomographyMatrix(BaseModel): pts_destination: conlist(conlist(float, min_items=2, max_items=2), min_items=4, max_items=4) class Config: schema_extra = { 'example': { 'pts_destination': [[130., 310.], [45., 420.], [275., 420.], [252., 310.]] } }
class Export(OscalBaseModel): description: Optional[Description] = None properties: Optional[List[Prop]] = None annotations: Optional[Union[Annotation, conlist(Annotation, min_items=2)]] = None links: Optional[List[Link]] = None provided_group: Optional[Union[Provided, conlist(Provided, min_items=2)]] = Field( None, alias='provided-group' ) responsibilities: Optional[Union[Responsibility, conlist(Responsibility, min_items=2)]] = None remarks: Optional[Remarks] = None
class Commit(BaseModel): time_updated: int time_created: int user_id: str workspace: str commit_id: str entry_id: str type: str data: str title: str marked: bool locked: Any comments: conlist(Comment, min_items=0) likes: conlist(Like, min_items=0) tags: conlist(CommitTag, min_items=0)
class Search(StrictModel): terms: Union[conlist(nonEmptyString, min_items=1), nonEmptyString] price: Optional[conlist(conint(ge=0), min_items=2, max_items=2)] location: Optional[Union[Location, conlist(Location, min_items=1)]] shippable: Optional[bool] @validator('price') def check_max_is_higher_than_min(cls, v): if not v[1] > v[0]: raise ValueError('Max price must be > min price') return {'min': v[0], 'max': v[1]} # validators _normalize_terms = validator('terms', allow_reuse=True)(ensure_list) _normalize_terms = validator('location', allow_reuse=True)(ensure_list)
class MoleculeNode(pydantic.BaseModel): """ Node representing a molecule """ smiles: str type: pydantic.constr(regex=r"^mol$") children: Optional[pydantic.conlist(ReactionNode, min_items=1, max_items=1)]
class Pipeline(BaseModel): __root__: conlist(Union[StepWrapper, ParallelStep, Variables], min_items=1) # noinspection PyMethodParameters @validator("__root__") def validate_variables_must_be_first_element_of_list_if_present( cls, pipeline_items): if any(i for i in pipeline_items[1:] if isinstance(i, Variables)): raise ValueError( "'variables' can only be the first element of the list") return pipeline_items def get_variables(self) -> Optional[Variables]: if isinstance(self.__root__[0], Variables): return self.__root__[0] return Variables(variables=[]) def get_steps(self) -> List[Union[StepWrapper, ParallelStep]]: return [i for i in self.__root__ if not isinstance(i, Variables)] def __iter__(self): return iter(self.__root__) def __getitem__(self, item): return self.__root__[item] def expand_env_vars(self, variables: Dict[str, str]): for s in self.get_steps(): s.expand_env_vars(variables)
class TopSecretRequestSchema(BaseModel): satellites: conlist(SatelliteSchema, min_items=3, max_items=3) class Config: schema_extra = { 'example': { "satellites": [ { "name": "kenobi", "distance": 103.14, "message": [" ", "es", " ", "mensaje"], }, { "name": "skywalker", "distance": 53.27, "message": ["Este", " ", " ", "mensaje"], }, { "name": "sato", "distance": 82.89, "message": [" ", " ", "un", "mensaje"], }, ] } }
class RechargeTarget(OptimizationTarget): """A fitting target which uses the ``openff-recharge`` framework to train bond charge correction parameters against QM electrostatic potential data.""" model_version: Literal[0] = Field( 0, description="The current version of this model. Models with different version " "numbers are incompatible.", ) qc_data_set_ids: conlist(IdentifierStr, min_items=1) = Field( ..., description="The unique identifiers of the QC data sets to include in this " "optimization target.", ) grid_settings: GridSettings = Field( ..., description="The settings which define the grid to compute the ESP and " "electric field on for each entry in each QC data set (``qc_data_set_ids``).", ) property: Literal["esp", "electric-field"] = Field( ..., description="The type of electrostatic property to train against." )
class PodcastSchema(AudioSchema): name: constr(min_length=1, max_length=100) host: constr(min_length=1, max_length=100) participants: Optional[conlist(constr(min_length=1, max_length=100), min_items=0, max_items=10)] = [] class Config: orm_mode = True
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'))
class Manifest(pydantic.BaseModel): """Manifest data""" repos: pydantic.conlist(Repository, min_items=1) def get_repos(self) -> List[Repository]: return self.repos
class AnnealingTaskResult(BraketSchemaBase): """ The annealing task result schema. Attributes: braketSchemaHeader (BraketSchemaHeader): Schema header. Users do not need to set this value. Only default is allowed. solutions (List[int]): Solutions of task result. Default is `None`. solutionCounts (List[int]): The number of times the solutions occurred. Default is `None`. values (List[float]): Output or energy of the solutions. Default is `None`. variableCount (int): The number of variables. Default is `None`. taskMetadata (TaskMetadata): The task metadata. additionalMetadata (AdditionalMetadata): Additional metadata of the task. """ _ANNEALING_TASK_RESULT_HEADER = BraketSchemaHeader( name="braket.task_result.annealing_task_result", version="1") braketSchemaHeader: BraketSchemaHeader = Field( default=_ANNEALING_TASK_RESULT_HEADER, const=_ANNEALING_TASK_RESULT_HEADER) solutions: Optional[List[conlist(conint(ge=-1, le=3), min_items=1)]] solutionCounts: Optional[List[conint(ge=0)]] values: Optional[List[float]] variableCount: Optional[conint(ge=0)] taskMetadata: TaskMetadata additionalMetadata: AdditionalMetadata
class PostbackEvent(BaseEvent, WithMessaging): messaging: conlist(PostbackMessageMessaging, min_items=1, max_items=1) @property def payload(self): postback: Postback = self.theMessaging.postback return postback.payload
class Restaurant: name: constr(regex=r'^[a-zA-Z0-9 ]*$', min_length=1, max_length=16) owner: constr(min_length=1) address: constr(min_length=1) employees: conlist(Employee, min_items=2) dishes: conlist(Dish, min_items=3) number_of_seats: PositiveInt to_go: bool delivery: bool @validator('employees') def check_chef_and_server(cls, employees): if (any(e for e in employees if e.position == 'Chef') and any(e for e in employees if e.position == 'Server')): return employees raise ValueError('Must have at least one chef and one server')
class OrderIn(BaseModel): name: constr( min_length=2, max_length=models.Sample.order.property.columns[0].type.length) comment: Optional[str] customer: constr( min_length=1, max_length=models.Customer.internal_id.property.columns[0].type.length) samples: conlist(Any, min_items=1) ticket: Optional[str] @classmethod def parse_obj(cls, obj: dict, project: OrderType): parsed_obj: OrderIn = super().parse_obj(obj) parsed_obj.parse_samples(project=project) return parsed_obj def parse_samples(self, project: OrderType): """ Parses samples of by the type given by the project Parameters: project (OrderType): type of project Returns: Nothing """ parsed_samples = [] sample: dict for sample in self.samples: parsed_sample = sample_class_for(project=project).parse_obj(sample) parsed_samples.append(parsed_sample) self.samples = parsed_samples
class PODCAST(BaseModel): id: int name: str duration: int upload_time: datetime host: str participants: Optional[conlist(str, max_items=10)] = Field(None)
class Feed(BaseModel): title: str description: str explicit: bool = False language: str = "en" link: constr(max_length=500) = "" # type: ignore items: conlist(Item, min_items=1) # type: ignore authors: List[str] image: Optional[str] categories: List[str] @validator("language") def language_code(cls, value: str) -> str: return (value[:2] if value else "en").strip().lower() @validator("link", pre=True) def prepare_link(cls, value: str) -> str: if not value: return value # links often just consist of domain: try prefixing http:// if not value.startswith("http"): value = "http://" + value # if not a valid URL, just return empty string try: URLValidator(value) except ValidationError: return "" return value
class Settings(BaseSettings): debug: bool = False log_file: Optional[str] = None api_prefix: str = "/api" projects: conlist(constr(strict=True, regex=r"[0-9_\-a-zA-Z]+"), min_items=1) = ["pulse-lenta"] projectspace: DirectoryPath = BASE.joinpath("../projectspace").absolute() email: Optional[EmailSettings] = EmailSettings() allure: str flock_timeout_sec: PositiveInt = 60 stats_handler_maker: Optional[ PyObject] = None # staticmethod(make_stats_handler) @validator("projects") def projects_validator(cls, projects: List[str]) -> List[str]: return [project.lower() for project in projects] @validator("allure") def escape_cmd(cls, value: str) -> str: if shlex.quote(value) != value: raise RuntimeError("Allure cmd should be escaped") try: version: str = subprocess.check_output([value, "--version" ]).decode("utf-8") logger.info(f"Allure version: {version}") except (FileNotFoundError, subprocess.CalledProcessError): raise RuntimeError(f"Invalid allure cmd '{value}'") return value
class Responsibility(OscalBaseModel): uuid: constr( regex= r'^[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-4[0-9A-Fa-f]{3}-[89ABab][0-9A-Fa-f]{3}-[0-9A-Fa-f]{12}$' ) = Field( ..., description= 'A RFC 4122 version 4 Universally Unique Identifier (UUID) for the containing object.', title='Universally Unique Identifier', ) provided_uuid: Optional[str] = Field( None, alias='provided-uuid', description= "Identifies a 'provided' assembly associated with this assembly.", title='Provided UUID', ) description: Description properties: Optional[List[Prop]] = None annotations: Optional[Union[Annotation, conlist(Annotation, min_items=2)]] = None links: Optional[List[Link]] = None responsible_roles: Optional[Dict[str, ResponsibleRole]] = Field( None, alias='responsible-roles') remarks: Optional[Remarks] = None
class GenericRequest(BaseModel): name: constr(max_length=100, min_length=1) duration: conint(gt=0) author: constr(max_length=100) host: constr(max_length=100) narrator: constr(max_length=100) duration: conint(gt=0) participants: conlist(str, max_items=10, min_items=0)
class AnomalousRegion(BaseModel): bounding_box: conlist(int, min_items=4, max_items=4) = Field( ..., description=("[x left, y top, x right, y bottom]. " "Must be an absolute type value.")) score: confloat(ge=0., le=1.0) = Field( ..., description=("Score for the region. " "For GT, value must be 1."))
class Meeting(BaseModel): days: Optional[conlist(conint(ge=0, le=8), max_items=10)] start: Optional[constr(max_length=10)] end: Optional[constr(max_length=10)] f_time: constr(max_length=100) bldg: constr(max_length=100) # Can be 'TBA' rm: Optional[constr(max_length=100)] rm_l: Optional[constr(max_length=200)]
class AddNewPlaylist(BaseModel): """ define AddNewPlaylist model for data validation :user_id: str :songs: constraint list, minimum length is 1 """ user_id: str songs: conlist(str, min_items=1)