Construct the primary HDU file containing basic header info.
964177
def PrimaryHDU(model):
    '''
    

    '''

    # Get mission cards
    cards = model._mission.HDUCards(model.meta, hdu=0)
    if 'KEPMAG' not in [c[0] for c in cards]:
        cards.append(('KEPMAG', model.mag, 'Kepler magnitude'))

    # Add EVEREST info
    cards.append(('COMMENT', '************************'))
    cards.append(('COMMENT', '*     EVEREST INFO     *'))
    cards.append(('COMMENT', '************************'))
    cards.append(('MISSION', model.mission, 'Mission name'))
    cards.append(('VERSION', EVEREST_MAJOR_MINOR, 'EVEREST pipeline version'))
    cards.append(('SUBVER', EVEREST_VERSION, 'EVEREST pipeline subversion'))
    cards.append(('DATE', strftime('%Y-%m-%d'),
                  'EVEREST file creation date (YYYY-MM-DD)'))

    # Create the HDU
    header = pyfits.Header(cards=cards)
    hdu = pyfits.PrimaryHDU(header=header)

    return hdu
1252709
def _create_header(info, format, encoding, errors):
        
        parts = [
            stn(info.get("name", ""), 100, encoding, errors),
            itn(info.get("mode", 0) & 0o7777, 8, format),
            itn(info.get("uid", 0), 8, format),
            itn(info.get("gid", 0), 8, format),
            itn(info.get("size", 0), 12, format),
            itn(info.get("mtime", 0), 12, format),
            b"        ", # checksum field
            info.get("type", REGTYPE),
            stn(info.get("linkname", ""), 100, encoding, errors),
            info.get("magic", POSIX_MAGIC),
            stn(info.get("uname", ""), 32, encoding, errors),
            stn(info.get("gname", ""), 32, encoding, errors),
            itn(info.get("devmajor", 0), 8, format),
            itn(info.get("devminor", 0), 8, format),
            stn(info.get("prefix", ""), 155, encoding, errors)
        ]

        buf = struct.pack("%ds" % BLOCKSIZE, b"".join(parts))
        chksum = calc_chksums(buf[-BLOCKSIZE:])[0]
        buf = buf[:-364] + ("%06o\0" % chksum).encode("ascii") + buf[-357:]
        return buf
1274033
def create_from_hdu(cls, hdu, ebins=None):
        
        convname = HPX.identify_HPX_convention(hdu.header)
        conv = HPX_FITS_CONVENTIONS[convname]
        try:
            pixels = hdu.data[conv.idxstring]
        except KeyError:
            pixels = None
        return cls.create_from_header(hdu.header, ebins, pixels)
1256701
def build_specfile_header(spec):
    
    str = ""

    # first the mandatory sections
    mandatory_header_fields = {
        'NAME'           : '%%define name %s\nName: %%{name}\n',
        'VERSION'        : '%%define version %s\nVersion: %%{version}\n',
        'PACKAGEVERSION' : '%%define release %s\nRelease: %%{release}\n',
        'X_RPM_GROUP'    : 'Group: %s\n',
        'SUMMARY'        : 'Summary: %s\n',
        'LICENSE'        : 'License: %s\n', }

    str = str + SimpleTagCompiler(mandatory_header_fields).compile( spec )

    # now the optional tags
    optional_header_fields = {
        'VENDOR'              : 'Vendor: %s\n',
        'X_RPM_URL'           : 'Url: %s\n',
        'SOURCE_URL'          : 'Source: %s\n',
        'SUMMARY_'            : 'Summary(%s): %s\n',
        'X_RPM_DISTRIBUTION'  : 'Distribution: %s\n',
        'X_RPM_ICON'          : 'Icon: %s\n',
        'X_RPM_PACKAGER'      : 'Packager: %s\n',
        'X_RPM_GROUP_'        : 'Group(%s): %s\n',

        'X_RPM_REQUIRES'      : 'Requires: %s\n',
        'X_RPM_PROVIDES'      : 'Provides: %s\n',
        'X_RPM_CONFLICTS'     : 'Conflicts: %s\n',
        'X_RPM_BUILDREQUIRES' : 'BuildRequires: %s\n',

        'X_RPM_SERIAL'        : 'Serial: %s\n',
        'X_RPM_EPOCH'         : 'Epoch: %s\n',
        'X_RPM_AUTOREQPROV'   : 'AutoReqProv: %s\n',
        'X_RPM_EXCLUDEARCH'   : 'ExcludeArch: %s\n',
        'X_RPM_EXCLUSIVEARCH' : 'ExclusiveArch: %s\n',
        'X_RPM_PREFIX'        : 'Prefix: %s\n',

        # internal use
        'X_RPM_BUILDROOT'     : 'BuildRoot: %s\n', }

    # fill in default values:
    # Adding a BuildRequires renders the .rpm unbuildable under System, which
    # are not managed by rpm, since the database to resolve this dependency is
    # missing (take Gentoo as an example)
