コード例 #1
0
void test_dependent_init(T *p) {
  X0<int> i(p);
  (void)i;
}
コード例 #2
0
	void RetrieveFromRegistryCreoInstallLocations(
								const std::string &in_StartingKeyPath,
								const std::vector<std::string> &in_SupportedVersionPrefixes,
								const std::string			   &in_SupportedVersionString_ForErrorMsg,
								std::string &out_CreoParametricInstallPath,
								std::string &out_CreoParametricCommMsgExe ) throw (isis::application_exception)
	{
		std::string key_Creo_Parametric = in_StartingKeyPath;

		std::string errorMsg_1 =  "Creo Parametric is not installed.  Please install Creo " + in_SupportedVersionString_ForErrorMsg + ". Note - Higher versions are currently not supported.  ";
		std::string errorMsg_2 =  "Creo Parametric is not installed or the registry information for the install is incorrect or the format of the registry information has changed.  If not installed, please install Creo " + in_SupportedVersionString_ForErrorMsg + ". Note - Higher versions are currently not supported.  ";

		std::string key_Temp;
		//////////////////////////////////////////////////////////////////////
		// Retrieve Key to in_StartingKeyPath (e.g. HKEY_LOCAL_MACHINE\SOFTWARE\PTC\Creo Parametric)
		/////////////////////////////////////////////////////////////////////
		HKEY hKey;
		if ( RegOpenKeyExA(HKEY_LOCAL_MACHINE,
			 key_Creo_Parametric.c_str(),
			 0, KEY_READ|KEY_WOW64_64KEY, &hKey) != ERROR_SUCCESS)
		{
			std::string TempError =   errorMsg_1 +
				std::string("Could not find registry key HKEY_LOCAL_MACHINE\\") + key_Creo_Parametric; 
			throw isis::application_exception(TempError.c_str());
		}
		///////////////////////////////////////////////////////////////////
		// Get Subkeys of in_StartingKeyPath
		//////////////////////////////////////////////////////////////////
		std::vector<std::string> subKeys_vec;
		RetrieveRegistryListOfSubkeys( hKey, subKeys_vec );

		std::vector<std::string> versionNumber_vec;
		for ( std::vector<std::string>::const_iterator i(subKeys_vec.begin()); i != subKeys_vec.end(); ++i )
		{
			//std::cout << std::endl << *i;
			for ( std::vector<std::string>::const_iterator j(in_SupportedVersionPrefixes.begin()); j != in_SupportedVersionPrefixes.end(); ++ j )
			{
				if ( i->find(*j) != i->front())
				{
					versionNumber_vec.push_back(*i);
					break;
				} 
			}
		}

		if ( versionNumber_vec.size() == 0 )
		{
			std::string TempError =   errorMsg_2 + 
				std::string("Could not find registry keys subordinate to HKEY_LOCAL_MACHINE\\") + key_Creo_Parametric; 
			throw isis::application_exception(TempError.c_str());
		}

		// Sort the keys, so that the highest key (highest Creo Version) could be selected.
		std::sort( versionNumber_vec.begin(), versionNumber_vec.end() );

		key_Temp = key_Creo_Parametric + "\\" + versionNumber_vec[versionNumber_vec.size() - 1 ];

		//std::cout << std::endl << key_Temp;

		////////////////////////////////////////////////////////////////////////////////
		// Retrieve next Key (e.g.in_StartingKeyPath\1.0 )
		////////////////////////////////////////////////////////////////////////////////
		if ( RegOpenKeyExA(HKEY_LOCAL_MACHINE,
			 key_Temp.c_str(),
			 0, KEY_READ|KEY_WOW64_64KEY, &hKey) != ERROR_SUCCESS)
		{
			std::string TempError =   errorMsg_2 +
				std::string("Could not find key HKEY_LOCAL_MACHINE\\") + key_Temp; 
			throw isis::application_exception(TempError.c_str());
		}
		subKeys_vec.empty();

		/////////////////////////////////////////////////////////////////////////////////////////////
		// Get Subkeys of in_StartingKeyPath\1.0   could be 1.1, 2.0 ...
		/////////////////////////////////////////////////////////////////////////////////////////////
		subKeys_vec.clear();
		RetrieveRegistryListOfSubkeys( hKey, subKeys_vec );

		if ( subKeys_vec.size() == 0 )
		{
			std::string TempError =  errorMsg_2 + 
				std::string("Could not find registry keys subordinate to HKEY_LOCAL_MACHINE\\") + key_Temp; 
			throw isis::application_exception(TempError.c_str());
		}


		//for ( std::vector<std::string>::const_iterator i(subKeys_vec.begin()); i != subKeys_vec.end(); ++i )
		//{
		//	std::cout << std::endl << *i;
		//}

		// Sort the keys, so that the highest key (highest Creo Version) could be selected.
		std::sort( subKeys_vec.begin(), subKeys_vec.end() );

		key_Temp = key_Temp + "\\" + subKeys_vec[subKeys_vec.size() - 1 ];

		//std::cout << std::endl << key_Temp;

		////////////////////////////////////////////////////////////////////////////////
		// Retrieve next Key (e.g. in_StartingKeyPath\2.0\2011109 )
		////////////////////////////////////////////////////////////////////////////////
		if ( RegOpenKeyExA(HKEY_LOCAL_MACHINE,
			 key_Temp.c_str(),
			 0, KEY_READ|KEY_WOW64_64KEY, &hKey) != ERROR_SUCCESS)
		{
			std::string TempError =   errorMsg_2 +
				std::string("Could not find key HKEY_LOCAL_MACHINE\\") + key_Temp; 
			throw isis::application_exception(TempError.c_str());
		}


		////////////////////////////////
		// Get CommonFilesLocation
		////////////////////////////////
		std::string commonFilesLocation = RetrieveRegistryStringValue( hKey, "CommonFilesLocation" );

		if ( commonFilesLocation.size() == 0 )
		{
			std::string TempError =   errorMsg_2 + 
				std::string("Could not find registry value \"CommonFilesLocation\" subordinate to HKEY_LOCAL_MACHINE\\") + key_Temp; 
			throw isis::application_exception(TempError.c_str());
		}

		//std::cout << std::endl << "CommonFilesLocation: " <<  commonFilesLocation;

		////////////////////////////////
		// Get InstallDir
		////////////////////////////////
		std::string installDir = RetrieveRegistryStringValue( hKey, "InstallDir" );

		if ( commonFilesLocation.size() == 0 )
		{
			std::string TempError =   errorMsg_2 +
				std::string("Could not find registry value \"InstallDir\" subordinate to HKEY_LOCAL_MACHINE\\") + key_Temp; 
			throw isis::application_exception(TempError.c_str());
		}

		//std::cout << std::endl << "InstallDir: " <<  installDir;
		
		DWORD bufferSize = static_cast<DWORD>(installDir.size() * 2);  // the shortname should be less, allocated double the space as a safety measure
		char *installPath_ShortName = new char[bufferSize ];  
		GetShortPathNameA(  installDir.c_str(), installPath_ShortName, bufferSize );						
		out_CreoParametricInstallPath =  installPath_ShortName + std::string("\\");
		delete installPath_ShortName;

		out_CreoParametricCommMsgExe =  commonFilesLocation + "\\x86e_win64\\obj\\pro_comm_msg";
	
		//std::cout << std::endl << "out_CreoParametricInstallPath: " <<  out_CreoParametricInstallPath;
		//std::cout << std::endl << "out_CreoParametricCommMsgExe: " <<  out_CreoParametricCommMsgExe;
	}
