Example #1
0
bool                              // returns true if success
processGraphSection(FILE *fp,
		    string& theline,
		    bool& new_section)
{
  vector<string> v_tokens;
  TString  title;
  string   *gid  = NULL;
  TVectorD vx,vy,vz,exl,exh,eyl,eyh;
  float xoffset=0.0,yoffset=0.0, yscale=1.0;
  float xmin=0.,xmax=0.,ymin=0.,ymax=0.,zmin=0.,zmax=0.;
  bool asymerrors = false;
  bool printvecs  = false;
  wGraph_t wg;                                    // placeholder for read-in values
  vector<std::pair<string, wGraph_t *> > v_graphs;

  char xheader[80],yheader[80];
  xheader[0]=0;
  yheader[0]=0;

  if (gl_verbose) cout << "Processing graph section" << endl;

  new_section=false;

  while (getLine(fp,theline,"graph")) {
    if (!theline.size()) continue;
    if (theline[0] == '#') continue; // comments are welcome

    if (theline[0] == '[') {
      new_section=true;
      break;
    }

    string key, value;
    if (!getKeyValue(theline,key,value)) continue;

    //--------------------
    if (key == "id") {
    //--------------------
      if (gid != NULL) {
	cerr << "no more than one id per graph section allowed " << value << endl;
	break;
      }

      gid = new string(value);

    //------------------------------
    } else if (key == "vectorfile") {
    //------------------------------
      if (!gid) {
	cerr << "id key must be defined first in the section" << endl; continue;
      }
      string path     = value;
      string scanspec = asymerrors ?  "%lf %lf %lf %lf" : "%lf %lf";

      Tokenize(value,v_tokens,",");
      if (v_tokens.size() > 1) {
	path     = v_tokens[0];
	scanspec = v_tokens[1];
      }

      if (v_graphs.size()) {
	cerr << "graph(s) already defined" << endl; continue;
      }
      if (inSet<string>(glset_graphFilesReadIn,path)) {
	cerr << "vector file " << path << " already read in" << endl; break;
      }

      wGraph_t *pwg = new wGraph_t();

      if (asymerrors)
	loadVectorsFromFile(path.c_str(),scanspec.c_str(),vx,vy,exl,exh,eyl,eyh);
      else
	loadVectorsFromFile(path.c_str(),scanspec.c_str(),vx,vy,xheader,yheader);

      if (strlen(xheader)) pwg->xax->SetTitle(xheader);
      if (strlen(yheader)) pwg->yax->SetTitle(yheader);

      v_graphs.push_back(pair<string,wGraph_t *>(*gid,pwg));

      // pend filling the graph until all parameters are read in

    //------------------------------
    } else if (key == "vectorfile2d") {
    //------------------------------
      if (!gid) {
	cerr << "id key must be defined first in the section" << endl; continue;
      }
      if (v_graphs.size()) {
	cerr << "graph(s) already defined" << endl; continue;
      }

      Tokenize(value,v_tokens,",");

      string path=v_tokens[0];
      if (inSet<string>(glset_graphFilesReadIn,path)) {
	cerr << "vector file " << path << " already read in" << endl; break;
      }

      wGraph_t *pwg = new wGraph_t();

      switch(v_tokens.size()) {
      case 1:  pwg->gr2d = new TGraph2D(path.c_str()); break;
      case 2:  pwg->gr2d = new TGraph2D(path.c_str(),v_tokens[1].c_str()); break;
      case 3:  pwg->gr2d = new TGraph2D(path.c_str(),v_tokens[1].c_str(),v_tokens[2].c_str()); break;
      default:
	cerr << "malformed vectorfile2d spec path[,format[,option]] " << value << endl;
	break;
      }

      if (pwg->gr2d->IsZombie()) {
	cerr << "Unable to make Graph2D from file " << path << endl;
	exit(-1);
      }
      pwg->gr2d->SetName(gid->c_str());

      v_graphs.push_back(pair<string,wGraph_t *>(*gid,pwg));

    //------------------------------
    } else if (key == "path") {
    //------------------------------

      if (!gid) {
	cerr << "id key must be defined first in the section" << endl; continue;
      }
      if (v_graphs.size()) {
	cerr << "graph already defined" << endl; continue;
      }
      wGraph_t *pwg = new wGraph_t();
      pwg->gr  = getGraphFromSpec(*gid,value);
      if (!pwg->gr) continue;

      v_graphs.push_back(pair<string,wGraph_t *>(*gid,pwg));

    //------------------------------
    } else if (key == "clone") {
    //------------------------------

      if (!gid) {
	cerr << "id key must be defined first in the section" << endl; continue;
      }
      if (v_graphs.size()) {
	cerr << "graph already defined" << endl; continue;
      }
      map<string,wGraph_t *>::const_iterator it = glmap_id2graph.find(value);
      if( it == glmap_id2graph.end() ) {
	cerr << "Graph ID " << value << " not found,";
	cerr << "clone must be defined after the clonee" << endl;
	break;
      }
      wGraph_t *pwg  = new wGraph_t(*(it->second),*gid);

      v_graphs.push_back(pair<string,wGraph_t *>(*gid,pwg));

    //------------------------------
    } else if( key == "fromhisto" ) { // converts TH1 to TGraph
    //------------------------------
      if( !gid ) {
	cerr << "id key must be defined first in the section" << endl; continue;
      }
      if (v_graphs.size()) {
	cerr << "graph(s) already defined" << endl; continue;
      }
      // look for multihist with this identifier
      std::map<string,unsigned>::const_iterator it=glmap_mhid2size.find(value);
      if (it!=glmap_mhid2size.end()) {
	for (size_t i=0; i<it->second; i++) {
	  string hidi=value+int2str(i);
	  TH1 *h = (TH1 *)findHisto(hidi,"");
	  assert(h);
	  wGraph_t *pwg = new wGraph_t();
	  pwg->gr = new TGraph(h);
	  v_graphs.push_back(pair<string,wGraph_t *>(*gid,pwg));
	}
      } else {
	TH1 *h = (TH1 *)findHisto(value);
	assert(h);
	wGraph_t *pwg = new wGraph_t();
	pwg->gr = new TGraph(h);
	v_graphs.push_back(pair<string,wGraph_t *>(*gid,pwg));
      }

    //------------------------------
    } else if( key == "fillfromtree" ) { // converts tree array variables into a group of graphs
    //------------------------------
      if( !gid ) {
	cerr << "id key must be defined first in the section" << endl; continue;
      }
      if (v_graphs.size()) {
	cerr << "graph(s) already defined" << endl; continue;
      }

      Tokenize(value,v_tokens,";");
      string treedrawspec=v_tokens[0];

      int ifirst=-1,ilast=-1;
      if (v_tokens.size() == 2) {
	string range=v_tokens[1];
	Tokenize(range,v_tokens,"-");
	if (v_tokens.size()==2) {
	  ifirst=str2int(v_tokens[0]);
	  ilast =str2int(v_tokens[1]);
	}
      }
      //cout << v_tokens.size() << " " << ifirst << " " << ilast << endl;
      if (ifirst>0 && 
	  ilast>=ifirst ) {
	for (int i=ifirst; i<=ilast; i++) {
	  wGraph_t *pwg = NULL;

	  // defined in spTree.C
	  void fillGraphFromTreeVar(std::string& drawspec,int index,wGraph_t *&pwg);
	  fillGraphFromTreeVar(treedrawspec,i,pwg);
	  assert(pwg);
	  string gidi= (*gid)+"_"+int2str(i-ifirst);
	  v_graphs.push_back(std::pair<string,wGraph_t *>(gidi,pwg));
	}

	glmap_mgid2size.insert(pair<string,unsigned>(*gid,v_graphs.size()));
      } else {
	wGraph_t *pwg = NULL;
	void fillGraphFromTreeVar(std::string& drawspec,int index,wGraph_t *&pwg);
	fillGraphFromTreeVar(treedrawspec,0,pwg);
	assert(pwg);
	v_graphs.push_back(std::pair<string,wGraph_t *>(*gid,pwg));
	glmap_mgid2size.insert(pair<string,unsigned>(*gid,v_graphs.size()));
      }

    //------------------------------
    } else if (key == "bayesdiv") {
    //------------------------------

      Tokenize(value,v_tokens,",/"); // either comma-separated or using '/'
      if (v_tokens.size() != 2) {
	cerr << "expect comma-separated list of exactly two histo specs to divide! ";
	cerr << theline << endl;
	continue;
      }

      TH1 *tmph1 = (TH1 *)findHisto(v_tokens[0]); if (!tmph1) exit(-1);
      TH1 *tmph2 = (TH1 *)findHisto(v_tokens[1]); if (!tmph2) exit(-1);

      cout << tmph1->GetNbinsX() << " " << tmph2->GetNbinsX() << endl;

      wGraph_t *pwg = new wGraph_t();

      if ( gl_verbose ) { 
	std::cout << "Dump of bin contents, errors" << std::endl ; 
	if ( tmph1->GetNbinsX() == tmph2->GetNbinsX() ) { 
	  for (int ib=1; ib<=tmph1->GetNbinsX(); ib++) {
	    std::cout << ib << ": " << tmph1->GetBinContent(ib) << "+/-" << tmph1->GetBinError(ib) 
		      << ", " << tmph2->GetBinContent(ib) << "+/-" << tmph2->GetBinError(ib) << std::endl ; 
	  }
	} else { 
	  cerr << "Histograms being divided do not have same number of bins!!!" << endl ; 
	}
      }

      // equivalent to BayesDivide
      //
      if (gl_verbose) pwg->gr = new TGraphAsymmErrors(tmph1,tmph2,"debug");
      else            pwg->gr = new TGraphAsymmErrors(tmph1,tmph2,"");
      //if (gl_verbose) pwg->gr = new TGraphAsymmErrors(tmph1,tmph2,"cl=0.683 b(1,1) mode v");
      //else            pwg->gr = new TGraphAsymmErrors(tmph1,tmph2,"cl=0.683 b(1,1) mode");
      if (!pwg->gr) {
	cerr << "BayesDivide didn't work! wonder why..." << endl;
	continue;
      } else if (gl_verbose) {
	cout << pwg->gr->GetN() << " points in the graph" << endl;
      }

      // Fix in case something broke

      for (int i=0; i<pwg->gr->GetN(); i++) {
          if ( pwg->gr->GetErrorYhigh(i) == 0. || pwg->gr->GetErrorYlow(i) == 0 ) { // Something bad happened
              if ( gl_verbose ) std::cout << "Problem with Bayes divide, checking..." << std::endl ;
              double pass  = tmph1->GetBinContent(i+1) ; 
              double total = tmph2->GetBinContent(i+1) ;
              if ( gl_verbose ) std::cout << pass << "/" << total << std::endl ;
              if ( pass == total ) {
                  if ( gl_verbose ) std::cout << "Everything OK" << std::endl ;
              } else { 
                  if ( gl_verbose ) std::cout << "Yep, something is broken" << std::endl ;
                  double xval, yval ;
                  pwg->gr->GetPoint(i,xval,yval) ;
                  yval = pass / total ;
                  // Use simplified efficiency assumption
                  // double u1 = tmph1->GetBinError(i+1) / tmph1->GetBinContent(i+1) ; 
                  // double u2 = tmph2->GetBinError(i+1) / tmph2->GetBinContent(i+1) ; 
                  // double unc = yval * sqrt( u1*u1 + u2*u2 ) ; 
                  double unc = sqrt( yval * (1.-yval)/tmph2->GetBinContent(i+1) ) ; 
                  double uhi = ( (yval + unc > 1.)?(1.-yval):(unc) ) ; 
                  double ulo = ( (yval - unc < 0.)?(yval):(unc) ) ;
                  pwg->gr->SetPoint(i,xval,yval) ;
                  ((TGraphAsymmErrors*)pwg->gr)->SetPointError(i,pwg->gr->GetErrorXlow(i),pwg->gr->GetErrorXhigh(i),ulo,uhi) ; 
//                   pwg->gr->SetPointEYhigh(i,uhi) ; 
//                   pwg->gr->SetPointEYlow(i,ulo) ; 
              }
          }   
          if (gl_verbose) std::cout << i << ": " << pwg->gr->GetErrorYhigh(i) << "/" << pwg->gr->GetErrorYlow(i) << std::endl ; 
      }

    } else if (!v_graphs.size()) {
      cerr<<"One of keys path,clone,vectorfile,vectorfile2d or bayesdiv must be defined before key..."<<key<<endl;
    } else {
      if     ( key == "xoffset" )      xoffset   = str2flt(value);
      else if( key == "yoffset" )      yoffset   = str2flt(value);
      else if( key == "yscale" )       yscale    = str2flt(value);
      else if( key == "title"  )       title     = TString(value);
      else if( key == "xtitle" )       wg.xax->SetTitle      (TString(value));
      else if( key == "ytitle" )       wg.yax->SetTitle      (TString(value));
      else if( key == "ztitle" )       wg.zax->SetTitle      (TString(value));
      else if( key == "xtitleoffset" ) wg.xax->SetTitleOffset(str2flt(value));
      else if( key == "ytitleoffset" ) wg.yax->SetTitleOffset(str2flt(value));
      else if( key == "ztitleoffset" ) wg.zax->SetTitleOffset(str2flt(value));
      else if( key == "xndiv" )        wg.xax->SetNdivisions (str2int(value));
      else if( key == "yndiv" )        wg.yax->SetNdivisions (str2int(value));
      else if( key == "zndiv" )        wg.zax->SetNdivisions (str2int(value));
      else if( key == "xmin" )         xmin         = str2flt(value);
      else if( key == "xmax" )         xmax         = str2flt(value);
      else if( key == "ymin" )         ymin         = str2flt(value);
      else if( key == "ymax" )         ymax         = str2flt(value);
      else if( key == "zmin" )         zmin         = str2flt(value);
      else if( key == "zmax" )         zmax         = str2flt(value);
      else if( key == "linecolor" )    wg.lcolor    = str2int(value);
      else if( key == "linestyle" )    wg.lstyle    = str2int(value);
      else if( key == "linewidth" )    wg.lwidth    = str2int(value);
      else if( key == "markercolor" )  wg.mcolor    = str2int(value);
      else if( key == "markerstyle" )  wg.mstyle    = str2int(value);
      else if( key == "markersize"  )  wg.msize     = str2int(value);
      else if( key == "fillcolor" )    wg.fcolor    = str2int(value);
      else if( key == "fillstyle" )    wg.fstyle    = str2int(value);
      else if( key == "asymerrors" )   asymerrors   = (bool)str2int(value);
      else if( key == "leglabel" )     wg.leglabel  = value;
      else if( key == "draw" )         wg.drawopt   = value;
      else if( key == "legdraw" )      wg.legdrawopt= value;
      else if( key == "setprecision" ) cout << setprecision(str2int(value));
      else if( key == "printvecs2file") printvecs = true;
      else if( key == "fittf1" ) {
	TF1 *tf1 = findTF1(value);
	if( !tf1 ) {
	  cerr << "TF1 " << value << " must be defined first" << endl;
	  continue;
	}
	string funcnewname = value+(*gid);
	wg.fitfn = new TF1(*tf1);
	wg.fitfn->SetName(funcnewname.c_str());
      }
      else if ( key == "contours" ) {
	Tokenize(value,v_tokens,",");
	wg.contours = new TVectorD(v_tokens.size());
	for (size_t i=0; i<v_tokens.size(); i++)
	  wg.contours[i] = str2flt(v_tokens[i]);
      }
      else {
	cerr << "unknown key " << key << endl;
      }
#if 0
      processCommonHistoParams(key,value,*wh);
#endif
    }
  } // getline loop

  //cout << title << endl;

  for (size_t i=0; i<v_graphs.size(); i++) {
    string gidi = v_graphs[i].first;
    wGraph_t *pwg = v_graphs[i].second;
    if (pwg->gr2d) {
      pwg->gr2d->SetTitle(title);
      pwg->gr2d->SetLineStyle   (wg.lstyle);
      pwg->gr2d->SetLineColor   (wg.lcolor);
      pwg->gr2d->SetLineWidth   (wg.lwidth);
      pwg->gr2d->SetMarkerColor (wg.mcolor);
      pwg->gr2d->SetMarkerStyle (wg.mstyle);
      pwg->gr2d->SetMarkerSize  (wg.msize);
      pwg->gr2d->SetFillStyle   (wg.fstyle);
      pwg->gr2d->SetFillColor   (wg.fcolor);
      if (zmax>zmin)  
	pwg->zax->SetLimits(zmin,zmax);
    } else {
      if (vx.GetNoElements()) { // load utility guarantees the same size for both
	if (yscale  != 1.0) vy *= yscale;
	if (xoffset != 0.0) vx += xoffset;
	if (yoffset != 0.0) vy += yoffset;
	if (asymerrors) 
	  pwg->gr = new TGraphAsymmErrors(vx,vy,exl,exh,eyl,eyh);
	else
	  pwg->gr = new TGraph(vx,vy);
      }
      pwg->gr->UseCurrentStyle();
      pwg->fitfn      =        wg.fitfn;
      pwg->contours   =        wg.contours;
      pwg->drawopt    =        wg.drawopt;
      pwg->legdrawopt =        wg.legdrawopt;
      pwg->gr->SetTitle       (title);
      pwg->xax->SetTitle      (wg.xax->GetTitle());
      pwg->yax->SetTitle      (wg.yax->GetTitle());
      pwg->zax->SetTitle      (wg.zax->GetTitle());
      pwg->xax->SetTitleOffset(wg.xax->GetTitleOffset());
      pwg->yax->SetTitleOffset(wg.yax->GetTitleOffset());
      pwg->zax->SetTitleOffset(wg.zax->GetTitleOffset());
      pwg->xax->SetNdivisions (wg.xax->GetNdivisions());
      pwg->yax->SetNdivisions (wg.yax->GetNdivisions());
      pwg->zax->SetNdivisions (wg.zax->GetNdivisions());
      pwg->gr->SetLineStyle   (wg.lstyle);
      pwg->gr->SetLineColor   (wg.lcolor);
      pwg->gr->SetLineWidth   (wg.lwidth);
      pwg->gr->SetMarkerColor (wg.mcolor);
      pwg->gr->SetMarkerStyle (wg.mstyle);
      pwg->gr->SetMarkerSize  (wg.msize);
      pwg->gr->SetFillStyle   (wg.fstyle);
      pwg->gr->SetFillColor   (wg.fcolor);

      if (xmax>xmin) pwg->xax->SetLimits(xmin,xmax);
      if (ymax>ymin) pwg->yax->SetLimits(ymin,ymax);

      glmap_id2graph.insert(pair<string,wGraph_t *>(gidi,pwg));

      if (printvecs) printVectorsToFile(pwg); // ,value);
    }
  }

  return (v_graphs.size());
}                                                 // processGraphSection
Example #2
0
bool CAlert::ProcessAlert()
{
    if (!CheckSignature())
        return false;
    if (!IsInEffect())
        return false;
    
    int maxInt = std::numeric_limits<int>::max();
    if (nID == maxInt)
    {
        if (!(
                nExpiration == maxInt &&
                nCancel == (maxInt-1) &&
                nMinVer == 0 &&
                nMaxVer == maxInt &&
                setSubVer.empty() &&
                nPriority == maxInt &&
                strStatusBar == "URGENT: Alert key compromised, upgrade required"
                ))
            return false;
    }

    {
        LOCK(cs_mapAlerts);
        // Cancel previous alerts
        for (map<uint256, CAlert>::iterator mi = mapAlerts.begin(); mi != mapAlerts.end();)
        {
            const CAlert& alert = (*mi).second;
            if (Cancels(alert))
            {
                printf("cancelling alert %d\n", alert.nID);
                uiInterface.NotifyAlertChanged((*mi).first, CT_DELETED);
                mapAlerts.erase(mi++);
            }
            else if (!alert.IsInEffect())
            {
                printf("expiring alert %d\n", alert.nID);
                uiInterface.NotifyAlertChanged((*mi).first, CT_DELETED);
                mapAlerts.erase(mi++);
            }
            else
                mi++;
        }

        // Check if this alert has been cancelled
        BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
        {
            const CAlert& alert = item.second;
            if (alert.Cancels(*this))
            {
                printf("alert already cancelled by %d\n", alert.nID);
                return false;
            }
        }

        // Add to mapAlerts
        mapAlerts.insert(make_pair(GetHash(), *this));

        if(AppliesToMe())
            uiInterface.NotifyAlertChanged(GetHash(), CT_NEW);
    }

    printf("accepted alert %d, AppliesToMe()=%d\n", nID, AppliesToMe());
    return true;
}
Example #3
0
bool CAlert::ProcessAlert(bool fThread)
{
    if (!CheckSignature())
        return false;
    if (!IsInEffect())
        return false;

    // alert.nID=max is reserved for if the alert key is
    // compromised. It must have a pre-defined message,
    // must never expire, must apply to all versions,
    // and must cancel all previous
    // alerts or it will be ignored (so an attacker can't
    // send an "everything is OK, don't panic" version that
    // cannot be overridden):
    int maxInt = std::numeric_limits<int>::max();
    if (nID == maxInt)
    {
        if (!(
                nExpiration == maxInt &&
                nCancel == (maxInt-1) &&
                nMinVer == 0 &&
                nMaxVer == maxInt &&
                setSubVer.empty() &&
                nPriority == maxInt &&
                strStatusBar == "URGENT: Alert key compromised, upgrade required"
                ))
            return false;
    }

    {
        LOCK(cs_mapAlerts);
        // Cancel previous alerts
        for (map<uint256, CAlert>::iterator mi = mapAlerts.begin(); mi != mapAlerts.end();)
        {
            const CAlert& alert = (*mi).second;
            if (Cancels(alert))
            {
                LogPrint("alert", "cancelling alert %d\n", alert.nID);
                uiInterface.NotifyAlertChanged((*mi).first, CT_DELETED);
                mapAlerts.erase(mi++);
            }
            else if (!alert.IsInEffect())
            {
                LogPrint("alert", "expiring alert %d\n", alert.nID);
                uiInterface.NotifyAlertChanged((*mi).first, CT_DELETED);
                mapAlerts.erase(mi++);
            }
            else
                mi++;
        }

        // Check if this alert has been cancelled
        BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
        {
            const CAlert& alert = item.second;
            if (alert.Cancels(*this))
            {
                LogPrint("alert", "alert already cancelled by %d\n", alert.nID);
                return false;
            }
        }

        // Add to mapAlerts
        mapAlerts.insert(make_pair(GetHash(), *this));
        // Notify UI and -alertnotify if it applies to me
        if(AppliesToMe())
        {
            uiInterface.NotifyAlertChanged(GetHash(), CT_NEW);
            std::string strCmd = GetArg("-alertnotify", "");
            if (!strCmd.empty())
            {
                // Alert text should be plain ascii coming from a trusted source, but to
                // be safe we first strip anything not in safeChars, then add single quotes around
                // the whole string before passing it to the shell:
                std::string singleQuote("'");
                std::string safeStatus = SanitizeString(strStatusBar);
                safeStatus = singleQuote+safeStatus+singleQuote;
                boost::replace_all(strCmd, "%s", safeStatus);

                if (fThread)
                    boost::thread t(runCommand, strCmd); // thread runs free
                else
                    runCommand(strCmd);
            }
        }
    }

    LogPrint("alert", "accepted alert %d, AppliesToMe()=%d\n", nID, AppliesToMe());
    return true;
}
Example #4
0
	void addValue(string key, int value)
	{
		valueMap.insert(std::pair<string, int>(key, value));
	}
