• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

C++ string类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了C++中string的典型用法代码示例。如果您正苦于以下问题:C++ string类的具体用法?C++ string怎么用?C++ string使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



在下文中一共展示了string类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C++代码示例。

示例1: ReportStranded

// =========================================================
// Convenience method for reporting merged blocks by strand
// =========================================================
void BedMerge::ReportStranded(string chrom, int start, 
                              int end, const vector<string> &names, 
                              const vector<string> &scores, int mergeCount,
                              string strand) 
{
    // ARQ: removed to force all output to be zero-based, BED format, reagrdless of input type
    //if (_bed->isZeroBased == false) {start++;}
    
    printf("%s\t%d\t%d", chrom.c_str(), start, end);
    // just the merged intervals
    if (_numEntries == false && _reportNames == false && 
        _reportScores == false) {
        printf("\t%s\n", strand.c_str());
    }
    // merged intervals and counts    
    else if (_numEntries == true && _reportNames == false &&
        _reportScores == false) {
        printf("\t%d\t%s\n", mergeCount, strand.c_str());
    }
    // merged intervals, counts, and scores
    else if (_numEntries == true && _reportNames == false &&
        _reportScores == true) {
        printf("\t%d", mergeCount);
        ReportMergedScores(scores);
        printf("\t%s\n", strand.c_str());
    }
    // merged intervals, counts, and names
    else if (_numEntries == true && _reportNames == true &&
        _reportScores == false) {
        ReportMergedNames(names);
        printf("\t%d\t%s", mergeCount, strand.c_str());
        printf("\n");
    }
    // merged intervals, counts, names, and scores
    else if (_numEntries == true && _reportNames == true &&
        _reportScores == true) {
        ReportMergedNames(names);
        ReportMergedScores(scores);
        printf("\t%s\t%d", strand.c_str(), mergeCount);
        printf("\n");
    }
    // merged intervals and names        
    else if (_numEntries == false && _reportNames == true &&
        _reportScores == false) {
        ReportMergedNames(names);
        printf("\t%s\n", strand.c_str());
    }
    // merged intervals and scores        
    else if (_numEntries == false && _reportNames == false && 
        _reportScores == true) {
        ReportMergedScores(scores);
        printf("\t%s\n", strand.c_str());
    }
    // merged intervals, names, and scores        
    else if (_numEntries == false && _reportNames == true && 
        _reportScores == true) {
        ReportMergedNames(names);
        ReportMergedScores(scores);
        printf("\t%s\n", strand.c_str());
    }
}
开发者ID:alexpenson,项目名称:bedtools,代码行数:64,代码来源:mergeBed.cpp


示例2: fscanf

