Exemplo n.º 1
0
///
/// Extracts files from the given archive content.
///
/// @throws InvalidArchiveError when the archive is invalid.
///
Files Extractor::extract(const std::string& archiveContent) {
	initializeWith(archiveContent);
	readMagicString();
	readLookupTable();
	readFileNameTable();
	auto files = readFiles();
	return files;
}
Exemplo n.º 2
0
int readFiles( char *source, char *dest)
{
	long h, err;
	struct _finddata_t data;
	char *filename, *prevname, *destname;
	unsigned int failID;
	int failpos;
	lwReader reader;
	Lwo2MeshWriter lwo2mesh;
	
	filename = (char *)malloc(3 * 512);
	if ( !filename ) return 0;
	prevname = filename + 512;
	destname = filename + 1024;
	
	err = h = _findfirst( source, &data );
	if ( err == -1 )
	{
		printf( "No files found: '%s'\n", source );
		return 0;
	}
	
	while ( err != -1 )
	{
		if (( data.attrib & _A_SUBDIR ) && data.name[ 0 ] != '.' )
		{
			make_filespec( source, data.name, filename );
			readFiles( filename, dest );
		}
		if ( !( data.attrib & _A_SUBDIR ))
		{
			make_filename( source, data.name, filename );

			if ( !strcmp( filename, prevname )) break;
			strcpy( prevname, filename );
			failID = failpos = 0;

			lwObject *object = reader.readObjectFromFile( filename );
			if ( object )
			{
				if (flags[InfoOnly])
					info(object, filename);
				else
				{
					make_destname( dest, data.name, destname );
					lwo2mesh.writeLwo2Mesh(object, destname);
				}
				delete object;
			}
		}
		err = _findnext( h, &data );
	}
	
	_findclose( h );
	free (filename);
	return 1;
}
Exemplo n.º 3
0
static void readFiles( std::vector<File>& files, const char* fname )
{
	char cwd[2048];
	_getcwd( cwd, sizeof(cwd) );

	_finddata_t info;
	long handle = _findfirst( fname, &info );
	if ( -1 != handle )
	{
		File file;

		do
		{
			if ( info.name[0] != '.' )
			{
				file.name = info.name;
				file.path = cwd;

				printf( "Reading %s...\n", info.name );

				FILE* fh = fopen( info.name, "rb" );
				if ( fh )
				{
					fseek( fh, 0, SEEK_END );
					file.data.resize( ftell( fh ) );
					fseek( fh, 0, SEEK_SET );
					fread( file.data.begin(), 1, file.data.size(), fh );

					if ( !ferror(fh) )
						files.push_back( file );

					fclose( fh );
				}
			}

		} while ( 0 == _findnext(handle,&info) );
	}

	handle = _findfirst( "*", &info );
	if ( -1 != handle )
	{
		do
		{
			if ( 0 != (info.attrib & _A_SUBDIR) && info.name[0] != '.' )
			{
				if ( 0 == _chdir(info.name) )
				{
					printf( "Recursing to %s...\n", info.name );
					readFiles( files, fname );
					_chdir( cwd );
				}
			}
		} while ( 0 == _findnext(handle,&info) );
	}
}
Exemplo n.º 4
0
int main( int argc, char **argv ){
   struct options options;
   list_ref list = NULL;
   bzero( &options, sizeof options );
   set_progname( argv[0] );
   progname = argv[0];
   scanoptions( &options, argc, argv );
   list = new_list();
   readFiles(list, &options);
   editfile( &options, list );
   free_list( list ); list = NULL;
   return get_exitcode();
}
Exemplo n.º 5
0
void CollectionConfigReader::readGenerate()
{
    while (!atEnd()) {
        readNext();
        if (isStartElement()) {
            if (name() == QLatin1String("file"))
                readFiles();
            else
                raiseErrorWithLine();
        } else if (isEndElement() && name() == QLatin1String("generate")) {
            break;
        }
    }
}
Exemplo n.º 6
0
static void* fileReadingThread(void *arg)
{
  fileReadThreadInitialized = 1;
 
  for(;;)
  {
    usleep(100000);
    printf("readingLoop\n"); 
    openPendingFiles();
    readFiles();
  }

  return NULL;
}
Exemplo n.º 7
0
int main(void) {
    setvbuf(stdout, NULL, _IONBF, 0);
    char myName[MAX_NAME_TOTAL][MAX_NAME_LENGTH];
    int myRank[MAX_NAME_TOTAL][MAX_RANK_LENGTH];
    init(myName, myRank);
    char fileNames[MAX_FILE][MAX_NAME_LENGTH] = {{"yob1920.txt"}, {"yob1930.txt"}, {"yob1940.txt"},
        {"yob1950.txt"}, {"yob1960.txt"}, {"yob1970.txt"}, {"yob1980.txt"}, {"yob1990.txt"},
        {"yob2000.txt"}, {"yob2010.txt"}
    };
    readFiles(*fileNames,myName, myRank);
    sort(myName, myRank);
    createOutput(myName, myRank);

    return 0;
}
Exemplo n.º 8
0
void StateManager::runCommand(const std::string &command, const std::string &arguments) {
  assert(m_initialised);
  if (command == CMD_LOAD_STATE_CONFIG) {
    std::string a = arguments;
    m_state_configs.push_back(a);
    System::instance()->getFileHandler()->getFilePath(a);
    readFiles(a);
  }
  else if (command == CMD_reload_config_states) {
    // Destroy current display lists
    contextDestroyed(true);
    // We can safely re-read the config files to overwrite existing data
    // This only breaks if the config file does no specify all fields
    std::list<std::string>::const_iterator I = m_state_configs.begin();
    std::list<std::string>::const_iterator Iend = m_state_configs.end();
    while (I != Iend) {
      std::string args_cpy = *I++;
      System::instance()->getFileHandler()->getFilePath(args_cpy);
      readFiles(args_cpy);
    }

    contextCreated();
  }
}
Exemplo n.º 9
0
int main(int argc,char** argv){
  if(argc < 4 || argc > 5)
    return 1;

  int verbose = 0;
  Matrices m;

  int i = 0;
  for( i = 0 ; i < argc ; i++){
    if(strcmp(argv[i],"-p") == 0)
      verbose = 1;
    if(strcmp(argv[i],"-f") == 0){
      if( argc - i < 3){
        printf("You have to specify two files\n");
        return 1;
      }
      else{
	      readFiles(argv[i+1],argv[i+2],&m);
        i+=2;
      }
    }
  }

#ifdef conventionnel
  //multiplyMatrix(&m);
  strassen(&m);
#endif
#ifdef conventionnelT
	multiplyMatrixT(&m);
#endif
  if(verbose){
  for( i = 0 ; i < m.size*m.size; i++){
	 	printf("%d\t",m.result[i]);
	 	if(i%m.size == m.size - 1)
	  	printf("\n");
 	  }
  }
  free(m.a);
  free(m.b);
  free(m.result);
	return 0;
}
Exemplo n.º 10
0
void QHelpProjectDataPrivate::readFilterSection()
{
    filterSectionList.append(QHelpDataFilterSection());
    while (!atEnd()) {
        readNext();
        if (isStartElement()) {
            if (name() == QLatin1String("filterAttribute"))
                filterSectionList.last().addFilterAttribute(readElementText());
            else if (name() == QLatin1String("toc"))
                readTOC();
            else if (name() == QLatin1String("keywords"))
                readKeywords();
            else if (name() == QLatin1String("files"))
                readFiles();
            else
                raiseUnknownTokenError();
        } else if (isEndElement() && name() == QLatin1String("filterSection")) {
            break;
        }
    }
}
Exemplo n.º 11
0
//------------------------------------------------------------------------------------
// function to load all images in a given folder
//------------------------------------------------------------------------------------
vector<string> dir::readImages(LPCSTR path)
{
	string Path(path);
	if(Path[Path.size()-1]!='\\')
		Path.push_back('\\');

	vector<string> filelist;
	LPCSTR imgformats[4]={"*.jpg","*.jpeg","*.bmp","*.png"};//,L"*.gif"};
	for(int  i=0;i<4;i++)
	{
		vector<string> templist;
		string search(Path);
		search+= imgformats[i];
		//wcout<<search.data() <<endl;
		templist = readFiles(search.data());
		
		for(int j = 0;j<templist.size(); j++)
			filelist.push_back(templist[j]);
	}
	return filelist;
}
Exemplo n.º 12
0
/** Parses the in.file to get the name of all the input files */
PROCESS *parseFiles(char *fname) {
    //attempt to open file
    FILE *fp;
    if ((fp = fopen(fname,"r")) == NULL) {
        char error[BUFSIZ];
        sprintf(error,"Error opening %s",fname);
        perror(error);
        usage();
        exit(0);
    } else {
        files = (char**) realloc(files,(nfiles+1)*sizeof(char*));
        //files = malloc(BUFSIZ*sizeof(char*));
        if (files == NULL) {
            perror("Cannot allocate to files");
            exit(0);
        }
        //Parsing all the filenames.
        char* strCheck;
        char line[BUFSIZ];
        while (INFILE(fp) && (strCheck = fgets(line,sizeof line,fp)) != NULL ) {
            files = realloc(files,(nfiles+1)*sizeof(char*)); //Yes, C99 prefers you use void pointers.
            //TODO: what about an empty line?
            trimLine(line);
            files[nfiles] = malloc(sizeof line);
            if (files[nfiles] == NULL) {
                perror("Cannot allocate space for file name");
                exit(0);
            }
            strcpy(files[nfiles],line);
            ++nfiles;
        }
    }
    fclose(fp);

    return readFiles();
}
Exemplo n.º 13
0
int main( int argc, char* argv[] )
{
	char cwd[2048];
	_getcwd( cwd, sizeof(cwd) );

	// zar <opt> <dir>
	if ( argc != 4 )
	{
		printf( "Usage:\n"
			"archive:   zar -a <name> <dir>\n"
			"unarchive: zar -x <name> <dir>\n"
			"remove:    zar -d <name> <filelist>\n" );
		return 0;
	}
	const char* opt		= argv[1];
	const char* name	= argv[2];
	const char* dir		= argv[3];

	if ( std::string(opt) == "-a" )
	{
		// read files
		std::vector<File> files;
		if ( -1 != _chdir(dir) )
		{
			printf( "Processing %s...\n", dir );
			readFiles( files, "*.*" );
		}
		else
		{
			printf( "Path %s not found\n", dir );
		}
		_chdir( cwd );

		// check for duplicate file names
		int i;
		for ( i = 0 ; i < (int)files.size() ; ++i )
		{
			for ( int j = i+1 ; j < (int)files.size() ; ++j )
			{
				if ( files[i].name == files[j].name )
				{
					printf( "Warning: Two files have identical names (%s). Paths:\n", files[i].name.c_str() );
					printf( "%s\n", files[i].path.c_str() );
					printf( "%s\n", files[j].path.c_str() );
					printf( "Removing %s/%s...\n", files[j].path.c_str(), files[j].name.c_str() );
					files.erase( files.begin()+j );
					--j;
				}
			}
		}

		// write zip
		printf( "Writing %s...\n", name );
		gzFile zip = gzopen( name, "wb" );
		writeInt( zip, files.size() );
		for ( i = 0 ; i < (int)files.size() ; ++i )
		{
			File& file = files[i];
			writeString( zip, file.name.c_str() );
			writeBytes( zip, file.data.begin(), file.data.size() );
		}
		gzclose( zip );
	}
	else if ( std::string(opt) == "-x" )
	{
		// read zip
		printf( "Reading %s...\n", name );
		gzFile zip = gzopen( name, "rb" );
		if ( !zip )
		{
			printf( "Failed to open %s.", name );
			return 1;
		}
		std::vector<File> files;
		int count = readInt( zip );
		files.resize( count );
		for ( int i = 0 ; i < count ; ++i )
		{
			File& file = files[i];
			readString( zip, file.name );
			readBytes( zip, file.data );
		}
		gzclose( zip );

		// write files
		if ( -1 != _chdir(dir) )
		{
			for ( int i = 0 ; i < (int)files.size() ; ++i )
			{
				File& file = files[i];
				printf( "Writing %s...\n", file.name.c_str() );
				FILE* fh = fopen( file.name.c_str(), "wb" );
				if ( fh )
				{
					fwrite( file.data.begin(), 1, file.data.size(), fh );
					fclose( fh );
				}
				else
				{
					printf( "Cannot write to file: %s\n", file.name.c_str() );
				}
			}
		}
		else
		{
			printf( "Path %s not found\n", dir );
		}

		_chdir( cwd );
	}
	else if ( std::string(opt) == "-d" )
	{
		// read zip
		printf( "Reading %s...\n", name );
		gzFile zip = gzopen( name, "rb" );
		if ( !zip )
		{
			printf( "Failed to open %s.", name );
			return 1;
		}
		std::vector<File> files;
		int count = readInt( zip );
		files.resize( count );
		for ( int i = 0 ; i < count ; ++i )
		{
			File& file = files[i];
			readString( zip, file.name );
			readBytes( zip, file.data );
		}
		gzclose( zip );

		// read file list
		printf( "Reading list %s...\n", dir );
		FILE* fh = fopen( dir, "rt" );
		if ( !fh )
		{
			printf( "File list not found: %s\n", dir );
			return 1;
		}
		std::vector<std::string> filelist;
		char buf[2048];
		while ( !feof(fh) )
		{
			if ( 1 != fscanf(fh,"%s",buf) )
				break;
			filelist.push_back( buf );
		}

		// remove listed files
		for ( int i = 0 ; i < (int)filelist.size() ; ++i )
		{
			std::string str = filelist[i];
			for ( int j = 0 ; j < (int)files.size() ; ++j )
			{
				if ( files[j].name == str )
				{
					files.erase( files.begin()+j );
					--j;
				}
			}
		}

		// write zip
		printf( "Writing %s...\n", name );
		zip = gzopen( name, "wb" );
		writeInt( zip, files.size() );
		for ( int i = 0 ; i < (int)files.size() ; ++i )
		{
			File& file = files[i];
			writeString( zip, file.name.c_str() );
			writeBytes( zip, file.data.begin(), file.data.size() );
		}
		gzclose( zip );
	}
	else
	{
		printf( "Invalid option: %s\n", opt );
	}

	return 0;
}
Exemplo n.º 14
0
int ChimeraPerseusCommand::execute(){
	try{
		if (abort == true) { if (calledHelp) { return 0; }  return 2;	}
		
				
		//process each file
		for (int s = 0; s < fastaFileNames.size(); s++) {
			
			m->mothurOut("Checking sequences from " + fastaFileNames[s] + " ..." ); m->mothurOutEndLine();
			
			int start = time(NULL);	
			if (outputDir == "") { outputDir = m->hasPath(fastaFileNames[s]);  }//if user entered a file with a path then preserve it				
			string outputFileName = outputDir + m->getRootName(m->getSimpleName(fastaFileNames[s])) + "perseus.chimera";
			string accnosFileName = outputDir + m->getRootName(m->getSimpleName(fastaFileNames[s]))  + "perseus.accnos";
			//string newFasta = m->getRootName(fastaFileNames[s]) + "temp";
			
			//you provided a groupfile
			string groupFile = "";
			if (groupFileNames.size() != 0) { groupFile = groupFileNames[s]; }
			
			string nameFile = "";
			if (nameFileNames.size() != 0) { //you provided a namefile and we don't need to create one
				nameFile = nameFileNames[s];
			}else { nameFile = getNamesFile(fastaFileNames[s]); }
			
			if (m->control_pressed) {  for (int j = 0; j < outputNames.size(); j++) {	m->mothurRemove(outputNames[j]);	} return 0;	}				
			
			int numSeqs = 0;
			int numChimeras = 0;
			
			if (groupFile != "") {
				//Parse sequences by group
				SequenceParser parser(groupFile, fastaFileNames[s], nameFile);
				vector<string> groups = parser.getNamesOfGroups();
				
				if (m->control_pressed) { for (int j = 0; j < outputNames.size(); j++) {	m->mothurRemove(outputNames[j]);	}  return 0; }
				
				//clears files
				ofstream out, out1, out2;
				m->openOutputFile(outputFileName, out); out.close(); 
				m->openOutputFile(accnosFileName, out1); out1.close();
				
				if(processors == 1)	{	numSeqs = driverGroups(parser, outputFileName, accnosFileName, 0, groups.size(), groups);	}
				else				{	numSeqs = createProcessesGroups(parser, outputFileName, accnosFileName, groups, groupFile, fastaFileNames[s], nameFile);			}
				
				if (m->control_pressed) {  for (int j = 0; j < outputNames.size(); j++) {	m->mothurRemove(outputNames[j]);	}  return 0;	}				
				
				numChimeras = deconvoluteResults(parser, outputFileName, accnosFileName);
				
				m->mothurOut("The number of sequences checked may be larger than the number of unique sequences because some sequences are found in several samples."); m->mothurOutEndLine(); 
				
				if (m->control_pressed) {  for (int j = 0; j < outputNames.size(); j++) {	m->mothurRemove(outputNames[j]);	}  return 0;	}				
				
			}else{
				if (processors != 1) { m->mothurOut("Without a groupfile, mothur can only use 1 processor, continuing."); m->mothurOutEndLine(); processors = 1; }
				
				//read sequences and store sorted by frequency
				vector<seqData> sequences = readFiles(fastaFileNames[s], nameFile);
				
				if (m->control_pressed) { for (int j = 0; j < outputNames.size(); j++) {	m->mothurRemove(outputNames[j]);	} return 0; }
				
				numSeqs = driver(outputFileName, sequences, accnosFileName, numChimeras); 
			}
			
			if (m->control_pressed) { for (int j = 0; j < outputNames.size(); j++) {	m->mothurRemove(outputNames[j]);	} return 0; }
			
			m->mothurOutEndLine(); m->mothurOut("It took " + toString(time(NULL) - start) + " secs to check " + toString(numSeqs) + " sequences. " + toString(numChimeras) + " chimeras were found.");	m->mothurOutEndLine();
			outputNames.push_back(outputFileName); outputTypes["chimera"].push_back(outputFileName);
			outputNames.push_back(accnosFileName); outputTypes["accnos"].push_back(accnosFileName);
		}
		
		//set accnos file as new current accnosfile
		string current = "";
		itTypes = outputTypes.find("accnos");
		if (itTypes != outputTypes.end()) {
			if ((itTypes->second).size() != 0) { current = (itTypes->second)[0]; m->setAccnosFile(current); }
		}
		
		m->mothurOutEndLine();
		m->mothurOut("Output File Names: "); m->mothurOutEndLine();
		for (int i = 0; i < outputNames.size(); i++) {	m->mothurOut(outputNames[i]); m->mothurOutEndLine();	}	
		m->mothurOutEndLine();
		
		return 0;
		
	}
	catch(exception& e) {
		m->errorOut(e, "ChimeraPerseusCommand", "execute");
		exit(1);
	}
}
Exemplo n.º 15
0
int main(int argc, char *argv[])
{
	if (argc != 3) {
		perror("usage: manager topologyfile messagefile"); 
	}
	router_addr = (struct sockaddr_storage *) malloc(sizeof(struct sockaddr_storage) * 16);
	for (int i = 0; i < 16; i ++) {
	  online[i] = false;
	  exist[i] = false;
	}
	int sockfd;
	struct addrinfo hints, *servinfo, *p;
	int rv;
	int numbytes;
	struct sockaddr_storage their_addr;
	char buf[MAXBUFLEN];
	socklen_t addr_len;
	char s[INET6_ADDRSTRLEN];

	memset(&hints, 0, sizeof hints);
	hints.ai_family = AF_UNSPEC; // set to AF_INET to force IPv4
	hints.ai_socktype = SOCK_DGRAM;
	hints.ai_flags = AI_PASSIVE; // use my IP

	if ((rv = getaddrinfo(NULL, MYPORT, &hints, &servinfo)) != 0) {
		fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv));
		return 1;
	}

	// loop through all the results and bind to the first we can
	for(p = servinfo; p != NULL; p = p->ai_next) {
		if ((sockfd = socket(p->ai_family, p->ai_socktype,
				p->ai_protocol)) == -1) {
			perror("manager: socket");
			continue;
		}

		if (bind(sockfd, p->ai_addr, p->ai_addrlen) == -1) {
			close(sockfd);
			perror("manager: bind");
			continue;
		}

		break;
	}

	if (p == NULL) {
		fprintf(stderr, "manager: failed to bind socket\n");
		return 2;
	}

	freeaddrinfo(servinfo);

	
	
	readFiles(argv[1], argv[2]);
	
	//start to build topology
	addr_len = sizeof (router_addr[0]);
	int id;
	int terminator = 77;
	
	//char adjacent[16];
	//int pos = 0;
	for (int i = 0; i < numNode; i ++) {
	        id = i + 1;
	        if ((numbytes = recvfrom(sockfd, buf, MAXBUFLEN-1 , 0,
					 (struct sockaddr *) &(router_addr[id-1]), &addr_len)) == -1) {
			perror("recvfrom");
			exit(1);
		}
		
		//send node ID to node and set it to online
		online[id-1] = true;
		
		if (numbytes = sendto(sockfd, &id, sizeof(id), 0,
				      (struct sockaddr *) &(router_addr[id - 1]), sizeof(router_addr[id - 1])) == -1) {
			perror("sendto");
			exit(1);
		}
		    printf("set new node with ID %d\n", id);
		
		//send adjacent node information to nodes
		int adjacentnum = 0;
		for (int i = 0; i < 16; i ++) {
			if (exist[i] && topology[i][id-1] > 0 && i != id - 1) {
				adjacentnum ++;
			}
		}

	       	if (numbytes = sendto(sockfd, &numNode, sizeof(int), 0,
				      (struct sockaddr *)  &(router_addr[id-1]), sizeof(router_addr[id-1])) == -1) {
       		       	perror("sendto");
	 	       	exit(1);
		}

	       if (numbytes = sendto(sockfd, &adjacentnum, sizeof(int), 0,
				     (struct sockaddr *)  &(router_addr[id-1]), sizeof(router_addr[id-1])) == -1) {
       		       	perror("sendto");
	      	       	exit(1);
		}
		
		
		    printf("start sending node %d its neignbor information\n", id);
		struct adjacent_node n;
		
		for (int i = 0; i < 16; i ++) {
			if (exist[i] && topology[i][id-1] > 0 && i != id - 1) {
				
				//set adjacent node values
				n.id = i + 1;
				if(online[i]) {
				  memcpy(&(n.router_addr),&(router_addr[i]), sizeof(struct sockaddr_storage));
					n.online = true;
				}
				else {
				  //	n.router_addr = NULL;
					n.online = false;
				}
				n.cost = topology[i][id-1];
				
				//send adjacent node value information to nodes
				if (numbytes = sendto(sockfd, &n, sizeof(n), 0,
						      (struct sockaddr *)    &(router_addr[id-1]), sizeof(router_addr[id-1])) == -1) {
					perror("sendto");
					exit(1);
				}
			}
		}
			printf("finish sending neighbor information\n");
		
		       
		//if a new node is online, should send this update to all adjacent nodes that are already online
		
		n.id = id;
		n.online = true;
		//	n.router_addr = router_addr[id-1];
		 memcpy(&(n.router_addr),&(router_addr[id-1]), sizeof(struct sockaddr_storage));
		for (int i = 0; i < 16 ; i ++) {
			if(exist[i] && topology[i][id-1] > 0 && i != id-1 && online[i]) {
			  //n.cost = topology[i][id-1];
			  if (numbytes = sendto(sockfd, &id, sizeof(id), 0, (struct sockaddr *) &(router_addr[i]), sizeof(router_addr[i])) == -1) {
			    perror("sendto");
			    exit(1);
			  }
			  if (numbytes = sendto(sockfd, &(router_addr[id-1]), sizeof(router_addr[id-1]), 0, (struct sockaddr *) &(router_addr[i]), sizeof(router_addr[i])) == -1) {
			    perror("sendto");
			    exit(1);
			  }
			  
				/*
				if (numbytes = sendto(sockfd, &n, sizeof(n), 0,
						      (struct sockaddr *) &(router_addr[i]), sizeof(router_addr[i])) == -1) {
					perror("sendto");
					exit(1);
				}
				*/
			}
		}
	
		/*
		if ((numbytes = sendto(sockfd, &terminator, sizeof(terminator), 0,
			router_addr[id-1], sizeof(router_addr[id-1])) == -1) {
			perror("sendto");
			exit(1);
		}
		*/
		
		
	}
		  printf("All nodes are online now!\n");
		  
	//broadcast information that all nodes are online
	
	char temp[2];
	temp[0] = 's';
	temp[1] = '\0';
	for (int i = 0; i < 16; i ++) {
		if(exist[i] && online[i]) {
			if (numbytes = sendto(sockfd, temp, sizeof(temp), 0,
					      (struct sockaddr *)    &(router_addr[i]), sizeof(router_addr[i])) == -1) {
			perror("sendto");
			exit(1);
			}	
		}
	}
	
	//wait for all nodes to announce convergence
	int finished = 0;
	temp[0] = 'f';
	temp[1] = '\0';
	while (finished != numNode) {
	if ((numbytes = recvfrom(sockfd, buf, MAXBUFLEN-1 , 0,
			(struct sockaddr *)&their_addr, &addr_len)) == -1) {
			perror("recvfrom");
			exit(1);
		}
	
	if(!strcmp(temp, buf)) finished ++;
	
	}
	
	//send messgae information to corresponding nodes
	sendMessages(sockfd);
	
	update(sockfd);
	
	close(sockfd);

	return 0;
}
Exemplo n.º 16
0
int main( int argc, char *argv[] )
{
	int i = 1;
	unsigned int ndistances = 0;
	Real distance = 0;
	char *source = 0;
	char *dest = 0;

	if ( argc < 2 ) help(argv[0]);

	while (i < argc)
	{
		if (argv[i][0] == '-' || argv[i][0] == '/')
		{
			switch (argv[i++][1])
			{
			case 'd':
			case 'D':
				i--;
				flags[GenerateLOD] = true;
				switch (argv[i++][2])
				{
				case 'f':
				case 'F':
					flags[UseFixedMethod] = true;
					break;
				case 'p':
				case 'P':
					flags[UseFixedMethod] = false;
					break;
				default:
					help(argv[0]);
				}
				try
				{
					reduction = atof(argv[i++]);
					ndistances = atoi(argv[i++]);
					while (ndistances > 0)
					{
						if (i < argc && argv[i][0] != '-' && argv[i][0] != '/')
							distanceList.push_back(atof(argv[i++]));									
						else
							ndistances = 0;
						ndistances--;
					}
				}
				catch (Exception *e)
				{
					ndistances = 0;
					distanceList.clear();
					flags[GenerateLOD] = false;
				}
				break;
			case 'g':
			case 'G':
				flags[UseSharedVertexData] = false;
				break;
			case 'i':
			case 'I':
				flags[InfoOnly] = true;
				break;
			case 'l':
			case 'L':
				flags[UseSeparateLayers] = true;
				break;
			case 'm':
			case 'M':
				flags[ExportMaterials] = false;
				break;
			case 'r':
			case 'R':
				flags[RenameMaterials] = true;
				if (strlen(argv[i-1]) > 2) {
					i--;
					switch (argv[i++][2])
					{
					case 'i':
					case 'I':
						flags[UseInteractiveMethod] = true;
						break;
					case 'o':
					case 'O':
						flags[UseObjectMethod] = true; // default
						break;
					case 'p':
					case 'P':
						flags[UsePrefixMethod] = true;
						if (argv[i][0] != '-' && argv[i][0] != '/')
							matPrefix = argv[i++];
						else
							help(argv[0]);
						break;
					default:
						help(argv[0]);
					}
				}
				break;
			case 's':
			case 'S':
				flags[ExportSkeleton] = false;
				break;
			case 'v':
			case 'V':
				flags[PrintVMaps] = true;
				break;
			default:
				help(argv[0]);
			}
		}
		else
		{
			if (!source) source = argv[i];
			else
				if (!dest) dest = argv[i];
			i++;
		}
	}

	if ( !source ) help(argv[0]);

	if (!dest) dest = "\0";

	float t1, t2;
	
	t1 = ( float ) clock() / CLOCKS_PER_SEC;

	if (!flags[InfoOnly])
	{
		logMgr = new LogManager();
		logMgr->createLog("lwo2mesh.log", true);
		resourceGroupMgr = new ResourceGroupManager();
		mth = new Math();
		matMgr = new MaterialManager();
		matMgr->initialise();
		meshMgr  = new MeshManager();
		skelMgr = new SkeletonManager();
		meshSerializer = new MeshSerializer();
		materialSerializer = new MaterialSerializer();
		skeletonSerializer = new SkeletonSerializer();
		bufferMgr = new DefaultHardwareBufferManager(); // needed because we don't have a rendersystem
	}

	if ( strchr(source, '*') ) 
		// On Linux this will only be called if you pass the source argument in
		// quotation marks (e.g. as LightwaveConverter "abc..*" ). Otherwise the
		// shell will expand the arguments. At least, this is how it works with
		// bash.
		readFiles( source, dest );
	else
	{
		lwReader reader;
		lwObject *object = reader.readObjectFromFile(source);
		if ( object )
		{
			if (flags[InfoOnly])
				info(object, source);
			else
			{
				char *destname = (char *)malloc(512);
				if ( !destname ) return 1;

				if (strlen(dest))
					make_destname(dest, dest, destname);
				else
					make_destname(dest, source, destname);

				Lwo2MeshWriter lwo2mesh;
				lwo2mesh.writeLwo2Mesh(object, destname);
				free(destname);
			}
			delete object;
		}
	}

	t2 = ( float ) clock() / CLOCKS_PER_SEC - t1;
	
	if (flags[InfoOnly])
	{
		cout << "Total:" << nl
			<< setw(8) << nobjects << " objects" << nl
			<< setw(8) << nlayers << " layers" << nl
			<< setw(8) << nsurfs << " surfaces" << nl
			<< setw(8) << nclips << " clips" << nl
			<< setw(8) << nenvs << " envelopes" << nl
			<< setw(8) << npoints << " points" << nl
			<< setw(8) << npolygons << " polygons" << nl
			<< setw(8) << t2 << " seconds processing time." << endl;
	}
	else
	{
		delete bufferMgr;
		delete skeletonSerializer;
		delete materialSerializer;
		delete meshSerializer;
		delete meshMgr;
		delete skelMgr;
		delete matMgr;
		delete mth;
		delete resourceGroupMgr;
		delete logMgr;
	}

	return 0;
	
}
Exemplo n.º 17
0
DataLayer *ConfigurationParser::readLayer()
{
    Q_ASSERT(isStartElement()
              && name() == "layer");

    DataLayer *layer = new DataLayer();
    ColorMap colorMap;
    
    QColor c;
    c.setHsv(240, 255, 189, 255);
    colorMap.addColor(c);
    c.setHsv(240, 255, 255, 255);
    colorMap.addColor(c);
    c.setHsv(224, 255, 255, 255);
    colorMap.addColor(c);
    c.setHsv(208, 255, 255, 255);
    colorMap.addColor(c);
    c.setHsv(195, 255, 255, 255);
    colorMap.addColor(c);
    c.setHsv(180, 255, 255, 255);
    colorMap.addColor(c);
    c.setHsv(159, 189, 255, 255);
    colorMap.addColor(c);
    c.setHsv(120, 123, 255, 255);
    colorMap.addColor(c);
    c.setHsv(80, 189, 255, 255);
    colorMap.addColor(c);
    c.setHsv(60, 255, 255, 255);
    colorMap.addColor(c);
    c.setHsv(44, 255, 255, 255);
    colorMap.addColor(c);
    c.setHsv(15, 255, 255, 255);
    colorMap.addColor(c);
    c.setHsv(0, 255, 255, 255);
    colorMap.addColor(c);
    c.setHsv(0, 255, 189, 255);
    colorMap.addColor(c);
    c.setHsv(0, 255, 132, 255);
    colorMap.addColor(c);
    colorMap.setInterpolationSpec(QColor::Hsv);

    while(!atEnd()) {
        readNext();

        if(isEndElement())
            break;

        if(isStartElement()) {
            if(name() == "file") {
                QXmlStreamAttributes att = attributes();
                QDateTime dateTime;
                dateTime.setTime(QTime::fromString(att.value("time").toString(), Qt::ISODate));
                dateTime.setDate(QDate::fromString(att.value("date").toString(), Qt::ISODate));
                layer->setFileName(dateTime, readCharacters());
                qDebug() << "Added file for time:" << dateTime;
            }
            else if(name() == "files") {
                readFiles(layer);
            }
            else if(name() == "name") {
                layer->setName(readCharacters());
                qDebug() << "Name:" << layer->name();
            }
            else if(name() == "geometry") {
                QString geometryName = readCharacters();
                
                QHash<QString,MapGeometry>::iterator it = m_geometries.find(geometryName);
                if(it != m_geometries.end()) {
                    layer->setGeometry(it.value());
                }
                else {
                    delete layer;
                    qDebug() << "Geometry not found.";
                    return 0;
                }
            }
            else if(name() == "scaleMin") {
                layer->setScaleMin(readCharacters().toDouble());
            }
            else if(name() == "scaleMax") {
                layer->setScaleMax(readCharacters().toDouble());
            }
            else if(name() == "defaultColorMap") {
                QString colorMapString = readCharacters();
                if(m_colorMaps.contains(colorMapString)) {
                    colorMap = m_colorMaps.value(colorMapString);
                }
            }
            else {
                readUnknownElement();
            }
        }
    }

    layer->setDefaultColorMap(colorMap);
    return layer;
}
Exemplo n.º 18
0
void tickMenu(int menu){
    switch(menu){
        case MENU_SETTINGS:
        if(!bindOpt){
            if(!selBut){
		        if (k_up.clicked){ --currentSelection; if(currentSelection < 0)currentSelection=21;}
		        if (k_down.clicked){ ++currentSelection; if(currentSelection > 21)currentSelection=0;}
		        if (k_left.clicked){ left = true;}
		        if (k_right.clicked){ left = false;}
            } else {
                if (k_left.clicked){ 
                    if(left)switchGameBut(true,keys[currentSelection]);
                    else switchMenuBut(true,keys[currentSelection]);
                } else if (k_right.clicked) { 
                    if(left)switchGameBut(false,keys[currentSelection]);
                    else switchMenuBut(false,keys[currentSelection]);
                }
            }
		    
            if (k_accept.clicked) selBut = !selBut;
            if (k_decline.clicked){ 
                bindOpt = true;
                curSaveSel = 0;
            }
        } else {
		    if (k_up.clicked){ --curSaveSel; if(curSaveSel < 0)curSaveSel=2;}
		    if (k_down.clicked){ ++curSaveSel; if(curSaveSel > 2)curSaveSel=0;}
            if (k_decline.clicked){ 
                bindOpt = false;
                errorBut = -1;
            }
            if (k_accept.clicked){
                switch(curSaveSel){
                    case 0: // Exit and save  
                        if(checkPropButtons() == -1){
                            k_up.input = keyProp[0];
                            k_down.input = keyProp[1];
                            k_left.input = keyProp[2];
                            k_right.input = keyProp[3];
                            k_attack.input = keyProp[4];
                            k_menu.input = keyProp[5];
                            k_pause.input = keyProp[6];
                            k_accept.input = keyProp[7];
                            k_decline.input = keyProp[8];
                            k_delete.input = keyProp[9];
                            
                            FILE *fs=fopen("btnSave.bin","wb");
                            fwrite(keyProp,sizeof(int),9,fs);
                            fclose(fs);
                            
                            currentSelection = 2;
                            currentMenu = MENU_TITLE;
                            errorBut = -1;
                        } else errorBut = checkPropButtons();
                        break;
                    case 1: // Exit and DON'T save  
                        currentSelection = 2;
                        currentMenu = MENU_TITLE;
                        errorBut = -1;
                        break;
                    case 2: // reset defaults
	                    keyProp[0] = KEY_DUP | KEY_CPAD_UP | KEY_CSTICK_UP;
	                    keyProp[1] = KEY_DDOWN | KEY_CPAD_DOWN | KEY_CSTICK_DOWN;
	                    keyProp[2] = KEY_DLEFT | KEY_CPAD_LEFT | KEY_CSTICK_LEFT;
	                    keyProp[3] = KEY_DRIGHT | KEY_CPAD_RIGHT | KEY_CSTICK_RIGHT;
	                    keyProp[4] = KEY_A | KEY_B | KEY_L | KEY_ZR;
	                    keyProp[5] = KEY_X | KEY_Y | KEY_R | KEY_ZL;
	                    keyProp[6] = KEY_START;
                        keyProp[7] = KEY_A;
                        keyProp[8] = KEY_B;
                        keyProp[9] = KEY_X;
	                    bindOpt = false;
                        errorBut = -1;
                        break;
                    }
                }
            }
        break;
        case MENU_PAUSED:
            if(!areYouSure && !areYouSureSave){
                if(pauseSaveDisplayTimer > 0) --pauseSaveDisplayTimer;
                if (k_pause.clicked) currentMenu = MENU_NONE;
		        if (k_up.clicked){ --currentSelection; if(currentSelection < 0)currentSelection=2;}
		        if (k_down.clicked){ ++currentSelection; if(currentSelection > 2)currentSelection=0;}
                if (k_accept.clicked){
                    switch(currentSelection){
                    case 0:      
                        currentMenu = MENU_NONE;
                        break;
                    case 1:
	                    areYouSureSave = true;
                        break;
                    case 2:
	                    areYouSure = true;
                        break;
                    }
                }
            } else if(areYouSureSave) {
                if (k_accept.clicked){
                    pauseSaveDisplayTimer = 60;
                    saveCurrentWorld(currentFileName, &eManager, &player, (u8*)map, (u8*)data);
                    areYouSureSave = false;
                    areYouSure = false;
                } else if (k_decline.clicked){
                    areYouSureSave = false;
                    areYouSure = false;
                }
            } else {
                if (k_accept.clicked){
                    areYouSure = false;
                    areYouSureSave = false;
	                sf2d_set_clear_color(0xFF);
                    currentSelection = 0;
                    currentMenu = MENU_TITLE;
                } else if (k_decline.clicked){
                    areYouSure = false;
                    areYouSureSave = false;
                }
            }
        break;
        case MENU_INVENTORY:
            if (k_menu.clicked || k_decline.clicked){
                 currentMenu = MENU_NONE;
                 player.p.activeItem = &noItem;
                 player.p.isCarrying = false;
            }
            if (k_accept.clicked){ // Select item from inventory
                if(player.p.inv->lastSlot!=0){
                    median = player.p.inv->items[curInvSel]; // create copy of item.
                    removeItemFromInventory(curInvSel, player.p.inv); // remove original
                    pushItemToInventoryFront(median, player.p.inv); // add copy to front
                    player.p.activeItem = &player.p.inv->items[0]; // active item = copy.
                    if(player.p.activeItem->id > 27) player.p.isCarrying = true;
                    else player.p.isCarrying = false;
                }
                currentMenu = MENU_NONE;
            }
		    if (k_up.clicked){ --curInvSel; if(curInvSel < 0)curInvSel=player.p.inv->lastSlot-1;}
		    if (k_down.clicked){ ++curInvSel; if(curInvSel > player.p.inv->lastSlot-1)curInvSel=0;}
        break;
        
        case MENU_CRAFTING:
        if (k_menu.clicked || k_decline.clicked) currentMenu = MENU_NONE;
        if (k_accept.clicked){
            int newslot = player.p.activeItem->slotNum + 1;
            if(craftItem(currentRecipes, &currentRecipes->recipes[curInvSel], player.p.inv)){
                playSound(snd_craft);
                if(player.p.activeItem != &noItem)player.p.activeItem = &player.p.inv->items[newslot];
            }
        }
		if (k_up.clicked){ --curInvSel; if(curInvSel < 0)curInvSel=currentRecipes->size-1;}
		if (k_down.clicked){ ++curInvSel; if(curInvSel > currentRecipes->size-1)curInvSel=0;}
        break;
        
        case MENU_WIN:
            if (k_accept.clicked){ 
	            sf2d_set_clear_color(0xFF);
                currentMenu = MENU_TITLE;
                saveCurrentWorld(currentFileName, &eManager, &player, (u8*)map, (u8*)data);
            }
        break;
        case MENU_LOSE:
            if (k_accept.clicked){ 
	            sf2d_set_clear_color(0xFF);
                currentMenu = MENU_TITLE;
            }
        break;
        case MENU_ABOUT:
            if (k_decline.clicked) currentMenu = MENU_TITLE;
        break;
        
        case MENU_CONTAINER:
        if (k_menu.clicked || k_decline.clicked)currentMenu = MENU_NONE;
        
        if (k_left.clicked) {
			curChestEntity->entityFurniture.r = 0;
			int tmp = curInvSel;
			curInvSel = curChestEntity->entityFurniture.oSel;
			curChestEntity->entityFurniture.oSel = tmp;
		}
		if (k_right.clicked) {
			curChestEntity->entityFurniture.r = 1;
			int tmp = curInvSel;
			curInvSel = curChestEntity->entityFurniture.oSel;
			curChestEntity->entityFurniture.oSel = tmp;
		}
		
		Inventory* i1 = curChestEntity->entityFurniture.r == 1 ? player.p.inv : curChestEntity->entityFurniture.inv;
		Inventory* i2 = curChestEntity->entityFurniture.r == 0 ? player.p.inv : curChestEntity->entityFurniture.inv;
		int len = i1->lastSlot;
		if (curInvSel < 0) curInvSel = 0;
		if (curInvSel >= len) curInvSel = len - 1;
		if (k_up.clicked) --curInvSel;
		if (k_down.clicked) ++curInvSel;
		if (len == 0) curInvSel = 0;
		if (curInvSel < 0) curInvSel += len;
		if (curInvSel >= len) curInvSel -= len;
		
		if(k_accept.clicked && len > 0){
            Item* pullItem = &i1->items[curInvSel];
            Item pushItem = newItem(pullItem->id,pullItem->countLevel);
            pushItem.chestPtr = pullItem->chestPtr;
            pushItemToInventoryFront(pushItem, i2);
            if(i2 == player.p.inv){
                int newslot = player.p.activeItem->slotNum + 1;
                player.p.activeItem = &player.p.inv->items[newslot];
            } else if(pullItem == player.p.activeItem){
                player.p.activeItem = &noItem;
            }
            removeItemFromCurrentInv(pullItem);
			if (curInvSel >= i1->lastSlot) curInvSel = i1->lastSlot - 1;
        }
		
        break;
        
        case MENU_LOADGAME:
            if(!enteringName && !areYouSure){ // World select
                if (k_decline.clicked){
                    currentMenu = MENU_TITLE;
                    currentSelection = 0;
                }
                if (k_up.clicked){ --currentSelection; if(currentSelection < 0)currentSelection = worldFileCount;}
                if (k_down.clicked){ ++currentSelection; if(currentSelection > worldFileCount)currentSelection=0;}
            
                if(k_delete.clicked){
                    if(currentSelection < worldFileCount) areYouSure = true;
                }
            
                if(k_accept.clicked){
                    if(currentSelection == worldFileCount){
                        
                        enteringName = true;
                    } else {
                        memset(&currentFileName, 0, 255); // reset currentFileName
                            sprintf(currentFileName,"%s.wld",fileNames[currentSelection]);
                            playSound(snd_test);
                            initGame = 1;
                            currentMenu = MENU_NONE;
                    }
                }
            } else if (areYouSure){
                if (k_decline.clicked || k_delete.clicked) areYouSure = false;
                if (k_accept.clicked){
                    sprintf(currentFileName,"%s.wld",fileNames[currentSelection]);
                    remove(currentFileName);
                    readFiles();
                    enteringName = false;
                    areYouSure = false;
                    memset(&currentFileName, 0, 255); // reset currentFileName
                }
            }else { // Enter new world name.
                if(k_decline.clicked) enteringName = false;
                if(k_accept.clicked && errorFileName == 0){
                    errorFileName = checkFileNameForErrors();
                    if(errorFileName == 0){ // If no errors are found with the filename, then start a new game!
                        memset(&currentFileName, 0, 255); // reset currentFileName
                        sprintf(currentFileName,"%s.wld",fileNames[worldFileCount]);
                        currentMenu = MENU_NONE;
                        playSound(snd_test);
                        initGame = 2;
                        ++worldFileCount;
                    }
                }
                touchPosition touch;
                hidTouchRead(&touch);
                if((touch.px != 0 || touch.py != 0) && touchDelay == 0){ 
                    if(!isTouching)doTouchButton(touch); 
                }
                else if(touch.px == 0 || touch.py == 0) isTouching = false;
                if(touchDelay > 0) --touchDelay;
            }
        break;
        
        case MENU_TITLE:
		    if (k_up.clicked){ --currentSelection; if(currentSelection < 0)currentSelection=4;}
		    if (k_down.clicked){ ++currentSelection; if(currentSelection > 4)currentSelection=0;}
		    
		    if(k_accept.clicked){
                switch(currentSelection){
                    case 0:
                        currentMenu = MENU_LOADGAME;
                        readFiles();
                        currentSelection = 0;
                        enteringName = false;
                        areYouSure = false;
                    break;
                    case 2:
                        keyProp[0] = k_up.input;
                        keyProp[1] = k_down.input;
                        keyProp[2] = k_left.input;
                        keyProp[3] = k_right.input;
                        keyProp[4] = k_attack.input;
                        keyProp[5] = k_menu.input;
                        keyProp[6] = k_pause.input;
                        keyProp[7] = k_accept.input;
                        keyProp[8] = k_decline.input;
                        keyProp[9] = k_delete.input;
                        left = true;
                        selBut = false;
                        bindOpt = false;
                        currentSelection = 0;
                        currentMenu = MENU_SETTINGS;
                    break;
                    case 3: 
                        currentMenu = MENU_ABOUT;
                    break;
                    case 4: 
                        quitGame = true;
                    break;
                }
                
            }
        break;
    }
    
}