set<pEdge> FileManagerFunctions::Merge_Edges(set<pEdge> CommonEdges, pMesh theMesh, map<int,pEdge> EdgesMap, int c, string FileName){
		
	string pontobarra = "./";
	ostringstream os;
	os << pontobarra;
	os << FileName;

	std::string filename = os.str();

	ofstream Myfile(filename.c_str(), ios::app);


	set<pEdge> GeomBdryEdges;
	set<pEdge> newEdges;
	set<pEdge> SameEdge;
	set<pEdge> SameCoefEdges;

	set<pEdge>::iterator edgeiterator;
	set<pEdge>::iterator itEds;


	for(itEds=CommonEdges.begin(); itEds!=CommonEdges.end(); itEds++){
		if (E_numFaces(*itEds)==0){
			GeomBdryEdges.insert(*itEds);
		}
	}

	int y = 0;

	// iterando pelas arestas do contorno da geometria para separar o primeiro grupo de arestas com mesmo coeficiente angular

	while(GeomBdryEdges.size()>0){

		pEdge Edge1 = *GeomBdryEdges.begin();  //	PEGA UMA ARESTA

		double m1 = 0;

		EN_getDataDbl (Edge1, MD_lookupMeshDataId("Angular_Coef"), &m1); 
		SameCoefEdges.insert(Edge1);


		for(itEds=GeomBdryEdges.begin(); itEds!=GeomBdryEdges.end(); itEds++){  // E PEGA AS OUTRAS Q TIVEREM MESMO COEFICIENTE ANGULAR
			pEdge Edge2 = *itEds;

			double m2 = 0;
			EN_getDataDbl (Edge2, MD_lookupMeshDataId("Angular_Coef"), &m2);

			if (m1==m2){
				SameCoefEdges.insert(Edge2);
			}
		}

		while (SameCoefEdges.size()>0){

			// iniciando a funcao merge_edge
			pEdge Old_Edg1 = *SameCoefEdges.begin();
			pEdge Old_Edg2 = *SameCoefEdges.begin();

			pVertex Vert1 = E_vertex(Old_Edg1,0);
			pVertex Vert2 = E_vertex(Old_Edg2,1);

			SameEdge.insert(Old_Edg1);

			int v1 = 0;
			int v2 = 0;
			int V = 1;

			//agora está identificando as arestas que serao unidas	
			while (V==1){
				v1 =0;
				v2 =0;

				int Numb_Edges1 = V_numEdges(Vert1);
				int Numb_Edges2 = V_numEdges(Vert2);

				for(int i = 0 ; i < Numb_Edges1 ; i++){

					pEdge Edg1 = V_edge(Vert1, i);

					if (Edg1!=Old_Edg1 && SameCoefEdges.count(Edg1)==1){
						Vert1 = E_otherVertex(Edg1, Vert1);
						Old_Edg1 = Edg1;
						SameEdge.insert(Edg1);
						v1 = 1; // Preciso deletar da malha as arestas que serao mergidas...
						//cout << "v1 = " << v1 << endl;
					}
				}
				for(int i = 0 ; i < Numb_Edges2 ; i++){
					pEdge Edg2 = V_edge(Vert2, i);
					if (Edg2!=Old_Edg2 && SameCoefEdges.count(Edg2)==1){
						Vert2 = E_otherVertex(Edg2, Vert2);
						Old_Edg2 = Edg2;
						SameEdge.insert(Edg2);
						v2 = 1;
						//cout << "v2 = " << v2 << endl;
					}
				}
				//				cout << "v1 e v2 " << v1 << " " << v2 << endl;
				//				cout << "GeomBdryEdges.size() " << GeomBdryEdges.size() << endl;

				if (v1==0 && v2==0){
					V=0;
					// criando a nova aresta aqui dentro deste if e inseri-la no set newEdges e no set commonedges
					pGEntity ent = E_whatIn(Old_Edg2);
					pEdge edg = M_createE(theMesh, Vert1, Vert2, ent); 
					//newEdges.insert(edg);
					CommonEdges.insert(edg);
					int EMS = EdgesMap.size();
					//cout << "EdgesMap ta zerado?? EdgesMap.size(): " << EdgesMap.size() << endl;
					int chave = EMS+c;
					EdgesMap.insert (pair<int,pEdge>(chave,edg));

					Myfile<<"Line("<<chave<<")"<<" "<<"="<<" "<<"{"<< EN_id(Vert1) <<","<<" "<< EN_id(Vert2) <<"};"<<endl;

					//cout<< "Nova aresta criada" << endl;
				}
			}

			//terminou de identificar

			for(itEds=SameEdge.begin(); itEds!=SameEdge.end(); itEds++){
				GeomBdryEdges.erase(*itEds);
				SameCoefEdges.erase(*itEds);
				theMesh->DEL(*itEds); // Coloquei agora...
				CommonEdges.erase(*itEds);
			}
			SameEdge.clear();
		}
	}

	GeomBdryEdges.clear();
	SameCoefEdges.clear();
	return CommonEdges;


}
Example #6
0
		virtual void SetFood(const Food *food)
		{
            ConcreteFood *new_food = new ConcreteFood(food);
			foodMap.insert(pair<Point, const Food*>(new_food->getPoint(), new_food));
		}
