Пример #1
0
TranslationUnitUpdater Document::createUpdater() const
{
    TranslationUnit unit = translationUnit();

    const TranslationUnitUpdateInput updateInput = createUpdateInput();
    TranslationUnitUpdater updater(unit.id(),
                                   unit.cxIndex(),
                                   unit.cxTranslationUnit(),
                                   updateInput);

    return updater;
}
Пример #2
0
void
MediaWindow::UpdateOutputListItem(MediaListItem::media_type type,
	const dormant_node_info* node)
{
	NodeListItem compareTo(node, type);
	NodeListItemUpdater updater(&compareTo, &NodeListItem::SetDefaultOutput);
	for (int32 i = 0; i < fListView->CountItems(); i++) {
		MediaListItem* item = static_cast<MediaListItem*>(fListView->ItemAt(i));
		item->Accept(updater);
	}
	fListView->Invalidate();
}
    static void NO_INLINE execute(const Source & data, size_t num_threads, std::vector<std::unique_ptr<Map>> & results,
                        Creator && creator, Updater && updater,
                        ThreadPool & pool)
    {
        results.reserve(num_threads);
        for (size_t i = 0; i < num_threads; ++i)
            results.emplace_back(new Map);

        for (size_t i = 0; i < num_threads; ++i)
        {
            auto begin = data.begin() + (data.size() * i) / num_threads;
            auto end = data.begin() + (data.size() * (i + 1)) / num_threads;
            auto & map = *results[i];

            pool.schedule([&, begin, end]()
            {
                typename Map::iterator place;
                Key prev_key {};
                for (auto it = begin; it != end; ++it)
                {
                    if (it != begin && *it == prev_key)
                    {
                        updater(place->second);
                        continue;
                    }
                    prev_key = *it;

                    bool inserted;
                    map.emplace(*it, place, inserted);

                    if (inserted)
                        creator(place->second);
                    else
                        updater(place->second);
                }
            });
        }

        pool.wait();
    }
Пример #4
0
bool frmSpr::eventFilter(QObject *obj, QEvent *event){
    if (event->type() == QEvent::KeyPress){
        QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event);
        // Обработка нажатия enter или return
        if (keyEvent->key() == Qt::Key_Enter || keyEvent->key() == Qt::Key_Return){
            if(ui->sprTable->model() != 0)
                updater(ui->sprTable->currentIndex(),ui->sprTable->model()->rowCount(),obj);
        }
        // Обработка нажатия Insert
        if (keyEvent->key() == Qt::Key_Insert)
            if(ui->sprTable->model() != 0)
                on_add_usluga_clicked();
    }
}
Пример #5
0
int main(int argc, char *argv[])
{
    QApplication app(argc, argv);

    QQmlApplicationEngine engine;

    engine.rootContext()->setContextProperty( "timer", NULL );

    engine.load(QUrl(QStringLiteral("qrc:/main.qml")));

    ConextPropertyUpdater updater( &engine );

    return app.exec();
}
Пример #6
0
// TODO: Pass the event object around instead of keeping a global one
void Mouse_Pressed() {
	if(had_text_freeze > 0) {
		had_text_freeze--;
		return;
	}
	
	if(overall_mode != MODE_STARTUP) {
		location mousePos(event.mouseButton.x, event.mouseButton.y);
		volatile bool doneScrolling = false;
		if(mousePos.in(text_sbar->getBounds())) {
			mainPtr.setActive(false);
			boost::thread updater(std::bind(handleUpdateWhileScrolling, std::ref(doneScrolling), REFRESH_TRANS));
			text_sbar->handleClick(mousePos);
			doneScrolling = true;
			updater.join();
			redraw_screen(REFRESH_TRANS);
		} else if(mousePos.in(item_sbar->getBounds())) {
			mainPtr.setActive(false);
			boost::thread updater(std::bind(handleUpdateWhileScrolling, std::ref(doneScrolling), REFRESH_INVEN));
			item_sbar->handleClick(mousePos);
			doneScrolling = true;
			updater.join();
			redraw_screen(REFRESH_INVEN);
		} else if(overall_mode == MODE_SHOPPING && mousePos.in(shop_sbar->getBounds())) {
			mainPtr.setActive(false);
			boost::thread updater(std::bind(handleUpdateWhileScrolling, std::ref(doneScrolling), REFRESH_DLOG));
			shop_sbar->handleClick(mousePos);
			doneScrolling = true;
			updater.join();
			redraw_screen(REFRESH_DLOG);
		} else All_Done = handle_action(event);
	} else All_Done = handle_startup_press({event.mouseButton.x, event.mouseButton.y});
	
	menu_activate();
	
}
void KisQueuesProgressUpdaterTest::testFastProgress()
{
    /**
     * If the progress is too fast we don't even touch the bar
     */

    TestUtil::TestProgressBar progressProxy;
    KisQueuesProgressUpdater updater(&progressProxy);

    updater.updateProgress(200, "test task");
    updater.updateProgress(0, "test task");

    QTest::qWait(20);

    QCOMPARE(progressProxy.min(), 0);
    QCOMPARE(progressProxy.max(), 0);
    QCOMPARE(progressProxy.value(), 0);
    QCOMPARE(progressProxy.format(), QString());

    updater.updateProgress(100, "test task");
    updater.updateProgress(0, "test task");

    QTest::qWait(20);

    QCOMPARE(progressProxy.min(), 0);
    QCOMPARE(progressProxy.max(), 0);
    QCOMPARE(progressProxy.value(), 0);
    QCOMPARE(progressProxy.format(), QString());

    updater.updateProgress(0, "test task");
    updater.updateProgress(0, "test task");

    QTest::qWait(20);

    QCOMPARE(progressProxy.min(), 0);
    QCOMPARE(progressProxy.max(), 0);
    QCOMPARE(progressProxy.value(), 0);
    QCOMPARE(progressProxy.format(), QString());

    QTest::qWait(500);

    QCOMPARE(progressProxy.min(), 0);
    QCOMPARE(progressProxy.max(), 0);
    QCOMPARE(progressProxy.value(), 0);
    QCOMPARE(progressProxy.format(), QString());
}
      //
      // publish
      //
      int WindowsProcessorProbe_Bridge::
      publish (const ::OASIS::DAC::Data_Packet & packet)
      {
        // Extract the base contents of the packet.
        OASIS::Software_Probe_Header probe;
        probe.recall (packet.probe_data (),
                      packet.probe_data_length (),
                      packet.byte_order ());

        // Locate the servant for this software probe instance.
        ServantPtr_Map::const_iterator iter =
          this->servants_.find (probe.name_);

        if (iter == this->servants_.end ())
          ACE_ERROR_RETURN ((LM_ERROR,
                             ACE_TEXT ("%T (%t) - %M - servant does not exist for %s\n"),
                             probe.name_.c_str ()),
                             -1);

        // Locate the probe in the mapping.
        ::OASIS::System::Processor::WindowsProcessorProbe::ServantPtr servant = iter->second;

        if (!servant.isValid ())
          ACE_ERROR_RETURN ((LM_ERROR,
                             ACE_TEXT ("%T (%t) - %M - invalid servant for %s\n"),
                             probe.name_.c_str ()),
                             -1);

        // Instantiate a new updater.
        std::auto_ptr < ::OASIS::System::Processor::WindowsProcessorProbe::PublicationStateUpdater >
          updater (servant->createUpdater ());

        // Update the servant values.
        Software_Probe_Data_Preparer prep (packet.probe_data (),
                                           packet.probe_data_length ());
        ACE_InputCDR input (prep.message_block (),
                            packet.byte_order ());

        if (0 != this->update (*updater, input))
          return -1;

        // We are now ready to commit the updater.
        servant->commitUpdater (updater);
        return 0;
      }
