Read header from EDF file.

        It only reads the header for internal purposes and adds a hdr.
509326
def _read_hdr(self):
        
        with self.filename.open('rb') as f:

            hdr = {}
            assert f.tell() == 0
            assert f.read(8) == b'0       '

            # recording info
            hdr['subject_id'] = decode(f.read(80)).strip()
            hdr['recording_id'] = decode(f.read(80)).strip()

            # parse timestamp
            date_str = decode(f.read(8)).strip()

            if date_str == '':
                edf_date = DEFAULT_DATETIME.date()
            else:
                (day, month, year) = [int(x) for x in findall('(\d+)', date_str)]
                # Y2K: cutoff is 1985
                if year >= 85:
                    year += 1900
                else:
                    year += 2000
                edf_date = date(year, month, day)

            time_str = decode(f.read(8)).strip()
            if time_str == '':
                edf_time = DEFAULT_DATETIME.time()
            else:
                (hour, minute, day) = [int(x) for x in findall('(\d+)', time_str)]

                edf_time = time(hour, minute, day)

            hdr['start_time'] = datetime.combine(edf_date, edf_time)

            # misc
            hdr['header_n_bytes'] = int(f.read(8))
            f.seek(44, 1)  # reserved for EDF+
            hdr['n_records'] = int(f.read(8))
            hdr['record_length'] = float(f.read(8))  # in seconds
            nchannels = hdr['n_channels'] = int(f.read(4))

            # read channel info
            channels = range(hdr['n_channels'])
            hdr['label'] = [decode(f.read(16)).strip() for n in
                            channels]
            hdr['transducer'] = [decode(f.read(80)).strip()
                                 for n in channels]
            hdr['physical_dim'] = [decode(f.read(8)).strip() for n in
                                   channels]
            hdr['physical_min'] = [float(f.read(8)) for n in channels]
            hdr['physical_max'] = [float(f.read(8)) for n in channels]
            hdr['digital_min'] = [float(f.read(8)) for n in channels]
            hdr['digital_max'] = [float(f.read(8)) for n in channels]
            hdr['prefiltering'] = [decode(f.read(80)).strip()
                                   for n in channels]
            hdr['n_samples_per_record'] = [int(f.read(8)) for n in channels]
            f.seek(32 * nchannels, 1)  # reserved

            assert f.tell() == hdr['header_n_bytes']

            self.hdr = hdr
330915
def _read_header(self):
        """"""
        self._header = self.cdmrf.fetch_header()
        self.load_from_stream(self._header)
933333
def read_mm_header(fd, byte_order, dtype, count):
    """"""
    return numpy.rec.fromfile(fd, MM_HEADER, 1, byteorder=byte_order)[0]
53023
def run(self, fnc_name, hdrs_usr):
        """"""
        fnc = self.fncs[fnc_name]
        with open(self.fin) as fin_stream:
            for lnum, line in enumerate(fin_stream):
                line = line.rstrip('\r\n') # chomp
                # Obtain Data if headers have been collected from the first line
                if self.hdr2idx:
                    self._init_data_line(fnc, lnum, line)
                # Obtain the header
                else:
                    self.do_hdr(line, hdrs_usr)
            if self.log is not None:
                self.log.write("  {:9} data READ:  {}\n".format(len(self.ret_list), self.fin))
        return self.ret_list, self.hdr2idx
23481
def read_abinit_hdr(self):
        
        d = {}
        for hvar in _HDR_VARIABLES.values():
            ncname = hvar.etsf_name if hvar.etsf_name is not None else hvar.name
            if ncname in self.rootgrp.variables:
                d[hvar.name] = self.read_value(ncname)
            elif ncname in self.rootgrp.dimensions:
                d[hvar.name] = self.read_dimvalue(ncname)
            else:
                raise ValueError("Cannot find `%s` in `%s`" % (ncname, self.path))
            # Convert scalars to (well) scalars.
            if hasattr(d[hvar.name], "shape") and not d[hvar.name].shape:
                d[hvar.name] = np.asscalar(d[hvar.name])
            if hvar.name in ("title", "md5_pseudos", "codvsn"):
                # Convert array of numpy bytes to list of strings
                if hvar.name == "codvsn":
                    d[hvar.name] = "".join(bs.decode("utf-8").strip() for bs in d[hvar.name])
                else:
                    d[hvar.name] = ["".join(bs.decode("utf-8") for bs in astr).strip()
                            for astr in d[hvar.name]]

        return AbinitHeader(d)