コード例 #3
0
int main(int argc, char *argv[])
{
  std::string app_name(argv[0]);
  unsigned short port_number(via::comms::tcp_adaptor::DEFAULT_HTTP_PORT);

  // Get a port number from the user (the default is 80)
  if (argc > 2)
  {
    std::cerr << "Usage: " << app_name << " [port number]\n"
              << "E.g. "   << app_name << " " << port_number
              << std::endl;
    return 1;
  }
  else if (argc == 2)
  {
    std::string port(argv[1]);
    port_number = atoi(port.c_str());
  }

  std::cout << app_name << ": " << port_number << std::endl;

  try
  {
    // create an io_service for the server
    boost::asio::io_service io_service;

    // create an http_server and connect the request handler
    http_server_type http_server(io_service);
    http_server.request_received_event(request_handler);

    // connect the handler callback functions
    http_server.chunk_received_event(chunk_handler);
    http_server.request_expect_continue_event(expect_continue_handler);
    http_server.invalid_request_event(invalid_request_handler);
    http_server.socket_connected_event(connected_handler);
    http_server.socket_disconnected_event(disconnected_handler);
    http_server.message_sent_event(message_sent_handler);

    // start accepting http connections on the given port
    boost::system::error_code error(http_server.accept_connections(port_number));
    if (error)
    {
      std::cerr << "Error: "  << error.message() << std::endl;
      return 1;
    }

    // The signal set is used to register for termination notifications
    boost::asio::signal_set signals_(io_service);
    signals_.add(SIGINT);
    signals_.add(SIGTERM);
#if defined(SIGQUIT)
    signals_.add(SIGQUIT);
#endif // #if defined(SIGQUIT)

    // register the handle_stop callback
    signals_.async_wait([&http_server]
      (boost::system::error_code const& error, int signal_number)
    { handle_stop(error, signal_number, http_server); });

    // Determine the number of concurrent threads supported
    size_t no_of_threads(std::thread::hardware_concurrency());
    std::cout << "No of threads: " << no_of_threads << std::endl;

    if (no_of_threads > 0)
    {
      // Create a thread pool for the threads and run the asio io_service
      // in each of the threads.
      std::vector<std::shared_ptr<std::thread> > threads;
      for (std::size_t i = 0; i < no_of_threads; ++i)
      {
        std::shared_ptr<std::thread> thread(std::make_shared<std::thread>
                             ([&io_service](){ io_service.run(); }));
        threads.push_back(thread);
      }

      // Wait for all threads in the pool to exit.
      for (std::size_t i(0); i < threads.size(); ++i)
        threads[i]->join();
    }
    else
      io_service.run();

    std::cout << "io_service.run, all work has finished" << std::endl;
  }
  catch (std::exception& e)
  {
    std::cerr << "Exception:"  << e.what() << std::endl;
  }

  return 0;
}
コード例 #4
0
ファイル: indexkey.cpp プロジェクト: LsRbls/mongo
    void IndexSpec::_getKeys( vector<const char*> fieldNames , vector<BSONElement> fixed , const BSONObj &obj, BSONObjSetDefaultOrder &keys ) const {
        BSONElement arrElt;
        unsigned arrIdx = ~0;
        int numNotFound = 0;

        for( unsigned i = 0; i < fieldNames.size(); ++i ) {
            if ( *fieldNames[ i ] == '\0' )
                continue;

            BSONElement e = obj.getFieldDottedOrArray( fieldNames[ i ] );

            if ( e.eoo() ) {
                e = _nullElt; // no matching field
                numNotFound++;
            }

            if ( e.type() != Array )
                fieldNames[ i ] = ""; // no matching field or non-array match

            if ( *fieldNames[ i ] == '\0' )
                fixed[ i ] = e; // no need for further object expansion (though array expansion still possible)

            if ( e.type() == Array && arrElt.eoo() ) { // we only expand arrays on a single path -- track the path here
                arrIdx = i;
                arrElt = e;
            }

            // enforce single array path here
            if ( e.type() == Array && e.rawdata() != arrElt.rawdata() ) {
                stringstream ss;
                ss << "cannot index parallel arrays [" << e.fieldName() << "] [" << arrElt.fieldName() << "]";
                uasserted( 10088 ,  ss.str() );
            }
        }

        bool allFound = true; // have we found elements for all field names in the key spec?
        for( vector<const char*>::const_iterator i = fieldNames.begin(); i != fieldNames.end(); ++i ) {
            if ( **i != '\0' ) {
                allFound = false;
                break;
            }
        }

        if ( _sparse && numNotFound == _nFields ) {
            // we didn't find any fields
            // so we're not going to index this document
            return;
        }

        bool insertArrayNull = false;

        if ( allFound ) {
            if ( arrElt.eoo() ) {
                // no terminal array element to expand
                BSONObjBuilder b(_sizeTracker);
                for( vector< BSONElement >::iterator i = fixed.begin(); i != fixed.end(); ++i )
                    b.appendAs( *i, "" );
                keys.insert( b.obj() );
            }
            else {
                // terminal array element to expand, so generate all keys
                BSONObjIterator i( arrElt.embeddedObject() );
                if ( i.more() ) {
                    while( i.more() ) {
                        BSONObjBuilder b(_sizeTracker);
                        for( unsigned j = 0; j < fixed.size(); ++j ) {
                            if ( j == arrIdx )
                                b.appendAs( i.next(), "" );
                            else
                                b.appendAs( fixed[ j ], "" );
                        }
                        keys.insert( b.obj() );
                    }
                }
                else if ( fixed.size() > 1 ) {
                    insertArrayNull = true;
                }
            }
        }
        else {
            // nonterminal array element to expand, so recurse
            assert( !arrElt.eoo() );
            BSONObjIterator i( arrElt.embeddedObject() );
            if ( i.more() ) {
                while( i.more() ) {
                    BSONElement e = i.next();
                    if ( e.type() == Object ) {
                        _getKeys( fieldNames, fixed, e.embeddedObject(), keys );
                    }
                }
            }
            else {
                insertArrayNull = true;
            }
        }

        if ( insertArrayNull ) {
            // x : [] - need to insert undefined
            BSONObjBuilder b(_sizeTracker);
            for( unsigned j = 0; j < fixed.size(); ++j ) {
                if ( j == arrIdx ) {
                    b.appendUndefined( "" );
                }
                else {
                    BSONElement e = fixed[j];
                    if ( e.eoo() )
                        b.appendNull( "" );
                    else
                        b.appendAs( e , "" );
                }
            }
            keys.insert( b.obj() );
        }
    }
