void KeyValueStore::handleQuery(StreamSocket& client, Config::ThreadControl& control, char req, const string& buf)
{
  if(buf.empty())
    return; // Should not happen?

  // If we handle the data, do some magic
  if(req == Protocol::INSERT) {
    KeyValueStore::handleInsert(client, buf, control);
  } else if(req == Protocol::REMOVE) {
    KeyValueStore::handleRemove(client, buf, control);
  } else if(req == Protocol::LOOKUP) {
    KeyValueStore::handleLookup(client, buf, control);
  } else if(req == Protocol::INS_MOVIE) {
    KeyValueStore::handleInsertMovie(client, buf, control);
  } else if(req == Protocol::LUP_MOVIE) {
    KeyValueStore::handleLookupMovie(client, buf, control);
  } else if(req == Protocol::REPL_INS || req == Protocol::REPL_REM || req == Protocol::REPL_MOVIE) {
    unsigned space = buf.find_first_of(' ');
    if(space == string::npos) {
      printKv("Invalid replication request received");
      return;
    }
    int count = KeyValueStore::stringToInt(buf.substr(0, space));
    if(count < 0)
      return; // Paranoia - this should never be sent to us

    string rem(buf.substr(space+1));

    if(req == Protocol::REPL_INS) {
      KeyValueStore::handleInsRepl(rem, count, control);
    } else if(req == Protocol::REPL_REM) {
      KeyValueStore::handleRemRepl(rem, count, control);
    } else if(req == Protocol::REPL_MOVIE) {
      KeyValueStore::handleMovieInsRepl(rem, count, control);
    }
  }
}
Example #2
0
    string simplifyPath(string path) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function


    	vector<string> ds;
		size_t n = 0;

		size_t s = 1;
		while (s != string::npos)
		{
			const size_t t = path.find_first_of('/', s);
			const string str =
				t == string::npos ? path.substr(s) : path.substr(s, t-s);

			if (str == "..") 
				n == 0 ? n : --n;
			else if (str != "." && str != "")
			{
				if (n == ds.size())
					ds.push_back(str);
				else
					ds[n] = str;
				++n;
			}

			s = t == string::npos ? string::npos : t + 1;
		}
		
        if (n == 0) return "/";
		string r;
		for (size_t i = 0; i < n; ++i)
			r += "/" + ds[i];

		return r;

    }
Example #3
0
string expand_path( const string &path )
{
	if( path.length() == 0 || path[ 0 ] != '~' )
		return path;

	const char *pfx = NULL;
	string::size_type pos = path.find_first_of( '/' );

	if( path.length() == 1 || pos == 1 ) {
		pfx = getenv( "HOME" );

		if( !pfx ) {
			// Punt. We're trying to expand ~/, but HOME
			// isn't set.
			struct passwd *pw = getpwuid( getuid() );
			if( pw ) pfx = pw->pw_dir;
		}
	} else {
		string user( path, 1, ( pos == string::npos ) ? string::npos : pos - 1 );
		struct passwd *pw = getpwnam( user.c_str() );
		if( pw ) pfx = pw->pw_dir;
	}

	// If we failed to find an expansion, return the path unchanged.
	if( !pfx ) return path;

	string result( pfx );

	if( pos == string::npos ) return result;

	if( result.length() == 0 || result[ result.length() - 1 ] != '/' )
		result += '/';

	result += path.substr(pos+1);

	return result;
}
Example #4
0
/**
 * Read an integer from an input string. The input string is
 * modified by deleting the integer from it after it is read.
 *
 * @param aString input string to read from.
 * @param rNumber integer that is read is returned here.
 * @return True if integer was read, false if not.
 */
bool OpenSim::readIntegerFromString(string &aString, int *rNumber)
{
   size_t i, end;
   string buffer;

   if (aString.empty())
      return false;

   /* remove any characters before the number */
   i = aString.find_first_of("0123456789-", 0);
   if (i != 0)
      aString.erase(0, i);

   /* remove number from string, copy number to buffer */
   i = aString.find_first_not_of("0123456789-eE", 0);
   end = aString.length();
   if (i != aString.npos)
   {
      buffer.assign(aString, 0, i);
      aString.erase(0, i);
   }
   else
   {
      buffer.assign(aString);
      aString.erase(0, end);
   }

   /* remove any whitespace after the string*/
   i = findFirstNonWhiteSpace(aString);
   if (i > 0)
      aString.erase(0, i);
   
   if (buffer.empty())
      return false;
   *rNumber = atoi(buffer.c_str());
   return true;
}
    string ReverseSentence(string str)
    {
        if (str.size( ) == 0)
        {
            return str;
        }

        reverse(str.begin(), str.end());

        size_t left = 0;
        size_t right = 0;
        while(right != string::npos)
        {
            left = str.find_first_not_of(' ', left);  //  第一个非空格字符是单词的起始位置
            right = str.find_first_of(' ', left);      //  第一个空格位置标识了单词的结束

            //  处理末尾是空格(原字符串开头是空格的情况)
            //  当最后全是空格的时候,此时可以结束循环
            if (left == string::npos)
            {
                break;
            }
            //  如果查找不到空格, 到了字符串的末尾
            //  此时[degin, str.size( )]是末尾的字符串
            if (right == string::npos)
            {
                reverse(str.begin( ) + left, str.end( ));
            }
            else        //  否则[left, end]是一个单词
            {
                reverse(str.begin( ) + left, str.begin() + right);
                left = right + 1;
            }
        }

        return str;
    }
