Example #1
0
int main(int argc, char *argv[])
{
    const char *word = argv[1];
    int array[argc - 2];

    if(argc < 3) {
        printf("You forgot to set word/fileNames!\n");
        exit(1);
    }
    for(int index = 0; index < argc - 2; index++){
        int temp = 0;
        int textCounter = 0;
        char ch;
        char *text = (char*)malloc(sizeof(char));

        FILE *file;
        if(!(file = fopen(argv[index + 2], "r"))){
            printf("Cannot open the #%i file\n", (index + 1));
            exit(2);
        }
        while((ch = fgetc(file)) != EOF){
            textCounter++;
            text = (char*)realloc(text, textCounter * sizeof(char));
            text[textCounter - 1] = ch;
        }
        fclose(file);
        temp = func(word, text, checkWord(word), (textCounter));
        free(text);
        array[index] = temp;
    }
    printf("Arithmetic Mean is %f\n",arithmeticMean(array, sizeof(array) / 4));
    return 0;
}
void Player::oneWord(std::string word, std::string encoding)
{
	std::vector<std::vector<char>> board = decode(encoding);
	//holds the previous word, because sometimes there is duplicates
	std::string prev = "";
	//keeps track of visited cells
	bool visited[X_SIZE][Y_SIZE] = {{false}};
	bool found = false;
	//searches the board to find the starting letter of the word being searched for
	for(int i = 0; i < X_SIZE; i++){
		for(int j = 0; j < Y_SIZE; j++){
			if(board[i][j] == word[0]){
				found = checkWord(board, visited, i, j, word, 1);
				if(found){
					std::cout << "YES" << std::endl;
					return;
				}
			}
		}
		if(found){
			break;
		}
	}
	if(!found){
		std::cout << "NO" << std::endl;
	}
}
bool Player::checkWord(std::vector<std::vector<char>> board , bool visited[X_SIZE][Y_SIZE], 
						int i, int j, std::string word, unsigned int level)
{
	bool found = false;
	//this cell has been visited in this branch of recursion
	visited[i][j] = true;
	//base case, if word has been found
	if(level == word.length()){
		return true;
	}
	//traverses adjacent cells
	for(int x = i-1; x <= i + 1 && x < X_SIZE; x++){
		for(int y = j-1; y <= j + 1 && y < Y_SIZE; y++){
			if(x >= 0 && y >= 0 && !visited[x][y] && word[level] == board[x][y]){
				found = checkWord(board, visited, x, y, word, level+1);
				if(found){
					break;
				}
			}
		}
		if(found){
			break;
		}
	}
	//if the word cant be made at this adjacent square set it not being visted so if it is needed later in the word
	//it can be used.
	visited[i][j] = false;
	return found;
}
void Player::listWords(std::string encoding)
{
	std::vector<std::vector<char>> board = decode(encoding);
	std::string prev = "";
	//loops through each word in dictionary
	for(int i = 0; i < dictionarySize; i++){
		//gets the word from the dictionary to search for it
		std::string word = wordlist.getWord(i);
		//keeps track of visited cells
		bool visited[X_SIZE][Y_SIZE] = {{false}};
		bool found = false;
		//searches the board to find the starting letter of the word being searched for
		for(int i = 0; i < X_SIZE; i++){
			for(int j = 0; j < Y_SIZE; j++){
				if(board[i][j] == word[0]){
					found = checkWord(board, visited, i, j, word, 1);
					if(found && word != prev){
						//compares the word to the previous word to check for duplicates,
						//this occurs very rarely
						prev = word;
						std::cout << word << std::endl;
					}
				}
			}
			if(found){
				break;
			}
		}
	}
}
void Highlighter::spellCheck(const QString &text)
{
	if (spellCheckActive) {
		// split text into words
		QString str = text.simplified();
		if (!str.isEmpty()) {
			QStringList Checkliste = str.split(QRegExp("([^\\w,^\\\\]|(?=\\\\))+"),
					QString::SkipEmptyParts);
			int l,number;
			// check all words
			for (int i=0; i<Checkliste.size(); ++i) {
				str = Checkliste.at(i);
				if (str.length()>1 &&!str.startsWith('\\'))
				{
					if (!checkWord(str)) {
						number = text.count(QRegExp("\\b" + str + "\\b"));
						l=-1;
						// underline all incorrect occurences of misspelled word
						for (int j=0;j < number; ++j)
						{
							l = text.indexOf(QRegExp("\\b" + str + "\\b"),l+1);
							if (l>=0)
								setFormat(l, str.length(), spellCheckFormat);
						} // for j
					} // if spell chek error
				} // if str.length > 1
			} // for
		} // if str.isEmpty
	} // initial check
}
Example #6
0
int main(int argc, char** argv) {
  char msg[SIZE];
		int len=0;
		int start=0;
		int *pstart=&start; 
		int end=0;
		int *pend=&end;
		int count=0;
		// read in every line of the tweets
  while ((len = readMsg(msg)) != EOF) {
    // get every word in the current line
    *pstart=0;
				*pend=0;
    while (getWord(msg,len,pstart,pend)) {
      // turn the word to small case
//	printf("start %d\n", *pend - *pstart);
//	printf("end %d\n", *pend);
      count = *pstart;
						while(count <= *pend) {
							unCapitalize(msg+count);
							count++;
      }
      // check and process the word
	printf("word %s\n",(msg+*pstart));
      checkWord((msg+*pstart),*pend-*pstart,argv,argc); 
    		
	}
    // output the processed message
    for(count=0;count<len;count++) {
   // putchar(*(msg+count));
    }
  }
  return 0;
}
Example #7
0
void highlighterClass::spellCheck(const QString &text)
{
    if(spellCheckActive == true)
    {
        QString simplifiedText = text.simplified();
        if(simplifiedText.isEmpty() == false)
        {
            QStringList checkList = simplifiedText.split(QRegExp("[^\\w'-]+"), QString::SkipEmptyParts);
            for(const QString& thisString : checkList)
            {
                simplifiedText = thisString;
                if(simplifiedText.length() > 1)
                {
                    if(checkWord(simplifiedText) == false)
                    {
                        int wordCount;
                        int index = -1;
                        wordCount = text.count(QRegExp("\\b" + simplifiedText + "\\b"));
                        for(int j = 0; j < wordCount; ++j)
                        {
                            index = text.indexOf(QRegExp("\\b" + simplifiedText + "\\b"), index + 1);
                            if(index >= 0)
                            {
                                setFormat(index, simplifiedText.length(), spellCheckFormat);
                            }
                        }
                    }
                }
            }
        }
    }
}
Example #8
0
int main(int argc, string argv[]){
    if(argc == 2 && argv[1] != NULL){
        //cypher word
        string word = argv[1];
        //check if word is all letters.
        if(checkWord(word) == 1){
            printf("Invalid Input\n");
            return 1;
        }
        string text = GetString();
        
        int word_len = strlen(word);
        //printf("%s\n", argv[1]);
        //keep track of char position in word.
        int count = 0;
        for(int x=0,n=strlen(text);x<n;x++){
            if(count == word_len){
                count = 0;
            }
            if(isalpha(text[x])){
                convertToCypher(tolower(word[count])-'a', text[x]);
                count+=1;
            }
            else{
                printf("%c",text[x]);
            }
        }
        printf("\n");
        return 0;
    }
    else{
       printf("Did not recieve proper number of arguments\n");
       return 1;
    }
}
Example #9
0
int main(int argv, char *argc){
	int i = 0,
		len = 0,
		lenSentence = 0,
		flag = 0;
	char sentence[WORD*WORDS];
	char ch;
	
	while((ch = getchar()) != '\n'){
		if(ch != ' '){
			flag = 0;
			sentence[i] = ch;
			i++;
			len++;
		}
		else if(flag == 0){
			flag = 1;
			sentence[i] = ch;
			i++;
			len++;
		}
	}

	lenSentence = checkSentence(len, sentence);
	checkWord(lenSentence, sentence);
	checkWords(lenSentence, sentence);
	printWords(lenSentence, sentence);

	system("PAUSE");
	return 0;
}
Example #10
0
Word::Word(std::string const str){
	if (checkWord(str))
		throw std::invalid_argument{"Invalid word characters"};

	std::stringstream ss;
	ss << str;
	read(ss);
}
Example #11
0
static bool checkFile(char * filename, const char hash[17], const char * const salt, bool caseSensitive, int *returnValue)
{
	char ** words = NULL;
	*returnValue = 0;

	words = ReadFile(filename);
	if (words == NULL) {
		printf("Invalid file: %s\n", filename);
		*returnValue = 1;
		return false;
	}

	char buff[strlen(salt) + maxLength + 1];
	char * const end = buff + maxLength * sizeof(char); //end is the part where the salt begins
	
	memcpy(end, salt, strlen(salt) * sizeof(char));
	*(end + strlen(salt) * sizeof(char)) = '\0'; //puts the \0 as last char in de buff 
	
	char * iter;
	for (iter = buff; iter < end; iter += sizeof(char)) { //sets all the char before the salt as \0
		*(iter) = '\0';
	}

	printf("Checking for password ");
	fflush(stdout);

	int count;
	char *start;
	int length;
	for(count = 0;count < nbLines; count++){
		if ((count << (sizeof(int) * 8 - 10)) == 0) {
			printf(".");
			fflush(stdout);
		}

		length = strlen(words[count]);
		start = end - length;
		memcpy(start, words[count], length * sizeof(char)); //tries to copy the string on the right place in the buff
		
		if(checkWord(start, length, hash, caseSensitive)) {
			printf("\nMatch: %s\nPassword: %s\n", start, words[count]);
			return true;
		}
	}
	printf("\nThe password is not in the dictonary.\n\n");
	return false;	
}
Example #12
0
void ChatView::checkTag(QTextCursor &cursor, QString &message)
{
    if (message.startsWith("[card]"))
    {
        message = message.mid(6);
        int closeTagIndex = message.indexOf("[/card]");
        QString cardName = message.left(closeTagIndex);
        if (closeTagIndex == -1)
            message.clear();
        else
            message = message.mid(closeTagIndex + 7);
        
        appendCardTag(cursor, cardName);
        return;
    }

    if (message.startsWith("[["))
    {
        message = message.mid(2);
        int closeTagIndex = message.indexOf("]]");
        QString cardName = message.left(closeTagIndex);
        if (closeTagIndex == -1)
            message.clear();
        else
            message = message.mid(closeTagIndex + 2);
        
        appendCardTag(cursor, cardName);
        return;
    }

    if (message.startsWith("[url]"))
    {
        message = message.mid(5);
        int closeTagIndex = message.indexOf("[/url]");
        QString url = message.left(closeTagIndex);
        if (closeTagIndex == -1)
            message.clear();
        else
            message = message.mid(closeTagIndex + 6);
        
        appendUrlTag(cursor, url);
        return;
    }

    // no valid tag found
    checkWord(cursor, message);
}
Example #13
0
std::istream& Word::read(std::istream &in){
	char character{};
	std::string w{};
	while(in.get(character) && !std::isalpha(character));
	while (std::isalpha(character)){
		w += std::tolower(character);
		if (!in.get(character)) break;
	}
	if (checkWord(w))
		 in.clear(std::ios::failbit);
	else {
		value=w;
		if (in.eof()) in.clear();
	}

	return in;
}
Example #14
0
//__________________________________________________________________________
bool Speller::Aspell::Suggest::checkWord(const std::string& word,
					 std::vector<std::string>& replacement,
					 bool always)
	throw( std::invalid_argument )
{
	// Checks 'word', and returns true if it is spelt correctly,
	// else returns false. If 'always' is true, returns an
	// array of suggestions in 'replacement', regardless of
	// whether 'word' is spelt incorrectly or not. Else, if
	// 'always' is false, the list of suggestions is stored only if
	// 'word'is spelt incorrectly.
	bool status = checkWord( word );

	if( always )
	{
		const AspellWordList* wlist =
			aspell_speller_suggest( fspeller, word.c_str(), -1 );
		try
		{
			storeWordList( wlist, replacement );
		}
		catch( const std::invalid_argument& err )
		{
			throw err;
		}
	}
	else
	{
		if( ! status )
		{
			const AspellWordList* wlist =
				aspell_speller_suggest( fspeller, word.c_str(),
							-1 );
			try
			{
				storeWordList( wlist, replacement );
			}
			catch( const std::invalid_argument& err )
			{
				throw err;
			}
		}
	}
	return status;
}
Example #15
0
//__________________________________________________________________________
bool Speller::Aspell::Suggest::printSuggestions(const std::string& word,
						bool always)
	throw( std::invalid_argument )
{
	// Checks 'word', and returns true if it is spelt correctly,
	// else returns false. If 'always' is true, prints a list of
	// suggestions to the console as UTF-8, regardless of whether
	// 'word' is spelt correctly, or not. Else, if 'always' is
	// false, only prints the list if 'word' is incorrect.
	bool status = checkWord( word );

	if( always )
	{
		const AspellWordList* wlist =
			aspell_speller_suggest( fspeller, word.c_str(), -1 );
		try
		{
			printWordList( wlist );
		}
		catch( const std::invalid_argument& err )
		{
			throw err;
		}
	}
	else
	{
		if( ! status )
		{
			const AspellWordList* wlist =
				aspell_speller_suggest( fspeller, word.c_str(),
							-1 );
			try
			{
				printWordList( wlist );
			}
			catch( const std::invalid_argument& err )
			{
				throw err;
			}
		}
	}
	return status;  
}
Example #16
0
int main(int argc, char** argv) {
	int ch=255;
	char a=ch;
	char msg[]="hkyhuyfytfy ytytuy iu";
	msg[0]=a;
	int len;
	int start=0;
	int end=0;
	char* index=msg;
	int i=0;
	

  // read in every line of the tweets
  while ((len=readMsg(msg))!=EOF) {
      start=0;
      end=0;


    // get every word in the current line
    while (getWord(msg,len,&start,&end)) {
	    i=0;
	    while (i<len){
		unCapitalize(index+i);
	    i++;
	      
	    }
      // turn the word to small case
		checkWord(index+start,end-start,argv+1,argc-1);

      // check and process the word
    }
    i=0;
    while(i<len){
      printf("%c", msg[i]);
      i++;
    }
    // output the processed message
  }
  return 0;
}
Example #17
0
void testTurn(){ 
	
	Grid<char> board = makeRandomBoard(StandardCubes); 
	Vector<pointT> moves = makeDeltas();

	DrawBoard(4,4); 
	addLetters(board); 
	
	while (true){ 
		cout << "Enter Word: " << endl;
		string s = GetLine(); 
		if (s == "") break; 
		
		cout << "Word entered: " << s << endl;
		Vector<pointT> path; 
		bool res = checkWord(s, board, moves,path); 
		if (res) cout << "checkWord returned true" << endl;
		if (!res) cout << "checkWord returned false" << endl; 
		highlightPath(path); 
		Pause(0.5); 
		clearHighlights(board); 
		
	}
}
Example #18
0
int main(int argc, char** argv) {
  char msg[SIZE];
  // read in every line of the tweets 
  //int counter = 0; 
  int length = 0 ; 
  int  start = 0;
  int  end  = 0;  
  while (length = readMsg(msg) != EOF) 
   {

	 unCapitalize (msg); 
	
	    while ( getWord(msg,length,&start, &end) ) 
	   {
	     
		 
	      checkWord(msg,length,argv , argc);	      // check and process the word
	    }
    // output the processed message 
  	
  }
printf("%s", msg);
 return 0;
}
Example #19
0
void ChatView::checkMention(QTextCursor &cursor, QString &message, QString &sender, UserLevelFlags userLevel)
{
    const QRegExp notALetterOrNumber = QRegExp("[^a-zA-Z0-9]");

    int firstSpace = message.indexOf(' ');
    QString fullMentionUpToSpaceOrEnd = (firstSpace == -1) ? message.mid(1) : message.mid(1, firstSpace - 1);
    QString mentionIntact = fullMentionUpToSpaceOrEnd;

    QMap<QString, UserListTWI *> userList = tabSupervisor->getUserListsTab()->getAllUsersList()->getUsers();

    while (fullMentionUpToSpaceOrEnd.size())
    {
        if (isFullMentionAValidUser(userList, fullMentionUpToSpaceOrEnd)) // Is there a user online named this?
        {
            if (userName.toLower() == fullMentionUpToSpaceOrEnd.toLower()) // Is this user you?
            {
                // You have received a valid mention!!
                soundEngine->playSound("chat_mention");
                mentionFormat.setBackground(QBrush(getCustomMentionColor()));
                mentionFormat.setForeground(settingsCache->getChatMentionForeground() ? QBrush(Qt::white) : QBrush(Qt::black));
                cursor.insertText(mention, mentionFormat);
                message = message.mid(mention.size());
                QApplication::alert(this);
                if (settingsCache->getShowMentionPopup() && shouldShowSystemPopup())
                {
                    QString ref = sender.left(sender.length() - 2);
                    showSystemPopup(ref);
                }
            } else {
                QString correctUserName = getNameFromUserList(userList, fullMentionUpToSpaceOrEnd);
                UserListTWI *vlu = userList.value(correctUserName);
                mentionFormatOtherUser.setAnchorHref("user://" + QString::number(vlu->getUserInfo().user_level()) + "_" + correctUserName);
                cursor.insertText("@" + correctUserName, mentionFormatOtherUser);

                message = message.mid(correctUserName.size() + 1);
            }

            cursor.setCharFormat(defaultFormat);
            return;
        }

        if (isModeratorSendingGlobal(userLevel, fullMentionUpToSpaceOrEnd)) {
            // Moderator Sending Global Message
            soundEngine->playSound("all_mention");
            mentionFormat.setBackground(QBrush(getCustomMentionColor()));
            mentionFormat.setForeground(settingsCache->getChatMentionForeground() ? QBrush(Qt::white) : QBrush(Qt::black));
            cursor.insertText("@" + fullMentionUpToSpaceOrEnd, mentionFormat);
            message = message.mid(fullMentionUpToSpaceOrEnd.size() + 1);
            QApplication::alert(this);
            if (settingsCache->getShowMentionPopup() && shouldShowSystemPopup())
            {
                QString ref = sender.left(sender.length() - 2);
                showSystemPopup(ref);
            }

            cursor.setCharFormat(defaultFormat);
            return;
        }

        if (fullMentionUpToSpaceOrEnd.right(1).indexOf(notALetterOrNumber) == -1 || fullMentionUpToSpaceOrEnd.size() < 2)
        {
            cursor.insertText("@" + mentionIntact, defaultFormat);
            message = message.mid(mentionIntact.size() + 1);
            cursor.setCharFormat(defaultFormat);
            return;
        }

        fullMentionUpToSpaceOrEnd.chop(1);
    }

    // no valid mention found
    checkWord(cursor, message);
}
Example #20
0
solution solve(string &c, bigNumber previous, settings &user)
{
    c += '$';
    PTYPE pType=ERROR;
    
    vector<int> first;
    vector<int> second;
    bigNumber bn1;
    bigNumber bn2;
    bigNumber temp;
    
    bn1.setBase(user.getBase());
    bn2.setBase(user.getBase());
    temp.setBase(user.getBase());

    int decimalCount1=0;
    int decimalCount2=0;
    int commaNumbers=0;
    int numbers=0;

    bool decimal=false;
	bool comma=false;
	bool negative1=false;
	bool negative2=false;
    bool done=false;
	bool printExact=false;
	bool printStats=false;

    bigNumber* targetBN = &bn1;
    vector<int>* targetVec = &first;
    int* targetDec = &decimalCount1;
	bool* targetNegative = &negative1;
    
    int counter = c.size();
    
    for (int i=0; i<counter; i++)
    {
        if (checkWord(c, i, "pi"))
        {
            if (numbers>0 || comma==true || decimal==true)
            {
                RETURN_ERROR;
            }
            
            else
            {
                string piString(PI);
		
				for (int piMarker=PRECISION; piMarker>=0; piMarker--)
				{
					char piChar = '0';
					int piNum = piString[PRECISION-piMarker] - piChar;
				
					(*targetVec).push_back(piNum);
				}
                
                done=true;
				*targetDec = PRECISION;
                
                numbers += (PRECISION+1);
                counter += 2;
                i += 2;
            }
        }
        
        if (checkWord(c, i, "theta"))
        {
            if (numbers>0 || comma==true || decimal==true)
            {
                RETURN_ERROR;
            }
            
            else
            {
                string thetaString(THETA);
		
				for (int thetaMarker=PRECISION; thetaMarker>=0; thetaMarker--)
				{
					char thetaChar = '0';
					int thetaNum = thetaString[PRECISION-thetaMarker] - thetaChar;
				
					(*targetVec).push_back(thetaNum);
				}
                
                done=true;
				*targetDec = PRECISION;
                
                numbers += (PRECISION+1);
                counter += 5;
                i += 5;
            }
        }
        
		//if it isn't a space, number, symbol, end marker, or decimal point, return error
		if (checkSpace(c[i])==false && 
			isNumber(c[i], user)==false && 
			isSymbol(c[i])==false && 
			c[i] != '$' && 
			c[i] != ',' && 
			c[i] != '.')
		{
			RETURN_ERROR;
		}

		if (c[i]==',')
		{
			if (comma==false)
			{
				if (decimal==true || numbers==0 || numbers > 3 || done==true)
					RETURN_ERROR;

				else comma = true;
			}

			else if (commaNumbers != 3)
			    RETURN_ERROR;
			    
			commaNumbers=0;    
		}
			
		//if it's a space
		else if (checkSpace(c[i])==true)
		{
			//if it's preceeded by a number, number is complete
			if (isNumber(c[i-1], user))
		    {
		        done = true;
		    }
		    
		    //if negative is set, and it is preceeded by a minus symbol, return error
		    else if (checkSymbol(c[i-1]) == SUBTRACT && *targetNegative == true)
		    {
		        RETURN_ERROR;
		    }
		}

        //if it's a number
        else if (isNumber(c[i], user))
        {        
            //if number was complete, return error
            if (done==true)
			{
                RETURN_ERROR;
			}
			
		    if (comma==true)
		        commaNumbers++;
                
            //otherwise add number to target vector, add decimal count if needed
            (*targetVec).push_back(checkNumber(c[i]));
                numbers++;
                
            if (decimal==true)
			{
                (*targetDec)++;
			}
        }
        
        //if it's a minus symbol
        else if (checkSymbol(c[i]) == SUBTRACT)
        {
            //if no numbers have been added
            if (numbers==0)
            {
                //if target isn't negative, make target negative
                if ((*targetNegative)==false)
                {
                    (*targetNegative) = true;
                    (*targetBN).setNegative();
                }
                
                //if target is negative, no numbers have been added, and the target is the first number: 
				//there are two minus symbols, which means the intent is to 
				//subtract a negative number from previous
                else if (targetBN == &bn1)
                {
                    pType = SUBTRACT;
                    targetBN = &bn2;
                    numbers=0;
					commaNumbers=0;
					comma=false;
                    bn2.setNegative(); //sets 2nd number to negative
					negative2=true; //sets 2nd number to negative
                    targetNegative= &negative2;
                    done=false;
                    targetDec = &decimalCount2;
                    targetVec = &second;
                    decimal=false;
                }
                
                else 
				{
					RETURN_ERROR;
				}
            }
            
            //if numbers have been added, and the target is the first number, the problem type is subtraction
            else if (targetBN == &bn1)
            {
                if (comma==true && decimal==false && commaNumbers != 3)
                    RETURN_ERROR;
                
                pType = SUBTRACT;
                numbers=0;
				commaNumbers=0;
				comma=false;
                done=false;
                targetBN = &bn2;
				targetNegative= &negative2;
                targetDec = &decimalCount2;
                targetVec = &second;
                decimal=false;
            }
            
            //if numbers have been added, and the target is the second number, return error
            else 
			{
				RETURN_ERROR;
			}
        }
        
        //if it's a symbol other than minus
        else if (checkSymbol(c[i]) != ERROR && checkSymbol(c[i]) != SUBTRACT)
        {
            //if the type is already established, return error
            if (pType != ERROR)
			{
            	RETURN_ERROR;
			}
                
            //otherwise, set problem type based on symbol and reset figures
            else 
            {
                if (comma==true && decimal==false && commaNumbers != 3)
                    RETURN_ERROR;
                
                pType = checkSymbol(c[i]);
                targetBN = &bn2;
                numbers=0;
				commaNumbers=0;
				comma=false;
                done=false;
				targetNegative = &negative2;
                targetDec = &decimalCount2;
                targetVec = &second;
                decimal=false;
            }
        }
        
        //if it's a decimal point
        else if (c[i]=='.')
        {
            //if there's already been a decimal point, return error
            if (decimal==true)
			{
                RETURN_ERROR;
			}
                
            else decimal = true;
            
            if (comma==true && commaNumbers != 3)
                RETURN_ERROR;
        }
        
        //if it's an endline character
        else if (c[i] == '$')
        {
            if (comma==true && decimal==false && commaNumbers != 3)
                    RETURN_ERROR;
                    
			//if both numbers are empty
			if (first.size()==0 && second.size()==0)
			{
				if (pType==FACTORIAL)
				{
					bn1 = previous;
				}

				else RETURN_ERROR;
			}

			//if first number is empty, set bn1 to previous
			if (first.size()==0)
			{
				bn1 = previous;
			}

			//otherwise create bn1 from entered and print it as is
            else
            {   
				bn1 = numberFromVector(first, negative1, decimalCount1, user);
				printExact=true;
            }
            
            //if second number is empty
            if (second.size()==0)
            {               
                //if first number is negative and pType is undefined, subtract number from previous
                if (negative1==true && pType == ERROR)
                {
					bn1.setPositive();
                    temp = previous - bn1;

					cout << "Entered: "; 
					displayNumber(previous, user, false, false);
					cout << " - "; 
					displayNumber(bn1, user, true, false);

					RETURN_OK(temp);
					//return solution(temp, 0);
                }
                
                //if first number isn't negative and no problem type has been declared, return that number
                else if (pType == ERROR)
                {
					cout << "Entered: "; 
					displayNumber(bn1, user, true, false);
					RETURN_OK(bn1);
                    //return solution(bn1, 0);
                }
               
                else if (pType != FACTORIAL)
                {
                    RETURN_ERROR;
                }
            }
                
            //otherwise take ints from second vector and use to set bigNumber2
            else 
            {
                bn2 = numberFromVector(second, negative2, decimalCount2, user);
            }

			cout << "Entered: ";
			displayNumber(bn1, user, printExact, printStats);
			
			break;
        }
    }
    
    //use problem type to calculate solution, return with no errors if valid
    switch(pType)
    {
        case ERROR: RETURN_ERROR;
        
        case ADD: cout << " + "; bn2.printNumber();
            temp = bn1 + bn2;
			RETURN_OK(temp);
        
        case SUBTRACT: cout << " - "; bn2.printNumber();
			temp = bn1 - bn2;
			RETURN_OK(temp);
                
        case MULTIPLY: cout << " * "; bn2.printNumber();
			temp = bn1 * bn2;
			RETURN_OK(temp);
                
        case DIVIDE: cout << " / "; bn2.printNumber();
            if (bn2==0)
            {
                RETURN_ERROR;
            }
            temp = bn1 / bn2;
			RETURN_OK(temp);
                
        case FACTORIAL: 
			if (bn1<0 || bn1.getDecimalCount() > 0)
            {
				RETURN_ERROR;
            }
            
            else if (bn1==0)
            {
				cout << "!";
				bigNumber fact(1);
				fact.setBase(user.getBase());
				RETURN_OK(fact);
            }
            
            temp = bigNumber::factorial(bn1);
			cout << "!";
			RETURN_OK(temp);    
           
        case EXPONENT: cout << "^"; bn2.printNumber();
			temp = bigNumber::exponent(bn1, bn2);
			RETURN_OK(temp);
        
        case ITERATION: cout << "c"; bn2.printNumber();
			temp = bigNumber::iterations(bn1, bn2);
			RETURN_OK(temp);
        
        default: RETURN_ERROR;
    }

}
Example #21
0
void ChatView::appendMessage(QString message, RoomMessageTypeFlags messageType, QString sender, UserLevelFlags userLevel, QString UserPrivLevel, bool playerBold)
{
    bool atBottom = verticalScrollBar()->value() >= verticalScrollBar()->maximum();
    bool sameSender = (sender == lastSender) && !lastSender.isEmpty();
    QTextCursor cursor = prepareBlock(sameSender);
    lastSender = sender;
    
    // timestamp
    if (showTimestamps && (!sameSender || sender.toLower() == "servatrice") && !sender.isEmpty()) {
        QTextCharFormat timeFormat;
        timeFormat.setForeground(QColor(SERVER_MESSAGE_COLOR));
        if (sender.isEmpty())
            timeFormat.setFontWeight(QFont::Bold);
        cursor.setCharFormat(timeFormat);
        cursor.insertText(QDateTime::currentDateTime().toString("[hh:mm:ss] "));
    }

    // nickname
    if (sender.toLower() != "servatrice") {
        QTextCharFormat senderFormat;
        if (tabSupervisor && tabSupervisor->getUserInfo() &&
            (sender == QString::fromStdString(tabSupervisor->getUserInfo()->name()))) {
            senderFormat.setForeground(QBrush(getCustomMentionColor()));
            senderFormat.setFontWeight(QFont::Bold);
        } else {
            senderFormat.setForeground(QBrush(OTHER_USER_COLOR));
            if (playerBold)
                senderFormat.setFontWeight(QFont::Bold);
        }
        senderFormat.setAnchor(true);
        senderFormat.setAnchorHref("user://" + QString::number(userLevel) + "_" + sender);
        if (sameSender) {
            cursor.insertText("    ");
        } else {
            if (!sender.isEmpty() && tabSupervisor->getUserListsTab()) {
                const int pixelSize = QFontInfo(cursor.charFormat().font()).pixelSize();
                QMap<QString, UserListTWI *> buddyList = tabSupervisor->getUserListsTab()->getBuddyList()->getUsers();
                cursor.insertImage(UserLevelPixmapGenerator::generatePixmap(pixelSize, userLevel, buddyList.contains(sender), UserPrivLevel).toImage());
                cursor.insertText(" ");
            }
            cursor.setCharFormat(senderFormat);
            if (!sender.isEmpty())
                sender.append(": ");
            cursor.insertText(sender);
        }
    }

    // use different color for server messages 
    defaultFormat = QTextCharFormat();
    if (sender.isEmpty()) {
        switch (messageType) {
            case Event_RoomSay::Welcome:
                defaultFormat.setForeground(Qt::darkGreen);
                defaultFormat.setFontWeight(QFont::Bold);
                break;
            case Event_RoomSay::ChatHistory:
                defaultFormat.setForeground(Qt::gray);
                defaultFormat.setFontWeight(QFont::Light);
                defaultFormat.setFontItalic(true);
                break;
            default:
                defaultFormat.setForeground(Qt::darkGreen);
                defaultFormat.setFontWeight(QFont::Bold);
        }
    } else if (sender.toLower() == "servatrice") {
        defaultFormat.setForeground(Qt::darkGreen);
        defaultFormat.setFontWeight(QFont::Bold);
    }
    cursor.setCharFormat(defaultFormat);

    bool mentionEnabled = settingsCache->getChatMention();
    highlightedWords = settingsCache->getHighlightWords().split(' ', QString::SkipEmptyParts);

    // parse the message
    while (message.size())
    {
        QChar c = message.at(0);    
        switch(c.toLatin1())
        {
            case '[':
                checkTag(cursor, message);
                break;
            case '@':
                if(mentionEnabled) {
                    checkMention(cursor, message, sender, userLevel);
                } else {
                    cursor.insertText(c, defaultFormat);
                    message = message.mid(1);
                }
                break;
            case ' ':
                cursor.insertText(c, defaultFormat);
                message = message.mid(1);
                break;
            default:
                if(c.isLetterOrNumber()) {
                    checkWord(cursor, message);
                } else {
                    cursor.insertText(c, defaultFormat);
                    message = message.mid(1);
                }
                break;
        }
    }

    if (atBottom)
        verticalScrollBar()->setValue(verticalScrollBar()->maximum());
}
Example #22
0
void ChatView::checkMention(QTextCursor &cursor, QString &message, QString &sender, UserLevelFlags userLevel)
{
    const QRegExp notALetterOrNumber = QRegExp("[^a-zA-Z0-9]");

    int firstSpace = message.indexOf(' ');
    QString fullMentionUpToSpaceOrEnd = (firstSpace == -1) ? message.mid(1) : message.mid(1, firstSpace - 1);
    QString mentionIntact = fullMentionUpToSpaceOrEnd;

    while (fullMentionUpToSpaceOrEnd.size())
    {
        const ServerInfo_User *onlineUser = userlistProxy->getOnlineUser(fullMentionUpToSpaceOrEnd);
        if (onlineUser) // Is there a user online named this?
        {
            if (userName.toLower() == fullMentionUpToSpaceOrEnd.toLower()) // Is this user you?
            {
                // You have received a valid mention!!
                soundEngine->playSound("chat_mention");
                mentionFormat.setBackground(QBrush(getCustomMentionColor()));
                mentionFormat.setForeground(settingsCache->getChatMentionForeground() ? QBrush(Qt::white) : QBrush(Qt::black));
                cursor.insertText(mention, mentionFormat);
                message = message.mid(mention.size());
                showSystemPopup(sender);
            } else {
                QString correctUserName = QString::fromStdString(onlineUser->name());
                mentionFormatOtherUser.setAnchorHref("user://" + QString::number(onlineUser->user_level()) + "_" + correctUserName);
                cursor.insertText("@" + correctUserName, mentionFormatOtherUser);

                message = message.mid(correctUserName.size() + 1);
            }

            cursor.setCharFormat(defaultFormat);
            return;
        }

        if (isModeratorSendingGlobal(userLevel, fullMentionUpToSpaceOrEnd)) {
            // Moderator Sending Global Message
            soundEngine->playSound("all_mention");
            mentionFormat.setBackground(QBrush(getCustomMentionColor()));
            mentionFormat.setForeground(settingsCache->getChatMentionForeground() ? QBrush(Qt::white) : QBrush(Qt::black));
            cursor.insertText("@" + fullMentionUpToSpaceOrEnd, mentionFormat);
            message = message.mid(fullMentionUpToSpaceOrEnd.size() + 1);
            showSystemPopup(sender);

            cursor.setCharFormat(defaultFormat);
            return;
        }

        if (fullMentionUpToSpaceOrEnd.right(1).indexOf(notALetterOrNumber) == -1 || fullMentionUpToSpaceOrEnd.size() < 2)
        {
            cursor.insertText("@" + mentionIntact, defaultFormat);
            message = message.mid(mentionIntact.size() + 1);
            cursor.setCharFormat(defaultFormat);
            return;
        }

        fullMentionUpToSpaceOrEnd.chop(1);
    }

    // no valid mention found
    checkWord(cursor, message);
}
Example #23
0
int main(){
  FILE *fin,*fout;
  int i_line,startSentence; // use i_line to index line when read text
  int i,j;
  char c;
  char str[80];

  initTable();
  // read stop words from stopw.txt file
  if((fin = fopen("stopw.txt","r")) == NULL){
    printf("Cant read file stopw.txt\n");exit(1);
  }
  while(fscanf(fin,"%s",str) == 1){
    char* buff = (char*)malloc((strlen(str)+1)*sizeof(char));
    strcpy(buff,str);
    toLower(buff);
    stop.words[(stop.size)++] = buff;
  }
  fclose(fin);
  qsort(stop.words,stop.size,sizeof(char*),compare_str);
      
  // read text from vanban.txt file
  char name[100];
  printf("Nhap ten file:");
  scanf("%s",name);
  if((fin = fopen(name,"r")) == NULL){
    printf("Cant read file %s\n",name);exit(1);
  }

  i=0;
  i_line = 1;
  startSentence = 1;
  while(!feof(fin)){
    if ((c=fgetc(fin)) != EOF){
      /* if a character is an alphabet or a '-' character (but not at start of word), add it to str string
       */
      if(isAlphabet(c) || (c == '-' && i != 0)){
	str[i++] = c;
      } else {
	str[i] = '\0';
	if(checkWord(str,startSentence)){
	  //	  printf(">%s\n",str);
	  char* buff = (char*)malloc(sizeof(char)*(strlen(str)+1));
	  strcpy(buff,str);
	  addWord(buff,i_line);
	}

	if (c == '\r' || c == '\n'){
	  i_line++;
	}
	startSentence = isEndSentenceCharacter(c);
	i = 0;
      }
    }
  }
  fclose(fin);

  for(i = 0; i < table.size; i++){
    Index index = table.table[i];
    printf("%s %d %s\n",index.word,index.numberOfWords,index.line);
  }

  return 0;
}
Example #24
0
int main(int argc, char* argv[]) {
    struct stat filestatus;
    stat(argv[1], &filestatus);

    buffer = new char[filestatus.st_size + 1];

    std::ifstream wordFile(argv[1]);
    if (wordFile.is_open()) {
        char word[MAX_WORD_LENGTH];

        while (wordFile.good()) {
            wordFile.getline(word, MAX_WORD_LENGTH);
            if (wordFile.gcount() != 0) {
                trie.add(word);
            }
        }
        wordFile.close();
    }

    char rootWord[] = "hello";
    trie.add(rootWord);
    checkWord(&trie, rootWord, strlen(rootWord));

    Trie* node;
    char slate[MAX_WORD_LENGTH + 1];
    while (!queue.empty()) {
        char* word = queue.front();
        queue.pop();

        int len = strlen(word);

        // Edits
        char* chars = word;
        node = &trie;
        int i = 0;
        while (word[i] != '\0') {
            char original = chars[i];
            for (char c = 'a'; c < original; ++c) {
                if (node->children[c - 'a'] != NULL) {
                    chars[i] = c;
                    checkWord(node, chars, len, i);
                }

            }
            // Skip original
            for (char c = original + 1; c <= 'z'; ++c) {
                if (node->children[c - 'a'] != NULL) {
                    chars[i] = c;
                    checkWord(node, chars, len, i);
                }
            }
            chars[i] = original;

            node = node->children[original - 'a'];
            ++i;
        }

        // Inserts
        chars = slate;
        chars[len + 1] = '\0';
        node = &trie;
        int idx = -2;
        for (i = 0; i <= len; ++i) {
            if (++idx >= 0)
                chars[idx] = word[idx];
            for (int j = i + 1; j <= len; ++j)
                chars[j] = word[j - 1];
            for (char c = 'a'; c <= 'z'; ++c) {
                if (node->children[c - 'a'] != NULL) {
                    chars[i] = c;
                    checkWord(node, chars, len + 1, i);
                }
            }

            node = node->children[word[i] - 'a'];
        }

        // Deletes
        chars = slate;
        chars[len - 1] = '\0';
        idx = -2;
        for (i = 0; i < len; ++i) {
            if (++idx >= 0)
                chars[idx] = word[idx];
            for (int j = i + 1; j < len; ++j)
                chars[j - 1] = word[j];

            checkWord(&trie, chars, len - 1);
        }
    }

    // Don't include initial word in count
    std::cout << numVisited - 1 << std::endl;
    return 0;
}