// Recursively traverse an eZ Publish directory static void traverse( const QDir &dir, Translator &fetchedTor, ConversionData cd, UpdateOptions options, bool *fail ) { if ( options & Verbose ) printOut( QObject::tr( " Checking subdirectory '%1'" ).arg( qPrintable(dir.path()) ) ); if ( !dir.exists() ) return; const QFileInfoList list = dir.entryInfoList(); QFileInfo fi; for ( int i = 0; i < list.size(); ++i ) { fi = list.at( i ); if ( fi.fileName().startsWith( "." ) ) { // Do nothing } else if ( fi.isDir() ) { QDir subdir = dir; subdir.setCurrent( subdir.path() + QDir::separator() + fi.fileName() ); traverse( subdir.currentPath(), fetchedTor, cd, options, fail ); subdir.setCurrent( dir.path() ); } else { if ( fi.fileName().endsWith(QLatin1String(".php"), Qt::CaseInsensitive) ) { if ( options & Verbose ) printOut( QObject::tr( " Checking '%1'" ).arg( qPrintable(fi.fileName()) ) ); if ( !fetchedTor.load(fi.fileName(), cd, QLatin1String("php")) ) { qWarning( "%s", qPrintable( cd.error() ) ); *fail = true; } } else if ( fi.fileName().endsWith(QLatin1String(".tpl"), Qt::CaseInsensitive) ) { if ( options & Verbose ) printOut( QObject::tr( " Checking '%1'" ).arg( qPrintable(fi.fileName()) ) ); if ( !fetchedTor.load(fi.fileName(), cd, QLatin1String("tpl")) ) { qWarning( "%s", qPrintable( cd.error() ) ); *fail = true; } } } } }
void HHCObject::fromDir(int level,QString dir,QString temp){ QDir dirModel; dirModel.setCurrent(dir); QStringList list = dirModel.entryList(); if(list.contains("index.html",Qt::CaseInsensitive)){ QFileInfo fileInfo(dir+"/index.html"); QString absDir = temp.length()>0?temp+"/index.html":"index.html"; treeModel->addModelData(level, "index.html",absDir); }else if(list.contains("index.htm",Qt::CaseInsensitive)){ QFileInfo fileInfo(dir+"/index.htm"); QString absDir = temp.length()>0?temp+"/index.htm":"index.htm"; treeModel->addModelData(level, "index.htm",absDir); } foreach(QString fileName,list){ if(fileName.compare(".")==0||fileName.compare("..")==0||fileName.compare("index.htm")==0||fileName.compare("index.html")==0){ continue; } if(!(fileName.endsWith(".htm",Qt::CaseInsensitive)||fileName.endsWith(".html",Qt::CaseInsensitive))){ continue; } QFileInfo fileInfo(dir+"/"+fileName); QString absDir = temp.length()>0?temp+"/"+fileName:fileName; treeModel->addModelData(level, fileName,absDir); if(fileInfo.isDir()){ level++; fromDir(level*4,dir+"/"+fileName,absDir); level--; } } save(); }
void CCCITT4Client::OnFilesListItemClicked(QListWidgetItem *pItem) { QImage *pImage; QString sFilename; QDir oDir; QMessageBox msgBox; oDir.setCurrent(ui->lineEditPath->text()); sFilename = oDir.absoluteFilePath(pItem->text()); this->ui->graphicsView->Scene->clear(); pImage = new QImage(sFilename); if(pImage->isNull()) { msgBox.setText(QString("Can't' open the file: %1").arg(sFilename)); msgBox.exec(); /* Update the file list because it seems to be corrupt */ UpdateFileList(); return; } this->ui->graphicsView->Scene->addItem(new QGraphicsPixmapItem(QPixmap::fromImage(*pImage))); this->show(); /* Move the splitter to enhance the image viewer. */ setVerticalSpitter(0, 80); }
void BinaryWidget::updateNote() { NoteWidget::updateNote(); if(note->getPath() != path->text()) { QString p = path->text(); if(SettingsDialog::binaryCopy()){ QDir d; d.setCurrent(NotesManager::getInstance()->getPath()); d.mkdir("files"); QDir b(d.absoluteFilePath("files")); if(p.indexOf("http://") == 0){ // download from internet with a dialog tmp_dest = b.absoluteFilePath(p.split("/").last()); download(p); } else if(p != "" && !p.contains(d.absolutePath())){ QString new_p = b.absoluteFilePath(QFileInfo(p).fileName()); QFile(p).copy(new_p); path->setText(new_p); } } NotesManager::getInstance()->getHistory()->addAndExec( new ModifyBinaryPath(note,path->text())); updateBinaryWidget(); note->setModified(true); NotesManager::getInstance()->setNoteModified(); } if(note->getDescription() != description->toPlainText()){ NotesManager::getInstance()->getHistory()->addAndExec( new ModifyBinaryDescription(note,description->toPlainText())); note->setModified(true); NotesManager::getInstance()->setNoteModified(); } }
/* read in saved IQ error data */ bool Spectrum::readError() { QDir directory; directory.setCurrent(userDirectory); QByteArray fname = "iq" + QByteArray::number(nrig) + ".dat"; QFile file(fname); if (!file.open(QIODevice::ReadOnly)) { return(false); } QDataStream in(&file); for (int i = 0; i < sizeIQ; i++) { calibSigList[i].n = 0; calibSigList[i].zsum[0] = 0.; calibSigList[i].zsum[1] = 0.; } while (!in.atEnd()) { int i; long long n; double x, y; in >> i; in >> n; in >> x >> y; if (i >= 0 && i < sizeIQ) { calibSigList[i].n = n; calibSigList[i].zsum[0] = x; calibSigList[i].zsum[1] = y; calibSigList[i].z[0] = calibSigList[i].zsum[0] / calibSigList[i].n; calibSigList[i].z[1] = calibSigList[i].zsum[1] / calibSigList[i].n; } } file.close(); return(true); }
//! set file name void TextEdit::setCurrentFileName(const QString &curPath) { path = curPath + "/help/"; QDir dir; dir.mkpath(path); textEdit->document()->setModified(false); dir.setCurrent(path); }
QString Config::resourcesPath() { #ifdef Q_OS_LINUX QDir resourcesDir; resourcesDir.setCurrent("/usr/share/qstamina"); if( !resourcesDir.exists() ) resourcesDir.setCurrent(QApplication::applicationDirPath()); return resourcesDir.absolutePath(); #endif #ifdef Q_OS_MACX return QApplication::applicationDirPath()+"/../Resources"; #endif #ifdef Q_OS_WIN return QApplication::applicationDirPath(); #endif return QString(); }
bool TestCompiler::removeMakefile( const QString &workPath ) { QDir D; D.setCurrent( workPath ); if ( D.exists( "Makefile" ) ) return D.remove( "Makefile" ); else return true; }
/*! append note to file @todo File write error not handled */ void NoteDialog::writeNotes() { QDir directory; directory.setCurrent(noteDir); QFile file(noteFile); if (file.open(QIODevice::Append | QIODevice::Text)) { file.write(NoteLineEdit->text().toAscii().data()); file.write("\n"); file.close(); } }
void AMExportController::setDefaultDestinationFolderPath() { QDir exportDir; if(!AMUserSettings::remoteDataFolder.isEmpty()) exportDir.setCurrent(AMUserSettings::remoteDataFolder); else exportDir.setCurrent(AMUserSettings::userDataFolder); exportDir.cdUp(); if(!exportDir.entryList(QDir::AllDirs).contains("exportData")){ if(!exportDir.mkdir("exportData")){ AMErrorMon::alert(this, AMSCANACTION_CANT_CREATE_EXPORT_FOLDER, "Could not create the auto-export folder."); return; } } exportDir.cd("exportData"); setDestinationFolderPath(exportDir.absolutePath()); }
bool TestCompiler::make( const QString &workPath, const QString &target ) { QDir D; D.setCurrent( workPath ); QString cmdline = makeCmd_; if ( cmdline.contains("nmake", Qt::CaseInsensitive) ) cmdline.append(" /NOLOGO"); if ( !target.isEmpty() ) cmdline += " " + target; return runCommand( cmdline ); }
/** * @brief Copies model binary to the temporary folder. * @param temp_path System temporary folder. * @return 0 if success. */ int BinaryHandler::_set_temp_env(const QString& temp_path) { QDir qdir; qdir.setCurrent(temp_path); // Set up a bin directory where to move the model binaries. if (!qdir.exists("bin")) { qdir.mkdir("bin"); } QString temp_bin_path = temp_path + "/bin"; qdir.setCurrent(temp_bin_path); // Assuming the model binaries reside under ../Resources/bin/ relative // to the app. dir. QDir resources(QCoreApplication::applicationDirPath()); resources.cd(RESOURCES); resources.cd("bin"); if (DEBUG_MODE) { fprintf(stderr, "Model resources directory: %s\n", resources.path().toStdString().c_str()); fprintf(stderr, "Application directory: %s\n", QCoreApplication::applicationDirPath().toStdString().c_str()); fprintf(stderr, "Current directory: '%s'\n", qdir.currentPath().toStdString().c_str()); } QStringList files = resources.entryList(QDir::Files); for (auto& f : files) { auto dest = temp_bin_path+"/"+f; if (QFile::exists(dest)) { QFile::remove(dest); } QFile::copy(resources.path()+"/"+f, dest); } return 0; }
/** * @brief Initialize binary model. * @param temp_path System temporary folder. * @param max_cores Maximum number of CPU cores (not used). * @param tlife Toothlife object for results. * @param num_iter Number of iterations. * @param step_size Step size. * @param id Unique run ID. * @return 0 if success, else -1. */ int BinaryHandler::init_model(const QString& temp_path, const int max_cores, ToothLife& tlife, const int num_iter, const int step_size, const int id) { (void)max_cores; _binary = QString(modelBin.c_str()); _id = id; _toothLife = &tlife; systemTempPath = temp_path; _set_temp_env(temp_path); QDir qdir; qdir.setCurrent(temp_path); QString run_folder = QString::number(_id); qdir.mkdir(run_folder); qdir.setCurrent(run_folder); QString parfile; QTextStream str; str.setString(&parfile); str << temp_path << "/" << run_folder << "/mpar_" << _id << ".txt"; int rv = morphomaker::Export_parameters( parameters, parfile.toStdString(), _input_style ); if (rv) { return -1; } stepSize = step_size; nIter = num_iter; // Can't send the parameter file with the full path to the binary, // as some programs have difficulties with long arguments. parfile = ""; str << "mpar_" << _id << ".txt"; _set_bin_settings( parfile, num_iter, step_size ); return 0; }
void Controller::loadAlbums() { QDir dir; dir.setFilter(QDir::Files | QDir::Hidden | QDir::NoSymLinks); dir.setSorting(QDir::Name); dir.setCurrent(m_pParser->getDirectory()); QFileInfoList list = dir.entryInfoList(); for(int i = 0; i < list.count(); ++i) { QFileInfo fileInfo = list.at(i); m_pParser->setFile(fileInfo.baseName()); m_listAlbums.insert(fileInfo.baseName(),new Album(m_pParser->getAlbumFromFile(fileInfo.baseName()))); } }
bool TestCompiler::makeClean( const QString &workPath ) { QDir D; if (!D.exists(workPath)) { testOutput_.append( "Directory '" + workPath + "' doesn't exist" ); return false; } D.setCurrent(workPath); QFileInfo Fi( workPath + "/Makefile"); if (Fi.exists()) // Run make clean return runCommand( makeCmd_ + " clean" ); return true; }
void MainWindow::readImages(const QString& dirname) { m_loadDialog = new LoadDialog(this); m_loadDialog->show(); QDir dir; dir.setCurrent(dirname); QList<QString> filenames(dir.entryList(QDir::Files, QDir::Name)); m_loadWatcher = new QFutureWatcher<QList<ProcessedImage> >(this); connect(m_loadWatcher, SIGNAL(progressValueChanged(int)), m_loadDialog, SLOT(update(int))); connect(m_loadWatcher, SIGNAL(progressRangeChanged(int, int)), m_loadDialog, SLOT(updateRange(int, int))); connect(m_loadWatcher, SIGNAL(finished()), this, SLOT(finishedReadImages())); m_loadWatcher->setFuture(QtConcurrent::mappedReduced(filenames, processImage, buildImageList)); }
bool TestCompiler::qmake( const QString &workDir, const QString &proName, const QString &buildDir ) { QDir D; D.setCurrent( workDir ); if (D.exists("Makefile")) D.remove("Makefile"); QString projectFile = proName; QString makeFile = buildDir; if (!projectFile.endsWith(".pro")) projectFile += ".pro"; if (!makeFile.isEmpty() && !makeFile.endsWith('/')) makeFile += '/'; makeFile += "Makefile"; // Now start qmake and generate the makefile return runCommand( qmakeCmd_ + " " + projectFile + " -o " + makeFile ); }
void CrashHandler::checkCrashsaves() { MainWindow *mw = MainWinConnect::pMainWin; QDir crashSave; crashSave.setCurrent(AppPathManager::userAppDir()); if(crashSave.exists("__crashsave")) { crashSave.cd("__crashsave"); QStringList allCrashFiles = crashSave.entryList(QDir::Files | QDir::NoDotAndDotDot); for(QString &file : allCrashFiles) { QString fPath = crashSave.absoluteFilePath(file); mw->OpenFile(fPath, false); } QList<QMdiSubWindow *> listOfAllSubWindows = mw->allEditWins(); for(QMdiSubWindow *subWin : listOfAllSubWindows) { /*if(MainWinConnect::pMainWin->activeChildWindow(subWin) == 1){ MainWinConnect::pMainWin->activeLvlEditWin()->makeCrashState(); }else */ if(mw->activeChildWindow(subWin) == MainWindow::WND_NpcTxt) mw->activeNpcEditWin()->makeCrashState(); /*else if(MainWinConnect::pMainWin->activeChildWindow(subWin) == 3){ MainWinConnect::pMainWin->activeWldEditWin()->makeCrashState(); }*/ } //Clean up all files from crash-save folder after restoring crashSave.removeRecursively(); QMessageBox::information(mw, tr("Crash recovery", "Crash recovery - emergency file saving after crash. A title of message box."), tr("Since the last crash, the editor recovered some files.\n" "Please save them before doing anything else."), QMessageBox::Ok); } }
/* save IQ data to disk */ bool Spectrum::saveError() { QDir directory; directory.setCurrent(userDirectory); QByteArray fname = "iq" + QByteArray::number(nrig) + ".dat"; QFile file(fname); if (!file.open(QIODevice::WriteOnly)) { return(false); } QDataStream fstr(&file); for (int i = 0; i < sizeIQ; i++) { if (calibSigList[i].n) { fstr << i; fstr << calibSigList[i].n; fstr << calibSigList[i].zsum[0]; fstr << calibSigList[i].zsum[1]; } } file.close(); return(true); }
void FileDownloader::downloadFinished(QNetworkReply *reply) { //qDebug() << "enter 4"; if (reply->error()) { qDebug() << "download error."; //QMessageBox::warning(this, QStringLiteral("警告"), QStringLiteral("下载失败!请检查输入网址是否正确!")); return; } file.write(reply->readAll()); file.flush(); file.close(); reply->deleteLater(); QFileInfo info(file); this->absoluteAddr = info.absoluteFilePath(); //qDebug() << absoluteAddr; QDir dir; dir.setCurrent("../"); emit downloadSuccess(); }
void FileDownloader::doDownload(const QUrl url) { //qDebug() << "enter 2"; filename = saveFileName(url); //qDebug() << filename; QDir xmlDir; //qDebug() << xmlDir.currentPath(); if (!xmlDir.exists("XML")) { xmlDir.mkdir("XML"); } file.setFileName(filename); xmlDir.setCurrent("XML"); if (!file.open(QIODevice::ReadWrite)) { //QMessageBox::warning(this, QStringLiteral("警告"), QStringLiteral("打开文件错误!")); return; } QNetworkRequest request(url); reply = manager->get(request); }
void CheckAndSync::Syncronize(){ QStack <QFileInfo> File_Stack; QFileInfo backdir(".."); QDir *tempDir = new QDir(); tempDir->setCurrent("/home/quark/YaDiskDir"); tempDir->setFilter(QDir::Files| QDir::Dirs | QDir::Hidden | QDir::NoDotAndDotDot); tempDir->setSorting(QDir::DirsLast); QVector <QString> VizitedDirs; qDebug() << QDateTime::currentDateTime().toString("ddd MMM dd hh:mm:ss yyyy")+" | "+"Begin to global syncronizing"; do { if (!VizitedDirs.contains(tempDir->path())) { File_Stack.push(backdir); for(int i=tempDir->entryInfoList().count();i>0;i--){ File_Stack.push(tempDir->entryInfoList().at(i-1)); if (File_Stack.top().isFile()) { if(tempDir->path() == "."){ emit NeedFilePropeties("/",File_Stack.pop().fileName()); qDebug() << QDateTime::currentDateTime().toString("ddd MMM dd hh:mm:ss yyyy")+" | "+"NeedFileProperties signal emmited"; } else { emit NeedFilePropeties('/'+tempDir->path()+'/',File_Stack.pop().fileName()); qDebug() << QDateTime::currentDateTime().toString("ddd MMM dd hh:mm:ss yyyy")+" | "+"NeedFileProperties signal emmited"; } } } } qDebug() << "CD to "+File_Stack.top().fileName(); VizitedDirs.append(tempDir->path()); tempDir->cd(File_Stack.pop().fileName()); } while(!File_Stack.empty()); qDebug() << QDateTime::currentDateTime().toString("ddd MMM dd hh:mm:ss yyyy")+" | "+"Global syncronizing complete.Waiting."; }
void Grid::openHash() { cout << "Opening hash" << endl; // if dir exists QDir dir; QFile *keysFile; QString currentHashKey(""); realvec currentFeature; int currentHashFileNumber = 0; if(dir.exists("extractFiles") ) { // open keys dir.setCurrent("extractFiles"); keysFile = new QFile(dir.filePath("keys.txt")); if(keysFile->open(QFile::ReadWrite)) { QTextStream keysInput(keysFile); while(!keysInput.atEnd()) { keysInput >> currentHashKey; keysInput >> currentHashFileNumber; if(!currentHashKey.isNull() ) { std::stringstream stringStream; stringStream << "featureVec" << currentHashFileNumber << ".hsh"; cout << dir.filePath(stringStream.str().c_str()).toStdString() << endl; currentFeature.read(dir.cleanPath(stringStream.str().c_str()).toStdString()); if(normFeatureHash->find(currentHashKey.toStdString()) == normFeatureHash->end()) { normFeatureHash->insert( pair<std::string, realvec>(currentHashKey.toStdString(), currentFeature) ); } } //TODO:: Clean up pointers } }
void SaveTextExport::save() { SaveTextExport e; NotesManager* nm = NotesManager::getInstance(); QString workplace = nm->getPath(); nm->setNoteModified(false); //CLEAN QDir dir; dir.setCurrent(workplace); dir.setFilter(QDir::Hidden | QDir::Files); QFileInfoList list = dir.entryInfoList(); for (int i = 0; i < list.size(); ++i) { QFileInfo fileInfo = list.at(i); if(fileInfo.fileName().contains(".note") || fileInfo.fileName() == ".notes" || fileInfo.fileName() == ".tags" ){ QFile(fileInfo.absoluteFilePath()).remove(); } } //SERIALIZE QString base = dir.absolutePath(); writeToFile(base+"/.notes",e.exportNotesMetafile()); writeToFile(base+"/.tags",e.exportTagsMetafile()); for(NotesManager::Iterator it = nm->begin();it != nm->end();++it){ writeToFile(base+"/"+QString::number((*it)->getId())+".note",e.exportNote(*it)); (*it)->setModified(false); } Trash* trash = Trash::getInstance(); for(Trash::Iterator it = trash->begin();it != trash->end();++it){ writeToFile(base+"/"+QString::number((*it)->getId())+".note",e.exportNote(*it)); (*it)->setModified(false); } nm->setNoteModified(false); }
void AMExportController::continueScanExport() { if(state_ != Exporting) return; // done, or paused. Don't keep going. // 0. emit progress and signals emit progressChanged(exportScanIndex_, scanCount()); // 1. Check for finished: if(exportScanIndex_ >= scanCount()) { emit stateChanged(state_ = Finished); // Reset whether the exporter should overwrite files with matching filenames. exporter_->setOverwriteOption(AMExporter::Default); QString message = "Exported " % QString::number(succeededCount()) % " scans."; if(failedCount()) message.append(" (" % QString::number(failedCount()) % " scans could not be exported.)"); AMErrorMon::report(AMErrorReport(this, AMErrorReport::Information, 0, message)); AMUser::user()->setLastExportDestination(destinationFolderPath()); AMUser::user()->storeToDb(AMUser::user()->database()); deleteLater(); return; // We're done! } try { // 2. Load scan from db and check loaded successfully AMScan* scan = 0; AMDbObject* databaseObject = 0; if(usingScanURLs_){ const QUrl& url = scanURLsToExport_.at(exportScanIndex_); AMDatabase* db = 0; QStringList path; QString tableName; int id = 0; bool idOkay = false; // parse the URL and make sure it's valid if(!( url.scheme() == "amd" && (db = AMDatabase::database(url.host())) && (path = url.path().split('/', QString::SkipEmptyParts)).count() == 2 && (id = path.at(1).toInt(&idOkay)) > 0 && idOkay == true && (tableName = path.at(0)).isEmpty() == false )) throw QString("The export system couldn't understand the scan URL '" % url.toString() % "', so this scan has not been exported."); emit statusChanged(status_ = "Opening: " % url.toString()); databaseObject = AMDbObjectSupport::s()->createAndLoadObjectAt(db, tableName, id); scan = qobject_cast<AMScan*>(databaseObject); if(!scan) { databaseObject->deleteLater(); throw QString("The export system couldn't load a scan out of the database (" % url.toString() % "), so this scan has not been exported."); } } else if(usingScanObjects_) { scan = scanObjectsToExport_.at(exportScanIndex_); if(!scan) throw QString("An invalid scan reference was provided, so this scan has not been exported."); } emit statusChanged(status_ = "Opening: " % scan->name()); // this is kinda pointless... emit statusChanged(status_ = "Writing: " % scan->fullName()); // 3. Check that it can be exported with the exporter and option selected if(!exporter_->isValidFor(scan, option_)) { QString err("The exporter '" % exporter_->description() % "' and the template '" % option_->name() % "' are not compatible with this scan (" % scan->fullName() % "), so it has not been exported."); emit statusChanged(status_ = err); if (usingScanURLs_) scan->deleteLater(); throw err; } // 4. Export // 4.1 check and create the export folder for the current run QString destinationFolderPathWithRun = destinationFolderPath_; exporter_->setCurrentScan(scan); // we must set this, otherwise we can't get the name of the current run QString currentRunExportFilePath = exporter_->currentRunExportFilePath(); if(currentRunExportFilePath.length() > 0) { QDir exportDir; exportDir.setCurrent(destinationFolderPath_); if (!exportDir.entryList(QDir::AllDirs).contains(currentRunExportFilePath)) { if(!exportDir.mkdir(currentRunExportFilePath)){ QString err("Could not create the export folder." % exportDir.absolutePath()); emit statusChanged(status_ = err); throw err; } } destinationFolderPathWithRun = destinationFolderPathWithRun % "/" % currentRunExportFilePath; } // 4.2 export QString writtenFile = exporter_->exportScan(scan, destinationFolderPathWithRun, option_, exportScanIndex_); if(writtenFile.isNull()) { QString err("Export failed for scan '" % scan->fullName() % " to " % destinationFolderPathWithRun % "'."); emit statusChanged(status_ = err); if (usingScanURLs_) scan->deleteLater(); throw err; } emit statusChanged(status_ = "Wrote: " % writtenFile); succeededCount_++; if (usingScanURLs_) scan->deleteLater(); } catch(QString errMsg) { failedCount_++; AMErrorMon::report(AMErrorReport(this, AMErrorReport::Alert, -1, errMsg)); } // 5. increment exportScanIndex_ and re-schedule next one exportScanIndex_++; QTimer::singleShot(5, this, SLOT(continueScanExport())); }
int main(int argc, char* argv[]) { namespace DU = util::directory; BibleTimeApp app(argc, argv); //for QApplication app.setApplicationName("bibletime"); app.setApplicationVersion(BT_VERSION); showDebugMessages = QCoreApplication::arguments().contains("--debug"); #ifdef Q_WS_WIN // Use the default Qt message handler if --debug is not specified // This works with Visual Studio debugger Output Window if (showDebugMessages) qInstallMsgHandler( myMessageOutput ); #else qInstallMsgHandler( myMessageOutput ); #endif #ifdef BT_ENABLE_TESTING if (QString(argv[1]) == QString("--run-tests")) { BibleTimeTest testClass; return QTest::qExec(&testClass); } #endif /** \todo Reimplement "--ignore-session" and "--open-default-bible <key>" command line argument handling. */ #ifdef Q_WS_WIN // On Windows, add a path for Qt plugins to be loaded from app.addLibraryPath(app.applicationDirPath() + "/plugins"); // Must set HOME var on Windows QString homeDir(getenv("APPDATA")); _putenv_s("HOME", qPrintable(homeDir)); #endif registerMetaTypes(); if (!DU::initDirectoryCache()) { qFatal("Error initializing directory cache!"); return EXIT_FAILURE; } #ifdef Q_WS_WIN // change directory to the Sword or .sword directory in the $HOME dir so that // the sword.conf is found. It points to the sword/locales.d directory QString homeSwordDir = util::directory::getUserHomeDir().absolutePath(); QDir dir; dir.setCurrent(homeSwordDir); #endif // This is needed for languagemgr language names to work, they use \uxxxx escape sequences in string literals QTextCodec::setCodecForTr(QTextCodec::codecForName("UTF-8")); //first install QT's own translations QTranslator qtTranslator; qtTranslator.load("qt_" + QLocale::system().name()); app.installTranslator(&qtTranslator); //then our own QTranslator BibleTimeTranslator; BibleTimeTranslator.load( QString("bibletime_ui_").append(QLocale::system().name()), DU::getLocaleDir().canonicalPath()); app.installTranslator(&BibleTimeTranslator); app.setProperty("--debug", QVariant(showDebugMessages)); //Migrate configuration data, if neccessary util::migration::checkMigration(); // setSignalHandler(signalHandler); BibleTime *mainWindow = new BibleTime(); mainWindow->setAttribute(Qt::WA_DeleteOnClose); // a new BibleTime version was installed (maybe a completely new installation) if (CBTConfig::get(CBTConfig::bibletimeVersion) != BT_VERSION) { CBTConfig::set(CBTConfig::bibletimeVersion, BT_VERSION); mainWindow->saveConfigSettings(); } // restore the workspace and process command line options //app.setMainWidget(bibletime_ptr); //no longer used in qt4 (QApplication) mainWindow->show(); mainWindow->processCommandline(); //must be done after the bibletime window is visible #ifndef NO_DBUS new BibleTimeDBusAdaptor(mainWindow); // connect to D-Bus and register as an object: QDBusConnection::sessionBus().registerService("info.bibletime.BibleTime"); QDBusConnection::sessionBus().registerObject("/BibleTime", mainWindow); #endif int r = app.exec(); CLOSE_DEBUG_STREAM; return r; }
void Grid::extractAction(std::string filename) { total_->updctrl("mrs_string/filename", filename); total_->updctrl("WekaSink/wsink/mrs_string/filename", "margrid2.arff"); int numFiles = total_->getctrl("mrs_natural/numFiles")->to<mrs_natural>(); realvec som_in; realvec som_res; realvec som_fmatrix; multimap<std::string, realvec>::iterator it; mrs_natural total_onObservations = total_->getctrl("mrs_natural/onObservations")->to<mrs_natural>(); som_in.create(total_->getctrl("mrs_natural/inObservations")->to<mrs_natural>(), total_->getctrl("mrs_natural/inSamples")->to<mrs_natural>()); som_res.create(total_onObservations, total_->getctrl("mrs_natural/onSamples")->to<mrs_natural>()); som_fmatrix.create(total_onObservations+2, numFiles); // calculate features cout << "Calculating features" << endl; for (int index=0; index < numFiles; index++) { if(cancel_) { cancel_ = false; return; } total_->updctrl("mrs_natural/label", index); total_->updctrl("mrs_bool/memReset", true); total_->updctrl("mrs_natural/cindex", index); total_->process(som_in,som_res); string current = total_->getctrl("mrs_string/currentlyPlaying")->to<mrs_string>(); cout << "Processed " << index + 1 << " file of "<<numFiles<<" files" << endl; cout << current << "\n"; // hash the resulting feature on file name if(featureHash->find(current) == featureHash->end()) { featureHash->insert(pair<string,realvec>(current,som_res)); } for (int o=0; o < total_onObservations; o++) som_fmatrix(o, index) = som_res(o, 0); for (int o=total_onObservations; o< total_onObservations+2; o++) { som_fmatrix(o, index) = -1.0; } total_->updctrl("mrs_natural/advance", 1); } ofstream oss; oss.open("som_fmatrix.txt"); oss << som_fmatrix << endl; oss.close(); // normalize and create hashmap of normalized feature vectors on their file name realvec norm_som_fmatrix; // Normalize the feature matrix so that all features are between 0 and 1 norm_som_fmatrix.create(som_fmatrix.getRows(), som_fmatrix.getCols()); norm_ = mng.create("NormMaxMin", "norm"); norm_->updctrl("mrs_natural/inSamples", som_fmatrix.getCols()); norm_->updctrl("mrs_natural/inObservations", som_fmatrix.getRows()); norm_->updctrl("mrs_natural/ignoreLast", 3); norm_->updctrl("mrs_string/mode", "train"); norm_->process(som_fmatrix, norm_som_fmatrix); norm_->updctrl("mrs_string/mode", "predict"); norm_->process(som_fmatrix, norm_som_fmatrix); numFeatures = norm_->getctrl("mrs_natural/onObservations")->to<mrs_natural>(); // make the hashmap of filename and normalized feature vector ifstream inFeatureName; std::string featureName = ""; int counter = 0; realvec* normFeature = new realvec(); inFeatureName.open(filename.c_str()); getline(inFeatureName, featureName); while(inFeatureName) { norm_som_fmatrix.getCol(counter, *normFeature); if(normFeatureHash->find(featureName) == normFeatureHash->end()) normFeatureHash->insert(pair<string,realvec>(featureName, *normFeature)); getline(inFeatureName, featureName); counter++; } oss.open("norm_som_fmatrix.txt"); oss << norm_som_fmatrix << endl; oss.close(); ofstream noss; noss.open("norm.mpl"); noss << *norm_ << endl; noss.close(); delete norm_; /* Save the feature hash Each realvec is a separate file as it is the only way they can be loaded each file is named in the following pattern "featureVec" where X is an integer The file keys.txt holds space separated pairs of the hash key and the filename of the corresponding realvec NOTE: QT is used for platform independence. */ QDir dir; QFile *keys; QString keysFile; QString realvecFile; if(!dir.exists("extractFiles")) { dir.mkdir("extractFiles"); } dir.setCurrent("extractFiles"); keysFile = dir.filePath("keys.txt"); keys = new QFile(keysFile); if(keys->open(QIODevice::Truncate | QIODevice::ReadWrite )) { QTextStream txtStr(keys); int counter = 0; for ( it=normFeatureHash->begin() ; it != normFeatureHash->end(); it++ ) { // make the key entry txtStr << it->first.c_str(); txtStr << " "; txtStr << counter << endl; // open the realvec file and write the value std::stringstream stringStream; stringStream << "featureVec" << counter << ".hsh"; realvecFile = stringStream.str().c_str(); realvecFile = dir.filePath( realvecFile ); it->second.write( realvecFile.toStdString() ); counter++; } keys->close(); delete keys; dir.setCurrent(".."); } else { cerr << "Could not open keys.txt for writing"; } }
bool ConexaoBanco::BancoSqLite() { const QString sBarra = QDir::separator(); QString sCaminhoBanco; const QString sPastaBanco("Almoco"); QDir diretorio; //Quando testado no computador esse caminho não existe if( diretorio.exists( sBarra + "mnt" + sBarra + "sdcard" ) ) { sCaminhoBanco = sBarra + "mnt" + sBarra + "sdcard"; } else { sCaminhoBanco = sBarra + "sdcard" + sBarra; } diretorio.setCurrent( sCaminhoBanco ); if( !diretorio.exists( sPastaBanco ) ) { diretorio.mkdir( sPastaBanco ); } diretorio.setCurrent( sCaminhoBanco + sBarra + sPastaBanco ); //Verifica se precisa restaurar banco { if( diretorio.exists( "almocoRestaurar.db" ) ) { QFile restaurarBanco( sCaminhoBanco + sBarra + sPastaBanco + sBarra + "almocoRestaurar.db" ); QFile bancoAtual( sCaminhoBanco + sBarra + sPastaBanco + sBarra + "almoco.db" ); if( bancoAtual.exists() ) { if( !bancoAtual.remove() ) { Funcoes::MensagemAndroid( "Restaurar banco", "Remover arquivo\nDescriçao: " + bancoAtual.errorString() ); } } if( !restaurarBanco.rename( "almoco.db" ) ) { Funcoes::MensagemAndroid( "Renomear banco", "Descriçao: " + restaurarBanco.errorString() ); } } // else // { // Funcoes::MensagemAndroid( "Restarurar", "Nada para restaurar" ); // } } sCaminhoBanco.append( sBarra + sPastaBanco + sBarra + "almoco.db" ); db = QSqlDatabase::addDatabase( "QSQLITE", "almoco" ); db.setDatabaseName( sCaminhoBanco ); if( !db.open() ) { QMessageBox::warning( 0, "Erro", "Erro ao conectar no banco:\n" + db.lastError().text(), "ok"); return false; } bool conectou; QStringList Tabelas = db.tables(); int iQtdTabelas = Tabelas.size(); if( iQtdTabelas <= 1 ) { conectou = CriarTabelas( db ); } else { conectou = AtualizaEstruturaDoBanco(); } return conectou; }
void CrashHandler::attemptCrashsave() { QDir crashSave; crashSave.setCurrent(AppPathManager::userAppDir()); /* * For case if crash happened while ... attempt to load crashed files! * This avoids looping crashes because backup files are causing crash too! */ if(crashSave.exists("__crashsave")) { LogCriticalNC("We are detected that crash has been occouped on attempt to load or initialize backup files. Backup directory has been renamed into \"__crashsave_danger\"."); LogCriticalNC("Please attach all files in that directory and, if possible, additional contents (custom images, sounds, musics, configs and scripts) while reporting this crash."); QDir dupeDir(AppPathManager::userAppDir() + "/__crashsave_danger"); if(dupeDir.exists()) dupeDir.removeRecursively(); crashSave.rename("__crashsave", "__crashsave_danger"); return; } crashSave.mkdir("__crashsave"); crashSave.cd("__crashsave"); int untitledCounter = 0; MainWindow *mw = MainWinConnect::pMainWin; if(!mw) return; QList<QMdiSubWindow *> listOfAllSubWindows = mw->allEditWins(); for(QMdiSubWindow *subWin : listOfAllSubWindows) { if(mw->activeChildWindow(subWin) == MainWindow::WND_Level) { LevelEdit *lvledit = mw->activeLvlEditWin(subWin); if(!lvledit) continue; QString fName = lvledit->currentFile(); if(lvledit->isUntitled()) fName = QString("Untitled_Crash") + QString::number(untitledCounter++) + QString(".lvlx"); else fName = fName.section("/", -1) + QString(".lvlx"); LevelData &lvl = lvledit->LvlData; lvl.metaData.crash.used = true; lvl.metaData.crash.untitled = lvl.meta.untitled; lvl.metaData.crash.modifyed = lvl.meta.modified; lvl.metaData.crash.strictModeSMBX64 = lvl.meta.smbx64strict; lvl.metaData.crash.fmtID = lvl.meta.RecentFormat; lvl.metaData.crash.fmtVer = lvl.meta.RecentFormatVersion; lvl.metaData.crash.filename = lvl.meta.filename; lvl.metaData.crash.path = lvl.meta.path; lvl.metaData.crash.fullPath = lvledit->curFile; //Forcely save data into PGE-X format lvl.meta.RecentFormat = LevelData::PGEX; lvledit->saveFile(crashSave.absoluteFilePath(fName), false); } else if(mw->activeChildWindow(subWin) == MainWindow::WND_NpcTxt) { NpcEdit *npcedit = mw->activeNpcEditWin(subWin); if(!npcedit) continue; QString fName = npcedit->currentFile(); if(npcedit->isUntitled()) fName = QString("Untitled_Crash") + QString::number(untitledCounter++) + QString(".txt"); else fName = fName.section("/", -1); npcedit->saveFile(crashSave.absoluteFilePath(fName), false); } else if(mw->activeChildWindow(subWin) == MainWindow::WND_World) { WorldEdit *worldedit = mw->activeWldEditWin(subWin); if(!worldedit) continue; QString fName = worldedit->currentFile(); if(worldedit->isUntitled()) fName = QString("Untitled_Crash") + QString::number(untitledCounter++) + QString(".wldx"); else fName = fName.section("/", -1) + QString(".wldx"); WorldData &wld = worldedit->WldData; wld.metaData.crash.used = true; wld.metaData.crash.untitled = wld.meta.untitled; wld.metaData.crash.modifyed = wld.meta.modified; wld.metaData.crash.strictModeSMBX64 = wld.meta.smbx64strict; wld.metaData.crash.fmtID = wld.meta.RecentFormat; wld.metaData.crash.fmtVer = wld.meta.RecentFormatVersion; wld.metaData.crash.filename = wld.meta.filename; wld.metaData.crash.path = wld.meta.path; wld.metaData.crash.fullPath = worldedit->curFile; //Forcely save data into PGE-X format wld.meta.RecentFormat = WorldData::PGEX; worldedit->saveFile(crashSave.absoluteFilePath(fName), false); } } }
bool QZip::unzipRead() { QuaZip zip(_zipFileName); if(!zip.open(QuaZip::mdUnzip)) { qWarning("File Can't be Open:%s",_zipFileName.toLocal8Bit().data()); return false; } zip.setFileNameCodec("IBM866"); printf("%d entries\n", zip.getEntriesCount()); printf("Global comment: %s\n", zip.getComment().toLocal8Bit().constData()); QuaZipFileInfo info; printf("name\tcver\tnver\tflags\tmethod\tctime\tCRC\tcsize\tusize\tdisknum\tIA\tEA\tcomment\textra\n"); QuaZipFile file(&zip); QFile out; QString name; char c; for(bool more=zip.goToFirstFile(); more; more=zip.goToNextFile()) { if(!zip.getCurrentFileInfo(&info)) { qWarning("testRead(): getCurrentFileInfo(): %d\n", zip.getZipError()); return false; } printf("%s\t%hu\t%hu\t%hu\t%hu\t%s\t%u\t%u\t%u\t%hu\t%hu\t%u\t%s\t%s\n", info.name.toLocal8Bit().constData(), info.versionCreated, info.versionNeeded, info.flags, info.method, info.dateTime.toString(Qt::ISODate).toLocal8Bit().constData(), info.crc, info.compressedSize, info.uncompressedSize, info.diskNumberStart, info.internalAttr, info.externalAttr, info.comment.toLocal8Bit().constData(), info.extra.constData()); if(!file.open(QIODevice::ReadOnly)) { qWarning("testRead(): file.open(): %d", file.getZipError()); return false; } QStringList list; if(info.name.contains("\\")){ list = info.name.split("\\"); }else if(info.name.contains("/")){ list = info.name.split("/"); } QDir dir; dir.setCurrent(_zipPathName); QString tempDir = _zipPathName; for(int ccc=0;ccc<list.count()-1;ccc++){ tempDir+="\\"+list.at(ccc); if(!dir.exists(list.at(ccc))){ dir.mkdir(tempDir); } dir.setCurrent(tempDir); } name=file.getActualFileName(); if(file.getZipError()!=UNZ_OK) { qWarning("testRead(): file.getFileName(): %d", file.getZipError()); return false; } out.setFileName(_zipPathName+"\\"+name); // this will fail if "name" contains subdirectories, but we don't mind that out.open(QIODevice::WriteOnly); // Slow like hell (on GNU/Linux at least), but it is not my fault. // Not ZIP/UNZIP package's fault either. // The slowest thing here is out.putChar(c). while(file.getChar(&c)) out.putChar(c); out.close(); if(file.getZipError()!=UNZ_OK) { qWarning("testRead(): file.getFileName(): %d", file.getZipError()); return false; } if(!file.atEnd()) { qWarning("testRead(): read all but not EOF"); return false; } file.close(); if(file.getZipError()!=UNZ_OK) { qWarning("testRead(): file.close(): %d", file.getZipError()); return false; } } zip.close(); if(zip.getZipError()!=UNZ_OK) { qWarning("testRead(): zip.close(): %d", zip.getZipError()); return false; } return true; }