Пример #1
0
int main()
{
	freopen("11220.txt", "r", stdin);
	int t, i, j, a, now, k, l;
	scanf("%d%c", &t, &ch);
	getchar();
	for(i=1; i<=t; i++)
	{
		printf("Case #%d:\n", i);
		while(gets(s1))
		{
			now = 0;
			l = strlen(s1);
			if(!l)break;
			for(k=0; k<l; k++)
			{
				a = 0;
				if(isChar(s1[k]))
				{
					while(isChar(s1[k]))
						str[a++] = s1[k++];
					k--;
					str[a] = '\0';
					if(now<a)
						printf("%c", str[now++]);
				}
			}
			printf("\n");
		}
		if(i<t)
			printf("\n");
	}
	return 0;
}
Пример #2
0
std::string getIdentifier(std::string &exp)
{
    std::string token = "";
    if (exp.size() == 0)
        return token;
    
    bool done = false;
    
    for (int i = 0; !done; i ++)
    {
        if (i == 0)
        {
            if (exp[i] == '_' || isChar(exp[i]))
                token += exp[i];
            else
                done = true;
        }
        else
        {
            if (exp[i] == '_' || isChar(exp[i]) || isNum(exp[i]))
                token += exp[i];
            else
                done = true;
        }
        
        if (i >= exp.size())
            done = true;
    }
    
    exp.erase(0, token.size());
    
    return token;
}
Пример #3
0
bool cUObject::onCollide( cUObject* Obstacle )
{
	// If we got ANY events process them in order
	for( UI08 i = 0; i < scriptChain.size(); i++ )
	{
		// Items cannot collide with items
		if( !isChar() ) // Item, so obstacle has to be character
			scriptChain[ i ]->onCollideItem( (P_CHAR)Obstacle, (P_ITEM)this );
		else
			if( Obstacle->isItem() )
				if( scriptChain[ i ]->onCollideItem( (P_CHAR)this, (P_ITEM)Obstacle ) )
					return true;

			else // Character, Character
				if( scriptChain[ i ]->onCollideChar( (P_CHAR)this, (P_CHAR)Obstacle ) )
					return true;
	}

	// Try to process the hooks then
	QValueVector< WPDefaultScript* > hooks;
	QValueVector< WPDefaultScript* >::const_iterator it;

	hooks = ScriptManager->getGlobalHooks( OBJECT_OBJECT, EVENT_COLLIDE );
	for( it = hooks.begin(); it != hooks.end(); ++it )
	{
		// Items cannot collide with items
		if( !isChar() ) // Item, so obstacle has to be character
			(*it)->onCollideItem( (P_CHAR)Obstacle, (P_ITEM)this );
		else
		{
			if( Obstacle->isItem() )
				(*it)->onCollideItem( (P_CHAR)this, (P_ITEM)Obstacle );
			else
				(*it)->onCollideChar( (P_CHAR)this, (P_CHAR)Obstacle );
		}
	}

	if( isChar() )
	{
		hooks = ScriptManager->getGlobalHooks( OBJECT_CHAR, EVENT_COLLIDE );
		for( it = hooks.begin(); it != hooks.end(); ++it )
		{
			if( Obstacle->isItem() )
				(*it)->onCollideItem( (P_CHAR)this, (P_ITEM)Obstacle );
			else
				(*it)->onCollideChar( (P_CHAR)this, (P_CHAR)Obstacle );
		}
	}
	
	if( isItem() )
	{
		hooks = ScriptManager->getGlobalHooks( OBJECT_ITEM, EVENT_COLLIDE );
		for( it = hooks.begin(); it != hooks.end(); ++it )
			(*it)->onCollideItem( (P_CHAR)Obstacle, (P_ITEM)this );
	}

	return false;
}
Пример #4
0
char event(){
        SDL_Event e;
        char c;
        if(SDL_PollEvent(&e)){
            if(e.type == SDL_QUIT) {
                return QUIT;
            }
            if(e.type == SDL_KEYDOWN){
                switch(e.key.keysym.sym){
                    case SDLK_UP:
                        return -2;
                        break;
                    case SDLK_DOWN:
                        return -3;
                        break;
                    case SDLK_RIGHT:
                        return -4;
                        break;
                    case SDLK_LEFT:
                        return -5;
                        break;
                    case SDLK_RETURN:
                        return KEYRETURN;
                        break;
                    default:
                        break;
                }
                if(isChar(e.key.keysym.sym))
                    return isChar(e.key.keysym.sym);
            }
            if(e.type == SDL_MOUSEBUTTONUP){
                switch(e.button.button){
                    case SDL_BUTTON_RIGHT:
                        return CLICKR;
                        break;
                    case SDL_BUTTON_MIDDLE:
                        return CLICKM;
                        break;
                    case SDL_BUTTON_LEFT:
                        return CLICKL;
                        break;
                    /*case SDL_BUTTON_WHEELUP:
                        return WHEELUP;
                        break;
                    case SDL_BUTTON_WHEELDOWN:
                        return WHEELDOWN;
                        break;*/
                }
            }
        }
}
Пример #5
0
// SUBEXP
statment_type subexp::getStatmentType()
{
	build_in_func buildInFunc;
	char *pFuncName;
	parser parParser;
	int iFuncNameLen;

	for (int i = 0; exp[i]; i++)
	{
		if (exp[i] == '=') return Setter;
		else if (isChar(exp[i]))
		{
			iFuncNameLen = isFunc(exp, i);
			if (iFuncNameLen)
			{
				pFuncName = new char[iFuncNameLen];
				parParser.parseFuncName(exp, pFuncName, i);
				if (buildInFunc.chooseFunc(pFuncName) == buildInFunc.chooseFunc("show"))
				{
					delete pFuncName;
					return VoidFunc;
				}
				delete pFuncName;
			}
		}
	}

	return Equation;
}
Пример #6
0
int parser::parseVariable(char *p, int &iStartParse, variable_scope &varScope, bool bReturnParseIndex)
{
	const int iMaxVarNameSize = 36;
	int k = 0 , iParseIndex = iStartParse;
	char cVarName[iMaxVarNameSize];
	int iCurVarIndex;
	for (; p[iParseIndex] && isChar(p[iParseIndex]);k++, iParseIndex++)
	{
		cVarName[k] = p[iParseIndex];
	}
	cVarName[k] = '\0';
	iCurVarIndex = varScope.isExistedVar(cVarName);
	if (bReturnParseIndex) iStartParse = iParseIndex;
	if ( iCurVarIndex != -1 )
	{
		return iCurVarIndex;
	}
	else
	{
		varScope.vScope[varScope.iVarNum].setName(cVarName);
		varScope.iVarNum++;
	}
	// Return "iVarNum-1" becouse index is always less than len on 1 
	return varScope.iVarNum-1;
}
Пример #7
0
 bool isPalindrome(string s) {
     int i = 0;
     int j = s.size() - 1;
     while(i < j){
         while(i < s.size() && !isChar(s[i])) i++;
         while(0 <= j && !isChar(s[j])) j--;
         if(j <= i) return true;
         if(getV(s[i]) == getV(s[j])){
             i++;
             j--;
         }else{
             return false;
         }
     }
     return true;
 }
