bool testpca(bool silent)
{
    bool result;
    int passcount;
    int maxn;
    int maxm;
    double threshold;
    int m;
    int n;
    int i;
    int j;
    int k;
    int info;
    ap::real_1d_array means;
    ap::real_1d_array s;
    ap::real_1d_array t2;
    ap::real_1d_array t3;
    ap::real_2d_array v;
    ap::real_2d_array x;
    double t;
    double h;
    double tmean;
    double tmeans;
    double tstddev;
    double tstddevs;
    double tmean2;
    double tmeans2;
    double tstddev2;
    double tstddevs2;
    bool pcaconverrors;
    bool pcaorterrors;
    bool pcavarerrors;
    bool pcaopterrors;
    bool waserrors;

    
    //
    // Primary settings
    //
    maxm = 10;
    maxn = 100;
    passcount = 1;
    threshold = 1000*ap::machineepsilon;
    waserrors = false;
    pcaconverrors = false;
    pcaorterrors = false;
    pcavarerrors = false;
    pcaopterrors = false;
    
    //
    // Test 1: N random points in M-dimensional space
    //
    for(m = 1; m <= maxm; m++)
    {
        for(n = 1; n <= maxn; n++)
        {
            
            //
            // Generate task
            //
            x.setbounds(0, n-1, 0, m-1);
            means.setbounds(0, m-1);
            for(j = 0; j <= m-1; j++)
            {
                means(j) = 1.5*ap::randomreal()-0.75;
            }
            for(i = 0; i <= n-1; i++)
            {
                for(j = 0; j <= m-1; j++)
                {
                    x(i,j) = means(j)+(2*ap::randomreal()-1);
                }
            }
            
            //
            // Solve
            //
            pcabuildbasis(x, n, m, info, s, v);
            if( info!=1 )
            {
                pcaconverrors = true;
                continue;
            }
            
            //
            // Orthogonality test
            //
            for(i = 0; i <= m-1; i++)
            {
                for(j = 0; j <= m-1; j++)
                {
                    t = ap::vdotproduct(v.getcolumn(i, 0, m-1), v.getcolumn(j, 0, m-1));
                    if( i==j )
                    {
                        t = t-1;
                    }
                    pcaorterrors = pcaorterrors||fabs(t)>threshold;
                }
            }
            
            //
            // Variance test
            //
            t2.setbounds(0, n-1);
            for(k = 0; k <= m-1; k++)
            {
                for(i = 0; i <= n-1; i++)
                {
                    t = ap::vdotproduct(x.getrow(i, 0, m-1), v.getcolumn(k, 0, m-1));
                    t2(i) = t;
                }
                calculatemv(t2, n, tmean, tmeans, tstddev, tstddevs);
                if( n!=1 )
                {
                    t = ap::sqr(tstddev)*n/(n-1);
                }
                else
                {
                    t = 0;
                }
                pcavarerrors = pcavarerrors||fabs(t-s(k))>threshold;
            }
            for(k = 0; k <= m-2; k++)
            {
                pcavarerrors = pcavarerrors||s(k)<s(k+1);
            }
            
            //
            // Optimality: different perturbations in V[..,0] can't
            // increase variance of projection - can only decrease.
            //
            t2.setbounds(0, n-1);
            t3.setbounds(0, n-1);
            for(i = 0; i <= n-1; i++)
            {
                t = ap::vdotproduct(x.getrow(i, 0, m-1), v.getcolumn(0, 0, m-1));
                t2(i) = t;
            }
            calculatemv(t2, n, tmean, tmeans, tstddev, tstddevs);
            for(k = 0; k <= 2*m-1; k++)
            {
                h = 0.001;
                if( k%2!=0 )
                {
                    h = -h;
                }
                ap::vmove(&t3(0), &t2(0), ap::vlen(0,n-1));
                ap::vadd(t3.getvector(0, n-1), x.getcolumn(k/2, 0, n-1), h);
                t = 0;
                for(j = 0; j <= m-1; j++)
                {
                    if( j!=k/2 )
                    {
                        t = t+ap::sqr(v(j,0));
                    }
                    else
                    {
                        t = t+ap::sqr(v(j,0)+h);
                    }
                }
                t = 1/sqrt(t);
                ap::vmul(&t3(0), ap::vlen(0,n-1), t);
                calculatemv(t3, n, tmean2, tmeans2, tstddev2, tstddevs2);
                pcaopterrors = pcaopterrors||tstddev2>tstddev+threshold;
            }
        }
    }
    
    //
    // Special test for N=0
    //
    for(m = 1; m <= maxm; m++)
    {
        
        //
        // Solve
        //
        pcabuildbasis(x, 0, m, info, s, v);
        if( info!=1 )
        {
            pcaconverrors = true;
            continue;
        }
        
        //
        // Orthogonality test
        //
        for(i = 0; i <= m-1; i++)
        {
            for(j = 0; j <= m-1; j++)
            {
                t = ap::vdotproduct(v.getcolumn(i, 0, m-1), v.getcolumn(j, 0, m-1));
                if( i==j )
                {
                    t = t-1;
                }
                pcaorterrors = pcaorterrors||fabs(t)>threshold;
            }
        }
    }
    
    //
    // Final report
    //
    waserrors = pcaconverrors||pcaorterrors||pcavarerrors||pcaopterrors;
    if( !silent )
    {
        printf("PCA TEST\n");
        printf("TOTAL RESULTS:                           ");
        if( !waserrors )
        {
            printf("OK\n");
        }
        else
        {
            printf("FAILED\n");
        }
        printf("* CONVERGENCE                            ");
        if( !pcaconverrors )
        {
            printf("OK\n");
        }
        else
        {
            printf("FAILED\n");
        }
        printf("* ORTOGONALITY                           ");
        if( !pcaorterrors )
        {
            printf("OK\n");
        }
        else
        {
            printf("FAILED\n");
        }
        printf("* VARIANCE REPORT                        ");
        if( !pcavarerrors )
        {
            printf("OK\n");
        }
        else
        {
            printf("FAILED\n");
        }
        printf("* OPTIMALITY                             ");
        if( !pcaopterrors )
        {
            printf("OK\n");
        }
        else
        {
            printf("FAILED\n");
        }
        if( waserrors )
        {
            printf("TEST SUMMARY: FAILED\n");
        }
        else
        {
            printf("TEST SUMMARY: PASSED\n");
        }
        printf("\n\n");
    }
    result = !waserrors;
    return result;
}
Exemplo n.º 2
0
int main(int argc, char** argv)
{
	try
	{
		// Detection parameters :
		// -> Region of interest detection
		// -> Tag validator
		typedef aram::TagDetector<aram::CannyFittingDetector,aram::LocalThreshTagMatcher> myDetector;
		
		// Tag detector instanciation
		myDetector *detector = new myDetector();
		
		// Intrinsics parameters
		aram::Intrinsic intr("camera_data.xml");
		
		aram::MultiTag mt;
		float m_size = 28.0;
		float m_delta = 14.0;

		aram::TagInfo t0(0,aram::Point2D(0.0,m_delta+m_size),m_size);
		aram::TagInfo t1(1,aram::Point2D(0.0,0.0),m_size);
		aram::TagInfo t2(2,aram::Point2D(m_delta+m_size,0.0),m_size);
		aram::TagInfo t3(3,aram::Point2D(m_delta+m_size,m_delta+m_size),m_size);

		mt.addTagInfo(t0);
		mt.addTagInfo(t1);
		mt.addTagInfo(t2);
		mt.addTagInfo(t3);

		
		// Video input (see openCV doc)
		cv::VideoCapture cap(0); // use default video (usually your webcam)
		if(!cap.isOpened()) throw std::exception();
		
		cv::Mat frame;

		// Main loop
		while(true)
       	{
			// next frame from video input 
			cap >> frame;
						
			// Tag detection
			detector->detect(frame);

			// Tag list iterator
			aram::iteratorTag it;
			
			for(it=detector->begin();it!=detector->end();++it)
			{
				aram::vecPoint2D corners = (*it)->corners();

				for(unsigned int i=0;i<corners.size();++i)
				{
					cv::line(frame,corners[i%4],corners[(i+1)%4],cv::Scalar(100,150,150),2);
				}
			}

			// If any tags was detected
			if(detector->begin()!=detector->end())
			{
				// Get extrinsics parameters
				aram::Extrinsic e = mt.compute(detector->begin(),detector->end(),intr);
				drawPyramide(frame,m_size*2+m_delta,aram::Point3D(m_size+m_delta/2,m_size+m_delta/2,0),cv::Scalar(0,255,0),e);
			}
	
			// render
			cv::imshow("render", frame);
			// GUI refresh (see openCV doc)
			if(cv::waitKey(10)>=0) break;
		}
	}
	catch(std::exception &)
	{
	}

	return 0;
}
Exemplo n.º 3
0
void f() {
    C(); // expected-error {{allocation of an object of abstract type 'C'}}
    t3(C()); // expected-error {{allocation of an object of abstract type 'C'}}
}
Exemplo n.º 4
0
TEST(LockManagerTest, TxPolicy) {

    {
        // Test FirstComeFirstServe policy
        LockManager lm_first;
        ClientTransaction t1(&lm_first, 1);
        ClientTransaction t2(&lm_first, 2);
        ClientTransaction t3(&lm_first, 3);
        // test1
        t1.acquire(kExclusive, 1, ACQUIRED);
        t2.acquire(kShared, 1, BLOCKED);
        t3.acquire(kExclusive, 1, BLOCKED);
        t1.release(kExclusive, 1);
        // t2 should wake first, because its request came before t3's
        t2.wakened();
        t2.release(kShared, 1);
        t3.wakened();
        t3.release(kExclusive, 1);

        // test2
        t1.acquire(kExclusive, 1, ACQUIRED);
        t3.acquire(kExclusive, 1, BLOCKED);
        t2.acquire(kShared, 1, BLOCKED);
        t1.release(kExclusive, 1);
        // t3 should wake first, because its request came before t2's
        t3.wakened();
        t3.release(kExclusive, 1);
        t2.wakened();
        t2.release(kShared, 1);

        t1.quit();
        t2.quit();
        t3.quit();
    }

    {
        // Test kPolicyReadersFirst
        // shared request are considered read requests

        LockManager lm_readers(LockManager::kPolicyReadersFirst);
        ClientTransaction t1(&lm_readers, 1);
        ClientTransaction t2(&lm_readers, 2);
        ClientTransaction t3(&lm_readers, 3);

        t1.acquire(kExclusive, 1, ACQUIRED);
        t3.acquire(kExclusive, 1, BLOCKED);
        t2.acquire(kShared, 1, BLOCKED);
        t1.release(kExclusive, 1);

        // t2 should wake first, even though t3 came first in time
        // because t2 is a reader and t3 is a writer
        t2.wakened();
        t2.release(kShared, 1);
        t3.wakened();
        t3.release(kExclusive, 1);

        t1.quit();
        t2.quit();
        t3.quit();
    }

    {
        // Test OLDEST_TX_FIRST policy
        // for now, smaller TxIds are considered older

        LockManager lm_oldest(LockManager::kPolicyOldestTxFirst);
        ClientTransaction t1(&lm_oldest, 1);
        ClientTransaction t2(&lm_oldest, 2);
        ClientTransaction t3(&lm_oldest, 3);

        // test 1
        t1.acquire(kExclusive, 1, ACQUIRED);
        t3.acquire(kExclusive, 1, BLOCKED);
        t2.acquire(kShared, 1, BLOCKED);
        t1.release(kExclusive, 1);

        // t2 should wake first, even though t3 came first in time
        // because t2 is older than t3
        t2.wakened();
        t2.release(kShared, 1);
        t3.wakened();
        t3.release(kExclusive, 1);

        // test 2
        t1.acquire(kExclusive, 1, ACQUIRED);
        t2.acquire(kShared, 1, BLOCKED);
        t3.acquire(kExclusive, 1, BLOCKED);
        t1.release(kExclusive, 1);

        // t2 should wake first, because it's older than t3
        t2.wakened();
        t2.release(kShared, 1);
        t3.wakened();
        t3.release(kExclusive, 1);

        t1.quit();
        t2.quit();
        t3.quit();
    }

    {
        LockManager lm_blockers(LockManager::kPolicyBlockersFirst);
        ClientTransaction t1(&lm_blockers, 1);
        ClientTransaction t2(&lm_blockers, 2);
        ClientTransaction t3(&lm_blockers, 3);
        ClientTransaction t4(&lm_blockers, 4);

        // BIGGEST_BLOCKER_FIRST policy

        // set up t3 as the biggest blocker
        t3.acquire(kExclusive, 2, ACQUIRED);
        t4.acquire(kExclusive, 2, BLOCKED);

        // test 1
        t1.acquire(kExclusive, 1, ACQUIRED);
        t3.acquire(kExclusive, 1, BLOCKED);
        t2.acquire(kShared, 1, BLOCKED);
        t1.release(kExclusive, 1);
        // t3 should wake first, because it's a bigger blocker than t2
        t3.wakened();
        t3.release(kExclusive, 1);
        t2.wakened();
        t2.release(kShared, 1);

        // test 2
        t1.acquire(kExclusive, 1, ACQUIRED);
        t2.acquire(kShared, 1, BLOCKED);
        t3.acquire(kExclusive, 1, BLOCKED);
        t1.release(kExclusive, 1);
        // t3 should wake first, even though t2 came first,
        // because it's a bigger blocker than t2
        t3.wakened();
        t3.release(kExclusive, 1);
        t2.wakened();
        t2.release(kShared, 1);

        t3.release(kExclusive, 2);
        t4.wakened();
        t4.release(kExclusive, 2);

        t1.quit();
        t2.quit();
        t3.quit();
        t4.quit();
    }
}
void SecureNodeListProvider::clientLeave(Client<SecureNodeListProvider> *leaving)
{
	cout << "Client quitte le réseau" << std::endl;

	std::ostringstream oStringStream;
	std::ostringstream oStringStreamPrevious;
	std::ostringstream oStringStreamNext;
	boost::archive::text_oarchive oTextArchive(oStringStream);
	boost::archive::text_oarchive oTextArchivePrevious(oStringStreamPrevious);
	boost::archive::text_oarchive oTextArchiveNext(oStringStreamNext);

	list<pair <string, int> > ipPortVoisins;
	Client<SecureNodeListProvider> *previous=NULL;
	list<pair <string, int> > ipPortOfPreviousNode;
	Client<SecureNodeListProvider> *next=NULL;
	list<pair <string, int> > ipPortOfNextNode;

	if (this->toutlemonde.size() == 2){
		auto i = std::begin(this->toutlemonde);

		while (i != std::end(this->toutlemonde)) {
			if (*i == leaving)
				i = this->toutlemonde.erase(i);
			else
				++i;
		}
		i = std::begin(this->toutlemonde);

		ipPortVoisins.push_front(pair<string, int>("0.0.0.0", 0));
		ipPortVoisins.push_back(pair<string, int>("0.0.0.0", 0));

		oTextArchive << ipPortVoisins;
		Trame t(-4, oStringStream.str());
		cout << "/*********Trame réponse" << std::endl <<
				"TTL : " << t.getTTL() << std::endl <<
				"Commande : " << t.getCommande() << std::endl <<
				"*********/" << std::endl;
		(*i)->send(t);
	}
	else{
		// On trouve le précédent et suivant
		auto it=this->toutlemonde.begin();
		auto tmp=it;
		for(; it != this->toutlemonde.end(); ++it){
			Client<SecureNodeListProvider> *cli = *it;
			if (cli == leaving){
				tmp=it;
				if (++tmp == this->toutlemonde.end()){
					tmp=this->toutlemonde.begin();
				}
				next=*tmp;
			}
		}
		auto it2=this->toutlemonde.rbegin();
		auto tmp2=it2;
		for(; it2 != this->toutlemonde.rend(); ++it2){
			Client<SecureNodeListProvider> *cli = *it2;
			if (cli == leaving){
				tmp2=it2;
				if (++tmp2 == this->toutlemonde.rend()){
					tmp2=this->toutlemonde.rbegin();
				}
				previous=*tmp2;
			}
		}

		// on delete notre client de la liste :
		auto i = std::begin(this->toutlemonde);

		while (i != std::end(this->toutlemonde)) {
			if (*i == leaving)
				i = this->toutlemonde.erase(i);
			else
				++i;
		}

		//completion des listes des deux voisins
		auto it3=this->toutlemonde.begin();
		auto tmp3=it3;
		for(; it3 != this->toutlemonde.end(); ++it3){
			Client<SecureNodeListProvider> *cli = *it3;
			if (cli == next){
				tmp3=it3;
				if (++tmp3 == this->toutlemonde.end()){
					tmp3=this->toutlemonde.begin();
				}
				ipPortOfNextNode.push_back(pair<string, int>((*tmp3)->getIpStr(), (*tmp3)->getPort()));
			}
			if (cli == previous){
				tmp3=it3;
				if (++tmp3 == this->toutlemonde.end()){
					tmp3=this->toutlemonde.begin();
				}
				ipPortOfPreviousNode.push_back(pair<string, int>((*tmp3)->getIpStr(), (*tmp3)->getPort()));
			}
		}
		auto it4=this->toutlemonde.rbegin();
		auto tmp4=it4;
		for(; it4 != this->toutlemonde.rend(); ++it4){
			Client<SecureNodeListProvider> *cli = *it4;
			if (cli == next){
				tmp4=it4;
				if (++tmp4 == this->toutlemonde.rend()){
					tmp4=this->toutlemonde.rbegin();
				}
				ipPortOfNextNode.push_front(pair<string, int>((*tmp4)->getIpStr(), (*tmp4)->getPort()));
			}
			if (cli == previous){
				tmp4=it4;
				if (++tmp4 == this->toutlemonde.rend()){
					tmp4=this->toutlemonde.rbegin();
				}
				ipPortOfPreviousNode.push_front(pair<string, int>((*tmp4)->getIpStr(), (*tmp4)->getPort()));
			}
		}

		// envoi des information aux noeuds toujours présents :
		oTextArchivePrevious << ipPortOfPreviousNode;
		Trame t2(-4, oStringStreamPrevious.str());
		cout << "/*********Trame envoyée au noeud précédent le client déconnecté" << std::endl <<
				"TTL : " << t2.getTTL() << std::endl <<
				"Commande : " << t2.getCommande() << std::endl <<
				"*********/" << std::endl;

		previous->send(t2);

		oTextArchiveNext << ipPortOfNextNode;
		Trame t3(-4, oStringStreamNext.str());
		cout << "/*********Trame envoyée au noeud suivant le client déconnecté" << std::endl <<
				"TTL : " << t3.getTTL() << std::endl <<
				"Commande : " << t3.getCommande() << std::endl <<
				"*********/" << std::endl;
		next->send(t3);
	}


}
Exemplo n.º 6
0
int main()
{
    std::thread t1(waits, 1), t2(waits, 2), t3(waits, 3), t4(signals);
    t1.join(); t2.join(), t3.join(), t4.join();
}
Exemplo n.º 7
0
int main(){
	vector< string > Flds;
	Flds.push_back("NAME");
	Flds.push_back("UIN");
	Flds.push_back("MAJOR");
	cout<<" Table Created\n\n";
	Table t(Flds);
	t.show();
	
	cout<<"Adding two rows to the table\n\n";
	
	Flds[0] = "Jane Doe";
	Flds[1] = "101010101";
	Flds[2] = "CSCE";
	bool test1 = t.addEntry(Flds);
	if(test1) cout<<"Added row 1 successfully...\n";
	else cout<<"FAILED to add row 1\n";
	
	Flds[0] = "John Smith";
	Flds[1] = "010101010";
	Flds[2] = "CPSC";
	bool test2 = t.addEntry(Flds);
	if(test2) cout<<"Added row 2 successfully...\n\n";
	else cout<<"FAILED to add row 2\n\n";
	t.show();

	Flds[0]=("NAME");
	Flds[1]=("UIN");
	Flds[2]=("MAJOR");
	Table t2(Flds);
	Flds[0]=("Paul Gaughan");
	Flds[1]=("519001954");
	Flds[2]=("ECEN"); 
	t2.addEntry(Flds);
	Flds[0] = "John Smith";
	Flds[1] = "010101010";
	Flds[2] = "CPSC";
	t2.addEntry(Flds);
	cout<< "Created second table:\n\n";
	t2.show();
	
	Table t3(t);
	bool test3 = t3.setUnion(t2);
	if(	test3){ cout<<"\nTable 3: Set Union of first and second Tables:\n\n";	t3.show();}
	else cout<<"\n Set Union Failed.  Size mismatch.\n";
	
	Table t4(t);
	bool test4 = t4.setDifference(t2);
	if(	test4){ cout<<"\nTable 4: Set Difference of first and second Tables:\n\n";	t4.show();}
	else cout<<"\n Set Difference Failed.  Size mismatch.\n";
	
	Table t5(t);
	cout<<"\nTable 5: Computing Cartesian Product of first and second tables:\n\n";
	t5.crossProduct(t2);
	t5.show();
	
	cout<<"\n\nAttempting to compute set Union and Difference of first and fifth Tables\n\n";
	bool test6 = t5.setUnion(t);
	bool test7 = t5.setDifference(t);
	cout<<"Result:  Union Allowed?: " << test6<<"  Diff Allowed?: "<<test7<<endl;
	
	cout<<"\nTable 6: Projection of Names column from Table 3\n\n";
	vector<int> columns;
	columns.push_back(0);
	Table t6 = *(t3.projection(columns));
	t6.show();
	
	cout<<"\nTable 7: Selecting Row with Name = Paul Gaughan from Table 3\n\n";
	Table t7 = *(t3.rowQuerry("Paul Gaughan", "NAME"));
	t7.show();
	
	cout<<"\nTable 8: Renaming UIN column in Table 1 to NUMBER\n\n";
	Table t8(t);
	bool test8 = t8.update("NAME", "UIN", "NUMBER");
	t8.show();

	cout<<"\n Table 9: Removing row with Key = Jane Doe from Table 1\n\n";
	Table t9(t);
	vector< string > temp = t9.removeRow("Jane Doe");
	t9.show();
	bool test9 = false;
	if (temp[0].compare("Jane Doe")==0) test9 = true;
	
	cout<<"\n\n\n\n";
	if(test1 && test2 && test3 && test4 && (!test6) &&(!test7) && test8 && test9){
		cout<<"ALL TESTS PASSED!\n";
	}else cout<<"\nFAIL!";
	
}
Exemplo n.º 8
0
Arquivo: main.cpp Projeto: CCJY/coliru
int main() {
  test t1(1);
  test t2(1, 2);
  test t3(1, 2, 3);
}
Exemplo n.º 9
0
int test_parallel(int num_threads) {
    tbb::flow::graph g;
    tbb::flow::queue_node<T> q(g);
    tbb::flow::queue_node<T> q2(g);
    tbb::flow::queue_node<T> q3(g);
    {
        Check< T > my_check;
        T bogus_value(-1);
        T j = bogus_value;
        NativeParallelFor( num_threads, parallel_puts<T>(q) );

        T *next_value = new T[num_threads];
        for (int tid = 0; tid < num_threads; ++tid) next_value[tid] = T(0);

        for (int i = 0; i < num_threads * N; ++i ) {
            spin_try_get( q, j );
            check_item( next_value, j );
            j = bogus_value;
        }
        for (int tid = 0; tid < num_threads; ++tid)  {
            ASSERT( next_value[tid] == T(N), NULL );
        }
        delete[] next_value;

        j = bogus_value;
        g.wait_for_all();
        ASSERT( q.try_get( j ) == false, NULL );
        ASSERT( j == bogus_value, NULL );

        NativeParallelFor( num_threads, parallel_puts<T>(q) );

        {
            touches< T > t( num_threads );
            NativeParallelFor( num_threads, parallel_gets<T>(q, t) );
            g.wait_for_all();
            ASSERT( t.validate_touches(), NULL );
        }
        j = bogus_value;
        ASSERT( q.try_get( j ) == false, NULL );
        ASSERT( j == bogus_value, NULL );

        g.wait_for_all();
        {
            touches< T > t2( num_threads );
            NativeParallelFor( num_threads, parallel_put_get<T>(q, t2) );
            g.wait_for_all();
            ASSERT( t2.validate_touches(), NULL );
        }
        j = bogus_value;
        ASSERT( q.try_get( j ) == false, NULL );
        ASSERT( j == bogus_value, NULL );

        tbb::flow::make_edge( q, q2 );
        tbb::flow::make_edge( q2, q3 );

        NativeParallelFor( num_threads, parallel_puts<T>(q) );
        {
            touches< T > t3( num_threads );
            NativeParallelFor( num_threads, parallel_gets<T>(q3, t3) );
            g.wait_for_all();
            ASSERT( t3.validate_touches(), NULL );
        }
        j = bogus_value;
        g.wait_for_all();
        ASSERT( q.try_get( j ) == false, NULL );
        g.wait_for_all();
        ASSERT( q2.try_get( j ) == false, NULL );
        g.wait_for_all();
        ASSERT( q3.try_get( j ) == false, NULL );
        ASSERT( j == bogus_value, NULL );

        // test copy constructor
        ASSERT( q.remove_successor( q2 ), NULL );
        NativeParallelFor( num_threads, parallel_puts<T>(q) );
        tbb::flow::queue_node<T> q_copy(q);
        j = bogus_value;
        g.wait_for_all();
        ASSERT( q_copy.try_get( j ) == false, NULL );
        ASSERT( q.register_successor( q_copy ) == true, NULL );
        {
            touches< T > t( num_threads );
            NativeParallelFor( num_threads, parallel_gets<T>(q_copy, t) );
            g.wait_for_all();
            ASSERT( t.validate_touches(), NULL );
        }
        j = bogus_value;
        ASSERT( q.try_get( j ) == false, NULL );
        ASSERT( j == bogus_value, NULL );
        ASSERT( q_copy.try_get( j ) == false, NULL );
        ASSERT( j == bogus_value, NULL );
    }

    return 0;
}
void
TensorMechanicsPlasticMohrCoulombMulti::activeConstraints(const std::vector<Real> & /*f*/, const RankTwoTensor & stress, const Real & intnl, std::vector<bool> & act) const
{
  act.assign(6, false);

  std::vector<Real> eigvals;
  stress.symmetricEigenvalues(eigvals);
  eigvals[0] += _shift;
  eigvals[2] -= _shift;

  Real sinphi = std::sin(phi(intnl));
  Real cosphi = std::cos(phi(intnl));
  Real coh = cohesion(intnl);
  Real cohcot = coh*cosphi/sinphi;

  std::vector<Real> v(3);
  v[0] = eigvals[0] - cohcot;
  v[1] = eigvals[1] - cohcot;
  v[2] = eigvals[2] - cohcot;

  // naively there are lots of different combinations
  // to try.  Eg, there are 6 yield surfaces, and so
  // for returning-to-the-tip, there are 6*5*4 possible
  // combinations of 3 yield functions that we could try.
  // However, with the constraint v0<=v1<=v2, and symmetry,
  // the following combinations of act are checked:
  // 110100 (tip) (about 43%)
  // 010101 (tip) (about 1%)
  // 010100 (edge) (about 22%)
  // 000101 (edge) (about 22%)
  // 000100 (plane) (about 12%)
  // Some other "tip" combinations are tried by
  // FiniteStrainMultiPlasticity, in about 0.001% of cases,
  // but these are not work checking.

  // these are the normals to the 6 yield surfaces (flow directions)
  std::vector<std::vector<Real> > n(6);
  Real sinpsi = std::sin(psi(intnl));
  Real oneminus = 1 - sinpsi;
  Real oneplus = 1 + sinpsi;
  n[0].resize(3);
  n[0][0] = oneplus ; n[0][1] = -oneminus ; n[0][2] = 0;
  n[1].resize(3);
  n[1][0] = -oneminus ; n[1][1] = oneplus ; n[1][2] = 0;
  n[2].resize(3);
  n[2][0] = oneplus ; n[2][1] = 0 ; n[2][2] = -oneminus;
  n[3].resize(3);
  n[3][0] = -oneminus ; n[3][1] = 0 ; n[3][2] = oneplus;
  n[4].resize(3);
  n[4][0] = 0 ; n[4][1] = oneplus ; n[4][2] = -oneminus;
  n[5].resize(3);
  n[5][0] = 0 ; n[5][1] = -oneminus ; n[5][2] = oneplus;

  // Check for return to the tip.
  // For tip-return to satisfy Kuhn-Tucker we need
  // v = a*n[a] + b*n[b] + c*n[c]
  // with a, b, and c all being non-negative (they are
  // the plasticity multipliers)

  Real denom;

  // 110100 (tip)
  denom = triple(n[0], n[1], n[3]);
  if (triple(v, n[0], n[1])/denom >= 0 && triple(v, n[1], n[3])/denom >= 0 && triple(v, n[3], n[0])/denom >= 0)
  {
    act[0] = act[1] = act[3] = true;
    return;
  }

  // 010101 (tip)
  denom = triple(n[1], n[3], n[5]);
  if (triple(v, n[1], n[3])/denom >= 0 && triple(v, n[3], n[5])/denom >= 0 && triple(v, n[5], n[1])/denom >= 0)
  {
    act[1] = act[3] = act[5] = true;
    return;
  }

  // the following are tangents to the 1, 3, and 5 yield surfaces
  // used below.
  std::vector<Real> t1(3);
  t1[0] = oneplus ; t1[1] = oneminus ; t1[2] = 0;
  std::vector<Real> t3(3);
  t3[0] = oneplus ; t3[1] = 0 ; t3[2] = oneminus;
  std::vector<Real> t5(3);
  t5[0] = 0 ; t5[1] = oneplus ; t5[2] = oneminus;


  // 010100 (edge)
  std::vector<Real> n1xn3(3);
  n1xn3[0] = oneplus ; n1xn3[1] = oneminus ; n1xn3[2] = oneminus;
  // work out the point to which we would return, "a".  It is defined by
  // f1 = 0 = f3, and that (p - a).(n1 x n3) = 0, where "p" is the
  // starting position (p = eigvals).
  // In the following a = (lam0, lam2, lam2)
  Real pdotn1xn3 = dot(eigvals, n1xn3);
  Real lam0 = pdotn1xn3 - 4*coh*cosphi*oneminus/(1 + sinphi);
  lam0 /= oneplus + 2*oneminus*(1 - sinphi)/(1 + sinphi);
  Real lam1 = lam0*(1 - sinphi)/(1 + sinphi) + 2*coh*cosphi/(1 + sinphi);
  std::vector<Real> pminusa(3);
  pminusa[0] = eigvals[0] - lam0;
  pminusa[1] = eigvals[1] - lam1;
  pminusa[2] = eigvals[2] - lam1;
  if (dot(pminusa, t3)/dot(n[1], t3) >= 0 && dot(pminusa, t1)/dot(n[3], t1) >= 0)
  {
    act[1] = act[3] = true;
    return;
  }

  // 000101 (edge)
  std::vector<Real> n3xn5(3);
  n3xn5[0] = oneplus ; n3xn5[1] = oneplus ; n3xn5[2] = oneminus;
  // work out the point to which we would return, "a".  It is defined by
  // f3 = 0 = f5, and that (p - a).(n3 x n5) = 0, where "p" is the
  // starting position (p = eigvals).
  // In the following a = (lam0, lam2, lam2)
  Real pdotn3xn5 = dot(eigvals, n3xn5);
  Real lam2 = pdotn3xn5 + 4*coh*cosphi*oneplus/(1 - sinphi);
  lam2 /= oneminus + 2*oneplus*(1 + sinphi)/(1 - sinphi);
  lam1 = lam2*(1 + sinphi)/(1 - sinphi) - 2*coh*cosphi/(1 - sinphi);
  pminusa[0] = eigvals[0] - lam1;
  pminusa[1] = eigvals[1] - lam1;
  pminusa[2] = eigvals[2] - lam2;
  if (dot(pminusa, t5)/dot(n[3], t5) >= 0 && dot(pminusa, t3)/dot(n[5], t3) >= 0)
  {
    act[3] = act[5] = true;
    return;
  }

  // 000100 (plane)
  act[3] = true;
  return;
}
Exemplo n.º 11
0
        Problem_Representation_Type const 
        operator()( Chromosome_Args ... ch_args )  
        {
            //initialize first generation randomly
            for ( std::size_t i = 0; i != population_per_generation; ++i )
                current_population.push_back( chromosome_type( ch_args... ) );

            //std::cerr << "\ninitialized " << population_per_generation << " chromosomes.\n";


            std::size_t debug_counter = 0;
            best_fitness = std::numeric_limits<Fitness_Type>::max();
            srand ( unsigned ( time (NULL) ) ); //for random_shuffle
            Fitness_Type total_fit;

            Problem_Representation_Type pr_0;
            Problem_Representation_Type pr_1;
            Problem_Representation_Type pr_2;
            Problem_Representation_Type pr_3;

            std::ofstream elite_out( "elite.dat" );
            std::ofstream elite_fit( "elite_fit.dat");
            
            for (;;)
            {
            //evaluate
                //feng::for_each( current_population.begin(), current_population.end(), [](chromosome_type& chrom) { Evaluation_Method()(Chromosome_Problem_Translation_Method()(chrom)); });
                //std::cerr << "\nevaluating........";

#if 0
                for ( auto& ch : current_population )
                    if ( ch.modification_after_last_evaluation_flag )
                    {
                        Chromosome_Problem_Translation_Method()( *(ch.chrom), pr );
                        ch.fit = Evaluation_Method()(pr);
                        //Evaluation_Method()(Chromosome_Problem_Translation_Method()(ch));
                        ch.modification_after_last_evaluation_flag = false;
                    }
#endif
#if 1
                std::thread t0( parallel_evaluator(), current_population.begin(), current_population.begin()+(current_population.size()/4), &pr_0 );
                std::thread t1( parallel_evaluator(), current_population.begin()+(current_population.size()/4), current_population.begin()+(current_population.size()/2), &pr_1 );
                std::thread t2( parallel_evaluator(), current_population.begin()+(current_population.size()/2), current_population.begin()+(current_population.size()*3/4), &pr_2 );
                std::thread t3( parallel_evaluator(), current_population.begin()+(current_population.size()*3/4), current_population.end(), &pr_3 );
                //parallel_evaluator()( current_population.begin()+(current_population.size()*3/4), current_population.end(), &pr_3 );
                t0.join();
                t1.join();
                t2.join();
                t3.join();
#endif

                //using nth_element?
                //mutate duplicated chromosome?
                std::sort( current_population.begin(), current_population.end() );

                auto const elite_one = *(current_population.begin());
                Chromosome_Problem_Translation_Method()( *(elite_one.chrom), pr );

                //keep the best individual of the current generation
                if ( elite_one.fit < best_fitness )
                {
                    debug_counter++;

                    best_fitness = elite_one.fit;
                    best_one = pr;
                    
                    elite_out << best_one;
                    elite_fit << best_fitness;


                    if ( debug_counter & 0xf )
                    {
                        elite_out << "\n";
                        elite_fit << "\n";
                    }
                    else
                    {
                        elite_out << std::endl;
                        elite_fit << std::endl;
                    }
                }

                current_population.resize( std::distance( current_population.begin(), std::unique( current_population.begin(), current_population.end() )) );
                if ( current_population.size() < population_per_generation )
                {
                    //generate someone randomly and evaluate
                    for ( std::size_t i = current_population.size(); i != population_per_generation; ++i )
                    {
                        auto ch = chromosome_type( ch_args...);
                        Chromosome_Problem_Translation_Method()( *(ch.chrom), pr );
                        ch.fit = Evaluation_Method()(pr);
                        ch.modification_after_last_evaluation_flag = false;
                        current_population.push_back( ch );
                    }
                }
                else
                {
                    //shuffle the resize
                    std::random_shuffle( current_population.begin(), current_population.end() );
                    current_population.resize( population_per_generation );
                }
    
                std::sort( current_population.begin(), current_population.end() );

                //total_fit = 0;
                //for( auto& ch : current_population )
                //    total_fit += ch.fit;
                //std::cout.precision(20);
                //std::cout << total_fit << "\n";

                //if timeout, return output elite
                auto& t_manager = feng::singleton<time_manager>::instance();
                if ( t_manager.is_timeout() )
                {
                    std::cerr << "\nthe residual for the best individual is " << best_fitness;

                    elite_out.close();
                    elite_fit.close();

                    return best_one;
                    //return pr;
                }

                //std::cerr << "\nElite of " << debug_counter++ << " is \n" << pr;
                //std::cerr << "\nElite of " << debug_counter << " is \n" << *(elite_one.chrom);


            //select 
                auto& xpm = feng::singleton<xover_probability_manager<>>::instance();
                std::size_t const selection_number = xpm(population_per_generation);
                //selected_population_for_xover_father.resize(selection_number);
                //selected_population_for_xover_mother.resize(selection_number);
                selected_population_for_xover_father.clear();
                selected_population_for_xover_mother.clear();

                //std::cerr << "\nselecting............." << selection_number;

                auto& xs_manager = feng::singleton<xover_selection_manager>::instance();
                for ( std::size_t i = 0; i != selection_number; ++i )
                {
                    //selected_population_for_xover_father[i] = current_population[xs_manager()];
                    //selected_population_for_xover_mother[i] = current_population[xs_manager()];
                    
                    const std::size_t select1 = xs_manager();
                    const std::size_t select2 = xs_manager();

                    //selected_population_for_xover_father.push_back(current_population[xs_manager()]);
                    //selected_population_for_xover_mother.push_back(current_population[xs_manager()]);
                    selected_population_for_xover_father.push_back(current_population[select1]);
                    selected_population_for_xover_mother.push_back(current_population[select2]);
                }

                //std::cerr << "\nselectedted";
            //xover
#if 0
                //not working as selected population for xover are pure reference of current populaiton
                for ( std::size_t i = 0; i != selection_number; ++i )
                    feng::for_each( selected_population_for_xover_father[i].begin(), selected_population_for_xover_father[i].end(), 
                                    selected_population_for_xover_mother[i].begin(), Chromosome_Xover_Method() );

                current_population.reserve( population_per_generation + selection_number + selection_number );
                //append newly generated genes into current population
                current_population.insert( current_population.begin()+population_per_generation, selected_population_for_xover_father.begin(), selected_population_for_xover_father.end() );
                current_population.insert( current_population.begin()+population_per_generation+selection_number, selected_population_for_xover_mother.begin(), selected_population_for_xover_mother.end() );
#endif
                //std::cerr << "\nxover.............";
                
                for ( std::size_t i = 0; i != selection_number; ++i )
                {
                    chromosome_type son( ch_args... ); 
                    chromosome_type daughter( ch_args... ); 

                    feng::for_each( selected_population_for_xover_father[i].begin(), selected_population_for_xover_father[i].end(), selected_population_for_xover_mother[i].begin(), son.begin(), daughter.begin(), Chromosome_Xover_Method() );

                    current_population.push_back( son ); 
                    current_population.push_back( daughter ); 
                }
                //mark new generation not evaluated
                feng::for_each( current_population.begin()+population_per_generation, current_population.end(), [](chromosome_type& ch) { ch.modification_after_last_evaluation_flag = true; } );

                //std::cerr << "\nxovered";

            //mutate
                //std::cerr << "\nmutating";

                auto& mpm = feng::singleton<mutation_probability_manager<>>::instance();
                mpm.reset();
                for ( auto& chromosome : current_population )
                    if ( mpm.should_mutate_current_gene() )
                    {
                        for ( auto& gene : chromosome )
                            Chromosome_Mutation_Method()(gene);
                        //makr muated ones as not evaluated
                        chromosome.modification_after_last_evaluation_flag = true;
                    }

                //std::cerr << "\nmutated";

            //goto evaluate



            }

            assert( !"Should never reach here!!" );

            return Problem_Representation_Type();
                


        }
