Returns the GA4GH protocol representation of this read group's
        ReadStats.
967
def getStats(self):
        
        stats = protocol.ReadStats()
        stats.aligned_read_count = self.getNumAlignedReads()
        stats.unaligned_read_count = self.getNumUnalignedReads()
        # TODO base_count requires iterating through all reads
        return stats
812313
def read(self):
        ""
        status = gpscommon.read(self)
        if status <= 0:
            return status
        if self.response.startswith("{") and self.response.endswith("}\r\n"):
            self.unpack(self.response)
            self.__oldstyle_shim()
            self.newstyle = True
            self.valid |= PACKET_SET
        elif self.response.startswith("GPSD"):
            self.__oldstyle_unpack(self.response)
            self.valid |= PACKET_SET
        return 0
1194730
def read_block_epb(self, block, size):
        """"""
        intid, tshigh, tslow, caplen, wirelen = struct.unpack(
            self.endian + "5I",
            block[:20],
        )
        return (block[20:20 + caplen][:size],
                RawPcapNgReader.PacketMetadata(linktype=self.interfaces[intid][0],  # noqa: E501
                                               tsresol=self.interfaces[intid][2],  # noqa: E501
                                               tshigh=tshigh,
                                               tslow=tslow,
                                               wirelen=wirelen))
1010643
function getStats() {
  var o = {};
  o.total_connections_received = this.stats.connections;
  o.total_commands_processed = this.stats.commands;
  o.total_net_input_bytes = this.stats.ibytes;
  o.total_net_output_bytes = this.stats.obytes;

  o.rejected_connections = this.stats.rejected;

  o.expired_keys = this.stats.expired;
  o.keyspace_hits = this.stats.hits;
  o.keyspace_misses = this.stats.misses;

  o.pubsub_channels = this.stats.pubsub_channels;
  o.pubsub_patterns = this.stats.pubsub_patterns;

  return o;
}
590868
def prt_gos_grouped(self, prt, **kws_grp):
        """"""
        prtfmt = self.datobj.kws['fmtgo']
        wrobj = WrXlsxSortedGos(self.name, self.sortobj)
        # Keyword arguments: control content: hdrgo_prt section_prt top_n use_sections
        desc2nts = self.sortobj.get_desc2nts(**kws_grp)
        wrobj.prt_txt_desc2nts(prt, desc2nts, prtfmt)
811517
def read_bytes(self, count):
        """"""
        if self.pos + count > self.remaining_length:
            return NC.ERR_PROTOCOL, None
        
        ba = bytearray(count)
        for x in xrange(0, count):
            ba[x] = self.payload[self.pos]
            self.pos += 1
        
        return NC.ERR_SUCCESS, ba
775777
def read_stats(self, *stats):
        
        from ixexplorer.ixe_stream import IxePacketGroupStream
        sleep_time = 0.1  # in cases we only want few counters but very fast we need a smaller sleep time
        if not stats:
            stats = [m.attrname for m in IxePgStats.__tcl_members__ if m.flags & FLAG_RDONLY]
            sleep_time = 1

        # Read twice to refresh rate statistics.
        for port in self.tx_ports_streams:
            port.api.call_rc('streamTransmitStats get {} 1 4096'.format(port.uri))
        for rx_port in self.rx_ports:
            rx_port.api.call_rc('packetGroupStats get {} 0 65536'.format(rx_port.uri))
        time.sleep(sleep_time)

        self.statistics = OrderedDict()
        for tx_port, streams in self.tx_ports_streams.items():
            for stream in streams:
                stream_stats = OrderedDict()
                tx_port.api.call_rc('streamTransmitStats get {} 1 4096'.format(tx_port.uri))
                stream_tx_stats = IxeStreamTxStats(tx_port, stream.index)
                stream_stats_tx = {c: v for c, v in stream_tx_stats.get_attributes(FLAG_RDONLY).items()}
                stream_stats['tx'] = stream_stats_tx
                stream_stat_pgid = IxePacketGroupStream(stream).groupId
                stream_stats_pg = pg_stats_dict()
                for port in self.session.ports.values():
                    stream_stats_pg[str(port)] = OrderedDict(zip(stats, [-1] * len(stats)))
                for rx_port in self.rx_ports:
                    if not stream.rx_ports or rx_port in stream.rx_ports:
                        rx_port.api.call_rc('packetGroupStats get {} 0 65536'.format(rx_port.uri))
                        pg_stats = IxePgStats(rx_port, stream_stat_pgid)
                        stream_stats_pg[str(rx_port)] = pg_stats.read_stats(*stats)
                stream_stats['rx'] = stream_stats_pg
                self.statistics[str(stream)] = stream_stats
        return self.statistics
