Пример #1
0
// поток чтения пайпа 
DWORD Updater::read_update_progress_thread(LPVOID param)
{
	Updater* updater = static_cast<Updater*>(param);
	updater->AddProgressInfo(prog_info::PROGRESS_START);
	for (;;) 
	{ 
		std::string output;
		const int	BUFSIZE = 1024;
		char		chBuf[BUFSIZE];
		DWORD		dwRead;
		DWORD		ec = 0; //exit code
		
    DWORD bytesAvailable = 0;
    while (PeekNamedPipe(updater->_hReadPipe, NULL, 0, NULL, &bytesAvailable, NULL) && bytesAvailable > 0)
  		if (ReadFile(updater->_hReadPipe, chBuf, BUFSIZE - 1, &dwRead,	NULL) && dwRead)
	  	{
		  	chBuf[dwRead] = '\0';
			  output += chBuf;
			  LOG_DEBUG << output;
			  updater->parse(output);
		  }

    if (!GetExitCodeThread(updater->_pi.hThread, &ec) || ec != STILL_ACTIVE)
      break;

	} 
	updater->AddProgressInfo(prog_info::PROGRESS_END);
	updater->DestroyHandle();
	return 0;
}
Пример #2
0
void UpdaterTest::testRun()
{
	vector<string> versionStrings;
	versionStrings.push_back("800");
	versionStrings.push_back("900");
	versionStrings.push_back("1000");
	versionStrings.push_back("Error, no connection");
	versionStrings.push_back("1100");
	versionStrings.push_back("1200");

	MockUpdateServer *mus = new MockUpdateServer(versionStrings);
	Updater *u = new Updater((UpdateServer*)mus, 1100, ".", 0, 0, 0);

	u->run();

	vector<bool> wasDownloadAttempted = mus->_recordedDownloadAttemptsAfterUpdateChecks;
	CPPUNIT_ASSERT_EQUAL((size_t)6, wasDownloadAttempted.size());
	CPPUNIT_ASSERT_EQUAL(false, (bool)wasDownloadAttempted[0]);
	CPPUNIT_ASSERT_EQUAL(false, (bool)wasDownloadAttempted[1]);
	CPPUNIT_ASSERT_EQUAL(false, (bool)wasDownloadAttempted[2]);
	CPPUNIT_ASSERT_EQUAL(false, (bool)wasDownloadAttempted[3]);
	CPPUNIT_ASSERT_EQUAL(false, (bool)wasDownloadAttempted[4]);
	CPPUNIT_ASSERT_EQUAL(true, (bool)wasDownloadAttempted[5]);

	delete mus;
	delete u;

}
Пример #3
0
int     main(int argc, char** argv)
{
  QApplication  app(argc, argv);
  Updater       updater;

  if (argc != 3) return 1;
  updater.show();
  return app.exec();
}
Пример #4
0
int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    MapMaker w;
    Updater *u = new Updater();
    w.getTerrainPainter()->setUpdater(u);
    u->connect(u,SIGNAL(update()),w.getTerrainPainter(),SLOT(paintMap()));
    w.show();
    u->start();

    return a.exec();
}
Пример #5
0
// поток, проверка наличия обновления 
DWORD Updater::read_check_update_thread(LPVOID param)
{
	Updater*	updater = static_cast<Updater*>(param);
	std::string output;
	for (;;) 
	{ 
		const int	BUFSIZE = 1024;
		char		chBuf[BUFSIZE];
		DWORD		dwRead;
		DWORD		ec = 0; //exit code

    DWORD bytesAvailable = 0;
    while (PeekNamedPipe(updater->_hReadPipe, NULL, 0, NULL, &bytesAvailable, NULL) && bytesAvailable > 0)
      if (ReadFile(updater->_hReadPipe, chBuf, BUFSIZE - 1, &dwRead,	NULL) && dwRead)
      {
        chBuf[dwRead] = '\0';
        output += chBuf;

      }
    if (!GetExitCodeThread(updater->_pi.hThread, &ec) || ec != STILL_ACTIVE)
			break;
	} 
	
	LOG_DEBUG << output;
	int	count_line = 0;
	for (std::string::iterator it = output.begin(); it != output.end(); ++it)
	{
		if (*it != '\n')
			continue;
		std::string line = output.substr(0, std::distance(output.begin(), it));
		++it;
		output.erase(output.begin(), it);
		it = output.begin();
		if (0 != line.find("sending") &&
			(line.size()-1) != line.find("/") &&
			0 != line.find("deleting") &&
			1 != line.find("sent") &&
			0 != line.find("total size") &&
			0 != line.size())
				++count_line;			
		if (it == output.end())
			break;
	}

	bool exist_update = count_line > 0;

	updater->_status_check.get_content(); // удаляем предыдущую информацию
	updater->_status_check.push_back(exist_update);

	updater->DestroyHandle();
	return 0;
}
Пример #6
0
bool Filemanager::update(std::string file_path) {
    Updater *updater = new Updater();
    std::pair<std::map<int, int>, std::vector<std::pair<long, long> > > updater_result = updater->get_similar(file_path);
    std::map<int, int> similar_chunk = updater_result.first;
    std::vector<std::pair<long, long> > diff = updater_result.second;
    // std::cout << "similar:" << std::endl;
    // updater->show_similar(similar_chunk);
    // std::cout << "diff bytes:" << std::endl;
    updater->show_diff(diff);
    this->mworker = new Metaworker();
    this->mworker->load(file_path);
    std::vector<int> chunk_to_del;

    this->mworker->show();
    
    for(int i = 0; i < mworker->mdata_size(); i++) {
        if(similar_chunk.find(i) == similar_chunk.end()) {
            // std::cout << i << " ";
            chunk_to_del.push_back(i);

        } else {
            mworker->mdata[i].start += ( *(similar_chunk.find(i))).second - 1;
            mworker->mdata[i].finish += ( *(similar_chunk.find(i))).second - 1;
        }
    }

    // std::cout << std::endl << "old mdata: " << std::endl;;

   
    for(int i = chunk_to_del.size() - 1;i >= 0; i--) {
        // std::cout << "num: " << i << " chunk:" << chunk_to_del[i] << std::endl;
        this->rm_file(this->mworker->get(chunk_to_del[i]).cipher_hash);
        this->mworker->remove(chunk_to_del[i]);
    }

    for(int i = 0; i < diff.size(); i++) {
        this->segmentate(file_path, diff[i].first, diff[i].second);
    }

std::cout << std::endl << "new mdata: " << std::endl;
this->mworker->sort();
    this->mworker->save();



    // this->mworker->save();
    return true;

}
Пример #7
0
int main(int argc, char* argv[])
{
    QApplication app(argc, argv);

    QTranslator translator;
    translator.load(":/translation/qt_fr");

    app.installTranslator(&translator);

    Updater up;

    up.show();

    return app.exec();
}
Пример #8
0
void UpdaterTest::testRegisteringUpdateMessage()
{
	vector<string> versionStrings;
	versionStrings.push_back("800");
	MockUpdateServer *mus = new MockUpdateServer(versionStrings);
	Updater *u = new Updater(mus, 99, ".", 0, 0, 0);

	CPPUNIT_ASSERT_EQUAL(u->getUpdateDownloadedMessageId(), u->getUpdateDownloadedMessageId());

	delete u;
	delete mus;
	// updater->getUpdateDownloadedMessage()
	// should be consistent, even if you call it twice

}
Пример #9
0
void testTaskNumDiff(const std::vector<rbd::MultiBody>& mbs,
	const std::vector<rbd::MultiBodyConfig>& mbcs,
	Task& task, Updater updater, Tester tester,
	int nrIter=100, double diffStep=1e-6, double tol=1e-4)
{
	using namespace Eigen;
	using namespace sva;
	using namespace rbd;

	std::vector<MultiBodyConfig> mbcsPost(mbcs), mbcsCur(mbcs);

	std::vector<Eigen::VectorXd> q(mbs.size());
	std::vector<Eigen::VectorXd> alpha(mbs.size());
	std::vector<Eigen::VectorXd> alphaD(mbs.size());

	for(int i = 0; i < nrIter; ++i)
	{
		for(std::size_t r = 0; r < mbs.size(); ++r)
		{
			const rbd::MultiBody& mb = mbs[r];
			const rbd::MultiBodyConfig& mbc = mbcs[r];
			rbd::MultiBodyConfig& mbcPost = mbcsPost[r];
			rbd::MultiBodyConfig& mbcCur = mbcsCur[r];

			q[r].setRandom(mb.nrParams());
			alpha[r].setRandom(mb.nrDof());
			alphaD[r].setRandom(mb.nrDof());

			mbcCur = mbc;
			vectorToParam(q[r], mbcCur.q);
			vectorToParam(alpha[r], mbcCur.alpha);
			vectorToParam(alphaD[r], mbcCur.alphaD);

			mbcPost = mbcCur;

			eulerIntegration(mb, mbcPost, diffStep);

			forwardKinematics(mb, mbcCur);
			forwardKinematics(mb, mbcPost);
			forwardVelocity(mb, mbcCur);
			forwardVelocity(mb, mbcPost);
		}

		updater(task, mbs, mbcsCur);
		VectorXd evalCur = task.eval();
		VectorXd speedCur = -task.speed();
		VectorXd accCur = -task.normalAcc();
		accCur -= updater.tanAcc(task, alphaD);

		updater(task, mbs, mbcsPost);
		VectorXd evalPost = task.eval();
		VectorXd speedPost = -task.speed();

		VectorXd speedDiff = (evalPost - evalCur)/diffStep;
		VectorXd accDiff = (speedPost - speedCur)/diffStep;

		tester(speedCur, accCur, speedDiff, accDiff, tol);
	}
}
Пример #10
0
void TestUpdater::updaterCopy()
{
    Updater u;
    u.setLocalRepository(dataCopy + "/local_repo");
    u.copy(testOutputCopy);
    QSignalSpy spy(&u, SIGNAL(copyFinished(bool)));
    QVERIFY(spy.wait());

    try {
        (TestUtils::assertFileEquals(dataCopy + "/local_repo/patch_same.txt", testOutputCopy + "/patch_same.txt"));
        (TestUtils::assertFileEquals(dataCopy + "/local_repo/path_diff.txt", testOutputCopy + "/path_diff.txt"));
        (TestUtils::assertFileEquals(dataCopy + "/local_repo/path_diff2.txt", testOutputCopy + "/path_diff2.txt"));
        (TestUtils::assertFileEquals(dataCopy + "/local_repo/rmfile.txt", testOutputCopy + "/rmfile.txt"));
    } catch(QString &msg) {
        QFAIL(msg.toLatin1());
    }
    QVERIFY(!QFile::exists(testOutputCopy + "/add.txt"));
}
Пример #11
0
void TestUpdater::updaterIsManaged()
{
    Updater u;
    u.setLocalRepository(testOutputIsManaged);
    QVERIFY(u.isManaged(testOutputIsManaged + "/status.json"));
    QVERIFY(u.isManaged(testOutputIsManaged + "/path_diff.txt"));
    QVERIFY(u.isManaged(testOutputIsManaged + "/dirs/empty_dir2/"));
    QVERIFY(u.isManaged(testOutputIsManaged + "/dirs/"));
    QVERIFY(!u.isManaged(testOutputIsManaged + "/dirs/empty_dir1/"));
    QVERIFY(!u.isManaged(testOutputIsManaged + "/unmanaged.json"));
}
/**
 * Returns the \c Updater instance registered with the given \a url.
 *
 * If an \c Updater instance registered with teh given \a url does not exist,
 * this function will create it and configure it automatically.
 */
