示例#1
0
文件: testApp.cpp 项目: Mana-Hanno/oF
//--------------------------------------------------------------
void testApp::setup(){
	
	camWidth 		= 320;	// try to grab at this size. 
	camHeight 		= 240;
	
	vidGrabber.setVerbose(true);
	vidGrabber.initGrabber(camWidth,camHeight);
	
	videoInverted 	= new unsigned char[camWidth*camHeight*3];
	videoTexture.allocate(camWidth,camHeight, GL_RGB);
	
	// create a unique file name for this movie file
	createFileName();
	
	// initialize a timestamp which we'll use to properly
	// time the frame as they're added to the movie
	mTimestamp = ofGetElapsedTimef();
	
	// allocate the frame buffer object
	mFbo.allocate(camWidth, camHeight, GL_RGB, 0);
	
	// init the movie saver
    mVidSaver.setCodecQualityLevel(OF_QT_SAVER_CODEC_QUALITY_NORMAL);
    mVidSaver.setup(camWidth, camHeight, mFileName);

}
示例#2
0
void outputSelectedAlignments(std::vector<std::vector<Chain*>>& alignment_strings,
    Chain** queries, int32_t queries_length, const std::string& out_path) {

    std::string out_extension = ".aligned.fasta";

    for (uint32_t i = 0; i < alignment_strings.size(); ++i) {

        std::ofstream out_file;
        char* out_file_name = createFileName(chainGetName(queries[i]), out_path, out_extension);

        int query_len = chainGetLength(queries[i]);

        out_file.open(out_file_name);
        out_file << ">QUERY" << std::endl;

        for (int j = 1; j < query_len + 1; ++j) {
            out_file << chainGetChar(queries[i], j - 1);
            if (j % 60 == 0) out_file << std::endl;
        }
        out_file << std::endl;

        for (uint32_t j = 0; j < alignment_strings[i].size(); ++j) {
            out_file << ">" << chainGetName(alignment_strings[i][j]) << std::endl;

            for (int k = 1; k < query_len + 1; ++k) {
                out_file << chainGetChar(alignment_strings[i][j], k - 1);
                if (k % 60 == 0) out_file << std::endl;
            }
            out_file << std::endl;
        }

        out_file.close();
        delete[] out_file_name;
    }
}
CreationOptions::CreationOptions(std::string name)
  : m_name{std::move(name)} {

  tinyxml2::XMLDocument doc;
  tinyxml2::XMLError errorCode{doc.LoadFile(createFileName(m_name).c_str())};

  // If there is an error, it is probably because the file dose not exist.
  // There will be a new one generated when closing the game.
  if (errorCode != 0)
    return;

  tinyxml2::XMLNode* root{doc.FirstChild()};

  {
    {
      tinyxml2::XMLElement* seed{root->FirstChildElement("seed")};
      std::string value(seed->GetText());
      m_seed = stoi(value);
    }

    {
      tinyxml2::XMLElement* flat{root->FirstChildElement("flat")};
      std::string value(flat->GetText());
      m_flat = value == "true";
    }

    {
      tinyxml2::XMLElement* different{
        root->FirstChildElement("different_cube_for_each_chunk")};
      std::string value(different->GetText());
      m_differentCubeForEachChunk = value == "true";
    }
  }
}
void JUnitTestOutput::writeTestGroupToFile()
{
	openFileForWrite(createFileName(impl_->results_.group_));
	writeXmlHeader();
	writeTestSuiteSummery();
	writeProperties();
	writeTestCases();
	writeFileEnding();
	closeFile();
}
示例#5
0
void ResearchEngine::doSingleResearch(Point *start, Point *end, int type, int populationSize, float f, float cr, int movementSteps, int epochs, bool showResult){
	Environment env(*start, *end, type, populationSize, f, cr, movementSteps);

	vector<float> results;
	for(currentEpoch = 0; currentEpoch < epochs; currentEpoch++){
		results.push_back(env.evolutionCycle());
	}

	Worm * worm = env.getBestWorm();
	worm->saveToFile(createFileName("", "_worm.txt", start, end, type, populationSize, f, cr, movementSteps, epochs));
	saveResultsToFile(createFileName("", "_results.txt", start, end, type, populationSize, f, cr, movementSteps, epochs), results);

	if(showResult){
		SDLInterface inteface;
		inteface.displayWorm(worm);
	}

	env.clear();
}
示例#6
0
/*
 * Class:     edu_uw_apl_commons_tsk4j_filesys_FileSystem
 * Method:    dirOpen
 * Signature: (JLjava/lang/String;)Ledu/uw/apl/commons/tsk4j/filesys/Directory;
 */
JNIEXPORT jobject JNICALL 
Java_edu_uw_apl_commons_tsk4j_filesys_FileSystem_dirOpen
(JNIEnv *env, jobject thiz, jlong nativePtr, jstring path ) {

  const char* pathC = (*env)->GetStringUTFChars( env, path, NULL );

  TSK_FS_INFO* info = (TSK_FS_INFO*)nativePtr;
  TSK_FS_DIR* fsDir = tsk_fs_dir_open( info, pathC );

  if( !fsDir ) {
	(*env)->ReleaseStringUTFChars( env, path, pathC );
	return (jobject)NULL;
  }
  TSK_FS_FILE* fsFile = fsDir->fs_file;

  jobject fileMeta = NULL;
  if( fsFile->meta ) {
	fileMeta = createFileMeta( env, fsFile->meta );
	if( !fileMeta ) {
	  tsk_fs_dir_close( fsDir );
	  (*env)->ReleaseStringUTFChars( env, path, pathC );
	  return NULL;
	}
  }

  jobject fileName = NULL;
  if( fsFile->name ) {
	fileName = createFileName( env, fsFile->name );
	if( !fileName ) {
	  tsk_fs_dir_close( fsDir );
	  (*env)->ReleaseStringUTFChars( env, path, pathC );
	  // LOOK: release fileMeta ????
	  return NULL;
	}
  }

  jobject file = createFile( env, fsFile, thiz, fileMeta, fileName ); 
  if( !file ) {
	  tsk_fs_dir_close( fsDir );
	  (*env)->ReleaseStringUTFChars( env, path, pathC );
	  // LOOK: release fileMeta, fileName ????
	  return NULL;
  }
  
  jobject result = createDirectory( env, fsDir, thiz, file );
  if( !result ) {
	  tsk_fs_dir_close( fsDir );
	  (*env)->ReleaseStringUTFChars( env, path, pathC );
	  // LOOK: release fileMeta, fileName, file ????
	  return NULL;
  }

  (*env)->ReleaseStringUTFChars( env, path, pathC );
  return result;
}
示例#7
0
int main(){
	char fileName[20];
	char errorLogFileName[20];
	createBotDirectory(errorLogFileName);
	createFileName(fileName, 1);
	genFile(fileName);
	if(buildFile(fileName, errorLogFileName)!=-1){
		runFile(fileName, errorLogFileName);
	}else{
		printf("Build error\n");
	}
}
示例#8
0
void prepareMsiData(int localeId) {
  String msiFilePath = getTmpPath() + kMsiFileName;
  // Copy msi file to temp
  copyFile(IDR_MSI, msiFilePath);
  
  // Don't need transform for English (United States)
  if (localeId != kEnglishLocalId) {
    String transformFile = createFileName(localeId);
    String transformFilePath = getTmpPath() + transformFile;
    // Copy mst file to temp if needed
    copyFile(localeId, transformFilePath);
  }
}
示例#9
0
void Log::openLog(ofstream& _logFile, string& _logFileName)
{
	static bool isOpen = false;
	if(!isOpen){
		createFileName(_logFileName);
		_logFile.open(_logFileName, std::ios::out);
		assert(_logFile.is_open());												//raise if file has not been opened at this point
		isOpen = true;
		_logFile << logMessages(LOGGING_STARTING);
	}

	return;
}
示例#10
0
/** Base method for opening a file
  * Creates the file name with NDPluginBase::createFileName, then calls the pure virtual function openFile
  * in the derived class. */