//						==========================
string					Number::RemoveLeadingZeros
//						==========================
(
	const string&		strNumber
) const
{
	string strResult = "";

	// Check if the number string is not empty.
	if ( !strNumber.empty() )
	{
		// Check if the number starts with a minus sign.
		if ( strNumber[0] == '-' )
		{
			// Add the minus sign to the result.
			strResult = "-";
		}

		// Find the position of the first non-zero digit.
		int nPos = strNumber.find_first_of( "123456789" );

		// Determine if a non-zero digit has been found.
		if ( nPos != string::npos )
		{
			// Add all characters (which must be digits) after the last zero
			// to the result.
			strResult += strNumber.substr( nPos );
		}
		else
		{
			// The number must be 0; add one 0 to the result.
			strResult += "0";
		}
	}

	return strResult;
}
Example #7
0
//-----------------------------------------------------------------------------------------------
void CGUI::Message (const string& msg)
{
	uint32 Sz = msg.size();
	for (uint32 i = 0; i < Sz; ++i)
	{
		uint32 Pos = msg.find_first_of('\n', i);
		if (Pos == string::npos)
		{
			m_Console.push_back(msg.substr(i));
			break;
		}
		else
		{
			m_Console.push_back (msg.substr (i, Pos-i));
			i = Pos+1;
		}
	}
	m_LogFile << msg << endl;
	if (msg.size()>=1)
	if (*(msg.end()-1)=='\n')
	{
		m_Console.push_back (string(""));
	}
}
Example #8
0
        vector<string> split_param(const string &p, const string &sep,
                                   char open_par, char close_par)
        {
                vector<string> temp;
                string::size_type pos = 0;
                string::size_type old_pos = 0;

                string symbols = sep + open_par;

                while (pos <= p.size()) {
                        pos = p.find_first_of(symbols, pos);

                        if (pos != string::npos)
                                if (p[pos] == open_par) {
                                        pos = p.find(close_par, pos);
                                        if (pos == p.size()) pos = string::npos;
                                        else ++pos;
                                }
      
                        if (pos != string::npos) {
                                string t = remove_spaces(p.substr(old_pos, pos - old_pos));

                                temp.push_back(t);

                                old_pos = ++pos;
                        }
                }

                if (pos != old_pos) {
                        string t = remove_spaces(p.substr(old_pos, p.size() - old_pos));

                        if (t != "") temp.push_back(t);
                }

                return temp;
        }
