Block MongoDBBlockInputStream::readImpl()
{
    if (all_read)
        return {};

    MutableColumns columns(description.sample_block.columns());
    const size_t size = columns.size();

    for (const auto i : ext::range(0, size))
        columns[i] = description.sample_block.getByPosition(i).column->cloneEmpty();

    size_t num_rows = 0;
    while (num_rows < max_block_size)
    {
        Poco::MongoDB::ResponseMessage & response = cursor->next(*connection);

        for (const auto & document : response.documents())
        {
            ++num_rows;

            for (const auto idx : ext::range(0, size))
            {
                const auto & name = description.sample_block.getByPosition(idx).name;
                const Poco::MongoDB::Element::Ptr value = document->get(name);

                if (value.isNull() || value->type() == Poco::MongoDB::ElementTraits<Poco::MongoDB::NullValue>::TypeId)
                    insertDefaultValue(*columns[idx], *description.sample_block.getByPosition(idx).column);
                else
                {
                    if (description.types[idx].second)
                    {
                        ColumnNullable & column_nullable = static_cast<ColumnNullable &>(*columns[idx]);
                        insertValue(column_nullable.getNestedColumn(), description.types[idx].first, *value, name);
                        column_nullable.getNullMapData().emplace_back(0);
                    }
                    else
                        insertValue(*columns[idx], description.types[idx].first, *value, name);
                }
            }
        }

        if (response.cursorID() == 0)
        {
            all_read = true;
            break;
        }
    }

    if (num_rows == 0)
        return {};

    return description.sample_block.cloneWithColumns(std::move(columns));
}
Beispiel #2
0
void NVMap::insertValue(std::string key, int value)
{
    char buf[48];
    snprintf (buf, sizeof(buf), "%d", value);

    insertValue(key, buf);
}
Beispiel #3
0
int lineReader(char *line, HashTable *numbers){

	int key;
    int x;

	if(line[0] == 'i' || line[0] == 'I'){
			key = makeKey(&line[2]);
       		x = insertValue(key, numbers);
       		if(x == -1){
       			printf("duplicate\n");
       			return 0;
       		}else{
       			printf("inserted\n");
       			return 0;
       		}
    }else if(line[0] == 's' || line[0] == 'S'){
    		key = makeKey(&line[2]);
       		x = searchValue(key, numbers);
        	if(x == -1){
        		printf("absent\n");
       			return 0;
       		}else{
       			printf("present\n");
       			return 0;
       		}
    }else{
    		printf("error\n");
    		return 0;
    }
}
  //---------------------------------------------------------------------------
  template<typename T> bool loadDelimitedFileNoHeaderT(ifstream &delimitedFileHandle,
                                                       const string &delim,
                                                       const string &commentDelim,
                                                       vector<vector<T> > &lines)
  {
    //read fields for file
    string lineBuff;

    while (!delimitedFileHandle.eof())
    {
      DelimitedTextReader::getlineChomp(delimitedFileHandle, lineBuff);

      if (lineBuff[0] == *commentDelim.c_str())
      { //skip comments
        //do nothing
        DEBUG_TRACE;
      }
      else
      {
        //load in  file
        vector<string> fields;
        stringSplit2(lineBuff, fields, delim);
        insertValue(fields, lines);
      }
    }
    return true;
  }
