Detects the format of a network data file according to the
        file extension and the header.
345669
def detect_data_file(input, file_name=""):
    
    _, ext = os.path.splitext(file_name)

    if ext == ".m":
        line = input.readline() # first line
        if line.startswith("function"):
            type = "matpower"
            logger.info("Recognised MATPOWER data file.")
        elif line.startswith("Bus.con" or line.startswith("%")):
            type = "psat"
            logger.info("Recognised PSAT data file.")
        else:
            type = "unrecognised"
        input.seek(0) # reset buffer for parsing

    elif (ext == ".raw") or (ext == ".psse"):
        type = "psse"
        logger.info("Recognised PSS/E data file.")

    elif (ext == ".pkl") or (ext == ".pickle"):
        type = "pickle"
        logger.info("Recognised pickled case.")

    else:
        type = None

    return type
163589
def determine_packet_positions(self):
        """"""
        print("Analysing file...")
        self.rewind_file()
        with ignored(struct.error):
            while True:
                pointer_position = self.blob_file.tell()
                length = struct.unpack('<i', self.blob_file.read(4))[0]
                self.packet_positions.append(pointer_position)
                self.blob_file.seek(length, 1)
        self.rewind_file()
        print("Found {0} CLB UDP packets.".format(len(self.packet_positions)))
775972
def get_anchor_format(a):
    

    # (. or format=) then (file_extension) then (? or $)
    # e.g. "...format=txt" or "...download.mp4?..."
    fmt = re.search(r"(?:\.|format=)(\w+)(?:\?.*)?$", a)
    return fmt.group(1) if fmt else None
556786
def _get_content_type(self, filename):
        
        mntype = mimetypes.guess_type(filename)[0]
        filename, fileExtension = os.path.splitext(filename)
        if mntype is None and\
            fileExtension.lower() == ".csv":
            mntype = "text/csv"
        elif mntype is None and \
            fileExtension.lower() == ".sd":
            mntype = "File/sd"
        elif mntype is None:
            #mntype = 'application/octet-stream'
            mntype= "File/%s" % fileExtension.replace('.', '')
        return mntype
960726
def get_file_extension(filepath):
    
    _ext = os.path.splitext(filepath)[-1]
    if _ext:
        return _ext[1:] if _ext.startswith('.') else _ext

    return ''
31834
function (type, data) {
  if (type === 'size') {
    return `File size should be less than ${bytes(data.size)}`
  }

  if (type === 'type') {
    const verb = data.types.length === 1 ? 'is' : 'are'
    return `Invalid file type ${data.subtype} or ${data.type}. Only ${data.types.join(', ')} ${verb} allowed`
  }

  if (type === 'extname') {
    const verb = data.extnames.length === 1 ? 'is' : 'are'
    return `Invalid file extension ${data.extname}. Only ${data.extnames.join(', ')} ${verb} allowed`
  }
}
816383
public static String fileExtensionForMIMEType(String mimeType) {
        loadMappings();

        String ext = mimeTypeToExtensionMap.get(mimeType);

        if (ext == null) ext = "dat";

        return ext;
    }
349251
def determine_file_type(self, z):
        """"""

        mimetype = z.read('mimetype').decode('utf-8').strip()
        self.type = MIMEMAP[mimetype]
354998
def detect_file(filename):
    """"""
    image_format = get_image_format(filename)

    if image_format in Settings.formats:
        return image_format

    if image_format in (NONE_FORMAT, ERROR_FORMAT):
        return None

    if Settings.verbose > 1 and not Settings.list_only:
        print(filename, image_format, 'is not a enabled image or '
              'comic archive type.')
    return None