Example #9
0
float my_stof(string s, int d)
{
    if(s.length()==0)
        return 0.0;
    float out=0.0;
    float add=1.0;
    int l1;
    int l2;
    size_t p1=s.find_first_of("1234567890.");
    s=s.substr(p1);
    p1=s.find_first_not_of("1234567890.");
    s=s.substr(0,p1);

    l1=s.find(".");
    if(l1==s.npos)
        l1=s.length();
    l2=s.length();

    for(int i=l1-1; i>=0; i--)
    {
        out+=add*(int(s.at(i))-48);
        add=add*10;
    }

    add=0.1;
    int j=0;
    for(int i=l1+1; i<l2; i++)
    {
        out+=add*(int(s.at(i))-48);
        add=add*0.1;
        j++;
        if(j==d)
            break;
    }
    return out;
}
static vector<string> Tokenize(const string& line, int minWords = 0)
{
	vector<string> words;
	string::size_type start;
	string::size_type end = 0;
	while (true) {
		start = line.find_first_not_of(" \t", end);
		if (start == string::npos) {
			break;
		}
		string word;
		if ((minWords > 0) && (words.size() >= minWords)) {
			word = line.substr(start);
			// strip trailing whitespace
			string::size_type pos = word.find_last_not_of(" \t");
			if (pos != (word.size() - 1)) {
				word.resize(pos + 1);
			}
			end = string::npos;
		}
		else {
			end = line.find_first_of(" \t", start);
			if (end == string::npos) {
				word = line.substr(start);
			} else {
				word = line.substr(start, end - start);
			}
		}
		words.push_back(word);
		if (end == string::npos) {
			break;
		}
	}
	
	return words;
}
Example #11
0
string MacroExtender::hasMacro(string line) {
	string consideredLine;
	if (regex_match(line,regex(labelReg))) {
		return ";";		
	}
	size_t labelPos = line.find_first_of(':');
	if (labelPos != string::npos && labelPos+1<line.length()) {
		consideredLine = line.substr(labelPos+2);
	}
	else {
		consideredLine = line;
	}
	for (const auto &i : MNT) {
		string auxFinder = string(" ") + i.first + string(" ");
		//cout << "Testing line [" << consideredLine << "] to [" << i.first << "]" << endl;
		if (consideredLine.find(auxFinder)!=string::npos) {
			return string(i.first);
		}
		auxFinder = string(" ") + i.first;
		size_t auxPos = consideredLine.find(auxFinder);
		size_t sumLen = (i.first).length()+1;
		if (auxPos!=string::npos && (auxPos+sumLen+1)<consideredLine.length()) {
			return string(i.first);
		}
		auxFinder = i.first + string(" ");
		auxPos = consideredLine.find(auxFinder);
		if (auxPos==0) {
			return string(i.first);
		}
		auxFinder = string("\\b") + i.first + string("\\b");
		if (regex_match(consideredLine,regex(auxFinder))) {
			return string(i.first);
		}
	}
	return string(";");
}
Example #12
0
// split given string by delims
StringArray split_text(const string &intext, const string &delims)
{
    StringArray         r;
    string::size_type   begIdx, endIdx;
    string              s;

    begIdx = intext.find_first_not_of(delims);

    while(begIdx != string::npos) {
        // search end of the word
        endIdx = intext.find_first_of(delims, begIdx);
        if( endIdx == string::npos )
            endIdx = intext.length();

        // get the sub string
        s = intext.substr(begIdx, endIdx-begIdx);
        r.push_back(s);

        // find next begin position
        begIdx = intext.find_first_not_of(delims, endIdx);
    }

    return r;
}
Example #13
0
bool CGeometry::ReadLineStringCoordinates(string s)
{
	istringstream ss(s);
	string sub_str;

	if(std::string::npos == s.find_first_of("0123456789"))
	{
			// "digit not found!, empty string//
		return false;
	}

	while(std::getline(ss,sub_str, ' '))
	{


		CCoordinate coordinate;
		istringstream sub_ss(sub_str);
		string tmp;

		std::getline(sub_ss,tmp,',');
		istringstream x_ss(tmp);
		x_ss >> coordinate.X;
		
		std::getline(sub_ss,tmp,',');
		istringstream y_ss(tmp);
		y_ss >> coordinate.Y;

		std::getline(sub_ss,tmp,',');
		istringstream z_ss(tmp);
		z_ss >> coordinate.Z;

		v_Coordinates.push_back(coordinate);
		m_NumOfCoordinates += 1;
	}
	return true;
}
Example #14
0
// Tokenizes the string using the delimiters.
// Empty tokens will not be included in the result.
vector<string>Util::tokenizeString(const string &s, const string &delims)
{
  size_t offset = 0;

  vector<string>tokens;

  while (true) {
    size_t i = s.find_first_not_of(delims, offset);
    if (i == string::npos) {
      break;
    }

    size_t j = s.find_first_of(delims, i);
    if (j == string::npos) {
      tokens.push_back(s.substr(i));
      offset = s.length();
      continue;
    }

    tokens.push_back(s.substr(i, j - i));
    offset = j;
  }
  return tokens;
}
Example #15
0
/****************************************************
 CleanUp( )
removes spacing and converts all to lower case
****************************************************/
string CScript::CleanUp(string linein){
  string lineout;
  int it;
  
  //clean up string that have something in them
  if (linein.length()>0){
    int ret = linein.find_first_of("//");//find //
    switch(ret){
      case -1:
        ret = linein.length();
        break;
      case 0:
        ret = 0;
        break;
    }
  
    //create replacement string without spaces
    for(it = 0; it < ret;it++){
      if(linein.substr(it,1)!= " ")
        lineout += linein.substr(it,1);
    }
    lineout = lineout + linein.substr(ret);
   
    //convert string to lower case (doesn't affect comment
    char *buf = new char[lineout.length()]; //create temp buffer
    lineout.copy(buf,lineout.length());
    for (int i=0; i<lineout.length();i++){
      buf[i] = tolower(buf[i]);             //convert to lowercase 1 at a time
    }  
    string lineoutlower(buf,lineout.length());
    lineout = lineoutlower;
    delete buf;
  }

  return lineout;
}
/**
 * It will be called from JNext JavaScript side with passed string.
 * This method implements the interface for the JavaScript to native binding
 * for invoking native code. This method is triggered when JNext.invoke is
 * called on the JavaScript side with this native objects id.
 */
