Scan the buffer for modelines and return filetype if one is found.
347404
def get_filetype_from_buffer(buf, max_lines=5):
    
    lines = buf.splitlines()
    for l in lines[-1:-max_lines-1:-1]:
        ret = get_filetype_from_line(l)
        if ret:
            return ret
    for i in range(max_lines, -1, -1):
        if i < len(lines):
            ret = get_filetype_from_line(lines[i])
            if ret:
                return ret

    return None
694981
def _text_or_file(input_):
    '''
    
    '''
    if _isfile(input_):
        with salt.utils.files.fopen(input_) as fp_:
            out = salt.utils.stringutils.to_str(fp_.read())
    else:
        out = salt.utils.stringutils.to_str(input_)

    return out
442819
def file_type(filename, param='rb'):
    """"""
    magic_dict = {
        b"\x1f\x8b\x08": "gz",
        b"\x42\x5a\x68": "bz2",
        b"\x50\x4b\x03\x04": "zip"
    }
    if param.startswith('w'):
        return filename.split('.')[-1]
    max_len = max(len(x) for x in magic_dict)
    with open(filename, 'rb') as f:
        file_start = f.read(max_len)
    for magic, filetype in list(magic_dict.items()):
        if file_start.startswith(magic):
            return filetype
    return "no match"
77357
def guess_filetype(filepath):
    """"""
    # If we have python-magic, use it to determine file type
    typ = None

    # Some specific checks for known file suffixes
    _fn = filepath.lower()
    _name, _ext = os.path.splitext(_fn)
    if _ext in known_types:
        typ = known_types[_ext]

    if typ is None and have_magic:
        try:
            # it seems there are conflicting versions of a 'magic'
            # module for python floating around...*sigh*
            if hasattr(magic, 'from_file'):
                typ = magic.from_file(filepath, mime=True)

            elif magic_tester is not None:
                descrip = magic_tester.file(filepath)
                if descrip.startswith("FITS image data"):
                    return ('image', 'fits')

        except Exception as e:
            pass

    if typ is None:
        # if no magic, or magic fails, fall back to mimetypes
        try:
            typ, enc = mimetypes.guess_type(filepath)

        except Exception as e:
            # fail
            pass

    if typ:
        typ, subtyp = typ.split('/')
        return (typ, subtyp)

    raise ValueError("Can't determine file type of '%s'" % (filepath))
534283
def model_type(dtype):
    ""
    return (torch.float32 if np.issubdtype(dtype, np.floating) else
            torch.int64 if np.issubdtype(dtype, np.integer)
            else None)
1248177
void checkInterfaces(ClassFile cf) throws ConstantPoolException {
        int ni = cf.interfaces.length;
        for (int i = 0; i < ni; i++) {
            String iname = cf.getInterfaceName(i);
            DeprData dd = db.getTypeDeprecated(iname);
            if (dd != null) {
                printType("scan.out.implements", cf, iname, dd.isForRemoval());
            }
        }
    }
106803
def identify_link_type(filename):
    '''
    '''
    mime_type = mimetypes.guess_type(filename)[0]

    if not mime_type:
        return

    if mime_type == 'text/css':
        return LinkType.css
    elif mime_type == 'application/javascript':
        return LinkType.javascript
    elif mime_type == 'text/html' or mime_type.endswith('xml'):
        return LinkType.html
    elif mime_type.startswith('video') or \
            mime_type.startswith('image') or \
            mime_type.startswith('audio') or \
            mime_type.endswith('shockwave-flash'):
        return LinkType.media
1240486
def lookup_model_by_kind(kind):
    
    model = _known_models.get(kind)
    if model is None:
        raise RuntimeError(f"Model for kind {kind!r} not found.")
    return model
1247231
def _guess_content_type(url):
    '''
    
    '''
    OCTET_STREAM = 'application/octet-stream'
    n = url.rfind('.')
    if n == -1:
        return OCTET_STREAM
    return mimetypes.types_map.get(url[n:].lower(), OCTET_STREAM)
929846
def parse_ftype(input_file):
    
    if input_file.endswith(".bam"):
        return "bam"
    elif input_file.endswith(".fastq") or \
            input_file.endswith(".fq") or \
            input_file.endswith(".fq.gz") or \
            input_file.endswith(".fastq.gz"):
        return "fastq"
    else:
        raise TypeError("Type of input file ends in neither '.bam' "
                        "nor '.fastq' [file: '" + input_file + "']")
1088882
def checkParametersInputFile(filename):
    
    fin = open(filename, 'r')
    line = fin.readline()
    line2 = fin.readline()
    fin.close()

    temp = re.split('\s+', line)
    temp2 = re.split('\s+', line2)

    if temp[0] == '#Minor':
        return groovesParameters

    if temp[0] == '#Shift':
        return baseStepParameters

    if temp[0] == '#X-disp':
        return helicalBaseStepParameters

    if temp[0] == '#Shear':
        return basePairParameters

    if temp[0] == '#Position':
        return helicalAxisParameters

    if temp2[0] == '#P':
        return helicalRadiusParameters

    if temp2[0] == '#alpha':
        return backboneDihedrals
1155818
def _need_to_buffer(file_obj, mode, ext):
    """"""
    try:
        is_seekable = file_obj.seekable()
    except AttributeError:
        #
        # Under Py2, built-in file objects returned by open do not have
        # .seekable, but have a .seek method instead.
        #
        is_seekable = hasattr(file_obj, 'seek')
    return six.PY2 and mode.startswith('r') and ext in _COMPRESSOR_REGISTRY and not is_seekable
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.")
1094945
private void tryScanFile() {
        if (!isScanned) {
            synchronized (AssetsWebsite.class) {
                if (!isScanned) {
                    List<String> fileList = mReader.scanFile(mRootPath);
                    for (String filePath : fileList) {
                        String httpPath = filePath.substring(mRootPath.length(), filePath.length());
                        httpPath = addStartSlash(httpPath);
                        mPatternMap.put(httpPath, filePath);

                        String indexFileName = getIndexFileName();
                        if (filePath.endsWith(indexFileName)) {
                            httpPath = filePath.substring(0, filePath.indexOf(indexFileName) - 1);
                            httpPath = addStartSlash(httpPath);
                            mPatternMap.put(httpPath, filePath);
                            mPatternMap.put(addEndSlash(httpPath), filePath);
                        }
                    }
                    isScanned = true;
                }
            }
        }
    }
660626
def load_model(f, format=None, load_external_data=True):  # type: (Union[IO[bytes], Text], Optional[Any], bool) -> ModelProto
    '''
    
    '''
    s = _load_bytes(f)
    model = load_model_from_string(s, format=format)

    if load_external_data:
        model_filepath = _get_file_path(f)
        if model_filepath:
            base_dir = os.path.dirname(model_filepath)
            load_external_data_for_model(model, base_dir)

    return model
904835
def mime(self):
        '''
        
        '''
        return self.metadata['ContentType'] if 'ContentType' in self.metadata else BaseEngine.get_mimetype(self.buffer)
431542
def get_file_type(variant_source):
    
    file_type = 'unknown'
    valid_vcf_suffixes = ('.vcf', '.vcf.gz')
    if variant_source:
        logger.debug("Check file type with file: {0}".format(variant_source))
        if variant_source.endswith('.db'):
            file_type = 'gemini'
            logger.debug("File {0} is a gemini database".format(variant_source))
        elif variant_source.endswith(valid_vcf_suffixes):
            file_type = 'vcf'
            logger.debug("File {0} is a vcf".format(variant_source))
        else:
            logger.debug("File is in a unknown format")
    
    return file_type