ImageSourceDir::ImageSourceDir(const char* directory, bool _keepFrames)
{
	curImage = NULL;

	m_keepFrames = _keepFrames;

	strncpy (m_DirSpec, directory, strlen(directory)+1);

	countFiles();
	setCurrentImage(0);
}
Example #2
0
FileModel::FileModel(QObject *parent)
   : MAbstractItemModel(parent),
     numFiles(-1),
     entryList(),
     buckets(),
     dateBuckets()
{
    // Load sorting settings
    selectedBuckets = Settings::getSortMode();

    numFiles = countFiles();
    insertRows(0, numFiles, QModelIndex());
}
Example #3
0
void countFiles(std::wstring dir, PKGItem *base, std::map<RPKGEntry *, PKGItem*>& itemMap)
{
    for (int i = 0; i < base->childCount; i++)
    {
        if (base->childs[i].dataType == 3)
            countFiles(dir + fromASCII(base->childs[i].name) + L"/", &base->childs[i], itemMap);
        else
        {
            RPKGEntry *e = new RPKGEntry;
            e->name = dir + fromASCII(base->childs[i].name);
            itemMap[e] = &base->childs[i];
        }
    }
}
Example #4
0
static void countFiles(lab_header *head, DIR *dir, const char *dirname, int additionalLen) {
	struct dirent *dirfile;
	while ((dirfile = readdir(dir))) {
		if (!strcmp(dirfile->d_name, ".") || !strcmp(dirfile->d_name, ".."))
			continue;

		if (dirfile->d_type == S_IFDIR) {
			char *d = appendPath(dirfile->d_name, dirname);
			DIR *subdir = opendir(d);
			countFiles(head, subdir, d, additionalLen + strlen(dirfile->d_name) + 1);
			free(d);
			closedir(subdir);
		} else {
			++head->num_entries;
			head->string_table_size += strlen(dirfile->d_name) + 1 + additionalLen;
		}
	}
}
void AttributesAndDateChangerThread::countFiles(QString path) const
{
    WinFileInfoPtrList* filesInDirectory=WinFileInfo::listFiles(path);

    for(int i=0; i<filesInDirectory->count(); i++)
    {
        const WinFileInfo& fi=*filesInDirectory->at(i);
        if(isProcessableDir(fi))
        {
            dirCounter_++;
            countFiles(fi.filePath());
        }
        if(fi.isFile())
            fileCounter_++;
    }

    delete filesInDirectory;
}
Example #6
0
int pkg2rpkg(const std::string& inputFile, const std::string& outputFile, Rangers::RPKGCompression compression)
{
    ifstream pkgfile(inputFile.c_str(), ios::binary | ios::in);
    std::map<RPKGEntry*, PKGItem*> itemMap;
    PKGItem *root = loadPKG(pkgfile);
    if (root->childCount != 1)
    {
        std::cout << "Incorrect input file" << endl;
        return -1;
    }
    countFiles(L"", root, itemMap);

    //FIXME: OH SHI~
    std::vector<RPKGEntry> files;
    std::vector<PKGItem> pkgfiles;
    for (std::map<RPKGEntry*, PKGItem*>::iterator i = itemMap.begin(); i != itemMap.end(); i++)
    {
        files.push_back(*(i->first));
        pkgfiles.push_back(*(i->second));
    }

    int c = itemMap.size();

    uint32_t headerSize = calculateRPKGHeaderSize(files);
    ofstream outfile(outputFile.c_str(), ios::binary | ios::out);
    //FIXME: Better way to fill file
    for (int i = 0; i < headerSize + 8; i++)
        outfile.put(0);

    for (int i = 0; i < files.size(); i++)
    {
        wcout << files[i].name << endl;
        unsigned char *data = extractFile(pkgfiles[i], pkgfile);
        appendRPKGFile(outfile, files[i], (const char*)data, pkgfiles[i].size, compression);
        delete data;
    }
    outfile.seekp(0, ios_base::beg);
    writeRPKGHeader(outfile, files);

    cleanup(root);
    delete root;
    outfile.close();
    pkgfile.close();
}
Example #7
0
  void run() {
    emitStarted();

    QStringList l;
    for( KURL::List::const_iterator it = urls.begin();
	 it != urls.end(); ++it ) {
      const KURL& url = *it;

      if( !url.isLocalFile() ) {
	kdDebug() << "(K3bDirSizeJob) no remote support." << endl;
	emitFinished( false );
	return;
      }

      l.append( url.path() );
    }

    emitFinished( countFiles( l, QString() ) );
  }
