Exemple #1
0
VideoAsset::VideoAsset(bfs::path videoFile, bfs::path path, bool copy) : path(path) {
    try {
        name = path.filename().string();
        if(!bfs::exists(videoFile)) throw VideoAssetException("video File doesn't exist!");
        if(!bfs::exists(path) || !bfs::is_directory(path)) throw VideoAssetException("Destination folder doesn't exist");
        if(copy) {
            video_path = path;
            video_path /= videoFile.filename();
            bfs::copy_file(videoFile, video_path, bfs::copy_option::overwrite_if_exists);
        } else video_path = videoFile;
        
        isExternal = !copy;

        loadPlayerSync();

        writeInfoFile();
        
        hasTimetable = false;
        hasShotBoundaries = false;
        hasHistograms = false;
        hasMeans = false;
        isReady = false;
    } catch (const bfs::filesystem_error& ex) {
        (*Tobago.log)(Log::ERROR) << "Error creating video asset " << path.string() << ": " << ex.what();
        throw VideoAssetException(ex.what());
    }
}
Exemple #2
0
void basics::copy_folder(const bfs::path& frompath, const bfs::path& topath) 
{
    // Check whether the function call is valid
    if (!bfs::exists(frompath) || !bfs::is_directory(frompath)) {
        std::stringstream err;
        err << "Source directory " << frompath.string() << " does not exist or is not a directory.";
        throw std::runtime_error(err.str());
    }
    if(bfs::exists(topath)) {
        std::stringstream err;
        err << "Destination directory " << topath.string() << " already exists.";
        throw std::runtime_error(err.str());
    }
    // Create the destination directory
    if(!bfs::create_directory(topath))
    {
        std::stringstream err;
        err << "Unable to create destination directory " << topath.string();
        throw std::runtime_error(err.str());
    }

    // Iterate through the source directory
    for(bfs::directory_iterator file(frompath); file != bfs::directory_iterator(); ++file) {
        bfs::path current(file->path());
        
        if(bfs::is_directory(current)) {
            // Found directory: Recursion
            copy_folder(current, topath / current.filename());
        }
        else {
            // Found file: Copy
            bfs::copy_file(current, topath / current.filename());
        }
    }
}
 bfs::path GetParentPath(const bfs::path& path) {
     #if defined(USE_BOOST_FILESYSTEM_V3) || defined(USE_NON_DEPRECATED_BOOST_FILESYSTEM_V2)
         return path.parent_path();
     #else
         return path.branch_path();
     #endif
 }
