Example #1
0
bool SetColorByName( const string& name , AIColor &color)
{
    if (name.compare("[Registration]") == 0)
    {
        color.kind = kCustomColor;
        color.c.c.tint = 0;
        sAICustomColor->NewRegistrationColor(&color.c.c.color, 1, 1, 1, 1, kCustomFourColor);
        return TRUE;
    }

    string colorName;
    float tint = 0;
    size_t found = 0;
    string buffer;

    AISwatchRef swatchRef;
    int numSwatches = 0;
    AIColor tempColor;
    ai::UnicodeString tempName;

    found = name.find("%");

    if (found != string::npos)
    {
        buffer = name.substr(0, found);
        tint = .01 * (100 - atoi(buffer.c_str()));
    }

    if(found == string::npos)
    {
        colorName = name.substr(found+1);
    }
    else
    {
        colorName = name.substr(found+2);
    }


    numSwatches = sAISwatchList->CountSwatches( NULL );
    for ( int i=0; i<numSwatches; i++)
    {
        swatchRef = sAISwatchList->GetNthSwatch( NULL , i );
        sAISwatchList->GetSwatchName( swatchRef, tempName );
        sAISwatchList->GetAIColor( swatchRef, &tempColor );
        if ( tempName == (ai::UnicodeString)colorName )
        {
            if (tempColor.kind != kCustomColor)
            {
                color = tempColor;
                return TRUE;
            }
            else if ( sAIRealMath->EqualWithinTol(tempColor.c.c.tint, tint, .01) )
            {
                color = tempColor;
                return TRUE;
            }
        }
    }

    return FALSE;
}
Example #2
0
string consume(string rdr, size_t& pos, string lmt = "\r\n") {
	size_t s = lmt.size(), l = rdr.find(lmt, pos) - pos;
	if(string::npos == l) throw ws::exception("Delimiter not found");
	pos += s += l;
	return rdr.substr(pos-s, l);
}
Example #3
0
void BeatBoard::IRCChannel::addUserJoin(string user){
  if(user.find('!')){
    user = user.substr(0, user.find('!'));
  }
  this->users.push_back(user);
}
Example #4
0
string DeleteLastLeter(string s)
{
	return s.substr(0, s.length() - 1);
}
Example #5
0
int Parser::getFirstNumberOf(string &line){
    size_t tab_start = line.find_first_of("\t");
    return atoi (line.substr(0, tab_start).c_str());
}
int get_1() {
    return atoi(line.substr(::plus+1, eq-::plus).c_str());
}
Example #7
0
	private : void ruleTruncate(string & word, char length) {
		if (atoi( &length ) > word.size()) return;
		word = word.substr(0, atoi( &length ));
	}
/**returns IP address from the string which is a particular line from config file
 * Input: string s - Particular line from config file
 */
string getIP(string s) {
	int pos = s.find(":");
	return s.substr(0,pos);
}
/**returns port from the string which is a particular line from config file
 * Input: string s - Particular line from config file
 */