asynStatus NDPluginFile::openFileBase(NDFileOpenMode_t openMode, NDArray *pArray)
{
    /* Opens a file for reading or writing */
    asynStatus status = asynSuccess;
    char fullFileName[MAX_FILENAME_LEN];
    char tempSuffix[MAX_FILENAME_LEN];
    char errorMessage[256];
    static const char* functionName = "openFileBase";

    if (this->useAttrFilePrefix)
        this->attrFileNameSet();

    setIntegerParam(NDFileWriteStatus, NDFileWriteOK);
    setStringParam(NDFileWriteMessage, "");
    status = (asynStatus)createFileName(MAX_FILENAME_LEN, fullFileName);
    if (status) {
        asynPrint(this->pasynUserSelf, ASYN_TRACE_ERROR, 
              "%s::%s error creating full file name, fullFileName=%s, status=%d\n", 
              driverName, functionName, fullFileName, status);
        setIntegerParam(NDFileWriteStatus, NDFileWriteError);
        setStringParam(NDFileWriteMessage, "Error creating full file name");
        return(status);
    }
    setStringParam(NDFullFileName, fullFileName);
    
    getStringParam(NDFileTempSuffix, sizeof(tempSuffix), tempSuffix);
    if ( *tempSuffix != 0 && 
         (strlen(fullFileName) + strlen(tempSuffix)) < sizeof(fullFileName) ) {
        strcat( fullFileName, tempSuffix );
    }

    /* Call the openFile method in the derived class */
    /* Do this with the main lock released since it is slow */
    this->unlock();
    epicsMutexLock(this->fileMutexId);
    this->registerInitFrameInfo(pArray);
    status = this->openFile(fullFileName, openMode, pArray);
    if (status) {
        epicsSnprintf(errorMessage, sizeof(errorMessage)-1, 
            "Error opening file %s, status=%d", fullFileName, status);
        asynPrint(this->pasynUserSelf, ASYN_TRACE_ERROR, 
              "%s::%s %s\n", 
              driverName, functionName, errorMessage);
        setIntegerParam(NDFileWriteStatus, NDFileWriteError);
        setStringParam(NDFileWriteMessage, errorMessage);
    }
    epicsMutexUnlock(this->fileMutexId);
    this->lock();
    
    return(status);
}
示例#11
0
CreationOptions::CreationOptions(std::string name,
                                 int seed,
                                 bool flat,
                                 bool different)
  : m_name{std::move(name)}
  , m_seed{seed}
  , m_flat{flat}
  , m_differentCubeForEachChunk{different} {

  tinyxml2::XMLDocument doc;
  tinyxml2::XMLNode* root{doc.NewElement("xml")};
  doc.InsertFirstChild(root);

  {
    {
      tinyxml2::XMLElement* name{doc.NewElement("name")};
      name->SetText(m_name.c_str());
      root->InsertEndChild(name);
    }

    {
      tinyxml2::XMLElement* seed{doc.NewElement("seed")};
      seed->SetText(m_seed);
      root->InsertEndChild(seed);
    }

    {
      tinyxml2::XMLElement* flat{doc.NewElement("flat")};
      flat->SetText(m_flat);
      root->InsertEndChild(flat);
    }

    {
      tinyxml2::XMLElement* different{
        doc.NewElement("different_cube_for_each_chunk")};
      different->SetText(config::graphics_data::fullScreen);
      root->InsertEndChild(different);
    }
  }

  tinyxml2::XMLError errorCode{doc.SaveFile(createFileName(m_name).c_str())};

  if (errorCode) {
    std::cout << "Error while creating xml file for world options. \n";
  }
}
示例#12
0
  void WriteVtk::perform(MultiBlockLattice2D<T,DESCRIPTOR> &lattice, 
			 plint nStep)
  {
    T dx = controller->getParams().getDeltaX();
    T physU = controller->getUnits().physVelocity();
    std::string fname = createFileName(prefix, nStep, fileNameLength);
    VtkImageOutput2D<T> vtkOut(fname, dx);
    
    std::auto_ptr<MultiScalarField2D<T> > density = computeDensity(lattice);
    PressureFromRho p(controller);

    apply(p,*density);
    
    vtkOut.writeData<float>(*density, "pressure", 1);
    vtkOut.writeData<2,float>(*computeVelocity(lattice), "velocity", physU);
    pcout << "vtk file " << fname << " written" << std::endl;
  };
示例#13
0
void runMsi(int localeId) {
  String msiFilePath = getTmpPath() + kMsiFileName;

  // Crete parameter string for msiexec
  std::wstringstream parameter;
  parameter << "/i \"" << msiFilePath << "\""
            << " LanguageChoice=\"" << localeIdToShortLocale(localeId) << "\"";
  // Don't need transform for English (United States)
  if (localeId != kEnglishLocalId) {
    String transformFile = createFileName(localeId);
    String transformFilePath = getTmpPath() + transformFile;
    parameter  << " transforms=\"" << transformFilePath  << "\"";
  }

  // Execute msiexec with the parameter from above
  ShellExecute(NULL, _T("open"), _T("msiexec.exe"),
    parameter.str().c_str(), NULL, SW_SHOWNORMAL);
}
void testApp::setup(){
	
	camWidth = 640;
	camHeight = 480;
	
	vidGrabber.setVerbose(true);
	vidGrabber.initGrabber(camWidth,camHeight);
	
	videoInverted 	= new unsigned char[camWidth*camHeight*3];
	videoTexture.allocate(camWidth,camHeight, GL_RGB);
	
	createFileName();
	mTimestamp = ofGetElapsedTimef();
	
    mVidSaver.setCodecQualityLevel(OF_QT_SAVER_CODEC_QUALITY_NORMAL);
    mVidSaver.setup(camWidth, camHeight, mFileName);

}
示例#15
0
/*
 * Class:     edu_uw_apl_commons_tsk4j_filesys_FileSystem
 * Method:    dirOpenMeta
 * Signature: (JJ)Ledu/uw/apl/commons/tsk4j/filesys/Directory;
 */
JNIEXPORT jobject JNICALL 
Java_edu_uw_apl_commons_tsk4j_filesys_FileSystem_dirOpenMeta
(JNIEnv *env, jobject thiz, jlong nativePtr, jlong metadataAddr ) {

  TSK_FS_INFO* info = (TSK_FS_INFO*)nativePtr;
  TSK_FS_DIR* fsDir = tsk_fs_dir_open_meta( info, (TSK_INUM_T)metadataAddr );
  if( fsDir == NULL )
	return (jobject)NULL;
  TSK_FS_FILE* fsFile = fsDir->fs_file;

  jobject fileMeta = NULL;
  if( fsFile->meta ) {
	fileMeta = createFileMeta( env, fsFile->meta );
	if( !fileMeta ) {
	  tsk_fs_dir_close( fsDir );
	  return NULL;
	}
  }

  jobject fileName = NULL;
  if( fsFile->name ) {
	fileName = createFileName( env, fsFile->name );
	if( !fileName ) {
	  tsk_fs_dir_close( fsDir );
	  // LOOK: release fileMeta ????
	  return NULL;
	}
  }

  jobject file = createFile( env, fsFile, thiz, fileMeta, fileName ); 
  if( !file ) {
	  tsk_fs_dir_close( fsDir );
	  // LOOK: release fileMeta, fileName ????
	  return NULL;
  }
  
  jobject result = createDirectory( env, fsDir, thiz, file );
  if( !result ) {
	  tsk_fs_dir_close( fsDir );
	  // LOOK: release fileMeta, fileName, file ????
	  return NULL;
  }
  return result;
}
示例#16
0
/** Base method for reading a file
  * Creates the file name with NDPluginBase::createFileName, then calls the pure virtual functions openFile,
  * readFile and closeFile in the derived class.  Does callbacks with the NDArray that was read in. */
asynStatus NDPluginFile::readFileBase(void)
{
    asynStatus status = asynSuccess;
    char fullFileName[MAX_FILENAME_LEN];
    int dataType=0;
    NDArray *pArray=NULL;
    static const char* functionName = "readFileBase";

    status = (asynStatus)createFileName(MAX_FILENAME_LEN, fullFileName);
    if (status) { 
        asynPrint(this->pasynUserSelf, ASYN_TRACE_ERROR, 
              "%s:%s error creating full file name, fullFileName=%s, status=%d\n", 
              driverName, functionName, fullFileName, status);
        return(status);
    }
    
    /* Call the readFile method in the derived class */
    /* Do this with the main lock released since it is slow */
    this->unlock();
    epicsMutexLock(this->fileMutexId);
    status = this->openFile(fullFileName, NDFileModeRead, pArray);
    status = this->readFile(&pArray);
    status = this->closeFile();
    epicsMutexUnlock(this->fileMutexId);
    this->lock();
    
    /* If we got an error then return */
    if (status) return(status);
    
    /* Update the new values of dimensions and the array data */
    setIntegerParam(NDDataType, dataType);
    
    /* Call any registered clients */
    doCallbacksGenericPointer(pArray, NDArrayData, 0);

    /* Set the last array to be this one */
    this->pArrays[0]->release();
    this->pArrays[0] = pArray;    
    
    return(status);
}
示例#17
0
/** Base method for opening a file
  * Creates the file name with NDPluginBase::createFileName, then calls the pure virtual function openFile
  * in the derived class. */
