Пример #1
0
int test_main( int /* argc */, char* /* argv */[] )
{
    const char * testfile = boost::archive::tmpnam(NULL);
    
    BOOST_REQUIRE(NULL != testfile);

    const A *ta = new A();
    A *ta1 = NULL;

    {   
        test_ostream os(testfile, TEST_STREAM_FLAGS);
        test_oarchive oa(os, TEST_ARCHIVE_FLAGS);
        oa << boost::serialization::make_nvp("ta", ta);
    }
    {
        test_istream is(testfile, TEST_STREAM_FLAGS);
        test_iarchive ia(is, TEST_ARCHIVE_FLAGS);
        ia >> boost::serialization::make_nvp("ta", ta1);
    }
    BOOST_CHECK(ta != ta1);
    BOOST_CHECK(*ta == *ta1);
    std::remove(testfile);
    return EXIT_SUCCESS;
}
Пример #2
0
int test_main( int /* argc */, char* /* argv */[] )
{
    const char * testfile = boost::archive::tmpnam(NULL);
    BOOST_REQUIRE(NULL != testfile);

    // test array of objects
    std::queue<A> aqueue, aqueue1;
    aqueue.push(A());
    aqueue.push(A());
    {
        test_ostream os(testfile, TEST_STREAM_FLAGS);
        test_oarchive oa(os, TEST_ARCHIVE_FLAGS);
        oa << boost::serialization::make_nvp("aqueue",aqueue);
    }
    {
        test_istream is(testfile, TEST_STREAM_FLAGS);
        test_iarchive ia(is, TEST_ARCHIVE_FLAGS);
        ia >> boost::serialization::make_nvp("aqueue",aqueue1);
    }
    BOOST_CHECK(aqueue == aqueue1);

    std::remove(testfile);
    return EXIT_SUCCESS;
}
Пример #3
0
 void CheckPoint::load(DispatcherMessage *dispMsg, DispatcherNode *dispNode) {
     console.ConsoleOut("Восстановление из контрольной точки включено");
     std::fstream check("check.txt");
     std::size_t count = 0;
     if(check) {
         console.ConsoleOut("Начинаю восстановление из глобальной контрольной точки");
         console.ConsoleOut("Всего задач: " + std::to_string(dispMsg -> getReserveSizeQueueFinal()));
         while (!check.eof()) {
             Elem out;
             try {
                 boost::archive::text_iarchive ia(check);
                 ia >> out;
             }
             catch(...) {
                 break;
             }
             console.ConsoleOut("Восстанавливаю задачу: " + std::to_string(out.getNumberInVectorTask()));
             count++;
             dispMsg -> addFinalTask(out.getOutArgs());
             dispNode -> setTrues(out.getNumberInVectorTask());
         }
         console.ConsoleOut("Восстановлено из контрольной точки " + std::to_string(count) + "/" + std::to_string(dispMsg -> getReserveSizeQueueFinal()));
     }
     else {
Пример #4
0
int test_vector(T)
{
    const char * testfile = boost::archive::tmpnam(NULL);
    BOOST_REQUIRE(NULL != testfile);

    // test array of objects
    std::vector<T> avector;
    avector.push_back(T());
    avector.push_back(T());
    {   
        test_ostream os(testfile, TEST_STREAM_FLAGS);
        test_oarchive oa(os, TEST_ARCHIVE_FLAGS);
        oa << boost::serialization::make_nvp("avector", avector);
    }
    std::vector<T> avector1;
    {
        test_istream is(testfile, TEST_STREAM_FLAGS);
        test_iarchive ia(is, TEST_ARCHIVE_FLAGS);
        ia >> boost::serialization::make_nvp("avector", avector1);
    }
    BOOST_CHECK(avector == avector1);
    std::remove(testfile);
    return EXIT_SUCCESS;
}
Пример #5
0
void
test_map(){
    const char * testfile = boost::archive::tmpnam(NULL);
    BOOST_REQUIRE(NULL != testfile);

    BOOST_MESSAGE("map");
    // test map of objects
    std::map<random_key, A> amap;
    amap.insert(std::make_pair(random_key(), A()));
    amap.insert(std::make_pair(random_key(), A()));
    {   
        test_ostream os(testfile, TEST_STREAM_FLAGS);
        test_oarchive oa(os, TEST_ARCHIVE_FLAGS);
        oa << boost::serialization::make_nvp("amap", amap);
    }
    std::map<random_key, A> amap1;
    {
        test_istream is(testfile, TEST_STREAM_FLAGS);
        test_iarchive ia(is, TEST_ARCHIVE_FLAGS);
        ia >> boost::serialization::make_nvp("amap", amap1);
    }
    BOOST_CHECK(amap == amap1);
    std::remove(testfile);
}
void loadMat(cv::Mat& m, std::string filename) {
	std::ifstream ifs(filename.c_str());
	boost::archive::binary_iarchive ia(ifs);
	//boost::archive::text_iarchive ia(ifs);
	ia >> m;
}
Пример #7
0
CrsGraph_AMD::NewTypeRef
CrsGraph_AMD::
operator()( OriginalTypeRef orig )
{
  origObj_ = &orig;

  int n = orig.NumMyRows();
  int nnz = orig.NumMyNonzeros();

  //create std CRS format
  std::vector<int> ia(n+1,0);
  std::vector<int> ja(nnz);
  int cnt;
  for( int i = 0; i < n; ++i )
  {
    int * tmpP = &ja[ia[i]];
    orig.ExtractMyRowCopy( i, nnz-ia[i], cnt, tmpP );
    ia[i+1] = ia[i] + cnt;
  }

  //trim down to local only
  std::vector<int> iat(n+1);
  std::vector<int> jat(nnz);
  int loc = 0;
  for( int i = 0; i < n; ++i )
  {
    iat[i] = loc;
    for( int j = ia[i]; j < ia[i+1]; ++j )
    {
      if( ja[j] < n )
        jat[loc++] = ja[j];
      else
	break;
    }
  }
  iat[n] = loc;


  if( verbose_ )
  {
    std::cout << "Orig Graph\n";
    std::cout << orig << std::endl;
    std::cout << "-----------------------------------------\n";
    std::cout << "CRS Format Graph\n";
    std::cout << "-----------------------------------------\n";
    for( int i = 0; i < n; ++i )
    {
      std::cout << i << ": " << iat[i+1] << ": ";
      for( int j = iat[i]; j<iat[i+1]; ++j )
        std::cout << " " << jat[j];
      std::cout << std::endl;
    }
    std::cout << "-----------------------------------------\n";
  }

  std::vector<int> perm(n);
  std::vector<double> info(AMD_INFO);

  amd_order( n, &iat[0], &jat[0], &perm[0], NULL, &info[0] ); 

  if( info[AMD_STATUS] == AMD_INVALID )
    std::cout << "AMD ORDERING: Invalid!!!!\n";

  if( verbose_ )
  {
    std::cout << "-----------------------------------------\n";
    std::cout << "AMD Output\n";
    std::cout << "-----------------------------------------\n";
    std::cout << "STATUS: " << info[AMD_STATUS] << std::endl;
    std::cout << "SYMM: " << info[AMD_SYMMETRY] << std::endl;
    std::cout << "N: " << info[AMD_N] << std::endl;
    std::cout << "NZ: " << info[AMD_NZ] << std::endl;
    std::cout << "SYMM: " << info[AMD_SYMMETRY] << std::endl;
    std::cout << "NZDIAG: " << info[AMD_NZDIAG] << std::endl;
    std::cout << "NZ A+At: " << info[AMD_NZ_A_PLUS_AT] << std::endl;
    std::cout << "NDENSE: " << info[AMD_SYMMETRY] << std::endl;
    std::cout << "Perm\n";
    for( int i = 0; i<n; ++i )
      std::cout << perm[i] << std::endl;
    std::cout << "-----------------------------------------\n";
  }

  //Generate New Domain and Range Maps
  //for now, assume they start out as identical
  const Epetra_BlockMap & OldMap = orig.RowMap();
  int nG = orig.NumGlobalRows();

  std::vector<int> newElements( n );
  for( int i = 0; i < n; ++i )
    newElements[i] = OldMap.GID( perm[i] );

  NewMap_ = new Epetra_Map( nG, n, &newElements[0], OldMap.IndexBase(), OldMap.Comm() );

  if( verbose_ )
  {
    std::cout << "Old Map\n";
    std::cout << OldMap << std::endl;
    std::cout << "New Map\n";
    std::cout << *NewMap_ << std::endl;
  }

  //Generate New Graph
  NewGraph_ = new Epetra_CrsGraph( Copy, *NewMap_, 0 );
  Epetra_Import Importer( *NewMap_, OldMap );
  NewGraph_->Import( orig, Importer, Insert );
  NewGraph_->FillComplete();

  if( verbose_ )
  {
    std::cout << "New CrsGraph\n";
    std::cout << *NewGraph_ << std::endl;
  }

  newObj_ = NewGraph_;

  return *NewGraph_;
}
Пример #8
0
int main(int argc, char *argv[]){

	srand(time(NULL));
	int mouse_x, mouse_y; 

	sf::RenderWindow window_game (sf::VideoMode(900, 700), "Gamemilans!",
	sf::Style::Resize|sf::Style::Close);
	
//	sf::RenderWindow window_game (sf::VideoMode::getDesktopMode(), "Gamemilans!",
//		sf::Style::Resize|sf::Style::Close);

	sf::Music music;
	if (!music.openFromFile("music/GameSong1.ogg")) std::cout << " no puc carregar la musica " << std::endl;
	music.play();
	music.setPitch(1);
	music.setLoop(true);

		sf::Clock clock;
		
	window_game.setVerticalSyncEnabled(true);

		window_game.display();
		Presentacio p(window_game);
		p.portada();
		window_game.display();

			p.portada(); 
			window_game.display();
		while (p.handler() != 0){
		}
		window_game.clear();

			p.inst(1); 
			window_game.display();
		while (p.handler() != 0){
		}
		window_game.clear();

			p.inst(2); 
			window_game.display();
		while (p.handler() != 0){
		}
		window_game.clear();

		p.prepareText();
		int n_murs = p.handler();
		int oldmurs = n_murs;
			p.murs(); 
			window_game.display();
		while (n_murs < 0){
			n_murs = p.handler();
			if(n_murs != oldmurs){
				p.murs(); 
				window_game.display();
				oldmurs = n_murs;
			}
		}
		window_game.clear();

	Board taulell(window_game);
	Logica logica(taulell);
 	Ia ia(0);
 	Ia ia2(1);

	taulell.draw();
	logica.print_me_the_players();
	for(int i = 0; i < n_murs; ++i)
		logica.print_me_random_wall();

	bool is_server = false;
	bool online = false;
	bool ia_playing = false;

	int port;
	if(argc >= 2){
		int n;
		if(argc >= 3) {
			if((*(argv[2])) == 'S') is_server = true;
			if((*(argv[2])) == 'I') ia_playing = true;
			if((*(argv[2])) != 'I') online = true;
		}
		if((*(argv[1]))-'0' >= 0) n = atoi((argv[1]));
		else n = 2; /*(?) think it have no sense*/
		for(int i = 0; i < n; ++i) logica.print_me_random_wall();	
	}
	taulell.draw();
	window_game.display(); 
	
	sf::TcpSocket socket;
	sf::TcpSocket client;
	sf::TcpListener listener;

	if( (argc >= 3) and online) { 	//Is online so you have to connect the socket
		port = 53000;
		if(not is_server){
			//Connect the socket
			sf::Socket::Status status = socket.connect("127.0.0.1", port);
			if (status != sf::Socket::Done)	{
				std::cout << "Not conected the socket okly" << std::endl;
			}
			else std::cout << "I'm Conected to the port " << port << std::endl;
		} else /*if (is_server)*/ {
			//Bind the listener to a port
			if (listener.listen(port) != sf::Socket::Done) {
				std::cout << "Not listened okly" << std::endl;
			}
			else std::cout << "Im Listening at the port " << port << std::endl;
			// Accept the connection
			if (listener.accept(client) != sf::Socket::Done) {
				std::cout << "Not accepted the client okly" << std::endl;
			}
			else std::cout << "Conection Accepted" << std::endl;
		}
	}

//	std::cout << "-----------------The gaem is starting here biach ---------------------" << std::endl;

	bool serverTurn = true;
	clock.restart();
	int asong = 0;
	int msong = 6;
	// Mentre estigui oberta 
	while(window_game.isOpen()){

		if(asong == 0 or clock.getElapsedTime().asSeconds() >= 54){
			if(asong == 0) asong = 2;
				std::stringstream s;
				s << "music/GameSong" << asong+1 << ".ogg";
				if (!music.openFromFile(s.str())) std::cout << " no puc carregar la song " << asong+1 << std::endl;
				music.play();
				++asong;
				if(asong > msong) asong = 3;
			clock.restart();
		}
		sf::Event event;
		// If you are playing online and it is not your turn
		while(online and ((not is_server and serverTurn) or (is_server and not serverTurn))){

			float data[2];
			std::size_t received;

			//	std::cout << " I'm gonna wait for data... " << std::endl;
			if(not is_server){
				if (socket.receive(&data, sizeof(float)*2, received) != sf::Socket::Done)	{
				//	std::cout << "Not recived okly" << std::endl;
				} 
				else {
					logica.click(taulell.fixed(data[0], true), taulell.fixed(data[1], true));
					serverTurn = false;
				//	std::cout << "Rebut" << std::endl;
				}
			}
			else if(is_server){
				if (client.receive(&data, sizeof(float)*2, received) != sf::Socket::Done)	{
				//	std::cout << "Not recived okly" << std::endl;
				} 
				else {
					logica.click(taulell.fixed(data[0], true), taulell.fixed(data[1], true));
					serverTurn = true;
				//	std::cout << "rebut" << std::endl;
				}
			}

			//Empty the pollEvent
			while(window_game.pollEvent(event)){
				switch (event.type)	{
					// window closed 
					case sf::Event::Closed:
					window_game.close();
					break;
					default:
					break;
				}
			}
			window_game.display(); 
		}

		bool acted = false;
		while(window_game.pollEvent(event)){

			// mira els events
			switch (event.type) {
				// window closed 
				case sf::Event::Closed:
				window_game.close();
				break;

				// mouse pressed
				case sf::Event::MouseButtonPressed:
//					std::cout << " clicked " << std::endl;
					if (event.mouseButton.button == sf::Mouse::Left) {
						mouse_x = event.mouseButton.x;
						mouse_y = event.mouseButton.y;
					}
					if(not acted and (online and ((is_server and serverTurn) or (not is_server and not serverTurn))) ){
						if(online) {
							float data[2];
							data[0] = mouse_x;
							data[1] = mouse_y;
							// TCP socket:
							if(is_server and logica.click(taulell.fixed(data[0], true), taulell.fixed(data[1], true))){
								//	std::cout << " I'm the server who will send u data biach! " << std::endl;
								if (client.send(&data, sizeof(float)*2) != sf::Socket::Done) {
								//	std::cout << "not sent okly server->client" << std::endl;
								}
								else {
									serverTurn = false;
								//	std::cout << "sent okly S->C!!!" << std::endl;
								}
							}
							else if(not is_server and logica.click(taulell.fixed(data[0], true), taulell.fixed(data[1], true))){
								//	std::cout << " This client want's to send u shiet... " << std::endl;
								if (socket.send(&data, sizeof(float)*2) != sf::Socket::Done) {
								//	std::cout << "not sent okly client->server" << std::endl;
								}
								else {
								serverTurn = true;
								//	std::cout << "sent okly S->C!!!" << std::endl;
								}
							}
						}
						acted = true;
					}
					else {
						if(ia_playing and serverTurn) {
							int movement, deep, i, j;
							double bestvalue;
							movement = -1;
							deep = 2;
							std::cout << "Calculant..." << std::endl;
							if(serverTurn) bestvalue = ia.minMax(logica, deep, false, movement);
							else bestvalue = ia2.minMax(logica, deep, true, movement);

							std::cout << "bestval: " << bestvalue << " movement: "<< movement<< std::endl;

							if(movement < 4){
								if(serverTurn){
									i = logica.get_player_position_x(ia.getPlayer())+movx[movement];
									j = logica.get_player_position_y(ia.getPlayer())+movy[movement];
								}
								else{
									i = logica.get_player_position_x(ia2.getPlayer())+movx[movement];
									j = logica.get_player_position_y(ia2.getPlayer())+movy[movement];	
								}
							}
							else{
								movement -= 4;
								i = (movement*2+1)%17;
								j = (movement*2+1)/17;
							}
							
							std::cout << "initial pos " << logica.get_player_position_x(logica.getActualPlayer()) << " , " << logica.get_player_position_y(logica.getActualPlayer()) << " delay: " << movx[movement] << " , " << movy[movement] << std::endl;
							std::cout << "ia "<< logica.getActualPlayer() << " clicked on " << i << " " << j << std::endl;
							
							if(logica.click(i, j)) {
								if(serverTurn)serverTurn = false;
								else serverTurn = true;
								std::cout << "Torn acabat " << std::endl;
							}
						}
						else {
							int mx, my;
							mx = taulell.fixed(mouse_x, true);
							my = taulell.fixed(mouse_y, true);
							if(logica.click(mx, my)){
								if(serverTurn)serverTurn = false;
								else serverTurn = true;
							}
						}
					}
					break;
					
				case  sf::Event::KeyPressed:		/* These is not working online :$ */
					if (online and is_server and event.key.code == sf::Keyboard::R or (not online and event.key.code == sf::Keyboard::R)) {
						taulell.restart();
						logica.restart();
						taulell.draw();
						logica.print_me_the_players();
						if(argc >= 2) {	
							int n;
							if((*(argv[1]))-'0' >= 0 or true) n = atoi((argv[1]))/* - '0'*/;
							else n = 2;
							for(int i = 0; i < n; ++i) logica.print_me_random_wall();
						}
					}
				break;
				
				// we don't process other types of events
				default:
				break;
			}  
		}
		window_game.display(); 
	}
	return 0;
}
Пример #9
0
//==============================================================================
int Ifpack2_AMDReordering::Compute(const Ifpack2_Graph& Graph)
{
  IsComputed_ = false;
  NumMyRows_ = Graph.NumMyRows();
  int NumNz = Graph.NumMyNonzeros();
  
  if (NumMyRows_ == 0)
    IFPACK2_CHK_ERR(-1); // strange graph this one
  
  // Extract CRS format
  vector<int> ia(NumMyRows_+1,0);
  vector<int> ja(NumNz);
  int cnt;
  for( int i = 0; i < NumMyRows_; ++i )
  {
    int * tmpP = &ja[ia[i]];
    Graph.ExtractMyRowCopy( i, NumNz-ia[i], cnt, tmpP );
    ia[i+1] = ia[i] + cnt;
  }

  // Trim down to local only
  vector<int> iat(NumMyRows_+1);
  vector<int> jat(NumNz);
  int loc = 0;
  for( int i = 0; i < NumMyRows_; ++i )
  {
    iat[i] = loc;
    for( int j = ia[i]; j < ia[i+1]; ++j )
    {
      if( ja[j] < NumMyRows_ )
        jat[loc++] = ja[j];
      else
	break;
    }
  }
  iat[NumMyRows_] = loc;

  // Compute AMD permutation
  Reorder_.resize(NumMyRows_);
  vector<double> info(AMD_INFO);

  amesos_amd_order( NumMyRows_, &iat[0], &jat[0], &Reorder_[0], NULL, &info[0] );

  if( info[AMD_STATUS] == AMD_INVALID )
    cout << "AMD ORDERING: Invalid!!!!\n";

  // Build inverse reorder (will be used by ExtractMyRowCopy() 
  InvReorder_.resize(NumMyRows_);

  for (int i = 0 ; i < NumMyRows_ ; ++i)
    InvReorder_[i] = -1;

  for (int i = 0 ; i < NumMyRows_ ; ++i)
    InvReorder_[Reorder_[i]] = i;

  for (int i = 0 ; i < NumMyRows_ ; ++i) {
    if (InvReorder_[i] == -1)
      IFPACK2_CHK_ERR(-1);
  }

  IsComputed_ = true;
  return(0);
}
Пример #10
0
void DisplayGroupManager::calibrateTimestampOffset()
{
    // can't calibrate timestamps unless we have at least 2 processes
    if(g_mpiSize < 2)
    {
        put_flog(LOG_DEBUG, "cannot calibrate with g_mpiSize == %i", g_mpiSize);
        return;
    }

    // synchronize all processes
    MPI_Barrier(g_mpiRenderComm);

    // get current timestamp immediately after
    boost::posix_time::ptime timestamp(boost::posix_time::microsec_clock::universal_time());

    // rank 1: send timestamp to rank 0
    if(g_mpiRank == 1)
    {
        // serialize state
        std::ostringstream oss(std::ostringstream::binary);

        // brace this so destructor is called on archive before we use the stream
        {
            boost::archive::binary_oarchive oa(oss);
            oa << timestamp;
        }

        // serialized data to string
        std::string serializedString = oss.str();
        int size = serializedString.size();

        // send the header and the message
        MessageHeader mh;
        mh.size = size;

        MPI_Send((void *)&mh, sizeof(MessageHeader), MPI_BYTE, 0, 0, MPI_COMM_WORLD);
        MPI_Send((void *)serializedString.data(), size, MPI_BYTE, 0, 0, MPI_COMM_WORLD);
    }
    // rank 0: receive timestamp from rank 1
    else if(g_mpiRank == 0)
    {
        MessageHeader messageHeader;

        MPI_Status status;
        MPI_Recv((void *)&messageHeader, sizeof(MessageHeader), MPI_BYTE, 1, 0, MPI_COMM_WORLD, &status);

        // receive serialized data
        char * buf = new char[messageHeader.size];

        // read message into the buffer
        MPI_Recv((void *)buf, messageHeader.size, MPI_BYTE, 1, 0, MPI_COMM_WORLD, &status);

        // de-serialize...
        std::istringstream iss(std::istringstream::binary);

        if(iss.rdbuf()->pubsetbuf(buf, messageHeader.size) == NULL)
        {
            put_flog(LOG_FATAL, "rank %i: error setting stream buffer", g_mpiRank);
            exit(-1);
        }

        // read to a new timestamp
        boost::posix_time::ptime rank1Timestamp;

        boost::archive::binary_iarchive ia(iss);
        ia >> rank1Timestamp;

        // free mpi buffer
        delete [] buf;

        // now, calculate and store the timestamp offset
        timestampOffset_ = rank1Timestamp - timestamp;

        put_flog(LOG_DEBUG, "timestamp offset = %s", (boost::posix_time::to_simple_string(timestampOffset_)).c_str());
    }
void in(const char *testfile, A & a)
{
    test_istream is(testfile, TEST_STREAM_FLAGS);
    test_iarchive ia(is);
    ia >> BOOST_SERIALIZATION_NVP(a);
}
Пример #12
0
int test_main( int /* argc */, char* /* argv */[] )
{
    const char * testfile = boost::archive::tmpnam(NULL);
    BOOST_REQUIRE(NULL != testfile);

    const A a;
    char s1[] = "a";
    char s2[] = "ab";
    char s3[] = "abc";
    char s4[] = "abcd";
    const int i = 12345;

    A a1;
    char s1_1[10];
    char s1_2[10];
    char s1_3[10];
    char s1_4[10];
    int i1 = 34790;

    std::memset(s1_1, '\0', sizeof(s1_1));
    std::memset(s1_2, '\0', sizeof(s1_2));
    std::memset(s1_3, '\0', sizeof(s1_3));
    std::memset(s1_4, '\0', sizeof(s1_4));
    {
        test_ostream os(testfile, TEST_STREAM_FLAGS);
        test_oarchive oa(os, TEST_ARCHIVE_FLAGS);
        oa << boost::serialization::make_nvp(
            "s1", 
            boost::serialization::make_binary_object(
                s1, 
                sizeof(s1)
            )
        );
        oa << boost::serialization::make_nvp(
            "s2", 
            boost::serialization::make_binary_object(
                s2, 
                sizeof(s2)
            )
        );
        oa << boost::serialization::make_nvp(
            "s3", 
            boost::serialization::make_binary_object(
                s3, 
                sizeof(s3)
            )
        );
        oa << boost::serialization::make_nvp(
            "s4", 
            boost::serialization::make_binary_object(
                s4, 
                sizeof(s4)
            )
        );
        oa << BOOST_SERIALIZATION_NVP(a);
        // note: add a little bit on the end of the archive to detect
        // failure of text mode binary.
        oa << BOOST_SERIALIZATION_NVP(i);
    }
    {
        test_istream is(testfile, TEST_STREAM_FLAGS);
        test_iarchive ia(is, TEST_ARCHIVE_FLAGS);
        ia >> boost::serialization::make_nvp(
            "s1", 
            boost::serialization::make_binary_object(
                s1_1, 
                sizeof(s1)
            )
        );
        ia >> boost::serialization::make_nvp(
            "s2", 
            boost::serialization::make_binary_object(
                s1_2, 
                sizeof(s2)
            )
        );
        ia >> boost::serialization::make_nvp(
            "s3", 
            boost::serialization::make_binary_object(
                s1_3, 
                sizeof(s3)
            )
        );
        ia >> boost::serialization::make_nvp(
            "s4", 
            boost::serialization::make_binary_object(
                s1_4, 
                sizeof(s4)
            )
        );
        ia >> BOOST_SERIALIZATION_NVP(a1);
        // note: add a little bit on the end of the archive to detect
        // failure of text mode binary.
        ia >> BOOST_SERIALIZATION_NVP(i1);
    }
    BOOST_CHECK(0 == std::strcmp(s1, s1_1));
    BOOST_CHECK(0 == std::strcmp(s2, s1_2));
    BOOST_CHECK(0 == std::strcmp(s3, s1_3));
    BOOST_CHECK(0 == std::strcmp(s4, s1_4));
    BOOST_CHECK(a == a1);
    BOOST_CHECK(i == i1);
    std::remove(testfile);
    return EXIT_SUCCESS;
}
Пример #13
0
    void render_raster_marker(agg::trans_affine const& marker_tr,
                              double opacity)
    {
        using pixfmt_pre = agg::pixfmt_rgba32_pre;
        agg::scanline_u8 sl_;
        double width  = src_.width();
        double height = src_.height();
        if (std::fabs(1.0 - scale_factor_) < 0.001
            && (std::fabs(1.0 - marker_tr.sx) < agg::affine_epsilon)
            && (std::fabs(0.0 - marker_tr.shy) < agg::affine_epsilon)
            && (std::fabs(0.0 - marker_tr.shx) < agg::affine_epsilon)
            && (std::fabs(1.0 - marker_tr.sy) < agg::affine_epsilon))
        {
            agg::rendering_buffer src_buffer((unsigned char *)src_.getBytes(),src_.width(),src_.height(),src_.width() * 4);
            pixfmt_pre pixf_mask(src_buffer);
            if (snap_to_pixels_)
            {
                renb_.blend_from(pixf_mask,
                                 0,
                                 std::floor(marker_tr.tx + .5),
                                 std::floor(marker_tr.ty + .5),
                                 unsigned(255*opacity));
            }
            else
            {
                renb_.blend_from(pixf_mask,
                                 0,
                                 marker_tr.tx,
                                 marker_tr.ty,
                                 unsigned(255*opacity));
            }
        }
        else
        {
            using img_accessor_type = agg::image_accessor_clone<pixfmt_pre>;
            using interpolator_type = agg::span_interpolator_linear<>;
            //using span_gen_type = agg::span_image_filter_rgba_2x2<img_accessor_type,interpolator_type>;
            using span_gen_type = agg::span_image_resample_rgba_affine<img_accessor_type>;
            using renderer_type = agg::renderer_scanline_aa_alpha<renderer_base,
                                                                  agg::span_allocator<color_type>,
                                                                  span_gen_type>;

            double p[8];
            p[0] = 0;     p[1] = 0;
            p[2] = width; p[3] = 0;
            p[4] = width; p[5] = height;
            p[6] = 0;     p[7] = height;
            marker_tr.transform(&p[0], &p[1]);
            marker_tr.transform(&p[2], &p[3]);
            marker_tr.transform(&p[4], &p[5]);
            marker_tr.transform(&p[6], &p[7]);
            agg::span_allocator<color_type> sa;
            agg::image_filter_lut filter;
            filter.calculate(agg::image_filter_bilinear(), true);
            agg::rendering_buffer marker_buf((unsigned char *)src_.getBytes(),
                                             src_.width(),
                                             src_.height(),
                                             src_.width()*4);
            pixfmt_pre pixf(marker_buf);
            img_accessor_type ia(pixf);
            agg::trans_affine final_tr(p, 0, 0, width, height);
            if (snap_to_pixels_)
            {
                final_tr.tx = std::floor(final_tr.tx+.5);
                final_tr.ty = std::floor(final_tr.ty+.5);
            }
            interpolator_type interpolator(final_tr);
            span_gen_type sg(ia, interpolator, filter);
            renderer_type rp(renb_,sa, sg, unsigned(opacity*255));
            ras_.move_to_d(p[0],p[1]);
            ras_.line_to_d(p[2],p[3]);
            ras_.line_to_d(p[4],p[5]);
            ras_.line_to_d(p[6],p[7]);
            agg::render_scanlines(ras_, sl_, rp);
        }
    }
void ScientificProcessor::loadAllCells(std::fstream &filestr)
{
    boost::archive::text_iarchive ia(filestr);
    ia >> allCells;
    filestr.close();
}
Пример #15
0
inline void
irccon::parse (const string & what)
{
	//m_parser.enterMutex();
	ircargs ia (htmlspecialchars(what));
	/*
	  Insertme:
	  if (ia.command() == "NICK") {
	    yace->irc().insertUser(ia.arg(0), ia(arg4));
	    replace(yace->sql().getString("enters"),"%CNAME%",ia.arg(0));
	    return;
	  }
	*/
	if (ia.command () == "PRIVMSG")
	{
		  commandargs ca(ia.rest());
	  if (ia.arg(0) == "YaCEServ") {
		  if (ia.prefix() == "NickServ") {
			  yace->sql().insertRegistry(ca.arg(0),ca.arg(1),ca.arg(2));
		   	  //m_parser.leaveMutex();
			  return;
			}

			// YaCEServ needs OperServ access for some Features
			commandargs ca(ia.rest());
			typedef hash_map<string, commandfunc> commandmap;
			string command;
			commandargs argz("");
			commandfunc f;
			commandmap cmds;
      register_commands(cmds);
			
			bool iscmd = false;
			if (ca.arg(0) == "help") {
			  cout << "HELP REQUEST!" << endl;
			  iscmd = false;
			  yace->irc().send(":YaCEServ PRIVMSG " + ia.prefix() + ": YaCEServ Help:");
				yace->irc().send(":YaCEServ PRIVMSG " + ia.prefix() + ": Pic <url>: Inserts picture");
				yace->irc().send(":YaCEServ PRIVMSG " + ia.prefix() + ": YaCEServ Sound <url>: Inserts Sound");
			  yace->irc().send(":YaCEServ PRIVMSG " + ia.prefix() + ": YaCEServ Vipmsg <text>: Vipmsg with <text>");
			  yace->irc().send(":YaCEServ PRIVMSG " + ia.prefix() + ": YaCEServ Amsg <text>: Admin msg with <text>");
			}
			else if (ca.arg(0) == "Pic") {
			  iscmd = true;
				command = "p";
				argz = ca.rest(0);
			}
			if (iscmd) {
			  f = cmds[command];
			  f(ia.prefix(),argz);
			}
		}

	  user* u = yace->users().getUser(ia.prefix());
		u->incrProp("said");
		u->isetProp("silence",0);

		if (ia.arg (0)[0] == '#')
		{
			if (ia.rest ()[0] == (char) 1)
			{
				string s_me = ia.rest ().substr (0, ia.rest ().length () - 2);
				s_me = s_me.substr (s_me.find (" "), s_me.length () - s_me.find ("N"));
				i2y_me (ia.prefix (), s_me, ia.arg(0));
			    //m_parser.leaveMutex();
				return;
				} else {
				i2y_say (ia.prefix (), ia.rest (), ia.arg (0));
		        //m_parser.leaveMutex();
				return; 
				}
			} else {
			i2y_whisper (ia.prefix (), ia.rest (), ia.arg (0));
		//m_parser.leaveMutex();
		return;
		}
	} else	if (ia.command() == "PING")
	{
		string pong = "PONG " + name + " " + ia.arg (0);
		yace->irc ().send (pong);
		//m_parser.leaveMutex();
		return;
	}
	else if (ia.command() == "TOPIC") 
	{
	  string msg = yace->sql().getString("settopic");
		msg = replaceCommon(msg);
		msg = replaceUser(ia.prefix(), msg);
		msg = replace(msg, "%TEXT%", ia.rest().substr(0, ia.rest().length()-1));
		sendRoomU(ia.prefix(),msg);
	  setTopic(getRoom(ia.arg(0)),ia.rest());
	  //m_parser.leaveMutex();
		return;
	}
  else if (ia.command() == "NICK")
	{
	  if (ia.prefix() != "") {
			string tosend;
			tosend = yace->sql().getString("nick");
			tosend = replaceCommon(tosend);
			tosend = replace(tosend, "%NICK%", ia.arg(0));
			tosend = replaceUser(ia.prefix(), tosend);
			yace->users().getUser(ia.prefix())->ssetProp("nick", ia.arg(0));
			sendRoomU(ia.prefix(), tosend);
			//m_parser.leaveMutex();
		  return;																			
		}
	  string nick = ia.arg(0);
		string host = ia.arg(4);
		bool hasreg = false;
		if (yace->users().existsUser(nick)) {
		  //m_parser.leaveMutex();
			return;
		}
		
		hasreg = yace->sql().isReg(nick);

		//if (hasreg) {
		  // We need NickServ-Plugins for identify
		  // yace->irc().send(":yace.filbboard.de KILL " + nick + " :Registered. If its your nick, please reconnect and identify");
		  //return;
		//}

		if(nick.length() >= 5) {
		  if (nick.substr(nick.length()-4,4) == "Serv" || nick == "DevNull" || nick == "Global" || nick == "BrotSheep") {
		    //m_parser.leaveMutex();
			  return;
		  }
	   }
		
	  user* irchehe = new user(ia.arg(0),ia.arg(4));
	  user* hehe = irchehe;
		irchehe->IncRef();
		yace->users().insertUser(irchehe);
		 yace->rooms().joinRoom(irchehe->getName(), "TEMP-ROOM"); // this is untill we got a JOIN
	   //TOLLE SACHEN
		string regstrings = yace->sql().getConfStr("regstrings");
    string regnums = yace->sql().getConfStr("regnums");

    {
      if(hasreg)
	yace->sql().updateTime(hehe->getName());

      commandargs str(regstrings);
      
      string act;
      string actval;
      for(int i = 0; (act = str.arg(i)) != ""; ++i) {
	
	unsigned long pos = act.find("=");
	if(pos != string::npos) {
	  actval = act.substr(pos + 1);
	  act = act.substr(0, pos);
	}
	else {
	  actval = "";
	}

	if(hasreg)
	  hehe->ssetProp(act, yace->sql().getRegStr(nick, act));
	else
	  hehe->ssetProp(act, actval);
      }

      commandargs num(regnums);

      for(int i = 0; (act = num.arg(i)) != ""; ++i) {
	unsigned long pos = act.find("=");
	if(pos != string::npos) {
	  actval = act.substr(pos + 1);
	  act = act.substr(0, pos);
	}
	else {
	  actval = "";
	}

	long actnumval;
	istringstream is(actval);
	is >> actnumval;
	
	if(hasreg)
	  hehe->isetProp(act, yace->sql().getRegNum(nick, act));
	else
	  hehe->isetProp(act, actnumval);
      }
    }
    // END TOLLE SACHEN
		enters(irchehe);
    	yace->rooms().leaves(irchehe->getName(), true, "TEMP-ROOM");

	    irchehe->DecRef();
	    //m_parser.leaveMutex();
	    return;
	}
  else if (ia.command() == "JOIN") {
Пример #16
0
// -------------------------------------------------------------
// OptimizerImplementation::p_gatherProblem
// -------------------------------------------------------------
void
OptimizerImplementation::p_gatherProblem(void)
{
  parallel::Communicator comm(this->communicator());
  int nproc(comm.size());
  int me(comm.rank());

  // package up the local part of the problem into a string buffer;
  // MPI serialization cannot be used directly because VariablePtr's
  // are used in Expression's

  std::string lbuf;
  {
    std::ostringstream oss;
    boost::archive::binary_oarchive oa(oss);
    oa & p_variables;
    oa & p_constraints;
    oa & p_objective;
    oa & p_globalConstraints;
    lbuf = oss.str();
  }

  // all processes get a copy of the other processor parts of the problem 

  std::vector<std::string> gbuf(nproc);
  boost::mpi::all_gather(comm, lbuf, gbuf);

  // extract the problem and put it in local variables as required

  for (int p = 0; p < nproc; ++p) {
    if (p != me) {
      std::istringstream iss(gbuf[p]);
      boost::archive::binary_iarchive ia(iss);
      std::vector<VariablePtr> tmpvars;
      std::vector<ConstraintPtr> tmpcons;
      ConstraintMap tmpglobal;
      ExpressionPtr tmpobj;
      ia & tmpvars;
      ia & tmpcons;
      ia & tmpobj;
      ia & tmpglobal;

      for (std::vector<VariablePtr>::iterator v = tmpvars.begin();
           v != tmpvars.end(); ++v) {
        p_allVariables[(*v)->name()] = *v;
      }
      
      std::copy(tmpcons.begin(), tmpcons.end(), 
                std::back_inserter(p_allConstraints));

      // ConstraintMap::const_iterator c;
      // for (c = tmpglobal.begin(); c != tmpglobal.end(); ++c) {
      //   std::cout << me << ": " << p << ": " << c->second->name() << ": "
      //             << c->second->render() << std::endl;
      // }

      p_gatherGlobalConstraints(tmpglobal);

      if (tmpobj) {
        if (!p_fullObjective) {
          p_fullObjective = tmpobj;
        } else {
          p_fullObjective = p_fullObjective + tmpobj;
        }
      }
      
    } else {
      std::copy(p_constraints.begin(), p_constraints.end(), 
                std::back_inserter(p_allConstraints));

      // ConstraintMap::const_iterator c;
      // for (c = p_globalConstraints.begin(); c != p_globalConstraints.end(); ++c) {
      //   std::cout << me << ": " << p << ": " << c->second->name() << ": "
      //             << c->second->render() << std::endl;
      // }

      p_gatherGlobalConstraints(p_globalConstraints);

      if (p_objective) {
        if (!p_fullObjective) {
          p_fullObjective = p_objective;
        } else {
          p_fullObjective = p_fullObjective + p_objective;
        }
      }
    }
    comm.barrier();
  }


  // add global constraints to the constraints list
  ConstraintMap::const_iterator c;
  for (c = p_allGlobalConstraints.begin(); c != p_allGlobalConstraints.end(); ++c) {
    // std::cout << me << ": after: " << c->second->name() << ": "
    //           << c->second->render() << std::endl;
    p_allConstraints.push_back(c->second);
  }
  
  // make sure the locally defined variables are used on this processor

  for (std::vector<VariablePtr>::iterator v = p_variables.begin();
       v != p_variables.end(); ++v) {
    p_allVariables[(*v)->name()] = *v;
  }

  // subsitute variables in constraints and objective so they are unique

  VariableSubstituter vs(p_allVariables);
  std::for_each(p_allConstraints.begin(), p_allConstraints.end(),
                boost::bind(&Constraint::accept, _1, boost::ref(vs)));
  p_fullObjective->accept(vs);

  // uniquely name all constraints in parallel
  if (nproc > 1) {
    ConstraintRenamer r;
    std::for_each(p_allConstraints.begin(), p_allConstraints.end(),
                  boost::bind(&Constraint::accept, _1, boost::ref(r)));
  }
}
Пример #17
0
int main(int argc, char** argv)
{	
	size_t nof_peptides = 10;
	if (argc < 4)
	{
		std::cout << "Usage: compute_distance <matrix> <trie> <input> [<nof_peptides>]" << std::endl;
		return -1;
	}
	//cout << argc << endl;
	if (argc > 4) // nof_peptides is optional
	{
		nof_peptides = atoi(argv[4]);
	}

	string matrix(argv[1]);
	string trie(argv[2]);
	string filename(argv[3]);
	//std::cout << matrix << ", " << trie << ", " << filename << ", " << outname << ", " << nof_peptides << std::endl;

	//std::cout << "Reading trie..." << std::endl;
	TrieArray ta;
	{
	std::ifstream ifs(trie.c_str()); //trie is a string containing the path and filename of the trie file.
	boost::archive::text_iarchive ia(ifs);
	ta.load(ia,1);
	}

	
	Matrix m(matrix);	 

	set<string> peptides;
	
	
	// Read petides! One peptide sequence per line
	
	{ 

		//std::cout << "Reading search peptides and additional information from file " <<   std::endl;
		
		ifstream is(filename.c_str());
		if (not is)
			throw "Cannot open info File!";
		string line;
		while (getline(is,line))
		{	
			string::size_type comment = line.find("#");
			if (comment == string::npos)
			{	
						peptides.insert(line);
					//	std::cout << line << std::endl;
			}
		}
		is.close();
	}
	
	
	//std::cout << "Computing distances..." << std::endl;
	
	//ofstream os( outname.c_str() );	
	for( set<string>::const_iterator iter = peptides.begin(); iter != peptides.end(); ++iter ) 
	{
    string s = *iter;
    //std::cout << s << std::endl; 
  	
		//std::cout << "." ;
		flush(cout);		
		Node n (0,0); //start at top of the trie
		Peptide p; //
		Peptide seq;
		//std::cout << s << std::endl;
		m.translate(s, seq); //translate peptide sequence to matrix indices. seq contains the translated peptide sequence. 
		
		multiset<pair<double,string> > dist_min;
		multiset<pair<double,string> > dt;
		double dist = 0.0;
		dist_min = DFS_BnB_x_pair(ta,n,dist,m,p,seq,dt,nof_peptides);	
//		os << s << "," << query_reactivity[s] << "," << query_affinity[s] << "," << query_virality[s] <<":";
		//os << s << ":";
		cout << s << ":";
		for (multiset<pair<double,string> >::iterator it=dist_min.begin() ; it != dist_min.end(); it++ )
							//{os << (*it).second <<"," << (*it).first << ";";}
							{cout << (*it).second <<"," << (*it).first << ";";}
					//cout << (*it).second << (*it).first << endl;}
			//{os << (*it).second <<"," << (*it).first << "," << affinities[(*it).second] << ";";}
		//os << std::endl;	
		cout << std::endl;
		

	}
	//std::cout << std::endl;
//	os.close();
	return 0;
	
	
	
}
Пример #18
0
SmafeAbstractFeatureVector* SmafeStoreDB::readFeatureVector(long fvt_id,
		long track_id, bool load_fvt_info, long file_id, long segmentnr, bool onErrorSilent, bool load_file_id) {
	SmafeAbstractFeatureVector *safv;

	char* s11nbuf = NULL;
	size_t buf_len;
	std::string class_id;
	long file_id_db; // the file_id from the fv record in the db
	std::string s11nbuf_decrypted;

	try {

		// get feature vector as serialized  (raw)
		readFeatureRecord_raw(track_id, segmentnr, fvt_id, s11nbuf, buf_len, class_id,
				file_id_db, load_file_id);

		// check for NULL
		if (s11nbuf != NULL) {

			// decrypt if necessary
			try {
				s11nbuf_decrypted = decryptString(s11nbuf);
			} catch (CryptoPP::Exception& e) {
				if (onErrorSilent) {
					return NULL;
				} else {
					throw "Error decrypting feature vector: " + e.GetWhat();
				}
			}

			/*
			 // check the save operation
			 std::stringstream ssq (std::stringstream::in | std::stringstream::out);
			 {
			 const SmafeNumericFeatureVector rp(10);
			 // xml
			 //boost::archive::xml_oarchive xoa(ssq);
			 //xoa << BOOST_SERIALIZATION_NVP(rp);
			 //text
			 boost::archive::text_oarchive toa(ssq);
			 toa << BOOST_SERIALIZATION_NVP(rp);
			 }
			 */

			{

				// test
				//			strcpy(s11nbuf, "22 serialization::archive 4 0 25 SmafeNumericFeatureVector 1 0   0 0 0 0");
				//			strcpy(s11nbuf, "22 serialization::archive 4 0 25 SmafeNumericFeatureVector 1 0   0 0 60 15.750428559896203 15.835513677740561 14.431150283495295 9.1691797843426137 12.811824920752358 13.586624597153685 11.002659647379955 11.064217292864679 7.9797139825054986 9.9235703018379375 9.2886428424895762 8.0324006306601525 15.276850905877762 6.9980024541539478 6.5534074804978939 8.2741463327244738 5.5196410597310415 7.0535993338265381 12.179729021310999 7.614244901519533 8.2170004314708081 7.2385293826428949 7.670518295296743 7.4098476138708218 9.1962051599756762 22.083150886531712 7.1937839234320631 5.3740144890307757 9.4028271947731152 4.9368000302025195 5.54337365004546 12.558513608835014 5.0464122111050171 5.2942967940821957 5.1293983657093012 4.0150540410477955 4.1744641937907305 4.4020548029323763 6.5890940735936869 4.9097187529569455 3.4772659337619394 5.18100803316465 3.9710662965692674 3.4761336596970747 6.1217972638432858 2.9740695367326637 3.4272158068985425 5.1425586241272487 4.0814512317989635 5.4559700678194245 10.940316799899946 10.544862969781059 4.6729446737166676 3.1199454721889417 4.0808752427976582 3.2306116954569353 2.6467356438540484 4.4918005045229616 2.4698196267397305 2.414333588255281");
				//strcpy(s11nbuf, "22 serialization::archive 4 0 25 SmafeNumericFeatureVector 1 0\0120 0 0 60 15.750428559896203 15.835513677740561 14.431150283495295 9.1691797843426137 12.811824920752358 13.586624597153685 11.002659647379955 11.064217292864679 7.9797139825054986 9.9235703018379375 9.2886428424895762 8.0324006306601525 15.276850905877762 6.9980024541539478 6.5534074804978939 8.2741463327244738 5.5196410597310415 7.0535993338265381 12.179729021310999 7.614244901519533 8.2170004314708081 7.2385293826428949 7.670518295296743 7.4098476138708218 9.1962051599756762 22.083150886531712 7.1937839234320631 5.3740144890307757 9.4028271947731152 4.9368000302025195 5.54337365004546 12.558513608835014 5.0464122111050171 5.2942967940821957 5.1293983657093012 4.0150540410477955 4.1744641937907305 4.4020548029323763 6.5890940735936869 4.9097187529569455 3.4772659337619394 5.18100803316465 3.9710662965692674 3.4761336596970747 6.1217972638432858 2.9740695367326637 3.4272158068985425 5.1425586241272487 4.0814512317989635 5.4559700678194245 10.940316799899946 10.544862969781059 4.6729446737166676 3.1199454721889417 4.0808752427976582 3.2306116954569353 2.6467356438540484 4.4918005045229616 2.4698196267397305 2.414333588255281\012");


				std::stringstream ss(std::stringstream::in
						| std::stringstream::out);
				//				ss << boost_s11n_workaround_135(s11nbuf_decrypted) << std::endl;
				ss << s11nbuf_decrypted << std::endl;

				SMAFELOG_FUNC(SMAFELOG_DEBUG3, std::string(s11nbuf));

				//ss << stringvalues << endl;

				boost::archive::text_iarchive ia(ss);

				// restore  from the archive
				ia >> BOOST_SERIALIZATION_NVP(safv);
			}

			// get info about featurevectortype if desired
			if (load_fvt_info)
				getFeatureVectorMetaInfo(*safv, fvt_id, track_id, file_id);

			// store foreign keys;
			safv->track_id = track_id;
			// if a specific file_id is given, store this one
			// otherweise store the one that comes from the db
			if (file_id < 0)
				safv->file_id = file_id_db;
			else
				safv->file_id = file_id;

		} else { //if (s11nbuf != NULL)
			if (onErrorSilent) {
				return NULL;
			} else {
				throw std::string("Feature vector not found for track_id = "
						+ stringify(track_id) + ", featurevectortype_id = "
						+ stringify(fvt_id));
			}
		}//if (s11nbuf != NULL)

	} // try block
Пример #19
0
int main(int argc, char* argv[])
{
    directory_structure_t ds;

    vector<object_trj_t> good_trlet_list;
    {
	std::string name = ds.workspace+"good_trlet_list.xml";
	std::ifstream fin(name.c_str());
	boost::archive::xml_iarchive ia(fin);
	ia >> BOOST_SERIALIZATION_NVP(good_trlet_list);
    }

    matrix<int> Tff;
    {
	std::string name = ds.workspace+"Tff.txt";
	std::ifstream fin(name.c_str());
	fin>>Tff;
	fin.close();
    }

    matrix<float> Aff;
    {
	std::string name = ds.workspace+"Aff.txt";
	std::ifstream fin(name.c_str());
	fin>>Aff;
	fin.close();
    }

    matrix<float> Ocff;
    {
	std::string name = ds.workspace+"Ocff.txt";
	std::ifstream fin(name.c_str());
	fin>>Ocff;
	fin.close();
    }

    matrix<object_trj_t> gap_trlet_list;
    {
	std::string name = ds.workspace+"gap_trlet_list.xml";
	std::ifstream fin(name.c_str());
	boost::archive::xml_iarchive ia(fin);
	ia >> BOOST_SERIALIZATION_NVP(gap_trlet_list);
    }


//////////////////////////////////////////////////////////////////////////
    vector<std::vector<std::string> > seq(2);
    read_sequence_list(ds.prefix, seq);
    int T = seq[0].size();
    int Ncam = 2;

    array<std::size_t, 2> img_size = {768, 1024};
    geometric_info_t gi;
    gi.load(ds, img_size);

    parameter_t P;

    //load_part_model(model, P.head_wid_ratio, P.head_hi_ratio, P.torso_hi_ratio);


    real_timer_t timer2;

    matrix<int> LMat;
    matrix<int> links;

    matrix<float> Aff2(Aff+Ocff*0.2);
    solve_linprog(Tff, Aff2, LMat, links);

    std::cout<<"LP time: "<<timer2.elapsed()/1000.0f<<std::endl;

    std::cout<<"Lv="<<links<<std::endl;

    vector<object_trj_t> final_trj_list;
    vector<vector<int> > final_trj_index;
    matrix<int> final_state_list;

    finalize_trajectory(Ncam, T, 
			links, good_trlet_list, gap_trlet_list,
			final_trj_list, final_trj_index, final_state_list);


    {
	std::string name = ds.workspace+"final_trj_list.xml";
	std::ofstream fout(name.c_str());
	boost::archive::xml_oarchive oa(fout);
	oa << BOOST_SERIALIZATION_NVP(final_trj_list);
    }

    {
	std::string name = ds.workspace+"final_state_list.txt";
	std::ofstream fout(name.c_str());
	fout<<final_state_list;
	fout.close();
    }

    {
	std::string name = ds.workspace+"final_trj_index.txt";
	std::ofstream fout(name.c_str());
	fout << final_trj_index;
	fout.close();
    }

    return 0;

}
Пример #20
0
void reproject_and_scale_raster(raster & target, raster const& source,
                      proj_transform const& prj_trans,
                      double offset_x, double offset_y,
                      unsigned mesh_size,
                      double filter_radius,
                      scaling_method_e scaling_method)
{
    CoordTransform ts(source.data_.width(), source.data_.height(),
                      source.ext_);
    CoordTransform tt(target.data_.width(), target.data_.height(),
                      target.ext_, offset_x, offset_y);
    unsigned i, j;
    unsigned mesh_nx = ceil(source.data_.width()/double(mesh_size)+1);
    unsigned mesh_ny = ceil(source.data_.height()/double(mesh_size)+1);

    ImageData<double> xs(mesh_nx, mesh_ny);
    ImageData<double> ys(mesh_nx, mesh_ny);

    // Precalculate reprojected mesh
    for(j=0; j<mesh_ny; j++) {
        for (i=0; i<mesh_nx; i++) {
            xs(i,j) = i*mesh_size;
            ys(i,j) = j*mesh_size;
            ts.backward(&xs(i,j), &ys(i,j));
        }
    }
    prj_trans.backward(xs.getData(), ys.getData(), NULL, mesh_nx*mesh_ny);

    // Initialize AGG objects
    typedef agg::pixfmt_rgba32 pixfmt;
    typedef pixfmt::color_type color_type;
    typedef agg::renderer_base<pixfmt> renderer_base;
    typedef agg::pixfmt_rgba32_pre pixfmt_pre;
    typedef agg::renderer_base<pixfmt_pre> renderer_base_pre;

    agg::rasterizer_scanline_aa<> rasterizer;
    agg::scanline_u8  scanline;
    agg::rendering_buffer buf((unsigned char*)target.data_.getData(),
                              target.data_.width(),
                              target.data_.height(),
                              target.data_.width()*4);
    pixfmt_pre pixf_pre(buf);
    renderer_base_pre rb_pre(pixf_pre);
    rasterizer.clip_box(0, 0, target.data_.width(), target.data_.height());
    agg::rendering_buffer buf_tile(
        (unsigned char*)source.data_.getData(),
        source.data_.width(),
        source.data_.height(),
        source.data_.width() * 4);

    pixfmt pixf_tile(buf_tile);

    typedef agg::image_accessor_clone<pixfmt> img_accessor_type;
    img_accessor_type ia(pixf_tile);

    agg::span_allocator<color_type> sa;

    // Initialize filter
    agg::image_filter_lut filter;
    switch(scaling_method)
    {
    case SCALING_NEAR: break;
    case SCALING_BILINEAR8: // TODO - impl this or remove?
    case SCALING_BILINEAR:
        filter.calculate(agg::image_filter_bilinear(), true); break;
    case SCALING_BICUBIC:
        filter.calculate(agg::image_filter_bicubic(), true); break;
    case SCALING_SPLINE16:
        filter.calculate(agg::image_filter_spline16(), true); break;
    case SCALING_SPLINE36:
        filter.calculate(agg::image_filter_spline36(), true); break;
    case SCALING_HANNING:
        filter.calculate(agg::image_filter_hanning(), true); break;
    case SCALING_HAMMING:
        filter.calculate(agg::image_filter_hamming(), true); break;
    case SCALING_HERMITE:
        filter.calculate(agg::image_filter_hermite(), true); break;
    case SCALING_KAISER:
        filter.calculate(agg::image_filter_kaiser(), true); break;
    case SCALING_QUADRIC:
        filter.calculate(agg::image_filter_quadric(), true); break;
    case SCALING_CATROM:
        filter.calculate(agg::image_filter_catrom(), true); break;
    case SCALING_GAUSSIAN:
        filter.calculate(agg::image_filter_gaussian(), true); break;
    case SCALING_BESSEL:
        filter.calculate(agg::image_filter_bessel(), true); break;
    case SCALING_MITCHELL:
        filter.calculate(agg::image_filter_mitchell(), true); break;
    case SCALING_SINC:
        filter.calculate(agg::image_filter_sinc(filter_radius), true); break;
    case SCALING_LANCZOS:
        filter.calculate(agg::image_filter_lanczos(filter_radius), true); break;
    case SCALING_BLACKMAN:
        filter.calculate(agg::image_filter_blackman(filter_radius), true); break;
    }

    // Project mesh cells into target interpolating raster inside each one
    for(j=0; j<mesh_ny-1; j++) {
        for (i=0; i<mesh_nx-1; i++) {
            double polygon[8] = {xs(i,j), ys(i,j),
                                 xs(i+1,j), ys(i+1,j),
                                 xs(i+1,j+1), ys(i+1,j+1),
                                 xs(i,j+1), ys(i,j+1)};
            tt.forward(polygon+0, polygon+1);
            tt.forward(polygon+2, polygon+3);
            tt.forward(polygon+4, polygon+5);
            tt.forward(polygon+6, polygon+7);

            rasterizer.reset();
            rasterizer.move_to_d(polygon[0]-1, polygon[1]-1);
            rasterizer.line_to_d(polygon[2]+1, polygon[3]-1);
            rasterizer.line_to_d(polygon[4]+1, polygon[5]+1);
            rasterizer.line_to_d(polygon[6]-1, polygon[7]+1);

            unsigned x0 = i * mesh_size;
            unsigned y0 = j * mesh_size;
            unsigned x1 = (i+1) * mesh_size;
            unsigned y1 = (j+1) * mesh_size;

            agg::trans_affine tr(polygon, x0, y0, x1, y1);
            if (tr.is_valid())
            {
                typedef agg::span_interpolator_linear<agg::trans_affine>
                    interpolator_type;
                interpolator_type interpolator(tr);

                if (scaling_method == SCALING_NEAR) {
                    typedef agg::span_image_filter_rgba_nn
                        <img_accessor_type, interpolator_type>
                        span_gen_type;
                    span_gen_type sg(ia, interpolator);
                    agg::render_scanlines_aa(rasterizer, scanline, rb_pre,
                                             sa, sg);
                } else {
                    typedef mapnik::span_image_resample_rgba_affine
                        <img_accessor_type> span_gen_type;
                    span_gen_type sg(ia, interpolator, filter);
                    agg::render_scanlines_aa(rasterizer, scanline, rb_pre,
                                             sa, sg);
                }
            }

        }
    }
}
// save derived polymorphic class
void load_derived(const char *testfile)
{
    test_istream is(testfile, TEST_STREAM_FLAGS);
    test_iarchive ia(is);

    polymorphic_derived1 *rd1 = NULL;
    polymorphic_derived2 *rd2 = NULL;

    std::cout << "loading polymorphic_derived1 (no_rtti)\n";
    ia >> BOOST_SERIALIZATION_NVP(rd1);

    BOOST_CHECK_MESSAGE(
        boost::serialization::type_info_implementation<
            polymorphic_derived1
        >::type::get_const_instance()
        == 
        * boost::serialization::type_info_implementation<
            polymorphic_derived1
        >::type::get_const_instance().get_derived_extended_type_info(*rd1)
        ,
        "restored pointer d1 not of correct type"
    );

    std::cout << "loading polymorphic_derived2\n";
    ia >> BOOST_SERIALIZATION_NVP(rd2);
    BOOST_CHECK_MESSAGE(
        boost::serialization::type_info_implementation<
            polymorphic_derived2
        >::type::get_const_instance()
        == 
        * boost::serialization::type_info_implementation<
            polymorphic_derived2
        >::type::get_const_instance().get_derived_extended_type_info(*rd2)
        ,
        "restored pointer d2 not of correct type"
    );
    polymorphic_base *rb1 = NULL;
    polymorphic_base *rb2 = NULL;

    // the above opereration registers the derived classes as a side
    // effect.  Hence, instances can now be correctly serialized through
    // a base class pointer.
    std::cout << "loading polymorphic_derived1 (no_rtti) through base (no_rtti)\n";
    ia >> BOOST_SERIALIZATION_NVP(rb1);

    BOOST_CHECK_MESSAGE(
        rb1 == dynamic_cast<polymorphic_base *>(rd1),
        "serialized pointers not correctly restored"
    );

    BOOST_CHECK_MESSAGE(
        boost::serialization::type_info_implementation<
            polymorphic_derived1
        >::type::get_const_instance()
        == 
        * boost::serialization::type_info_implementation<
            polymorphic_base
        >::type::get_const_instance().get_derived_extended_type_info(*rb1)
        ,
        "restored pointer b1 not of correct type"
    );

    std::cout << "loading polymorphic_derived2 through base (no_rtti)\n";
    ia >> BOOST_SERIALIZATION_NVP(rb2);

    BOOST_CHECK_MESSAGE(
        rb2 ==  dynamic_cast<polymorphic_base *>(rd2),
        "serialized pointers not correctly restored"
    );

    BOOST_CHECK_MESSAGE(
        boost::serialization::type_info_implementation<
            polymorphic_derived2
        >::type::get_const_instance()
        == 
        * boost::serialization::type_info_implementation<
            polymorphic_base
        >::type::get_const_instance().get_derived_extended_type_info(*rb2)
        ,
        "restored pointer b2 not of correct type"
    );

    delete rb1;
    delete rb2;
}
int test_main( int /* argc */, char* /* argv */[] )
{
    const char * testfile = boost::archive::tmpnam(NULL);
    BOOST_REQUIRE(NULL != testfile);

    std::list<A *> alist;
    {   
        test_ostream os(testfile, TEST_STREAM_FLAGS);
        test_oarchive oa(os);
        A * free_a_ptr = new A;
        alist.push_back(free_a_ptr);
        alist.push_back(new A);
        // verify that first element is the same as the free pointer
        BOOST_CHECK((*alist.begin()) == free_a_ptr);
        oa << boost::serialization::make_nvp("alist", alist);
        oa << boost::serialization::make_nvp("free_a_ptr", free_a_ptr);
    }
    std::list<A *> alist1;
    {
        test_istream is(testfile, TEST_STREAM_FLAGS);
        test_iarchive ia(is);
        A * free_a_ptr1;
        ia >> boost::serialization::make_nvp("alist", alist1);
        ia >> boost::serialization::make_nvp("free_a_ptr", free_a_ptr1);
        BOOST_CHECK(
            alist.size() == alist1.size() 
            && std::equal(alist.begin(),alist.end(),alist1.begin(),ptr_equal_to<A *>())
        );
        // verify that first element is the same as the free pointer
        BOOST_CHECK((*alist1.begin()) == free_a_ptr1);
    }

    std::for_each(
        alist.begin(), 
        alist.end(), 
        boost::checked_deleter<A>()
    );
    std::for_each(
        alist1.begin(), 
        alist1.end(), 
        boost::checked_deleter<A>()
    );
    
    #ifdef BOOST_HAS_SLIST
    std::list<A *> aslist;
    {   
        aslist.push_back(new A);
        aslist.push_back(new A);
        test_ostream os(testfile, TEST_STREAM_FLAGS);
        test_oarchive oa(os);
        aslist.push_back(new A);
        aslist.push_back(new A);
        oa << boost::serialization::make_nvp("aslist", aslist);
    }
    std::list<A *> aslist1;
    {
        test_istream is(testfile, TEST_STREAM_FLAGS);
        test_iarchive ia(is);
        ia >> boost::serialization::make_nvp("aslist", aslist1);
        BOOST_CHECK(aslist.size() == aslist1.size() &&
            std::equal(aslist.begin(),aslist.end(),aslist1.begin(),ptr_equal_to<A *>())
        );
    }
    std::for_each(
        aslist.begin(), 
        aslist.end(), 
        boost::checked_deleter<A>()
    );
    std::for_each(
        aslist1.begin(), 
        aslist1.end(), 
        boost::checked_deleter<A>()
    );  
    #endif
    std::remove(testfile);
    return EXIT_SUCCESS;
}
Пример #23
0
bool History::loadChatLog(std::string chatlog, HistoryMementoCollection * hmc, std::string * userlogin, StringList * cuuidList) {

	// complete filename
	Config & config = ConfigManager::getInstance().getCurrentConfig();
	std::string filename = File::convertPathSeparators( 
		config.getConfigDir() + "chatlogs" + File::getPathSeparator() 
		+ _userProfile.getName() + File::getPathSeparator()
		+ chatlog + ".xml"
	);
	////

	//open and read chat log
	FileReader file( filename );
	if(!file.open()) {
		return false;
	}
	std::string lu = file.read();
	std::stringstream ss(lu);
	boost::archive::xml_iarchive ia(ss);
	////

	// contact
	int nbcontact = 0;
	ia >> BOOST_SERIALIZATION_NVP(nbcontact);
	for( int ic = 0; ic < nbcontact; ++ic) {
		std::string cuuid;
		ia >> BOOST_SERIALIZATION_NVP(cuuid);
		cuuidList->push_back(cuuid);
	}

	//user login
	ia >> BOOST_SERIALIZATION_NVP(*userlogin);

	//number of message
	int size = 0;
	ia >> BOOST_SERIALIZATION_NVP(size);

	//load every message
	std::string date, peer, data;
	for(int i = 0; i < size; ++i) {

		//
		//	more compact serialization
		//
		//ia >> BOOST_SERIALIZATION_NVP(date);
		//ia >> BOOST_SERIALIZATION_NVP(peer);
		//ia >> BOOST_SERIALIZATION_NVP(data);

		//Date fdate(	String(date.substr(8,2)).toInteger(), 
		//			String(date.substr(5,2)).toInteger(), 
		//			String(date.substr(0,4)).toInteger());

		//Time ftime(	String(date.substr(11,2)).toInteger(), 
		//			String(date.substr(14,2)).toInteger(), 
		//			String(date.substr(17,4)).toInteger());

		//HistoryMemento* hm = new HistoryMemento(HistoryMemento::ChatSession, fdate, ftime, peer, -1, data);

		HistoryMemento* hm = new HistoryMemento();
		hm->load(ia,HistoryMemento::SERIALIZATION_VERSION);

		/** duration -1 means it is an history message */
		hm->updateDuration(-1);

		hmc->addMemento(hm);
	}
	return true;
}
Пример #24
0
int udp_sock::send(const struct sa *dst, struct mbuf *mb)
{
	struct sa hdst;
	TRequestStatus stat;
	int err = 0;

	DEBUG_INFO("udp_sock::send %u bytes to %J\n", mbuf_get_left(mb), dst);

	/* Check for error in e.g. connected state */
	if (cerr) {
		err = cerr;
		cerr = 0; /* clear error */
		return err;
	}

	/* call helpers in reverse order */
	struct le *le = list_tail(&helpers);
	while (le) {
		struct udp_helper *uh;

		uh = (struct udp_helper *)le->data;
		le = le->prev;

		if (dst != &hdst) {
			sa_cpy(&hdst, dst);
			dst = &hdst;
		}

		if (uh->sendh(&err, &hdst, mb, uh->arg) || err)
			return err;
	}

	TInetAddr ia(sa_in(dst), sa_port(dst));

	const TPtrC8 buf_tx(mb->buf + mb->pos, mb->end - mb->pos);

	if (conn) {
		cus->iSocket.Connect(ia, stat);
		User::WaitForRequest(stat);

		if (KErrNone != stat.Int()) {
			DEBUG_WARNING("udp_sock::send Connect: kerr=%d\n",
				      stat.Int());
			if (KErrGeneral == stat.Int())
				return ECONNREFUSED;
		}

#if 0
		/* TODO: Cause Access-Violation in WINS emulator! */
		cus->iSocket.Send(buf_tx, 0, stat);
#else
		cus->iSocket.SendTo(buf_tx, ia, 0, stat);
#endif
	}
	else {
		cus->iSocket.SendTo(buf_tx, ia, 0, stat);
	}

	User::WaitForRequest(stat);

	return kerr2errno(stat.Int());
}
Пример #25
0
void deplacements(char terrain[20][38], coordonees *PacMan, coordonees *fantomeA, coordonees *fantomeB, coordonees *fantomeC, coordonees *fantomeD)
{
    char entree, pointA = ' ', pointB = ' ', pointC = ' ', pointD = ' ';
    int directionA = 0, directionB = 0, directionC = 0, directionD = 0;
    int score=0, bonus = 0, frame = 0;
    int c;
    int vies;


    for(vies = 3 ; vies > 0 ; vies--)
    {

        //Le PacMan se déplace à l'aide des touches z,q,s et d. Le jeu peut être quitté avec Esc

        affichage(terrain, score, bonus, frame, vies);

        entree = getch(); //Cette commande permet au jeu de ne pas démarer tout de suite, mais d'attendre que le joueur soit pret

        do
        {

            /*On récupère les entrées au clavier grace à la fonction GetKeyState qui est dans windows.h
              Les tests empèchent le joueur de diriger PacMan vers un mur (cela ralentirai le jeu)*/
            if(GetKeyState(0x5A) < 0 && (terrain[PacMan->i - 1][PacMan->j] == ' ' || terrain[PacMan->i - 1][PacMan->j] == '.' || terrain[PacMan->i - 1][PacMan->j] == 'M'))
            {
                entree = 'z';
            }

            if(GetKeyState(0x51) < 0 && (terrain[PacMan->i][PacMan->j - 1] == ' ' || terrain[PacMan->i][PacMan->j - 1] == '.' || terrain[PacMan->i][PacMan->j - 1] == 'M'))
            {
                entree = 'q';
            }

            if(GetKeyState(0x53) < 0 && (terrain[PacMan->i + 1][PacMan->j] == ' ' || terrain[PacMan->i + 1][PacMan->j] == '.' || terrain[PacMan->i + 1][PacMan->j] == 'M'))
            {
                entree = 's';
            }

            if(GetKeyState(0x44) < 0 && (terrain[PacMan->i][PacMan->j + 1] == ' ' || terrain[PacMan->i][PacMan->j + 1] == '.' || terrain[PacMan->i][PacMan->j + 1] == 'M'))
            {
                entree = 'd';
            }

            if(GetKeyState(VK_ESCAPE) < 0)
            {
                entree = 'Q';
            }


            //En fonction de la touche appuiée on déplace le PacMan

            switch(entree)
            {

                case 's':

                    if(terrain[PacMan->i + 1][PacMan->j] == '.') //Si PacMan se dirige vers un point on supprime le point et on incrémente le score
                    {
                        terrain[PacMan->i][PacMan->j] = ' ';
                        PacMan->i = PacMan->i + 1;
                        terrain[PacMan->i][PacMan->j] = 'C';
                        score = score + 1;
                    }
                    else if(terrain[PacMan->i + 1][PacMan->j] == ' ') //Si il n'y a rien on déplace juste PacMan
                    {
                        terrain[PacMan->i][PacMan->j] = ' ';
                        PacMan->i = PacMan->i + 1;
                        terrain[PacMan->i][PacMan->j] = 'C';

                    }
                    else if(terrain[PacMan->i + 1][PacMan->j] == 'M' && !bonus) //Si c'est un fantôme et que le bonus n'est pas activé c'est perdu
                    {
                        entree = 'Q';
                    }
                    else if(terrain[PacMan->i + 1][PacMan->j] == 'M' && bonus) //Si c'est un fantôme et que le bonus est activé, PacMan mange le fantôme et gagne 10 points
                    {
                        terrain[PacMan->i][PacMan->j] = ' '; //La réaparition de PacMan est gérée plus loin car il y a plusieurs fantômes et qu'il faut les gérer au cas par cas
                        PacMan->i = PacMan->i + 1;
                        score += 10;
                    }
                    else if(terrain[PacMan->i + 1][PacMan->j] == point) //Si la case est un bonus on active le bonus
                    {
                        terrain[PacMan->i][PacMan->j] = ' ';
                        PacMan->i = PacMan->i + 1;
                        terrain[PacMan->i][PacMan->j] = 'C';
                        bonus = 1;
                    }
                    break;

                case 'q':

                    if(terrain[PacMan->i][PacMan->j - 1]=='.')
                    {
                        terrain[PacMan->i][PacMan->j] = ' ';
                        PacMan->j = PacMan->j - 1;
                        terrain[PacMan->i][PacMan->j] = 'C';
                        score = score + 1;
                    }
                    else if(terrain[PacMan->i][PacMan->j - 1]==' ')
                    {
                        terrain[PacMan->i][PacMan->j] = ' ';
                        PacMan->j = PacMan->j - 1;
                        terrain[PacMan->i][PacMan->j] = 'C';

                    }
                    else if(terrain[PacMan->i][PacMan->j - 1]=='M' && !bonus)
                    {
                        entree = 'Q';
                    }
                    else if(terrain[PacMan->i][PacMan->j - 1]=='M' && bonus)
                    {
                        terrain[PacMan->i][PacMan->j] = ' ';
                        PacMan->j = PacMan->j - 1;
                        score += 10;
                    }
                    else if(terrain[PacMan->i][PacMan->j - 1]==point)
                    {
                        terrain[PacMan->i][PacMan->j] = ' ';
                        PacMan->j = PacMan->j - 1;
                        terrain[PacMan->i][PacMan->j] = 'C';
                        bonus = 1;
                    }
                    break;

                case 'z':

                    if(terrain[PacMan->i - 1][PacMan->j] == '.')
                    {
                        terrain[PacMan->i][PacMan->j] = ' ';
                        PacMan->i = PacMan->i - 1;
                        terrain[PacMan->i][PacMan->j] = 'C';
                        score = score + 1;
                    }
                    else if(terrain[PacMan->i - 1][PacMan->j] == ' ')
                    {
                        terrain[PacMan->i][PacMan->j] = ' ';
                        PacMan->i = PacMan->i - 1;
                        terrain[PacMan->i][PacMan->j] = 'C';

                    }
                    else if(terrain[PacMan->i - 1][PacMan->j] == 'M' && !bonus)
                    {
                        entree = 'Q';
                    }
                    else if(terrain[PacMan->i - 1][PacMan->j] == 'M' && bonus)
                    {
                        terrain[PacMan->i][PacMan->j] = ' ';
                        PacMan->i = PacMan->i - 1;
                        score += 10;
                    }
                    else if(terrain[PacMan->i - 1][PacMan->j] == point)
                    {
                        terrain[PacMan->i][PacMan->j] = ' ';
                        PacMan->i = PacMan->i - 1;
                        terrain[PacMan->i][PacMan->j] = 'C';
                        bonus = 1;
                    }
                    break;

                case 'd':

                    if(terrain[PacMan->i][PacMan->j + 1]=='.')
                    {
                        terrain[PacMan->i][PacMan->j] = ' ';
                        PacMan->j = PacMan->j + 1;
                        terrain[PacMan->i][PacMan->j] = 'C';
                        score = score + 1;
                    }
                    else if(terrain[PacMan->i][PacMan->j + 1]==' ')
                    {
                        terrain[PacMan->i][PacMan->j] = ' ';
                        PacMan->j = PacMan->j + 1;
                        terrain[PacMan->i][PacMan->j] = 'C';

                    }
                    else if(terrain[PacMan->i][PacMan->j + 1]=='M' && !bonus)
                    {
                        entree = 'Q';
                    }
                    else if(terrain[PacMan->i][PacMan->j + 1]=='M' && bonus)
                    {
                        terrain[PacMan->i][PacMan->j] = ' ';
                        PacMan->j = PacMan->j + 1;
                        score += 10;
                    }
                    else if(terrain[PacMan->i][PacMan->j + 1]==point)
                    {
                        terrain[PacMan->i][PacMan->j] = ' ';
                        PacMan->j = PacMan->j + 1;
                        terrain[PacMan->i][PacMan->j] = 'C';
                        bonus = 1;
                    }
                    break;


            }

            /*On gère les fantômes au cas par cas, il n'y a pas de condition bonus car le seul moyen
              pour que les coordonées de PacMan soient identiques à celle d'un fantôme est que le bonus soit activé*/

            if(PacMan->i == fantomeA->i && PacMan->j == fantomeA->j)
            {
                terrain[fantomeA->i][fantomeA->j] = 'C';
                fantomeA->i = 13;
                fantomeA->j = 15;
                pointA = ' ';
                terrain[fantomeA->i][fantomeA->j] = 'M';
            }
            else if(PacMan->i == fantomeB->i && PacMan->j == fantomeB->j)
            {
                terrain[fantomeB->i][fantomeB->j] = 'C';
                fantomeB->i = 13;
                fantomeB->j = 17;
                pointB = ' ';
                terrain[fantomeB->i][fantomeB->j] = 'M';
            }
            else if(PacMan->i == fantomeC->i && PacMan->j == fantomeC->j)
            {
                terrain[fantomeC->i][fantomeC->j] = 'C';
                fantomeC->i = 13;
                fantomeC->j = 19;
                pointC = ' ';
                terrain[fantomeC->i][fantomeC->j] = 'M';
            }
            else if(PacMan->i == fantomeD->i && PacMan->j == fantomeD->j)
            {
                terrain[fantomeD->i][fantomeD->j] = 'C';
                fantomeD->i = 13;
                fantomeD->j = 21;
                pointD = ' ';
                terrain[fantomeD->i][fantomeD->j] = 'M';
            }

            //Deplacement des fantomes
            directionA = ia(*PacMan, *fantomeA, terrain, directionA);
            directionB = ia(*PacMan, *fantomeB, terrain, directionB);
            directionC = ia(*PacMan, *fantomeC, terrain, directionC);
            directionD = ia(*PacMan, *fantomeD, terrain, directionD);

            pointA = deplacementFantome(directionA, fantomeA, pointA, terrain, &entree, bonus);
            pointB = deplacementFantome(directionB, fantomeB, pointB, terrain, &entree, bonus);
            pointC = deplacementFantome(directionC, fantomeC, pointC, terrain, &entree, bonus);
            pointD = deplacementFantome(directionD, fantomeD, pointD, terrain, &entree, bonus);

            //On affiche la nouvelle frame ainsi générée
            affichage(terrain, score, bonus, frame, vies);

            //compteur de frame
            if(bonus)
            {
                frame++;
            }

            //On réinitialise le bonus après 50 frames
            if(frame>50)
            {
                bonus=0;
                frame=0;
            }

        }while(entree != 'Q');

        if(vies-1>0)
        {

            system("CLS");

            do {

                textcolor(12);
                printf("\n\n\n                              OUILLE !\n\n\n\n");
                textcolor(15);
                printf("Tu as perdu une vie, pour continuer appuye sur la touche espace");
                if(vies>1)
                {
                    printf("\nIl te reste %d vies", vies-1);
                }
                else
                {
                    printf("\nIl te reste %d vie", vies-1);
                }
                c = getch();
                system("CLS");

            }while (c != ' '); //On valide par espace

            terrain[PacMan->i][PacMan->j] = ' ';
            terrain[1][1] = 'C';
            PacMan->i = 1;
            PacMan->j = 1;
        }


    }



    //On vide le buffer clavier car la fonction GetKeyState garde toutes les entrées en mémoire et les ressorts au getch suivant

    system("CLS");

    do {

        textcolor(12);
        printf("\n\n\n                              GAME OVER\n\n\n\n");
        textcolor(15);
        printf("Pour sauvegarder et afficher votre score appuyer sur la touche espace");
        c = getch();
        system("CLS");

    } while (c != ' '); //On valide par espace

    fscore(score);



}
Пример #26
0
Файл: rule.hpp Проект: lynus/spm
	void load(const char *fname) {
		std::ifstream ifs(fname);
		boost::archive::text_iarchive ia(ifs);
		ia>> *this;
	}
Пример #27
0
//int main(int argc,const char** argv){
int main_combine(int argc,const char** argv){
	const unsigned block_size=BLOCK_SIZE_CAO;
	const unsigned thread_count=4;
	const unsigned expander_buffer=4;
	std::vector<column_type> column_list,column_list_;
	column_list.push_back(column_type(t_int));

	Schema* schema=new SchemaFix(column_list);
	ExpandableBlockStreamSingleColumnScan::State ebssc_state1("/home/imdb/temp/Uniform_0_99.column",schema,block_size);
	BlockStreamIteratorBase* ebssc1=new ExpandableBlockStreamSingleColumnScan(ebssc_state1);
	ExpandableBlockStreamSingleColumnScan::State ebssc_state2("/home/imdb/temp/Uniform_0_99.column",schema,block_size);
	BlockStreamIteratorBase* ebssc2=new ExpandableBlockStreamSingleColumnScan(ebssc_state2);

	std::vector<Schema *> inputs;
	inputs.push_back(schema);
	inputs.push_back(schema);

	column_list_.push_back(column_type(t_int));
	column_list_.push_back(column_type(t_int));
	Schema* output=new SchemaFix(column_list_);

	std::vector<BlockStreamIteratorBase *> children_;
	children_.push_back(ebssc1);
	children_.push_back(ebssc2);

	BlockStreamCombinedIterator::State bsci_state(inputs,output,children_);
	BlockStreamCombinedIterator *bsc=new BlockStreamCombinedIterator(bsci_state);

	BlockStreamExpander::State bse_state(schema,bsc,thread_count,block_size,expander_buffer);
	BlockStreamIteratorBase* bse=new BlockStreamExpander(bse_state);

	BlockStreamBase *block=new BlockStreamFix(block_size,8);
	int choice=0;


	std::ostringstream ostr;
	boost::archive::text_oarchive oa(ostr);
	oa.register_type(static_cast<BlockStreamCombinedIterator *>(NULL));
	oa.register_type(static_cast<BlockStreamExpander *>(NULL));
	oa.register_type(static_cast<ExpandableBlockStreamSingleColumnScan *>(NULL));
	Register_Schemas<boost::archive::text_oarchive>(oa);
//	Register_Iterators(oa);
	oa<<bse;

	std::cout<<"Serialization Result:"<<ostr.str()<<std::endl;

	std::istringstream istr(ostr.str());
	boost::archive::text_iarchive ia(istr);
	BlockStreamIteratorBase* des;

	ia.register_type(static_cast<BlockStreamCombinedIterator *>(NULL));
	ia.register_type(static_cast<BlockStreamExpander *>(NULL));
	ia.register_type(static_cast<ExpandableBlockStreamSingleColumnScan *>(NULL));
	Register_Schemas<boost::archive::text_iarchive>(ia);
	ia>>des;
//	return 1;
	while(choice==0){


//		bsf->open();
		des->open();
		cout<<"after open!"<<endl;
		unsigned long long int start=curtick();

		cout<<"ready for the next"<<endl;

		unsigned tuple_count=0;
		while(des->next(block)){
			BlockStreamBase::BlockStreamTraverseIterator* it=block->createIterator();
			while(it->nextTuple()){
				tuple_count++;
			}
			block->setEmpty();
		}
		printf("Time=%f Throughput=%f.\n tuple=%d",getSecond(start),1024/getSecond(start),tuple_count);
		des->close();
		printf("Continue(0) or Not(1) ?\n");

		scanf("%d",&choice);

	}

}
Пример #28
0
inline void load_from_stream(std::basic_istream<Ch, Tr> &i, Data &d, unsigned flags = ARCHIVE_FLAGS_DEFAULT)
{
  Archive ia(i, flags);
  ia & d;
}
Пример #29
0
void LoadGame(const std::string& filename, ServerSaveGameData& server_save_game_data,
              std::vector<PlayerSaveGameData>& player_save_game_data, Universe& universe,
              EmpireManager& empire_manager, SpeciesManager& species_manager,
              CombatLogManager& combat_log_manager, GalaxySetupData& galaxy_setup_data)
{
    //boost::this_thread::sleep(boost::posix_time::seconds(1));

    ScopedTimer timer("LoadGame: " + filename, true);

    // player notifications
    if (ServerApp* server = ServerApp::GetApp())
        server->Networking().SendMessage(TurnProgressMessage(Message::LOADING_GAME));

    GetUniverse().EncodingEmpire() = ALL_EMPIRES;

    std::map<int, SaveGameEmpireData>   ignored_save_game_empire_data;
    SaveGamePreviewData                 ignored_save_preview_data;
    std::vector<PlayerSaveHeaderData>   ignored_player_save_header_data;

    empire_manager.Clear();
    universe.Clear();

    try {
        // set up input archive / stream for loading
        const fs::path path = FilenameToPath(filename);
        fs::ifstream ifs(path, std::ios_base::binary);
        if (!ifs)
            throw std::runtime_error(UNABLE_TO_OPEN_FILE);

        try {
            // first attempt binary deserialziation
            freeorion_bin_iarchive ia(ifs);
            DebugLogger() << "Reading binary iarchive";
            ia >> BOOST_SERIALIZATION_NVP(ignored_save_preview_data);
            ia >> BOOST_SERIALIZATION_NVP(galaxy_setup_data);
            ia >> BOOST_SERIALIZATION_NVP(server_save_game_data);
            ia >> BOOST_SERIALIZATION_NVP(ignored_player_save_header_data);
            ia >> BOOST_SERIALIZATION_NVP(ignored_save_game_empire_data);

            ia >> BOOST_SERIALIZATION_NVP(player_save_game_data);
            ia >> BOOST_SERIALIZATION_NVP(empire_manager);
            ia >> BOOST_SERIALIZATION_NVP(species_manager);
            ia >> BOOST_SERIALIZATION_NVP(combat_log_manager);
            Deserialize(ia, universe);
            DebugLogger() << "Done deserializing";
        } catch (...) {
            // if binary deserialization failed, try more-portable XML deserialization

            // reset to start of stream (attempted binary serialization will have consumed some input...)
            boost::iostreams::seek(ifs, 0, std::ios_base::beg);

            // allocate buffers for serialized gamestate
            DebugLogger() << "Allocating buffers for XML deserialization...";
            std::string serial_str, compressed_str;
            try {
                serial_str.reserve(    std::pow(2.0, 29.0));
                compressed_str.reserve(std::pow(2.0, 26.0));
            } catch (...) {
                DebugLogger() << "Unable to preallocate full deserialization buffers. Attempting deserialization with dynamic buffer allocation.";
            }

            // create archive with (preallocated) buffer...
            freeorion_xml_iarchive xia(ifs);
            // read from save file: uncompressed header serialized data, with compressed main archive string at end...
            // deserialize uncompressed save header info
            xia >> BOOST_SERIALIZATION_NVP(ignored_save_preview_data);
            xia >> BOOST_SERIALIZATION_NVP(galaxy_setup_data);
            xia >> BOOST_SERIALIZATION_NVP(server_save_game_data);
            xia >> BOOST_SERIALIZATION_NVP(ignored_player_save_header_data);
            xia >> BOOST_SERIALIZATION_NVP(ignored_save_game_empire_data);
            // extract compressed gamestate info
            xia >> BOOST_SERIALIZATION_NVP(compressed_str);

            // wrap compressed string in iostream::stream to extract compressed data
            typedef boost::iostreams::basic_array_source<char> SourceDevice;
            SourceDevice compressed_source(compressed_str.data(), compressed_str.size());
            boost::iostreams::stream<SourceDevice> c_source(compressed_source);

            // wrap uncompressed buffer string in iostream::stream to receive decompressed string
            typedef boost::iostreams::back_insert_device<std::string> InsertDevice;
            InsertDevice serial_inserter(serial_str);
            boost::iostreams::stream<InsertDevice> s_sink(serial_inserter);

            // set up filter to decompress data
            boost::iostreams::filtering_istreambuf i;
            i.push(boost::iostreams::zlib_decompressor());
            i.push(c_source);
            boost::iostreams::copy(i, s_sink);
            s_sink.flush();

            // wrap uncompressed buffer string in iostream::stream to extract decompressed string
            SourceDevice serial_source(serial_str.data(), serial_str.size());
            boost::iostreams::stream<SourceDevice> s_source(serial_source);

            // create archive with (preallocated) buffer...
            freeorion_xml_iarchive xia2(s_source);
            // deserialize main gamestate info
            xia2 >> BOOST_SERIALIZATION_NVP(player_save_game_data);
            xia2 >> BOOST_SERIALIZATION_NVP(empire_manager);
            xia2 >> BOOST_SERIALIZATION_NVP(species_manager);
            xia2 >> BOOST_SERIALIZATION_NVP(combat_log_manager);
            Deserialize(xia2, universe);
        }

    } catch (const std::exception& err) {
        ErrorLogger() << "LoadGame(...) failed!  Error: " << err.what();
        return;
    }
    DebugLogger() << "LoadGame : Successfully loaded save file";
}
Пример #30
0
int main(int, char**)
{
    int a1[] = { 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11,
                12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23,
                24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35,
                36, 37, 38, 39, 40};
    const std::size_t N1 = sizeof(a1)/sizeof(a1[0]);
    int a2[] = {  1,   2,   3,   4,   5,   6,   7,   8,   9,  10,  11, 12,
                 13,  14,  15,  16,  17,  18,  19,  20,  21,  22,  23, 24};
    const std::size_t N2 = sizeof(a2)/sizeof(a2[0]);
    std::size_t s[N2] = { 3,  4,  5,  7,  8,  9, 11, 12, 13, 15, 16, 17,
                         22, 23, 24, 26, 27, 28, 30, 31, 32, 34, 35, 36};
    std::valarray<int> v1(a1, N1);
    std::valarray<int> v2(a2, N2);
    std::valarray<std::size_t> ia(s, N2);
    v1[ia] %= v2;
    assert(v1.size() == 41);
    assert(v1[ 0] ==  0);
    assert(v1[ 1] ==  1);
    assert(v1[ 2] ==  2);
    assert(v1[ 3] ==  0);
    assert(v1[ 4] ==  0);
    assert(v1[ 5] ==  2);
    assert(v1[ 6] ==  6);
    assert(v1[ 7] ==  3);
    assert(v1[ 8] ==  3);
    assert(v1[ 9] ==  3);
    assert(v1[10] == 10);
    assert(v1[11] ==  4);
    assert(v1[12] ==  4);
    assert(v1[13] ==  4);
    assert(v1[14] == 14);
    assert(v1[15] ==  5);
    assert(v1[16] ==  5);
    assert(v1[17] ==  5);
    assert(v1[18] == 18);
    assert(v1[19] == 19);
    assert(v1[20] == 20);
    assert(v1[21] == 21);
    assert(v1[22] ==  9);
    assert(v1[23] ==  9);
    assert(v1[24] ==  9);
    assert(v1[25] == 25);
    assert(v1[26] == 10);
    assert(v1[27] == 10);
    assert(v1[28] == 10);
    assert(v1[29] == 29);
    assert(v1[30] == 11);
    assert(v1[31] == 11);
    assert(v1[32] == 11);
    assert(v1[33] == 33);
    assert(v1[34] == 12);
    assert(v1[35] == 12);
    assert(v1[36] == 12);
    assert(v1[37] == 37);
    assert(v1[38] == 38);
    assert(v1[39] == 39);
    assert(v1[40] == 40);

  return 0;
}