string GSECryptoJS::InvokeMethod(const string& command) {
	// command appears with parameters following after a space
	int index = command.find_first_of(" ");
	std::string strCommand = command.substr(0, index);
	std::string arg = command.substr(index + 1, command.length());

	if (strCommand == "hash") {
		return gseCryptoController->hash(arg);
	} else if (strCommand == "generateKey") {
		return gseCryptoController->generateKey(arg);
	} else if (strCommand == "encrypt") {
		return gseCryptoController->encrypt(arg);
	} else if (strCommand == "decrypt") {
		return gseCryptoController->decrypt(arg);
	} else if (strCommand == "random") {
		return gseCryptoController->random(arg);
	}

	Json::Value error;
	error["error"] = "No implementation found for " + strCommand + "(" + command
			+ ")";
	Json::FastWriter writer;
	return writer.write(error);
}
Example #17
0
TokenSet tokenize(const string& str,const string& delimiters,bool trimEmpty)
{
    TokenSet tokens;
    size_t pos, lastPos = 0;

    while(true){
        pos = str.find_first_of(delimiters, lastPos);
        if(pos == std::string::npos){
            pos = str.length();

            if(pos != lastPos || !trimEmpty){
                tokens.push_back(string(str.data()+lastPos,pos-lastPos));
            }
            break;
        }
        else{
            if(pos != lastPos || !trimEmpty){
                tokens.push_back(string(str.data()+lastPos,pos-lastPos));
            }
        }
        lastPos = pos + 1;
    }
    return tokens;
}
Example #18
0
    inline bool split(const string& src, vector<string>& res, const string& pattern, size_t offset = 0, size_t len = string::npos)
    {
        if(src.empty())
        {
            return false;
        }
        res.clear();

        size_t start = 0;
        size_t end = 0;
        size_t cnt = 0;
        while(start < src.size() && res.size() < len)
        {
            end = src.find_first_of(pattern, start);
            if(string::npos == end)
            {
                if(cnt >= offset)
                {
                    res.push_back(src.substr(start));
                }
                return true;
            }
            //if(end == src.size() - 1)
            //{
            //    res.push_back("");
            //    return true;
            //}
            if(cnt >= offset)
            {
                res.push_back(src.substr(start, end - start));
            }
            cnt ++;
            start = end + 1;
        }
        return true;
    }
Example #19
0
string PhyloTree::getNextTaxon(string& heirarchy, string seqname){
	try {
		string currentLevel = "";
		if(heirarchy != ""){
			int pos = heirarchy.find_first_of(';');
			
			if (pos == -1) { //you can't find another ;
				currentLevel = heirarchy;
				heirarchy = "";
				m->mothurOut(seqname + " is missing a ;, please check for other errors."); m->mothurOutEndLine();
			}else{
				currentLevel=heirarchy.substr(0,pos);
				if (pos != (heirarchy.length()-1)) {  heirarchy=heirarchy.substr(pos+1);  }
				else { heirarchy = ""; }
			}
			
		}
		return currentLevel;
	}
	catch(exception& e) {
		m->errorOut(e, "PhyloTree", "getNextTaxon");
		exit(1);
	}
}
Example #20
0
StringUtils::tStringsList StringUtils::split(const string& str, const string& delims)
{
    tStringsList ret;

    // Pre-allocate some space for performance
    ret.reserve(10);    // 10 is guessed capacity for most case

    // Use STL methods
    size_t start, pos;
    start = 0;
    do
    {
        pos = str.find_first_of(delims, start);
        if (pos == start)
        {
            // Do nothing
            ret.push_back("");
            start = pos + 1;
        }
        else if (pos == string::npos)
        {
            // Copy the rest of the string
            ret.push_back(str.substr(start));
            break;
        }
        else
        {
            // Copy up to delimiter
            ret.push_back(str.substr(start, pos - start));
            start = pos + 1;
        }

    } while ((start != string::npos) && (pos != string::npos));

    return ret;
}
Example #21
0
/*
Second heuristic
By careful analysis, i found that in the goal, the maximum distance between
sum of pos of whites and blacks(B - W) will be 12 and minimum will be 9. 
I used this a heuristic to see how far we are from the goal which is B-W to be made at least 9.
However, hofn value is not allowed to be negative and is considered as zero if B-W is >9
*/
int FindHofN2(string node)
{
    int Distance = 0;
    int pos = 0;
    int posW = 0;
    int posB = 0;
    
    pos = node.find_first_of(WHITE, 0);
    posW+= pos;
    pos = node.find_first_of(WHITE, pos+1);
    posW += pos;
    pos = node.find_first_of(WHITE, pos+1);
    posW += pos;
    pos = node.find_first_of(BLACK, 0);
    posB += pos;
    pos = node.find_first_of(BLACK, pos+1);
    posB += pos;
    pos = node.find_first_of(BLACK, pos+1);
    posB += pos;
    Distance = 9 - (posB - posW);
    if(Distance<=0)
         Distance = 0;
    return Distance;
}
Example #22
0
File: dump.cpp Project: ANTco/mongo
    void go(const string& db,
            const string& coll,
            const Query& query,
            const boost::filesystem::path& outdir,
            const string& outFilename,
            bool usingMongos) {
        // Can only provide outFilename if db and coll are provided
        fassert(17368, outFilename.empty() || (!coll.empty() && !db.empty()));
        boost::filesystem::create_directories( outdir );

        map <string, BSONObj> collectionOptions;
        multimap <string, BSONObj> indexes;
        vector <string> collections;

        // Save indexes for database
        string ins = db + ".system.indexes";
        auto_ptr<DBClientCursor> cursor = conn( true ).query( ins.c_str() , Query() , 0 , 0 , 0 , QueryOption_SlaveOk | QueryOption_NoCursorTimeout );
        while ( cursor->more() ) {
            BSONObj obj = cursor->nextSafe();
            const string name = obj.getField( "ns" ).valuestr();
            indexes.insert( pair<string, BSONObj> (name, obj.getOwned()) );
        }

        string sns = db + ".system.namespaces";
        cursor = conn( true ).query( sns.c_str() , Query() , 0 , 0 , 0 , QueryOption_SlaveOk | QueryOption_NoCursorTimeout );
        while ( cursor->more() ) {
            BSONObj obj = cursor->nextSafe();
            const string name = obj.getField( "name" ).valuestr();
            if (obj.hasField("options")) {
                collectionOptions[name] = obj.getField("options").embeddedObject().getOwned();
            }

            // skip namespaces with $ in them only if we don't specify a collection to dump
            if (coll == "" && name.find(".$") != string::npos) {
                if (logger::globalLogDomain()->shouldLog(logger::LogSeverity::Debug(1))) {
                    toolInfoLog() << "\tskipping collection: " << name << std::endl;
                }
                continue;
            }

            // We use the collection name as the file name
            const string filename = name.substr( db.size() + 1 );

            //if a particular collections is specified, and it's not this one, skip it
            if (coll != "" && db + "." + coll != name && coll != name) {
                continue;
            }

            // If the user has specified that we should exclude certain collections, skip them
            std::vector<std::string>::const_iterator it =
                std::find(mongoDumpGlobalParams.excludedCollections.begin(),
                          mongoDumpGlobalParams.excludedCollections.end(), filename);

            if (it != mongoDumpGlobalParams.excludedCollections.end()) {
                if (logger::globalLogDomain()->shouldLog(logger::LogSeverity::Debug(1))) {
                    toolInfoLog() << "\tskipping explicitly excluded collection: " << name
                                  << std::endl;
                }
                continue;
            }

            std::string matchedPrefix;
            for (it = mongoDumpGlobalParams.excludeCollectionPrefixes.begin();
                 it != mongoDumpGlobalParams.excludeCollectionPrefixes.end(); it++) {
                if (startsWith(filename.c_str(), *it)) {
                    matchedPrefix = *it;
                    break;
                }
            }

            if (!matchedPrefix.empty()) {
                if (logger::globalLogDomain()->shouldLog(logger::LogSeverity::Debug(1))) {
                    toolInfoLog() << "\tskipping collection: " << name
                                  << " that matches exclude prefix: " << matchedPrefix
                                  << std::endl;
                }
                continue;
            }

            // raise error before writing collection with non-permitted filename chars in the name
            size_t hasBadChars = name.find_first_of("/\0");
            if (hasBadChars != string::npos){
                toolError() << "Cannot dump "  << name
                          << ". Collection has '/' or null in the collection name." << std::endl;
                continue;
            }

            if (nsToCollectionSubstring(name) == "system.indexes") {
              // Create system.indexes.bson for compatibility with pre 2.2 mongorestore
              const string filename = name.substr( db.size() + 1 );
              writeCollectionFile( name.c_str(), query, outdir / ( filename + ".bson" ),
                                   usingMongos );
              // Don't dump indexes as *.metadata.json
              continue;
            }

            if (nsToCollectionSubstring(name) == "system.users" &&
                    !mongoDumpGlobalParams.dumpUsersAndRoles) {
                continue;
            }

            collections.push_back(name);
        }
        
        for (vector<string>::iterator it = collections.begin(); it != collections.end(); ++it) {
            string name = *it;
            const string filename = outFilename != "" ? outFilename : name.substr( db.size() + 1 );
            writeCollectionFile( name , query, outdir / ( filename + ".bson" ), usingMongos );
            writeMetadataFile( name, outdir / (filename + ".metadata.json"), collectionOptions, indexes);
        }

    }
