Exemplo n.º 1
0
bool StringToBool(std::string const& str)
{
    std::string lowerStr = str;
    std::transform(str.begin(), str.end(), lowerStr.begin(), [](char c) { return char(::tolower(c)); });
    return lowerStr == "1" || lowerStr == "true" || lowerStr == "yes";
}
Exemplo n.º 2
0
inline unsigned int regex_grep(bool (*foo)(const match_results<std::string::const_iterator>&), const std::string& s,
                        const regex& e, 
                        match_flag_type flags = match_default)
{
   return regex_grep(foo, s.begin(), s.end(), e, flags);
}
Exemplo n.º 3
0
 std::string remove(std::string expression, const std::string& toRemove) {
     for (std::string::const_iterator str = toRemove.begin(); str != toRemove.end(); str++) {
         expression.erase(std::remove(expression.begin(), expression.end(), *str), expression.end());
     }
     return expression;
 }
Exemplo n.º 4
0
Time::Time(const std::string& str, const std::string& fmt)
: _msecs(0)
{
  unsigned hours = 0;
  unsigned minutes = 0;
  unsigned seconds = 0;
  unsigned mseconds = 0;
  bool am = true;

  enum {
    state_0,
    state_fmt
  } state = state_0;

  std::string::const_iterator dit = str.begin();
  std::string::const_iterator it;
  for (it = fmt.begin(); it != fmt.end(); ++it)
  {
    char ch = *it;
    switch (state)
    {
      case state_0:
        if (ch == '%')
          state = state_fmt;
        else
        {
          if (dit == str.end() || *dit != ch)
            throw std::runtime_error("string <" + str + "> does not match time format <" + fmt + '>');
          ++dit;
        }
        break;

      case state_fmt:
        switch (ch)
        {
          case 'H':
          case 'I':
            hours = getUnsigned(dit, str.end(), 2);
            break;

          case 'M':
            minutes = getUnsigned(dit, str.end(), 2);
            break;

          case 'S':
            seconds = getUnsigned(dit, str.end(), 2);
            break;

          case 'j':
            if (dit != str.end() && *dit == '.')
              ++dit;
            mseconds = getMilliseconds(dit, str.end());
            break;

          case 'J':
          case 'K':
            if (dit != str.end() && *dit == '.')
            {
              ++dit;
              mseconds = getMilliseconds(dit, str.end());
            }
            break;

          case 'k':
            mseconds = getMilliseconds(dit, str.end());
            break;

          case 'p':
            if (dit == str.end()
              || dit + 1 == str.end()
              || ((*dit != 'A'
                && *dit != 'a'
                && *dit != 'P'
                && *dit != 'p')
              || (*(dit + 1) != 'M'
                &&  *(dit + 1) != 'm')))
            {
                throw std::runtime_error("string <" + str + "> does not match time format <" + fmt + '>');
            }

            am = (*dit == 'A' || *dit == 'a');
            dit += 2;
            break;

          default:
            throw std::runtime_error("invalid time format <" + fmt + '>');
        }

        state = state_0;
        break;
    }
  }

  if (it != fmt.end() || dit != str.end())
    throw std::runtime_error("string <" + str + "> does not match time format <" + fmt + '>');

  set(am ? hours : hours + 12, minutes, seconds, mseconds);
}
Exemplo n.º 5
0
bool is_number(const std::string& s)
{
    std::string::const_iterator it = s.begin();
    while (it != s.end() && (isdigit(*it))) ++it;
    return !s.empty() && it == s.end();
}
Exemplo n.º 6
0
 void Toolbox::ToLowerCase(std::string& s)
 {
   std::transform(s.begin(), s.end(), s.begin(), tolower);
 }
Exemplo n.º 7
0
entry decode(std::string const& str)
{
	return bdecode(str.begin(), str.end());
}
Exemplo n.º 8
0
	// returns protocol, auth, hostname, port, path
	boost::tuple<std::string, std::string, std::string, int, std::string>
		parse_url_components(std::string url, error_code& ec)
	{
		std::string hostname; // hostname only
		std::string auth; // user:pass
		std::string protocol; // http or https for instance
		int port = -1;

		std::string::iterator at;
		std::string::iterator colon;
		std::string::iterator port_pos;

		// PARSE URL
		std::string::iterator start = url.begin();
		// remove white spaces in front of the url
		while (start != url.end() && is_space(*start))
			++start;
		std::string::iterator end
			= std::find(url.begin(), url.end(), ':');
		protocol.assign(start, end);

		if (end == url.end())
		{
			ec = errors::unsupported_url_protocol;
			goto exit;
		}
		++end;
		if (end == url.end() || *end != '/')
		{
			ec = errors::unsupported_url_protocol;
			goto exit;
		}
		++end;
		if (end == url.end() || *end != '/')
		{
			ec = errors::unsupported_url_protocol;
			goto exit;
		}
		++end;
		start = end;

		at = std::find(start, url.end(), '@');
		colon = std::find(start, url.end(), ':');
		end = std::find(start, url.end(), '/');

		if (at != url.end()
			&& colon != url.end()
			&& colon < at
			&& at < end)
		{
			auth.assign(start, at);
			start = at;
			++start;
		}

		// this is for IPv6 addresses
		if (start != url.end() && *start == '[')
		{
			port_pos = std::find(start, url.end(), ']');
			if (port_pos == url.end())
			{
				ec = errors::expected_close_bracket_in_address;
				goto exit;
			}
			port_pos = std::find(port_pos, url.end(), ':');
		}
		else
		{
			port_pos = std::find(start, url.end(), ':');
		}

		if (port_pos < end)
		{
			hostname.assign(start, port_pos);
			++port_pos;
			for (std::string::iterator i = port_pos; i < end; ++i)
			{
				if (is_digit(*i)) continue;
				ec = errors::invalid_port;
				goto exit;
			}
			port = std::atoi(std::string(port_pos, end).c_str());
		}
		else
		{
			hostname.assign(start, end);
		}

		start = end;
exit:
		return boost::make_tuple(protocol, auth, hostname, port
			, std::string(start, url.end()));
	}
