ZCE_SQLite_STMTHdl::~ZCE_SQLite_STMTHdl()
{
    finalize();
}
Example #2
0
void SyncEngine::slotDiscoveryJobFinished(int discoveryResult)
{
    // To clean the progress info
    emit folderDiscovered(false, QString());

    if (discoveryResult < 0 ) {
        handleSyncError(_csync_ctx, "csync_update");
        return;
    }
    qDebug() << "<<#### Discovery end #################################################### " << _stopWatch.addLapTime(QLatin1String("Discovery Finished"));

    // Sanity check
    if (!_journal->isConnected()) {
        qDebug() << "Bailing out, DB failure";
        emit csyncError(tr("Cannot open the sync journal"));
        finalize();
        return;
    } else {
        // Commits a possibly existing (should not though) transaction and starts a new one for the propagate phase
        _journal->commitIfNeededAndStartNewTransaction("Post discovery");
    }

    if( csync_reconcile(_csync_ctx) < 0 ) {
        handleSyncError(_csync_ctx, "csync_reconcile");
        return;
    }

    _stopWatch.addLapTime(QLatin1String("Reconcile Finished"));

    _progressInfo = Progress::Info();

    _hasNoneFiles = false;
    _hasRemoveFile = false;
    bool walkOk = true;
    _seenFiles.clear();

    if( csync_walk_local_tree(_csync_ctx, &treewalkLocal, 0) < 0 ) {
        qDebug() << "Error in local treewalk.";
        walkOk = false;
    }
    if( walkOk && csync_walk_remote_tree(_csync_ctx, &treewalkRemote, 0) < 0 ) {
        qDebug() << "Error in remote treewalk.";
    }

    if (_csync_ctx->remote.root_perms) {
        _remotePerms[QLatin1String("")] = _csync_ctx->remote.root_perms;
        qDebug() << "Permissions of the root folder: " << _remotePerms[QLatin1String("")];
    }

    // The map was used for merging trees, convert it to a list:
    _syncedItems = _syncItemMap.values().toVector();

    // Adjust the paths for the renames.
    for (SyncFileItemVector::iterator it = _syncedItems.begin();
            it != _syncedItems.end(); ++it) {
        it->_file = adjustRenamedPath(it->_file);
    }

    // Sort items per destination
    std::sort(_syncedItems.begin(), _syncedItems.end());

    // make sure everything is allowed
    checkForPermission();

    // To announce the beginning of the sync
    emit aboutToPropagate(_syncedItems);
    _progressInfo._completedFileCount = ULLONG_MAX; // indicate the start with max
    emit transmissionProgress(_progressInfo);
    _progressInfo._completedFileCount = 0;

    if (!_hasNoneFiles && _hasRemoveFile) {
        qDebug() << Q_FUNC_INFO << "All the files are going to be changed, asking the user";
        bool cancel = false;
        emit aboutToRemoveAllFiles(_syncedItems.first()._direction, &cancel);
        if (cancel) {
            qDebug() << Q_FUNC_INFO << "Abort sync";
            finalize();
            return;
        }
    }

    ne_session_s *session = 0;
    // that call to set property actually is a get which will return the session
    csync_set_module_property(_csync_ctx, "get_dav_session", &session);
    Q_ASSERT(session);

    // post update phase script: allow to tweak stuff by a custom script in debug mode.
    if( !qgetenv("OWNCLOUD_POST_UPDATE_SCRIPT").isEmpty() ) {
#ifndef NDEBUG
        QString script = qgetenv("OWNCLOUD_POST_UPDATE_SCRIPT");

        qDebug() << "OOO => Post Update Script: " << script;
        QProcess::execute(script.toUtf8());
#else
    qDebug() << "**** Attention: POST_UPDATE_SCRIPT installed, but not executed because compiled with NDEBUG";
#endif
    }

    // do a database commit
    _journal->commit("post treewalk");

    _propagator = QSharedPointer<OwncloudPropagator>(
        new OwncloudPropagator (session, _localPath, _remoteUrl, _remotePath, _journal, &_thread));
    connect(_propagator.data(), SIGNAL(completed(SyncFileItem)),
            this, SLOT(slotJobCompleted(SyncFileItem)));
    connect(_propagator.data(), SIGNAL(progress(SyncFileItem,quint64)),
            this, SLOT(slotProgress(SyncFileItem,quint64)));
    connect(_propagator.data(), SIGNAL(adjustTotalTransmissionSize(qint64)), this, SLOT(slotAdjustTotalTransmissionSize(qint64)));
    connect(_propagator.data(), SIGNAL(finished()), this, SLOT(slotFinished()), Qt::QueuedConnection);

    // apply the network limits to the propagator
    setNetworkLimits(_uploadLimit, _downloadLimit);

    deleteStaleDownloadInfos();
    deleteStaleUploadInfos();
    deleteStaleBlacklistEntries();
    _journal->commit("post stale entry removal");

    // Emit the started signal only after the propagator has been set up.
    if (_needsUpdate)
        emit(started());

    _propagator->start(_syncedItems);
}
Example #3
0
/*
** Advance the cursor to the next row.
*/
static int schemaNext(sqlite3_vtab_cursor *cur){
  int rc = SQLITE_OK;
  schema_cursor *pCur = (schema_cursor *)cur;
  schema_vtab *pVtab = (schema_vtab *)(cur->pVtab);
  char *zSql = 0;

  while( !pCur->pColumnList || SQLITE_ROW!=sqlite3_step(pCur->pColumnList) ){
    if( SQLITE_OK!=(rc = finalize(&pCur->pColumnList)) ) goto next_exit;

    while( !pCur->pTableList || SQLITE_ROW!=sqlite3_step(pCur->pTableList) ){
      if( SQLITE_OK!=(rc = finalize(&pCur->pTableList)) ) goto next_exit;

      assert(pCur->pDbList);
      while( SQLITE_ROW!=sqlite3_step(pCur->pDbList) ){
        rc = finalize(&pCur->pDbList);
        goto next_exit;
      }

      /* Set zSql to the SQL to pull the list of tables from the 
      ** sqlite_master (or sqlite_temp_master) table of the database
      ** identfied by the row pointed to by the SQL statement pCur->pDbList
      ** (iterating through a "PRAGMA database_list;" statement).
      */
      if( sqlite3_column_int(pCur->pDbList, 0)==1 ){
        zSql = sqlite3_mprintf(
            "SELECT name FROM sqlite_temp_master WHERE type='table'"
        );
      }else{
        sqlite3_stmt *pDbList = pCur->pDbList;
        zSql = sqlite3_mprintf(
            "SELECT name FROM %Q.sqlite_master WHERE type='table'",
             sqlite3_column_text(pDbList, 1)
        );
      }
      if( !zSql ){
        rc = SQLITE_NOMEM;
        goto next_exit;
      }

      rc = sqlite3_prepare(pVtab->db, zSql, -1, &pCur->pTableList, 0);
      sqlite3_free(zSql);
      if( rc!=SQLITE_OK ) goto next_exit;
    }

    /* Set zSql to the SQL to the table_info pragma for the table currently
    ** identified by the rows pointed to by statements pCur->pDbList and
    ** pCur->pTableList.
    */
    zSql = sqlite3_mprintf("PRAGMA %Q.table_info(%Q)", 
        sqlite3_column_text(pCur->pDbList, 1),
        sqlite3_column_text(pCur->pTableList, 0)
    );

    if( !zSql ){
      rc = SQLITE_NOMEM;
      goto next_exit;
    }
    rc = sqlite3_prepare(pVtab->db, zSql, -1, &pCur->pColumnList, 0);
    sqlite3_free(zSql);
    if( rc!=SQLITE_OK ) goto next_exit;
  }
  pCur->rowid++;

next_exit:
  /* TODO: Handle rc */
  return rc;
}
gtAction::~gtAction()
{
	finalize();
}
Example #5
0
void   diaElemMenuDynamic::updateMe(void)
{
  finalize();
}
Example #6
0
	void test_normal(system::window::Window& window,
	                 bool const& running)
	{
		auto vb = window.renderer().new_vertex_buffer();
		auto ib = window.renderer().new_index_buffer();
		auto sp = window.renderer().new_shader_program();
		renderer::Renderer::TexturePtr tex0;
		try {
			tex0 = std::move(window.renderer().new_texture("/home/hotgloupi/pif.png"));
		} catch(cube::exception::Exception const&) {
			tex0 = std::move(window.renderer().new_texture("/home/hotgloupi/Downloads/Water_snail_Rex_2.jpg"));
		}

		font::Font f(window.renderer(),
			//"/usr/share/fonts/truetype/ubuntu-font-family/Ubuntu-R.ttf",
			"/usr/share/fonts/truetype/droid/DroidSerif-Regular.ttf",
			48);
		text::Text text(f, u"Ceci est un test, et ça aussi !");

		vector::Vector2f vertices[] = {
			vector::Vector2f{10,     10},
			vector::Vector2f{630,    10},
			vector::Vector2f{630,    470},
			vector::Vector2f{10,     470},
		};

		vb->push_static_content(
			renderer::ContentKind::vertex,
			vertices,
			4
		);

		vector::Vector2f tex_coords[] = {
			vector::Vector2f{0,     0},
			vector::Vector2f{1,     0},
			vector::Vector2f{1,     1},
			vector::Vector2f{0,     1},
		};
		vb->push_static_content(
			renderer::ContentKind::tex_coord0,
			tex_coords,
			4
		);

		color::Color3f colors[] = {
			{"black"}, {"green"}, {"gray"}, {"blue"},
		};
		vb->push_static_content(
			renderer::ContentKind::color,
			colors,
			4
		);

		unsigned int indices[] = {0,1,2,3};
		ib->push_static_content(
			renderer::ContentKind::index,
			indices,
			4
		);

		{
			auto vs = window.renderer().new_vertex_shader();
			vs->push_source(
				"uniform mat4 cube_ModelViewProjectionMatrix;\n"
				"void main(void)\n"
				"{\n"
				"   //gl_FrontColor = gl_Color;\n"
				"   gl_Position = cube_ModelViewProjectionMatrix * gl_Vertex;\n"
				"   gl_TexCoord[0] = gl_MultiTexCoord0;\n"
				"}\n"
			);
			sp->push_shader(std::move(vs));
		}
		{
			auto fs = window.renderer().new_fragment_shader();
			fs->push_source(
				"uniform sampler2D sampler0;"
				"void main(void) {\n"
				"   float r = texture2D(sampler0, vec2(gl_TexCoord[0])).r;\n"
				"   gl_FragColor = vec4(0,0,1,r);\n"
				"}\n"
			);
			sp->push_shader(std::move(fs));
		}

		sp->finalize();
		vb->finalize();
		ib->finalize();


		sp->parameter("cube_ModelViewProjectionMatrix");
		sp->parameter("sampler0") = *tex0;

		if (!tex0)
			throw "pif";

		while (running)
		{
			window.renderer().clear(
				renderer::BufferBit::color |
				renderer::BufferBit::depth
			);
			window.poll();
			if (auto painter = window.renderer().begin(renderer::Mode::_2d))
				{
					painter.bind(*sp);
					//painter.with(*vb, *tex0)->draw_elements(
					//	renderer::DrawMode::quads, *ib
					//);
					painter.draw(text, sp->parameter("sampler0"));

				}

			window.renderer().swap_buffers();

			::usleep(30);
		}
	}