#    if not s.has_key('x_rpm_BuildRequires'):
#        s['x_rpm_BuildRequires'] = 'scons'

    if 'X_RPM_BUILDROOT' not in spec:
        spec['X_RPM_BUILDROOT'] = '%{_tmppath}/%{name}-%{version}-%{release}'

    str = str + SimpleTagCompiler(optional_header_fields, mandatory=0).compile( spec )
    return str
373334
def get_header(self, hdrclass, returnval=None):
        '''
        
        '''
        if isinstance(hdrclass, str):
            return self.get_header_by_name(hdrclass)

        for hdr in self._headers:
            if isinstance(hdr, hdrclass):
                return hdr
        return returnval
440201
def header(cls, name, type_=Type.String, description=None, default=None, required=None, **options):
        
        return cls(name, In.Header, type_, None, description,
                   required=required, default=default,
                   **options)
1029574
def _populate_header(self, root):
        """"""
        # If this gets more complicated, it should be handled via an XSLT.
        title_stmt = root.xpath(
            'tei:teiHeader/tei:fileDesc/tei:titleStmt',
            namespaces=constants.NAMESPACES)[0]
        # There is no guarantee that a title or author is specified,
        # in which case do nothing.
        try:
            title_stmt[0].text = root.xpath(
                'tei:TEI[1]/tei:teiHeader/tei:fileDesc/tei:titleStmt/'
                'tei:title', namespaces=constants.NAMESPACES)[0].text
        except IndexError:
            pass
        try:
            title_stmt[1].text = root.xpath(
                'tei:TEI[1]/tei:teiHeader/tei:fileDesc/tei:titleStmt/'
                'tei:author', namespaces=constants.NAMESPACES)[0].text
        except IndexError:
            pass
        return root
204094
def from_file(cls, h5_file):
        
        return cls({
            country: HDF5DailyBarReader.from_file(h5_file, country)
            for country in h5_file.keys()
        })
355512
def make_energies_hdu(energy_vals, extname="ENERGIES"):
    
    cols = [fits.Column("Energy", "D", unit='MeV', array=energy_vals)]
    hdu = fits.BinTableHDU.from_columns(cols, name=extname)
    return hdu
871731
def headers(self):
        '''  '''
        self.__dict__['headers'] = hdict = HeaderDict()
        hdict.dict = self._headers
        return hdict
247111
function privCheckFileHeaders(&$p_local_header, &$p_central_header)
  {
    $v_result=1;

  	// ----- Check the static values
  	// TBC
  	if ($p_local_header['filename'] != $p_central_header['filename']) {
  	}
  	if ($p_local_header['version_extracted'] != $p_central_header['version_extracted']) {
  	}
  	if ($p_local_header['flag'] != $p_central_header['flag']) {
  	}
  	if ($p_local_header['compression'] != $p_central_header['compression']) {
  	}
  	if ($p_local_header['mtime'] != $p_central_header['mtime']) {
  	}
  	if ($p_local_header['filename_len'] != $p_central_header['filename_len']) {
  	}
  
  	// ----- Look for flag bit 3
  	if (($p_local_header['flag'] & 8) == 8) {
          $p_local_header['size'] = $p_central_header['size'];
          $p_local_header['compressed_size'] = $p_central_header['compressed_size'];
          $p_local_header['crc'] = $p_central_header['crc'];
  	}

    // ----- Return
    return $v_result;
  }
