def __init__( # noqa pylint: disable=too-many-arguments self, metadata_writer, # type: MetadataWriter interactive, # type: bool no_overwrite, # type: bool decode_input, # type: bool encode_output, # type: bool required_encryption_context, # type: Dict[str, str] required_encryption_context_keys, # type: List[str] commitment_policy, # type: CommitmentPolicy buffer_output, max_encrypted_data_keys, # type: Union[None, int] ): # type: (...) -> None """Workaround pending resolution of attrs/mypy interaction. https://github.com/python/mypy/issues/2088 https://github.com/python-attrs/attrs/issues/215 """ self.metadata_writer = metadata_writer self.interactive = interactive self.no_overwrite = no_overwrite self.decode_input = decode_input self.encode_output = encode_output self.required_encryption_context = required_encryption_context self.required_encryption_context_keys = required_encryption_context_keys # pylint: disable=invalid-name self.buffer_output = buffer_output self.client = aws_encryption_sdk.EncryptionSDKClient( commitment_policy=commitment_policy, max_encrypted_data_keys=max_encrypted_data_keys, ) attr.validate(self)
def __init__(self, java_name, mode): # type: (Text, Callable) -> None # noqa=D107 # Workaround pending resolution of attrs/mypy interaction. # https://github.com/python/mypy/issues/2088 # https://github.com/python-attrs/attrs/issues/215 self.java_name = java_name self.mode = mode attr.validate(self)
def _clean_attrs_matcher(ob): try: attr.validate(ob) return True # return clean_dict(attr.asdict(ob)) except NotAnAttrsClassError: return False
def parse_raml(loaded_raml, config): """ Parse loaded RAML file into RAML/Python objects. :param RAMLDict loaded_raml: OrderedDict of loaded RAML file :returns: :py:class:`.raml.RootNode` object. :raises: :py:class:`.errors.InvalidRAMLError` when RAML file is invalid """ validate = str(_get(config, "validate")).lower() == 'true' # Postpone validating the root node until the end; otherwise, # we end up with duplicate validation exceptions. attr.set_run_validators(False) root = create_root(loaded_raml, config) attr.set_run_validators(validate) root.security_schemes = create_sec_schemes(root.raml_obj, root) root.traits = create_traits(root.raml_obj, root) root.resource_types = create_resource_types(root.raml_obj, root) root.resources = create_resources(root.raml_obj, [], root, parent=None) if validate: attr.validate(root) # need to validate again for root node if root.errors: raise InvalidRAMLError(root.errors) return root
def _parse_view(self, elem) -> ProtoView: attributes = elem.attrib sofa = int(attributes["sofa"]) members = [int(e) for e in attributes.get("members", "").split(" ")] result = ProtoView(sofa=sofa, members=members) attr.validate(result) return result
def __init__(self, ld_type, ld_id=None, ld_context=None, validator=DEFAULT_DATA_VALIDATOR, data=None): """Initialize a :class:`~.LazyLoadableModel` instance. If a :attr:`data` is provided, a :class:`Model` is generated as the instance's :attr:`~.LazyLoadableModel.loaded_model` using the given arguments. Ignores :attr:`ld_id`, see the :meth:`ld_id` property instead. """ self.ld_type = ld_type self.ld_context = _make_context_immutable(ld_context or get_default_ld_context()) self.validator = validator self.loaded_model = None attr.validate(self) if data: self.loaded_model = Model(data=data, ld_type=self.ld_type, ld_context=self.ld_context, validator=self.validator)
def __init__( self, key_id, # type: Text botocore_session=None, # type: Optional[botocore.session.Session] grant_tokens=None, # type: Optional[Tuple[Text]] material_description=None, # type: Optional[Dict[Text, Text]] regional_clients=None, # type: Optional[Dict[Text, botocore.client.BaseClient]] ): # noqa=D107 # type: (...) -> None # Workaround pending resolution of attrs/mypy interaction. # https://github.com/python/mypy/issues/2088 # https://github.com/python-attrs/attrs/issues/215 if botocore_session is None: botocore_session = botocore.session.Session() if grant_tokens is None: # reassignment confuses mypy grant_tokens = () # type: ignore if material_description is None: material_description = {} if regional_clients is None: regional_clients = {} self._key_id = key_id self._botocore_session = botocore_session self._grant_tokens = grant_tokens self._material_description = material_description self._regional_clients = regional_clients attr.validate(self) self.__attrs_post_init__()
def load(self, filepath='pwm.settings'): """Loads setting from a json file""" with open(filepath) as infile: file_dict = json.load(infile) passwd_filter = self._get_attr_filters() attr_fields = attr.asdict(self, filter=passwd_filter) try: for attr_key in attr_fields: if attr_key in file_dict: self.__setattr__(attr_key, file_dict[attr_key]) try: attr.validate(self) except TypeError: # Python 2 fix value = file_dict[attr_key].encode("utf-8") self.__setattr__(attr_key, value) attr.validate(self) except TypeError as err: # If attrs are of the wrong type then roll back for attr_key in attr_fields: self.__setattr__(attr_key, attr_fields[attr_key]) raise TypeError(err)
def __init__( self, algorithm=None, data_encryption_key=None, encrypted_data_keys=None, encryption_context=None, signing_key=None, **kwargs ): # noqa we define this in the class docstring if algorithm is None: raise TypeError("algorithm must not be None") if encryption_context is None: raise TypeError("encryption_context must not be None") if data_encryption_key is None and encrypted_data_keys: # If data_encryption_key is not set, encrypted_data_keys MUST be either None or empty raise TypeError("encrypted_data_keys cannot be provided without data_encryption_key") if encrypted_data_keys is None: encrypted_data_keys = [] super(EncryptionMaterials, self).__init__( algorithm=algorithm, encryption_context=encryption_context, data_encryption_key=data_encryption_key, **kwargs ) self._setattr("signing_key", signing_key) self._setattr("_encrypted_data_keys", encrypted_data_keys) attr.validate(self)
def load(self, filepath='pwm.settings'): """Loads setting from a json file""" with open(filepath) as infile: file_dict = json.load(infile) passwd_filter = self._get_attr_filters() attr_fields = attr.asdict(self, filter=passwd_filter) try: for attr_key in attr_fields: if attr_key in file_dict: self.__setattr__(attr_key, file_dict[attr_key]) try: attr.validate(self) except TypeError: # Python 2 fix value = file_dict[attr_key].encode("utf-8") self.__setattr__(attr_key, value) attr.validate(self) except TypeError as err: # If attrs are of the wrong type then roll back for attr_key in attr_fields: self.__setattr__(attr_key, attr_fields[attr_key]) raise TypeError(err)
def __call__(self, output_file=None): # type: (Optional[str]) -> MetadataWriter """Set the output file target and validate init and call arguments. .. note:: Separated from ``__init__`` to make use as an argparse type simpler. :param str output_file: Path to file to write to, or "-" for stdout (optional) """ self.output_file = output_file if self.suppress_output: return self if self.output_file is None: raise TypeError( "output_file cannot be None when suppress_output is False") if self.output_file == "-": self._output_mode = "w" return self if not os.path.isdir( os.path.dirname(os.path.realpath(self.output_file))): raise BadUserArgumentError( "Parent directory for requested metdata file does not exist.") self._output_mode = "ab" self.output_file = os.path.abspath(self.output_file) attr.validate(self) return self
def request_from_json(self, json_request, encoded=True): """ Method produces HppRequest object from JSON. Carries out the following actions: * Deserialize JSON to request object * Decodes Base64 inputs * Validates inputs :param json_request: string :param encoded: bool :return: HppRequest """ logger.info("Converting JSON to HppRequest.") logger.debug("Decoding object.") try: hpp_request = JsonUtils.from_json_hpp_request( json_request, self.encoding_charset, encoded) except Exception as e: error_msg = "Exception decoding json HPP request" logger.error("{}: {}".format(error_msg, e)) raise SdkError(error_msg, e) # validate request attr.validate(hpp_request) return hpp_request
def request_to_json(self, hpp_request, encoded=True): """ Method produces JSON from HppRequest object. Carries out the following actions: * Generate security hash * Validates inputs * Base64 encodes inputs * Serialises request object to JSON :param hpp_request: HppRequest :param encoded: bool :return: string """ logger.info("Converting HppRequest to JSON.") # generate hash logger.debug("Generating hash.") # set request object and calculate hash from it self.get_request_hash(hpp_request) # validate request logger.debug("Validating request.") attr.validate(hpp_request) logger.debug("Encoding to base64 and converting HppRequest to JSON.") try: json_request = JsonUtils.to_json(hpp_request, self.encoding_charset, encoded) except Exception as e: error_msg = "Exception json encoding HPP request" logger.error("{}: {}".format(error_msg, e)) raise SdkError(error_msg, e) return json_request
def set_state( self, state: AgentState, reset_sensors: bool = True, infer_sensor_states: bool = True, is_initial: bool = False, ) -> None: r"""Sets the agents state :param state: The state to set the agent to :param reset_sensors: Whether or not to reset the sensors to their default intrinsic/extrinsic parameters before setting their extrinsic state. :param infer_sensor_states: Whether or not to infer the location of sensors based on the new location of the agent base state. :param is_initial: Whether this state is the initial state of the agent in the scene. Used for resetting the agent at a later time Setting ``reset_sensors`` to :py:`False` allows the agent base state to be moved and the new sensor locations inferred without changing the configuration of the sensors with respect to the base state of the agent. Setting ``infer_sensor_states`` to :py:`False` is useful if you'd like to directly control the state of a sensor instead of moving the agent. """ attr.validate(state) habitat_sim.errors.assert_obj_valid(self.body) if isinstance(state.rotation, (list, np.ndarray)): state.rotation = quat_from_coeffs(state.rotation) self.body.object.reset_transformation() self.body.object.translate(state.position) self.body.object.rotation = quat_to_magnum(state.rotation) if reset_sensors: for _, v in self._sensors.items(): v.set_transformation_from_spec() if not infer_sensor_states: for k, v in state.sensor_states.items(): assert k in self._sensors if isinstance(v.rotation, list): v.rotation = quat_from_coeffs(v.rotation) s = self._sensors[k] s.node.reset_transformation() s.node.translate( quat_rotate_vector(state.rotation.inverse(), v.position - state.position)) s.node.rotation = quat_to_magnum(state.rotation.inverse() * v.rotation) if is_initial: self.initial_state = state
def __init__(self, encrypt, decrypt): # noqa=D107 # type: (bool, bool) -> None # Workaround pending resolution of attrs/mypy interaction. # https://github.com/python/mypy/issues/2088 # https://github.com/python-attrs/attrs/issues/215 self.encrypt = encrypt self.decrypt = decrypt attr.validate(self)
def __init__(self, capacity): # noqa=D107 # type: (int) -> None # Workaround pending resolution of attrs/mypy interaction. # https://github.com/python/mypy/issues/2088 # https://github.com/python-attrs/attrs/issues/215 self.capacity = capacity attr.validate(self) self.__attrs_post_init__()
def validate(self): validate(self) if not ( (self.rtime is None and self.duration is None) or (self.rtime is not None and self.duration is not None) ): raise ValueError("rtime and duration must be used together")
def is_valid_url(self, url): validate = URLValidator() try: validate(url) except ValidationError: return False return True
def test_create_view_creates_view(): cas = Cas() view = cas.create_view("testView") sofa = view.get_sofa() attr.validate(sofa) assert sofa.sofaID == "testView"
def update(data: InventoryModel) -> InventoryModel: today = date.today() discount: DiscountModel = data.discounts["Apples"] discount.since = today - timedelta(days=today.weekday()) discount.until = today - timedelta(days=today.weekday() - 6) validate(discount) return data
def test_initial_view_is_created(): cas = Cas() view = cas.get_view("_InitialView") sofa = view.get_sofa() attr.validate(sofa) assert sofa.sofaID == "_InitialView"
def __init__(self, java_name, padding): # type: Text # type: Callable # noqa=D107 # type: (...) -> None # Workaround pending resolution of attrs/mypy interaction. # https://github.com/python/mypy/issues/2088 # https://github.com/python-attrs/attrs/issues/215 self.java_name = java_name self.padding = padding attr.validate(self)
def __init__(self, cipher, mode, padding): # noqa=D107 # type: (JavaEncryptionAlgorithm, JavaMode, JavaPadding) -> None # Workaround pending resolution of attrs/mypy interaction. # https://github.com/python/mypy/issues/2088 # https://github.com/python-attrs/attrs/issues/215 self.cipher = cipher self.mode = mode self.padding = padding attr.validate(self)
def test_validate_shape_init(): # Construct a Spam instance with valid arguments. This should just work spam = Spam( np.zeros((1, 7, 4)), np.zeros((4, 3)), np.zeros((2, 3)), np.zeros(5), "abcde" ) # Double check attr.validate(spam) # Call constructor with invalid arguments with pytest.raises(TypeError): _ = Spam( np.zeros((2, 7, 4)), np.zeros((4, 3)), np.zeros((2, 3)), np.zeros(5), "abcde", ) with pytest.raises(TypeError): _ = Spam( np.zeros((2, 7)), np.zeros((4, 3)), np.zeros((2, 3)), np.zeros(5), "abcde", ) with pytest.raises(TypeError): _ = Spam( np.zeros((2, 7, 4)), np.zeros((1, 3)), np.zeros((2, 3)), np.zeros(5), "abcde", ) with pytest.raises(TypeError): _ = Spam( np.zeros((2, 7, 4)), np.zeros((4, 9)), np.zeros((2, 3)), np.zeros(5), "abcde", ) with pytest.raises(TypeError): _ = Spam( np.zeros((2, 7, 4)), np.zeros((4, 3)), np.zeros((2, 3)), np.zeros(5), "abcde", ) with pytest.raises(TypeError): _ = Spam( np.zeros((2, 7, 4)), np.zeros((4, 3)), np.zeros((2, 3)), np.zeros(5), 4, "abcd", )
def __init__(self, partition, sort=None): # type: Text # type: Optional[Text] # noqa=D107 # type: (...) -> None # Workaround pending resolution of attrs/mypy interaction. # https://github.com/python/mypy/issues/2088 # https://github.com/python-attrs/attrs/issues/215 self.partition = partition self.sort = sort attr.validate(self) self.__attrs_post_init__()
def __attrs_post_init__(self): # Casefold nicks after instantiation # as its not worth adding a custom decode hook to do this in cattrs. self.announcer_nicks = { nick.casefold() for nick in self.announcer_nicks } # Assert we didn't somehow invalidate the dataclass. attr.validate(self)
def __init__(self, java_name, algorithm_type, hash_type): # noqa=D107 # type: (Text, Callable, Callable) -> None # Workaround pending resolution of attrs/mypy interaction. # https://github.com/python/mypy/issues/2088 # https://github.com/python-attrs/attrs/issues/215 self.java_name = java_name self.algorithm_type = algorithm_type self.hash_type = hash_type attr.validate(self)
def __init__(self, client, auto_refresh_table_indexes): # noqa=D107 # type: (botocore.client.BaseClient, bool) -> None # Workaround pending resolution of attrs/mypy interaction. # https://github.com/python/mypy/issues/2088 # https://github.com/python-attrs/attrs/issues/215 self._client = client self._auto_refresh_table_indexes = auto_refresh_table_indexes attr.validate(self) self.__attrs_post_init__()
def hash(self, secret): """ Set and validate sha1hash :param secret: string """ self.sha1hash = self.generate_hash(secret) # Validate hash attr.validate(self) return self.sha1hash
def __init__(self, description, algorithm, length): # type: (Text, Text, int) -> None # Workaround pending resolution of attrs/mypy interaction. # https://github.com/python/mypy/issues/2088 # https://github.com/python-attrs/attrs/issues/215 self.description = description self.algorithm = algorithm self.length = length attr.validate(self)
def __init__(self, table, materials_provider): # noqa=D107 # type: (ServiceResource, CryptographicMaterialsProvider) -> None # Workaround pending resolution of attrs/mypy interaction. # https://github.com/python/mypy/issues/2088 # https://github.com/python-attrs/attrs/issues/215 self._table = table self._materials_provider = materials_provider attr.validate(self) self.__attrs_post_init__()
def _readInfo(self): """ Read the info.plist if the file is availble. """ # get the info.plist path infoPath = self.infoPath() if infoPath and os.path.exists(infoPath): info = readPlist(infoPath) self.info.fromDict(info) # validate incoming info attr.validate(self.info)
def parse_raml(loaded_raml, config): """ Parse loaded RAML file into RAML/Python objects. :param RAMLDict loaded_raml: OrderedDict of loaded RAML file :returns: :py:class:`.raml.RootNode` object. """ validate = str(config.get("validate")).lower() == 'true' attr.set_run_validators(validate) root = create_root(loaded_raml, config) root.security_schemes = create_sec_schemes(root.raml_obj, root) root.traits = create_traits(root.raml_obj, root) root.resource_types = create_resource_types(root.raml_obj, root) root.resources = create_resources(root.raml_obj, [], root, parent=None) if validate: attr.validate(root) # need to validate again for root node return root
def buildPackage(self, destinationPath, scriptRoot): """ Build a .drawbot package """ if not destinationPath.endswith(".drawbot"): return False, "The path to save the package must have a .drawbot file extension." # check if the script root exists if not os.path.exists(scriptRoot): return False, "Cannot find the script root '%s'" % scriptRoot # check if the main script path exists mainScriptPath = os.path.join(scriptRoot, self.info.mainScript) if not os.path.exists(mainScriptPath): return False, "Main script path '%s' does not exists in '%s'." % (self.info.mainScript, mainScriptPath) # build packages in temp folder tempDir = tempfile.mkdtemp() # set the temp folder self.path = tempDir # validate info attr.validate(self.info) # write the plist infoData = self.info.asDict() # only write info that is different from if infoData: writePlist(infoData, self.infoPath()) # build lib root path libRoot = os.path.join(self.path, "lib") # copy the script root shutil.copytree(scriptRoot, libRoot) # remove existing destination paths if os.path.exists(destinationPath): shutil.rmtree(destinationPath) # copy the temp to the destination path shutil.copytree(tempDir, destinationPath) # remove the temp shutil.rmtree(tempDir) # set the destination path self.path = destinationPath return True, ""