std::string CEqParserV2::_getFcnSubstr(std::string &equation, int &it)
{
	//-//-//-//-//-//-//-//-//-//-//-//
	// Example:	2+func((2+1),3)+42
	//            ^           ^
	//-//-//-//-//-//-//-//-//-//-//-//
	bool doExit = false;
	bool initOk = false;
	int parCount = 0;
	std::string rVal = "";

	while ((unsigned)it < equation.length() && !doExit)
	{
		char chr = equation.at(it);
		it++;

		int parCountDelta = cc::parseParanthesis(chr);
		parCount += parCountDelta;
		if (parCountDelta==1)
		{
			parCount++;
			initOk = true;
		}

		rVal.push_back(chr);

		if (initOk && parCount == 0)
		{
			return rVal;
		}
		

	}
	
	return "";

}
Example #2
0
void WorldSession::LoadSecurity(std::string securitystring)
{
	std::list<char> tmp;
	bool hasa = false;
	for(uint32 i = 0; i < securitystring.length(); ++i)
	{
		char c = securitystring.at(i);
		c = tolower(c);
		if(c == '4' || c == '3')
			c = 'a';	// for the lazy people

		if(c == 'a')
		{
			// all permissions
			tmp.push_back('a');
			hasa = true;
		}
		else if(!hasa && (c == '0') && i == 0)
			break;
		else if(!hasa || (hasa && (c == 'z')))
		{
			tmp.push_back(c);
		}
	}

	permissions = new char[tmp.size()+1];
	memset(permissions, 0, tmp.size()+1);
	permissioncount = (uint32)tmp.size();
	int k = 0;
	for(std::list<char>::iterator itr = tmp.begin(); itr != tmp.end(); ++itr)
		permissions[k++] = (*itr);
	
	if(permissions[tmp.size()] != 0)
		permissions[tmp.size()] = 0;

	sLog.outDebug("Loaded permissions for %u. (%u) : [%s]", this->GetAccountId(), permissioncount, securitystring.c_str());
}
  /*!
   * @if jp
   * @brief 文字列の分割
   * @else
   * @brief Split of string
   * @endif
   */
  unsigned int CorbaNaming::split(const std::string& input,
				  const std::string& delimiter,
				  std::vector<std::string>& results)
  {
    typedef std::string::size_type size;
    size delim_size = delimiter.size();
    size found_pos(0), begin_pos(0), pre_pos(0), substr_size(0);
    
    if (input.substr(0, delim_size) == delimiter)
      begin_pos = pre_pos = delim_size;
    
    while (1)
      {
      REFIND:
	found_pos = input.find(delimiter, begin_pos);
	if (found_pos == std::string::npos) 
	  {
	    results.push_back(input.substr(pre_pos));
	    break;
	  }
	if ('\\' == input.at(found_pos - 1))
	  {
	    begin_pos = found_pos + delim_size;
	    goto REFIND;
	  }
	
	substr_size = found_pos - pre_pos;
	
	if (substr_size > 0)
	  {
	    results.push_back(input.substr(pre_pos, substr_size));
	  }
	begin_pos = found_pos + delim_size;
	pre_pos   = found_pos + delim_size;
      }
    return results.size();
  }
Example #4
0
void c_rpc_server::c_session::send_response(nlohmann::json json_response)
{
	try {
		const std::string response = json_response.dump();
		assert(response.size() <= std::numeric_limits<uint16_t>::max());
		uint16_t size = static_cast<uint16_t>(response.size());
		m_write_data.resize(size + 2); ///< 2 first bytes for size
		m_write_data.at(0) = static_cast<char>(size >> 8);
		m_write_data.at(1) = static_cast<char>(size & 0xFF);
		for (size_t i = 0; i < response.size(); ++i)
			m_write_data.at(i + 2) = response.at(i);
		// send response

		dbg("send packet");
		dbg(m_write_data);
		std::array<unsigned char, crypto_auth_hmacsha512_BYTES> hash;
		int ret = crypto_auth_hmacsha512(hash.data(), reinterpret_cast<unsigned char *>(&m_write_data.at(2)), size, m_rpc_server_ptr->m_hmac_key.data());
		if (ret != 0) _throw_error(std::runtime_error("crypto_auth_hmacsha512 error"));
		dbg("hmac");
		//for (const auto & byte : hash) std::cout << std::hex << "0x" << static_cast<int>(byte) << " ";
		//std::cout << std::dec << std::endl;
		std::array<boost::asio::const_buffer, 2> buffers = {
			{boost::asio::buffer(m_write_data.data(), m_write_data.size()),
			boost::asio::buffer(hash.data(), hash.size())}
		};
		m_socket.async_write_some(buffers,
			[this](const boost::system::error_code& error, std::size_t bytes_transferred) {
				write_handler(error, bytes_transferred);
		});
	}
	catch (const std::exception &e) {
		_erro( "exception in execute_rpc_command " << e.what() );
		_erro( "close connection\n" );
		delete_me();
		return;
	}
}
Example #5
0
std::string Util::nameToDescription(const std::string& name)
{
    std::stringstream ss;

    bool prevWasUpper = false;
    bool nextToUpper = false;

    for (int i = 0; i < name.length(); i++)
    {
        char c = name.at(i);

        if (isupper(c))
        {
            if (!prevWasUpper && i != 0)
            {
              ss <<" ";
            }
            prevWasUpper = true;
        }else {
            prevWasUpper = false;
        }

        if (i == 0 || nextToUpper) {
            c = toupper(c);
            nextToUpper = false;
        }

        if (c == '_') {
            ss <<" ";
            nextToUpper = true;
        }else{
            ss <<c;
        }
    }

    return ss.str();
}
Example #6
0
std::string RemoveComments(const std::string Str)
{
    std::string Result;
    int k = 0;
    int AwatingEOL = 0;
    ptrdiff_t len = Str.length() - 1;

    for (ptrdiff_t i = 0; i < len; i++)
    {
        if (AwatingEOL)
        {
            if (Str[i] != '\n')
                continue;
            else
            {
                AwatingEOL = 0;
                continue;
            }
        }
        else
        {
            if (Str[i] == '/' && Str[i + 1] == '/')
            {
                AwatingEOL = true;
                continue;
            }
            else
            {
                Result.push_back(Str.at(i));
                k++;
            }
        }
    }

    Utility::ReplaceAll(Result, "[\\n\\r ]", "");
    return Result;
}
Example #7
0
   bool stage_t::set_dir( std::string const & dir)
   {
       if ( dir_exists(dir)){
            if ( (m_temp_dir_name != "") && (m_remove_dir_on_exit == true) && (m_temp_dir_name != dir)){
                std::string cmd = "rmdir " + m_temp_dir_name;
               // std::cout  <<" cmd is " << cmd << '\n';
                int result =  system (cmd.c_str());
                if (result == -1){
                  std::cout << "warning couldnt remove old temp dir\n";
                }
            }
            m_remove_dir_on_exit = false;
            if ( dir.at(dir.length() -1) != get_platform()->get_dir_sep().at(0)){
               m_temp_dir_name = dir + get_platform()->get_dir_sep();
            }else{
              m_temp_dir_name = dir;
            }

            return true;
       }else{
         std::cout << "dir not found\n";
         return false;
       }
   }
