Example #1
0
void SumDigester::addTerm(RicoPtr A) {
  if(A->isNumber()) {
    m_constant = m_constant + A;
    return;
  }

  if(A->isAdd()) {
    const vRicoPtr& P = ((const RicoFunction&)(*A)).get_params();
    addTerm(P);
    return;
  }

  if(A->isMultiply()) {
    RicoPtr C = Rico::One;
    const vRicoPtr& P = ((const RicoFunction&)(*A)).get_params();
    vRicoPtr        Q;
    for(vRicoPtr::const_iterator it = P.begin(); it != P.end(); it++) {
      if((*it)->isNumber()) C = C * (*it);
      else Q.push_back(*it);
    }
    addTerm(C, Rico::Multiply(Q));
    return;
  }

  addTerm(Rico::One, A);
}
void PirateDictionary::readDictionaryData()
{
    cerr << "reading data" << endl;

    ifstream in; // an input stream
    in.open(m_pirateTerms);

    // check to see if the open failed
    if (in.fail()) {
        cout << "Couldn't open the file " << m_pirateTerms << " for reading." << endl;

    } else
    {
        while (!in.eof())
        {
            string englishTerm;
            string pirateTerm;
            getline(in, englishTerm, '#');

            getline(in, pirateTerm);
            addTerm(englishTerm, pirateTerm);
        }
    }
    in.close();
}
/*
 * func : convert a text index line to binary index and write to files
 *
 * args : line, a line include a term's text index
 * args : lineLen, text index line len
 *
 * ret  : <=0, error
 *      : >0, success. the ret is the doc_id count of the term
 */
int IndexFieldBuilder::addTerm(const char * line, int lineLen)
{
    if(_pLineParse->init(line, lineLen) < 0) {
        return KS_EFAILED;
    }
    _pLineParse = _pParseInstance;
    return addTerm();
}
Vocabulary::Vocabulary( const Vocabulary& voc ) 
    : Base(), id( voc.id ), markedForStudy( voc.markedForStudy ), markedForDeletion( voc.markedForDeletion ), 
        title( voc.title ), description( voc.description ), author( voc.author ), 
            creationDate( voc.creationDate ), modificationDate( voc.modificationDate ), dirty( voc.dirty ), parent( voc.parent ) {
    for( TermMap::ConstIterator it = voc.terms.begin(); it != voc.terms.end(); it++ ) {
        const Term& term = *it;
        addTerm( term );
    }
}
    void LinguisticVariable::createTerms(int number_of_terms,
            LinguisticTerm::eMembershipFunction mf, flScalar min, flScalar max,
            const std::vector<std::string>& labels) {
        std::vector<std::string> final_labels;
        for (int i = 0; i < number_of_terms; ++i) {
            if ((int) labels.size() <= i) {
                final_labels.push_back(name() + "-" + StrOp::IntToString(i + 1));
            } else {
                final_labels.push_back(labels[i]);
            }
        }
        fl::flScalar intersection = sqrt(-1.0); //Proportion of intersection between terms
        if (mf == LinguisticTerm::MF_TRAPEZOIDAL) {
            intersection = 4.0 / 5.0;
        } else {
            intersection = 0.5;
        }
        //TODO: What is the intersection in other terms?

        fl::flScalar term_range = (max - min) / (number_of_terms - number_of_terms / 2);
        fl::flScalar current_step = min + (1 - intersection) * term_range;
        for (int i = 0; i < number_of_terms; ++i) {
            fl::LinguisticTerm* term = NULL;
            switch (mf) {
                case LinguisticTerm::MF_TRIANGULAR:
                    term = new fl::TriangularTerm(final_labels.at(i), 
                            current_step - (1 - intersection) * term_range,
                            current_step + intersection * term_range);
                    break;
                case LinguisticTerm::MF_SHOULDER:
                    if (i == 0 || i == number_of_terms - 1) {
                        term = new fl::ShoulderTerm(final_labels[i],
                                current_step - (1 - intersection) * term_range,
                                current_step + intersection * term_range, i == 0);
                    } else {
                        term = new fl::TriangularTerm(final_labels.at(i),
                                current_step - (1 - intersection) * term_range, 
                                current_step + intersection * term_range);
                    }
                    break;
                case LinguisticTerm::MF_TRAPEZOIDAL:

                    term = new fl::TrapezoidalTerm(final_labels.at(i),
                            current_step - (1 - intersection) * term_range,
                            current_step + intersection * term_range);
//                    term = new fl::TriangularTerm(final_labels.at(i), current_step
//                            - (1 - intersection) * term_range, current_step + intersection
//                            * term_range);
                    break;
                default:
                    throw fl::InvalidArgumentException(FL_AT, "Invalid option for membership function");
            }
            current_step += intersection * term_range;
            addTerm(term);
        }
    }
