示例#1
0
void ReleaseFileSet::Visitor::VisitSection(const IniFile& iniFile, const std::string& section)
			{
				if( utils::startsWith( section, "File" ) )
				{
					vfs::Path filename = section.substr(5);

					ReleaseFile rfile(filename);
          // Lets check platform compatibility using 'platforms' property of section
          std::string platform = iniFile.GetValue(section, "platforms");
          if (!platform.empty()) {
            if (platform.find(GAME_PLATFORM_NAME) == std::string::npos) {
              return;
            }
          }
          // TODO: remove in later releases
					if( rfile.isWrongOS() )
						return;

					std::pair<ReleaseFileSet::iterator, bool> result = _set.insert(	ReleaseFileSet::value_type(filename.toString(), rfile));
					
					result.first->second.crc = CRC::ParseFromString(iniFile.GetValue(section, "crc"));
					result.first->second.filesize = utils::toUint( iniFile.GetValue(section, "filesize") );

					if( filename.isMyExtension( ".zip") )
					{
						result.first->second.isArchive = true;
					}
					else
					{
						result.first->second.isArchive = false;
					}
				}
			}
示例#2
0
bool Manager::move(QString folder, QString dir, bool remove)
{
    try
    {
        QStringList files = this->getAllFiles(folder);
        QStringList folders = this->getAllFolders(folder);

        foreach(QString file, files)
        {
            QFile rfile(QString("%1/%2").arg(folder).arg(file));
            if(!rfile.exists()) return false;

            QString nfile = QString("%1/%2").arg(dir).arg(file);
            if(QFile(nfile).exists()) { logs->append(QApplication::tr("<span style=\"color: #ea7878\"><b>•</b> File %1 already exists, replacing...</span>").arg(nfile)); QFile(nfile).remove(); }
            rfile.copy(nfile);
            logs->append(QApplication::tr("<span style=\"color: #ced0f3\"><b>•</b> File %1 moved to %2.</span>").arg(file).arg(dir));

            if(remove)
            {
                rfile.remove();
                logs->append(QApplication::tr("<span style=\"color: #ced0f3\"><b>•</b> File %1 has successfully removed.</span>").arg(file));
            }
        }

        foreach(QString path, folders)
        {
            QDir directory(path);
            //qDebug() << path;
            //qDebug() << directory.dirName();

        }
示例#3
0
UtlBoolean OsTestUtilities::verifyDummyFile(OsPath testFile, unsigned long size)
{
    OsStatus stat;
    UtlBoolean ok = false;
    char rbuff[256];
    size_t rbuffsize = (size_t)sizeof(rbuff);
    OsFile rfile(testFile);
    stat = rfile.open();
    if (stat == OS_SUCCESS)
    {
        size_t rposition = 0;
        ok = true;
        for (int i = 0; ok && rposition < size; i++)
        {
            size_t remaining = (size - rposition);
            size_t readsize = remaining < rbuffsize ? remaining : rbuffsize;
            size_t bytesread = 0;
            stat = rfile.read(rbuff, readsize, bytesread);
            if (stat != OS_SUCCESS)
            {
                ok = false;
                printf("Error reading file, status = %i", stat);
            }
            else
            {
                ok = OsTestUtilities::testDummyBuffer(rbuff, bytesread, rposition);
                rposition += bytesread;
            }
        }

        rfile.close();
    }

    return ok;
}
示例#4
0
void BattleReport::addReport( UInt32 id, std::vector<UInt8>& v )
{
	FastMutex::ScopedLock lk(_mutex);
	_reports[id] = v;
	char path[1024], path2[1024];
	sprintf(path, "%s%u/%u", /*cfg.reportPath.c_str()*/ _type ? cfg.reportPath1.c_str() : cfg.reportPath0.c_str(), id / 100000, (id / 1000) % 100);
	sprintf(path2, "%s/%u.dat", path, id);
	File rfile(path);
	rfile.createDirectories();
	FILE * f = fopen(path2, "wb");
	if(f == NULL)
		return;
	fwrite(&v[0], 1, v.size(), f);
	fclose(f);
    if( _type == 0 )
    {
        if(id >static_cast<UInt32>(lastMaxId0))
            DB1().PushUpdateData("update reportid set maxid = %d where type = %d", id,_type);
        lastMaxId0 = id;
    }
    else
    {
        if(id >static_cast<UInt32>(lastMaxId1))
            DB1().PushUpdateData("update reportid set maxid = %d where type = %d", id,_type);
        lastMaxId1 = id;
    }

    RptLife rptLife = {id, TimeUtil::Now()};
    _rptLife.insert(rptLife);
    travelRptLife();
}
示例#5
0
文件: dialog.cpp 项目: fengyikil/Qpwd
void Dialog::Pwd()
{
    QFileInfo  rfile(ui->lineEdit->text());
    QFileInfo wfile(ui->lineEdit_2->text());

    if(!rfile.isFile())
    {
        QMessageBox::information(this,"提示","输入文件不存在");
        return;
    }
    if(wfile.isFile() && !wfile.isDir())
    {
        int result = QMessageBox::information(this,"提示","输出文件已存在,点击继续则覆盖!","继续","取消");

        qDebug()<<result;
        if (result)
        {
            return;
        }
    }
    else if(!wfile.isFile()&& wfile.isDir())
    {
        int result = QMessageBox::information(this,"提示","请补全输出文件名!","确定");
        return;
    }
    emit SendPwd(ui->lineEdit->text(),ui->lineEdit_2->text());
}
示例#6
0
    /**
     * Creates a new dummy file then reads it back in to verify it's
     * contents, buffer by buffer.
     */
    void testReadWriteBuffer()
    {
        ///////////////////////
        //       W R I T E
        ///////////////////////
        OsStatus stat;
        OsPath testFile = mRootPath + OsPath::separator + "testWriteBuffer";
        char wbuff[10000];
        unsigned long wbuffsize = (unsigned long)sizeof(wbuff);

        OsTestUtilities::initDummyBuffer(wbuff, sizeof(wbuff));

        OsFile wfile(testFile);
        stat = wfile.open(OsFile::CREATE);
        CPPUNIT_ASSERT(stat == OS_SUCCESS);

        unsigned long wposition = 0;
        int i;
        for (i = 0; wposition < wbuffsize; i++)
        {
            unsigned long remaining = wbuffsize - wposition;
            unsigned long byteswritten = 0;
            stat = wfile.write(wbuff + wposition, remaining, byteswritten);
            CPPUNIT_ASSERT(stat == OS_SUCCESS);
            wposition += byteswritten;
        }

        //close the file after working with it.
        wfile.close();

        ///////////////////////
        //       R E A D
        ///////////////////////
        char rbuff[256];
        unsigned long rbuffsize = (unsigned long)sizeof(rbuff);
        OsFile rfile(testFile);
        stat = rfile.open();
        CPPUNIT_ASSERT(stat == OS_SUCCESS);
        
        unsigned long rposition = 0;
        for (i = 0; rposition < wbuffsize; i++)
        {
            unsigned long remaining = (wbuffsize - rposition);
            unsigned long readsize = remaining < rbuffsize ? remaining : rbuffsize;
            unsigned long bytesread = 0;
            stat = rfile.read(rbuff, readsize, bytesread);
            CPPUNIT_ASSERT_MESSAGE("Read buffer", stat == OS_SUCCESS);
            UtlBoolean ok = OsTestUtilities::testDummyBuffer(rbuff, bytesread, rposition);
            CPPUNIT_ASSERT_MESSAGE("Test buffer data", ok);
            rposition += bytesread;
        }

        // proper EOF
        unsigned long zeroread = 0;
        stat = rfile.read(rbuff, 1, zeroread);
        CPPUNIT_ASSERT_MESSAGE("End of file", stat == OS_FILE_EOF);
        CPPUNIT_ASSERT_MESSAGE("No bytes read", zeroread == 0);
    }
示例#7
0
bool vfs::PropertyContainer::initFromXMLFile(vfs::Path const& sFileName, vfs::PropertyContainer::TagMap& tagmap)
{
	vfs::tReadableFile *file = NULL;
	bool delete_file = false;
	if(getVFS()->fileExists(sFileName))
	{
		vfs::COpenReadFile rfile(sFileName);
		file = &rfile.file();
		rfile.release();
	}
	else
	{
		vfs::CFile* rfile = new vfs::CFile(sFileName);
		delete_file = true;
		file = vfs::tReadableFile::cast(rfile);
		if(!file->openRead())
		{
			delete file;
			return false;
		}
	}
	if(!file)
	{
		return false;
	}

	vfs::size_t size = file->getSize();

	std::vector<vfs::Byte> buffer(size+1);

	SGP_TRYCATCH_RETHROW( file->read(&buffer[0],size), L"" );
	buffer[size] = 0;

	file->close();
	if(delete_file) delete file;

	XML_Parser parser = XML_ParserCreate(NULL);

	CPropertyXMLParser pp(*this,tagmap,parser,NULL);
	pp.grabParser();

	if(!XML_Parse(parser, &buffer[0], size, TRUE))
	{
		std::wstringstream wss;
		wss << L"XML Parser Error in Groups.xml: "
			<< vfs::String::as_utf16(XML_ErrorString(XML_GetErrorCode(parser))) 
			<< L" at line "
			<< XML_GetCurrentLineNumber(parser);
		SGP_THROW(wss.str().c_str());
		//return false;
	}

	return true;
}
示例#8
0
/**
Appends csmp customary `-regions.txt` to `fnamepref`.
*/
bool write_rfile(const char *fnamepref, const vector<string> &rnames) {
  auto fname = (string)fnamepref + "-regions.txt";
  ofstream rfile(fname);
  if (!rfile.is_open())
    return false;
  rfile << "regions file\nno properties\n";
  for (const auto &rn : rnames)
    rfile << rn << endl;
  rfile.close();
  return true;
}
示例#9
0
int main(int argc,char** argv) {
#ifdef INLIB_MEM
  inlib::mem::set_check_by_class(true);{
#endif //INLIB_MEM

  inlib::args args(argc,argv);

  std::string file;
  if(!args.file(file)) {
    std::cout << " give a file at the CERN-ROOT format." << std::endl;
    return EXIT_FAILURE;
  }

  bool verbose = args.is_arg("-verbose");

  inlib::rroot::file rfile(std::cout,file,verbose);
#ifdef EXLIB_DONT_HAVE_ZLIB
#else
  rfile.add_unziper('Z',exlib::decompress_buffer);
#endif

  bool sinfos = args.is_arg("-sinfos");

  std::string kbuf;
  args.find("-kbuf",kbuf,"");

  if(kbuf.size()) {
    inlib::rroot::key* k = rfile.dir().find_key(kbuf);
    if(!k) {
      std::cout << kbuf << " not a key in file root directory." << std::endl;
      return EXIT_FAILURE;
    }
    unsigned int sz;
    char* buf = k->get_object_buffer(sz); //we don't have ownership of buf.
    if(!buf) {
      std::cout << " can't get data buffer of " << k->object_name() << "." << std::endl;
      return EXIT_FAILURE;
    }
    std::cout << "size of decompressed data buffer " << sz << std::endl;
  } else {
    const std::vector<inlib::rroot::key*>& keys = rfile.dir().keys();
    inlib::rroot::dump(std::cout,rfile,keys,true,0);
    bool ls = args.is_arg("-ls");
    bool dump = args.is_arg("-dump");
    if(ls||dump) inlib::rroot::read(std::cout,rfile,keys,true,ls,dump,0);
    if(sinfos) inlib::rroot::read_sinfos(rfile);
  }
  
#ifdef INLIB_MEM
  }inlib::mem::balance(std::cout);
#endif //INLIB_MEM

  return EXIT_SUCCESS;
}
示例#10
0
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
QString PMFileGenerator::getFileContents(QString replaceStr)
{
  //Get text feature values from widget
  QString pluginName = getPluginName();
  QString pluginDir = getOutputDir();
  QString text = "";

  if (pluginName.isEmpty() == true)
  {
    return text;
  }

  //Open file
  QFile rfile(getCodeTemplateResourcePath());
  if (rfile.open(QIODevice::ReadOnly | QIODevice::Text))
  {
    QTextStream in(&rfile);
    text = in.readAll();
    text.replace("@PluginName@", pluginName);
    QFileInfo fi(m_FileName);
    QString className = fi.baseName();
    QString filterName = className;
    //filterName = filterName.remove("Test");   // For the test files
    text.replace("@ClassName@", className);
    text.replace("@FilterName@", filterName);
    text.replace("@MD_FILE_NAME@", m_FileName);
    text.replace("@ClassNameLowerCase@", className.toLower());
    text.replace("@FilterGroup@", pluginName);
    text.replace("@FilterSubgroup@", pluginName);

    // Replace function contents with the string that we have stored
    text.replace("@SetupFPContents@", setupFPContents);
    text.replace("@FPContents@", fpContents);
    text.replace("@ReadFPContents@", readFPContents);
    text.replace("@WriteFPContents@", writeFPContents);
    text.replace("@DataCheckContents@", dataCheckContents);
    text.replace("@InitList@", initListContents);
    text.replace("@Filter_H_Includes@", filterHIncludesContents);
    text.replace("@Filter_CPP_Includes@", filterCPPIncludesContents);

    if (replaceStr.isEmpty() == false)
    {
      text.replace("@AddTestText@", replaceStr);    // Replace token for Test/CMakeLists.txt file
      text.replace("@Namespaces@", replaceStr);   // Replace token for Test/TestFileLocations.h.in file
    }

    rfile.close();
  }

  return text;
}
示例#11
0
void CSyntaxDlg::OnGenerate() 
{
  	CStdioFile rfile( m_strTagPath,  CFile::modeRead | CFile::typeText );
	CArchive rar( & rfile, CArchive::load );
	if( m_bTitles )
		ProcessTitles( rar ); 
	else
		ProcessText( rar );
	rar.Close();	
	rfile.Close();
	WriteReportFile();
	m_strTagPath = "";
	EnableControls( FALSE );
	GetDlgItem( IDC_SYN_FILENAME )->SetWindowText( "Keine Datei ausgewählt" );
}
示例#12
0
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
void PMFileGenerator::generateOutput()
{
//  std::cout << "PMFileGenerator::generateOutput" << std::endl;
  if (doesGenerateOutput() == false)
  {
    return;
  }

  //Get text field values from widget
  QString pluginName = getPluginName();
  QString pluginDir = getOutputDir();

  if (pluginName.isEmpty() == true || pluginDir.isEmpty() == true)
  {
      return;
  }

//  QString classNameLowerCase = m_ClassName.toLower();

  //Open file
    QFile rfile(getCodeTemplateResourcePath());
    if ( rfile.open(QIODevice::ReadOnly | QIODevice::Text) ) {
      QTextStream in(&rfile);
      QString text = in.readAll();
      text.replace("@PluginName@", pluginName);
      QFileInfo fi(m_FileName);
      QString className = fi.baseName();
      text.replace("@ClassName@", className);
      text.replace("@MD_FILE_NAME@", m_FileName);
      text.replace("@ClassNameLowerCase@", className.toLower());
      text.replace("@FilterGroup@", pluginName);
      text.replace("@FilterSubgroup@", pluginName);

      QString parentPath = getOutputDir() + QDir::separator() + getPathTemplate().replace("@PluginName@", getPluginName());
      parentPath = QDir::toNativeSeparators(parentPath);

      QDir dir(parentPath);
      dir.mkpath(parentPath);

      parentPath = parentPath + QDir::separator() + m_FileName;
      //Write to file
      QFile f(parentPath);
      if ( f.open(QIODevice::WriteOnly | QIODevice::Text) ) {
        QTextStream out(&f);
        out << text;
      }
    }
}
示例#13
0
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
QString PMFileGenerator::generateFileContents() {
  QString pluginName = getPluginName();
  QString text = "";

  //Open file
  QFile rfile( getCodeTemplateResourcePath() );
  if ( rfile.open(QIODevice::ReadOnly | QIODevice::Text) ) {
    QTextStream in(&rfile);
    text = in.readAll();
    text.replace("@PluginName@", pluginName);
    QFileInfo fi( getFileName() );
    QString className = fi.baseName();
    text.replace("@ClassName@", className);
    text.replace("@ClassNameLowerCase@", className.toLower());
  }
  return text;
}
示例#14
0
UtlBoolean OsTestUtilities::verifyDummyFile(OsPath testFile, unsigned long size)
{
    OsStatus stat;
    UtlBoolean ok = false;
    char rbuff[256];
    unsigned long rbuffsize = (unsigned long)sizeof(rbuff);
    OsFile rfile(testFile);
    stat = rfile.open();
    UtlString msg("Failed to create file: ");
    msg.append(testFile);
    CPPUNIT_ASSERT_MESSAGE(testFile.data(), stat == OS_SUCCESS);
    if (stat == OS_SUCCESS)
    {
        unsigned long rposition = 0;
        ok = true;
        for (int i = 0; ok && rposition < size; i++)
        {
            unsigned long remaining = (size - rposition);
            unsigned long readsize = remaining < rbuffsize ? remaining : rbuffsize;
            unsigned long bytesread = 0;
            stat = rfile.read(rbuff, readsize, bytesread);
            CPPUNIT_ASSERT_MESSAGE("Failed to read", stat != 0);
            if (stat != OS_SUCCESS)
            {
                ok = false;
                printf("Error reading file, status = %i", stat);
            }
            else
            {
                ok = OsTestUtilities::testDummyBuffer(rbuff, bytesread, rposition);
                rposition += bytesread;
            }
        }

        rfile.close();
    }

    return ok;
}
Int_t VisualizeRegionIntegratedSurface()
{
    std::string fname = GetRootFile();

    TGraph2DErrors* gr = GetGraph(fname);
    gr->SetMarkerColor(kOrange);
    gr->SetLineColor(kOrange+3);

    std::string parfname = GetParamFile();
    std::ifstream pfile(parfname.data(),std::ios::in);
    Parameters params(pfile);
    if (! params.KeysAreSensible()) return -1;
    AngDist W(params);
    W.SetConstrainedRange(false);
    SphCoordsIntegrand Wsph(W);

    std::string regfname = GetRegionFile();
    std::ifstream rfile(regfname.data());
    RegionFileLoader rfl(rfile);
    rfile.close();

    std::vector<Regions> regs = rfl.GetRegions();

    TGraph2DErrors* grint = GenerateRegionIntegratedSurface(gr, Wsph, regs);
    grint->SetMarkerColor(kAzure);
    grint->SetLineColor(kAzure+3);

    TCanvas* c = new TCanvas("c");
    c->Divide(2,1);
    c->cd(1);
    grint->Draw("p0 tri1 err");
    c->cd(2);
    gr->Draw("p0 tri1 err");

    return 0;
}
示例#16
0
int main(){

   sky sky;

   double hbarc = 197.327;

   double Mu = M;   //Mass in MeV
   cout<<Mu<<endl;
   complex <double> M_I(0,1);

   // Create momentum space grid
   std::vector<double> kmesh;
   std::vector<double> kweights;
   double const kmax = 5.0;
   int const kpts = 170;
   kmesh.resize( kpts );
   kweights.resize( kpts );
   GausLeg( 0., kmax, kmesh, kweights );

   ////////Input Parameters of the potential (fit parameters) /////
   std::string parameters_filename="Input.inp";

   NuclearParameters Nu = read_nucleus_parameters( "Input/pca40.inp" );

   //I'm altering the potential to represent ca40 after a proton is removed (i.e. the potential for K39)
   /*Nu.A = 39.0;
     Nu.Z = 19.0;

     cout<<Nu.Z<<" "<<Nu.A<<endl;
     */

   double Ef=Nu.Ef;
   int lmax=20;
   double zp0;
   double tz=+0.5;

   int type=1;
   int mvolume = 4;
   int AsyVolume = 1;

   double A = Nu.A;

   double  mu = (A)/((A-1.));

   if (tz>0) { zp0=1;}
   else {zp0=0;}

   double ph_gap = Nu.ph_gap;
   cout<<"ph_gap = "<<Nu.ph_gap<<endl;
   double  rStart = .05;
   double  rmax = 13.51999;
   int  ham_pts = 340; //300 for highR 

   double  rdelt = rmax / (ham_pts-1);
   cout<<"rdelt = "<<rdelt<<endl;

   vector<double> dr;
   dr.assign(ham_pts,rdelt);

   // Construct Parameters Object
   Parameters p = get_parameters( parameters_filename, Nu.A, Nu.Z, zp0 );
   // Construct Potential Object
   pot pottt = get_bobs_pot2( type, mvolume, AsyVolume, tz, Nu, p );
   pot * pott = &pottt;
   cout<<"kconstant = "<<pott->kconstant<<endl;

   boundRspace initiate(rmax , ham_pts , Ef, ph_gap , lmax , Nu.Z , zp0 , Nu.A, pott);

   double Elower = -11.61818;
   double Eupper = -9.4;
   double jj = .5;
   int ll = 0;
   int Ifine = 1;
   initiate.searchNonLoc( Elower, Eupper, jj,  ll,  Ifine);
   initiate.exteriorWaveFunct(ll);
   initiate.normalizeWF();


   double tol=.01;
   double estart=Ef;

   ///// Making rmesh///

   std::vector<double> rmesh_p= initiate.make_rmesh_point();
   std::vector<double> rmesh= initiate.make_rmesh();

   matrix_t test(rmesh.size(),rmesh.size());

   test = initiate.re_hamiltonian(rmesh,Ef,ll,jj); 

   eigen_t dom_wf_s = initiate.find_boundstate(rmesh, Ef, 1, 0, 0.5, tol);
   eigen_t dom_wf_d = initiate.find_boundstate(rmesh, Ef, 0, 2, 1.5, tol);

   ofstream dfile("wfdomd32.txt");
   ofstream sfile("wfdoms12.txt");

   double sf = initiate.sfactor(rmesh,dom_wf_d.first,2,1.5,dom_wf_d.second);

   //dfile<<"0.0 0.0"<<endl;
   //Going to start from 0.08, since this is what dweepy does for BSWF
   //even though the partial wave starts from 0 in dweepy...
   for(int i=0;i<rmesh.size();i++){
      if(i%2==1){
         dfile<<rmesh[i]<<" "<<dom_wf_d.second[i]<<endl;
         sfile<<rmesh[i]<<" "<<dom_wf_s.second[i]<<endl;
      }
   }

   double rms = 0.0;
   for(int i=0;i<rmesh.size();i++){
      rms += pow(dom_wf_d.second[i]*rmesh[i]*rmesh[i],2) * rdelt;
   }
   rms = sqrt(rms);

   cout<<"rms = "<<rms<<endl;

   cout<<"d3/2 spectroscopic factor = "<<sf<<endl;
   cout<<"d3/2 bound energy = "<<dom_wf_d.first<<endl;
   cout<<"s1/2 bound energy = "<<dom_wf_s.first<<endl;
   cout<<"Fermi Energy = "<<Ef<<endl;

   double  rdelt_p = rdelt / 1.025641026;

   double Emax = 2*Ef;
   double Emin=-200.0 + Emax;

   string title = "pca40";
   string* title0 = &title;

   double E0 = 0.52;

   ofstream rfile("react2.txt");

   //for(int j=1;j<201;j++){
   //      double Elab = E0 + j;

   double Elab = 100.0;

   /*
      if (Ecm < 0.) return Ecm/A*(1.+A);

   //find momentum of projecile, also momentum of target
   double pc = sqrt(Ecm)*sqrt((Ecm+2.*Mu)*(Ecm+2.*A*
   Mu)*
   (Ecm+2.*(A+1.)*scatterRspace::m0))/2./(Ecm+(A+1)
    *Mu);
   //velocity of target in units of c
   double vtarget = pc/sqrt(pow(pc,2)+pow(A*Mu,2));
   //gamma factor for this velocity
   double gam = 1./sqrt(1.-pow(vtarget,2));
   // tot energy of projectile (neutron or proton in com frame)
   double Eproj = sqrt(pow(Mu,2)+pow(pc,2));
   double Elab = (Eproj + vtarget*pc)*gam;
   //this energy contains rest mass , so remove it 
   Elab -= Mu;
   */

   //  A = Nu.A-1;

   if (Elab < 0.) return Elab*A/(1.+A);
   // center of mass velocity in units of c
   double vcm = sqrt(Elab*(Elab+2.*scatterRspace::m0))/(Elab+(1.+A)*
         scatterRspace::m0);
   //gamma factor for this velocity
   double gam = 1./sqrt(1.-std::pow(vcm,2));
   double Ecm = (gam-1.)*(1.+A)*scatterRspace::m0 +
      gam*Elab*(A-1.)*scatterRspace::m0/((A+1.)*
            scatterRspace::m0+Elab);


   ////Just using the exact same com energy from e'p code...
   ////Ecm = 96.4967424;


   //scatterRspace scat(Nu.Z,1,Nu.A,pott,title0);

   //scat.getSmatrix(Ecm,Elab);

   
   //ofstream eout("elast.txt");
   //ofstream rout("ruth.txt");
   //ifstream din("cross.dat");
   //ofstream dout("cross.txt");
   ////ofstream eout("anal.txt");
   //double ruth,cross,angle;
   //double data,error,theta;
   //int count = 22;
   
   ////Just needed to run this once to adjust the data by dividing out rutherford
   //for(int i=0;i<count;i++){
      //din >> theta >> data >> error;
      //ruth = scat.Rutherford(theta*3.14159/180);
      //data = data / ruth;
      //error = error / ruth;
      //dout << theta << " " << data << " " << error << endl;
   //}
   //din.close();
   //dout.close();

   //// testing out differential cross section

   //count = 1000;
   //for(int i=1;i<count;i++){
      //angle = i *(3.14159/count/2);
      //cross = scat.DifferentialXsection(angle);
      //ruth = scat.Rutherford(angle);
      //angle = angle * (180.0/3.14159);
      //eout<<angle<<" "<<cross/ruth<<endl;
      //rout<<angle<<" "<<ruth<<endl;
   //}
   //eout.close();

   //string Estring;
   //ostringstream convert;
   //convert << Elab ;
   //Estring = convert.str();

   //double react = scat.AbsorptionXsection();

   //rfile<<Elab<<" "<<react<<endl;

   //}
} //end of main
示例#17
0
bool UserManagerBackend::commit()
{
    
    //Process users
    QMap<QString, User>::Iterator userIt;

    QStringList args;
    
    for ( userIt = userList.begin(); userIt != userList.end(); ++userIt )
    {
	args.clear();
        switch(userIt->getStatus())
        {
            case 1:
                //Modify User
                qDebug() << "Modifying user " << userIt->getUsername();
		if ( ! chroot.isEmpty() )
		   args << chroot << "pw";
                args << "usermod";
                args << userIt->getUsername();
		// Only change home-dir on non-encrypted users
                if ( ! userIt->getEnc() ) {
                  args << "-d";
                  args << userIt->getHome();
		}
                args << "-s";
                args << userIt->getShell();
                args << "-c";
                args << userIt->getFullname();
		if ( ! chroot.isEmpty() )
		   QProcess::execute("chroot", args);
		else
		   QProcess::execute("pw", args);
                
                if (userIt->getPassword() != "")
                {
		    // Refuse to continue if we are trying to change PW
		    // On an encrypted users homedir
                    if ( userIt->getEnc() ) {
                      qDebug() << "Cannot change encrypted password: "******"Changing password: "******"/tmp/.XXXXXXXX");
  		    if ( rfile.open() ) {
       		      QTextStream stream( &rfile );
      		      stream << userIt->getClearPassword();
    		      rfile.close();
  		    }
		    if ( ! chroot.isEmpty() )
  		      system("cat " + rfile.fileName().toLatin1() + " | chroot " + chroot.toLatin1() + " pw usermod " + userIt->getUsername().toLatin1() + " -h 0 ");
		    else
  		      system("cat " + rfile.fileName().toLatin1() + " | pw usermod " + userIt->getUsername().toLatin1() + " -h 0 ");

  		    rfile.remove();
                }
                break;
            case 2:
	    {
                //Add User
                qDebug() << "Adding user " << userIt->getUsername();
		// Create the new home-directory
		if ( chroot.isEmpty() ) {
		   system("/usr/local/share/pcbsd/scripts/mkzfsdir.sh " + userIt->getHome().toLatin1() );
		   system("pw groupadd " + userIt->getUsername().toLatin1() );
		} else {
		   system("mkdir -p " + chroot.toLatin1() + "/" + userIt->getHome().toLatin1() + " 2>/dev/null" );
		   system("chroot " + chroot.toLatin1() + " ln -s /usr/home /home 2>/dev/null" );
		   system("chroot " + chroot.toLatin1() + " pw groupadd " + userIt->getUsername().toLatin1() );
		}

		if ( ! chroot.isEmpty() )
		   args << chroot << "pw";
                args << "useradd";
                args << userIt->getUsername();
                args << "-c";
                args << userIt->getFullname();
		args << "-m";
                args << "-d";
                args << userIt->getHome();
                args << "-s";
                args << userIt->getShell();
                if (userIt->getGid() != -1)
                {
                    args << "-g";
                    args << QString::number(userIt->getGid());
		} else {
                    args << "-g";
                    args << userIt->getUsername();
                }
                args << "-G";
                args << "operator";
		if ( ! chroot.isEmpty() )
		   QProcess::execute("chroot", args);
		else
		   QProcess::execute("pw", args);

    		QTemporaryFile nfile("/tmp/.XXXXXXXX");
  		if ( nfile.open() ) {
       		  QTextStream stream( &nfile );
      		  stream << userIt->getClearPassword();
    		  nfile.close();
  		}
		if ( ! chroot.isEmpty() )
  		  system("cat " + nfile.fileName().toLatin1() + " | chroot " + chroot.toLatin1() + " pw usermod " + userIt->getUsername().toLatin1() + " -h 0 ");
		else
  		  system("cat " + nfile.fileName().toLatin1() + " | pw usermod " + userIt->getUsername().toLatin1() + " -h 0 ");
  	        nfile.remove();

		if ( chroot.isEmpty() ) {
		   qDebug() << "Enabling Flash Plugin for " << userIt->getUsername();
		   QString flashCmd = "su " + userIt->getUsername() + " -c \"flashpluginctl on\"";
		   system(flashCmd.toLatin1());
		}

		// Set permissions
		if ( chroot.isEmpty() )
		   system("chown -R " + userIt->getUsername().toLatin1() +":" + userIt->getUsername().toLatin1() + " "  + userIt->getHome().toLatin1() );
		else
		   system("chroot " + chroot.toLatin1() + " chown -R " + userIt->getUsername().toLatin1() +":" + userIt->getUsername().toLatin1() + " "  + userIt->getHome().toLatin1() );

		// Are we enabling encryption?
		if ( userIt->getEnc() ) {
		   QProcess::execute("enable_user_pefs", QStringList() << userIt->getUsername() << userIt->getClearPassword() );

		}

                break;
	    }
            case 3:
                //Delete User
                qDebug() << "Deleting user " << userIt->getUsername();

                if(userIt->getEnc()) {
		  // Unmount PEFS
	  	  system("umount " + userIt->getHome().toLatin1() );
		}
		if ( ! chroot.isEmpty() )
		   args << chroot << "pw";
                args << "userdel";
                args << userIt->getUsername();
                if(userIt->getDeleteHome()) {
			args << "-r";
			system("/usr/local/share/pcbsd/scripts/rmzfsdir.sh " + userIt->getHome().toLatin1() );
		}
		if ( ! chroot.isEmpty() )
		   QProcess::execute("chroot", args);
		else
		   QProcess::execute("pw", args);
                break;
        }
    }
    refreshUsers();
    
    //Process groups
    QMap<int, Group>::Iterator groupIt;
 
    for ( groupIt = groupList.begin(); groupIt != groupList.end(); ++groupIt )
    {
	args.clear();
        switch(groupIt->getStatus())
        {
            case 1:
                //Modify Group
                qDebug() << "Modifying group " << groupIt->getGroupname();
		if ( ! chroot.isEmpty() )
		   args << chroot << "pw";
		args << "groupmod";
		args << groupIt->getGroupname();
		args << "-M";
		args << groupIt->getMembers().join(",");
		if ( ! chroot.isEmpty() )
		   QProcess::execute("chroot", args);
		else
		   QProcess::execute("pw", args);
                break;
            case 2:
                //Add Group
                qDebug() << "Adding group " << groupIt->getGroupname();
		if ( ! chroot.isEmpty() )
		   args << chroot << "pw";
                args << "groupadd";
                args << groupIt->getGroupname();
                args << "-M";
                args << groupIt->getMembers().join(",");
		if ( ! chroot.isEmpty() )
		   QProcess::execute("chroot", args);
		else
		   QProcess::execute("pw", args);
                break;
            case 3:
                //Delete Group
                qDebug() << "Deleting group " << groupIt->getGroupname();
		if ( ! chroot.isEmpty() )
		   args << chroot << "pw";
                args << "groupdel";
                args << groupIt->getGroupname();
		if ( ! chroot.isEmpty() )
		   QProcess::execute("chroot", args);
		else
		   QProcess::execute("pw", args);
                break;
	}
    }
    refreshGroups();
    emit groupsChanged();
    emit usersChanged();
    
    return true;
}
示例#18
0
int main(int argc,char** argv) {

#ifdef INLIB_MEM
  inlib::mem::set_check_by_class(true);{
#endif //INLIB_MEM

  inlib::args args(argc,argv);

  std::string file;
  if(!args.file(file)) {
    std::cout << " give a root file." << std::endl;
    return EXIT_FAILURE;
  }

  bool verbose = args.is_arg("-verbose");
  bool ls = args.is_arg("-ls");
  bool dump = args.is_arg("-dump");

 {bool is;
  inlib::file::is_root(file,is);
  if(!is) {
    std::cout << " file is not a root file." << std::endl;
    return EXIT_FAILURE;
  }}

  inlib::rroot::file rfile(std::cout,file,verbose);
#ifdef EXLIB_DONT_HAVE_ZLIB
#else
  rfile.add_unziper('Z',exlib::decompress_buffer);
#endif

  if(ls) {
    std::cout << "format version " << rfile.version() << std::endl;
  }
      
  const std::vector<inlib::rroot::key*>& keys = rfile.dir().keys();
  inlib::rroot::read(std::cout,rfile,keys,true,ls,dump,0);

  ///////////////////////////////////////////////////////////////
  /// if reading the wroot.root produced with wroot.cpp : ///////
  ///////////////////////////////////////////////////////////////
 {inlib::rroot::TDirectory* dir = inlib::rroot::find_dir(rfile.dir(),"histo");
  if(dir) {
   {inlib::rroot::key* key = dir->find_key("rg");
    if(key) {
      inlib::histo::h1d* h = inlib::rroot::key_to_h1d(*key);
      if(h) {
        std::cout << "h1d : " << h->title()
                  << ", all_entries " << h->all_entries()
                  << ", entries " << h->entries()
                  << ", mean " << h->mean() << ", rms " << h->rms()
                  << std::endl;
        delete h;
      }
    }}
   {inlib::rroot::key* key = dir->find_key("rf");
    if(key) {
      inlib::histo::h1d* h = inlib::rroot::key_to_h1d(*key);
      if(h) {
        std::cout << "h1d : " << h->title()
                  << ", all_entries " << h->all_entries()
                  << ", entries " << h->entries()
                  << ", mean " << h->mean() << ", rms " << h->rms()
                  << std::endl;
        delete h;
      }
    }}
   {inlib::rroot::key* key = dir->find_key("rgbw");
    if(key) {
      inlib::histo::h2d* h = inlib::rroot::key_to_h2d(*key);
      if(h) {
        std::cout << "h2d : " << h->title()
                  << ", all_entries " << h->all_entries()
                  << ", entries " << h->entries()
                  << ", mean_x " << h->mean_x() << ", rms_x " << h->rms_x()
                  << ", mean_y " << h->mean_y() << ", rms_y " << h->rms_y()
                  << std::endl;
        delete h;
      }
    }}
   {inlib::rroot::key* key = dir->find_key("prof");
    if(key) {
      inlib::histo::p1d* h = inlib::rroot::key_to_p1d(*key);
      if(h) {
        std::cout << "p1d : " << h->title()
                  << ", all_entries " << h->all_entries()
                  << ", entries " << h->entries()
                  << ", mean " << h->mean() << ", rms " << h->rms()
                  << std::endl;
        delete h;
      }
    }}
   {inlib::rroot::key* key = dir->find_key("prof2D");
    if(key) {
      inlib::histo::p2d* h = inlib::rroot::key_to_p2d(*key);
      if(h) {
        std::cout << "p2d : " << h->title()
                  << ", all_entries " << h->all_entries()
                  << ", entries " << h->entries()
                  << ", mean_x " << h->mean_x() << ", rms_x " << h->rms_x()
                  << ", mean_y " << h->mean_y() << ", rms_y " << h->rms_y()
                  << std::endl;
        delete h;
      }
    }}
   {inlib::rroot::key* key = dir->find_key("rggbw");
    if(key) {
      inlib::histo::h3d* h = inlib::rroot::key_to_h3d(*key);
      if(h) {
        std::cout << "h3d : " << h->title()
                  << ", all_entries " << h->all_entries()
                  << ", entries " << h->entries()
                  << ", mean_x " << h->mean_x() << ", rms_x " << h->rms_x()
                  << ", mean_y " << h->mean_y() << ", rms_y " << h->rms_y()
                  << ", mean_z " << h->mean_z() << ", rms_z " << h->rms_z()
                  << std::endl;
        delete h;
      }
    }}
    delete dir; 
  }}
  // read an ntuple :
 {inlib::rroot::key* key = rfile.dir().find_key("rg_rbw");
  if(key) {
    unsigned int sz;
    char* buf = key->get_object_buffer(sz);
    if(!buf) {
      std::cout << "can't get data buffer for ntuple." << std::endl;
      return EXIT_FAILURE;
    }
    inlib::rroot::buffer b(std::cout,rfile.byte_swap(),sz,buf,key->key_length(),verbose);
    inlib::rroot::fac fac(rfile);
    inlib::rroot::tree tree(rfile,fac);
    if(!tree.stream(b)) {
      std::cout << "TTree streaming failed." << std::endl;
      return EXIT_FAILURE;
    }
    tree.dump(std::cout,"","  ");
    //inlib::uint64 entries = tree.entries();
   {for(inlib::uint32 i=0;i<5;i++){
      if(!tree.show(std::cout,i)) {
        std::cout << "show failed for entry " << i << std::endl;
        return EXIT_FAILURE;
      }
    }}

    // read with the flat ntuple API :
   {inlib::rroot::ntuple ntu(tree); //use the flat ntuple API.
    inlib::ntuple_binding nbd;
    double v_rgauss;
    nbd.add_column("rgauss",v_rgauss);
    std::string v_string;
    nbd.add_column("strings",v_string);
    if(!ntu.initialize(std::cout,nbd)) {
      std::cout << "can't initialize ntuple with ntuple_binding." << std::endl;
      return EXIT_FAILURE;
    }
    inlib::histo::h1d hg("rgauss",100,-5,5);
    ntu.start();
    unsigned int count = 0;
    while(ntu.next()){
      if(!ntu.get_row()) {
        std::cout << "get_row() failed." << std::endl;
        return EXIT_FAILURE;
      }
      hg.fill(v_rgauss);
      if(count<5) std::cout << "v_string " << v_string << std::endl;
      count++;
    }
    std::cout << "ntuple_binding(rgauss) : " << hg.mean() << " " << hg.rms() << std::endl;}

  }}

  ///////////////////////////////////////////////////////////////
  /// if reading the pawdemo.root : /////////////////////////////
  ///////////////////////////////////////////////////////////////
 {inlib::rroot::key* key = rfile.dir().find_key("h10");
  if(key) {
    inlib::histo::h1d* h = inlib::rroot::key_to_h1d(*key);
    if(h) {
      std::cout << "h1d : h10"
                << ", all_entries " << h->all_entries()
                << ", entries " << h->entries()
                << ", mean " << h->mean() << ", rms " << h->rms()
                << std::endl;
      delete h;
    }
  }}

  /////////////////////////////////////////////////////////////////////
  /// if reading the prof.root produced with croot_TProfile.cpp : /////
  /////////////////////////////////////////////////////////////////////
 {inlib::rroot::key* key = rfile.dir().find_key("prof");
  if(key) {
    inlib::histo::p1d* h = inlib::rroot::key_to_p1d(*key);
    if(h) {
      std::cout << "p1d : prof"
                << ", all_entries " << h->all_entries()
                << ", entries " << h->entries()
                << ", mean " << h->mean() << ", rms " << h->rms()
                << std::endl;
      delete h;
    }
  }}
 {inlib::rroot::key* key = rfile.dir().find_key("prof2D");
  if(key) {
    inlib::histo::p2d* h = inlib::rroot::key_to_p2d(*key);
    if(h) {
      std::cout << "p2d : prof"
                << ", all_entries " << h->all_entries()
                << ", entries " << h->entries()
                << ", mean_x " << h->mean_x() << ", rms_x " << h->rms_x()
                << ", mean_y " << h->mean_y() << ", rms_y " << h->rms_y()
                << std::endl;
      delete h;
    }
  }}

#ifdef INLIB_MEM
  }inlib::mem::balance(std::cout);
#endif //INLIB_MEM

  return EXIT_SUCCESS;
}
示例#19
0
int main(int,char**) {

#ifdef INLIB_MEM
  inlib::mem::set_check_by_class(true);{
#endif //INLIB_MEM

  //////////////////////////////////////////////////////////
  /// create a .root file : ////////////////////////////////
  //////////////////////////////////////////////////////////
  std::string file = "wroot_tree.root";
  inlib::wroot::file rfile(std::cout,file);
  rfile.add_ziper('Z',exlib::compress_buffer);
  rfile.set_compression(9);

  //////////////////////////////////////////////////////////
  /// create and fill a tree : /////////////////////////////
  //////////////////////////////////////////////////////////
 {//WARNING : the tree can't be on the stack. It is owned
  //          by the directory.
  inlib::wroot::tree* tr = 
    new inlib::wroot::tree(rfile.dir(),"tree","first tree");

  inlib::wroot::branch* br = tr->create_branch("branch");
  inlib::wroot::leaf<int>* leaf_index =
    br->create_leaf<int>("index","index");
  inlib::wroot::leaf<double>* leaf_rgauss =
    br->create_leaf<double>("rgauss","Random gaussian");
  inlib::wroot::leaf<float>* leaf_rbw =
    br->create_leaf<float>("rbw","Random BW");
  
  inlib::rgaussd rg(1,2);
  inlib::rbwf rbw(0,1);
  // fill :
  unsigned int entries = 1000000;
  //unsigned int entries = 400000000; //to test >2Gbytes file.
  //br->set_basket_size(1000000);
  for(unsigned int count=0;count<entries;count++) {    
    //inlib::count_out<unsigned int>(std::cout,count,1000000);
    leaf_index->fill(count);
    leaf_rgauss->fill(rg.shoot());
    leaf_rbw->fill(rbw.shoot());
    inlib::uint32 n;
    if(!tr->fill(n)) {
      std::cout << "tree fill failed." << std::endl;
      break;
    }
  }}

  //////////////////////////////////////////////////////////
  /// write and close file : ///////////////////////////////
  //////////////////////////////////////////////////////////
 {unsigned int n;
  if(!rfile.write(n)) {
    std::cout << "file write failed." << std::endl;
  }}
  
  rfile.close();

  //////////////////////////////////////////////////////////
  //////////////////////////////////////////////////////////
  //////////////////////////////////////////////////////////

#ifdef INLIB_MEM
  }inlib::mem::balance(std::cout);
#endif //INLIB_MEM

  return EXIT_SUCCESS;
}
//------------------------------------------------------------------------------
bool MainWindow::editOutputFile(QString inputPath, QString meCabOutputPath, QString outputPath, QString maskColumnNo)
{
    bool stat = true;
    QString errmsg = "";
    int col = 0;
    QTextCodec *codec = QTextCodec::codecForName("Shift-JIS");
    QTextDecoder *decoder = codec->makeDecoder();
    QTextEncoder *encoder = codec->makeEncoder();
    
    QFile wfile(outputPath);
    QFile rfileMeCab(meCabOutputPath);
    QFile rfile(inputPath);
    if (wfile.open(QIODevice::WriteOnly | QIODevice::Text)){
        if (rfileMeCab.open(QIODevice::ReadOnly | QIODevice::Text)){
            if(maskColumnNo != ""){
                if (rfile.open(QIODevice::ReadOnly | QIODevice::Text)){
                    bool ok;
                    col = maskColumnNo.toInt(&ok, 10);
                    if(! ok){
                        errmsg = tr("Illegal Mask Column No.") + "(" + maskColumnNo + ")";
                        rfile.close();
                        stat = false;
                    }
                }
                else{
                    // Can't open input file.
                    errmsg = tr("Can't open the intput file.") + "(" + inputPath + ")";
                    stat = false;
                }
            }
            
            if(stat){
                QString outline = "";
                while (!rfileMeCab.atEnd()) {
                    QByteArray line = rfileMeCab.readLine();
                    //QString str = decoder->toUnicode(line);
                    QString str = line;
                    if(str == "EOS\n"){
                        if(maskColumnNo != ""){
                            QByteArray wline = rfile.readLine();
                            str = wline;
                            QStringList wlist = str.split("\t", QString::KeepEmptyParts, Qt::CaseSensitive);
                            str = outline;
                            outline = "";
                            for(int ii = 0; ii < wlist.count(); ii++){
                                if(outline != ""){
                                    outline += "\t";
                                }
                                if(ii == col){
                                    outline += str;
                                }
                                else{
                                    outline += wlist[ii];
                                }
                            }
                        }
                        wfile.write((outline + "\n").toAscii());
                        outline = "";
                    }
                    else{
                        QStringList wlist = str.split("\t", QString::KeepEmptyParts, Qt::CaseSensitive);
                        if(wlist[1].left(13) == "����,�ŗL����"){
                            QString unicodeStr = decoder->toUnicode(wlist[0].toAscii());
                            QString maskStr = unicodeStr.replace(QRegExp("."), decoder->toUnicode("��"));
                            outline += encoder->fromUnicode(maskStr);
                        }
                        else{
                            outline += wlist[0];
                        }
                    }
                }
                rfileMeCab.close();
                if(maskColumnNo != ""){
                    rfile.close();
                }
            }
        }
        else{
            // Can't open MeCab output file.
            errmsg = tr("Can't open the MeCab output file.") + "(" + meCabOutputPath + ")";
            stat = false;
        }
        
        wfile.close();
    }
    else{
        // Can't open the output file.
        errmsg = tr("Can't open the output file.") + "(" + outputPath + ")";
        stat = false;
    }
    
    if(! stat){
        QMessageBox::StandardButton reply;
        reply = QMessageBox::critical(this, tr("ERROR"),
            errmsg,
            QMessageBox::Abort);
        if (reply == QMessageBox::Abort){
            close();
        }
    }
    
    return stat;
}
示例#21
0
BINKFLIC *BinkOpenFlic( const CHAR8 *cFilename )
{
	BINKFLIC *pBink;

	// Get an available flic slot from the list
	if( !( pBink = BinkGetFreeFlic() ) )
	{
		ErrorMsg("BINK ERROR: Out of flic slots, cannot open another");
		return(NULL);
	}
#ifndef USE_VFS
	// Attempt opening the filename
	if(!(pBink->hFileHandle = FileOpen( const_cast<CHAR8*>(cFilename), FILE_OPEN_EXISTING | FILE_ACCESS_READ, FALSE ) ) )
	{
		ErrorMsg("BINK ERROR: Can't open the BINK file");
		return(NULL);
	}

	//Get the real file handle for the file man handle for the smacker file
	HANDLE hFile = GetRealFileHandleFromFileManFileHandle( pBink->hFileHandle );
#else
	vfs::Path introname(cFilename);
	vfs::Path dir,filename;
	introname.splitLast(dir,filename);
	vfs::Path tempfile = vfs::Path(L"Temp") + filename;
	if(!getVFS()->fileExists(tempfile))
	{
		try
		{
			if(!getVFS()->fileExists(introname))
			{
				return NULL;
			}
			vfs::COpenReadFile rfile(introname);
			vfs::size_t size = rfile->getSize();
			std::vector<vfs::Byte> data(size);
			rfile->read(&data[0],size);

			vfs::COpenWriteFile wfile(tempfile,true);
			wfile->write(&data[0],size);
		}
		catch(std::exception& ex)
		{
			SGP_RETHROW(_BS(L"Intro file \"") << filename << L"\" could not be extracted" << _BS::wget, ex);
		}
	}
#endif

#ifndef USE_VFS
	if( !( pBink->BinkHandle = BinkOpen((CHAR8 *)hFile, BINKFILEHANDLE ) ) ) //| SMACKTRACKS 
#else
	vfs::Path tempfilename;
	try
	{
		vfs::COpenWriteFile wfile(tempfile);
		if(!wfile->_getRealPath(tempfilename))
		{
			return NULL;
		}
	}
	catch(std::exception& ex)
	{
		SGP_RETHROW(L"Temporary intro file could not be read", ex);
	}
	if( !( pBink->BinkHandle = BinkOpen(tempfilename.to_string().c_str(), BINKNOTHREADEDIO /*BINKFILEHANDLE*/ ) ) ) //| SMACKTRACKS 
#endif
	{
		ErrorMsg("BINK ERROR: Bink won't open the BINK file");
		return(NULL);
	}

	// Make sure we have a video surface
	BinkSetupVideo();

	pBink->cFilename = cFilename;

	pBink->lpDDS = lpBinkVideoPlayback2;

	pBink->hWindow = hBinkDisplayWindow;

	// Bink flic is now open and ready to go
	pBink->uiFlags |= BINK_FLIC_OPEN;

	return( pBink );
}
示例#22
0
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
void PMFileGenerator::generateOutputWithFilterNames(QSet<QString> names)
{
  //  qDebug() << "PMFileGenerator::generateOutput" << "\n";
  if (doesGenerateOutput() == false)
  {
    return;
  }

  //Get text feature values from widget
  QString pluginName = getPluginName();
  QString pluginDir = getOutputDir();

  if (pluginName.isEmpty() == true || pluginDir.isEmpty() == true)
  {
    return;
  }

  //  QString classNameLowerCase = m_ClassName.toLower();

  //Open file
  QFile rfile(getCodeTemplateResourcePath());
  if (rfile.open(QIODevice::ReadOnly | QIODevice::Text))
  {
    QTextStream in(&rfile);
    QString text = in.readAll();

    text.replace("@PluginName@", pluginName);
    QFileInfo fi(m_FileName);
    QString className = fi.baseName();
    text.replace("@ClassName@", className);
    text.replace("@MD_FILE_NAME@", m_FileName);
    text.replace("@ClassNameLowerCase@", className.toLower());
    text.replace("@FilterGroup@", pluginName);
    text.replace("@FilterSubgroup@", pluginName);

    if (names.isEmpty() == false)
    {
      if (getFileName() == "TestFileLocations.h.in")
      {
        QString replaceStr = createReplacementString(TESTFILELOCATIONS, names);
        text.replace("@Namespaces@", replaceStr);   // Replace token for Test/TestFileLocations.h.in file
      }
      else if (getFileName() == "CMakeLists.txt")
      {
        QString replaceStr = createReplacementString(CMAKELISTS, names);
        text.replace("@AddTestText@", replaceStr);    // Replace token for Test/CMakeLists.txt file
      }
    }
    else
    {
      text.replace("\n  @Namespaces@\n", "");   // Replace token for Test/TestFileLocations.h.in file
      text.replace("\n@AddTestText@\n", "");    // Replace token for Test/CMakeLists.txt file
    }

    QString parentPath = getOutputDir() + QDir::separator() + getPathTemplate().replace("@PluginName@", getPluginName());
    parentPath = QDir::toNativeSeparators(parentPath);

    QDir dir(parentPath);
    dir.mkpath(parentPath);

    parentPath = parentPath + QDir::separator() + m_FileName;
    //Write to file
    QFile f(parentPath);
    if (f.open(QIODevice::WriteOnly | QIODevice::Text))
    {
      QTextStream out(&f);
      out << text;
    }
  }
}
示例#23
0
void konsole::execCommand()
{
bool executed = false;
QString inputstring = input->text();
if(!inputstring.isEmpty())
{
	lastcommands << inputstring;
// lc_iterator.toBack();
	row = lastcommands.size();
}
output->appendPlainText(QString(inputstring).prepend("> "));

if(inputstring.startsWith("load "))
{
	executed = true;
	QString filestring = QString(inputstring).remove("load ");
	if(QFile(filestring).exists())
	{
// 	karteladen(QString(inputstring).remove("load "));
		qWarning() << "Load: " << filestring;
		output->appendPlainText(QString("Load: ").append(filestring));
		if(filestring.endsWith(".ohm"))
		{
			emit sig_command(inputstring.simplified());
			return;
		}
		else if(filestring.endsWith(".ohs"))		//Savegame
		{
			return;
		}
		else if(filestring.endsWith(".oht"))		//Script
		{
			return;
		}
		else
		{
			QFile rfile(filestring);
			rfile.open(QIODevice::ReadOnly|QIODevice::Text);
			output->appendPlainText(rfile.readAll());
			rfile.close();
		}
	}
	else
	{
	output->appendPlainText(tr("Fehler: Datei nicht gefunden: \"").append(filestring).append("\" !"));
	}
}

else if(inputstring.startsWith("echo "))
{
	output->appendPlainText(inputstring.remove("echo "));
	return;
}

else if(QString(inputstring).simplified().contains(" sidemenu"))
{
	emit sig_command(inputstring);
	return;
}

else if(inputstring.isEmpty() || QString(inputstring).remove(" ").isEmpty() ||  QString(inputstring).simplified().isEmpty())
{
	return;
}

else if(inputstring == "test a")
{
	emit sig_command(inputstring);
	return;
}

else if(inputstring == "print Shipposition")
{
GAMEDATA->activeShip()->printPosition();
return;
}

else if(inputstring.startsWith("print Citygoods"))
{
bool printed = false;
QList<CityClass> citylist = *GAMEDATA->cityList();
QString cityname = QString(inputstring).remove("print Citygoods ");
qWarning() << "Cityname:" << cityname << "Inputstring:" << inputstring ;

if(!cityname.isEmpty())
{
	for(QList<CityClass>::iterator it = citylist.begin();
	it != citylist.end();
	++it)
	{
	qWarning() << "It->cityname():" << it->cityname();
		if(it->cityname() == cityname)
		{
			it->printGoods();
			printed = true;
		}
	}
}
if(!printed)
{
OHDebug(QString(cityname).prepend("City \"").append("\" not found!"));
}
return;
}

else if(inputstring == QString("gametime"))
{
// output->appendPlainText(QString("%1.%2.%3, %4:%5").arg(QChar(GAMEDATA->gametime().retDay()), QChar(GAMEDATA->gametime().retMonth()), QChar(GAMEDATA->gametime().retYear()), QChar(GAMEDATA->gametime().retHour()), QChar(int(GAMEDATA->gametime().retMinute()))));
output->appendPlainText(QString("%1.%2.%3, %4:%5").arg(QString("%1").arg(GAMEDATA->gametime().day()), QString("%1").arg(GAMEDATA->gametime().month()), QString("%1").arg(GAMEDATA->gametime().year()), QString("%1").arg(GAMEDATA->gametime().hour()), QString("%1").arg(GAMEDATA->gametime().minute())));

qWarning() << QString("%1.%2.%3, %4:%5").arg(QString("%1").arg(GAMEDATA->gametime().day()), QString("%1").arg(GAMEDATA->gametime().month()), QString("%1").arg(GAMEDATA->gametime().year()), QString("%1").arg(GAMEDATA->gametime().hour()), QString("%1").arg(GAMEDATA->gametime().minute()));
return;
}

if(!executed)
{
	output->appendPlainText(tr("Error: unknown Command \"").append(inputstring).append("\" !"));
}
}
示例#24
0
int main(){

   sky sky;

   double hbarc = 197.327;

   double Mu = M;   //Mass in MeV
   cout<<Mu<<endl;
   complex <double> M_I(0,1);

   // Create momentum space grid
   std::vector<double> kmesh;
   std::vector<double> kweights;
   double const kmax = 5.0;
   int const kpts = 170;
   kmesh.resize( kpts );
   kweights.resize( kpts );
   GausLeg( 0., kmax, kmesh, kweights );

   ////////Input Parameters of the potential (fit parameters) /////
   std::string parameters_filename="Input.inp";

   NuclearParameters Nu = read_nucleus_parameters( "Input/pca40.inp" );

   //I'm altering the potential to represent ca40 after a proton is removed (i.e. the potential for K39)
   /*Nu.A = 39.0;
     Nu.Z = 19.0;

     cout<<Nu.Z<<" "<<Nu.A<<endl;
     */

   double Ef=Nu.Ef;
   int lmax=20;
   double zp0;
   double tz=0.5;

   int type=1;
   int mvolume = 4;
   int AsyVolume = 1;

   double A = Nu.A;

   double  mu = (A)/((A-1.));

   if (tz>0) { zp0=1;}
   else {zp0=0;}

   double ph_gap = Nu.ph_gap;
   cout<<"ph_gap = "<<Nu.ph_gap<<endl;
   double  rStart = .05;
   double  rmax = 13.51999;
   int  ham_pts = 340; //300 for highR 

   double  rdelt = rmax / (ham_pts-2);
   cout<<"rdelt = "<<rdelt<<endl;

   vector<double> dr;
   dr.assign(ham_pts,rdelt);

   // Construct Parameters Object
   Parameters p = get_parameters( parameters_filename, Nu.A, Nu.Z, zp0 );
   // Construct Potential Object
   pot pottt = get_bobs_pot2( type, mvolume, AsyVolume, tz, Nu, p );
   pot * pott = &pottt;
   cout<<"kconstant = "<<pott->kconstant<<endl;

   boundRspace initiate(rmax , ham_pts , Ef, ph_gap , lmax , Nu.Z , zp0 , Nu.A, pott);

   double Elower = -11.61818;
   double Eupper = -9.4;
   double jj = .5;
   int ll = 0;
   int Ifine = 1;
   initiate.searchNonLoc( Elower, Eupper, jj,  ll,  Ifine);
   initiate.exteriorWaveFunct(ll);
   initiate.normalizeWF();


   double tol=.01;
   double estart=Ef;

   ///// Making rmesh///

   std::vector<double> rmesh_p= initiate.make_rmesh_point();
   std::vector<double> rmesh= initiate.make_rmesh();

   //int J=0.5;
   //lmax=6;
   //for(int L=0;L<lmax+1;L++){
   //	for(int s=0;s<2;s++){	
   //		J=L-0.5+s;
   //		if(J<0){
   //			J=0.5;
   //			s=1;
   //		}	
   //
   //		string slab;
   //		ostringstream convert;
   //		convert << s;
   //		slab = convert.str();
   //
   //		string jlab = sky.jlab(J);
   //		string llab = sky.llab(L);
   //	
   //		cout<<endl;
   //		cout<<"L = "<<L<<" J = "<<J<<endl;
   //		cout<<endl;
   //
   //		int N = 0;
   //
   //            string preq = "waves/partials/dom/eep100";
   //            string instring = preq + sky.Nlab(L) + sky.Nlab(s+1) + ".txt"; 
   //            cout<<instring<<endl;
   //	ifstream filein(instring.c_str());
   //      cout<<filein<<endl;
   //	vector <double> par;
   //	par.assign(rmesh.size(),0);
   //	std::string line;
   //	int i;
   //	i=0;
   //	while(getline(filein,line)){
   //		par[i] = atof(line.c_str());
   //            cout<<par[i]<<endl;
   //		i++;
   //	}
   //      cout<<"i = "<<i<<endl;
   //	filein.close();		
   //            vector<double> park = sky.four(L,par,rmesh,kmesh);
   //
   //            
   //		string fname = "waves/kwave/dom/" + llab +  slab + ".txt";
   //		ofstream ffile(fname.c_str());
   //            
   //            for(int i=0;i<kmesh.size();i++){
   //                  ffile<<kmesh[i]<<" "<<park[i]<<endl;
   //            }
   //
   //      }
   //}
   //
   //cout<<"done fourier transforming"<<endl;

   matrix_t test(rmesh.size(),rmesh.size());

   test = initiate.re_hamiltonian(rmesh,Ef,ll,jj); 

   eigen_t dom_wf_s = initiate.find_boundstate(rmesh, Ef, 1, 0, 0.5, tol);
   eigen_t dom_wf_d = initiate.find_boundstate(rmesh, Ef, 0, 2, 1.5, tol);

   ofstream dfile("wfdomd32.txt");
   ofstream sfile("wfdoms12.txt");

   double sf = initiate.sfactor(rmesh,dom_wf_d.first,2,1.5,dom_wf_d.second);

   sfile<<rmesh[0]<<" "<<dom_wf_s.second[0]<<endl;
   dfile<<"0.0 0.0"<<endl;
   for(int i=0;i<rmesh.size()-1;i++){
      if(i%2==1){
         dfile<<rmesh[i]<<" "<<dom_wf_d.second[i]<<endl;
         sfile<<rmesh[i]<<" "<<dom_wf_s.second[i]<<endl;
      }
   }

   double rms = 0.0;
   for(int i=0;i<rmesh.size();i++){
      rms += pow(dom_wf_d.second[i]*rmesh[i]*rmesh[i],2) * rdelt;
   }
   rms = sqrt(rms);

   cout<<"rms = "<<rms<<endl;

   cout<<"d3/2 spectroscopic factor = "<<sf<<endl;
   cout<<"d3/2 bound energy = "<<dom_wf_d.first<<endl;

   double  rdelt_p = rdelt / 1.025641026;

   double Emax = 2*Ef;
   double Emin=-200.0 + Emax;

   string title = "pca40";
   string* title0 = &title;

   double E0 = 0.52;

   ofstream rfile("react2.txt");

   //for(int j=1;j<201;j++){
   //      double Elab = E0 + j;

   double Elab = 100.0;

   /*
      if (Ecm < 0.) return Ecm/A*(1.+A);

   //find momentum of projecile, also momentum of target
   double pc = sqrt(Ecm)*sqrt((Ecm+2.*Mu)*(Ecm+2.*A*
   Mu)*
   (Ecm+2.*(A+1.)*scatterRspace::m0))/2./(Ecm+(A+1)
    *Mu);
   //velocity of target in units of c
   double vtarget = pc/sqrt(pow(pc,2)+pow(A*Mu,2));
   //gamma factor for this velocity
   double gam = 1./sqrt(1.-pow(vtarget,2));
   // tot energy of projectile (neutron or proton in com frame)
   double Eproj = sqrt(pow(Mu,2)+pow(pc,2));
   double Elab = (Eproj + vtarget*pc)*gam;
   //this energy contains rest mass , so remove it 
   Elab -= Mu;
   */

   //  A = Nu.A-1;

   if (Elab < 0.) return Elab*A/(1.+A);
   // center of mass velocity in units of c
   double vcm = sqrt(Elab*(Elab+2.*scatterRspace::m0))/(Elab+(1.+A)*
         scatterRspace::m0);
   //gamma factor for this velocity
   double gam = 1./sqrt(1.-std::pow(vcm,2));
   double Ecm = (gam-1.)*(1.+A)*scatterRspace::m0 +
      gam*Elab*(A-1.)*scatterRspace::m0/((A+1.)*
            scatterRspace::m0+Elab);


   //Just using the exact same com energy from e'p code...
   //Ecm = 96.4967424;


   //cout<<"A = "<<Nu.A<<" Z = "<<Nu.Z<<endl;
   //Doing the scattering from an N-1,A-1 nucleus
   scatterRspace scat(Nu.Z,1,Nu.A,pott,title0);

   scat.getSmatrix(Ecm,Elab);


   // testing out differential cross section

   //ofstream cfile("cross.txt");
   //
   //int count = 1000;
   //for(int i=0;i<count;i++){
   //double angle = i *(3.14159/count/2);
   //double cross = scat.DifferentialXsection(angle);
   //angle = angle * (180.0/3.14159);
   //cfile<<angle<<" "<<cross<<endl;
   //}
   string Estring;
   ostringstream convert;
   convert << Elab ;
   Estring = convert.str();

   double react = scat.AbsorptionXsection();

   rfile<<Elab<<" "<<react<<endl;

   //}
} //end of main
示例#25
0
void MainWindow::openDB(const QString &openDBName, bool useCP1250)
{
    if (openDBName.isNull())
        return;
    this->setEnabled(false); qApp->processEvents();
    try {
        QFile file(openDBName);
        if (!file.open(QFile::ReadOnly | QFile::Text)) {
            QMessageBox::critical(this, tr("Open database"), tr("Cannot read file %1:\n%2.").arg(openDBName).arg(file.errorString()));
            this->setEnabled(true); return;
        }
        setProgress(3); // PROGRESS >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
        QTextStream rfile(&file);
        if (useCP1250) {
            rfile.setCodec("CP 1250");
        } else {
            rfile.setCodec("UTF-8");
        }

        QString db_buffer;
        QStringList bufferlist;
        // ---------------------------------------------------------------------
        if (rfile.readLine() != "[ITEST_VERSION]") { throw xInvalidDBFile(0); }
        rfile.readLine();
        if (rfile.readLine() != "[ITEST_DB_VERSION]") { throw xInvalidDBFile(1); }
        double db_version = rfile.readLine().toDouble();
        if (db_version > F_ITDB_VERSION) {
            QMessageBox::critical(this, tr("iTest version notice"), tr("You need a newer version of iTest to open this database file."));
            this->setEnabled(true);
            return;
        }
        if (!useCP1250) {
            if (db_version == 1.0) {
                openDB(openDBName, true);
                return;
            }
        }

        if (rfile.readLine() != "[DB_NAME]") { throw xInvalidDBFile(10); }
        // Database name
        QString db_name = rfile.readLine();
        if (rfile.readLine() != "[DB_DATE]") { throw xInvalidDBFile(12); }
        // Database date
        QString db_date = rfile.readLine();
        if (rfile.readLine() != "[DB_DATE_ULSD]") { throw xInvalidDBFile(14); }
        // Use last save date
        rfile.readLine();
        if (rfile.readLine() != "[DB_COMMENTS]") { throw xInvalidDBFile(16); }
        // Database comments
        QString db_comments = rfile.readLine();
        if (rfile.readLine() != "[DB_QNUM]") { throw xInvalidDBFile(18); }
        // Question number
        int db_qnum = rfile.readLine().toInt();
        if (rfile.readLine() != "[DB_SNUM]") { throw xInvalidDBFile(20); }
        // Number of saved sessions
        int db_snum = rfile.readLine().toInt();
        int db_cnum = 0;
        if (db_version >= 1.35) {
            if (rfile.readLine() != "[DB_CNUM]") { throw xInvalidDBFile(22); }
            // Number of classes
            db_cnum = rfile.readLine().toInt();
        }
        if (rfile.readLine() != "[DB_FLAGS]") { throw xInvalidDBFile(50); }
        setProgress(6); // PROGRESS >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
        // Categories enabled
        db_buffer = rfile.readLine();
        QVector<bool> db_categories_enabled(db_buffer.length());
        for (int i = 0; i < db_categories_enabled.size(); ++i) {
            if (db_buffer.at(i) == '+') {
                db_categories_enabled[i] = true;
            } else if (db_buffer.at(i) == '-') {
                db_categories_enabled[i] = false;
            } else {
                throw xInvalidDBFile(52);
            }
        }
        // Categories
        QVector<QString> db_categories(db_buffer.length());
        for (int i = 0; i < db_categories.size(); ++i) {
            if (rfile.readLine() != QString("[DB_F%1]").arg(i)) { throw xInvalidDBFile(54); }
            db_categories[i] = rfile.readLine();
        }
        // End of categories
        if (rfile.readLine() != "[DB_FLAGS_END]") { throw xInvalidDBFile(59); }
        setProgress(10); // PROGRESS >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
        int count = db_qnum + db_snum;
        // Questions
        QuestionItem *item;
        QStringList answers;
        for (int i = 0; i < db_qnum; ++i) {
            answers.clear();
            // Question name
            if (rfile.readLine() != "[Q_NAME]") { throw xInvalidDBFile(100); }
            item = new QuestionItem (rfile.readLine());
            // Category
            if (rfile.readLine() != "[Q_FLAG]") { throw xInvalidDBFile(102); }
            item->setCategory(rfile.readLine().toInt());
            if (db_version >= 1.2) {
                // Question group
                if (rfile.readLine() != "[Q_GRP]") { throw xInvalidDBFile(104); }
                item->setGroup(rfile.readLine());
            }
            // Difficulty
            if (db_version >= 1.2) {
                if (rfile.readLine() != "[Q_DIF]") { throw xInvalidDBFile(106); }
            } else {
                if (rfile.readLine() != "[Q_DIFFICULTY]") { throw xInvalidDBFile(108); }
            }
            item->setDifficulty(rfile.readLine().toInt());
            // Question text
            if (rfile.readLine() != "[Q_TEXT]") { throw xInvalidDBFile(110); }
            item->setText(rfile.readLine());
            if (db_version >= 1.35) {
                // Answers
                if (rfile.readLine() != "[Q_ANS]") { throw xInvalidDBFile(112); }
                item->setSelectionType((Question::SelectionType)rfile.readLine().toInt());
                item->setCorrectAnswers((Question::Answer)rfile.readLine().toInt());
                int numanswers = rfile.readLine().toInt();
                for (int a = 0; a < numanswers; ++a) { answers << rfile.readLine(); }
                // Explanation
                if (rfile.readLine() != "[Q_EXPL]") { throw xInvalidDBFile(114); }
                item->setExplanation(rfile.readLine());
            } else {
                // Answer A
                if (rfile.readLine() != "[Q_ANSA]") { throw xInvalidDBFile(116); }
                answers << rfile.readLine();
                if (db_version < 1.2) {
                    if (rfile.readLine() != "[Q_ANSA_C]") { throw xInvalidDBFile(118); }
                }
                item->setAnswerCorrect(Question::A, rfile.readLine() == "true");
                // Answer B
                if (rfile.readLine() != "[Q_ANSB]") { throw xInvalidDBFile(120); }
                answers << rfile.readLine();
                if (db_version < 1.2) {
                    if (rfile.readLine() != "[Q_ANSB_C]") { throw xInvalidDBFile(122); }
                }
                item->setAnswerCorrect(Question::B, rfile.readLine() == "true");
                // Answer C
                if (rfile.readLine() != "[Q_ANSC]") { throw xInvalidDBFile(124); }
                answers << rfile.readLine();
                if (db_version < 1.2) {
                    if (rfile.readLine() != "[Q_ANSC_C]") { throw xInvalidDBFile(126); }
                }
                item->setAnswerCorrect(Question::C, rfile.readLine() == "true");
                // Answer D
                if (rfile.readLine() != "[Q_ANSD]") { throw xInvalidDBFile(128); }
                answers << rfile.readLine();
                if (db_version < 1.2) {
                    if (rfile.readLine() != "[Q_ANSD_C]") { throw xInvalidDBFile(130); }
                }
                item->setAnswerCorrect(Question::D, rfile.readLine() == "true");
            }
            // Statistics
            if (db_version < 1.2) {
                if (rfile.readLine() != "[Q_ICNT]") { throw xInvalidDBFile(132); }
            } else {
                if (rfile.readLine() != "[Q_ICCNT]") { throw xInvalidDBFile(134); }
            }
            item->setIncorrectAnsCount(rfile.readLine().toUInt());
            if (db_version < 1.2) {
                if (rfile.readLine() != "[Q_CCNT]") { throw xInvalidDBFile(136); }
            }
            item->setCorrectAnsCount(rfile.readLine().toUInt());
            // Hidden
            if (db_version >= 1.2) {
                if (rfile.readLine() != "[Q_HID]") { throw xInvalidDBFile(138); }
                item->setHidden(rfile.readLine() == "true");
            }
            if (db_version > 1.25) {
                // SVG
                if (rfile.readLine() != "[Q_SVG]") { throw xInvalidDBFile(140); }
                int numsvgitems = rfile.readLine().toInt();
                for (int g = 0; g < numsvgitems; ++g) {
                    db_buffer = rfile.readLine();
                    item->addSvgItem(new SvgItem(db_buffer, rfile.readLine()));
                }
            }
            // End
            if (db_version < 1.25) {
                if (rfile.readLine() != "[Q_END]") { throw xInvalidDBFile(199); }
            }
            // Add map entry
            item->setAnswers(answers);
            QListWidgetItem *q_item = new QListWidgetItem (item->group().isEmpty() ? item->name() : QString("[%1] %2").arg(item->group()).arg(item->name()));
            LQListWidget->addItem(q_item);
            current_db_questions.insert(q_item, item);
            setQuestionItemIcon(q_item, item->difficulty());
            setQuestionItemColour(q_item, item->category());
            hideQuestion(q_item, item);
            setProgress((85/(i+1)*count)+10); // PROGRESS >>>>>>>>>>>>>>>>>>>>>>
        }
        // Saved sessions
        int ans_category = -1;
        int ans_dif = 0;
        Question::Answer c_ans;
        Question::Answer ans;
        Question::SelectionType ans_selectiontype = Question::SingleSelection;
        for (int i = 0; i < db_snum; ++i) {
            if (rfile.atEnd())
                break;
            if (rfile.readLine() != "[SESSION]")
                continue;
            Session *session = new Session;
            session->setName(rfile.readLine());
            session->setDateTimeFromString(rfile.readLine());
            if (db_version >= 1.2) {
                if (rfile.readLine() != "[PASSMARK]") { throw xInvalidDBFile(202); }
                PassMark pm(rfile.readLine().toInt());
                int pm_count = rfile.readLine().toInt();
                int pm_c, pm_v;
                for (int i = 0; i < pm_count; ++i) {
                    pm_c = rfile.readLine().toInt();
                    pm_v = rfile.readLine().toInt();
                    pm.addCondition(pm_c, pm_v, pm_v);
                }
                session->setPassMark(pm);
            } else {
                session->setPassMark(PassMark(rfile.readLine().toInt()));
            }
            ScoringSystem sys;
            if (db_version >= 1.35) {
                db_buffer = rfile.readLine(); db_buffer.append("\n");
                db_buffer.append(rfile.readLine()); db_buffer.append("\n");
                db_buffer.append(rfile.readLine());
                sys.loadData(db_buffer);
            }
            int s_snum = rfile.readLine().toInt();
            int s_lenum = rfile.readLine().toInt();
            for (int le = 0; le < s_lenum; ++le) {
                bufferlist.clear();
                bufferlist = rfile.readLine().split(';');
                if (bufferlist.count() == 6) {
                    session->addLogEntry(bufferlist.at(0).toInt(),
                                         bufferlist.at(1).toInt(),
                                         bufferlist.at(2).toInt(),
                                         bufferlist.at(3).toInt(),
                                         bufferlist.at(4).toInt(),
                                         bufferlist.at(5).toInt(),
                                         rfile.readLine());
                } else {
                    session->addLogEntry(255, 255, 255, 0, 0, 0, rfile.readLine());
                }
            }
            for (int s = 0; s < s_snum; ++s) {
                if (rfile.atEnd())
                    break;
                if (rfile.readLine() != "[STUDENT]")
                    continue;
                Student *student = new Student(rfile.readLine());
                student->setReady(rfile.readLine() == "true");
                if (db_version >= 1.2) {
                    student->setPassed(rfile.readLine() == "true");
                }
                student->setNumber(rfile.readLine().toInt());
                if (db_version < 1.35) {
                    rfile.readLine(); // SCORE
                }
                int numresults = rfile.readLine().toInt();
                QMap<QString, QuestionAnswer> *results = new QMap<QString, QuestionAnswer>;
                for (int a = 0; a < numresults; ++a) {
                    db_buffer = rfile.readLine();
                    if (db_version >= 1.2) {
                        ans_category = rfile.readLine().toInt();
                    }

                    QuestionItem *item = NULL;
                    QMapIterator<QListWidgetItem *, QuestionItem *> q(current_db_questions);
                    while (q.hasNext()) { q.next();
                        if (q.value()->name() == db_buffer) {
                            item = q.value();
                            break;
                        }
                    }

                    if (db_version >= 1.35) {
                        ans_dif = rfile.readLine().toInt();
                        ans_selectiontype = (Question::SelectionType)rfile.readLine().toInt();
                    } else {
                        if (item == NULL) {
                            if (db_version < 1.2) {
                                ans_category = -1;
                            }
                            if (db_version < 1.35) {
                                ans_dif = 0;
                                ans_selectiontype = Question::SingleSelection;
                            }
                        } else {
                            if (db_version < 1.2) {
                                ans_category = item->category();
                            }
                            if (db_version < 1.35) {
                                ans_dif = item->difficulty();
                                ans_selectiontype = item->selectionType();
                            }
                        }
                    }

                    if (db_version < 1.27) {
                        ans = Question::convertOldAnsNumber(rfile.readLine().toInt());
                        c_ans = Question::convertOldAnsNumber(rfile.readLine().toInt());
                    } else {
                        ans = (Question::Answer)rfile.readLine().toInt();
                        c_ans = (Question::Answer)rfile.readLine().toInt();
                    }

                    QuestionAnswer qans(c_ans, ans, item ? item->numAnswers() : 9, ans_category, ans_dif, ans_selectiontype);
                    results->insert(db_buffer, qans);
                }
                student->setResults(results);
                student->updateScore(sys);
                if (db_version < 1.2) {
                    student->setPassed(session->passMark().check(student->results(), &current_db_questions, sys));
                }
                session->addStudent(student);
            }
            session->setScoringSystem(sys);
            current_db_sessions.insert(session->dateTime(), session);
            QListWidgetItem *item = new QListWidgetItem (QString("%1 - %2").arg(session->dateTimeToString()).arg(session->name()));
            SVLSListWidget->insertItem(0, item);
            item->setData(Qt::UserRole, session->dateTime());
            setProgress((85/(db_qnum+i+1)*count)+10); // PROGRESS >>>>>>>>>>>>>>
        }
        // Classes
        for (int i = 0; i < db_cnum; ++i) {
            if (rfile.atEnd())
                break;
            if (rfile.readLine() != "[CLASS]")
                continue;
            Class *cl = new Class(rfile.readLine());
            bufferlist = rfile.readLine().split("-", QString::SkipEmptyParts);
            cl->setFirstYear(bufferlist.at(0).toInt());
            cl->setLastYear(bufferlist.at(1).toInt());
            QStringList cl_sessions = rfile.readLine().split(";", QString::SkipEmptyParts);
            for (int s = 0; s < cl_sessions.count(); ++s) {
                cl->addSession(cl_sessions.at(s));
            }
            int mnum = rfile.readLine().toInt();
            for (int m = 0; m < mnum; ++m) {
                if (rfile.readLine() != "[MEM]")
                    continue;
                ClassMember *mem = new ClassMember(rfile.readLine());
                int msnum = rfile.readLine().toInt();
                for (int ms = 0; ms < msnum; ++ms) {
                    db_buffer = rfile.readLine();
                    mem->addSession(db_buffer, rfile.readLine().toInt());
                }
                cl->addMember(mem);
            }
            QListWidgetItem *cl_item = new QListWidgetItem(QString("%1-%2: %3").arg(cl->firstYear()).arg(cl->lastYear()).arg(cl->name()), CLLCListWidget);
            current_db_classes.insert(cl_item, cl);
        }

        ECTextEdit->setHtml( db_comments );
        // Set categories
        current_db_categories_enabled = db_categories_enabled;
        current_db_categories = db_categories;
        setProgress(97); // PROGRESS >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
        // Apply categories
        setCategories(); loadCategories();
        setProgress(98); // PROGRESS >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
        // Enable All
        setAllEnabled(true);
        setProgress(99); // PROGRESS >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
        // Save values
        current_db_file = openDBName;
        current_db_comments = db_comments;
        current_db_open = true;
#ifdef Q_OS_MAC
        this->setWindowTitle(QString("%1[*]").arg(currentDatabaseName()));
#else
        this->setWindowTitle(QString("%1[*] - iTestServer").arg(currentDatabaseName()));
#endif
        this->setWindowModified(false);
        statusBar()->showMessage(tr("Database open"), 10000);
        setProgress(100); setProgress(-1); // PROGRESS >>>>>>>>>>>>>>>>>>>>>>>>>
        actionEdit_questions->setChecked(true);
        mainStackedWidget->setCurrentIndex(1);
        // ---------------------------------------------------------------------
        this->setEnabled(true);
    }
    catch (xInvalidDBFile e) {
        errorInvalidDBFile(tr("Open database"), openDBName, e.error());
    }
    catch (...) {
        QMessageBox::critical(this, tr("iTestServer"), tr("Error opening database."));
        clearAll(); setAllEnabled(false); current_db_open = false;
        this->setWindowTitle(tr("iTestServer"));
        this->setWindowModified(false); setProgress(-1);
        mainStackedWidget->setCurrentIndex(0);
        this->setEnabled(true);
    }
}
//------------------------------------------------------------------------------
bool MainWindow::makeMeCabInputFile(QString orgFilePath, QString meCabInputPath, QString maskColumnNo)
{
    bool stat = true;
    
    QFile wfile(meCabInputPath);
    if (wfile.open(QIODevice::WriteOnly | QIODevice::Text)){
        QFile rfile(orgFilePath);
        if (rfile.open(QIODevice::ReadOnly | QIODevice::Text)){
            while (!rfile.atEnd()) {
                QByteArray line = rfile.readLine();
                if(maskColumnNo == ""){
                    wfile.write(line);
                }
                else{
                    QString str = line;
                    QStringList wlist = str.split("\t", QString::KeepEmptyParts, Qt::CaseSensitive);
                    bool ok;
                    int col = maskColumnNo.toInt(&ok, 10);
                    if(ok){
                        QString wstr = wlist[col];
                        wstr.remove(QRegExp("\r\n$"));
                        wfile.write((wstr + "\r\n").toAscii());
                    }
                    else{
                        QMessageBox::StandardButton reply;
                        reply = QMessageBox::critical(this, tr("ERROR"),
                            tr("Illegal Mask Column No.") + "(" + maskColumnNo + ")",
                            QMessageBox::Abort);
                        if (reply == QMessageBox::Abort){
                            wfile.close();
                            close();
                        }
                        stat = false;
                        break;
                    }
                }
            }
            rfile.close();
        }
        else{
            // Can't open input file.
            QMessageBox::StandardButton reply;
            reply = QMessageBox::critical(this, tr("ERROR"),
                tr("Can't open the input file.") + "(" + orgFilePath + ")",
                QMessageBox::Abort);
            if (reply == QMessageBox::Abort){
                wfile.close();
                close();
            }
            stat = false;
        }
        
        wfile.close();
    }
    else{
        // Can't open the work file.
        QMessageBox::StandardButton reply;
        reply = QMessageBox::critical(this, tr("ERROR"),
            tr("Can't generate the work file.") + "(" + meCabInputPath + ")",
            QMessageBox::Abort);
        if (reply == QMessageBox::Abort){
            close();
        }
        stat = false;
    }
    
    return stat;
}
示例#27
0
int
main(int argc, char *argv[])
{
	extern int optind;
	extern char *optarg;
	enum S command, state;
	DB *dbp;
	DBT data, key, keydata;
	size_t len;
	int ch, oflags, sflag;
	char *fname, *infoarg, *p, *t, buf[8 * 1024];

	infoarg = NULL;
	fname = NULL;
	oflags = O_CREAT | O_RDWR;
	sflag = 0;
	while ((ch = getopt(argc, argv, "f:i:lo:s")) != -1)
		switch (ch) {
		case 'f':
			fname = optarg;
			break;
		case 'i':
			infoarg = optarg;
			break;
		case 'l':
			oflags |= DB_LOCK;
			break;
		case 'o':
			if ((ofd = open(optarg,
			    O_WRONLY|O_CREAT|O_TRUNC, 0666)) < 0)
				err("%s: %s", optarg, strerror(errno));
			break;
		case 's':
			sflag = 1;
			break;
		case '?':
		default:
			usage();
		}
	argc -= optind;
	argv += optind;

	if (argc != 2)
		usage();

	/* Set the type. */
	type = dbtype(*argv++);

	/* Open the descriptor file. */
        if (strcmp(*argv, "-") && freopen(*argv, "r", stdin) == NULL)
	    err("%s: %s", *argv, strerror(errno));

	/* Set up the db structure as necessary. */
	if (infoarg == NULL)
		infop = NULL;
	else
		for (p = strtok(infoarg, ",\t "); p != NULL;
		    p = strtok(0, ",\t "))
			if (*p != '\0')
				infop = setinfo(type, p);

	/*
	 * Open the DB.  Delete any preexisting copy, you almost never
	 * want it around, and it often screws up tests.
	 */
	if (fname == NULL) {
		p = getenv("TMPDIR");
		if (p == NULL)
			p = "/var/tmp";
		snprintf(buf, sizeof(buf), "%s/__dbtest", p);
		fname = buf;
		unlink(buf);
	} else  if (!sflag)
		unlink(fname);

	if ((dbp = dbopen(fname,
	    oflags, S_IRUSR | S_IWUSR, type, infop)) == NULL)
		err("dbopen: %s", strerror(errno));
	XXdbp = dbp;

	state = COMMAND;
	for (lineno = 1;
	    (p = fgets(buf, sizeof(buf), stdin)) != NULL; ++lineno) {
		/* Delete the newline, displaying the key/data is easier. */
		if (ofd == STDOUT_FILENO && (t = strchr(p, '\n')) != NULL)
			*t = '\0';
		if ((len = strlen(buf)) == 0 || isspace(*p) || *p == '#')
			continue;

		/* Convenient gdb break point. */
		if (XXlineno == lineno)
			XXlineno = 1;
		switch (*p) {
		case 'c':			/* compare */
			if (state != COMMAND)
				err("line %lu: not expecting command", lineno);
			state = KEY;
			command = COMPARE;
			break;
		case 'e':			/* echo */
			if (state != COMMAND)
				err("line %lu: not expecting command", lineno);
			/* Don't display the newline, if CR at EOL. */
			if (p[len - 2] == '\r')
				--len;
			if (write(ofd, p + 1, len - 1) != len - 1 ||
			    write(ofd, "\n", 1) != 1)
				err("write: %s", strerror(errno));
			break;
		case 'g':			/* get */
			if (state != COMMAND)
				err("line %lu: not expecting command", lineno);
			state = KEY;
			command = GET;
			break;
		case 'p':			/* put */
			if (state != COMMAND)
				err("line %lu: not expecting command", lineno);
			state = KEY;
			command = PUT;
			break;
		case 'r':			/* remove */
			if (state != COMMAND)
				err("line %lu: not expecting command", lineno);
                        if (flags == R_CURSOR) {
				rem(dbp, &key);
				state = COMMAND;
                        } else {
				state = KEY;
				command = REMOVE;
			}
			break;
		case 'S':			/* sync */
			if (state != COMMAND)
				err("line %lu: not expecting command", lineno);
			synk(dbp);
			state = COMMAND;
			break;
		case 's':			/* seq */
			if (state != COMMAND)
				err("line %lu: not expecting command", lineno);
			if (flags == R_CURSOR) {
				state = KEY;
				command = SEQ;
			} else
				seq(dbp, &key);
			break;
		case 'f':
			flags = setflags(p + 1);
			break;
		case 'D':			/* data file */
			if (state != DATA)
				err("line %lu: not expecting data", lineno);
			data.data = rfile(p + 1, &data.size);
			goto ldata;
		case 'd':			/* data */
			if (state != DATA)
				err("line %lu: not expecting data", lineno);
			data.data = xmalloc(p + 1, len - 1);
			data.size = len - 1;
ldata:			switch (command) {
			case COMPARE:
				compare(&keydata, &data);
				break;
			case PUT:
				put(dbp, &key, &data);
				break;
			default:
				err("line %lu: command doesn't take data",
				    lineno);
			}
			if (type != DB_RECNO)
				free(key.data);
			free(data.data);
			state = COMMAND;
			break;
		case 'K':			/* key file */
			if (state != KEY)
				err("line %lu: not expecting a key", lineno);
			if (type == DB_RECNO)
				err("line %lu: 'K' not available for recno",
				    lineno);
			key.data = rfile(p + 1, &key.size);
			goto lkey;
		case 'k':			/* key */
			if (state != KEY)
				err("line %lu: not expecting a key", lineno);
			if (type == DB_RECNO) {
				static recno_t recno;
				recno = atoi(p + 1);
				key.data = &recno;
				key.size = sizeof(recno);
			} else {
				key.data = xmalloc(p + 1, len - 1);
				key.size = len - 1;
			}
lkey:			switch (command) {
			case COMPARE:
				getdata(dbp, &key, &keydata);
				state = DATA;
				break;
			case GET:
				get(dbp, &key);
				if (type != DB_RECNO)
					free(key.data);
				state = COMMAND;
				break;
			case PUT:
				state = DATA;
				break;
			case REMOVE:
				rem(dbp, &key);
				if ((type != DB_RECNO) && (flags != R_CURSOR))
					free(key.data);
				state = COMMAND;
				break;
			case SEQ:
				seq(dbp, &key);
				if ((type != DB_RECNO) && (flags != R_CURSOR))
					free(key.data);
				state = COMMAND;
				break;
			default:
				err("line %lu: command doesn't take a key",
				    lineno);
			}
			break;
		case 'o':
			dump(dbp, p[1] == 'r');
			break;
		default:
			err("line %lu: %s: unknown command character",
			    lineno, p);
		}
	}
#ifdef STATISTICS
	/*
	 * -l must be used (DB_LOCK must be set) for this to be
	 * used, otherwise a page will be locked and it will fail.
	 */
	if (type == DB_BTREE && oflags & DB_LOCK)
		__bt_stat(dbp);
#endif
	if (dbp->close(dbp))
		err("db->close: %s", strerror(errno));
	close(ofd);
	exit(0);
}
示例#28
0
int main(){

   double hbarc = 197.327;

   double Mu = M;   //Mass in MeV
   cout<<Mu<<endl;
   complex <double> M_I(0,1);

   ////////Input Parameters of the potential (fit parameters) /////
   std::string parameters_filename="Input.inp";

   NuclearParameters Nu = read_nucleus_parameters( "Input/pca40.inp" );

   double Ef=Nu.Ef;
   int lmax=5;
   double zp0;
   double tz=+0.5;

   int type=1;
   int mvolume = 4;
   int AsyVolume = 1;

   double A = Nu.A;

   double  mu = (A)/((A-1.));

   if (tz>0) { zp0=1;}
   else {zp0=0;}

   double ph_gap = Nu.ph_gap;
   cout<<"ph_gap = "<<Nu.ph_gap<<endl;

   double  rStart = .05;
   double  rmax = 12.;
   int  ham_pts = 180; 

   double  rdelt = rmax /ham_pts;

   vector<double> dr;
   dr.assign(ham_pts,rdelt);

   // Construct Parameters Object
   Parameters p = get_parameters( parameters_filename, Nu.A, Nu.Z, zp0 );
   // Construct Potential Object
   pot pottt = get_bobs_pot2( type, mvolume, AsyVolume, tz, Nu, p );
   pot * pott = &pottt;
   cout<<"kconstant = "<<pott->kconstant<<endl;

   boundRspace initiate(rmax , ham_pts , Ef, ph_gap , lmax , Nu.Z , zp0 , Nu.A, pott);

   double Elower = -11.61818;
   double Eupper = -9.4;
   double jj = .5;
   int ll = 0;
   int Ifine = 1;
   initiate.searchNonLoc( Elower, Eupper, jj,  ll,  Ifine);
   initiate.exteriorWaveFunct(ll);
   initiate.normalizeWF();


   double tol=.01;
   double estart=Ef;

   ///// Making rmesh///

   std::vector<double> rmesh= initiate.make_rmesh();

   //std::vector< lj_eigen_t > bound_levels = initiate.get_bound_levels( rmesh, tol );

   eigen_t dom_wf_s = initiate.find_boundstate(rmesh, Ef, 1, 0, 0.5, tol);
   eigen_t dom_wf_d = initiate.find_boundstate(rmesh, Ef, 0, 2, 1.5, tol);


   double sf = initiate.sfactor(rmesh,dom_wf_d.first,2,1.5,dom_wf_d.second);


   cout<<"d3/2 spectroscopic factor = "<<sf<<endl;
   cout<<"d3/2 bound energy = "<<dom_wf_d.first<<endl;
   cout<<"s1/2 bound energy = "<<dom_wf_s.first<<endl;
   cout<<"Fermi Energy = "<<Ef<<endl;

   string title = "pca40";
   string* title0 = &title;

   double E0 = 0.52;

   ofstream rfile("react2.txt");

   double Elab = 100.0;

   if (Elab < 0.) return Elab*A/(1.+A);
   // center of mass velocity in units of c
   double vcm = sqrt(Elab*(Elab+2.*scatterRspace::m0))/(Elab+(1.+A)*
         scatterRspace::m0);
   //gamma factor for this velocity
   double gam = 1./sqrt(1.-std::pow(vcm,2));
   double Ecm = (gam-1.)*(1.+A)*scatterRspace::m0 +
      gam*Elab*(A-1.)*scatterRspace::m0/((A+1.)*
            scatterRspace::m0+Elab);

   //scatterRspace scat(Nu.Z,1,Nu.A,pott,title0);

   //scat.getSmatrix(Ecm,Elab);


   //ofstream eout("elast.txt");
   //ofstream rout("ruth.txt");
   //ifstream din("cross.dat");
   //ofstream dout("cross.txt");
   ////ofstream eout("anal.txt");
   //double ruth,cross,angle;
   //double data,error,theta;
   //int count = 22;

   ////Just needed to run this once to adjust the data by dividing out rutherford
   //for(int i=0;i<count;i++){
      //din >> theta >> data >> error;
      //ruth = scat.Rutherford(theta*3.14159/180);
      //data = data / ruth;
      //error = error / ruth;
      //dout << theta << " " << data << " " << error << endl;
   //}
   //din.close();
   //dout.close();

   //// testing out differential cross section

   //count = 1000;
   //for(int i=1;i<count;i++){
      //angle = i *(3.14159/count/2);
      //cross = scat.DifferentialXsection(angle);
      //ruth = scat.Rutherford(angle);
      //angle = angle * (180.0/3.14159);
      //eout<<angle<<" "<<cross/ruth<<endl;
      //rout<<angle<<" "<<ruth<<endl;
   //}
   //eout.close();

}                                               /* end of main */
示例#29
0
bool CTransferRules::initFromTxtFile(vfs::tReadableFile* pFile)
{
	if(pFile && pFile->openRead())
	{
		vfs::COpenReadFile rfile(pFile);
		std::string sBuffer;
		vfs::UInt32 line_counter = 0;
		vfs::CReadLine rl(*pFile);
		while(rl.getLine(sBuffer))
		{
			line_counter++;
			// very simple parsing : key = value
			if(!sBuffer.empty())
			{
				// remove leading white spaces
				::size_t iStart = sBuffer.find_first_not_of(" \t",0);
				char first = sBuffer.at(iStart);
				switch(first)
				{
				case '!':
				case ';':
				case '#':
					// comment -> do nothing
					break;
				default:
					::size_t iEnd = sBuffer.find_first_of(" \t", iStart);
					if(iEnd != std::string::npos)
					{
						SRule rule;
						std::string action = sBuffer.substr(iStart, iEnd - iStart);
						if( vfs::StrCmp::Equal(action, "deny") )
						{
							rule.action = CTransferRules::DENY;
						}
						else if( vfs::StrCmp::Equal(action, "accept") )
						{
							rule.action = CTransferRules::ACCEPT;
						}
						else
						{
							std::wstring trybuffer = L"Invalid UTF-8 character in string";
							VFS_IGNOREEXCEPTION( trybuffer = vfs::String(sBuffer).c_wcs(), "" ); /* just make sure we don't break off when string conversion fails */
							std::wstringstream wss;
							wss << L"Unknown action in file \"" << pFile->getPath().c_wcs()
								<< L", line " << line_counter << " : " << vfs::String(sBuffer).c_wcs();
							SGP_THROW(wss.str().c_str());
						}
						try
						{
							rule.pattern = vfs::Path(vfs::trimString(sBuffer, iEnd, sBuffer.length()));
						}
						catch(vfs::Exception& ex)
						{
							std::wstringstream wss;
							wss << L"Could not convert string, invalid utf8 encoding in file \"" << pFile->getPath().c_wcs()
								<< L"\", line "  << line_counter;
							SGP_RETHROW(wss.str().c_str(), ex);
						}
						m_listRules.push_back(rule);
					}
					break;
				}; // end switch
			} // end if (empty)
		} // end while(!eof)
		return true;
	}
	return false;
}