Пример #9
0
Window::Window(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::Window)
{
    ui->setupUi(this);
    scene = new Visual(0);
    scene2 = new Visual(0);
    ui->graphicsView->setScene(scene);
    ui->graphicsView_2->setScene(scene2);
    ui->graphicsView->setFocusPolicy(Qt::WheelFocus);
    ui->graphicsView->setFocus(Qt::OtherFocusReason);
    game.startGame(1,scene,scene2);
    timer = new QTimer(this);
    connect(timer, SIGNAL(timeout()), this,SLOT(updater()));
    timer->start(30);
    timer = new QTimer(this);
    connect(timer, SIGNAL(timeout()), this,SLOT(updater2()));
    timer->start(30);
}
Пример #10
0
void TrackList::UpdatePendingTracks()
{
   auto pUpdater = mUpdaters.begin();
   for (const auto &pendingTrack : mPendingUpdates) {
      // Copy just a part of the track state, according to the update
      // function
      const auto &updater = *pUpdater;
      auto src = FindById( pendingTrack->GetId() );
      if (pendingTrack && src) {
         if (updater)
            updater( *pendingTrack, *src );
         pendingTrack->DoSetY(src->GetY());
         pendingTrack->DoSetHeight(src->GetActualHeight());
         pendingTrack->DoSetMinimized(src->GetMinimized());
         pendingTrack->DoSetLinked(src->GetLinked());
      }
      ++pUpdater;
   }
}
Пример #11
0
void CManageVariableDlg::OnBnClickedRename()
{
	int nItem = m_List.GetSelectionMark();
	if (nItem == -1)
		return;

	CAddVariableDlg Dlg;
	CString oldName = Dlg.Name = m_List.GetItemText(nItem, 0);
	Dlg.Type = GetNameType(m_List.GetItemText(nItem, 1));
	Dlg.Value = m_List.GetItemText(nItem, 2);

	Dlg.Caption = "Construct : Edit private variable";

	if (Dlg.DoModal() == IDOK) {

		if (Dlg.Name != oldName && VariableNameExists(Dlg.Name))
			MessageBox(CString("The private variable name '") + Dlg.Name + "' already exists.  Please choose a unique name.", "Private variables", MB_OK | MB_ICONEXCLAMATION);

		else
		{
			m_List.SetItemText(nItem, 0, Dlg.Name);
			m_List.SetItemText(nItem, 1, GetTypeName(Dlg.Type));
			m_List.SetItemText(nItem, 2, Dlg.Value);

			vector<PrivateValue>::iterator v = find(pType->m_PrivateValues.begin(), pType->m_PrivateValues.end(), oldName);

			// If renamed, update
			if (Dlg.Name != oldName)
				(*v).name = Dlg.Name;
			(*v).type = Dlg.Type;

			// Value changed - update across all instances
			if (Dlg.Value != "") 
			{
				// Iterate and update all objects
				int index = find_index(pType->m_PrivateValues.begin(), pType->m_PrivateValues.end(), Dlg.Name);

				PrivateVariableValueUpdater updater(index, Dlg.Value);
				ForEachObjectInstance(pType, layout->application, updater);
			}
		}
	}
}
Пример #12
0
int main (int argc, char **argv) {
  std::ifstream ifs("japanese_sentences.txt");
  std::string line;
  std::vector<std::string> sentences;
  while (std::getline(ifs, line)) {
    sentences.push_back(line);
    if (sentences.size() == 10000) {
      break;
    }
  }

  MeCab::Model *model = MeCab::createModel(argc, argv);
  if (!model) {
    std::cerr << "model is NULL" << std::endl;
    return -1;
  }
  MeCab::ModelUpdater updater(model);
  updater.start();

  const int kMaxThreadSize = 8;

  std::vector<MeCab::TaggerThread *> threads(kMaxThreadSize);
  for (int i = 0; i < kMaxThreadSize; ++i) {
    threads[i] = new MeCab::TaggerThread(&sentences, model, i);
  }

  for (int i = 0; i < kMaxThreadSize; ++i) {
    threads[i]->start();
  }

  for (int i = 0; i < kMaxThreadSize; ++i) {
    threads[i]->join();
    delete threads[i];
  }

  updater.join();
   
  delete model;

  return 0;
}
Пример #13
0
void MainWindow::UserInfoChanged()
{
  ChannelTreeWidget::RemoteChannelUpdater updater(channelTree);
  clientMutex.lock();

  int useridx;
  for (useridx = 0; useridx < client.GetNumUsers(); useridx++) {
    const char *name = client.GetUserState(useridx, NULL, NULL, NULL);
    updater.addUser(useridx, QString::fromUtf8(name));

    int channelidx;
    for (channelidx = 0; client.EnumUserChannels(useridx, channelidx) != -1; channelidx++) {
      bool mute;
      name = client.GetUserChannelState(useridx, channelidx, NULL, NULL, NULL, &mute, NULL);
      updater.addChannel(channelidx, QString::fromUtf8(name), mute);
    }
  }

  clientMutex.unlock();
  updater.commit();
}
Пример #14
0
int main(int argc, const char * argv[])
{
	if (argc > 3)
	{
		TransLoader loader(argv[1]);
		if (!loader.load())
		{
			std::cout << "error loading trans file " << argv[1] << "\n";
		}
		XliffUpdater updater(loader, argv[2], argv[3]);
		if (!updater.update())
		{
			std::cout << "error updating xliff " << argv[2] << " to " << argv[3] << "\n";
		}
	}
	else
	{
		std::cout << "Usage: MacTrans <Trans Filename> <English Xliff Filename> <Trans Xliff Filename>\n";
	}
	return 0;
}
Пример #15
0
void YaDayUse::dayUse()
{
	PsiLogger::instance()->log("YaDayUse::dayUse()");
	int timeout = 86400;
#ifdef YAPSI_ACTIVEX_SERVER
	QAxObject updater("Yandex.YandexUpdater");
	updater.dynamicCall("PingStat(const QString&, const QString&, const QString&)",
	                    YaDayUse::appId(),
	                    YaDayUse::basePingUrl(),
	                    QString::number(timeout));
#else
	QString url = QString("%1?yasoft=%2&ui=%3&ver=%4&os=%5&osver=%6")
	              .arg(basePingUrl())
	              .arg(appId())
	              .arg(ui())
	              .arg(ver())
	              .arg(osId())
	              .arg(osVer());

	httpGet(url);
#endif
	QTimer::singleShot(timeout * 1000, this, SLOT(dayUse()));
}
Пример #16
0
int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    // set these values so we can use default settings constructor
    QCoreApplication::setOrganizationName("Motrs INC");
    QCoreApplication::setOrganizationDomain("motrs.superjoesoftware.com");
    QCoreApplication::setApplicationName("Motrs Game Editor");

    // move updater.exe.new to updater.exe
    QDir appDir(QApplication::applicationDirPath());
    QFile updater(appDir.absoluteFilePath("updater.exe.new"));
    if( updater.exists() ) {
        // delete updater.exe
        appDir.remove("updater.exe");
        // rename updater.exe.new to updater.exe
        updater.rename("updater.exe");
    }

    WorldEditor w;
    w.show();
    return a.exec();
}
Пример #17
0
void
TextUpdater::Run(nsDocAccessible* aDocument, nsTextAccessible* aTextLeaf,
                 const nsAString& aNewText)
{
  NS_ASSERTION(aTextLeaf, "No text leaf accessible?");

  const nsString& oldText = aTextLeaf->Text();
  PRUint32 oldLen = oldText.Length(), newLen = aNewText.Length();
  PRUint32 minLen = NS_MIN(oldLen, newLen);

  // Skip coinciding begin substrings.
  PRUint32 skipStart = 0;
  for (; skipStart < minLen; skipStart++) {
    if (aNewText[skipStart] != oldText[skipStart])
      break;
  }

  // The text was changed. Do update.
  if (skipStart != minLen || oldLen != newLen) {
    TextUpdater updater(aDocument, aTextLeaf);
    updater.DoUpdate(aNewText, oldText, skipStart);
  }
}
Пример #18
0
void KisThreadedApplicatorTest::testApplication()
{
    const KoColorSpace * colorSpace = KoColorSpaceRegistry::instance()->rgb8();
    TestJobFactory factory;
    TestUtil::TestProgressBar bar;
    KoProgressUpdater updater(&bar);
    KisPaintDeviceSP test = new KisPaintDevice(colorSpace);

    quint8 *bytes = test->colorSpace()->allocPixelBuffer(1);
    memset(bytes, 128, test->colorSpace()->pixelSize());
    test->fill(0, 0, 1000, 1000, bytes);

    KisThreadedApplicator applicator(test, QRect(0, 0, 1000, 1000), &factory, &updater);
    applicator.execute();

    KisRectConstIteratorPixel it = test->createRectConstIterator(0, 0, 1000, 1000);
    while (!it.isDone()) {
        QCOMPARE((int)it.rawData()[0], (int)255);
        QCOMPARE((int)it.rawData()[1], (int)255);
        QCOMPARE((int)it.rawData()[2], (int)255);
        QCOMPARE((int)it.rawData()[3], (int)255);
        ++it;
    }
}
Пример #19
0
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE, LPSTR, int)
{
	LPTSTR cmdLine = ::GetCommandLine();
	ParamVector params;
	parseCommandLine(cmdLine, params);

	MiniDumper mdump;	//for debugging purposes.

	bool TheFirstOne = true;
	::SetLastError(NO_ERROR);
	::CreateMutex(NULL, false, TEXT("nppInstance"));
	if (::GetLastError() == ERROR_ALREADY_EXISTS)
		TheFirstOne = false;

	bool isParamePresent;
	bool showHelp = isInList(FLAG_HELP, params);
	bool isMultiInst = isInList(FLAG_MULTI_INSTANCE, params);
	
	CmdLineParams cmdLineParams;
	cmdLineParams._isNoTab = isInList(FLAG_NOTABBAR, params);
	cmdLineParams._isNoPlugin = isInList(FLAG_NO_PLUGIN, params);
	cmdLineParams._isReadOnly = isInList(FLAG_READONLY, params);
	cmdLineParams._isNoSession = isInList(FLAG_NOSESSION, params);
	cmdLineParams._isPreLaunch = isInList(FLAG_SYSTRAY, params);
	cmdLineParams._alwaysOnTop = isInList(FLAG_ALWAYS_ON_TOP, params);
	cmdLineParams._showLoadingTime = isInList(FLAG_LOADINGTIME, params);
	cmdLineParams._isSessionFile = isInList(FLAG_OPENSESSIONFILE, params);
	cmdLineParams._isRecursive = isInList(FLAG_RECURSIVE, params);
	cmdLineParams._langType = getLangTypeFromParam(params);
	cmdLineParams._localizationPath = getLocalizationPathFromParam(params);
	cmdLineParams._line2go = getNumberFromParam('n', params, isParamePresent);
    cmdLineParams._column2go = getNumberFromParam('c', params, isParamePresent);
	cmdLineParams._point.x = getNumberFromParam('x', params, cmdLineParams._isPointXValid);
	cmdLineParams._point.y = getNumberFromParam('y', params, cmdLineParams._isPointYValid);
	
	if (showHelp)
	{
		::MessageBox(NULL, COMMAND_ARG_HELP, TEXT("Notepad++ Command Argument Help"), MB_OK);
	}

	NppParameters *pNppParameters = NppParameters::getInstance();
	
	if (cmdLineParams._localizationPath != TEXT(""))
	{
		pNppParameters->setStartWithLocFileName(cmdLineParams._localizationPath);
	}
	pNppParameters->load();

	// override the settings if notepad style is present
	if (pNppParameters->asNotepadStyle())
	{
		isMultiInst = true;
		cmdLineParams._isNoTab = true;
		cmdLineParams._isNoSession = true;
	}

	// override the settings if multiInst is choosen by user in the preference dialog
	const NppGUI & nppGUI = pNppParameters->getNppGUI();
	if (nppGUI._multiInstSetting == multiInst)
	{
		isMultiInst = true;
		// Only the first launch remembers the session
		if (!TheFirstOne)
			cmdLineParams._isNoSession = true;
	}

	generic_string quotFileName = TEXT("");
    // tell the running instance the FULL path to the new files to load
	size_t nrFilesToOpen = params.size();
	const TCHAR * currentFile;
	TCHAR fullFileName[MAX_PATH];

	for(size_t i = 0; i < nrFilesToOpen; ++i)
	{
		currentFile = params.at(i);
		if (currentFile[0])
		{
			//check if relative or full path. Relative paths dont have a colon for driveletter
			BOOL isRelative = ::PathIsRelative(currentFile);
			quotFileName += TEXT("\"");
			if (isRelative)
			{
				::GetFullPathName(currentFile, MAX_PATH, fullFileName, NULL);
				quotFileName += fullFileName;
			}
			else
			{
				if ((currentFile[0] == '\\' && currentFile[1] != '\\') || currentFile[0] == '/')
				{
					quotFileName += getDriveLetter();
					quotFileName += ':';
				}
				quotFileName += currentFile;
			}
			quotFileName += TEXT("\" ");
		}
	}

	//Only after loading all the file paths set the working directory
	::SetCurrentDirectory(NppParameters::getInstance()->getNppPath().c_str());	//force working directory to path of module, preventing lock

	if ((!isMultiInst) && (!TheFirstOne))
	{
		HWND hNotepad_plus = ::FindWindow(Notepad_plus_Window::getClassName(), NULL);
		for (int i = 0 ;!hNotepad_plus && i < 5 ; ++i)
		{
			Sleep(100);
			hNotepad_plus = ::FindWindow(Notepad_plus_Window::getClassName(), NULL);
		}

        if (hNotepad_plus)
        {
		// First of all, destroy static object NppParameters
		pNppParameters->destroyInstance();
		MainFileManager->destroyInstance();

		int sw = 0;

		if (::IsZoomed(hNotepad_plus))
			sw = SW_MAXIMIZE;
		else if (::IsIconic(hNotepad_plus))
			sw = SW_RESTORE;

/* REMOVED
		else
			sw = SW_SHOW;

		// IMPORTANT !!!
		::ShowWindow(hNotepad_plus, sw);
DEVOMER*/
/* ADDED */
		if (sw != 0)
			::ShowWindow(hNotepad_plus, sw);
/* DEDDA */
		::SetForegroundWindow(hNotepad_plus);

		if (params.size() > 0)	//if there are files to open, use the WM_COPYDATA system
		{
			COPYDATASTRUCT paramData;
			paramData.dwData = COPYDATA_PARAMS;
			paramData.lpData = &cmdLineParams;
			paramData.cbData = sizeof(cmdLineParams);

			COPYDATASTRUCT fileNamesData;
			fileNamesData.dwData = COPYDATA_FILENAMES;
			fileNamesData.lpData = (void *)quotFileName.c_str();
			fileNamesData.cbData = long(quotFileName.length() + 1)*(sizeof(TCHAR));

			::SendMessage(hNotepad_plus, WM_COPYDATA, (WPARAM)hInstance, (LPARAM)&paramData);
			::SendMessage(hNotepad_plus, WM_COPYDATA, (WPARAM)hInstance, (LPARAM)&fileNamesData);
		}
		return 0;
        }
	}

	Notepad_plus_Window notepad_plus_plus;
	
	NppGUI & nppGui = (NppGUI &)pNppParameters->getNppGUI();

	generic_string updaterDir = pNppParameters->getNppPath();
	updaterDir += TEXT("\\updater\\");

	generic_string updaterFullPath = updaterDir + TEXT("gup.exe");
 
	generic_string version = TEXT("-v");
	version += VERSION_VALUE;

	bool isUpExist = nppGui._doesExistUpdater = (::PathFileExists(updaterFullPath.c_str()) == TRUE);

    bool doUpdate = nppGui._autoUpdateOpt._doAutoUpdate;

    if (doUpdate) // check more detail 
    {
        Date today(0);
        
        if (today < nppGui._autoUpdateOpt._nextUpdateDate)
            doUpdate = false;
    }

	if (TheFirstOne && isUpExist && doUpdate)
	{
		Process updater(updaterFullPath.c_str(), version.c_str(), updaterDir.c_str());
		updater.run();
        
        // Update next update date
        if (nppGui._autoUpdateOpt._intervalDays < 0) // Make sure interval days value is positive
            nppGui._autoUpdateOpt._intervalDays = 0 - nppGui._autoUpdateOpt._intervalDays;
        nppGui._autoUpdateOpt._nextUpdateDate = Date(nppGui._autoUpdateOpt._intervalDays);
	}

	MSG msg;
	msg.wParam = 0;
	Win32Exception::installHandler();
	try {
		notepad_plus_plus.init(hInstance, NULL, quotFileName.c_str(), &cmdLineParams);

		// Tell UAC that lower integrity processes are allowed to send WM_COPYDATA messages to this process (or window)
		// This allows opening new files to already opened elevated Notepad++ process via explorer context menu.
		if(pNppParameters->getWinVersion() >= WV_VISTA)
		{
			HMODULE hDll = GetModuleHandle(TEXT("user32.dll"));
			if (hDll)
			{
				// According to MSDN ChangeWindowMessageFilter may not be supported in future versions of Windows, 
				// that is why we use ChangeWindowMessageFilterEx if it is available (windows version >= Win7).

				if(pNppParameters->getWinVersion() == WV_VISTA)
				{
					typedef BOOL (WINAPI *MESSAGEFILTERFUNC)(UINT message,DWORD dwFlag);
					const DWORD MSGFLT_ADD = 1;

					MESSAGEFILTERFUNC func = (MESSAGEFILTERFUNC)::GetProcAddress( hDll, "ChangeWindowMessageFilter" );

					if (func)
					{
						func(WM_COPYDATA, MSGFLT_ADD);
					}
				}
				else
				{
					typedef BOOL (WINAPI *MESSAGEFILTERFUNCEX)(HWND hWnd,UINT message,DWORD action,VOID* pChangeFilterStruct);
					const DWORD MSGFLT_ALLOW = 1;

					MESSAGEFILTERFUNCEX func = (MESSAGEFILTERFUNCEX)::GetProcAddress( hDll, "ChangeWindowMessageFilterEx" );

					if (func)
					{
						func(notepad_plus_plus.getHSelf(), WM_COPYDATA, MSGFLT_ALLOW, NULL );
					}
				}
			}
		}

		bool unicodeSupported = pNppParameters->getWinVersion() >= WV_NT;
		bool going = true;
		while (going)
		{
			going = (unicodeSupported?(::GetMessageW(&msg, NULL, 0, 0)):(::GetMessageA(&msg, NULL, 0, 0))) != 0;
			if (going)
			{
				// if the message doesn't belong to the notepad_plus_plus's dialog
				if (!notepad_plus_plus.isDlgsMsg(&msg, unicodeSupported))
				{
					if (::TranslateAccelerator(notepad_plus_plus.getHSelf(), notepad_plus_plus.getAccTable(), &msg) == 0)
					{
						::TranslateMessage(&msg);
						if (unicodeSupported)
							::DispatchMessageW(&msg);
						else
							::DispatchMessage(&msg);
					}
				}
			}
		}
	} catch(int i) {
		TCHAR str[50] = TEXT("God Damned Exception : ");
		TCHAR code[10];
		wsprintf(code, TEXT("%d"), i);
		::MessageBox(Notepad_plus_Window::gNppHWND, lstrcat(str, code), TEXT("Int Exception"), MB_OK);
		doException(notepad_plus_plus);
	} catch(std::runtime_error & ex) {
		::MessageBoxA(Notepad_plus_Window::gNppHWND, ex.what(), "Runtime Exception", MB_OK);
		doException(notepad_plus_plus);
	} catch (const Win32Exception & ex) {
		TCHAR message[1024];	//TODO: sane number
		wsprintf(message, TEXT("An exception occured. Notepad++ cannot recover and must be shut down.\r\nThe exception details are as follows:\r\n")
		TEXT("Code:\t0x%08X\r\nType:\t%S\r\nException address: 0x%08X"), ex.code(), ex.what(), ex.where());
		::MessageBox(Notepad_plus_Window::gNppHWND, message, TEXT("Win32Exception"), MB_OK | MB_ICONERROR);
		mdump.writeDump(ex.info());
		doException(notepad_plus_plus);
	} catch(std::exception & ex) {
		::MessageBoxA(Notepad_plus_Window::gNppHWND, ex.what(), "General Exception", MB_OK);
		doException(notepad_plus_plus);
	} catch(...) {	//this shouldnt ever have to happen
		::MessageBoxA(Notepad_plus_Window::gNppHWND, "An exception that we did not yet found its name is just caught", "Unknown Exception", MB_OK);
		doException(notepad_plus_plus);
	}

	return (UINT)msg.wParam;
}
Пример #20
0
void ExclusivePoolMgr::ExecuteEvent(ExclusivePool& pool)
{
    sLog.outBasic("ExclusivePool: Shuffling pool %u...", pool.poolID);

    // Get the spawn points and shuffle them.
    std::vector<ExclusivePoolSpot> poolSpotList;
    poolSpotList.insert(poolSpotList.begin(), m_poolSpots[pool.poolID].begin(), m_poolSpots[pool.poolID].end());
    std::random_shuffle(poolSpotList.begin(), poolSpotList.end());
    
    for (std::pair<const uint32, std::list<ObjectGuid> >& poolPair : pool.m_objects)
    {
        // If we have run out of spawn positions we stop spawning creatures.
        if (poolSpotList.empty())
            break;
        
        std::list<ObjectGuid> poolObjectList = poolPair.second;

        // Check if any creatures in the current group are alive.
        // If they are the group should be skipped.
        bool foundAlive = false;
        for (ObjectGuid currentCreature : poolObjectList)
        {
            const CreatureData* pData = sObjectMgr.GetCreatureData(currentCreature.GetCounter());
            if (pData)
            {
                Map* pMap = sMapMgr.FindMap(pData->mapid);
                if (pMap)
                {
                    if (!pMap->IsLoaded(pData->posX, pData->posY))
                    {
                        MaNGOS::ObjectUpdater updater(0);
                        // for creature
                        TypeContainerVisitor<MaNGOS::ObjectUpdater, GridTypeMapContainer  > grid_object_update(updater);
                        // for pets
                        TypeContainerVisitor<MaNGOS::ObjectUpdater, WorldTypeMapContainer > world_object_update(updater);
                        // Make sure that the creature is loaded before checking its status.
                        CellPair cellPair = MaNGOS::ComputeCellPair(pData->posX, pData->posY);
                        Cell cell(cellPair);
                        pMap->Visit(cell, grid_object_update);
                        pMap->Visit(cell, world_object_update);
                    }


                    Creature* pCreature = pMap->GetCreature(currentCreature);
                    if (pCreature)
                    {
                        // If the creature is alive or being looted we don't include it in the randomisation.
                        if (pCreature->isAlive() || pCreature->HasFlag(UNIT_DYNAMIC_FLAGS, UNIT_DYNFLAG_LOOTABLE))
                        {
                            sLog.outBasic("ExclusivePool: Skipping creature with guid %u.", currentCreature.GetCounter());
                            auto itr = std::find_if(poolSpotList.begin(), poolSpotList.end(),
                            [&](const ExclusivePoolSpot& spot)
                            {
                                if (spot.x == pData->posX && spot.y == pData->posY && 
                                    spot.z == pData->posZ && spot.mapID == pData->mapid)
                                {
                                    return true;
                                }
                                else
                                    return false;
                            });

                            // If we found the spot on which the living creature is standing
                            // we remove that spot since it's occupied.
                            if (itr != poolSpotList.end())
                            {
                                poolSpotList.erase(itr);
                                foundAlive = true;
                            }
                            else
                            {
                                sLog.outBasic("ExclusivePool: Could not find the pool position for creature %u. Moving it to avoid double spawns!", currentCreature.GetCounter());
                            }

                            DespawnAllExcept(poolObjectList, currentCreature);

                            break;
                        }
                    }
                }
            }
        }

        // If a creature in the current group was alive we skip it.
        if (foundAlive)
            continue;

        
        // Pick a random creature from the current group.
        auto itr = poolObjectList.begin();
        std::advance(itr, urand(0, poolObjectList.size() - 1));
        
        // Get a spawn point for the creature.
        ExclusivePoolSpot spot = poolSpotList.back();
        poolSpotList.pop_back();

        CreatureData& rData = sObjectMgr.mCreatureDataMap[itr->GetCounter()];
        
        // If the creature is already in the correct spot we skip it.
        if (rData.posX == spot.x && rData.posY == spot.y && 
            rData.posZ == spot.z && rData.mapid == spot.mapID)
        {
            continue;
        }
        
        // Do the actual spawning.
        sObjectMgr.RemoveCreatureFromGrid(itr->GetCounter(), &rData);
        Creature::AddToRemoveListInMaps(itr->GetCounter(), &rData);
        
        rData.posX = spot.x;
        rData.posY = spot.y;
        rData.posZ = spot.z;
        rData.orientation = spot.orientation;
        rData.mapid = spot.mapID;
        
        // Update the creature entry in the database.
        WorldDatabase.PQuery("UPDATE creature SET map=%u, position_x=%f, position_y=%f, position_z=%f, orientation=%f WHERE guid=%u",
                             spot.mapID, spot.x, spot.y, spot.z, spot.orientation, itr->GetCounter());

        // Make sure that all other creatures in the group are despawned.
        DespawnAllExcept(poolObjectList, *itr);
    }
    
    SaveRespawnTime(pool);

    sLog.outBasic("ExclusivePool: Finished shuffling pool %u.", pool.poolID);
}
Пример #21
0
/* Update pointers to words referenced from all code blocks.
Only needed after redefining an existing word.
If generic words were redefined, inline caches need to be reset. */
void factor_vm::update_code_heap_words(bool reset_inline_caches)
{
	word_updater updater(this,reset_inline_caches);
	each_code_block(updater);
}
Пример #22
0
bool psCheckReadyUpdate() {
    QString readyPath = cWorkingDir() + qsl("tupdates/ready");
	if (!QDir(readyPath).exists()) {
		return false;
	}

	// check ready version
	QString versionPath = readyPath + qsl("/tdata/version");
	{
		QFile fVersion(versionPath);
		if (!fVersion.open(QIODevice::ReadOnly)) {
			LOG(("Update Error: cant read version file '%1'").arg(versionPath));
			PsUpdateDownloader::clearAll();
			return false;
		}
		VerInt versionNum;
		if (fVersion.read((char*)&versionNum, sizeof(VerInt)) != sizeof(VerInt)) {
			LOG(("Update Error: cant read version from file '%1'").arg(versionPath));
			PsUpdateDownloader::clearAll();
			return false;
		}
		fVersion.close();
		if (versionNum <= AppVersion) {
			LOG(("Update Error: cant install version %1 having version %2").arg(versionNum).arg(AppVersion));
			PsUpdateDownloader::clearAll();
			return false;
		}
	}

#ifdef Q_OS_WIN
	QString curUpdater = (cExeDir() + qsl("Updater.exe"));
	QFileInfo updater(cWorkingDir() + qsl("tupdates/ready/Updater.exe"));
#elif defined Q_OS_MAC
	QString curUpdater = (cExeDir() + cExeName() + qsl("/Contents/Frameworks/Updater"));
	QFileInfo updater(cWorkingDir() + qsl("tupdates/ready/Telegram.app/Contents/Frameworks/Updater"));
#endif
	if (!updater.exists()) {
		QFileInfo current(curUpdater);
		if (!current.exists()) {
			PsUpdateDownloader::clearAll();
			return false;
		}
		if (!QFile(current.absoluteFilePath()).copy(updater.absoluteFilePath())) {
			PsUpdateDownloader::clearAll();
			return false;
		}
	}
#ifdef Q_OS_WIN
	if (CopyFile(updater.absoluteFilePath().toStdWString().c_str(), curUpdater.toStdWString().c_str(), FALSE) == FALSE) {
		PsUpdateDownloader::clearAll();
		return false;
	}
	if (DeleteFile(updater.absoluteFilePath().toStdWString().c_str()) == FALSE) {
		PsUpdateDownloader::clearAll();
		return false;
    }
#elif defined Q_OS_MAC
	QDir().mkpath(QFileInfo(curUpdater).absolutePath());
	DEBUG_LOG(("Update Info: moving %1 to %2..").arg(updater.absoluteFilePath()).arg(curUpdater));
	if (!objc_moveFile(updater.absoluteFilePath(), curUpdater)) {
		PsUpdateDownloader::clearAll();
		return false;
	}
#endif
    return true;
}
Пример #23
0
void CManageVariableDlg::ConfirmDeleteSelectedItems()
{
	int selCount = m_List.GetSelectedCount();

	if (selCount == 1) 
	{
		CString name = m_List.GetItemText(m_List.GetSelectionMark(), 0);

		// Determine if this variable belongs to any families
		vector<Family*>::iterator f = pType->families.begin();

		CString familiesList;

		for ( ; f != pType->families.end(); f++) {
			(*f)->UpdateFamilyData();

			if ((*f)->VariableNameExists(name))
				familiesList += (*f)->name + "\n";				
		}

		bool okay = false;

		if (familiesList != "") {
			CString msg = "This private variable is also used by the following families:\n\n";
			msg += familiesList;
			msg += "\nIf you delete this variable, it will also be removed from the above families.  All events referring to this variable and the variable in the above families will be removed.  Do you want to continue?";

			if (MessageBox(msg, "Remove private variable", MB_ICONEXCLAMATION | MB_YESNO) == IDYES)
				okay = true;
		}
		else if (MessageBox(CString("This will remove all actions, conditions and expressions relating to the variable.  Are you sure you want to delete the variable '") + name + "'?", "Delete Variable", MB_ICONQUESTION | MB_YESNO) == IDYES)
		{
			okay = true;
		}

		if (okay) {
			m_List.DeleteItem(m_List.GetSelectionMark());

			// Iterate and update all objects
			int index = find_index(pType->m_PrivateValues.begin(), pType->m_PrivateValues.end(), name);

			pType->m_PrivateValues.erase(pType->m_PrivateValues.begin() + index);

			for(int i=0; i<pType->families.size(); i++) //remove it from families also
			{
				int findex=find_index(pType->families[i]->variables.begin(), pType->families[i]->variables.end(), name);
				if(i<pType->families[i]->variables.size())
					pType->families[i]->variables.erase(pType->families[i]->variables.begin() + findex);
			}

			PrivateVariableInstanceDeleter updater(index);
			ForEachObjectInstance(pType, layout->application, updater);
		}
	}

	else if (selCount > 1)
	{
		CString msg;
		msg.Format("Are you sure you want to delete these %d private variables?", m_List.GetSelectedCount());
	
		if (MessageBox(msg, "Delete Variables", MB_ICONQUESTION | MB_YESNO) == IDNO)
			return;

		// Iterate selected items and delete
		POSITION selpos = m_List.GetFirstSelectedItemPosition();

		while (selpos) 
		{
			int nItem = m_List.GetNextSelectedItem(selpos);
			CString name = m_List.GetItemText(nItem, 0);

			// Iterate and update all objects
			int index = find_index(pType->m_PrivateValues.begin(), pType->m_PrivateValues.end(), name);

			ErasePrivateVariableReferences(application, pType, pType->m_PrivateValues[index].identifier);

			pType->m_PrivateValues.erase(pType->m_PrivateValues.begin() + index);

			for(int i=0; i<pType->families.size(); i++) //remove it from families also
			{
				int findex=find_index(pType->families[i]->variables.begin(), pType->families[i]->variables.end(), name);
				if(i<pType->families[i]->variables.size())
					pType->families[i]->variables.erase(pType->families[i]->variables.begin() + findex);
			}

			PrivateVariableInstanceDeleter updater(index);
			ForEachObjectInstance(pType, layout->application, updater);
		}

		RefreshVariablesList();
	}
}
Пример #24
0
int main(int argc, char *argv[])
{
	QTextCodec::setCodecForCStrings(QTextCodec::codecForName("utf8"));
	QTextCodec::setCodecForTr(QTextCodec::codecForName("utf8"));
	
	julyTranslator=new JulyTranslator;
	appDataDir_=new QByteArray();
	appVerIsBeta_=new bool(false);
	appVerStr_=new QByteArray("1.0707");
	appVerReal_=new double(appVerStr.toDouble());
	if(appVerStr.size()>4)
	{ 
		appVerStr.insert(4,".");
		if(appVerStr.at(appVerStr.size()-1)!='0')appVerIsBeta=true;
	}
	appVerLastReal_=new double(appVerReal);
	currencyBStr_=new QByteArray("USD");
	currencyBStrLow_=new QByteArray("usd");
	currencyBSign_=new QByteArray("USD");
	validKeySign_=new bool(false);
	currencyASign_=new QByteArray("BTC");
	currencyAStr_=new QByteArray("BTC");
	currencyAStrLow_=new QByteArray("btc");
	currencyRequest_=new QByteArray("BTCUSD");
	defaultLangFile_=new QString();pickDefaultLangFile();
	currencySignMap=new QMap<QByteArray,QByteArray>;
	currencyNamesMap=new QMap<QByteArray,QByteArray>;
	dateTimeFormat_=new QString(QLocale().dateTimeFormat(QLocale::ShortFormat));
	timeFormat_=new QString(QLocale().timeFormat(QLocale::ShortFormat));
	exchangeName_=new QString("Mt.Gox");
	btcDecimals_=new int(8);
	usdDecimals_=new int(5);
	priceDecimals_=new int(5);

	minTradePrice_=new double(0.01);
	minTradeVolume_=new double(0.01);
	currentTimeStamp_=new qint32(QDateTime::currentDateTime().toTime_t());
	httpRequestInterval_=new int(400);
	httpRequestTimeout_=new int(5);

	QString globalStyleSheet="QGroupBox {background: rgba(255,255,255,190); border: 1px solid gray;border-radius: 3px;margin-top: 7px;} QGroupBox:title {background: qradialgradient(cx: 0.5, cy: 0.5, fx: 0.5, fy: 0.5, radius: 0.7, stop: 0 #fff, stop: 1 transparent); border-radius: 2px; padding: 1 4px; top: -7; left: 7px;} QLabel {color: black;} QDoubleSpinBox {background: white;} QTextEdit {background: white;} QPlainTextEdit {background: white;} QCheckBox {color: black;} QLineEdit {color: black; background: white; border: 1px solid gray;}";

#ifdef Q_OS_WIN
	if(QFile::exists("./QtBitcoinTrader"))
	{
		appDataDir="./QtBitcoinTrader/";
		QDir().mkpath(appDataDir+"Language");
		if(!QFile::exists(appDataDir+"Language"))appDataDir.clear();
	}
	if(appDataDir.isEmpty())
	{
	appDataDir=QDesktopServices::storageLocation(QDesktopServices::DataLocation).replace("\\","/").toAscii()+"/QtBitcoinTrader/";
	if(!QFile::exists(appDataDir))QDir().mkpath(appDataDir);
	}
#else
	appDataDir=QDesktopServices::storageLocation(QDesktopServices::HomeLocation).toAscii()+"/.config/QtBitcoinTrader/";
	if(!QFile::exists(appDataDir))QDir().mkpath(appDataDir);
#endif
	
    if(argc>1)
	{
		QApplication a(argc,argv);
        if(a.arguments().last().startsWith("/checkupdate"))
		{
#ifndef Q_OS_WIN
			a.setStyle(new QPlastiqueStyle);
#endif
			a.setStyleSheet(globalStyleSheet);

			QSettings settings(appDataDir+"/Settings.set",QSettings::IniFormat);
			QString langFile=settings.value("LanguageFile","").toString();
			if(langFile.isEmpty()||!langFile.isEmpty()&&!QFile::exists(langFile))langFile=defaultLangFile;
			julyTranslator->loadFromFile(langFile);

			UpdaterDialog updater(a.arguments().last()!="/checkupdate");
			return a.exec();
		}
	}

	QApplication a(argc,argv);
#ifndef Q_OS_WIN
	a.setStyle(new QPlastiqueStyle);
#endif

#ifdef  Q_OS_WIN
	if(QFile::exists(a.applicationFilePath()+".upd"))QFile::remove(a.applicationFilePath()+".upd");
	if(QFile::exists(a.applicationFilePath()+".bkp"))QFile::remove(a.applicationFilePath()+".bkp");
#endif

#ifdef  Q_OS_MAC
	if(QFile::exists(a.applicationFilePath()+".upd"))QFile::remove(a.applicationFilePath()+".upd");
	if(QFile::exists(a.applicationFilePath()+".bkp"))QFile::remove(a.applicationFilePath()+".bkp");
#endif

	a.setWindowIcon(QIcon(":/Resources/QtBitcoinTrader.png"));
	QFile *lockFile=0;

	{
		QNetworkProxy proxy;
		QList<QNetworkProxy> proxyList=QNetworkProxyFactory::systemProxyForQuery(QNetworkProxyQuery(QUrl("https://")));
		if(proxyList.count())proxy=proxyList.first();
		QNetworkProxy::setApplicationProxy(proxy);

	logEnabled_=new bool(false);

	a.setStyleSheet(globalStyleSheet);

	logFileName_=new QString("QtBitcoinTrader.log");
	iniFileName_=new QString("QtBitcoinTrader.ini");

	restKey_=new QByteArray;
	restSign_=new QByteArray;
	{
		QFile currencyFile("://Resources/Currencies.map");
		currencyFile.open(QIODevice::ReadOnly);
		QStringList currencyList=QString(currencyFile.readAll().replace("\r","")).split("\n");
		currencyFile.close();
		for(int n=0;n<currencyList.count();n++)
		{
			QStringList currencyName=currencyList.at(n).split("=");
			if(currencyName.count()!=3)continue;
			currencyNamesMap->insert(currencyName.at(0).toAscii(),currencyName.at(1).toAscii());
			currencySignMap->insert(currencyName.at(0).toAscii(),currencyName.at(2).toAscii());
		}
		if(!QFile::exists(appDataDir+"Language"))QDir().mkpath(appDataDir+"Language");
		QSettings settings(appDataDir+"/Settings.set",QSettings::IniFormat);
		QString langFile=settings.value("LanguageFile","").toString();
		appVerLastReal=settings.value("Version",1.0).toDouble();
		settings.setValue("Version",appVerReal);
		if(langFile.isEmpty()||!langFile.isEmpty()&&!QFile::exists(langFile))langFile=defaultLangFile;
			julyTranslator->loadFromFile(langFile);
	}

	bool tryDecrypt=true;
	bool showNewPasswordDialog=false;
	while(tryDecrypt)
	{
		QString tryPassword;
		restKey.clear();
		restSign.clear();

		if(QDir(appDataDir,"*.ini").entryList().isEmpty()||showNewPasswordDialog)
		{
			NewPasswordDialog newPassword;
			if(newPassword.exec()==QDialog::Accepted)
			{
			tryPassword=newPassword.getPassword();
			newPassword.updateIniFileName();
			restKey=newPassword.getRestKey().toAscii();
			QSettings settings(iniFileName,QSettings::IniFormat);
			settings.setValue("ExchangeId",newPassword.getExchangeId());
			QByteArray cryptedData;
			if(newPassword.getExchangeId()==0)
			{
			restSign=QByteArray::fromBase64(newPassword.getRestSign().toAscii());
			cryptedData=JulyAES256::encrypt("Qt Bitcoin Trader\r\n"+restKey+"\r\n"+restSign.toBase64(),tryPassword.toAscii());
			}
			else
			if(newPassword.getExchangeId()==1)
			{
				restSign=newPassword.getRestSign().toAscii();
				cryptedData=JulyAES256::encrypt("Qt Bitcoin Trader\r\n"+restKey+"\r\n"+restSign.toBase64(),tryPassword.toAscii());
			}
			settings.setValue("CryptedData",QString(cryptedData.toBase64()));
			settings.setValue("ProfileName",newPassword.selectedProfileName());
			settings.remove("RestSign");
			settings.remove("RestKey");
			settings.sync();

			showNewPasswordDialog=false;
			}
		}
			PasswordDialog enterPassword;
			if(enterPassword.exec()==QDialog::Rejected)return 0;
			if(enterPassword.resetData)
			{
				if(QFile::exists(enterPassword.getIniFilePath()))
					QFile::remove(enterPassword.getIniFilePath());
				continue;
			}
			if(enterPassword.newProfile){showNewPasswordDialog=true;continue;}
			tryPassword=enterPassword.getPassword();

		if(!tryPassword.isEmpty())
		{
			iniFileName=enterPassword.getIniFilePath();
			bool profileLocked=enterPassword.isProfileLocked(iniFileName);
			if(profileLocked)
			{
				QMessageBox msgBox(0);
				msgBox.setIcon(QMessageBox::Question);
				msgBox.setWindowTitle("Qt Bitcoin Trader");
				msgBox.setText(julyTr("THIS_PROFILE_ALREADY_USED","This profile is already used by another instance.<br>API does not allow to run two instances with same key sign pair.<br>Please create new profile if you want to use two instances."));
#ifdef Q_OS_WIN
				msgBox.setStandardButtons(QMessageBox::Ok);
				msgBox.setDefaultButton(QMessageBox::Ok);
				msgBox.exec();
#else
				msgBox.setStandardButtons(QMessageBox::Ignore|QMessageBox::Ok);
				msgBox.setDefaultButton(QMessageBox::Ok);
				if(msgBox.exec()==QMessageBox::Ignore)profileLocked=false;
#endif
				if(profileLocked)tryPassword.clear();
			}
			if(!profileLocked)
			{
				QSettings settings(iniFileName,QSettings::IniFormat);
				QStringList decryptedList=QString(JulyAES256::decrypt(QByteArray::fromBase64(settings.value("CryptedData","").toString().toAscii()),tryPassword.toAscii())).split("\r\n");

				if(decryptedList.count()==3&&decryptedList.first()=="Qt Bitcoin Trader")
				{
					restKey=decryptedList.at(1).toAscii();
					restSign=QByteArray::fromBase64(decryptedList.last().toAscii());
                    tryDecrypt=false;
					lockFile=new QFile(enterPassword.lockFilePath(iniFileName));
                    lockFile->open(QIODevice::WriteOnly|QIODevice::Truncate);
					lockFile->write("Qt Bitcoin Trader Lock File");
				}
			}
		}
	}

	QSettings settings(iniFileName,QSettings::IniFormat);
	isLogEnabled=settings.value("LogEnabled",false).toBool();
	settings.setValue("LogEnabled",isLogEnabled);
	currencyASign=currencySignMap->value("BTC","BTC");
	currencyBStr=settings.value("Currency","USD").toString().toAscii();
	currencyBSign=currencySignMap->value(currencyBStr,"$");

	if(isLogEnabled)logThread=new LogThread;

	mainWindow_=new QtBitcoinTrader;
	QObject::connect(mainWindow_,SIGNAL(quit()),&a,SLOT(quit()));
	}
	mainWindow.loadUiSettings();
	a.exec();
	if(lockFile)
	{
		lockFile->close();
		lockFile->remove();
		delete lockFile;
	}
	return 0;
}
Пример #25
0
bool DatabaseAccess::checkReadyForUse(InitializationObserver* observer)
{
    QStringList drivers = QSqlDatabase::drivers();

    if (!drivers.contains("QSQLITE"))
    {
        kError() << "No SQLite3 driver available. List of QSqlDatabase drivers: " << drivers;
        d->lastError = i18n("The driver \"SQLITE\" for SQLite3 databases is not available.\n"
                            "digiKam depends on the drivers provided by the SQL module of Qt4.");
        return false;
    }

    if (!DatabaseConfigElement::checkReadyForUse())
    {
        d->lastError = DatabaseConfigElement::errorMessage();
        return false;
    }

    // create an object with private shortcut constructor
    DatabaseAccess access(false);

    if (!d->backend)
    {
        kWarning() << "No database backend available in checkReadyForUse. "
                   "Did you call setParameters before?";
        return false;
    }

    if (d->backend->isReady())
    {
        return true;
    }

    //TODO: Implement a method to wait until the database is open
    if (!d->backend->isOpen())
    {
        if (!d->backend->open(d->parameters))
        {
            access.setLastError(i18n("Error opening database backend.\n ")
                                + d->backend->lastError());
            return false;
        }
    }

    // avoid endless loops (if called methods create new DatabaseAccess objects)
    d->initializing = true;

    // update schema
    SchemaUpdater updater(access.db(), access.backend(), access.parameters());
    updater.setDatabaseAccess(&access);

    updater.setObserver(observer);

    if (!d->backend->initSchema(&updater))
    {
        access.setLastError(updater.getLastErrorMessage());
        d->initializing = false;
        return false;
    }

    // set identifier again
    d->databaseWatch->setDatabaseIdentifier(d->db->databaseUuid());

    // initialize CollectionManager
    CollectionManager::instance()->refresh();

    d->initializing = false;

    return d->backend->isReady();
}
Пример #26
0
int main(int argc, char** argv)
{
  // command arguments
  typedef bool (*commandFunction)(SensorUpdater&); // function pointer type
  std::map<std::string, commandFunction> argCmds =
  {
      {"update", cmdUpdate},
      {"update-16488", cmdUpdate16488},
      {"update-devel", cmdUpdateDevelop},
      {"update-16488-devel", cmdUpdate16488Develop},
      {"clean", cmdClean},
      {"reboot", cmdReboot},
      {"version", cmdVersion},
  };

  //parse args
  std::vector<std::string> args;
  for(int i=1; i<argc; i++)
    args.push_back( std::string(argv[i]) );

  /* find all sensors using auto discovery */

  //make IP optional
  std::string hostname,
              command;

  if(args.size() == 2)
  {
    //args <IP> <COMMAND>
    hostname = args[0];
    command = args[1];
  }
  else if (args.size() == 1)
  {
    //args <COMMAND>, use default hostname
    std::cout << "Sensor IP address not specified; using default (10.0.0.1)\n\n";
    hostname = std::string("10.0.0.1");
    command = args[0];
  }
  else
  {
    printArgs();
    exit(1);
  }

  //check command and run it
  bool success=false;

  if( !argCmds.count( command ) )
  {
    //invalid command
    printArgs();
    exit(-1);
  }

  // try to connect to the specified hostname/IP
  SensorUpdater updater(hostname);

  // run the command
  success = argCmds[command](updater);

  return success;
}
Пример #27
0
void ScanController::run()
{
    while (d->running)
    {
        bool doInit = false, doScan = false, doPartialScan = false, doUpdateUniqueHash = false;
        QString task;
        {
            QMutexLocker lock(&d->mutex);

            if (d->needsInitialization)
            {
                d->needsInitialization = false;
                doInit                 = true;
            }
            else if (d->needsCompleteScan)
            {
                d->needsCompleteScan = false;
                doScan               = true;
            }
            else if (d->needsUpdateUniqueHash)
            {
                d->needsUpdateUniqueHash = false;
                doUpdateUniqueHash       = true;
            }
            else if (!d->scanTasks.isEmpty() && !d->scanSuspended)
            {
                doPartialScan = true;
                task          = d->scanTasks.takeFirst();
            }
            else
            {
                d->idle = true;
                d->condVar.wait(&d->mutex);
                d->idle = false;
            }
        }

        if (doInit)
        {
            d->continueInitialization = true;
            // pass "this" as InitializationObserver
            bool success = DatabaseAccess::checkReadyForUse(this);

            // If d->advice has not been adjusted to a value indicating failure, do this here
            if (!success && d->advice == Success)
            {
                d->advice = ContinueWithoutDatabase;
            }

            emit databaseInitialized(success);
        }
        else if (doScan)
        {
            CollectionScanner scanner;
            connectCollectionScanner(&scanner);
            scanner.setNeedFileCount(d->needTotalFiles);
            scanner.recordHints(d->albumHints);
            scanner.recordHints(d->itemHints);
            scanner.recordHints(d->itemChangeHints);
            SimpleCollectionScannerObserver observer(&d->continueScan);
            scanner.setObserver(&observer);
            scanner.completeScan();
            emit completeScanDone();
        }
        else if (doPartialScan)
        {
            CollectionScanner scanner;
            scanner.recordHints(d->albumHints);
            scanner.recordHints(d->itemHints);
            scanner.recordHints(d->itemChangeHints);
            //connectCollectionScanner(&scanner);
            SimpleCollectionScannerObserver observer(&d->continuePartialScan);
            scanner.setObserver(&observer);
            scanner.partialScan(task);
        }
        else if (doUpdateUniqueHash)
        {
            DatabaseAccess access;
            SchemaUpdater updater(access.db(), access.backend(), access.parameters());
            updater.setDatabaseAccess(&access);
            updater.setObserver(this);
            updater.updateUniqueHash();
            emit completeScanDone();
        }
    }
}
Пример #28
0
/* Update pointers to words referenced from all code blocks. Only after
defining a new word. */
void factor_vm::update_code_heap_words()
{
	word_updater updater(this);
	iterate_code_heap(updater);
}
Пример #29
0
int Contractor::Run()
{
    if (config.core_factor > 1.0 || config.core_factor < 0)
    {
        throw util::exception("Core factor must be between 0.0 to 1.0 (inclusive)" + SOURCE_REF);
    }

    if (config.use_cached_priority)
    {
        util::Log(logWARNING) << "Using cached priorities is deprecated and they will be ignored.";
    }

    TIMER_START(preparing);

    util::Log() << "Reading node weights.";
    std::vector<EdgeWeight> node_weights;
    {
        storage::io::FileReader reader(config.GetPath(".osrm.enw"),
                                       storage::io::FileReader::VerifyFingerprint);
        storage::serialization::read(reader, node_weights);
    }
    util::Log() << "Done reading node weights.";

    util::Log() << "Loading edge-expanded graph representation";

    std::vector<extractor::EdgeBasedEdge> edge_based_edge_list;

    updater::Updater updater(config.updater_config);
    EdgeID max_edge_id = updater.LoadAndUpdateEdgeExpandedGraph(edge_based_edge_list, node_weights);

    // Contracting the edge-expanded graph

    TIMER_START(contraction);

    std::vector<std::vector<bool>> node_filters;
    {
        extractor::EdgeBasedNodeDataContainer node_data;
        extractor::files::readNodeData(config.GetPath(".osrm.ebg_nodes"), node_data);

        extractor::ProfileProperties properties;
        extractor::files::readProfileProperties(config.GetPath(".osrm.properties"), properties);

        node_filters = util::excludeFlagsToNodeFilter(max_edge_id + 1, node_data, properties);
    }

    RangebasedCRC32 crc32_calculator;
    const unsigned checksum = crc32_calculator(edge_based_edge_list);

    QueryGraph query_graph;
    std::vector<std::vector<bool>> edge_filters;
    std::vector<std::vector<bool>> cores;
    std::tie(query_graph, edge_filters, cores) =
        contractExcludableGraph(toContractorGraph(max_edge_id + 1, std::move(edge_based_edge_list)),
                                std::move(node_weights),
                                std::move(node_filters),
                                config.core_factor);
    TIMER_STOP(contraction);
    util::Log() << "Contracted graph has " << query_graph.GetNumberOfEdges() << " edges.";
    util::Log() << "Contraction took " << TIMER_SEC(contraction) << " sec";

    files::writeGraph(config.GetPath(".osrm.hsgr"), checksum, query_graph, edge_filters);

    files::writeCoreMarker(config.GetPath(".osrm.core"), cores);

    TIMER_STOP(preparing);

    util::Log() << "Preprocessing : " << TIMER_SEC(preparing) << " seconds";

    util::Log() << "finished preprocessing";

    return 0;
}
Пример #30
0
// Refresh not up to date metrics and metrics after date
void MetricAggregator::refreshMetrics(QDateTime forceAfterThisDate)
{
    // only if we have established a connection to the database
    if (dbaccess == NULL || main->isclean==true) return;

    // first check db structure is still up to date
    // this is because metadata.xml may add new fields
    dbaccess->checkDBVersion();

    // Get a list of the ride files
    QRegExp rx = RideFileFactory::instance().rideFileRegExp();
    QStringList filenames = RideFileFactory::instance().listRideFiles(home);
    QStringListIterator i(filenames);

    // get a Hash map of statistic records and timestamps
    QSqlQuery query(dbaccess->connection());
    QHash <QString, status> dbStatus;
    bool rc = query.exec("SELECT filename, timestamp, fingerprint FROM metrics ORDER BY ride_date;");
    while (rc && query.next()) {
        status add;
        QString filename = query.value(0).toString();
        add.timestamp = query.value(1).toInt();
        add.fingerprint = query.value(2).toInt();
        dbStatus.insert(filename, add);
    }

    // begin LUW -- byproduct of turning off sync (nosync)
    dbaccess->connection().transaction();

    // Delete statistics for non-existant ride files
    QHash<QString, status>::iterator d;
    for (d = dbStatus.begin(); d != dbStatus.end(); ++d) {
        if (QFile(home.absolutePath() + "/" + d.key()).exists() == false) {
            dbaccess->deleteRide(d.key());
#ifdef GC_HAVE_LUCENE
            main->lucene->deleteRide(d.key());
#endif
        }
    }

    unsigned long zoneFingerPrint = zones->getFingerprint() + hrzones->getFingerprint(); // crc of *all* zone data (HR and Power)

    // update statistics for ride files which are out of date
    // showing a progress bar as we go
    QTime elapsed;
    elapsed.start();
    QString title = tr("Refreshing Ride Statistics...\nStarted");
    QProgressDialog bar(title, tr("Abort"), 0, filenames.count(), main);
    bar.setWindowModality(Qt::WindowModal);
    bar.setMinimumDuration(0);
    bar.show();

    int processed=0;
    QApplication::processEvents(); // get that dialog up!

    // log of progress
    QFile log(home.absolutePath() + "/" + "metric.log");
    log.open(QIODevice::WriteOnly);
    log.resize(0);
    QTextStream out(&log);
    out << "METRIC REFRESH STARTS: " << QDateTime::currentDateTime().toString() + "\r\n";

    while (i.hasNext()) {
        QString name = i.next();
        QFile file(home.absolutePath() + "/" + name);

        // if it s missing or out of date then update it!
        status current = dbStatus.value(name);
        unsigned long dbTimeStamp = current.timestamp;
        unsigned long fingerprint = current.fingerprint;

        RideFile *ride = NULL;

        // update progress bar
        long elapsedtime = elapsed.elapsed();
        QString elapsedString = QString("%1:%2:%3").arg(elapsedtime/3600000,2)
                                                .arg((elapsedtime%3600000)/60000,2,10,QLatin1Char('0'))
                                                .arg((elapsedtime%60000)/1000,2,10,QLatin1Char('0'));
        QString title = tr("Refreshing Ride Statistics...\nElapsed: %1\n%2").arg(elapsedString).arg(name);
        bar.setLabelText(title);
        bar.setValue(++processed);
        QApplication::processEvents();

        if (dbTimeStamp < QFileInfo(file).lastModified().toTime_t() ||
            zoneFingerPrint != fingerprint ||
            (!forceAfterThisDate.isNull() && name >= forceAfterThisDate.toString("yyyy_MM_dd_hh_mm_ss"))) {
            QStringList errors;

            // log
            out << "Opening ride: " << name << "\r\n";

            // read file and process it if we didn't already...
            if (ride == NULL) ride = RideFileFactory::instance().openRideFile(main, file, errors);

            out << "File open completed: " << name << "\r\n";

            if (ride != NULL) {

                out << "Updating statistics: " << name << "\r\n";
                importRide(home, ride, name, zoneFingerPrint, (dbTimeStamp > 0));

            }
        }

        // update cache (will check timestamps itself)
        // if ride wasn't opened it will do it itself
        // we only want to check so passing check=true
        // because we don't actually want the results now
        RideFileCache updater(main, home.absolutePath() + "/" + name, ride, true);

        // free memory - if needed
        if (ride) delete ride;

        if (bar.wasCanceled()) {
            out << "METRIC REFRESH CANCELLED\r\n";
            break;
        }
    }

    // stop logging
    out << "METRIC REFRESH ENDS: " << QDateTime::currentDateTime().toString() + "\r\n";
    log.close();

    // end LUW -- now syncs DB
    dbaccess->connection().commit();
#ifdef GC_HAVE_LUCENE
    main->lucene->optimise();
#endif
    main->isclean = true;

    dataChanged(); // notify models/views
}