Allocate tempfile on same device as cache with a suffix chosen to prevent collisions
197034
def _tmpfile(self, cache_key, use):
    """"""
    with temporary_file(suffix=cache_key.id + use, root_dir=self._cache_root,
                        permissions=self._permissions) as tmpfile:
      yield tmpfile
438047
def _create_cache_filename(self, cache_dir=None, **kwargs):
        """"""
        cache_dir = cache_dir or '.'
        hash_str = self.get_hash(**kwargs)

        return os.path.join(cache_dir, 'resample_lut-' + hash_str + '.npz')
619845
def cache_context(self, context):
        '''
        
        '''
        if not os.path.isdir(os.path.dirname(self.cache_path)):
            os.mkdir(os.path.dirname(self.cache_path))
        with salt.utils.files.fopen(self.cache_path, 'w+b') as cache:
            self.serial.dump(context, cache)
287980
def file(suffix='', prefix='tmp', parent=None):
    '''
    
    '''
    fh_, tmp_ = tempfile.mkstemp(suffix, prefix, parent)
    os.close(fh_)
    return tmp_
1205194
void renameTempFile(FileExtension extension) {
    String fileName = filenameForUrl(url, extension, true);
    File file = new File(appContext.getCacheDir(), fileName);
    String newFileName = file.getAbsolutePath().replace(".temp", "");
    File newFile = new File(newFileName);
    boolean renamed = file.renameTo(newFile);
    L.debug("Copying temp file to real file (" + newFile + ")");
    if (!renamed) {
      L.warn( "Unable to rename cache file " + file.getAbsolutePath() + " to " + newFile.getAbsolutePath() + ".");
    }
  }
1038157
def set_cache(config_fpath, cache_dir):
    
    cache_dir = os.path.abspath(cache_dir)
    return write_config_value_to_file(
        CACHE_DIRECTORY_KEY,
        cache_dir,
        config_fpath
    )
1130579
static synchronized File tempFile(HttpServerFileUpload upload) {
        String newpostfix;
        String diskFilename = new File(upload.filename()).getName();
        newpostfix = '_' + diskFilename;
        File tmpFile;
        try {
            if (baseDirectory == null) {
                // create a temporary file
                tmpFile = File.createTempFile(prefix, newpostfix);
            } else {
                tmpFile = File.createTempFile(prefix, newpostfix, new File(
                        baseDirectory));
            }
            if (deleteOnExitTemporaryFile) {
                tmpFile.deleteOnExit();
            }
            return tmpFile;
        } catch (IOException e) {
            // Really bad, can't create the tmp file.
            throw new IllegalStateException(e);
        }

    }
458889
def global_cache_write(key, val, appname='default'):
    
    with GlobalShelfContext(appname) as shelf:
        shelf[key] = val
1263471
def cache(self, name='cache', default_timeout=3600):
        
        return Cache(self, name=name, default_timeout=default_timeout)
3227
def save_cache(dpath, fname, cfgstr, data, ext='.cPkl', verbose=None):
    
    fpath = _args2_fpath(dpath, fname, cfgstr, ext)
    util_io.save_data(fpath, data, verbose=verbose)
    return fpath
785367
protected void putToCache(String cacheName, String key, Object value,
            long expireAfterWriteSeconds, long expireAfterAccessSeconds) {
        try {
            ICache cache = getCache(cacheName);
            if (value != null && cache != null) {
                cache.set(key, value, expireAfterWriteSeconds, expireAfterAccessSeconds);
            }
        } catch (CacheException e) {
            LOGGER.warn(e.getMessage(), e);
        }
    }
643790
def write_to_cache(self, data, filename):
        '''  '''

        json_data = json.dumps(data, sort_keys=True, indent=2)
        cache = open(filename, 'w')
        cache.write(json_data)
        cache.close()