コード例 #5
0
void graph::make_adjs_av( ver * plus )
{
    plus->availabe = true;
    for( size_t i(0); i < plus->adjs.size(); i++)
        plus->adjs[i].toself->availabe = true;
}
コード例 #6
0
int main(int argc, char **argv)
{
    // OSG init
    osgInit(argc,argv);

    // Set up Window
    TutorialWindow = createNativeWindow();
    TutorialWindow->initWindow();

    TutorialWindow->setDisplayCallback(display);
    TutorialWindow->setReshapeCallback(reshape);

    TutorialKeyListener TheKeyListener;
    TutorialWindow->addKeyListener(&TheKeyListener);
    TutorialMouseListener TheTutorialMouseListener;
    TutorialMouseMotionListener TheTutorialMouseMotionListener;
    TutorialWindow->addMouseListener(&TheTutorialMouseListener);
    TutorialWindow->addMouseMotionListener(&TheTutorialMouseMotionListener);

    // Create the SimpleSceneManager helper
    mgr = new SimpleSceneManager;

    // Tell the Manager what to manage
    mgr->setWindow(TutorialWindow);

    //Particle System Material
    PointChunkRefPtr PSPointChunk = PointChunk::create();
    PSPointChunk->setSize(5.0f);
    PSPointChunk->setSmooth(true);
    BlendChunkRefPtr PSBlendChunk = BlendChunk::create();
    PSBlendChunk->setSrcFactor(GL_SRC_ALPHA);
    PSBlendChunk->setDestFactor(GL_ONE_MINUS_SRC_ALPHA);

    MaterialChunkRefPtr PSMaterialChunkChunk = MaterialChunk::create();
    PSMaterialChunkChunk->setAmbient(Color4f(0.3f,0.3f,0.3f,1.0f));
    PSMaterialChunkChunk->setDiffuse(Color4f(0.7f,0.7f,0.7f,1.0f));
    PSMaterialChunkChunk->setSpecular(Color4f(0.9f,0.9f,0.9f,1.0f));
    PSMaterialChunkChunk->setColorMaterial(GL_AMBIENT_AND_DIFFUSE);

    ChunkMaterialRefPtr PSMaterial = ChunkMaterial::create();
    PSMaterial->addChunk(PSPointChunk);
    PSMaterial->addChunk(PSMaterialChunkChunk);
    PSMaterial->addChunk(PSBlendChunk);

    Distribution3DRefPtr PositionDistribution = createPositionDistribution();

    Pnt3f PositionReturnValue;

    //Particle System
    ParticleSystemRefPtr ExampleParticleSystem = OSG::ParticleSystem::create();
    for(UInt32 i(0) ; i<500 ; ++i)//controls how many particles are created
    {
        if(PositionDistribution != NULL)
        {
            PositionReturnValue = Pnt3f(PositionDistribution->generate());
        }

        ExampleParticleSystem->addParticle(
                                           PositionReturnValue,
                                           Vec3f(0.0f,0.0f,1.0f),
                                           Color4f(1.0,0.0,0.0,1.0), 
                                           Vec3f(1.0,1.0,1.0), 
                                           -1, 
                                           Vec3f(0.0f,0.0f,0.0f), //Velocity
                                           Vec3f(0.0f,0.0f,0.0f)	//acceleration
                                          );
    }
    ExampleParticleSystem->attachUpdateListener(TutorialWindow);

    //Particle System Drawer
    PointParticleSystemDrawerRefPtr ExampleParticleSystemDrawer = OSG::PointParticleSystemDrawer::create();



    //Particle System Node
    ParticleSystemCoreRefPtr ParticleNodeCore = OSG::ParticleSystemCore::create();
    ParticleNodeCore->setSystem(ExampleParticleSystem);
    ParticleNodeCore->setDrawer(ExampleParticleSystemDrawer);
    ParticleNodeCore->setMaterial(PSMaterial);

    NodeRefPtr ParticleNode = OSG::Node::create();
    ParticleNode->setCore(ParticleNodeCore);


    // Make Main Scene Node and add the Torus
    NodeRefPtr scene = OSG::Node::create();
    scene->setCore(OSG::Group::create());
    scene->addChild(ParticleNode);

    mgr->setRoot(scene);

    // Show the whole Scene
    mgr->showAll();

    //Create an DistanceKill
    DistanceKillParticleAffectorRefPtr ExampleDistanceKillParticleAffector = OSG::DistanceKillParticleAffector::create();
    ExampleDistanceKillParticleAffector->setKillDistance(1000.0f);
    ExampleDistanceKillParticleAffector->setParticleSystemNode(ParticleNode);
    ExampleDistanceKillParticleAffector->setDistanceFromSource(DistanceKillParticleAffector::DISTANCE_FROM_CAMERA);
    ExampleDistanceKillParticleAffector->setDistanceFromCamera(mgr->getCamera());

    ExampleParticleSystem->pushToAffectors(ExampleDistanceKillParticleAffector);

    //Open Window
    Vec2f WinSize(TutorialWindow->getDesktopSize() * 0.85f);
    Pnt2f WinPos((TutorialWindow->getDesktopSize() - WinSize) *0.5);
    TutorialWindow->openWindow(WinPos,
                               WinSize,
                               "09DistanceKillParticleAffector");

    //Enter main Loop
    TutorialWindow->mainLoop();

    osgExit();

    return 0;
}
コード例 #7
0
        void commit( set<DiskLoc>* dupsToDrop,
                     CurOp* op,
                     bool mayInterrupt ) {

            Timer timer;

            IndexCatalogEntry* entry = _real->_btreeState;

            bool dupsAllowed = !entry->descriptor()->unique() ||
                ignoreUniqueIndex(entry->descriptor());
            bool dropDups = entry->descriptor()->dropDups() || inDBRepair;

            BtreeBuilder<V> btBuilder(dupsAllowed, entry);

            BSONObj keyLast;
            scoped_ptr<BSONObjExternalSorter::Iterator> i( _phase1.sorter->iterator() );

            // verifies that pm and op refer to the same ProgressMeter
            ProgressMeter& pm = op->setMessage("Index Bulk Build: (2/3) btree bottom up",
                                               "Index: (2/3) BTree Bottom Up Progress",
                                               _phase1.nkeys,
                                               10);

            while( i->more() ) {
                RARELY killCurrentOp.checkForInterrupt( !mayInterrupt );
                ExternalSortDatum d = i->next();

                try {
                    if ( !dupsAllowed && dropDups ) {
                        LastError::Disabled led( lastError.get() );
                        btBuilder.addKey(d.first, d.second);
                    }
                    else {
                        btBuilder.addKey(d.first, d.second);
                    }
                }
                catch( AssertionException& e ) {
                    if ( dupsAllowed ) {
                        // unknown exception??
                        throw;
                    }

                    if( e.interrupted() ) {
                        killCurrentOp.checkForInterrupt();
                    }

                    if ( ! dropDups )
                        throw;

                    /* we could queue these on disk, but normally there are very few dups,
                     * so instead we keep in ram and have a limit.
                    */
                    if ( dupsToDrop ) {
                        dupsToDrop->insert(d.second);
                        uassert( 10092,
                                 "too may dups on index build with dropDups=true",
                                 dupsToDrop->size() < 1000000 );
                    }
                }
                pm.hit();
            }
            pm.finished();
            op->setMessage("Index Bulk Build: (3/3) btree-middle",
                           "Index: (3/3) BTree Middle Progress");
            LOG(timer.seconds() > 10 ? 0 : 1 ) << "\t done building bottom layer, going to commit";
            btBuilder.commit( mayInterrupt );
            if ( btBuilder.getn() != _phase1.nkeys && ! dropDups ) {
                warning() << "not all entries were added to the index, probably some "
                          << "keys were too large" << endl;
            }
        }