Example #23
0
void Feature::Parse(const string & optionName, const string & optionValue)
{
  if (optionName == "DISPLAY")
    displayName = optionValue;

  else if (optionName == "DEFINE") {
    string::size_type equal = optionValue.find('=');
    if (equal == string::npos)
      simpleDefineName = optionValue;
    else {
      simpleDefineName.assign(optionValue, 0, equal);
      simpleDefineValue.assign(optionValue, equal+1, INT_MAX);
    }
  }

  else if (optionName == "VERSION") {
    string::size_type equal = optionValue.find('=');
    if (equal != string::npos)
      defines.insert(pair<string,string>(optionValue.substr(0, equal), optionValue.substr(equal+1)));
  }

  else if (optionName == "CHECK_FILE") {
    string::size_type comma = optionValue.find(',');
    if (comma == string::npos)
      return;

    CheckFileInfo check;
    string::size_type pipe = optionValue.find('|');
    if (pipe < 0 || pipe > comma)
      check.fileName.assign(optionValue, 0, comma);
    else {
      check.fileName.assign(optionValue, 0, pipe);
      check.fileText.assign(optionValue, pipe+1, comma-pipe-1);
    }

    string::size_type equal = optionValue.find('=', comma);
    if (equal == string::npos)
      check.defineName.assign(optionValue, comma+1, INT_MAX);
    else {
      check.defineName.assign(optionValue, comma+1, equal-comma-1);
      check.defineValue.assign(optionValue, equal+1, INT_MAX);
    }

    checkFiles.push_back(check);
  }

  else if (optionName == "DIR_SYMBOL")
    directorySymbol = '@' + optionValue + '@';

  else if (optionName == "CHECK_DIR")
    checkDirectories.push_back(GetFullPathNameString(optionValue));

  else if (optionName == "FIND_FILE") {
    string::size_type comma1 = optionValue.find(',');
    if (comma1 == string::npos)
      return;

    string::size_type comma2 = optionValue.find(',', comma1+1);
    if (comma2 == string::npos)
      comma2 = INT_MAX-1;

    FindFileInfo find;
    find.symbol.assign(optionValue, 0, comma1);
    find.basename.assign(optionValue, comma1+1, comma2-comma1-1);
    find.subdir.assign(optionValue, comma2+1, INT_MAX);
    if (find.subdir.empty())
      find.subdir = "...";
    findFiles.push_back(find);
  }

  else if (optionName == "IF_FEATURE") {
    const char * delimiters = "&";
    string::size_type lastPos = optionValue.find_first_not_of(delimiters, 0);
    string::size_type pos = optionValue.find_first_of(delimiters, lastPos);
    while (string::npos != pos || string::npos != lastPos) {
      string str = optionValue.substr(lastPos, pos - lastPos);
      if (str[0] == '!')
        ifNotFeature.push_back(str.substr(1));
      else
        ifFeature.push_back(str);
      lastPos = optionValue.find_first_not_of(delimiters, pos);
      pos = optionValue.find_first_of(delimiters, lastPos);
    }
  }
}
Example #24
0
void Save::readShip(Ship* mShip, string& property, string& value)
{
	if (!readObject(mShip, property, value))
	{
		if (!property.compare("health"))
		{
			mShip->setHealth(stoi(value));
		}
		if (!property.compare("numFiredBullets"))
		{
			mShip->setNumFiredBullets(stoi(value));
		}
		if (!property.compare("score"))
		{
			mShip->setScore(stoi(value));
		}
		if (!property.compare("lastHitPlanet"))
		{
			mShip->setLastHitPlanet(stoi(value));
		}
		if (!property.compare("speed"))
		{
			mShip->setSpeed(stof(value));
		}
		if (!property.compare("acceleration"))
		{
			mShip->setAcceleration(stof(value));
		}
		if (!property.compare("jolt"))
		{
			mShip->setJolt(stof(value));
		}
		if (!property.compare("maxSpeed"))
		{
			mShip->setMaxSpeed(stof(value));
		}
		if (!property.compare("timer"))
		{
			mShip->setTimer(stof(value));
		}
		if (!property.compare("mAnimationStill"))
		{
			//Manage the animation
			getMI()->_animationManager->addToSurface(mShip->getAnimationStill(), value.c_str(), IND_ALPHA, IND_32);
			getMI()->_entity2dManager->add(mShip->getAnim2dShip());
			mShip->getAnim2dShip()->setAnimation(mShip->getAnimationStill());
			mShip->loadPropsAnim2d();

			// manage the 2d entity
			mShip->getEntity2d()->setPosition(mShip->getPosX(), mShip->getPosY(), 1);
			// set bounding areas
			mShip->getEntity2d()->setBoundingAreas("../SpaceGame/resources/Spaceship with motor new/spaceship_collisions.xml");
		}
		if (!property.compare("mAnimationShip"))
		{
			getMI()->_animationManager->addToSurface(mShip->getAnimationShip(), value.c_str(), IND_ALPHA, IND_32);
		}
		if (!property.compare("mAnimationLeft"))
		{
			getMI()->_animationManager->addToSurface(mShip->getAnimationLeft(), value.c_str(), IND_ALPHA, IND_32);
		}
		if (!property.compare("mAnimationRight"))
		{
			getMI()->_animationManager->addToSurface(mShip->getAnimationRight(), value.c_str(), IND_ALPHA, IND_32);
		}
		if (!property.compare("mAnimationExplode"))
		{
			getMI()->_animationManager->addToSurface(mShip->getAnimationExplode(), value.c_str(), IND_ALPHA, IND_32);
		}
		if (!property.compare(0, 6, "bullet"))
		{
			// extract the serial number of the bullet
			int id = std::stoi(property.substr(6, property.find_first_of("-") - 6));
			if (mShip->getBullets().size() <= id)
			{
				mShip->getBullets().push_back(new Bullet());
				mShip->getBullets().back()->setMI(getMI());
			}

			// change property so that it contains only the actual property of the bullet
			property = property.substr(property.find_first_of("-") + 1, property.find_first_of("]") - property.find_first_of("-") - 1);
			readBullet(mShip->getBullets().back(), property, value);
		}
	}
}
Example #25
0
bool Path::IsPathRooted( string path )
{
	return path.find_first_of(VolumeSeparatorChar()) > -1;
}
Example #26
0
void Rectan::Load(string &in)
{
	in.erase(0, in.find_first_of("\"") + 1);
	string temp = in.substr(0, in.find_first_of("\""));
	m_x1 = stoi(temp);
	in.erase(0, in.find_first_of("\"") + 1);

	in.erase(0, in.find_first_of("\"") + 1);
	temp = in.substr(0, in.find_first_of("\""));
	m_y1 = stoi(temp);
	in.erase(0, in.find_first_of("\"") + 1);

	int width, height;
	in.erase(0, in.find_first_of("\"") + 1);
	temp = in.substr(0, in.find_first_of("\""));
	width = stoi(temp);
	in.erase(0, in.find_first_of("\"") + 1);

	in.erase(0, in.find_first_of("\"") + 1);
	temp = in.substr(0, in.find_first_of("\""));
	height = stoi(temp);
	in.erase(0, in.find_first_of("\"") + 1);

	m_x2 = width + m_x1;
	m_y2 = height + m_y1;

	int r, g, b;
	in.erase(0, in.find_first_of("(") + 1);
	temp = in.substr(0, in.find_first_of(","));
	r = stoi(temp);
	in.erase(0, in.find_first_of(",") + 2);

	temp = in.substr(0, in.find_first_of(","));
	g = stoi(temp);
	in.erase(0, in.find_first_of(",") + 2);

	temp = in.substr(0, in.find_first_of(","));
	b = stoi(temp);
	m_Background_Color = Color(r, g, b);
	in.erase(0, in.find_first_of("\"") + 1);

	in.erase(0, in.find_first_of("(") + 1);
	temp = in.substr(0, in.find_first_of(","));
	r = stoi(temp);
	in.erase(0, in.find_first_of(",") + 2);

	temp = in.substr(0, in.find_first_of(","));
	g = stoi(temp);
	in.erase(0, in.find_first_of(",") + 2);

	temp = in.substr(0, in.find_first_of(","));
	b = stoi(temp);
	m_Color = Color(r, g, b);
	in.erase(0, in.find_first_of("\"") + 1);

	in.erase(0, in.find_first_of("\"") + 1);
	temp = in.substr(0, in.find_first_of("\""));
	m_Width = stof(temp);
	in.erase(0, in.find_first_of("\"") + 1);
}
Example #27
0
void ReturnAfternEqual(string & strTemp)
{
    size_t pos = strTemp.find_first_of('=');
    strTemp = strTemp.substr(pos + 1);
}
Example #28
0
	/**
	 * Helper
	 * @param idString is a String that have to be converted in a long
	 * @param id the id
	 */
	long PlanParser::fetchId(const string& idString, long id)
	{
		int hashPos = idString.find_first_of("#");
		char* temp = nullptr;
		char* temp2 = nullptr;
		string locator = idString.substr(0, hashPos);
		if (!locator.empty())
		{
			if (!supplementary::FileSystem::endsWith(this->currentDirectory, "/"))
			{
				this->currentDirectory = this->currentDirectory + "/";
			}
			string path = this->currentDirectory + locator;
			//not working no clue why
			//char s[2048];
			//char s2[2048];
			temp = realpath(path.c_str(), NULL);
			string pathNew = temp;
			free(temp);
			//This is not very efficient but necessary to keep the paths as they are
			//Here we have to check whether the file has already been parsed / is in the list for toparse files
			//problem is the normalization /home/etc/plans != /home/etc/Misc/../plans
			//list<string>::iterator findIterParsed = find(filesParsed.begin(), filesParsed.end(), pathNew);
			bool found = false;
			for(auto& it : filesParsed) {
				temp2 = realpath(it.c_str(), NULL);
				string pathNew2 =temp2;
				free(temp2);
				if(pathNew2 == pathNew) {
					found = true;
					break;
				}
			}

			//list<string>::iterator findIterToParse = find(filesToParse.begin(), filesToParse.end(), pathNew);
			if(!found) {
				for(auto& it : filesToParse) {
					temp2 = realpath(it.c_str(), NULL);
					string pathNew2 =temp2;
					free(temp2);
					if(pathNew2 == pathNew) {
						found = true;
						break;
					}
				}
			}


			if (!found)
			{
#ifdef PP_DEBUG
				cout << "PP: Adding " + path + " to parse queue " << endl;
#endif
				filesToParse.push_back(path);
			}
		}
		string tokenId = idString.substr(hashPos + 1, idString.length() - hashPos);
		try
		{
			id = stol(tokenId);
		}
		catch (exception& e)
		{
			ae->abort("PP: Cannot convert ID to long: " + tokenId + " WHAT?? " + e.what());
		}
		return id;
	}
