/*===========================================================================*/ bool GrADS::read( const std::string& filename ) { BaseClass::setFilename( filename ); BaseClass::setSuccess( true ); // Open file. std::ifstream ifs( filename.c_str(), std::ios::binary | std::ios::in ); if( !ifs.is_open() ) { kvsMessageError( "Cannot open %s.", filename.c_str() ); ifs.close(); BaseClass::setSuccess( false ); return false; } // Read control file. if ( !m_data_descriptor.read( ifs ) ) { kvsMessageError( "Cannot read control file." ); ifs.close(); BaseClass::setSuccess( false ); return false; } const bool sequential = m_data_descriptor.options().find( kvs::grads::Options::Sequential ); const bool big_endian = m_data_descriptor.options().find( kvs::grads::Options::BigEndian ); // Read binary file. (The data is not loaded into the memory) std::string data_pathname; std::string template_data_filename = m_data_descriptor.dset().name; const kvs::File template_data_file( template_data_filename ); if ( template_data_file.pathName() == template_data_file.pathName( true ) ) // absolute path { data_pathname = template_data_file.pathName(); } else { data_pathname = kvs::File( filename ).pathName(); if ( template_data_filename[0] == '^' ) { template_data_filename.erase( 0, 1 ); } } kvs::Directory directory( data_pathname ); kvs::grads::TDef tdef = m_data_descriptor.tdef(); const size_t tnum = m_data_descriptor.tdef().num; for ( size_t i = 0; i < tnum; ++i, ++tdef ) { std::string data_filename = template_data_filename; data_filename = ::ReplaceYear( data_filename, tdef.start.year ); data_filename = ::ReplaceMonth( data_filename, tdef.start.month ); data_filename = ::ReplaceDay( data_filename, tdef.start.day ); data_filename = ::ReplaceHour( data_filename, tdef.start.hour ); data_filename = ::ReplaceMinute( data_filename, tdef.start.minute ); kvs::FileList::const_iterator file = directory.fileList().begin(); kvs::FileList::const_iterator last = directory.fileList().end(); while ( file != last ) { if ( file->fileName() == data_filename ) { const std::string sep = kvs::File::Separator(); const std::string path = directory.directoryPath( true ); GriddedBinaryDataFile::Date date; date.year = tdef.start.year; date.month = tdef.start.month; date.day = tdef.start.day; date.hour = tdef.start.hour; date.minute = tdef.start.minute; GriddedBinaryDataFile data; data.setFilename( path + sep + data_filename ); data.setSequential( sequential ); data.setBigEndian( big_endian ); data.setDate( date ); m_data_list.push_back( data ); break; } ++file; } } return true; }
int main( int argc, char** argv) { std::string directory("/home/nick/competition/data/"); // Create a vector of strings pointing to the various // lists of categories std::vector<std::string> categories; categories.push_back(directory+"categories/DSFS.txt"); categories.push_back(directory+"categories/PrimaryConditionGroup.txt"); std::string dataFileY3(directory+"dsfspcgY3.csv"); std::string dataFileY2(directory+"pcgdsfsY2_dih.csv"); std::string dataFileY1(directory+"pcgdsfsY1_dih.csv"); // Create the parser pcgdsfs csvY1(dataFileY1,categories[0],categories[1]); pcgdsfs csvY2(dataFileY2,categories[0],categories[1]); pcgdsfsY3 csvY3(dataFileY3,categories[0],categories[1]); csvY1.combinations(); csvY1.parseFile(); csvY2.combinations(); csvY2.parseFile(); csvY3.combinations(); csvY3.parseFile(); std::vector<double> h0matY1 = csvY1.H0Matrix(); std::vector<double> h1matY1 = csvY1.H1Matrix(); std::vector<double> h0matY2 = csvY2.H0Matrix(); std::vector<double> h1matY2 = csvY2.H1Matrix(); // Determine the ratio std::vector<double> ratio; ratio.assign(h0matY1.size(),0.); double meanValue = 0; double nvalid = 0; for( size_t i = 0; i < ratio.size(); ++i) { double nMem = h0matY1[i] + h1matY1[i] + h0matY2[i] + h1matY2[i]; double h1mem = h1matY1[i] + h1matY2[i]; if( nMem > 100 ) { meanValue += h1mem/nMem; ratio[i] = h1mem/nMem; ++nvalid; } //else ratio[i] = -1; } meanValue /= nvalid; #if 0 for( size_t i = 0; i < ratio.size(); ++i) { if( ratio[i] < 0 ) ratio[i] = meanValue; } std::cout << "mean: " << meanValue << std::endl; #endif // Now create the metrics csvY1.createMetrics(ratio); csvY2.createMetrics(ratio); csvY3.createMetrics(ratio); csvY1.writeMetricsToFile(std::string("y1members.csv")); csvY2.writeMetricsToFile(std::string("y2members.csv")); csvY3.writeMetricsToFile(std::string("y3members.csv")); }
// Get the list of Address Books for the currently logged in user profile STDMETHODIMP CPalmSyncImp::nsGetABList(BOOL aIsUnicode, short * aABListCount, lpnsMozABDesc * aABList, long ** aABCatIndexList, BOOL ** aDirFlagsList) { if (!aABListCount || !aABList || !aABCatIndexList ||!aDirFlagsList) return E_FAIL; *aABListCount = 0; nsresult rv; nsCOMPtr<nsIAbManager> abManager(do_GetService(NS_ABMANAGER_CONTRACTID, &rv)); if (NS_FAILED(rv)) return E_FAIL; nsCOMPtr<nsISimpleEnumerator> subDirectories; if (NS_SUCCEEDED(abManager->GetDirectories(getter_AddRefs(subDirectories))) && subDirectories) { // Get the total number of addrbook. PRInt16 count=0; nsCOMPtr<nsISupports> item; PRBool hasMore; while (NS_SUCCEEDED(rv = subDirectories->HasMoreElements(&hasMore)) && hasMore) { if (NS_SUCCEEDED(subDirectories->GetNext(getter_AddRefs(item)))) { nsCOMPtr<nsIAbDirectory> directory(do_QueryInterface(item, &rv)); if (NS_SUCCEEDED(rv)) { nsCAutoString fileName; rv = directory->GetFileName(fileName); if(NS_FAILED(rv)) continue; PRInt32 dirType; rv = directory->GetDirType(&dirType); if(NS_FAILED(rv)) continue; PRBool disableThisAB; rv = directory->GetBoolValue("disablePalmSync", PR_FALSE, &disableThisAB); if (NS_FAILED(rv)) continue; // Skip/Ignore 4.X addrbooks (ie, with ".na2" extension), and non personal AB's if (disableThisAB || ((fileName.Length() > kABFileName_PreviousSuffixLen) && strcmp(fileName.get() + fileName.Length() - kABFileName_PreviousSuffixLen, kABFileName_PreviousSuffix) == 0) || (dirType != kPABDirectory && dirType != kMAPIDirectory)) continue; } } count++; } if (!count) return E_FAIL; // should not happen but just in case. lpnsMozABDesc serverDescList = (lpnsMozABDesc) CoTaskMemAlloc(sizeof(nsMozABDesc) * count); BOOL *dirFlagsList = (BOOL *) CoTaskMemAlloc(sizeof(BOOL) * count); long *catIndexList = (long *) CoTaskMemAlloc(sizeof(long) * count); *aABListCount = count; *aABList = serverDescList; *aDirFlagsList = dirFlagsList; *aABCatIndexList = catIndexList; // reset enumerator if (NS_FAILED(abManager->GetDirectories(getter_AddRefs(subDirectories)))) return E_FAIL; // For each valid addrbook collect info. while (NS_SUCCEEDED(rv = subDirectories->HasMoreElements(&hasMore)) && hasMore) { if (NS_SUCCEEDED(subDirectories->GetNext(getter_AddRefs(item)))) { nsCOMPtr<nsIAbDirectory> directory(do_QueryInterface(item, &rv)); if (NS_SUCCEEDED(rv)) { // We don't have to skip mailing list since there's no mailing lists at the top level. nsCAutoString fileName; nsCAutoString uri; nsString description; PRUint32 palmSyncTimeStamp; PRInt32 dirType, palmCategoryIndex; rv = directory->GetDescription(description); if(NS_FAILED(rv)) return E_FAIL; rv = directory->GetFileName(fileName); if(NS_FAILED(rv)) return E_FAIL; rv = directory->GetURI(uri); if(NS_FAILED(rv)) return E_FAIL; rv = directory->GetDirType(&dirType); if(NS_FAILED(rv)) return E_FAIL; rv = directory->GetIntValue("PalmCategoryId", -1, &palmCategoryIndex); if (NS_FAILED(rv)) return E_FAIL; rv = directory->GetIntValue("PalmSyncTimeStamp", 0, (PRInt32*)&palmSyncTimeStamp); if (NS_FAILED(rv)) return E_FAIL; PRBool disableThisAB; rv = directory->GetBoolValue("disablePalmSync", PR_FALSE, &disableThisAB); if (NS_FAILED(rv)) return E_FAIL; // Skip/Ignore 4.X addrbooks (ie, with ".na2" extension), and non personal AB's if (disableThisAB || ((fileName.Length() > kABFileName_PreviousSuffixLen) && strcmp(fileName.get() + fileName.Length() - kABFileName_PreviousSuffixLen, kABFileName_PreviousSuffix) == 0) || (dirType != kPABDirectory && dirType != kMAPIDirectory)) { continue; } if(aIsUnicode) { // convert uri to Unicode nsAutoString abUrl; rv = ConvertToUnicode("UTF-8", uri, abUrl); if (NS_FAILED(rv)) break; // add to the list CopyUnicodeString(&(serverDescList->lpszABName), description); CopyUnicodeString(&(serverDescList->lpszABUrl), abUrl); } else { // we need to convert uri to Unicode and then to ASCII nsAutoString abUUrl; rv = ConvertToUnicode("UTF-8", uri, abUUrl); if (NS_FAILED(rv)) break; CopyCString(&(serverDescList->lpszABName), NS_ConvertUTF16toUTF8(description)); CopyCString(&(serverDescList->lpszABUrl), NS_ConvertUTF16toUTF8(abUUrl)); } serverDescList++; PRUint32 dirFlag = 0; if (palmSyncTimeStamp <= 0) dirFlag |= kFirstTimeSyncDirFlag; // was this the pab? nsCAutoString prefName; rv = directory->GetDirPrefId(prefName); if (NS_FAILED(rv)) break; if (prefName.Equals("ldap_2.servers.pab")) dirFlag |= kIsPabDirFlag; *dirFlagsList = (BOOL) dirFlag; dirFlagsList++; *catIndexList = palmCategoryIndex; catIndexList++; } } } // assign member variables to the beginning of the list serverDescList = *aABList; dirFlagsList = *aDirFlagsList; catIndexList = *aABCatIndexList; if(NS_FAILED(rv)) return E_FAIL; } return S_OK; }
void wrapInFunction() { //! [0] QDir("/home/user/Documents") QDir("C:/Documents and Settings") //! [0] //! [1] QDir("images/landscape.png") //! [1] //! [2] QDir("Documents/Letters/Applications").dirName() // "Applications" QDir().dirName() // "." //! [2] //! [3] QDir directory("Documents/Letters"); QString path = directory.filePath("contents.txt"); QString absolutePath = directory.absoluteFilePath("contents.txt"); //! [3] //! [4] QDir dir("example"); if (!dir.exists()) qWarning("Cannot find the example directory"); //! [4] //! [5] QDir dir = QDir::root(); // "/" if (!dir.cd("tmp")) { // "/tmp" qWarning("Cannot find the \"/tmp\" directory"); } else { QFile file(dir.filePath("ex1.txt")); // "/tmp/ex1.txt" if (!file.open(QIODevice::ReadWrite)) qWarning("Cannot create the file %s", file.name()); } //! [5] //! [6] QString bin = "/local/bin"; // where /local/bin is a symlink to /usr/bin QDir binDir(bin); QString canonicalBin = binDir.canonicalPath(); // canonicalBin now equals "/usr/bin" QString ls = "/local/bin/ls"; // where ls is the executable "ls" QDir lsDir(ls); QString canonicalLs = lsDir.canonicalPath(); // canonicalLS now equals "/usr/bin/ls". //! [6] //! [7] QDir dir("/home/bob"); QString s; s = dir.relativeFilePath("images/file.jpg"); // s is "images/file.jpg" s = dir.relativeFilePath("/home/mary/file.txt"); // s is "../mary/file.txt" //! [7] //! [8] QDir::setSearchPaths("icons", QStringList(QDir::homePath() + "/images")); QDir::setSearchPaths("docs", QStringList(":/embeddedDocuments")); ... QPixmap pixmap("icons:undo.png"); // will look for undo.png in QDir::homePath() + "/images" QFile file("docs:design.odf"); // will look in the :/embeddedDocuments resource path //! [8] //! [9] QDir dir("/tmp/root_link"); dir = dir.canonicalPath(); if (dir.isRoot()) qWarning("It is a root link"); //! [9] //! [10] // The current directory is "/usr/local" QDir d1("/usr/local/bin"); QDir d2("bin"); if (d1 == d2) qDebug("They're the same"); //! [10] //! [11] // The current directory is "/usr/local" QDir d1("/usr/local/bin"); d1.setFilter(QDir::Executable); QDir d2("bin"); if (d1 != d2) qDebug("They differ"); //! [11] //! [12] C:/Documents and Settings/Username //! [12] //! [13] Q_INIT_RESOURCE(myapp); //! [13] //! [14] inline void initMyResource() { Q_INIT_RESOURCE(myapp); }
Library::Library(QObject* parent, UserSettingsPointer pConfig, PlayerManagerInterface* pPlayerManager, RecordingManager* pRecordingManager) : m_pConfig(pConfig), m_pSidebarModel(new SidebarModel(parent)), m_pTrackCollection(new TrackCollection(pConfig)), m_pLibraryControl(new LibraryControl(this)), m_pRecordingManager(pRecordingManager), m_scanner(m_pTrackCollection, pConfig) { qRegisterMetaType<Library::RemovalType>("Library::RemovalType"); m_pKeyNotation.reset(new ControlObject(ConfigKey("[Library]", "key_notation"))); connect(&m_scanner, SIGNAL(scanStarted()), this, SIGNAL(scanStarted())); connect(&m_scanner, SIGNAL(scanFinished()), this, SIGNAL(scanFinished())); // Refresh the library models when the library (re)scan is finished. connect(&m_scanner, SIGNAL(scanFinished()), this, SLOT(slotRefreshLibraryModels())); // TODO(rryan) -- turn this construction / adding of features into a static // method or something -- CreateDefaultLibrary m_pMixxxLibraryFeature = new MixxxLibraryFeature(this, m_pTrackCollection,m_pConfig); addFeature(m_pMixxxLibraryFeature); addFeature(new AutoDJFeature(this, pConfig, pPlayerManager, m_pTrackCollection)); m_pPlaylistFeature = new PlaylistFeature(this, m_pTrackCollection, m_pConfig); addFeature(m_pPlaylistFeature); m_pCrateFeature = new CrateFeature(this, m_pTrackCollection, m_pConfig); addFeature(m_pCrateFeature); BrowseFeature* browseFeature = new BrowseFeature( this, pConfig, m_pTrackCollection, m_pRecordingManager); connect(browseFeature, SIGNAL(scanLibrary()), &m_scanner, SLOT(scan())); connect(&m_scanner, SIGNAL(scanStarted()), browseFeature, SLOT(slotLibraryScanStarted())); connect(&m_scanner, SIGNAL(scanFinished()), browseFeature, SLOT(slotLibraryScanFinished())); addFeature(browseFeature); addFeature(new RecordingFeature(this, pConfig, m_pTrackCollection, m_pRecordingManager)); addFeature(new SetlogFeature(this, pConfig, m_pTrackCollection)); m_pAnalysisFeature = new AnalysisFeature(this, pConfig, m_pTrackCollection); connect(m_pPlaylistFeature, SIGNAL(analyzeTracks(QList<TrackId>)), m_pAnalysisFeature, SLOT(analyzeTracks(QList<TrackId>))); connect(m_pCrateFeature, SIGNAL(analyzeTracks(QList<TrackId>)), m_pAnalysisFeature, SLOT(analyzeTracks(QList<TrackId>))); addFeature(m_pAnalysisFeature); //iTunes and Rhythmbox should be last until we no longer have an obnoxious //messagebox popup when you select them. (This forces you to reach for your //mouse or keyboard if you're using MIDI control and you scroll through them...) if (RhythmboxFeature::isSupported() && pConfig->getValueString(ConfigKey("[Library]","ShowRhythmboxLibrary"),"1").toInt()) { addFeature(new RhythmboxFeature(this, m_pTrackCollection)); } if (pConfig->getValueString(ConfigKey("[Library]","ShowBansheeLibrary"),"1").toInt()) { BansheeFeature::prepareDbPath(pConfig); if (BansheeFeature::isSupported()) { addFeature(new BansheeFeature(this, m_pTrackCollection, pConfig)); } } if (ITunesFeature::isSupported() && pConfig->getValueString(ConfigKey("[Library]","ShowITunesLibrary"),"1").toInt()) { addFeature(new ITunesFeature(this, m_pTrackCollection)); } if (TraktorFeature::isSupported() && pConfig->getValueString(ConfigKey("[Library]","ShowTraktorLibrary"),"1").toInt()) { addFeature(new TraktorFeature(this, m_pTrackCollection)); } // On startup we need to check if all of the user's library folders are // accessible to us. If the user is using a database from <1.12.0 with // sandboxing then we will need them to give us permission. QStringList directories = m_pTrackCollection->getDirectoryDAO().getDirs(); qDebug() << "Checking for access to user's library directories:"; foreach (QString directoryPath, directories) { QFileInfo directory(directoryPath); bool hasAccess = Sandbox::askForAccess(directory.canonicalFilePath()); qDebug() << "Checking for access to" << directoryPath << ":" << hasAccess; }
int main(int argc, char** argv) { // initialize guacamole gua::init(argc, argv); // setup scene gua::SceneGraph graph("main_scenegraph"); gua::math::vec4 iron(0.560, 0.570, 0.580, 1); gua::math::vec4 silver(0.972, 0.960, 0.915, 1); gua::math::vec4 aluminium(0.913, 0.921, 0.925, 1); gua::math::vec4 gold(1.000, 0.766, 0.336, 1); gua::math::vec4 copper(0.955, 0.637, 0.538, 1); gua::math::vec4 chromium(0.550, 0.556, 0.554, 1); gua::math::vec4 nickel(0.660, 0.609, 0.526, 1); gua::math::vec4 titanium(0.542, 0.497, 0.449, 1); gua::math::vec4 cobalt(0.662, 0.655, 0.634, 1); gua::math::vec4 platinum(0.672, 0.637, 0.585, 1); auto pbrMat(gua::MaterialShaderDatabase::instance()->lookup("gua_default_material")->make_new_material()); // pbrMat.set_uniform("Color", chromium); // pbrMat.set_uniform("Roughness", 0.2f); // pbrMat.set_uniform("Metalness", 1.0f); std::string directory("/opt/3d_models/Cerberus_by_Andrew_Maximov/Textures/"); pbrMat->set_uniform("ColorMap", directory + "Cerberus_A.tga"); pbrMat->set_uniform("MetalnessMap", directory + "Cerberus_M.tga"); pbrMat->set_uniform("RoughnessMap", directory + "Cerberus_R.tga"); pbrMat->set_uniform("NormalMap", directory + "Cerberus_N.negated_green.tga"); gua::TriMeshLoader loader; auto transform = graph.add_node<gua::node::TransformNode>("/", "transform"); auto cerberus(loader.create_geometry_from_file( "cerberus", "/opt/3d_models/Cerberus_by_Andrew_Maximov/Cerberus_LP.3ds", pbrMat, gua::TriMeshLoader::NORMALIZE_POSITION | gua::TriMeshLoader::NORMALIZE_SCALE)); graph.add_node("/transform", cerberus); cerberus->set_draw_bounding_box(true); cerberus->rotate(90, 0.f, 1.f, 0.f); cerberus->rotate(90, 0.f, 0.f, 1.f); auto pointLight = graph.add_node<gua::node::LightNode>("/", "pointLight"); pointLight->data.set_type(gua::node::LightNode::Type::POINT); pointLight->data.color = gua::utils::Color3f(1.0f, 1.0f, 1.0f); pointLight->data.brightness = 150.0f; // lm pointLight->scale(9.f); pointLight->translate(-2.f, 3.f, 5.f); auto screen = graph.add_node<gua::node::ScreenNode>("/", "screen"); screen->data.set_size(gua::math::vec2(1.92f, 1.08f)); screen->translate(0, 0, 1.0); // add mouse interaction gua::utils::Trackball trackball(0.01, 0.002, 0.2); // setup rendering pipeline and window // auto resolution = gua::math::vec2ui(1920, 1080); auto resolution = gua::math::vec2ui(2560, 1440); std::string skymaps_dir("/opt/guacamole/resources/skymaps/"); for(auto const& file : {std::string(directory + "Cerberus_A.tga"), std::string(directory + "Cerberus_M.tga"), std::string(directory + "Cerberus_R.tga"), std::string(directory + "Cerberus_N.negated_green.tga"), std::string(skymaps_dir + "skymap.jpg")}) { gua::TextureDatabase::instance()->load(file); } auto tiledPipe(std::make_shared<gua::PipelineDescription>()); tiledPipe->add_pass(std::make_shared<gua::TriMeshPassDescription>()); tiledPipe->add_pass(std::make_shared<gua::LightVisibilityPassDescription>()); tiledPipe->add_pass(std::make_shared<gua::ResolvePassDescription>()); auto camera = graph.add_node<gua::node::CameraNode>("/screen", "cam"); camera->translate(0, 0, 2.0); camera->config.set_resolution(resolution); camera->config.set_screen_path("/screen"); camera->config.set_scene_graph_name("main_scenegraph"); camera->config.set_output_window_name("main_window"); camera->config.set_enable_stereo(false); camera->set_pipeline_description(tiledPipe); auto window = std::make_shared<gua::GlfwWindow>(); gua::WindowDatabase::instance()->add("main_window", window); window->config.set_enable_vsync(false); window->config.set_size(resolution); window->config.set_resolution(resolution); window->config.set_stereo_mode(gua::StereoMode::MONO); window->on_resize.connect([&](gua::math::vec2ui const& new_size) { window->config.set_resolution(new_size); camera->config.set_resolution(new_size); screen->data.set_size(gua::math::vec2(0.001 * new_size.x, 0.001 * new_size.y)); }); window->on_move_cursor.connect([&](gua::math::vec2 const& pos) { trackball.motion(pos.x, pos.y); }); window->on_button_press.connect(std::bind(mouse_button, std::ref(trackball), std::placeholders::_1, std::placeholders::_2, std::placeholders::_3)); window->open(); gua::Renderer renderer; // application loop gua::events::MainLoop loop; gua::events::Ticker ticker(loop, 1.0 / 500.0); size_t ctr{}; ticker.on_tick.connect([&]() { // apply trackball matrix to object gua::math::mat4 modelmatrix = scm::math::make_translation(gua::math::float_t(trackball.shiftx()), gua::math::float_t(trackball.shifty()), gua::math::float_t(trackball.distance())) * gua::math::mat4(trackball.rotation()); transform->set_transform(modelmatrix); if(ctr++ % 150 == 0) gua::Logger::LOG_WARNING << "Frame time: " << 1000.f / window->get_rendering_fps() << " ms, fps: " << window->get_rendering_fps() << std::endl; window->process_events(); if(window->should_close()) { renderer.stop(); window->close(); loop.stop(); } else { renderer.queue_draw({&graph}); } }); loop.start(); return 0; }
void ImageFileManger::ProcessFiles() { if (!this->InputFileList.isEmpty()) { QDir directory(this->imageDir); for (int k = 0; k < this->outputDirectories.size(); k++) { directory.mkdir(this->outputDirectories[k]); } QProgressDialog progress("Converting Images", "Abort", 0, this->InputFileList.size(), this); progress.setWindowModality(Qt::WindowModal); for (int i = 0; i < this->InputFileList.size(); i++) { progress.setValue(i); if (progress.wasCanceled()) { break; } QString currentDir; currentDir.clear(); QString tempname = QFileInfo(this->InputFileList[i]).fileName(); for (int j = 0; j < this->outputDirectories.size(); j++) { if (tempname.contains(this->outputDirectories.at(j), Qt::CaseInsensitive)) { currentDir = this->outputDirectories.at(j); }//end search } if (currentDir.isEmpty()) { continue; } tempname.replace(" ", "_"); tempname.prepend("8Bit"); QString outputFilename = QString(this->imageDir +"/"+ currentDir +"/"+tempname); InputReaderType::Pointer reader = InputReaderType::New(); OutputWriterType::Pointer writer = OutputWriterType::New(); reader->SetFileName(this->InputFileList[i].toStdString().c_str()); //16 to 8 bit conversion RescaleFilterType::Pointer rescaleFilter = RescaleFilterType::New(); rescaleFilter->SetInput(reader->GetOutput()); rescaleFilter->SetOutputMinimum(0); rescaleFilter->SetOutputMaximum(255); rescaleFilter->Update(); preprocessdialog->SetImage( rescaleFilter->GetOutput() ); writer->SetFileName(outputFilename.toStdString().c_str()); try { preprocessdialog->Process(); writer->SetInput(preprocessdialog->GetImage()); writer->Update(); } catch(itk::ExceptionObject & e) { std::cerr << "Exception in ITK Pipeline: " << e << std::endl; continue; } } progress.setValue(this->InputFileList.size()); } }
//----------------------------------------------------------------------------- //! //----------------------------------------------------------------------------- void tFilepathSelector::UpdateList() { m_FilePathList.clear(); m_FriendlyFilepathList.clear(); m_DisplayList.clear(); m_pListWidget->clear(); // First add the NONE option, No need to translate (appears in settings.ini) m_FilePathList << "None"; m_FriendlyFilepathList << "None"; m_DisplayList << "None"; int currentRow = 0; // setCurrentRow to the currentFile // Add files from all locations for (int i = 0; i < m_PathAndDirNameList.size(); ++i) { tPathAndDirname pathAndDirname = m_PathAndDirNameList.at(i); QDir directory(pathAndDirname.Path(), "", m_SortFlags, m_Filters); directory.setNameFilters(m_NameFilters); QFileInfoList fileInfoList = directory.entryInfoList(); for (int j = 0; j < fileInfoList.size(); ++j) { QFileInfo fileInfo = fileInfoList.at(j); // Add the real filepath string to our list m_FilePathList.append(fileInfo.filePath()); // Add the user displayed filepath e.g. "Sonar.sl2 (factory)" const QString dirname = pathAndDirname.DirName(); QString friendlyFilepath; if (dirname.isEmpty()) { friendlyFilepath = fileInfo.fileName(); m_FriendlyFilepathList.append(friendlyFilepath); } else { friendlyFilepath = QString("%1 (%2)").arg(fileInfo.fileName()).arg(dirname); m_FriendlyFilepathList.append(friendlyFilepath); // compare currentFile to path and set currentRow if there is an exact match if (friendlyFilepath.compare(m_CurrentFile) == 0) { currentRow = j + 1; } } if (m_ShowFileSize) { QString item = QString("%1 (%2)").arg(friendlyFilepath).arg(FormatSize(fileInfo.size())); m_DisplayList << item; } else { m_DisplayList << friendlyFilepath; } } } m_pListWidget->addItems(m_DisplayList); if (m_CurrentFile.isEmpty()) { m_pListWidget->setCurrentRow(0); } else { m_pListWidget->setCurrentRow(currentRow); } }
void NetworkWindow::_ScanAddOns() { BStringList paths; BPathFinder::FindPaths(B_FIND_PATH_ADD_ONS_DIRECTORY, "Network Settings", paths); // Collect add-on paths by name, so that each name will only be // loaded once. typedef std::map<BString, BPath> PathMap; PathMap addOnMap; for (int32 i = 0; i < paths.CountStrings(); i++) { BDirectory directory(paths.StringAt(i)); BEntry entry; while (directory.GetNextEntry(&entry) == B_OK) { BPath path; if (entry.GetPath(&path) != B_OK) continue; if (addOnMap.find(path.Leaf()) == addOnMap.end()) addOnMap.insert(std::pair<BString, BPath>(path.Leaf(), path)); } } for (PathMap::const_iterator addOnIterator = addOnMap.begin(); addOnIterator != addOnMap.end(); addOnIterator++) { const BPath& path = addOnIterator->second; image_id image = load_add_on(path.Path()); if (image < 0) { printf("Failed to load %s addon: %s.\n", path.Path(), strerror(image)); continue; } BNetworkSettingsAddOn* (*instantiateAddOn)(image_id image, BNetworkSettings& settings); status_t status = get_image_symbol(image, "instantiate_network_settings_add_on", B_SYMBOL_TYPE_TEXT, (void**)&instantiateAddOn); if (status != B_OK) { // No "addon instantiate function" symbol found in this addon printf("No symbol \"instantiate_network_settings_add_on\" found " "in %s addon: not a network setup addon!\n", path.Path()); unload_add_on(image); continue; } BNetworkSettingsAddOn* addOn = instantiateAddOn(image, fSettings); if (addOn == NULL) { unload_add_on(image); continue; } fAddOns.AddItem(addOn); // Per interface items ItemMap::const_iterator iterator = fInterfaceItemMap.begin(); for (; iterator != fInterfaceItemMap.end(); iterator++) { const BString& interface = iterator->first; BListItem* interfaceItem = iterator->second; uint32 cookie = 0; while (true) { BNetworkSettingsItem* item = addOn->CreateNextInterfaceItem( cookie, interface.String()); if (item == NULL) break; fSettingsMap[item->ListItem()] = item; fListView->AddUnder(item->ListItem(), interfaceItem); } fListView->SortItemsUnder(interfaceItem, true, NetworkWindow::_CompareListItems); } // Generic items uint32 cookie = 0; while (true) { BNetworkSettingsItem* item = addOn->CreateNextItem(cookie); if (item == NULL) break; fSettingsMap[item->ListItem()] = item; fListView->AddUnder(item->ListItem(), _ListItemFor(item->Type())); } _SortItemsUnder(fServicesItem); _SortItemsUnder(fDialUpItem); _SortItemsUnder(fOtherItem); } fListView->SortItemsUnder(NULL, true, NetworkWindow::_CompareTopLevelListItems); }
/*! \brief Factory function resembling directory(url, int) constructor */ static directory create(saga::url const& url, int mode = Read) { return directory(url, mode); }
void web(int fd, int hit) { int j, file_fd, buflen, len; long i, ret; char * fstr; //buffer is the whole file path static char buffer[BUFSIZE+1]; /* static so zero filled */ struct stat st; ret =read(fd,buffer,BUFSIZE); /* read Web request in one go */ if(ret == 0 || ret == -1) { /* read failure stop now */ log(SORRY,"failed to read browser request","",fd); } if(ret > 0 && ret < BUFSIZE) /* return code is valid chars */ buffer[ret]=0; /* terminate the buffer */ else buffer[0]=0; for(i=0;i<ret;i++) /* remove CF and LF characters */ if(buffer[i] == '\r' || buffer[i] == '\n') buffer[i]='*'; log(LOG,"request",buffer,hit); if( strncmp(buffer,"GET ",4) && strncmp(buffer,"get ",4) ) log(SORRY,"Only simple GET operation supported",buffer,fd); for(i=4;i<BUFSIZE;i++) { /* null terminate after the second space to ignore extra stuff */ if(buffer[i] == ' ') { /* string is "GET URL " +lots of other stuff */ buffer[i] = 0; break; } } for(j=0;j<i-1;j++) /* check for illegal parent directory use .. */ if(buffer[j] == '.' && buffer[j+1] == '.') log(SORRY,"Parent directory (..) path names not supported",buffer,fd); if( !strncmp(&buffer[0],"GET /\0",6) || !strncmp(&buffer[0], "get /\0",6) ) /* convert no filename to index file */ (void)strcpy(buffer,"GET /index.html"); /* work out the file type and check we support it */ buflen=strlen(buffer); fstr = (char *)0; for(i=0;extensions1[i].ext != 0;i++) { len = strlen(extensions1[i].ext); if( !strncmp(&buffer[buflen-len], extensions1[i].ext, len)) { fstr =extensions1[i].filetype; break; } } if((stat((&buffer[buflen-len]), st))==0) fstr =1; else log(SORRY,"file extension type not supported", buffer, fd); /*if(fstr == 0) log(SORRY,"file extension type not supported", buffer,fd);*/ if((file_fd = open(&buffer[5],O_RDONLY)) == -1) /* open the file for reading */ { log(SORRY, "failed to open file",&buffer[5],fd); status(404, &buffer[5], fd); directory("/home/alex/ByteHTTP", fd); } log(LOG,"SEND",&buffer[5],hit); if(!(strncmp(&buffer[buflen-len], "php", 3)==-1)) { char *fp = &buffer[4]; // "/test.php" getPHP(fp, fd); } if(!(file_fd = open(&buffer[5],O_RDONLY)) == -1) { (void)sprintf(buffer,"HTTP/1.0 200 OK\r\nContent-Type: %s\r\n\r\n", fstr); //(void)write(fd,buffer,strlen(buffer)); } if((strncmp(&buffer[buflen-len], "php", 3) == -1)){ while ( ((ret = read(file_fd, buffer, BUFSIZE)) > 0 )) { (void)write(fd,buffer,ret); } } /* send file in 8KB block - last block may be smaller */ #ifdef LINUX sleep(1); /* to allow socket to drain */ #endif exit(1); }
/*! \brief Factory function resembling directory(session, url, int) * constructor */ static directory create(session const& s, saga::url const& url, int mode = Read) { return directory(s, url, mode); }
QDir PluginManager::pluginDirectory() { QDir directory(QiiPayload::instance()->location()); return directory; }
int main(int argc, char* argv[]) { if (argc < 2) { std::cerr << "Error: no file given\n"; print_usage(argv[0]); return EXIT_FAILURE; } // include paths std::vector<std::string> paths; std::string file_name, target_name, output_file; bool ignore_non_existing = true; // -MG bool add_empty_phony_targets = false; // -MP for (int i = 1; i < argc; i++) { const std::string arg(argv[i]); if (starts_with(arg, "-I") && arg.length() > 2) { paths.push_back(arg.substr(2)); continue; } if (arg == "-MG") { ignore_non_existing = false; continue; } if (arg == "-MM") { // ignore headers from system directories (default) continue; } if (arg == "-M") { std::cerr << "Warning: ignoring unsupported option " << arg << '\n'; continue; } if (arg == "-MD" || arg == "-MQ") { std::cerr << "Warning: ignoring unsupported option " << arg << '\n'; i++; continue; } if (arg == "-MP") { add_empty_phony_targets = true; continue; } if (arg == "-MT" && i + 1 < argc) { target_name = argv[++i]; continue; } if ((arg == "-MF" || arg == "-MMD" || arg == "-o") && i + 1 < argc) { output_file = argv[++i]; continue; } if (arg == "--help" || arg == "-h") { print_usage(argv[0]); return EXIT_SUCCESS; } // interpret last argument as file name if (i + 1 == argc) { file_name = arg; if (!file_exists(file_name)) { std::cerr << "Error: file does not exist: " << file_name << '\n'; return EXIT_FAILURE; } continue; } std::cerr << "Error: unknown option: " << arg << '\n'; print_usage(argv[0]); return EXIT_FAILURE; } // select output stream std::ofstream fstr(output_file); std::ostream* ostr = &std::cout; if (!output_file.empty()) { if (!fstr.good()) { std::cerr << "Error: cannot write to file " << output_file << '\n'; return EXIT_FAILURE; } ostr = &fstr; } // include paths paths.insert(paths.begin(), directory(file_name)); paths.push_back("."); paths = delete_duplicates(paths); // search for header inclusions in file const std::vector<std::string> dependencies = delete_duplicates( search_includes(file_name, paths, ignore_non_existing), Is_not_duplicate_ignore_path()); // prepend file itself to dependency list std::vector<std::string> dependencies_and_main(dependencies); dependencies_and_main.insert(dependencies_and_main.begin(), file_name); if (target_name.empty()) target_name = replace_extension(filename(file_name), "o"); // output print_dependencies(target_name, dependencies_and_main, *ostr); if (add_empty_phony_targets) print_empty_phony_targets(dependencies, *ostr); return EXIT_SUCCESS; }
void KeymapWindow::MessageReceived(BMessage* message) { switch (message->what) { case B_SIMPLE_DATA: case B_REFS_RECEIVED: { entry_ref ref; int32 i = 0; while (message->FindRef("refs", i++, &ref) == B_OK) { fCurrentMap.Load(ref); fAppliedMap = fCurrentMap; } fKeyboardLayoutView->SetKeymap(&fCurrentMap); fSystemListView->DeselectAll(); fUserListView->DeselectAll(); break; } case B_SAVE_REQUESTED: { entry_ref ref; const char* name; if (message->FindRef("directory", &ref) == B_OK && message->FindString("name", &name) == B_OK) { BDirectory directory(&ref); BEntry entry(&directory, name); entry.GetRef(&ref); fCurrentMap.SetName(name); fCurrentMap.Save(ref); fAppliedMap = fCurrentMap; _FillUserMaps(); fCurrentMapName = name; _SelectCurrentMap(); } break; } case kMsgMenuFileOpen: fOpenPanel->Show(); break; case kMsgMenuFileSaveAs: fSavePanel->Show(); break; case kMsgShowModifierKeysWindow: be_app->PostMessage(kMsgShowModifierKeysWindow); break; case kChangeKeyboardLayout: { entry_ref ref; BPath path; if (message->FindRef("ref", &ref) == B_OK) path.SetTo(&ref); _SetKeyboardLayout(path.Path()); break; } case kMsgSwitchShortcuts: _SwitchShortcutKeys(); break; case kMsgMenuFontChanged: { BMenuItem* item = fFontMenu->FindMarked(); if (item != NULL) { BFont font; font.SetFamilyAndStyle(item->Label(), NULL); fKeyboardLayoutView->SetBaseFont(font); fTextControl->TextView()->SetFontAndColor(&font); } break; } case kMsgSystemMapSelected: case kMsgUserMapSelected: { BListView* listView; BListView* otherListView; if (message->what == kMsgSystemMapSelected) { listView = fSystemListView; otherListView = fUserListView; } else { listView = fUserListView; otherListView = fSystemListView; } int32 index = listView->CurrentSelection(); if (index < 0) break; // Deselect item in other BListView otherListView->DeselectAll(); if (index == 0 && listView == fUserListView) { // we can safely ignore the "(Current)" item break; } KeymapListItem* item = static_cast<KeymapListItem*>(listView->ItemAt(index)); if (item != NULL) { fCurrentMap.Load(item->EntryRef()); fAppliedMap = fCurrentMap; fKeyboardLayoutView->SetKeymap(&fCurrentMap); _UseKeymap(); _UpdateButtons(); } break; } case kMsgDefaultKeymap: _DefaultKeymap(); _UpdateButtons(); break; case kMsgRevertKeymap: _RevertKeymap(); _UpdateButtons(); break; case kMsgUpdateNormalKeys: { uint32 keyCode; if (message->FindUInt32("keyCode", &keyCode) != B_OK) break; bool unset; if (message->FindBool("unset", &unset) == B_OK && unset) { fCurrentMap.SetKey(keyCode, modifiers(), 0, "", 0); _UpdateButtons(); fKeyboardLayoutView->SetKeymap(&fCurrentMap); } break; } case kMsgUpdateModifierKeys: { uint32 keyCode; bool unset; if (message->FindBool("unset", &unset) != B_OK) unset = false; if (message->FindUInt32("left_shift_key", &keyCode) == B_OK) { fCurrentMap.SetModifier(unset ? 0x00 : keyCode, B_LEFT_SHIFT_KEY); } if (message->FindUInt32("right_shift_key", &keyCode) == B_OK) { fCurrentMap.SetModifier(unset ? 0x00 : keyCode, B_RIGHT_SHIFT_KEY); } if (message->FindUInt32("left_control_key", &keyCode) == B_OK) { fCurrentMap.SetModifier(unset ? 0x00 : keyCode, B_LEFT_CONTROL_KEY); } if (message->FindUInt32("right_control_key", &keyCode) == B_OK) { fCurrentMap.SetModifier(unset ? 0x00 : keyCode, B_RIGHT_CONTROL_KEY); } if (message->FindUInt32("left_option_key", &keyCode) == B_OK) { fCurrentMap.SetModifier(unset ? 0x00 : keyCode, B_LEFT_OPTION_KEY); } if (message->FindUInt32("right_option_key", &keyCode) == B_OK) { fCurrentMap.SetModifier(unset ? 0x00 : keyCode, B_RIGHT_OPTION_KEY); } if (message->FindUInt32("left_command_key", &keyCode) == B_OK) { fCurrentMap.SetModifier(unset ? 0x00 : keyCode, B_LEFT_COMMAND_KEY); } if (message->FindUInt32("right_command_key", &keyCode) == B_OK) { fCurrentMap.SetModifier(unset ? 0x00 : keyCode, B_RIGHT_COMMAND_KEY); } if (message->FindUInt32("menu_key", &keyCode) == B_OK) fCurrentMap.SetModifier(unset ? 0x00 : keyCode, B_MENU_KEY); if (message->FindUInt32("caps_key", &keyCode) == B_OK) fCurrentMap.SetModifier(unset ? 0x00 : keyCode, B_CAPS_LOCK); if (message->FindUInt32("num_key", &keyCode) == B_OK) fCurrentMap.SetModifier(unset ? 0x00 : keyCode, B_NUM_LOCK); if (message->FindUInt32("scroll_key", &keyCode) == B_OK) fCurrentMap.SetModifier(unset ? 0x00 : keyCode, B_SCROLL_LOCK); _UpdateButtons(); fKeyboardLayoutView->SetKeymap(&fCurrentMap); break; } case kMsgKeymapUpdated: _UpdateButtons(); fSystemListView->DeselectAll(); fUserListView->Select(0L); break; case kMsgDeadKeyAcuteChanged: { BMenuItem* item = fAcuteMenu->FindMarked(); if (item != NULL) { const char* trigger = item->Label(); if (strcmp(trigger, kDeadKeyTriggerNone) == 0) trigger = NULL; fCurrentMap.SetDeadKeyTrigger(kDeadKeyAcute, trigger); fKeyboardLayoutView->Invalidate(); } break; } case kMsgDeadKeyCircumflexChanged: { BMenuItem* item = fCircumflexMenu->FindMarked(); if (item != NULL) { const char* trigger = item->Label(); if (strcmp(trigger, kDeadKeyTriggerNone) == 0) trigger = NULL; fCurrentMap.SetDeadKeyTrigger(kDeadKeyCircumflex, trigger); fKeyboardLayoutView->Invalidate(); } break; } case kMsgDeadKeyDiaeresisChanged: { BMenuItem* item = fDiaeresisMenu->FindMarked(); if (item != NULL) { const char* trigger = item->Label(); if (strcmp(trigger, kDeadKeyTriggerNone) == 0) trigger = NULL; fCurrentMap.SetDeadKeyTrigger(kDeadKeyDiaeresis, trigger); fKeyboardLayoutView->Invalidate(); } break; } case kMsgDeadKeyGraveChanged: { BMenuItem* item = fGraveMenu->FindMarked(); if (item != NULL) { const char* trigger = item->Label(); if (strcmp(trigger, kDeadKeyTriggerNone) == 0) trigger = NULL; fCurrentMap.SetDeadKeyTrigger(kDeadKeyGrave, trigger); fKeyboardLayoutView->Invalidate(); } break; } case kMsgDeadKeyTildeChanged: { BMenuItem* item = fTildeMenu->FindMarked(); if (item != NULL) { const char* trigger = item->Label(); if (strcmp(trigger, kDeadKeyTriggerNone) == 0) trigger = NULL; fCurrentMap.SetDeadKeyTrigger(kDeadKeyTilde, trigger); fKeyboardLayoutView->Invalidate(); } break; } default: BWindow::MessageReceived(message); break; } }
bool ImageStripScene::setCurrentDirectory(const QString& path) { m_path = path; QMutexLocker locker(&m_mutex); QDir directory(path); QImageReader reader; if (directory.exists()) { clear(); if (m_loader) { m_loader->disconnect(this); m_loader->stopExecution(); if (!m_loader->wait(500)) { m_loader->terminate(); m_loader->wait(); } } delete m_loader; m_numItems = 0; m_loader = new ImageLoader(m_imgSize); connect(m_loader, SIGNAL(sigItemContentChanged(ImageItem*)), SLOT(slotItemContentChanged(ImageItem*))); QStringList files = directory.entryList(QDir::Files); QGraphicsLinearLayout* layout = new QGraphicsLinearLayout(); for (QStringList::iterator name=files.begin(); name!=files.end(); ++name) { QString path = directory.absoluteFilePath(*name); QString fileExtension = QFileInfo(path).suffix(); if (!fileExtension.compare("DNG", Qt::CaseInsensitive)) { warnKrita << "WARNING: Qt is known to crash when trying to open a DNG file. Skip it"; continue; } reader.setFileName(path); if(reader.canRead()) { ImageItem* item = new ImageItem(m_imgSize, path, m_loader); m_loader->addPath(item, path); layout->addItem(item); ++m_numItems; } } QGraphicsWidget* widget = new QGraphicsWidget(); widget->setLayout(layout); widget->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); addItem(widget); setSceneRect(widget->boundingRect()); m_loader->start(QThread::LowPriority); return true; } return false; }
void ThreadRemoveExifDatas::run() { QTableWidgetItem *item; Exiv2::ExifData::iterator keyIteratorRemove; Exiv2::ExifKey *keyRemove; QVector<QString> listErrorRemoveFile; QVector<int> listErrorRemoveFilePosition; connect(this, SIGNAL(progressBarValue(int)), progressBar, SLOT(setValue(int))); connect(this, SIGNAL(progressBarSetVisible(bool)), progressBar, SLOT(setVisible(bool))); emit progressBarSetVisible(true); progressBar->setRange(0, tableWidgetJpeg->rowCount()); for (int i = 0; i < tableWidgetJpeg->rowCount(); i++) { try { emit progressBarValue(i); Exiv2::Image::AutoPtr image; image = Exiv2::ImageFactory::open(tableWidgetJpeg->item(i, 7)->text().toStdString().c_str()); if (tableWidgetJpeg->item(i, 3) != 0 || tableWidgetJpeg->item(i, 4) != 0 || tableWidgetJpeg->item(i, 5) != 0) { bool exifRemovido = false; assert(image.get() != 0); image->readMetadata(); Exiv2::ExifData &exifData = image->exifData(); Exiv2::ExifKey keyLatitude = Exiv2::ExifKey("Exif.GPSInfo.GPSLatitude"); keyIteratorRemove = exifData.findKey(keyLatitude); if (keyIteratorRemove != exifData.end()) { exifData.erase(keyIteratorRemove); exifRemovido = true; } keyRemove = new Exiv2::ExifKey("Exif.GPSInfo.GPSTimeStamp"); keyIteratorRemove = exifData.findKey(*keyRemove); if (keyIteratorRemove != exifData.end()) { exifData.erase(keyIteratorRemove); exifRemovido = true; } keyRemove = new Exiv2::ExifKey("Exif.GPSInfo.GPSDateStamp"); keyIteratorRemove = exifData.findKey(*keyRemove); if (keyIteratorRemove != exifData.end()) { exifData.erase(keyIteratorRemove); exifRemovido = true; } keyRemove = new Exiv2::ExifKey("Exif.GPSInfo.GPSVersionID"); keyIteratorRemove = exifData.findKey(*keyRemove); if (keyIteratorRemove != exifData.end()) { exifData.erase(keyIteratorRemove); exifRemovido = true; } keyRemove = new Exiv2::ExifKey("Exif.GPSInfo.GPSMapDatum"); keyIteratorRemove = exifData.findKey(*keyRemove); if (keyIteratorRemove != exifData.end()) { exifData.erase(keyIteratorRemove); exifRemovido = true; } keyRemove = new Exiv2::ExifKey("Exif.GPSInfo.GPSLatitudeRef"); keyIteratorRemove = exifData.findKey(*keyRemove); if (keyIteratorRemove != exifData.end()) { exifData.erase(keyIteratorRemove); } keyRemove = new Exiv2::ExifKey("Exif.GPSInfo.GPSLongitude"); keyIteratorRemove = exifData.findKey(*keyRemove); if (keyIteratorRemove != exifData.end()) { exifData.erase(keyIteratorRemove); exifRemovido = true; } keyRemove = new Exiv2::ExifKey("Exif.GPSInfo.GPSLongitudeRef"); keyIteratorRemove = exifData.findKey(*keyRemove); if (keyIteratorRemove != exifData.end()) { exifData.erase(keyIteratorRemove); } keyRemove = new Exiv2::ExifKey("Exif.GPSInfo.GPSAltitude"); keyIteratorRemove = exifData.findKey(*keyRemove); if (keyIteratorRemove != exifData.end()) { exifData.erase(keyIteratorRemove); exifRemovido = true; } keyRemove = new Exiv2::ExifKey("Exif.GPSInfo.GPSAltitudeRef"); keyIteratorRemove = exifData.findKey(*keyRemove); if (keyIteratorRemove != exifData.end()) { exifData.erase(keyIteratorRemove); exifRemovido = true; } keyRemove = new Exiv2::ExifKey("Exif.GPSInfo.GPSImgDirectionRef"); keyIteratorRemove = exifData.findKey(*keyRemove); if (keyIteratorRemove != exifData.end()) { exifData.erase(keyIteratorRemove); exifRemovido = true; } keyRemove = new Exiv2::ExifKey("Exif.GPSInfo.GPSImgDirection"); keyIteratorRemove = exifData.findKey(*keyRemove); if (keyIteratorRemove != exifData.end()) { exifData.erase(keyIteratorRemove); exifRemovido = true; } keyRemove = new Exiv2::ExifKey("Exif.GPSInfo.GPSProcessingMethod"); keyIteratorRemove = exifData.findKey(*keyRemove); if (keyIteratorRemove != exifData.end()) { exifData.erase(keyIteratorRemove); exifRemovido = true; } if (exifRemovido) { QString softwareTag = QApplication::applicationName(); softwareTag += " "; softwareTag += QApplication::applicationVersion(); exifData["Exif.Image.Software"] = softwareTag.toStdString(); } image->setExifData(exifData); image->writeMetadata(); QString itemStatus = QString::fromUtf8("Dados Removidos"); item = new QTableWidgetItem(); item->setText(itemStatus); delete tableWidgetJpeg->takeItem(i, 3); delete tableWidgetJpeg->takeItem(i, 4); delete tableWidgetJpeg->takeItem(i, 5); tableWidgetJpeg->setItem(i, 6, item); } else { QString itemStatus = QString::fromUtf8("Não Há Dados Para Remover"); item = new QTableWidgetItem(); item->setText(itemStatus); tableWidgetJpeg->setItem(i, 6, item); } } catch (Exiv2::AnyError& e) { QString itemMsg; switch (e.code()) { case 2: itemMsg = QString::fromUtf8("Erro ao Remover Arquivo"); // Quando ocorrer erro na remoção do arquivo, ele será colocado numa lista para // que ao fim da execução seja tentado mais uma vez a sua remoção. listErrorRemoveFile.push_back(tableWidgetJpeg->item(i, 7)->text()); listErrorRemoveFilePosition.push_back(i); break; case 9: itemMsg = QString::fromUtf8("Erro de Acesso ao Arquivo"); break; case 10: itemMsg = QString::fromUtf8("Arquivo Somente Leitura"); break; case 11: itemMsg = QString::fromUtf8("Arquivo Inválido"); break; } item = new QTableWidgetItem(); item->setForeground(QColor(255, 0, 0)); item->setText(itemMsg); tableWidgetJpeg->setItem(i, 6, item); } } for (int i = 0; i < listErrorRemoveFile.size(); i++) { //precisa pesquisar no disco se tem outro arquivo com o nome igual mas com a extensão diferente // se achar, tem que remover o atual e renomear o outro arquivo. QString fileName; QString filePath; QString itemMsg; int pos; pos = listErrorRemoveFile.at(i).lastIndexOf("/"); fileName.operator =(QString::fromUtf8(listErrorRemoveFile.at(i).right(listErrorRemoveFile.at(i).size() - pos - 1).toStdString().c_str())); filePath = listErrorRemoveFile.at(i).left(pos); QDir directory(filePath); QStringList filesOnDirectory = directory.entryList(QDir::Files); QString regularExpression(fileName); regularExpression.append("[0-9]{1,4}"); QRegExp fileRegExp(regularExpression, Qt::CaseSensitive, QRegExp::RegExp); QStringList filesLocated = filesOnDirectory.filter(fileRegExp); for (int j = 0; j < filesLocated.size(); j++) { itemMsg = QString::fromUtf8("Não Foi Possível Corrigir o Arquivo, Verifique Manualmente"); QFileInfo fileTemp(directory, filesLocated.at(j)); QFileInfo fileCurrent(directory, fileName); if (fileTemp.size() > fileCurrent.size()) { if (directory.remove(fileName)) { if (directory.rename(filesLocated.at(j), fileName)) { itemMsg = QString::fromUtf8("O Erro no Arquivo foi Corrigido"); delete tableWidgetJpeg->takeItem(listErrorRemoveFilePosition.at(i), 3); delete tableWidgetJpeg->takeItem(listErrorRemoveFilePosition.at(i), 4); delete tableWidgetJpeg->takeItem(listErrorRemoveFilePosition.at(i), 5); } } } else { if (directory.remove(filesLocated.at(j))) itemMsg = QString::fromUtf8("O Erro no Arquivo foi Corrigido"); } item = new QTableWidgetItem(); item->setForeground(QColor(0, 110, 0)); item->setText(itemMsg); tableWidgetJpeg->setItem(listErrorRemoveFilePosition.at(i), 6, item); } } emit progressBarValue(tableWidgetJpeg->rowCount()); sleep(1); emit progressBarSetVisible(false); }
void SingleAnalysis::ComputeSystematics(int pointID, int energy, DataType dataType, GraphMap &graphMapAtNominalValues) { TSystemDirectory directory((m_rootFileDirectory + this->GetDataName(dataType) + "/SYSTEMATICS/").c_str(), (m_rootFileDirectory + this->GetDataName(dataType) + "/SYSTEMATICS/").c_str()); TList *pFileList = directory.GetListOfFiles(); if( ! pFileList ) { std::cout << "No systematics study performed. Directory '" << m_rootFileDirectory + this->GetDataName(dataType) + "/SYSTEMATICS/" << "' doesn't exists" << std::endl; return; } std::vector<std::string> pm; pm.push_back("+"); pm.push_back("-"); GraphSystErrorMap upperErrorMap; GraphSystErrorMap lowerErrorMap; upperErrorMap[EFFICIENCY] = 0.d; upperErrorMap[E_REC] = 0.d; upperErrorMap[E_REC_DEVIATION] = 0.d; upperErrorMap[E_RESOL] = 0.d; upperErrorMap[N_PFOS] = 0.d; lowerErrorMap[EFFICIENCY] = 0.d; lowerErrorMap[E_REC] = 0.d; lowerErrorMap[E_REC_DEVIATION] = 0.d; lowerErrorMap[E_RESOL] = 0.d; lowerErrorMap[N_PFOS] = 0.d; for(unsigned int sp=DISTANCE_1 ; sp<N_SYSTEMATIC_PARAMETERS ; sp++) { unsigned int parameterID = sp+1; for(unsigned int signID=0 ; signID<pm.size() ; signID++) { std::string sign = pm.at( signID ); TString fileName = "SingleParticleReconstruction_" + this->GetEnergyToString(dataType, energy) + "_cut_ArborPFA_" + this->GetDataName(dataType) + "_P" + TString::UItoa(parameterID, 10) + "_S" + sign + "_basic.root"; std::cout << "File name is " << fileName << " !!!!!" << std::endl; TString completeFileName = m_rootFileDirectory + this->GetDataName(dataType) + "/SYSTEMATICS/" + fileName; TFile *pFile = TFile::Open(completeFileName.Data()); if( ! pFile ) { std::cerr << "Wrong sys file name !" << std::endl; continue; } TTree *pTree = (TTree *) pFile->Get(m_treeName.c_str()); if(!pTree) { std::cerr << "Wrong sys tree name !" << std::endl; continue; } GraphMap graphMap; graphMap[EFFICIENCY] = new TGraphErrors(); graphMap[E_REC] = new TGraphErrors(); graphMap[E_REC_DEVIATION] = new TGraphErrors(); graphMap[E_RESOL] = new TGraphErrors(); graphMap[N_PFOS] = new TGraphErrors(); TreeAnalyzer treeAnalyzer(pTree); treeAnalyzer.Loop(pointID, static_cast<double>(energy), graphMap); this->ComputeSystematics(pointID, graphMapAtNominalValues, graphMap, EFFICIENCY, upperErrorMap, lowerErrorMap); this->ComputeSystematics(pointID, graphMapAtNominalValues, graphMap, E_REC, upperErrorMap, lowerErrorMap); this->ComputeSystematics(pointID, graphMapAtNominalValues, graphMap, E_REC_DEVIATION, upperErrorMap, lowerErrorMap); this->ComputeSystematics(pointID, graphMapAtNominalValues, graphMap, E_RESOL, upperErrorMap, lowerErrorMap); this->ComputeSystematics(pointID, graphMapAtNominalValues, graphMap, N_PFOS, upperErrorMap, lowerErrorMap); } } delete pFileList; // First try : combine upper and lower values for efficiency graphMapAtNominalValues[EFFICIENCY]->SetPointError(pointID, 0, graphMapAtNominalValues[EFFICIENCY]->GetEY()[pointID] + std::sqrt( upperErrorMap[EFFICIENCY] + lowerErrorMap[EFFICIENCY] ) ); graphMapAtNominalValues[E_REC]->SetPointError(pointID, 0, graphMapAtNominalValues[E_REC]->GetEY()[pointID] + std::sqrt( upperErrorMap[E_REC] + lowerErrorMap[E_REC] ) ); graphMapAtNominalValues[E_REC_DEVIATION]->SetPointError(pointID, 0, graphMapAtNominalValues[E_REC_DEVIATION]->GetEY()[pointID] + std::sqrt( upperErrorMap[E_REC_DEVIATION] + lowerErrorMap[E_REC_DEVIATION] ) ); graphMapAtNominalValues[E_RESOL]->SetPointError(pointID, 0, graphMapAtNominalValues[E_RESOL]->GetEY()[pointID] + std::sqrt( upperErrorMap[E_RESOL] + lowerErrorMap[E_RESOL] ) ); graphMapAtNominalValues[N_PFOS]->SetPointError(pointID, 0, graphMapAtNominalValues[N_PFOS]->GetEY()[pointID] + std::sqrt( upperErrorMap[N_PFOS] + lowerErrorMap[N_PFOS] ) ); }
void CollectionScanner::scanFiles( const QStringList& entries ) { DEBUG_BLOCK typedef QPair<QString, QString> CoverBundle; QStringList validImages; validImages << "jpg" << "png" << "gif" << "jpeg"; QStringList validPlaylists; validPlaylists << "m3u" << "pls"; QValueList<CoverBundle> covers; QStringList images; int itemCount = 0; DCOPRef dcopRef( "amarok", "collection" ); foreachType( QStringList, entries ) { const QString path = *it; const QString ext = extension( path ); const QString dir = directory( path ); itemCount++; // Write path to logfile if( !m_logfile.isEmpty() ) { QFile log( m_logfile ); if( log.open( IO_WriteOnly ) ) { QCString cPath = path.utf8(); log.writeBlock( cPath, cPath.length() ); log.close(); } } if( validImages.contains( ext ) ) images += path; else if( m_importPlaylists && validPlaylists.contains( ext ) ) { AttributeMap attributes; attributes["path"] = path; writeElement( "playlist", attributes ); } else { MetaBundle::EmbeddedImageList images; MetaBundle mb( KURL::fromPathOrURL( path ), true, TagLib::AudioProperties::Fast, &images ); const AttributeMap attributes = readTags( mb ); if( !attributes.empty() ) { writeElement( "tags", attributes ); CoverBundle cover( attributes["artist"], attributes["album"] ); if( !covers.contains( cover ) ) covers += cover; foreachType( MetaBundle::EmbeddedImageList, images ) { AttributeMap attributes; attributes["path"] = path; attributes["hash"] = (*it).hash(); attributes["description"] = (*it).description(); writeElement( "embed", attributes ); } } }
void SudokuWindow::MessageReceived(BMessage* message) { if (message->WasDropped()) { _MessageDropped(message); return; } switch (message->what) { case kMsgOpenFilePanel: fOpenPanel->Show(); break; case B_REFS_RECEIVED: case B_SIMPLE_DATA: _MessageDropped(message); break; case kMsgGenerateSudoku: { int32 level; if (message->FindInt32("level", &level) != B_OK) level = _Level(); _SetLevel(level); _Generate(level); break; } case kMsgAbortSudokuGenerator: if (fGenerator != NULL) fGenerator->Abort(); break; case kMsgSudokuGenerated: { BMessage archive; if (message->FindMessage("field", &archive) == B_OK) { SudokuField* field = new SudokuField(&archive); fSudokuView->SetTo(field); } fSudokuView->SetEditable(true); fProgressWindow->Stop(); delete fGenerator; fGenerator = NULL; break; } case kMsgExportAs: { if (message->FindInt32("as", (int32 *)&fExportFormat) < B_OK) fExportFormat = kExportAsText; fSavePanel->Show(); break; } case B_COPY: fSudokuView->CopyToClipboard(); break; case B_SAVE_REQUESTED: { entry_ref directoryRef; const char* name; if (message->FindRef("directory", &directoryRef) != B_OK || message->FindString("name", &name) != B_OK) break; BDirectory directory(&directoryRef); BEntry entry(&directory, name); entry_ref ref; if (entry.GetRef(&ref) == B_OK) fSudokuView->SaveTo(ref, fExportFormat); break; } case kMsgNewBlank: _ResetStoredState(); fSudokuView->ClearAll(); break; case kMsgStartAgain: fSudokuView->ClearChanged(); break; case kMsgMarkInvalid: case kMsgMarkValidHints: { BMenuItem* item; if (message->FindPointer("source", (void**)&item) != B_OK) return; uint32 flag = message->what == kMsgMarkInvalid ? kMarkInvalid : kMarkValidHints; item->SetMarked(!item->IsMarked()); if (item->IsMarked()) fSudokuView->SetHintFlags(fSudokuView->HintFlags() | flag); else fSudokuView->SetHintFlags(fSudokuView->HintFlags() & ~flag); break; } case kMsgStoreState: delete fStoredState; fStoredState = new BMessage; fSudokuView->Field()->Archive(fStoredState, true); fRestoreStateItem->SetEnabled(true); break; case kMsgRestoreState: { if (fStoredState == NULL) break; SudokuField* field = new SudokuField(fStoredState); fSudokuView->SetTo(field); break; } case kMsgSudokuSolved: { BAlert* alert = new BAlert(B_TRANSLATE("Sudoku request"), B_TRANSLATE("Sudoku solved - congratulations!\n"), B_TRANSLATE("OK"), NULL, NULL, B_WIDTH_AS_USUAL, B_IDEA_ALERT); alert->SetFlags(alert->Flags() | B_CLOSE_ON_ESCAPE); alert->Go(); break; } case B_OBSERVER_NOTICE_CHANGE: { int32 what; if (message->FindInt32(B_OBSERVE_WHAT_CHANGE, &what) != B_OK) break; if (what == kUndoRedoChanged) { fUndoItem->SetEnabled(fSudokuView->CanUndo()); fRedoItem->SetEnabled(fSudokuView->CanRedo()); } break; } default: BWindow::MessageReceived(message); break; } }
main (int argc, char **argv, char **envp) { register c; if (argc > 2) { outerr("Usage: deco [dirname]\n",0); exit (1); } outerr("Demos Commander, Copyright (C) 1989-1994 Serge Vakulenko\n",0); palette = dflt_palette; EnvInit (envp); uid = getuid (); gid = getgid (); # ifdef GROUPS gidnum = getgroups (sizeof(gidlist)/sizeof(gidlist[0]), (unsigned int *)gidlist); # endif ppid = getppid (); user = username (uid); group = groupname (gid); tty = ttyname (0); machine = getmachine (); #if 0 sigign(); #else signal(SIGTERM, SIG_IGN); signal(SIGQUIT, SIG_IGN); signal(SIGINT, SIG_IGN); # ifdef SIGTSTP signal(SIGTSTP, SIG_IGN); # endif #endif init (); // inithome (); VClear (); /* init class dir */ if (argc > 1) // chdir (argv [1]); left = new dir(argv [1]); else left = new dir; right = new dir; left->d.basecol = 0; right->d.basecol = 40; /*-----------*/ initfile.read(); if (uid == 0) palette.dimfg = 6; v.VSetPalette (palette.fg, palette.bg, palette.revfg, palette.revbg, palette.boldfg, palette.boldbg, palette.boldrevfg, palette.boldrevbg, palette.dimfg, palette.dimbg, palette.dimrevfg, palette.dimrevbg); setdir (left, "."); setdir (right, "."); left->chdir(left->d.cwd); cur = left; draw.draw(cur, left, right); for (;;) { if (! cmdreg) draw.drawcursor(cur); // cmd.drawcmd(cur, &left, &right); VSync (); c = KeyGet (); if (! cmdreg) draw.undrawcursor(cur); switch (c) { case '+': /* select */ case '-': /* unselect */ if (! cpos && ! cmdreg && ! cur->d.status) { if (c == '+') tagall (); else untagall (); draw.draw(cur, left, right); continue; } default: // if (c>=' ' && c<='~' || c>=0300 && c<=0376) { // if (cpos || c!=' ') // cmd.inscmd(c); // continue; // } VBeep (); continue; // case cntrl ('V'): /* quote next char */ // cmd.inscmd(quote ()); // continue; // case cntrl ('J'): /* insert file name */ // if (! cmdreg && ! cur->status) // cmd.namecmd(cur); // continue; // case cntrl ('G'): // cmd.delcmd(); // continue; // case meta ('b'): /* backspace */ // if (cpos) { // cmd.leftcmd(); // cmd.delcmd(); // } // continue; case cntrl ('O'): /* set/unset command mode */ case cntrl ('P'): /* set/unset command mode */ switchcmdreg (); if (! cmdreg) visualwin = 1; draw.draw(cur, left, right); continue; case cntrl ('M'): /* return */ // if (command [0]) { // cmd.exec(cur, &left, &right, 1, 1); // draw.draw(cur, &left, &right); // continue; // } if (cmdreg) { cmdreg = 0; if (! visualwin) { visualwin = 1; setdir (cur==left ? right : left, NULL); setdir (cur, NULL); } draw.draw(cur, left, right); continue; } execute (); continue; case cntrl (']'): /* redraw screen */ VRedraw (); continue; // case cntrl ('B'): /* history */ // if (! visualwin) // VClearBox (1, 0, LINES-2, 80); // cmd.histmenu(cur, &left, &right); // draw.draw(cur, &left, &right); // continue; case meta ('A'): /* f1 */ genhelp (); draw.draw(cur, left, right); continue; case meta ('B'): /* f2 */ udm.menu(); draw.draw(cur, left, right); continue; case meta ('I'): /* f9 */ mymenu.runmenu (cur==left ? 'l' : 'r'); draw.draw(cur, left, right); continue; case meta ('J'): /* f0 */ case cntrl ('C'): /* quit */ quit (); continue; case cntrl ('U'): /* swap panels */ swappanels (); draw.draw(cur, left, right); continue; case cntrl ('F'): /* full screen */ fullscreen (); draw.draw(cur, left, right); continue; case cntrl ('^'): /* cd / */ directory (0, 'r'); if (! cur->d.status) draw.drawdir(cur, 1, left, right); continue; case cntrl ('\\'): /* cd $HOME */ directory (0, 'o'); if (! cur->d.status) draw.drawdir(cur, 1, left, right); continue; // case cntrl ('Y'): /* clear line */ // command [cpos = 0] = 0; // continue; // case cntrl ('X'): /* next history */ // cmd.nextcmd(); // continue; // case cntrl ('E'): /* prev history */ // cmd.prevcmd(); // continue; // case cntrl ('S'): /* char left */ // case cntrl ('A'): /* char left */ // cmd.leftcmd(); // continue; // case cntrl ('D'): /* char right */ // cmd.rightcmd(); // continue; case cntrl ('I'): /* tab */ if (cmdreg) {} // if (command [cpos]) // cmd.endcmd(); // else // cmd.homecmd(); else { switchpanels (); if (fullwin) { draw.drawbanners(); draw.drawdir(cur, 0, left, right); break; } } continue; case cntrl ('W'): /* double width */ if (! cmdreg) { setdwid (); draw.draw(cur, left, right); } continue; // case meta ('G'): /* f7 */ // makedir (); // draw.draw(cur, &left, &right); // continue; case meta ('h'): /* home */ case meta ('e'): /* end */ case meta ('u'): /* up */ case meta ('d'): /* down */ case meta ('l'): /* left */ case meta ('r'): /* right */ case meta ('n'): /* next page */ case meta ('p'): /* prev page */ case cntrl ('K'): /* find file */ case cntrl ('R'): /* reread catalog */ case cntrl ('T'): /* tag file */ case meta ('C'): /* f3 */ case meta ('D'): /* f4 */ case meta ('E'): /* f5 */ case meta ('F'): /* f6 */ case meta ('H'): /* f8 */ case cntrl ('L'): /* status */ if (cmdreg || cur->d.status) {} // docmdreg (c); else doscrreg (c); continue; } } }
void ControlPlotter(){ string directory("HH4b_subjetBTagged_01Mar2016/"); string s_file = directory + "ControlPlotsSignal.root"; //string s_file = "ControlPlotsNoReg_X270.root"; fWrite = new TFile(s_file.data(), "RECREATE"); const int ntrees = 21; string s[ntrees] = { // "QCD_HT1000to1500_Moriond.root", // }; "Data_RunCD_Moriond.root", "TT_TuneCUETP8M1_13TeV-powheg-pythia8_Moriond.root", "QCD_HT500to700_Moriond.root", "QCD_HT700to1000_Moriond.root", "QCD_HT1000to1500_Moriond.root", "QCD_HT1500to2000_Moriond.root", "QCD_HT2000toInf_Moriond.root", "hh4bTree_RadionTohhTohbbhbb_narrow_M-1000_13TeV-madgraph_Moriond.root", "hh4bTree_RadionTohhTohbbhbb_narrow_M-1200_13TeV-madgraph_Moriond.root", "hh4bTree_RadionTohhTohbbhbb_narrow_M-1400_13TeV-madgraph_Moriond.root", "hh4bTree_RadionTohhTohbbhbb_narrow_M-1600_13TeV-madgraph_Moriond.root", "hh4bTree_RadionTohhTohbbhbb_narrow_M-1800_13TeV-madgraph_Moriond.root",//10 "hh4bTree_RadionTohhTohbbhbb_narrow_M-2000_13TeV-madgraph_Moriond.root", "hh4bTree_RadionTohhTohbbhbb_narrow_M-2500_13TeV-madgraph_Moriond.root", "hh4bTree_BulkGravTohhTohbbhbb_narrow_M-1000_13TeV-madgraph_Moriond.root", "hh4bTree_BulkGravTohhTohbbhbb_narrow_M-1200_13TeV-madgraph_Moriond.root", "hh4bTree_BulkGravTohhTohbbhbb_narrow_M-1400_13TeV-madgraph_Moriond.root", "hh4bTree_BulkGravTohhTohbbhbb_narrow_M-1600_13TeV-madgraph_Moriond.root", "hh4bTree_BulkGravTohhTohbbhbb_narrow_M-1800_13TeV-madgraph_Moriond.root", "hh4bTree_BulkGravTohhTohbbhbb_narrow_M-2000_13TeV-madgraph_Moriond.root", "hh4bTree_BulkGravTohhTohbbhbb_narrow_M-2500_13TeV-madgraph_Moriond.root" //19 }; string sampleName[ntrees] = { //"QCD_HT1000to1500" // }; "Data", "TTbar", "QCD_HT500to700", "QCD_HT700to1000", "QCD_HT1000to1500", "QCD_HT1500to2000", "QCD_HT2000toInf", "Radion_m1000_13TeV", "Radion_m1200_13TeV", "Radion_m1400_13TeV", "Radion_m1600_13TeV", "Radion_m1800_13TeV", "Radion_m2000_13TeV", "Radion_m2500_13TeV", "Graviton_m1000_13TeV", "Graviton_m1200_13TeV", "Graviton_m1400_13TeV", "Graviton_m1600_13TeV", "Graviton_m1800_13TeV", "Graviton_m2000_13TeV", "Graviton_m2500_13TeV" }; //ControlPlotsSignal.root hh4bTree_RadionTohhTohbbhbb_narrow_M-1800_13TeV-madgraph.root Plots //hh4bTree_JetHT_Run2015D-05Oct2015-v1.root hh4bTree_RadionTohhTohbbhbb_narrow_M-2000_13TeV-madgraph.root QCD_HT1000to1500.root //hh4bTree_JetHT_Run2015D-PromptReco-v4.root hh4bTree_RadionTohhTohbbhbb_narrow_M-2500_13TeV-madgraph.root QCD_HT1500to2000.root //hh4bTree_RadionTohhTohbbhbb_narrow_M-1000_13TeV-madgraph.root hh4bTree_RadionTohhTohbbhbb_narrow_M-3500_13TeV-madgraph.root QCD_HT2000toInf.root //hh4bTree_RadionTohhTohbbhbb_narrow_M-1200_13TeV-madgraph.root hh4bTree_RadionTohhTohbbhbb_narrow_M-4000_13TeV-madgraph.root QCD_HT300to500.root //hh4bTree_RadionTohhTohbbhbb_narrow_M-1400_13TeV-madgraph.root hh4bTree_RadionTohhTohbbhbb_narrow_M-4500_13TeV-madgraph.root QCD_HT500to700.root //hh4bTree_RadionTohhTohbbhbb_narrow_M-1600_13TeV-madgraph.root MassPlotFineBins.root QCD_HT700to1000.root for (int i = 0; i < ntrees; i++){ // if (sampleName[i].find("Data") != string::npos) generalCut = "(HJets_MassPruned[0] > 105) * (HJets_MassPruned[1] > 105) * (HJets_MassPruned[0] < 135) * (HJets_MassPruned[1] < 135) * (SelectedEventminv_leading2hjets > 1100)*(TMath::Abs(SelectedEvent_deta_leading2hjets) < 1.3)";// * ((HJets_nsubjetsBTaggedCSVL[0]+HJets_nsubjetsBTaggedCSVL[1]) > 0.1)"; // else generalCut = "SelectedEvent_btagsf*(HJets_MassPruned[0] > 105) * (HJets_MassPruned[1] > 105) * (HJets_MassPruned[0] < 135) * (HJets_MassPruned[1] < 135) * (SelectedEventminv_leading2hjets > 1000)"; // else generalCut = "(HJets_MassPruned[0] > 105) * (HJets_MassPruned[1] > 105) * (HJets_MassPruned[0] < 135) * (HJets_MassPruned[1] < 135) * (SelectedEventminv_leading2hjets > 1000)*(TMath::Abs(SelectedEvent_deta_leading2hjets) < 1.3)*(TMath::Abs(HJets_Eta[0]) < 2.4)*(TMath::Abs(HJets_Eta[1]) < 2.4)";// * ((HJets_nsubjetsBTaggedCSVL[0]+HJets_nsubjetsBTaggedCSVL[1]) > 0.1)"; generalCut = "SelectedEvent_btagsf*(HJets_MassPruned[0] > 105) * (HJets_MassPruned[1] > 105) * (HJets_MassPruned[0] < 135) * (HJets_MassPruned[1] < 135)"; generalCut = generalCut*mainCut; /* if (sampleName[i].find("Data") != string::npos) generalCut = mainCut; else { } */ string s1 = directory + "" + s[i]; f1 = TFile::Open(s1.data()); TDirectory* hh4b = (TDirectory*) f1->Get("hh4b;1"); TFile* test = new TFile("test", "RECREATE"); R2S = ((TTree*) hh4b->Get("tree;1"))->CopyTree(mainCut); TDirectory* allEvents = (TDirectory*) f1->Get("allEvents;1"); TH1D* counter = (TH1D*) allEvents->Get("hEventCount;1"); cout << s1.c_str() << endl; counter = (TH1D*) allEvents->Get("hEventCount;1"); if (counter) cout << "TOTAL NUMBER OF EVENTS hEventCount ======================================= " << counter->Integral() << endl; else{ counter = (TH1D*) allEvents->Get("hEventCount_wt;1"); cout << "TOTAL NUMBER OF EVENTS ======================================= " << counter->Integral() << endl; } // R2S->Print(); nbins = 10; minBin = 0.8, width = 0.1; maxBin = minBin + nbins*width; plotName = "BTAG_SF_" + sampleName[i]; histo_title = ""; xaxis_title = "btag SF"; yaxis_title = "Events / 40 GeV"; variable = "SelectedEvent_btagsf"; cut0 = ""; cut = cut0*generalCut; PlottiPlotta(); // R2S->Print(); nbins = 75; minBin = 600., width = 40.; maxBin = minBin + nbins*width; plotName = "TotalMass_" + sampleName[i]; histo_title = ""; xaxis_title = "m_{4b} (GeV)"; yaxis_title = "Events / 40 GeV"; variable = "SelectedEvent_minv_leading2hjets"; cut0 = ""; cut = cut0*generalCut; PlottiPlotta(); cout << "Leading jets" << endl; nbins = 75; minBin = 1000., width = 40.; maxBin = minBin + nbins*width; plotName = "TotalMass_0to2btag_" + sampleName[i]; histo_title = ""; xaxis_title = "m_{4b} (GeV)"; yaxis_title = "Events / 40 GeV"; variable = "SelectedEvent_minv_leading2hjets"; cut0 = "((HJets_nsubjetsBTaggedCSVL[0]+HJets_nsubjetsBTaggedCSVL[1])<2.99)"; cut = cut0*generalCut; PlottiPlotta(); nbins = 4000; minBin = 1000., width = 1.; maxBin = minBin + nbins*width; plotName = "TotalMass1GeV_" + sampleName[i]; histo_title = ""; xaxis_title = "m_{4b} (GeV)"; yaxis_title = "Events / 1 GeV"; variable = "SelectedEvent_minv_leading2hjets"; cut0 = ""; cut = cut0*generalCut; PlottiPlotta(); nbins = 4000; minBin = 1000., width = 1.; maxBin = minBin + nbins*width; plotName = "TotalMass1GeV_3btag_" + sampleName[i]; histo_title = ""; xaxis_title = "m_{4b} (GeV)"; yaxis_title = "Events / 1 GeV"; variable = "SelectedEvent_minv_leading2hjets"; cut0 = "(HJets_nsubjetsBTaggedCSVL[0]+HJets_nsubjetsBTaggedCSVL[1])>2.99"; cut = cut0*generalCut; PlottiPlotta(); nbins = 4000; minBin = 1000., width = 1.; maxBin = minBin + nbins*width; plotName = "TotalMass1GeV_3btagExactly_" + sampleName[i]; histo_title = ""; xaxis_title = "m_{4b} (GeV)"; yaxis_title = "Events / 1 GeV"; variable = "SelectedEvent_minv_leading2hjets"; cut0 = "((HJets_nsubjetsBTaggedCSVL[0]+HJets_nsubjetsBTaggedCSVL[1])>2.99) * ((HJets_nsubjetsBTaggedCSVL[0]+HJets_nsubjetsBTaggedCSVL[1])<3.01)"; cut = cut0*generalCut; PlottiPlotta(); nbins = 4000; minBin = 1000., width = 1.; maxBin = minBin + nbins*width; plotName = "TotalMass1GeV_3btagExactly_HPHP_" + sampleName[i]; histo_title = ""; xaxis_title = "m_{4b} (GeV)"; yaxis_title = "Events / 1 GeV"; variable = "SelectedEvent_minv_leading2hjets"; cut0 = "((HJets_nsubjetsBTaggedCSVL[0]+HJets_nsubjetsBTaggedCSVL[1])>2.99) * ((HJets_nsubjetsBTaggedCSVL[0]+HJets_nsubjetsBTaggedCSVL[1])<3.01)*(HJets_tau2[0]/HJets_tau1[0] < 0.6)*(HJets_tau2[1]/HJets_tau1[1] < 0.6)"; cut = cut0*generalCut; PlottiPlotta(); nbins = 4000; minBin = 1000., width = 1.; maxBin = minBin + nbins*width; plotName = "TotalMass1GeV_3btagExactly_HPLP_" + sampleName[i]; histo_title = ""; xaxis_title = "m_{4b} (GeV)"; yaxis_title = "Events / 1 GeV"; variable = "SelectedEvent_minv_leading2hjets"; cut0 = "((HJets_nsubjetsBTaggedCSVL[0]+HJets_nsubjetsBTaggedCSVL[1])>2.99) * ((HJets_nsubjetsBTaggedCSVL[0]+HJets_nsubjetsBTaggedCSVL[1])<3.01)*(HJets_tau2[0]/HJets_tau1[0] < 0.6)*(HJets_tau2[1]/HJets_tau1[1] > 0.6)"; cut = cut0*generalCut; PlottiPlotta(); nbins = 4000; minBin = 1000., width = 1.; maxBin = minBin + nbins*width; plotName = "TotalMass1GeV_3btagExactly_LPHP_" + sampleName[i]; histo_title = ""; xaxis_title = "m_{4b} (GeV)"; yaxis_title = "Events / 1 GeV"; variable = "SelectedEvent_minv_leading2hjets"; cut0 = "((HJets_nsubjetsBTaggedCSVL[0]+HJets_nsubjetsBTaggedCSVL[1])>2.99) * ((HJets_nsubjetsBTaggedCSVL[0]+HJets_nsubjetsBTaggedCSVL[1])<3.01)*(HJets_tau2[0]/HJets_tau1[0] > 0.6)*(HJets_tau2[1]/HJets_tau1[1] < 0.6)"; cut = cut0*generalCut; PlottiPlotta(); nbins = 4000; minBin = 1000., width = 1.; maxBin = minBin + nbins*width; plotName = "TotalMass1GeV_4btag_" + sampleName[i]; histo_title = ""; xaxis_title = "m_{4b} (GeV)"; yaxis_title = "Events / 1 GeV"; variable = "SelectedEvent_minv_leading2hjets"; cut0 = "(HJets_nsubjetsBTaggedCSVL[0]+HJets_nsubjetsBTaggedCSVL[1])>3.99"; cut = cut0*generalCut; PlottiPlotta(); nbins = 16; minBin = -0.1, width = 0.1; maxBin = minBin + nbins*width; plotName = "DeltaEta_" + sampleName[i]; histo_title = ""; xaxis_title = "#Delta #eta"; yaxis_title = "Events / 0.1"; variable = "SelectedEvent_deta_leading2hjets"; cut0 = ""; cut = cut0*generalCut; PlottiPlotta(); nbins = 84; minBin = 200., width = 25; maxBin = minBin + nbins*width; plotName = "HThat_" + sampleName[i]; histo_title = ""; xaxis_title = "HT_hat (GeV)"; yaxis_title = "Events / 25 GeV"; variable = "SelectedEvent_htHat"; cut0 = ""; cut = cut0*generalCut; PlottiPlotta(); nbins = 42; minBin = 200., width = 25; maxBin = minBin + nbins*width; plotName = "PT0_" + sampleName[i]; histo_title = ""; xaxis_title = "p_{T, j0} (GeV)"; yaxis_title = "Events / 25 GeV"; variable = "HJets_Pt[0]"; cut0 = ""; cut = cut0*generalCut; PlottiPlotta(); nbins = 42; minBin = 200., width = 25; maxBin = minBin + nbins*width; plotName = "PT1_" + sampleName[i]; histo_title = ""; xaxis_title = "p_{T, j1} (GeV)"; yaxis_title = "Events / 25 GeV"; variable = "HJets_Pt[1]"; cut0 = ""; cut = cut0*generalCut; PlottiPlotta(); nbins = 30; minBin = -3., width = 0.2; maxBin = minBin + nbins*width; plotName = "ETA_" + sampleName[i]; histo_title = ""; xaxis_title = "#eta "; yaxis_title = "Events / 0.1"; variable = "HJets_Eta"; cut0 = ""; cut = cut0*generalCut; PlottiPlotta(); nbins = 30; minBin =90., width = 2; maxBin = minBin + nbins*width; plotName = "M0Pruned_" + sampleName[i]; histo_title = ""; xaxis_title = "m_{j0} (GeV)"; yaxis_title = "Events / 5 GeV"; variable = "HJets_MassPruned[0]"; cut0 = "SelectedEvent_btagsf*(SelectedEvent_minv_leading2hjets > 1000)*(TMath::Abs(SelectedEvent_deta_leading2hjets) < 1.3)"; cut = cut0; // no general cut applied PlottiPlotta(); nbins = 30; minBin =90., width = 2; maxBin = minBin + nbins*width; plotName = "M1Pruned_" + sampleName[i]; histo_title = ""; xaxis_title = "m_{j1} (GeV)"; yaxis_title = "Events / 5 GeV"; variable = "HJets_MassPruned[1]"; cut0 = "SelectedEvent_btagsf*(SelectedEvent_minv_leading2hjets > 1000)*(TMath::Abs(SelectedEvent_deta_leading2hjets) < 1.3)"; cut = cut0; // no general cut applied PlottiPlotta(); nbins = 30; minBin =90., width = 2; maxBin = minBin + nbins*width; plotName = "M0Pruned_WMJcut_" + sampleName[i]; histo_title = ""; xaxis_title = "m_{j0} (GeV)"; yaxis_title = "Events / 5 GeV"; variable = "HJets_MassPruned[0]"; cut0 = ""; cut = cut0*generalCut; // no general cut applied PlottiPlotta(); nbins = 30; minBin =90., width = 2; maxBin = minBin + nbins*width; plotName = "M1Pruned_WMJcut_" + sampleName[i]; histo_title = ""; xaxis_title = "m_{j1} (GeV)"; yaxis_title = "Events / 5 GeV"; variable = "HJets_MassPruned[1]"; cut0 = ""; cut = cut0*generalCut; // no general cut applied PlottiPlotta(); nbins = 10; minBin =0., width = 0.1; maxBin = minBin + nbins*width; plotName = "nCSV_J0_SJ0_" + sampleName[i]; histo_title = ""; xaxis_title = "CSV J0 SJ0"; yaxis_title = "Events / 0.1"; variable = "HJets_csvSubjet0[0]"; cut0 = ""; cut = cut0*generalCut; PlottiPlotta(); nbins = 10; minBin =0., width = 0.11; maxBin = minBin + nbins*width; plotName = "nCSV_J1_SJ0_" + sampleName[i]; histo_title = ""; xaxis_title = "CSV J1 SJ0"; yaxis_title = "Events"; variable = "HJets_csvSubjet0[1]"; cut0 = ""; cut = cut0*generalCut; PlottiPlotta(); nbins = 10; minBin =0., width = 0.1; maxBin = minBin + nbins*width; plotName = "nCSV_J0_SJ1_" + sampleName[i]; histo_title = ""; xaxis_title = "CSV J0 SJ1"; yaxis_title = "Events / 0.1"; variable = "HJets_csvSubjet1[0]"; cut0 = ""; cut = cut0*generalCut; PlottiPlotta(); nbins = 10; minBin =0., width = 0.11; maxBin = minBin + nbins*width; plotName = "nCSV_J1_SJ1_" + sampleName[i]; histo_title = ""; xaxis_title = "CSV J1 SJ1"; yaxis_title = "Events / 0.1"; variable = "HJets_csvSubjet1[1]"; cut0 = ""; cut = cut0*generalCut; PlottiPlotta(); nbins = 6; minBin =-0.5, width = 1; maxBin = minBin + nbins*width; plotName = "nCSV_" + sampleName[i]; histo_title = ""; xaxis_title = "N(CSV0)+N(CSV1)"; yaxis_title = "Events"; variable = "HJets_nsubjetsBTaggedCSVL[0]+HJets_nsubjetsBTaggedCSVL[1]"; cut0 = ""; cut = cut0*generalCut; PlottiPlotta(); //================================================================= nobtasf cut0 = "(HJets_MassPruned[0] > 105) * (HJets_MassPruned[1] > 105) * (HJets_MassPruned[0] < 135) * (HJets_MassPruned[1] < 135) * (SelectedEvent_minv_leading2hjets > 1000)*(TMath::Abs(SelectedEvent_deta_leading2hjets) < 1.3) * ((HJets_nsubjetsBTaggedCSVL[0]+HJets_nsubjetsBTaggedCSVL[1]) > 0.1)"; nbins = 10; minBin =0., width = 0.1; maxBin = minBin + nbins*width; plotName = "nCSV_J0_SJ0_noBtagSF_" + sampleName[i]; histo_title = ""; xaxis_title = "CSV J0 SJ0"; yaxis_title = "Events / 0.1"; variable = "HJets_csvSubjet0[0]"; cut = cut0; PlottiPlotta(); nbins = 10; minBin =0., width = 0.11; maxBin = minBin + nbins*width; plotName = "nCSV_J1_SJ0_noBtagSF_" + sampleName[i]; histo_title = ""; xaxis_title = "CSV J1 SJ0"; yaxis_title = "Events"; variable = "HJets_csvSubjet0[1]"; cut = cut0; PlottiPlotta(); nbins = 10; minBin =0., width = 0.1; maxBin = minBin + nbins*width; plotName = "nCSV_J0_SJ1_noBtagSF_" + sampleName[i]; histo_title = ""; xaxis_title = "CSV J0 SJ1"; yaxis_title = "Events / 0.1"; variable = "HJets_csvSubjet1[0]"; cut = cut0; PlottiPlotta(); nbins = 10; minBin =0., width = 0.11; maxBin = minBin + nbins*width; plotName = "nCSV_J1_SJ1_noBtagSF_" + sampleName[i]; histo_title = ""; xaxis_title = "CSV J1 SJ1"; yaxis_title = "Events / 0.1"; variable = "HJets_csvSubjet1[1]"; cut = cut0; PlottiPlotta(); nbins = 6; minBin =-0.5, width = 1; maxBin = minBin + nbins*width; plotName = "nCSV_noBtagSF_" + sampleName[i]; histo_title = ""; xaxis_title = "N(CSV0)+N(CSV1)"; yaxis_title = "Events"; variable = "HJets_nsubjetsBTaggedCSVL[0]+HJets_nsubjetsBTaggedCSVL[1]"; cut = cut0; PlottiPlotta(); //====================================================== // R2S->Print(); nbins = 150; minBin = 1000., width = 20.; maxBin = minBin + nbins*width; plotName = "TotalMass3btag_" + sampleName[i]; histo_title = "3 btags"; xaxis_title = "m_{4b} (GeV)"; yaxis_title = "Events / 20 GeV"; variable = "SelectedEvent_minv_leading2hjets"; cut0 = "(HJets_nsubjetsBTaggedCSVL[0]+HJets_nsubjetsBTaggedCSVL[1])>2.99"; cut = cut0*generalCut; PlottiPlotta(); nbins = 150; minBin = 1000., width = 20.; maxBin = minBin + nbins*width; plotName = "TotalMass4btag_" + sampleName[i]; histo_title = "4 btags"; xaxis_title = "m_{4b} (GeV)"; yaxis_title = "Events / 20 GeV"; variable = "SelectedEvent_minv_leading2hjets"; cut0 = "(HJets_nsubjetsBTaggedCSVL[0]+HJets_nsubjetsBTaggedCSVL[1])>3.99"; cut = cut0*generalCut; PlottiPlotta(); nbins = 10; minBin =0., width = 0.1; maxBin = minBin + nbins*width; plotName = "TAU21_J0_" + sampleName[i]; histo_title = ""; xaxis_title = "#tau_{21} J0"; yaxis_title = "Events / 0.1"; variable = "HJets_tau2[0]/HJets_tau1[0]"; cut0 = ""; cut = cut0*generalCut; PlottiPlotta(); nbins = 10; minBin =0., width = 0.1; maxBin = minBin + nbins*width; plotName = "TAU21_J1_" + sampleName[i]; histo_title = ""; xaxis_title = "#tau_{21} J1"; yaxis_title = "Events / 0.1"; variable = "HJets_tau2[1]/HJets_tau1[1]"; cut0 = ""; cut = cut0*generalCut; PlottiPlotta(); test->Close(); f1->Close(); } fWrite->Close(); }
LadspaManager::LadspaManager() { // Make sure plugin search paths are set up PluginFactory::instance(); QStringList ladspaDirectories = QString( getenv( "LADSPA_PATH" ) ). split( LADSPA_PATH_SEPERATOR ); ladspaDirectories += ConfigManager::inst()->ladspaDir().split( ',' ); ladspaDirectories.push_back( "plugins:ladspa" ); #ifndef LMMS_BUILD_WIN32 ladspaDirectories.push_back( qApp->applicationDirPath() + '/' + LIB_DIR + "ladspa" ); ladspaDirectories.push_back( "/usr/lib/ladspa" ); ladspaDirectories.push_back( "/usr/lib64/ladspa" ); ladspaDirectories.push_back( "/usr/local/lib/ladspa" ); ladspaDirectories.push_back( "/usr/local/lib64/ladspa" ); ladspaDirectories.push_back( "/Library/Audio/Plug-Ins/LADSPA" ); #endif for( QStringList::iterator it = ladspaDirectories.begin(); it != ladspaDirectories.end(); ++it ) { QDir directory( ( *it ) ); QFileInfoList list = directory.entryInfoList(); for( QFileInfoList::iterator file = list.begin(); file != list.end(); ++file ) { const QFileInfo & f = *file; if( !f.isFile() || f.fileName().right( 3 ).toLower() != #ifdef LMMS_BUILD_WIN32 "dll" #else ".so" #endif ) { continue; } QLibrary plugin_lib( f.absoluteFilePath() ); if( plugin_lib.load() == true ) { LADSPA_Descriptor_Function descriptorFunction = ( LADSPA_Descriptor_Function ) plugin_lib.resolve( "ladspa_descriptor" ); if( descriptorFunction != NULL ) { addPlugins( descriptorFunction, f.fileName() ); } } else { qWarning() << plugin_lib.errorString(); } } } l_ladspa_key_t keys = m_ladspaManagerMap.keys(); for( l_ladspa_key_t::iterator it = keys.begin(); it != keys.end(); ++it ) { m_sortedPlugins.append( qMakePair( getName( *it ), *it ) ); } qSort( m_sortedPlugins ); }
void getDirectoryListing( std::vector< std::string >& listing, const std::string& dir, const std::string& extension, bool appenddetails ) { std::list< std::pair< std::string, std::string > > files; #ifdef WIN32 WIN32_FIND_DATA findData; HANDLE fileHandle; int flag = 1; std::string search ( ( extension == "" ) ? "*" : "*." ); std::string directory( dir ); if ( directory == "" ) directory = "."; directory += "/"; search = directory + search + extension; fileHandle = FindFirstFile( search.c_str(), &findData ); if ( fileHandle == INVALID_HANDLE_VALUE ) return; while ( flag ) { if ( strcmp( findData.cFileName, "." ) && strcmp( findData.cFileName, ".." ) ) { std::string details; if ( appenddetails ) details = convertFileTime( findData.ftLastWriteTime ); // check for directories if( findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY ) files.push_back( make_pair( "[" + std::string( findData.cFileName ) + "]", details ) ); else files.push_back( make_pair( findData.cFileName, details ) ); } flag = FindNextFile( fileHandle, &findData ); } FindClose( fileHandle ); #endif #ifdef LINUX struct stat fileInfo; glob_t ff_glob; std::string directory( dir ); if ( directory == "" ) directory = "."; directory += "/"; std::string search = directory + "*" + extension; // check if the directory exists if ( opendir( directory.c_str() ) == NULL ) return; glob( search.c_str(), 0, NULL, &ff_glob ); for ( size_t cnt = 0; cnt < ff_glob.gl_pathc; ++cnt ) { std::string filename( ff_glob.gl_pathv[ cnt ] ); filename.erase( 0, directory.size() ); std::string details; // check for directories stat( std::string( directory + filename ).c_str(), &fileInfo ); if ( appenddetails ) { time_t modtime = fileInfo.st_mtime; details = ctime( &modtime ); details.erase( details.size() - 1 ); // remove line break at end of string } if( S_ISDIR( fileInfo.st_mode ) ) files.push_back( make_pair( "[" + std::string( filename ) + "]", details ) ); else files.push_back( make_pair( filename, details ) ); } #endif // sort and copy files into listing files.sort(); std::list< std::pair< std::string, std::string > >::iterator p_beg = files.begin(), p_end = files.end(); for ( ; p_beg != p_end; ++p_beg ) { if ( appenddetails ) listing.push_back( p_beg->second + " " + p_beg->first ); else listing.push_back( p_beg->first ); } }
/**OK * Comprime la cartella dir nel file fileCompressed, se recursive e true allora * comprime anche le sotto cartelle. I nomi dei file preceduti dal path creato * togliendo il pat della cartella origDir al path della cartella dir. * Se la funzione fallisce restituisce false e cancella il file che si e tentato * di creare. * * La funzione fallisce se: * * zip==NULL; * * l'oggetto zip e stato aperto in una modalita non compatibile con l'aggiunta di file; * * la cartella dir non esiste; * * la compressione di una sotto cartella fallisce (1); * * la compressione di un file fallisce; * (1) La funzione si richiama in maniera ricorsiva per comprimere le sotto cartelle * dunque gli errori di compressione di una sotto cartella sono gli stessi di questa * funzione. */ bool JlCompress::compressSubDir(QuaZip* zip, QString dir, QString origDir, bool recursive) { // zip: oggetto dove aggiungere il file // dir: cartella reale corrente // origDir: cartella reale originale // (path(dir)-path(origDir)) = path interno all'oggetto zip // Controllo l'apertura dello zip if(!zip) { return false; } if(zip->getMode() != QuaZip::mdCreate && zip->getMode() != QuaZip::mdAppend && zip->getMode() != QuaZip::mdAdd) { return false; } // Controllo la cartella QDir directory(dir); if(!directory.exists()) { return false; } // Se comprimo anche le sotto cartelle if(recursive) { // Per ogni sotto cartella QFileInfoList files = directory.entryInfoList(QDir::AllDirs | QDir::NoDotAndDotDot); Q_FOREACH(QFileInfo file, files) { // Comprimo la sotto cartella if(!compressSubDir(zip, file.absoluteFilePath(), origDir, recursive)) { return false; } } } // Per ogni file nella cartella QFileInfoList files = directory.entryInfoList(QDir::Files); QDir origDirectory(origDir); Q_FOREACH(QFileInfo file, files) { // Se non e un file o e il file compresso che sto creando if(!file.isFile() || file.absoluteFilePath() == zip->getZipName()) { continue; } // Creo il nome relativo da usare all'interno del file compresso QString filename = origDirectory.relativeFilePath(file.absoluteFilePath()); // Comprimo il file if(!compressFile(zip, file.absoluteFilePath(), filename)) { return false; } } return true; }
void CollectionScanner::scanFiles( const QStringList& entries ) { typedef QPair<QString, QString> CoverBundle; QStringList validImages; validImages << "jpg" << "png" << "gif" << "jpeg" << "bmp"; QStringList validPlaylists; validPlaylists << "m3u" << "pls"; QList<CoverBundle> covers; QStringList images; int itemCount = 0; for( QStringList::ConstIterator it = entries.constBegin(), end = entries.constEnd(); it != end; ++it ) { const QString path = *it; const QString ext = extension( path ); const QString dir = directory( path ); itemCount++; // Write path to logfile if( !m_logfile.isEmpty() ) { QFile log( m_logfile ); if( log.open( QIODevice::WriteOnly ) ) { QByteArray cPath = path.toUtf8(); log.write( cPath, cPath.length() ); log.close(); } } if( validImages.contains( ext ) ) images += path; else if( m_importPlaylists && validPlaylists.contains( ext ) ) { AttributeHash attributes; if( m_batch && !m_rpath.isEmpty() ) { QString rpath = path; rpath.remove( QDir::cleanPath( QDir::currentPath() ) ); rpath.prepend( QDir::cleanPath( m_rpath + '/' ) ); attributes["path"] = rpath; } else attributes["path"] = path; writeElement( "playlist", attributes ); } else { //FIXME: PORT 2.0 // QList<EmbeddedImage> images; const AttributeHash attributes = readTags( path ); if( !attributes.empty() ) { writeElement( "tags", attributes ); CoverBundle cover( attributes["artist"], attributes["album"] ); if( !covers.contains( cover ) ) covers += cover; //FIXME: PORT 2.0 // foreach( EmbeddedImage image, images ) // { // AttributeHash attributes; // if( m_batch && !m_rpath.isEmpty() ) // { // QString rpath = path; // rpath.remove( QDir::cleanPath( QDir::currentPath() ) ); // rpath.prepend( QDir::cleanPath( m_rpath + '/' ) ); // attributes["path"] = rpath; // } // else // attributes["path"] = path; // attributes["hash"] = image.hash(); // attributes["description"] = image.description(); // writeElement( "embed", attributes ); // } } } // Update Compilation-flag, when this is the last loop-run // or we're going to switch to another dir in the next run QStringList::const_iterator itTemp( it ); ++itTemp; if( path == entries.last() || dir != directory( *itTemp ) ) { // we entered the next directory foreach( const QString &imagePath, images ) { // Serialize CoverBundle list with AMAROK_MAGIC as separator QString string; for( QList<CoverBundle>::ConstIterator it2 = covers.begin(); it2 != covers.end(); ++it2 ) { string += ( string.isEmpty() ? "" : "AMAROK_MAGIC" ) + (*it2).first + "AMAROK_MAGIC" + (*it2).second; } AttributeHash attributes; if( m_batch && !m_rpath.isEmpty() ) { QString rpath = imagePath; rpath.remove( QDir::cleanPath( QDir::currentPath() ) ); rpath.prepend( QDir::cleanPath( m_rpath + '/' ) ); attributes["path"] = rpath; } else attributes["path"] = imagePath; attributes["list"] = string; writeElement( "image", attributes ); } AttributeHash attributes; if( m_batch && !m_rpath.isEmpty() ) { QString rdir = dir; rdir.remove( QDir::cleanPath( QDir::currentPath() ) ); rdir.prepend( QDir::cleanPath( m_rpath + '/' ) ); attributes["path"] = rdir; } else attributes["path"] = dir; writeElement( "compilation", attributes ); // clear now because we've processed them covers.clear(); images.clear(); }
bool CGUIWindowMusicSongs::OnMessage(CGUIMessage& message) { switch ( message.GetMessage() ) { case GUI_MSG_WINDOW_DEINIT: if (m_thumbLoader.IsLoading()) m_thumbLoader.StopThread(); break; case GUI_MSG_WINDOW_INIT: { // removed the start window check from files view // the window translator does it by using a virtual window id (5) // is this the first time the window is opened? if (m_vecItems->GetPath() == "?" && message.GetStringParam().IsEmpty()) message.SetStringParam(g_settings.m_defaultMusicSource); return CGUIWindowMusicBase::OnMessage(message); } break; case GUI_MSG_DIRECTORY_SCANNED: { CFileItem directory(message.GetStringParam(), true); // Only update thumb on a local drive if (directory.IsHD()) { CStdString strParent; URIUtils::GetParentPath(directory.GetPath(), strParent); if (directory.GetPath() == m_vecItems->GetPath() || strParent == m_vecItems->GetPath()) Refresh(); } } break; case GUI_MSG_NOTIFY_ALL: { if (message.GetParam1()==GUI_MSG_REMOVED_MEDIA) DeleteRemoveableMediaDirectoryCache(); } break; case GUI_MSG_CLICKED: { int iControl = message.GetSenderId(); if (iControl == CONTROL_BTNPLAYLISTS) { if (!m_vecItems->GetPath().Equals("special://musicplaylists/")) Update("special://musicplaylists/"); } else if (iControl == CONTROL_BTNSCAN) { OnScan(-1); } else if (iControl == CONTROL_BTNREC) { if (g_application.IsPlayingAudio() ) { if (g_application.m_pPlayer->CanRecord() ) { bool bIsRecording = g_application.m_pPlayer->IsRecording(); g_application.m_pPlayer->Record(!bIsRecording); UpdateButtons(); } } } else if (iControl == CONTROL_BTNRIP) { OnRipCD(); } } break; } return CGUIWindowMusicBase::OnMessage(message); }
TrackSupplier* FilePlaylistItem::CreateTrackSupplier() const { MediaFileTrackSupplier* supplier = new(std::nothrow) MediaFileTrackSupplier(); if (supplier == NULL) return NULL; for (vector<entry_ref>::size_type i = 0; i < fRefs.size(); i++) { BMediaFile* mediaFile = new(std::nothrow) BMediaFile(&fRefs[i]); if (mediaFile == NULL) { delete supplier; return NULL; } if (supplier->AddMediaFile(mediaFile) != B_OK) delete mediaFile; } for (vector<entry_ref>::size_type i = 0; i < fImageRefs.size(); i++) { BBitmap* bitmap = BTranslationUtils::GetBitmap(&fImageRefs[i]); if (bitmap == NULL) continue; if (supplier->AddBitmap(bitmap) != B_OK) delete bitmap; } // Search for subtitle files in the same folder // TODO: Error checking BEntry entry(&fRefs[0], true); char originalName[B_FILE_NAME_LENGTH]; entry.GetName(originalName); BString nameWithoutExtension(originalName); int32 extension = nameWithoutExtension.FindLast('.'); if (extension > 0) nameWithoutExtension.Truncate(extension); BPath path; entry.GetPath(&path); path.GetParent(&path); BDirectory directory(path.Path()); while (directory.GetNextEntry(&entry) == B_OK) { char name[B_FILE_NAME_LENGTH]; if (entry.GetName(name) != B_OK) continue; BString nameString(name); if (nameString == originalName) continue; if (nameString.IFindFirst(nameWithoutExtension) < 0) continue; BFile file(&entry, B_READ_ONLY); if (file.InitCheck() != B_OK) continue; int32 pos = nameString.FindLast('.'); if (pos < 0) continue; BString extensionString(nameString.String() + pos + 1); extensionString.ToLower(); BString language = "default"; if (pos > 1) { int32 end = pos; while (pos > 0 && *(nameString.String() + pos - 1) != '.') pos--; language.SetTo(nameString.String() + pos, end - pos); } if (extensionString == "srt") { SubTitles* subTitles = new(std::nothrow) SubTitlesSRT(&file, language.String()); if (subTitles != NULL && !supplier->AddSubTitles(subTitles)) delete subTitles; } } return supplier; }
//------------------------------------------------------------------------------------ void ExtractThread::extractFiles(QString path, const OFS::FileList& list) { std::ofstream out_handle; OFS::OFSHANDLE in_handle; unsigned int output_amount = 0; mutex.lock(); currentPos = 0.0f; msgProgress = ""; mutex.unlock(); for(unsigned int i = 0;i < list.size();i++) { if(list[i].flags & OFS::OFS_DIR) { QString dir_path = path + QString("/") + QString(list[i].name.c_str()); QDir directory(dir_path); directory.mkpath(dir_path); } else { std::string file_path = path.toStdString() + std::string("/") + list[i].name; std::string file_ofs_path = list[i].name; QFileInfo info(QString(file_path.c_str())); QDir directory(info.absolutePath()); directory.mkpath(info.absolutePath()); mutex.lock(); msgProgress = file_ofs_path.c_str(); mutex.unlock(); out_handle.open(file_path.c_str(), std::ofstream::out | std::ofstream::binary); if(out_handle.is_open()) { try { OFS::OfsResult ret = ofsFile->openFile(in_handle, file_ofs_path.c_str()); if(ret != OFS::OFS_OK) { out_handle.close(); continue; } unsigned int total = list[i].file_size; while(total > 0) { if(total < MAX_BUFFER_SIZE) { ofsFile->read(in_handle, tmp_buffer, total); out_handle.write(tmp_buffer, total); output_amount += total; total = 0; } else { ofsFile->read(in_handle, tmp_buffer, MAX_BUFFER_SIZE); out_handle.write(tmp_buffer, MAX_BUFFER_SIZE); total -= MAX_BUFFER_SIZE; output_amount += MAX_BUFFER_SIZE; } if(mTotalFileSize > 0) { mutex.lock(); currentPos = (float)output_amount / (float)mTotalFileSize; mutex.unlock(); } } } catch(OFS::Exception& e) { QMessageBox::information(QApplication::activeWindow(),"Ofs Exception:", tr("Error Extracting File : ") + QString(file_ofs_path.c_str()) + QString("\n") + QString(e.getDescription().c_str()), QMessageBox::Ok); } out_handle.close(); ofsFile->closeFile(in_handle); } } } mutex.lock(); currentPos = 1.0f; msgProgress = tr("Finished Extracting"); mutex.unlock(); }
SlideshowClip::SlideshowClip(const Timecode &tc, QString clipFolder, ProjectClip *clip, QWidget * parent) : QDialog(parent), m_count(0), m_timecode(tc), m_thumbJob(NULL) { setFont(QFontDatabase::systemFont(QFontDatabase::SmallestReadableFont)); setWindowTitle(i18n("Add Slideshow Clip")); m_view.setupUi(this); if (clip) { m_view.clip_name->setText(clip->name()); m_view.groupBox->setHidden(true); } else m_view.clip_name->setText(i18n("Slideshow Clip")); m_view.folder_url->setMode(KFile::Directory); m_view.folder_url->setUrl(QUrl::fromLocalFile(KRecentDirs::dir(QStringLiteral(":KdenliveSlideShowFolder")))); m_view.icon_list->setIconSize(QSize(50, 50)); m_view.show_thumbs->setChecked(KdenliveSettings::showslideshowthumbs()); connect(m_view.folder_url, SIGNAL(textChanged(QString)), this, SLOT(parseFolder())); connect(m_view.image_type, SIGNAL(currentIndexChanged(int)), this, SLOT(parseFolder())); connect(m_view.pattern_url, SIGNAL(textChanged(QString)), this, SLOT(parseFolder())); connect(m_view.show_thumbs, SIGNAL(stateChanged(int)), this, SLOT(slotEnableThumbs(int))); connect(m_view.slide_fade, SIGNAL(stateChanged(int)), this, SLOT(slotEnableLuma(int))); connect(m_view.luma_fade, SIGNAL(stateChanged(int)), this, SLOT(slotEnableLumaFile(int))); //WARNING: keep in sync with project/clipproperties.cpp m_view.image_type->addItem(QStringLiteral("JPG (*.jpg)"), "jpg"); m_view.image_type->addItem(QStringLiteral("JPEG (*.jpeg)"), "jpeg"); m_view.image_type->addItem(QStringLiteral("PNG (*.png)"), "png"); m_view.image_type->addItem(QStringLiteral("SVG (*.svg)"), "svg"); m_view.image_type->addItem(QStringLiteral("BMP (*.bmp)"), "bmp"); m_view.image_type->addItem(QStringLiteral("GIF (*.gif)"), "gif"); m_view.image_type->addItem(QStringLiteral("TGA (*.tga)"), "tga"); m_view.image_type->addItem(QStringLiteral("TIF (*.tif)"), "tif"); m_view.image_type->addItem(QStringLiteral("TIFF (*.tiff)"), "tiff"); m_view.image_type->addItem(QStringLiteral("Open EXR (*.exr)"), "exr"); m_view.animation->addItem(i18n("None"), QString()); m_view.animation->addItem(i18n("Pan"), "Pan"); m_view.animation->addItem(i18n("Pan, low-pass"), "Pan, low-pass"); m_view.animation->addItem(i18n("Pan and zoom"), "Pan and zoom"); m_view.animation->addItem(i18n("Pan and zoom, low-pass"), "Pan and zoom, low-pass"); m_view.animation->addItem(i18n("Zoom"), "Zoom"); m_view.animation->addItem(i18n("Zoom, low-pass"), "Zoom, low-pass"); m_view.clip_duration->setInputMask(m_timecode.mask()); m_view.luma_duration->setInputMask(m_timecode.mask()); m_view.luma_duration->setText(m_timecode.getTimecodeFromFrames(int(ceil(m_timecode.fps())))); if (clipFolder.isEmpty()) { clipFolder = QDir::homePath(); } m_view.folder_url->setUrl(QUrl::fromLocalFile(clipFolder)); m_view.clip_duration_format->addItem(i18n("hh:mm:ss:ff")); m_view.clip_duration_format->addItem(i18n("Frames")); connect(m_view.clip_duration_format, SIGNAL(activated(int)), this, SLOT(slotUpdateDurationFormat(int))); m_view.clip_duration_frames->setHidden(true); m_view.luma_duration_frames->setHidden(true); m_view.method_mime->setChecked(KdenliveSettings::slideshowbymime()); connect(m_view.method_mime, SIGNAL(toggled(bool)), this, SLOT(slotMethodChanged(bool))); slotMethodChanged(m_view.method_mime->isChecked()); // Check for Kdenlive installed luma files QStringList filters; filters << QStringLiteral("*.pgm") << QStringLiteral("*.png"); QStringList customLumas = QStandardPaths::locateAll(QStandardPaths::DataLocation, QStringLiteral("lumas")); foreach(const QString & folder, customLumas) { QDir directory(folder); QStringList filesnames = directory.entryList(filters, QDir::Files); foreach(const QString & fname, filesnames) { QString filePath = directory.absoluteFilePath(fname); m_view.luma_file->addItem(QIcon::fromTheme(filePath), fname, filePath); }