コード例 #1
0
/* The core of recursive retrieving.  Endless recursion is avoided by
   having all URLs stored to a linked list of URLs, which is checked
   before loading any URL.  That way no URL can get loaded twice.

   The function also supports specification of maximum recursion depth
   and a number of other goodies.  */
uerr_t
recursive_retrieve (const char *file, const char *this_url)
{
  char *constr, *filename, *newloc;
  char *canon_this_url = NULL;
  int dt, inl, dash_p_leaf_HTML = FALSE;
  int meta_disallow_follow;
  int this_url_ftp;            /* See below the explanation */
  uerr_t err;
  struct urlinfo *rurl;
  urlpos *url_list, *cur_url;
  char *rfile; /* For robots */
  struct urlinfo *u;

  assert (this_url != NULL);
  assert (file != NULL);
  /* If quota was exceeded earlier, bail out.  */
  if (downloaded_exceeds_quota ())
    return QUOTEXC;
  /* Cache the current URL in the list.  */
  if (first_time)
    {
      /* These three operations need to be done only once per Wget
         run.  They should probably be at a different location.  */
      if (!undesirable_urls)
	undesirable_urls = make_string_hash_table (0);

      hash_table_clear (undesirable_urls);
      string_set_add (undesirable_urls, this_url);
      /* Enter this_url to the hash table, in original and "enhanced" form.  */
      u = newurl ();
      err = parseurl (this_url, u, 0);
      if (err == URLOK)
	{
	  string_set_add (undesirable_urls, u->url);
	  if (opt.no_parent)
	    base_dir = xstrdup (u->dir); /* Set the base dir.  */
	  /* Set the canonical this_url to be sent as referer.  This
	     problem exists only when running the first time.  */
	  canon_this_url = xstrdup (u->url);
	}
      else
	{
	  DEBUGP (("Double yuck!  The *base* URL is broken.\n"));
	  base_dir = NULL;
	}
      freeurl (u, 1);
      depth = 1;
      robots_host = NULL;
      forbidden = NULL;
      first_time = 0;
    }
  else
    ++depth;

  if (opt.reclevel != INFINITE_RECURSION && depth > opt.reclevel)
    /* We've exceeded the maximum recursion depth specified by the user. */
    {
      if (opt.page_requisites && depth <= opt.reclevel + 1)
	/* When -p is specified, we can do one more partial recursion from the
	   "leaf nodes" on the HTML document tree.  The recursion is partial in
	   that we won't traverse any <A> or <AREA> tags, nor any <LINK> tags
	   except for <LINK REL="stylesheet">. */
	dash_p_leaf_HTML = TRUE;
      else
	/* Either -p wasn't specified or it was and we've already gone the one
	   extra (pseudo-)level that it affords us, so we need to bail out. */
	{
	  DEBUGP (("Recursion depth %d exceeded max. depth %d.\n",
		   depth, opt.reclevel));
	  --depth;
	  return RECLEVELEXC;
	}
    }

  /* Determine whether this_url is an FTP URL.  If it is, it means
     that the retrieval is done through proxy.  In that case, FTP
     links will be followed by default and recursion will not be
     turned off when following them.  */
  this_url_ftp = (urlproto (this_url) == URLFTP);

  /* Get the URL-s from an HTML file: */
  url_list = get_urls_html (file, canon_this_url ? canon_this_url : this_url,
			    dash_p_leaf_HTML, &meta_disallow_follow);

  if (opt.use_robots && meta_disallow_follow)
    {
      /* The META tag says we are not to follow this file.  Respect
         that.  */
      free_urlpos (url_list);
      url_list = NULL;
    }

  /* Decide what to do with each of the URLs.  A URL will be loaded if
     it meets several requirements, discussed later.  */
  for (cur_url = url_list; cur_url; cur_url = cur_url->next)
    {
      /* If quota was exceeded earlier, bail out.  */
      if (downloaded_exceeds_quota ())
	break;
      /* Parse the URL for convenient use in other functions, as well
	 as to get the optimized form.  It also checks URL integrity.  */
      u = newurl ();
      if (parseurl (cur_url->url, u, 0) != URLOK)
	{
	  DEBUGP (("Yuck!  A bad URL.\n"));
	  freeurl (u, 1);
	  continue;
	}
      if (u->proto == URLFILE)
	{
	  DEBUGP (("Nothing to do with file:// around here.\n"));
	  freeurl (u, 1);
	  continue;
	}
      assert (u->url != NULL);
      constr = xstrdup (u->url);

      /* Several checkings whether a file is acceptable to load:
	 1. check if URL is ftp, and we don't load it
	 2. check for relative links (if relative_only is set)
	 3. check for domain
	 4. check for no-parent
	 5. check for excludes && includes
	 6. check for suffix
	 7. check for same host (if spanhost is unset), with possible
	 gethostbyname baggage
	 8. check for robots.txt

	 Addendum: If the URL is FTP, and it is to be loaded, only the
	 domain and suffix settings are "stronger".

	 Note that .html and (yuck) .htm will get loaded regardless of
	 suffix rules (but that is remedied later with unlink) unless
	 the depth equals the maximum depth.

	 More time- and memory- consuming tests should be put later on
	 the list.  */

      /* inl is set if the URL we are working on (constr) is stored in
	 undesirable_urls.  Using it is crucial to avoid unnecessary
	 repeated continuous hits to the hash table.  */
      inl = string_set_contains (undesirable_urls, constr);

      /* If it is FTP, and FTP is not followed, chuck it out.  */
      if (!inl)
	if (u->proto == URLFTP && !opt.follow_ftp && !this_url_ftp)
	  {
	    DEBUGP (("Uh, it is FTP but i'm not in the mood to follow FTP.\n"));
	    string_set_add (undesirable_urls, constr);
	    inl = 1;
	  }
      /* If it is absolute link and they are not followed, chuck it
	 out.  */
      if (!inl && u->proto != URLFTP)
	if (opt.relative_only && !cur_url->link_relative_p)
	  {
	    DEBUGP (("It doesn't really look like a relative link.\n"));
	    string_set_add (undesirable_urls, constr);
	    inl = 1;
	  }
      /* If its domain is not to be accepted/looked-up, chuck it out.  */
      if (!inl)
	if (!accept_domain (u))
	  {
	    DEBUGP (("I don't like the smell of that domain.\n"));
	    string_set_add (undesirable_urls, constr);
	    inl = 1;
	  }
      /* Check for parent directory.  */
      if (!inl && opt.no_parent
	  /* If the new URL is FTP and the old was not, ignore
             opt.no_parent.  */
	  && !(!this_url_ftp && u->proto == URLFTP))
	{
	  /* Check for base_dir first.  */
	  if (!(base_dir && frontcmp (base_dir, u->dir)))
	    {
	      /* Failing that, check for parent dir.  */
	      struct urlinfo *ut = newurl ();
	      if (parseurl (this_url, ut, 0) != URLOK)
		DEBUGP (("Double yuck!  The *base* URL is broken.\n"));
	      else if (!frontcmp (ut->dir, u->dir))
		{
		  /* Failing that too, kill the URL.  */
		  DEBUGP (("Trying to escape parental guidance with no_parent on.\n"));
		  string_set_add (undesirable_urls, constr);
		  inl = 1;
		}
	      freeurl (ut, 1);
	    }
	}
      /* If the file does not match the acceptance list, or is on the
	 rejection list, chuck it out.  The same goes for the
	 directory exclude- and include- lists.  */
      if (!inl && (opt.includes || opt.excludes))
	{
	  if (!accdir (u->dir, ALLABS))
	    {
	      DEBUGP (("%s (%s) is excluded/not-included.\n", constr, u->dir));
	      string_set_add (undesirable_urls, constr);
	      inl = 1;
	    }
	}
      if (!inl)
	{
	  char *suf = NULL;
	  /* We check for acceptance/rejection rules only for non-HTML
	     documents.  Since we don't know whether they really are
	     HTML, it will be deduced from (an OR-ed list):

	     1) u->file is "" (meaning it is a directory)
	     2) suffix exists, AND:
	     a) it is "html", OR
	     b) it is "htm"

	     If the file *is* supposed to be HTML, it will *not* be
            subject to acc/rej rules, unless a finite maximum depth has
            been specified and the current depth is the maximum depth. */
	  if (!
	      (!*u->file
	       || (((suf = suffix (constr)) != NULL)
                  && ((!strcmp (suf, "html") || !strcmp (suf, "htm"))
                      && ((opt.reclevel != INFINITE_RECURSION) &&
			  (depth != opt.reclevel))))))
	    {
	      if (!acceptable (u->file))
		{
		  DEBUGP (("%s (%s) does not match acc/rej rules.\n",
			  constr, u->file));
		  string_set_add (undesirable_urls, constr);
		  inl = 1;
		}
	    }
	  FREE_MAYBE (suf);
	}
      /* Optimize the URL (which includes possible DNS lookup) only
	 after all other possibilities have been exhausted.  */
      if (!inl)
	{
	  if (!opt.simple_check)
	    opt_url (u);
	  else
	    {
	      char *p;
	      /* Just lowercase the hostname.  */
	      for (p = u->host; *p; p++)
		*p = TOLOWER (*p);
	      xfree (u->url);
	      u->url = str_url (u, 0);
	    }
	  xfree (constr);
	  constr = xstrdup (u->url);
	  string_set_add (undesirable_urls, constr);
	  if (!inl && !((u->proto == URLFTP) && !this_url_ftp))
	    if (!opt.spanhost && this_url && !same_host (this_url, constr))
	      {
		DEBUGP (("This is not the same hostname as the parent's.\n"));
		string_set_add (undesirable_urls, constr);
		inl = 1;
	      }
	}
      /* What about robots.txt?  */
      if (!inl && opt.use_robots && u->proto == URLHTTP)
	{
	  /* Since Wget knows about only one set of robot rules at a
	     time, /robots.txt must be reloaded whenever a new host is
	     accessed.

	     robots_host holds the host the current `forbid' variable
	     is assigned to.  */
	  if (!robots_host || !same_host (robots_host, u->host))
	    {
	      FREE_MAYBE (robots_host);
	      /* Now make robots_host the new host, no matter what the
		 result will be.  So if there is no /robots.txt on the
		 site, Wget will not retry getting robots all the
		 time.  */
	      robots_host = xstrdup (u->host);
	      free_vec (forbidden);
	      forbidden = NULL;
	      err = retrieve_robots (constr, ROBOTS_FILENAME);
	      if (err == ROBOTSOK)
		{
		  rurl = robots_url (constr, ROBOTS_FILENAME);
		  rfile = url_filename (rurl);
		  forbidden = parse_robots (rfile);
		  freeurl (rurl, 1);
		  xfree (rfile);
		}
	    }

	  /* Now that we have (or don't have) robots, we can check for
	     them.  */
	  if (!robots_match (u, forbidden))
	    {
	      DEBUGP (("Stuffing %s because %s forbids it.\n", this_url,
		       ROBOTS_FILENAME));
	      string_set_add (undesirable_urls, constr);
	      inl = 1;
	    }
	}

      filename = NULL;
      /* If it wasn't chucked out, do something with it.  */
      if (!inl)
	{
	  DEBUGP (("I've decided to load it -> "));
	  /* Add it to the list of already-loaded URL-s.  */
	  string_set_add (undesirable_urls, constr);
	  /* Automatically followed FTPs will *not* be downloaded
	     recursively.  */
	  if (u->proto == URLFTP)
	    {
	      /* Don't you adore side-effects?  */
	      opt.recursive = 0;
	    }
	  /* Reset its type.  */
	  dt = 0;
	  /* Retrieve it.  */
	  retrieve_url (constr, &filename, &newloc,
		       canon_this_url ? canon_this_url : this_url, &dt);
	  if (u->proto == URLFTP)
	    {
	      /* Restore...  */
	      opt.recursive = 1;
	    }
	  if (newloc)
	    {
	      xfree (constr);
	      constr = newloc;
	    }
	  /* If there was no error, and the type is text/html, parse
	     it recursively.  */
	  if (dt & TEXTHTML)
	    {
	      if (dt & RETROKF)
		recursive_retrieve (filename, constr);
	    }
	  else
	    DEBUGP (("%s is not text/html so we don't chase.\n",
		     filename ? filename: "(null)"));

	  if (opt.delete_after || (filename && !acceptable (filename)))
	    /* Either --delete-after was specified, or we loaded this otherwise
	       rejected (e.g. by -R) HTML file just so we could harvest its
	       hyperlinks -- in either case, delete the local file. */
	    {
	      DEBUGP (("Removing file due to %s in recursive_retrieve():\n",
		       opt.delete_after ? "--delete-after" :
		       "recursive rejection criteria"));
	      logprintf (LOG_VERBOSE,
			 (opt.delete_after ? _("Removing %s.\n")
			  : _("Removing %s since it should be rejected.\n")),
			 filename);
	      if (unlink (filename))
		logprintf (LOG_NOTQUIET, "unlink: %s\n", strerror (errno));
	      dt &= ~RETROKF;
	    }

	  /* If everything was OK, and links are to be converted, let's
	     store the local filename.  */
	  if (opt.convert_links && (dt & RETROKF) && (filename != NULL))
	    {
	      cur_url->convert = CO_CONVERT_TO_RELATIVE;
	      cur_url->local_name = xstrdup (filename);
	    }
	}
      else
	DEBUGP (("%s already in list, so we don't load.\n", constr));
      /* Free filename and constr.  */
      FREE_MAYBE (filename);
      FREE_MAYBE (constr);
      freeurl (u, 1);
      /* Increment the pbuf for the appropriate size.  */
    }
  if (opt.convert_links && !opt.delete_after)
    /* This is merely the first pass: the links that have been
       successfully downloaded are converted.  In the second pass,
       convert_all_links() will also convert those links that have NOT
       been downloaded to their canonical form.  */
    convert_links (file, url_list);
  /* Free the linked list of URL-s.  */
  free_urlpos (url_list);
  /* Free the canonical this_url.  */
  FREE_MAYBE (canon_this_url);
  /* Decrement the recursion depth.  */
  --depth;
  if (downloaded_exceeds_quota ())
    return QUOTEXC;
  else
    return RETROK;
}
コード例 #2
0
ファイル: lcc.c プロジェクト: ArtanAhmeti/lab
/* filename - process file name argument `name', return status */
static int filename(char *name, char *base) {
	int status = 0;
	static char *stemp, *itemp;

	if (base == 0)
		base = basename(name);
	switch (suffix(name, suffixes, 4)) {
	case 0:	/* C source files */
		compose(cpp, plist, append(name, 0), 0);
		if (Eflag) {
			status = callsys(av);
			break;
		}
		if (itemp == NULL)
			itemp = tempname(first(suffixes[1]));
		compose(cpp, plist, append(name, 0), append(itemp, 0));
		status = callsys(av);
		if (status == 0)
			return filename(itemp, base);
		break;
	case 1:	/* preprocessed source files */
		if (Eflag)
			break;
		if (Sflag)
			status = compile(name, outfile ? outfile : concat(base, first(suffixes[2])));
		else if ((status = compile(name, stemp?stemp:(stemp=tempname(first(suffixes[2]))))) == 0)
			return filename(stemp, base);
		break;
	case 2:	/* assembly language files */
		if (Eflag)
			break;
		if (!Sflag) {
			char *ofile;
			if (cflag && outfile)
				ofile = outfile;
			else if (cflag)
				ofile = concat(base, first(suffixes[3]));
			else
				ofile = tempname(first(suffixes[3]));
			compose(as, alist, append(name, 0), append(ofile, 0));
			status = callsys(av);
			if (!find(ofile, llist[1]))
				llist[1] = append(ofile, llist[1]);
		}
		break;
	case 3:	/* object files */
		if (!find(name, llist[1]))
			llist[1] = append(name, llist[1]);
		break;
	default:
		if (Eflag) {
			compose(cpp, plist, append(name, 0), 0);
			status = callsys(av);
		}
		llist[1] = append(name, llist[1]);
		break;
	}
	if (status)
		errcnt++;
	return status;
}
コード例 #3
0
void LbmControlData::parseControldataAttrList(AttributeList *attr) {
	// controlpart vars
	mSetForceStrength = attr->readFloat("tforcestrength", mSetForceStrength,"LbmControlData", "mSetForceStrength", false);
	//errMsg("tforcestrength set to "," "<<mSetForceStrength);
	mCpUpdateInterval = attr->readInt("controlparticle_updateinterval", mCpUpdateInterval,"LbmControlData","mCpUpdateInterval", false);
	// tracer output file
	mCpOutfile = attr->readString("controlparticle_outfile",mCpOutfile,"LbmControlData","mCpOutfile", false);
	if(getenv("ELBEEM_CPOUTFILE")) {
		string outfile(getenv("ELBEEM_CPOUTFILE"));
		mCpOutfile = outfile;
		debMsgStd("LbmControlData::parseAttrList",DM_NOTIFY,"Using envvar ELBEEM_CPOUTFILE to set mCpOutfile to "<<outfile<<","<<mCpOutfile,7);
	}

	for(int cpii=0; cpii<10; cpii++) {
		string suffix("");
		//if(cpii>0)
		{  suffix = string("0"); suffix[0]+=cpii; }
		LbmControlSet *cset;
		cset = new LbmControlSet();
		cset->initCparts();

		cset->mContrPartFile = attr->readString("controlparticle"+suffix+"_file",cset->mContrPartFile,"LbmControlData","cset->mContrPartFile", false);
		if((cpii==0) && (getenv("ELBEEM_CPINFILE")) ) {
			string infile(getenv("ELBEEM_CPINFILE"));
			cset->mContrPartFile = infile;
			debMsgStd("LbmControlData::parseAttrList",DM_NOTIFY,"Using envvar ELBEEM_CPINFILE to set mContrPartFile to "<<infile<<","<<cset->mContrPartFile,7);
		}

		LbmFloat cpvort=0.;
		cset->mcRadiusAtt =  attr->readChannelSinglePrecFloat("controlparticle"+suffix+"_radiusatt", 0., "LbmControlData","mcRadiusAtt" );
		cset->mcRadiusVel =  attr->readChannelSinglePrecFloat("controlparticle"+suffix+"_radiusvel", 0., "LbmControlData","mcRadiusVel" );
		cset->mcRadiusVel =  attr->readChannelSinglePrecFloat("controlparticle"+suffix+"_radiusvel", 0., "LbmControlData","mcRadiusVel" );
		cset->mCparts->setRadiusAtt(cset->mcRadiusAtt.get(0.));
		cset->mCparts->setRadiusVel(cset->mcRadiusVel.get(0.));

		// WARNING currently only for first set
		//if(cpii==0) {
		cset->mcForceAtt  =  attr->readChannelSinglePrecFloat("controlparticle"+suffix+"_attraction", 0. , "LbmControlData","cset->mcForceAtt", false);
		cset->mcForceVel  =  attr->readChannelSinglePrecFloat("controlparticle"+suffix+"_velocity",   0. , "LbmControlData","mcForceVel", false);
		cset->mcForceMaxd =  attr->readChannelSinglePrecFloat("controlparticle"+suffix+"_maxdist",    0. , "LbmControlData","mcForceMaxd", false);
		cset->mCparts->setInfluenceAttraction(cset->mcForceAtt.get(0.) );
		// warning - stores temprorarily, value converted to dt dep. factor
		cset->mCparts->setInfluenceVelocity(cset->mcForceVel.get(0.) , 0.01 ); // dummy dt
		cset->mCparts->setInfluenceMaxdist(cset->mcForceMaxd.get(0.) );
		cpvort =  attr->readFloat("controlparticle"+suffix+"_vorticity",   cpvort, "LbmControlData","cpvort", false);
		cset->mCparts->setInfluenceTangential(cpvort);
			
		cset->mcRadiusMind =  attr->readChannelSinglePrecFloat("controlparticle"+suffix+"_radiusmin", cset->mcRadiusMind.get(0.), "LbmControlData","mcRadiusMind", false);
		cset->mcRadiusMaxd =  attr->readChannelSinglePrecFloat("controlparticle"+suffix+"_radiusmax", cset->mcRadiusMind.get(0.), "LbmControlData","mcRadiusMaxd", false);
		cset->mCparts->setRadiusMinMaxd(cset->mcRadiusMind.get(0.));
		cset->mCparts->setRadiusMaxd(cset->mcRadiusMaxd.get(0.));
		//}

		// now local...
		//LbmVec cpOffset(0.), cpScale(1.);
		LbmFloat cpTimescale = 1.;
		string cpMirroring("");

		//cset->mcCpOffset = attr->readChannelVec3f("controlparticle"+suffix+"_offset", ntlVec3f(0.),"LbmControlData","mcCpOffset", false);
		//cset->mcCpScale =  attr->readChannelVec3f("controlparticle"+suffix+"_scale",  ntlVec3f(1.), "LbmControlData","mcCpScale", false);
		cset->mcCpOffset = attr->readChannelVec3f("controlparticle"+suffix+"_offset", ntlVec3f(0.),"LbmControlData","mcCpOffset", false);
		cset->mcCpScale =  attr->readChannelVec3f("controlparticle"+suffix+"_scale",  ntlVec3f(1.), "LbmControlData","mcCpScale", false);
		cpTimescale =  attr->readFloat("controlparticle"+suffix+"_timescale",  cpTimescale, "LbmControlData","cpTimescale", false);
		cpMirroring =  attr->readString("controlparticle"+suffix+"_mirror",  cpMirroring, "LbmControlData","cpMirroring", false);

		LbmFloat cpsWidth = cset->mCparts->getCPSWith();
		cpsWidth =  attr->readFloat("controlparticle"+suffix+"_cpswidth",  cpsWidth, "LbmControlData","cpsWidth", false);
		LbmFloat cpsDt = cset->mCparts->getCPSTimestep();
		cpsDt =  attr->readFloat("controlparticle"+suffix+"_cpstimestep",  cpsDt, "LbmControlData","cpsDt", false);
		LbmFloat cpsTstart = cset->mCparts->getCPSTimeStart();
		cpsTstart =  attr->readFloat("controlparticle"+suffix+"_cpststart",  cpsTstart, "LbmControlData","cpsTstart", false);
		LbmFloat cpsTend = cset->mCparts->getCPSTimeEnd();
		cpsTend =  attr->readFloat("controlparticle"+suffix+"_cpstend",  cpsTend, "LbmControlData","cpsTend", false);
		LbmFloat cpsMvmfac = cset->mCparts->getCPSMvmWeightFac();
		cpsMvmfac =  attr->readFloat("controlparticle"+suffix+"_cpsmvmfac",  cpsMvmfac, "LbmControlData","cpsMvmfac", false);
		cset->mCparts->setCPSWith(cpsWidth);
		cset->mCparts->setCPSTimestep(cpsDt);
		cset->mCparts->setCPSTimeStart(cpsTstart);
		cset->mCparts->setCPSTimeEnd(cpsTend);
		cset->mCparts->setCPSMvmWeightFac(cpsMvmfac);

		cset->mCparts->setOffset( vec2L(cset->mcCpOffset.get(0.)) );
		cset->mCparts->setScale( vec2L(cset->mcCpScale.get(0.)) );
		cset->mCparts->setInitTimeScale( cpTimescale );
		cset->mCparts->setInitMirror( cpMirroring );

		int mDebugInit = 0;
		mDebugInit = attr->readInt("controlparticle"+suffix+"_debuginit", mDebugInit,"LbmControlData","mDebugInit", false);
		cset->mCparts->setDebugInit(mDebugInit);

		// motion particle settings
		LbmVec mcpOffset(0.), mcpScale(1.);
		LbmFloat mcpTimescale = 1.;
		string mcpMirroring("");

		cset->mCpmotionFile = attr->readString("cpmotion"+suffix+"_file",cset->mCpmotionFile,"LbmControlData","mCpmotionFile", false);
		mcpTimescale =  attr->readFloat("cpmotion"+suffix+"_timescale",  mcpTimescale, "LbmControlData","mcpTimescale", false);
		mcpMirroring =  attr->readString("cpmotion"+suffix+"_mirror",  mcpMirroring, "LbmControlData","mcpMirroring", false);
		mcpOffset = vec2L( attr->readVec3d("cpmotion"+suffix+"_offset", vec2P(mcpOffset),"LbmControlData","cpOffset", false) );
		mcpScale =  vec2L( attr->readVec3d("cpmotion"+suffix+"_scale",  vec2P(mcpScale), "LbmControlData","cpScale", false) );

		cset->mCpmotion->setOffset( vec2L(mcpOffset) );
		cset->mCpmotion->setScale( vec2L(mcpScale) );
		cset->mCpmotion->setInitTimeScale( mcpTimescale );
		cset->mCpmotion->setInitMirror( mcpMirroring );

		if(cset->mContrPartFile.length()>1) {
			errMsg("LbmControlData","Using control particle set "<<cpii<<" file:"<<cset->mContrPartFile<<" cpmfile:"<<cset->mCpmotionFile<<" mirr:'"<<cset->mCpmotion->getInitMirror()<<"' " );
			mCons.push_back( cset );
		} else {
			delete cset;
		}
	}

	// debug, testing - make sure theres at least an empty set
	if(mCons.size()<1) {
		mCons.push_back( new LbmControlSet() );
		mCons[0]->initCparts();
	}

	// take from first set
	for(int cpii=1; cpii<(int)mCons.size(); cpii++) {
		mCons[cpii]->mCparts->setRadiusMinMaxd( mCons[0]->mCparts->getRadiusMinMaxd() );
		mCons[cpii]->mCparts->setRadiusMaxd(    mCons[0]->mCparts->getRadiusMaxd() );
		mCons[cpii]->mCparts->setInfluenceAttraction( mCons[0]->mCparts->getInfluenceAttraction() );
		mCons[cpii]->mCparts->setInfluenceTangential( mCons[0]->mCparts->getInfluenceTangential() );
		mCons[cpii]->mCparts->setInfluenceVelocity( mCons[0]->mCparts->getInfluenceVelocity() , 0.01 ); // dummy dt
		mCons[cpii]->mCparts->setInfluenceMaxdist( mCons[0]->mCparts->getInfluenceMaxdist() );
	}
	
	// invert for usage in relax macro
	mDiffVelCon =  1.-attr->readFloat("cpdiffvelcon",  mDiffVelCon, "LbmControlData","mDiffVelCon", false);

	mDebugCpscale     =  attr->readFloat("cpdebug_cpscale",  mDebugCpscale, "LbmControlData","mDebugCpscale", false);
	mDebugMaxdScale   =  attr->readFloat("cpdebug_maxdscale",  mDebugMaxdScale, "LbmControlData","mDebugMaxdScale", false);
	mDebugAttScale    =  attr->readFloat("cpdebug_attscale",  mDebugAttScale, "LbmControlData","mDebugAttScale", false);
	mDebugVelScale    =  attr->readFloat("cpdebug_velscale",  mDebugVelScale, "LbmControlData","mDebugVelScale", false);
	mDebugCompavScale =  attr->readFloat("cpdebug_compavscale",  mDebugCompavScale, "LbmControlData","mDebugCompavScale", false);
	mDebugAvgVelScale =  attr->readFloat("cpdebug_avgvelsc",  mDebugAvgVelScale, "LbmControlData","mDebugAvgVelScale", false);
}
コード例 #4
0
ファイル: RunMyJob.C プロジェクト: hkaushalya/CDFPhoJets
//void RunMyJob (int events = -1, int dataset=0, const int tightencut=1)
void RunMyJob (int events = -1, int dataset=0, int stupleVer=7)
{
	std::cout << "events, dataset = " << events << "," << dataset << std::endl;
	gROOT->Reset();
	gSystem->Load("$ROOTSYS/lib/libPhysics.so");
	//if (gSystem->Load("../RootTools/CommonTools_cc.so") == 0)
	{
	//	gSystem->Load("../RoooTools/CommonTools_cc.so");
	}

	// gROOT->LoadMacro() method does not seeme to return 1 when the compilation is a success.
	// not sure why . but gSystem->CompileMacro does
	//int st = gROOT->LoadMacro("Stuple.cc+");
	//
	std::vector<std::string> vLibs;
	//vLibs.push_back("Stuple.cc");
	//vLibs.push_back("../RootTools/CommonTools.cc");
	vLibs.push_back("PhotonList.cc");
	vLibs.push_back("ElectronList.cc");
	vLibs.push_back("JetList.cc");
	vLibs.push_back("CommonVars.cc");
	vLibs.push_back("ReadInAll.cc");
	vLibs.push_back("FreeFunctions.cc");
	vLibs.push_back("Histograms.cc");
	vLibs.push_back("HistManager.cc");
	vLibs.push_back("HaloTypes.cc");
	vLibs.push_back("NewJetList.cc");
	vLibs.push_back("HaloStudy.cc");
	vLibs.push_back("HaloStudy_DelR.cc");
	vLibs.push_back("PhotonJets.cc");
	  vLibs.push_back("HaloJetsTemp.cc");
	  vLibs.push_back("EleFakeRate.cc");
	  vLibs.push_back("EleJetsTemp.cc");
	  vLibs.push_back("LooseEleJetsTemp.cc");
	  vLibs.push_back("CosmicJetsTemp.cc");
	  vLibs.push_back("QCDJetsTemp.cc");
	  vLibs.push_back("SidebandHalos.cc");
	  vLibs.push_back("HaloIdEff.cc");
	  vLibs.push_back("MCPhotonJets.cc");
	  vLibs.push_back("ReadInAll_4StUpgrade.cc");
	  vLibs.push_back("UpgradeStuple.cc");
	  vLibs.push_back("ewkMCPhotonJets.cc");
	vLibs.push_back("LoosePhoCuts.cc");
	  vLibs.push_back("Systematics.cc");
	 vLibs.push_back("CosmicNoVtx.cc");
	vLibs.push_back("PhotonTriggerStudy.cc");
	vLibs.push_back("QCDSystematics.cc");
	//must load this last, otherwise there'll be dlopen errors!
	vLibs.push_back("ZSel.cc");
	vLibs.push_back("WSel.cc");
	vLibs.push_back("ZJetSel.cc");
	vLibs.push_back("WJetSel.cc");
	vLibs.push_back("DoRunMyJob.cc");


	bool bReady = true;
	for (unsigned i=0; i<vLibs.size(); ++i)
	{
		if (gSystem->CompileMacro(vLibs[i].c_str(),"k") == 1) continue;
		bReady = false;
		break;
	}

	if (! bReady) 
	{
		//gSystem->ListLibraries();
		std::cout << __FILE__ << ":: NOT ALL REQUIRED LIBRARIES ARE LOADED PROPERLY!" << std::endl;
		return;
	}
	// gObjectTable->Print();
	
	gSystem->Setenv("REWGT_SIDEBAND","0");
	gSystem->Setenv("ADD_ISO_2_SIDEBAND","0");

	//change file name for testing. DON'T BE LAZY! and mess up!
	//std::string prefix("/data/nbay04/c/samantha/PhoFlatResults/ICHEP_LaptopVersion/p1_26/PhoJets_");
	std::string prefix("/data/nbay04/c/samantha/PhoFlatResults/ICHEP_LaptopVersion/p1_26/NvtxWgtAndMetCleaned_final/PhoJets_");
	//std::string prefix("WJets_");
	//std::string prefix("PhoJets_Cosmics");
	//std::string prefix("~/ICHEP_LaptopVersion/p1_26/NvtxWgtAndMetCleaned_final_PhoEt200/PhoJets_");
	//std::string prefix("~/ICHEP_LaptopVersion/p1_26/NvtxWgtAndMetCleaned_Met20_final/PhoJets_");
	//std::string prefix("~/ICHEP_LaptopVersion/p1_26/NvtxWgtAndMetCleaned_final/NvtxWgting_dibo_ttbar/PhoJets_");
	//std::string prefix("~/ICHEP_LaptopVersion/p1_26/NvtxWgtAndMetCleaned_Met20_final/WJetsStudy/Incl2Jet/WJets_2InclNjet15_");
	//std::string suffix("_Met50_NvtxSigmaWgtd_MetCleaned.root");
	//std::string suffix("_Met20NvtxWgtedCleaned.root");
	//std::string suffix("_Met30NvtxWgtdCleaned.root");
	//std::string suffix("_Met50.root");
	std::string suffix("_BuckleysWgZgTest.root");
	//std::string suffix("_Test.root");

	std::string sdataset("unknown");
	if (dataset == 1 || dataset == 50) sdataset = "data";
	//else if (dataset == 2) sdataset = "phomc";
	else if (dataset == 2) sdataset = "phomcWithMB";
	else if (dataset == 3) sdataset = "zeemc";
	else if (dataset == 4) sdataset = "zmmmc";
	else if (dataset == 5) sdataset = "zttmc";
	else if (dataset == 6) sdataset = "wenmc";
	else if (dataset == 7) sdataset = "wmnmc";
	else if (dataset == 8) sdataset = "wtnmc";
	else if (dataset == 9) sdataset = "diphomc";
	else if (dataset == 10) sdataset = "wwmc";
	else if (dataset == 11) sdataset = "wzmc";
	else if (dataset == 12) sdataset = "zzmc";
	else if (dataset == 13) sdataset = "ttbarmc";
	else if (dataset == 70) sdataset = "Wgmc";
	else if (dataset == 80) sdataset = "Zgmc";



	std::string sRewgt("");
	std::string rewgt(gSystem->Getenv("REWGT_SIDEBAND"));
	if (rewgt.length()>0)
	{
		if (atoi(rewgt.c_str()) == 1) sRewgt += "_SidebandNominalWgtByPhoEtAndJetEta_";
		else if (atoi(rewgt.c_str()) == 2) sRewgt += "_SidebandSigmaWgtByPhoEtAndJetEta_";
		else if (atoi(rewgt.c_str()) == 3) sRewgt += "_SidebandNominalWgtByPhoEt_";
		else if (atoi(rewgt.c_str()) == 4) sRewgt += "_SidebandSigmaWgtByPhoEt_";
	}
		
	
	std::ostringstream outfilename;
	outfilename << prefix << sdataset << sRewgt << suffix;
	gSystem->Setenv("OUT_FILE",outfilename.str().c_str());
	//gSystem->Setenv("OUT_FILE","PhoJets_wenmc_g30_withsideband_03282010.root");
	
	//DoRunMyJob (events, dataset, tightencut);
	//DoRunMyJob (events, dataset, stupleVer);
	//gObjectTable->Print();
}
コード例 #5
0
ファイル: vcf_materialization.cpp プロジェクト: IsmailM/seqan
void VcfMaterializer::_appendToVariants(Variants & variants, seqan::VcfRecord const & vcfRecord)
{
    // Compute maximal length of alternative.
    unsigned altLength = 0;
    seqan::StringSet<seqan::CharString> alts;
    strSplit(alts, vcfRecord.alt, seqan::EqualsChar<','>());
    for (unsigned i = 0; i < length(alts); ++i)
        altLength = std::max(altLength, (unsigned)length(alts[i]));

    if (contains(vcfRecord.info, "SVTYPE"))  // Structural Variant
    {
        StructuralVariantRecord svRecord;
        svRecord.rId = vcfRecord.rID;
        svRecord.pos = vcfRecord.beginPos + 1;  // given with shift of -1
        svRecord.haplotype = 0;

        SEQAN_ASSERT_EQ(length(alts), 1u);

        if (contains(vcfRecord.info, "SVTYPE=INS"))  // Insertion
        {
            svRecord.kind = StructuralVariantRecord::INDEL;
            svRecord.size = getSVLen(vcfRecord.info);
            svRecord.seq = suffix(vcfRecord.alt, 1);
        }
        else if (contains(vcfRecord.info, "SVTYPE=DEL"))  // Deletion
        {
            svRecord.kind = StructuralVariantRecord::INDEL;
            svRecord.size = getSVLen(vcfRecord.info);
        }
        else if (contains(vcfRecord.info, "SVTYPE=INV"))  // Inversion
        {
            svRecord.kind = StructuralVariantRecord::INVERSION;
            svRecord.size = getSVLen(vcfRecord.info);
        }
        else if (contains(vcfRecord.info, "SVTYPE=DUP"))  // Duplication
        {
            svRecord.kind = StructuralVariantRecord::DUPLICATION;
            svRecord.size = getSVLen(vcfRecord.info);
            std::pair<seqan::CharString, int> pos = getTargetPos(vcfRecord.info);
            unsigned idx = 0;
            if (!getIdByName(idx, contigNamesCache(context(vcfFileIn)), pos.first))
                SEQAN_FAIL("Unknown sequence %s", toCString(pos.first));
            svRecord.targetRId = idx;
            svRecord.targetPos = pos.second - 1;
        }
        else if (contains(vcfRecord.info, "SVTYPE=BND"))  // Breakend (Must be Translocation)
        {
            SEQAN_FAIL("Unexpected 'SVTYPE=BND' at this place!");
        }
        else
        {
            SEQAN_FAIL("ERROR: Unknown SVTYPE!\n");
        }

        // Split the target variants.
        SEQAN_ASSERT_NOT(empty(vcfRecord.genotypeInfos));
        seqan::DirectionIterator<seqan::CharString const, seqan::Input>::Type inputIter =
                directionIterator(vcfRecord.genotypeInfos[0], seqan::Input());
        seqan::CharString buffer;
        svRecord.haplotype = 0;
        for (; !atEnd(inputIter); ++inputIter)
            if ((*inputIter == '|' || *inputIter == '/'))
            {
                if (!empty(buffer))
                {
                    unsigned idx = std::min(seqan::lexicalCast<unsigned>(buffer), 1u);
                    if (idx != 0u)  // if not == ref
                        appendValue(variants.svRecords, svRecord);
                }
                svRecord.haplotype++;
                clear(buffer);
            }
            else
            {
                appendValue(buffer, *inputIter);
            }
        if (!empty(buffer))
        {
            unsigned idx = std::min(seqan::lexicalCast<unsigned>(buffer), 1u);
            if (idx != 0u)  // if not == ref
                appendValue(variants.svRecords, svRecord);
        }
    }
    else if (length(vcfRecord.ref) == 1u && altLength == 1u)  // SNP
    {
        SnpRecord snpRecord;
        snpRecord.rId = vcfRecord.rID;
        snpRecord.pos = vcfRecord.beginPos;

        // Split the alternatives.
        seqan::StringSet<seqan::CharString> alternatives;
        strSplit(alternatives, vcfRecord.alt, seqan::EqualsChar<','>());

        // Split the target variants.
        SEQAN_ASSERT_NOT(empty(vcfRecord.genotypeInfos));
        seqan::DirectionIterator<seqan::CharString const, seqan::Input>::Type inputIter =
                directionIterator(vcfRecord.genotypeInfos[0], seqan::Input());
        seqan::CharString buffer;
        snpRecord.haplotype = 0;
        for (; !atEnd(inputIter); ++inputIter)
            if ((*inputIter == '|' || *inputIter == '/'))
            {
                if (!empty(buffer))
                {
                    unsigned idx = std::min(seqan::lexicalCast<unsigned>(buffer),
                                            (unsigned)length(alternatives));
                    if (idx != 0u)  // if not == ref
                    {
                        SEQAN_ASSERT_NOT(empty(alternatives[idx - 1]));
                        snpRecord.to = alternatives[idx - 1][0];
                        appendValue(variants.snps, snpRecord);
                    }
                }
                snpRecord.haplotype++;
                clear(buffer);
            }
            else
            {
                appendValue(buffer, *inputIter);
            }
        if (!empty(buffer))
        {
            unsigned idx = std::min(seqan::lexicalCast<unsigned>(buffer),
                                    (unsigned)length(alternatives));
            if (idx != 0u)  // if not == ref
            {
                SEQAN_ASSERT_NOT(empty(alternatives[idx - 1]));
                snpRecord.to = alternatives[idx - 1][0];
                appendValue(variants.snps, snpRecord);
            }
        }
    }
    else  // Small Indel
    {
        SmallIndelRecord smallIndel;
        smallIndel.rId = vcfRecord.rID;
        smallIndel.pos = vcfRecord.beginPos + 1;

        SEQAN_ASSERT_NOT(contains(vcfRecord.alt, ","));  // only one alternative
        SEQAN_ASSERT((length(vcfRecord.alt) == 1u) != (length(vcfRecord.ref) == 1u));  // XOR

        smallIndel.haplotype = 0;
        if (length(vcfRecord.ref) == 1u)  // insertion
        {
            smallIndel.seq = suffix(vcfRecord.alt, 1);
            smallIndel.size = length(smallIndel.seq);
        }
        else  // deletion
        {
            smallIndel.size = -(int)(length(vcfRecord.ref) - 1);
        }

        // Split the target variants.
        SEQAN_ASSERT_NOT(empty(vcfRecord.genotypeInfos));
        seqan::DirectionIterator<seqan::CharString const, seqan::Input>::Type inputIter =
                directionIterator(vcfRecord.genotypeInfos[0], seqan::Input());
        seqan::CharString buffer;
        smallIndel.haplotype = 0;
        for (; !atEnd(inputIter); ++inputIter)
            if ((*inputIter == '|' || *inputIter == '/'))
            {
                if (!empty(buffer))
                {
                    unsigned idx = std::min(seqan::lexicalCast<unsigned>(buffer), 1u);
                    if (idx != 0u)  // if not == ref
                        appendValue(variants.smallIndels, smallIndel);
                }
                smallIndel.haplotype++;
                clear(buffer);
            }
            else
            {
                appendValue(buffer, *inputIter);
            }
        if (!empty(buffer))
        {
            unsigned idx = std::min(seqan::lexicalCast<unsigned>(buffer), 1u);
            if (idx != 0u)  // if not == ref
                appendValue(variants.smallIndels, smallIndel);
        }
    }
}
コード例 #6
0
ファイル: SRAssembler.cpp プロジェクト: hsienchao/SRAssembler
void SRAssembler::do_preprocessing(int lib_idx, int file_part){
	Library lib = this->libraries[lib_idx];

	logger->info("preprocessing lib " + int2str(lib_idx + 1) + ", reads file (" + int2str(file_part) + "/" + int2str(lib.get_num_parts()) + ")");
	char suffixc[3];
	suffixc[0] = (char)(((file_part-1) / 26) + 97);
	suffixc[1] = (char)(((file_part-1) % 26) + 97);
	suffixc[2] = '\0';
	string suffix(suffixc);
	string left_src_read = lib.get_prefix_split_src_file(lib.get_left_read()) + suffix;
	string right_src_read = "";
	if (lib.get_paired_end())
	    right_src_read = lib.get_prefix_split_src_file(lib.get_right_read()) + suffix;
	ifstream left_file(left_src_read.c_str());
	ifstream right_file;
	if (lib.get_paired_end()){
		right_file.open(right_src_read.c_str(), ios_base::in);
	}
	string left_header = "";
	string right_header = "";
	string left_seq = "";
	string right_seq = "";
	string left_qual = "";
	string right_qual = "";
	string plus;
	ofstream split_read_fasta_file;
	ofstream split_read_fastq_file;
	split_read_fasta_file.open(lib.get_split_file_name(file_part, FORMAT_FASTA).c_str(), ios_base::out);
	if (lib.get_format() == FORMAT_FASTQ)
	    split_read_fastq_file.open(lib.get_split_file_name(file_part, FORMAT_FASTQ).c_str(), ios_base::out);
	while (getline(left_file, left_header)) {
		// get read data point, which includes 4 lines
		string lead_chr = (lib.get_format() == FORMAT_FASTQ)? "@" : ">";
		if (left_header.substr(0,1) == lead_chr){
		 //save left-end reads
			getline(left_file, left_seq);
			if (lib.get_format() == FORMAT_FASTQ) {
				getline(left_file, plus);
				getline(left_file, left_qual);
			}
			if (lib.get_paired_end()){
				 //save right-end reads
				 while (getline(right_file, right_header))
					 if (right_header.substr(0,1) == lead_chr)
						 break;
				 getline(right_file, right_seq);
				 if (lib.get_format() == FORMAT_FASTQ) {
					 getline(right_file, plus);
					 getline(right_file, right_qual);
				 }
			}
			if (lib.get_format() == FORMAT_FASTQ) {
				split_read_fastq_file << left_header << endl
									  << left_seq << endl
									  << "+" << endl
									  << left_qual << endl;
			}
			split_read_fasta_file << ">" << left_header.substr(1) << endl << left_seq << endl;
			if (lib.get_paired_end()){
				if (lib.get_format() == FORMAT_FASTQ) {
					split_read_fastq_file << right_header << endl
								 << right_seq << endl
								 << "+" << endl
								 << right_qual << endl;
				}
				split_read_fasta_file << ">" << right_header.substr(1) << endl << right_seq << endl;
			}
		 }
	}
	split_read_fasta_file.close();
	if (lib.get_format() == FORMAT_FASTQ)
		split_read_fastq_file.close();
	left_file.close();
	if (lib.get_paired_end())
		right_file.close();
	string cmd = "rm " + left_src_read + " " + right_src_read;
	run_shell_command(cmd);
}
コード例 #7
0
ファイル: BigNumDelegate.cpp プロジェクト: VSRonin/CLOModel
void BigNumDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    bool selected = option.state & QStyle::State_Selected;
    bool mouseOver = option.state & QStyle::State_MouseOver;
    QPalette palette(option.palette);
    if (selected){
        palette.setBrush(QPalette::Active, QPalette::Window, option.palette.highlight());
        palette.setBrush(QPalette::Active, QPalette::WindowText, option.palette.highlightedText());
    }
    else if (mouseOver) {
        palette.setBrush(QPalette::Active, QPalette::Window, option.palette.button());
        palette.setBrush(QPalette::Active, QPalette::WindowText, option.palette.buttonText());
    }
    else{
        palette.setBrush(QPalette::Active, QPalette::Window, option.palette.base());
        palette.setBrush(QPalette::Active, QPalette::WindowText, option.palette.text());
    }
    QRect labelRect(option.rect.x(), option.rect.y(), option.rect.width(), option.rect.height());
    if (m_adjustPadding)
        labelRect.adjust(LabelPadding, LabelPadding, -(2 * LabelPadding), -(2 * LabelPadding));
    m_label->setPalette(palette);
    m_label->setFixedSize(qMax(0, labelRect.width()), labelRect.height());
    if (index.model()->data(index, Qt::DisplayRole).isNull()) {
        m_label->clear();
    }
    else {
        m_label->setText(
            (index.model()->data(index, CustomStyleRole).toString().contains("%1") ? index.model()->data(index, CustomStyleRole).toString() : QString("%1"))
            .arg(prefix() + m_label->locale().toString(index.model()->data(index, Qt::DisplayRole).toDouble(), 'f', decimals()) + suffix())
        );
    }
    if (index.model()->data(index, Qt::TextAlignmentRole).isNull())
        m_label->setAlignment(Qt::AlignRight | Qt::AlignVCenter);
    else
        m_label->setAlignment(Qt::Alignment(index.model()->data(index, Qt::TextAlignmentRole).toInt()));
    QPixmap pixmap(m_label->size());
    m_label->render(&pixmap);
    painter->drawPixmap(labelRect, pixmap);
}
コード例 #8
0
ファイル: main.cpp プロジェクト: rulk/eyerie-ogitor-fork
//-------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------
int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    QDir::setCurrent(a.applicationDirPath());

    // See if we are loading something from the commandline.
    QString fileArg("");
    QString suffix("");
    QString argument = a.arguments().last();
    QFileInfo info(a.arguments().last());
    if(info.exists() && info.isFile())
    {
        if(info.suffix() == "ogscene")
        {
            // Yes we've got an ogscene file to load.
            fileArg = info.absoluteFilePath();
            suffix = info.suffix();
        }
        else if(info.baseName() != "qtOgitor" && info.baseName() != "qtOgitor_d"  )
        {
            // We are trying to load something we can't load
            // Exit the application.
            QMessageBox msg(QMessageBox::Critical, "Ogitor Error", "We can only load Ogitor Scenes.\nExiting..");
            msg.exec();
            return 0;
        }
    }

    a.setOrganizationName("Ogitor");
    a.setApplicationName("qtOgitor");

