Best Python code snippet using assertpy_python
matprop.py
Source:matprop.py  
1# -*- coding: utf-8 -*-2"""3Created on Mon Sep 18 08:27:22 201745@author: Jaywan Chung6"""78import numpy as np9from scipy.interpolate import interp1d1011from .measured import Measured121314class MatProp:15    """Manage Material Properties (TEPs).1617    The class is initialized by property name, metric unit, and the raw data.18    """1920    INTERP_LINEAR = 'linear_wo_extrap'21    OPT_INTERP = 'interp'22    OPT_EXTEND_LEFT_TO = 'extend_left_to'23    OPT_EXTEND_RIGHT_TO = 'extend_right_to'24    OPT_EXTEND_LEFT_BY = 'extend_left_by'25    OPT_EXTEND_RIGHT_BY = 'extend_right_by'26    default_interp_opt = {OPT_INTERP:INTERP_LINEAR,27                          OPT_EXTEND_LEFT_TO:None,28                          OPT_EXTEND_RIGHT_TO:None,29                          OPT_EXTEND_LEFT_BY:None,30                          OPT_EXTEND_RIGHT_BY:None}31    32    def __init__(self,names,units,raw_data,\33                 interp_opt=default_interp_opt):34        if len(names) != len(units):35            raise ValueError("'names' and 'units' arguments must have the same lengths.")36            37        self.__names = tuple(names)38        self.__units = tuple(units)39        self.__raw_data = tuple( [tuple(item) for item in raw_data] )40        self.set_interp_opt(interp_opt)4142        pass43    44    def __call__(self,xs):45        xs = to_real_values(xs,self.__units[:-1])46        return self.__interp_func(xs)47        pass48    49    def __repr__(self):50        repr_str  = 'MatProp(names=' + str(self.__names) + ',\n\t'51        repr_str += 'units=' + str(self.__units) + ',\n\t'52        repr_str += 'raw_data=' + str(self.__raw_data) + ',\n\t'53        repr_str += "interp_opt=" + str(self.__interp_opt) +")"54        return repr_str55    56    def set_interp_opt(self,interp_opt):57        if len(self.__names) == 2:58            x = np.array([item[0] for item in self.__raw_data])59            y = np.array([item[1] for item in self.__raw_data])60            x_at_left_end = np.min(x)61            x_at_right_end = np.max(x)62            y_at_left_end = y[np.argmin(x)]63            y_at_right_end = y[np.argmax(x)]64            if interp_opt.get(MatProp.OPT_EXTEND_LEFT_TO) is not None:65                extended_left_x = interp_opt[MatProp.OPT_EXTEND_LEFT_TO]66                x = np.append(x,[extended_left_x])67                y = np.append(y,[y_at_left_end])68            elif interp_opt.get(MatProp.OPT_EXTEND_LEFT_BY) is not None:69                extended_left_x = x_at_left_end - interp_opt[MatProp.OPT_EXTEND_LEFT_BY]70                x = np.append(x,[extended_left_x])71                y = np.append(y,[y_at_left_end])72            if interp_opt.get(MatProp.OPT_EXTEND_RIGHT_TO) is not None:73                extended_right_x = interp_opt[MatProp.OPT_EXTEND_RIGHT_TO]74                x = np.append(x,[extended_right_x])75                y = np.append(y,[y_at_right_end])76            elif interp_opt.get(MatProp.OPT_EXTEND_RIGHT_BY) is not None:77                extended_right_x = x_at_right_end + interp_opt[MatProp.OPT_EXTEND_RIGHT_BY]78                x = np.append(x,[extended_right_x])79                y = np.append(y,[y_at_right_end])8081            if interp_opt[MatProp.OPT_INTERP] == MatProp.INTERP_LINEAR:82                x = tuple( x )83                y = tuple( y )84                #self.__interp_func = interp1d(x,y,kind='linear')85                self.__interp_func = interp1d(x,y,kind='linear')86            else:87                raise ValueError("Invalid interpolation method.")88        else:89            raise ValueError("Sorry we do not support 2D or more dimensions for now.")90        self.__interp_opt = interp_opt.copy()            91    92    def unit(self):   # unit of the output material property93        return self.__units[-1]94    95    def input_units(self):96        return self.__units[:-1]97    98    def names(self):99        return self.__names100    101    def units(self):102        return self.__units103    104    def raw_data(self):105        return self.__raw_data106    107    def raw_input(self,col=0):108        result = []109        for row in self.__raw_data:110            result.append(row[col])111        return tuple(result)112    113    def raw_output(self):114        return self.raw_input(col=-1)115    116    def raw_interval(self,col=0):117        raw = self.raw_input(col)118        return (min(raw), max(raw))119    120    def has_structure(self,names,units):121        if list(names) == list(self.__names):122            if list(units) == list(self.__units):123                return True124        else:125            return False126        127    def to_units(self,new_units):128        rows = self.__raw_data129        units = self.__units130        # compute new raw_data131        is_not_iterable = False132        try:133            _ = iter(rows)134        except TypeError:135            # not a iterable136            rows = (rows,)137            is_not_iterable = True138        try:139            _ = iter(units)140        except TypeError:141            units = (units,)142        result = []143        for row in rows:144            row_item = []145            is_a_single_xp = False146            try:147                _ = iter(row)148            except TypeError:149                row = (row,)150                is_a_single_xp = True151            for idx,col in enumerate(row):152                prev_unit = units[idx]153                new_unit = new_units[idx]154                # exception handling: temperature conversion155                temperature = ['K','degC','°C','degF','°F']156                if (prev_unit in temperature) and (new_unit in temperature):157                    if isinstance(col,Measured):158                        col = col.value159                    col = temperature_conversion(col,prev_unit,new_unit)160                    prev_unit = new_unit161                # usual cases162                if isinstance(col,Measured):163                    col = col.to(new_unit).drop_zero_exponent().value  # unit conversion164                else:165                    col = Measured(col,prev_unit).to(new_unit).drop_zero_exponent().value166                row_item.append(float(col))167            if is_a_single_xp:168                result.append(row_item[0])169            else:170                result.append(tuple(row_item))171        if is_not_iterable:172            result = result[0]173        else:174            result = tuple(result)175        # return the result as a MatProp176        return MatProp(self.__names,new_units,result,interp_opt=self.__interp_opt)177        178    179def to_real_values(xs,units):180    is_not_iterable = False181    try:182        _ = iter(xs)183    except TypeError:184        # not a iterable185        xs = (xs,)186        is_not_iterable = True187    try:188        _ = iter(units)189    except TypeError:190        units = (units,)191    result = []192    for row in xs:193        row_item = []194        is_a_single_xp = False195        try:196            _ = iter(row)197        except TypeError:198            row = (row,)199            is_a_single_xp = True200        for idx,col in enumerate(row):201            default_unit = units[idx]202            if isinstance(col,Measured):203                col = col.to(default_unit).drop_zero_exponent().value  # unit conversion204            row_item.append(float(col))205        if is_a_single_xp:206            result.append(row_item[0])207        else:208            result.append(tuple(row_item))209    if is_not_iterable:210        result = result[0]211    else:212        result = tuple(result)213    return result214215216def temperature_conversion(value,unit,new_unit):217    if unit in ['degF','°F']:218        if new_unit in ['degF','°F']:219            return value220        elif new_unit in ['degC','°F']:221            return (value-32)*5/9222        elif new_unit == 'K':223            return (value-32)*5/9+273.15224    elif unit in ['degC','°C']:225        if new_unit in ['degF','°F']:226            return (value*9/5)+32227        elif new_unit in ['degC','°C']:228            return value229        elif new_unit == 'K':230            return value+273.15231    elif unit == 'K':232        if new_unit in ['degF','°F']:233            return (value-273.15)*9/5+32234        elif new_unit in ['degC','°C']:235            return value-273.15236        elif new_unit == 'K':237            return value
...request_objects.py
Source:request_objects.py  
...22        invalid_req = InvalidRequestObject()23        if is_empty(input_dict):24            invalid_req.add_error('command', 'Empty dict')25            return invalid_req26        if is_not_iterable(input_dict):27            invalid_req.add_error('command', 'Is not iterable')28            return invalid_req29        if cls.__is_incomplete(input_dict):30            invalid_req.add_error('command', 'Is incomplete')31            return invalid_req32        if amount_is_negative(input_dict):33            invalid_req.add_error('command: amount', 'Is negative')34            return invalid_req35        return OrderPlaceMktRequestObject(command=input_dict.get('command', None))36    def __is_incomplete(input_dict):37        return not all(k in input_dict['command'] for k in ("stock_name", "amount"))38    def __nonzero__(self):39        return True40class OrderPlaceLmtRequestObject(ValidRequestObject):41    """Request object corresponding to BUY/SELL LMT command42    Arguments:43        command(dict): Dictionary with BUY/SELL LMT command info44    """45    def __init__(self, command):46        self.command = command47    @classmethod48    def from_dict(cls, input_dict):49        """Generate request from BUY/SELL LMT command dictionary50        Arguments:51            input_dict(dict): BUY/SELL LMT command dictionary with command info52        Returns:53            OrderPlaceLmtRequestObject: Valid request object iff command is correct54            InvalidRequestObject: Invalid request iff command is incorrect55        """56        invalid_req = InvalidRequestObject()57        if is_empty(input_dict):58            invalid_req.add_error('command', 'Empty dict')59            return invalid_req60        if is_not_iterable(input_dict):61            invalid_req.add_error('command', 'Is not iterable')62            return invalid_req63        if cls.__is_incomplete(input_dict):64            invalid_req.add_error('command', 'Is incomplete')65            return invalid_req66        if price_is_negative(input_dict):67            invalid_req.add_error('command: price', 'Is negative')68            return invalid_req69        if amount_is_negative(input_dict):70            invalid_req.add_error('command: amount', 'Is negative')71            return invalid_req72        return OrderPlaceLmtRequestObject(command=input_dict.get('command', None))73    def __is_incomplete(input_dict):74        return not all(k in input_dict['command'] for k in ("stock_name",75                                                            "price",76                                                            "amount"))77    def __nonzero__(self):78        return True79class OrderViewRequestObject(ValidRequestObject):80    """Request object corresponding to VIEW ORDERS command81    Arguments:82        command(dict): Dictionary with VIEW ORDERS command info83    """84    def __init__(self, command):85        self.command = command86    @classmethod87    def from_dict(cls, input_dict):88        """Generate request from VIEW ORDERS command dictionary89        Arguments:90            input_dict(dict): VIEW ORDERS command dictionary with command info91        Returns:92            OrderViewRequestObject: Valid request object iff command is correct93            InvalidRequestObject: Invalid request iff command is incorrect94        """95        invalid_req = InvalidRequestObject()96        if cls.__is_empty(input_dict):97            invalid_req.add_error('command', 'Empty dict')98            return invalid_req99        if cls.__is_not_iterable(input_dict):100            invalid_req.add_error('command', 'Is not iterable')101            return invalid_req102        if cls.__wrong_command(input_dict):103            invalid_req.add_error('command', 'Must be VIEW ORDERS')104            return invalid_req105        return OrderViewRequestObject(command=input_dict['command'])106    def __is_empty(input_dict):107        return 'command' not in input_dict.keys()108    def __is_not_iterable(input_dict):109        return ('command' in input_dict.keys()110                and not isinstance(input_dict, collections.Mapping))111    def __wrong_command(input_dict):112        return input_dict['command'] != "VIEW ORDERS"113    def __nonzero__(self):114        return True115class OrderQuoteRequestObject(ValidRequestObject):116    """Request object corresponding to QUOTE command117    Arguments:118        stock_name(str): Name of stock to quote119    """120    def __init__(self, stock_name):121        self.stock_name = stock_name122    @classmethod123    def from_dict(cls, input_dict):124        """Generate request from QUOTE command dictionary125        Arguments:126            input_dict(dict): QUOTE command dictionary with command info127        Returns:128            OrderPlaceLmtRequestObject: Valid request object iff command is correct129            InvalidRequestObject: Invalid request iff command is incorrect130        """131        invalid_req = InvalidRequestObject()132        if is_empty(input_dict):133            invalid_req.add_error('command', 'Empty dict')134            return invalid_req135        if is_not_iterable(input_dict):136            invalid_req.add_error('command', 'Is not iterable')137            return invalid_req138        if cls.__no_stock_name(input_dict):139            invalid_req.add_error('command', 'Stock name not defined')140            return invalid_req141        return OrderQuoteRequestObject(stock_name=input_dict['command']['stock_name'])142    def __no_stock_name(input_dict):143        return "stock_name" not in input_dict['command'].keys()144    def __nonzero__(self):145        return True146def is_empty(input_dict):147    return 'command' not in input_dict148def is_not_iterable(input_dict):149    return ('command' in input_dict150            and not isinstance(input_dict['command'], collections.Mapping))151def amount_is_negative(input_dict):152    return input_dict['command']['amount'] <= 0153def price_is_negative(input_dict):...nesting_structure_comparison.py
Source:nesting_structure_comparison.py  
1import collections2is_not_iterable = lambda e: not isinstance(e, collections.Iterable) or isinstance(e, type('string'))3is_iterable = lambda e: not is_not_iterable(e)4is_same_kind = lambda this, that: type(this) == type(that)5is_same_length = lambda this, that: len(this) == len(that)6def same_structure_as(this, that):7    if is_iterable(this) and is_iterable(that):8        return is_same_kind(this, that) and is_same_length(this, that) \9               and all(map(lambda x: same_structure_as(x[0], x[1]), zip(this, that)))...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!!