Exemplo n.º 9
0
/**
 * We don't want to pronounce punctuation
 */
void ALSpeech::replaceSymbols(std::string& text)
{
    replace(text.begin(), text.end(), '_', ' ');
    replace(text.begin(), text.end(), ':', ' ');
    replace(text.begin(), text.end(), '-', ' ');
}
Exemplo n.º 10
0
	/// c'tor
	Parser(std::string input_data) :
		data_(input_data),
		state_(data_.begin()),
		error_state_(data_.begin())
	{}
Exemplo n.º 11
0
void Lux_OGL_DrawText( std::string text, LuxRect dest_rect, Effects image_effects, bool allow_custom )
{
	//glPushMatrix();
	int32_t z = dest_rect.z/1000;
	glColor4ub(image_effects.colour.r, image_effects.colour.g, image_effects.colour.b, image_effects.colour.a);
	uint16_t x = dest_rect.x;
	std::string::iterator object;
	for ( object = text.begin(); object != text.end(); object++ )
	{
		uint32_t cchar = *object;
		/*
		194-223 2 bytes
		224-239 3 bytes
		240-244 4 bytes
		*/
		if (cchar == '\n' || cchar == '\r')
		{
			dest_rect.y += ( oglGraphics_customtext && allow_custom ? oglGraphics_customtext_height + 2 : 10);
			x = dest_rect.x;
		}
		else if ( cchar <= 32 )
		{
			x += 7;
		}
		else if ( cchar <= 128 )
		{
			if ( oglGraphics_customtext && allow_custom )
			{
				x += Lux_OGL_DrawChar((int32_t)cchar,  x, dest_rect.y, z, image_effects);
			}
			else
			{
				glEnable(GL_TEXTURE_2D);
				glBindTexture(GL_TEXTURE_2D, font[cchar-32]);
				glBegin(GL_QUADS);
					glTexCoord2f( 0.0, 0.0 );
					Lux_OGL_ColouredVertex3(image_effects.colour, image_effects.colour2, image_effects.style, 1, x, dest_rect.y, z);
					glTexCoord2f( 1.0, 0.0 );
					Lux_OGL_ColouredVertex3(image_effects.colour, image_effects.colour2, image_effects.style, 2, x + 8, dest_rect.y, z);
					glTexCoord2f( 1.0, 1.0 );
					Lux_OGL_ColouredVertex3(image_effects.colour, image_effects.colour2, image_effects.style, 3, x + 8, dest_rect.y + 8, z);
					glTexCoord2f( 0.0, 1.0 );
					Lux_OGL_ColouredVertex3(image_effects.colour, image_effects.colour2, image_effects.style, 4, x, dest_rect.y + 8, z );
				glEnd();
				glDisable(GL_TEXTURE_2D);
				x += 7;
			}
		}
		else
		{
			glEnable(GL_TEXTURE_2D);
			glBindTexture(GL_TEXTURE_2D, font['?'-32]);
			glBegin(GL_QUADS);
				glTexCoord2f( 0.0, 0.0 );
				Lux_OGL_ColouredVertex3(image_effects.colour, image_effects.colour2, image_effects.style, 1, x, dest_rect.y, z);
				glTexCoord2f( 1.0, 0.0 );
				Lux_OGL_ColouredVertex3(image_effects.colour, image_effects.colour2, image_effects.style, 2, x + 8, dest_rect.y, z);
				glTexCoord2f( 1.0, 1.0 );
				Lux_OGL_ColouredVertex3(image_effects.colour, image_effects.colour2, image_effects.style, 3, x + 8, dest_rect.y + 8, z);
				glTexCoord2f( 0.0, 1.0 );
				Lux_OGL_ColouredVertex3(image_effects.colour, image_effects.colour2, image_effects.style, 4, x, dest_rect.y + 8, z );
			glEnd();
			glDisable(GL_TEXTURE_2D);
			x += 7;
			if ( cchar < 224 )
				object++;
			else if ( cchar < 240 )
				object +=2;
			else if ( cchar < 245 )
				object +=3;
		}

	}
	glColor4f(1.0,1.0,1.0,1.0);
	//glPopMatrix();
}
Exemplo n.º 12
0
void DateTimeFormatter::append(std::string& str, const DateTime& dateTime, const std::string& fmt, int timeZoneDifferential)
{
    std::string::const_iterator it  = fmt.begin();
    std::string::const_iterator end = fmt.end();
    while (it != end)
    {
        if (*it == '%')
        {
            if (++it != end)
            {
                switch (*it)
                {
                case 'w':
                    str.append(DateTimeFormat::WEEKDAY_NAMES[dateTime.dayOfWeek()], 0, 3);
                    break;
                case 'W':
                    str.append(DateTimeFormat::WEEKDAY_NAMES[dateTime.dayOfWeek()]);
                    break;
                case 'b':
                    str.append(DateTimeFormat::MONTH_NAMES[dateTime.month() - 1], 0, 3);
                    break;
                case 'B':
                    str.append(DateTimeFormat::MONTH_NAMES[dateTime.month() - 1]);
                    break;
                case 'd':
                    NumberFormatter::append0(str, dateTime.day(), 2);
                    break;
                case 'e':
                    NumberFormatter::append(str, dateTime.day());
                    break;
                case 'f':
                    NumberFormatter::append(str, dateTime.day(), 2);
                    break;
                case 'm':
                    NumberFormatter::append0(str, dateTime.month(), 2);
                    break;
                case 'n':
                    NumberFormatter::append(str, dateTime.month());
                    break;
                case 'o':
                    NumberFormatter::append(str, dateTime.month(), 2);
                    break;
                case 'y':
                    NumberFormatter::append0(str, dateTime.year() % 100, 2);
                    break;
                case 'Y':
                    NumberFormatter::append0(str, dateTime.year(), 4);
                    break;
                case 'H':
                    NumberFormatter::append0(str, dateTime.hour(), 2);
                    break;
                case 'h':
                    NumberFormatter::append0(str, dateTime.hourAMPM(), 2);
                    break;
                case 'a':
                    str.append(dateTime.isAM() ? "am" : "pm");
                    break;
                case 'A':
                    str.append(dateTime.isAM() ? "AM" : "PM");
                    break;
                case 'M':
                    NumberFormatter::append0(str, dateTime.minute(), 2);
                    break;
                case 'S':
                    NumberFormatter::append0(str, dateTime.second(), 2);
                    break;
                case 's':
                    NumberFormatter::append0(str, dateTime.second(), 2);
                    str += '.';
                    NumberFormatter::append0(str, dateTime.millisecond()*1000 + dateTime.microsecond(), 6);
                    break;
                case 'i':
                    NumberFormatter::append0(str, dateTime.millisecond(), 3);
                    break;
                case 'c':
                    NumberFormatter::append(str, dateTime.millisecond()/100);
                    break;
                case 'F':
                    NumberFormatter::append0(str, dateTime.millisecond()*1000 + dateTime.microsecond(), 6);
                    break;
                case 'z':
                    tzdISO(str, timeZoneDifferential);
                    break;
                case 'Z':
                    tzdRFC(str, timeZoneDifferential);
                    break;
                default:
                    str += *it;
                }
                ++it;
            }
        }
        else str += *it++;
    }
}
Exemplo n.º 13
0
 explicit binary(const std::string& s) : std::vector<value_type>(s.begin(), s.end()) {}