Example #29
0
    bool packet::parse(const string& payload_ptr)
    {
        assert(!is_binary_message(payload_ptr)); //this is ensured by outside
        _frame = (packet::frame_type) (payload_ptr[0] - '0');
        _message.reset();
        _pack_id = -1;
        _buffers.clear();
        _pending_buffers = 0;
        size_t pos = 1;
        if (_frame == frame_message) {
            _type = (packet::type)(payload_ptr[pos] - '0');
            if(_type < type_min || _type > type_max)
            {
                return false;
            }
            pos++;
            if (_type == type_binary_event || _type == type_binary_ack) {
                size_t score_pos = payload_ptr.find('-');
                _pending_buffers = boost::lexical_cast<unsigned>(payload_ptr.substr(pos,score_pos - pos));
                pos = score_pos+1;
            }
        }

        size_t nsp_json_pos = payload_ptr.find_first_of("{[\"/",pos,4);
        if(nsp_json_pos==string::npos)//no namespace and no message,the end.
        {
            _nsp = "/";
            return false;
        }
        size_t json_pos = nsp_json_pos;
        if(payload_ptr[nsp_json_pos] == '/')//nsp_json_pos is start of nsp
        {
            size_t comma_pos = payload_ptr.find_first_of(",");//end of nsp
            if(comma_pos == string::npos)//packet end with nsp
            {
                _nsp = payload_ptr.substr(nsp_json_pos);
                return false;
            }
            else//we have a message, maybe the message have an id.
            {
                _nsp = payload_ptr.substr(nsp_json_pos,comma_pos - nsp_json_pos);
                pos = comma_pos+1;//start of the message
                json_pos = payload_ptr.find_first_of("\"[{", pos, 3);//start of the json part of message
                if(json_pos == string::npos)
                {
                    //no message,the end
                    //assume if there's no message, there's no message id.
                    return false;
                }
            }
        }
        else
        {
            _nsp = "/";
        }

        if(pos<json_pos)//we've got pack id.
        {
            _pack_id = boost::lexical_cast<int>(payload_ptr.substr(pos,json_pos - pos));
        }
        if (_frame == frame_message && (_type == type_binary_event || _type == type_binary_ack)) {
            //parse later when all buffers are arrived.
            _buffers.push_back(make_shared<string>(payload_ptr.data() + json_pos, payload_ptr.length() - json_pos));
            return true;
        }
        else
        {
            Document doc;
            doc.Parse<0>(payload_ptr.data()+json_pos);
            _message = from_json(doc, vector<shared_ptr<const string> >());
            return false;
        }

    }