string getPort(string s) {
	int pos = s.find(":");
	int pos1 = s.find(" ");
	return s.substr(pos+1,(pos1-1)-pos);
}
/*!
* Extracts and stores logical lines of code.
* Determines and extract logical SLOC to place in the result variable
* using addSLOC function. Each time the addSLOC function is called,
* a new logical SLOC is added. This function assumes that the directive
* is handled before it is called.
*
* \param result counter results
* \param line processed physical line of code
* \param lineBak original physical line of code
* \param strLSLOC processed logical string
* \param strLSLOCBak original logical string
* \param paren_cnt count of parenthesis
* \param forflag found for flag
* \param found_forifwhile found for, if, or while flag
* \param found_while found while flag
* \param prev_char previous character
* \param data_continue continuation of a data declaration line
* \param temp_lines tracks physical line count
* \param phys_exec_lines number of physical executable lines
* \param phys_data_lines number of physical data lines
* \param openBrackets number of open brackets (no matching close bracket)
* \param loopLevel nested loop level
*/
void CPerlCounter::LSLOC(results* result, string line, size_t lineNumber, string lineBak, string &strLSLOC, string &strLSLOCBak, unsigned int &paren_cnt,
	bool &forflag, bool &found_forifwhile, bool &found_while, char &prev_char, bool &data_continue,
	unsigned int &temp_lines, unsigned int &phys_exec_lines, unsigned int &phys_data_lines,
	unsigned int &openBrackets, StringVector &loopLevel)
{
	size_t start = 0; // starting index of the working string
	size_t i = 0, strSize, pos;
	bool do_boolean, trunc_flag = false;
	string exclude = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_";
	unsigned int cnt = 0;
	unsigned int loopCnt = 0;
	StringVector::iterator lit;
	string tmp = CUtil::TrimString(strLSLOC);
	string tmp2;

	// check for the keyword do
	do_boolean = (CUtil::FindKeyword(tmp, "do") == tmp.length() - 2);

	// check the entire line for SLOC present in it
	while (i < line.length())
	{
		if (line[i] == ';' || line[i] == '{')
		{
			// LSLOC terminators
			// ';' any valid perl command ends with a ';' terminator
			// do statements start with a '{' and ends with '}'

			if (line[i] == ';' && paren_cnt > 0)
			{
				// for a 'for' statement counter is incremented.
				i++;
				continue;
			}

			// record open bracket for nested loop processing
			if (print_cmplx)
			{
				if (line[i] == '{')
				{
					openBrackets++;
					if ((unsigned int)loopLevel.size() < openBrackets)
						loopLevel.push_back("");
				}
				else
				{
					if ((unsigned int)loopLevel.size() > openBrackets && openBrackets > 0)
						loopLevel.pop_back();
				}
			}

			if (found_while && found_forifwhile)
			{
				found_while = false;
				found_forifwhile = false;
				start = i + 1;
				i++;
				continue;
			}

			if (line[i] == '{')
			{
				// case for(...); and if (...) {
				// these specials are handled
				if (found_forifwhile)
				{
					found_forifwhile = false;
					start = i + 1;
					i++;
					continue;
				}

				// check if 'do' precedes '{'
				if (!do_boolean)
				{
					// find for 'do' in string before tmp string
					tmp = CUtil::TrimString(line.substr(start, i - start));

					// check for 'do' statement
					do_boolean = (tmp == "do");
				}
				if (do_boolean)
				{
					if (print_cmplx)
					{
						if (loopLevel.size() > 0) loopLevel.pop_back();
						loopLevel.push_back("do");
					}

					do_boolean = false;
					start = i + 1;
					i++;
					continue; // do not store '{' following 'do'
				}
			}

			if (line[i] == ';' && prev_char == '}')
			{
				i++;
				continue;
			}

			// the 'for(...)' or 'while(..)' or anything with the '{' on the next line gets counted as an extra SLOC
			// so to avoid that increment the counter and continue
			if (line[i] == '{' && prev_char == ')')
			{
				i++;
				continue;
			}

			// check for expression modifiers using 'foreach', 'while', 'if', 'unless', 'until' (for example, statement unless condition;)
			pos = string::npos;
			if (line[i] == ';')
			{
				// check for empty statement (=1 LSLOC)
				if (CUtil::TrimString(line.substr(start, i + 1 - start)) == ";" && strLSLOC.length() < 1)
				{
					strLSLOC = ";";
					strLSLOCBak = ";";
				}
				else
				{
					tmp = CUtil::TrimString(strLSLOC + line.substr(start, i + 1 - start));
					pos = CUtil::FindKeyword(tmp, "foreach");
					if (pos == string::npos)
					{
						pos = CUtil::FindKeyword(tmp, "while");
						if (pos == string::npos)

							pos = CUtil::FindKeyword(tmp, "if");
						if (pos == string::npos)
						{
							pos = CUtil::FindKeyword(tmp, "unless");
							if (pos == string::npos)
								pos = CUtil::FindKeyword(tmp, "until");
						}
					}
				}
			}
			if (pos != string::npos)
			{
				// capture statement before modifier
				tmp2 = CUtil::TrimString(strLSLOCBak + lineBak.substr(start, i - start));
				strSize = CUtil::TruncateLine(pos, 0, this->lsloc_truncate, trunc_flag);
				if (strSize > 0)
				{
					strLSLOC = tmp.substr(0, strSize);
					strLSLOCBak = tmp2.substr(0, strSize);
				}
				if (result->addSLOC(strLSLOCBak, lineNumber, trunc_flag))
					result->exec_lines[LOG]++;
				strLSLOC = "";
				strLSLOCBak = "";

				strSize = CUtil::TruncateLine(tmp.length() - pos, 0, this->lsloc_truncate, trunc_flag);
				if (strSize > 0)
				{
					strLSLOC = tmp.substr(pos, strSize);
					strLSLOCBak = tmp2.substr(pos, strSize);
				}
				if (result->addSLOC(strLSLOCBak, lineNumber, trunc_flag))
					result->exec_lines[LOG]++;
				found_forifwhile = false;
			}
			else
			{
				strSize = CUtil::TruncateLine(i - start, strLSLOC.length(), this->lsloc_truncate, trunc_flag);
				if (strSize > 0)
				{
					strLSLOC += line.substr(start, strSize);
					strLSLOCBak += lineBak.substr(start, strSize);
				}
				tmp = strLSLOC;
				if (result->addSLOC(strLSLOCBak, lineNumber, trunc_flag))
				{
					cnt = 0;
					CUtil::CountTally(strLSLOC, data_name_list, cnt, 1, exclude, "", "", &result->data_name_count);

					temp_lines++;
					if (data_continue == true)
					{
						result->data_lines[LOG]++;
						phys_data_lines = temp_lines;
					}
					else
					{
						if (cnt > 0)
						{
							result->data_lines[LOG]++;
							phys_data_lines = temp_lines;
						}
						else
						{
							result->exec_lines[LOG]++;
							phys_exec_lines = temp_lines;
						}
					}
				}
				else if (data_continue == true)
					phys_data_lines = temp_lines;
				else
					phys_exec_lines = temp_lines;
			}
			data_continue = false;
			temp_lines = 0;
			strLSLOC = "";
			strLSLOCBak = "";
			start = i + 1;
		}
		else if (line[i] == '}')
		{
			// also, {} is also skipped, empty block is not counted
			if (prev_char == ';' || prev_char == '{')
				start = i + 1; 

			// record close bracket for nested loop processing
			if (print_cmplx)
			{
				if (openBrackets > 0)
					openBrackets--;
				if (loopLevel.size() > 0)
					loopLevel.pop_back();
			}
		}
		else if (line[i] == '(')
		{ 
			if (!forflag)
			{
				// handle 'for', 'foreach', 'while', 'if', 'elsif,  and 'unless'
				tmp = "xxx " + CUtil::TrimString(line.substr(start, i));
				if ((CUtil::FindKeyword(tmp, "for") != string::npos) || (CUtil::FindKeyword(tmp, "foreach") != string::npos) ||
					(CUtil::FindKeyword(tmp, "while")!= string::npos) || (CUtil::FindKeyword(tmp, "if") != string::npos) ||
					(CUtil::FindKeyword(tmp, "elsif") != string::npos) || (CUtil::FindKeyword(tmp, "unless") != string::npos) ||
					(CUtil::FindKeyword(tmp, "until") != string::npos))
				{
					forflag = true;
					paren_cnt++;

					if (print_cmplx && (loopLevel.size() > openBrackets) && (openBrackets > 0))
						loopLevel.pop_back();

					if (CUtil::FindKeyword(tmp, "while")!= string::npos)
					{
						if (print_cmplx)
							loopLevel.push_back("while");
						found_while = true;
					}
					else if (CUtil::FindKeyword(tmp, "until")!= string::npos)
					{
						if (print_cmplx)
							loopLevel.push_back("until");
						found_while = true;
					}
					else if (print_cmplx)
					{
						if (CUtil::FindKeyword(tmp, "for") != string::npos)
							loopLevel.push_back("for");
						else if (CUtil::FindKeyword(tmp, "foreach") != string::npos)
							loopLevel.push_back("foreach");

						// record nested loop level
						if (CUtil::FindKeyword(tmp, "if") == string::npos && CUtil::FindKeyword(tmp, "elsif") == string::npos &&
							CUtil::FindKeyword(tmp, "unless") == string::npos)
						{
							loopCnt = 0;
							for (lit = loopLevel.begin(); lit < loopLevel.end(); lit++)
							{
								if ((*lit) != "")
									loopCnt++;
							}
							if ((unsigned int)result->cmplx_nestloop_count.size() < loopCnt)
								result->cmplx_nestloop_count.push_back(1);
							else
								result->cmplx_nestloop_count[loopCnt-1]++;
						}
					}
				}
			}
			else
				paren_cnt++;
		}
		else if (line[i] == ')')
		{
			/* 
			cases 
			'while(...);', 
			'while(...) {' and 
			'} while(...);' 
			is handled in this case
			*/
			if (forflag)
			{
				if (paren_cnt > 0)
					paren_cnt--;
				if (paren_cnt == 0)
				{
					// handling 'for', 'foreach', 'while', 'if', 'elsif', 'unless', 'until'
					// check for expression modifiers using 'foreach', 'while', 'if', 'unless', 'until' (for example, statement unless (condition);)
					tmp = CUtil::TrimString(strLSLOC + line.substr(start, i + 1 - start));
					pos = CUtil::FindKeyword(tmp, "foreach");
					if (pos == string::npos)
					{
						pos = CUtil::FindKeyword(tmp, "while");
						if (pos == string::npos)
						{
							pos = CUtil::FindKeyword(tmp, "if");
							if (pos == string::npos)
							{
								pos = CUtil::FindKeyword(tmp, "unless");
								if (pos == string::npos)
									pos = CUtil::FindKeyword(tmp, "until");
							}
						}
					}
					if (pos != string::npos)
					{
						// capture statement before modifier
						tmp2 = CUtil::TrimString(strLSLOCBak + lineBak.substr(start, i + 1 - start));
						strSize = CUtil::TruncateLine(pos, 0, this->lsloc_truncate, trunc_flag);
						if (strSize > 0)
						{
							strLSLOC = tmp.substr(0, strSize);
							strLSLOCBak = tmp2.substr(0, strSize);
						}
						if (result->addSLOC(strLSLOCBak, lineNumber, trunc_flag))
							result->exec_lines[LOG]++;
						strLSLOC = "";
						strLSLOCBak = "";

						strSize = CUtil::TruncateLine(tmp.length() - pos, 0, this->lsloc_truncate, trunc_flag);
						if (strSize > 0)
						{
							strLSLOC = tmp.substr(pos, strSize);
							strLSLOCBak = tmp2.substr(pos, strSize);
						}
						if (result->addSLOC(strLSLOCBak, lineNumber, trunc_flag))
							result->exec_lines[LOG]++;
						found_forifwhile = false;

						// skip trailing ';'
						tmp = CUtil::TrimString(line.substr(i + 1));
						if (tmp.length() > 0 && tmp[0] == ';')
							i++;
					}
					else
					{
						strSize = CUtil::TruncateLine(i + 1 - start, strLSLOC.length(), this->lsloc_truncate, trunc_flag);
						if (strSize > 0)
						{
							strLSLOC += line.substr(start, strSize);
							strLSLOCBak += lineBak.substr(start, strSize);
						}
						tmp = strLSLOC;
						if (result->addSLOC(strLSLOCBak, lineNumber, trunc_flag))
							result->exec_lines[LOG]++;
						found_forifwhile = true;
					}
					strLSLOC = "";
					strLSLOCBak = "";
					phys_exec_lines = temp_lines;
					temp_lines = 0;
					start = i + 1; 
					forflag = false;
				}
			}
		}

		if (line[i] != ' ' && line[i] != '\t')
		{
			// if ;}}} --> don't count }}} at all
			// also, if {}}} --> don't count }}} at all
			if (!(line[i] == '}' && (prev_char == ';' || prev_char == '{'))) // see case '}' above
				prev_char = line[i];

			// change to not found if a char appears before
			if (line[i] != ')' && found_forifwhile)
				found_forifwhile = false;

			if (CUtil::FindKeyword(line, "or", i, i + 2, true) == i)
			{
				strSize = CUtil::TruncateLine(i + 1 - start, strLSLOC.length(), this->lsloc_truncate, trunc_flag);
				if (strSize > 0)
				{
					strLSLOC += line.substr(start, strSize);
					strLSLOCBak += lineBak.substr(start, strSize);
				}
				tmp = strLSLOC;
				if (result->addSLOC(strLSLOCBak, lineNumber, trunc_flag))
					result->exec_lines[LOG]++;
				phys_exec_lines = temp_lines;
				temp_lines = 0;
				strLSLOC = "";
				strLSLOCBak = "";
				start = i;
			}
		}
		i++;
	}

	tmp2 = CUtil::TrimString(line.substr(start, i - start));
	strSize = CUtil::TruncateLine(tmp2.length(), strLSLOC.length(), this->lsloc_truncate, trunc_flag);
	if (strSize > 0)
	{
		strLSLOC += tmp2.substr(0, strSize);
		tmp2 = CUtil::TrimString(lineBak.substr(start, i - start));
		strLSLOCBak += tmp2.substr(0, strSize);
	}
	if (tmp == "")
		found_forifwhile = found_while = false;

	// make sure that we are not beginning to process a new data line
	cnt = 0;
	CUtil::CountTally(strLSLOC, data_name_list, cnt, 1, exclude, "", "", NULL);

	if (cnt > 0)
		data_continue = true;
	if (data_continue)
		temp_lines++;
	if (temp_lines == 0 && phys_data_lines == 0 && phys_exec_lines == 0)
		phys_exec_lines = 1;
}
void strsp(string &stringaGenerica){
   if(stringaGenerica.substr(0, 1) == " "){
       stringaGenerica.erase(0, 1);
   }
   return;
}
    string minWindow(string S, string T) {
        int minFrom = -1;
        int minSize = -1;

        ::memset(mTCount, 0, sizeof(mTCount));
        ::memset(mSCount, 0, sizeof(mSCount));

        // the number of characters in T
        int nT = 0;

        // initialize the info of T
        for (int i = 0; i < T.size(); ++i) {
            mTCount[T[i]]++;
            nT++;
        }
        
        int from = 0; //_from begins from the left most 

        // fix the _from, try to find the left most _to so that S[from, to] covers all the chars in T
        for (int to = 0; to < S.size(); ++to) {
            {
                char t = S[to];

                // update the count of chars in S[from, to]
                mSCount[t]++;
                
                // update the count of chars in T covered by S 
                // !! TRICK: if a char only appears in T for n time(s), we must not decrease the nT more than it.
                if (mSCount[t] <= mTCount[t]) {
                    nT--;
                }
            }
            
            // all the chars in T are covered by S[from, to]
            if (0 == nT) {
                // fix the _to, try to find the right most _from but still preserving the coverage of T
                while (true) {
                    char f = S[from++];
                    
                    // update the count of chars in S[from, to]
                    mSCount[f]--;

                    // the coverage is broken
                    if (mSCount[f] < mTCount[f]) {
                        nT++;
                        
                        // record the current minimum window 
                        int size = to - (from - 1) + 1;
                        if (-1 == minSize || size < minSize) {
                            minFrom = from - 1;
                            minSize = size;
                        }

                        break;  
                    }
                }
            }
        }

        return minSize <= 0 ? "" : S.substr(minFrom, minSize);
    }
 int Reversi::PlayOneStep(int y,string str,char playerChar,char targetChar)
 {
    string alphabet[]={"a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"};//Alphabet for X coordinate.
     int x=0,count=0,x1=0;
     int i,j=0,m=0,n=0;
     --y;

       while(x<52&&str.compare(alphabet[x])!=0)//counts for X coordinate
        ++x;
    if(x>=52)//if size of x larger than size of alphabet counts two letters for x coordinate.
     {
         x=0;
        while(x<52&&alphabet[x].compare(str.substr (1,2))!=0)//selects second argument of X coordinate and count it.
        ++x;

         while(x1<52&&str.substr(0,1).compare(alphabet[x1])!=0)//selects first argument of X coordinate and count it.
        ++x1;

        x=(x+1)*52+x1;//second argument multipled by  52 and added first index of first letter and count X coordinate.

     }
    i=x+1;//for Down
    j=y;
	while(i<gameCells[j].size()&&gameCells[j][i].getCellCh()==targetChar)
		++i;
	if(i<gameCells[j].size())
	{
		if(gameCells[j][i].getCellCh()==playerChar&&i!=x+1)
		{
			gameCells[j][x].getCellCh()=playerChar;
			for(m=x;m<i;++m)
			{
				gameCells[j][m].getCellCh()=playerChar;
			}
			++count;
		}
	}
    j=y;//for Up.
	i=x-1;
	while(i>=0&&gameCells[j][i].getCellCh()==targetChar)
		--i;
	if(i>=0)
	{
		if(gameCells[j][i].getCellCh()==playerChar&&i!=x-1)
		{
			gameCells[j][x-1].getCellCh()=playerChar;
			gameCells[j][x].getCellCh()=playerChar;
			for(m=i;m<x-1;++m)
			{
				gameCells[j][m].getCellCh()=playerChar;
			}
			++count;
		}
	}
    i=x;//for right.
	j=y+1;
	while(j<gameCells.size()&&gameCells[j][i].getCellCh()==targetChar)
		++j;

	if(j<gameCells.size())
	{
		if(gameCells[j][i].getCellCh()==playerChar&&j!=y+1)
		{
			gameCells[y][i].getCellCh()=playerChar;
			for(m=y+1;m<j;++m)
			{
				gameCells[m][i].getCellCh()=playerChar;
			}
			++count;
		}
	}
    i=x;//for left.
	j=y-1;
	while(j>=0&&gameCells[j][i].getCellCh()==targetChar)
		--j;
	if(j>=0)
	{
		if(gameCells[j][i].getCellCh()==playerChar&&j!=y-1)
		{
			gameCells[y][i].getCellCh()=playerChar;
			gameCells[y-1][i].getCellCh()=playerChar;
			for(m=j;m<y-1;++m)
			{
				gameCells[m][i].getCellCh()=playerChar;
			}
			++count;
		}
	}
	i=x-1;
	j=y-1;//up-left
	while(j>=0&&i>=0&&gameCells[j][i].getCellCh()==targetChar)
	{
		--i;
		--j;
	}
	if(j>=0&&i>=0)
	{
		if(gameCells[j][i].getCellCh()==playerChar&&i!=x-1&&j!=y-1)
		{

			gameCells[y][x].getCellCh()=playerChar;
			++count;
			m=j;
			n=i;
			while(m<y&&n<x)
			{
				gameCells[m][n].getCellCh()=playerChar;
				++m;
				++n;
			}
		}
	}
    i=x+1;
	j=y+1;//down-right
	while(j<gameCells.size()&&i<gameCells[j].size()&&gameCells[j][i].getCellCh()==targetChar)
	{
		++i;
		++j;
	}
	if(j<gameCells.size()&&i<gameCells[j].size())
	{
		if(gameCells[j][i].getCellCh()==playerChar&&i!=x+1&&j!=y+1)
		{

			++count;
			gameCells[y][x].getCellCh()=playerChar;
			gameCells[y+1][x+1].getCellCh()=playerChar;
			m=y+1;
			n=x+1;
			while(m<j&&n<i)
			{
				gameCells[m][n].getCellCh()=playerChar;
				++m;
				++n;
			}
		}
	}
	i=x+1;
	j=y-1;//left-down.
	while(j>=0&&i<i<gameCells[j].size()&&gameCells[j][i].getCellCh()==targetChar)
	{
		++i;
		--j;
	}
	if(j>=0&&i<gameCells[j].size())
	{
		if(gameCells[j][i].getCellCh()==playerChar&&i!=x+1&&j!=y-1)
		{

			++count;
			gameCells[y][x].getCellCh()=playerChar;
			m=y-1;
			n=x+1;
			while(m>j&&n<i)
			{
				gameCells[m][n].getCellCh()=playerChar;
				++n;
				--m;
			}
		}
	}
	i=x-1;
	j=y+1;//up-right
	while(j<gameCells.size()&&i>=0&&gameCells[j][i].getCellCh()==targetChar)
	{
		--i;
		++j;
	}
	if(j<gameCells.size()&&i>=0)
	{
		if(gameCells[j][i].getCellCh()==playerChar&&i!=x-1&&j!=y+1)
		{

			++count;
			gameCells[y][x].getCellCh()=playerChar;
			gameCells[y+1][x-1].getCellCh()=playerChar;
			m=y+1;
			n=x-1;
			while(m<j&&n>i)
			{
				gameCells[m][n].getCellCh()=playerChar;
				--n;
				++m;
			}
		}
	}
	totalLivingCells();//counts number of living cells.
	return count;
 }