Example #7
0
int OutCoreInterp::finish(char *outputName, int outputFormat, unsigned int outputType)
{
    int i, j;
    GridPoint *p;
    GridFile *gf;
    int len_y;
    int offset;

    //struct tms tbuf;
    clock_t t0, t1;


    /*
    // managing overlap.
    read adjacent blocks and store ghost cells and update the cells

    merging multiple files
    */
    if(openFile != -1) {
        gridMap[openFile]->getGridFile()->unmap();
        openFile = -1;
    }

    ////////////////////////////////////////////////////////////
    // flushing
    // can be moved inside the communications
    for(i = 0; i < numFiles; i++)
    {
        if(qlist[i].size() != 0)
        {
            if((gf = gridMap[i]->getGridFile()) == NULL)
            {
                cout << "OutCoreInterp::finish() getGridFile() NULL" << endl;
                return -1;
            }

            gf->map();
            openFile = i;

            // flush UpdateInfo queue
            // pop every update information
            list<UpdateInfo>::const_iterator iter;

            for(iter = qlist[i].begin(); iter!= qlist[i].end(); iter++) {
                updateInterpArray(i, (*iter).data_x, (*iter).data_y, (*iter).data_z);
            }
            qlist[i].erase(qlist[i].begin(), qlist[i].end());

            gf->unmap();
            openFile = -1;
            gf = NULL;
        }
    }
    ////////////////////////////////////////////////////////////

    for(i = 0; i < numFiles - 1; i++)
    {
        //////////////////////////////////////////////////////////////
        // read the upside overlap

        if((gf = gridMap[i]->getGridFile()) == NULL)
        {
            cout << "OutCoreInterp::finish() getGridFile() NULL" << endl;
            return -1;
        }

        if(gf->map() != -1)
        {
            openFile = i;
            // Sriram's edit to copy over DEM values to overlap also
            len_y = 2 * (gridMap[i]->getOverlapUpperBound() - gridMap[i]->getUpperBound() - 1);

            if((p = (GridPoint *)malloc(sizeof(GridPoint) * len_y * GRID_SIZE_X)) == NULL)
            {
                cout << "OutCoreInterp::finish() malloc error" << endl;
                return -1;
            }

            int start = (gridMap[i]->getOverlapUpperBound() - gridMap[i]->getOverlapLowerBound() - len_y) * GRID_SIZE_X;
            cout << "copy from " << start << " to " << (start + len_y * GRID_SIZE_X) << endl;

            memcpy(p, &(gf->interp[start]), sizeof(GridPoint) * len_y * (GRID_SIZE_X) );

            gf->unmap();
            gf = NULL;
            openFile = -1;

        } else {
            cout << "OutCoreInterp::finish() gf->map() error" << endl;
            return -1;
        }
        //////////////////////////////////////////////////////////////

        //////////////////////////////////////////////////////////////
        // update (i+1)th component
        if((gf = gridMap[i+1]->getGridFile()) == NULL)
        {
            cout << "OutCoreInterp::finish() getGridFile() NULL" << endl;
            return -1;
        }

        if(gf->map() != -1)
        {
            offset = 0;
            openFile = i - 1;

            for(j = 0; j < len_y * GRID_SIZE_X; j++)
            {
                if(gf->interp[j + offset].Zmin > p[j].Zmin)
                    gf->interp[j + offset].Zmin = p[j].Zmin;

                if(gf->interp[j + offset].Zmax < p[j].Zmax)
                    gf->interp[j + offset].Zmax = p[j].Zmax;

                gf->interp[j + offset].Zmean += p[j].Zmean;
                gf->interp[j + offset].count += p[j].count;

                if (p[j].sum != -1) {
                    gf->interp[j + offset].Zidw += p[j].Zidw;
                    gf->interp[j + offset].sum += p[j].sum;
                } else {
                    gf->interp[j + offset].Zidw = p[j].Zidw;
                    gf->interp[j + offset].sum = p[j].sum;
                }
            }

            if(p != NULL) {
                free(p);
                p = NULL;
            }

            gf->unmap();
            gf = NULL;
            openFile = -1;

        } else {
            cout << "OutCoreInterp::finish() gf->map() error" << endl;
            return -1;
        }
        //////////////////////////////////////////////////////////////
    }

    for(i = numFiles -1; i > 0; i--)
    {
        //////////////////////////////////////////////////////////////
        // read the downside overlap

        if((gf = gridMap[i]->getGridFile()) == NULL)
        {
            cout << "GridFile is NULL" << endl;
            return -1;
        }

        if(gf->map() != -1)
        {
            openFile = i;
            len_y = 2 * (gridMap[i]->getLowerBound() - gridMap[i]->getOverlapLowerBound());

            if((p = (GridPoint *)malloc(sizeof(GridPoint) * len_y * GRID_SIZE_X)) == NULL)
            {
                cout << "OutCoreInterp::finish() malloc error" << endl;
                return -1;
            }

            memcpy(p, &(gf->interp[0]), len_y * sizeof(GridPoint) * GRID_SIZE_X);

            //finalize();

            gf->unmap();
            gf = NULL;
            openFile = -1;
        } else {
            cout << "OutCoreInterp::finish gf->map() error" << endl;
            return -1;
        }
        //////////////////////////////////////////////////////////////

        //////////////////////////////////////////////////////////////
        // update (i-1)th component
        if((gf = gridMap[i-1]->getGridFile()) == NULL)
        {
            cout << "GridFile is NULL" << endl;
            return -1;
        }

        if(gf->map() != -1)
        {
            offset = (gridMap[i-1]->getOverlapUpperBound() - gridMap[i-1]->getOverlapLowerBound() - len_y) * GRID_SIZE_X;
            openFile = i - 1;

            for(j = 0; j < len_y * GRID_SIZE_X; j++)
            {
                // Sriram - the overlap already contains the correct values
                gf->interp[j + offset].Zmin = p[j].Zmin;
                gf->interp[j + offset].Zmax = p[j].Zmax;
                gf->interp[j + offset].Zmean = p[j].Zmean;
                gf->interp[j + offset].count = p[j].count;
                gf->interp[j + offset].Zidw = p[j].Zidw;
                gf->interp[j + offset].sum = p[j].sum;
            }

            //if(i - 1 == 0)
            //finalize();

            if(p != NULL) {
                free(p);
                p = NULL;
            }

            gf->unmap();
            gf = NULL;
            openFile = -1;
        }
        //////////////////////////////////////////////////////////////
    }

    for(i = 0; i < numFiles; i++)
    {
        gridMap[i]->getGridFile()->map();
        openFile = i;
        finalize();
        gridMap[i]->getGridFile()->unmap();
        openFile = -1;
    }



    t0 = clock();
    //t0 = times(&tbuf);

    // merge pieces into one file
    if(outputFile(outputName, outputFormat, outputType) < 0)
    {
        cout << "OutCoreInterp::finish outputFile error" << endl;
        return -1;
    }

    t1 = clock();
    //t1 = times(&tbuf);
    printf("Output Execution time: %10.2f\n", (double)(t1 - t0)/CLOCKS_PER_SEC);

    return 0;
}
Example #8
0
    //---------------------------------------------------------------------
    // ●
	//---------------------------------------------------------------------
	int run( MD_lnMain ln_main_, MD_lnConfig ln_config_ )
    {
        if ( !ln_main_ ) { return -1; }

        int r = -1;
        //LNRESULT lr;

        //// Framework の初期化データを作る
        //Core::ConfigData* init_data = LN_NEW Core::ConfigData();
        //
        //// LConfig と lnConfig を使って初期化データ設定
        //LConfig config( init_data );
        //if ( ln_config_ )
        //{
        //    ln_config_( config );
        //}

        /*
        if ( init_data->Failed )
        {
            SAFE_DELETE( init_data );
		    return -1;
        }
        */

		EngineSettings settings;
		ln_config_(&settings);

        initialize();

        // Framework を初期化する
        //Framework* fw = Framework::getInstance();
        //gFramework = LN_NEW Core::Manager();

		try
		{
			Engine::initialize();
			//gFramework->initialize( *init_data );
			//LN_PCALL( lr );

			// 設定はもう使わないので解放
			//SAFE_DELETE( init_data );

			gGameSceneManager = LN_NEW Utility::GameSceneManager();
			//Utility::GameSceneManager::InitData sdata;
			////sdata.LogFile = NULL;
			//sdata.Framework = gFramework;
			gGameSceneManager->initialize(/* sdata */);

			//if ( LN_SUCCEEDED( lr ) && lr != LN_FALSE )
			{
				// Accessor 初期化
				Accessor::initializeLNGlobalAccessor();

				// main 呼び出し
				r = ln_main_();

           
				// 終了処理
				//gFramework->finalize();
			}

			gGameSceneManager->finalize();
            ln::RefObjectHelper::release(gGameSceneManager);

			Accessor::finalizeLNGlobalAccessor();
		}
		catch (Exception& e)
		{
            std::cout << e.getMessage();
			throw;
		}
        
        finalize();

        return r;
    }