asynStatus NDPluginFile::openFileBase(NDFileOpenMode_t openMode, NDArray *pArray)
{
    /* Opens a file for reading or writing */
    asynStatus status = asynSuccess;
    char fullFileName[MAX_FILENAME_LEN];
    char errorMessage[256];
    const char* functionName = "openFileBase";

    if (this->useAttrFilePrefix)
        this->attrFileNameSet();

    setIntegerParam(NDFileWriteStatus, NDFileWriteOK);
    setStringParam(NDFileWriteMessage, "");
    status = (asynStatus)createFileName(MAX_FILENAME_LEN, fullFileName);
    if (status) {
        asynPrint(this->pasynUserSelf, ASYN_TRACE_ERROR, 
              "%s:%s error creating full file name, fullFileName=%s, status=%d\n", 
              driverName, functionName, fullFileName, status);
        setIntegerParam(NDFileWriteStatus, NDFileWriteError);
        setStringParam(NDFileWriteMessage, "Error creating full file name");
        return(status);
    }
    setStringParam(NDFullFileName, fullFileName);
    
    /* Call the openFile method in the derived class */
    epicsMutexLock(this->fileMutexId);
    status = this->openFile(fullFileName, openMode, pArray);
    if (status) {
        epicsSnprintf(errorMessage, sizeof(errorMessage)-1, 
            "Error opening file %s, status=%d", fullFileName, status);
        asynPrint(this->pasynUserSelf, ASYN_TRACE_ERROR, 
              "%s:%s %s\n", 
              driverName, functionName, errorMessage);
        setIntegerParam(NDFileWriteStatus, NDFileWriteError);
        setStringParam(NDFileWriteMessage, errorMessage);
    }
    epicsMutexUnlock(this->fileMutexId);
    
    return(status);
}
示例#18
0
/**
 * Creates a log file, if it not yet already exists and writes the header items
 * into it.
 *
 * Returns true if file is ready for further writing otherwise false.
 */
bool IgcLogger::isLogFileOpen()
{
  // IGC Logfile is stored at User Data Directory / igc

  if( _logfile.isOpen() )
    {
      // Logfile is already opened
      return true;
    }

  QString path(GeneralConfig::instance()->getUserDataDirectory() + "/igc");

  QString fname = createFileName(path);

  QDir dir(path);

  if ( ! dir.exists() )
    {
      dir.mkpath(path);
    }

  _logfile.setFileName( fname );

  if ( ! _logfile.open(QIODevice::WriteOnly) )
    {
      qWarning() << "IGC-Logger: Cannot open file" << fname;
      return false;
    }

  // qDebug( "IGC-Logger: Created Logfile %s", fname.toLatin1().data() );

  _stream.setDevice(&_logfile);

  writeHeader();

  // As first create a F record
  slotConstellation( GpsNmea::gps->getLastSatInfo() );

  return true;
}
示例#19
0
QString SvgSavingContext::saveImage(KoImageData *image)
{
    if (isSavingInlineImages()) {
        QByteArray ba;
        QBuffer buffer(&ba);
        buffer.open(QIODevice::WriteOnly);
        if (image->saveData(buffer)) {
            //const QString mimeType(KMimeType::findByContent(ba)->name());
			const QString mimeType = QString::fromLocal8Bit("mimeType");
			//QString ext = "";
            const QString header("data:" + mimeType + ";base64,");
            return header + ba.toBase64();
        }
    } else {
        // write to a temp file first
        QTemporaryFile imgFile;
        if (image->saveData(imgFile)) {
            // tz: TODO the new version of KoImageData has the extension save inside maybe that can be used
            // get the mime type from the temp file content
            //KMimeType::Ptr mimeType = KMimeType::findByFileContent(imgFile.fileName());
            // get extension from mimetype
            //QString ext = "";
            //QStringList patterns = mimeType->patterns();
            //if (patterns.count())
            //    ext = patterns.first().mid(1);
			QString ext = "*.png";

            QString dstFilename = createFileName(ext);

            // move the temp file to the destination directory
            //KIO::Job * job = KIO::move(QUrl(imgFile.fileName()), QUrl(dstFilename));
            //if (job && KIO::NetAccess::synchronousRun(job, 0))
            //    return dstFilename;
            //else
                //KIO::NetAccess::removeTempFile(imgFile.fileName());
				QFile::remove(imgFile.fileName());
        }
    }
    return QString();
}
示例#20
0
/*
 * Class:     edu_uw_apl_commons_tsk4j_filesys_FileSystem
 * Method:    fileOpen
 * Signature: (JLjava/lang/String;)Ledu/uw/apl/commons/tsk4j/filesys/File;
 */
