Makes sure the correct GD implementation exists for the file type
493991
protected function verifyFormatCompatiblity ()
	{
		$isCompatible 	= true;
		$gdInfo			= gd_info();
		
		switch ($this->format)
		{
			case 'GIF':
				$isCompatible = $gdInfo['GIF Create Support'];
				break;
			case 'JPG':
				$isCompatible = (isset($gdInfo['JPG Support']) || isset($gdInfo['JPEG Support'])) ? true : false;
				break;
			case 'PNG':
				$isCompatible = $gdInfo[$this->format . ' Support'];
				break;
			default:
				$isCompatible = false;
		}
		
		if (!$isCompatible)
		{
			// one last check for "JPEG" instead
			$isCompatible = $gdInfo['JPEG Support'];
			
			if (!$isCompatible)
			{
				$this->triggerError('Your GD installation does not support ' . $this->format . ' image types');
			}
		}
	}
322246
protected void integrityCheck() throws DataStoreException
    {
        try
        {
            //========================
            // 1 - Check files sizes
            //========================
            // -- Allocation table
            long atFileSize = allocationTableRandomAccessFile.length();
            if (atFileSize < AT_HEADER_SIZE+AT_BLOCK_SIZE) /* Should have at least one entry */
                throw new DataStoreException("Allocation table is truncated : "+allocationTableFile.getAbsolutePath());
            
            // Read some header fields
            FileInputStream inFile = new FileInputStream(allocationTableFile);
            DataInputStream in = new DataInputStream(new BufferedInputStream(inFile,16384));
            int blockCount = in.readInt();
            int blockSize  = in.readInt();
            int firstBlock = in.readInt();
            // Fix AT size
            long expectedATFileSize = AT_HEADER_SIZE+AT_BLOCK_SIZE*(long)blockCount;
            if (atFileSize != expectedATFileSize)
            {
                log.error("["+descriptor.getName()+"] Allocation table has an invalid size (actual:"+atFileSize+",expected:"+expectedATFileSize+"), fixing.");
                allocationTableRandomAccessFile.setLength(expectedATFileSize);
            }
            // Fix data size
            long dataFileSize = dataRandomAccessFile.length();
            long expectedDataFileSize = (long)blockSize*blockCount;
            if (dataFileSize != expectedDataFileSize)
            {
                log.error("["+descriptor.getName()+"] Data file has an invalid size (actual:"+dataFileSize+",expected:"+expectedDataFileSize+"), fixing.");
                dataRandomAccessFile.setLength(expectedDataFileSize);
            }
            
            //============================
            // 2 - Check allocation table
            //============================
            // Read the AT into memory
            byte[] flags        = new byte[blockCount];
            int[] allocatedSize = new int[blockCount];
            int[] previousBlock = new int[blockCount];
            int[] nextBlock     = new int[blockCount];
            int blocksInUse = 0;
            int msgCount = 0;
            for (int n = 0 ; n < blockCount ; n++)
            {
                flags[n]         = in.readByte();
                allocatedSize[n] = in.readInt();
                previousBlock[n] = in.readInt();
                nextBlock[n]     = in.readInt();
                if (allocatedSize[n] != -1)
                {
                    blocksInUse++;
                    if ((flags[n] & FLAG_START_BLOCK) > 0)
                        msgCount++;
                }
            }
            in.close();
            log.debug("["+descriptor.getName()+"] Blocks in use before fix : "+blocksInUse);
            log.debug("["+descriptor.getName()+"] Messages count before fix : "+msgCount);
            
            // Fix first block index
            boolean changed = false;
            if (firstBlock < -1 || firstBlock >= blockCount)
            {
                log.error("["+descriptor.getName()+"] Invalid allocation table first block index ("+firstBlock+"), guessing new one ...");
                firstBlock = guessFirstBlockIndex(blockCount, allocatedSize, nextBlock);
                log.debug("["+descriptor.getName()+"] Guessed first block index : "+firstBlock);
                changed = true;
            }
            
            // Recover table
            if (msgCount == 0)
            {
                if (firstBlock == -1)
                {
                    // Table is empty, cleanup dirty entries
                    changed = changed || cleanupEmptyBlocks(blockCount, flags, allocatedSize, previousBlock, nextBlock);
                }
                else
                {
                    log.error("["+descriptor.getName()+"] First block index should be -1, clearing ...");
                    firstBlock = -1;
                    changed = true;
                }
            }
            else
            {
                if (firstBlock == -1)
                {
                    log.error("["+descriptor.getName()+"] Invalid first block index, guessing value ...");
                    firstBlock = guessFirstBlockIndex(blockCount, allocatedSize, nextBlock);
                    log.debug("["+descriptor.getName()+"] Guessed first block index : "+firstBlock);
                    changed = true;
                }
     
                changed = changed || fixBlocks(blockCount, blockSize, firstBlock, flags, allocatedSize, previousBlock, nextBlock);
                changed = changed || cleanupEmptyBlocks(blockCount, flags, allocatedSize, previousBlock, nextBlock);
            }
            
            // Update the allocation file table
            if (changed)
            {
                // Re-compute size
                msgCount = 0;
                blocksInUse = 0;
                for (int n = 0 ; n < blockCount ; n++)
                {
                    if (allocatedSize[n] != -1) 
                    {
                        blocksInUse++;
                        if ((flags[n] & FLAG_START_BLOCK) > 0)
                            msgCount++;
                    }
                }
                log.debug("["+descriptor.getName()+"] Blocks in use after fix : "+blocksInUse);
                log.debug("["+descriptor.getName()+"] Messages count after fix : "+msgCount);
                
                log.debug("["+descriptor.getName()+"] Allocation table was altered, saving ...");
                allocationTableRandomAccessFile.seek(AT_HEADER_FIRSTBLOCK_OFFSET);
                allocationTableRandomAccessFile.writeInt(firstBlock);
                for (int n = 0 ; n < blockCount ; n++)
                {
                    byte[] allocationBlock = new byte[AT_BLOCK_SIZE];

                    // Regroup I/O to improve performance
                    allocationBlock[AB_FLAGS_OFFSET]       = flags[n];
                    allocationBlock[AB_ALLOCSIZE_OFFSET]   = (byte)((allocatedSize[n] >>> 24) & 0xFF);
                    allocationBlock[AB_ALLOCSIZE_OFFSET+1] = (byte)((allocatedSize[n] >>> 16) & 0xFF);
                    allocationBlock[AB_ALLOCSIZE_OFFSET+2] = (byte)((allocatedSize[n] >>>  8) & 0xFF);
                    allocationBlock[AB_ALLOCSIZE_OFFSET+3] = (byte)((allocatedSize[n] >>>  0) & 0xFF);
                    allocationBlock[AB_PREVBLOCK_OFFSET]   = (byte)((previousBlock[n] >>> 24) & 0xFF);
                    allocationBlock[AB_PREVBLOCK_OFFSET+1] = (byte)((previousBlock[n] >>> 16) & 0xFF);
                    allocationBlock[AB_PREVBLOCK_OFFSET+2] = (byte)((previousBlock[n] >>>  8) & 0xFF);
                    allocationBlock[AB_PREVBLOCK_OFFSET+3] = (byte)((previousBlock[n] >>>  0) & 0xFF);
                    allocationBlock[AB_NEXTBLOCK_OFFSET]   = (byte)((nextBlock[n] >>> 24) & 0xFF);
                    allocationBlock[AB_NEXTBLOCK_OFFSET+1] = (byte)((nextBlock[n] >>> 16) & 0xFF);
                    allocationBlock[AB_NEXTBLOCK_OFFSET+2] = (byte)((nextBlock[n] >>>  8) & 0xFF);
                    allocationBlock[AB_NEXTBLOCK_OFFSET+3] = (byte)((nextBlock[n] >>>  0) & 0xFF);
                    
                    allocationTableRandomAccessFile.seek(AT_HEADER_SIZE+n*AT_BLOCK_SIZE);
                    allocationTableRandomAccessFile.write(allocationBlock);
                }
                allocationTableRandomAccessFile.getFD().sync();
            }
            else
                log.debug("["+descriptor.getName()+"] Allocation table was not altered");
        }
        catch (IOException e)
        {
            throw new DataStoreException("Cannot check/fix store integrity : "+e);
        }
    }