Example #30
0
// Handle preprocessor comamnds in the input
void FileBuffer::handlePreproc(string fileDataLine)
{
    /*Thanks to the preprocessor step, the location of text in
        the input file rarely matches that in the source file, but
        locations should refer to source. The preprocessor handles
        this by inserting source file locations into its output.
        These consist of a hash, a number, and the file name in
        quotes. Hunt for them here and update the source file
        location accordingly

        Anything else starting with a hash is an actual
        preprocessor command. The source code should be run
        through the preprocessor before calling this routine,
        so finding one is an error. Issue a warning and ignore
        it */

    // Search for the location by trying to extract it.
    bool haveLocation = false;
    unsigned int lineNo = 0;
    string fileName;
    bool wasWrapped = _haveWrap; // Wrapped from previous line
    _haveWrap = hasEscNewline(fileDataLine, false); // Wraps to next line
    // Locations never wrap
    if ((!wasWrapped) && (!_haveWrap)) {
        // Find the line number
        unsigned short start = 0;
        unsigned short end = 0;
        start = fileDataLine.find_first_of('#');
        start = burnSpaces(fileDataLine, start + 1); // Actual text of command
        if (start != string::npos) { // Something on line other than hash
            if (isdigit(fileDataLine[start])) {
                // Find first non digit and extract line number
                end = fileDataLine.find_first_not_of("0123456789", start);
                if (end != string::npos) { // Something after the digits
                    /* NOTE: This is not the "official" way of extracting
                        an integer from a string, but it is the fastest */
                    lineNo = atoi(fileDataLine.substr(start, end-start).c_str());
                    /* The line gives the location of the next source line. Since reading
                        that line will increment the line counter, need to decrement it here
                        to compensate */
                    lineNo--;

                    // Find the first non-space after the digits. Must be a quote
                    start = burnSpaces(fileDataLine, end);
                    if (start != string::npos) { // Found more data
                        if (fileDataLine[start] == '"') {
                            start++;
                            // Find next quote and extract file name
                            end = fileDataLine.find_first_of('"', start);
                            if (end != string::npos) {
                                // Filename with no chars is illegal
                                if (end > start) {
                                    fileName = fileDataLine.substr(start, end - start);
                                    /* Find the first non-space after the just extracted
                                        file name. If any exist, it's not a location */
                                    end++;
                                    if (end != fileDataLine.length()) {
                                        end = burnSpaces(fileDataLine, end);
                                        haveLocation = (end == string::npos);
                                    } // Quote not last char on the line
                                    else
                                        haveLocation = true;
                                    if (haveLocation)
                                        _bufferPosition = FilePosition(fileName, lineNo);
                                } // Have at least one char between quotes
                            } // Quote at end of filename exists
                        } // Quote at start of filename exists
                    } // Have non-space after the line number
                } // More chars exist after the line number
            } // First thing after hash is a digit
        } // Have something after the hash
    } // Preprocessor command did not wrap

    /* If a file location was no found, this is an actual preprocessor command
        which indicates a processing error */
    if ((!haveLocation) && (!wasWrapped))
        cout << "WARNING: Preprocessor directive " << fileDataLine << " ignored on "
             << _inputPosition << ". Must g++ -E source files before calling" << endl;
}