void CFeatureHandler::LoadFeaturesFromMap(bool onlyCreateDefs)
{
	PrintLoadMsg("Initializing map features");

	int numType = readmap->GetNumFeatureTypes ();

	for (int a = 0; a < numType; ++a) {
		const string name = StringToLower(readmap->GetFeatureType(a));

		if (name.find("treetype") != string::npos) {
			FeatureDef* fd = SAFE_NEW FeatureDef;
			fd->blocking = 1;
			fd->burnable = true;
			fd->destructable = 1;
			fd->reclaimable = true;
			fd->drawType = DRAWTYPE_TREE;
			fd->modelType = atoi(name.substr(8).c_str());
			fd->energy = 250;
			fd->metal = 0;
			fd->reclaimTime = 250;
			fd->maxHealth = 5;
			fd->xsize = 2;
			fd->ysize = 2;
			fd->myName = name;
			fd->description = "Tree";
			fd->mass = 20;
			// trees by default have spherical collision volumes of fixed radius <TREE_RADIUS>
			fd->collisionVolume = SAFE_NEW CollisionVolume("", ZeroVector, ZeroVector, COLVOL_TEST_DISC);
			AddFeatureDef(name, fd);
		}
		else if (name.find("geovent") != string::npos) {
			FeatureDef* fd = SAFE_NEW FeatureDef;
			fd->blocking = 0;
			fd->burnable = 0;
			fd->destructable = 0;
			fd->reclaimable = false;
			fd->geoThermal = true;
			// geos are drawn into the ground texture and emit smoke to be visible
			fd->drawType = DRAWTYPE_NONE;
			fd->modelType = 0;
			fd->energy = 0;
			fd->metal = 0;
			fd->reclaimTime = 0;
			fd->maxHealth = 0;
			fd->xsize = 0;
			fd->ysize = 0;
			fd->myName = name;
			fd->mass = 100000;
			// geothermals have no collision volume at all
			fd->collisionVolume = 0;
			AddFeatureDef(name, fd);
		}
		else {
			if (GetFeatureDef(name) == NULL) {
				logOutput.Print("Unknown map feature type %s", name.c_str());
			}
		}
	}

	if (!onlyCreateDefs) {
		const int numFeatures = readmap->GetNumFeatures();
		MapFeatureInfo* mfi = SAFE_NEW MapFeatureInfo[numFeatures];
		readmap->GetFeatureInfo(mfi);

		for(int a = 0; a < numFeatures; ++a) {
			const string name = StringToLower(readmap->GetFeatureType(mfi[a].featureType));
			std::map<std::string, const FeatureDef*>::iterator def = featureDefs.find(name);

			if (def == featureDefs.end()) {
				logOutput.Print("Unknown feature named '%s'", name.c_str());
				continue;
			}

			const float ypos = ground->GetHeight2(mfi[a].pos.x, mfi[a].pos.z);
			(SAFE_NEW CFeature)->Initialize (float3(mfi[a].pos.x, ypos, mfi[a].pos.z),
			                                 featureDefs[name], (short int)mfi[a].rotation,
			                                 0, -1, "");
		}
		delete[] mfi;
	}
}
Example #15
0
static bool StartsWith(const string &s1, string s2) {
    if (s1.length()<s2.length()) return false;
    else return s1.substr(0,s2.length())==s2;
}
/**returns folder from the string which is a particular line from config file
 * Input: string s - Particular line from config file
 */
