示例#1
0
void updateQRZ(Matrix& X, UpperTriangularMatrix& U)
{
   REPORT
   Tracer et("updateQRZ");
   int n = X.Nrows(); int s = X.Ncols();
   if (s != U.Ncols())
      Throw(ProgramException("Incompatible dimensions",X,U));
   if (n == 0 || s == 0) return; 
   Real* xi0 = X.Store(); Real* u0 = U.Store(); Real* u;
   RowVector V(s); Real* v0 = V.Store(); Real* v; V = 0.0;
   int j, k; int J = s; int i = s;
   while (i--)
   {
      Real* xj0 = xi0; Real* xi = xi0; k = n;
      if (k) for (;;)
      {
         v = v0; Real Xi = *xi; Real* xj = xj0;
         j = J; while(j--) *v++ += Xi * *xj++;
         if (!(--k)) break;
         xi += s; xj0 += s;
      }

      Real r = *u0;
      Real sum = sqrt(*v0 + square(r));
      
      if (sum == 0.0)
      {
         REPORT
         u = u0; v = v0;
         j = J; while(j--) { *u++ = 0.0; *v++ = 0.0; }
         xj0 = xi0++; k = n;
         if (k) for (;;)
         {
            *xj0 = 0.0;
            if (!(--k)) break;
	          xj0 += s;
         }
         u0 += J--;
      }
      else
      {
         Real frs = fabs(r) + sum;
         Real a0 = sqrt(frs / sum); Real alpha = a0 / frs;
         if (r <= 0) { REPORT alpha = -alpha; *u0 = sum; }
         else { REPORT *u0 = -sum; }
      
         j = J - 1; v = v0 + 1; u = u0 + 1;     
         while (j--)
            { *v = a0 * *u + alpha * *v; *u -= a0 * *v; ++v; ++u; }

         xj0 = xi0; xi = xi0++; k = n;
         if (k) for (;;)
         {
            v = v0 + 1; Real Xi = *xi; Real* xj = xj0;
            Xi *= alpha; *xj++ = Xi;
            j = J - 1; while(j--) *xj++ -= *v++ * Xi;
            if (!(--k)) break;
	          xi += s; xj0 += s;
         }
         
         j = J; v = v0;
         while (j--) *v++ = 0.0;
         
         u0 += J--;
      }
   }
}
示例#2
0
文件: MET.cpp 项目: dhidas/UserCode
bool MET::isGood() const {
    return et() > 20;
}
int main(int argc, char *agrv[]) {
  google::ParseCommandLineFlags(&argc, &agrv, true);

  hal::MatrixIOBus bus;
  if (!bus.Init()) return false;

  if (!bus.IsDirectBus()) {
    std::cerr << "Kernel Modules has been loaded. Use ALSA implementation "
              << std::endl;
    return false;
  }

  int sampling_rate = FLAGS_sampling_frequency;
  int seconds_to_record = FLAGS_duration;

  // Microhone Array Configuration
  hal::MicrophoneArray mics;
  mics.Setup(&bus);
  mics.SetSamplingRate(sampling_rate);
  if (FLAGS_gain > 0) mics.SetGain(FLAGS_gain);

  mics.ShowConfiguration();
  std::cout << "Duration : " << seconds_to_record << "s" << std::endl;

  // Microphone Core Init
  hal::MicrophoneCore mic_core(mics);
  mic_core.Setup(&bus);
  mic_core.SelectFIRCoeff(&FIR_bandpass[0]);

  int16_t buffer[mics.Channels() + 1]
                [mics.SamplingRate() + mics.NumberOfSamples()];

  mics.CalculateDelays(0, 0, 1000, 320 * 1000);

  std::ofstream os[mics.Channels() + 1];

  for (uint16_t c = 0; c < mics.Channels() + 1; c++) {
    std::string filename = "mic_" + std::to_string(mics.SamplingRate()) +
                           "_s16le_channel_" + std::to_string(c) + ".raw";
    os[c].open(filename, std::ofstream::binary);
  }

  std::thread et(
      [seconds_to_record](hal::MatrixIOBus *bus) {

        hal::Everloop everloop;
        everloop.Setup(bus);

        hal::EverloopImage image(bus->MatrixLeds());

        for (auto &led : image.leds) led.red = 10;
        everloop.Write(&image);

        int sleep = int(1000.0 * seconds_to_record / image.leds.size());

        for (auto &led : image.leds) {
          led.red = 0;
          led.green = 10;

          everloop.Write(&image);

          std::this_thread::sleep_for(std::chrono::milliseconds(sleep));
        }
      },
      &bus);

  uint32_t samples = 0;
  for (int s = 0; s < seconds_to_record; s++) {
    for (;;) {
      mics.Read(); /* Reading 8-mics buffer from de FPGA */

      /* buffering */
      for (uint32_t s = 0; s < mics.NumberOfSamples(); s++) {
        for (uint16_t c = 0; c < mics.Channels(); c++) { /* mics.Channels()=8 */
          buffer[c][samples] = mics.At(s, c);
        }
        buffer[mics.Channels()][samples] = mics.Beam(s);
        samples++;
      }

      /* write to file */
      if (samples >= mics.SamplingRate()) {
        for (uint16_t c = 0; c < mics.Channels() + 1; c++) {
          os[c].write((const char *)buffer[c], samples * sizeof(int16_t));
        }
        samples = 0;
        break;
      }
    }
  }

  et.join();
  return 0;
}
void NetworkConfig::_fromDictionary(const Dictionary &d)
{
	static const std::string zero("0");
	static const std::string one("1");

	// NOTE: d.get(name) throws if not found, d.get(name,default) returns default

	memset(_etWhitelist,0,sizeof(_etWhitelist));
	std::vector<std::string> ets(Utils::split(d.get(ZT_NETWORKCONFIG_DICT_KEY_ALLOWED_ETHERNET_TYPES).c_str(),",","",""));
	for(std::vector<std::string>::const_iterator et(ets.begin());et!=ets.end();++et) {
		unsigned int tmp = Utils::hexStrToUInt(et->c_str()) & 0xffff;
		_etWhitelist[tmp >> 3] |= (1 << (tmp & 7));
	}

	_nwid = Utils::hexStrToU64(d.get(ZT_NETWORKCONFIG_DICT_KEY_NETWORK_ID).c_str());
	if (!_nwid)
		throw std::invalid_argument("configuration contains zero network ID");
	_timestamp = Utils::hexStrToU64(d.get(ZT_NETWORKCONFIG_DICT_KEY_TIMESTAMP).c_str());
	_issuedTo = Address(d.get(ZT_NETWORKCONFIG_DICT_KEY_ISSUED_TO));
	_multicastPrefixBits = Utils::hexStrToUInt(d.get(ZT_NETWORKCONFIG_DICT_KEY_MULTICAST_PREFIX_BITS,zero).c_str());
	_multicastDepth = Utils::hexStrToUInt(d.get(ZT_NETWORKCONFIG_DICT_KEY_MULTICAST_DEPTH,zero).c_str());
	_allowPassiveBridging = (Utils::hexStrToUInt(d.get(ZT_NETWORKCONFIG_DICT_KEY_ALLOW_PASSIVE_BRIDGING,zero).c_str()) != 0);
	_private = (Utils::hexStrToUInt(d.get(ZT_NETWORKCONFIG_DICT_KEY_PRIVATE,one).c_str()) != 0);
	_enableBroadcast = (Utils::hexStrToUInt(d.get(ZT_NETWORKCONFIG_DICT_KEY_ENABLE_BROADCAST,one).c_str()) != 0);
	_name = d.get(ZT_NETWORKCONFIG_DICT_KEY_NAME);
	_description = d.get(ZT_NETWORKCONFIG_DICT_KEY_DESC,std::string());

	if (!_multicastPrefixBits)
		_multicastPrefixBits = ZT_DEFAULT_MULTICAST_PREFIX_BITS;
	if (!_multicastDepth)
		_multicastDepth = ZT_DEFAULT_MULTICAST_DEPTH;

	std::string ipAddrs(d.get(ZT_NETWORKCONFIG_DICT_KEY_IPV4_STATIC,std::string()));
	std::string v6s(d.get(ZT_NETWORKCONFIG_DICT_KEY_IPV6_STATIC,std::string()));
	if (v6s.length()) {
		if (ipAddrs.length())
			ipAddrs.push_back(',');
		ipAddrs.append(v6s);
	}
	std::vector<std::string> ipAddrs2(Utils::split(ipAddrs.c_str(),",","",""));
	for(std::vector<std::string>::const_iterator ipstr(ipAddrs2.begin());ipstr!=ipAddrs2.end();++ipstr) {
		InetAddress addr(*ipstr);
		switch(addr.type()) {
			case InetAddress::TYPE_IPV4:
				if ((!addr.netmaskBits())||(addr.netmaskBits() > 32))
					throw std::invalid_argument("static IP address fields contain one or more invalid IP/netmask entries");
				break;
			case InetAddress::TYPE_IPV6:
				if ((!addr.netmaskBits())||(addr.netmaskBits() > 128))
					throw std::invalid_argument("static IP address fields contain one or more invalid IP/netmask entries");
				break;
			default:
				throw std::invalid_argument("static IP address fields contain one or more invalid IP/netmask entries");
		}
		_staticIps.insert(addr);
	}

	std::vector<std::string> ab(Utils::split(d.get(ZT_NETWORKCONFIG_DICT_KEY_ACTIVE_BRIDGES,"").c_str(),",","",""));
	for(std::vector<std::string>::const_iterator a(ab.begin());a!=ab.end();++a) {
		if (a->length() == ZT_ADDRESS_LENGTH_HEX) {
			Address tmp(*a);
			if (!tmp.isReserved())
				_activeBridges.insert(tmp);
		}
	}

	Dictionary mr(d.get(ZT_NETWORKCONFIG_DICT_KEY_MULTICAST_RATES,std::string()));
	for(Dictionary::const_iterator i(mr.begin());i!=mr.end();++i) {
		std::vector<std::string> params(Utils::split(i->second.c_str(),",","",""));
		if (params.size() >= 3)
			_multicastRates[MulticastGroup(i->first)] = MulticastRate(Utils::hexStrToUInt(params[0].c_str()),Utils::hexStrToUInt(params[1].c_str()),Utils::hexStrToUInt(params[2].c_str()));
	}

	_com.fromString(d.get(ZT_NETWORKCONFIG_DICT_KEY_CERTIFICATE_OF_MEMBERSHIP,std::string()));
}
示例#5
0
Real OneDimSolve::Solve(Real Y, Real X, Real Dev, int Lim)
{
   enum Loop { start, captured1, captured2, binary, finish };
   Tracer et("OneDimSolve::Solve");
   lim=Lim; Captured = false;
   if (Dev==0.0) Throw(SolutionException("Dev is zero"));
   L=0; C=1; U=2; vpol=1; hpol=1; y[C]=0.0; y[U]=0.0;
   if (Dev<0.0) { hpol=-1; Dev = -Dev; }
   YY=Y;                                // target value
   x[L] = X;                            // initial trial value
   if (!function.IsValid(X))
      Throw(SolutionException("Starting value is invalid"));
   Loop TheLoop = start;
   for (;;)
   {
      switch (TheLoop)
      {
      case start:
	 LookAt(L); if (Finish) { TheLoop = finish; break; }
	 if (y[L]>0.0) VFlip();               // so Y[L] < 0

         x[U] = X + Dev * hpol;
         if (!function.maxXinf && x[U] > function.maxX)
            x[U] = (function.maxX + X) / 2.0;
         if (!function.minXinf && x[U] < function.minX)
            x[U] = (function.minX + X) / 2.0;

	 LookAt(U); if (Finish) { TheLoop = finish; break; }
	 if (y[U] > 0.0) { TheLoop = captured1; Captured = true; break; }
	 if (y[U] == y[L])
	    Throw(SolutionException("Function is flat"));
	 if (y[U] < y[L]) HFlip();             // Change direction
	 State(L,U,C);
	 for (i=0; i<20; i++)
	 {
	    // cout << "Searching for crossing point\n";
	    // Have L C then crossing point, Y[L]<Y[C]<0
            x[U] = x[C] + Dev * hpol;
            if (!function.maxXinf && x[U] > function.maxX)
               x[U] = (function.maxX + x[C]) / 2.0;
            if (!function.minXinf && x[U] < function.minX)
               x[U] = (function.minX + x[C]) / 2.0;

	    LookAt(U); if (Finish) { TheLoop = finish; break; }
	    if (y[U] > 0) { TheLoop = captured2; Captured = true; break; }
	    if (y[U] < y[C])
	       Throw(SolutionException("Function is not monotone"));
	    Dev *= 2.0;
	    State(C,U,L);
	 }
	 if (TheLoop != start ) break;
	 Throw(SolutionException("Can't locate a crossing point"));

      case captured1:
	 // cout << "Captured - 1\n";
	 // We have 2 points L and U with crossing between them
	 Linear(L,C,U);                   // linear interpolation
					  // - result to C
	 LookAt(C); if (Finish) { TheLoop = finish; break; }
	 if (y[C] > 0.0) Flip();            // Want y[C] < 0
	 if (y[C] < 0.5*y[L]) { State(C,L,U); TheLoop = binary; break; }

      case captured2:
	 // cout << "Captured - 2\n";
	 // We have L,C before crossing, U after crossing
	 Quadratic(L,C,U);                // quad interpolation
					  // - result to L
	 State(C,L,U);
	 if ((x[C] - x[L])*hpol <= 0.0 || (x[C] - x[U])*hpol >= 0.0)
	    { TheLoop = captured1; break; }
	 LookAt(C); if (Finish) { TheLoop = finish; break; }
	 // cout << "Through first stage\n";
	 if (y[C] > 0.0) Flip();
	 if (y[C] > 0.5*y[L]) { TheLoop = captured2; break; }
	 else { State(C,L,U); TheLoop = captured1; break; }

      case binary:
	 // We have L, U around crossing - do binary search
	 // cout << "Binary\n";
	 for (i=3; i; i--)
	 {
	    x[C] = 0.5*(x[L]+x[U]);
	    LookAt(C); if (Finish) { TheLoop = finish; break; }
	    if (y[C]>0.0) State(L,U,C); else State(C,L,U);
	 }
	 if (TheLoop != binary) break;
	 TheLoop = captured1; break;

      case finish:
	 return x[Last];

      }
   }
}
示例#6
0
int main (int argc, char * const argv[]) {
	clock_t clock_start = clock();
	
	int option_char;
	char* jdb;
	char* block;
	bool blocked = false;
	bool snp = false;
	int seed = -1;
	int method = -1;
	bool log = false;
	int nbTree = 1;
	int k = 1;
	int inc = 0;
	int nmin = 1;
	int intc = 1;
	bool startend = true;
	bool startendlsts = true;
	std::string acfile = "";
	std::string lsfile = "";
	std::string tsfile = "";
	std::string gcfile = "";
	while ((option_char = getopt(argc, argv, "x?m:j:b:r:sl:t:k:i:a:g:v:fn:c:e")) != -1) {
		switch (option_char) {
			case 'e':	startend = false; break;
			case 'x':	startendlsts = false; break;
			case 'b':	block	= optarg; blocked = true; break;
			case 'a':	acfile	= optarg; break;
			case 'v':	tsfile	= optarg; break;
			case 'l':	lsfile	= optarg; break;
			case 'g':	gcfile	= optarg; break;
			case 'j':	jdb		= optarg; break;
			case 's':	snp		= true; break;
			case 'r':	seed	= atoi(optarg); break;
			case 'm':	method	= atoi(optarg); break;
			case 't':	nbTree	= atoi(optarg); break;
			case 'k':	k		= atoi(optarg); break;
			case 'i':	inc		= atoi(optarg); break;
			case 'n':	nmin	= atoi(optarg); break;
			case 'c':	intc	= atoi(optarg); break;
			case 'f':	log		= true; break;
			case '?':	printHelp(); return -1 ; break;
			default:	printHelp(); return -1 ; break;
		}
	}
	
	//return 0;
	
	if (seed>-1)
		srand(seed);
	else
		srand((unsigned int) time(NULL));
	
	// OUTPUT FILES 
	char prefix[256];
	sprintf(prefix, "%s_k%d_m%d_t%d_ic%d_nmin%d",jdb,k,method,nbTree,intc,nmin);
	Logs l(prefix,inc);
		
	// DATABASE INPUT
	JavaDB db(jdb);
	if (blocked) {
		if (startend)
			db.readBlockStartEnd(block);
		else
			db.readBlock(block);
		l.main("BLOCK FILE:"); l.main(block); l.main("\n");
	}
	if (snp) {
		db.setType(SNP);
		l.main("SNP DB MODE : ON\n");
	}
	if (log)
		db.print(l.main());
	
	// LEARNING, TEST SETS AND CANDIDATE ATTRIBUTES SETTINGS
	std::vector<SETREP> ls;
	if (lsfile == "") 
		ls = db.selectAll();
	else {
		if (startendlsts)
			ls = Sampler::readStartEndSet(lsfile);
		else 
			ls = Sampler::readSet(lsfile);
		l.main("LEARNING SET FILE:"); l.main(lsfile.c_str()); l.main("\n");
	}
	
	std::vector<SETREP> ts;
	if (tsfile == "")
		ts = db.selectAll();
	else {
		if (startendlsts)
			ts = Sampler::readStartEndSet(tsfile);
		else
			ts = Sampler::readSet(tsfile);
		l.main("TEST SET FILE:"); l.main(tsfile.c_str()); l.main("\n");
	}
	
	std::vector<unsigned int> attcand;
	if (acfile == "")
		attcand = db.selectAllAtt();
	else {
		attcand = Sampler::readStartEndSet(acfile);
		l.main("CANDIDATE ATT. FILE:"); l.main(acfile.c_str()); l.main("\n");
	}
	
	std::vector<unsigned int> groupcand;
	if (blocked) {
		if (gcfile == "")
			groupcand = db.selectAllGroup();
		else {
			groupcand = Sampler::readStartEndSet(gcfile);
			l.main("CANDIDATE ATT. FILE:"); l.main(gcfile.c_str()); l.main("\n");
		}
	}
	
	Result result(&db);

	std::vector<float> vim(db.getNbAtt(),0.0);
	
	switch (method) {
		case 0: {
			fprintf(stderr,"CLASSIC TREE\n");
			ClassicTree ct(&db,nmin);
			ct.setLS(&ls);
			ct.setTS(&ts);
			ct.setAttCand(&attcand);
			ct.print(l.main());
			fprintf(l.main(),"Learning Time : %f sec\n",	ct.learn()/CLOCKS_PER_SEC);
			result = ct.test();
			fprintf(l.main(),"Error rate : %f %%\n", result.getErrorRate());
			fprintf(stderr,"Error rate : %f %%\n", result.getErrorRate());
			result.printProb(l.roc());
			//ct.computeVimp();
			//ct.printVimp(l.varimp());
			
			ct.computeVimp(vim,ls);
			ct.printVimp(vim,l.varimp());
			
			fprintf(l.dot(),"digraph G {\n");
			ct.dotit(l.dot());
			fprintf(l.dot(),"}\n");
			
			l.flush();
			break; 
		} case 1: {
			fprintf(stderr,"RANDOM FOREST\n");
			RandomForest rf(&db,nbTree,k,nmin);
			rf.setLS(&ls);
			rf.setTS(&ts);
			rf.setAttCand(&attcand);
			rf.print(l.main());
			rf.setTreeInfo(l.tree());
			fprintf(l.main(),"Learning Time : %f sec\n",	rf.learn()/CLOCKS_PER_SEC);
			result = rf.test();
			fprintf(l.main(),"Error rate : %f %%\n", result.getErrorRate());	
			fprintf(stderr,"Error rate : %f %%\n", result.getErrorRate());
			result.printProb(l.roc());
			
			rf.computeVimp(vim,ls);
			rf.printVimp(vim,l.varimp());
			rf.dotit(l.dot(),10);
			
			l.flush();
			break; 
		} case 2: {
			fprintf(stderr,"EXTRATREES\n");
			ExtraTrees et(&db,nbTree,k,nmin);
			et.setLS(&ls);
			et.setTS(&ts);
			et.setAttCand(&attcand);
			et.print(l.main());
			et.setTreeInfo(l.tree());
			fprintf(l.main(),"Learning Time : %f sec\n",	et.learn()/CLOCKS_PER_SEC);
			result = et.test();
			fprintf(l.main(),"Error rate : %f %%\n", result.getErrorRate());	
			fprintf(stderr,"Error rate : %f %%\n", result.getErrorRate());
			result.printProb(l.roc());
			
			et.computeVimp(vim,ls);
			et.printVimp(vim,l.varimp());
			et.dotit(l.dot(),10);
					
			l.flush();
			break;
		} case 3: {
			fprintf(stderr,"RANDOM TT FOREST\n");
			RandomTTForest rttf(&db,nbTree,k,nmin);
			rttf.setKint(0);
			rttf.setLS(&ls);
			rttf.setTS(&ts);
			rttf.setAttCand(&attcand);
			rttf.setGroupCand(groupcand);
			rttf.setInternalComp(intc);
			rttf.print(l.main());
			rttf.setTreeInfo(l.tree());
			fprintf(l.main(),"Learning Time : %f sec\n",	rttf.learn()/CLOCKS_PER_SEC);
			result = rttf.test();
			fprintf(l.main(),"Error rate : %f %%\n", result.getErrorRate());
			fprintf(stderr,"Error rate : %f %%\n", result.getErrorRate());
			result.printProb(l.roc());
			
			
			std::vector<float> gim(db.getNbGroup(),0.0);
			rttf.computeGroupVimp(gim,ls);
			rttf.printGroupVimp(gim,l.groupimp());
			
			rttf.computeVimp(vim,ls);
			rttf.printVimp(vim, l.varimp());
			rttf.dotit(l.dot(),10);
			
			
			l.flush();
			break;
		} case 4: {
			fprintf(stderr,"EXTRATTREES\n");
			ExtraTTrees ett(&db,nbTree,k,nmin);
			ett.setKint(0);
			ett.setLS(&ls);
			ett.setTS(&ts);
			ett.setAttCand(&attcand);
			ett.setGroupCand(groupcand);
			ett.setInternalComp(intc);
			ett.print(l.main());
			fprintf(l.main(),"Learning Time : %f sec\n",	ett.learn()/CLOCKS_PER_SEC);
			result = ett.test();
			fprintf(l.main(),"Error rate : %f %%\n", result.getErrorRate());
			fprintf(stderr,"Error rate : %f %%\n", result.getErrorRate());
			result.printProb(l.roc());
			
			std::vector<float> gim(db.getNbGroup(),0.0);
			ett.computeGroupVimp(gim,ls);
			ett.printGroupVimp(gim,l.groupimp());	
			
			ett.computeVimp(vim,ls);
			ett.printVimp(vim,l.varimp());
			
			l.flush();
			break;
		} case 5: { // WIP...
			fprintf(stderr,"RANDOM TT STUMP\n");
			RandomTTForest rttf(&db,nbTree,k,nmin);
			rttf.setKint(0);
			rttf.setLS(&ls);
			rttf.setTS(&ts);
			rttf.setTreeType(RANDOMTTSTUMP);
			rttf.setAttCand(&attcand);
			rttf.setGroupCand(groupcand);
			rttf.setInternalComp(intc);
			rttf.print(l.main());
			fprintf(l.main(),"Learning Time : %f sec\n",	rttf.learn()/CLOCKS_PER_SEC);
			result = rttf.test();
			fprintf(l.main(),"Error rate : %f %%\n", result.getErrorRate());
			fprintf(stderr,"Error rate : %f %%\n", result.getErrorRate());
			result.printProb(l.roc());
			rttf.computeVimp();
			rttf.printVimp(l.varimp());
			rttf.computeGroupVimp();
			rttf.printGroupVimp(l.groupimp());
			l.flush();
			break;
		} case 6: { // WIP...
			fprintf(stderr,"EXTRATTSTUMP\n");
			ExtraTTrees ett(&db,nbTree,k,nmin);
			ett.setKint(0);
			ett.setLS(&ls);
			ett.setTS(&ts);
			ett.setTreeType(EXTRATTSTUMP);
			ett.setAttCand(&attcand);
			ett.setGroupCand(groupcand);
			ett.setInternalComp(intc);
			ett.print(l.main());
			fprintf(l.main(),"Learning Time : %f sec\n",	ett.learn()/CLOCKS_PER_SEC);
			result = ett.test();
			fprintf(l.main(),"Error rate : %f %%\n", result.getErrorRate());
			fprintf(stderr,"Error rate : %f %%\n", result.getErrorRate());
			result.printProb(l.roc());
			ett.computeVimp();
			ett.printVimp(l.varimp());
			ett.computeGroupVimp();
			ett.printGroupVimp(l.groupimp());	
			l.flush();			
			break;
		} default: break;
	}

	
	fprintf(l.main(),"Overall Time : %f sec\n",(clock()-clock_start) / (double) CLOCKS_PER_SEC);
	fprintf(l.main(),"Program terminated...\n");
	fprintf(stdout,"Program terminated...\n");

	return 0;
}
示例#7
0
int main( int argc , char * argv[] )  {
    std::cout << "算术" << std::endl;
    int a = 10 , b = 20;
    int ret;

    std::plus<int>add;
    ret = add(a,b);
    std::cout << ret << std::endl;

    std::minus<int> min;
    ret = min(b,a);
    std::cout << ret << std::endl;

    std::multiplies<int> mp;
    ret = mp(a,b);
    std::cout << ret << std::endl;

    std::divides<int> divi;
    ret = divi(a,b);
    std::cout << ret << std::endl;

    std::modulus<int> mod;
    ret = mod(a,b);
    std::cout << ret << std::endl;

    std::negate<int> neg;
    ret = neg(a);
    std::cout << ret << std::endl;


    std::cout << "关系" <<std::endl;
    int a2 = 10 , b2 = 20;
    int ret2;
    std::equal_to<int> et;
    ret2 = et(a,b);
    std::cout << ret2 <<std::endl;

    std::not_equal_to<int> net;
    ret2 = net(a,b);
    std::cout << ret2 << std::endl;

    std::greater<int>gt;
    ret2 = gt(b,a);
    std::cout << ret2 << std::endl;

    std::greater_equal<int> gte;
    ret2 = gte(a,b);
    std::cout << ret2 <<std::endl;

    std::less<int> ls;
    ret2 = ls(a,b);
    std::cout << ret2 << std::endl;

    std::less_equal<int> lel;
    ret2 = lel(a,b);
    std::cout << ret2 << std::endl;

    std::cout << "逻辑" << std::endl;
    int ret3;
    std::logical_and<int> la;
    ret3 = la(a,b);
    std::cout << ret3 <<std::endl;

    std::logical_or<int> lo;
    ret3 = lo(a,b);
    std::cout << ret3 << std::endl;

    std::logical_not<int>ln;
    ret3 = ln(b);
    std::cout << ret3 <<std::endl;

    return EXIT_SUCCESS;
}
示例#8
0
  /**
   * GetPointInfo builds the PvlGroup containing all the important 
   * information derived from the Camera.  
   * 
   * @return PvlGroup* Data taken directly from the Camera and 
   *         drived from Camera information. Ownership passed.
   */
  PvlGroup * CameraPointInfo::GetPointInfo() {
    CheckConditions();

    Brick b(3,3,1,currentCube->PixelType());
    
    int intSamp = (int)(camera->Sample() + 0.5);
    int intLine = (int)(camera->Line() + 0.5);
    b.SetBasePosition(intSamp, intLine, 1);
    currentCube->Read(b);

    double pB[3], spB[3], sB[3];
    string utc;
    double ssplat, ssplon, sslat, sslon, pwlon, oglat;

    // Create group with ground position
    PvlGroup * gp = new PvlGroup("GroundPoint");
    {
      gp->AddKeyword(PvlKeyword("Filename",currentCube->Filename()));
      gp->AddKeyword(PvlKeyword("Sample",camera->Sample()));
      gp->AddKeyword(PvlKeyword("Line",camera->Line()));
      gp->AddKeyword(PvlKeyword("PixelValue",PixelToString(b[0])));
      gp->AddKeyword(PvlKeyword("RightAscension",camera->RightAscension()));
      gp->AddKeyword(PvlKeyword("Declination",camera->Declination()));
      gp->AddKeyword(PvlKeyword("PlanetocentricLatitude",
                                camera->UniversalLatitude()));
  
      // Convert lat to planetographic
      double radii[3];
      camera->Radii(radii);
      oglat = Isis::Projection::ToPlanetographic(camera->UniversalLatitude(),
                                                 radii[0],radii[2]);
      gp->AddKeyword(PvlKeyword("PlanetographicLatitude",oglat));
      
      gp->AddKeyword(PvlKeyword("PositiveEast360Longitude",
                                camera->UniversalLongitude()));
  
      //Convert lon to -180 - 180 range
      gp->AddKeyword(PvlKeyword("PositiveEast180Longitude",
                                Isis::Projection::To180Domain(
                                  camera->UniversalLongitude())));

      //Convert lon to positive west
      pwlon = Isis::Projection::ToPositiveWest(camera->UniversalLongitude(),
                                               360);
      gp->AddKeyword(PvlKeyword("PositiveWest360Longitude",pwlon));

      //Convert pwlon to -180 - 180 range
      gp->AddKeyword(PvlKeyword("PositiveWest180Longitude",
                                Isis::Projection::To180Domain(pwlon)));
  
      camera->Coordinate(pB);
      PvlKeyword coord("BodyFixedCoordinate");
      coord.AddValue(pB[0],"km");
      coord.AddValue(pB[1],"km");
      coord.AddValue(pB[2],"km");
      gp->AddKeyword(coord);
  
      gp->AddKeyword(PvlKeyword("LocalRadius",camera->LocalRadius(),"m"));
      gp->AddKeyword(PvlKeyword("SampleResolution",camera->SampleResolution(),"m"));
      gp->AddKeyword(PvlKeyword("LineResolution",camera->LineResolution(),"m"));
  
      camera->InstrumentPosition(spB);
      PvlKeyword spcoord("SpacecraftPosition");
      spcoord.AddValue(spB[0],"km");
      spcoord.AddValue(spB[1],"km");
      spcoord.AddValue(spB[2],"km");
      spcoord.AddComment("Spacecraft Information");
      gp->AddKeyword(spcoord);
  
  
      gp->AddKeyword(PvlKeyword("SpacecraftAzimuth",camera->SpacecraftAzimuth()));
      gp->AddKeyword(PvlKeyword("SlantDistance",camera->SlantDistance(),"km"));
      gp->AddKeyword(PvlKeyword("TargetCenterDistance",camera->TargetCenterDistance(),"km"));
      camera->SubSpacecraftPoint(ssplat,ssplon);
      gp->AddKeyword(PvlKeyword("SubSpacecraftLatitude",ssplat));
      gp->AddKeyword(PvlKeyword("SubSpacecraftLongitude",ssplon));
      gp->AddKeyword(PvlKeyword("SpacecraftAltitude",camera->SpacecraftAltitude(),"km"));
      gp->AddKeyword(PvlKeyword("OffNadirAngle",camera->OffNadirAngle()));
      double subspcgrdaz;
      subspcgrdaz = camera->GroundAzimuth(camera->UniversalLatitude(),camera->UniversalLongitude(),
        ssplat,ssplon);
      gp->AddKeyword(PvlKeyword("SubSpacecraftGroundAzimuth",subspcgrdaz));
  
      camera->SunPosition(sB);
      PvlKeyword scoord("SunPosition");
      scoord.AddValue(sB[0],"km");
      scoord.AddValue(sB[1],"km");
      scoord.AddValue(sB[2],"km");
      scoord.AddComment("Sun Information");
      gp->AddKeyword(scoord);
  
      gp->AddKeyword(PvlKeyword("SubSolarAzimuth",camera->SunAzimuth()));
      gp->AddKeyword(PvlKeyword("SolarDistance",camera->SolarDistance(),"AU"));
      camera->SubSolarPoint(sslat,sslon);
      gp->AddKeyword(PvlKeyword("SubSolarLatitude",sslat));
      gp->AddKeyword(PvlKeyword("SubSolarLongitude",sslon));
      double subsolgrdaz;
      subsolgrdaz = camera->GroundAzimuth(camera->UniversalLatitude(),camera->UniversalLongitude(),
        sslat,sslon);
      gp->AddKeyword(PvlKeyword("SubSolarGroundAzimuth",subsolgrdaz));
  
      PvlKeyword phase("Phase",camera->PhaseAngle());
      phase.AddComment("Illumination and Other");
      gp->AddKeyword(phase);
      gp->AddKeyword(PvlKeyword("Incidence",camera->IncidenceAngle()));
      gp->AddKeyword(PvlKeyword("Emission",camera->EmissionAngle()));
      gp->AddKeyword(PvlKeyword("NorthAzimuth",camera->NorthAzimuth()));
  
      PvlKeyword et("EphemerisTime",camera->EphemerisTime(),"seconds");
      et.AddComment("Time");
      gp->AddKeyword(et);
      iTime t(camera->EphemerisTime());
      utc = t.UTC();
      gp->AddKeyword(PvlKeyword("UTC",utc));
      gp->AddKeyword(PvlKeyword("LocalSolarTime",camera->LocalSolarTime(),"hour"));
      gp->AddKeyword(PvlKeyword("SolarLongitude",camera->SolarLongitude()));
    }
    return gp;
  }
