Return the filetype guessed for a buffer
        :param buffer: bytes
        :return: str of filetype
323877
def _get_file_magic_name(self, buffer):
        
        default = "Unknown"
        ftype = None

        try:
            # Magic is optional
            import magic
        except ImportError:
            return default

        try:
            # There are several implementations of magic,
            # unfortunately all called magic
            # We use this one: https://github.com/ahupp/python-magic/
            getattr(magic, "MagicException")
        except AttributeError:
            # Looks like no magic was installed
            return default

        try:
            ftype = magic.from_buffer(buffer[:1024])
        except magic.MagicError as e:
            log.exception("Error getting the magic type!")
            return default

        if not ftype:
            return default
        else:
            return self._patch_magic(buffer, ftype)
377783
def _guess_file_type(self, filename):
        

        # First attempt to guess from the file name.
        namelc = filename.lower()

        if namelc.endswith('.fits') or namelc.endswith('.fit'):
            return 'fits'
        elif namelc.endswith('.json'):
            return 'json'
        elif namelc.endswith('.txt') or namelc.endswith('.ascii'):
            return 'ascii'

        # Otherwise, if the file exists, look at the first character.
        if isfile(filename):
            with open(filename, 'r') as f:
                c = f.read(1)

            if c == 'S':
                return 'fits'
            elif c == '{':
                return 'json'
            elif c.isdigit():
                return 'ascii'

        raise ValueError('Unable to determine format of {0}'.format(filename))
1085245
def parse_buffer_to_jpeg(data):
    

    return [
        Image.open(BytesIO(image_data + b'\xff\xd9'))
        for image_data in data.split(b'\xff\xd9')[:-1] # Last element is obviously empty
    ]
218384
def determine_package_type(filename, args):
    
    if args.package_type:
        package_type = args.package_type
    else:
        logger.info('Detecting file type...')

        package_type = detect_package_type(filename)

        if package_type is None:
            message = 'Could not detect package type of file %r please specify package type with option --package-type' % filename
            logger.error(message)
            raise errors.BinstarError(message)

        logger.info('File type is "%s"', package_type)

    return package_type
481320
def determine_type(filename):
    ''''''
    ftype = magic.from_file(filename, mime=True).decode('utf8')
    if ftype == 'text/plain':
        ftype = 'text'
    elif ftype == 'image/svg+xml':
        ftype = 'svg'
    else:
        ftype = ftype.split('/')[1]
    return ftype
1278516
function type(buffer) {
    if (buffer[0] === 0x89 && buffer[1] === 0x50 && buffer[2] === 0x4E &&
        buffer[3] === 0x47 && buffer[4] === 0x0D && buffer[5] === 0x0A &&
        buffer[6] === 0x1A && buffer[7] === 0x0A) {
        return 'png';
    } else if (buffer[0] === 0xFF && buffer[1] === 0xD8 &&
        buffer[buffer.length - 2] === 0xFF && buffer[buffer.length - 1] === 0xD9) {
        return 'jpg';
    } else if (buffer[0] === 0x47 && buffer[1] === 0x49 && buffer[2] === 0x46 &&
        buffer[3] === 0x38 && (buffer[4] === 0x39 || buffer[4] === 0x37) &&
        buffer[5] === 0x61) {
        return 'gif';
    } else if (buffer[0] === 0x52 && buffer[1] === 0x49 && buffer[2] === 0x46 && buffer[3] === 0x46 &&
        buffer[8] === 0x57 && buffer[9] === 0x45 && buffer[10] === 0x42 && buffer[11] === 0x50) {
        return 'webp';
    // deflate: recklessly assumes contents are PBF.
    } else if (buffer[0] === 0x78 && buffer[1] === 0x9C) {
        return 'pbf';
    // gzip: recklessly assumes contents are PBF.
    } else if (buffer[0] === 0x1F && buffer[1] === 0x8B) {
        return 'pbf';
    }
    return false;
}
334976
def determine_file_type(filename):
    
    if filename.endswith('.cls'):
        return FileType.CLS
    elif filename.endswith('.go'):
        return FileType.GO
    elif filename.endswith('.java'):
        return FileType.JAVA
    elif filename.endswith('.js'):
        return FileType.JAVASCRIPT
    elif filename.endswith('.php'):
        return FileType.PHP
    elif filename.endswith('.py'):
        return FileType.PYTHON
    elif (
        filename.endswith(
            ('.yaml', '.yml'),
        )
    ):
        return FileType.YAML
    return FileType.OTHER
721649
def check_file_type(files):
   
   all_are_fasta = True
   all_are_reads = True
   all_are_empty = True
   if sys.version_info < (3, 0):
      if isinstance(files, (str, unicode)): files = [files]
   else:
      if isinstance(files, str): files = [files]
   for file_ in files:
      debug.log('Checking file type: %s'%file_)
      # Check if file is empty
      if os.stat(file_).st_size == 0: continue
      else: all_are_empty = False
      with open_(file_) as f:
         fc = f.readline()[0]
         if fc != "@": all_are_reads = False
         if fc != ">": all_are_fasta = False
   if all_are_empty:   return 'empty'
   elif all_are_fasta: return 'fasta'
   elif all_are_reads: return 'fastq'
   else: return 'other'
