Exemplo n.º 1
0
//@+node:gcross.20101224191604.2770: ** Functions
//@+node:gcross.20110114154616.2017: *3* channelMatrix
IntMatrix channelMatrix(Space& space, const BoolMatrix& matrix) {
    BoolVarArgs vars = matrix.get_array();
    IntVarArgs vars_as_ints(space,vars.size(),0,1);
    BOOST_FOREACH(const unsigned int i, irange(0u,(unsigned int)vars.size())) { channel(space,vars[i],vars_as_ints[i]); }
    return IntMatrix(vars_as_ints,matrix.width(),matrix.height());
}
Exemplo n.º 2
0
void EventData::write(Xml& xml) const
      {
      switch(_type) {
            case ME_NOTE:
                  xml.tagE(QString("note  tick=\"%1\" channel=\"%2\" len=\"%3\" pitch=\"%4\" velo=\"%5\"")
                     .arg(_ontime).arg(_channel).arg(_duration).arg(pitch()).arg(velo()));
                  break;

            case ME_NOTEON:
                  xml.tagE(QString("note-on  tick=\"%1\" channel=\"%2\" pitch=\"%3\" velo=\"%4\"")
                     .arg(_ontime).arg(_channel).arg(pitch()).arg(velo()));
                  break;

            case ME_NOTEOFF:
                  xml.tagE(QString("note-off  tick=\"%1\" channel=\"%2\" pitch=\"%3\" velo=\"%4\"")
                     .arg(_ontime).arg(_channel).arg(pitch()).arg(velo()));
                  break;

            case ME_CONTROLLER:
                  if (controller() == CTRL_PROGRAM) {
                        if ((_ontime == -1) && (_channel == 0)) {
                              xml.tagE(QString("program value=\"%1\"").arg(value()));
                              }
                        else {
                              xml.tagE(QString("program tick=\"%1\" channel=\"%2\" value=\"%3\"")
                                 .arg(ontime()).arg(channel()).arg(value()));
                              }
                        }
                  else {
                        if ((ontime() == -1) && (channel() == 0)) {
                              xml.tagE(QString("controller ctrl=\"%1\" value=\"%2\"")
                                 .arg(controller()).arg(value()));
                              }
                        else {
                              xml.tagE(QString("controller tick=\"%1\" channel=\"%2\" ctrl=\"%3\" value=\"%4\"")
                                 .arg(ontime()).arg(channel()).arg(controller()).arg(value()));
                              }
                        }
                  break;

            case ME_SYSEX:
                  xml.stag(QString("sysex tick=\"%1\" len=\"%2\"").arg(ontime()).arg(_len));
                  xml.dump(_len, _data);
                  xml.etag();
                  break;

            case ME_META:
                  switch(metaType()) {
                        case META_TRACK_NAME:
                              xml.tag(QString("TrackName tick=\"%1\"").arg(ontime()), QString((char*)(data())));
                              break;

                        case META_LYRIC:
                              xml.tag(QString("Lyric tick=\"%1\"").arg(ontime()), QString((char*)(data())));
                              break;

                        case META_KEY_SIGNATURE:
                              {
                              const char* keyTable[] = {
                                    "Ces", "Ges", "Des", "As", "Es", "Bes", "F",
                                    "C",
                                    "G", "D", "A", "E", "B", "Fis", "Cis"
                                    };
                              int key = (char)(_data[0]) + 7;
                              if (key < 0 || key > 14) {
                                    qDebug("bad key signature %d\n", key);
                                    key = 0;
                                    }
                              QString sex(_data[1] ? "Minor" : "Major");
                              QString keyName(keyTable[key]);
                              xml.tag(QString("Key tick=\"%1\" key=\"%2\" sex=\"%3\"").arg(ontime()).arg(_data[0]).arg(_data[1]),
                                 QString("%1 %2").arg(keyName).arg(sex));
                              }
                              break;

                        case META_TIME_SIGNATURE:
                              xml.tagE(QString("TimeSig tick=\"%1\" num=\"%2\" denom=\"%3\" metro=\"%4\" quarter=\"%5\"")
                                 .arg(ontime())
                                 .arg(int(_data[0]))
                                 .arg(int(_data[1]))
                                 .arg(int(_data[2]))
                                 .arg(int(_data[3])));
                              break;

                        case META_TEMPO:
                              {
                              unsigned tempo = _data[2] + (_data[1] << 8) + (_data[0] << 16);
                              xml.tagE(QString("Tempo tick=\"%1\" value=\"%2\"").arg(ontime()).arg(tempo));
                              }
                              break;

                        default:
                              xml.stag(QString("Meta tick=\"%1\" type=\"%2\" len=\"%3\" name=\"%4\"")
                                 .arg(ontime()).arg(metaType()).arg(_len).arg(midiMetaName(metaType())));
                              xml.dump(_len, _data);
                              xml.etag();
                              break;
                        }
                  break;
            }
      }
