コード例 #1
1
ファイル: ArmParser.cpp プロジェクト: ketlerd/armips
void ArmParser::parsePsr(Parser& parser, bool& dest)
{
    dest = parser.peekToken().type == TokenType::Caret;
    if (dest)
        parser.eatToken();
}
コード例 #2
0
ファイル: MipsMacros.cpp プロジェクト: Kingcom/armips
std::unique_ptr<CAssemblerCommand> createMacro(Parser& parser, const std::wstring& text, int flags, std::initializer_list<AssemblyTemplateArgument> variables)
{
	std::unique_ptr<CAssemblerCommand> content = parser.parseTemplate(text,variables);
	return ::make_unique<MipsMacroCommand>(std::move(content),flags);
}
コード例 #3
0
ファイル: itemclass.cpp プロジェクト: laurynasl/gerpgr
void ItemClass:: load(Parser& parser) {
    stackability = Stackable; // most items are stackable, except containers, depletable and some others
    parser >> name;
    int token;
    do {
        token = parser.nextToken();
        switch (token) {
            case tktOnehanded: {
                onehanded.load(parser);
                break;
            }
            case tktTwohanded: {
                twohanded.load(parser);
                break;
            }
            case tktThrown: {
                thrown.load(parser);
                break;
            }
            // just features
            case tktPrototype: {
                features.insert(token);
                break;
            }
            // string features
            case tktKey: {
                stringFeatures.insert(token, parser.getString());
                Tables::addKeyCode(stringFeatures[token]);
                break;
            }
            // int features
            case tktDv: {
                intFeatures.insert(token, parser.getInt());
                break;
            }
            // token features
            case tktEquipSlot: {
                tokenFeatures.insert(token, parser.nextToken());
                break;
            }
            case tktLike: {
                QString otherName;
                parser >> otherName;
                int otherIndex = Tables::nameToItem(otherName);
                assert(otherIndex >= 0);
                const ItemClass& other = Tables::itemToClass(otherIndex);
                {// name isn't copied. everything else is
                    onehanded = other.onehanded;
                    twohanded = other.twohanded;
                    thrown = other.thrown;
                    stackability = other.stackability;
                    features = other.features;
                    stringFeatures = other.stringFeatures;
                    intFeatures = other.intFeatures;
                    tokenFeatures = other.tokenFeatures;
                    // parent (other) item mustn't be marked as prototype to be used as prototype
                    features.remove(tktPrototype);
                }
                break;
            }
            case tktDamage: {
                int token2 = parser.nextToken();
                switch (token2) {
                    case tktHp: {
                        int amount;
                        parser >> amount;
                        onehanded.hDamage += amount;
                        twohanded.hDamage += amount;
                        thrown.hDamage += amount;
                        break;
                    }
                    case tktFp: {
                        int amount;
                        parser >> amount;
                        onehanded.fDamage += amount;
                        twohanded.fDamage += amount;
                        thrown.fDamage += amount;
                        break;
                    }
                    default: {
                        throw EException(QString("itemclass.cpp: tktDamage: Unexpected token \"%1\"").arg(Tables::tokenToName(token2)));
                    }
                }
                break;
            }
            case tktMaximum: {
                int token2 = parser.nextToken();
                switch (token2) {
                    case tktHp: {
                        int amount;
                        parser >> amount;
                        onehanded.hMaximum += amount;
                        twohanded.hMaximum += amount;
                        thrown.hMaximum += amount;
                        break;
                    }
                    case tktFp: {
                        int amount;
                        parser >> amount;
                        onehanded.fMaximum += amount;
                        twohanded.fMaximum += amount;
                        thrown.fMaximum += amount;
                        break;
                    }
                    default: {
                        throw EException(QString("itemclass.cpp: tktMaximum: Unexpected token \"%1\"").arg(Tables::tokenToName(token2)));
                    }
                }
                break;
            }
            case tktMinstrength:{
                int amount;
                parser >> amount;
                onehanded.minStrength += amount;
                twohanded.minStrength += amount;
                thrown.minStrength += amount;
                break;
            }
            case tktEnd: {
                break;
            }
            default: {
                throw EException(QString("itemclass.cpp: Unexpected token \"%1\"").arg(Tables::tokenToName(token)));
            }
        }
    } while (token != tktEnd);
}
コード例 #4
0
int main(int argc, char *argv[])
{
	Parser p;
	int a;
	double b;
	string c;
	ivec d;
	vec e;
	svec f;
	bvec g;
	imat h;
	mat i;
	smat j;
	bmat k;
	bool l, m;
	string n;
	Array<Array<cvec> > o, q;
	cout << "Use the Parser class on a parameter file:" << boolalpha << endl;
	p.init(string(PARSER_TEST_FILE));
	a = p.get_int("a");
	cout << "a = " << a << endl;
	p.get_double("b"); //The default value of b
	p.get_double("b", 1); //The first alternative value of b
	p.get_double("b", 2); //The second alternative value of b
	c = p.get_string("c");
	cout << "c = " << c << endl;
	d = p.get_ivec("d");
	cout << "d = " << d << endl;
	e = p.get_vec("e");
	cout << "e = " << e << endl;
	f = p.get_svec("f");
	cout << "f = " << f << endl;
	g = p.get_bvec("g");
	cout << "g = " << g << endl;
	h = p.get_imat("h");
	cout << "h = " << h << endl;
	i = p.get_mat("i");
	cout << "i = " << i << endl;
	j = p.get_smat("j");
	cout << "j = " << j << endl;
	k = p.get_bmat("k");
	cout << "k = " << k << endl;
	l = p.get_bool("l");
	cout << "l = " << l << endl;
	m = p.get_bool("m");
	cout << "m = " << m << endl;
	n = p.get_string("n");
	cout << "n = " << n << endl;
	cout << "------------------------------------------------------------"
			<< endl;
	cout << "Use the Parser class on the command line input:" << endl;
	cout << "Example: > ./parser_test.run \"a=3; b=-1.2; d=[0 1 2 45];\""
			<< endl << endl;
	cout << "Use the following code:" << endl;
	cout << " p.init(argc,argv);" << endl;
	cout << " a = p.get_int(\"a\"); cout << \"a = \" << a << endl;" << endl;
	cout << " b = p.get_double(\"b\"); cout << \"b = \" << b << endl;" << endl;
	cout << " d = p.get_ivec(\"d\"); cout << \"d = \" << d << endl;" << endl;
	cout << "------------------------------------------------------------"
			<< endl;
	cout
			<< "Use the Parser class on a char pointer (usually the command line input):"
			<< endl;
	char argv1_0[] = "a=345";
	char argv1_1[] = "b=1.001";
	char argv1_2[] = "c=\"Hello Bird\"";
	char argv1_3[] = "d=[1,2,3,-1,-2,-3]";
	int argc1 = 4;
	char *argv1[4] =
	{ argv1_0, argv1_1, argv1_2, argv1_3 };
	p.init(argc1, argv1);
	a = p.get_int("a");
	b = p.get_double("b");
	c = p.get_string("c");
	d = p.get_ivec("d");
	cout << "------------------------------------------------------------"
			<< endl;
	cout << "Use the Parser class on a parameter file and a char pointer:"
			<< endl;
// The data in the char pointer are selected first. The data in the
// file are used as default values
	char argv2_0[] = "a=345";
	char argv2_1[] = "d=[1,-2,3,-4,5,-6,7,-8]";
	int argc2 = 2;
	char *argv2[2] =
	{ argv2_0, argv2_1 };
	if (argc == 0)
	{
		p.init(string(PARSER_TEST_FILE), argc2, argv2);
	}
	else
	{
		p.init(string(PARSER_TEST_FILE), argc, argv);
	}
	a = p.get_int("a");
	cout << "a = " << a << endl;
	b = p.get_double("b");
	cout << "b = " << b << endl;
	c = p.get_string("c");
	cout << "c = " << c << endl;
	d = p.get_ivec("d");
	cout << "d = " << d << endl;
	cout << "------------------------------------------------------------"
			<< endl;
	cout << "Use the Parser class on an Array of strings:" << endl;
	Array<string> parser_data(4);
	parser_data(0) = "a=-11";
	parser_data(1) = "b=3.14";
	parser_data(2) = "c=\"Hello Nerd\"";
	parser_data(3) = "d=[0,1,2,0,3,4,7]";
	p.init(parser_data);
	a = p.get_int("a");
	b = p.get_double("b");
	c = p.get_string("c");
	d = p.get_ivec("d");
	cout << "------------------------------------------------------------"
			<< endl;
	cout << "Use the Parser::get() method on a parameter file:" << endl;
	p.init(string(PARSER_TEST_FILE));
	p.get(a, "a");
	p.get(b, "b");
	p.get(b, "b", 1);
	p.get(b, "b", 2);
	p.get(c, "c");
	p.get(d, "d");
	p.get(e, "e");
	p.get(f, "f");
	p.get(g, "g");
	p.get(h, "h");
	p.get(i, "i");
	p.get(j, "j");
	p.get(k, "k");
	p.get(l, "l");
	p.get(m, "m");
	p.get(n, "n");
	p.get(o, "o");
// The following tries can not be found in the data file, so their initial
// values should not be changed:
	set_array(q, "{{[1][2 3][4 5 6]}}");
	p.get(q, "q");
	bool r = true;
	p.get(r, "r");
	int s = 7;
	p.get(s, "s");
	double t = 3.14;
	p.get(t, "t");
	std::string u = "test string";
	p.get(u, "u");
	cout << "------------------------------------------------------------"
			<< endl;
	cout << "Check if variables exist in the Parser:" << endl;
	cout << "p.exist(\"a\") = " << p.exist("a") << endl;
	cout << "p.exist(\"aa\") = " << p.exist("aa") << endl;
	cout << "------------------------------------------------------------"
			<< endl;
	return 0;
}
コード例 #5
0
//-------------------------------------------------------------------------------------------------
double BenchMuParser2::DoBenchmarkBulk(const std::string& sExpr, long iCount)
{
   int nBulkSize = (int)iCount;

   // allocate arrays for storing the variables
   double *a = new double[nBulkSize];
   double *b = new double[nBulkSize];
   double *c = new double[nBulkSize];
   double *d = new double[nBulkSize];
   double *x = new double[nBulkSize];
   double *y = new double[nBulkSize];
   double *z = new double[nBulkSize];
   double *w = new double[nBulkSize];
   double *result = new double[nBulkSize];

   // Note: There is a bit of variable swapping going on. I use aa,bb,xx,yy as
   //       buffer variables to toggle values.
   volatile double aa = 1.1;
   volatile double bb = 2.2;
   volatile double xx = 2.123456;
   volatile double yy = 3.123456;

   for (int i = 0; i < nBulkSize; ++i)
   {
      a[i] = aa;
      b[i] = bb;
      c[i] = 3.3;
      d[i] = 4.4;
      x[i] = xx;
      y[i] = yy;
      z[i] = 4.123456;
      w[i] = 5.123456;

      std::swap(aa,bb);
      std::swap(xx,yy);
   }

   double fTime(0);
   try
   {
      Parser p;
      p.SetExpr(sExpr.c_str());
      p.DefineVar("a", a);
      p.DefineVar("b", b);
      p.DefineVar("c", c);
      p.DefineVar("x", x);
      p.DefineVar("y", y);
      p.DefineVar("z", z);
      p.DefineVar("w", w);
      p.DefineConst("pi", (double)M_PI);
      p.DefineConst("e", (double)M_E);

      // Do the computation
      StartTimer();

      // Needlessly spend time swapping variables for the sake of timing fairness.
      for (int i = 0; i < nBulkSize; ++i)
      {
         std::swap(aa,bb);
         std::swap(xx,yy);
      }

      p.Eval(result, nBulkSize);

      // Note: Performing the addition inside the timed section is done
      //       because all other parsers do it in their main loop too.
      double fSum(0);

      for (int j = 0; j < nBulkSize; ++j)
      {
         fSum += result[j];
      }

      StopTimer(result[0], fSum, iCount);

      fTime = m_fTime1;
   }
   catch(ParserError &exc)
   {
      fTime = std::numeric_limits<double>::quiet_NaN();
      StopTimerAndReport(exc.GetMsg());
   }
   catch(...)
   {
      fTime = std::numeric_limits<double>::quiet_NaN();
      StopTimerAndReport("unexpected exception");
   }

   delete [] a;
   delete [] b;
   delete [] c;
   delete [] d;
   delete [] x;
   delete [] y;
   delete [] z;
   delete [] w;
   delete [] result;

   return fTime;
}
コード例 #6
0
void TatortFMParser::convertDataToMatrix(string inTrainFilename, string inTestFilename, string delimiter, string outTrainFilename, string outTestFilename, bool isHeaderPresent) {

	Parser trainParser;
	Parser testParser;

	trainParser.parseFile(inTrainFilename, delimiter, isHeaderPresent);
	testParser.parseFile(inTestFilename, delimiter, isHeaderPresent);


	Logger::getInstance()->log("start converting data to libFM conform format ...", LOG_DEBUG);

	int numTrainData = trainParser.getNumberOfDatasets();
	int numTestData = testParser.getNumberOfDatasets();

	Logger::getInstance()->log("number of train datasets '"+ to_string(numTrainData) +"'", LOG_DEBUG);
	Logger::getInstance()->log("number of test datasets '"+ to_string(numTestData) +"'", LOG_DEBUG);

	if(trainParser.getNumberOfColumns() != testParser.getNumberOfColumns())
		throw MyException("EXCEPTION: number of columns mismatch between train and test data!");

	if((numTrainData <= 0) || (numTestData <= 0))
		throw MyException("EXCEPTION: no datasets to convert!");

	int numOfColumns = trainParser.getNumberOfColumns();

	vector<string> trainRatings = trainParser.getColumn(numOfColumns - 1);
	vector<string> trainUserIds = trainParser.getColumn(0);
	vector<string> trainEpisodeIds = trainParser.getColumn(2);

	vector<string> testRatings = testParser.getColumn(numOfColumns - 1);
	vector<string> testUserIds = testParser.getColumn(0);
	vector<string> testEpisodeIds = testParser.getColumn(2);

	int maxUserId = max(stoi(trainUserIds[0]), stoi(testUserIds[0]));
	int maxEpisodeId = max(stoi(trainEpisodeIds[0]), stoi(testEpisodeIds[0]));


	int maxNumDatasets = max(numTestData, numTrainData);

	

	// looking for max Ids
	for(int i = 1; i < maxNumDatasets; i++) {
		
		//Logger::getInstance()->log("iteration '"+ to_string(i) +"'", LOG_DEBUG);

		if(i < numTrainData) {
			maxUserId = max(maxUserId, stoi(trainUserIds[i]));
			maxEpisodeId = max(maxEpisodeId, stoi(trainEpisodeIds[i]));
		}

		//Logger::getInstance()->log("train done!", LOG_DEBUG);

		if(i < numTestData) {
			//Logger::getInstance()->log("numTestData = '"+ to_string(numTestData) +"' and i = '"+ to_string(i) +"'", LOG_DEBUG);
			maxUserId = max(maxUserId, stoi(testUserIds[i]));
			maxEpisodeId = max(maxEpisodeId, stoi(testEpisodeIds[i]));
		}

		
	}


	ofstream ofTrain(outTrainFilename);
	if(!ofTrain.is_open())
		throw MyException("EXCEPTION: could not open file '"+ outTrainFilename +"'!");


	ofstream ofTest(outTestFilename);
	if(!ofTest.is_open())
		throw MyException("EXCEPTION: could not open file '"+ outTestFilename +"'!");


	// writing data in libfm conform format to file
	for (int i = 0; i < maxNumDatasets; i++)
	{
		int userOffset = 0;
		int episodeOffset = maxUserId;

		if(i < numTrainData) {
			ofTrain << stod(trainRatings[i]) << " ";
			ofTrain << (userOffset + stoi(trainUserIds[i])) << ":1 ";
			ofTrain << (episodeOffset + stoi(trainEpisodeIds[i])) << ":1 ";
			ofTrain << endl;
		}

		if(i < numTestData) {
			ofTest << stod(testRatings[i]) << " ";
			ofTest << (userOffset + stoi(testUserIds[i])) << ":1 ";
			ofTest << (episodeOffset + stoi(testEpisodeIds[i])) << ":1 ";
			ofTest << endl;
		}
	}

	Logger::getInstance()->log("converting data to libFM conform format done!", LOG_DEBUG);



}
コード例 #7
0
ファイル: experiment.cpp プロジェクト: spicydonkey/cellml-ga
int main(int argc,char *argv[])
{
    char *pBuffer=NULL;
    long nSize=0;
    GAEngine<COMP_FUNC > ga;	// initialise GA engine for the program
	int proc,nproc;
    int generations=0;
    const char *filename=NULL;

    MPI_Init(&argc,&argv);

    if(argc<2)
    {
		// warn user for incorrect usage at command line
        usage(argv[0]);
        return -1;
    }

    for(int i=1;i<argc;i++)
    {
        if(!strcmp(argv[i],"-v"))
			// if an arg string is "-v" increment verbosity
            verbosity++;
        else
			// other arg string becomes the filename
            filename=argv[i];
    }

    MPI_Comm_rank(MPI_COMM_WORLD, &proc);
    MPI_Comm_size(MPI_COMM_WORLD, &nproc);

	srand(time(NULL)*proc);		// unique seed for RNG

    //Load and initialise CellML API
    bootstrap=CreateCellMLBootstrap();
    cis=CreateIntegrationService();

	// Read input file and store contents in buffer
    if((pBuffer=OpenXmlFile(filename,nSize)) == NULL)
    {
		std::cerr << "Error: main: error opening input file " << argv[1] << ": " << currentDateTime() << std::endl;
		return -1;
    }
	// Read success: pBuffer is a C-string containing file and nSize is size of file

    //Load the experiments package: Virtual Experiment data and GA parameters
    try
    {
        Parser parser;

        ObjRef<CellMLComponentSet> comps;	// TODO comps not referenced elsewhere in project

		// Parse the XML contents in buffer
        auto_ptr<Document> pDoc(parser.Parse(pBuffer,nSize));	// can throw an exception
		// Get the root of the XML structure
        const Element& root=pDoc->GetRoot();

		// Load virtual experiments
		// load all virtual experiments in the XML file
		for(int i=0;;i++)
        {
			// load the VE data in file
            VirtualExperiment *vx=VirtualExperiment::LoadExperiment(root("VirtualExperiments",0)("VirtualExperiment",i));
			if(!vx)
               break;	// loaded all the VE in file
			
			// Quit program with err msg if VE is invalid
			if (!vx->isValid())
				return -1;

			// add each VE into the group singleton
            VEGroup::instance().add(vx);
        }
		
		// load the GA parameters from file and initialise the engine
        if(!proc)
        {
			// Master processor initialises the GA engine
			// get max generations (-1 for errors) and GA parameters
            generations=SetAndInitEngine(ga,root("GA",0));
        }
        else
        {
			// The slaves initialise the template variable holder to create gene-pool
            initialize_template_var(root("GA",0));
        }
    }
    catch(ParsingException e)
    {
		std::cerr << "Error: main: parsing error at line " << e.GetLine() << std::endl;
    }
    delete [] pBuffer;	// free memory used to store file

	// Wait until all the clients are ready
    MPI_Barrier(MPI_COMM_WORLD);

    // Only master task needs GA engine to be initialised and used   
    if(!proc)
    {
		// Print a summary of configuration of GA engine and VEs
		ga.print_config(generations);
		VEGroup::instance().print_summary();

		// Validate and run GA
		if(generations<0)
		{
			std::cerr << "Error: main: invalid settings for the Genetic Algorithm: " << currentDateTime() << std::endl;
		}
		else
		{
			// Initialise the population in GA engine
			ga.Initialise();
			// Run GA
			ga.RunGenerations(generations);
        
			// Print best genome from the run
			VariablesHolder v;
			double bf=ga.GetBest(v);
			std::cout << "==========================================\n";
			fprintf(stdout,"BEST GENOME (%lf):\n",bf);
			v.print(stdout);
			std::cout << "==========================================\n";
		}

        Distributor::instance().finish();	// request end of service to all slaves
    }
    else
    {
        run_slave(proc);
    }

    MPI_Barrier(MPI_COMM_WORLD);
    MPI_Finalize();

    return 0;
}
コード例 #8
0
void ValgrindMemcheckParserTest::testHelgrindSample1()
{
    QSKIP("testfile does not exist");

    initTest("helgrind-output-sample1.xml");

    QList<Error> expectedErrors;
    {
        Error error1;
        error1.setUnique(0x0);
        error1.setTid(1);
        error1.setKind(LockOrder);
        error1.setWhat("Thread #1: lock order \"0xA39C270 before 0xA3AC010\" violated");
        error1.setHelgrindThreadId(1);
        Stack stack1;
        Frame frame11;
        frame11.setInstructionPointer(0x4C2B806);
        frame11.setObject("/usr/lib/valgrind/vgpreload_helgrind-amd64-linux.so");
        frame11.setFunctionName("QMutex::lock()");
        frame11.setDirectory("/build/buildd/valgrind-3.6.0~svn20100212/helgrind");
        frame11.setFileName("hg_intercepts.c");
        frame11.setLine(1988);
        Frame frame12;
        frame12.setInstructionPointer(0x72E57EE);
        frame12.setObject("/home/frank/local/qt4-4.6.3-shared-debug/lib/libQtCore.so.4.6.3");
        frame12.setFunctionName("QMutexLocker::relock()");
        frame12.setDirectory("/home/frank/source/tarballs/qt-4.6.3-build/src/corelib/../../include/QtCore/../../src/corelib/thread");
        frame12.setFileName("qmutex.h");
        frame12.setLine(120);
        stack1.setFrames(QVector<Frame>() << frame11 << frame12);

        Stack stack2;
        stack2.setAuxWhat("Required order was established by acquisition of lock at 0xA39C270");
        Frame frame21;
        frame21.setInstructionPointer(0x4C2B806);
        frame21.setObject("/usr/lib/valgrind/vgpreload_helgrind-amd64-linux.so");
        frame21.setFunctionName("QMutex::lock()");
        frame21.setDirectory("/build/buildd/valgrind-3.6.0~svn20100212/helgrind");
        frame21.setFileName("hg_intercepts.c");
        frame21.setLine(1989);
        Frame frame22;
        frame22.setInstructionPointer(0x72E57EE);
        frame22.setObject("/home/frank/local/qt4-4.6.3-shared-debug/lib/libQtCore.so.4.6.3");
        frame22.setFunctionName("QMutexLocker::relock()");
        frame22.setDirectory("/home/frank/source/tarballs/qt-4.6.3-build/src/corelib/../../include/QtCore/../../src/corelib/thread");
        frame22.setFileName("qmutex.h");
        frame22.setLine(121);
        stack2.setFrames(QVector<Frame>() << frame21 << frame22);

        Stack stack3;
        stack3.setAuxWhat("followed by a later acquisition of lock at 0xA3AC010");
        Frame frame31;
        frame31.setInstructionPointer(0x4C2B806);
        frame31.setObject("/usr/lib/valgrind/vgpreload_helgrind-amd64-linux.so");
        frame31.setFunctionName("QMutex::lock()");
        frame31.setDirectory("/build/buildd/valgrind-3.6.0~svn20100212/helgrind");
        frame31.setFileName("hg_intercepts.c");
        frame31.setLine(1990);
        Frame frame32;
        frame32.setInstructionPointer(0x72E57EE);
        frame32.setObject("/home/frank/local/qt4-4.6.3-shared-debug/lib/libQtCore.so.4.6.3");
        frame32.setFunctionName("QMutexLocker::relock()");
        frame32.setDirectory("/home/frank/source/tarballs/qt-4.6.3-build/src/corelib/../../include/QtCore/../../src/corelib/thread");
        frame32.setFileName("qmutex.h");
        frame32.setLine(122);

        stack3.setFrames(QVector<Frame>() << frame31 << frame32);
        error1.setStacks(QVector<Stack>() << stack1 << stack2 << stack3);
        expectedErrors.append(error1);
    }

    Parser parser;
    Recorder rec(&parser);

    parser.parse(m_socket);

    m_process->waitForFinished();
    QCOMPARE(m_process->exitStatus(), QProcess::NormalExit);
    QCOMPARE(m_process->state(), QProcess::NotRunning);

    QVERIFY2(parser.errorString().isEmpty(), qPrintable(parser.errorString()));
    const QList<Error> actualErrors = rec.errors;

    if (actualErrors.first() != expectedErrors.first()) {
        dumpError(actualErrors.first());
        dumpError(expectedErrors.first());
    }

    QCOMPARE(actualErrors.first(), expectedErrors.first());

    QCOMPARE(actualErrors.size(), 1);

//    QCOMPARE(rec.errorcounts, expectedErrorCounts);
//    QCOMPARE(rec.suppcounts, expectedSuppCounts);
}
コード例 #9
0
void ValgrindMemcheckParserTest::testMemcheckSample1()
{
    initTest("memcheck-output-sample1.xml");

    QList<Error> expectedErrors;
    {
        Error error;
        error.setKind(InvalidRead);
        error.setWhat("Invalid read of size 4");
        error.setUnique(0x9);
        error.setTid(1);
        Frame f1;
        f1.setInstructionPointer(0x6E47964);
        f1.setObject("/usr/lib/libQtGui.so.4.7.0");
        f1.setFunctionName("QFrame::frameStyle() const");
        f1.setDirectory("/build/buildd/qt4-x11-4.7.0/src/gui/widgets");
        f1.setFileName("qframe.cpp");
        f1.setLine(252);
        Frame f2;
        f2.setInstructionPointer(0x118F2AF7);
        f2.setObject("/usr/lib/kde4/plugins/styles/oxygen.so");
        Frame f3;
        f3.setInstructionPointer(0x6A81671);
        f3.setObject("/usr/lib/libQtGui.so.4.7.0");
        f3.setFunctionName("QWidget::event(QEvent*)");
        f3.setDirectory("/build/buildd/qt4-x11-4.7.0/src/gui/kernel");
        f3.setFileName("qwidget.cpp");
        f3.setLine(8273);
        Frame f4;
        f4.setInstructionPointer(0x6A2B6EB);
        f4.setObject("/usr/lib/libQtGui.so.4.7.0");
        f4.setDirectory("/build/buildd/qt4-x11-4.7.0/src/gui/kernel");
        f4.setFileName("qapplication.cpp");
        f4.setFunctionName("QApplicationPrivate::notify_helper(QObject*, QEvent*)");
        f4.setLine(4396);
        Stack s1;
        s1.setAuxWhat("Address 0x11527cb8 is not stack'd, malloc'd or (recently) free'd");
        s1.setFrames(QVector<Frame>() << f1 << f2 << f3 << f4);
        error.setStacks( QVector<Stack>() << s1 );

        expectedErrors << error;
    }

    QVector<QPair<qint64,qint64> > expectedErrorCounts;
    expectedErrorCounts.push_back(QPair<qint64,qint64>(9, 2));

    QVector<QPair<QString,qint64> > expectedSuppCounts;
    expectedSuppCounts.push_back(qMakePair(QString("X on SUSE11 writev uninit padding"), static_cast<qint64>(12)));
    expectedSuppCounts.push_back(qMakePair(QString("dl-hack3-cond-1"), static_cast<qint64>(2)));
    expectedSuppCounts.push_back(qMakePair(QString("glibc-2.5.x-on-SUSE-10.2-(PPC)-2a"), static_cast<qint64>(2)));

    Parser parser;
    Recorder rec(&parser);

    parser.parse(m_socket);

    m_process->waitForFinished();
    QCOMPARE(m_process->exitStatus(), QProcess::NormalExit);
    QCOMPARE(m_process->state(), QProcess::NotRunning);

    QVERIFY2(parser.errorString().isEmpty(), qPrintable(parser.errorString()));
    const QList<Error> actualErrors = rec.errors;

    if (actualErrors.first() != expectedErrors.first()) {
        dumpError(actualErrors.first());
        dumpError(expectedErrors.first());
    }

    QCOMPARE(actualErrors.first(), expectedErrors.first());

    QCOMPARE(actualErrors.size(), 3);

    QCOMPARE(rec.errorcounts, expectedErrorCounts);
    QCOMPARE(rec.suppcounts, expectedSuppCounts);
}
コード例 #10
0
ファイル: VmTranslator.cpp プロジェクト: npat1126/nand2tetris
bool VmTranslator::translateOptimisedSequence(Parser& parser, CodeWriterOptimised* codeWriterOpt)
{
    if (vmCmdList.size() >= 3) {
        if (vmCmdList.at(0) == VmCommandOptType::C_PUSH_CONSTANT &&
            vmCmdList.at(1) == VmCommandOptType::C_PUSH_LOCAL &&
            vmCmdList.at(2) == VmCommandOptType::C_ARITHMETIC_ADD)
            {
                int constant = parser.arg2();
                parser.advance();
                int index = parser.arg2();

                codeWriterOpt->writeSeqPushConstantPushTempAdd(constant, index);
                vmCmdList.erase(vmCmdList.begin(), vmCmdList.begin() + 3);
                parser.advance();
                return true;
            }
    }

    if (vmCmdList.size() >= 2) {

        if (vmCmdList.at(0) == VmCommandOptType::C_PUSH_CONSTANT &&
            vmCmdList.at(1) == VmCommandOptType::C_ARITHMETIC_ADD)
            {
                codeWriterOpt->writeSeqPushConstantAdd(parser.arg2());
                vmCmdList.erase(vmCmdList.begin(), vmCmdList.begin() + 2);
                parser.advance();
                return true;
            }

        if (vmCmdList.at(0) == VmCommandOptType::C_PUSH_CONSTANT &&
            vmCmdList.at(1) == VmCommandOptType::C_ARITHMETIC_SUB)
            {
                codeWriterOpt->writeSeqPushConstantSub(parser.arg2());
                vmCmdList.erase(vmCmdList.begin(), vmCmdList.begin() + 2);
                parser.advance();
                return true;
            }

        if (vmCmdList.at(0) == VmCommandOptType::C_PUSH_CONSTANT &&
            vmCmdList.at(1) == VmCommandOptType::C_ARITHMETIC_NEG)
            {
                codeWriterOpt->writeSeqPushConstantNeg(parser.arg2());
                vmCmdList.erase(vmCmdList.begin(), vmCmdList.begin() + 2);
                parser.advance();
                return true;
            }

        if ((vmCmdList.at(0) == VmCommandOptType::C_PUSH_ARGUMENT ||
             vmCmdList.at(0) == VmCommandOptType::C_PUSH_LOCAL ||
             vmCmdList.at(0) == VmCommandOptType::C_PUSH_THIS ||
             vmCmdList.at(0) == VmCommandOptType::C_PUSH_THAT) &&
             vmCmdList.at(1) == VmCommandOptType::C_ARITHMETIC_ADD)
            {
                codeWriterOpt->writeSeqPushArgLocalThisThatAdd(parser.arg1(), parser.arg2());
                vmCmdList.erase(vmCmdList.begin(), vmCmdList.begin() + 2);
                parser.advance();
                return true;
            }

        if ((vmCmdList.at(0) == VmCommandOptType::C_PUSH_ARGUMENT ||
             vmCmdList.at(0) == VmCommandOptType::C_PUSH_LOCAL ||
             vmCmdList.at(0) == VmCommandOptType::C_PUSH_THIS ||
             vmCmdList.at(0) == VmCommandOptType::C_PUSH_THAT) &&
             vmCmdList.at(1) == VmCommandOptType::C_ARITHMETIC_SUB)
            {
                codeWriterOpt->writeSeqPushArgLocalThisThatSub(parser.arg1(), parser.arg2());
                vmCmdList.erase(vmCmdList.begin(), vmCmdList.begin() + 2);
                parser.advance();
                return true;
            }

        if (vmCmdList.at(0) == VmCommandOptType::C_PUSH_TEMP &&
            vmCmdList.at(1) == VmCommandOptType::C_POP_THAT)
            {
                int tempIndex = parser.arg2();
                parser.advance();
                int thatIndex = parser.arg2();

                codeWriterOpt->writeSeqPushTempPopThat(tempIndex, thatIndex);
                vmCmdList.erase(vmCmdList.begin(), vmCmdList.begin() + 2);
                return true;
            }

        if (vmCmdList.at(0) == VmCommandOptType::C_PUSH_ARGUMENT &&
            vmCmdList.at(1) == VmCommandOptType::C_POP_POINTER)
            {
                int argIndex = parser.arg2();
                parser.advance();
                int pointerIndex = parser.arg2();

                cout << "HERE" << endl;

                codeWriterOpt->writeSeqPushArgumentPopPointer(argIndex, pointerIndex);
                vmCmdList.erase(vmCmdList.begin(), vmCmdList.begin() + 2);
                return true;
            }

        if (vmCmdList.at(0) == VmCommandOptType::C_PUSH_STATIC &&
            vmCmdList.at(1) == VmCommandOptType::C_ARITHMETIC_ADD)
            {
                codeWriterOpt->writeSeqPushStaticAdd(parser.arg2());
                vmCmdList.erase(vmCmdList.begin(), vmCmdList.begin() + 2);
                parser.advance();
                return true;
            }

    }

    return false;
}
コード例 #11
0
ファイル: VmTranslator.cpp プロジェクト: npat1126/nand2tetris
void VmTranslator::translateNonOptimised(Parser& parser, CodeWriter* codeWriter)
{
    while (parser.advance()) {

        switch (parser.commandType()) {

            case VmCommandType::C_ARITHMETIC:
                codeWriter->writeArithmetic(parser.getCommand());
                break;

            case VmCommandType::C_PUSH:
            case VmCommandType::C_POP:
                codeWriter->writePushPop(parser.commandType(), parser.arg1(), parser.arg2());
                break;

            case VmCommandType::C_LABEL:
                codeWriter->writeLabel(parser.arg1());
                break;

            case VmCommandType::C_GOTO:
                codeWriter->writeGoto(parser.arg1());
                break;

            case VmCommandType::C_IF:
                codeWriter->writeIf(parser.arg1());
                break;

            case VmCommandType::C_FUNCTION:
                if (verbose)
                    cout << "  ~ function " << parser.arg1() << " (allocates " << parser.arg2() << " local vars)" << endl;

                codeWriter->writeFunction(parser.arg1(), parser.arg2());
                break;

            case VmCommandType::C_CALL:
                codeWriter->writeCall(parser.arg1(), parser.arg2());
                break;

            case VmCommandType::C_RETURN:
                codeWriter->writeReturn();
                break;

        }
    }
}
コード例 #12
0
ファイル: VmTranslator.cpp プロジェクト: npat1126/nand2tetris
void VmTranslator::translateOptimised(Parser& parser, CodeWriterOptimised* codeWriterOpt)
{
    static bool globalFunctions = true;

    if (globalFunctions) {
        codeWriterOpt->writeGlobalFunctions();
        globalFunctions = false;
    }

    vmCmdList.clear();

    while (parser.advance())
        vmCmdList.push_back(parser.commandOptType());

    parser.reset();

    while (parser.advance()) {

        if (translateOptimisedSequence(parser, codeWriterOpt))
            continue;

        switch (parser.commandType()) {

            case VmCommandType::C_ARITHMETIC:
                codeWriterOpt->writeArithmetic(parser.getCommand());
                break;

            case VmCommandType::C_PUSH:
            case VmCommandType::C_POP:
                codeWriterOpt->writePushPop(parser.commandType(), parser.arg1(), parser.arg2());
                break;

            case VmCommandType::C_LABEL:
                codeWriterOpt->writeLabel(parser.arg1());
                break;

            case VmCommandType::C_GOTO:
                codeWriterOpt->writeGoto(parser.arg1());
                break;

            case VmCommandType::C_IF:
                codeWriterOpt->writeIf(parser.arg1());
                break;

            case VmCommandType::C_FUNCTION:
                if (verbose)
                    cout << "  ~ function " << parser.arg1() << " (allocates " << parser.arg2() << " local vars)" << endl;

                codeWriterOpt->writeFunction(parser.arg1(), parser.arg2());
                break;

            case VmCommandType::C_CALL:
                codeWriterOpt->writeCall(parser.arg1(), parser.arg2());
                break;

            case VmCommandType::C_RETURN:
                codeWriterOpt->writeReturn();
                break;

        }

        if (!vmCmdList.empty())
            vmCmdList.erase(vmCmdList.begin());

    }
}
コード例 #13
0
ファイル: ArmParser.cpp プロジェクト: ketlerd/armips
bool ArmParser::parseArmParameters(Parser& parser, const tArmOpcode& opcode, ArmOpcodeVariables& vars)
{
    const u8* encoding = (const u8*) opcode.mask;

    ArmRegisterValue tempRegister;

    vars.Shift.UseShift = false;
    vars.Shift.UseFinal = false;
    vars.psr = false;
    vars.writeback = false;
    vars.SignPlus = false;
    vars.Opcode.UseNewEncoding = false;
    vars.Opcode.UseNewType = false;

    while (*encoding != 0)
    {
        bool optional = *encoding == '/';
        if (optional)
            encoding++;

        switch (*encoding++)
        {
        case 'd': // register
            CHECK(parseRegister(parser,vars.rd,*encoding++ == '1' ? 14 : 15));
            break;
        case 's': // register
            CHECK(parseRegister(parser,vars.rs,*encoding++ == '1' ? 14 : 15));
            break;
        case 'n': // register
            CHECK(parseRegister(parser,vars.rn,*encoding++ == '1' ? 14 : 15));
            break;
        case 'm': // register
            CHECK(parseRegister(parser,vars.rm,*encoding++ == '1' ? 14 : 15));
            break;
        case 'D': // cop register
            CHECK(parseCopRegister(parser,vars.CopData.cd));
            break;
        case 'N': // cop register
            CHECK(parseCopRegister(parser,vars.CopData.cn));
            break;
        case 'M': // cop register
            CHECK(parseCopRegister(parser,vars.CopData.cm));
            break;
        case 'W':	// writeback
            parseWriteback(parser,vars.writeback);
            break;
        case 'p':	// psr
            parsePsr(parser,vars.psr);
            break;
        case 'P':	// msr/mrs psr data
            CHECK(parsePsrTransfer(parser,vars,*encoding++ == '1'));
            break;
        case 'R':	// register list
            CHECK(parseRegisterList(parser,vars.rlist,0xFFFF));
            break;
        case 'S':	// shift
            CHECK(parseShift(parser,vars,*encoding++ == '1'));
            break;
        case 'I':	// immediate
        case 'i':
            CHECK(parseImmediate(parser,vars.ImmediateExpression));
            vars.ImmediateBitLen = 32;
            break;
        case 'j':	// variable bit immediate
            CHECK(parseImmediate(parser,vars.ImmediateExpression));
            vars.ImmediateBitLen = *encoding++;
            break;
        case 'X': // cop number
            CHECK(parseCopNumber(parser,vars.CopData.pn));
            break;
        case 'Y':	// cop opcode number
            CHECK(parseImmediate(parser,vars.CopData.CpopExpression));
            vars.ImmediateBitLen = 4;
            break;
        case 'Z':	// cop info number
            CHECK(parseImmediate(parser,vars.CopData.CpinfExpression));
            vars.ImmediateBitLen = 3;
            break;
        case 'z':	// shift for pseudo opcodes
            CHECK(parsePseudoShift(parser,vars,*encoding++));
            break;
        case 'v':	// sign for register index parameter
            parseSign(parser,vars.SignPlus);
            break;
        default:
            CHECK(matchSymbol(parser,*(encoding-1),optional));
            break;
        }
    }

    // the next token has to be an identifier, else the parameters aren't
    // completely parsed
    return parser.atEnd() || parser.peekToken().type == TokenType::Identifier;
}
コード例 #14
0
ファイル: ArmParser.cpp プロジェクト: ketlerd/armips
bool ArmParser::parsePsrTransfer(Parser& parser, ArmOpcodeVariables& vars, bool shortVersion)
{
    const Token& token = parser.nextToken();
    if (token.type != TokenType::Identifier)
        return false;

    const std::wstring stringValue = token.getStringValue();
    size_t pos = 0;
    if (startsWith(stringValue,L"cpsr"))
    {
        vars.PsrData.spsr = false;
        pos = 4;
    } else if (startsWith(stringValue,L"spsr"))
    {
        vars.PsrData.spsr = true;
        pos = 4;
    } else {
        return false;
    }

    if (shortVersion)
        return pos == stringValue.size();

    if (pos == stringValue.size())
    {
        vars.PsrData.field = 0xF;
        return true;
    }

    if (stringValue[pos++] != '_')
        return false;

    if (startsWith(stringValue,L"ctl",pos))
    {
        vars.PsrData.field = 1;
        return pos+3 == stringValue.size();
    }

    if (startsWith(stringValue,L"flg",pos))
    {
        vars.PsrData.field = 8;
        return pos+3 == stringValue.size();
    }

    vars.PsrData.field = 0;
    for (int i = 0; i < 4; i++)
    {
        if (pos == stringValue.size())
            break;

        switch(stringValue[pos++])
        {
        case 'f':
            if (vars.PsrData.field & 8)
                return false;	// can only appear once
            vars.PsrData.field |= 8;
            break;
        case 's':
            if (vars.PsrData.field & 4)
                return false;	// can only appear once
            vars.PsrData.field |= 4;
            break;
        case 'x':
            if (vars.PsrData.field & 2)
                return false;	// can only appear once
            vars.PsrData.field |= 2;
            break;
        case 'c':
            if (vars.PsrData.field & 1)
                return false;	// can only appear once
            vars.PsrData.field |= 1;
            break;
        default:
            return false;	// has to be one of those
        }
    }

    return true;
}
コード例 #15
0
 void set_expression_string( const std::string& expression, Parser& parser ) {
     this->expression = parser.parse_numeric( expression );
     DEBUG( this << " parsed expression " << this->expression->root_node << " from " << expression );
 }
