Best Python code snippet using autotest_python
AbstractDataContainer.py
Source:AbstractDataContainer.py
1from typing import Any2class AbstractDataContainer:3 def __init__(self):4 self._container = None5 self._is_dictionary = False6 self._is_list = False7 def __getitem__(self, key: str):8 if self._is_dictionary:9 return self._container[key]10 elif self._is_list:11 for item in self._container:12 if item[0] == key:13 return item[1]14 def __setitem__(self, key: str, value):15 if self._is_dictionary:16 self._container[key] = value17 elif self._is_list:18 for item in self._container:19 if item[0] == key:20 item[1] = value21 def __iter__(self):22 if self._is_dictionary:23 self._container_iterator = iter(self._container.items())24 elif self._is_list:25 self._container_iterator = iter(self._container)26 return self27 def __next__(self):28 if self._is_dictionary:29 return next(self._container_iterator)30 elif self._is_list:31 item = next(self._container_iterator)32 return item[0], item[1]33 def __len__(self):34 if self._container is not None:35 return len(self._container)36 else:37 return 038 def __eq__(self, other):39 if isinstance(other, AbstractDataContainer):40 if (self._is_dictionary and other.is_dictionary()) or \41 (self._is_list and other.is_list()):42 return self._container == other._container43 elif not self._is_dictionary and not self._is_list and not other.is_dictionary() and not other.is_list():44 return True45 else:46 raise TypeError47 else:48 raise TypeError49 def __ne__(self, other):50 if isinstance(other, AbstractDataContainer):51 if (self._is_dictionary and other._is_dictionary) or \52 (self._is_list and other._is_list):53 return self._container != other._container54 else:55 raise TypeError56 else:57 raise TypeError58 def __contains__(self, other):59 if isinstance(other, AbstractDataContainer):60 if self._is_dictionary and other._is_dictionary:61 return self._compare_dictionaries(other)62 elif self._is_list and other._is_list:63 return self._compare_lists(other)64 else:65 raise TypeError66 else:67 raise TypeError68 def __repr__(self):69 return 'AbstractDataContainer('f'container={self._container}, 'f'is_dictionary={self._is_dictionary}, ' \70 f'is_list={self._is_list})'71 def _compare_dictionaries(self, other):72 for key1 in other._container.keys():73 if key1 not in self._container or self._container[key1] != other._container[key1]:74 return False75 return True76 def _compare_lists(self, other):77 for item in other._container:78 if item not in self._container:79 return False80 return True81 def create_dictionary(self):82 self._container = {}83 self._is_dictionary = True84 def create_list(self):85 self._container = []86 self._is_list = True87 def append(self, key: str, value: Any):88 if self._is_dictionary:89 self._container[key] = value90 elif self._is_list:91 self._container.append([key, value])92 def get(self, key: str):93 if self._is_dictionary:94 return self._container.get(key, None)95 elif self._is_list:96 for item in self._container:97 if item[0] == key:98 return item[1]99 return None100 def get_values_as_list(self) -> list:101 if self._is_dictionary:102 return list(self._container.values())103 elif self._is_list:104 return [item[1] for item in self._container]105 def extend(self, other):106 if isinstance(other, AbstractDataContainer):107 if self._is_dictionary and other._is_dictionary:108 self._container.update(other._container)109 elif self._is_list and other._is_list:110 self._container.extend(other._container)111 else:112 raise TypeError113 else:114 raise TypeError115 def pop(self, key: str):116 if self._is_dictionary:117 return self._container.pop(key)118 elif self._is_list:119 item_position = -1120 for position, item in enumerate(self._container):121 if item[0] == key:122 item_position = position123 if item_position == -1:124 raise KeyError125 return self._container.pop(item_position)[1]126 def is_dictionary(self) -> bool:127 return self._is_dictionary128 def is_list(self) -> bool:...
image_like.py
Source:image_like.py
1import matplotlib.pyplot as plt2import numpy as np3from visualplot.blocks.base import Block4class Pcolormesh(Block):5 """ Animates a pcolormesh """6 def __init__(self, *args, ax=None, t_axis=0, **kwargs):7 """8 :param X : 1D or 2D np.ndarray, optional9 :param Y : 1D or 2D np.ndarray, optional10 :param C : list of 2D np.ndarray or a 3D np.ndarray11 :param ax : matplotlib.axes.Axes, optional12 The matplotlib axes to attach the block to.13 Defaults to matplotlib.pyplot.gca()14 :param t_axis : int, optional15 The axis of the array that represents time. Defaults to 0.16 No effect if C is a list.17 All other keyword arguments get passed to ``axis.pcolormesh``18 see :meth:`matplotlib.axes.Axes.pcolormesh` for details.19 """20 if len(args) == 1:21 self.C = args[0]22 self._arg_len = 123 elif len(args) == 3:24 self.X, self.Y, self.C = args25 self._arg_len = 326 if len(self.X.shape) not in [1, 2]:27 raise TypeError('X must be a 1D or 2D arrays')28 if len(self.Y.shape) not in [1, 2]:29 raise TypeError('Y must be a 1D or 2D arrays')30 else:31 raise TypeError('Illegal arguments to pcolormesh; see help(pcolormesh)')32 super().__init__(ax, t_axis)33 self._is_list = isinstance(self.C, list)34 self.C = np.asanyarray(self.C)35 slice_c = self._make_slice(0, 3)36 # replicate matplotlib logic for setting default shading value because37 # matplotlib resets the _shading member variable of the QuadMesh to "flat" after38 # interpolating X and Y to corner positions39 self.shading = kwargs.get('shading', plt.rcParams.get('pcolor.shading', 'flat'))40 Nx = self.X.shape[-1]41 Ny = self.Y.shape[0]42 if self.shading == 'auto':43 if (Ny, Nx) == self.C[slice_c].shape:44 self.shading = 'nearest'45 else:46 self.shading = 'flat'47 if self.shading == "flat" and ((Ny - 1, Nx - 1) == self.C[slice_c].shape):48 # Need to slice without the workaround in _update()49 self.shading = "flat_corner_grid"50 if self._arg_len == 1:51 self.quad = self.ax.pcolormesh(self.C[slice_c], **kwargs)52 elif self._arg_len == 3:53 self.quad = self.ax.pcolormesh(self.X, self.Y, self.C[slice_c], **kwargs)54 def _update(self, i):55 if self.shading == "flat":56 slice_c = self._make_pcolormesh_flat_slice(i, 3)57 self.quad.set_array(self.C[slice_c].ravel())58 else:59 slice_c = self._make_slice(i, 3)60 self.quad.set_array(self.C[slice_c])61 return self.quad62 def __len__(self):63 if self._is_list:64 return self.C.shape[0]65 return self.C.shape[self.t_axis]66 def _make_pcolormesh_flat_slice(self, i, dim):67 if self._is_list:68 return i69 slice_c = [slice(-1)] * 3 # weird thing to make animation work70 slice_c[self.t_axis] = i71 return tuple(slice_c)72class Imshow(Block):73 """ Animates a series of images """74 def __init__(self, images, ax=None, t_axis=0, **kwargs):75 """76 :param images: list of 2D/3D arrays, or a 3D or 4D array77 matplotlib considers arrays of the shape78 (n,m), (n,m,3), and (n,m,4) to be images.79 Images is either a list of arrays of those shapes,80 or an array of shape (T,n,m), (T,n,m,3), or (T,n,m,4)81 where T is the length of the time axis (assuming ``t_axis=0``).82 :param ax: matplotlib.axes.Axes, optional83 The matplotlib axes to attach the block to.84 Defaults to matplotlib.gca()85 :param t_axis: int, optional86 The axis of the array that represents time. Defaults to 0.87 No effect if images is a list88 This block accepts additional keyword arguments to be passed to89 :meth:`matplotlib.axes.Axes.imshow`90 """91 self.ims = np.asanyarray(images)92 super().__init__(ax, t_axis)93 self._is_list = isinstance(images, list)94 self._dim = len(self.ims.shape)95 slice_c = self._make_slice(0, self._dim)96 self.im = self.ax.imshow(self.ims[slice_c], **kwargs)97 def _update(self, i):98 slice_c = self._make_slice(i, self._dim)99 self.im.set_array(self.ims[slice_c])100 return self.im101 def __len__(self):102 if self._is_list:103 return self.ims.shape[0]...
restapi.py
Source:restapi.py
1# Copyright 2020 ACSONE SA/NV2# License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl).3import marshmallow4from apispec.ext.marshmallow.openapi import OpenAPIConverter5from marshmallow.exceptions import ValidationError6from odoo import _7from odoo.exceptions import UserError8from odoo.addons.base_rest import restapi9class Datamodel(restapi.RestMethodParam):10 def __init__(self, name, is_list=False, partial=None):11 """12 :param name: The datamodel name13 :param is_list: Should be set to True if params is a collection so that14 the object will be de/serialized from/to a list15 :param partial: Whether to ignore missing fields and not require16 any fields declared. Propagates down to ``Nested`` fields as well. If17 its value is an iterable, only missing fields listed in that iterable18 will be ignored. Use dot delimiters to specify nested fields.19 """20 self._name = name21 self._is_list = is_list22 self._partial = partial23 def from_params(self, service, params):24 ModelClass = service.env.datamodels[self._name]25 try:26 return ModelClass.load(27 params,28 many=self._is_list,29 unknown=marshmallow.EXCLUDE,30 partial=self._partial,31 )32 except ValidationError as ve:33 raise UserError(_("BadRequest %s") % ve.messages)34 def to_response(self, service, result):35 ModelClass = service.env.datamodels[self._name]36 if self._is_list:37 json = [i.dump() for i in result]38 else:39 json = result.dump()40 errors = ModelClass.validate(41 json, many=self._is_list, unknown=marshmallow.EXCLUDE42 )43 if errors:44 raise SystemError(_("Invalid Response %s") % errors)45 return json46 def to_openapi_query_parameters(self, service):47 converter = self._get_converter()48 schema = self._get_schema(service)49 return converter.schema2parameters(schema, location="query")50 # TODO, we should probably get the spec as parameters. That should51 # allows to add the definition of a schema only once into the specs52 # and use a reference to the schema into the parameters53 def to_openapi_requestbody(self, service):54 return {55 "content": {56 "application/json": {"schema": self.to_json_schema(service, "input")}57 }58 }59 def to_openapi_responses(self, service):60 return {61 "200": {62 "content": {63 "application/json": {64 "schema": self.to_json_schema(service, "output")65 }66 }67 }68 }69 def to_json_schema(self, service, direction):70 converter = self._get_converter()71 schema = self._get_schema(service)72 return converter.resolve_nested_schema(schema)73 def _get_schema(self, service):74 return service.env.datamodels[self._name].get_schema(many=self._is_list)75 def _get_converter(self):76 return OpenAPIConverter("3.0", self._schema_name_resolver, None)77 def _schema_name_resolver(self, schema):78 # name resolver used by the OpenapiConverter. always return None79 # to force nested schema definition80 return None...
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!