checks for the top level file, but returns the file that it can actually use
 Params:
 +type+:: type of
353475
def do_hierarchy_templating(type)

      case type
      when 'archive'

        if template_exists?("archive")
          render :template => "themes/#{current_theme}/archive." + get_theme_ext
        elsif template_exists?("category")
          render :template => "themes/#{current_theme}/category." + get_theme_ext
        else
          render :template => "themes/#{current_theme}/page." + get_theme_ext
        end

      when 'category'

        if template_exists?("category")
          render :template => "themes/#{current_theme}/category." + get_theme_ext
        else
          render :template => "themes/#{current_theme}/page." + get_theme_ext
        end

      when 'search'

        if template_exists?("category")
          render :template => "themes/#{current_theme}/search." + get_theme_ext
        else
          render :tempalte => "themes/#{current_theme}/page." + get_theme_ext
        end

      end

    end
499564
def _GetFileSystemTypeFromFileEntry(self, file_entry):
    
    if file_entry.type_indicator != dfvfs_definitions.TYPE_INDICATOR_TSK:
      return file_entry.type_indicator

    # TODO: Implement fs_type in dfVFS and remove this implementation
    # once that is in place.
    file_system = file_entry.GetFileSystem()
    fs_info = file_system.GetFsInfo()
    if fs_info.info:
      type_string = '{0!s}'.format(fs_info.info.ftype)
      if type_string.startswith('TSK_FS_TYPE_'):
        type_string = type_string[12:]
      if type_string.endswith('_DETECT'):
        type_string = type_string[:-7]

    return type_string
948336
def prompt_filetype(args):
    """"""
    valid_types = ('print', 'text', 'csv', 'pdf', 'html')
    if not any(args[x] for x in valid_types):
        try:
            filetype = input('Print or save output as ({0}): '
                             .format(', '.join(valid_types))).lower()
            while filetype not in valid_types:
                filetype = input('Invalid entry. Choose from ({0}): '
                                 .format(', '.join(valid_types))).lower()
        except (KeyboardInterrupt, EOFError):
            return
        args[filetype] = True
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.")
1316221
def _valid_file(self, base, name):
        """"""

        valid = False
        fullpath = os.path.join(base, name)
        if self.file_check is not None and self.compare_file(fullpath[self._base_len:] if self.file_pathname else name):
            valid = True
        if valid and (not self.show_hidden and util.is_hidden(fullpath)):
            valid = False
        return self.on_validate_file(base, name) if valid else valid
1308552
def image?(new_file)
      content_type = model.content_type || new_file.content_type
      content_type.to_s.start_with? "image"
    end
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 + "']")
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'
45851
def IsFileStatEntry(self, original_result):
    """"""
    return (original_result.pathspec.pathtype in [
        rdf_paths.PathSpec.PathType.OS, rdf_paths.PathSpec.PathType.TSK
    ])
