Reproduced from packet.py
357182
def _show_or_dump(self, dump=False, indent=3,
                      lvl="", label_lvl="", first_call=True):
        
        ct = AnsiColorTheme() if dump else conf.color_theme
        s = "%s%s %s %s \n" % (label_lvl, ct.punct("###["),
                               ct.layer_name(self.name), ct.punct("]###"))
        for f in self.fields_desc[:-1]:
            ncol = ct.field_name
            vcol = ct.field_value
            fvalue = self.getfieldval(f.name)
            begn = "%s  %-10s%s " % (label_lvl + lvl, ncol(f.name),
                                     ct.punct("="),)
            reprval = f.i2repr(self, fvalue)
            if isinstance(reprval, str):
                reprval = reprval.replace("\n", "\n" + " " * (len(label_lvl) +
                                                              len(lvl) +
                                                              len(f.name) +
                                                              4))
            s += "%s%s\n" % (begn, vcol(reprval))
        f = self.fields_desc[-1]
        ncol = ct.field_name
        vcol = ct.field_value
        fvalue = self.getfieldval(f.name)
        begn = "%s  %-10s%s " % (label_lvl + lvl, ncol(f.name), ct.punct("="),)
        reprval = f.i2repr(self, fvalue)
        if isinstance(reprval, str):
            reprval = reprval.replace("\n", "\n" + " " * (len(label_lvl) +
                                                          len(lvl) +
                                                          len(f.name) +
                                                          4))
        s += "%s%s\n" % (begn, vcol(reprval))
        if self.payload:
            s += self.payload._show_or_dump(dump=dump, indent=indent,
                                            lvl=lvl + (" " * indent * self.show_indent),  # noqa: E501
                                            label_lvl=label_lvl, first_call=False)  # noqa: E501

        if first_call and not dump:
            print(s)
        else:
            return s
589060
private int readPacket(byte[] packet, int offset, int psize)
            throws IOException {
        int length = 0;
        try {
            while (length < psize) {
                int len = stream.read(packet, offset + length, psize - length);
                if (len == -1) {
                    return length;
                }
                length += len;
            }
            return length;
        } catch (Exception e) {
        	logger.error(e);
        }
        return length;
    }
1372072
def encode(self, b64=False):
        """"""
        encoded_payload = b''
        for pkt in self.packets:
            encoded_packet = pkt.encode(b64=b64)
            packet_len = len(encoded_packet)
            if b64:
                encoded_payload += str(packet_len).encode('utf-8') + b':' + \
                    encoded_packet
            else:
                binary_len = b''
                while packet_len != 0:
                    binary_len = six.int2byte(packet_len % 10) + binary_len
                    packet_len = int(packet_len / 10)
                if not pkt.binary:
                    encoded_payload += b'\0'
                else:
                    encoded_payload += b'\1'
                encoded_payload += binary_len + b'\xff' + encoded_packet
        return encoded_payload
289699
def print_packet_count():
    """"""
    for name in archive.list_packet_names():
        packet_count = 0
        for group in archive.list_packet_histogram(name):
            for rec in group.records:
                packet_count += rec.count
        print('  {: <40} {: >20}'.format(name, packet_count))
180542
def packet_get_samples_per_frame(data, fs):
    """"""

    data_pointer = ctypes.c_char_p(data)

    result = _packet_get_nb_frames(data_pointer, ctypes.c_int(fs))
    if result < 0:
        raise OpusError(result)

    return result
1370345
def packet2chain(packet):
    """"""
    if scapy_all is None:
        raise ModuleNotFound("No module named 'scapy'", name='scapy')
    chain = [packet.name]
    payload = packet.payload
    while not isinstance(payload, scapy_all.packet.NoPayload):
        chain.append(payload.name)
        payload = payload.payload
    return ':'.join(chain)