Exemplo n.º 3
0
Channel RabbitMQConnection::getChannel(){
	Channel channel(*this);
	return channel;
}
int main(int argc, const char **argv)
{
	po::options_description	options("usage");
	int fd = -1;

	try
	{
		std::string host;
		std::string port;
		std::string filename;
		std::string start_string;
		std::string length_string;
		std::string chunk_size_string;
		unsigned int start, length, chunk_size;
		bool use_udp = false;
		bool verbose = false;
		bool verbose2 = false;
		bool nocommit = false;
		bool noreset = false;
		bool notemp = false;
		bool otawrite = false;
		bool use_force = false;
		bool erase_before_write = false;
		bool cmd_write = false;
		bool cmd_simulate = false;
		bool cmd_verify = false;
		bool cmd_checksum = false;
		bool cmd_read = false;
		bool force_used;
		action_t action;

		options.add_options()
			("checksum,C",	po::bool_switch(&cmd_checksum)->implicit_value(true),				"CHECKSUM")
			("chunksize,c",	po::value<std::string>(&chunk_size_string)->default_value("0"),		"send/receive chunk size")
			("erase,e",		po::bool_switch(&erase_before_write)->implicit_value(true),			"erase before write (instead of during write)")
			("filename,f",	po::value<std::string>(&filename),									"file name")
			("force,F",		po::bool_switch(&use_force)->implicit_value(true),					"use force if image seems to be incompatible")
			("host,h",		po::value<std::string>(&host)->required(),							"host to connect to")
			("length,l",	po::value<std::string>(&length_string)->default_value("0x1000"),	"read length")
			("nocommit,n",	po::bool_switch(&nocommit)->implicit_value(true),					"don't commit after writing")
			("noreset,N",	po::bool_switch(&noreset)->implicit_value(true),					"don't reset after commit")
			("notemp,t",	po::bool_switch(&notemp)->implicit_value(true),						"don't commit temporarily, commit to flash")
			("port,p",		po::value<std::string>(&port)->default_value("24"),					"port to connect to")
			("start,s",		po::value<std::string>(&start_string)->default_value("2147483647"),	"send/receive start address")
			("read,R",		po::bool_switch(&cmd_read)->implicit_value(true),					"READ")
			("simulate,S",	po::bool_switch(&cmd_simulate)->implicit_value(true),				"WRITE simulate")
			("udp,u",		po::bool_switch(&use_udp)->implicit_value(true),					"use UDP instead of TCP")
			("verbose,v",	po::bool_switch(&verbose)->implicit_value(true),					"verbose output")
			("verbose2,x",	po::bool_switch(&verbose2)->implicit_value(true),					"less verbose output")
			("verify,V",	po::bool_switch(&cmd_verify)->implicit_value(true),					"VERIFY")
			("write,W",		po::bool_switch(&cmd_write)->implicit_value(true),					"WRITE");

		po::positional_options_description positional_options;

		po::variables_map varmap;
		po::store(po::parse_command_line(argc, argv, options), varmap);
		po::notify(varmap);

		if(cmd_checksum)
			action = action_checksum;
		else
			if(cmd_verify)
				action = action_verify;
			else
				if(cmd_simulate)
					action = action_simulate;
				else
					if(cmd_write)
						action = action_write;
					else
						if(cmd_read)
							action = action_read;
						else
							action = action_none;

		start = 0;
		chunk_size = 0;

		try
		{
			chunk_size = std::stoi(chunk_size_string, 0, 0);
		}
		catch(...)
		{
			throw(std::string("invalid value for chunk size argument"));
		}

		try
		{
			start = std::stoi(start_string, 0, 0);
		}
		catch(...)
		{
			throw(std::string("invalid value for start argument"));
		}

		try
		{
			length = std::stoi(length_string, 0, 0);
		}
		catch(...)
		{
			throw(std::string("invalid value for length argument"));
		}

		std::string reply;
		std::vector<int> int_value;
		std::vector<std::string> string_value;
		unsigned int flash_sector_size, flash_ota, flash_slots, flash_slot;
		unsigned int flash_address[4];
		unsigned int preferred_chunk_size;

		GenericSocket channel(host, port, use_udp, verbose);

		force_used = false;

		try
		{
			process(channel, "flash-info", reply, "OK [^,]+, sector size: ([0-9]+)[^,]+, OTA update available: ([0-9]+), "
						"slots: ([0-9]+), slot: ([0-9]+), "
						"address: ([0-9]+), address: ([0-9]+), address: ([0-9]+), address: ([0-9]+)"
						"(?:, preferred chunk size: ([0-9]+))?"
						"\\s*",
						string_value, int_value, verbose);
		}
		catch(std::string &e)
		{
			if(use_force)
			{
				std::cout << "OTA incompatible image, trying to continue due to force flag: " << e << std::endl;
				force_used = true;
			}
			else
				throw(std::string("OTA incompatible image: ") + e);
		}

		if(force_used)
		{
			flash_sector_size = 4096;
			flash_ota = 0;
			flash_slots = 0;
			flash_slot = 0;
			flash_address[0] = 0;
			flash_address[1] = 0;
			flash_address[2] = 0;
			flash_address[3] = 0;
			preferred_chunk_size = 512;
		}
		else
		{
			flash_sector_size = int_value[0];
			flash_ota = int_value[1];
			flash_slots = int_value[2];
			flash_slot = int_value[3];
			flash_address[0] = int_value[4];
			flash_address[1] = int_value[5];
			flash_address[2] = int_value[6];
			flash_address[3] = int_value[7];
			preferred_chunk_size = int_value[8];
		}

		std::cout << "flash operations available, sector size: " << flash_sector_size;

		if(flash_ota)
			std::cout << ", OTA update available, slots: " << flash_slots << ", current slot: " << flash_slot
					<< ", address[0]: 0x" << std::setw(6) << std::setfill('0') << std::hex << flash_address[0]
					<< ", address[1]: 0x" << std::setw(6) << std::setfill('0') << std::hex << flash_address[1]
					<< ", address[2]: 0x" << std::setw(6) << std::setfill('0') << std::hex << flash_address[2]
					<< ", address[3]: 0x" << std::setw(6) << std::setfill('0') << std::hex << flash_address[3]
					<< ", preferred chunk size: " << std::setw(0) << std::setfill(' ') << std::dec << preferred_chunk_size << std::endl;
		else
			std::cout << ", OTA update NOT available" << std::endl;

		if(chunk_size == 0)
			chunk_size = preferred_chunk_size;

		if(chunk_size == 0)
			chunk_size = 512;

		if((flash_sector_size % chunk_size) != 0)
			throw(std::string("chunk size should be dividable by flash sector size"));

		if(start == 2147483647)
		{
			if(flash_ota)
			{
				if(action == action_write)
				{
					flash_slot++;

					if(flash_slot >= flash_slots)
						flash_slot = 0;
				}

				start = flash_address[flash_slot];
				otawrite = true;
			}
			else
				throw(std::string("no start address supplied and image does not support OTA updating"));
		}

		if((start % flash_sector_size) != 0)
			throw(std::string("start address should be dividable by flash sector size"));

		int64_t file_length = 0;

		if((action != action_none) && (action != action_read))
		{
			struct stat stat;

			if(filename.empty())
				throw(std::string("file name required"));

			if((fd = open(filename.c_str(), O_RDONLY, 0)) < 0)
				throw(std::string("file not found"));

			fstat(fd, &stat);

			file_length = stat.st_size;
		}

		if(action == action_read)
		{
			if(filename.empty())
				throw(std::string("file name required"));

			if((fd = open(filename.c_str(), O_WRONLY | O_TRUNC | O_CREAT, 0777)) < 0)
				throw(std::string("can't create file"));

			file_length = 0;
		}

		switch(action)
		{
			case(action_read):
			{
				command_read(channel, fd, start, length, flash_sector_size, chunk_size, verbose);
				break;
			}

			case(action_checksum):
			{
				command_checksum(channel, fd, file_length, start, flash_sector_size, verbose);
				break;
			}

			case(action_write):
			case(action_simulate):
			case(action_verify):
			{
				command_write(channel, fd, file_length, start, flash_sector_size, chunk_size, verbose, action, erase_before_write);
				break;
			}

			case(action_none):
			{
				break;
			}
		}

		if((action == action_write) && otawrite)
		{
			if(!nocommit)
			{
				std::string send_string;
				std::string reply;

				if(notemp)
				{
					send_string = std::string("flash-select ") + std::to_string(flash_slot);
					process(channel, send_string, reply, "OK flash-select: slot ([0-9]+) selected, address ([0-9]+)\\s*", string_value, int_value, verbose || verbose2);
				}
				else
				{
					send_string = std::string("flash-select-once ") + std::to_string(flash_slot);
					process(channel, send_string, reply, "OK flash-select-once: slot ([0-9]+) selected, address ([0-9]+)\\s*", string_value, int_value, verbose ||verbose2);
				}

				if((unsigned int)int_value[0] != flash_slot)
					throw(std::string("flash-select failed, local slot (") + std::to_string(flash_slot) + ") != remote slot (" + std::to_string(int_value[0]) + ")");

				if((unsigned int)int_value[1] != start)
					throw(std::string("flash-select failed, local address (") +  std::to_string(flash_slot) + ") != remote address (" + std::to_string(int_value[0]) + ")");

				if(notemp)
					std::cout << "selected boot slot";
				else
					std::cout << "selected one time boot slot";

				std::cout << ": " << flash_slot << ", address: 0x" << std::hex << std::setw(6) << std::setfill('0') << start << std::dec << std::setw(0) << std::endl;

				if(!noreset)
				{
					std::cout << "rebooting" << std::endl;

					channel.send(1000, std::string("reset"));

					sleep(2);

					channel.reconnect();

					std::cout << "reboot finished" << std::endl;

					if(!notemp)
					{
						process(channel, "flash-info", reply, "OK [^,]+, sector size: ([0-9]+)[^,]+, OTA update available: ([0-9]+), "
									"slots: ([0-9]+), slot: ([0-9]+), "
									"address: ([0-9]+), address: ([0-9]+), address: ([0-9]+), address: ([0-9]+)"
									"(?:, preferred chunk size: ([0-9]+))?"
									"\\s*",
									string_value, int_value, verbose);

						if(int_value[3] != (int)flash_slot)
							std::cout << "boot failed, requested slot: " << flash_slot << ", active slot: " << int_value[3] << std::endl;
						else
						{
							std::cout << "boot succeeded, permanently selecting boot slot: " << flash_slot << ", address: 0x" << std::hex << std::setw(6) << std::setfill('0') << start << std::dec << std::setw(0) << std::endl;

							std::string send_string;
							std::string reply;

							send_string = std::string("flash-select ") + std::to_string(flash_slot);
							process(channel, send_string, reply,
									"OK flash-select: slot ([0-9]+) selected, address ([0-9]+)\\s*",
									string_value, int_value, verbose || verbose2);

							if((unsigned int)int_value[0] != flash_slot)
								throw(std::string("flash-select failed, local slot (") + std::to_string(flash_slot) + ") != remote slot (" + std::to_string(int_value[0]) + ")");

							if((unsigned int)int_value[1] != start)
								throw(std::string("flash-select failed, local address (") + std::to_string(flash_slot) +  ") != remote address (" + std::to_string(int_value[0]) + ")");
						}
					}
				}

				process(channel, "stats", reply, "> firmware version date: ([a-zA-Z0-9: ]+).*", string_value, int_value, verbose, 1000);

				std::cout << "firmware version: " << string_value[0] << std::endl;
			}
		}
	}
	catch(const po::error &e)
	{
		std::cerr << std::endl << "espflash: " << e.what() << std::endl << options;
		goto error;
	}
	catch(const std::exception &e)
	{
		std::cerr << std::endl << "espflash: " << e.what() << std::endl;
		goto error;
	}
	catch(const std::string &e)
	{
		std::cerr << std::endl << "espflash: " << e << std::endl;
		goto error;
	}
	catch(...)
	{
		std::cerr << std::endl << "espflash: unknown exception caught" << std::endl;
		goto error;
	}

	if(fd >= 0)
		close(fd);

	return(0);

error:
	if(fd >= 0)
		close(fd);

	return(1);
}
Exemplo n.º 5
0
NS_IMETHODIMP
nsFeedSniffer::GetMIMETypeFromContent(nsIRequest* request, 
                                      const PRUint8* data, 
                                      PRUint32 length, 
                                      nsACString& sniffedType)
{
  nsCOMPtr<nsIHttpChannel> channel(do_QueryInterface(request));
  if (!channel)
    return NS_ERROR_NO_INTERFACE;

  // Check that this is a GET request, since you can't subscribe to a POST...
  nsCAutoString method;
  channel->GetRequestMethod(method);
  if (!method.Equals("GET")) {
    sniffedType.Truncate();
    return NS_OK;
  }

  // We need to find out if this is a load of a view-source document. In this
  // case we do not want to override the content type, since the source display
  // does not need to be converted from feed format to XUL. More importantly, 
  // we don't want to change the content type from something 
  // nsContentDLF::CreateInstance knows about (e.g. application/xml, text/html 
  // etc) to something that only the application fe knows about (maybe.feed) 
  // thus deactivating syntax highlighting.
  nsCOMPtr<nsIURI> originalURI;
  channel->GetOriginalURI(getter_AddRefs(originalURI));

  nsCAutoString scheme;
  originalURI->GetScheme(scheme);
  if (scheme.EqualsLiteral("view-source")) {
    sniffedType.Truncate();
    return NS_OK;
  }

  // Check the Content-Type to see if it is set correctly. If it is set to 
  // something specific that we think is a reliable indication of a feed, don't
  // bother sniffing since we assume the site maintainer knows what they're 
  // doing. 
  nsCAutoString contentType;
  channel->GetContentType(contentType);
  bool noSniff = contentType.EqualsLiteral(TYPE_RSS) ||
                   contentType.EqualsLiteral(TYPE_ATOM);

  // Check to see if this was a feed request from the location bar or from
  // the feed: protocol. This is also a reliable indication.
  // The value of the header doesn't matter.  
  if (!noSniff) {
    nsCAutoString sniffHeader;
    nsresult foundHeader =
      channel->GetRequestHeader(NS_LITERAL_CSTRING("X-Moz-Is-Feed"),
                                sniffHeader);
    noSniff = NS_SUCCEEDED(foundHeader);
  }

  if (noSniff) {
    // check for an attachment after we have a likely feed.
    if(HasAttachmentDisposition(channel)) {
      sniffedType.Truncate();
      return NS_OK;
    }

    // set the feed header as a response header, since we have good metadata
    // telling us that the feed is supposed to be RSS or Atom
    channel->SetResponseHeader(NS_LITERAL_CSTRING("X-Moz-Is-Feed"),
                               NS_LITERAL_CSTRING("1"), false);
    sniffedType.AssignLiteral(TYPE_MAYBE_FEED);
    return NS_OK;
  }

  // Don't sniff arbitrary types.  Limit sniffing to situations that
  // we think can reasonably arise.
  if (!contentType.EqualsLiteral(TEXT_HTML) &&
      !contentType.EqualsLiteral(APPLICATION_OCTET_STREAM) &&
      // Same criterion as XMLHttpRequest.  Should we be checking for "+xml"
      // and check for text/xml and application/xml by hand instead?
      contentType.Find("xml") == -1) {
    sniffedType.Truncate();
    return NS_OK;
  }

  // Now we need to potentially decompress data served with 
  // Content-Encoding: gzip
  nsresult rv = ConvertEncodedData(request, data, length);
  if (NS_FAILED(rv))
    return rv;

  // We cap the number of bytes to scan at MAX_BYTES to prevent picking up 
  // false positives by accidentally reading document content, e.g. a "how to
  // make a feed" page.
  const char* testData;
  if (mDecodedData.IsEmpty()) {
    testData = (const char*)data;
    length = NS_MIN(length, MAX_BYTES);
  } else {
    testData = mDecodedData.get();
    length = NS_MIN(mDecodedData.Length(), MAX_BYTES);
  }

  // The strategy here is based on that described in:
  // http://blogs.msdn.com/rssteam/articles/PublishersGuide.aspx
  // for interoperarbility purposes.

  // Thus begins the actual sniffing.
  nsDependentCSubstring dataString((const char*)testData, length);

  bool isFeed = false;

  // RSS 0.91/0.92/2.0
  isFeed = ContainsTopLevelSubstring(dataString, "<rss");

  // Atom 1.0
  if (!isFeed)
    isFeed = ContainsTopLevelSubstring(dataString, "<feed");

  // RSS 1.0
  if (!isFeed) {
    isFeed = ContainsTopLevelSubstring(dataString, "<rdf:RDF") &&
      dataString.Find(NS_RDF) != -1 &&
      dataString.Find(NS_RSS) != -1;
  }

  // If we sniffed a feed, coerce our internal type
  if (isFeed && !HasAttachmentDisposition(channel))
    sniffedType.AssignLiteral(TYPE_MAYBE_FEED);
  else
    sniffedType.Truncate();
  return NS_OK;
}
Exemplo n.º 6
0
void MainWindow::setupConnections()
{
	int		i;

	/*
		Andrea修改
	*/
	//connect( openButton,		  SIGNAL(clicked()), this, SLOT( launchBMPImport() ) );  測試用 

    connect( openBMP,			 	SIGNAL(clicked()),						this,       			SLOT(launchBMPImport()) );						// 按下open BMP  可以讀取圖檔  Andrea
    connect( openBMP_2,			 	SIGNAL(clicked()),						this,       			SLOT(launchBMPImport()) );						// 按下open BMP  可以讀取圖檔  Andrea    2號用在measure
	connect( progress,				SIGNAL(signalImage(int,QImage)),		this,					SLOT(displayImage(int,QImage)) );				// 輸出畫面到顯示視窗

	connect( filedata,			 	SIGNAL(svgChanged(QString)),			pivDisplay_3,			SLOT(displaySVG(QString)) );					// 丟svg的方式顯示圖片 (svg暫存在硬碟)   丟到視窗三去做顯示

	connect( ScaleW,			 	SIGNAL(valueChanged(int)),				settings,    			SLOT(set_scale_w(int)) );						// 設定 Gauss filter scale w
	connect( ScaleL,			 	SIGNAL(valueChanged(int)),				settings,    			SLOT(set_scale_l(int)) );						// 設定 Gauss filter scale l
	connect( measureX,			 	SIGNAL(valueChanged(int)),				settings,    			SLOT(set_measure_X(int)) );						// 設定 Measure的座標X
	connect( measureY,			 	SIGNAL(valueChanged(int)),				settings,    			SLOT(set_measure_Y(int)) );						// 設定 Measure的座標Y
	connect( this,               	SIGNAL(doprocess()),                	process,				SLOT(processBatch()) );							// 進行process的動作
	connect( DoFilter,			 	SIGNAL(clicked()),						this,					SLOT(blob()) );									// 按下按鈕 開始執行blob detector  (包含subblob  watershed)
	connect( ChannelButton,			SIGNAL(clicked()),						this,					SLOT(channel()) );								// 抽取指定顏色的通道 
	connect( FFTJunctionButton,   	SIGNAL(clicked()),						this,					SLOT(FFTJunctionProcess()) );					// 按下按鈕 開始執行 FFT Junction Detector
	connect( SteerJunctionButton, 	SIGNAL(clicked()),						this,					SLOT(SteerJunctionProcess()) );					// 按下按鈕 開始執行 Steer Junction Detector
	connect( EdgeButton,		  	SIGNAL(clicked()),						this,					SLOT(EdgeProcess()) );							// 按下按鈕 開始執行 Subpixel Edge
	connect( CornerButton,		  	SIGNAL(clicked()),						this,					SLOT(CornerProcess()) );						// 按下Corner的按鈕 進行subpixel的Corner計算
	
	//connect( process,			  	SIGNAL(imageThrow(QImage)),				pivDisplay,				SLOT(displayBMP(QImage)) );						// 計算好 Gauss Filter 將資料丟給顯示
	connect( process,			  	SIGNAL(signalsGress(int)),				filterProgress,			SLOT(setValue(int)) );							// 設定進度條
	connect( process,			  	SIGNAL(signalsGress(int)),				measureProgress,		SLOT(setValue(int)) );							// 設定進度條
	connect( process,			  	SIGNAL(signalTabText(int,QString)),		this,					SLOT(setTabText(int,QString)) );				// 設定進度條

	connect( blobCombo,			  	SIGNAL(currentIndexChanged(int)),		this,					SLOT(setBlobmethod(int)) );						// 設定現在執行的是哪一個blob detector
	connect( waterCheck,		  	SIGNAL(stateChanged(int)),				this,					SLOT(setHighlight(int)) );						// 設定是否要反白
	connect( waterCombo,		  	SIGNAL(currentIndexChanged(int)),		this,					SLOT(setWatershed(int)) );						// 設定哪個watershed方法  4.8 4.1 mser


	// 把訊息印到除錯訊息的地方   append  or   setText
	connect( filedata,   			SIGNAL(debugSignal(QString)),     		text_debug,				SLOT(append(QString)) );
	connect( process,    			SIGNAL(debugSignal(QString)),     		text_debug,				SLOT(append(QString)) );
	connect( progress,	 			SIGNAL(debugSignal(QString)),	   		text_debug,				SLOT(append(QString)) );

	// 這邊跟顯示畫面 pointlist有關
	for( i = 0; i < 2; i++ )
		connect( display[i],			SIGNAL(mousePressed(PIXEL)),			this,					SLOT(addPixel(PIXEL)) );					// 點擊畫面 更新資料
	connect( progress,				SIGNAL(updateWidgeB()),					pointList[1],			SLOT(updatePointList()) );						// 將資料顯示到 point list (output)
	//connect( pointList[0],			SIGNAL(cellClicked(int,int)),			this,					SLOT(removePointList(int,int)) );				// 點擊 point list (input) 刪除點資料
	// 陰影檢測用 改成點擊到的時候顯示該區域到顯示區
	connect( pointList[0],			SIGNAL(cellClicked(int,int)),			this,					SLOT(view_square(int,int)) );
	connect( removeButton,			SIGNAL(clicked()),						this,					SLOT(remove_square()) );						// 移除某個square
	connect( clearButton,			SIGNAL(clicked()),						this,					SLOT(clearData()) );							// 按下clear按鈕  清空資料
	connect( inhenceCheck,			SIGNAL(stateChanged(int)),				settings,				SLOT(setInhence(int)) );						// 設定inhencement  判斷是抓單點陰影 還是整段的陰影 (應付noise很強 跟noise不強的case)
	connect( saveCheck,				SIGNAL(stateChanged(int)),				settings,				SLOT(setSaved(int))	);							// 設定是否要將結果輸出到檔案 (image部分)
	connect( batchCheck,			SIGNAL(stateChanged(int)),				settings,				SLOT(setBatch(int)) );							// 設定是否為批次作業
	
    // Importing
   // connect(importButton,			SIGNAL(clicked()),						this,					SLOT(launchImageImport()));
   // connect(filedata,				SIGNAL(imagesImported()),				this,					SLOT(notifyFolderChange()));

    connect(vectorListWidget, SIGNAL(fileClicked(int)), this, SLOT(vectorClicked(int)));

    // The following should be moved into settings
    //
    connect(colourButtonFiltered, SIGNAL(clicked()), this, SLOT(chooseFilteredColour()));
    connect(colourButtonUnfiltered, SIGNAL(clicked()), this, SLOT(chooseUnfilteredColour()));
    connect(scaleSpin, SIGNAL(valueChanged(double)), settings, SLOT(setVectorScale(double)));
    connect(subSpin, SIGNAL(valueChanged(double)), settings, SLOT(setVectorSub(double)));

    // Process tab
    connect(hSizeCombo, SIGNAL(activated(int)), settings, SLOT(setIntLengthX(int)));
    connect(vSizeCombo, SIGNAL(activated(int)), settings, SLOT(setIntLengthY(int)));
    connect(hSpaceSpin, SIGNAL(valueChanged(int)), settings, SLOT(setDeltaX(int)));
    connect(vSpaceSpin, SIGNAL(valueChanged(int)), settings, SLOT(setDeltaY(int)));


    // DoingPIV
    connect(outputFolderEdit, SIGNAL(textEdited(QString)), this, SLOT(setOutput()));
    connect(outputFolderButton, SIGNAL(clicked()), this, SLOT(chooseOutputFolder()));
    connect(outputFormatCombo, SIGNAL(currentIndexChanged(int)), this, SLOT(setOutput()));


    connect(batchButton, SIGNAL(clicked()), process, SLOT(launchBatchWindow()));
    connect(process, SIGNAL(batchProcessed()), this, SLOT(batchDone()));


	//for( i = 0; i < displaySize; i++ )
	//	connect(display[i],   	SIGNAL(mousePressed(PIXEL)),			this,			SLOT(updatePositionPixel(PIXEL)));				// Andrea修改  點一下滑鼠,把RGB資訊輸入進去.


	/*connect(pivDisplay,   	SIGNAL(mousePressed(QPointF)),			this,			SLOT(uptdaePositionRGB(QPointF)));				// Andrea修改  點一下滑鼠,把RGB資訊輸入進去.
	connect(pivDisplay_2,  	SIGNAL(mousePressed(QPointF)),			this,			SLOT(uptdaePositionRGB(QPointF)));				// Andrea修改  點一下滑鼠,把RGB資訊輸入進去.   用在視窗2
	connect(pivDisplay,   	SIGNAL(mousePressed(QPointF)),			this,			SLOT(updatePositionXY(QPointF)));				// Andrea修改  點一下滑鼠,把座標輸入進去.
	connect(pivDisplay_2,  	SIGNAL(mousePressed(QPointF)),			this,			SLOT(updatePositionXY(QPointF)));				// Andrea修改  點一下滑鼠,把座標輸入進去.   用在視窗2*/



	//connect(pivDisplay,   	SIGNAL(mousePressed(QPointF)),			pivDisplay,		SLOT(mark_XY(QPointF)));						// Andrea修改  點一下滑鼠, 在上面標記點
	//connect(pivDisplay_2,  	SIGNAL(mousePressed(QPointF)),			pivDisplay_2,	SLOT(mark_XY(QPointF)));						// Andrea修改  點一下滑鼠, 在上面標記點    用在視窗2



	connect(this,			SIGNAL(set_measure_X(int)),				measureX,		SLOT(setValue(int) ) );							// 設定 X 座標的spinbox
	connect(this,			SIGNAL(set_measure_Y(int)),				measureY,		SLOT(setValue(int) ) );							// 設定 Y 座標的spinbox
	

}
Exemplo n.º 7
0
int
main(int argc,
     char ** argv)
{
/// @section csv_segmentation Chan-Sandberg-Vese segmentation
///
/// @subsection csv_theory Theory
/// Since the routine contains too many free parameters which makes it unreasonable to place it into a separate
/// function, all the code is kept in main(). Here's a rough explanation of what's Chan-Sandberg-Vese all about,
/// which is based on paper @cite Getreuer2012.
///
/// The Chan-Vese method seeks a contour @f$\mathcal{C}@f$ which minimizes the functional
/// @f[
///    \mathcal{F}[I;\,\mathcal{C},\,c_{1},\,c_{2}]=
///        \mu\mathrm{Length}(\mathcal{C})+
///        \nu\mathrm{Area}(\mathcal{C})+
///        \lambda_{1}\int_{\mathcal{C}}|I-c_{1}|^{2}\,\mathrm{d}x\mathrm{d}y+
///        \lambda_{2}\int_{\Omega\setminus\mathcal{C}}|I-c_{2}|^{2}\,\mathrm{d}x\mathrm{d}y\,,
/// @f]
/// where
///    - the single-channel image @f$I=I(x,\,y)@f$ is defined on the region @f$\Omega=[0,\,a]\times[0,\,b]@f$;
///         - regions in the integral limits, @f$\mathcal{C}@f$ and @f$\Omega\setminus\mathcal{C}@f$,
///           denote the region enclosed by the contour and the region outside the contour, respectively;
///    -  @f$\mu(=0.5)@f$, @f$\nu(=0)@f$, @f$\lambda_{1}(=1)@f$ and @f$\lambda_{2}(=1)@f$ are free parameters,
///       whereby only @f$\nu@f$ can be negative (default values in parentheses);
///    - @f$c_{1}@f$ and @f$c_{2}@f$ are constants that depend on the information of the regions enclosed by and
///      outside of the contour.
///
/// Instead of dealing with @f$\mathcal{C}@f$ explicitly, it's custom to define a level set function @f$u(x,\,y;\,t)@f$
/// so that its zero-level iso-surface (also: zero level set) coincides with the contour:
/// @f$\mathcal{C}=\{\Omega\ni(x,\,y)\,:\,u(x,\,y;\,t)=0\forall t\}@f$. This in turn leads us to a new definition
/// of the functional:
/// @f[
///      \mathcal{F}[I;\,u,\,c_{1},\,c_{2}] =
///             \mu\left(\int_{\Omega}|\nabla H(u)|\,\mathrm{d}x\mathrm{d}y\right)^{p}+
///             \nu\int_{\Omega}H(u)\,\mathrm{d}x\mathrm{d}y+
///             \lambda_{1}\int_{\Omega}|I-c_{1}|^{2}H(u)\,\mathrm{d}x\mathrm{d}y+
///             \lambda_{2}\int_{\Omega}|I-c_{2}|^{2}(1-H(u))\,\mathrm{d}x\mathrm{d}y\,.
/// @f]
/// In our implementation we've picked @f$p=1@f$, so that the first integral reduces to
/// @f[
///      \left.\mu\left(\int_{\Omega}|\nabla H(u)|\,\mathrm{d}x\mathrm{d}y\right)^{p}\right|_{p=1}=
///       \mu\int_{\Omega}\delta(u)|\nabla u|\,\mathrm{d}x\mathrm{d}y\,,
/// @f]
/// where @f$H(x)@f$ and @f$\delta(x)=H'(x)@f$ are Heaviside's step and Dirac's delta functions.
/// In this prescription @f$c_{1}@f$ and @f$c_{2}@f$ are now region averages and take the following form:
/// @f[
///      c_{1}=\frac{\int_{\Omega}IH(u)\mathrm{d}x\mathrm{d}y}{\int_{\Omega}H(u)\,\mathrm{d}x\mathrm{d}y}\,,\quad
///      c_{2}=\frac{\int_{\Omega}I(1-H(u))\mathrm{d}x\mathrm{d}y}{\int_{\Omega}(1 - H(u))\,\mathrm{d}x\mathrm{d}y}\,.
/// @f]
/// For practical reasons the functions are replaced by smooth/regularized versions (see regularized_heaviside() and
/// regularized_delta()):
/// @f[
///      H_{\epsilon}(x)=\frac{1}{2}\left[1+\frac{2}{\pi}\arctan\left(\frac{x}{\epsilon}\right)\right]\,,\quad
///      \delta_{\epsilon}(x)=\frac{\epsilon}{\pi\left(\epsilon^{2}+x^{2}\right)}\,,
/// @f]
/// with @f$\epsilon=1@f$ by default.
/// The interpretation of the functional @f$\mathcal{F}@f$ is the following:
///     - the first term penalizes the length of @f$\mathcal{C}@f$;
///     - the second term penalizes the area enclosed by the curve;
///     - the 3rd and 4th term penalize region averages inside and outside of the contour; in other words
///       it keeps track of the discrepancy between the two regions.
///
/// A stationary solution to @f$\mathcal{F}@f$, or equivalently the equation of motion (e.o.m) for the contour,
/// can be found by solving it with Euler-Lagrange equation, which results in
/// @f[
///    u_{t} = \delta_{\epsilon}(u)\left[\mu\kappa-\nu-\lambda_{1}(I-c_{1})^{2}+\lambda_{2}(I-c_{2})^{2}\right]\,,
/// @f]
/// where @f$\kappa=\nabla\cdot\left(\frac{\nabla u}{|\nabla u|}\right)@f$ is curvature of @f$u@f$.
///
/// If the (still 2D) image has @f$I@f$ has @f$N@f$ channels @f$\{I_{i}(x,\,y)\}_{i=1}^{N}@f$, there should still
/// be a single level set @f$u@f$, which leads us the following functional:
/// @f[
///    \mathcal{F}[I;\,u,\,\mathbf{c_{1}},\,\mathbf{c}_{2}]=
///      \mu\int_{\Omega}|\nabla H(u)|\mathrm{d}x\mathrm{d}y+
///      \nu\int_{\Omega}H(u)\mathrm{d}x\mathrm{d}y+
///      \int_{\Omega}\frac{1}{N}\sum_{i=1}^{N}\lambda_{1}^{(i)}|I_{i}-c_{1}^{(i)}|^{2}H(u)\mathrm{d}x\mathrm{d}y+
///      \int_{\Omega}\frac{1}{N}\sum_{i=1}^{N}\lambda_{2}^{(i)}|I_{i}-c_{2}^{(i)}|^{2}(1-H(u))\mathrm{d}x\mathrm{d}y\,.
/// @f]
/// Variables @f$\{c_{1}^{(i)},\,c_{2}^{(i)}\}_{i=1}^{N}@f$ retain their original meaning,
/// @f[
///     c_{1}^{(i)}=\frac{\int_{\Omega}I_{i}H(u)\mathrm{d}x\mathrm{d}y}{\int_{\Omega}H(u)\mathrm{d}x\mathrm{d}y}\,,\quad
///     c_{2}^{(i)}=\frac{\int_{\Omega}I_{i}(1-H(u))\mathrm{d}x\mathrm{d}y}{\int_{\Omega}(1-H(u))\mathrm{d}x\mathrm{d}y}
///     \quad\forall i=\{1,\,\ldots,\,N\}\,;
/// @f]
/// the constants @f$\{\lambda_{1}^{(i)},\,\lambda_{2}^{(i)}\}_{i=1}^{N}@f$ are defined for each channel separately.
/// This implementation consider only grayscale (@f$N=1@f$) and RGB (@f$N=3@f$) images, for which @f$\lambda_{i}=1@f$
/// by default for any @f$i@f$-th channel.
/// The corresponding e.o.m reads
/// @f[
///      u_{t}=\delta_{\epsilon}(u)\left[\mu\kappa-\nu-
///            \frac{1}{N}\sum_{i=1}^{N}\lambda_{1}^{(i)}\left(I_{i}-c_{1}^{(i)}\right)^{2}+
///            \frac{1}{N}\sum_{i=1}^{N}\lambda_{2}^{(i)}\left(I_{i}-c_{2}^{(i)}\right)^{2}\right]\,.
/// @f]
///
/// @subsection csv_numsch Numerical scheme
///
/// Finite difference expression for the curvature @f$\kappa@f$ is explained in curvature(). The advantage of this scheme
/// is that we only need nearest neighbouring points at current point while keeping the derivative centered at current point,
/// whereas naive implementation would use more distant points. Since we're dealing with a finite domain and therefore
/// boundaries, we don't have to "extend" the region by two pixels each direction. Instead, we just duplicate border pixels.
///
/// Rest of the calculation is actually quite straightforward -- the zero level set is iteratively updated with
/// @f[
///      u_{i,j}^{n+1}=u_{i,j}^{n}+\mathrm{d}t\;\delta_{\epsilon}(u_{i,j}^{n})\left[\kappa_{i,j}^{n}-\nu-
///      \frac{1}{N}\sum_{k=1}^N\lambda_{1}^{(k)}\left(I_{i,j}-c_{1}^{n,(k)}\right)+
///      \frac{1}{N}\sum_{k=1}^N\lambda_{2}^{(k)}\left(I_{i,j}-c_{2}^{n,(k)}\right)\right]\,.
/// @f]
/// The method is inherently implicit and is implemented with ordinary matrix operations. The first term in the brackets
/// has already been discussed; the second term is trivial; the final two terms are explained in region_variance() and
/// variance_penalty().
///
/// There are various ways to initialize the level set, and since we're solving a differential equation, different initial
/// conditions lead to different outcome. The simplest way is to let the user draw either rectangular or circular contour.
/// The level set will be evaluated with @f$+1@f$'s inside the contour and with @f$-1@f$'s outside of it.
/// A more optimal (here the default) contour would be checkerboard
/// @f[
///      u(i,\,j;\,0)=\sin\left(\frac{\pi}{5}i\right)\sin\left(\frac{\pi}{5}j\right)\,,
/// @f]
/// because it converges faster to a solution (see levelset_checkerboard()). The solution is reached when the maximum number
/// of iterations, @f$T_\max@f$, is reached or when @f$||u_{i,j}^{n+1}-u_{i,j}^{n}||_{2}\leqslant\delta ||\bar{I}||_{2}@f$,
/// where the subscript denotes @f$L_{2}@f$-norm, @f$\delta=(10^{-3})@f$ is tolerance parameter and @f$\bar{I}@f$ is
/// the intensity average in the image (averaged across the channels).
///
/// @subsection csv_summary Summary
///
/// The main logic described above starts with a timestep loop (look for the comment below); everything else preciding
/// that is actually sugar coating just to make the program usable for anyone.
///
/// If it isn't clear from above text or the code below, here is the list of variables which the user can pass as an argument
/// (the default values in the parentheses): @f$\mu(=0.5)@f$, @f$\nu(=0)@f$, @f$\mathrm{d}t(=1)@f$,
/// @f$\lambda_{1}^{(i)}(=1)@f$ and @f$\lambda_{1}^{(i)}(=1)@f$ @f$\forall i=1\ldots N@f$, @f$\epsilon(=1)@f$,
/// @f$\delta(=10^{-3})@f$, @f$T_\max@f$(=INT_MAX), @f$N(=1\;\mbox{or}\;3)@f$ (number of channels).
///
/// Other general options include:
///    - object selection (-s) -- the region enclosed by the contour will be cut out and placed onto white canvas and saved;
///    - region inversion (-I) -- sometimes the ROI is inverted; there's an option to circumvent that (goes with -s option);
///    - video output (-V) -- see contour evolution in a video (*.avi, the same filename as the image; see VideoWriterManager);
///    - overlay text (-O) -- puts overlay text (timesteps) on the video (goes with the previous option);
///    - frame rate (-f) -- frame rate of the video;
///    - line color (-l) -- color of the contour line (see Colors);
///    - rectangular (-R) or circular (-C) contour -- lets the user draw it on the image (see InteractiveData and its subclasses);
///    - grayscale image (-g) -- sometimes we just want do perform it on a black-white image, but the original source is RGB.
///
/// For Perona-Malik-specific parameters @f$K@f$, @f$L@f$, @f$T@f$, see perona_malik().
///
/// @sa curvature, region_variance, variance_penalty, levelset_checkerboard, VideoWriterManager, InteractiveData, Colors, perona_malik

  double mu, nu, eps, tol, dt, fps, K, L, T;
  int max_steps;
  std::vector<double> lambda1,
                      lambda2;
  std::string input_filename,
              text_position,
              line_color_str;
  bool grayscale         = false,
       write_video       = false,
       overlay_text      = false,
       object_selection  = false,
       invert            = false,
       segment           = false,
       rectangle_contour = false,
       circle_contour    = false;
  ChanVese::TextPosition pos = ChanVese::TextPosition::TopLeft;
  cv::Scalar contour_color = ChanVese::Colors::blue;

//-- Parse command line arguments
//   Negative values in multitoken are not an issue, b/c it doesn't make much sense
//   to use negative values for lambda1 and lambda2
  try
  {
    namespace po = boost::program_options;
    po::options_description desc("Allowed options", get_terminal_width());
    desc.add_options()
      ("help,h",                                                                               "this message")
      ("input,i",            po::value<std::string>(&input_filename),                          "input image")
      ("mu",                 po::value<double>(&mu) -> default_value(0.5),                     "length penalty parameter (must be positive or zero)")
      ("nu",                 po::value<double>(&nu) -> default_value(0),                       "area penalty parameter")
      ("dt",                 po::value<double>(&dt) -> default_value(1),                       "timestep")
      ("lambda1",            po::value<std::vector<double>>(&lambda1) -> multitoken(),         "penalty of variance inside the contour (default: 1's)")
      ("lambda2",            po::value<std::vector<double>>(&lambda2) -> multitoken(),         "penalty of variance outside the contour (default: 1's)")
      ("epsilon,e",          po::value<double>(&eps) -> default_value(1),                      "smoothing parameter in Heaviside/delta")
      ("tolerance,t",        po::value<double>(&tol) -> default_value(0.001),                  "tolerance in stopping condition")
      ("max-steps,N",        po::value<int>(&max_steps) -> default_value(-1),                  "maximum nof iterations (negative means unlimited)")
      ("fps,f",              po::value<double>(&fps) -> default_value(10),                     "video fps")
      ("overlay-pos,P",      po::value<std::string>(&text_position) -> default_value("TL"),    "overlay tex position; allowed only: TL, BL, TR, BR")
      ("line-color,l",       po::value<std::string>(&line_color_str) -> default_value("blue"), "contour color (allowed only: black, white, R, G, B, Y, M, C")
      ("edge-coef,K",        po::value<double>(&K) -> default_value(10),                       "coefficient for enhancing edge detection in Perona-Malik")
      ("laplacian-coef,L",   po::value<double>(&L) -> default_value(0.25),                     "coefficient in the gradient FD scheme of Perona-Malik (must be [0, 1/4])")
      ("segment-time,T",     po::value<double>(&T) -> default_value(20),                       "number of smoothing steps in Perona-Malik")
      ("segment,S",          po::bool_switch(&segment),                                        "segment the image with Perona-Malik beforehand")
      ("grayscale,g",        po::bool_switch(&grayscale),                                      "read in as grayscale")
      ("video,V",            po::bool_switch(&write_video),                                    "enable video output (changes the extension to '.avi')")
      ("overlay-text,O",     po::bool_switch(&overlay_text),                                   "add overlay text")
      ("invert-selection,I", po::bool_switch(&invert),                                         "invert selected region (see: select)")
      ("select,s",           po::bool_switch(&object_selection),                               "separate the region encolosed by the contour (adds suffix '_selection')")
      ("rectangle,R",        po::bool_switch(&rectangle_contour),                              "select rectangular contour interactively")
      ("circle,C",           po::bool_switch(&circle_contour),                                 "select circular contour interactively")
    ;
    po::variables_map vm;
    po::store(po::command_line_parser(argc, argv).options(desc).run(), vm);
    po::notify(vm);

    if(vm.count("help"))
    {
      std::cout << desc << "\n";
      return EXIT_SUCCESS;
    }
    if(! vm.count("input"))
      msg_exit("Error: you have to specify input file name!");
    else if(vm.count("input") && ! boost::filesystem::exists(input_filename))
      msg_exit("Error: file \"" + input_filename + "\" does not exists!");
    if(vm.count("dt") && dt <= 0)
      msg_exit("Cannot have negative or zero timestep: " + std::to_string(dt) + ".");
    if(vm.count("mu") && mu < 0)
      msg_exit("Length penalty parameter cannot be negative: " + std::to_string(mu) + ".");
    if(vm.count("lambda1"))
    {
      if(grayscale && lambda1.size() != 1)
        msg_exit("Too many lambda1 values for a grayscale image.");
      else if(! grayscale && lambda1.size() != 3)
        msg_exit("Number of lambda1 values must be 3 for a colored input image.");
      else if(grayscale && lambda1[0] < 0)
        msg_exit("The value of lambda1 cannot be negative.");
      else if(! grayscale && (lambda1[0] < 0 || lambda1[1] < 0 || lambda1[2] < 0))
        msg_exit("Any value of lambda1 cannot be negative.");
    }
    else if(! vm.count("lambda1"))
    {
      if(grayscale) lambda1 = {1};
      else          lambda1 = {1, 1, 1};
    }
    if(vm.count("lambda2"))
    {
      if(grayscale && lambda2.size() != 1)
        msg_exit("Too many lambda2 values for a grayscale image.");
      else if(! grayscale && lambda2.size() != 3)
        msg_exit("Number of lambda2 values must be 3 for a colored input image.");
      else if(grayscale && lambda2[0] < 0)
        msg_exit("The value of lambda2 cannot be negative.");
      else if(! grayscale && (lambda2[0] < 0 || lambda2[1] < 0 || lambda2[2] < 0))
        msg_exit("Any value of lambda2 cannot be negative.");
    }
    else if(! vm.count("lambda2"))
    {
      if(grayscale) lambda2 = {1};
      else          lambda2 = {1, 1, 1};
    }
    if(vm.count("eps") && eps < 0)
      msg_exit("Cannot have negative smoothing parameter: " + std::to_string(eps) + ".");
    if(vm.count("tol") && tol < 0)
      msg_exit("Cannot have negative tolerance: " + std::to_string(tol) + ".");
    if(vm.count("overlay-pos"))
    {
      if     (boost::iequals(text_position, "TL")) pos = ChanVese::TextPosition::TopLeft;
      else if(boost::iequals(text_position, "BL")) pos = ChanVese::TextPosition::BottomLeft;
      else if(boost::iequals(text_position, "TR")) pos = ChanVese::TextPosition::TopRight;
      else if(boost::iequals(text_position, "BR")) pos = ChanVese::TextPosition::BottomRight;
      else
        msg_exit("Invalid text position requested.\n"\
                 "Correct values are: TL -- top left\n"\
                 "                    BL -- bottom left\n"\
                 "                    TR -- top right\n"\
                 "                    BR -- bottom right"\
                );
    }
    if(vm.count("line-color"))
    {
      if     (boost::iequals(line_color_str, "red"))     contour_color = ChanVese::Colors::red;
      else if(boost::iequals(line_color_str, "green"))   contour_color = ChanVese::Colors::green;
      else if(boost::iequals(line_color_str, "blue"))    contour_color = ChanVese::Colors::blue;
      else if(boost::iequals(line_color_str, "black"))   contour_color = ChanVese::Colors::black;
      else if(boost::iequals(line_color_str, "white"))   contour_color = ChanVese::Colors::white;
      else if(boost::iequals(line_color_str, "magenta")) contour_color = ChanVese::Colors::magenta;
      else if(boost::iequals(line_color_str, "yellow"))  contour_color = ChanVese::Colors::yellow;
      else if(boost::iequals(line_color_str, "cyan"))    contour_color = ChanVese::Colors::cyan;
      else
        msg_exit("Invalid contour color requested.\n"\
                 "Correct values are: red, green, blue, black, white, magenta, yellow, cyan.");
    }
    if(vm.count("laplacian-coef") && (L > 0.25 || L < 0))
      msg_exit("The Laplacian coefficient in Perona-Malik segmentation must be between 0 and 0.25.");
    if(vm.count("segment-time") && (T < L))
      msg_exit("The segmentation duration must exceed the value of Laplacian coefficient, " +
               std::to_string(L) + ".");
    if(rectangle_contour && circle_contour)
      msg_exit("Cannot initialize with both rectangular and circular contour");
  }
  catch(std::exception & e)
  {
    msg_exit("error: " + std::string(e.what()));
  }

//-- Read the image (grayscale or BGR? RGB? BGR? help)
  cv::Mat _img;
  if(grayscale) _img = cv::imread(input_filename, CV_LOAD_IMAGE_GRAYSCALE);
  else          _img = cv::imread(input_filename, CV_LOAD_IMAGE_COLOR);
  if(! _img.data)
    msg_exit("Error on opening \"" + input_filename + "\" (probably not an image)!");

//-- Second conversion needed since we want to display a colored contour on a grayscale image
  cv::Mat img;
  if(grayscale) cv::cvtColor(_img, img, CV_GRAY2RGB);
  else          img = _img;
  _img.release();

//-- Determine the constants and define functionals
  max_steps = max_steps < 0 ? std::numeric_limits<int>::max() : max_steps;
  const int h = img.rows;
  const int w = img.cols;
  const int nof_channels = grayscale ? 1 : img.channels();
  const auto heaviside = std::bind(regularized_heaviside, std::placeholders::_1, eps);
  const auto delta = std::bind(regularized_delta, std::placeholders::_1, eps);

//-- Construct the level set
  cv::Mat u;
  if(rectangle_contour || circle_contour)
  {
    std::unique_ptr<InteractiveData> id;
    cv::startWindowThread();
    cv::namedWindow(WINDOW_TITLE, cv::WINDOW_NORMAL);

    if     (rectangle_contour)
      id = std::unique_ptr<InteractiveDataRect>(new InteractiveDataRect(&img, contour_color));
    else if(circle_contour)
      id = std::unique_ptr<InteractiveDataCirc>(new InteractiveDataCirc(&img, contour_color));

    if(id) cv::setMouseCallback(WINDOW_TITLE, on_mouse, id.get());
    cv::imshow(WINDOW_TITLE, img);
    cv::waitKey();
    cv::destroyWindow(WINDOW_TITLE);

    if(id)
    {
      if(! id -> is_ok())
        msg_exit("You must specify the contour with non-zero dimensions");
      u = id -> get_levelset(h, w);
    }
  }
  else
    u = levelset_checkerboard(h, w);

//-- Set up the video writer (and save the first frame)
  VideoWriterManager vwm;
  if(write_video)
  {
    vwm = VideoWriterManager(input_filename, img, contour_color, fps, pos, overlay_text);
    vwm.write_frame(u, overlay_text ? "t = 0" : "");
  }

//-- Split the channels
  std::vector<cv::Mat> channels;
  channels.reserve(nof_channels);
  cv::split(img, channels);
  if(grayscale) channels.erase(channels.begin() + 1, channels.end());

//-- Smooth the image with Perona-Malik
  cv::Mat smoothed_img;
  if(segment)
  {
    smoothed_img = perona_malik(channels, h, w, K, L, T);
    channels.clear();
    cv::split(smoothed_img, channels);
    cv::imwrite(add_suffix(input_filename, "pm"), smoothed_img);
  }

//-- Find intensity sum and derive the stopping condition
  cv::Mat intensity_avg = cv::Mat(h, w, CV_64FC1);
#pragma omp parallel for num_threads(nof_channels)
  for(int k = 0; k < nof_channels; ++k)
  {
    cv::Mat channel(h, w, intensity_avg.type());
    channels[k].convertTo(channel, channel.type());
    intensity_avg += channel;
  }
  intensity_avg /= nof_channels;
  double stop_cond = tol * cv::norm(intensity_avg, cv::NORM_L2);
  intensity_avg.release();

//-- Timestep loop
  for(int t = 1; t <= max_steps; ++t)
  {
    cv::Mat u_diff(cv::Mat::zeros(h, w, CV_64FC1));

//-- Channel loop
#pragma omp parallel for num_threads(nof_channels)
    for(int k = 0; k < nof_channels; ++k)
    {
      cv::Mat channel = channels[k];
//-- Find the average regional variances
      const double c1 = region_variance(channel, u, h, w, ChanVese::Region::Inside, heaviside);
      const double c2 = region_variance(channel, u, h, w, ChanVese::Region::Outside, heaviside);

//-- Calculate the contribution of one channel to the level set
      const cv::Mat variance_inside = variance_penalty(channel, h, w, c1, lambda1[k]);
      const cv::Mat variance_outside = variance_penalty(channel, h, w, c2, lambda2[k]);
      u_diff += -variance_inside + variance_outside;
    }
//-- Calculate the curvature (divergence of normalized gradient)
    const cv::Mat kappa = curvature(u, h, w);

//-- Mash the terms together
    u_diff = dt * (mu * kappa - nu + u_diff / nof_channels);

//-- Run delta function on the level set
    cv::Mat u_cp = u.clone();
    cv::parallel_for_(cv::Range(0, h * w), ParallelPixelFunction(u_cp, w, delta));

//-- Shift the level set
    cv::multiply(u_diff, u_cp, u_diff);
    const double u_diff_norm = cv::norm(u_diff, cv::NORM_L2);
    u += u_diff;

//-- Save the frame
    if(write_video) vwm.write_frame(u, overlay_text ? "t = " + std::to_string(t) : "");

//-- Check if we have achieved the desired precision
    if(u_diff_norm <= stop_cond) break;
  }

//-- Select the region enclosed by the contour and save it to the disk
  if(object_selection)
    cv::imwrite(add_suffix(input_filename, "selection"), separate(img, u, h, w, invert));

  return EXIT_SUCCESS;
}
Exemplo n.º 8
0
void PeersMgr::broadcastMsg(const QString &msg)
{
    QDataStream channel(iLink);
    channel << QString("send %1").arg(msg);
}
void main()
{
	int i, x,value;
	float start,finish;
	unsigned long int j;
	unsigned int mask=1;
	long int error, ferror;
	double progress, b;

	FILE *fp;
	if((fp=fopen("data_(63,31)m=3.txt","a"))==NULL)
	{
		printf("Can't open the data.txt\n");
		exit(0);
	}
	fclose(fp);


	srand(1977);

	mono_table();



	printf("\nEnter start SNR: ");
	scanf("%f", &start);
	printf("\nEnter finish SNR: ");
	scanf("%f", &finish);
	printf("\nseq_num: ");
	scanf("%d", &seq_num);


	for(SNR=start;SNR<=finish;SNR++)
	{	
		N0=(1.0/(float(k)/float(n)))/pow(10.0, SNR/10.0);
		sgm=sqrt(N0/2);
		b=1.0;
		error=0;
		//ferror=0; 
		for(j=1;j<=seq_num;j++)
		{

		//printf("\n\n*************For the %dth frame*************:\n", j);
		//Generate binary message
			for(i=0;i<k*p;i++)
				bi_message[i]=rand()%2;

			//Convert to nonbinary
			for(i=0;i<k;i++)
				message[i]=bi_message[p*i]+2*bi_message[p*i+1]+4*bi_message[p*i+2]+8*bi_message[p*i+3]
					   +16*bi_message[p*i+4]+32*bi_message[p*i+5];


			encoder();

	
			//Convert the codeword into binary
			for(i=0;i<n;i++)
			{
				value=codeword[i];
				mask=1;
				for(x=0;x<p;x++) //for(m=p-1;m>=0;m--)
				{
					if((value & mask)>0)
						bi_codeword[p*i+x]=1;
					else
						bi_codeword[p*i+x]=0;
					mask=mask<<1;
				}
			}
		
			modulation();
			
			channel();
			
			/////////To be done?////////////
			demodulation();

			interpolation();

			factorization();
			
			//Number of errors calculation
			//error=0;
			for(i=0;i<p*n;i++)
				if(bi_codeword[i]!=dec_codeword[i])
					error++;
/*			
			if(f_error_temp==1)
				printf("\nerror=%d\n",error);
			f_error_temp=0;
*/			/*
			if(error!=0)
				ferror++;
			*/

			progress=(double)(j*100)/(double)seq_num;
			
			BER=(double)(error)/(double)(n*p*j);
			//FER=(double)(ferror)/(double)(j),
			printf("Progress=%0.1f, SNR=%2.1f, Bit Errors=%2.1d, BER=%E\r", progress, SNR, error, BER);
//			printf(" Progress=%0.1f,dectect=%d\r",progress,dectec);
			
		}
		BER=(double)error/(double)(n*p*seq_num);
		//FER=(double)(ferror)/(double)(seq_num);
		printf("Progress=%0.1f, SNR=%2.1f, Bit Errors=%2.1d, BER=%E\n",progress, SNR, error, BER);
//		printf(" Progress=%0.1f,dectect=%d\r",progress,dectec);
		fp=fopen("data_(63,31)m=3.txt","a");
		fprintf(fp,"Progress=%0.1f, SNR=%2.1f, Bit Errors=%2.1d, BER=%E\n",progress, SNR, error, BER);
		fclose(fp);

	}


	getchar();
	getchar();
		
}
Exemplo n.º 10
0
void Pull::run()
{
   QLOG_TRACE() << "Receiving file " << m_sourceFilePath;
   qDebug() << "SecureConnection::Pull " << m_sourceFilePath << "->" << m_destinationFilePath;

   // Set blocking, which apparently is required.
   QByteArray source(m_sourceFilePath.toLocal8Bit());
   libssh2_session_set_blocking(m_session, 1);
   struct stat fileInfo;
   LIBSSH2_CHANNEL* channel(libssh2_scp_recv(m_session, source.data(), &fileInfo));

   if (channel == 0) {
       QString msg("Could not stat file ");
       msg += m_sourceFilePath;
       throw Exception(m_session, msg);
   }

   QByteArray destination(m_destinationFilePath.toLocal8Bit());
   FILE* localFileHandle(fopen(destination.data(), "wb"));

   if (!localFileHandle) {
      QString msg("Could not open file for writing ");
      msg += m_destinationFilePath;
      throw Exception(msg);
   }

   // If the buffer size changes, anything connected to the copyProgress will
   // need updating as it assumes kbyte increments.
   char buffer[1024];
   off_t got(0);
   
   while (got < fileInfo.st_size && !m_terminate) {
       int amount(sizeof(buffer));
       if ((fileInfo.st_size - got) < amount) {
          amount = fileInfo.st_size - got;
       }

       int bc(libssh2_channel_read(channel, buffer, amount));

       if (bc > 0) {
          fwrite(buffer, 1, bc, localFileHandle);
       }else if (bc < 0) {
          m_success = false;
          m_errorMessage = "Error reading from channel";
          break;
       }
       got += bc;
       copyProgress();
//qDebug() << "sleeping 1"; sleep(1);
   }

   fclose(localFileHandle);

   libssh2_channel_send_eof(channel);
// This seems to cause a hang sometimes
//   libssh2_channel_wait_eof(channel);
   libssh2_channel_wait_closed(channel);
   libssh2_channel_free(channel);

   if (!m_errorMessage.isEmpty()) throw Exception(m_errorMessage);
   if (!m_terminate) m_success = true;
}
Exemplo n.º 11
0
void Push::run()
{
   QLOG_TRACE() << "Sending file " << m_sourceFilePath;
   // Check the local file is there first
qDebug() << "SecureConnection::Push " << m_sourceFilePath << "->" << m_destinationFilePath;
   QByteArray source(m_sourceFilePath.toLocal8Bit());
   FILE* localFileHandle(fopen(source.data(), "rb"));
            
   if (!localFileHandle) {
      QString msg("Could not stat file ");
      msg += m_sourceFilePath;
      throw Exception(msg);
   }  
         
   struct stat fileInfo;
   stat(source.data(), &fileInfo);
         
   // Set blocking, which apparently is required.
   libssh2_session_set_blocking(m_session, 1);

   QByteArray destination(m_destinationFilePath.toLocal8Bit());
   LIBSSH2_CHANNEL* channel(libssh2_scp_send(m_session, destination.data(),
      fileInfo.st_mode & 0777, (unsigned long)fileInfo.st_size));
         
   if (channel == 0) {
      QString msg("Unable to open channel for writing to file ");
      msg += m_destinationFilePath;
      throw Exception(msg);
   }
  
   size_t nread;
   char buffer[1024];
   char* ptr;
   int rc;
      
   do {
       nread = fread(buffer, 1, sizeof(buffer), localFileHandle);
       if (nread <= 0)  break; // end of file
       ptr = buffer;
       
       do {
          // write the same data over and over, until error or completion 
          // rc indicates how many bytes were written this time 
          rc = libssh2_channel_write(channel, ptr, nread);
          if (rc < 0) {
             m_errorMessage = "Error writing to channel " + QString::number(rc);
             break;
          }else {
             ptr += rc;
             nread -= rc;
          }
       } while (nread && !m_terminate);
       copyProgress();
   
   } while (!m_terminate);
   
   fclose(localFileHandle);
   
   libssh2_channel_send_eof(channel);
   libssh2_channel_wait_eof(channel);
   libssh2_channel_wait_closed(channel);
   libssh2_channel_free(channel);
   
   if (!m_errorMessage.isEmpty()) throw Exception(m_errorMessage);
   if (!m_terminate) m_success = true;
}
Exemplo n.º 12
0
bool GdbServerProvider::isValid() const
{
    return !channel().isNull();
}
Exemplo n.º 13
0
Arquivo: midievent.C Projeto: imv/non
bool
midievent::is_same_note ( midievent * e ) const
{
    return channel() == e->channel() && note() == e->note();
}
Exemplo n.º 14
0
QString Fixture::status() const
{
    QString info;
    QString t;

    QString title("<TR><TD CLASS='hilite' COLSPAN='3'>%1</TD></TR>");
    QString subTitle("<TR><TD CLASS='subhi' COLSPAN='3'>%1</TD></TR>");
    QString genInfo("<TR><TD CLASS='emphasis'>%1</TD><TD COLSPAN='2'>%2</TD></TR>");

    /********************************************************************
     * General info
     ********************************************************************/

    info += "<TABLE COLS='3' WIDTH='100%'>";

    // Fixture title
    info += title.arg(name());

    if (m_fixtureDef != NULL && m_fixtureMode != NULL)
    {
        // Manufacturer
        info += genInfo.arg(tr("Manufacturer")).arg(m_fixtureDef->manufacturer());
        info += genInfo.arg(tr("Model")).arg(m_fixtureDef->model());
        info += genInfo.arg(tr("Mode")).arg(m_fixtureMode->name());
        info += genInfo.arg(tr("Type")).arg(m_fixtureDef->typeToString(m_fixtureDef->type()));
    }

    // Universe
    info += genInfo.arg(tr("Universe")).arg(universe() + 1);

    // Address
    QString range = QString("%1 - %2").arg(address() + 1).arg(address() + channels());
    info += genInfo.arg(tr("Address Range")).arg(range);

    // Channels
    info += genInfo.arg(tr("Channels")).arg(channels());

    // Binary address
    QString binaryStr = QString("%1").arg(address() + 1, 10, 2, QChar('0'));
    QString dipTable("<TABLE COLS='33' cellspacing='0'><TR><TD COLSPAN='33'><IMG SRC=\"" ":/ds_top.png\"></TD></TR>");
    dipTable += "<TR><TD><IMG SRC=\"" ":/ds_border.png\"></TD><TD><IMG SRC=\"" ":/ds_border.png\"></TD>";
    for (int i = 9; i >= 0; i--)
    {
        if (binaryStr.at(i) == '0')
            dipTable += "<TD COLSPAN='3'><IMG SRC=\"" ":/ds_off.png\"></TD>";
        else
            dipTable += "<TD COLSPAN='3'><IMG SRC=\"" ":/ds_on.png\"></TD>";
    }
    dipTable += "<TD><IMG SRC=\"" ":/ds_border.png\"></TD></TR>";
    dipTable += "<TR><TD COLSPAN='33'><IMG SRC=\"" ":/ds_bottom.png\"></TD></TR>";
    dipTable += "</TABLE>";

    info += genInfo.arg(tr("Binary Address (DIP)"))
            .arg(QString("%1").arg(dipTable));

    /********************************************************************
     * Channels
     ********************************************************************/

    // Title row
    info += QString("<TR><TD CLASS='subhi'>%1</TD>").arg(tr("Channel"));
    info += QString("<TD CLASS='subhi'>%1</TD>").arg(tr("DMX"));
    info += QString("<TD CLASS='subhi'>%1</TD></TR>").arg(tr("Name"));

    // Fill table with the fixture's channels
    for (quint32 ch = 0; ch < channels();	ch++)
    {
        QString chInfo("<TR><TD>%1</TD><TD>%2</TD><TD>%3</TD></TR>");
        info += chInfo.arg(ch + 1).arg(address() + ch + 1)
                .arg(channel(ch)->name());
    }

    /********************************************************************
     * Extended device information
     ********************************************************************/

    if (m_fixtureMode != NULL)
    {
        QLCPhysical physical = m_fixtureMode->physical();
        info += title.arg(tr("Physical"));

        float mmInch = 0.0393700787;
        float kgLbs = 2.20462262;
        QString mm("%1mm (%2\")");
        QString kg("%1kg (%2 lbs)");
        QString W("%1W");
        info += genInfo.arg(tr("Width")).arg(mm.arg(physical.width()))
                                        .arg(physical.width() * mmInch, 0, 'g', 4);
        info += genInfo.arg(tr("Height")).arg(mm.arg(physical.height()))
                                         .arg(physical.height() * mmInch, 0, 'g', 4);
        info += genInfo.arg(tr("Depth")).arg(mm.arg(physical.depth()))
                                        .arg(physical.depth() * mmInch, 0, 'g', 4);
        info += genInfo.arg(tr("Weight")).arg(kg.arg(physical.weight()))
                                         .arg(physical.weight() * kgLbs, 0, 'g', 4);
        info += genInfo.arg(tr("Power consumption")).arg(W.arg(physical.powerConsumption()));
        info += genInfo.arg(tr("DMX Connector")).arg(physical.dmxConnector());

        // Bulb
        QString K("%1K");
        QString lm("%1lm");
        info += subTitle.arg(tr("Bulb"));
        info += genInfo.arg(tr("Type")).arg(physical.bulbType());
        info += genInfo.arg(tr("Luminous Flux")).arg(lm.arg(physical.bulbLumens()));
        info += genInfo.arg(tr("Colour Temperature")).arg(K.arg(physical.bulbColourTemperature()));

        // Lens
        QString angle1("%1&deg;");
        QString angle2("%1&deg; &ndash; %2&deg;");

        info += subTitle.arg(tr("Lens"));
        info += genInfo.arg(tr("Name")).arg(physical.lensName());

        if (physical.lensDegreesMin() == physical.lensDegreesMax())
        {
            info += genInfo.arg(tr("Beam Angle"))
                .arg(angle1.arg(physical.lensDegreesMin()));
        }
        else
        {
            info += genInfo.arg(tr("Beam Angle"))
                .arg(angle2.arg(physical.lensDegreesMin())
                .arg(physical.lensDegreesMax()));
        }

        // Focus
        QString frange("%1&deg;");
        info += subTitle.arg(tr("Focus"));
        info += genInfo.arg(tr("Type")).arg(physical.focusType());
        info += genInfo.arg(tr("Pan Range")).arg(frange.arg(physical.focusPanMax()));
        info += genInfo.arg(tr("Tilt Range")).arg(frange.arg(physical.focusTiltMax()));
    }

    // HTML document & table closure
    info += "</TABLE>";

    if (m_fixtureDef != NULL)
    {
        info += "<HR>";
        info += "<DIV CLASS='author' ALIGN='right'>";
        info += tr("Fixture definition author: ") + m_fixtureDef->author();
        info += "</DIV>";
    }

    return info;
}
void compareLimits(const char* filename, const char* channelstr, bool expected, bool observed, const char* type, double minimum=0., double maximum=20., bool log=false, const char* label="CMS Preliminary,  H#rightarrow#tau#tau,  4.9 fb^{-1} at 7 TeV, 19.4 fb^{-1} at 8 TeV", bool legendOnRight=true, bool legendOnTop=true)
{
  SetStyle();

  std::map<std::string, unsigned int> colors;
  colors["0jet"       ] = kBlue;
  colors["2jet"       ] = kMagenta;
  colors["vbf"        ] = kRed;
  colors["boost"      ] = kGreen;
  colors["btag"       ] = kRed;
  colors["nobtag"     ] = kBlue;
  colors["em"         ] = kBlue;
  colors["et"         ] = kRed;
  colors["mt"         ] = kGreen;
  colors["mm"         ] = kMagenta;
  colors["ee"         ] = kCyan;
  colors["tt"         ] = kMagenta+3;
  colors["vhtt"       ] = kCyan-6;
  colors["cmb"        ] = kBlack;
  colors["cmb+"       ] = kBlack; //kGray+2;
  colors["htt"        ] = kBlack;
  colors["ggH"        ] = kRed;
  colors["bbH"        ] = kBlue;
  colors["mvis"       ] = kBlue+2;
  colors["test-0"     ] = kRed+2;
  colors["test-1"     ] = kGreen+2;
  colors["test-2"     ] = kGreen;
  colors["test-3"     ] = kRed+2;
  colors["test-4"     ] = kBlue;
  colors["test-5"     ] = kViolet-6;
  colors["HIG-11-020" ] = kBlue+2;
  colors["HIG-11-029" ] = kRed+2;
  colors["HIG-12-018" ] = kBlue;
  colors["HIG-12-032" ] = kRed+2;
  colors["HIG-12-043" ] = kRed;
  colors["HIG-12-050" ] = kBlack;

  std::cout << " *******************************************************************************************************\n"
	    << " * Usage     : root -l                                                                                  \n"
	    << " *             .x MitLimits/Higgs2Tau/macros/compareLimits.C+(file, chn, exp, obs, type, min, max, log) \n"
	    << " *                                                                                                      \n"
	    << " * Arguments :  + file     const char*      full path to the input file                                 \n"
	    << " *              + chn      const char*      list of channels; choose between: 'cmb', 'htt', 'emu',      \n"
	    << " *                                          'etau', 'mutau', 'mumu', 'vhtt', 'hgg', 'hww', 'ggH',       \n"
	    << " *                                          'bbH', 'nomix[-200, +200]', 'mhmax[-400, -200, +200]'       \n"
	    << " *                                          'mhmax[+400, +600, +800]', 'test-0...5', 'saeff', 'gluph'   \n"
	    << " *                                          The list should be comma separated and may contain          \n"
	    << " *                                          whitespaces                                                 \n"
	    << " *              + exp       bool            compare expected limits                                     \n"
	    << " *              + obs       bool            compare observed limits                                     \n"
	    << " *              + type      const char*     type of plot; choose between 'sm-xsec', 'mssm-xsec' and     \n"
	    << " *                                          'mssm-tanb'                                                 \n"
	    << " *              + max       double          maximum of the plot (default is 20.)                        \n"
	    << " *                                                                                                      \n"
	    << " *              + min       double          minimum of the plot (default is  0.)                        \n"
	    << " *                                                                                                      \n"
	    << " *              + log       bool            set log scale yes or no (default is false)                  \n"
	    << " *                                                                                                      \n"
	    << " *******************************************************************************************************\n";

  /// open input file  
  TFile* inputFile = new TFile(filename); if(inputFile->IsZombie()){ std::cout << "ERROR:: file: " << filename << " does not exist.\n"; }

  /// prepare input parameters
  std::vector<std::string> channels;
  string2Vector(cleanupWhitespaces(channelstr), channels);

  /// prepare histograms
  std::vector<TGraph*> hobs, hexp;
  for(unsigned i=0; i<channels.size(); ++i){
    if(observed) hobs.push_back(get<TGraph>(inputFile, std::string(channels[i]).append("/observed").c_str()));
    if(expected) hexp.push_back(get<TGraph>(inputFile, std::string(channels[i]).append("/expected").c_str()));
  }

  /// do the drawing
  TCanvas* canv1 = new TCanvas("canv1", "Limit Comparison", 600, 600);
  canv1->cd();
  canv1->SetGridx(1);
  canv1->SetGridy(1);
 
  bool firstPlot=true;
  for(unsigned int i=0; i<hexp.size(); ++i){
    if(firstPlot){
      if(std::string(type) == std::string("mssm-xsec")){
	if(log){ canv1->SetLogy(1); }
	hexp[i]->SetMaximum(maximum);
	hexp[i]->SetMinimum(minimum);
      }
      else{
	if(log){ canv1->SetLogy(1); }
	hexp[i]->SetMaximum(maximum);
	hexp[i]->SetMinimum(minimum);
      }
      
      // format x-axis
      std::string x_title;
      if(std::string(type).find("mssm")!=std::string::npos){
	x_title = std::string("m_{#phi} [GeV]");
      }
      else{
	x_title = std::string("m_{H} [GeV]");
      }
      hexp[i]->GetXaxis()->SetTitle(x_title.c_str());
      hexp[i]->GetXaxis()->SetLabelFont(62);
      hexp[i]->GetXaxis()->SetTitleFont(62);
      hexp[i]->GetXaxis()->SetTitleColor(1);
      hexp[i]->GetXaxis()->SetTitleOffset(1.05);
      if(std::string(type) == std::string("mssm-tanb")) hexp[i]->GetYaxis()->SetRangeUser(0,maximum);

      // format y-axis
      std::string y_title;
      if( std::string(type) == std::string("mssm-xsec") ){
	y_title = std::string("#sigma(#phi#rightarrow#tau#tau)_{95% CL} [pb]");
      }
      else if(  std::string(type) == std::string("mssm-tanb")  ){
	y_title = std::string("#bf{tan#beta}");
      }
      else{
	//y_title = std::string("#sigma(H#rightarrow#tau#tau)_{95% CL} / #sigma(H#rightarrow#tau#tau)_{SM}");
	y_title = std::string("95% CL limit on #sigma/#sigma_{SM}");
      }
      hexp[i]->GetYaxis()->SetTitle(y_title.c_str());
      hexp[i]->GetYaxis()->SetLabelFont(62);
      hexp[i]->GetYaxis()->SetTitleOffset(1.05);
      hexp[i]->GetYaxis()->SetLabelSize(0.03);
      hexp[i]->GetXaxis()->SetLimits(hexp[i]->GetX()[0]-.1, hexp[i]->GetX()[hexp[i]->GetN()-1]+.1);
    }
    hexp[i]->SetLineStyle(11.);
    hexp[i]->SetLineWidth( 3.); 
    hexp[i]->SetLineColor(colors.find(channels[i])->second);
    hexp[i]->SetMarkerStyle(20);
    hexp[i]->SetMarkerSize(MARKER_SIZE);
    hexp[i]->SetMarkerColor(colors.find(channels[i])->second);
    hexp[i]->Draw(firstPlot ? "APL" : "PLsame");
    //hexp[i]->Draw(firstPlot ? "AL" : "Lsame");
    firstPlot=false;
  }
  for(unsigned int i=0; i<hobs.size(); ++i){
    if(firstPlot){
      if(std::string(type) == std::string("mssm-xsec")){
	if(log){ canv1->SetLogy(1); }
	hobs[i]->SetMaximum(maximum);
	hobs[i]->SetMinimum(minimum);
      }
      else{
	if(log){ canv1->SetLogy(1); }
	hobs[i]->SetMaximum(maximum);
	hobs[i]->SetMinimum(minimum);
      }
      
      // format x-axis
      std::string x_title;
      if(std::string(type).find("mssm")!=std::string::npos){
	x_title = std::string("m_{#phi} [GeV]");
      }
      else{
	x_title = std::string("m_{H} [GeV]");
      }
      hobs[i]->GetXaxis()->SetTitle(x_title.c_str());
      hobs[i]->GetXaxis()->SetLabelFont(62);
      hobs[i]->GetXaxis()->SetTitleFont(62);
      hobs[i]->GetXaxis()->SetTitleColor(1);
      hobs[i]->GetXaxis()->SetTitleOffset(1.05);
      if(std::string(type) == std::string("mssm-tanb")) hobs[i]->GetYaxis()->SetRangeUser(0,maximum);
      
      // format y-axis
      std::string y_title;
      if( std::string(type) == std::string("mssm-xsec") ){
	y_title = std::string("#sigma(#phi#rightarrow#tau#tau)_{95% CL} [pb]");
      }
      else if(  std::string(type) == std::string("mssm-tanb")  ){
	y_title = std::string("#bf{tan#beta}");
      }
      else{
	y_title = std::string("95% CL limit on #sigma/#sigma_{SM}");
	//y_title = std::string("#sigma(H)_{95% CL} / #sigma(H)_{SM}");
      }
      hobs[i]->GetYaxis()->SetTitle(y_title.c_str());
      hobs[i]->GetYaxis()->SetLabelFont(62);
      hobs[i]->GetYaxis()->SetTitleOffset(1.05);
      hobs[i]->GetYaxis()->SetLabelSize(0.03);
      hobs[i]->GetXaxis()->SetLimits(hobs[i]->GetX()[0]-.1, hobs[i]->GetX()[hobs[i]->GetN()-1]+.1);
    }
    hobs[i]->SetLineStyle(11.);
    hobs[i]->SetLineWidth( 3.); 
    hobs[i]->SetLineColor(colors.find(channels[i])->second);
    hobs[i]->SetMarkerStyle(20);
    hobs[i]->SetMarkerSize(MARKER_SIZE);
    hobs[i]->SetMarkerColor(colors.find(channels[i])->second);
    hobs[i]->Draw(firstPlot ? "APL" : "PLsame");
    //hobs[i]->Draw(firstPlot ? "AL" : "Lsame");
    firstPlot=false;
  }
  canv1->RedrawAxis();
  bool firstLeg=true;
  if(observed){
    TLegend* leg1;
    if(expected && observed){
      /// setup the CMS Preliminary
       if(std::string(type) == std::string("mssm-tanb")){
	  if (firstLeg) CMSPrelim(label, "", 0.15, 0.835);
	  leg1 = new TLegend(firstLeg ? 0.60 : 0.20, hobs.size()<5 ? 0.20-0.06*hobs.size() : 0.4, firstLeg ? 0.93 : 0.60, 0.20);
       }
       else{
	  if (firstLeg) CMSPrelim(label, "", 0.15, 0.835);
	  leg1 = new TLegend(firstLeg ? 0.20 : 0.20, hobs.size()<5 ? 0.90-0.08*hobs.size() : 0.6, firstLeg ? 0.63 : 0.60, 0.90);
       }
    }
    else{
      /// setup the CMS Preliminary
      if(std::string(type) == std::string("mssm-tanb")){
	CMSPrelim(label, "", 0.15, 0.835);
	leg1 = new TLegend(legendOnRight?0.60:0.20, hobs.size()<5 ? (legendOnTop?0.90:0.20)-0.06*hobs.size() : (legendOnTop?0.6:0.4), legendOnRight?0.94:0.45, (legendOnTop?0.90:0.20));
	   }
      else{
	CMSPrelim(label, "", 0.15, 0.835);
	leg1 = new TLegend(legendOnRight ? 0.50 : 0.20, hobs.size()<5 ? 0.90-0.08*hobs.size() : 0.6, legendOnRight ? 0.94 : 0.64, 0.90);
      }
    }
    //leg1->SetTextSize(0.02);
    leg1->SetBorderSize( 0 );
    leg1->SetFillStyle ( 1001 );
    //leg1->SetFillColor ( 0 );
    leg1->SetFillColor (kWhite);
    leg1->SetHeader( "#bf{Observed Limit}" );
    for(unsigned int i=0; i<hobs.size(); ++i){
      // skip one of the two split options
      if(channels[i] == std::string("hzz2l2q+")){ continue; }
      leg1->AddEntry( hobs[i] , channel(channels[i]) ? legendEntry(channels[i]).c_str() : legendEntry(channels[i]).append("-Channel").c_str(),  "PL" );
    }
    leg1->Draw("same");
    firstLeg=false;
  }
  if(expected){
    TLegend* leg0;
    if(expected && observed){
      /// setup the CMS Preliminary
      if(std::string(type) == std::string("mssm-tanb")){
	CMSPrelim(label, "", 0.15, 0.835);
	leg0 = new TLegend(legendOnRight ? 0.60 : 0.20, hexp.size()<5 ? 0.20-0.06*hexp.size() : 0.4, legendOnRight ? 0.94 : 0.63, 0.20);
      }
      else{
	CMSPrelim(label, "", 0.15, 0.835);
	leg0 = new TLegend(legendOnRight ? 0.20 : 0.20, hexp.size()<5 ? 0.75-0.08*hexp.size() : 0.6, legendOnRight ? 0.94 : 0.63, 0.75);
      }
    }
    else{
      /// setup the CMS Preliminary
      if(std::string(type) == std::string("mssm-tanb")){
	CMSPrelim(label, "", 0.15, 0.835);
	leg0 = new TLegend(legendOnRight?0.60:0.20, hexp.size()<5 ? (legendOnTop?0.90:0.40)-0.04*hexp.size() : (legendOnTop?0.6:0.2), legendOnRight?0.94:0.45, (legendOnTop?0.90:0.40));
	   }
      else{
	CMSPrelim(label, "", 0.15, 0.835);
	leg0 = new TLegend(legendOnRight ? 0.50 : 0.20, hexp.size()<5 ? 0.90-0.06*hexp.size() : 0.6, legendOnRight ? 0.94 : 0.63, 0.90);
	//leg0 = new TLegend(legendOnRight ? 0.50 : 0.20, hexp.size()<5 ? 0.90-0.08*hexp.size() : 0.6, legendOnRight ? 0.94 : 0.80, 0.90);
      }
    }
    if(std::string(type) == std::string("mssm-tanb")) {leg0->SetTextSize(0.03);}
    leg0->SetBorderSize( 0 );
    leg0->SetFillStyle ( 1001 );
    leg0->SetFillColor (kWhite);
    leg0->SetHeader( "#bf{Expected Limit}" );
    for(unsigned int i=0; i<hexp.size(); ++i){
      // skip one of the two split options
      if(channels[i] == std::string("hzz2l2q+")){ continue; }
      leg0->AddEntry( hexp[i] , channel(channels[i]) ? legendEntry(channels[i]).c_str() : legendEntry(channels[i]).append("-Channel").c_str(),  "PL" );
    }
    leg0->Draw("same");
    firstLeg=false;
  }
  canv1->Print(std::string("singleLimits").append(expected ? "_expected" : "").append(observed ? "_observed" : "").append(std::string(type).find("mssm")!=std::string::npos ? "_mssm.png" : "_sm.png").c_str());
  canv1->Print(std::string("singleLimits").append(expected ? "_expected" : "").append(observed ? "_observed" : "").append(std::string(type).find("mssm")!=std::string::npos ? "_mssm.pdf" : "_sm.pdf").c_str());
  canv1->Print(std::string("singleLimits").append(expected ? "_expected" : "").append(observed ? "_observed" : "").append(std::string(type).find("mssm")!=std::string::npos ? "_mssm.pdf" : "_sm.eps").c_str());
  return;
}
Exemplo n.º 16
0
void filter::close( const tcode::diagnostics::error_code& ec ){
	channel()->close( ec );
}
Exemplo n.º 17
0
bool IrcTopicMessage::isValid() const
{
    return IrcMessage::isValid() && !channel().isEmpty();
}
Exemplo n.º 18
0
QString Fixture::status()
{
	QString t;
	QString info;

	// HTML header
	info += QString("<HTML>");
	info += QString("<HEAD>");
	info += QString("<TITLE>Fixture Information</TITLE>");
	info += QString("</HEAD>");
	info += QString("<BODY>");

	// Fixture title
	info += QString("<TABLE COLS=\"1\" WIDTH=\"100%\">");
	info += QString("<TR>");
	info += QString("<TD BGCOLOR=\"");
	info += _app->colorGroup().highlight().name();
	info += QString("\">");
	info += QString("<FONT COLOR=\"");
	info += _app->colorGroup().highlightedText().name();
	info += QString("\" SIZE=\"5\">");
	info += name();
	info += QString("</FONT>");
	info += QString("</TD>");
	info += QString("</TR>");
	info += QString("</TABLE>");
	
	// Manufacturer
	info += QString("<TABLE COLS=\"2\" WIDTH=\"100%\">");
	info += QString("<TR>");
	info += QString("<TD>");
	info += QString("<B>Manufacturer</B>");
	info += QString("</TD>");
	info += QString("<TD>");
	
	if (m_fixtureDef != NULL)
		info += m_fixtureDef->manufacturer();
	else
		info += KXMLFixtureGeneric;

	info += QString("</TD>");
	info += QString("</TR>");

	// Model
	info += QString("<TR>");
	info += QString("<TD>");
	info += QString("<B>Model</B>");
	info += QString("</TD>");
	info += QString("<TD>");

	if (m_fixtureDef != NULL)
		info += m_fixtureDef->model();
	else
		info += KXMLFixtureGeneric;

	info += QString("</TD>");
	info += QString("</TR>");
	
	// Mode
	info += QString("<TR>");
	info += QString("<TD>");
	info += QString("<B>Mode</B>");
	info += QString("</TD>");
	info += QString("<TD>");

	if (m_fixtureDef != NULL && m_fixtureMode != NULL)
		info += m_fixtureMode->name();
	else
		info += KXMLFixtureGeneric;
		
	info += QString("</TD>");
	info += QString("</TR>");

	// Type
	info += QString("<TR>");
	info += QString("<TD>");
	info += QString("<B>Type</B>");
	info += QString("</TD>");
	info += QString("<TD>");

	if (m_fixtureDef != NULL && m_fixtureMode != NULL)
		info += m_fixtureDef->type();
	else
		info += KXMLFixtureDimmer;

	info += QString("</TD>");
	info += QString("</TR>");

	// Universe
	info += QString("<TR>");
	info += QString("<TD>");
	info += QString("<B>Universe</B>");
	info += QString("</TD>");
	info += QString("<TD>");
	info += t.sprintf("%d", universe() + 1);
	info += QString("</TD>");
	info += QString("</TR>");
	
	// Address
	info += QString("<TR>");
	info += QString("<TD>");
	info += QString("<B>Address space</B>");
	info += QString("</TD>");
	info += QString("<TD>");
	info += t.sprintf("%d - %d", address() + 1, address() + channels());
	info += QString("</TD>");
	info += QString("</TR>");
	info += QString("</TABLE>");
	
	//
	// Channels
	//
	info += QString("<TABLE COLS=\"3\" WIDTH=\"100%\">");
	info += QString("<TR>");
	
	// Relative channel column title
	info += QString("<TD BGCOLOR=\"");
	info += _app->colorGroup().highlight().name();
	info += QString("\">");
	info += QString("<FONT COLOR=\"");
	info += _app->colorGroup().highlightedText().name();
	info += QString("\" SIZE=\"3\">");
	info += QString("Channel");
	info += QString("</FONT>");
	info += QString("</TD>");
	
	// DMX channel column title
	info += QString("<TD BGCOLOR=\"");
	info += _app->colorGroup().highlight().name();
	info += QString("\">");
	info += QString("<FONT COLOR=\"");
	info += _app->colorGroup().highlightedText().name();
	info += QString("\" SIZE=\"3\">");
	info += QString("DMX");
	info += QString("</FONT>");
	info += QString("</TD>");
	info += QString("</TR>");

	// Channel name column title
	info += QString("<TD BGCOLOR=\"");
	info += _app->colorGroup().highlight().name();
	info += QString("\">");
	info += QString("<FONT COLOR=\"");
	info += _app->colorGroup().highlightedText().name();
	info += QString("\" SIZE=\"3\">");
	info += QString("Name");
	info += QString("</FONT>");
	info += QString("</TD>");
	info += QString("</TR>");
	
	// Fill table with device's channels
	for (t_channel ch = 0; ch < channels();	ch++)
	{
		info += QString("<TR>");

		// Relative channel
		info += QString("<TD>");
		info += t.setNum(ch + 1);
		info += QString("</TD>");

		// DMX channel
		info += QString("<TD>");
		info += t.setNum(address() + ch + 1);
		info += QString("</TD>");
		
		// Channel name
		info += QString("<TD>");
		
		if (m_fixtureDef != NULL && m_fixtureMode != NULL)
			info += channel(ch)->name();
		else
			info += "Level";

		info += QString("</TD>");
	}

	info += QString("</TR>");
	info += QString("</TABLE>");
	info += QString("</BODY>");
	info += QString("</HTML>");

	return info;
}
Exemplo n.º 19
0
int filter::release( void ){
	return channel()->release();
}
Exemplo n.º 20
0
/**
 * Write out a batch of 32 control data bits from the control_data_bits
 * register to the URB.
 *
 * The current value of the vertex_count register determines which DWORD in
 * the URB receives the control data bits.  The control_data_bits register is
 * assumed to contain the correct data for the vertex that was most recently
 * output, and all previous vertices that share the same DWORD.
 *
 * This function takes care of ensuring that if no vertices have been output
 * yet, no control bits are emitted.
 */