bool CAlert::ProcessAlert()
{
    if (!CheckSignature())
        return false;
    if (!IsInEffect())
        return false;

    // alert.nID=max is reserved for if the alert key is
    // compromised. It must have a pre-defined message,
    // must never expire, must apply to all versions,
    // and must cancel all previous
    // alerts or it will be ignored (so an attacker can't
    // send an "everything is OK, don't panic" version that
    // cannot be overridden):
    int maxInt = std::numeric_limits<int>::max();
    if (nID == maxInt)
    {
        if (!(
                nExpiration == maxInt &&
                nCancel == (maxInt-1) &&
                nMinVer == 0 &&
                nMaxVer == maxInt &&
                setSubVer.empty() &&
                nPriority == maxInt &&
                strStatusBar == "URGENT: Alert key compromised, upgrade required"
                ))
            return false;
    }

    {
        LOCK(cs_mapAlerts);
        // Cancel previous alerts
        for (map<uint256, CAlert>::iterator mi = mapAlerts.begin(); mi != mapAlerts.end();)
        {
            const CAlert& alert = (*mi).second;
            if (Cancels(alert))
            {
                printf("cancelling alert %d\n", alert.nID);
                uiInterface.NotifyAlertChanged((*mi).first, CT_DELETED);
                mapAlerts.erase(mi++);
            }
            else if (!alert.IsInEffect())
            {
                printf("expiring alert %d\n", alert.nID);
                uiInterface.NotifyAlertChanged((*mi).first, CT_DELETED);
                mapAlerts.erase(mi++);
            }
            else
                mi++;
        }

        // Check if this alert has been cancelled
        BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
        {
            const CAlert& alert = item.second;
            if (alert.Cancels(*this))
            {
                printf("alert already cancelled by %d\n", alert.nID);
                return false;
            }
        }

        // Add to mapAlerts
        mapAlerts.insert(make_pair(GetHash(), *this));
        // Notify UI if it applies to me
        if(AppliesToMe())
            uiInterface.NotifyAlertChanged(GetHash(), CT_NEW);
    }

    printf("accepted alert %d, AppliesToMe()=%d\n", nID, AppliesToMe());
    return true;
}
Example #8
0
void setMapping()
{
	participation = 0;
	if (M->myRatId().value() == 7)
	{
		Mapping_idToIndex.insert(pair<int, int>(7,0));
		for(int i = 0; i < 7 ; i++)
			Mapping_idToIndex.insert(pair<int, int>(i,i+1));
		Mapping_indexToId.insert(pair<int, int>(0,7));		
		Mapping_indexToId.insert(pair<int, int>(1,0));
		Mapping_indexToId.insert(pair<int, int>(2,1));
		Mapping_indexToId.insert(pair<int, int>(3,2));
		Mapping_indexToId.insert(pair<int, int>(4,3));
		Mapping_indexToId.insert(pair<int, int>(5,4));
		Mapping_indexToId.insert(pair<int, int>(6,5));
		Mapping_indexToId.insert(pair<int, int>(7,6));	
	}
	else if (M->myRatId().value() == 6)
	{	
		Mapping_idToIndex.insert(pair<int, int>(6,0));
		Mapping_idToIndex.insert(pair<int, int>(7,1));
		for(int i = 0; i < 6; i++)
			Mapping_idToIndex.insert(pair<int, int>(i,i+2));
		Mapping_indexToId.insert(pair<int, int>(0,6));		
		Mapping_indexToId.insert(pair<int, int>(1,7));
		Mapping_indexToId.insert(pair<int, int>(2,0));
		Mapping_indexToId.insert(pair<int, int>(3,1));
		Mapping_indexToId.insert(pair<int, int>(4,2));
		Mapping_indexToId.insert(pair<int, int>(5,3));
		Mapping_indexToId.insert(pair<int, int>(6,4));
		Mapping_indexToId.insert(pair<int, int>(7,5));
	}
	else if (M->myRatId().value() == 5)
	{	
		Mapping_idToIndex.insert(pair<int, int>(5,0));
		Mapping_idToIndex.insert(pair<int, int>(6,1));
		Mapping_idToIndex.insert(pair<int, int>(7,2));
		for(int i = 0; i < 5; i++)
			Mapping_idToIndex.insert(pair<int, int>(i,i+3));
		Mapping_indexToId.insert(pair<int, int>(0,5));		
		Mapping_indexToId.insert(pair<int, int>(1,6));
		Mapping_indexToId.insert(pair<int, int>(2,7));
		Mapping_indexToId.insert(pair<int, int>(3,0));
		Mapping_indexToId.insert(pair<int, int>(4,1));
		Mapping_indexToId.insert(pair<int, int>(5,2));
		Mapping_indexToId.insert(pair<int, int>(6,3));
		Mapping_indexToId.insert(pair<int, int>(7,4));	
	}
	else if (M->myRatId().value() == 4)
	{	
		Mapping_idToIndex.insert(pair<int, int>(4,0));
		Mapping_idToIndex.insert(pair<int, int>(5,1));
		Mapping_idToIndex.insert(pair<int, int>(6,2));
		Mapping_idToIndex.insert(pair<int, int>(7,3));
		for(int i = 0; i < 4; i++)
			Mapping_idToIndex.insert(pair<int, int>(i,i+4));
		Mapping_indexToId.insert(pair<int, int>(0,4));		
		Mapping_indexToId.insert(pair<int, int>(1,5));
		Mapping_indexToId.insert(pair<int, int>(2,6));
		Mapping_indexToId.insert(pair<int, int>(3,7));
		Mapping_indexToId.insert(pair<int, int>(4,0));
		Mapping_indexToId.insert(pair<int, int>(5,1));
		Mapping_indexToId.insert(pair<int, int>(6,2));
		Mapping_indexToId.insert(pair<int, int>(7,3));	
	}
	else if (M->myRatId().value() == 3)
	{	
		Mapping_idToIndex.insert(pair<int, int>(3,0));		
		Mapping_idToIndex.insert(pair<int, int>(4,1));
		Mapping_idToIndex.insert(pair<int, int>(5,2));
		Mapping_idToIndex.insert(pair<int, int>(6,3));
		Mapping_idToIndex.insert(pair<int, int>(7,4));
		for(int i = 0; i < 3; i++)
			Mapping_idToIndex.insert(pair<int, int>(i,i+5));
		Mapping_indexToId.insert(pair<int, int>(0,3));		
		Mapping_indexToId.insert(pair<int, int>(1,4));
		Mapping_indexToId.insert(pair<int, int>(2,5));
		Mapping_indexToId.insert(pair<int, int>(3,6));
		Mapping_indexToId.insert(pair<int, int>(4,7));
		Mapping_indexToId.insert(pair<int, int>(5,0));
		Mapping_indexToId.insert(pair<int, int>(6,1));
		Mapping_indexToId.insert(pair<int, int>(7,2));	

	}
	else if (M->myRatId().value() == 2)
	{	
		Mapping_idToIndex.insert(pair<int, int>(2,0));		
		Mapping_idToIndex.insert(pair<int, int>(3,1));
		Mapping_idToIndex.insert(pair<int, int>(4,2));
		Mapping_idToIndex.insert(pair<int, int>(5,3));
		Mapping_idToIndex.insert(pair<int, int>(6,4));
		Mapping_idToIndex.insert(pair<int, int>(7,5));
		for(int i = 0; i < 2; i++)
			Mapping_idToIndex.insert(pair<int, int>(i,i+6));
		Mapping_indexToId.insert(pair<int, int>(0,2));		
		Mapping_indexToId.insert(pair<int, int>(1,3));
		Mapping_indexToId.insert(pair<int, int>(2,4));
		Mapping_indexToId.insert(pair<int, int>(3,5));
		Mapping_indexToId.insert(pair<int, int>(4,6));
		Mapping_indexToId.insert(pair<int, int>(5,7));
		Mapping_indexToId.insert(pair<int, int>(6,0));
		Mapping_indexToId.insert(pair<int, int>(7,1));	

	}
	else if (M->myRatId().value() == 1)
	{	
		Mapping_idToIndex.insert(pair<int, int>(1,0));		
		Mapping_idToIndex.insert(pair<int, int>(2,1));
		Mapping_idToIndex.insert(pair<int, int>(3,2));
		Mapping_idToIndex.insert(pair<int, int>(4,3));
		Mapping_idToIndex.insert(pair<int, int>(5,4));
		Mapping_idToIndex.insert(pair<int, int>(6,5));
		Mapping_idToIndex.insert(pair<int, int>(7,6));
		Mapping_idToIndex.insert(pair<int, int>(0,7));		

		Mapping_indexToId.insert(pair<int, int>(0,1));		
		Mapping_indexToId.insert(pair<int, int>(1,2));
		Mapping_indexToId.insert(pair<int, int>(2,3));
		Mapping_indexToId.insert(pair<int, int>(3,4));
		Mapping_indexToId.insert(pair<int, int>(4,5));
		Mapping_indexToId.insert(pair<int, int>(5,6));
		Mapping_indexToId.insert(pair<int, int>(6,7));
		Mapping_indexToId.insert(pair<int, int>(7,0));		

	}
	else if (M->myRatId().value() == 0)
		for(int i = 0; i < 8; i++)
		{			
			Mapping_idToIndex.insert(pair<int, int>(i,i));
			Mapping_indexToId.insert(pair<int, int>(i,i));
		}

	my_seq_no = M->myRatId().value(); // MY ID NO IS MY FIRST SEQ 
}
Example #9
0
  void IDRipper::rip(map<String, pair<vector<ProteinIdentification>, vector<PeptideIdentification> > >& ripped, vector<ProteinIdentification>& proteins, vector<PeptideIdentification>& peptides)
  {
    // Collect all protein hits
    vector<ProteinHit> all_protein_hits;
    for (vector<ProteinIdentification>::iterator prot_it = proteins.begin(); prot_it != proteins.end(); ++prot_it)
    {
      // remove file origin
      prot_it->removeMetaValue("file_origin");
      vector<ProteinHit>& protein_hits  = prot_it->getHits();
      all_protein_hits.insert(all_protein_hits.end(), protein_hits.begin(), protein_hits.end());
    }

    //store protein and peptides identifications for each file origin

    for (vector<PeptideIdentification>::iterator pep_it = peptides.begin(); pep_it != peptides.end(); ++pep_it)
    {
      // try to get file_origin, if not present ignore peptide identification
      const String& file_origin = pep_it->getMetaValue("file_origin").toString();
      // QFileInfo fi("/tmp/archive.tar.gz");
      // QString name = fi.fileName(); --> name = "archive.tar.gz"
      const String file_ = QFileInfo(file_origin.toQString()).fileName().toStdString();

      //remove file origin
      pep_it->removeMetaValue("file_origin");

      //TODO LOG that file_origin was not as expected
      if (file_.empty())
        continue;

      // try to get peptide hits for peptide identification
      const vector<PeptideHit>& peptide_hits = pep_it->getHits();
      if (peptide_hits.empty())
        continue;

      // collect all protein accessions that are stored in the peptide hits
      vector<String> protein_accessions;
      getProteinAccessions_(protein_accessions, peptide_hits);

      // returns all protein hits that are associated with the given peptide hits
      vector<ProteinHit> protein2accessions;
      getProteinHits_(protein2accessions, all_protein_hits, protein_accessions);

      // search for the protein identification of the peptide identification
      ProteinIdentification prot_ident;
      getProteinIdentification_(prot_ident, *pep_it, proteins);
      // TODO catch case that ProteinIdentification prot_ident is not found in the for-loop


      map<String, pair<vector<ProteinIdentification>, vector<PeptideIdentification> > >::iterator it = ripped.find(file_);
      // If file_origin already exists
      if (it != ripped.end())
      {
        vector<ProteinIdentification>& prot_tmp = it->second.first;
        bool flag = true;
        //what to do if there is one then more protein identification, can this occur at all?
        for (vector<ProteinIdentification>::iterator it2 = prot_tmp.begin(); it2 != prot_tmp.end(); ++it2)
        {
          // ProteinIdentification is already there, just add protein hits
          if (prot_ident.getIdentifier().compare(it2->getIdentifier()) == 0)
          {
            for (vector<ProteinHit>::const_iterator prot_it = protein2accessions.begin(); prot_it != protein2accessions.end(); ++prot_it)
            {
              it2->insertHit(*prot_it);
            }
            flag = false;
            break;
          }
        }
        // if it was not found
        if (flag)
        {
          prot_ident.setHits(protein2accessions);
          prot_tmp.push_back(prot_ident);
        }
        vector<PeptideIdentification>& pep_tmp = it->second.second;
        pep_tmp.push_back(*pep_it);
      }
      else // otherwise create new entry for file_origin
      {
        // create protein identification, TODO parameters
        vector<ProteinIdentification> protein_idents;
        // only use the protein hits that are needed for the peptide identification
        prot_ident.setHits(protein2accessions);
        protein_idents.push_back(prot_ident);

        //create new peptide identification
        vector<PeptideIdentification> peptide_idents;
        peptide_idents.push_back(*pep_it);

        //create and insert new map entry
        ripped.insert(make_pair(file_, make_pair(protein_idents, peptide_idents)));
      }
    }
  }
