Пример #1
0
bool FileUtils::writeStringToFile(std::string dataStr, const std::string& fullPath)
{
    Data retData;
    retData.copy((unsigned char*)dataStr.c_str(), dataStr.size());

    return writeDataToFile(retData, fullPath);
}
Пример #2
0
void CurlDownload::didReceiveData(void* data, int size)
{
    MutexLocker locker(m_mutex);

    callOnMainThread(MainThreadTask(receivedDataCallback, this, size));

    writeDataToFile(static_cast<const char*>(data), size);
}
Пример #3
0
bool FileUtils::writeStringToFile(const std::string& dataStr, const std::string& fullPath)
{
    Data data;
    data.fastSet((unsigned char*)dataStr.c_str(), dataStr.size());

    bool rv = writeDataToFile(data, fullPath);

    data.fastSet(nullptr, 0);
    return rv;
}
Пример #4
0
void CurlDownload::didReceiveData(void* data, int size)
{
    MutexLocker locker(m_mutex);

    callOnMainThread([this, size] {
        didReceiveDataOfLength(size);
    });

    writeDataToFile(static_cast<const char*>(data), size);
}
Пример #5
0
TestExitStatus SaveGametests::testListingSavefile() {
	Common::SaveFileManager *saveFileMan = g_system->getSavefileManager();
	saveFileMan->clearError();

	// create some savefiles
	const char *savefileName[] = {"tBedSavefileToList.0", "tBedSavefileToList.1", "tBedSavefileToList.2"};
	writeDataToFile("tBedSavefileToList.0", "Save me!");
	writeDataToFile("tBedSavefileToList.1", "Save me!");
	writeDataToFile("tBedSavefileToList.2", "Save me!");

	Common::Error error = saveFileMan->getError();

	if (error != Common::kNoError) {
		// Abort. Some Error in writing files
		Testsuite::logDetailedPrintf("Error while creating savefiles: %s\n", Common::errorToString(error));
		return kTestFailed;
	}

	Common::StringArray savefileList = saveFileMan->listSavefiles("tBedSavefileToList.?");
	if (savefileList.size() == ARRAYSIZE(savefileName)) {
		// Match them exactly
		// As the order of savefileList may be platform specific, match them exhaustively
		for (uint i = 0; i < ARRAYSIZE(savefileName); i++) {
			for (uint j = 0; j < savefileList.size(); j++) {
				if (savefileList[j].equals(savefileName[i])) {
					break;
				}
				if (savefileList.size() == j) {
					// A match for this name not found
					Testsuite::logDetailedPrintf("Listed Names don't match\n");
					return kTestFailed;
				}
			}
		}
		return kTestPassed;
	} else {
		Testsuite::logDetailedPrintf("listing Savefiles failed!\n");
		return kTestFailed;
	}

	return kTestFailed;
}
Пример #6
0
void DataPrinter::update(){
    
    if( !file.isOpen() ){ file.openFile(outFile, wrap::file::Write); }
    
    if( !hasHeader ){
        
        if( file.isOpen() ){
            writeNameHeader( file.ref() );
            writeDataToFile( file.ref() );
            hasHeader = true;
        }
        
    }else{
        
        if( file.isOpen() ){
            writeDataToFile( file.ref() );
        }
    }
    
}
Пример #7
0
void CurlDownload::didReceiveData(void* data, int size)
{
    LockHolder locker(m_mutex);

    RefPtr<CurlDownload> protectedThis(this);

    callOnMainThread([this, size, protectedThis] {
        didReceiveDataOfLength(size);
    });

    writeDataToFile(static_cast<const char*>(data), size);
}
Пример #8
0
TestExitStatus SaveGametests::testSaveLoadState() {
	// create a savefile with "ScummVM Rocks!" written on it
	if (!writeDataToFile("tBedSavefile.0", "ScummVM Rocks!")) {
		Testsuite::logDetailedPrintf("Writing data to savefile failed\n");
		return kTestFailed;
	}

	// Verify if it contains the same data
	if (!readAndVerifyData("tBedSavefile.0", "ScummVM Rocks!")) {
		Testsuite::logDetailedPrintf("Reading data from savefile failed\n");
		return kTestFailed;
	}

	return kTestPassed;
}
Пример #9
0
MainWindow::~MainWindow()
{
    writeDataToFile();

    if(controllerSocket != NULL)
        delete controllerSocket;

    if(socket != NULL)
        delete socket;

    if(media != NULL)
        delete media;

    delete player;
    delete instance;
    delete ui;
}
Пример #10
0
TestExitStatus SaveGametests::testRenamingSavefile() {
	Common::SaveFileManager *saveFileMan = g_system->getSavefileManager();
	// Open a file for renaming
	if (!writeDataToFile("tBedSomeWeirdName.0", "Rename me!")) {
		Testsuite::logDetailedPrintf("Writing data to savefile failed\n");
		return kTestFailed;
	}

	// Rename it
	saveFileMan->renameSavefile("tBedSomeWeirdName.0", "tBedSomeCoolName.0");

	// Verify if it contains the same data
	if (!readAndVerifyData("tBedSomeCoolName.0", "Rename me!")) {
		Testsuite::logDetailedPrintf("Renaming savefile failed\n");
		return kTestFailed;
	}

	return kTestPassed;
}
Пример #11
0
int main(int argc, char **argv) {
    
    if (argc != 3) {
        printf("Usage: plconvert <in file> <out file>\nIf the in file is an XML property list, convert to binary property list in out file. If the in file is a binary property list, convert to XML property list in out file.\n");
    } else {
        CFMutableDataRef plistData = createDataFromFile(argv[1]);
        if (!plistData) {
            printf("Unable to create data from file name: %s", argv[1]);
        } else {
            CFPropertyListFormat fmt;
            CFErrorRef err;
            CFPropertyListRef plist = CFPropertyListCreateWithData(kCFAllocatorSystemDefault, (CFDataRef)plistData, 0, &fmt, &err);
            if (!plist) {
                logIt(CFSTR("Unable to create property list from data: %@"), err);
            } else {
                logIt(CFSTR("Property list contents:\n%@"), plist);
                if (fmt == kCFPropertyListBinaryFormat_v1_0) {
                    logIt(CFSTR("Converting to XML property list at: %s"), argv[2]);
                    fmt = kCFPropertyListXMLFormat_v1_0;
                } else if (fmt == kCFPropertyListXMLFormat_v1_0) {
                    logIt(CFSTR("Converting to binary property list at: %s"), argv[2]);
                    fmt = kCFPropertyListBinaryFormat_v1_0;
                } else {
                    logIt(CFSTR("Unknown property list format! Not converting output format."));
                }
                
                CFDataRef outputData = CFPropertyListCreateData(kCFAllocatorSystemDefault, plist, fmt, 0, &err);
                if (!outputData) {
                    logIt(CFSTR("Unable to write property list to data: %@"), err);
                } else {
                    bool success = writeDataToFile(outputData, argv[2]);
                    if (!success) {
                        logIt(CFSTR("Unable to write data to file"));
                    }
                    CFRelease(outputData);
                }
                CFRelease(plist);
            }
            CFRelease(plistData);
        }
    }
}
Пример #12
0
//Takes any array (including single value pointers) and writes it to the file.
//Returns the number of indexes written to the file.
int FileIO::writeData(int dataLength, int arrayLength, ...){

if (dataLength<=0||arrayLength<=0){
   return 0;
}

va_list ap;
const char* dataBytes;
va_start(ap, arrayLength);

   dataBytes = va_arg(ap, const char*);

va_end(ap);

if (!(writeDataToFile(dataBytes, dataLength * arrayLength))){
   return 0;
}
   dataBytes=dataBytes+dataLength;//I forgot to change the variable. Derp.
   return 1;
//return arrayLength;
}
Пример #13
0
TestExitStatus SaveGametests::testRemovingSavefile() {
	Common::SaveFileManager *saveFileMan = g_system->getSavefileManager();

	// Create a dummy savefile
	if (!writeDataToFile("tBedSavefileToRemove.0", "Dummy Savefile!")) {
		Testsuite::logDetailedPrintf("Writing data to savefile failed\n");
		return kTestFailed;
	}

	// Remove it
	saveFileMan->removeSavefile("tBedSavefileToRemove.0");

	// Try opening it Now
	Common::InSaveFile *loadFile = saveFileMan->openForLoading("saveFile.0");
	if (loadFile) {
		// Removing failed
		Testsuite::logDetailedPrintf("Removing savefile failed\n");
		return kTestFailed;
	}

	return kTestPassed;
}
Пример #14
0
void TestUnicodePath::onEnter()
{
    FileUtilsDemo::onEnter();
    auto s = Director::getInstance()->getWinSize();
    auto util = FileUtils::getInstance();
    
    int x = s.width/2,
    y = s.height/5;
    Label* label = nullptr;
    
    std::string dir = "中文路径/";
    std::string filename = "测试文件.test";

    std::string act;
    auto getMsg = [&act](bool b, const std::string& path)-> std::string
    {
        char msg[512];
        snprintf((char *)msg, 512, "%s for %s path: \"%s\"", b ? "success" : "failed", act.c_str(), path.c_str());
        return std::string(msg);
    };
    
    // Check whether unicode dir should be create or not
    std::string dirPath = util->getWritablePath() + dir;
    if (!util->isDirectoryExist(dirPath))
    {
        util->createDirectory(dirPath);
    }
    
    act = "create";
    bool isExist = util->isDirectoryExist(dirPath);
    label = Label::createWithSystemFont(getMsg(isExist, dirPath), "", 12, Size(s.width, 0));
    label->setPosition(x, y * 4);
    this->addChild(label);
    
    if (isExist)
    {
        // Check whether unicode file should be create or not
        std::string filePath = dirPath + filename;
        if (! util->isFileExist(filePath))
        {
            std::string writeDataStr = " 测试字符串.";
            Data writeData;
            writeData.copy((unsigned char *)writeDataStr.c_str(), writeDataStr.size());
            util->writeDataToFile(writeData, filePath);
        }
        
        isExist = util->isFileExist(filePath);
        label = Label::createWithSystemFont(getMsg(isExist, filePath), "", 12, Size(s.width, 0));
        label->setPosition(x, y * 3);
        this->addChild(label);
        
        act = "remove";
        if (isExist)
        {
            // read file content and log it
            unsigned char* buffer = nullptr;
            Data readData = util->getDataFromFile(filePath);
            buffer = (unsigned char*)malloc(sizeof(unsigned char) * (readData.getSize() + 1));
            memcpy(buffer, readData.getBytes(), readData.getSize());
            buffer[readData.getSize()] = '\0';
            // vc can't treat unicode string correctly, don't use unicode string in code
            log("The content of file from writable path: %s", buffer);
            free(buffer);
            
            // remove test file
            label = Label::createWithSystemFont(getMsg(util->removeFile(filePath), filePath), "", 12, Size(s.width, 0));
            label->setPosition(x, y * 2);
            this->addChild(label);
        }
        
        // remove test dir
        label = Label::createWithSystemFont(getMsg(util->removeDirectory(dirPath), dirPath), "", 12, Size(s.width, 0));
        label->setPosition(x, y * 1);
        this->addChild(label);
    }
}
Пример #15
0
int main(int argc, char** argv)
{
    loadConfig(CONFIG_FILE);

    if (!hasSimMatrix)
    {
	readData(&A, nMovies, nUsers, trainSet);
    
#ifdef DEBUG
	readArr(A, nMovies, nUsers);
#endif

	omp_set_num_threads(MAX_THREAD);


    
	/*        CHUAN HOA       */
	printf("\n\nChuan hoa: ");
#pragma omp parallel for
	for (int i=0; i<nMovies; i++)
	{
	    float sum = 0; //Tong cac rating
	    int t = 0;     //So rating
	    
#pragma omp parallel for schedule(static, 3) reduction(+:sum)
	    for (int j=0; j<nUsers; j++)
	    {
		if (A[i][j] != 0)
		{
		    sum += A[i][j];
		    t++;
		}
	    }

	    float rowMean = sum/t;
	    
#pragma omp parallel for schedule(static, 3)
	    for (int j=0; j<nUsers; j++)
	    {
		if (A[i][j] != 0)
		    A[i][j] -= rowMean;
	    }

	    printf("\n%d/%d", i, nMovies);
	}


#ifdef DEBUG
	puts("");
	printf("\nSTANDARDIZED MARTRIX: \n");
	readArr(A, nMovies, nUsers);
	puts("");
#endif



	/*         TINH SIMILARY MATRIX           */
	printf("\n\nTinh sim: ");    sim = calloc(nMovies, sizeof(float*));
	for (int i=0; i<nMovies; i++)
	    sim[i] = calloc(nMovies, sizeof(float*));

#pragma omp parallel for schedule(static, 3)
	for (int i=0; i<nMovies; i++)
	{
#pragma omp parallel for schedule(static, 3)
	    for (int j=i+1; j<nMovies; j++)
	    {
		sim[i][j] = cosine(A[i], A[j], nUsers);
	    }
	    printf("\n%d/%d: ", i, nMovies);
	}

	for (int i=0; i<nMovies; i++)
	    for (int j=0; j<=i; j++)
	    {
		if (i == j)
		    sim[i][j] = 1;
		else
		    sim[i][j] = sim[j][i];
	    }

	writeDataToFile(sim, nMovies, nMovies, pathToSimMatrix);
	freeArr(A, nMovies);
    }
    else
    {
	int tmp;
	loadArrFromFile(&sim, &tmp, &tmp, pathToSimMatrix);
    }
    
#ifdef DEBUG
    puts("");
    printf("\nSIMILARY MATRIX: \n");
    readArr(sim, nMovies, nMovies);
    puts("");
#endif


    
    /*          TINH RATING            */
    Rating *B;
    int len;
    readTestData(&B, &len, testSet);
    readData(&A, nMovies, nUsers, trainSet);
    float *AVG;
    computeAvgRating(&AVG, A, nMovies, nUsers);

    
#pragma omp parallel for schedule(static, 3)
    for (int i=0; i<len; i++)
    {
	ratePredict(&B[i], A, sim);
	//Neu khong the du doan thi dua ve gia tri trung binh
	if (B[i].P == 0)
	    B[i].P = AVG[B[i].uID];
    }

    writeResultToFile(B, len, "data/result.txt");

    float T = 0;
    float temp;
#pragma omp parallel for schedule(static, 3) reduction(+:T) private(temp)
    for (int i=0; i<len; i++)
    {
	temp = B[i].R - B[i].P;
	T += temp * temp;
    }

    printf("\n %f", sqrt(T/len));
    
#ifdef DEBUG
    puts("");
    printf("RESULT: ");
    for (int i=0; i<len; i++)
    {
	printf("\nmID: %5d    uID: %5d     Real: %6.2fd      Predict: %6.2f", B[i].mID, B[i].uID, B[i].R, B[i].P);
	usleep(1000000);
    }
    puts("");
#endif

    


    free(AVG);
    freeArr(sim, nMovies);
    free(B);
    freeArr(A, nMovies);
    puts("");
    return 0;
}
int main(int argc, char *argv[])
{
	int opt;
	char* appName = NULL;
	char* resourceID = NULL;
	char* payloadBuffer = NULL;
	char* fileName = NULL;
	unsigned char* writeBuffer = NULL;
	eOperationMode opMode = modeInvalid;
	unsigned int user_no = 0, seat_no = 0;
	unsigned int ldbid = 0xFF;    // default value
	unsigned int doHexdump = 0;

	printf("\n");
   /// debug log and trace (DLT) setup
   DLT_REGISTER_APP("Ptool","persistence client library tools");


	while ((opt = getopt(argc, argv, "hVo:a:u:s:r:-l:p:f:H")) != -1)
	{
		switch (opt)
		{
		   case 'o':      // option
		      if(strcmp(optarg, "readkey")  == 0)
            {
		         opMode = modeReadKey;
            }
		      else if(strcmp(optarg, "writekey")  == 0)
            {
		         opMode = modeWriteKey;
            }
		      else if(strcmp(optarg, "deletekey")  == 0)
            {
		         opMode = modeDeleteKey;
            }
		      else if(strcmp(optarg, "getkeysize")  == 0)
            {
		         opMode = modeGetKeySize;
            }
		      else
		      {
		         printf("Unsupported Unsupported mode: %s\"\n\"", optarg);
		         printSynopsis();
	            exit(EXIT_FAILURE);
		      }
		      break;
		   case 'a':   // application name
		   {
		      size_t len = strlen(optarg);
            appName = malloc(len + 1);
            if(appName != NULL)
            {
               memset(appName, 0, len + 1);
               strncpy(appName, optarg, len);
            }
		   }
		      break;
		   case 'r':   // resource ID
         {
            size_t len = strlen(optarg);
            resourceID = malloc(len + 1);
            if(resourceID != NULL)
            {
               memset(resourceID, 0, len + 1);
               strncpy(resourceID, optarg, len);
            }
         }
            break;
         case 'p':   // payload to write
         {
            size_t len = strlen(optarg);
            payloadBuffer = malloc(len + 1);
            if(payloadBuffer != NULL)
            {
               memset(payloadBuffer, 0, len + 1);
               strncpy(payloadBuffer, optarg, len);
            }
         }
            break;
         case 'f':   // filename to read data from, write data to
         {
            size_t len = strlen(optarg);
            fileName = malloc(len + 1);
            if(fileName != NULL)
            {
               memset(fileName, 0, len + 1);
               strncpy(fileName, optarg, len);
            }
         }
            break;
		   case 'u':   // user number
		      user_no = (unsigned int)atoi(optarg);
		      break;
		   case 's':   // seat number
            seat_no = (unsigned int)atoi(optarg);
            break;
		   case 'l':
		      ldbid = (unsigned int)strtol(optarg, NULL, 16);
		      break;
		   case 'H':   // hexdump of data
		      doHexdump = 1;
		      break;
	   	case 'h':   // help
	   	   printSynopsis();
	         break;
	   	case 'v':   // version
	   		printf("Version: %s\n", PCLT_VERSION);
	         break;
	   	default: /* '?' */
	      	printSynopsis();
	         exit(EXIT_FAILURE);
	         break;
		}
   }


	if(appName != NULL && resourceID != NULL)
	{
	   printf("Application name: %s\n", appName);

	   int shutdownReg = PCL_SHUTDOWN_TYPE_NONE;
	   (void)pclInitLibrary(appName, shutdownReg);

      switch(opMode)
      {
         case modeReadKey:
         {
            unsigned char* buffer = NULL;
            int keysize = pclKeyGetSize(ldbid, resourceID, user_no, seat_no);

            if(keysize > 0)
            {
               buffer = malloc((size_t)keysize + 1);
               if(buffer != NULL)
               {
                  memset(buffer, 0, (size_t)(keysize + 1));
                  readKey(resourceID, user_no, seat_no, ldbid, doHexdump, buffer, keysize);

                  if(fileName != NULL)
                     (void)writeDataToFile(fileName, buffer, keysize);

                  free(buffer);
               }
            }
            else
            {
               printf("readkey: key is empty: %d\n", keysize);
            }
            break;
         }
         case modeWriteKey:
            if(fileName != NULL)    // if filename is available, read data from file
            {
               writeBuffer = readDataFromFile(fileName);
            }
            else
            {
               writeBuffer = (unsigned char*)payloadBuffer;    // use data from payload parameter
            }

            if(writeBuffer != NULL)
            {
               writeKey(resourceID, user_no, seat_no, ldbid, writeBuffer, doHexdump);
            }
            else
            {
               printf("No Data to write to key\n");
            }
            break;
         case modeDeleteKey:
            deletekey(resourceID, user_no, seat_no, ldbid);
            break;
         case modeGetKeySize:
            getkeysize(resourceID, user_no, seat_no, ldbid);
            break;
         default:
            printSynopsis();
            break;
      }

      if(appName != NULL)
         free(appName);

      if(resourceID != NULL)
         free(resourceID);

      if(writeBuffer != NULL)
         free(writeBuffer);

      if(fileName != NULL)
         free(fileName);


      pclLifecycleSet(PCL_SHUTDOWN);

      pclDeinitLibrary();
	}
	else
	{
	   printf("Invalid application name or resourceID\n");
	   exit(EXIT_FAILURE);
	}

   // unregister debug log and trace
   DLT_UNREGISTER_APP();
   dlt_free();

   printf("\n");

   return 0;
}
Пример #17
0
int main(int argc, char** argv)
{
    loadConfig(CONFIG_FILE);

    indexMovie();

    if (!hasSimMatrix)
    {
	readData(&A, nMovies, nUsers, trainSet);
    
#ifdef DEBUG
	readArr(A, nMovies, nUsers);
#endif



    
	/*        CHUAN HOA       */
	printf("\n\nChuan hoa: ");
	for (int i=0; i<nMovies; i++)
	{
	    float sum = 0; //Tong cac rating
	    int t = 0;     //So rating
	    
	    for (int j=0; j<nUsers; j++)
	    {
		if (A[i][j] != 0)
		{
		    sum += A[i][j];
		    t++;
		}
	    }

	    float rowMean = 0;
	    if (t!=0)
		rowMean = sum/t;
	    
	    for (int j=0; j<nUsers; j++)
	    {
		if (A[i][j] != 0)
		    A[i][j] -= rowMean;
	    }

	    printf("\r\%-10d/%10d", i, nMovies);
	}


#ifdef DEBUG
	puts("");
	printf("\nSTANDARDIZED MARTRIX: \n");
	readArr(A, nMovies, nUsers);
	puts("");
#endif



	/*         TINH SIMILARY MATRIX           */
	printf("\n\nTinh sim: ");    sim = calloc(nMovies, sizeof(float*));
	for (int i=0; i<nMovies; i++)
	    sim[i] = calloc(nMovies, sizeof(float*));

	for (int i=0; i<nMovies; i++)
	{
	    for (int j=i+1; j<nMovies; j++)
	    {
		sim[i][j] = cosine(A[i], A[j], nUsers);
	    }
	    printf("\r%-10d/%10d", i, nMovies);
	}

	for (int i=0; i<nMovies; i++)
	    for (int j=0; j<=i; j++)
	    {
		if (i == j)
		    sim[i][j] = 1;
		else
		    sim[i][j] = sim[j][i];
	    }

	writeDataToFile(sim, nMovies, nMovies, pathToSimMatrix);
	freeArr(A, nMovies);
    }