コード例 #8
0
ファイル: tool.cpp プロジェクト: kapouer/mongo-debian
    long long BSONTool::processFile( const path& root ){
        string fileString = root.string();
        
        long long fileLength = file_size( root );

        if ( fileLength == 0 ) {
            out() << "file " << fileString << " empty, skipping" << endl;
            return 0;
        }


        FILE* file = fopen( fileString.c_str() , "rb" );
        if ( ! file ){
            log() << "error opening file: " << fileString << endl;
            return 0;
        }

#if !defined(__sunos__) && defined(POSIX_FADV_SEQUENTIAL)
        posix_fadvise(fileno(file), 0, fileLength, POSIX_FADV_SEQUENTIAL);
#endif

        log(1) << "\t file size: " << fileLength << endl;

        long long read = 0;
        long long num = 0;
        long long processed = 0;

        const int BUF_SIZE = 1024 * 1024 * 5;
        boost::scoped_array<char> buf_holder(new char[BUF_SIZE]);
        char * buf = buf_holder.get();

        ProgressMeter m( fileLength );

        while ( read < fileLength ) {
            int readlen = fread(buf, 4, 1, file);
            int size = ((int*)buf)[0];
            if ( size >= BUF_SIZE ){
                cerr << "got an object of size: " << size << "  terminating..." << endl;
            }
            uassert( 10264 ,  "invalid object size" , size < BUF_SIZE );

            readlen = fread(buf+4, size-4, 1, file);

            BSONObj o( buf );
            if ( _objcheck && ! o.valid() ){
                cerr << "INVALID OBJECT - going try and pring out " << endl;
                cerr << "size: " << size << endl;
                BSONObjIterator i(o);
                while ( i.more() ){
                    BSONElement e = i.next();
                    try {
                        e.validate();
                    }
                    catch ( ... ){
                        cerr << "\t\t NEXT ONE IS INVALID" << endl;
                    }
                    cerr << "\t name : " << e.fieldName() << " " << e.type() << endl;
                    cerr << "\t " << e << endl;
                }
            }
            
            if ( _matcher.get() == 0 || _matcher->matches( o ) ){
                gotObject( o );
                processed++;
            }

            read += o.objsize();
            num++;

            m.hit( o.objsize() );
        }

        uassert( 10265 ,  "counts don't match" , m.done() == fileLength );
        out() << "\t "  << m.hits() << " objects found" << endl;
        if ( _matcher.get() )
            out() << "\t "  << processed << " objects processed" << endl;
        return processed;
    }