855681
function tryAddingExtensions(candidate, extensions, failedLookupLocation, onlyRecordFailures, state) {
        if (!onlyRecordFailures) {
            // check if containing folder exists - if it doesn't then just record failures for all supported extensions without disk probing
            var directory = ts.getDirectoryPath(candidate);
            if (directory) {
                onlyRecordFailures = !directoryProbablyExists(directory, state.host);
            }
        }
        return ts.forEach(extensions, function (ext) {
            return !(state.skipTsx && ts.isJsxOrTsxExtension(ext)) && tryFile(candidate + ext, failedLookupLocation, onlyRecordFailures, state);
        });
    }
246048
def optional_file_like(path):
    
    if (os.path.exists(path) and not (os.path.isfile(path) or
                                      stat.S_ISFIFO(os.stat(path).st_mode) or
                                      stat.S_ISCHR(os.stat(path).st_mode))):
        raise ValidationFailed(
            '{} is not a valid file, character device, or fifo.'.format(path))
1065280
public static final void checkFileType(Path path, String perms)
    {
        if (perms.length() != 10)
        {
            throw new IllegalArgumentException(perms+" not permission. E.g. -rwxr--r--");
        }
        switch (perms.charAt(0))
        {
            case '-':
                if (!Files.isRegularFile(path))
                {
                    throw new IllegalArgumentException("file is not regular file");
                }
                break;
            case 'd':
                if (!Files.isDirectory(path))
                {
                    throw new IllegalArgumentException("file is not directory");
                }
                break;
            case 'l':
                if (!Files.isSymbolicLink(path))
                {
                    throw new IllegalArgumentException("file is not symbolic link");
                }
                break;
            default:
                throw new UnsupportedOperationException(perms+" not supported");
        }
    }