Updater* QSimpleUpdater::getUpdater (const QString& url) const
{
    if (!URLS.contains (url)) {
        Updater* updater = new Updater;
        updater->setUrl (url);

        URLS.append (url);
        UPDATERS.append (updater);

        connect (updater, SIGNAL (checkingFinished  (QString)),
                 this,    SIGNAL (checkingFinished  (QString)));
        connect (updater, SIGNAL (downloadFinished  (QString, QString)),
                 this,    SIGNAL (downloadFinished  (QString, QString)));
        connect (updater, SIGNAL (appcastDownloaded (QString, QByteArray)),
                 this,    SIGNAL (appcastDownloaded (QString, QByteArray)));
    }

    return UPDATERS.at (URLS.indexOf (url));
}
Пример #13
0
void UpdaterTest::testRunTiming()
{
	vector<string> versionStrings;
	versionStrings.push_back("800");
	versionStrings.push_back("900");
	versionStrings.push_back("1000");
	versionStrings.push_back("Error, no connection");
	versionStrings.push_back("1100");
	versionStrings.push_back("1200");

	MockUpdateServer *mus = new MockUpdateServer(versionStrings);

	int currentVersion = 1100;
	uint retryTimeAfterFailedUpdateCheck = 50;
	uint timeBetweenUpdateChecks = 150;
	Updater *u = new Updater((UpdateServer*)mus,
		currentVersion,
		".",
		retryTimeAfterFailedUpdateCheck,
		timeBetweenUpdateChecks,
		0);

	u->run();

	vector<bool> wasDownloadAttempted = mus->_recordedDownloadAttemptsAfterUpdateChecks;
	CPPUNIT_ASSERT_EQUAL((size_t)6, wasDownloadAttempted.size());
	CPPUNIT_ASSERT_EQUAL(false, (bool)wasDownloadAttempted[0]);
	CPPUNIT_ASSERT_EQUAL(false, (bool)wasDownloadAttempted[1]);
	CPPUNIT_ASSERT_EQUAL(false, (bool)wasDownloadAttempted[2]);
	CPPUNIT_ASSERT_EQUAL(false, (bool)wasDownloadAttempted[3]);
	CPPUNIT_ASSERT_EQUAL(false, (bool)wasDownloadAttempted[4]);
	CPPUNIT_ASSERT_EQUAL(true, (bool)wasDownloadAttempted[5]);

	vector<uint> timeBetweenDownloadAttempts = mus->_recordedTimeForEachUpdateCheck;
	CPPUNIT_ASSERT_EQUAL((size_t)6, timeBetweenDownloadAttempts.size());
	CPPUNIT_ASSERT(timeBetweenDownloadAttempts[0] < 10);
	CPPUNIT_ASSERT(145 < timeBetweenDownloadAttempts[1] && timeBetweenDownloadAttempts[1] < 155);
	CPPUNIT_ASSERT(145 < timeBetweenDownloadAttempts[2] && timeBetweenDownloadAttempts[2] < 155);
	CPPUNIT_ASSERT(145 < timeBetweenDownloadAttempts[3] && timeBetweenDownloadAttempts[3] < 155);
	CPPUNIT_ASSERT(45 < timeBetweenDownloadAttempts[4] && timeBetweenDownloadAttempts[4] < 55);
	CPPUNIT_ASSERT(145 < timeBetweenDownloadAttempts[5] && timeBetweenDownloadAttempts[5] < 155);

}
Пример #14
0
void TestUpdater::updaterRemoveOtherFiles()
{
    Updater u;
    u.setLocalRepository(testOutputIsManaged);
    QVERIFY(QFile::exists(testOutputIsManaged + "/status.json"));
    QVERIFY(QFile::exists(testOutputIsManaged + "/unmanaged.json"));
    QVERIFY(QDir(testOutputIsManaged + "/dirs/empty_dir1").exists());

    u.removeOtherFiles([](QFileInfo file) {
        return file.fileName() != "unmanaged.json";
    });
    QVERIFY(QFile::exists(testOutputIsManaged + "/status.json"));
    QVERIFY(QFile::exists(testOutputIsManaged + "/unmanaged.json"));
    QVERIFY(!QDir(testOutputIsManaged + "/dirs/empty_dir1").exists());

    u.removeOtherFiles();
    QVERIFY(QFile::exists(testOutputIsManaged + "/status.json"));
    QVERIFY(!QFile::exists(testOutputIsManaged + "/unmanaged.json"));
    QVERIFY(!QDir(testOutputIsManaged + "/dirs/empty_dir1").exists());
}
Пример #15
0
void UpdaterTest::testIsUpdateDownloaded()
{
	if (exists("a_temporary_test_data_directory"))
	{
		remove("a_temporary_test_data_directory\\BumpTopInstaller.msi");
		remove("a_temporary_test_data_directory\\version.txt");
		remove("a_temporary_test_data_directory\\desc.txt");
	}

	vector<string> versionStrings;
	versionStrings.push_back("800");
	MockUpdateServer *mus = new MockUpdateServer(versionStrings);
	Updater *u = new Updater(mus, 99, "a_temporary_test_data_directory", 0, 0, 0);

	create_directory("a_temporary_test_data_directory");

	ofstream installer("a_temporary_test_data_directory//BumpTopInstaller.msi");
	installer << "!!!!!";
	installer.close();

	CPPUNIT_ASSERT_EQUAL(false, u->isUpdateDownloaded());

	ofstream versionFile("a_temporary_test_data_directory//version.txt");
	versionFile << "2000";
	versionFile.close();

	CPPUNIT_ASSERT_EQUAL(false, u->isUpdateDownloaded());

	ofstream descFile("a_temporary_test_data_directory//desc.txt");
	descFile << "best version ever";
	descFile.close();

	CPPUNIT_ASSERT_EQUAL(true, u->isUpdateDownloaded());

	remove("a_temporary_test_data_directory\\BumpTopInstaller.msi");
	remove("a_temporary_test_data_directory\\version.txt");
	remove("a_temporary_test_data_directory\\desc.txt");
	remove("a_temporary_test_data_directory");


}
Пример #16
0
int main(int argc, char *argv[])
{
    Application a(argc, argv);
    a.setAttribute(Qt::AA_DontShowIconsInMenus, true);
    a.setApplicationName("psnewmodel");
    a.setOrganizationName("LB Productions");
    a.setOrganizationDomain("lbproductions.github.com");
    a.setApplicationVersion(APP_VERSION);

#ifdef Q_OS_MAC
    CocoaInitializer cocoaInitializer;
    Q_UNUSED(cocoaInitializer);

    CrashReporter::init();
#endif

    Updater *updater = Updater::instanceForPlatform();
    if(updater)
        updater->checkForUpdatesInBackground();

    if(a.arguments().contains("-C")) {
        QSettings s;
        s.clear();
    }

    ChooseLibraryWidget *mainWindow = new ChooseLibraryWidget;
    if(a.fileToOpen().isEmpty()) {
        mainWindow->showOrOpenLibrary();
    }
    else {
        mainWindow->openLibrary(a.fileToOpen()+"/database/database.sqlite");
    }

    int ret = a.exec();

    Library::instance()->close();
    delete updater;

    return ret;
}
Пример #17
0
void SpawnerMgr::unload()
{
	LogError(LN, "Unloading the spawner conf");
	_lock.lock();
	std::list<Spawner*>::iterator ptr = _spawners.begin();
	Updater* updater = WorldMgr::get_singleton().get_updater();
	MapMgr* map_mgr = MapMgr::get_instance();
	for (; ptr != _spawners.end(); ++ptr)
	{
		Map* map = (*ptr)->get_map();//map_mgr->get_map((*ptr)->get_spawn_info()._map);
		if (map)
		{
			map->remove_unit(*ptr);
		}
		updater->remove(*ptr);
		delete (*ptr);
	}
	_spawners.clear();
	_smf_nodes.clear();
	_inited = false;
	_lock.unlock();
}
Пример #18
0
int main(){
    const char* path_new      = CS1_APPS"/new";
    const char* path_current  = CS1_APPS"/current";
    const char* path_old      = CS1_APPS"/old";
    const char* path_rollback = CS1_APPS"/rollback";
    const char* log_folder    = CS1_LOGS;

    Updater* updater = new Updater(path_new, path_current, path_old, path_rollback, log_folder);
    
    bool isSuccess = updater->StartUpdate();
    
    if (updater != NULL){
        delete updater;
        updater = NULL;
    }

    if (isSuccess == true){
        return 0;
    }else{
        return 1;
    }
}
Пример #19
0
void UpdaterTest::testVersionStringParsing()
{
	const int NUM_VERSIONS_STRING = 6;
	string versionStrings[NUM_VERSIONS_STRING] = 
	{
		"1", "abc", "-2", "234sc", "2", ""
	};

	int versions[NUM_VERSIONS_STRING] = 
	{
		1, -1, -2, 234, 2, -1
	};

	for (int i = 0; i < NUM_VERSIONS_STRING; i++)
	{
		string versionString = versionStrings[i];
		int version = versions[i];

		vector<string> versionStrings;
		versionStrings.push_back(versionString);
		UpdateServer *us = (UpdateServer*) new MockUpdateServer(versionStrings);


		CPPUNIT_ASSERT_EQUAL(versionString, us->getVersionString());

		Updater *u = new Updater(us, 0, ".", 0, 0, 0);
		if (version == -1)
			CPPUNIT_ASSERT_THROW(u->getNewestVersionNumber(), UpdateCheckFailedException);
		else
			CPPUNIT_ASSERT_EQUAL(version, u->getNewestVersionNumber());

		delete us;
		delete u;

	}



}
Пример #20
0
void UpdaterScheduler::slotTimerFired()
{
    ConfigFile cfg;

    // re-set the check interval if it changed in the config file meanwhile
    auto checkInterval = cfg.updateCheckInterval();
    if (checkInterval != _updateCheckTimer.interval()) {
        _updateCheckTimer.setInterval(checkInterval);
        qCInfo(lcUpdater) << "Setting new update check interval " << checkInterval;
    }

    // consider the skipUpdateCheck flag in the config.
    if (cfg.skipUpdateCheck()) {
        qCInfo(lcUpdater) << "Skipping update check because of config file";
        return;
    }

    Updater *updater = Updater::instance();
    if (updater) {
        updater->backgroundCheckForUpdate();
    }
}
Пример #21
0
int main()
{
#if 0
    DBG("test main\n");
    PCSTR olddir = "ver1001";
    PCSTR newdir = "ver1002";
    FileDiff fd;
    printf("olddir = %s\n",olddir);
    printf("newdir = %s\n",newdir);
    fd.setOldPathPrefix(olddir);
    fd.setNewPathPrefix(newdir);
    fd.listDir(olddir,0,OLD_VERSION);
    fd.listDir(newdir,0,NEW_VERSION);
    std::string diff_str = fd.diffFile();
    return 0;
#endif

#if 1
    MyHttp h("172.17.180.69",8888);
    h.establishConnection();
    std::string diff_str = h.test_send_recv();
    h.destroyConnection();

#endif

    Updater ud;
    PCSTR olddir_update = "android/ver1001";
    PCSTR newdir_update = "android/ver1002";
    PCSTR patchdir_update = "android/ver1002_patch";
    INT ret = ud.doUpdate(diff_str,olddir_update,newdir_update,patchdir_update);
    if(ret == BAV_OK) {
        DBG("\nUpdate complete.\n");
    }
    else {
        DBG("\nUpdate failed.\n");
    }
    return 0;
}
Пример #22
0
int WINAPI WinMain(HINSTANCE inst, HINSTANCE prev, LPSTR cmdline, int show) {
	TCHAR exePath[MAX_PATH];
	char filepath[MAX_PATH];
	if (Util::ProcessCount("update.exe") <= 1) {
		Updater* pUpdater = new Updater();
		GetModuleFileName(NULL, exePath, MAX_PATH);
		(strrchr(exePath, '\\'))[0] = 0;
		sprintf(filepath, "%s\\config.txt", exePath);
		sprintf(exePath, "%s\\", exePath);
		pUpdater->SetPath(exePath);
		Properties properties;
		properties.SafeLoad(filepath);
		pUpdater->SetHost(properties.GetString("host", "192.168.1.115"));
		pUpdater->SetIpPort(properties.GetInteger("port", 8888));
		pUpdater->SetInterval(
				properties.GetInteger("interval", 1000 * 60 * 30));
		pUpdater->SetUrl(properties.GetString("url", "/bank/client"));
		pUpdater->SetApplication("terminal.exe");
		void* handle = ThreadCreator::StartThread(pUpdater);
		WaitForSingleObject(handle, INFINITE);
	}
	return 0;
}
Пример #23
0
void SerialLineIn::begin(Updater& up)
{
  up.add(this);
}
Пример #24
0
void PinTimer::begin(Updater& up,Connectable* who) 
{ 
  PinControl::begin(who);
  up.add(this);
}
Пример #25
0
void Application::slotStartUpdateDetector()
{
    Updater *updater = Updater::instance();
    updater->backgroundCheckForUpdate();
}
Пример #26
0
int main(int argc, char *argv[])
{
    QCoreApplication app(argc, argv);

    QCommandLineParser parser;
    parser.setApplicationDescription(QCoreApplication::tr("manage a local repository (check for updates, update, check integrity)"));
    parser.addHelpOption();
    parser.addVersionOption();

    QCommandLineOption checkonly(QStringList() << "c" << "checkonly"
         , QCoreApplication::tr("Only check for updates."));

    QCommandLineOption verbose(QStringList() << "verbose"
         , QCoreApplication::tr("Run in verbose mode."));

    QCommandLineOption force(QStringList() << "f" << "force"
         , QCoreApplication::tr("Force integrity checks if the local repository is uptodate."));

    QCommandLineOption tmpDirectoryPath(QStringList() << "t" << "tmp"
         , QCoreApplication::tr("Path to use for temporary files.")
         , "tmp_directory");

    parser.addOption(checkonly);
    parser.addOption(force);
    parser.addOption(tmpDirectoryPath);
    parser.addOption(verbose);
    parser.addPositionalArgument("local_repository", QCoreApplication::tr("Path to the local repository."), "<local_repository>");
    parser.addPositionalArgument("remote_repository", QCoreApplication::tr("Path to the remote repository."), "<remote_repository>");
    parser.addPositionalArgument("username", QCoreApplication::tr("Username for the remote repository."), "[<username>");
    parser.addPositionalArgument("password", QCoreApplication::tr("Password for the remote repository."), "<password>]");
    parser.process(app);

    QLoggingCategory::setFilterRules(QStringLiteral("updatesystem.*.debug=%1").arg(parser.isSet(verbose) ? "true" : "false"));

    const QStringList args = parser.positionalArguments();
    if(args.size() < 1)
        qWarning() << "Error : local_repository argument is missing";
    else if(args.size() < 2)
        qWarning() << "Error : remote_repository argument is missing";
    else if(args.size() > 2 && args.size() < 4)
        qWarning() << "Error : password argument is missing";
    else if(args.size() > 4)
        qWarning() << "Error : too much arguments";
    else
    {
        Updater updater;
        updater.setLocalRepository(args[0]);
        updater.setRemoteRepository(args[1]);

        if(parser.isSet(tmpDirectoryPath))
            updater.setTmpDirectory(parser.value(tmpDirectoryPath));

        if(args.size() == 4)
            updater.setCredentials(args[2], args[3]);

        if(parser.isSet(checkonly))
        {
            updater.checkForUpdates();
            QEventLoop loop;
            QObject::connect(&updater, &Updater::checkForUpdatesFinished, &loop, &QEventLoop::quit);
            loop.exec();

            if(!updater.errorString().isEmpty())
            {
                fprintf(stderr, "Failure : %s\n", qPrintable(updater.errorString()));
                return 2;
            }

            if(updater.isUpdateAvailable())
            {
                printf("An update is available\n");
            }
            else
            {
                printf("Already up-to-date\n");
            }
        }
        else
        {
            updater.checkForUpdates();
            QEventLoop loop;
            QObject::connect(&updater, &Updater::checkForUpdatesFinished, &loop, &QEventLoop::quit);
            loop.exec();

            printf("Checking for updates...\n");
            if(!updater.errorString().isEmpty())
            {
                fprintf(stderr, "Failure : %s\n", qPrintable(updater.errorString()));
            }
            else if(updater.isUpdateAvailable() || parser.isSet(force))
            {
                printf("Updating...\n");
                printf("Download   0%%, Apply   0%%");
                fflush(stdout);
                updater.update();
                QObject::connect(&updater, &Updater::updateFinished, &loop, &QEventLoop::quit);
                qint64 downloaded = 0, applied = 0;
                QObject::connect(&updater, &Updater::updateDownloadProgress, [&downloaded, &applied](qint64 bytesReceived, qint64 bytesTotal) {
                    downloaded = (bytesReceived*100)/bytesTotal;
                    printf("\rDownload %3lld%%, Apply %3lld%%", downloaded, applied);
                    fflush(stdout);
                });
                QObject::connect(&updater, &Updater::updateApplyProgress, [&downloaded, &applied](qint64 bytesReceived, qint64 bytesTotal) {
                    applied = (bytesReceived*100)/bytesTotal;
                    printf("\rDownload %3lld%%, Apply %3lld%%", downloaded, applied);
                    fflush(stdout);
                });
                loop.exec();

                if(updater.state() != Updater::Uptodate)
                {
                    fprintf(stderr, "Failure : %s\n", qPrintable(updater.errorString()));
                    return 2;
                }

                printf("\nUpdated\n");
            }
            else
            {
                printf("Already up-to-date\n");
            }
        }

        return 0;
    }

    parser.showHelp(1);

    return 1;
}
Пример #27
0
int main(int argc, char** argv) {

#ifdef OMP1
    cout << "OPENMP SIMULATION" << endl;
#endif

#ifdef ENABLE_MPI
    cout << "MPI SIMULATION" << endl;
#endif

    FILE *infile,*outfile,*mov;       // Handle for writing configuration

    Sim sim;                  // Should contain the simulation options.
    Conf conf;                // Should contain fast changing particle and box(?) information
    FileNames files;

    Updater* updater; // need to get an instance of updater after initialization, because of initFCE

    sim.wl.setConf(&conf);

    cout << "\nPatchy Spherocylinders version 3.6\n"
         << "-------------------------------------" << endl;

#ifdef EXTRA_HYDROPHOBIC_ALL_BODY_ATTRACTION
    cout << "\n!!! Extra hydrophobic interaction in e_cpsc_cpsc added\n" << endl;
#endif


    /********************************************************/
    /*                  INITIALIZATION                      */
    /********************************************************/

    Inicializer init(&sim, &conf, &files);

    init.initWriteFiles();
    init.initMPI(argc,argv);
    init.readOptions();
    init.initTop(); // here particleStore filled in setParticleParams
    init.testChains(); // if no chains -> move probability of chains 0

    cout << "\nReading configuration...\n";
    if(init.poolConfig) {
        infile = fopen(files.configurationPool, "r");
        if (infile == NULL) {
            fprintf (stderr, "\nERROR: Could not open %s file.\n\n", files.configurationPool);
            exit (1);
        }
        init.initConfig(&infile, conf.pool);
        fclose (infile);
    }
    infile = fopen(files.configurationInFile, "r");
    if (infile == NULL) {
        fprintf (stderr, "\nERROR: Could not open %s file.\n\n", files.configurationInFile);
        exit (1);
    }
    init.initConfig(&infile, conf.pvec);
    conf.geo.info();
    fclose (infile);

    cout << "Equilibration of maximum step sizes: " << sim.nequil/2 << " sweeps" << endl;

    if ( sim.wl.wlm[0] > 0 ) {
        outfile = fopen(files.wlinfile, "r");
        if (outfile == NULL) {
            printf ("ERROR: Cannot open file for Wang-Landau method (%s).\n",files.wlinfile);
            sim.~Sim(); topo.~Topo(); conf.~Conf();
            exit(1);
        }
        fclose (outfile);
    }

    // Empty movie file
    mov = fopen("movie", "w");
    fclose (mov);

    if (sim.pairlist_update) {
        init.initNeighborList();
        conf.pairlist_update = true;
    }

    updater = new Updater(&sim, &conf, &files);

    /********************************************************/
    /*                  ANALYZE                             */
    /********************************************************/

    /*double r1, r2, fi, a=0.0, b=0.0, c=0.0;
    double aver1=0.0, aver2=0.0;
    vector<double> array1;
    vector<double> array2;
    double s1=0.0, s2=0.0;
    int N = 0, mid=0, mid2=0;

    infile = fopen("movieAll4", "r");
    if (infile == NULL) {
        fprintf (stderr, "\nERROR: Could not open %s file.\n\n", "movieAll");
        exit (1);
    }
    char * line;
    size_t line_size = (STRLEN + 1) * sizeof(char);
    for(int i=0; i<200; i++) {
        init.initConfig(&infile, conf.pvec);
        analyzeCur(r1, r2, fi, &conf, mid, mid2);
        if(r1 > r2-0.1 && r1 < r2+0.1) {
            cout << r1 << " " << r2 << " " << fi << endl;
            aver1 += r1;
            aver2 += r2;
            N++;
            array1.push_back(r1);
            array2.push_back(r2);
            cout << mid <<" "<< mid2 << endl;
        }

        a += r1;
        b += r2;
        c += fi;
    }
    aver1 /= N;
    aver2 /= N;
    for(unsigned int w=0; w<array1.size(); w++) {
        s1 += (aver1 - array1[w])*(aver1 - array1[w]);
        s2 += (aver2 - array2[w])*(aver2 - array2[w]);

    }
    s1 /= N; s1 = sqrt(s1);
    s2 /= N; s2 = sqrt(s2);

    cout << "N= " << N << endl;
    cout << "r1="<< aver1 << ", s1= " << s1 << ", r2= " << aver2 << ", s2= " << s2 << endl;
    cout << "H= " << 1/aver1 - 1/aver2 << ", s= " << s1*s1/(aver1*aver1) + s2*s2/(aver2*aver2) << endl;
    cout << "K= " << 1/aver1 * 1/aver2 * (-1.0) << ", s= " << 1/(aver1*aver2) * (s1*s1/aver1 + s2*s2/aver2) << endl;
    fclose (infile);
    exit(1);*/

    /********************************************************/
    /*                  EQUILIBRATION                       */
    /********************************************************/

    if (sim.nequil) {
        printf("\nStart equilibration...\n");

        updater->simulate(sim.nequil/2, sim.adjust, 0, 0);
        updater->simulate(sim.nequil/2, 0,          0, 0);

        sim.printEqStat();

        cout << "Further equilibration of configuration:  " << sim.nequil/2 <<  " sweeps" << endl;

        outfile = fopen("config.eq", "w");
        fprintf (outfile, "%15.8e %15.8e %15.8e\n", conf.geo.box.x, conf.geo.box.y, conf.geo.box.z);
        conf.draw(outfile);
        fclose (outfile);

        printf ("   Equilibrated configuration written to config.eq\n");
        printf ("   Box dimensions: %.10f, %.10f, %.10f\n\n", conf.geo.box.x, conf.geo.box.y, conf.geo.box.z);
    }

    /********************************************************/
    /*                  PRODUCTION RUN                      */
    /********************************************************/

    cout << "Production run:  "<< sim.nsweeps << " sweeps\n" << endl;

    updater->simulate(sim.nsweeps, 0, sim.paramfrq, sim.report);

#ifdef ENABLE_MPI
        printf ("   MPI replica changeT / changeP / acceptance ratio: \t %.6f   /   %.6f  /  %.6f\n\n", sim.mpiexch.mx,sim.mpiexch.angle,RATIO(sim.mpiexch));
#endif

    outfile = fopen(files.configurationoutfile, "w");
#ifdef TESTING
    fprintf (outfile, "%15.6e %15.6e %15.6e\n", conf.geo.box.x, conf.geo.box.y, conf.geo.box.z);
#else
    fprintf (outfile, "%15.8e %15.8e %15.8e\n", conf.geo.box.x, conf.geo.box.y, conf.geo.box.z);
#endif
    conf.draw (outfile);
    fclose (outfile);

    if(sim.nGrandCanon != 0) {
        FILE* inFile = fopen(files.topologyInFile, "r");
        outfile = fopen(files.topologyOutFile, "w");

        char line[128];

        while(strncmp(line, "[System]", 8) != 0) {
            if(fgets(line,127, inFile) == NULL ) {
                printf("Error writing Topology [System] not found\n");
                break;
            }
            fputs(line, outfile);
        }
        for(int i=0; i < conf.pvec.molTypeCount; i++)
            fprintf(outfile, "%s %d\n", topo.moleculeParam[i].name, conf.pvec.molCountOfType(i));

        fclose (outfile);
        fclose (inFile);
    }

    /// For testing the pairlist
    //gen_pairlist(&topo, &sim, &conf);
    //FILE * fpairlist;
    //fpairlist = fopen("pairlist.dat", "w");
    //print_pairlist(fpairlist, &sim, &topo);
    //fclose(fpairlist);
    //printf("sqmaxcut = %f\n", topo.sqmaxcut);

    /// For testing the cluster algorithm
    //gen_clusterlist(&topo, &sim, &conf);
    //print_clusterlist(stdout, TRUE, &topo, &sim, &conf);
    //sort_clusterlist(&topo, &sim);
    //print_clusters(stdout, TRUE, &sim);
    //print_clusterstat(stdout, TRUE, &sim);

    /********************************************************/
    /*                   MEMORY DEALLOC                     */
    /********************************************************/

    //sim.~Sim(); topo.~Topo(); conf.~Conf(); // note: called automatically at end of main

#ifdef ENABLE_MPI
    MPI_Finalize();
#endif

    printf ("\nDone\n\n");

    return 0;
}
Пример #28
0
void RtcEvTable::begin(Updater& up)
{
  up.add(this);
  begin();
}
Пример #29
0
void UpdaterTest::testSendingUpdateMessageToBumpTop()
{
	// start up an instance of bumptop
	STARTUPINFO si;
	PROCESS_INFORMATION pi;

	ZeroMemory( &si, sizeof(si) );
	si.cb = sizeof(si);
	ZeroMemory( &pi, sizeof(pi) );

#ifdef DEBUG
	path bumptopDirPath = current_path().branch_path() / path("Source/Debug", native);
#else
	path bumptopDirPath = current_path().branch_path() / path("Source/Release", native);
#endif

	path bumptopPath = bumptopDirPath / path("BumpTop.exe");


	// Start the child process. 
	if( !CreateProcess( NULL,   // No module name (use command line)
		(LPSTR) bumptopPath.native_file_string().c_str(),        // Command line
		NULL,           // Process handle not inheritable
		NULL,           // Thread handle not inheritable
		FALSE,          // Set handle inheritance to FALSE
		0,              // No creation flags
		NULL,           // Use parent's environment block
		(LPSTR) bumptopDirPath.native_directory_string().c_str(),           // Use parent's starting directory 
		&si,            // Pointer to STARTUPINFO structure
		&pi )           // Pointer to PROCESS_INFORMATION structure
		) 
	{
		ostringstream error_message;
		error_message << "CreateProcess failed (" <<  GetLastError() << ")\n";
		CPPUNIT_ASSERT_MESSAGE(error_message.str(), false);
	}

	Sleep(500);

	
	// Search for BumpTop window
	bool foundBumptopWindow = false;
	HWND bumptopHwnd = 0;

	for (int i = 0; i < 50; i++)
	{
		
		CWindowIterator cwi(1000);
		for (HWND hwnd = cwi.First(); hwnd; hwnd=cwi.Next())
		{
			if ((GetWindowLong(hwnd,GWL_STYLE) & WS_VISIBLE)) {
				DWORD pidwin;
				GetWindowThreadProcessId(hwnd, &pidwin);
				TCHAR classnameBuffer[MAX_PATH+1];
				GetClassName(hwnd, classnameBuffer, MAX_PATH);
				TCHAR titleBuffer[MAX_PATH+1];
				GetWindowText(hwnd, titleBuffer, MAX_PATH);
				
				if (pidwin==pi.dwProcessId && string(classnameBuffer) == string("BumpTop") && string(titleBuffer) == string("BumpTop"))
				{
					foundBumptopWindow = true;
					bumptopHwnd = hwnd;
					break;
				}
			}
		}
		if (foundBumptopWindow)
			break;

		Sleep(100); // give the window a little time to start

	}
	
	
	CPPUNIT_ASSERT_MESSAGE("Testing if we found the BumpTop window", foundBumptopWindow);

	Sleep(500);
	vector<string> versionStrings;
	versionStrings.push_back("800");
	MockUpdateServer *mus = new MockUpdateServer(versionStrings);
	Updater *u = new Updater(mus, 99, ".", 0, 0, bumptopHwnd);
	int updateDownloadedMessageResponse = u->sendUpdateDownloadedMessageToBumpTop(true);

	SendMessageTimeout(bumptopHwnd, WM_CLOSE, 0, 0, SMTO_NORMAL, 1000, NULL);
	
	CloseHandle(pi.hProcess);
	CloseHandle(pi.hThread);

	CPPUNIT_ASSERT_EQUAL(3, updateDownloadedMessageResponse);

}
Пример #30
0
	void operator()() {
		m_updater->Run();
	}