140350
private void readHeader(RandomAccessInputStream raf, long location) throws IOException
	{
		byte[] head = new byte[HEADER_SIZE];
		raf.seek(location);

		if (raf.read(head) != HEADER_SIZE)
		{
			throw new IOException("Error reading MPEG frame header.");
		}

		version = (head[1]&0x18)>>3;
		layer = (head[1]&0x06)>>1;
		crced = (head[1]&0x01)==0;
		bitRate = findBitRate((head[2]&0xF0)>>4, version, layer);
		sampleRate = findSampleRate((head[2]&0x0C)>>2, version);
		channelMode = (head[3]&0xC0)>>6;
		copyrighted = (head[3]&0x08)!=0;
		original = (head[3]&0x04)!=0;
		emphasis = head[3]&0x03;
	}
1119645
def _read_image_data( mhd_file):
    
    tempdir = get_tempdir()
    
    # Load description from mhd file
    fname = tempdir + '/' + mhd_file
    des = open(fname, 'r').read()
    
    # Get data filename and load raw data
    match = re.findall('ElementDataFile = (.+?)\n', des)
    fname = tempdir + '/' + match[0]
    data = open(fname, 'rb').read()
    
    # Determine dtype
    match = re.findall('ElementType = (.+?)\n', des)
    dtype_itk = match[0].upper().strip()
    dtype = DTYPE_ITK2NP.get(dtype_itk, None)
    if dtype is None:
        raise RuntimeError('Unknown ElementType: ' + dtype_itk)
    
    # Create numpy array
    a = np.frombuffer(data, dtype=dtype)
    
    # Determine shape, sampling and origin of the data
    match = re.findall('DimSize = (.+?)\n', des)
    shape = [int(i) for i in match[0].split(' ')]
    #
    match = re.findall('ElementSpacing = (.+?)\n', des)
    sampling = [float(i) for i in match[0].split(' ')]
    #
    match = re.findall('Offset = (.+?)\n', des)
    origin = [float(i) for i in match[0].split(' ')]
    
    # Reverse shape stuff to make z-y-x order
    shape = [s for s in reversed(shape)]
    sampling = [s for s in reversed(sampling)]
    origin = [s for s in reversed(origin)]
    
    # Take vectors/colours into account
    N = np.prod(shape)
    if N != a.size:
        extraDim = int( a.size / N )
        shape = tuple(shape) + (extraDim,)
        sampling = tuple(sampling) + (1.0,)
        origin = tuple(origin) + (0,)
    
    # Check shape
    N = np.prod(shape)
    if N != a.size:
        raise RuntimeError('Cannot apply shape to data.')
    else:
        a.shape = shape
        a = Image(a)
        a.sampling = sampling
        a.origin = origin
    return a
238330
def read_header(stream):
    """"""
    type_id = stream.read(4)
    if type_id != b"DIRC":
        raise AssertionError("Invalid index file header: %r" % type_id)
    version, num_entries = unpack(">LL", stream.read(4 * 2))

    # TODO: handle version 3: extended data, see read-cache.c
    assert version in (1, 2)
    return version, num_entries
60019
public static <T extends Header> T getHeader(final Header[] hdrs, short id) {
        if(hdrs == null)
            return null;
        for(Header hdr: hdrs) {
            if(hdr == null)
                return null;
            if(hdr.getProtId() == id)
                return (T)hdr;
        }
        return null;
    }