int QgsUniqueValueRenderer::readXML( const QDomNode& rnode, QgsVectorLayer& vl )
{
  mGeometryType = vl.geometryType();
  QDomNode classnode = rnode.namedItem( "classificationfield" );
  QString classificationField = classnode.toElement().text();

  QgsVectorDataProvider* theProvider = vl.dataProvider();
  if ( !theProvider )
  {
    return 1;
  }

  int classificationId = vl.fieldNameIndex( classificationField );
  if ( classificationId == -1 )
  {
    //go on. Because with joins, it might be the joined layer is not loaded yet
  }
  setClassificationField( classificationId );

  QDomNode symbolnode = rnode.namedItem( "symbol" );
  while ( !symbolnode.isNull() )
  {
    QgsSymbol* msy = new QgsSymbol( mGeometryType );
    msy->readXML( symbolnode, &vl );
    insertValue( msy->lowerValue(), msy );
    symbolnode = symbolnode.nextSibling();
  }
  updateSymbolAttributes();
  vl.setRenderer( this );
  return 0;
}
Block MySQLBlockInputStream::readImpl()
{
    auto row = result.fetch();
    if (!row)
        return {};

    auto block = description.sample_block.cloneEmpty();

    /// cache pointers returned by the calls to getByPosition
    std::vector<IColumn *> columns(block.columns());
    for (const auto i : ext::range(0, columns.size()))
        columns[i] = block.getByPosition(i).column.get();

    std::size_t num_rows = 0;
    while (row)
    {
        for (const auto idx : ext::range(0, row.size()))
        {
            const auto value = row[idx];
            if (!value.isNull())
                insertValue(columns[idx], description.types[idx], value);
            else
                insertDefaultValue(columns[idx], *description.sample_columns[idx]);
        }

        ++num_rows;
        if (num_rows == max_block_size)
            break;

        row = result.fetch();
    }

    return block;
}
void insertAll()
{
    int i;
    for(i = 0; i<bufferSize; i++)
    {
        insertValue(randomNumbersBuffer[i]);
    }
}
GVN::Value * GVN::getValue()
{
    list.emplace_back(current);
    Value & value = list.back();
    insertValue(current++, value);

    return &value;
}
Beispiel #9
0
int insertHeaders(char **png, sParameterStruct *sSO2Parameters, sConfigStruct *config, int png_length){
	char iso_date[25];
	dateStructToISO8601(sSO2Parameters->timestampBefore, iso_date);
	png_length = insertHeader(png, "Creation Time ",    iso_date, png_length);
	png_length = insertValue(png, "dBufferlength",      (float)config->dBufferlength,      png_length);
	png_length = insertValue(png, "dHistMinInterval",   (float)config->dHistMinInterval,   png_length);
	png_length = insertValue(png, "dHistPercentage",    (float)config->dHistPercentage,    png_length);
	png_length = insertValue(png, "dDarkCurrent",       (float)sSO2Parameters->dDarkCurrent,       png_length);
	png_length = insertValue(png, "dImageCounter",      (float)config->dImageCounter,      png_length);
	png_length = insertValue(png, "dInterFrameDelay",   (float)config->dInterFrameDelay,   png_length);
	png_length = insertValue(png, "dTriggerPulseWidth", (float)sSO2Parameters->dTriggerPulseWidth, png_length);
	png_length = insertValue(png, "dExposureTime",      (float)sSO2Parameters->dExposureTime,      png_length);
	png_length = insertValue(png, "dFixTime",           (float)config->dFixTime,           png_length);

	return png_length;
}
Block ODBCBlockInputStream::readImpl()
{
    if (iterator == result.end())
        return {};

    MutableColumns columns(description.sample_block.columns());
    for (const auto i : ext::range(0, columns.size()))
        columns[i] = description.sample_block.getByPosition(i).column->cloneEmpty();

    size_t num_rows = 0;
    while (iterator != result.end())
    {
        Poco::Data::Row & row = *iterator;

        for (const auto idx : ext::range(0, row.fieldCount()))
        {
            const Poco::Dynamic::Var & value = row[idx];

            if (!value.isEmpty())
            {
                if (description.types[idx].second)
                {
                    ColumnNullable & column_nullable = static_cast<ColumnNullable &>(*columns[idx]);
                    insertValue(column_nullable.getNestedColumn(), description.types[idx].first, value);
                    column_nullable.getNullMapData().emplace_back(0);
                }
                else
                    insertValue(*columns[idx], description.types[idx].first, value);
            }
            else
                insertDefaultValue(*columns[idx], *description.sample_block.getByPosition(idx).column);
        }

        ++iterator;

        ++num_rows;
        if (num_rows == max_block_size)
            break;
    }

    return description.sample_block.cloneWithColumns(std::move(columns));
}
// inserts at the leaf
void insertValue(TreeNode *n, int value)
{
    if (*n == NULL){ // create a leaf node
        *n = malloc(sizeof(treenode));
        (*n)->leftnode = NULL;
        (*n)->rightnode = NULL;
        (*n)->value = value;
		(*n)->nnodes = 1;
    }

    else{ // search the tree to insert the value
        if (value < (*n)->value){ // insert in left sub tree
            insertValue(&((*n)->leftnode), value);
        }

        else if (value > (*n)->value){ // insert in right subtree
            insertValue(&((*n)->rightnode), value);
        }
    }
}
QgsUniqueValueRenderer::QgsUniqueValueRenderer( const QgsUniqueValueRenderer& other )
{
  mGeometryType = other.mGeometryType;
  mClassificationField = other.mClassificationField;
  QMap<QString, QgsSymbol*> s = other.mSymbols;
  for ( QMap<QString, QgsSymbol*>::iterator it = s.begin(); it != s.end(); ++it )
  {
    QgsSymbol* s = new QgsSymbol( * it.value() );
    insertValue( it.key(), s );
  }
  updateSymbolAttributes();
}
Beispiel #13
0
void NVMap::insertPair(std::string nameValue, char delim)
{
    std::size_t pos;
    if ((pos = nameValue.find(delim)) == std::string::npos)
    {
        std::cout << "Wrong format to parse NameValue `" << nameValue << "`." << std::endl;
        return;
    }

    std::string name = nameValue.substr(0, pos);
    std::string value = nameValue.substr(pos+1);
    insertValue(name, value);
}
Beispiel #14
0
int main()
{
    printf("Type numbers of values to insert: ");
    int nr_of_values;
    scanf("%d", &nr_of_values);
    srand(time(NULL));
    createHashTable();
    int max = 0;

    printf("Would you like random string length ? (Y/N)\n");
    char key;
    do
    {
        key = getch();
    }
    while ((toupper(key) != 'Y') && (toupper(key) != 'N'));
    int length = -1;
    if (toupper(key) == 'N')
    {
        printf("Type the length of the strings: ");
        scanf("%d", &length);
    }

    for (int i=0; i<nr_of_values; i++)
    {
        char* string = randomString(length);
        int val = insertValue(string);
        if (max < val)
        {
            max = val;
        }
    }
    printf("The max number of collisions: %d\n", max);
    printf("Save the hash table file ? (Y/N)\n");
    do
    {
        key = getch();
    }
    while ((toupper(key) != 'Y') && (toupper(key) != 'N'));
    if (toupper(key) == 'Y')
    {
        char* buffer = (char*) calloc(1024, sizeof(char));
        printf("Type the name of the file (without extension): ");
        scanf("%s", buffer);
        strcat(buffer, ".txt");
        printHashTable(buffer);
    }
    return 0;
}
GVN::Value * GVN::getValue(const symbol::Symbol & sym)
{
    const auto i = maps.equal_range(sym);
    if (i.first == i.second)
    {
        GVN::Value & value = maps.emplace(sym, current)->second;
        insertValue(current++, value);

        return &value;
    }
    else
    {
        return &std::prev(i.second)->second;
    }
}
GVN::Value * GVN::getValue(const int64_t x)
{
    const auto i = mapi64.find(x);
    if (i == mapi64.end())
    {
        GVN::Value & value = mapi64.emplace(x, current++).first->second;
        insertValue(x, value);

        return &value;
    }
    else
    {
        return &i->second;
    }
}
GVN::Value * GVN::getValue(const MultivariatePolynomial & mp)
{
    const auto i = mapp.find(mp);
    if (i != mapp.end())
    {
        return i->second;
    }
    else
    {
        list.emplace_back(current++);
        Value & val = list.back();
        insertValue(mp, val);

        return &val;
    }
}
QgsUniqueValueRenderer& QgsUniqueValueRenderer::operator=( const QgsUniqueValueRenderer & other )
{
  if ( this != &other )
  {
    mGeometryType = other.mGeometryType;
    mClassificationField = other.mClassificationField;
    clearValues();
    for ( QMap<QString, QgsSymbol*>::iterator it = mSymbols.begin(); it != mSymbols.end(); ++it )
    {
      QgsSymbol* s = new QgsSymbol( *it.value() );
      insertValue( it.key(), s );
    }
    updateSymbolAttributes();
  }
  return *this;
}
Beispiel #19
0
Block MongoDBBlockInputStream::readImpl()
{
    if (all_read)
        return {};

    Block block = description.sample_block.cloneEmpty();

    /// cache pointers returned by the calls to getByPosition
    std::vector<IColumn *> columns(block.columns());
    const size_t size = columns.size();

    for (const auto i : ext::range(0, size))
        columns[i] = block.getByPosition(i).column.get();

    size_t num_rows = 0;
    while (num_rows < max_block_size)
    {
        Poco::MongoDB::ResponseMessage & response = cursor->next(*connection);

        for (const auto & document : response.documents())
        {
            ++num_rows;

            for (const auto idx : ext::range(0, size))
            {
                const auto & name = description.names[idx];
                const Poco::MongoDB::Element::Ptr value = document->get(name);

                if (value.isNull())
                    insertDefaultValue(columns[idx], *description.sample_columns[idx]);
                else
                    insertValue(columns[idx], description.types[idx], *value, name);
            }
        }

        if (response.cursorID() == 0)
        {
            all_read = true;
            break;
        }
    }

    if (num_rows == 0)
        return {};

    return block;
}
void GVN::setValue(const symbol::Symbol & sym, const MultivariatePolynomial & mp)
{
    MapPolys::iterator i = mapp.find(mp);
    if (i != mapp.end())
    {
        maps.emplace(sym, i->second->value)->second.poly = i->second->poly;
    }
    else
    {
        Value & value = maps.emplace(sym, current++)->second;
        insertValue(mp, value);
        if (mp.isConstant() && mapi64.find(mp.constant) == mapi64.end())
        {
            mapi64.emplace(mp.constant, value);
        }
    }
}
Beispiel #21
0
main()
{
    SkipList_t *list = NULL;
    char buf[256];
    int  choice = 0;
 
    list = SkipListAlloc( myCmp, myFree );
    if ( list == NULL ) {
        printf( "ERROR: Allocation of skip list failed\n" );
        exit(1);
    }

    while (1) {
        displayMenu();
        choice = atoi( gets(buf) );
        switch( choice ) {
            case 1 :
                insertValue( list );
                break;
            case 2 :
                deleteValue( list );
                break;
            case 3 :
                searchValue( list );
                break;
            case 4 :
                getNextValue( list );
                break;
            case 5 :
                printValue( list );
                break;
            case 6 :
                clearList( list );
                break;
            case 7:
                SkipListFree(list);
                exit(0);
            default :
                break;
        }
    }

    exit(0);
}
Beispiel #22
0
    GVN::Value * GVN::getValue(const double x)
    {
        int64_t _x;
        if (tools::asInteger(x, _x))
        {
            const auto i = mapi64.find(_x);
            if (i == mapi64.end())
            {
                GVN::Value & value = mapi64.emplace(_x, current++).first->second;
                insertValue(_x, value);

                return &value;
            }
            else
            {
                return &i->second;
            }
        }

        return nullptr;
    }
  //---------------------------------------------------------------------------
  template<typename T> bool loadDelimitedFileNoHeaderT(const char * filename,
                                                       const string &delim,
                                                       const string &commentDelim,
                                                       vector<vector<T> > &lines)
  {
    //open delimited file
    ifstream delimitedFileHandle(filename);

    if (!delimitedFileHandle.is_open() || !delimitedFileHandle.good())
    {
      ERROR_MSG("Unable to read file! " << filename);
      return false;
    }

    //read fields for file
    string lineBuff;

    while (!delimitedFileHandle.eof())
    {
      DelimitedTextReader::getlineChomp(delimitedFileHandle, lineBuff);

      if (lineBuff[0] == *commentDelim.c_str())
      { //skip comments
        //do nothing
        DEBUG_TRACE;
      }
      else if (lineBuff.compare("") == 0) //skip blank lines
      {
        DEBUG_TRACE;
      }
      else
      {
        //load in  file
        vector<string> fields;
        stringSplit2(lineBuff, fields, delim);
        insertValue(fields, lines);
      }
    }
    return true;
  }