bool Database::filterIsValid(std::string filter) {

	/* Clean the filter term of any caps*/
	std::string cleaned = "";
	for (unsigned int i = 0; i < filter.length(); ++i) {
		cleaned.push_back(tolower(filter.at(i)));
	}

	if (cleaned.compare("age") == 0) return true;
	else if (cleaned.compare("ssn") == 0) return true;
	else if (cleaned.compare("email") == 0) return true;
	else if (cleaned.compare("phone") == 0) return true;
	else if (cleaned.compare("job") == 0) return true;

	if (filter.compare("age") == 0) return true;
	else if (filter.compare("ssn") == 0) return true;
	else if (filter.compare("email") == 0) return true;
	else if (filter.compare("phone") == 0) return true;
	else if (filter.compare("job") == 0) return true;

	std::cout << "Error: Invalid filter" << std::endl;
	return false;
	
}
Example #9
0
void dump()
{
	const std::string grayscale = " .'`^\",:;Il!i><~+_-?][}{1)(|\\/tfjrxnuvczXYUJCLQ0OZmwqpdbkhao*#MW&8%[email protected]$";
	std::cerr << "\n";
	double max = 0.0;
	for(double f: frequencies) {
		max = std::max(f, max);
	}
	const double scale = (grayscale.size() - 1) / max;
	static bool printed = false;
	if(printed) {
		std::cerr << "\033[19A";
	}
	std::cerr << "+--------------------------------------------------+\n";
	for(uint h = 0 ; h < 256; h += 16) {
		std::cerr << "|";
		for(uint l = 0 ; l < 16; l += 1) {
			std::cerr << "  " << grayscale.at(scale * frequencies[h + l]);
		}
		std::cerr << "  |\n";
	}
	std::cerr << "+--------------------------------------------------+\n";
	printed = true;
}
Example #10
0
std::vector< std::string > list_devices( std::string p, unsigned char t, bool rec )
{
    std::vector< std::string >  v_dev;
    DIR                        *dir;
    struct dirent              *dir_ent;

    // optionally correction of path param
    if( p.at( p.length()-1 ) != '/' ) { p += '/'; }

    if( (dir = opendir( p.c_str() )) )
    {
        while( (dir_ent = readdir( dir )) )
        {
            if( (strcmp( dir_ent->d_name, "." )  == 0) || 
                (strcmp( dir_ent->d_name, ".." ) == 0) 
            ) { continue; /* ignore + jump to next */ }
            else
            {
                std::string tmp_str = p;
                tmp_str += dir_ent->d_name; 

                if( dir_ent->d_type == t )
                    { v_dev.push_back( std::string( tmp_str ) ); } 
                if( (dir_ent->d_type == DT_DIR) && rec )
                {
                    std::vector< std::string > tmp_v;
                    v_dev.push_back( std::string( tmp_str ) );
                    tmp_v = list_devices( tmp_str, t, rec );
                    v_dev.insert( v_dev.end(), tmp_v.begin(), tmp_v.end() );
                } else { continue; /* ignore + jump to next */ }
            } // end pathcheck if
        } // end while loop
        closedir( dir );
    } else { /* nothing to do */ }
    return v_dev;
}
vector<size_t> MicroCompiler::_ParseArgumentIndices(const std::string &action)
{
   vector<size_t> indices;
   bool isIndex(false);
   for(size_t i = 0; i < action.size(); i++)
   {
      if (action.at(i) == '$') 
      {
         if (isIndex)
         {
            indices.push_back(_LeftIndex);
            isIndex = false;
         }
         else
            isIndex = true;
            continue;
      }
      else if(isIndex)
      {
         const size_t comma = action.find_first_of(',', i);
         const size_t rParen = action.find_first_of(')', i);
         const size_t numBytes = (comma < rParen ? comma : rParen) - i;
         const string num(action.substr(i, numBytes));
         indices.push_back(_RightIndex + boost::lexical_cast<size_t>(num) -1);
         isIndex = false;
      }
   }
   if (Debug)
   {
      cout << "Indices for : " << action << " is ";
      std::copy(indices.begin(), indices.end(), std::ostream_iterator<size_t>(std::cout, ","));
      cout << endl;
   }
   return indices;

}
protein::protein(std::string p, double temp)
{
    seq = p;
    pH = temp;
    std::cout << "Calculating net charge for " << p.length() << " membered protein\n\n";
    //Allocate memory to chop string
    residue = new char[p.length()];
    size = p.length();
    for (unsigned count = 0; count < p.length(); count++)
    {
        //Chop string into char
        residue[count] = p.at(count);
    }
    protein::storeCharge(pH);
    //Find total charge using net charge at R group.
    for (unsigned count = 0; count < size; count++)
    {
        totalCharge += ratio[protein::getNumber(residue[count])][2];
    }
    //Add to the total charge the net charge at COOH and NH3.
    totalCharge += ratio[protein::getNumber(residue[0])][1];
    totalCharge += ratio[protein::getNumber(residue[size - 1])][0];
    std::cout << "\nNet Charge of Peptide : " << totalCharge << std::endl;
}
std::vector<std::string> generateAllCombinations(std::string s)
{
	std::vector<std::string> v;
	std::vector<std::string> combinations;

	if (s.size() == 0)
	{
		return v;
	}

	if (s.size() == 1)
	{
		v.push_back(s);

		return v;
	}

	char characterToMix = s.at(0);
	s = s.substr(1, s.size() - 1);

	combinations = generateAllCombinations(s);

	for (size_t i = 0; i < combinations.size(); ++i)
	{
		std::string combination = combinations[i];

		for (size_t j = 0; j <= combination.size(); ++j)
		{
			std::string left = combination.substr(0, j);
			std::string right = combination.substr(j, combination.size() - j);
			v.push_back(left + characterToMix + right);
		}
	}

	return v;
}
Example #14
0
void Dialog::setText(std::string str)
{
    unsigned int maxSize(40);
    unsigned int maxLine(3);

    if(str.length() >= maxSize)
    {

        for(unsigned int j = 1 ; j <= (unsigned int)(str.length()/maxSize); j++)
        {
            str.insert(j * maxSize , "\n");
        }
    }

    unsigned int nb = 0;
    for(unsigned int j = 0 ; j < str.length(); j++)
    {
        if(str.at(j) == '\n')
        {
            nb++;
            if(nb == maxLine)
            {
                texts.push_back(str.substr(0, j + 1));
                str.erase(0, j + 1);
                nb = 0;
                j = 0;
            }

        }
    }
    if(str.length() > 0 )
    {
        texts.push_back(str);
    }

}
Example #15
0
std::string token_word(const std::string& in) {
    int pos = -1;
    int digits_prefixed = 0;
    int nalpha = 0;
    int len = in.size();
    std::vector<char> cv;
    int last_quirk = -1;
    while (++pos < len) {
        char ch = in.at(pos);
        if (std::isdigit(ch)) {
            if (digits_prefixed > 0) {
                last_quirk = pos;
                break;
            }
            digits_prefixed--;
            cv.push_back(std::tolower(ch));
        } else if (std::isalpha(ch)) {
            if (digits_prefixed < 0)
                digits_prefixed = -digits_prefixed;
            cv.push_back(std::tolower(ch));
            nalpha++;
        } else {
            if (digits_prefixed < 0)
                digits_prefixed = -digits_prefixed;
            last_quirk = pos;
            if ((ch == '-' || ch == '\'') && pos != 0) {
                cv.push_back(ch);
            } else {
                break;
            }
        }
    }
    if (last_quirk == pos || (digits_prefixed > 0 && nalpha == 0))
        cv.clear(); // invalid word
    return std::string(cv.begin(),cv.end());
}
Example #16
0
bool ParseLine( const std::string &line )
{
	int num = 0;
	float fl = 0;
	u32 size = 0;

	//sikp empty lines or ones starting with #
	if( !line.size() || line.at( 0 ) == '#' )
		return true;
	if( !line.compare( 0, 11, "viewportX: " ) )
	{
		sscanf( line.c_str(), "viewportX: %i%n", &num, &size);
		if( size == line.size() )
		{
			Settings::viewportX = num;
			return true;
		}
	}
	if( !line.compare( 0, 11, "viewportY: " ) )
	{
		sscanf( line.c_str(), "viewportY: %i%n", &num, &size);
		if( size == line.size() )
		{
			Settings::viewportY = num;
			return true;
		}
	}
	if( !line.compare( 0, 12, "installDir: " ) )
	{
		installDir = line.substr( 12 );
		return true;
	}

	cout << "failed to parse setting line: \"" << line << "\"" << endl;
	return false;
}
Example #17
0
/** 
 * Append a single token to the given list of tokens.
 * The token is assumed to be lowercase, free of comments, and non-blank.  
 * This function is for handling shortcut
 * syntax, e.g. 1 4r, which should translate into four copies of the token 1
 */
