Example #1
0
static int
Test_verifierParseSymbol(void)
{
  char* file;
  struct reader r;
  struct verifier vrf;
  int isEndOfStatement;
#define testfile(f, e) \
  do { \
    file = f; \
    readerInitString(&r, file); \
    verifierInit(&vrf); \
    verifierBeginReadingFile(&vrf, &r); \
    verifierParseSymbol(&vrf, &isEndOfStatement, '.'); \
    check_err(vrf.err, e); \
    readerClean(&r); \
    verifierClean(&vrf); \
  } while (0)
  testfile("forced:", error_unterminatedStatement);
  ut_assert(isEndOfStatement == 0, "isEndOfStatement is %d, expected 0",
   isEndOfStatement);
  // testfile("bursts$. ", error_invalidSymbol);
  // ut_assert(isEndOfStatement == 0, "isEndOfStatement is %d, expected 0",
   // isEndOfStatement);
  testfile("$. ", error_none);
  ut_assert(isEndOfStatement == 1, "isEndOfStatement is %d, expected 1",
   isEndOfStatement);
  return 0;
#undef testfile
}
Example #2
0
int
test_ntfs_comp()
{
    TSK_FS_INFO *fs;
    TSK_IMG_INFO *img;
    char *tname = "ntfs-comp-1";
    char fname[512];

    snprintf(fname, 512, "%s/ntfs-comp-1.img", s_root);
    if ((img = tsk_img_open_sing(fname, (TSK_IMG_TYPE_ENUM) 0, 0)) == NULL) {
        fprintf(stderr, "Error opening %s image\n", tname);
        tsk_error_print(stderr);
        return 1;
    }

    if ((fs = tsk_fs_open_img(img, 0, (TSK_FS_TYPE_ENUM) 0)) == NULL) {
        fprintf(stderr, "Error opening %s image\n", tname);
        tsk_error_print(stderr);
        return 1;
    }

    if (testfile(fs, 34)) {
        fprintf(stderr, "%s error (both)\n", tname);
        return 1;
    }

    if (testfile(fs, 32)) {
        fprintf(stderr, "%s error (sparse)\n", tname);
        return 1;
    }

    tsk_fs_close(fs);
    tsk_img_close(img);
    return 0;
}
Example #3
0
static void findfile (FIND * find, flag_t flags)

{
	struct dirent * dirent;
	char * filename = find->fullname;
	DIR * dir = opendir (filename);
	if (dir == (DIR *) (0))
	{
		testfile (find, flags);
		return;
	}
	while (* filename)
	{
		filename++;
	}
	* filename = PATH_C_EXTENDER;
	while ((dirent = readdir (dir)))
	{
		strcpy (filename +  1, dirent->d_name);
		partpath (find->fullname, find->pathname, find->filename);
		partfile (find->filename, find->basename, find->extender);
		testfile (find, flags);
	}
	* filename = (char) (0);
	closedir (dir);
	return;
}
Example #4
0
File: test.c Project: noct/cutf
int main(int argc, char** argv)
{
	testfile("utf8_invalid.txt");
	testfile("quickbrown.txt");
	testfile("UTF-8-demo.txt");
	testfile("big.txt");
	return 0;
}
Example #5
0
int main( int argc, char * argv[] )
{
	const char * sql = NULL;
	const char * dbfile = NULL;

	extern char *optarg ;
	int c ;

	while( ( c = getopt ( argc, argv, "s:f:v" )) != EOF ) {
		switch ( c ) {
			case 's':
				sql = optarg;
				break;
			case 'f':
				dbfile = optarg;
				break;
			default:
				printf( "Usage: %s [-s <ddl>] [-f <dbfile>]\n", argv[0] );
				exit( -1 );
		}
	}

	if( NULL == sql && NULL == dbfile ) {
		printf( "Usage: %s [-s <ddl>] [-f <dbfile>]\n", argv[0] );
		exit( -1 );
	}

	if( NULL != sql ) testsql( sql );
	if( NULL != dbfile ) testfile( dbfile );

	return 0;
}
/**
 * Extracts the nPos command line argument.
 */
LOCAL_D HBufC* GetArgument(TInt nPos)
	{
	HBufC *argv = HBufC::NewLC(User::CommandLineLength());
	TPtr cmd(argv->Des());
	User::CommandLine(cmd);

	TLex arguments(cmd);

	// finds nth parameter 
	while(nPos && !arguments.Eos())
		{
		TPtrC token = arguments.NextToken();
		if(token.Length() > 0)		
			nPos--;
		}

	HBufC* result = NULL;
	if(!arguments.Eos())
		{
		TPtrC testfile(arguments.NextToken());

		if(testfile.Length() > 0)
			result = testfile.AllocL();
		};

	// no parameter found, but must return something so..
	if(!result)
		result = HBufC::NewL(0);

	CleanupStack::PopAndDestroy(argv);

	return result;
	}
