//========================================================
void IndexationMenu(){
	int choice , validPath;
	int const maxSizePath = 100;
	char *path[maxSizePath];
	FileType filetype;
	FILE *fileTOindex;
	BaseDesc basedesc;
	initList(&basedesc);
	void *desc = NULL;
	
	do{
		printf("+=========================+\n");
		printf("|                         |\n");
		printf("|1. Index a SOUND         |\n");
		printf("|2. Index an IMAGE        |\n");
		printf("|3. Index a TEXT          |\n");
		printf("|                         |\n");
		printf("+=================0.RETURN+\n");

		scanf("%d" , &choice);
		if(choice!=1 && choice!=0 && choice!=2 && choice!=3){
			system("clear");
		}
	}while(choice!=1 && choice!=2 && choice!=0);
	clearBuffer();
	
	do{
			
					printf("Sgronieunieux\n");
					fflush(stdout);	
		if(choice==0){ system("clear");mainMenu(); }
		printf("Add an empty path with \"Enter\" to start Indexation.\n");
		printf("Enter your(s) path(s) : \n");
		validPath = getKeyboard_String(path,0, maxSizePath);
		if(fileExists(path)){
			fileTOindex=fopen(path,"r");
			if(fileTOindex==NULL){ printf("FAIL !\n"); fflush(stdout) ; exit(0);}
			switch(choice){
				case(1):			 
					addDesc(&basedesc,createSoundDesc(fileTOindex),SOUND);
				break;
				case(2):	
					addDesc(&basedesc,createPictureDesc(fileTOindex),PICTURE);
				break;
				case(3):			
					/*desc=createTextDesc(fileTOindex); 
					basedesc=;
					addDesc(&basedesc,desc,TEXT);*/
				break;
				default: 
					exit(0); 
				break;
			}
			fclose(fileTOindex);
			strcpy(path,""); // Permite to  secure the next path to enter by the user
			printf("Succesfull indexation.\n");
		}
		else{
			system("clear");
			printf("Error, file don\'t exists\n");
			mainMenu();
		}				
	} while ( validPath > 0 ); //while !0=NULL or !-1=so littre or !=-2=ERROR
	mainMenu();
}
Ejemplo n.º 2
0
/* Yet !!! main funtion in here */
int main (int argc, char *argv[])
{
    if (RaiseItsPriority ())
	{
	    printf ("Raise it's priority failed.\n");
	}

    memset (&zfs, 0, sizeof (ZFS));
    PZFS pzfs = &zfs;
    /* Parse command line */
    if (parseArgv (pzfs, argc, argv) != 0)
	exit (-1);

	getFileSupport(CONFIG_SUPPORT_FILE, pzfs); //add by Joe
	ZError(DBG_MISC, "pzfs->audioConfig = %d\n", pzfs->audioConfig);
	ZError(DBG_MISC, "pzfs->photoConfig = %d\n", pzfs->photoConfig);
	ZError(DBG_MISC, "pzfs->videoConfig = %d\n", pzfs->videoConfig);

    /* Check, if /data/ImportsummaryDB exists */
    if (fileExists (IMPORT_SUMMARY_DB) == 0)
	{
	    ZError (DBG_MISC, "Will create database->%s", IMPORT_SUMMARY_DB);
	    if (createImportSummaryDB () != 0)
		{
		    ZError (DBG_MISC, "Create database failed.");
		    exit (-1);
		}
	}
    /* initialize zfs */
    if (initZFS (pzfs) != 0)
	exit (-1);
    /* Sync persist data */
    if (getSummary (pzfs) != 0)
	{
	    ZError (DBG_MISC, "Get persist data failed");
	    exit (-1);
	}

    /* Check to see if the DIR_IMPORT and DIR_IMPORTED exists
       NOTE: The zfs will make sure DIR_IMPORTED (/data/AudioLibrary1exists, if it doesn't exists, create it */
    if (fixImportFolder () != 0)
	exit (-1);
    if (fixImportedFolder () != 0)
	exit (-1);
    if (fixExtractedFolder () != 0)
	exit (-1);
    if (fixTmpFolder () != 0)
	exit (-1);

    /* NOTE:Don't give SIGINT signal, just uncommit it when we want debug it */
    //signal(SIGINT, catchKill); /* ctr+c */
    signal (SIGKILL, catchKill);
    signal (SIGTERM, catchKill);

    /* add_inotify_watch to DIR_IMPORT */
    if (addWatchDir (pzfs, DIR_IMPORT) != 0)
	{
	    ZError (DBG_MISC, "Add watch to %s failed", DIR_IMPORT);
	    exit (-1);
	}

    /* Send ide event to zqdevice for our policy */
    zfsSendIdleEvent ();
    /* TCP & UDP */
    ZUtilStartThread (&pzfs->tcpThr, "ZFS_TCP", pzfs, requestThread);
    ZUtilStartThread (&pzfs->udpThr, "ZFS_UDP", pzfs, eventThread);
    /* Watch thread */
    ZUtilStartThread (&pzfs->watchThr, "ZFS_WATCH", pzfs, watchThread);

    //scan import folder on start
    scanImportFolder(pzfs, REMOVE_UNSUPPORTED_FILE);	 


    /* Task thread */
    sleep (2);			/* TBD */
    ZUtilStartThread (&pzfs->taskThr, "ZFS_TASK", pzfs, taskThead);

    /* NOTE: May we can move one thread in here, May be it can cut down spend */
    while (1) {
		#ifdef 		Z_CFG_SMBPRIORITY
	   //	printf ("this is raise smb priority");
		if(pzfs-> b_renice == TRUE)
		{
		//	printf ("raise sma success 222222222222....");
			ZInfo4 (DBG_MISC,"will RaiseItsPriority.");
			if(RaiseSMBPriority() == 0)
			{
				ZInfo4 (DBG_MISC,"RaiseSMBPriority success.");
			}
			else
			{
				ZError (DBG_MISC,"RaiseSMBPriority failed.");
			}
		}
#endif
       sleep (1);
    }
    return 0;
}
Ejemplo n.º 3
0
	void GingaNclGfx::showText(IWindow* window, string text) {
		ISurface* s;
		IColor* fontColor;
		IColor* bgColor;
		string fontUri;
		int fontSize;

		fontUri = DATA_PREFIX_PATH "/share/ginga/font/decker.ttf";
		fontSize = 12;

		if (!fileExists(fontUri)) {
			cout << "GingaNclGfx::show Warning! File not found: '";
			cout << fontUri.c_str() << "'" << endl;
			return;
		}

		IFontProvider* font = NULL;

		window->clearContent();
		window->show();

#if HAVE_COMPSUPPORT
		font = ((FontProviderCreator*)(cm->getObject("FontProvider")))(
				fontUri.c_str(), fontSize);

		s = ((SurfaceCreator*)(cm->getObject("Surface")))(NULL, 0, 0);
#else
		font = new DFBFontProvider(fontUri.c_str(), fontSize);
		s = new DFBSurface();
#endif

		s->setParent(window);

		bgColor = new Color("black");
		fontColor = new Color("white");

		s->setFont(font);
		s->setColor(fontColor);

		font->playOver(
				(void*)s,
				text.c_str(), 0, 0, (0x00000004 | 0x00000000));

		delete font;
		font = NULL;

#if HAVE_COMPSUPPORT
		cm->releaseComponentFromObject("FontProvider");
#endif

		delete bgColor;
		bgColor = NULL;

		delete s;
		s = NULL;


		delete fontColor;
		fontColor = NULL;

		window->validate();
		window->raiseToTop();
	}
Ejemplo n.º 4
0
int main(int argc, char **argv)
{
  char inFormat[25], outFormat[25], configFile[255];
  int currArg = 1, NUM_ARGS = 1, configFlag = FALSE;
  c2v_config *cfg=NULL;

  if (argc < 3) {
    usage(argv[0]);
    exit(1);
  }
    
  // Check for configuration file option first
  while (currArg < (argc-NUM_ARGS)) {
    char *key = argv[currArg++];
    if (strmatches(key, "-help", "--help", NULL)) {
      usage(argv[0]);
      char format[25], data_dictionary[512];
      CHECK_ARG(1);
      strcpy(format, GET_ARG(1));
      sprintf(data_dictionary, "%s%c%s_data_dictionary.csv", 
        get_asf_share_dir(), DIR_SEPARATOR, format);
      if (fileExists(data_dictionary)) {
        asfPrintStatus("\nFormat defined in %s_data_dictionary.csv\n\n", 
        format);
        catFile(data_dictionary);
        asfPrintStatus("\n\n");
      }
      else
        asfPrintWarning("Could not find a data dictionary for format (%s)!\n\n", 
          format);
      exit(1);
    }
    else if (strmatches(key, "-config", "--config", "-c", NULL)) {
      CHECK_ARG(1);
      strcpy(configFile, GET_ARG(1));
      cfg = read_c2v_config(configFile);
      configFlag = TRUE;
    }
  }
  if (!configFlag) {
    sprintf(configFile, "%s%cconvert2vector.config", 
      get_asf_share_dir(), DIR_SEPARATOR);
    asfPrintStatus("\nReading parameters from default configuration file:\n"
		   "%s\n", configFile);
    cfg = read_c2v_config(configFile);
  }

  // Pick up the rest of the arguments
  currArg = 1;
  NUM_ARGS = 2;
  while (currArg < (argc-NUM_ARGS)) {
    char *key = argv[currArg++];
    if (strmatches(key, "-config", "--config", "-c", NULL)) { ; }
    else if (strmatches(key, "-log", "--log", NULL)) {
      CHECK_ARG(1);
      strcpy(logFile,GET_ARG(1));
      fLog = FOPEN(logFile, "a");
      logflag = TRUE;
    }
    else if (strmatches(key, "-quiet", "--quiet", "-q", NULL))
      quietflag = TRUE;
    else if (strmatches(key, "-list", "--list", NULL))
      cfg->list = TRUE;
    else if (strmatches(key, "-nosplit", "--nosplit", "-ns", NULL))
      cfg->nosplit = TRUE;
    else if (strmatches(key, "-input-format", "--input-format", "-i", NULL)) {
      CHECK_ARG(1);
      strcpy(cfg->input_format, GET_ARG(1));
    }
    else if (strmatches(key, "-output-format", "--output-format", "-o", NULL)) {
      CHECK_ARG(1);
      strcpy(cfg->output_format, GET_ARG(1));
    }
    else {
      --currArg;
      break;
    }
  }
  if ((argc-currArg) < NUM_ARGS) {
    printf("Insufficient arguments.\n");
    usage(argv[0]);
  }

  if (!configFlag) {
    sprintf(cfg->input_file, "%s", argv[currArg++]);
    sprintf(cfg->output_file, "%s", argv[currArg]);
  }

  asfSplashScreen (argc, argv);

  sprintf(inFormat, "%s", uc(cfg->input_format));
  sprintf(outFormat, "%s", uc(cfg->output_format));
  
  // Check whether you can find information about the format in the header
  // list file in the share directory
  dbf_header_t *dbf;
  int nCols;
  char shape_type[25];
  if (strcmp_case(inFormat, "CSV") == 0 ||
    read_header_config(inFormat, &dbf, &nCols, shape_type))
    asfPrintStatus("   Converting a %s format file to %s\n", 
      inFormat, outFormat);
  else
    asfPrintError("   Unsupported input format (%s)\n", inFormat);
  
  // Set output directory as the temporary directory -- where all temp files
  // created during import should be put
  char *tmpdir = get_dirname(cfg->output_file);
  if (tmpdir && strlen(tmpdir) > 0)
    set_asf_tmp_dir(tmpdir);

  convert2vector(cfg);

  asfPrintStatus("Done.\n\n");

  return(0);
}
Ejemplo n.º 5
0
  Config::Config(const std::string country, const std::string config_file, const std::string runtime_dir)
  {

    string debug_message = "";

    this->loaded = false;


    string configFile;

    char* envConfigFile;
    envConfigFile = getenv (ENV_VARIABLE_CONFIG_FILE);
    if (config_file.compare("") != 0)
    {
        // User has supplied a config file.  Use that.
      configFile = config_file;
      debug_message = "Config file location provided via API";
    }
    else if (envConfigFile != NULL)
    {
      // Environment variable is non-empty.  Use that.
      configFile = envConfigFile;
      debug_message = "Config file location provided via environment variable: " + string(ENV_VARIABLE_CONFIG_FILE);
    }
    else if (DirectoryExists(getExeDir().c_str()) && fileExists((getExeDir() + CONFIG_FILE).c_str()))
    {
          configFile = getExeDir() + CONFIG_FILE;
      debug_message = "Config file location provided via exe location";
    }
    else
    {
      // Use the default
      configFile = DEFAULT_CONFIG_FILE;
      debug_message = "Config file location provided via default location";
    }

    //string configFile = (this->runtimeBaseDir + CONFIG_FILE);

    if (fileExists(configFile.c_str()) == false)
    {
      std::cerr << "--(!) Config file '" << configFile << "' does not exist!" << endl;
      std::cerr << "--(!)             You can specify the configuration file location via the command line " << endl;
      std::cerr << "--(!)             or by setting the environment variable '" << ENV_VARIABLE_CONFIG_FILE << "'" << endl;
      return;
    }
    else if (DirectoryExists(configFile.c_str()))
    {
      std::cerr << "--(!) Config file '" << configFile << "' was specified as a directory, rather than a file!" << endl;
      std::cerr << "--(!)             Please specify the full path to the 'openalpr.conf file'" << endl;
      std::cerr << "--(!)             e.g., /etc/openalpr/openalpr.conf" << endl;
      return;
    }


    this->country = country;


    loadCommonValues(configFile);

    if (runtime_dir.compare("") != 0)
    {
      // User provided a runtime directory directly into the library.  Use this.
      this->runtimeBaseDir = runtime_dir;
    }

    if ((DirectoryExists(this->runtimeBaseDir.c_str()) == false) &&
            (DirectoryExists((getExeDir() + RUNTIME_DIR).c_str())))
    {
            // Runtime dir in the config is invalid and there is a runtime dir in the same dir as the exe.
      this->runtimeBaseDir = getExeDir() + RUNTIME_DIR;

    }

    if (DirectoryExists(this->runtimeBaseDir.c_str()) == false)
    {
      std::cerr << "--(!) Runtime directory '" << this->runtimeBaseDir << "' does not exist!" << endl;
      std::cerr << "--(!)                   Please update the OpenALPR config file: '" << configFile << "'" << endl;
      std::cerr << "--(!)                   to point to the correct location of your runtime_dir" << endl;
      return;
    }

    std::string country_config_file = this->runtimeBaseDir + "/config/" + country + ".conf";
    if (fileExists(country_config_file.c_str()) == false)
    {
      std::cerr << "--(!) Country config file '" << country_config_file << "' does not exist.  Missing config for the country: '" << country<< "'!" << endl;
      return;
    }
    
    loadCountryValues(country_config_file, country);

    if (fileExists((this->runtimeBaseDir + "/ocr/tessdata/" + this->ocrLanguage + ".traineddata").c_str()) == false)
    {
      std::cerr << "--(!) Runtime directory '" << this->runtimeBaseDir << "' is invalid.  Missing OCR data for the country: '" << country<< "'!" << endl;
      return;
    }
    
    if (this->debugGeneral)
    {
      std::cout << debug_message << endl;
    }

    this->loaded = true;
  }
