Beispiel #1
0
void FeatureMap :: save_to_file( string filename ) const{
    ofstream output_file( filename.c_str() );
    output_file << _items.size() << endl;
    for( size_t i = 0; i < _items.size(); i++ ){
        FeatureMapItem item = _items[i];
        output_file <<  item.ctr.first  << " " << item.ctr.second
                    <<  "\t" 
                    <<  shape_to_name(item.shape)
                    <<  "\t"
                    <<  item.size.first << " " << item.size.second
                    <<  "\t";
        output_file << item.feature.size() << " ";
        for( size_t j = 0; j < item.feature.size(); j++ ){
            output_file << item.feature[j] << " ";
        }
        output_file << "\t";
        output_file << item.label;
        output_file <<  endl;
    }
    output_file.close();
}
Beispiel #2
0
int main(int argc, char **argv) {
	int size;
	configure(argc, argv);
	open_files();
	print_conf();
	size = read(sfd, asm_buf, LINE_MAX*COL_MAX);
	if (size<0) { exit(1); }
	size = expand_mnemonic(ex_mne_buf, asm_buf);
	if (size<0) { exit(1); }
	if (output_type == OFMT_EX_MNE) {
		mywrite(ex_mne_buf, size);
	} else {
		size = assemble(binary_data, ex_mne_buf);
		if (size<0) { exit(1); }
		output_file((char*)binary_data, size*4);
	}
	if (lst_flag>0) {
		asm_listing(lfd, binary_data, ex_mne_buf);
	}
	exit(0);
}
Beispiel #3
0
int wxbencode_test::OnRun()
{

	wxFileInputStream input_file(wxT("original.torrent"));
	wxFileOutputStream output_file(wxT("test_binary.torrent"));
	wxDataInputStream input_data(input_file);
	wxDataOutputStream output_data(output_file);
	wxTextOutputStream output_text(output_file);

	wxLogMessage(wxT("decoding torrent file"));
	wx_bdecode(input_file, input_data, e, 0);
	wxLogMessage(wxT("done decoding"));

	//wx_entry_print(e,0);

	wxLogMessage(wxT("encoding torrent file"));
	wx_bencode(output_data, output_text, e);
	wxLogMessage(wxT("done encoding"));

	return 0;
}
Beispiel #4
0
void TestCases::testWriteAllArraysValues()
{
    std::cout << "\n-----------------------------\n";
    std::cout << "TESTING WRITE ALL ARRAY VALUES";
    BaseSerializedObj* obj = new BaseSerializedObj(32);
    bench->start();

    obj->writeUInt32Array(t32, t32Size);
    obj->writeInt64Array(t33, t33Size);
    obj->writeFloatArray(t34, t34Size);
    obj->writeDoubleArray(t35, t35Size);

    bench->stop();
    std::cout << "\n WRITE time taken : ";
    bench->getAll();
    std::ofstream output_file("data.tx", std::ios::binary);
    output_file.write(obj->getBytes(), obj->getSize());
    output_file.close();
    obj->~BaseSerializedObj();
    std::cout << "\n\n";
}
Beispiel #5
0
	void FileHelp::copy_file(const std::string &from, const std::string &to, bool copy_always)
	{
#ifdef WIN32
		BOOL result = CopyFile(StringHelp::utf8_to_ucs2(from).c_str(), StringHelp::utf8_to_ucs2(to).c_str(), copy_always ? FALSE : TRUE);
		if (result == FALSE)
			throw Exception("Unable to copy file");
#else
		while (!copy_always)
		{
			try
			{
				File input_file(to);
			}
			catch (const Exception&)
			{
				break;
			}

			throw Exception("Destination file already exists");
		}

		File input_file(from);
		File output_file(to, File::create_always, File::access_read_write);
		char buffer[16*1024];
		while (true)
		{
			int bytes_read = input_file.read(buffer, 16*1024);
			if (bytes_read <= 0)
				break;

			int bytes_written = output_file.write(buffer, bytes_read);
			if (bytes_written != bytes_read)
			{
				output_file.close();
				FileHelp::delete_file(to);
				throw Exception("Unable to copy file");
			}
		}
#endif
	}