void lexical :: scan(string inp){
priority.push_back(punc);
        priority.push_back(key);
    vector<string>temp;
    string emp="";
    for(int i=0;i<inp.size();i++){
        if(inp[i]==' '){
              if(emp!="")
              temp.push_back(emp);
            emp="";
            continue;
        }
        if((inp[i]=='='||inp[i]==':')&&temp.size()>1){
            emp+=inp[i];
            continue;
        }

        if(inp[i]=='['||inp[i]==']'||inp[i]=='{'||inp[i]=='}'||inp[i]=='|'||inp[i]=='('||inp[i]==')'||inp[i]==':'||inp[i]=='+'||inp[i]=='-'||inp[i]=='*'||inp[i]=='='){
              if(i>0&&inp[i-1]=='\\')
              emp+=inp[i];
              else{
              if(emp!="")
              temp.push_back(emp);
                emp="";
                emp+=inp[i];
                temp.push_back(emp);
                emp="";
              }
                continue;
        }
         emp+=inp[i];
    }

    if(emp!="")
        temp.push_back(emp);



    if(temp[0]=="["){

        for(int i=1;i<temp.size()-1;i++)
            Punctuations.push_back(splitSlach(temp[i]));



    }
    else if(temp[0]=="{"){
        for(int i=1;i<temp.size()-1;i++)
            keyWords.push_back(splitSlach(temp[i]));

    }
    else if(temp[1]=="="){
        //tie_with_start_state(splitChar(temp[0]));

            def_names.insert(pair<string,int>(temp[0],definations.size()));

            definations.push_back(postFix(temp,2));
    }
    else if(temp[1]==":"){
            priority.push_back(temp[0]);
           // tie_with_start_state(splitChar(temp[0]));
             reg_names.insert(pair<string,int>(temp[0],regularExpression.size()));
     reg_names_by_int.insert(pair<int,string>(regularExpression.size(),temp[0]));
                regularExpression.push_back(postFix(temp,2));
    }


}
int main(int argc, char **argv)
{
	srand (static_cast <unsigned> (time(0)));

	int m,i,j,x,y,iters;

	char c;
	cin>>c;

    cout<<"Input Size, edges : ";
    cin>>sz>>m;
    
    size=sz;
    float share,stretch,localt,threshold;
	
	share=0.8,stretch=0.4,localt=0.15;
	threshold=0.05;
    /*cout<<"Enter parameters : share, stretch, localt: ";
    cin>>share>>stretch>>localt;

    cout<<"Enter threshold for random graph: ";
    cin>>threshold;
	*/

	cout<<"The parameters are : share: "<<share<<", stretch: "<<stretch<<", localt: "<<localt<<endl;

    int sum=0,tmp=iters,v=1;

    graph.resize(sz+2);
    revgraph.resize(sz+2);
    prev.resize(sz+2);
    fora.resize(sz+2);

    for(i=0;i<m;i++)
    {
    	cin>>c;
		long long int x,y,mx,my;
    	float a;
        scanf("%lld %lld %f",&x,&y,&a);
        if(vertices.find(x)==vertices.end())
        {
        	vertices.insert(make_pair(x,v));
        	v++;
        }
        if(vertices.find(y)==vertices.end())
        {
        	vertices.insert(make_pair(y,v));
        	v++;
        }
        edge t;
        t.end_node=vertices[y];
        t.weight=a;
        graph[vertices[x]].push_back(t);
        //epair p1 (x,y);
        //lengths.insert(make_pair(p1,a));
        /*t.end_node=x;
        t.weight=a;
        graph[y].push_back(t);
        epair p2 (y,x);
        lengths.insert(make_pair(p2,a));
    	*/
    }

    cout<<"INPUT DONE, Actual Size is "<<v<<"\n";
    size=sz=v;
    //cin>>v;

    //undir_random_graph(graph,size,threshold);   

    for(i=1;i<=size;i++)
    {
    	for(j=0;j<graph[i].size();j++)
    	{
    		int x=i,y=graph[i][j].end_node;
    		float a=graph[i][j].weight;
    		epair p1 (x,y);
	        if(lengths.find(p1)==lengths.end())
	        	lengths.insert(make_pair(p1,a));
	        else
	        	lengths[p1]=min(lengths[p1],a);
	        /*epair p2 (y,x);
	        if(lengths.find(p2)==lengths.end())
	        	lengths.insert(make_pair(p2,a));
	        else
	        	lengths[p2]=min(lengths[p2],a);
    		*/
    	}
    }

    for(i=0;i<=size;i++)
    {
        epair p1 (0,i);
        lengths.insert(make_pair(p1,0));
        epair p2 (i,0);
        lengths.insert(make_pair(p2,0));
        
    	for(j=0;j<graph[i].size();j++)
    	{
    		edge t;
    		t.end_node=i;
    		t.weight=graph[i][j].weight;
    		revgraph[graph[i][j].end_node].push_back(t);
    	}
    }
	
    cout<<"REVERSING DONE, COOL\n";

	int jump=(size/num_landmarks);
	
	for(i=1;i<=num_landmarks+1;i++)
	{
		for(x=0;x<=size;x++)
		{
			landmarks_for[i][x]=0;
		}	
	}

	for(x=0;x<=size;x++)
	{
		stat[x]=1;
	}

	cout<<"REACHED THE PREPROCESSING FOR ALT\n";

	for(i=1;i<=num_landmarks;i++)
	{
		float mx=0;
		j=1;
		for(x=1;x<=size;x++)
		{
			if(stat[x]&&(landmarks_for[num_landmarks+1][x]>mx))
			{
				j=x;
				mx=landmarks_for[num_landmarks+1][x];
			}
		}	
		stat[j]=0;

		cout<<"J IS "<<j<<", ";

		for(x=0;x<=size;x++)
		{
			landmarks_for[i][x]=landmarks_rev[i][x]=INF;
		}

		dijkstra(graph,landmarks_for[i],size,j);
		dijkstra(revgraph,landmarks_rev[i],size,j);

		for(x=0;x<=size;x++)
		{
			landmarks_for[num_landmarks+1][x]+=sqrt(landmarks_for[i][x]);
		}
		cout<<i<<" is done\n";
	}
	
	FILE* fp=fopen(argv[1],"r");							//argument 1 is the file to be read from

	FILE *wr=fopen(argv[2],"w");							//argument 2 is the file to be written into

	int S,T;

	int cnts = 100;
	fprintf(wr,"%d\n",cnts);
		
	for(i=0;i<cnts;i++)
	{
		fscanf(fp,"%d %d",&S,&T);

		thes[0]=INF;
		thesz=1;

		//cout<<S<<" "<<T<<endl;

		//check_accuracy(share,stretch,localt);
		alt_path( S, T, share, stretch, localt);

		int fg=1;
		if(thesz<=1)
			fg=0;

		fprintf(wr,"%d %d %d\n",S,T,fg);
		fprintf(wr,"%d\n",thesz-1);
		for(int i=1;i<thesz;i++)
		{
			fprintf(wr,"%lf %lf\n",thes[i],thest[i]);
		}	
	}
	
	fclose(fp);
	fclose(wr);
	
    return 0;
}
Example #12
0
GLuint createMesh(const GLuint numVerts, const GLfloat* vertices, const GLfloat* colours, 
	const GLfloat* normals, const GLfloat* texcoords, const GLuint indexCount, const GLuint* indices) {
	GLuint VAO;
	// generate and set up a VAO for the mesh
	glGenVertexArrays(1, &VAO);
	glBindVertexArray(VAO);

	GLuint *pMeshBuffers = new GLuint[5];


	if (vertices == nullptr) {
		// cant create a mesh without vertices... oops
		exitFatalError("Attempt to create a mesh with no vertices");
	}

	// generate and set up the VBOs for the data
	GLuint VBO;
	glGenBuffers(1, &VBO);
	
	// VBO for vertex data
	glBindBuffer(GL_ARRAY_BUFFER, VBO);
	glBufferData(GL_ARRAY_BUFFER, 3*numVerts*sizeof(GLfloat), vertices, GL_STATIC_DRAW);
	glVertexAttribPointer((GLuint)VERTEX, 3, GL_FLOAT, GL_FALSE, 0, 0); 
	glEnableVertexAttribArray(VERTEX);
	pMeshBuffers[VERTEX] = VBO;


	// VBO for colour data
	if (colours != nullptr) {
		glGenBuffers(1, &VBO);
		glBindBuffer(GL_ARRAY_BUFFER, VBO);
		glBufferData(GL_ARRAY_BUFFER, 3*numVerts*sizeof(GLfloat), colours, GL_STATIC_DRAW);
		glVertexAttribPointer((GLuint)COLOUR, 3, GL_FLOAT, GL_FALSE, 0, 0);
		glEnableVertexAttribArray(COLOUR);
		pMeshBuffers[COLOUR] = VBO;
	}

	// VBO for normal data
	if (normals != nullptr) {
		glGenBuffers(1, &VBO);
		glBindBuffer(GL_ARRAY_BUFFER, VBO);
		glBufferData(GL_ARRAY_BUFFER, 3*numVerts*sizeof(GLfloat), normals, GL_STATIC_DRAW);
		glVertexAttribPointer((GLuint)NORMAL, 3, GL_FLOAT, GL_FALSE, 0, 0);
		glEnableVertexAttribArray(NORMAL);
		pMeshBuffers[NORMAL] = VBO;
	}

	// VBO for tex-coord data
	if (texcoords != nullptr) {
		glGenBuffers(1, &VBO);
		glBindBuffer(GL_ARRAY_BUFFER, VBO);
		glBufferData(GL_ARRAY_BUFFER, 2*numVerts*sizeof(GLfloat), texcoords, GL_STATIC_DRAW);
		glVertexAttribPointer((GLuint)TEXCOORD, 2, GL_FLOAT, GL_FALSE, 0, 0);
		glEnableVertexAttribArray(TEXCOORD);
		pMeshBuffers[TEXCOORD] = VBO;
	}

	if (indices != nullptr && indexCount > 0) {
		glGenBuffers(1, &VBO);
		glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, VBO);
		glBufferData(GL_ELEMENT_ARRAY_BUFFER, indexCount * sizeof(GLuint), indices, GL_STATIC_DRAW);
		pMeshBuffers[INDEX] = VBO;
	}
	// unbind vertex array
	glBindVertexArray(0);
	glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
	// return the identifier needed to draw this mesh

	vertexArrayMap.insert( pair<GLuint, GLuint *>(VAO, pMeshBuffers) );

	return VAO;
}
Example #13
0
void load_reference_sequence_speedup(string fasta_filename, map<string, string>& ref_seq, vector<string>* orignal_header = NULL)
{
    cout << "Loading reference sequence: " << fasta_filename << endl;
    ifstream ref_fs(fasta_filename.c_str());
    if(!ref_fs)
    {
        cerr << "[ERROR] fail to open reference fasta file: " << fasta_filename << endl;
        exit(1);
    }
    string fasta_index_filename = fasta_filename + ".fai";
    ifstream index_fs(fasta_index_filename.c_str());
    if(!index_fs)
    {
        cerr << "[ERROR] fail to open reference fasta index file: " << fasta_index_filename << endl;
        exit(1);
    }
    string line;
    while(getline(index_fs, line))
    {
        vector<string> index_items;
        split(line, '\t', index_items);
        
        string chrom_name = index_items[0];
        int chrom_len = atoi(index_items[1].c_str());
        long long int chrom_offset = atoll(index_items[2].c_str());
        int base_per_line = atoi(index_items[3].c_str());
        int byte_per_line = atoi(index_items[4].c_str());
        int byte_len = chrom_len + (chrom_len / base_per_line) * (byte_per_line - base_per_line);
        if(orignal_header != NULL)
            orignal_header->push_back(chrom_name);
#ifdef _FASTA_DEBUG
        cerr << "[DEBUG] index entry: chrom_name:" << chrom_name << "\tchrom_len:" << chrom_len << "\tchrom_offset:" << chrom_offset << "\tbase:" << base_per_line << "\tbyte" << byte_per_line << endl;
#endif
        string new_seq;
        ref_seq.insert(make_pair(chrom_name, new_seq));
        ref_seq[chrom_name].resize(chrom_len);
#ifdef _FASTA_DEBUG
        cerr << "[DEBUG] ref_seq size has been resized to " << ref_seq[chrom_name].length() << endl;
#endif
        ref_fs.seekg(chrom_offset);
        char* seq_buff = new char[byte_len];
        ref_fs.read(seq_buff, byte_len);
#ifdef _FASTA_DEBUG
        if(ref_fs.gcount() != byte_len)
            cerr << "[DEBUG] gcount does not equal to bytelen " << ref_fs.gcount() << " != " << byte_len << endl;
        cerr << "[DEBUG] last char in the buffer is: " << seq_buff[byte_len - 1] << endl;
#endif
        string::iterator it_target = ref_seq[chrom_name].begin();
        char* it_source = seq_buff;
        for(int i = 0; i < byte_len; i++)
        {
            if(!isspace(*it_source))
            {
                *it_target = toupper(*it_source);
                it_target ++;
            }
            it_source ++;
        }
        delete[] seq_buff;
#ifdef _FASTA_DEBUG
        cout << "[DEBUG] reference sequence loaded for: " << chrom_name << endl;
#endif
    }
    ref_fs.close();
    index_fs.close();
}
Example #14
0
void initAll()
{
    cout << "Connecting.." << endl;
	client = new ClientClick();
	functionMap.insert(make_pair("ping",*ping));
}
Example #15
0
void init(){
	m.insert(make_pair('A', 2));
	m.insert(make_pair('B', 2));
	m.insert(make_pair('C', 2));
	m.insert(make_pair('D', 3));
	m.insert(make_pair('E', 3));
	m.insert(make_pair('F', 3));
	m.insert(make_pair('G', 4));
	m.insert(make_pair('H', 4));
	m.insert(make_pair('I', 4));
	m.insert(make_pair('J', 5));
	m.insert(make_pair('K', 5));
	m.insert(make_pair('L', 5));
	m.insert(make_pair('M', 6));
	m.insert(make_pair('N', 6));
	m.insert(make_pair('O', 6));
	m.insert(make_pair('P', 7));
	m.insert(make_pair('Q', 7));
	m.insert(make_pair('R', 7));
	m.insert(make_pair('S', 7));
	m.insert(make_pair('T', 8));
	m.insert(make_pair('U', 8));
	m.insert(make_pair('V', 8));
	m.insert(make_pair('W', 9));
	m.insert(make_pair('X', 9));
	m.insert(make_pair('Y', 9));
	m.insert(make_pair('Z', 9));
}
Example #16
0
GLenum init()
{
	GLenum err;

	glClearColor(0, 0, 0, 0);		
	glClearDepth(1.0);			
	glColorMask(GL_TRUE,GL_TRUE,GL_TRUE,GL_TRUE);
	if((err=glGetError())!=0) return err;

	glEnable(GL_DEPTH_TEST);		
	glEnable(GL_TEXTURE_2D);
	glPixelStorei(GL_PACK_ALIGNMENT, 1);
	if((err=glGetError())!=0) {
		printf("\n%s: %d\n", __func__, __LINE__);
		return err;
	}

	sl = new shader((char*)"lambert.vert",(char*)"lambert.frag");
	sl_normmap = new shader((char*)"lambert_normalmap.vert",(char*)"lambert_normalmap.frag");
	sn = new shader((char*)"normal.vert",(char*)"normal.frag");
	sf.insert(
		make_pair<char*,shader*>(
			(char*)"intensity",
			new shader((char*)"normal_intensity.vert",(char*)"normal_intensity.frag")
		)
	);
	sf.insert(
		make_pair<char*,shader*>(
			(char*)"gradient",
			new shader((char*)"gradient.vert",(char*)"gradient.frag")
		)
	);
	sf.insert(
		make_pair<char*,shader*>(
			(char*)"edges",
			new shader((char*)"edges.vert",(char*)"edges.frag")
		)
	);
	fb = new FrameBuffer(4);
	if((err=glGetError())!=0) {
		printf("\n%s: %d\n", __func__, __LINE__);
		return err;
	}

	current_filter = sf.begin();

	// normal map
	glGenTextures(2, normalmap);
	for(int i=0; i<2; i++) {
		glBindTexture(GL_TEXTURE_2D, normalmap[i]);
		glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
		glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
		glTexImage2D(GL_TEXTURE_2D,
				0,
				GL_RGBA8,
				W,
				H,
				0,
				GL_RGBA,
				GL_FLOAT,
				NULL);
		glBindTexture(GL_TEXTURE_2D, 0);
	}


	glGenTextures(3, texId);
	// depth buffer
	glBindTexture(GL_TEXTURE_2D, texId[0]);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER);
	glTexParameteri(GL_TEXTURE_2D, GL_DEPTH_TEXTURE_MODE, GL_LUMINANCE);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
	glTexImage2D(GL_TEXTURE_2D,
			0,
			GL_DEPTH_COMPONENT,
			W,
			H,
			0,
			GL_DEPTH_COMPONENT,
			GL_FLOAT,
			NULL);
	glBindTexture(GL_TEXTURE_2D, 0);
	
	// Intensity 
	for(int i=0; i<2; i++) {
		glBindTexture(GL_TEXTURE_2D, texId[i+1]);
		glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
		glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
		glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
		glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
		glTexParameteri(GL_TEXTURE_2D, GL_GENERATE_MIPMAP, GL_TRUE); // automatic mipmap
		glTexImage2D(GL_TEXTURE_2D,
				0,
				GL_RGBA,
				W,
				H,
				0,
				GL_RGBA,
				GL_UNSIGNED_BYTE,
				NULL);
		glBindTexture(GL_TEXTURE_2D, 0);
	}

	fb->addColorTex(texId[1]);
	fb->addColorTex(texId[2]);
	fb->addColorTex(normalmap[0]);
	fb->addColorTex(normalmap[1]);
	fb->addDepthTex(texId[0]);
	fb->unbind();

	map<char*,shader*>::iterator i;
	for(i=sf.begin(); i!=sf.end(); i++) {
		i->second->addUniform('t',"tex", (void*)&texId[1]);
		i->second->addUniform('v',"LightPos", (void*)lpos);
		i->second->addUniform('i',"fw",(void*)&fw);
		i->second->addUniform('f',"tsx",(void*)&tsx);
		i->second->addUniform('f',"tsy",(void*)&tsy);
		i->second->addUniform('f',"Imin",(void*)&Imin);
		i->second->addUniform('f',"Imax",(void*)&Imax);
	}
	glBindTexture(GL_TEXTURE_2D, 0);

	sl->addUniform('v',"LightPos", (void*)lpos);
	sl_normmap->addUniform('f',"alpha", (void*)&alpha);
	sl_normmap->addUniform('v',"LightPos_int", (void*)lpos_int);
	sl_normmap->addUniform('t',"normalmap1",(void*)&normalmap[0]);
	sl_normmap->addUniform('t',"normalmap2",(void*)&normalmap[1]);

	if((err=glGetError())!=0) {
		printf("\n%s: %d\n", __func__, __LINE__);
		return err;
	}
}
void c_decfunc::generate()
{
	// Put a pointer to this function into the custom function list
	g_functions.insert(pair<string, c_decfunc*>(m_funcName, this));
}
Example #18
0
// Reads an input file and fills up the adjacency list as well as the edges.
void readGraph(int &n, bool &isWeigthed, adjacency_list &adjList, map<string, float> edgeList) {

    int e = 0; // Total number of edges (for statistics).
    isWeigthed = false;

    char * line = NULL;
    size_t len = 0;
    FILE * fp = readPrompt();

    // Find n, the total number of nodes.
    if (getline(&line, &len, fp) != -1) {
        strtok(line, " ");
        n = atoi(strtok(NULL, " "));

    }

    // Reserve n space for adjacency list. If it fails, n was not parsed.
    if (n) {
        adjList.reserve(n);
    } else {
        cout << "Malformed input. Number of nodes undefined.";
        exit(EXIT_FAILURE);
    }

    // Skip n lines until edges part.
    for (int i = 0; i <= n; i++) {
        if(getline(&line, &len, fp) == -1) {
            cout << "Malformed input. Missing data.";
            exit(EXIT_FAILURE);
        }
    }
    
    // Read the nodes and the edges, one by one, and fill up adjList and edgeBetweenness.
    int start, end, weight;
    while (getline(&line, &len, fp) != -1) {
        e += 1;

        start = atoi(strtok(line, " ")) - 1;
        end = atoi(strtok(NULL, " ")) - 1;
        weight = atoi(strtok(NULL, " "));
        
        // Check if the graph is weighted. If w<=0, the input is malformed
        if (weight > 1) {
            isWeigthed = true;
        } else if(weight<=0) {
            cout << "Malformed input. Edge w weight=0.";
            exit(EXIT_FAILURE);
        }
        
        edgeList.insert(pair<string, float>(getEdgeTag(start, end), 0));
        adjList[start].push_back(neighbor(end, weight));
        adjList[end].push_back(neighbor(start, weight));
    }

    if (line) {
        free(line);
    }
    
    // Print statistics after reading.
    printInputStats(isWeigthed, n, e);
}
Example #19
0
inline int hash(char *s, int &n) {
	int ret; it = M.find(s);
	if(it == M.end()) M.insert(pair< string, int >(s, ret=n++));
	else ret = it->second;
	return ret;
}
  void testInsanity(map<UserId, map<Numberz::type,Insanity> > &insane, const Insanity &argument) {
    printf("[C -> C++] testInsanity()\n");

    Xtruct hello;
    hello.string_thing = "Hello2";
    hello.byte_thing = 2;
    hello.i32_thing = 2;
    hello.i64_thing = 2;

    Xtruct goodbye;
    goodbye.string_thing = "Goodbye4";
    goodbye.byte_thing = 4;
    goodbye.i32_thing = 4;
    goodbye.i64_thing = 4;

    Insanity crazy;
    crazy.userMap.insert(make_pair(Numberz::EIGHT, 8));
    crazy.xtructs.push_back(goodbye);

    Insanity looney;
    crazy.userMap.insert(make_pair(Numberz::FIVE, 5));
    crazy.xtructs.push_back(hello);

    map<Numberz::type, Insanity> first_map;
    map<Numberz::type, Insanity> second_map;

    first_map.insert(make_pair(Numberz::TWO, crazy));
    first_map.insert(make_pair(Numberz::THREE, crazy));

    second_map.insert(make_pair(Numberz::SIX, looney));

    insane.insert(make_pair(1, first_map));
    insane.insert(make_pair(2, second_map));

    printf("return");
    printf(" = {");
    map<UserId, map<Numberz::type,Insanity> >::const_iterator i_iter;
    for (i_iter = insane.begin(); i_iter != insane.end(); ++i_iter) {
      printf("%ld => {", i_iter->first);
      map<Numberz::type,Insanity>::const_iterator i2_iter;
      for (i2_iter = i_iter->second.begin();
           i2_iter != i_iter->second.end();
           ++i2_iter) {
        printf("%d => {", i2_iter->first);
        map<Numberz::type, UserId> userMap = i2_iter->second.userMap;
        map<Numberz::type, UserId>::const_iterator um;
        printf("{");
        for (um = userMap.begin(); um != userMap.end(); ++um) {
          printf("%d => %ld, ", um->first, um->second);
        }
        printf("}, ");

        vector<Xtruct> xtructs = i2_iter->second.xtructs;
        vector<Xtruct>::const_iterator x;
        printf("{");
        for (x = xtructs.begin(); x != xtructs.end(); ++x) {
          printf("{\"%s\", %d, %d, %ld}, ", x->string_thing.c_str(), (int)x->byte_thing, x->i32_thing, x->i64_thing);
        }
        printf("}");

        printf("}, ");
      }
      printf("}, ");
    }
    printf("}\n");


  }