Ejemplo n.º 6
0
int wmain(int argc, wchar_t* argv[])
{
	Global.Radix = 10;
	Global.Revalidate = true;
	Global.Section = 0;
	Global.nocash = false;
	Global.IncludeNestingLevel = 0;
	Global.FileInfo.FileCount = 0;
	Global.FileInfo.TotalLineCount = 0;
	Global.DebugMessages = 0;
	Global.relativeInclude = false;
	Global.warningAsError = false;
	Global.validationPasses = 0;
	Arch = &InvalidArchitecture;

	Logger::printLine("ARMIPS Assembler v0.7d ("__DATE__" "__TIME__") by Kingcom");
	StringList arguments = getStringListFromArray(argv,argc);

	if (arguments.size() < 2)
	{
		Logger::printLine("Usage: armips.exe file.asm [-temp temp.txt] [-sym symfile.sym]");
		return 1;
	}

	if (fileExists(arguments[1]) == false)
	{
		Logger::printLine("File %S not found\n",arguments[1].c_str());
		return 1;
	}

	int argpos = 2;
	while (argpos < (int)arguments.size())
	{
		if (arguments[argpos] == L"-temp")
		{
			Global.tempData.setFileName(arguments[argpos+1]);
			argpos += 2;
		} else if (arguments[argpos] == L"-sym")
		{
			Global.symData.setNocashSymFileName(arguments[argpos+1]);
			argpos += 2;
		} else if (arguments[argpos] == L"-exsym")
		{
			Global.symData.setExSymFileName(arguments[argpos+1]);
			argpos += 2;
		} else if (arguments[argpos] == L"-erroronwarning")
		{
			Global.warningAsError = true;
			argpos += 1;
		} else {
			Logger::printLine("Invalid parameter %S\n",arguments[argpos].c_str());
			return 1;
		}
	}

	LoadAssemblyFile(arguments[1]);
	if (Logger::hasError())
	{
		Logger::printLine("Aborting.");
		return 1;
	}

	if (EncodeAssembly() == true)
	{
		Logger::printLine("Done.");
	} else {
		Logger::printLine("Aborting.");
		return 1;
	}
	return 0;
}
Ejemplo n.º 7
0
//---------------------------------------------------------------------------
void ensureOutputFilesExist(const SubmitDagDeepOptions &deepOpts,
			SubmitDagShallowOptions &shallowOpts)
{
	int maxRescueDagNum = param_integer("DAGMAN_MAX_RESCUE_NUM",
				MAX_RESCUE_DAG_DEFAULT, 0, ABS_MAX_RESCUE_DAG_NUM);

	if (deepOpts.doRescueFrom > 0)
	{
		MyString rescueDagName = RescueDagName(shallowOpts.primaryDagFile.Value(),
				shallowOpts.dagFiles.number() > 1, deepOpts.doRescueFrom);
		if (!fileExists(rescueDagName))
		{
			fprintf( stderr, "-dorescuefrom %d specified, but rescue "
						"DAG file %s does not exist!\n", deepOpts.doRescueFrom,
						rescueDagName.Value() );
	    	exit( 1 );
		}
	}

		// Get rid of the halt file (if one exists).
	tolerant_unlink( HaltFileName( shallowOpts.primaryDagFile ).Value() );

	if (deepOpts.bForce)
	{
		tolerant_unlink(shallowOpts.strSubFile.Value());
		tolerant_unlink(shallowOpts.strSchedLog.Value());
		tolerant_unlink(shallowOpts.strLibOut.Value());
		tolerant_unlink(shallowOpts.strLibErr.Value());
		RenameRescueDagsAfter(shallowOpts.primaryDagFile.Value(),
					shallowOpts.dagFiles.number() > 1, 0, maxRescueDagNum);
	}

		// Check whether we're automatically running a rescue DAG -- if
		// so, allow things to continue even if the files generated
		// by condor_submit_dag already exist.
	bool autoRunningRescue = false;
	if (deepOpts.autoRescue) {
		int rescueDagNum = FindLastRescueDagNum(shallowOpts.primaryDagFile.Value(),
					shallowOpts.dagFiles.number() > 1, maxRescueDagNum);
		if (rescueDagNum > 0) {
			printf("Running rescue DAG %d\n", rescueDagNum);
			autoRunningRescue = true;
		}
	}

	bool bHadError = false;
		// If not running a rescue DAG, check for existing files
		// generated by condor_submit_dag...
	if (!autoRunningRescue && deepOpts.doRescueFrom < 1 && !deepOpts.updateSubmit) {
		if (fileExists(shallowOpts.strSubFile))
		{
			fprintf( stderr, "ERROR: \"%s\" already exists.\n",
				 	shallowOpts.strSubFile.Value() );
			bHadError = true;
		}
		if (fileExists(shallowOpts.strLibOut))
		{
			fprintf( stderr, "ERROR: \"%s\" already exists.\n",
				 	shallowOpts.strLibOut.Value() );
			bHadError = true;
		}
		if (fileExists(shallowOpts.strLibErr))
		{
			fprintf( stderr, "ERROR: \"%s\" already exists.\n",
				 	shallowOpts.strLibErr.Value() );
			bHadError = true;
		}
		if (fileExists(shallowOpts.strSchedLog))
		{
			fprintf( stderr, "ERROR: \"%s\" already exists.\n",
				 	shallowOpts.strSchedLog.Value() );
			bHadError = true;
		}
	}

		// This is checking for the existance of an "old-style" rescue
		// DAG file.
	if (!deepOpts.autoRescue && deepOpts.doRescueFrom < 1 &&
				fileExists(shallowOpts.strRescueFile))
	{
		fprintf( stderr, "ERROR: \"%s\" already exists.\n",
				 shallowOpts.strRescueFile.Value() );
	    fprintf( stderr, "  You may want to resubmit your DAG using that "
				 "file, instead of \"%s\"\n", shallowOpts.primaryDagFile.Value());
	    fprintf( stderr, "  Look at the Condor manual for details about DAG "
				 "rescue files.\n" );
	    fprintf( stderr, "  Please investigate and either remove \"%s\",\n",
				 shallowOpts.strRescueFile.Value() );
	    fprintf( stderr, "  or use it as the input to condor_submit_dag.\n" );
		bHadError = true;
	}

	if (bHadError) 
	{
	    fprintf( stderr, "\nSome file(s) needed by %s already exist.  ",
				 dagman_exe );
	    fprintf( stderr, "Either rename them,\nuse the \"-f\" option to "
				 "force them to be overwritten, or use\n"
				 "the \"-update_submit\" option to update the submit "
				 "file and continue.\n" );
	    exit( 1 );
	}
}
Ejemplo n.º 8
0
CDirectiveFile::CDirectiveFile(Type type, ArgumentList& args)
	: type(type)
{
	file = NULL;
	
	std::wstring originalName;
	std::wstring fileName;
	int virtualAddress;

	switch (type)
	{
	case Type::Open:
		fileName = getFullPathName(args[0].text);

		if (fileExists(fileName) == false)
		{
			Logger::printError(Logger::FatalError,L"File %s not found",fileName);
			return;
		}
		if (ConvertExpression(args[1].text,virtualAddress) == false)
		{
			Logger::printError(Logger::FatalError,L"Invalid ram address %s",args[1].text);
			return;
		}

		file = new GenericAssemblerFile(fileName,virtualAddress,false);
		break;
	case Type::Create:
		fileName = getFullPathName(args[0].text);

		if (ConvertExpression(args[1].text,virtualAddress) == false)
		{
			Logger::printError(Logger::FatalError,L"Invalid ram address %s",args[1].text);
			return;
		}

		file = new GenericAssemblerFile(fileName,virtualAddress,true);
		break;
	case Type::Copy:
		originalName = getFullPathName(args[0].text);
		fileName = getFullPathName(args[1].text);

		if (fileExists(originalName) == false)
		{
			Logger::printError(Logger::FatalError,L"File %s not found",originalName);
			return;
		}
		if (ConvertExpression(args[2].text,virtualAddress) == false)
		{
			Logger::printError(Logger::FatalError,L"Invalid ram address %s",args[2].text);
			return;
		}

		file = new GenericAssemblerFile(fileName,originalName,virtualAddress);
		break;
	case Type::Close:
		return;
	}

	g_fileManager->addFile(file);
	Global.Section++;
}
Ejemplo n.º 9
0
int handle_uavsar_file(const char *filename, char *meta_name, char *data_name,
                       char **err)
{
    // for uavsar data, require that they specify the full name of the data
    // file they want to look at, and we'll find the .ann file.
    char *ext = findExt(filename);
    int has_ext = ext && strlen(ext) > 0;
    int has_uavsar_ext = has_ext &&
        (strcmp_case(ext,".grd")==0 ||
         strcmp_case(ext,".mlc")==0 ||
         strcmp_case(ext,".hgt")==0);

    if (has_uavsar_ext)
    {
        int ret;

        char *m = find_uavsar_annotation_file(filename);
        if (!m) {
            int l = sizeof(char)*strlen(filename)*2+255;
            *err = MALLOC(l);
            snprintf(*err, l, "Could not find annotation file for UAVSAR "
                "data file '%s'.\n", filename);
            ret = FALSE;
        }
        else {
            strcpy(meta_name, m);
            strcpy(data_name, filename);
            const char *d = filename;

            if (!fileExists(meta_name) || !fileExists(data_name)) {
                int l = sizeof(char)*strlen(filename)*2+255;
                *err = MALLOC(l);
                snprintf(*err, l,
                    "Error opening UAVSAR data file.\n"
                    "  Annotation file: %s - %s\n"
                    "        Data file: %s - %s\n",
                    m, fileExists(m) ? "Found" : "NOT FOUND",
                    d, fileExists(d) ? "Found" : "NOT FOUND");

                ret = FALSE;
            }
            else
                ret = TRUE;
        
            free(m);
        }

        return ret;
    }
    else {
        // in theory this shouldn't happen, if try_ext is working
        int l = sizeof(char)*strlen(filename)*2+255;
        *err = MALLOC(l);
        snprintf(*err, l,
            "Failed to open %s as an UAVSAR Format File.\n", filename);
        return FALSE;
    }

    // not reached
    assert(FALSE);
    return FALSE;
}
Ejemplo n.º 10
0
void checkProgram(ParticipantTask &task, string participantName)
{
	addLog("Cheking task number "+to_str(task.taskNumber+1)+". Participant "
			+participantName);
	if (skipCheckedPrograms)
	{
		unsigned int newTime=getFileTime(task.path.c_str());
		if (saving.find(task.path)!=saving.end())

		{
			SaveInformation sinfo=saving[task.path];

			if (newTime==sinfo.checkFileTime)
			{
				addLog("Task "+task.path+" was skipped");
				task.result = sinfo.result;
				task.score = sinfo.score;
				task.checkFileTime=newTime;
				return;
			}
		}
		task.checkFileTime=newTime;
	}
	CompilerInfo compiler=compilers[task.compilerNumber];
	Task tsk=tasks[task.taskNumber];
	clearDir(runDir, "");
	CopyFile(task.path.c_str(),(runDir+compiler.inFile).c_str(),0);
	SetCurrentDirectory(runDir.c_str());
	runProgram(compiler.exeFile + " " + compiler.params, 1);
	string exename=runDir+compiler.outFile;
	if (!fileExists(exename))
	{
		task.result="Compile failed";
		addLog("Compile Failed...");
		task.score=0;
		return;
	}
	clearDir(runDir, compiler.outFile);
	task.score=0;
	for (unsigned int i=0; i<tsk.tests.size(); i++)
	{
		CopyFile(tsk.tests[i].testFile.c_str(),(runDir+tsk.inFile).c_str(),0);
		addLog(participantName+": task "+to_str(task.taskNumber+1)+" test "
				+to_str(i+1)+" ", 0);
		char res=runProgramTimer(exename, tsk.tests[i].maxTime, 1);
		if (res!='+')
		{
			task.result+=res;
			continue;
		}
		if (!fileExists(runDir+tsk.outFile))
		{
			task.result+="F";
			addLog("No output File...");
			continue;
		}
		CopyFile(tsk.tests[i].judgeFile.c_str(),(runDir+"judge.sol1").c_str(),0);
		if (!tsk.checkProgram.empty())
		{
			CopyFile(tsk.checkProgram.c_str(),(runDir+"check.exe").c_str(),0);
			res=validatingTask(tsk.inFile, tsk.outFile, "judge.sol1",
					"check.exe");
		}
		else
			res=validatingTask(tsk.inFile, tsk.outFile, "judge.sol1");
		task.result+=res;
		if (res=='+')
			task.score+=tsk.tests[i].maxScore, addLog("Right answer!!! ");
		else if (res=='P')
			task.score+=tsk.tests[i].maxScore*tsk.wrongFormat,
					addLog("Presentation error.");
		else
			addLog("Wrong answer...");
		clearDir(runDir, compiler.outFile);
	}
	addLog("Task "+task.path+" Result: "+task.result+" score "
			+to_str(task.score));
	addLog("***********************************************************************");
}
Ejemplo n.º 11
0
int main(int argc, char** argv) {

    // Argument parsing

    if ((argc == 1) ||
        ((argc >= 2) && (std::string("--help") == argv[1]))) {
        printHelp();
        return 0;
    }

    if ((argc == 2) && (std::string("--version") == argv[1])) {
        printVersion();
        return 0;
    }

    std::string src = "";
    std::string dst = "";

    // Figure out source and dest filenames
    if (argc >= 4) {
        if (std::string("-o") != argv[1]) {
            printf("Invalid command line to GLSLCheck.  Expected '-o' or"
                " filename as 1st argument, found: '%s'\n", argv[1]);
            return -1;
        }
        dst = argv[2];
        src = argv[3];
    } else {
        src = argv[1];
    }

    if (! fileExists(src)) {
        printf("GLSLCheck error : input file '%s' not found\n", src.c_str());
        return -4;
    }

    if (endsWith(dst, "/") || endsWith(dst, "\\")) {
        if (! fileExists(dst.substr(0, dst.size() - 1))) {
            printf("GLSLCheck error : output directory '%s' not found\n", dst.c_str());
            return -5;
        }

        // Add the filename part of src to dst, since dst is a directory
        dst = dst + filenameBaseExt(src);
    }


    Mode mode;
    if (endsWith(toLower(src), ".vert")) {
        mode = VERTEX;
    } else if (endsWith(toLower(src), ".frag")) {
        mode = FRAGMENT;
    } else {
        printf("Invalid filename; source file must end with .vert or .frag\n");
        return -2;
    }

    // We must create a GL context before loading extensions.
    GWindowSettings settings;
    settings.visible = false;
    settings.width = 200;
    settings.height = 200;

    GWindow* window;
    #ifdef G3D_WIN32
        window = new Win32Window(settings);
    #else
        window = new SDLWindow(settings);
    #endif
    GLCaps::loadExtensions();

    if (! VertexAndPixelShader::fullySupported()) {
        printf("GLSL not supported by your graphics card and driver.\n");
        return -3;
    }

    int result = check(mode, src);

    if ((result == 0) && (dst != "")) {
        copyFile(src, dst);
    }

    delete window;
    return result;
}
Ejemplo n.º 12
0
int CVSCPTable::init() 
{
	// Protect
    int rv = VSCP_ERROR_SUCCESS;
	struct _vscpFileRecord record;

	// Open/create main file
	if ( fileExists( m_path.mbc_str() ) ) {
		m_ft = fopen( m_path.mbc_str(), "r+b") ;	  // binary Read Write
		if ( NULL == m_ft ) return VSCP_ERROR_ERROR;  // Failed to open file
	}
	else {
		// Create file
		m_ft = fopen( m_path.mbc_str(), "w+b") ;	  // binary Read Write		
		if ( NULL == m_ft ) return VSCP_ERROR_ERROR;  // Failed to create file
		
		if ( VSCP_TABLE_DYNAMIC == m_vscpFileHead.type ) {
			m_vscpFileHead.id[0] = 0x55;
			m_vscpFileHead.id[0] = 0xAA;
		}
		else {
			m_vscpFileHead.id[0] = 0xAA;
			m_vscpFileHead.id[0] = 0x55;
		}
		
		// Write header
		if ( sizeof( m_vscpFileHead ) != fwrite( &m_vscpFileHead, 
											1, 
											sizeof(m_vscpFileHead), m_ft ) ) {
            return VSCP_ERROR_ERROR;
        }

		// If we have a static table we initiate it
		if ( VSCP_TABLE_STATIC == m_vscpFileHead.type ) {
			_vscpFileRecord rec;
			memset( &rec, 0, sizeof(_vscpFileRecord) ); 
            for ( unsigned int i=0; i<m_vscpFileHead.staticSize; i++ ) {
			    if ( sizeof(_vscpFileRecord) != fwrite( &rec, 
													1, 
													sizeof(_vscpFileRecord), m_ft ) ) {
                    return VSCP_ERROR_ERROR;
                }
            }
		}
	}

    //Read header information
	rv = readMainHeader();

    if ( VSCP_TABLE_DYNAMIC == m_vscpFileHead.type ) {

        // Calculate number of records in file
	    m_number_of_records = ( fdGetFileSize( m_path.mbc_str() ) - sizeof( m_vscpFileHead ))/sizeof(_vscpFileRecord);
	    if ( m_number_of_records ) {

		    // Go to last pos - Read last timestamp
		    fseek( m_ft, sizeof( m_vscpFileHead ) + (m_number_of_records-1) * sizeof(_vscpFileRecord) , SEEK_SET );							
		    (void)fread( &record, 1, sizeof(record), m_ft );
		    m_timestamp_last = record.timestamp;

		    // Go to first pos - read first timestamp
		    fseek( m_ft, sizeof( m_vscpFileHead ), SEEK_SET );							
		    (void)fread( &record, 1, sizeof(record), m_ft );
		    m_timestamp_first = record.timestamp;

	    }

    }
    else {  // STATIC TABLE
        m_number_of_records = m_vscpFileHead.staticSize;
    }

	return rv; 
}
Ejemplo n.º 13
0
bool Server::init(cgicc::Cgicc cgicc) {
    std::cout << "Access-Control-Allow-Origin: \"*\"\r\n";

    serverReceiveImageTime = timestamp_usec();

    //gets the fields of the request
    cgicc::form_iterator fiImage = cgicc.getElement("image");
    cgicc::form_iterator fiScreenWidthPixel = cgicc.getElement("screenWidthPixel");
    cgicc::form_iterator fiScreenHeightPixel = cgicc.getElement("screenHeightPixel");
    cgicc::form_iterator fiNumSnapshot = cgicc.getElement("numSnapshot");
    cgicc::form_iterator fiSnapshotType = cgicc.getElement("snapshotType");
    cgicc::form_iterator fiIsBoundingBox = cgicc.getElement("isBoundingBox");
    //    cgicc::form_iterator fiSeed = cgicc.getElement("seed");
    //    cgicc::form_iterator fiToken = cgicc.getElement("token");
    //    cgicc::form_iterator fiSessionName = cgicc.getElement("sessionName");
    cgicc::form_iterator fiOldIp = cgicc.getElement("ip");
    if (((fiImage != (*cgicc).end()) && (!fiImage->isEmpty()))
            && ((fiScreenWidthPixel != (*cgicc).end()) && (!fiScreenWidthPixel->isEmpty()))
            && ((fiScreenHeightPixel != (*cgicc).end()) && (!fiScreenHeightPixel->isEmpty()))
            && ((fiNumSnapshot != (*cgicc).end()) && (!fiNumSnapshot->isEmpty()))
            && ((fiSnapshotType != (*cgicc).end()) && (!fiSnapshotType->isEmpty()))
            && ((fiIsBoundingBox != (*cgicc).end()) && (!fiIsBoundingBox->isEmpty()))
            //            && ((fiSeed != (*cgicc).end()) && (!fiSeed->isEmpty()))
            //            && ((fiToken != (*cgicc).end()) && (!fiToken->isEmpty()))
            //            && ((fiSessionName != (*cgicc).end()))
            && ((fiOldIp != (*cgicc).end()))
            ) {

        //TODO: if the diff flag is true, use the difference construction of the image
        //      using the rules in the .js file

        std::string stringUrlImage = (**fiImage);
        const char * urlImage = stringUrlImage.c_str();

        if (strlen(urlImage) > 4) {
            char * imageDecoded;

            //if the url has not the "data:" in the firsts characters, probably is because isn't decoded
            if (urlImage[4] != ':') {
                imageDecoded = CGI_decode_url(urlImage);
            }
            else {
                imageDecoded = new char[stringUrlImage.size() + 1];
                copy(stringUrlImage.begin(), stringUrlImage.end(), imageDecoded);
                imageDecoded[stringUrlImage.size()] = '\0';
            }

            //find the comma that splits the header of the url image, to the data of the image
            int iPreviousComma = -1;
            int strlenImageDecoded = strlen(imageDecoded);
            for (int i = 0; i < strlenImageDecoded; i++) {
                if (imageDecoded[i] == ',') {
                    iPreviousComma = i + 1;
                    break;
                }
            }

            if (iPreviousComma > -1) {
                //takes the data of the image
                char imageDecodeWithoutContent[strlenImageDecoded - iPreviousComma];
                for (int i = iPreviousComma, j = 0; i < strlenImageDecoded; i++, j++) {
                    imageDecodeWithoutContent[j] = imageDecoded[i];
                }

                //convert the url image in a byte array
                std::vector<BYTE> imageByteArray = base64_decode(imageDecodeWithoutContent);

                //convert the byte array in a Mat
                cv::Mat image = cv::imdecode(imageByteArray, CV_LOAD_IMAGE_COLOR);


                /*SAVE THE IMAGE*/
                long long now = timestamp_usec();
                std::stringstream fileName;
                fileName << "stream/" << now << ".jpeg";
                int i = 0;
                while (fileExists(fileName.str().c_str())) {
                    fileName << "stream/" << now << i << ".jpeg";
                    i++;
                }
                cv::imwrite(fileName.str(), image);

                numSnapshot = atoi((**fiNumSnapshot).c_str());
                snapshotType = (**fiSnapshotType).c_str();
                screenWidthPixel = atoi((**fiScreenWidthPixel).c_str());
                screenHeightPixel = atoi((**fiScreenHeightPixel).c_str());
                isBoundingBox = atoi((**fiIsBoundingBox).c_str());
                //                seed = atoi((**fiSeed).c_str());
                //                token = atoi((**fiSeed).c_str());
                //                sessionName = (**fiSessionName).c_str();
                std::string oldIp = (**fiOldIp).c_str();

                ip = cgicc.getEnvironment().getRemoteAddr();


                //activate those lines to see the print of the code and see the debug in the webservice mode
                //                                saveCookies();
                std::cout << "Content-type:text/html\r\n\r\n";

                createSessionName();

                if (oldIp.compare("") != 0) {
                    if (ip.compare(oldIp) != 0) {
                        if (copyInfo(oldIp, ip) == -1) {
                            //error on copy
                            eraseSessionInfo();
                        }
                        std::stringstream filePath;
                        filePath << "session/" << oldIp << "/";
                        removeDirectoryElements(filePath.str().c_str(), "");
                    }
                }

                readInfo();

                setPreviousFrame(getPersistentImage("frame"));
                setFrame(image);
                setPersistentImage("frame", image);
                setPersistentImage("previousFrame", previousFrame);

                /*GET COOKIES*/

                // get environment variables
                //initCookies(cgicc.getEnvironment().getCookieList());
                //                const cgicc::CgiEnvironment& env = cgicc.getEnvironment();
                //                cgicc::const_cookie_iterator cci;
                //                for(cci = env.getCookieList().begin(); cci != env.getCookieList().end(); cci++) {
                //                    Server::getServer()->setCookie(cci->getName(), cci->getValue());
                //                    //std::cout << "<tr><td>" << cci->getName() << "</td><td>";
                //                    //std::cout << cci->getValue();
                //                    //std::cout << "</td></tr>\n";
                //                }
                //std::cout << "</table><\n";

                //std::cout << "<br/>\n";
                //std::cout << "</body>\n";
                //std::cout << "</html>\n";

                return true;
            }
        }
    }

    return false;
}
Ejemplo n.º 14
0
bool ForceGroupBar::setPilotVideo( const char* pVideo, MechWarrior* pPilot )
{
	if ( !pVideo  )
	{
		if ( ForceGroupIcon::bMovie )
		{
			delete ForceGroupIcon::bMovie;
			ForceGroupIcon::bMovie = NULL;
			
		}
		else if ( ForceGroupIcon::pilotVideoTexture )
			gos_DestroyTexture( ForceGroupIcon::pilotVideoTexture );
		
		ForceGroupIcon::pilotVideoTexture = 0;
		ForceGroupIcon::pilotVideoPilot = 0;
	}

	else if  (ForceGroupIcon::bMovie || ControlGui::instance->isMoviePlaying()
		|| ForceGroupIcon::pilotVideoTexture || !prefs.pilotVideos)
	{
		// one already playing...
		// OR we don't want them playing.
		return 0;
	}

	else
	{
		for ( int i = 0; i < iconCount; i++ )
		{
			if ( icons[i] && icons[i]->unit->getPilot() == pPilot )
			{
				ForceGroupIcon::pilotVideoPilot = pPilot;
				FullPathFileName aviPath;
				aviPath.init( moviePath, pVideo, ".bik" );

				if ( (frameRate > 15.0) && fileExists(aviPath) && prefs.pilotVideos) // This is about correct.  Slower then this and movie has hard time keeping up!
				{
					//Update the RECT every frame.  What if we shift Icons around cause someone died!!
					RECT vRect;
					vRect.left 		= icons[i]->bmpLocation[icons[i]->locationIndex][1].x;
					vRect.right 	= icons[i]->pilotLocation[icons[i]->locationIndex][2];
					vRect.top 		= icons[i]->bmpLocation[icons[i]->locationIndex][3].y;
					vRect.bottom 	= icons[i]->bmpLocation[icons[i]->locationIndex][1].y;

					ForceGroupIcon::bMovie = new MC2Movie;
					ForceGroupIcon::bMovie->init(aviPath,vRect,true);
				}
				else // make a still texture
				{
					char realPilotName[9];

					//Set everything to zero so the strncpy below doesn't go off into LALA land!!
					memset(realPilotName,0,9);
					strncpy(realPilotName,pPilot->getName(),8);

					FullPathFileName path;
					path.init( moviePath, realPilotName, ".tga" );

					if (fileExists(path))
						ForceGroupIcon::pilotVideoTexture = gos_NewTextureFromFile( gos_Texture_Solid, path, 0 );
					else
					{
						char realMovieName[256];
						char realMoviePath[1024];
						_splitpath(path,NULL,realMoviePath,realMovieName,NULL);

						//Not in main installed directory and not in fastfile.  Look on CD.
						char actualPath[2048];
						strcpy(actualPath,CDInstallPath);
						strcat(actualPath,realMoviePath);
						strcat(actualPath,realMovieName);
						strcat(actualPath,".tga");

						bool fileThere = fileExists(actualPath);
						if (fileThere)
							ForceGroupIcon::pilotVideoTexture = gos_NewTextureFromFile( gos_Texture_Solid, actualPath, 0 );

						bool openFailed = false;
						while (!fileThere)
						{
							openFailed = true;
							EnterWindowMode();

							char data[2048];
							char msg[1024];
							char msg1[512];
							char title[256];
							cLoadString(IDS_MC2_movieMISSING,msg1,511);
							cLoadString(IDS_MC2_CDMISSING,msg,1023);
							cLoadString(IDS_MC2_MISSING_TITLE,title,255);
							sprintf(data,msg1,path,msg);
							DWORD result = MessageBox(NULL,data,title,MB_OKCANCEL | MB_ICONWARNING);
							if (result == IDCANCEL)
							{
								ExitGameOS();
								return 1; 
							}

							fileThere = fileExists(actualPath);
							if (fileThere)
								ForceGroupIcon::pilotVideoTexture = gos_NewTextureFromFile( gos_Texture_Solid, actualPath, 0 );
						}

						if (openFailed && (Environment.fullScreen == 0) && prefs.fullScreen)
							EnterFullScreenMode();
					}
				}

				break;
			}
		}
	}

	return 1;
}
Ejemplo n.º 15
0
int main(int argc, char * const argv[]) {
  GArgs args(argc, argv, "hFCq:r:o:");
  int e;
  if ((e=args.isError())>0)
    GError("%s\nInvalid argument: %s\n", USAGE, argv[e]);
    if (args.getOpt('h')!=NULL){
      GMessage("%s\n", USAGE);
                exit(1);
      }
  args.startNonOpt();
  GStr fadb(args.nextNonOpt());
  if (fadb.is_empty()) GError("%s Error: multi-fasta file expected!\n",USAGE);
  GStr fname(fadb);
  fname.append(".fai");
  bool createLocal=(args.getOpt('F')!=NULL);
  const char* idxname=(createLocal)? NULL : fname.chars();
  GFastaIndex faidx(fadb.chars(), idxname);
  //also tried to load the index if exists in the current directory
  GStr fnamecwd(fname); //name in current directory (without path)
  int ip=-1;
  if ((ip=fnamecwd.rindex(CHPATHSEP))>=0) {
    fnamecwd.cut(0,ip+1);
    }
  if (!createLocal) { //look for existing indexes to load
    //try the same directory as the fasta file first
    if (!faidx.hasIndex() and fileExists(fnamecwd.chars())>1) { //try current working directory next
        faidx.loadIndex(fnamecwd.chars());
       }
    if (!faidx.hasIndex()) {//could not load any index data
       //try to create it in the same directory as the fasta file
       GMessage("No fasta index found. Rebuilding..\n");
       faidx.buildIndex();
       if (faidx.getCount()==0) GError("Error: no fasta records to be indexed!\n");
       GMessage("Fasta index rebuilt.\n");
       //check if we can create a file there
       FILE* fcreate=fopen(fname.chars(), "w");
       if (fcreate==NULL)
         GMessage("Warning: cannot create fasta index %s! (permissions?)\n", fname.chars());
       else {
         fclose(fcreate);
         if (faidx.storeIndex(fname.chars())<faidx.getCount())
           GMessage("Warning: error writing the index file %s!\n",fname.chars());
         } //creating index file in the same directory as fasta file
       }//trying to create the index file
    }

  if (createLocal || !faidx.hasIndex()) {
    //simply rebuild the index in the current directory and use it:
    //remove directories in path, if any
    if (faidx.getCount()==0) {
          faidx.buildIndex();
          if (faidx.getCount()==0) GError("Error: no fasta records to be indexed!\n");
          }
    if (faidx.storeIndex(fnamecwd.chars())<faidx.getCount())
        GMessage("Warning: error writing the index file %s!\n",fnamecwd.chars());
    }

  GStr qry(args.getOpt('q'));
  if (qry.is_empty()) exit(0);
  GFastaRec* farec=faidx.getRecord(qry.chars());
  if (farec==NULL) {
      GMessage("Error: couldn't find fasta record for '%s'!\n",qry.chars());
      exit(1);
      }
  GFaSeqGet faseq(fadb.chars(),farec->seqlen, farec->fpos, farec->line_len, farec->line_blen);
  //TODO: read these from -r option
  uint qstart=0;
  uint qend=0; //farec->seqlen
  bool revCompl=(args.getOpt('C')!=NULL);
  char* s=args.getOpt('r');
  if (s!=NULL) {
     char *p=s;
     while (isdigit(*p)) p++;
     if (*p=='-') {
                sscanf(s,"%u-%u",&qstart, &qend);
                if (qstart==0 || qend==0)
                      GError("Error parsing sequence range: %s\n",s);
                }
       else if (*p==':') {
                int qlen=0;
                sscanf(s,"%u:%d", &qstart, &qlen);
                if (qstart==0 || qlen==0)
                     GError("Error parsing sequence range: %s\n",s);
                qend=qstart+qlen-1;
                }
       else if (*p=='.') {
               sscanf(s,"%u..%u",&qstart, &qend);
               if (qstart==0 || qend==0)
               GError("Error parsing sequence range: %s\n",s);
               }
     }
  if (qstart==0) qstart=1;
  if (qend==0) qend=farec->seqlen;
  // call faseq.loadall() here if multiple ranges are to be extracted all
  // over this genomic sequence
  char* subseq=faseq.copyRange(qstart, qend, revCompl, true);
  FILE* f_out=NULL;
  openfwrite(f_out, args, 'o');
  if (f_out==NULL) f_out=stdout;
  writeFasta(f_out, qry.chars(), NULL, subseq, 70, qend-qstart+1);
  GFREE(subseq);
}
Ejemplo n.º 16
0
void hrChooseSinglePlayerBitmap(char* pFilenameBuffer)
{
    char fname[128];
    sdword x, y, width, height;

    memset(&hrSinglePlayerPos, 0, sizeof(hrSinglePlayerPos));

    //image itself
#if defined(HW_GAME_RAIDER_RETREAT)
    if (spGetCurrentMission() == MISSION_5B_TURANIC_RAIDER_PLANETOID)
    {
#ifdef _WIN32
        sprintf(fname, "SinglePlayer\\mission05_OEM\\loading.jpg");
#else
        sprintf(fname, "SinglePlayer/mission05_OEM/loading.jpg");
#endif
    }
    else
#endif
    {
#ifdef _WIN32
        sprintf(fname, "SinglePlayer\\mission%02d\\loading.jpg", spGetCurrentMission());
#else
        sprintf(fname, "SinglePlayer/mission%02d/loading.jpg", spGetCurrentMission());
#endif
    }

    if (!fileExists(fname, 0))
    {
        pFilenameBuffer[0] = '\0';
        return;
    }

    strcpy(pFilenameBuffer, fname);

    // loading bar position
    // NB: the single player loading images are not all aligned properly...
    #define SP_LOADING_IMAGE_PROGRESS_BAR_X        43
    #define SP_LOADING_IMAGE_PROGRESS_BAR_Y       133
    #define SP_LOADING_IMAGE_PROGRESS_BAR_WIDTH   151
    #define SP_LOADING_IMAGE_PROGRESS_BAR_HEIGHT    2

    x      = hrScaleMissionLoadingScreens
           ? feResRepositionScaledX (SP_LOADING_IMAGE_PROGRESS_BAR_X)
           : feResRepositionCentredX(SP_LOADING_IMAGE_PROGRESS_BAR_X);
      
    y      = hrScaleMissionLoadingScreens
           ? feResRepositionScaledY (SP_LOADING_IMAGE_PROGRESS_BAR_Y)
           : feResRepositionCentredY(SP_LOADING_IMAGE_PROGRESS_BAR_Y);
    
    width  = hrScaleMissionLoadingScreens
           ? (SP_LOADING_IMAGE_PROGRESS_BAR_WIDTH  * FE_SCALE_TO_FIT_FACTOR_RELIC_SCREEN)
           :  SP_LOADING_IMAGE_PROGRESS_BAR_WIDTH;
    
    height = hrScaleMissionLoadingScreens
           ? (SP_LOADING_IMAGE_PROGRESS_BAR_HEIGHT * FE_SCALE_TO_FIT_FACTOR_RELIC_SCREEN)
           :  SP_LOADING_IMAGE_PROGRESS_BAR_HEIGHT;
    
    hrSinglePlayerPos.x0 = x;
    hrSinglePlayerPos.y0 = y;
    hrSinglePlayerPos.x1 = x + width;
    hrSinglePlayerPos.y1 = y + height;
}
Ejemplo n.º 17
0
lasErr c_putddr(const char *hname,struct DDR *ddr)
{
    int   access;                   /* file access type                      */
    int   action;                   /* file close action                     */
    int   clen;                     /* length of char part of record         */
    int   dlen;                     /* length of data part of record         */
    FILE *fd;                       /* file descriptor                       */
    char  d_temp[DDSTCT][DDSYLN];   /* temporary for squeezed strings        */
    char *junk_temp,hostddr[1024];
    unsigned char *dbuf;            /* pointer to area where data is stuffed */
    int ii;                         /* Index for corresponding metadata      */

    /* Ensure that required parameters were specified.
    --------------------------------------------------*/
    if ((ddr->nl < 1) || (ddr->nl > MAXNL)) {
      c_errmsg("Invalid number of lines specified","putddr-badnl",NON_FATAL);
      return(E_FAIL);
    }
    if ((ddr->ns < 1) || (ddr->ns > MAXNS)) {
      c_errmsg("Invalid number of samples specified","putddr-badns",NON_FATAL);
      return(E_FAIL);
    }
    if ((ddr->nbands < 1) || (ddr->nbands > MAXBND)) {
      c_errmsg("Invalid number of bands specified","putddr-badbnds",NON_FATAL);
      return(E_FAIL);
    }
    if ((ddr->dtype < 1) || (ddr->dtype > 20)) {
      c_errmsg("Invalid data type specified","putddr-bdtype",NON_FATAL);
      return(E_FAIL);
    }

    strcpy(ddr->system,"ieee-std");

    c_lsmknm(hname,".ddr",hostddr);

    access = 1;                          /* open DDR file for write access   */
    c_lsopen(&fd,hostddr,&access);

    /*  Place the string portion of the DDR into a temporary buffer
    ---------------------------------------------------------------*/
    junk_temp = (char *)&ddr->spare;
    strncpy(junk_temp,ddr->system,4);
    strcpy(d_temp[0],squeeze(ddr->system,DDSYLN));
    strcpy(d_temp[1],squeeze(ddr->proj_units,DDPULN));
    strcpy(d_temp[2],squeeze(ddr->last_used_date,DDLDLN));
    strcpy(d_temp[3],squeeze(ddr->last_used_time,DDLTLN));

    clen = DDSTCT * DDSYLN - 1;                /* set up and output record 1 */
    dlen = DISIZE * 4;
    dbuf = (unsigned char *) MALLOC(dlen);
    int2byteArr((int *)ddr,dbuf,DISIZE);
    c_lswrit(&fd,"DDRINT",&clen,&dlen,d_temp[0],dbuf,"I4");
    free(dbuf);

    /* Set up and output record 2
       There is no character part to this record 
    --------------------------------------------*/
    clen = 0;				  
    dlen = DDSIZE * 8;

    // convert all floating point values to proper endian-ness
    for (ii=0; ii<15; ++ii)
      big64(ddr->proj_coef[ii]);
    for (ii=0; ii<2; ++ii) {
      big64(ddr->upleft[ii]);
      big64(ddr->loleft[ii]);
      big64(ddr->upright[ii]);
      big64(ddr->loright[ii]);
    }
    big64(ddr->pdist_y);
    big64(ddr->pdist_x);
    big64(ddr->line_inc);
    big64(ddr->sample_inc);

    dbuf = (unsigned char *) &(ddr->proj_coef[0]);
    c_lswrit(&fd,"DDRDUB",&clen,&dlen,d_temp[0],dbuf,"R8");

    action = 0;                                 /* close associated DDR file */
    c_lsclos(&fd,hostddr,&action);

    {/*Create/write correct number of BDRs*/
	    int bandNo;
	    for (bandNo=1;bandNo<=ddr->nbands;bandNo++)
	    {
		    struct BDDR bdr;
		    int_c_intbdr(&bdr);
		    bdr.bandno=bandNo;
		    int_c_putbdr(hname,&bdr);
	    }
    }

    /* Find corresponding meta structure to fill necessary values to
    ----------------------------------------------------------------*/
    ii = get_meta_ddr_struct_index(hname);
    if ((ii>-1) && (ii<NUM_META_DDR_STRUCTS)) {
        if (meta_ddr_structs[ii].ddr != ddr) {
/*            printf("\n"
                   "Warning: Bad programming in the asf_meta library.\n"
                   "         Something that should not have happened in c_putddr() did.\n"
                   "         Please contact Patrick Denny ([email protected]).\n");*/
        }
        if (meta_ddr_structs[ii].ddr == ddr) {
            meta_parameters *mds_meta;
            struct DDR *mds_ddr  = meta_ddr_structs[ii].ddr;
            int open_flag = 0;
            char meta_name[512];

            create_name(meta_name, meta_ddr_structs[ii].base_name, ".meta");

            /* Get the meta structure if its never been gotten (meta=NULL)
             * or its been free'd (meta->general==NULL) */
            if (meta_ddr_structs[ii].meta==NULL
	       || meta_ddr_structs[ii].meta->general==NULL) {
	        if (fileExists(meta_name)) {
                    mds_meta = meta_read(meta_name);
                    open_flag = 1;
		}
		else /* No meta struct/file */ {
		    return(E_SUCC);
		}
            }
            else
                {mds_meta = meta_ddr_structs[ii].meta;}

            /* Fill the meta structure with updated values */
            mds_meta->general->line_count     = mds_ddr->nl;
            mds_meta->general->sample_count   = mds_ddr->ns;
            mds_meta->general->start_line     = mds_ddr->master_line - 1;
            mds_meta->general->start_sample   = mds_ddr->master_sample - 1;
            mds_meta->sar->line_increment     = mds_ddr->line_inc;
            mds_meta->sar->sample_increment   = mds_ddr->sample_inc;
            if (mds_meta->sar->image_type=='P')
                    {strcpy(mds_meta->projection->units, mds_ddr->proj_units);}
            switch ( mds_ddr->dtype ) {
              case 0: /* DTYPE_BYTE */
              case DTYPE_BYTE:  mds_meta->general->data_type = ASF_BYTE;  break;
              case DTYPE_SHORT: mds_meta->general->data_type = INTEGER16; break;
              case DTYPE_LONG:  mds_meta->general->data_type = INTEGER32; break;
              case DTYPE_FLOAT: mds_meta->general->data_type = REAL32;    break;
              case DTYPE_DOUBLE:mds_meta->general->data_type = REAL64;    break;
              case DTYPE_COMPLEX:
                           mds_meta->general->data_type = COMPLEX_REAL32; break;
              default:
	            printf("WARNING: c_putddr: Unrecognized meta/DDR data type (%d).\n",
		           mds_ddr->dtype);
                    break;
            }
 	    if (open_flag) {
                meta_write(mds_meta, meta_ddr_structs[ii].base_name);
                meta_free(mds_meta);
            }
        }
    }
    return(E_SUCC);
}
Ejemplo n.º 18
0
Archivo: filelib.c Proyecto: cs50/spl
static void *checkExists(string name, void *data) {
   return (fileExists(name)) ? name : NULL;
}
Ejemplo n.º 19
0
Archivo: Mergetime.c Proyecto: AZed/cdo
void *Mergetime(void *argument)
{
  int streamID1, streamID2 = CDI_UNDEFID;
  int tsID2 = 0, recID, varID, levelID;
  int vlistID1, vlistID2;
  int nfiles, fileID;
  int taxisID1, taxisID2 = CDI_UNDEFID;
  int lcopy = FALSE;
  int gridsize;
  int nmiss;
  int vdate, vtime;
  int last_vdate = -1, last_vtime = -1;
  int next_fileID;
  int skip_same_time = FALSE;
  int process_timestep;
  const char *ofilename;
  double *array = NULL;
  typedef struct
  {
    int streamID;
    int vlistID;
    int taxisID;
    int tsID;
    int vdate;
    int vtime;
    int nrecs;
  } sfile_t;
  sfile_t *sf = NULL;

  cdoInitialize(argument);

  {
    char *envstr;
    envstr = getenv("SKIP_SAME_TIME");
    if ( envstr )
      {
	int ival;
	ival = atoi(envstr);
	if ( ival == 1 )
	  {
	    skip_same_time = TRUE;
	    if ( cdoVerbose )
	      cdoPrint("Set SKIP_SAME_TIME to %d", ival);
	  }
      }
  }

  if ( UNCHANGED_RECORD ) lcopy = TRUE;

  nfiles = cdoStreamCnt() - 1;

  sf = (sfile_t*) malloc(nfiles*sizeof(sfile_t));

  for ( fileID = 0; fileID < nfiles; fileID++ )
    {
      if ( cdoVerbose ) cdoPrint("process: %s", cdoStreamName(fileID)->args);

      streamID1 = streamOpenRead(cdoStreamName(fileID));

      vlistID1 = streamInqVlist(streamID1);
      taxisID1 = vlistInqTaxis(vlistID1);

      sf[fileID].streamID = streamID1;
      sf[fileID].vlistID  = vlistID1;
      sf[fileID].taxisID  = taxisID1;
    }

  
  /* check that the contents is always the same */
  for ( fileID = 1; fileID < nfiles; fileID++ )
    vlistCompare(sf[0].vlistID, sf[fileID].vlistID, CMP_ALL);

  /* read the first time step */
  for ( fileID = 0; fileID < nfiles; fileID++ )
    {
      sf[fileID].tsID = 0;
      sf[fileID].nrecs = streamInqTimestep(sf[fileID].streamID, sf[fileID].tsID);
      if ( sf[fileID].nrecs == 0 )
	{
	  streamClose(sf[fileID].streamID);
	  sf[fileID].streamID = -1;
	}
      else
	{
	  sf[fileID].vdate = taxisInqVdate(sf[fileID].taxisID);
	  sf[fileID].vtime = taxisInqVtime(sf[fileID].taxisID);
	}
    }

  ofilename = cdoStreamName(nfiles)->args;

  if ( !cdoSilentMode && !cdoOverwriteMode )
    if ( fileExists(ofilename) )
      if ( !userFileOverwrite(ofilename) )
	cdoAbort("Outputfile %s already exists!", ofilename);

  streamID2 = streamOpenWrite(cdoStreamName(nfiles), cdoFiletype());

  if ( ! lcopy )
    {
      gridsize = vlistGridsizeMax(sf[0].vlistID);
      array = (double*) malloc(gridsize*sizeof(double));
    }

  while ( TRUE )
    {
      process_timestep = TRUE;

      next_fileID = -1;
      vdate = 0;
      vtime = 0;
      for ( fileID = 0; fileID < nfiles; fileID++ )
	{
	  if ( sf[fileID].streamID != -1 )
	    if ( next_fileID == -1 || sf[fileID].vdate < vdate ||
		 (sf[fileID].vdate == vdate && sf[fileID].vtime < vtime) )
	      {
		next_fileID = fileID;
		vdate = sf[fileID].vdate;
		vtime = sf[fileID].vtime;
	      }
	}

      fileID = next_fileID;

      if ( cdoVerbose )
	cdoPrint("nextstep = %d  vdate = %d  vtime = %d", next_fileID, vdate, vtime);

      if ( next_fileID == -1 ) break;

      if ( skip_same_time )
	if ( vdate == last_vdate && vtime == last_vtime )
	  {
	    char vdatestr[32], vtimestr[32];
	    date2str(vdate, vdatestr, sizeof(vdatestr));
	    time2str(vtime, vtimestr, sizeof(vtimestr));
	    cdoPrint("Timestep %4d in stream %d (%s %s) already exists, skipped!",
		     sf[fileID].tsID+1, sf[fileID].streamID, vdatestr, vtimestr);
	    process_timestep = FALSE;
	  }

      if ( process_timestep )
	{
	  if ( tsID2 == 0 )
	    {
	      vlistID1 = sf[0].vlistID;
	      vlistID2 = vlistDuplicate(vlistID1);
	      taxisID1 = vlistInqTaxis(vlistID1);
	      taxisID2 = taxisDuplicate(taxisID1);
	      vlistDefTaxis(vlistID2, taxisID2);
	      
	      streamDefVlist(streamID2, vlistID2);
	    }

	  last_vdate = vdate;
	  last_vtime = vtime;

	  taxisCopyTimestep(taxisID2, sf[fileID].taxisID);

	  streamDefTimestep(streamID2, tsID2);
	       
	  for ( recID = 0; recID < sf[fileID].nrecs; recID++ )
	    {
	      streamInqRecord(sf[fileID].streamID, &varID, &levelID);
	      streamDefRecord(streamID2,  varID,  levelID);
	  
	      if ( lcopy )
		{
		  streamCopyRecord(streamID2, sf[fileID].streamID); 
		}
	      else
		{
		  streamReadRecord(sf[fileID].streamID, array, &nmiss);
		  streamWriteRecord(streamID2, array, nmiss);
		}
	    }

	  tsID2++;
	}

      sf[fileID].nrecs = streamInqTimestep(sf[fileID].streamID, ++sf[fileID].tsID);
      if ( sf[fileID].nrecs == 0 )
	{
	  streamClose(sf[fileID].streamID);
	  sf[fileID].streamID = -1;
	}
      else
	{
	  sf[fileID].vdate = taxisInqVdate(sf[fileID].taxisID);
	  sf[fileID].vtime = taxisInqVtime(sf[fileID].taxisID);
	}
    }

  streamClose(streamID2);

  if ( ! lcopy )
    if ( array ) free(array);

  if ( sf ) free(sf);

  cdoFinish();

  return (0);
}
Ejemplo n.º 20
0
Archivo: filelib.c Proyecto: cs50/spl
static void testFileExists(void) {
   test(fileExists("src/filelib.c"), true);
   test(fileExists("xyzzy.c"), false);
}
static void rnaStructurePrint(struct section *section, 
	struct sqlConnection *conn, char *geneId)