//*************************************************************************************************
// MAIN
//*************************************************************************************************
int main(int argc, char* argv[])
{
   ossimString tempString;
   double tempDouble, tempDouble2;
   ossimArgumentParser::ossimParameter stringParam(tempString);
   ossimArgumentParser::ossimParameter doubleParam(tempDouble);
   ossimArgumentParser::ossimParameter doubleParam2(tempDouble2);

   ossimArgumentParser argumentParser(&argc, argv);
   ossimInit::instance()->addOptions(argumentParser);
   ossimInit::instance()->initialize(argumentParser);

   argumentParser.getApplicationUsage()->setApplicationName(argumentParser.getApplicationName());
   argumentParser.getApplicationUsage()->setDescription(argumentParser.getApplicationName()+
      " Generates a bit-mask given source image and target pixel range to mask out. If the input"
      " image has overviews, then masks will be generated for all R-levels.");
   argumentParser.getApplicationUsage()->setCommandLineUsage(argumentParser.getApplicationName()+
      " [options] <input file>");

   argumentParser.getApplicationUsage()->addCommandLineOption("-d", 
      "Write mask to directory specified.");

   argumentParser.getApplicationUsage()->addCommandLineOption("-e or --entry",
      "Give the entry(zero based) for which to build a mask. Only one entry can be processed. "
      "If the input is multi-entry and no entry was specified, entry 0 is assumed.");

   argumentParser.getApplicationUsage()->addCommandLineOption("-h or --help", 
      "Shows help");

   argumentParser.getApplicationUsage()->addCommandLineOption("--mask-mode <mode>",
      "Specifies how to treat multi-band imagery when determining whether pixel will be masked "
      "according to the defined target value or range. Possible modes are: "
      "\"mask_full_and_partial_targets\" (default) | \"mask_only_full_targets\".");

   argumentParser.getApplicationUsage()->addCommandLineOption("--mask-range <min> <max>", 
      "Specifies the range of pixels to target for masking out.");

   argumentParser.getApplicationUsage()->addCommandLineOption("--mask-value <target>", 
      "Specifies the unique pixel value to target for masking out.");

   argumentParser.getApplicationUsage()->addCommandLineOption("-o", 
      "Write mask to file specified.  If used on a multi-entry file, given \"foo.mask\" you will "
      "get: \"foo_e0.mask\". If none specified, the input filename is used with \".mask\" "
      "extension.");

   argumentParser.getApplicationUsage()->addCommandLineOption("--ovr-from-image", 
      "Uses exclusively the image overview data when computing subsequent overviews. "
      "Normally the mask overview from the prior level is referenced for establishing the masks at "
      "the next level.");

   argumentParser.getApplicationUsage()->addCommandLineOption("--spec-kwl <filename>", 
      "In lieu of providing mask parameters on the command line, this option specifies a keyword "
      "list filename that contains all settings. Typically used when spawning from other process.");

   argumentParser.getApplicationUsage()->addCommandLineOption("-x or --exclude-fullres", 
      "Excludes R0 mask computation. The mask file will start at R1.");

   if(argumentParser.read("-h") || argumentParser.read("--help"))
   {
      argumentParser.getApplicationUsage()->write(std::cout);
      finalize(0);
   }

   if ( argumentParser.read("--version") || argumentParser.read("-v"))
   {
      ossimNotify(ossimNotifyLevel_NOTICE)<< argumentParser.getApplicationName().c_str() << " " 
         << ossimInit::instance()->instance()->version().c_str()<< std::endl;
      finalize(0);
   }

   // Fetch command line options:
   ossimFilename outputFile;
   if (argumentParser.read("-o", stringParam))
      outputFile = tempString.trim();

   ossimFilename outputDir;
   if (argumentParser.read("-d", stringParam))
      outputDir = tempString.trim();

   bool exclude_r0 = false;
   if (argumentParser.read("-x") || argumentParser.read("--exclude-fullres"))
      exclude_r0 = true;

   bool entry_specified = false;
   ossim_int32 entry = 0;
   if (argumentParser.read("-e", stringParam) || argumentParser.read("--entry", stringParam))
   {
      entry = ossimString(tempString).toUInt32();
      entry_specified = true;
   }

   double target_min = 0;
   double target_max = 0;
   if (argumentParser.read("--mask-range", doubleParam, doubleParam2))
   {
      target_min = tempDouble;
      target_max = tempDouble2;
   }

   if (argumentParser.read("--mask-value", doubleParam))
   {
      target_min = tempDouble;
      target_max = target_min;
   }

   ossimString mask_mode = "REPLACE_ALL_BANDS_IF_ANY_TARGET";
   ossimString mask_mode_arg;
   if (argumentParser.read("--mask-mode", stringParam))
   {
      mask_mode_arg = tempString;
      if (mask_mode_arg == "mask_full_and_partial_targets")
         mask_mode = "REPLACE_ALL_BANDS_IF_ANY_TARGET";
      else if (mask_mode_arg == "mask_only_full_targets")
         mask_mode = "REPLACE_ONLY_FULL_TARGETS";
      else
      {
         ossimNotify(ossimNotifyLevel_NOTICE)<< argumentParser.getApplicationName().c_str() << " " 
            << " Unknown mask-mode <"<<mask_mode_arg<<"> specified. See usage below." << std::endl;
         argumentParser.getApplicationUsage()->write(std::cout);
         finalize(1);
      }
   }

   bool ovr_from_image = false;
   if (argumentParser.read("--ovr-from-image"))
      ovr_from_image = true;

   ossimFilename spec_kwl_file;
   if (argumentParser.read("--spec_kwl", stringParam))
      spec_kwl_file = tempString.trim();

   // Handle bad command line:
   argumentParser.reportRemainingOptionsAsUnrecognized();
   if (argumentParser.errors())
   {
      argumentParser.writeErrorMessages(std::cout);
      finalize(1);
   }
   if ((argumentParser.argc()<2) && spec_kwl_file.empty())
   {
      argumentParser.getApplicationUsage()->write(std::cout);
      finalize(1);
   }

   // Establish input filename:
   ossimFilename inputFile;
   ossimKeywordlist kwl;
   if (spec_kwl_file.isReadable())
   {
      kwl.addFile(spec_kwl_file);
      inputFile = kwl.find(ossimKeywordNames::IMAGE_FILE_KW);
      outputFile = kwl.find(ossimKeywordNames::OUTPUT_FILE_KW);
   }
   else
   {
      inputFile = argv[1];
   }

   // Establish the input image handler:
   ossimRefPtr<ossimImageHandler> handler = ossimImageHandlerRegistry::instance()->open(inputFile);
   if (!handler.valid())
   {
      ossimNotify(ossimNotifyLevel_FATAL)<<argumentParser.getApplicationName().c_str()
         <<" Error encountered opening input file <"<<inputFile<<">."<<endl;
      finalize(1);
   }

   // Establish output filename:
   if (outputFile.empty())
      outputFile = handler->getFilenameWithThisExtension("mask", entry_specified);
   if (!outputDir.empty())
      outputFile.setPath(outputDir);
   else
   {
      ossimFilename path (outputFile.path());
      if (path.empty())
         outputFile.setPath(inputFile.path());
   }

   // Consider input file with multiple entries:
   std::vector<ossim_uint32> entryList;
   handler->getEntryList(entryList); 
   if (entryList.size() <= entry)
   {
      ossimNotify(ossimNotifyLevel_FATAL)<<argumentParser.getApplicationName().c_str()
         <<" Entry specified <"<<entry<<"> exceeds total number of entries available <"
         <<entryList.size()<<">. Aborting..."<<endl;
      finalize(1);
   }
   handler->setCurrentEntry(entry); 


   // Establish a keywordlist to pass to the mask builder. This KWL may have already been specified
   // on the command line with --spec_kwl option:
   kwl.add(ossimKeywordNames::OUTPUT_FILE_KW, outputFile.chars()); // may overwrite same value
   if (kwl.getSize() == 0)
   {
      kwl.add(ossimKeywordNames::IMAGE_FILE_KW, inputFile.chars());
      ossimString target_str (ossimString::toString(target_min)+" "+ossimString::toString(target_max));
      kwl.add(ossimPixelFlipper::PF_TARGET_RANGE_KW, target_str.chars());
      kwl.add(ossimPixelFlipper::PF_REPLACEMENT_MODE_KW, mask_mode.chars());
      kwl.add(ossimPixelFlipper::PF_REPLACEMENT_VALUE_KW, (int) 0);
      if (exclude_r0)
         kwl.add(ossimBitMaskWriter::BM_STARTING_RLEVEL_KW, (int) 1);
      else
         kwl.add(ossimBitMaskWriter::BM_STARTING_RLEVEL_KW, (int) 0);
   }

   // Instantiate the bit mask processor and write out the mask file:
   ossimRefPtr<ossimBitMaskWriter> mask_writer = new ossimBitMaskWriter;
   mask_writer->loadState(kwl);
   mask_writer->connectMyInputTo(handler.get());

   // Need to loop over all R-levels. Use a sequencer:
   ossimRefPtr<ossimImageSourceSequencer> sequencer =  new ossimImageSourceSequencer(handler.get());
   sequencer->initialize();
   int num_rlevels = handler->getNumberOfDecimationLevels();
   int num_tiles = sequencer->getNumberOfTiles();
   int tile_idx = 0;
   int percent_complete = 0;
   ossimRefPtr<ossimImageData> tile = 0;

   int start_res = 0;
   if (exclude_r0)
   {
      start_res = 1;
      num_tiles = (num_tiles+3)/4;
   }

   for (int r=start_res; r<num_rlevels; r++)
   {
      ossimNotify(ossimNotifyLevel_NOTICE)<<"\nProcessing R-level "<<r<<"... "<<endl;

      // Set the area of interest to the full image rectangle at this R-level:
      ossimIrect rect (handler->getBoundingRect(r));
      sequencer->setAreaOfInterest(rect);
      sequencer->setToStartOfSequence();
      do
      {
         tile = sequencer->getNextTile(r);
         mask_writer->generateMask(tile, r);

         percent_complete = 100 * tile_idx++/num_tiles;
         ossimNotify(ossimNotifyLevel_NOTICE)<<percent_complete<< "%\r";
      } 
      while(tile.valid());
      tile_idx = 0;
      num_tiles = (num_tiles+3)/4;
      if (num_tiles == 0)
         num_tiles = 1;

      // Check if additional overviews are to be generated directly from the mask at first R-level:
      if ((r == start_res) && !ovr_from_image)
      {
         ossimNotify(ossimNotifyLevel_NOTICE)<<"\nBuilding remaining overviews from initial mask..."
            <<endl;
         mask_writer->buildOverviews(num_rlevels);
         break;
      }
   }

   // Finished sequencing all levels, ready to write out the mask buffers:
   mask_writer->close();
   ossimNotify(ossimNotifyLevel_NOTICE)<<"\nSuccessfully wrote mask file to <"<<outputFile
      <<">. Finished."<<endl;
   
   finalize(0);
}
Example #10
0
SQLiteStatement::~SQLiteStatement()
{
    finalize();
}
Example #11
0
ch_cad_window::~ch_cad_window()
{
	finalize();
}
Example #12
0
static void second(HttpConn *conn) {
    setConn(conn);
    render("World\n");
    finalize();
}
Example #13
0
File: node.cpp Project: hunanhd/vns
    ~MPIThreadedEnv()
    {

      finalize ();
    }