#if(OGRE_PLATFORM == OGRE_PLATFORM_APPLE)
    QFile file(":/stylesheets/osx.qss");
#else
    QFile file(":/stylesheets/obsidian.qss");
#endif
    file.open(QFile::ReadOnly);
    QString styleSheet = QLatin1String(file.readAll());
    a.setStyleSheet(styleSheet);

    QSettings settings;
    QString languageFile = settings.value("preferences/customLanguage").toString();

    QTranslator qtTranslator;
    QTranslator ogitorTranslator;

    if(languageFile != "ogitor_en.qm")
    {
        QString lang = "../languages/qt_" + languageFile;
        lang.remove("ogitor_");

        QString lang2 = "../languages/" + languageFile;

        if(QFile::exists(lang) && QFile::exists(lang2))
        {
            if(qtTranslator.load(lang))
                a.installTranslator(&qtTranslator);

            if(ogitorTranslator.load(lang2))
                a.installTranslator(&ogitorTranslator);
        }
        else
        {    
            // If the system-wide Qt translation file is present, load it.
            if(qtTranslator.load("qt_" + QLocale::system().name(),
                QLibraryInfo::location(QLibraryInfo::TranslationsPath)))
            {
                a.installTranslator(&qtTranslator);
            }
            // Otherwise: load our own Qt translation file.
            else if(qtTranslator.load("../languages/qt_" + QLocale::system().name()))
            {
                a.installTranslator(&qtTranslator);
            }

            // Install qtOgitor translator
            if(ogitorTranslator.load("../languages/ogitor_" + QLocale::system().name()))
            {
                a.installTranslator(&ogitorTranslator);
            }
        }
    }

    bool skipSplash = settings.value("preferences/skipSplash", false).toBool();

    QSplashScreen *splash;
    if(!skipSplash)
    {
        QPixmap pixmap(":/images/OgitorLogo.png");
        splash = new QSplashScreen(pixmap);
        splash->show();
    }