Пример #8
0
 const bool Rule::DFA_Edge::compare(const char*& first, const char* last)const
 {
     if (first == last) return false;
     if (isFromTo())
     {
         if (compare_fromto(*first))
         {
             ++first;
             return true;
         }
         return false;
     }
     else if (isChar())
     {
         if (compare_char(*first))
         {
             ++first;
             return true;
         }
         return false;
     }
     else if (isString())
     {
         size_t n = 0;
         if (compare_string(first, last, n))
         {
             first += n;
             return true;
         }
         return false;
     }
     return false;
 }
Пример #9
0
void AutoCompletionAgent::tell(string st){
    for (int i=0;i<st.length();i++){
        st[i] = toLowerCase(st[i]);
        if (! isChar(st[i])) return;
    } 
    tree->tell(st);
}
Пример #10
0
    inline const bool Rule::DFA_Edge::compare_char(char c)const
    {
#ifdef _DEBUG
        if (!isChar()) throw error<const char*>("error calling function compare_char!", __FILE__, __LINE__);
#endif
        if (isNot()) return c != value.data.Char.value1;
        else return c == value.data.Char.value1;
    }
Пример #11
0
 const Rule::Variant::Type Rule::Variant::trueType()const
 {
     if (isEpsilon()) return TEpsilon;
     else if (isFromTo()) return TFromTo;
     else if (isChar()) return TChar;
     else if (isString()) return TString;
     else return TUnknown;
 }