Exemple #4
0
void World::saveToFile(const bfs::path & path) const
{
   Logger::get().debug("Сохранение объектов в файл %1%") % path.string();

   json::Object jworld(json::Object::Hash);

   // Local rect
   {
      b2AABB combinedAABB;
      combinedAABB.lowerBound.Set( FLT_MAX,  FLT_MAX);
      combinedAABB.upperBound.Set(-FLT_MAX, -FLT_MAX);
      for(const b2Body * b2body = getB2World()->GetBodyList(); b2body; b2body = b2body->GetNext())
      {
         const Body * body = static_cast<const Body *>(b2body->GetUserData());
         if(body->isDynamic())
            combinedAABB.Combine(body->getB2AABB());
      }
      jworld.add("aabb", Rectf::fromB2AABB(combinedAABB).toJson());
   }

   // Bodies
   {
      json::Object jentities(json::Object::Array);
      for(auto it = getBodyIterator(); it; ++it)
         if(it.get()->isDynamic())
            jentities.add(it.get()->getEntity()->toJson());

      jworld.add("entities", std::move(jentities));
   }

   std::ofstream file(path.string());
   assert(file.good());
   file << std::move(jworld.toString(false));
}
Exemple #5
0
bfs::path find_codedb_path(const bfs::path& p) {
  if (p.empty()) return p;

  if (bfs::exists(p / ".codedb")) return p / ".codedb";

  return find_codedb_path(p.parent_path());
}
Exemple #6
0
void BamReaderPool::openBamFile(const bfs::path& file) {
	if (file.empty()) {
		throw BamReaderPoolException("No BAM file specified.");
	}
	std::lock_guard<std::mutex> lock(poolmtx_); // GUARD
	closeBamFile_nolock();
	if (!open_) {
		// try to open all readers
		for (BamTools::BamReader& reader : readers_) {
			if (!reader.Open(file.c_str())) {
				throw BamReaderPoolException(
						"Unable to open BAM file " + file.string() + ":\n\t"
								+ reader.GetErrorString());
			}
		}
		// try to open index
		for (BamTools::BamReader& reader : readers_) {
			if (!reader.LocateIndex()) {
				throw BamReaderPoolException(
						"Unable to open BAM index file " + file.string() + ":\n\t"
								+ reader.GetErrorString());
			}
		}
		// all are open, now push them onto the queue
		for (BamTools::BamReader& reader : readers_) {
			pushReader(reader);
		}
		file_ = file;
		open_ = true;
	} else {
		throw BamReaderPoolException("Failed to close BAM reader pool.");
	}
}
Exemple #7
0
void condor2nav::Download(const std::string &server, const bfs::path &url, const bfs::path &fileName, unsigned timeout /* = 30 */)
{
  DirectoryCreate(fileName.parent_path());
  bfs::ofstream out{fileName, std::ios_base::out | std::ios_base::binary};
  CIStream in{server, url.generic_string(), timeout};
  out << in;
}
Exemple #8
0
	bfs::path request_new_project_path( bfs::path default_path )
	{
		if( default_path.empty() )
			default_path = path::DEFAULT_PROJECTS_DIR;

		return bfs::path( QFileDialog::getExistingDirectory( nullptr
															, QObject::tr("New AOS Designer Project Location")
															, QString::fromStdString( default_path.string() )
															).toStdString() );
	}
Exemple #9
0
	bfs::path request_project_path( bfs::path default_path )
	{
		if( default_path.empty() )
			default_path = path::DEFAULT_PROJECTS_DIR;

		return bfs::path( QFileDialog::getOpenFileName( nullptr
														, QObject::tr( "Open AOS Designer Project" )
														, QString::fromStdString( default_path.string() )
														, QObject::tr( "AOS Designer Project (*.aosp)" )
														).toStdString() );
	}