Example #8
0
/*
Функция подготавливает список файлов для копирования и подсчитивает их колличество. Содержимое
каталога строится в алфавитном порядке. (можно изменить с помощью переменной filesSort)
При работе функции возможно возбуждение исключения CopyExcepion. При обработки символической ссылки
в список копирования будет добавлен путь к файлу на который указывает эта ссылка
*/
int CopyJob::prepareCopy(int index, int level, const QString& sName, QString destDir, CopyInfoList& files)
{
  QFileInfo sourceInfo(sName);
  qint64 countFiles(0);
  
  CopyExcepion::throwIf(breakCurrentWork, UserTerminate, "User terminate");
  
  if ( !destDir.isEmpty() && !destDir.endsWith(QLatin1Char('/')) ) destDir += QLatin1Char('/');
  
  CopyExcepion::throwIf(!sourceInfo.exists(), SourceNotExists, sourceInfo.absoluteFilePath());
  
  if ( sourceInfo.isSymLink() )
    sourceInfo.setFile(sourceInfo.symLinkTarget());
  
  CopyInfo copyInfo;
  
  if ( sourceInfo.isFile() ){
    copyInfo.fill(sourceInfo.fileName(), sourceInfo.absoluteDir().absolutePath() + QLatin1Char('/'),
                  destDir, CopyInfo::FILE, sourceInfo.size(), index, level);
    files.append(copyInfo);
    countFiles++;
  }
  else 
    if ( sourceInfo.isDir() ){
      QDir sourceDir(sourceInfo.filePath());
          
      copyInfo.fill(sourceDir.dirName(), "", destDir, CopyInfo::DIR, 0, index, level);
      files.append(copyInfo);
      countFiles++;

      QFileInfoList filesInDir = sourceDir.entryInfoList(filesFilter, filesSort);
    
      for ( int i = 0; i < filesInDir.size(); i++ ){
        countFiles += prepareCopy(index, level + 1, filesInDir.at(i).absoluteFilePath(), 
                                  destDir + sourceDir.dirName(), files);
      }
    }
    else
      throw CopyExcepion(UnknownFileType, "Unknown file type");
    
  return countFiles;
}
Example #9
0
static void generalStreamReg(HRSstream_t s, void *tf)
{
  s->type = HRS_GENERALSTREAM;

  s->gs = (generalStream_s *) HRSmalloc(sizeof(generalStream_s), 
				       "generalStreamReg");
  s->bs = NULL;
  s->ms = NULL;
  
  if (strcmp(s->streamName, "sfstdin") == 0 || 
      (strcmp(s->streamName, "stdin") == 0)) {
    s->gs->numFileNames = 0;
    s->gs->numFilesinStream = 1;  /* count standard in stream as one file */
    s->gs->fileNames = NULL;
    s->gs->sio = 1;  /* standard in stream */
  }
  else if (isDir(s->streamName)) {
    s->gs->numFileNames = countFiles(s->streamName);
    s->gs->fileNames = (char **) HRSmalloc(sizeof(char *)*s->gs->numFileNames,
					  "generalStreamReg");
    getFileNames(s->streamName, s->gs->fileNames, 0);
    s->gs->numFilesinStream = s->gs->numFileNames;
    s->gs->sio = 0;
  }
  else { /* single file stream */
    s->gs->numFileNames = 1;
    s->gs->fileNames = (char **) HRSmalloc(sizeof(char *)*s->gs->numFileNames,
				    "generalStreamReg");
    s->gs->fileNames[0] = (char *) HRSmalloc(strlen(s->streamName)+1, 
					     "generalStreamReg");

    strcpy(s->gs->fileNames[0], s->streamName);
    checkStreamFile(s->gs->fileNames[0], 0);
    s->gs->numFilesinStream = s->gs->numFileNames;
    s->gs->sio = 0;
  }
   
  s->gs->count = 0;
  s->gs->translate = (int (*)(char, void *, Sfio_t *, char *))tf;
  s->gs->filter = NULL;

}
Example #10
0
static void binaryStreamReg(HRSstream_t s,int physicalSize, void *tf)
{
  s->type = HRS_BINARYSTREAM;

  s->bs = (binaryStream_s *) HRSmalloc(sizeof(binaryStream_s), 
				      "binaryStreamReg");
  s->gs = NULL;
  s->ms = NULL;

  s->bs->physicalSize = physicalSize;
  s->bs->temp = (char *) HRSmalloc(physicalSize, "binaryStreamReg");

  if (strcmp(s->streamName, "sfstdin") == 0 || 
      (strcmp(s->streamName, "stdin") == 0)) {
    s->bs->numFileNames = 0;
    s->bs->numFilesinStream = 1;  /* count standard in stream as one file */
    s->bs->fileNames = NULL;
    s->bs->sio = 1;  /* standard in stream */
  }
  else if (isDir(s->streamName)) {
    s->bs->numFileNames = countFiles(s->streamName);
    s->bs->fileNames = (char **) HRSmalloc(sizeof(char *)*s->bs->numFileNames,
				    "binaryStreamReg");
    getFileNames(s->streamName, s->bs->fileNames, physicalSize);
    s->bs->numFilesinStream = s->bs->numFileNames;
    s->bs->sio = 0;
  }
  else { /* single file stream */
    s->bs->numFileNames = 1;
    s->bs->fileNames = (char **) HRSmalloc(sizeof(char *), "binaryStreamReg");
    s->bs->fileNames[0] = (char *) HRSmalloc(strlen(s->streamName)+1, 
					    "binaryStreamReg");
    strcpy(s->bs->fileNames[0], s->streamName);
    checkStreamFile(s->bs->fileNames[0], physicalSize);
    s->bs->numFilesinStream = s->bs->numFileNames;
    s->bs->sio = 0;
  }
   
  s->bs->count = 0;
  s->bs->translate = (int (*)(char, void *, char *, char *))tf;
  s->bs->filter = NULL;
}
Example #11
0
bool Corpus::loadRawCorpus( string directory) {
	DIR* dir = opendir( directory.c_str());
	if( dir == 0) {
		debug( "error: directory don't exist when loading corpus\n");
	}
	struct dirent* entry = readdir( dir); // read directory.
	newsgroupN = 0;
	while( entry) {
		if( entry->d_type == DT_DIR && entry->d_name[0] != '.') { // is newsgroup directory.
			debug( "loading corpus group: %s\n", entry->d_name);
			Mapper::newsgroupID[string(entry->d_name)] = newsgroupN;
			Mapper::newsgroupIDInv[newsgroupN] = string(entry->d_name);
			newsgroupN++;
		}
		entry = readdir(dir);
	}
	closedir(dir);
	documents = new Document**[newsgroupN];
	D = new int[newsgroupN];
	int groupi = 0;
	for( map<string,int>::iterator it = Mapper::newsgroupID.begin();
		it != Mapper::newsgroupID.end(); it++, groupi++) {
		string sub_directory = directory+string((*it).first)+"/";
		D[groupi] = countFiles(sub_directory);
		documents[groupi] = new Document*[D[groupi]];
		int filei = 0;
		DIR* subdir = opendir( sub_directory.c_str());
		while( (entry = readdir(subdir))) {
			if( entry->d_type == DT_DIR || entry->d_name[0] == '.') continue;
			((documents[groupi])[filei]) = new Document();
			((documents[groupi])[filei])->name = entry->d_name;
			string file_path = sub_directory+entry->d_name;
			((documents[groupi])[filei])->parseDocument(fopen(file_path.c_str(), "r"));
			((documents[groupi])[filei])->newsgroupId = groupi;
			filei++;
		}
		closedir(subdir);
	}
	return true;
}
Example #12
0
bool K3b::DirSizeJob::run()
{
    d->totalSize = 0;
    d->totalFiles = 0;
    d->totalDirs = 0;
    d->totalSymlinks = 0;

    QStringList l;
    for( QList<QUrl>::const_iterator it = d->urls.constBegin();
         it != d->urls.constEnd(); ++it ) {
        const QUrl& url = *it;

        if( !url.isLocalFile() ) {
            qDebug() << "(K3b::DirSizeJob) no remote support.";
            return false;
        }

        l.append( url.toLocalFile() );
    }

    return countFiles( l, QString() );
}
Example #13
0
static int countFiles(char *dirName)
{
	DIR *dirp, *dirp2;
	struct dirent *dfile;
	char filename[MAX_FILE_LENGTH];
	int count = 0;

	dirp = opendir(dirName);

	while ((dfile = readdir(dirp)))
	{
		if (dfile->d_name[0] == '.')
		{
			continue;
		}

		sprintf(filename, "%s/%s", dirName, dfile->d_name);

		dirp2 = opendir(filename);

		if (dirp2)
		{
			closedir(dirp2);

			count += countFiles(filename);
		}

		else
		{
			count++;
		}
	}

	closedir(dirp);

	return count;
}
void AttributesAndDateChangerThread::run()
{        
    emit(processMessage(tr("Counting files...")));
    for(int i=0; i<files_->count(); i++)
    {
        const WinFileInfo& fi=*files_->at(i);
        if(isProcessableDir(fi))
        {
            dirCounter_++;
            countFiles(fi.filePath());
        }
        else if(fi.isFile())
            fileCounter_++;
    }

    sumOfFilesAndDirectories_=fileCounter_+dirCounter_;
    emit(fileRangeMessage(0,sumOfFilesAndDirectories_));
    processTimer_.start();

    for(int i=0; i<files_->count(); i++)
    {
        const WinFileInfo& fi=*files_->at(i);        
        if(isProcessableDir(fi))
        {
            processFileOrDirectory(fi);
            if(properties_.processSubFolders_)
                processSubDirectory(fi);
        }
        else if(fi.isFile())
            processFileOrDirectory(fi);
    }

    emit(operationFinished(this));

    quit();
}
Example #15
0
int main(int argc, char *argv[])
{
	int i;
	int32_t length;
	char versionName[5];
	FILE *versionFile;

	if (argc == 3)
	{
		if (strcmpignorecase(argv[1], "-test") == 0)
		{
			testPak(argv[2]);

			exit(0);
		}
	}

	else if (argc < 3)
	{
		printf("Usage   : pak <directory names> <outputname>\n");
		printf("Example : pak data music gfx sound font edgar.pak\n");

		exit(1);
	}

	pak = fopen(argv[argc - 1], "wb");

	totalFiles = 0;

	for (i=1;i<argc-1;i++)
	{
		totalFiles += countFiles(argv[i]);
	}

	totalFiles++;

	printf("Will compress %d files\n", totalFiles);

	printf("Compressing 00%%...\r");

	fileData = malloc(totalFiles * sizeof(FileData));

	if (fileData == NULL)
	{
		printf("Failed to create File Data\n");

		exit(1);
	}

	atexit(cleanup);

	snprintf(versionName, sizeof(versionName), "%0.2f", VERSION);

	versionFile = fopen(versionName, "wb");

	fprintf(versionFile, "%s", versionName);

	fclose(versionFile);

	for (i=1;i<argc-1;i++)
	{
		recurseDirectory(argv[i]);
	}

	compressFile(versionName, NULL);

	remove(versionName);

	length = ftell(pak);

	for (i=0;i<totalFiles;i++)
	{
		if (fileData[i].fileSize == 0)
		{
			break;
		}

		fileData[i].offset = SWAP32(fileData[i].offset);
		fileData[i].compressedSize = SWAP32(fileData[i].compressedSize);
		fileData[i].fileSize = SWAP32(fileData[i].fileSize);

		fwrite(&fileData[i], sizeof(FileData), 1, pak);
	}

	length = SWAP32(length);
	totalFiles = SWAP32(totalFiles);

	fwrite(&length, sizeof(int32_t), 1, pak);
	fwrite(&totalFiles, sizeof(int32_t), 1, pak);

	fclose(pak);

	printf("Compressing 100%%\nCompleted\n");

	return 0;
}
void process()
{
    switch (buff_obj[0]) {
        case 'V':
            writeString((char *)"{VER:008}");
            return;

        case 'S':
            if (buff_value[0]=='E') writeString((char *)"{SYS:echo}");
/*            else if (buff_value[0]=='H')
            {
                uint8_t i,itemCount;
                
                itemCount=countFiles(false);
                //if (file_from_wifi!=0)
                {
                    writeString((char *)"{WIFI:");
                    writeInt(file_from_wifi,3);
                    put('/');
                    writeInt(itemCount,3);
                    put('}');
                }
            }*/
            else if (buff_value[0]=='L')
            {
                uint8_t i;
                uint8_t itemCount;
                
                if ( card.isFileOpen() ) {
                    writeString((char *)"{SYS:BUSY}");
                    return;
                }
				
				//card.initsd();
				//card.getWorkDirName();

                itemCount = countFiles(true);
				
				if (itemCount==0)
				{
					card.initsd();
					card.setroot();
					itemCount = countFiles(true);
				}
				
                for (i=0;i<itemCount;i++)
                {
                    ListFile(i,itemCount);
                }

                if (itemCount==0)
                {
                    if (card.cardOK) i=101;
					else i=102;
                    writeString((char *)"{ERR:");
                    writeInt(i,3);
                    put('}');
                }
                else writeString((char *)"{SYS:OK}");
            }
            else if (buff_value[0]=='I')
            {
                int16_t t;
                                
				writeString((char *)"{T0:");
				t=degHotend(0);
				if (t>999) t=999;
				writeInt(t,3);
				put('/');
				t=degTargetHotend(0);
				writeInt(t,3);
				put('}');
				
				writeString((char *)"{T1:");
				t=degHotend(1);
				if (t>999) t=999;
				writeInt(t,3);
				put('/');
				t=degTargetHotend(1);
				writeInt(t,3);
				put('}');
				
				writeString((char *)"{TP:");
				t=degBed();
				if (t>999) t=999;
				writeInt(t,3);
				put('/');
				t=degTargetBed();
				writeInt(t,3);
				put('}');
            }
            else if (buff_value[0]=='F')
            {
                /*if (buff_value[1]=='X')
                {
                    eeprom::setEepromInt64(eeprom_offsets::FILAMENT_TRIP, eeprom::getEepromInt64(eeprom_offsets::FILAMENT_LIFETIME, 0));
                    eeprom::setEepromInt64(eeprom_offsets::FILAMENT_TRIP + sizeof(int64_t), eeprom::getEepromInt64(eeprom_offsets::FILAMENT_LIFETIME + sizeof(int64_t), 0));
                }*/
                
                writeString((char *)"{TU:");
                
                uint16_t total_hours;
                uint8_t total_minutes;
                //eeprom::getBuildTime(&total_hours, &total_minutes);
				total_hours=0;
				total_minutes=0;
                writeInt(total_hours,5);
                put('.');
                writeInt(total_minutes,2);
                put('/');
                
                uint8_t build_hours;
                uint8_t build_minutes;
                //host::getPrintTime(build_hours, build_minutes);
				build_hours=0;
				build_minutes=0;
                writeInt(build_hours,3);
                put('.');
                writeInt(build_minutes,2);
                put('/');
                
                uint32_t filamentUsedA,filamentUsedB,filamentUsed;
                char str[11];
                //filamentUsedA=stepperAxisStepsToMM(eeprom::getEepromInt64(eeprom_offsets::FILAMENT_LIFETIME, 0),                  A_AXIS);
                //filamentUsedB=stepperAxisStepsToMM(eeprom::getEepromInt64(eeprom_offsets::FILAMENT_LIFETIME + sizeof(int64_t),0), B_AXIS);
                //filamentUsed=filamentUsedA+filamentUsedB;
				filamentUsed=0;
                itoa(filamentUsed,str,10);
                writeString((char *)str);
                put('/');
                
                //filamentUsedA -= stepperAxisStepsToMM(eeprom::getEepromInt64(eeprom_offsets::FILAMENT_TRIP, 0),                  A_AXIS);
                //filamentUsedB -= stepperAxisStepsToMM(eeprom::getEepromInt64(eeprom_offsets::FILAMENT_TRIP + sizeof(int64_t),0), B_AXIS);
                //filamentUsed=filamentUsedA+filamentUsedB;
				filamentUsed=0;
                itoa(filamentUsed,str,10);
                writeString((char *)str);
                put('}');
            }
            else if (buff_value[0]=='R' && 
                buff_value[1]=='E' &&
                buff_value[2]=='S' &&
                buff_value[3]=='E' &&
                buff_value[4]=='T')
            {
                //Motherboard::getBoard().reset(true);
				
            }
/*
            else if (buff_value[0]=='S')
            {
                writeString((char *)"{SYS:P");
                uint8_t i = command::pauseState();
                writeInt(i,3);
                put('/');
                put('H');
                i=host::getHostState();
                writeInt(i,3);
                put('}');
            }
            break;
            */
		
        case 'C':
            if (buff_value[0]=='P')
            {
                uint16_t t;
                
                t=atoi((const char*)buff_value+1);
                
                if (t<0 || t>150) return;
                setTargetBed(t);
            }
            else if (buff_value[0]=='T')
            {
                int16_t t;
                
                t=atoi((const char*)buff_value+2);
                if (t<0 || t>280) return;
                
                if (buff_value[1] == '0')
                {
                    setTargetHotend(t,0);
                }
                else
                {
                    setTargetHotend(t,1);
                }
            }
            else if (buff_value[0]=='S')
            {
                int16_t t;
                uint8_t i;
                
                t=atoi((const char*)buff_value+1);
                
                if (t<1) t=1;
                else if (t>50) t=50;
                
                feedmultiply=t*10;
            }
            break;
            
        case 'P':
            uint8_t i;
            if (buff_value[0]=='H')
            {
            	enquecommand_P(PSTR("G28"));
            }
            else if (buff_value[0]=='C')
            {
                //host::startOnboardBuild(utility::TOOLHEAD_CALIBRATE);
            }
            else if (buff_value[0]=='X')
            {
				extern bool cancel_heatup;
                writeString((char *)"{SYS:CANCELING}");
				//card.pauseSDPrint();
				//disable_heater();
				card.sdprinting = false;
				card.closefile();
				quickStop();
				if(SD_FINISHED_STEPPERRELEASE)
				{
					enquecommand_P(PSTR(SD_FINISHED_RELEASECOMMAND));
				}
				autotempShutdown();
				cancel_heatup = true;
				writeString((char *)"{SYS:STARTED}");
				writeString((char *)"{U:RG1R180180120P0L1S0D0O1E1H0C0X1Y1Z1A2B2N3M0}");
				
            }
            else if (buff_value[0]=='P')
            {
                writeString((char *)"{SYS:PAUSE}");
                card.pauseSDPrint();
                writeString((char *)"{SYS:PAUSED}");
            }
            else if (buff_value[0]=='R')
            {
                writeString((char *)"{SYS:RESUME}");
                card.startFileprint();
                writeString((char *)"{SYS:RESUMED}");
            }
            else if (buff_value[0]=='Z')
            {
                /*i=(buff_value[1]-'0')*100 + (buff_value[2]-'0')*10 + (buff_value[3]-'0');
                float pauseAtZPos = i;
                command::pauseAtZPos(stepperAxisMMToSteps(pauseAtZPos, Z_AXIS));*/
            }
            else
            {
                i=(buff_value[0]-'0')*100 + (buff_value[1]-'0')*10 + (buff_value[2]-'0');
                card.getfilename(i);
				if (card.filenameIsDir)
				{
					writeString((char *)"{SYS:DIR}");
					card.chdir(card.filename);
				}
				else 
				{
					char cmd[30];
					char* c;
					
					writeString((char *)"{PRINTFILE:");
					if (card.longFilename[0]!=0) writeString(card.longFilename);
					else writeString(card.filename);
					put('}');
					
					sprintf_P(cmd, PSTR("M23 %s"), card.filename);
					for(c = &cmd[4]; *c; c++)
					*c = tolower(*c);
					enquecommand(cmd);
					enquecommand_P(PSTR("M24"));
				}
            }
            break;

        case 'B':
            PrintingStatus();
            break;

/*
        case 'J':
            switch (buff_value[0])
            {
                case 'S':
                    BOARD_STATUS_SET(Motherboard::STATUS_MANUAL_MODE);
                    jog_speed=atoi((const char*)buff_value+1);
                    break;
                    
                case 'E':
                    steppers::enableAxes(0xff, false);
                    BOARD_STATUS_CLEAR(Motherboard::STATUS_MANUAL_MODE);
                    break;
                    
                case 'X':
                case 'Y':
                case 'Z':
                case 'A':
                case 'B':
                    steppers::abort();
                    uint8_t dummy;
                    Point position = steppers::getStepperPosition(&dummy);
                    
                    int32_t t;
                    t=atoi((const char*)buff_value+1);

                    if (buff_value[0]<='B') position[buff_value[0]-'A'+3] += (t<<4);
                    else position[buff_value[0]-'X'] += (t<<4);
                    
                    steppers::setTargetNew(position, jog_speed, 0, 0);
                    break;
            }
            break;
*/
/*
        case 'H':
        	if (buff_value[0]=='R')
        	{
        		extern uint32_t homePosition[PROFILES_HOME_POSITIONS_STORED];

        		writeString((char *)"{H:R");
        		eeprom_read_block(homePosition, (void *)eeprom_offsets::AXIS_HOME_POSITIONS_STEPS, PROFILES_HOME_POSITIONS_STORED * sizeof(uint32_t));
        		writeInt(homePosition[0],5);
        		put('/');
        		writeInt(homePosition[1],5);
        		put('/');
        		writeInt(homePosition[2],5);
        		put('/');
        		writeInt((int32_t)(eeprom::getEeprom32(eeprom_offsets::TOOLHEAD_OFFSET_SETTINGS, 0)),5);
        		put('/');
        		writeInt((int32_t)(eeprom::getEeprom32(eeprom_offsets::TOOLHEAD_OFFSET_SETTINGS + sizeof(int32_t), 0)),5);
        		put('}');
        	}
        	else if (buff_value[0]=='W')
        	{
        		extern uint32_t homePosition[PROFILES_HOME_POSITIONS_STORED];
        		int32_t offset[2],t;
        		uint8_t axis;
        		axis=buff_value[1]-'X';
        		if (axis>=0 && axis<=2)
        		{
        			homePosition[axis]=atoi((const char*)buff_value+2);
        			cli();
					eeprom_write_block((void *)&homePosition[axis],
					   (void*)(eeprom_offsets::AXIS_HOME_POSITIONS_STEPS + sizeof(uint32_t) * axis) ,
					   sizeof(uint32_t));
					sei();
        		}

        		axis=buff_value[1]-'x';
        		if (axis>=0 && axis<=1)
        		{
        			t=atoi((const char*)buff_value+2);

                    int32_t offset[2];
                    bool    smallOffsets;

                    offset[0]  = (int32_t)(eeprom::getEeprom32(eeprom_offsets::TOOLHEAD_OFFSET_SETTINGS, 0));
                    offset[1]  = (int32_t)(eeprom::getEeprom32(eeprom_offsets::TOOLHEAD_OFFSET_SETTINGS + sizeof(int32_t), 0));
                    smallOffsets = abs(offset[0]) < ((int32_t)stepperAxisStepsPerMM(0) << 2);

                    int32_t delta = stepperAxisMMToSteps((float)(t - 7) * 0.1f, axis);
                    if ( !smallOffsets ) delta = -delta;

                    int32_t new_offset = offset[axis] + delta;
                    eeprom_write_block((uint8_t *)&new_offset,
                           (uint8_t *)eeprom_offsets::TOOLHEAD_OFFSET_SETTINGS + axis * sizeof(int32_t),
                           sizeof(int32_t));
        		}
        	}
        	break;
*/
/*
        case 'U':
            if (buff_value[0]=='R')
            {
            	int temp;

                writeString((char *)"{U:RG");
                if (eeprom::getEeprom8(eeprom_offsets::OVERRIDE_GCODE_TEMP, 0) != 0) put('1');
                else put('0');

                put('R');
                temp=eeprom::getEeprom16(eeprom_offsets::PREHEAT_SETTINGS + preheat_eeprom_offsets::PREHEAT_LEFT_OFFSET, DEFAULT_PREHEAT_TEMP);
                writeInt(temp,3);
                //put('/');
                temp=eeprom::getEeprom16(eeprom_offsets::PREHEAT_SETTINGS + preheat_eeprom_offsets::PREHEAT_RIGHT_OFFSET, DEFAULT_PREHEAT_TEMP);
                writeInt(temp,3);
                //put('/');
                temp=eeprom::getEeprom16(eeprom_offsets::PREHEAT_SETTINGS + preheat_eeprom_offsets::PREHEAT_PLATFORM_OFFSET, DEFAULT_PREHEAT_TEMP);
                writeInt(temp,3);

                put('P');
                if (eeprom::hasHBP() != 0) put('1');
                else put('0');
                
                put('L');
                if (eeprom::getEeprom8(eeprom_offsets::ACCELERATION_SETTINGS + acceleration_eeprom_offsets::ACCELERATION_ACTIVE, 0x01) != 0) put('1');
                else put('0');
                
                put('S');
                if (eeprom::getEeprom8(eeprom_offsets::COOL_PLAT, 0) != 0) put('1');
                else put('0');
                
                put('D');
                if (eeprom::getEeprom8(eeprom_offsets::DITTO_PRINT_ENABLED, 0) != 0) put('1');
                else put('0');
                
                put('O');
                if (eeprom::getEeprom8(eeprom_offsets::TOOLHEAD_OFFSET_SYSTEM,
                                       DEFAULT_TOOLHEAD_OFFSET_SYSTEM) != 0) put('1');
                else put('0');
                
                put('E');
                if (eeprom::getEeprom8(eeprom_offsets::EXTRUDER_HOLD,
                                       DEFAULT_EXTRUDER_HOLD) != 0) put('1');
                else put('0');
                
                put('H');
                if (eeprom::getEeprom8(eeprom_offsets::HEAT_DURING_PAUSE, DEFAULT_HEAT_DURING_PAUSE) != 0) put('1');
                else put('0');
                
                put('C');
                if (eeprom::getEeprom8(eeprom_offsets::SD_USE_CRC, DEFAULT_SD_USE_CRC) != 0) put('1');
                else put('0');
                
                put('X');
                put ('0' + eeprom::getEeprom8(eeprom_offsets::STEPPER_X_CURRENT, 0));
                
                put('Y');
                put ('0' + eeprom::getEeprom8(eeprom_offsets::STEPPER_Y_CURRENT, 0));
                
                put('Z');
                put ('0' + eeprom::getEeprom8(eeprom_offsets::STEPPER_Z_CURRENT, 0));
                
                put('A');
                put ('0' + eeprom::getEeprom8(eeprom_offsets::STEPPER_A_CURRENT, 0));
                
                put('B');
                put ('0' + eeprom::getEeprom8(eeprom_offsets::STEPPER_B_CURRENT, 0));

                put('N');
                put ('0' + eeprom::getEeprom8(eeprom_offsets::LANGUAGE, 0));

                put('M');
                put ('0' + eeprom::getEeprom8(eeprom_offsets::WIFI_SD, 0));
                
                put('}');
            }
            else if (buff_value[0]=='W')
            {
                uint8_t *c;
                uint8_t cmd=0;
                
                c=buff_value;
                while (*++c!=0)
                {
                    if (*c<='9' && *c>='0')
                    {
                        uint8_t value;
                        value = *c - '0';
                        
                        switch (cmd)
                        {
                            case 'G':
                                eeprom_write_byte((uint8_t *)eeprom_offsets::OVERRIDE_GCODE_TEMP,value);
                                break;
                                
                            case 'P':
                                eeprom_write_byte((uint8_t*)eeprom_offsets::HBP_PRESENT, value);
                                break;
                                
                            case 'L':
                                eeprom_write_byte((uint8_t*)eeprom_offsets::ACCELERATION_SETTINGS +
                                                  acceleration_eeprom_offsets::ACCELERATION_ACTIVE,
                                                  value);
                                break;
                                
                            case 'S':
                                eeprom_write_byte((uint8_t*)eeprom_offsets::COOL_PLAT, value);
                                break;
                                
                            case 'D':
                                eeprom_write_byte((uint8_t*)eeprom_offsets::DITTO_PRINT_ENABLED, value);
                                break;
                                
                            case 'O':
                                eeprom_write_byte((uint8_t*)eeprom_offsets::TOOLHEAD_OFFSET_SYSTEM, value);
                                break;
                                
                            case 'E':
                                eeprom_write_byte((uint8_t*)eeprom_offsets::EXTRUDER_HOLD, value);
                                break;
                                
                            case 'H':
                                eeprom_write_byte((uint8_t*)eeprom_offsets::HEAT_DURING_PAUSE, value);
                                break;
                                
                            case 'C':
                                eeprom_write_byte((uint8_t*)eeprom_offsets::SD_USE_CRC, value);
                                break;
                                
                            case 'T':
                                eeprom_write_byte((uint8_t*)eeprom_offsets::PSTOP_ENABLE, value);
                                break;
                                
                            case 'X':
                                eeprom_write_byte((uint8_t*)eeprom_offsets::STEPPER_X_CURRENT, value);
                                break;
                                
                            case 'Y':
                                eeprom_write_byte((uint8_t*)eeprom_offsets::STEPPER_Y_CURRENT, value);
                                break;
                                
                            case 'Z':
                                eeprom_write_byte((uint8_t*)eeprom_offsets::STEPPER_Z_CURRENT, value);
                                break;
                                
                            case 'A':
                                eeprom_write_byte((uint8_t*)eeprom_offsets::STEPPER_A_CURRENT, value);
                                break;
                                
                            case 'B':
                                eeprom_write_byte((uint8_t*)eeprom_offsets::STEPPER_B_CURRENT, value);
                                break;

                            case 'N':
                                eeprom_write_byte((uint8_t*)eeprom_offsets::LANGUAGE, value);
                                break;

                            case 'M':
                                eeprom_write_byte((uint8_t*)eeprom_offsets::WIFI_SD, value);
                                break;
                                
                            default:
                                break;
                        }
                    }
                    else if (*c<='Z' && *c>='A') cmd = *c;
                }
            }
            else if (buff_value[0] == 'U' &&
                    buff_value[1] == 'P' &&
                    buff_value[2] == 'D' &&
                    buff_value[3] == 'A' &&
                    buff_value[4] == 'T' &&
                    buff_value[5] == 'E')
            {
                char r;
                cli();
                wdt_disable();

                while (1)
                {
                    if (UCSR0A & (1<<RXC0))
                    {
                        r = UDR0;
                        UDR3 = r;
                    }

                    if (UCSR3A & (1<<RXC3))
                    {
                        r = UDR3;
                        UDR0 = r;
                    }
                }
            }
            else {
                if (buff_value[0]=='E' && buff_value[1]=='R' && buff_value[2]=='A' && buff_value[3]=='S' && buff_value[4]=='E')
                {
                    eeprom::factoryResetEEPROM();
                    Motherboard::getBoard().reset(true);
                }
                
                else if (buff_value[0]=='F' && buff_value[1]=='U' && buff_value[2]=='L' && buff_value[3]=='L' && buff_value[4]=='E' && buff_value[5]=='R' && buff_value[6]=='A' && buff_value[7]=='S' && buff_value[8]=='E')
                {
                    eeprom::erase();
                    host::stopBuildNow();
                }
            }
            break;
*/
        default:
            break;
    }
}
Example #17
0
static int rpmtsPrepare(rpmts ts)
{
    tsMembers tsmem = rpmtsMembers(ts);
    rpmtsi pi;
    rpmte p;
    int rc = 0;
    uint64_t fileCount = countFiles(ts);
    const char *dbhome = NULL;
    struct stat dbstat;

    fingerPrintCache fpc = fpCacheCreate(fileCount/2 + 10001, rpmtsPool(ts));

    rpmlog(RPMLOG_DEBUG, "computing %" PRIu64 " file fingerprints\n", fileCount);

    /* Reset actions, set skip for netshared paths and excluded files */
    pi = rpmtsiInit(ts);
    while ((p = rpmtsiNext(pi, 0)) != NULL) {
	rpmfiles files = rpmteFiles(p);
	if (rpmfilesFC(files) > 0) {
	    rpmfs fs = rpmteGetFileStates(p);
	    /* Ensure clean state, this could get called more than once. */
	    rpmfsResetActions(fs);
	    if (rpmteType(p) == TR_ADDED) {
		skipInstallFiles(ts, files, fs);
	    } else {
		skipEraseFiles(ts, files, fs);
	    }
	}
	rpmfilesFree(files);
    }
    rpmtsiFree(pi);

    /* Open rpmdb & enter chroot for fingerprinting if necessary */
    if (rpmdbOpenAll(ts->rdb) || rpmChrootIn()) {
	rc = -1;
	goto exit;
    }
    
    rpmtsNotify(ts, NULL, RPMCALLBACK_TRANS_START, 6, tsmem->orderCount);
    /* Add fingerprint for each file not skipped. */
    fpCachePopulate(fpc, ts, fileCount);
    /* check against files in the rpmdb */
    checkInstalledFiles(ts, fileCount, fpc);

    dbhome = rpmdbHome(rpmtsGetRdb(ts));
    /* If we can't stat, ignore db growth. Probably not right but... */
    if (dbhome && stat(dbhome, &dbstat))
	dbhome = NULL;

    pi = rpmtsiInit(ts);
    while ((p = rpmtsiNext(pi, 0)) != NULL) {
	rpmfiles files = rpmteFiles(p);;
	if (files == NULL)
	    continue;   /* XXX can't happen */

	(void) rpmswEnter(rpmtsOp(ts, RPMTS_OP_FINGERPRINT), 0);
	/* check files in ts against each other and update disk space
	   needs on each partition for this package. */
	handleOverlappedFiles(ts, fpc, p, files);

	/* Check added package has sufficient space on each partition used. */
	if (rpmteType(p) == TR_ADDED) {
	    /*
	     * Try to estimate space needed for rpmdb growth: guess that the
	     * db grows 4 times the header size (indexes and all).
	     */
	    if (dbhome) {
		int64_t hsize = rpmteHeaderSize(p) * 4;
		rpmtsUpdateDSI(ts, dbstat.st_dev, dbhome,
			       hsize, 0, 0, FA_CREATE);
	    }

	    rpmtsCheckDSIProblems(ts, p);
	}
	(void) rpmswExit(rpmtsOp(ts, RPMTS_OP_FINGERPRINT), 0);
	rpmfilesFree(files);
    }
    rpmtsiFree(pi);
    rpmtsNotify(ts, NULL, RPMCALLBACK_TRANS_STOP, 6, tsmem->orderCount);

    /* return from chroot if done earlier */
    if (rpmChrootOut())
	rc = -1;

    /* On actual transaction, file info sets are not needed after this */
    if (!(rpmtsFlags(ts) & (RPMTRANS_FLAG_TEST|RPMTRANS_FLAG_BUILD_PROBS))) {
	pi = rpmtsiInit(ts);
	while ((p = rpmtsiNext(pi, 0)) != NULL) {
	    rpmteCleanFiles(p);
	}
	rpmtsiFree(pi);
    }

exit:
    fpCacheFree(fpc);
    rpmtsFreeDSI(ts);
    return rc;
}
Example #18
0
bool K3b::DirSizeJob::countDir( const QString& dir )
{
    QStringList l = QDir(dir).entryList( QDir::AllEntries|QDir::Hidden|QDir::System|QDir::NoDotAndDotDot );
    return countFiles( l, dir );
}
Example #19
0
static int rpmtsPrepare(rpmts ts)
{
    tsMembers tsmem = rpmtsMembers(ts);
    rpmtsi pi;
    rpmte p;
    rpmfi fi;
    int rc = 0;
    uint64_t fileCount = countFiles(ts);

    fingerPrintCache fpc = fpCacheCreate(fileCount/2 + 10001);
    rpmFpHash ht = rpmFpHashCreate(fileCount/2+1, fpHashFunction, fpEqual,
			     NULL, NULL);
    rpmDiskSpaceInfo dsi;

    rpmlog(RPMLOG_DEBUG, "computing %" PRIu64 " file fingerprints\n", fileCount);

    /* Skip netshared paths, not our i18n files, and excluded docs */
    pi = rpmtsiInit(ts);
    while ((p = rpmtsiNext(pi, 0)) != NULL) {
	if (rpmfiFC(rpmteFI(p)) == 0)
	    continue;
	if (rpmteType(p) == TR_ADDED) {
	    skipInstallFiles(ts, p);
	} else {
	    skipEraseFiles(ts, p);
	}
    }
    rpmtsiFree(pi);

    /* Open rpmdb & enter chroot for fingerprinting if necessary */
    if (rpmdbOpenAll(ts->rdb) || rpmChrootIn()) {
	rc = -1;
	goto exit;
    }
    
    rpmtsNotify(ts, NULL, RPMCALLBACK_TRANS_START, 6, tsmem->orderCount);
    addFingerprints(ts, fileCount, ht, fpc);
    /* check against files in the rpmdb */
    checkInstalledFiles(ts, fileCount, ht, fpc);

    dsi = rpmtsDbDSI(ts);

    pi = rpmtsiInit(ts);
    while ((p = rpmtsiNext(pi, 0)) != NULL) {
	if ((fi = rpmteFI(p)) == NULL)
	    continue;   /* XXX can't happen */

	(void) rpmswEnter(rpmtsOp(ts, RPMTS_OP_FINGERPRINT), 0);
	/* check files in ts against each other and update disk space
	   needs on each partition for this package. */
	handleOverlappedFiles(ts, ht, p, fi);

	rpmtsUpdateDSIrpmDBSize(p, dsi);

	/* Check added package has sufficient space on each partition used. */
	if (rpmteType(p) == TR_ADDED) {
	    rpmtsCheckDSIProblems(ts, p);
	}
	(void) rpmswExit(rpmtsOp(ts, RPMTS_OP_FINGERPRINT), 0);
    }
    rpmtsiFree(pi);
    rpmtsNotify(ts, NULL, RPMCALLBACK_TRANS_STOP, 6, tsmem->orderCount);

    /* return from chroot if done earlier */
    if (rpmChrootOut())
	rc = -1;

    /* File info sets, fp caches etc not needed beyond here, free 'em up. */
    pi = rpmtsiInit(ts);
    while ((p = rpmtsiNext(pi, 0)) != NULL) {
	rpmteSetFI(p, NULL);
    }
    rpmtsiFree(pi);

exit:
    rpmFpHashFree(ht);
    fpCacheFree(fpc);
    rpmtsFreeDSI(ts);
    return rc;
}
Example #20
0
int main(int argc, char* argv[]) 
{
	// parameters that you can set. 
	string infF    = "";
	string infR    = "";
	string infPath = "";
	string outI    = "oIter.txt";
	string outP    = "oPar.txt";
	string outCorr = "oCorr.txt";
	string outCnt  = "oCnt.txt";
	string outPath = "";
	string outStub = "";
	//bool useemp    = false;
	double truncLimit = 0.99;
	int verbose    = 3;
	int lambdaD    = 147;
	int minD       = 130;
	int maxD       = 180;
	int sampleSize = -1;
	int burnins    = 1000;
	int iterations = 10000;
	int seed       = -1;
	// Unknowns
	double lambdaF[2];
	double lambdaR[2];
	double pF[2];
	double pR[2];

	/*
	 *  Read and check input parameters
	 */

	string errorLine =  "usage " + 
		string(argv[0]) + 
		" [parameters] \n" +
		"\t-iF      <forward reads binary file> \n" +
		"\t-iR      <reverse reads binary file> \n" +
		"\t-iPath   <path to forward and reverse reads binary files \n" +
		"            (overrides iR and iF if set)> \n" +
		"\t-oPath   <outdirectory, where all output files are put. \n" + 
		"\t          NOT created - needs to exists. Defaults to where \n"+
		"\t          the program is executed from.>\n" +
		"\t-oStub   <outfile names stub, \n" +
		"\t          defaults -oIter to <-oStub_>oIter.txt, \n" + 
		"\t          defaults -oPar to <-oStub_>oPar.txt> \n" + 
		"\t          defaults -oCorr to <-oStub_>oCorr.txt> \n" +
		"\t          defaults -oCnt to <-oStub_>oCnt.txt> \n" + 
		"\t-oIter   <outfile, where to write MCMC parameter\n" +
		"\t          estimates for each iteration,default generated from -oStub>\n" +
		"\t-oPar    <parameter-file, where to write MCMC\n" +
		"\t          final parameter estimates, default generated from -oStub> \n" +
         /*
		   "\t-oCorr   <out-file, lists correlation coefficients between forward\n" +
		   "\t          and reverse reads in [mind,maxd] \n" +
		   "\t          default generated from -oStub> \n" +
		 */
		"\t-oCnt    <out-file, lists forward and reverse read count frequencies\n" +
		"\t          default generated from -oStub> \n" +
		"\t-trunc   <truncation limit in (0,1], default 0.99.> \n" +
		"\t-size    <sample size, default all observations.> \n" +
		"\t-burnin  <number of MCMC burnin iterations,\n" +
		"\t          default 1000.> \n" +
		"\t-iter    <number of MCMC iterations\n" +
		"\t          (non-burnin iterations), default 10000.> \n" +
		"\t-seed    <set seed to random number generator.> \n" +
		"\t-ld      <distance-lambda, default 147 bp.> \n" +
		"\t-mind    <min distance, default 130 bp.> \n" +
		"\t-maxd    <max distance, default 180 bp.> \n" +
		/*
		  "\t-useemp  <toggle use of data-driven distance distribution, or poisson\n" +
		  "\t          around distance-lambda. default off.>\n" +
		*/
		"\t-v       <verbose level 0-3. default 2>";
	
	bool fail = false;
	string failmessage = "";
	
	for (int i = 1; i < argc; i++)
	{
	    if(strcmp(argv[i],"-iF") == 0)
			infF.assign(argv[++i]);
	    else if(strcmp(argv[i],"-iR") == 0)
			infR.assign(argv[++i]);
		else if(strcmp(argv[i],"-iPath") == 0)
			infPath.assign(argv[++i]);
	    else if(strcmp(argv[i],"-oPath") == 0)
			outPath.assign(argv[++i]);
	    else if(strcmp(argv[i],"-oStub") == 0)
			outStub.assign(argv[++i]);
	    else if(strcmp(argv[i],"-oIter") == 0)
			outI.assign(argv[++i]);
	    else if(strcmp(argv[i],"-oPar") == 0)
			outP.assign(argv[++i]);
	    /*
		  else if(strcmp(argv[i],"-oCorr") == 0)
			outCorr.assign(argv[++i]);
		*/
	    else if(strcmp(argv[i],"-oCnt") == 0)
			outCnt.assign(argv[++i]);
	    /*
		  else if (strcmp(argv[i],"-useemp") == 0)
			useemp = true;
		*/
	    else if (strcmp(argv[i],"-v") == 0)
			verbose = atoi(argv[++i]);
	    else if (strcmp(argv[i],"-seed") == 0)
			seed = atoi(argv[++i]);
	    else if (strcmp(argv[i],"-trunc") == 0)
			truncLimit = atof(argv[++i]);
	    else if (strcmp(argv[i],"-size") == 0)
			sampleSize = atoi(argv[++i]);
	    else if (strcmp(argv[i],"-burnin") == 0)
			burnins = atoi(argv[++i]);
	    else if (strcmp(argv[i],"-iter") == 0)
			iterations = atoi(argv[++i]);
	    else if (strcmp(argv[i],"-ld") == 0)
			lambdaD = atoi(argv[++i]);
	    else if (strcmp(argv[i],"-mind") == 0)
			minD = atoi(argv[++i]);
	    else if (strcmp(argv[i],"-maxd") == 0)
			maxD = atoi(argv[++i]);
	    else
		{
			failmessage.assign("Unknown argument: ");
			failmessage.append(argv[i]);
			failmessage.append("\n");
			fail = true;
		}
	}
	
	if (truncLimit <= 0 || truncLimit > 1)
	{
	    failmessage.append("-trunc value does not make sense.\n");
	    fail = true;
	}

	bool infPathSpec = false;
	if (strcmp(infPath.c_str(), "") != 0)
	{
		infPathSpec = true;
	    DIR *d = opendir(infPath.c_str());
	    if(d)
		{
			closedir(d);
		}
	    else
		{
			failmessage.append("-iPath does not exist.\n");
			fail = true;
		}
	}
	
	if (strcmp(infF.c_str(), "") == 0)
	{
		if (!infPathSpec)
		{
			failmessage.append("-iF or -iPath must be specified.\n");
			fail = true;
		}
	}
	
	if (strcmp(infR.c_str(), "") == 0)
	{
		if (!infPathSpec)
		{
			failmessage.append("-iR or -iPath must be specified.\n");
			fail = true;
		}
	}
		
	if (strcmp(outI.c_str(), "") == 0)
	{
	    failmessage.append("invalid -oIter.\n");
	    fail = true;
	}
		
	if (strcmp(outP.c_str(), "") == 0)
	{
	    failmessage.append("invalid -oPar.\n");
	    fail = true;
	}

	if (strcmp(outCorr.c_str(), "") == 0)
	{
	    failmessage.append("invalid -oCorr.\n");
	    fail = true;
	}

	if (strcmp(outCnt.c_str(), "") == 0)
	{
	    failmessage.append("invalid -oCnt.\n");
	    fail = true;
	}
	
	if (strcmp(outPath.c_str(), "") != 0)
	{
	    DIR* d = opendir(outPath.c_str());
	    if(d)
		{
			closedir(d);
		}
	    else
		{
			failmessage.append("-oPath does not exist.\n");
			fail = true;
		}
	}

	int infFCnt = 1;
	if (infPathSpec)
	{
		infFCnt = countFiles(infPath);
		if (infFCnt < 1)
		{
			failmessage.append("ERROR: infile path \"");
			failmessage.append(infPath.c_str());
			failmessage.append("\" does not contain a positive number of F and R binary files, aborting.\n");
			fail = true;
		}
	}
	
	if (fail)
	{
		cerr << endl << failmessage.c_str() << endl << errorLine << endl;
		return(-1);
	}
	
	if(strcmp(outStub.c_str(),"") != 0)
	{
	    outI = outStub + "_" + outI;
	    outP = outStub + "_" + outP;
	    outCorr = outStub + "_" + outCorr;
		outCnt = outStub + "_" + outCnt;
	}
	
	if(strcmp(outPath.c_str(),"") != 0)
	{
	    outI = outPath + outI;
	    outP = outPath + outP;
	    outCorr = outPath + outCorr;
		outCnt = outPath + outCnt;
	}

	if (seed < -1)
		seed = -1;

	ifstream iff[infFCnt];
	ifstream ifr[infFCnt];
	string fileNames[infFCnt];
	
	if (infPathSpec)
	{
		if (openFiles(infPath, iff, ifr, fileNames) != infFCnt)
		{
			failmessage.append("ERROR: all files in \"");
			failmessage.append(infPath.c_str());
			failmessage.append("\" could not be opened, aborting.\n");
			fail = true;
		}
	}
	else
	{
		iff[0].open(infF.c_str(),ios::binary);
		ifr[0].open(infR.c_str(),ios::binary);
		if (iff[0].fail())
		{
			failmessage.append("ERROR: Forward reads binary file \"");
			failmessage.append(infF.c_str());
			failmessage.append("\" could not be opened, aborting.\n");
			fail = true;
		}
		if (ifr[0].fail())
		{
			failmessage.append("ERROR: Reverse reads binary file \"");
			failmessage.append(infR.c_str());
			failmessage.append("\" could not be opened, aborting.\n");
			fail = true;
		}
	}
	
/*
	iff.open(infF.c_str(),ios::binary);
	if (iff.fail())
	{
		failmessage.append("ERROR: Forward reads binary file \"");
		failmessage.append(infF.c_str());
		failmessage.append("\" could not be opened, aborting.\n");
		fail = true;
	}
	ifstream ifr;
	ifr.open(infR.c_str(),ios::binary);
	if (ifr.fail())
	{
		failmessage.append("ERROR: Reverse reads binary file \"");
		failmessage.append(infR.c_str());
		failmessage.append("\" could not be opened, aborting.\n");
		fail = true;
	}
*/
	
	ofstream ofi;
	ofi.open(outI.c_str(),ios::trunc);
	if (ofi.fail())
	{
		failmessage.append("ERROR: Output file \"");
		failmessage.append(outI.c_str());
		failmessage.append("\" could not be created, aborting.\n");
		fail = true;
	}

	ofstream ofc;
	ofc.open(outCorr.c_str(),ios::trunc);
	if (ofc.fail())
	{
		failmessage.append("ERROR: Output file \"");
		failmessage.append(outCorr.c_str());
		failmessage.append("\" could not be created, aborting.\n");
		fail = true;
	}

	ofstream ofcnt;
	ofcnt.open(outCnt.c_str(),ios::trunc);
	if (ofcnt.fail())
	{
		failmessage.append("ERROR: Output file \"");
		failmessage.append(outCnt.c_str());
		failmessage.append("\" could not be created, aborting.\n");
		fail = true;
	}
	ofstream ofp;
	int truncValF,truncValR;
	int estMinD = minD, estMaxD = maxD, estLambdaD = lambdaD;
	double* distDens;
	vector<string> distDensV;

	ofp.open(outP.c_str(),ios::trunc);
	if (ofp.fail())
	{
		failmessage.append("ERROR: Paramater file \"");
		failmessage.append(outP.c_str());
		failmessage.append("\" could not be created, aborting.\n");
		fail = true;
	}

	if (fail)
	{
		cerr << endl << failmessage.c_str() << endl << errorLine << endl;
		return(-1);
	}
	
	ofi << "! Command:";
	for (int i = 0; i < argc; i++)
		ofi << " " << argv[i];
	ofi << endl;
	
	vlevel = verbose;
	
	/*
	 * Check file lengths
	 */

	int minPos[infFCnt], maxPos[infFCnt], minF[infFCnt], maxF[infFCnt], minR[infFCnt], maxR[infFCnt];
	checkFileLengths(iff, ifr, minPos, maxPos, minR, minF, maxF, maxR, infFCnt);
	
	/*
	 *  Estimate parameters
	 */
	
	ofp << "! Command:";
	for (int i = 0; i < argc; i++)
		ofp << " " << argv[i];
	ofp << endl;
	
	vcerr(1) << "*** Identifying truncation limits and data distributions ***" << endl;
	calculateTruncVal(iff,ifr,&ofcnt,
					  &truncValF, &truncValR, truncLimit,
					  minPos, maxPos,
					  minR, minF,
					  maxF, maxR, infFCnt);
	ofcnt.close();
	
	distDens = new double[maxD-minD+1];

	if (infFCnt == 1)
	{
		estimateDistance(&iff[0],&ifr[0],&ofc,
						 &estMinD, &estMaxD, &estLambdaD,
						 minD, maxD,
						 minPos[0], maxPos[0],
						 minR[0], minF[0],
						 maxF[0], maxR[0],
						 truncValF, truncValR,distDens,0.3);
		ofc.close();
	}
	
	/*
	if (useemp)
	{
		vcerr(2) << "\t* Estimating forward-reverse distance" << endl;
		estimateDistance(&iff,&ifr,&ofc,
						 &estMinD, &estMaxD, &estLambdaD,
						 minD, maxD,
						 minPos, maxPos,
						 minR, minF,
						 maxF, maxR,
						 truncValF, truncValR,distDens,0.3);
		
		ofc.close();
	}
	else
	{
	*/
	for (int dist = minD; dist <= maxD; dist++)
		distDens[dist-minD] = gsl_ran_poisson_pdf(dist, lambdaD);
	/*
	  }
	*/
	
	vcerr(1) << "*** Parameter estimation ***" << endl;
	if (estimateParameters(iff,ifr,&ofi,
						   estMinD,estMaxD,estLambdaD,
						   pF, pR, lambdaF, lambdaR,
						   sampleSize,burnins,iterations,
						   seed,
						   minPos, maxPos,
						   minR, minF,
						   maxF, maxR,
						   truncValF, truncValR, infFCnt) < 0)
	{
		cerr << "ERROR: estimateParameters failed, aborting." << endl;
		
		for (int i=0; i<infFCnt; i++)
		{
			iff[i].close();
			ifr[i].close();
		}		
		ofi.close();
		ofp.close();
		delete[] distDens;
		return(-1);
	}
 	else
 	{
 		if (writeParameters(&ofp, pF, pR, lambdaF, lambdaR, lambdaD,
							truncValF, truncValR,
							minD, maxD, estLambdaD,
							estMinD, estMaxD, distDens) < 0)
 		{
 			cerr << "WARNING: could not write parameters to file, skipping." << endl;
 		}
 	}
	ofi.close();
	ofp.close();

	for (int i=0; i<infFCnt; i++)
	{
		iff[i].close();
		ifr[i].close();
	}

	delete[] distDens;
	
	vcerr(3) << setprecision(3);
	vcerr(3) << endl << "\t\tParameter estimates:" << endl;
	vcerr(3) << "\t\tpF: S = " << pF[0] << " NotS = " << pF[1] << endl;
	vcerr(3) << "\t\tpR: E = " << pR[0] << " NotE = " << pR[1] << endl;
	vcerr(3) << "\t\tlambdaF: S = " << lambdaF[0] << " NotS = " << lambdaF[1] << endl;
	vcerr(3) << "\t\tlambdaR: E = " << lambdaR[0] << " NotE = " << lambdaR[1] << endl;
	vcerr(3) << "\t\testMinD:  = " << estMinD << " estMaxd = " << estMaxD << endl;
}
Example #21
0
int main(int argc, char **argv) {
	if (argc > 1 && !strcmp(argv[1], "--help")) {
		help();
	}

	if (argc < 4) {
		usage();
		exit(1);
	}

	const char *type = argv[1];
	const char *dirname = argv[2];
	const char *out = argv[3];

	uint8_t g_type;
	if (!strcmp(type, "--grim")) {
		g_type = GT_GRIM;
	} else if (!strcmp(type, "--emi")) {
		g_type = GT_EMI;
	} else {
		usage();
		exit(1);
	}

	DIR *dir = opendir(dirname);
	if (dir == 0) {
		printf("Can not open source dir: %s\n", dirname);
		exit(2);
	}

	lab_header head;

	head.num_entries = 0;
	head.string_table_size = 0;

	countFiles(&head, dir, dirname, 0);

// 	printf("%d files, string table of size %d\n", head.num_entries, head.string_table_size);

	lab_entry *entries = (lab_entry *)malloc(head.num_entries * sizeof(lab_entry));
	char *str_table = (char *)malloc(head.string_table_size);
	if (!str_table || !entries) {
		printf("Could not allocate memory\n");
		exit(3);
	}

	rewinddir(dir);
	uint32_t offset = 16 + head.num_entries * sizeof(lab_entry) + head.string_table_size + 16;
	createEntries(dir, entries, str_table, dirname, offset);

	closedir(dir);

	// Open the output file after we've finished with the dir, so that we're sure
	// we don't include the lab into itself if it was asked to be created into the same dir.
	FILE *outfile = fopen(out, "wb");
	if (!outfile) {
		printf("Could not open file %s for writing\n", out);
		exit(2);
	}

	fwrite("LABN", 1, 4, outfile);
	fwrite("\x00\x00\x01\x00", 1, 4, outfile); //version
	writeUint32(outfile, head.num_entries);
	writeUint32(outfile, head.string_table_size);

	if (g_type == GT_GRIM) {
		uint32_t s_offset = 0; // First entry of the table has offset 0 for Grim
		fwrite(&s_offset, 1, 4, outfile);
		fseek(outfile, -4, SEEK_CUR);
	} else { // EMI has an offset instead.
		writeUint32(outfile, 20 + head.num_entries * sizeof(lab_entry) + 0x13d0f);
	}

	fwrite(entries, 1, head.num_entries * sizeof(lab_entry), outfile);
	if (g_type == GT_GRIM) {
		fwrite(str_table, 1, head.string_table_size, outfile);
	} else {
		char *s = (char *)malloc(head.string_table_size);
		memset(s, 0, head.string_table_size);
		for (uint32_t j = 0; j < head.string_table_size; j++) {
			if (str_table[j] != 0)
				s[j] = str_table[j] ^ 0x96;
		}
		fwrite(s, 1, head.string_table_size, outfile);
		free(s);
	}

	uint32_t bufsize = 1024*1024;
	char *buf = (char *)malloc(bufsize);

	for (uint32_t i = 0; i < head.num_entries; ++i) {
		lab_entry &entry = entries[i];
		const char *fname = str_table + READ_LE_UINT32(&entry.fname_offset);

		char *path = appendPath(fname, dirname);

		FILE *file = fopen(path, "rb");
		free(path);

		uint32_t offset = READ_LE_UINT32(&entry.start);
		uint32_t size = READ_LE_UINT32(&entry.size);

		if (size > bufsize) {
			char *newbuf = (char *)realloc(buf, size);
			if (!newbuf) {
				free(buf);
				printf("Could not allocate memory\n");
				exit(3);
			}
			bufsize = size;
			buf = newbuf;
		}

// 		printf("writing file %s, at offset %d and of size %d\n", fname, offset, size);

		fread(buf, 1, size, file);
		fseek(outfile, offset, SEEK_SET);
		fwrite(buf, 1, size, outfile);

		fclose(file);
	}

	fclose(outfile);
	free(buf);
	free(entries);
	free(str_table);

	return 0;
}
Example #22
-1
  bool countDir( const QString& dir ) {
    const QString& dot = KGlobal::staticQString( "." );
    const QString& dotdot = KGlobal::staticQString( ".." );
    QStringList l = QDir(dir).entryList( QDir::All|QDir::Hidden|QDir::System );
    l.remove( dot );
    l.remove( dotdot );

    return countFiles( l, dir );
  }