/* Print out rnaStructure table. */
{
static boolean firstTime = TRUE;
static char *names[2] = 
	{"5' UTR", "3' UTR"};
static char *tables[2] = {"foldUtr5", "foldUtr3"};
int side;

if (firstTime)
    {
    rnaTrashDirsInit(tables, ArraySize(tables));
    firstTime = FALSE;
    }

webPrintLinkTableStart();
webPrintLabelCell("Region");
webPrintLabelCell("Fold Energy");
webPrintLabelCell("Bases");
webPrintLabelCell("Energy/Base");
webPrintWideCenteredLabelCell("Display As", 3);
for (side = 0; side < ArraySize(names); ++side)
    {
    char *table = tables[side];
    struct sqlResult *sr;
    char query[256], **row;
    safef(query, sizeof(query), "select * from %s where name = '%s'",
    	table, geneId);
    sr = sqlGetResult(conn, query);
    if ((row = sqlNextRow(sr)) != NULL)
	{
	struct rnaFold fold;
	int bases;
	char psName[128];

	/* Load fold and save it as postScript. */
	rnaFoldStaticLoad(row, &fold);
	safef(psName, sizeof(psName), "../trash/%s/%s_%s.ps", table, table, geneId);
	if (!fileExists(psName))
	    {
	    FILE *f;
	    f = popen("../cgi-bin/RNAplot", "w");
	    if (f != NULL)
	        {
		fprintf(f, ">%s\n", psName);	/* This tells where to put file. */
		fprintf(f, "%s\n%s\n", fold.seq, fold.fold);
		pclose(f);
		}
	    }

	/* Print row of table, starting with energy terms . */
	hPrintf("</TR><TR>");
	bases = strlen(fold.seq);
	webPrintLinkCell(names[side]);
	webPrintLinkCellStart();
	hPrintf("%1.2f", fold.energy);
	webPrintLinkCellEnd();
	webPrintLinkCellStart();
	hPrintf("%d", bases);
	webPrintLinkCellEnd();
	webPrintLinkCellStart();
	hPrintf("%1.3f", fold.energy/bases);
	webPrintLinkCellEnd();

	/* Print link to png image. */
	webPrintLinkCellStart();
	hPrintf("<A HREF=\"%s?%s&%s=%s&%s=%s&%s=%s\" class=\"toc\" TARGET=_blank>",
	    geneCgi, cartSidUrlString(cart), 
	    hggMrnaFoldRegion, table,
	    hggMrnaFoldPs, psName,
	    hggDoRnaFoldDisplay, "picture");
	hPrintf(" Picture ");
	hPrintf("</A>");
	webPrintLinkCellEnd();

	/* Print link to PostScript. */
	webPrintLinkCellStart();
	hPrintf("<A HREF=\"%s\" class=\"toc\">", psName);
	hPrintf(" PostScript ");
	hPrintf("</A>");
	webPrintLinkCellEnd();

	/* Print link to text. */
	webPrintLinkCellStart();
	hPrintf("<A HREF=\"%s?%s&%s=%s&%s=%s\" class=\"toc\" TARGET=_blank>",
	    geneCgi, cartSidUrlString(cart), 
	    hggMrnaFoldRegion, table,
	    hggDoRnaFoldDisplay, "text");
	hPrintf(" Text ");
	hPrintf("</A>");
	webPrintLinkCellEnd();
	}
    sqlFreeResult(&sr);
    }
webPrintLinkTableEnd();
hPrintf("<BR>The RNAfold program from the ");
hPrintf("<A HREF=\"http://www.tbi.univie.ac.at/~ivo/RNA/\" TARGET=_blank>");
hPrintf("Vienna RNA Package</A> is used to perform the ");
hPrintf("secondary structure predictions and folding calculations. ");
hPrintf("The estimated folding energy is in kcal/mol.  The more ");
hPrintf("negative the energy, the more secondary structure the RNA ");
hPrintf("is likely to have.");
}
Ejemplo n.º 22
0
    void FileIo::transfer(BasicIo& src)
    {
        const bool wasOpen = (fp_ != 0);
        const std::string lastMode(openMode_);

        FileIo *fileIo = dynamic_cast<FileIo*>(&src);
        if (fileIo) {
            // Optimization if src is another instance of FileIo
            fileIo->close();
            // Check if the file can be written to, if it already exists
            if (open("w+b") != 0) {
                // Remove the (temporary) file
                std::remove(fileIo->path_.c_str());
                throw Error(10, path_, "w+b", strError());
            }
            close();
            bool statOk = true;
            struct stat buf1;
            if (::stat(path_.c_str(), &buf1) == -1) {
                statOk = false;
#ifndef SUPPRESS_WARNINGS
                std::cerr << "Warning: " << Error(2, path_, strError(), "stat") << "\n";
#endif
            }
            // MSVCRT rename that does not overwrite existing files
            if (fileExists(path_) && std::remove(path_.c_str()) != 0) {
                throw Error(2, path_, strError(), "std::remove");
            }
            if (std::rename(fileIo->path_.c_str(), path_.c_str()) == -1) {
                throw Error(17, fileIo->path_, path_, strError());
            }
            std::remove(fileIo->path_.c_str());
            // Check permissions of new file
            struct stat buf2;
            if (statOk && ::stat(path_.c_str(), &buf2) == -1) {
                statOk = false;
#ifndef SUPPRESS_WARNINGS
                std::cerr << "Warning: " << Error(2, path_, strError(), "stat") << "\n";
#endif
            }
            if (statOk && buf1.st_mode != buf2.st_mode) {
                // Set original file permissions
                if (::chmod(path_.c_str(), buf1.st_mode) == -1) {
#ifndef SUPPRESS_WARNINGS
                    std::cerr << "Warning: " << Error(2, path_, strError(), "chmod") << "\n";
#endif
                }
            }
        }
        else {
            // Generic handling, reopen both to reset to start
            if (open("w+b") != 0) {
                throw Error(10, path_, "w+b", strError());
            }
            if (src.open() != 0) {
                throw Error(9, src.path(), strError());
            }
            write(src);
            src.close();
        }

        if (wasOpen) {
            if (open(lastMode) != 0) {
                throw Error(10, path_, lastMode, strError());
            }
        }
        else close();

        if (error() || src.error()) throw Error(18, path_, strError());
    }