Пример #12
0
std::string MxArray::toString() const
{
    if (!isChar())
        mexErrMsgIdAndTxt("mexopencv:error", "MxArray not of type char");
    char *pc = mxArrayToString(p_);
    std::string s(pc);
    mxFree(pc);
    return s;
}
Пример #13
0
int main()
{
	for(int i = 0;i<10;i++)
	{
		char a = '0' + i;
		printf("%d\n",isChar(a));
	}
	return 0;
}
Пример #14
0
int parser::parseFuncArgs(char *p, int &iStartParse, subexp *pSubExp, float *pArgs, int &iArgsNum, variable_scope &varScope)
{
	iStartParse++;
	int iSubIndex = floatToInt(parseDigit(p,iStartParse,true));
    // Implement unary minus here
	for (int i = 0; pSubExp[iSubIndex].exp[i]; i++)
	{
		// Parse digit
		if (isDigit(pSubExp[iSubIndex].exp[i]))
        {
			pArgs[iArgsNum] = parseDigit(pSubExp[iSubIndex].exp, i, true);
		}
		// Parse unary minus
        else if (pSubExp[iSubIndex].exp[i]=='-' && pSubExp[iSubIndex].exp[i+1] && isDigit(pSubExp[iSubIndex].exp[i+1]))
        {
            i++;
            pArgs[iArgsNum] = parseDigit(pSubExp[iSubIndex].exp, i, true, true);
        }
		// Parse next arg
		else if (pSubExp[iSubIndex].exp[i]==',')
		{
			iArgsNum += 1;
			continue;
		}
		// Parse build in func
        else if (isChar(pSubExp[iSubIndex].exp[i]) && isFunc(pSubExp[iSubIndex].exp, i))
        {
            pArgs[iArgsNum] = pSubExp[parseBuildInFunc(pSubExp[iSubIndex].exp, i, pSubExp, varScope, true)].result;
        }
		// Parse variable
		else if (isChar(pSubExp[iSubIndex].exp[i]))
		{
			pArgs[iArgsNum] = varScope.vScope[parseVariable(pSubExp[iSubIndex].exp, i, varScope, false)].getValue();
		}
		// Parse sub string
		else if (pSubExp[iSubIndex].exp[i]=='$')
		{
			pArgs[iArgsNum] = pSubExp[parseSubExp(pSubExp[iSubIndex].exp, i, pSubExp, varScope, true)].result;
		}
	}
	iArgsNum += 1;

	return iSubIndex;
}
Пример #15
0
string AutoCompletionAgent::ask(string st){
    if (enabled=false) return "";
    //misterious
    if (st.length()<2) return "";
    for (int i=0;i<st.length();i++){
        st[i] = toLowerCase(st[i]);
        if (! isChar(st[i])) return "";
    } 
    return tree->ask(st);
}
Пример #16
0
void parser::parseFuncName(char *p, char *cFuncName, int &iStartParse, bool bReturnParseIndex)
{
	int i, k;
	for (i = iStartParse, k = 0; p[i] && isChar(p[i]); i++, k++)
	{
		cFuncName[k] = p[i];
	}
	cFuncName[k] = '\0';
	if (bReturnParseIndex) iStartParse = i;
}
Пример #17
0
/**
 * Lex the string into tokens, each of which has a given offset into the string.
 * Lexing is done by the following algorithm:
 *  (1) If the current character is a space, and if it is then check the next:
 *  	(a) If it is another space, then the token is a tab.
 *	(b) If it is some other character, the token is a space.
 *  (2) If the current character is a character (either upper or lower case), or a digit,
 *	 then continue until the first non-matching character and that is an ident.
 *  (3) If the current character is a #, then ignore everything until the end of the line.
 *  (4) If the current character is a newline, then the token is a newline.
 *  (5) If the current character is a colon, then the token is just a colon.
 *  (6) If the current character is a quote, then read until the endquote and
 *	 declare the string as the contents of the string.
 */
