Example #1
0
bool readXML(map<string, Table>& tables) {
    TiXmlDocument *myDoc = new TiXmlDocument("information.xml");

    if (!myDoc->LoadFile()) {
        cout << myDoc->ErrorDesc() << endl;
        return false;
    } else
        myDoc->LoadFile();
    TiXmlElement* root = myDoc->RootElement();
    //the first layer loop
    for (TiXmlNode* firstNode = root->FirstChild(); firstNode;
            firstNode = firstNode->NextSibling()) {
        Table tmpTable;
        if (strcmp(firstNode->Value(), "class") == 0) {
            //the second layer loop
            for (TiXmlNode *secondNode = firstNode->FirstChild();
                    secondNode; secondNode = secondNode->NextSibling()) {
                if (strcmp(secondNode->Value(), "class_name") == 0) {
                    tmpTable.setTableName(secondNode->FirstChild()->Value());
                } else if (strcmp(secondNode->Value(), "attribute") == 0) {
                    Attribute tmpAttribute;
                    for (TiXmlNode *thirdNode = secondNode->FirstChild();
                            thirdNode; thirdNode = thirdNode->NextSibling()) {
                        if (strcmp(thirdNode->Value(), "attribute_name") == 0) {
                            if (thirdNode->FirstChild() != 0)
                                tmpAttribute.name = thirdNode->FirstChild()->Value();
								string name = tmpTable.getTableName();
								string newName = name.substr(0,2) + '_';
								newName += tmpAttribute.name;
								tmpAttribute.name = newName;

                        } else if (strcmp(thirdNode->Value(), "identifier") == 0) {
                            if (thirdNode->FirstChild() != 0) {
                                tmpAttribute.id = thirdNode->FirstChild()->Value();
                            }
                        } else if (strcmp(thirdNode->Value(), "multiplicity") == 0) {
                            if (thirdNode->FirstChild() != 0)
                                tmpAttribute.multiplicity = thirdNode->FirstChild()->Value();
                        }

                    }

                    tmpTable.setAttribute(tmpAttribute);
                }
            }
            tables.insert(make_pair(tmpTable.getTableName(), tmpTable));

        } else if (strcmp(firstNode->Value(), "association") == 0) {
            Association tmpAssociation;
            for (TiXmlNode *secondNode = firstNode->FirstChild();
                    secondNode; secondNode = secondNode->NextSibling()) {
                if (strcmp(secondNode->Value(), "nameOfAssociation") == 0) {
                    if (secondNode->FirstChild() != 0)
                        tmpAssociation.nameOfAssociation = secondNode->FirstChild()->Value();
                } else if (strcmp(secondNode->Value(), "class") == 0) {
                    Association_class tableValue;
                    for (TiXmlNode *thirdNode = secondNode->FirstChild();
                            thirdNode; thirdNode = thirdNode->NextSibling()) {
                        if (strcmp(thirdNode->Value(), "class_name") == 0) {
                            if (thirdNode->FirstChild() != 0)
                                tableValue.name = thirdNode->FirstChild()->Value();
                        } else if (strcmp(thirdNode->Value(), "multiplicity") == 0) {
                            if (thirdNode->FirstChild() != 0)
                                tableValue.multiplicity = thirdNode->FirstChild()->Value();
                        } else if (strcmp(thirdNode->Value(), "role") == 0) {
                            if (thirdNode->FirstChild() != 0)
                                tableValue.role = thirdNode->FirstChild()->Value();
                        } else {
                            if (thirdNode->FirstChild() != 0)
                                tableValue.qualification.push_back(thirdNode->
                                    FirstChild()->Value());
                        }
                    }
                    tmpAssociation.startTable = tableValue;
                } else if (strcmp(secondNode->Value(), "other_class") == 0) {
                    Association_class tableValue;
                    for (TiXmlNode *thirdNode = secondNode->FirstChild();
                            thirdNode; thirdNode = thirdNode->NextSibling()) {
                        if (strcmp(thirdNode->Value(), "class_name") == 0) {
                            tableValue.name = thirdNode->FirstChild()->Value();
                        } else if (strcmp(thirdNode->Value(), "multiplicity") == 0) {
                            if (thirdNode->FirstChild() != 0)
                                tableValue.multiplicity = thirdNode->FirstChild()->Value();
                        } else if (strcmp(thirdNode->Value(), "role") == 0) {
                            if (thirdNode->FirstChild() != 0)
                                tableValue.role = thirdNode->FirstChild()->Value();
                        } else {
                            if (thirdNode->FirstChild() != 0)
                                tableValue.qualification.push_back(thirdNode->
                                    FirstChild()->Value());
                        }
                    }
                    tmpAssociation.anotherTable = tableValue;
                } else if (strcmp(secondNode->Value(), "Link") == 0) {
                    Linker tmpLink;
                    TiXmlNode* thirdNode = secondNode->FirstChild();
                    for (; thirdNode; thirdNode = thirdNode->NextSibling()) {
                        if (strcmp(thirdNode->Value(), "link_attribute") == 0
                                && thirdNode->FirstChild() != 0) {
                            TiXmlNode* forthNode = thirdNode->FirstChild();
                            for (; forthNode; forthNode = forthNode->NextSibling()) {
                                if (forthNode->FirstChild() != NULL)
                                    tmpLink.attributes.push_back(forthNode->FirstChild()
                                        ->Value());
                            }
                        } else if (strcmp(thirdNode->Value(), "association_class") == 0
                                && thirdNode->FirstChild() != 0) {
                            TiXmlNode* forthNode = thirdNode->FirstChild();
                            for (; forthNode; forthNode = forthNode->NextSibling()) {
                                if (strcmp(forthNode->Value(), "nameOfAssociationClass") == 0) {
                                    if (strlen(forthNode->FirstChild()->Value()) > 0) {
                                        if (forthNode->FirstChild() != 0)
                                            tmpLink.nameOfAssociationClass = forthNode->FirstChild()
                                            ->Value();
                                    }
                                } else if (strcmp(forthNode->Value(), "qualification") == 0) {
                                    if (strlen(forthNode->FirstChild()->Value()) > 0) {
                                        if (forthNode->FirstChild() != 0)
                                            tmpLink.qualification.push_back(forthNode->FirstChild()
                                                ->Value());
                                    }
                                }
                            }
                        }
                    }
                    if (tmpLink.attributes.size() != 0 ||
                            tmpLink.nameOfAssociationClass != "" ||
                            tmpLink.qualification.size() != 0) {
                        tmpAssociation.link = tmpLink;
                    }
                }

            }
            map<string, Table>::iterator tableIte = tables.find(tmpAssociation.
                    startTable.name);
            if (tableIte != tables.end()) {
                tableIte->second.setAssociation(tmpAssociation);
				tableIte->second.setHasLink(true);
				tableIte = tables.find(tmpAssociation.anotherTable.name);
				tableIte->second.setHasLink(true);
            } else {
                cerr << "There is no table in this database.";
            }
        } else if (strcmp(firstNode->Value(), "generlisation") == 0) {
            TiXmlNode* secondNode = firstNode->FirstChild();
            Generalisation tmpGeneralisation;
            vector<string> tmpClassName;
            for (; secondNode; secondNode = secondNode->NextSibling()) {
                if (strcmp(secondNode->Value(), "class_name") == 0) {
                    if (secondNode->FirstChild() != 0)
                        tmpClassName.push_back(secondNode->FirstChild()->Value());
                } else if (strcmp(secondNode->Value(), "ISA") == 0) {
                    if (secondNode->FirstChild() != 0)
                        tmpGeneralisation.ISA = secondNode->FirstChild()->Value();
                } else if (strcmp(secondNode->Value(), "generalisation") == 0) {
                    if (secondNode->FirstChild() != 0)
                        tmpGeneralisation.type = secondNode->FirstChild()->Value();
                }
            }
            
            vector<string>::iterator classNameIter = tmpClassName.begin();
            while(classNameIter != tmpClassName.end()){
                tmpGeneralisation.className = *classNameIter;
                map<string, Table>::iterator tableIte = tables.find(tmpGeneralisation.className);
            if (tableIte != tables.end()) {
                tableIte->second.setGeneralisation(tmpGeneralisation);
                 } else {
                cerr << "There is no table in this database.";
                 }
                classNameIter++;
             }
        }                    
    }
    return true;
}
Example #2
0
void translate(Table& envT, Table& userT)
{

  enum QueueType { UNKNOWN = -1, SLURM = 1, SGE, SLURM_TACC, PBS, LSF };
  QueueType queueType = UNKNOWN;

  // Pick type of queuing system.

  if (envT.count("SGE_ACCOUNT"))
    queueType = SGE;
  else if (envT.count("SLURM_TACC_ACCOUNT") || envT.count("SLURM_TACC_JOBNAME"))
    queueType = SLURM_TACC;
  else if (envT.count("SBATCH_ACCOUNT"))
    queueType = SLURM;
  else if (envT.count("PBS_JOBID"))
    queueType = PBS;
  else if (envT.count("LSF_VERSION"))
    queueType = LSF;
  

  // Now fill in num_cores, num_nodes, account, job_id, queue, submit_host in userT from the environment
  if (queueType == SGE)
    {
      userT["num_cores"]   = safe_get(userT, "num_tasks",   "1");
      userT["num_nodes"]   = safe_get(envT,  "NHOSTS",      "1");
      userT["account"]     = safe_get(envT,  "SGE_ACCOUNT", "unknown");
      userT["job_id"]      = safe_get(envT,  "JOB_ID",      "unknown");
      userT["queue"]       = safe_get(envT,  "QUEUE",       "unknown");
      userT["submit_host"] = "unknown";
    }
  else if (queueType == SLURM_TACC || queueType == SLURM )
    {
      userT["num_cores"]   = safe_get(userT, "num_tasks",           "1");
      userT["num_nodes"]   = safe_get(envT,  "SLURM_NNODES",        "1"); 
      userT["job_id"]      = safe_get(envT,  "SLURM_JOB_ID",        "unknown");
      userT["queue"]       = safe_get(envT,  "SLURM_QUEUE",         "unknown");
      userT["submit_host"] = safe_get(envT,  "SLURM_SUBMIT_HOST",   "unknown");
      if (queueType == SLURM_TACC)
        userT["account"]   = safe_get(envT,  "SLURM_TACC_ACCOUNT",  "unknown");
    }
  else if (queueType == PBS)
    {
      userT["num_cores"]   = safe_get(userT, "num_tasks",     "1");
      userT["num_nodes"]   = safe_get(envT,  "PBS_NUM_NODES", "1"); 
      userT["job_id"]      = safe_get(envT,  "PBS_JOBID",     "unknown");
      userT["queue"]       = safe_get(envT,  "PBS_QUEUE",     "unknown");
      userT["submit_host"] = safe_get(envT,  "PBS_O_HOST",    "unknown");
      userT["account"]     = safe_get(envT,  "PBS_ACCOUNT",   "unknown");
    }
  else if (queueType == LSF)
    {
      // We must count the number of "words" in mcpuA.
      // We find the number of words by counting space blocks and add 1;
      // then divide by 2. then convert to a string.
      std::string mcpuA    = safe_get(envT,  "LSB_MCPU_HOSTS",  "a 1");
      std::string::size_type idx;
      int count = 1;
      idx = 0;
      while (1)
        {
          idx = mcpuA.find(" ",idx);
          if (idx == std::string::npos)
            break;
          count++;
          idx = mcpuA.find_first_not_of(" ",idx+1);
        }
      count /= 2;
      std::ostringstream sstream;
      sstream << count; 
      
      userT["num_cores"]   = safe_get(userT, "num_tasks",        "1");
      userT["num_nodes"]   = sstream.str();
      userT["job_id"]      = safe_get(envT,  "LSB_JOBID",        "unknown");
      userT["queue"]       = safe_get(envT,  "LSB_QUEUE",        "unknown");
      userT["submit_host"] = safe_get(envT,  "LSB_EXEC_CLUSTER", "unknown");
      userT["account"]     = "unknown";
    }
  else
    {
      userT["num_cores"]   = "1";
      userT["num_nodes"]   = "1";
      userT["job_id"]      = "unknown";
      userT["queue"]       = "unknown";
      userT["submit_host"] = "unknown";
      userT["account"]     = "unknown";
    }
}
Example #3
0
void print_system_meminfo()
{
  // We can't use sysinfo() here because iit doesn't tell us how much cached
  // memory we're using.  (On B2G, this is often upwards of 30mb.)
  //
  // Instead, we have to parse /proc/meminfo.

  FILE* meminfo = fopen("/proc/meminfo", "r");
  if (!meminfo) {
    perror("Couldn't open /proc/meminfo");
    return;
  }

  // These are all in kb.
  int total = -1;
  int free = -1;
  int buffers = -1;
  int cached = -1;
  int swap_total = -1;
  int swap_free = -1;
  int swap_cached = -1;

  char line[256];
  while(fgets(line, sizeof(line), meminfo)) {
    int val;
    if (sscanf(line, "MemTotal: %d kB", &val) == 1) {
        total = val;
    } else if (sscanf(line, "MemFree: %d kB", &val) == 1) {
        free = val;
    } else if (sscanf(line, "Buffers: %d kB", &val) == 1) {
        buffers = val;
    } else if (sscanf(line, "Cached: %d kB", &val) == 1) {
        cached = val;
    } else if (sscanf(line, "SwapTotal: %d kB", &val) == 1) {
        swap_total = val;
    } else if (sscanf(line, "SwapFree: %d kB", &val) == 1) {
        swap_free = val;
    } else if (sscanf(line, "SwapCached: %d kB", &val) == 1) {
        swap_cached = val;
    }
  }

  fclose(meminfo);

  if (total == -1 || free == -1 || buffers == -1 || cached == -1 ||
      swap_total == -1 || swap_free == -1 || swap_cached == -1) {
    fprintf(stderr, "Unable to parse /proc/meminfo.\n");
    return;
  }

  int actually_used = total - free - buffers - cached - swap_cached;

  puts("System memory info:\n");

  Table t;

  t.start_row();
  t.add("Total");
  t.add_fmt("%0.1f MB", kb_to_mb(total));

  t.start_row();
  t.add("SwapTotal");
  t.add_fmt("%0.1f MB", kb_to_mb(swap_total));

  t.start_row();
  t.add("Used - cache");
  t.add_fmt("%0.1f MB", kb_to_mb(total - free - buffers - cached - swap_cached));

  t.start_row();
  t.add("B2G procs (PSS)");

  int b2g_mem_kb = 0;
  for (vector<Process*>::const_iterator it = ProcessList::singleton().b2g_processes().begin();
       it != ProcessList::singleton().b2g_processes().end(); ++it) {
    b2g_mem_kb += (*it)->pss_kb();
  }
  t.add_fmt("%0.1f MB", b2g_mem_kb / 1024.0);

  t.start_row();
  t.add("Non-B2G procs");
  t.add_fmt("%0.1f MB", kb_to_mb(total - free - buffers - cached - b2g_mem_kb - swap_cached));

  t.start_row();
  t.add("Free + cache");
  t.add_fmt("%0.1f MB", kb_to_mb(free + buffers + cached + swap_cached));

  t.start_row();
  t.add("Free");
  t.add_fmt("%0.1f MB", kb_to_mb(free));

  t.start_row();
  t.add("Cache");
  t.add_fmt("%0.1f MB", kb_to_mb(buffers + cached + swap_cached));

  t.start_row();
  t.add("SwapFree");
  t.add_fmt("%0.1f MB", kb_to_mb(swap_free));

  t.print_with_indent(2);
}
void MeshAlg::weldBoundaryEdges(
    Array<Face>&       faceArray,
    Array<Edge>&       edgeArray,
    Array<Vertex>&     vertexArray) {

    // Copy over the original edge array
    Array<Edge> oldEdgeArray = edgeArray;

    // newEdgeIndex[e] is the new index of the old edge with index e
    // Note that newEdgeIndex[e] might be negative, indicating that
    // the edge switched direction between the arrays.
    Array<int> newEdgeIndex;
    newEdgeIndex.resize(edgeArray.size());
    edgeArray.resize(0);

    // boundaryEdgeIndices[v_low] is an array of the indices of 
    // all boundary edges whose lower vertex is v_low.
    Table<int, Array<int> > boundaryEdgeIndices;

    // Copy over non-boundary edges to the new array
    for (int e = 0; e < oldEdgeArray.size(); ++e) {
        if (oldEdgeArray[e].boundary()) {

            // Add to the boundary table
            const int v_low = iMin(oldEdgeArray[e].vertexIndex[0], oldEdgeArray[e].vertexIndex[1]);
            if (! boundaryEdgeIndices.containsKey(v_low)) {
                boundaryEdgeIndices.set(v_low, Array<int>());
            }
            boundaryEdgeIndices[v_low].append(e);

            // We'll fill out newEdgeIndex[e] later, when we find pairs

        } else {

            // Copy the edge to the new array
            newEdgeIndex[e] = edgeArray.size();
            edgeArray.append(oldEdgeArray[e]);

        }
    }


    // Remove all edges from the table that have pairs.
    Table<int, Array<int> >::Iterator cur = boundaryEdgeIndices.begin();
    Table<int, Array<int> >::Iterator end = boundaryEdgeIndices.end();
    while (cur != end) {
        Array<int>&     boundaryEdge = cur->value;

        for (int i = 0; i < boundaryEdge.size(); ++i) {
            int ei = boundaryEdge[i];
            const Edge& edgei = oldEdgeArray[ei];

            for (int j = i + 1; j < boundaryEdge.size(); ++j) {
                int ej = boundaryEdge[j];
                const Edge& edgej = oldEdgeArray[ej];

                // See if edge ei is the reverse (match) of edge ej.

                // True if the edges match
                bool match = false;

                // True if edgej's vertex indices are reversed from
                // edgei's (usually true).
                bool reversej = false;
                
                int u = edgei.vertexIndex[0];
                int v = edgei.vertexIndex[1];

                if (edgei.faceIndex[0] != Face::NONE) {
                    //        verts|faces
                    // edgei = [u v A /]

                    if (edgej.faceIndex[0] != Face::NONE) {
                        if ((edgej.vertexIndex[0] == v) && (edgej.vertexIndex[1] == u)) {
                            // This is the most common of the four cases

                            // edgej = [v u B /]
                            match = true;
                            reversej = true;
                        }
                    } else {
                        if ((edgej.vertexIndex[0] == u) && (edgej.vertexIndex[1] == v)) {
                            // edgej = [u v / B]
                            match = true;
                        }
                    }
                } else {
                    // edgei = [u v / A]
                    if (edgej.faceIndex[0] != Face::NONE) {
                        if ((edgej.vertexIndex[0] == u) && (edgej.vertexIndex[1] == v)) {
                            // edgej = [u v B /]
                            match = true;
                        }
                    } else {
                        if ((edgej.vertexIndex[0] == v) && (edgej.vertexIndex[1] == u)) {
                            // edgej = [v u / B]
                            match = true;
                            reversej = true;
                        }
                    }
                }

                if (match) {
                    // ei and ej can be paired as a single edge
                    int e = edgeArray.size();
                    Edge& edge = edgeArray.next();

                    // Follow the direction of edgei.
                    edge = edgei;
                    newEdgeIndex[ei] = e;

                    // Insert the face index for edgej.
                    int fj = edgej.faceIndex[0];
                    if (fj == Face::NONE) {
                        fj = edgej.faceIndex[1];
                    }
                    
                    if (edge.faceIndex[0] == Face::NONE) {
                        edge.faceIndex[0] = fj;
                    } else {
                        edge.faceIndex[1] = fj;
                    }
                    
                    if (reversej) {
                        // The new edge is backwards of the old edge for ej
                        newEdgeIndex[ej] = ~e;
                    } else {
                        newEdgeIndex[ej] = e;
                    }

                    // Remove both ei and ej from being candidates for future pairing.
                    // Remove ej first since it comes later in the list (removing
                    // ei would decrease the index of ej to j - 1).
                    boundaryEdge.fastRemove(j);
                    boundaryEdge.fastRemove(i);

                    // Re-process element i, which is now a new edge index
                    --i;

                    // Jump out of the j for-loop
                    break;
                }
            }
        }
        ++cur;
    }

    // Anything remaining in the table is a real boundary edge; just copy it to
    // the end of the array.
    cur = boundaryEdgeIndices.begin();
    end = boundaryEdgeIndices.end();
    while (cur != end) {
        Array<int>&     boundaryEdge = cur->value;

        for (int b = 0; b < boundaryEdge.size(); ++b) {
            const int e = boundaryEdge[b];

            newEdgeIndex[e] = edgeArray.size();
            edgeArray.append(oldEdgeArray[e]);
        }

        ++cur;
    }

    // Finally, fix up edge indices in the face and vertex arrays
    for (int f = 0; f < faceArray.size(); ++f) {
        Face& face = faceArray[f];
        for (int i = 0; i < 3; ++i) {
            int e = face.edgeIndex[i];

            if (e < 0) {
                face.edgeIndex[i] = ~newEdgeIndex[~e];
            } else {
                face.edgeIndex[i] = newEdgeIndex[e];
            }
        }
    }

    for (int v = 0; v < vertexArray.size(); ++v) {
        Vertex& vertex = vertexArray[v];
        for (int i = 0; i < vertex.edgeIndex.size(); ++i) {
            int e = vertex.edgeIndex[i];

            if (e < 0) {
                vertex.edgeIndex[i] = ~newEdgeIndex[~e];
            } else {
                vertex.edgeIndex[i] = newEdgeIndex[e];
            }
        }
    }
}
Example #5
0
	Table( const Table& t){	//Copy constructor
		for(int i=0; i< t.size(); i++){
			Data.push_back(t.getRow(i));
		}
		recalc();
	}
Example #6
0
void MaskSprite::deserialize(const Table& table)
{
    Sprite::deserialize(table);
    setAlphaMask( table.getFloat("alphaMask", getAlphaMask()) );
}
Example #7
0
void MaskBox::deserialize(const Table& table)
{
    box.set(table.getVector2D("center", box.getCenter()),
            table.getVector2D("size", box.getSize()),
            Angle::degree(table.getFloat("angle", box.getAngle().valueDegrees())));
}
void TestTable::parseSQL()
{
    QString sSQL = "create TABLE hero (\n"
            "\tid integer PRIMARY KEY AUTOINCREMENT,\n"
            "\tname text NOT NULL DEFAULT 'xxxx',\n"
            "\tinfo VARCHAR(255) CHECK (info == 'x')\n"
            ");";

    Table tab = Table::parseSQL(sSQL).first;

    QVERIFY(tab.name() == "hero");
    QVERIFY(tab.rowidColumn() == "_rowid_");
    QVERIFY(tab.fields().at(0)->name() == "id");
    QVERIFY(tab.fields().at(1)->name() == "name");
    QVERIFY(tab.fields().at(2)->name() == "info");

    QVERIFY(tab.fields().at(0)->type() == "integer");
    QVERIFY(tab.fields().at(1)->type() == "text");
    QCOMPARE(tab.fields().at(2)->type(), QString("VARCHAR ( 255 )"));

    FieldVector pk = tab.primaryKey();
    QVERIFY(tab.fields().at(0)->autoIncrement());
    QVERIFY(pk.size() == 1 && pk.at(0) == tab.fields().at(0));
    QVERIFY(tab.fields().at(1)->notnull());
    QCOMPARE(tab.fields().at(1)->defaultValue(), QString("'xxxx'"));
    QCOMPARE(tab.fields().at(1)->check(), QString(""));
    QCOMPARE(tab.fields().at(2)->check(), QString("info == 'x'"));
}
void TestTable::parseSQLdefaultexpr()
{
    QString sSQL = "CREATE TABLE chtest(\n"
            "id integer primary key,\n"
            "dumpytext text default('axa') CHECK(dumpytext == \"aa\"),\n"
            "date datetime default CURRENT_TIMESTAMP,"
            "zoi integer)";

    Table tab = Table::parseSQL(sSQL).first;

    QCOMPARE(tab.name(), QString("chtest"));
    QCOMPARE(tab.fields().at(0)->name(), QString("id"));
    QCOMPARE(tab.fields().at(1)->name(), QString("dumpytext"));
    QCOMPARE(tab.fields().at(2)->name(), QString("date"));
    QCOMPARE(tab.fields().at(3)->name(), QString("zoi"));

    QCOMPARE(tab.fields().at(0)->type(), QString("integer"));
    QCOMPARE(tab.fields().at(1)->type(), QString("text"));
    QCOMPARE(tab.fields().at(2)->type(), QString("datetime"));
    QCOMPARE(tab.fields().at(3)->type(), QString("integer"));

    QCOMPARE(tab.fields().at(1)->defaultValue(), QString("('axa')"));
    QCOMPARE(tab.fields().at(1)->check(), QString("dumpytext == \"aa\""));
    QCOMPARE(tab.fields().at(2)->defaultValue(), QString("CURRENT_TIMESTAMP"));
    QCOMPARE(tab.fields().at(2)->check(), QString(""));
    QCOMPARE(tab.fields().at(3)->defaultValue(), QString(""));
    QCOMPARE(tab.fields().at(3)->check(), QString(""));

    sqlb::FieldVector pk = tab.primaryKey();
    QVERIFY(pk.size() == 1 && pk.at(0) == tab.fields().at(0));
}
Example #10
0
void Table::addObject(BaseObject *obj, int obj_idx)
{
	ObjectType obj_type;

	if(!obj)
		throw Exception(ERR_ASG_NOT_ALOC_OBJECT,__PRETTY_FUNCTION__,__FILE__,__LINE__);
	else
	{
		int idx;
		obj_type=obj->getObjectType();

		#ifdef DEMO_VERSION
			#warning "DEMO VERSION: table children objects creation limit."
      vector<TableObject *> *obj_list=(obj_type!=OBJ_TABLE ? getObjectList(obj_type) : nullptr);

      if((obj_list && obj_list->size() >= GlobalAttributes::MAX_OBJECT_COUNT) ||
         (obj_type==OBJ_TABLE && ancestor_tables.size() >= GlobalAttributes::MAX_OBJECT_COUNT))
       throw Exception(trUtf8("In demonstration version tables can have only `%1' instances of each child object type or ancestor tables! You've reach this limit for the type: `%2'")
											 .arg(GlobalAttributes::MAX_OBJECT_COUNT)
											 .arg(BaseObject::getTypeName(obj_type)),
											 ERR_CUSTOM,__PRETTY_FUNCTION__,__FILE__,__LINE__);

		#endif

		try
		{
			//Raises an error if already exists a object with the same name and type
			if(getObject(obj->getName(),obj_type,idx))
			{
				throw Exception(QString(Exception::getErrorMessage(ERR_ASG_DUPLIC_OBJECT))
												.arg(obj->getName(true))
												.arg(obj->getTypeName())
												.arg(this->getName(true))
												.arg(this->getTypeName()),
												ERR_ASG_DUPLIC_OBJECT,__PRETTY_FUNCTION__,__FILE__,__LINE__);
			}

			//Raises an error if the user try to set the table as ancestor/copy of itself
			else if((obj_type==OBJ_TABLE || obj_type==BASE_TABLE) && obj==this)
				throw Exception(ERR_INV_INH_COPY_RELATIONSHIP,__PRETTY_FUNCTION__,__FILE__,__LINE__);

			switch(obj_type)
			{
				case OBJ_COLUMN:
				case OBJ_CONSTRAINT:
				case OBJ_TRIGGER:
				case OBJ_INDEX:
				case OBJ_RULE:
					TableObject *tab_obj;
					vector<TableObject *> *obj_list;
					Column *col;

					tab_obj=dynamic_cast<TableObject *>(obj);
					col=dynamic_cast<Column *>(tab_obj);

					//Sets the object parent table if there isn't one
					if(!tab_obj->getParentTable())
						tab_obj->setParentTable(this);
					//Raises an error if the parent table of the table object is different from table 'this'
					else if(tab_obj->getParentTable()!=this)
						throw Exception(ERR_ASG_OBJ_BELONGS_OTHER_TABLE,__PRETTY_FUNCTION__,__FILE__,__LINE__);

					//Validates the object SQL code befor insert on table
					obj->getCodeDefinition(SchemaParser::SQL_DEFINITION);

					if(col && col->getType()==this)
					{
						throw Exception(Exception::getErrorMessage(ERR_INV_COLUMN_TABLE_TYPE)
                            .arg(col->getName())
                            .arg(this->getName()),
														ERR_INV_COLUMN_TABLE_TYPE,__PRETTY_FUNCTION__,__FILE__,__LINE__);
					}
					else if(obj_type==OBJ_CONSTRAINT)
					{
						//Raises a error if the user try to add a second primary key on the table
						if(dynamic_cast<Constraint *>(tab_obj)->getConstraintType()==ConstraintType::primary_key &&
							 this->getPrimaryKey())
							throw Exception(ERR_ASG_EXISTING_PK_TABLE,__PRETTY_FUNCTION__,__FILE__,__LINE__);
					}
					else if(obj_type==OBJ_TRIGGER)
						dynamic_cast<Trigger *>(tab_obj)->validateTrigger();

					obj_list=getObjectList(obj_type);

					//Adds the object to the table
					if(obj_idx < 0 || obj_idx >= static_cast<int>(obj_list->size()))
						obj_list->push_back(tab_obj);
					else
					{
						//If there is a object index specified inserts the object at the position
						if(obj_list->size() > 0)
							obj_list->insert((obj_list->begin() + obj_idx), tab_obj);
						else
							obj_list->push_back(tab_obj);
					}

					if(obj_type==OBJ_COLUMN || obj_type==OBJ_CONSTRAINT)
          {
						updateAlterCmdsStatus();

            if(obj_type==OBJ_CONSTRAINT)
              dynamic_cast<Constraint *>(tab_obj)->setColumnsNotNull(true);
          }
				break;

				case OBJ_TABLE:
					Table *tab;
					tab=dynamic_cast<Table *>(obj);
					if(obj_idx < 0 || obj_idx >= static_cast<int>(ancestor_tables.size()))
						ancestor_tables.push_back(tab);
					else
						ancestor_tables.insert((ancestor_tables.begin() + obj_idx), tab);

          /* Updating the storage parameter WITH OIDS depending on the ancestors.
             According to the docs, the child table will inherit WITH OID status from the parents */
          with_oid=(with_oid || tab->isWithOIDs());
				break;

				default:
					throw Exception(ERR_ASG_OBJECT_INV_TYPE,__PRETTY_FUNCTION__,__FILE__,__LINE__);
				break;
			}

			setCodeInvalidated(true);
		}
		catch(Exception &e)
		{
			if(e.getErrorType()==ERR_UNDEF_ATTRIB_VALUE)
				throw Exception(Exception::getErrorMessage(ERR_ASG_OBJ_INV_DEFINITION)
                        .arg(obj->getName())
												.arg(obj->getTypeName()),
												ERR_ASG_OBJ_INV_DEFINITION,__PRETTY_FUNCTION__,__FILE__,__LINE__, &e);
			else
				throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e);
		}
	}
}
Example #11
0
typename Table::size_type bucket_count () const {return table.size();}
Example #12
0
bool InsertExecutor::p_init(AbstractPlanNode* abstractNode,
                            const ExecutorVector& executorVector)
{
    VOLT_TRACE("init Insert Executor");

    m_node = dynamic_cast<InsertPlanNode*>(abstractNode);
    assert(m_node);
    assert(m_node->getTargetTable());
    assert(m_node->getInputTableCount() == (m_node->isInline() ? 0 : 1));

    Table* targetTable = m_node->getTargetTable();
    m_isUpsert = m_node->isUpsert();

    //
    // The insert node's input schema is fixed.  But
    // if this is an inline node we don't set it here.
    // We let the parent node set it in p_execute_init.
    //
    // Also, we don't want to set the input table for inline
    // insert nodes.
    //
    if ( ! m_node->isInline()) {
        setDMLCountOutputTable(executorVector.limits());
        m_inputTable = dynamic_cast<AbstractTempTable*>(m_node->getInputTable()); //input table should be temptable
        assert(m_inputTable);
    } else {
        m_inputTable = NULL;
    }

    // Target table can be StreamedTable or PersistentTable and must not be NULL
    PersistentTable *persistentTarget = dynamic_cast<PersistentTable*>(targetTable);
    m_partitionColumn = -1;
    StreamedTable *streamTarget = dynamic_cast<StreamedTable*>(targetTable);
    m_hasStreamView = false;
    if (streamTarget != NULL) {
        m_isStreamed = true;
        //See if we have any views.
        m_hasStreamView = streamTarget->hasViews();
        m_partitionColumn = streamTarget->partitionColumn();
    }
    if (m_isUpsert) {
        VOLT_TRACE("init Upsert Executor actually");
        assert( ! m_node->isInline() );
        if (m_isStreamed) {
            VOLT_ERROR("UPSERT is not supported for Stream table %s", targetTable->name().c_str());
        }
        // look up the tuple whether it exists already
        if (persistentTarget->primaryKeyIndex() == NULL) {
            VOLT_ERROR("No primary keys were found in our target table '%s'",
                    targetTable->name().c_str());
        }
    }

    if (persistentTarget) {
        m_partitionColumn = persistentTarget->partitionColumn();
    }

    m_multiPartition = m_node->isMultiPartition();

    m_sourceIsPartitioned = m_node->sourceIsPartitioned();

    // allocate memory for template tuple, set defaults for all columns
    m_templateTupleStorage.init(targetTable->schema());


    TableTuple tuple = m_templateTupleStorage.tuple();

    std::set<int> fieldsExplicitlySet(m_node->getFieldMap().begin(), m_node->getFieldMap().end());
    // These default values are used for an INSERT including the INSERT sub-case of an UPSERT.
    // The defaults are purposely ignored in favor of existing column values
    // for the UPDATE subcase of an UPSERT.
    m_node->initTupleWithDefaultValues(m_engine,
                                       &m_memoryPool,
                                       fieldsExplicitlySet,
                                       tuple,
                                       m_nowFields);
    m_hasPurgeFragment = persistentTarget ? persistentTarget->hasPurgeFragment() : false;

    return true;
}
Example #13
0
std::string System::findDataFile
(const std::string&  full,
 bool                errorIfNotFound) {

    // Places where specific files were most recently found.  This is
    // used to cache seeking of common files.
    static Table<std::string, std::string> lastFound;

    // First check if the file exists as requested.  This will go
    // through the FileSystemCache, so most calls do not touch disk.
    if (fileExists(full)) {
        return full;
    }

    // Now check where we previously found this file.
    std::string* last = lastFound.getPointer(full);
    if (last != NULL) {
        if (fileExists(*last)) {
            // Even if cwd has changed the file is still present.
            // We won't notice if it has been deleted, however.
            return *last;
        } else {
            // Remove this from the cache it is invalid
            lastFound.remove(full);
        }
    }

    // Places to look
    static Array<std::string> directoryArray;

    if (directoryArray.size() == 0) {
        // Initialize the directory array
        RealTime t0 = System::time();

        Array<std::string> baseDirArray;

        std::string initialAppDataDir(instance().m_appDataDir);
        
        baseDirArray.append("");
        if (! initialAppDataDir.empty()) {
            baseDirArray.append(initialAppDataDir);
        }

        const char* g3dPath = getenv("G3DDATA");

        if (g3dPath && (initialAppDataDir != g3dPath)) {
            baseDirArray.append(g3dPath);
        }

        static const std::string subdirs[] = 
            {"font", "gui", "SuperShader", "cubemap", "icon", "material", "image", "md2", "md3", "ifs", "3ds", "sky", ""};
        for (int j = 0; j < baseDirArray.size(); ++j) {
            std::string d = baseDirArray[j];
            if (fileExists(d)) {
                directoryArray.append(d);
                for (int i = 0; ! subdirs[i].empty(); ++i) {
                    const std::string& p = pathConcat(d, subdirs[i]);
                    if (fileExists(p)) {
                        directoryArray.append(p);
                    }
                }
            }
        }

        logLazyPrintf("Initializing System::findDataFile took %fs\n", System::time() - t0);
    }

    for (int i = 0; i < directoryArray.size(); ++i) {
        const std::string& p = pathConcat(directoryArray[i], full);
        if (fileExists(p)) {
            lastFound.set(full, p);
            return p;
        }
    }

    if (errorIfNotFound) {
        // Generate an error message
        std::string locations;
        for (int i = 0; i < directoryArray.size(); ++i) {
            locations += pathConcat(directoryArray[i], full) + "\n";
        }
        alwaysAssertM(false, "Could not find '" + full + "' in:\n" + locations);
    }

    // Not found
    return "";
}
Example #14
0
int main()
{

    Connection conn;
    DbRetVal rv = conn.open("root", "manager");
    if (rv != OK)
    {
       printf("Error during connection %d\n", rv);
       return 1;
    }
    DatabaseManager *dbMgr = conn.getDatabaseManager();
    if (dbMgr == NULL) { printf("Auth failed\n"); return 2;}
    TableDef tabDef;
    tabDef.addField("f1", typeInt, 0, NULL, true);
    tabDef.addField("f2", typeString, 196);
    rv = dbMgr->createTable("t1", tabDef);
    if (rv != OK) { printf("Table creation failed\n"); return 3; }
    printf("Table created\n");
#ifdef WITHINDEX
    HashIndexInitInfo *idxInfo = new HashIndexInitInfo();
    strcpy(idxInfo->tableName, "t1");
    idxInfo->list.append("f1");
    idxInfo->indType = hashIndex;
    idxInfo->isUnique = true;
    idxInfo->isPrimary = true;
    rv = dbMgr->createIndex("indx1", idxInfo);
    if (rv != OK) { printf("Index creation failed\n"); return -1; }
    printf("Index created\n");
    delete idxInfo;
#endif
#ifdef WITHTREEINDEX
    HashIndexInitInfo *idxInfo = new HashIndexInitInfo();
    strcpy(idxInfo->tableName, "t1");
    idxInfo->list.append("f1");
    idxInfo->indType = treeIndex;
    rv = dbMgr->createIndex("indx1", idxInfo);
    if (rv != OK) { printf("Index creation failed\n"); return -1; }
    printf("Index created\n");
    delete idxInfo;
#endif
#ifdef WITHTRIEINDEX
    HashIndexInitInfo *idxInfo = new HashIndexInitInfo();
    strcpy(idxInfo->tableName, "t1");
    idxInfo->list.append("f1");
    idxInfo->indType = trieIndex;
    rv = dbMgr->createIndex("indx1", idxInfo);
    if (rv != OK) { printf("Index creation failed\n"); return -1; }
    printf("Index created\n");
    delete idxInfo;
#endif

    Table *table = dbMgr->openTable("t1");
    if (table == NULL) { printf("Unable to open table\n"); return 4; }
    table->bindFld("f1", &id);
    table->bindFld("f2", name);
    char *tuple;
    int ret;
    int i;
    rv =conn.startTransaction();
    for(i = 0; i< 5; i++)
    {
        if (rv != OK) exit(5);
        id= i;
        strcpy(name, "PRABAKARAN0123456750590");
        ret = table->insertTuple();
        if (ret != 0) break;
    }
    conn.commit();

    conn.startTransaction();
    select(table, OpEquals);
    conn.commit();

    conn.startTransaction();
    select(table, OpNotEquals);
    conn.commit();

    conn.startTransaction();
    select(table, OpLessThan);
    conn.commit();

    conn.startTransaction();
    select( table, OpLessThanEquals);
    conn.commit();

    conn.startTransaction();
    select( table, OpGreaterThan);
    conn.commit();

    conn.startTransaction();
    select( table, OpGreaterThanEquals);
    conn.commit();

    dbMgr->closeTable(table);
    dbMgr->dropTable("t1");

    conn.close();
    return 0;
}
Example #15
0
void assert_field_type(Table &td, int field_index,
    ActiveRecord::Type::Type type) {
  ASSERT_EQ(type, td.fields()[field_index].type());
}
Example #16
0
void LineProfileTool::calculateLineProfile(const QPoint& start, const QPoint& end)
{
	QRect rect = d_target->rect();
	if (!rect.contains(start) || !rect.contains(end)){
		QMessageBox::warning(d_graph, tr("MantidPlot - Pixel selection warning"),
				tr("Please select the end line point inside the image rectangle!"));
		return;
	}

	QPoint o = d_target->origin();
	QPixmap pic = d_target->pixmap();
	QImage image = pic.convertToImage();

	int x1 = start.x()-o.x();
	int x2 = end.x()-o.x();
	int y1 = start.y()-o.y();
	int y2 = end.y()-o.y();

	QSize realSize = pic.size();
	QSize actualSize = d_target->size();

	if (realSize != actualSize){
		double ratioX = (double)realSize.width()/(double)actualSize.width();
		double ratioY = (double)realSize.height()/(double)actualSize.height();
		x1 = static_cast<int>(x1*ratioX);
		x2 = static_cast<int>(x2*ratioX);
		y1 = static_cast<int>(y1*ratioY);
		y2 = static_cast<int>(y2*ratioY);
	}

	QString text = tr("pixel") + "\tx\ty\t" + tr("intensity") + "\n";

	//uses the fast Bresenham's line-drawing algorithm
#define sgn(x) ((x<0)?-1:((x>0)?1:0))
	int i,dx,dy,sdx,sdy,dxabs,dyabs,x,y,px,py,n = 0;

	dx=x2-x1;      //the horizontal distance of the line
	dy=y2-y1;      //the vertical distance of the line
	dxabs=abs(dx);
	dyabs=abs(dy);
	sdx=sgn(dx);
	sdy=sgn(dy);
	x=dyabs>>1;
	y=dxabs>>1;
	px=x1;
	py=y1;

	if (dxabs>=dyabs){ //the line is more horizontal than vertical
		for(i=0;i<dxabs;i++){
			y+=dyabs;
			if (y>=dxabs){
				y-=dxabs;
				py+=sdy;
			}
			px+=sdx;

			n=dxabs;
			text+=QString::number(i)+"\t";
			text+=QString::number(px)+"\t";
			text+=QString::number(py)+"\t";
			text+=QString::number(averageImagePixel(image, px, py, true))+"\n";
		}
	} else {// the line is more vertical than horizontal
		for(i=0;i<dyabs;i++){
			x+=dxabs;
			if (x>=dyabs){
				x-=dyabs;
				px+=sdx;
			}
			py+=sdy;

			n=dyabs;
			text+=QString::number(i)+"\t";
			text+=QString::number(px)+"\t";
			text+=QString::number(py)+"\t";
			text+=QString::number(averageImagePixel(image, px, py, false))+"\n";
		}
	}

	Table *t = d_app->newTable(tr("Table") + "1", n, 4, text);
	MultiLayer* plot = d_app->multilayerPlot(t, QStringList(QString(t->objectName())+"_intensity"), 0);
  Graph *g = dynamic_cast<Graph*>(plot->activeGraph());
	if (g){
		g->setTitle("");
		g->setXAxisTitle(tr("pixels"));
		g->setYAxisTitle(tr("pixel intensity (a.u.)"));
	}

}
Example #17
0
void MaskSprite::serialize(Table& table)
{
    Sprite::serialize(table);
    table.set("alphaMask", getAlphaMask());
}
Example #18
0
/*****************************************************
**
**   HoraExpert   ---   write
**
******************************************************/
void HoraExpert::write( Sheet *sheet, const bool isLocaltime )
{
	TzUtil tzu;
	wxString s;
	TzFormattedDate fd;
	Lang lang;
	SheetFormatter fmt;

	double corr = ( location->getTimeZone() + location->getDST()) / 24;

	Table *table = new Table( 7, 13 );
	if ( config->view->showTextViewHeaders ) table->setHeader( _( "Hora" ));

	table->setHeader( 0,  _( "Begin" ));
	table->setHeader( 1,  _( "Lord" ));
	table->setHeader( 2,  _( "End" ));
	//table->setHeader( 3,  wxEmptyString );
	table->setHeader( 4,  _( "Begin" ));
	table->setHeader( 5,  _( "Lord" ));
	table->setHeader( 6,  _( "End" ));
	int line = 1;
	int colskip = 0;
	for ( int i = 0; i < 24; i++ )
	{
		if ( i == 12 )
		{
			colskip = 4;
			line = 1;
		}

		table->setEntry( 3, line, wxEmptyString );
		fd = tzu.getDateFormatted( horaStart[i] + corr, isLocaltime );
		table->setEntry( colskip, line, fd.timeFormatted );

		table->setEntry( 1+colskip, line, fmt.getObjectName( horaLord[i], TF_LONG ));

		fd = tzu.getDateFormatted( horaStart[i+1] + corr, isLocaltime );
		table->setEntry( 2+colskip, line, fd.timeFormatted );
		line++;
	}
	sheet->addItem( table );

	sheet->addLine( wxString::Format( wxT( "%s: %s" ), _( "Lord of the day" ),
		lang.getObjectName( getDinaLord(), TF_LONG ).c_str()));
	sheet->addLine( wxString::Format( wxT( "%s: %s" ), _( "Lord of the month" ),
		lang.getObjectName( getMasaLord(), TF_LONG ).c_str()));
	sheet->addLine( wxString::Format( wxT( "%s: %s" ), _( "Lord of the year" ),
		lang.getObjectName( getVarshaLord(), TF_LONG ).c_str() ));
}
Example #19
0
void MaskBox::serialize(Table& table)
{
    table.set("center", box.getCenter());
    table.set("size", box.getSize());
    table.set("angle", box.getAngle().valueDegrees());
}
Example #20
0
bool InsertExecutor::p_execute(const NValueArray &params) {
    assert(m_node == dynamic_cast<InsertPlanNode*>(m_abstractNode));
    assert(m_node);
    assert(m_inputTable == dynamic_cast<TempTable*>(m_node->getInputTable()));
    assert(m_inputTable);

    // Target table can be StreamedTable or PersistentTable and must not be NULL
    // Update target table reference from table delegate
    Table* targetTable = m_node->getTargetTable();
    assert(targetTable);
    assert((targetTable == dynamic_cast<PersistentTable*>(targetTable)) ||
            (targetTable == dynamic_cast<StreamedTable*>(targetTable)));

    PersistentTable* persistentTable = m_isStreamed ?
        NULL : static_cast<PersistentTable*>(targetTable);
    TableTuple upsertTuple = TableTuple(targetTable->schema());

    VOLT_TRACE("INPUT TABLE: %s\n", m_inputTable->debug().c_str());

    // count the number of successful inserts
    int modifiedTuples = 0;

    Table* outputTable = m_node->getOutputTable();
    assert(outputTable);

    TableTuple templateTuple = m_templateTuple.tuple();

    std::vector<int>::iterator it;
    for (it = m_nowFields.begin(); it != m_nowFields.end(); ++it) {
        templateTuple.setNValue(*it, NValue::callConstant<FUNC_CURRENT_TIMESTAMP>());
    }

    VOLT_DEBUG("This is a %s-row insert on partition with id %d",
               m_node->getChildren()[0]->getPlanNodeType() == PLAN_NODE_TYPE_MATERIALIZE ?
               "single" : "multi", m_engine->getPartitionId());
    VOLT_DEBUG("Offset of partition column is %d", m_partitionColumn);

    //
    // An insert is quite simple really. We just loop through our m_inputTable
    // and insert any tuple that we find into our targetTable. It doesn't get any easier than that!
    //
    TableTuple inputTuple(m_inputTable->schema());
    assert (inputTuple.sizeInValues() == m_inputTable->columnCount());
    TableIterator iterator = m_inputTable->iterator();
    while (iterator.next(inputTuple)) {

        for (int i = 0; i < m_node->getFieldMap().size(); ++i) {
            // Most executors will just call setNValue instead of
            // setNValueAllocateForObjectCopies.
            //
            // However, We need to call
            // setNValueAlocateForObjectCopies here.  Sometimes the
            // input table's schema has an inlined string field, and
            // it's being assigned to the target table's outlined
            // string field.  In this case we need to tell the NValue
            // where to allocate the string data.
            templateTuple.setNValueAllocateForObjectCopies(m_node->getFieldMap()[i],
                                                           inputTuple.getNValue(i),
                                                           ExecutorContext::getTempStringPool());
        }

        VOLT_TRACE("Inserting tuple '%s' into target table '%s' with table schema: %s",
                   templateTuple.debug(targetTable->name()).c_str(), targetTable->name().c_str(),
                   targetTable->schema()->debug().c_str());

        // if there is a partition column for the target table
        if (m_partitionColumn != -1) {

            // get the value for the partition column
            NValue value = templateTuple.getNValue(m_partitionColumn);
            bool isLocal = m_engine->isLocalSite(value);

            // if it doesn't map to this site
            if (!isLocal) {
                if (!m_multiPartition) {
                    throw ConstraintFailureException(
                            dynamic_cast<PersistentTable*>(targetTable),
                            templateTuple,
                            "Mispartitioned tuple in single-partition insert statement.");
                }

                // don't insert
                continue;
            }
        }

        // for multi partition export tables, only insert into one
        // place (the partition with hash(0)), if the data is from a
        // replicated source.  If the data is coming from a subquery
        // with partitioned tables, we need to perform the insert on
        // every partition.
        if (m_isStreamed && m_multiPartition && !m_sourceIsPartitioned) {
            bool isLocal = m_engine->isLocalSite(ValueFactory::getBigIntValue(0));
            if (!isLocal) continue;
        }


        if (! m_isUpsert) {
            // try to put the tuple into the target table

            if (m_hasPurgeFragment) {
                if (!executePurgeFragmentIfNeeded(&persistentTable))
                    return false;
                // purge fragment might have truncated the table, and
                // refreshed the persistent table pointer.  Make sure to
                // use it when doing the insert below.
                targetTable = persistentTable;
            }

            if (!targetTable->insertTuple(templateTuple)) {
                VOLT_ERROR("Failed to insert tuple from input table '%s' into"
                           " target table '%s'",
                           m_inputTable->name().c_str(),
                           targetTable->name().c_str());
                return false;
            }

        } else {
            // upsert execution logic
            assert(persistentTable->primaryKeyIndex() != NULL);
            TableTuple existsTuple = persistentTable->lookupTupleByValues(templateTuple);

            if (existsTuple.isNullTuple()) {
                // try to put the tuple into the target table

                if (m_hasPurgeFragment) {
                    if (!executePurgeFragmentIfNeeded(&persistentTable))
                        return false;
                }

                if (!persistentTable->insertTuple(templateTuple)) {
                    VOLT_ERROR("Failed to insert tuple from input table '%s' into"
                               " target table '%s'",
                               m_inputTable->name().c_str(),
                               persistentTable->name().c_str());
                    return false;
                }
            } else {
                // tuple exists already, try to update the tuple instead
                upsertTuple.move(templateTuple.address());
                TableTuple &tempTuple = persistentTable->getTempTupleInlined(upsertTuple);

                if (!persistentTable->updateTupleWithSpecificIndexes(existsTuple, tempTuple,
                        persistentTable->allIndexes())) {
                    VOLT_INFO("Failed to update existsTuple from table '%s'",
                            persistentTable->name().c_str());
                    return false;
                }
            }
        }

        // successfully inserted or updated
        modifiedTuples++;
    }

    TableTuple& count_tuple = outputTable->tempTuple();
    count_tuple.setNValue(0, ValueFactory::getBigIntValue(modifiedTuples));
    // try to put the tuple into the output table
    if (!outputTable->insertTuple(count_tuple)) {
        VOLT_ERROR("Failed to insert tuple count (%d) into"
                   " output table '%s'",
                   modifiedTuples,
                   outputTable->name().c_str());
        return false;
    }

    // add to the planfragments count of modified tuples
    m_engine->addToTuplesModified(modifiedTuples);
    VOLT_DEBUG("Finished inserting %d tuples", modifiedTuples);
    return true;
}
Example #21
0
int main()
{

    Connection conn;
    DbRetVal rv = conn.open("root", "manager");
    if (rv != OK)
    {
       printf("Error during connection %d\n", rv);
       return -1;
    }


    DatabaseManager *dbMgr = conn.getDatabaseManager();
    if (dbMgr == NULL) { printf("Auth failed\n"); return -1;}
    TableDef tabDef;
    tabDef.addField("f1", typeInt, 0, NULL, true );
    tabDef.addField("f2", typeString, 196);
    rv = dbMgr->createTable("t1", tabDef);
    if (rv != OK) { printf("Table creation failed\n"); return -1; }
    printf("Table created\n");
    HashIndexInitInfo *idxInfo = new HashIndexInitInfo();
    strcpy(idxInfo->tableName, "t1");
    idxInfo->list.append("f1");
    idxInfo->indType = hashIndex;
    if (LOAD >0 )
       idxInfo->bucketSize = 100007;
    else
       idxInfo->bucketSize = 10007;
    rv = dbMgr->createIndex("indx1", idxInfo);
    if (rv != OK) { printf("Index creation failed\n"); return -1; }
    printf("Index created\n");
    delete idxInfo;
    Table *table = dbMgr->openTable("t1");
    if (table == NULL) { printf("Unable to open table\n"); return -1; }
    int id = 0;
    char name[196] = "PRABAKARAN";
    table->bindFld("f1", &id);
    table->bindFld("f2", name);
    char *tuple;
    int ret;
    int i;
    int icount =0;
    if (LOAD > 0) {
      TableImpl *impl = (TableImpl*)table;
      impl->setUndoLogging(false);
      strcpy(name, "PRABAKARAN0123456750590");
      rv = conn.startTransaction();
      if (rv != OK) exit(1);
      for(i = 0; i< LOAD; i++)
      {
        id= i;
        ret = table->insertTuple();
        if (ret != 0) break;
        icount++;
        if (i % 100 == 0 ) { rv = conn.commit(); 
                             if (rv != OK) exit(1);
                             rv = conn.startTransaction(); 
                             if (rv != OK) exit(1);
                           }
        if (i %50000 == 0) printf("%d rows inserted\n", i);
      }
      conn.commit();
      impl->setUndoLogging(true);
      printf("Loaded %d records\n", icount);
    }
   
      //TableImpl *impl = (TableImpl*)table;
      //impl->setUndoLogging(false);
    i = 0; 
    NanoTimer timer;
    icount =0;
    for(i = LOAD; i< LOAD+ITERATIONS; i++)
    {
        timer.start();
        rv = conn.startTransaction();
        if (rv != OK) exit(1);
        id= i;
        strcpy(name, "PRABAKARAN0123456750590");
        ret = table->insertTuple();
        if (ret != 0) break;
    //    printf("%d\n ", i);
        icount++;
        conn.commit();
        timer.stop();
    }
   printf("%d rows inserted %lld %lld %lld\n",icount, timer.minc(), timer.maxc(), timer.avg());

    int offset1= os::align(sizeof(int));
    Condition p1;
    int val1 = 0;
    p1.setTerm("f1", OpEquals, &val1);
    table->setCondition(&p1);
    icount=0;
   

    timer.reset();
    for(i = LOAD; i< LOAD+ITERATIONS; i++)
    {    
        timer.start();
        rv =conn.startTransaction();
        if (rv != OK) exit(1);
        val1 = i;
        table->execute();
        tuple = (char*)table->fetch() ;
        if (tuple == NULL) {printf("loop break in %d\n", i);table->closeScan();break;}
  //      printf(" %d tuple value is %d %s \n", i, *((int*)tuple), tuple+offset1);
        table->closeScan();
        icount++;
        conn.commit();
        timer.stop();
    }
    printf("%d rows selected %lld %lld %lld\n", icount, timer.minc(), timer.maxc(), timer.avg());
    timer.reset();

    for(i = LOAD; i< LOAD+ITERATIONS; i++)
    {
        timer.start();
        rv  = conn.startTransaction();
        if (rv != OK) exit (1);
        val1 = i;
        table->execute();
        tuple = (char*)table->fetch() ;
        if (tuple == NULL) {printf("loop break in %d\n", i);table->closeScan();break;}
        strcpy(name, "PRABAKARAN0950576543210");
        table->updateTuple();
        table->closeScan();
        conn.commit();
        timer.stop();
    }
    printf("%d rows updated %lld %lld %lld\n", i- LOAD, timer.minc(), timer.maxc(), timer.avg());


    icount=0;
    for(i = LOAD; i< LOAD+ITERATIONS; i++)
    {
        timer.start();
        rv = conn.startTransaction();
        if (rv != OK) exit (1);
        val1 = i;
        table->execute();
        tuple = (char*)table->fetch() ;
        if (tuple == NULL) {printf("No record for %d\n", i);table->closeScan();break;}
        table->deleteTuple();
        icount++;
        table->closeScan();
        conn.commit();
        timer.stop();
    }
    printf("%d rows deleted %lld %lld %lld\n", icount, timer.minc(), timer.maxc(), timer.avg());


    dbMgr->closeTable(table);
    dbMgr->dropTable("t1");
    printf("Table dropped\n");

    conn.close();
    return 0;
}
Example #22
0
void InfoPanel::DrawInfo() const
{
	Color dim = *GameData::Colors().Get("medium");
	Color bright = *GameData::Colors().Get("bright");
	Color elsewhere = *GameData::Colors().Get("dim");
	Color dead(.4, 0., 0., 0.);
	const Font &font = FontSet::Get(14);
	
	// Player info.
	Table table;
	table.AddColumn(0, Table::LEFT);
	table.AddColumn(230, Table::RIGHT);
	table.SetUnderline(0, 230);
	table.DrawAt(Point(-490., -265.));
	
	table.Draw("player:", dim);
	table.Draw(player.FirstName() + " " + player.LastName(), bright);
	table.Draw("net worth:", dim);
	table.Draw(Format::Number(player.Accounts().NetWorth()) + " credits", bright);
	
	// Determine the player's combat rating.
	table.DrawGap(10);
	size_t ratingLevel = 0;
	auto it = player.Conditions().find("combat rating");
	if(it != player.Conditions().end() && it->second > 0)
	{
		ratingLevel = log(it->second);
		ratingLevel = min(ratingLevel, RATINGS.size() - 1);
	}
	table.DrawUnderline(dim);
	table.Draw("combat rating:", bright);
	table.Advance();
	table.DrawGap(5);
	table.Draw(RATINGS[ratingLevel], dim);
	table.Draw("(" + to_string(ratingLevel) + ")", dim);
	
	auto salary = Match(player, "salary: ", "");
	sort(salary.begin(), salary.end());
	DrawList(salary, table, "salary:", 4);
	
	auto tribute = Match(player, "tribute: ", "");
	sort(tribute.begin(), tribute.end());
	DrawList(tribute, table, "tribute:", 4);
	
	int maxRows = static_cast<int>(250. - 30. - table.GetPoint().Y()) / 20;
	auto licenses = Match(player, "license: ", " License");
	DrawList(licenses, table, "licenses:", maxRows, false);
	
	// Fleet listing.
	Point pos = Point(-240., -270.);
	font.Draw("ship", pos + Point(0., 0.), bright);
	font.Draw("model", pos + Point(220., 0.), bright);
	font.Draw("system", pos + Point(350., 0.), bright);
	font.Draw("shields", pos + Point(550. - font.Width("shields"), 0.), bright);
	font.Draw("hull", pos + Point(610. - font.Width("hull"), 0.), bright);
	font.Draw("fuel", pos + Point(670. - font.Width("fuel"), 0.), bright);
	font.Draw("crew", pos + Point(730. - font.Width("crew"), 0.), bright);
	FillShader::Fill(pos + Point(365., 15.), Point(730., 1.), dim);
	
	if(!player.Ships().size())
		return;
	int lastIndex = player.Ships().size() - 1;
	
	pos.Y() += 5.;
	int index = 0;
	auto sit = player.Ships().begin() + scroll;
	for( ; sit < player.Ships().end(); ++sit)
	{
		const shared_ptr<Ship> &ship = *sit;
		pos.Y() += 20.;
		if(pos.Y() >= 250.)
			break;
		
		bool isElsewhere = (ship->GetSystem() != player.GetSystem());
		bool isDead = ship->IsDestroyed() || ship->IsDisabled();
		bool isHovered = (index == hover);
		const Color &color = isDead ? dead : isElsewhere ? elsewhere : isHovered ? bright : dim;
		font.Draw(ship->Name(), pos + Point(10. * ship->CanBeCarried(), 0.), color);
		font.Draw(ship->ModelName(), pos + Point(220., 0.), color);
		
		const System *system = ship->GetSystem();
		if(system)
			font.Draw(system->Name(), pos + Point(350., 0.), color);
		
		string shields = to_string(static_cast<int>(100. * max(0., ship->Shields()))) + "%";
		font.Draw(shields, pos + Point(550. - font.Width(shields), 0.), color);
		
		string hull = to_string(static_cast<int>(100. * max(0., ship->Hull()))) + "%";
		font.Draw(hull, pos + Point(610. - font.Width(hull), 0.), color);
		
		string fuel = to_string(static_cast<int>(
			ship->Attributes().Get("fuel capacity") * ship->Fuel()));
		font.Draw(fuel, pos + Point(670. - font.Width(fuel), 0.), color);
		
		string crew = ship->IsParked() ? "Parked" : to_string(index ? ship->RequiredCrew() : ship->Crew());
		font.Draw(crew, pos + Point(730. - font.Width(crew), 0.), color);
		
		if(index < lastIndex || selected < 0)
			zones.emplace_back(pos + Point(365, font.Height() / 2), Point(730, 20), index);
		else
		{
			int height = 270. - pos.Y();
			zones.emplace_back(pos + Point(365, height / 2), Point(730, height), index);
		}
		++index;
	}
	
	// Re-ordering ships in your fleet.
	if(selected >= 0)
	{
		const string &name = player.Ships()[selected]->Name();
		Point pos(hoverPoint.X() - .5 * font.Width(name), hoverPoint.Y());
		font.Draw(name, pos + Point(1., 1.), Color(0., 1.));
		font.Draw(name, pos, bright);
	}
}
Example #23
0
void IsisMain() {
  // Create a serial number list
  UserInterface &ui = Application::GetUserInterface();
  QString filename = ui.GetFileName("FROM");
  SerialNumberList serialNumberList;
  serialNumberList.Add(filename);

  // Get the coordinate for updating the camera pointing
  // We will want to make the camera pointing match the lat/lon at this
  // line sample
  double samp1 = ui.GetDouble("SAMP1");
  double line1 = ui.GetDouble("LINE1");
  Latitude lat1(ui.GetDouble("LAT1"), Angle::Degrees);
  Longitude lon1(ui.GetDouble("LON1"), Angle::Degrees);
  Distance rad1;
  if(ui.WasEntered("RAD1")) {
    rad1 = Distance(ui.GetDouble("RAD1"), Distance::Meters);
  }
  else {
    rad1 = GetRadius(ui.GetFileName("FROM"), lat1, lon1);
  }

  // In order to use the bundle adjustment class we will need a control
  // network
  ControlMeasure * m = new ControlMeasure;
  m->SetCubeSerialNumber(serialNumberList.SerialNumber(0));
  m->SetCoordinate(samp1, line1);
//   m->SetType(ControlMeasure::Manual);
  m->SetType(ControlMeasure::RegisteredPixel);

  ControlPoint * p = new ControlPoint;
  p->SetAprioriSurfacePoint(SurfacePoint(lat1, lon1, rad1));
  p->SetId("Point1");
  p->SetType(ControlPoint::Fixed);
  p->Add(m);

  ControlNet cnet;
//  cnet.SetType(ControlNet::ImageToGround);
  cnet.AddPoint(p);

    // We need the target body
    Cube c;
    c.open(filename, "rw");
    //check for target name
    if(c.label()->hasKeyword("TargetName", PvlObject::Traverse)) {
//       c.Label()->findKeyword("TargetName");
      PvlGroup inst = c.label()->findGroup("Instrument", PvlObject::Traverse);
      QString targetName = inst["TargetName"];
      cnet.SetTarget(targetName);
    }
    c.close();

  // See if they wanted to solve for twist
  if(ui.GetBoolean("TWIST")) {
    double samp2 = ui.GetDouble("SAMP2");
    double line2 = ui.GetDouble("LINE2");
    Latitude lat2(ui.GetDouble("LAT2"), Angle::Degrees);
    Longitude lon2(ui.GetDouble("LON2"), Angle::Degrees);
    Distance rad2;
    if(ui.WasEntered("RAD2")) {
      rad2 = Distance(ui.GetDouble("RAD2"), Distance::Meters);
    }
    else {
      rad2 = GetRadius(ui.GetFileName("FROM"), lat2, lon2);
    }

    ControlMeasure * m = new ControlMeasure;
    m->SetCubeSerialNumber(serialNumberList.SerialNumber(0));
    m->SetCoordinate(samp2, line2);
    m->SetType(ControlMeasure::Manual);

    ControlPoint * p = new ControlPoint;
    p->SetAprioriSurfacePoint(SurfacePoint(lat2, lon2, rad2));
    p->SetId("Point2");
    p->SetType(ControlPoint::Fixed);
    p->Add(m);

    cnet.AddPoint(p);
  }

  // Bundle adjust to solve for new pointing
  try {
    BundleAdjust b(cnet, serialNumberList);
    b.SetSolveTwist(ui.GetBoolean("TWIST"));
    //    double tol = ui.GetDouble("TOL");
    //int maxIterations = ui.GetInteger("MAXITS");
    //b.Solve(tol, maxIterations);
    b.SetSolveCmatrix(BundleAdjust::AnglesOnly);
    b.SetSolveSpacecraftPosition(BundleAdjust::Nothing);
    b.SetErrorPropagation(false);
    b.SetOutlierRejection(false);
    b.SetSolutionMethod("SPECIALK");
    b.SetStandardOutput(true);
    b.SetCSVOutput(false);
    b.SetResidualOutput(true);
    b.SetConvergenceThreshold(ui.GetDouble("SIGMA0"));
    b.SetMaxIterations(ui.GetInteger("MAXITS"));

    b.SetDecompositionMethod(BundleAdjust::SPECIALK);
    b.SolveCholesky();

    Cube c;
    c.open(filename, "rw");

    //check for existing polygon, if exists delete it
    if(c.label()->hasObject("Polygon")) {
      c.label()->deleteObject("Polygon");
    }

    Table cmatrix = b.Cmatrix(0);

    // Write out a description in the spice table
    QString deltackComment = "deltackAdjusted = " + Isis::iTime::CurrentLocalTime();
    cmatrix.Label().addComment(deltackComment);
    //PvlKeyword description("Description");
    //description = "Camera pointing updated via deltack application";
    //cmatrix.Label().findObject("Table",Pvl::Traverse).addKeyword(description);

    // Update the cube history
    c.write(cmatrix);
    History h("IsisCube");
    c.read(h);
    h.AddEntry();
    c.write(h);
    c.close();
    PvlGroup gp("DeltackResults");
    gp += PvlKeyword("Status", "Camera pointing updated");
    Application::Log(gp);
  }
  catch(IException &e) {
    QString msg = "Unable to update camera pointing for [" + filename + "]";
    throw IException(e, IException::Unknown, msg, _FILEINFO_);
  }

}
Example #24
0
void  Emitter::serialize(Table& table)
{
	rsSerialize(table);
    //////////////////////////////////////////////////////////
    table.set("maxParticles",getMaxParticles());
    table.set("emissionRate",getEmissionRate());
    table.set("gravity",getGravity());
    if(getDuration()>=0.0) 
        table.set("duration",getDuration());
    table.set("relative",(float)getRelative());
    //////////////////////////////////////////////////////////
    table.set("position",getPosition());
    table.set("direction",getDirection());

    table.set("startScale",getStartScale());
    table.set("endScale",getEndScale());

    table.set("startSpin",getStartSpin().valueDegrees());
    table.set("endSpin",  getEndSpin().valueDegrees());
    
    table.set("startColor",getStartColor().toVec4());
    table.set("endColor",getEndColor().toVec4());

    table.set("life",getLife());
    //////////////////////////////////////////////////////////
    table.set("positionVar",getPositionVar());
    table.set("directionVar",getDirectionVar());

    table.set("startScaleVar",getStartScaleVar());
    table.set("endScaleVar",getEndScaleVar());

    table.set("startSpinVar",getStartSpinVar().valueDegrees());
    table.set("endSpinVar"  ,getEndSpinVar().valueDegrees());

    table.set("startColorVar",getStartColorVar().toVec4());
    table.set("endColorVar",getEndColorVar().toVec4());

    table.set("lifeVar",getLifeVar());
    //////////////////////////////////////////////////////////
    //serialize texture
    if(getTexture())
        table.set("texture",getTexture()->getName());
    //serialize shader
    if(getShader())
        table.set("shader",getShader()->getName());
    
}
Example #25
0
std::string System::findDataFile
(const std::string&  full,
 bool                errorIfNotFound) {

    // Places where specific files were most recently found.  This is
    // used to cache seeking of common files.
    static Table<std::string, std::string> lastFound;

    // First check if the file exists as requested.  This will go
    // through the FileSystemCache, so most calls do not touch disk.
    if (FileSystem::exists(full)) {
        return full;
    }

    // Now check where we previously found this file.
    std::string* last = lastFound.getPointer(full);
    if (last != NULL) {
        if (FileSystem::exists(*last)) {
            // Even if cwd has changed the file is still present.
            // We won't notice if it has been deleted, however.
            return *last;
        } else {
            // Remove this from the cache it is invalid
            lastFound.remove(full);
        }
    }

    // Places to look
    static Array<std::string> directoryArray;

    std::string initialAppDataDir(instance().m_appDataDir);
    const char* g3dPath = getenv("G3DDATA");

    if (directoryArray.size() == 0) {
        // Initialize the directory array
        RealTime t0 = System::time();

        Array<std::string> baseDirArray;
        
        baseDirArray.append("");
        if (! initialAppDataDir.empty()) {
            baseDirArray.append(initialAppDataDir);
        }

#       ifdef G3D_WIN32
        if (g3dPath == NULL) {
            // If running the demos under visual studio from the G3D.sln file,
            // this will locate the data directory.
            const char* paths[] = {"../data-files/", "../../data-files/", "../../../data-files/", NULL};
            for (int i = 0; paths[i]; ++i) {
                if (FileSystem::exists(pathConcat(paths[i], "G3D-DATA-README.TXT"))) {
                    g3dPath = paths[i];
                    break;
                }
            }
        }
#       endif

        if (g3dPath && (initialAppDataDir != g3dPath)) {
            baseDirArray.append(g3dPath);
        }

        static const std::string subdirs[] = 
            {"font", "gui", "SuperShader", "cubemap", "icon", "material", "image", "md2", "md3", "ifs", "3ds", "sky", ""};
        for (int j = 0; j < baseDirArray.size(); ++j) {
            std::string d = baseDirArray[j];
            if ((d == "") || FileSystem::exists(d)) {
                directoryArray.append(d);
                for (int i = 0; ! subdirs[i].empty(); ++i) {
                    const std::string& p = pathConcat(d, subdirs[i]);
                    if (FileSystem::exists(p)) {
                        directoryArray.append(p);
                    }
                }
            }
        }

        logLazyPrintf("Initializing System::findDataFile took %fs\n", System::time() - t0);
    }

    for (int i = 0; i < directoryArray.size(); ++i) {
        const std::string& p = pathConcat(directoryArray[i], full);
        if (FileSystem::exists(p)) {
            lastFound.set(full, p);
            return p;
        }
    }

    if (errorIfNotFound) {
        // Generate an error message
        std::string locations;
        for (int i = 0; i < directoryArray.size(); ++i) {
            locations += "\'" + pathConcat(directoryArray[i], full) + "'\n";
        }

        std::string msg = "Could not find '" + full + "'.\n\n";
        msg += "cwd = \'" + FileSystem::currentDirectory() + "\'\n";
        if (g3dPath) {
            msg += "G3DDATA = ";
            if (! FileSystem::exists(g3dPath)) {
                msg += "(illegal path!) ";
            }
            msg += std::string(g3dPath) + "\'\n";
        } else {
            msg += "(G3DDATA environment variable is undefined)\n";
        }
        msg += "GApp::Settings.dataDir = ";
        if (! FileSystem::exists(initialAppDataDir)) {
            msg += "(illegal path!) ";
        }
        msg += std::string(initialAppDataDir) + "\'\n";

        msg += "\nLocations searched:\n" + locations;

        alwaysAssertM(false, msg);
    }

    // Not found
    return "";
}
Example #26
0
void  Emitter::deserialize(const Table& table)
{
    //////////////////////////////////////////////////////////
	rsDeserialize(table);
    //allways false
    setCanBatch(false);
    //get shader
    if(table.existsAsType("shader",Table::STRING))
    {
        auto rsmanager=table.getResourcesManager();
        DEBUG_ASSERT(rsmanager);
        auto rsgroup=rsmanager->getResourcesGroup();
        DEBUG_ASSERT(rsgroup);
        setShader(rsgroup->load<Shader>(table.getString("shader")));
    }
    //get texture
    if(table.existsAsType("texture",Table::STRING))
    {
        auto rsmanager=table.getResourcesManager();
        DEBUG_ASSERT(rsmanager);
        auto rsgroup=rsmanager->getResourcesGroup();
        DEBUG_ASSERT(rsgroup);   
        //set texture 
        setTexture(rsgroup->load<Texture>(table.getString("texture")));
    }
    //////////////////////////////////////////////////////////
    DEBUG_ASSERT(table.existsAsType("maxParticles",Table::FLOAT));
    //////////////////////////////////////////////////////////
    setMaxParticles(table.get("maxParticles",getMaxParticles()));
    setEmissionRate(table.get("emissionRate",getEmissionRate()));
    setDuration(table.get("duration",getDuration()));
    setGravity(table.get("gravity",getGravity()));
    setRelative(table.get("relative",getRelative()));
    center.dir=table.get("direction",getDirection());

    //////////////////////////////////////////////////////////
    center.position=table.get("position",getPosition());
    center.startScale=table.get("startScale",getStartScale());
    center.endScale=table.get("endScale",getEndScale());
    
    center.startSpin=Angle( Degree( table.getFloat("startSpin",getStartSpin().valueDegrees()) ) );
    center.endSpin  =Angle( Degree( table.getFloat("endSpin"  ,getEndSpin().valueDegrees()  ) ) );

    center.startColor=table.get("startColor",getStartColor()).toNormalize();
    center.endColor=table.get("endColor",getEndColor()).toNormalize();

    center.life=table.getFloat("life",getLife());
    //////////////////////////////////////////////////////////
    var.position=table.getVector2D("positionVar",getPositionVar());
    var.dir=table.getVector2D("directionVar",getDirectionVar());

    var.startScale=table.getVector2D("startScaleVar",getStartScaleVar());
    var.endScale=table.getVector2D("endScaleVar",getEndScaleVar());

	var.startSpin=Angle( Degree( table.getFloat("startSpinVar",getStartSpinVar().valueDegrees()) ) );
    var.endSpin  =Angle( Degree( table.getFloat("endSpinVar",getEndSpinVar().valueDegrees()) ) ); 

    var.startColor=table.get("startColorVar",getStartColorVar()).toNormalize();
    var.endColor=table.get("endColorVar",getEndColorVar()).toNormalize();

    var.life=table.getFloat("lifeVar",getLifeVar());
    //////////////////////////////////////////////////////////
}
int updateNewTable(vector<ihead_t> &iheadvec, vector<ohead_t> &oheadvec, Table &itab, Table &otab, int orowoff)
{
    unsigned i, row;
    char c;
    std::stringstream valstream;
    if(itab.getNbrofrows()+orowoff>otab.getNbrofrows()) return -1;

    for(i=0; i<min(iheadvec.size(),oheadvec.size()); i++) {
        // write out tablehead
        c = oheadvec[i].oname[0];
        if('$'==c || '+'==c || '-'==c || '%'==c || '['==c || ']'==c) {
            otab.Tablewrite(0, oheadvec[i].ocol, oheadvec[i].oname.substr(1,std::string::npos));
        } else {
            otab.Tablewrite(0, oheadvec[i].ocol, oheadvec[i].oname);
        }
        // process/write table content
        for(row=1; row<itab.getNbrofrows(); row++) {
            if(1>iheadvec[i].iname.size()) return -4;
            if(-2==iheadvec[i].icol) {
                otab.Tablewrite(row + orowoff, oheadvec[i].ocol, iheadvec[i].iname.substr(1, std::string::npos));
            } else if('$'==oheadvec[i].oname[0]) {
                otab.Tablewrite(row + orowoff, oheadvec[i].ocol, "");
                valstream.str("");
                valstream << std::scientific << norm_value(itab.Tableread(row, iheadvec[i].icol));
                otab.Tablewrite(row + orowoff, oheadvec[i].ocol, valstream.str());
            } else if('%'==oheadvec[i].oname[0]) {
                otab.Tablewrite(row + orowoff, oheadvec[i].ocol, to_string(is_relative(itab.Tableread(row, iheadvec[i].icol))));
            } else if('\\'==oheadvec[i].oname[0]) {
                otab.Tablewrite(row + orowoff, oheadvec[i].ocol, firstword(itab.Tableread(row, iheadvec[i].icol)));
            } else if('+'==oheadvec[i].oname[0]) {
                otab.Tablewrite(row + orowoff, oheadvec[i].ocol, "");
                valstream.str("");
                valstream << std::scientific << tolupp(itab.Tableread(row, iheadvec[i].icol));
                otab.Tablewrite(row + orowoff, oheadvec[i].ocol, valstream.str());
            } else if('-'==oheadvec[i].oname[0]) {
                otab.Tablewrite(row + orowoff, oheadvec[i].ocol, "");
                valstream.str("");
                valstream << std::scientific << tollow(itab.Tableread(row, iheadvec[i].icol));
                otab.Tablewrite(row + orowoff, oheadvec[i].ocol, valstream.str());
            } else if('['==oheadvec[i].oname[0]) {
                otab.Tablewrite(row + orowoff, oheadvec[i].ocol, "");
                valstream.str("");
                valstream << std::scientific << vallow(norm_value(itab.Tableread(row, iheadvec[i+1].icol)), tollow(itab.Tableread(row, iheadvec[i].icol)), is_relative(itab.Tableread(row, iheadvec[i].icol)));
                otab.Tablewrite(row + orowoff, oheadvec[i].ocol, valstream.str());
            } else if(']'==oheadvec[i].oname[0]) {
                otab.Tablewrite(row + orowoff, oheadvec[i].ocol, "");
                valstream.str("");
                valstream << std::scientific << valupp(norm_value(itab.Tableread(row, iheadvec[i-1].icol)), tolupp(itab.Tableread(row, iheadvec[i].icol)), is_relative(itab.Tableread(row, iheadvec[i].icol)));
                otab.Tablewrite(row + orowoff, oheadvec[i].ocol, valstream.str());
            } else {
                otab.Tablewrite(row + orowoff, oheadvec[i].ocol, itab.Tableread(row, iheadvec[i].icol));
            }
            if(false==otab.OK) return -2;
            if(false==itab.OK) return -3;
        }
    }
    return 0;
}
Example #28
0
void assert_field_name( Table &td,
                        int field_index,
                        const string &name ) {
  ASSERT_STREQ( td.fields()[ field_index ].name().c_str(), name.c_str() );
}
Example #29
0
void
b2g_ps_add_table_headers(Table& t, bool show_threads)
{
  t.start_row();
  t.add("NAME");
  t.add(show_threads ? "TID" : "PID");
  t.add("PPID");
  t.add("CPU(s)");
  t.add("NICE");
  t.add("USS");
  t.add("PSS");
  t.add("RSS");
  t.add("SWAP");
  t.add("VSIZE");
  t.add("OOM_ADJ");
  t.add("USER", Table::ALIGN_LEFT);
}
Example #30
0
void generateFKey(map<string, Table>& tables) {
    map<string, Table>::iterator tableIte = tables.begin();
    vector<Table> linkers;
    ForeignKey foreignKey;
    while (tableIte != tables.end()) {
        if (!tableIte->second.getAssociation().empty()) {
            vector <Association> tmpAssociation =
                    tableIte->second.getAssociation();
            vector <Association>::iterator associationIter
                    = tmpAssociation.begin();

            while (associationIter != tmpAssociation.end()) {
                //these are all one-to-many.
                if (isMultiplicity(associationIter->startTable) &&
                        !isMultiplicity(associationIter->anotherTable)) {
                     map<string, Table>::iterator tmpTableIte = tables.find(
                            associationIter->anotherTable.name);
                     if(!tmpTableIte->second.getPK().empty()){
                        foreignKey.associationClassName =
                            associationIter->anotherTable.name;
                   
                        foreignKey.attributes = tmpTableIte->second.getPK();
                        tableIte->second.setFK(foreignKey);
						tableIte->second.setAttribute(foreignKey.attributes);
                        foreignKey.attributes.clear();
                        foreignKey.associationClassName.clear();
                     }
                } else if (!isMultiplicity(associationIter->startTable) &&
                        isMultiplicity(associationIter->anotherTable)) {
                    foreignKey.associationClassName = associationIter->startTable.name;
                    map<string, Table>::iterator tmpTableIte = tables.find(
                            associationIter->anotherTable.name);
                    if(!tableIte->second.getPK().empty()){
                        
                        foreignKey.attributes = tableIte->second.getPK();
                        tmpTableIte->second.setFK(foreignKey);
						tmpTableIte->second.setAttribute(foreignKey.attributes);
                        foreignKey.attributes.clear();
                        foreignKey.associationClassName.clear();
                    
                    }
                }//it is many to many,so I create a linker to set it as one to many
				else if (isMultiplicity(associationIter->startTable) &&
					isMultiplicity(associationIter->anotherTable)) {
						if (associationIter->link.nameOfAssociationClass.empty() &&
							tableIte->first == associationIter->startTable.name){
							Table newLink;
							string name = associationIter->startTable.name;
							string of = "_";
							name += of;
							name += associationIter->anotherTable.name;
							newLink.setTableName(name);

							//set the first FK and attributes
							map<string, Table>::iterator aTableIte = tables.find(
								associationIter->anotherTable.name);
							if (!aTableIte->second.getPK().empty()) {

								
								foreignKey.associationClassName = associationIter->anotherTable.name;
								foreignKey.attributes = aTableIte->second.getPK();
								newLink.setFK(foreignKey);
								vector <Attribute>::iterator attributeIte = foreignKey.attributes.begin();
								while(attributeIte != foreignKey.attributes.end()){
									attributeIte->id = "ID";
									attributeIte++;
								}
								newLink.setAttribute(foreignKey.attributes);
								foreignKey.attributes.clear();
								foreignKey.associationClassName.clear();

							}
							//set another FK and attributes
							map<string, Table>::iterator sTableIte = tables.find(associationIter->startTable.name);
							if (!sTableIte->second.getPK().empty()) {

								foreignKey.associationClassName = associationIter->startTable.name;
								foreignKey.attributes = sTableIte->second.getPK();
								newLink.setFK(foreignKey);
								vector <Attribute>::iterator attributeIte = foreignKey.attributes.begin();
								while(attributeIte != foreignKey.attributes.end()){
									attributeIte->id = "ID";
									attributeIte++;
								}
								newLink.setAttribute(foreignKey.attributes);	

								foreignKey.attributes.clear();
								foreignKey.associationClassName.clear();

							}
							newLink.setPK();
							linkers.push_back(newLink);

						}else
						{
							editLink(tables, *associationIter);
						}
				}//here is one-to-one model
                else {
                    //set another table's FK
                    foreignKey.associationClassName = associationIter->startTable.name;
                    map<string, Table>::iterator tmpTableIte = tables.find(
                            associationIter->anotherTable.name);
                    if (!tableIte->second.getPK().empty()) {

                        foreignKey.attributes = tableIte->second.getPK();
                        tmpTableIte->second.setFK(foreignKey);
                        tmpTableIte->second.setAttribute(foreignKey.attributes);
                        foreignKey.attributes.clear();
                        foreignKey.associationClassName.clear();
                    }
                    //set current table's FK
                    foreignKey.associationClassName = associationIter->anotherTable.name;
                    tmpTableIte = tables.find(associationIter->anotherTable.name);
                    if (!tmpTableIte->second.getPK().empty()) {

                        foreignKey.attributes = tmpTableIte->second.getPK();
                        tableIte->second.setFK(foreignKey);
                        tableIte->second.setAttribute(foreignKey.attributes);
                        foreignKey.attributes.clear();
                        foreignKey.associationClassName.clear();
                    }
                }
                associationIter++;
            }
        }
        tableIte++;
    }

    //insert new table into container
    vector<Table>::iterator linkIte = linkers.begin();
    while (linkIte != linkers.end()) {
        tables.insert(make_pair(linkIte->getTableName(), *linkIte));
        linkIte++;
    }
}