Example #14
0
/**
 * @brief	
 * @param	
 * @see		
 * @remarks	
 * @code		
 * @endcode	
 * @return	
**/
Debugger::~Debugger()
{
	finalize();
}
Example #15
0
// Destructor
Kinect::~Kinect()
{
    // Finalize
    finalize();
}
Example #16
0
File: main.cpp Project: mystor/cppi
int main(int argc, const char * argv[]) {
    // Usage Message (TODO: Improve)
    if (argc < 3) {
        std::cerr << "Usage: " << argv[0] << " <FileName>\n"
                  << "Compiles the file given by <FileName>\n";
        return 1;
    }

    // Read in the file passed as the first argument
    std::ifstream fileStream;
    fileStream.open(argv[1]);

    // We'll output to the file passed in as the second argument
    std::error_code ec;
    auto openflags = llvm::sys::fs::F_None;
    auto out = std::make_unique<llvm::tool_output_file>(argv[2], ec, openflags);

    if (ec) {
        std::cerr << argv[0] << ": " << ec.message() << "\n";
        return 1;
    }

    // Parse it!
    auto lex = Lexer(&fileStream);
    auto stmts = parse(&lex);

    // std::cout << "Result of parsing: \n";
    // for (auto &stmt : stmts) {
    //     std::cout << *stmt << ";\n";
    // }

    auto prgm = Program();
    prgm.addItems(stmts);
    prgm.finalize();

    auto mod = prgm.module;

    /* DEBUG */
    // mod->dump();

    llvm::InitializeNativeTarget();
    llvm::InitializeNativeTargetAsmPrinter();
    llvm::InitializeNativeTargetAsmParser();

    llvm::PassRegistry *registry = llvm::PassRegistry::getPassRegistry();
    llvm::initializeCore(*registry);
    llvm::initializeCodeGen(*registry);
    llvm::initializeLoopStrengthReducePass(*registry);
    llvm::initializeLowerIntrinsicsPass(*registry);
    llvm::initializeUnreachableBlockElimPass(*registry);

    llvm::Triple targetTriple(mod->getTargetTriple());
    if (targetTriple.getTriple().empty()) {
        targetTriple.setTriple(llvm::sys::getDefaultTargetTriple());
    }

    std::cout << "Target Triple: " << targetTriple.getTriple() << "\n";

    std::string error;
    const llvm::Target *target = llvm::TargetRegistry::lookupTarget("", targetTriple, error);
    if (! target) {
        std::cerr << argv[0] << ": " << error;
        return 1;
    }

    auto optLvl = llvm::CodeGenOpt::Default;
    switch ('0') { // TEmporary
    default:
        std::cerr << argv[0] << ": invalid optimization level.\n";
        return 1;
    case ' ': break;
    case '0': optLvl = llvm::CodeGenOpt::None; break;
    case '1': optLvl = llvm::CodeGenOpt::Less; break;
    case '2': optLvl = llvm::CodeGenOpt::Default; break;
    case '3': optLvl = llvm::CodeGenOpt::Aggressive; break;
    }

    // llvm::TargetOptions options;
    // TODO: llc line 268

    std::unique_ptr<llvm::TargetMachine> targetMachine(target->createTargetMachine(targetTriple.getTriple(),
                                                                                   llvm::sys::getHostCPUName(),
                                                                                   "",
                                                                                   llvm::TargetOptions(),
                                                                                   llvm::Reloc::Default,
                                                                                   llvm::CodeModel::Default,
                                                                                   optLvl));
    assert(targetMachine && "Could not allocate target machine!");

    llvm::PassManager passmanager;
    llvm::TargetLibraryInfo *TLI = new llvm::TargetLibraryInfo(targetTriple);
    passmanager.add(TLI);

    if (const llvm::DataLayout *datalayout = targetMachine->getSubtargetImpl()->getDataLayout())
        mod->setDataLayout(datalayout);

    llvm::formatted_raw_ostream ostream(out->os());

    // Ask the target to add backend passes as necessary.
    if (targetMachine->addPassesToEmitFile(passmanager, ostream, llvm::TargetMachine::CGFT_ObjectFile)) {
        std::cerr << argv[0] << ": target does not support generation of this"
                  << " file type!\n";
        return 1;
    }

    passmanager.run(*mod);

    out->keep();

    return 0;
}
Example #17
0
	void test_texture(system::window::Window& window, bool& running)
	{
		auto sp = window.renderer().new_shader_program();
		{
			auto vs = window.renderer().new_vertex_shader();
			vs->push_source(
				"uniform mat4 cube_ModelViewProjectionMatrix;\n"
				"void main(void)\n"
				"{\n"
				"   //gl_FrontColor = gl_Color;\n"
				"   gl_Position = cube_ModelViewProjectionMatrix * gl_Vertex;\n"
				"   gl_TexCoord[0] = gl_MultiTexCoord0;\n"
				"}\n"
			);
			sp->push_shader(std::move(vs));
		}
		{
			auto fs = window.renderer().new_fragment_shader();
			fs->push_source(
				"uniform sampler2D sampler0;"
				"void main(void) {\n"
				"   float c = texture2D(sampler0, vec2(gl_TexCoord[0])).r;\n"
				"   gl_FragColor = vec4(c,c,c,1);\n"
				"}\n"
			);
			sp->push_shader(std::move(fs));
		}
		sp->finalize();
		sp->parameter("cube_ModelViewProjectionMatrix");

		auto tex = window.renderer().new_texture(
			renderer::PixelFormat::red,
			24,
			24,
			renderer::PixelFormat::red,
			renderer::ContentPacking::uint8,
			nullptr
		);

		{
			char buf[24*24];
			for (int x = 0; x < 24; ++x)
				for (int y = 0; y < 24; ++y)
				{
					buf[x + y * 24] = (x > 4 && x < 19 ? 255 : 64);
				}
			tex->set_data(0, 0, 24, 24,
			              renderer::PixelFormat::red,
			              renderer::ContentPacking::uint8,
			              buf);
		}

		sp->parameter("sampler0") = *tex;

		auto vb = window.renderer().new_vertex_buffer();
		{
			vector::Vector2f vertices[] = {
				vector::Vector2f{10,     10},
				vector::Vector2f{630,    10},
				vector::Vector2f{630,    470},
				vector::Vector2f{10,     470},
			};
			vb->push_static_content(
				renderer::ContentKind::vertex,
				vertices,
				4
			);

			vector::Vector2f tex_coords[] = {
				vector::Vector2f{0,     0},
				vector::Vector2f{1,     0},
				vector::Vector2f{1,     1},
				vector::Vector2f{0,     1},
			};
			vb->push_static_content(
				renderer::ContentKind::tex_coord0,
				tex_coords,
				4
			);
		}
		vb->finalize();

		auto ib = window.renderer().new_index_buffer();
		{
			unsigned int indices[] = {0,1,2,3};
			ib->push_static_content(
				renderer::ContentKind::index,
				indices,
				4
			);
		}
		ib->finalize();

		while (running)
		{
			window.renderer().clear(
				renderer::BufferBit::color |
				renderer::BufferBit::depth
			);
			window.poll();
			if (auto painter = window.renderer().begin(renderer::Mode::_2d))
				{
					painter.bind(*vb);
					painter.bind(*sp);
					painter.bind(*tex);
					painter.draw_elements(renderer::DrawMode::quads, *ib, 0, 4);
				}

			window.renderer().swap_buffers();

			::usleep(30);
		}
	}