Exemplo n.º 14
0
  std::string RegexSMatch::format(const std::string& s) const
  {
    enum state_type
    {
      state_0,
      state_esc,
      state_var0,
      state_var1,
      state_1
    } state;

    state = state_0;
    std::string ret;

    for (std::string::const_iterator it = s.begin(); it != s.end(); ++it)
    {
      char ch = *it;

      switch (state)
      {
        case state_0:
          if (ch == '$')
            state = state_var0;
          else if (ch == '\\')
            state = state_esc;
          break;

        case state_esc:
          ret += ch;
          state = state_1;
          break;

        case state_var0:
          if (std::isdigit(ch))
          {
            ret = std::string(s.begin(), it - 1);
            regoff_t s = matchbuf[ch - '0'].rm_so;
            regoff_t e = matchbuf[ch - '0'].rm_eo;
            if (s >= 0 && e >= 0)
              ret.append(str, s, e-s);
            state = state_1;
          }
          else
            state = state_0;
          break;

        case state_1:
          if (ch == '$')
            state = state_var1;
          else if (state == '\\')
            state = state_esc;
          else
            ret += ch;
          break;

        case state_var1:
          if (std::isdigit(ch))
          {
            regoff_t s = matchbuf[ch - '0'].rm_so;
            regoff_t e = matchbuf[ch - '0'].rm_eo;
            if (s >= 0 && e >= 0)
              ret.append(str, s, e-s);
            state = state_1;
          }
          else if (ch == '$')
            ret += '$';
          else
          {
            ret += '$';
            ret += ch;
          }
          break;
      }
    }

    switch (state)
    {
      case state_0:
      case state_var0:
        return s;

      case state_esc:
        return ret + '\\';

      case state_var1:
        return ret + '$';

      case state_1:
        return ret;
    }

    return ret;
  }