void
vec4_gs_visitor::emit_control_data_bits()
{
   assert(c->control_data_bits_per_vertex != 0);

   /* Since the URB_WRITE_OWORD message operates with 128-bit (vec4 sized)
    * granularity, we need to use two tricks to ensure that the batch of 32
    * control data bits is written to the appropriate DWORD in the URB.  To
    * select which vec4 we are writing to, we use the "slot {0,1} offset"
    * fields of the message header.  To select which DWORD in the vec4 we are
    * writing to, we use the channel mask fields of the message header.  To
    * avoid penalizing geometry shaders that emit a small number of vertices
    * with extra bookkeeping, we only do each of these tricks when
    * c->prog_data.control_data_header_size_bits is large enough to make it
    * necessary.
    *
    * Note: this means that if we're outputting just a single DWORD of control
    * data bits, we'll actually replicate it four times since we won't do any
    * channel masking.  But that's not a problem since in this case the
    * hardware only pays attention to the first DWORD.
    */
   enum brw_urb_write_flags urb_write_flags = BRW_URB_WRITE_OWORD;
   if (c->control_data_header_size_bits > 32)
      urb_write_flags = urb_write_flags | BRW_URB_WRITE_USE_CHANNEL_MASKS;
   if (c->control_data_header_size_bits > 128)
      urb_write_flags = urb_write_flags | BRW_URB_WRITE_PER_SLOT_OFFSET;

   /* If vertex_count is 0, then no control data bits have been accumulated
    * yet, so we should do nothing.
    */
   emit(CMP(dst_null_d(), this->vertex_count, 0u, BRW_CONDITIONAL_NEQ));
   emit(IF(BRW_PREDICATE_NORMAL));
   {
      /* If we are using either channel masks or a per-slot offset, then we
       * need to figure out which DWORD we are trying to write to, using the
       * formula:
       *
       *     dword_index = (vertex_count - 1) * bits_per_vertex / 32
       *
       * Since bits_per_vertex is a power of two, and is known at compile
       * time, this can be optimized to:
       *
       *     dword_index = (vertex_count - 1) >> (6 - log2(bits_per_vertex))
       */
      src_reg dword_index(this, glsl_type::uint_type);
      if (urb_write_flags) {
         src_reg prev_count(this, glsl_type::uint_type);
         emit(ADD(dst_reg(prev_count), this->vertex_count, 0xffffffffu));
         unsigned log2_bits_per_vertex =
            _mesa_fls(c->control_data_bits_per_vertex);
         emit(SHR(dst_reg(dword_index), prev_count,
                  (uint32_t) (6 - log2_bits_per_vertex)));
      }

      /* Start building the URB write message.  The first MRF gets a copy of
       * R0.
       */
      int base_mrf = 1;
      dst_reg mrf_reg(MRF, base_mrf);
      src_reg r0(retype(brw_vec8_grf(0, 0), BRW_REGISTER_TYPE_UD));
      vec4_instruction *inst = emit(MOV(mrf_reg, r0));
      inst->force_writemask_all = true;

      if (urb_write_flags & BRW_URB_WRITE_PER_SLOT_OFFSET) {
         /* Set the per-slot offset to dword_index / 4, to that we'll write to
          * the appropriate OWORD within the control data header.
          */
         src_reg per_slot_offset(this, glsl_type::uint_type);
         emit(SHR(dst_reg(per_slot_offset), dword_index, 2u));
         emit(GS_OPCODE_SET_WRITE_OFFSET, mrf_reg, per_slot_offset, 1u);
      }

      if (urb_write_flags & BRW_URB_WRITE_USE_CHANNEL_MASKS) {
         /* Set the channel masks to 1 << (dword_index % 4), so that we'll
          * write to the appropriate DWORD within the OWORD.  We need to do
          * this computation with force_writemask_all, otherwise garbage data
          * from invocation 0 might clobber the mask for invocation 1 when
          * GS_OPCODE_PREPARE_CHANNEL_MASKS tries to OR the two masks
          * together.
          */
         src_reg channel(this, glsl_type::uint_type);
         inst = emit(AND(dst_reg(channel), dword_index, 3u));
         inst->force_writemask_all = true;
         src_reg one(this, glsl_type::uint_type);
         inst = emit(MOV(dst_reg(one), 1u));
         inst->force_writemask_all = true;
         src_reg channel_mask(this, glsl_type::uint_type);
         inst = emit(SHL(dst_reg(channel_mask), one, channel));
         inst->force_writemask_all = true;
         emit(GS_OPCODE_PREPARE_CHANNEL_MASKS, dst_reg(channel_mask),
                                               channel_mask);
         emit(GS_OPCODE_SET_CHANNEL_MASKS, mrf_reg, channel_mask);
      }

      /* Store the control data bits in the message payload and send it. */
      dst_reg mrf_reg2(MRF, base_mrf + 1);
      inst = emit(MOV(mrf_reg2, this->control_data_bits));
      inst->force_writemask_all = true;
      inst = emit(GS_OPCODE_URB_WRITE);
      inst->urb_write_flags = urb_write_flags;
      /* We need to increment Global Offset by 256-bits to make room for
       * Broadwell's extra "Vertex Count" payload at the beginning of the
       * URB entry.  Since this is an OWord message, Global Offset is counted
       * in 128-bit units, so we must set it to 2.
       */
      if (brw->gen >= 8)
         inst->offset = 2;
      inst->base_mrf = base_mrf;
      inst->mlen = 2;
   }
   emit(BRW_OPCODE_ENDIF);
}
Exemplo n.º 21
0
void QDiscordStateComponent::messageDeleteReceived(const QJsonObject& object)
{
	QDiscordMessage message(object, channel(object["channel_id"].toString("")));
	emit messageDeleted(message);
}
Exemplo n.º 22
0
//------------------------------------------------------------------------------
// Printing functions
//------------------------------------------------------------------------------
void Navaid::printRecord(std::ostream& sout) const
{
   char icas[32];
   icaoCode(icas);

   char ikey[32];
   key(ikey);

   char id[12];
   ident(id);

   char ccode[4];
   countryCode(ccode);

   char rc[8];
   radioClass(rc);

   sout << icas << ", ";

   sout << "\"";
   sout << ikey;
   sout << "\", ";

   sout << id;
   sout << "-";
   sout << static_cast<char>(navaidType());
   sout << "-";
   sout << ccode;
   sout << "-";
   sout << keyCode();
   sout << ":";

   std::streamoff old = sout.precision();
   sout.precision(12);

   sout << "  ";
   sout << latitude();
   sout << ", ";
   sout << longitude();

   sout.precision(old);
   sout << ", ";
   sout << elevation();

   sout << "  ";
   sout << frequency();
   sout << "-";
   sout << channel();

   sout << "  ( ";
   sout << magVariance();
   sout << ", ";
   sout << slaveVariance();
   sout << " )";

   sout << " (";
   sout << power();
   sout << "-";
   sout << rc;
   sout << "-";
   sout << range();
   sout << ")";

}
Exemplo n.º 23
0
QString KoCtlChannelImpl<half>::channelValueText(const quint8* pixel) const
{
return QString::number(double(*channel(pixel)));
}
long Nonlinear_Effects_Buffer::read_samples( blip_sample_t* out, long count )
{
	count = 2 * nonlinearizer.make_nonlinear( *channel( 2 ).center, count / 2 );
	return Effects_Buffer::read_samples( out, count );
}
Exemplo n.º 25
0
void plot_bgnd(int ch=4) {
  vector<fileInfo> files;
  files.push_back(fileInfo("u#bar{u}", TFile::Open(Form("Histo_ch%d_uubar.root"  ,ch)), kRed));
  files.push_back(fileInfo("d#bar{d}", TFile::Open(Form("Histo_ch%d_ddbar.root"  ,ch)), kGreen));
  files.push_back(fileInfo("s#bar{s}", TFile::Open(Form("Histo_ch%d_ssbar.root"  ,ch)), kBlue));
  files.push_back(fileInfo("c#bar{c}", TFile::Open(Form("Histo_ch%d_ccbar.root"  ,ch)), kOrange));
  // files.push_back(fileInfo("mixed",    TFile::Open(Form("Histo_ch%d_mixed.root"  ,ch)), kViolet));
  // files.push_back(fileInfo("charged",  TFile::Open(Form("Histo_ch%d_charged.root",ch)), kGray));

  gStyle->SetPadTopMargin(0.10);
  gStyle->SetOptStat(0);
  gStyle->SetTitleSize(.5,"XYZ");

  TLatex* tt=new TLatex();
  tt->SetTextSize(0.05);

  vector<plotInfo> plotInfos;
  getWhatToPlot(ch, plotInfos);

  if (plotAllDistributions) {
    TLine* tl=new TLine();
    tl->SetLineWidth(2);
    tl->SetLineColor(kRed+2);
    int nHisto=plotInfos.size();

    int nX=3, nY=1;
    float sizeX=900,sizeY=300;
    const int nCanvas(nHisto/(nX*nY)+1);

    TLegend* tleg=new TLegend(0.8,0.6,0.96,0.89);
    tleg->SetFillStyle(0);

    TCanvas* c0[nCanvas];
    int iCan=0;
    c0[iCan]=new TCanvas(Form("c0%d",iCan),"Before Cuts",sizeX,sizeY);
    c0[iCan]->Divide(nX,nY);
    int i=0;
    for (vector<plotInfo>::const_iterator h=plotInfos.begin(); h!=plotInfos.end(); ++h) {
      THStack hs;
      TString xTitle;
      for (vector<fileInfo>::const_iterator f=files.begin(); f!=files.end(); ++f) {
        c0[iCan]->cd(i+1);
        (f->file)->cd("AllCandidates");
        TH1* htmp=(TH1F*)gDirectory->Get(h->name);
        float ymin=0;
        if (h->log) {
          gPad->SetLogy();
          ymin=10;
        }
        if (htmp) {
          htmp->GetXaxis()->SetTitleOffset(.7);
          htmp->GetXaxis()->SetTitleSize(0.08);
          htmp->SetFillColor(f->color);
          htmp->SetMinimum(ymin);
          hs.Add(htmp);
          xTitle=htmp->GetXaxis()->GetTitle();
          if (i==0) {
            tleg->AddEntry(htmp,f->name,"f");
          }
        }
      }
      hs.DrawClone();
      tt->SetTextAlign(32);
      tt->DrawLatexNDC(0.95,.03,xTitle);

      tl->DrawLine(h->cutLow,ymin,h->cutLow,htmp->GetMaximum()*1.05);
      tl->DrawLine(h->cutHigh,ymin,h->cutHigh,htmp->GetMaximum()*1.05);
      if (i==0) tleg->Draw();
      ++i;

      // Check if I need a new canvas
      if (i>nX*nY) {
        channel(ch,c0[iCan]);
        c0[iCan]->Print(Form("Ch%d_all_distr%d_bgnd.pdf",ch,iCan));
        c0[iCan]->Print(Form("Ch%d_all_distr%d_bgnd.png",ch,iCan));
        iCan++;
        c0[iCan]=new TCanvas(Form("c0%d",iCan),"Before Cuts",sizeX,sizeY);
        c0[iCan]->Divide(nX,nY);
        tleg->Clear();
        i=0;
      }
    }
    channel(ch,c0[iCan]);
    c0[iCan]->Print(Form("Ch%d_all_distr%d_bgnd.pdf",ch,iCan));
    c0[iCan]->Print(Form("Ch%d_all_distr%d_bgnd.png",ch,iCan));
  }


  if(plotGoldDistributions) {

    TLine* tl=new TLine();
    tl->SetLineWidth(2);
    tl->SetLineColor(kRed+2);
    TCanvas* c1=new TCanvas("c1","Before Cuts",900,600);
    c1->Divide(3,2);
    TLegend* tleg=new TLegend(0.8,0.6,0.96,0.89);
    tleg->SetFillStyle(0);
    int i=0;
    for (vector<plotInfo>::const_iterator h=plotInfos.begin(); h!=plotInfos.end(); ++h) {
      if (!h->gold) continue;
      THStack hs;
      TString xTitle;
      for (vector<fileInfo>::const_iterator f=files.begin(); f!=files.end(); ++f) {

        c1->cd(i+1);
        (f->file)->cd("AllCandidates");
        TH1* htmp=(TH1F*)gDirectory->Get(h->name);
        float ymin=0;
        if (h->log) {
          gPad->SetLogy();
          ymin=10;
        }
        if (htmp) {
          htmp->SetFillColor(f->color);
          htmp->GetXaxis()->SetTitleOffset(.7);
          htmp->GetXaxis()->SetTitleOffset(.7);
          htmp->GetXaxis()->SetTitleSize(0.08);
          xTitle=htmp->GetXaxis()->GetTitle();
          hs.Add(htmp);
          if (i==0) {
            cout << "Adding " << f->name << endl;
            tleg->AddEntry(htmp,f->name,"f");
          }
        }
      }
      hs.DrawClone();
      tt->SetTextAlign(32);
      tt->DrawLatexNDC(0.95,.03,xTitle);

      tl->DrawLine(h->cutLow,ymin,h->cutLow,htmp->GetMaximum()*1.05);
      tl->DrawLine(h->cutHigh,ymin,h->cutHigh,htmp->GetMaximum()*1.05);
      if (i==0) tleg->Draw();
      ++i;
    }
    channel(ch,c1);
    c1->Print(Form("Ch%d_distr_bgnd.pdf",ch));
    c1->Print(Form("Ch%d_distr_bgnd.png",ch));


  }

}
Exemplo n.º 26
0
nsresult
nsHttpChannelAuthProvider::PromptForIdentity(uint32_t            level,
        bool                proxyAuth,
        const char         *realm,
        const char         *authType,
        uint32_t            authFlags,
        nsHttpAuthIdentity &ident)
{
    LOG(("nsHttpChannelAuthProvider::PromptForIdentity [this=%p channel=%p]\n",
         this, mAuthChannel));

    nsresult rv;

    nsCOMPtr<nsIInterfaceRequestor> callbacks;
    rv = mAuthChannel->GetNotificationCallbacks(getter_AddRefs(callbacks));
    if (NS_FAILED(rv)) return rv;

    nsCOMPtr<nsILoadGroup> loadGroup;
    rv = mAuthChannel->GetLoadGroup(getter_AddRefs(loadGroup));
    if (NS_FAILED(rv)) return rv;

    nsCOMPtr<nsIAuthPrompt2> authPrompt;
    GetAuthPrompt(callbacks, proxyAuth, getter_AddRefs(authPrompt));
    if (!authPrompt && loadGroup) {
        nsCOMPtr<nsIInterfaceRequestor> cbs;
        loadGroup->GetNotificationCallbacks(getter_AddRefs(cbs));
        GetAuthPrompt(cbs, proxyAuth, getter_AddRefs(authPrompt));
    }
    if (!authPrompt)
        return NS_ERROR_NO_INTERFACE;

    // XXX i18n: need to support non-ASCII realm strings (see bug 41489)
    NS_ConvertASCIItoUTF16 realmU(realm);

    // prompt the user...
    uint32_t promptFlags = 0;
    if (proxyAuth)
    {
        promptFlags |= nsIAuthInformation::AUTH_PROXY;
        if (mTriedProxyAuth)
            promptFlags |= nsIAuthInformation::PREVIOUS_FAILED;
        mTriedProxyAuth = true;
    }
    else {
        promptFlags |= nsIAuthInformation::AUTH_HOST;
        if (mTriedHostAuth)
            promptFlags |= nsIAuthInformation::PREVIOUS_FAILED;
        mTriedHostAuth = true;
    }

    if (authFlags & nsIHttpAuthenticator::IDENTITY_INCLUDES_DOMAIN)
        promptFlags |= nsIAuthInformation::NEED_DOMAIN;

    nsRefPtr<nsHTTPAuthInformation> holder =
        new nsHTTPAuthInformation(promptFlags, realmU,
                                  nsDependentCString(authType));
    if (!holder)
        return NS_ERROR_OUT_OF_MEMORY;

    nsCOMPtr<nsIChannel> channel(do_QueryInterface(mAuthChannel, &rv));
    if (NS_FAILED(rv)) return rv;

    rv =
        authPrompt->AsyncPromptAuth(channel, this, nullptr, level, holder,
                                    getter_AddRefs(mAsyncPromptAuthCancelable));

    if (NS_SUCCEEDED(rv)) {
        // indicate using this error code that authentication prompt
        // result is expected asynchronously
        rv = NS_ERROR_IN_PROGRESS;
    }
    else {
        // Fall back to synchronous prompt
        bool retval = false;
        rv = authPrompt->PromptAuth(channel, level, holder, &retval);
        if (NS_FAILED(rv))
            return rv;

        if (!retval)
            rv = NS_ERROR_ABORT;
        else
            holder->SetToHttpAuthIdentity(authFlags, ident);
    }

    // remember that we successfully showed the user an auth dialog
    if (!proxyAuth)
        mSuppressDefensiveAuth = true;

    return rv;
}
Exemplo n.º 27
0
bool
ServerWindow::ParseEvents (const char *data)
{
	BString firstWord = GetWord(data, 1).ToUpper();
	BString secondWord = GetWord(data, 2).ToUpper();

	if(firstWord == "PING")
	{
		BString tempString,
		        theServer (GetWord(data, 2));
		theServer.RemoveFirst(":");
		
		tempString << "PONG " << myNick << " " << theServer;
		SendData (tempString.String());
		tempString = "";
		tempString << "PONG " << theServer; // fix for some noncompliant servers
		SendData (tempString.String());
		return true;
	}

	if (secondWord == "JOIN")
	{
		BString nick (GetNick (data));
		BString channel (GetWord (data, 3));

		channel.RemoveFirst (":");
		ClientWindow *client (Client (channel.String()));

		if (nick == myNick)
		{
			if (!client)
			{
				client =  new ChannelWindow (
					channel.String(),
					sid,
					serverName.String(),
					sMsgr,
					myNick.String());

				clients.AddItem (client);
				client->Show();
			}
				
			BString tempString ("MODE ");
			tempString << channel;
			SendData (tempString.String());
		}
		else if (client)
		{
			// someone else
			BString ident (GetIdent (data));
			BString address (GetAddress (data));
			const char *expansions[3];
			BString tempString, addy;

			expansions[0] = nick.String();
			expansions[1] = ident.String();
			expansions[2] = address.String();

			tempString = ExpandKeyed (events[E_JOIN], "NIA", expansions);
			BMessage display (M_DISPLAY);
			PackDisplay (
				&display,
				tempString.String(),
				&joinColor,
				0,
				true);

			addy << ident << "@" << address;

			BMessage aMsg (M_IS_IGNORED), reply;
			bool ignored;

			aMsg.AddString ("server", serverName.String());
			aMsg.AddString ("nick", nick.String());
			aMsg.AddString ("address", addy.String());

			be_app_messenger.SendMessage (&aMsg, &reply);
			reply.FindBool ("ignored", &ignored);
			
			BMessage msg (M_USER_ADD);
			msg.AddString ("nick",  nick.String());
			msg.AddBool ("ignore", ignored);
			msg.AddMessage ("display", &display);
			client->PostMessage (&msg);
		}
		return true;
	}
	
	if (secondWord == "PART")
	{
		BString nick (GetNick (data));
		BString channel (GetWord (data, 3));
		ClientWindow *client;

		if ((client = Client (channel.String())) != 0)
		{
			BString ident (GetIdent (data));
			BString address (GetAddress (data));
			const char *expansions[3];
			BString buffer;

			expansions[0] = nick.String();
			expansions[1] = ident.String();
			expansions[2] = address.String();

			buffer = ExpandKeyed (events[E_PART], "NIA", expansions);

			BMessage display (M_DISPLAY);
			PackDisplay (&display, buffer.String(), &joinColor, 0, true);

			BMessage msg (M_USER_QUIT);
			msg.AddString ("nick", nick.String());
			msg.AddMessage ("display", &display);
			client->PostMessage (&msg);
		}

		return true;
	}
	
	if(secondWord == "PRIVMSG")
	{
		BString theNick (GetNick (data)),
			ident (GetIdent (data)),
			address (GetAddress (data)),
			addy;


		addy << ident << "@" << address;
		BMessage aMsg (M_IS_IGNORED), reply;
		bool ignored;

		aMsg.AddString ("server", serverName.String());
		aMsg.AddString ("nick", theNick.String());
		aMsg.AddString ("address", addy.String());

		be_app_messenger.SendMessage (&aMsg, &reply);
		reply.FindBool ("ignored", &ignored);

		if (ignored)
		{
			BMessage msg (M_IGNORED_PRIVMSG);
			const char *rule;

			reply.FindString ("rule", &rule);
			msg.AddString ("nick", theNick.String());
			msg.AddString ("address", addy.String());
			msg.AddString ("rule", rule);
			Broadcast (&msg);
			return true;
		}

		BString theTarget (GetWord (data, 3).ToUpper()),
		        theTargetOrig (GetWord (data, 3)),
		        theMsg (RestOfString (data, 4));
		ClientWindow *client (0);

		theMsg.RemoveFirst(":");

		if(theMsg[0] == '\1' && GetWord(theMsg.String(), 1) != "\1ACTION") // CTCP
		{
			ParseCTCP (theNick, theTargetOrig, theMsg);
			return true;
		}

		if (theTarget[0] == '#')
			client = Client (theTarget.String());
		else if (!(client = Client (theNick.String())))
		{
			BString ident = GetIdent(data);
			BString address = GetAddress(data);
			BString addyString;
			addyString << ident << "@" << address;

			client = new MessageWindow (
				theNick.String(),
				sid,
				serverName.String(),
				sMsgr,
				myNick.String(),
				addyString.String(),
				false, // not a dcc chat
				true); // initated by server

			clients.AddItem (client);
			client->Show();
		}

		if (client) client->ChannelMessage (
			theMsg.String(),
			theNick.String(),
			ident.String(),
			address.String());

		return true;
	}
	
	if (secondWord == "NICK")
	{
		BString oldNick (GetNick (data)),
		        ident (GetIdent (data)),
		        address (GetAddress (data)),
		        newNick (GetWord (data, 3)),
		        buffer;
		const char *expansions[4];

		newNick.RemoveFirst (":");

		expansions[0] = oldNick.String();
		expansions[1] = newNick.String();
		expansions[2] = ident.String();
		expansions[3] = address.String();

		buffer = ExpandKeyed (events[E_NICK], "NnIA", expansions);
		BMessage display (M_DISPLAY);
		PackDisplay (&display, buffer.String(), &nickColor, 0, bowser_app->GetStampState());

		BMessage msg (M_CHANGE_NICK);
		msg.AddString ("oldnick", oldNick.String());
		msg.AddString ("newnick", newNick.String());
		msg.AddString ("ident", ident.String());
		msg.AddString ("address", address.String());
		msg.AddMessage ("display", &display);

		Broadcast (&msg);

		// Gotta change the server as well!
		if (myNick.ICompare (oldNick) == 0)
		{
			myNick = newNick;
			status->SetItemValue (STATUS_NICK, newNick.String());
		}

		bowser_app->PostMessage (&msg); // for ignores

		return true;
	}

	if (secondWord == "QUIT")
	{
		BString theNick (GetNick (data).String()),
		        theRest (RestOfString (data, 3)),
		        ident (GetIdent (data)),
		        address (GetAddress (data)),
		        theMsg,
		        firstNick;
		const char *expansions[4];

		theRest.RemoveFirst (":");
		
		expansions[0] = theNick.String();
		expansions[1] = theRest.String();
		expansions[2] = ident.String();
		expansions[3] = address.String();

		theMsg = ExpandKeyed (events[E_QUIT], "NRIA", expansions);
		BMessage display (M_DISPLAY);
		PackDisplay (&display, theMsg.String(), &quitColor, 0, true);

		BMessage msg (M_USER_QUIT);
		msg.AddMessage ("display", &display);
		msg.AddString ("nick", theNick.String());

		Broadcast (&msg);
		
		// see if it was our first nickname. if so, change
		firstNick = (const char *)lnicks->ItemAt (0);
		if (theNick == firstNick)
		{
			BString tempCmd ("/nick ");
			tempCmd << firstNick;
			ParseCmd (tempCmd.String());
		}
				
		return true;
	}

	if (secondWord == "KICK")
	{
		BString kicker (GetNick (data)),
		        kickee (GetWord (data, 4)),
		        rest (RestOfString (data, 5)),
		        channel (GetWord (data, 3));
		ClientWindow *client (Client (channel.String()));

		rest.RemoveFirst (":");

		if ((client = Client (channel.String())) != 0
		&&   kickee == myNick)
		{
			BMessage display (M_DISPLAY); // "you were kicked"
			BString buffer;

			buffer << "*** You have been kicked from "
				<< channel << " by " << kicker << " (" << rest << ")\n";
			PackDisplay (&display, buffer.String(), &quitColor, 0, true);

			BMessage display2 (M_DISPLAY); // "attempting auto rejoin"
			buffer = "*** Attempting to automagically rejoin ";
			buffer << channel << "...\n";
			PackDisplay (&display2, buffer.String(), &quitColor, 0, true);
						

			BMessage msg (M_CHANNEL_GOT_KICKED);
			msg.AddString ("channel", channel.String());
			msg.AddMessage ("display", &display);  // "you were kicked"
			msg.AddMessage ("display2", &display2); // "attempting auto rejoin"
			client->PostMessage (&msg);
		}

		if (client && kickee != myNick)
		{
			BMessage display (M_DISPLAY);
			const char *expansions[4];
			BString buffer;

			expansions[0] = kickee.String();
			expansions[1] = channel.String();
			expansions[2] = kicker.String();
			expansions[3] = rest.String();

			buffer = ExpandKeyed (events[E_KICK], "NCnR", expansions);
			PackDisplay (&display, buffer.String(), &quitColor, 0, true);

			BMessage msg (M_USER_QUIT);
			msg.AddString ("nick", kickee.String());
			msg.AddMessage ("display", &display);
			client->PostMessage (&msg);
		}

		return true;
	}

	if(secondWord == "TOPIC")
	{
		BString theNick (GetNick (data)),
		        theChannel (GetWord (data, 3)),
		        theTopic (RestOfString (data, 4));
		ClientWindow *client (Client (theChannel.String()));

		theTopic.RemoveFirst (":");

		if (client && client->Lock())
		{
			BString ident (GetIdent (data));
			BString address (GetAddress (data));
			const char *expansions[5];
			BString buffer;

			expansions[0] = theNick.String();
			expansions[1] = theTopic.String();
			expansions[2] = client->Id().String();
			expansions[3] = ident.String();
			expansions[4] = address.String();

			if(bowser_app->GetShowTopicState())
			{
				buffer << client->Id() << " : " << theTopic;
				client->SetTitle (buffer.String());
				client->Unlock();
			}
			else
			{
				buffer << client->Id();
				client->SetTitle (buffer.String());
				client->Unlock();
			}
			
			BMessage topic (M_CHANNEL_TOPIC);
			
			topic.AddString("topic", theTopic.String());
						
			BMessage display (M_DISPLAY);

			buffer = ExpandKeyed (events[E_TOPIC], "NTCIA", expansions);
			PackDisplay (&display, buffer.String(), &whoisColor, 0, true);
			topic.AddMessage("display", &display);
			client->PostMessage (&topic);
		}
		return true;
	}

	if (secondWord == "MODE")
	{
		BString theNick (GetNick (data)),
		        theChannel (GetWord (data, 3)),
		        theMode (GetWord (data, 4)),
		        theTarget (RestOfString (data, 5));
		ClientWindow *client (Client (theChannel.String()));

		if (client)
		{
			BMessage msg (M_CHANNEL_MODE);

			msg.AddString("nick", theNick.String());
			msg.AddString("mode", theMode.String());
			msg.AddString("target", theTarget.String());

			client->PostMessage (&msg);
		}
		else
		{
			BMessage msg (M_DISPLAY);
			BString buffer;
			
			theMode.RemoveFirst(":");
	
			buffer << "*** User mode changed: " << theMode << "\n";
			PackDisplay (&msg, buffer.String(), 0, 0, true);

			PostActive (&msg);
		}

		return true;
	}

	if(firstWord == "NOTICE") // _server_ notice
	{
		BString theNotice (RestOfString(data, 3));
		const char *expansions[1];

		theNotice.RemoveFirst(":");

		expansions[0] = theNotice.String();
		theNotice = ExpandKeyed (events[E_SNOTICE], "R", expansions);
		Display (theNotice.String(), 0, 0, true);

		return true;
	}

	if (firstWord == "ERROR") // server error (on connect?)
	{
		BString theError (RestOfString (data, 2));

		theError.RemoveAll (":");
		theError.Append ("\n");

		Display (theError.String(), &quitColor);
		isConnecting = false;
		return true;
	}

	if(secondWord == "NOTICE") // _user_ notice
	{
		BString theNick (GetNick (data)),
			ident (GetIdent (data)),
			address (GetAddress (data)),
			addy;

		addy << theNick << "@" << address;

		BMessage aMsg (M_IS_IGNORED), reply;
		bool ignored;

		aMsg.AddString ("server", serverName.String());
		aMsg.AddString ("nick", theNick.String());
		aMsg.AddString ("address", addy.String());

		be_app_messenger.SendMessage (&aMsg, &reply);
		reply.FindBool ("ignored", &ignored);

		if (ignored) return true;

		BString theNotice = RestOfString(data, 4);

		theNotice.RemoveFirst(":");

		if(theNotice[0] == '\1')
		{
			ParseCTCPResponse(theNick, theNotice);
			return true;
		}

		const char *expansions[4];
		BString tempString;

		expansions[0] = theNick.String();
		expansions[1] = theNotice.String();
		expansions[2] = ident.String();
		expansions[3] = address.String();

		tempString = ExpandKeyed (events[E_UNOTICE], "NRIA", expansions);
		BMessage display (M_DISPLAY);
		PackDisplay (&display, tempString.String(), &noticeColor, 0, true);
		PostActive (&display);
		return true;
	}

	return ParseENums (data, secondWord.String());
}
void
IPDLUnitTestThreadChild::Init()
{
    MozillaChildThread::Init();
    IPDLUnitTestChildInit(channel(), GetParentProcessHandle(), owner_loop());
}
Exemplo n.º 29
-1
void filter::add_ref( void ) {
	channel()->add_ref();
}
Exemplo n.º 30
-1
bool IrcKickMessage::isValid() const
{
    return IrcMessage::isValid() && !channel().isEmpty() && !user().isEmpty();
}