#ifdef _DEBUG
    setupOgre(resourcePath() + Ogre::String("plugins_debug.cfg"), Ogre::String("ogre.cfg"), Ogre::String("ogitor.log"));
#else
    setupOgre(resourcePath() + Ogre::String("plugins.cfg"), Ogre::String("ogre.cfg"), Ogre::String("ogitor.log"));
#endif

    readRecentFiles(settings);

    mOgitorMainWindow = new MainWindow();
    mOgitorMainWindow->show();
    
    mOgitorMainWindow->setApplicationObject(&a);

    QString sceneToLoad = "";
    QString lastLoadedScene = settings.value("preferences/lastLoadedScene", "").toString();
    if((settings.value("preferences/loadLastLoadedScene", false).toBool()) && (fileArg.isEmpty()))
    {
        if(!lastLoadedScene.isEmpty())
        {
            sceneToLoad = lastLoadedScene;
        }
    }
    else if(!fileArg.isEmpty())
    {
        sceneToLoad = fileArg;
    }

    if(!sceneToLoad.isEmpty())
    {
        if(suffix == "material")
        {
        }
        else
        {
            Ogitors::OgitorsRoot::getSingletonPtr()->LoadScene(sceneToLoad.toStdString());
        }
    }

    mOgitorMainWindow->repaint();

    if(!skipSplash)
    {
        splash->finish(mOgitorMainWindow);
        delete splash;
    }

    int retval = a.exec();

    writeRecentFiles();

    delete mOgitorMainWindow;
    delete shortCuts;
    OGRE_DELETE mOgitorsRoot;
    OGRE_DELETE mSystem;
    OGRE_DELETE mOgreRoot;

    return retval;
}
コード例 #9
0
ファイル: alias.c プロジェクト: asvitkine/phxd
/* alias
   -----
   Will create a Macintosh HFS  specific  alias at the path
   pointed to by dest.  The  alias  will  point to the file
   located at target. The target must exist.

   The return value is zero upon success.  If unsuccessful,
   a  non-zero value will be  returned and both  errno  and
   mac_errno should be consulted.
*/
int alias (const char *target, const char *dest)
{
   char *rtarget;
   char *destparentdir, *destname;
#ifdef HAVE_CORESERVICES
   char *targetsuffix;
   UniChar *udestname;
   FSRef *fstarget, *fsdest, *fsnewfile;
   FSCatalogInfo *fscdestinfo, *fsctargetinfo;
   FileInfo destinfo, targetinfo;
   AliasHandle aliasrec;
   u_int32_t infomap = 0;
   int resfrk;
   u_int8_t targetisdir = 0;
#endif
   u_int8_t destisdir = 0;
   size_t len = 0;

#ifndef HAVE_CORESERVICES
   /* this function is for creating macintosh aliases.
      if we don't have the CoreServices API it's impossible,
      so why fool ourselves, let's just return error now
      and save the cpu cycles for something else */

   errno = EIO; /* returning a generic I/O error */
   return errno;
#endif

   /* As of this writing,  this  function is not  complete.
      Things left to  complete are to  check the  target to
      see if it has a custom icon (if so,  copy the  custom
      to the alias file so that they appear the same. Also,
      copy custom icons of bundles to the alias.

      Another very  important thing left to  complete is to
      retire the process of making the alias  manually to a
      last resort if we cannot create the  alias by sending
      an apple event to the finder.
   */

   /* check for null parameters and return accordingly */
   if (!target || !dest) return 0;

#ifdef HAVE_CORESERVICES

   rtarget = (char *)malloc(PATH_MAX);
   if (!rtarget) return errno; /* ENOMEM */

   if (!resolve_alias(target, rtarget) || mac_errno)
      return errno;

   /* convert the target path into an FSRef */
  
   fstarget = (FSRef *)malloc(sizeof(FSRef));
   if (!fstarget) return errno; /* ENOMEM */
 
   mac_errno = FSPathMakeRef(rtarget, fstarget, &targetisdir);
   if (mac_errno) return 0;

   fsdest = (FSRef *)malloc(sizeof(FSRef));
   if (!fsdest) return errno; /* ENOMEM */

   /* convert the destination into an FSRef so that we can test if it exists
      and if it is a directory (in which we should save the new alias file
      inside the directory specified) */
   mac_errno = FSPathMakeRef(dest, fsdest, &destisdir);

#endif

   /* if the destination is not a directory, we'll disassemble the path we
      were given for the destination into a parent directory and a name */
   if (!destisdir) {

      /* obtain the name of the destination file */
      len = strlen(dest);
      destname = (char *)dest + len;
      while (destname > dest && *(destname - 1) != '/') destname--, len--;

      /* obtain the parent directory of the destination file */
      destparentdir = (char *)malloc(len);
      snprintf(destparentdir, len ? len + 1 : 3, "%s", len ? dest : "./");

   } else {

      /* the parent directory should be the destination we were passed */
      destparentdir = (char *)dest;

      /* and the name should be the real name of the target */
      destname = (char *)rtarget + strlen(rtarget);
      while (destname > rtarget && *(destname - 1) != '/') destname--;

   }

#ifdef HAVE_CORESERVICES

   /* attempt to convert the parent directory into an FSRef */
   mac_errno = FSPathMakeRef(destparentdir, fsdest, 0);
   if (mac_errno) return 0;

   /* infomap is an integer telling FSCreateResFile which settings from
      the FSCatalogInfo paramater you want to set */
   infomap |= kFSCatInfoFinderInfo;

   /* if the target is not a directory, get its file type/creator */
   if (!targetisdir) {

      fsctargetinfo = (FSCatalogInfo *)malloc(sizeof(FSCatalogInfo));
      if (!fsctargetinfo) return errno; /* ENOMEM */

      /* get the target files information */
      mac_errno = FSGetCatalogInfo(fstarget, infomap, fsctargetinfo, 0,0,0);
      if (mac_errno) return 0;

      /* I don't know why Apple did not declare the structure member
         'finderInfo' as an FileInfo type (it is an array of 16 single bytes).
         This makes it impossible to address elements of the finderInfo
         directly. So, we move it into an FileInfo data type we allocated */
      memmove(&targetinfo, fsctargetinfo->finderInfo, sizeof(FileInfo));

      /* this is not really necessary for the creation of the file, since
         a null type or creator will be transposed to '????', but should any
         functions try to display the type/creator, it is much friendlier to
         display '????' than an empty string (which hardcore mac people will
         understand better */
      if (!targetinfo.fileType) {
         targetinfo.fileType = '\?\?\?\?';
         targetinfo.fileCreator = '\?\?\?\?';
      }

   } else {

      /* folders natively return null as their file type and creator but to
         make an alias appear as a folder, we use the following settings */
      targetinfo.fileType = 'fldr';
      targetinfo.fileCreator = 'MACS';

      /* there is one exception, when the folder ends in .app it is an
         application package and should get the following settings */
      targetsuffix = suffix(rtarget);
      if (!strcmp(targetsuffix, "app")) {
         targetinfo.fileType = 'fapa';
         targetinfo.fileCreator = '\?\?\?\?';
         *--targetsuffix = '\0'; /* this will cut off the .app from the name */
      }

   }

   fscdestinfo = (FSCatalogInfo *)malloc(sizeof(FSCatalogInfo));
   if (!fscdestinfo) return errno; /* ENOMEM */

   /* set the file type, creator, and alias flag for the file */
   destinfo.fileType    = targetinfo.fileType;
   destinfo.fileCreator = targetinfo.fileCreator;
   destinfo.finderFlags = kIsAlias;
   memcpy(fscdestinfo->finderInfo, &destinfo, sizeof(FileInfo));

   fsnewfile = (FSRef *)malloc(sizeof(FSRef));
   if (!fsnewfile) return errno; /* ENOMEM */

   udestname = (UniChar *)malloc(PATH_MAX);
   len = utf8to16(destname, udestname, PATH_MAX);
   if (len < 0) return errno; /* caller: consult both errno and mac_errno */

   /* attempt to create the resource file (fails if it already exists) */
   FSCreateResFile(fsdest, len, udestname, infomap, fscdestinfo, fsnewfile, 0);

   free(udestname);

   /* test for error creating the file */
   mac_errno = ResError();
   if (mac_errno) return 0;

   /* attempt to open the resource fork of the file now */
   resfrk = FSOpenResFile(fsnewfile, fsRdWrPerm);

   /* test for errors */
   mac_errno = ResError();
   if (mac_errno) return 0;

   /* attempt to create an alias record to save in the resource file */
   mac_errno = FSNewAlias(0, fstarget, &aliasrec);
   if (mac_errno) return CloseResFile(resfrk), 0;

   /* add the alias record to the resource fork */
   AddResource((Handle)aliasrec, rAliasType, 0, 0);

   /* test for errors */
   mac_errno = ResError();
   if (mac_errno) return CloseResFile(resfrk), 0;

   /* write the resource fork data */
   WriteResource((Handle)aliasrec);

   /* test for errors */
   mac_errno = ResError();
   if (mac_errno) return CloseResFile(resfrk), 0;

   /* clean up */
   CloseResFile(resfrk);

#endif /* HAVE_CORESERVICES */

   /* return success */
   return 0;

}
コード例 #10
0
static
bool
do_change_version(atrt_config& config, SqlResultSet& command,
                  AtrtClient& atrtdb){
  /**
   * TODO make option to restart "not" initial
   */
  uint process_id= command.columnAsInt("process_id");
  const char* process_args= command.column("process_args");

  g_logger.info("Change version for process: %d, args: %s",
                process_id, process_args);

  // Get the process
  if (process_id > config.m_processes.size()){
    g_logger.critical("Invalid process id %d", process_id);
    return false;
  }
  atrt_process& proc= *config.m_processes[process_id];

  const char* new_prefix= g_prefix1 ? g_prefix1 : g_prefix;
  const char* old_prefix= g_prefix;
  const char *start= strstr(proc.m_proc.m_path.c_str(), old_prefix);
  if (!start){
    /* Process path does not contain old prefix.  
     * Perhaps it contains the new prefix - e.g. is already
     * upgraded?
     */
    if (strstr(proc.m_proc.m_path.c_str(), new_prefix))
    {
      /* Process is already upgraded, *assume* that this
       * is ok
       * Alternatives could be - error, or downgrade.
       */
      g_logger.info("Process already upgraded");
      return true;
    }
      
    g_logger.critical("Could not find '%s' in '%s'",
                      old_prefix, proc.m_proc.m_path.c_str());
    return false;
  }

  // Save current proc state
  if (proc.m_save.m_saved == false)
  {
    proc.m_save.m_proc= proc.m_proc;
    proc.m_save.m_saved= true;
  }
  
  g_logger.info("stopping process...");
  if (!stop_process(proc))
    return false;
  BaseString newEnv = set_env_var(proc.m_proc.m_env, 
                                  BaseString("MYSQL_BASE_DIR"),
                                  BaseString(new_prefix));
  proc.m_proc.m_env.assign(newEnv);
  BaseString suffix(proc.m_proc.m_path.substr(strlen(old_prefix)));
  proc.m_proc.m_path.assign(new_prefix).append(suffix);
  if (process_args && strlen(process_args))
  {
    /* Beware too long args */
    proc.m_proc.m_args.append(" ");
    proc.m_proc.m_args.append(process_args);
  }

  ndbout << proc << endl;

  g_logger.info("starting process...");
  if (!start_process(proc))
    return false;
  return true;
}
コード例 #11
0
// Classes are included for queues only (not for queue classes)
string
SQueueParameters::GetPrintableParameters(bool  include_class,
                                         bool  url_encoded) const
{
    string      result;

    /* Initialized for multi-line output */
    string      prefix("OK:");
    string      suffix(": ");
    string      separator("\n");

    if (url_encoded) {
        prefix    = "";
        suffix    = "=";
        separator = "&";
    }

    if (include_class) {
        // These parameters make sense for queues only
        result = prefix + "kind" + suffix;
        if (kind == CQueue::eKindStatic)
            result += "static" + separator;
        else
            result += "dynamic" + separator;

        result +=
        prefix + "position" + suffix + NStr::NumericToString(position) + separator +
        prefix + "qclass" + suffix + qclass + separator +
        prefix + "refuse_submits" + suffix + NStr::BoolToString(refuse_submits) + separator +
        prefix + "max_aff_slots" + suffix + NStr::NumericToString(max_aff_slots) + separator +
        prefix + "aff_slots_used" + suffix + NStr::NumericToString(aff_slots_used) + separator +
        prefix + "clients" + suffix + NStr::NumericToString(clients) + separator +
        prefix + "groups" + suffix + NStr::NumericToString(groups) + separator +
        prefix + "gc_backlog" + suffix + NStr::NumericToString(gc_backlog) + separator +
        prefix + "notif_count" + suffix + NStr::NumericToString(notif_count) + separator;
    }

    result +=
    prefix + "delete_request" + suffix + NStr::BoolToString(delete_request) + separator +
    prefix + "timeout" + suffix + NStr::NumericToString(timeout) + separator +
    prefix + "notif_hifreq_interval" + suffix + NStr::NumericToString(notif_hifreq_interval) + separator +
    prefix + "notif_hifreq_period" + suffix + NStr::NumericToString(notif_hifreq_period) + separator +
    prefix + "notif_lofreq_mult" + suffix + NStr::NumericToString(notif_lofreq_mult) + separator +
    prefix + "notif_handicap" + suffix + NStr::NumericToString(notif_handicap) + separator +
    prefix + "dump_buffer_size" + suffix + NStr::NumericToString(dump_buffer_size) + separator +
    prefix + "run_timeout" + suffix + NStr::NumericToString(run_timeout) + separator +
    prefix + "failed_retries" + suffix + NStr::NumericToString(failed_retries) + separator +
    prefix + "blacklist_time" + suffix + NStr::NumericToString(blacklist_time) + separator +
    prefix + "max_input_size" + suffix + NStr::NumericToString(max_input_size) + separator +
    prefix + "max_output_size" + suffix + NStr::NumericToString(max_output_size) + separator +
    prefix + "wnode_timeout" + suffix + NStr::NumericToString(wnode_timeout) + separator +
    prefix + "pending_timeout" + suffix + NStr::NumericToString(pending_timeout) + separator +
    prefix + "max_pending_wait_timeout" + suffix + NStr::NumericToString(max_pending_wait_timeout) + separator +
    prefix + "run_timeout_precision" + suffix + NStr::NumericToString(run_timeout_precision) + separator;

    if (url_encoded) {
        result +=
        prefix + "program_name" + suffix + NStr::URLEncode(program_name) + separator +
        prefix + "subm_hosts" + suffix + NStr::URLEncode(subm_hosts) + separator +
        prefix + "wnode_hosts" + suffix + NStr::URLEncode(wnode_hosts) + separator +
        prefix + "description" + suffix + NStr::URLEncode(description);
    } else {
        result +=
        prefix + "program_name" + suffix + NStr::PrintableString(program_name) + separator +
        prefix + "subm_hosts" + suffix + NStr::PrintableString(subm_hosts) + separator +
        prefix + "wnode_hosts" + suffix + NStr::PrintableString(wnode_hosts) + separator +
        prefix + "description" + suffix + NStr::PrintableString(description);
    }

    return result;
}
コード例 #12
0
ファイル: url.cpp プロジェクト: svn2github/texmacs
string
basename (url u) {
  string s= suffix (u);
  if (N(s) != 0) s= "." * s;
  return basename (u, s);
}
コード例 #13
0
bool DurationSpinBox::isOnUnit() const
{
    int pos = lineEdit()->cursorPosition();
    return ( pos <= text().size() - suffix().size() ) &&
           ( pos > text().size() - suffix().size() - Duration::unitToString( m_unit, true ).size() );
}
コード例 #14
0
ファイル: RefEntityName.cpp プロジェクト: chrismullins/cgma
CubitStatus RefEntityName::generate_unique_name(CubitString &name)
{
  // The method used to generate a unique name is to append
  // 'suffixCharacter' and
  // a letter from A-Z, a-z, or 0-9 to the end of name.
  // If none of these produce a unique name, CUBIT_FALSE is returned.

  CubitString alphabet =
    "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
  CubitString suffix("  ");
  suffix.put_at(0, suffixCharacter);
  
  CubitString internal = name;

  // See if there is an suffixCharacter sign in name already. If so, is it
  // the second to the last character in the string.
  if (name.length() < 2 ||
      name.get_at(name.length()-2) != suffixCharacter) {
    // Name does not contain suffixCharacter at correct location, add one on.
    internal += suffix;
  }
  
  CubitStatus found_unique = CUBIT_FAILURE;
  int continue_trying = CUBIT_TRUE;

  while (!found_unique && continue_trying) {
	 
    continue_trying = CUBIT_FALSE;
    int name_length = internal.length();
    unsigned int number_tested = 0;
    for (unsigned int i=0; i < alphabet.length(); i++) {
      internal.put_at(name_length-1, (char)alphabet.get_at(i));
      if (!nameEntityList.move_to(internal)) {
	found_unique = CUBIT_SUCCESS;
	break;
      }
      number_tested++;
    }

    if (number_tested == alphabet.length()) {
      // All suffixes used. Add another suffixCharacter and try again
      // Name will look like 'Name@@1' or 'Name@@@1'...
      // Find LAST suffixCharacter in name
      int ch;
      for (ch = (int)(internal.length())-1; ch >= 0; ch--) {
	if (internal.get_at(ch) == suffixCharacter) {
	  break;
	}
      }
      if (internal.get_at(ch) == suffixCharacter) {
	// Add another suffixCharacter at ch+1
	// Assured that position ch+1 exists or we wouldn't be here
	internal.put_at(ch+1, suffixCharacter);
	if (ch+2 < (int)internal.length())
	  internal.put_at(ch+2, ' ');
	else
	  internal += " ";
	continue_trying = CUBIT_TRUE;
      }
    }
  }
  
  if (found_unique)
    name = internal;

  return found_unique;
}
コード例 #15
0
void ProduceDatacards_em(int nBins = 35,
			 float xmin = 0,
			 float xmax = 350,
			 bool pileUp = false) {

  double lumi = 2092;
  double normSS = 1.06;
    
  // sample names
  TString sampleNames[20] = {
    "MuEG_2015D", // data
    "DYJetsToLL_M-50_MG", // isZTT (ZTT)
    "DYJetsToLL_M-50_MG", // !isZTT (ZLL)
    "WJetsToLNu_MG", 
    "TTPowHeg",  
    "ST_t-channel_top_4f_leptonDecays",  
    "ST_t-channel_antitop_4f_leptonDecays",
    "ST_tW_antitop_5f_inclusiveDecays",
    "ST_tW_top_5f_inclusiveDecays",
    "VVTo2L2Nu",
    "WWToLNuQQ",
    "WZTo2L2Q",
    "WZTo1L1Nu2Q",
    "WZTo1L3Nu",
    "WZJets",
    "ZZTo4L",
    "ZZTo2L2Q",
    "",
    "",
    ""};

  double xsec[20] = {1, // data (0)
		     6025.2, // DY (1)
		     6025.2, // DY (2)
		     61526.7, // WJets (3)
		     831.76, // TT (4)
		     136.95, // ST_t-channel_top (5)
		     80.95,  // ST_t-channel_antitop (6)
		     35.6, // ST_tW_antitop (7)
		     35.6, // ST_tW_top_5f (8)
		     11.95,  // VV (9)
		     49.997, // WWToLNuQQ (10)
		     5.595, // WZTo2L2Q (11)
		     10.71, // WZTo1L1Nu2Q (12)
		     3.05, // WZTo1L3Nu (13)
		     5.26, // WZJets (3L1Nu) (14)
		     1.212, // ZZTo4L (15)
		     3.22, // ZZTo2L2Q (16)
		     0, //
		     0, //
		     0}; // 
  
  TString cuts[20];
  TString cutsSS[20];
  for (int i=0; i<20; ++i) {
    cuts[i] = "mcweight*(os>0.5)";
    cutsSS[i] = "mcweight*(os<0.5)";
  }

  cuts[0] = "os>0.5";
  cuts[1] = "mcweight*(os>0.5&&isZTT)";
  cuts[2] = "mcweight*(os>0.5&&!isZTT)";

  cutsSS[0] = "os<0.5";
  cutsSS[1] = "mcweight*(os<0.5&&isZTT)";
  cutsSS[2] = "mcweight*(os<0.5&&!isZTT)";
  
  if (pileUp) {
    for (int i=1; i<20; ++i) {
      cuts[i] = "puweight*" + cuts[i];
      cutsSS[i] = "puweight*" + cutsSS[i];
    }
  }

  TH1D * hist[20];
  TH1D * histSS[20];

  for (int i=0; i<17; ++i) {
    std::cout << sampleNames[i] << std::endl;
    TFile * file = new TFile(sampleNames[i]+".root");
    TH1D * histWeightsH = (TH1D*)file->Get("histWeightsH");
    TTree * tree = (TTree*)file->Get("TauCheck");
    double norm = xsec[i]*lumi/histWeightsH->GetSumOfWeights();
    TString histName = sampleNames[i] + "_mvis";
    TString histNameSS = sampleNames[i] + "_mvis_os";
    hist[i] = new TH1D(histName,"",nBins,xmin,xmax);
    histSS[i] = new TH1D(histNameSS,"",nBins,xmin,xmax);
    hist[i]->Sumw2();
    histSS[i]->Sumw2();
    tree->Draw("m_vis>>"+histName,cuts[i]);
    tree->Draw("m_vis>>"+histNameSS,cutsSS[i]);
    if (i>0) {
      for (int iB=1; iB<=nBins; ++iB) {
	double x = hist[i]->GetBinContent(iB);
	double e = hist[i]->GetBinError(iB);
    	hist[i]->SetBinContent(iB,norm*x);
    	hist[i]->SetBinError(iB,norm*e);
	double xSS = histSS[i]->GetBinContent(iB);
	double eSS = histSS[i]->GetBinError(iB);
    	histSS[i]->SetBinContent(iB,norm*xSS);
    	histSS[i]->SetBinError(iB,norm*eSS);
      }
    }
  }

  //  adding up single top and VV backgrounds
  for (int iH=6; iH<17; ++iH) {
    hist[5]->Add(hist[5],hist[iH]);
    histSS[5]->Add(histSS[5],histSS[iH]);
  }

  // subtracting background from SS
  for (int iH=1; iH<6; ++iH) {
    histSS[0]->Add(histSS[0],histSS[iH],1,-1);
  }

  for (int iB=1; iB<=nBins; ++iB) {
    double x = histSS[0]->GetBinContent(iB);
    double e = histSS[0]->GetBinError(iB);
    histSS[0]->SetBinContent(iB,normSS*x);
    histSS[0]->SetBinError(iB,normSS*e);
  }
  TString suffix("");
  if (!pileUp)
    suffix = "_noPU";

  TFile * file = new TFile("htt_em.inputs-sm-13TeV-mvis"+suffix+".root","recreate"); 
  file->mkdir("em_inclusive");
  file->cd("em_inclusive");
  TH1D * data_obs = (TH1D*)hist[0]->Clone("data_obs");
  TH1D * QCD = (TH1D*)histSS[0]->Clone("QCD");
  TH1D * ZTT = (TH1D*)hist[1]->Clone("ZTT");
  TH1D * ZLL = (TH1D*)hist[2]->Clone("ZLL");
  TH1D * W = (TH1D*)hist[3]->Clone("W");
  TH1D * TT = (TH1D*)hist[4]->Clone("TT");
  TH1D * VV = (TH1D*)hist[5]->Clone("VV");
  file->Write();
  file->Close();
  

}
コード例 #16
0
ファイル: printpdf.cpp プロジェクト: nathaneltitane/lpub
void Gui::exportAsPng()
{
    QString suffix(".png");
    exportAs(suffix);
}
コード例 #17
0
ファイル: fixmsxpart.c プロジェクト: texlive/texlive-source
int 
main (int argc, char *argv[])
{
  int c;
  char today[12];
  time_t mytime; 
# define NOPTS 4
  struct option longopts[NOPTS] =
  {  { "help", 0, NULL, 'h'},
     { "version", 0, NULL, 'v'},
     { "debug", 0, NULL, 'd'},
     { NULL, 0, NULL, 0}
  };
  
  time (&mytime);
  strftime (today, 11, "%Y-%m-%d", localtime (&mytime) );
  c = getopt_long (argc, argv, "hvd", longopts, NULL);
  while (c != -1)
    {
      switch (c)
        {
        case 'h':
          fprintf (stdout, "This is fixmsxpart, version %s.\n", version);
          usage (stdout);
          fprintf (stdout, "Please report bugs to [email protected].\n" );
          exit (0);
        case 'v':
          fprintf (stdout, "This is fixmsxpart, version %s.\n", version);
          exit (0);
        case 'd':
          debug++; break;
        case '?':
          exit (EXIT_FAILURE);
        default:
          fprintf (stderr,"Function getopt returned character code 0%o.\n",
                  (unsigned int) c);
          exit (EXIT_FAILURE);
        }
      c = getopt_long (argc, argv, "hvd", longopts, NULL);
    }
  fprintf (stderr, "This is fixmsxpart, version %s.\n", version);
  fprintf (stderr, "Copyright (C) 2014-15  R. D. Tennent\n" );
  fprintf (stderr, "School of Computing, Queen's University, [email protected]\n" );
  fprintf (stderr, "License GNU GPL version 2 or later <http://gnu.org/licences/gpl.html>.\n" );
  fprintf (stderr, "There is NO WARRANTY, to the extent permitted by law.\n\n" );

  infilename[0] = '\0';
  infilename_n = infilename;
  if ( (optind < argc) && (optind+2 >= argc))
    {
      append (infilename, &infilename_n, argv[optind], sizeof (infilename));
      if (!suffix (".tex", infilename))
      append (infilename, &infilename_n, ".tex", sizeof (infilename));
    }
  else 
  {  usage (stderr);
     exit (EXIT_FAILURE);
  }
  optind++;
  outfilename[0] = '\0';
  outfilename_n = outfilename;
  if (optind < argc)  /* user-provided outfilename */
    {
      append (outfilename, &outfilename_n, argv[optind], sizeof (outfilename));
      if (!suffix (".tex", outfilename))
        append (outfilename, &outfilename_n, ".tex", sizeof (outfilename));
    }
  infile = fopen (infilename, "r");
  if (infile == NULL)
    {
      fprintf (stderr,"Can't open %s\n", infilename);
      exit (EXIT_FAILURE);
    }
  fprintf (stderr, "Reading from %s.", infilename);
  if (*outfilename == '\0')
  {
    outfile = stdout;
    fprintf (stderr, " Writing to stdout.\n");
  }
  else
  {
    outfile = fopen (outfilename, "w");
    if (outfile == NULL)
    {
      fprintf (stderr,"Can't open %s\n", outfilename);
      exit (EXIT_FAILURE);
    }
    fprintf (stderr, " Writing to %s.\n", outfilename);
  }
  fprintf (stderr,"\n");

  fprintf (outfile, "%% Generated on %s by fixmsxpart (%s).\n", today, version);
  process_score ();

  return 0;
}
コード例 #18
0
ファイル: printpdf.cpp プロジェクト: nathaneltitane/lpub
void Gui::exportAsJpg()
{
    QString suffix(".jpg");
    exportAs(suffix);
}
コード例 #19
0
ファイル: doname.c プロジェクト: elbing/apex
int
doname(nameblkp p, int reclevel, time_t *tval, int nowait)
{
int errstat;
int okdel1;
int didwork;
int len;
time_t td, td1, tdep, ptime, ptime1;
depblkp q;
depblkp qtemp, suffp, suffp1;
nameblkp p1, p2;
struct shblock *implcom, *explcom;
lineblkp lp;
lineblkp lp1, lp2;
char sourcename[100], prefix[100], temp[100], concsuff[20];
char *stem;
char *pnamep, *p1namep;
chainp allchain, qchain;
char qbuf[QBUFMAX], tgsbuf[QBUFMAX];
wildp wp;
int nproc1;
char *lastslash, *s;

if(p == 0)
	{
	*tval = 0;
	return 0;
	}

if(dbgflag)
	{
	printf("doname(%s,%d)\n",p->namep,reclevel);
	fflush(stdout);
	}

if(p->done > 0)
	{
	*tval = p->modtime;
	return (p->done == 3);
	}

errstat = 0;
tdep = 0;
implcom = 0;
explcom = 0;
ptime = exists(p->namep);
ptime1 = 0;
didwork = NO;
p->done = 1;	/* avoid infinite loops */
nproc1 = nproc;	/* current depth of process stack */

qchain = NULL;
allchain = NULL;

/* define values of Bradford's $$@ and $$/ macros */
for(s = lastslash = p->namep; *s; ++s)
	if(*s == '/')
		lastslash = s;
setvar("$@", p->namep, YES);
setvar("$/", lastslash, YES);


/* expand any names that have embedded metacharacters */

for(lp = p->linep ; lp ; lp = lp->nxtlineblock)
	for(q = lp->depp ; q ; q=qtemp )
		{
		qtemp = q->nxtdepblock;
		expand(q);
		}

/* make sure all dependents are up to date */

for(lp = p->linep ; lp ; lp = lp->nxtlineblock)
	{
	td = 0;
	for(q = lp->depp ; q ; q = q->nxtdepblock)
		if(q->depname)
			{
			errstat += doname(q->depname, reclevel+1, &td1, q->nowait);
			if(dbgflag)
				printf("TIME(%s)=%ld\n",q->depname->namep, td1);
			if(td1 > td)
				td = td1;
			if(ptime < td1)
				qchain = appendq(qchain, q->depname->namep);
			allchain = appendq(allchain, q->depname->namep);
			}
	if(p->septype == SOMEDEPS)
		{
		if(lp->shp)
		     if( ptime<td || (ptime==0 && td==0) || lp->depp==0)
			{
			okdel1 = okdel;
			okdel = NO;
			set3var("@", p->namep);
			setvar("?", mkqlist(qchain,qbuf), YES);
			setvar("^", mkqlist(allchain,tgsbuf), YES);
			qchain = NULL;
			if( !questflag )
				errstat += docom(lp->shp, nowait, nproc1);
			set3var("@", CHNULL);
			okdel = okdel1;
			ptime1 = prestime();
			didwork = YES;
			}
		}

	else	{
		if(lp->shp != 0)
			{
			if(explcom)
				fprintf(stderr, "Too many command lines for `%s'\n",
					p->namep);
			else	explcom = lp->shp;
			}

		if(td > tdep) tdep = td;
		}
	}



/* Look for implicit dependents, using suffix rules */

for(lp = sufflist ; lp ; lp = lp->nxtlineblock)
    for(suffp = lp->depp ; suffp ; suffp = suffp->nxtdepblock)
	{
	pnamep = suffp->depname->namep;
	if(suffix(p->namep , pnamep , prefix))
		{
		(void)srchdir(concat(prefix,"*",temp), NO, (depblkp) NULL);
		for(lp1 = sufflist ; lp1 ; lp1 = lp1->nxtlineblock)
		    for(suffp1=lp1->depp; suffp1 ; suffp1 = suffp1->nxtdepblock)
			{
			p1namep = suffp1->depname->namep;
			if( (p1=srchname(concat(p1namep, pnamep ,concsuff))) &&
			    (p2=srchname(concat(prefix, p1namep ,sourcename))) )
				{
				errstat += doname(p2, reclevel+1, &td, NO);
				if(ptime < td)
					qchain = appendq(qchain, p2->namep);
if(dbgflag) printf("TIME(%s)=%ld\n", p2->namep, td);
				if(td > tdep) tdep = td;
				set3var("*", prefix);
				set3var("<", copys(sourcename));
				for(lp2=p1->linep ; lp2 ; lp2 = lp2->nxtlineblock)
					if(implcom = lp2->shp) break;
				goto endloop;
				}
			}
		}
	}

/* Look for implicit dependents, using pattern matching rules */

len = strlen(p->namep);
for(wp = firstwild ; wp ; wp = wp->next)
	if(stem = wildmatch(wp, p->namep, len) )
		{
		lp = wp->linep;
		for(q = lp->depp; q; q = q->nxtdepblock)
			{
			if(dbgflag>1 && q->depname)
				fprintf(stderr,"check dep of %s on %s\n", p->namep,
					wildsub(q->depname->namep,stem));
			if(q->depname &&
				! chkname(wildsub(q->depname->namep,stem)))
					break;
			}

		if(q)	/* some name not found, go to next line */
			continue;

		for(q = lp->depp; q; q = q->nxtdepblock)
			{
			nameblkp tamep;
			if(q->depname == NULL)
				continue;
			tamep = srchname( wildsub(q->depname->namep,stem));
/*TEMP fprintf(stderr,"check dep %s on %s =>%s\n",p->namep,q->depname->namep,tamep->namep);*/
/*TEMP*/if(dbgflag) printf("%s depends on %s. stem=%s\n", p->namep,tamep->namep, stem);
			errstat += doname(tamep, reclevel+1, &td, q->nowait);
			if(ptime < td)
				qchain = appendq(qchain, tamep->namep);
			allchain = appendq(allchain, tamep->namep);
			if(dbgflag) printf("TIME(%s)=%ld\n", tamep->namep, td);
			if(td > tdep)
				tdep = td;
			set3var("<", copys(tamep->namep) );
			}
		set3var("*", stem);
		setvar("%", stem, YES);
		implcom = lp->shp;
		goto endloop;
		}

endloop:


if(errstat==0 && (ptime<tdep || (ptime==0 && tdep==0) ) )
	{
	ptime = (tdep>0 ? tdep : prestime() );
	set3var("@", p->namep);
	setvar("?", mkqlist(qchain,qbuf), YES);
	setvar("^", mkqlist(allchain,tgsbuf), YES);
	if(explcom)
		errstat += docom(explcom, nowait, nproc1);
	else if(implcom)
		errstat += docom(implcom, nowait, nproc1);
	else if(p->septype == 0)
		if(p1=srchname(".DEFAULT"))
			{
			set3var("<", p->namep);
			for(lp2 = p1->linep ; lp2 ; lp2 = lp2->nxtlineblock)
				if(implcom = lp2->shp)
					{
					errstat += docom(implcom, nowait,nproc1);
					break;
					}
			}
		else if(keepgoing)
			{
			printf("Don't know how to make %s\n", p->namep);
			++errstat;
			}
		else
			fatal1(" Don't know how to make %s", p->namep);

	set3var("@", CHNULL);
	if(noexflag || nowait || (ptime = exists(p->namep)) == 0 )
		ptime = prestime();
	}

else if(errstat!=0 && reclevel==0)
	printf("`%s' not remade because of errors\n", p->namep);

else if(!questflag && reclevel==0  &&  didwork==NO)
	printf("`%s' is up to date.\n", p->namep);

if(questflag && reclevel==0)
	exit(ndocoms>0 ? -1 : 0);

p->done = (errstat ? 3 : 2);
if(ptime1 > ptime)
	ptime = ptime1;
p->modtime = ptime;
*tval = ptime;
return errstat;
}
コード例 #20
0
ファイル: printpdf.cpp プロジェクト: nathaneltitane/lpub
void Gui::exportAsBmp()
{
    QString suffix(".bmp");
    exportAs(suffix);
}
コード例 #21
0
ファイル: gs_utilities.cpp プロジェクト: wangjiezhe/texmacs
bool
gs_supports (url image) {
  string s= suffix (image);
  if (s == "ps" || s == "eps" || s == "pdf") return true;
  return false;
}
コード例 #22
0
int AbstractMeter::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
    _id = WidgetWithBackground::qt_metacall(_c, _id, _a);
    if (_id < 0)
        return _id;
    if (_c == QMetaObject::InvokeMetaMethod) {
        switch (_id) {
        case 0: valueChanged((*reinterpret_cast< int(*)>(_a[1]))); break;
        case 1: valueChanged((*reinterpret_cast< double(*)>(_a[1]))); break;
        case 2: setValue((*reinterpret_cast< int(*)>(_a[1]))); break;
        case 3: setValue((*reinterpret_cast< double(*)>(_a[1]))); break;
        default: ;
        }
        _id -= 4;
    }
