Parse a tag-length-value style beacon packet.
965989
def parse_ltv_packet(packet):
    """"""
    try:
        frame = LTVFrame.parse(packet)
        for ltv in frame:
            if ltv['type'] == SERVICE_DATA_TYPE:
                data = ltv['value']

                if data["service_identifier"] == EDDYSTONE_UUID:
                    return parse_eddystone_service_data(data)

                elif data["service_identifier"] == ESTIMOTE_UUID:
                    return parse_estimote_service_data(data)

    except ConstructError:
        return None

    return None
569584
def _parse_user_id(stream, packet_type='user_id'):
    """"""
    value = stream.read()
    to_hash = b'\xb4' + util.prefix_len('>L', value)
    return {'type': packet_type, 'value': value, '_to_hash': to_hash}
216709
def _tag(val, tag):
        """"""
        if isinstance(val, str):
            val = bytes(val, 'utf-8')
        return (bytes('<' + tag + '>', 'utf-8') + val +
                bytes('</' + tag + '>', 'utf-8'))
1076773
def __parse_tag(self, tag, count):
        """"""

        fileobj = cBytesIO(tag)

        for i in xrange(count):
            tag_data = fileobj.read(8)
            # someone writes wrong item counts
            if not tag_data:
                break
            if len(tag_data) != 8:
                raise error
            size = cdata.uint32_le(tag_data[:4])
            flags = cdata.uint32_le(tag_data[4:8])

            # Bits 1 and 2 bits are flags, 0-3
            # Bit 0 is read/write flag, ignored
            kind = (flags & 6) >> 1
            if kind == 3:
                raise APEBadItemError("value type must be 0, 1, or 2")

            key = value = fileobj.read(1)
            if not key:
                raise APEBadItemError
            while key[-1:] != b'\x00' and value:
                value = fileobj.read(1)
                if not value:
                    raise APEBadItemError
                key += value
            if key[-1:] == b"\x00":
                key = key[:-1]

            if PY3:
                try:
                    key = key.decode("ascii")
                except UnicodeError as err:
                    reraise(APEBadItemError, err, sys.exc_info()[2])
            value = fileobj.read(size)
            if len(value) != size:
                raise APEBadItemError

            value = _get_value_type(kind)._new(value)

            self[key] = value
670479
def parse_content_type(header):
    """"""
    typ = subtyp = None; options = {}
    typ, pos = expect_re(re_token, header, 0)
    _, pos = expect_lit('/', header, pos)
    subtyp, pos = expect_re(re_token, header, pos)
    ctype = header[:pos] if subtyp else ''
    while pos < len(header):
        _, pos = accept_ws(header, pos)
        _, pos = expect_lit(';', header, pos)
        _, pos = accept_ws(header, pos)
        name, pos = expect_re(re_token, header, pos)
        _, pos = expect_lit('=', header, pos)
        char = lookahead(header, pos)
        if char == '"':
            value, pos = expect_re(re_qstring, header, pos)
            value = re_qpair.sub('\\1', value)
        elif char:
            value, pos = expect_re(re_token, header, pos)
        if name and value is not None:
            options[name] = value
    return ctype, options
783813
def _parse(self, stream, context, path):
        """"""
        start = stream.tell()
        read_bytes = ""
        if self.max_length:
            read_bytes = stream.read(self.max_length)
        else:
            read_bytes = stream.read()
        skip = read_bytes.find(self.find) + len(self.find)
        stream.seek(start + skip)
        return skip