29026
def _packetlist_timeskew_graph(self, ip, **kargs):
    """"""  # noqa: E501

    # Filter TCP segments which source address is 'ip'
    tmp = (self._elt2pkt(x) for x in self.res)
    b = (x for x in tmp if IP in x and x[IP].src == ip and TCP in x)

    # Build a list of tuples (creation_time, replied_timestamp)
    c = []
    tsf = ICMPTimeStampField("", None)
    for p in b:
        opts = p.getlayer(TCP).options
        for o in opts:
            if o[0] == "Timestamp":
                c.append((p.time, tsf.any2i("", o[1][0])))

    # Stop if the list is empty
    if not c:
        warning("No timestamps found in packet list")
        return []

    # Prepare the data that will be plotted
    first_creation_time = c[0][0]
    first_replied_timestamp = c[0][1]

    def _wrap_data(ts_tuple, wrap_seconds=2000):
        """Wrap the list of tuples."""

        ct, rt = ts_tuple  # (creation_time, replied_timestamp)
        X = ct % wrap_seconds
        Y = ((ct - first_creation_time) - ((rt - first_replied_timestamp) / 1000.0))  # noqa: E501

        return X, Y

    data = [_wrap_data(e) for e in c]

    # Mimic the default gnuplot output
    if kargs == {}:
        kargs = MATPLOTLIB_DEFAULT_PLOT_KARGS
    lines = plt.plot(data, **kargs)

    # Call show() if matplotlib is not inlined
    if not MATPLOTLIB_INLINED:
        plt.show()

    return lines
444128
public void bufferPacket(OggPacket packet, long granulePosition) {
        if(closed) {
            throw new IllegalStateException("Can't buffer packets on a closed stream!");
        }
        if(! doneFirstPacket) {
            packet.setIsBOS();
            doneFirstPacket = true;
        }

        int size = packet.getData().length;
        boolean emptyPacket = (size==0);

        // Add to pages in turn
        OggPage page = getCurrentPage(false);
        int pos = 0;
        while( pos < size || emptyPacket) {
            pos = page.addPacket(packet, pos);
            if(pos < size) {
                page = getCurrentPage(true);
                page.setIsContinuation();
            }
            page.setGranulePosition(granulePosition);
            emptyPacket = false;
        }
        currentGranulePosition = granulePosition;
        packet.setParent(page);
    }
179424
def packet2dict(packet):
    """"""
    dict_ = dict()
    frame = packet.frame_info
    for field in frame.field_names:
        dict_[field] = getattr(frame, field)

    tempdict = dict_
    for layer in packet.layers:
        tempdict[layer.layer_name.upper()] = dict()
        tempdict = tempdict[layer.layer_name.upper()]
        for field in layer.field_names:
            tempdict[field] = getattr(layer, field)

    return dict_
344886
def _sense_packet_to_data(packet):
        """"""
        data = bytearray(0)
        last = 0
        i = 1
        while (i < len(packet)):
            if not (last == 2 and packet[i] == 0):
                data.append(packet[i])
            last = packet[i]
            i += 1

        return data
1056284
function Packet(length) {
    this._index = 0;
    if (length instanceof Buffer) {
        this.buf = length;
    } else {
        this.buf = Buffer.alloc(length, 0);

        this.writeInt32LE(length);
    }
}
342253
def from_bytes(cls, bitstream):
        '''
        
        '''
        packet = cls()

        # Convert to ConstBitStream (if not already provided)
        if not isinstance(bitstream, ConstBitStream):
            if isinstance(bitstream, Bits):
                bitstream = ConstBitStream(auto=bitstream)
            else:
                bitstream = ConstBitStream(bytes=bitstream)

        # Read the source and destination ports
        (packet.source_port,
         packet.destination_port) = bitstream.readlist('2*uint:16')

        # Store the length
        length = bitstream.read('uint:16')
        if length < 8:
            raise ValueError('Invalid UDP length')

        # Read the checksum
        packet.checksum = bitstream.read('uint:16')

        # And the rest is payload
        payload_bytes = length - 8
        packet.payload = bitstream.read('bytes:%d' % payload_bytes)

        # LISP-specific handling
        if packet.source_port == 4341 or packet.destination_port == 4341:
            # Payload is a LISP data packet
            from pylisp.packet.lisp.data import DataPacket
            packet.payload = DataPacket.from_bytes(packet.payload)
        elif packet.source_port == 4342 or packet.destination_port == 4342:
            # Payload is a LISP control message
            from pylisp.packet.lisp.control.base import ControlMessage
            packet.payload = ControlMessage.from_bytes(packet.payload)

        # There should be no remaining bits
        if bitstream.pos != bitstream.len:
            raise ValueError('Bits remaining after processing packet')

        # Verify that the properties make sense
        packet.sanitize()

        return packet