85030
def _createCacheLockFile(self, tempCacheDir):
        
        # The nlink threshold is setup along with the first instance of the cache class on the
        # node. It needs the cache dir to sniff link count for files form the job store.
        self.setNlinkThreshold(tempCacheDir)
        # Get the free space on the device
        freeSpace, _ = getFileSystemSize(tempCacheDir)
        # Create the cache lock file.
        open(os.path.join(tempCacheDir, os.path.basename(self.cacheLockFile)), 'w').close()
        # Setup the cache state file
        personalCacheStateFile = os.path.join(tempCacheDir,
                                              os.path.basename(self.cacheStateFile))
        # Setup the initial values for the cache state file in a dict
        cacheInfo = self._CacheState({
            'nlink': self.nlinkThreshold,
            'attemptNumber': self.workflowAttemptNumber,
            'total': freeSpace,
            'cached': 0,
            'sigmaJob': 0,
            'cacheDir': self.localCacheDir,
            'jobState': {}})
        cacheInfo.write(personalCacheStateFile)
903146
def _save_cache(self):
        """"""
        # Create the cache directory
        safe_makedirs(self.cache_dir)

        # Create/overwrite the cache file
        try:
            with open(self.cache_file, 'wb') as f:
                pickle.dump(self.data, f)
        except Exception as e:
            logger.error("Cannot write version to cache file {} ({})".format(self.cache_file, e))
11765
def flush_cache(name=nil)
      if name
        name = name.to_s
        self.cache_hash[name] &&= nil
      else
        logger.warn "RConfig: Flushing config data cache."
        self.suffixes        = {}
        self.cache           = {}
        self.cache_files     = {}
        self.cache_hash      = {}
        self.last_auto_check = {}
        self
      end
    end
532510
def tmpfile(prefix, direc):
    """"""
    return tempfile.mktemp(prefix=prefix, suffix='.pdb', dir=direc)
850726
private static Path localizeCache(Configuration conf,
                                    URI cache, long confFileStamp,
                                    CacheStatus cacheStatus,
                                    boolean isArchive)
  throws IOException {
    FileSystem fs = getFileSystem(cache, conf);
    FileSystem localFs = FileSystem.getLocal(conf);
    Path parchive = null;

    if (isArchive) {
      parchive = new Path(cacheStatus.localizedLoadPath,
        new Path(cacheStatus.localizedLoadPath.getName()));
    } else {
      parchive = cacheStatus.localizedLoadPath;
    }
    if (!localFs.mkdirs(parchive.getParent())) {
      throw new IOException("Mkdirs failed to create directory " +
          cacheStatus.localizedLoadPath.toString());
    }
    String cacheId = cache.getPath();

    fs.copyToLocalFile(new Path(cacheId), parchive);
    if (isArchive) {
      String tmpArchive = parchive.toString().toLowerCase();
      File srcFile = new File(parchive.toString());
      File destDir = new File(parchive.getParent().toString());
      if (tmpArchive.endsWith(".jar")) {
        RunJar.unJar(srcFile, destDir);
      } else if (tmpArchive.endsWith(".zip")) {
        FileUtil.unZip(srcFile, destDir);
      } else if (isTarFile(tmpArchive)) {
        FileUtil.unTar(srcFile, destDir);
      }
      // else will not do anyhting
      // and copy the file into the dir as it is
    }
    long cacheSize = FileUtil.getDU(new File(parchive.getParent().toString()));
    cacheStatus.size = cacheSize;
    addCacheInfoUpdate(cacheStatus);

    // do chmod here
    try {
      //Setting recursive permission to grant everyone read and execute
      Path localDir = new Path(cacheStatus.localizedBaseDir,
                               cacheStatus.uniqueParentDir);
      LOG.info("Doing chmod on localdir :" + localDir);
      FileUtil.chmod(localDir.toString(), "ugo+rx", true);
    } catch(InterruptedException e) {
      LOG.warn("Exception in chmod" + e.toString());
    }

    // update cacheStatus to reflect the newly cached file
    cacheStatus.mtime = getTimestamp(conf, cache);
    return cacheStatus.localizedLoadPath;
  }