949810
def files_type(request, fstype=None):
    """"""
    try:
        host = Host.objects.get(code=fstype)
    except Host.DoesNotExist:
        messages.error(request, "Could not find host in database.")
        return redirect("files")

    if host.available_to_all:
        pass
    elif not host.visible_to(request.user):
        messages.error(request, "You don't have permission to access this host.")
        return redirect("files")

    authinfo = get_authinfo(request)

    if not authinfo:
        return redirect("{}?next={}".format(reverse("files_auth"), request.get_full_path()))

    try:
        sftp = create_session(host.address, authinfo["username"], authinfo["password"])
    except exceptions as e:
        messages.error(request, e)
        error_msg = str(e).lower()
        if "authentication" in error_msg:
            return redirect("files_auth")
        return redirect("files")
    finally:
        # Delete the stored credentials, so they aren't mistakenly used or
        # accessed later.
        del authinfo

    if host.directory:
        host_dir = host.directory
        if "{}" in host_dir:
            host_dir = host_dir.format(request.user.username)
        if "{win}" in host_dir:
            host_dir = windows_dir_format(host_dir, request.user)
            try:
                sftp.chdir(host_dir)
            except exceptions as e:
                if "NoSuchFile" in "{}".format(e):
                    host_dir = "/"
                    try:
                        sftp.chdir(host_dir)
                    except exceptions as e2:
                        messages.error(request, e)
                        messages.error(request, "Root directory: {}".format(e2))
                        return redirect("files")
                    else:
                        messages.error(request, "Unable to access home folder -- showing root directory instead.")
                else:
                    messages.error(request, e)
                    return redirect("files")
        else:
            try:
                sftp.chdir(host_dir)
            except exceptions as e:
                messages.error(request, e)
                return redirect("files")

    default_dir = normpath(sftp.pwd)

    def can_access_path(fsdir):
        return normpath(fsdir).startswith(default_dir)

    if "file" in request.GET:
        # Download file
        filepath = request.GET.get("file")
        filepath = normpath(filepath)
        filebase = os.path.basename(filepath)
        filebase_escaped = re.sub(r"[^\w\s\-\.]", "", filebase).strip()
        if can_access_path(filepath):
            try:
                fstat = sftp.stat(filepath)
            except exceptions as e:
                messages.error(request, "Unable to access {}: {}".format(filebase, e))
                return redirect("/files/{}?dir={}".format(fstype, os.path.dirname(filepath)))

            if fstat.st_size > settings.FILES_MAX_DOWNLOAD_SIZE:
                messages.error(request, "Too large to download (>200MB)")
                return redirect("/files/{}?dir={}".format(fstype, os.path.dirname(filepath)))

            tmpfile = tempfile.TemporaryFile(prefix="ion_filecenter_{}_{}".format(request.user.username, filebase_escaped))
            logger.debug(tmpfile)

            try:
                sftp.getfo(filepath, tmpfile)
            except exceptions as e:
                messages.error(request, e)
                return redirect("/files/{}?dir={}".format(fstype, os.path.dirname(filepath)))

            content_len = tmpfile.tell()
            tmpfile.seek(0)
            chunk_size = 8192
            response = StreamingHttpResponse(FileWrapper(tmpfile, chunk_size), content_type="application/octet-stream")
            response['Content-Length'] = content_len
            response["Content-Disposition"] = "attachment; filename={}".format(filebase_escaped)
            return response

    fsdir = request.GET.get("dir")
    if fsdir:
        fsdir = normpath(fsdir)
        if can_access_path(fsdir):
            try:
                sftp.chdir(fsdir)
            except exceptions as e:
                messages.error(request, e)
                return redirect("files")
        else:
            messages.error(request, "Access to the path you provided is restricted.")
            return redirect("/files/{}/?dir={}".format(fstype, default_dir))

    if "zip" in request.GET:
        dirbase_escaped = os.path.basename(fsdir)
        dirbase_escaped = slugify(dirbase_escaped)
        tmpfile = tempfile.TemporaryFile(prefix="ion_filecenter_{}_{}".format(request.user.username, dirbase_escaped))

        with tempfile.TemporaryDirectory(prefix="ion_filecenter_{}_{}_zip".format(request.user.username, dirbase_escaped)) as tmpdir:
            remote_directories = [fsdir]
            totalsize = 0
            while remote_directories:
                rd = remote_directories.pop()
                try:
                    remotelist = sftp.listdir(rd)
                except PermissionError as e:
                    logger.debug("Exception %s on %s" % (e, rd))
                    continue
                for item in remotelist:
                    itempath = os.path.join(rd, item)
                    try:
                        fstat = sftp.stat(itempath)
                    except exceptions as e:
                        logger.debug("Could not read %s: %s" % (item, e))
                        continue

                    if stat.S_ISDIR(fstat.st_mode):
                        remote_directories.append(itempath)
                        continue

                    totalsize += fstat.st_size
                    if totalsize > settings.FILES_MAX_DOWNLOAD_SIZE:
                        messages.error(request, "Too large to download (>200MB)")
                        return redirect("/files/{}?dir={}".format(fstype, os.path.dirname(fsdir)))

                    try:
                        localpath = os.path.join(tmpdir, os.path.relpath(rd, fsdir))
                        if not os.path.exists(localpath):
                            os.makedirs(localpath)
                        with open(os.path.join(localpath, item), "wb") as fh:
                            sftp.getfo(itempath, fh)
                    except exceptions as e:
                        logger.debug("Exception %s on %s" % (e, item))
                        continue

            with zipfile.ZipFile(tmpfile, "w", zipfile.ZIP_DEFLATED) as zf:
                for root, dirs, files in os.walk(tmpdir):
                    for f in files:
                        zf.write(os.path.join(root, f), os.path.join(os.path.relpath(root, tmpdir), f))

        content_len = tmpfile.tell()
        tmpfile.seek(0)
        chunk_size = 8192
        response = StreamingHttpResponse(FileWrapper(tmpfile, chunk_size), content_type="application/octet-stream")
        response["Content-Length"] = content_len
        if not dirbase_escaped:
            dirbase_escaped = "files"
        response["Content-Disposition"] = "attachment; filename={}".format(dirbase_escaped + ".zip")
        return response

    try:
        listdir = sftp.listdir()
    except exceptions as e:
        messages.error(request, e)
        listdir = []
    files = []
    for f in listdir:
        if not f.startswith("."):
            try:
                fstat = sftp.stat(f)
            except exceptions:
                # If we can't stat the file, don't show it
                continue
            files.append({
                "name": f,
                "folder": sftp.isdir(f),
                "stat": fstat,
                "stat_mtime": datetime.datetime.fromtimestamp(int(fstat.st_mtime or 0)),
                "too_big": fstat.st_size > settings.FILES_MAX_DOWNLOAD_SIZE
            })

    logger.debug(files)

    current_dir = normpath(sftp.pwd)  # current directory
    dir_list = current_dir.split("/")
    if len(dir_list) > 1 and len(dir_list[-1]) == 0:
        dir_list.pop()
    parent_dir = "/".join(dir_list[:-1])

    if len(parent_dir) == 0:
        parent_dir = "/"

    files = sorted(files, key=lambda f: (not f["folder"], f["name"]))

    context = {
        "host": host,
        "files": files,
        "current_dir": current_dir,
        "parent_dir": parent_dir if can_access_path(parent_dir) else None,
        "max_download_mb": (settings.FILES_MAX_DOWNLOAD_SIZE / 1024 / 1024)
    }

    return render(request, "files/directory.html", context)