void appendToTokenList( const std::string& token, token_list_t& tokens ){
  if( token.find_first_of("123456789") == 0 && token.at(token.length()-1) == 'r' ){
    // token starts with a number and ends with r: treat as repeat syntax.
    const char* string = token.c_str();
    char* p;
    int num = strtol( string, &p, 10 );
    if( (p - string) != static_cast<int>(token.length()) - 1 ){
      // oops, this isn't repeat format after all
      tokens.push_back(token);
      return;
    }

    if( OPT_DEBUG ) { std::cout << "Repeat syntax: " << token << " repeats " 
                                << tokens.back() << " " << num << " times." << std::endl; }

    for( int i = 0; i < num; ++i){
      const std::string& last_tok = tokens.back();
      tokens.push_back( last_tok );
    }
  }
  else{
    tokens.push_back(token);
  }
}
Example #18
0
std::string util::parseThreadId(std::string op)
{
    //for branch operations, we parse the thread id after the first "-"
    if(op.find("branch")!=string::npos){
        int posBegin = (int)op.find_first_of("-")+1;
        int posEnd = (int)op.find_first_of("-", posBegin);
        string tid = op.substr(posBegin, posEnd-posBegin);
        return op.substr(posBegin, posEnd-posBegin);
    }
    
    //for branch operations, we parse the thread id after the second "-"
    int posBegin = (int)op.find_first_of("-", op.find_first_of("-") + 1)+1;
    while(op.at(posBegin) == '>')
        posBegin = (int)op.find_first_of("-", posBegin) + 1;
    
    //for read operations, we have to consider the readId as well
    int posEnd = (int)op.find_first_of("-", posBegin);
    int posEnd2 = (int)op.find_first_of("&", posBegin);
    if(posEnd != string::npos)
        return op.substr(posBegin, posEnd-posBegin);
    
    return op.substr(posBegin, posEnd2-posBegin);
    
}
Example #19
0
/**
 * add a step to the history variable
 */
