/** 将glossary.dat文件中的概念信息读入到数据库中 */ int GlossaryDao::ReadGlossaryToDB(const std::string str_path) { std::ifstream ifs_glossary(str_path.c_str()); //打开词典文件 std::string str_line; RemoveAll(); while(getline(ifs_glossary,str_line)) //逐行读取词典文件 { std::istringstream iss(str_line); std::string str_word,str_pos,str_sememe; iss>>str_word>>str_pos>>str_sememe; //由空白把一行分割成:词、词性、义原集合 std::string str_set; if(str_sememe[0]=='{') //该行是虚词,因为虚词的描述只有“{句法义原}”或“{关系义原}” { str_set=str_sememe; } else { std::string str1,str2,str3,str4;//分别是 基本义原描述式\n其他义原描述式\n关系义原描述式\n关系符号义原描述式 std::string::size_type pos1,pos2; pos1=0; bool flag=true; while(flag) { pos2=str_sememe.find(",",pos1); std::string str_sem; if(std::string::npos==pos2) //已是最后一个义原 { flag=false; str_sem=str_sememe.substr(pos1); //提取最后一个义原 } else { str_sem=str_sememe.substr(pos1,pos2-pos1); //提取下一个义原 }//sem是pos1之后的第一个逗号之前的义原 pos1=pos2+1; if(str_sem.find("=")!=std::string::npos) //关系义原,加入str3 { str3+=str_sem+","; } else { char c=str_sem[0]; //义原以大/小写英文字母开始,或者是具体词--单独在小括号里,属于其他义原,加入str2。40是"("的ASCII值 if((c>64&&c<91) || (c>96&&c<123) || (c==40)) { str2+=str_sem+","; } else //关系符号义原,加入str4 { str4+=str_sem+","; } } } //把str2中的第一条取出来,赋给str1 std::string::size_type pos3=str2.find(","); if(pos3!=std::string::npos) { str1=str2.substr(0,pos3); str2.erase(0,pos3+1); } if(str2!="") { str2.erase(str2.length()-1,1); } if(str3!="") { str3.erase(str3.length()-1,1); } if(str4!="") { str4.erase(str4.length()-1,1); } str_set=str1+"\n"+str2+"\n"+str3+"\n"+str4; } Insert(str_word,str_pos,str_set); } return 0; }
void ExtractTrackBasedTiming(int runNumber){ TString fileName = Form ("Run%i/TrackBasedTiming.root", runNumber); TString prefix = Form ("Run%i/constants/TrackBasedTiming/",runNumber); TString inputPrefix = Form ("Run%i/constants/TDCADCTiming/",runNumber); thisFile = TFile::Open( fileName , "UPDATE"); if (thisFile == 0) { cout << "Unable to open file " << fileName.Data() << "...Exiting" << endl; return; } //We need the existing constants, The best we can do here is just read them from the file. vector<double> sc_tdc_time_offsets; vector<double> sc_fadc_time_offsets; vector<double> tof_tdc_time_offsets; vector<double> tof_fadc_time_offsets; vector<double> tagm_tdc_time_offsets; vector<double> tagm_fadc_time_offsets; vector<double> tagh_tdc_time_offsets; vector<double> tagh_fadc_time_offsets; double sc_t_base_fadc; double sc_t_base_tdc; double tof_t_base_fadc; double tof_t_base_tdc; double bcal_t_base_fadc; double bcal_t_base_tdc; double tagm_t_base_fadc; double tagm_t_base_tdc; double tagh_t_base_fadc; double tagh_t_base_tdc; double fcal_t_base; double cdc_t_base; ifstream inFile; inFile.open(inputPrefix + "sc_tdc_timing_offsets.txt"); string line; if (inFile.is_open()){ while (getline (inFile, line)){ sc_tdc_time_offsets.push_back(atof(line.data())); } } inFile.close(); ifstream inFile; inFile.open(inputPrefix + "sc_adc_timing_offsets.txt"); string line; if (inFile.is_open()){ while (getline (inFile, line)){ sc_fadc_time_offsets.push_back(atof(line.data())); } } inFile.close(); inFile.open(inputPrefix + "tof_tdc_timing_offsets.txt"); if (inFile.is_open()){ while (getline (inFile, line)){ tof_tdc_time_offsets.push_back(atof(line.data())); } } inFile.close(); inFile.open(inputPrefix + "tof_adc_timing_offsets.txt"); if (inFile.is_open()){ while (getline (inFile, line)){ tof_fadc_time_offsets.push_back(atof(line.data())); } } inFile.close(); inFile.open(inputPrefix + "tagm_tdc_timing_offsets.txt"); if (inFile.is_open()){ while (getline (inFile, line)){ istringstream iss(line); double r, c, offset; while (iss>>r>>c>>offset){ //if (row != 0) continue; tagm_tdc_time_offsets.push_back(offset); } } } inFile.close(); inFile.open(inputPrefix + "tagm_adc_timing_offsets.txt"); if (inFile.is_open()){ while (getline (inFile, line)){ istringstream iss(line); double r, c, offset; while (iss>>r>>c>>offset){ //if (row != 0) continue; tagm_fadc_time_offsets.push_back(offset); } } } inFile.close(); inFile.open(inputPrefix + "tagh_tdc_timing_offsets.txt"); if (inFile.is_open()){ while (getline (inFile, line)){ istringstream iss(line); double counter, offset; while (iss>>counter>>offset){ tagh_tdc_time_offsets.push_back(offset); } } } inFile.close(); inFile.open(inputPrefix + "tagh_adc_timing_offsets.txt"); if (inFile.is_open()){ while (getline (inFile, line)){ istringstream iss(line); double counter, offset; while (iss>>counter>>offset){ tagh_fadc_time_offsets.push_back(offset); } } } inFile.close(); inFile.open(inputPrefix + "tof_base_time.txt"); if (inFile.is_open()){ while (getline (inFile, line)){ istringstream iss(line); iss>>tof_t_base_fadc>>tof_t_base_tdc; } } inFile.close(); inFile.open(inputPrefix + "sc_base_time.txt"); if (inFile.is_open()){ while (getline (inFile, line)){ istringstream iss(line); iss>>sc_t_base_fadc>>sc_t_base_tdc; } } inFile.close(); inFile.open(inputPrefix + "bcal_base_time.txt"); if (inFile.is_open()){ while (getline (inFile, line)){ istringstream iss(line); double adc_offset, tdc_offset; iss>>adc_offset>>tdc_offset; // TDC not used currently bcal_t_base_fadc = adc_offset; bcal_t_base_tdc = tdc_offset; } } inFile.close(); inFile.open(inputPrefix + "tagm_base_time.txt"); if (inFile.is_open()){ while (getline (inFile, line)){ istringstream iss(line); double adc_offset, tdc_offset; iss>>adc_offset>>tdc_offset; // TDC not used currently tagm_t_base_fadc = adc_offset; tagm_t_base_tdc = tdc_offset; } } inFile.close(); inFile.open(inputPrefix + "tagh_base_time.txt"); if (inFile.is_open()){ while (getline (inFile, line)){ istringstream iss(line); double adc_offset, tdc_offset; iss>>adc_offset>>tdc_offset; // TDC not used currently tagh_t_base_fadc = adc_offset; tagh_t_base_tdc = tdc_offset; } } inFile.close(); inFile.open(inputPrefix + "fcal_base_time.txt"); if (inFile.is_open()){ while (getline (inFile, line)){ istringstream iss(line); iss>>fcal_t_base; } } inFile.close(); inFile.open(inputPrefix + "cdc_base_time.txt"); if (inFile.is_open()){ while (getline (inFile, line)){ istringstream iss(line); iss>>cdc_t_base; } } inFile.close(); // Do our final step in the timing alignment with tracking //When the RF is present we can try to simply pick out the correct beam bucket for each of the runs //First just a simple check to see if we have the appropriate data bool useRF = false; double RF_Period = 4.0080161; TH1I *testHist = Get1DHistogram("HLDetectorTiming", "TAGH_TDC_RF_Compare","Counter ID 001"); if (testHist != NULL){ // Not great since we rely on channel 1 working, but can be craftier later. useRF = true; } ofstream outFile; TH2I *thisHist; thisHist = Get2DHistogram("HLDetectorTiming", "TRACKING", "TAGM - SC Target Time"); if (useRF) thisHist = Get2DHistogram("HLDetectorTiming", "TRACKING", "TAGM - RFBunch Time"); if (thisHist != NULL){ //Statistics on these histograms are really quite low we will have to rebin and do some interpolation outFile.open(prefix + "tagm_tdc_timing_offsets.txt", ios::out | ios::trunc); outFile.close(); // clear file outFile.open(prefix + "tagm_adc_timing_offsets.txt", ios::out | ios::trunc); outFile.close(); // clear file int nBinsX = thisHist->GetNbinsX(); int nBinsY = thisHist->GetNbinsY(); TH1D * selectedTAGMOffset = new TH1D("selectedTAGMOffset", "Selected TAGM Offset; Column; Offset [ns]", nBinsX, 0.5, nBinsX + 0.5); TH1I * TAGMOffsetDistribution = new TH1I("TAGMOffsetDistribution", "TAGM Offset; TAGM Offset [ns]; Entries", 500, -250, 250); for (int i = 1 ; i <= nBinsX; i++){ TH1D *projY = thisHist->ProjectionY("temp", i, i); // Scan over the histogram //chose the correct number of bins based on the histogram float nsPerBin = (projY->GetBinCenter(projY->GetNbinsX()) - projY->GetBinCenter(1)) / projY->GetNbinsX(); float timeWindow = 3; //ns (Full Width) int binWindow = int(timeWindow / nsPerBin); double maxEntries = 0; double maxMean = 0; for (int j = 1 ; j <= projY->GetNbinsX();j++){ int minBin = j; int maxBin = (j + binWindow) <= projY->GetNbinsX() ? (j + binWindow) : projY->GetNbinsX(); double sum = 0, nEntries = 0; for (int bin = minBin; bin <= maxBin; bin++){ sum += projY->GetBinContent(bin) * projY->GetBinCenter(bin); nEntries += projY->GetBinContent(bin); if (bin == maxBin){ if (nEntries > maxEntries) { maxMean = sum / nEntries; maxEntries = nEntries; } } } } //In the case there is RF, our job is to pick just the number of the correct beam bunch, so that's really all we need. if(useRF) { int beamBucket = int((maxMean / RF_Period) + 0.5); // +0.5 to handle rounding correctly selectedTAGMOffset->SetBinContent(i, beamBucket); TAGMOffsetDistribution->Fill(beamBucket); } else{ selectedTAGMOffset->SetBinContent(i, maxMean); TAGMOffsetDistribution->Fill(maxMean); } } /* if (!useRF){ //TFitResultPtr fr1 = selectedTAGMOffset->Fit("pol1", "SQ", "", 0.5, nBinsX + 0.5); TFitResultPtr fr1 = selectedTAGMOffset->Fit("pol1", "SQ", "", 5, 50); for (int i = 1 ; i <= nBinsX; i++){ double x0 = fr1->Parameter(0); double x1 = fr1->Parameter(1); //double x2 = fr1->Parameter(2); //double fitResult = x0 + i*x1 + i*i*x2; double fitResult = x0 + i*x1; double outlierCut = 20; double valueToUse = selectedTAGMOffset->GetBinContent(i); if (fabs(selectedTAGMOffset->GetBinContent(i) - fitResult) > outlierCut && valueToUse != 0.0){ valueToUse = fitResult; } selectedTAGMOffset->SetBinContent(i, valueToUse); if (valueToUse != 0 ) TAGMOffsetDistribution->Fill(valueToUse); } } */ double meanOffset = TAGMOffsetDistribution->GetMean(); // This might be in units of beam bunches, so we need to convert if (useRF) meanOffset *= RF_Period; /* for (int i = 1 ; i <= nBinsX; i++){ double valueToUse = selectedTAGMOffset->GetBinContent(i); if (useRF) valueToUse *= RF_Period; if (valueToUse == 0) valueToUse = meanOffset; outFile.open(prefix + "tagm_tdc_timing_offsets.txt", ios::out | ios::app); outFile << "0 " << i << " " << valueToUse + tagm_tdc_time_offsets[i-1] - meanOffset<< endl; if (i == 7 || i == 25 || i == 79 || i == 97){ for(int j = 1; j <= 5; j++){ outFile << j << " " << i << " " << valueToUse + tagm_tdc_time_offsets[i-1] - meanOffset<< endl; } } outFile.close(); // Apply the same shift to the adc offsets outFile.open(prefix + "tagm_adc_timing_offsets.txt", ios::out | ios::app); outFile << "0 " << i << " " << valueToUse + tagm_fadc_time_offsets[i-1] - meanOffset<< endl; if (i == 7 || i == 25 || i == 79 || i == 97){ for(int j = 1; j <= 5; j++){ outFile << j << " " << i << " " << valueToUse + tagm_fadc_time_offsets[i-1] - meanOffset<< endl; } } outFile.close(); } */ outFile.open(prefix + "tagm_adc_timing_offsets.txt", ios::out); //for (int i = 1 ; i <= nBinsX; i++){ // Loop over rows for (unsigned int column = 1; column <= 102; column++){ int index = GetCCDBIndexTAGM(column, 0); double valueToUse = selectedTAGMOffset->GetBinContent(index); if (useRF) valueToUse *= RF_Period; if (valueToUse == 0) valueToUse = meanOffset; outFile << "0 " << column << " " << valueToUse + tagm_fadc_time_offsets[index-1] - meanOffset<< endl; if (column == 9 || column == 27 || column == 81 || column == 99){ for (unsigned int row = 1; row <= 5; row++){ index = GetCCDBIndexTAGM(column, row); valueToUse = selectedTAGMOffset->GetBinContent(index); if (useRF) valueToUse *= RF_Period; if (valueToUse == 0) valueToUse = meanOffset; outFile << row << " " << column << " " << valueToUse + tagm_fadc_time_offsets[index-1] - meanOffset<< endl; } } } outFile.close(); outFile.open(prefix + "tagm_tdc_timing_offsets.txt", ios::out); //for (int i = 1 ; i <= nBinsX; i++){ // Loop over rows for (unsigned int column = 1; column <= 102; column++){ int index = GetCCDBIndexTAGM(column, 0); double valueToUse = selectedTAGMOffset->GetBinContent(index); if (useRF) valueToUse *= RF_Period; if (valueToUse == 0) valueToUse = meanOffset; outFile << "0 " << column << " " << valueToUse + tagm_tdc_time_offsets[index-1] - meanOffset << endl; if (column == 9 || column == 27 || column == 81 || column == 99){ for (unsigned int row = 1; row <= 5; row++){ index = GetCCDBIndexTAGM(column, row); valueToUse = selectedTAGMOffset->GetBinContent(index); if (useRF) valueToUse *= RF_Period; if (valueToUse == 0) valueToUse = meanOffset; outFile << row << " " << column << " " << valueToUse + tagm_tdc_time_offsets[index-1] - meanOffset << endl; } } } outFile.close(); outFile.open(prefix + "tagm_base_time.txt", ios::out); outFile << tagm_t_base_fadc - meanOffset << " " << tagm_t_base_tdc - meanOffset << endl; outFile.close(); } thisHist = Get2DHistogram("HLDetectorTiming", "TRACKING", "TAGH - SC Target Time"); if (useRF) thisHist = Get2DHistogram("HLDetectorTiming", "TRACKING", "TAGH - RFBunch Time"); if(thisHist != NULL){ outFile.open(prefix + "tagh_tdc_timing_offsets.txt", ios::out | ios::trunc); outFile.close(); // clear file outFile.open(prefix + "tagh_adc_timing_offsets.txt", ios::out | ios::trunc); outFile.close(); // clear file int nBinsX = thisHist->GetNbinsX(); int nBinsY = thisHist->GetNbinsY(); TH1D * selectedTAGHOffset = new TH1D("selectedTAGHOffset", "Selected TAGH Offset; ID; Offset [ns]", nBinsX, 0.5, nBinsX + 0.5); TH1I * TAGHOffsetDistribution = new TH1I("TAGHOffsetDistribution", "TAGH Offset; TAGH Offset [ns]; Entries", 500, -250, 250); for (int i = 1 ; i <= nBinsX; i++){ TH1D *projY = thisHist->ProjectionY("temp", i, i); // Scan over the histogram //chose the correct number of bins based on the histogram float nsPerBin = (projY->GetBinCenter(projY->GetNbinsX()) - projY->GetBinCenter(1)) / projY->GetNbinsX(); float timeWindow = 2; //ns (Full Width) int binWindow = int(timeWindow / nsPerBin); double maxEntries = 0; double maxMean = 0; for (int j = 1 ; j <= projY->GetNbinsX();j++){ int minBin = j; int maxBin = (j + binWindow) <= projY->GetNbinsX() ? (j + binWindow) : projY->GetNbinsX(); double sum = 0; double nEntries = 0; for (int bin = minBin; bin <= maxBin; bin++){ sum += projY->GetBinContent(bin) * projY->GetBinCenter(bin); nEntries += projY->GetBinContent(bin); if (bin == maxBin){ if (nEntries > maxEntries){ maxMean = sum / nEntries; maxEntries = nEntries; } } } } if(useRF) { int beamBucket = int((maxMean / RF_Period) + 0.5); // +0.5 to handle rounding correctly selectedTAGHOffset->SetBinContent(i, beamBucket); TAGHOffsetDistribution->Fill(beamBucket); } else{ selectedTAGHOffset->SetBinContent(i, maxMean); } /* outFile.open("tagh_tdc_timing_offsets.txt", ios::out | ios::app); outFile << i << " " << maxMean + tagh_tdc_time_offsets[i] << endl; outFile.close(); outFile.open("tagh_adc_timing_offsets.txt", ios::out | ios::app); outFile << i << " " << maxMean + tagh_fadc_time_offsets[i] << endl; outFile.close(); */ } // Fit 1D histogram. If value is far from the fit use the fitted value // Two behaviors above and below microscope // This isn't working well, so removing... /* TFitResultPtr fr1 = selectedTAGHOffset->Fit("pol2", "SQ", "", 0.5, 131.5); TFitResultPtr fr2 = selectedTAGHOffset->Fit("pol2", "SQ", "", 182.5, 274.5); for (int i = 1 ; i <= nBinsX; i++){ double fitResult = 0.0; if (i < 150){ double x0 = fr1->Parameter(0); double x1 = fr1->Parameter(1); double x2 = fr1->Parameter(2); fitResult = x0 + i*x1 + i*i*x2; } else{ double x0 = fr2->Parameter(0); double x1 = fr2->Parameter(1); double x2 = fr2->Parameter(2); fitResult = x0 + i*x1 + i*i*x2; } double outlierCut = 7; double valueToUse = selectedTAGHOffset->GetBinContent(i); if (fabs(selectedTAGHOffset->GetBinContent(i) - fitResult) > outlierCut && valueToUse != 0.0){ valueToUse = fitResult; } selectedTAGHOffset->SetBinContent(i, valueToUse); if(valueToUse != 0) TAGHOffsetDistribution->Fill(valueToUse); } */ double meanOffset = TAGHOffsetDistribution->GetMean(); if (useRF) meanOffset *= RF_Period; for (int i = 1 ; i <= nBinsX; i++){ valueToUse = selectedTAGHOffset->GetBinContent(i); if (useRF) valueToUse *= RF_Period; if (valueToUse == 0) valueToUse = meanOffset; outFile.open(prefix + "tagh_tdc_timing_offsets.txt", ios::out | ios::app); outFile << i << " " << valueToUse + tagh_tdc_time_offsets[i-1] - meanOffset << endl; outFile.close(); outFile.open(prefix + "tagh_adc_timing_offsets.txt", ios::out | ios::app); outFile << i << " " << valueToUse + tagh_fadc_time_offsets[i-1] - meanOffset << endl; outFile.close(); } outFile.open(prefix + "tagh_base_time.txt", ios::out); outFile << tagh_t_base_fadc - meanOffset << " " << tagh_t_base_tdc - meanOffset << endl; outFile.close(); } // We can use the RF time to calibrate the SC time (Experimental for now) double meanSCOffset = 0.0; // In case we change the time of the SC, we need this in this scope if(useRF){ TH1F * selectedSCSectorOffset = new TH1F("selectedSCSectorOffset", "Selected TDC-RF offset;Sector; Time", 30, 0.5, 30.5); TH1F * selectedSCSectorOffsetDistribution = new TH1F("selectedSCSectorOffsetDistribution", "Selected TDC-RF offset;Time;Entries", 100, -3.0, 3.0); TF1* f = new TF1("f","pol0(0)+gaus(1)", -3.0, 3.0); for (int sector = 1; sector <= 30; sector++){ TH1I *scRFHist = Get1DHistogram("HLDetectorTiming", "SC_Target_RF_Compare", Form("Sector %.2i", sector)); if (scRFHist == NULL) continue; //Do the fit TFitResultPtr fr = scRFHist->Fit("pol0", "SQ", "", -2, 2); double p0 = fr->Parameter(0); f->FixParameter(0,p0); f->SetParLimits(2, -2, 2); f->SetParLimits(3, 0, 2); f->SetParameter(1, 10); f->SetParameter(2, scRFHist->GetBinCenter(scRFHist->GetMaximumBin())); f->SetParameter(3, 0); fr = scRFHist->Fit(f, "SQ", "", -2, 2); double SCOffset = fr->Parameter(2); selectedSCSectorOffset->SetBinContent(sector, SCOffset); selectedSCSectorOffsetDistribution->Fill(SCOffset); } // Now write out the offsets meanSCOffset = selectedSCSectorOffsetDistribution->GetMean(); outFile.open(prefix + "sc_tdc_timing_offsets.txt"); for (int sector = 1; sector <= 30; sector++){ outFile << sc_tdc_time_offsets[sector-1] + selectedSCSectorOffset->GetBinContent(sector) - meanSCOffset << endl; } outFile.close(); outFile.open(prefix + "sc_adc_timing_offsets.txt"); for (int sector = 1; sector <= 30; sector++){ outFile << sc_fadc_time_offsets[sector-1] + selectedSCSectorOffset->GetBinContent(sector) - meanSCOffset << endl; } outFile.close(); outFile.open(prefix + "sc_base_time.txt"); outFile << sc_t_base_fadc - meanSCOffset << " " << sc_t_base_tdc - meanSCOffset << endl; outFile.close(); } TH1I *this1DHist = Get1DHistogram("HLDetectorTiming", "TRACKING", "TOF - SC Target Time"); if(this1DHist != NULL){ //Gaussian Double_t maximum = this1DHist->GetBinCenter(this1DHist->GetMaximumBin()); TFitResultPtr fr = this1DHist->Fit("gaus", "S", "", maximum - 1.5, maximum + 1.5); float mean = fr->Parameter(1); outFile.open(prefix + "tof_base_time.txt"); outFile << tof_t_base_fadc - mean - meanSCOffset<< " " << tof_t_base_tdc - mean - meanSCOffset<< endl; outFile.close(); } this1DHist = Get1DHistogram("HLDetectorTiming", "TRACKING", "BCAL - SC Target Time"); if(this1DHist != NULL){ //Gaussian Double_t maximum = this1DHist->GetBinCenter(this1DHist->GetMaximumBin()); TFitResultPtr fr = this1DHist->Fit("gaus", "S", "", maximum - 5, maximum + 5); float mean = fr->Parameter(1); outFile.open(prefix + "bcal_base_time.txt"); outFile << bcal_t_base_fadc - mean - meanSCOffset << " " << bcal_t_base_tdc - mean - meanSCOffset << endl; // TDC info not used outFile.close(); } this1DHist = Get1DHistogram("HLDetectorTiming", "TRACKING", "FCAL - SC Target Time"); if(this1DHist != NULL){ //Gaussian Double_t maximum = this1DHist->GetBinCenter(this1DHist->GetMaximumBin()); TFitResultPtr fr = this1DHist->Fit("gaus", "S", "", maximum - 5, maximum + 5); float mean = fr->Parameter(1); outFile.open(prefix + "fcal_base_time.txt"); outFile << fcal_t_base - mean - meanSCOffset<< endl; outFile.close(); } this1DHist = Get1DHistogram("HLDetectorTiming", "TRACKING", "Earliest CDC Time Minus Matched SC Time"); if(this1DHist != NULL){ //Gaussian Double_t maximum = this1DHist->GetBinCenter(this1DHist->GetMaximumBin()); TFitResultPtr fr = this1DHist->Fit("gaus", "S", "", maximum - 15, maximum + 10); float mean = fr->Parameter(1); outFile.open(prefix + "cdc_base_time.txt"); outFile << cdc_t_base - mean - meanSCOffset << endl; outFile.close(); } thisFile->Write(); return; }
void Config::parseNodeID(std::string configStr, PublicKey& retKey, SecretKey& sKey, bool isSeed) { if (configStr.size() < 2) throw std::invalid_argument("invalid key"); // check if configStr is a PublicKey or a common name if (configStr[0] == '$') { if (isSeed) { throw std::invalid_argument("aliases only store public keys"); } if (!resolveNodeID(configStr, retKey)) { std::stringstream msg; msg << "unknown key in config: " << configStr; throw std::invalid_argument(msg.str()); } } else { std::istringstream iss(configStr); std::string nodestr; iss >> nodestr; if (isSeed) { sKey = SecretKey::fromStrKeySeed(nodestr); retKey = sKey.getPublicKey(); nodestr = sKey.getStrKeyPublic(); } else { retKey = PubKeyUtils::fromStrKey(nodestr); } if (iss) { // get any common name they have added std::string commonName; iss >> commonName; if (commonName.size()) { std::string cName = "$"; cName += commonName; if (resolveNodeID(cName, retKey)) { throw std::invalid_argument("name already used"); } if (!VALIDATOR_NAMES.emplace(std::make_pair(nodestr, commonName)).second) { std::stringstream msg; msg << "naming node twice: " << commonName; throw std::invalid_argument(msg.str()); } } } } }
int FilterSeqsCommand::driverMPIRun(int start, int num, MPI_File& inMPI, MPI_File& outMPI, vector<unsigned long long>& MPIPos) { try { string outputString = ""; int count = 0; MPI_Status status; for(int i=0;i<num;i++){ if (m->control_pressed) { return 0; } //read next sequence int length = MPIPos[start+i+1] - MPIPos[start+i]; char* buf4 = new char[length]; MPI_File_read_at(inMPI, MPIPos[start+i], buf4, length, MPI_CHAR, &status); string tempBuf = buf4; if (tempBuf.length() > length) { tempBuf = tempBuf.substr(0, length); } istringstream iss (tempBuf,istringstream::in); delete buf4; Sequence seq(iss); m->gobble(iss); if (seq.getName() != "") { string align = seq.getAligned(); string filterSeq = ""; for(int j=0;j<alignmentLength;j++){ if(filter[j] == '1'){ filterSeq += align[j]; } } count++; outputString += ">" + seq.getName() + "\n" + filterSeq + "\n"; if(count % 10 == 0){ //output to file //send results to parent int length = outputString.length(); char* buf = new char[length]; memcpy(buf, outputString.c_str(), length); MPI_File_write_shared(outMPI, buf, length, MPI_CHAR, &status); outputString = ""; delete buf; } } if((i+1) % 100 == 0){ cout << (i+1) << endl; } } if(outputString != ""){ //output to file //send results to parent int length = outputString.length(); char* buf = new char[length]; memcpy(buf, outputString.c_str(), length); MPI_File_write_shared(outMPI, buf, length, MPI_CHAR, &status); outputString = ""; delete buf; } if((num) % 100 != 0){ cout << (num) << endl; } return 0; } catch(exception& e) { m->errorOut(e, "FilterSeqsCommand", "driverRunFilter"); exit(1); } }
void MapBlock::deSerialize(std::istream &is, u8 version, bool disk) { if(!ser_ver_supported(version)) throw VersionMismatchException("ERROR: MapBlock format not supported"); TRACESTREAM(<<"MapBlock::deSerialize "<<PP(getPos())<<std::endl); m_day_night_differs_expired = false; if(version <= 21) { deSerialize_pre22(is, version, disk); return; } u8 flags = readU8(is); is_underground = (flags & 0x01) ? true : false; m_day_night_differs = (flags & 0x02) ? true : false; m_lighting_expired = (flags & 0x04) ? true : false; m_generated = (flags & 0x08) ? false : true; /* Bulk node data */ TRACESTREAM(<<"MapBlock::deSerialize "<<PP(getPos()) <<": Bulk node data"<<std::endl); u32 nodecount = MAP_BLOCKSIZE*MAP_BLOCKSIZE*MAP_BLOCKSIZE; u8 content_width = readU8(is); u8 params_width = readU8(is); if(content_width != 1 && content_width != 2) throw SerializationError("MapBlock::deSerialize(): invalid content_width"); if(params_width != 2) throw SerializationError("MapBlock::deSerialize(): invalid params_width"); MapNode::deSerializeBulk(is, version, data, nodecount, content_width, params_width, true); /* NodeMetadata */ TRACESTREAM(<<"MapBlock::deSerialize "<<PP(getPos()) <<": Node metadata"<<std::endl); // Ignore errors try{ std::ostringstream oss(std::ios_base::binary); decompressZlib(is, oss); std::istringstream iss(oss.str(), std::ios_base::binary); if(version >= 23) m_node_metadata.deSerialize(iss, m_gamedef); else content_nodemeta_deserialize_legacy(iss, &m_node_metadata, &m_node_timers, m_gamedef); } catch(SerializationError &e) { errorstream<<"WARNING: MapBlock::deSerialize(): Ignoring an error" <<" while deserializing node metadata at (" <<PP(getPos())<<": "<<e.what()<<std::endl; } /* Data that is only on disk */ if(disk) { // Node timers if(version == 23){ // Read unused zero readU8(is); } if(version == 24){ TRACESTREAM(<<"MapBlock::deSerialize "<<PP(getPos()) <<": Node timers (ver==24)"<<std::endl); m_node_timers.deSerialize(is, version); } // Static objects TRACESTREAM(<<"MapBlock::deSerialize "<<PP(getPos()) <<": Static objects"<<std::endl); m_static_objects.deSerialize(is); // Timestamp TRACESTREAM(<<"MapBlock::deSerialize "<<PP(getPos()) <<": Timestamp"<<std::endl); setTimestamp(readU32(is)); m_disk_timestamp = m_timestamp; // Dynamically re-set ids based on node names TRACESTREAM(<<"MapBlock::deSerialize "<<PP(getPos()) <<": NameIdMapping"<<std::endl); NameIdMapping nimap; nimap.deSerialize(is); correctBlockNodeIds(&nimap, data, m_gamedef); if(version >= 25){ TRACESTREAM(<<"MapBlock::deSerialize "<<PP(getPos()) <<": Node timers (ver>=25)"<<std::endl); m_node_timers.deSerialize(is, version); }
TEST( serialise, DISABLED_path_value_confused_with_ini_comments ) { config c; std::istringstream iss( ";comment=2" ); ASSERT_THROW( comma::read< config >( c, iss ), comma::exception ); }
// Create Objects void TestScene::SetupObjects() { spObject sun(new Object); sun->SetVO(MakeShareable(new PrimitiveUVSphere(256, 128))); sun->GetTransform().SetScale(Vector3(2.f, 2.f, 2.f)); Texture sunTexture; LoadTexture(sunTexture, "textures/texture_sun.png"); sun->GetVO()->GetTexture() = sunTexture; sun->SetGLMode(GL_TRIANGLES); sun->EnableTexture(); sun->SetName(L"Sun"); objects.push_back(sun); objectMap.insert(std::make_pair(sun->GetName(), sun)); spObject world(new Object); world->SetVO(MakeShareable(new PrimitiveUVSphere(256, 128))); world->GetTransform().SetPosition(Vector3(5.f, 0.f, 0.f)); Texture worldTexture; LoadTexture(worldTexture, "textures/4kworld.png"); world->GetVO()->GetTexture() = worldTexture; world->SetGLMode(GL_TRIANGLES); world->EnableTexture(); world->SetName(L"Earth"); world->SetParent(sun.Get(), TransformInheritance(true, false, true, false)); objects.push_back(world); objectMap.insert(std::make_pair(world->GetName(), world)); spObject clouds(new Object); clouds->SetVO(MakeShareable(new PrimitiveUVSphere(256, 128))); clouds->GetTransform().SetScale(Vector3(1.01f, 1.01f, 1.01f)); Texture cloudTexture; LoadTexture(cloudTexture, "textures/clouds.png"); clouds->GetVO()->GetTexture() = cloudTexture; clouds->SetGLMode(GL_TRIANGLES); clouds->EnableTexture(); clouds->EnableTransparency(); clouds->SetName(L"Clouds"); clouds->SetParent(world.Get(), TransformInheritance(true, false, true, false)); objects.push_back(clouds); objectMap.insert(std::make_pair(clouds->GetName(), clouds)); //spObject disc(new Object); //disc->SetVO(new PrimitiveDisc(64)); //Texture discTexture; //LoadTexture(discTexture, "crate.png"); //disc->GetVO()->GetTexture() = discTexture; //disc->SetGLMode(GL_TRIANGLE_FAN); //disc->GetTransform().SetPosition(Vector3(2.5f, 0.0f, 0.0f)); //disc->EnableTexture(); //disc->SetName(L"Disc"); //objects.push_back(disc); spObject moon(new Object); moon->SetVO(MakeShareable(new PrimitiveUVSphere(256, 128))); moon->GetTransform().SetScale(Vector3(0.27f, 0.27f, 0.27f)); moon->GetTransform().SetPosition(Vector3(0.f, 0.f, -2.2f)); Texture moonTexture; LoadTexture(moonTexture, "textures/moonmap1k.png"); moon->GetVO()->GetTexture() = moonTexture; moon->SetGLMode(GL_TRIANGLES); moon->EnableTexture(); moon->SetName(L"Moon"); moon->SetParent(world.Get(), TransformInheritance(true, false, true, false)); objects.push_back(moon); objectMap.insert(std::make_pair(moon->GetName(), moon)); spObject hst(new Object); hst->SetVO(MakeShareable(new Model)); static_cast<Model*>(hst->GetVO().Get())->Load("models/hst.obj", "textures/hst.png"); hst->GetTransform().SetScale(Vector3(0.0001f, 0.0001f, 0.0001f)); // This thing is yuge! hst->GetTransform().SetPosition(Vector3(-1.1f, 0.f, 0.f)); hst->GetTransform().SetPreRotation(Rotation(0.f, Vector3(0.25f, 0.25f, -0.25f))); hst->GetTransform().SetRotation(Rotation(0.f, Vector3(-0.2f, 0.8f, -0.2f))); hst->SetGLMode(GL_TRIANGLES); hst->SetName(L"HST"); hst->EnableTexture(); hst->SetParent(world.Get(), TransformInheritance(true, false, true, false)); objects.push_back(hst); objectMap.insert(std::make_pair(hst->GetName(), hst)); spObject iss(new Object); iss->SetVO(MakeShareable(new Model)); static_cast<Model*>(iss->GetVO().Get())->Load("models/iss.obj", "textures/iss.png"); iss->GetTransform().SetScale(Vector3(0.01f, 0.01f, 0.01f)); iss->GetTransform().SetPreRotation(Rotation(0.f, Vector3(0.f, 0.5f, 0.f))); iss->GetTransform().SetRotation(Rotation(0.f, Vector3(0.25f, 0.5f, 0.25f))); iss->GetTransform().SetPosition(Vector3(0.f, 0.f, 1.2f)); iss->SetGLMode(GL_TRIANGLES); iss->SetName(L"ISS"); iss->EnableTexture(); iss->SetParent(world.Get(), TransformInheritance(true, false, true, false)); objects.push_back(iss); objectMap.insert(std::make_pair(iss->GetName(), iss)); spObject teapot(new Object); teapot->SetVO(MakeShareable(new Model)); static_cast<Model*>(teapot->GetVO().Get())->Load("Models/teapot.obj", "textures/teapot.png"); teapot->GetTransform().SetPosition(Vector3(5.f, 5.f, -3.f)); teapot->GetTransform().SetPreRotation(Rotation(0.f, Vector3(1.f, 0.f, 0.f))); teapot->GetTransform().SetRotation(Rotation(0.f, Vector3(0.f, 0.f, 1.f))); teapot->GetTransform().SetScale(Vector3(0.05f, 0.05f, 0.05f)); teapot->SetGLMode(GL_TRIANGLES); teapot->SetName(L"Teapot"); teapot->EnableTexture(); teapot->SetParent(iss.Get(), TransformInheritance(true, true, true, false)); objects.push_back(teapot); objectMap.insert(std::make_pair(teapot->GetName(), teapot)); }
int OnlineMapsPlanner::extractLineCount(std::string line) { std::istringstream iss(line.c_str()); int num_points = 0; iss >> num_points; return num_points; }
bool StrToken::stringTo(Type& tipo,const std::string& s) { std::istringstream iss(s); return !(iss >> tipo).fail(); }
int main(int argc, char *argv[]){ if(argc < 2){ std::cout << "Fail, not enough args" << std::endl; return 1; } std::ifstream input_file(argv[2]); //std::ifstream input_file("myTests.txt"); if(!input_file.is_open()){ std::cout << "File not found" << std::endl; return 1; } int num_sims; input_file >> num_sims; input_file.ignore(INT_MAX, '\n'); std::ofstream output("output.txt"); for(int i=0; i<num_sims; i++){ //parse a single simulation worth of data // <task> algorithm that you are supposed to use for this case std::string alg; input_file >> alg; input_file.ignore(INT_MAX, '\n'); Graph *g = new Graph(); // <source> name of the source node std::string source_name; input_file >> source_name; input_file.ignore(INT_MAX, '\n'); g->create_node(source_name, SOURCE); // <destinations> names of the destination nodes std::string line; if(std::getline(input_file, line)){ std::istringstream iss(line); std::string name; while(iss >> name){ g->create_node(name, DEST); } } // <middle nodes> names of the middle nodes if(std::getline(input_file, line)){ std::istringstream iss(line); std::string name; while(iss >> name){ g->create_node(name, MID); } } // <#pipes> represents the number of pipes int num_pipes; input_file >> num_pipes; input_file.ignore(INT_MAX, '\n'); // <graph> represents start-end nodes, lengths and off-times of pipes for (int i = 0; i < num_pipes; ++i) { //<start> <end> <length> <#off-periods> < period1 > .... <periodn> std::string start; std::string end; int length; int num_periods; input_file >> start >> end >> length >> num_periods; int hours[24] = {}; for (int j=0; j<num_periods; j++) { std::string period; input_file >> period; std::stringstream ss(period); std::string item1; std::string item2; std::getline(ss, item1, '-'); std::getline(ss, item2, '-'); int s = atoi(item1.c_str()); int f = atoi(item2.c_str()); for (int k=s; k<=f; k++) { hours[k]++; } } g->add_edge(start, end, length, hours); input_file.ignore(INT_MAX, '\n'); } int start_time; input_file >> start_time; input_file.ignore(INT_MAX, '\n'); start_time = start_time%24; //run simulation if(alg == "BFS"){ run_BFS(*g, start_time, output); } else if(alg == "DFS") { run_DFS(*g, start_time, output); } else if(alg == "UCS"){ //run_UCS(*g, start_time, output); std::cout << "UCS not working" << std::endl; output << "UCS not working" << std::endl; } else{ std::cout << "Haven't written these yet" << std::endl; } delete g; } std::cout << "Finished" << std::endl; return 0; }
unsigned int CppCheck::check(const std::string &path, const std::string &content) { std::istringstream iss(content); return checkFile(Path::simplifyPath(path), emptyString, iss); }
static void* android_app_entry(void* param) { LOGV("+android_app_entry"); struct android_app* android_app = (struct android_app*)param; android_app->config = AConfiguration_new(); AConfiguration_fromAssetManager(android_app->config, android_app->activity->assetManager); print_cur_config(android_app); android_app->cmdPollSource.id = LOOPER_ID_MAIN; android_app->cmdPollSource.app = android_app; android_app->cmdPollSource.process = process_cmd; android_app->inputPollSource.id = LOOPER_ID_INPUT; android_app->inputPollSource.app = android_app; android_app->inputPollSource.process = process_input; ALooper* looper = ALooper_prepare(ALOOPER_PREPARE_ALLOW_NON_CALLBACKS); ALooper_addFd(looper, android_app->msgread, LOOPER_ID_MAIN, ALOOPER_EVENT_INPUT, NULL, &android_app->cmdPollSource); android_app->looper = looper; pthread_mutex_lock(&android_app->mutex); android_app->running = 1; pthread_cond_broadcast(&android_app->cond); pthread_mutex_unlock(&android_app->mutex); std::string sargv; // Load command line from ARGV parameter JNIEnv *env = GetEnvAttachThread(android_app->activity->vm); if(env) { jobject me = android_app->activity->clazz; jclass acl = env->GetObjectClass(me); //class pointer of NativeActivity jmethodID giid = env->GetMethodID(acl, "getIntent", "()Landroid/content/Intent;"); jobject intent = env->CallObjectMethod(me, giid); //Got our intent jclass icl = env->GetObjectClass(intent); //class pointer of Intent jmethodID gseid = env->GetMethodID(icl, "getStringExtra", "(Ljava/lang/String;)Ljava/lang/String;"); jstring jsARGV = (jstring)env->CallObjectMethod(intent, gseid, env->NewStringUTF("ARGV")); if(jsARGV) { const char *chARGV = env->GetStringUTFChars(jsARGV, 0); if(chARGV) { sargv = std::string(chARGV); LOGI("ARGV: pango %s", chARGV); } env->ReleaseStringUTFChars(jsARGV, chARGV); } android_app->activity->vm->DetachCurrentThread(); } // Set up argv/argc to pass to users main std::vector<std::string> vargv; vargv.push_back("pango"); // Parse parameters from ARGV android intent parameter std::istringstream iss(sargv); std::copy(std::istream_iterator<std::string>(iss), std::istream_iterator<std::string>(), std::back_inserter<std::vector<std::string> >(vargv)); char* argv[vargv.size()+1]; for(size_t ac = 0; ac < vargv.size(); ++ac) { argv[ac] = new char[vargv[ac].size()]; strcpy( argv[ac], vargv[ac].c_str() ); } argv[vargv.size()] = NULL; // Call users standard main entry point. main(vargv.size(), argv); // Clean up parameters for(size_t ac = 0; ac < vargv.size(); ++ac) { delete[] argv[ac]; } android_app_destroy(android_app); LOGV("-android_app_entry"); return NULL; }
bool SdpInfo::processSdp(const std::string& sdp) { std::string strLine; std::istringstream iss(sdp); char* line = (char*) malloc(1000); char** pieces = (char**) malloc(10000); char** cryptopiece = (char**) malloc(5000); MediaType mtype = OTHER; while (std::getline(iss, strLine)) { const char* theline = strLine.c_str(); sprintf(line, "%s\n", theline); char* isVideo = strstr(line, video); char* isAudio = strstr(line, audio); char* isGroup = strstr(line, group); char* isCand = strstr(line, cand); char* isCrypt = strstr(line, crypto); char* isUser = strstr(line, ice_user); char* isPass = strstr(line, ice_pass); char* isSsrc = strstr(line, ssrctag); char* isSAVPF = strstr(line, savpf); char* isRtpmap = strstr(line,rtpmap); char* isRtcpMuxchar = strstr(line,rtcpmux); if (isRtcpMuxchar){ isRtcpMux = true; } if (isSAVPF){ profile = SAVPF; printf("PROFILE %s (1 SAVPF)\n", isSAVPF); } if (isGroup) { isBundle = true; } if (isVideo) { mtype = VIDEO_TYPE; } if (isAudio) { mtype = AUDIO_TYPE; } if (isCand != NULL) { char *pch; pch = strtok(line, " :"); pieces[0] = pch; int i = 0; while (pch != NULL) { pch = strtok(NULL, " :"); pieces[i++] = pch; } processCandidate(pieces, i - 1, mtype); } if (isCrypt) { // printf("crypt %s\n", isCrypt ); CryptoInfo crypinfo; char *pch; pch = strtok(line, " :"); cryptopiece[0] = pch; int i = 0; while (pch != NULL) { pch = strtok(NULL, " :"); // printf("cryptopiece %i es %s\n", i, pch); cryptopiece[i++] = pch; } crypinfo.cipherSuite = std::string(cryptopiece[1]); crypinfo.keyParams = std::string(cryptopiece[3]); crypinfo.mediaType = mtype; cryptoVector_.push_back(crypinfo); // sprintf(key, "%s",cryptopiece[3]); // keys = g_slist_append(keys,key); } if (isUser) { char* pch; pch = strtok(line, " : \n"); pch = strtok(NULL, " : \n"); iceUsername_ = std::string(pch); } if (isPass) { char* pch; pch = strtok(line, " : \n"); pch = strtok(NULL, ": \n"); icePassword_ = std::string(pch); } if (isSsrc) { char* pch; pch = strtok(line, " : \n"); pch = strtok(NULL, ": \n"); if (mtype == VIDEO_TYPE) { videoSsrc = strtoul(pch, NULL, 10); } else if (mtype == AUDIO_TYPE) { audioSsrc = strtoul(pch, NULL, 10); } } // a=rtpmap:PT codec_name/clock_rate if(isRtpmap){ RtpMap theMap; char* pch; pch = strtok(line, " : / \n"); pch = strtok(NULL, " : / \n"); unsigned int PT = strtoul(pch, NULL, 10); pch = strtok(NULL, " : / \n"); std::string codecname(pch); pch = strtok(NULL, " : / \n"); unsigned int clock = strtoul(pch, NULL, 10); theMap.payloadType = PT; theMap.encodingName = codecname; theMap.clockRate = clock; theMap.mediaType = mtype; payloadVector_.push_back(theMap); } } free(line); free(pieces); free(cryptopiece); for (unsigned int i = 0; i < candidateVector_.size(); i++) { CandidateInfo& c = candidateVector_[i]; c.username = iceUsername_; c.password = icePassword_; c.isBundle = isBundle; } return true; }
vector<string> Util::split(const string &str, char delim){ istringstream iss(str); string tmp; vector<string> res; while(getline(iss, tmp, delim)) res.push_back(tmp); return res; }
TEST( serialise, guess_corrupted_xml ) { std::istringstream iss( "<name>dummy<name>" ); config c; ASSERT_THROW( comma::read< config >( c, iss ), comma::exception ); }
void EBSDReader::initialSetup() { // No need to re-read data upon recovery if (_app.isRecovering()) return; // Fetch and check mesh EBSDMesh * mesh = dynamic_cast<EBSDMesh *>(&_mesh); if (mesh == NULL) mooseError("Please use an EBSDMesh in your simulation."); std::ifstream stream_in(mesh->getEBSDFilename().c_str()); if (!stream_in) mooseError("Can't open EBSD file: " << mesh->getEBSDFilename()); const EBSDMesh::EBSDMeshGeometry & g = mesh->getEBSDGeometry(); // Copy file header data from the EBSDMesh _dx = g.d[0]; _nx = g.n[0]; _minx = g.min[0]; _maxx = _minx + _dx * _nx; _dy = g.d[1]; _ny = g.n[1]; _miny = g.min[1]; _maxy = _miny + _dy * _ny; _dz = g.d[2]; _nz = g.n[2]; _minz = g.min[2]; _maxz = _minz + _dz * _nz; // Resize the _data array unsigned total_size = g.dim < 3 ? _nx*_ny : _nx*_ny*_nz; _data.resize(total_size); std::string line; while (std::getline(stream_in, line)) { if (line.find("#") != 0) { // Temporary variables to read in on each line EBSDPointData d; Real x, y, z; std::istringstream iss(line); iss >> d.phi1 >> d.phi >> d.phi2 >> x >> y >> z >> d.grain >> d.phase >> d.symmetry; if (x < _minx || y < _miny || x > _maxx || y > _maxy || (g.dim == 3 && (z < _minz || z > _maxz))) mooseError("EBSD Data ouside of the domain declared in the header ([" << _minx << ':' << _maxx << "], [" << _miny << ':' << _maxy << "], [" << _minz << ':' << _maxz << "]) dim=" << g.dim << "\n" << line); d.p = Point(x,y,z); // determine number of grains in the dataset if (d.grain > _feature_num) _feature_num = d.grain; // The Order parameter is not yet assigned. // We initialize it to zero in order not to have undefined values that break the testing. d.op = 0; unsigned global_index = indexFromPoint(Point(x, y, z)); _data[global_index] = d; } }
TEST( serialise, guess_corrupted_path_value ) { config c; std::istringstream iss( "name/" ); ASSERT_THROW( comma::read< config >( c, iss ), comma::exception ); }
void feathists() { // Choose files string in_file = "uneven2.dat"; const Int_t LENGTH = 24998; // In lines const Int_t VARS = 21; // Number of features // Canvases TCanvas* c[4]; char cname[50], ctitle[50]; for (Int_t i = 0; i < 4; i++) { sprintf(cname, "c%i", i); sprintf(ctitle, "Feature set %i", i + 1); c[i] = new TCanvas(cname, ctitle, 1280, 720); c[i]->Divide(2, 2); } // Histograms TH1D* h[15][3]; // WW 0, tt 1, DY 2 char hname[50], htitle[15][100]; Int_t bins[15] = { 50, 50, 50, 50, 50, 50, 7, 50, 50, 50, 50, 50, 50, 50, 4}; Double_t xmin[15] = { 0, 0, 0, 0, 0, 0, -0.5, 0, 0, 0, 0, 0, 0, 0, -0.5}; Double_t xmax[15] = {200, 200, 150, 200, 3.5, 3.5, 6.5, 500, 500, 200, 3.5, 120, 120, 120, 3.5}; for (Int_t j = 0; j < 3; j++) { for (Int_t k = 0; k < 15; k++) { if (j == 0) sprintf(hname, "h%i WW", k); else if (j == 1) sprintf(hname, "h%i tt", k); else if (j == 2) sprintf(hname, "h%i DY", k); if ((k == 0) || (k == 1)) sprintf(htitle[k], "pT lepton %i", k + 1); if (k == 2) sprintf(htitle[k], "qT"); if (k == 3) sprintf(htitle[k], "MET"); if (k == 4) sprintf(htitle[k], "d phi"); if (k == 5) sprintf(htitle[k], "d phi dilep MET"); if (k == 6) sprintf(htitle[k], "jet pT"); if (k == 7) sprintf(htitle[k], "HT"); if (k == 8) sprintf(htitle[k], "dilepton mass"); if (k == 9) sprintf(htitle[k], "pT extra lepton"); if (k == 10) sprintf(htitle[k], "dilep-jet angle"); if (k == 11) sprintf(htitle[k], "proj MET e pair"); if (k == 12) sprintf(htitle[k], "proj MET mu pair"); if (k == 13) sprintf(htitle[k], "proj MET e/mu pair"); if (k == 14) sprintf(htitle[k], "b-tagged jets"); h[k][j] = new TH1D(hname, htitle[k], bins[k], xmin[k], xmax[k]); } } // Read in file and store in array Float_t data[LENGTH][VARS + 1]; ifstream ifs(in_file.c_str()); string line; for (Int_t i = 0; i < LENGTH; i++) { getline(ifs, line); istringstream iss(line); for (Int_t j = 0; j < VARS + 1; j++) iss >> data[i][j]; } ifs.close(); /* ifs.open(in_file2.c_str()); string line; for (Int_t i = 20000; i < LENGTH; i++) { getline(ifs, line); istringstream iss(line); for (Int_t j = 0; j < VARS + 1; j++) iss >> data[i][j]; } ifs.close(); */ Int_t type; for (Int_t i = 0; i < LENGTH; i++) { type = data[i][0] - 1; for (Int_t j = 1; j < 8; j++) h[j - 1][type]->Fill(data[i][j]); h[7][type]->Fill(data[i][14]); h[8][type]->Fill(data[i][16]); h[9][type]->Fill(data[i][18]); h[10][type]->Fill(data[i][19]); if (data[i][15] == -2) h[11][type]->Fill(data[i][20]); else if (data[i][15] == -1) h[12][type]->Fill(data[i][20]); else if (data[i][15] == 1) h[13][type]->Fill(data[i][20]); h[14][type]->Fill(data[i][21]); } Int_t a, b; for (Int_t k = 0; k < 15; k++) { a = k / 4; b = k % 4 + 1; c[a]->cd(b); h[k][1]->SetLineColor(kRed); h[k][2]->SetLineColor(kGreen); if (h[k][1]->GetBinContent(h[k][1]->GetMaximumBin()) > h[k][0]->GetBinContent(h[k][0]->GetMaximumBin())) { h[k][1]->Draw(); h[k][0]->Draw("SAME"); } else { h[k][0]->Draw(); h[k][1]->Draw("SAME"); } h[k][2]->Draw("SAME"); } }
/** Send the actual command to the radio. The data is passed to us in a list of strings. We go through each string, add all the hex numbers into a long string and total their values to use in the checksum. (We use them in a string because it's easier to enter them into maps and other info as humans and it lets us easily print them out for reference, as well as defining one standard way to store them.) @param inlist list of different hex strings to send to the radio */ void HDCommands::sendcommand(list<string> inlist) {//private int msgout = 0, msglen = 0; char byte; char hbyte [10]; int dec, count = 0, csum = 0; string cmd = "", ref = "", line; list<int> iout; list<string>::iterator x; for (x = inlist.begin(); x != inlist.end(); ++x) { line = *x; istringstream iss(line); do { dec = -1; iss >> hex >> dec; if (dec < 0) { break; } count++; csum += dec; } while (dec >= 0); ref += " "; ref += line; } csum += count; msglen = count + 3; sprintf(hbyte, "0x%2X", count); if (hbyte[2] == ' ') hbyte[2] = '0'; line = ref; // ref = hdconstants["begincommand"]; ref = hdvals->getconstant("begincommand"); istringstream istr(ref); istr >> hex >> dec; csum += dec; csum = csum % 256; ref += " "; ref += hbyte; ref += line; sprintf(hbyte, "0x%2X", csum); if (hbyte[2] == ' ') hbyte[2] = '0'; ref += " "; ref += hbyte; istringstream iscmd(ref); do { dec = - 1; iscmd >> hex >> dec; if (dec < 0) break; // cout << "\tConverting to byte: " << dec << endl; byte = dec; if (dec == 0x1B || (dec == 0xA4 && (msgout > 1 && msgout < msglen - 1))) { // cout << "Sending escape byte.\n"; ioport->hdsendbyte(0x1B); if (dec == 0xA4) { dec = 0x48; byte = dec; // cout << "Changing value to: " << dec << endl; } } ioport->hdsendbyte(byte); msgout++; } while (dec >= 0);; // cout << "Command sent\n"; if (verbose) cout << "\tCommand bytes: " << ref << ", Length: " << msglen << endl; return; }
bool ImporterOBJ::FillMeshData() { int i,j,k,l,objectListSize; int startline = 0; int endline = 0; int count = 0; bool result; Vector4D tempVertex; Vector3D tempNormal; TexCoord tempTex; FaceData tempFace; std::string line,input,input2; int lineSize; int vertexIndex, normalIndex, texCoordIndex, faceIndex; int vertexCount, normalCount, texCoordCount, faceCount; vertexIndex = normalIndex = texCoordIndex = faceIndex = 0; objectListSize = objectDataList.size(); //Fill the arrays with mesh data for(i = 0; i < objectListSize; ++i) { startline = objectLineStart[i]; endline = objectLineStart[i + 1] - 1; vertexCount = 0; normalCount = 0; texCoordCount = 0; for(j = startline; j < endline; ++j) { line = fileLines[j]; lineSize = line.size(); std::istringstream iss(line.c_str()); while(iss >> input) { if(input == "v") { iss >> tempVertex.m_x; iss >> tempVertex.m_y; iss >> tempVertex.m_z; vertexList.push_back(tempVertex); vertexCount++; vertexIndex++; } if(input == "vt") { iss >> tempTex.u; iss >> tempTex.v; texCoordList.push_back(tempTex); texCoordCount++; texCoordIndex++; } if(input == "vn") { iss >> tempNormal.m_x; iss >> tempNormal.m_y; iss >> tempNormal.m_z; normalList.push_back(tempNormal); normalCount++; normalIndex++; } if(input == "f") { tempFace; for(k = 0; k < 3; ++k) { iss >> input2; int length = input2.size(); for(l = 0; l < length ; ++l) { char test = input2[l]; if(test == '/') input2[l] = ' '; } std::istringstream iss2(input2); iss2 >> tempFace.indices[k][0]; iss2 >> tempFace.indices[k][1]; iss2 >> tempFace.indices[k][2]; } objectDataList[i].faceList.push_back(tempFace); faceIndex++; }
void update(int value) { handleKeyboard(); camera.mouseMove(); if (rotateEnabled) camera.rotateView(0.001); switch (state) { case pause: lastState = pause; break; case algorithm: lastState = algorithm; for (int i = 0; i < numberOfSteps; i++) { algoEngine.step(atomTable, numberOfAtoms); } //pliku << algoEngine.steps << " " << (double) (algoEngine.currentEnergy / elementaryCharge / numberOfAtoms) << std::endl; resetAtomsVelocities(atomTable, numberOfAtoms); break; case physics: lastState = physics; for (int i = 0; i < numberOfSteps; i++) { physxEngine.step(atomTable, numberOfAtoms); } break; case reset: generateAtoms(atomTable, numberOfAtoms, diameter, atomMass); //generateAtomsInCube(atomTable, numberOfAtoms, 2.5e-10, atomMass, // rows, columns); algoEngine.currentEnergy = algoEngine.configurationEnergy(atomTable, numberOfAtoms); algoEngine.steps = 0; algoEngine.lastChangeStep = 0; algoEngine.temp = 750; physxEngine.resetTime(); state = pause; break; case a2: numberOfAtoms = 2; atomTable = new Atom[numberOfAtoms]; rows = 2; columns = 1; state = reset; break; case a5: numberOfAtoms = 5; atomTable = new Atom[numberOfAtoms]; rows = 3; columns = 2; state = reset; break; case a10: numberOfAtoms = 10; atomTable = new Atom[numberOfAtoms]; rows = 4; columns = 3; state = reset; break; case a15: numberOfAtoms = 15; atomTable = new Atom[numberOfAtoms]; rows = 4; columns = 4; state = reset; break; case a20: numberOfAtoms = 20; atomTable = new Atom[numberOfAtoms]; rows = 5; columns = 4; state = reset; break; case a50: numberOfAtoms = 50; atomTable = new Atom[numberOfAtoms]; rows = 8; columns = 7; state = reset; break; case a100: numberOfAtoms = 100; atomTable = new Atom[numberOfAtoms]; rows = 10; columns = 10; state = reset; break; case s1: numberOfSteps = 1; state = lastState; break; case s5: numberOfSteps = 5; state = lastState; break; case s10: numberOfSteps = 10; state = lastState; break; case s30: numberOfSteps = 30; state = lastState; break; case s50: numberOfSteps = 50; state = lastState; break; case s100: numberOfSteps = 100; state = lastState; break; case s1000: numberOfSteps = 1000; state = lastState; break; case axes: axesEnabled = axesEnabled ? false : true; state = lastState; break; case rotate: rotateEnabled = rotateEnabled ? false : true; state = lastState; break; case read: { std::ifstream reader; reader.open(readFile.c_str()); int ratoms, rsteps, rlastchange; long double renergy; std::string line; std::getline(reader, line); ratoms = atoi(line.substr(2, 3).c_str()); std::getline(reader, line); rsteps = atoi(line.substr(2, 10).c_str()); std::getline(reader, line); rlastchange = atoi(line.substr(2, 10).c_str()); std::getline(reader, line); renergy = atof(line.substr(2, 10).c_str()); algoEngine.steps = rsteps; algoEngine.lastChangeStep = rlastchange; algoEngine.currentEnergy = renergy * elementaryCharge; numberOfAtoms = ratoms; atomTable = new Atom[numberOfAtoms]; //TODO :zmienic Atom atom; Vector position; int i = 0; long double x, y, z; while (std::getline(reader, line)) { std::istringstream iss(line); iss >> x; iss >> y; iss >> z; position = Vector(x, y, z); atom = Atom(atomMass, position, Vector(0., 0., 0.)); atomTable[i] = atom; i++; } reader.close(); } state = pause; break; case rr: readFile = "random.txt"; state = read; break; case r5: readFile = "5.txt"; state = read; break; case r10: readFile = "10.txt"; state = read; break; case r15: readFile = "15.txt"; state = read; break; case r20: readFile = "20.txt"; state = read; break; case r2d: readFile = "2d.txt"; state = read; break; case save: std::ofstream plik; std::ostringstream name, comment; int licznika = 0; double suum = 0; for (int f=0; f < numberOfAtoms; f++) for (int k=0; k < numberOfAtoms; k++){ double odleglosc = atomTable[f].position().distanceFromVector(atomTable[k].position()); if (odleglosc > 2e-10 && odleglosc < 3e-10){ std::cout << odleglosc << std::endl; licznika++; suum += odleglosc; } } std::cout << "liczba sasiadow: "<< licznika << " suma: " << suum << " srednia: " << suum/licznika << std::endl; name << numberOfAtoms << "-" << algoEngine.steps << ".txt"; comment << "# " << numberOfAtoms << " atoms" << std::endl << "# " << algoEngine.steps << " steps" << std::endl << "# " << algoEngine.lastChangeStep << " last change step" << std::endl << "# " << (double) algoEngine.currentEnergy / elementaryCharge << " eV" << std::endl; plik.open(name.str().c_str()); plik << comment.str(); for (int i = 0; i < numberOfAtoms; i++) plik << atomTable[i].position() << std::endl; plik.close(); state = pause; break; } //if ((algoEngine.steps - algoEngine.lastChangeStep) > 20000) // state = pause; //std::cout << atomTable[0].position() << "\t\t" << atomTable[1].position() // << std::endl; glutPostRedisplay(); glutTimerFunc(1, update, 0); }
TEST( serialise, guess_xml ) { std::istringstream iss( xml ); ASSERT_NO_THROW( test_interface( iss ) ); }
unsigned int CppCheck::processFile(const std::string& filename) { exitcode = 0; // only show debug warnings for accepted C/C++ source files if (!Path::acceptFile(filename)) _settings.debugwarnings = false; if (_settings.terminated()) return exitcode; if (_settings._errorsOnly == false) { std::string fixedpath = Path::simplifyPath(filename.c_str()); fixedpath = Path::toNativeSeparators(fixedpath); _errorLogger.reportOut(std::string("Checking ") + fixedpath + std::string("...")); } try { Preprocessor preprocessor(&_settings, this); std::list<std::string> configurations; std::string filedata = ""; if (!_fileContent.empty()) { // File content was given as a string std::istringstream iss(_fileContent); preprocessor.preprocess(iss, filedata, configurations, filename, _settings._includePaths); } else { // Only file name was given, read the content from file std::ifstream fin(filename.c_str()); Timer t("Preprocessor::preprocess", _settings._showtime, &S_timerResults); preprocessor.preprocess(fin, filedata, configurations, filename, _settings._includePaths); } if (_settings.checkConfiguration) { return 0; } if (!_settings.userDefines.empty()) { configurations.clear(); configurations.push_back(_settings.userDefines); } if (!_settings._force && configurations.size() > _settings._maxConfigs) { const std::string fixedpath = Path::toNativeSeparators(filename); ErrorLogger::ErrorMessage::FileLocation location; location.setfile(fixedpath); const std::list<ErrorLogger::ErrorMessage::FileLocation> loclist(1, location); std::ostringstream msg; msg << "Too many #ifdef configurations - cppcheck will only check " << _settings._maxConfigs << " of " << configurations.size() << ".\n" "The checking of the file will be interrupted because there are too many " "#ifdef configurations. Checking of all #ifdef configurations can be forced " "by --force command line option or from GUI preferences. However that may " "increase the checking time."; ErrorLogger::ErrorMessage errmsg(loclist, Severity::information, msg.str(), "toomanyconfigs", false); reportErr(errmsg); } unsigned int checkCount = 0; for (std::list<std::string>::const_iterator it = configurations.begin(); it != configurations.end(); ++it) { // Check only a few configurations (default 12), after that bail out, unless --force // was used. if (!_settings._force && checkCount >= _settings._maxConfigs) { const std::string fixedpath = Path::toNativeSeparators(filename); ErrorLogger::ErrorMessage::FileLocation location; location.setfile(fixedpath); std::list<ErrorLogger::ErrorMessage::FileLocation> loclist; loclist.push_back(location); ErrorLogger::ErrorMessage errmsg(loclist, Severity::information, "Interrupted checking because of too many #ifdef configurations.", "toomanyconfigs", false); reportInfo(errmsg); break; } cfg = *it; // If only errors are printed, print filename after the check if (_settings._errorsOnly == false && it != configurations.begin()) { std::string fixedpath = Path::simplifyPath(filename.c_str()); fixedpath = Path::toNativeSeparators(fixedpath); _errorLogger.reportOut(std::string("Checking ") + fixedpath + ": " + cfg + std::string("...")); } Timer t("Preprocessor::getcode", _settings._showtime, &S_timerResults); const std::string codeWithoutCfg = preprocessor.getcode(filedata, *it, filename, _settings.userDefines.empty()); t.Stop(); const std::string &appendCode = _settings.append(); if (_settings.debugFalsePositive) { if (findError(codeWithoutCfg + appendCode, filename.c_str())) { return exitcode; } } else { checkFile(codeWithoutCfg + appendCode, filename.c_str()); } ++checkCount; } } catch (const std::runtime_error &e) { // Exception was thrown when checking this file.. const std::string fixedpath = Path::toNativeSeparators(filename); _errorLogger.reportOut("Bailing out from checking " + fixedpath + ": " + e.what()); } if (!_settings._errorsOnly) reportUnmatchedSuppressions(_settings.nomsg.getUnmatchedLocalSuppressions(filename)); _errorList.clear(); return exitcode; }
TEST( serialise, guess_path_value ) { std::istringstream iss( path_value ); ASSERT_NO_THROW( test_interface( iss ) ); }
virtual std::string identify(const std::string& filename, const std::string& head) const { istringstream iss(head); return std::string((type(iss) != Type_Unknown)?getType():""); }
TEST( serialise, guess_path_value_root ) { std::istringstream iss( path_value_root ); ASSERT_NO_THROW( test_interface( iss, "root/item" ) ); }
int main(int argc, char** argv) { if (argc < 3) { std::cerr << "Provide a filename of an image and a threshold value ([0, 255])" << std::endl; return 1; } cv::Mat image = cv::imread(argv[1], CV_LOAD_IMAGE_GRAYSCALE); int threshold; std::istringstream iss(argv[2]); iss >> threshold; if (threshold < 0 || threshold > 255) { std::cerr << "Threshold value must be between 0 and 255, inclusive" << std::endl; return 1; } cv::imshow("Grayscale image", image); cv::waitKey(0); cv::Mat binary(image.rows, image.cols, CV_8UC1); cv::threshold(image, binary, threshold, 255, cv::THRESH_BINARY); cv::imshow("Binary image", binary); cv::waitKey(0); // Convert the binary image to a 32-bit integer image so it can contain // a potentially large number of labels binary.convertTo(binary, CV_32S); std::vector<cvx::connected_component> components; auto extraction_flags = cvx::feature_flag::area | cvx::feature_flag::centroid | cvx::feature_flag::bounding_box | cvx::feature_flag::points; try { auto start = hires_clock::now(); auto first = binary.begin<int>(); auto last = binary.end<int>(); auto ccs = cvx::label_connected_components(first, last, std::back_inserter(components), binary.cols, binary.rows, 8, 0, 255, extraction_flags); auto end = hires_clock::now(); auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count(); std::cout << "Found " << ccs << " connected components in " << duration << " ms" << std::endl; // Display some statistics std::cout << "Area Centroid Extent Bounding box Solid?\n"; for (auto& cc : components) { std::cout << cc.area() << " " << cc.centroid() << " " << cc.extent() << " " << cc.bounding_box() << " " << cc.solid() << std::endl; } // Display all visual features of the connected components cvx::display_connected_components(first, last, binary.cols, binary.rows, components.cbegin(), components.cend(), cvx::feature_flag::all, "Components and extracted features"); cvx::wait_for_key(); } catch (cvx::exception& ex) { std::cerr << "Error: " << ex.what() << std::endl; return 1; } return 0; }
TEST( serialise, guess_corrupted_json ) { std::istringstream iss( "{ \"name\": \"dummy\", }" ); config c; ASSERT_THROW( comma::read< config >( c, iss ), comma::exception ); }
size_t TextBox::textAsNum() const { std::istringstream iss(_text); int n; iss >> n; return n; }
void Mouse_SDL::SetHome(const char * pcHome) { istringstream iss(pcHome); iss >> s_xHome >> s_yHome; }