1130241
def CheckFile(self, path):
    
    print('Checking: {0:s}'.format(path))

    definitions_registry = registry.DataTypeDefinitionsRegistry()
    definitions_reader = reader.YAMLDataTypeDefinitionsFileReader()
    result = False

    try:
      definitions_reader.ReadFile(definitions_registry, path)
      result = True

    except KeyError as exception:
      logging.warning((
          'Unable to register data type definition in file: {0:s} with '
          'error: {1:s}').format(path, exception))

    except errors.FormatError as exception:
      logging.warning(
          'Unable to validate file: {0:s} with error: {1:s}'.format(
              path, exception))

    return result
1085835
def _validate_file_roots(file_roots):
    '''
    
    '''
    if not isinstance(file_roots, dict):
        log.warning('The file_roots parameter is not properly formatted,'
                    ' using defaults')
        return {'base': _expand_glob_path([salt.syspaths.BASE_FILE_ROOTS_DIR])}
    return _normalize_roots(file_roots)
1294101
def has_file_changed(directory, checksums, filetype='genbank'):
    """"""
    pattern = NgdConfig.get_fileending(filetype)
    filename, expected_checksum = get_name_and_checksum(checksums, pattern)
    full_filename = os.path.join(directory, filename)
    # if file doesn't exist, it has changed
    if not os.path.isfile(full_filename):
        return True

    actual_checksum = md5sum(full_filename)
    return expected_checksum != actual_checksum
997342
def __isValidTGZ(self, suffix):
        """"""
        if suffix and isinstance(suffix, string_types):
            if suffix.endswith(".tar.gz") or suffix.endswith(".tgz"):
                return True
        return False
67919
function fileExists(file, handle) {
		fs.exists(file, function(exists) {
			handle.apply(null, exists ? [file] : []);
		});
	}
476178
function getFileTypeReg(type) {
  var map = [], ext = her.config.get('project.fileType.' + type);
  if (type === 'text') {
    map = TEXT_FILE_EXTS;
  } else if (type === 'image') {
    map = IMAGE_FILE_EXTS;
  } else {
    throw new Error('invalid file type [' + type + ']');
  }
  if (ext && ext.length) {
    if (typeof ext === 'string') {
      ext = ext.split(/\s*,\s*/);
    }
    map = map.concat(ext);
  }
  map = map.join('|');
  return new RegExp('\\.(?:' + map + ')$', 'i');
}
701367
def register(filetypes):
    
    def decorator(clazz):
        for ext in filetypes:
            checkers.setdefault(ext, []).append(clazz)
        return clazz
    return decorator
790974
function fileExists(file) {
    try {
        var targetStat = fs.statSync(file);
        if (targetStat.isDirectory() ) {
            throw new Error("File exists but it's a driectory: " + file);
        }
    }
    catch(err) {
        if (err.code == 'ENOENT') {         // No such file or directory
            return false;
        }
        else {
            throw err;
        }
    }
    return true;
}
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`
  }
}
170489
function _checksums(dir) {
  const checksums = {};

  glob.sync(resolve(dir, '**/!(*.pack.+(s[ac]ss|js))'), { mark: true }).forEach((file) => {
    if (Utils.endsWith(file, '/')) { return; }

    const relativePath = relative(dir, file);
    checksums[relativePath] = Utils.checksum(file);
  });

  return checksums;
}
782127
private void checkFileDataSink(FileDataSinkBase<?> fileSink) {
		String path = fileSink.getFilePath();
		if (path == null) {
			throw new InvalidProgramException("File path of FileDataSink is null.");
		}
		if (path.length() == 0) {
			throw new InvalidProgramException("File path of FileDataSink is empty string.");
		}
		
		try {
			Path p = new Path(path);
			String scheme = p.toUri().getScheme();
			
			if (scheme == null) {
				throw new InvalidProgramException("File path \"" + path + "\" of FileDataSink has no file system scheme (like 'file:// or hdfs://').");
			}
		} catch (Exception e) {
			throw new InvalidProgramException("File path \"" + path + "\" of FileDataSink is an invalid path: " + e.getMessage());
		}
		checkDataSink(fileSink);
	}
500940
def choose_type(cls, content_type):
        """"""
        return cls.type_cls.SUBDIR if content_type in cls.subdir_types \
            else cls.type_cls.FILE