408089
def _incoming(self, packet):
        
        if len(packet.data) < 1:
            logger.warning('Localization packet received with incorrect' +
                           'length (length is {})'.format(len(packet.data)))
            return

        pk_type = struct.unpack('<B', packet.data[:1])[0]
        data = packet.data[1:]

        # Decoding the known packet types
        # TODO: more generic decoding scheme?
        decoded_data = None
        if pk_type == self.RANGE_STREAM_REPORT:
            if len(data) % 5 != 0:
                logger.error('Wrong range stream report data lenght')
                return
            decoded_data = {}
            raw_data = data
            for i in range(int(len(data) / 5)):
                anchor_id, distance = struct.unpack('<Bf', raw_data[:5])
                decoded_data[anchor_id] = distance
                raw_data = raw_data[5:]

        pk = LocalizationPacket(pk_type, data, decoded_data)
        self.receivedLocationPacket.call(pk)
1001482
def packet2dict(packet, timestamp, *, data_link):
    """"""
    def wrapper(packet):
        dict_ = dict()
        for field in packet.__hdr_fields__:
            dict_[field] = getattr(packet, field, None)
        payload = packet.data
        if not isinstance(payload, bytes):
            dict_[type(payload).__name__] = wrapper(payload)
        return dict_
    return {
        'timestamp': timestamp,
        'packet': packet.pack(),
        data_link.name: wrapper(packet),
    }
478802
def encode(self):
        """"""
        tftpassert(self.filename, "filename required in initial packet")
        tftpassert(self.mode, "mode required in initial packet")
        # Make sure filename and mode are bytestrings.
        filename = self.filename
        mode = self.mode
        if not isinstance(filename, bytes):
            filename = filename.encode('ascii')
        if not isinstance(self.mode, bytes):
            mode = mode.encode('ascii')

        ptype = None
        if self.opcode == 1: ptype = "RRQ"
        else:                ptype = "WRQ"
        log.debug("Encoding %s packet, filename = %s, mode = %s",
            ptype, filename, mode)
        for key in self.options:
            log.debug("    Option %s = %s", key, self.options[key])

        fmt = b"!H"
        fmt += b"%dsx" % len(filename)
        if mode == b"octet":
            fmt += b"5sx"
        else:
            raise AssertionError("Unsupported mode: %s" % mode)
        # Add options. Note that the options list must be bytes.
        options_list = []
        if len(list(self.options.keys())) > 0:
            log.debug("there are options to encode")
            for key in self.options:
                # Populate the option name
                name = key
                if not isinstance(name, bytes):
                    name = name.encode('ascii')
                options_list.append(name)
                fmt += b"%dsx" % len(name)
                # Populate the option value
                value = self.options[key]
                # Work with all strings.
                if isinstance(value, int):
                    value = str(value)
                if not isinstance(value, bytes):
                    value = value.encode('ascii')
                options_list.append(value)
                fmt += b"%dsx" % len(value)

        log.debug("fmt is %s", fmt)
        log.debug("options_list is %s", options_list)
        log.debug("size of struct is %d", struct.calcsize(fmt))
        
        self.buffer = struct.pack(fmt,
                                  self.opcode,
                                  filename,
                                  mode,
                                  *options_list)

        log.debug("buffer is %s", repr(self.buffer))
        return self
