Best Python code snippet using localstack_python
parser.py
Source:parser.py  
...24    for e in element.iterfind(query):25        lib = Library.from_et(e)26        result[lib.ref] = lib27    return result28def _parse_map(element: Element, query: str, parser: Callable[[Element], T]) \29        -> Dict[str, T]:30    return {e.attrib['name']: parser(e) for e in element.iterfind(query)}31def _text_at(element: Element, query: str, none_ok: bool=True) \32        -> Optional[str]:33    found = element.find(query)34    if found is None:35        if none_ok:36            return None37        raise ValueError('Element not found for query {!r}'.format(query))38    return found.text39class Board:40    @classmethod41    def from_et(cls, element: Element) -> 'Board':42        raise NotImplementedError()43class Technology:44    def __init__(self, name: str, attributes: Dict[str, str]) -> None:45        self.name = name46        self.attributes = attributes47    @classmethod48    def from_et(cls, element: Element) -> 'Technology':49        name = element.attrib['name']50        attributes = _parse_map(element, './attribute',51                                lambda e: e.attrib['value'])52        return cls(name, attributes)53class Variant:54    def __init__(self, name: str, package: Optional[str],55                 technologies: Dict[str, Technology]) -> None:56        self.name = name57        self.package = package58        self.technologies = technologies59    @classmethod60    def from_et(cls, element: Element) -> 'Variant':61        name = element.attrib['name']62        package = element.attrib.get('package')63        techs = _parse_map(element, './technologies/technology',64                           Technology.from_et)65        return cls(name, package, techs)66class Device:67    def __init__(self, name: str, prefix: str, uservalue: bool,68                 description: Optional[str], gates: Dict[str, Element],69                 variants: Dict[str, Variant]) -> None:70        self.name = name71        self.prefix = prefix72        self.uservalue = uservalue73        self.description = description74        self.gates = gates75        self.variants = variants76    @classmethod77    def from_et(cls, element: Element) -> 'Device':78        name = element.attrib['name']79        prefix = element.attrib.get('prefix', '')80        uservalue = _parse_bool(element.attrib.get('uservalue', 'no'))81        description = _text_at(element, './description')82        gates = _parse_map(element, './gates/gate', lambda e: e)83        variants = {}84        for var_elt in element.iterfind('./devices/device'):85            var_name = var_elt.attrib.get('name', '')86            variants[var_name] = Variant.from_et(var_elt)87        return cls(name, prefix, uservalue, description, gates, variants)88class Library:89    def __init__(self, name: Optional[str], urn: str,90                 description: Optional[str],91                 packages: Dict[str, Element],92                 symbols: Dict[str, Element],93                 devices: Dict[str, Device]) -> None:94        self.name = name95        self.urn = urn96        self.description = description97        self.packages = packages98        self.symbols = symbols99        self.devices = devices100    @classmethod101    def from_et(cls, element: Element) -> 'Library':102        # Per DTD, name is only present within board/schematic files103        name = element.attrib.get('name')104        urn = element.attrib.get('urn', '')105        description = _text_at(element, './description')106        packages = _parse_map(element, './packages/package', lambda e: e)107        symbols = _parse_map(element, './symbols/symbol', lambda e: e)108        devices = _parse_map(element, './devicesets/deviceset',109                             Device.from_et)110        return cls(name, urn, description, packages, symbols, devices)111    @property112    def ref(self) -> LibraryRef:113        if self.name is None:114            raise AttributeError("Can't get ref of Library with no name")115        return LibraryRef(self.name, self.urn)116class Part:117    def __init__(self, name: str, library: str, library_urn: str, device: str,118                 variant: str, technology: str, value: Optional[str],119                 attributes: Dict[str, str]) -> None:120        self.name = name121        self.library = library122        self.library_urn = library_urn123        self.device = device124        self.variant = variant125        self.technology = technology126        self.value = value127        self.attributes = attributes128    @classmethod129    def from_et(cls, element: Element) -> 'Part':130        name = element.attrib['name']131        library = element.attrib['library']132        library_urn = element.attrib.get('library_urn', '')133        device = element.attrib['deviceset']134        variant = element.attrib['device']135        technology = element.attrib.get('technology', '')136        value = element.attrib.get('value')137        attributes = _parse_map(element, './attribute',138                                lambda e: e.attrib['value'])139        return cls(name, library, library_urn, device, variant, technology,140                   value, attributes)141    @property142    def library_ref(self) -> LibraryRef:143        return LibraryRef(self.library, self.library_urn)144class Schematic:145    def __init__(self, description: Optional[str],146                 libraries: Dict[LibraryRef, Library],147                 parts: Dict[str, Part]) -> None:148        self.description = description149        self.libraries = libraries150        self.parts = parts151    @classmethod152    def from_et(cls, element: Element) -> 'Schematic':153        description = _text_at(element, './description')154        libraries = _parse_library_map(element, './libraries/library')155        parts = _parse_map(element, './parts/part', Part.from_et)156        return cls(description, libraries, parts)157def load_file(source: TextIO) -> Tuple[str, ElementTree, Element]:158    et = parse_xml_et(source)159    if et.getroot().tag != 'eagle':160        raise ValueError('Not an EAGLE file')161    board = et.find('./drawing/board')162    if board:163        return 'board', et, board164    library = et.find('./drawing/library')165    if library:166        return 'library', et, library167    schematic = et.find('./drawing/schematic')168    if schematic:169        return 'schematic', et, schematic...wps.py
Source:wps.py  
1# Hastily made script to read WPS intermediate files2from __future__ import print_function3import struct4import numpy as np5# Number of bytes used at the start and end of a fortran record to6# indicate the record size7SIZE_BYTES = 48class WPSData(object):9    def __init__(self, ifv=None, hdate=None, xfcst=None, map_source=None,10                 field=None, units=None, desc=None, xlvl=None, nx=None,11                 ny=None, iproj=None, startloc=None, startlat=None,12                 startlon=None, deltalat=None, deltalon=None, nlats=None,13                 dx=None, dy=None, xlonc=None, truelat1=None, truelat2=None,14                 earth_radius=None, is_wind_earth_rel=None, slab=None):15        self.ifv = ifv16        self.hdate = hdate17        self.xfcst = xfcst18        self.map_source = map_source19        self.field = field20        self.units = units21        self.desc = desc22        self.xlvl = xlvl23        self.nx = nx24        self.ny = ny25        self.iproj = iproj26        self.startloc = startloc27        self.startlat = startlat28        self.startlon = startlon29        self.deltalat = deltalat30        self.deltalon = deltalon31        self.nlats = nlats32        self.dx = dx33        self.dy = dy34        self.xlonc = xlonc35        self.truelat1 = truelat136        self.truelat2 = truelat237        self.earth_radius = earth_radius38        self.is_wind_earth_rel = is_wind_earth_rel39        self.slab = slab40def _parse_record1(data):41    result = {}42    result["ifv"] = struct.unpack(">i", data)43    return result44def _parse_record2(data):45    result = {}46    parsed = struct.unpack(">24sf32s9s25s46sfiii", data)47    result["hdate"] = parsed[0]48    result["xfcst"] = parsed[1]49    result["map_source"] = parsed[2]50    result["field"] = parsed[3]51    result["units"] = parsed[4]52    result["desc"] = parsed[5]53    result["xlvl"] = parsed[6]54    result["nx"] = parsed[7]55    result["ny"] = parsed[8]56    result["iproj"] = parsed[9]57    return result58def _parse_record3(data, iproj):59    result = {}60    if iproj == 0:61        fmt = ">8sfffff"62        parsed = struct.unpack(fmt, data)63        result["startloc"] = parsed[0]64        result["startlat"] = parsed[1]65        result["startlon"] = parsed[2]66        result["deltalat"] = parsed[3]67        result["deltalon"] = parsed[4]68        result["earth_radius"] = parsed[5]69    elif iproj == 1:70        fmt = ">8sffffff"71        parsed = struct.unpack(fmt, data)72        result["startloc"] = parsed[0]73        result["startlat"] = parsed[1]74        result["startlon"] = parsed[2]75        result["dx"] = parsed[3]76        result["dy"] = parsed[4]77        result["truelat1"] = parsed[5]78        result["earth_radius"] = parsed[6]79    elif iproj == 3:80        fmt = ">8sffffffff"81        parsed = struct.unpack(fmt, data)82        result["startloc"] = parsed[0]83        result["startlat"] = parsed[1]84        result["startlon"] = parsed[2]85        result["dx"] = parsed[3]86        result["dy"] = parsed[4]87        result["xlonc"] = parsed[5]88        result["truelat1"] = parsed[6]89        result["truelat2"] = parsed[7]90        result["earth_radius"] = parsed[8]91    elif iproj == 4:92        fmt = ">8sfffff"93        parsed = struct.unpack(fmt, data)94        result["startloc"] = parsed[0]95        result["startlat"] = parsed[1]96        result["startlon"] = parsed[2]97        result["nlats"] = parsed[3]98        result["deltalon"] = parsed[4]99        result["earth_radius"] = parsed[5]100    elif iproj == 5:101        fmt = ">8sfffffff"102        parsed = struct.unpack(fmt, data)103        result["startloc"] = parsed[0]104        result["startlat"] = parsed[1]105        result["startlon"] = parsed[2]106        result["dx"] = parsed[3]107        result["dy"] = parsed[4]108        result["xlonc"] = parsed[5]109        result["truelat1"] = parsed[6]110        result["earth_radius"] = parsed[7]111    return result112def _parse_record4(data):113    result = {}114    result["is_wind_earth_rel"] = struct.unpack(">i", data)115    return result116def _parse_record5(data, nx, ny):117    result = {}118    size = nx * ny119    fmt = ">{}f".format(size)120    parsed = struct.unpack(fmt, data)121    arr = np.array(parsed, dtype=np.float32)122    result["slab"] = arr.reshape((nx, ny), order="F")123    return result124_PARSE_MAP = {0: _parse_record1,125              1: _parse_record2,126              2: _parse_record3,127              3: _parse_record4,128              4: _parse_record5}129def parse_record(record_idx, data, iproj=None, nx=None, ny=None):130    if record_idx == 0 or record_idx == 1 or record_idx == 3:131        return _PARSE_MAP[record_idx](data)132    elif record_idx == 2:133        return _PARSE_MAP[record_idx](data, iproj)134    elif record_idx == 4:135        return _PARSE_MAP[record_idx](data, nx, ny)136def read_wps(wps_file, field=None):137    with open(wps_file, "rb") as f:138        wps_params = {}139        record_list = []140        raw_data = f.read()141        record_size_idx = 0142        end_of_file_idx = len(raw_data) - 1143        while True:144            iproj = None145            nx = None146            ny = None147            keep_record = True148            for record_idx in range(5):149                # Each record has the size (in SIZE_BYTES bytes) at the150                # start and end of each record.  This might be compiler151                # dependent though, so this might need to be modified.152                # Also, the WPS files are stored big endian.153                record_size = struct.unpack(154                    ">i",155                    raw_data[record_size_idx: record_size_idx + SIZE_BYTES])156                record_start = record_size_idx + SIZE_BYTES157                record_end = record_start + record_size[0]158                record_data = raw_data[record_start:record_end]159                parsed_record = parse_record(record_idx, record_data, iproj,160                                             nx, ny)161                try:162                    field_name = parsed_record["field"].strip()163                except KeyError:164                    pass165                else:166                    if field is not None:167                        if field_name != field:168                            keep_record = False169                try:170                    iproj = parsed_record["iproj"]171                except KeyError:172                    pass173                try:174                    nx = parsed_record["nx"]175                except KeyError:176                    pass177                try:178                    ny = parsed_record["ny"]179                except KeyError:180                    pass181                wps_params.update(parsed_record)182                record_size_idx = record_end + SIZE_BYTES183            if keep_record:184                record_list.append(WPSData(**wps_params))185            # Repeat for all record slabs186            if record_end + SIZE_BYTES > end_of_file_idx:187                break...body_parser.py
Source:body_parser.py  
1#!/usr/bin/env python2__author__ = 'SLZ'3import json4def get_parser(file_type):5    return _parse_map.get(file_type,_default_parser)6_parse_map= {}7def _default_parser(data_in_bytes):8    return data_in_bytes9def _parse_to_json(data_in_bytes,encoding='utf-8'):10    return json.loads(data_in_bytes.decode(encoding))...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!!