717136
def _parse_pubkey(stream, packet_type='pubkey'):
    """"""
    p = {'type': packet_type}
    packet = io.BytesIO()
    with stream.capture(packet):
        p['version'] = stream.readfmt('B')
        p['created'] = stream.readfmt('>L')
        p['algo'] = stream.readfmt('B')
        if p['algo'] in ECDSA_ALGO_IDS:
            log.debug('parsing elliptic curve key')
            # https://tools.ietf.org/html/rfc6637#section-11
            oid_size = stream.readfmt('B')
            oid = stream.read(oid_size)
            assert oid in SUPPORTED_CURVES, util.hexlify(oid)
            p['curve_oid'] = oid

            mpi = parse_mpi(stream)
            log.debug('mpi: %x (%d bits)', mpi, mpi.bit_length())
            leftover = stream.read()
            if leftover:
                leftover = io.BytesIO(leftover)
                # https://tools.ietf.org/html/rfc6637#section-8
                # should be b'\x03\x01\x08\x07': SHA256 + AES128
                size, = util.readfmt(leftover, 'B')
                p['kdf'] = leftover.read(size)
                p['secret'] = leftover.read()

            parse_func, keygrip_func = SUPPORTED_CURVES[oid]
            keygrip = keygrip_func(parse_func(mpi))
            log.debug('keygrip: %s', util.hexlify(keygrip))
            p['keygrip'] = keygrip

        elif p['algo'] == DSA_ALGO_ID:
            parse_mpis(stream, n=4)  # DSA keys are not supported
        elif p['algo'] == ELGAMAL_ALGO_ID:
            parse_mpis(stream, n=3)  # ElGamal keys are not supported
        else:  # assume RSA
            parse_mpis(stream, n=2)  # RSA keys are not supported
        assert not stream.read()

    # https://tools.ietf.org/html/rfc4880#section-12.2
    packet_data = packet.getvalue()
    data_to_hash = (b'\x99' + struct.pack('>H', len(packet_data)) +
                    packet_data)
    p['key_id'] = hashlib.sha1(data_to_hash).digest()[-8:]
    p['_to_hash'] = data_to_hash
    log.debug('key ID: %s', util.hexlify(p['key_id']))
    return p
67414
def _parse(self, raw, next_cls):
        '''
        
        '''
        if next_cls is None:
            from switchyard.lib.packet import Ethernet
            next_cls = Ethernet

        self._headers = []
        while issubclass(next_cls, PacketHeaderBase):
            packet_header_obj = next_cls()
            raw = packet_header_obj.from_bytes(raw)
            self.add_header(packet_header_obj)
            next_cls = packet_header_obj.next_header_class()
            if next_cls is None:
                break
        if raw:
            self.add_header(RawPacketContents(raw))
658273
def parse(buf)
      return nil if buf.size < 9
      frame = read_common_header(buf)
      return nil if buf.size < 9 + frame[:length]

      fail ProtocolError, 'payload too large' if frame[:length] > DEFAULT_MAX_FRAME_SIZE

      buf.read(9)
      payload = buf.read(frame[:length])

      # Implementations MUST discard frames
      # that have unknown or unsupported types.
      # - http://tools.ietf.org/html/draft-ietf-httpbis-http2-16#section-5.5
      return nil if frame[:type].nil?

      # Process padding
      padlen = 0
      if FRAME_TYPES_WITH_PADDING.include?(frame[:type])
        padded = frame[:flags].include?(:padded)
        if padded
          padlen = payload.read(1).unpack(UINT8).first
          frame[:padding] = padlen + 1
          fail ProtocolError, 'padding too long' if padlen > payload.bytesize
          payload.slice!(-padlen, padlen) if padlen > 0
          frame[:length] -= frame[:padding]
          frame[:flags].delete(:padded)
        end
      end

      case frame[:type]
      when :data
        frame[:payload] = payload.read(frame[:length])
      when :headers
        if frame[:flags].include? :priority
          e_sd = payload.read_uint32
          frame[:stream_dependency] = e_sd & RBIT
          frame[:exclusive] = (e_sd & EBIT) != 0
          frame[:weight] = payload.getbyte + 1
        end
        frame[:payload] = payload.read(frame[:length])
      when :priority
        e_sd = payload.read_uint32
        frame[:stream_dependency] = e_sd & RBIT
        frame[:exclusive] = (e_sd & EBIT) != 0
        frame[:weight] = payload.getbyte + 1
      when :rst_stream
        frame[:error] = unpack_error payload.read_uint32

      when :settings
        # NOTE: frame[:length] might not match the number of frame[:payload]
        # because unknown extensions are ignored.
        frame[:payload] = []
        unless (frame[:length] % 6).zero?
          fail ProtocolError, 'Invalid settings payload length'
        end

        if (frame[:stream]).nonzero?
          fail ProtocolError, "Invalid stream ID (#{frame[:stream]})"
        end

        (frame[:length] / 6).times do
          id  = payload.read(2).unpack(UINT16).first
          val = payload.read_uint32

          # Unsupported or unrecognized settings MUST be ignored.
          # Here we send it along.
          name, _ = DEFINED_SETTINGS.find { |_name, v| v == id }
          frame[:payload] << [name, val] if name
        end
      when :push_promise
        frame[:promise_stream] = payload.read_uint32 & RBIT
        frame[:payload] = payload.read(frame[:length])
      when :ping
        frame[:payload] = payload.read(frame[:length])
      when :goaway
        frame[:last_stream] = payload.read_uint32 & RBIT
        frame[:error] = unpack_error payload.read_uint32

        size = frame[:length] - 8 # for last_stream and error
        frame[:payload] = payload.read(size) if size > 0
      when :window_update
        frame[:increment] = payload.read_uint32 & RBIT
      when :continuation
        frame[:payload] = payload.read(frame[:length])
      when :altsvc
        frame[:max_age], frame[:port] = payload.read(6).unpack(UINT32 + UINT16)

        len = payload.getbyte
        frame[:proto] = payload.read(len) if len > 0

        len = payload.getbyte
        frame[:host] = payload.read(len) if len > 0

        frame[:origin] = payload.read(payload.size) if payload.size > 0
        # else # Unknown frame type is explicitly allowed
      end

      frame
    end