550563
function writePESPackets() {
  var continuityCounters = {};
  var pesWriter = x => {
    if (x.type === 'PESPacket') {
      // var bytePos = 0;
      var counter = continuityCounters[x.pid];
      if (typeof counter === 'undefined') counter = 0;
      counter = counter % 16;
      var packets = [];
      var data = (x.payloads.length === 1) ? x.payloads[0] :
        Buffer.concat(x.payloads);
      var packetLength = data.length;
      if (packetLength > 0xffff) {
        packetLength = 0;
        if (!x.streamID.startsWith('video_stream')) {
          console.log(`Warning: PES packet for pid ${x.pid} is not video and has length greater than 0xffff.`);
        }
      }
      var hpp = Buffer.allocUnsafe(100);
      hpp.writeUIntBE(1, 0, 3);
      hpp.writeUInt8(util.streamNameID[x.streamID], 3);
      hpp.writeUInt16BE(packetLength, 4);
      hpp.writeUInt16BE(
        0x8000 |
        (x.scramblingControl & 0x03) << 12 |
        ((x.priority === true) ? 0x0800 : 0x0000) |
        ((x.dataAlignmentIndicator === true) ? 0x0400 : 0x0000) |
        ((x.copyright === true) ? 0x0200 : 0x0000) |
        ((x.originalOrCopy === true) ? 0x0100 : 0x0000) |
        (x.ptsDtsIndicator & 0x03) << 6 |
        ((x.escrFlag === true) ? 0x0020 : 0x0000) |
        ((x.esRateFlag === true) ? 0x0010 : 0x0000) |
        ((x.dsmTrickModeFlag === true) ? 0x0008 : 0x0000) |
        ((x.additionalCopyInfoFlag === true) ? 0x0004 : 0x0000) |
        ((x.crcFlag === true) ? 0x0002 : 0x0000) |
        ((x.extensionFlag === true) ? 0x0001 : 0x0000), 6);
      var pesHeaderLength =
        (x.ptsDtsIndicator === 2 ? 5 : 0) +
        (x.ptsDtsIndicator === 3 ? 10 : 0);
      hpp.writeUInt8(pesHeaderLength, 8);
      hpp = hpp.slice(0, 9 + pesHeaderLength);
      switch (x.ptsDtsIndicator) {
      case 2:
        writeTimeStamp(x.pts, 0x02, hpp, 9);
        break;
      case 3:
        writeTimeStamp(x.pts, 0x03, hpp, 9);
        writeTimeStamp(x.dts, 0x01, hpp, 14);
        break;
      default:
        break;
      }
      var dataPos = 0;
      var payloadStart = true;
      var available = 184 - hpp.length;
      while (dataPos < (data.length - available)) {
        var nextPacket = {
          type : 'TSPacket',
          packetSync : 0x47,
          transportErrorIndicator : false,
          payloadUnitStartIndicator : payloadStart,
          transportPriority : false,
          pid : x.pid,
          scramblingControl : 0,
          adaptationFieldControl : 1,
          continuityCounter : counter++,
          payload : payloadStart ? Buffer.concat(
            [hpp, data.slice(0, available)]) :
            data.slice(dataPos, dataPos + 184)
        };
        counter = counter % 16;
        dataPos += available;
        packets.push(nextPacket);
        payloadStart = false;
        available = 184;
      }
      if (data.length - dataPos > 0) {
        var adaptationLength = 183 - (payloadStart ?
          (data.length - dataPos) + hpp.length :
          (data.length - dataPos));
        var finalPacket = {
          type : 'TSPacket',
          packetSync : 0x47,
          transportErrorIndicator : false,
          payloadUnitStartIndicator : payloadStart,
          transportPriority : false,
          pid : x.pid,
          scramblingControl : 0,
          adaptationFieldControl : 3,
          continuityCounter : counter++,
          adaptationField : { // padding
            type : 'AdaptationField',
            adaptationFieldLength : adaptationLength,
            discontinuityIndicator : false,
            randomAccessIndicator : false,
            elementaryStreamPriorityIndicator : false,
            pcrFlag : false,
            opcrFlag : false,
            splicingPointFlag : false,
            transportPrivateDataFlag : false,
            adaptationFieldExtensionFlag : false
          },
          payload : payloadStart ?
            Buffer.concat([hpp, data]) : data.slice(dataPos)
        };
        if (finalPacket.adaptationField.adaptationFieldLength === -1) {
          delete finalPacket.adaptationField;
          finalPacket.adaptationFieldControl = 1;
        } else if (finalPacket.adaptationField.adaptationFieldLength === 0) {
          finalPacket.adaptationField = {
            type : 'AdaptationField',
            adaptationFieldLength : 0
          };
        }
        packets.push(finalPacket);
        return H(packets);
      }
      continuityCounters[x.pid] = counter % 16;
    } else { // Is PESPacket
      return H([x]);
    }
  };

  return H.pipeline(H.flatMap(pesWriter));
}
1165069
def data_received(self, data):
        '''
        
        '''
        self._buffered_data.extend(data)
        while self._buffered_data:
            size = len(self._buffered_data)
            if self._data_package is None:
                if size < DataPackage.struct_datapackage.size:
                    return None
                self._data_package = DataPackage(self._buffered_data)
            if size < self._data_package.length:
                return None
            try:
                self._data_package.extract_data_from(self._buffered_data)
            except KeyError as e:
                logging.error('Unsupported package received: {}'.format(e))
            except Exception as e:
                logging.exception(e)
                # empty the byte-array to recover from this error
                self._buffered_data.clear()
            else:
                self._on_package_received()
            self._data_package = None