string getFolder(string s) {
	int pos = s.find(" ");
	if(pos==-1)
		pos = s.find("\t");
	return s.substr(pos+1);
}
KeyboardTarget::KeyState
KeyboardTarget::translate_key_name (const string& name)
{
	string::size_type i;
	string::size_type len;
	bool at_end;
	string::size_type hyphen;
	string keyname;
	string whatevers_left;
	KeyState result;
	unsigned int keycode;
	
	i = 0;
	len = name.length();
	at_end = (len == 0);

	while (!at_end) {

		whatevers_left = name.substr (i);

		if ((hyphen = whatevers_left.find_first_of ('-')) == string::npos) {
			
                        /* no hyphen, so use the whole thing */
			
			keyname = whatevers_left;
			at_end = true;

		} else {

			/* There is a hyphen. */
			
			if (hyphen == 0 && whatevers_left.length() == 1) {
				/* its the first and only character */
			
				keyname = "-";
				at_end = true;

			} else {

				/* use the text before the hypen */
				
				keyname = whatevers_left.substr (0, hyphen);
				
				if (hyphen == len - 1) {
					at_end = true;
				} else {
					i += hyphen + 1;
					at_end = (i >= len);
				}
			}
		}
		
// 		if (keyname.length() == 1 && isupper (keyname[0])) {
// 			result.push_back (WXK_SHIFT);
// 		}
		
		if ((keycode = keycode_from_name (wxString::FromAscii(keyname.c_str()))) == 0) {
			cerr << "KeyboardTarget: keyname " <<  keyname << "  is unknown" << endl;
			result.clear();
			return result;
		}
		
		result.push_back (keycode);
	}

	sort (result.begin(), result.end());

	return result;
}
Example #18
0
int Options::define(const string& aDefinition) {
   Option_register* definitionEntry = NULL;

   // Error if definition string doesn't contain an equals sign
   auto location = aDefinition.find("=");
   if (location == string::npos) {
      cerr << "Error: no \"=\" in option definition: " << aDefinition << endl;
      exit(1);
   }

   string aliases = aDefinition.substr(0, location);
   string rest    = aDefinition.substr(location+1);
   string otype   = rest;
   string ovalue  = "";

   location = rest.find(":");
   if (location != string::npos) {
      otype  = rest.substr(0, location);
      ovalue = rest.substr(location+1);
   }

   // Remove anyspaces in the option type field
   otype.erase(remove_if(otype.begin(), otype.end(), ::isspace), otype.end());
   
   // Option types are only a single charater (b, i, d, c or s)
   if (otype.size() != 1) {
      cerr << "Error: option type is invalid: " << otype 
           << " in option definition: " << aDefinition << endl;
      exit(1);
   }

   // Check to make sure that the type is known
   if (otype[0] != OPTION_STRING_TYPE  &&
       otype[0] != OPTION_INT_TYPE     &&
       otype[0] != OPTION_FLOAT_TYPE   &&
       otype[0] != OPTION_DOUBLE_TYPE  &&
       otype[0] != OPTION_BOOLEAN_TYPE &&
       otype[0] != OPTION_CHAR_TYPE ) {
      cerr << "Error: unknown option type \'" << otype[0]
           << "\' in defintion: " << aDefinition << endl;
      exit(1);
   }

   // Set up space for a option entry in the registry
   definitionEntry = new Option_register(aDefinition, otype[0], ovalue);

   auto definitionIndex = optionRegister.size();

   // Store option aliases
   string optionName;
   unsigned int i;
   aliases += '|';
   for (i=0; i<aliases.size(); i++) {
      if (::isspace(aliases[i])) {
         continue;
      } else if (aliases[i] == '|') {
         if (isDefined(optionName)) {
            cerr << "Option \"" << optionName << "\" from definition:" << endl;
            cerr << "\t" << aDefinition << endl;
            cerr << "is already defined in: " << endl;
            cerr << "\t" << getDefinition(optionName) << endl;
            exit(1);
         }
         if (optionName.size() > 0) {
            optionList[optionName] = definitionIndex;
         }
         optionName.clear();
      } else {
         optionName += aliases[i];
      }
   }

   // Store definition in registry and return its indexed location.
   // This location will be used to link option aliases to the main
   // command name.
   optionRegister.push_back(definitionEntry);
   return definitionIndex;
}
int get_2() {
    return atoi(line.substr(eq+1).c_str());
}
Example #20
0
string SplitLP::get_opp_name(string name)const{
    return is_pos(name) ? NEG_TAG + name : name.substr(1);
}
 bool valid(const string &s, const int first, const int last) {
     if (first >= last || last - first > 3) return false;
     if (last - first > 1 && s[first] == '0') return false;
     int num = std::stoi(s.substr(first, last - first));
     return num >= 0 && num <= 255;
 }