//void PieceAppearanceWidget::applyCurrentTemplate( QObject * tgt )
void PieceAppearanceWidget::applyCurrentTemplate( QGIPiece * tgt )
{
    if( !tgt ) return;
    typedef QList<QGraphicsItem*> QIL;
    QIL li( impl->gv->scene()->selectedItems() );
    impl->pc = 0;
    // If there are multiple items selected, simply pick the first
    // selected item which has an associated piece (the order has no
    // meaning, however).
    for( QIL::iterator it = li.begin();
	 li.end() != it;
	 ++it )
    {
	QGIPiece * pvi = dynamic_cast<QGIPiece*>(*it);
	if( pvi )
	{
	    impl->pc = pvi;
	}
    }
    if( ! impl->pc ) return;

    /**
       We want to keep certain properties intact:
    
       pixmap: b/c the game client normally sets this

       pos: we don't want to use the template's pos

       dragDisabled: that property was developed to support
       this class. The client will almost always expect
       his pieces to be draggable.
    */
    QVariant pix( tgt->property("pixmap") );
    QVariant pos( tgt->property("pos") );
    QVariant dragDisabled( tgt->property("dragDisabled") );
    {
#if 0
	QObject * src = impl->pc;
	typedef QList<QByteArray> QL;
	QL ql( src->dynamicPropertyNames() );
	QL::const_iterator it( ql.begin() );
	QL::const_iterator et( ql.end() );
	for( ; et != it; ++it )
	{
	    char const * key = it->constData();
	    if( !key || (*key == '_') ) continue; // Qt reserves the "_q_" prefix, so we'll elaborate on that.
	    tgt->setProperty( key, src->property(key) );
	}
#else
	S11nNode n;
	impl->pc->serialize(n);
	// Lame kludge to ensure that we don't throw
	// here if tgt is a subclass of QGIType:
	const QString cn1( S11nNodeTraits::class_name(n).c_str() );
	const QString cn2( tgt->s11nClass() );
	if( cn1 != cn2 )
	{
	    S11nNodeTraits::class_name(n,cn2.toAscii().constData());
	}
	tgt->deserialize(n);
#endif
    }
    tgt->setProperty("pos", pos );
    tgt->setProperty("pixmap", pix );
    tgt->setProperty("dragDisabled", dragDisabled );
}
示例#10
0
static void tred2(const SymmetricMatrix& A, DiagonalMatrix& D,
   DiagonalMatrix& E, Matrix& Z)
{
   Tracer et("Evalue(tred2)");
   Real tol =
      FloatingPointPrecision::Minimum()/FloatingPointPrecision::Epsilon();
   int n = A.Nrows(); Z.ReSize(n,n); Z.Inject(A);
   D.ReSize(n); E.ReSize(n);
   Real* z = Z.Store(); int i;

   for (i=n-1; i > 0; i--)                   // i=0 is excluded
   {
      Real f = Z.element(i,i-1); Real g = 0.0;
      int k = i-1; Real* zik = z + i*n;
      while (k--) g += square(*zik++);
      Real h = g + square(f);
      if (g <= tol) { E.element(i) = f; h = 0.0; }
      else
      {
	 g = sign(-sqrt(h), f); E.element(i) = g; h -= f*g;
	 Z.element(i,i-1) = f-g; f = 0.0;
         Real* zji = z + i; Real* zij = z + i*n; Real* ej = E.Store();
         int j;
	 for (j=0; j<i; j++)
	 {
	    *zji = (*zij++)/h; g = 0.0;
            Real* zjk = z + j*n; zik = z + i*n;
            k = j; while (k--) g += *zjk++ * (*zik++);
            k = i-j; while (k--) { g += *zjk * (*zik++); zjk += n; }
	    *ej++ = g/h; f += g * (*zji); zji += n;
	 }
	 Real hh = f / (h + h); zij = z + i*n; ej = E.Store();
	 for (j=0; j<i; j++)
	 {
	    f = *zij++; g = *ej - hh * f; *ej++ = g;
            Real* zjk = z + j*n; Real* zik = z + i*n;
            Real* ek = E.Store(); k = j+1;
            while (k--)  *zjk++ -= ( f*(*ek++) + g*(*zik++) ); 
	 }
      }
      D.element(i) = h;
   }

   D.element(0) = 0.0; E.element(0) = 0.0;
   for (i=0; i<n; i++)
   {
      if (D.element(i) != 0.0)
      {
	 for (int j=0; j<i; j++)
	 {
	    Real g = 0.0;
            Real* zik = z + i*n; Real* zkj = z + j;
            int k = i; while (k--) { g += *zik++ * (*zkj); zkj += n; }
            Real* zki = z + i; zkj = z + j;
            k = i; while (k--) { *zkj -= g * (*zki); zkj += n; zki += n; }
	 }
      }
      Real* zij = z + i*n; Real* zji = z + i;
      int j = i; while (j--)  { *zij++ = 0.0; *zji = 0.0; zji += n; }
      D.element(i) = *zij; *zij = 1.0;
   }
}
示例#11
0
static void tql2(DiagonalMatrix& D, DiagonalMatrix& E, Matrix& Z)
{
   Tracer et("Evalue(tql2)");
   Real eps = FloatingPointPrecision::Epsilon();
   int n = D.Nrows(); Real* z = Z.Store(); int l;
   for (l=1; l<n; l++) E.element(l-1) = E.element(l);
   Real b = 0.0; Real f = 0.0; E.element(n-1) = 0.0;
   for (l=0; l<n; l++)
   {
      int i,j;
      Real& dl = D.element(l); Real& el = E.element(l);
      Real h = eps * ( fabs(dl) + fabs(el) );
      if (b < h) b = h;
      int m;
      for (m=l; m<n; m++) if (fabs(E.element(m)) <= b) break;
      bool test = false;
      for (j=0; j<30; j++)
      {
	 if (m==l) { test = true; break; }
	 Real& dl1 = D.element(l+1);
	 Real g = dl; Real p = (dl1-g) / (2.0*el); Real r = sqrt(p*p + 1.0);
	 dl = el / (p < 0.0 ? p-r : p+r); Real h = g - dl; f += h;
	 Real* dlx = &dl1; i = n-l-1; while (i--) *dlx++ -= h;

	 p = D.element(m); Real c = 1.0; Real s = 0.0;
	 for (i=m-1; i>=l; i--)
	 {
	    Real ei = E.element(i); Real di = D.element(i);
	    Real& ei1 = E.element(i+1);
	    g = c * ei; h = c * p;
	    if ( fabs(p) >= fabs(ei))
	    {
	       c = ei / p; r = sqrt(c*c + 1.0);
	       ei1 = s*p*r; s = c/r; c = 1.0/r;
	    }
	    else
	    {
	       c = p / ei; r = sqrt(c*c + 1.0);
	       ei1 = s * ei * r; s = 1.0/r; c /= r;
	    }
	    p = c * di - s*g; D.element(i+1) = h + s * (c*g + s*di);

	    Real* zki = z + i; Real* zki1 = zki + 1; int k = n;
	    while (k--)
	    {
	       h = *zki1; *zki1 = s*(*zki) + c*h; *zki = c*(*zki) - s*h;
	       zki += n; zki1 += n;
	    }
	 }
	 el = s*p; dl = c*p;
	 if (fabs(el) <= b) { test = true; break; }
      }
      if (!test) Throw ( ConvergenceException(D) );
      dl += f;
   }

   for (int i=0; i<n; i++)
   {
      int k = i; Real p = D.element(i);
      for (int j=i+1; j<n; j++)
         { if (D.element(j) < p) { k = j; p = D.element(j); } }
      if (k != i)
      {
         D.element(k) = D.element(i); D.element(i) = p; int j = n;
	 Real* zji = z + i; Real* zjk = z + k;
         while (j--) { p = *zji; *zji = *zjk; *zjk = p; zji += n; zjk += n; }
      }
   }

}
示例#12
0
文件: Solveur.cpp 项目: prShadoko/SAT
/**
 * Simplifie une formule.
 * Cette fonction exprime les équivalences et implications de la formule en entrée avec les opérateurs ET, OU et NON.
 * Elle ramène également toutes les négations de la formule au niveau des littéraux.
 * @param form La formule à simplifier.
 * @param negation Indique si l'élément parent était un NON. Vaut false par défaut.
 * @return La formule simplifiée.
 * @see formule
 */