std::string CHistory::addToHistory(char steptype, std::string const &prevhist)
{
  std::string history;

  size_t histLenMinus1 = prevhist.length();
  char last;
  if(histLenMinus1>0) {
    histLenMinus1--;
    last = prevhist.at(histLenMinus1);
  } else {
    last = '\0';
  }

  if( last == EvaporationResidue && steptype == Evaporation )
    history = prevhist.substr(0,histLenMinus1) + Evaporation;
  else if( last == EvaporationResidue && steptype == EvaporationResidue )
    history = prevhist;
  else if( last == SaddleToScission && steptype == SaddleToScission )
    history = prevhist;
  else
    history = prevhist + steptype;

  return history;
}
Example #20
0
	T lexical_cast_integer(const std::string &str) {
		bool containsHexValues = false;
		bool containsNegative = false;
		for (int i = 0; i < str.size(); ++i) {
			char c = str.at(i);
			if ((c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F')) {
				containsHexValues = true;
			}
			else if (!(c >= '0' && c <= '9') && c != 'x' && c != '-') {
				throw std::runtime_error("Invalid cast");
			}
		}
		int start = 0;
		bool isHex = containsHexValues;
		if (str.size() > 1 && str.at(start) == '-') {
			++start;
			containsNegative = true;
		}
		if (str.size() > (start + 1) && str.at(start) == 'x') {
			start ++;
			isHex = true;
		}
		if (str.size() > (start + 2) && str.at(start) == '0' && str.at(start + 1) == 'x') {
			isHex = true;
			start += 2;
		}
		
		T value = 0;
		T base = (isHex ? 16 : 10);
		for (; start < str.size(); ++start) {
			char c = str.at(start);
			T place = ( (c >= '0' && c <= '9') ? (T)(c - '0') :
				( (c >= 'A' && c <= 'F') ? ((T)(c - 'A') + 10) :
					(c >= 'a' && c <= 'f') ? ((T)(c - 'a') + 10) : 0));
			value = value * base + place;
		}
		if (containsNegative) {
			value = -value;
		}
		return value;
	}
Example #21
0
inline bool Util_Parser::levelValido(std::string &name)
{
    try
    {
        if (name.size() > 99 )
        {
            NotifyWarning("levelValido: valor de level demasiado largo", "Util_Parser.cpp");
            return false;
        }

        char c1[100];
        for(unsigned i = 0; i<name.size(); i++)
        {
            name.at(i) = toupper(name.at(i));
            c1[i] = name.at(i);
        }

        char c2[] = "DEBUG";
        char c3[] = "INFO";
        char c4[] = "ERROR";

        NotifyMessage("levelValido: obteniendo level ", "Util_Parser.cpp");
        if((strncasecmp(c1,c2,2))==0)
        {
            name = "debug";
            NotifyMessage("levelValido: level seteado:" + name, "Util_Parser.cpp");;
            return true;
        }

        if((strncasecmp(c1,c3,2))==0)
        {
            name = "info";
            NotifyMessage("levelValido: level seteado:" + name, "Util_Parser.cpp");
            return true;
        }

        if((strncasecmp(c1,c4,2))==0)
        {
            name = "error";
            NotifyMessage("levelValido: level seteado:" + name, "Util_Parser.cpp");
            return true;
        }

        name = "";
        NotifyWarning("levelValido: valor de level invalido", "Util_Parser.cpp");
        return false;
    }
    catch(const std::runtime_error& re)
    {
        NotifyError("Error en Runtime: ", "Util_Parser.cpp");
        NotifyError(re.what(), "Util_Parser.cpp");
        return false;
    }
    catch(const std::exception& ex)
    {
        NotifyError("Ha ocurrido un error: ", "Util_Parser.cpp");
        NotifyError(ex.what(), "Util_Parser.cpp");
        return false;
    }
    catch(...)
    {
        NotifyError("Error desconocido que no se ha podido especificar.", "Util_Parser.cpp");
        return false;
    }
}
Example #22
0
//pasar por referencia
inline bool Util_Parser::formacionValido(std::string &name)
{
    try
    {
        if (name.size() > 99 )
        {
            NotifyWarning("formacionValido: valor de formacion demasiado largo", "Util_Parser.cpp");
            return false;
        }
        char c1[100];
        for(unsigned i = 0; i<name.size(); i++)
        {
            c1[i] = name.at(i);
        }
        char c2[] = "3-3";
        char c3[] = "3-1-2";
        char c4[] = "3-2-1";

        NotifyMessage("formacionValido: obteniendo formacion ", "Util_Parser.cpp");
        if((strncasecmp(c1,c2,3))==0)
        {
            name = "3-3";
            NotifyMessage("formacionValido: formacion seteado:" + name, "Util_Parser.cpp");
            return true;
        }

        if((strncasecmp(c1,c3,3))==0)
        {
            name = "3-1";
            NotifyMessage("formacionValido: formacion seteado:" + name, "Util_Parser.cpp");
            return true;
        }

        if((strncasecmp(c1,c4,3))==0)
        {
            name = "3-2-1";
            NotifyMessage("casacaValido: formacion seteado:" + name, "Util_Parser.cpp");
            return true;
        }
        name = "";
        NotifyWarning("formacionValido: valor de formacion invalido", "Util_Parser.cpp");
        return false;
    }
    catch(const std::runtime_error& re)
    {
        NotifyError("Error en Runtime: ", "Util_Parser.cpp");
        NotifyError(re.what(), "Util_Parser.cpp");
        return false;
    }
    catch(const std::exception& ex)
    {
        NotifyError("Ha ocurrido un error: ", "Util_Parser.cpp");
        NotifyError(ex.what(), "Util_Parser.cpp");
        return false;
    }
    catch(...)
    {
        NotifyError("Error desconocido que no se ha podido especificar.", "Util_Parser.cpp");
        return false;
    }
}
Example #23
0
//pasar por referencia
inline bool Util_Parser::casacaValido(std::string &name)
{
    try
    {
        if (name.size() > 99 )
        {
            NotifyWarning("casacaValido: valor de casaca demasiado largo", "Util_Parser.cpp");
            return false;
        }
        char c1[100];
        for(unsigned i = 0; i<name.size(); i++)
        {
            name.at(i) = toupper(name.at(i));
            c1[i] = name.at(i);
        }

        char c2[] = "PRINCIPAL";
        char c3[] = "SUPLENTE";
        char c4[] = "AUXILIAR";

        NotifyMessage("casacaValido: obteniendo casaca ", "Util_Parser.cpp");
        if((strncasecmp(c1,c2,2))==0)
        {
            name = "principal";
            NotifyMessage("casacaValido: casaca seteado:" + name, "Util_Parser.cpp");
            return true;
        }

        if((strncasecmp(c1,c3,2))==0)
        {
            name = "suplente";
            NotifyMessage("casacaValido: casaca seteado:" + name, "Util_Parser.cpp");
            return true;
        }

        if((strncasecmp(c1,c4,2))==0)
        {
            name = "auxiliar";
            NotifyWarning("casaca Auxiliar: casaca seteado:" + name, "Util_Parser.cpp");
            return true;
        }

        name = "";
        NotifyWarning("casacaValido: valor de casaca invalido", "Util_Parser.cpp");
        return false;
    }
    catch(const std::runtime_error& re)
    {
        NotifyError("Error en Runtime: ", "Util_Parser.cpp");
        NotifyError(re.what(), "Util_Parser.cpp");
        return false;
    }
    catch(const std::exception& ex)
    {
        NotifyError("Ha ocurrido un error: ", "Util_Parser.cpp");
        NotifyError(ex.what(), "Util_Parser.cpp");
        return false;
    }
    catch(...)
    {
        NotifyError("Error desconocido que no se ha podido especificar.", "Util_Parser.cpp");
        return false;
    }
}
Example #24
0
ShipType::ShipType(const Id &_id, const std::string &path)
{
	Json::Reader reader;
	Json::Value data;

	isGlobalColorDefined = false;

	auto fd = FileSystem::gameDataFiles.ReadFile(path);
	if (!fd) {
		Output("couldn't open ship def '%s'\n", path.c_str());
		return;
	}

	if (!reader.parse(fd->GetData(), fd->GetData()+fd->GetSize(), data)) {
		Output("couldn't read ship def '%s': %s\n", path.c_str(), reader.getFormattedErrorMessages().c_str());
		return;
	}

	// determine what kind (tag) of ship this is.
	const std::string tagStr = data.get("tag", "").asString();
	if( tagStr.empty() || strcasecmp(tagStr.c_str(), "ship")==0 ) {
		tag = TAG_SHIP;
	} else if( strcasecmp(tagStr.c_str(), "static")==0 ) {
		tag = TAG_STATIC_SHIP;
	} else if( strcasecmp(tagStr.c_str(), "missile")==0 ) {
		tag = TAG_MISSILE;
	}

	id = _id;
	name = data.get("name", "").asString();
	shipClass = data.get("ship_class", "").asString();
	manufacturer = data.get("manufacturer", "").asString();
	modelName = data.get("model", "").asString();
	cockpitName = data.get("cockpit", "").asString();

	linThrust[THRUSTER_REVERSE] = data.get("reverse_thrust", 0.0f).asFloat();
	linThrust[THRUSTER_FORWARD] = data.get("forward_thrust", 0.0f).asFloat();
	linThrust[THRUSTER_UP] = data.get("up_thrust", 0.0f).asFloat();
	linThrust[THRUSTER_DOWN] = data.get("down_thrust", 0.0f).asFloat();
	linThrust[THRUSTER_LEFT] = data.get("left_thrust", 0.0f).asFloat();
	linThrust[THRUSTER_RIGHT] = data.get("right_thrust", 0.0f).asFloat();
	angThrust = data.get("angular_thrust", 0.0f).asFloat();

	// Parse global thrusters color
	bool error = false;
	int parse = 0;
	for( Json::Value::iterator thruster_color = data["thruster_global_color"].begin() ; thruster_color != data["thruster_global_color"].end() ; ++thruster_color ) {
		const std::string colorchannel = thruster_color.key().asString();
		if (colorchannel.length()!=1) {
			error = true;
			break;
		}
		if (colorchannel.at(0) == 'r') {
			globalThrusterColor.r = data["thruster_global_color"].get(colorchannel, 0).asInt();
			parse++;
			continue;
		} else if (colorchannel.at(0) == 'g') {
			globalThrusterColor.g = data["thruster_global_color"].get(colorchannel, 0).asInt();
			parse++;
			continue;
		} else if (colorchannel.at(0) == 'b') {
			globalThrusterColor.b = data["thruster_global_color"].get(colorchannel, 0).asInt();
			parse++;
			continue;
		} else {
			// No 'r', no 'g', no 'b', no good :/
			error = true;
			break;
		}
	}
	if (error==true) {
		Output("In file \"%s.json\" global thrusters custom color must be \"r\",\"g\" and \"b\"\n", modelName.c_str());
	} else if (parse>0 && parse<3) {
		Output("In file \"%s.json\" global thrusters custom color is malformed\n", modelName.c_str());
	} else if (parse==3) {
		globalThrusterColor.a = 255;
		isGlobalColorDefined = true;
	}
	// Parse direction thrusters color
	for (int i=0; i<THRUSTER_MAX; i++) isDirectionColorDefined[i]=false;
	error = false;
	for( Json::Value::iterator thruster_color = data["thruster_direction_color"].begin() ; thruster_color != data["thruster_direction_color"].end() ; ++thruster_color ) {
		const std::string th_color_dir = thruster_color.key().asString();
		Json::Value dir_color = data["thruster_direction_color"].get(th_color_dir, 0);
		Color color;
		if (!dir_color.isMember("r")||!dir_color.isMember("g")||!dir_color.isMember("b")) {
			error = true;
			continue /* for */;
		} else {
			color.r = dir_color["r"].asInt();
			color.g = dir_color["g"].asInt();
			color.b = dir_color["b"].asInt();
			color.a = 255;
		}
		if (th_color_dir.find("forward")!=std::string::npos) {
			isDirectionColorDefined[THRUSTER_FORWARD]=true;
			directionThrusterColor[THRUSTER_FORWARD]= color;
		}
		if (th_color_dir.find("retro")!=std::string::npos) {
			isDirectionColorDefined[THRUSTER_REVERSE]=true;
			directionThrusterColor[THRUSTER_REVERSE]= color;
		}
		if (th_color_dir.find("left")!=std::string::npos) {
			isDirectionColorDefined[THRUSTER_LEFT]=true;
			directionThrusterColor[THRUSTER_LEFT]= color;
		}
		if (th_color_dir.find("right")!=std::string::npos) {
			isDirectionColorDefined[THRUSTER_RIGHT]=true;
			directionThrusterColor[THRUSTER_RIGHT]= color;
		}
		if (th_color_dir.find("up")!=std::string::npos) {
			isDirectionColorDefined[THRUSTER_UP]=true;
			directionThrusterColor[THRUSTER_UP]= color;
		}
		if (th_color_dir.find("down")!=std::string::npos) {
			isDirectionColorDefined[THRUSTER_DOWN]=true;
			directionThrusterColor[THRUSTER_DOWN]= color;
		}
	}
	if (error==true) {
		for (int i=0; i<THRUSTER_MAX; i++) isDirectionColorDefined[i]=false;
		Output("In file \"%s.json\" directional thrusters custom color must be \"r\",\"g\" and \"b\"\n", modelName.c_str());
	}
	// invert values where necessary
	linThrust[THRUSTER_FORWARD] *= -1.f;
	linThrust[THRUSTER_LEFT] *= -1.f;
	linThrust[THRUSTER_DOWN] *= -1.f;
	// angthrust fudge (XXX: why?)
	angThrust = angThrust * 0.5f;

	hullMass = data.get("hull_mass", 100).asInt();
	capacity = data.get("capacity", 0).asInt();
	fuelTankMass = data.get("fuel_tank_mass", 5).asInt();

	for( Json::Value::iterator slot = data["slots"].begin() ; slot != data["slots"].end() ; ++slot ) {
		const std::string slotname = slot.key().asString();
		slots[slotname] = data["slots"].get(slotname, 0).asInt();
	}

	for( Json::Value::iterator role = data["roles"].begin(); role != data["roles"].end(); ++role ) {
		const std::string rolename = role.key().asString();
		roles[rolename] = data["roles"].get(rolename, 0).asBool();
	}

	for(int it=0;it<4;it++) thrusterUpgrades[it] = 1.0 + (double(it)/10.0);
	for( Json::Value::iterator slot = data["thrust_upgrades"].begin() ; slot != data["thrust_upgrades"].end() ; ++slot ) {
		const std::string slotname = slot.key().asString();
		const int index = Clamp(atoi(&slotname.c_str()[9]), 1, 3);
		thrusterUpgrades[index] = data["thrust_upgrades"].get(slotname, 0).asDouble();
	}

	atmosphericPressureLimit = data.get("atmospheric_pressure_limit", 10.0).asDouble();	// 10 atmosphere is about 90 metres underwater (on Earth)

	{
		const auto it = slots.find("engine");
		if (it != slots.end())
		{
			it->second = Clamp(it->second, 0, 1);
		}
	}

	effectiveExhaustVelocity = data.get("effective_exhaust_velocity", -1.0f).asFloat();
	const float thruster_fuel_use = data.get("thruster_fuel_use", -1.0f).asFloat();

	if(effectiveExhaustVelocity < 0 && thruster_fuel_use < 0) {
		// default value of v_c is used
		effectiveExhaustVelocity = 55000000;
	} else if(effectiveExhaustVelocity < 0 && thruster_fuel_use >= 0) {
		// v_c undefined and thruster fuel use defined -- use it!
		effectiveExhaustVelocity = GetEffectiveExhaustVelocity(fuelTankMass, thruster_fuel_use, linThrust[Thruster::THRUSTER_FORWARD]);
	} else {
		if(thruster_fuel_use >= 0) {
			Output("Warning: Both thruster_fuel_use and effective_exhaust_velocity defined for %s, using effective_exhaust_velocity.\n", modelName.c_str());
		}
	}

	baseprice = data.get("price", 0.0).asDouble();
	minCrew = data.get("min_crew", 1).asInt();
	maxCrew = data.get("max_crew", 1).asInt();
	hyperdriveClass = data.get("hyperdrive_class", 1).asInt();
}
Example #25
0
bool menu::item_ends_with_image(const std::string& item) const
{
	std::string::size_type pos = item.find_last_of(IMG_TEXT_SEPARATOR);
	pos = (pos == std::string::npos) ? 0 : pos+1;
	return(item.size() > pos && item.at(pos) == IMAGE_PREFIX);
}
Example #26
0
//! (internal)
hashvalue EScript::_hash( const std::string &  s) {
	hashvalue h=0;
	for (size_t i=0;i<s.length();++i)
		h^=(((s.at(i)+h)*1234393)% 0xffffff);
	return h;
}
void tb_draw_string(int x, int y, const std::string &str,
                    uint16_t fg, uint16_t bg) {
  for (std::size_t i = 0; i < str.size(); ++i) {
    tb_change_cell(x + i, y, str.at(i), fg, bg);
  }
}
Example #28
0
bool ImageLoader::insertColor(std::string &oneLine)
{
    string temp;//temporary copy of oneLine, used to shorten it
    stringstream converter;//converts strings into ints
    char colorName = ' ';//used to refer to this color in the file
    unsigned int redCol = 0;//the components of this color
    unsigned int greenCol = 0;
    unsigned int blueCol = 0;
    bool result = true;//false if the line was malformed

    //cout << "ImageLoader::insertColor(): added " << oneLine << endl;

    //### Verify that there are at least 6 chars ###
    if (oneLine.size() < 6)
    {
        cout << "ImageLoader::insertColor(): line with less than 6 chars" << endl;
        result = false;
    }//if size()

    //### Extract the color name ###
    if (result)
    {
        colorName = oneLine.at(0);
        if (fileColors.find(colorName) != fileColors.end())
        {
            cout << "ImageLoader::insertColor(): Color " << colorName
                 << " is present multiple times" << endl;
            result = false;
        }//if find()
    }//if result

    //### Strip everything but space-separated color values ###
    if (result)
    {
        temp.clear();
        temp.append(oneLine, 5, oneLine.size() - 6);

        oneLine.clear();
        for (unsigned int i = 0; i < temp.size(); i++)
        {
            if (temp.at(i) != ',')
                oneLine.push_back(temp.at(i));
        }//for i
    }//if result

    //### Extract the red color ###
    if (result)
    {
        converter << oneLine;

        converter >> redCol;
        if (!converter.good())
        {
            cout << "ImageLoader::insertColor(): invalid red color given" << endl;
            result = false;
        }//if !good()
    }//if result

    //### Extract the green color ###
    if (result)
    {
        converter >> greenCol;
        if (!converter.good())
        {
            cout << "ImageLoader::insertColor(): invalid green color given" << endl;
            result = false;
        }//if !good()
    }//if result

    //### Extract the blue color ###
    if (result)
    {
        converter >> blueCol;
        if (converter.fail())
        {
            cout << "ImageLoader::insertColor(): invalid blue color given" << endl;
            result = false;
        }//if fail()
    }//if result

    //### Insert the colors into the map ###
    if (result)
        fileColors.insert(pair<char, QRgb>(colorName, qRgb(redCol, greenCol, blueCol)));

    return result;
}//insertColor
//int doffire(unsigned tmax=1000000, unsigned short fmatch=200, unsigned int randPlant=1, unsigned int clustPlant=0, unsigned short burnAge=1, unsigned short burnPropAge=1, int rhoRocks=0, int doSQL=1, float pImmune=0, int nnnAge=0) {
int doffire(unsigned int tmax=1000000, unsigned int fmatch=125, int doSQL=2, float pImmune=0, float kImmune=1, std::string immCode=std::string("100") ) {
	// immCode: [1]: cluster level, [2]: fire-front elements, [3]: each new element. (evaluate immunity at these times).
	//printf("test immCode: %s\n", immCode.c_str());
	if (immCode.at(2)==std::string("1")[0] ) printf("and we are not doing perim-level immunity.\n");
	bool doImPrim=0, doImFlameFront=0, doImFireElement=0;
	if (immCode.at(2)==std::string("1")[0] ) doImPrim=1;
	if (immCode.at(1)==std::string("1")[0] ) doImFlameFront=1;
	if (immCode.at(0)==std::string("1")[0] ) doImFireElement=1;
	
	
	int aveRho = 0, aveVol=0;
	int burnAge=1, burnPropAge=1;
	int nTreesOnGrid=0;
	
	std::string simName("ForestFire5c");
	std::string simPramComment("single-pass fire propagation/immunity evaluation");
	//
	unsigned short rFire = 1;
	unsigned int nBurning = 1;
	unsigned short dnBurning = 1;
	int thisXY, xFire, yFire;
//	int thisStatus;
	int * thisSquare, * fireSquare;
	unsigned int nBurnedTotal=0, nFires=0;  // number of elements burning, new Elements burning...
	float aveTreeAge=0;
	//signed int grids[(ymax+2)*(xmax+2)];
	int *grids = new int[(ymax+2)*(xmax+2)];
	//int *directions = new int[4];
	//*directions={1,-1, xmax+2, -(xmax+2)};
	int directions[4]={1,-1, xmax+2, -(xmax+2)};
	//int randDirs[4]={1,-1, xmax+2, -(xmax+2)};	// new array to be randomized
	int *newOrder = new int[4];
	// v9:
	int *fireList = new int[(ymax)*(xmax)];
	unsigned int *fcounts = new unsigned int[(ymax)*(xmax)];
	unsigned short newFireElements=0;		// [x, x, x, x, x, x[nBurning], x, x, x, x[dnBurning], x, x, x, x[newFireElements] ]: old-fire, current flame-front, new elements.
	unsigned int totalFireCount=0;
	//
	bool doQuench = 0;
	//
	float frandImmune=0;
	int randImmune = 0;
	//
	//unsigned int rhoRocks = 10;	// of 100
	// initialize?
	srand(time(NULL));	// eventually, we have to be smarter about this and use independent random sets. see Gleb's random number gens.
	for (unsigned int i=0; i<(xmax+2)*(ymax+2); i++) {
		grids[i]=0;
		// seed the grid with some trees
		if (rand()%(xmax/2)==1 and i%(xmax+2)!=0 and i%(xmax+2)!=(xmax+1) and i>(xmax+2) and i<((xmax+2)*(ymax+1)) ) {
			grids[i]=1;
			nTreesOnGrid ++;
			};
		//if (i>(xmax+2)*(ymax+1)) printf("initializing grid %d\n", i);
		//yodapause();
		};
	//printf("random grid established...\n");
	//printGrid(&grids[0], 1, xmax, ymax);
	//
	char DB[]="ForestFire";
	char HOST[]="localhost";
	char USER[]="myoder";
	char PASSWORD[]="yoda";
	mysqlpp::Connection myconn(DB, HOST, USER, PASSWORD);
	mysqlpp::Query myquery=myconn.query();
	//mysqlpp::Result res1;
	mysqlpp::StoreQueryResult res1;
	int intKey;
		
	//unsigned int fcounts[xmax*ymax];
		for (unsigned int i=0; i<xmax*ymax; i++) {
			//fcounts[i]=0;
			//fireList[i]=0;
			*(fcounts + i)=0;
			*(fireList + i)=0;
			};
	if (doSQL==1 or doSQL==5 or doSQL==25) {	
		//
		// insert a new row for this sim-run:
		myquery.reset();
		printf("insert simprams.\n");
		myquery << "insert into ForestFire.SimPrams (`SimName`, `xmax`, `ymax`, `sparkInterval`, `burnAge`, `tmax`, `nRand`, `pImmune`, `kImmune`, `Comment`) values (%0q, %1q, %2q, %3q, %4q, %5q, %6q, %7q, %8q, %9q )";
		myquery.parse();
		// note: simIndex(auto-int) and dtTime (default TIMESTAMP) set automatically.
		//myquery.execute(simName.c_str(), simName.c_str(), xmax, ymax, fmatch, burnAge, tmax, randPlant, clustPlant, kmax, simPramComment.c_str());
		 myquery.execute(simName.c_str(), xmax, ymax, fmatch, 1, tmax, 1, pImmune, kImmune, simPramComment.c_str());
		//
		// now, get the integer key for this simulation:
		// note that this could be accomplished with one call (optimal if MySQL calls have high overhead)
		// by writing a SPROC on the MySQL side.
		// also see the mysql_insert_id() (C API) and LAST_INSERT_ID() (SQL) functions, by which we should be ablt to automatically retrieve the indexID.
		myquery.reset();
		printf("fetch simIndex.\n");
		myquery << "select max(simIndex) from ForestFire.SimPrams";
		myquery.parse();
		res1 = myquery.store(simName.c_str(), simName.c_str());
		intKey = res1.at(0).at(0);
		}; // doSQL
	//
	//printf("beginnn.\n");
	//for (unsigned int i=0; i<=tmax; i++) {
	unsigned int i=0;		// just so other bits don't break...
	while (totalFireCount<=tmax) {
		i++;		// this might overflow i guess. if so... figure out something.
		//if (doSQL==5 or doSQL==6) if(i%1000000 == 0) printf("%d million\n", i/1000000);
		if (doSQL==6) if(i%1000000 == 0) printf("%d million\n", i/1000000);

		if (doSQL==16) {
			if(i%100000 == 0) {
				// printf("%d million\n", i/1000000);
				aveRho=0;
				aveVol=0;
				for (unsigned int k=0; k<(xmax+2)*(ymax+2); k++) {
					if (*(grids+k)>0 and *(grids+k)<rockAge) {
						aveRho = aveRho + 1;
						aveVol = aveVol + *(grids+k);
						};
					};
				//printf("mils,\t Rho,\t Vol,\t %d, %f, %f\n", i/1000000, float(aveRho)/float(xmax*ymax), float(aveVol)/float(xmax*ymax));
				printf("%d, %f, %f\n", i/1000000, float(aveRho)/float(xmax*ymax), float(aveVol)/float(xmax*ymax));
				};
			};
		//
		// PLANT A TREE:
		// select a grid for tree planting:
			//thisX = rand()%xmax+1;
			//thisY = rand()%ymax+1;
			//thisSquare = &grids[0] + thisX + (xmax+2)*thisY;	// point to the current square...
			// for speed, select one random number; if we land on a rock, then just skip. there aren't many rocks.
			thisXY = xmax+3 + rand()%((xmax+2)*ymax-1);
			thisSquare = grids + thisXY;
			// if (*thisSquare<rockAge) {
			if (*thisSquare==0) {
				*thisSquare = *thisSquare + 1;
				nTreesOnGrid ++;
				};

	// we've planted a tree. do we throw a match?
		// we can do this two ways. we can trow a match every M steps or set a 
		// 1/M probability every time.
		// for now, we're being super simple; throw a match every 'fmatch' steps:
		// throw a match with 1/fmatch probability. generate a random number beteen 1 and fmatch; each number appears with freq. 1/fmatch
		//ffmatch = float(i+1)/float(fmatch);
		//if (float(int(ffmatch))==ffmatch and i>xmax) {
		//if (rand()%((1+prefPlant)*fmatch)==1) {
		
		if (rand()%fmatch==1) {
			//yodapause();
			// throw a match.
			xFire = rand()%xmax+1;
			yFire = rand()%ymax+1;
			fireSquare = &grids[0] + xFire + (xmax+2)*yFire;
			//printf("match: (%d, %d) :: %d/%d\n", xFire, yFire, *fireSquare, *(&grids[0] + (xFire + (xmax+2)*yFire)));
			//yodapause();
			//
			//printf("now evaluate *fireSquare, etc. %d\n", *fireSquare);
			//if (getGridStatus(*fireSquare, i) >= burnAge and getGridStatus(*fireSquare, i) < rockAge) {
			if (*fireSquare >= burnAge and *fireSquare < rockAge) {				
				// initiate a new fire.
				// now, we have three places to test quench-immunity:
				// 1) after each new step of front propagation
				// 2) after each burning element is tested against its NN
				// 3) after each element is added.
				// when the sequence of testing is fully randomized, we can test at any level.
				//
				// use the list-method (see v9a comments at the top) to propagate the fire.
				//printf("set 0-grid...\n");
				//*fireSquare = -(*fireSquare);	// we could remove the square; we track the fire in a list (=0), but we want to be able to plot the grid...
				//*fireSquare=0;
				//printf("set fireSquare... %d, %d, %d: %d\n",xFire, yFire, xmax, (xFire + (xmax+2)*yFire));
				totalFireCount++;
				*fireSquare=-1;
				fireList[0]=(xFire + (xmax+2)*yFire);	// or should we use an array of addresses?
				//printf("set fireSquare done\n");
				//
				rFire = 1;
				dnBurning = 1;
				nBurning = 0;
				newFireElements=0;
				//
				//int yFireMin = int(yodacode::greaterOf((yFire-rFire), 1));	// we always start with a 1 squar boundary. we might, however, encounter the edges.
				//int yFireMax = int(yodacode::lesserOf((yFire+rFire), float(ymax)));
				//int xFireMin = int(yodacode::greaterOf(float(xFire-rFire), 1));
				//int xFireMax = int(yodacode::lesserOf(float(xFire+rFire), float(xmax)));
				//
				//printf("fire range: %d, %d, %d, %d\n", yFireMin, yFireMax, xFireMin, xFireMax);
				//printf("preplot\n.");
				//
				//plotGrid(&grids[0],i, xmax, ymax);
				if (doSQL==0) {
					printGrid(&grids[0], i, xmax, ymax);
					};
				//while (dnBurning > 0) {
				doQuench = 0;
				//nFireSteps=0;	// steps fire has propagated, max dist/radius from flash-point. effectively time it's been burning.
				//printf("fire started at %d. now propagate.\n", xFire + (xmax+2)*yFire);
				while (dnBurning > 0 and doQuench==0) {
					//dnBurning=0;
					// evaluate neighbors of current burn front (nBurning-1 < i < (nBurning-1)+dnBurning
					unsigned int fireIndex=nBurning;
					//unsigned int newFireIndex=0;
					unsigned int currentElementIndex;
					//printf("fire front burning. fireIndex=%d\n", fireIndex);
					int * randomFireSequence = new int[dnBurning];
					int * testSeq = new int[dnBurning];
					for (int itest=0; itest<dnBurning; itest++) {
						*(testSeq + itest) = itest;
						}
					scrambleList(testSeq, randomFireSequence, dnBurning);
					delete [] testSeq;
					//if (dnBurning>1) randomSequence(randomFireSequence, dnBurning);	// randomize order in which we evalueate fire propagation.
					//for (int ilist=0; ilist<dnBurning; ilist++) {
					//	printf("randomSequence[%d]=%d\n", ilist, randomFireSequence[ilist]);
					//	};
					//
					while (fireIndex < (nBurning+dnBurning) and doQuench==0) {
						//newFireIndex=fireIndex-nBurning;
						currentElementIndex=nBurning+randomFireSequence[fireIndex-nBurning];	// this is long-winded because i'm building it off the simpler non-randomized model.
						//printf("fire index: %d (%d, %d, %d, %d)\n", fireIndex-nBurning, fireIndex, nBurning, dnBurning, currentElementIndex);
						//printf("failing here? %d, %d, %d\n", nBurning, dnBurning, fireIndex-nBurning);
					
						//currentElementIndex=nBurning+randomFireSequence[fireIndex-nBurning];
					//	printf("nope. ");
						
						
						// check for fire:
						// to maintain symmetry, randomize directions:
						// randDirs
						//scrambleList(directions, randDirs, 4);
						//int ordr[4]={0,1,2,3};
						//int newOrder[4];
						randomSequence(newOrder,4);
						//scrambleList(ordr, newOrder, 4);	// i think this is killing the random number generator.
						//printf("newOrder: %d, %d, %d, %d\n" , newOrder[0], newOrder[1],newOrder[2],newOrder[3]);
						
						for (int idir=0; idir<4; idir++) {
							// note: this loop format may facilitate randomization of direction later on...
							// nothing randomized:
							/*
							// I.
							if (grids[fireList[fireIndex] + directions[idir]]==1) {
								grids[fireList[fireIndex] + directions[idir]]=-1;
								fireList[nBurning + dnBurning + newFireElements]=fireList[fireIndex]+directions[idir];
								newFireElements++;
								};
							*/
							// order of each element (NN) randomized:
							/*
							// II.
							if (grids[fireList[fireIndex] + directions[newOrder[idir]]]==1) {
								grids[fireList[fireIndex] + directions[newOrder[idir]]]=-1;
								fireList[nBurning + dnBurning + newFireElements]=fireList[fireIndex]+directions[newOrder[idir]];
								newFireElements++;
								};
							*/
							// III.
							// each element (NN) and order of flame-front randomized:
							//printf("currentElement: %d\n", currentElementIndex);
							//printf("grid index: %d, %d, %d\n" , fireList[currentElementIndex], directions[newOrder[idir]], newOrder[idir]);
							//printf("segmentation fault test: grid-val (%d)\n", grids[fireList[currentElementIndex] + directions[newOrder[idir]]]);
							if (grids[fireList[currentElementIndex] + directions[newOrder[idir]]]==1) {
								//
								// add an entry to fireList. at the end of fireList [nBurning+dnBurning+newFireElements], add the fire location value,
								// fireList[currentElementIndex] + direction[]
								if (doQuench==0) {
									grids[fireList[currentElementIndex] + directions[newOrder[idir]]]=-1;
									fireList[nBurning + dnBurning + newFireElements]=fireList[currentElementIndex]+directions[newOrder[idir]];
									newFireElements++;
									};
								//if (immCode[2]=="1") {
								// so, do we do this before or after we evaluate the element? by doing this after we propagate the first step (so
								// fires are always k>1; alternatively we could use 1/(k+1)^p), we can use Pimmune>1 .
								if (doImFireElement) {
									// evaluate immunity (as each new element burns):
									//if (testQuench((nBurning+dnBurning+newFireElements), pImmune, kImmune)) {
									randImmune = rand()%RAND_MAX;
									frandImmune = float(randImmune)/RAND_MAX;
									if (frandImmune < (pImmune/pow(float(nBurning+dnBurning+newFireElements), kImmune)) ) {
										idir=4;
										doQuench=1;
										
										//printf("fire quenched during element-propagation: %d/%d\n", nBurning+dnBurning+newFireElements, fireIndex+1);
										//printGrid(&grids[0], i, xmax, ymax);
										//continue;
										};
									};
								};
							//
							// MFI (after each element is tested to the fire). this is only allowed at this step for type III propagation (above). if we apply immunity
							// as each element is added and elements are added in some geometrical sequence (aka, around the fire-front), we break the symmetry and break
							// SOC between integer values of L^2. by itself, using the list method (in particular when we randomize direction) might fix this problem,
							// since it breakes down the spiral geometry of our former concentric square propagation.
								
							};
						fireIndex++;

						// evaluate immunity (as each burning (fire-front) element propagates):
						//if (testQuench((nBurning+dnBurning+newFireElements), pImmune, kImmune)) {
						//if (immCode[1]=="1") {
						if (doImFlameFront) {
							randImmune = rand()%RAND_MAX;
							frandImmune = float(randImmune)/RAND_MAX;
							if (frandImmune < (pImmune/pow(float(nBurning+dnBurning+newFireElements), kImmune)) ) {
								//printf("quenched a fire at k=%d, Pq=%f/%f\n", (nBurning+dnBurning+newFireElements), pImmune/pow((nBurning+dnBurning+newFireElements), kImmune), frandImmune);
								doQuench=1;
								};
							};
					 	//
						//
						
						};
					// this round of propagation is over (new elements have propagated to NN).
					nBurning = nBurning + dnBurning;
					dnBurning=newFireElements;
					newFireElements=0;
					delete [] randomFireSequence;
					//
					// evaluate immunity (after each full propagation step):
					//if (immCode[0]=="1") {
					if (doImPrim) {
						// at this point, the first step of propagation has occurred, so nominally we can use pImmune>1.
						// arguably, this creates a new characteristic size; maybe the omori-type immunity is a better idea?
						//if (testQuench((nBurning+dnBurning+newFireElements), pImmune, kImmune)) {
						randImmune = rand()%RAND_MAX;
						frandImmune = float(randImmune)/RAND_MAX;
						if (frandImmune < (pImmune/pow(float(nBurning+dnBurning+newFireElements), kImmune)) ) {
						//if (frandImmune < (pImmune/(1+float(nBurning+dnBurning+newFireElements)/kImmune) ) ){
							//idir=4;
							doQuench=1;
							};
						};
					//printGrid(&grids[0], i, xmax, ymax);
					// g1.plot_xy(vfireX, vfireY, "");
					};	// end fire still burining
				//
				// fire is over:
				nFires++;
				nBurnedTotal = nBurnedTotal + nBurning;
				nTreesOnGrid = nTreesOnGrid-nBurning;
				//printf("fire over; %d burned.\n", nBurning);
				fcounts[nBurning-1]++;
				// printf("fcounts[%d]: %d\n", nBurning-1, fcounts[nBurning-1]);
				//plotGrid(&grids[0], xmax, ymax);
				//printGrid(&grids[0], i, xmax, ymax);
				if (doSQL==0) {
					printGrid(&grids[0], i, xmax, ymax);
					};
				// write fire to MySQL:
				if (doSQL==1) {
					// printf("fire size, nFires, totalBurned: (%d) (%d) (%d)\n", nBurning, nFires, nBurnedTotal);
					myquery.reset();
					myquery << "insert into ForestFire.ForestFires (simIndex, t, xSpark, ySpark, nBurned, nTrees) values (%0q, %1q, %2q, %3q, %4q, %5q) ";
					myquery.parse();
					myquery.execute(intKey, i, xFire, yFire, nBurning, nTreesOnGrid);
					//yodapause();
					};
				if (doSQL==3) {
					printf("fire at time %d\n", i);
					if (nBurning>=xmax/5) plotGrid (&grids[0], i, xmax, ymax, burnPropAge);
					};
				if (doSQL==4) {
					if (nBurning>=xmax/5) plotGridImg (&grids[0], i, xmax, ymax, burnPropAge);
					};
				//
				// fires finished burning; extinguish:
				unsigned int icleanup=0;
				while (fireList[icleanup]!=0) {
				//while (icleanup<nBurning+dnBurning+newFireElements){
				//while (icleanup<(xmax*ymax)){
					grids[fireList[icleanup]]=0;
					fireList[icleanup]=0;
					icleanup++;
					};
				nBurning = 0;
				dnBurning=0;
				newFireElements=0;
				//printGrid(&grids[0], i, xmax, ymax);
				//fireIndex=0;
				}; //else printf("no tree at match point.\n");	// if match -> tree...
			}; // if match-time

		// do we initialize with 0?
		//printf("ary element 0,i: %d", grids[0][i]);
		};	// end sim-steps.

	// end simulation.
	//printf("doSQL: %d\n", doSQL);
	// doSQL's:
	// 0: 'print-grid" fires
	// 1: full SQL: insert each forest fire data-set into ForestFires
	// 2: print summary to screen. use this for direct gnuplot calls, " plot '<./ffire4...'" 
	// 3: Print each fire to screen; "plotGrid" each fire nBurning>(25) print summary to screen at end
	// 4: plotGridImg each fire nBurning>(20); print summary to screen,
	// 5: SQL: insert just summary data to SQL; prints progress by million (will screw up plotting)
	// 6: report summary, progress by million.
	// 11: return to standard-output the last grid in full. use to make an image of the final grid.
	//
	// for super long runs (10^9 steps), it looks like the mysql connection times out, so all is lost.
	// renew the connection. 
	//
//	if (myconn.connected()==0) myconn.connect(DB, HOST, USER, PASSWORD);
	mysqlpp::Connection newconn(DB, HOST, USER, PASSWORD);
	mysqlpp::Query newquery=myconn.query();
	//mysqlpp::Result res1;

	//mysqlpp::Query myquery=myconn.query();
	//mysqlpp::Result res1;
	// end-o-run summaries (print):
	
	//printf("xmax*ymax = %d; %d, %d\n", xmax*ymax, ymax, xmax);
	if (doSQL==2  or doSQL==25 or doSQL==3 or doSQL==4 or doSQL==6) {
		//printf("dosql=2 or something. we should get a summary.");
		for (unsigned int i=0; i<(xmax*ymax); i++) {
			if (fcounts[i]!=0) {
				printf("%d\t%d\n", i+1, fcounts[i]);
				//printf("%d\t%d\n", i+1, i);
				//printf("%d,\t%d\n", i+1, fcounts[i]);
				}
			else {
				//printf("finished.\nfire size, nFires, totalBurned: (%d) (%d) (%d)\n", nBurning, nFires, nBurnedTotal);
				};
			};
		};
	//printf("moving past dosql2\n");
	if (doSQL==5 or doSQL==25 ) { // no plots, just a summary -> SQL
		//
		for (unsigned int i=0; i<(xmax*ymax); i++) {
			// if (fcounts[i]!=0) printf("%d\t%d\n", i+1, fcounts[i]);
		//	printf ("sql bits: %d, %d, %d, %d\n", intKey, tmax, i+1, fcounts[i]);
			newquery.reset();
			newquery << "insert into ffcounts (simIndex, tmax, nBurned, nEvents) values (%0q, %1q, %2q, %3q)";
			newquery.parse();
			newquery.execute(intKey, tmax, i+1, fcounts[i]);
			//printf("%d,\t%d\n", i+1, fcounts[i]);
			};				
		};
	//printf("moving past dosql5,25\n");
	// return the final grid in full and give an average density at the end...?
	if (doSQL==11) {
		for (unsigned int i=0; i<(xmax+2)*(ymax+2); i++) {
			printf ("%d,\t%d,\t%d\n", i-int(i/(xmax+2))*(xmax+2), i/(xmax+2), getGridStatus(*(grids+i), tmax));
			};
		};
	//g1.reset_plot();
	//g1.plot_xyz(vx, vy, vGridStat, "xyz plot of TreesPlanted");

	//yodacode::yodapause();
	//
	// clean up memory?
	delete [] grids;
	delete [] fireList;
	delete [] fcounts;
	//delete [] directions;
	return 0;
	//return &grids[0];
	};
//======================================================================
bool sccan_point_pair_handler::
is_string_a_sccan_run_config(std::string line){
	
	if(verbosity){
		std::cout<<"sccan_point_pair_handler -> ";
		std::cout<<"is_string_a_sccan_run_config() -> line: ";
		std::cout<<line<<std::endl;
	}
	
	// use DEAs for the std::string control
	// find 

	enum TokenT{ 
		digit,
		point,
		underscore,
		char_c,
		char_f,
		char_g,
		char_s,
		char_a,
		char_n,
		ERR
	};
		   
	int GetState[][23] ={
	//dig point under	c	f	g	s	a	n
	{  1,	-1,	-1,		-1,	-1,	-1, -1,	-1,	-1 },	//0		d
	{  2,	-1,	-1,		-1,	-1,	-1, -1,	-1,	-1 },	//1		d
	{  3,	-1,	-1,		-1,	-1,	-1, -1,	-1,	-1 },	//2		d
	{  4,	-1,	-1,		-1,	-1,	-1, -1,	-1,	-1 },	//3		d
	{  5,	-1,	-1,		-1,	-1,	-1, -1,	-1,	-1 },	//4		d
	{  6,	-1,	-1,		-1,	-1,	-1, -1,	-1,	-1 },	//5		d
	{  7,	-1,	-1,		-1,	-1,	-1, -1,	-1,	-1 },	//6		d
	{  8,	-1,	-1,		-1,	-1,	-1, -1,	-1,	-1 },	//7		d
	{  -1,	-1,  9,		-1,	-1,	-1, -1,	-1,	-1 },	//8		_
	{  10,	-1,	-1,		-1,	-1,	-1, -1,	-1,	-1 },	//9		d
	{  11,	-1,	-1,		-1,	-1,	-1, -1,	-1,	-1 },	//10	d
	{  12,	-1,	-1,		-1,	-1,	-1, -1,	-1,	-1 },	//11	d
	{  13,	-1,	-1,		-1,	-1,	-1, -1,	-1,	-1 },	//12	d
	{  -1,	-1,	14,		-1,	-1,	-1, -1,	-1,	-1 },	//13	_	
	{  -1,	-1,	-1,		-1,	-1,	-1, 15,	-1,	-1 },	//14	s
	{  -1,	-1,	-1,		16,	-1,	-1, -1,	-1,	-1 },	//15	c
	{  -1,	-1,	-1,		17,	-1,	-1, -1,	-1,	-1 },	//16	c
	{  -1,	-1,	-1,		-1,	-1,	-1, -1,	18,	-1 },	//17	a
	{  -1,	-1,	-1,		-1,	-1,	-1, -1,	-1,	19 },	//18	n
	{  -1,	-1,	20,		-1,	-1,	-1, -1,	-1,	-1 },	//19	_	
	{  20,	21,	-1,		-1,	-1,	-1, -1,	-1,	-1 },	//20	d	
	{  -1,	-1,	-1,		22,	-1,	-1, -1,	-1,	-1 },	//21	.
	{  -1,	-1,	-1,		-1,	23,	-1, -1,	-1,	-1 },	//22	c
	{  -1,	-1,	-1,		-1,	-1,	24, -1,	-1,	-1 },	//23	f
													//24	g
	};
	//for( int i=0; i<11;i++){std::cout<<"("<<i<<")"<<GetState[26][i]<<", ";}
	//std::cout<<std::endl;
	std::string ID;
	std::string tilt_x;
	std::string tilt_y;
	std::string tilt_z;
	std::string str_vec2D_x;
	std::string str_vec2D_y;
	int int_vec2D_count = 0;
	
	
	int state = 0;
	int char_number = 0;
	//std::cout<<"str laenge: "<<line.size()<<std::endl;
	while(state != -1 && char_number<line.size()){
		TokenT token = ERR;
		char s = line.at( char_number);
		if(is_c(s)) token = char_c;
		if(is_f(s)) token = char_f;
		if(is_g(s)) token = char_g;
		if(is_s(s)) token = char_s;
		if(is_a(s)) token = char_a;
		if(is_n(s)) token = char_n;
		if(isdigit(s)) token = digit; 
		//std::cout<<char(s)<<"==digit"<<std::endl;}
		if(is_point(s)) token = point;
		if(is_underscore(s)) token = underscore;
		//std::cout<<"check"<<char_number<<": ";
		//std::cout<<char(s)<<" state: "<<state<<" token: "<<token<<std::endl;
		state = (token == ERR) ? :GetState[state][token];
		char_number ++; 	
	
	}
	if(state==24){return true;}else{return false;};
}