JNIEXPORT jobject JNICALL 
Java_edu_uw_apl_commons_tsk4j_filesys_FileSystem_fileOpen
(JNIEnv *env, jobject thiz, jlong nativePtr, jstring path ) {
  
  const char* pathC = (*env)->GetStringUTFChars( env, path, NULL );

  TSK_FS_INFO* info = (TSK_FS_INFO*)nativePtr;
  TSK_FS_FILE* fsFile = tsk_fs_file_open( info, NULL, pathC );

  if( !fsFile ) {
	(*env)->ReleaseStringUTFChars( env, path, pathC );
	return (jobject)NULL;
  }

  jobject fileMeta = NULL;
  if( fsFile->meta ) {
	fileMeta = createFileMeta( env, fsFile->meta );
	if( !fileMeta ) {
	  (*env)->ReleaseStringUTFChars( env, path, pathC );
	  tsk_fs_file_close( fsFile );
	  return (jobject)NULL;
	}
  }

  jobject fileName = NULL;
  if( fsFile->name ) {
	fileName = createFileName( env, fsFile->name );
	if( !fileName ) {
	  (*env)->ReleaseStringUTFChars( env, path, pathC );
	  tsk_fs_file_close( fsFile );
	  return (jobject)NULL;
	}
  }
  jobject result = createFile( env, fsFile, thiz, fileMeta, fileName ); 
  (*env)->ReleaseStringUTFChars( env, path, pathC );
  return result;
}
示例#21
0
bool init()
{
    Serial.print( F("Init SD...") );

    //TODO: check if needed
    //pinMode(13, OUTPUT);
    //digitalWrite(13, HIGH);

    pinMode(10, OUTPUT);
    if (!SD.begin(10))
    {
        Serial.println( F("ERROR") );
        return false;
    }

    Serial.println( F("OK") );

    int i = 0;
    do
    {
        createFileName(i++);

        if (!SD.exists(filename))
            break;
    }
    while (true);

    Serial.println( F("SD File:") );
    Serial.println(filename);

    file = SD.open(filename, O_CREAT | O_WRITE);
    CSV::setOutput(&file);
    CSV::printHead();

    return true;
}
示例#22
0
static liHandlerResult cache_etag_handle(liVRequest *vr, gpointer param, gpointer *context) {
	cache_etag_context *ctx = (cache_etag_context*) param;
	cache_etag_file *cfile = (cache_etag_file*) *context;
	GList *etag_entry;
	liHttpHeader *etag;
	struct stat st;
	GString *tmp_str = vr->wrk->tmp_str;
	liHandlerResult res;
	int err, fd;

	if (!cfile) {
		if (vr->request.http_method != LI_HTTP_METHOD_GET) return LI_HANDLER_GO_ON;

		LI_VREQUEST_WAIT_FOR_RESPONSE_HEADERS(vr);

		if (vr->response.http_status != 200) return LI_HANDLER_GO_ON;

		/* Don't cache static files if filter list is empty */
		if (NULL == vr->filters_out_first && vr->backend_source->out->is_closed && 0 == vr->backend_source->out->mem_usage)
			return LI_HANDLER_GO_ON;

		etag_entry = li_http_header_find_first(vr->response.headers, CONST_STR_LEN("etag"));
		if (!etag_entry) return LI_HANDLER_GO_ON; /* no etag -> no caching */
		if (li_http_header_find_next(etag_entry, CONST_STR_LEN("etag"))) {
			VR_ERROR(vr, "%s", "duplicate etag header in response, will not cache it");
			return LI_HANDLER_GO_ON;
		}
		etag = (liHttpHeader*) etag_entry->data;

		cfile = cache_etag_file_create(createFileName(vr, ctx->path, etag));
		*context = cfile;
	}

	res = li_stat_cache_get(vr, cfile->filename, &st, &err, &fd);
	if (res == LI_HANDLER_WAIT_FOR_EVENT)
		return res;

	if (res == LI_HANDLER_GO_ON) {
		liFilter *f;
		if (!S_ISREG(st.st_mode)) {
			VR_ERROR(vr, "Unexpected file type for cache file '%s' (mode %o)", cfile->filename->str, (unsigned int) st.st_mode);
			close(fd);
			return LI_HANDLER_GO_ON; /* no caching */
		}
		cfile->hit_fd = fd;
#ifdef FD_CLOEXEC
		fcntl(cfile->hit_fd, F_SETFD, FD_CLOEXEC);
#endif
		if (CORE_OPTION(LI_CORE_OPTION_DEBUG_REQUEST_HANDLING).boolean) {
			VR_DEBUG(vr, "cache hit for '%s'", vr->request.uri.path->str);
		}
		cfile->hit_length = st.st_size;
		g_string_truncate(tmp_str, 0);
		li_string_append_int(tmp_str, st.st_size);
		li_http_header_overwrite(vr->response.headers, CONST_STR_LEN("Content-Length"), GSTR_LEN(tmp_str));
		f = li_vrequest_add_filter_out(vr, cache_etag_filter_hit, NULL, NULL, NULL);
		if (NULL != f) {
			li_chunkqueue_append_file_fd(f->out, NULL, 0, cfile->hit_length, cfile->hit_fd);
			f->out->is_closed = TRUE;
			cfile->hit_fd = -1;
		}
		cache_etag_file_free(cfile);

		*context = NULL;
		return LI_HANDLER_GO_ON;
	}

	if (CORE_OPTION(LI_CORE_OPTION_DEBUG_REQUEST_HANDLING).boolean) {
		VR_DEBUG(vr, "cache miss for '%s'", vr->request.uri.path->str);
	}

	if (!cache_etag_file_start(vr, cfile)) {
		cache_etag_file_free(cfile);
		*context = NULL;
		return LI_HANDLER_GO_ON; /* no caching */
	}

	li_vrequest_add_filter_out(vr, cache_etag_filter_miss, cache_etag_filter_free, NULL, cfile);
	*context = NULL;

	return LI_HANDLER_GO_ON;
}
示例#23
0
int
main (int argc, char *argv[])
{
  static const struct option long_options[] = {
    {"help", no_argument, 0, 'h'},
    {"version", no_argument, 0, 'v'},
    {"check", no_argument, 0, 'c'},
    {"output", required_argument, 0, 'o'},
    {0, 0, 0, 0}
  };
  int option_index = 0;
  int option_result;
  char *outputFileName = NULL;
  char *inputFileAsnName = NULL;
  char *inputFileAssignmentName = NULL;
  int checkSyntaxOnly = 0;
  asn1_node definitions = NULL;
  asn1_node structure = NULL;
  char errorDescription[ASN1_MAX_ERROR_DESCRIPTION_SIZE];
  int asn1_result = ASN1_SUCCESS;
  FILE *outputFile;
  FILE *inputFile;
  char varName[1024];
  char value[1024];
  unsigned char *der = NULL;
  int der_len;
  int k;
  int last_ra;

  set_program_name (argv[0]);

  opterr = 0;			/* disable error messages from getopt */

  while (1)
    {

      option_result =
	getopt_long (argc, argv, "hvco:", long_options, &option_index);

      if (option_result == -1)
	break;

      switch (option_result)
	{
	case 'h':		/* HELP */
	  free (outputFileName);
	  usage (EXIT_SUCCESS);
	  break;
	case 'v':		/* VERSION */
	  version_etc (stdout, program_name, PACKAGE, VERSION,
		       "Fabio Fiorina", NULL);
	  free (outputFileName);
	  exit (0);
	  break;
	case 'c':		/* CHECK SYNTAX */
	  checkSyntaxOnly = 1;
	  break;
	case 'o':		/* OUTPUT */
	  outputFileName = (char *) malloc (strlen (optarg) + 1);
	  strcpy (outputFileName, optarg);
	  break;
	case '?':		/* UNKNOW OPTION */
	  free (outputFileName);
	  fprintf (stderr,
		   "asn1Coding: option '%s' not recognized or without argument.\n\n",
		   argv[optind - 1]);
	  usage (EXIT_FAILURE);
	  break;
	default:
	  fprintf (stderr,
		   "asn1Coding: ?? getopt returned character code Ox%x ??\n",
		   option_result);
	}
    }

  if (optind == argc || optind == argc - 1)
    {
      free (outputFileName);
      fputs ("asn1Coding: input files missing\n", stderr);
      usage (EXIT_FAILURE);
    }

  inputFileAsnName = (char *) malloc (strlen (argv[optind]) + 1);
  strcpy (inputFileAsnName, argv[optind]);

  inputFileAssignmentName = (char *) malloc (strlen (argv[optind + 1]) + 1);
  strcpy (inputFileAssignmentName, argv[optind + 1]);

  asn1_result =
    asn1_parser2tree (inputFileAsnName, &definitions, errorDescription);

  switch (asn1_result)
    {
    case ASN1_SUCCESS:
      fputs ("Parse: done.\n", stderr);
      break;
    case ASN1_FILE_NOT_FOUND:
      fprintf (stderr, "asn1Coding: FILE %s NOT FOUND\n", inputFileAsnName);
      break;
    case ASN1_SYNTAX_ERROR:
    case ASN1_IDENTIFIER_NOT_FOUND:
    case ASN1_NAME_TOO_LONG:
      fprintf (stderr, "asn1Coding: %s\n", errorDescription);
      break;
    default:
      fprintf (stderr, "libtasn1 ERROR: %s\n", asn1_strerror (asn1_result));
    }

  if (asn1_result != ASN1_SUCCESS)
    {
      free (inputFileAsnName);
      free (inputFileAssignmentName);
      exit (1);
    }


  inputFile = fopen (inputFileAssignmentName, "r");

  if (inputFile == NULL)
    {
      fprintf (stderr, "asn1Coding: file '%s' not found\n",
	       inputFileAssignmentName);
      free (inputFileAsnName);
      free (inputFileAssignmentName);
      exit (1);
    }


  putc ('\n', stderr);

  while ((last_ra = readAssignment (inputFile, varName, value))
	 == ASSIGNMENT_SUCCESS)
    {
      fprintf (stderr, "var=%s, value=%s\n", varName, value);
      if (structure == NULL)
	{
	  asn1_result = asn1_create_element (definitions, value, &structure);
	}
      else
        {
	  if (strcmp(value, "(NULL)") == 0)
	    asn1_result = asn1_write_value (structure, varName, NULL, 0);
	  else
	    asn1_result = asn1_write_value (structure, varName, value, 0);
	}

      if (asn1_result != ASN1_SUCCESS)
	{
	  fprintf (stderr, "libtasn1 ERROR: %s\n",
		   asn1_strerror (asn1_result));

	  asn1_delete_structure (&definitions);
	  asn1_delete_structure (&structure);

	  free (inputFileAsnName);
	  free (inputFileAssignmentName);

	  fclose (inputFile);
	  exit (1);
	}
    }
  if (last_ra != ASSIGNMENT_EOF)
    {
      fprintf (stderr, "asn1Coding: error reading assignment file\n");
      exit (1);
    }
  fclose (inputFile);

  putc ('\n', stderr);
  asn1_print_structure (stderr, structure, "", ASN1_PRINT_NAME_TYPE_VALUE);

  der_len = 0;
  asn1_result = asn1_der_coding (structure, "", der, &der_len,
				 errorDescription);
  if (asn1_result == ASN1_MEM_ERROR)
    {
      der = malloc (der_len);
      asn1_result = asn1_der_coding (structure, "", der, &der_len,
				     errorDescription);
    }
  fprintf (stderr, "\nCoding: %s\n\n", asn1_strerror (asn1_result));
  if (asn1_result != ASN1_SUCCESS)
    {
      fprintf (stderr, "asn1Coding: %s\n", errorDescription);

      free (der);

      asn1_delete_structure (&definitions);
      asn1_delete_structure (&structure);

      free (inputFileAsnName);
      free (inputFileAssignmentName);

      exit (1);
    }

  /* Print the 'Certificate1' DER encoding */
  fprintf (stderr, "-----------------\nNumber of bytes=%i\n", der_len);
  for (k = 0; k < der_len; k++)
    fprintf (stderr, "%02x ", der[k]);
  fputs ("\n-----------------\n", stderr);

  asn1_delete_structure (&definitions);
  asn1_delete_structure (&structure);

  if (!checkSyntaxOnly)
    {
      if (outputFileName == NULL)
	createFileName (inputFileAssignmentName, &outputFileName);

      fprintf (stderr, "\nOutputFile=%s\n", outputFileName);

      outputFile = fopen (outputFileName, "w");

      if (outputFile == NULL)
	{
	  fprintf (stderr,
		   "asn1Coding: output file '%s' not available\n",
		   outputFileName);
	  free (der);
	  free (inputFileAsnName);
	  free (inputFileAssignmentName);
	  free (outputFileName);
	  exit (1);
	}

      for (k = 0; k < der_len; k++)
	fprintf (outputFile, "%c", der[k]);
      fclose (outputFile);
      fputs ("\nWriting: done.\n", stderr);
    }

  free (der);

  free (inputFileAsnName);
  free (inputFileAssignmentName);
  free (outputFileName);

  exit (0);
}
示例#24
0
文件: ExportHTML.cpp 项目: AdriCS/osg
bool ExportHTML::write(osgPresentation::SlideEventHandler* seh, osgViewer::Viewer& viewer, const std::string& filename)
{
    std::string image_basename;
    std::string image_ext;
    std::string html_basename;
    std::string html_ext;

    std::string ext = osgDB::getFileExtension(filename);
    if (ext=="html" || ext=="htm")
    {
        image_basename = osgDB::getNameLessExtension(filename);
        image_ext = ".jpg";
        html_basename = osgDB::getNameLessExtension(filename);
        html_ext = std::string(".")+ext;
    }
    else
    {
        image_basename = osgDB::getNameLessExtension(filename);
        image_ext = ".jpg";
    }
    
    std::cout<<"Writing slides to "<<image_basename<<"_[slidenumber]"<<image_ext<<std::endl;

    osg::ref_ptr<SnapImageDrawCallback> sidc = new SnapImageDrawCallback;

    osgViewer::Viewer::Cameras cameras;
    viewer.getCameras(cameras);

    for(osgViewer::Viewer::Cameras::iterator itr = cameras.begin();
        itr != cameras.end();
        ++itr)
    {
        (*itr)->setPostDrawCallback(sidc.get());
    }

    std::string home_file = createFileName(html_basename, 0, html_ext);

    unsigned int i;
    for(i=0; i<seh->getNumSlides(); ++i)
    {
        std::ostringstream os;
        os << image_basename <<"_"<<i<<image_ext;

        sidc->setFileName(os.str());
        sidc->setSnapImageOnNextFrame(true);

        if (!html_basename.empty())
        {
            std::string htmlFileName = createFileName(html_basename, i, html_ext);

            std::ofstream fout(htmlFileName.c_str());
            if (fout)
            {
                std::string previous_file = i>0 ? createFileName(html_basename,i-1,html_ext) : "";
                std::string next_file = i<seh->getNumSlides()-1 ? createFileName(html_basename,i+1,html_ext) : "";

                std::cout<<"Writing html slides "<<htmlFileName<<std::endl;

                fout<<"<html>"<<std::endl;
                fout<<"<table width=\"100%\">"<<std::endl;
                fout<<"<tr>"<<std::endl;
                if (!previous_file.empty())
                {
                    fout<<"<td align=\"left\" width=\"33%\"><a href=\""<<osgDB::getSimpleFileName(previous_file)<<"\"> Previous </a></td>"<<std::endl;
                }
                else
                {
                    fout<<"<td align=\"left\" width=\"33%\"></td>"<<std::endl;
                }
                if (i != 0)
                {
                    fout<<"<td align=\"center\" width=\"33%\"><a href=\""<<osgDB::getSimpleFileName(home_file)<<"\"> Home </a></td>"<<std::endl;
                }
                else
                {
                    fout<<"<td align=\"center\" width=\"33%\"></td>"<<std::endl;
                }
                if (!next_file.empty())
                {
                    fout<<"<td align=\"right\" width=\"33%\"><a href=\""<<osgDB::getSimpleFileName(next_file)<<"\"> Next </a></td>"<<std::endl;
                }
                else
                {
                    fout<<"<td align=\"right\" width=\"33%\"></td>"<<std::endl;
                }
                fout<<"</tr>"<<std::endl;
                fout<<"</table>"<<std::endl;
                fout<<"<img src=\""<<osgDB::getSimpleFileName(os.str())<<"\">"<<std::endl; 
                fout<<"</html>"<<std::endl;
            }
            else
            {
                std::cout<<"Could not open '"<<filename<<"' for writing."<<std::endl;
            }
        }
        // wait for all cull and draw threads to complete.

        seh->selectSlide(i, osgPresentation::SlideEventHandler::LAST_POSITION);

        // fire off the cull and draw traversals of the scene.
        viewer.frame();
    }
    return true;
}
/** This thread controls acquisition, reads SFRM files to get the image data, and
  * does the callbacks to send it to higher layers */