// Analysis routine
void Crawler::analyse_image(const bfs::path& path) 
{
    std::ostringstream msg;
    msg << "Running image analysis on " << path;
	logger->message(msg.str(), traceLevel);

    // Construct and segment picture
    std::auto_ptr<ImageAnalyst> \
        analyst(new ImageAnalyst(bfs::absolute(path.filename()), 
            analyst_settings));
	analyst->segment();
	
	// Get centroids and dump to file if required 
	if (settings.output) {   
	    std::ostringstream msg; 
        msg << "Dumping segment centroids to " << settings.outputfile;
        logger->message(msg.str(), traceLevel);
        
        // Get segmentation window size
        blitz::TinyVector<int, 4> wsize = analyst->get_window_size();
        
        // Open dumpfile as stream, add path, altered path and image and 
        // window sizes  
        std::fstream dumpFileStream;
        dumpFileStream.open(settings.outputfile.string().c_str(), 
            std::fstream::out | std::fstream::app); 
        dumpFileStream << "{'original_file': '" << path.string()
                       << "', 'segmented_file': '" 
                       << path.stem() << "_segments" << bfs::extension(path) 
                       << "', 'image_size': (" 
                       << analyst->columns() << ", " << analyst->rows() 
                       << "), 'window_size': (" << wsize[0] << ", " 
                       << wsize[1] << ", " << wsize[2] << ", " 
                       << wsize[3] << "), ";
        
        // Get centroids, push to file
        std::vector<Index> centroids;
        analyst->get_centroids(centroids); 
        dumpFileStream << "'centroids': [";
        foreach(Index index, centroids)
            dumpFileStream << "(" << index[0] << "," << index[1] << "), ";
        dumpFileStream << "]}" << std::endl;  
        
        // Clean up
        dumpFileStream.flush();
        dumpFileStream.close();
    }
    
    // Exit
	logger->message("Done!", traceLevel);
}
ReadCameraParameter::ReadCameraParameter(boost::filesystem::path p){
	ifstream camera;
	std::string ignore;
	double tmp ;

	BFS::path txt = p/ "camera.txt";
	camera.open(txt.string().c_str());
	if( !camera.is_open() ) cout << "Cannot open cameraParameter!" << endl;
	else cout << "Success!!!!" << endl;
	if( !camera.eof()){
		for (int i = 0; i< 5; ++i) getline(camera, ignore, '\n');  // ignore words	
		camera >> no_frame;	// number of frames
		cout << "There are " << no_frame << " frames." << endl;
		getline(camera, ignore, '\n');  // ignore 

		for(int s = 0; s < no_frame; s++){ // read camera_para of frames
			
			/* read matrix for K */
			CvMat* k = cvCreateMat(3, 3, CV_64FC1);
			for(int i = 0; i < 9; i++){
					camera >> tmp;
					cvmSet(k, (int) (i/3), i%3, tmp);
					//cout << i << " " << tmp[i] << endl;
				}
			K.push_back(k);

			/* read matrix for R */
			CvMat* r = cvCreateMat(3, 3, CV_64FC1);
			for(int i = 0; i < 9; i++){
					camera >> tmp;
					cvmSet(r, (int) (i/3), i%3, tmp);
					//cout << i << " " << tmp[i] << endl;
				}
			R.push_back(r);
			
			/* read matrix for T */
			CvMat* t = cvCreateMat(3, 1, CV_64FC1);
			for(int i = 0; i < 3; i++){
					camera >> tmp;
					cvmSet(t, i%3, 0, tmp);
					//cout << i << " " << tmp[i] << endl;
				}
			T.push_back(t);
			
			for (int i =0; i< 3; ++i)
			getline(camera, ignore, '\n');  // ignore 
		}
		
	}
	camera.close();
}
void RunFolderGenerator::generateRunInfo() const
{
    using boost::property_tree::ptree;
    ptree pt;
    pt.put("RunInfo.<xmlattr>.xmlns:xsd", "http://www.w3.org/2001/XMLSchema");
    pt.put("RunInfo.<xmlattr>.xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
    pt.put("RunInfo.<xmlattr>.Version", "2");
    pt.put("RunInfo.Run.<xmlattr>.Id", runFolder_);
    pt.put("RunInfo.Run.<xmlattr>.Number", runInfo_.runNumber);
    pt.put("RunInfo.Run.<xmlattr>.TileNameMethod", runInfo_.tileNameMethod);
    ptree &run = pt.get_child("RunInfo.Run");
    run.put("Flowcell", flowcell_);
    run.put("Date", runFolderDate_);
    run.put("FlowcellLayout.<xmlattr>.LaneCount", runInfo_.laneCount);
    run.put("FlowcellLayout.<xmlattr>.SurfaceCount", runInfo_.surfaceCount);
    run.put("FlowcellLayout.<xmlattr>.SwathCount", runInfo_.swathCount);
    run.put("FlowcellLayout.<xmlattr>.TileCount", runInfo_.tileCount);
    run.put("Reads", "");
    ptree &reads = run.get_child("Reads");

    int readNum = 1;
    BOOST_FOREACH(const eagle::io::ReadDescription &rd, runInfo_.reads)
    {
        ptree read;

        // Attributes for recent RunInfo.xml format
        read.put("<xmlattr>.Number", readNum++);
        read.put("<xmlattr>.IsIndexedRead", rd.isIndex?"Y":"N");
        read.put("<xmlattr>.NumCycles", rd.lastCycle - rd.firstCycle + 1);

        // Attributes for older RunInfo.xml format
        read.put("<xmlattr>.FirstCycle", rd.firstCycle);
        read.put("<xmlattr>.LastCycle", rd.lastCycle);
        if (rd.isIndex)
        {
            read.put("Index", "");
        }

        reads.add_child("Read", read);
    }

    const boost::property_tree::xml_writer_settings<string> w(' ', 2);
    const bfs::path runInfoPath = runFolderPath_ / "RunInfo.xml";

    // DEBUG
    std::clog << "Writing RunInfo file " << runInfoPath.string() << std::endl;

    write_xml(runInfoPath.string(), pt, std::locale(), w);
}
 std::string GetExtension(const bfs::path& path) {
     #if defined(USE_BOOST_FILESYSTEM_V3)
         return path.extension().string();
     #else
         return bfs::extension(path);
     #endif
 }
void testDefaultTabHandler(const bfs::path& datafile)
{
    const char* alphabet = "abcd";
    const char* numbers = "1234";

    TabReader tr;
    VectorTabHandler vth;

    tr.setHandler(&vth);
    tr.process(datafile.string().c_str());

    VectorTabHandler::const_iterator it = vth.begin();
    cout << (* (*it).begin()) << endl;

    size_t y=0;
    for (; it != vth.end(); it++)
    {
        size_t x=0;
        for (vector<string>::const_iterator it2=(*it).begin(); it2!=(*it).end();it2++)
        {
            const char* value = (*it2).c_str();
            unit_assert(value[0] == alphabet[x]);
            unit_assert(value[1] == numbers[y]);
            x++;
        }
        cerr << endl;
        y++;
    }
}
Exemple #15
0
void create_file(const bfs::path& ph, const string& contents)
{
    ofstream f(ph.string().c_str());
    if (!f)
        throw bfs::filesystem_error("create_file", ph, error_code(errno, SYSTEMCATEGORY));
    if (!contents.empty()) f << contents;
}
Exemple #16
0
DistributedObject::DistributedObject(const bfs::path& file)
	: persistence_enabled_(false),
	  path_(bfs::path()),
	  file_(!path_.string().empty() && !file.string().empty() ? (path_ / file) : bfs::path()),
	  timestamp_(0)
{
}
void testMSIHandler(const bfs::path& datafile)
{
    TabReader tr;
    MSIHandler mh;

    tr.setHandler(&mh);
    tr.process(datafile.string().c_str());
}
Exemple #18
0
/**
* @brief Returns file type.
*
* Determinates file type based on its name.
*/
condor2nav::TPathType condor2nav::PathType(const bfs::path &fileName)
{
  std::string str{fileName.string()};
  if(str.size() > 2 && str[0] == '\\' && str[1] != '\\')
    return TPathType::ACTIVE_SYNC;
  else
    return TPathType::LOCAL;
}
/**
 * Just initialize fields, does not loads the data.
 *
 * @param pFilename Where the configuration data will be stored.
 */
YubikoOtpKeyConfig::YubikoOtpKeyConfig(KeyManager& pKeyManager,
		const bfs::path& pFilename) :
		itsKeyManager(pKeyManager), itsChangedFlag(false), itsFilename(
				pFilename) {
	BOOST_LOG_NAMED_SCOPE("YubikoOtpKeyConfig::YubikoOtpKeyConfig");
	BOOST_LOG_TRIVIAL(debug)<< "Passed filename:  " << pFilename.native();
	zeroToken();
}
Exemple #20
0
PWIZ_API_DECL void expand_pathmask(const bfs::path& pathmask,
                                   vector<bfs::path>& matchingPaths)
{
    using bfs::path;

#ifdef WIN32
    path maskParentPath = pathmask.branch_path();
	WIN32_FIND_DATA fdata;
	HANDLE srcFile = FindFirstFileEx(pathmask.string().c_str(), FindExInfoStandard, &fdata, FindExSearchNameMatch, NULL, 0);
	if (srcFile == INVALID_HANDLE_VALUE)
		return; // no matches

    do
    {
        if (strcmp(fdata.cFileName, ".") != 0 &&
            strcmp(fdata.cFileName, "..") != 0)
	        matchingPaths.push_back( maskParentPath / fdata.cFileName );
    }
    while (FindNextFile(srcFile, &fdata));

	FindClose(srcFile);

#else

	glob_t globbuf;
	int rv = glob(pathmask.string().c_str(), 0, NULL, &globbuf);
	if(rv > 0 && rv != GLOB_NOMATCH)
		throw runtime_error("FindFilesByMask(): glob() error");

	DIR* curDir = opendir(".");
	struct stat curEntryData;

	for (size_t i=0; i < globbuf.gl_pathc; ++i)
	{
		stat(globbuf.gl_pathv[i], &curEntryData);
		if (S_ISDIR(curEntryData.st_mode) ||
            S_ISREG(curEntryData.st_mode) ||
            S_ISLNK(curEntryData.st_mode))
			matchingPaths.push_back(globbuf.gl_pathv[i]);
	}
	closedir(curDir);

	globfree(&globbuf);

#endif
}
 std::string GetStem(const bfs::path& path) {
     #if defined(USE_BOOST_FILESYSTEM_V3)
         if (!HasExtension(path)) {
             // if no extension return empty string
             return "";
         }
         else {
             return path.stem().string();
         }
     #else
         if (!HasExtension(path)) {
             // if no extension, return empty string
             return "";
         }
         else {
             return path.stem();
         }
     #endif
 }
Exemple #22
0
RlSemaphore::RlSemaphore(const bfs::path& semname, int index)
{
    std::string filename = semname.native_file_string();
    key_t key = ftok(filename.c_str(), index);
    if (key == -1)
        throw SgException("Semaphore " + filename + " doesn't exist");
    m_id = semget(key, 1, 0644 | IPC_CREAT);
    if (semctl(m_id, 0, SETVAL, 1) == -1)
        throw SgException("Failed to initialise semaphore");
}
 std::string GetFilenameFromPath(const bfs::path& path) {
     #if defined(USE_BOOST_FILESYSTEM_V3)
         // boost version 1.46 and above uses
         // boost filesystem version 3 as the default
         // which has yet a different way of getting
         // a filename string
         return path.filename().string();
     #elif defined(USE_NON_DEPRECATED_BOOST_FILESYSTEM_V2)
         // the new way in boost filesystem version 2
         // to get a filename string
         //(this is for boost version 1.36 and above)
         return path.filename();
     #else
         // the old way in boost filesystem version 2
         // to get a filename string 
         //(this is for boost version 1.35 and below)
         return path.leaf();
     #endif
 }
Exemple #24
0
void WiiPlatform::ConvertSound(bfs::path filename, SoundResource *obj)
{
	std::ostringstream cmd;

	cmd << this->GetName() << PLATFORM_PATH_SEPARATOR_STR << "sox ";
	cmd << filename.string().c_str() << " -b 16 ";
	cmd << obj->GetInputPath().string().c_str();

	RUN_COMMAND(cmd);
}
Exemple #25
0
void World::loadFromFile(const bfs::path & path, const Vec2f & posModifier)
{
   Logger::get().debug("Загрузка объектов из файла %1%") % path.string();

   json::Parser jparser;
   jparser.readFile(path.string());
   const json::Object & jroot = jparser.getRoot();

   // Local rect
   Rectf aabb = Rectf::fromJson(jroot.get("aabb"));

   // Entities
   for(const json::Object & jentity : jroot.get("entities").getArray())
   {
      Entity * entity = Entity::fromJson(this, jentity);
      entity->getBody()->setPos(
               entity->getBody()->getPos() + Vec2f(-aabb.x + posModifier.x,
                                                   -aabb.y + posModifier.y));
   }
}
Exemple #26
0
/** 
 * @brief Checks if file exists in current directory
 * 
 * Function checks if specified file exists.
 * 
 * @param fileName File name to search for
 * 
 * @return Check status
 */
bool condor2nav::FileExists(const bfs::path &fileName) 
{
  bool activeSync = false;
  const auto str = fileName.string();
  if(str.size() > 2 && str[0] == '\\' && str[1] != '\\')
    activeSync = true;

  if(activeSync)
    return CActiveSync::Instance().FileExists(fileName);
  else
    return bfs::exists(fileName);
}
Exemple #27
0
void item_action(const bfs::path& ipath)
{
	/* use file_status instead of is_xxx */
	bfs::file_status sts=bfs::status(ipath);
	/* status_error, file_not_found, regular_file, directory_file,
	 * symlink_file, block_file, character_file, fifo_file, socket_file,
	 * type_unknown
	 */
	if (sts.type()==bfs::regular_file)
	{
		std::cout<<ipath.generic_string()<<"\t"<<bfs::file_size(ipath)<<std::endl;
	}
	else if (sts.type()==bfs::directory_file)
	{
		std::cout<<ipath.generic_string()<<std::endl;
	}
	else
	{
		std::cout<<ipath.generic_string()<<std::endl;
	}
}
void PointcloudPublisherNode::publish_pointcloud(const bfs::path &pointcloud_file_path)
{
    pcl::PCLPointCloud2::Ptr cloud(new pcl::PCLPointCloud2);

    if (pcl::io::loadPCDFile(pointcloud_file_path.string(), *cloud) == -1)
    {
        ROS_ERROR("Could not open %s", pointcloud_file_path.string().c_str());
        return;
    }

    double frames_per_second = 0.0;

    sensor_msgs::PointCloud2 ros_output_cloud;
    pcl_conversions::fromPCL(*cloud, ros_output_cloud);

    std::string frame_id;
    if (nh_.getParam("frame_id", frame_id))
    {
        ros_output_cloud.header.frame_id = frame_id;
    }

    if (!nh_.getParam("frames_per_second", frames_per_second))
    {
        ros_output_cloud.header.stamp = ros::Time::now();
        pointcloud_publisher_.publish(ros_output_cloud);
        ROS_INFO("Published pointcloud. Exiting");
        ros::shutdown();
        return;
    }

    ros::Rate loop_rate(frames_per_second);

    ROS_INFO("Going to publish pointcloud at %.2f fps", frames_per_second);
    while(ros::ok())
    {
        ros_output_cloud.header.stamp = ros::Time::now();
        pointcloud_publisher_.publish(ros_output_cloud);
        loop_rate.sleep();
    }
}
Exemple #29
0
void find(const bfs::path& cdb_path, const options& opt)
{
    config cfg = load_config(cdb_path / "config");

    const bfs::path cdb_root = cdb_path.parent_path();
    const bfs::path search_root = bfs::initial_path();

    std::size_t prefix_size = 0;
    std::string file_match;
    if(opt.m_options.count("-a") == 0 && search_root != cdb_root)
    {
        file_match = "^" + escape_regex(
            search_root.generic_string().substr(cdb_root.string().size() + 1) + "/") + ".*";
        prefix_size = search_root.string().size() - cdb_root.string().size();
    }

    file_lock lock(cdb_path / "lock");
    lock.lock_sharable();

    const char* find_regex_options =
        opt.m_options.count("-i") ? "i" : "";
    const char* file_regex_options =
        cfg.get_value("nocase-file-match") == "on" ? "i" : "";

    bool trim = cfg.get_value("find-trim-ws") == "on";
    unsigned thread_count = get_thread_count(cfg);
    unsigned buffer_count = get_buffer_count(thread_count);

    for(unsigned i = 0; i != opt.m_args.size(); ++i)
    {
        database_ptr db = open_database(cdb_path / "db");

        std::string pattern = opt.m_args[i];
        if(opt.m_options.count("-v"))
            pattern = escape_regex(pattern);

        mt_search mts(*db, trim, prefix_size, buffer_count);

        auto worker = [&]
        {
            mts.search_db(compile_regex(pattern, 0, find_regex_options),
                          compile_regex(file_match, 0, file_regex_options));
        };

        boost::thread_group workers;
        for(unsigned i = 0; i != thread_count-1; ++i)
            workers.create_thread(worker);

        worker();

        workers.join_all();
    }
}
Exemple #30
0
RlSharedMemory::RlSharedMemory(
    const bfs::path& sharename, int index, int bytes)
{
    std::string filename = sharename.native_file_string();
    key_t key = ftok(filename.c_str(), index);
    if (key == -1)
        throw SgException("Shared file " + filename + " doesn't exist");
    m_id = shmget(key, bytes, 0644 | IPC_CREAT);
    if (m_id == -1)
        Error("shmget");
    m_data = (char*) shmat(m_id, 0, 0);
    if (m_data == (char*) -1)
        Error("shmat");
}