/*	You need to read the configuration file and extract the page size and number of pages
 * (these two parameter together define the maximum main memory you can use).
 * Values are in number of bytes.
 * You should read the names of the tables from the configuration file.
 * You can assume that the table data exists in a file named <table_name>.csv at the path
 * pointed by the config parameter PATH_FOR_DATA.
***************************************************************************************/
void DBSystem::readConfig(string configFilePath)
{
	FILE *fd=fopen(configFilePath.c_str(),"rw+");
	int count=0;
	char* temp=new char[100];
	bool isBegin=false;
	bool isInTable=false;

	if(fd==NULL)
		cout<<"Config file not found"<<endl;

	fscanf (fd, "%s %d", temp, &pageSize);
	fscanf (fd, "%s %d", temp, &(numberOfPages));
	fscanf (fd, "%s %s", temp, (pathForData));

	fclose(fd);

	string sLine="";

	ifstream infile;
	infile.open(configFilePath.c_str());

	getline(infile, sLine);
	getline(infile, sLine);
	getline(infile, sLine);

	//cout<<sLine;
	//cout<<"Page size is : "<< pageSize << endl;
	//cout<<"Number of pages are : "<< numberOfPages <<endl;
	//cout<<"Path for table files is : "<< pathForData <<endl;
	string currentTableName;

	while(!infile.eof())
	{
		string current("");

		getline(infile, current);
		//cout << current<<endl;
		if( current.find("BEGIN") != -1 && !isBegin)
		{
			count=0;
			isBegin=true;
			continue;
		}
		else if( current.find("END") != -1 )
		{
			if(count++==1)
				break;

			isBegin=false;
			isInTable=false;

			continue;
		}

		if(isBegin)
		{
			isInTable=true;
			isBegin=false;

			tableNames.push_back(current.substr(0,current.length()));
			currentTableName=current;
			tableNameToPrimaryKeys[currentTableName]="";
		}

		else if(isInTable)
		{
			int index=current.find(',');
			string currentColumnName=current.substr(0,index);
			int len=current.length();
			string currentDataType=current.substr(index+1,len);

			//	cout<<currentDataType<<endl;
			currentColumnName=removeSpaces(currentColumnName);
			currentDataType=removeSpaces(currentDataType);

			if(currentDataType.find("varchar")!=string::npos || currentDataType.find("VARCHAR")!=string::npos)
				currentDataType="VARCHAR";

			if(currentDataType=="integer")
				currentDataType="INT";

			if(currentDataType=="float")
				currentDataType="FLOAT";


			if(currentColumnName.compare("PRIMARY_KEY")==0){
			//	cout<<currentTableName<<"  "<<currentDataType<<endl;
				tableNameToPrimaryKeys[currentTableName]=currentDataType;
			}
			else{
				std::pair < string,string > bar = std::make_pair (currentColumnName,currentDataType);
				tableNameToColumnNames[currentTableName].push_back(bar);
//.........这里部分代码省略.........
开发者ID:gsagarcoep,项目名称:DBMS-Working,代码行数:101,代码来源:DBSystem.cpp


示例3: DBG

bool DSMFactory::loadConfig(const string& conf_file_name, const string& conf_name, 
			    bool live_reload, DSMStateDiagramCollection* m_diags) {

  string script_name = conf_name.substr(0, conf_name.length()-5); // - .conf
  DBG("loading %s from %s ...\n", script_name.c_str(), conf_file_name.c_str());
  AmConfigReader cfg;
  if(cfg.loadFile(conf_file_name))
    return false;

  DSMScriptConfig script_config;
  script_config.RunInviteEvent = 
    cfg.getParameter("run_invite_event")=="yes";

  script_config.SetParamVariables = 
    cfg.getParameter("set_param_variables")=="yes";

  script_config.config_vars.insert(cfg.begin(), cfg.end());

  if (live_reload) {
    INFO("live DSM config reload does NOT reload prompts and prompt sets!\n");
    INFO("(see http://tracker.iptel.org/browse/SEMS-68)\n");
  } else {
    if (!loadPrompts(cfg))
      return false;

    if (!loadPromptSets(cfg))
      return false;
  }

  DSMStateDiagramCollection* used_diags;
  if (m_diags != NULL)
    used_diags = m_diags;     // got this from caller (main diags)
  else {
    // create a new set of diags 
    used_diags = script_config.diags = new DSMStateDiagramCollection();
  }

  if (!loadDiags(cfg, used_diags))
    return false;

  vector<string> registered_apps;
  if (!registerApps(cfg, used_diags, registered_apps))
    return false;

  ScriptConfigs_mut.lock();
  try {
    Name2ScriptConfig[script_name] = script_config;
    // set ScriptConfig to this for all registered apps' names
    for (vector<string>::iterator reg_app_it=
	   registered_apps.begin(); reg_app_it != registered_apps.end(); reg_app_it++) {
      string& app_name = *reg_app_it;
      // dispose of the old one, if it exists
      map<string, DSMScriptConfig>::iterator it=ScriptConfigs.find(app_name);
      if (it != ScriptConfigs.end()) {
	// may be in use by active call - don't delete but save to 
	// old_diags for garbage collection (destructor)
	if (it->second.diags != NULL)
	  old_diags.insert(it->second.diags);   
      }
      
      // overwrite with new config
      ScriptConfigs[app_name] = script_config;
    }
  } catch(...) {
    ScriptConfigs_mut.unlock();
    throw;
  }
  ScriptConfigs_mut.unlock();

  bool res = true;

  vector<string> system_dsms = explode(cfg.getParameter("run_system_dsms"), ",");
  for (vector<string>::iterator it=system_dsms.begin(); it != system_dsms.end(); it++) {
    string status;
    if (createSystemDSM(script_name, *it, live_reload, status)) {
    } else {
      ERROR("creating system DSM '%s': '%s'\n", it->c_str(), status.c_str());
      res = false;
    }
  }

  return res;
}
开发者ID:Chocolatbuddha,项目名称:sems,代码行数:83,代码来源:DSM.cpp


示例4: _tWinMain


//.........这里部分代码省略.........


	//////////////////////////
	//initialize random number
	//////////////////////////
	srand((unsigned)time(0));



	pFILE = fopen("devices.txt","w");
	
	///////////////////////
	//initialize port audio
	///////////////////////
    global_err = Pa_Initialize();
    if( global_err != paNoError )
	{
		//MessageBox(0,"portaudio initialization failed",0,MB_ICONERROR);
		if(pFILE) fprintf(pFILE, "portaudio initialization failed.\n");
		fclose(pFILE);
		return 1;
	}
	

	
	////////////////////////
	//audio device selection
	////////////////////////
	//SelectAudioInputDevice();
	SelectAudioOutputDevice();
	
	/*
	// Create an api map.
	std::map<int, std::string> apiMap;
	apiMap[RtAudio::MACOSX_CORE] = "OS-X Core Audio";
	apiMap[RtAudio::WINDOWS_ASIO] = "Windows ASIO";
	apiMap[RtAudio::WINDOWS_DS] = "Windows Direct Sound";
	apiMap[RtAudio::UNIX_JACK] = "Jack Client";
	apiMap[RtAudio::LINUX_ALSA] = "Linux ALSA";
	apiMap[RtAudio::LINUX_OSS] = "Linux OSS";
	apiMap[RtAudio::RTAUDIO_DUMMY] = "RtAudio Dummy";

	std::vector< RtAudio::Api > apis;
	RtAudio::getCompiledApi(apis);

	fprintf(pFILE, "\nCompiled APIs:\n");
	for (unsigned int i = 0; i<apis.size(); i++)
		fprintf(pFILE, " %s\n ", apiMap[apis[i]] );


	fprintf(pFILE, "\nCurrent API: %s\n", apiMap[global_dac.getCurrentApi()]);

	unsigned int devices = global_dac.getDeviceCount();
	fprintf(pFILE, "\nFound %i device(s) ...\n", devices);
	*/

	/*
	// Configure RtAudio
	global_rtParams.deviceId = global_dac.getDefaultOutputDevice();
	global_rtParams.nChannels = NUM_CHANNELS;
	unsigned int sampleRate = SAMPLE_RATE;
	unsigned int bufferFrames = 512; // 512 sample frames
	*/

	// You don't necessarily have to do this - it will default to 44100 if not set.
	Tonic::setSampleRate(SAMPLE_RATE);
开发者ID:oifii,项目名称:spitonicsimplestepseqsynthvoroguiwin32_vs2013,代码行数:67,代码来源:spitonicsimplestepseqsynthvoroguiwin32.cpp


示例5: srand

void TestSuite::menu_tests( string spec_file_path )
{
	ifstream fin;
	ofstream fout_tst, fout_ans;
	
	string tst_filename = "menu_test_";	
	string ans_filename = "menu_ans_";
	string read;
	stringstream ss;

	int num_test_files = -1;
	double max, min = 0;
	int rand_int = 0;
	float rand_float = 0;

	srand (time(NULL));	
	system("mkdir -p tests");

	char ans[128] = {'\0'};

	while (strcmp(ans,"y") && strcmp(ans,"n") )
	{
		for (int i = 0; i < 128; i++)
			ans[i] = '\0'; 
		cout << "Would you like to generate files for testing menues? (y/n): " << endl;
		cin >> ans;
	}

	if (!strcmp(ans,"y") )
	{
		// open .spec file check for success
		fin.open(spec_file_path.c_str());
		if (!fin)
			return;	
		fin.close();

		//display menu for range, number of test cases
		while ( num_test_files < 0 || num_test_files > 100)
		{
			cout << "Enter number of test files to generate for menu testing (between 0 and 100): ";
			cin >> num_test_files;
			cout << endl;
		}
	
		cout <<
    		"\nWhat is the MINIMUM value you would like the randomly generated values to be?"
    	     << "\n Number between –2147483648 to 2147483646"<< endl;
    	cin >> min;
    	cout <<
    	     "\nWhat is the MAXIMUM value you would like the randomly generated values to be?"
    	     << "\n Number between –2147483647 to 2147483647"<< endl;
    	cin >> max;
    	while(max <= min)
    	{
    	    cout << "\n Maximum must be larger than mimimum." << endl;
    	    cout <<
    	         "\nWhat is the MINIMUM value you would like the randomly generated values to be?"
    	         << "\n Number between –2147483648 to 2147483646"<< endl;
    	    cin >> min;
    	    cout <<
    	         "\nWhat is the MAXIMUM value you would like the randomly generated values to be?"
    	         << "\n Number between –2147483647 to 2147483647"<< endl;
    	    cin >> max;
    	}
	
	
		double range = max - min;
		//generate .tst files
		for (int i = 0; i < num_test_files;i++)
		{
			string test_filename = tst_filename;
			string answer_filename = ans_filename;
			//generate time stamp
    	    time_t rawTime;
    	    tm * timeInfo;
    	    char buffer [40];
			string i_to_string = "";
			ss.str("");	
	
    	    time (&rawTime);
    	    timeInfo = localtime (&rawTime);
	
    	    strftime (buffer,40,"%d_%m_%y_%H_%M_%S",timeInfo);
    	    string curr_time(buffer);
			
			ss << i+1;
			i_to_string = ss.str();
	
			test_filename += i_to_string;
			answer_filename += i_to_string;
			test_filename = test_filename + "_"	+ curr_time + ".tst";
			answer_filename = answer_filename + "_"	+ curr_time + ".ans";
				
			fin.open(spec_file_path.c_str());
			fout_ans.open(answer_filename.c_str());
			fout_tst.open(test_filename.c_str());
			//open .tst and .ans files for output
	
			while ( fin >> read )
			{	
//.........这里部分代码省略.........
开发者ID:bonnebonne,项目名称:autotest-sp3,代码行数:101,代码来源:testsuite_fork_works.cpp


示例6: exists

		//Uses stat to check if the specified file exists
		static bool exists(string p)
		{
			struct stat DirInfo;
			int err = stat(p.c_str(), &DirInfo);
			return (err == 0);
		}
开发者ID:HPCToolkit,项目名称:hpctoolkit,代码行数:7,代码来源:FileUtils.hpp


示例7: main

/*******************************************************************************
 * For each run, the input filename and restart information (if needed) must   *
 * be given on the command line.  For non-restarted case, command line is:     *
 *                                                                             *
 *    executable <input file name>                                             *
 *                                                                             *
 * For restarted run, command line is:                                         *
 *                                                                             *
 *    executable <input file name> <restart directory> <restart number>        *
 *                                                                             *
 *******************************************************************************/
int main(int argc, char* argv[])
{
    // Initialize libMesh, PETSc, MPI, and SAMRAI.
    LibMeshInit init(argc, argv);
    SAMRAI_MPI::setCommunicator(PETSC_COMM_WORLD);
    SAMRAI_MPI::setCallAbortInSerialInsteadOfExit();
    SAMRAIManager::startup();

    { // cleanup dynamically allocated objects prior to shutdown

        // Parse command line options, set some standard options from the input
        // file, initialize the restart database (if this is a restarted run),
        // and enable file logging.
        Pointer<AppInitializer> app_initializer = new AppInitializer(argc, argv, "IB.log");
        Pointer<Database> input_db = app_initializer->getInputDatabase();

        // Setup user-defined kernel function.
        LEInteractor::s_kernel_fcn = &kernel;
        LEInteractor::s_kernel_fcn_stencil_size = 8;

        // Get various standard options set in the input file.
        const bool dump_viz_data = app_initializer->dumpVizData();
        const int viz_dump_interval = app_initializer->getVizDumpInterval();
        const bool uses_visit = dump_viz_data && app_initializer->getVisItDataWriter();
        const bool uses_exodus = dump_viz_data && !app_initializer->getExodusIIFilename().empty();
        const string exodus_filename = app_initializer->getExodusIIFilename();

        const bool dump_restart_data = app_initializer->dumpRestartData();
        const int restart_dump_interval = app_initializer->getRestartDumpInterval();
        const string restart_dump_dirname = app_initializer->getRestartDumpDirectory();

        const bool dump_postproc_data = app_initializer->dumpPostProcessingData();
        const int postproc_data_dump_interval = app_initializer->getPostProcessingDataDumpInterval();
        const string postproc_data_dump_dirname = app_initializer->getPostProcessingDataDumpDirectory();
        if (dump_postproc_data && (postproc_data_dump_interval > 0) && !postproc_data_dump_dirname.empty())
        {
            Utilities::recursiveMkdir(postproc_data_dump_dirname);
        }

        const bool dump_timer_data = app_initializer->dumpTimerData();
        const int timer_dump_interval = app_initializer->getTimerDumpInterval();

        // Create a simple FE mesh.
        Mesh solid_mesh(NDIM);
        const double dx = input_db->getDouble("DX");
        const double ds = input_db->getDouble("MFAC") * dx;
        string elem_type = input_db->getString("ELEM_TYPE");
        const double R = 0.5;
        if (NDIM == 2 && (elem_type == "TRI3" || elem_type == "TRI6"))
        {
            const int num_circum_nodes = ceil(2.0 * M_PI * R / ds);
            for (int k = 0; k < num_circum_nodes; ++k)
            {
                const double theta = 2.0 * M_PI * static_cast<double>(k) / static_cast<double>(num_circum_nodes);
                solid_mesh.add_point(libMesh::Point(R * cos(theta), R * sin(theta)));
            }
            TriangleInterface triangle(solid_mesh);
            triangle.triangulation_type() = TriangleInterface::GENERATE_CONVEX_HULL;
            triangle.elem_type() = Utility::string_to_enum<ElemType>(elem_type);
            triangle.desired_area() = 1.5 * sqrt(3.0) / 4.0 * ds * ds;
            triangle.insert_extra_points() = true;
            triangle.smooth_after_generating() = true;
            triangle.triangulate();
        }
        else
        {
            // NOTE: number of segments along boundary is 4*2^r.
            const double num_circum_segments = 2.0 * M_PI * R / ds;
            const int r = log2(0.25 * num_circum_segments);
            MeshTools::Generation::build_sphere(solid_mesh, R, r, Utility::string_to_enum<ElemType>(elem_type));
        }

        // Ensure nodes on the surface are on the analytic boundary.
        MeshBase::element_iterator el_end = solid_mesh.elements_end();
        for (MeshBase::element_iterator el = solid_mesh.elements_begin(); el != el_end; ++el)
        {
            Elem* const elem = *el;
            for (unsigned int side = 0; side < elem->n_sides(); ++side)
            {
                const bool at_mesh_bdry = !elem->neighbor(side);
                if (!at_mesh_bdry) continue;
                for (unsigned int k = 0; k < elem->n_nodes(); ++k)
                {
                    if (!elem->is_node_on_side(k, side)) continue;
                    Node& n = *elem->get_node(k);
                    n = R * n.unit();
                }
            }
        }
//.........这里部分代码省略.........
开发者ID:Nasrollah,项目名称:IBAMR,代码行数:101,代码来源:main.cpp


示例8: if


//.........这里部分代码省略.........
	if (wd.targetBorder > 1.0f) {
		logOutput.Print("warning: targetBorder truncated to 1 (was %f)", wd.targetBorder);
		wd.targetBorder = 1.0f;
	} else if (wd.targetBorder < -1.0f) {
		logOutput.Print("warning: targetBorder truncated to -1 (was %f)", wd.targetBorder);
		wd.targetBorder = -1.0f;
	}
	wd.cylinderTargetting = wdTable.GetFloat("cylinderTargetting", melee ? 1.0f : 0.0f);

	wd.range = wdTable.GetFloat("range", 10.0f);
	const float accuracy       = wdTable.GetFloat("accuracy",   0.0f);
	const float sprayAngle     = wdTable.GetFloat("sprayAngle", 0.0f);
	const float movingAccuracy = wdTable.GetFloat("movingAccuracy", accuracy);
	// should really be tan but TA seem to cap it somehow
	// should also be 7fff or ffff theoretically but neither seems good
	wd.accuracy       = sin((accuracy)       * PI / 0xafff);
	wd.sprayAngle     = sin((sprayAngle)     * PI / 0xafff);
	wd.movingAccuracy = sin((movingAccuracy) * PI / 0xafff);

	wd.targetMoveError = wdTable.GetFloat("targetMoveError", 0.0f);
	wd.leadLimit = wdTable.GetFloat("leadLimit", -1.0f);
	wd.leadBonus = wdTable.GetFloat("leadBonus", 0.0f);

	// setup the default damages
	const LuaTable dmgTable = wdTable.SubTable("damage");
	float defDamage = dmgTable.GetFloat("default", 0.0f);
	if (defDamage == 0.0f) {
		defDamage = 1.0f; //avoid division by zeroes
	}
	for (int a = 0; a < damageArrayHandler->GetNumTypes(); ++a) {
		wd.damages[a] = defDamage;
	}

	map<string, float> damages;
	dmgTable.GetMap(damages);

	map<string, float>::const_iterator di;
	for (di = damages.begin(); di != damages.end(); ++di) {
		const int type = damageArrayHandler->GetTypeFromName(di->first);
		if (type != 0) {
			float dmg = di->second;
			if (dmg != 0.0f) {
				wd.damages[type] = dmg;
			} else {
				wd.damages[type] = 1.0f;
			}
		}
	}

	wd.damages.impulseFactor = wdTable.GetFloat("impulseFactor", 1.0f);
	wd.damages.impulseBoost  = wdTable.GetFloat("impulseBoost",  0.0f);
	wd.damages.craterMult    = wdTable.GetFloat("craterMult",    wd.damages.impulseFactor);
	wd.damages.craterBoost   = wdTable.GetFloat("craterBoost",   0.0f);

	wd.areaOfEffect = wdTable.GetFloat("areaOfEffect", 8.0f) * 0.5f;
	wd.edgeEffectiveness = wdTable.GetFloat("edgeEffectiveness", 0.0f);
	// prevent 0/0 division in CGameHelper::Explosion
	if (wd.edgeEffectiveness > 0.999f) {
		wd.edgeEffectiveness = 0.999f;
	}

	wd.projectilespeed = wdTable.GetFloat("weaponVelocity", 0.0f) / GAME_SPEED;
	wd.startvelocity = max(0.01f, wdTable.GetFloat("startVelocity", 0.0f) / GAME_SPEED);
	wd.weaponacceleration = wdTable.GetFloat("weaponAcceleration", 0.0f) / GAME_SPEED / GAME_SPEED;
	wd.reload = wdTable.GetFloat("reloadTime", 1.0f);
	wd.salvodelay = wdTable.GetFloat("burstRate", 0.1f);
开发者ID:genxinzou,项目名称:svn-spring-archive,代码行数:67,代码来源:WeaponDefHandler.cpp


示例9: check_size

bool check_size( const string& s, size_t sz ) {
    return s.size( ) > sz;
}
开发者ID:PINK-FL0YD,项目名称:CodeSnippet,代码行数:3,代码来源:HellTest.cpp


示例10: check_size_

auto check_size_( const int& n, const string& s ) {
    return to_string( n ).size( ) > s.size( );
}
开发者ID:PINK-FL0YD,项目名称:CodeSnippet,代码行数:3,代码来源:HellTest.cpp


示例11: isNumber

    bool isNumber(string s) {
        if (s.empty()) return false;
        int i = 0;
        while(isspace(s[i])) {
            i++;
        }
            
        if (s[i] == '+' || s[i] == '-') {
            i++;
        }
            
        bool eAppear = false;
        bool dotAppear = false;
        bool firstPart = false;
        bool secondPart = false;
        bool spaceAppear = false;

        while(s[i] != '\0') {
            if (s[i] == '.') {
                if (dotAppear || eAppear || spaceAppear) {
                    return false;
                } else {
                    dotAppear = true;
                }
            } else if (s[i] == 'e' || s[i] == 'E') {
                if (eAppear || !firstPart || spaceAppear) {
                    return false;
                } else {
                    eAppear = true;
                }
            } else if (isdigit(s[i])) {
                if (spaceAppear) {
                    return false;
                }
   
                if (!eAppear) {
                    firstPart = true;
                } else {
                    secondPart = true;
                }
            } else if (s[i] == '+' || s[i] == '-') {
                if (spaceAppear) {
                    return false;
                }

                if (!eAppear || !(s[i - 1] == 'e' || s[i - 1] == 'E')) {
                    return false;
                }
            } else if (isspace(s[i])) {
                spaceAppear = true;
            } else {
                return false;
            }
            i++;            
        }
        
        if (!firstPart) {
            return false;
        } else if (eAppear && !secondPart) {
            return false;
        } else {
            return true;
        }
    }
开发者ID:HaochenLiu,项目名称:My-LeetCode-CPP,代码行数:64,代码来源:065.cpp


示例12:

/*
 * Apply delta
 */
bool	CReferenceBuilder::updateReference(std::vector<TUpdateList>& updateList,
										   const CTimestamp& baseTimestamp,
										   const CTimestamp& endTimestamp,
										   const string& refRootPath,
										   const string& refPath,
										   volatile bool* stopAsked)
{
	if (updateList.empty())
		return true;
	
	uint	i, j;
	for (i=0; i<updateList.size(); ++i)
	{
		const TUpdateList&	tableList = updateList[i];

		if (tableList.empty())
			continue;

		CTableBuffer	tableBuffer;
		tableBuffer.init(i, refRootPath, refPath);

		if (!tableBuffer.openAllRefFilesWrite())
		{
			nlwarning("CReferenceBuilder::updateReference(): failed to preopen all reference files for table '%d' in reference '%s'", i, refPath.c_str());
			return false;
		}

		for (j=0; j<tableList.size(); ++j)
		{
			const CUpdateFile&	update = tableList[j];

			if (update.EndTime < baseTimestamp || update.StartTime >= endTimestamp)
				continue;

			if (!tableBuffer.applyDeltaChanges(update.Filename))
			{
				nlwarning("CReferenceBuilder::updateReference(): failed to apply delta file '%s'", update.Filename.c_str());
				return false;
			}

			PDS_LOG_DEBUG(1)("CReferenceBuilder::updateReference(): updated reference with file '%s'", update.Filename.c_str());
		}
	}

	return true;
}
开发者ID:Kiddinglife,项目名称:ryzom,代码行数:49,代码来源:reference_builder.cpp


示例13:

FragSpectrumScanDatabase::FragSpectrumScanDatabase(string id_par) :
    scan2rt(0) 
{
  if(id_par.empty()) id = "no_id"; else id = id_par;
}
开发者ID:theold190,项目名称:percolator,代码行数:5,代码来源:FragSpectrumScanDatabase.cpp


示例14: init_files

static void init_files(CursesWindow* window, const string& bbsdir) {
  window->SetColor(SchemeId::PROMPT);
  window->Puts("Creating Data Files.\n");
  window->SetColor(SchemeId::NORMAL);

  memset(&syscfg, 0, sizeof(configrec));

  strcpy(syscfg.systempw, "SYSOP");
  sprintf(syscfg.msgsdir, "%smsgs%c", bbsdir.c_str(), File::pathSeparatorChar);
  sprintf(syscfg.gfilesdir, "%sgfiles%c", bbsdir.c_str(), File::pathSeparatorChar);
  sprintf(syscfg.datadir, "%sdata%c", bbsdir.c_str(), File::pathSeparatorChar);
  sprintf(syscfg.dloadsdir, "%sdloads%c", bbsdir.c_str(), File::pathSeparatorChar);
  sprintf(syscfg.tempdir, "%stemp1%c", bbsdir.c_str(), File::pathSeparatorChar);
  sprintf(syscfg.menudir, "%sgfiles%cmenus%c", bbsdir.c_str(), File::pathSeparatorChar, File::pathSeparatorChar);
  strcpy(syscfg.systemname, "My WWIV BBS");
  strcpy(syscfg.systemphone, "   -   -    ");
  strcpy(syscfg.sysopname, "The New Sysop");

  syscfg.newusersl = 10;
  syscfg.newuserdsl = 0;
  syscfg.maxwaiting = 50;
  // Always use 1 for the primary port.
  syscfg.primaryport = 1;
  syscfg.newuploads = 0;
  syscfg.maxusers = 500;
  syscfg.newuser_restrict = restrict_validate;
  syscfg.req_ratio = 0.0;
  syscfg.newusergold = 100.0;

  valrec v;
  v.ar = 0;
  v.dar = 0;
  v.restrict = 0;
  v.sl = 10;
  v.dsl = 0;
  for (int i = 0; i < 10; i++) {
    syscfg.autoval[i] = v;
  }
  for (int i = 0; i < 256; i++) {
    slrec sl;
    sl.time_per_logon = static_cast<uint16_t>((i / 10) * 10);
    sl.time_per_day = static_cast<uint16_t>(((float)sl.time_per_logon) * 2.5);
    sl.messages_read = static_cast<uint16_t>((i / 10) * 100);
    if (i < 10) {
      sl.emails = 0;
    } else if (i <= 19) {
      sl.emails = 5;
    } else {
      sl.emails = 20;
    }

    if (i <= 10) {
      sl.posts = 10;
    } else if (i <= 25) {
      sl.posts = 10;
    } else if (i <= 39) {
      sl.posts = 4;
    } else if (i <= 79) {
      sl.posts = 10;
    } else {
      sl.posts = 25;
    }

    sl.ability = 0;
    if (i >= 150) {
      sl.ability |= ability_cosysop;
    }
    if (i >= 100) {
      sl.ability |= ability_limited_cosysop;
    }
    if (i >= 90) {
      sl.ability |= ability_read_email_anony;
    }
    if (i >= 80) {
      sl.ability |= ability_read_post_anony;
    }
    if (i >= 70) {
      sl.ability |= ability_email_anony;
    }
    if (i >= 60) {
      sl.ability |= ability_post_anony;
    }
    if (i == 255) {
      sl.time_per_logon = 255;
      sl.time_per_day = 255;
      sl.posts = 255;
      sl.emails = 255;
    }
    syscfg.sl[i] = sl;
  }

  syscfg.userreclen = sizeof(userrec);
  syscfg.waitingoffset = offsetof(userrec, waiting);
  syscfg.inactoffset = offsetof(userrec, inact);
  syscfg.sysstatusoffset = offsetof(userrec, sysstatus);
  syscfg.fuoffset = offsetof(userrec, forwardusr);
  syscfg.fsoffset = offsetof(userrec, forwardsys);
  syscfg.fnoffset = offsetof(userrec, net_num);

  syscfg.max_subs = 64;
//.........这里部分代码省略.........
开发者ID:TRI0N,项目名称:wwiv,代码行数:101,代码来源:newinit.cpp


示例15: log

void AndroidWrapper::log(string tag, string message){
	__android_log_write(ANDROID_LOG_INFO, tag.c_str(), message.c_str());

}
开发者ID:ser26,项目名称:MPG,代码行数:4,代码来源:AndroidWrapper.cpp


示例16: DataSplit

//___________________________________________________________________
static LREThreadBuffer * 
            DataSplit(LinesReader  ** lrIRScript,
                      const string & stProgName,
                      HANDLE mutex,
                      const string & stSampleFolder,
                      const string & stThreadID,
                      const int      iMaxAnonymsNum,
                      const vector<FeatureSet*> & vAuthors,
                      const int iAuthorsNumber,
                      const map<string,FeatureInfo,LexComp> & lexicon)
{
    const string stLogsFolder = ResourceBox::Get()->getStringValue("LogsFolder");
    LREThreadBuffer * buffer = NULL;
    int i;
    string stLine(75,'\0');
    
    fprintf(stderr,"Alloc LRE Thread buffer\n");
    fflush(stderr);

    buffer = new LREThreadBuffer(mutex,NULL,iMaxAnonymsNum+1,iAuthorsNumber);
    
    if (buffer == NULL)
    {
        fprintf(stderr,"Alloc Thread Buffer failed\n");
        fflush(stderr);
        return NULL;
    }

    buffer->vAuthors = &vAuthors;
    
    fprintf(stderr,"Alloc LRE IR Aux buffer\n");
    fflush(stderr);

    LREAuxBuffer * irAuxBuffer=NULL;
    if (stProgName.compare("LRE") == 0)
    {
        const bool bIsClosedSet = (ResourceBox::Get()->getIntValue("ClosedAuthorSet") > 0);
        const bool bIsNoAuthorSet = (ResourceBox::Get()->getIntValue("IsNoAuthor") > 0);
        if (bIsClosedSet)
            irAuxBuffer = new LREAuxBuffer();
        else if (!bIsNoAuthorSet)
            irAuxBuffer = new LREOpenSet(&lexicon);
        else
            irAuxBuffer = new LRENoAuthor();
    }
    else if (stProgName.compare("LREClassify") == 0)
    {
        irAuxBuffer = new LREClassify();
    }
    else abort_err(string("Unknown program name in LRE: name=")+stProgName);
    
    if (irAuxBuffer == NULL) abort_err(string("Failed to alloc LREAuxBuffer. name=")+stProgName);
    
    buffer->irAuxBuffer=irAuxBuffer;

    SimilarityMeasure * simMatch = NULL;
    const string stSimFuncType = ResourceBox::Get()->getStringValue("SimilarityMeasure");
    if (stSimFuncType.compare("cos") == 0) simMatch = new CosineMatch;
    else if (stSimFuncType.compare("dist") == 0) simMatch = new DistanceMatch;
    else if (stSimFuncType.compare("mmx") == 0) simMatch = new MinMaxMatch;
    else abort_err(string("Illegal SimilarityMeasure: ")+stSimFuncType);
    if (simMatch == NULL) abort_err(string("Failed to alloc SimilarityMeasure. name=")+stSimFuncType);
    
    buffer->simMatch = simMatch;
    
    buffer->lexicon = &lexicon;
        
    buffer->iAnonymIndex=0;
    
    buffer->stThreadID = stThreadID;
    buffer->stIRScriptFile = stSampleFolder+"IRScript_"+stThreadID+".txt";
    buffer->stIRQueryLog = stLogsFolder+"IR_"+stThreadID+".txt";
    buffer->stDebugLog = stLogsFolder+"debug_"+stThreadID+".txt";
    
    fprintf(stderr,"open the script file: %s\n",buffer->stIRScriptFile.c_str());
    fflush(stderr);

    FILE * fIRScript = open_file(buffer->stIRScriptFile,"DataSplit","w");
    
    i=0;
    
    const string stScriptFile = stSampleFolder+"anonyms.txt";
    fprintf(stderr,"Alloc Lines Reader: %s\n",stScriptFile.c_str());
    fflush(stderr);

    if (lrIRScript == NULL) {fprintf(stderr,"NULL lines reader buffer\n"); fflush(stderr); exit(0);}
    if (*lrIRScript == NULL) *lrIRScript = new LinesReader(stScriptFile,512);
    if (*lrIRScript == NULL) {fprintf(stderr,"Failed to alloc lines reader object\n"); fflush(stderr); exit(0);}
    while ((i++<iMaxAnonymsNum) && (*lrIRScript)->bMoreToRead())
    {
        (*lrIRScript)->voGetLine(stLine);
        fprintf(fIRScript,"%s\n",stLine.c_str());
        fflush(fIRScript);
    }
    fclose(fIRScript);
    
    fprintf(stderr,"Create Thread\n");
    fflush(stderr);

//.........这里部分代码省略.........
开发者ID:mikekestemont,项目名称:Apuleius,代码行数:101,代码来源:LRE.cpp


示例17: build_head

void mime_head::build_head(string& out, bool clean)
{
	if (clean)
		out.clear();
	if (m_headers)
	{
		std::list<HEADER*>::const_iterator cit = m_headers->begin();
		for (; cit != m_headers->end(); ++cit)
		{
			out.format_append("%s: %s\r\n",
				(*cit)->name, (*cit)->value);
		}
	}
	char buf[64];
	rfc822 rfc;
	rfc.mkdate_cst(time(NULL), buf, sizeof(buf));
	out.format_append("Date: %s\r\n", buf);

	if (m_from)
		out.format_append("From: %s\r\n", m_from->c_str());
	if (m_replyto)
		out.format_append("Reply-To: %s\r\n", m_replyto->c_str());
	if (m_returnpath)
		out.format_append("Return-Path: %s\r\n", m_returnpath->c_str());
	if (m_tos)
		append_recipients(out, "To", *m_tos);
	if (m_ccs)
		append_recipients(out, "Cc", *m_ccs);
	if (m_bccs)
		append_recipients(out, "Bcc", *m_bccs);
	if (m_subject)
		out.format_append("Subject: %s\r\n", m_subject->c_str());
	out.append("MIME-Version: 1.0\r\n");
	out.format_append("Content-Type: %s/%s", get_ctype(), get_stype());
	if (m_boundary)
		out.format_append(";\r\n\tboundary=\"%s\"\r\n",
			m_boundary->c_str());
	else
		out.append("\r\n");

	out.append("\r\n");
}
开发者ID:Tim9Liu9,项目名称:acl,代码行数:42,代码来源:mime_head.cpp


示例18: LRE

//___________________________________________________________________
void LRE(const string & stProgName)
{
    Timer tiLRE;
    tiLRE.reset();
    tiLRE.start();
        
    const string stLogsFolder = ResourceBox::Get()->getStringValue("LogsFolder");
    const string stSampleFolder = ResourceBox::Get()->getStringValue("SampleFolder");
    const string stFeaturePool = stSampleFolder+"FeaturePool.txt";
    const int iIRLoops = ResourceBox::Get()->getIntValue("IRLoops");
    map<string,FeatureInfo,LexComp> lexicon;
    HANDLE mutex;
    
    fprintf(stderr,"Main Thread - Start\n");
    fflush(stderr);

    mutex = CreateMutex(NULL,FALSE,NULL);
    if (mutex == NULL) abort_err("Create mutex failed in LRE");

    fprintf(stderr,"Load Feature Pool\n");
    fflush(stderr);

    LoadFeatureSet(lexicon,NULL,stFeaturePool,NULL);
    LinesReader * lrSamples=NULL;
    
    fprintf(stderr,"Load Authors Set - Start\n");
    fflush(stderr);

    const string stAuthorSuffix = string("Author") + ((stProgName.compare("LREClassify") == 0)?"\\":"\\Ftrs\\");
    const string stAuthorsList = stSampleFolder + "authors.txt";
    const int iMaxCandsNum = ScriptSize(stAuthorsList);
    vector<FeatureSet*> vAuthors(iMaxCandsNum+1);
    const int iAuthorsNumber = LoadCandidates(vAuthors,stSampleFolder+stAuthorSuffix,stAuthorsList,&lexicon);

    fprintf(stderr,"Load Authors Set - End (#Authors=%d)\n",iAuthorsNumber);
    fflush(stderr);

    FILE * fIRQueryLog = open_file(stLogsFolder+"IR_All.txt","LRE","w");

    const int iMaxAnonymsNum = ScriptSize(stSampleFolder+"anonyms.txt");
    const int iMultiProcDegree = ResourceBox::Get()->getIntValue("MultiProcessingDegree");
    const int iAnonymSegment = iMaxAnonymsNum/iMultiProcDegree + iMaxAnonymsNum%iMultiProcDegree;
    int i;
    list<LREThreadBuffer*> threadsList;
    LREThreadBuffer * buffer=NULL;
    char thread_id[50];
    string stLine(75,'\0');
    
    fprintf(stderr,"#MaxAnonyms=%d; Segment: %d + %d = %d\n",iMaxAnonymsNum,iMaxAnonymsNum/iMultiProcDegree,iMaxAnonymsNum%iMultiProcDegree,iAnonymSegment);
    fflush(stderr);

    fprintf(stderr,"Alloc Threads\n");
    fflush(stderr);

    for (i=0;i<iMultiProcDegree;i++)
    {
        sprintf(thread_id,"tid%d",i);
        buffer = DataSplit(&lrSamples,
                           stProgName,
                           mutex,
                           stSampleFolder,
                           thread_id,
                           iAnonymSegment,
                           vAuthors,
                           iAuthorsNumber,
                           lexicon);
        threadsList.push_back(buffer);
    }
    
    fprintf(stderr,"Join Threads\n");
    fflush(stderr);

    list<LREThreadBuffer*>::iterator threadsIter = threadsList.begin();
    int iAnonymsNumber=0;
    while (threadsIter != threadsList.end())
    {
        fprintf(stderr,"Wait for thread end\n");
        fflush(stderr);

        LREThreadBuffer * ltbTemp = *threadsIter;

        fprintf(stderr,"Call Join\n");
        fflush(stderr);

        // Wait for the LRE thread end.
        WaitForSingleObject(ltbTemp->tid,INFINITE);
        CloseHandle(ltbTemp->tid);
        threadsIter++;

        fprintf(stderr,"Consolidate the IR queries log. tid=%s, #Anonyms=%d\nIRLog=%s\n",
                ltbTemp->stThreadID.c_str(),ltbTemp->iAnonymIndex,ltbTemp->stIRQueryLog.c_str());
        fflush(stderr);
        
        ConsolidateLogs(fIRQueryLog,ltbTemp->stIRQueryLog);

        iAnonymsNumber += ltbTemp->iAnonymIndex;
        
        fprintf(stderr,"Del Buffer\n");
        fflush(stderr);
//.........这里部分代码省略.........
开发者ID:mikekestemont,项目名称:Apuleius,代码行数:101,代码来源:LRE.cpp


示例19: WndProc

该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C++ string16类代码示例发布时间:2022-05-31
下一篇:
C++ stream_type类代码示例发布时间:2022-05-31
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap