Builds and returns a FITs HDU with input data

        data      : The data begin stored

        Keyword arguments
        -------------------
        extname   : The HDU extension name        
        colbase   : The prefix for column names
163024
def make_hdu(self, data, **kwargs):
        
        shape = data.shape
        extname = kwargs.get('extname', self.conv.extname)

        if shape[-1] != self._npix:
            raise Exception(
                "Size of data array does not match number of pixels")
        cols = []

        if self._ipix is not None:
            cols.append(fits.Column(self.conv.idxstring, "J", array=self._ipix))

        if self.conv.convname == 'FGST_SRCMAP_SPARSE':
            nonzero = data.nonzero()
            nfilled = len(nonzero[0])
            if len(shape) == 1:
                cols.append(fits.Column("PIX", "J", array=nonzero[0].astype(int)))
                cols.append(fits.Column("VALUE", "E", array=data.flat[nonzero].astype(float).reshape(nfilled)))
            elif len(shape) == 2:
                keys = self._npix * nonzero[0] + nonzero[1]
                cols.append(fits.Column("PIX", "J", array=nonzero[1].reshape(nfilled)))
                cols.append(fits.Column("CHANNEL", "I", array=nonzero[0].reshape(nfilled)))
                cols.append(fits.Column("VALUE", "E",
                                        array=data.flat[keys].astype(float).reshape(nfilled)))
            else:
                raise Exception("HPX.write_fits only handles 1D and 2D maps")

        else:
            if len(shape) == 1:
                cols.append(fits.Column(self.conv.colname(
                    indx=self.conv.firstcol), "E", array=data.astype(float)))
            elif len(shape) == 2:
                for i in range(shape[0]):
                    cols.append(fits.Column(self.conv.colname(
                        indx=i + self.conv.firstcol), "E", array=data[i].astype(float)))
            else:
                raise Exception("HPX.write_fits only handles 1D and 2D maps")

        header = self.make_header()
        hdu = fits.BinTableHDU.from_columns(cols, header=header, name=extname)

        return hdu
985203
def create_from_hdulist(cls, hdulist, **kwargs):
        
        extname = kwargs.get('hdu', hdulist[1].name)
        ebins = fits_utils.find_and_read_ebins(hdulist)
        return cls.create_from_hdu(hdulist[extname], ebins)
331028
def get_file_type(filename):
    
    txt_extensions = [".txt", ".dat", ".csv"]
    hdf_extensions = [".hdf", ".h5", ".bkup", ".checkpoint"]
    for ext in hdf_extensions:
        if filename.endswith(ext):
            with _h5py.File(filename, 'r') as fp:
                filetype = fp.attrs['filetype']
            return filetypes[filetype]
    for ext in txt_extensions:
        if filename.endswith(ext):
            return InferenceTXTFile
    raise TypeError("Extension is not supported.")
967516
def extend_relations(self, data, kind):
        
        # 'data' is a generator object. It can throw an exception while being
        # consumed. This could happen if the user has launched the app without
        # specifying a database name. This exception must be handled to prevent
        # crashing.
        try:
            data = [self.escaped_names(d) for d in data]
        except Exception:
            data = []

        # dbmetadata['tables'][$schema_name][$table_name] should be a list of
        # column names. Default to an asterisk
        metadata = self.dbmetadata[kind]
        for relname in data:
            try:
                metadata[self.dbname][relname[0]] = ['*']
            except KeyError:
                _logger.error('%r %r listed in unrecognized schema %r',
                              kind, relname[0], self.dbname)
            self.all_completions.add(relname[0])
859637
def build_extension_item(name: str, parameters: List[ExtensionParameter]) -> str:
    
    return "; ".join(
        [name]
        + [
            # Quoted strings aren't necessary because values are always tokens.
            name if value is None else f"{name}={value}"
            for name, value in parameters
        ]
    )
430295
def colname_gen(df,col_name = 'unnamed_col'):
    
    if col_name not in df.keys():
        yield col_name
    id_number = 0
    while True:
        col_name = col_name + str(id_number)
        if col_name in df.keys():
            id_number+=1
        else:
            return col_name
1227518
def make_exploded_column(df, colname_new, colname_old):
    
    s = df[colname_old].apply(pd.Series).stack()
    s.name = colname_new
    return s
