Exemplo n.º 1
0
int main ()
{
    // Basic example (1/6) :
    try
    {
        // Open a database file in readonly mode
        SQLite::Database    db(filename_example_db3);  // SQLITE_OPEN_READONLY
        std::cout << "SQLite database file '" << db.getFilename().c_str() << "' opened successfully\n";

        // Test if the 'test' table exists
        bool bExists = db.tableExists("test");
        std::cout << "SQLite table 'test' exists=" << bExists << "\n";

        // Get a single value result with an easy to use shortcut
        std::string value = db.execAndGet("SELECT value FROM test WHERE id=2");
        std::cout << "execAndGet=" << value.c_str() << std::endl;

        // Compile a SQL query, containing one parameter (index 1)
        SQLite::Statement   query(db, "SELECT id as test_id, value as test_val, weight as test_weight FROM test WHERE weight > ?");
        std::cout << "SQLite statement '" << query.getQuery().c_str() << "' compiled (" << query.getColumnCount () << " columns in the result)\n";
        // Bind the integer value 2 to the first parameter of the SQL query
        query.bind(1, 2);
        std::cout << "binded with integer value '2' :\n";

        // Loop to execute the query step by step, to get one a row of results at a time
        while (query.executeStep())
        {
            // Demonstrate how to get some typed column value (and the equivalent explicit call)
            int         id      = query.getColumn(0); // = query.getColumn(0).getInt()
          //const char* pvalue  = query.getColumn(1); // = query.getColumn(1).getText()
            std::string value2  = query.getColumn(1); // = query.getColumn(1).getText()
            int         bytes   = query.getColumn(1).getBytes();
            double      weight  = query.getColumn(2); // = query.getColumn(2).getInt()

            static bool bFirst = true;
            if (bFirst)
            {
                // Show how to get the aliased names of the result columns.
                std::string name0 = query.getColumn(0).getName();
                std::string name1 = query.getColumn(1).getName();
                std::string name2 = query.getColumn(2).getName();
                std::cout << "aliased result [\"" << name0.c_str() << "\", \"" << name1.c_str() << "\", \"" << name2.c_str() << "\"]\n";
#ifdef SQLITE_ENABLE_COLUMN_METADATA
                // Show how to get origin names of the table columns from which theses result columns come from.
                // Requires the SQLITE_ENABLE_COLUMN_METADATA preprocessor macro to be
                // also defined at compile times of the SQLite library itself.
                name0 = query.getColumn(0).getOriginName();
                name1 = query.getColumn(1).getOriginName();
                name2 = query.getColumn(2).getOriginName();
                std::cout << "origin table 'test' [\"" << name0.c_str() << "\", \"" << name1.c_str() << "\", \"" << name2.c_str() << "\"]\n";
#endif
                bFirst = false;
            }
            std::cout << "row (" << id << ", \"" << value2.c_str() << "\" "  << bytes << " bytes, " << weight << ")\n";
        }

        // Reset the query to use it again
        query.reset();
        std::cout << "SQLite statement '" << query.getQuery().c_str() << "' reseted (" << query.getColumnCount () << " columns in the result)\n";
        // Bind the string value "6" to the first parameter of the SQL query
        query.bind(1, "6");
        std::cout << "binded with string value \"6\" :\n";

        while (query.executeStep())
        {
            // Demonstrate that inserting column value in a std:ostream is natural
            std::cout << "row (" << query.getColumn(0) << ", \"" << query.getColumn(1) << "\", " << query.getColumn(2) << ")\n";
        }
    }
    catch (std::exception& e)
    {
        std::cout << "SQLite exception: " << e.what() << std::endl;
        return EXIT_FAILURE; // unexpected error : exit the example program
    }

    ////////////////////////////////////////////////////////////////////////////
    // Object Oriented Basic example (2/6) :
    try
    {
        // Open the database and compile the query
        Example example;

        // Demonstrate the way to use the same query with different parameter values
        example.ListGreaterThan(8);
        example.ListGreaterThan(6);
        example.ListGreaterThan(2);
    }
    catch (std::exception& e)
    {
        std::cout << "SQLite exception: " << e.what() << std::endl;
        return EXIT_FAILURE; // unexpected error : exit the example program
    }

    // The execAndGet wrapper example (3/6) :
    try
    {
        // Open a database file in readonly mode
        SQLite::Database    db(filename_example_db3);  // SQLITE_OPEN_READONLY
        std::cout << "SQLite database file '" << db.getFilename().c_str() << "' opened successfully\n";

        // WARNING: Be very careful with this dangerous method: you have to
        // make a COPY OF THE result, else it will be destroy before the next line
        // (when the underlying temporary Statement and Column objects are destroyed)
        std::string value = db.execAndGet("SELECT value FROM test WHERE id=2");
        std::cout << "execAndGet=" << value.c_str() << std::endl;
    }
    catch (std::exception& e)
    {
        std::cout << "SQLite exception: " << e.what() << std::endl;
        return EXIT_FAILURE; // unexpected error : exit the example program
    }

    ////////////////////////////////////////////////////////////////////////////
    // Simple batch queries example (4/6) :
    try
    {
        // Open a database file in create/write mode
        SQLite::Database    db("test.db3", SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
        std::cout << "SQLite database file '" << db.getFilename().c_str() << "' opened successfully\n";

        // Create a new table with an explicit "id" column aliasing the underlying rowid
        db.exec("DROP TABLE IF EXISTS test");
        db.exec("CREATE TABLE test (id INTEGER PRIMARY KEY, value TEXT)");

        // first row
        int nb = db.exec("INSERT INTO test VALUES (NULL, \"test\")");
        std::cout << "INSERT INTO test VALUES (NULL, \"test\")\", returned " << nb << std::endl;

        // second row
        nb = db.exec("INSERT INTO test VALUES (NULL, \"second\")");
        std::cout << "INSERT INTO test VALUES (NULL, \"second\")\", returned " << nb << std::endl;

        // update the second row
        nb = db.exec("UPDATE test SET value=\"second-updated\" WHERE id='2'");
        std::cout << "UPDATE test SET value=\"second-updated\" WHERE id='2', returned " << nb << std::endl;

        // Check the results : expect two row of result
        SQLite::Statement   query(db, "SELECT * FROM test");
        std::cout << "SELECT * FROM test :\n";
        while (query.executeStep())
        {
            std::cout << "row (" << query.getColumn(0) << ", \"" << query.getColumn(1) << "\")\n";
        }

        db.exec("DROP TABLE test");
    }
    catch (std::exception& e)
    {
        std::cout << "SQLite exception: " << e.what() << std::endl;
        return EXIT_FAILURE; // unexpected error : exit the example program
    }
    remove("test.db3");

    ////////////////////////////////////////////////////////////////////////////
    // RAII transaction example (5/6) :
    try
    {
        // Open a database file in create/write mode
        SQLite::Database    db("transaction.db3", SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
        std::cout << "SQLite database file '" << db.getFilename().c_str() << "' opened successfully\n";

        db.exec("DROP TABLE IF EXISTS test");

        // Exemple of a successful transaction :
        try
        {
            // Begin transaction
            SQLite::Transaction transaction(db);

            db.exec("CREATE TABLE test (id INTEGER PRIMARY KEY, value TEXT)");

            int nb = db.exec("INSERT INTO test VALUES (NULL, \"test\")");
            std::cout << "INSERT INTO test VALUES (NULL, \"test\")\", returned " << nb << std::endl;

            // Commit transaction
            transaction.commit();
        }
        catch (std::exception& e)
        {
            std::cout << "SQLite exception: " << e.what() << std::endl;
            return EXIT_FAILURE; // unexpected error : exit the example program
        }

        // Exemple of a rollbacked transaction :
        try
        {
            // Begin transaction
            SQLite::Transaction transaction(db);

            int nb = db.exec("INSERT INTO test VALUES (NULL, \"second\")");
            std::cout << "INSERT INTO test VALUES (NULL, \"second\")\", returned " << nb << std::endl;

            nb = db.exec("INSERT INTO test ObviousError");
            std::cout << "INSERT INTO test \"error\", returned " << nb << std::endl;

            return EXIT_FAILURE; // unexpected success : exit the example program

            // Commit transaction
            transaction.commit();
        }
        catch (std::exception& e)
        {
            std::cout << "SQLite exception: " << e.what() << std::endl;
            // expected error, see above
        }

        // Check the results (expect only one row of result, as the second one has been rollbacked by the error)
        SQLite::Statement   query(db, "SELECT * FROM test");
        std::cout << "SELECT * FROM test :\n";
        while (query.executeStep())
        {
            std::cout << "row (" << query.getColumn(0) << ", \"" << query.getColumn(1) << "\")\n";
        }
    }
    catch (std::exception& e)
    {
        std::cout << "SQLite exception: " << e.what() << std::endl;
        return EXIT_FAILURE; // unexpected error : exit the example program
    }
    remove("transaction.db3");

    ////////////////////////////////////////////////////////////////////////////
    // Binary blob and in-memory database example (6/6) :
    try
    {
        // Open a database file in create/write mode
        SQLite::Database    db(":memory:", SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
        std::cout << "SQLite database file '" << db.getFilename().c_str() << "' opened successfully\n";

        db.exec("DROP TABLE IF EXISTS test");
        db.exec("CREATE TABLE test (id INTEGER PRIMARY KEY, value BLOB)");

        FILE* fp = fopen(filename_logo_png.c_str(), "rb");
        if (NULL != fp)
        {
            char  buffer[16*1024];
            void* blob = &buffer;
            int size = static_cast<int>(fread(blob, 1, 16*1024, fp));
            buffer[size] = '\0';
            fclose (fp);
            std::cout << "blob size=" << size << " :\n";

            // Insert query
            SQLite::Statement   query(db, "INSERT INTO test VALUES (NULL, ?)");
            // Bind the blob value to the first parameter of the SQL query
            query.bind(1, blob, size);
            std::cout << "blob binded successfully\n";

            // Execute the one-step query to insert the blob
            int nb = query.exec ();
            std::cout << "INSERT INTO test VALUES (NULL, ?)\", returned " << nb << std::endl;
        }
        else
        {
            std::cout << "file " << filename_logo_png << " not found !\n";
            return EXIT_FAILURE; // unexpected error : exit the example program
        }

        fp = fopen("out.png", "wb");
        if (NULL != fp)
        {
            const void* blob = NULL;
            size_t size;

            SQLite::Statement   query(db, "SELECT * FROM test");
            std::cout << "SELECT * FROM test :\n";
            if (query.executeStep())
            {
                SQLite::Column colBlob = query.getColumn(1);
                blob = colBlob.getBlob ();
                size = colBlob.getBytes ();
                std::cout << "row (" << query.getColumn(0) << ", size=" << size << ")\n";
                size_t sizew = fwrite(blob, 1, size, fp);
                SQLITECPP_ASSERT(sizew == size, "fwrite failed");   // See SQLITECPP_ENABLE_ASSERT_HANDLER
                fclose (fp);
            }
        }
        else
        {
            std::cout << "file out.png not created !\n";
            return EXIT_FAILURE; // unexpected error : exit the example program
        }
    }
    catch (std::exception& e)
    {
        std::cout << "SQLite exception: " << e.what() << std::endl;
        return EXIT_FAILURE; // unexpected error : exit the example program
    }
    remove("out.png");

    std::cout << "everything ok, quitting\n";

    return EXIT_SUCCESS;
}
Exemplo n.º 2
0
int VACA_MAIN()
{
  Example app;
  app.run();
  return 0;
}
int main(int argc, char** argv)
{
	Example *example =  new Example();
	example->run();
	
}
Exemplo n.º 4
0
	void FilterBoostClassifier::saveLikelihoods(const string& dataFileName, const string& shypFileName, 
		const string& outFileName, int numIterations)
	{
		InputData* pData = loadInputData(dataFileName, shypFileName);

		if (_verbose > 0)
			cout << "Loading strong hypothesis..." << flush;

		// The class that loads the weak hypotheses
		UnSerialization us;

		// Where to put the weak hypotheses
		vector<BaseLearner*> weakHypotheses;

		// loads them
		us.loadHypotheses(shypFileName, weakHypotheses, pData);

		// where the results go
		vector< ExampleResults* > results;

		if (_verbose > 0)
			cout << "Classifying..." << flush;

		const int numClasses = pData->getNumClasses();
		const int numExamples = pData->getNumExamples();


		ofstream outFile(outFileName.c_str());
		string exampleName;

		if (_verbose > 0)
			cout << "Output likelihoods..." << flush;

		// get the results
		/////////////////////////////////////////////////////////////////////
		// computeResults( pData, weakHypotheses, results, numIterations );
		assert( !weakHypotheses.empty() );

		// Initialize the output info
		OutputInfo* pOutInfo = NULL;

		if ( !_outputInfoFile.empty() )
			pOutInfo = new OutputInfo(_outputInfoFile);

		// Creating the results structures. See file Structures.h for the
		// PointResults structure
		results.clear();
		results.reserve(numExamples);
		for (int i = 0; i < numExamples; ++i)
			results.push_back( new ExampleResults(i, numClasses) );

		// sum votes for classes
		vector< float > votesForExamples( numClasses );
		vector< double > expVotesForExamples( numClasses );

		// iterator over all the weak hypotheses
		vector<BaseLearner*>::const_iterator whyIt;
		int t;

		pOutInfo->initialize( pData );

		// for every feature: 1..T
		for (whyIt = weakHypotheses.begin(), t = 0; 
			whyIt != weakHypotheses.end() && t < numIterations; ++whyIt, ++t)
		{
			BaseLearner* currWeakHyp = *whyIt;
			float alpha = currWeakHyp->getAlpha();

			// for every point
			for (int i = 0; i < numExamples; ++i)
			{
				// a reference for clarity and speed
				vector<float>& currVotesVector = results[i]->getVotesVector();

				// for every class
				for (int l = 0; l < numClasses; ++l)
					currVotesVector[l] += alpha * currWeakHyp->classify(pData, i, l);
			}

			// if needed output the step-by-step information
			if ( pOutInfo )
			{
				pOutInfo->outputIteration(t);
				pOutInfo->outputError(pData, currWeakHyp);

				// Margins and edge requires an update of the weight,
				// therefore I keep them out for the moment
				//outInfo.outputMargins(pData, currWeakHyp);
				//outInfo.outputEdge(pData, currWeakHyp);
				pOutInfo->endLine();
			} // for (int i = 0; i < numExamples; ++i)
			// calculate likelihoods from votes

			fill( votesForExamples.begin(), votesForExamples.end(), 0.0 );
			double lLambda = 0.0;
			for (int i = 0; i < numExamples; ++i)
			{
				// a reference for clarity and speed
				vector<float>& currVotesVector = results[i]->getVotesVector();
				double sumExp = 0.0;
				// for every class
				for (int l = 0; l < numClasses; ++l) 
				{				 
					expVotesForExamples[l] =  exp( currVotesVector[l] ) ;
					sumExp += expVotesForExamples[l];
				}			

				if ( sumExp > numeric_limits<double>::epsilon() ) 
				{
					for (int l = 0; l < numClasses; ++l) 
					{
						expVotesForExamples[l] /= sumExp;
					}
				}

				Example ex = pData->getExample( results[i]->getIdx() );
				vector<Label> labs = ex.getLabels();
				double m = numeric_limits<double>::infinity();
				for (int l = 0; l < numClasses; ++l)  
				{
					if ( labs[l].y > 0 )
					{
						if ( expVotesForExamples[l] > numeric_limits<double>::epsilon() )
						{
							double logVal = log( expVotesForExamples[l] );
							
							if ( logVal != m ) {
								lLambda += ( ( 1.0/(double)numExamples ) * logVal );
							}
						}
					}
				}


			}
			

			outFile << t << "\t" << lLambda ;
			outFile << '\n';
			
			outFile.flush();
		}

		if (pOutInfo)
			delete pOutInfo;

		// computeResults( pData, weakHypotheses, results, numIterations );
		///////////////////////////////////////////////////////////////////////////////////


		/*
		for (int i = 0; i < numExamples; ++i)
		{
			// output the name if it exists, otherwise the number
			// of the example
			exampleName = pData->getExampleName(i);
			if ( !exampleName.empty() )
				outFile << exampleName << ',';

			// output the posteriors
			outFile << results[i]->getVotesVector()[0];
			for (int l = 1; l < numClasses; ++l)
				outFile << ',' << results[i]->getVotesVector()[l];
			outFile << '\n';
		}
		*/

		if (_verbose > 0)
			cout << "Done!" << endl;

		if (_verbose > 1)
		{
			cout << "\nClass order (You can change it in the header of the data file):" << endl;
			for (int l = 0; l < numClasses; ++l)
				cout << "- " << pData->getClassMap().getNameFromIdx(l) << endl;
		}

		// delete the input data file
		if (pData) 
			delete pData;

		vector<ExampleResults*>::iterator it;
		for (it = results.begin(); it != results.end(); ++it)
			delete (*it);
	}
Exemplo n.º 5
0
         RC_ASSERT(failure.numShrinks ==
                   ((values.first / 2) + (values.second / 2)));
       });

  prop("returns a correct counter-example",
       [](const TestParams &params, std::vector<int> values) {
         RC_PRE(params.maxSuccess > 0);
         const auto results =
             checkTestable([&](FixedCountdown<0>, FixedCountdown<0>) {
               for (auto value : values) {
                 *gen::just(value);
               }
               return false;
             }, params, dummyListener);

         Example expected;
         expected.reserve(values.size() + 1);
         std::tuple<FixedCountdown<0>, FixedCountdown<0>> expectedArgs(
             FixedCountdown<0>{}, FixedCountdown<0>{});
         expected.push_back(std::make_pair(
             typeToString<decltype(expectedArgs)>(), toString(expectedArgs)));
         std::transform(begin(values),
                        end(values),
                        std::back_inserter(expected),
                        [](int x) {
                          return std::make_pair(typeToString<int>(),
                                                toString(x));
                        });

         FailureResult failure;
         RC_ASSERT(results.match(failure));
Exemplo n.º 6
0
bool Example::sortByNumericalAttribute(const Example& e, const unsigned int index) const{
    if(numericalTokens.size() < index) return false;

    else return numericalTokens[index] < e.getNumericalValue(index);
}
Exemplo n.º 7
0
int WINAPI WinMain(HINSTANCE hInstance,
                   HINSTANCE hPrevInstance,
                   LPSTR cmdLine,
                   int cmdShow)
{
#else
int main(int argc, char** argv)
{
#endif
    //Mengatur Tampilan Window
    const int windowWidth = 1024;
    const int windowHeight = 768;
    const int windowBPP = 16;
    const int windowFullscreen = false;

#ifdef _WIN32
    
    GLWindow programWindow(hInstance);
#else
    SimpleGLXWindow programWindow;
#endif

    //Contoh Kode OpenGL
    Example example;

    //Menyertakan Contoh Proyek ke window
    programWindow.attachExample(&example);

    
    if (!programWindow.create(windowWidth, windowHeight, windowBPP, windowFullscreen))
    {
        
#ifdef _WIN32
        MessageBox(NULL, "Unable to create the OpenGL Window", "An error occurred", MB_ICONERROR | MB_OK);
#endif
        programWindow.destroy(); 
        return 1;
    }

    if (!example.init()) 
    {
#ifdef _WIN32
        MessageBox(NULL, "Could not initialize the application", "An error occurred", MB_ICONERROR | MB_OK);
#endif
        programWindow.destroy(); 
        return 1;
    }

    
    while(programWindow.isRunning())
    {
        programWindow.processEvents(); //Proses Semua Aktifitas Window

       
        float elapsedTime = programWindow.getElapsedSeconds();

        example.prepare(elapsedTime); 
        example.render(); 

        programWindow.swapBuffers();
    }

    example.shutdown(); 
    programWindow.destroy(); 

    return 0; 
}
Exemplo n.º 8
0
void MyGP::evaluate(bool printFinalOutfile, std::string msg){

    // Evaluate main tree
    // Iterate through every term/class, computing all
    // [<term, class> -> credibilityScore] mappings. Then, 
    // write it to a credibility file, and call Naive Bayes! 

    //TODO: voltar para onde estava  
    ExampleIterator testItBegin;
    ExampleIterator testItEnd;

    testItBegin = io->getTest().getBegin();
    testItEnd = io->getTest().getEnd();

    map<string, double> credibilities;

    cout << "-----------------  Gen: " << MyGP::gennum  <<" ------------- Ind: "<< ++MyGP::indCounter <<" ----------------"<<endl;

    int contentCredibilityOffset = stats->getUsingTermCredibility() || stats->getUsingCategoricalCredibility() ? 1 : 0;

    if( stats->getUsingTermCredibility()){
        for(set<string>::iterator vocIt = stats->getVocabulary().begin(); vocIt != stats->getVocabulary().end(); vocIt++) {
            for(set<string>::iterator c**t = (stats->getClasses()).begin(); c**t != (stats->getClasses()).end(); c**t++) {

                double credibility = NthMyGene(0)->evaluate(*this, *vocIt, *c**t);
                string idx = getCompIndex(*vocIt, *c**t);
                credibilities[idx] = credibility;
            }
        }
    }
    else if( stats->getUsingCategoricalCredibility()){
        for(int i = 0; i < stats->getNumberOfCategoricalAttibutes(); i++){
            set<string> tokenSet = stats->getCategoricalSet(i);

            for(set<string>::iterator tokenIt = tokenSet.begin(); tokenIt != tokenSet.end(); tokenIt++){    
                set<string> classes = stats->getClasses();
                for(set<string>::iterator classIt = classes.begin(); classIt != classes.end(); classIt++) {
                    string idxa = getCompIndex(i, *tokenIt);
                    string idx = getCompIndex(idxa, *classIt);
                    
                    double credibility = NthMyGene(0)->evaluate(*this, idxa, *classIt);
                    credibilities[idx] = credibility;
                }
            }
        }
    }

    vector<map<string, double> > credibilityGraph(stats->getNumberOfGraphs());

    for(ExampleIterator testIt = testItBegin; testIt != testItEnd; testIt++){ 
        for(set<string>::iterator classIt = stats->getClasses().begin(); classIt != stats->getClasses().end(); classIt++){
            for(int g = 0; g < stats->getNumberOfGraphs(); g++){

                Example e = *testIt;

                double credibility = NthMyGene(contentCredibilityOffset + g)-> evaluate(*this, e.getId(), *classIt, g);

                string idx = getCompIndex(e.getId(), *classIt);
                credibilityGraph[g][idx] = credibility;
            }
        }
    } 
    
    ICredibilityClassifier *classifier;
    if(stats->getUsingKNN())
        classifier = new KNN(stats, stats->getK(), stats->getUsingKNNOptimize());
    else
        classifier = new NaiveBayes(stats);
    
    classifier->useContentCredibility(true);
    classifier->setContentCredibilityMap(credibilities);
    classifier->setGraphCredibilityMaps(credibilityGraph);
    
    classifier->train(io->getTrain());
    classifier->test(io->getTest());

    if(printFinalOutfile)
        classifier->printFinalOutFile(io->getFinalOutFile(), msg);

    // Print trees related to solutions generated (for debugging purposes).
    for(int i = 0; i < contentCredibilityOffset + stats->getNumberOfGraphs(); i++){
        cout<<"Adfs: "; NthMyGene(i)->printOn(cout); cout<<endl;
    }

    /**
      Print to file 
      fstats.open(statsFileName,ios_base::app);
      for(int i = 0 ; i < numVisions; i++)
      NthMyGene(i)->printOn(fstats);

      fstats <<"\t#\t"<<(1.0-microF1) <<endl;
      fstats.close();
     **/

    if(stats->getUsingMicroF1() && stats->getUsingMacroF1()){
        stdFitness = ((1.0 - classifier->getMicroF1())*100.0) + ((1.0 - classifier->getMacroF1())*100.0);
        cout<<"using both"<<endl;
    }
    else if(stats->getUsingMacroF1()){
        stdFitness = (1.0 - classifier->getMacroF1())*100.0;
        cout<<"using macro"<<endl;
    }
    else{
        stdFitness = (1.0 - classifier->getMicroF1())*100.0;
        cout<<"using micro"<<endl;
    }
    delete classifier;
}
Exemplo n.º 9
0
int main(int argc, char** argv)
{
    Example* p = new Example();
    p->add100(1);
    return 0;
}