formule* simplifie_formule(const formule *form, const bool negation) {
	formule *form_out = NULL;

	switch(form->op) {
		case o_variable:
		{
			if(negation) {
				form_out = non(var(*(form->nom)));
			} else {
				form_out = var(*(form->nom));
			}
			break;
		}

		case o_equivaut:
		{
			if(negation) {
				form_out = ou(
								et(	simplifie_formule(form->arg1, true),
									simplifie_formule(form->arg2)),
								et(	simplifie_formule(form->arg2, true),
									simplifie_formule(form->arg1))
							);
			} else {
				form_out = et(
								ou(	simplifie_formule(form->arg1, true),
									simplifie_formule(form->arg2)),
								ou(	simplifie_formule(form->arg2, true),
									simplifie_formule(form->arg1))
							);
			}
			break;
		}

		case o_implique:
		{
			if(negation) {
				form_out = et(simplifie_formule(form->arg1), simplifie_formule(form->arg2, true));
			} else {
				form_out = ou(simplifie_formule(form->arg1, true), simplifie_formule(form->arg2));
			}
			break;
		}

		case o_non:
		{
			form_out = simplifie_formule(form->arg, !negation);
			break;
		}

		case o_ou:
		{
			if(negation) {
				form_out = et(simplifie_formule(form->arg1, true), simplifie_formule(form->arg2, true));
			} else {
				form_out = ou(simplifie_formule(form->arg1), simplifie_formule(form->arg2));
			}
			break;
		}

		case o_et:
		{
			if(negation) {
				form_out = ou(simplifie_formule(form->arg1, true), simplifie_formule(form->arg2, true));
			} else {
				form_out = et(simplifie_formule(form->arg1), simplifie_formule(form->arg2));
			}
			break;
		}
	}
	return form_out;
}
示例#13
0
void State::enforce_outflow(const OctFace& f, const _3Vec& X) {
	switch (f) {
#ifdef USE_LZ
	case XU:
		if (vx(X) > 0.0) {
			(*this)[sy_index] = X[0] * vy(X) * rho();
			(*this)[sx_index] = X[1] * vy(X) * rho() / sqrt(X[0] * X[0] + X[1] * X[1]);
		}
		break;
	case XL:
		if (vx(X) < 0.0) {
			(*this)[sy_index] = X[0] * vy(X) * rho();
			(*this)[sx_index] = X[1] * vy(X) * rho() / sqrt(X[0] * X[0] + X[1] * X[1]);
		}
		break;
	case YU:
		if (vy(X) > 0.0) {
			(*this)[sy_index] = -X[1] * vx(X) * rho();
			(*this)[sx_index] = X[0] * vx(X) * rho() / sqrt(X[0] * X[0] + X[1] * X[1]);
		}
		break;
	case YL:
		if (vy(X) < 0.0) {
			(*this)[sy_index] = -X[1] * vx(X) * rho();
			(*this)[sx_index] = X[0] * vx(X) * rho() / sqrt(X[0] * X[0] + X[1] * X[1]);
		}
		break;
#else
		case XU:
		if (vx() > 0.0) {
			set_et(et() - 0.5 * sx() * sx() / rho());
			set_sx(0.0);
		}
		break;
		case XL:
		if (vx() < 0.0) {
			set_et(et() - 0.5 * sx() * sx() / rho());
			set_sx(0.0);
		}
		break;
		case YU:
		if (vy() > 0.0) {
			set_et(et() - 0.5 * sy() * sy() / rho());
			set_sy(0.0);
		}
		break;
		case YL:
		if (vy() < 0.0) {
			set_et(et() - 0.5 * sy() * sy() / rho());
			set_sy(0.0);
		}
		break;
#endif
	case ZU:
		if (sz() > 0.0) {
			set_et(et() - 0.5 * sz() * sz() / rho());
			set_sz(0.0);
		}
		break;
	case ZL:
		if (sz() < 0.0) {
			set_et(et() - 0.5 * sz() * sz() / rho());
			set_sz(0.0);
		}
		break;
	}
}
示例#14
0
void NetworkConfig::_fromDictionary(const Dictionary &d)
{
	static const std::string zero("0");
	static const std::string one("1");

	// NOTE: d.get(name) throws if not found, d.get(name,default) returns default

	_nwid = Utils::hexStrToU64(d.get(ZT_NETWORKCONFIG_DICT_KEY_NETWORK_ID).c_str());
	if (!_nwid)
		throw std::invalid_argument("configuration contains zero network ID");

	_timestamp = Utils::hexStrToU64(d.get(ZT_NETWORKCONFIG_DICT_KEY_TIMESTAMP).c_str());
	_revision = Utils::hexStrToU64(d.get(ZT_NETWORKCONFIG_DICT_KEY_REVISION,"1").c_str()); // older controllers don't send this, so default to 1

	memset(_etWhitelist,0,sizeof(_etWhitelist));
	std::vector<std::string> ets(Utils::split(d.get(ZT_NETWORKCONFIG_DICT_KEY_ALLOWED_ETHERNET_TYPES).c_str(),",","",""));
	for(std::vector<std::string>::const_iterator et(ets.begin());et!=ets.end();++et) {
		unsigned int tmp = Utils::hexStrToUInt(et->c_str()) & 0xffff;
		_etWhitelist[tmp >> 3] |= (1 << (tmp & 7));
	}

	_issuedTo = Address(d.get(ZT_NETWORKCONFIG_DICT_KEY_ISSUED_TO));
	_multicastLimit = Utils::hexStrToUInt(d.get(ZT_NETWORKCONFIG_DICT_KEY_MULTICAST_LIMIT,zero).c_str());
	if (_multicastLimit == 0) _multicastLimit = ZT_MULTICAST_DEFAULT_LIMIT;
	_allowPassiveBridging = (Utils::hexStrToUInt(d.get(ZT_NETWORKCONFIG_DICT_KEY_ALLOW_PASSIVE_BRIDGING,zero).c_str()) != 0);
	_private = (Utils::hexStrToUInt(d.get(ZT_NETWORKCONFIG_DICT_KEY_PRIVATE,one).c_str()) != 0);
	_enableBroadcast = (Utils::hexStrToUInt(d.get(ZT_NETWORKCONFIG_DICT_KEY_ENABLE_BROADCAST,one).c_str()) != 0);
	_name = d.get(ZT_NETWORKCONFIG_DICT_KEY_NAME);
	if (_name.length() > ZT1_MAX_NETWORK_SHORT_NAME_LENGTH)
		throw std::invalid_argument("network short name too long (max: 255 characters)");
	_description = d.get(ZT_NETWORKCONFIG_DICT_KEY_DESC,std::string());

	// In dictionary IPs are split into V4 and V6 addresses, but we don't really
	// need that so merge them here.
	std::string ipAddrs(d.get(ZT_NETWORKCONFIG_DICT_KEY_IPV4_STATIC,std::string()));
	{
		std::string v6s(d.get(ZT_NETWORKCONFIG_DICT_KEY_IPV6_STATIC,std::string()));
		if (v6s.length()) {
			if (ipAddrs.length())
				ipAddrs.push_back(',');
			ipAddrs.append(v6s);
		}
	}

	std::vector<std::string> ipAddrsSplit(Utils::split(ipAddrs.c_str(),",","",""));
	for(std::vector<std::string>::const_iterator ipstr(ipAddrsSplit.begin());ipstr!=ipAddrsSplit.end();++ipstr) {
		InetAddress addr(*ipstr);
		switch(addr.ss_family) {
			case AF_INET:
				if ((!addr.netmaskBits())||(addr.netmaskBits() > 32))
					continue;
				break;
			case AF_INET6:
				if ((!addr.netmaskBits())||(addr.netmaskBits() > 128))
					continue;
				break;
			default: // ignore unrecognized address types or junk/empty fields
				continue;
		}
		_staticIps.push_back(addr);
	}
	if (_staticIps.size() > ZT1_MAX_ZT_ASSIGNED_ADDRESSES)
		throw std::invalid_argument("too many ZT-assigned IP addresses");
	std::sort(_staticIps.begin(),_staticIps.end());
	std::unique(_staticIps.begin(),_staticIps.end());

	std::vector<std::string> activeBridgesSplit(Utils::split(d.get(ZT_NETWORKCONFIG_DICT_KEY_ACTIVE_BRIDGES,"").c_str(),",","",""));
	for(std::vector<std::string>::const_iterator a(activeBridgesSplit.begin());a!=activeBridgesSplit.end();++a) {
		if (a->length() == ZT_ADDRESS_LENGTH_HEX) { // ignore empty or garbage fields
			Address tmp(*a);
			if (!tmp.isReserved())
				_activeBridges.push_back(tmp);
		}
	}
	std::sort(_activeBridges.begin(),_activeBridges.end());
	std::unique(_activeBridges.begin(),_activeBridges.end());

	Dictionary multicastRateEntries(d.get(ZT_NETWORKCONFIG_DICT_KEY_MULTICAST_RATES,std::string()));
	for(Dictionary::const_iterator i(multicastRateEntries.begin());i!=multicastRateEntries.end();++i) {
		std::vector<std::string> params(Utils::split(i->second.c_str(),",","",""));
		if (params.size() >= 3)
			_multicastRates[MulticastGroup(i->first)] = MulticastRate(Utils::hexStrToUInt(params[0].c_str()),Utils::hexStrToUInt(params[1].c_str()),Utils::hexStrToUInt(params[2].c_str()));
	}

	std::vector<std::string> relaysSplit(Utils::split(d.get(ZT_NETWORKCONFIG_DICT_KEY_RELAYS,"").c_str(),",","",""));
	for(std::vector<std::string>::const_iterator r(relaysSplit.begin());r!=relaysSplit.end();++r) {
		std::size_t semi(r->find(';')); // address;ip/port,...
		if (semi == ZT_ADDRESS_LENGTH_HEX) {
			std::pair<Address,InetAddress> relay(
				Address(r->substr(0,semi)),
				((r->length() > (semi + 1)) ? InetAddress(r->substr(semi + 1)) : InetAddress()) );
			if ((relay.first)&&(!relay.first.isReserved()))
				_relays.push_back(relay);
		}
	}
	std::sort(_relays.begin(),_relays.end());
	std::unique(_relays.begin(),_relays.end());

	_com.fromString(d.get(ZT_NETWORKCONFIG_DICT_KEY_CERTIFICATE_OF_MEMBERSHIP,std::string()));
}
示例#15
0
	void GSurface::createForwardDiffMatrices(){
	  Transformation es(_es), et(_et);
	  _DDx = (es * _cx * et).m();
	  _DDy = (es * _cy * et).m();
	  _DDz = (es * _cz * et).m();
	}