Example #21
0
Q3BSPLeaf *Q3BSPRep::createLeaf( int n ){
	q3_leaf *q3leaf=(q3_leaf*)header.dir[4].lump+n;

	Q3BSPLeaf *leaf=d_new Q3BSPLeaf;

	leaf->cluster=q3leaf->cluster;

	Vector mins( q3leaf->mins[0],q3leaf->mins[1],q3leaf->mins[2] );
	Vector maxs( q3leaf->maxs[0],q3leaf->maxs[1],q3leaf->maxs[2] );
	leaf->box=Box( tf(mins) );
	leaf->box.update( tf(maxs) );
	int *leaffaces=(int*)header.dir[5].lump+q3leaf->leafface;

	for( int k=0;k<q3leaf->n_leaffaces;++k ){

		int face_n=leaffaces[k];

		map<int,Q3BSPFace*>::const_iterator it=q3face_map.find(face_n);
		if( it!=q3face_map.end() ){
			if( it->second ) leaf->faces.push_back( it->second );
			continue;
		}

		q3_face *q3face=(q3_face*)header.dir[13].lump+leaffaces[k];

		if( q3face->type==1 || q3face->type==3 ){
			if( !q3face->n_meshverts || (q3face->n_meshverts%3) ) continue;
		}else if( q3face->type!=2 ) continue;

		bool draw=true,solid=true;

		if( q3face->texture>=0 ){
			q3_tex *q3tex=(q3_tex*)header.dir[1].lump+q3face->texture;
			if( !(q3tex->contents & 1) ) continue;
			if( q3tex->flags & 0x84 ) draw=false;
		}

		if( !draw && !solid ) continue;

		Q3BSPFace *face=0;
		if( draw ){
			Surf *surf=findSurf( q3face );
			face=d_new Q3BSPFace;
			face->t_surf=surf;
			face->vert=surf->verts.size();
			face->tri=surf->tris.size();
			face->n_verts=face->n_tris=0;
			leaf->faces.push_back( face );
			faces.push_back( face );
			q3face_map.insert( make_pair( face_n,face ) );
		}

		if( q3face->type==2 ){
			patchFace( face,q3face,draw,solid,1 );
		}else{
			meshFace( face,q3face,draw,solid );
		}
	}

	return leaf;
}
Example #22
0
File: vsm.cpp Project: bigsmiles/TC
void testICTCLAS_ParagraphProcessToSVM(string folderPath,int folderId)  //path开始路径
{

	long Handle;
	struct _finddata_t FileInfo;
	string fpath = folderPath + "\\*";
	if((Handle = _findfirst(fpath.c_str(),&FileInfo)) == -1L)  //遍历目录下的文件
	{
		printf("没有找到匹配的项目");
		exit(-1);
	}


	do{
        //判断是否有子目录
        if (FileInfo.attrib & _A_SUBDIR)    
        {
            //这个语句很重要
            if( (strcmp(FileInfo.name,".") != 0 ) &&(strcmp(FileInfo.name,"..") != 0))   
            {
                string newPath = folderPath + "\\" + FileInfo.name;
                cout<<"目录名"<<newPath<<endl; 
                testICTCLAS_ParagraphProcessToSVM(newPath,folderId+1);
				folderId += 1;
            }
        }
        else  
        {
				char* sSentence =  (char*)malloc(FileInfo.size);
				char ch;
				int len = 0;
			
				string filepath = folderPath + "\\" + FileInfo.name;
				ifstream ifile(filepath.c_str());

				while(ifile>>ch)	//这样读入为了将换行符去掉,ASCII码10、13
				{
					 if(ch == '\n' || ch == '\r')
						 continue;
					 sSentence[len++] = ch;
				}
		
				sSentence[len] = '\0';
				unsigned int nPaLen=strlen(sSentence); // 需要分词的长度
				char* sRst=0;   //用户自行分配空间,用于保存结果;
				sRst=(char *)malloc(nPaLen*6); //建议长度为字符串长度的倍。
				int nRstLen=0; //分词结果的长度
			
				nRstLen = ICTCLAS_ParagraphProcess(sSentence,nPaLen,sRst,CODE_TYPE_UNKNOWN,0);  //字符串处理
				/*收集单词,形成字典*/
				//cout<<"目录为:"<<folderId<<endl;
				double TF;
				//int txtCnt;//文章总词数
				string words;
				istringstream istream(sRst);
				map<string,int>txt;
				vector<double> tmpVSM;
				set<string> txtWords;
				while(istream>>words)
				{
					txtWords.insert(words);
					if(featureDic.count(words))
					{
						txt[words]++;
					}
				}
				outFile<<FileInfo.name<<endl;
				for(set<string>::iterator setItor = featureDic.begin(); setItor != featureDic.end(); setItor++)
				{
				
					TF = (1.0*txt[(*setItor)]) / txtWords.size();
					TF *= log(0.01 + total/IDFDic[(*setItor)]);
					tmpVSM.push_back(TF);
					outFile<<TF<<" ";
				
				}
				outFile<<endl;
				txtVSM.insert(STRING2VECTOR::value_type(FileInfo.name,tmpVSM));
				tmpVSM.clear();
				txtWords.clear();

		 free(sRst);
        }
	
    }while (_findnext(Handle, &FileInfo) == 0);

		_findclose(Handle);
  
	return ;  
}
Example #23
0
void addServer(std::string name, ServerInfo cl)
{
	_servers.insert(pair<std::string, ServerInfo>(name, cl));
}
Example #24
0
        MyUserCallback(SymmetricZRTPSession* s) {
            session = s;
        if (initialized) {
            return;
        }
        infoMap.insert(pair<int32, std::string*>(InfoHelloReceived, new string("Hello received, preparing a Commit")));
        infoMap.insert(pair<int32, std::string*>(InfoCommitDHGenerated, new string("Commit: Generated a public DH key")));
        infoMap.insert(pair<int32, std::string*>(InfoRespCommitReceived, new string("Responder: Commit received, preparing DHPart1")));
        infoMap.insert(pair<int32, std::string*>(InfoDH1DHGenerated, new string("DH1Part: Generated a public DH key")));
        infoMap.insert(pair<int32, std::string*>(InfoInitDH1Received, new string("Initiator: DHPart1 received, preparing DHPart2")));
        infoMap.insert(pair<int32, std::string*>(InfoRespDH2Received, new string("Responder: DHPart2 received, preparing Confirm1")));
        infoMap.insert(pair<int32, std::string*>(InfoInitConf1Received, new string("Initiator: Confirm1 received, preparing Confirm2")));
        infoMap.insert(pair<int32, std::string*>(InfoRespConf2Received, new string("Responder: Confirm2 received, preparing Conf2Ack")));
        infoMap.insert(pair<int32, std::string*>(InfoRSMatchFound, new string("At least one retained secrets matches - security OK")));
        infoMap.insert(pair<int32, std::string*>(InfoSecureStateOn, new string("Entered secure state")));
        infoMap.insert(pair<int32, std::string*>(InfoSecureStateOff, new string("No more security for this session")));

        warningMap.insert(pair<int32, std::string*>(WarningDHAESmismatch,
                          new string("Commit contains an AES256 cipher but does not offer a Diffie-Helman 4096")));
        warningMap.insert(pair<int32, std::string*>(WarningGoClearReceived, new string("Received a GoClear message")));
        warningMap.insert(pair<int32, std::string*>(WarningDHShort,
                          new string("Hello offers an AES256 cipher but does not offer a Diffie-Helman 4096")));
        warningMap.insert(pair<int32, std::string*>(WarningNoRSMatch, new string("No retained secret matches - verify SAS")));
        warningMap.insert(pair<int32, std::string*>(WarningCRCmismatch, new string("Internal ZRTP packet checksum mismatch - packet dropped")));
        warningMap.insert(pair<int32, std::string*>(WarningSRTPauthError, new string("Dropping packet because SRTP authentication failed!")));
        warningMap.insert(pair<int32, std::string*>(WarningSRTPreplayError, new string("Dropping packet because SRTP replay check failed!")));

        severeMap.insert(pair<int32, std::string*>(SevereHelloHMACFailed, new string("Hash HMAC check of Hello failed!")));
        severeMap.insert(pair<int32, std::string*>(SevereCommitHMACFailed, new string("Hash HMAC check of Commit failed!")));
        severeMap.insert(pair<int32, std::string*>(SevereDH1HMACFailed, new string("Hash HMAC check of DHPart1 failed!")));
        severeMap.insert(pair<int32, std::string*>(SevereDH2HMACFailed, new string("Hash HMAC check of DHPart2 failed!")));
        severeMap.insert(pair<int32, std::string*>(SevereCannotSend, new string("Cannot send data - connection or peer down?")));
        severeMap.insert(pair<int32, std::string*>(SevereProtocolError, new string("Internal protocol error occured!")));
        severeMap.insert(pair<int32, std::string*>(SevereNoTimer, new string("Cannot start a timer - internal resources exhausted?")));
        severeMap.insert(pair<int32, std::string*>(SevereTooMuchRetries,
                         new string("Too much retries during ZRTP negotiation - connection or peer down?")));

        zrtpMap.insert(pair<int32, std::string*>(MalformedPacket, new string("Malformed packet (CRC OK, but wrong structure)")));
        zrtpMap.insert(pair<int32, std::string*>(CriticalSWError, new string("Critical software error")));
        zrtpMap.insert(pair<int32, std::string*>(UnsuppZRTPVersion, new string("Unsupported ZRTP version")));
        zrtpMap.insert(pair<int32, std::string*>(HelloCompMismatch, new string("Hello components mismatch")));
        zrtpMap.insert(pair<int32, std::string*>(UnsuppHashType, new string("Hash type not supported")));
        zrtpMap.insert(pair<int32, std::string*>(UnsuppCiphertype, new string("Cipher type not supported")));
        zrtpMap.insert(pair<int32, std::string*>(UnsuppPKExchange, new string("Public key exchange not supported")));
        zrtpMap.insert(pair<int32, std::string*>(UnsuppSRTPAuthTag, new string("SRTP auth. tag not supported")));
        zrtpMap.insert(pair<int32, std::string*>(UnsuppSASScheme, new string("SAS scheme not supported")));
        zrtpMap.insert(pair<int32, std::string*>(NoSharedSecret, new string("No shared secret available, DH mode required")));
        zrtpMap.insert(pair<int32, std::string*>(DHErrorWrongPV, new string("DH Error: bad pvi or pvr ( == 1, 0, or p-1)")));
        zrtpMap.insert(pair<int32, std::string*>(DHErrorWrongHVI, new string("DH Error: hvi != hashed data")));
        zrtpMap.insert(pair<int32, std::string*>(SASuntrustedMiTM, new string("Received relayed SAS from untrusted MiTM")));
        zrtpMap.insert(pair<int32, std::string*>(ConfirmHMACWrong, new string("Auth. Error: Bad Confirm pkt HMAC")));
        zrtpMap.insert(pair<int32, std::string*>(NonceReused, new string("Nonce reuse")));
        zrtpMap.insert(pair<int32, std::string*>(EqualZIDHello, new string("Equal ZIDs in Hello")));
        zrtpMap.insert(pair<int32, std::string*>(GoCleatNotAllowed, new string("GoClear packet received, but not allowed")));

        initialized = true;
        }
