Beispiel #1
0
void Keyboard(unsigned char key, int x, int y)
{
    switch(key)
    {
        case 27: //ESC
            exit(0);
            break;
        case 't':   //'t' has been pressed. this will toggle tracking
        case 'T':
            trackingEnabled = !trackingEnabled;
            if (trackingEnabled == false) status = "Tracking disabled.";
            else status = "Tracking enabled.";
            break;
        case 'p':   //'p' has been pressed. this will pause/resume the code.
        case 'P':
            pauses = !pauses;
            if (pauses == true) {
                status = "Code paused, press 'p' again to resume";
                while (pauses == true) {
                    //stay in this loop until
                    switch (waitKey()) {
                        case 112:
                            //change pause back to false
                            pauses = false;
                            status = "Code resumed.";
                            break;
                    }
                }
            }
            break;
        case 'd':
        case 'D': //'d' has been pressed. this will debug mode
            debugMode = !debugMode;
            if (debugMode == false) status = "Debug mode disabled.";
            else status = "Debug mode enabled.";
            break;
            break;
    }
}
int main()
{
    // Set skt abort function to mine (above)
    skt_set_abort(my_skt_abort);

    SERVER_SOCKET srv = skt_server(&port);
    if (srv == -1)
    {
        cerr << "Error: Could not reserve port #" << port << endl;
        cerr << "EXITING" << endl;
        exit(1);
    }

    while (true)
    {
        listen(srv);
    }

    // Done; close server socket
    skt_close(srv);

    return 0;
}
void PPC::loadCameraFromFile(string fName)
{
	// ifstream constructor opens the file
	ifstream inFile(fName, ios::in);

	// exit program if unable to create file
	if (!inFile) { // overloaded ! operator
		cerr << "Camera saved file could not be loaded" << endl;
		exit(1);
	}

	// read camera contents to file sequentially
	inFile >> a;
	inFile >> b;
	inFile >> c;
	inFile >> C;
	inFile >> w;
	inFile >> h;

	buildProjM();

	return; // ifstram destructor closes file
}
int Cryption::decrypt(int fd){

  string IVContents, decryptionKey, decodedKey, decodedIV;

  IVContents = read(fd);
  string encodedIV = IVContents.substr(0,32);
  string FileContents = IVContents.substr(encodedIV.length());

  //Decoding the Key
  decryptionKey = getKey();
  StringSource(decryptionKey, true, new HexDecoder(new StringSink(decodedKey)));
  const byte* dbyteKey = (const byte*) decodedKey.data();

  //Decoding the IV
  StringSource(encodedIV, true, new HexDecoder(new StringSink(decodedIV)));
  const byte* IV = (const byte*) decodedIV.data();

  string decryptedContents;
  //Decrypting actual file
  try{
    CBC_Mode< AES >::Decryption d;
    d.SetKeyWithIV(dbyteKey, CryptoPP::AES::DEFAULT_KEYLENGTH, IV);
    StringSource de(FileContents, true, new StreamTransformationFilter(d, new StringSink (decryptedContents)));
  }
  catch(const CryptoPP::Exception& e){
    cerr<<e.what()<<endl;
    exit(1);
  }


  string DContents = decryptedContents;
  const char *OriginalContents = DContents.c_str();
  ssize_t WriteLength = pwrite(fd, OriginalContents, DContents.length(), 0);
  ftruncate(fd, DContents.length());

  return 0;
}
int Cryption::encrypt(int fd){
  AutoSeededRandomPool prng;
  string encryptedBytes, encodedKey, decodedKey;

  encodedKey = getKey();
  cout<<"Encode: "<<encodedKey<<endl;
  StringSource(encodedKey, true, new HexDecoder(new StringSink(decodedKey)));
  cout<<"Decode: "<<decodedKey<<endl;
  const byte* ebyteKey = (const byte*) decodedKey.data();

  string encodedIV;
  //createIV
  byte IVBytes[AES::BLOCKSIZE];
  prng.GenerateBlock(IVBytes, sizeof(IVBytes));
  StringSource(IVBytes, sizeof(IVBytes), true, new HexEncoder(new StringSink(encodedIV)));

  encryptedBytes = read(fd);

  string encryptedContents;
  //Encrypting the file contents
  try{
    CBC_Mode< AES >::Encryption e;
    e.SetKeyWithIV(ebyteKey, CryptoPP::AES::DEFAULT_KEYLENGTH, IVBytes);
    StringSource file(encryptedBytes, true, new StreamTransformationFilter(e,new StringSink(encryptedContents)));
  }
  catch( const CryptoPP::Exception& e ){
    cerr << e.what() << endl;
    exit(1);
  }

  string output = encodedIV + encryptedContents;
  const char *bufContents = output.c_str();
  ssize_t WriteLength = pwrite(fd, bufContents, output.length(), 0);
  ftruncate(fd, output.length());
  
  return 0;
}
Beispiel #6
0
void CellLine::getParameters_LQ3(double &returnAlpha_X3,
                                 double &returnBeta_X3,
                                 double &returnD_t3,
                                 double &returnGenome_Length,
                                 double &returnAlpha_SSB,
                                 double &returnAlpha_DSB,
                                 long int &returnBase_Pairs) const
{
    if( isLQ3loaded )
    {
        returnAlpha_X3 = alpha_X3;
        returnBeta_X3 = beta_X3;
        returnD_t3 = D_t3;
        returnGenome_Length = genomeLength;
        returnAlpha_SSB = alpha_SSB;
        returnAlpha_DSB = alpha_DSB;
        returnBase_Pairs = base_Pairs;
    }
    else
    {
        cerr << "CellLine: the LQ3 parametrization has not been loaded." << endl;
        exit(1);
    }
}
Beispiel #7
0
double Track_Elsasser2007::getRadialIntegral(const double r_min,
                                             const double r_max) const
{
   if( r_min < 0. || r_max < r_min )
   {
      cerr << "double Track_Elsasser2007::getRadialIntegral(const double, const double) const -- Invalid r_min, r_max specified." << endl;
      exit(1);
   }

   if( r_max == r_min )
      return 0.;

   cerr << "Warning: implementation of double Track_Elsasser2007::getRadialIntegral(const double, const double) const not complete." << endl;

//    double r_end = (r_max < r_penumbra ? r_max : r_penumbra);
//    double dose = 0.;
//    if( r_min < r_core )
//    {
//       if( r_max <= r_core )
//          dose += dose_core * (r_max*r_max - r_min*r_min);
//       else
//       {
//          dose += dose_core * (r_core*r_core - r_min*r_min);
// 
// 
//          dose += 2 * k_p * log(r_end / r_core);
//       }
//    }
//    else if( r_min < r_penumbra )
//    {
//       dose += 2 * k_p * log(r_end / r_min);
//    }
// 
//    return dose / (r_max*r_max - r_min*r_min);
   return -1.;
}
Beispiel #8
0
// create formatted text file for printing
void createTextFile( fstream &readFromFile )
{
   // create text file
   ofstream outPrintFile( "print.txt", ios::out );

   // exit program if ofstream cannot create file
   if ( !outPrintFile ) 
   {
      cerr << "File could not be created." << endl;
      exit( 1 );
   } // end if

   outPrintFile << left << setw( 10 ) << "Account" << setw( 16 )
      << "Last Name" << setw( 11 ) << "First Name" << right
      << setw( 10 ) << "Balance" << endl;

   // set file-position pointer to beginning of readFromFile
   readFromFile.seekg( 0 );

   // read first record from record file
   ClientData client;
   readFromFile.read( reinterpret_cast< char * >( &client ),
      sizeof( ClientData ) );

   // copy all records from record file into text file
   while ( !readFromFile.eof() ) 
   {
      // write single record to text file
      if ( client.getAccountNumber() != 0 ) // skip empty records
         outputLine( outPrintFile, client );

      // read next record from record file
      readFromFile.read( reinterpret_cast< char * >( &client ), 
         sizeof( ClientData ) );
   } // end while
} // end function createTextFile
int main(int argc, char* argv[])
{
	AutoSeededRandomPool prng;

	byte key[AES::DEFAULT_KEYLENGTH] = {0x00,0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09,0x0a,0x0b,0x0c,0x0d,0x0e,0x0f};
	//prng.GenerateBlock(key, sizeof(key));  /* For pseudo random key generation */

	byte plain[] = {0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff};
	string cipher, encoded, recovered;

	/**************************************************************************************
	NOTE:
	***************************************************************************************
	-- plaintext can also be changed to type string of 16 bytes i.e. 16 characters
	-- Only Decryption can also be performed on the same basis
	****************************************************************************************/

	if(sizeof(key) != BLOCK_SIZE_BYTES || sizeof(plain) != BLOCK_SIZE_BYTES)
	{
		cerr << "Either plainText or Key has improper block size" << endl;
		exit(1);
	}

	/*********************************\
	\*********************************/

	// print key
	encoded.clear();
	StringSource(key, sizeof(key), true,
		new HexEncoder(
			new StringSink(encoded)
		) // HexEncoder
	); // StringSource
	cout << "key: " << encoded << endl;

	/*********************************\
	\*********************************/

	try
	{
		cout << "plain text: " << plain << endl;

		ECB_Mode< AES >::Encryption e;
		e.SetKey(key, sizeof(key));

		StringSource ss(plain, sizeof(plain), true, 
			new StreamTransformationFilter(e,
				new StringSink(cipher)//,
					//BlockPaddingScheme::NO_PADDING
			) // StreamTransformationFilter      
		); // StringSource
	}
	catch(const CryptoPP::Exception& e)
	{
		cerr << e.what() << endl;
		exit(1);
	}

	/*********************************\
	\*********************************/

	// print Cipher Text
	encoded.clear();
	StringSource(cipher, true,
		new HexEncoder(
			new StringSink(encoded)
		) // HexEncoder
	); // StringSource
	encoded.resize(16*2);
	cout << "cipher text: " << encoded << endl;

	/*********************************\
	\*********************************/

	try
	{
		ECB_Mode< AES >::Decryption d;
		d.SetKey(key, sizeof(key));

		StringSource s(cipher, true, 
			new StreamTransformationFilter(d,
				new StringSink(recovered)
			) // StreamTransformationFilter
		); // StringSource

		cout << "recovered text: " << recovered << endl;
	}
	catch(const CryptoPP::Exception& e)
	{
		cerr << e.what() << endl;
		exit(1);
	}

	/*********************************\
	\*********************************/

	return 0;
}
Beispiel #10
0
int main(void) {
  int ret;
  // register Ctrl-C handler
  std::signal(SIGINT, exitGraceful);

  if (0 != initialize_enclave(&eid)) {
    cerr << "failed to init enclave" << endl;
    exit(-1);
  }

  mbedtls_net_context listen_fd, client_fd;
  // initialize the object
  ssl_conn_init(eid);
  // initialize threads
  memset(threads, 0, sizeof(threads));

  mbedtls_printf("  . Bind on https://localhost:4433/ ...");
  fflush(stdout);

  if ((ret = mbedtls_net_bind(&listen_fd, NULL, "4433", MBEDTLS_NET_PROTO_TCP)) != 0) {
    mbedtls_printf(" failed\n  ! mbedtls_net_bind returned %d\n\n", ret);
    std::exit(-1);
  }

  mbedtls_printf(" ok\n");

  mbedtls_printf("  [ main ]  Waiting for a remote connection\n");

  // non-block accept
  while (true) {
    // check for Ctrl-C flag
    std::this_thread::sleep_for (std::chrono::seconds(1));
    if (quit.load()) {
      cerr << "Ctrl-C pressed. Quiting..." << endl;
      break;
    }

#ifdef MBEDTLS_ERROR_C
    if (ret != 0) {
      char error_buf[100];
      mbedtls_strerror(ret, error_buf, 100);
      mbedtls_printf("  [ main ]  Last error was: -0x%04x - %s\n", -ret, error_buf);
    }
#endif

    /*
     * 3. Wait until a client connects
     */

    if (0 != mbedtls_net_set_nonblock(&listen_fd)) {
      cerr << "can't set nonblock for the listen socket" << endl;
    }
    ret = mbedtls_net_accept(&listen_fd, &client_fd, NULL, 0, NULL);
    if (ret == MBEDTLS_ERR_SSL_WANT_READ) {
      ret = 0;
      continue;
    } else if (ret != 0) {
      mbedtls_printf("  [ main ] failed: mbedtls_net_accept returned -0x%04x\n", ret);
      break;
    }

    mbedtls_printf("  [ main ]  ok\n");
    mbedtls_printf("  [ main ]  Creating a new thread for client %d\n", client_fd.fd);

    if ((ret = thread_create(&client_fd)) != 0) {
      mbedtls_printf("  [ main ]  failed: thread_create returned %d\n", ret);
      mbedtls_net_free(&client_fd);
      continue;
    }
    ret = 0;
  } // while (true)

  sgx_destroy_enclave(eid);
  return (ret);
}
Beispiel #11
0
int main (int argc, char ** argv)
{
   const clock_t begin_time = clock();
   const solreal begin_walltime = time(NULL);
   string infilnam,outfilnam,gnpnam;
   string progname;
   optFlags options;
   ifstream ifile;
   ofstream ofile;
   
   getOptions(argc,argv,options); //This processes the options from the command line.
   mkFileNames(argv,options,infilnam,outfilnam,gnpnam); //This creates the names used.
   printHappyStart(argv,CURRENTVERSION,PROGRAMCONTRIBUTORS); //Just to let the user know that the initial configuration is OK
   
   cout << endl << "Loading wave function from file: " << infilnam << "... ";
   
   GaussWaveFunction gwf;
   if (!(gwf.readFromFile(infilnam))) { //Loading the wave function
      setScrRedBoldFont();
      cout << "Error: the wave function could not be loaded!\n";
      setScrNormalFont();
      exit(1);
   }
   cout << "Done." << endl;
   
   bondNetWork bnw;
   bnw.readFromFile(infilnam); //Loading the bond-network (if the wave function
                               //was read, there souldn't be problems here.
   bnw.setUpBNW();             //To setup the bond network.
   
   waveFunctionGrid2D grid;    //Defining a grid object
   
   /* Looking for user grid dimensions */
   
   int nn=DEFAULTPOINTSPERDIRECTION;
   if (options.setn1) {
      sscanf(argv[options.setn1],"%d",&nn);
      grid.setNPts(nn);
   } else {
      grid.setNPts(nn);
   }
   
   /* Defining the line direction and other properties, and setting up the grid */
   
   int at1=0,at2=1,at3=2;
   if (bnw.nNuc==1) {
      at1=at2=0,at3=0;
      grid.setUpSimplePlane(bnw,0);
      cout << "The file " << infilnam << " has only one atom" << endl;
      cout << "Using this atom to set the plane...\n";
   } else if (bnw.nNuc==2) {
      at1=0;
      at2=at3=1;
      grid.setUpSimplePlane(bnw,0,1);
      cout << "The file " << infilnam << " has only two atoms" << endl;
      cout << "Using these atoms to set the plane...\n";
   } else {
      if (options.setats) {
         sscanf(argv[options.setats],"%d",&at1);
         sscanf(argv[options.setats+1],"%d",&at2);
         sscanf(argv[options.setats+2],"%d",&at3);
         if (at1<1||at2<1||at3<1||at1>bnw.nNuc||at2>bnw.nNuc||at3>bnw.nNuc) {
            setScrRedBoldFont();
            cout << "Error: one of the given atoms do not exist!\n";
            setScrNormalFont();
            exit(1);
         }
         cout << "Using atoms " << at1 << "(" << bnw.atLbl[at1-1]
         << "), " << at2 << "(" << bnw.atLbl[at2-1] << "), and "
         << at3 << "(" << bnw.atLbl[at3-1] << ") to set the plane."
         << endl;
         at1--;
         at2--;
         at3--;
         grid.setUpSimplePlane(bnw,at1,at2,at3);
      } else {
         at1=at2=at3=0;
         grid.setUpSimplePlane(bnw,0);
         cout << "Using the first atom to set the line...\n";
      }
   }
   //cout << "checkpoint" << endl;
   cout << "The size of the grid will be: " << grid.getNPts(0) << "x" << grid.getNPts(1) << endl;
   cout << "Total number of points that will be computed: " << grid.getNPts(0)*grid.getNPts(1) << endl;
   
   /* Setting the property to be computed */
   
   char prop;
   if (options.prop2plot) {
      prop=argv[options.prop2plot][0];
   } else {
      prop='d';
   }
   
   /* Main calculation loop, chooses between different available fields. */
   
   cout << "Evaluating and writing property..." << endl;
   cout << "(Scalar Field to plot: " << getFieldTypeKeyLong(prop) << ")." << endl << endl;
   switch (prop) {
      case 'd':
         grid.makeTsv(outfilnam,gwf,DENS);
         cout << endl;
         break;
      case 'g':
         grid.makeTsv(outfilnam,gwf,MGRD);
         break;
      case 'l':
         grid.makeTsv(outfilnam,gwf,LAPD);
         cout << endl;
         break;
      case 'G':
         grid.makeTsv(outfilnam,gwf,KEDG);
         break;
      case 'E':
         grid.makeTsv(outfilnam,gwf,ELFD);
         break;
      case 'K':
         grid.makeTsv(outfilnam,gwf,KEDK);
         break;
      case 'S':
         grid.makeTsv(outfilnam,gwf,SENT);
         break;
      case 'L':
         grid.makeTsv(outfilnam,gwf,LOLD);
         break;
      case 'M':
         grid.makeTsv(outfilnam,gwf,MGLD);
         break;
      case 'N':
         grid.makeTsv(outfilnam,gwf,GLOL);
         break;
      case 'p' :
         grid.makeTsv(outfilnam,gwf,LEDV);
         break;
      case 'P' :
         grid.makeTsv(outfilnam,gwf,MLED);
         break;
      case 'r' :
         grid.makeTsv(outfilnam,gwf,ROSE);
         break;
      case 's' :
         grid.makeTsv(outfilnam,gwf,REDG);
         break;
      case 'u' :
         grid.makeTsv(outfilnam,gwf,SCFD);
         break;
      case 'U' :
         grid.makeTsv(outfilnam,gwf,VCFD);
         break;
      case 'V':
         grid.makeTsv(outfilnam,gwf,MEPD);
         break;
      default:
         setScrRedBoldFont();
         cout << "Error: The property \"" << prop << "\" does not exist!" << endl;
         setScrNormalFont();
         exit(1);
         break;
   }
   
   cout << endl << "Output written in file: " << outfilnam << endl;
   
#if _HAVE_GNUPLOT_
   cout << "          Gnuplot file: " << gnpnam << endl;
   solreal dd=0.0e0,r[3];
   for (int i=0; i<3; i++) {
      r[i]=grid.Ca[i]-grid.Cb[i];
      dd+=r[i]*r[i];
   }
   dd=0.45e0*sqrt(dd);
   if (options.mkplt) {
      makeGnuplotFile(options,gnpnam,outfilnam,prop,dd,bnw,at1,at2,at3,grid);
   }
   if (!(options.kpgnp)) {
      cout << "Cleaning temporary files..." << endl;
#if (defined(__APPLE__)||defined(__linux__))
      //string cmdl="rm ";
      //cmdl+=gnpnam;
      //system(cmdl.c_str());
      system("rm contourtemp.dat");
#endif//defined(__APPLE__)||defined(__linux__)
   }
#endif /* _HAVE_GNUPLOT_ */
   
#if (defined(__APPLE__)||defined(__linux__))
   if (options.zipdat) {
      string cmdl;
      cmdl=string("gzip -9f ")+outfilnam;
      cout << "Calling gzip...";
      system(cmdl.c_str());
      cout << " Done!" << endl;
   }
#endif/* defined(__APPLE__)||defined(__linux__) */
   
   /* At this point the computation has ended. Usually this means no errors ocurred. */
   
   setScrGreenBoldFont();
   printHappyEnding();
   printScrStarLine();
   cout << setprecision(3) << "CPU Time: "
        << solreal( clock () - begin_time ) / CLOCKS_PER_SEC << "s" << endl;
   solreal end_walltime=time(NULL);
   cout << "Wall-clock time: " << solreal (end_walltime-begin_walltime) << "s" << endl;
#if DEBUG
   cout << "Debuggin mode (under construction...)" << endl;
#endif
   printScrStarLine();
   setScrNormalFont();
   return 0;
}
Beispiel #12
0
//*******************************************************************************************
void makeGnuplotFile(optFlags &opts, string &gnpn,string &outn,char p2p,
                     solreal dimparam,bondNetWork &bn,int a1,int a2,int a3,waveFunctionGrid2D &grd)
{
   ofstream gfil;
   gfil.open(gnpn.c_str());
   
   /* Choosing the label (legend) for the plot  and the zrange for the plot */
   solreal minzrange,maxzrange;
   string plbl=getFieldTypeKeyShort(p2p);;
   switch (p2p) {
      case 'd':
         minzrange=0.0e0;
         maxzrange=0.6e0;
         break;
      case 'g':
         minzrange=0.0e0;
         maxzrange=2.0e0;
         break;
      case 'l':
         minzrange=-2.0e0;
         maxzrange=2.0e0;
         break;
      case 'E':
         minzrange=0.0e0;
         maxzrange=1.0e0;
         break;
      case 'S':
         minzrange=-10.0e0;
         maxzrange=10.0e0;
         break;
      case 'L':
         minzrange=0.0e0;
         maxzrange=1.0e0;
         break;
      case 'M':
         minzrange=0.0e0;
         maxzrange=2.0e0;
         break;
      case 'N':
         minzrange=0.0e0;
         maxzrange=2.0e0;
         break;
      case 'G':
         minzrange=0.0e0;
         maxzrange=10.0e0;
         break;
      case 'K':
         minzrange=0.0e0;
         maxzrange=10.0e0;
         break;
      case 'p' :
         minzrange=0.0e0;
         maxzrange=2.0e0;
         break;
      case 'P' :
         minzrange=0.0e0;
         maxzrange=2.0e0;
         break;
      case 'r' :
         minzrange=-1.0e0;
         maxzrange=1.0e0;
         break;
      case 's' :
         minzrange=0.0e0;
         maxzrange=1.0e0;
         break;
      case 'u' :
         minzrange=-1.0e0;
         maxzrange=1.0e0;
         break;
      case 'U' :
         minzrange=-1.0e0;
         maxzrange=1.0e0;
         break;
      case 'V':
         minzrange=-0.6e0;
         maxzrange=0.6e0;
         break;
      default:
         setScrRedBoldFont();
         cout << "Error: The property \"" << p2p << "\" does not exist!" << endl;
         setScrNormalFont();
         exit(1);
         break;
   }
   
   gfil << "reset" << endl;
   
   /* In this part the name is scanned for possible occurrings of the character '_'.
    For a proper display in the eps file, it has to be changed to "\_" */
   string line="";
   for (size_t i=0; i<outn.length(); i++) {
      if (outn[i]=='_') {line+='\\';}
      line+=outn[i];
   }
   gfil << "set title '" << line << "'" << endl;
   
   /* Adding an underscore and braces to the atome labels in order to make the numbers
    subindices */
   
   gfil << "set isosample 300, 300" << endl;
   
   gfil << "set zrange [" << minzrange << ":" << maxzrange << "]" << endl;
   
   gfil << "set contour base" << endl;

   gfil << "set cntrparam bspline" << endl;
   
   //gfil << "set cntrparam levels discrete 0.001, 0.005, 0.02, 0.05, 0.1, 0.2, 0.3" <<endl;

   gfil << "set cntrparam levels incremental " << minzrange << ", " 
        << (0.10*(maxzrange-minzrange)) << ", " << maxzrange << endl;
   
   gfil << "unset surface" << endl;
   
   gfil << "set table 'contourtemp.dat'" << endl;
   
   gfil << "splot '" << outn << "'";
   if (p2p=='N' || p2p=='p' || p2p=='U') {gfil << " using 1:2:(sqrt($3*$3+$4*$4))";}
   gfil << endl;
   
   gfil << "unset table" << endl;
   
   gfil << "reset" << endl;
   
   gfil << "unset key" << endl;
   
   gfil << "set size ratio 1" << endl;
   
   gfil << "set tmargin at screen 0.99\nset bmargin at screen 0.01\nset lmargin at screen 0.01" << endl;
   
   gfil << "dimparam=" << dimparam
        << " #Decrease this number to zoom in the plot" << endl;
   
   if (p2p=='N'||p2p=='p'||p2p=='U') {
      gfil << "VMXS=dimparam/40.0 #Maximum lenght of the vectors" << endl;
   }
   
   gfil << "set notics" << endl;
   
   gfil << "set xrange[-dimparam:dimparam]\nset yrange[-dimparam:dimparam]" << endl;
   
   gfil << "minvalfield=" << minzrange << endl << "maxvalfield=" << maxzrange << endl;
   
   gfil << "set cbrange [minvalfield:maxvalfield]" << endl;
   
   gfil << "set style data lines" << endl;
   
   gfil << "set palette rgbformulae 33,13,10" << endl;
   
   if (p2p=='N'||p2p=='p'||p2p=='U') {
      //gfil << "plot '" << outn << "' using 1:2:3:4:(sqrt($3*$3+$4*$4)) "
      //<< "with vectors head size 0.1,20,60 filled lc palette";
      gfil << "plot '" << outn << "' every 1:1 using 1:2:(sqrt($3*$3+$4*$4)>VMXS? VMXS*$3/sqrt($3*$3+$4*$4) : $3):(sqrt($3*$3+$4*$4)>VMXS ? VMXS*$4/sqrt($3*$3+$4*$4) : $4):(sqrt($3*$3+$4*$4)) "
           << "with vectors head size 0.1,20,60 filled lc palette" << endl;
   } else {
      gfil << "plot '" << outn << "' with image" << endl;
   }
   
   if (opts.showcont) {gfil << "replot 'contourtemp.dat' w l lt -1 lw 1 ";}
   else {gfil << " #replot 'contourtemp.dat' w l lt -1 lw 1 #Activate this line to show contours";}
   gfil << endl;
   
   /* Here the atoms' labels are set and written to the gnuplot input file. */
   
   writeScrCharLine(gfil,'#');
   gfil << "# Here are the labes of the atoms" << endl;
   writeScrCharLine(gfil,'#');
   
   string lbl;
   int at[3];
   at[0]=a1; at[1]=a2; at[2]=a3;
   solreal xproj,yproj;
   size_t pos;
   std::ostringstream numst;
   bool IDefPlane;
   for (int i=0; i<bn.nNuc; i++) {
      xproj=0.0e0;
      yproj=0.0e0;
      IDefPlane=false;
      for (int j=0; j<3; j++) {
         xproj+=(bn.R[i][j]-grd.orig[j])*grd.dircos1[j];
         yproj+=(bn.R[i][j]-grd.orig[j])*grd.dircos2[j];
         if ((i==at[j])&&opts.showatlbl) {IDefPlane=true;}
      }
      if (opts.showallatlbl||IDefPlane) {lbl="";} else {lbl="#";}
      lbl+="set label ";
      numst.str("");
      numst << (i+1);
      lbl+=numst.str();
      lbl+=" at ";
      numst.str("");
      numst << xproj << "," << yproj;
      lbl+=numst.str();
      lbl+=" '";
      lbl+=bn.atLbl[i];
      /* Adding an underscore and braces to the atome labels in order to make the numbers
         subindices */
      pos=lbl.find_last_not_of("0123456789");
      if (pos!=string::npos) {
         lbl.insert(pos+1,"_{");
         lbl.append("}");
      }
      lbl+="' front offset character -0.5,-0.15";
      for (int k=0; k<3; k++) {
         if (at[k]==i) {lbl+=" #* This atom was used for setting the plane!";}
      }
      gfil << lbl << endl;
   }
   writeScrCharLine(gfil,'#');
   
   /* Here is enabled the logarithmic scale in the case of G, d or g */
   gfil << "set terminal postscript eps enhanced color fontscale 1.75 lw 2 dashlength 4" << endl;
   
   string imgnam,epsname,extepsname,pdfname;
   imgnam=outn.substr(0,(outn.length()-4));
   imgnam.append("ext.eps"); //here is set the name for the image
   gfil << "set output '";
   gfil << imgnam << "'" << endl; //so far, the image's name is *.eps
   gfil << "set cbtics #deactivate if you do not want tics on the colorbox scale" << endl;
   gfil << "replot" << endl;
   extepsname=imgnam;
   epsname=outn.substr(0,(outn.length()-3));
   epsname.append("eps");
   pdfname=outn.substr(0,(outn.length()-3));
   pdfname.append("eps");
   gfil << "#" << endl;
   writeScrCharLine(gfil,'#');
   gfil << "#                 END OF GNUPLOT COMMANDS" << endl;
   writeScrCharLine(gfil,'#');
   gfil << "#If you want to reconstruct the plot using this file, type:" << endl
        << "#gnuplot " << gnpn << endl
        << "#epstool --copy -b " << extepsname << " " << epsname << endl
        << "#epstopdf --outfile=" << pdfname << " " << extepsname << endl;
   
   gfil.close();
#if (defined(__APPLE__)||defined(__linux__))
   line=string("gnuplot ");
#endif
#if (defined(__CYGWIN__))
   line=string("wgnuplot ");
#endif
   line+=gnpn;
   cout << "Calling gnuplot... ";
   system(line.c_str());
#if _HAVE_EPSTOOL_
   line=string("epstool --copy -b ");
   line+=(imgnam+string(" "));
   imgnam=outn.substr(0,(outn.length()-3)); //Here the image name changes from eps to pdf
   imgnam.append("eps");
   line+=imgnam;
   if (opts.quiet) {line+=string(" > /dev/null 2>&1");}
   system(line.c_str());
#endif
#if _HAVE_EPSTOPDF_
   string pdfnam=outn.substr(0,(outn.length()-3));
   pdfnam.append("pdf");
   line=string("epstopdf --outfile=")+pdfnam+string(" ")+imgnam;
   if (opts.quiet) {line+=string(" > /dev/null 2>&1");}
   system(line.c_str());
#endif
#if (defined(__APPLE__)||defined(__linux__)||defined(__CYGWIN__))
   line="rm ";
#if _HAVE_EPSTOOL_
   line+=imgnam;
#endif
   imgnam=outn.substr(0,(outn.length()-4));
   imgnam.append("ext.eps");
   line+=(string(" ")+imgnam);
   system(line.c_str());
#endif//defined(__APPLE__)||defined(__linux__)
   cout << "Done." << endl;
   return;
}
Beispiel #13
0
int main(int argc, char* argv[])
{
	//Tabela consulta comando
		//Armazena comando HELO
		char helo[6] = "helo ";
		char H_E_L_O[6] = "HELO ";
		//Armazena comando MAIL FROM
		char mail[11] = "mail from:";
		char M_A_I_L[11] = "MAIL FROM:";
		//Armazena comando RCPT
		char rcpt[9] = "rcpt to:";
		char R_C_P_T[9] = "RCPT TO:";
		//Fim de comando
		//char fim[3] = "\r\n";
		char at = '@';
		//Armazena comando DATA
		char D_A_T_A[7] = "DATA\r\n";
		char data[7] = "data\r\n";
		//Armazena comando RSET
		char R_S_E_T[7] = "RSTE\r\n";
		char rset[7] = "rste\r\n";
		//Armazena comando NOOP
		char N_O_O_P[7] = "NOOP\r\n";
		char noop[7] = "noop\r\n";
		//Armazena comando QUIT
		char Q_U_I_T[7] = "QUIT\r\n";
		char quit[7] = "quit\r\n";


    int sock, cliente_sock;
    struct sockaddr_in sock_param, cliente;
    socklen_t addrlen= sizeof(cliente);

	string recebe, envia; //strings dos textos
	const char *char_envia; //usado como parametro no write
	char char_recebe[TAMANHO_BUFFER_RECEBE];
	//char *char_recebe; //usado como parametro no read

	sock = socket(AF_INET, SOCK_STREAM, 0);

	if (sock==-1) //ou <0
		{
	 	perror("opening stream socket"); //erro ao abrir o socket
	 	exit(1);
		}

	bzero(&sock_param, sizeof(sock_param)); //zera o resto da estrutura
	sock_param.sin_family = AF_INET; //declaração da familia arpa net
	sock_param.sin_port=htons(PORTA); /*25 eh a SMTP PORT */
	sock_param.sin_addr.s_addr = INADDR_ANY; //aceita conexão de qq ip, eh setado em 0.0.0.0

	bind (sock, (struct sockaddr*)&sock_param, sizeof(sock_param)); //vincula o socket a um endereço ip
	

	// Escutando Porta
	listen(sock, 5); //"escuta" o socket esperando conexao, numero de conexções q ele guenta ate a certa aparecer (5 maximo)

	
	while (1) //o servidor nunca para
	{
	//strings para formar arquivo
	//Armazena e-mail from
	string str_mail = "";
	//Armazena e-mail to
	string str_rcpt = "";
	//Armazena mensagem
	string mensagem = "";
	//Nome do arquivo
	string nome_arquivo = "";

	//O cliente conecta
	cliente_sock = accept(sock, (struct sockaddr*)&cliente, &addrlen);

	//Quando o servidor aceita uma comunicacao ele envia uma mensage (Primeira Mensagem)
	envia = "220 SERVIDOR TP1 SMTP\n";
	char_envia=envia.c_str(); //converte a string
	send(cliente_sock,char_envia,envia.length(),0);	//envia a msg pro cliente

	//inicializando variáveis a cada nova conexão
	recebeu_helo = false;
	recebeu_mail = false;
	recebeu_rcpt = false;
	recebeu_msg = false;
	recebeu_data = false;
	recebeu_rset = false;
	recebeu_noop = false;
	recebeu_quit = false;
	loop2 = true;

	do {//Loop2
		recebe.clear();
		
		//Esvazia char_recebe
		bzero(char_recebe,TAMANHO_BUFFER_RECEBE);
		//Escuta mensagens e se recebe armazena em "recebe"
		read(cliente_sock, char_recebe, TAMANHO_BUFFER_RECEBE);//;recv (, char_recebe, ,MSG_WAITALL);								
		recebe=string(char_recebe); //converte para string										

		if ((recebeu_data == true) && (recebeu_msg == false))
			{
			//Envia mensagem de confirmação por ter recebido a mensagem
			envia = "250 OK\n";
			char_envia=envia.c_str(); //converte a string
			send(cliente_sock,char_envia,envia.length(),0);	//envia a msg pro cliente
			//carrega string para armazenamento
			mensagem.clear();
			if (recebe [recebe.length()-2] == '\r')
				mensagem = recebe.substr(0 , (recebe.size()-5)) + "\n";		//Retira<CRLF>.<CRLF> = \r\n.\r\n
			else 															//Retira<CR>.<CR> = Termina com "\n.\n" 	
				mensagem = recebe.substr(0 , (recebe.size()-3)) + "\n";
			recebeu_msg = true;
			}

		//Testa mensagem HELO
		int i = 0;
		do{
			if (recebe[i] == helo[i] || recebe[i] == H_E_L_O[i])
				{
				continua = true;
				if (i == 4) //compara o ultimo caracter e esta certo e o comando certo
					{
					//Envia mensagem de confirmação do comando helo
					envia = "250 Hello\n";
					char_envia=envia.c_str(); //converte a string
					send(cliente_sock,char_envia,envia.length(),0);	//envia a msg pro cliente
					continua = false;
					//Recebeu comando helo
					recebeu_helo = true;
					}
				}
			else
				{
				//Nao e o comando helo
				continua = false;
				}
			i++;
			} while (continua);

		//Testa mensagem MAIL
		i = 0;
		do{
			if (recebe[i] == mail[i] || recebe[i] == M_A_I_L[i])
				{
				continua = true;
				if (i == 9) //compara o ultimo caracter e esta certo -> "MAIL FROM:"
					{
					unsigned int num_at = 0;
					//Procura pelo @
					for (unsigned int aux = i+1; aux <= recebe.length()-2; aux++)
						{
						if (recebe[aux] == at)			//o caracter é um @?
							num_at++;
						str_mail = str_mail + recebe[aux];
						}
					if (num_at == 1 ) //&& recebe[recebe.length()-2] == '\r' && recebe[recebe.length()-1] == '\n' )		//tem 1 @ e finaliza certo?
						{
						//Envia mensagem de confirmação do comando MAIL
						envia = "250 OK\n";
						char_envia=envia.c_str(); //converte a string
						send(cliente_sock,char_envia,envia.length(),0);	//envia a msg pro cliente
						//MAIL FROM preenchido
						recebeu_mail = true;
						}
					continua = false;
					}
				}
			else
				{
				//Nao e o comando MAIL
				continua = false;
				}
		i++;
		} while (continua);

		//Testa mensagem RCPT
		i = 0;
		do{
			if (recebe[i] == rcpt[i] || recebe[i] == R_C_P_T[i])
				{
				continua = true;
				if (i == 7) //compara o ultimo caracter e esta certo -> "RCPT TO:"
					{
					unsigned int num_at = 0;
					//Procura pelo @ e armazena o nome do arquivo RCPT TO:<nome do arquivo>@domain
					for (unsigned int aux = i+1; aux <= recebe.length()-2; aux++)
						{
						if (recebe[aux] == at)
							{
							//Nome do arquivo
							nome_arquivo = str_rcpt;
							num_at++;
							}
						str_rcpt = str_rcpt + recebe[aux];
						}
					if (num_at == 1 ) //&& recebe[recebe.length()-2] == '\r' && recebe[recebe.length()-1] == '\n' )		//tem 1 @ e finaliza certo?
						{
						//Envia mensagem de confirmação do comando RCPT
						envia = "250 Accepted\n";
						char_envia=envia.c_str(); //converte a string
						send(cliente_sock,char_envia,envia.length(),0);	//envia a msg pro cliente
						//Se entrou aqui, "nome_arquivo" contém o nome do arquivo certo
						//MAIL FROM preenchido
						recebeu_rcpt = true;
						}
					continua = false;
					}
				}
			else
				{
				//Nao e o comando RCPT
				continua = false;
				}
			i++;
			} while (continua);

			//Testa mensagem DATA
			i = 0;
			do{
				if (recebe[i] == data[i] || recebe[i] == D_A_T_A[i])
					{
					continua = true;
					if (i == 5) //compara o ultimo caracter e esta certo e o comando certo
						{
						//Envia mensagem de confirmação do comando data
						envia = "354 Enter message\n";
						char_envia=envia.c_str(); //converte a string
						send(cliente_sock,char_envia,envia.length(),0);	//envia a msg pro cliente
						//Flags de recebeu data e recebeu mensagem
						recebeu_msg = false;
						recebeu_data = true;
						continua = false;
						}
					}
				else
					{
					//Nao e o comando data
					continua = false;
					}
				i++;
				} while (continua);

			//Testa mensagem RSET
			i = 0;
			do{
				if (recebe[i] == rset[i] || recebe[i] == R_S_E_T[i])
					{
					continua = true;
					if (i == 5) //compara o ultimo caracter e esta certo e o comando certo
						{
						//Envia mensagem de confirmação do comando rset
						envia = "250 Reset OK\n";
						char_envia=envia.c_str(); //converte a string
						send(cliente_sock,char_envia,envia.length(),0);	//envia a msg pro cliente
						//"Zera" Flags: Inicia o server novamente
						recebeu_helo = false;
						recebeu_mail = false;
						recebeu_rcpt = false;
						recebeu_msg = false;
						recebeu_data = false;
						recebeu_rset = false;
						recebeu_noop = false;
						recebeu_quit = false;
						}
					}
				else
					{
					//Nao e o comando data
					continua = false;
					}
				i++;
				} while (continua);
			//Testa mensagem NOOP
			i = 0;
			do{
				if (recebe[i] == noop[i] || recebe[i] == N_O_O_P[i])
					{
					continua = true;
					if (i == 5) //compara o ultimo caracter e esta certo e o comando certo
						{
						//Envia mensagem de confirmação do comando noop
						envia = "250 OK\n";
						char_envia=envia.c_str(); //converte a string
						send(cliente_sock,char_envia,envia.length(),0);	//envia a msg pro cliente
						continua = false;
						//Recebeu comando noop
						recebeu_noop = true;
						}
					}
				else
					{
					//Nao e o comando data
					continua = false;
					}
				i++;
				} while (continua);

			//Testa mensagem QUIT
			i = 0;
			do{
				if (recebe[i] == quit[i] || recebe[i] == Q_U_I_T[i])
					{
					continua = true;
					if (i == 5) //compara o ultimo caracter e esta certo e o comando certo
						{
						//Envia mensagem de confirmação do comando quit
						envia = "221 FECHANDO CONEXAO\n";
						char_envia=envia.c_str(); //converte a string
						send(cliente_sock,char_envia,envia.length(),0);	//envia a msg pro cliente
						//Fecha conexao com o cliente
						close (cliente_sock);
						//Recebeu comando quit
						recebeu_quit = true;
						if ((recebeu_mail == true && recebeu_rcpt == true) && (recebeu_msg == true && recebeu_data == true))		//e-mail completo?
							{
							cout << "Cria arquivo" << endl;
							//pegar nome do arquivo
							nome_arquivo = nome_arquivo + ".mbox";
							//Montar arquivo
							//Funcoes abrir arquivo para gravacao
							ofstream outClientFile(nome_arquivo.c_str(), ios::app);
							if (!outClientFile)
								{
								cerr << "Arquivo nao pode ser aberto" << endl;
								exit(1);
								}
							//Grava arquivo mensagem
							mensagem = "\nDelivered-to: " + str_rcpt + "From: " + str_mail + "\n" + mensagem + "====================";
							outClientFile << mensagem;
							}
						continua = false;
						loop2 = false;
						}						
					}
				else
					{
					//Nao e o comando data
					continua = false;
					}
				i++;
				} while (continua);

		//Comando errado
		if (recebeu_helo == false &&
		recebeu_mail == false &&
		recebeu_rcpt == false &&
		recebeu_msg == false &&
		recebeu_data == false &&
		recebeu_rset == false &&
		recebeu_noop == false &&
		recebeu_quit == false)
			{
			//Envia mensagem de erro de comando
			envia = "500 Comando nao reconhecido\n";
			char_envia=envia.c_str(); //converte a string
			send(cliente_sock,char_envia,envia.length(),0);	//envia a msg pro cliente
			}
		} while (loop2);
	}
	return(0);
}
Beispiel #14
0
int main( int argc, char** argv )
{
	commandline_options cmdopt;
	get_commandline_options( cmdopt, argc, argv );

	typedef void (*generator_type)(
		const std::string&,
		std::ostream&,
		const GenerateOptions&,
		const symbol_map_type&,
		const symbol_map_type&,
		const std::map< size_t, std::string >&,
		const action_map_type&,
		const tgt::parsing_table& );
		
	std::map< std::string, generator_type > generators;
	generators["Java"]		= generate_java;
	generators["C#"]		= generate_csharp;
	generators["C++"]				= generate_cpp;
	generators["JavaScript"]		= generate_javascript;
	generators["D"]					= generate_d;

	std::ifstream ifs( cmdopt.infile.c_str() );
	if( !ifs ) {
		std::cerr << "caper: can't open input file '" << cmdopt.infile << "'" << std::endl;
		exit(1);
	}

	std::ofstream ofs( cmdopt.outfile.c_str() );
	if( !ofs ) {
		std::cerr << "caper: can't open output file '" << cmdopt.outfile << "'" << std::endl;
		exit(1);
	}

	// cpgスキャナ
	typedef std::istreambuf_iterator<char> is_iterator;
	is_iterator b( ifs );	// 即値にするとVC++が頓珍漢なことを言う
	is_iterator e;
	scanner< is_iterator > s( b, e );

	try {
		// cpgパーサ
		cpg::parser p;
		make_cpg_parser( p );

		// cpgパース
		Token token = token_empty;
		while( token != token_eof ) {
			value_type v;
			token = s.get( v );
			try {
				p.push( token, v );
			}
			catch( zw::gr::syntax_error& ) {
				throw syntax_error( v.range.beg, token );
			}
		}


		// 各種情報の収集
		GenerateOptions options;
		options.token_prefix = "token_";
		options.external_token = false;
		options.namespace_name = "caper_parser";
		options.dont_use_stl = false;

		symbol_map_type terminal_types;
		symbol_map_type nonterminal_types;
		collect_informations(
			options,
			terminal_types,
			nonterminal_types,
			p.accept_value() );

		// 対象文法の構文テーブルの作成
		tgt::parsing_table table;
		std::map< std::string, size_t > token_id_map;
		action_map_type actions;
		make_target_parser(
			table,
			token_id_map,
			actions,
			p.accept_value(),
			terminal_types,
			nonterminal_types,
			cmdopt.algorithm == "lr1" );

		// ターゲットパーサの出力
		std::map< size_t, std::string > reverse_token_id_map;
		for( std::map< std::string, size_t >::const_iterator i = token_id_map.begin() ;
			 i != token_id_map.end();
			 ++i ) {
			reverse_token_id_map[(*i).second] = (*i).first;
		}
		generators[ cmdopt.language ](
			cmdopt.outfile,
			ofs,
			options,
			terminal_types,
			nonterminal_types,
			reverse_token_id_map,
			actions,
			table );

	}
	catch( caper_error& e ) {
		if( e.addr < 0 ) {
			std::cerr << "caper: " << e.what() << std::endl;
		} else {
			std::cerr << "caper: " 
					  << e.what()
					  << ", line: " << s.lineno( e.addr )
					  << ", column: " << s.column( e.addr )
					  << std::endl;
		}

		ofs.close();
		std::remove( cmdopt.outfile.c_str() );

		return 1;
	}
	catch( std::exception& e ) {
		std::cerr << e.what() << std::endl;
		return 1;
	}

	return 0;
}
Beispiel #15
0
void CellLine::setParametrization(const string parametrization_type)
{
    if(parametrization_type == "LQ_noDt" && isLQ_noDtLoaded)
        selectedParametrization = &CellLine::parametrization_LQ_noDt;
    
    else if(parametrization_type == "LQ_noDt_T" && isLQ_noDt_TLoaded)
        selectedParametrizationT = &CellLine::parametrization_LQ_noDt_T;
    
    else if(parametrization_type == "LQ" && isLQloaded)
        selectedParametrization = &CellLine::parametrization_LQ;
    
    else if((parametrization_type == "LQ2" || parametrization_type == "LQ2_interpolated_readfile") && isLQ2loaded)
    {
        selectedParametrization = &CellLine::parametrization_LQ2;
        selectedDamageEnhancement = &CellLine::interpolatedDamageEnhancement;
        selectedEtaGeneration = &CellLine::readDamageEnhancement;
        needEtaGenerated = true;
    }
    
    else if(parametrization_type == "LQ3" && isLQ3loaded)
    {
        selectedParametrization = &CellLine::parametrization_LQ3;
        selectedDamageEnhancement = &CellLine::interpolatedDamageEnhancement;
        selectedEtaGeneration = &CellLine::readDamageEnhancement;
        needEtaGenerated = true;
    }
    
    else if(parametrization_type == "LQ2_interpolated_analytic" && isLQ2loaded)
    {
        selectedParametrization = &CellLine::parametrization_LQ2;
        selectedDamageEnhancement = &CellLine::interpolatedDamageEnhancement;
        selectedEtaGeneration = &CellLine::analyticDamageEnhancement;
        needEtaGenerated = true;
    }
    
    else if(parametrization_type == "LQ2_interpolated_MC" && isLQ2loaded)
    {
        selectedParametrization = &CellLine::parametrization_LQ2;
        selectedDamageEnhancement = &CellLine::interpolatedDamageEnhancement;
        selectedEtaGeneration = &CellLine::damageEnhancement;
        needEtaGenerated = true;
    }
    
    else if(parametrization_type == "LQ2_punctual_analytic" && isLQ2loaded)
    {
        selectedParametrization = &CellLine::parametrization_LQ2;
        selectedDamageEnhancement = &CellLine::analyticDamageEnhancement;
    }
    
    else if(parametrization_type == "LQ2_punctual_MC" && isLQ2loaded)
    {
        selectedParametrization = &CellLine::parametrization_LQ2;
        selectedDamageEnhancement = &CellLine::damageEnhancement;
    }
    
    else
    {
        cerr << "CellLine: The selected X-ray parametrization is not provided or has not been loaded." << endl;
        exit(1);
    }

    //clog << "Selected " << parametrization_type << " parametrization for X-rays." << endl;

    if(needEtaGenerated)
    {
        cout << "Generating damage enhancement... ";
        double d = 100;
        int etaCounter = 0;
        int points = 200;
        do {
            doseForEta[etaCounter] = d;
            etaPre[etaCounter] = (*this.*selectedEtaGeneration)(d);
            etaCounter++;
            d = pow( double(10), 2 + etaCounter * (4 + log10(5))/(points - 1) );
        } while( d <= 5e6 );
        needEtaGenerated = false;
        cout << "done." << endl
             << endl << flush;
    }
}
Beispiel #16
0
int main(int argc, char* argv[])
{
  string encoded_mac;
  string line;
  ifstream encrypted_file(argv[1]);
  int count=0;
  string str_cipher, str_fkey, cipher;
  //encrypted_file.read(encoded_mac,64-1);
  if(encrypted_file.is_open())
    getline(encrypted_file,encoded_mac);
  while(!encrypted_file.eof()){
    getline(encrypted_file,str_cipher);
  }
  encrypted_file.close();


  StringSource(argv[2], true, new HexDecoder(
                                             new StringSink(str_fkey)
                                             )
               );

  byte fkey[str_fkey.length()];
  for (int i=0;i<=str_fkey.length();i++)
    fkey[i]=(byte)str_fkey[i];

  byte iv[AES::BLOCKSIZE]; // 16 bytes
  iv[0] = 0;

  string encoded, recovered;
  StringSource(str_cipher, true, new HexDecoder(
                                                new StringSink(cipher))
               );

  SecByteBlock mac_key(16);
  for (int i=0;i<sizeof(mac_key);i++){
    mac_key[i]=1;
  }
  string mac;

  // This step performs AES decryption

  try
    {
      CTR_Mode< AES >::Decryption d;
      d.SetKeyWithIV(fkey, sizeof(fkey), iv);

      // The StreamTransformationFilter removes
      //  padding as required.

      StringSource s(cipher, true,
                     new StreamTransformationFilter(d,
                                                    new StringSink(recovered)
                                                    )
                     ); // StringSource

      cout << "recovered text: " << recovered << endl;
    }
  catch(const CryptoPP::Exception& e)
    {
      cerr << e.what() << endl;
      exit(1);
    }


  StringSource(encoded_mac, true,
               new HexDecoder(
                              new StringSink(mac)
                              ) // HexEncoder
               );

  try
    {
      HMAC< SHA256 > hmac(mac_key, mac_key.size());
      const int flags = HashVerificationFilter::THROW_EXCEPTION | HashVerificationFilter::HASH_AT_END;
      StringSource(recovered + mac, true,
                   new HashVerificationFilter(hmac, NULL, flags)
                   ); // StringSource
      cout<<endl<<endl;
      cout << "HMAC has been implemented and plaintext message is verified" << endl;
    }
  catch(const CryptoPP::Exception& e)
    {
      cerr << e.what() << endl;
      exit(1);
    }

  return 0;
}
Beispiel #17
0
int main(int argc, char* argv[])
{
    std::clock_t start,finish;
    start=clock();
    
    mapp['0'] = 0;
    mapp['1'] = 1;
    mapp['2'] = 2;
    mapp['3'] = 3;
    mapp['4'] = 4;
    mapp['5'] = 5;
    mapp['6'] = 6;
    mapp['7'] = 7;
    mapp['8'] = 8;
    mapp['9'] = 9;
    mapp['a'] = 10;
    mapp['b'] = 11;
    mapp['c'] = 12;
    mapp['d'] = 13;
    mapp['e'] = 14;
    mapp['f'] = 15;
    
    //SecByteBlock key1(16);
    //SecByteBlock key2(AES::DEFAULT_KEYLENGTH);
    unsigned char key1[16];
    unsigned char key2[AES::DEFAULT_KEYLENGTH];
    
    /* generate iv */
   // AutoSeededRandomPool prng;
    //unsigned char iv[AES::BLOCKSIZE];
    //prng.GenerateBlock(iv, sizeof(iv));
    //memset( iv, 0x00, CryptoPP::AES::BLOCKSIZE );
    /*std::fstream fiv("iv.txt",std::ios::out);
     fiv<<iv;
     fiv.close();
     cout << "iv is: " << iv << endl;*/
    
    string encoded1,encoded2,mac,plain,plainlen,cipher;
    
    encoded1.clear();
    encoded2.clear();
    
    std::fstream f(argv[1],std::ios::in);
    f>>encoded1;
    f>>encoded2;
    f.close();
    
    /* read in keys */
    for(int i=0,j=0;i<16*2;){
        key1[j]=mapp[encoded1[i]]*16+mapp[encoded1[i+1]];
        i+=2;
        j++;
    }
    cout << "hexadecimal key for mac is: " << encoded1 << endl;

    
    for(int i=0,j=0;i<AES::DEFAULT_KEYLENGTH*2;){
        key2[j]=mapp[encoded2[i]]*16+mapp[encoded2[i+1]];
        i+=2;
        j++;
    }
    cout << "hexadecimal key for encrypt: " << encoded2 << endl;
  
    
    /*read in plaintext*/
    std::fstream fplain(argv[2],std::ios::in);
    fplain>>plainlen;
    fplain>>plain;
    fplain.close();
    cout << "the length of plain is: " << plainlen << endl;
    cout << "plaint is: " << plain << endl;
    
    /* encrypt */
    try
	{
	    CBC_Mode< AES >::Encryption e;
	    unsigned char ivv[AES::BLOCKSIZE]="0";
	    e.SetKeyWithIV(key2, sizeof(key2), ivv);
        
	    StringSource(plain, true,
                     new StreamTransformationFilter(e,
                                                    new StringSink(cipher)
                                                    ) // StreamTransformationFilter
                     ); // StringSource
	}
	catch(const CryptoPP::Exception& e)
	{
	    cerr << e.what() << endl;
	    exit(1);
	}
    
    // print
    encoded2.clear();
    StringSource(cipher, true,
                 new HexEncoder(
                                new StringSink(encoded2)
                                ) // HexEncoder
                 ); // StringSource
    cout << "hexadecimal cipher text is: " << encoded2 << endl;
    cout << "cipher text is: " << cipher << endl;
    
    time_t ltime;
    time(&ltime);
    char tmp[20];
    sprintf(tmp, "%ld",ltime);
    string s=tmp;
    cout << "the time is: " << s << endl;
    
    try
    {
        CBC_MAC< CryptoPP::AES > cbcmac(key1, sizeof(key1));
        
        StringSource(cipher+s, true,
                     new HashFilter(cbcmac,
                                    new StringSink(mac)
                                    ) // HashFilter
                     ); // StringSource
    }
    catch(const CryptoPP::Exception& e)
    {
        cerr << e.what() << endl;
        exit(1);
    }
    
    encoded1.clear();
    StringSource(mac, true,
                 new HexEncoder(
                                new StringSink(encoded1)
                                ) // HexEncoder
                 ); // StringSource
    
    cout << "hexadecimal cbcmac: " << encoded1 << endl;
    cout << "cbcmac: " << mac << endl;
    
    std::fstream fcipher("ciphertext.txt",std::ios::out);
    fcipher << encoded2.length() <<endl;
    fcipher << s << endl;
    fcipher << encoded1 << endl;
    fcipher << encoded2 <<endl;
    fcipher.close();
	
    finish=clock();
    cout<< "the encrypto running time is " << difftime(finish,start) << " ms" << endl;
    
    return 0;
    
}
Beispiel #18
0
int main(int argc, char** argv)
{
    //OPENGL//////////////////////////////////////////////////
    glutInit(&argc, argv);
    getShaderFilenames(vshadername0, fshadername0, argc, argv);
    glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
    
    //Create the Main Window
    glutInitWindowSize(windowStartSize,windowStartSize);
    glutInitWindowPosition(50,50);
    mainWindow = glutCreateWindow("Motion Tracking");
    
    if(glewInit() != GLEW_OK)
    {
        cerr << "glewInit failed" << endl;
        exit(1);
    }
    
        init();
        glutDisplayFunc(DisplayFunc);
        glutReshapeFunc(Reshape);
        glutKeyboardFunc(Keyboard);
        glutSpecialFunc(specialKey);
        glutIdleFunc(Idle);
    
debugWindow1 = glutCreateSubWindow(mainWindow, windowStartSize/2 + 250, 10, 150, 150);
    init();
    glutDisplayFunc(differenceDisplay);

debugWindow2 = glutCreateSubWindow(mainWindow, windowStartSize/2 + 250, 170, 150, 150);
    init();
    glutDisplayFunc(threshDisplay);
    
debugWindow3 = glutCreateSubWindow(mainWindow, windowStartSize/2 + 250, 330, 150, 150);
    init();
    glutDisplayFunc(finalDisplay);
    
    
//    //Create Debug Mode Difference Image window
//    glutInitWindowSize(windowStartSize,windowStartSize);
//    glutInitWindowPosition(100, 100);
//    debugWindow1 = glutCreateWindow("Debug Mode: Difference Image");
//    
//    if(glewInit() != GLEW_OK)
//    {
//        cerr << "glewInit failed" << endl;
//        exit(1);
//    }
//    
//        init();
//        glutDisplayFunc(differenceDisplay);
//        glutReshapeFunc(differenceReshape);
//        glutKeyboardFunc(Keyboard);
//        glutSpecialFunc(specialKey);
//        glutIdleFunc(Idle);
//    
//    glutHideWindow();
//    
//    //Create Debug Mode Threshold Image window
//    glutInitWindowSize(windowStartSize,windowStartSize);
//    glutInitWindowPosition(100, 100);
//    debugWindow2 = glutCreateWindow("Debug Mode: Threshold Image");
//    
//    if(glewInit() != GLEW_OK)
//    {
//        cerr << "glewInit failed" << endl;
//        exit(1);
//    }
//    
//    init();
//    glutDisplayFunc(threshDisplay);
//    glutReshapeFunc(threshReshape);
//    glutKeyboardFunc(Keyboard);
//    glutSpecialFunc(specialKey);
//    glutIdleFunc(Idle);
//    
//    glutHideWindow();
//    
    

    //for glut to do its thing
    glutMainLoop();
    
    return 0;
}
Beispiel #19
0
void get_commandline_options(
	commandline_options&	cmdopt,
	int						argc,
	char**					argv )
{
	cmdopt.language = "C++";
	cmdopt.algorithm = "lalr1";
		
	int state = 0;
	for( int index = 1 ; index < argc ; index++ ) {
		if( argv[index][0] == '-' ) {
			if( strcmp( argv[index], "-java" ) == 0 ||
				strcmp( argv[index], "-Java" ) == 0 ) {
				cmdopt.language = "Java";
				continue;
			}
			if( strcmp( argv[index], "-cs" ) == 0 || strcmp( argv[index], "-CS" ) == 0 ||
				strcmp( argv[index], "-Cs" ) == 0 || strcmp( argv[index], "-C#" ) == 0 ||
				strcmp( argv[index], "-CSharp" ) == 0 || strcmp( argv[index], "-csharp#" ) == 0 ||
				strcmp( argv[index], "-c#" ) == 0 ) {
				cmdopt.language = "C#";
				continue;
			}
			if( strcmp( argv[index], "-d" ) == 0 || strcmp( argv[index], "-D" ) == 0 ) {
				cmdopt.language = "D";
				continue;
			}
			if( strcmp( argv[index], "-c++" ) == 0 || strcmp( argv[index], "-C++" ) == 0 ||
				strcmp( argv[index], "-cpp" ) == 0 || strcmp( argv[index], "-CPP" ) == 0 ) {
				cmdopt.language = "C++";
				continue;
			}
			if( strcmp( argv[index], "-js" ) == 0 || strcmp( argv[index], "-JS" ) == 0 ||
				strcmp( argv[index], "-javascript" ) == 0 ||
				strcmp( argv[index], "-JavaScript" ) == 0 ||
				strcmp( argv[index], "-JAVASCRIPT" ) == 0 ) {
				cmdopt.language = "JavaScript";
				continue;
			}
			if( strcmp( argv[index], "-lalr1" ) == 0 ) {
				cmdopt.algorithm = "lalr1";
				continue;
			}
			if( strcmp( argv[index], "-lr1" ) == 0 ) {
				cmdopt.algorithm = "lr1";
				continue;
			}

			std::cerr << "caper: unknown option: " << argv[index] << std::endl;
			exit(1);
		}

		switch( state ) {
		case 0: cmdopt.infile  = argv[index]; state++; break;
		case 1: cmdopt.outfile = argv[index]; state++; break;
		default:
			std::cerr << "caper: too many arguments" << std::endl;
			exit(1);
		}
	}

	if( state < 2 ) {
		std::cerr << "caper: usage: caper [ -c++ | -js | -cs | -java ] input_filename output_filename" << std::endl;
		exit(1);
	}
		
}
int main(int argc, char** argv)
{
    if (argc < 3) {
        cerr << "Syntax: " << argv[0] << " nwafilename nwafilename...\n";
        exit(1);
    }

    std::vector<std::string> filenames;
    for (int i=1; i<argc; ++i) {
        filenames.push_back(argv[i]);
    }

    // Read in all NWAs
    std::vector<NwaRefPtr> nwas;
    for (size_t i=0; i<filenames.size(); ++i) {
        ifstream infile(filenames[i].c_str());
        if (!infile.good()) {
            cerr << "Error opening input file " << argv[1] << "\n";
            exit(2);
        }
        nwas.push_back(opennwa::read_nwa(infile));
    }

    // Collect up all symbols
    std::set<opennwa::Symbol> symbols;
    for (size_t i=0; i<nwas.size(); ++i) {
        symbols.insert(nwas.at(i)->beginSymbols(), nwas.at(i)->endSymbols());
    }

    // Apply those symbols to each NWA
    for (size_t i=0; i<nwas.size(); ++i) {
        NwaRefPtr nwa = nwas[i];
        bool anything_new = false;
        for (std::set<opennwa::Symbol>::const_iterator symiter = symbols.begin();
             symiter != symbols.end(); ++symiter)
        {
            anything_new |= nwa->addSymbol(*symiter);
        }

        // If nothing was added, we won't rewrite the file. We'll indicate
        // this by setting that NWA ptr to NULL.
        if (!anything_new) {
            nwas[i] = NULL;
        }
    }

    // Write things back out
    assert(filenames.size() == nwas.size());
    for (size_t i=0; i<nwas.size(); ++i) {
        if (nwas.at(i) != NULL) {
            std::string bakname = filenames.at(i) + ".bak";
            if (boost::filesystem::exists(bakname)) {
                boost::filesystem::remove(bakname);
            }
            boost::filesystem::rename(filenames.at(i), bakname);

            ofstream outfile(filenames.at(i).c_str());

            nwas.at(i)->print(outfile);
        }
    }
}
int main(int argc, char* argv[])
{
	AutoSeededRandomPool prng;

	byte key[AES::DEFAULT_KEYLENGTH];
	prng.GenerateBlock(key, sizeof(key));

	byte iv[AES::BLOCKSIZE];
	prng.GenerateBlock(iv, sizeof(iv));

	string plain = "CBC Mode Test";
	string cipher, encoded, recovered;

	/*********************************\
	\*********************************/

	// Pretty print key
	encoded.clear();
	StringSource(key, sizeof(key), true,
		new HexEncoder(
			new StringSink(encoded)
		) // HexEncoder
	); // StringSource
	cout << "key: " << encoded << endl;

	// Pretty print iv
	encoded.clear();
	StringSource(iv, sizeof(iv), true,
		new HexEncoder(
			new StringSink(encoded)
		) // HexEncoder
	); // StringSource
	cout << "iv: " << encoded << endl;

	/*********************************\
	\*********************************/

	try
	{
		cout << "plain text: " << plain << endl;

		CBC_Mode< AES >::Encryption e;
		e.SetKeyWithIV(key, sizeof(key), iv);

		// The StreamTransformationFilter removes
		//  padding as required.
		StringSource s(plain, true, 
			new StreamTransformationFilter(e,
				new StringSink(cipher)
			) // StreamTransformationFilter
		); // StringSource

#if 0
		StreamTransformationFilter filter(e);
		filter.Put((const byte*)plain.data(), plain.size());
		filter.MessageEnd();

		const size_t ret = filter.MaxRetrievable();
		cipher.resize(ret);
		filter.Get((byte*)cipher.data(), cipher.size());
#endif
	}
	catch(const CryptoPP::Exception& e)
	{
		cerr << e.what() << endl;
		exit(1);
	}

	/*********************************\
	\*********************************/

	// Pretty print
	encoded.clear();
	StringSource(cipher, true,
		new HexEncoder(
			new StringSink(encoded)
		) // HexEncoder
	); // StringSource
	cout << "cipher text: " << encoded << endl;

	/*********************************\
	\*********************************/

	try
	{
		CBC_Mode< AES >::Decryption d;
		d.SetKeyWithIV(key, sizeof(key), iv);

		// The StreamTransformationFilter removes
		//  padding as required.
		StringSource s(cipher, true, 
			new StreamTransformationFilter(d,
				new StringSink(recovered)
			) // StreamTransformationFilter
		); // StringSource

#if 0
		StreamTransformationFilter filter(d);
		filter.Put((const byte*)cipher.data(), cipher.size());
		filter.MessageEnd();

		const size_t ret = filter.MaxRetrievable();
		recovered.resize(ret);
		filter.Get((byte*)recovered.data(), recovered.size());
#endif

		cout << "recovered text: " << recovered << endl;
	}
	catch(const CryptoPP::Exception& e)
	{
		cerr << e.what() << endl;
		exit(1);
	}

	/*********************************\
	\*********************************/

	return 0;
}
Beispiel #22
0
void getOptions(int &argc, char** &argv, optFlags &flags)
{
   string progname;
   progname=":-)  ";
   progname+=argv[0];
   progname+="  (-:";
   size_t pos;
   pos=progname.find("./");
   if (!(pos==string::npos)) {
      progname.erase(pos,2);
   }
   if (argc<2) {
      setScrRedBoldFont();
      cout << "\nError: Not enough arguments." << endl;
      setScrNormalFont();
      cout << "\nTry: \n\t" << argv[0] << " -h\n" << endl << "to view the help menu.\n\n";
      exit(1);
   }
   if (string(argv[1])==string("-h")) {
      printHelpMenu(argc,argv);
      exit(1);
   }
   for (int i=1; i<argc; i++){
      if (argv[i][0] == '-'){
         switch (argv[i][1]){
            case 'a':
               if ((i+2)>=argc) {printErrorMsg(argv,'a');}
               flags.setats=(++i);
               i++;
               break;
            case 'k':
               flags.kpgnp=i;
               break;
            case 'l':
               flags.showatlbls=i;
               break;
            case 'L':
               flags.uponbp=0;
               flags.uponsl=i;
               break;
            case 'n':
               flags.setn1=(++i);
               if (i>=argc) {printErrorMsg(argv,'n');}
               break;
            case 's':
               flags.setstep=(++i);
               if (i>=argc) {printErrorMsg(argv,'s');}
               break;
            case 'o':
               flags.outfname=(++i);
               if (i>=argc) {printErrorMsg(argv,'o');}
               break;
            case 'p':
               flags.prop2plot=(++i);
               if (i>=argc) {printErrorMsg(argv,'p');}
               break;
            case 'P':
               flags.mkplt=i;
               break;
            case 'z':
               flags.zipdat=i;
               break;
            case 'v':
               flags.quiet=0;
               break;
            case 'V':
               progname=argv[0];
               pos=progname.find("./");
               if (!(pos==string::npos)) {progname.erase(pos,2);}
               cout << progname << " " << CURRENTVERSION << endl;
               exit(0);
               break;
            case 'h':
               printHelpMenu(argc,argv);
               exit(1);
               break;
            case '-':
               processDoubleDashOptions(argc,argv,flags,i);
               break;
            default:
               cout << "\nCommand line error. Unknown switch: " << argv[i] << endl;
               cout << "\nTry: \n\t" << argv[0] << " -h\n" << endl << "to view the help menu.\n\n";
               exit(1);
         }
      }
   }
   return;
}//end updateFlags
int
main( int argc, char* argv[])
{
  // seed for random number generator:
  int random_seed;
  // number of matrices:
  int num;
  // dimension of matrices to generate:
  int dim;
  // bound for matrix entries:
  int upper_entry_bound;
  // set of matrices to search:
  Matrix_cont matrices;
  // set of vectors the matrices are build from:
  Vector_cont vectors;
  // handle command line arguments:
  if ( argc < 4 ||
       (num = atoi(argv[1])) <= 0 ||
       (dim = atoi(argv[2])) <= 0 ||
       (upper_entry_bound = atoi(argv[3])) <= 0) {
    cerr << "usage: " << argv[0] <<
      " num dim upper_entry_bound [random_seed]" << endl;
    exit(1);
  }
  if ( argc < 5 || (random_seed = atoi(argv[4])) <= 0) {
  
    #ifdef OUTPUT
    cerr << "No random seed specified - generating it" << endl;
    #endif
  
    // generate random seed
    random_seed = default_random.get_int( 0, (1 << 30));
  }
  else
    random_seed = atoi(argv[4]);
  
  // define random source:
  Random r( random_seed);
  
  #ifdef OUTPUT
  cout << "random seed is " << random_seed << endl;
  #endif
  // maximum entry of all matrices:
  Value max_entry( -1);
  
  for ( int k = 0; k < num; ++k) {
    // generate two vectors a and b to build the cartesian
    // matrix from
    Vector a, b;
    assert( a.size() == 0 && b.size() == 0);
  
    // fill a and b with random values and sort them:
    for ( int i = 0; i < dim; ++i) {
      a.push_back( r( upper_entry_bound));
      b.push_back( r( upper_entry_bound));
    }
    // to test some non-quadratic matrices:
    // for ( i = 0; i < dim / 5; ++i) {
    //   b.push_back( r());
    // }
  
    sort( a.begin(), a.end(), less< Value >());
    sort( b.begin(), b.end(), less< Value >());
  
    /*
    cout << "a = (";
    for ( Vector_iterator pp( a.begin());
    pp != a.end();
    ++pp)
      cout << (*pp) << ", ";
    cout << ")\nb = (";
    for ( Vector_iterator pq( a.begin());
    pq != a.end();
    ++pq)
      cout << (*pq) << ", ";
    cout << ")" << endl;
    */
  
    // evt. update max_entry:
    max_entry = max( a[dim - 1] + b[dim - 1], max_entry);
  
    // keep both vectors:
    vectors.push_back( a);
    vectors.push_back( b);
  } // for ( int k = 0; k < num; ++k)
  
  
  // construct matrices:
  for ( Vector_iterator i( vectors.begin());
        i != vectors.end();
        i += 2)
    {
      Vector_iterator j = i + 1;
      matrices.push_back(
        Matrix( (*i).begin(), (*i).end(),
                (*j).begin(), (*j).end()));
    }
  // search lower bound for a random value v in matrices
  Value bound;
  // assure there is any feasible value in m:
  do
    bound = r.get_int( 0, 2 * upper_entry_bound);
  while ( bound > max_entry);
  
  #ifdef OUTPUT
  cout << "searching upper bound for " << bound << endl;
  #endif
  Value u(
    sorted_matrix_search(
      matrices.begin(),
      matrices.end(),
      sorted_matrix_search_traits_adaptor(
        boost::bind( greater_equal< Value >(), _1, bound),
        *(matrices.begin()))));
  
  #ifdef OUTPUT
  cout << "************* DONE *************\nresult: "
       << u << "\n********************************" << endl;
  CGAL_optimisation_assertion(
    u == compute_upper_bound(
      matrices.begin(), matrices.end(), bound, max_entry));
  #else
  Value brute_force(
    compute_upper_bound(
      matrices.begin(), matrices.end(), bound, max_entry));
  if ( u != brute_force)
    cerr << "\nerror: num( " << num << "), dim ( "
         << dim << "), upper_entry_bound( " << upper_entry_bound
         << ")\nrandom_seed( " << random_seed << ")"
         << "\nresult was " << u << "\ntrivial algorithm gives "
         << brute_force << endl;
  #endif

  return 0;
}
Beispiel #24
0
// Program execution begins with main
int main()
{
    cout << "----------- WELOME TO CRAPS ----------" << endl;

    // Display message if player would start game or not
    char startGame;
    cout << "Would you begin game? [y/n] ";
    cin >> startGame;

    // validation: determine correct input character
    if (startGame == 'n') {
        cout << "Exit games..." << endl;
        exit(0); // exit game
    }
    else if (startGame == 'y') {
        cout << "Press key to throw dice..." << endl;
        cin.get();
    }
    else {
        cout << "Unknown input! Exit." << endl;
        exit(0); // exit game
    }

    // enumeration with constants that represents game status
    enum Status { CONTINUE, WON, LOST };

    srand( time(NULL) ); // initialize every second new seed

    Status gameStatus; 			// determine current game status: won, lose, continue(or point)
    int currentPoint;			// save current point for continuation phase
    int sumOfDice = rollDice(); // current dice sum

    // determine result in first roll
    // main algorithm process
    switch (sumOfDice) {
    case 7:		// win with 7 on first roll
    case 11:	// win with 11 on frist roll
        gameStatus = WON;
        break;
    case 2:		// lose with 2 on first roll
    case 3:		// lose with 3 on first roll
    case 12:	// lose with 12 on first roll
        gameStatus = LOST;
        break;
    default:	// did not win or lose; remember point
        // continuation phase
        gameStatus = CONTINUE;
        currentPoint = sumOfDice;
        cout << "Point is " << currentPoint << endl;
        break;
    }

    // Continuation phase
    // You win if die sum equals "point" i.e. currentPoint
    // and lose if sum equals 7. If non of them is reached,
    // game continues.
    while (gameStatus == CONTINUE)
    {
        cin.get(); // simulate rolling die
        sumOfDice = rollDice(); // roll die

        // determine game status
        if (sumOfDice == currentPoint) // player win
            gameStatus = WON;
        else if (sumOfDice == 7) // player lose
            gameStatus = LOST;
    }

    // Display player status: win or lose
    if (gameStatus == WON)
        cout << "Player wins." << endl;
    else
        cout << "Player lose." << endl;

    return 0;
}
Beispiel #25
0
void usage() {
	cout << "Usage:" << endl
		 << "\tywc dir1 [dir2 ...] -f cpp [py .rb .sh ...]" << endl
		 << "\tywc -h" << endl;
	exit(1);
}
int
main(int argc, char* argv[])
{
#ifndef CGAL_PCENTER_NO_OUTPUT
  CGAL::set_pretty_mode(cerr);
#endif // CGAL_PCENTER_NO_OUTPUT

  int number_of_points;
  int random_seed;

  // handle command line arguments:
  if (argc < 2 || (number_of_points = atoi(argv[1])) <= 0) {
    cerr << "usage: " << argv[0]
         << " num [random_seed]" << endl;
    exit(1);
  }
  if (argc < 3) {

#ifndef CGAL_PCENTER_NO_OUTPUT
    cerr << "No random seed specified - generating it" << endl;
#endif // CGAL_PCENTER_NO_OUTPUT

    // generate random seed
    random_seed = CGAL::get_default_random().get_int(0, (1 << 30));
  }
  else
    random_seed = atoi(argv[2]);

  // define random source:
  Random rnd(random_seed);

#ifndef CGAL_PCENTER_NO_OUTPUT
  cerr << "random seed is " << random_seed << endl;
#endif // CGAL_PCENTER_NO_OUTPUT
  PCont input_points;
  CGAL::cpp11::copy_n(Point_generator(1, rnd),
                number_of_points,
                back_inserter(input_points));

  for (int p(2); p < 5; ++p) {
#ifndef CGAL_PCENTER_NO_OUTPUT
    cerr << "** computing " << p << "-centers:" << endl;
#endif // CGAL_PCENTER_NO_OUTPUT

    PCont centers;
    FT result;
    Timer t;
    t.start();
    rectangular_p_center_2(
      input_points.begin(),
      input_points.end(),
      back_inserter(centers),
      result,
      p);
    t.stop();
#ifndef CGAL_PCENTER_NO_OUTPUT
    cerr << "[time: " << t.time() << " sec]" << endl;
#endif // CGAL_PCENTER_NO_OUTPUT

#ifdef CGAL_USE_LEDA
    // check that all points are covered
    CGAL::I_Infinity_distance_2< K > dist;
    #ifdef _MSC_VER
    {
    #endif
    for (iterator i = input_points.begin(); i != input_points.end(); ++i) {
      iterator j = centers.begin();
      do {
        if (dist(*i, *j) <= result / FT(2))
          break;
        if (++j == centers.end()) {
    #ifndef _MSC_VER
          cerr << "Error: Point " << *i << " is not covered." << endl;
    #else
          cerr << "Error: A point is not covered." << endl;
    #endif
          assert(j != centers.end());
        }
      } while (j != centers.end());
    }
    #ifdef _MSC_VER
    }
    #endif
    
    // check that there is at least one square with two points
    // on opposite sides
    CGAL::I_Signed_x_distance_2< K > xdist;
    CGAL::I_Signed_y_distance_2< K > ydist;
    bool boundary = false;
    #ifdef _MSC_VER
    {
    #endif
    for (iterator i = centers.begin(); i != centers.end(); ++i) {
      int left = 0, right = 0, bottom = 0, top = 0;
      for (iterator j = input_points.begin(); j != input_points.end(); ++j) {
        if (xdist(*i, *j) == result / FT(2))
          ++left;
        if (xdist(*j, *i) == result / FT(2))
          ++right;
        if (ydist(*j, *i) == result / FT(2))
          ++top;
        if (ydist(*i, *j) == result / FT(2))
          ++bottom;
      }
      if ( (left > 0 && right > 0) || (top > 0 && bottom > 0) )
        boundary = true;
    }
    #ifdef _MSC_VER
    }
    #endif
    if (!boundary)
      cerr << "Error: No square has two points on boundary." << endl;
    assert(boundary);
#endif // CGAL_USE_LEDA

  } // for (int p(2); p < 5; ++p)

  return 0;
} 
Beispiel #27
0
int main(int argc, char* argv[])
{
    AutoSeededRandomPool prng;

    byte key[AES::DEFAULT_KEYLENGTH];
    prng.GenerateBlock(key, sizeof(key));

    byte iv[AES::BLOCKSIZE];
    prng.GenerateBlock(iv, sizeof(iv));

    // string plain = "CBC Mode Test";
    string encoded;

    string file_out("");


    char file_path[256];
    int action;

    // default initialization
    strcpy(file_path, "test.dat");
    action = 2;
    while(1)
    {

        static struct option long_option[] =
        {
            {"file", required_argument, 0, 'a'},
            {"action", required_argument, 0, 'b'},
            {"out", required_argument, 0, 'c'},
            {"help", no_argument, 0, 'i'},
            {"key", required_argument, 0, 'd'},
            {"iv", required_argument, 0, 'e'},
            {0, 0, 0, 0}
        };

#define HELP \
    printf("Usage: \n ./crypto_cbc_test [OPTIONS] \n"); \
    printf("    file:            file for doing encryption \n"); \
    printf("    action:          0: encryption, 1: decryption, 2: both Default 2 \n"); \
    printf("    out:             write out file, default no \n"); \
    printf("    key:             key in hex string, if it is not specified, automatically generate \n"); \
    printf("    iv:              Initialization vector, if it is not specified, automatically generate \n"); \
    printf("    help:            help  \n");


        int option_index = 0;
        int rc = getopt_long(argc, argv, "a:b:c:d:e:f:g:h:i", long_option, &option_index);

        if (rc == -1)
            break;

        switch(rc)
        {
        case 'a':
            printf("[Debug] file : %s \n", optarg);
            sprintf(file_path, optarg);
            break;
        case 'b':
            printf("[Debug] action: %s \n", optarg);
            action = atoi(optarg);
            break;
        case 'c':
            printf("[Debug] out: %s \n", optarg);
            file_out.append(optarg);
            break;
        case 'd':
            printf("[Debug] key: %s \n", optarg);
            for (int i = 0; i < 16; i++)
                key[i] = i;
            /*
            CryptoPP::ArraySink ar(key, sizeof(key));
            StringSource(new string(optarg), true, new CryptoPP::HexDecoder( ar ));
            */
            break;
        case 'e':
            printf("[Debug] iv: %s \n", optarg);
            for (int i = 0; i < 16; i++)
                iv[i] = i;

            break;
        case 'i':
            HELP
                    exit(1);
        default:
            printf("invalid option \n");
            exit(1);
        }

    }

    /*********************************\
    \*********************************/

    // Pretty print key
    encoded.clear();
    StringSource(key, sizeof(key), true,
                 new HexEncoder(
                     new StringSink(encoded)
                     ) // HexEncoder
                 ); // StringSource
    cout << "key: " << encoded << endl;

    // Pretty print iv
    encoded.clear();
    StringSource(iv, sizeof(iv), true,
                 new HexEncoder(
                     new StringSink(encoded)
                     ) // HexEncoder
                 ); // StringSource
    cout << "iv: " << encoded << endl;

    /*********************************\
    \*********************************/




    char file_buff[2*1024];


    std::ifstream infile(file_path, std::ifstream::binary);

    std::ofstream outfile;


    if (file_out.length() > 0)
        outfile.open(file_out.c_str());

    if (action == 0)
        cout << "[Encryption]:  ";
    else if (action == 1)
        cout << "[Decryption]:  ";
    else if (action == 2)
        cout << "[Encryption|Decryption]:  ";



    cout  << file_path <<  "size: " << fileSize(file_path) << " (Bytes)" << endl;

    timeCounter tc(true);

    CBC_Mode< AES >::Encryption e;
    e.SetKeyWithIV(key, sizeof(key), iv);


    CBC_Mode< AES >::Decryption d;
    d.SetKeyWithIV(key, sizeof(key), iv);


    // testing
    if (action == 0)
    { // encryption
        CryptoPP::FileSource file(file_path, true,
                                  new StreamTransformationFilter(e,
                                                                 new CryptoPP::FileSink(file_out.c_str())
                                                                 ) // StreamTransformationFilter
                                  ); // StringSource
    } else if (action == 1)
    { // decryption
        CryptoPP::FileSource file(file_path, true,
                                  new StreamTransformationFilter(d,
                                                                 new CryptoPP::FileSink(file_out.c_str())
                                                                 ) // StreamTransformationFilter
                                  ); // StringSource
    }

    return 0;

    int count;
    int acc_count = 0;
    while ((count = infile.read(file_buff, 16).gcount()) > 0)
    {
        string cipher, recovered;

        std::string plain(file_buff, count);
        acc_count += count;

        if (action == 0 || action == 2)
        {

            //cout << "data:" << plain << endl;
            try
            {

                // The StreamTransformationFilter removes
                //  padding as required.

                StringSource s(plain, true,
                               new StreamTransformationFilter(e,
                                                              new StringSink(cipher)
                                                              ) // StreamTransformationFilter
                               ); // StringSource

#if 0
                StreamTransformationFilter filter(e);
                filter.Put((const byte*)plain.data(), plain.size());
                filter.MessageEnd();

                const size_t ret = filter.MaxRetrievable();
                cipher.resize(ret);
                filter.Get((byte*)cipher.data(), cipher.size());
#endif
            }
            catch(const CryptoPP::Exception& e)
            {
                cerr << e.what() << endl;
                cerr << "ERRO 1" << endl;
                exit(1);
            }
        }

        if (action == 1 || action == 2)
        {
            if (action == 1) // just do decryption
                cipher = plain;



            /*********************************\
    \*********************************/
#if 0
            // Pretty print
            encoded.clear();
            StringSource(cipher, true,
                         new HexEncoder(
                             new StringSink(encoded)
                             ) // HexEncoder
                         ); // StringSource
            // cout << "cipher text: " << encoded << endl;
#endif

            /*********************************\
    \*********************************/

            try
            {

                // The StreamTransformationFilter removes
                //  padding as required.
                StringSource s(cipher, true,
                               new StreamTransformationFilter(d,
                                                              new StringSink(recovered)
                                                              ) // StreamTransformationFilter
                               ); // StringSource

#if 0
                StreamTransformationFilter filter(d);
                filter.Put((const byte*)cipher.data(), cipher.size());
                filter.MessageEnd();

                const size_t ret = filter.MaxRetrievable();
                recovered.resize(ret);
                filter.Get((byte*)recovered.data(), recovered.size());
#endif

                // cout << "recovered text: " << recovered << endl;
            }
            catch(const CryptoPP::Exception& e)
            {
                cerr << e.what() << endl;
                cout << "ERROR";
                exit(1);
            }

        }


        cout << "Size: " << acc_count << "," << count << ", " << cipher.size() << endl;

        if (outfile.is_open())
            if (action == 0)
                outfile.write(cipher.c_str(), cipher.size());
            else
                outfile.write(recovered.c_str(), recovered.size());

    }

    tc.Stop();
    printf("Elapsed: %s\n", tc.ToString().c_str());

    if (outfile.is_open())
        outfile.close();

    /*********************************\
    \*********************************/

    return 0;
}
Beispiel #28
0
Tracematch::Tracematch(string n,
                       TRACEMATCH_MODE m,
                       UINT32 v,
                       TracematchSymbolNames s_n,
                       const TracematchRegexTokens& regex_tokens)
    : name(n), mode(m), variables(v), symbol_names(s_n)
{
    /* Create a Thompson NFA from the regex tokens */
    stack<GraphProperties> graph_properties_stack;

    for (TracematchRegexTokens::const_iterator i = regex_tokens.begin();
         i != regex_tokens.end(); ++i) {
        if (i->token == SYMBOL) {
            GraphProperties gp(boost::add_vertex(graph),
                               boost::add_vertex(graph));
            EdgeProperties ep(i-> value);
            boost::add_edge(gp.start, gp.end, ep, graph);
            graph_properties_stack.push(gp);
        }
        else if (i->token == QUESTION) {
            if (graph_properties_stack.size() < 1) {
                output << format_prefix(ERROR) << "Invalid regular expression."
                       << endl;
                exit(EXIT_FAILURE);
            }

            GraphProperties gp1 = graph_properties_stack.top();
            graph_properties_stack.pop();
            GraphProperties gp(boost::add_vertex(graph),
                               boost::add_vertex(graph));
            EdgeProperties ep(SYMBOL_ID_EPSILON);
            boost::add_edge(gp.start, gp1.start, ep, graph);
            boost::add_edge(gp1.end, gp.end, ep, graph);
            boost::add_edge(gp.start, gp.end, ep, graph);
            graph_properties_stack.push(gp);
        }
        else if (i->token == PLUS) {
            if (graph_properties_stack.size() < 1) {
                output << format_prefix(ERROR) << "Invalid regular expression."
                       << endl;
                exit(EXIT_FAILURE);
            }

            GraphProperties gp1 = graph_properties_stack.top();
            graph_properties_stack.pop();
            GraphProperties gp(gp1.start, boost::add_vertex(graph));
            EdgeProperties ep(SYMBOL_ID_EPSILON);
            boost::add_edge(gp1.end, gp.start, ep, graph);
            boost::add_edge(gp1.end, gp.end, ep, graph);
            graph_properties_stack.push(gp);
        }
        else if (i->token == STAR) {
            if (graph_properties_stack.size() < 1) {
                output << format_prefix(ERROR) << "Invalid regular expression."
                       << endl;
                exit(EXIT_FAILURE);
            }

            GraphProperties gp1 = graph_properties_stack.top();
            graph_properties_stack.pop();
            GraphProperties gp(boost::add_vertex(graph),
                               boost::add_vertex(graph));
            EdgeProperties ep(SYMBOL_ID_EPSILON);
            boost::add_edge(gp.start, gp1.start, ep, graph);
            boost::add_edge(gp1.end, gp.start, ep, graph);
            boost::add_edge(gp.start, gp.end, ep, graph);
            graph_properties_stack.push(gp);
        }
        else if (i->token == CONSTANT) {
            if (graph_properties_stack.size() < 1 || i->value < 1) {
                output << format_prefix(ERROR) << "Invalid regular expression."
                       << endl;
                exit(EXIT_FAILURE);
            }

            GraphProperties gp = graph_properties_stack.top();
            graph_properties_stack.pop();

            list<GraphProperties> copies;

            for (UINT32 j = 0; j < (i->value - 1); ++j) {
                /* Copy the current tracematch value - 1 times */
                GraphProperties gp_copy(boost::add_vertex(graph),
                                        boost::add_vertex(graph));
                unordered_map<Vertex, Vertex> vertex_copy_map;
                vertex_copy_map[gp.start] = gp_copy.start;
                vertex_copy_map[gp.end] = gp_copy.end;
                copy_dfs_visitor vis(vertex_copy_map, graph);
                boost::depth_first_search(graph, visitor(vis));
                copies.push_back(gp_copy);
            }

            /* Then */
            EdgeProperties ep(SYMBOL_ID_EPSILON);
            for (UINT32 j = 0; j < (i->value - 1); ++j) {
                GraphProperties gp_copy = copies.front();
                boost::add_edge(gp.end, gp_copy.start, ep, graph);
                gp.end = gp_copy.end;
                copies.pop_front();
            }

            graph_properties_stack.push(gp);
        }
        else if (i->token == OR) {
            if (graph_properties_stack.size() < 2) {
                output << format_prefix(ERROR) << "Invalid regular expression."
                       << endl;
                exit(EXIT_FAILURE);
            }

            GraphProperties gp1 = graph_properties_stack.top();
            graph_properties_stack.pop();
            GraphProperties gp2 = graph_properties_stack.top();
            graph_properties_stack.pop();
            GraphProperties gp(boost::add_vertex(graph),
                               boost::add_vertex(graph));
            EdgeProperties ep(SYMBOL_ID_EPSILON);
            boost::add_edge(gp.start, gp1.start, ep, graph);
            boost::add_edge(gp.start, gp2.start, ep, graph);
            boost::add_edge(gp1.end, gp.end, ep, graph);
            boost::add_edge(gp2.end, gp.end, ep, graph);
            graph_properties_stack.push(gp);
        }
        else if (i->token == THEN) {
            if (graph_properties_stack.size() < 2) {
                output << format_prefix(ERROR) << "Invalid regular expression."
                       << endl;
                exit(EXIT_FAILURE);
            }

            GraphProperties gp1 = graph_properties_stack.top();
            graph_properties_stack.pop();
            GraphProperties gp2 = graph_properties_stack.top();
            graph_properties_stack.pop();
            GraphProperties gp;
            gp.start = gp2.start;
            gp.end = gp1.end;
            EdgeProperties ep(SYMBOL_ID_EPSILON);
            boost::add_edge(gp2.end, gp1.start, ep, graph);
            graph_properties_stack.push(gp);
        }
    }

    if (graph_properties_stack.size() != 1) {
        output << format_prefix(ERROR) << "Invalid regular expression."
               << endl;
        exit(EXIT_FAILURE);
    }

    graph_properties = graph_properties_stack.top();
    graph_properties_stack.pop();
}