Example #18
0
	AnnFuncGroupFactory::~AnnFuncGroupFactory()
	{
		finalize();
	}
Example #19
0
tempstmt::~tempstmt()
{
    finalize();
}
Example #20
0
BulletWorld::~BulletWorld() {
    finalize();
}
// clears all the inner structures and loads the configuration parameters'
// values again
void
ReplicatorStateMachine::reinitialize()
{
    // delete all configurations and start everything over from the scratch
    finalize( );
    AbstractReplicatorStateMachine::reinitialize( );

    m_myVersion.initialize( m_stateFilePath, m_versionFilePath );

    m_replicationInterval =
		param_integer("REPLICATION_INTERVAL",
					  5 * MINUTE,
					  0); // min value, must be positive
    // deduce HAD alive tolerance
    int hadConnectionTimeout =
		param_integer("HAD_CONNECTION_TIMEOUT",
					  DEFAULT_SEND_COMMAND_TIMEOUT,
					  0); // min value, must be positive
    m_maxTransfererLifeTime =
		param_integer("MAX_TRANSFER_LIFETIME",
					  5 * MINUTE,
					  0); // min value, must be positive
    m_newlyJoinedWaitingVersionInterval =
		param_integer("NEWLY_JOINED_WAITING_VERSION_INTERVAL",
					  NEWLY_JOINED_TOLERANCE_FACTOR * (hadConnectionTimeout + 1),
					  0); // min value, must be positive

    char* buffer = param( "HAD_LIST" );

    if ( buffer ) {
        StringList hadList;

        hadList.initializeFromString( buffer );
        free( buffer );
        m_hadAliveTolerance = HAD_ALIVE_TOLERANCE_FACTOR *
                            ( 2 * hadConnectionTimeout * hadList.number() + 1 );

        dprintf( D_FULLDEBUG, "ReplicatorStateMachine::reinitialize %s=%d\n",
                "HAD_LIST", m_hadAliveTolerance );
    } else {
        utilCrucialError( utilNoParameterError( "HAD_LIST", "HAD" ).Value( ));
    }

    initializeClassAd();
    int updateInterval = param_integer ( "REPLICATION_UPDATE_INTERVAL", 300 );
    if ( m_updateInterval != updateInterval ) {
        m_updateInterval = updateInterval;

        utilCancelTimer(m_updateCollectorTimerId);

        m_updateCollectorTimerId = daemonCore->Register_Timer ( 0,
               m_updateInterval,
               (TimerHandlercpp) &ReplicatorStateMachine::updateCollectors,
               "ReplicatorStateMachine::updateCollectors", this );
    }

    // set a timer to replication routine
    dprintf( D_ALWAYS, "ReplicatorStateMachine::reinitialize setting "
                                      "replication timer\n" );
    m_replicationTimerId = daemonCore->Register_Timer( m_replicationInterval,
            (TimerHandlercpp) &ReplicatorStateMachine::replicationTimer,
            "Time to replicate file", this );
    // register the download/upload reaper for the transferer process
    if( m_downloadReaperId == -1 ) {
		m_downloadReaperId = daemonCore->Register_Reaper(
        	"downloadReplicaTransfererReaper",
        (ReaperHandler)&ReplicatorStateMachine::downloadReplicaTransfererReaper,
        	"downloadReplicaTransfererReaper", this );
	}
    if( m_uploadReaperId == -1 ) {
		m_uploadReaperId = daemonCore->Register_Reaper(
        	"uploadReplicaTransfererReaper",
        (ReaperHandler) &ReplicatorStateMachine::uploadReplicaTransfererReaper,
        	"uploadReplicaTransfererReaper", this );
    }
	// for debugging purposes only
	printDataMembers( );
	
	beforePassiveStateHandler( );
}
Example #22
0
bson_codec::~bson_codec()
{
    finalize();
}
Example #23
0
Database::~Database()
{
  finalize();
  sqlite3_close(m_db);
}
Example #24
0
/** MAIN */
int main(int argc, char** argv) {

    int opt,threads;
    extern char* optarg;
    extern int optind;

    timer io_start, b_start, b_end;

    // Who we are
    fprintf(stderr, "StarBench - RGBYUV Kernel\n");

    // Parse command line options
    while ( (opt=getopt(argc,argv,"i:c:ht:")) != EOF) {
        switch (opt) {
            case 'i':
                infile = optarg;
                break;
            case 'c':
                iterations = atoi(optarg);
                break;
            case 'h':
                fprintf(stderr, usage, argv[0]);
                return 0;
                break;
    /**************************************SET THREADS NUMBER**************************************************/
	    case 't':
                threads = atoi(optarg); 
                break;
            default:
                fprintf(stderr, usage, argv[0]);
                return 0;
                break;
        }
    }

    if (infile == NULL || iterations < 0) {
        fprintf(stderr, "Illegal argument given, exiting\n");
        return -1;
    }

#ifdef VERBOSE
    statsme();
#endif

    rgbyuv_args_t args;

    TIME(io_start);

    if(initialize(&args)) {
        fprintf(stderr, "Could Not Initialize Kernel Data\n");
        return -1;
    }

    TIME(b_start);
    /**************************************SET THREADS NUMBER**************************************************/
    omp_set_num_threads(threads);
   
    processImage(&args);

    TIME(b_end);

    writeComponents(&args);

    if(finalize(&args)) {
        fprintf(stderr, "Could Not Free Allocated Memory\n");
        return -1;
    }

    double io_time = (double)timediff(&io_start, &b_start)/1000;
    double b_time = (double)timediff(&b_start, &b_end)/1000;

    printf("\nI/O time: %.3f\nTime: %.3f\n", io_time, b_time);

    return 0;
}
Example #25
0
void SyncEngine::startSync()
{
    if (_journal->exists()) {
        QVector< SyncJournalDb::PollInfo > pollInfos = _journal->getPollInfos();
        if (!pollInfos.isEmpty()) {
            qDebug() << "Finish Poll jobs before starting a sync";
            CleanupPollsJob *job = new CleanupPollsJob(pollInfos, AccountManager::instance()->account(),
                                                       _journal, _localPath, this);
            connect(job, SIGNAL(finished()), this, SLOT(startSync()));
            connect(job, SIGNAL(aborted(QString)), this, SLOT(slotCleanPollsJobAborted(QString)));
            job->start();
            return;
        }
    }

    Q_ASSERT(!_syncRunning);
    _syncRunning = true;

    Q_ASSERT(_csync_ctx);

    if (!QDir(_localPath).exists()) {
        // No _tr, it should only occur in non-mirall
        emit csyncError("Unable to find local sync directory.");
        finalize();
        return;
    }

    _syncedItems.clear();
    _syncItemMap.clear();
    _needsUpdate = false;

    csync_resume(_csync_ctx);

    int fileRecordCount = -1;
    if (!_journal->exists()) {
        qDebug() << "=====sync looks new (no DB exists)";
    } else {
        qDebug() << "=====sync with existing DB";
    }

    qDebug() <<  "=====Using Qt" << qVersion();
#if QT_VERSION >= QT_VERSION_CHECK(5,0,0)
    qDebug() <<  "=====Using SSL library version"
             <<  QSslSocket::sslLibraryVersionString().toUtf8().data();
#endif
    // Note that this seems to output the OpenSSL build version not runtime version:
    qDebug() <<  "=====Using" << ne_version_string();

    fileRecordCount = _journal->getFileRecordCount(); // this creates the DB if it does not exist yet
    bool isUpdateFrom_1_5 = _journal->isUpdateFrom_1_5();

    if( fileRecordCount == -1 ) {
        qDebug() << "No way to create a sync journal!";
        emit csyncError(tr("Unable to initialize a sync journal."));
        finalize();
        return;
        // database creation error!
    }

    if (fileRecordCount >= 1 && isUpdateFrom_1_5) {
        qDebug() << "detected update from 1.5" << fileRecordCount << isUpdateFrom_1_5;
        // Disable the read from DB to be sure to re-read all the fileid and etags.
        csync_set_read_from_db(_csync_ctx, false);
    } else {
        csync_set_read_from_db(_csync_ctx, true);
    }

    bool usingSelectiveSync = (!_selectiveSyncBlackList.isEmpty());
    qDebug() << (usingSelectiveSync ? "====Using Selective Sync" : "====NOT Using Selective Sync");
    if (fileRecordCount >= 0 && fileRecordCount < 50 && !usingSelectiveSync) {
        qDebug() << "===== Activating recursive PROPFIND (currently" << fileRecordCount << "file records)";
        bool no_recursive_propfind = false;
        csync_set_module_property(_csync_ctx, "no_recursive_propfind", &no_recursive_propfind);
    } else {
        bool no_recursive_propfind = true;
        csync_set_module_property(_csync_ctx, "no_recursive_propfind", &no_recursive_propfind);
    }

    csync_set_userdata(_csync_ctx, this);
    // TODO: This should be a part of this method, but we don't have
    // any way to get "session_key" module property from csync. Had we
    // have it, then we could keep this code and remove it from
    // AbstractCredentials implementations.
    if (Account *account = AccountManager::instance()->account()) {
        account->credentials()->syncContextPreStart(_csync_ctx);
    } else {
        qDebug() << Q_FUNC_INFO << "No default Account object, huh?";
    }
    // if (_lastAuthCookies.length() > 0) {
    //     // Stuff cookies inside csync, then we can avoid the intermediate HTTP 401 reply
    //     // when https://github.com/owncloud/core/pull/4042 is merged.
    //     QString cookiesAsString;
    //     foreach(QNetworkCookie c, _lastAuthCookies) {
    //         cookiesAsString += c.name();
    //         cookiesAsString += '=';
    //         cookiesAsString += c.value();
    //         cookiesAsString += "; ";
    //     }
    //     csync_set_module_property(_csync_ctx, "session_key", cookiesAsString.to
    // }

    // csync_set_auth_callback( _csync_ctx, getauth );
    //csync_set_log_level( 11 ); don't set the loglevel here, it shall be done by folder.cpp or owncloudcmd.cpp
    int timeout = OwncloudPropagator::httpTimeout();
    csync_set_module_property(_csync_ctx, "timeout", &timeout);


    _stopWatch.start();

    qDebug() << "#### Discovery start #################################################### >>";

    DiscoveryJob *job = new DiscoveryJob(_csync_ctx);
    job->_selectiveSyncBlackList = _selectiveSyncBlackList;
    job->moveToThread(&_thread);
    connect(job, SIGNAL(finished(int)), this, SLOT(slotDiscoveryJobFinished(int)));
    connect(job, SIGNAL(folderDiscovered(bool,QString)),
            this, SIGNAL(folderDiscovered(bool,QString)));
    QMetaObject::invokeMethod(job, "start", Qt::QueuedConnection);
}
Example #26
0
Thread::~Thread()                               { finalize(); }
Example #27
0
void SyncEngine::slotCleanPollsJobAborted(const QString &error)
{
    csyncError(error);
    finalize();
}
SVIPostEffectRenderer::~SVIPostEffectRenderer() {
	SVI_SVIFE_DELETE(mScene);
	mSVIGLSurface = NULL; // Multi-Instance-Support

	finalize();
}
Example #29
0
/**
 * Kontrola a zpracovani zprav pomoci MPI.
 */
