Exemplo n.º 1
0
	bool remove_all(const NetworkPath& path) {
		if (path.isLocal()) return bfs::remove_all(path.path);
		string dir = toString(path.path);
		return runCommand("ssh " + path.getUserHostnamePrefix() + " \"test -e " + dir + " && rm -rf " + dir + "\"") == 0;
	}
Exemplo n.º 2
0
bool NativePath::isReadable() const
{
    return QFileInfo(toString()).isReadable();
}
Exemplo n.º 3
0
int correctDist::createProcess(string distanceFileName){
	try {
#if defined (__APPLE__) || (__MACH__) || (linux) || (__linux) || (__linux__) || (__unix__) || (__unix)
		int process = 1;
		vector<int> processIDs;
        bool recalc = false;
		
		while(process != processors){
			
			pid_t pid = fork();
			
			if(pid > 0){
				processIDs.push_back(pid);
				process++;
			}
			else if(pid == 0){
				driver(start[process], end[process], distanceFileName + m->mothurGetpid(process) + ".temp");
				exit(0);
			}
			else{
                m->mothurOut("[ERROR]: unable to spawn the number of processes you requested, reducing number to " + toString(process) + "\n"); processors = process;
                for (int i = 0; i < processIDs.size(); i++) { kill (processIDs[i], SIGINT); }
                //wait to die
                for (int i=0;i<processIDs.size();i++) {
                    int temp = processIDs[i];
                    wait(&temp);
                }
                m->control_pressed = false;
                recalc = true;
                break;
			}
		}
		
        if (recalc) {
            start.clear(); end.clear();
            for(int i=0;i<processors;i++){
                start.push_back(int (sqrt(float(i)/float(processors)) * numSeqs));
                end.push_back(int (sqrt(float(i+1)/float(processors)) * numSeqs));
            }
            
            processIDs.resize(0);
            process = 1;
            
            while(process != processors){
                
                pid_t pid = fork();
                
                if(pid > 0){
                    processIDs.push_back(pid);
                    process++;
                }
                else if(pid == 0){
                    driver(start[process], end[process], distanceFileName + m->mothurGetpid(process) + ".temp");
                    exit(0);
                }
                else{
                    m->mothurOut("[ERROR]: unable to spawn the necessary processes."); m->mothurOutEndLine();
                    for (int i=0;i<processIDs.size();i++) {  int temp = processIDs[i]; kill(temp, SIGINT); }
                    exit(0);
                }
            }
        }
        
		driver(start[0], end[0], distanceFileName);
		
		for (int i=0;i<processIDs.size();i++) { 
			int temp = processIDs[i];
			wait(&temp);
		}
		
		for(int i=0;i<processIDs.size();i++){
			m->appendFiles((distanceFileName + toString(processIDs[i]) + ".temp"), distanceFileName);
			remove((distanceFileName + toString(processIDs[i]) + ".temp").c_str());
		}
#endif
		return 0;
	}
	catch(exception& e) {
		m->errorOut(e, "correctDist", "createProcess");
		exit(1);
	}	
}
Exemplo n.º 4
0
/* SRC: classes/xhprof.php line 7 */
void c_XhprofFrame::t___construct(Variant v_name) {
  x_xhprof_frame_begin(toString(v_name));
}
int HyperNEAT_main(int argc,char **argv)
{
    //This is for memory debugging
    //_CrtSetDbgFlag ( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF ); 
    //_CrtSetBreakAlloc(1378);

    int retval=0;

    CommandLineParser commandLineParser(argc,argv);

#if 1

#if 0
    try
#endif
    {
        if (argc<=1)
        {
#ifndef HCUBE_NOGUI
            cout_ << "Starting wxEntry...\n";
            retval = wxEntry(argc, argv);
#else
            cout_ << "You must pass the parameters and the output file as command "
                 << "parameters!\n";
            cout_ << "(If you intended to run in GUI mode, please run cmake and set the USE_GUI flag to true)\n";
#endif
        }
        else if (argc==2)
        {
            //Run the post-hoc analysis on last generation
            cout_ << "Running post-hoc analysis on: " << argv[1] << endl;
            HCUBE::ExperimentRun experimentRun;
			
            experimentRun.setupExperimentInProgress(
													string(argv[1]),
													""
													);
			
            int numGenerations = experimentRun.getPopulation()->getGenerationCount();
			
            HCUBE::Experiment *experiment = experimentRun.getExperiment()->clone();
			
            /*
			 {
			 string outString = (erase_tail_copy(string(argv[1]),4)+string("_fitness.out"));
			 cout_ << "Creating file " << outString << endl;
			 ofstream outfile( outString.c_str() );
			 string previousSummary;
			 
			 bool doOnce=false;
			 
			 for (int generation=0;generation<numGenerations;generation++)
			 {
			 //CREATE_PAUSE(string("Error!: ")+toString(__LINE__));
			 
			 //CREATE_PAUSE(string("Error!: ")+toString(__LINE__));
			 
			 if ( generation &&
			 (*(experimentRun.getIndividual(generation,0).get())) == (*(experimentRun.getIndividual(generation-1,0).get())) )
			 {
			 outfile << (generation+1) << ' ' << previousSummary << endl;
			 continue;
			 }
			 
			 shared_ptr<NEAT::GeneticIndividual> indiv =
			 shared_ptr<NEAT::GeneticIndividual>(
			 new NEAT::GeneticIndividual(
			 *(experimentRun.getIndividual(generation,0).get())
			 )
			 );
			 
			 //CREATE_PAUSE(string("Error!: ")+toString(__LINE__));
			 
			 cout_ << "Beginning fitness evaluation " << (generation+1) << "/" << numGenerations << "...";
			 cout_.flush();
			 experiment->addIndividualToGroup(indiv);
			 experiment->processGroup(experimentRun.getGeneration(generation));
			 experiment->clearGroup();
			 cout_ << "done!\n";
			 
			 //CREATE_PAUSE(string("Error!: ")+toString(__LINE__));
			 
			 if (indiv->getUserData())
			 {
			 if (!doOnce)
			 {
			 doOnce=true;
			 outfile
			 << "#Generation: "
			 << indiv->getUserData()->summaryHeaderToString()
			 << endl;
			 }
			 
			 previousSummary = indiv->getUserData()->summaryToString();
			 outfile << (generation+1) << ' ' << previousSummary << endl;
			 }
			 else
			 {
			 throw CREATE_LOCATEDEXCEPTION_INFO("No user data!\n");
			 }
			 
			 }
			 }
			 */
			
            {
                string outString = (erase_tail_copy(string(argv[1]),3)+string("_fitness.out"));
                cout_ << "Creating file " << outString << endl;
                ofstream outfile( outString.c_str() );
                string previousSummary;
				
                bool doOnce=false;
				
				int firstGen = 0;
				//int firstGen = numGenerations-1;
                for (int generation=firstGen;generation<numGenerations;generation++)
                {
                    //CREATE_PAUSE(string("Error!: ")+toString(__LINE__));
					
                    //CREATE_PAUSE(string("Error!: ")+toString(__LINE__));
					
#if 0
                    if ( generation &&
						(*(experimentRun.getIndividual(generation,0).get())) == (*(experimentRun.getIndividual(generation-1,0).get())) )
                    {
                        outfile << (generation+1) << ' ' << previousSummary << endl;
                        continue;
                    }
#endif
					
                    shared_ptr<NEAT::GeneticIndividual> indiv =
					shared_ptr<NEAT::GeneticIndividual>(
														new NEAT::GeneticIndividual(
																					*(experimentRun.getIndividual(generation,0).get())
																					)
														);
					
					if(generation!=firstGen)
					{
						shared_ptr<NEAT::GeneticIndividual> lastindiv =
                        shared_ptr<NEAT::GeneticIndividual>(
															new NEAT::GeneticIndividual(
																						*(experimentRun.getIndividual(generation-1,0).get())
																						)
															);
						
						if(fabsf(indiv->getFitness()-lastindiv->getFitness())<1e-3)
						{
							//cout_ << "Skipping redundant individual\n";
							continue;
						}
					}
					
                    //CREATE_PAUSE(string("Error!: ")+toString(__LINE__));
					
                    //cout_ << "Beginning post-hoc evaluation " << (generation+1) << "/" << numGenerations << "...";
                    //experiment->processIndividualPostHoc(indiv);
                    //cout_ << "done!\n";
					
                    //CREATE_PAUSE(string("Error!: ")+toString(__LINE__));
					
#if 0
                    if (indiv->getUserData().length())
                    {
                        if (!doOnce)
                        {
                            doOnce=true;
                            outfile
							<< "#Generation: "
							<< indiv->getUserData()
							<< endl;
                        }
						
                        previousSummary = indiv->getUserData();
                        outfile << (generation+1) << ' ' << previousSummary << endl;
                    }
                    else
                    {
                        if (!doOnce)
                        {
                            doOnce=true;
                            outfile
							<< "#Generation: "
							<< "Fitness:"
							<< endl;
                        }
						
                        previousSummary = toString(indiv->getFitness());
                        outfile << (generation+1) << ' ' << previousSummary << endl;
                    }
#endif
					
					cout_ << "Beginning post-hoc evaluation " << (generation+1) << "/" << numGenerations << "...";
					experiment->processIndividualPostHoc(indiv);
					cout_ << indiv->getUserData() << endl;
					cout_ << "done!\n";
					
					//CREATE_PAUSE(string("Error!: ")+toString(__LINE__));
					
#if 0
					if (indiv->getUserData())
					{
						if (!doOnce)
						{
							doOnce=true;
							outfile
							<< "#Generation: "
							<< indiv->getUserData()->summaryHeaderToString()
							<< endl;
						}
						
						previousSummary = indiv->getUserData()->summaryToString();
						outfile << (generation+1) << ' ' << previousSummary << endl;
					}
					else
					{
						if (!doOnce)
						{
							doOnce=true;
							outfile
							<< "#Generation: "
							<< "Fitness:"
							<< endl;
						}
						
						previousSummary = toString(indiv->getFitness());
						outfile << (generation+1) << ' ' << previousSummary << endl;
					}
#endif
				}
			}
		}
        else if (
				 commandLineParser.HasSwitch("-P")
				 )
        {
			string inputFile = commandLineParser.GetSafeArgument("-P",0,"input.dat");
            //Run the post-hoc analysis
            cout_ << "Running post-hoc analysis on: " << inputFile << endl;
            HCUBE::ExperimentRun experimentRun;
			
            experimentRun.setupExperimentInProgress(
													inputFile,
													""
													);
			
            int numGenerations = experimentRun.getPopulation()->getGenerationCount();
			
            HCUBE::Experiment *experiment = experimentRun.getExperiment()->clone();
			
			{
				int firstGen = 0;
				//int firstGen = numGenerations-1;
				bool ignoreFirstIfElitism=false;
				
				if(commandLineParser.HasSwitch("-G"))
				{
					firstGen = atoi(commandLineParser.GetSafeArgument("-G",0,"0").c_str())-1;
					if(firstGen<numGenerations)
						numGenerations = firstGen+1;
				}
		
				if(firstGen && commandLineParser.HasSwitch("-S"))
					ignoreFirstIfElitism=true;
				
                for (int generation=firstGen;generation<numGenerations;generation++)
                {
                    shared_ptr<NEAT::GeneticIndividual> indiv =
					shared_ptr<NEAT::GeneticIndividual>(
														new NEAT::GeneticIndividual(
																					*(experimentRun.getIndividual(generation,0).get())
																					)
														);
					
					if(generation!=firstGen || ignoreFirstIfElitism)
					{
						shared_ptr<NEAT::GeneticIndividual> lastindiv =
                        shared_ptr<NEAT::GeneticIndividual>(
															new NEAT::GeneticIndividual(
																						*(experimentRun.getIndividual(generation-1,0).get())
																						)
															);
						
						if(fabsf(indiv->getFitness()-lastindiv->getFitness())<1e-3)
						{
							//cout_ << "Skipping redundant individual\n";
							continue;
						}
					}
					
					cout_ << "Beginning post-hoc evaluation " << (generation+1) << "/" << numGenerations << "..." << endl;
					experiment->processIndividualPostHoc(indiv);
					cout_ << indiv->getUserData() << endl;
					cout_ << "done!\n";
				}
			}
		}
		else if(
    commandLineParser.HasSwitch("-I") &&
    commandLineParser.HasSwitch("-O")
    )
{
    NEAT::Globals::init(commandLineParser.GetSafeArgument("-I",0,"input.dat"));

    if(commandLineParser.HasSwitch("-R"))
    {
        NEAT::Globals::getSingleton()->seedRandom(stringTo<unsigned int>(commandLineParser.GetSafeArgument("-R",0,"0")));
    }

    int experimentType = int(NEAT::Globals::getSingleton()->getParameterValue("ExperimentType")+0.001);

    cout_ << "Loading Experiment: " << experimentType << endl;

    HCUBE::ExperimentRun experimentRun;

    experimentRun.setupExperiment(experimentType,commandLineParser.GetSafeArgument("-O",0,"output.xml"));

    cout_ << "Experiment set up\n";

    experimentRun.createPopulation();

    experimentRun.setCleanup(true);

    cout_ << "Population Created\n";

    experimentRun.start();
}
else if(
    commandLineParser.HasSwitch("-C")
    )
{
    HCUBE::ExperimentRun experimentRun;

    string backupFile = commandLineParser.GetArgument("-C",0);
    string outputFile = backupFile.substr(0,backupFile.length()-14);
			
    //This also calls NEAT::Globals::init(...)
    experimentRun.setupExperimentInProgress(backupFile,outputFile);

    cout_ << "Experiment set up\n";

    experimentRun.setCleanup(true);
    experimentRun.start();
}
else
{
    cout_ << "Syntax for passing command-line options to HyperNEAT (do not actually type '(' or ')' ):\n";
    cout_ << "./HyperNEAT [-R (seed)] -I (datafile) -O (outputfile)\n";
}
}
#if 0
catch (const std::exception &ex)
{
    cout_ << "CAUGHT ERROR AT " << __FILE__ << " : " << __LINE__ << endl;
    cout_ << "An exception has occured: " << ex.what() << endl;
}
catch (string s)
{
    cout_ << "CAUGHT ERROR AT " << __FILE__ << " : " << __LINE__ << endl;
    cout_ << "An exception has occured: " << s << endl;
}
catch (...)
{
    cout_ << "CAUGHT ERROR AT " << __FILE__ << " : " << __LINE__ << endl;
    cout_ << "An error has occured!\n";
}
#endif

NEAT::Globals::deinit();

#endif

return retval;
}
void
GUISettingsHandler::myStartElement(int element,
                                   const SUMOSAXAttributes& attrs) {
    bool ok = true;
    switch (element) {
        case SUMO_TAG_BREAKPOINTS_FILE: {
            std::string file = attrs.get<std::string>(SUMO_ATTR_VALUE, 0, ok);
            myBreakpoints = loadBreakpoints(file);
        }
        break;
        case SUMO_TAG_VIEWSETTINGS:
            myViewType = attrs.getOpt<std::string>(SUMO_ATTR_TYPE, 0, ok, "default");
            std::transform(myViewType.begin(), myViewType.end(), myViewType.begin(), tolower);
            break;
        case SUMO_TAG_DELAY:
            myDelay = attrs.getOpt<SUMOReal>(SUMO_ATTR_VALUE, 0, ok, myDelay);
            break;
        case SUMO_TAG_VIEWPORT: {
            const SUMOReal x = attrs.getOpt<SUMOReal>(SUMO_ATTR_X, 0, ok, myLookFrom.x());
            const SUMOReal y = attrs.getOpt<SUMOReal>(SUMO_ATTR_Y, 0, ok, myLookFrom.y());
            const SUMOReal z = attrs.getOpt<SUMOReal>(SUMO_ATTR_ZOOM, 0, ok, myLookFrom.z());
            myLookFrom.set(x, y, z);
            const SUMOReal cx = attrs.getOpt<SUMOReal>(SUMO_ATTR_CENTER_X, 0, ok, myLookAt.x());
            const SUMOReal cy = attrs.getOpt<SUMOReal>(SUMO_ATTR_CENTER_Y, 0, ok, myLookAt.y());
            const SUMOReal cz = attrs.getOpt<SUMOReal>(SUMO_ATTR_CENTER_Z, 0, ok, myLookAt.z());
            myLookAt.set(cx, cy, cz);
            break;
        }
        case SUMO_TAG_SNAPSHOT: {
            bool ok = true;
            std::string file = attrs.get<std::string>(SUMO_ATTR_FILE, 0, ok);
            if (file != "" && !FileHelpers::isAbsolute(file)) {
                file = FileHelpers::getConfigurationRelative(getFileName(), file);
            }
            mySnapshots[attrs.getOptSUMOTimeReporting(SUMO_ATTR_TIME, file.c_str(), ok, 0)] = file;
        }
        break;
        case SUMO_TAG_VIEWSETTINGS_SCHEME: {
            bool ok = true;
            mySettings.name = attrs.getOpt<std::string>(SUMO_ATTR_NAME, 0, ok, mySettings.name);
            if (gSchemeStorage.contains(mySettings.name)) {
                mySettings = gSchemeStorage.get(mySettings.name);
            }
        }
        break;
        case SUMO_TAG_VIEWSETTINGS_OPENGL:
            mySettings.antialiase = TplConvert::_2bool(attrs.getStringSecure("antialiase", toString(mySettings.antialiase)).c_str());
            mySettings.dither = TplConvert::_2bool(attrs.getStringSecure("dither", toString(mySettings.dither)).c_str());
            break;
        case SUMO_TAG_VIEWSETTINGS_BACKGROUND: {
            bool ok = true;
            mySettings.backgroundColor = RGBColor::parseColorReporting(attrs.getStringSecure("backgroundColor", toString(mySettings.backgroundColor)), "background", 0, true, ok);
            mySettings.showGrid = TplConvert::_2bool(attrs.getStringSecure("showGrid", toString(mySettings.showGrid)).c_str());
            mySettings.gridXSize = TplConvert::_2SUMOReal(attrs.getStringSecure("gridXSize", toString(mySettings.gridXSize)).c_str());
            mySettings.gridYSize = TplConvert::_2SUMOReal(attrs.getStringSecure("gridYSize", toString(mySettings.gridYSize)).c_str());
        }
        break;
        case SUMO_TAG_VIEWSETTINGS_EDGES: {
            int laneEdgeMode = TplConvert::_2int(attrs.getStringSecure("laneEdgeMode", "0").c_str());
            mySettings.laneShowBorders = TplConvert::_2bool(attrs.getStringSecure("laneShowBorders", toString(mySettings.laneShowBorders)).c_str());
            mySettings.showLinkDecals = TplConvert::_2bool(attrs.getStringSecure("showLinkDecals", toString(mySettings.showLinkDecals)).c_str());
            mySettings.showRails = TplConvert::_2bool(attrs.getStringSecure("showRails", toString(mySettings.showRails)).c_str());
            mySettings.edgeName = parseTextSettings("edgeName", attrs, mySettings.edgeName);
            mySettings.internalEdgeName = parseTextSettings("internalEdgeName", attrs, mySettings.internalEdgeName);
            mySettings.streetName = parseTextSettings("streetName", attrs, mySettings.streetName);
            mySettings.hideConnectors = TplConvert::_2bool(attrs.getStringSecure("hideConnectors", toString(mySettings.hideConnectors)).c_str());
            myCurrentColorer = element;
#ifdef HAVE_INTERNAL
            mySettings.edgeColorer.setActive(laneEdgeMode);
#endif
            mySettings.laneColorer.setActive(laneEdgeMode);
        }
        break;
        case SUMO_TAG_COLORSCHEME:
            myCurrentScheme = 0;
            if (myCurrentColorer == SUMO_TAG_VIEWSETTINGS_EDGES) {
                myCurrentScheme = mySettings.laneColorer.getSchemeByName(attrs.getStringSecure(SUMO_ATTR_NAME, ""));
#ifdef HAVE_INTERNAL
                if (myCurrentScheme == 0) {
                    myCurrentScheme = mySettings.edgeColorer.getSchemeByName(attrs.getStringSecure(SUMO_ATTR_NAME, ""));
                }
#endif
            }
            if (myCurrentColorer == SUMO_TAG_VIEWSETTINGS_VEHICLES) {
                myCurrentScheme = mySettings.vehicleColorer.getSchemeByName(attrs.getStringSecure(SUMO_ATTR_NAME, ""));
            }
            if (myCurrentColorer == SUMO_TAG_VIEWSETTINGS_JUNCTIONS) {
                myCurrentScheme = mySettings.junctionColorer.getSchemeByName(attrs.getStringSecure(SUMO_ATTR_NAME, ""));
            }
            if (myCurrentScheme && !myCurrentScheme->isFixed()) {
                bool ok = true;
                myCurrentScheme->setInterpolated(attrs.getOpt<bool>(SUMO_ATTR_INTERPOLATED, 0, ok, false));
                myCurrentScheme->clear();
            }
            break;
        case SUMO_TAG_ENTRY:
            if (myCurrentScheme) {
                bool ok = true;
                RGBColor color = attrs.get<RGBColor>(SUMO_ATTR_COLOR, 0, ok);
                if (myCurrentScheme->isFixed()) {
                    myCurrentScheme->setColor(attrs.getStringSecure(SUMO_ATTR_NAME, ""), color);
                } else {
                    myCurrentScheme->addColor(color, attrs.getOpt<SUMOReal>(SUMO_ATTR_THRESHOLD, 0, ok, 0));
                }
            }
            break;
        case SUMO_TAG_VIEWSETTINGS_VEHICLES:
            mySettings.vehicleColorer.setActive(TplConvert::_2int(attrs.getStringSecure("vehicleMode", "0").c_str()));
            mySettings.vehicleQuality = TplConvert::_2int(attrs.getStringSecure("vehicleQuality", toString(mySettings.vehicleQuality)).c_str());
            mySettings.minVehicleSize = TplConvert::_2SUMOReal(attrs.getStringSecure("minVehicleSize", toString(mySettings.minVehicleSize)).c_str());
            mySettings.vehicleExaggeration = TplConvert::_2SUMOReal(attrs.getStringSecure("vehicleExaggeration", toString(mySettings.vehicleExaggeration)).c_str());
            mySettings.showBlinker = TplConvert::_2bool(attrs.getStringSecure("showBlinker", toString(mySettings.showBlinker)).c_str());
            mySettings.vehicleName = parseTextSettings("vehicleName", attrs, mySettings.vehicleName);
            myCurrentColorer = element;
            break;
        case SUMO_TAG_VIEWSETTINGS_PERSONS:
            mySettings.personColorer.setActive(TplConvert::_2int(attrs.getStringSecure("personMode", "0").c_str()));
            mySettings.personQuality = TplConvert::_2int(attrs.getStringSecure("personQuality", toString(mySettings.personQuality)).c_str());
            mySettings.minPersonSize = TplConvert::_2SUMOReal(attrs.getStringSecure("minPersonSize", toString(mySettings.minPersonSize)).c_str());
            mySettings.personExaggeration = TplConvert::_2SUMOReal(attrs.getStringSecure("personExaggeration", toString(mySettings.personExaggeration)).c_str());
            mySettings.personName = parseTextSettings("personName", attrs, mySettings.personName);
            myCurrentColorer = element;
            break;
        case SUMO_TAG_VIEWSETTINGS_JUNCTIONS:
            mySettings.junctionColorer.setActive(TplConvert::_2int(attrs.getStringSecure("junctionMode", "0").c_str()));
            mySettings.drawLinkTLIndex = TplConvert::_2bool(attrs.getStringSecure("drawLinkTLIndex", toString(mySettings.drawLinkTLIndex)).c_str());
            mySettings.drawLinkJunctionIndex = TplConvert::_2bool(attrs.getStringSecure("drawLinkJunctionIndex", toString(mySettings.drawLinkJunctionIndex)).c_str());
            mySettings.junctionName = parseTextSettings("junctionName", attrs, mySettings.junctionName);
            mySettings.internalJunctionName = parseTextSettings("internalJunctionName", attrs, mySettings.internalJunctionName);
            mySettings.showLane2Lane = TplConvert::_2bool(attrs.getStringSecure("showLane2Lane", toString(mySettings.showLane2Lane)).c_str());
            mySettings.drawJunctionShape = TplConvert::_2bool(attrs.getStringSecure("drawShape", toString(mySettings.drawJunctionShape)).c_str());
            myCurrentColorer = element;
            break;
        case SUMO_TAG_VIEWSETTINGS_ADDITIONALS:
            mySettings.addMode = TplConvert::_2int(attrs.getStringSecure("addMode", toString(mySettings.addMode)).c_str());
            mySettings.minAddSize = TplConvert::_2SUMOReal(attrs.getStringSecure("minAddSize", toString(mySettings.minAddSize)).c_str());
            mySettings.addExaggeration = TplConvert::_2SUMOReal(attrs.getStringSecure("addExaggeration", toString(mySettings.addExaggeration)).c_str());
            mySettings.addName = parseTextSettings("addName", attrs, mySettings.addName);
            break;
        case SUMO_TAG_VIEWSETTINGS_POIS:
            mySettings.poiExaggeration = TplConvert::_2SUMOReal(attrs.getStringSecure("poiExaggeration", toString(mySettings.poiExaggeration)).c_str());
            mySettings.minPOISize = TplConvert::_2SUMOReal(attrs.getStringSecure("minPOISize", toString(mySettings.minPOISize)).c_str());
            mySettings.poiName = parseTextSettings("poiName", attrs, mySettings.poiName);
            break;
        case SUMO_TAG_VIEWSETTINGS_POLYS:
            mySettings.polyExaggeration = TplConvert::_2SUMOReal(attrs.getStringSecure("polyExaggeration", toString(mySettings.polyExaggeration)).c_str());
            mySettings.minPolySize = TplConvert::_2SUMOReal(attrs.getStringSecure("minPolySize", toString(mySettings.minPolySize)).c_str());
            mySettings.polyName = parseTextSettings("polyName", attrs, mySettings.polyName);
            break;
        case SUMO_TAG_VIEWSETTINGS_LEGEND:
            mySettings.showSizeLegend = TplConvert::_2bool(attrs.getStringSecure("showSizeLegend", toString(mySettings.showSizeLegend)).c_str());
            break;
        case SUMO_TAG_VIEWSETTINGS_DECAL: {
            GUISUMOAbstractView::Decal d;
            d.filename = attrs.getStringSecure("filename", d.filename);
            if (d.filename != "" && !FileHelpers::isAbsolute(d.filename)) {
                d.filename = FileHelpers::getConfigurationRelative(getFileName(), d.filename);
            }
            d.centerX = attrs.getOpt<SUMOReal>(SUMO_ATTR_CENTER_X, 0, ok, d.centerX);
            d.centerY = attrs.getOpt<SUMOReal>(SUMO_ATTR_CENTER_Y, 0, ok, d.centerY);
            d.centerZ = attrs.getOpt<SUMOReal>(SUMO_ATTR_CENTER_Z, 0, ok, d.centerZ);
            d.width = attrs.getOpt<SUMOReal>(SUMO_ATTR_WIDTH, 0, ok, d.width);
            d.height = attrs.getOpt<SUMOReal>(SUMO_ATTR_HEIGHT, 0, ok, d.height);
            d.altitude = TplConvert::_2SUMOReal(attrs.getStringSecure("altitude", toString(d.height)).c_str());
            d.rot = TplConvert::_2SUMOReal(attrs.getStringSecure("rotation", toString(d.rot)).c_str());
            d.tilt = TplConvert::_2SUMOReal(attrs.getStringSecure("tilt", toString(d.tilt)).c_str());
            d.roll = TplConvert::_2SUMOReal(attrs.getStringSecure("roll", toString(d.roll)).c_str());
            d.layer = attrs.getOpt<SUMOReal>(SUMO_ATTR_LAYER, 0, ok, d.layer);
            d.initialised = false;
            myDecals.push_back(d);
        }
        break;
        default:
            break;
    }
}
Exemplo n.º 7
0
SetDirectoryCommand::SetDirectoryCommand(string option)  {
	try {
		abort = false; calledHelp = false;   
		
		//allow user to run help
		if(option == "help") { help(); abort = true; calledHelp = true; }
		else if(option == "citation") { citation(); abort = true; calledHelp = true;}
		
		else {
			vector<string> myArray = setParameters();
			
			OptionParser parser(option);
			map<string, string> parameters = parser.getParameters();
			
			ValidParameters validParameter;
			//check to make sure all parameters are valid for command
			for (map<string,string>::iterator it = parameters.begin(); it != parameters.end(); it++) { 
				if (validParameter.isValidParameter(it->first, myArray, it->second) != true) {  abort = true;  }
			}
		
			output = validParameter.validFile(parameters, "output", false);			
			if (output == "not found") {  output = "";  } 
			
			input = validParameter.validFile(parameters, "input", false);			
			if (input == "not found") {  input = "";  }
			
			tempdefault = validParameter.validFile(parameters, "tempdefault", false);			
			if (tempdefault == "not found") {  tempdefault = "";  }
            
            bool debug = false;
            bool nodebug = false;
            debugorSeedOnly = false;
            string temp = validParameter.validFile(parameters, "debug", false);			
			if (temp == "not found") {  debug = false;  nodebug=true; }
            else {  debug = m->isTrue(temp); }
            m->debug = debug;
            
            bool nomod = false;
            temp = validParameter.validFile(parameters, "modifynames", false);
			if (temp == "not found") {  modifyNames = true;  nomod=true; }
            else {  modifyNames = m->isTrue(temp); }
            m->modifyNames = modifyNames;
            
            bool seed = false;
            temp = validParameter.validFile(parameters, "seed", false);
            if (temp == "not found") { random = 0; }
            else {
                if (m->isInteger(temp)) { m->mothurConvert(temp, random); seed = true; }
                else { m->mothurOut("[ERROR]: Seed must be an integer for the set.outdir command."); m->mothurOutEndLine(); abort = true; }
            }
            
            if (debug) { m->mothurOut("Setting [DEBUG] flag.\n"); }
            if (seed)  {
                m->mothurOut("\nRandom number(1-100) seeded with mothur's default of current time: " + toString(rand()%100 + 1) + ".\n");
                srand(random);
                m->mothurOut("Random number(1-100) seeded with " + toString(random) + ": " + toString(rand()%100 + 1) + ".\n\n");
            }
            
			if ((input == "") && (output == "") && (tempdefault == "") && nodebug && nomod && !seed) {
				m->mothurOut("[ERROR]: You must provide either an input, output, tempdefault, debug or modifynames for the set.outdir command."); m->mothurOutEndLine(); abort = true;
			}else if((input == "") && (output == "") && (tempdefault == "")) { debugorSeedOnly = true; }
		}
	}
	catch(exception& e) {
		m->errorOut(e, "SetDirectoryCommand", "SetDirectoryCommand");
		exit(1);
	}
}
Exemplo n.º 8
0
void
GNECrossing::setAttribute(SumoXMLAttr key, const std::string& value) {
    auto crossing = myParentJunction->getNBNode()->getCrossing(myCrossingEdges);
    switch (key) {
        case SUMO_ATTR_ID:
            throw InvalidArgument("Modifying attribute '" + toString(key) + "' of " + getTagStr() + " isn't allowed");
        case SUMO_ATTR_EDGES: {
            // obtain GNEEdges
            std::vector<GNEEdge*> edges = parse<std::vector<GNEEdge*> >(myNet, value);
            // remove NBEdges of crossing
            crossing->edges.clear();
            // set NBEdge of every GNEEdge into Crossing Edges
            for (auto i : edges) {
                crossing->edges.push_back(i->getNBEdge());
            }
            // sort new edges
            std::sort(crossing->edges.begin(), crossing->edges.end());
            // change myCrossingEdges by the new edges
            myCrossingEdges = crossing->edges;
            // update geometry of parent junction
            myParentJunction->updateGeometry(true);
            break;
        }
        case SUMO_ATTR_WIDTH:
            // Change width an refresh element
            crossing->customWidth = parse<double>(value);
            break;
        case SUMO_ATTR_PRIORITY:
            crossing->priority = parse<bool>(value);
            break;
        case SUMO_ATTR_TLLINKINDEX:
            crossing->customTLIndex = parse<int>(value);
            // make new value visible immediately
            crossing->tlLinkIndex = crossing->customTLIndex;
            break;
        case SUMO_ATTR_TLLINKINDEX2:
            crossing->customTLIndex2 = parse<int>(value);
            // make new value visible immediately
            crossing->tlLinkIndex2 = crossing->customTLIndex2;
            break;
        case SUMO_ATTR_CUSTOMSHAPE: {
            // first remove object from grid
            myNet->removeGLObjectFromGrid(this);
            // set custom shape
            crossing->customShape = parse<PositionVector>(value);
            // insert object in grid again
            myNet->removeGLObjectFromGrid(this);
            break;
        }
        case GNE_ATTR_SELECTED:
            if (parse<bool>(value)) {
                selectAttributeCarrier();
            } else {
                unselectAttributeCarrier();
            }
            break;
        case GNE_ATTR_GENERIC:
            setGenericParametersStr(value);
            break;
        default:
            throw InvalidArgument(getTagStr() + " doesn't have an attribute of type '" + toString(key) + "'");
    }
    // Crossing are a special case and we need ot update geometry of junction instead of crossing
    if ((key != SUMO_ATTR_ID) && (key != GNE_ATTR_GENERIC) && (key != GNE_ATTR_SELECTED)) {
        myParentJunction->updateGeometry(true);
    }
}
Exemplo n.º 9
0
/* -------------------------------------------------------------------------
 * main
 * ----------------------------------------------------------------------- */