コード例 #9
0
ファイル: FullID.cpp プロジェクト: ecell/ecell3
SystemPath SystemPath::toRelative( SystemPath const& aBaseSystemPath ) const
{
    // 1. "" (empty) means Model itself, which is invalid for this method.
    // 2. Not absolute is invalid (not absolute implies not empty).
    if( ! isAbsolute() || isModel() )
    {
        return *this;
    }

    if( ! aBaseSystemPath.isAbsolute() || aBaseSystemPath.isModel() )
    {
        THROW_EXCEPTION( BadSystemPath, 
                         "[" + aBaseSystemPath.asString() +
                         "] is not an absolute SystemPath" );
    }

    SystemPath aThisPathCopy;
    SystemPath const* thisPath;

    if ( !isCanonicalized() )
    {
        aThisPathCopy = *this;
        aThisPathCopy.canonicalize();
        thisPath = &aThisPathCopy;
    }
    else
    {
        thisPath = this;
    }

    SystemPath aBaseSystemPathCopy;
    SystemPath const* aCanonicalizedBaseSystemPath;
    if ( !aBaseSystemPath.isCanonicalized() )
    {
        aCanonicalizedBaseSystemPath = &aBaseSystemPath;
    }
    else
    {
        aBaseSystemPathCopy = aBaseSystemPath;
        aBaseSystemPathCopy.canonicalize();
        aCanonicalizedBaseSystemPath = &aBaseSystemPathCopy;
    }

    SystemPath aRetval;
    StringVector::const_iterator j( thisPath->theComponents.begin() ),
                               je( thisPath->theComponents.end() );
    StringVector::const_iterator
        i( aCanonicalizedBaseSystemPath->theComponents.begin() ),
        ie( aCanonicalizedBaseSystemPath->theComponents.end() );

    while ( i != ie && j != je )
    {
        String const& aComp( *i );
        if ( aComp != *j )
        {
            break;
        }
        ++i, ++j;
    }
    if ( i != ie )
    {
        while ( i != ie )
        {
            aRetval.theComponents.push_back( ".." );
            ++i;
        }
    }
    std::copy( j, je, std::back_inserter( aRetval.theComponents ) );

    if ( aRetval.theComponents.empty() )
    {
        aRetval.theComponents.push_back( "." );
    }

    return aRetval; 
}
コード例 #10
0
ファイル: worker.cpp プロジェクト: Matoking/Filetug
/*
 *  Paste files to destination
 */