void mpi_handle() {
	MPI_Status mpi_status;
	int mpi_flag;
	unsigned int l;
	unsigned int v = 1;
	char *b = NULL;

	MPI_Iprobe(MPI_ANY_SOURCE, MPI_ANY_TAG, MPI_COMM_WORLD, &mpi_flag,
		&mpi_status);

	// odeslu nejnizsi nalezenou penalizaci (podmineno viz. telo funkce)
	mpi_send_penalty();

	if(mpi_flag) {
		srpdebug("msg", node, "zprava <tag=%d>", mpi_status.MPI_TAG);

		switch(mpi_status.MPI_TAG) {
		case MSG_REQUEST:
			srpdebug("msg", node, "MSG_REQUEST");
			MPI_Recv(&v, 1, MPI_UNSIGNED, mpi_status.MPI_SOURCE, MSG_REQUEST,
				MPI_COMM_WORLD, &mpi_status);

			srpdebug("mpi", node, "prijata zadost o praci <src=%d>",
				mpi_status.MPI_SOURCE);

			// TODO rozdelit praci a odpovedet MSG_STACK nebo MSG_NOSTACK
			if(s->s_real > 1) {
				mpi_send_stack(2, mpi_status.MPI_SOURCE);
			} else {
				mpi_send_nostack(mpi_status.MPI_SOURCE);
			}
			break;

		case MSG_STACK:
			srpdebug("msg", node, "MSG_STACK");
			mpi_recv_stack(mpi_status.MPI_SOURCE);
			break;

		case MSG_NOSTACK:
			srpdebug("msg", node, "MSG_NOSTACK");
			mpi_recv_nostack(mpi_status.MPI_SOURCE);
			break;

		case MSG_PENALTY:
			srpdebug("msg", node, "MSG_PENALTY");
			mpi_recv_penalty(mpi_status.MPI_SOURCE);
			break;

		case MSG_TOKEN:
			srpdebug("msg", node, "MSG_TOKEN");
			mpi_recv_token(mpi_status.MPI_SOURCE);
			break;

		case MSG_FINALIZE:
			srpdebug("msg", node, "MSG_FINALIZE");
			mpi_recv_finalize(mpi_status.MPI_SOURCE);
			finalize();
			break;

		default:
			// neznama zprava
			srpprintf(stderr, "msg", node, "neznama zprava");
			exit(EXIT_FAILURE);
		}
	} /* else {
		srpdebug("mpi", node, "zadne zpravy");
	} */
}
Example #30
0
  bool WFMCSingleOMP::run()
  {
    resetRun();

    //start the main estimator
    Estimators->start(nBlocks);

    ///Load a single walkers position into the walker.
    MCWalkerConfiguration Keeper(W);
    Keeper.createWalkers(W.begin(),W.end());
    MCWalkerConfiguration::iterator Kit=(Keeper.begin()), Kit_end(Keeper.end());

    int block=0;
    while ((Kit!=Kit_end)&&(nBlocks>block))
      {
        MCWalkerConfiguration::iterator Wit(W.begin()), Wit_end(W.end());
        while ((Wit!=Wit_end))
          {
            (*Wit)->R=(*Kit)->R;
            (*Wit)->G=(*Kit)->G;
            (*Wit)->L=(*Kit)->L;
            //(*Wit)->Drift=(*Kit)->Drift;
            (*Wit)->reset();
            (*Wit)->resetPropertyHistory();
            ++Wit;
          }
#pragma omp parallel for
        for (int ip=0; ip<NumThreads; ++ip)
          Movers[ip]->initWalkers(W.begin()+wPerNode[ip],W.begin()+wPerNode[ip+1]);

        Wit=W.begin();
        while ((Wit!=Wit_end))
          {
            //       app_log()<<std::exp((*Wit)->Properties(LOGPSI))<<endl;
            (*Wit)->PropertyHistory[0][0]=std::exp((*Wit)->Properties(LOGPSI));
            ++Wit;
          }


#pragma omp parallel
        {
#pragma omp for
          for (int ip=0; ip<NumThreads; ++ip)
            Movers[ip]->startRun(nBlocks,false);

#pragma omp for
          for (int ip=0; ip<NumThreads; ++ip)
            {
              //assign the iterators and resuse them
              MCWalkerConfiguration::iterator wit(W.begin()+wPerNode[ip]), wit_end(W.begin()+wPerNode[ip+1]);

              Movers[ip]->startBlock(nSteps);
              for (int step=0; step<nSteps;++step)
                {
                  Movers[ip]->advanceWalkers(wit,wit_end,false);
                  //      Movers[ip]->updateWalkers(wit,wit_end);
                  //      wClones[ip]->saveEnsemble(wit,wit_end);
                }
              Movers[ip]->accumulate(wit,wit_end);
              Movers[ip]->stopBlock();
            }
#pragma omp master
          {
            Estimators->stopBlock(estimatorClones);
            recordBlock(block+1);
            block++;
            ++Kit;
          }
        }

      }//end of parallel
    Estimators->stop(estimatorClones);

    //copy back the random states
    for (int ip=0; ip<NumThreads; ++ip)
      *(RandomNumberControl::Children[ip])=*(Rng[ip]);

    //finalize a qmc section
    return finalize(nBlocks);
  }