コード例 #16
0
ファイル: channel.cpp プロジェクト: rashikamishra/CS-6323
bool channel::Load(Parser &reader) 
{
	reader.FindToken("{");
	char temp[256];
	reader.GetToken(temp);
	if (strcmp(temp, "extrapolate") == 0) 
	{
		reader.GetToken(temp);
		extrapolateInMode = temp;
		reader.GetToken(temp);
		extrapolateOutMode = temp;
	}
	reader.GetToken(temp);
	if (strcmp(temp, "keys") == 0) 
	{
		int index = reader.GetInt();
		reader.FindToken("{");
		for (int i = 0; i < index; i++) 
		{
			keyframe *key = new keyframe();
			key->time = (reader.GetFloat());
			key->keyframeValue = (reader.GetFloat());
			reader.GetToken(temp);
			if (isdigit(temp[0])) 
			{
				key->tangentInValue = atof(temp);
				key->tangentOutMode = "constant value";
			}
			else
				key->tangentInMode = temp;
			reader.GetToken(temp);
			if (isdigit(temp[0])) 
			{
				key->tangentOutValue = atof(temp);
				key->tangentOutMode = "constant value";
			}
			else
				key->tangentOutMode = temp;
			keyframes.push_back(*key);
		}
		reader.FindToken("}");
		reader.FindToken("}");
	}
	return true;
}
コード例 #17
0
void TatortFMParser::convertDataToTensorPlusAttributes(string inTrainFilename, string inTestFilename, string delimiter, vector<unsigned int> attributeIndices, string outTrainFilename, string outTestFilename, bool isHeaderPresent) {
	Parser trainParser;
	Parser testParser;

	// parsing data
	trainParser.parseFile(inTrainFilename, delimiter, isHeaderPresent);
	testParser.parseFile(inTestFilename, delimiter, isHeaderPresent);


	Logger::getInstance()->log("start converting data to libFM conform format ...", LOG_DEBUG);

	int numTrainData = trainParser.getNumberOfDatasets();
	int numTestData = testParser.getNumberOfDatasets();

	Logger::getInstance()->log("number of train datasets '" + to_string(numTrainData) + "'", LOG_DEBUG);
	Logger::getInstance()->log("number of test datasets '" + to_string(numTestData) + "'", LOG_DEBUG);

	if (trainParser.getNumberOfColumns() != testParser.getNumberOfColumns())
		throw MyException("EXCEPTION: number of columns mismatch between train and test data!");

	if ((numTrainData <= 0) || (numTestData <= 0))
		throw MyException("EXCEPTION: no datasets to convert!");

	int numOfColumns = trainParser.getNumberOfColumns();

	Logger::getInstance()->log("number of columns '" + to_string(numOfColumns) + "'", LOG_DEBUG);


	// query all important data
	vector<string> trainRatings = trainParser.getColumn(numOfColumns - 1);
	vector<string> trainUserIds = trainParser.getColumn(0);
	vector<string> trainEpisodeIds = trainParser.getColumn(2);
	vector<string> trainDetectiveIds = trainParser.getColumn(4);
	vector<vector<string> > trainAttributes;
	

	Logger::getInstance()->log("train data initialized", LOG_DEBUG);

	vector<string> testRatings = testParser.getColumn(numOfColumns - 1);
	vector<string> testUserIds = testParser.getColumn(0);
	vector<string> testEpisodeIds = testParser.getColumn(2);
	vector<string> testDetectiveIds = testParser.getColumn(4);
	vector<vector<string> > testAttributes;

	Logger::getInstance()->log("test data initialized", LOG_DEBUG);

	for (unsigned int i = 0; i < attributeIndices.size(); i++) {
		trainAttributes.push_back(trainParser.getColumn(attributeIndices[i]));
		testAttributes.push_back(testParser.getColumn(attributeIndices[i]));
	}

		

	int maxUserId = max(stoi(trainUserIds[0]), stoi(testUserIds[0]));
	int maxEpisodeId = max(stoi(trainEpisodeIds[0]), stoi(testEpisodeIds[0]));
	int maxDetectiveId = max(stoi(trainDetectiveIds[0]), stoi(trainDetectiveIds[0]));

	Logger::getInstance()->log("max variables initialized", LOG_DEBUG);

	int maxNumDatasets = max(numTestData, numTrainData);



	// looking for max Ids
	for (int i = 1; i < maxNumDatasets; i++) {

		//Logger::getInstance()->log("iteration '"+ to_string(i) +"'", LOG_DEBUG);

		if (i < numTrainData) {
			maxUserId = max(maxUserId, stoi(trainUserIds[i]));
			maxEpisodeId = max(maxEpisodeId, stoi(trainEpisodeIds[i]));
			maxDetectiveId = max(maxDetectiveId, stoi(trainDetectiveIds[i]));
		}

		//Logger::getInstance()->log("train done!", LOG_DEBUG);

		if (i < numTestData) {
			//Logger::getInstance()->log("numTestData = '"+ to_string(numTestData) +"' and i = '"+ to_string(i) +"'", LOG_DEBUG);
			maxUserId = max(maxUserId, stoi(testUserIds[i]));
			maxEpisodeId = max(maxEpisodeId, stoi(testEpisodeIds[i]));
			maxDetectiveId = max(maxDetectiveId, stoi(testDetectiveIds[i]));
		}
	}


	Logger::getInstance()->log("max ids computed", LOG_DEBUG);




	ofstream ofTrain(outTrainFilename);
	if (!ofTrain.is_open())
		throw MyException("EXCEPTION: could not open file '" + outTrainFilename + "'!");


	ofstream ofTest(outTestFilename);
	if (!ofTest.is_open())
		throw MyException("EXCEPTION: could not open file '" + outTestFilename + "'!");

	Logger::getInstance()->log("output files successfully opened", LOG_DEBUG);


	// computing index ranges
	int userOffset = 0;
	int episodeOffset = maxUserId;
	int detectiveOffset = episodeOffset + maxEpisodeId;
	int attributeIndexStart = detectiveOffset + maxDetectiveId;
	
	// writing data in libfm conform format to file
	for (int i = 0; i < maxNumDatasets; i++)
	{

		if (i < numTrainData) {
			ofTrain << stod(trainRatings[i]) << " ";
			ofTrain << (userOffset + stoi(trainUserIds[i])) << ":1 ";
			ofTrain << (episodeOffset + stoi(trainEpisodeIds[i])) << ":1 ";
			ofTrain << (detectiveOffset + stoi(trainDetectiveIds[i])) << ":1 ";
			
			for (unsigned int attr = 0; attr < trainAttributes.size(); attr++) {
				ofTrain << (attributeIndexStart + attr) << ":" << trainAttributes[attr][i] << " ";
			}
			
			/*ofTrain << (viewerIndex) << ":" << trainViewers[i] << " ";
			ofTrain << (quoteIndex) << ":" << trainQuotes[i] << " ";
			ofTrain << (episodeIndex) << ":" << trainEpisodeIds[i] << " ";*/
			
			ofTrain << endl;
		}

		if (i < numTestData) {
			ofTest << stod(testRatings[i]) << " ";
			ofTest << (userOffset + stoi(testUserIds[i])) << ":1 ";
			ofTest << (episodeOffset + stoi(testEpisodeIds[i])) << ":1 ";
			ofTest << (detectiveOffset + stoi(testDetectiveIds[i])) << ":1 ";

			for (unsigned int attr = 0; attr < trainAttributes.size(); attr++) {
				ofTest << (attributeIndexStart + attr) << ":" << testAttributes[attr][i] << " ";
			}

			/*ofTest << (viewerIndex) << ":" << testViewers[i] << " ";
			ofTest << (quoteIndex) << ":" << testQuotes[i] << " ";
			ofTest << (episodeIndex) << ":" << testEpisodeIds[i] << " ";*/
			
			ofTest << endl;
		}
	}

	Logger::getInstance()->log("converting data to libFM conform format done!", LOG_DEBUG);
}
コード例 #18
0
ファイル: Main.cpp プロジェクト: kurtiscc/Discrete-Structures
Token outputError(Parser& parser)
{
	return parser.getError();
}
コード例 #19
0
ファイル: TpDatos.cpp プロジェクト: javierlara/datos-indexer
void indexar(string nombre, string dir) {

	Parser* parser = Parser::getInstance();
	parser->parsearDirectorio(dir);

}
コード例 #20
0
ファイル: scgiServer.cpp プロジェクト: akalend/libscgi
void on_connect(int fd, short event, void *arg) 
	{
		sockaddr_in client_addr;
		socklen_t  len = sizeof(client_addr);
		// Accept incoming connection
		int sock = accept(fd, reinterpret_cast<sockaddr*>(&client_addr), &len);
		if (sock < 1) { 
			std::cerr << "accept error" << std::endl;
			return;
		}

		char * data =  (char*) malloc(BUFFSIZE);
		if (!data) {
			free(data);
			close(sock);
			cerr << "malloc error" << endl;
			return;
		}

		int data_size = read(sock, data, BUFFSIZE);
		if (data_size <= 0) {
			std::cout << "error read data " << strerror(errno) << std::cout;
			free(data);
			close(sock);
			return;	
		}

		map<string,string> parms;
		Parser parser;
		parser.run(data, &parms);

		map<string,string>::iterator ip;
		
//		for(ip = parms.begin(); ip != parms.end(); ip++) {
//			cout << (*ip).first << "\t\t" << (*ip).second << endl;
//		}

		char handler_data[BUFFSIZE];	
		bzero(handler_data,BUFFSIZE);	
		char out_data[BUFFSIZE];		
		
		map<string,IScgiHandler *>::iterator it;
		map<string,IScgiHandler *> * pHandlers = reinterpret_cast< map<string,IScgiHandler *> * >(arg);
						 		 
		it = pHandlers->find( parms["DOCUMENT_URI"] );

		int statusCode = 200; 
		char statusMsg[10];
		bzero(statusMsg,10);
		*handler_data = '\0';
		int contentLenght = 0;
		
		char headersOutBuff[1024];
		headersOutBuff[0] = '\0';
		if (it == pHandlers->end()) {
			statusCode = 404;
			strcpy(statusMsg,"Not Found");
		} else {
			strcpy(statusMsg,"Ok");
			IScgiHandler * handler = (*it).second;
			handler->run(&parms, handler_data);	
			contentLenght = strlen(handler_data);
			handler->getHeaders(headersOutBuff);	
		}
		
		sprintf(out_data,"Status: %d %s\r\nContent-lenght: %d\r\nX-Powered-By: libscgi\r\n%s\r\n%s", statusCode, statusMsg, contentLenght, headersOutBuff,handler_data);

		write(sock, out_data, strlen((char*)out_data) );	

		free(data);
		close(sock);
	}