Beispiel #6
0
Datei: tsar.c Projekt: ntvis/tsar
void
running_cron()
{
    int    have_collect = 0;
    /* output interface */
    if (strstr(conf.output_interface, "file")) {
        /* output data */
        collect_record();
        output_file();
        have_collect = 1;
    }

    if (strstr(conf.output_interface, "db")) {
        output_db(have_collect);
    }
    if (strstr(conf.output_interface, "nagios")) {
        output_nagios();
    }
    if (strstr(conf.output_interface, "tcp")) {
        output_multi_tcp(have_collect);
    }
}
Beispiel #7
0
int main( int argc, char* argv[] )
{
    std::ifstream input_file	( SOURCE_DIR "/tests/data/001/input.txt" );
    std::ofstream output_file	( SOURCE_DIR "/tests/data/001/output.txt");

    std::string line;
    std::getline( input_file, line );

    optimize_string(line);

    std::string test_line;
    while ( ! input_file.eof() ) {
        std::getline( input_file, test_line );
        if ( ! test_line.empty() ) {	  
            optimize_string(test_line);
            std::string::const_reverse_iterator result = std::search( line.rbegin(), line.rend(), test_line.begin(), test_line.end() );
            output_file << ( (result != line.rend() ) ? "YES" : "NO" ) << std::endl;
        }
    }
    output_file.close();
    input_file.close();
}
void FWLiteExamplePlots(const std::string& ntuple_path, const std::string& output_filename, long long num_events=-1)
{
    // get the data
    TChain e("Events");
    e.Add(ntuple_path.c_str());

    // set aliases
    e.SetAlias("gp"       , "recoGenParticles_genParticles__SIM.obj"   ); 
    e.SetAlias("is_z"     , "gp.status()==3 && gp.pdgId()==23"         ); 
    e.SetAlias("d1"       , "gp.daughterRef(0).get()"                  ); 
    e.SetAlias("d2"       , "gp.daughterRef(1).get()"                  ); 
    e.SetAlias("is_tautau", "abs(d1.pdgId())*abs(d2.pdgId())!=(-15*15)"); 

    // book hists
    TH1F h_zmass("h_zmass", "Invariant mass of Z boson;m_{Z} (GeV)" , 60, 60, 120);
    TH1F h_d1_pt("h_d1_pt", "Z higher daughter's p_{T};p_{T} (GeV)" ,100,  0, 100);
    TH1F h_d2_pt("h_d2_pt", "Z lower daughter's p_{T};p_{T} (GeV)"  ,100,  0, 100);
     
    // num_events < -1 means run on all the events
    if (num_events < 0)
    {
        num_events = std::min(e.GetEntries(), std::numeric_limits<long long>::max());
    }

    // fill the hists
    e.Draw("gp.mass()>>h_zmass", "is_z && !is_tautau", "goff", num_events);
    e.Draw("d1.pt()>>h_d1_pt"  , "is_z && !is_tautau", "goff", num_events);
    e.Draw("d2.pt()>>h_d2_pt"  , "is_z && !is_tautau", "goff", num_events);

    // output
    TFile output_file(output_filename.c_str(), "RECREATE");
    h_zmass.Write();
    h_d1_pt.Write();
    h_d2_pt.Write();
    output_file.Close();

    // done
    return;
}
Beispiel #9
0
void ModelObject::save_obj()
{
    std::ofstream output_file ("output.obj", std::ios::out | std::ios::trunc);

    // std::cout.precision(9);

    output_file << std::fixed;

    if (output_file.is_open())
    {
        output_file << "o output\n";

        for (unsigned int i = 0; i < object->vertices.size(); i++)
        {
            output_file << "v" << " ";
            output_file << object->vertices[i]->x << " ";
            output_file << object->vertices[i]->y << " ";
            output_file << object->vertices[i]->z << "\n";
        }

        for (unsigned int i = 0; i < object->faces.size(); i++)
        {
            output_file << "f" << " ";

            for (unsigned int h = 0; h < object->faces[i]->coords.size(); h++)
            {
                output_file << object->faces[i]->coords[h]->id << " ";

                // if (h < object->faces[i]->coords.size() - 1)
                //     output_file << " ";
            }

            output_file << "\n";
        }

        output_file.close();
    }
}
bool ROSRuntimeUtils::store_tf_broadcasters(std::string &package_path, std::string &file_name)
{
  std::string filepath = package_path+file_name;
  std::ofstream output_file(filepath.c_str(), std::ios::out);// | std::ios::app);
  if (output_file.is_open())
  {
    ROS_INFO_STREAM("Storing results in: "<<filepath);
  }
  else
  {
    ROS_ERROR_STREAM("Unable to open file");
    return false;
  }
  output_file << "<launch>";
  //have calibrated transforms
  double roll, pitch, yaw, x_position, y_position, z_position;
  tf::Vector3 origin;
  tf::Matrix3x3 orientation;
  for (int i=0; i<calibrated_transforms_.size(); i++)
  {
    origin = calibrated_transforms_.at(i).getOrigin();
    x_position=origin.getX();
    y_position=origin.getY();
    z_position=origin.getZ();
    orientation = calibrated_transforms_.at(i).getBasis();
    orientation.getEulerYPR(yaw, pitch, roll);
    output_file<<"\n";
    output_file<<" <node pkg=\"tf\" type=\"static_transform_publisher\" name=\"world_to_camera"<<i<<"\" args=\"";
    //tranform publisher launch files requires x y z yaw pitch roll
    output_file<<x_position<< ' '<<y_position<< ' '<<z_position<< ' '<<yaw<< ' '<<pitch<< ' '<<roll ;
    output_file<<" "<<world_frame_;
    output_file<<" "<<camera_intermediate_frame_[i];
    output_file<<" 100\" />";
  }
  output_file<<"\n";
  output_file << "</launch>";
  return true;
}
Beispiel #11
0
int main(int argc, char* argv[]) {    

    std::ifstream input_file(BINARY_DIR "/input.txt");
    std::ofstream output_file(BINARY_DIR "/output.txt");
    IslandsMap map;
    map.readFromFile(input_file);
    unsigned int iselands_count = 0;
    std::stack<Point> stack;

    for (int y = 0; y < map.dimy(); y++) {
      for (int x = 0; x < map.dimx(); x++) {
        if (map.isLand(x, y) && !map.isMarked(x, y)) {
          std::cout << "Found an island (" << x << ", " << y << std::endl;
          stack.push(Point(x, y));
          iselands_count++;
          while (!stack.empty()) {
            Point current_point = stack.top();
            stack.pop();
            map.markLand(current_point.x, current_point.y);
            std::cout << "Marked island (" << current_point.x << ", " << current_point.y << std::endl;
            std::list<Point> neighbors = map.landsNearby(current_point.x, current_point.y);
            for(std::list<Point>::iterator iterator = neighbors.begin(); iterator != neighbors.end(); ++iterator) {
              Point neighbor = *iterator;
              if (!map.isMarked(neighbor.x, neighbor.y)) {
                std::cout << "Neigbor added (" << neighbor.x << ", " << neighbor.y << std::endl;
                stack.push(neighbor);
              }
            }
          }
        }
      }
    }

    output_file << iselands_count << std::endl;
    input_file.close();
    output_file.close();
}
Beispiel #12
0
void Binairo::SauvegarderText(const string & nomFichier)
{
	/*Le programme doit écrire la solution à l’écran ainsi que dans un fichier qui sera
	  nommé « Solution - <nom original du fichier> »; faites en sorte que l’affichage soit
	  intéressant et facile à lire – le modèle ci - haut en est un exemple;*/

	ofstream output_file("Solution - " + nomFichier);
	if (output_file.is_open())
	{
		for (int i = 0; i < binairoGrille.GetNbLignes(); i++)
		{
			for (int j = 0; j < binairoGrille.GetNbColonnes(); j++)
			{
				output_file << binairoGrille[i][j];
			}
			output_file << endl;
		}
		cout << endl << "Les donnees du reseau sauvegardes avec succes dans le fichier: Solution - " + nomFichier << ".txt" << endl;
	}
	else //file could not be opened
	{
		cout << "Le fichier ne peut être ouvert." << endl;
	}
}
Beispiel #13
0
int main()
{
    std::ifstream input_file	( SOURCE_DIR "/tests/data/003/input.txt" );
    std::ofstream output_file	( SOURCE_DIR "/tests/data/003/output.txt");


    IslandMap vect;
    int strCount=0;
    std::string str;

    while ( !input_file.eof() ) {
        std::getline(input_file, str);
        if ( !str.empty() ) {
            std::vector<bool> tmp(str.size(), false);
            for (size_t i=0; i<str.size(); i++){
                if (str.at(i) == 'o') {
                    tmp[i] = true;
                }
            }
            vect.push_back(tmp);
            strCount++;
        }
    }
    int islandCount = 0;
    for (int i=0;i<strCount; i++) {
        for (size_t j=0; j<vect[i].size();j++) {
            islandCount += mark_island(vect, i, j);
        }
    }

    output_file << islandCount;

    input_file.close();
    output_file.close();

}
Beispiel #14
0
int main()
{
  std::cerr << "Modify the w-a-r-n-i-n-g-s handler...\n";
  CGAL::set_warning_handler(special_warnings);
  std::string testfile_prefix("data/validation/test");
  std::string testfile_suffix(".dat");
  const char* output_filename("data/validation/validation_test_output.txt");
  std::ofstream output_file (output_filename);
  if (! output_file.is_open()) {
    std::cerr << "Failed to open the " << output_filename <<std::endl;
    return (1);
  }

  int result = 0;
  for (size_t i = 1; i < 11; ++i) {
    std::stringstream strs;
    std::string si;
    strs << i;
    strs >> si;
    std::string filename = testfile_prefix + si + testfile_suffix;
    bool res =  test(filename, output_file);
    if (!res) {
      std::cout << "test " << i << " failed" << std::endl;
      result = 1;
    }
    else {
      std::cout <<"test " << i << " succeeded" << std::endl;
    }
  }
  if (result != 0) {
    std::cout << "SOME TESTS FAILED" << std::endl;
    return 1;
  }
  std::cout << "ALL TESTS SUCCEEDED!" << std::endl;
  return 0;
}
Beispiel #15
0
int CppUnitTestRunner::Run(std::vector<CPPUNIT_NS::Test *>& tests)
{
    CPPUNIT_NS::TestRunner					runner;
    CPPUNIT_NS::TestResult					controller;
    CPPUNIT_NS::TestResultCollector			result;
    CPPUNIT_NS::BriefTestProgressListener	progress;
    CPPUNIT_NS::CompilerOutputter			outputter( &result, std::cerr );
    std::string								xmlFileName   = (s_XmlPath=="" ? "" : s_XmlPath + "\\") + m_TestSuiteName + ".xml";
    std::ofstream							output_file( xmlFileName.c_str() , std::ios::out );
    CPPUNIT_NS::XmlOutputter                 xmloutputter( &result, output_file );

    controller.addListener( &result );        
    controller.addListener( &progress );      

    for each (CPPUNIT_NS::Test * test in tests)
        runner.addTest(test);

    runner.run( controller );

    outputter.write();
    xmloutputter.write();

    return result.wasSuccessful() ? EXIT_SUCCESS : EXIT_FAILURE;
}
Beispiel #16
0
int plot_omg(){
    TFile* output_histo = new TFile("output_histo.root", "recreate");
    double mV0 = 1.67245;
    ifstream fList_sig("./total_omg_sig.list");
    ifstream fList_bg("./total_omg_bg.list");
    ofstream output_file("./output_omg");

    float pt_bin[7] = {0.8, 1.2, 1.6, 2.0, 2.4, 2.8, 3.6}; 
    int cent_bin[3] = {66, 97, 198}; 
    char linefromlist[250];
    int no_centbin = 4;
    int no_ptbin = 6;
    //int nEvents[4] = {2970564, 3340670, 2136072, 10037274};

//===========Initialize Total Invariant Mass Histogram==============================
    TH1F* hist_total_sig = new TH1F("hist_total_sig", "hist_total_sig", 100, mV0 - 0.07, mV0 + 0.07);
    TH1F* hist_total_bg = new TH1F("hist_total_bg", "hist_total_bg", 100, mV0 - 0.07, mV0 + 0.07);
//===========Initialize TObjArray to Store Histograms=============================
    TObjArray HList(0);
    
    for(int i = 0; i < no_centbin; i++){
	for(int j = 0; j < no_ptbin; j++){
	    char hist_name_sig[100];
	    char hist_des_sig[100];
	    char hist_name_bg[100];
	    char hist_des_bg[100];

	    sprintf(hist_name_sig, "sig_omgpt%dcent%d", j+1, i+1);
	    sprintf(hist_des_sig, "sig_omg(%.1f< pt<%.1f)cent%d", pt_bin[j], pt_bin[j+1], i+1);
	    sprintf(hist_name_bg, "bg_omgpt%dcent%d", j+1, i+1);
	    sprintf(hist_des_bg, "bg_omg(%.1f<pt<%.1f)cent%d", pt_bin[j], pt_bin[j+1], i+1);

	    TH1F* new_histo_sig = new TH1F(hist_name_sig, hist_des_sig, 100, mV0 - 0.07, mV0 + 0.07);
            new_histo_sig -> Sumw2();
	    TH1F* new_histo_bg = new TH1F(hist_name_bg, hist_des_bg, 100, mV0 - 0.07, mV0 + 0.07);
            new_histo_bg -> Sumw2();

	    HList.Add(new_histo_sig);
	    HList.Add(new_histo_bg);
	}
    }

//===========Input files listed in filelist===================
//===========QA Plots========================================
/*
    TH1F* hNRefMult  = new TH1F("RefMult", "Reference Multiplicity", 1000, 0.0, 1000.0 ) ;
    TH1F* hSelectedMult  = new TH1F("SelectedRefMult", "Selected Reference Multiplicity", 1000, 0.0, 1000.0 ) ;
    TH1F* hVz_before = new TH1F("vz_before", "vz_before_cut", 400, -100, 100);
    TH1F* hVz_after = new TH1F("vz_after", "vz_after_cut", 400, -100, 100);
    TH2F* hVr_before = new TH2F("vr_before", "vr_before_cut", 200, -5.0, 5.0, 200, -5.0, 5.0);
    TH2F* hVr_after = new TH2F("vr_after", "vr_after_cut", 200, -5.0, 5.0, 200, -5.0, 5.0);
    TH2F* hDeDx = new TH2F("dedxP", "DeDx_P", 300, -3, 3, 300, 0, 3e-5);
*/
//===================Add up signal invariant mass histograms===============================
    int count_sig = 0;
    while(fList_sig.getline(linefromlist, 250)){
        TFile* file = new TFile(linefromlist, "read");
	count_sig++;
        if(count_sig%100==0) std::cout<< count_sig<<" files processed"<<std::endl;
        //===========Invariant Mass Histograms===================================
	for(int i = 0; i < no_centbin; i++){
	    for(int j = 0; j < no_ptbin; j++){
		char hist_name_sig[100];
		sprintf(hist_name_sig, "sig_omgpt%dcent%d", j+1, i+1);

		char cur_hist_name_sig[100];
		sprintf(cur_hist_name_sig, "sig_omgpt%dcent%d", j+1, i+1);

		TH1F* cur_histo_sig = (TH1F*)file->Get(cur_hist_name_sig);
   

                TH1F* hist_sig = (TH1F*)HList.FindObject(hist_name_sig);
                if(cur_histo_sig) hist_sig -> Add(cur_histo_sig);
                if(cur_histo_sig) hist_total_sig -> Add(cur_histo_sig);

                //std::cout<<"sofarsogood in signal part"<<std::endl;
                delete cur_histo_sig;
	    }
	}
        delete file;
    }
//======================Add up background histograms==============================
    int count_bg = 0;
    while(fList_bg.getline(linefromlist, 250)){
        TFile* file = new TFile(linefromlist, "read");
        count_bg++;
        if(count_bg%100==0) std::cout<< count_bg<<" files processed"<<std::endl;
        //===========Invariant Mass Histograms===================================
	for(int i = 0; i < 4; i++){
	    for(int j = 0; j < 5; j++){
		char hist_name_bg[100];
		sprintf(hist_name_bg, "bg_omgpt%dcent%d", j+1, i+1);

		char cur_hist_name_bg[100];
		sprintf(cur_hist_name_bg, "sig_omgpt%dcent%d", j+1, i+1);

		TH1F* cur_histo_bg = (TH1F*)file -> Get(cur_hist_name_bg);

                TH1F* hist_bg = (TH1F*)HList.FindObject(hist_name_bg);
                
                if(cur_histo_bg) hist_bg -> Add(cur_histo_bg);
                if(cur_histo_bg) hist_total_bg -> Add(cur_histo_bg);
                //std::cout<<"sofarsogood in background part"<<std::endl;
                delete cur_histo_bg;
	    }
	}
        delete file;
    }


//=============Define scale factor=====================
    int low_bin = 21;
    int high_bin = 42;
//=============Scale Background and Signal==============
//==================Plot the Sig with Bg and Bg============================
    for(int i = 0; i < 4; i++){
	for(int j = 0; j < 5; j++){
	    char hist_name_sig[100];
	    char hist_name_bg[100];
	    sprintf(hist_name_sig, "sig_omgpt%dcent%d", j+1, i+1);
	    sprintf(hist_name_bg, "bg_omgpt%dcent%d", j+1, i+1);

	    TH1F* hist_sig = (TH1F*)HList.FindObject(hist_name_sig);

	    TH1F* hist_bg = (TH1F*)HList.FindObject(hist_name_bg);
     
            //hist_sig -> Sumw2();
            //hist_bg -> Sumw2();

            TCanvas* new_canvas = new TCanvas("c1", "c1", 200, 100, 600, 400);
            new_canvas -> cd();
             
            double int_sig = hist_sig -> Integral(low_bin, high_bin); 
            double int_bg = hist_bg -> Integral(low_bin, high_bin); 

            double scale_factor = int_sig / int_bg;
            hist_bg -> Scale(scale_factor);
            hist_bg -> SetLineColor(2);
            
            hist_sig -> Draw("HIST"); 
            hist_bg -> Draw("sames HIST");

            char figure_name_1[100];
            char figure_name_2[100];
            sprintf(figure_name_1, "../../plots/omg/omgpt%dcent%d.png", j+1, i+1);
            sprintf(figure_name_2, "../../plots/omg/omgpt%dcent%d.eps", j+1, i+1);
            new_canvas -> SaveAs(figure_name_1);
            new_canvas -> SaveAs(figure_name_2);
            
            delete new_canvas;
	}
    }
//=============Plot total result =======================================================
    double int_total_sig = hist_total_sig -> Integral(low_bin, high_bin); 
    double int_total_bg = hist_total_bg -> Integral(low_bin, high_bin); 
    double scale_total_factor = int_total_sig / int_total_bg;

    TCanvas* canvas_total = new TCanvas("c1", "c1", 200, 100, 600, 400);
    hist_total_bg -> Scale(scale_total_factor);
    hist_total_bg -> SetLineColor(2);
    hist_total_sig -> Draw("HIST");
    hist_total_bg -> Draw("sames HIST");
    canvas_total -> SaveAs("../../plots/omg/total_mix.png");
    
    hist_total_sig -> Add(hist_total_bg, -1);
    hist_total_sig -> SetMarkerStyle(4);
    TCanvas* canvas_total_pure = new TCanvas("c1", "c1", 200, 100, 600, 400);
    hist_total_sig -> Draw("HIST");
    canvas_total_pure -> SaveAs("../../plots/omg/total_pure.png");


//===============Get the pure signal by subtracting the background===============
//===============Plot the Invariant Mass Figures(After Subtraction)=================================
    float sig_count[4][5] = {};
    float sig_count_cal[4][5] = {};
    for(int i = 0; i < 4; i++){
	for(int j = 0; j < 5; j++){
	    char hist_name_sig[100];
	    char hist_name_bg[100];
	    sprintf(hist_name_sig, "sig_omgpt%dcent%d", j+1, i+1);
	    sprintf(hist_name_bg, "bg_omgpt%dcent%d", j+1, i+1);

	    TH1F* hist_sig = (TH1F*)HList.FindObject(hist_name_sig);

	    TH1F* hist_bg = (TH1F*)HList.FindObject(hist_name_bg);

            //hist_sig -> Sumw2(); 
            //hist_bg -> Sumw2();

	    TCanvas* new_canvas = new TCanvas("c1", "c1", 200, 100, 600, 400);
	    new_canvas -> cd();

	    double int_sig = hist_sig -> Integral(low_bin, high_bin); 
	    double int_bg = hist_bg -> Integral(low_bin, high_bin); 

	    double scale_factor = int_sig / int_bg;
	    hist_bg -> Scale(scale_factor);
	    hist_bg -> SetLineColor(2);

	    hist_sig -> Add(hist_bg, -1);
	    hist_sig -> SetMarkerStyle(4); 
            hist_sig -> Draw("HIST");
               
            //=================Fitting Ends=====================================
            
	    char figure_name_1[100];
	    char figure_name_2[100];
	    sprintf(figure_name_1, "../../plots/omg/pure_omgpt%dcent%d.png", j+1, i+1);
	    sprintf(figure_name_2, "../../plots/omg/pure_omgpt%dcent%d.eps", j+1, i+1);
	    new_canvas -> SaveAs(figure_name_1);
	    new_canvas -> SaveAs(figure_name_2);

            //=================Some Calculation==================================
            /*
            sig_count[i][j] = sig_func -> Integral(1.660, 1.684);  
            sig_count_cal[i][j] = par[2] / 0.0014;  
            */
	    delete new_canvas;
	}
    }

    //plot_pt_spectra(hSelectedMult, sig_count);
    output_histo -> cd();
    hNRefMult -> Write();
    hSelectedMult -> Write();
    hVz_before -> Write();
    hVz_after -> Write();
    hVr_before -> Write();
    hVr_after -> Write();
    hDeDx -> Write();
    hNRefMult -> Write();
    hSelectedMult -> Write();
    HList.Write();
    output_histo -> Close();
    output_file.close();
}
Beispiel #17
0
 bool operator()(html::parser const& _parser) {
     std::string const& file_path = _parser.get_file_path();
     return output_file(chilon::string_range(file_path.begin(), file_path.end() - sizeof("meow")));
 }