#ifndef QT_NO_PROPERTIES
      else if (_c == QMetaObject::ReadProperty) {
        void *_v = _a[0];
        switch (_id) {
        case 0: *reinterpret_cast< double*>(_v) = minimum(); break;
        case 1: *reinterpret_cast< double*>(_v) = maximum(); break;
        case 2: *reinterpret_cast< double*>(_v) = value(); break;
        case 3: *reinterpret_cast< double*>(_v) = nominal(); break;
        case 4: *reinterpret_cast< double*>(_v) = critical(); break;
        case 5: *reinterpret_cast< QString*>(_v) = prefix(); break;
        case 6: *reinterpret_cast< QString*>(_v) = suffix(); break;
        case 7: *reinterpret_cast< QFont*>(_v) = valueFont(); break;
        case 8: *reinterpret_cast< double*>(_v) = valueOffset(); break;
        case 9: *reinterpret_cast< QFont*>(_v) = digitFont(); break;
        case 10: *reinterpret_cast< double*>(_v) = digitOffset(); break;
        }
        _id -= 11;
    } else if (_c == QMetaObject::WriteProperty) {
        void *_v = _a[0];
        switch (_id) {
        case 0: setMinimum(*reinterpret_cast< double*>(_v)); break;
        case 1: setMaximum(*reinterpret_cast< double*>(_v)); break;
        case 2: setValue(*reinterpret_cast< double*>(_v)); break;
        case 3: setNominal(*reinterpret_cast< double*>(_v)); break;
        case 4: setCritical(*reinterpret_cast< double*>(_v)); break;
        case 5: setPrefix(*reinterpret_cast< QString*>(_v)); break;
        case 6: setSuffix(*reinterpret_cast< QString*>(_v)); break;
        case 7: setValueFont(*reinterpret_cast< QFont*>(_v)); break;
        case 8: setValueOffset(*reinterpret_cast< double*>(_v)); break;
        case 9: setDigitFont(*reinterpret_cast< QFont*>(_v)); break;
        case 10: setDigitOffset(*reinterpret_cast< double*>(_v)); break;
        }
        _id -= 11;
    } else if (_c == QMetaObject::ResetProperty) {
        _id -= 11;
    } else if (_c == QMetaObject::QueryPropertyDesignable) {
        _id -= 11;
    } else if (_c == QMetaObject::QueryPropertyScriptable) {
        _id -= 11;
    } else if (_c == QMetaObject::QueryPropertyStored) {
        _id -= 11;
    } else if (_c == QMetaObject::QueryPropertyEditable) {
        _id -= 11;
    } else if (_c == QMetaObject::QueryPropertyUser) {
        _id -= 11;
    }