void BISDetector::BISTask()
{
    int status = asynSuccess;
    int imageCounter;
        int numImages, numImagesCounter;
    int imageMode;
    int acquire;
    NDArray *pImage;
    double acquireTime, timeRemaining;
    ADShutterMode_t shutterMode;
    int frameType;
    int numDarks;
    double readSFRMTimeout;
    epicsTimeStamp startTime, currentTime;
    const char *functionName = "BISTask";
    char fullFileName[MAX_FILENAME_LEN];
    char statusMessage[MAX_MESSAGE_SIZE];
    size_t dims[2];
    int itemp;
    int arrayCallbacks;
    
    this->lock();

    /* Loop forever */
    while (1) {
        /* Is acquisition active? */
        getIntegerParam(ADAcquire, &acquire);
        
        /* If we are not acquiring then wait for a semaphore that is given when acquisition is started */
        if (!acquire) {
            setStringParam(ADStatusMessage, "Waiting for acquire command");
            setIntegerParam(ADStatus, ADStatusIdle);
            callParamCallbacks();
            /* Release the lock while we wait for an event that says acquire has started, then lock again */
            this->unlock();
            asynPrint(this->pasynUserSelf, ASYN_TRACE_FLOW, 
                "%s:%s: waiting for acquire to start\n", driverName, functionName);
            status = epicsEventWait(this->startEventId);
            this->lock();
            setIntegerParam(ADNumImagesCounter, 0);
        }
        
        /* Get current values of some parameters */
        getIntegerParam(ADFrameType, &frameType);
        /* Get the exposure parameters */
        getDoubleParam(ADAcquireTime, &acquireTime);
        getIntegerParam(ADShutterMode, &itemp);  shutterMode = (ADShutterMode_t)itemp;
        getDoubleParam(BISSFRMTimeout, &readSFRMTimeout);
        
        setIntegerParam(ADStatus, ADStatusAcquire);

        /* Create the full filename */
        createFileName(sizeof(fullFileName), fullFileName);
        
        setStringParam(ADStatusMessage, "Starting exposure");
        /* Call the callbacks to update any changes */
        setStringParam(NDFullFileName, fullFileName);
        callParamCallbacks();
        switch (frameType) {
            case BISFrameNormal:
                epicsSnprintf(this->toBIS, sizeof(this->toBIS), 
                    "[Scan /Filename=%s /scantime=%f /Rescan=0]", fullFileName, acquireTime);
                break;
            case BISFrameDark:
                getIntegerParam(BISNumDarks, &numDarks);
                epicsSnprintf(this->toBIS, sizeof(this->toBIS), 
                    "[Dark /AddTime=%f /Repetitions=%d]", acquireTime, numDarks);
                break;
            case BISFrameRaw:
                epicsSnprintf(this->toBIS, sizeof(this->toBIS), 
                    "[Scan /Filename=%s /scantime=%f /Rescan=0 /DarkFlood=0]", fullFileName, acquireTime);
                break;
            case BISFrameDoubleCorrelation:
                epicsSnprintf(this->toBIS, sizeof(this->toBIS), 
                    "[Scan /Filename=%s /scantime=%f /Rescan=1]", fullFileName, acquireTime);
                break;
        }
        /* Send the acquire command to BIS */
        writeBIS(2.0);

        setStringParam(ADStatusMessage, "Waiting for Acquisition");
        callParamCallbacks();
        /* Set the the start time for the TimeRemaining counter */
        epicsTimeGetCurrent(&startTime);
        timeRemaining = acquireTime;

        /* BIS will control the shutter if we are using the hardware shutter signal.
         * If we are using the EPICS shutter then tell it to open */
        if (shutterMode == ADShutterModeEPICS) ADDriver::setShutter(1);

        /* Wait for the exposure time using epicsEventWaitWithTimeout, 
         * so we can abort. */
        epicsTimerStartDelay(this->timerId, acquireTime);
        while(1) {
            this->unlock();
            status = epicsEventWaitWithTimeout(this->stopEventId, BIS_POLL_DELAY);
            this->lock();
            if (status == epicsEventWaitOK) {
                /* The acquisition was stopped before the time was complete */
                epicsTimerCancel(this->timerId);
                break;
            }
            epicsTimeGetCurrent(&currentTime);
            timeRemaining = acquireTime -  epicsTimeDiffInSeconds(&currentTime, &startTime);
            if (timeRemaining < 0.) timeRemaining = 0.;
            setDoubleParam(ADTimeRemaining, timeRemaining);
            callParamCallbacks();
        }
        if (shutterMode == ADShutterModeEPICS) ADDriver::setShutter(0);
        setDoubleParam(ADTimeRemaining, 0.0);
        callParamCallbacks();
        this->unlock();
        status = epicsEventWaitWithTimeout(this->readoutEventId, 5.0);
        this->lock();
        /* If there was an error jump to bottom of loop */
        if (status != epicsEventWaitOK) {
            setIntegerParam(ADAcquire, 0);
            asynPrint(pasynUserSelf, ASYN_TRACE_ERROR,
                "%s:%s: error waiting for readout to complete\n",
                driverName, functionName);
            goto done;
        }
        getIntegerParam(NDArrayCallbacks, &arrayCallbacks);
        getIntegerParam(NDArrayCounter, &imageCounter);
        imageCounter++;
        setIntegerParam(NDArrayCounter, imageCounter);
        getIntegerParam(ADNumImagesCounter, &numImagesCounter);
        numImagesCounter++;
        setIntegerParam(ADNumImagesCounter, numImagesCounter);
        callParamCallbacks();

        if (arrayCallbacks && frameType != BISFrameDark) {
            /* Get an image buffer from the pool */
            getIntegerParam(ADSizeX, &itemp); dims[0] = itemp;
            getIntegerParam(ADSizeY, &itemp); dims[1] = itemp;
            pImage = this->pNDArrayPool->alloc(2, dims, NDInt32, 0, NULL);
            epicsSnprintf(statusMessage, sizeof(statusMessage), "Reading from File %s", fullFileName);
            setStringParam(ADStatusMessage, statusMessage);
            callParamCallbacks();
            status = readSFRM(fullFileName, &startTime, acquireTime + readSFRMTimeout, pImage); 
            /* If there was an error jump to bottom of loop */
            if (status) {
                setIntegerParam(ADAcquire, 0);
                pImage->release();
                goto done;
            } 

            /* Put the frame number and time stamp into the buffer */
            pImage->uniqueId = imageCounter;
            pImage->timeStamp = startTime.secPastEpoch + startTime.nsec / 1.e9;
            updateTimeStamp(&pImage->epicsTS);

            /* Get any attributes that have been defined for this driver */        
            this->getAttributes(pImage->pAttributeList);

            /* Call the NDArray callback */
            /* Must release the lock here, or we can get into a deadlock, because we can
             * block on the plugin lock, and the plugin can be calling us */
            this->unlock();
            asynPrint(this->pasynUserSelf, ASYN_TRACE_FLOW, 
                 "%s:%s: calling NDArray callback\n", driverName, functionName);
            doCallbacksGenericPointer(pImage, NDArrayData, 0);
            this->lock();
            /* Free the image buffer */
            pImage->release();
        }
        getIntegerParam(ADImageMode, &imageMode);
        if (imageMode == ADImageMultiple) {
            getIntegerParam(ADNumImages, &numImages);
            if (numImagesCounter >= numImages) setIntegerParam(ADAcquire, 0);
        }    
        if (imageMode == ADImageSingle) setIntegerParam(ADAcquire, 0);
        done:
        callParamCallbacks();
    }
}
void dataPageFunction(int choice)
{
	string fname,data,updatedData;
	int pageNo,result;
	switch(choice)
	{
		case 1: cout<<"\n Creating data page.....";
			cout<<"\n Enter the name of the data file to be created: ";
			cin>>fname;
			createFileName(fname);
			break;
		case 2: cout<<"\n Opening a data page.....";
			cout<<"\n Enter the name of the data file to be opened: ";
			cin>>fname;
			openFileName(fname);
			break;
		case 3: cout<<"\n Displaying the properties of the data page....";
			cout<<"\n Enter the name of the data file: ";
			cin>>fname;
			cout<<"\n Enter the page, for which details are to be displayed: ";
			cin>>pageNo;
			dispPageProperties(fname,pageNo);
			break;
		case 4: cout<<"\n Displaying the page as hex.....";
			cout<<"\n Enter the name of the data file: ";
			cin>>fname;
			cout<<"\n Enter the page, for which hex dump has to be displayed: ";
			cin>>pageNo;
			printhex(fname,pageNo);
			break;
		case 5: cout<<"\n Inserting data into a data page.....";
			cout<<"\n Enter the name of the data file: ";
			cin>>fname;
			cout<<"\n Enter the page no.: ";
			cin>>pageNo;
			cout<<"\n Enter the data to be inserted: ";
			cin>>data;
			result = insertData(fname,pageNo,data);
			cout<<"\n No. of rows modified: "<<result;
			break;
		case 6: cout<<"\n Deleting data from a data page....";
			cout<<"\n Enter the name of the data file: ";
			cin>>fname;
			cout<<"\n Enter the data to be deleted: ";
			cin>>data;
			result = deleteData(fname,data);
			cout<<"\n No. of rows modified: "<<result;
			break;
		case 7: cout<<"\n Listing all the data pages.....";
			cout<<"\n Enter the name of the data file: ";
			cin>>fname;
			dispPageProperties(fname);
			break;
		case 8: cout<<"\n Modifying data in a data page.....";
			cout<<"\n Enter the name of the data file: ";
			cin>>fname;
			cout<<"\n Enter the data to be modified: ";
			cin>>data;
			cout<<"\n Enter the data to be updated: ";
			cin>>updatedData;
			result = updateData(fname,data,updatedData);
			cout<<"\n No. of rows modified: "<<result;
			break;
		case 9: cout<<"\n Printing all the slots information.....";
			cout<<"\n Enter the name of the data file: ";
			cin>>fname;
			printAllSlotsInformation(fname);
			break;
		case 10: cout<<"\n Exiting.....";
			 break;
	}
}
示例#27
0
//***************************************************************************
int Kwave::SaveBlocksPlugin::start(QStringList &params)
{
    qDebug("SaveBlocksPlugin::start()");

    // interprete the parameters
    int result = interpreteParameters(params);
    if (result) return result;

    QString filename = m_url.path();
    QFileInfo file(filename);
    QString path = file.absolutePath();
    QString ext  = file.suffix();
    QString base = findBase(filename, m_pattern);
    QByteArray sep("/");

    // determine the selection settings
    sample_index_t selection_left  = 0;
    sample_index_t selection_right = 0;
    selection(0, &selection_left, &selection_right, false);

    bool selected_something = (selection_left != selection_right);
    bool selected_all = ((selection_left == 0) &&
                         (selection_right+1 >= signalLength()));
    bool enable_selection_only = selected_something && !selected_all;
    bool selection_only = enable_selection_only && m_selection_only;

    if (selection_only) {
	selection(0, &selection_left, &selection_right, true);
    } else {
	selection_left  = 0;
	selection_right = signalLength() - 1;
    }

    // get the index range
    scanBlocksToSave(base, selection_only);
    unsigned int count = m_block_info.count();
    unsigned int first = firstIndex(path, base, ext, m_pattern,
                                    m_numbering_mode, count);

//     qDebug("m_url            = '%s'", m_url.prettyURL().local8Bit().data());
//     qDebug("m_pattern        = '%s'", m_pattern.local8Bit().data());
//     qDebug("m_numbering_mode = %d", (int)m_numbering_mode);
//     qDebug("selection_only   = %d", selection_only);
//     qDebug("indices          = %u...%u (count=%u)", first, first+count-1,count);

    // iterate over all blocks to check for overwritten files and missing dirs
    QStringList  overwritten_files;
    QStringList  missing_dirs;
    for (unsigned int i = first; i < (first + count); i++) {
	QString name = createFileName(base, ext, m_pattern, i, count,
	                              first + count - 1);
	QString display_name = Kwave::Parser::unescape(name);

	// split the name into directory and file name
	name = QString::fromLatin1(QUrl::toPercentEncoding(display_name, sep));
	QUrl url = m_url.adjusted(QUrl::RemoveFilename);
	url.setPath(url.path(QUrl::FullyEncoded) + name, QUrl::StrictMode);

	QString filename = url.path();
	QFileInfo file_info(filename);

	// check for potentially overwritten file
	if (file_info.exists())
	    overwritten_files += Kwave::Parser::unescape(display_name);

	// check for missing subdirectory
	if (!file_info.dir().exists()) {
	    QFileInfo inf(display_name);
	    QString missing_dir = inf.path();
	    if (!missing_dirs.contains(missing_dir))
		missing_dirs += missing_dir;
	}
    }

    // inform about overwritten files
    if (!overwritten_files.isEmpty()) {
	// ask the user for confirmation if he really wants to overwrite...
	if (Kwave::MessageBox::warningYesNo(parentWidget(),
	    _("<html>") +
	    i18n("This would overwrite the following file(s): %1" \
	    "Do you really want to continue?",
	    createDisplayList(overwritten_files, 5)) +
	    _("</html>") ) != KMessageBox::Yes)
	{
	    return -1;
	}
    }

    // handle missing directories
    if (!missing_dirs.isEmpty()) {
	// ask the user if he wants to continue and create the directory
	if (Kwave::MessageBox::warningContinueCancel(parentWidget(),
	    i18n("The following directories do not exist: %1"
	         "Do you want to create them and continue?",
	         createDisplayList(missing_dirs, 5)),
	    QString(),
	    QString(),
	    QString(),
	    _("saveblocks_create_missing_dirs")
	    ) != KMessageBox::Continue)
	{
	    return -1;
	}

	// create all missing directories
	QUrl base_url = m_url.adjusted(QUrl::RemoveFilename);
	foreach (const QString &missing, missing_dirs) {
	    QUrl url(base_url);
	    url.setPath(
		base_url.path(QUrl::FullyEncoded) +
		QString::fromLatin1(QUrl::toPercentEncoding(missing)),
		QUrl::StrictMode
	    );
	    QString path = url.path();
	    QDir dir;
	    if (!dir.mkpath(path))
		qWarning("creating path '%s' failed", DBG(path));
	}
    }
示例#28
0
asynStatus mar345::acquireFrame()
{
    asynStatus status=asynSuccess;
    epicsTimeStamp startTime, currentTime;
    int eraseMode;
    epicsEventWaitStatus waitStatus;
    int imageCounter;
    int arrayCallbacks;
    double acquireTime;
    double timeRemaining;
    int size, res;
    int shutterMode, useShutter;
    char tempFileName[MAX_FILENAME_LEN];
    char fullFileName[MAX_FILENAME_LEN];
    //const char *functionName = "acquireframe";

    /* Get current values of some parameters */
    getDoubleParam(ADAcquireTime, &acquireTime);
    getIntegerParam(ADShutterMode, &shutterMode);
    getIntegerParam(mar345Size, &size);
    getIntegerParam(mar345Res, &res);
    getIntegerParam(NDArrayCallbacks, &arrayCallbacks);
    getIntegerParam(mar345EraseMode, &eraseMode);
    if (shutterMode == ADShutterModeNone) useShutter=0; else useShutter=1;

    epicsTimeGetCurrent(&this->acqStartTime);

    createFileName(MAX_FILENAME_LEN, tempFileName);
    /* We need to append the extension */
    epicsSnprintf(fullFileName, sizeof(fullFileName), "%s.mar%d", tempFileName, imageSizes[res][size]);

    /* Erase before exposure if set */
    if (eraseMode == mar345EraseBefore) {
        status = this->erase();
        if (status) return(status);
    }
    
    /* Set the the start time for the TimeRemaining counter */
    epicsTimeGetCurrent(&startTime);
    timeRemaining = acquireTime;
    if (useShutter) setShutter(1);

    /* Wait for the exposure time using epicsEventWaitWithTimeout, 
     * so we can abort */
    epicsTimerStartDelay(this->timerId, acquireTime);
    setIntegerParam(ADStatus, mar345StatusExpose);
    callParamCallbacks();
    while(1) {
        if (epicsEventTryWait(this->abortEventId) == epicsEventWaitOK) {
            status = asynError;
            break;
        }
        this->unlock();
        waitStatus = epicsEventWaitWithTimeout(this->stopEventId, MAR345_POLL_DELAY);
        this->lock();
        if (waitStatus == epicsEventWaitOK) {
            /* The acquisition was stopped before the time was complete */
            epicsTimerCancel(this->timerId);
            break;
        }
        epicsTimeGetCurrent(&currentTime);
        timeRemaining = acquireTime - 
            epicsTimeDiffInSeconds(&currentTime, &startTime);
        if (timeRemaining < 0.) timeRemaining = 0.;
        setDoubleParam(ADTimeRemaining, timeRemaining);
        callParamCallbacks();
    }
    setDoubleParam(ADTimeRemaining, 0.0);
    if (useShutter) setShutter(0);
    setIntegerParam(ADStatus, mar345StatusIdle);
    callParamCallbacks();
    // If the exposure was aborted return error
    if (status) return asynError;
    setIntegerParam(ADStatus, mar345StatusScan);
    callParamCallbacks();
    epicsSnprintf(this->toServer, sizeof(this->toServer), "COMMAND SCAN %s", fullFileName);
    setStringParam(NDFullFileName, fullFileName);
    callParamCallbacks();
    writeServer(this->toServer);
    status = waitForCompletion("SCAN_DATA    Ended o.k.", MAR345_COMMAND_TIMEOUT);
    if (status) {
        return asynError;
    }
    getIntegerParam(NDArrayCounter, &imageCounter);
    imageCounter++;
    setIntegerParam(NDArrayCounter, imageCounter);
    /* Call the callbacks to update any changes */
    callParamCallbacks();

    /* If arrayCallbacks is set then read the file back in */
    if (arrayCallbacks) {
        getImageData();
    }

    /* Erase after scanning if set */
    if (eraseMode == mar345EraseAfter) status = this->erase();

    return status;
}
示例#29
0
/** Base method for reading a file
  * Creates the file name with NDPluginBase::createFileName, then calls the pure virtual functions openFile,
  * readFile and closeFile in the derived class.  Does callbacks with the NDArray that was read in. */
asynStatus NDPluginFile::readFileBase(void)
{
    asynStatus status = asynSuccess;
    char fullFileName[MAX_FILENAME_LEN];
    NDArray *pArray=NULL;
    char errorMessage[256];
    static const char* functionName = "readFileBase";

    setIntegerParam(NDFileWriteStatus, NDFileWriteOK);
    setStringParam(NDFileWriteMessage, "");

    status = (asynStatus)createFileName(MAX_FILENAME_LEN, fullFileName);
    if (status) { 
        asynPrint(this->pasynUserSelf, ASYN_TRACE_ERROR, 
              "%s::%s error creating full file name, fullFileName=%s, status=%d\n", 
              driverName, functionName, fullFileName, status);
        return status;
    }
    
    /* Call the readFile method in the derived class */
    /* Do this with the main lock released since it is slow */
    setStringParam(NDFullFileName, fullFileName);
    this->unlock();
    epicsMutexLock(this->fileMutexId);
    status = this->openFile(fullFileName, NDFileModeRead, pArray);
    if (status) {
        epicsSnprintf(errorMessage, sizeof(errorMessage)-1,
                "Error opening file %s, status=%d", fullFileName, status);
        asynPrint(this->pasynUserSelf, ASYN_TRACE_ERROR,
                "%s::%s %s\n",
                driverName, functionName, errorMessage);
        setIntegerParam(NDFileWriteStatus, NDFileWriteError);
        setStringParam(NDFileWriteMessage, errorMessage);
    }
    else {
        status = this->readFile(&pArray);
        if (status) {
            epicsSnprintf(errorMessage, sizeof(errorMessage)-1,
                    "Error  file %s, status=%d", fullFileName, status);
            asynPrint(this->pasynUserSelf, ASYN_TRACE_ERROR,
                    "%s::%s %s\n",
                    driverName, functionName, errorMessage);
            setIntegerParam(NDFileWriteStatus, NDFileWriteError);
            setStringParam(NDFileWriteMessage, errorMessage);
        }
        this->closeFile();
    }
    epicsMutexUnlock(this->fileMutexId);
    this->lock();
    
    /* If we got an error then return */
    if (status) return(status);
    
    // This sets all of the plugin PVs from the NDArray
    NDPluginDriver::beginProcessCallbacks(pArray);    

    /* Call any registered clients */
    NDPluginDriver::endProcessCallbacks(pArray, false, true);

    return status;
}
void DepthPeelBin::drawImplementation( osg::RenderInfo& renderInfo, osgUtil::RenderLeaf*& previous )
{
    TRACEDUMP("DepthPeelBin::drawImplementation");
    UTIL_GL_ERROR_CHECK("DepthPeelBin::drawImplementation start");

    unsigned int debugMode = Manager::instance()->getDebugMode();

    osg::State& state = *renderInfo.getState();
    const unsigned int contextID = state.getContextID();
    osg::FBOExtensions* fboExt( osg::FBOExtensions::instance( contextID, true ) );
    UTIL_GL_FBO_ERROR_CHECK("DepthPeelBin::drawImplementation start",fboExt);
    osg::GL2Extensions* ext = osg::GL2Extensions::Get( contextID, true );
    UTIL_MEMORY_CHECK( ext, "DepthPeelBin: NULL GL2Extensions", );

    // Get the last applied viewport. When we render to our internal textures,
    // we will render to the lower left corner in an area the size of the viewport.
    // We track the width and height and maintain internal textures large enough
    // to render the largest width and height we've seen.
    const osg::Viewport* vp = dynamic_cast< const osg::Viewport* >(
        state.getLastAppliedAttribute( osg::StateAttribute::VIEWPORT ) );
    const GLsizei width( vp->width() ), height( vp->height() );

    char* pixels( NULL );
    const bool dumpImages = ( ( debugMode & backdropFX::BackdropCommon::debugImages ) != 0 );
    if( dumpImages )
    {
        pixels = new char[ width * height * 4 ];
        UTIL_MEMORY_CHECK( pixels, "DepthPeelBin: debug image pixel buffer", )
    }

    // Fix for redmine issue 8, and the recurrance of this issue
    // in the new depth peel work.
    // The most general way to handle the single StateGraph case
    // is to save the last StateGraph and re-apply it just before
    // we return from ::draw().
    osgUtil::StateGraph* savedStateGraph( NULL );
    if( _stateGraphList.size() )
        savedStateGraph = _stateGraphList.back();

    PerContextInfo& pci = s_contextInfo[ contextID ];
    unsigned int insertStateSetPosition;
    {
        // Get the current Draw FBO and restore it when fboSRH goes out of scope.
        // Get this now, first, before we call pci._init. Also, having it hear means
        // we query OpenGL once. If, instead, we instantiated one of these for every
        // layer, we would query OpenGL every layer. Having just one instance, with
        // its constructor invoked once, is a better solution.
        FBOSaveRestoreHelper fboSRH( fboExt, pci );

        insertStateSetPosition = drawInit( state, previous );

        if( pci._init &&
            ( ( pci._width < width ) || ( pci._height < height ) ) )
        {
            // We've already created textures at a given size, but we
            // now have a larger viewport. Delete those textures and
            // force a re-initialization.
            // NOTE We never resize the textures smaller, only larger.
            osg::notify( osg::INFO ) << "BDFX: DepthPeelBin cleanup. ";
            pci.cleanup( state );
        }
        if( !pci._init )
        {
            osg::notify( osg::INFO ) << "BDFX: DepthPeelBin resize to width: " <<
                width << " height: " << height << std::endl;
            pci.init( state, width, height );
        }

        // Compute the percentage of the texture we will render to.
        // This is the viewport width and height divided by the texture
        // width and height. It's used to ensure we display the appropriate
        // portion of the texture during drawFSTP().
        osg::Vec2f texturePercent( vp->width() / (float)( pci._width ),
            vp->height() / (float)( pci._height ) );
        _texturePercentUniform->set( texturePercent );

        // Uniform locations, used during drawFSTP(). We declare them here and pass
        // them by reference. drawFSTP() inits them after binding the fstpProgram.
        // Then we reuse the values until next frame. Avoids looking up the uniform
        // location (via map keyed by string) for every layer.
        GLint fstpLoc( -1 ), texturePercentLoc( -1 );


        // Opaque pass.
        bool transparentRemaining( false ); // After opaque pass, are there transparent bins?
        int drawCount( 0 );
        {
            osgwTools::glBindFramebuffer( fboExt, GL_FRAMEBUFFER_EXT, pci._fbo );

            state.applyAttribute( _opaqueDepth.get() );
            state.applyMode( GL_DEPTH_TEST, true );
            glClearDepth( 1.0 );
            unsigned int idx;
            for( idx=0; idx<2; idx++ )
            {
                osgwTools::glFramebufferTexture2D( fboExt, GL_DRAW_FRAMEBUFFER_EXT,
                    GL_DEPTH_ATTACHMENT_EXT, GL_TEXTURE_2D, pci._depthTex[ idx ], 0 );
                glClear( GL_DEPTH_BUFFER_BIT );
            }
            osgwTools::glFramebufferTexture2D( fboExt, GL_DRAW_FRAMEBUFFER_EXT,
                GL_DEPTH_ATTACHMENT_EXT, GL_TEXTURE_2D, pci._depthTex[ 2 ], 0 );

            state.setActiveTextureUnit( s_textureUnit );
            glBindTexture( GL_TEXTURE_2D, pci._depthTex[ 0 ] );
            state.setActiveTextureUnit( s_textureUnit+1 );
            glBindTexture( GL_TEXTURE_2D, pci._depthTex[ 1 ] );

            glClearColor( 0., 0., 0., 0. );
            glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
            drawCount = drawOpaque( renderInfo, previous, transparentRemaining );

            // Blend the opaque pass into the output buffer.
            // We could probably do this a different way, by attaching
            // the output color buffer to our FBO and rendering directly
            // into it. This is TBD as a later enhancement.
            fboSRH.restore();

            drawFSTP( renderInfo, state, ext, pci, fstpLoc, texturePercentLoc );

            if( dumpImages )
            {
                FBOSaveRestoreHelper fboSRHRead( fboExt, pci, GL_READ_FRAMEBUFFER_EXT );
                osgwTools::glBindFramebuffer( fboExt, GL_READ_FRAMEBUFFER_EXT, pci._fbo );

                std::string fileName = createFileName( state );
                glReadBuffer( GL_COLOR_ATTACHMENT0_EXT );
                glReadPixels( (GLint)( 0 ), (GLint)( 0 ), width, height, GL_RGBA, GL_UNSIGNED_BYTE, (GLvoid*)pixels );
                backdropFX::debugDumpImage( fileName, pixels, width, height );
                osg::notify( osg::NOTICE ) << " - " << fileName << std::endl;

                fileName = createFileName( state, -1, true );
                glReadPixels( (GLint)( 0 ), (GLint)( 0 ), width, height, GL_DEPTH_COMPONENT, GL_UNSIGNED_SHORT, (GLvoid*)pixels );
                backdropFX::debugDumpDepthImage( fileName, (const short*)pixels, width, height );
                osg::notify( osg::NOTICE ) << " - " << fileName << std::endl;
            }
        }


        // drawOpaque() sets this to true if there are transparent bins to render.
        if( transparentRemaining )
        {
            // Transparent passes
            state.setActiveTextureUnit( s_textureUnit );
            glBindTexture( GL_TEXTURE_2D, pci._depthTex[ 2 ] );

            // If we already drew something in the opaque pass, then GL_LESS has already been
            // set. But if we didn't draw anything in the opaque pass (drawCount==0) then the
            // scene graph will almost certainly set depth function to GL_LESS using lazy state
            // setting. In that case, we must apply state _now_ so that the transparent pass can
            // correctly set the depth function to GL_GREATER.
            if( drawCount == 0 )
                state.apply();

            // Create depth peel layers until we hit _maxPasses, or until
            // occlusion query indicates we didn't render anything.
            unsigned int passCount;
            for( passCount = 0; passCount < _maxPasses; passCount++ )
            {
                // Specify the depth buffer to render to.
                osgwTools::glBindFramebuffer( fboExt, GL_FRAMEBUFFER_EXT, pci._fbo );
                osgwTools::glFramebufferTexture2D( fboExt, GL_DRAW_FRAMEBUFFER_EXT,
                    GL_DEPTH_ATTACHMENT_EXT, GL_TEXTURE_2D, pci._depthTex[ passCount & 0x1 ], 0 );
                osg::notify( osg::DEBUG_FP ) << "  Attaching depth buffer " << pci._depthTex[ passCount & 0x1 ] << std::endl;

                // Use the other depth buffer as an input texture.
                state.setActiveTextureUnit( s_textureUnit+1 );
                glBindTexture( GL_TEXTURE_2D, pci._depthTex[ (passCount+1) & 0x1 ] );
                osg::notify( osg::DEBUG_FP ) << "  Binding depth map " << pci._depthTex[ (passCount+1) & 0x1 ] << std::endl;

                _transparentDepth->apply( state );
                glEnable( GL_DEPTH_TEST );
                glClearDepth( 0.0 );
                glClearColor( 0., 0., 0., 0. );
                glClear( GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT );

                pci._glBeginQuery( GL_SAMPLES_PASSED_ARB, pci._queryID );
                drawTransparent( renderInfo, previous );
                pci._glEndQuery( GL_SAMPLES_PASSED_ARB );

                if( dumpImages )
                {
                    FBOSaveRestoreHelper fboSRHRead( fboExt, pci, GL_READ_FRAMEBUFFER_EXT );
                    osgwTools::glBindFramebuffer( fboExt, GL_READ_FRAMEBUFFER_EXT, pci._fbo );

                    std::string fileName = createFileName( state, passCount );
                    glReadBuffer( GL_COLOR_ATTACHMENT0_EXT );
                    glReadPixels( (GLint)( 0 ), (GLint)( 0 ), width, height, GL_RGBA, GL_UNSIGNED_BYTE, (GLvoid*)pixels );
                    backdropFX::debugDumpImage( fileName, pixels, width, height );
                    osg::notify( osg::NOTICE ) << " - " << fileName << std::endl;

                    fileName = createFileName( state, passCount, true );
                    glReadPixels( (GLint)( 0 ), (GLint)( 0 ), width, height, GL_DEPTH_COMPONENT, GL_UNSIGNED_SHORT, (GLvoid*)pixels );
                    backdropFX::debugDumpDepthImage( fileName, (const short*)pixels, width, height );
                    osg::notify( osg::NOTICE ) << " - " << fileName << std::endl;
                }

                // Query the number of pixels rendered to see if it's time to stop.
                GLint numPixels( 0 );
                pci._glGetQueryObjectiv( pci._queryID, GL_QUERY_RESULT, &numPixels );
                osg::notify( osg::DEBUG_FP ) << "  BDFX: DP pass " << passCount << ",  numPixels " << numPixels << std::endl;
                if( numPixels < _minPixels )
                {
                    passCount++;
                    break;
                }

                // We rendered something, so now we render the FSTP to combine the layer we just
                // created with the original FBO.
                fboSRH.restore();

                drawFSTP( renderInfo, state, ext, pci, fstpLoc, texturePercentLoc );
            }

            if( debugMode & BackdropCommon::debugConsole )
                osg::notify( osg::DEBUG_FP ) << "BDFX: DepthPeelBin: " << passCount << " pass" <<
                ((passCount==1)?".":"es.") << std::endl;

            // Restore to default.
            glClearDepth( 1.0 );

        } // if transparentRemaining
    }


    // RenderBin::drawImplementation wrap-up: State restore.
    drawComplete( state, insertStateSetPosition );

    if( dumpImages )
        delete[] pixels;

    // Re-apply the last StateGraph used to render the child subgraph.
    // This restores state to the way OSG thinks it should be.
    if( savedStateGraph != NULL )
        state.apply( savedStateGraph->getStateSet() );

    UTIL_GL_ERROR_CHECK("DepthPeelBin::drawImplementation end");
    UTIL_GL_FBO_ERROR_CHECK("DepthPeelBin::drawImplementation end",fboExt);
}