示例#16
0
void test_2d_compare()
{
    P p1 = bg::make<P>(3, 1);
    P p2 = bg::make<P>(3, 1);
    P p3 = bg::make<P>(1, 3);
    P p4 = bg::make<P>(5, 2);
    P p5 = bg::make<P>(3, 2);

    // Test in all dimensions
    {
        bg::equal_to<P> et;
        bg::less<P> lt;
        bg::greater<P> gt;

        BOOST_CHECK_EQUAL(et(p1, p2), true);
        BOOST_CHECK_EQUAL(et(p1, p3), false);
        BOOST_CHECK_EQUAL(et(p1, p4), false);
        BOOST_CHECK_EQUAL(et(p1, p5), false);
        BOOST_CHECK_EQUAL(et(p3, p4), false);

        BOOST_CHECK_EQUAL(lt(p1, p2), false);
        BOOST_CHECK_EQUAL(lt(p1, p3), false);
        BOOST_CHECK_EQUAL(lt(p1, p4), true);
        BOOST_CHECK_EQUAL(lt(p1, p5), true);
        BOOST_CHECK_EQUAL(lt(p3, p4), true);

        BOOST_CHECK_EQUAL(gt(p1, p2), false);
        BOOST_CHECK_EQUAL(gt(p1, p3), true);
        BOOST_CHECK_EQUAL(gt(p1, p4), false);
        BOOST_CHECK_EQUAL(gt(p1, p5), false);
        BOOST_CHECK_EQUAL(gt(p3, p4), false);
    }


    // Test in dimension 0, X
    {
        bg::equal_to<P, 0> et;
        bg::less<P, 0> lt;
        bg::greater<P, 0> gt;

        BOOST_CHECK_EQUAL(et(p1, p2), true);
        BOOST_CHECK_EQUAL(et(p1, p3), false);
        BOOST_CHECK_EQUAL(et(p1, p4), false);
        BOOST_CHECK_EQUAL(et(p1, p5), true);
        BOOST_CHECK_EQUAL(et(p3, p4), false);

        BOOST_CHECK_EQUAL(lt(p1, p2), false);
        BOOST_CHECK_EQUAL(lt(p1, p3), false);
        BOOST_CHECK_EQUAL(lt(p1, p4), true);
        BOOST_CHECK_EQUAL(lt(p1, p5), false);
        BOOST_CHECK_EQUAL(lt(p3, p4), true);

        BOOST_CHECK_EQUAL(gt(p1, p2), false);
        BOOST_CHECK_EQUAL(gt(p1, p3), true);
        BOOST_CHECK_EQUAL(gt(p1, p4), false);
        BOOST_CHECK_EQUAL(gt(p1, p5), false);
        BOOST_CHECK_EQUAL(gt(p3, p4), false);
    }

    // Test in dimension 1, Y
    {
        bg::equal_to<P, 1> et;
        bg::less<P, 1> lt;
        bg::greater<P, 1> gt;

        BOOST_CHECK_EQUAL(et(p1, p2), true);
        BOOST_CHECK_EQUAL(et(p1, p3), false);
        BOOST_CHECK_EQUAL(et(p1, p4), false);
        BOOST_CHECK_EQUAL(et(p1, p5), false);
        BOOST_CHECK_EQUAL(et(p3, p4), false);

        BOOST_CHECK_EQUAL(lt(p1, p2), false);
        BOOST_CHECK_EQUAL(lt(p1, p3), true);
        BOOST_CHECK_EQUAL(lt(p1, p4), true);
        BOOST_CHECK_EQUAL(lt(p1, p5), true);
        BOOST_CHECK_EQUAL(lt(p3, p4), false);

        BOOST_CHECK_EQUAL(gt(p1, p2), false);
        BOOST_CHECK_EQUAL(gt(p1, p3), false);
        BOOST_CHECK_EQUAL(gt(p1, p4), false);
        BOOST_CHECK_EQUAL(gt(p1, p5), false);
        BOOST_CHECK_EQUAL(gt(p3, p4), true);
    }
}
示例#17
0
void Jacobi(const SymmetricMatrix& X, DiagonalMatrix& D, SymmetricMatrix& A,
   Matrix& V, bool eivec)
{
   Real epsilon = FloatingPointPrecision::Epsilon();
   Tracer et("Jacobi");
   REPORT
   int n = X.Nrows(); DiagonalMatrix B(n), Z(n); D.resize(n); A = X;
   if (eivec) { REPORT V.resize(n,n); D = 1.0; V = D; }
   B << A; D = B; Z = 0.0; A.Inject(Z);
   bool converged = false;
   for (int i=1; i<=50; i++)
   {
      Real sm=0.0; Real* a = A.Store(); int p = A.Storage();
      while (p--) sm += fabs(*a++);            // have previously zeroed diags
      if (sm==0.0) { REPORT converged = true; break; }
      Real tresh = (i<4) ? 0.2 * sm / square(n) : 0.0; a = A.Store();
      for (p = 0; p < n; p++)
      {
         Real* ap1 = a + (p*(p+1))/2;
         Real& zp = Z.element(p); Real& dp = D.element(p);
         for (int q = p+1; q < n; q++)
         {
            Real* ap = ap1; Real* aq = a + (q*(q+1))/2;
            Real& zq = Z.element(q); Real& dq = D.element(q);
            Real& apq = A.element(q,p);
            Real g = 100 * fabs(apq); Real adp = fabs(dp); Real adq = fabs(dq);

            if (i>4 && g < epsilon*adp && g < epsilon*adq) { REPORT apq = 0.0; }
            else if (fabs(apq) > tresh)
            {
               REPORT
               Real t; Real h = dq - dp; Real ah = fabs(h);
               if (g < epsilon*ah) { REPORT t = apq / h; }
               else
               {
                  REPORT
                  Real theta = 0.5 * h / apq;
                  t = 1.0 / ( fabs(theta) + sqrt(1.0 + square(theta)) );
                  if (theta<0.0) { REPORT t = -t; }
               }
               Real c = 1.0 / sqrt(1.0 + square(t)); Real s = t * c;
               Real tau = s / (1.0 + c); h = t * apq;
               zp -= h; zq += h; dp -= h; dq += h; apq = 0.0;
               int j = p;
               while (j--)
               {
                  g = *ap; h = *aq;
                  *ap++ = g-s*(h+g*tau); *aq++ = h+s*(g-h*tau);
               }
               int ip = p+1; j = q-ip; ap += ip++; aq++;
               while (j--)
               {
                  g = *ap; h = *aq;
                  *ap = g-s*(h+g*tau); *aq++ = h+s*(g-h*tau);
                  ap += ip++;
               }
               if (q < n-1)             // last loop is non-empty
               {
                  int iq = q+1; j = n-iq; ap += ip++; aq += iq++;
                  for (;;)
                  {
                     g = *ap; h = *aq;
                     *ap = g-s*(h+g*tau); *aq = h+s*(g-h*tau);
                     if (!(--j)) break;
                     ap += ip++; aq += iq++;
                  }
               }
               if (eivec)
               {
                  REPORT
                  RectMatrixCol VP(V,p); RectMatrixCol VQ(V,q);
                  Rotate(VP, VQ, tau, s);
               }
            }
         }
      }
      B = B + Z; D = B; Z = 0.0;
   }
   if (!converged) Throw(ConvergenceException(X));
   if (eivec) SortSV(D, V, true);
   else SortAscending(D);
}
示例#18
0
文件: fetch.C 项目: mousebrains/kayak
int
main (int argc,
      char **argv)
{
  const char *options("hs:u:v");
  bool qVerbose(false);
  std::string saveFilename;

  typedef std::vector<std::string> tStrings;
  tStrings urls;

  for (int c; (c = getopt(argc, argv, options)) != EOF;) {
    switch (c) {
      case 's': saveFilename = optarg; break;
      case 'u': urls.push_back(optarg); break;
      case 'v': qVerbose = !qVerbose; break;
      default:
        std::cerr << "Unrecognized option (" << ((char) optopt) << ")" << std::endl;
      case 'h':
        return usage(argv[0], options);
    }
  }

  if (optind < argc) {
    std::cerr << "Unprocessed command line arguments:";
    for (int i(optind); i < argc; ++i) {
      std::cerr << " '" << argv[i] << "'";
    }
    std::cerr << std::endl;
    return usage(argv[0], options);
  }

  if (urls.empty()) { // Build from database
    std::cerr << "urls from database not currently implemented!" << std::endl;
    return 1;
  }

  for (tStrings::const_iterator it(urls.begin()), et(urls.end()); it != et; ++it) {
    const std::string::size_type j(it->find(':'));
    if (j == it->npos) {
      std::cerr << "Malformed parser:URL field(" << *it << ")" << std::endl;
      return 1;
    }
    const std::string parser(it->substr(0,j));
    const std::string url(it->substr(j+1));
    Curl curl(url, qVerbose); // Load the file
    if (!curl) {
      std::cerr << "Error fetching '" << url << "', " << curl.errmsg() << std::endl;
      continue;
    }
    if (curl.responseCode() != 200) {
      std::cerr << "Error fetching '" << url 
                << "', response code " << curl.responseCode()
                << ", " << HTTP::statusMsg(curl.responseCode())
                << std::endl;
      continue;
    }

    if (!saveFilename.empty()) {
      std::ofstream os(saveFilename);
      if (!os) {
         std::cerr << "Error opening '" << saveFilename << "', " << strerror(errno) << std::endl;
         return 1;
      }
      os << curl.str();
    }

    if (parser == "USGS0") {
      ParserUSGS0 a(url, curl.str(), qVerbose);
    } else if (parser == "USGS1") {
      ParserUSGS1 a(url, curl.str(), qVerbose);
    } else if (parser == "NOAA0") {
      ParserNOAA0 a(url, curl.str(), qVerbose);
    } else {
      std::cerr << "Unrecongized parser '" << parser << "'" << std::endl;
      continue;
    }
  }

  return 0;
}