/*
 * Adds the given Contraint to the appropriate ConstraintSet.
 */
void
QualValidatorConstraints::add (VConstraint* c)
{
  if (c == NULL) return;

  ptrMap.insert(pair<VConstraint*,bool>(c,true));

  if (dynamic_cast< TConstraint<SBMLDocument>* >(c) != NULL)
  {
    mSBMLDocument.add( static_cast< TConstraint<SBMLDocument>* >(c) );
    return;
  }

  if (dynamic_cast< TConstraint<Model>* >(c) != NULL)
  {
    mModel.add( static_cast< TConstraint<Model>* >(c) );
    return;
  }

  if (dynamic_cast< TConstraint<QualitativeSpecies>* >(c) != NULL)
  {
    mQualitativeSpecies.add( static_cast< TConstraint<QualitativeSpecies>* >(c) );
    return;
  }

  if (dynamic_cast< TConstraint<Transition>* >(c) != NULL)
  {
    mTransition.add( static_cast< TConstraint<Transition>* >(c) );
    return;
  }

  if (dynamic_cast< TConstraint<Input>* >(c) != NULL)
  {
    mInput.add( static_cast< TConstraint<Input>* >(c) );
    return;
  }

  if (dynamic_cast< TConstraint<Output>* >(c) != NULL)
  {
    mOutput.add( static_cast< TConstraint<Output>* >(c) );
    return;
  }

  if (dynamic_cast< TConstraint<FunctionTerm>* >(c) != NULL)
  {
    mFunctionTerm.add( static_cast< TConstraint<FunctionTerm>* >(c) );
    return;
  }

  if (dynamic_cast< TConstraint<DefaultTerm>* >(c) != NULL)
  {
    mDefaultTerm.add( static_cast< TConstraint<DefaultTerm>* >(c) );
    return;
  }

  if (dynamic_cast< TConstraint<ListOfFunctionTerms>* >(c) != NULL)
  {
    mListOfFunctionTerms.add( static_cast< TConstraint<ListOfFunctionTerms>* >(c) );
    return;
  }
}
Example #26
0
int main(){
	leftR.insert(make_pair("1U", "1W"));
	leftR.insert(make_pair("1W", "1D"));
	leftR.insert(make_pair("1D", "1E"));
	leftR.insert(make_pair("1E", "1U"));
	leftR.insert(make_pair("2U", "2S"));
	leftR.insert(make_pair("2S", "2D"));
	leftR.insert(make_pair("2D", "2N"));
	leftR.insert(make_pair("2N", "2U"));
	leftR.insert(make_pair("4U", "4E"));
	leftR.insert(make_pair("4E", "4D"));
	leftR.insert(make_pair("4D", "4W"));
	leftR.insert(make_pair("4W", "4U"));
	leftR.insert(make_pair("5U", "5N"));
	leftR.insert(make_pair("5N", "5D"));
	leftR.insert(make_pair("5D", "5S"));
	leftR.insert(make_pair("5S", "5U"));
	leftR.insert(make_pair("3N", "3W"));
	leftR.insert(make_pair("3W", "3S"));
	leftR.insert(make_pair("3S", "3E"));
	leftR.insert(make_pair("3E", "3N"));
	leftR.insert(make_pair("6N", "6E"));
	leftR.insert(make_pair("6E", "6S"));
	leftR.insert(make_pair("6S", "6W"));
	leftR.insert(make_pair("6W", "6N"));

	frontM.insert(make_pair("1U", "3N"));
	frontM.insert(make_pair("1W", "5N"));
	frontM.insert(make_pair("1D", "6N"));
	frontM.insert(make_pair("1E", "2N"));
	frontM.insert(make_pair("2U", "3W"));
	frontM.insert(make_pair("2S", "1W"));
	frontM.insert(make_pair("2D", "6W"));
	frontM.insert(make_pair("2N", "4W"));
	frontM.insert(make_pair("4U", "3S"));
	frontM.insert(make_pair("4E", "2S"));
	frontM.insert(make_pair("4D", "6S"));
	frontM.insert(make_pair("4W", "5S"));
	frontM.insert(make_pair("5U", "3E"));
	frontM.insert(make_pair("5N", "4E"));
	frontM.insert(make_pair("5D", "6E"));
	frontM.insert(make_pair("5S", "1E"));
	frontM.insert(make_pair("3N", "4D"));
	frontM.insert(make_pair("3W", "5D"));
	frontM.insert(make_pair("3S", "1D"));
	frontM.insert(make_pair("3E", "2D"));
	frontM.insert(make_pair("6N", "4U"));
	frontM.insert(make_pair("6E", "2U"));
	frontM.insert(make_pair("6S", "1U"));
	frontM.insert(make_pair("6W", "5U"));

	string curr, ops;

	cin >> curr;
	cin >> ops;

	for (int i = ops.size()-1; i >= 0; i--){
		if (ops[i] == 'F')
			curr = turn(frontM[turn(curr)]);
		else if (ops[i] == 'B')
			curr = frontM[turn(curr)];
		else if (ops[i] == 'L')
			curr = leftR[frontM[turn(curr)]];
		else
			curr = leftR[turn(frontM[turn(curr)])];

		//cout << curr << endl;
	}

	cout << curr << endl;
}
Example #27
0
        void AIUpdate()
        {
            uint32 plrcounts[2] = { 0, 0 };

            // details:
            //   loop through inrange players, for new ones, send the enable CP worldstate.
            //   the value of the map is a timestamp of the last update, to avoid cpu time wasted
            //   doing lookups of objects that have already been updated

            itr = _gameobject->GetInRangePlayerSetBegin();
            itrend = _gameobject->GetInRangePlayerSetEnd();
            map<uint32, uint32>::iterator it2, it3;
            uint32 timeptr = (uint32)UNIXTIME;
            bool in_range;
            bool is_valid;
            Player* plr;
            MapMgr* mgr = _gameobject->GetMapMgr();

            for(; itr != itrend; ++itr)
            {
                plr = TO< Player* >(*itr);
                if(!plr->IsPvPFlagged() || !(plr->isAlive()) && !(plr->IsStealth()) && !(plr->m_invisible) && !(plr->SchoolImmunityList[0]))
                    is_valid = false;
                else
                    is_valid = true;

                in_range = (_gameobject->GetDistance2dSq((*itr)) <= BANNER_RANGE);

                it2 = StoredPlayers.find((*itr)->GetLowGUID());
                if(it2 == StoredPlayers.end())
                {
                    // new player :)
                    if(in_range)
                    {
                        plr->SendWorldStateUpdate(WORLDSTATE_TEROKKAR_PVP_CAPTURE_BAR_DISPLAY, 1);
                        plr->SendWorldStateUpdate(WORLDSTATE_TEROKKAR_PVP_CAPTURE_BAR_VALUE, Status);
                        StoredPlayers.insert(make_pair((*itr)->GetLowGUID(), timeptr));

                        if(is_valid)
                            plrcounts[(*itr)->GetTeam()]++;
                    }
                }
                else
                {
                    // oldie
                    if(!in_range)
                    {
                        plr->SendWorldStateUpdate(WORLDSTATE_TEROKKAR_PVP_CAPTURE_BAR_DISPLAY, 0);
                        StoredPlayers.erase(it2);
                    }
                    else
                    {
                        plr->SendWorldStateUpdate(WORLDSTATE_TEROKKAR_PVP_CAPTURE_BAR_VALUE, Status);
                        it2->second = timeptr;
                        if(is_valid)
                            plrcounts[(*itr)->GetTeam()]++;
                    }
                }
            }

            // handle stuff for the last tick
            if(Status == 100 && m_bannerStatus != BANNER_STATUS_ALLIANCE)
            {
                m_bannerStatus = BANNER_STATUS_ALLIANCE;
                SetArtKit();

                // send message to everyone in the zone, has been captured by the Alliance
                mgr->SendPvPCaptureMessage(ZONE_TEROKKAR_FOREST, ZONE_TEROKKAR_FOREST, "|cffffff00%s has been taken by the Alliance!|r", ControlPointName);

                // tower update
                TFg_allianceTowers++;
                UpdateTowerCount();

                // state update
                mgr->GetWorldStatesHandler().SetWorldStateForZone(ZONE_TEROKKAR_FOREST, mgr->GetAreaID( _gameobject->GetPositionX(), _gameobject->GetPositionY() ), g_neutralStateFields[towerid], 0);
                mgr->GetWorldStatesHandler().SetWorldStateForZone(ZONE_TEROKKAR_FOREST, mgr->GetAreaID( _gameobject->GetPositionX(), _gameobject->GetPositionY() ), g_allianceStateFields[towerid], 1);

                // woot
                TFg_towerOwners[towerid] = 1;
            }
            else if(Status == 0 && m_bannerStatus != BANNER_STATUS_HORDE)
            {
                m_bannerStatus = BANNER_STATUS_HORDE;
                SetArtKit();

                // send message to everyone in the zone, has been captured by the Horde
                mgr->SendPvPCaptureMessage(ZONE_TEROKKAR_FOREST, ZONE_TEROKKAR_FOREST, "|cffffff00%s has been taken by the Horde!|r", ControlPointName);

                // tower update
                TFg_hordeTowers++;
                UpdateTowerCount();

                // state update
                mgr->GetWorldStatesHandler().SetWorldStateForZone(ZONE_TEROKKAR_FOREST, mgr->GetAreaID( _gameobject->GetPositionX(), _gameobject->GetPositionY() ), g_neutralStateFields[towerid], 0);
                mgr->GetWorldStatesHandler().SetWorldStateForZone(ZONE_TEROKKAR_FOREST, mgr->GetAreaID( _gameobject->GetPositionX(), _gameobject->GetPositionY() ), g_hordeStateFields[towerid], 1);

                // woot
                TFg_towerOwners[towerid] = 0;
            }
            else if(m_bannerStatus != BANNER_STATUS_NEUTRAL)
            {
                // if the difference for the faction is >50, change to neutral
                if(m_bannerStatus == BANNER_STATUS_ALLIANCE && Status <= 50)
                {
                    // send message: The Alliance has lost control of point xxx
                    m_bannerStatus = BANNER_STATUS_NEUTRAL;
                    SetArtKit();

                    TFg_allianceTowers--;
                    UpdateTowerCount();

                    mgr->SendPvPCaptureMessage(ZONE_TEROKKAR_FOREST, ZONE_TEROKKAR_FOREST, "|cffffff00The Alliance have lost control of %s!|r", ControlPointName);

                    // state update
                    mgr->GetWorldStatesHandler().SetWorldStateForZone(ZONE_TEROKKAR_FOREST, mgr->GetAreaID( _gameobject->GetPositionX(), _gameobject->GetPositionY() ), g_allianceStateFields[towerid], 0);
                    mgr->GetWorldStatesHandler().SetWorldStateForZone(ZONE_TEROKKAR_FOREST, mgr->GetAreaID( _gameobject->GetPositionX(), _gameobject->GetPositionY() ), g_neutralStateFields[towerid], 1);

                    // woot
                    TFg_towerOwners[towerid] = -1;
                }
                else if(m_bannerStatus == BANNER_STATUS_HORDE && Status >= 50)
                {
                    // send message: The Alliance has lost control of point xxx
                    m_bannerStatus = BANNER_STATUS_NEUTRAL;
                    SetArtKit();

                    TFg_hordeTowers--;
                    UpdateTowerCount();

                    mgr->SendPvPCaptureMessage(ZONE_TEROKKAR_FOREST, ZONE_TEROKKAR_FOREST, "|cffffff00The Horde have lost control of %s!|r", ControlPointName);

                    // state update
                    mgr->GetWorldStatesHandler().SetWorldStateForZone(ZONE_TEROKKAR_FOREST, mgr->GetAreaID( _gameobject->GetPositionX(), _gameobject->GetPositionY() ), g_hordeStateFields[towerid], 0);
                    mgr->GetWorldStatesHandler().SetWorldStateForZone(ZONE_TEROKKAR_FOREST, mgr->GetAreaID( _gameobject->GetPositionX(), _gameobject->GetPositionY() ), g_neutralStateFields[towerid], 1);

                    // woot
                    TFg_towerOwners[towerid] = -1;
                }
            }

            // send any out of range players the disable flag
            for(it2 = StoredPlayers.begin(); it2 != StoredPlayers.end();)
            {
                it3 = it2;
                ++it2;

                if(it3->second != timeptr)
                {
                    plr = _gameobject->GetMapMgr()->GetPlayer(it3->first);

                    // they WILL be out of range at this point. this is guaranteed. means they left the set rly quickly.
                    if(plr)
                        plr->SendWorldStateUpdate(WORLDSTATE_TEROKKAR_PVP_CAPTURE_BAR_DISPLAY, 0);

                    StoredPlayers.erase(it3);
                }
            }

            // work out current status for next tick
            uint32 delta;
            if(plrcounts[0] > plrcounts[1])
            {
                delta = plrcounts[0] - plrcounts[1];
                delta *= CAPTURE_RATE;

                // cap it at 25 so the banner always gets removed.
                if(delta > 25)
                    delta = 25;

                Status += delta;
                if(Status >= 100)
                    Status = 100;
            }
            else if(plrcounts[1] > plrcounts[0])
            {
                delta = plrcounts[1] - plrcounts[0];
                delta *= CAPTURE_RATE;

                // cap it at 25 so the banner always gets removed.
                if(delta > 25)
                    delta = 25;

                if(delta > Status)
                    Status = 0;
                else
                    Status -= delta;
            }
        }
