Exemplo n.º 1
0
int main (int argc, char *argv[]) {
    
    /*
     Declaração de variáveis
     */
    
    float velocidadeDoBarco = velocidadeDoBarcoInicial;
    int larguraDoRio = larguraDoRioInicial;
    int fluxoDesejado = fluxoDesejadoInicial;
    int dIlha = distanciaEntreIlhasInicial;
    float pIlha = probabilidadeDeObstaculosInicial;
    float limiteMargens = limiteDasMargens;
    
    struct timespec tim2; 
    struct timespec tim;
    
    int seed = 1;
    int verbose = 0;
    int indice = 0;
    pixel **grade;
    
    /*
     Leitura de parametros
     */
    
    getArgs(argc, argv, &velocidadeDoBarco, &larguraDoRio, &seed, &fluxoDesejado, &verbose, &dIlha, &pIlha, &limiteMargens);
    corrigeArgs(argc, argv, &velocidadeDoBarco, &larguraDoRio, &seed, &fluxoDesejado, &verbose, &dIlha, &pIlha, &limiteMargens);

    
    
    if (verbose) {
        printf ("\t \t Opcoes disponiveis: \n"
                "-b = %f  - Velocidade do barco\n"
                "-l = %d  - Largura do Rio\n"
                "-s = %d  - Semente para o gerador aleatorio\n"
                "-f = %d  - Fluxo da agua\n"
                "-v = %d  - Verbose\n"
                "-pI = %f - Probabilidade de haver obstaculos\n"
                "-dI = %d - Distancia minima entre obstaculos\n"
                "-lM = %f - Limite de tamanho das margens (de 0 a 1)\n"
                "Pressione Enter para continuar...\n", velocidadeDoBarco, larguraDoRio, seed, fluxoDesejado, verbose, pIlha, dIlha, limiteMargens);
        getchar();
    }
    
    /*
     Inicialização
     */
    
    tim.tv_sec  = 0;
    tim.tv_nsec = 100000000/velocidadeDoBarco;
    
    /*
     Seed
     */
    
    if (seed == 0)
        seed = time(NULL);
    
    srand(seed);
    
    /*
     Criação do primeiro frame
     */
    
    grade = initGrade(alturaDaGrade, larguraDoRio);
    
    criaPrimeiroFrame(grade, alturaDaGrade, larguraDoRio, limiteMargens, fluxoDesejado, dIlha, pIlha);
    
    outputArray(grade, alturaDaGrade, larguraDoRio, indice);
    
    clearScreen();
    
    /*
     Frames subsequentes
     */
    
    for(;;){
        indice = (indice - 1+alturaDaGrade) % alturaDaGrade;
        
        criaProximoFrame(grade, alturaDaGrade, larguraDoRio, limiteMargens, fluxoDesejado, indice, dIlha, pIlha);
        
        outputArray(grade, alturaDaGrade, larguraDoRio, indice);

        clearScreen();
        
        nanosleep(&tim, &tim2);
    }
    
    /*
     Frees
    */
    
    freeGrade(grade, alturaDaGrade, larguraDoRio);
    
    
    
    
    return 0;
}
Exemplo n.º 2
0
int main(int argc, char *argv[]){
    char input [INPUT_SIZE_MAX];
    char exitKey[]="exit\n";
    pid_t childPID;

    //output prompt
    printf("Prompt:");
    //read line from stdin
    fgets (input, sizeof(input), stdin);

/*
    //array of arguments for exec, must be null-terminated
    char *newargv[] = {"ls", NULL};

    //execvp doesn't need the environment variable
    //why do I have to put "ls" twice in execvp?
        //The first "ls" finds where ls is (/bin/ls), then the second one
        //is what actually does the command (or vice-versa)

        if(execvp("ls",newargv) < 0){
            //execvp returns -1 if it fails
            printf("ERROR: exec failed\n");
            exit(EXIT_FAILURE);
        }
*/

    //fork a new process
    childPID = fork();

    if(childPID >= 0) { //fork successful
    
        if(childPID == 0) { //child process
            printf("In child process\n");
            //note that input inculdes the newline character
            printf("input is:%s", input);

            //parsing input into arguments
            int numArgs; //updated in getArgs function
            char** arguments = getArgs(input, &numArgs);
            int i;
            for(i = 0; i < numArgs; i++){
                printf("arguments[%d]=%s\n", i, arguments[i]);
            }

            printf("exiting child process\n");
        }
        
        else { //parent process
            printf("In parent process\n");

            int status; 
            do {
                //puts return value into status
                wait(&status);

                //wait returns the process ID of a child (greater than 0),
                //-1 on error, and errno is set to ECHILD when
                //there are no child processes to wait for
                if (status == -1 && errno != ECHILD){
                    perror("Error during wait()");
                    //not sure what this does yet
                    //abort(); 
                }
            } while (status > 0);
            printf("exiting parent process\n");
        }
    }

    else { //fork failed
        printf("\nFork failed!\n");
        return 1;
    }
    
    printf("program terminated\n");

return 0;
}
Exemplo n.º 3
0
Arquivo: main.c Projeto: wtmcneill/HPC
int main(int argc, char *argv[])
{
  int err = 0;
  int i, j;
  double *vecA, *matB, *vecC;
  double s_time,e_time;
    
  // Get cmndln args exit if error occurs
  if((err = getArgs(argc, argv)))
    errExit("Exiting app");

 //Args.m = 3;
 // Args.n = 3;
 // Args.verbose = 1;

  // Allocate memory for the matrix and vectors
  if(! (vecA = (double*) malloc(Args.m * sizeof(double))))
    errExit("Error: Failed to allocate memory for vecA\n");
  
  if(! (matB = (double*) malloc(Args.m * Args.n * sizeof(double))))
    errExit("Error: Failed to allocate memory for matB\n");
  
  if(! (vecC = (double*) malloc(Args.n * sizeof(double))))
    errExit("Error: Failed to allocate memory for vecC\n");
  
  // Seed the random number generator (This provides a repeatable random series)
  srand(1);

  // Init matB as an array with random values between 1 and 10
  for(i=0; i < Args.m; i++)
  {
    for(j=0; j < Args.n; j++)
       matB[i * Args.n + j] = RNDRANGE(10.0);
  }

  // Init vecC as our vector which multiples matB*2
  for(i=0; i < Args.n; i++)
    vecC[i] = RNDRANGE(10.0);

  // Perform the matrix-vector multiply
  s_time=omp_get_wtime();
  matvectMultiply(vecA, matB, vecC);
  e_time=omp_get_wtime();

  // If verbose then display the matrices
  if(Args.verbose)
  {
    outputMat("Matrix B:", matB);
    outputVec("Vector C:", vecC);
    outputVec("Resultant Vector A:", vecA);
  }
  
  printf("%d %f\n",omp_get_max_threads(),e_time-s_time);

  // Free memory 
  if(vecA) free(vecA);
  if(matB) free(matB);
  if(vecC) free(vecC);
  
  //system("pause");
  return err;
}
Exemplo n.º 4
0
int main(int argc, char *argv[])
{
	QApplication a(argc, argv);
	QString port = "";
	bool autoconnect = true;
	QString plugin = "";
	QList<QPair<QString,QString> > args = getArgs(argc,argv);
	for (int i=0;i<args.size();i++)
	{
		if (args[i].first == "--dev" || args[i].first == "-d")
		{
			port = args[i].second;
		}
		else if (args[i].first == "--help" || args[i].first == "-h")
		{
			printHelp();
			return 0;
		}
		else if (args[i].first == "--autoconnect" || args[i].first == "-a")
		{
			if (args[i].second.toLower() == "false")
			{
				autoconnect = false;
			}
		}
		else if (args[i].first == "--plugin" || args[i].first == "-p")
		{
			plugin = args[i].second;
		}
		else
		{
			qDebug() << "Unknown command" << args[i].first;
			printHelp();
			return 0;
		}
	}

	MainWindow w;
	if (port != "")
	{
		w.setDevice(port);
	}
	if (plugin == "")
	{
		if (QFile::exists("plugins/libfreeemsplugin.so"))
		{
			plugin = "plugins/libfreeemsplugin.so";
		}
		else if (QFile::exists("/usr/share/emstudio/plugins/libfreeemsplugin.so"))
		{
			plugin = "/usr/share/emstudio/plugins/libfreeemsplugin.so";
        }
        else if (QFile::exists("plugins/freeemsplugin.lib"))
        {
            plugin = "plugins/freeemsplugin.lib";
        }
        else if (QFile::exists("plugins/libfreeemsplugin.a"))
        {
            plugin = "plugins/libfreeemsplugin.a";
        }
        else if (QFile::exists("plugins/freeemsplugin.dll"))
        {
            plugin = "plugins/freeemsplugin.dll";
        }
	}
	w.setPlugin(plugin);
	if (autoconnect)
	{
		w.connectToEms();
	}
	w.show();
	return a.exec();
}
Exemplo n.º 5
0
int main(int argc, char **argv) {
  /* Initial number of changepoints */
  int nK0=1;
  
#ifdef FIXED
  FILE *pfp, *kfp, *Lfp;
  char *pfn="Probs.dat", *kfn="K.dat", *Lfn="Likelihood.dat";
  prefix=NULL;
#endif

#ifndef FIXED
  getArgs(argc, argv);
#else
  getFixedArgs(argc, argv);
#endif
  processData(dataFn);

  initialise();

#ifdef FIXED
  if(prefix) {
    pfn=addPrefix(pfn, prefix);
    kfn=addPrefix(kfn, prefix);
    Lfn=addPrefix(Lfn, prefix);
  }
  pfp=fopen(pfn,"w");
  kfp=fopen(kfn,"w");
  Lfp=fopen(Lfn,"w");

  setData(CDFdata, getNdata());
  setSample(sampleMixed);
  iterate(pfp, kfp, Lfp, /* dPriorNew */dPriorFixedChangepoints, dFixedLikelihood,p0,nProb, ip0, nK, seed, nIter);
#endif

#ifdef DEFAULT
    if(!restart) {

    iterateRJ(prefix, prefix, prefix, prefix,
	      sampleBirthDeath,
	      dPriorChangepoints,dLikelihood,
	      p0, nK0+1,1, nProb,
	      ip0, nK0,1, nK, seed,  nIter);
  }
  else {
  /* int k0[]={50000, 100000}; */
  /* nK0=2; */
  /* initialiseLocations(ip0, k0, CDFdata,getNdata()-1, */
  /* 		       p0, 2); */
  FILE *re_fp=fopen(re_K, "rb");
  char *buf=malloc(MAX_LEN+1);
  char *ll;
  int nReK=0, nReP=0;
  int i;
  
  int nums[NCHANGE+1];
  double dNums[NCHANGE+2];
  
  ll=lastLine(re_fp, buf, MAX_LEN);
  fclose(re_fp);
  
  nReK=str2ints(ll, nums);
  /* for(i=0; i<nReK; i++) { */
  /*   fprintf(OUT, "%d\t", nums[i]); */
  /* } */
  /* fprintf(OUT, "\nSuccessfully converted %d integers\n", nReK); */
  

  re_fp=fopen(re_P, "rb");
  ll=lastLine(re_fp, buf, MAX_LEN);
  free(buf);
  fclose(re_fp);
  
  nReP=str2doubles(ll, dNums);
  /* for(i=0; i<nReP; i++) { */
  /*   fprintf(OUT, "%f\t", dNums[i]); */
  /* } */
  /* fprintf(OUT, "\nSuccessfully converted %d doubles\n", nReP); */

  initialiseLocationsAndProbs(ip0, p0,
			      nums+1, dNums+1,
			      nReK-1);
  /* printIntParameters(OUT, ip0, nReK-1); */
  /* printParameters(OUT, p0, nReP-1); */
  /* exit(1); */

  iterateRJ(prefix, prefix, prefix, prefix,
	    sampleBirthDeath,
	    dPriorChangepoints,dLikelihood,
	    p0, nReP-1,1, nProb,
	    ip0, nReK-1,1, nK, seed,  nIter);
  }
#endif

#ifdef GEO
  iterateRJ(prefix, prefix, prefix, prefix,
	    sampleBirthDeath,
	    dPriorChangepointsGeo,dLikelihood,
	    p0, nK0+1,1, nProb,
	    ip0, nK0,1, nK, seed,  nIter);
#endif

#ifdef NEGATIVEBINK1
  iterateRJ(prefix, prefix, prefix, prefix,
	    sampleBirthDeath,
	    dPriorChangepointsNegativeBinK1,dLikelihood,
	    p0, nK0+1,1, nProb,
	    ip0, nK0,1, nK, seed,  nIter);
#endif
#ifdef NEGATIVEBINK2
  iterateRJ(prefix, prefix, prefix, prefix,
	    sampleBirthDeath,
	    dPriorChangepointsNegativeBinK2,dLikelihood,
	    p0, nK0+1,1, nProb,
	    ip0, nK0,1, nK, seed,  nIter);
#endif
#ifdef NJGEONEGATIVEBINK1
  iterateRJ(prefix, prefix, prefix, prefix,
	    sampleBirthDeath,
	    dPriorChangepoints_nJGeoNegativeBinK1,dLikelihood,
	    p0, nK0+1,1, nProb,
	    ip0, nK0,1, nK, seed,  nIter);
#endif
#ifdef NJGEONEGATIVEBINK2
  iterateRJ(prefix, prefix, prefix, prefix,
	    sampleBirthDeath,
	    dPriorChangepoints_nJGeoNegativeBinK2,dLikelihood,
	    p0, nK0+1,1, nProb,
	    ip0, nK0,1, nK, seed,  nIter);
#endif

  return 0;  
}
Exemplo n.º 6
0
int main(int argc, char** argv)
{	

//--Foodweb Struktur mit Standardwerten aufstellen------------------------------------------------------------------------------------------
	struct simuParams simParams 	= {0.3, 0.65, 0.35, 0.5, 6.0};			// Diese Parameter sind konstant
	struct simuMemory simMem 	= {NULL, NULL, NULL, NULL, NULL};		// Größe der Vektoren liegt noch nicht fest	

	gsl_vector* fixpunkte	= gsl_vector_calloc(9);
 	

	struct foodweb nicheweb	= {NULL, fixpunkte, NULL,&simParams, &simMem, 18, 3, 1, 5, 0, 0, -7., 0.0, 0, 1};		// Reihenfolge: network, fxpkt, migrPara, AllMus, AllNus, S, B, Rnum, Y, T, Tchoice, d, x, M, Z
	
	struct migration stochastic = {NULL, NULL, NULL, NULL, NULL, NULL, 0.00001, NULL, NULL, NULL, NULL, NULL};
	
	struct resource res = {500.0, 0.0};											// Resource: Größe, Wachstum
	
	
	
	
//--Konsoleneingabe-------------------------------------------------------------------------------------------------------------------------
	
	int L = 5;	// Statistik
	int i = 0,j;	// Counter
	char aims6[255] = ORT;
	FILE* RobustnessEachRun;
	
	int checksum = getArgs(argc, argv, &(nicheweb.S), &(nicheweb.B), &(nicheweb.T), &(nicheweb.d), &L, &(nicheweb.Y), &(nicheweb.x), &(nicheweb.M), &(res.size), &(nicheweb.Z), &(stochastic.Bmigr));	

		if (checksum != 11 && checksum!=(int)(argc-1)/2) 	// Alles gesetzt?									
		 {	
			printf("Bitte gültige Eingabe für Parameter machen!\nProgramm wird beendet.\n");		
			return(0);		
		 }

/*	int length			= ((nicheweb.Rnum+nicheweb.S)*(nicheweb.S+nicheweb.Rnum)+1+nicheweb.Y*nicheweb.Y+1+(nicheweb.Rnum+nicheweb.S)+nicheweb.S+1);	// Länge des Rückabewerts
	nicheweb.network = gsl_vector_calloc(length);	 
*/	
	// Speicher belegen, nachdem die Größe des Systems durch die Konsoleneingabe bekannt ist	
	CallocFoodwebMem(&nicheweb); 
	CallocStochasticMem(&stochastic, nicheweb.Y, nicheweb.S);
	
	printf("Z = %i\n",nicheweb.Z);
	nicheweb.migrPara = gsl_vector_calloc(7); // Reihenfolge: tau, mu, nu, SpeciesNumber, momentanes t, ymigr, migrationEventNumber	 
// 	stochastic.SpeciesNumbers = gsl_vector_calloc(nicheweb.Z);
// 	stochastic.AllMus = gsl_vector_calloc(nicheweb.Z);
// 	stochastic.AllNus = gsl_vector_calloc(nicheweb.Z);
// 	stochastic.Biomass_SpeciesNumbers = gsl_vector_calloc(nicheweb.Z);
// 	stochastic.Biomass_AllMus = gsl_vector_calloc(nicheweb.Z);
// 	stochastic.Biomass_AllNus = gsl_vector_calloc(nicheweb.Z);
	
//--Zufallszahlengenerator initialisieren--------------------------------------------------------------------------------

		const gsl_rng_type *rng1_T;											// ****
		gsl_rng *rng1;   													// initialize random number generator
		gsl_rng_env_setup();   												// ermöglicht Konsolenparameter
		rng1_T = gsl_rng_default;   										// default random number generator (so called mt19937)
		gsl_rng_default_seed = 0;											// default seed for rng
// 		gsl_rng_default_seed = ((unsigned)time(NULL));						// random starting seed for rng
		rng1 = gsl_rng_alloc(rng1_T);
		
		
		
		
//--Struct initialisieren für patchweise Ausgabe----------------------------------------------------------------------------------------		 

	struct data patchwise[nicheweb.Y];
	for(i=0; i<nicheweb.Y; i++)
	{
	  gsl_vector* sini  = gsl_vector_calloc(6);
	  gsl_vector* sfini  = gsl_vector_calloc(6);
	  gsl_vector* bini  = gsl_vector_calloc(6);
	  gsl_vector* bfini  = gsl_vector_calloc(6);
	  gsl_vector* robness  = gsl_vector_calloc(2);
	  
	  //struct data tempo = {sini,sfini,bini,bfini,robness};
	  struct data temp = {sini,sfini,bini,bfini,robness};
	  patchwise[i] = temp;
	}
	
	//printf("test");
//--Initialisierungen---------------------------------------------------------------------------------------------------
	nicheweb.Tchoice = nicheweb.T;
	nicheweb.T = 0;
	nicheweb.d = nicheweb.d/10;
	printf("d ist %f\n",nicheweb.d);
	res.size = res.size/10;
	stochastic.Bmigr = 2.5*stochastic.Bmigr*pow(10,nicheweb.d);
	nicheweb.Z = pow(10,nicheweb.Z);
	printf("Bmigr ist %f\n",stochastic.Bmigr);
	printf("Z ist %i\n",nicheweb.Z);
	printf("x ist %f\n",nicheweb.x);
	//int len	= ((nicheweb.Rnum+nicheweb.S)*(nicheweb.S+nicheweb.Rnum)+1+nicheweb.Y*nicheweb.Y+1+(nicheweb.Rnum+nicheweb.S)+nicheweb.S);	// Länge des Rückabewerts

	gsl_vector *populationFIN 	= gsl_vector_calloc((nicheweb.Rnum + nicheweb.S)*(nicheweb.Y)*5 + (nicheweb.S) + 3);				// Gleiche Länge wie Rückgabe von evolveNetwork
	gsl_vector *robustness		= gsl_vector_calloc(63);
	gsl_vector *resultEvolveWeb	= gsl_vector_calloc((nicheweb.Rnum+nicheweb.S)*nicheweb.Y*5 + 3 + nicheweb.S); 				// y[Simulation], y0, ymax, ymin, yavg, fixp, TL
	gsl_vector *resultRobustness 	= gsl_vector_calloc(63);
	gsl_matrix *D 			= gsl_matrix_calloc(nicheweb.Y,nicheweb.Y);
	gsl_matrix* Dchoice		= gsl_matrix_calloc(nicheweb.Y,nicheweb.Y);
	
	gsl_vector *robustnesstemp	= gsl_vector_calloc(63);
	gsl_vector *meanSquOfDataAll 	= gsl_vector_calloc(63);
	gsl_vector *meanSquOfDataAlltemp = gsl_vector_calloc(63);
	
	gsl_vector *standardDeviationAll = gsl_vector_calloc(63);
	
	gsl_vector *meanOfData	= gsl_vector_calloc((6*4+2)*nicheweb.Y);
	gsl_vector *meanOfDatatemp = gsl_vector_calloc((6*4+2)*nicheweb.Y);
	gsl_vector *meanSquOfData = gsl_vector_calloc((6*4+2)*nicheweb.Y);
	
	gsl_vector *standardDeviation = gsl_vector_calloc((6*4+2)*nicheweb.Y);
	
	gsl_vector_set_zero(robustness);
	gsl_vector_set_zero(meanOfData);
	gsl_vector_set_zero(meanSquOfData); 
	gsl_vector_set_zero(nicheweb.migrPara);
	gsl_vector_set_zero(meanSquOfDataAll);
	
// 	double SpeciesNumber[L*nicheweb.Z][2]; 
// 	double AllMu[L*nicheweb.Z][2];
// 	double AllNu[L*nicheweb.Z][2];
	
	double ymigr = 0;
	double mu = 0;
	double nu = 0;
	double ymigrtemp;
	double ymigrSqu = 0;
	double ymigrDeviation;
	double migrationEventNumber = 0;
	double migrationEventNumbertemp;
	double migrationEventNumberSqu = 0.0;
	double migrationEventNumberDeviation;
	int lastMigrationEventNumber = 0;

//--Simulation---------------------------------------------------------------------------------------------------------------------
	//SetTopology(nicheweb.Y, nicheweb.T, D);	
	SetTopology(nicheweb.Y, nicheweb.Tchoice, Dchoice);	
// 	for(i = 0; i<nicheweb.Y; i++)
// 	{
// 	  for(j = 0 ; j<nicheweb.Y; j++)
// 	  {
// 	    printf("%f\t",gsl_matrix_get(Dchoice,i,j));
// 	  }
// 	  printf("\n");
// 	}

	for(i = 0; i < L; i++)																							
	 { 	
// 		const gsl_rng_type *rng1_T;											// ****
// 		gsl_rng *rng1;   													// initialize random number generator
// 		gsl_rng_env_setup();   												// ermöglicht Konsolenparameter
// 		rng1_T = gsl_rng_default;   										// default random number generator (so called mt19937)
// 		gsl_rng_default_seed = 0;											// default seed for rng
// 		//gsl_rng_default_seed = ((unsigned)time(NULL));						// random starting seed for rng
// 		rng1 = gsl_rng_alloc(rng1_T);
		
		
		printf("\nStarte Durchlauf L = %i\n", i);
//--Starte Simulation-----------------------------------------------------------------------------------------------			
		SetNicheNetwork(nicheweb, stochastic, res, rng1, rng1_T, D);
		gsl_vector_set_zero(resultEvolveWeb);
		populationFIN	 = EvolveNetwork(nicheweb, stochastic, rng1, rng1_T, Dchoice, resultEvolveWeb);
			
		gsl_vector_set_zero(resultRobustness);										
		gsl_vector_memcpy(robustnesstemp, EvaluateRobustness(populationFIN, nicheweb, patchwise, resultRobustness));	// Robustness Analyse
		
		
//--Standardabweichung für Mittelung vorbereiten-----------------------------------------------------------------------------------------		
		determineMean(robustnesstemp, 63, robustness);
		determineMeanSqu(robustnesstemp, 63, meanSquOfDataAll);
		
//--Ausgabewerte----------------------------------------------------------------------------------------------------------		
		ymigrtemp = gsl_vector_get(nicheweb.migrPara, 5);
		migrationEventNumbertemp = gsl_vector_get(nicheweb.migrPara, 6);
// 		for(int j= 0; j<migrationEventNumbertemp; j++)
// 		{
// 		  AllMu[lastMigrationEventNumber+j][0] = gsl_vector_get(stochastic.AllMus, j);
// 		  AllNu[lastMigrationEventNumber+j][0] = gsl_vector_get(stochastic.AllNus, j);
// 		  SpeciesNumber[lastMigrationEventNumber+j][0] = gsl_vector_get(stochastic.SpeciesNumbers,j);
// 		  
// 		  AllMu[lastMigrationEventNumber+j][1] = gsl_vector_get(stochastic.Biomass_AllMus, j);
// 		  AllNu[lastMigrationEventNumber+j][1] = gsl_vector_get(stochastic.Biomass_AllNus, j);
// 		  SpeciesNumber[lastMigrationEventNumber+j][1] = gsl_vector_get(stochastic.Biomass_SpeciesNumbers,j);
// 		}
		lastMigrationEventNumber += migrationEventNumbertemp;
		
		//printf("SpeciesNumber ist %f\n",SpeciesNumber[i]);
		ymigr += ymigrtemp;
		migrationEventNumber += migrationEventNumbertemp;
		
		ymigrSqu += (ymigrtemp*ymigrtemp); 
		migrationEventNumberSqu = (migrationEventNumberSqu*(i)+(migrationEventNumbertemp*migrationEventNumbertemp))/(i+1); 
// 		printf("Additionsteil ist %f\n",(migrationEventNumberSqu*(i)+(migrationEventNumbertemp*migrationEventNumbertemp))/(i+1));
//--Mittelwert und Vorbereitungen für Standardabweichung für die patchweise Ausgabe berechnen--------------------------------		
		linkElements(patchwise, nicheweb.Y, meanOfDatatemp);
		
		determineMean(meanOfDatatemp, (6*4+2)*nicheweb.Y, meanOfData);
		determineMeanSqu(meanOfDatatemp, (6*4+2)*nicheweb.Y, meanSquOfData);
		
		createOutputRobustnessPatchwiseEachRun(nicheweb,patchwise,aims6,RobustnessEachRun,i);
		
		printf("\nBeende Durchlauf L = %i\n", i);
	 }


//-- Standardabweichung berechnen--------------------------------------------------------------------------------------

	ymigrSqu = ymigrSqu/L;
	ymigr = ymigr/L;
	ymigrDeviation = sqrt(ymigrSqu - ymigr*ymigr);
	
	//migrationEventNumberSqu = migrationEventNumberSqu/L;
	migrationEventNumber = migrationEventNumber/L;
	migrationEventNumberDeviation = sqrt(migrationEventNumberSqu - migrationEventNumber*migrationEventNumber);
// 	printf("migrationEventNumber ist %f\n",migrationEventNumber);
// 	printf("migrationEventNumberSqu ist %f\n",migrationEventNumberSqu);
// 	printf("migrationEventNumberDeviation ist %f\n",migrationEventNumberDeviation);
// 	
//-- Für patchweise Ausgabe-------------------------------------------------------------------------------------------
	standardDeviation = determineStandardDeviation((6*4+2)*nicheweb.Y, meanOfData, meanSquOfData, L, standardDeviation);
	standardDeviationAll = determineStandardDeviation(63, robustness, meanSquOfDataAll, L, standardDeviationAll);
	 //printf("der 3. Eintrag in standardDeviationAll ist %f\n", gsl_vector_get(standardDeviationAll,3));
// 	 printf("S ist %f\n", gsl_vector_get(robustness,3));
// 	 printf("Standardabweichung von S ist %f\n", gsl_vector_get(standardDeviationAll,3));
// 	 printf("meanOfDataSqu ist %f\n", gsl_vector_get(meanOfDataSquAll,3));
// 	 printf("meanSquOfData ist %f\n", gsl_vector_get(meanSquOfDataAll,3));
	 
	 
	 
	printf("L=%i\tspeciesini=%f\tspeciesfinal=%f\n", L, gsl_vector_get(robustness, 3)/L, gsl_vector_get(robustness, 9)/L);
	

	
	
//--Abspeichern in File-------------------------------------------------------------------------------------	
	char aims[255] = ORT;

	
	createOutputGeneral(nicheweb, res, stochastic, aims, robustness, standardDeviationAll, L, mu, nu, ymigr, ymigrDeviation, migrationEventNumber, migrationEventNumberDeviation);													// Datei schließen

	
    
	
//--Daten patchweise abspeichern----------------------------------------------------------------------	
// 	printf("population ist %f\n",gsl_vector_get(stochastic.Biomass_AllMus,0));
     
     for(int l = 0 ; l< nicheweb.Y; l++)
     {
       //char name[100];
       char aims2[255] = ORT2;
       
       createOutputPatchwise(nicheweb, res, stochastic, aims2, meanOfData, standardDeviation, L, l);
       
      }
      
//       if(nicheweb.Tchoice != 0)
//       {
//--Ausgewählte Spezies rausschreiben, die migrieren darf---------------------------------------------------------------------------
	
// 	char aims3[255] = ORT;
// 	
// 	//createOutputSpeciesNumber(nicheweb, res, aims3, SpeciesNumber, L, migrationEventNumber);
// 
//       
// //--Ausgewählte Verbindung rausschreiben, über die migriert werden darf---------------------------------------------------------------------------
// 	
// 	char aims4[255] = ORT;
// 	
// // 	createOutputPatchlink(nicheweb, res, aims4, AllMu, AllNu, L, migrationEventNumber);
//       }
      
      printf("\nSimulation abgespeichert\n\n");
	
//--free----------------------------------------------------------------------------------------------------------------  
	free(nicheweb.network);
	
	gsl_vector_free(fixpunkte);
	
	for(i=0; i<nicheweb.Y; i++)
	{
	  gsl_vector_free(patchwise[i].sini);
	  gsl_vector_free(patchwise[i].sfini);
	  gsl_vector_free(patchwise[i].bini);
	  gsl_vector_free(patchwise[i].bfini);
	  gsl_vector_free(patchwise[i].robness);

	}
	
	FreeFoodwebMem(&nicheweb);	// eigene Funktion
	FreeStochasticMem(&stochastic);
	gsl_vector_free(nicheweb.migrPara);
// 	gsl_vector_free(stochastic.AllMus);
// 	gsl_vector_free(stochastic.AllNus);
// 	gsl_vector_free(stochastic.SpeciesNumbers);
// 	gsl_vector_free(stochastic.Biomass_AllMus);
// 	gsl_vector_free(stochastic.Biomass_AllNus);
// 	gsl_vector_free(stochastic.Biomass_SpeciesNumbers);
	gsl_vector_free(populationFIN);
	gsl_vector_free(robustness);	
	gsl_vector_free(meanOfData);
	gsl_vector_free(meanOfDatatemp);
	gsl_vector_free(meanSquOfData);
	gsl_vector_free(standardDeviation);
	gsl_vector_free(standardDeviationAll);
	gsl_vector_free(meanSquOfDataAll);
	gsl_vector_free(meanSquOfDataAlltemp);
	gsl_matrix_free(D);
	gsl_matrix_free(Dchoice);
	//gsl_vector_free(resultEvolveWeb);
	gsl_vector_free(robustnesstemp);
	gsl_rng_free(rng1);
	
	return(0);

}
Exemplo n.º 7
0
int main(int argc, char *argv[])
{
	QApplication a(argc, argv);

	//Init the logger
	QsLogging::Logger& logger = QsLogging::Logger::instance();
	logger.setLoggingLevel(QsLogging::TraceLevel);
#ifdef Q_OS_WIN
	QString appDataDir = QString(getenv("%USERPROFILE%")).replace("\\","/");
#else
	QString appDataDir = getenv("HOME");
#endif
	QDir appDir(appDataDir);
	if (appDir.exists())
	{
		if (!appDir.cd("EMStudio"))
		{
			appDir.mkdir("EMStudio");
			appDir.cd("EMStudio");
		}
		if (!appDir.cd("applogs"))
		{
			appDir.mkdir("applogs");
		}
	}
	const QString sLogPath(QDir(appDataDir + "/EMStudio/applogs").filePath("log.txt"));

	QsLogging::DestinationPtr fileDestination(QsLogging::DestinationFactory::MakeFileDestination(sLogPath, true, 0, 100));
	QsLogging::DestinationPtr debugDestination(QsLogging::DestinationFactory::MakeDebugOutputDestination());
	logger.addDestination(debugDestination);
	logger.addDestination(fileDestination);

	QString port = "";
	bool autoconnect = true;
	QString plugin = "";
	QList<QPair<QString,QString> > args = getArgs(argc,argv);
	for (int i=0;i<args.size();i++)
	{
		if (args[i].first == "--dev" || args[i].first == "-d")
		{
			port = args[i].second;
		}
		else if (args[i].first == "--help" || args[i].first == "-h")
		{
			printHelp();
			return 0;
		}
		else if (args[i].first == "--autoconnect" || args[i].first == "-a")
		{
			if (args[i].second.toLower() == "false")
			{
				autoconnect = false;
			}
		}
		else if (args[i].first == "--plugin" || args[i].first == "-p")
		{
			plugin = args[i].second;
		}
		else
		{
			qDebug() << "Unknown command" << args[i].first;
			printHelp();
			return 0;
		}
	}

	MainWindow *w = new MainWindow();
	if (port != "")
	{
		w->setDevice(port);
	}
	if (plugin == "")
	{
		//If no plugin is specified, load some reasonable defaults.
		if (QFile::exists("plugins/libfreeemsplugin.so"))
		{
			plugin = "plugins/libfreeemsplugin.so";
		}
		else if (QFile::exists("/usr/share/yats/plugins/libfreeemsplugin.so"))
		{
			plugin = "/usr/share/yats/plugins/libfreeemsplugin.so";
		}
		else if (QFile::exists("plugins/freeemsplugin.lib"))
		{
			plugin = "plugins/freeemsplugin.lib";
		}
		else if (QFile::exists("plugins/libfreeemsplugin.a"))
		{
			plugin = "plugins/libfreeemsplugin.a";
		}
		else if (QFile::exists("plugins/freeemsplugin.dll"))
		{
			plugin = "plugins/freeemsplugin.dll";
		}
		else if (QFile::exists("../../../plugins/libfreeemsplugin.dylib"))
		{
			plugin = "../../../plugins/libfreeemsplugin.dylib";
		}
		else if (QFile::exists("/usr/share/yats/plugins/libfreeemsplugin.dylib"))
		{
			plugin = "/usr/share/yats/plugins/libfreeemsplugin.dylib";
		}
	}
	w->setPlugin(plugin);
	if (autoconnect)
	{
		w->connectToEms();
	}
	w->show();
	return a.exec();
}
Exemplo n.º 8
0
Arquivo: grep.c Projeto: kinroux/grep
int eGrep(int argc, char** argv){


	Arguments* args = getArgs(argc, argv);

	int return_val = 0;
	short int quit = 0;

	if (args == NULL)
	{
		printf("Invalid command.\n");
		return_val = 2;
		quit = 1;
	}

	if (!quit && !hasOption('q', args->options))
	{
		// Command display
		printf("grep");
		int i;
		for (i = 1; argv[i] != NULL; i++)
			printf(" %s", argv[i]);
		printf("\n");
		for (i = 0; i < 50; i++)
			printf("-");
		printf("\n");
		// ---

	}
	else
	{
#ifdef _WIN32
		system("cls");
#else
		system("clear");
#endif
	}
	if (!quit && args->options != NULL && (*(Options*)args->options->data).name == '-' && args->files == NULL && args->pattern == NULL)
	{
		printf(
					"Usage : grep [OPTION] ... PATTERN [FILE]...\n"
					"Search for PATTERN or standard input in each FILE\n"
					"PATTERN is, by default, a standard regular expression (BRE) i.e \"hello world\".\n"
					"\nRegex selection :\n"
					"\n-E, --extended-regexp\tPattern is an extended regular expression (ERE)\n"
					"\n-e, --regexp=PATTERN\tuse PATTERN for matching\n"
					"\n-f, --file=FILE\t\tObtain PATTERN from file, the content of FILE is\n\t\t\tconsidered as the PATTERN to look for\n"
					"\n-i, --ignore-case\tIgnore case distinction\n"
					"\n-w, --word-regexp\tForce PATTERN to match only whole words\n"
					"\n-x, --line-regexp\tForce PATTERN to match only whole line\n"
					"\n-z, --null-data\t\tData lines end in 0 byte instead of a newline\n"
					"\nMiscellaneous :\n"
					"\n-s, --no-messages\tSuppress error messages\n"
					"\n-v, --invert-match\tSelect non-matching lines (uncompatible with -o)\n"
					"\n    --help\t\tDisplay this help and exit\n"
					"\nOutput control :\n"
					"\n-m, --max-count=NUM\tStop searching in a file after NUM matching lines\n"
					"\n-b, --byte-offset\tPrint the byte offset for each output lines,\n"
					"\t\t\twhen combined with -o print the offset of the match\n"
					"\n-n, --line-number\tPrint line number with outuput lines (starts at 1)\n"
					"\n-H, --with-filename\tPrint the filename for each match (default when having\n\t\t\tmore than one FILE)\n"
					"\n-h, --no-filename\tSuppress the file name prefix on output (default when\n\t\t\thaving only one FILE)\n"
					"\n-o, --only-matching\tDisplays only the part of a line matching the pattern,\n"
					"\t\t\tin the case of multiple matches per line, displays\n\t\t\tas many lines as matches\n"
					"\t\t\tuncompatible with -v, -e and -E\n"
					"\n-q, --quiet, --silent\tSuppress all normal output\n"
					"\n-R, -r, --recursive\tSearch recursively in each files contained in FILE\n"
					"\n--include=GLOB\t\tSearch only files whose base name matches GLOB\n"
					"\n--exclude=GLOB\t\tSkip   files  whose  base  name  matches  GLOB\n"
					"\n--exclude-dir=DIR\tExclude directories matching  the  pattern  DIR\n\t\t\tfrom  recursive searches\n"
					"\n-L, --files-without-match Print only names of FILEs containing no match\n"
					"\n-l, --file-with-matches\tPrint only names of FILEs containing matches\n"
					"\n-c, --count\t\tprint only a count of matching lines per FILE\n"
					"\n-Z, --null\t\tPrint 0 byte after FILE name\n"
					"\nSpecial handling : if '-' is given as PATTERN, PATTERN become the standard input"
					"\nExit status :\n\n" 
					"0 if no results were found\n"
					"1 if at least one result was found\n"
					"2 if an error was given\n\n"
					

				);
		quit = 1;
	}

	if (!quit && args->options != NULL &&  (*(Options*)args->options->data).name == 'V' && args->files == NULL && args->pattern == NULL)
	{
		printf( 
				"Grep command revised :\n\n"
				"version : %d.%d.%d\n\n"
				"authors :\n\tBASSET Cyril\n\tLAMBERTI Jean-Vincent\n\tPICARD David\n\n"
				,GREP_STATUS,GREP_MAJOR_VERSION,GREP_MINOR_VERSION);
		quit = 1;
	}


	if(!quit && args->pattern == NULL)
	{
		if(!hasOption('s', args->options) && !hasOption('q', args->options))
			printf("Pattern not found.\n");
		return_val = 2;
		quit = 1;
	}

	if(!quit && (!args->files || !args->pattern))
		quit = 1;

	if (!quit)
	{
		if (args->files != NULL)
		{

			Maillon* lines = NULL;
			int file_count = 0;
			if(hasOption('r',args->options))
			{
				Maillon* files = NULL;
				Maillon* next = args->files;
				while(next != NULL)
				{
					getFileFrom((char*)next->data,&files,args->options);
					next = next->next;
				}
				lines = nFileLoader(files, hasOption('z',args->options));
				file_count = listSize(files);
			}
			else
			{
				lines = nFileLoader(args->files, hasOption('z',args->options));
				file_count = listSize(args->files);
			}

			if (lines != NULL)
			{
				Maillon* results = extractWithPattern(lines, args->pattern, args->options);
				if (!hasOption('q', args->options))
					displayFileLine(results, file_count, args);
				return_val = listSize(results) > 0 ? 0 : 1 ;
				//listSize(results)>0?return_val=0:return_val=1;
			}
		}
	}

	if (args != NULL)
	{
		//freeList(&(args->options));
		// Do not free pattern!!! It's the argv[i] address
		//freeList(&(args->files));
		FREE(args);
	}

	return return_val;
}
Exemplo n.º 9
0
int main(int argc, const char* argv[])
{
    MainClass mainInstance;
    mainInstance.Main(argc, getArgs(argc, argv));
    return 0;
}
Exemplo n.º 10
0
//----------------------------------------------------------------------
//  Main program
//----------------------------------------------------------------------
int nao_kmeans()
{
  ifstream importMeans; // permettra d'utiliser les centres enregistrés dans l'étape de training
  int nPts; // actual number of points

  getArgs();			// read command-line arguments

  term.setAbsMaxTotStage(stages);	// set number of stages

  // I- IMPORT STIPS
  nPts = 0;
  dim = STIPS_DIMENSION;
  KMdata dataPts(dim, maxPts);		// allocate data storage
  if (dataIn != NULL){
    laptevParser(*dataIn, dataPts, &nPts);
  }
  else{
      perror("Pas de données à lire !!!");
      return EXIT_FAILURE;
    }
  dataPts.setNPts(nPts);			// set actual number of pts
  dataPts.buildKcTree();			// build filtering structure

  // II- IMPORT TRAINING CENTERS
  KMfilterCenters ctrs(k, dataPts);		// allocate centers
  importMeans.open("/home/nao/data/activities_recognition/training.means", ios::in);
  if(importMeans != NULL){
    trainingMeansParser(importMeans,ctrs);
    importMeans.close();
  }
  else{
    cerr << "Error while importing Means" << endl;
    return 2;
  }

  // III- GET ASSIGNMENTS
  KMctrIdxArray closeCtr = new KMctrIdx[dataPts.getNPts()]; // dataPts = 1 label
  double* sqDist = new double[dataPts.getNPts()];
  ctrs.getAssignments(closeCtr, sqDist);

  // IV- BAG OF WORDS STEP
  // initialisation de l'histogramme
  int* bowHistogram = NULL;
  bowHistogram = new int[k];
  for(int centre = 0; centre<k; centre++)
    bowHistogram[centre]=0;
  // remplissage de l'histogramme
  for(int point = 0; point < nPts ; point++){
    bowHistogram[closeCtr[point]]++;
  }
  delete closeCtr;
  delete[] sqDist;
  // exportation dans le fichier "testing.bow" sous un format pouvant être lu par libSVM
  char* KMeansToBow = NULL;
  KMeansToBow = new char[(256+1)];
   sprintf(KMeansToBow,"%s","/home/nao/data/activities_recognition/stip"); //sprintf(KMeansToBow,"%s.bow",argv[1]);
  ofstream testingBow(KMeansToBow, ios::out | ios::trunc);  // ouverture en écriture avec effacement du fichier ouvert
  if(testingBow){
    testingBow << "0";
    for(int centre = 0; centre<k ; centre++){
      testingBow << " " << centre + 1 << ":" << bowHistogram[centre];
    }
    testingBow << endl;
    testingBow.close();
  }
  else
    cerr << "Impossible d'ouvrir le fichier erreur1" << endl;
  // affichage
  cout << "Bag Of Words histogram" << endl;
  for(int centre = 0; centre<k; centre++){
  cout << "Centre " << centre << ": ";
    for (int i = 0; i<bowHistogram[centre]; i++)
      cout << "*";
    cout << endl;
  }

  delete[] bowHistogram;

  //kmExit(0);
   cout << "[kmeans.cpp]delete[]" << endl;
}
Exemplo n.º 11
0
void scheduler_FIFO(){

	int i,j,k,timeout,pid,status;
	int * processes_running;
	PROG_T prog;
	char cmd[50];


	i = 0;

	p_sem();
		for(i=0;i<NUM_TAB;i++){
			if((pshm[i].nreq < 0)&&(pshm[i].status == FINISHED)){
				pshm[i].nreq = 0;
				p_sem2();
					/*printf("Liberando antes: %d\n",proc_livres);*/
					proc_livres += pshm[i].num_proc;
					/*printf("Liberando depois: %d\n",proc_livres);*/
				v_sem2();
			}else if((pshm[i].nreq > 0)&&(pshm[i].status == RUNNING)){
				timeout = checkTime(i);
				if(timeout){
					
					sprintf(cmd,"pkill -P %d",pshm[i].pid);
					system(cmd);
					kill(pshm[i].pid,SIGKILL);

					pshm[i].nreq = 0;
					pshm[i].status = FINISHED;
					p_sem2();
						proc_livres += pshm[i].num_proc;
					v_sem2();

				}
			}
		}
	v_sem();

	

	p_sem();

		i = chooseReq();
		
		if((pshm[i].nreq > 0)&&(pshm[i].status == PENDING)&&(pshm[i].num_proc <= proc_livres)){
			
			p_sem2();
			/*printf("Alocando antes: %d\n",proc_livres);*/
			proc_livres -= pshm[i].num_proc;
			/*printf("Alocando depois: %d\n",proc_livres);*/
			v_sem2();

			
			prog.n_params = countParams(pshm[i].proc);
			getArgs(pshm[i],&prog);
			pshm[i].status = RUNNING;

			pid = fork();
			if(pid<0){
				printf("Erro no fork dispatcher\n");
				exit(-1);
			}else if(!pid){
				/*Processo dispatcher*/
				processes_running = (int*)calloc(pshm[i].num_proc,sizeof(int));

				for(j=0;j<pshm[i].num_proc;j++){

					processes_running[j] = fork();
					if(processes_running[j] < 0){
						printf("Erro no fork worker\n");
						exit(-1);
					}else if(processes_running[j] == 0){
						/*Processos worker*/

						execv(prog.nome,prog.params);
					}else{
						/*Processo dispatcher*/

						for(k=0;k<pshm[i].num_proc;k++){
							wait(&status);
							if((k == pshm[i].num_proc-1)&&(j==pshm[i].num_proc-1)){
								pshm[i].status = FINISHED;
								pshm[i].nreq = -1;

								exit(0);
							}
						}
					}
				}
			}else{
				pshm[i].pid = pid;
			}
		}
		
	v_sem();


	for(i=0;i<NUM_TAB;i++){
		if(pshm[i].status == FINISHED){
			waitpid(pshm[i].pid,&status,WNOHANG);
		}
	}

}
Exemplo n.º 12
0
int main(int argc, char** argv)
{
	--argc;
	++argv;

	const int WIDTH = 800;
	const int HEIGHT = 600;

	/*
	*	Create window
	*/
	sf::RenderWindow window(sf::VideoMode(WIDTH, HEIGHT), "Window", sf::Style::Default, sf::ContextSettings(32));
	
	/*
	*	Initialize GLEW
	*/
	GLenum status = glewInit();
	if(status != GLEW_OK)
	{
		std::cerr << "[F] GLEW NOT INITIALIZED: ";
		std::cerr << glewGetErrorString(status) << std::endl;
	
		window.close();
	
		return -1;
	}

	/*
	*	Create GUI
	*/
	tgui::Gui gui(window);
	tgui::Gui gui2(window);
	gui.setGlobalFont("fonts/DejaVuSans.ttf");
	loadWidgets(gui, gui2, window);
	
	char* args[argc + 1];
	
	/*
	*	load geometry
	*/
	Model cube;
	getArgs(argc, argv, ".obj", args);
	
	if (!args[0])
	{
		std::cerr << "[F] MUST SUPPLY 1+ OBJ FILES IN COMMAND LINE ARGS <filename.obj>" << std::endl;
		exit(-1);
	} //if
	
	cube.mesh = loadMesh(args[0]);
	
	getArgs(argc, argv, ".scale", args);
	if (args[0])
	{
		cube.scale = glm::vec3(strtof(args[0], NULL));
	} //if
	else
	{
		cube.scale = glm::vec3(1.0f);
	} //else
	
	/*
	*	load shaders
	*/
	Shader vertexShader(GL_VERTEX_SHADER);
	getArgs(argc, argv, ".vs", args);
	vertexShader.loadFromFile(args[0]? args[0] : ".vs");
	vertexShader.compile();
	
	Shader fragmentShader(GL_FRAGMENT_SHADER);
	getArgs(argc, argv, ".fs", args);
	fragmentShader.loadFromFile(args[0]? args[0] : ".fs");
	fragmentShader.compile();
	
	/*
	*	create program
	*/
	ShaderProgram program;
	
	program.attachShader(vertexShader);
	program.attachShader(fragmentShader);
	program.linkProgram();
	
	program.addAttribute("vertexPosition_modelspace");
	program.addAttribute("vertexUV");
	//program.addAttribute("vertexNormal_modelspace");
	
	program.addUniform("MVP");
	program.addUniform("myTextureSampler");
	
	glEnable(GL_DEPTH_TEST);
	glDepthMask(GL_TRUE);
	glEnable(GL_CULL_FACE);
	glClearDepth(1.f);
	glShadeModel (GL_SMOOTH);
	
	glUniform1i(program.uniform("myTextureSampler"), 0);

	Camera camera;
	
	sf::Event event;
	tgui::Callback callback;
	
	Planet p(&cube);
	
	/*
	*	main loop
	*/
	
	while (window.isOpen())
	{
		while (window.pollEvent(event))
		{
			switch (event.type)
			{
				case sf::Event::Closed:
					window.close();
				
					break;
				case sf::Event::Resized:
					glViewport(0, 0, event.size.width, event.size.height);
					camera.projection = glm::perspective(45.0f, float(event.size.width)/float(event.size.height), 0.01f, 100.0f);
					
					break;
				default:
					break;
			} //switch
			
			gui.handleEvent(event);
		} //if
		
		while (gui.pollCallback(callback))
		{
			gui.handleEvent(event);
		} //if
		
		window.clear();
		guiDraw(window, gui2);
		glClear(GL_DEPTH_BUFFER_BIT); 
		
		/*
		*	render OpenGL here
		*/
		//glValidateProgram(program.program);
		
		for (Planet* planet : planets)
		{
			render(*planet, camera, program);
		} //for
		
		guiDraw(window, gui);
		
		window.display();
	} //while

	// Clean up after ourselves
	if (window.isOpen())
	{
		window.close();
	} //if
	
	return EXIT_SUCCESS;
} //main
Exemplo n.º 13
0
int main(int argc, char **argv) {
	int fd, addrlen, ret, newfd;
	int fdStat, nStat, nreadStat;
	int addrStatlen;
	struct sockaddr_in addrStat;
	int nread, nwritten, nbytes;
	struct sockaddr_in addr;
	char *ptr, buffer[BUFFER_SIZE], buffer2[BUFFER_SIZE];
	struct hostent *hostptr;
	int SMBport, STATport;
	char *STATname;
	char *userTokens;
	char reg[BUFFER_SIZE], udp[BUFFER_SIZE];
	struct in_addr* ip;
	char hostname[BUFFER_SIZE];

	getArgs(argc, argv, &SMBport, &STATname, &STATport);
	
	fdStat = socket(AF_INET, SOCK_DGRAM, 0);
	
	if(fdStat == -1) {
		fprintf(stderr, "ERROR: Couldn't create de UDP socket...\n");
		exit(1);
	}
	
	hostptr = gethostbyname(STATname);
	
	memset((void*)&addrStat, (int)'\0', sizeof(addrStat));
	addrStat.sin_family = AF_INET;
	addrStat.sin_addr.s_addr = ((struct in_addr*)(hostptr->h_addr_list[0]))->s_addr;
	addrStat.sin_port = htons(STATport);
	
	if(gethostname(hostname, BUFFER_SIZE)==-1) {
		fprintf(stderr, "ERROR: Couldn't send message to STAT...\n");
	    exit(1);
	}
	hostptr = gethostbyname(hostname);
	addrStatlen = sizeof(addrStat);
	ip = (struct in_addr*)(hostptr->h_addr_list[1]);
	if(ip == NULL) ip = (struct in_addr*)(hostptr->h_addr_list[0]);
	sprintf(reg, "OLA %s %d\n", inet_ntoa(*ip), SMBport);
	nStat = sendto(fdStat, reg, strlen(reg), 0, (struct sockaddr*)&addrStat, addrStatlen);
	
	if(nStat == -1) {
		fprintf(stderr, "ERROR: Couldn't send message to STAT...\n");
		exit(1);
	}
	
	nreadStat = recvfrom(fdStat, buffer, BUFFER_SIZE, 0, (struct sockaddr*)&addrStat, &addrStatlen);
	
	if(nreadStat == -1) {
		fprintf(stderr, "ERROR: Couldn't receive message from STAT...\n");
		exit(1);
	}
	
	printf("%s", buffer);
	
	if((fd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
		fprintf(stderr, "ERROR: Couldn't create de TCP socket...\n");
		exit(1);
	}
	
	memset((void*)&addr, (int)'\0', sizeof(addr));
	addr.sin_family = AF_INET;
	addr.sin_addr.s_addr = htonl(INADDR_ANY);
	addr.sin_port = htons(SMBport);
	
	ret = bind(fd, (struct sockaddr*)&addr, sizeof(addr));
	if(ret == -1) {
		fprintf(stderr, "ERROR: Couldn't bind socket...\n");
		exit(1);
	}
	
	if(listen(fd,5) == -1) {
		fprintf(stderr, "ERROR: Couldn't listen...\n");
		exit(1);
	}
	
	while(1) {
		addrlen = sizeof(addr);
		
		if((newfd = accept(fd, (struct sockaddr*)&addr, &addrlen)) == -1) {
			fprintf(stderr, "ERROR: Couldn't accept TCP connection...\n");
			exit(1);
		}

		nread = read(newfd, buffer, BUFFER_SIZE);
		
		if(nread == -1) {
			fprintf(stderr, "ERROR: Couldn't read message from User...\n");
			exit(1);
		}
		
		printf("%s", buffer);
		
		userTokens = strtok(buffer, " ");
		
		if(strcmp(userTokens, "REQ") == 0) {
			userTokens = strtok(NULL, " ");
			
			if(userTokens != NULL) {
				sprintf(reg, "OPOP %s %d %s\n", inet_ntoa(*ip), SMBport, userTokens);
				nStat = sendto(fdStat, reg, strlen(reg), 0, (struct sockaddr*)&addrStat, addrStatlen);
				
				if(nStat == -1) {
					fprintf(stderr, "ERROR: Couldn't send message to STAT...\n");
					exit(1);
				}

				printf("OK: sent msg to stat\n");
				
				memset(buffer2, '\0', sizeof(buffer2));
				nreadStat = recvfrom(fdStat, buffer2, BUFFER_SIZE, 0, (struct sockaddr*)&addrStat, &addrStatlen);

				if(nreadStat == -1) {
					fprintf(stderr, "ERROR: Couldn't receive message from STAT...\n");
					exit(1);
				}
				
				nwritten = write(newfd, buffer2, strlen(buffer2));
				if(nwritten == -1)
					exit(1);

				printf("%s", buffer2);
					
			} else {
				fprintf(stderr, "ERROR: message unknown...\n");
				ptr = strcpy(buffer, "KO\n");
				nwritten = write(newfd, ptr, strlen(ptr));
				if(nwritten == -1)
					exit(1);
			}
			
		} else {
			fprintf(stderr, "ERROR: message unknown...\n");
			ptr = strcpy(buffer, "KO\n");
			nwritten = write(newfd, ptr, strlen(ptr));
			if(nwritten == -1)
				exit(1);
		}
		
		close(newfd);
	}
	
	close(fd);
	exit(0);
}