Beispiel #18
0
static int recurse_dir(int srcrootlen, int dstrootlen, astring &srcdir, astring &dstdir, astring &tempheader, astring &tempfooter)
{
	static const osd_dir_entry_type typelist[] = { ENTTYPE_DIR, ENTTYPE_FILE };

	// extract a normalized subpath
	astring srcdir_subpath;
	normalized_subpath(srcdir_subpath, srcdir, srcrootlen + 1);

	// create an index file
	astring indexname;
	indexname.printf("%s%c%s", dstdir.cstr(), PATH_SEPARATOR[0], "index.html");
	core_file *indexfile = create_file_and_output_header(indexname, tempheader, srcdir_subpath);

	// output the directory navigation
	core_fprintf(indexfile, "<h3>Viewing Directory: ");
	output_path_as_links(indexfile, srcdir_subpath, true, false);
	core_fprintf(indexfile, "</h3>");

	// iterate first over directories, then over files
	int result = 0;
	for (int entindex = 0; entindex < ARRAY_LENGTH(typelist) && result == 0; entindex++)
	{
		osd_dir_entry_type entry_type = typelist[entindex];

		// open the directory and iterate through it
		osd_directory *dir = osd_opendir(srcdir);
		if (dir == NULL)
		{
			result = 1;
			break;
		}

		// build up the list of files
		const osd_directory_entry *entry;
		int found = 0;
		list_entry *list = NULL;
		while ((entry = osd_readdir(dir)) != NULL)
			if (entry->type == entry_type && entry->name[0] != '.')
			{
				list_entry *lentry = new list_entry;
				lentry->name.cpy(entry->name);
				lentry->next = list;
				list = lentry;
				found++;
			}

		// close the directory
		osd_closedir(dir);

		// skip if nothing found
		if (found == 0)
			continue;

		// allocate memory for sorting
		list_entry **listarray = new list_entry *[found];
		found = 0;
		for (list_entry *curlist = list; curlist != NULL; curlist = curlist->next)
			listarray[found++] = curlist;

		// sort the list
		qsort(listarray, found, sizeof(listarray[0]), compare_list_entries);

		// rebuild the list
		list = NULL;
		while (--found >= 0)
		{
			listarray[found]->next = list;
			list = listarray[found];
		}
		delete[] listarray;

		// iterate through each file
		for (list_entry *curlist = list; curlist != NULL && result == 0; curlist = curlist->next)
		{
			// add a header
			if (curlist == list)
				core_fprintf(indexfile, "\t<h2>%s</h2>\n\t<ul>\n", (entry_type == ENTTYPE_DIR) ? "Directories" : "Files");

			// build the source filename
			astring srcfile;
			srcfile.printf("%s%c%s", srcdir.cstr(), PATH_SEPARATOR[0], curlist->name.cstr());

			// if we have a file, output it
			astring dstfile;
			if (entry_type == ENTTYPE_FILE)
			{
				// make sure we care, first
				file_type type = FILE_TYPE_INVALID;
				for (int extnum = 0; extnum < ARRAY_LENGTH(extension_lookup); extnum++)
					if (core_filename_ends_with(curlist->name, extension_lookup[extnum].extension))
					{
						type = extension_lookup[extnum].type;
						break;
					}

				// if we got a valid file, process it
				if (type != FILE_TYPE_INVALID)
				{
					dstfile.printf("%s%c%s.html", dstdir.cstr(), PATH_SEPARATOR[0], curlist->name.cstr());
					if (indexfile != NULL)
						core_fprintf(indexfile, "\t<li><a href=\"%s.html\">%s</a></li>\n", curlist->name.cstr(), curlist->name.cstr());
					result = output_file(type, srcrootlen, dstrootlen, srcfile, dstfile, srcdir == dstdir, tempheader, tempfooter);
				}
			}

			// if we have a directory, recurse
			else
			{
				dstfile.printf("%s%c%s", dstdir.cstr(), PATH_SEPARATOR[0], curlist->name.cstr());
				if (indexfile != NULL)
					core_fprintf(indexfile, "\t<li><a href=\"%s/index.html\">%s/</a></li>\n", curlist->name.cstr(), curlist->name.cstr());
				result = recurse_dir(srcrootlen, dstrootlen, srcfile, dstfile, tempheader, tempfooter);
			}
		}

		// close the list if we found some stuff
		if (list != NULL)
			core_fprintf(indexfile, "\t</ul>\n");

		// free all the allocated entries
		while (list != NULL)
		{
			list_entry *next = list->next;
			delete list;
			list = next;
		}
	}

	if (indexfile != NULL)
		output_footer_and_close_file(indexfile, tempfooter, srcdir_subpath);
	return result;
}
Beispiel #19
0
int main(int argc, char *argv[]) {
  char train_file_name[256];
  char test_file_name[256];
  char output_file_name[256];
  char model_file_name[256];
  struct Problem *train, *test;
  struct Model *model;
  int num_correct = 0, num_empty = 0, num_multi = 0, num_incl = 0;
  double avg_conf = 0, avg_cred = 0;
  const char *error_message;

  ParseCommandLine(argc, argv, train_file_name, test_file_name, output_file_name, model_file_name);
  error_message = CheckParameter(&param);

  if (error_message != NULL) {
    std::cerr << error_message << std::endl;
    exit(EXIT_FAILURE);
  }

  train = ReadProblem(train_file_name);
  test = ReadProblem(test_file_name);

  std::ofstream output_file(output_file_name);
  if (!output_file.is_open()) {
    std::cerr << "Unable to open output file: " << output_file_name << std::endl;
    exit(EXIT_FAILURE);
  }

  std::chrono::time_point<std::chrono::steady_clock> start_time = std::chrono::high_resolution_clock::now();

  if (param.load_model == 1) {
    model = LoadModel(model_file_name);
    if (model == NULL) {
      exit(EXIT_FAILURE);
    }
  } else {
    model = TrainCP(train, &param);
  }

  if (param.save_model == 1) {
    if (SaveModel(model_file_name, model) != 0) {
      std::cerr << "Unable to save model file" << std::endl;
    }
  }

  for (int i = 0; i < test->num_ex; ++i) {
    double conf, cred;
    std::vector<int> predict_label;

    predict_label = PredictCP(train, model, test->x[i], conf, cred);

    avg_conf += conf;
    avg_cred += cred;

    output_file << std::resetiosflags(std::ios::fixed) << test->y[i] << ' ' << predict_label[0] << ' '
                << std::setiosflags(std::ios::fixed) << conf << ' ' << cred;
    if (predict_label[0] == test->y[i]) {
      ++num_correct;
    }

    if (predict_label.size() == 1) {
      ++num_empty;
      output_file << " Empty\n";
    } else {
      output_file << " set:";
      for (size_t j = 1; j < predict_label.size(); ++j) {
        output_file << ' ' << predict_label[j];
        if (predict_label[j] == test->y[i]) {
          ++num_incl;
        }
      }
      if (predict_label.size() > 2) {
        ++num_multi;
        output_file << " Multi\n";
      } else {
        output_file << " Single\n";
      }
    }
    std::vector<int>().swap(predict_label);
  }
  avg_conf /= test->num_ex;
  avg_cred /= test->num_ex;

  std::chrono::time_point<std::chrono::steady_clock> end_time = std::chrono::high_resolution_clock::now();

  std::cout << "Simple Accuracy: " << 100.0*num_correct/test->num_ex << '%'
            << " (" << num_correct << '/' << test->num_ex << ") "
            << "Mean Confidence: " << std::fixed << std::setprecision(4) << 100*avg_conf << "%, "
            << "Mean Credibility: " << 100*avg_cred << "%\n";
  std::cout << "Accuracy: " << 100.0*num_incl/test->num_ex << '%'
            << " (" << num_incl << '/' << test->num_ex << ") "
            << "Multi Prediction: " << std::fixed << std::setprecision(4) << 100.0*num_multi/test->num_ex << "%, "
            << "Empty Prediction: " << 100.0*num_empty/test->num_ex << "%\n";
  output_file.close();

  std::cout << "Time cost: " << std::chrono::duration_cast<std::chrono::milliseconds>(end_time - start_time).count()/1000.0 << " s\n";

  FreeProblem(train);
  FreeProblem(test);
  FreeModel(model);
  FreeParam(&param);

  return 0;
}
Beispiel #20
0
int
main(int argc, char *argv[])
{
	int ch, size;
	struct Options opts = {0};
	struct PNGImage png = {0};
	struct GBImage gb = {0};
	struct Tilemap tilemap = {0};
	char *ext;
	const char *errmsg = "Warning: The PNG's %s setting is not the same as the setting defined on the command line.";

	if (argc == 1) {
		usage();
	}

	opts.mapfile = "";
	opts.palfile = "";
	opts.outfile = "";

	depth = 2;

	while((ch = getopt(argc, argv, "Dd:Ffho:Tt:uPp:Vvx:")) != -1) {
		switch(ch) {
		case 'D':
			opts.debug = true;
			break;
		case 'd':
			depth = strtoul(optarg, NULL, 0);
			break;
		case 'F':
			opts.hardfix = true;
		case 'f':
			opts.fix = true;
			break;
		case 'h':
			opts.horizontal = true;
			break;
		case 'o':
			opts.outfile = optarg;
			break;
		case 'P':
			opts.palout = true;
			break;
		case 'p':
			opts.palfile = optarg;
			break;
		case 'T':
			opts.mapout = true;
			break;
		case 't':
			opts.mapfile = optarg;
			break;
		case 'u':
			opts.unique = true;
			break;
		case 'V':
			printf("rgbgfx %s\n", get_package_version_string());
			exit(0);
		case 'v':
			opts.verbose = true;
			break;
		case 'x':
			opts.trim = strtoul(optarg, NULL, 0);
			break;
		default:
			usage();
			/* NOTREACHED */
		}
	}
	argc -= optind;
	argv += optind;

	if (argc == 0) {
		usage();
	}

	opts.infile = argv[argc - 1];

	if (depth != 1 && depth != 2) {
		errx(1, "Depth option must be either 1 or 2.");
	}
	colors = 1 << depth;

	input_png_file(opts, &png);

	png.mapfile = "";
	png.palfile = "";

	get_text(&png);

	if (png.horizontal != opts.horizontal) {
		if (opts.verbose) {
			warnx(errmsg, "horizontal");
		}
		if (opts.hardfix) {
			png.horizontal = opts.horizontal;
		}
	}
	if (png.horizontal) {
		opts.horizontal = png.horizontal;
	}

	if (png.trim != opts.trim) {
		if (opts.verbose) {
			warnx(errmsg, "trim");
		}
		if (opts.hardfix) {
			png.trim = opts.trim;
		}
	}
	if (png.trim) {
		opts.trim = png.trim;
	}
	if (opts.trim > png.width / 8 - 1) {
		errx(1, "Trim (%i) for input png file '%s' too large (max: %i)", opts.trim, opts.infile, png.width / 8 - 1);
	}

	if (strcmp(png.mapfile, opts.mapfile) != 0) {
		if (opts.verbose) {
			warnx(errmsg, "tilemap file");
		}
		if (opts.hardfix) {
			png.mapfile = opts.mapfile;
		}
	}
	if (!*opts.mapfile) {
		opts.mapfile = png.mapfile;
	}

	if (png.mapout != opts.mapout) {
		if (opts.verbose) {
			warnx(errmsg, "tilemap file");
		}
		if (opts.hardfix) {
			png.mapout = opts.mapout;
		}
	}
	if (png.mapout) {
		opts.mapout = png.mapout;
	}

	if (strcmp(png.palfile, opts.palfile) != 0) {
		if (opts.verbose) {
			warnx(errmsg, "palette file");
		}
		if (opts.hardfix) {
			png.palfile = opts.palfile;
		}
	}
	if (!*opts.palfile) {
		opts.palfile = png.palfile;
	}

	if (png.palout != opts.palout) {
		if (opts.verbose) {
			warnx(errmsg, "palette file");
		}
		if (opts.hardfix) {
			png.palout = opts.palout;
		}
	}
	if (png.palout) {
		opts.palout = png.palout;
	}

	if (!*opts.mapfile && opts.mapout) {
		if ((ext = strrchr(opts.infile, '.')) != NULL) {
			size = ext - opts.infile + 9;
			opts.mapfile = malloc(size);
			strncpy(opts.mapfile, opts.infile, size);
			*strrchr(opts.mapfile, '.') = '\0';
			strcat(opts.mapfile, ".tilemap");
		} else {
			opts.mapfile = malloc(strlen(opts.infile) + 9);
			strcpy(opts.mapfile, opts.infile);
			strcat(opts.mapfile, ".tilemap");
		}
	}

	if (!*opts.palfile && opts.palout) {
		if ((ext = strrchr(opts.infile, '.')) != NULL) {
			size = ext - opts.infile + 5;
			opts.palfile = malloc(size);
			strncpy(opts.palfile, opts.infile, size);
			*strrchr(opts.palfile, '.') = '\0';
			strcat(opts.palfile, ".pal");
		} else {
			opts.palfile = malloc(strlen(opts.infile) + 5);
			strcpy(opts.palfile, opts.infile);
			strcat(opts.palfile, ".pal");
		}
	}

	gb.size = png.width * png.height * depth / 8;
	gb.data = calloc(gb.size, 1);
	gb.trim = opts.trim;
	gb.horizontal = opts.horizontal;

	if (*opts.outfile || *opts.mapfile) {
		png_to_gb(png, &gb);
		create_tilemap(opts, &gb, &tilemap);
	}

	if (*opts.outfile) {
		output_file(opts, gb);
	}

	if (*opts.mapfile) {
		output_tilemap_file(opts, tilemap);
	}

	if (*opts.palfile) {
		output_palette_file(opts, png);
	}

	if (opts.fix || opts.debug) {
		set_text(&png);
		output_png_file(opts, &png);
	}

	free_png_data(&png);
	free(gb.data);

	return 0;
}
int main (int argc, char** argv)
{

	if(argc != 4+1 )
	{
		std::cerr<<" The function :"<<argv[0]<<" should be called with the following parameters: "<< std::endl
				 <<" config_file Puddle_Height[eV] Puddle_Concentration[0-1] Puddle_Range[lat_unit]."<<std::endl;
		return 0;
	}

	//Read the name of the configuration file
	const std::string config_filename(argv[1]);
	const double puddHeight=atof(argv[2]);
	const double puddConcen=atof(argv[3]);
	const double puddRange =atof(argv[4]);


	std::ifstream config_file(config_filename.c_str());
	///Look for the line lattice_info
	std::string line;
	bool found=false;
	for (int line_num = 0; std::getline(config_file, line); ++line_num)
		if(line=="lattice_info")
		{
			found=true;
			break;
		}
	if(!found)
	{
		config_file.close();
		std::cerr<<"The config file does not posses a disorder_info section. The simulation cannot proceed"<<std::endl;
		return 0;
	}

		std::string label;
		int OrbitalNum=0;
		int SpinNum=0;
		int coord=0;
		std::vector<int> SitesInDir(3);
		std::vector < std::vector<double> > lat(3);
		for(int i=0;i<3;i++)
			lat[i]=std::vector<double>(3,0);

		config_file	>>label
					>>lat[0][0]>>lat[0][1]>>lat[0][2]
					>>lat[1][0]>>lat[1][1]>>lat[1][2]
	                >>lat[2][0]>>lat[2][1]>>lat[2][2]
	                >>SitesInDir[0]>>SitesInDir[1]>>SitesInDir[2]
				    >>OrbitalNum>>SpinNum>>coord;

		const double Delta[] = { (lat[0][0]+lat[1][0])/3. , (lat[0][1]+lat[1][1])/3. , 0 };			// THIRD LATTICE VECTOR


		std::string output_name=label+"PuddleHeight"+
								argv[2]+"eVConc"+argv[3]+
								"Range"+argv[4]+"nm.dis";

		std::ofstream output_file(output_name.c_str());


		const double epsilon=std::numeric_limits<double>::epsilon();
		if(puddHeight <= epsilon || puddConcen  <= epsilon)
		{
			output_file.close();
			return 0;
		}


		boost::random::mt19937 rng;         // produces randomness out of thin air
		boost::random::uniform_01<double> dice;
		boost::random::uniform_real_distribution<double> RandomEnergy( -1.0 , 1.0);


		///Number of orbitals in the simulation
		const int TotalOfOrbitals=SitesInDir[0]*SitesInDir[0]*SitesInDir[2]*OrbitalNum*SpinNum;

		///Stimated number of impurities
		const int  estImpNum= (1.3)*puddConcen * TotalOfOrbitals/SpinNum;//The two is to overstimate the value
		std::vector< std::vector< double > > impPosition;
		impPosition.reserve( estImpNum );
		std::cout<<"The estimated number of puddles is set as: "<<estImpNum<<std::endl;


		std::vector< double >
		this_imp_pos(3);										//a singl impurity position

		int impurity_count= 0;


		// first we go through all the possible positions
		for(int i2=0; i2 < SitesInDir[2]  ; i2++ )
			for(int i1=0; i1 < SitesInDir[1]  ; i1++ )
				for(int i0=0; i0 < SitesInDir[0] ; i0++ )
					for(int io=0; io < OrbitalNum ; io++ )
						if( dice(rng) < puddConcen )
						{
							this_imp_pos[0]=lat[0][0]*i0 + lat[1][0]*i1 + lat[2][0]*i2 + io*Delta[0];
							this_imp_pos[1]=lat[0][1]*i0 + lat[1][1]*i1 + lat[2][1]*i2 + io*Delta[1];
							this_imp_pos[1]=lat[0][2]*i0 + lat[1][2]*i1 + lat[2][2]*i2 + io*Delta[2];
							impPosition.push_back(this_imp_pos);
						}

		int counter=0;
		std::vector<double> diagElements( TotalOfOrbitals ,0 );
		//We incorporate the onsite energy of the puddles.
		for(int i2=0; i2 < SitesInDir[2]  ; i2++ )
			for(int i1=0; i1 < SitesInDir[1]  ; i1++ )
				for(int i0=0; i0 < SitesInDir[0] ; i0++ )
					for(int io=0; io < OrbitalNum ; io++ )
					{
						for(int it0=-1; it0 <= 1; it0++ )	// tile index 1
							for(int it1=-1; it1 <= 1; it1++ )	// tile index 2. This is used to take into account the periodic boundary condition
							{
								const int I0=i0+SitesInDir[0]*it0 ;
								const int I1=i1+SitesInDir[1]*it1 ;
								const double
								r[2]={
										lat[0][0]*I0+lat[1][0]*I1+io*Delta[0],
										lat[0][1]*I0+lat[1][1]*I1+io*Delta[1]
								};
								for(int  imp=0;imp< impPosition.size(); imp++)
								{
									const double
									dist = 	( r[0]-impPosition[imp][0] )*( r[0]-impPosition[imp][0] ) +
											( r[1]-impPosition[imp][1] )*( r[1]-impPosition[imp][1] );

									const double
									Ei=RandomEnergy(rng)*puddHeight*exp(-0.5*dist/puddRange/puddRange);
									//Created for periodic puddles
									if( std::abs(Ei) > epsilon )
										for(int is=0; is <SpinNum   ; is++ )
										{
											//compute the site where the energy is going to be changed
											const int
											k0= IndexesToIndex(	I0, SitesInDir[0],
																I1, SitesInDir[1],
																i2, SitesInDir[2],
																io, OrbitalNum,
																is, SpinNum);
											diagElements[k0]=diagElements[k0]+Ei;
										}
								}
							}
						++counter;
						const int checkpoint= int((double)TotalOfOrbitals/SpinNum/100);
						if(counter%checkpoint == 0 )
							std::cout<<"Setting the puddles, there are :"<<counter<<"/"<<TotalOfOrbitals/SpinNum<<" left."<<std::endl;
						}
		// std::cout<<"Setting the hamiltonian in the sparse matrix"<<std::endl;

		double mean=0;
		double stdDev=0;

		for(int k0=0;k0<diagElements.size();k0++)
			if(std::abs(diagElements[k0])>epsilon)
			{
				output_file<<k0<<" "<<diagElements[k0]<<std::endl;
				mean=mean+diagElements[k0];
				stdDev= stdDev +diagElements[k0]*diagElements[k0];
			}

		mean=mean/diagElements.size();
		stdDev=stdDev/diagElements.size();
		stdDev=sqrt(stdDev- mean*mean);

/*		for(int k0=0;k0<diagElements.size();k0++)
			if(std::abs(diagElements[k0])>epsilon)
				stdDev=stdDev+pow(mean-diagElements[k0],2.);
		stdDev=sqrt(stdDev/diagElements.size());
 */
		std::cout<<"The puddle have mean:"<<mean<<" StdDev: "<<stdDev<<std::endl;


	output_file.close();
 return 0;}