Beispiel #24
0
//--------------------------------------------------------------
bool  ofxMuiNumberData::insertValue(int index, float val, ofxMuiRange _bounds) {
    insertValue(index, val, _bounds, ofxMuiRange());
}
void Emotions::arousalValence(double arousal, double valence){
    arousal=(int)(arousal*qPow(10,EMOTION_AROUSAL_ACCURACY));
    valence=(int)(valence*qPow(10,EMOTION_VALENCE_ACCURACY));

    if(_record){
        insertValue(_arousalSet, arousal);
        insertValue(_valenceSet, valence);

        QString* movie = new QString(EMOTION_MOVIE);
        if(!movie->isEmpty()){
            QFile file(_dataPath+"."+EMOTION_MOVIE);
            if (!file.open(QIODevice::WriteOnly|QIODevice::Append)) {
                qDebug() << "Emotions : cannot open file "+file.fileName()+" : "
                         << qPrintable(file.errorString()) << file.fileName()<< endl;
                return;
            }

            QString* arousalStr=new QString("");
            arousalStr->setNum(arousal,'f', EMOTION_AROUSAL_ACCURACY);

            QString* valenceStr=new QString("");
            valenceStr->setNum(valence,'f', EMOTION_VALENCE_ACCURACY);

            QString emotion = getEmotion();
            QDateTime time = QDateTime::currentDateTime();

            QString* line = new QString(*arousalStr+" "+*valenceStr+" "+emotion+" "+time.toString("hh:mm:ss:zzz")+"\n");
            file.write(line->toAscii());
            file.close();

            if(_lastPlot.msecsTo(time)>EMOTION_PLOT_TIME){
                // QProcess to call R script
                /*
                 * This script will make a boxplot of valence and arousal every
                 * EMOTION_PLOT_TIME seconds and save them in a pdf.
                 *
                 * WARNING : be aware that your computer will make a lot of job using this script
                 * and it will certainly _overload_ your CPU. You can reduce it by increasing
                 * EMOTION_PLOT_TIME.
                */
                /*QString program = "plot_movie.R";
                QStringList arguments;
                arguments << file.fileName()
                          << _dataPath+".calm"
                          << _dataPath+".exited"
                          << _dataPath+".positive"
                          << _dataPath+".negative";

                QProcess *plotProcess = new QProcess(this);
                plotProcess->startDetached(program, arguments);
                _lastPlot=QDateTime::currentDateTime();
                */
            }
        }
    }

    if(_saveCalm){
        updateTrainedClass("calm", arousal, "positive", valence);
    }
    if(_saveJoy){
        updateTrainedClass("exited", arousal, "positive", valence);
    }
    if(_saveSad){
        updateTrainedClass("calm", arousal, "negative", valence);
    }
    if(_saveAngry){
        updateTrainedClass("exited", arousal, "negative", valence);
    }

    if(_guess){
        emit giveEmotion(QVariant(getEmotion()));
        _guess=false;
    }
}
Beispiel #26
0
int main()
{
    node *Table[MAX];
    clearTable(Table);
    int a[MAX];
    char *str;
    /*char in;
    char input[CHARS];*/
    int i, j;
    double t;
    clock_t t1,t2;
    t1=clock();
    for (j=0;j<MAX;j++)
    {
        a[j]=0;
    }
    for (j=0; j<2000; j++)
    {
        str=randstring(CHARS);
        insertValue(Table[hashFunction(str)], str);
        a[hashFunction(str)]++;
    }
    t2=clock();
    t=(double)(t2-t1);
    printf ("The insertion of 2000 elements took %f seconds.", &t);
    printf ("\n");
    for (j=0; j<MAX; j++)
    {
        printf ("%d ", a[j]);
    }

    /*while(1)
    {
        printf("(I)nsert\n(S)earch\n(L)ist all\n\n");
        printf(" > ");
        scanf("%d",&in);
        switch(in)
        {
            case 1:
                printf("\tInserting: \n");
                printf("\t > "); scanf("%s",input);
                Table[hashFunction(input)] = insertValue(Table[hashFunction(input)],input);
                break;
            case 2:
                printf("\tSearching value: \n");
                printf("\t > "); scanf("%s", &input);
                if (hasValue(Table[hashFunction(input)],input))
                {
                    printf("%s is in the table!\n",input);
                }
                else
                {
                    printf("%s is not in the table!\n",input);
                }
                break;
            case 3:
                for (i = 0; i < MAX; i++)
                {
                    printf("[%d] ",i);
                    printList(Table[i]);
                }
                break;
            default:
                break; return;
        }
        printf("_______________________________________________________\n");
    }*/
}
Beispiel #27
0
int main()
{
    /** Variables to measure the time **/
    double start,finish;

    node *Table[MAX];
    clearTable(Table);
    char input[CHARS];

    int j,k,i,x;

    /** For Hash function 1, dispersion and time for inserting the elements**/
    start=clock();
    for(k=1;k<=200;k++)
        for(j=1;j<=10;j++)
        {
            strcpy(input,mkrndstr(j));
            x=hashFunction1(input);
            if (hasValue(Table[x],input))
            {
                /**printf("%s is in the table!\n",input);**/
            }
            else
            {
                    Table[x] = insertValue(Table[x],input);
            }
        }
    finish=clock();
    printf("\nThe time (in seconds) for 1st function=%lf \n",(finish-start)/CLOCKS_PER_SEC);

    printf("\nDispersion for 1st function:\n");
    for (i=0;i<MAX;i++)
    {
        printf("[%d]: %d \n",i,countElements(Table[i]));
    }


    /** For Hash function 2, dispersion and time for inserting the elements**/
    clearTable(Table);
    start=clock();
    for(k=1;k<=200;k++)
        for(j=1;j<=10;j++)
        {
            strcpy(input,mkrndstr(j));
            x=hashFunction2(input);
            if (hasValue(Table[x],input))
            {
                /**printf("%s is in the table!\n",input);**/
            }
            else
            {
                    Table[x] = insertValue(Table[x],input);
            }
        }
    finish=clock();
    printf("\nThe time (in seconds) for 2nd function=%lf \n",(finish-start)/CLOCKS_PER_SEC);
    printf("\nDispersion for 2nd function:\n");
    for (i=0;i<MAX;i++)
    {
        printf("[%d]: %d \n",i,countElements(Table[i]));
    }


    /**
    node *Table[MAX];
    clearTable(Table);
    char input[CHARS];
    int in=-1;
    int i;
    while(in!=0)
    {
        printf("(1)Insert\n(2)Search\n(3)Count all\n(4)List all\n(0)Escape\n\n");
        printf(" > ");
        scanf("%d",&in);
        switch(in)
        {
            case 1:
                printf("\tInserting: \n");
                printf("\t > ");
                scanf("%s",input);
                if (hasValue(Table[hashFunction1(input)],input))
                {
                    printf("%s is in the table!\n",input);
                }
                else
                {
                    Table[hashFunction1(input)] = insertValue(Table[hashFunction1(input)],input);
                }
                break;
            case 2:
                printf("\tSearching value: \n");
                printf("\t > ");
                scanf("%s", &input);
                if (hasValue(Table[hashFunction1(input)],input))
                {
                    printf("%s is in the table!\n",input);
                }
                else
                {
                    printf("%s is not in the table!\n",input);
                }
                break;
            case 4:
                for (i = 0; i < MAX; i++)
                {
                    printf("[%d] ",i);
                    printList(Table[i]);
                }
                break;
            case 3:
                for (i = 0; i < MAX; i++)
                {
                    printf("\n[%d]: %d ",i, countElements(Table[i]));
                }
                break;
        }
        printf("_______________________________________________________\n");
    }
    **/
    return 0;
}
Beispiel #28
0
void insertArgument(QDomDocument& doc, QDomElement& where, const QVariant& what)
{
	switch(what.type())
	{
	case QMetaType::Bool:
		insertValue(doc, where, "boolean", what.toBool() ? "1" : "0");
		break;
	case QMetaType::Int:
	case QMetaType::UInt:
//	case QMetaType::Long:
//	case QMetaType::Short:
//	case QMetaType::ULong:
//	case QMetaType::UShort:
		insertValue(doc, where, "i4", what.toString());
		break;
	case QMetaType::ULongLong:
	case QMetaType::LongLong:
		insertValue(doc, where, "ex:i8", what.toString());
		break;
//	case QMetaType::Float:
	case QMetaType::Double:
		insertValue(doc, where, "double", what.toString());
		break;
	case QMetaType::QString:
		insertValue(doc, where, "string", what.toString());
		break;
	case QMetaType::QByteArray:
		insertValue(doc, where, "base64", what.toByteArray().toBase64());
		break;
	case QMetaType::QDateTime:
		insertValue(doc, where, "dateTime.iso8601", what.toDateTime().toString(Qt::ISODate));
		break;
	case QMetaType::QVariantList:
		{
			QDomElement array, data, value;
			value = doc.createElement("value");
			array = doc.createElement("array");
			data = doc.createElement("data");
			
			QList<QVariant> list = what.toList();
			foreach(QVariant v, list)
				insertArgument(doc, data, v);
			
			array.appendChild(data);
			value.appendChild(array);
			where.appendChild(value);
		}
		break;
	case QMetaType::QStringList:
		{
			QDomElement array, data, value;
			value = doc.createElement("value");
			array = doc.createElement("array");
			data = doc.createElement("data");

			QStringList list = what.toStringList();
			foreach(QString v, list)
				insertArgument(doc, data, v);

			array.appendChild(data);
			value.appendChild(array);
			where.appendChild(value);
		}
		break;
	case QMetaType::QVariantMap:
		{
			QDomElement _struct, value;
			_struct = doc.createElement("struct");
			value = doc.createElement("value");
			
			QMap<QString, QVariant> map = what.toMap();
			for(QMap<QString, QVariant>::iterator it = map.begin(); it != map.end(); it++)
			{
				QDomElement member = doc.createElement("member");
				QDomElement name = doc.createElement("name");
				QDomText ntext = doc.createTextNode(it.key());
				
				name.appendChild(ntext);
				member.appendChild(name);
				insertArgument(doc, member, it.value());
				_struct.appendChild(member);
			}
			
			value.appendChild(_struct);
			where.appendChild(value);
		}
		break;
	default:
		qDebug() << "XmlRpc::insertArgument(): Unsupported QVariant type:" << what.type();
	}
}
Beispiel #29
0
int main() {
	DBMSAPI dbms;	//Declare the dbms api

	initRelations(&dbms);
	cout << displayMainMenu() << endl;

	int searchResults = 0;
	
	while (1) {		//input loop
		string in;
		getline(cin, in);

		vector<string> tokens = splitAtSpace(in);	//split the command given by spaces

		if (tokens[0] == "HELP") {				//process HELP
			cout << displayMainMenu() << endl;
		}
		else if (tokens[0] == "EXIT") {			//process EXIT
			saveRelations(&dbms);
			exit(0);
		}
		else if (tokens[0] == "ADD") {			
			if (tokens[1] == "CAR") {			//process ADD CAR
				vector<string> values;
				for (int i = 2; i < tokens.size(); i++) {
					values.push_back(tokens[i]);
				}
				insertValue("cars", values, &dbms);
				cout << "Addition approved!" << endl << endl;
			}
			else if (tokens[1] == "DEALERSHIP") {//process ADD DEALERSHIP
				vector<string> values;
				for (int i = 2; i < tokens.size(); i++) {
					values.push_back(tokens[i]);
				}
				insertValue("dealerships", values, &dbms);
				cout << "Addition approved!" << endl << endl;
			}
		}
		else if (tokens[0] == "LIST") {			//process LIST
			if (tokens.size() != 5) {
				cout << "Invalid number of arguments!" << endl << endl;
			}
			else {
				//Price INTEGER, Date_Listed VARCHAR(20), VIN VARCHAR(17), Dealership_Name VARCHAR(30)
				string listing = "INSERT INTO listings VALUES FROM (" + tokens[1] + ", " + tokens[2] + ", " + tokens[3] + ", " + tokens[4] + ");";
				dbms.execute(listing);
				cout << "Listing approved!" << endl << endl;
			}
		}
		else if (tokens[0] == "UNLIST") {		//process UNLIST
			if (tokens.size() != 2) {
				cout << "Invalid number of arguments!" << endl << endl;
			}
			else {
				string removeListing = "DELETE FROM listings WHERE (VIN == \"" + tokens[1] + "\");";
				dbms.execute(removeListing);
			}
		}
		else if (tokens[0] == "SELL") {			//process SELL
			if (tokens.size() != 6) {
				cout << "Invalid number of arguments!" << endl << endl;
			}
			else {
				//Price INTEGER, Date_Sold VARCHAR(20), VIN VARCHAR(17), Dealership_Name VARCHAR(30), Buyer_Name VARCHAR(50)
				string sale = "INSERT INTO sales VALUES FROM (" + tokens[1] + ", " + tokens[2] + ", " + tokens[3] + ", " + tokens[4] + ", " + tokens[5] + ");";
				dbms.execute(sale);
				string removeListing = "DELETE FROM listings WHERE (VIN == \"" + tokens[3] + "\");";
				dbms.execute(removeListing);
				string removeInventory = "DELETE FROM cars WHERE (VIN == \"" + tokens[3] + "\");";
				dbms.execute(removeInventory);
				cout << "Sale approved!" << endl << endl;
			}			
		}
		else if (tokens[0] == "INVENTORY") {	//process INVENTORY
			showRelation("cars", &dbms);
		}
		else if (tokens[0] == "DEALERSHIPS") {	//process DEALERSHIPS
			showRelation("dealerships", &dbms);
		}
		else if (tokens[0] == "LISTINGS") {		//process LISTINGS
			showRelation("listings", &dbms);
		}
		else if (tokens[0] == "SALES") {		//process SALES
			showRelation("sales", &dbms);
		}
		else if (tokens[0] == "SEARCH") {		//process SEARCH
			searchResults++;
			stringstream ss;
			ss << searchResults;
			string query = "searchresult" + ss.str() + " <- select (";
			for (int i = 2; i < tokens.size(); i++) {
				query += tokens[i];
				if (i + 1 < tokens.size()) { query += " "; }
			}
			query += ") " + tokens[1] + ";";
			dbms.execute(query);			
			string showResult = "SHOW searchresult" + ss.str() + ";";
			dbms.execute(showResult);
			cout << endl;
		}
		else if (tokens[0] == "UPDATE") {
			if (tokens[1] == "LISTING") {		//process UPDATE LISTING
				if (tokens.size() != 4) {
					cout << "Invalid number of arguments!" << endl;
				}
				else {
					string updateListings = "UPDATE listings SET Price = " + tokens[3] + " WHERE VIN == " + tokens[2] + ";";
					dbms.execute(updateListings);
				}				
			}
		}
		else if (tokens[0] == "CROSS") {		//process CROSS
			string cross = "crossResult <- dealerships * cars;";
			dbms.execute(cross);
			string showCross = "SHOW crossResult;";
			dbms.execute(showCross);
			string closeCross = "CLOSE crossResult;";
			dbms.execute(closeCross);
		}
		else if (tokens[0] == "PROJECT") {		//process PROJECT
			string project = "projectResult <- project (";
			for (int i = 2; i < tokens.size(); i++) {
				project += tokens[i];
				if (i + 1 < tokens.size()) { project += ", "; }
			}
			project += ") " + tokens[1] + ";";
			dbms.execute(project);
			string showProject = "SHOW projectResult;";
			dbms.execute(showProject);
			string closeProject = "CLOSE projectResult;";
			dbms.execute(closeProject);
		}
		else if (tokens[0] == "UNION") {		
			if (tokens[1] == "SEARCHES") {		//process UNION SEARCHES
				string unionQuery = "unionResult <- " + tokens[2] + " + " + tokens[3] + ";";
				dbms.execute(unionQuery);
				string showUnion = "SHOW unionResult;";
				dbms.execute(showUnion);
				string closeUnion = "CLOSE unionResult;";
				dbms.execute(closeUnion);
			}
		}
		else if (tokens[0] == "DIFFERENCE") {	
			if (tokens[1] == "SEARCHES") {		//process DIFFERENCE SEARCHES
				string diffQuery = "diffResult <- " + tokens[2] + " - " + tokens[3] + ";";
				dbms.execute(diffQuery);
				string showDiff = "SHOW diffResult;";
				dbms.execute(showDiff);
				string closeDiff = "CLOSE diffResult;";
				dbms.execute(closeDiff);
			}
		}
		else {									//process unknown command
			cout << "Unknown command!" << endl << endl;
		}

	}
}
// get an field index and edit the new value from the user
void CourseEditingState::edit(int index) {
	string new_svalue;
	int choise = 0;
	bool circle = false;;
	cout << "You have choosen to edit the field: \n";
	switch (index) {
	case 0:
		cout << "Name " << this->course.name.get() << endl << endl;
		cout << "Please enter new value \n\n";
		cin.ignore();
		getline(cin, new_svalue);
		course.name.set(new_svalue);
		break;
	case 1:
		cout << "Description " << this->course.description.get() << endl << endl;
		cout << "Please enter new value \n\n";
		cin.ignore();
		getline(cin, new_svalue);
		course.description.set(new_svalue);
		break;
	case 2:
		cout << "Max Number of students " << this->course.maxNumberOfStudents.get() << endl << endl;
		cout << "Please enter new value \n\n";
		course.maxNumberOfStudents.set(insertValue());
		break;
	case 3:
		cout << "Teaching Hours " << this->course.teachingHours.get() << endl << endl;
		cout << "Please enter new value \n\n";
		course.teachingHours.set(insertValue());
		break;
	case 4:
		system("cls");
		while (choise != 3) {
			cout << getCaption(4) << " : " << getValue(4) << endl << endl;
			cout << "1.adding pre course\n2.remove\n3.exit\n\n";
			choise = insertValue();
			switch (choise) {
			case 1:
				if (displayAllAvailableCourses(seasonConfig, course) != 0) {
					cout << "enter course index: ";
					course.pre.add(seasonConfig.courses.get(insertValue()));
					circle = checkCircle(this->seasonConfig);
					if (circle == true) {
						cout << "Cannot add course because circle was found \n\n";
						course.pre.remove(course.pre.count() - 1);	
					}
				}
				else {
					cout << "No available courses to add" << endl << endl;
				}
				_sleep(3000);
				break;
			case 2:
				if (course.pre.count() != 0) {
					cout << "enter course index: ";
					course.pre.remove(insertValue());
				}
				else {
					cout << "No pre courses to remove" << endl << endl;
					_sleep(3000);
				}
				break;
			case 3:
				choise = 3;
			default:
				cout << "Wrong key \n";
				break;
			}
		}
		break;
	}
}