/* takes a c-string with a polynomial in the given format "exp coeff exp coeff etc..." */
Polynomial::Polynomial( char * poly ) {
  /* have to assume that the string is null terminated */
  char curr[SLEN];
  int index = 0;
  curr[0] = '\0';
  double coeff = 0.0f;
  int exp = 0;

  // true => coeff, false => exp
  bool mode = true;

  for( int i = 0; (i < SLEN) && (poly[i] != '\0'); ++i )
    {
      if( (poly[i] == ' ') && mode )
	{
	  curr[index] = '\0';
	  coeff = atof(curr);
	  mode = false;
	  index = 0;
	}      
      else if( (poly[i] == ' ') && !mode )
	{
	  curr[index] = '\0';
	  exp = atoi(curr);
	  mode = true;
	  addTerm( coeff, exp );
	  index = 0;
	}
      else
	{
	  curr[index] = poly[i];
	  index++;
	}
    }

  
  // the last set of terms will have been collected, but not trigger poly[i] == ' '
  curr[index] = '\0';
  exp = atoi(curr);
  addTerm( coeff, exp );
}
int IndexFieldBuilder::addTerm(const uint64_t termSign, const uint32_t* docList, uint32_t docNum)
{
    if(unlikely(_maxOccNum > 0)) {
        return KS_EFAILED;
    }
    IndexNoneOccParseNew parse;
    if(parse.init(termSign, docList, docNum) < 0) {
        return KS_EFAILED;
    }
    _pLineParse = &parse;
    return addTerm();
}
polynomial& polynomial::operator=(polynomial rhs)
{
    node* p=rhs.n;
    n = 0; //reset the polynomial linked list

    while(p!=0)
    {
        addTerm(p->getCoefficient(),p->getExponent()); //iteratively add the nodes from the rhs polynomial
        p=p->next;
    }

    return *this;
}
Example #9
0
    PlanStage::StageState TextStage::readFromSubScanners(WorkingSetID* out) {
        // This should be checked before we get here.
        invariant(_currentIndexScanner < _scanners.size());

        // Read the next result from our current scanner.
        WorkingSetID id = WorkingSet::INVALID_ID;
        PlanStage::StageState childState = _scanners.vector()[_currentIndexScanner]->work(&id);

        if (PlanStage::ADVANCED == childState) {
            WorkingSetMember* wsm = _ws->get(id);
            invariant(1 == wsm->keyData.size());
            invariant(wsm->hasLoc());
            IndexKeyDatum& keyDatum = wsm->keyData.back();
            addTerm(keyDatum.keyData, wsm->loc);
            _ws->free(id);
            return PlanStage::NEED_TIME;
        }
        else if (PlanStage::IS_EOF == childState) {
            // Done with this scan.
            ++_currentIndexScanner;

            if (_currentIndexScanner < _scanners.size()) {
                // We have another scan to read from.
                return PlanStage::NEED_TIME;
            }

            // If we're here we are done reading results.  Move to the next state.
            _scoreIterator = _scores.begin();
            _internalState = RETURNING_RESULTS;

            // Don't need to keep these around.
            _scanners.clear();
            return PlanStage::NEED_TIME;
        }
        else {
            if (PlanStage::FAILURE == childState) {
                // Propagate failure from below.
                *out = id;
                // If a stage fails, it may create a status WSM to indicate why it
                // failed, in which case 'id' is valid.  If ID is invalid, we
                // create our own error message.
                if (WorkingSet::INVALID_ID == id) {
                    mongoutils::str::stream ss;
                    ss << "text stage failed to read in results from child";
                    Status status(ErrorCodes::InternalError, ss);
                    *out = WorkingSetCommon::allocateStatusMember( _ws, status);
                }
            }
            return childState;
        }
    }
