当前位置: 首页>>代码示例>>C++>>正文


C++ CommandLine类代码示例

本文整理汇总了C++中CommandLine的典型用法代码示例。如果您正苦于以下问题:C++ CommandLine类的具体用法?C++ CommandLine怎么用?C++ CommandLine使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了CommandLine类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。

示例1: main

int main(int argc, char *argv[]) {
  CommandLine cl;
  MathRandom<MathMersenneTwister> rng;
  Error error;
  ya_check_debug();

  YA_MatD input_matrix;
  YA_MatD output_matrix;

  // Parse the command line
  HandleArgs(cl,argc,argv,&error);

  string outputfile="";
  if (cl.argsize(' ')>0) {
    load(cl.argstring(' ',0),input_matrix);
    if (cl.argsize(' ')>1)
      outputfile=cl.argstring(' ',1);
  } else
    read(cin,input_matrix);

  // Select rows
  if (cl['r']) {
    output_matrix=input_matrix(YA_RowI(cl.argstring('r',0)),":");
    input_matrix=output_matrix;
  }
  
  // Select cols
  if (cl['c']) {
    output_matrix=input_matrix(":",YA_RowI(cl.argstring('c',0)));
    input_matrix=output_matrix;
  }

  // Reorder rows using modulus
  else if (cl['z']) {
    ya_sizet mod=cl.argint('z',0);
    if (mod==0)
      error.generate_error(0,"vm_slice","Cannot specify a mod_num of 0.");
    if (input_matrix.rows()%mod!=0) {
      error.buffer() << "When using -z, the number of rows in the matrix "
                     << "must be evenly divisible by the mod_num.";
      error.addbuf(0,"vm_slice");
    }
    YA_VecI row_order(input_matrix.rows());
    ya_sizet offset=input_matrix.rows()/mod;
    for (ya_sizet i=0; i<input_matrix.rows(); i++) {
      div_t index=div(int(i),int(mod));
      row_order(i)=index.quot+index.rem*offset;
    }
    output_matrix=input_matrix(row_order,":");
  } else    
    output_matrix=input_matrix;

  ya_sizet file_format=YA_DEFAULT_IO;
  if (cl['t'])
    file_format=YA_PRETTY_IO;
  if (cl['b'])
    file_format=YA_BINARY_IO;

  // Random subset
  if (cl['s']) {
    double percent=cl.argdouble('s',0);
    if (percent>1)
      error.generate_error(0,"mat_convert",
        "Random percentage must be between 0 and 1");
    YA_RowI rand_perm(randperm(output_matrix.rows(),rng));
    output_matrix=copy(output_matrix(rand_perm,":"));
    ya_sizet cut_frac=ya_sizet(percent*output_matrix.rows());
    if (cl.argstring('s',1)!="NO_OUTPUT")
      save(cl.argstring('s',1),
           output_matrix(vmcount(cut_frac,":",output_matrix.rows()-1),":"),
           file_format);
    output_matrix=copy(output_matrix(vmcount(cut_frac),":"));
  }

  if (cl['q'])
    ip_transpose(output_matrix);

  if (outputfile=="")
    write(cout,output_matrix,file_format);
  else
    save(outputfile,output_matrix,file_format);
  return 0;
}
开发者ID:behollis,项目名称:muViewBranch,代码行数:83,代码来源:vm_slice.cpp

示例2: UpdateVerificationResults