1243361
protected Extensions get(String extensionName, String tableName,
			String columnName) {

		Extensions extension = null;
		try {
			if (extensionsDao.isTableExists()) {
				extension = extensionsDao.queryByExtension(extensionName,
						tableName, columnName);
			}
		} catch (SQLException e) {
			throw new GeoPackageException("Failed to query for '"
					+ extensionName + "' extension for GeoPackage: "
					+ geoPackage.getName() + ", Table Name: " + tableName
					+ ", Column Name: " + columnName, e);
		}
		return extension;
	}
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
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)
667157
def make_energy_bounds_hdu(self, extname="EBOUNDS"):
        
        if self._ebins is None:
            return None
        cols = [fits.Column("CHANNEL", "I", array=np.arange(1, len(self._ebins + 1))),
                fits.Column("E_MIN", "1E", unit='keV',
                            array=1000 * self._ebins[0:-1]),
                fits.Column("E_MAX", "1E", unit='keV', array=1000 * self._ebins[1:])]
        hdu = fits.BinTableHDU.from_columns(
            cols, self.make_header(), name=extname)
        return hdu
648808
def getKeyword(filename, keyword, default=None, handle=None):
    
    # Insure that there is at least 1 extension specified...
    if filename.find('[') < 0:
        filename += '[0]'

    _fname, _extn = parseFilename(filename)

    if not handle:
        # Open image whether it is FITS or GEIS
        _fimg = openImage(_fname)
    else:
        # Use what the user provides, after insuring
        # that it is a proper PyFITS object.
        if isinstance(handle, fits.HDUList):
            _fimg = handle
        else:
            raise ValueError('Handle must be %r object!' % fits.HDUList)

    # Address the correct header
    _hdr = getExtn(_fimg, _extn).header

    try:
        value =  _hdr[keyword]
    except KeyError:
        _nextn = findKeywordExtn(_fimg, keyword)
        try:
            value = _fimg[_nextn].header[keyword]
        except KeyError:
            value = ''

    if not handle:
        _fimg.close()
        del _fimg

    if value == '':
        if default is None:
            value = None
        else:
            value = default

    # NOTE:  Need to clean up the keyword.. Occasionally the keyword value
    # goes right up to the "/" FITS delimiter, and iraf.keypar is incapable
    # of realizing this, so it incorporates "/" along with the keyword value.
    # For example, after running "pydrizzle" on the image "j8e601bkq_flt.fits",
    # the CD keywords look like this:
    #
    #   CD1_1   = 9.221627430999639E-06/ partial of first axis coordinate w.r.t. x
    #   CD1_2   = -1.0346992614799E-05 / partial of first axis coordinate w.r.t. y
    #
    # so for CD1_1, iraf.keypar returns:
    #       "9.221627430999639E-06/"
    #
    # So, the following piece of code CHECKS for this and FIXES the string,
    # very simply by removing the last character if it is a "/".
    # This fix courtesy of Anton Koekemoer, 2002.
    elif isinstance(value, string_types):
        if value[-1:] == '/':
            value = value[:-1]

    return value
731091
def _sql_expand_insert(self, spec, key_prefix = '', col_prefix = ''):
        
        col = list(spec)
        sql = '('
        sql += ', '.join(col_prefix + key for key in col)
        sql += ') VALUES ('
        sql += ', '.join('%(' + key_prefix + key + ')s' for key in col)
        sql += ')'
        params = {}
        for key in spec:
            params[key_prefix + key] = spec[key]

        return sql, params
730122
def format_name_for_ext(metadata, ext, cm_default_formats=None, explicit_default=True):
    """"""
    # Is the format information available in the text representation?
    text_repr = metadata.get('jupytext', {}).get('text_representation', {})
    if text_repr.get('extension', '').endswith(ext) and text_repr.get('format_name'):
        return text_repr.get('format_name')

    # Format from jupytext.formats
    formats = metadata.get('jupytext', {}).get('formats', '') or cm_default_formats
    formats = long_form_multiple_formats(formats)
    for fmt in formats:
        if fmt['extension'] == ext:
            if (not explicit_default) or fmt.get('format_name'):
                return fmt.get('format_name')

    if (not explicit_default) or ext in ['.Rmd', '.md']:
        return None

    return get_format_implementation(ext).format_name
676338
def findKeywordExtn(ft, keyword, value=None):
    

    i = 0
    extnum = -1
    # Search through all the extensions in the FITS object
    for chip in ft:
        hdr = chip.header
        # Check to make sure the extension has the given keyword
        if keyword in hdr:
            if value is not None:
                # If it does, then does the value match the desired value
                # MUST use 'str.strip' to match against any input string!
                if hdr[keyword].strip() == value:
                    extnum = i
                    break
            else:
                extnum = i
                break
        i += 1
    # Return the index of the extension which contained the
    # desired EXTNAME value.
    return extnum
257578
def movnam_hdu(self, extname, hdutype=ANY_HDU, extver=0):
        
        extname = mks(extname)
        hdu = self._FITS.movnam_hdu(hdutype, extname, extver)
        return hdu
714303
def _col_name(index):
    
    for exp in itertools.count(1):
        limit = 26 ** exp
        if index < limit:
            return ''.join(chr(ord('A') + index // (26 ** i) % 26) for i in range(exp-1, -1, -1))
        index -= limit