Beispiel #22
0
bool processPDBChainList(Options& opts)
{
  // Open up the chain list file
  ifstream listfp(opts.chain_list);
  if( !listfp )
    {
      cerr << red << "Error" << reset << ": Failed to open list file, " << opts.chain_list << endl;
      perror("\t");
      return false;
    }

  // Open up the output file
  ofstream output_file(opts.outputfile);
  if( !output_file )
    {
      cerr << red << "Error" << reset << ": Failed to open output file" << endl;
      perror("\t");
    }

  // Write the header to the ouput file
  write_output_head(output_file,opts.triplets);

  string line;

  //open the pair list file (if we're searching for triplets, and if the option to log pairs is specified
  ofstream pairlistfile;

  if(opts.triplets && opts.pairlistfile != NULL){
    pairlistfile.open(opts.pairlistfile);
    if( !pairlistfile)
      {
        cerr << red << "Error" << reset << ": Failed to open pairfile output file" << endl;
        perror("\t");
      }
  }

  // Go through each line of the list file
  while(getline(listfp, line))
    {
      // Store the PDB directory path first
      string filename(opts.pdbfile);

      // Separate the line into files
      vector<string> fields = split(line,'\t');
      if( fields.size() < 2)
        {
          cerr << "Chain file is malformed!" << endl;
          return false;
        }

      // Create and output the file name
      filename += "/" + fields[0] + opts.extension;
      cout << purple << fields[0] << opts.extension << endl;

      // Process the file
      processSinglePDBFile(filename.c_str(), opts, output_file,pairlistfile, fields[1].c_str());
    }
  cout << endl;
  output_file.close();
  listfp.close();
  if(opts.triplets && opts.pairlistfile != NULL){
    pairlistfile.close();
  }

  return true;
}
Beispiel #23
0
int main(int argc, char* argv[]){
  printHeader();
  int return_value;
  double start = getTime();

  // Parse and error check the command line arguments
  Options opts(argc, argv);

  // Looks like something is wrong with the cmd line args
  // or the user input the -h flag
  if(opts.fail())
    {
      return 1;
    }

  // Lets check to see what kind of input we received for the
  // PDB file.  If we have a list file of PDBs, just go through
  // list with the specified directory. If a directory, parse 
  // all files in the directory. Otherwise just parse the single 
  // file
  if( opts.pdblist )
    {
      return_value = processPDBList(opts);
    }
  else if( opts.chain_list )
    {
      return_value = processPDBChainList(opts);
    }
  else if( isDirectory(opts.pdbfile) )
    {
      // go through each file in the directory
      return_value = processPDBDirectory(opts);
    }
  else
    {
      ofstream output_file(opts.outputfile);
      if(!output_file)
        {
          cerr << red << "Error" << reset << ": Failed to open output file," << opts.outputfile << endl;
          return 1;
        }
      write_output_head(output_file,opts.triplets);
      //open the pair list file (if we're searching for triplets, and if the option to log pairs is specified
      ofstream pairlistfile;

      if(opts.triplets && opts.pairlistfile != NULL){
        pairlistfile.open(opts.pairlistfile);
        if( !pairlistfile)
          {
            cerr << red << "Error" << reset << ": Failed to open pairfile output file" << endl;
            perror("\t");
          }
      }

      return_value = processSinglePDBFile(opts.pdbfile, opts, output_file,pairlistfile);
      if(opts.triplets && opts.pairlistfile != NULL){
        pairlistfile.close();
      }
      output_file.close();
    }

  cout << "Time taken: " << getTime() - start << "s" << endl;
  return !return_value;
}
Beispiel #24
0
static int
verify(PubkeyStruct *pubkey_struct, const char *message_file,
       const char *sig_file, int quiet, int output)
{
    char           trusted_comment[TRUSTEDCOMMENTMAXBYTES];
    unsigned char  global_sig[crypto_sign_BYTES];
    FILE          *info_fp = stdout;
    unsigned char *sig_and_trusted_comment;
    SigStruct     *sig_struct;
    unsigned char *message;
    size_t         message_len;
    size_t         trusted_comment_len;
    int            hashed;

    if (output != 0) {
        info_fp = stderr;
    }
    sig_struct = sig_load(sig_file, global_sig, &hashed,
                          trusted_comment, sizeof trusted_comment);
    message = message_load(&message_len, message_file, hashed);
    if (memcmp(sig_struct->keynum, pubkey_struct->keynum_pk.keynum,
               sizeof sig_struct->keynum) != 0) {
        fprintf(stderr, "Signature key id in %s is %" PRIX64 "\n"
                "but the key id in the public key is %" PRIX64 "\n",
                sig_file, le64_load(sig_struct->keynum),
                le64_load(pubkey_struct->keynum_pk.keynum));
        exit(1);
    }
    if (crypto_sign_verify_detached(sig_struct->sig, message, message_len,
                                    pubkey_struct->keynum_pk.pk) != 0) {
        if (quiet == 0) {
            fprintf(stderr, "Signature verification failed\n");
        }
        exit(1);
    }
    free(message);

    trusted_comment_len = strlen(trusted_comment);
    sig_and_trusted_comment = xmalloc((sizeof sig_struct->sig) +
                                      trusted_comment_len);
    memcpy(sig_and_trusted_comment, sig_struct->sig, sizeof sig_struct->sig);
    memcpy(sig_and_trusted_comment + sizeof sig_struct->sig, trusted_comment,
           trusted_comment_len);
    if (crypto_sign_verify_detached(global_sig, sig_and_trusted_comment,
                                    (sizeof sig_struct->sig) + trusted_comment_len,
                                    pubkey_struct->keynum_pk.pk) != 0) {
        if (quiet == 0) {
            fprintf(stderr, "Comment signature verification failed\n");
        }
        exit(1);
    }
    free(sig_and_trusted_comment);
    free(pubkey_struct);
    free(sig_struct);
    if (quiet == 0) {
        fprintf(info_fp, "Signature and comment signature verified\n"
                "Trusted comment: %s\n", trusted_comment);
    } else if (quiet == 2) {
        fprintf(info_fp, "%s\n", trusted_comment);
    }
    if (output != 0 && output_file(message_file) != 0) {
        exit(2);
    }
    return 0;
}
Beispiel #25
0
static int recurse_dir(int srcrootlen, int dstrootlen, std::string &srcdir, std::string &dstdir, std::string &tempheader, std::string &tempfooter)
{
	static const osd::directory::entry::entry_type typelist[] = { osd::directory::entry::entry_type::DIR, osd::directory::entry::entry_type::FILE };

	// extract a normalized subpath
	std::string srcdir_subpath;
	normalized_subpath(srcdir_subpath, srcdir, srcrootlen + 1);

	// create an index file
	std::string indexname;
	indexname = string_format("%s%c%s", dstdir.c_str(), PATH_SEPARATOR[0], "index.html");
	util::core_file::ptr indexfile = create_file_and_output_header(indexname, tempheader, srcdir_subpath);

	// output the directory navigation
	indexfile->printf("<h3>Viewing Directory: ");
	output_path_as_links(*indexfile, srcdir_subpath, true, false);
	indexfile->printf("</h3>");

	// iterate first over directories, then over files
	int result = 0;
	for (int entindex = 0; entindex < ARRAY_LENGTH(typelist) && result == 0; entindex++)
	{
		auto entry_type = typelist[entindex];

		// open the directory and iterate through it
		auto dir = osd::directory::open(srcdir.c_str());
		if (dir == nullptr)
		{
			result = 1;
			break;
		}

		// build up the list of files
		const osd::directory::entry *entry;
		int found = 0;
		list_entry *list = nullptr;
		while ((entry = dir->read()) != nullptr)
			if (entry->type == entry_type && entry->name[0] != '.')
			{
				auto lentry = new list_entry;
				lentry->name.assign(entry->name);
				lentry->next = list;
				list = lentry;
				found++;
			}

		// close the directory
		dir.reset();

		// skip if nothing found
		if (found == 0)
			continue;

		// allocate memory for sorting
		auto listarray = new list_entry *[found];
		found = 0;
		for (list_entry *curlist = list; curlist != nullptr; curlist = curlist->next)
			listarray[found++] = curlist;

		// sort the list
		qsort(listarray, found, sizeof(listarray[0]), compare_list_entries);

		// rebuild the list
		list = nullptr;
		while (--found >= 0)
		{
			listarray[found]->next = list;
			list = listarray[found];
		}
		delete[] listarray;

		// iterate through each file
		for (list_entry *curlist = list; curlist != nullptr && result == 0; curlist = curlist->next)
		{
			// add a header
			if (curlist == list)
				indexfile->printf("\t<h2>%s</h2>\n\t<ul>\n", (entry_type == osd::directory::entry::entry_type::DIR) ? "Directories" : "Files");

			// build the source filename
			std::string srcfile;
			srcfile = string_format("%s%c%s", srcdir.c_str(), PATH_SEPARATOR[0], curlist->name.c_str());

			// if we have a file, output it
			std::string dstfile;
			if (entry_type == osd::directory::entry::entry_type::FILE)
			{
				// make sure we care, first
				file_type type = FILE_TYPE_INVALID;
				for (auto & elem : extension_lookup)
					if (core_filename_ends_with(curlist->name, elem.extension))
					{
						type = elem.type;
						break;
					}

				// if we got a valid file, process it
				if (type != FILE_TYPE_INVALID)
				{
					dstfile = string_format("%s%c%s.html", dstdir.c_str(), PATH_SEPARATOR[0], curlist->name.c_str());
					if (indexfile != nullptr)
						indexfile->printf("\t<li><a href=\"%s.html\">%s</a></li>\n", curlist->name.c_str(), curlist->name.c_str());
					result = output_file(type, srcrootlen, dstrootlen, srcfile, dstfile, srcdir.compare(dstdir) == 0, tempheader, tempfooter);
				}
			}

			// if we have a directory, recurse
			else
			{
				dstfile = string_format("%s%c%s", dstdir.c_str(), PATH_SEPARATOR[0], curlist->name.c_str());
				if (indexfile != nullptr)
					indexfile->printf("\t<li><a href=\"%s/index.html\">%s/</a></li>\n", curlist->name.c_str(), curlist->name.c_str());
				result = recurse_dir(srcrootlen, dstrootlen, srcfile, dstfile, tempheader, tempfooter);
			}
		}

		// close the list if we found some stuff
		if (list != nullptr)
			indexfile->printf("\t</ul>\n");

		// free all the allocated entries
		while (list != nullptr)
		{
			list_entry *next = list->next;
			delete list;
			list = next;
		}
	}

	if (indexfile != nullptr)
		output_footer_and_close_file(std::move(indexfile), tempfooter, srcdir_subpath);
	return result;
}
int main(int argc, char** argv)
//int coincidence(TString filename)
{
  std::cout << "Reading file " << argv[1] << std::endl;
  
  //TFile *file = new TFile(argv[1], "READ");
  std::string filename = argv[1];
  
  std::string outFileName;
  outFileName = filename.substr(0,filename.length() -5 );
  outFileName += ".elm2";
  
  TFile *file = new TFile(filename.c_str(), "UPDATE");
  TTree *tree = (TTree *)file->Get("Singles");
  
  Float_t distance = 209.059998; //real heads distance, in mm
  Float_t yozRot = 0.0; //head rotation, in radiands
  Float_t absTime = 0.0; //t_start of this take, from the beginning of the "exam"
  
  if(argc > 2)
    distance = atof(argv[2]);
  if(argc > 3)
    yozRot = atof(argv[3]);
  if(argc > 4)
    absTime = atof(argv[4]);
  
  std::cout << "Heads distance [mm] = " << distance << std::endl;
  std::cout << "Rotation [rad] = " << yozRot << std::endl;
  std::cout << "Absolute initial time for this take [s] = " << absTime << std::endl;
  
  u_int8_t randomSet = 0;
  u_int8_t n1Set = 1;
  u_int8_t n2Set = 1;
  
  int entry;
  double time;
  Float_t xPos,yPos,zPos;
  Float_t energy;
  tree->SetBranchAddress("eventID",&entry);
  tree->SetBranchAddress("time",&time);
  
  tree->SetBranchAddress("globalPosX",&xPos);
  tree->SetBranchAddress("globalPosY",&yPos);
  tree->SetBranchAddress("globalPosZ",&zPos);
  tree->SetBranchAddress("energy",&energy);
  
  int ctrue = 0;
  int crandom = 0;
  
  long int nEvents = tree->GetEntries();
  std::cout << std::endl;
  std::cout << "nEvents = " << nEvents << std::endl;
  const int depth = 100;
  double dt = 4e-9;
  double timeWindow = 90e-9;
  
  //output binary file  
  
  ofstream output_file(outFileName.c_str(), std::ios::binary);
  
  //count the coincidences generated
  long int nCoincidence = 0;
  
  for(int i = 0 ; i < nEvents ; i++)
  {
    //std::cout << "Event " << i << std::endl;
    
    
    std::vector<double> t;
    std::vector<Float_t> x,y,z,e;
    std::vector<int> id;
    
    
    
    //get the "first" single
    tree->GetEntry(i);
    t.push_back( time + absTime);
    id.push_back( entry );
    x.push_back( (Float_t) xPos );
    y.push_back( (Float_t) yPos );
    z.push_back( (Float_t) zPos );
    e.push_back( (Float_t) energy );
    
    //     tree->GetEntry(i+1);
    //     t.push_back(time);
    //     e.push_back(entry);
    //     std::cout << "diff " << t[1] - t[0] << std::endl;
    
    //get all the events in a 90ns time window
    int j=0;
    while( (fabs(t[j] - t[0]) < timeWindow) && ((i+j) < nEvents) )
    {
      j++;
      tree->GetEntry(i+j);
      t.push_back( time + absTime);
      id.push_back(entry);
      x.push_back( (Float_t) xPos);
      y.push_back( (Float_t) yPos);
      z.push_back( (Float_t) zPos);
      e.push_back( (Float_t) energy);
      //std::cout << "diff " << t[j] - t[0] << std::endl;
    }
    
    //std::cout << "size " << t.size() << std::endl;
    for(int j = 1 ; j < t.size()  ; j++)
    {
      //first check, the coincidence is NOT in the same detector head
      if(z[0]*z[j] < 0)
      {
	
	
	//prepare the coincidence event to be written 
	nCoincidence++;
	EventFormat fe;
	fe.ts = t[0];
	fe.random = randomSet;
	fe.d = distance;
	fe.yozRot = yozRot;
	
// 	//invert x with y - definitions in clearpem are different
// 	fe.x1 = y[0];
// 	fe.y1 = x[0];
// 	fe.z1 = z[0];
// 	fe.e1 = e[0] * 1000;
// 	fe.n1 = n1Set;
	
// // 	invert x with y - definitions in clearpem are different
// 	fe.x2 = y[j];
// 	fe.y2 = x[j];
// 	fe.z2 = z[j];
// 	fe.e2 = e[j] * 1000;
// 	fe.n2 = n2Set;
// 	fe.dt = fabs(t[j] - t[0]);
	
	//geometry fixed in the simulation, axis don't need to be inverted anymore
	fe.x1 = x[0];
	fe.y1 = y[0];
	fe.z1 = z[0];
	fe.e1 = e[0] * 1000;
	fe.n1 = n1Set;
        fe.x2 = x[j];
	fe.y2 = y[j];
	fe.z2 = z[j];
	fe.e2 = e[j] * 1000;
	fe.n2 = n2Set;
	fe.dt = fabs(t[j] - t[0]);
	
	
	//debug
// 	std::cout << fe.ts
// 	<< " " 
// 	<< std::bitset<8>(fe.random)
// 	<< " "
// 	<< fe.d
// 	<< " "
// 	<< fe.x1
// 	<< " "
// 	<< fe.y1
// 	<< " "
// 	<< fe.z1
// 	<< " "
// 	<< fe.e1
// 	<< " "
// 	<< std::bitset<8>(fe.n1)
// 	<< " "
// 	<< fe.x2
// 	<< " "
// 	<< fe.y2
// 	<< " "
// 	<< fe.z2		
// 	<< " "
// 	<< fe.e2
// 	<< " "
// 	<< std::bitset<8>(fe.n2)
// 	<< " "
// 	<< fe.dt
// 	<< std::endl;
	
	//write data to file
	output_file.write((char*)&fe,sizeof(fe));
	
	if(fabs(t[j] - t[0]) < dt)
	{
	  if(id[j] == id[0])
	  {
	    //std::cout << "true " << t[j] - t[0] << " " << id[0] << " " << id[j] << std::endl;
	    ctrue++;
	  }
	  else
	  {
	    //std::cout << "random " << t[j] - t[0] << " " << id[0] << " " << id[j] << std::endl;
	    crandom++;
	  }
	}
      }
      //delete t;
      //delete e;
      //cout << i << "\t" << entry<< "\t" << std::setprecision(11)  << time << endl;
    }
  }
  
  output_file.close();
  
  
  std::cout << std::endl;
  std::cout << "Number of coincidences written = " << nCoincidence << std::endl;
  std::cout << "Trues = " << ctrue << std::endl;
  std::cout << "Randoms = " << crandom << std::endl;
  std::cout << std::endl;
  std::cout << "Output written to " << outFileName << std::endl;
  
  return 0;
}
void Config::SaveConfig(const std::string path)
{
	std::ofstream output_file(path);

	if (!output_file.good())
		return;

	Save(g_Options.misc_autoaccept, "misc_autoaccept");
	Save(g_Options.misc_revealAllRanks, "misc_revealAllRanks");
	Save(g_Options.misc_bhop, "misc_bhop");
	Save(g_Options.misc_autostrafe, "misc_autostrafe");
	Save(g_Options.misc_auto_pistol, "misc_auto_pistol");
	Save(g_Options.misc_chatspamer, "misc_chatspamer");
	Save(g_Options.misc_thirdperson, "misc_thirdperson");
	Save(g_Options.misc_thirdperson_bind, "misc_thirdperson_bind");
	Save(g_Options.misc_fakewalk, "misc_fakewalk");
	Save(g_Options.misc_fakewalk_bind, "misc_fakewalk_bind");
	Save(g_Options.misc_fakelag_enabled, "misc_fakelag_enabled");
	Save(g_Options.misc_fakelag_value, "misc_fakelag_value");
	Save(g_Options.misc_fakelag_activation_type, "misc_fakelag_activation_type");
	Save(g_Options.misc_fakelag_adaptive, "misc_fakelag_adaptive");
	Save(g_Options.misc_animated_clantag, "misc_animated_clantag");
	Save(g_Options.misc_spectatorlist, "misc_spectatorlist");
	Save(g_Options.misc_logevents, "misc_logevents");
	Save(g_Options.removals_flash, "removals_flash");
	Save(g_Options.removals_smoke, "removals_smoke");
	Save(g_Options.removals_smoke_type, "removals_smoke_type");
	Save(g_Options.removals_scope, "removals_scope");
	Save(g_Options.removals_novisualrecoil, "removals_novisualrecoil");
	Save(g_Options.removals_postprocessing, "removals_postprocessing");
	Save(g_Options.esp_enemies_only, "esp_enemies_only");
	Save(g_Options.esp_farther, "esp_farther");
	Save(g_Options.esp_fill_amount, "esp_fill_amount");
	SaveArray(g_Options.esp_player_fill_color_t, "esp_player_fill_color_t");
	SaveArray(g_Options.esp_player_fill_color_ct, "esp_player_fill_color_ct");
	SaveArray(g_Options.esp_player_fill_color_t_visible, "esp_player_fill_color_t_visible");
	SaveArray(g_Options.esp_player_fill_color_ct_visible, "esp_player_fill_color_ct_visible");
	Save(g_Options.esp_player_boundstype, "esp_player_boundstype");
	Save(g_Options.esp_player_boxtype, "esp_player_boxtype");
	SaveArray(g_Options.esp_player_bbox_color_t, "esp_player_bbox_color_t");
	SaveArray(g_Options.esp_player_bbox_color_ct, "esp_player_bbox_color_ct");
	SaveArray(g_Options.esp_player_bbox_color_t_visible, "esp_player_bbox_color_t_visible");
	SaveArray(g_Options.esp_player_bbox_color_ct_visible, "esp_player_bbox_color_ct_visible");
	Save(g_Options.esp_player_name, "esp_player_name");
	Save(g_Options.esp_player_health, "esp_player_health");
	Save(g_Options.esp_player_weapons, "esp_player_weapons");
	Save(g_Options.esp_player_snaplines, "esp_player_snaplines");
	Save(g_Options.esp_player_chams, "esp_player_chams");
	Save(g_Options.esp_player_chams_type, "esp_player_chams_type");
	SaveArray(g_Options.esp_player_chams_color_t_visible, "esp_player_chams_color_t_visible");
	SaveArray(g_Options.esp_player_chams_color_ct_visible, "esp_player_chams_color_ct_visible");
	SaveArray(g_Options.esp_player_chams_color_t, "esp_player_chams_color_t");
	SaveArray(g_Options.esp_player_chams_color_ct, "esp_player_chams_color_ct");
	Save(g_Options.esp_player_skelet, "esp_player_skelet");
	Save(g_Options.esp_player_anglelines, "esp_player_anglelines");
	Save(g_Options.esp_dropped_weapons, "esp_dropped_weapons");
	Save(g_Options.esp_planted_c4, "esp_planted_c4");
	Save(g_Options.esp_grenades, "esp_grenades");
	Save(g_Options.esp_grenades_type, "esp_grenades_type");
	Save(g_Options.esp_backtracked_player_skelet, "esp_backtracked_player_skelet");
	Save(g_Options.esp_lagcompensated_hitboxes, "esp_lagcompensated_hitboxes");
	Save(g_Options.esp_lagcompensated_hitboxes_type, "esp_lagcompensated_hitboxes_type");
	Save(g_Options.visuals_others_player_fov, "visuals_others_player_fov");
	Save(g_Options.visuals_others_player_fov_viewmodel, "visuals_others_player_fov_viewmodel");
	Save(g_Options.visuals_others_watermark, "visuals_others_watermark");
	Save(g_Options.visuals_others_grenade_pred, "visuals_others_grenade_pred");
	Save(g_Options.visuals_others_hitmarker, "visuals_others_hitmarker");
	Save(g_Options.visuals_others_bulletimpacts, "visuals_others_bulletimpacts");
	SaveArray(g_Options.visuals_others_bulletimpacts_color, "visuals_others_bulletimpacts_color");
	Save(g_Options.visuals_others_sky, "visuals_others_sky");
	Save(g_Options.glow_enabled, "glow_enabled");
	Save(g_Options.glow_players, "glow_players");
	SaveArray(g_Options.glow_player_color_t, "glow_player_color_t");
	SaveArray(g_Options.glow_player_color_ct, "glow_player_color_ct");
	SaveArray(g_Options.glow_player_color_t_visible, "glow_player_color_t_visible");
	SaveArray(g_Options.glow_player_color_ct_visible, "glow_player_color_ct_visible");
	Save(g_Options.glow_players_style, "glow_players_style");
	Save(g_Options.glow_others, "glow_others");
	Save(g_Options.glow_others_style, "glow_others_style");
	Save(g_Options.legit_enabled, "legit_enabled");
	Save(g_Options.legit_aimkey1, "legit_aimkey1");
	Save(g_Options.legit_aimkey2, "legit_aimkey2");
	Save(g_Options.legit_rcs, "legit_rcs");
	Save(g_Options.legit_trigger, "legit_trigger");
	Save(g_Options.legit_trigger_with_aimkey, "legit_trigger_with_aimkey");
	Save(g_Options.legit_preaim, "legit_preaim");
	Save(g_Options.legit_aftershots, "legit_aftershots");
	Save(g_Options.legit_afteraim, "legit_afteraim");
	Save(g_Options.legit_smooth_factor, "legit_smooth_factor");
	Save(g_Options.legit_fov, "legit_fov");
	Save(g_Options.rage_enabled, "rage_enabled");
	Save(g_Options.rage_aimkey, "rage_aimkey");
	Save(g_Options.rage_usekey, "rage_usekey");
	Save(g_Options.rage_silent, "rage_silent");
	Save(g_Options.rage_norecoil, "rage_norecoil");
	Save(g_Options.rage_autoshoot, "rage_autoshoot");
	Save(g_Options.rage_autoscope, "rage_autoscope");
	Save(g_Options.rage_autocrouch, "rage_autocrouch");
	Save(g_Options.rage_autostop, "rage_autostop");
	Save(g_Options.rage_autobaim, "rage_autobaim");
	Save(g_Options.rage_autocockrevolver, "rage_autocockrevolver");
	Save(g_Options.rage_baim_after_x_shots, "rage_baim_after_x_shots");
	Save(g_Options.rage_lagcompensation, "rage_lagcompensation");
	Save(g_Options.rage_lagcompensation_type, "rage_lagcompensation_type");
	Save(g_Options.rage_fixup_entities, "rage_fixup_entities");
	Save(g_Options.rage_mindmg, "rage_mindmg");
	Save(g_Options.rage_hitchance_amount, "rage_hitchance_amount");
	Save(g_Options.rage_hitbox, "rage_hitbox");
	Save(g_Options.rage_prioritize, "rage_prioritize");
	Save(g_Options.rage_multipoint, "rage_multipoint");
	Save(g_Options.rage_pointscale, "rage_pointscale");
	SaveArray(g_Options.rage_multiHitboxes, "rage_multiHitboxes");
	Save(g_Options.hvh_antiaim_x, "hvh_antiaim_x");
	Save(g_Options.hvh_antiaim_y, "hvh_antiaim_y");
	Save(g_Options.hvh_antiaim_y_fake, "hvh_antiaim_y_fake");
	Save(g_Options.hvh_antiaim_lby_breaker, "hvh_antiaim_lby_breaker");
	Save(g_Options.hvh_show_real_angles, "hvh_show_real_angles");
	Save(g_Options.hvh_resolver, "hvh_resolver");
	Save(g_Options.hvh_resolver_override, "hvh_resolver_override");
	Save(g_Options.hvh_resolver_override_key, "hvh_resolver_override_key");
	Save(g_Options.skinchanger_enabled, "skinchanger_enabled");

	output_file << std::setw(4) << config << std::endl;
	output_file.close();
}
Beispiel #28
0
int main(int argc, char *argv[]) {
  char data_file_name[256];
  char output_file_name[256];
  struct Problem *prob;
  int num_correct = 0, num_empty = 0, num_multi = 0, num_incl = 0;
  int *indices = NULL;
  double avg_conf = 0, avg_cred = 0;
  double *conf = NULL, *cred = NULL;
  std::vector<int> *predict_labels = NULL;
  const char *error_message;

  ParseCommandLine(argc, argv, data_file_name, output_file_name);
  error_message = CheckParameter(&param);

  if (error_message != NULL) {
    std::cerr << error_message << std::endl;
    exit(EXIT_FAILURE);
  }

  prob = ReadProblem(data_file_name);

  std::ofstream output_file(output_file_name);
  if (!output_file.is_open()) {
    std::cerr << "Unable to open output file: " << output_file_name << std::endl;
    exit(EXIT_FAILURE);
  }

  predict_labels = new std::vector<int>[prob->num_ex];
  conf = new double[prob->num_ex];
  cred = new double[prob->num_ex];
  indices = new int[prob->num_ex];

  std::chrono::time_point<std::chrono::steady_clock> start_time = std::chrono::high_resolution_clock::now();

  OnlinePredict(prob, &param, predict_labels, indices, conf, cred);

  std::chrono::time_point<std::chrono::steady_clock> end_time = std::chrono::high_resolution_clock::now();

  output_file << prob->y[indices[0]] << '\n';

  for (int i = 1; i < prob->num_ex; ++i) {
    avg_conf += conf[i];
    avg_cred += cred[i];

    output_file << std::resetiosflags(std::ios::fixed) << prob->y[indices[i]] << ' ' << predict_labels[i][0] << ' '
                << std::setiosflags(std::ios::fixed) << conf[i] << ' ' << cred[i];
    if (predict_labels[i][0] == prob->y[indices[i]]) {
      ++num_correct;
    }

    if (predict_labels[i].size() == 1) {
      ++num_empty;
      output_file << " Empty\n";
    } else {
      output_file << " set:";
      for (size_t j = 1; j < predict_labels[i].size(); ++j) {
        output_file << ' ' << predict_labels[i][j];
        if (predict_labels[i][j] == prob->y[indices[i]]) {
          ++num_incl;
        }
      }
      if (predict_labels[i].size() > 2) {
        ++num_multi;
        output_file << " Multi\n";
      } else {
        output_file << " Single\n";
      }
    }
    std::vector<int>().swap(predict_labels[i]);
  }
  avg_conf /= prob->num_ex - 1;
  avg_cred /= prob->num_ex - 1;

  std::cout << "Online Accuracy: " << 100.0*num_correct/(prob->num_ex-1) << '%'
            << " (" << num_correct << '/' << prob->num_ex-1 << ") "
            << "Mean Confidence: " << std::fixed << std::setprecision(4) << 100*avg_conf << "%, "
            << "Mean Credibility: " << 100*avg_cred << "%\n";
  std::cout << "Accuracy: " << 100.0*num_incl/(prob->num_ex-1) << '%'
            << " (" << num_incl << '/' << prob->num_ex-1 << ") "
            << "Multi Prediction: " << std::fixed << std::setprecision(4) << 100.0*num_multi/(prob->num_ex-1) << "%, "
            << "Empty Prediction: " << 100.0*num_empty/(prob->num_ex-1) << "%\n";
  output_file.close();

  std::cout << "Time cost: " << std::chrono::duration_cast<std::chrono::milliseconds>(end_time - start_time).count()/1000.0 << " s\n";

  FreeProblem(prob);
  FreeParam(&param);
  delete[] predict_labels;
  delete[] conf;
  delete[] cred;
  delete[] indices;

  return 0;
}
Beispiel #29
0
int main(int argc, char **argv)
{
    // Good to include a usage message if necessary.
    if (argc != 2) {
        std::cerr << "Usage: " << argv[0] << " filename\n";
        return 1;
    }

    // Get the file names.
    std::string input_name = argv[1];
    std::string output_name = input_name;
    output_name += ".q";

    // Open the files.
    std::ifstream input_file(input_name.c_str());
    if (!input_file) {
        std::cerr << "Can't open " << input_name << " for reading.\n";
        return 1;
    }
    std::ofstream output_file(output_name.c_str());
    if (!output_file) {
        std::cerr << "Can't open " << output_name << " for writing.\n";
        return 1;
    }

    // Initialize.
    std::string input_line;
    std::string output_line = ">";

    // Read the input file a line at a time.
    while (getline(input_file, input_line)) {

        // If this is a blank like handle it. This might involve outputing a partially filled
        // output line.
        //
        if (is_blank(input_line)) {
            if (output_line.length() > 2) {
                output_file << output_line << "\n";
                output_line = ">";
            }
            output_file << ">\n";
        }

        // Otherwise the line is not blank and needs to be broken down by words.
        else {
            std::string word;
            while (get_next_word(input_line, word)) {
                if (output_line.length() + word.length() + 1 > 76) {
                    output_file << output_line << "\n";
                    output_line = ">";
                }
                output_line += ' ';
                output_line += word;
            }
        }
    }

    // If there is a partially filled line at the end, output that too.
    if (output_line.length() > 2) {
        output_file << output_line << "\n";
    }

    return 0;
}
Beispiel #30
0
/**
 * the worker
 **/