Example #10
0
int IndexFieldBuilder::addTerm(const uint64_t termSign, const DocListUnit* docList, uint32_t docNum)
{
    if(unlikely(_maxOccNum < 0)) {
        return KS_EFAILED;
    }
    if(_maxOccNum == 1) {
        IndexOneOccParseNew parse;
        if(parse.init(termSign, docList, docNum) < 0) {
            return KS_EFAILED;
        }
        _pLineParse = &parse;
        return addTerm();
    }

    // 多occ情况下可能内存不足
    if((docNum + 1) * sizeof(idx2_nzip_unit_t) > _pIndexBuilder->raw_buf_size) {
        _pIndexBuilder->raw_buf_size = (docNum + 1) * sizeof(idx2_nzip_unit_t);
        free(_pIndexBuilder->raw_buf);
        _pIndexBuilder->raw_buf = (char*)malloc(_pIndexBuilder->raw_buf_size);

        int size = ((docNum + P4D_BLOCK_SIZE) / P4D_BLOCK_SIZE + 1) * sizeof(_idx2_p4d_skip_unit_t);
        size += (docNum + 1) * sizeof(int32_t) + sizeof(idx2_zip_header_t);
        if(size > _pIndexBuilder->final_buf_size) {
            free(_pIndexBuilder->final_buf);
            _pIndexBuilder->final_buf_size = size;
            _pIndexBuilder->final_buf = (char*)malloc(_pIndexBuilder->final_buf_size);
        }
    }

    IndexMultiOccParseNew parse;
    if(parse.init(termSign, docList, docNum) < 0) {
        return KS_EFAILED;
    }
    _pLineParse = &parse;
    return addTerm();
}
Index* InMemoryIndexBuilder::createIndex()
{
	if (iDictionary == nullptr) {
		iDictionary = new HashTableDictionary();
	}
	if (iCompressor == nullptr) {
		iCompressor = new NoCompressor();
	}
	DocumentTable * documentTable = new DocumentTable();

	if (outputFilePath.compare("")==0) {
		outputFilePath = DEFAULT_OUTPUT_FILE;
	}
	
	
	IDocumentProvider* documentProvider = new DocumentProvider(repositoryPath);

	Document* document;
	while ((document = documentProvider->getNextDocument()) != nullptr)
	{
		ITokenizer* tokenizer;
		switch (iTokenizerType) {
		case SIMPLE_TOKENIZER:
			tokenizer = new Tokenizer(document);
			break;
		case STRTK_TOKENIZER :
			tokenizer = new StrTkTokenizer(document);
			break;
		default:
			throw runtime_error("No Tokenizer with such ID");
			break;
		}
		string token;
		while ((token = tokenizer->getNextToken()).compare("") != 0)
		{
			addTerm(token, documentTable);
		}
		documentTable->addDocument(document->getDocumentMetaData());
		delete document;
		delete tokenizer;
	}
	delete documentProvider;
	finalize(documentTable);
	Index *index = new Index(iDictionary, documentTable, iCompressor, outputFilePath);
	return index;
}
bool Vocabulary::load( const QString& filename ) {
    QFile dataFile( filename );
    if( !dataFile.open( QIODevice::ReadOnly ) )
        return( false );

    QByteArray compressedData( dataFile.readAll() );
    QByteArray data( qUncompress( compressedData ) );

    QDataStream in( data );

    qint32 tempMagicNumber;
    qint16 tempVersion;
    Vocabulary tempVocab;

    in >> tempMagicNumber >> tempVersion;

    if( tempMagicNumber != Vocabulary::magicNumber ) {
        cerr << "Wrong magic number: Incompatible vocabulary data file." << endl;
        return( false );
    }
    if( tempVersion > 0x0010 ) {
        cerr << "Vocabulary data file is from a more recent version.  Upgrade toMOTko." << endl;
        return( false );
    }

    in.setVersion( QDataStream::Qt_2_1 );
    in >> tempVocab;

    dataFile.close();

    id = tempVocab.getId();
    markedForStudy = tempVocab.isMarkedForStudy();
    title = tempVocab.getTitle();
    description = tempVocab.getDescription();
    author = tempVocab.getAuthor();
    creationDate = tempVocab.getCreationDate();
    modificationDate = tempVocab.getModificationDate();
    dirty = tempVocab.isDirty();
    for( TermMap::ConstIterator it = tempVocab.begin(); it != tempVocab.end(); it++ ) {
        const Term& term = *it;
        addTerm( term );
    }
    return( true );
}
Index finalIndex(Index * i) {
	Index finalI ;
	initIndex(&finalI) ; 
		while ((*i) -> ptr_next != NULL) 
		{		
			if ((*i) -> t1.occur < TMAX) 
			{	Cell * ptr_stock = *i ; 
			 	*i = (*i)->ptr_next ;
			 	free(ptr_stock) ; 
			}
		
	 		else 
			{ 	Cell * ptr_stock = *i ;
				addTerm(&finalI, (*i)->t1) ; 
				(*i) = (*i) -> ptr_next ; 
				free(ptr_stock) ; 
			}
		}
	printf("End of final Indexation\n") ; 
	return finalI ;
} 
Example #14
0
LanguageModel::LanguageModel(Index *index, offset start, offset end, bool stemmed) {
	char line[Query::MAX_RESPONSELINE_LENGTH + 4];
	initialize();
	this->corpusSize = (end - start + 1);
	this->documentCount = 1;
	this->stemmed = stemmed;

	char queryBody[64];
	sprintf(queryBody, OFFSET_FORMAT " " OFFSET_FORMAT, start, end);
	const char *modifiers[2] = { "filtered", NULL };
	GetQuery *query = new GetQuery(index, "get", modifiers, queryBody, Index::GOD, -1);
	if (query->parse()) {
		line[sizeof(line) - 1] = 0;
		while (query->getNextLine(line)) {
			assert(line[sizeof(line) - 1] == 0);
			StringTokenizer *tok = new StringTokenizer(line, " ");
			while (tok->hasNext()) {
				char *t = tok->getNext();
				if ((strchr(t, '<') == NULL) && (strchr(t, '>') == NULL)) {
					if (getTermID(t) < 0)
						addTerm(t, 1, 1);
					else
						updateTerm(t, 1, 0);
				}
			}
			delete tok;
		}
	}
	else {
		log(LOG_ERROR, LOG_ID, "Parsing failed in LanguageModel(Index*, offset, offset, bool)");
		fprintf(stderr, "%lld %lld\n", static_cast<long long>(start), static_cast<long long>(end));
	}
	delete query;

	this->corpusSize = 0;
	for (int i = 0; i < termSlotsUsed; i++)
		this->corpusSize += terms[i].termFrequency;
} //end of LanguageModel(Index*, offset, offset, bool)
void readWordbyWord(const char * path , Index * i) {
	FILE * text = fopen(path,"r") ;
	char * word ; 
	word = malloc(sizeof(char)*100) ;  
	if (text != NULL) 
	
	{	
		while(fscanf(text,"%s",word) != EOF)
		{
	
				if ((!isInBeacons(word)) && (isWordRelevant(word)))
				{	
	
					 if (doesTermExist(*i ,word) == FALSE) 	
					 
					{	
										
						Term * t = (Term*) malloc(sizeof(Term)) ;
						createTerm(t , word) ;	
						addTerm(i , *t) ;
					}

				  	else
					{	
						Cell * cTmp = *i ; 
						while ( strcmp(cTmp->t1.word , word) != 0) 
						{ cTmp = (cTmp)->ptr_next ; }		
						(cTmp)->t1.occur ++ ;   
					} 
				
				}
			
		}  
		fclose(text) ; 
	}
	free(word) ;    
}
Example #16
0
int main(){
//int indexer() {

	FILE *files,*fp,*conf;
	char temp[MAXIMUM],tempFileName[MAXIMUM],filesName[MAXIMUM],textFileName[MAXIMUM];
	int i,docId = 1;
	int fileType;
	int ret;
	int totalErrors = 0;

	initializeStopWordsArray();
	initializeTrie();

/*	conf = fopen("CONFIG","r");
	readLine(conf,filesName);
	fclose(conf);*/

	files = fopen("INDEX/files.txt","r");

	if(files == NULL){
		goto createStatusFile;
	}
	
	while(readLine(files,tempFileName) != FAIL) {
		printf("%d \n",docId);
		printf("%s\n",tempFileName);

		fileType = checkFileExtension(tempFileName);

		strcpy(textFileName,"temp.txt");
		if(fileType == PDF){
			ret = convertPdfToTxt(tempFileName,textFileName);
			if(ret != SUCCESS){
				++totalErrors;
				++docId;
				continue;
			}
		}
		else if(fileType == DOC){
			ret = convertDocToTxt(tempFileName,textFileName);
			if(ret != SUCCESS){
				++totalErrors;
				++docId;
				continue;
			}
		}
		else if(fileType == ODT){
			ret = convertOdtToTxt(tempFileName,textFileName);
			if(ret != SUCCESS){
				++totalErrors;
				++docId;
				continue;
			}
		}else if(fileType == TXT){
			strcpy(textFileName,tempFileName);
		}else if(fileType == 0){
			++totalErrors;
			++docId;
			continue;
		}

		fp = fopen(textFileName,"r");

		if(fp == NULL){
				++totalErrors;
			++docId;
			continue;
		}

		// 	Read each filename from the file 'files.txt'
		//	For each filename, read each word and add to index trie.

	
		while(readWord(fp,temp) != FAIL) {
			
			convertToLowerCase(temp);
			removeSpecialSymbols(temp);

//			printf("%s ",temp);

			if(temp[0] == '\0' || temp[0] == '\t' || temp[0] == ' ' || temp[0] == '\n')
				continue;

			if(checkForStopWords(temp) != SUCCESS) {
				int i = 0;

				// Presently on the words containing letters are allowed 
				while(temp[i] != '\0') {
					if(temp[i] < 97 || temp[i] > 122)
						break;
					++i;
				}
				if(temp[i] == '\0') {
					fileLen[docId]++;
//					printf("%d %s\n",docId,temp);
					addTerm(temp,docId);
				}

				//if(temp[0] >= 97 && temp[0]<=122) {
				//	addTerm(temp,docId);
				//}
				//printf("%s\n",temp);
			}
		}

		++docId;

		fclose(fp);
		if(fileType != TXT){
			system("rm temp.txt");
			system("touch temp.txt");
		}
		printf("...Done\n");
	}


	//printf("\nTrie Traversal\n");
	//traverseTerms();
	numOfDocs = docId - 1;

	printf("Number of docs : %d\n",numOfDocs);
	printf("Number of Errors : %d\n",totalErrors);

//	traverseTerms();
	createIndexFile();
	
	createStatusFile:
	system("echo \"Index Status\n==================\nIndex created on :\n\"  > INDEX/STATUS.txt");
	system("date >> INDEX/STATUS.txt");
	system("echo \"Directory indexed : \"#// >> INDEX/STATUS.txt");
	sprintf(temp,"echo \"No of Documents indexed : %d\" >> INDEX/STATUS.txt",numOfDocs);
	system(temp);

	return 0;
}
Example #17
0
void SumDigester::addTerm(const vRicoPtr& V) {
  for(vRicoPtr::const_iterator it = V.begin(); it != V.end(); it++) 
    addTerm(*it);
}
/* just reverse the coefficient and add it */
void Polynomial::subTerm( double coeff, int exp ) {
  addTerm( -1 * coeff, exp );
}
Example #19
0
    PlanStage::StageState TextStage::readFromSubScanners(WorkingSetID* out) {
        // This should be checked before we get here.
        invariant(_currentIndexScanner < _curScanner->size());

        // Read the next result from our current scanner.
        WorkingSetID id = WorkingSet::INVALID_ID;
        PlanStage::StageState childState = _curScanner->vector()[_currentIndexScanner]->work(&id);

        if (PlanStage::ADVANCED == childState) {
            WorkingSetMember* wsm = _ws->get(id);
            invariant(1 == wsm->keyData.size());
            invariant(wsm->hasLoc());
            IndexKeyDatum& keyDatum = wsm->keyData.back();
            addTerm(keyDatum.keyData, wsm->loc, _curScoreMap);
            _ws->free(id);
            return PlanStage::NEED_TIME;
        }
        else if (PlanStage::IS_EOF == childState) {
            // Done with this scan.
            ++_currentIndexScanner;

            if (_currentIndexScanner < _curScanner->size()) {
                // We have another scan to read from.
                return PlanStage::NEED_TIME;
            }

            // Don't need to keep these around.
            _curScanner->clear();

            // If we have negated terms, we need to scan them unless there
            // are so few documents that the potential I/O overhead of
            // an additional scan overwhelms the cost of parsing
            // all of the documents.
            if ( !_startedNegativeScans && _params.query.getNegatedTerms().size() > 0
                 && _curScoreMap->size() >= NEGATION_SCAN_THRESHOLD) {
                _startedNegativeScans = true;
                _curScanner = &_negativeScanners;
                _curScoreMap = &_negativeScores;
                _currentIndexScanner = 0;

                // Return to INIT_SCANS to set up negative scans.
                _internalState = INIT_SCANS;
                return PlanStage::NEED_TIME;
            }

            // If we're here we are done reading results.  Move to the next state.
            if (_startedNegativeScans) {
                _internalState = FILTER_NEGATIVES;
            }
            else {
                _scoreIterator = _scores.begin();
                _internalState = RETURNING_RESULTS;
            }

            return PlanStage::NEED_TIME;
        }
        else {
            if (PlanStage::FAILURE == childState) {
                // Propagate failure from below.
                *out = id;
                // If a stage fails, it may create a status WSM to indicate why it
                // failed, in which case 'id' is valid.  If ID is invalid, we
                // create our own error message.
                if (WorkingSet::INVALID_ID == id) {
                    mongoutils::str::stream ss;
                    ss << "text stage failed to read in results from child";
                    Status status(ErrorCodes::InternalError, ss);
                    *out = WorkingSetCommon::allocateStatusMember( _ws, status);
                }
            }
            return childState;
        }
    }