721416
def get_read_strategy(cls, response):
        '''
        '''
        chunked_match = re.match(
            r'chunked($|;)',
            response.fields.get('Transfer-Encoding', '')
        )

        if chunked_match:
            return 'chunked'
        elif 'Content-Length' in response.fields:
            return 'length'
        else:
            return 'close'
1333474
function usageRead(opts, cb) {
  if (typeof opts === 'function') {
    cb = opts;
    opts = {
      sectorSizeBytes: 512,
      sampleMs: 1000,
      device: 'sda',
      units: 'bytes',
    };
  } else {
    opts.sectorSizeBytes = opts.sectorSizeBytes || 512;
    opts.sampleMs = opts.sampleMs || 1000;
    opts.device =  opts.device || 'sda';
    opts.units =  opts.units || 'bytes';
  }

  var time;
  var delta1;
  var delta0 = _parseProcDiskstats()[opts.device].sectorsRead;
  time = process.hrtime();
  setTimeout(function() {
    delta1 = _parseProcDiskstats()[opts.device].sectorsRead;

    var diff = process.hrtime(time);
    var diffSeconds = diff[0] + diff[1] * 1e-9;

    var totalBytes = (delta1 - delta0) * opts.sectorSizeBytes;
    var totalBytesPerSecond = totalBytes / (diffSeconds * diffSeconds);
    var converted = _bytesTo(totalBytesPerSecond, opts.units);

    return cb(converted);
  }, opts.sampleMs);
}
92104
def retrieve_scores(gname, sdir,
                    codon_pos, germ_aa, somatic_aa,
                    default_mga=5., default_vest=0,
                    no_file_flag=-1):
    
    # get variant types
    #var_class = cutils.get_variant_classification(germ_aa, somatic_aa, codon_pos)

    # get information about MGA entropy
    mga_path = os.path.join(sdir, gname+".mgaentropy.pickle")
    if os.path.exists(mga_path):
        if sys.version_info < (3,):
            # python 2.7 way
            with open(mga_path) as handle:
                mga_ent = pickle.load(handle)
        else:
            # python 3.X way
            with open(mga_path, 'rb') as handle:
                mga_ent = pickle.load(handle, encoding='latin-1')
    else:
        mga_ent = None
    missense_pos = [p for i, p in enumerate(codon_pos)
                    if (germ_aa[i]!=somatic_aa[i]) and
                       (germ_aa[i] not in ['-', '*', 'Splice_Site']) and
                       (somatic_aa[i] not in ['-', '*', 'Splice_Site'])]
    total_mga_ent = compute_mga_entropy_stat(mga_ent, missense_pos, sum, default_mga)

        #mga_ent_ixs = [codon_pos[i] for i in range(len(var_class))
                       #if var_class[i] == 'Missense_Mutation']
        #len_mga_ent = len(mga_ent)
        #mga_ent_scores = [mga_ent[ix] for ix in mga_ent_ixs if ix < len_mga_ent]
        #if mga_ent_scores:
            #total_mga_ent = sum(mga_ent_scores)
        #else:
            #total_mga_ent = default_mga
    #else:
        #total_mga_ent = no_file_flag

    # get information about VEST scores
    vest_path = os.path.join(sdir, gname+".vest.pickle")
    if os.path.exists(vest_path):
        if sys.version_info < (3,):
            # python 2.7 way
            with open(vest_path) as handle:
                vest_score = pickle.load(handle)
        else:
            # python 3.X way
            with open(vest_path, 'rb') as handle:
                vest_score = pickle.load(handle, encoding='latin-1')
    else:
        vest_score = None
    total_vest = compute_vest_stat(vest_score,
                                   germ_aa, somatic_aa, codon_pos,
                                   stat_func=sum, default_val=default_vest)
        #vest_scores = [vest_score.get(codon_pos[i]+1, {}).get(germ_aa[i], {}).get(somatic_aa[i], default_vest)
                        #for i in range(len(var_class))
                        #if var_class[i] == 'Missense_Mutation']
        #total_vest = sum(vest_scores)
    #else:
        #total_vest = no_file_flag
    return total_mga_ent, total_vest