Example #22
0
    void go( const string db , const boost::filesystem::path outdir ) {
        log() << "DATABASE: " << db << "\t to \t" << outdir.string() << endl;

        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 ) {
                LOG(1) << "\tskipping collection: " << name << endl;
                continue;
            }

            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;

            // 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){
              error() << "Cannot dump "  << name << ". Collection has '/' or null in the collection name." << endl;
              continue;
            }

            if ( endsWith(name.c_str(), ".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() , outdir / ( filename + ".bson" ) );
              // Don't dump indexes as *.metadata.json
              continue;
            }
            
            if ( _coll != "" && db + "." + _coll != name && _coll != name )
              continue;
            
            collections.push_back(name);
        }
        
        for (vector<string>::iterator it = collections.begin(); it != collections.end(); ++it) {
            string name = *it;
            const string filename = name.substr( db.size() + 1 );
            writeCollectionFile( name , outdir / ( filename + ".bson" ) );
            writeMetadataFile( name, outdir / (filename + ".metadata.json"), collectionOptions, indexes);
        }

    }
Example #23
0
/**
 * load DataModel to CHAT file
 * @param filename CHAT file to write
 * @param id AGSet Id
 * @param options save options : corpus name, data model adress, load mode (full or not)
 * @return ""
 */
string
CHAT::store(const string& filename,
			const string& id,
			map<string,string>* options)     throw (agfio::StoreError)
{
	try {
		string addr= "";
		string corpusName = "";
		map<string,string>::iterator it;
		tag::DataModel* data = NULL;

		if ( (it = options->find("&datamodel")) != options->end() )  addr = it->second;
		if (  addr != "" ) {
			// data model adress passed by caller -> use it
			data = (tag::DataModel*)strtoul(addr.c_str(), NULL, 16);
		} else {
			// TODO : initialize data model from agset Id
//			data = new tag::DataModel(id);
			throw agfio::StoreError("No datamodel address provided");
		}


		// -- Single track export --
		int nbtracks = data->getNbTracks();

		ostream* out = &cout;

		if (nbtracks == 1)
		{
			if ( filename != "" )
			{
				ofstream* fout = new ofstream(filename.c_str());
				if ( ! fout->good() )
					throw agfio::StoreError(string("Can't open file for writing: ")+filename);
				out = fout;
			}

			CHATWriter writer;

			writer.setTrackID(-1);
			writer.write(*out, data, FileInfo(filename).rootname());

			if ( filename != "" )
				((ofstream*)out)->close();
		}

		// -- Multiple tracks --
		if (nbtracks > 1)
		{
			string rootname = filename.substr(0, filename.find_last_of("."));

			for(int i=0; i<nbtracks; i++)
			{
				// -- Renaming : file.cha -> file_N.cha --
				string trackname = rootname + "_";
				trackname += i;
				trackname += ".cha";

				// -- Writing CHA file --
				ofstream* fout = new ofstream(trackname.c_str());
				if ( ! fout->good() )
					throw agfio::StoreError(string("Can't open file for writing: ") + trackname);
				out = fout;

				CHATWriter writer;

				writer.setTrackID(i);
				writer.write(*out, data, FileInfo(trackname).rootname());

				if ( trackname != "" )
					((ofstream*)out)->close();
			}
		}

	} catch (agfio::StoreError& e) {
		throw e;
	}
	catch (const char* msg) {
		throw agfio::StoreError("\nCHAT format: " + string(msg));
	}
	return "";
}
Example #24
0
//interpretacao e execucao de comando
//forma <pilha_origem>,<posicao_origem>,<pilha_destino>, em numero
int YUKON_CLI::interpretar(string cmd){
	
	bool ok;
	
	if (cmd == ""){
		if (verificaFimJogo())
			return 3;
		return 2;
	}
	
	if(cmd=="novo"||cmd=="novojogo"){
		YUKON::novoJogo();
		return 4;
	}
	
	if (cmd=="fechar")
		return 3;
	
	int origemp;	//pilha de origem
	int origemc;	//carta de origem
	int destino;	//pilha de destino
	
	unsigned int posvirg1 = cmd.find(",");	//posicao da 1a virgula
	unsigned int posvirg2 = cmd.rfind(",");	//posicao da 2a (ultima) virgula
	if ((posvirg1 != string::npos)&&(posvirg2 != string::npos)){	//se foi obtido posicao das duas virgulas, faca:
		origemp = atoi((cmd.substr(0,posvirg1)).data());
		origemc = atoi((cmd.substr(posvirg1+1,posvirg2-posvirg1)).data());
		destino = atoi((cmd.substr(posvirg2+1,cmd.size()-posvirg2)).data());
		
	}
	else{
		cout << "formato de comando incorreto!" << endl;
		return 1;
	}
	
	if(destino==8)
		cout <<"Movendo carta "<<origemc<<" da pilha "<<origemp<<" para a fundamento " << endl;
	else
		cout <<"Movendo carta "<<origemc<<" da pilha "<<origemp<<" para a pilha "<<destino << endl;
	
	if (origemp>7||origemp<0||destino>7||destino<0) {
		cout << "origem ou destino e incorreto!" << endl;
		return 1;
	}
	
	MONTE * monteOrigem = getMonte(origemp);
	
	if (monteOrigem->getTamanho()<0) // ??????????????? 0 é vazio ou tem 1 elemento ??????????????????
		cout << "monte nao possui nenhuma carta!" << endl;
	if(origemp == destino)
		cout<< "Coluna de origem igual coluna de destino" << endl;
	else
		if (destino==7){
			fundacao.receberCarta(monteOrigem, ok);
			if(!ok)
				cout << "Esse movimento não é possível." <<  endl;
		} else {
			MONTE * monteDestino = getMonte(destino);
			monteDestino->receberCartas(monteOrigem, origemc, ok);
			if(!ok)
				cout << "Esse movimento nao é possivel."<<endl;
		}
		
		/*cout << "pos1=" << posvirg1 << endl;
		 * cout << "pos2=" << posvirg2 << endl;*/
		return 0;
}
Example #25
0
bool MtlLibrary :: readMapChannel (const string& str, unsigned int target, ostream& r_logstream)
{
	assert(target < CHANNEL_TARGET_TYPES);

	string filename;
	unsigned char channel;
	double bump_multiplier = 1.0;

	size_t index;
	unsigned int current_material;

	current_material = mvp_materials.size() - 1;

	if(target == CHANNEL_TARGET_DECAL)
		channel = Material::CHANNEL_MATTE;
	else
		channel = Material::CHANNEL_LUMINANCE;

	if(isspace(str[0]))
		index = nextToken(str, 0);
	else
		index = 0;

	filename = str.substr(index, getTokenLength(str, index));
	if(filename.compare("") == 0 || isMaterial(filename))
		return false;

	index = nextToken(str, index);
	while(index != string::npos)
	{
		string token;

		token = str.substr(index, getTokenLength(str, index));
		if(token.compare("-imfchan") == 0)
		{
			index = nextToken(str, index);
			if(index == string::npos)
				return false;

			token = str.substr(index, getTokenLength(str, index));
			if(token.compare("r") == 0)
				channel = Material::CHANNEL_RED;
			else if(token.compare("g") == 0)
				channel = Material::CHANNEL_GREEN;
			else if(token.compare("b") == 0)
				channel = Material::CHANNEL_BLUE;
			else if(token.compare("m") == 0)
				channel = Material::CHANNEL_MATTE;
			else if(token.compare("l") == 0)
				channel = Material::CHANNEL_LUMINANCE;
			else if(token.compare("z") == 0)
				channel = Material::CHANNEL_Z_DEPTH;
			else
				return false;
		}
		else if(token.compare("-bm") == 0)
		{
			if(channel != CHANNEL_TARGET_BUMP)
				return false;

			index = nextToken(str, index);
			if(index == string::npos)
				return false;

			bump_multiplier = atof(str.c_str() + index);
		}

		index = nextToken(str, index);
	}

	switch(target)
	{
	case CHANNEL_TARGET_SPECULAR_EXPONENT:
		mvp_materials[current_material]->setSpecularExponentMap(filename, channel);
		break;
	case CHANNEL_TARGET_TRANSPARENCY:
		mvp_materials[current_material]->setTransparencyMap(filename, channel);
		break;
	case CHANNEL_TARGET_DECAL:
		mvp_materials[current_material]->setDecalMap(filename, channel);
		break;
	case CHANNEL_TARGET_DISPLACEMENT:
		mvp_materials[current_material]->setDisplacementMap(filename, channel);
		break;
	case CHANNEL_TARGET_BUMP:
		mvp_materials[current_material]->setBumpMap(filename, channel, bump_multiplier);
		break;
	}

	return true;
}
Example #26
0
static bool
merge_mates(const size_t suffix_len, const size_t range,
            const MappedRead &one, const MappedRead &two,
            MappedRead &merged, int &len) {
  
  const bool pos_str = one.r.pos_strand();
  const size_t overlap_start = max(one.r.get_start(), two.r.get_start());
  const size_t overlap_end = min(one.r.get_end(), two.r.get_end());

  const size_t one_left = pos_str ? 
    one.r.get_start() : max(overlap_end, one.r.get_start());
  const size_t one_right = 
    pos_str ? min(overlap_start, one.r.get_end()) : one.r.get_end();
  
  const size_t two_left = pos_str ? 
    max(overlap_end, two.r.get_start()) : two.r.get_start();
  const size_t two_right = pos_str ? 
    two.r.get_end() : min(overlap_start, two.r.get_end());

  len = pos_str ? (two_right - one_left) : (one_right - two_left);
  
  if(len < 0){
    cerr << one << endl;
    cerr << two << endl;
    return false;
  }
  // assert(len > 0);
  // assert(one_left <= one_right && two_left <= two_right);
  // assert(overlap_start >= overlap_end || static_cast<size_t>(len) == 
  //    ((one_right - one_left) + (two_right - two_left) + (overlap_end - overlap_start)));
  
  string seq(len, 'N');
  string scr(len, 'B');
  if (len >= 0 && len <= static_cast<int>(range)) {
    // lim_one: offset in merged sequence where overlap starts
    const size_t lim_one = one_right - one_left;
    copy(one.seq.begin(), one.seq.begin() + lim_one, seq.begin());
    copy(one.scr.begin(), one.scr.begin() + lim_one, scr.begin());
    
    const size_t lim_two = two_right - two_left;
    copy(two.seq.end() - lim_two, two.seq.end(), seq.end() - lim_two);
    copy(two.scr.end() - lim_two, two.scr.end(), scr.end() - lim_two);
    
    // deal with overlapping part
    if (overlap_start < overlap_end) {
      const size_t one_bads = count(one.seq.begin(), one.seq.end(), 'N');
      const int info_one = one.seq.length() - (one_bads + one.r.get_score());
      
      const size_t two_bads = count(two.seq.begin(), two.seq.end(), 'N');
      const int info_two = two.seq.length() - (two_bads + two.r.get_score());
      
      // use the mate with the most info to fill in the overlap
      if (info_one >= info_two)
	fill_overlap(pos_str, one, overlap_start, overlap_end, lim_one, seq, scr);
      else
	fill_overlap(pos_str, two, overlap_start, overlap_end, lim_one, seq, scr);
    }
  }
  
  merged = one;
  merged.r.set_start(pos_str ? one.r.get_start() : two.r.get_start());
  merged.r.set_end(merged.r.get_start() + len);
  merged.r.set_score(one.r.get_score() + two.r.get_score());
  merged.seq = seq;
  merged.scr = scr;  
  const string name(one.r.get_name());
  merged.r.set_name("FRAG:" + name.substr(0, name.size() - suffix_len));

  return true;
}
string rand_pattern(int len)
{
    return text.substr(rand()%(text.size()-len),len);
}
Example #28
0
#define mp make_pair
#define LL long long

using namespace std;

string s;

string s05;

int main() {
	// your code goes here
	cin>>s;
	int period = 0;
	FOR(i,0,s.size())
		if (s[i] == '.')
			period = i;
	string s1 = s.substr(0, period);
	string s2 = s.substr(period + 1, s.size() - period - 1);
	s05 = "5";
	while (s05.size() < s2.size())
		s05 += '0';
	if (s1[s1.size() - 1] == '9') {
		cout << "GOTO Vasilisa." << endl;
	} else {
		if (s2 >= s05)
			s1[s1.size() - 1]++;
		cout<<s1<<endl;
	}
	return 0;
}
Example #29
0
//TODO: Calibration?
//TODO: move this function?
string getLabel(const string& filepath){
	int start = filepath.find_last_of("/") + 1;
	return	filepath.substr(start, filepath.find_last_of("_") - start);
}
Example #30
0
string trim_left_copy(
        const string& s,
        const string& delimiters = " \f\n\r\t\v" )
{
    return s.substr( s.find_first_not_of( delimiters ) );
}