コード例 #21
0
IAssistProposal *QssCompletionAssistProcessor::perform(const IAssistInterface *interface)
{
    m_interface.reset(interface);

    if (isInComment())
        return 0;

    if (interface->reason() == IdleEditor && !acceptsIdleEditor())
        return 0;

    if (m_startPosition == -1)
        m_startPosition = findStartOfName();

    QTextBlock block = interface->textDocument()->findBlock(interface->position());
    QTextBlock prevBlock = block.previous();
    Lexer lexer;
    Parser parser;
    if (prevBlock.isValid()) {
        lexer.setState(qssLexerState(prevBlock.userState()));
        parser.setState(qssParserState(prevBlock.userState()));
    }
    QList<Token> tokenList = lexer.scanMore(block.text());
    int index = m_startPosition - block.position();
    Q_FOREACH (const Token &t, tokenList) {
        if (index <= t.begin())
            break;
        parser.parseMore(t);
    }
    QStringList keywords;
    QIcon icon;
    switch (parser.state()) {
    case Parser::ObjectState:
        keywords << Lexer::objects();
        icon = QIcon(":/qsseditor/images/class.png");
        break;
    case Parser::PseudoStatesState:
        keywords << Lexer::pseudoStates();
        icon = QIcon(":/qsseditor/images/func.png");
        break;
    case Parser::SubControlState:
        keywords << Lexer::subControls();
        icon = QIcon(":/qsseditor/images/func.png");
        break;
    case Parser::AttributeNameState:
        keywords << Lexer::attributeNames();
        icon = QIcon(":/qsseditor/images/var.png");
        break;
    case Parser::AttributeBodyState:
        keywords << Lexer::attributeCtors() << Lexer::attributeKeywords();
        icon = QIcon(":/qsseditor/images/keyword.png");
        break;
    default:
        ;
    }
    keywords.removeDuplicates();
    QList<TextEditor::BasicProposalItem *> items;
    for (int i = 0; i < keywords.count(); i++) {
        BasicProposalItem *item = new QssAssistProposalItem;
        item->setText(keywords[i]);
        item->setIcon(icon);
        items.append(item);
    }
    return new GenericProposal(m_startPosition, new QssAssistProposalModel(items));
}
コード例 #22
0
ファイル: grepExample.C プロジェクト: matzke1/sawyer
int main(int argc, char *argv[]) {

    // Command-line parsing will "push" parsed values into members of this struct when ParserResult::apply is called.
    // Alternatively, we could have used a "pull" paradigm in which we query the ParserResult to obtain the values. In
    // fact, nothing prevents us from doing both, except if we use a pull paradigm we would probably want to set some
    // of the Switch::key properties so related switches (like -E, -F, -G, -P) all store their result in the same place
    // within the ParserResult.
    Options opt;

    // We split the switches into individual groups only to make the documentation better.  The name supplied to the
    // switch group constructor is the subsection under which the documentation for those switches appears.
    SwitchGroup generic("Generic Program Information");
    generic.switchOrder(INSERTION_ORDER);
    generic.doc("This paragraph is attached to a switch group and appears before the switches that this "
                "group contains.  It may be as many paragraphs as you like and may contain markup like for the "
                "individual switches.\n\n"
                "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec a diam lectus. Sed sit amet ipsum "
                "mauris. Maecenas congue ligula ac quam viverra nec consectetur ante hendrerit. Donec et mollis dolor. "
                "Praesent et diam eget libero egestas mattis sit amet vitae augue. Nam tincidunt congue enim, ut porta "
                "lorem lacinia consectetur. Donec ut libero sed arcu vehicula ultricies a non tortor. Lorem ipsum "
                "dolor sit amet, consectetur adipiscing elit. Aenean ut gravida lorem. Ut turpis felis, pulvinar a "
                "semper sed, adipiscing id dolor. Pellentesque auctor nisi id magna consequat sagittis. Curabitur "
                "dapibus enim sit amet elit pharetra tincidunt feugiat nisl imperdiet. Ut convallis libero in urna "
                "ultrices accumsan. Donec sed odio eros. Donec viverra mi quis quam pulvinar at malesuada arcu rhoncus. "
                "Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. In rutrum "
                "accumsan ultricies. Mauris vitae nisi at sem facilisis semper ac in est.");
    generic.insert(Switch("help")
                   .action(showHelpAndExit(0))
                   .doc("Print a usage message briefly summarizing these command-line options and the bug-reporting "
                        "address, then exit."));
    generic.insert(Switch("version", 'V')
                   .action(showVersion(VERSION_STRING))
                   .doc("Print the version number of @prop{programName} to the standard output stream. This version "
                        "number should be included in all bug reports (see below)."));
    generic.insert(Switch("log")
                   .action(configureDiagnostics("log", Sawyer::Message::mfacilities))
                   .argument("config")
                   .whichValue(SAVE_ALL)
                   .doc("Controls Sawyer diagnostics.  See Sawyer::Message::Facilities::control for details."));

    SwitchGroup matcher("Matcher Selection");
    matcher.switchOrder(INSERTION_ORDER);
    matcher.insert(Switch("extended-regexp", 'E')
                   .intrinsicValue(MATCHER_EXTENDED, opt.matcher)
                   .doc("Interpret @v{pattern} as an extended regular expression (ERE, see below). (@s{E} is specified "
                        "by POSIX.)"));
    matcher.insert(Switch("fixed-strings", 'F')
                   .intrinsicValue(MATCHER_STRINGS, opt.matcher)
                   .doc("Interpret @v{pattern} as a list of fixed strings, separated by newlines, any of which is to "
                        "be matched. (@s{F} is specified by POSIX.)"));
    matcher.insert(Switch("basic-regexp", 'G')
                   .intrinsicValue(MATCHER_BASIC, opt.matcher)
                   .doc("Interpret @v{pattern} as a basic regular expression (BRE, see below).  This is the default."));
    matcher.insert(Switch("perl-regexp", 'P')
                   .intrinsicValue(MATCHER_PERL, opt.matcher)
                   .doc("Interpret @v{pattern} as a Perl regular expression.  This is highly experimental and "
                        "@prop{programName} @s{P} may warn of unimplemented features."));

    SwitchGroup control("Matching Control");
    control.switchOrder(INSERTION_ORDER);
    control.insert(Switch("regexp", 'e')
                   .argument("pattern", anyParser(opt.pattern))
                   .doc("Use @v{pattern} as the pattern.  This can be used to specify multiple search patterns, or to "
                        "protect a pattern beginning with a hyphen (\"-\"). (@s{e} is specified by POSIX.)"));
    control.insert(Switch("file", 'f')
                   .argument("file", anyParser(opt.patternFile))
                   .doc("Obtain patterns from @v{file}, one per line.  The empty file contains zero patterns, and "
                        "therefore matches nothing. (@s{f} is specified by POSIX.)"));
    control.insert(Switch("ignore-case", 'i')
                   .intrinsicValue(true, opt.ignoreCase)
                   .doc("Ignore case distinctions in both the @v{pattern} and the input files. (@s{i} is specified "
                        "by POSIX.)"));
    control.insert(Switch("invert-match", 'v')
                   .intrinsicValue(true, opt.invert)
                   .doc("Invert the sense of matching, to select non-matching lines. (@s{v} is specified by POSIX.)"));
    control.insert(Switch("word-regexp", 'w')
                   .intrinsicValue(true, opt.wordRegexp)
                   .doc("Select only those lines containing matches that form whole words.  The test is that the "
                        "matching substring must either be at the beginning of the line, or preceded by a non-word "
                        "constituent character.  Similarly, it must be either at the end of the line or followed by "
                        "a non-word constituent character.  Word-constituent characters are letters, digits, and "
                        "the underscore."));
    control.insert(Switch("line-regexp", 'x')
                   .intrinsicValue(true, opt.lineRegexp)
                   .doc("Select only those matches that exactly match the whole line. (@s{x} is specified by POSIX.)"));
    control.insert(Switch("", 'y')
                   .whichValue(SAVE_NONE)
                   .doc("Obsolete synonym for @s{i}."));

    SwitchGroup output("General Output Control");
    output.name("output");
    output.doc("In this example, we've given this group of switches a name, \"output\", to demonstrate how switch group "
               "name spaces work.  The switches here can be invoked by the name they were given in the C++ source code, "
               "or they can include the switch group name, as in @s{count} or @s{output-count}.");
    output.switchOrder(INSERTION_ORDER);
    output.insert(Switch("count", 'c')
                  .intrinsicValue(true, opt.count)
                  .doc("Suppress normal output; instead print a count of matching lines for each input file.  With "
                       "the @s{v}, @s{invert-match} option (see below), count non-matching lines. (@s{c} is specified "
                       "by POSIX.)"));
    output.insert(Switch("color")
                  .longName("colour")
                  .argument("when",
                            enumParser(opt.colorWhen)
                            ->with("never", COLOR_NEVER)
                            ->with("always", COLOR_ALWAYS)
                            ->with("auto", COLOR_AUTO),
                            "auto")
                  .doc("Surround the matched (non-empty) strings, matching lines, context lines, file names, line "
                       "numbers, byte offsets, and separators (for fields and groups of context lines) with escape "
                       "sequences to display them in color on the terminal.  The colors are defined by the "
                       "environment variable \"GREP_COLORS\".  The deprecated environment variable \"GREP_COLOR\" "
                       "is still supported, but its setting does not have priority. @v{when} is \"never\", \"always\", "
                       "or \"auto\"."));
    output.insert(Switch("files-without-match", 'L')
                  .intrinsicValue(true, opt.filesWithoutMatch)
                  .doc("Suppress normal output; instead print the name of each input file from which no output "
                       "would normally have been printed.  The scanning will stop on the first match."));
    output.insert(Switch("files-with-matches", 'l')
                  .intrinsicValue(true, opt.filesWithMatches)
                  .doc("Suppress normal output; instead print the name of each input file from which output would "
                       "normally have been printed.  The scanning will stop on the first match. (@s{l} is specified "
                       "by POSIX.)"));
    output.insert(Switch("max-count", 'm')
                  .argument("num", nonNegativeIntegerParser(opt.maxCount))
                  .doc("Stop reading a file after @v{num} matching lines.  If the input is standard input from a "
                       "regular file, and @v{num} matching lines are output, @prop{programName} ensures that the "
                       "standard input is positioned to just after the last matching line before exiting, "
                       "regardless of the presence of trailing context lines.  This enables a calling process "
                       "to resume a search.  When @prop{programName} stops after @v{num} matching lines, it "
                       "outputs any trailing context lines.  When the @s{c} or @s{count} options is also used, "
                       "@prop{programName} does not output a count greater than @v{num}.  When the @s{v} or "
                       "@s{invert-match} option is also used, @prop{programName} stops after outputting @v{num} "
                       "non-matching lines."));
    output.insert(Switch("only-matching", 'o')
                  .intrinsicValue(true, opt.onlyMatching)
                  .doc("Print only the matched (non-empty) parts of a matching line, with each such part on a "
                       "separate output line."));
    output.insert(Switch("quiet", 'q')
                  .longName("silent")
                  .intrinsicValue(true, opt.quiet)
                  .doc("Quiet; do not write anything to standard output.  Exit immediately with zero status "
                       "if any match is found, even if an error was detected.  Also see the @s{s} or "
                       "@s{no-messages} option. (@s{q} is specified by POSIX.)"));
    output.insert(Switch("no-messages", 's')
                  .intrinsicValue(true, opt.noMessages)
                  .doc("Suppress error messages about nonexistent or unreadable files.  Portability note: "
                       "unlike GNU grep, 7th Edition Unix grep did not conform to POSIX, because it lacked "
                       "@s{q} and its @s{s} option behaved like GNU grep's @s{q} option.  USG-style grep "
                       "also lacked @s{q} but its @s{s} option behaved like GNU grep.  Portable shell "
                       "scripts should avoid both @s{q} and @s{s} and should redirect standard and error "
                       "output to /dev/null instead.  (@s{s} is specified by POSIX.)"));

    SwitchGroup prefix("Output Line Prefix Control");
    prefix.switchOrder(INSERTION_ORDER);
    prefix.insert(Switch("byte-offset", 'b')
                  .intrinsicValue(true, opt.byteOffset)
                  .doc("Print the 0-based byte offset within the input file before each line of output. "
                       "If @s{o} (@s{only-matching}) is specified, print the offset of the matching part "
                       "itself."));
    prefix.insert(Switch("with-filename", 'H')
                  .intrinsicValue(true, opt.withFileName)
                  .doc("Print the file name for each match.  This is the default when there is more than one "
                       "file to search."));
    prefix.insert(Switch("no-filename", 'h')
                  .intrinsicValue(false, opt.withFileName)
                  .doc("Suppress the prefixing of file names on output.  This is the default when there is only "
                       "one file (or only standard input) to search."));
    prefix.insert(Switch("label")
                  .argument("label", anyParser(opt.label))
                  .doc("Display input actually coming from standard input as input coming from file @v{label}. "
                       "This is especially useful when implementing tools like zgep, e.g., \"gzip -cd foo.gz | "
                       "grep --label=foo -H something\".  See also the @s{H} option."));
    prefix.insert(Switch("line-number", 'n')
                  .intrinsicValue(true, opt.lineNumbers)
                  .doc("Prefix each line of output with the 1-based line number within its input file. (@s{n} "
                       "is specified by POSIX.)"));
    prefix.insert(Switch("initial-tab", 'T')
                  .intrinsicValue(true, opt.initialTab)
                  .doc("Make sure that the first character of actual line content lies on a tab stop, so that "
                       "the alignment of tabs looks normal.  This is useful with options that prefix their "
                       "output to the actual content: @s{H}, @s{n}, and @s{b}.  In order to improve the "
                       "probability that lines from a single file will all start at the same column, this "
                       "also causes the line number and byte offset (if present) to be printed in a minimum "
                       "size field width."));
    prefix.insert(Switch("unix-byte-offsets", 'u')
                  .intrinsicValue(true, opt.unixByteOffsets)
                  .doc("Report Unix-style byte offsets.  This switch causes @prop{programName} to report byte "
                       "offsets as if the file were a Unix-style text file, i.e., with CR characters stripped "
                       "off.  This will produce results identical to running @prop{programName} on a Unix "
                       "machine.  This option has no effect unless @s{b} option is also used;  it has no "
                       "effect on platforms other than MS-DOS and MS-Windows."));
    prefix.insert(Switch("null", 'Z')
                  .intrinsicValue(true, opt.nullAfterName)
                  .doc("Output a zero byte (the ASCII NUL character) instead of the character that normally "
                       "follows a file name.  For example, \"grep -lZ\" outputs a zero byte after each file "
                       "name instead of the usual newline.  This option makes the output unambiguous, even in "
                       "the presence of file name containing unusual characters like newlines.  This option "
                       "can be used with commands like \"find -print0\", \"perl -0\", \"sort -z\", and \"xargs "
                       "-0\" to process arbitrary file names, even those that contain newline characters."));

    SwitchGroup context("Context Line Control");
    context.switchOrder(INSERTION_ORDER);
    context.insert(Switch("after-context", 'A')
                   .argument("num", nonNegativeIntegerParser(opt.afterContext))
                   .doc("Print @v{num} lines of trailing context after matching lines.  Places a line containing "
                        "a group separator (\"--\") between contiguous groups of matches.  With the @s{o} or "
                        "@s{only-matching} option, this has no effect and a warning is given."));
    context.insert(Switch("before-context", 'B')
                   .argument("num", nonNegativeIntegerParser(opt.beforeContext))
                   .doc("Print @v{num} lines of leading context before matching lines.  Places a line containing "
                        "a group separator (\"--\") between contigous groups of matches.  With the @s{o} or "
                        "@s{only-matching} option, this has no effect and a warning is given."));
    context.insert(Switch("context", 'C')               // FIXME[Robb Matzke 2014-03-15]: allow "-NUM"
                   .argument("num", nonNegativeIntegerParser(opt.contextLines))
                   .doc("Print @v{num} lines of output context.  Places a line containing a group separator "
                        "(\"--\") between contigous groups of matches.  With the @s{o} or @s{only-matching} "
                        "option, this has no effect and a warning is given."));

    SwitchGroup selection("File and Directory Selection");
    selection.switchOrder(INSERTION_ORDER);
    selection.insert(Switch("text", 'a')
                     .intrinsicValue(BIN_TEXT, opt.binaryFile)
                     .doc("Process a binary file as if it were text; this is the equivalent to the "
                          "\"@s{binary-files}=text\" option."));
    selection.insert(Switch("binary-files")
                     .argument("type",
                               enumParser(opt.binaryFile)
                               ->with("binary", BIN_BINARY)
                               ->with("without-match", BIN_SKIP)
                               ->with("text", BIN_TEXT))
                     .doc("If the first few bytes of a file indicate that the file contains binary data, assume "
                          "that the file is of type @v{type}.  By default, @v{type} is \"binary\", and "
                          "@prop{programName} normally outputs either a one-line message saying that a binary "
                          "file matches, or no message if there is no match.  If @v{type} is \"without-match"
                          "@prop{programName} assumes that a binary file does not match; this is equivalent to "
                          "the @s{I} option.  If @v{type} is \"text\", @prop{programName} processes a binary "
                          "file as if it were text; ths is equivalent to the @s{a} option.  @b{Warning:} "
                          "\"@prop{programName} @s{binary-files}=text\" might output binary garbage, which can "
                          "have nasty side effects if the output is a terminal and if the terminal driver "
                          "interprets some of it as commands."));
    selection.insert(Switch("devices", 'D')
                     .argument("action",
                               enumParser(opt.deviceAction)
                               ->with("read", ACTION_READ)
                               ->with("skip", ACTION_SKIP))
                     .doc("If an input file is a device, FIFO, or socket, use @v{action} to process it.  By "
                          "default, @v{action} is \"read\", which means that devices are read just as if they "
                          "were ordinary files.  If @v{action} is \"skip\", devices are silently skipped."));
    selection.insert(Switch("directories", 'd')
                     .argument("action",
                               enumParser(opt.directoryAction)
                               ->with("read", ACTION_READ)
                               ->with("skip", ACTION_SKIP)
                               ->with("recurse", ACTION_RECURSE))
                     .doc("If an input file is a directory, use @v{action} to process it.  By default, "
                          "@v{action} is \"read\", which means that directories are read just as if they were "
                          "ordinary files.  If @v{action} is \"skip\", directories are silently skipped. If "
                          "@v{action} is \"recurse\", @prop{programName} reads all files under each directory, "
                          "recursively; this is equivalent to the @s{r} option."));
    selection.insert(Switch("exclude")
                     .argument("glob", anyParser(opt.excludeGlob))
                     .doc("Skip files whose base name matches @v{glob} (using wildcard matching). A file-name "
                          "glob can use \"*\", \"?\", and \"[...]\" as wildcards, and \"\\\" to quote a wildcard "
                          "or backslash character literally."));
    selection.insert(Switch("exclude-from")
                     .argument("file", anyParser(opt.excludeFromFile))
                     .doc("Skip files whose base name matches any of the file-name globs read from @v{file} "
                          "(using wildcard matching as described under @s{exclude})."));
    selection.insert(Switch("", 'I')
                     .intrinsicValue(BIN_SKIP, opt.binaryFile)
                     .doc("Process a binary file as if it did not contain matching data; this is equivalent "
                          "to the \"@s{binary-files}=without-match\" option."));
    selection.insert(Switch("include")
                     .argument("glob", anyParser(opt.includeGlob))
                     .doc("Search only files whose base names match @v{glob} (using wildcard matching as "
                          "described under @s{exclude})."));
    selection.insert(Switch("recursive", 'R')
                     .shortName('r')
                     .intrinsicValue(ACTION_RECURSE, opt.directoryAction)
                     .doc("Read all files under each directory, recursively; this is equivalent to the "
                          "\"@s{d} recurse\" option."));

    SwitchGroup misc("Other Options");
    misc.switchOrder(INSERTION_ORDER);
    misc.insert(Switch("line-buffered")
                .intrinsicValue(true, opt.lineBuffered)
                .doc("Use line buffering on output.  This can cause a performance penalty."));
    misc.insert(Switch("mmap")
                .intrinsicValue(true, opt.useMmap)
                .doc("If possible, use the @man{mmap}{2} system call to read input, instead of the default "
                     "@man{read}{2} system call.  In some situations, @s{mmap} yields better performance.  "
                     "However, @s{mmap} can cause undefined behavior (including core dumps) if an input "
                     "file shrinks while @prop{programName} is operating, or if an I/O error occurs."));
    misc.insert(Switch("binary", 'U')
                .intrinsicValue(true, opt.openAsBinary)
                .doc("Treat the file(s) as binary.  By default, under MS-DOS and MS-Windows, "
                     "@prop{programName} guesses the file type by looking at the contents of the first 32kB "
                     "read from the file.  If @prop{programName} decides the file is a text file, it strips "
                     "the CR characters from the original file contents (to make regular expressions with "
                     "\"^\" and \"$\" work correctly).  Specifying @s{U} overrules this guesswork, causing all "
                     "files to be read and passed to the matching mechanism verbatim; if the file is a text file "
                     "with CR/LF pairs at the end of each line, this will cause some regular expressions to "
                     "fail.  This option has no effect on platforms other than MS-DOS and MS-Windows."));
    misc.insert(Switch("null-data", 'Z')
                .intrinsicValue(true, opt.nulTerminatedLines)
                .doc("Treat the input as a set of lines, each terminated by a zero byte (the ASCII NUL character) "
                     "instead of a newline.  Like the @s{Z} or @s{null} option, this option can be used with "
                     "commands like \"sort -z\" to process arbitrary file names."));


    // Build the parser
    Parser parser;
    parser
        .with(generic)
        .with(matcher)
        .with(control)
        .with(output)
        .with(prefix)
        .with(context)
        .with(selection)
        .with(misc);

    // Add some top-level documentation.
    parser
        .programName("demoGrep")                        // override the real command name
        .purpose("print lines matching a pattern")
        .version(VERSION_STRING)
        .doc("Synopsis",
             "@b{@prop{programName}} [@v{options}] @v{pattern} [@v{file}...]\n\n"
             "@b{@prop{programName}} [@v{options}] [@s{e} @v{pattern} | @s{f} @v{file}] [@v{file}...]")
        .doc("Description",
             "@prop{programName} searches the named input @v{file}s (or standard input if no files are named, or if "
             "a single hyphen-minus (\"-\") is given as the file name) for lines containing a match to the given "
             "@v{pattern}.  By default, @prop{programName} prints the matching lines."
             "\n\n"
             "In addition, three variant programs egrep, fgrep, and rgrep are available.  egrep is the same as "
             "\"@prop{programName} @s{E}\"; fgrep is the same as \"@prop{programName} @s{F}\"; rgrep is the same as "
             "\"@prop{programName} @s{r}\".  Direct invocation as either \"egrep\" or \"fgrep\" is deprecated, but "
             "is provided to allow historical applications that rely on them to run unmodified.")
        .doc("Regular Expressions",
             "A regular expression is a pattern that describes a set of strings.  Regular expressions are "
             "constructed analogously to arithmetic expressions, by using various operators to combine smaller "
             "expressions."
             "\n\n"
             "@prop{programName} understands three different versions of regular expression syntax: \"basic,\" "
             "\"extended\" and \"perl.\"  In @prop{programName}, there is no difference in available functionality "
             "between basic and extended syntaxes.  In other implementations, basic regular expressions are less "
             "powerful.  The following description applies to extended regular expressions; differences for basic "
             "regular expressions are summarized afterwards.  Perl regular expressions give additional functionality, "
             "and are documented in @man{pcresyntax}{3} and @man{pcrepattern}{3}, but may not be available on every "
             "system."
             "\n\n"
             "The fundamental building blocks are the regular expressions that match a single character.  Most "
             "characters, including all letters and digits, are regular expressions that  match  themselves.   Any "
             "meta-character with special meaning may be quoted by preceding it with a backslash."
             "\n\n"
             "The period \".\" matches any single character.");


    // Parse the command-line
    ParserResult cmdline = parser.parse(argc, argv);

    // Apply the parser results, causing values to be saved and actions to be executed.
    cmdline.apply();

}
コード例 #23
0
ファイル: GenWordList.cpp プロジェクト: rhyme9316/project
void GenWordList::sortAllWords(vector<Page>& pages){
    cout<<"pages.size = "<< pages.size()<<endl;
    
    for(int i = 0; i < pages.size(); i++){
        Parser *ps = new Parser(pages[i].page.length());
        //buffer = NULL;
        //cout << i << endl;
        //cout <<pages[i].page<<endl;
        //buffer = (char*)malloc(sizeof(char)*pages[i].page.length());
        char buffer[pages[i].page.length()];
        
        strcpy(buffer,pages[i].page.c_str());
        unsigned int res = ps->parser(buffer, pages[i].len);

        //  cout<<"i="<<i<<"	page_docId:  "<<pages[i].docId << "   res= "<<res<<endl;
        
        if (res > 0){
            string resBuffer = ps->getBuf();
            vector<int> pos = ps->getPos();
            
            //cout<<"buffer length = "<<buffer.length()<<endl;
            //cout<<"pos size = "<< pos.size()<<endl;
            
            storeDocInfo(pages[i].docId, pages[i].url,pos.size());
            string word = "";
            int k = 0;
            for(int j = 0; j < resBuffer.length(); j++){
                //cout<<"k="<<k<<endl;
                if(resBuffer[j] == ' '){
                    if(word == "") continue;
                    map<string,list<Post>>::iterator it = word_by_alphabet.find(word);
                    if(it == word_by_alphabet.end() || it->second.back().previousDocId != pages[i].docId){
                        //docId for new post, freqency, previous pos,previous docId;
                        Post post(pages[i].docId,1,pos[k],pages[i].docId);
                        post.pos.push_back(pos[k++]);
                        if(it == word_by_alphabet.end()){
                            list<Post> tmpList;
                            tmpList.push_back(post);
                            
                            word_by_alphabet.insert(pair<string,list<Post>>(word, tmpList));
                        } else{
                            post.docId -= it->second.back().previousDocId;
                            it->second.back().previousDocId = pages[i].docId;
                            it->second.push_back(post);
                        }
                    } else{
                        it->second.back().freq ++;
                        it->second.back().pos.push_back(pos[k] - it->second.back().previousPos);
                        it->second.back().previousPos = pos[k++];
                    }
                    //cout<<word<<endl;
                    word = "";
                } else if(resBuffer[j] == '\n'){
                    word = "";
                } else{
                    word += resBuffer[j];
                }
            }
            
        }
        //ps->resetBuf();
        //ps->resetPos();
        delete ps;
    }
    cout<<"here   "<<word_by_alphabet.size()<<endl;
    printToFile();
    //delete ps;
    return;
}
コード例 #24
0
ファイル: main.cpp プロジェクト: hnawaz/SC_Tracers
int main ( int argc)
{
	Triangle t1;
	Triangle t2;
	int	status = 0; 

	int lights = 4; //no.of lights
	ImageBuffer image(WIDTH,HEIGHT);
	status |= image.initImageBuf();
	Parser* p = new Parser("E:\\USC\\CSCI 580 (Fall 2014)\\Final\\diamond\\diamond_trans_330.asc");
	Diamond d = Diamond(p->parse());
	int* count= new int(0);
	float angle_x = 25;
	float Rx[3][3] =
    {
		{1,0,0},
		{0,cosd(angle_x),-sind(angle_x)},
		{0,sind(angle_x),cosd(angle_x)}
    };


	float AAFilter[AAKERNEL_SIZE][3] 	=		/* X, Y, coef */
	{
		-0.52, 0.38, 0.128,
		0.41, 0.56, 0.119,
		0.27, 0.08, 0.294,
		-0.17, -0.29, 0.249,
		0.58, -0.55, 0.104,
		-0.31, -0.71, 0.106
	};


	Vertex dir = Vertex(0,0,10.75);//-[-0.1,3,6]);
	Vertex temp= Vertex(-0.1,3,6);
	dir=dir.sub(temp);
	dir.norm();// = direction/norm(direction);
	const int num_lights=2;

	float light_vec[][11] = 
	{
		{1,1,0,2.745,10.75, 0, -1, 0, 0, 0, -1},
		{1,1,0,0,6,dir.x,dir.y,dir.z,0,1,0}
	};


	float x_l[5] = {-0.5, -0.25, 0, 0.25, 0.5};
	float y_l[5] = {-0.5, -0.25, 0, 0.25, 0.5};
	float light_list[5*5*num_lights][3] = {0}; // zeros(num_lights,3);

	

	int count_light =0;
	for(int i=0;i<num_lights;i++)
	{
		float point1[4] = {-0.5,-0.5,0,1};//'';
	    float point2[4] ={0.5,-0.5,0,1};//]';
        float point3[4] = {0.5,0.5,0,1};//]';
        float point4[4] = {-0.5,0.5,0,1};//]';


		float cur_light[11] ;
		for(int k=0;k<11;k++)
			cur_light[k]=light_vec[i][k];
    
		Vertex z1 = Vertex(cur_light[5],cur_light[6],cur_light[7]);///norm(light(6:8));
		z1.norm();

		Vertex up_p = Vertex(cur_light[8],cur_light[9],cur_light[10]);///norm(light(6:8));
		up_p=up_p.mul(z1);
		up_p=up_p.mul(z1);
		Vertex y1=Vertex(cur_light[8],cur_light[9],cur_light[10]);
		y1=y1.sub(up_p);
		y1.norm();
		Vertex x1=y1.cross(z1);

		float x_wi[4][4]=
		{
			{x1.x,y1.x,z1.x,0},
			{x1.y,y1.y,z1.y,0},
			{x1.z,y1.z,z1.z,0},
			{0,0,0,1}
		};

//    x_wi = [[[x1',y1',z1'],[0 0 0]'];[0 0 0 1]];
		float trans[4][4] = 
		{
			{light_vec[i][0],0, 0 ,light_vec[i][2]},
			{ 0, light_vec[i][1],0 ,light_vec[i][3]},
			{0 ,0, 1, light_vec[i][4]},
			{0,0,0,1}
		}; 

		float M[4][4];

		matMult(trans,x_wi,M);
		pointMult(M,point1,point1);
		pointMult(M,point2,point2);
		pointMult(M,point3,point3);
		pointMult(M,point4,point4);
    
		for(int x=0;x<3;x++)
		{
			point1[x]/=point1[3];
			point2[x]/=point2[3];
			point3[x]/=point3[3];
			point4[x]/=point4[3];
		}
    
		Vertex vv1 = Vertex(point1[0],point1[1],point1[2]);
		Vertex vv2 = Vertex(point2[0],point2[1],point2[2]);
		Vertex vv3 = Vertex(point3[0],point3[1],point3[2]);
		Vertex vv4 = Vertex(point4[0],point4[1],point4[2]);

		 t1 = Triangle (vv1,vv2,vv4,"L");
		 t2 = Triangle (vv4,vv2,vv3,"L");
		t1.surfaceColor = Color(1,1,1,1);
		t1.emissionColor = Color(1,1,1,1);
		t2.surfaceColor = Color(1,1,1,1);
		t2.emissionColor = Color(1,1,1,1);
		d.tri.push_back(t1);
		d.tri.push_back(t2);

		for (int ii=0;ii<5;ii++){
			for(int jj=0;jj<5;jj++){
				float pos[4]={x_l[ii],y_l[jj],0,1};	
				float M[4][4];
				matMult(trans,x_wi,M);
				pointMult(M,pos,pos);
				pos[0]/=pos[3];
				pos[1]/=pos[3];
				pos[2]/=pos[3];

				light_list[count_light][0]= pos[0];
				light_list[count_light][1]= pos[1];
				light_list[count_light][2]= pos[2];
				count_light++;
			}
		}


	}

/*
	float x_l[5] =  {-0.5000,   -0.2500  ,       0   , 0.2500  ,  0.5000};
	float y_l[5] =  {-0.5000,   -0.2500  ,       0   , 0.2500  ,  0.5000};
	int count = 0;t
	float light_list[5*5*num_lights][3] = {0};// zeros(num_lights,3);
	for (int li=0; li < num_lights;li++)
	{
		
	}
    light = lights(l_ii,:);

    trans = [light(1),0 0 light(3); 0, light(2),0 light(4);0 0 1 light(5);0 0 0 1]; 

    z1 = light(6:8)/norm(light(6:8));
    up_p = light(9:11) - (light(9:11)*z1')*z1;
    y1 = up_p/norm(up_p);
    x1  = cross(y1,z1);
    x_wi = [[[x1',y1',z1'],[0 0 0]'];[0 0 0 1]];
    

    for ii = 1:length(x_l)
        for jj = 1:length(y_l)
            pos = [x_l(ii), y_l(jj) ,0, 1]';
            pos1 = trans*x_wi*pos;
            xxx = pos1(1)/pos1(4);
            yyy = pos1(2)/pos1(4);
            zzz = pos1(3)/pos1(4);
            count = count+1;
            light_list(count,:) = [xxx,yyy,zzz];
       
        end
    end
end
*/

	for ( int y = 0 ; y < HEIGHT ; y++ )
	{
		//display(['trace ' num2str(yy/height*100) '%']);
		cout<<"tracing "<< (double)y/(double)HEIGHT*100 <<"%"<<endl;
		for ( int x = 0 ; x < WIDTH ; x++ )
		{
			for (int aa = 0; aa < AAKERNEL_SIZE; aa++)
			{
				Vertex dr(0,0,0);
				dr.x = (2 * ((x+0.5 + AAFilter[aa][0])/WIDTH) -1  )*ANGLE*ASPECTRATIO;
				float temp = (1 - 2*((y+0.5 + AAFilter[aa][1])/HEIGHT)) ;
				float angle=tand(0.5*FOV);;
				dr.y=temp*angle;
				dr.z = 1;
				float n=normalize(dr);
				dr.x = dr.x/n;	dr.y = dr.y/n;	dr.z = dr.z/n;
				Vertex v(0,0,0);
				Color output_color_r,output_color_g,output_color_b;
				dr.matMul(Rx);
				Vertex dr_origin;
				dr_origin.x=dr.x*9-0.1;
				dr_origin.y=dr.y*9+3;
				dr_origin.z=dr.z*9;
				output_color_r = raytrace(dr_origin,dr,d.tri,0,count,count_light,2.40,light_list);
				output_color_g = raytrace(dr_origin,dr,d.tri,0,count,count_light,2.43,light_list);
				output_color_b = raytrace(dr_origin,dr,d.tri,0,count,count_light,2.46,light_list);

				image.addImageBuf(x,y, (output_color_r.r)*AAFilter[aa][2], (output_color_g.g)*AAFilter[aa][2], (output_color_b.b)*AAFilter[aa][2]);
				//image.addImageBuf(x,y, (output_color_r.r)*AAFilter[aa][2], (output_color_r.g)*AAFilter[aa][2], (output_color_r.b)*AAFilter[aa][2]);
		
			}
		}
	}
	*count=*count+1-1;

	FILE *outfile;
	if( (outfile  = fopen( "330.ppm" , "wb" )) == NULL )
	{
		cout<<"Failed to open output file"<<endl;
		return 0;
	}

	image.flushDisplay2File(outfile);
	image.freeBuf();
}
コード例 #25
0
//-------------------------------------------------------------------------------------------------
double BenchMuParser2::DoBenchmarkStd(const std::string& sExpr, long iCount)
{
   Parser p;

   double fRes(0);
   double fSum(0);
   double a = 1.1;
   double b = 2.2;
   double c = 3.3;
   double x = 2.123456;
   double y = 3.123456;
   double z = 4.123456;
   double w = 5.123456;

   p.SetExpr(sExpr.c_str());
   p.DefineVar("a", &a);
   p.DefineVar("b", &b);
   p.DefineVar("c", &c);

   p.DefineVar("x", &x);
   p.DefineVar("y", &y);
   p.DefineVar("z", &z);
   p.DefineVar("w", &w);

   p.DefineConst("pi", (double)M_PI);
   p.DefineConst("e", (double)M_E);

   try
   {

      fRes = p.Eval(); // create bytecode on first time parsing, don't want to have this in the benchmark loop
                       // since fparser does it in Parse(...) wich is outside too
                       // (Speed of bytecode creation is irrelevant)
   }
   catch(ParserError &exc)
   {
      StopTimerAndReport(exc.GetMsg());
      return std::numeric_limits<double>::quiet_NaN();
   }
   catch(...)
   {
      StopTimerAndReport("unexpected exception");
      return std::numeric_limits<double>::quiet_NaN();
   }

   //Prime the I and D caches for the expression
   {
      double d0 = 0.0;
      double d1 = 0.0;

      for (std::size_t i = 0; i < priming_rounds; ++i)
      {
         if (i & 1)
            d0 += p.Eval();
         else
            d1 += p.Eval();
      }

      if (
            (d0 == std::numeric_limits<double>::infinity()) &&
            (d1 == std::numeric_limits<double>::infinity())
         )
      {
         printf("\n");
      }
   }

   StartTimer();

   for (int j = 0; j < iCount; ++j)
   {
      fSum += p.Eval();
      std::swap(a,b);
      std::swap(x,y);
   }

   StopTimer(fRes, fSum, iCount);

   return m_fTime1;
}
コード例 #26
0
ファイル: main.cpp プロジェクト: micahdlamb/Lisp
	void operator()(string s){
		p.scanner(s);
	}