Token* lex(char* input, int len) {
    Token* first = newToken(0, 0, 0);
    Token* last = first;
    int index = 0;
    while (index < len-1) {
        //printf("*");
        int start = index;
        char cur = input[index];
        if (isSpace(cur)) {
            if (isSpace(input[index+1])) {
                index++;
                addNewToken(last, TAB, start, index);
            } else {
                addNewToken(last, SPACE, index, index);
            }
            index++;
        } else if (isTab(cur)) {
            index++;
            addNewToken(last, TAB, start, index);
        } else if (isChar(cur)) {
            while (isChar(input[++index]));
            addNewToken(last, IDENT, start, index);
        } else if (isComment(cur)) {
            while (!isNewLine(input[++index]));
        } else if (isNewLine(cur)) {
            index++;
            addNewToken(last, NEWLINE, index, index);
        } else if (isColon(cur)) {
            index++;
            addNewToken(last, COLON, index, index);
        } else if (isQuote(cur)) {
            while (!isQuote(input[++index]));
            addNewToken(last, STRING, start+1, index);
            index++; /* Pass by the end quote. */
        }
        if (last->next != NULL)
            last = last->next;
    }
    addNewToken(last, NEWLINE, index, index);

    return first->next;
}
Пример #18
0
Файл: 494.cpp Проект: fkrafi/UVa
int main()
{
	int l, i, cnt;
	while(gets(s))
	{
		l = strlen(s);
		cnt = 0;
		for(i=0; i<l; i++)
		{
			if(isChar(s[i]))
			{
				cnt++;
				while(isChar(s[i+1]) && i<l)
					i++;
			}
		}
		printf("%d\n", cnt);
	}
	return 0;
}
Пример #19
0
cv::Range MxArray::toRange() const
{
    cv::Range r;
    if (isNumeric() && numel()==2)
        r = cv::Range(at<int>(0), at<int>(1));
    else if (isChar() && toString()==":")
        r = cv::Range::all();
    else
        mexErrMsgIdAndTxt("mexopencv:error", "Invalid range value");
    return r;
}
Пример #20
0
void raw_string::validateParentheses()
{
    // Check parentless and also check operation symbol before open parentheses
    // and digits before closed parentheses

    int iOpened = 0, iClosed = 0;
    char cSymbols[] = "*/+-", cDigits[] = "0123456789";
    char cBeforeOpen[] = "(,", cAfterOpen[]="(-", cAfterClose[] = ",)";
    for (int i=0; cRawString[i];i++ )
    {
        switch (cRawString[i])
        {
            case '(':
                iOpened += 1;
                if (i!=0 &&
					!(isInArray(cRawString[i-1],cBeforeOpen)) &&
					!(isChar(cRawString[i-1])) &&
					!(isInArray(cRawString[i-1],cSymbols))) throw PreAfterParentlessError;
				if (cRawString[i + 1] &&
					!(isChar(cRawString[i+1])) &&
					!(isInArray(cRawString[i + 1], cDigits)) &&
					!(isInArray(cRawString[i + 1], cAfterOpen))) throw PreAfterParentlessError;
                break;
            case ')':
                iClosed += 1;
                if (i!=0 && cRawString[i-1]!=')' &&
					!(isChar(cRawString[i - 1])) &&
					!(isInArray(cRawString[i-1],cDigits))) throw PreAfterParentlessError;
				if (cRawString[i + 1] &&
					!(isInArray(cRawString[i + 1], cAfterClose)) &&
					!(isInArray(cRawString[i + 1], cSymbols))) throw PreAfterParentlessError;
                if (iClosed>iOpened) throw ParentlessError;
                break;
            default:
                continue;

        }
    }

    if (iClosed != iOpened) throw ParentlessError;
}
Пример #21
0
/*
 * Perform an editing function for the field.
 */