void Worker::pasteFiles(bool cut)
{
    buildFileList();

    QList<QString> directoryList;

    QDir sourceDir(m_clipboardDir);

    QTime startTime = QTime::currentTime();

    emit progressTextChanged(QString("Copying files..."));

    // Create a list of directories to be created
    for (int i=0; i < m_directoryList.count(); i++)
    {
        QString sourcePath = m_directoryList.at(i);
        QString newDirPath = QString("%1/%2").arg(m_destination, sourceDir.relativeFilePath(sourcePath));

        qDebug() << sourcePath.toLatin1() << " > " << newDirPath.toLatin1();

        directoryList.append(newDirPath);
    }

    emit progressTextChanged("Creating directories...");

    qDebug() << "FILES";

    // Create a list of files to be copied
    for (int i=0; i < m_fileList.count(); i++)
    {
        QString sourcePath = m_fileList.at(i);
        QString newFilePath = QString("%1/%2").arg(m_destination, sourceDir.relativeFilePath(sourcePath));

        qDebug() << sourcePath.toLatin1() << " > " << newFilePath.toLatin1();

        m_fileMap.insert(sourcePath, newFilePath);
    }

    // First, create the directories
    for (int i = 0; i < directoryList.count(); i++)
    {
        QString newDir = directoryList.at(i);

        QDir dir(newDir);

        // If the directory already exists, skip it
        if (dir.exists())
            continue;

        bool success = dir.mkdir(newDir);

        if (!success)
            directoryErrorMap.insert(newDir, DirCreateError);
    }

    // If any of the directories couldn't be created, abort the process
    if (directoryErrorMap.count() > 0)
    {
        emit progressTextChanged("Directories couldn't be created.");
        emit fileOperationFinished();

        // Abort the process
        quit();
    }

    // Now, copy the files
    int fileCount = 0;
    QMapIterator<QString, QString> i(m_fileMap);
    while (i.hasNext())
    {
        i.next();
        fileCount++;
        QString sourceFilePath = i.key();
        QString newFilePath = i.value();

        QFile sourceFile(sourceFilePath);

        // Report the progress, but only every 50 milliseconds to prevent the UI thread
        // from being flooded with signals
        if (QTime::currentTime().msecsTo(startTime) <= -50)
        {
            startTime = QTime::currentTime();

            emit progressTextChanged(QString("Copying files (%1 of %2)...").arg(QString("%1").arg(fileCount),
                                                                                 QString("%1").arg(m_fileMap.count())));
            emit currentEntryChanged(sourceFile.fileName());

            double progress = (double)(fileCount) / (double)m_fileMap.count();
            emit progressValueChanged(progress);
        }

        // Copy the file
        bool success = sourceFile.copy(sourceFilePath, newFilePath);

        if (!success)
            fileErrorMap.insert(newFilePath, sourceFile.error());
    }

    // If we don't have to cut files we are done
    if (!cut)
    {
        if (fileErrorMap.count() == 0 && directoryErrorMap.count() == 0)
            emit progressTextChanged("All files were copied successfully.");
        else
            emit progressTextChanged("All files couldn't be copied successfully.");

        emit fileOperationFinished();

        // Done, time to self-destruct
        quit();
    }
    else
    {
        fileCount = 0;

        if (fileErrorMap.count() == 0 && directoryErrorMap.count() == 0)
        {
            // We copied all files successfully, so delete the old ones now
            i.toFront();
            while (i.hasNext())
            {
                i.next();
                fileCount++;
                QString sourceFilePath = i.key();

                QFile sourceFile(sourceFilePath);

                // Report the progress, but only every 50 milliseconds to prevent the UI thread
                // from being flooded with signals
                if (QTime::currentTime().msecsTo(startTime) <= -50)
                {
                    startTime = QTime::currentTime();

                    emit progressTextChanged(QString("Deleting old files (%1 of %2)...").arg(QString("%1").arg(fileCount),
                                                                                         QString("%1").arg(m_fileMap.count())));
                    emit currentEntryChanged(sourceFile.fileName());

                    double progress = (double)(fileCount) / (double)m_fileMap.count();
                    emit progressValueChanged(progress);
                }

                // Delete the file
                bool success = sourceFile.remove();

                if (!success)
                    fileErrorMap.insert(sourceFilePath, sourceFile.error());
            }

            emit progressTextChanged(QString("Deleting old directories..."));
            emit progressValueChanged(-1);

            // Then delete the directories
            for (int i=m_directoryList.count()-1; i >= 0; i--)
            {
                QString sourcePath = m_directoryList.at(i);

                QDir dir(sourcePath);

                // If it doesn't exist, it was most likely removed earlier
                if (!dir.exists())
                    continue;

                bool success = dir.rmdir(sourcePath);

                if (!success)
                    directoryErrorMap.insert(sourcePath, DirDeleteError);
            }

            // Check if files were copied and deleted successfully
            if (fileErrorMap.count() == 0 && directoryErrorMap.count() == 0)
                emit progressTextChanged("All of the files were cut and pasted successfully.");
            else
                emit progressTextChanged("All of the files couldn't be cut and pasted successfully.");

            emit fileOperationFinished();

            // Done, time to self-destruct
            quit();
        }
        else
        {
            // All files couldn't be copied, so delete the new copied files to revert the process
            i.toFront();
            while (i.hasNext())
            {
                i.next();
                fileCount++;
                QString newFilePath = i.value();

                QFile newFile(newFilePath);

                // Report the progress, but only every 50 milliseconds to prevent the UI thread
                // from being flooded with signals
                if (QTime::currentTime().msecsTo(startTime) <= -50)
                {
                    startTime = QTime::currentTime();

                    emit progressTextChanged(QString("Failed to copy all files, deleting copied files (%1 of %2)...").arg(QString("%1").arg(fileCount),
                                                                                         QString("%1").arg(m_fileMap.count())));
                    emit currentEntryChanged(newFile.fileName());

                    double progress = (double)(fileCount) / (double)m_fileMap.count();
                    emit progressValueChanged(progress);
                }

                // Delete the file
                newFile.remove();
            }

            emit progressTextChanged(QString("Failed to copy all files, deleting created directories..."));
            emit progressValueChanged(-1);

            // Delete the directories
            for (int i=directoryList.count()-1; i >= 0; i--)
            {
                QString newDir = directoryList.at(i);

                QDir dir(newDir);

                // If the directory already exists, skip it
                if (dir.exists())
                    continue;

                bool success = dir.rmdir(newDir);

                if (!success)
                    directoryErrorMap.insert(newDir, DirDeleteError);
            }

            emit progressTextChanged("All files couldn't be copied successfully.");

            emit fileOperationFinished();
        }
    }
}
コード例 #11
0
void ctkServiceRegistration::unregister()
{
  Q_D(ctkServiceRegistration);
  if (!d) throw std::logic_error("ctkServiceRegistration object invalid");

  if (d->unregistering) return; // Silently ignore redundant unregistration.
  {
    QMutexLocker lock(&d->eventLock);
    if (d->unregistering) return;
    d->unregistering = true;

    if (d->available)
    {
      if (d->plugin)
      {
        d->plugin->fwCtx->services->removeServiceRegistration(*this);
      }
    }
    else
    {
      throw std::logic_error("Service is unregistered");
    }
  }

  if (d->plugin)
  {
     d->plugin->fwCtx->listeners.serviceChanged(
         d->plugin->fwCtx->listeners.getMatchingServiceSlots(d->reference),
         ctkServiceEvent(ctkServiceEvent::UNREGISTERING, d->reference));
  }

  {
    QMutexLocker lock(&d->eventLock);
    {
      QMutexLocker lock2(&d->propsLock);
      d->available = false;
      if (d->plugin)
      {
        for (QHashIterator<QSharedPointer<ctkPlugin>, QObject*> i(d->serviceInstances); i.hasNext();)
        {
          QObject* obj = i.next().value();
          try
          {
            // NYI, don't call inside lock
            qobject_cast<ctkServiceFactory*>(d->service)->ungetService(i.key(),
                                                                       *this,
                                                                       obj);
          }
          catch (const std::exception& ue)
          {
            ctkPluginFrameworkEvent pfwEvent(ctkPluginFrameworkEvent::ERROR, d->plugin->q_func().data(), ue);
            d->plugin->fwCtx->listeners
                .emitFrameworkEvent(pfwEvent);
          }
        }
      }
      d->plugin = 0;
      d->dependents.clear();
      d->service = 0;
      d->serviceInstances.clear();;
      d->unregistering = false;
    }
  }
}
コード例 #12
0
ファイル: saex.cpp プロジェクト: Bathla/SMS_Encryptor
void CSAEXAppUi::CreateNewSMSMessageL()
    {
    
   	TMsvSelectionOrdering order( KMsvNoGrouping, EMsvSortByDate, ETrue );
    CMsvEntry* folderEntry = CMsvEntry::NewL( *iSession,KMsvDraftEntryId, order );
    CleanupStack::PushL( folderEntry );    
    CMsvEntrySelection* folderSelection = folderEntry->ChildrenWithTypeL(
        KUidMsvMessageEntry );
    CleanupStack::PushL( folderSelection );

	const TInt count( folderSelection->Count() );
	 for ( TInt i( 0 ); i < count; i++ )
	 {
		CMsvEntry *msgEntry; 		
       TMsvId msgEntryId = ( *folderSelection )[ i ];	  
		msgEntry=iSession->GetEntryL( msgEntryId);
		CleanupStack::PushL(msgEntry);

		if( msgEntry!= KErrNone )
		{

				if(true)//msgEntry->Entry().iType)//KUidMsvMessageEntry)
				{				
					CParaFormatLayer* paraLayer = CParaFormatLayer::NewL();
					CleanupStack::PushL(paraLayer); 
					CCharFormatLayer* charLayer = CCharFormatLayer::NewL(); 
					CleanupStack::PushL(charLayer); 
					CRichText* cipherBody = CRichText::NewL(paraLayer, charLayer); 
					CRichText * plainBody=CRichText::NewL(paraLayer, charLayer); 

					CleanupStack::PushL(cipherBody); 
					CleanupStack::PushL(plainBody); 

					CMsvStore* store= msgEntry->ReadStoreL();
					CleanupStack::PushL(store);

					store->RestoreBodyTextL(*cipherBody);

					CSendAs* iSendAs=NULL;   
					iSendAs = CSendAs::NewL(*this);				

					if(iSendAs)
						{
								CleanupStack::PushL(iSendAs);        
								iSendAs->SetMtmL(KUidMsgTypeSMS);        

								if(iSendAs->AvailableServices().Count()<1)
									{
										CEikonEnv::Static()->InfoMsg(_L("No SMS services available."));
										User::Leave(KErrNotFound);
									}
        
								iSendAs->SetService(0); 
        
								User::LeaveIfError(iSendAs->QueryMessageCapability(KUidMtmQueryCanSendMsg, EFalse));
								User::LeaveIfError(iSendAs->QueryMessageCapability(KUidMtmQueryMaxBodySize, ETrue));

        
								iSendAs->CreateMessageL();

								iSendAs->AddRecipientL( iRecipient->Des() );
								//iSendAs->SetSubjectL( KIGainTag ); 
								
								decryptBody(cipherBody,plainBody);								
								iSendAs->SetBodyL(*plainBody);									
								

								User::LeaveIfError(iSendAs->ValidateMessage());
								iSendAs->SaveMessageL(ETrue); // message is saved into Outbox(drafts)

								CleanupStack::PopAndDestroy(1,iSendAs);//plainBody and iSendAs

								
						}		

							CleanupStack::PopAndDestroy(5, paraLayer);	

					}
					else
					{
								CEikonEnv::Static()->AlertWin(_L("No SMS found."));
								User::Leave(KErrNotFound);
					
					}
						CleanupStack::PopAndDestroy(1, msgEntry);	
		}


	 }	 
	 	CleanupStack::PopAndDestroy( 2 ); 	

    }
コード例 #13
0
ファイル: Marking.cpp プロジェクト: marshall/mozilla-central
void
PushArenaTyped(GCMarker *gcmarker, ArenaHeader *aheader)
{
    for (CellIterUnderGC i(aheader); !i.done(); i.next())
        PushMarkStack(gcmarker, i.get<T>());
}
コード例 #14
0
void CMTPSetObjectPropList::RunL()
    {    
    if (iStatus == KErrNone) // send request to the next dp
        {
        if (!iDpListCreated)
            {    
            // Data provider list under construction.
            iResponseCode = EMTPRespCodeOK;
            const TUint KElementCount(iObjectPropList->NumberOfElements());
            const TUint KRunLength(32);
		
            for (TUint i(0); ((i < KRunLength) && (iPropertyIdx < KElementCount) && (iResponseCode == EMTPRespCodeOK)); ++i)
                {
				iPropertyIdx++;
				CMTPTypeObjectPropListElement& element=iObjectPropList->GetNextElementL();			
                const TUint32 KHandle(element.Uint32L(CMTPTypeObjectPropListElement::EObjectHandle));
                const TUint16 KPropCode(element.Uint16L(CMTPTypeObjectPropListElement::EPropertyCode));
                CMTPParserRouter::TRoutingParameters params(*iRequest, iConnection);
                params.SetParam(CMTPParserRouter::TRoutingParameters::EParamObjectHandle, KHandle);
                params.SetParam(CMTPParserRouter::TRoutingParameters::EParamObjectPropCode, KPropCode);
                                
                CMTPObjectMetaData* meta(CMTPObjectMetaData::NewLC());
                if (!iSingletons.ObjectMgr().ObjectL(KHandle, *meta))
                    {
                    // Invalid object handle.
                    iResponseCode = EMTPRespCodeInvalidObjectHandle;
                    }
                else if(!iSingletons.StorageMgr().IsReadWriteStorage(meta->Uint(CMTPObjectMetaData::EStorageId)))
                	{
					iResponseCode = EMTPRespCodeAccessDenied;
                	}
                else
                    {
                    RArray<TUint> targets;
                    CleanupClosePushL(targets);
                    iSingletons.Router().RouteOperationRequestL(params, targets);
                    __ASSERT_DEBUG((targets.Count() <= 1), User::Invariant());
                    if (targets.Count() == 1)
                        {
                        iDpList.InsertInOrder(targets[0]);
                        }
                    else
                        {
                        // Unsupported object propertycode.
                        iResponseCode = EMTPRespCodeObjectPropNotSupported;
                        }
                    CleanupStack::PopAndDestroy(&targets);
                    }
                CleanupStack::PopAndDestroy(meta);
                
                if (iResponseCode != EMTPRespCodeOK)
                    {
                    // If an error occurs at this point then no properties have been updated.
                    iPropertyIdx = 0;
                    iDpList.Reset();
                    }
                }	                
            if ((iPropertyIdx < KElementCount) && (iResponseCode == EMTPRespCodeOK))
                {
                Reschedule(KErrNone);
                }
            else
                {
                iDpListCreated = ETrue;
                }
            }
            
        if (iDpListCreated)
            {
            if (iDpIdx < iDpList.Count())
                {
                iSingletons.DpController().DataProviderL(iDpList[iDpIdx]).ExecuteProxyRequestL(Request(), Connection(), *this);
                }
            else
                {
                SendResponseL(iResponseCode, 1, &iPropertyIdx);                
                }
            }
        }
    else
        {
        if (!iDpListCreated)
            {
            /* 
            If an error occurs prior to starting the proxy transaction cycles 
            then no properties have been updated.
            */
            iPropertyIdx = 0;
            }
            
        if (iResponseCode == EMTPRespCodeOK)
            {
            iResponseCode = EMTPRespCodeGeneralError;
            }
        SendResponseL(iResponseCode, 1, &iPropertyIdx);
        }    
    }