int
main(int argc, char** argv) {
    OptionsCont& oc = OptionsCont::getOptions();
    // give some application descriptions
    oc.setApplicationDescription("Importer of O/D-matrices for the microscopic, multi-modal traffic simulation SUMO.");
    oc.setApplicationName("od2trips", "Eclipse SUMO od2trips Version " VERSION_STRING);
    int ret = 0;
    try {
        // initialise subsystems
        XMLSubSys::init();
        fillOptions();
        OptionsIO::setArgs(argc, argv);
        OptionsIO::getOptions();
        if (oc.processMetaOptions(argc < 2)) {
            SystemFrame::close();
            return 0;
        }
        XMLSubSys::setValidation(oc.getString("xml-validation"), oc.getString("xml-validation.net"));
        MsgHandler::initOutputOptions();
        if (!checkOptions()) {
            throw ProcessError();
        }
        RandHelper::initRandGlobal();
        // load the districts
        // check whether the user gave a net filename
        if (!oc.isSet("taz-files")) {
            throw ProcessError("You must supply a TAZ, network or districts file ('-n').");
        }
        // get the file name and set it
        ODDistrictCont districts;
        districts.loadDistricts(oc.getStringVector("taz-files"));
        if (districts.size() == 0) {
            throw ProcessError("No districts loaded.");
        }
        // load the matrix
        ODMatrix matrix(districts);
        matrix.loadMatrix(oc);
        if (matrix.getNumLoaded() == 0) {
            throw ProcessError("No vehicles loaded.");
        }
        if (MsgHandler::getErrorInstance()->wasInformed() && !oc.getBool("ignore-errors")) {
            throw ProcessError("Loading failed.");
        }
        WRITE_MESSAGE(toString(matrix.getNumLoaded()) + " vehicles loaded.");
        // apply a curve if wished
        if (oc.isSet("timeline")) {
            matrix.applyCurve(matrix.parseTimeLine(oc.getStringVector("timeline"), oc.getBool("timeline.day-in-hours")));
        }
        // write
        bool haveOutput = false;
        if (OutputDevice::createDeviceByOption("output-file", "routes", "routes_file.xsd")) {
            matrix.write(string2time(oc.getString("begin")), string2time(oc.getString("end")),
                         OutputDevice::getDeviceByOption("output-file"),
                         oc.getBool("spread.uniform"), oc.getBool("different-source-sink"),
                         oc.getBool("ignore-vehicle-type"),
                         oc.getString("prefix"), !oc.getBool("no-step-log"),
                         oc.getBool("pedestrians"),
                         oc.getBool("persontrips"));
            haveOutput = true;
        }
        if (OutputDevice::createDeviceByOption("flow-output", "routes", "routes_file.xsd")) {
            matrix.writeFlows(string2time(oc.getString("begin")), string2time(oc.getString("end")),
                              OutputDevice::getDeviceByOption("flow-output"),
                              oc.getBool("ignore-vehicle-type"), oc.getString("prefix"),
                              oc.getBool("flow-output.probability"));
            haveOutput = true;
        }
        if (!haveOutput) {
            throw ProcessError("No output file given.");
        }
        WRITE_MESSAGE(toString(matrix.getNumDiscarded()) + " vehicles discarded.");
        WRITE_MESSAGE(toString(matrix.getNumWritten()) + " vehicles written.");
    } catch (const ProcessError& e) {
        if (std::string(e.what()) != std::string("Process Error") && std::string(e.what()) != std::string("")) {
            WRITE_ERROR(e.what());
        }
        MsgHandler::getErrorInstance()->inform("Quitting (on error).", false);
        ret = 1;
#ifndef _DEBUG
    } catch (const std::exception& e) {
        if (std::string(e.what()) != std::string("")) {
            WRITE_ERROR(e.what());
        }
        MsgHandler::getErrorInstance()->inform("Quitting (on error).", false);
        ret = 1;
    } catch (...) {
        MsgHandler::getErrorInstance()->inform("Quitting (on unknown error).", false);
        ret = 1;
#endif
    }
    SystemFrame::close();
    if (ret == 0) {
        std::cout << "Success." << std::endl;
    }
    return ret;
}
Exemplo n.º 10
0
inline std::string toString( unsigned int value ) {
    return toString( static_cast<unsigned long>( value ) );
}
Exemplo n.º 11
0
void printStack(){
	for(int i = 0; i < obj_in_stack; i++){
		std::cout<<"Stack["<< i + 1 <<"] : " << toString(&loli_stack[i])<<std::endl;
	}
}
Exemplo n.º 12
0
int ClassifySeqsCommand::createProcesses(string taxFileName, string tempTaxFile, string accnos, string filename) {
	try {
		
		int num = 0;
		processIDS.clear();
        bool recalc = false;
		
#if defined (__APPLE__) || (__MACH__) || (linux) || (__linux) || (__linux__) || (__unix__) || (__unix)
		int process = 1;
		
		//loop through and create all the processes you want
		while (process != processors) {
			pid_t pid = fork();
			
			if (pid > 0) {
				processIDS.push_back(pid);  //create map from line number to pid so you can append files in correct order later
				process++;
			}else if (pid == 0){
				num = driver(lines[process], taxFileName + m->mothurGetpid(process) + ".temp", tempTaxFile + m->mothurGetpid(process) + ".temp", accnos + m->mothurGetpid(process) + ".temp", filename);

				//pass numSeqs to parent
				ofstream out;
				string tempFile = filename + m->mothurGetpid(process) + ".num.temp";
				m->openOutputFile(tempFile, out);
				out << num << endl;
				out.close();

				exit(0);
            }else {
                m->mothurOut("[ERROR]: unable to spawn the number of processes you requested, reducing number to " + toString(process) + "\n"); processors = process;
                for (int i = 0; i < processIDS.size(); i++) { kill (processIDS[i], SIGINT); }
                //wait to die
                for (int i=0;i<processIDS.size();i++) {
                    int temp = processIDS[i];
                    wait(&temp);
                }
                m->control_pressed = false;
                recalc = true;
                break;
            }
		}
        
        if (recalc) {
            //test line, also set recalc to true.
            //for (int i = 0; i < processIDS.size(); i++) { kill (processIDS[i], SIGINT); } for (int i=0;i<processIDS.size();i++) { int temp = processIDS[i]; wait(&temp); } m->control_pressed = false;  processors=3; m->mothurOut("[ERROR]: unable to spawn the number of processes you requested, reducing number to " + toString(processors) + "\n");
            for (int i = 0; i < lines.size(); i++) {  delete lines[i];  }  lines.clear();
            vector<unsigned long long> positions = m->divideFile(filename, processors);
            for (int i = 0; i < (positions.size()-1); i++) {	lines.push_back(new linePair(positions[i], positions[(i+1)]));	}
            
            num = 0;
            processIDS.resize(0);
            process = 1;
            
            while (process != processors) {
                pid_t pid = fork();
                
                if (pid > 0) {
                    processIDS.push_back(pid);  //create map from line number to pid so you can append files in correct order later
                    process++;
                }else if (pid == 0){
                    num = driver(lines[process], taxFileName + m->mothurGetpid(process) + ".temp", tempTaxFile + m->mothurGetpid(process) + ".temp", accnos + m->mothurGetpid(process) + ".temp", filename);
                    
                    //pass numSeqs to parent
                    ofstream out;
                    string tempFile = filename + m->mothurGetpid(process) + ".num.temp";
                    m->openOutputFile(tempFile, out);
                    out << num << endl;
                    out.close();
                    
                    exit(0);
                }else {
                    m->mothurOut("[ERROR]: unable to spawn the necessary processes."); m->mothurOutEndLine();
                    for (int i = 0; i < processIDS.size(); i++) { kill (processIDS[i], SIGINT); }
                    exit(0);
                }
            }
        }

		
		//parent does its part
		num = driver(lines[0], taxFileName, tempTaxFile, accnos, filename);
		
		//force parent to wait until all the processes are done
		for (int i=0;i<processIDS.size();i++) { 
			int temp = processIDS[i];
			wait(&temp);
		}
		
		for (int i = 0; i < processIDS.size(); i++) {
			ifstream in;
			string tempFile =  filename + toString(processIDS[i]) + ".num.temp";
			m->openInputFile(tempFile, in);
			if (!in.eof()) { int tempNum = 0; in >> tempNum; num += tempNum; }
			in.close(); m->mothurRemove(m->getFullPathName(tempFile));
		}
#else
		//////////////////////////////////////////////////////////////////////////////////////////////////////
		//Windows version shared memory, so be careful when passing variables through the alignData struct. 
		//Above fork() will clone, so memory is separate, but that's not the case with windows, 
		//////////////////////////////////////////////////////////////////////////////////////////////////////
		
		vector<classifyData*> pDataArray; 
		DWORD   dwThreadIdArray[processors-1];
		HANDLE  hThreadArray[processors-1]; 
		
		//Create processor worker threads.
		for( int i=0; i<processors-1; i++ ){
			// Allocate memory for thread data.
			string extension = "";
			if (i != 0) { extension = toString(i) + ".temp"; processIDS.push_back(i); }
			
			classifyData* tempclass = new classifyData((accnos + extension), probs, method, templateFileName, taxonomyFileName, (taxFileName + extension), (tempTaxFile + extension), filename, search, kmerSize, iters, numWanted, m, lines[i]->start, lines[i]->end, match, misMatch, gapOpen, gapExtend, cutoff, i, flip, writeShortcuts);
			pDataArray.push_back(tempclass);
			
			//MySeqSumThreadFunction is in header. It must be global or static to work with the threads.
			//default security attributes, thread function name, argument to thread function, use default creation flags, returns the thread identifier
			hThreadArray[i] = CreateThread(NULL, 0, MyClassThreadFunction, pDataArray[i], 0, &dwThreadIdArray[i]);  
			
		}
		
		//parent does its part
		num = driver(lines[processors-1], taxFileName + toString(processors-1) + ".temp", tempTaxFile + toString(processors-1) + ".temp", accnos + toString(processors-1) + ".temp", filename);
		processIDS.push_back((processors-1));
		
		//Wait until all threads have terminated.
		WaitForMultipleObjects(processors-1, hThreadArray, TRUE, INFINITE);
		
		//Close all thread handles and free memory allocations.
		for(int i=0; i < pDataArray.size(); i++){
			num += pDataArray[i]->count;
            if (pDataArray[i]->count != pDataArray[i]->end) {
                m->mothurOut("[ERROR]: process " + toString(i) + " only processed " + toString(pDataArray[i]->count) + " of " + toString(pDataArray[i]->end) + " sequences assigned to it, quitting. \n"); m->control_pressed = true; 
            }
			CloseHandle(hThreadArray[i]);
			delete pDataArray[i];
		}
		
	#endif	
        vector<string> nonBlankAccnosFiles;
		if (!(m->isBlank(accnos))) { nonBlankAccnosFiles.push_back(accnos); }
		else { m->mothurRemove(accnos); } //remove so other files can be renamed to it
        
		for(int i=0;i<processIDS.size();i++){
			m->appendFiles((taxFileName + toString(processIDS[i]) + ".temp"), taxFileName);
			m->appendFiles((tempTaxFile + toString(processIDS[i]) + ".temp"), tempTaxFile);
            if (!(m->isBlank(accnos + toString(processIDS[i]) + ".temp"))) {
				nonBlankAccnosFiles.push_back(accnos + toString(processIDS[i]) + ".temp");
			}else { m->mothurRemove((accnos + toString(processIDS[i]) + ".temp"));  }

			m->mothurRemove((m->getFullPathName(taxFileName) + toString(processIDS[i]) + ".temp"));
			m->mothurRemove((m->getFullPathName(tempTaxFile) + toString(processIDS[i]) + ".temp"));
		}
		
        //append accnos files
		if (nonBlankAccnosFiles.size() != 0) { 
			rename(nonBlankAccnosFiles[0].c_str(), accnos.c_str());
			
			for (int h=1; h < nonBlankAccnosFiles.size(); h++) {
				m->appendFiles(nonBlankAccnosFiles[h], accnos);
				m->mothurRemove(nonBlankAccnosFiles[h]);
			}
		}else { //recreate the accnosfile if needed
			ofstream out;
			m->openOutputFile(accnos, out);
			out.close();
		}

		return num;
		
	}
Exemplo n.º 13
0
int ClassifySeqsCommand::execute(){
	try {
		if (abort == true) { if (calledHelp) { return 0; }  return 2;	}
        
        string outputMethodTag = method;
		if(method == "wang"){	classify = new Bayesian(taxonomyFileName, templateFileName, search, kmerSize, cutoff, iters, rand(), flip, writeShortcuts);	}
		else if(method == "knn"){	classify = new Knn(taxonomyFileName, templateFileName, search, kmerSize, gapOpen, gapExtend, match, misMatch, numWanted, rand());				}
        else if(method == "zap"){	
            outputMethodTag = search + "_" + outputMethodTag;
            if (search == "kmer") {   classify = new KmerTree(templateFileName, taxonomyFileName, kmerSize, cutoff); }
            else {  classify = new AlignTree(templateFileName, taxonomyFileName, cutoff);  }
        }
		else {
			m->mothurOut(search + " is not a valid method option. I will run the command using wang.");
			m->mothurOutEndLine();
			classify = new Bayesian(taxonomyFileName, templateFileName, search, kmerSize, cutoff, iters, rand(), flip, writeShortcuts);	
		}
		
		if (m->control_pressed) { delete classify; return 0; }
				
		for (int s = 0; s < fastaFileNames.size(); s++) {
		
			m->mothurOut("Classifying sequences from " + fastaFileNames[s] + " ..." ); m->mothurOutEndLine();
			
			string baseTName = m->getSimpleName(taxonomyFileName);
			
            //set rippedTaxName to 
			string RippedTaxName = "";
            bool foundDot = false;
            for (int i = baseTName.length()-1; i >= 0; i--) {
                if (foundDot && (baseTName[i] != '.')) {  RippedTaxName = baseTName[i] + RippedTaxName; }
                else if (foundDot && (baseTName[i] == '.')) {  break; }
                else if (!foundDot && (baseTName[i] == '.')) {  foundDot = true; }
            }
            //if (RippedTaxName != "") { RippedTaxName +=  "."; }   
          
			if (outputDir == "") { outputDir += m->hasPath(fastaFileNames[s]); }
            map<string, string> variables; 
            variables["[filename]"] = outputDir + m->getRootName(m->getSimpleName(fastaFileNames[s]));
            variables["[tag]"] = RippedTaxName;
            variables["[tag2]"] = outputMethodTag;
			string newTaxonomyFile = getOutputFileName("taxonomy", variables);
			string newaccnosFile = getOutputFileName("accnos", variables);
			string tempTaxonomyFile = outputDir + m->getRootName(m->getSimpleName(fastaFileNames[s])) + "taxonomy.temp";
			string taxSummary = getOutputFileName("taxsummary", variables);
			
			if ((method == "knn") && (search == "distance")) { 
				string DistName = getOutputFileName("matchdist", variables);
				classify->setDistName(DistName);  outputNames.push_back(DistName); outputTypes["matchdist"].push_back(DistName);
			}
			
			outputNames.push_back(newTaxonomyFile); outputTypes["taxonomy"].push_back(newTaxonomyFile);
			outputNames.push_back(taxSummary);	outputTypes["taxsummary"].push_back(taxSummary);
			
			int start = time(NULL);
			int numFastaSeqs = 0;
			for (int i = 0; i < lines.size(); i++) {  delete lines[i];  }  lines.clear();
		
			vector<unsigned long long> positions; 
#if defined (__APPLE__) || (__MACH__) || (linux) || (__linux) || (__linux__) || (__unix__) || (__unix)
			positions = m->divideFile(fastaFileNames[s], processors);
			for (int i = 0; i < (positions.size()-1); i++) {	lines.push_back(new linePair(positions[i], positions[(i+1)]));	}
#else
			if (processors == 1) {
				lines.push_back(new linePair(0, 1000));
			}else {
				positions = m->setFilePosFasta(fastaFileNames[s], numFastaSeqs); 
                if (numFastaSeqs < processors) { processors = numFastaSeqs; }
				
				//figure out how many sequences you have to process
				int numSeqsPerProcessor = numFastaSeqs / processors;
				for (int i = 0; i < processors; i++) {
					int startIndex =  i * numSeqsPerProcessor;
					if(i == (processors - 1)){	numSeqsPerProcessor = numFastaSeqs - i * numSeqsPerProcessor; 	}
					lines.push_back(new linePair(positions[startIndex], numSeqsPerProcessor));
				}
			}
#endif
			if(processors == 1){
				numFastaSeqs = driver(lines[0], newTaxonomyFile, tempTaxonomyFile, newaccnosFile, fastaFileNames[s]);
			}else{
				numFastaSeqs = createProcesses(newTaxonomyFile, tempTaxonomyFile, newaccnosFile, fastaFileNames[s]); 
			}
			
			if (!m->isBlank(newaccnosFile)) { m->mothurOutEndLine(); m->mothurOut("[WARNING]: mothur reversed some your sequences for a better classification.  If you would like to take a closer look, please check " + newaccnosFile + " for the list of the sequences."); m->mothurOutEndLine(); 
                outputNames.push_back(newaccnosFile); outputTypes["accnos"].push_back(newaccnosFile);
            }else { m->mothurRemove(newaccnosFile); }

            m->mothurOutEndLine();
            m->mothurOut("It took " + toString(time(NULL) - start) + " secs to classify " + toString(numFastaSeqs) + " sequences."); m->mothurOutEndLine(); m->mothurOutEndLine();
            start = time(NULL);
            
            //read namefile
            if(namefile != "") {
                
                m->mothurOut("Reading " + namefileNames[s] + "..."); cout.flush();
                nameMap.clear(); //remove old names
                m->readNames(namefileNames[s], nameMap);
                m->mothurOut("  Done."); m->mothurOutEndLine();
            }
            
            //output taxonomy with the unclassified bins added
            ifstream inTax;
            m->openInputFile(newTaxonomyFile, inTax);
            
            ofstream outTax;
            string unclass = newTaxonomyFile + ".unclass.temp";
            m->openOutputFile(unclass, outTax);
            
            //get maxLevel from phylotree so you know how many 'unclassified's to add
            int maxLevel = classify->getMaxLevel();
            
            //read taxfile - this reading and rewriting is done to preserve the confidence scores.
            string name, taxon;
            string group = "";
            GroupMap* groupMap = NULL;
            CountTable* ct = NULL;
            PhyloSummary* taxaSum;
            
            if (hasCount) {
                ct = new CountTable();
                ct->readTable(countfileNames[s], true, false);
                taxaSum = new PhyloSummary(ct, relabund, printlevel);
            }else {
                if (groupfile != "") {  group = groupfileNames[s]; groupMap = new GroupMap(group); groupMap->readMap(); }
                taxaSum = new PhyloSummary(groupMap, relabund, printlevel);
            }
            
            while (!inTax.eof()) {
                if (m->control_pressed) { outputTypes.clear(); if (ct != NULL) { delete ct; }  if (groupMap != NULL) { delete groupMap; } delete taxaSum; for (int i = 0; i < outputNames.size(); i++) {	m->mothurRemove(outputNames[i]);	} delete classify; return 0; }
                
                inTax >> name >> taxon; m->gobble(inTax);
                
                string newTax = m->addUnclassifieds(taxon, maxLevel, probs);
                
                outTax << name << '\t' << newTax << endl;
                
                if (namefile != "") {
                    itNames = nameMap.find(name);
                    
                    if (itNames == nameMap.end()) {
                        m->mothurOut(name + " is not in your name file please correct."); m->mothurOutEndLine(); exit(1);
                    }else{
                        for (int i = 0; i < itNames->second.size(); i++) {
                            taxaSum->addSeqToTree(itNames->second[i], newTax);  //add it as many times as there are identical seqs
                        }
                        itNames->second.clear();
                        nameMap.erase(itNames->first);
                    }
                }else {
                    taxaSum->addSeqToTree(name, newTax);
                }
            }
            inTax.close();
            outTax.close();
            
            m->mothurRemove(newTaxonomyFile);
            rename(unclass.c_str(), newTaxonomyFile.c_str());
            
            if (m->control_pressed) {  outputTypes.clear(); if (ct != NULL) { delete ct; } if (groupMap != NULL) { delete groupMap; } for (int i = 0; i < outputNames.size(); i++) {	m->mothurRemove(outputNames[i]);	} delete classify; return 0; }
            
            //print summary file
            ofstream outTaxTree;
            m->openOutputFile(taxSummary, outTaxTree);
            taxaSum->print(outTaxTree, output);
            outTaxTree.close();
            
            if (ct != NULL) { delete ct; }
            if (groupMap != NULL) { delete groupMap; } delete taxaSum;
            m->mothurRemove(tempTaxonomyFile);
            
            m->mothurOutEndLine();
            m->mothurOut("It took " + toString(time(NULL) - start) + " secs to create the summary file for " + toString(numFastaSeqs) + " sequences."); m->mothurOutEndLine(); m->mothurOutEndLine();
			
		}
        delete classify;
        
        m->mothurOutEndLine();
        m->mothurOut("Output File Names: "); m->mothurOutEndLine();
        for (int i = 0; i < outputNames.size(); i++) {	m->mothurOut(outputNames[i]); m->mothurOutEndLine();	}
        m->mothurOutEndLine();
		
		//set taxonomy file as new current taxonomyfile
		string current = "";
		itTypes = outputTypes.find("taxonomy");
		if (itTypes != outputTypes.end()) {
			if ((itTypes->second).size() != 0) { current = (itTypes->second)[0]; m->setTaxonomyFile(current); }
		}
		
		current = "";
		itTypes = outputTypes.find("accnos");
		if (itTypes != outputTypes.end()) {
			if ((itTypes->second).size() != 0) { current = (itTypes->second)[0]; m->setAccnosFile(current); }
		}
		
		
		
		return 0;
	}
	catch(exception& e) {
		m->errorOut(e, "ClassifySeqsCommand", "execute");
		exit(1);
	}
}
Exemplo n.º 14
0
	bool copy(const NetworkPath& src, const NetworkPath& trg) {
		string srcFile = toString(src);
		string trgFile = toString(trg);
		return runCommand("scp -r -p " + srcFile + " " + trgFile) == 0;
	}
Exemplo n.º 15
0
 Error(int code, const A& arg1)
     : code_(code), count_(1), arg1_(toString(arg1))
 {
     setMsg();
 }
Exemplo n.º 16
0
// ===========================================================================
// method definitions
// ===========================================================================
TraCIServer::TraCIServer(const SUMOTime begin, const int port)
    : mySocket(0), myTargetTime(begin), myDoingSimStep(false), myAmEmbedded(port == 0), myLaneTree(0) {

    myVehicleStateChanges[MSNet::VEHICLE_STATE_BUILT] = std::vector<std::string>();
    myVehicleStateChanges[MSNet::VEHICLE_STATE_DEPARTED] = std::vector<std::string>();
    myVehicleStateChanges[MSNet::VEHICLE_STATE_STARTING_TELEPORT] = std::vector<std::string>();
    myVehicleStateChanges[MSNet::VEHICLE_STATE_ENDING_TELEPORT] = std::vector<std::string>();
    myVehicleStateChanges[MSNet::VEHICLE_STATE_ARRIVED] = std::vector<std::string>();
    myVehicleStateChanges[MSNet::VEHICLE_STATE_NEWROUTE] = std::vector<std::string>();
    myVehicleStateChanges[MSNet::VEHICLE_STATE_STARTING_PARKING] = std::vector<std::string>();
    myVehicleStateChanges[MSNet::VEHICLE_STATE_ENDING_PARKING] = std::vector<std::string>();
    myVehicleStateChanges[MSNet::VEHICLE_STATE_STARTING_STOP] = std::vector<std::string>();
    myVehicleStateChanges[MSNet::VEHICLE_STATE_ENDING_STOP] = std::vector<std::string>();
    MSNet::getInstance()->addVehicleStateListener(this);

    myExecutors[CMD_GET_INDUCTIONLOOP_VARIABLE] = &TraCIServerAPI_InductionLoop::processGet;
    myExecutors[CMD_GET_AREAL_DETECTOR_VARIABLE] = &TraCIServerAPI_ArealDetector::processGet;
    myExecutors[CMD_GET_MULTI_ENTRY_EXIT_DETECTOR_VARIABLE] = &TraCIServerAPI_MeMeDetector::processGet;

    myExecutors[CMD_GET_TL_VARIABLE] = &TraCIServerAPI_TLS::processGet;
    myExecutors[CMD_SET_TL_VARIABLE] = &TraCIServerAPI_TLS::processSet;
    myExecutors[CMD_GET_LANE_VARIABLE] = &TraCIServerAPI_Lane::processGet;
    myExecutors[CMD_SET_LANE_VARIABLE] = &TraCIServerAPI_Lane::processSet;
    myExecutors[CMD_GET_VEHICLE_VARIABLE] = &TraCIServerAPI_Vehicle::processGet;
    myExecutors[CMD_SET_VEHICLE_VARIABLE] = &TraCIServerAPI_Vehicle::processSet;
    myExecutors[CMD_GET_VEHICLETYPE_VARIABLE] = &TraCIServerAPI_VehicleType::processGet;
    myExecutors[CMD_SET_VEHICLETYPE_VARIABLE] = &TraCIServerAPI_VehicleType::processSet;
    myExecutors[CMD_GET_ROUTE_VARIABLE] = &TraCIServerAPI_Route::processGet;
    myExecutors[CMD_SET_ROUTE_VARIABLE] = &TraCIServerAPI_Route::processSet;
    myExecutors[CMD_GET_POI_VARIABLE] = &TraCIServerAPI_POI::processGet;
    myExecutors[CMD_SET_POI_VARIABLE] = &TraCIServerAPI_POI::processSet;
    myExecutors[CMD_GET_POLYGON_VARIABLE] = &TraCIServerAPI_Polygon::processGet;
    myExecutors[CMD_SET_POLYGON_VARIABLE] = &TraCIServerAPI_Polygon::processSet;
    myExecutors[CMD_GET_JUNCTION_VARIABLE] = &TraCIServerAPI_Junction::processGet;
    myExecutors[CMD_GET_EDGE_VARIABLE] = &TraCIServerAPI_Edge::processGet;
    myExecutors[CMD_SET_EDGE_VARIABLE] = &TraCIServerAPI_Edge::processSet;
    myExecutors[CMD_GET_SIM_VARIABLE] = &TraCIServerAPI_Simulation::processGet;
    myExecutors[CMD_SET_SIM_VARIABLE] = &TraCIServerAPI_Simulation::processSet;

    myParameterSizes[VAR_LEADER] = 9;

    myDoCloseConnection = false;

    // display warning if internal lanes are not used
    if (!MSGlobals::gUsingInternalLanes) {
        WRITE_WARNING("Starting TraCI without using internal lanes!");
        MsgHandler::getWarningInstance()->inform("Vehicles will jump over junctions.", false);
        MsgHandler::getWarningInstance()->inform("Use without option --no-internal-links to avoid unexpected behavior", false);
    }

    if (!myAmEmbedded) {
        try {
            WRITE_MESSAGE("***Starting server on port " + toString(port) + " ***");
            mySocket = new tcpip::Socket(port);
            mySocket->accept();
            // When got here, a client has connected
        } catch (tcpip::SocketException& e) {
            throw ProcessError(e.what());
        }
    }
}
Exemplo n.º 17
0
 Error(int code, const A& arg1, const B& arg2, const C& arg3)
     : code_(code), count_(3),
       arg1_(toString(arg1)), arg2_(toString(arg2)), arg3_(toString(arg3))
 {
     setMsg();
 }
Exemplo n.º 18
0
//*******************************************************************
// Public Method: ossimDrect::print
//*******************************************************************
void ossimDrect::print(std::ostream& os) const
{
    os << toString();
}
Exemplo n.º 19
0
 MyObject3(int value) : value(value) {
     print_created(this, toString());
 }
Exemplo n.º 20
0
void DebugModeStatPrinter::run() {
  const string separator = "--------------------------------------------------";
  const string indent1 = " ";
  const string indent2 = indent1 + "      ";

  statFile.open("debug_mode_stats_file.txt", ios::trunc);
  printLine("This file was created because Infra Arcana was run in Debug mode\n");
  printLine("Created on   : " + eng->basicUtils->getCurrentTime().getTimeStr(time_minute, true));
  printLine("Game version : " + eng->config->GAME_VERSION);
  printLine("\n");

  printLine("SPELL MAX SPI COSTS");
  printLine(separator);
  for(int i = 0; i < endOfSpells; i++) {
    Spell* const spell = eng->spellHandler->getSpellFromId(Spell_t(i));
    string name = spell->getName();
    name.insert(name.end(), 24 - name.size(), ' ');
    Range cost = spell->getSpiCost(true, eng->player, eng);
    const string costStr =
      toString(cost.lower) + "-" + toString(cost.upper);
    delete spell;
    printLine(indent1 + name + costStr);
  }
  printLine("\n");

  vector<ActorData*> actorDataSorted;
  for(unsigned int i = actor_player + 1; i < endOfActorIds; i++) {
    actorDataSorted.push_back(&(eng->actorDataHandler->dataList[i]));
  }
  IsHigherSpawnMinLvl isHigherSpawnMinLvl;
  std::sort(actorDataSorted.begin(), actorDataSorted.end(), isHigherSpawnMinLvl);

  printLine("MONSTERS PER MIN DLVL");
  printLine(separator);
  printLine(indent1 + "LVL   NR");
  printLine(indent1 + "---------");

  vector<int> monstersPerMinDLVL(actorDataSorted.back()->spawnMinDLVL + 1, 0);
  for(unsigned int i = 0; i < actorDataSorted.size(); i++) {
    monstersPerMinDLVL.at(actorDataSorted.at(i)->spawnMinDLVL)++;
  }
  for(unsigned int i = 0; i < monstersPerMinDLVL.size(); i++) {
    const int LVL = i;
    string lvlStr = toString(LVL);
    lvlStr.insert(lvlStr.end(), 6 - lvlStr.size(), ' ');
    string nrStr = toString(monstersPerMinDLVL.at(i));
    nrStr.insert(nrStr.end(), 3, ' ');
    if(monstersPerMinDLVL.at(i) > 0) {
      nrStr.insert(nrStr.end(), monstersPerMinDLVL.at(i), '*');
    }
    printLine(indent1 + lvlStr + nrStr);
  }
  printLine("\n" + indent1 + "Total number of monsters: " +
            toString(actorDataSorted.size()));
  printLine("\n");

  printLine("STATS FOR EACH MONSTER");
  printLine(separator);
  printLine(indent1 + "Notes:");
  printLine(indent1 + "(U) = Unique monster");
  printLine(indent1 + "(M) = Melee weapon");
  printLine(indent1 + "(R) = Ranged weapon");
  printLine("");

  for(unsigned int i = 0; i < actorDataSorted.size(); i++) {
    ActorData& d = *(actorDataSorted.at(i));

    Actor* const actor = eng->actorFactory->makeActorFromId(d.id);
    actor->place(Pos(-1, -1), &d, eng);

    const string uniqueStr = d.isUnique ? " (U)" : "";
    printLine(indent1 + actor->getNameA() + uniqueStr);

    const string xpStr =
      "XP:" + toString(eng->dungeonMaster->getMonsterXpWorth(d));
    printLine(indent2 + xpStr);

    string hpStr = "HP:" + toString(d.hp);
    hpStr.insert(hpStr.end(), 8 - hpStr.size(), ' ');

    const int attackSkill = d.abilityVals.getVal(ability_accuracyMelee, false, *actor);
    const string attackSkillStr = "Attack skill:" + toString(attackSkill) + "%";
    printLine(indent2 + hpStr + attackSkillStr);

    const Inventory* const inv = actor->getInventory();
    const unsigned int NR_INTRINSIC_ATTACKS = inv->getIntrinsicsSize();
    for(unsigned int i_intr = 0; i_intr < NR_INTRINSIC_ATTACKS; i_intr++) {
      const Item* const item = inv->getIntrinsicInElement(i_intr);
      const ItemData& itemData = item->getData();
      const string meleeOrRangedStr = itemData.isRangedWeapon ? "(R)" : "(M)";
      const string attackNrStr = "Attack " + toString(i_intr + 1);
      const string dmgStr =
        toString(itemData.meleeDmg.first) + "d" +
        toString(itemData.meleeDmg.second);
      printLine(
        indent2 + attackNrStr + " " + meleeOrRangedStr + ": " + dmgStr);
    }
    delete actor;

    printLine("");
  }



  statFile.close();
}
Exemplo n.º 21
0
  {OptionId::RETIRED_VILLAINS, "Retired villains"},
  {OptionId::LESSER_VILLAINS, "Lesser villains"},
  {OptionId::ALLIES, "Allies"},
  {OptionId::INFLUENCE_SIZE, "Min. tribes in influence zone"},
};