169910
def get_ntp_stats(self):
        """"""
        # NTP Peers does not have XML RPC defined
        # thus we need to retrieve raw text and parse...
        # :(

        ntp_stats = []

        REGEX = (
            r"^\s?(\+|\*|x|-)?([a-zA-Z0-9\.+-:]+)"
            r"\s+([a-zA-Z0-9\.]+)\s+([0-9]{1,2})"
            r"\s+(-|u)\s+([0-9h-]+)\s+([0-9]+)"
            r"\s+([0-9]+)\s+([0-9\.]+)\s+([0-9\.-]+)"
            r"\s+([0-9\.]+)\s?$"
        )

        ntp_assoc_output = self.device.cli("show ntp associations no-resolve")
        ntp_assoc_output_lines = ntp_assoc_output.splitlines()

        for ntp_assoc_output_line in ntp_assoc_output_lines[3:]:  # except last line
            line_search = re.search(REGEX, ntp_assoc_output_line, re.I)
            if not line_search:
                continue  # pattern not found
            line_groups = line_search.groups()
            try:
                ntp_stats.append(
                    {
                        "remote": napalm.base.helpers.ip(line_groups[1]),
                        "synchronized": (line_groups[0] == "*"),
                        "referenceid": py23_compat.text_type(line_groups[2]),
                        "stratum": int(line_groups[3]),
                        "type": py23_compat.text_type(line_groups[4]),
                        "when": py23_compat.text_type(line_groups[5]),
                        "hostpoll": int(line_groups[6]),
                        "reachability": int(line_groups[7]),
                        "delay": float(line_groups[8]),
                        "offset": float(line_groups[9]),
                        "jitter": float(line_groups[10]),
                    }
                )
            except Exception:
                continue  # jump to next line

        return ntp_stats
957139
def afterqc_general_stats_table(self):
        

        headers = OrderedDict()
        headers['pct_good_bases'] = {
            'title': '% Good Bases',
            'description': 'Percent Good Bases',
            'max': 100,
            'min': 0,
            'suffix': '%',
            'scale': 'BuGn',
        }
        headers['good_reads'] = {
            'title': '{} Good Reads'.format(config.read_count_prefix),
            'description': 'Good Reads ({})'.format(config.read_count_desc),
            'min': 0,
            'modify': lambda x: x * config.read_count_multiplier,
            'scale': 'GnBu',
            'shared_key': 'read_count'
        }
        headers['total_reads'] = {
            'title': '{} Total Reads'.format(config.read_count_prefix),
            'description': 'Total Reads ({})'.format(config.read_count_desc),
            'min': 0,
            'modify': lambda x: x * config.read_count_multiplier,
            'scale': 'Blues',
            'shared_key': 'read_count'
        }
        headers['readlen'] = {
            'title': 'Read Length',
            'description': 'Read Length',
            'min': 0,
            'suffix': ' bp',
            'format': '{:,.0f}',
            'scale': 'YlGn'
        }
        self.general_stats_addcols(self.afterqc_data, headers)
406053
def _read_gaf_nts(self, fin_gaf, hdr_only, allow_missing_symbol):
        """"""
        nts = []
        ver = None
        hdrobj = GafHdr()
        datobj = None
        # pylint: disable=not-callable
        ntobj_make = None
        get_gafvals = None
        lnum = -1
        line = ''
        try:
            with open(fin_gaf) as ifstrm:
                for lnum, line in enumerate(ifstrm, 1):
                    # Read data
                    if get_gafvals:
                        # print(lnum, line)
                        gafvals = get_gafvals(line)
                        if gafvals:
                            nts.append(ntobj_make(gafvals))
                        else:
                            datobj.ignored.append((lnum, line))
                    # Read header
                    elif datobj is None:
                        if line[0] == '!':
                            if ver is None and line[1:13] == 'gaf-version:':
                                ver = line[13:].strip()
                            hdrobj.chkaddhdr(line)
                        else:
                            self.hdr = hdrobj.get_hdr()
                            if hdr_only:
                                return nts
                            datobj = GafData(ver, allow_missing_symbol)
                            get_gafvals = datobj.get_gafvals
                            ntobj_make = datobj.get_ntobj()._make
        except Exception as inst:
            import traceback
            traceback.print_exc()
            sys.stderr.write("\n  **FATAL-gaf: {MSG}\n\n".format(MSG=str(inst)))
            sys.stderr.write("**FATAL-gaf: {FIN}[{LNUM}]:\n{L}".format(FIN=fin_gaf, L=line, LNUM=lnum))
            if datobj is not None:
                datobj.prt_line_detail(sys.stdout, line)
            sys.exit(1)
        self.datobj = datobj
        return nts
1141795
def Recv(self):
    
    size = struct.unpack(_STRUCT_FMT, self._ReadN(_STRUCT_LEN))[0]
    if size > MAX_SIZE:
      raise ProtocolError("Expected size to be at most %d, got %d" % (MAX_SIZE,
                                                                      size))
    with self._read_lock:
      buf = self._ReadN(size)
      self._ReadMagic()

    res = common_pb2.Message()
    res.ParseFromString(buf)

    return res, len(buf)
260655
def toProtocolElement(self):
        
        gaContinuousSet = protocol.ContinuousSet()
        gaContinuousSet.id = self.getId()
        gaContinuousSet.dataset_id = self.getParentContainer().getId()
        gaContinuousSet.reference_set_id = pb.string(
                                            self._referenceSet.getId())
        gaContinuousSet.name = self._name
        gaContinuousSet.source_uri = self._sourceUri
        attributes = self.getAttributes()
        for key in attributes:
            gaContinuousSet.attributes.attr[key] \
                .values.extend(protocol.encodeValue(attributes[key]))
        return gaContinuousSet
357684
def get_stats(self):
        """"""

        try:
            ret = fcntl.ioctl(self.ins, BIOCGSTATS, struct.pack("2I", 0, 0))
            return struct.unpack("2I", ret)
        except IOError:
            warning("Unable to get stats from BPF !")
            return (None, None)
512904
def toProtocolElement(self):
        
        # TODO this is very incomplete, but we don't have the
        # implementation to fill out the rest of the fields currently
        readGroup = protocol.ReadGroup()
        readGroup.id = self.getId()
        readGroup.created = self._creationTime
        readGroup.updated = self._updateTime
        dataset = self.getParentContainer().getParentContainer()
        readGroup.dataset_id = dataset.getId()
        readGroup.name = self.getLocalId()
        readGroup.predicted_insert_size = pb.int(self.getPredictedInsertSize())
        referenceSet = self._parentContainer.getReferenceSet()
        readGroup.sample_name = pb.string(self.getSampleName())
        readGroup.biosample_id = pb.string(self.getBiosampleId())
        if referenceSet is not None:
            readGroup.reference_set_id = referenceSet.getId()
        readGroup.stats.CopyFrom(self.getStats())
        readGroup.programs.extend(self.getPrograms())
        readGroup.description = pb.string(self.getDescription())
        readGroup.experiment.CopyFrom(self.getExperiment())
        self.serializeAttributes(readGroup)
        return readGroup