438024
def set_base_headers(self, hdr):
        """"""
        hdr = super(JoinDitheredImagesRecipe, self).set_base_headers(hdr)
        hdr['IMGOBBL'] = 0
        hdr['OBSMODE'] = 'DITHERED_IMAGE'
        return hdr
868117
def read_csu_3(barmodel, hdr):
    """"""
    conf = CSUConf(barmodel)
    conf.set_state(hdr)
    return conf
399313
def _get_hd(self, hdr_info):
        

        hdr_map, variable_length_headers, text_headers = hdr_info

        with open(self.filename) as fp:
            total_header_length = 16
            while fp.tell() < total_header_length:
                hdr_id = np.fromfile(fp, dtype=common_hdr, count=1)[0]
                the_type = hdr_map[hdr_id['hdr_id']]
                if the_type in variable_length_headers:
                    field_length = int((hdr_id['record_length'] - 3) /
                                       the_type.itemsize)
                    current_hdr = np.fromfile(fp,
                                              dtype=the_type,
                                              count=field_length)
                    key = variable_length_headers[the_type]
                    if key in self.mda:
                        if not isinstance(self.mda[key], list):
                            self.mda[key] = [self.mda[key]]
                        self.mda[key].append(current_hdr)
                    else:
                        self.mda[key] = current_hdr
                elif the_type in text_headers:
                    field_length = int((hdr_id['record_length'] - 3) /
                                       the_type.itemsize)
                    char = list(the_type.fields.values())[0][0].char
                    new_type = np.dtype(char + str(field_length))
                    current_hdr = np.fromfile(fp,
                                              dtype=new_type,
                                              count=1)[0]
                    self.mda[text_headers[the_type]] = current_hdr
                else:
                    current_hdr = np.fromfile(fp,
                                              dtype=the_type,
                                              count=1)[0]
                    self.mda.update(
                        dict(zip(current_hdr.dtype.names, current_hdr)))

                total_header_length = self.mda['total_header_length']

        self.mda.setdefault('number_of_bits_per_pixel', 10)

        self.mda['projection_parameters'] = {'a': 6378169.00,
                                             'b': 6356583.80,
                                             'h': 35785831.00,
                                             # FIXME: find a reasonable SSP
                                             'SSP_longitude': 0.0}
        self.mda['navigation_parameters'] = {}
342851
def _load_h5(filename):
    ''''''
    from neurom.io import hdf5
    return hdf5.read(filename,
                     remove_duplicates=False,
                     data_wrapper=DataWrapper)
1099688
def _parseImageDosHeader(self, data):
        """"""
        ioh = IMAGE_DOS_HEADER.from_buffer(data)
        if ioh.e_magic != b'MZ':
            raise BinaryError('No valid PE/COFF file')

        return ImageDosHeaderData(header=ioh)
452628
def read_header(cls, headers_path, block_height, allow_none=False):
        
        if os.path.exists(headers_path):
    
            header_parser = BlockHeaderSerializer()
            sb = os.stat( headers_path )
            if sb.st_size < BLOCK_HEADER_SIZE * block_height:
                # beyond EOF 
                if allow_none:
                    return None 
                else:
                    raise Exception('EOF on block headers')

            with open( headers_path, "rb" ) as f:
                f.seek( block_height * BLOCK_HEADER_SIZE, os.SEEK_SET )
                hdr = SPVClient.read_header_at( f )

            return hdr
        else:
            if allow_none:
                return None
            else:
                raise Exception('No such file or directory: {}'.format(headers_path))
1004143
def set_base_headers(self, hdr):
        """"""
        hdr = super(StareImageRecipe2, self).set_base_headers(hdr)
        # Set EXP to 0
        hdr['EXP'] = 0
        return hdr
950755
def get_expstart(header,primary_hdr):
    """"""

    if 'expstart' in primary_hdr:
        exphdr = primary_hdr
    else:
        exphdr = header

    if 'EXPSTART' in exphdr:
        expstart = float(exphdr['EXPSTART'])
        expend = float(exphdr['EXPEND'])
    else:
        expstart = 0.
        expend = 0.0

    return (expstart,expend)