Exemplo n.º 15
0
std::size_t ByteBuffer::writeBytes(const std::string& buffer)
{
    _buffer.reserve(_buffer.size() + buffer.size());
    _buffer.insert(_buffer.end(), buffer.begin(), buffer.end());
    return buffer.size();
}
Exemplo n.º 16
0
std::string glob_to_regex(const std::string& glob)
{
	std::string regex;
	regex.reserve(glob.size()<<1);
	S32 braces = 0;
	bool escaped = false;
	bool square_brace_open = false;

	for (std::string::const_iterator i = glob.begin(); i != glob.end(); ++i)
	{
		char c = *i;

		switch (c)
		{
			case '.':
				regex+="\\.";
				break;
			case '*':
				if (glob.begin() == i)
				{
					regex+="[^.].*";
				}
				else
				{
					regex+= escaped ? "*" : ".*";
				}
				break;
			case '?':
				regex+= escaped ? '?' : '.';
				break;
			case '{':
				braces++;
				regex+='(';
				break;
			case '}':
				if (!braces)
				{
					llerrs << "glob_to_regex: Closing brace without an equivalent opening brace: " << glob << llendl;
				}

				regex+=')';
				braces--;
				break;
			case ',':
				regex+= braces ? '|' : c;
				break;
			case '!':
				regex+= square_brace_open ? '^' : c;
				break;
			default:
				regex+=c;
				break;
		}

		escaped = ('\\' == c);
		square_brace_open = ('[' == c);
	}

	if (braces)
	{
		llerrs << "glob_to_regex: Unterminated brace expression: " << glob << llendl;
	}

	return regex;
}
Exemplo n.º 17
0
std::size_t ByteBuffer::readBytes(std::string& buffer) const
{
    buffer.resize(_buffer.size());
    buffer.insert(buffer.begin(), _buffer.begin(), _buffer.end());
    return buffer.size();
}
Exemplo n.º 18
0
std::string reverse(std::string str)
{
   // Not the most efficient way of doing this.
   std::reverse(str.begin(),str.end());
   return str;
}
void Parser::nextToken(unsigned line, const std::string& token, Schema& schema) {
	if (getenv("DEBUG"))
		std::cerr << line << ": " << token << std::endl;
   if (token.empty())
      return;
   std::string tok;
   std::transform(token.begin(), token.end(), std::back_inserter(tok), tolower);
   switch(state) {
      case State::Semicolon: /* fallthrough */
      case State::Init:
         if (tok==keyword::Create)
            state=State::Create;
         else
            throw ParserError(line, "Expected 'CREATE', found '"+token+"'");
         break;
      case State::Create:
         if (tok==keyword::Table)
            state=State::Table;
         else
            throw ParserError(line, "Expected 'TABLE', found '"+token+"'");
         break;
      case State::Table:
         if (isIdentifier(tok)) {
            state=State::TableName;
            if(tok.find("\"") == 0) {                 // For handling tableNames with quotes in SQL
               std::string tokModified = tok;
               tokModified.erase(tokModified.begin());
               tokModified.erase(tokModified.end()-1);
               schema.relations.push_back(Schema::Relation(tokModified));
            } else {
               schema.relations.push_back(Schema::Relation(token));
            }
         } else {
            throw ParserError(line, "Expected TableName, found '"+token+"'");
         }
         break;
      case State::TableName:
         if (tok.size()==1 && tok[0]==literal::ParenthesisLeft)
            state=State::CreateTableBegin;
         else
            throw ParserError(line, "Expected '(', found '"+token+"'");
         break;
      case State::Separator: /* fallthrough */
      case State::CreateTableBegin:
         if (tok.size()==1 && tok[0]==literal::ParenthesisRight) {
            state=State::CreateTableEnd;
         } else if (tok==keyword::Primary) {
            state=State::Primary;
         } else if (isIdentifier(tok)) {
            schema.relations.back().attributes.push_back(Schema::Relation::Attribute());
            schema.relations.back().attributes.back().name = token;
            state=State::AttributeName;
         } else {
            throw ParserError(line, "Expected attribute definition, primary key definition or ')', found '"+token+"'");
         }
         break;
      case State::CreateTableEnd:
         if (tok.size()==1 && tok[0]==literal::Semicolon)
            state=State::Semicolon;
         else
            throw ParserError(line, "Expected ';', found '"+token+"'");
         break;
      case State::Primary:
         if (tok==keyword::Key)
            state=State::Key;
         else
            throw ParserError(line, "Expected 'KEY', found '"+token+"'");
         break;
      case State::Key:
         if (tok.size()==1 && tok[0]==literal::ParenthesisLeft)
            state=State::KeyListBegin;
         else
            throw ParserError(line, "Expected list of key attributes, found '"+token+"'");
         break;
      case State::KeyListBegin:
         if (isIdentifier(tok)) {
            struct AttributeNamePredicate {
               const std::string& name;
               AttributeNamePredicate(const std::string& name) : name(name) {}
               bool operator()(const Schema::Relation::Attribute& attr) const {
                  return attr.name == name;
               }
            };
            const auto& attributes = schema.relations.back().attributes;
            AttributeNamePredicate p(token);
            auto it = std::find_if(attributes.begin(), attributes.end(), p);
            if (it == attributes.end())
               throw ParserError(line, "'"+token+"' is not an attribute of '"+schema.relations.back().name+"'");
            schema.relations.back().primaryKey.push_back(std::distance(attributes.begin(), it));
            state=State::KeyName;
         } else {
            throw ParserError(line, "Expected key attribute, found '"+token+"'");
         }
         break;
      case State::KeyName:
         if (tok.size()==1 && tok[0] == literal::Comma)
            state=State::KeyListBegin;
         else if (tok.size()==1 && tok[0] == literal::ParenthesisRight)
            state=State::KeyListEnd;
         else
            throw ParserError(line, "Expected ',' or ')', found '"+token+"'");
         break;
      case State::KeyListEnd:
         if (tok.size()==1 && tok[0] == literal::Comma)
            state=State::Separator;
         else if (tok.size()==1 && tok[0] == literal::ParenthesisRight)
            state=State::CreateTableEnd;
         else
            throw ParserError(line, "Expected ',' or ')', found '"+token+"'");
         break;
      case State::AttributeName:
         if (tok==keyword::Integer) {
            schema.relations.back().attributes.back().type=Types::Tag::Integer;
            state=State::AttributeTypeInt;
         } else if (tok==keyword::Char) {
            schema.relations.back().attributes.back().type=Types::Tag::Char;
            state=State::AttributeTypeChar;
         } else if (tok==keyword::Numeric) {
            schema.relations.back().attributes.back().type=Types::Tag::Numeric;
            state=State::AttributeTypeNumeric;
         } else if (tok==keyword::Varchar) {
            schema.relations.back().attributes.back().type=Types::Tag::Varchar;
            state=State::AttributeTypeVarchar;
         } else if (tok==keyword::Timestamp) {
            schema.relations.back().attributes.back().type=Types::Tag::Timestamp;
            state=State::AttributeTypeTimestamp;
         }
         else throw ParserError(line, "Expected type after attribute name, found '"+token+"'");
         break;
      case State::AttributeTypeChar:
         if (tok.size()==1 && tok[0]==literal::ParenthesisLeft)
            state=State::CharBegin;
         else
            throw ParserError(line, "Expected '(' after 'CHAR', found'"+token+"'");
         break;
      case State::CharBegin:
         if (isInt(tok)) {
            schema.relations.back().attributes.back().len=std::atoi(tok.c_str());
            state=State::CharValue;
         } else {
            throw ParserError(line, "Expected integer after 'CHAR(', found'"+token+"'");
         }
         break;
      case State::CharValue:
         if (tok.size()==1 && tok[0]==literal::ParenthesisRight)
            state=State::CharEnd;
         else
            throw ParserError(line, "Expected ')' after length of CHAR, found'"+token+"'");
         break;
      case State::AttributeTypeVarchar:
         if (tok.size()==1 && tok[0]==literal::ParenthesisLeft)
            state=State::VarcharBegin;
         else
            throw ParserError(line, "Expected '(' after 'VARCHAR', found'"+token+"'");
         break;
      case State::VarcharBegin:
         if (isInt(tok)) {
            schema.relations.back().attributes.back().len=std::atoi(tok.c_str());
            state=State::VarcharValue;
         } else {
            throw ParserError(line, "Expected integer after 'VARCHAR(', found'"+token+"'");
         }
         break;
      case State::VarcharValue:
         if (tok.size()==1 && tok[0]==literal::ParenthesisRight)
            state=State::VarcharEnd;
         else
            throw ParserError(line, "Expected ')' after length of VARCHAR, found'"+token+"'");
         break;
      case State::AttributeTypeNumeric:
         if (tok.size()==1 && tok[0]==literal::ParenthesisLeft)
            state=State::NumericBegin;
         else
            throw ParserError(line, "Expected '(' after 'NUMERIC', found'"+token+"'");
         break;
      case State::NumericBegin:
         if (isInt(tok)) {
            schema.relations.back().attributes.back().len1=std::atoi(tok.c_str());
            state=State::NumericValue1;
         } else {
            throw ParserError(line, "Expected integer after 'NUMERIC(', found'"+token+"'");
         }
         break;
      case State::NumericValue1:
         if (tok.size()==1 && tok[0]==literal::Comma)
            state=State::NumericSeparator;
         else
            throw ParserError(line, "Expected ',' after first length of NUMERIC, found'"+token+"'");
         break;
      case State::NumericValue2:
         if (tok.size()==1 && tok[0]==literal::ParenthesisRight)
            state=State::NumericEnd;
         else
            throw ParserError(line, "Expected ')' after second length of NUMERIC, found'"+token+"'");
         break;
      case State::NumericSeparator:
         if (isInt(tok)) {
            schema.relations.back().attributes.back().len2=std::atoi(tok.c_str());
            state=State::NumericValue2;
         } else {
            throw ParserError(line, "Expected second length for NUMERIC type, found'"+token+"'");
         }
         break;
      case State::CharEnd: /* fallthrough */
      case State::VarcharEnd: /* fallthrough */
      case State::NumericEnd: /* fallthrough */
      case State::AttributeTypeInt:
         if (tok.size()==1 && tok[0]==literal::Comma)
            state=State::Separator;
         else if (tok==keyword::Not)
            state=State::Not;
         else if (tok.size()==1 && tok[0]==literal::ParenthesisRight)
				state=State::CreateTableEnd;
         else throw ParserError(line, "Expected ',' or 'NOT NULL' after attribute type, found '"+token+"'");
         break;
      case State::AttributeTypeTimestamp:
         if (tok.size()==1 && tok[0]==literal::Comma)
            state=State::Separator;
         else if (tok==keyword::Not)
            state=State::Not;
         else if (tok.size()==1 && tok[0]==literal::ParenthesisRight)
				state=State::CreateTableEnd;
         else throw ParserError(line, "Expected ',' or 'NOT NULL' after attribute type, found '"+token+"'");
         break;
      case State::Not:
         if (tok==keyword::Null) {
            schema.relations.back().attributes.back().notNull=true;
            state=State::Null;
         }
         else throw ParserError(line, "Expected 'NULL' after 'NOT' name, found '"+token+"'");
         break;
      case State::Null:
         if (tok.size()==1 && tok[0]==literal::Comma)
            state=State::Separator;
         else if (tok.size()==1 && tok[0]==literal::ParenthesisRight)
            state=State::CreateTableEnd;
         else throw ParserError(line, "Expected ',' or ')' after attribute definition, found '"+token+"'");
         break;
      default:
         throw;
   }
}
Exemplo n.º 20
0
std::string::size_type RegularExpression::substOne(std::string& subject, std::string::size_type offset, const std::string& replacement, int options) const
{
	if (offset >= subject.length()) return std::string::npos;

	int ovec[OVEC_SIZE];
	int rc = pcre_exec(_pcre, _extra, subject.c_str(), int(subject.size()), int(offset), options & 0xFFFF, ovec, OVEC_SIZE);
	if (rc == PCRE_ERROR_NOMATCH)
	{
		return std::string::npos;
	}
	else if (rc == PCRE_ERROR_BADOPTION)
	{
		throw RegularExpressionException("bad option");
	}
	else if (rc == 0)
	{
		throw RegularExpressionException("too many captured substrings");
	}
	else if (rc < 0)
	{
		std::ostringstream msg;
		msg << "PCRE error " << rc;
		throw RegularExpressionException(msg.str());
	}
	std::string result;
	std::string::size_type len = subject.length();
	std::string::size_type pos = 0;
	std::string::size_type rp = std::string::npos;
	while (pos < len)
	{
		if (ovec[0] == pos)
		{
			std::string::const_iterator it  = replacement.begin();
			std::string::const_iterator end = replacement.end();
			while (it != end)
			{
				if (*it == '$' && !(options & RE_NO_VARS))
				{
					++it;
					if (it != end)
					{
						char d = *it;
						if (d >= '0' && d <= '9')
						{
							int c = d - '0';
							if (c < rc)
							{
								int o = ovec[c*2];
								int l = ovec[c*2 + 1] - o;
								result.append(subject, o, l);
							}
						}
						else
						{
							result += '$';
							result += d;
						}
						++it;
					}
					else result += '$';
				}
				else result += *it++;
			}
			pos = ovec[1];
			rp = result.length();
		}
		else result += subject[pos++];
	}
	subject = result;
	return rp;
}
Exemplo n.º 21
0
std::string Time::toString(const std::string& fmt) const
{
  unsigned hours, minutes, seconds, mseconds;

  get(hours, minutes, seconds, mseconds);

  std::string str;

  enum {
    state_0,
    state_fmt
  } state = state_0;

  for (std::string::const_iterator it = fmt.begin(); it != fmt.end(); ++it)
  {
    switch (state)
    {
      case state_0:
        if (*it == '%')
          state = state_fmt;
        else
          str += *it;
        break;

      case state_fmt:
        switch (*it)
        {
          case 'H': appendD2(str, hours); break;
          case 'I': appendD2(str, hours % 12); break;
          case 'M': appendD2(str, minutes); break;
          case 'S': appendD2(str, seconds); break;
          case 'j': if (mseconds != 0)
                    {
                      str += '.';
                      str += (mseconds / 100 + '0');
                      if (mseconds % 100 != 0)
                      {
                        str += (mseconds / 10 % 10 + '0');
                        if (mseconds % 10 != 0)
                          str += (mseconds % 10 + '0');
                      }
                    }
                    break;

          case 'J': str += '.';
                    str += (mseconds / 100 + '0');
                    if (mseconds % 100 != 0)
                    {
                      str += (mseconds / 10 % 10 + '0');
                      if (mseconds % 10 != 0)
                        str += (mseconds % 10 + '0');
                    }
                    break;

          case 'k': appendD3(str, mseconds);
                    break;

          case 'K': str += '.';
                    appendD3(str, mseconds);
                    break;

          case 'p': str += (hours < 12 ? "am" : "pm"); break;
          case 'P': str += (hours < 12 ? "AM" : "PM"); break;
          default:
            str += '%';
        }

        if (*it != '%')
          state = state_0;
        break;
    }
  }

  if (state == state_fmt)
    str += '%';

  return str;
}
Exemplo n.º 22
0
void TrimLeft(std::string& s)
{
    s.erase(s.begin(),
            std::find_if(s.begin(), s.end(), std::not1(IsDigit())));
}
Exemplo n.º 23
0
std::wstring StringToWString(const std::string& s)
{
  std::wstring temp(s.length(),L' ');
  std::copy(s.begin(), s.end(), temp.begin());
  return temp;
}
Exemplo n.º 24
0
bool is_number(const std::string& s) {
    return !s.empty()
        && std::find_if(s.begin(), s.end(),
                        [](char c) { return !std::isdigit(c); }) == s.end();
}
Exemplo n.º 25
0
void RemoveSubStr(std::string& sInput, const std::string& sub)
{
	std::string::size_type foundpos = sInput.find(sub);
	if ( foundpos != std::string::npos )
	sInput.erase(sInput.begin() + foundpos, sInput.begin() + foundpos + sub.length());
}
Exemplo n.º 26
0
/**
 *  formatiert einen Zeitstring.
 *
 *  @param[in] format Formatstring (%Y=4 stelliges Jahr, %m 2 stelliges Monat, %D tag, %H Stunde, %i Minute, %s Sekunden)
 *  @param[in] time   zu benutzender Timestamp.
 *
 *  @return Formatted string
 */