388177
function respondWithFile(req, res, path, ifNoFile) {
  ifNoFile = ifNoFile || function() {};
  // We use `documentRoot` as the root wherein we seek files.
  var realpath = protectedPath(req.server.documentRoot, path);
  fs.stat(realpath, function(err, stats) {
    if (err) return ifNoFile();

    if (stats.isDirectory()) {
      realpath = p.join(realpath, 'index.html');
    }
    res.mime(p.extname(realpath).slice(1));

    // Cache management (compare timestamps at second-level precision).
    var lastModified = Math.floor(stats.mtime / 1000);
    var since = req.headers['if-modified-since'];
    if (since && (lastModified <= Math.floor(new Date(since) / 1000))) {
      res.statusCode = 304; // not modified.
      res.end();
      return;
    }
    res.setHeader('Last-Modified', stats.mtime.toUTCString());

    // Connect the output of the file to the network!
    var raw = fs.createReadStream(realpath);
    raw.on('error', function(err) {
      log(err.stack, 'error');
      res.statusCode = 404;
      res.end('Not Found\n');
    });
    raw.pipe(res.compressed());
  });
}
143937
def infer_format(filename:str) -> str:
    """"""
    _, ext = os.path.splitext(filename)
    return ext
312040
def _read_file_header(self):
        """"""
        header = self.fileobj.readline()
        payload1 = self.fileobj.readline()
        payload2 = self.fileobj.readline()
        version, reserved, organisation = payload1.split(None, 2)
        self.fileobj.readline() # Lose the separator newline
        self.header_read = True
        # print "--------------------------------------------------"
        # print header,"\n", payload1, "\n", payload2,"\n"
        # print "--------------------------------------------------"
        if self.version and int(self.version) != version:
            raise IOError("Version mismatch. Requested version was '%s' but version in file was '%s'"%(self.version, version))
        
        if version == '1':
            url, ip_address, date, content_type, length = header.split()
            self.file_headers = {"ip_address" : ip_address,
                                 "date" : datetime.datetime.strptime(date, "%Y%m%d%H%M%S"),
                                 "org" : organisation}
            self.version = 1
        elif version == '2':
            url, ip_address, date, content_type, result_code, checksum, location, offset, filename, length  = header.split()
            self.file_headers = {"ip_address" : ip_address,
                                 "date" : datetime.datetime.strptime(date, "%Y%m%d%H%M%S"),
                                 "org" : organisation}
            self.version = 2
        else:
            raise IOError("Unknown ARC version '%s'"%version)
161370
def get_file_extension(format_):
    """"""
    if format_ not in FORMAT_IDENTIFIER_TO_FORMAT_CLASS:
        raise UnknownFormatIdentifierError(format_)

    for ext, f in FILE_EXTENSION_TO_FORMAT_IDENTIFIER.items():
        if f == format_:
            return ext

    raise RuntimeError("No file extension for format %r" % format_)
624568
public String guessContentTypeFromFile(File file) {
        String contentType = URLConnection.guessContentTypeFromName(file.getName());
        if (contentType == null) {
            return "application/octet-stream";
        } else {
            return contentType;
        }
    }
558751
private static String getFileExtension(final String filename) {

		String extension = "";
		int i = filename.lastIndexOf('.');
		int p = Math.max(filename.lastIndexOf('/'), filename.lastIndexOf('\\'));
		if (i > p)
			extension = filename.substring(i+1);

		return extension;
	}
1033548
def is_likely_link(text):
    '''
    '''
    text = text.lower()

    # Check for absolute or relative URLs
    if (
        text.startswith('http://')
        or text.startswith('https://')
        or text.startswith('ftp://')
        or text.startswith('/')
        or text.startswith('//')
        or text.endswith('/')
        or text.startswith('../')
    ):
        return True

    # Check if it has a alphanumeric file extension and not a decimal number
    dummy, dot, file_extension = text.rpartition('.')

    if dot and file_extension and len(file_extension) <= 4:
        file_extension_set = frozenset(file_extension)

        if file_extension_set \
           and file_extension_set <= ALPHANUMERIC_CHARS \
           and not file_extension_set <= NUMERIC_CHARS:
            if file_extension in COMMON_TLD:
                return False

            file_type = mimetypes.guess_type(text, strict=False)[0]

            if file_type:
                return True
            else:
                return False
1279009
def has_extensions(self, *exts):
        """"""
        file_ext = splitext(self.filename)[1]
        file_ext = file_ext.lower()

        for e in exts:
            if file_ext == e:
                return True
        return False