static bool performEdit(CDKFSLIDER *widget, chtype input)
{
   bool result = FALSE;
   bool modify = TRUE;
   int base = widget->fieldWidth;
   int need = formattedSize(widget, widget->current);
   char *temp = (char *)malloc(need + 5);
   char *data = temp;
   char test;
   int col = need - widget->fieldEdit;
   double value;
#define SCANF_FMT "%lg%c"

   if (temp != 0)
   {
      int adj = (col < 0) ? (-col) : 0;
      if (adj)
      {
	 memset(temp, ' ', adj);
	 temp += adj;
      }
      wmove(widget->fieldWin, 0, base);
      winnstr(widget->fieldWin, temp, need);
      strcpy(temp + need, " ");
      if (isChar(input))	/* replace the char at the cursor */
      {
	 temp[col] = CharOf(input);
      }
      else if (input == KEY_BACKSPACE)	/* delete the char before the cursor */
      {
	 modify = removeChar(temp, col - 1);
      }
      else if (input == KEY_DC)	/* delete the char at the cursor */
      {
	 modify = removeChar(temp, col);
      }
      else
      {
	 modify = FALSE;
      }
      if (modify
       && sscanf(temp, SCANF_FMT, &value, &test) == 2
       && test == ' '
       && value >= widget->low
       && value <= widget->high)
      {
	 setCDKFSliderValue(widget, value);
	 result = TRUE;
      }
      free(data);
   }
   return result;
}
Пример #22
0
bool cUObject::onUse( cUObject *Target )
{
	// If we got ANY events process them in order
	for( UI08 i = 0; i < scriptChain.size(); i++ )
	{
		// If we're the Character pass us as the second param
		// if not as the first
		bool Handeled = false;

		if( !this->isChar() )
			Handeled = scriptChain[ i ]->onUse( (P_PLAYER)Target, (P_ITEM)this );
		else
			Handeled = scriptChain[ i ]->onUse( (P_PLAYER)this, (P_ITEM)Target );

		if( Handeled )
			return true;
	}

	// Try to process the hooks then
	QValueVector< WPDefaultScript* > hooks;
	QValueVector< WPDefaultScript* >::const_iterator it;

	hooks = ScriptManager->getGlobalHooks( OBJECT_OBJECT, EVENT_USE );
	for( it = hooks.begin(); it != hooks.end(); ++it )
	{
		if( !this->isChar() )
			(*it)->onUse( (P_PLAYER)Target, (P_ITEM)this );
		else
			(*it)->onUse( (P_PLAYER)this, (P_ITEM)Target );
	}

	if( isChar() )
	{
		hooks = ScriptManager->getGlobalHooks( OBJECT_CHAR, EVENT_USE );
		for( it = hooks.begin(); it != hooks.end(); ++it )
				(*it)->onUse( (P_PLAYER)this, (P_ITEM)Target );
	}
	
	if( isItem() )
	{
		hooks = ScriptManager->getGlobalHooks( OBJECT_ITEM, EVENT_USE );
		for( it = hooks.begin(); it != hooks.end(); ++it )
			(*it)->onUse( (P_PLAYER)Target, (P_ITEM)this );
	}

	return false;
}
Пример #23
0
void mod_comms_service()
{
	char		data;

	switch(mc_comm_mode)
	{
		case MC_IDLE:
			if(isChar())
			{
				data = recvChar();
				// parse command
				switch(data)
				{
					case 'B':
						triggerBeepTone(2);
						break;
						
					case 'C':
						if(mc_count > 9) {
							mc_count = 0;
						}
						sendChar('@');
						sendChar(mc_count + '0');
						sendChar(13);		// CR
						sendChar(10);		// LF
						++mc_count;
						break;
						
					case 'G':
						mod_io_setBlink(100, IO_GREEN_LED);
						break;

					case 'R':
						mod_io_setBlink(100, IO_RED_LED);
						break;
						
					default:
						break;
				}
			}
			break;

		default:
			mc_comm_mode = MC_IDLE;
			break;
	}
}
Пример #24
0
/*
 * Perform an editing function for the field.
 */