std::string Time::FormatTime(const std::string& format, unser_time_t* time)
{
    time_t inTime;
    if(time)
        inTime = *time;
    else
        inTime = CurrentTime();

    tm* time_data = localtime(&inTime);
    if(!time_data)
        return "";

    using std::setw;
    std::stringstream res;
    res << std::setfill('0');

    bool isInFormat = false;
    for(std::string::const_iterator c = format.begin(); c != format.end(); ++c)
    {
        if(isInFormat)
        {
            isInFormat = false;
            switch(*c)
            {
                case 'Y':
                    res << setw(4) << (1900 + time_data->tm_year);
                    break;
                case 'm':
                    res << setw(2) << (time_data->tm_mon+1);
                    break;
                case 'd':
                    res << setw(2) << time_data->tm_mday;
                    break;
                case 'H':
                    res << setw(2) << time_data->tm_hour;
                    break;
                case 'i':
                    res << setw(2) << time_data->tm_min;
                    break;
                case 's':
                    res << setw(2) << time_data->tm_sec;
                    break;
                case '%':
                    res << '%';
                    break;
                default:
                    std::cerr << "Invalid format string: " << format << std::endl;
                    res << *c;
                    break;
            }
        }else if(*c == '%')
            isInFormat = true;
        else
            res << *c;
    }

    if(isInFormat)
        std::cerr << "Invalid format string: " << format << std::endl;

    return res.str();
}
Exemplo n.º 27
0
bool BinaryExpParser::checkExpression(std::string& strexp)
{
    ErrorLogger* logger = ErrorLogger::Instance();

    if(std::count(strexp.begin(), strexp.end(), '(') !=
        std::count(strexp.begin(), strexp.end(), ')'))
    {
        logger->addError("Incorrect expression format! (parentheses do not match)");
        return false;
    }
    if(std::count(strexp.begin(), strexp.end(), IMPLY) != 1 )
    {
        logger->addError("Incorrect expression format! (no implication ':' found)");
        return false;
    }

    // erassing all the sapces
    strexp.erase(std::remove_if(strexp.begin(), strexp.end(), ::isspace), strexp.end());
    if(!strexp.size())
    {
       logger->addError("Empty expression!");
       return false;
    }

    // making a copy of strexp and checking more
    string  dummy = strexp;
    // removing all pranteses
    dummy.erase(std::remove_if(dummy.begin(), dummy.end(), isParentheses), dummy.end());
    leftOpr = dummy.substr(0, dummy.find(IMPLY));
    if(!leftOpr.size())
    {
        logger->addError("Missing operand before ':'");
        return false;
    }
    if(dummy.find(IMPLY) == (dummy.size()-1))
    {
        logger->addError("Missing operands after ':'");
        return false;
    }

    dummy.erase(0, dummy.find(IMPLY)+1);
    if(dummy.find(leftOpr) != string::npos)
    {
        std::string msg;
        msg = "recursive assignment of operand '" + leftOpr + "'";
        logger->addError(msg.c_str());
        return false;
    }

    // checking '~'
    size_t n = dummy.find(EXPNOT);
    while(n != string::npos)
    {
        OSTRINGSTREAM msg;
        bool bError = ((n+1) == dummy.length()); // empty operand after ~
        if((n+1) < dummy.length())
        {
            bError |= (dummy[n+1] == EXPAND);        // operator & after ~
            bError |= (dummy[n+1] == EXPOR);         // operand | after ~
        }
        if(n != 0)
            bError |= (dummy[n-1] != EXPAND) && (dummy[n-1] != EXPOR);  // an operand before ~
        if(bError)
        {
            msg<<"Incorrect expression format of '~' at "<<(int)n;
            logger->addError(msg.str().c_str());
            return false;
        }
        n = dummy.find(EXPNOT, n+1);
    }

    // checking '| &'
    n = dummy.find_first_of("&|");
    while(n != string::npos)
    {
        OSTRINGSTREAM msg;
        bool bError = ((n+1) == dummy.length());    // empty operand after & or |
        if((n+1) < dummy.length())
        {
            bError |= (dummy[n+1] == EXPAND);        // operator & after & or |
            bError |= (dummy[n+1] == EXPOR);         // operand | after & or |
        }
        bError |= (n == 0);                      // empty operand before & or |
        if(n != 0)
        {
            bError |= (dummy[n-1] == EXPAND);        // operator & before & or |
            bError |= (dummy[n-1] == EXPOR);         // operand | before & or |
            bError |= (dummy[n-1] == EXPOR);         // operand ~ before & or |
        }
        if(bError)
        {
            msg<<"Incorrect expression format of '&' or '|' at "<<(int)n;
            logger->addError(msg.str().c_str());
            return false;
        }
        n = dummy.find_first_of("&|", n+1);
    }

    // at the end
    strexp.erase(0, strexp.find(IMPLY)+1);
    return true;
}
Exemplo n.º 28
0
inline bool headers_equal(const std::string &a, const std::string &b)
{
    if (a.length() != b.length())
        return false;
    return std::equal(a.begin(), a.end(), b.begin(), tolower_compare);
}
//---------------------------------------------------------------------------
//From http://www.richelbilderbeek.nl/CppStrToLower.htm
const std::string StrToLower(std::string s)
{
  std::transform(s.begin(), s.end(), s.begin(),std::ptr_fun<int,int>(std::tolower));
  return s;
}
Exemplo n.º 30
0
/**
 * @brief method to render tags with a given map
 *
 * @param tmplate template std::string to render
 * @param ctx map of values
 *
 * @return rendered std::string
 */