575601
def hgh_header(filename, ppdesc):
        
        lines = _read_nlines(filename, 3)

        header = _dict_from_lines(lines[:3], [0, 3, 6])
        summary = lines[0]

        return NcAbinitHeader(summary, **header)
903453
def CheckHeaderFileIncluded(filename, include_state, error):
  """"""

  # Do not check test files
  if filename.endswith('_test.cc') or filename.endswith('_unittest.cc'):
    return

  fileinfo = FileInfo(filename)
  headerfile = filename[0:len(filename) - 2] + 'h'
  if not os.path.exists(headerfile):
    return
  headername = FileInfo(headerfile).RepositoryName()
  first_include = 0
  for section_list in include_state.include_list:
    for f in section_list:
      if headername in f[0] or f[0] in headername:
        return
      if not first_include:
        first_include = f[1]

  error(filename, first_include, 'build/include', 5,
        '%s should include its header file %s' % (fileinfo.RepositoryName(),
                                                  headername))
359558
def _read_header(filename):
    
    header = _read_header_text(filename)
    first_row = header[0]
    EXTRA_ROWS = 3  # drop DefaultValue1 LowRange1 HighRange1

    hdr = {}
    for group in finditer('(\w*)= ([\w.]*)', first_row):
        hdr[group.group(1)] = group.group(2)

    if first_row.startswith('BCI2000V'):
        VERSION = hdr['BCI2000V']

    else:
        VERSION = '1'
        hdr['DataFormat'] = 'int16'

    for row in header[1:]:
        if row.startswith('['):  # remove '[ ... Definition ]'
            section = row[2:-14].replace(' ', '')

            if section == 'StateVector':
                hdr[section] = []
            else:
                hdr[section] = {} # defaultdict(dict)
            continue

        if row == '':
            continue

        elif section == 'StateVector':
            statevector = {key: value for key, value in list(zip(STATEVECTOR, row.split(' ')))}
            hdr[section].append(statevector)

        else:
            group = match('(?P<subsection>[\w:%]*) (?P<format>\w*) (?P<key>\w*)= (?P<value>.*) // ', row)
            onerow = group.groupdict()

            values = onerow['value'].split(' ')
            if len(values) > EXTRA_ROWS:
                value = ' '.join(onerow['value'].split(' ')[:-EXTRA_ROWS])
            else:
                value = ' '.join(values)

            hdr[section][onerow['key']] = value  # similar to matlab's output

    return hdr
1334116
def create_from_hdu(cls, hdu, ebins):
        
        hpx = HPX.create_from_hdu(hdu, ebins)
        colnames = hdu.columns.names
        cnames = []
        if hpx.conv.convname == 'FGST_SRCMAP_SPARSE':
            pixs = hdu.data.field('PIX')
            chans = hdu.data.field('CHANNEL')
            keys = chans * hpx.npix + pixs
            vals = hdu.data.field('VALUE')
            nebin = len(ebins)
            data = np.zeros((nebin, hpx.npix))
            data.flat[keys] = vals
        else:
            for c in colnames:
                if c.find(hpx.conv.colstring) == 0:
                    cnames.append(c)
            nebin = len(cnames)
            data = np.ndarray((nebin, hpx.npix))
            for i, cname in enumerate(cnames):
                data[i, 0:] = hdu.data.field(cname)

        return cls(data, hpx)
438587
def standard_program_header(self, title, length, line=32768):
        
        self.save_header(self.HEADER_TYPE_BASIC, title, length, param1=line, param2=length)
1211666
def build_header(self, title):
        """"""
        header = ['---',
                  'title: ' + title,
                  'author(s): ' + self.user,
                  'tags: ',
                  'created_at: ' + str(self.date_created),
                  'updated_at: ' + str(self.date_updated),
                  'tldr: ',
                  'thumbnail: ',
                  '---']

        self.out = header + self.out