Ejemplo n.º 23
0
/**
 * A particular event has been triggered.
 * Process all of this events components.
 *
 * @param The triggered event
 * @return Returns true if the event shall not be run again.
 */
bool EventManager::executeEvent(Event &ev) {
	if(&ev == NULL) return false;

	// skip executing events that are on cooldown
	if (ev.cooldown_ticks > 0) return false;

	// set cooldown
	ev.cooldown_ticks = ev.cooldown;

	Event_Component *ec;

	for (unsigned i = 0; i < ev.components.size(); ++i) {
		ec = &ev.components[i];

		if (ec->type == EC_SET_STATUS) {
			camp->setStatus(ec->s);
		}
		else if (ec->type == EC_UNSET_STATUS) {
			camp->unsetStatus(ec->s);
		}
		else if (ec->type == EC_INTERMAP) {

			if (fileExists(mods->locate(ec->s))) {
				mapr->teleportation = true;
				mapr->teleport_mapname = ec->s;
				mapr->teleport_destination.x = static_cast<float>(ec->x) + 0.5f;
				mapr->teleport_destination.y = static_cast<float>(ec->y) + 0.5f;
			}
			else {
				ev.keep_after_trigger = false;
				mapr->log_msg = msg->get("Unknown destination");
			}
		}
		else if (ec->type == EC_INTRAMAP) {
			mapr->teleportation = true;
			mapr->teleport_mapname = "";
			mapr->teleport_destination.x = static_cast<float>(ec->x) + 0.5f;
			mapr->teleport_destination.y = static_cast<float>(ec->y) + 0.5f;
		}
		else if (ec->type == EC_MAPMOD) {
			if (ec->s == "collision") {
				if (ec->x >= 0 && ec->x < mapr->w && ec->y >= 0 && ec->y < mapr->h) {
					mapr->collider.colmap[ec->x][ec->y] = static_cast<unsigned short>(ec->z);
					mapr->map_change = true;
				}
				else
					logError("EventManager: Mapmod at position (%d, %d) is out of bounds 0-255.", ec->x, ec->y);
			}
			else {
				size_t index = static_cast<size_t>(distance(mapr->layernames.begin(), find(mapr->layernames.begin(), mapr->layernames.end(), ec->s)));
				if (!mapr->isValidTile(ec->z))
					logError("EventManager: Mapmod at position (%d, %d) contains invalid tile id (%d).", ec->x, ec->y, ec->z);
				else if (index >= mapr->layers.size())
					logError("EventManager: Mapmod at position (%d, %d) is on an invalid layer.", ec->x, ec->y);
				else if (ec->x >= 0 && ec->x < mapr->w && ec->y >= 0 && ec->y < mapr->h)
					mapr->layers[index][ec->x][ec->y] = static_cast<unsigned short>(ec->z);
				else
					logError("EventManager: Mapmod at position (%d, %d) is out of bounds 0-255.", ec->x, ec->y);
			}
		}
		else if (ec->type == EC_SOUNDFX) {
			FPoint pos(0,0);
			bool loop = false;

			if (ec->x != -1 && ec->y != -1) {
				if (ec->x != 0 && ec->y != 0) {
					pos.x = static_cast<float>(ec->x) + 0.5f;
					pos.y = static_cast<float>(ec->y) + 0.5f;
				}
			}
			else if (ev.location.x != 0 && ev.location.y != 0) {
				pos.x = static_cast<float>(ev.location.x) + 0.5f;
				pos.y = static_cast<float>(ev.location.y) + 0.5f;
			}

			if (ev.type == "on_load" || static_cast<bool>(ec->z) == true)
				loop = true;

			SoundManager::SoundID sid = snd->load(ec->s, "MapRenderer background soundfx");

			snd->play(sid, GLOBAL_VIRTUAL_CHANNEL, pos, loop);
			mapr->sids.push_back(sid);
		}
		else if (ec->type == EC_LOOT) {
			Event_Component *ec_lootcount = ev.getComponent(EC_LOOT_COUNT);
			if (ec_lootcount) {
				mapr->loot_count.x = ec_lootcount->x;
				mapr->loot_count.y = ec_lootcount->y;
			}
			else {
				mapr->loot_count.x = 0;
				mapr->loot_count.y = 0;
			}

			ec->x = ev.hotspot.x;
			ec->y = ev.hotspot.y;
			mapr->loot.push_back(*ec);
		}
		else if (ec->type == EC_MSG) {
			mapr->log_msg = ec->s;
		}
		else if (ec->type == EC_SHAKYCAM) {
			mapr->shaky_cam_ticks = ec->x;
		}
		else if (ec->type == EC_REMOVE_CURRENCY) {
			camp->removeCurrency(ec->x);
		}
		else if (ec->type == EC_REMOVE_ITEM) {
			camp->removeItem(ec->x);
		}
		else if (ec->type == EC_REWARD_XP) {
			camp->rewardXP(ec->x, true);
		}
		else if (ec->type == EC_REWARD_CURRENCY) {
			camp->rewardCurrency(ec->x);
		}
		else if (ec->type == EC_REWARD_ITEM) {
			ItemStack istack;
			istack.item = ec->x;
			istack.quantity = ec->y;
			camp->rewardItem(istack);
		}
		else if (ec->type == EC_RESTORE) {
			camp->restoreHPMP(ec->s);
		}
		else if (ec->type == EC_SPAWN) {
			Point spawn_pos;
			spawn_pos.x = ec->x;
			spawn_pos.y = ec->y;
			powers->spawn(ec->s, spawn_pos);
		}
		else if (ec->type == EC_POWER) {
			Event_Component *ec_path = ev.getComponent(EC_POWER_PATH);
			FPoint target;

			if (ec_path) {
				// targets hero option
				if (ec_path->s == "hero") {
					target.x = mapr->cam.x;
					target.y = mapr->cam.y;
				}
				// targets fixed path option
				else {
					target.x = static_cast<float>(ec_path->a) + 0.5f;
					target.y = static_cast<float>(ec_path->b) + 0.5f;
				}
			}
			// no path specified, targets self location
			else {
				target.x = static_cast<float>(ev.location.x) + 0.5f;
				target.y = static_cast<float>(ev.location.y) + 0.5f;
			}

			// ec->x is power id
			// ec->y is statblock index
			mapr->activatePower(ec->x, ec->y, target);
		}
		else if (ec->type == EC_STASH) {
			mapr->stash = toBool(ec->s);
			if (mapr->stash) {
				mapr->stash_pos.x = static_cast<float>(ev.location.x) + 0.5f;
				mapr->stash_pos.y = static_cast<float>(ev.location.y) + 0.5f;
			}
		}
		else if (ec->type == EC_NPC) {
			mapr->event_npc = ec->s;
		}
		else if (ec->type == EC_MUSIC) {
			mapr->music_filename = ec->s;
			mapr->loadMusic();
		}
		else if (ec->type == EC_CUTSCENE) {
			mapr->cutscene = true;
			mapr->cutscene_file = ec->s;
		}
		else if (ec->type == EC_REPEAT) {
			ev.keep_after_trigger = toBool(ec->s);
		}
		else if (ec->type == EC_SAVE_GAME) {
			mapr->save_game = toBool(ec->s);
		}
		else if (ec->type == EC_NPC_ID) {
			mapr->npc_id = ec->x;
		}
		else if (ec->type == EC_BOOK) {
			mapr->show_book = ec->s;
		}
	}
	return !ev.keep_after_trigger;
}
Ejemplo n.º 24
0
int isTerrasar_ext(char *dataFile, int checkPolarimetry, char **error)
{
  int found = FALSE;
  char *inFile = STRDUP(dataFile);
  // Let's first check for an .xml extension
  char *ext = findExt(inFile);

  // If it has the correct extension, investigate it further
  // Might sound a little harsh but avoids some XML parser warning otherwise.
  if (ext && strcmp_case(ext, ".xml") == 0) {
    char *satellite = NULL;
    char tmp[256], *message = NULL, *path=NULL, *inDataName=NULL;
    char imageDataType[25];
    int ii, numberOfLayers;
    satellite = (char *) MALLOC(sizeof(char)*25);
    FILE *fp;
    fp = fopen(inFile, "r");
    xmlDoc *doc = xmlReadFile(inFile, NULL, 0);
    if (doc) {
      strcpy(satellite, xml_get_string_value(doc, 
        "level1Product.productInfo.missionInfo.mission"));

      // only care about TerraSAR-X data
      if (satellite && 
	  (strncmp_case(satellite, "TSX", 3) == 0 ||
	   strncmp_case(satellite, "TDX", 3) == 0)) {

	found = TRUE;
	if (checkPolarimetry) {
	  strcpy(imageDataType, xml_get_string_value(doc, 
	     "level1Product.productInfo.imageDataInfo.imageDataType"));
	  if (strcmp_case(imageDataType, "COMPLEX") != 0) {
	    if (!message)
	      message = (char *) MALLOC(sizeof(char)*1024);
	    sprintf(tmp, "Wrong data type!\n"
		    "Polarimetric processing requires SLC data!\n");
	    strcat(message, tmp);
	    found = FALSE;
	  }
	}

	// path from the xml (metadata) file
	path = get_dirname(inFile);
	inDataName = (char *) MALLOC(sizeof(char)*(strlen(path)+100));
	numberOfLayers = xml_get_int_value(doc, 
	  "level1Product.productInfo.imageDataInfo.numberOfLayers");

	for (ii=0; ii<numberOfLayers; ii++) {
	  if (strlen(path)>0) {
	    strcpy(inDataName, path);
	    if (inDataName[strlen(inDataName)-1] != '/')
	      strcat(inDataName, "/");
	  }
	  else
	    strcpy(inDataName, "");
	  
	  // check whether data file exists
	  strcat(inDataName, xml_get_string_value(doc, 
	    "level1Product.productComponents.imageData[%d].file.location.path",
	    ii));
	  strcat(inDataName, "/");
	  strcat(inDataName, xml_get_string_value(doc, 
	    "level1Product.productComponents.imageData[%d].file.location."
	    "filename", ii));
	  if (!fileExists(inDataName)) {
	    if (!message)
	      message = (char *) MALLOC(sizeof(char)*1024);
	    sprintf(tmp, "Data file (%s) does not exist!\n", inDataName);
	    strcat(message, tmp);
	    found = FALSE;
	  }	
	}
      }
    }
    fclose(fp);
    xmlFreeDoc(doc);
    xmlCleanupParser();
    if (path)
      FREE(path);
    if (inDataName)
      FREE(inDataName);
    FREE(inFile);
  }

  return found;
}
Ejemplo n.º 25
0
static int ProcessAudioFile(ZFS_TASK *ptask){
	//Audio policy:
	//1. check whether the file exist in imported folder
	//2. if exist, check whether they have same metadata
	// 3. if metadata are the same, skip/delete the file
	// 4. if metadata are not the same, insert to DB
	//5. if file is new, insert to DB
	//6. if the file had extract an alum art, check whether 
	//   the album art had been exist in DB or folder, if not
	//   exist, insert to DB and move to extracted folder
	//7. update import summary
	ZInfo4 (DBG_MISC, "Process Audio file[%s][%s]", ptask->path, ptask->name);

	const int PROCESS_AUDUIO_THUMBNAIL = 1;

	PAUDIO_METADATA metadata = NULL;
	char fileName[MAX_PATH_SIZE] = {0};
	char fullPath[MAX_PATH_SIZE] = {0};
	char dstPath[MAX_PATH_SIZE*2] = {0};
	int isDir;
	int validformat = TRUE;//paul add on 080827,merge from Olive.

	sprintf(&fullPath[0], "%s/%s", ptask->path, ptask->name);
	/* Covert fileName to UTF-8 */
	strcpy (fileName, ptask->name);
	if (ZUtilConvertStringToUTF8 (fileName) != 0) {
		ZError (DBG_MISC, "Covert UTF-8 failed, skip this file->%s", fileName);
		return -1;
	}
	else {
		ZInfo4 (DBG_MISC, "UTF-8 fileName->%s", fileName);
	}
	sprintf(&dstPath[0], "%s/%s", DIR_IMPORTED, fileName);

	if ((metadata = getAudioMetadata (fullPath, &validformat)) == NULL) {
		//paul add on 080827 for invalid format merge from Olive.
		if (validformat == FALSE){
			validformat = TRUE;
			if (removeFile (pzfs, ptask->path, fileName) != 0)
			{
				ZError (DBG_MISC,
						"Remove invalid file failed->%s/%s",
						ptask->path, fileName);
			}
			else{
				ZInfo4 (DBG_MISC,
						"Remove invalid file success->%s/%s",
						ptask->path, fileName);
			}
		}//end paul

		//this is an internal error, if the audio did not have embbed metadata
		//we will genreate an empty one
		ZError (DBG_MISC, "Cannot get any metadata -> %s", metadata);
		return -1;
	}
	ZInfo4 (DBG_MISC, "Get metadata successfully.");

	/* zfs policy here */
	/* First, we will check to see if the file exists in DIR_IMPORTED folder,
	   if yes, we will match the metadata, if the same of metadata, This is the
	   duplicate file, otherwise, it is the new file, so change it's name as the
	   format xxxx_DDUUPPx.ext and insert it into DB */

	/* get the file in DIR_IMPORTED ??? */
	if(ZUtilIsFilePresent(dstPath, &isDir)) {
	//if (matchFile (DIR_IMPORTED, fileName) == 1) {
		/* get the file in the DIR_IMPORT folder */
		/* Now, try to match the metadata */
		// NOTE: not finished
		if (matchMetadata (pzfs, metadata) == 1) {
			ZError (DBG_MISC, "Duplicate file!!! The metadata exists in DB->%s", fullPath);
//			if (removeFile (pzfs, ptask->path, fileName) != 0) {
			if (removeFile (pzfs, ptask->path, ptask->name) != 0) {
				ZError (DBG_MISC, "Remove duplicate file failed->%s/%s",
						ptask->path, fileName);
			}
			else {
				deletedPlusOne ();	/* Deleted plus one */
				saveSummary (pzfs);	/* Sync to DB */
			}

			if (metadata)
				free(metadata);

			return 0;
		}
		else {
			/* not the same metadata, so change the last file name to new name */
			/* filename format xxx_DDUUPPx.xxx */
			getNewFileName (pzfs, fileName);
			sprintf(&dstPath[0], "%s/%s", DIR_IMPORTED, fileName);
			ZInfo3(DBG_MISC, "Have file with same name, use new filename [%s]", fileName);
		}
	}

	if(AUTO_SORT) {
		/* move media file to DIR_IMPORTED */
		if (rename (fullPath, dstPath) != 0) {
			ZError (DBG_MISC, "Move file failed -> %s", fullPath);
			if (removeFile (pzfs, ptask->path, ptask->name) != 0) {
				ZError (DBG_MISC, "Remove file failed -> %s/%s",
						ptask->path, ptask->name);
			}
			else {
				deletedPlusOne ();	/* Deleted plus one */
				saveSummary (pzfs);	/* Sync to DB */
			}

			if (metadata)
				free(metadata);

			return 0;
		}
		strcpy (metadata->path, dstPath);
		ZInfo4 (DBG_MISC, "Move file successfully -> %s", metadata->path);
	}

	if(PROCESS_AUDUIO_THUMBNAIL) {
		/* move thumbnail to DIR_EXTRACTED 2008-3-18 */
		/* Thumbnail Policy:
		   If the thumbnail of the album exist, don't replace it, otherwise move it to
		   DIR_ EXTRACTED with album name */

		//TODO: need to check unknown policy
		// changed by Joe (if album is unknown , do not get the albumArt)
		if ((strcasestr (metadata->album, "unknown") != NULL)
				&& (fileExists (metadata->albumArt) == 1)) {
			remove (metadata->albumArt);
			metadata->albumArt[0] = '\0';
		}

		if (strlen (metadata->albumArt) > 1 && fileExists (metadata->albumArt) == 1) {
			/* NOTE: if the album art exists in zDB, don't replace it */
			int exists = isAlbumArtExists (pzfs, metadata->album);
			if (exists == 0) {
				char tmp[MAX_PATH_SIZE] = {0};
				sprintf (tmp, "%s/%s%s", DIR_EXTRACTED,
						metadata->album,
						THUMBNAIL_EXTENSION);
				/* Move the thumbnail to DIR_EXTRACTED */
				ZInfo4 (DBG_MISC, "Move thumbnail %s to %s",
						metadata->albumArt, tmp);
				/* NOTE: rename don't support over-partition move */
				if (rename (metadata->albumArt, tmp) != 0) {
					ZError (DBG_MISC, "Move thumbnail failed ->%s",
							metadata->albumArt);

					/* Delete the thumbnail */
					remove (metadata->albumArt);
					metadata->albumArt[0] = '\0';
				}
				else {
					strcpy (metadata->albumArt, tmp);
					ZInfo4 (DBG_MISC, "Move thumbnail successfully");
				}
			}
			else {
				if (exists == -1)
					ZError (DBG_MISC, "Get album art info from zDB failed, will not insert albumArt");
				else
					ZInfo4 (DBG_MISC, "Duplicate albumArt, will not insert");

				/* Delete the thumbnail */
				remove (metadata->albumArt);
				//the album art should be cleaned to avoid zDB update the album's album art
				metadata->albumArt[0] = '\0';
			}
		}
	}

	/* add to DB */
	if (addAudioDBItem (pzfs, metadata) != 0) {
		ZError (DBG_MISC, "add metadata to DB failed");

			if (metadata)
				free(metadata);

		return -1;
	}
	else {
		/* import num plus one */
		importedPlusOne ();
		if (saveSummary (pzfs) != 0) {
			ZWarning (DBG_MISC, "Save summary failed 2.");
		}
	}
	
	if(metadata)
		free(metadata);

	return 0;
}
Ejemplo n.º 26
0
int isRadarsat2_ext(char *dataFile, int check_data, char **error)
{
  char dataType[25];
  char *message = NULL;
  int found = FALSE;
  char *inFile = MALLOC(sizeof(char)*(strlen(dataFile)+16));
  strcpy(inFile, dataFile);
  // Let's first check for an .xml extension
  char *ext = findExt(inFile);

  // Append extension in case we don't find it
  if (!fileExists(inFile) && ext == NULL) {
    strcat(inFile, ".xml");
    ext = findExt(inFile);
  }

  // If it has the correct extension, investigate it further
  // Might sound a little harsh but avoids some XML parser warning otherwise.
  if (fileExists(inFile) && ext && strcmp_case(ext, ".xml") == 0) {
    int ii, band_count = 0;
    char tmp[256], *path = NULL, *inDataName = NULL;
    char polarizations[25], satellite[25];
    FILE *fp;
    fp = fopen(inFile, "r");
    xmlDoc *doc = xmlReadFile(inFile, NULL, 0);
    if (doc) {
      strncpy_safe(satellite, 
	           xml_get_string_value(doc, "product.sourceAttributes.satellite"), 20);
      
      // only care about Radarsat-2 data
      if (strcmp_case(satellite, "RADARSAT-2") == 0) {
	
	found = TRUE;
	strncpy_safe(dataType, xml_get_string_value(doc, 
          "product.imageAttributes.rasterAttributes.dataType"), 20);
	if (strcmp_case(dataType, "COMPLEX") != 0) {
	  if (!message)
	    message = (char *) MALLOC(sizeof(char)*1024);
	  sprintf(tmp, "Wrong data type!\n"
		  "Polarimetric processing requires SLC data!\n");
	  strcat(message, tmp);
	  if (check_data)
  	  found = FALSE;
	}
	
	// path from the xml (metadata) file
	path = get_dirname(inFile);
	inDataName = (char *) MALLOC(sizeof(char)*(strlen(path)+512));
	strncpy_safe(polarizations, xml_get_string_value(doc, 
	  "product.sourceAttributes.radarParameters.polarizations"),20);
	for (ii=0; ii<strlen(polarizations)-1; ii++)
	  if (polarizations[ii] == ' ')
	  polarizations[ii] = ',';
	if (strstr(polarizations, "HH"))
	  band_count++;
	if (strstr(polarizations, "VV"))
	  band_count++;
	if (strstr(polarizations, "HV"))
	  band_count++;
	if (strstr(polarizations, "VH"))
	  band_count++;
	
	for (ii=0; ii<band_count; ii++) {
	  if (strlen(path)>0) {
	    strcpy(inDataName, path);
	    if (inDataName[strlen(inDataName)-1] != '/')
	      strcat(inDataName, "/");
	  }
	  else
	    strcpy(inDataName, "");
	  strcat(inDataName, xml_get_string_value(doc, 
	    "product.imageAttributes.fullResolutionImageData[%d]", ii));
	  if (!fileExists(inDataName)) {
	    if (!message)
	      message = (char *) MALLOC(sizeof(char)*1024);
	    sprintf(tmp, "Data file (%s) does not exist!\n", inDataName);
	    strcat(message, tmp);
	    if (check_data)
  	    found = FALSE;
	  }
	}
      }
    }
    if (fp) {
      fclose(fp);
      xmlFreeDoc(doc);
      xmlCleanupParser();
    }
  }    
  FREE(inFile);

  if (!found && message)
    *error = message;

  return found;
}
Ejemplo n.º 27
0
int InitServer()
{
    char ErrBuff[256] = {0};
    FILE* fileLogTmp;
    //##############  CONFIGURATE SERVER  ###############
    
    // Read parameters from 'conf/httpd.conf' to list
    List *lstConf = initList();
    if (0 != getParamsFromFile("conf/httpd.conf", lstConf, '='))
    {
        puts("Could not read configuration file...");
        return 1;
    }
    // Apply parameters from list (or set to default, if they are absent)
    int port          = getParamInt(lstConf, "portListen",    80);
    int maxConn       = getParamInt(lstConf, "maxConnection", 100);
    char *logAccessPath = getParamS(lstConf, "logAccess",    "log/access.log");
    char *logErrorPath  = getParamS(lstConf, "logError",     "log/error.log");
    defaultPage         = getParamS(lstConf, "defaultPage",  "/index.htm");
    rootFolder          = getParamS(lstConf, "rootFolder",   "www/");
    char *interface     = getParamS(lstConf, "interfaceToListen", "");
    // Open new log files
    if ( initErrorLog(logErrorPath) == 0 )
    {
        return 1;
    }
    if ( !( fileLogAccess = fopen(logAccessPath, "a") ) )
    {
        snprintf(ErrBuff, sizeof(ErrBuff), "Could not open '%s'!", logAccessPath);
        puts(ErrBuff);
        logError(ErrBuff);
        return 1;
    }
    // Check if default page exists
    char *fullPath = malloc(strlen(rootFolder)+strlen(defaultPage)+1);
    strcpy(fullPath, rootFolder);
    strcat(fullPath, defaultPage);
    if (fileExists(fullPath) != 0)
    {
        snprintf(ErrBuff, sizeof(ErrBuff), 
            "Could not find default page following next path: '%s'!",
            fullPath);
        puts(ErrBuff);
        logError(ErrBuff);
    }
    // Free data with configuration from memory
    removeAll(lstConf);
    
    //#############  START SERVER  ###############

    struct sockaddr_in saddr;       // used for getting IP _
    socklen_t len = sizeof( saddr );// of incomming connection _
    char IP_Buff[INET_ADDRSTRLEN]; // defined in <netinet/in.h> .

    int listenSocket = 0, connSocket = 0;
    pid_t child_pid;
    
    // Try to start server
    listenSocket = startServer(interface, port, maxConn);

    if (listenSocket > 0)
    {
        #ifndef __DEBUG_MODE__
        logError("#Server started Successfully!");
        #endif
        printf("\n\nServer started Successfully!\n\n");
        //#############  MAIN PROCESSING LOOP  ###############
        while(1)
        {
            // Wait few second, if there's no connections - continue
            if (wait4Socket(listenSocket, ACCEPT_TIMEOUT) > 0)
            {
                connSocket = accept( listenSocket, ( struct sockaddr* )&saddr, &len );
                if ( listenSocket < 0 ) {
                    logError("Accept Error...");
                    break;
                }
                
                child_pid = fork ();
                if (child_pid == 0)     //####  child thread  ####
                {
                    #ifndef __DEBUG_MODE__
                    close (STDIN_FILENO);     //child don't need to print anything,
                    close (STDOUT_FILENO);    //  so close input/output streams
                    #endif
                    close (listenSocket);       //close a child-copy of listening port
                    
                    if ( inet_ntop( AF_INET, &saddr.sin_addr, IP_Buff, INET_ADDRSTRLEN ) == NULL )
                    {
                        logError("Can't convert IP addr");
                        close(connSocket);
                        exit(1);
                    }
                    procConn(IP_Buff, connSocket);
                    
                    exit (0);       // close child process
                }
                else if (child_pid > 0) // ####  parent thread  ####
                {
                    
                    close (connSocket);
                    #ifdef __DEBUG_MODE__
                    if (getComm() == 0)
                    {
                        break;
                    }
                    #endif
                }
                else
                    logError("Can't fork");     // if can't create child
            }
        }
        close(listenSocket);    // close parent listenSocket


        #ifndef __DEBUG_MODE__
        logError("#Server closed Successfully!");
        #endif
        printf("\n\nServer closed Successfully!\n\n");
        
        return 0;
    }
    logError("#Server was not started!");
    printf("\n\nServer was not started! See error.log to get more information!\n\n");
    return 1;
}
Ejemplo n.º 28
0
Cube_T::Cube_T(string filename){

  printf("Cube_T::loading from %s\n", filename.c_str());
  timeStep = 0;
  d_halo = false;
  d_gt = false;

  cubes.resize(0);
  string extension = getExtension(filename);
  if(extension != "cbt"){
    printf("Cube_T::error::the file %s does not end with cbt\n", filename.c_str());
    exit(0);
  }
  std::ifstream in(filename.c_str());
  if(!in.good())
    {
      printf("Cube_T::error::The file %s can not be opened\n",filename.c_str());
      exit(0);
    }
  string s;
  while(getline(in,s)){
    Cube_P* cb;
    if(fileExists(s))
      cb = CubeFactory::load(s);
    else if(fileExists(getDirectoryFromPath(filename) + "/" + getNameFromPath(s)))
      cb = CubeFactory::load(getDirectoryFromPath(filename) +
                             "/" + getNameFromPath(s));
    else{
      printf("Cube_T::The file %s does not exist, exiting\n", s.c_str());
    }
    if(!cb){
      printf("Cube_T::error::The cubee %s can not be loaded\n",s.c_str());
      exit(0);
    }
    cubes.push_back(cb);
  }
  in.close();
  if(cubes.size()==0){
      printf("Cube_T::error::There is no cube loaded from %s\n",s.c_str());
      exit(0);
  }

  // Get all the information from cubes[0] (we assume all the cubes are the same and
  //   do not check for that (check needed if we want to make the code robust)
  this->voxelWidth  = cubes[0]->voxelWidth;
  this->voxelHeight = cubes[0]->voxelHeight;
  this->voxelDepth  = cubes[0]->voxelDepth;
  this->cubeWidth   = cubes[0]->cubeWidth;
  this->cubeHeight  = cubes[0]->cubeHeight;
  this->cubeDepth   = cubes[0]->cubeDepth;
  this->r_max       = cubes[0]->r_max;
  this->s_max       = cubes[0]->s_max;
  this->t_max       = cubes[0]->t_max;
  this->nColToDraw  = cubes[0]->nColToDraw;
  this->nRowToDraw  = cubes[0]->nRowToDraw;
  this->filenameVoxelData = "";
  this->directory          = getDirectoryFromPath(filename);
  this->filenameParameters = getNameFromPath(filename);
  this->type               = cubes[0]->type;

  string noExt = getNameFromPathWithoutExtension(filename);
  string gtName = getDirectoryFromPath(filename) +  noExt + ".gt";
  printf("The ground truth data should be in %s\n", gtName.c_str());
  if(fileExists(gtName)){
    gtData = loadMatrix(gtName);
  }
  printf("ans it's size is %i\n", (int)gtData.size());

}
Ejemplo n.º 29
0
std::string System::findDataFile
(const std::string&  full,
 bool                errorIfNotFound) {

    // Places where specific files were most recently found.  This is
    // used to cache seeking of common files.
    static Table<std::string, std::string> lastFound;

    // First check if the file exists as requested.  This will go
    // through the FileSystemCache, so most calls do not touch disk.
    if (fileExists(full)) {
        return full;
    }

    // Now check where we previously found this file.
    std::string* last = lastFound.getPointer(full);
    if (last != NULL) {
        if (fileExists(*last)) {
            // Even if cwd has changed the file is still present.
            // We won't notice if it has been deleted, however.
            return *last;
        } else {
            // Remove this from the cache it is invalid
            lastFound.remove(full);
        }
    }

    // Places to look
    static Array<std::string> directoryArray;

    if (directoryArray.size() == 0) {
        // Initialize the directory array
        RealTime t0 = System::time();

        Array<std::string> baseDirArray;

        std::string initialAppDataDir(instance().m_appDataDir);
        
        baseDirArray.append("");
        if (! initialAppDataDir.empty()) {
            baseDirArray.append(initialAppDataDir);
        }

        const char* g3dPath = getenv("G3DDATA");

        if (g3dPath && (initialAppDataDir != g3dPath)) {
            baseDirArray.append(g3dPath);
        }

        static const std::string subdirs[] = 
            {"font", "gui", "SuperShader", "cubemap", "icon", "material", "image", "md2", "md3", "ifs", "3ds", "sky", ""};
        for (int j = 0; j < baseDirArray.size(); ++j) {
            std::string d = baseDirArray[j];
            if (fileExists(d)) {
                directoryArray.append(d);
                for (int i = 0; ! subdirs[i].empty(); ++i) {
                    const std::string& p = pathConcat(d, subdirs[i]);
                    if (fileExists(p)) {
                        directoryArray.append(p);
                    }
                }
            }
        }

        logLazyPrintf("Initializing System::findDataFile took %fs\n", System::time() - t0);
    }

    for (int i = 0; i < directoryArray.size(); ++i) {
        const std::string& p = pathConcat(directoryArray[i], full);
        if (fileExists(p)) {
            lastFound.set(full, p);
            return p;
        }
    }

    if (errorIfNotFound) {
        // Generate an error message
        std::string locations;
        for (int i = 0; i < directoryArray.size(); ++i) {
            locations += pathConcat(directoryArray[i], full) + "\n";
        }
        alwaysAssertM(false, "Could not find '" + full + "' in:\n" + locations);
    }

    // Not found
    return "";
}
Ejemplo n.º 30
0
//========================================================
void ResearchMenu(){

	char w[20];
	int validPath;
	int const maxSizePath = 100;
	char *path[maxSizePath] , *pathOfList[maxSizePath];
	int choice;
	float *percent;
	float *positionFile;
	char openPath[50]="xdg-open"; // Permite to default open file ex: xdg-open img.png
	
	PileVD *valDesc , tmpVD;
	PictureDesc imgDsc;
	SoundDesc sdDsc;
	//TextDesc txtDsc;
	FILE *IMGbase;
	FILE *TXTbase;
	FILE *SOUNDbase;
	FILE *fileOfDesc;
	FILE *GivenPath;
	
	do{
		printf("+=========================+\n");
		printf("|                         |\n");
		printf("|1. Research a word       |\n");
		printf("|2. Research a color      |\n");
		printf("|3. Research similar sound|\n");
		printf("|                         |\n");
		printf("+=================0.RETURN+\n");

		scanf("%d" , &choice);
		if(choice!=1 && choice !=2 && choice!=0 && choice!=3){
			system("clear");
		}
	}while(choice!=1 && choice!=2 && choice!=0 && choice!=3);
	clearBuffer();
	switch(choice){
		case(1):
			/*TXTbase=fopen("TextBaseDesc.db" , 'r');
			researchTXT
			fclose(TXTbase);
			system("clear");
			*/
			break;
		case(2):
			system("clear");
			if(!fileExists("PictureBaseDesc.db"))printf("PictureBaseDesc.db don\'t exists\n");
			else{
				IMGbase=fopen("PictureBaseDesc.db" , 'r');
				researchIMG(IMGbase);
				fclose(IMGbase);
			}
			ResearchMenu();
			break;
		case(3):
			if(!fileExists("PictureBaseDesc.db"))printf("PictureBaseDesc.db don\'t exists\n");
			else{
				SOUNDbase=fopen("SoundBaseDesc.db" , 'r');
				researchSound(SOUNDbase);
				fclose(SOUNDbase);
			}
			system("clear");
			ResearchMenu();
			break;
		case(0): 
			system("clear");
			mainMenu(); 
			break;
		default: // to secure
			exit(0); 
			break;
	}
	mainMenu();
}