Result Par1Repairer::Process(const CommandLine &commandline, bool dorepair) {
	// How noisy should we be
	noiselevel = commandline.GetNoiseLevel();

	// Do we want to purge par files on success ?
	bool purgefiles = commandline.GetPurgeFiles();

	// Get filesnames from the command line
	string par1filename = commandline.GetParFilename();
	const list<CommandLine::ExtraFile> &extrafiles = commandline.GetExtraFiles();

	// Determine the searchpath from the location of the main PAR file
	string name;
	DiskFile::SplitFilename(par1filename, searchpath, name);

	// Load the main PAR file
	if (!LoadRecoveryFile(searchpath + name))
		return eLogicError;

	// Load other PAR files related to the main PAR file
	if (!LoadOtherRecoveryFiles(par1filename))
		return eLogicError;

	// Load any extra PAR files specified on the command line
	if (!LoadExtraRecoveryFiles(extrafiles))
		return eLogicError;

	if (noiselevel > CommandLine::nlQuiet)
		cout << endl << "Verifying source files:" << endl << endl;

	// Check for the existence of and verify each of the source files
	if (!VerifySourceFiles())
		return eFileIOError;

	if (completefilecount<sourcefiles.size()) {
		if (noiselevel > CommandLine::nlQuiet)
			cout << endl << "Scanning extra files:" << endl << endl;

		// Check any other files specified on the command line to see if they are
		// actually copies of the source files that have the wrong filename
		if (!VerifyExtraFiles(extrafiles))
			return eLogicError;
	}

	// Find out how much data we have found
	UpdateVerificationResults();

	if (noiselevel > CommandLine::nlSilent)
		cout << endl;

	// Check the verification results and report the details
	if (!CheckVerificationResults())
		return eRepairNotPossible;

	// Are any of the files incomplete
	if (completefilecount<sourcefiles.size()) {
		// Do we want to carry out a repair
		if (dorepair) {
			if (noiselevel > CommandLine::nlSilent)
				cout << endl;

			// Rename any damaged or missnamed target files.
			if (!RenameTargetFiles())
				return eFileIOError;

			// Are we still missing any files
			if (completefilecount<sourcefiles.size()) {
				// Work out which files are being repaired, create them, and allocate
				// target DataBlocks to them, and remember them for later verification.
				if (!CreateTargetFiles())
					return eFileIOError;

				// Work out which data blocks are available, which need to be recreated,
				// and compute the appropriate Reed Solomon matrix.
				if (!ComputeRSmatrix()) {
					// Delete all of the partly reconstructed files
					DeleteIncompleteTargetFiles();
					return eFileIOError;
				}

				// Allocate memory buffers for reading and writing data to disk.
				if (!AllocateBuffers(commandline.GetMemoryLimit())) {
					// Delete all of the partly reconstructed files
					DeleteIncompleteTargetFiles();
					return eMemoryError;
				}
				if (noiselevel > CommandLine::nlSilent)
					cout << endl;

				// Set the total amount of data to be processed.
				progress = 0;
				totaldata = blocksize * sourcefiles.size() * verifylist.size();

				// Start at an offset of 0 within a block.
				u64 blockoffset = 0;
				while (blockoffset < blocksize) { // Continue until the end of the block.
					// Work out how much data to process this time.
					size_t blocklength = (size_t)min((u64)chunksize, blocksize-blockoffset);

					// Read source data, process it through the RS matrix and write it to disk.
//.........这里部分代码省略.........
开发者ID:JeanLouisFLOQUET,项目名称:par2cmdline,代码行数:101,代码来源:par1repairer.cpp

示例3: main

int main(int argc,char **argv) {
 
  CommandLine *parms = CommandLine::Instance();

  parms->add_valid_parm("ref","Reference sequence for alignment");
  parms->add_valid_parm("seq","Sequences to align (fastq)");

  cout << "SmallAlign" << endl;
  cout << parms->usage() << endl; 

  parms->process_args (argc, argv);

  SmallAlign<> aligner(true);

  //Perform alignment, calculate error rate
  
  // Load reference sequence
  FastaReader<> reference_fastafile(parms->get_parm("ref"));
  bool openok = reference_fastafile.open();

  if(openok == false) cerr << "Could not open reference file: " << parms->get_parm("ref") << endl;
  else                cerr << "Opened reference file: " << parms->get_parm("ref") << endl;
  bool fasta_eof=false;

  if(openok) {
    for(;!fasta_eof;) {
      FastaSequence reference = reference_fastafile.next_sequence(fasta_eof);
      if(!fasta_eof) {
        // Forward and Reverse? (true/false)
        aligner.add_reference(reference.sequence,true);
      }
    }
  }
  
  FastPrbReader<BaseProbability<4> > sequences_fastq(parms->get_parm("seq"));

  openok=true;
  if(openok == false) cerr << "Could not open sequences file: " << parms->get_parm("seq") << endl;
  else                cerr << "Opened sequences file: " << parms->get_parm("seq") << endl;
  fasta_eof=false;
 

  int max_cycles=40;
  int max_quality=100;
  int printevery=1000;
  vector<int> errors_by_cycle(max_cycles,0);
  vector<int> errors_by_quality(max_quality,0);
  vector<int> quality_count(max_quality,0);
  vector<int> total_by_cycle (max_cycles,0);
  
  vector<int> errors_count(max_cycles,0);

  if(openok) {
    int n=0;
    for(;!sequences_fastq.eof();) {
      ProbabilitySequence<BaseProbability<4> > seq = sequences_fastq.get_sequence();
      
      SequenceAlignment<> alm;
      alm = aligner.align(seq.string_sequence());

      if(alm.score > 30)
      for(unsigned int m=0;m<alm.matchstring.size();m++) {
        if(alm.matchstring[m] == false) {
          errors_by_quality[seq.sequence()[m].max_probability()*max_quality]++;
          errors_by_cycle[m]++;
        }
        quality_count[seq.sequence()[m].max_probability()*max_quality]++;
        total_by_cycle[m]++;
      }
      errors_count[alm.score]++;

      if((n%printevery == 0) || sequences_fastq.eof()) {
        // Errors by cycle
        cout << "Error rates" << endl;
        for(int cycle=0;(cycle < max_cycles) && (total_by_cycle[cycle] > 0);cycle++) {
          cout << setw(5) << cycle << " ";
          cout << setw(10) << (static_cast<double>(errors_by_cycle[cycle])/static_cast<double>(total_by_cycle[cycle]))*100 << " ";
          cout << setw(10) << errors_by_cycle[cycle] << " ";
          cout << setw(10) << total_by_cycle[cycle] << endl;
        }
        cout << "Score count" << endl;
        for(int errs=0;(errs < max_cycles);errs++) {
          cout << setw(5) << errs << " ";
          cout << setw(10) << errors_count[errs] << endl;
        }
        
        // Errors by quality
        cout << "Error by quality" << endl;
        for(int quality=0;(quality < max_quality);quality++) {
          if(quality_count[quality] != 0) {
            cout << setw(5) << quality << " ";
            cout << setw(5) << errors_by_quality[quality] << " ";
            cout << setw(5) << quality_count[quality] << " ";
            cout << setw(10) << 1-(static_cast<double>(errors_by_quality[quality])/static_cast<double>(quality_count[quality])) << endl;
          }  
        }
      }
      n++;
    }
  } else {
//.........这里部分代码省略.........
开发者ID:emmaggie,项目名称:swift,代码行数:101,代码来源:prb_quality_table.cpp

示例4: main

int main(int argc, char** argv)
{
  std::vector<Pathname> files;
  enum { 
    kTitle       = (1<<0),
    kDescription = (1<<1),
    kLevels      = (1<<2),
    kFilename    = (1<<3)
  };

  unsigned int mode = 0;

  CommandLine argp;
  argp.add_usage("[OPTIONS]... [FILE]...");

  argp.add_option('h', "help",    "", "Displays this help");

  argp.add_option('t', "title", "", "Display title of the levelset");
  argp.add_option('d', "description", "", "Display description of the levelset");
  argp.add_option('l', "levels", "", "Display levels in this levelset");
  argp.add_option('f', "filename", "", "Display filename of the level");

  argp.parse_args(argc, argv);
  argp.set_help_indent(20);

  while (argp.next())
  {
    switch (argp.get_key()) 
    {          
      case 'h':
        argp.print_help();
        exit(EXIT_SUCCESS);
        break;

      case 't':
        mode |= kTitle;
        break;

      case 'd':
        mode |= kDescription;
        break;

      case 'l':
        mode |= kLevels;
        break;

      case 'f':
        mode |= kFilename;
        break;

      case CommandLine::REST_ARG:
        files.push_back(Pathname(argp.get_argument(), Pathname::SYSTEM_PATH));
        break;
    }
  }

  if (files.empty())
  {
    argp.print_help();
    exit(EXIT_SUCCESS);
  }
  else
  {
    // FIXME: a little ugly that levelset loads sprites and savegames
    g_path_manager.set_path("data/");
    SavegameManager savegame_manager("savegames/savegames.scm");
    StatManager stat_manager("savegames/variables.scm");
    Resource::init();
    globals::framebuffer_type  = NULL_FRAMEBUFFER;
    Display::set_video_mode(Size(), false);

    for(auto it = files.begin(); it != files.end(); ++it)
    {
      const Pathname& path = *it;
      Levelset levelset(path);

      if (mode == 0)
      {
        std::cout << "filename      : " << path << std::endl;
        std::cout << "title         : " << levelset.get_title() << std::endl;
        std::cout << "description   : " << levelset.get_description() << std::endl;
        std::cout << "levels        : " << std::endl;
        for(int i = 0; i < levelset.get_level_count(); ++i)
        {
          std::cout << "  " << levelset.get_level(i)->resname << std::endl;
        }
        std::cout << std::endl;
      }
      else
      {
        if (mode & kFilename)
        {
          std::cout << path << ": ";
        }

        if (mode & kTitle)
        {
          std::cout << levelset.get_title() << std::endl;
        }

//.........这里部分代码省略.........
开发者ID:jcs12311,项目名称:pingus,代码行数:101,代码来源:pingus-levelset.cpp

示例5: while

Result Par2Creator::Process(const CommandLine &commandline)
{
  // Get information from commandline
  noiselevel = commandline.GetNoiseLevel();
  blocksize = commandline.GetBlockSize();
  sourceblockcount = commandline.GetBlockCount();
  const list<CommandLine::ExtraFile> extrafiles = commandline.GetExtraFiles();
  sourcefilecount = (u32)extrafiles.size();
  u32 redundancy = commandline.GetRedundancy();
  u64 redundancysize = commandline.GetRedundancySize();
  recoveryblockcount = commandline.GetRecoveryBlockCount();
  recoveryfilecount = commandline.GetRecoveryFileCount();
  firstrecoveryblock = commandline.GetFirstRecoveryBlock();
  recoveryfilescheme = commandline.GetRecoveryFileScheme();
  string par2filename = commandline.GetParFilename();
  string basepath = commandline.GetBasePath();
  size_t memorylimit = commandline.GetMemoryLimit();
  largestfilesize = commandline.GetLargestSourceSize();

  // Compute block size from block count or vice versa depending on which was
  // specified on the command line
  if (!ComputeBlockSizeAndBlockCount(extrafiles))
    return eInvalidCommandLineArguments;

  // Determine how many recovery blocks to create based on the source block
  // count and the requested level of redundancy.
  if ((redundancy > 0 || redundancysize >0) && !ComputeRecoveryBlockCount(redundancy, redundancysize))
    return eInvalidCommandLineArguments;

  // Determine how much recovery data can be computed on one pass
  if (!CalculateProcessBlockSize(memorylimit))
    return eLogicError;

  // Determine how many recovery files to create.
  if (!ComputeRecoveryFileCount())
    return eInvalidCommandLineArguments;

  if (noiselevel > CommandLine::nlQuiet)
  {
    // Display information.
    cout << "Block size: " << blocksize << endl;
    cout << "Source file count: " << sourcefilecount << endl;
    cout << "Source block count: " << sourceblockcount << endl;
    if (redundancy>0 || recoveryblockcount==0)
      cout << "Redundancy: " << redundancy << '%' << endl;
    cout << "Recovery block count: " << recoveryblockcount << endl;
    cout << "Recovery file count: " << recoveryfilecount << endl;
    cout << endl;
  }

  // Open all of the source files, compute the Hashes and CRC values, and store
  // the results in the file verification and file description packets.
  if (!OpenSourceFiles(extrafiles, basepath))
    return eFileIOError;

  // Create the main packet and determine the setid to use with all packets
  if (!CreateMainPacket())
    return eLogicError;

  // Create the creator packet.
  if (!CreateCreatorPacket())
    return eLogicError;

  // Initialise all of the source blocks ready to start reading data from the source files.
  if (!CreateSourceBlocks())
    return eLogicError;

  // Create all of the output files and allocate all packets to appropriate file offets.
  if (!InitialiseOutputFiles(par2filename))
    return eFileIOError;

  if (recoveryblockcount > 0)
  {
    // Allocate memory buffers for reading and writing data to disk.
    if (!AllocateBuffers())
      return eMemoryError;

    // Compute the Reed Solomon matrix
    if (!ComputeRSMatrix())
      return eLogicError;

    // Set the total amount of data to be processed.
    progress = 0;
    totaldata = blocksize * sourceblockcount * recoveryblockcount;

    // Start at an offset of 0 within a block.
    u64 blockoffset = 0;
    while (blockoffset < blocksize) // Continue until the end of the block.
    {
      // Work out how much data to process this time.
      size_t blocklength = (size_t)min((u64)chunksize, blocksize-blockoffset);

      // Read source data, process it through the RS matrix and write it to disk.
      if (!ProcessData(blockoffset, blocklength))
        return eFileIOError;

      blockoffset += blocklength;
    }

    if (noiselevel > CommandLine::nlQuiet)
//.........这里部分代码省略.........
开发者ID:jkansanen,项目名称:par2cmdline-mt,代码行数:101,代码来源:par2creator.cpp

示例6: Impl

CommandLine::CommandLine(const CommandLine &other)
    : impl_(new Impl(other.argv(), other.argc()))
{
}
开发者ID:martinhoefling,项目名称:gromacs,代码行数:4,代码来源:cmdlinetest.cpp

示例7: main

int main (int argc, char *argv[])
{
  uint32_t nWifis = 2;
  uint32_t nStas = 2;
  bool sendIp = true;
  bool writeMobility = false;

  CommandLine cmd;
  cmd.AddValue ("nWifis", "Number of wifi networks", nWifis);
  cmd.AddValue ("nStas", "Number of stations per wifi network", nStas);
  cmd.AddValue ("SendIp", "Send Ipv4 or raw packets", sendIp);
  cmd.AddValue ("writeMobility", "Write mobility trace", writeMobility);
  cmd.Parse (argc, argv);

  NodeContainer backboneNodes;
  NetDeviceContainer backboneDevices;
  Ipv4InterfaceContainer backboneInterfaces;
  std::vector<NodeContainer> staNodes;
  std::vector<NetDeviceContainer> staDevices;
  std::vector<NetDeviceContainer> apDevices;
  std::vector<Ipv4InterfaceContainer> staInterfaces;
  std::vector<Ipv4InterfaceContainer> apInterfaces;

  InternetStackHelper stack;
  CsmaHelper csma;
  Ipv4AddressHelper ip;
  ip.SetBase ("192.168.0.0", "255.255.255.0");

  backboneNodes.Create (nWifis);
  stack.Install (backboneNodes);

  backboneDevices = csma.Install (backboneNodes);

  double wifiX = 0.0;

  YansWifiPhyHelper wifiPhy = YansWifiPhyHelper::Default ();
  wifiPhy.SetPcapDataLinkType (YansWifiPhyHelper::DLT_IEEE802_11_RADIO); 

  for (uint32_t i = 0; i < nWifis; ++i)
    {
      // calculate ssid for wifi subnetwork
      std::ostringstream oss;
      oss << "wifi-default-" << i;
      Ssid ssid = Ssid (oss.str ());

      NodeContainer sta;
      NetDeviceContainer staDev;
      NetDeviceContainer apDev;
      Ipv4InterfaceContainer staInterface;
      Ipv4InterfaceContainer apInterface;
      MobilityHelper mobility;
      BridgeHelper bridge;
      WifiHelper wifi = WifiHelper::Default ();
      NqosWifiMacHelper wifiMac = NqosWifiMacHelper::Default ();
      YansWifiChannelHelper wifiChannel = YansWifiChannelHelper::Default ();
      wifiPhy.SetChannel (wifiChannel.Create ());

      sta.Create (nStas);
      mobility.SetPositionAllocator ("ns3::GridPositionAllocator",
                                     "MinX", DoubleValue (wifiX),
                                     "MinY", DoubleValue (0.0),
                                     "DeltaX", DoubleValue (5.0),
                                     "DeltaY", DoubleValue (5.0),
                                     "GridWidth", UintegerValue (1),
                                     "LayoutType", StringValue ("RowFirst"));


      // setup the AP.
      mobility.SetMobilityModel ("ns3::ConstantPositionMobilityModel");
      mobility.Install (backboneNodes.Get (i));
      wifiMac.SetType ("ns3::ApWifiMac",
                       "Ssid", SsidValue (ssid));
      apDev = wifi.Install (wifiPhy, wifiMac, backboneNodes.Get (i));

      NetDeviceContainer bridgeDev;
      bridgeDev = bridge.Install (backboneNodes.Get (i), NetDeviceContainer (apDev, backboneDevices.Get (i)));

      // assign AP IP address to bridge, not wifi
      apInterface = ip.Assign (bridgeDev);

      // setup the STAs
      stack.Install (sta);
      mobility.SetMobilityModel ("ns3::RandomWalk2dMobilityModel",
                                 "Mode", StringValue ("Time"),
                                 "Time", StringValue ("2s"),
                                 "Speed", StringValue ("ns3::ConstantRandomVariable[Constant=1.0]"),
                                 "Bounds", RectangleValue (Rectangle (wifiX, wifiX+5.0,0.0, (nStas+1)*5.0)));
      mobility.Install (sta);
      wifiMac.SetType ("ns3::StaWifiMac",
                       "Ssid", SsidValue (ssid),
                       "ActiveProbing", BooleanValue (false));
      staDev = wifi.Install (wifiPhy, wifiMac, sta);
      staInterface = ip.Assign (staDev);

      // save everything in containers.
      staNodes.push_back (sta);
      apDevices.push_back (apDev);
      apInterfaces.push_back (apInterface);
      staDevices.push_back (staDev);
      staInterfaces.push_back (staInterface);
//.........这里部分代码省略.........
开发者ID:shuiziliuBUPT,项目名称:HelloWorld,代码行数:101,代码来源:wifi-wired-bridging.cpp

示例8: main

int
main(int argc, char* argv[])
{
  // setting default parameters for Wifi
  // enable rts cts all the time.
  Config::SetDefault ("ns3::WifiRemoteStationManager::RtsCtsThreshold", StringValue ("0"));
  // disable fragmentation
  Config::SetDefault ("ns3::WifiRemoteStationManager::FragmentationThreshold", StringValue ("2200"));
  Config::SetDefault("ns3::WifiRemoteStationManager::NonUnicastMode",
                     StringValue("OfdmRate24Mbps"));

  // setting default parameters for PointToPoint links and channels
  Config::SetDefault("ns3::PointToPointNetDevice::DataRate", StringValue("1Mbps"));
  Config::SetDefault("ns3::PointToPointChannel::Delay", StringValue("10ms"));
  Config::SetDefault("ns3::DropTailQueue::MaxPackets", StringValue("20"));


  std::uint32_t max_routers = 1;
  std::string cSize = "100";
  std::string cSplit = "75";

  // Read optional command-line parameters (e.g., enable visualizer with ./waf --run=<> --visualize
  CommandLine cmd;
  cmd.AddValue("cSize", "Cache Size", cSize);
  cmd.AddValue("cSplit", "Cache Split", cSplit);
  cmd.AddValue("routers", "number of routers", max_routers);
  cmd.Parse(argc, argv);


  Packet::EnablePrinting ();

  // Wifi config

  WifiHelper wifi = WifiHelper::Default ();


  // Nodes
  NodeContainer sta_consumers;
  NodeContainer sta_mobile_consumers;
  NodeContainer ap;
  NodeContainer routers;
  NodeContainer producers;

  // ??
  NetDeviceContainer staDevs;
  PacketSocketHelper packetSocket;

  // 5 stationary consumers, 5 mobile, 4 APs and 1 router
  sta_consumers.Create(3*max_routers);
  sta_mobile_consumers.Create(7*max_routers);
  ap.Create (5*max_routers);
  routers.Create(max_routers);
  producers.Create(1);

  // give packet socket powers to nodes.
  packetSocket.Install(sta_mobile_consumers);
  packetSocket.Install(sta_consumers);
  packetSocket.Install (ap);

  // Wifi Config
  NqosWifiMacHelper wifiMac = NqosWifiMacHelper::Default ();
  YansWifiPhyHelper wifiPhy = YansWifiPhyHelper::Default ();
  YansWifiChannelHelper wifiChannel = YansWifiChannelHelper::Default ();
  wifiPhy.SetChannel (wifiChannel.Create ());
  wifiPhy.Set("TxPowerStart", DoubleValue(5));
  wifiPhy.Set("TxPowerEnd", DoubleValue(5));
  Ssid ssid = Ssid ("wifi-default");
  wifi.SetRemoteStationManager ("ns3::ArfWifiManager");
  // setup stas.
  wifiMac.SetType ("ns3::StaWifiMac",
                   "Ssid", SsidValue (ssid),
                   "ActiveProbing", BooleanValue (false));
  // install wifi
  wifi.Install(wifiPhy, wifiMac, sta_mobile_consumers);
  wifi.Install(wifiPhy, wifiMac, sta_consumers);
  // setup ap.
  wifiMac.SetType ("ns3::ApWifiMac",
                   "Ssid", SsidValue (ssid));
  wifi.Install (wifiPhy, wifiMac, ap);


  // Mobility config -- Change max_routers value to change size of sim
  int number_rows = sqrt(max_routers);
  int x = 0;
  int y = 0;
  int pos_counter = 0;
  Ptr<UniformRandomVariable> randomizerX = CreateObject<UniformRandomVariable>();
  Ptr<UniformRandomVariable> randomizerY = CreateObject<UniformRandomVariable>();

  MobilityHelper stationary_mobility;
  stationary_mobility.SetMobilityModel("ns3::ConstantPositionMobilityModel");

  MobilityHelper mobility;
  mobility.SetMobilityModel("ns3::GaussMarkovMobilityModel", "Bounds", BoxValue(Box (0, number_rows*10, 0, number_rows*10, 0, 0)), 
	  "TimeStep", TimeValue(Seconds(1)));

  // Place router in center of box
  randomizerX->SetAttribute("Min", DoubleValue(5));
  randomizerX->SetAttribute("Max", DoubleValue(5));
  randomizerY->SetAttribute("Min", DoubleValue(5));
//.........这里部分代码省略.........
开发者ID:seanbraley,项目名称:ndn-split-caching,代码行数:101,代码来源:scenario-03.cpp

示例9: _

void
PingusMain::parse_args(int argc, char** argv)
{
  CommandLine argp;
  argp.add_usage(_("[OPTIONS]... [FILE]"));
  argp.add_doc(_("Pingus is a puzzle game where you need to guide a bunch of little penguins around the world."));

  argp.add_group(_("General Options:"));
  argp.add_option('h', "help", "", 
                  _("Displays this help"));
  argp.add_option('V', "version", "", 
                  _("Print version number and exit"));
  argp.add_option('v', "verbose", "",
                  _("Enable info level log output"));
  argp.add_option('D', "debug", "", 
                  _("Enable debug level log output"));
  argp.add_option('Q', "quiet", "", 
                  _("Disable all log output"));   

  argp.add_group(_("Display Options:"));
  argp.add_option('w', "window", "",
                  _("Start in Window Mode"));
  argp.add_option('f', "fullscreen", "",
                  _("Start in Fullscreen"));
  argp.add_option('r', "renderer", "RENDERER",
                  _("Use the given renderer (default: sdl)"));
  argp.add_option('g', "geometry", "{width}x{height}",  
                  _("Set the window resolution for pingus (default: 800x600)"));
  argp.add_option('R', "fullscreen-resolution", "{width}x{height}",  
                  _("Set the resolution used in fullscreen mode (default: 800x600)"));
  argp.add_option(346, "software-cursor", "",
                  _("Enable software cursor"));

  argp.add_group(_("Game Options:"));
  argp.add_option(337, "no-auto-scrolling", "",
                  _("Disable automatic scrolling"));
  argp.add_option(338, "drag-drop-scrolling", "",
                  _("Enable drag'n drop scrolling"));

  argp.add_group(_("Sound Options:"));
  argp.add_option('s', "disable-sound", "", 
                  _("Disable sound"));
  argp.add_option('m', "disable-music", "", 
                  _("Disable music"));

  argp.add_group("Language Options:");
  argp.add_option('l', "language", "LANG",
                  _("Select language to use with Pingus"));
  argp.add_option(365, "list-languages", "",
                  _("List all available languages"));

  argp.add_group("Editor Options:");
  argp.add_option('e', "editor", "",
                  _("Loads the level editor"));

  argp.add_group(_("Directory Options:"));
  argp.add_option('d', "datadir", _("DIR"),
                  _("Load game datafiles from DIR"));
  argp.add_option('u', "userdir", _("DIR"),
                  _("Load config files and store savegames in DIR"));
  argp.add_option('a', "addon", _("DIR"),
                  _("Load game modifications from DIR"));
  argp.add_option(342, "no-cfg-file", "",
                  _("Don't read ~/.pingus/config"));
  argp.add_option('c', "config", _("FILE"),
                  _("Read config options from FILE"));
  argp.add_option(360, "controller", "FILE",
                  _("Uses the controller given in FILE"));

  argp.add_group(_("Debug Options:"));
  argp.add_option(334, "developer-mode",  "",  
                  _("Enables some special features for developers"));
  argp.add_option('t', "speed", "SPEED",
                  _("Set the game speed (0=fastest, >0=slower)"));
  argp.add_option('k', "fps", "FPS",
                  _("Set the desired game framerate (frames per second)"));
  argp.add_option(344, "tile-size", "INT",
                  _("Set the size of the map tiles (default: 32)"));

  argp.parse_args(argc, argv);
  argp.set_help_indent(20);

  while (argp.next())
  {
    switch (argp.get_key()) 
    {          
      case 'r': // --renderer
        if (argp.get_argument() == "help")
        {
          std::cout << "Available renderers: " << std::endl;
          std::cout << "   delta: Software rendering with dirty-rectangles" << std::endl;
          std::cout << "     sdl: Software rendering" << std::endl;
          std::cout << "  opengl: Hardware accelerated graphics" << std::endl;
          std::cout << "    null: No rendering at all, for debugging" << std::endl;
          exit(EXIT_SUCCESS);
        }
        else
        {
          cmd_options.framebuffer_type.set(framebuffer_type_from_string(argp.get_argument()));

//.........这里部分代码省略.........
开发者ID:liushuyu,项目名称:aosc-os-abbs,代码行数:101,代码来源:pingus_main.cpp

示例10: main

/**
 * This scenario simulates a one-node two-custom-app scenario:
 *
 *   +------+ <-----> (CustomApp)
 *   | Node |
 *   +------+ <-----> (Hijacker)
 *
 *     NS_LOG=CustomApp ./waf --run=ndn-custom-apps
 */
int
main(int argc, char* argv[])
{
  // Read optional command-line parameters (e.g., enable visualizer with ./waf --run=<> --visualize
  CommandLine cmd;
  cmd.Parse(argc, argv);

  AnnotatedTopologyReader topologyReader("", 1);
//  topologyReader.SetFileName("src/ndnSIM/examples/topologies/topo-custom1.txt");
//  topologyReader.SetFileName("src/ndnSIM/examples/topologies/topo-custom2.txt");
  topologyReader.SetFileName("src/ndnSIM/examples/topologies/topo-custom3.txt");
  topologyReader.Read();

  // Creating nodes
//  Ptr<Node> node = CreateObject<Node>();
  // Install Content Store stack on cache node
  ndn::StackHelper ndnHelperCache;
  ndnHelperCache.SetOldContentStore("ns3::ndn::cs::Lru", "MaxSize", "10");
  ndnHelperCache.Install(Names::Find<Node>("cacheServer")); 

  // Install NDN stack on all nodes
/*  ndn::StackHelper ndnHelper;
  ndnHelper.SetDefaultRoutes(true);
  ndnHelper.InstallAll();*/

// Install NDN stack on rest of the nodes
  ndn::StackHelper ndnHelper;
  ndnHelper.Install(Names::Find<Node>("client1"));
  ndnHelper.Install(Names::Find<Node>("client2"));
  ndnHelper.Install(Names::Find<Node>("client3"));
  ndnHelper.Install(Names::Find<Node>("originServer"));


// Choosing forwarding strategy
  ndn::StrategyChoiceHelper::InstallAll("/prefix", "/localhost/nfd/strategy/best-route");

//  Ptr<Node> consumers1 = Names::Find<Node>("client1");
//  Ptr<Node> consumers2 = Names::Find<Node>("client2");
//  Ptr<Node> consumers3 = Names::Find<Node>("client3");
  Ptr<Node> consumers[3] = {Names::Find<Node>("client1"), Names::Find<Node>("client2"), Names::Find<Node>("client3")};
  Ptr<Node> producer = Names::Find<Node>("originServer");

  cout << "Installing Global routing interface on all nodes";

// Installing global routing interface on all nodes
  ndn::GlobalRoutingHelper ndnGlobalRoutingHelper;
  ndnGlobalRoutingHelper.InstallAll();

  cout << " Creating app1....";
  // App1
  /*ndn::AppHelper app1("CustomApp");
  app1.SetPrefix("/root");
  app1.Install(consumers1);
  app1.Install(consumers2);
  app1.Install(consumers3);*/

//  for (int i = 0; i < 3; i++) {
 //   std::cout << "i: " << i;
    ndn::AppHelper consumerHelper1("ns3::ndn::ConsumerCbr");
    consumerHelper1.SetAttribute("Frequency", StringValue("1")); 
    consumerHelper1.SetPrefix("/root/" + Names::FindName(consumers[0]));
//    consumerHelper.Install(consumers[i]);
    ns3::ApplicationContainer ac1 = consumerHelper1.Install(consumers[0]);
    ac1.Start(Seconds (1.0));
    ac1.Stop(Seconds (2.0));
//  }
    
    ndn::AppHelper consumerHelper2("ns3::ndn::ConsumerCbr");
    consumerHelper2.SetAttribute("Frequency", StringValue("1")); 
    consumerHelper2.SetPrefix("/root/" + Names::FindName(consumers[1]));
//    consumerHelper.Install(consumers[i]);
    //consumerHelper2.Install(consumers[1]).Start(Seconds (2.0));
    ns3::ApplicationContainer ac2 = consumerHelper2.Install(consumers[1]);
    ac2.Start(Seconds (2.0));
    ac2.Stop(Seconds (3.0));
    //consumerHelper2.Install(consumers[0]).Stop(Seconds (3.0));
    
    ndn::AppHelper consumerHelper3("ns3::ndn::ConsumerCbr");
    consumerHelper3.SetAttribute("Frequency", StringValue("1")); 
    consumerHelper3.SetPrefix("/root/" + Names::FindName(consumers[2]));
//    consumerHelper.Install(consumers[i]);
    //consumerHelper3.Install(consumers[2]).Start(Seconds (3.0));
    ns3::ApplicationContainer ac3 = consumerHelper3.Install(consumers[2]);
    ac3.Start(Seconds (3.0));
    ac3.Stop(Seconds (4.0));
    //consumerHelper3.Install(consumers[0]).Stop(Seconds (4.0));

  // App2
  //ndn::AppHelper app2("Hijacker");
  //app2.Install(producer); // last node

//.........这里部分代码省略.........
开发者ID:AkshaySrivatsa03,项目名称:two-level-cache,代码行数:101,代码来源:ndn-custom-apps-multiCli.cpp

示例11: main

int
main(int argc, char* argv[])
{
  // setting default parameters for PointToPoint links and channels
  Config::SetDefault("ns3::PointToPointNetDevice::DataRate", StringValue("1Mbps"));
  Config::SetDefault("ns3::PointToPointChannel::Delay", StringValue("10ms"));
  Config::SetDefault("ns3::QueueBase::MaxSize", StringValue("20p"));

  // Read optional command-line parameters (e.g., enable visualizer with ./waf --run=<> --visualize
  CommandLine cmd;
  cmd.Parse(argc, argv);

  // Creating nodes
  Ptr<Node> consumer = CreateObject<Node>();
  Ptr<Node> intRouter = CreateObject<Node>();
  NodeContainer uclaRegion;
  uclaRegion.Create(3);

  // Connecting nodes using two links
  PointToPointHelper p2p;
  p2p.Install(consumer, intRouter);
  p2p.Install(intRouter, uclaRegion.Get(0));
  p2p.Install(intRouter, uclaRegion.Get(1));
  p2p.Install(uclaRegion.Get(0), uclaRegion.Get(1));
  p2p.Install(uclaRegion.Get(1), uclaRegion.Get(2));

  // Install NDN stack on all nodes
  ndn::StackHelper ndnHelper;
  ndnHelper.SetDefaultRoutes(true);
  ndnHelper.InstallAll();

  // Install Routes Manually
  ndn::FibHelper::AddRoute(intRouter, ndn::Name("/ucla"), uclaRegion.Get(1), 1);

  // Configure NetworkRegionTable
  ndn::NetworkRegionTableHelper::AddRegionName(uclaRegion, ndn::Name("/ucla"));

  // Installing applications

  // Consumer
  ndn::AppHelper requesterHelper("RequesterApp");
  requesterHelper.SetAttribute("Name", StringValue("/ndnSIM/someData"));
  requesterHelper.SetAttribute("Delegation", StringValue("/ucla1"));
  requesterHelper.Install(consumer).Start(Seconds(1));

  requesterHelper.SetAttribute("Name", StringValue("/ndnSIM/anotherData"));
  requesterHelper.Install(consumer).Start(Seconds(2));

  requesterHelper.SetAttribute("Name", StringValue("/ndnSIM/yetAnotherData"));
  requesterHelper.SetAttribute("Delegation", StringValue("/non-existing"));
  requesterHelper.Install(consumer).Start(Seconds(3));

  // Producer
  ndn::AppHelper producerHelper("ns3::ndn::Producer");
  producerHelper.SetPrefix("/ndnSIM");
  producerHelper.SetAttribute("PayloadSize", StringValue("1024"));
  producerHelper.Install(uclaRegion.Get(0));

  Simulator::Stop(Seconds(20.0));

  Simulator::Run();
  Simulator::Destroy();

  return 0;
}
开发者ID:cawka,项目名称:ndnSIM,代码行数:65,代码来源:ndn-simple-for-nrt-helper.cpp

示例12: main

int
main(int argc, char* argv[])
{
  // setting default parameters for PointToPoint links and channels
  Config::SetDefault("ns3::PointToPointNetDevice::DataRate", StringValue("10Mbps"));
  Config::SetDefault("ns3::PointToPointChannel::Delay", StringValue("10ms"));
  Config::SetDefault("ns3::DropTailQueue::MaxPackets", StringValue("20"));

  // Read optional command-line parameters (e.g., enable visualizer with ./waf --run=<> --visualize
  CommandLine cmd;
  cmd.Parse(argc, argv);

  // Creating nodes
  NodeContainer nodes;
  nodes.Create(3); // 3 nodes, connected: 0 <---> 1 <---> 2

  // Connecting nodes using two links
  PointToPointHelper p2p;
  p2p.Install(nodes.Get(0), nodes.Get(1));
  p2p.Install(nodes.Get(1), nodes.Get(2));

  // Install NDN stack on all nodes
  ndn::StackHelper ndnHelper;
  ndnHelper.SetDefaultRoutes(true);
  ndnHelper.setCsSize(0);
  ndnHelper.SetOldContentStore("ns3::ndn::cs::Lru", "MaxSize", "100");
  ndnHelper.InstallAll();

  // Choosing forwarding strategy
  ndn::StrategyChoiceHelper::InstallAll("/myprefix", "/localhost/nfd/strategy/best-route");

  ns3::ndn::AppHelper consumerHelper("ns3::ndn::FileConsumerCbr::MultimediaConsumer");
  consumerHelper.SetAttribute("AllowUpscale", BooleanValue(true));
  consumerHelper.SetAttribute("AllowDownscale", BooleanValue(false));
  consumerHelper.SetAttribute("ScreenWidth", UintegerValue(1920));
  consumerHelper.SetAttribute("ScreenHeight", UintegerValue(1080));
  consumerHelper.SetAttribute("StartRepresentationId", StringValue("auto"));
  consumerHelper.SetAttribute("MaxBufferedSeconds", UintegerValue(30));
  consumerHelper.SetAttribute("StartUpDelay", StringValue("0.1"));

  consumerHelper.SetAttribute("AdaptationLogic", StringValue("dash::player::RateAndBufferBasedAdaptationLogic"));
  consumerHelper.SetAttribute("MpdFileToRequest", StringValue(std::string("/myprefix/FakeVid1/vid1.mpd" )));

  //consumerHelper.SetPrefix (std::string("/Server_" + boost::lexical_cast<std::string>(i%server.size ()) + "/layer0"));
  ApplicationContainer app1 = consumerHelper.Install (nodes.Get(2));

  ndn::AppHelper fakeDASHProducerHelper("ns3::ndn::FakeMultimediaServer");

  // This fake multimedia producer will reply to all requests starting with /myprefix/FakeVid1
  fakeDASHProducerHelper.SetPrefix("/myprefix/FakeVid1");
  fakeDASHProducerHelper.SetAttribute("MetaDataFile", StringValue("representations/netflix_vid1.csv"));
  // We just give the MPD file a name that makes it unique
  fakeDASHProducerHelper.SetAttribute("MPDFileName", StringValue("vid1.mpd"));

  fakeDASHProducerHelper.Install(nodes.Get(0));

  // We can install more then one fake multimedia producer on one node:

  // This fake multimedia producer will reply to all requests starting with /myprefix/FakeVid2
  fakeDASHProducerHelper.SetPrefix("/myprefix/FakeVid2");
  fakeDASHProducerHelper.SetAttribute("MetaDataFile", StringValue("representations/netflix_vid2.csv"));
  // We just give the MPD file a name that makes it unique
  fakeDASHProducerHelper.SetAttribute("MPDFileName", StringValue("vid2.mpd"));


  // This fake multimedia producer will reply to all requests starting with /myprefix/FakeVid3
  fakeDASHProducerHelper.SetPrefix("/myprefix/FakeVid3");
  fakeDASHProducerHelper.SetAttribute("MetaDataFile", StringValue("representations/netflix_vid3.csv"));
  // We just give the MPD file a name that makes it unique
  fakeDASHProducerHelper.SetAttribute("MPDFileName", StringValue("vid3.mpd"));

  ndn::GlobalRoutingHelper ndnGlobalRoutingHelper;
  ndnGlobalRoutingHelper.InstallAll();

  ndnGlobalRoutingHelper.AddOrigins("/myprefix", nodes.Get(0));
  ndn::GlobalRoutingHelper::CalculateRoutes();

  Simulator::Stop(Seconds(60.0));

  Simulator::Run();
  Simulator::Destroy();

  NS_LOG_UNCOND("Simulation Finished.");

  return 0;
}
开发者ID:ChristianKreuzberger,项目名称:AMuSt-ndnSIM,代码行数:86,代码来源:ndn-multimedia-avc-fake-multimedia-server.cpp

示例13: main

int main (int argc, char *argv[])
{
  std::string phyMode ("DsssRate1Mbps");
  double rss = -80;  // -dBm
  uint32_t packetSize = 1000; // bytes
  uint32_t numPackets = 1;
  double interval = 1.0; // seconds
  bool verbose = false;

  CommandLine cmd;

  cmd.AddValue ("phyMode", "Wifi Phy mode", phyMode);
  cmd.AddValue ("rss", "received signal strength", rss);
  cmd.AddValue ("packetSize", "size of application packet sent", packetSize);
  cmd.AddValue ("numPackets", "number of packets generated", numPackets);
  cmd.AddValue ("interval", "interval (seconds) between packets", interval);
  cmd.AddValue ("verbose", "turn on all WifiNetDevice log components", verbose);

  cmd.Parse (argc, argv);
  // Convert to time object
  Time interPacketInterval = Seconds (interval);

  // disable fragmentation for frames below 2200 bytes
  Config::SetDefault ("ns3::WifiRemoteStationManager::FragmentationThreshold", StringValue ("2200"));
  // turn off RTS/CTS for frames below 2200 bytes
  Config::SetDefault ("ns3::WifiRemoteStationManager::RtsCtsThreshold", StringValue ("2200"));
  // Fix non-unicast data rate to be the same as that of unicast
  Config::SetDefault ("ns3::WifiRemoteStationManager::NonUnicastMode", 
                      StringValue (phyMode));

  NodeContainer c;
  c.Create (2);

  // The below set of helpers will help us to put together the wifi NICs we want
  WifiHelper wifi;
  if (verbose)
    {
      wifi.EnableLogComponents ();  // Turn on all Wifi logging
    }
  wifi.SetStandard (WIFI_PHY_STANDARD_80211b);

  YansWifiPhyHelper wifiPhy =  YansWifiPhyHelper::Default ();
  // This is one parameter that matters when using FixedRssLossModel
  // set it to zero; otherwise, gain will be added
  wifiPhy.Set ("RxGain", DoubleValue (0) ); 
  // ns-3 supports RadioTap and Prism tracing extensions for 802.11b
  wifiPhy.SetPcapDataLinkType (YansWifiPhyHelper::DLT_IEEE802_11_RADIO); 

  YansWifiChannelHelper wifiChannel;
  wifiChannel.SetPropagationDelay ("ns3::ConstantSpeedPropagationDelayModel");
  // The below FixedRssLossModel will cause the rss to be fixed regardless
  // of the distance between the two stations, and the transmit power
  wifiChannel.AddPropagationLoss ("ns3::FixedRssLossModel","Rss",DoubleValue (rss));
  wifiPhy.SetChannel (wifiChannel.Create ());

  // Add a non-QoS upper mac, and disable rate control
  NqosWifiMacHelper wifiMac = NqosWifiMacHelper::Default ();
  wifi.SetRemoteStationManager ("ns3::ConstantRateWifiManager",
                                "DataMode",StringValue (phyMode),
                                "ControlMode",StringValue (phyMode));

  // Setup the rest of the upper mac
  Ssid ssid = Ssid ("wifi-default");
  // setup sta.
  wifiMac.SetType ("ns3::StaWifiMac",
                   "Ssid", SsidValue (ssid),
                   "ActiveProbing", BooleanValue (false));
  NetDeviceContainer staDevice = wifi.Install (wifiPhy, wifiMac, c.Get (0));
  NetDeviceContainer devices = staDevice;
  // setup ap.
  wifiMac.SetType ("ns3::ApWifiMac",
                   "Ssid", SsidValue (ssid));
  NetDeviceContainer apDevice = wifi.Install (wifiPhy, wifiMac, c.Get (1));
  devices.Add (apDevice);

  // Note that with FixedRssLossModel, the positions below are not 
  // used for received signal strength. 
  MobilityHelper mobility;
  Ptr<ListPositionAllocator> positionAlloc = CreateObject<ListPositionAllocator> ();
  positionAlloc->Add (Vector (0.0, 0.0, 0.0));
  positionAlloc->Add (Vector (5.0, 0.0, 0.0));
  mobility.SetPositionAllocator (positionAlloc);
  mobility.SetMobilityModel ("ns3::ConstantPositionMobilityModel");
  mobility.Install (c);

  InternetStackHelper internet;
  internet.Install (c);

  Ipv4AddressHelper ipv4;
  NS_LOG_INFO ("Assign IP Addresses.");
  ipv4.SetBase ("10.1.1.0", "255.255.255.0");
  Ipv4InterfaceContainer i = ipv4.Assign (devices);

  TypeId tid = TypeId::LookupByName ("ns3::UdpSocketFactory");
  Ptr<Socket> recvSink = Socket::CreateSocket (c.Get (0), tid);
  InetSocketAddress local = InetSocketAddress (Ipv4Address::GetAny (), 80);
  recvSink->Bind (local);
  recvSink->SetRecvCallback (MakeCallback (&ReceivePacket));

  Ptr<Socket> source = Socket::CreateSocket (c.Get (1), tid);
//.........这里部分代码省略.........
开发者ID:shuiziliuBUPT,项目名称:HelloWorld,代码行数:101,代码来源:wifi-simple-infra.cpp

示例14: main

int 
main (int argc, char *argv[])
{

  //
  // Set up some default values for the simulation.
  //
  Config::SetDefault ("ns3::OnOffApplication::PacketSize", UintegerValue (137));

  // ??? try and stick 15kb/s into the data rate
  Config::SetDefault ("ns3::OnOffApplication::DataRate", StringValue ("14kb/s"));

  //
  // Default number of nodes in the star.  Overridable by command line argument.
  //
  uint32_t nSpokes = 8;

  CommandLine cmd;
  cmd.AddValue ("nSpokes", "Number of nodes to place in the star", nSpokes);
  cmd.Parse (argc, argv);

  NS_LOG_INFO ("Build star topology.");
  PointToPointHelper pointToPoint;
  pointToPoint.SetDeviceAttribute ("DataRate", StringValue ("5Mbps"));
  pointToPoint.SetChannelAttribute ("Delay", StringValue ("2ms"));
  PointToPointStarHelper star (nSpokes, pointToPoint);

  NS_LOG_INFO ("Install internet stack on all nodes.");
  InternetStackHelper internet;
  star.InstallStack (internet);

  NS_LOG_INFO ("Assign IP Addresses.");
  star.AssignIpv4Addresses (Ipv4AddressHelper ("10.1.1.0", "255.255.255.0"));

  NS_LOG_INFO ("Create applications.");
  //
  // Create a packet sink on the star "hub" to receive packets.
  // 
  uint16_t port = 50000;
  Address hubLocalAddress (InetSocketAddress (Ipv4Address::GetAny (), port));
  PacketSinkHelper packetSinkHelper ("ns3::TcpSocketFactory", hubLocalAddress);
  ApplicationContainer hubApp = packetSinkHelper.Install (star.GetHub ());
  hubApp.Start (Seconds (1.0));
  hubApp.Stop (Seconds (10.0));

  //
  // Create OnOff applications to send TCP to the hub, one on each spoke node.
  //
  OnOffHelper onOffHelper ("ns3::TcpSocketFactory", Address ());
  onOffHelper.SetAttribute ("OnTime", StringValue ("ns3::ConstantRandomVariable[Constant=1]"));
  onOffHelper.SetAttribute ("OffTime", StringValue ("ns3::ConstantRandomVariable[Constant=0]"));

  ApplicationContainer spokeApps;

  for (uint32_t i = 0; i < star.SpokeCount (); ++i)
    {
      AddressValue remoteAddress (InetSocketAddress (star.GetHubIpv4Address (i), port));
      onOffHelper.SetAttribute ("Remote", remoteAddress);
      spokeApps.Add (onOffHelper.Install (star.GetSpokeNode (i)));
    }
  spokeApps.Start (Seconds (1.0));
  spokeApps.Stop (Seconds (10.0));

  NS_LOG_INFO ("Enable static global routing.");
  //
  // Turn on global static routing so we can actually be routed across the star.
  //
  Ipv4GlobalRoutingHelper::PopulateRoutingTables ();

  NS_LOG_INFO ("Enable pcap tracing.");
  //
  // Do pcap tracing on all point-to-point devices on all nodes.
  //
  pointToPoint.EnablePcapAll ("star");

  NS_LOG_INFO ("Run Simulation.");
  Simulator::Run ();
  Simulator::Destroy ();
  NS_LOG_INFO ("Done.");

  return 0;
}
开发者ID:shuiziliuBUPT,项目名称:HelloWorld,代码行数:82,代码来源:star.cpp

示例15: main

int main(int argc, char *argv[])
{
   int retval = 0;

   QCoreApplication::setOrganizationName("SLART");
   QCoreApplication::setOrganizationDomain("svolli.org");
   QCoreApplication::setApplicationName("TestAppXxtea");
   QCoreApplication app( argc, argv );

   QTextStream qStdOut( stdout );
   QTextStream qStdErr( stderr );
   QSettings   settings;

   QString progName( QFileInfo( QCoreApplication::arguments().at(0) ).fileName() );
   bool help = false;
   bool encrypt = false;
   bool decrypt = false;
   QString key;
   QStringList files;
   CommandLine cl;
   cl.option( "-help",    "show help",     &help,    true );
   cl.option( "-encrypt", "encrypt files", &encrypt, true );
   cl.option( "-decrypt", "decrypt files", &decrypt, true );
   cl.option( "-key",     "set key",       &key );
   cl.parse( &files );

   if( cl.check() )
   {
      qStdErr << "fail! try '-help'\n";
      return 0;
   }

   if( help )
   {
      qStdErr <<
      "\nthis program encrypts and decrypts files using the xxtea algorithm\n"
      "see http://en.wikipedia.org/wiki/XXTEA for details\n"
      "\noptions:\n" << cl.help() << "\n\nexamples:\n"
      << progName << " -key secret                # writes the key secret in the registry\n"
      << progName << " -encrypt file1 (file2 ...) # encryptes the files\n"
      << progName << " -decrypt file1 (file2 ...) # decryptes the files\n"
      << progName << " -key secret -encrypt file  # set key and encrypt in one pass\n\n"
      ;
      return 0;
   }

   if( key.isNull() )
   {
      key = settings.value( "Key" ).toByteArray();
   }
   else
   {
      if( key.isEmpty() )
      {
         settings.remove( "Key" );
         qStdOut << "deleting key\n";
      }
      else
      {
         QCryptographicHash hash( QCryptographicHash::Md5 );
         hash.addData( key.toUtf8() );
         settings.setValue( "Key", hash.result() );
         qStdOut << "setting key to: " << settings.value( "Key" ).toByteArray().toHex() << "\n";
      }

      if( !encrypt && !decrypt )
      {
         return 0;
      }
   }

   if( encrypt == decrypt )
   {
      qStdErr << "you need to specify exactly one of -encrypt or -decrypt\n";
      return 1;
   }

   QFile       file;
   QByteArray  fileData;
   Xxtea       xxtea;
   bool        success = false;

   QByteArray hashedKey( settings.value( "Key" ).toByteArray() );
   if( hashedKey.size() != 16 )
   {
      qStdOut << "key is invalid\n";
      return 1;
   }
   else
   {
      qStdOut << "key is: " << hashedKey.toHex() << "\n";
   }
   xxtea.setKey( hashedKey );
   xxtea.setData( &fileData );
   foreach( const QString &fileName, files )
   {
      qStdOut << fileName << ": ";
      file.setFileName( fileName );
      file.open( QIODevice::ReadWrite );
      qStdOut << "reading, ";
//.........这里部分代码省略.........
开发者ID:SvOlli,项目名称:SLART,代码行数:101,代码来源:Application.cpp


注:本文中的CommandLine类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。