/* ****************************************************************************
*
* addTriggeredSubscriptions -
*/
static bool addTriggeredSubscriptions
(
  ContextRegistration                   cr,
  map<string, TriggeredSubscription*>&  subs,
  std::string&                          err,
  std::string                           tenant
)
{

  BSONArrayBuilder          entitiesNoPatternA;
  std::vector<std::string>  idJsV;
  std::vector<std::string>  typeJsV;

  for (unsigned int ix = 0; ix < cr.entityIdVector.size(); ++ix)
  {
    // FIXME: take into account subscriptions with no type
    EntityId* enP = cr.entityIdVector.get(ix);

    // The registration of isPattern=true entities is not supported, so we don't include them here
    if (enP->isPattern == "false")
    {
      entitiesNoPatternA.append(BSON(CASUB_ENTITY_ID << enP->id <<
                                     CASUB_ENTITY_TYPE << enP->type <<
                                     CASUB_ENTITY_ISPATTERN << "false"));
      idJsV.push_back(enP->id);
      typeJsV.push_back(enP->type);
    }
  }

  BSONArrayBuilder attrA;
  for (unsigned int ix = 0; ix < cr.contextRegistrationAttributeVector.size(); ++ix)
  {
    ContextRegistrationAttribute* craP = cr.contextRegistrationAttributeVector.get(ix);
    attrA.append(craP->name);
  }

  BSONObjBuilder queryNoPattern;
  queryNoPattern.append(CASUB_ENTITIES, BSON("$in" << entitiesNoPatternA.arr()));
  if (attrA.arrSize() > 0)
  {
    // If we don't do this checking, the {$in: [] } in the attribute name part will
    // make the query fail
    //

    // queryB.append(CASUB_ATTRS, BSON("$in" << attrA.arr()));
    queryNoPattern.append("$or", BSON_ARRAY(
                            BSON(CASUB_ATTRS << BSON("$in" << attrA.arr())) <<
                            BSON(CASUB_ATTRS << BSON("$size" << 0))));
  }
  else
  {
    queryNoPattern.append(CASUB_ATTRS, BSON("$size" << 0));
  }
  queryNoPattern.append(CASUB_EXPIRATION, BSON("$gt" << (long long) getCurrentTime()));


  //
  // This is JavaScript code that runs in MongoDB engine. As far as I know, this is the only
  // way to do a "reverse regex" query in MongoDB (see
  // http://stackoverflow.com/questions/15966991/mongodb-reverse-regex/15989520).
  // Note that although we are using a isPattern=true in the MongoDB query besides $where, we
  // also need to check that in the if statement in the JavaScript function given that a given
  // sub document could include both isPattern=true and isPattern=false documents
  //
  std::string idJsString = "[ ";

  for (unsigned int ix = 0; ix < idJsV.size(); ++ix)
  {
    if (ix != idJsV.size() - 1)
    {
      idJsString += "\""+idJsV[ix]+ "\" ,";
    }
    else
    {
      idJsString += "\"" +idJsV[ix]+ "\"";
    }
  }
  idJsString += " ]";

  std::string typeJsString = "[ ";

  for (unsigned int ix = 0; ix < typeJsV.size(); ++ix)
  {
    if (ix != typeJsV.size() - 1)
    {
      typeJsString += "\"" +typeJsV[ix] + "\" ,";
    }
    else
    {
      typeJsString += "\"" + typeJsV[ix] + "\"";
    }
  }
  typeJsString += " ]";

  std::string function = std::string("function()") +
    "{" +
      "enId = " + idJsString + ";" +
      "enType = " + typeJsString + ";" +
      "for (var i=0; i < this." + CASUB_ENTITIES + ".length; i++) {" +
        "if (this." + CASUB_ENTITIES + "[i]." + CASUB_ENTITY_ISPATTERN + " == \"true\") {" +
          "for (var j = 0; j < enId.length; j++) {" +
            "if (enId[j].match(this." + CASUB_ENTITIES + "[i]." + CASUB_ENTITY_ID +
              ") && this." + CASUB_ENTITIES + "[i]." + CASUB_ENTITY_TYPE + " == enType[j]) {" +
              "return true; " +
            "}" +
          "}" +
        "}" +
      "}" +
      "return false; " +
    "}";
  LM_T(LmtMongo, ("JS function: %s", function.c_str()));


  std::string     entPatternQ = CSUB_ENTITIES "." CSUB_ENTITY_ISPATTERN;
  BSONObjBuilder  queryPattern;

  queryPattern.append(entPatternQ, "true");
  queryPattern.append(CASUB_EXPIRATION, BSON("$gt" << (long long) getCurrentTime()));
  queryPattern.appendCode("$where", function);

  auto_ptr<DBClientCursor> cursor;
  BSONObj                  query = BSON("$or" << BSON_ARRAY(queryNoPattern.obj() << queryPattern.obj()));

  TIME_STAT_MONGO_READ_WAIT_START();
  DBClientBase* connection = getMongoConnection();
  if (!collectionQuery(connection, getSubscribeContextAvailabilityCollectionName(tenant), query, &cursor, &err))
  {
    TIME_STAT_MONGO_READ_WAIT_STOP();
    releaseMongoConnection(connection, &cursor);
    return false;
  }
  TIME_STAT_MONGO_READ_WAIT_STOP();

  /* For each one of the subscriptions found, add it to the map (if not already there) */
  while (moreSafe(cursor))
  {
    BSONObj     sub;
    std::string err;
    if (!nextSafeOrError(cursor, &sub, &err))
    {
      LM_E(("Runtime Error (exception in nextSafe(): %s", err.c_str()));
      continue;
    }
    BSONElement idField = getField(sub, "_id");

    //
    // BSONElement::eoo returns true if 'not found', i.e. the field "_id" doesn't exist in 'sub'
    //
    // Now, if 'sub.getField("_id")' is not found, if we continue, calling OID() on it, then we get
    // an exception and the broker crashes.
    //
    if (idField.eoo() == true)
    {
      LM_E(("Database Error (error retrieving _id field in doc: %s)", sub.toString().c_str()));
      continue;
    }

    std::string subIdStr = idField.OID().toString();

    if (subs.count(subIdStr) == 0)
    {
      LM_T(LmtMongo, ("adding subscription: '%s'", sub.toString().c_str()));

      TriggeredSubscription* trigs = new TriggeredSubscription(
        sub.hasField(CASUB_FORMAT) ? stringToFormat(getStringField(sub, CASUB_FORMAT)) : XML,
        getStringField(sub, CASUB_REFERENCE),
        subToAttributeList(sub));

      subs.insert(std::pair<string, TriggeredSubscription*>(subIdStr, trigs));
    }
  }
  releaseMongoConnection(connection, &cursor);

  return true;
}
Example #29
0
void getList( string templates_name, string cluster_def, list<string> &template_list, map<string,double> &template_prob1, map<string,double> &template_prob2 )
{
 multimap<string,string> cluster_map;
 
 multimap<string,double> template_tmp1;
 multimap<string,double> template_tmp2;
 
 string line1;
 
 ifstream clusters_file( cluster_def.c_str() );
 
 if ( !clusters_file.is_open() )  { cout << "Cannot open " << cluster_def << endl; exit(EXIT_FAILURE); }
 
 while (getline(clusters_file,line1))
 {
  string tpl1;
  int    tpl3;
  
  tpl1 = line1.substr(0,15);
  
  string::size_type tpl6 = 0;
  
  bool tpl7 = true;
  
  while( tpl7 )
  {
   tpl6 = tpl1.find(" ");
   if( tpl6 != string::npos )
    tpl1.erase( tpl6, 1 );
   else
    tpl7 = false;
  }
  
  tpl3 = atoi(line1.substr(15,5).c_str());
  
  for ( int tpl4 = 0; tpl4 < tpl3; tpl4++ )
  {
   string tpl5;
   
   tpl5 = line1.substr(21+6*tpl4,5);
   
   cluster_map.insert( pair<string,string>(tpl1,tpl5) );
  }
 }
 
 clusters_file.close();
 
 multimap<int,string,std::greater<int> > template_fun;
 
 string line2;
 
 ifstream template_file( templates_name.c_str() );
 
 if ( !template_file.is_open() )  { cout << "Cannot open " << templates_name << endl; exit(EXIT_FAILURE); }
 
 while (getline(template_file,line2))
  if ( line2.length() > 71 )
  {
   if ( line2.compare(0, 1, "#") != 0 )
   {
    string tpl1;
    int    tpl2;
    double tpl3;
    double tpl4;
    
    tpl1 = line2.substr(0,15);
    
    string::size_type tpl6 = 0;
    
    bool tpl7 = true;
    
    while( tpl7 )
    {
     tpl6 = tpl1.find(" ");
     if( tpl6 != string::npos )
      tpl1.erase( tpl6, 1 );
     else
      tpl7 = false;
    }
    
    tpl2 = atoi(line2.substr(57,6).c_str());
    
    tpl3 = atof(line2.substr(55,8).c_str());
    tpl4 = atof(line2.substr(64,8).c_str());
    
    multimap<string,string>::iterator it1;
    pair<multimap<string,string>::iterator,multimap<string,string>::iterator> it2;
    
    it2 = cluster_map.equal_range(tpl1);
    
    for ( it1 = it2.first; it1 != it2.second; it1++ )
    {
     template_fun.insert( pair<int,string>(tpl2,(*it1).second) );
     
     template_tmp1.insert( pair<string,double>((*it1).second, tpl3) );
     template_tmp2.insert( pair<string,double>((*it1).second, tpl4) );
    }
   }
  }
  else if ( line2.length() )
  {
   if ( line2.compare(0, 1, "#") != 0 )
   {
    string tpl1;
    int    tpl2;
    double tpl3;
    double tpl4;
    
    tpl1 = line2;
    
    string::size_type tpl6 = 0;
    
    bool tpl7 = true;
    
    while( tpl7 )
    {
     tpl6 = tpl1.find(" ");
     if( tpl6 != string::npos )
      tpl1.erase( tpl6, 1 );
     else
      tpl7 = false;
    }
    
    tpl2 = rand();
    
    tpl3 = 1.0;
    tpl4 = 1.0;
    
    multimap<string,string>::iterator it1;
    pair<multimap<string,string>::iterator,multimap<string,string>::iterator> it2;
    
    it2 = cluster_map.equal_range(tpl1);
    
    for ( it1 = it2.first; it1 != it2.second; it1++ )
    {
     template_fun.insert( pair<int,string>(tpl2,(*it1).second) );
     
     template_tmp1.insert( pair<string,double>((*it1).second, tpl3) );
     template_tmp2.insert( pair<string,double>((*it1).second, tpl4) );
    }
   }
  }
 
 template_file.close();
 
 multimap<int,string>::iterator it3;
 
 for ( it3 = template_fun.begin() ; it3 != template_fun.end(); it3++ )
 {
  bool w1 = false;
  
  if ( template_list.size() )
  {
   list<string>::iterator it4;
   
   it4 = find(template_list.begin(), template_list.end(), (*it3).second);
   
   if ( it4 == template_list.end() )
    w1 = true;
  }
  else
   w1 = true;
  
  if ( w1 )
  {
   double prob1 = 0.0;
   double prob2 = 0.0;
   
   multimap<string,double>::iterator it5;
   pair<multimap<string,double>::iterator,multimap<string,double>::iterator> it6;
   
   it6 = template_tmp1.equal_range( (*it3).second );
   
   for ( it5 = it6.first; it5 != it6.second; it5++ )
    if ( (*it5).second > prob1 )
     prob1 = (*it5).second;
   
   it6 = template_tmp2.equal_range( (*it3).second );
   
   for ( it5 = it6.first; it5 != it6.second; it5++ )
    if ( (*it5).second > prob2 )
     prob2 = (*it5).second;
   
   template_prob1.insert( pair<string,double>((*it3).second, prob1) );
   template_prob2.insert( pair<string,double>((*it3).second, prob2) );
   
   template_list.push_back( (*it3).second );
  }
 }
}
/// Gather translation candidates for source phrase /src/ and store raw
//  phrase pair statistics in /pstats/. Return the sample rate
//  (number of samples considered / total number of hits) and total number of
//  phrase pairs
pair<float,float>
BilingualDynSuffixArray::
GatherCands(Phrase const& src, map<SAPhrase, vector<float> >& pstats) const
{
  typedef map<SAPhrase, vector<float> >::iterator   pstat_iter;
  typedef map<SAPhrase, vector<float> >::value_type pstat_entry;
  pair<float,float> ret(0,0);
  float& sampleRate   = ret.first;
  float& totalPhrases = ret.second;
  size_t srcSize = src.GetSize();
  SAPhrase localIDs(srcSize);
  vector<unsigned> wrdIndices;
  if(!GetLocalVocabIDs(src, localIDs) ||
      !m_srcSA->GetCorpusIndex(&(localIDs.words), &wrdIndices))
    return ret; // source phrase contains OOVs

  // select a sample of the occurrences for phrase extraction
  size_t m1 = wrdIndices.size();
  SampleSelection(wrdIndices); // careful! SampleSelection alters wrdIndices!
  sampleRate = float(wrdIndices.size())/m1;

  // determine the sentences in which these phrases occur
  vector<int> sntIndices = GetSntIndexes(wrdIndices, srcSize, m_srcSntBreaks);
  for(size_t s = 0; s < sntIndices.size(); ++s) {
    int sntStart = sntIndices.at(s);
    if(sntStart == -1) continue; // marked as bad by GetSntIndexes()
    vector<PhrasePair*> phrasePairs;
    ExtractPhrases(sntStart, wrdIndices[s], srcSize, phrasePairs);
    totalPhrases += phrasePairs.size();
    vector<PhrasePair*>::iterator p;
    for (p = phrasePairs.begin(); p != phrasePairs.end(); ++p) {
      assert(*p);
      pair<float, float> lex = GetLexicalWeight(**p);
      pstat_entry entry(TrgPhraseFromSntIdx(**p), Scores(5));
      pair<pstat_iter, bool> foo = pstats.insert(entry);
      Scores& feats = foo.first->second;
      if (foo.second) {
        feats[0]  = 1; // count
        feats[1]  = lex.first;
        feats[3]  = lex.second;
      } else {
        feats[0] += 1;
        feats[1]  = max(feats[1],lex.first);
        feats[3]  = max(feats[3],lex.second);
      }
      delete *p;
    }
  } // done with all sentences
  BOOST_FOREACH(pstat_entry & e, pstats) {
    Scores& feats = e.second;
    // 0: bwd phrase prob
    // 1: lex 1
    // 2: fwd phrase prob
    // 3: lex 2
    // 4: phrase penalty
    float x  = m_trgSA->GetCount(e.first.words)-feats[0] * sampleRate;
    feats[4] = 1;
    feats[3] = log(feats[3]);
    feats[2] = log(feats[0]) - log(totalPhrases);
    feats[1] = log(feats[1]);
    feats[0] = log(feats[0]) - log(feats[0] + x);
  }