401022
def get_files_types(self):
        
        if self._files == {}:
            # Generate File Types / CRC List
            for i in self.get_files():
                buffer = self._get_crc32(i)
                self._files[i] = self._get_file_magic_name(buffer)

        return self._files
204337
def get_files_types(self):
        
        if self._files == {}:
            # Generate File Types / CRC List
            for i in self.get_files():
                buffer = self.zip.read(i)
                self.files_crc32[i] = crc32(buffer)
                # FIXME why not use the crc from the zipfile?
                # should be validated as well.
                # crc = self.zip.getinfo(i).CRC
                self._files[i] = self._get_file_magic_name(buffer)

        return self._files
849457
def SignBuffer(self, in_buffer):
    
    precondition.AssertType(in_buffer, bytes)
    with tempfile.NamedTemporaryFile() as temp_in:
      temp_in.write(in_buffer)
      temp_in.seek(0)
      outfile = self.SignFile(temp_in.name)
      with io.open(outfile, "rb") as filedesc:
        return filedesc.read()
387295
def guess_type_tag(self, input_bytes, filename):
        
        mime_to_type = {'application/jar': 'jar',
                        'application/java-archive': 'jar',
                        'application/octet-stream': 'data',
                        'application/pdf': 'pdf',
                        'application/vnd.ms-cab-compressed': 'cab',
                        'application/vnd.ms-fontobject': 'ms_font',
                        'application/vnd.tcpdump.pcap': 'pcap',
                        'application/x-dosexec': 'exe',
                        'application/x-empty': 'empty',
                        'application/x-shockwave-flash': 'swf',
                        'application/xml': 'xml',
                        'application/zip': 'zip',
                        'image/gif': 'gif',
                        'text/html': 'html',
                        'image/jpeg': 'jpg',
                        'image/png': 'png',
                        'image/x-icon': 'icon',
                        'text/plain': 'txt'
                        }

        # See what filemagic can determine
        with magic.Magic(flags=magic.MAGIC_MIME_TYPE) as mag:
            mime_type = mag.id_buffer(input_bytes[:1024])
            if mime_type in mime_to_type:
                type_tag = mime_to_type[mime_type]

                # If we get 'data' back look at the filename
                if type_tag == 'data':
                    print 'Info: File -- Trying to Determine Type from filename...'
                    ext = os.path.splitext(filename)[1][1:]
                    if ext in ['mem','vmem']:
                        type_tag = 'mem'
                    else:
                        print 'Alert: Failed to Determine Type for %s' % filename
                        exit(1) # Temp
                return type_tag
            else:
                print 'Alert: Sample Type could not be Determined'
                return 'unknown'
384745
def decode_buffer(buffer: dict) -> np.ndarray:
    
    buf = np.frombuffer(buffer['data'], dtype=buffer['dtype'])
    return buf.reshape(buffer['shape'])
270926
def guess_mime_type(self, path):
		
		_, ext = posixpath.splitext(path)
		if ext in self.extensions_map:
			return self.extensions_map[ext]
		ext = ext.lower()
		return self.extensions_map[ext if ext in self.extensions_map else '']
703341
def _get_crc32(self, filename):
        
        buffer = self.zip.read(filename)
        if filename not in self.files_crc32:
            self.files_crc32[filename] = crc32(buffer)
            if self.files_crc32[filename] != self.zip.getinfo(filename).CRC:
                log.error("File '{}' has different CRC32 after unpacking! "
                          "Declared: {:08x}, Calculated: {:08x}".format(filename,
                                                                        self.zip.getinfo(filename).CRC,
                                                                        self.files_crc32[filename]))
        return buffer
23672
def get_content_type(local_file_path)
      png = Regexp.new("\x89PNG".force_encoding("binary"))
      jpg = Regexp.new("\xff\xd8\xff\xe0\x00\x10JFIF".force_encoding("binary"))
      jpg2 = Regexp.new("\xff\xd8\xff\xe1(.*){2}Exif".force_encoding("binary"))
      case IO.read(local_file_path, 10)
      when /^GIF8/
        'image/gif'
      when /^#{png}/
        'image/png'
      when /^#{jpg}/
        'image/jpeg'
      when /^#{jpg2}/
        'image/jpeg'
      else
        if local_file_path.end_with? '.txt'
          'text/plain'
        else
          'application/octet-stream'
        end
        # mime_type = `file #{local_file_path} --mime-type`.gsub("\n", '') # Works on linux and mac
        # raise UnprocessableEntity, "unknown file type" if !mime_type
        # mime_type.split(':')[1].split('/')[1].gsub('x-', '').gsub(/jpeg/, 'jpg').gsub(/text/, 'txt').gsub(/x-/, '')
      end
    end
435978
def get_mimetype(path):
        
        filename = os.path.split(path)[1]
        mimetype = mimetypes.guess_type(filename)[0]
        if mimetype is None:
            mimetype = 'text/x-plain'
        _logger().debug('mimetype detected: %s', mimetype)
        return mimetype