static bool performEdit(CDKUSCALE *widget, chtype input)
{
    bool result = FALSE;
    bool modify = TRUE;
    int base = 0;
    int need  = widget->fieldWidth;
    char *temp = (char *)malloc(need + 2);
    char test;
    int col = need - widget->fieldEdit - 1;
    unsigned value;
#define SCANF_FMT "%u%c"

    if (temp != 0)
    {
        wmove(widget->fieldWin, 0, base);
        winnstr(widget->fieldWin, temp, need);
        strcpy(temp + need, " ");
        if (isChar(input))	/* replace the char at the cursor */
        {
            temp[col] = CharOf(input);
        }
        else if (input == KEY_BACKSPACE)	/* delete the char before the cursor */
        {
            modify = removeChar(temp, col - 1);
        }
        else if (input == KEY_DC)	/* delete the char at the cursor */
        {
            modify = removeChar(temp, col);
        }
        else
        {
            modify = FALSE;
        }
        if (modify
                && sscanf(temp, SCANF_FMT, &value, &test) == 2
                && test == ' '
                && value >= widget->low
                && value <= widget->high)
        {
            setCDKUScaleValue(widget, value);
            result = TRUE;
        }
        free(temp);
    }
    return result;
}
Пример #25
0
bool
Unicode::toUtf8(uint32 ucs4, char *out, int &len)
{
    const char replacement[] = {'\xef','\xbf','\xbd'};
    bool isUC = isChar(ucs4);
    if(!isUC) {
        memcpy(out,replacement,3);
        len = 3;
        return false;
    } else {
        if(ucs4 < 0x80) {
            out[0] = (char)ucs4;
            len = 1;
        } else if(ucs4 < 0x800) {
            out[0] = 0xC0 | (ucs4 >> 6);
            out[1] = 0x80 | (ucs4 & 0x3F);
            len = 2;
        } else if(ucs4 < 0x10000) {
Пример #26
0
bool cUObject::onCreate( const QString &definition )
{
	// If we got ANY events process them in order
	for( UI08 i = 0; i < scriptChain.size(); i++ )
	{
		// If we're the Character pass us as the second param
		// if not as the first
		bool Handeled = false;

		Handeled = scriptChain[ i ]->onCreate( this, definition );

		if( Handeled )
			return true;
	}

	// Try to process the hooks then
	QValueVector< WPDefaultScript* > hooks;
	QValueVector< WPDefaultScript* >::const_iterator it;

	hooks = ScriptManager->getGlobalHooks( OBJECT_OBJECT, EVENT_CREATE );
	for( it = hooks.begin(); it != hooks.end(); ++it )
		(*it)->onCreate( this, definition );

	if( isChar() )
	{
		hooks = ScriptManager->getGlobalHooks( OBJECT_CHAR, EVENT_CREATE );
		for( it = hooks.begin(); it != hooks.end(); ++it )
			(*it)->onCreate( this, definition );
	}
	
	if( isItem() )
	{
		hooks = ScriptManager->getGlobalHooks( OBJECT_ITEM, EVENT_CREATE );
		for( it = hooks.begin(); it != hooks.end(); ++it )
			(*it)->onCreate( this, definition );
	}

	return false;
}
Пример #27
0
TokenType nextTokenType(std::string exp)
{
    if (exp.size() == 0)
        return TT_UNDEFINED;
    if (exp[0] == '&')
        return TT_OPERATOR;
    if (exp[0] == '|')
        return TT_OPERATOR;
    if (iswhiteSp(exp[0]))
        return TT_WHITESPACE;
    if (isChar(exp[0]) || exp[0] == '_')
        return TT_IDENTIFIER;
    if (isNum(exp[0]))
        return TT_NUMBER;
    if (exp[0] == '\"')
        return TT_STRING;
    
    if (exp.size() == 1)
    {
        if (isLangSym(exp[0]))
            return TT_LANGSYM;
        if (isOpSym(exp[0]))
            return TT_OPERATOR;
    }
    else
    {
        if (exp[0] == '.' && isNum(exp[1]))
            return TT_NUMBER;
        else if (isLangSym(exp[0]))
            return TT_LANGSYM;
        else if (isOpSym(exp[0]))
            return TT_OPERATOR;
    }
    
    return TT_UNDEFINED;
}
Пример #28
0
bool ASTType::isValueType() const
{
   return isNumeric() || isChar() || isString();
}
Пример #29
0
boost::tribool
RequestParser::consume(Request &req, char input, http::CompressionType *compressionType)
{
    switch (state_)
    {
    case method_start:
        if (!isChar(input) || isCTL(input) || isTSpecial(input))
        {
            return false;
        }
        state_ = method;
        return boost::indeterminate;
    case method:
        if (input == ' ')
        {
            state_ = uri;
            return boost::indeterminate;
        }
        if (!isChar(input) || isCTL(input) || isTSpecial(input))
        {
            return false;
        }
        return boost::indeterminate;
    case uri_start:
        if (isCTL(input))
        {
            return false;
        }
        state_ = uri;
        req.uri.push_back(input);
        return boost::indeterminate;
    case uri:
        if (input == ' ')
        {
            state_ = http_version_h;
            return boost::indeterminate;
        }
        if (isCTL(input))
        {
            return false;
        }
        req.uri.push_back(input);
        return boost::indeterminate;
    case http_version_h:
        if (input == 'H')
        {
            state_ = http_version_t_1;
            return boost::indeterminate;
        }
        return false;
    case http_version_t_1:
        if (input == 'T')
        {
            state_ = http_version_t_2;
            return boost::indeterminate;
        }
        return false;
    case http_version_t_2:
        if (input == 'T')
        {
            state_ = http_version_p;
            return boost::indeterminate;
        }
        return false;
    case http_version_p:
        if (input == 'P')
        {
            state_ = http_version_slash;
            return boost::indeterminate;
        }
        return false;
    case http_version_slash:
        if (input == '/')
        {
            state_ = http_version_major_start;
            return boost::indeterminate;
        }
        return false;
    case http_version_major_start:
        if (isDigit(input))
        {
            state_ = http_version_major;
            return boost::indeterminate;
        }
        return false;
    case http_version_major:
        if (input == '.')
        {
            state_ = http_version_minor_start;
            return boost::indeterminate;
        }
        if (isDigit(input))
        {
            return boost::indeterminate;
        }
        return false;
    case http_version_minor_start:
        if (isDigit(input))
        {
            state_ = http_version_minor;
            return boost::indeterminate;
        }
        return false;
    case http_version_minor:
        if (input == '\r')
        {
            state_ = expecting_newline_1;
            return boost::indeterminate;
        }
        if (isDigit(input))
        {
            return boost::indeterminate;
        }
        return false;
    case expecting_newline_1:
        if (input == '\n')
        {
            state_ = header_line_start;
            return boost::indeterminate;
        }
        return false;
    case header_line_start:
        if (header.name == "Accept-Encoding")
        {
            /* giving gzip precedence over deflate */
            if (header.value.find("deflate") != std::string::npos)
            {
                *compressionType = deflateRFC1951;
            }
            if (header.value.find("gzip") != std::string::npos)
            {
                *compressionType = gzipRFC1952;
            }
        }

        if ("Referer" == header.name)
        {
            req.referrer = header.value;
        }

        if ("User-Agent" == header.name)
        {
            req.agent = header.value;
        }

        if (input == '\r')
        {
            state_ = expecting_newline_3;
            return boost::indeterminate;
        }
        if (!isChar(input) || isCTL(input) || isTSpecial(input))
        {
            return false;
        }
        state_ = header_name;
        header.Clear();
        header.name.push_back(input);
        return boost::indeterminate;
    case header_lws:
        if (input == '\r')
        {
            state_ = expecting_newline_2;
            return boost::indeterminate;
        }
        if (input == ' ' || input == '\t')
        {
            return boost::indeterminate;
        }
        if (isCTL(input))
        {
            return false;
        }
        state_ = header_value;
        return boost::indeterminate;
    case header_name:
        if (input == ':')
        {
            state_ = space_before_header_value;
            return boost::indeterminate;
        }
        if (!isChar(input) || isCTL(input) || isTSpecial(input))
        {
            return false;
        }
        header.name.push_back(input);
        return boost::indeterminate;
    case space_before_header_value:
        if (input == ' ')
        {
            state_ = header_value;
            return boost::indeterminate;
        }
        return false;
    case header_value:
        if (input == '\r')
        {
            state_ = expecting_newline_2;
            return boost::indeterminate;
        }
        if (isCTL(input))
        {
            return false;
        }
        header.value.push_back(input);
        return boost::indeterminate;
    case expecting_newline_2:
        if (input == '\n')
        {
            state_ = header_line_start;
            return boost::indeterminate;
        }
        return false;
    case expecting_newline_3:
        return (input == '\n');
    default:
        return false;
    }
}
Пример #30
0
void bank_process_local_command(Bank *bank, char *command, size_t len)
{
    // TODO: Implement the bank's local commands
    char *line = strtok (command," ");

    if(line != NULL){
        if(strcmp(line, "create-user") == 0){
            char *name = strtok(NULL, " ");
            char *pinStr = strtok(NULL, " ");
            char *balanceStr = strtok(NULL, " ");
            char *check = strtok(NULL, " ");

            if(name == NULL || pinStr == NULL || balanceStr == NULL || check != NULL){
                printf("Usage: create-user <user-name> <pin> <balance>\n");
            }
            else{
                if(strlen(name) > 250 || strlen(pinStr) != 4 || isChar(name, strlen(name)) == 0 || isNum(pinStr, 4) == 0 || isNum(balanceStr, strlen(balanceStr)-1) == 0){
                    printf("Usage: create-user <user-name> <pin> <balance>\n");
                }
                else{
                    unsigned int balance = atoi(balanceStr);
                    if(balance >= INT_MAX) 
                        printf("Usage: create-user <user-name> <pin> <balance>\n");
                    else{
                        Node *user = NULL;
                        if(bank->clientHead != NULL)
                            user = get_client(bank->clientHead, name);
                        if(user == NULL){
                            Node *put = malloc(sizeof(Node));
                            FILE *file;
                            char *filename = malloc(strlen(name) + 6);


                            memcpy(filename, name, strlen(name));
                            filename[strlen(name)] = '.';
                            filename[strlen(name)+1] = 'c';
                            filename[strlen(name)+2] = 'a';
                            filename[strlen(name)+3] = 'r';
                            filename[strlen(name)+4] = 'd';
                            filename[strlen(name)+5] = 0;

                            file = fopen(filename, "w+");

                            if(file != NULL){
                                EVP_MD_CTX *ctx = EVP_MD_CTX_create();
                                uint8_t thehash[32];
                                int hashlen;
                                uint32_t namelen = strlen(name);
                                uint8_t *data = malloc(4 + strlen(name) + 32);
                                put->name = malloc(strlen(name) + 1);

                                memcpy(put->name, name, namelen+1);

                                put->PIN[0] = pinStr[0];
                                put->PIN[1] = pinStr[1];
                                put->PIN[2] = pinStr[2];
                                put->PIN[3] = pinStr[3];

                                put->balance = balance;
                                put->next = bank->clientHead;
                                if(bank->clientHead != NULL)
                                    bank->clientHead->prev = put;
                                put->prev = NULL;
                                bank->clientHead = put;

                                EVP_DigestInit_ex(ctx, EVP_sha256(), NULL);

                                EVP_DigestUpdate(ctx, pinStr, 4);
                                EVP_DigestFinal_ex(ctx, thehash, &hashlen);

                                memcpy(data, &namelen, 4);
                                memcpy(data + 4, name, namelen);
                                memcpy(data + 4 + namelen, thehash, 32);

                                fwrite(data, 1, namelen + 36, file);
                                fclose(file);

                                printf("Created user %s\n", name);
                                free(data);
                                EVP_MD_CTX_destroy(ctx);
                            }
                            else
                                printf("Error creating card file for user %s\n", name);

                        
                            free(filename);
                        }
                        else{
                            printf("Error: user %s already exists\n", name);
                        }
                    }
                }
            }
        }
        else{
            if(strcmp(line, "deposit") == 0){
                char *name = strtok(NULL, " ");
                char *amtStr = strtok(NULL, " ");
                char *check = strtok(NULL, " ");
                if(name == NULL || amtStr == NULL || check != NULL)
                    printf("Usage: deposit <user-name> <amt>\n");
                else{
                    if(strlen(name) > 250 || isChar(name, strlen(name)) == 0 || isNum(amtStr, strlen(amtStr)-1) == 0){
                        printf("Usage: deposit <user-name> <amt>\n");
                    }
                    else{
                        unsigned int amt = atoi(amtStr);
                        if(amt >= INT_MAX)
                            printf("Too rich for this program\n");
                        else{  
                            Node *user = get_client(bank->clientHead, name);
                            if(user == NULL){
                                printf("No such user\n");
                            }
                            else{
                                unsigned int newbal = user->balance + amt;
                                if(newbal >= INT_MAX)
                                    printf("Too rich for this program\n");
                                else{
                                    user->balance = newbal;
                                    printf("$%u added to %s's account\n", amt, name);
                                }
                            }
                        }
                    }
                }

            }
            else{
                if(strcmp(line, "balance") == 0){
                    char *name = strtok(NULL, " ");
                    char *check = strtok(NULL, " ");
                    if(name == NULL || check != NULL)
                        printf("Usage: balance <user-name>\n");
                    else{
                        if(strlen(name) > 250 || isChar(name, strlen(name)-1) == 0){
                            printf("Usage: balance <user-name>\n");
                        }
                        else{
                            Node *user = NULL;

                            name[strlen(name)-1] = 0;

                            if(bank->clientHead != NULL)
                                user = get_client(bank->clientHead, name);

                            if(user == NULL){
                                printf("No such user\n");
                            }
                            else{
                                printf("$%u\n", user->balance);
                            }
                        }
                    }

                }
                else{
                    printf("Invalid command\n");
                }
            }
        }

    }
    else{
        printf("Invalid command\n");
    }

}