22880
def check(path)
      raise FileNotFoundError, "#{path}: no such file" unless File.exist?(path)

      valid = false
      unless disable_extension_check
        unless check_filename(path)
          errors[path] = ['File extension must be .yaml or .yml']
          return valid
        end
      end

      File.open(path, 'r') do |f|
        error_array = []
        valid = check_data(f.read, error_array)
        errors[path] = error_array unless error_array.empty?
      end

      valid
    end
595400
def file_is_image?(file)
      return unless file && file.respond_to?(:url)
      return file.content_type.start_with? "image" if file.content_type.present?
      Mime::Type.lookup_by_extension(File.extname(file.url)[1..-1]).to_s.start_with? "image" if file.url.present?
    end
1199420
def _CheckIsFile(self, file_entry):
    
    if definitions.FILE_ENTRY_TYPE_FILE not in self._file_entry_types:
      return False
    return file_entry.IsFile()
577309
def has_open_file(self, file_object):
        
        return (file_object in [wrappers[0].get_object()
                                for wrappers in self.open_files if wrappers])
983722
def regular_file() -> Callable:
    

    def check_regular_file(value_to_check):
        value_to_check = str(value_to_check)
        if not os.path.isfile(value_to_check):
            raise argparse.ArgumentTypeError("must exist and be a regular file.")
        return value_to_check

    return check_regular_file
1281067
private int getFileType(String typeInfo) {
        switch (typeInfo) {
            case "ASCII":
                return FTP.ASCII_FILE_TYPE;
            case "BINARY":
                return FTP.BINARY_FILE_TYPE;
            case "EBCDIC":
                return FTP.EBCDIC_FILE_TYPE;
            case "LOCAL":
                return FTP.LOCAL_FILE_TYPE;
            default:
                return FTP.BINARY_FILE_TYPE;
        }
    }
419715
def _CheckIsPipe(self, file_entry):
    
    if definitions.FILE_ENTRY_TYPE_PIPE not in self._file_entry_types:
      return False
    return file_entry.IsPipe()