Example #7
0
int main(int argc, char **argv) {
    string modelfile(argv[1]);
    string testfile(argv[2]);
    int thres = 10000;
    int analysis = 0;
    if(argc == 4)
    {
        thres = atoi(argv[3]);
    }
    if(argc == 5)
    {
        analysis = atoi(argv[4]);
    }
    printf("building pp dict...\n");
    Paraphrase* pp = new Paraphrase(testfile);
    //pp = new Paraphrase("/Users/gflfof/Desktop/new work/phrase_embedding/PPDB/ppdb-1.0-s-lexical.test");
    //pp = new Paraphrase("/Users/gflfof/Desktop/new work/phrase_embedding/PPDB/ppdb-1.0-s-lexical.wordlist100");
    printf("evaluating...\n");
    //evaluate(modelfile, thres, pp);
    evaluateMRR(modelfile, thres, pp);
    //GetLogLoss(modelfile, thres, pp);
    delete pp;
    pp = NULL;
    return 0;
}
Example #8
0
int loadtexture(char *filename){
	#ifdef EXCESSIVE
	printf("loadtexture(1)\n");
	#endif
	if (!testfile(filename)){
		return 0;
	}
	SDL_Surface *sdlimage;
	sdlimage=NULL;
	sdlimage=IMG_Load(filename);
	if (sdlimage==NULL){
		return 0;
	}
	if (sdlimage->format->BytesPerPixel < 2){
		if (sdlimage!=NULL)SDL_FreeSurface(sdlimage);
		return 0;
	}
	int retval=LoadTransTexture2(sdlimage,0,1);
	if (retval==0){
		if (sdlimage!=NULL)SDL_FreeSurface(sdlimage);
		return 0;
	}
	if (sdlimage!=NULL)SDL_FreeSurface(sdlimage);
	return retval;
}
Example #9
0
bool loadtexture(int a, char *filename, int size=1){
	#ifdef EXCESSIVE
	printf("loadtexture(3)\n");
	#endif
	if (strlen(filename)<1)return false;
	if (!testfile(filename)){
		return false;
	}
	SDL_Surface *sdlimage;
	sdlimage=NULL;
	sdlimage=IMG_Load(filename);
	if (sdlimage==NULL){
		return false;
	}
	if (sdlimage->format->BytesPerPixel < 2){
		if (sdlimage!=NULL)SDL_FreeSurface(sdlimage);
		return false;
	}
	for (int b=0;b<size;b++){
		g_Texture[a][b]=LoadTransTexture2(sdlimage,b,size);
		if (g_Texture[a][b]==0){
			if (sdlimage!=NULL)SDL_FreeSurface(sdlimage);
			return false;
		}
	}
	if (sdlimage!=NULL)SDL_FreeSurface(sdlimage);
	return true;
}
Example #10
0
int
test_fat12()
{
    TSK_FS_INFO *fs;
    TSK_IMG_INFO *img;
    const char *tname = "fat12.dd";
    char fname[512];

    snprintf(fname, 512, "%s/fat12.dd", s_root);
    if ((img = tsk_img_open_sing(fname, (TSK_IMG_TYPE_ENUM) 0, 0)) == NULL) {
        fprintf(stderr, "Error opening %s image\n", tname);
        tsk_error_print(stderr);
        tsk_error_reset();
        return 1;
    }

    if ((fs = tsk_fs_open_img(img, 0, (TSK_FS_TYPE_ENUM) 0)) == NULL) {
        fprintf(stderr, "Error opening %s image\n", tname);
        tsk_error_print(stderr);
        tsk_error_reset();
        return 1;
    }

    if (testfile(fs, 33)) {
        fprintf(stderr, "%s failure\n", tname);
        return 1;
    }

    tsk_fs_close(fs);
    tsk_img_close(img);
    return 0;
}
Example #11
0
int memcard_create(running_machine &machine, int index, int overwrite)
{
    char name[16];

    /* create a name */
    memcard_name(index, name);

    /* if we can't overwrite, fail if the file already exists */
    astring fname(machine.basename(), PATH_SEPARATOR, name);
    if (!overwrite)
    {
        emu_file testfile(machine.options().memcard_directory(), OPEN_FLAG_READ);
        if (testfile.open(fname) == FILERR_NONE)
            return 1;
    }

    /* create a new file */
    emu_file file(machine.options().memcard_directory(), OPEN_FLAG_WRITE | OPEN_FLAG_CREATE | OPEN_FLAG_CREATE_PATHS);
    file_error filerr = file.open(fname);
    if (filerr != FILERR_NONE)
        return 1;

    /* initialize and then save the card */
    if (machine.config().m_memcard_handler)
        (*machine.config().m_memcard_handler)(machine, file, MEMCARD_CREATE);

    /* close the file */
    return 0;
}
/// unit tests
int test() {
	std::ofstream log("flowIterated2_HS_Yosemite.log", std::ios::trunc);
	assert(log.good());
	sout.assign(log);

	// load plugin manager
	PluginManager man(GLOBAL_PLUGIN_DIR, LOCAL_PLUGIN_DIR);

	// start tests
	std::string testfile(TESTDIR "/flowIterated2.wrp");
	std::cout << "Loading parameter file \"" << testfile;
	std::cout << "\"" << std::endl;
	man.loadParameterFile(testfile);
	std::cout << "Executing workflow..." << std::endl;
	FileTool::changeDir(TESTDIR);
	man.runWorkflow();
	std::cout << "Workflow execution finished.\n" << std::endl;

	// get test instances
	FlowComparator<double>* comparator = dynamic_cast<FlowComparator<double>*>(
			man.getInstance("analyzer"));
	assert(comparator);
	std::cout << "mean endpoint error: "
			<< comparator->getMeanEndpointError() << std::endl;
	assert(comparator->getMeanEndpointError() <= 0.1);

	man.reset();
	sout.assign();
	log.close();

	return EXIT_SUCCESS;
}
Example #13
0
status Game::saveGame(string &filename)
{
	if (filename == "") {
		display("Enter a name for your save file (press enter to cancel process):\n");
		getline(cin, filename);
		if (filename == "") {
			display("No data saved.\n");
			return ERROR;
		}
		else {
			ifstream testfile(filename.c_str());
			
			if (! testfile) {
				testfile.close();
				
				saveData(filename);
				display("\nSaved successfully (new file written).\n");
				return OK;
			} else {
				string teststring;
				
				getline(testfile, teststring);
				testfile.close();
				
				if (teststring == "start_save_file") {
					
					stringstream tempstrstr;
					tempstrstr << "\n\"" << filename << "\" already exists as a save file. Would you like to overwrite it?\n 1. Yes\n 0. No\n";
					display(tempstrstr.str());
					
					int selection = getSelection();
					if (selection == 1) {
						saveData(filename);
						display("\nFile overwritten. Saved successfully.\n");
						return OK;
					} else {
						display("\nFile not overwritten. No data saved.\n");
						filename = "";
						return ERROR;
					}
				} else {
					display("\nThat file already exists, and it's not a save file, so it can't be overwritten. No data saved.\n");
					filename = "";
					return ERROR;
				}
			}
		}
	} else {
		saveData(filename);
		
		stringstream output;
		output << "Saved successfully to file \"" << filename << "\".\n";
		display(output.str());
		
		return OK;
	}
}
Example #14
0
int main(){
    Json::Value root;
    std::ifstream testfile("testfile.txt", std::ifstream::binary);
    testfile >> root;
    std::cout << root << std::endl;
    std::cout << root.get("my_plug_ins", "Placeholder")[1];
    std::cout << "Im alive" << std::endl;
    return 0;


}
Example #15
0
int main(int argc,char **argv)
{
    std::cout << "Unicode Escape Regression Tester\n";
    int ch;
    while ((ch = getopt(argc,argv,"r:h")) != -1){
        switch(ch) {
        case 'r':
            testfile(optarg);
            break;
        }
    }


    const char buf[] = {0xef, 0xbe, 0xad, 0x5c};
    check(std::string(buf,1),true);
    check(std::string(buf,2),true);
    check(std::string(buf,3),true);
    check(std::string(buf,4),true);

    /* Runs 16 copies simultaneously... */
    uint32_t max=0xFFFFFFFF;            // 2^32-1
    for(uint64_t prefix=0;prefix<max;prefix+=0x10000000){
        pid_t child = fork();
        if(child==0){
            /* Try all 4-byte sequences in the prefix range...*/
            for(uint32_t k=0;k<=0x0FFFFFFF;k++){
                uint32_t i=prefix+k;
                std::string ugly((char *)&i,4);
                check(ugly,false);
                if((i & 0x00FFFFFF)==0x00FFFFFF){
                    printf("pid=%d prefix=%x i=%x\n",getpid(),(uint32_t)prefix,(uint32_t)i);
                    fflush(stdout);
                }
            }
            exit(0);
        }
        printf("Launched PID %d\n",child);
        fflush(stdout);
    }
    for(int i=0;i<16;i++){
        int s=0;
        pid_t p = wait(&s);
        printf("pid %d finished with exit code %d\n",p,s);
    }
    std::cout << "done\n";
    exit(1);

    /* Generic fuzzing. Try random attempts */
    std::string line;
    while(getline(std::cin,line)){
        std::cout << validateOrEscapeUTF8(line,true) << "\n";
    }
        
}
Example #16
0
int
test_ntfs_fe()
{
    TSK_FS_INFO *fs;
    TSK_IMG_INFO *img;
    const char *tname = "fe_test_1-NTFS";
    char fname[512];

    snprintf(fname, 512, "%s/fe_test_1.img", s_root);
    if ((img = tsk_img_open_sing(fname, (TSK_IMG_TYPE_ENUM) 0, 0)) == NULL) {
        fprintf(stderr, "Error opening %s image\n", tname);
        tsk_error_print(stderr);
        tsk_error_reset();
        return 1;
    }

    if ((fs = tsk_fs_open_img(img, 32256, (TSK_FS_TYPE_ENUM) 0)) == NULL) {
        fprintf(stderr, "Error opening %s image\n", tname);
        tsk_error_print(stderr);
        tsk_error_reset();
        return 1;
    }

    if (testfile(fs, 31)) {
        fprintf(stderr, "%s error (non-resident)\n", tname);
        return 1;
    }

    if (testfile(fs, 32)) {
        fprintf(stderr, "%s error (resident)\n", tname);
        return 1;
    }

    tsk_fs_close(fs);
    tsk_img_close(img);
    return 0;
}
int main(int argc, char** argv)
{
    Beluga_CalibrationDataFile testfile("../matlab/calibration/test.dat");
    Beluga_CalibrationDataFile testOutFile("testOut.dat", CALIB_WRITE);

    if(!testfile.didLoadOK())
    {
        std::cerr << "Failure to load or validate file\n";
        return 1;
    }

    CalibrationData d;
    testfile.getCalibration(&d);
    
    std::cout << calibrationDataToString(d);

    if(!testOutFile.didLoadOK())
    {
        std::cerr << "Failure to load output file\n";
        return 1;
    }

    d.info = std::string("WELL HELLO");
    testOutFile.writeCalibration(d);

    Beluga_CalibrationDataFile testInFile("testOut.dat");
    if(!testInFile.didLoadOK())
    {
        std::cerr << "Failure to load or parse second file\n";
        return 1;
    }

    CalibrationData d2;
    testInFile.getCalibration(&d2);

    std::cout << calibrationDataToString(d2);

    return 0;
}
Example #18
0
int main(int argc, char** argv)
{
    QCoreApplication app(argc, argv);

    QStringList args = app.arguments();
    args.removeFirst(); // ourself

    QString args_quoted = QString("'%1'").arg(args.join("','"));

#ifdef Q_WS_QWS
    {
        // for QWS we expect tests to be run as the QWS server
        QString qws = args.takeLast();
        if (qws != "-qws") {
            fail(QString("Expected test to be run with `-qws', but it wasn't; args: %1").arg(args_quoted));
        }
    }
#endif

    if (args.count() != 1) {
        fail(QString("These arguments are not what I expected: %1").arg(args_quoted));
    }

    QString test = args.at(0);

    QFileInfo testfile(test);
    if (!testfile.exists()) {
        fail(QString("File %1 does not exist (my working directory is: %2, my args are: %3)")
            .arg(test)
            .arg(QDir::currentPath())
            .arg(args_quoted)
        );
    }

    pass(args_quoted);
}
Example #19
0
int main(int argc, char *argv[])
{
	FILE *fpin, *fpout;
	struct nodo *raiz;
	struct tablaCod *tabla;
	struct header h;
	u16 v;
	int verbose=0, benchmark=0;
	double tiempo;


	printf("hufc v. 0.2.2 Compress/Expand files using Huffman coding\n");

	if (argc < 2)
	{
		printf("To see help, write: %s -h\n", argv[0]);
		exit(0);
	}

	// Mostrar la ayuda?
	if (ExistArg("-h", argc, argv))
	{
		sintaxis(argv[0]);
		exit(0);
	}

	// Modo verbose?
	if (ExistArg("-v", argc, argv))
		verbose=1;

	// Medir el tiempo de crc o de checksum?
	if (ExistArg("-b", argc, argv))
		benchmark=1;

	if ((fpin=fopen(argv[1], "rb")) == NULL)
	{
		perror("fopen: input file");
		exit(1);
	}

	// Leer crc o checksum?
	if (ExistArg("-r", argc, argv))
	{
		if (!isHuf(fpin))
			printf("%s: not in huf format!\n", argv[1]);
		else
		{
			switch (leerDetErr(fpin))
			{
				case USE_CCITT:
					printf("%s: crc = 0x%04X\n", argv[1], readcrcsum(fpin));
					break;

				case USE_CHECKSUM:
					printf("%s: checksum = 0x%04X\n", argv[1], readcrcsum(fpin));
					break;

				default:
					printf("%s: error detection not used\n", argv[1]);
			}
		}

		fclose(fpin);
		exit(0);
	}

	// Testear el fichero?
	if (ExistArg("-t", argc, argv))
	{
		if (!isHuf(fpin))
			printf("%s: not in huf format!\n", argv[1]);
		else
		{
			switch (testfile(fpin, leerDetErr(fpin)))
			{
				case FILE_OK:
					printf("%s: seems to be ok\n", argv[1]);
					break;

				case FILE_CORRUPTED:
					printf("%s: file corrupted!\n", argv[1]);
					break;

				default:
					printf("%s: error detection not used\n", argv[1]);
			}
		}

		fclose(fpin);
		exit(0);
	}

	// Descomprimir
	if (ExistArg("-x", argc, argv))
	{
		if (!isHuf(fpin))
		{
			printf("%s: not in huf format!\n", argv[1]);
			fclose(fpin);
			exit(0);
		}

		// Testeamos el fichero
		h.deterr=leerDetErr(fpin);
		if (testfile(fpin, h.deterr) == FILE_CORRUPTED)
		{
			printf("%s: file corrupted!\n", argv[1]);
			fclose(fpin);
			exit(0);
		}

		raiz=leerCabecera(fpin, &h);
		fpout=fopen(h.filename, "wb");
		if (fpout == NULL)
		{
			perror("fopen: output file");
			exit(1);
		}

		// Le damos al fichero sus permisos originales
		chmod(h.filename, h.permisos);
		descomprimir(fpin, fpout, raiz, &h, verbose);
	}

	// Comprimir
	else
	{
		if (verbose)
		{
			printf("Scanning file (this may take a while)... ");
			fflush(stdout);
		}
		calcularFreq(fpin, &raiz);
		if (verbose)
			printf("Done\n");
		raiz=crearArbolHuffman(raiz);
		tabla=crearTablaCod(raiz);

		if (ExistArg("-ccitt", argc, argv))
			h.deterr=USE_CCITT;
		else if (ExistArg("-sum", argc, argv))
			h.deterr=USE_CHECKSUM;
		else
			h.deterr=DONT_USE_ERR_DET;

		setHeaderPermisos(&h, argv[1]);
		setHeaderFileName(&h, argv[1]);
		fpout=fopen(getCompressedFileName(&h), "w+b");
		if (fpout == NULL)
		{
			perror("fopen: output file");
			exit(1);
		}

		escribirCabecera(fpout, &h, raiz);
		h.padding_bits=comprimir(fpin, fpout, tabla, verbose);
		escribirPadding(fpout, h.padding_bits);
		borrarTablaCod(tabla);
		fflush(fpout);

		switch (h.deterr)
		{
			case USE_CCITT:
				if (benchmark)
					tiempo=gettime();

				v=calculacrc(fpout);

				if (verbose)
					printf("   crc = 0x%04X\n", v);

				if (benchmark)
					printf("crc time: %g s\n", gettime()-tiempo);

				writecrcsum(fpout, v);
				break;

			case USE_CHECKSUM:
				if (benchmark)
					tiempo=gettime();

				v=calculasum(fpout, COMPRIMIR);

				if (verbose)
					printf("   checksum = 0x%04X\n", v);

				if (benchmark)
					printf("checksum time: %g s\n", gettime()-tiempo);

				writecrcsum(fpout, v);
				break;

			default:
				if (verbose)
					printf("\n");
		}
	}

	borrarArbolHuffman(raiz);
	fclose(fpin);
	fclose(fpout);

	return 0;
}
/// unit tests
int test() {
	std::ofstream log("flowIterated4_SpatialPW.log", std::ios::trunc);
	std::ofstream csv("flowIterated4_energy.csv", std::ios::trunc);
	assert(log.good());
	sout.assign(log);

	// load plugin manager
	PluginManager man(GLOBAL_PLUGIN_DIR, LOCAL_PLUGIN_DIR);

	// start tests
	std::string testfile(TESTDIR "/flowIterated4.wrp");
	std::cout << "Loading parameter file \"" << testfile;
	std::cout << "\"" << std::endl;
	man.loadParameterFile(testfile);

	// get test instances
	SimpleIterator<double>* iterator =
			dynamic_cast<SimpleIterator<double>*>(
					man.getInstance("iterator"));
	assert(iterator);

	RelaxingIterator<double>* relaxator =
			dynamic_cast<RelaxingIterator<double>*>(
					man.getInstance("relaxator"));
	assert(relaxator);

	IteratorHelper<double>* helper =
			dynamic_cast<IteratorHelper<double>*>(
					man.getInstance("helper"));
	assert(helper);

	IteratorHelper<double>* relaxinghelper =
			dynamic_cast<IteratorHelper<double>*>(
					man.getInstance("relaxinghelper"));
	assert(helper);

	SpatialPW<double>* spatialPW = dynamic_cast<SpatialPW<double>*>(
			man.getInstance("spatialterm_learned"));
	assert(spatialPW);

	FlowComparator<double>* analyzer = dynamic_cast<FlowComparator<double>*>(
			man.getInstance("analyzer"));
	assert(analyzer);

	std::string curDir = FileTool::getCurrentDir();
	FileTool::changeDir(TESTDIR);

	// make sure that ground truth is available
	ParameteredObject* gen = man.getInstance("seqgen");
	assert(gen);
	gen->run();

	// connect analyzer input to current flow
	analyzer->result.disconnect();
	analyzer->result.connect(helper->flow);

	// write ground truth
	analyzer->groundtruth().get_append('c').save_cimg(
			(curDir+"/" PREFIX "_gt.cimg").c_str(),true);

	relaxator->prepareIterations();
	printHeader(csv);

	std::cout << "Iteration: " << std::flush;
	bool contOut, contIn;
	do {
		relaxator->prepareStep();
		double cur = relaxator->getCur();
		printInfos(csv,curDir,cur,helper,relaxinghelper,spatialPW,analyzer);
		iterator->prepareIterations();
		do {
			contIn = iterator->singleStep();
			printInfos(csv,curDir,cur,helper,relaxinghelper,spatialPW,analyzer);
			std::cout << helper->countAll() << " " << std::flush;
		} while (contIn);
		iterator->finishIterations();
		contOut = relaxator->finishStep();
	} while (contOut);
	relaxator->finishIterations();

	std::cout << "done" << std::endl;

	double meanEndpointError = analyzer->getMeanEndpointError();

	man.reset();

	sout.assign(std::cout, log);
	sout << "\tmean endpoint error: " << meanEndpointError << std::endl;
	sout.assign();
	csv.close();
	log.close();

	// check results
	if (meanEndpointError >= 0.15) {
		std::cout << "Mean endpoint error too bad!" << std::endl;
		return EXIT_FAILURE;
	}

	return EXIT_SUCCESS;
}
Example #21
0
int
runcmd(char *cmd) {
    static char argv0[BUFSIZE];
    const char *argv[EXEC_MAX_ARG_NUM + 1];
    char *t;
    int argc, token, ret, p[2];
again:
    argc = 0;
    while (1) {
        switch (token = gettoken(&cmd, &t)) {
        case 'w':
            if (argc == EXEC_MAX_ARG_NUM) {
                printf("sh error: too many arguments\n");
                return -1;
            }
            argv[argc ++] = t;
            break;
        case '<':
            if (gettoken(&cmd, &t) != 'w') {
                printf("sh error: syntax error: < not followed by word\n");
                return -1;
            }
            if ((ret = reopen(0, t, O_RDONLY)) != 0) {
                return ret;
            }
            break;
        case '>':
            if (gettoken(&cmd, &t) != 'w') {
                printf("sh error: syntax error: > not followed by word\n");
                return -1;
            }
            if ((ret = reopen(1, t, O_RDWR | O_TRUNC | O_CREAT)) != 0) {
                return ret;
            }
            break;
        case '|':
            if ((ret = pipe(p)) != 0) {
                return ret;
            }
            if ((ret = fork()) == 0) {
                close(0);
                if ((ret = dup2(p[0], 0)) < 0) {
                    return ret;
                }
                close(p[0]), close(p[1]);
                goto again;
            }
            else {
                if (ret < 0) {
                    return ret;
                }
                close(1);
                if ((ret = dup2(p[1], 1)) < 0) {
                    return ret;
                }
                close(p[0]), close(p[1]);
                goto runit;
            }
            break;
        case 0:
            goto runit;
        case ';':
            if ((ret = fork()) == 0) {
                goto runit;
            }
            else {
                if (ret < 0) {
                    return ret;
                }
                waitpid(ret, NULL);
                goto again;
            }
            break;
        default:
            printf("sh error: bad return %d from gettoken\n", token);
            return -1;
        }
    }

runit:
    if (argc == 0) {
        return 0;
    }
    else if (strcmp(argv[0], "cd") == 0) {
        if (argc != 2) {
            return -1;
        }
        strcpy(shcwd, argv[1]);
        return 0;
    }
    if ((ret = testfile(argv[0])) != 0) {
        if (ret != -E_NOENT) {
            return ret;
        }
        snprintf(argv0, sizeof(argv0), "/bin/%s", argv[0]);
        argv[0] = argv0;
    }
    argv[argc] = NULL;
    return __exec(NULL, argv, g_envp);
}
Example #22
0
bool hdfutil::FileExists (const std::string & filename) {
    std::ifstream testfile(filename.c_str());
    return testfile.is_open();
}
Example #23
0
void MediaScannerThread::run()
{
	if (multiPass)
	{
		qDebug() << "MediaScannerThread: multi non-single pass selected";
		multiPass = false;
		for (int i=0;i<multiPassFileNames.count();i++)
		{
			QString fullPath = multiPassFileNames.at(i);
			TagLib::FileRef testfile(fullPath.toStdString().c_str());
			if (!testfile.isNull())
			{
				ID3Tag *tmpTag = 0;
				if (!tmpTag)
				{
					tmpTag = new ID3Tag();
					tmpTag->valid = false;
				}
				if (TagLib::MPEG::File *file = dynamic_cast<TagLib::MPEG::File *>( testfile.file()))
				{
					if (file->ID3v2Tag(false))
					{
						//Check to see if there are images in the tag
						#ifdef Q_OS_WIN32 //Currently this only works in the windows version of taglib??
						if (!file->ID3v2Tag()->frameListMap()["APIC"].isEmpty())
						{
							TagLib::ID3v2::FrameList frameList = file->ID3v2Tag()->frameListMap()["APIC"];
							TagLib::ID3v2::FrameList::Iterator iter;
							for( iter = frameList.begin(); iter != frameList.end(); ++iter )
							{
								TagLib::ID3v2::AttachedPictureFrame::Type t = (((TagLib::ID3v2::AttachedPictureFrame*)*iter))->type();
								if (t == TagLib::ID3v2::AttachedPictureFrame::Type::FrontCover)
								{
									TagLib::ByteVector pic = (((TagLib::ID3v2::AttachedPictureFrame*)*iter))->picture();
									QImage tmpPicture;
									tmpPicture.loadFromData((uchar*)pic.data(),pic.size());
									tmpTag->frontcover = tmpPicture;
								}
								else if (t == TagLib::ID3v2::AttachedPictureFrame::Type::BackCover)
								{
									TagLib::ByteVector pic = (((TagLib::ID3v2::AttachedPictureFrame*)*iter))->picture();
									QImage tmpPicture;
									tmpPicture.loadFromData((uchar*)pic.data(),pic.size());
									tmpTag->backcover = tmpPicture;
								}
								
							}
						}
						#endif //Q_OS_WIN32
						TagLib::Tag *tag = testfile.tag();
						if (!tmpTag->valid)
						{
							tmpTag->artist = tag->artist().toCString();
							tmpTag->title = tag->title().toCString();
							tmpTag->filename = fullPath;
							emit tagReceived("",0,tmpTag);
						}	
					}

				}
				else
				{
					TagLib::Tag *tag = testfile.tag();
					if (!tmpTag->valid)
					{
						tmpTag->artist = tag->artist().toCString();
						tmpTag->title = tag->title().toCString();
						tmpTag->filename = fullPath;
						emit tagReceived("",0,tmpTag);
					}
				}
			}
			else
			{
				qDebug() << "MediaScannerThread: Invalid File in multipass" << fullPath;
				int stop = 1;
			}
			QThread::msleep(50);
		}
		multiPassFileNames.clear();
		
	}
	else if (singlePass)
	{
		qDebug() << "MediaScannerThread: Non-multi single pass selected";
		singlePass = false;
		QString fullPath = singlePassFileName;
		TagLib::FileRef testfile(fullPath.toStdString().c_str());
		if (!testfile.isNull())
		{
			TagLib::Tag *tag = testfile.tag();
		//if (tag)
		//{
			ID3Tag *tmpTag = 0;
			if (!tmpTag)
			{
				tmpTag = new ID3Tag();
				tmpTag->valid = false;
			}
			if (!tmpTag->valid)
			{
				tmpTag->artist = tag->artist().toCString();
				tmpTag->title = tag->title().toCString();
				tmpTag->filename = fullPath;
				emit tagReceived("",0,tmpTag);
			}
			//ID3Tag *tmpTag = new ID3Tag();
		}
		else
		{
			qDebug() << "MediaScannerThread: Invalid File in singlepass" << fullPath;
		}

	}
	else
	{
		qDebug() << "MediaScannerThread: Non-multi non-single pass selected";
		bool firstScan = true;
		int delay=0;
		bool anyValid = true;
		while (anyValid)
		{
			anyValid = false;
			if (firstScan)
			{
				delay=0;
				//firstScan = false;
			}
			else
			{	
				delay=20;
			}
			for (int i=0;i<m_playLists->count();i++)
			{
				for (int j=0;j<m_playLists->at(i)->size();j++)
				{

					QString fullPath = m_playLists->at(i)->getFileNum(j)->fullPath();
//					qDebug() << fullPath;
					TagLib::FileRef testfile(fullPath.toStdString().c_str());
					if (!testfile.isNull())
					{
						ID3Tag *tmpTag = m_playLists->at(i)->getFileNum(j)->getId3Tag();
						if (!tmpTag)
						{
							tmpTag = new ID3Tag();
							tmpTag->valid = false;
							anyValid = true;
						}
						if (TagLib::MPEG::File *file = dynamic_cast<TagLib::MPEG::File *>( testfile.file()))
						{
							if (file->ID3v2Tag(false))
							{
								//Check to see if there are images in the tag
								#ifdef Q_OS_WIN32 //Currently this only works in the windows version of taglib??
								if (!file->ID3v2Tag()->frameListMap()["APIC"].isEmpty())
								{
									TagLib::ID3v2::FrameList frameList = file->ID3v2Tag()->frameListMap()["APIC"];
									TagLib::ID3v2::FrameList::Iterator iter;
									for( iter = frameList.begin(); iter != frameList.end(); ++iter )
									{
										TagLib::ID3v2::AttachedPictureFrame::Type t = (((TagLib::ID3v2::AttachedPictureFrame*)*iter))->type();
										if (t == TagLib::ID3v2::AttachedPictureFrame::Type::FrontCover)
										{
											TagLib::ByteVector pic = (((TagLib::ID3v2::AttachedPictureFrame*)*iter))->picture();
											QImage tmpPicture;
											tmpPicture.loadFromData((uchar*)pic.data(),pic.size());
											tmpTag->frontcover = tmpPicture;
										}
										else if (t == TagLib::ID3v2::AttachedPictureFrame::Type::BackCover)
										{
											TagLib::ByteVector pic = (((TagLib::ID3v2::AttachedPictureFrame*)*iter))->picture();
											QImage tmpPicture;
											tmpPicture.loadFromData((uchar*)pic.data(),pic.size());
											tmpTag->backcover = tmpPicture;
										}
										
									}
								}
								#endif
								TagLib::Tag *tag = testfile.tag();
								if (!tmpTag->valid)
								{
									tmpTag->artist = tag->artist().toCString();
									tmpTag->title = tag->title().toCString();
									tmpTag->filename = fullPath;
									emit tagReceived(m_playLists->at(i)->title(),j,tmpTag);
								}	
							}
						}
						else
						{
							TagLib::Tag *tag = testfile.tag();
							if (!tmpTag->valid)
							{
								tmpTag->artist = tag->artist().toCString();
								tmpTag->title = tag->title().toCString();
								tmpTag->valid = true;
								tmpTag->filename = fullPath;
								m_playLists->at(i)->setId3(j,tmpTag);
								anyValid = true;
								emit tagReceived(m_playLists->at(i)->title(),j,tmpTag);
							}
							else
							{
								if (tmpTag->filename != fullPath)
								{
									tmpTag->artist = tag->artist().toCString();
									tmpTag->title = tag->title().toCString();
									tmpTag->filename = fullPath;
									tmpTag->valid = true;
									m_playLists->at(i)->setId3(j,tmpTag);
									anyValid = true;
									emit tagReceived(m_playLists->at(i)->title(),j,tmpTag);								
								}
							}
						}
						//ID3Tag *tmpTag = new ID3Tag();
					}
					else
					{
						qDebug() << "MediaScannerThread: Invalid File in standardpass" << fullPath;
					}
					QThread::msleep(delay);
				}
			}
			if (firstScan)
			{
				firstScan = false;
				qDebug() << "Initial scan of id3 tags completed. ";
				if (anyValid)
				{
					qDebug() << "Moving to background  mode...";
				}
				else
				{
					qDebug() << "All files scanned, exiting thread";
				}
			}
			else
			{
				qDebug() << "Secondary id3 scan complete... continuing...";
			}
		}
	}
	/*
	int done = 1;
	return;
	QFile tmpFile("music.conf");
	if (!tmpFile.open(QIODevice::ReadOnly | QIODevice::Text))
	{	
		printf("Error opening configuration file!!!\n");
		return;
	}
	QString musicDir(tmpFile.readLine());
	printf("Music Directory from configuration file: %s\n",musicDir.toStdString().c_str());
	tmpFile.close();
	musicDir = musicDir.mid(0,musicDir.length()-1);
	QDir tmpDir(musicDir);

	tmpDir.setFilter(QDir::Dirs | QDir::NoDotAndDotDot);
	QDir tmpFiles(musicDir);
	tmpFiles.setFilter(QDir::Files | QDir::NoDotAndDotDot);
	QStringList infoList = tmpDir.entryList();
	foreach (QString info,infoList)
	{
		TagLib::FileRef testfile(info.toStdString().c_str());
		TagLib::Tag *tag = testfile.tag();
		ID3Tag *tmpTag = new ID3Tag();
		tmpTag->artist = tag->artist().to8Bit().c_str();
		tmpTag->title = tag->title().to8Bit().c_str();
		//emit tagReceived(tmpTag);		
	}
	bool inLoop = true;
	//while (inLoop)
	//{
		//QThread::
	//	QThread::sleep(1);
		
	//	ID3Tag *tmpTag = new ID3Tag();
		//tmpTag->artist = 
		
	//}
	*/
}
void FriBasedRecommend::Recommend(string checkinDataFileName){
    ifstream testfile(checkinDataFileName);

    char buffer[100];
    int i=0;
    int lastUserId=-1;
    map<int,float> f2fWeightMap;//用户i和用户k的相似度:SIk,i,其中i为当前的userid,<int-k,float-f2fWeight:SIk,i>
    map<int,float> recResult;//针对用户i的推荐结果,其中第一个int表示位置j的id,float表示预测到的评价值
    map<int,float> sortedRec1;//Top-k个推荐结果TOPN1-5
    map<int,float> sortedRec2;//Top-k个推荐结果TOPN2-10
    map<int,float> sortedRec3;//Top-k个推荐结果TOPN3-20

    set<int> locIdSet;//测试集中当前用户已访问过的用户,用于消除测试集中用户多次访问某一位置
    int rightRec[3]={0};//推荐正确的数量
    int allRec[3]={0};//推荐的所有的元素数量
    int rightCase[3]={0};//应该被推荐的数量

    int rightRecOfUser[3] = {0};
    int rightCaseOfUser=0;
    while(true){
        i++;
        //读一行签到记录并解析
        if(testfile.eof()) break;
        testfile.getline(buffer,100);
        string str(buffer);
        vector<std::string> result=split(str);

        if(result.size()!=5){
            break;
        }

        int userid=atoi(result[0].data());
        int locid=atoi(result[4].data());
        Item * user=socialNet->getItemPtrById(userid,ITEMTYPE_USER);
        Item * loc = socialNet->getItemPtrById(locid,ITEMTYPE_LOCATION);

        //解析签到记录完毕

        if(user==NULL||loc==NULL){//如果用户或者位置不存在
            continue;
        }

        if(userid!=lastUserId){//针对于一个新的用户,为其推荐TOP-K的地点
            //先把上一个user的信息打印出来
            
            
            /*
            if (rightCaseOfUser>=TOPN1)
            {
                rightRec[0]+=rightRecOfUser[0];
                rightCase[0] += rightCaseOfUser;
                allRec[0]+=TOPN1;
            }
            if (rightCaseOfUser>=TOPN2)
            {
                rightRec[1]+=rightRecOfUser[1];
                rightCase[1] += rightCaseOfUser;
                allRec[1]+=TOPN2;
            }
            */
            if (rightCaseOfUser>=TOPN3)
            {
                rightRec[0]+=rightRecOfUser[0];
                rightCase[0] += rightCaseOfUser;
                allRec[0]+=TOPN1;

                rightRec[1]+=rightRecOfUser[1];
                rightCase[1] += rightCaseOfUser;
                allRec[1]+=TOPN2;

                rightRec[2]+=rightRecOfUser[2];
                rightCase[2] += rightCaseOfUser;
                allRec[2]+=TOPN3;
            }

            if(allRec[0]!=0){
                if(ISDEBUG){
                    cout<<"top-5:"<<endl;
                    printMap(sortedRec1);
                }

                cout<<" FriendBased精确率rightRec[0]/allRec[0]:"<<rightRec[0]<<"/"<<allRec[0]<<" :"<<(float)rightRec[0]/allRec[0]<<endl;
                cout<<"召回率rightRec[0]/rightCase"<<rightRec[0]<<"/"<<rightCase[0]<<" :"<<(float)rightRec[0]/rightCase[0]<<endl;
                if(ISDEBUG){
                    cout<<"top-10:"<<endl;
                    printMap(sortedRec2);
                }
                cout<<" 精确率rightRec[1]/allRec[1]:"<<rightRec[1]<<"/"<<allRec[1]<<" :"<<(float)rightRec[1]/allRec[1]<<endl;
                cout<<"召回率rightRec[1]/rightCase"<<rightRec[1]<<"/"<<rightCase[1]<<" :"<<(float)rightRec[1]/rightCase[1]<<endl;
                if(ISDEBUG){
                    cout<<"top-20:"<<endl;
                    printMap(sortedRec3);
                }
                cout<<" 精确率rightRec[2]/allRec[2]:"<<rightRec[2]<<"/"<<allRec[2]<<" :"<<(float)rightRec[2]/allRec[2]<<endl;
                cout<<"召回率rightRec[1]/rightCase"<<rightRec[2]<<"/"<<rightCase[2]<<" :"<<(float)rightRec[2]/rightCase[2]<<endl;
            }
            //计算这个新的user的推荐信息
            //首先清除一些东西
            f2fWeightMap.clear();
            recResult.clear();
            sortedRec1.clear();
            sortedRec2.clear();
            sortedRec3.clear();
            locIdSet.clear();
            for (int i=0;i<3;i++)
            {
                rightRecOfUser[i]=0;
            }
            rightCaseOfUser=0;


            //计算每一个用户和其他用户的相似度Wi,k,将结果存放在u2uWeightMap
            calculateSIik(f2fWeightMap,userid);
            if(ISDEBUG){
                cout<<"用户:"<<userid<<endl;
                cout<<"用户-用户权值:(用户,权值)"<<userid<<endl;
                printMap(f2fWeightMap);
            }
            //计算用户对未评价的ITEM的隐含评价,以此作为推荐结果
            calRecResult(recResult,f2fWeightMap,userid);//!!??!!!现在使用的是UCF的推荐函数,不确定可不可以用。
            if(ISDEBUG){
                cout<<"推荐结果:(位置ID,推荐度)"<<userid<<endl;
                printMap(recResult);
            }

            //选择top-k个推荐结果

            sortRecResult(sortedRec1,recResult,TOPN1);
            sortRecResult(sortedRec2,recResult,TOPN2);
            sortRecResult(sortedRec3,recResult,TOPN3);
            if (recResult.size()>20 &&(sortedRec1.size() != TOPN1||sortedRec2.size() != TOPN2||sortedRec3.size() != TOPN3))
            {
                cout<<"sortedRec.size() != TOPN"<<endl;
                int xx;
                cin>>xx;
            }
            //cout<<"排序厚的推荐结果:(位置ID,推荐度)"<<userid<<endl;
            lastUserId=userid;
        }
        //计算精确率和召回率
        //第一步统计推荐正确的数量
        if(sortedRec1.find(locid)!=sortedRec1.end()){

            if(sortedRec1[locid]!=-1){
                rightRecOfUser[0]++;
                sortedRec1[locid]=-1;
            }
        }
        if(sortedRec2.find(locid)!=sortedRec2.end()){
            if(sortedRec2[locid]!=-1){
                rightRecOfUser[1]++;
                sortedRec2[locid]=-1;
            }
        }
        if(sortedRec3.find(locid)!=sortedRec3.end()){
            if(sortedRec3[locid]!=-1){
                rightRecOfUser[2]++;
                sortedRec3[locid]=-1;
            }
        }

        if(locIdSet.find(locid)==locIdSet.end()){
            rightCaseOfUser++;
            locIdSet.insert(locid);
        }
    }
Example #25
0
int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    QFile testfile(QString("testfile"));
    QFile testfile2(QString("test"));

    //test code
    /*QVector<int> b3(1<<28);
    qint64 i=0;
    std::cout<<b3.size()<<std::endl;
    for(;i<(1<<28);i++)
    {
        b3[i]=i;
    }
    std::cout<<b3.at((1<<28)-1)<<std::endl;*/

    char b[]="abcdefghijklm\0nopqrst\xF0\xE4";
    char b3[]="abcdefghijklmn";
    char *b1=new char[100];
    char *b2=new char[1<<28];
    int c[1<<20]={32,33,34};

    if(b2==NULL)
    {
        std::cerr<<"Error alloc memory failed."<<std::endl;
    }

    b2[(1<<28)-1]='a';
    std::cout<<b2[(1<<28)-1]<<std::endl;

    /*if(!testfile.exists())
    {
        system("touch testfile");
    }
    else
    {
        system("rm testfile");
        system("touch testfile");
    }*/

    if(!testfile.open(QIODevice::WriteOnly))
    {
        std::cerr<<"Error: can't open file testfile."<<std::endl;
        return 1;
    }

    //QDataStream mystreamw(&testfile);
    //mystream.setVersion(QDataStream::Qt_4_8);

    //mystream<<b<<'\0'<<c[0]<<c[1]<<c[2]<<b;
    //mystreamw.writeBytes(b,sizeof(b));
    testfile.write(b3,sizeof(b3)-1);
    testfile.write(b3,sizeof(b3)-1);

    testfile.close();


    if(!testfile.open(QIODevice::ReadOnly))
    {
        std::cerr<<"Error: can't open file testfile."<<std::endl;
        return 1;
    }

    //std::cout<<"file size:"<<testfile.size()<<" stringsize:"<<sizeof(b)<<std::endl;
    //QDataStream mystreamr(&testfile);
    //mystreamr>>b1;
    testfile.read(b1,testfile.size());

    testfile.close();

    if(!testfile2.open(QIODevice::ReadOnly))
    {
        std::cerr<<"Error: can't open file test."<<std::endl;
        return 1;
    }

    //QDataStream mystream2r(&testfile);
    //mystream2r>>b2;
    testfile.read(b2,testfile.size());

    testfile2.close();

    std::cout<<b1<<' '<<&(b1[strlen(b1)+1])<<std::endl;
    std::cout<<"success"<<std::endl;
    std::cout<<"not break"<<std::endl;
    
    delete [] b1;
    delete [] b2;

    return a.exec();
}
Example #26
0
int LocalFileMng::savePattern( Song *song , const QString& drumkit_name, int selectedpattern , const QString& patternname, const QString& realpatternname, int mode)
{
	//int mode = 1 save, int mode = 2 save as
	// INSTRUMENT NODE

	Instrument *instr = song->get_instrument_list()->get( 0 );
	assert( instr );

	Pattern *pat = song->get_pattern_list()->get( selectedpattern );

	QString sPatternDir = Preferences::get_instance()->getDataDirectory() + "patterns/" +  drumkit_name;

	INFOLOG( "[savePattern]" + sPatternDir );

	// check if the directory exists
	QDir dir( sPatternDir );
	QDir dirPattern( sPatternDir );
	if ( !dir.exists() ) {
		dir.mkdir( sPatternDir );// create the drumkit directory
	}

	QString sPatternXmlFilename;
	// create the drumkit.xml file
	switch ( mode ){
	case 1: //save
		sPatternXmlFilename = sPatternDir + "/" + QString( patternname + QString( ".h2pattern" ));
		break;
	case 2: //save as
		sPatternXmlFilename = patternname;
		break;
	case 3: //"save" but overwrite a existing pattern. mode 3 disable the last file exist check
		sPatternXmlFilename = sPatternDir + "/" + QString( patternname + QString( ".h2pattern" ));
		break;
	case 4: //tmp pattern needed by undo/redo
		sPatternXmlFilename = patternname;
	default:
		WARNINGLOG( "Pattern Save unknown status");
		break;

	}

	//test if the file exists
	QFile testfile( sPatternXmlFilename );
	if ( testfile.exists() && mode == 1)
		return 1;

	QDomDocument doc;
	QDomProcessingInstruction header = doc.createProcessingInstruction( "xml", "version=\"1.0\" encoding=\"UTF-8\"");
	doc.appendChild( header );

	QDomNode rootNode = doc.createElement( "drumkit_pattern" );
	//LIB_ID just in work to get better usability
	//writeXmlString( &rootNode, "LIB_ID", "in_work" );
	writeXmlString( rootNode, "pattern_for_drumkit", drumkit_name );
	writeXmlString( rootNode, "author", song->get_author() );
	writeXmlString( rootNode, "license", song->get_license() );


	// pattern
	QDomNode patternNode = doc.createElement( "pattern" );
	writeXmlString( patternNode, "pattern_name", realpatternname );

	QString category;
	if ( pat->get_category().isEmpty() )
		category = "No category";
	else
		category = pat->get_category();

	writeXmlString( patternNode, "info", pat->get_info() );
	writeXmlString( patternNode, "category", category  );
	writeXmlString( patternNode, "size", QString("%1").arg( pat->get_length() ) );

	QDomNode noteListNode = doc.createElement( "noteList" );
	const Pattern::notes_t* notes = pat->get_notes();
	FOREACH_NOTE_CST_IT_BEGIN_END(notes,it) {
		Note *pNote = it->second;
		assert( pNote );

		QDomNode noteNode = doc.createElement( "note" );
		writeXmlString( noteNode, "position", QString("%1").arg( pNote->get_position() ) );
		writeXmlString( noteNode, "leadlag", QString("%1").arg( pNote->get_lead_lag() ) );
		writeXmlString( noteNode, "velocity", QString("%1").arg( pNote->get_velocity() ) );
		writeXmlString( noteNode, "pan_L", QString("%1").arg( pNote->get_pan_l() ) );
		writeXmlString( noteNode, "pan_R", QString("%1").arg( pNote->get_pan_r() ) );
		writeXmlString( noteNode, "pitch", QString("%1").arg( pNote->get_pitch() ) );

		writeXmlString( noteNode, "key", pNote->key_to_string() );

		writeXmlString( noteNode, "length", QString("%1").arg( pNote->get_length() ) );
		writeXmlString( noteNode, "instrument", QString("%1").arg( pNote->get_instrument()->get_id() ) );
		noteListNode.appendChild( noteNode );
	}
Example #27
0
int main()
{
    QFile testfile("test.mobi");

    testfile.open(QIODevice::ReadOnly);
    QDataStream inStream(&testfile);

	/* file starts with pdb header, 
	 * 4bytes at 60 should be 'BOOK'
	 * 4bytes at 64 should be 'MOBI'
	 * if file is a valid .mobi
	 */

    //goto pos 60
    if (!testfile.seek(60)) {
		printf("failed to seek to offset 60\n");
		return 0;
	}

	//read 8 bytes
	char * tmpchar = new  char[8];

    if (inStream.readRawData(tmpchar,8) != 8) {
		printf("failed to read 8 bytes\n");
		return 0;
	}
	//check'em
    if (strncmp(tmpchar,"BOOKMOBI",8) == 0)
        printf ( "got MOBI header\n");

	/* position 76 has number of PDB records
	 * records follow straight after
	 * 
	 */
    //goto pos 76

    testfile.seek(76);

    delete tmpchar;

    tmpchar = new  char[2];

    unsigned int records = 0 ;
    
    if (inStream.readRawData(tmpchar,2) == 2) {
        records = bytesToInt(tmpchar,0,2) ;   //needs a batter way to figure it out
        printf ( "mobi records : %d \n", records);
    }

    printf("parsing record0\n");

    //records start at  78 and take up 8*records bytes of data
    //http://wiki.mobileread.com/wiki/PDB#Palm_Database_Format

    testfile.seek(78);

    delete tmpchar;
    tmpchar = new char[8];

    //4b - record offset from start of file
    //1b - record flags
    //3b - record id

	testfile.seek(testfile.pos() + 8*records);
/*    for (int i=0;i<records;i++) {
        printf("record %d\n", i);
        if (inStream.readRawData(tmpchar,8) != 8) {
			printf("file ended prematurely. exiting\n");
			return 0;
		}

		//printbytes(tmpchar,8);

		unsigned int offset = bytesToInt(tmpchar,0,4)  ;   //needs a batter way to figure it out
		int flags = tmpchar2[4];
		unsigned int record_id = bytesToInt(tmpchar,5,2);
            
		printf ( " -- offset : %0x [%d] \n", offset, offset);
		printf ( " -- flags : %0x [%d] \n", flags, flags);
		printf ( " -- record_id : %0x [%d] \n", record_id, record_id);
       
    } 
*/

/* there are 2 bytes of padding after records, skip them */

	testfile.seek(testfile.pos() + 2);

    /* 16 byte palmdoc header starts here, read it */
	delete tmpchar;

	//save this location as reference for later
    qint64 header0pos = testfile.pos();

	
/*	tmpchar = new char[16];
	testresult = inStream.readRawData(tmpchar,16);

    if (testresult == 16) {

		printbytes(tmpchar,16);

        //we don't really need this, just for verification
        printf("compression : %0x \n",bytesToInt(tmpchar,0,2));
        printf("dummy       : %0x (expected 0)\n",bytesToInt(tmpchar,2,2));
        printf("textLength  : %0x \n",bytesToInt(tmpchar,4,4));
        printf("recCount    : %0x \n",bytesToInt(tmpchar,8,2));
        printf("recSize     : %0x (expected 0x1000)\n",bytesToInt(tmpchar,10,2));
        printf("encType     : %0x \n",bytesToInt(tmpchar,12,2));
        printf("unk         : %0x \n",bytesToInt(tmpchar,14,2));
    }
*/


	/* instead of parsing, we just go over it and skip to record #0 that follows */
	testfile.seek(testfile.pos() + 16);

    //go through MOBI header
    //first let's see if we have a header, 4 bytes should be 'MOBI', 16 bytes from beginning of PalmDoc header

	tmpchar = new char[4];
    
    if ((inStream.readRawData(tmpchar,4) == 4) && (strncmp(tmpchar,"MOBI",4) == 0))
        printf("got MOBI header in record 0\n");

    //next up is header length that includes that 'MOBI' signature just read.
    unsigned int mobiHeaderSize  = 0;

    if (inStream.readRawData(tmpchar,4) == 4) {
        mobiHeaderSize = bytesToInt(tmpchar,0,4);
    }

    printf("mobi header size : %d [ %0x ]\n", mobiHeaderSize, mobiHeaderSize);

    printf("EXTH should start at %llx\n", mobiHeaderSize + header0pos + 0x10);  //add 16 bytes for palmdoc header parsed previously

    //check if EXTH record exists

    testfile.seek(header0pos + 0x80) ; //location of EXTH flags in header;
    bool got_exth_header = false;

    if (inStream.readRawData(tmpchar,4) == 4)
    {
//		printbytes(tmpchar,4);

        unsigned int exth_flags = bytesToInt(tmpchar,0,4);

        if ( exth_flags & 0x40)
            got_exth_header = true;
    }

    if (!got_exth_header) {
        printf("EXTH not found, exiting\n");
        return 0;
    }

    printf("EXTH header exists\n");

    //if EXTH header size is not divisible by 4, it has to be padded to a multiple of 4, and then actual data starts.
    int exth_padding = 0;

    if (mobiHeaderSize % 4 )
        exth_padding = 4 - mobiHeaderSize % 4 ;

    printf(" exth padding : %d\n", exth_padding);


    //go through EXTH header, if found (indicated in MOBI header)

    //navigating to start of EXTH
    printf("seeking to exth header\n");
    qint64 exth_pos = header0pos + mobiHeaderSize+0x10;  //first palmdoc entry offset + 16bytes + entire mobi header is where exth starts
    testfile.seek(exth_pos);

    printf("at position %llu [ %llx ]\n", testfile.pos(), testfile.pos());
    /*
    'EXTH'
    4 bytes - length of entire header
    4 bytes - number of records

    < records follow >
    record {
        4 bytes      type
        4 bytes      length of entire record (that is, including 8 bytes for type and length)
        length-8     actual record data
    }

    0-3 bytes padding (in exth_padding)
    */

    delete tmpchar;
    tmpchar = new char [12];


    printf("reading 12 bytes\n");
    if (inStream.readRawData(tmpchar,12) == 12) {
//        printbytes(tmpchar,12);
        if (strncpy(tmpchar,"EXTH",4) == 0)
            printf("got EXTH header\n");
        unsigned int headerlength = bytesToInt(tmpchar,4,4);
        unsigned int exthRecords = bytesToInt(tmpchar,8,4);

        printf("header is %x long \n", headerlength);
        printf("there are %x records \n",exthRecords);

        //go through the EXTH records
        for (unsigned int j=0;j<exthRecords;j++) {
            char * tmprecord = new char [8];
            if (inStream.readRawData(tmprecord,8) ==8 ) {
//                printf("record %d/%d\n",j,exthRecords);
                unsigned int recType = bytesToInt(tmprecord,0,4);
//                printf(" type   : %d\n",recType);
                unsigned int recLength = bytesToInt(tmprecord,4,4);
//                printf(" length : %0x\n", recLength);

                char * recordData = new char[(int)recLength - 8];
                if (inStream.readRawData(recordData,(int)recLength - 8) == (int)recLength -8) {
//                    printf(" data : %s\n", recordData);
//					printbytes(recordData,(int)recLength -8);
                }

                switch (recType) {
                case 100:
                    printf("author : %s \n", recordData);
                    break;
                case 106:
                    printf("date : %s \n", recordData);
                    break;
				case 105:
                    printf("genre : %s \n", recordData);
                    break;
                case 503:
                    printf("title : %s \n", recordData);
                    break;
                case 524:
                    printf("lang : %s \n", recordData);
                    break;
                    
                default:
                    break;
                }
            }
            delete tmprecord;
        }
    }
    return 0;
}