std::string template_t::render_tags(const std::string& tmplate,
                                    const Context& ctx)
{
    // initialize data
    std::string ret = "";
    std::string rest = "";
    std::string::const_iterator start, end;
    boost::match_results<std::string::const_iterator> matches;
    start = tmplate.begin();
    end = tmplate.end();
    // return whole std::string when no tags are found
    if (!regex_search(start, end, matches, tag,
                      boost::match_default | boost::format_all))
    {
        ret = tmplate;
    }
    // loop through tags and replace
    while (regex_search(start, end, matches, tag,
                        boost::match_default | boost::format_all))
    {
        std::string modifier(matches[1].first, matches[1].second);
        std::string key(matches[2].first, matches[2].second);
        boost::algorithm::trim(key);
        boost::algorithm::trim(modifier);
        std::string text(start, matches[0].second);
        std::string repl;
        // don't html escape this
        if (modifier == "&" || modifier == "{")
        {
            try
            {
                repl.assign(ctx.get(key)[0][key]);
            }
            catch(int i) { repl.assign(""); }
        }
        // this is a comment
        else if (modifier == "!")
        {
            repl.assign("");
        }
        // found a partial
        else if (modifier == ">")
        {
            std::string partial = template_t::get_partial(key);
            repl.assign(template_t::render(partial, ctx));
        }
        // normal tag
        else
        {
            try
            {
                repl.assign(template_t::html_escape(ctx.get(key)[0][key]));
            }
            catch(int i) { repl.assign(""); }
        }

        // replace
        ret += boost::regex_replace(text, tag, repl,
                             boost::match_default | boost::format_all | boost::regex_constants::format_literal);
        // change delimiter after was removed
        if (modifier == "=")
        {
          // regex for finding delimiters
          boost::regex delim("(.+?) (.+?)=");
          // match object
          boost::match_results<std::string::const_iterator> delim_m;
          // search for the delimiters
          boost::regex_search(matches[2].first, matches[2].second, delim_m, delim,
                              boost::match_default | boost::format_all);
          // set new otag and ctag
          std::string new_otag = delim_m[1];
          std::string new_ctag = delim_m[2];
          // change delimiters
          template_t::change_delimiter(new_otag, new_ctag);
        }
        // set start for next tag and rest of std::string
        rest.assign(matches[0].second, end);
        start = matches[0].second;
    }
    // append and return
    ret += rest;
    return ret;
}