Process TRIPS EKB XML and return INDRA Statements.
327830
def trips_process_xml():
    """"""
    if request.method == 'OPTIONS':
        return {}
    response = request.body.read().decode('utf-8')
    body = json.loads(response)
    xml_str = body.get('xml_str')
    tp = trips.process_xml(xml_str)
    return _stmts_from_proc(tp)
953855
def from_xml(self, doc):
        """"""
        import xml.sax
        handler = DomainDumpParser(self)
        xml.sax.parse(doc, handler)
        return handler
774413
function handleGetTransports(sUri, sMethod, oData, mOptions, resolve, reject){
		if (sUri.match(/^\/sap\/bc\/lrep\/actions\/gettransports\//)){
			resolve({
				response: {
					"transports": [
						{
							"transportId": "U31K008488",
							"description": "The Ultimate Transport",
							"owner": "Fantasy Owner",
							"locked": true
						}
					],
					"localonly": false,
					"errorCode": ""
				}
			});
		}
	}
1094171
def parse_fast(xmlfile, element_name, attrnames, warn=False, optional=False):
    
    prefixedAttrnames = [_prefix_keyword(a, warn) for a in attrnames]
    if optional:
        pattern = ''.join(['<%s' % element_name] +
                          ['(\\s+%s="(?P<%s>[^"]*?)")?' % a for a in zip(attrnames, prefixedAttrnames)])
    else:
        pattern = '.*'.join(['<%s' % element_name] +
                            ['%s="([^"]*)"' % attr for attr in attrnames])
    Record = namedtuple(element_name, prefixedAttrnames)
    reprog = re.compile(pattern)
    for line in open(xmlfile):
        m = reprog.search(line)
        if m:
            if optional:
                yield Record(**m.groupdict())
            else:
                yield Record(*m.groups())
282374
def get_xml_parser(encoding=None):
    """"""
    parser = etree.ETCompatXMLParser(
        huge_tree=True,
        remove_comments=True,
        strip_cdata=False,
        remove_blank_text=True,
        resolve_entities=False,
        encoding=encoding
    )

    return parser
293011
def process_raw_data(cls, raw_data):
        """"""
        properties = raw_data.get("properties", {})

        raw_ip_configuration = properties.get("backendIPConfiguration", [])
        if isinstance(raw_ip_configuration, dict):
            raw_ip_configuration = [raw_ip_configuration]

        for raw_content in raw_ip_configuration:
            backend_ip_configuration = Resource.from_raw_data(raw_content)
            properties["backendIPConfiguration"] = backend_ip_configuration

        frontend_ip_configurations = []
        for raw_content in properties.get("frontendIPConfigurations", []):
            resource = Resource.from_raw_data(raw_content)
            frontend_ip_configurations.append(resource)
        properties["frontendIPConfigurations"] = frontend_ip_configurations

        return super(InboundNATRules, cls).process_raw_data(raw_data)
1172469
def process_raw_data(cls, raw_data):
        """"""
        properties = raw_data["properties"]

        ip_configurations = []
        raw_settings = properties.get("ipConfigurations", [])
        for raw_configuration in raw_settings:
            raw_configuration["parentResourceID"] = raw_data["resourceId"]
            ip_configuration = IPConfiguration.from_raw_data(raw_configuration)
            ip_configurations.append(ip_configuration)
        properties["ipConfigurations"] = ip_configurations

        raw_settings = properties.get("dnsSettings", {})
        dns_settings = DNSSettings.from_raw_data(raw_settings)
        properties["dnsSettings"] = dns_settings

        raw_settings = properties.get("portSettings", {})
        port_settings = PortSettings.from_raw_data(raw_settings)
        properties["portSettings"] = port_settings

        return super(NetworkInterfaces, cls).process_raw_data(raw_data)
26920
async def get_departures(
        self,
        station_id: str,
        direction_id: Optional[str] = None,
        max_journeys: int = 20,
        products: Optional[List[str]] = None,
    ) -> Dict[str, Any]:
        """"""
        self.station_id: str = station_id
        self.direction_id: str = direction_id

        self.max_journeys: int = max_journeys

        self.products_filter: str = _product_filter(products or ALL_PRODUCTS)

        base_url: str = _base_url()
        params: Dict[str, Union[str, int]] = {
            "selectDate": "today",
            "time": "now",
            "input": self.station_id,
            "maxJourneys": self.max_journeys,
            "boardType": "dep",
            "productsFilter": self.products_filter,
            "disableEquivs": "discard_nearby",
            "output": "xml",
            "start": "yes",
        }
        if self.direction_id:
            params["dirInput"] = self.direction_id

        url = base_url + urllib.parse.urlencode(params)

        try:
            with async_timeout.timeout(self._timeout):
                async with self._session.get(url) as response:
                    _LOGGER.debug(f"Response from RMV API: {response.status}")
                    xml = await response.read()
                    _LOGGER.debug(xml)
        except (asyncio.TimeoutError, aiohttp.ClientError):
            _LOGGER.error("Can not load data from RMV API")
            raise RMVtransportApiConnectionError()

        # pylint: disable=I1101
        try:
            self.obj = objectify.fromstring(xml)
        except (TypeError, etree.XMLSyntaxError):
            _LOGGER.debug(f"Get from string: {xml[:100]}")
            print(f"Get from string: {xml}")
            raise RMVtransportError()

        try:
            self.now = self.current_time()
            self.station = self._station()
        except (TypeError, AttributeError):
            _LOGGER.debug(
                f"Time/Station TypeError or AttributeError {objectify.dump(self.obj)}"
            )
            raise RMVtransportError()

        self.journeys.clear()
        try:
            for journey in self.obj.SBRes.JourneyList.Journey:
                self.journeys.append(RMVJourney(journey, self.now))
        except AttributeError:
            _LOGGER.debug(f"Extract journeys: {objectify.dump(self.obj.SBRes)}")
            raise RMVtransportError()

        return self.data()
206365
def _roads_extract(resp):
    """"""

    try:
        j = resp.json()
    except:
        if resp.status_code != 200:
            raise googlemaps.exceptions.HTTPError(resp.status_code)

        raise googlemaps.exceptions.ApiError("UNKNOWN_ERROR",
                                             "Received a malformed response.")

    if "error" in j:
        error = j["error"]
        status = error["status"]

        if status == "RESOURCE_EXHAUSTED":
            raise googlemaps.exceptions._OverQueryLimit(status,
                                                        error.get("message"))

        raise googlemaps.exceptions.ApiError(status, error.get("message"))

    if resp.status_code != 200:
        raise googlemaps.exceptions.HTTPError(resp.status_code)

    return j
446084
def process_raw_data(cls, raw_data):
        """"""
        properties = raw_data.get("properties", {})

        frontend_ip_configurations = []
        for raw_content in properties.get("frontendIPConfigurations", []):
            resource = Resource.from_raw_data(raw_content)
            frontend_ip_configurations.append(resource)
        properties["frontendIPConfigurations"] = frontend_ip_configurations

        raw_content = properties.get("backendAddressPool", None)
        if raw_content is not None:
            resource = Resource.from_raw_data(raw_content)
            properties["backendAddressPool"] = resource

        raw_content = properties.get("probe", None)
        if raw_content is not None:
            resource = Resource.from_raw_data(raw_content)
            properties["probe"] = resource

        return super(LoadBalancingRules, cls).process_raw_data(raw_data)
1339627
def handle_data(self, data):
        '''
            
        '''
        if data:
            inTag = self._inTag
            if len(inTag) > 0:
                if inTag[-1].tagName not in PRESERVE_CONTENTS_TAGS:
                    data = data.replace('\t', ' ').strip('\r\n')
                    if data.startswith(' '):
                        data = ' ' + data.lstrip()
                    if data.endswith(' '):
                        data = data.rstrip() + ' '
                inTag[-1].appendText(data)
            elif data.strip():
                # Must be text prior to or after root node
                raise MultipleRootNodeException()
412466
def _finalize_db(self):
        """"""
        for k, v in self._els_idxed.items():
            self._els_idxed[k] = dict(v)
        self._els_idxed = dict(self._els_idxed)
928167
def parse_xml(data, handle_units):
    """"""
    root = ET.fromstring(data)
    return squish(parse_xml_dataset(root, handle_units))
133719
def process_raw_data(cls, raw_data):
        """"""
        properties = raw_data["properties"]

        ip_pools = []
        for raw_content in properties.get("ipPools", []):
            raw_content["parentResourceID"] = raw_data["resourceId"]
            raw_content["grandParentResourceID"] = raw_data["parentResourceID"]
            ip_pools.append(IPPools.from_raw_data(raw_content))
        properties["ipPools"] = ip_pools

        ip_configurations = []
        for raw_content in properties.get("ipConfigurations", []):
            resource = Resource.from_raw_data(raw_content)
            ip_configurations.append(resource)
        properties["ipConfigurations"] = ip_configurations

        network_interfaces = []
        for raw_content in properties.get("networkInterfaces", []):
            resource = Resource.from_raw_data(raw_content)
            network_interfaces.append(resource)
        properties["networkInterfaces"] = network_interfaces

        return super(LogicalSubnetworks, cls).process_raw_data(raw_data)
1280556
def records(self):
        """"""
        compounds = ModelList()
        seen_labels = set()
        # Ensure no control characters are sent to a parser (need to be XML compatible)
        tagged_tokens = [(CONTROL_RE.sub('', token), tag) for token, tag in self.tagged_tokens]
        for parser in self.parsers:
            for record in parser.parse(tagged_tokens):
                p = record.serialize()
                if not p:  # TODO: Potential performance issues?
                    continue
                # Skip duplicate records
                if record in compounds:
                    continue
                # Skip just labels that have already been seen (bit of a hack)
                if all(k in {'labels', 'roles'} for k in p.keys()) and set(record.labels).issubset(seen_labels):
                    continue
                seen_labels.update(record.labels)
                compounds.append(record)
        return compounds
1112111
def process_raw_data(cls, raw_data):
        """"""
        properties = raw_data["properties"]

        ip_configurations = []
        for raw_content in properties.get("ipConfigurations", []):
            resource = Resource.from_raw_data(raw_content)
            ip_configurations.append(resource)
        properties["ipConfigurations"] = ip_configurations

        subnetworks = []
        for raw_subnet in properties.get("subnets", []):
            subnetworks.append(Resource.from_raw_data(raw_subnet))
        properties["subnets"] = subnetworks

        acl_rules = []
        for raw_rule in properties.get("aclRules", []):
            raw_rule["parentResourceID"] = raw_data["resourceId"]
            acl_rules.append(ACLRules.from_raw_data(raw_rule))
        properties["aclRules"] = acl_rules

        return super(AccessControlLists, cls).process_raw_data(raw_data)
547470
def handle_json_GET_stoptrips(self, params):
    """"""
    schedule = self.server.schedule
    stop = schedule.GetStop(params.get('stop', None))
    time = int(params.get('time', 0))
    date = params.get('date', "")

    time_trips = stop.GetStopTimeTrips(schedule)
    time_trips.sort()  # OPT: use bisect.insort to make this O(N*ln(N)) -> O(N)
    # Keep the first 5 after param 'time'.
    # Need make a tuple to find correct bisect point
    time_trips = time_trips[bisect.bisect_left(time_trips, (time, 0)):]
    time_trips = time_trips[:5]
    # TODO: combine times for a route to show next 2 departure times
    result = []
    for time, (trip, index), tp in time_trips:
      service_id = trip.service_id
      service_period = schedule.GetServicePeriod(service_id)
      if date and not service_period.IsActiveOn(date):
        continue
      headsign = None
      # Find the most recent headsign from the StopTime objects
      for stoptime in trip.GetStopTimes()[index::-1]:
        if stoptime.stop_headsign:
          headsign = stoptime.stop_headsign
          break
      # If stop_headsign isn't found, look for a trip_headsign
      if not headsign:
        headsign = trip.trip_headsign
      route = schedule.GetRoute(trip.route_id)
      trip_name = ''
      if route.route_short_name:
        trip_name += route.route_short_name
      if route.route_long_name:
        if len(trip_name):
          trip_name += " - "
        trip_name += route.route_long_name
      if headsign:
        trip_name += " (Direction: %s)" % headsign

      result.append((time, (trip.trip_id, trip_name, trip.service_id), tp))
    return result