const map<OptionId, string> hints {
  {OptionId::HINTS, "Display some extra helpful information during the game."},
  {OptionId::ASCII, "Switch to old school roguelike graphics."},
  {OptionId::KEEP_SAVEFILES, "Don't remove the save file when a game is loaded."},
  {OptionId::FULLSCREEN, "Switch between fullscreen and windowed mode."},
  {OptionId::FULLSCREEN_RESOLUTION, "Choose resolution for fullscreen mode."},
  {OptionId::ZOOM_UI, "All UI and graphics are zoomed in 2x. "
      "Use you have a large resolution screen and things appear too small."},
  {OptionId::ONLINE, "Upload your highscores and retired dungeons to keeperrl.com."},
  {OptionId::AUTOSAVE, "Autosave the game every " + toString(MainLoop::getAutosaveFreq()) + " turns. "
    "The save file will be used to recover in case of a crash."},
  {OptionId::WASD_SCROLLING, "Scroll the map using W-A-S-D keys. In this mode building shortcuts are accessed "
    "using alt + letter."},
};

const map<OptionSet, vector<OptionId>> optionSets {
  {OptionSet::GENERAL, {
      OptionId::HINTS,
      OptionId::ASCII,
      OptionId::MUSIC,
      OptionId::SOUND,
      OptionId::FULLSCREEN,
      OptionId::FULLSCREEN_RESOLUTION,
      OptionId::ZOOM_UI,
      OptionId::ONLINE,
Exemplo n.º 22
0
void ListServer_Main()
{
	static CBuffer packetBuffer;
	CStringList lines;

	if ( listServerFields[5] == "localhost" ) return;
	if (!lsConnected) return;

	// Read any new data into the socket.
	if ( listServer.getData() == -1 )
	{
		errorOut( "serverlog.txt", "Disconnected from list server." );
		lsConnected = false;
		return;
	}

	// Grab all the data from the socket buffer.
	packetBuffer << listServer.getBuffer();
	listServer.getBuffer().clear();

	// Search for a packet.  If none is found, break out of the loop.
	while (packetBuffer.length() != 0)
	{
		CPacket line;
		if (!nextIsRaw)
		{
			int lineEnd = packetBuffer.find( '\n' );
			if ( lineEnd == -1 ) return;

			// Copy the packet out and remove the \n
			line = packetBuffer.copy( 0, lineEnd + 1 );
			packetBuffer.remove(0, line.length());
			line.remove(line.length() - 1, 1);
		}
		else
		{
			if (packetBuffer.length() < rawPacketSize) return;
			line.writeBytes(packetBuffer.readChars(rawPacketSize), rawPacketSize);
			packetBuffer.remove(0, line.length());
			line.remove(line.length() - 1, 1);
			nextIsRaw = false;
		}
		packetBuffer.setRead(0);

		int messageId = line.readByte1();
		switch (messageId)
		{
			case GSVOLD:
			{
				printf("[%s] SERVER VERSION CHECK - Current: %i, Latest: %i - Old version, please upgrade.\n", getTimeStr(1).text(), GSERVER_BUILD, line.readByte2());
				break;
			}

			case GSVCURRENT:
			{
				printf("[%s] SERVER VERSION CHECK - Current: %i, Latest: %i - You are up to date :)\n", getTimeStr(1).text(), GSERVER_BUILD, GSERVER_BUILD);
				break;
			}

			case GSVACCOUNT:
			{
				CString accountName = line.readChars(line.readByte1());
				CString errorMsg = line.readString("");

				for (int i = 0; i < newPlayers.count(); i++)
				{
					CPlayer *player = (CPlayer *)newPlayers[i];

					if (player->accountName.comparei(accountName) == 0)
					{
						// The serverlist will return case sensitive account names.
						// This helps case sensitive file systems open/save the correct
						// acount.
						player->accountName = accountName;
						if (errorMsg == "SUCCESS")
						{
							player->sendAccount();
						}
						else
						{
							player->sendPacket(CPacket() << (char)DISMESSAGE << errorMsg);
							player->deleteMe = true;
						}

						break;
					}
				}

				break;
			}

			case GSVGUILD:
			{
				int playerId = line.readByte2();
				CPlayer *player = (CPlayer *)playerIds[playerId];

				if (player != NULL)
				{
					CString nick = line.readChars((unsigned char)line.readByte1());
					CString guild = nick.copy( nick.findl( '(' ) ).remove( ")" );

					if ( globalGuilds == false )
					{
						if ( globalGuildList.find( guild ) != -1 )
							player->setNick(nick, false);
					}
					else
						player->setNick(nick, false);
				}

				break;
			}

			case GSVPROFILE: /* Unsure if this works, temp */
			{
				CPacket profile;
				CPlayer *player1 = (CPlayer *)playerIds[line.readByte2()];
				CPlayer *player2 = findPlayerId(line.readChars(line.readByte1()));
				if (player1 == NULL || player2 == NULL)
					return;

				profile << (char)player2->accountName.length() << player2->accountName << line.readString("");

				int time = player2->onlineSecs;
				CString line2;
				//Online time
				line2 << toString((int)time/3600) << " hrs ";
				line2 << toString((int)(time/60)%60) << " mins ";
				line2 << toString((int)time%60) << " secs";
				profile << (char)line2.length() << line2;

				for (int i = 0; i < profileList.count(); i++)
				{
					CStringList a;
					a.load(profileList[i].text(), ":=");
					if (a[0].length() < 1)
						continue;

					CString n;

					if (a[1] == "playerkills")
						n = toString(player2->kills);
					else if (a[1] == "playerdeaths")
						n = toString(player2->deaths);
					else if (a[1] == "playerfullhearts")
					{
						if ( (float)(int)player2->maxPower == (float)player2->maxPower )
							n = toString((int)player2->maxPower);
						else
						{
							n = toString(player2->maxPower);
							n = n.copy( 0, n.length() - 1 );
						}
					}
					else if (a[1] == "playerrating")
						n = toString((int)player2->rating) << "/" << toString((int)player2->deviation);
					else if (a[1] == "playerap")
						n = toString(player2->ap);
					else if (a[1] == "playerrupees")
						n = toString(player2->rubins);
					else if (a[1] == "playerswordpower")
						n = toString(player2->swordPower);
					else if (a[1] == "canspin")
						n = (player2->status & 64 ? "true" : "false");
					else if (a[1] == "playerhearts")
					{
						if ( (float)(int)player2->power == (float)player2->power )
							n = toString((int)player2->power);
						else
						{
							n = toString(player2->power);
							n = n.copy( 0, n.length() - 1 );
						}
					}
					else if (a[1] == "playerdarts")
						n = toString(player2->darts);
					else if (a[1] == "playerbombs")
						n = toString(player2->bombs);
					else if (a[1] == "playermp")
						n = toString(player2->magicPoints);
					else if (a[1] == "playershieldpower")
						n = toString(player2->shieldPower);
					else if (a[1] == "playerglovepower")
						n = toString(player2->glovePower);
					else
					{
						for (int i = 0; i < player2->myFlags.count(); i++)
						{
							CStringList b;
							b.load(player2->myFlags[i].text(), "=");
							if (b[0] == a[1])
							{
								n = b[1];
								break;
							}
						}
					}

					profile << (char)(a[0].length() + n.length() + 2) << a[0] << ":=" << n;
				}

				player1->sendPacket(CPacket() << (char)DPROFILE << profile);
				break;
			}

			case GSVMSG:
				printf("[%s] %s\n", getTimeStr(1).text(), line.readString(""));
			break;

			case GSVFILESTART3:
			{
				unsigned char pTy = (unsigned char)line.readByte1();
				CString fileData, fileName = CString() << dataDir << "global" << fSep;
				switch (pTy)
				{
					case 0: // head
						fileName << "heads" << fSep;
					break;

					case 1: // body
						fileName << "bodies" << fSep;
					break;

					case 2: // sword
						fileName << "swords" << fSep;
					break;

					case 3: // shield
						fileName << "shields" << fSep;
					break;
				}
				fileName << line.readChars(line.readByte1());
				fileData.save(fileName.text());
				break;
			}

			case GSVFILEDATA3:
			{
				unsigned char pTy = (unsigned char)line.readByte1();
				CString fileData, fileName, newData, shortName;
				shortName = line.readChars(line.readByte1());
				fileName = CString() << dataDir << "global" << fSep;
				switch (pTy)
				{
					case 0: // head
						fileName << "heads" << fSep;
					break;

					case 1: // body
						fileName << "bodies" << fSep;
					break;

					case 2: // sword
						fileName << "swords" << fSep;
					break;

					case 3: // shield
						fileName << "shields" << fSep;
					break;
				}
				fileName << shortName.text();
				newData.writeBytes(line.readChars(line.bytesLeft()), line.bytesLeft());

				fileData.load(fileName.text());
				fileData << newData;
				fileData.save(fileName.text());
				break;
			}

			case GSVFILEEND3:
			{
				CPlayer *player = (CPlayer *)playerIds[line.readByte2()];
				int type = line.readByte1();
				char doCompress = line.readByte1();
				time_t modTime = line.readByte5();
				int fileLength = line.readByte5();
				CString shortName = line.readString("");
				CString fileName = CString() << dataDir << "global" << fSep;
				switch (type)
				{
					case 0: // head
						fileName << "heads" << fSep;
					break;

					case 1: // body
						fileName << "bodies" << fSep;
					break;

					case 2: // sword
						fileName << "swords" << fSep;
					break;

					case 3: // shield
						fileName << "shields" << fSep;
					break;
				}
				fileName << shortName.text();

				// If the file was sent compressed, we need to uncompress it.
				if (doCompress == 1)
				{
					// Open the file so we can uncompress it.
					CString fileData;
					fileData.load(fileName.text());

					// Uncompress the file.
					char* buffer = new char[fileLength];
					memset((void*)buffer, 0, fileLength);
					int cLen = fileLength;
					int error = uncompress((Bytef*)buffer,(uLongf*)&cLen,(const Bytef*)fileData.text(), fileData.length());
					if (error != Z_OK) printf("Failed to decompress file: %s\n", shortName.text());

					// Save the file now.
					fileData.clear();
					fileData.writeBytes(buffer, cLen);
					fileData.save(fileName.text());
					delete [] buffer;
				}

				// Set the file mod time.
				if (setFileModTime(fileName.text(), modTime) == false)
					printf("** [WARNING] Could not set modification time on file %s\n", shortName.text());

				if (player)
				{
					player->fileList.add(new COutFile(shortName, 0));
					switch (type)
					{
						case 0: // head
							player->headImage = shortName;
							player->updateProp(HEADGIF);
						break;

						case 1: // body
							player->bodyImage = shortName;
							player->updateProp(BODYIMG);
						break;

						case 2: // sword
							player->swordImage = shortName;
							player->updateProp(SWORDPOWER);
						break;

						case 3: // shield
							player->shieldImage = shortName;
							player->updateProp(SHIELDPOWER);
						break;
					}
				}
				break;
			}

			case GSVPING:
				// Sent every 60 seconds, do nothing.
			break;

			case GSVRAWDATA:
				nextIsRaw = true;
				rawPacketSize = line.readByte3();
			break;

			default:
				printf("[%s] Invalid List Server Message: %i\n", getTimeStr(1).text(), messageId);
			break;
		}
	}
}
Exemplo n.º 23
0
string Histogram::valuesToString(){
  return toString();
}
Exemplo n.º 24
0
void DateTime::display() {
    std::cout << toString() << std::endl;
}
Exemplo n.º 25
0
bool NativePath::exists() const
{
    if (isEmpty()) return false;
    return QFile::exists(toString());
}
void EuroToYenConverter::print() const{
  std::cout << toString();
}
Exemplo n.º 27
0
NativePath NativePath::concatenatePath(NativePath const &nativePath) const
{
    if (nativePath.isAbsolute()) return nativePath;
    return toString().concatenatePath(nativePath, QChar(DIR_SEPARATOR));
}
Exemplo n.º 28
0
MM::VOID MM::Definition::toString(MM::String * buf)
{
  toString(buf, 0);
}
Exemplo n.º 29
0
 JObject* JObject::clone(){
      throw new JCloneNotSupportedException("not clonable "+toString());
 }
Exemplo n.º 30
0
	bool remove(const NetworkPath& path) {
		if (path.isLocal()) return bfs::remove(path.path);
		string file = toString(path.path);
		return runCommand("ssh " + path.getUserHostnamePrefix() + " \"test -f " + file + " && rm " + file + "\"") == 0;
	}