Exemplo n.º 12
0
int main(int argc, char* argv)
{
	const int count = 100 * 10000;

	boost::asio::io_service ioService1;
	cr::network::AsyncQueue<int> queue1(ioService1);

	auto startTime = std::chrono::high_resolution_clock::now();
	std::thread t1([&]
	{
		boost::asio::io_service::work work(ioService1);
		queue1.asyncPush(1, std::bind(&push, std::ref(queue1), count, std::placeholders::_1));
		queue1.asyncPop(std::bind(&pop, std::ref(queue1), std::placeholders::_1, std::placeholders::_2));
		ioService1.run();
	});
	t1.join();
	//t2.join();
	auto topTime = std::chrono::high_resolution_clock::now();

	auto totalTime = std::chrono::duration_cast<std::chrono::microseconds>(topTime - startTime).count();
	std::cout << "microseonds: " << totalTime / 1000 << "\n"
		<< "message count: " << count << std::endl
		<< "speed :" << 1.0 * totalTime / count << "\n";

	boost::asio::io_service ioService2;
	boost::asio::io_service ioService3;
	cr::network::AsyncQueue<int, std::mutex> queue2(ioService2, ioService3);

	int count2 = count;
	for (int i = 0; i < 10; ++i)
	{
		boost::asio::spawn(ioService2, [&](boost::asio::yield_context yield)
		{
			boost::system::error_code ec;
			while (count2-- > 0)
			{
				queue2.asyncPush(1, yield[ec]);
			}
			queue2.getPushIoService().stop();
			queue2.getPopIoService().stop();
		});
	}

	boost::asio::spawn(ioService3, [&](boost::asio::yield_context yield)
	{
		boost::system::error_code ec;
		while (!ec)
		{
			int element = queue2.asyncPop(yield[ec]);
		}
	});

	auto startTime2 = std::chrono::high_resolution_clock::now();
	std::thread t2([&]
	{
		boost::asio::io_service::work work(ioService2);
		ioService2.run();
	});
	std::thread t3([&]
	{
		boost::asio::io_service::work work(ioService3);
		ioService3.run();
	});
	t2.join();
	t3.join();
	auto stopTime2 = std::chrono::high_resolution_clock::now();

	auto totalTime2 = std::chrono::duration_cast<std::chrono::microseconds>(stopTime2 - startTime2).count();
	std::cout << "microseonds: " << totalTime2 / 1000 << "\n"
		<< "message count: " << count << std::endl
		<< "speed :" << 1.0 * totalTime2 / count << "\n";

	boost::asio::io_service ioService4;
	cr::network::AsyncQueue<int, std::mutex> queue3(ioService4);
	boost::asio::spawn(ioService4, [&](boost::asio::yield_context yield)
	{
		boost::system::error_code ec;
		int element = 1;
		while (element != 0)
		{
			element = queue3.asyncPop(yield[ec]);
		}
		ioService4.stop();
	});
	auto startTime3 = std::chrono::high_resolution_clock::now();

	std::thread t4([&]
	{
		boost::asio::io_service::work work(ioService4);
		ioService4.run();
	});
	for (int i = 1; i < count; ++i)
	{
		queue3.push(i);
	}
	queue3.push(0);
	t4.join();

	auto stopTime3 = std::chrono::high_resolution_clock::now();
	auto totalTime3 = std::chrono::duration_cast<std::chrono::microseconds>(stopTime3 - startTime3).count();
	std::cout << "microseonds: " << totalTime3 / 1000 << "\n"
		<< "message count: " << count << std::endl
		<< "speed :" << 1.0 * totalTime3 / count << "\n";
}
Exemplo n.º 13
0
int main(int argc, const char * argv[])
{
    
    clock_t timer_1, timer_2;
    timer_1 = clock();
    
    std::queue<Plane> take_off_queue;
    std::queue<Plane> land_queue;
    int wind;
    Runway north_south("Runway 18-36");
    Runway east_west("Runway 9-27");
    
    
    std::thread t1(&plane_generator, &land_queue, &take_off_queue);
    std::thread t2(&wind_thread, &wind);
    std::thread t3(&take_off_thread, &wind, &take_off_queue, &north_south, &east_west);
    std::thread t4(&land_thread, &wind, &land_queue, &north_south, &east_west);
    
    
    // JOIN THREADS TO MAIN: ---------------------------------------------------
    

    // Plane Generator Thread
    if(t1.joinable())
    {
        t1.join();
    }
    else
    {
        std::cout << "Plane Generator Thread Could Not Join Main" << std::endl;
    }
    
    // Wind Generator Thread
    if(t2.joinable())
    {
        t2.join();
    }
    else
    {
        std::cout << "Wind Thread Could Not Join Main" << std::endl;
    }

    // Take Off Thread
    if(t3.joinable())
    {
        t3.join();
    }
    else
    {
        std::cout << "Take Off Thread Could Not Join Main" << std::endl;
    }
    
    // Land Thread
    if(t4.joinable())
    {
        t4.join();
    }
    else
    {
        std::cout << "Landing Thread Could Not Join Main" << std::endl;
    }

    // END OF JOINING THREADS --------------------------------------------------

    
    // DISPLAY
    
    std::cout << "\n########### Display ##########\n\n";
    
    east_west.display();
    
    std::cout << std::endl;
    
    north_south.display();
    
    
    timer_2 = clock();
    float diff = ((float)timer_2-(float)timer_1);
    diff = diff / CLOCKS_PER_SEC;
    std::cout << "Total Time: " << diff << " seconds.\n\n";
    
    return 0;
}
Exemplo n.º 14
0
/*
 * test kPolicyReadersOnly and kPolicyWritersOnly
 */