#endif // QT_NO_PROPERTIES
    return _id;
}
コード例 #23
0
void VoiceRecorderDialog::on_qpbStart_clicked() {
	if (!g.uiSession || !g.sh) {
		QMessageBox::critical(this,
		                      tr("Recorder"),
		                      tr("Unable to start recording. Not connected to a server."));
		reset();
		return;
	}

	if (g.sh->uiVersion < 0x010203) {
		QMessageBox::critical(this,
		                      tr("Recorder"),
		                      tr("The server you are currently connected to is version 1.2.2 or older. "
		                         "For privacy reasons, recording on servers of versions older than 1.2.3 "
		                         "is not possible.\nPlease contact your server administrator for further "
		                         "information."));
		return;
	}

	if (g.sh->recorder) {
		QMessageBox::information(this,
		                         tr("Recorder"),
		                         tr("There is already a recorder active for this server."));
		return;
	}

	// Check validity of input
	int ifm = qcbFormat->currentIndex();
	if (ifm == -1) {
		QMessageBox::critical(this,
		                      tr("Recorder"),
		                      tr("Please select a recording format."));
		return;
	}

	QString dstr = qleTargetDirectory->text();
	if (dstr.isEmpty()) {
		on_qpbTargetDirectoryBrowse_clicked();
		dstr = qleTargetDirectory->text();
		if (dstr.isEmpty())
			return;
	}
	QDir dir(dstr);

	QFileInfo fi(qleFilename->text());
	QString basename(fi.baseName());
	QString suffix(fi.completeSuffix());
	if (suffix.isEmpty())
		suffix = VoiceRecorderFormat::getFormatDefaultExtension(static_cast<VoiceRecorderFormat::Format>(ifm));


	if (basename.isEmpty()) {
		basename = QLatin1String("%user");
	}

	qleFilename->setText(basename);

	AudioOutputPtr ao(g.ao);
	if (!ao)
		return;

	g.sh->announceRecordingState(true);

	// Create the recorder
	g.sh->recorder.reset(new VoiceRecorder(this));
	VoiceRecorderPtr recorder(g.sh->recorder);

	// Wire it up
	connect(&*recorder, SIGNAL(recording_started()), this, SLOT(onRecorderStarted()));
	connect(&*recorder, SIGNAL(recording_stopped()), this, SLOT(onRecorderStopped()));
	connect(&*recorder, SIGNAL(error(int, QString)), this, SLOT(onRecorderError(int, QString)));

	// Configure it
	recorder->setSampleRate(ao->getMixerFreq());
	recorder->setFileName(dir.absoluteFilePath(basename + QLatin1Char('.') + suffix));
	recorder->setMixDown(qrbDownmix->isChecked());
	recorder->setFormat(static_cast<VoiceRecorderFormat::Format>(ifm));

	recorder->start();

	qpbStart->setDisabled(true);
	qpbStop->setEnabled(true);
	qgbMode->setDisabled(true);
	qgbOutput->setDisabled(true);
}
コード例 #24
0
ファイル: edit_main.cpp プロジェクト: svn2github/texmacs
void
edit_main_rep::print_bis (url name, bool conform, int first, int last) {
  bool ps  = (suffix (name) == "ps");
  bool pdf = (suffix (name) == "pdf");
  url  orig= resolve (name, "");

#ifdef USE_GS
  if (!use_pdf () && pdf)
    name= url_temp (".ps");
  if (!use_ps () && ps)
    name= url_temp (".pdf");
#endif
  
  string medium = env->get_string (PAGE_MEDIUM);
  if (conform && (medium != "paper")) conform= false;
  // FIXME: better command for conform printing

  // Set environment variables for printing

  typeset_prepare ();
  env->write (DPI, printing_dpi);
  env->write (PAGE_SHOW_HF, "true");
  env->write (PAGE_SCREEN_MARGIN, "false");
  if (!conform) {
    env->write (PAGE_MEDIUM, "paper");
    env->write (PAGE_PRINTED, "true");
  }

  // Typeset pages for printing

  box the_box= typeset_as_document (env, subtree (et, rp), reverse (rp));

  // Determine parameters for printer

  string page_type = env->get_string (PAGE_TYPE);
  double w         = env->page_width;
  double h         = env->page_height;
  double cm        = env->as_length (string ("1cm"));
  bool   landsc    = env->page_landscape;
  int    dpi       = as_int (printing_dpi);
  int    start     = max (0, first-1);
  int    end       = min (N(the_box[0]), last);
  int    pages     = end-start;
  if (conform) {
    page_type= "user";
    SI bw= the_box[0][0]->w();
    SI bh= the_box[0][0]->h();
    string bws= as_string (bw) * "tmpt";
    string bhs= as_string (bh) * "tmpt";
    w= env->as_length (bws);
    h= env->as_length (bhs);
  }

  // Print pages
  renderer ren;
#ifdef PDF_RENDERER
  if (use_pdf () && (pdf || !use_ps ()))
    ren= pdf_hummus_renderer (name, dpi, pages, page_type, landsc, w/cm, h/cm);
  else
    ren= printer (name, dpi, pages, page_type, landsc, w/cm, h/cm);
#else
  ren= printer (name, dpi, pages, page_type, landsc, w/cm, h/cm);
#endif
  
  if(ren->is_started()) {
	  int i;
	  ren->set_metadata ("title", get_metadata ("title"));
	  ren->set_metadata ("author", get_metadata ("author"));
	  ren->set_metadata ("subject", get_metadata ("subject"));
	  for (i=start; i<end; i++) {
		  tree bg= env->read (BG_COLOR);
		  ren->set_background (bg);
		  if (bg != "white")
			  ren->clear_pattern (0, (SI) -h, (SI) w, 0);

		  rectangles rs;
		  the_box[0]->sx(i)= 0;
		  the_box[0]->sy(i)= 0;
		  the_box[0][i]->redraw (ren, path (0), rs);
		  if (i<end-1) ren->next_page ();
	  }
  }
  tm_delete (ren);

#ifdef USE_GS
  if (!use_pdf () && pdf) {
    gs_to_pdf (name, orig, landsc, h/cm, w/cm);
    ::remove (name);
  }
  if (!use_ps () && ps) {
    gs_to_ps (name, orig, landsc, h/cm, w/cm);
    ::remove (name);
  }
#endif
}
コード例 #25
0
ファイル: tail.c プロジェクト: 00001/plan9port
void
main(int argc, char **argv)
{
	int seekable, c;

	Binit(&bout, 1, OWRITE);
	for(; argc > 1 && ((c=*argv[1])=='-'||c=='+'); argc--,argv++ ) {
		if(getnumber(argv[1])) {
			suffix(argv[1]);
			continue;
		} else
		if(c == '-')
			switch(argv[1][1]) {
			case 'c':
				units = CHARS;
			case 'n':
				if(getnumber(argv[1]+2))
					continue;
				else
				if(argc > 2 && getnumber(argv[2])) {
					argc--, argv++;
					continue;
				} else
					usage();
			case 'r':
				dir = REV;
				continue;
			case 'f':
				follow++;
				continue;
			case '-':
				argc--, argv++;
			}
		break;
	}
	if(dir==REV && (units==CHARS || follow || origin==BEG))
		fatal("incompatible options");
	if(!anycount)
		count = dir==REV? ~0ULL>>1: 10;
	if(origin==BEG && units==LINES && count>0)
		count--;
	if(argc > 2)
		usage();
	if(argc > 1 && (file=open(argv[1],0)) < 0)
		fatal(argv[1]);
	seekable = seek(file,0L,0) == 0;

	if(!seekable && origin==END)
		keep();
	else
	if(!seekable && origin==BEG)
		skip();
	else
	if(units==CHARS && origin==END)
		JUMP(-count, 2);
	else
	if(units==CHARS && origin==BEG)
		JUMP(count, 0);
	else
	if(units==LINES && origin==END)
		reverse();
	else
	if(units==LINES && origin==BEG)
		skip();
	if(follow && seekable)
		for(;;) {
			static Dir *sb0, *sb1;
			trunc(sb1, &sb0);
			copy();
			trunc(sb0, &sb1);
			sleep(5000);
		}
	exits(0);
}
コード例 #26
0
ファイル: drawSecondJet.C プロジェクト: amarini/pandolf
void drawSecondJet(std::string dataset, std::string recoType, std::string jetAlgo, const std::string& fitrms="") {

  ALGOTYPE_ = (recoType=="pf") ? recoType+jetAlgo : jetAlgo;
  RECOTYPE_ = recoType;

  TStyle *simpleStyle = new TStyle("simpleStyle","");
  simpleStyle->SetCanvasColor(0);
  simpleStyle->SetFrameFillColor(0);
  simpleStyle->SetStatColor(0);
  simpleStyle->SetOptStat(0);
  simpleStyle->SetTitleFillColor(0);
  simpleStyle->SetCanvasBorderMode(0);
  simpleStyle->SetPadBorderMode(0);
  simpleStyle->SetFrameBorderMode(0);
  simpleStyle->cd();

  if( fitrms != "" ) FIT_RMS = fitrms;

  char suffix_char[200];
  sprintf(suffix_char, "%s_%s_%s_%d", dataset.c_str(), ALGOTYPE_.c_str(), FIT_RMS.c_str(), INT_PERC);
  std::string suffix(suffix_char);
  if( LUMI>0 ) {
    char lumi_char[20];
    sprintf( lumi_char, "_%dPB", LUMI);
    std::string lumi_str(lumi_char);
    suffix += lumi_str;
  }
  if( NOQ ) suffix += "_05Q";
  OUTPUTDIR_ = "SecondJetPlots_" + suffix;

  std::string fileName = "SecondJet_"+dataset + "_" + ALGOTYPE_ + ".root";
  TFile* file = TFile::Open(fileName.c_str());

  TH2D* h2_ptPhotReco_vs_pt = (TH2D*)file->Get("ptPhotMean_vs_pt");


  Float_t ptPhotReco[NBINS_PT-1];
  Float_t ptPhotReco_err[NBINS_PT-1];

  Float_t extrapReso_RecoRel[NBINS_PT-1];
  Float_t extrapReso_err_RecoRel[NBINS_PT-1];
  Float_t trueReso_RecoRel[NBINS_PT-1];
  Float_t trueReso_err_RecoRel[NBINS_PT-1];
  Float_t intrReso_RecoRel[NBINS_PT-1];
  Float_t intrReso_err_RecoRel[NBINS_PT-1];
  Float_t extrapResp_RecoRel[NBINS_PT-1];
  Float_t extrapResp_err_RecoRel[NBINS_PT-1];
  Float_t trueResp_RecoRel[NBINS_PT-1];
  Float_t trueResp_err_RecoRel[NBINS_PT-1];
  Float_t intrResp_RecoRel[NBINS_PT-1];
  Float_t intrResp_err_RecoRel[NBINS_PT-1];
  Float_t imbalanceResp_RecoRel[NBINS_PT-1];
  Float_t imbalanceResp_err_RecoRel[NBINS_PT-1];
  Float_t pullResp_RecoRel[NBINS_PT-1];
  Float_t pullResp_err_RecoRel[NBINS_PT-1];
  Float_t pullReso_RecoRel[NBINS_PT-1];
  Float_t pullReso_err_RecoRel[NBINS_PT-1];
   
   

  for( int i=0; i<(NBINS_PT-1); ++i) {
    char projName[50];
    sprintf(projName, "projection_%d",i);
    TH1D* h1_proj = h2_ptPhotReco_vs_pt->ProjectionY(projName, i+1, i+1);
    ptPhotReco[i] = h1_proj->GetMean();
    ptPhotReco_err[i] = (h1_proj->GetEntries()>1.) ? h1_proj->GetRMS()/sqrt(h1_proj->GetEntries()) : h1_proj->GetRMS();
    drawSinglePtBin(file, i, "RecoRel", extrapReso_RecoRel[i], extrapReso_err_RecoRel[i], trueReso_RecoRel[i], trueReso_err_RecoRel[i], intrReso_RecoRel[i], intrReso_err_RecoRel[i], 
                                        extrapResp_RecoRel[i], extrapResp_err_RecoRel[i], trueResp_RecoRel[i], trueResp_err_RecoRel[i], intrResp_RecoRel[i], intrResp_err_RecoRel[i], imbalanceResp_RecoRel[i], imbalanceResp_err_RecoRel[i]);

    pullResp_RecoRel[i] = 100.*(extrapResp_RecoRel[i] - intrResp_RecoRel[i])/intrResp_RecoRel[i];
    pullResp_err_RecoRel[i] = 100.*sqrt( extrapResp_err_RecoRel[i]*extrapResp_err_RecoRel[i] + intrResp_RecoRel[i]*intrResp_RecoRel[i] );

    pullReso_RecoRel[i] = 100.*(extrapReso_RecoRel[i] - intrReso_RecoRel[i])/intrReso_RecoRel[i];
    pullReso_err_RecoRel[i] = 100.*sqrt( extrapReso_err_RecoRel[i]*extrapReso_err_RecoRel[i] + intrReso_RecoRel[i]*intrReso_RecoRel[i] );

    imbalanceResp_RecoRel[i] *= 100.; //in percent
    imbalanceResp_err_RecoRel[i] *= 100.;

  }

  TGraphErrors* gr_extrapRespRecoRel_vs_pt = new TGraphErrors(NBINS_PT-1, ptPhotReco, extrapResp_RecoRel, ptPhotReco_err, extrapResp_err_RecoRel); 
  gr_extrapRespRecoRel_vs_pt->SetName("gr_extrapRespRecoRel_vs_pt");
  gr_extrapRespRecoRel_vs_pt->SetMarkerStyle(25);
  gr_extrapRespRecoRel_vs_pt->SetMarkerColor(kBlack);
  gr_extrapRespRecoRel_vs_pt->SetMarkerSize(1.5);

  TGraphErrors* gr_intrRespRecoRel_vs_pt = new TGraphErrors(NBINS_PT-1, ptPhotReco, intrResp_RecoRel, ptPhotReco_err, intrResp_err_RecoRel); 
  gr_intrRespRecoRel_vs_pt->SetName("gr_intrRespRecoRel_vs_pt");
  gr_intrRespRecoRel_vs_pt->SetMarkerStyle(29);
  gr_intrRespRecoRel_vs_pt->SetMarkerColor(kBlue);
  gr_intrRespRecoRel_vs_pt->SetMarkerSize(1.5);

  TGraphErrors* gr_trueRespRecoRel_vs_pt = new TGraphErrors(NBINS_PT-1, ptPhotReco, trueResp_RecoRel, ptPhotReco_err, trueResp_err_RecoRel); 
  gr_trueRespRecoRel_vs_pt->SetName("gr_trueRespRecoRel_vs_pt");
  gr_trueRespRecoRel_vs_pt->SetMarkerStyle(23);
  gr_trueRespRecoRel_vs_pt->SetMarkerColor(kGray+2);
  gr_trueRespRecoRel_vs_pt->SetMarkerSize(1.5);

  TGraphErrors* gr_extrapResoRecoRel_vs_pt = new TGraphErrors(NBINS_PT-1, ptPhotReco, extrapReso_RecoRel, ptPhotReco_err, extrapReso_err_RecoRel); 
  gr_extrapResoRecoRel_vs_pt->SetName("gr_extrapResoRecoRel_vs_pt");
  gr_extrapResoRecoRel_vs_pt->SetMarkerStyle(25);
  gr_extrapResoRecoRel_vs_pt->SetMarkerColor(kBlack);
  gr_extrapResoRecoRel_vs_pt->SetMarkerSize(1.5);

  TGraphErrors* gr_intrResoRecoRel_vs_pt = new TGraphErrors(NBINS_PT-1, ptPhotReco, intrReso_RecoRel, ptPhotReco_err, intrReso_err_RecoRel); 
  gr_intrResoRecoRel_vs_pt->SetName("gr_intrResoRecoRel_vs_pt");
  gr_intrResoRecoRel_vs_pt->SetMarkerStyle(29);
  gr_intrResoRecoRel_vs_pt->SetMarkerColor(kBlue);
  gr_intrResoRecoRel_vs_pt->SetMarkerSize(1.5);

  TGraphErrors* gr_trueResoRecoRel_vs_pt = new TGraphErrors(NBINS_PT-1, ptPhotReco, trueReso_RecoRel, ptPhotReco_err, trueReso_err_RecoRel); 
  gr_trueResoRecoRel_vs_pt->SetName("gr_trueResoRecoRel_vs_pt");
  gr_trueResoRecoRel_vs_pt->SetMarkerStyle(23);
  gr_trueResoRecoRel_vs_pt->SetMarkerColor(kGray+2);
  gr_trueResoRecoRel_vs_pt->SetMarkerSize(1.5);

  TGraphErrors* gr_imbalanceRecoRel_vs_pt = new TGraphErrors(NBINS_PT-1, ptPhotReco, imbalanceResp_RecoRel, ptPhotReco_err, imbalanceResp_err_RecoRel); 
  gr_imbalanceRecoRel_vs_pt->SetName("gr_imbalanceRecoRel_vs_pt");
  gr_imbalanceRecoRel_vs_pt->SetMarkerStyle(20);
  gr_imbalanceRecoRel_vs_pt->SetMarkerColor(kBlack);
  gr_imbalanceRecoRel_vs_pt->SetMarkerSize(1.5);

  drawPullHistogram("pullResp", pullResp_RecoRel, pullResp_err_RecoRel);
  drawPullHistogram("pullReso", pullReso_RecoRel, pullReso_err_RecoRel);

  std::string graphFileName= "SecondJet_GraphFile_" + suffix + ".root";
  TFile* graphFile = TFile::Open(graphFileName.c_str(), "RECREATE");
  graphFile->cd();
  gr_extrapRespRecoRel_vs_pt->Write();
  gr_trueRespRecoRel_vs_pt->Write();
  gr_intrRespRecoRel_vs_pt->Write();
  gr_extrapResoRecoRel_vs_pt->Write();
  gr_trueResoRecoRel_vs_pt->Write();
  gr_intrResoRecoRel_vs_pt->Write();
  graphFile->Close();

  std::string graphName;
  std::string canvasName;

  //response:
  graphName = "gr_response_vs_pt_MEAN_barrel_" + ALGOTYPE_;
  TGraphErrors* gr_respReco_cutOn2ndJet = (TGraphErrors*)file->Get(graphName.c_str());
  gr_respReco_cutOn2ndJet->SetMarkerStyle(20);
  gr_respReco_cutOn2ndJet->SetMarkerColor(kRed);
  gr_respReco_cutOn2ndJet->SetMarkerSize(1.5);

  canvasName = OUTPUTDIR_ + "/response_vs_pt_noextrap."+PICTURE_FORMAT;
  drawGraphs_vs_pt( "Response", canvasName, gr_respReco_cutOn2ndJet, gr_intrRespRecoRel_vs_pt );
  
  canvasName = OUTPUTDIR_ + "/response_vs_pt_RECO."+PICTURE_FORMAT;
  drawGraphs_vs_pt( "Response", canvasName, gr_respReco_cutOn2ndJet, gr_intrRespRecoRel_vs_pt, gr_extrapRespRecoRel_vs_pt);


  // resolution:
  std::string resoType = (FIT_RMS=="RMS") ? "RMS" : "FIT";
  graphName = "gr_responseRes_vs_pt_"+resoType+"_barrel_" + ALGOTYPE_;
  TGraphErrors* gr_resoReco_cutOn2ndJet = (TGraphErrors*)file->Get(graphName.c_str());
  gr_resoReco_cutOn2ndJet->SetMarkerStyle(20);
  gr_resoReco_cutOn2ndJet->SetMarkerColor(kRed);
  gr_resoReco_cutOn2ndJet->SetMarkerSize(1.5);

  canvasName = OUTPUTDIR_ + "/resolution_vs_pt_noextrap."+PICTURE_FORMAT;
  drawGraphs_vs_pt( "Resolution", canvasName, gr_resoReco_cutOn2ndJet, gr_intrResoRecoRel_vs_pt );
  
  canvasName = OUTPUTDIR_ + "/resolution_vs_pt_RECO."+PICTURE_FORMAT;
  drawGraphs_vs_pt( "Resolution", canvasName, gr_resoReco_cutOn2ndJet, gr_intrResoRecoRel_vs_pt, gr_extrapResoRecoRel_vs_pt);


  TH2D* h2_axes = new TH2D("axes", "", 10, 20., 2200., 10, -10., 5.);
  h2_axes->GetXaxis()->SetTitleOffset(1.1);
  h2_axes->GetYaxis()->SetTitleOffset(1.2);
  h2_axes->SetYTitle("Residual Imbalance [%]");
  h2_axes->SetXTitle("p_{T}^{#gamma} [GeV/c]");
  h2_axes->GetXaxis()->SetMoreLogLabels();
  h2_axes->GetXaxis()->SetNoExponent();

  canvasName = OUTPUTDIR_ + "/imbalance." + PICTURE_FORMAT;
  TCanvas* c1 = new TCanvas("c1", "c1", 800, 600);
  c1->cd();
  c1->SetLogx();
  c1->SetGridx();
  c1->SetGridy();
  h2_axes->Draw();
  gr_imbalanceRecoRel_vs_pt->Draw("Psame");
  c1->SaveAs(canvasName.c_str());
  


  delete h2_axes;
  delete gr_extrapRespRecoRel_vs_pt;
  delete gr_extrapResoRecoRel_vs_pt;

}
コード例 #27
0
ファイル: lcc.c プロジェクト: ArtanAhmeti/lab
int main(int argc, char *argv[]) {
	int i, j, nf;

	progname = argv[0];

	UpdatePaths( progname );

	ac = argc + 50;
	av = alloc(ac*sizeof(char *));
	if (signal(SIGINT, SIG_IGN) != SIG_IGN)
		signal(SIGINT, interrupt);
	if (signal(SIGTERM, SIG_IGN) != SIG_IGN)
		signal(SIGTERM, interrupt);
#ifdef SIGHUP
	if (signal(SIGHUP, SIG_IGN) != SIG_IGN)
		signal(SIGHUP, interrupt);
#endif
	if (getenv("TMP"))
		tempdir = getenv("TMP");
	else if (getenv("TEMP"))
		tempdir = getenv("TEMP");
	else if (getenv("TMPDIR"))
		tempdir = getenv("TMPDIR");
	assert(tempdir);
	i = strlen(tempdir);
	for (; (i > 0 && tempdir[i-1] == '/') || tempdir[i-1] == '\\'; i--)
		tempdir[i-1] = '\0';
	if (argc <= 1) {
		help();
		exit(0);
	}
	plist = append("-D__LCC__", 0);
	initinputs();
	if (getenv("LCCDIR"))
		option(stringf("-lccdir=%s", getenv("LCCDIR")));
	for (nf = 0, i = j = 1; i < argc; i++) {
		if (strcmp(argv[i], "-o") == 0) {
			if (++i < argc) {
				if (suffix(argv[i], suffixes, 2) >= 0) {
					error("-o would overwrite %s", argv[i]);
					exit(8);
				}
				outfile = argv[i];
				continue;
			} else {
				error("unrecognized option `%s'", argv[i-1]);
				exit(8);
			}
		} else if (strcmp(argv[i], "-target") == 0) {
			if (argv[i+1] && *argv[i+1] != '-')
				i++;
			continue;
		} else if (*argv[i] == '-' && argv[i][1] != 'l') {
			opt(argv[i]);
			continue;
		} else if (*argv[i] != '-' && suffix(argv[i], suffixes, 3) >= 0)
			nf++;
		argv[j++] = argv[i];
	}
	if ((cflag || Sflag) && outfile && nf != 1) {
		fprintf(stderr, "%s: -o %s ignored\n", progname, outfile);
		outfile = 0;
	}
	argv[j] = 0;
	for (i = 0; include[i]; i++)
		plist = append(include[i], plist);
	if (ilist) {
		List b = ilist;
		do {
			b = b->link;
			plist = append(b->str, plist);
		} while (b != ilist);
	}
	ilist = 0;
	for (i = 1; argv[i]; i++)
		if (*argv[i] == '-')
			opt(argv[i]);
		else {
			char *name = exists(argv[i]);
			if (name) {
				if (strcmp(name, argv[i]) != 0
				|| (nf > 1 && suffix(name, suffixes, 3) >= 0))
					fprintf(stderr, "%s:\n", name);
				filename(name, 0);
			} else
				error("can't find `%s'", argv[i]);
		}
	if (errcnt == 0 && !Eflag && !Sflag && !cflag && llist[1]) {
		compose(ld, llist[0], llist[1],
			append(outfile ? outfile : concat("a", first(suffixes[4])), 0));
		if (callsys(av))
			errcnt++;
	}
	rm(rmlist);	
	return errcnt ? EXIT_FAILURE : EXIT_SUCCESS;
}
コード例 #28
0
ファイル: edit_main.cpp プロジェクト: KarlHegbloom/texmacs
void
edit_main_rep::print_doc (url name, bool conform, int first, int last) {
  bool ps  = (suffix (name) == "ps");
  bool pdf = (suffix (name) == "pdf");
  url  orig= resolve (name, "");

#ifdef USE_GS
  if (!use_pdf () && pdf)
    name= url_temp (".ps");
  if (!use_ps () && ps)
    name= url_temp (".pdf");
#endif
  
  string medium = env->get_string (PAGE_MEDIUM);
  if (conform && (medium != "paper")) conform= false;
    // FIXME: better command for conform printing

  typeset_preamble ();
    // FIXME: when printing several files via aux buffers,
    // it seems that the style can be corrupted.  Why?
  
  // Set environment variables for printing

  typeset_prepare ();
  env->write (DPI, printing_dpi);
  env->write (PAGE_SHOW_HF, "true");
  env->write (PAGE_SCREEN_MARGIN, "false");
  env->write (PAGE_BORDER, "none");
  if (!conform) {
    env->write (PAGE_MEDIUM, "paper");
    env->write (PAGE_PRINTED, "true");
  }

  // Typeset pages for printing

  box the_box= typeset_as_document (env, subtree (et, rp), reverse (rp));

  // Determine parameters for printer

  string page_type = env->get_string (PAGE_TYPE);
  double w         = env->page_width;
  double h         = env->page_height;
  double cm        = env->as_length (string ("1cm"));
  bool   landsc    = env->page_landscape;
  int    dpi       = as_int (printing_dpi);
  int    start     = max (0, first-1);
  int    end       = min (N(the_box[0]), last);
  int    pages     = end-start;
  if (conform) {
    page_type= "user";
    SI bw= the_box[0][0]->w();
    SI bh= the_box[0][0]->h();
    string bws= as_string (bw) * "tmpt";
    string bhs= as_string (bh) * "tmpt";
    w= env->as_length (bws);
    h= env->as_length (bhs);
  }

  // Print pages
  renderer ren= printer (name, dpi, pages, page_type, landsc, w/cm, h/cm);
  
  if (ren->is_started ()) {
    int i;
    ren->set_metadata ("title", get_metadata ("title"));
    ren->set_metadata ("author", get_metadata ("author"));
    ren->set_metadata ("subject", get_metadata ("subject"));
    for (i=start; i<end; i++) {
      tree bg= env->read (BG_COLOR);
      ren->set_background (bg);
      if (bg != "white" && bg != "#ffffff")
        ren->clear_pattern (0, (SI) -h, (SI) w, 0);

      rectangles rs;
      the_box[0]->sx(i)= 0;
      the_box[0]->sy(i)= 0;
      the_box[0][i]->redraw (ren, path (0), rs);
      if (i<end-1) ren->next_page ();
    }
  }
  tm_delete (ren);

#ifdef USE_GS
  if (!use_pdf () && pdf) {
    gs_to_pdf (name, orig, landsc, h/cm, w/cm);
    ::remove (name);
  }
  if (!use_ps () && ps) {
    gs_to_ps (name, orig, landsc, h/cm, w/cm);
    ::remove (name);
  }
  if (ps || pdf)
    if (get_preference ("texmacs->pdf:check", "off") == "on") {
      //system_wait ("Checking exported file for correctness", "please wait");
      // FIXME: the wait message often causes a crash, currently
      gs_check (orig);
    }
#endif
}
コード例 #29
0
ファイル: sequence_analyzer.cpp プロジェクト: MGKhKhD/meta
sequence_analyzer default_pos_analyzer()
{
    sequence_analyzer analyzer;

    auto word_feats = [](const std::string& word, uint64_t t,
                         sequence_analyzer::collector& coll)
    {
        auto norm = utf::foldcase(word);
        for (uint64_t i = 1; i <= 4; i++)
        {
            auto len = std::to_string(i);
            coll.add("w[t]_suffix_" + len + "=" + suffix(norm, i), 1);
            coll.add("w[t]_prefix_" + len + "=" + prefix(norm, i), 1);
        }
        coll.add("w[t]=" + norm, 1);

        // additional binary word features
        if (std::any_of(word.begin(), word.end(), [](char c)
                        {
                            return std::isdigit(c);
                        }))
        {
            coll.add("w[t]_has_digit=1", 1);
        }

        if (std::find(word.begin(), word.end(), '-') != word.end())
            coll.add("w[t]_has_hyphen=1", 1);

        if (std::any_of(word.begin(), word.end(), [](char c)
                        {
                            return std::isupper(c);
                        }))
        {
            coll.add("w[t]_has_upper=1", 1);
            if (t != 0)
            {
                coll.add("w[t]_has_upper_and_not_sentence_start=1", 1);
            }
        }

        if (std::all_of(word.begin(), word.end(), [](char c)
                        {
                            return std::isupper(c);
                        }))
        {
            coll.add("w[t]_all_upper=1", 1);
        }
    };

    // current word features
    analyzer.add_observation_function(
        [=](const sequence& seq, uint64_t t, sequence_analyzer::collector& coll)
        {
            std::string word = seq[t].symbol();
            word_feats(word, t, coll);
        });

    // previous word features
    analyzer.add_observation_function(
        [](const sequence& seq, uint64_t t, sequence_analyzer::collector& coll)
        {
            std::string word = seq[t].symbol();
            if (t > 0)
            {
                auto prevword = seq[t - 1].symbol();
                coll.add("w[t-1]=" + utf::foldcase(prevword), 1);
                if (t > 1)
                {
                    auto prev2word = seq[t - 2].symbol();
                    coll.add("w[t-2]=" + utf::foldcase(prev2word), 1);
                }
                else
                {
                    coll.add("w[t-2]=<s>", 1);
                }
            }
            else
            {
                coll.add("w[t-1]=<s>", 1);
                coll.add("w[t-2]=<s1>", 1);
            }
        });

    // next word features
    analyzer.add_observation_function(
        [](const sequence& seq, uint64_t t, sequence_analyzer::collector& coll)
        {
            if (t + 1 < seq.size())
            {
                auto nextword = seq[t + 1].symbol();
                coll.add("w[t+1]=" + utf::foldcase(nextword), 1);
                if (t + 2 < seq.size())
                {
                    auto next2word = seq[t + 2].symbol();
                    coll.add("w[t+2]=" + utf::foldcase(next2word), 1);
                }
                else
                {
                    coll.add("w[t+2]=</s>", 1);
                }
            }
            else
            {
                coll.add("w[t+1]=</s>", 1);
                coll.add("w[t+2]=</s1>", 1);
            }
        });

    // bias term
    analyzer.add_observation_function(
        [](const sequence&, uint64_t, sequence_analyzer::collector& coll)
        {
            coll.add("bias", 1);
        });

    return analyzer;
}
コード例 #30
0
ファイル: insider.cpp プロジェクト: aicro/patl
int main(/*int argc, char *argv[]*/)
{
    typedef patl::trie_set<std::string> StringSet;
    StringSet
        test1,
        test2;
    //&test2 = test1;
    //
    test1.insert("balka");
    test1.insert("balet");
    test1.insert("bulat");
    test1.insert("bulka");
    test1.insert("bal");
    //
    test2.insert("balet");
    test2.insert("balon");
    test2.insert("bal");
    test2.insert("baton");
    //
    test1.merge(test2.begin(), test2.end());
    test1.change_root(test1.find("balon"));
    //
    {
        typedef StringSet::const_iterator const_iterator;
        typedef std::pair<const_iterator, const_iterator> pair_cit_cit;
        pair_cit_cit pcc = test1.equal_range("balda");
        const_iterator
            low_cit = test1.lower_bound("balda"),
            upp_cit = test1.upper_bound("balda");
        printf("equal == <lower, upper>: %s\n",
            pcc == std::make_pair(low_cit, upp_cit) ? "true" : "false");
        printf("range of 'balda' (first: %s, limit: %s):\n",
            pcc.first != test1.end() ? pcc.first->c_str() : "end",
            pcc.second != test1.end() ? pcc.second->c_str() : "end");
        for (const_iterator cit = pcc.first; cit != pcc.second; ++cit)
            printf("\t%s\n", cit->c_str());
        //
        printf("\n---\n\n");
        //
        pcc = test1.equal_range("balda", 3 * 8);
        low_cit = test1.lower_bound("balda", 3 * 8);
        upp_cit = test1.upper_bound("balda", 3 * 8);
        printf("equal == <lower, upper>: %s\n",
            pcc == std::make_pair(low_cit, upp_cit) ? "true" : "false");
        printf("range of 'balda' [3] (first: %s, limit: %s):\n",
            pcc.first != test1.end() ? pcc.first->c_str() : "end",
            pcc.second != test1.end() ? pcc.second->c_str() : "end");
        for (const_iterator cit = pcc.first; cit != pcc.second; ++cit)
            printf("\t%s\n", cit->c_str());
    }
    //
    printf("\n--- iterator\n\n");
    //
    {
        typedef StringSet::const_iterator const_iter;
        const_iter
            itBeg = test1.begin(),
            itEnd = test1.end(),
            it = itBeg;
        for (; it != itEnd; ++it)
            printf("%s\n", it->c_str());
        printf("---\n");
        while (it != itBeg)
        {
            --it;
            printf("%s\n", it->c_str());
        }
    }
    //
    printf("\n--- partial_match\n\n");
    //
    {
        typedef patl::partial_match<StringSet, false> part_match;
        part_match pm(test1, "b?l?t");
        StringSet::const_partimator<part_match>
            it = test1.begin(pm),
            itEnd = test1.end(pm);
        printf("*** 'b?l?t':\n");
        for (; it != itEnd; ++it)
            printf("%s\n", it->c_str());
        printf("---\n");
        pm = part_match(test1, "b?l??");
        it = test1.begin(pm);
        itEnd = test1.end(pm);
        printf("*** 'b?l??\':\n");
        for (; it != itEnd; ++it)
            printf("%s\n", it->c_str());
    }
    //
    printf("\n--- hamming_distance\n\n");
    //
    {
        typedef patl::hamming_distance<StringSet, false> hamm_dist;
        hamm_dist hd(test1, 1, "bulk");
        StringSet::const_partimator<hamm_dist>
            it = test1.begin(hd),
            itEnd = test1.end(hd);
        printf("*** 'bulk', dist == 1:\n");
        for (; it != itEnd; ++it)
            printf("%s, dist: %u\n", it->c_str(), it.decis().distance());
    }
    //
    printf("\n--- levenshtein_distance\n\n");
    //
    {
        typedef patl::levenshtein_distance<StringSet, false> leven_dist;
        leven_dist ld(test1, 1, "balt");
        StringSet::const_partimator<leven_dist>
            it = test1.begin(ld),
            itEnd = test1.end(ld);
        printf("*** 'balt', dist == 1:\n");
        for (; it != itEnd; ++it)
            printf("%s, dist: %u\n", it->c_str(), it.decis().distance());
    }
    //
    printf("\n--- postorder_iterator\n\n");
    //
    typedef StringSet::const_vertex const_vertex;
    const const_vertex vtx_root = test1.root();
    {
        typedef StringSet::const_postorder_iterator const_postorder_iterator;
        const_postorder_iterator
            itBeg = vtx_root.postorder_begin(),
            itEnd = vtx_root.postorder_end(),
            it = itBeg;
        for (; it != itEnd; ++it)
            printf("%d\t%s\n", it->skip(), it->key().c_str());
        printf("---\n");
        while (it != itBeg)
        {
            --it;
            printf("%d\t%s\n", it->skip(), it->key().c_str());
        }
    }
    //
    printf("\n--- preorder_iterator\n\n");
    //
    {
        typedef StringSet::const_preorder_iterator const_preorder_iterator;
        const_preorder_iterator
            itBeg = vtx_root.preorder_begin(),
            itEnd = vtx_root.preorder_end(),
            it = itBeg;
        preorder_iterator_callback<typename StringSet::const_vertex> icb;
        for (; it != itEnd; /*++it*/it.increment(icb))
            printf("%d\t%s\n", it->skip(), it->key().c_str());
        printf("---\n");
        while (it != itBeg)
        {
            //--it;
            it.decrement(icb);
            printf("%d\t%s\n", it->skip(), it->key().c_str());
        }
    }
    //
    printf("\n--- preorder_iterator with levelorder behavior\n\n");
    //
    {
        const char *const X[] = {
            "asm", "auto", "bool", "break", "case", "catch", "char", "class", "const", 
            "const_cast", "continue", "default", "delete", "do", "double", 
            "dynamic_cast", "else", "enum", "explicit", "export", "extern", "false",
            "float", "for", "friend", "goto", "if", "inline", "int", "long", "mutable",
            "namespace", "new", "operator", "private", "protected", "public", 
            "register", "reinterpret_cast", "return", "short", "signed", "sizeof",
            "static", "static_cast", "struct", "switch", "template", "this", "throw",
            "true", "try", "typedef", "typeid", "typename", "union", "unsigned", 
            "using", "virtual", "void", "volatile", "wchar_t", "while"};
            //
            typedef patl::trie_set<std::string> ReservSet;
            typedef ReservSet::const_vertex const_vertex;
            const ReservSet rvset(X, X + sizeof(X) / sizeof(X[0]));
            //
            printf("*** Regexp:\n");
            const_vertex vtx = rvset.root();
            print_regexp(0, vtx.preorder_begin(8), vtx.preorder_end());
            printf("\n");
    }
    //
    printf("\n--- [super_]maxrep_iterator\n\n");
    //
    {
        typedef patl::suffix_set<char*> SuffixSet;
        char str[] =
            //"abrakadabraa";
            "xabcyiiizabcqabcyr";
            //"cxxaxxaxxb";
            //"How many wood would a woodchuck chuck.";
            //"xgtcacaytgtgacz";
        printf("*** string: '%s':\n", str);
        SuffixSet suffix(str);
        for (word_t i = 0; i != sizeof(str) - 1; ++i)
            suffix.push_back();
        for (uxn::patl::maxrep_iterator<SuffixSet> mrit(&suffix)
            ; !mrit->is_root()
            ; ++mrit)
        {
            printf("'%s' x %d:",
                std::string(mrit->key(), mrit->length()).c_str(),
                mrit.freq());
            const SuffixSet::const_vertex vtx = mrit->get_vertex();
            for (SuffixSet::const_iterator it = vtx.begin()
                ; it != vtx.end()
                ; ++it)
                printf(" at %u", suffix.index_of(
                    static_cast<const SuffixSet::const_vertex&>(it)));
            printf("\n");
        }
        printf("---\n");
        for (uxn::patl::super_maxrep_iterator<SuffixSet> mrit(&suffix)
            ; !mrit->is_root()
            ; ++mrit)
        {
            printf("'%s' x %d:",
                std::string(mrit->key(), mrit->length()).c_str(),
                mrit.freq());
            const SuffixSet::const_vertex vtx = mrit->get_vertex();
            for (SuffixSet::const_iterator it = vtx.begin()
                ; it != vtx.end()
                ; ++it)
                printf(" at %u", suffix.index_of(
                    static_cast<const SuffixSet::const_vertex&>(it)));
            printf("\n");
        }
    }
    //
    printf("\n--- search tandem repeats in O(n)\n\n");
    //
    {
        //typedef int typ;
        typedef char typ;
        typedef patl::suffix_set<const typ*> suffix_t;
        //typ arr[] = {10, 5, 6, 7, 5, 6, 7, 89, 64};
        typ arr[] = "qabrabrabrweabrabraaaad";
        //typ arr[] = "qweabrabrrrrd";
        printf("*** string: '%s':\n", arr);
        suffix_t suf(arr, 16 /* maximal length of tandem repeat + 1 */);
        do
        {
            const suffix_t::const_vertex
                vtx = suf.push_back(),
                sibl = vtx.sibling();
            if (suf.size() > 1)
            {
                const int skip = vtx.skip() / 8 / sizeof(typ);
                const word_t
                    delta = vtx.key() - sibl.key(),
                    count = skip / delta + 1;
                if (count > 1)
                {
                    printf("begin: %u, length: %u, count: %u\n",
                        sibl.key() - arr,
                        delta,
                        count);
                    suf.rebind(sibl.key() + delta * count);
                    suf.clear();
                }
                if (!suf.empty() && suf.endpoint())
                    suf.pop_front();
            }
        } while (suf.keys() + suf.size() != arr + sizeof(arr) / sizeof(arr[0]));
    }
    //
    printf("\n--- generate graphviz dot\n\n");
    //
    patl::patricia_dot_creator<StringSet>().create(vtx_root);
#if 0 // pat_.dot & pat_.clust.dot creation
    {
        std::ifstream fin(argc > 1 ? argv[1] : "WORD.LST");
        if (fin.is_open())
        {
            StringSet dict;
            std::string str;
            while (fin >> str)
                dict.insert(str);
            const_vertex vtx(dict.root());
            //
#if 0
            vtx.mismatch("patch", 5 * 8);
            typedef StringSet::const_preorder_iterator const_preorder_iterator;
            const_preorder_iterator
                itBeg = vtx.preorder_begin(),
                itEnd = vtx.preorder_end(),
                it = itBeg;
            for (; it != itEnd; it.increment(6 * 8))
            {
                if (it->limited(6 * 8))
                    printf("* ");
                printf("%d\t%s\n", it->skip(), it->key().c_str());
            }
            printf("---\n");
            while (it != itBeg)
            {
                it.decrement(6 * 8);
                if (it->limited(6 * 8))
                    printf("* ");
                printf("%d\t%s\n", it->skip(), it->key().c_str());
            }
#else
            vtx.mismatch("patr", 4 * 8);
            {
                std::ofstream fout("patr_.dot");
                patl::patricia_dot_creator<StringSet, std::ofstream>(fout).create(vtx);
            }
            printf("\npatr_.dot created!\n");
            {
                std::ofstream fout("patr_.clust.dot");
                patl::patricia_dot_creator<StringSet, std::ofstream>(fout).create(vtx, true);
            }
            printf("\npatr_.clust.dot created!\n");
#endif
        }
        else