void *preprocess( void *p )
{
    // get start & end for this thread
    Thread* thread = (Thread*)p;
    const long int start = thread->start();
    const long int end = thread->end();
    const long int nbop = (end-start)/100;
    // get output file name
    std::string output_file_name = std::string(c_output_file_name);

    // attach thread to CPU
    if (thread->id() != -1){
        thread->set();
        output_file_name += "-" + typeToString(thread->id());
        if (verbose) fprintf(stderr, "create pthread n°%ld, reading from position %ld to %ld\n",thread->id(), start, end-1);
    }

    // create output file
    File output_file(output_file_name,zip);
    output_file.open("w");

    // open input file
    std::string input_file_name = std::string(c_input_file_name);
    File input_file(input_file_name);
    input_file.open();
    input_file.jump_to_position(start);

    char *line = NULL;
    long int position=input_file.position();
    int itr=0;
    if (verbose) loadbar(thread->id(), itr, 100);
    while ( position<end ){

        // get the line
        line = input_file.getline();

        // lowercase?
        if (lower) lowercase(line);

        // replace digits?
        if (digit) replace_digit(line);

        // write the preprocessed line
        output_file.write(line);
        output_file.write("\n");

        // get current position in stream
        position = input_file.position();
        // display progress bar
        if (verbose){
            if ( position-(start+(itr*nbop)) > nbop)
                loadbar(thread->id(), ++itr, 100);
        }
        // release memory
        free(line);
    }
    // display last percent
    if (verbose) loadbar(thread->id(), 100, 100);
    // close output file
    output_file.close();
    // close input file
    input_file.close();

    // exit thread
    if ( thread->id()!= -1 ){
        pthread_exit( (void*)thread->id() );
    }
    return 0;
}