/* adds a Term to the Polynomial */
void Polynomial::addTerm( const Term& aTerm ) {
  addTerm( aTerm.coeff, aTerm.exp );
}
Example #21
0
	void copy_from(const Polynomial &P) {
		m_terms.clear();
		for (int j=0; j<P.termCount(); j++) {
			addTerm(P.term(j));
		}
	}
Example #22
0
void Polynomial::addTerm(fbreal coeff,int e1,int e2,int e3,int e4,int e5,int e6) {
	PolynomialTerm T;
	T.coefficient=coeff;
	T.exponents << e1 << e2 << e3 << e4 << e5 << e6;
	addTerm(T);
}
Example #23
0
int main( int argc, char *argv[]) {
 
   // create array of structs and initialize 
   POLYNOMIAL polynomials[MAX_POLYNOMIALS];
   for (int i = 0; i < MAX_POLYNOMIALS; i++) {
      for (int j = 0; j < MAX_TERMS; j++) {
	 polynomials[i].terms[j].coefficient = 0;
	 polynomials[i].terms[j].exponent = 0;
      }
      polynomials[i].size = 0;
   }

   // open file w/ error checking, etc.
   FILE *cmdFile; 
   if (argc != 2) {
      printf("Usage: %s filename\n", argv[0]);
      exit(-1);
   } else {
      cmdFile = fopen(argv[1], "r");
   }
   if (cmdFile == NULL) {
      printf("Error opening the file.\n");
      exit (-1);
   }
   
   // read through each line in the file 
   char line[MAX_COMMAND_LENGTH];
   while ( fgets(line, MAX_COMMAND_LENGTH, cmdFile) != NULL) {
      
      // Check which command is being used
      if (line[0] == 'A' && line[3] == 'T') {

	 // strtok() and atoi() are usually very bad idea, but input is guaranteed to be well formed
	 char *command =  strtok(line," ");
	 char *index = strtok(NULL," ");
	 char *coeff = strtok(NULL," ");
	 char *exp = strtok(NULL," \n");
	 // convert last symbol on line to int to strip any whitespace from input file
	 int exponent = atoi(exp);
	 printf("CMD: %s, Polynominal #: %s, Coefficient: %s, Exponent: %d\n", command, index, coeff, exponent);
	 int integerIndex = atoi(index);
	 // Adding term and printing the new polynomial 
	 polynomials[integerIndex] = addTerm(polynomials[integerIndex], atoi(coeff), atoi(exp) );
	 printPolynomial(integerIndex, polynomials[integerIndex]);

      } else if (line[0] == 'M') {

	 // Scalar multiplication
	 char *command =  strtok(line," ");
	 char *index = strtok(NULL," ");
	 char *value = strtok(NULL," ");
	 int scalar = atoi(value);
	 printf("CMD: %s, Polynominal #: %s, Scalar value: %d\n", command, index, scalar);
	 int integerIndex = atoi(index);
	 polynomials[integerIndex] = multiply(scalar, polynomials[integerIndex]);
	 printPolynomial(integerIndex, polynomials[integerIndex]);

      } else if (line[0] == 'A') {
	 
	 // Summation
	 char *command =  strtok(line," ");
	 char *sumIndex = strtok(NULL," ");
	 char *firstIndex = strtok(NULL, " ");
	 char *secondIndex = strtok(NULL," ");
	 int second = atoi(secondIndex);
	 printf("CMD: %s, Sum goes into index #: %s, First operand: %s, Second operand: %d\n", command, sumIndex, firstIndex, second);
	 int sum = atoi(sumIndex);
	 int first = atoi(firstIndex);
	 polynomials[sum] = add(polynomials[first], polynomials[second]);
	 printPolynomial(sum, polynomials[sum]);

      } else if (line[0] == 'S') {

	 // Subtraction
	 char *command =  strtok(line," ");
	 char *diffIndex = strtok(NULL," ");
	 char *firstIndex = strtok(NULL," ");
	 char *secondIndex = strtok(NULL," ");
	 int second = atoi(secondIndex);
	 printf("CMD: %s, Dif goes into index #: %s, First operand: %s, Second operand: %d\n", command, diffIndex, firstIndex, second);
	 int diff = atoi(diffIndex);
	 int first = atoi(firstIndex);
	 polynomials[diff] = subtract(polynomials[first], polynomials[second]);
	 printPolynomial(diff, polynomials[diff]);
      }
   }

   fclose(cmdFile);
   return 0;
}
void CellMLAnnotationViewMetadataEditDetailsWidget::updateGui(const Items &pItems,
                                                              const QString &pErrorMsg,
                                                              const bool &pLookupTerm,
                                                              const int &pItemsVerticalScrollBarPosition,
                                                              const bool &pRetranslate)
{
    // Note: we are using certain layouts to dislay the contents of our view,
    //       but this unfortunately results in some very bad flickering on OS X.
    //       This can, however, be addressed using a stacked widget, so...

    // Prevent ourselves from being updated (to avoid any flickering)

    setUpdatesEnabled(false);

    // Create a widget which will contain our GUI

    QWidget *newMainWidget = new QWidget(this);
    QVBoxLayout *newMainLayout = new QVBoxLayout(newMainWidget);

    newMainLayout->setMargin(0);

    newMainWidget->setLayout(newMainLayout);

    // Create a form widget which will contain our qualifier and term fields

    QWidget *newFormWidget = new QWidget(newMainWidget);
    QFormLayout *newFormLayout = new QFormLayout(newFormWidget);

    newFormWidget->setLayout(newFormLayout);

    // Add our qualifier field

    // Create a widget which will contain both our qualifier value widget and a
    // button to look up the qualifier

    QWidget *qualifierWidget = new QWidget(newFormWidget);

    QHBoxLayout *qualifierWidgetLayout = new QHBoxLayout(qualifierWidget);

    qualifierWidgetLayout->setMargin(0);

    qualifierWidget->setLayout(qualifierWidgetLayout);

    // Create our qualifier value widget

    mQualifierValue = new QComboBox(qualifierWidget);

    mQualifierValue->addItems(CellMLSupport::CellMLFileRdfTriple::qualifiersAsStringList());

    mQualifierValue->setCurrentIndex(mQualifierIndex);

    connect(mQualifierValue, SIGNAL(currentIndexChanged(int)),
            this, SLOT(qualifierChanged(const int &)));
    connect(mQualifierValue, SIGNAL(currentIndexChanged(const QString &)),
            this, SLOT(qualifierChanged(const QString &)));

    // Create our qualifier lookup button widget

    mLookupQualifierButton = new QPushButton(qualifierWidget);
    // Note #1: ideally, we could assign a QAction to our QPushButton, but this
    //          cannot be done, so... we assign a few properties by hand...
    // Note #2: to use a QToolButton would allow us to assign a QAction to it,
    //          but a QToolButton doesn't look quite the same as a QPushButton
    //          on some platforms, so...

    mLookupQualifierButton->setCheckable(true);
    mLookupQualifierButton->setChecked(mLookupQualifierButtonIsChecked);
    mLookupQualifierButton->setIcon(QIcon(":/oxygen/categories/applications-internet.png"));
    mLookupQualifierButton->setStatusTip(tr("Look up the qualifier"));
    mLookupQualifierButton->setToolTip(tr("Look Up"));
    mLookupQualifierButton->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);

    connect(mLookupQualifierButton, SIGNAL(clicked()),
            this, SLOT(lookupQualifier()));

    // Add our QComboBox and QPushButton to our cmeta:id widget

    qualifierWidgetLayout->addWidget(mQualifierValue);
    qualifierWidgetLayout->addWidget(mLookupQualifierButton);

    // Add our qualifier widget to our main layout

    newFormLayout->addRow(Core::newLabel(tr("Qualifier:"), 1.0, true, newFormWidget),
                          qualifierWidget);

    // Add our term field

    // Create a widget which will contain both our qualifier value widget and a
    // button to look up the qualifier

    QWidget *termWidget = new QWidget(newFormWidget);

    QHBoxLayout *termWidgetLayout = new QHBoxLayout(termWidget);

    termWidgetLayout->setMargin(0);

    termWidget->setLayout(termWidgetLayout);

    // Create our term value widget

    mTermValue = new QLineEdit(termWidget);

    mTermValue->setText(mTerm);
    // Note: we set the text to whatever term was previously being looked up and
    //       this before tracking changes to the term since we don't want to
    //       trigger a call to termChanged(). Indeed, we might come here as a
    //       result of a retranslation so we shouldn't look up for the term and,
    //       instead, we should call updateItemsGui() which we do at the end of
    //       this procedure...

    connect(mTermValue, SIGNAL(textChanged(const QString &)),
            this, SLOT(termChanged(const QString &)));

    // Create our add term button widget

    mAddTermButton = new QPushButton(termWidget);

    mAddTermButton->setEnabled(false);
    mAddTermButton->setIcon(QIcon(":/oxygen/actions/list-add.png"));
    mAddTermButton->setStatusTip(tr("Add the term"));
    mAddTermButton->setToolTip(tr("Add"));
    mAddTermButton->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);

    connect(mAddTermButton, SIGNAL(clicked()),
            this, SLOT(addTerm()));

    // Add our QComboBox and QPushButton to our cmeta:id widget

    termWidgetLayout->addWidget(mTermValue);
    termWidgetLayout->addWidget(mAddTermButton);

    // Add our term widget to our main layout

    newFormLayout->addRow(Core::newLabel(tr("Term:"), 1.0, true, newFormWidget),
                          termWidget);

    // Reset the tab order from our parent's CellML list's tree view widget
    // Note: ideally, we would take advantage of Qt's signal/slot approach with
    //       the signal being emitted here and the slot being implemented in
    //       mParent, but this wouldn't work here since updateGui() gets called
    //       as part of the creation of this metadata details widget, so...

    setTabOrder(qobject_cast<QWidget *>(mParent->cellmlList()->treeViewWidget()),
                mQualifierValue);
    setTabOrder(mQualifierValue, mLookupQualifierButton);
    setTabOrder(mLookupQualifierButton, mTermValue);
    setTabOrder(mTermValue, mAddTermButton);

    // Create a stacked widget (within a scroll area, so that only the items get
    // scrolled, not the whole metadata edit details widget) which will contain
    // a grid with the results of our terms lookup

    QScrollArea *newItemsScrollArea = new QScrollArea(newMainWidget);

    newItemsScrollArea->setFrameShape(QFrame::NoFrame);
    newItemsScrollArea->setWidgetResizable(true);

    // Add our 'internal' widgets to our new main widget

    newMainLayout->addWidget(newFormWidget);
    newMainLayout->addWidget(new Core::BorderedWidget(newItemsScrollArea,
                                                      true, false, false, false));

    // Keep track of the position of our items vertical scroll bar
    // Note: this is required to make sure that the position doesn't get reset
    //       as a result of retranslating the GUI...

    connect(newItemsScrollArea->verticalScrollBar(), SIGNAL(sliderMoved(int)),
            this, SLOT(trackItemsVerticalScrollBarPosition(const int &)));

    // Add our new widget to our stacked widget

    mWidget->addWidget(newMainWidget);

    // Remove the contents of our old form layout

    if (mFormWidget)
        for (int i = 0, iMax = mFormLayout->count(); i < iMax; ++i) {
            QLayoutItem *item = mFormLayout->takeAt(0);

            delete item->widget();
            delete item;
        }

    // Reset the widget of our old items scroll area and stop tracking the
    // position of its vertical scroll bar
    // Note: the resetting this will automatically delete our old grid widget...

    if (mItemsScrollArea) {
        mItemsScrollArea->setWidget(0);

        disconnect(mItemsScrollArea->verticalScrollBar(), SIGNAL(sliderMoved(int)),
                   this, SLOT(trackItemsVerticalScrollBarPosition(const int &)));
    }

    // Get rid of our old main widget and layout (and its contents)

    if (mMainWidget) {
        mWidget->removeWidget(mMainWidget);

        for (int i = 0, iMax = mMainLayout->count(); i < iMax; ++i) {
            QLayoutItem *item = mMainLayout->takeAt(0);

            delete item->widget();
            delete item;
        }

        delete mMainWidget;
    }

    // Keep track of our new main widgets and layouts

    mMainWidget = newMainWidget;
    mMainLayout = newMainLayout;

    mFormWidget = newFormWidget;
    mFormLayout = newFormLayout;

    mItemsScrollArea = newItemsScrollArea;

    mGridWidget = 0;   // Note: this will be set by our
    mGridLayout = 0;   //       other updateGui() function...

    // Allow ourselves to be updated again

    setUpdatesEnabled(true);

    // Update our items GUI

    updateItemsGui(pItems, pErrorMsg, pLookupTerm);

    // Request for something to be looked up, if needed

    if (mLookupInformation)
        // Look up an 'old' qualifier, resource or resource id

        genericLookup(mInformation, mType, pRetranslate);

    // Set the position of our vertical scroll bar

    mItemsScrollArea->verticalScrollBar()->setValue(pItemsVerticalScrollBarPosition);
}