TEST(LockManagerTest, TxOnlyPolicies) {
    LockManager lm;
    ClientTransaction t1(&lm, 1);
    ClientTransaction t2(&lm, 2);
    ClientTransaction t3(&lm, 3);
    ClientTransaction t4(&lm, 4);
    ClientTransaction t5(&lm, 5);
    ClientTransaction tp(&lm, 6);

    // show kPolicyReadersOnly blocking writers, which
    // awake when policy reverts
    t1.acquire(kShared, 1, ACQUIRED);
    tp.setPolicy(LockManager::kPolicyReadersOnly, ACQUIRED);
    t3.acquire(kExclusive, 2, BLOCKED); // just policy conflict
    t4.acquire(kExclusive, 1, BLOCKED); // both policy & t1
    t5.acquire(kShared, 1, ACQUIRED);   // even tho t4
    tp.setPolicy(LockManager::kPolicyReadersFirst, ACQUIRED);
    t3.wakened();
    t3.release(kExclusive, 2);
    t1.release(kShared, 1);
    t5.release(kShared, 1);
    t4.wakened();
    t4.release(kExclusive, 1);

    // show WRITERS_ONLY blocking readers, which
    // awake when policy reverts
    t1.acquire(kExclusive, 1, ACQUIRED);
    tp.setPolicy(LockManager::kPolicyWritersOnly, ACQUIRED);
    t3.acquire(kShared, 2, BLOCKED);       // just policy conflict
    t4.acquire(kShared, 1, BLOCKED);       // both policy & t1
    t1.release(kExclusive, 1);
    t5.acquire(kExclusive, 2, ACQUIRED);   // even tho t3
    t5.release(kExclusive, 2);
    tp.setPolicy(LockManager::kPolicyReadersFirst, ACQUIRED);
    t3.wakened();
    t3.release(kShared, 2);
    t4.wakened();
    t4.release(kShared, 1);

    // show READERS_ONLY blocked by existing writer
    // but still blocking new writers
    t1.acquire(kExclusive, 1, ACQUIRED);
    tp.setPolicy(LockManager::kPolicyReadersOnly, BLOCKED);  // blocked by t1
    t2.acquire(kExclusive, 2, BLOCKED);   // just policy conflict
    t3.acquire(kShared, 2, ACQUIRED);     // even tho t2
    t3.release(kShared, 2);
    t1.release(kExclusive, 1);
    tp.wakened();
    tp.setPolicy(LockManager::kPolicyReadersFirst, ACQUIRED);
    t2.wakened();
    t2.release(kExclusive, 2);

    // show WRITERS_ONLY blocked by existing reader
    // but still blocking new readers
    t1.acquire(kShared, 1, ACQUIRED);
    tp.setPolicy(LockManager::kPolicyWritersOnly, BLOCKED);  // blocked by t1
    t2.acquire(kShared, 2, BLOCKED);      // just policy conflict
    t1.release(kShared, 1);
    tp.wakened();
    tp.setPolicy(LockManager::kPolicyReadersFirst, ACQUIRED);
    t2.wakened();
    t2.release(kShared, 2);

    t1.quit();
    t2.quit();
    t3.quit();
    t4.quit();
    t5.quit();
    tp.quit();
}
Exemplo n.º 15
0
/*!
    \relates QGLCubeSphere

    Builds the geometry for \a sphere within the specified
    display \a list.
*/
QGLBuilder& operator<<(QGLBuilder& list, const QGLCubeSphere& sphere)
{
    /*
              A-----H
              |     |
              |     |
        A-----D-----E-----H-----A
        |     |     |     |     |
        |     |     |     |     |
        B-----C-----F-----G-----B
              |     |
              |     |
              B-----G

       ^  d  e
       |  c  f
       y  
        x-->
    */

    qreal scale = sphere.diameter();
    int depth = sphere.subdivisionDepth();

    const qreal offset = 1.0f;
    float cube[8][3] = {
        { -offset,  offset, -offset},    // A - 0
        { -offset, -offset, -offset },   // B - 1
        { -offset, -offset,  offset },   // C - 2
        { -offset,  offset,  offset },  // D - 3
        {  offset,  offset,  offset },   // E - 4
        {  offset, -offset,  offset },    // F - 5
        {  offset, -offset, -offset },   // G - 6
        {  offset,  offset, -offset },  // H - 7
    };

    int face[6][4] = {
        { 0, 1, 2, 3 }, // A-B-C-D
        { 3, 2, 5, 4 }, // D-C-F-E
        { 4, 5, 6, 7 }, // E-F-G-H
        { 7, 6, 1, 0 }, // H-G-B-A
        { 0, 3, 4, 7 }, // A-D-E-H
        { 2, 1, 6, 5 }, // C-B-G-F
    };

    const float v3 = 0.0f;
    const float v2 = 0.333333333f;
    const float v1 = 0.666666666f;
    const float v0 = 1.0f;

    const float u0 = 0.0f;
    const float u1 = 0.25f;
    const float u2 = 0.5f;
    const float u3 = 0.75f;
    const float u4 = 1.0f;

    float tex[6][4][2] = {
        { {u0, v1}, {u0, v2}, {u1, v2}, {u1, v1} }, // A-B-C-D
        { {u1, v1}, {u1, v2}, {u2, v2}, {u2, v1} }, // D-C-F-E
        { {u2, v1}, {u2, v2}, {u3, v2}, {u3, v1} }, // E-F-G-H
        { {u3, v1}, {u3, v2}, {u4, v2}, {u4, v1} }, // H-G-B-A
        { {u1, v0}, {u1, v1}, {u2, v1}, {u2, v0} }, // A-D-E-H
        { {u1, v2}, {u1, v3}, {u2, v3}, {u2, v2} }, // C-B-G-F
    };

    // Generate the initial vertex list from a plain cube.
    QVector3DArray vertices;
    QVector3DArray normals;
    QVector2DArray texCoords;
    for (int ix = 0; ix < 6; ++ix) {
        QVector3D n0(cube[face[ix][0]][0], cube[face[ix][0]][1], cube[face[ix][0]][2]);
        QVector3D n1(cube[face[ix][1]][0], cube[face[ix][1]][1], cube[face[ix][1]][2]);
        QVector3D n2(cube[face[ix][2]][0], cube[face[ix][2]][1], cube[face[ix][2]][2]);
        QVector3D n3(cube[face[ix][3]][0], cube[face[ix][3]][1], cube[face[ix][3]][2]);

        QVector2D t0(tex[ix][0][0], tex[ix][0][1]);
        QVector2D t1(tex[ix][1][0], tex[ix][1][1]);
        QVector2D t2(tex[ix][2][0], tex[ix][2][1]);
        QVector2D t3(tex[ix][3][0], tex[ix][3][1]);

        n0 = n0.normalized();
        n1 = n1.normalized();
        n2 = n2.normalized();
        n3 = n3.normalized();

        QVector3D v0 = n0 * scale / 2.0f;
        QVector3D v1 = n1 * scale / 2.0f;
        QVector3D v2 = n2 * scale / 2.0f;
        QVector3D v3 = n3 * scale / 2.0f;

        vertices.append(v0, v1, v2, v3);
        normals.append(n0, n1, n2, n3);
        texCoords.append(t0, t1, t2, t3);
    }

    // Subdivide the cube.
    while (depth-- > 1) {
        QVector3DArray newVertices;
        QVector3DArray newNormals;
        QVector2DArray newTexCoords;

        int count = vertices.count();
        for (int i = 0; i < count; i+= 4) {
            QVector3D v0 = vertices.at(i);
            QVector3D v1 = vertices.at(i+1);
            QVector3D v2 = vertices.at(i+2);
            QVector3D v3 = vertices.at(i+3);

            QVector3D n0 = normals.at(i);
            QVector3D n1 = normals.at(i+1);
            QVector3D n2 = normals.at(i+2);
            QVector3D n3 = normals.at(i+3);

            QVector2D t0 = texCoords.at(i);
            QVector2D t1 = texCoords.at(i+1);
            QVector2D t2 = texCoords.at(i+2);
            QVector2D t3 = texCoords.at(i+3);

            QVector3D n01 = (v0 + v1).normalized();
            QVector3D n12 = (v1 + v2).normalized();
            QVector3D n23 = (v2 + v3).normalized();
            QVector3D n30 = (v3 + v0).normalized();
            QVector3D nc = (v0 + v1 + v2 + v3).normalized();
            QVector3D v01 = n01 * scale / 2.0f;
            QVector3D v12 = n12 * scale / 2.0f;
            QVector3D v23 = n23 * scale / 2.0f;
            QVector3D v30 = n30 * scale / 2.0f;
            QVector3D vc = nc * scale / 2.0f;

            QVector2D t01 = (t0 + t1) / 2;
            QVector2D t12 = (t1 + t2) / 2;
            QVector2D t23 = (t2 + t3) / 2;
            QVector2D t30 = (t3 + t0) / 2;
            QVector2D tc = (t2 + t0) / 2;

            newVertices.append(v0, v01, vc, v30);
            newNormals.append(n0, n01, nc, n30);
            newTexCoords.append(t0, t01, tc, t30);

            newVertices.append(v01, v1, v12, vc);
            newNormals.append(n01, n1, n12, nc);
            newTexCoords.append(t01, t1, t12, tc);

            newVertices.append(vc, v12, v2, v23);
            newNormals.append(nc, n12, n2, n23);
            newTexCoords.append(tc, t12, t2, t23);

            newVertices.append(v30, vc, v23, v3);
            newNormals.append(n30, nc, n23, n3);
            newTexCoords.append(t30, tc, t23, t3);
        }

        vertices = newVertices;
        normals = newNormals;
        texCoords = newTexCoords;
    }

    // Add the final vertices to the display list.
    QGeometryData prim;
    prim.appendVertexArray(vertices);
    prim.appendNormalArray(normals);
    prim.appendTexCoordArray(texCoords);
    list.addTriangles(prim);
    return list;
}
Exemplo n.º 16
0
void testTensors() {
	Tensor1<float> t(10);
	for(int i=0;i<t.length();i++) {
		t(i) = (float)rand();
	}

	t.print();

	Tensor2<float> t2(3, 2);
	for(int i=0;i<t2.dim(0);i++) {
		for(int j=0;j<t2.dim(1);j++) {
			t2(i, j) = (float)(rand() % 16);
		}
	}

	t2.print("T2");

	t2.unfold().print();


	Tensor3<float> t3(2, 3, 4);
	for(int i=0;i<t3.dim(0);i++) {
		for(int j=0;j<t3.dim(1);j++) {
			for(int k=0;k<t3.dim(2);k++) {
				t3(i, j, k) = (float)(rand() % 32 );
			}			
		}
	}

	t3.print("T3");

	cout << "unfold in mode 0:" << endl;
	Tensor2<float> t3_unfold0 = t3.unfold(0);
	t3_unfold0.print("T30");
	Tensor3<float> t3new = Tensor3<float>::fold(t3_unfold0, 0, 2, 3, 4);
	t3new.print("fold back");

	cout << "unfold in mode 1:" << endl;
	Tensor2<float> t3_unfold1 = t3.unfold(1);
	t3_unfold1.print("T31");
	Tensor3<float> t3new2 = Tensor3<float>::fold(t3_unfold1, 1, 2, 3, 4);
	t3new2.print("fold back");

	cout << "unfold in mode 1:" << endl;
	Tensor2<float> t3_unfold2 = t3.unfold(2);
	t3_unfold2.print("T32");
	Tensor3<float> t3new3 = Tensor3<float>::fold(t3_unfold2, 2, 2, 3, 4);
	t3new3.print("fold back");

	cout << "mode product" << endl;
	Tensor3<float> tm0 = t3.modeProduct(t2, 0);
	tm0.print("TM0");	

	Tensor2<float> t22(3, 3);
	for(int i=0;i<t22.dim(0);i++) {
		for(int j=0;j<t22.dim(1);j++) {
			t22(i, j) = (float)(rand() % 16);
		}
	}
	t22.print("T22");

	Tensor3<float> tm1 = t3.modeProduct(t22, 1);
	tm1.print("TM1");

	Tensor2<float> t23(3, 4);
	for(int i=0;i<t23.dim(0);i++) {
		for(int j=0;j<t23.dim(1);j++) {
			t23(i, j) = (float)(rand() % 16);
		}
	}
	t23.print("T23");

	Tensor3<float> tm2 = t3.modeProduct(t23, 2);
	tm2.print("TM2");

	auto comp = t3.svd();
	auto tcore = std::get<0>(comp);
	auto tu0 = std::get<1>(comp);
	auto tu1 = std::get<2>(comp);
	auto tu2 = std::get<3>(comp);

	tcore.print("core");
	tu0.print("u0");
	tu1.print("u1");
	tu2.print("u2");

	auto trecon = tcore.modeProduct(tu0, 0)
		.modeProduct(tu1, 1)
		.modeProduct(tu2, 2);
	trecon.print("recon");
	t3.print("ref");

	int ms[3] = {0, 1, 2};
	int ds[3] = {2, 3, 4};
	vector<int> modes(ms, ms+3);
	vector<int> dims(ds, ds+3);
	auto comp2 = t3.svd(modes, dims);

	tcore = std::get<0>(comp2);
	auto tus = std::get<1>(comp2);
	tcore.print("core");
	trecon = tcore;
	for(int i=0;i<modes.size();i++) {
		auto tui = tus[i];
		trecon = trecon.modeProduct(tui, modes[i]);
		tui.print("ui");
	}

	trecon.print("recon");
	t3.print("ref");
}
Exemplo n.º 17
0
int main()
{
	try {
		{
			std::cout << "Test execution" << std::endl;
			TEST(!called_);
			booster::thread t(caller);
			t.join();
			TEST(called_);
		}
		{
			std::cout << "Functor destruction" << std::endl;
			TEST(counted_functor::objects==0);
			{
				counted_functor f;
				booster::thread t(f);
				TEST(counted_functor::objects>=2);
				t.join();
				TEST(counted_functor::objects==1);
			}
			TEST(counted_functor::objects==0);
			{
				{
                    counted_functor f;
                    booster::thread t(f);
                    TEST(counted_functor::objects>=2);
                    t.detach();
                }
				TEST(counted_functor::objects>=1);
                booster::ptime::millisleep(400);
                TEST(counted_functor::objects==0);
			}
			
		}
		std::cout << "Test recursive mutex" << std::endl;
		{
			booster::recursive_mutex m;
			m.lock();
			m.lock();
			TEST("Double lock works");
			m.unlock();
			m.unlock();
			TEST("Got there");
		}
		{
			variable = 0;
			booster::recursive_mutex m;
			incrementer<booster::recursive_mutex> inc = { &m };
			booster::thread t1(inc);
			booster::thread t2(inc);
			t1.join();
			t2.join();
			TEST(variable == 10);
		}
		std::cout << "Test mutex" << std::endl;
		{
			variable = 0;
			booster::mutex m;
			incrementer<booster::mutex> inc = { &m };
			booster::thread t1(inc);
			booster::thread t2(inc);
			t1.join();
			t2.join();
			TEST(variable == 10);
		}
		std::cout << "Test thread specific" << std::endl;
		{
			booster::thread_specific_ptr<tls_object> p;
			tls_functor f1(p);
			tls_functor f2(p);
			tls_functor f3(p);
			booster::thread t1(f1);
			booster::thread t2(f2);
			booster::thread t3(f3);

			t1.join();
			t2.join();
			t3.join();

			TEST(tls_ok);
			TEST(dtor_called == 3);
		}
		std::cout << "Non synchronous thread specific" << std::endl;
		{
			dtor_called = 0;
			booster::thread_specific_ptr<tls_object> *p = new booster::thread_specific_ptr<tls_object>();
			
			tls_functor2 f1(*p);
			tls_functor2 f2(*p);
			tls_functor2 f3(*p);

			booster::thread t1(f1);
			booster::thread t2(f2);
			booster::thread t3(f3);

			booster::ptime::millisleep(300);
			delete p;
			
			t1.join();
			t2.join();
			t3.join();

			TEST(dtor_called == 3);
		}
		std::cout << "Thest conditional variable notify one" << std::endl;
		{
			int counter = 0;
			booster::mutex m;
			booster::condition_variable c;
			cond_incrementer inc = { &counter, &m , &c };
			booster::thread t1(inc);
			booster::thread t2(inc);
			booster::thread t3(inc);
			booster::ptime::millisleep(100);
			TEST(counter == 0);
			c.notify_one();
			booster::ptime::millisleep(100);
			TEST(counter == 1);
			c.notify_one();
			booster::ptime::millisleep(100);
			TEST(counter == 2);
			c.notify_one();
			booster::ptime::millisleep(100);
			TEST(counter == 3);
			t1.join();
			t2.join();
			t3.join();
		}
		std::cout << "Thest conditional variable notify all" << std::endl;
		{
			int counter[3] = { 0, 0 , 0 };
			booster::mutex m;
			booster::condition_variable c;
			cond_incrementer inc = { counter, &m , &c };
			booster::thread t1(inc);
			inc.counter++;
			booster::thread t2(inc);
			inc.counter++;
			booster::thread t3(inc);
			booster::ptime::millisleep(100);
			TEST(counter[0]==0 && counter[1]==0 && counter[2]==0);
			c.notify_all();
			booster::ptime::millisleep(100);
			TEST(counter[0]==1 && counter[1]==1 && counter[2]==1);
			t1.join();
			t2.join();
			t3.join();
		}
		std::cout << "Test shared_mutex write lock" << std::endl;
		{
			variable = 0;
			booster::shared_mutex m;
			incrementer<booster::shared_mutex> inc = { &m };
			booster::thread t1(inc);
			booster::thread t2(inc);
			t1.join();
			t2.join();
			TEST(variable == 10);
		}
		std::cout << "Test recursive_shared_mutex write lock" << std::endl;
		{
			variable = 0;
			booster::shared_mutex m;
			incrementer<booster::shared_mutex> inc = { &m };
			booster::thread t1(inc);
			booster::thread t2(inc);
			t1.join();
			t2.join();
			TEST(variable == 10);
		}
		std::cout << "Test shared_mutex shared/write lock" << std::endl;
		{
			booster::mutex fm;
			booster::shared_mutex sm;
			bool flags[3] = {false,false,false};
			bool mread_happened  = false;
			bool write_happened = false;
			bool error_occured = false ;
			rw_executor<booster::shared_mutex> exec1 = { flags + 0, true, &fm, &sm };
			rw_executor<booster::shared_mutex> exec2 = { flags + 1, true, &fm, &sm };
			rw_executor<booster::shared_mutex> exec3 = { flags + 2, true, &fm, &sm };
			booster::thread t1(exec1);
			booster::thread t2(exec2);
			booster::thread t3(exec3);

			for(int i=0;i<100;i++) {
				booster::ptime::millisleep(1);
				{
					booster::unique_lock<booster::mutex> l(fm);
					if(flags[0] && flags[1])
						mread_happened = true;
					if(flags[2])
						write_happened = true;
					if((flags[0] || flags[1]) && flags[2])
						error_occured = true;
				}
			}

			t1.join();
			t2.join();
			t3.join();

			TEST(mread_happened);
			TEST(write_happened);
			TEST(error_occured);
		}
		std::cout << "Test recursive_shared_mutex shared/write lock" << std::endl;
		{
			booster::mutex fm;
			booster::recursive_shared_mutex sm;
			bool flags[3] = {false,false,false};
			bool mread_happened  = false;
			bool write_happened = false;
			bool error_occured = false ;
			rw_executor<booster::recursive_shared_mutex> exec1 = { flags + 0, true, &fm, &sm };
			rw_executor<booster::recursive_shared_mutex> exec2 = { flags + 1, true, &fm, &sm };
			rw_executor<booster::recursive_shared_mutex> exec3 = { flags + 2, true, &fm, &sm };
			booster::thread t1(exec1);
			booster::thread t2(exec2);
			booster::thread t3(exec3);

			for(int i=0;i<100;i++) {
				booster::ptime::millisleep(1);
				{
					booster::unique_lock<booster::mutex> l(fm);
					if(flags[0] && flags[1])
						mread_happened = true;
					if(flags[2])
						write_happened = true;
					if((flags[0] || flags[1]) && flags[2])
						error_occured = true;
				}
			}

			t1.join();
			t2.join();
			t3.join();

			TEST(mread_happened);
			TEST(write_happened);
			TEST(error_occured);
		}
		std::cout << "Test recursive_shared_mutex recursive shared lock" << std::endl;
		{
			booster::recursive_shared_mutex l;
			bool read  = false;
			bool write = false;
			rw_shared_thread t1c = { &l, &read };
			rw_unique_thread t2c = { &l, &write };
			booster::thread t1(t1c);
			booster::thread t2(t2c);
			t1.join();
			t2.join();
			TEST(read);
			TEST(write);
		}

}
	catch(std::exception const &e)
	{
		std::cerr << "Fail:" <<e.what();
		return EXIT_FAILURE;
	}
	std::cout << "Ok" << std::endl;
	return EXIT_SUCCESS;
	
}
Exemplo n.º 18
0
int CradleGame::Update()
{
	m_camera->Update();

	static float lasttime = 0.0f;

	float f = m_timer->UpdateFoo();


	std::thread t1(UpdateActor2, m_Actor, 0, 500, m_timer);
	std::thread t2(UpdateActor2, m_Actor, 500, 500, m_timer);
	std::thread t3(UpdateActor2, m_Actor, 1000, 500, m_timer);
	std::thread t4(UpdateActor2, m_Actor, 1500, 500, m_timer);
	std::thread t5(UpdateActor2, m_Actor, 2000, 500, m_timer);
	std::thread t6(UpdateActor2, m_Actor, 2500, 500, m_timer);


	t1.join();
	t2.join();
	t3.join();
	t4.join();
	t5.join();
	t6.join();

	wprintf_s(L"Actors.Update: %f\n", m_timer->UpdateFoo() - f);

	/*
	for (unsigned short i = 0; i < m_numActors; i++)
	{
		m_Actor[i].Update(m_timer);
	}
	*/



	
	/* */
	



	// STARTING HERE
	
	static char UPDATUS = 0;
	/*
	if (UPDATUS == 0 || true)
	{
		UPDATUS++;


		for (unsigned short i = 0; i < m_numActors; i++)
		{
			m_instanceData[i].world0 = DirectX::XMFLOAT4(m_Actor[i].m_mWorld.m[0]);
			m_instanceData[i].world1 = DirectX::XMFLOAT4(m_Actor[i].m_mWorld.m[1]);
			m_instanceData[i].world2 = DirectX::XMFLOAT4(m_Actor[i].m_mWorld.m[2]);
			m_instanceData[i].world3 = DirectX::XMFLOAT4(m_Actor[i].m_mWorld.m[3]);
		}
	}

	*/

	
	// END HERE
	/*
	D3D11_MAPPED_SUBRESOURCE ms;
	m_cd3d->m_d3dContext->Map(m_instanceBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &ms);
	memcpy(ms.pData, m_instanceData, sizeof(CradleVertexDeclarations::InstanceData) * m_numActors);
	m_cd3d->m_d3dContext->Unmap(m_instanceBuffer, 0);
	*/





	if (m_cInput->KeyPressed(DIK_ESCAPE))
		PostQuitMessage(0);

	return 0;
}
Exemplo n.º 19
0
long long t4 (void)
{
  long long i;
  t3 ((i = 4096) + 0x7fffffffULL);
  return i;
}
Exemplo n.º 20
0
void SecureNodeListProvider::sendVoisins(Client<SecureNodeListProvider> *to){
	cout << "Envoi des voisins d'un noeud" << std::endl;
	std::ostringstream oStringStream;
	std::ostringstream oStringStreamPrevious;
	std::ostringstream oStringStreamNext;
	boost::archive::text_oarchive oTextArchive(oStringStream);
	boost::archive::text_oarchive oTextArchivePrevious(oStringStreamPrevious);
	boost::archive::text_oarchive oTextArchiveNext(oStringStreamNext);

	list<pair <string, int> > ipPortVoisins;
	Client<SecureNodeListProvider> *previous=NULL;
	list<pair <string, int> > ipPortOfPreviousNode;
	Client<SecureNodeListProvider> *next=NULL;
	list<pair <string, int> > ipPortOfNextNode;

	if (this->toutlemonde.size() == 1){
		ipPortVoisins.push_front(pair<string, int>("0.0.0.0", 0));
		ipPortVoisins.push_back(pair<string, int>("0.0.0.0", 0));
	}
	else{
		// Completion le la liste de voisins et enregistrement des précédents et suivants
		auto it=this->toutlemonde.begin();
		auto tmp=it;
		for(; it != this->toutlemonde.end(); ++it){
			Client<SecureNodeListProvider> *cli = *it;
			if (cli == to){
				tmp=it;
				if (++tmp == this->toutlemonde.end()){
					tmp=this->toutlemonde.begin();
				}
				next=*tmp;
				ipPortVoisins.push_back(pair<string, int>(next->getIpStr(), next->getPort()));
			}
		}
		auto it2=this->toutlemonde.rbegin();
		auto tmp2=it2;
		for(; it2 != this->toutlemonde.rend(); ++it2){
			Client<SecureNodeListProvider> *cli = *it2;
			if (cli == to){
				tmp2=it2;
				if (++tmp2 == this->toutlemonde.rend()){
					tmp2=this->toutlemonde.rbegin();
				}
				previous=*tmp2;
				ipPortVoisins.push_front(pair<string, int>(previous->getIpStr(), previous->getPort()));
			}
		}

		//completion des listes des deux voisins

		auto it3=this->toutlemonde.begin();
		auto tmp3=it3;
		for(; it3 != this->toutlemonde.end(); ++it3){
			Client<SecureNodeListProvider> *cli = *it3;
			if (cli == next){
				tmp3=it3;
				if (++tmp3 == this->toutlemonde.end()){
					tmp3=this->toutlemonde.begin();
				}
				ipPortOfNextNode.push_back(pair<string, int>((*tmp3)->getIpStr(), (*tmp3)->getPort()));
			}
			if (cli == previous){
				tmp3=it3;
				if (++tmp3 == this->toutlemonde.end()){
					tmp3=this->toutlemonde.begin();
				}
				ipPortOfPreviousNode.push_back(pair<string, int>((*tmp3)->getIpStr(), (*tmp3)->getPort()));
			}
		}
		auto it4=this->toutlemonde.rbegin();
		auto tmp4=it4;
		for(; it4 != this->toutlemonde.rend(); ++it4){
			Client<SecureNodeListProvider> *cli = *it4;
			if (cli == next){
				tmp4=it4;
				if (++tmp4 == this->toutlemonde.rend()){
					tmp4=this->toutlemonde.rbegin();
				}
				ipPortOfNextNode.push_front(pair<string, int>((*tmp4)->getIpStr(), (*tmp4)->getPort()));
			}
			if (cli == previous){
				tmp4=it4;
				if (++tmp4 == this->toutlemonde.rend()){
					tmp4=this->toutlemonde.rbegin();
				}
				ipPortOfPreviousNode.push_front(pair<string, int>((*tmp4)->getIpStr(), (*tmp4)->getPort()));
			}
		}
	}

	oTextArchive << ipPortVoisins;
	Trame t(-4, oStringStream.str());
	cout << "/*********Trame réponse" << std::endl <<
			"TTL : " << t.getTTL() << std::endl <<
			"Commande : " << t.getCommande() << std::endl <<
			"*********/" << std::endl;
	to->send(t);

	if (this->toutlemonde.size() != 1){
		oTextArchivePrevious << ipPortOfPreviousNode;
		Trame t2(-4, oStringStreamPrevious.str());
		cout << "/*********Trame vers le précédent Précédent" << std::endl <<
				"TTL : " << t2.getTTL() << std::endl <<
				"Commande : " << t2.getCommande() << std::endl <<
				"*********/" << std::endl;
        previous->send(t2);

		oTextArchiveNext << ipPortOfNextNode;
		Trame t3(-4, oStringStreamNext.str());
		cout << "/*********Trame Svers le Suivant" << std::endl <<
				"TTL : " << t3.getTTL() << std::endl <<
				"Commande : " << t3.getCommande() << std::endl <<
				"*********/" << std::endl << std::endl;
        next->send(t3);
	}
}
Exemplo n.º 21
0
int main(int argc, char** argv)
{
	try
	{
		float size = 142.0;
		float delta = 654.0;

		aram::Grid g;
		aram::TagInfo t1(21,aram::Point2D(0.0,0.0),size);
		aram::TagInfo t2(22,aram::Point2D(0.0,delta),size);
		aram::TagInfo t3(19,aram::Point2D(delta,delta),size);
		aram::TagInfo t4(20,aram::Point2D(delta,0.0),size);
		
		g.addTagInfo(t1);
		g.addTagInfo(t2);
		g.addTagInfo(t3);
		g.addTagInfo(t4);
		aram::Chessboard *coord = new aram::Chessboard(g);


		// Detection parameters :
		// -> Region of interest detection
		// -> Tag validator USE HAMMINGTAG FOR MULTI TRACKING !
		typedef aram::TagDetector<aram::EdgeDetector,aram::HammingTag> myDetector;
		
		// Tag detector instanciation
		myDetector *detector = new myDetector();
		
		// Intrinsics parameters
		aram::Intrinsics intr("C:\\camera_data.xml");
		
		// Video input (see openCV doc)
		cv::VideoCapture cap(0); // use default video (usually your webcam)
		if(!cap.isOpened()) throw std::exception();
		
		cv::Mat frame;

		// Main loop
		while(true)
       	{
			// next frame from video input 
			cap >> frame;
						
			// Tag detection
			detector->detect(frame);
						
			// Intrinsics parameters
			aram::Intrinsics intr("C:\\camera_data.xml");

			// Tag list iterator
			aram::iteratorTag it;
			
			for(it=detector->begin();it!=detector->end();++it)
			{
				aram::vecPoint2D corners = (*it)->corners();

				for(unsigned int i=0;i<corners.size();++i)
				{
					cv::line(frame,corners[i%4],corners[(i+1)%4],cv::Scalar(100,150,150),2);
				}
			}

			// If any tags was detected
			if(detector->begin()!=detector->end())
			{
				// Get extrinsics parameters
				aram::Extrinsics e = coord->compute(detector->begin(),detector->end(),intr);

				// Project 3D world coordinate -> 2D image coordinate
				aram::Point2D o = e.project(aram::Point3D(0.0,0.0,0.0));
				aram::Point2D x = e.project(aram::Point3D(delta,0.0,0.0));
				aram::Point2D y = e.project(aram::Point3D(0.0,delta,0.0));
				aram::Point2D z = e.project(aram::Point3D(0.0,0.0,delta/2.0));

				// draw axis
				cv::line(frame,o,x,cv::Scalar(200,0,0),2);
				cv::line(frame,o,y,cv::Scalar(0,200,0),2);
				cv::line(frame,o,z,cv::Scalar(0,0,200),2);
			}
	
			// render
			cv::imshow("render", frame);
			// GUI refresh (see openCV doc)
			if(cv::waitKey(10)>=0) break;
		}
	}
	catch(std::exception &)
	{
	}

	return 0;
}
Exemplo n.º 22
0
TEST(LockManagerTest, TxUpgrade) {
    LockManager lm(LockManager::kPolicyReadersFirst);
    ClientTransaction t1(&lm, 1);
    ClientTransaction t2(&lm, 2);
    ClientTransaction t3(&lm, 3);

    ClientTransaction a2(&lm, 4);
    ClientTransaction a3(&lm, 5);

    // test upgrade succeeds, blocks subsequent reads
    t1.acquire(kShared, 1, ACQUIRED);
    t1.acquire(kExclusive, 1, ACQUIRED); // upgrade
    t2.acquire(kShared, 1, BLOCKED);
    t1.release(kExclusive, 1);
    t2.wakened();
    t1.release(kShared, 1);
    t2.release(kShared, 1);

    // test upgrade blocks, then wakes
    t1.acquire(kShared, 1, ACQUIRED);
    t2.acquire(kShared, 1, ACQUIRED);
    // t1 can't use resource 1 exclusively yet, because t2 is using it
    t1.acquire(kExclusive, 1, BLOCKED);
    t2.release(kShared, 1);
    t1.wakened(); // with t2's shared lock released, t1 wakes
    t1.release(kExclusive, 1);
    t1.release(kShared, 1);

    // test upgrade blocks on several, then wakes
    t1.acquire(kShared, 1, ACQUIRED);
    t2.acquire(kShared, 1, ACQUIRED);
    // t1 can't use resource 1 exclusively yet, because t2 is using it
    t1.acquire(kExclusive, 1, BLOCKED);
    t3.acquire(kShared, 1, ACQUIRED); // additional blocker
    t2.release(kShared, 1); // t1 still blocked
    t3.release(kShared, 1);
    t1.wakened(); // with t3's shared lock released, t1 wakes
    t1.release(kExclusive, 1);
    t1.release(kShared, 1);

    // failure to upgrade
    t1.acquire(kShared, 1, ACQUIRED);
    a2.acquire(kShared, 1, ACQUIRED);
    t1.acquire(kExclusive, 1, BLOCKED);
    a2.acquire(kExclusive, 1, ABORTED);
    // with a2's abort, t1 can wake
    t1.wakened();
    t1.release(kShared, 1);
    t1.release(kExclusive, 1);

    // failure to upgrade
    t1.acquire(kShared, 1, ACQUIRED);
    t2.acquire(kShared, 1, ACQUIRED);
    t1.acquire(kExclusive, 1, BLOCKED);
    a3.acquire(kShared, 1, ACQUIRED);
    t2.release(kShared, 1); // t1 still blocked on a3
    a3.acquire(kExclusive, 1, ABORTED);

    t1.quit();
    t2.quit();
    t3.quit();
}