コード例 #27
0
char* ABNFSIPPathSegments::parse(const char* _t)
{
  return _parser.parse(_t);
}
コード例 #28
0
std::auto_ptr<LValue> make_variable_lvalue( 
    const Variable& v, const std::string& s, const Parser& p )
{
    return std::auto_ptr<LValue>( new Assignment( v, p.parse_numeric(s)->root_node ) );
}
コード例 #29
0
ファイル: main.cpp プロジェクト: Latexi95/CBCompiler
int main(int argc, char *argv[]) {
    QCoreApplication a(argc, argv);

    /*QSettings test("test.ini", QSettings::IniFormat);
    test.beginGroup("compiler");
    test.setValue("test-value", "asd");
    test.setValue("other-value", "val");
    test.endGroup();
    test.beginGroup("opt");
    test.setValue("test-value2", "asd2");
    test.setValue("other-value2", "val2");
    test.endGroup();
    test.sync();
    return 0;*/

    QTime bigTimer;
    bigTimer.start();

    QStringList params = a.arguments();
    if (params.size() != 2) {
        qCritical() << "Expecting file to compile";
        return 0;
    }


    ErrorHandler errHandler;

    Settings settings;
    bool success = false;
    success = settings.loadDefaults();
    if (!success) {
        errHandler.error(ErrorCodes::ecSettingsLoadingFailed, errHandler.tr("Loading the default settings \"%1\" failed").arg(settings.loadPath()), CodePoint());
        return ErrorCodes::ecSettingsLoadingFailed;
    }


    Lexer lexer;
    QObject::connect(&lexer, &Lexer::error, &errHandler, &ErrorHandler::error);
    QObject::connect(&lexer, &Lexer::warning, &errHandler, &ErrorHandler::warning);
    QTime timer;
    timer.start();
    if (lexer.tokenizeFile(params[1], settings) == Lexer::Success) {
        qDebug() << "Lexical analysing took " << timer.elapsed() << "ms";
#ifdef DEBUG_OUTPUT
        lexer.writeTokensToFile("tokens.txt");
#endif
    }
    else {
        errHandler.error(ErrorCodes::ecLexicalAnalysingFailed, errHandler.tr("Lexical analysing failed"), CodePoint(lexer.files().first().first));
        return ErrorCodes::ecLexicalAnalysingFailed;
    }

    Parser parser;
    QObject::connect(&parser, &Parser::error, &errHandler, &ErrorHandler::error);
    QObject::connect(&parser, &Parser::warning, &errHandler, &ErrorHandler::warning);

    timer.start();
    ast::Program *program = parser.parse(lexer.tokens(), settings);
    qDebug() << "Parsing took " << timer.elapsed() << "ms";
    if (!parser.success()) {
        errHandler.error(ErrorCodes::ecParsingFailed, errHandler.tr("Parsing failed \"%1\"").arg(params[1]), CodePoint());
        return ErrorCodes::ecParsingFailed;
    }

#ifdef DEBUG_OUTPUT
    if (program) {
        QFile file("ast.txt");
        if (file.open(QFile::WriteOnly)) {
            QTextStream stream(&file);
            program->write(stream);
            file.close();
        }
    }
#endif



    CodeGenerator codeGenerator;
    //QObject::connect(&codeGenerator, &CodeGenerator::error, &errHandler, &ErrorHandler::error);
    //QObject::connect(&codeGenerator, &CodeGenerator::warning, &errHandler, &ErrorHandler::warning);
    QObject::connect(&codeGenerator, &CodeGenerator::error, &errHandler, &ErrorHandler::error);
    QObject::connect(&codeGenerator, &CodeGenerator::warning, &errHandler, &ErrorHandler::warning);

    timer.start();
    if (!codeGenerator.initialize(settings)) {
        return ErrorCodes::ecCodeGeneratorInitializationFailed;
    }


    qDebug() << "Code generator initialization took " << timer.elapsed() << "ms";
    timer.start();
    if (!codeGenerator.generate(program)) {
        errHandler.error(ErrorCodes::ecCodeGenerationFailed, errHandler.tr("Code generation failed"), CodePoint());
        return ErrorCodes::ecCodeGenerationFailed;
    }

    qDebug() << "Code generation took" << timer.elapsed() << "ms";
    qDebug() << "LLVM-IR generated";

    timer.start();
    codeGenerator.createExecutable(settings.defaultOutputFile());
    qDebug() << "Executable generation took " << timer.elapsed() << "ms";
    qDebug() << "The whole compilation took " << bigTimer.elapsed() << "ms";
    return 0;
}
コード例 #30
0
ファイル: ArmParser.cpp プロジェクト: ketlerd/armips
void ArmParser::parseWriteback(Parser& parser, bool& dest)
{
    dest = parser.peekToken().type == TokenType::Exclamation;
    if (dest)
        parser.eatToken();
}