コード例 #1
0
ファイル: ConfigFile.cpp プロジェクト: DuinoPilot/Picopter
void ConfigFile::ExtractKeys()
{
    std::ifstream file;
    file.open(fName.c_str());
    if (!file)
        std::cout << "CFG: File " << fName << " couldn't be found!\n" << std::endl;

    std::string line;
    size_t lineNo = 0;
    while (std::getline(file, line))
    {
        lineNo++;
        std::string temp = line;

        if (temp.empty())
            continue;

        removeComment(temp);
        if (onlyWhitespace(temp))
            continue;

        parseLine(temp, lineNo);
    }

    file.close();
}
コード例 #2
0
void Parser::parseLine(QString line){
	line = removeComment(line);
	if(line.length() > 0){
		QStringList list = line.split(" ");
		QString strName = list[0];
		if(m_bMultiLineCommand == true && list.size() == 2){
			if(list[0] == m_pTemporaryCommand->name() && list[1] == "end"){
				m_bMultiLineCommand = false;
				m_vCommands.push_back(m_pTemporaryCommand);
			}else{
				m_pTemporaryCommand->appendCode(line);
			}
		}else if(m_bMultiLineCommand == true){
				m_pTemporaryCommand->appendCode(line);
		}else if(m_pCommandsCollection->contains(strName)){
			m_bMultiLineCommand = m_pCommandsCollection->isMultiLine(strName);
			m_pTemporaryCommand = m_pCommandsCollection->create(strName);
			
			list.removeAt(0);
			m_pTemporaryCommand->setParams(list);
			QString sCheck = "";
			if(!m_pTemporaryCommand->check(sCheck)){
				m_pLogger->error("'" + strName + "'" + sCheck);
			}
			if(!m_bMultiLineCommand){
				m_vCommands.push_back(m_pTemporaryCommand);
			}
		}else{
			m_pLogger->warn("'" + strName + "' unknown command, skipped");
		}
	}
};
コード例 #3
0
ファイル: ConfigFile.cpp プロジェクト: trew/TDP005
void ConfigFile::parse()
{
	std::ifstream file;
	file.open(filename.c_str());
	if (!file)
	{
		ConfigUtil::warn("File " + filename + " could not be found.");
		return;
	}

	std::string line;
	size_t line_number = 0;
	while (std::getline(file, line))
	{
		line_number++;
		std::string tmp = line;
		if (tmp.empty() || tmp == "\r" || tmp == "\n")
		{
			continue;
		}

		removeComment(tmp);
		if (isOnlyWhitespace(tmp))
		{
			continue;
		}

		parseLine(tmp, line_number);
	}

	file.close();
}
コード例 #4
0
ファイル: Parser.cpp プロジェクト: ptjohns2/MIPSEM
vector<string> Parser::tokenizeInstruction(string str){
	// NAME A1,A2,A3,A4#xxxx
	str = removeComment(str);

	stringstream ss(str);

	vector<string> tokensBeforeParenSplit;
	vector<string> tokensAfterParenSplit;

	//tokenize instructions without splitting parenthises
	string tmpStr;
	getline(ss, tmpStr, ' ');	//get instruction name
	tokensBeforeParenSplit.push_back(trim(tmpStr));
	while(getline(ss, tmpStr, ',')){
		tokensBeforeParenSplit.push_back(trim(tmpStr));
	}
	ss.clear();
	//split tokens by parenthises
	for(int i=0; i<tokensBeforeParenSplit.size(); i++){
		stringstream ss(tokensBeforeParenSplit[i]);
		string beforeParen, afterParen;
		getline(ss, beforeParen, '(');
		getline(ss, afterParen);
		tokensAfterParenSplit.push_back(beforeParen);
		if(afterParen.length() != 0){
			tokensAfterParenSplit.push_back("(" + afterParen);
		}
	}
	
	return tokensAfterParenSplit;
}
コード例 #5
0
ファイル: IniConfig.cpp プロジェクト: Hasimir/darling
void IniConfig::loadConfig(std::ifstream& f)
{
	std::string line, section;
	ValueMap* valMap = 0;

	while (std::getline(f, line))
	{
		trim(removeComment(line));

		if (line.empty())
			continue;

		if (line[0] != '[' || *line.rbegin() != ']')
		{
			if (!valMap)
			{
				std::cerr << "Skipping invalid config file line: " << line << std::endl;
				continue;
			}
			else
			{
				size_t pos = line.find('=');
				if (pos == std::string::npos)
				{
					std::cerr << "Skipping invalid config file line: " << line << std::endl;
					continue;
				}
				else
				{
					std::string key, value;
					key = line.substr(0, pos);
					value = line.substr(pos+1);
					trim(key);
					trim(value);

					(*valMap)[key] = value;
				}
			}
		}
		else
		{
			if (valMap)
				m_sections[section] = valMap;

			valMap = new ValueMap;
			section = line.substr(1, line.size()-2);
		}
	}

	if (valMap)
		m_sections[section] = valMap;
}
コード例 #6
0
ファイル: XML.cpp プロジェクト: Surtr04/CPD_PI
void SparseXML::readXML(const char * filename,string &xml)
{
_current_position=0; // initialize the position 
_data_position=0;   
_data_length=0;
_level=0;
_empty_element=true;
_element.clear();  // clean the element string
//
size_t filesize;
ifstream f(filename);
if(!f.is_open())
            {
             cout<<" error opening file:"<<filename<<"  in "<<__FILE__<< " line "<<__LINE__<<endl; 
             cout<<" file does not exist"<<endl;
             exit(0);
            }
filesize=f.tellg();
 _xml_string= &xml;
(*_xml_string).reserve(filesize);
f.seekg(0);
while (!f.eof())// read the file
      {
      (*_xml_string) += f.get(); 
      }
f.close();        
// first find the prologue       
    string begin_string_prologue="<?xml",end_string_prologue="?>";
    size_t begin_position_prologue=_xml_string->find(begin_string_prologue);
  if(begin_position_prologue==string::npos)
            {cout<<" error prologue begin format:"<<"  in "<<__FILE__<< " line "<<__LINE__<<endl; exit(1);}  
    size_t end_position_prologue=_xml_string->find(end_string_prologue);
   if(end_position_prologue==string::npos)
            {cout<<" error prologue end format:"<<"  in "<<__FILE__<< " line "<<__LINE__<<endl; exit(1);}   
   string prologue;
   begin_position_prologue+=5;// eliminate <?xml
   prologue.append((*_xml_string),begin_position_prologue,end_position_prologue-begin_position_prologue);
   end_position_prologue+=2; // eliminate  ?>
  // store the  attribute in the map.
   makeMap(prologue);
   // now we have to check if the is one root and  extract  
   _xml_string->erase(0,end_position_prologue);
   (*_xml_string)+='\0';
   // and we remove the comment balise
   removeComment();
   //cout<< "after the prologue"<<(*_xml_string) <<endl;
}
コード例 #7
0
ファイル: personview.cpp プロジェクト: cornelius/polka
void PersonView::slotLinkClicked( const QUrl &url )
{
  qDebug() << "CLICKED" << url;

  if ( url.scheme() == "polka" ) {
    QStringList path = url.path().split("/");
    QString action = path.first();
    qDebug() << "ACTION" << action;

    if ( action == "editName" ) editName();

    else if ( action == "addEmail" ) addEmail();
    else if ( action == "editEmail" ) editEmail( path.value( 1 ) );
    else if ( action == "removeEmail" ) removeEmail( path.value( 1 ) );
    else if ( action == "commentEmail" ) commentEmail( path.value( 1 ) );

    else if ( action == "addPhone" ) addPhone();
    else if ( action == "editPhone" ) editPhone( path.value( 1 ) );
    else if ( action == "removePhone" ) removePhone( path.value( 1 ) );
    else if ( action == "commentPhone" ) commentPhone( path.value( 1 ) );

    else if ( action == "addLink" ) addLink();
    else if ( action == "editLink" ) editLink( path.value( 1 ) );
    else if ( action == "removeLink" ) removeLink( path.value( 1 ) );
    else if ( action == "commentLink" ) commentLink( path.value( 1 ) );

    else if ( action == "addAddress" ) addAddress();
    else if ( action == "editAddress" ) editAddress( path.value( 1 ) );
    else if ( action == "removeAddress" ) removeAddress( path.value( 1 ) );
    else if ( action == "commentAddress" ) commentAddress( path.value( 1 ) );

    else if ( action == "addComment" ) addComment();
    else if ( action == "editComment" ) editComment( path.value( 1 ) );
    else if ( action == "removeComment" ) removeComment( path.value( 1 ) );

    else if ( action == "close" ) requestClose();
    else if ( action == "magic" ) debugHtml();

    else qDebug() << "unknown action" << action;
  } else {
    new KRun( QUrl( url ), this );
  }
}
コード例 #8
0
ファイル: main.c プロジェクト: swiecki/C-Shell
int main(int argc, char **argv) {
	//Establish anything we'll need constantly.
	int mode = 1;//Start in sequential mode.
	int usepath = 0;//does our path file exist?
	int futuremode = mode;//This keeps track of mode changes until the end of the line.
	int printPrompt = 0;
	char *prompt = "s-term> ";//The prompt string.
	printf("%s", prompt);//Print the prompt.
	fflush(stdout);
 
	//do pathstuff
	char **paths = readFile("shell-config");
	if(paths != NULL){
		usepath = 1;
	}

	char **firststep = NULL;//The array of commands made by splitting the buffer along semicolons.
	char ***secondstep = NULL;//The array of commands, with each command split along whitespace into its arguments.
		
	struct node *head = NULL;//The head of the linked list of ongoing jobs.
	
	char buffer[1024];//The buffer.
	while (1) {//
		struct pollfd pfd = {0, POLLIN};
		if(printPrompt){
			//Need to reprint the prompt.
			printf("%s",prompt);
			fflush(stdout);
			printPrompt = 0;
		}
		int rv = poll(&pfd, 1, 1000);
		if (rv==0){
			//No change, use time to do other tasks
			struct node *anode = head;
			while(anode != NULL){
				int pstatus = 0;
				int pstate = waitpid((*anode).pid,&pstatus,WNOHANG);
				if(pstate>0){
					//Process has returned; print confirmation message and delete this node.
					printf("Command %s, id %i was executed.\n",(*anode).command, anode->pid);
					anode = (*anode).next;
					listDelete(pstate, &head);
					printPrompt = 1;
				} else if(pstate<0){
					//Error in waitpid, print error message and break from while loop.
					printf("Error retrieving process status.\n");
					break;
				} else{
					//Process has not returned.
					anode = (*anode).next;
				}
			}
		} else if (rv < 0){
			//Poll went horribly wrong and we're bailing out of the flaming wreckage, screaming at the tops of our lungs.
			printf("Polling error; shutting the (s)hell down.");
		} else {
			//Keyboard I/O
			if(fgets(buffer, 1024, stdin) != NULL){

				mode = futuremode;//Ensure that mode is up-to-date.

				//Remove any comments after a hash.
				removeComment(buffer);
		
				//Tokenize buffer by semicolons- each will be an executable command.
		
				firststep = tokenify(buffer,";");
				secondstep = tokenify2(firststep," \t\n");

				//Free firststep, as it is no longer needed. Free the sub-arrays first, then the array proper.
				freeAll1(firststep);
				free(firststep);
	
				int j = 0;
				int futureExit = 0;
				int status = 0;
				pid_t p = 1;

				//Execute all commands in a loop.
				while(secondstep[j] !=  NULL && secondstep[j][0] != NULL){
					//check for the special commands mode or exit. If neither of these, fork and execv.
					if(!strcasecmp(secondstep[j][0],"exit")){
						int canwequit = 1;
						struct node *tmp = head;
						while(tmp != NULL){
							if(tmp->state != 1){
								canwequit = 0;
							}
							tmp = tmp->next;
						}
						if (canwequit){
							futureExit = 1;//Will be checked at the end of the loop.
						} else {
							printf("Error: Jobs are currently running. Please wait for tasks to finish before exiting.\n");
						}
					}
					else if(!strcasecmp(secondstep[j][0],"pause")){
						setState(atoi(secondstep[j][1]), 1, head);
						if(kill(atoi(secondstep[j][1]), SIGSTOP) != -1){
							printf("Paused process %i\n",atoi(secondstep[j][1]));
						}
						else{
							printf("Something went terribly wrong\n");
						}
						
					}
					else if(!strcasecmp(secondstep[j][0],"resume")){
						setState(atoi(secondstep[j][1]), 0, head);
						if(kill(atoi(secondstep[j][1]), SIGCONT) != -1){
							printf("Resumed process %i\n",atoi(secondstep[j][1]));
						}
					}
					else if(!strcasecmp(secondstep[j][0],"jobs")){
						struct node *tmp = head;
						printf("\npid cmd paused\n");
						while(tmp != NULL){
							printf("%i %s %i\n",tmp->pid,tmp->command,tmp->state);
							tmp = tmp->next;
						}
					}
					/*else if(!strcasecmp(secondstep[j][0],"path")&& !strcasecmp(secondstep[j][1],"refresh")){
						if(paths != NULL){
						freeAll1(paths);
						free(paths);
						}
						//do pathstuff
						char **paths = readFile("shell-config");
						if(paths == NULL){
							usepath = 0;
						}else{
							usepath = 1;
						}
					}*/
					else if(!strcasecmp(secondstep[j][0],"MODE")){
						if(secondstep[j][1] == NULL){
							if(mode == 0){
								printf("\nCurrent mode is parallel\n");
							}
							else {
								printf("\nCurrent mode is sequential\n");
							}
						}
						else if(!strcasecmp(secondstep[j][1],"PARALLEL") || !strcasecmp(secondstep[j][1],"p")){
							futuremode = 0;
						}
						else if(!strcasecmp(secondstep[j][1],"SEQUENTIAL") || !strcasecmp(secondstep[j][1],"s")){
							futuremode = 1;
						}
						else {
							//Bullshit users with their bullshit commands - throw an error.
							printf("\nError: Your command was pretty awful.\n");
						}
					}
					else{
						//Fork and execute/wait depending on process id.
						p = fork();
						if (p == 0){
							break;//Child processes handled outside the while loop.
						}
						if(mode==1){//Sequential mode.
							wait(&status);
							//Do something with childp; error checking, probably
						} else {//Parallel mode; add this to the list
							listInsert(p, secondstep[j][0], 0, &head);
						}
					}
					j++;
				}
		
				if (p == 0){
					if(usepath==1){
						int k = 0;
						while(paths[k] != NULL){
							struct stat sr;
							char tempbuffer[1024];
							strcpy(tempbuffer, paths[k]);
							strcat(tempbuffer, "/");
							strcat(tempbuffer, secondstep[j][0]);
							int rv = stat(tempbuffer, &sr);
							if (rv < 0){
								k++;
							}	
							else{
								secondstep[j][0]=tempbuffer;
								if(execv(secondstep[j][0],secondstep[j])<0){
									exit(0);
								}
							}
						}
					}
					//Execv for an actual, non-hardcoded command.
					printf("\n%s\n",secondstep[j][0]);
					if(execv(secondstep[j][0],secondstep[j])<0){
						fprintf(stderr, "Your command failed, and here's why you're a bad person: %s\n", strerror(errno));
					}
					exit(0);//Close out the child process corpse.
		
				} 
				
				//check if there was an exit command earlier
				if(futureExit == 1){
					break;
				}

				//If we don't exit, free current buffer
				freeAll2(secondstep);	
				free(secondstep);
		
				//Make sure firststep and secondstep have an assigned value in case of early termination.
				firststep = NULL; 
				secondstep = NULL;
		
				printf("%s", prompt);
				fflush(stdout);
				}
			if(feof(stdin)){
				break;//End of file or Ctrl+D
			}
			}
		}
	//on a quit, flush our command array if it's not null already
	if(secondstep != NULL){
		freeAll2(secondstep);
		free(secondstep);
	}
		
	//Free the paths array as well.
	if(paths!=NULL){
		freeAll1(paths);
		free(paths);
	}
		
	//Check time spent in user mode and kernel mode. Right now I've got it separated by shell and processes, but we can add it together later.
	int idParent = RUSAGE_SELF;
	int idChild = RUSAGE_CHILDREN;
	int statParent = 0;
	int statChildren = 0;
	struct rusage dataParent;
	struct rusage dataChildren;
	statParent = getrusage(idParent, &dataParent);
	statChildren = getrusage(idChild, &dataChildren);
	if(!statParent){//If the getrvalue operation was a success
		printf("Shell time in user mode: %ld.%06ld seconds.\n", dataParent.ru_utime.tv_sec, dataParent.ru_utime.tv_usec);
		printf("Shell time in kernel mode: %ld.%06ld seconds. \n", dataParent.ru_stime.tv_sec, dataParent.ru_stime.tv_usec);
	}
	if(!statChildren){
		printf("Process time in user mode: %ld.%06ld seconds. \n", dataChildren.ru_utime.tv_sec, dataChildren.ru_utime.tv_usec);
		printf("Process time in kernel mode: %ld.%06ld seconds. \n", dataChildren.ru_stime.tv_sec, dataChildren.ru_stime.tv_usec);
	}
	exit(0);
	//Ctrl+D will drop you down here; need to make sure any cleanup also happens here too.
	return 0;
}
コード例 #9
0
//--------------------------------------------------------------------------
// Function:	CommonFG::removeComment
///\brief	This is an overloaded member function, provided for convenience.
///		It differs from the above function in that it takes an
///		\c H5std_string for \a name.
// Programmer	Binh-Minh Ribler - May 2005
//--------------------------------------------------------------------------
void CommonFG::removeComment(const H5std_string& name) const
{
   removeComment (name.c_str());
}
コード例 #10
0
ファイル: main.cpp プロジェクト: hklarner/PyBoolNet
int main(int argc, char ** argv) {
	try {
#ifdef _MSC_VER //Set the output buffer size for visual studio
		setvbuf(stdout, 0, _IOLBF, 4096);
#endif
#ifdef RUN_TESTS
		FormulaeResolver::test();
#else
		// Parse the input
		if (argc > 1) {
			string arg1 = argv[1];
			if (arg1 == "--help" || arg1 == "-h") {
				IO::printHelp();
				return 0;
			}
			if (arg1 == "--ver" || arg1 == "-v") {
				IO::printVersion();
				return 0;
			}
		}
		has_fin = argc > 1;
		has_fout = argc > 2;

		// Open the input and output files, use standard streams if not specified
		fstream fin;
		if (has_fin) {
			fin.open(argv[1], fstream::in);
			if (!fin) {
				throw invalid_argument(string("Failed to open the input file ") + argv[1]);
			}
		}
		istream & in = has_fin ? fin : cin;

		fstream fout;
		if (has_fout) {
			fout.open(argv[2], fstream::out);
			if (!fout) {
				throw invalid_argument(string("Failed to open the output file ") + argv[2]);
			}
		}
		ostream & out = has_fout ? fout : cout;


		// Holds the input
		map<string, pair<vector<string>, string> > line_data;
		string line;
		// Read computed and write line by line
		while (getline(in, line)) {
            line = FormulaeResolver::removeWhitespaces(line);
			line = removeComment(line);
			// Skip the first line, if it is "targets,factors"
            if (line.empty() || line == "targets,factors" ) {
				continue;
			}
			// Parse the line
			size_t comma_pos = line.find(',');
			string component = line.substr(0, comma_pos);
			if (line_data.count(component)) {
				throw runtime_error(component + " already has a function.");
			}
			string formula = FormulaeResolver::removeWhitespaces(line.substr(comma_pos + 1));
			vector<string> regulators = IO::getAllRegulators(formula);
			line_data.insert(make_pair(component, make_pair(regulators, formula)));
		}

		// Check if all components are present, if not, add self-regulation
		for (map<string, pair<vector<string>, string> >::iterator it = line_data.begin(); it != line_data.end(); it++) {
            for (vector<string>::const_iterator comp_it = it->second.first.begin(); comp_it != it->second.first.end(); comp_it++) {
				if (line_data.count(*comp_it) == 0) {
					vector<string> regulators;
					regulators.push_back(*comp_it);
					line_data.insert(make_pair(*comp_it, make_pair(regulators, *comp_it)));
				}
			}
		}

		// Compute and output data for each line
		out << "{";
        for (map<string, pair<vector<string>, string> >::const_iterator it = line_data.begin(); it != line_data.end(); it++) {
			const string component = it->first;
			const vector<string> regulators = it->second.first;
			const string formula = it->second.second;

			const size_t VALUATIONS_COUNT = static_cast<size_t>(pow(2, regulators.size())); // How many valuations of the variables there are
			if (regulators.size() > maxRegulatorsCount()) {
				throw runtime_error("The component '" + component + "' has too many regulators.");
			}

			// Create the valuation map, also write the current line on the output 
			map<string, bool> valuation;
			IF_HAS_FOUT(cout << "\rTarget: '" << component << "'. Regulators: [";)
            for (vector<string>::const_iterator it = regulators.begin(); it != regulators.end(); it++) {
				IF_HAS_FOUT(cout << *it << ",";)
				valuation.insert(make_pair(*it, false));
			} 
			IF_HAS_FOUT(cout << "]" << endl;)
コード例 #11
0
Element* parseLine (const char *s, Element *prev)
{
	Element *elem = prev;
	if (elem && !elem->cont)
		elem = 0;
	if (!elem)
	{
		elem = malloc(sizeof(Element));
		elem->cont = 0;
		elem->key = 0;
		elem->value = 0;
	}
	
	char *l = malloc(strlen(s) + 1);
	strcpy(l, s);
	char *line = trim(removeComment(l));
	
	char *p = line;
	char esc = 0;
	// find the seperating char between the key and the value
	if (!elem->cont)
	{
		while (*p && (esc || (!isspace((unsigned char)(*p)) && (*p != '=') && (*p != ':'))))
		{
			if (*p == '\\')
				esc = 1;
			else
				esc = 0;
			p++;
		}
		// if the seperating key exists, write it into the element
		if (*p)
		{
			int diff = p - line;
			char *key = malloc(diff + 1);
			strncpy(key, line, diff);
			key[diff] = 0;
			elem->key = unescape(key, 0);
			free(key);
		}
		// else, write the line as the key, set the cont value and return
		else
		{
			elem->key = unescape(line, 0);
			free(l);
			elem->cont = esc;
			return elem;
		}
	}
	
	// remove any whitespace, = and : from the beginning of the value
	while (*p && (isspace((unsigned char)(*p)) || (*p == '=') || (*p == ':')))
		p++;
	// store the value
	char *value = malloc(strlen(line) - (p - line) + 1);
	strcpy(value, p);
	if (elem->cont)
	{
		char *val = malloc(strlen(value) + strlen(elem->value) + 1);
		strcpy(val, elem->value);
		strcat(val, value);
		free(elem->value);
		elem->value = val;
	}
	else
		elem->value = unescape(value, &(elem->cont));
	free(value);
	free(l);
	return elem;
}
コード例 #12
0
ファイル: Parser.cpp プロジェクト: ptjohns2/MIPSEM
string Parser::sanitizeProgramLine(string line){
	line = removeComment(line);
	//others?
	return line;
}
コード例 #13
0
ファイル: H5Location.cpp プロジェクト: Hulalazz/rnnlib
//--------------------------------------------------------------------------
// Function:	H5Location::removeComment
///\brief	This is an overloaded member function, provided for convenience.
///		It differs from the above function in that it takes an
///		\c H5std_string for \a name.
// Programmer	Binh-Minh Ribler - May 2005 (moved from CommonFG, Sep 2013)
//--------------------------------------------------------------------------
void H5Location::removeComment(const H5std_string& name) const
{
   removeComment (name.c_str());
}