1298371
def pad(text, length):
    """"""
    text_length = wcswidth(text)

    if text_length < length:
        return text + ' ' * (length - text_length)

    return text
481600
def _parse_tag(self):
        """"""
        reset = self._head
        self._head += 1
        try:
            tag = self._really_parse_tag()
        except BadRoute:
            self._head = reset
            self._emit_text("<")
        else:
            self._emit_all(tag)
411850
def coarse_tag_str(pos_seq):
	""""""
	global tag2coarse
	tags = [tag2coarse.get(tag, 'O') for tag in pos_seq]
	return ''.join(tags)
101359
def extract_padding(self, data):
        """"""

        if self.plen == 0 and self.nh == 0 and len(data) >= 8:
            # Extract Hop-by-Hop extension length
            hbh_len = orb(data[1])
            hbh_len = 8 + hbh_len * 8

            # Extract length from the Jumbogram option
            # Note: the following algorithm take advantage of the Jumbo option
            #        mandatory alignment (4n + 2, RFC2675 Section 2)
            jumbo_len = None
            idx = 0
            offset = 4 * idx + 2
            while offset <= len(data):
                opt_type = orb(data[offset])
                if opt_type == 0xc2:  # Jumbo option
                    jumbo_len = struct.unpack("I", data[offset + 2:offset + 2 + 4])[0]  # noqa: E501
                    break
                offset = 4 * idx + 2
                idx += 1

            if jumbo_len is None:
                warning("Scapy did not find a Jumbo option")
                jumbo_len = 0

            tmp_len = hbh_len + jumbo_len
        else:
            tmp_len = self.plen

        return data[:tmp_len], data[tmp_len:]
377043
function parsePacket(packet) {
  var parsedPacket = loopPacket.parse(packet);
  var convertedPacket = {};
  for(var property in parsedPacket) {
    var value = parsedPacket[property];
    switch (property){
      case "BarTrend":
        value = _convertBarTrend(value);
        break;
      case "TempIn":
      case "TempOut":
        value = Convert(value/10).from('F').to('C');
        break;
      case "BatteryVolts":
	value = _convertToVoltage(value);
	break;	
      case "ForecastRuleNo":
	value = _getForecastString(value);
	break;
      case "ForecastIcon":
	value = _parseIconValue(value);
	break;
      case "SunRise":
      case "SunSet":
	value = _convertTime(value);
        break;
      case "WindSpeed":
      case "WindSpeed10Min":
	value = Convert(value).from('m/h').to('m/s');
	break;
	
    }
    convertedPacket[property] = value;

  }

  return parsedPacket;
}
164749
def _parse_byte_data(self, byte_data):
        """"""
        chunks = unpack('<iiiii', byte_data[:self.size])
        det_id, run, time_slice, time_stamp, ticks = chunks
        self.det_id = det_id
        self.run = run
        self.time_slice = time_slice
        self.time_stamp = time_stamp
        self.ticks = ticks
13816
long readTagAndSet(long bucketIndex, int posInBucket, long newTag) {
		long tagStartIdx = getTagOffset(bucketIndex, posInBucket);
		long tag = 0;
		long tagEndIdx = tagStartIdx + bitsPerTag;
		int tagPos = 0;
		for (long i = tagStartIdx; i < tagEndIdx; i++) {
			if ((newTag & (1L << tagPos)) != 0) {
				if (memBlock.getAndSet(i)) {
					tag |= 1 << tagPos;
				}
			} else {
				if (memBlock.getAndClear(i)) {
					tag |= 1 << tagPos;
				}
			}
			tagPos++;
		}
		return tag;
	}
449784
def parse(self, raw):
        """"""
        self._raw = raw
        self.hub_name = self._parse("userData", "hubName", converter=base64_to_unicode)
        self.ip = self._parse("userData", "ip")
        self.ssid = self._parse("userData", "ssid")