/** * @brief Initializes the application. */ bool App::OnInit() { // initialize wxWidgets SetAppName(wxT("UltraDefrag")); wxInitAllImageHandlers(); if(!wxApp::OnInit()) return false; // initialize udefrag library if(::udefrag_init_library() < 0){ wxLogError(wxT("Initialization failed!")); return false; } // set out of memory handler #if !defined(__GNUC__) winx_set_killer(out_of_memory_handler); _set_new_handler(out_of_memory_handler); _set_new_mode(1); #endif // initialize debug log wxFileName logpath(wxT(".\\logs\\ultradefrag.log")); logpath.Normalize(); wxSetEnv(wxT("UD_LOG_FILE_PATH"),logpath.GetFullPath()); ::udefrag_set_log_file_path(); // initialize logging m_log = new Log(); // use global config object for internal settings wxFileConfig *cfg = new wxFileConfig(wxT(""),wxT(""), wxT("gui.ini"),wxT(""),wxCONFIG_USE_RELATIVE_PATH); wxConfigBase::Set(cfg); // enable i18n support InitLocale(); // save report translation on setup wxString cmdLine(GetCommandLine()); if(cmdLine.Find(wxT("--setup")) != wxNOT_FOUND){ SaveReportTranslation(); ::winx_flush_dbg_log(0); delete m_log; return false; } // start web statistics m_statThread = new StatThread(); // check for administrative rights if(!Utils::CheckAdminRights()){ wxMessageDialog dlg(NULL, wxT("Administrative rights are needed to run the program!"), wxT("UltraDefrag"),wxOK | wxICON_ERROR ); dlg.ShowModal(); Cleanup(); return false; } // create synchronization event g_synchEvent = ::CreateEvent(NULL,TRUE,FALSE,NULL); if(!g_synchEvent){ letrace("cannot create synchronization event"); wxMessageDialog dlg(NULL, wxT("Cannot create synchronization event!"), wxT("UltraDefrag"),wxOK | wxICON_ERROR ); dlg.ShowModal(); Cleanup(); return false; } // keep things DPI-aware HDC hdc = ::GetDC(NULL); if(hdc){ g_scaleFactor = (double)::GetDeviceCaps(hdc,LOGPIXELSX) / 96.0f; ::ReleaseDC(NULL,hdc); } g_iconSize = wxSystemSettings::GetMetric(wxSYS_SMALLICON_X); if(g_iconSize < 20) g_iconSize = 16; else if(g_iconSize < 24) g_iconSize = 20; else if(g_iconSize < 32) g_iconSize = 24; else g_iconSize = 32; // support taskbar icon overlay setup on shell restart g_TaskbarIconMsg = ::RegisterWindowMessage(wxT("TaskbarButtonCreated")); if(!g_TaskbarIconMsg) letrace("cannot register TaskbarButtonCreated message"); // create main window g_mainFrame = new MainFrame(); g_mainFrame->Show(true); SetTopWindow(g_mainFrame); return true; }
int main(int argc, char *argv[]) { try { boost::asio::io_service io_service; Freenect::Freenect freenect; KinectFrameManager* device = &freenect.createDevice<KinectFrameManager>(0); boost::program_options::options_description generic("Generic Options"); generic.add_options() ("version,v", "print version information") ("help", "output help message") ; boost::program_options::options_description config("Standard Configuration"); config.add_options() ("port", boost::program_options::value<int>(&config_data.port)->default_value(4200), "port number") ; boost::program_options::options_description cmdLine("Allowed Options"); boost::program_options::options_description configFile; cmdLine.add(generic).add(config); configFile.add(config); boost::program_options::variables_map readOptions; boost::program_options::store(boost::program_options::command_line_parser(argc, argv).options(cmdLine).run(), readOptions); std::ifstream configFs("kinect-relay.cfg"); boost::program_options::store(parse_config_file(configFs, configFile), readOptions); boost::program_options::notify(readOptions); if (readOptions.count("help")) { std::cout << cmdLine << std::endl; return EXIT_SUCCESS; } if (readOptions.count("version")) { std::cout << "version information goes here" << std::endl; return EXIT_SUCCESS; } KinectServer server(io_service, config_data.port, device); /*boost::asio::signal_set signals(io_service, SIGINT, SIGTERM); signals.async_wait(boost::bind(&boost::asio::io_service::stop, &io_service)); io_service.notify_fork(boost::asio::io_service::fork_prepare); if (pid_t pid = fork()) if (pid > 0) exit(EXIT_SUCCESS); else { syslog(LOG_ERR | LOG_USER, "Primary fork failure: %m"); return EXIT_FAILURE; } close(0); close(1); close(2); if (open("/dev/null", O_RDONLY) < 0) { syslog(LOG_ERR | LOG_USER, "Unable to open /dev/null: %m"); return EXIT_FAILURE; } const char* output = "/tmp/kinectd.daemon.out"; const int flags = O_WRONLY | O_CREAT | O_APPEND; const mode_t mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH; if (open(output, flags, mode) < 0) { syslog(LOG_ERR | LOG_USER, "Unable to open output file %s: %m", output); return EXIT_FAILURE; } if (dup(1) < 0) { syslog(LOG_ERR | LOG_USER, "Unable to dup output descriptor: %m"); return EXIT_FAILURE; } io_service.notify_fork(boost::asio::io_service::fork_child); syslog(LOG_INFO | LOG_USER, "kinectd daemon started");*/ std::cout << "Starting kinect...." << std::endl; //device->startVideo(); device->startDepth(); device->setLed(LED_RED); std::cout << "Starting server...." << std::endl; io_service.run(); std::cout << "Stopping server...." << std::endl; //device->stopVideo(); device->stopDepth(); std::cout << "Stopping kinect...." << std::endl; //syslog(LOG_INFO | LOG_USER, "kinectd daemon stopped"); } catch (std::exception& e) { syslog(LOG_ERR | LOG_USER, "Exception: %s", e.what()); std::cerr << e.what() << std::endl; return EXIT_FAILURE; } return EXIT_SUCCESS; }
int main(int argc, char *argv[]) { char *password, *passFile, *userName; char *encodedPassword, *argp, *realm; char passBuf[MPR_HTTP_MAX_PASS], buf[MPR_HTTP_MAX_PASS * 2]; int c, errflg, create, nextArg; bool enable; programName = mprGetBaseName(argv[0]); userName = 0; create = errflg = 0; password = 0; enable = 1; #if BLD_FEATURE_LOG MprLogService *ls = new MprLogService(); ls->addListener(new MprLogToFile()); ls->setLogSpec("stdout:0"); #endif MprCmdLine cmdLine(argc, argv, "cdep:"); while ((c = cmdLine.next(&argp)) != EOF) { switch(c) { case 'c': create++; break; case 'e': enable = 1; break; case 'd': enable = 0; break; case 'p': password = argp; break; default: errflg++; break; } } nextArg = cmdLine.firstArg(); if ((nextArg + 3) > argc) { errflg++; } if (errflg) { printUsage(argv[0]); exit(2); } passFile = argv[nextArg++]; realm = argv[nextArg++]; userName = argv[nextArg++]; if (!create) { if (readPassFile(passFile) < 0) { exit(2); } if (access(passFile, R_OK) != 0) { mprError(MPR_L, MPR_USER, "Can't find %s\n", passFile); exit(3); } if (access(passFile, W_OK) < 0) { mprError(MPR_L, MPR_USER, "Can't write to %s\n", passFile); exit(4); } } else { if (access(passFile, R_OK) == 0) { mprError(MPR_L, MPR_USER, "Can't create %s, already exists\n", passFile); exit(5); } } if (password == 0) { password = getPassword(passBuf, sizeof(passBuf)); if (password == 0) { exit(1); } } mprSprintf(buf, sizeof(buf), "%s:%s:%s", userName, realm, password); encodedPassword = maMD5(buf); addUser(userName, realm, encodedPassword, enable); if (updatePassFile(passFile) < 0) { exit(6); } mprFree(encodedPassword); return 0; }
/** * Main function of fspc CLI unit test.. */ int main(int argc, char **argv) { wxString value; FspcIconMode mode; #ifdef MANUAL_TEST wxInitializer init; FspcCli cli(argc, argv); if (cli.GetResult() == false) { // When result is false, the usage will be shown automatically. // We just leave the program. cli.Usage(); return (-1); } else { // Get the parameters. wxPrintf(wxT("-h: %d\n"), (int)cli.GetParamHelp()); wxPrintf(wxT("-V: %d\n"), (int)cli.GetParamVersion()); wxPrintf(wxT("-v: %d\n"), (int)cli.GetParamVerbose()); wxPrintf(wxT("-d: %d\n"), (int)cli.GetParamDebug()); wxPrintf(wxT("-t: %d\n"), (int)cli.GetParamTextMode()); if (cli.GetParamConfig(value)) { wxPrintf(wxT("-c: %s\n"), value.c_str()); } else { wxPrintf(wxT("-c: <none>\n")); } if (cli.GetParamMode(mode)) { wxPrintf(wxT("-m: %d\n"), (int) mode); } else { wxPrintf(wxT("-m: <none>\n")); } if (cli.GetParamSetProp(value)) { wxPrintf(wxT("-s: %s\n"), value.c_str()); } else { wxPrintf(wxT("-s: <none>\n")); } if (cli.GetParamGetProp(value)) { wxPrintf(wxT("-g: %s\n"), value.c_str()); } else { wxPrintf(wxT("-g: <none>\n")); } wxPrintf(wxT("OK\n")); } #else wxInitializer init; wxString cmdLine(wxT("test")); FspcCli cli(cmdLine); cli.Usage(); // Test the default setting of arguments. wxASSERT(cli.GetParamHelp() == false); wxASSERT(cli.GetParamVersion() == false); wxASSERT(cli.GetParamVerbose() == false); wxASSERT(cli.GetParamDebug() == false); wxASSERT(cli.GetParamTextMode() == false); wxASSERT(cli.GetParamLoadConf(value) == false); wxASSERT(cli.GetParamSaveConf(value) == false); wxASSERT(cli.GetParamMode(mode) == false); wxASSERT(cli.GetParamProp(value) == false); // Test -c parameters. cmdLine = wxString(wxT("test --load=xxx.cfg")); cli.DoParse(cmdLine); wxASSERT(cli.GetParamHelp() == false); wxASSERT(cli.GetParamVersion() == false); wxASSERT(cli.GetParamVerbose() == false); wxASSERT(cli.GetParamDebug() == false); wxASSERT(cli.GetParamTextMode() == false); wxASSERT(cli.GetParamLoadConf(value) == true); wxASSERT(value == wxT("xxx.cfg")); wxASSERT(cli.GetParamSaveConf(value) == false); wxASSERT(cli.GetParamMode(mode) == false); wxASSERT(cli.GetParamProp(value) == false); // Test -m parameters. cmdLine = wxString(wxT("test")); cli.DoParse(cmdLine); wxASSERT(cli.GetParamMode(mode) == false); wxASSERT(mode == FSPC_ICON_MODE_DISABLE); cmdLine = wxString(wxT("test -mhidden")); cli.DoParse(cmdLine); wxASSERT(cli.GetParamMode(mode) == true); wxASSERT(mode == FSPC_ICON_MODE_HIDDEN); cmdLine = wxString(wxT("test --mode=static")); cli.DoParse(cmdLine); wxASSERT(cli.GetParamMode(mode) == true); wxASSERT(mode == FSPC_ICON_MODE_STATIC); cmdLine = wxString(wxT("test -m dynamic")); cli.DoParse(cmdLine); wxASSERT(cli.GetParamMode(mode) == true); wxASSERT(mode == FSPC_ICON_MODE_DYNAMIC); // Test Key Value Hash. KeyValueHash hash; KeyValueHash hash2; wxString str; hash[wxT("a")] = wxT("1"); hash[wxT("bc")] = wxT("2"); hash[wxT("def")] = wxT("34"); hash[wxT("ghij")] = wxT("567"); wxASSERT(ConvertHashToKeyValue(hash, str) == true); wxASSERT(ConvertKeyValueToHash(str, hash2) == true); wxASSERT(hash[wxT("a")] == hash2[wxT("a")]); wxASSERT(hash[wxT("bc")] == hash2[wxT("bc")]); wxASSERT(hash[wxT("def")] == hash2[wxT("def")]); wxASSERT(hash[wxT("ghij")] == hash2[wxT("ghij")]); // Test done. wxPrintf(wxT("\nAll tests passed..\n")); #endif }
void EngineProcess::start(const QString& program, const QStringList& arguments, OpenMode mode) { if (m_started) close(); m_started = false; m_finished = false; m_exitCode = 0; m_exitStatus = NormalExit; m_errRead = createFile(m_stdErrFile, m_stdErrFileMode); // Temporary handles for the child process' end of the pipes HANDLE outWrite; HANDLE inRead; // Security attributes. Use the same one for both pipes. SECURITY_ATTRIBUTES saAttr; saAttr.nLength = sizeof(SECURITY_ATTRIBUTES); saAttr.bInheritHandle = TRUE; saAttr.lpSecurityDescriptor = NULL; CreatePipe(&m_outRead, &outWrite, &saAttr, 0); CreatePipe(&inRead, &m_inWrite, &saAttr, 0); STARTUPINFO startupInfo; ZeroMemory(&startupInfo, sizeof(startupInfo)); startupInfo.cb = sizeof(startupInfo); startupInfo.hStdError = m_errRead; startupInfo.hStdOutput = outWrite; startupInfo.hStdInput = inRead; startupInfo.dwFlags |= STARTF_USESTDHANDLES; // Call DuplicateHandle with a NULL target to get non-inheritable // handles for the parent process' ends of the pipes DuplicateHandle(GetCurrentProcess(), m_outRead, // child's stdout read end GetCurrentProcess(), NULL, // no target 0, // flags FALSE, // not inheritable DUPLICATE_SAME_ACCESS); // same handle access DuplicateHandle(GetCurrentProcess(), m_inWrite, // child's stdin write end GetCurrentProcess(), NULL, // no target 0, // flags FALSE, // not inheritable DUPLICATE_SAME_ACCESS); // same handle access BOOL ok = FALSE; QString cmd = cmdLine(m_workDir, program, arguments); QString wdir = QDir::toNativeSeparators(m_workDir); ZeroMemory(&m_processInfo, sizeof(m_processInfo)); #ifdef UNICODE ok = CreateProcessW(NULL, (WCHAR*)cmd.utf16(), NULL, // process attributes NULL, // thread attributes TRUE, // inherit handles CREATE_NEW_PROCESS_GROUP | CREATE_NO_WINDOW, // creation flags NULL, // environment wdir.isEmpty() ? NULL : (WCHAR*)wdir.utf16(), &startupInfo, &m_processInfo); #else // not UNICODE ok = CreateProcessA(NULL, cmd.toLocal8Bit().data(), NULL, // process attributes NULL, // thread attributes TRUE, // inherit handles CREATE_NEW_PROCESS_GROUP | CREATE_NO_WINDOW, // creation flags NULL, // environment wdir.isEmpty() ? NULL : wdir.toLocal8Bit().data(), &startupInfo, &m_processInfo); #endif // not UNICODE m_started = (bool)ok; if (ok) { // Assign the engine process to the main job to make sure it's // terminated when CuteChess terminates. AssignProcessToJobObject(mainJob(), m_processInfo.hProcess); // Close the child process' ends of the pipes to make sure // that ReadFile and WriteFile will return when the child // terminates and closes its pipes killHandle(&outWrite); killHandle(&inRead); killHandle(&m_processInfo.hThread); // Start reading input from the child m_reader = new PipeReader(m_outRead, this); connect(m_reader, SIGNAL(finished()), this, SLOT(onFinished())); connect(m_reader, SIGNAL(finished()), this, SIGNAL(readChannelFinished())); connect(m_reader, SIGNAL(readyRead()), this, SIGNAL(readyRead())); m_reader->start(); // Make QIODevice aware that the device is now open QIODevice::open(mode); } else cleanup(); }
void CasmSubmitPage::Data::submit() { if (m_filepathTextField->getText() == toWideString("")) { TMessage::error("You must load a file"); return; } CasmTask *casm = m_configPanel->getTask(); TFarmController *controller = Application::instance()->getController(); string nativeCmdLine("runcasm "); nativeCmdLine += casm->m_casmFile; nativeCmdLine += " "; if (casm->m_setupFile != "") { nativeCmdLine += "-setup "; nativeCmdLine += casm->m_setupFile; nativeCmdLine += " "; } nativeCmdLine += casm->getCommandLine(); string casmName = TFilePath(casm->m_casmFile).getName(); int stepCount = casm->m_end - casm->m_start + 1; TFarmTaskGroup task( casmName, nativeCmdLine, TSystem::getUserName(), TSystem::getHostName(), stepCount); int ra = casm->m_start; for (;;) { CasmTask subcasm(*casm); string cmdLine("runcasm "); int rb = tmin(ra + casm->m_taskChunksize - 1, casm->m_end); subcasm.m_start = ra; subcasm.m_end = rb; cmdLine += subcasm.m_casmFile; cmdLine += " "; if (subcasm.m_setupFile != "") { cmdLine += "-setup "; cmdLine += subcasm.m_setupFile; cmdLine += " "; } cmdLine += subcasm.getCommandLine(); cmdLine += " -nowait "; try { string name = casmName + " " + toString(ra) + "-" + toString(rb); stepCount = rb - ra + 1; task.addTask(new TFarmTask( name, cmdLine, TSystem::getUserName(), TSystem::getHostName(), stepCount)); } catch (TException &e) { TMessage::error(toString(e.getMessage())); } if (rb == casm->m_end) break; ra = rb + 1; } try { controller->addTask(task, m_submitAsSuspended->isSelected()); } catch (TException &e) { TMessage::error(toString(e.getMessage())); } }
int APIENTRY wWinMain(_In_ HINSTANCE hInstance, _In_opt_ HINSTANCE hPrevInstance, _In_ LPWSTR lpCmdLine, _In_ int nCmdShow) { // Attempt to mitigate http://textslashplain.com/2015/12/18/dll-hijacking-just-wont-die SetDefaultDllDirectories(LOAD_LIBRARY_SEARCH_SYSTEM32); int exitCode = -1; CString cmdLine(lpCmdLine); if (cmdLine.Find(L"--checkInstall") >= 0) { // If we're already installed, exit as fast as possible if (!MachineInstaller::ShouldSilentInstall()) { exitCode = 0; goto out; } // Make sure update.exe gets silent wcscat(lpCmdLine, L" --silent"); } HRESULT hr = ::CoInitialize(NULL); ATLASSERT(SUCCEEDED(hr)); AtlInitCommonControls(ICC_COOL_CLASSES | ICC_BAR_CLASSES); hr = _Module.Init(NULL, hInstance); bool isQuiet = (cmdLine.Find(L"-s") >= 0); bool weAreUACElevated = CUpdateRunner::AreWeUACElevated() == S_OK; bool explicitMachineInstall = (cmdLine.Find(L"--machine") >= 0); if (explicitMachineInstall || weAreUACElevated) { exitCode = MachineInstaller::PerformMachineInstallSetup(); if (exitCode != 0) goto out; isQuiet = true; // Make sure update.exe gets silent if (explicitMachineInstall) { wcscat(lpCmdLine, L" --silent"); printf("Machine-wide installation was successful! Users will see the app once they log out / log in again.\n"); } } if (!CFxHelper::CanInstallDotNet4_5()) { // Explain this as nicely as possible and give up. MessageBox(0L, L"This program cannot run on Windows XP or before; it requires a later version of Windows.", L"Incompatible Operating System", 0); exitCode = E_FAIL; goto out; } if (!CFxHelper::IsDotNet45OrHigherInstalled()) { hr = CFxHelper::InstallDotNetFramework(isQuiet); if (FAILED(hr)) { exitCode = hr; // #yolo CUpdateRunner::DisplayErrorMessage(CString(L"Failed to install the .NET Framework, try installing .NET 4.5 or higher manually"), NULL); goto out; } // S_FALSE isn't failure, but we still shouldn't try to install if (hr != S_OK) { exitCode = 0; goto out; } } // If we're UAC-elevated, we shouldn't be because it will give us permissions // problems later. Just silently rerun ourselves. if (weAreUACElevated) { wchar_t buf[4096]; HMODULE hMod = GetModuleHandle(NULL); GetModuleFileNameW(hMod, buf, 4096); CUpdateRunner::ShellExecuteFromExplorer(buf, lpCmdLine); exitCode = 0; goto out; } exitCode = CUpdateRunner::ExtractUpdaterAndRun(lpCmdLine, false); out: _Module.Term(); ::CoUninitialize(); return exitCode; }
int LauncherMain(int argc, wchar_t* argv[]) { // Make sure that the launcher process itself has image load policies set if (IsWin10AnniversaryUpdateOrLater()) { const DynamicallyLinkedFunctionPtr<decltype(&SetProcessMitigationPolicy)> pSetProcessMitigationPolicy(L"kernel32.dll", "SetProcessMitigationPolicy"); if (pSetProcessMitigationPolicy) { PROCESS_MITIGATION_IMAGE_LOAD_POLICY imgLoadPol = {}; imgLoadPol.PreferSystem32Images = 1; DebugOnly<BOOL> setOk = pSetProcessMitigationPolicy(ProcessImageLoadPolicy, &imgLoadPol, sizeof(imgLoadPol)); MOZ_ASSERT(setOk); } } if (!SetArgv0ToFullBinaryPath(argv)) { ShowError(); return 1; } LauncherFlags flags = ProcessCmdLine(argc, argv); nsAutoHandle mediumIlToken; Maybe<ElevationState> elevationState = GetElevationState(flags, mediumIlToken); if (!elevationState) { return 1; } // If we're elevated, we should relaunch ourselves as a normal user. // Note that we only call LaunchUnelevated when we don't need to wait for the // browser process. if (elevationState.value() == ElevationState::eElevated && !(flags & (LauncherFlags::eWaitForBrowser | LauncherFlags::eNoDeelevate)) && !mediumIlToken.get()) { return !LaunchUnelevated(argc, argv); } // Now proceed with setting up the parameters for process creation UniquePtr<wchar_t[]> cmdLine(MakeCommandLine(argc, argv)); if (!cmdLine) { return 1; } const Maybe<bool> isSafeMode = IsSafeModeRequested(argc, argv, SafeModeFlag::NoKeyPressCheck); if (!isSafeMode) { ShowError(ERROR_INVALID_PARAMETER); return 1; } ProcThreadAttributes attrs; SetMitigationPolicies(attrs, isSafeMode.value()); HANDLE stdHandles[] = { ::GetStdHandle(STD_INPUT_HANDLE), ::GetStdHandle(STD_OUTPUT_HANDLE), ::GetStdHandle(STD_ERROR_HANDLE) }; attrs.AddInheritableHandles(stdHandles); DWORD creationFlags = CREATE_SUSPENDED | CREATE_UNICODE_ENVIRONMENT; STARTUPINFOEXW siex; Maybe<bool> attrsOk = attrs.AssignTo(siex); if (!attrsOk) { ShowError(); return 1; } BOOL inheritHandles = FALSE; if (attrsOk.value()) { creationFlags |= EXTENDED_STARTUPINFO_PRESENT; if (attrs.HasInheritableHandles()) { siex.StartupInfo.dwFlags |= STARTF_USESTDHANDLES; siex.StartupInfo.hStdInput = stdHandles[0]; siex.StartupInfo.hStdOutput = stdHandles[1]; siex.StartupInfo.hStdError = stdHandles[2]; // Since attrsOk == true, we have successfully set the handle inheritance // whitelist policy, so only the handles added to attrs will be inherited. inheritHandles = TRUE; } } PROCESS_INFORMATION pi = {}; BOOL createOk; if (mediumIlToken.get()) { createOk = ::CreateProcessAsUserW(mediumIlToken.get(), argv[0], cmdLine.get(), nullptr, nullptr, inheritHandles, creationFlags, nullptr, nullptr, &siex.StartupInfo, &pi); } else { createOk = ::CreateProcessW(argv[0], cmdLine.get(), nullptr, nullptr, inheritHandles, creationFlags, nullptr, nullptr, &siex.StartupInfo, &pi); } if (!createOk) { ShowError(); return 1; } nsAutoHandle process(pi.hProcess); nsAutoHandle mainThread(pi.hThread); if (!PostCreationSetup(process.get(), mainThread.get(), isSafeMode.value()) || ::ResumeThread(mainThread.get()) == static_cast<DWORD>(-1)) { ShowError(); ::TerminateProcess(process.get(), 1); return 1; } if (flags & LauncherFlags::eWaitForBrowser) { DWORD exitCode; if (::WaitForSingleObject(process.get(), INFINITE) == WAIT_OBJECT_0 && ::GetExitCodeProcess(process.get(), &exitCode)) { // Propagate the browser process's exit code as our exit code. return static_cast<int>(exitCode); } } else { const DWORD timeout = ::IsDebuggerPresent() ? INFINITE : kWaitForInputIdleTimeoutMS; // Keep the current process around until the callback process has created // its message queue, to avoid the launched process's windows being forced // into the background. mozilla::WaitForInputIdle(process.get(), timeout); } return 0; }
void mkdirs(const char * dir) { Line cmdLine("mkdir -p %s", dir); panicIf(system(cmdLine()), "mkdir"); }
BOOL CXPAntiSpyApp::InitInstance() { AfxEnableControlContainer(); AfxInitRichEdit(); // Standardinitialisierung #ifdef _AFXDLL Enable3dControls(); // Diese Funktion bei Verwendung von MFC in gemeinsam genutzten DLLs aufrufen #else Enable3dControlsStatic(); // Diese Funktion bei statischen MFC-Anbindungen aufrufen #endif //this is to get them commandline arguments for unattended running CString cmdLine(m_lpCmdLine); if(cmdLine.Find(_T("/apply"), 0) == 0) { CString profile = cmdLine.Mid(7, cmdLine.GetLength() - 7); profile.TrimLeft(); profile.TrimRight(); SettingVec settings =ProfileDlg::GetProfile(profile); CAntiSpySettings xpas; for(int i=0; i<settings.size(); ++i) { SETTING set = settings[i]; const SETTING_STATE state= xpas.TestSetting(set.settingID); if(state == NON_EXISTENT) continue; BOOL actChecked = state == ACTIVE || state == ACTIVE_NO_PERMISSION; if(set.checked != actChecked) { if(set.checked) xpas.DisableSetting(set.settingID); else xpas.EnableSetting(set.settingID); } } return true; } else if(wcscmp(m_lpCmdLine,_T("/check")) == 0) { CString profileName; SettingVec settings; int id = ProfileDlg::GetStartProfile();// - ID_PROFILE_SYSTEM_DEFAULT - 1; if(id == ID_PROFILE_SYSTEM_DEFAULT) { profileName.LoadString(IDS_PROFILE_SYSTEM_DEFAULT); settings = ProfileDlg::GetProfile(PROFILE_SYSTEM_DEFAULT_ON, PROFILE_SYSTEM_DEFAULT_OFF); //CheckProfile(PROFILE_SYSTEM_DEFAULT_ON, PROFILE_SYSTEM_DEFAULT_OFF, wParam); } else if(id == ID_PROFILE_SUGGESTED) { profileName.LoadString(IDS_PROFILE_SUGGESTED); settings = ProfileDlg::GetProfile(PROFILE_SUGGESTED_ON, PROFILE_SUGGESTED_OFF); } else if(id == ID_PROFILE_WINDOWS_UPDATE) { profileName.LoadString(IDS_PROFILE_WINDOWS_UPDATE); settings = ProfileDlg::GetProfile(PROFILE_WINDOWS_UPDATE_ON, PROFILE_WINDOWS_UPDATE_OFF); } else { id = id - ID_PROFILE_SYSTEM_DEFAULT - 1; ProfileDlg::StringVec profiles = ProfileDlg::GetExistingProfiles(); //do check, if id is out of range if(id < 0 || profiles.size() < id) { return false; } settings = ProfileDlg::GetProfile(profiles[id]); profileName = profiles[id]; } CAntiSpySettings xpas; SettingVec bad_settings; int cnt = 0; bool needsAdmin = false; for(int i = 0; i < settings.size(); ++i) { SETTING set = settings[i]; const SETTING_STATE state= xpas.TestSetting(set.settingID); if(state == NON_EXISTENT) continue; BOOL actChecked = state == ACTIVE || state == ACTIVE_NO_PERMISSION; if(set.checked != actChecked) { if(state == ACTIVE_NO_PERMISSION || state == INACTIVE_NO_PERMISSION) needsAdmin = true; //++cnt; bad_settings.push_back(set); } } if(bad_settings.size() > 0) { //inform the user that some settings do not comply to the selected profile CCheckProfileDlg dlg(profileName, bad_settings, needsAdmin); dlg.DoModal(); } return false; } else if(wcscmp(m_lpCmdLine,_T("/?")) == 0) { CCMDLineDlg cmd; cmd.DoModal(); return false; } else if (m_lpCmdLine[0] != _T('\0')) { CAntiSpySettings settings; std::wstringstream cmdStr; cmdStr<<m_lpCmdLine; while (!cmdStr.eof()) { std::wstring s; cmdStr>>s; int val = strToValue<int>(s); if(val<((-1)*ITEMCOUNT)||val>ITEMCOUNT) { if(s.at(0) == 'l') { std::wstring str = s.substr(1); unsigned int limit = strToValue<unsigned int>(str); ConnectionLimit cl; TCHAR windir[MAX_PATH]; GetWindowsDirectory(windir, MAX_PATH); wcscat(windir,DIR_LOC); if(cl.GetBuildID(windir)!=0) cl.WriteConnections(limit); } else { CString err; err.Format(_T("You mistyped some of the commandline aguments!\nThe wrong argument is %s"),s); AfxMessageBox(err); return false; } } if(val>=0 && val<=ITEMCOUNT) { val=abs(val); settings.DisableSetting(val); } else if(val<=0 && val>=((-1)*ITEMCOUNT)) { val=abs(val); settings.EnableSetting(val); } } return false; }
void FuzzwinAlgorithm::callPintool() { // ligne de commande pour appel de PIN avec l'entree en cours std::string cmdLine(this->getCmdLinePintool()); // mise à zéro de la formule _formula.erase(); STARTUPINFO si; PROCESS_INFORMATION pi; ZeroMemory(&si, sizeof(si)); ZeroMemory(&pi, sizeof(pi)); si.cb = sizeof(si); if (CreateProcess(nullptr, (LPSTR) cmdLine.c_str(), NULL, // process security attributes NULL, // primary thread security attributes TRUE, // handles are inherited CREATE_NO_WINDOW, // creation flags NULL, // use parent's environment NULL, // use parent's current directory &si, &pi)) { /***********************/ /** CONNEXION AU PIPE **/ /***********************/ BOOL fSuccess = ConnectNamedPipe(_hPintoolPipe, NULL); if (!fSuccess && GetLastError() != ERROR_PIPE_CONNECTED) { this->logTimeStamp(); this->log("erreur de connexion au pipe FuzzWin GLE=" + std::to_string(GetLastError())); this->logEndOfLine(); return; // formule vide } // envoi dans le pipe du chemin vers l'entrée étudiée if (EXIT_FAILURE == sendArgumentToPintool(_pCurrentInput->getFilePath())) { return; // formule vide } /********************************************************/ /** ATTENTE DE L'ARRIVEE DES DONNEES DEPUIS LE PINTOOL **/ /********************************************************/ char buffer[512]; // buffer de récupération des données DWORD cbBytesRead = 0; // lecture successive de blocs de 512 octets // et construction progressive de la formule do { fSuccess = ReadFile(_hPintoolPipe, // pipe handle &buffer[0], // buffer to receive reply 512, // size of buffer &cbBytesRead, // number of bytes read NULL); // not overlapped if ( ! fSuccess && (GetLastError() != ERROR_MORE_DATA) ) break; // ajout des données lues au resultat _formula.append(&buffer[0], cbBytesRead); } while (!fSuccess); // repetition si ERROR_MORE_DATA // deconnexion du pipe DisconnectNamedPipe(_hPintoolPipe); // attente de la fermeture de l'application WaitForSingleObject(pi.hProcess, INFINITE); // recupération du code de retour du pintool // (NON ENCORE IMPLEMENTE) DWORD exitCode = 0; GetExitCodeProcess(pi.hProcess, &exitCode); // fermeture des handles processus et thread CloseHandle(pi.hProcess); CloseHandle(pi.hThread); // si option 'keepfiles' ou 'traceonly': sauvegarde de la formule (extension .smt2) if (_keepFiles || _traceOnly) { std::ofstream ofs(_pCurrentInput->getLogFile()); // entete (version pin Z3 etc) et nom de l'entrée ofs << infoHeader << '\n'; ofs << "; Fichier instrumenté : "; ofs << _pCurrentInput->getFileName(); // ajout de l'arbre généalogique (si objet non-root et mode verbeux) CInput *pFather = _pCurrentInput->getFather(); if (_verbose && pFather) { ofs << '('; do // boucle récursive de déclaration des parents de chaque fichier { ofs << " <- " << pFather->getFileName(); pFather = pFather->getFather(); } while (pFather); ofs << ')'; } ofs << "\n\n"; // configuration du solveur ofs << solverConfig; ofs << "\n\n"; // formule brute smt2 ofs << _formula; ofs << "\n\n"; // commandes de lancement et de récupération des résultats ofs << "(check-sat)\n(get-model)\n"; ofs.close(); } } else { this->logVerboseTimeStamp(); this->logVerbose("erreur process FuzzWin GLE=" + std::to_string(GetLastError())); this->logVerboseEndOfLine(); } }
static int jaxerMain(int argc, char **argv) { nsresult rv; int ret = 0; nsCOMPtr<nsIPrefBranch> prefBranch(do_GetService(NS_PREFSERVICE_CONTRACTID)); /* Activate our JavaScript Console listener */ AutoConsoleListener aCL; /* Get the commandport, we use it as a lock for logging */ char * sLock = "4328"; for (int i = 1; i < argc-1; ++i) { if (!strcmp(argv[i], "-commandport") || !strcmp(argv[i], "--commandport")) { sLock = argv[i+1]; } } // Let's Init the logger so we can write log msgs. rv = gJaxerLog.Init(sLock); if (NS_FAILED(rv)) { fprintf(stderr, "Cannot init aptCoreTrace for jaxer logging. error=0x%x", rv); return 1; } gJaxerLog.Log(eDEBUG, "Jaxer: Log inited."); // We need to do this (seemingly superfluous operation) in order to make the // Mozilla core aware that this thread is the "main" thread. If we don't do // an operation like this here, Mozilla will cough up assertions later when // we attempt to load the HTML page. nsCOMPtr<nsIURI> url; rv = NS_NewURI(getter_AddRefs(url), "resource://framework"); if (NS_FAILED(rv)) { gJaxerLog.Log(eERROR, "Create new URI for resource://framework failed: rv=0x%x", rv); return 1; } if (!prefBranch) { gJaxerLog.Log(eERROR, "Get PrefService failed."); return 1; } { nsCOMPtr<nsIFile> file; PRBool exists = PR_FALSE; rv = NS_GetSpecialDirectory(NS_APP_PREF_DEFAULTS_50_DIR, getter_AddRefs(file)); NS_ENSURE_SUCCESS(rv, 1); rv = file->Append(NS_LITERAL_STRING("Jaxer_prefs.js")); NS_ENSURE_SUCCESS(rv, 1); rv = file->Exists(&exists); if (NS_FAILED(rv) || !exists) { nsString aMsg; file->GetPath(aMsg); gJaxerLog.Log(eINFO, "Preferences file (%s) could not be located.", NS_ConvertUTF16toUTF8(aMsg).get()); return 1; } gJaxerLog.Log(eTRACE, "Loaded Jaxer_prefs.js"); PRInt32 type; rv = prefBranch->GetPrefType("Jaxer.HTML.Tag.Monitor.1", &type); if ( NS_FAILED(rv) || type != nsIPrefBranch::PREF_STRING) { nsString aMsg; file->GetPath(aMsg); gJaxerLog.Log(eINFO, "Jaxer preferences were not found in file (%s).", NS_ConvertUTF16toUTF8(aMsg).get()); return 1; } } /* Initialize preference observer */ AutoPrefObserver apo; /* Send startup event */ nsCOMPtr<nsIObserver> startupNotifier (do_CreateInstance(NS_APPSTARTUPNOTIFIER_CONTRACTID, &rv)); startupNotifier->Observe(nsnull, APPSTARTUP_TOPIC, nsnull); /* Initialize command line */ nsCOMPtr<nsICommandLineRunner> cmdLine(do_CreateInstance("@mozilla.org/toolkit/command-line;1")); if (!cmdLine) { gJaxerLog.Log(eERROR, "Failed to create nsICommandLineRunner"); return 1; } nsCOMPtr<nsIFile> workingDir; rv = NS_GetSpecialDirectory(NS_OS_CURRENT_WORKING_DIR, getter_AddRefs(workingDir)); if (NS_FAILED(rv)) { gJaxerLog.Log(eERROR, "Get current working directory failed: rv=0x%x", rv); return 1; } rv = cmdLine->Init(argc, argv, workingDir, nsICommandLine::STATE_INITIAL_LAUNCH); if (NS_FAILED(rv)) { gJaxerLog.Log(eERROR, "CommandLine init failed: rv=0x%x", rv); ret = 1; return 1; } rv = cmdLine->Run(); if (NS_FAILED(rv)) { gJaxerLog.Log(eERROR, "CommandLine Run failed: rv=0x%x", rv); return 1; } // Init on main thread - same reasons as above { nsCOMPtr<nsICertOverrideService> overrideService = do_GetService(NS_CERTOVERRIDE_CONTRACTID); } #if defined(MOZ_WIDGET_GTK2) gtk_init_check(&argc, &argv); #endif #if defined(JAXER_PRO_BUILD) char sUser[400]; if (validateLicense(sUser) != PR_TRUE) { gJaxerLog.Terminate(); return 1; } #endif //rv = FCGXStream::Startup(argc, argv); if (JaxerStartup(argc, argv) != 0) { gJaxerLog.Log(eERROR, "Jaxer: Failed to establish communication with manager."); return 1; } gJaxerLog.Log(eTRACE, "Inited manager communication"); // Set WebConfig HTTPStream::SetWebServerConfigFile(gWebServerConfig); nsCOMPtr<aptIDocumentFetcherService> dfs; nsCOMPtr<aptIManagerCmdService> mcs; nsCOMPtr<nsIRunnable> aEvent; nsCOMPtr<nsIThread> aRunner; nsIThread *MainThread; dfs = do_GetService("@aptana.com/httpdocumentfetcher;1", &rv); rv = dfs->Init(); if (NS_FAILED(rv)) { gJaxerLog.Log(eERROR, "Init aptIDocumentFetcherService failed: rv=0x%x", rv); ret = 1; goto Done; } gJaxerLog.Log(eTRACE, "Inited aptIDocumentFetcherService"); mcs = do_GetService("@aptana.com/managercmdservice;1", &rv); rv = mcs->Init((PRInt32)g_pipe); if (NS_FAILED(rv)) { gJaxerLog.Log(eERROR, "Init aptIManagerCmdService failed: rv=0x%x", rv); ret = 1; goto Done; } /* Jaxer has started up! */ #if defined(JAXER_PRO_BUILD) gJaxerLog.Log(eNOTICE, "[Jaxer/%s -- starting] %s", JAXER_BUILD_ID, sUser); #else gJaxerLog.Log(eNOTICE, "[Jaxer/%s -- starting] Community Edition, licensed by Aptana, Inc. under GPL/APL (see LICENSE.TXT)", JAXER_BUILD_ID); #endif aEvent = new aptMgrCmdReader(g_pipe); if (!aEvent) { //return NS_ERROR_OUT_OF_MEMORY; ret = 1; goto Done; } rv = NS_NewThread(getter_AddRefs(aRunner), aEvent); if (NS_FAILED(rv)) { ret = 1; goto Done; } // Start waiting for incoming requests MainThread = NS_GetCurrentThread(); while (gJaxerState != eEXITING) { gJaxerLog.Log(eTRACE, "Waiting for next request."); PRBool processedEvent; rv = MainThread->ProcessNextEvent(PR_TRUE, &processedEvent); if (NS_FAILED(rv)) { //Process event failed } if (!processedEvent) { //Process event failed } } Done: gJaxerLog.Log(eTRACE, "Main done. Wait for thread"); gJaxerState = eEXITING; #ifdef _WIN32 CloseHandle(g_pipe); #else close(g_pipe); #endif if (aRunner) aRunner->Shutdown(); gJaxerLog.Log(eTRACE, "Main done. Thread returned"); gJaxerLog.Terminate(); //FCGXStream::Cleanup(); return ret; }
bool Program::ThreadMonitor::spawnProcess() { SECURITY_ATTRIBUTES saAttr; // Set the bInheritHandle flag so pipe handles are inherited. saAttr.nLength = (uint32) sizeof(SECURITY_ATTRIBUTES); saAttr.bInheritHandle = TRUE; saAttr.lpSecurityDescriptor = nullptr; if (not pipe(channels.outfd, saAttr, "stdout")) return false; if (not pipe(channels.infd, saAttr, "stdin")) return false; if (not pipe(channels.errd, saAttr, "stderr")) return false; #if _WIN32_WINNT >= 0x0600 // Prepare inherited handle list for STARTUPINFOEX LPPROC_THREAD_ATTRIBUTE_LIST attrList = nullptr; HANDLE inheritedHandles[3] = { channels.outfd[0], channels.infd[1], channels.errd[1], }; fillProcAttributeList(inheritedHandles, attrList); // Set up members of the STARTUPINFOEX structure. // This structure specifies the handles for redirection. // It is necessary to use the EX version, otherwise _all_ inheritable // handles in the program are inherited by the child. STARTUPINFOEX startInfo; ::ZeroMemory(&startInfo, sizeof(STARTUPINFOEX)); startInfo.StartupInfo.cb = (uint32) sizeof(STARTUPINFOEX); startInfo.lpAttributeList = attrList; startInfo.StartupInfo.dwFlags |= STARTF_USESTDHANDLES; startInfo.StartupInfo.hStdOutput = channels.infd[1]; startInfo.StartupInfo.hStdInput = channels.outfd[0]; startInfo.StartupInfo.hStdError = channels.errd[1]; #else STARTUPINFO startInfo; ::ZeroMemory(&startInfo, sizeof(STARTUPINFO)); startInfo.cb = (uint32) sizeof(STARTUPINFO); startInfo.dwFlags |= STARTF_USESTDHANDLES; startInfo.hStdOutput = channels.infd[1]; startInfo.hStdInput = channels.outfd[0]; startInfo.hStdError = channels.errd[1]; #endif // _WIN32_WINNT < 0x0600 // Set up members of the PROCESS_INFORMATION structure. PROCESS_INFORMATION winProcInfo; ::ZeroMemory(&winProcInfo, sizeof(PROCESS_INFORMATION)); String cmd; { String tmpstr = procinfo.executable; tmpstr.replace("\"", "\\\""); cmd << '"' << tmpstr << '"'; uint32_t count = static_cast<uint32_t>(procinfo.arguments.size()); for (uint32_t i = 0; i != count; ++i) { tmpstr = procinfo.arguments[i]; tmpstr.replace("\"", "\\\""); cmd << " \"" << tmpstr << '"'; } } WString cmdLine(cmd); // Getting the start time of execution pStartTime = currentTime(); // Create the child process. // ** FORK ** bool success = (0 != ::CreateProcessW(nullptr, cmdLine.data(), // command line nullptr, // process security attributes nullptr, // primary thread security attributes true, // handles are inherited (necessary for STARTF_USESTDHANDLES) 0, // creation flags nullptr, // use parent's environment nullptr, // use parent's current directory &startInfo, // STARTUPINFO pointer &winProcInfo)); // receives PROCESS_INFORMATION // Close streams passed to the child process closeHD(channels.outfd[0]); closeHD(channels.infd[1]); closeHD(channels.errd[1]); // If an error occurs, give up if (!success) { //DWORD error = ::GetLastError(); //std::wcerr << L"Fork failed with:\n"; //if (error) //{ // LPVOID lpMsgBuf = nullptr; // DWORD bufLen = ::FormatMessageW( // FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, // nullptr, error, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // (LPTSTR) &lpMsgBuf, 1024, nullptr); // if (bufLen) // { // LPCTSTR lpMsgStr = (LPCTSTR)lpMsgBuf; // std::wcerr << TEXT(" ") << lpMsgStr << std::endl; // ::HeapFree(::GetProcessHeap(), 0, lpMsgBuf); // return false; // } //} //std::wcerr << " Unknown error !" << std::endl; return false; } processHandle = winProcInfo.hProcess; threadHandle = winProcInfo.hThread; procinfo.processID = (int)winProcInfo.dwProcessId; procinfo.processInput = _open_osfhandle(reinterpret_cast<intptr_t>(channels.infd[0]), 0); // timeout for the sub process procinfo.createThreadForTimeoutWL(); return true; }
int MprTestSession::setupTests(MprTestResult *result, Mpr *mpr, int argc, char *argv[], char *switches) { char switchBuf[80]; char *programName, *argp; int errflg, c, i, l; #if BLD_FEATURE_LOG char *logSpec; #endif this->mpr = mpr; programName = mprGetBaseName(argv[0]); errflg = 0; #if BLD_FEATURE_LOG logSpec = "stdout:1"; logger = new MprLogToFile(); #endif switchBuf[0] = '\0'; mprStrcat(switchBuf, sizeof(switchBuf), 0, "cDeg:i:l:n:msT:t:v?", switches, (void*) 0); MprCmdLine cmdLine(argc, argv, switchBuf); while ((c = cmdLine.next(&argp)) != EOF) { switch(c) { case 'c': result->setContinueOnFailures(1); break; case 'D': mprSetDebugMode(1); result->setDebugOnFailures(1); break; case 'e': needEventsThread = 1; break; case 'g': testGroups->parse(argp); break; case 'i': iterations = atoi(argp); break; case 'l': #if BLD_FEATURE_LOG logSpec = argp; #endif break; case 'n': l = atoi(argp); if (l == 0) { sessionLevel = MPR_BASIC; } else if (l == 1) { sessionLevel = MPR_THOROUGH; } else { sessionLevel = MPR_DEDICATED; } break; case 'm': mprRequestMemStats(1); break; case 's': result->setSingleStep(1); break; case 't': i = atoi(argp); if (i <= 0 || i > 100) { mprFprintf(MPR_STDERR, "%s: Bad number of threads (0-100)\n", programName); exit(2); } #if BLD_FEATURE_MULTITHREAD numThreads = i; #endif break; case 'T': #if BLD_FEATURE_MULTITHREAD poolThreads = atoi(argp); #endif break; case 'v': verbose++; break; default: // // Ignore args we don't understand // break; case '?': errflg++; break; } } if (errflg) { mprFprintf(MPR_STDERR, "usage: %s [-cDemsv] [-g groups] [-i iterations] " "[-l logSpec] [-n testLevel] [-T poolThreads] [-t threads]\n", programName); exit(2); } #if !BLD_FEATURE_MULTITHREAD needEventsThread = 0; #endif #if BLD_FEATURE_LOG mpr->addListener(logger); mpr->setLogSpec(logSpec); #endif initSignals(); this->argc = argc; this->argv = argv; this->firstArg = cmdLine.firstArg(); #if BLD_FEATURE_MULTITHREAD mpr->setMaxPoolThreads(poolThreads); #endif if (mpr->start(needEventsThread ? MPR_SERVICE_THREAD : 0) < 0) { return MPR_ERR_CANT_INITIALIZE; } result->adjustThreadCount(numThreads); result->setVerbosity(verbose); if (result->getListenerCount() == 0) { result->addListener(new MprTestListener("__default__")); } if (verbose) { mprFprintf(MPR_STDOUT, "Testing: iterations %d, threads %d, pool %d, service thread %d\n", iterations, numThreads, poolThreads, needEventsThread); } // // Use current session object for the main thread // sessions = (MprTestSession**) mprMalloc(sizeof(MprTestSession*) * numThreads); sessions[0] = this; if (sessions[0]->initializeClasses(result) < 0) { exit(3); } #if BLD_FEATURE_MULTITHREAD // // Now clone this session object for all other threads // for (i = 1; i < numThreads; i++) { char tName[64]; sessions[i] = this->newSession(); sessions[i]->setResult(result); sessions[i]->cloneSettings(this); mprSprintf(tName, sizeof(tName), "test.%d", i); } #endif return 0; }
int main(int argc, char *argv[]) { try { ConfigChecker cc; cc.addIntegerParam("verboseLevel", false, true, "level of the verbose information 0=no verbose, 1=normal, 2=more"); cc.addStringParam("config", OPTIONAL, ARG_REQUIRED, "Train config file name "); cc.addStringParam("configTest", OPTIONAL, ARG_REQUIRED, "Unsupervised adaptation config file name "); cc.addStringParam("targetIdList", MANDATORY, ARG_REQUIRED, "targets list"); cc.addStringParam("inputWorldFilename", MANDATORY, ARG_REQUIRED, "world model"); cc.addStringParam("testsIdList", MANDATORY, ARG_REQUIRED, "tests list"); cc.addBooleanParam("NISTprotocol", MANDATORY, ARG_REQUIRED, "true to follow unsupervised NIST protocol, false to follow BATCH protocol"); cc.addBooleanParam("WMAP", false, false, "NO MORE USED, Choice of WMAP (one Gaussian) to compute trial feature server weights, need other param : MUtarget,MUimp,SIGMAtarget and SIGMAIMP;TAR weight and IMPweight, thrMin and thrMax"); cc.addBooleanParam("WMAPGMM", false, false, "Choice of WMAP GMM to compute trial feature server weights, param needed : two gmm of scores, TARScoresModel and NONScoresModel. Need also a value for Priors update, initPriorImp (10) and initPriorTar(1) "); cc.addBooleanParam("TNORM", false, false, " TNORM scores before computing WMAP, need gmm of Tnormed scores and a param : impScoreFile, score file for TNORM and testsNames, the list of trial segments "); cc.addBooleanParam("FAST", false, false, "FAST MODE : For computing LLR use top ten info files AND FOR FUSING EM MODELS WHEN UPDATING"); cc.addBooleanParam("FromResFile", false, false, " Avoid to compute LLR for WMAP computing, search LLR in a score file, param needed: InputResFilename"); cc.addBooleanParam("CrossValid", false, false, " compute LLR of a percentage of train data on a model learnt on a percentage of train data AverageIt times and return the best ML (one iter) model, need AverageIt, SelectedTrain."); cc.addBooleanParam("Oracle", false, false, " For Oracle (supervised) experiments, need targetTests to perform adaptation on target tests only"); cc.addBooleanParam("REGRESS", false, false, "Use logistic regression for adaptation weights computing, need BETA and THETA"); cc.addIntegerParam("MaxMixturesCount", false, true, "max mixtures stored in the mixture server (in memory)"); cc.addIntegerParam("LLKthreshold", false, true, "thresholds the results of LLR in order to avoid problem in WMAP computing"); cc.addStringParam("computeLLKWithTopDistribs", true, true, "PARTIAL/COMPLETE: will compute LLK with topdistribs. COMPLETE: add world LLK to client LLK, PARTIAL: just keeps the topDistrib LLK"); cc.addIntegerParam("topDistribsCount ", false, true, "Number of distrib to approximate complete LLK"); cc.addStringParam("InfoExtension", false, true, "Extension for top ten info files"); cc.addStringParam("InfoPath", false, true, "Path for top ten info files"); cc.addFloatParam("OptimalScore", false, true, "Used for updating priors (fixedPriors == false), if LLR is superior add one for target count, else add one for impostors count "); cc.addBooleanParam("SegMode", MANDATORY, ARG_REQUIRED, "For adaptation by segments (for the moment support only 3 frame segments)"); cc.addIntegerParam("mixtureDistribCountForGMMScores", false, true, "NUMBER OF GAUSSIAN IN SCORES GMM"); cc.addBooleanParam("ScoresByTarget", MANDATORY, ARG_REQUIRED," IF SET TO TRUE TWO GMM (TAR AND NON) ARE NEEDED BY CLIENT (idcinet.tar and idclient.non)"); cc.addStringParam("TARListFilename", false, true, "List of the TAR model id (used when ScoresByTarget is set to true)"); cc.addIntegerParam("ResetNbAdapt ", false, true, "Max number of tests used for adaptation"); Config tmp; CmdLine cmdLine(argc, argv); if (cmdLine.displayHelpRequired()) { // --help cout << "************************************" << endl; cout << "********** SpkAdapt.exe *********" << endl; cout << "************************************" << endl; cout << endl; cout << "Unsupervised adaptation process, update model using test trial information following NIST protocol" << endl; cout << "" << endl; cout << endl; cout << "Command Line example: " << endl; cout << "SpkAdapt.exe --config cfg/TrainTarget.cfg --configTest cfg/TrainTest.cfg --inputWorldFilename world --targetIdList ./lst/id.lst --testsIdList ./lst/tests.list --outputLLRFilename file --NISTprotocol true" << endl; cout << cc.getParamList() << endl; } else { cmdLine.copyIntoConfig(tmp); Config config(tmp.getParam("config")); cmdLine.copyIntoConfig(config); Config configTest(tmp.getParam("configTest")); if (config.existsParam("verbose")) verbose = config.getParam("verbose").toBool(); else verbose = false; bool segmode=false; if (config.existsParam("SegMode")) segmode = config.getParam("SegMode").toBool(); if (verbose) verboseLevel = 1; else verboseLevel = 0; if (config.existsParam("verboseLevel")) verboseLevel = config.getParam("verboseLevel").toLong(); if (verboseLevel > 0) verbose = true; TrainTargetAdapt(config, configTest); // Launch process } } catch(alize::Exception & e) { cout << e.toString() << endl; } return 0; }
int main(int _argc, const char* _argv[]) { bx::CommandLine cmdLine(_argc, _argv); const char* filePath = cmdLine.findOption('f'); if (NULL == filePath) { help("Input file name must be specified."); return EXIT_FAILURE; } const char* outFilePath = cmdLine.findOption('o'); if (NULL == outFilePath) { help("Output file name must be specified."); return EXIT_FAILURE; } float scale = 1.0f; const char* scaleArg = cmdLine.findOption('s', "scale"); if (NULL != scaleArg) { scale = (float)atof(scaleArg); } cmdLine.hasArg(s_obbSteps, '\0', "obb"); s_obbSteps = bx::uint32_min(bx::uint32_max(s_obbSteps, 1), 90); uint32_t packNormal = 0; cmdLine.hasArg(packNormal, '\0', "packnormal"); uint32_t packUv = 0; cmdLine.hasArg(packUv, '\0', "packuv"); bool ccw = cmdLine.hasArg("ccw"); bool flipV = cmdLine.hasArg("flipv"); bool hasTangent = cmdLine.hasArg("tangent"); FILE* file = fopen(filePath, "r"); if (NULL == file) { printf("Unable to open input file '%s'.", filePath); exit(EXIT_FAILURE); } int64_t parseElapsed = -bx::getHPCounter(); int64_t triReorderElapsed = 0; uint32_t size = (uint32_t)fsize(file); char* data = new char[size+1]; size = (uint32_t)fread(data, 1, size, file); data[size] = '\0'; fclose(file); // https://en.wikipedia.org/wiki/Wavefront_.obj_file Vector3Array positions; Vector3Array normals; Vector3Array texcoords; Index3Map indexMap; TriangleArray triangles; GroupArray groups; uint32_t num = 0; Group group; group.m_startTriangle = 0; group.m_numTriangles = 0; char commandLine[2048]; uint32_t len = sizeof(commandLine); int argc; char* argv[64]; const char* next = data; do { next = tokenizeCommandLine(next, commandLine, len, argc, argv, countof(argv), '\n'); if (0 < argc) { if (0 == strcmp(argv[0], "#") ) { if (2 < argc && 0 == strcmp(argv[2], "polygons") ) { } } else if (0 == strcmp(argv[0], "f") ) { Triangle triangle; for (uint32_t edge = 0, numEdges = argc-1; edge < numEdges; ++edge) { Index3 index; index.m_texcoord = -1; index.m_normal = -1; index.m_vertexIndex = -1; char* vertex = argv[edge+1]; char* texcoord = strchr(vertex, '/'); if (NULL != texcoord) { *texcoord++ = '\0'; char* normal = strchr(texcoord, '/'); if (NULL != normal) { *normal++ = '\0'; index.m_normal = atoi(normal)-1; } index.m_texcoord = atoi(texcoord)-1; } index.m_position = atoi(vertex)-1; uint64_t hash0 = index.m_position; uint64_t hash1 = uint64_t(index.m_texcoord)<<20; uint64_t hash2 = uint64_t(index.m_normal)<<40; uint64_t hash = hash0^hash1^hash2; std::pair<Index3Map::iterator, bool> result = indexMap.insert(std::make_pair(hash, index) ); if (!result.second) { Index3& oldIndex = result.first->second; BX_UNUSED(oldIndex); BX_CHECK(oldIndex.m_position == index.m_position && oldIndex.m_texcoord == index.m_texcoord && oldIndex.m_normal == index.m_normal , "Hash collision!" ); } switch (edge) { case 0: case 1: case 2: triangle.m_index[edge] = hash; if (2 == edge) { if (ccw) { std::swap(triangle.m_index[1], triangle.m_index[2]); } triangles.push_back(triangle); } break; default: if (ccw) { triangle.m_index[2] = triangle.m_index[1]; triangle.m_index[1] = hash; } else { triangle.m_index[1] = triangle.m_index[2]; triangle.m_index[2] = hash; } triangles.push_back(triangle); break; } } } else if (0 == strcmp(argv[0], "g") ) { EXPECT(1 < argc); group.m_name = argv[1]; } else if (*argv[0] == 'v') { group.m_numTriangles = (uint32_t)(triangles.size() ) - group.m_startTriangle; if (0 < group.m_numTriangles) { groups.push_back(group); group.m_startTriangle = (uint32_t)(triangles.size() ); group.m_numTriangles = 0; } if (0 == strcmp(argv[0], "vn") ) { Vector3 normal; normal.x = (float)atof(argv[1]); normal.y = (float)atof(argv[2]); normal.z = (float)atof(argv[3]); normals.push_back(normal); } else if (0 == strcmp(argv[0], "vp") ) { static bool once = true; if (once) { once = false; printf("warning: 'parameter space vertices' are unsupported.\n"); } } else if (0 == strcmp(argv[0], "vt") ) { Vector3 texcoord; texcoord.x = (float)atof(argv[1]); texcoord.y = 0.0f; texcoord.z = 0.0f; switch (argc) { case 4: texcoord.z = (float)atof(argv[3]); // fallthrough case 3: texcoord.y = (float)atof(argv[2]); break; default: break; } texcoords.push_back(texcoord); } else { float px = (float)atof(argv[1]); float py = (float)atof(argv[2]); float pz = (float)atof(argv[3]); float pw = 1.0f; if (argc > 4) { pw = (float)atof(argv[4]); } float invW = scale/pw; px *= invW; py *= invW; pz *= invW; Vector3 pos; pos.x = px; pos.y = py; pos.z = pz; positions.push_back(pos); } } else if (0 == strcmp(argv[0], "usemtl") ) { std::string material(argv[1]); if (material != group.m_material) { group.m_numTriangles = (uint32_t)(triangles.size() ) - group.m_startTriangle; if (0 < group.m_numTriangles) { groups.push_back(group); group.m_startTriangle = (uint32_t)(triangles.size() ); group.m_numTriangles = 0; } } group.m_material = material; } // unsupported tags // else if (0 == strcmp(argv[0], "mtllib") ) // { // } // else if (0 == strcmp(argv[0], "o") ) // { // } // else if (0 == strcmp(argv[0], "s") ) // { // } } ++num; } while ('\0' != *next); group.m_numTriangles = (uint32_t)(triangles.size() ) - group.m_startTriangle; if (0 < group.m_numTriangles) { groups.push_back(group); group.m_startTriangle = (uint32_t)(triangles.size() ); group.m_numTriangles = 0; } delete [] data; int64_t now = bx::getHPCounter(); parseElapsed += now; int64_t convertElapsed = -now; struct GroupSortByMaterial { bool operator()(const Group& _lhs, const Group& _rhs) { return _lhs.m_material < _rhs.m_material; } }; std::sort(groups.begin(), groups.end(), GroupSortByMaterial() ); bool hasColor = false; bool hasNormal; bool hasTexcoord; { Index3Map::const_iterator it = indexMap.begin(); hasNormal = -1 != it->second.m_normal; hasTexcoord = -1 != it->second.m_texcoord; if (!hasTexcoord && texcoords.size() == positions.size() ) { hasTexcoord = true; for (Index3Map::iterator it = indexMap.begin(), itEnd = indexMap.end(); it != itEnd; ++it) { it->second.m_texcoord = it->second.m_position; } } if (!hasNormal && normals.size() == positions.size() ) { hasNormal = true; for (Index3Map::iterator it = indexMap.begin(), itEnd = indexMap.end(); it != itEnd; ++it) { it->second.m_normal = it->second.m_position; } } } bgfx::VertexDecl decl; decl.begin(); decl.add(bgfx::Attrib::Position, 3, bgfx::AttribType::Float); if (hasColor) { decl.add(bgfx::Attrib::Color0, 4, bgfx::AttribType::Uint8, true); } if (hasTexcoord) { switch (packUv) { default: case 0: decl.add(bgfx::Attrib::TexCoord0, 2, bgfx::AttribType::Float); break; case 1: decl.add(bgfx::Attrib::TexCoord0, 2, bgfx::AttribType::Half); break; } } if (hasNormal) { hasTangent &= hasTexcoord; switch (packNormal) { default: case 0: decl.add(bgfx::Attrib::Normal, 3, bgfx::AttribType::Float); if (hasTangent) { decl.add(bgfx::Attrib::Tangent, 4, bgfx::AttribType::Float); } break; case 1: decl.add(bgfx::Attrib::Normal, 4, bgfx::AttribType::Uint8, true, true); if (hasTangent) { decl.add(bgfx::Attrib::Tangent, 4, bgfx::AttribType::Uint8, true, true); } break; } } decl.end(); uint32_t stride = decl.getStride(); uint8_t* vertexData = new uint8_t[triangles.size() * 3 * stride]; uint16_t* indexData = new uint16_t[triangles.size() * 3]; int32_t numVertices = 0; int32_t numIndices = 0; int32_t numPrimitives = 0; uint8_t* vertices = vertexData; uint16_t* indices = indexData; std::string material = groups.begin()->m_material; PrimitiveArray primitives; bx::CrtFileWriter writer; if (0 != writer.open(outFilePath) ) { printf("Unable to open output file '%s'.", outFilePath); exit(EXIT_FAILURE); } Primitive prim; prim.m_startVertex = 0; prim.m_startIndex = 0; uint32_t positionOffset = decl.getOffset(bgfx::Attrib::Position); uint32_t color0Offset = decl.getOffset(bgfx::Attrib::Color0); uint32_t ii = 0; for (GroupArray::const_iterator groupIt = groups.begin(); groupIt != groups.end(); ++groupIt, ++ii) { for (uint32_t tri = groupIt->m_startTriangle, end = tri + groupIt->m_numTriangles; tri < end; ++tri) { if (material != groupIt->m_material || 65533 < numVertices) { prim.m_numVertices = numVertices - prim.m_startVertex; prim.m_numIndices = numIndices - prim.m_startIndex; if (0 < prim.m_numVertices) { primitives.push_back(prim); } triReorderElapsed -= bx::getHPCounter(); for (PrimitiveArray::const_iterator primIt = primitives.begin(); primIt != primitives.end(); ++primIt) { const Primitive& prim = *primIt; triangleReorder(indexData + prim.m_startIndex, prim.m_numIndices, numVertices, 32); } triReorderElapsed += bx::getHPCounter(); if (hasTangent) { calcTangents(vertexData, numVertices, decl, indexData, numIndices); } write(&writer, vertexData, numVertices, decl, indexData, numIndices, material, primitives); primitives.clear(); for (Index3Map::iterator indexIt = indexMap.begin(); indexIt != indexMap.end(); ++indexIt) { indexIt->second.m_vertexIndex = -1; } vertices = vertexData; indices = indexData; numVertices = 0; numIndices = 0; prim.m_startVertex = 0; prim.m_startIndex = 0; ++numPrimitives; material = groupIt->m_material; } Triangle& triangle = triangles[tri]; for (uint32_t edge = 0; edge < 3; ++edge) { uint64_t hash = triangle.m_index[edge]; Index3& index = indexMap[hash]; if (index.m_vertexIndex == -1) { index.m_vertexIndex = numVertices++; float* position = (float*)(vertices + positionOffset); memcpy(position, &positions[index.m_position], 3*sizeof(float) ); if (hasColor) { uint32_t* color0 = (uint32_t*)(vertices + color0Offset); *color0 = rgbaToAbgr(numVertices%255, numIndices%255, 0, 0xff); } if (hasTexcoord) { float uv[2]; memcpy(uv, &texcoords[index.m_texcoord], 2*sizeof(float) ); if (flipV) { uv[1] = -uv[1]; } bgfx::vertexPack(uv, true, bgfx::Attrib::TexCoord0, decl, vertices); } if (hasNormal) { float normal[4]; vec3Norm(normal, (float*)&normals[index.m_normal]); bgfx::vertexPack(normal, true, bgfx::Attrib::Normal, decl, vertices); } vertices += stride; } *indices++ = (uint16_t)index.m_vertexIndex; ++numIndices; } } if (0 < numVertices) { prim.m_numVertices = numVertices - prim.m_startVertex; prim.m_numIndices = numIndices - prim.m_startIndex; prim.m_name = groupIt->m_name; primitives.push_back(prim); prim.m_startVertex = numVertices; prim.m_startIndex = numIndices; } BX_TRACE("%3d: s %5d, n %5d, %s\n" , ii , groupIt->m_startTriangle , groupIt->m_numTriangles , groupIt->m_material.c_str() ); } if (0 < primitives.size() ) { triReorderElapsed -= bx::getHPCounter(); for (PrimitiveArray::const_iterator primIt = primitives.begin(); primIt != primitives.end(); ++primIt) { const Primitive& prim = *primIt; triangleReorder(indexData + prim.m_startIndex, prim.m_numIndices, numVertices, 32); } triReorderElapsed += bx::getHPCounter(); if (hasTangent) { calcTangents(vertexData, numVertices, decl, indexData, numIndices); } write(&writer, vertexData, numVertices, decl, indexData, numIndices, material, primitives); } printf("size: %d\n", uint32_t(writer.seek() ) ); writer.close(); delete [] indexData; delete [] vertexData; now = bx::getHPCounter(); convertElapsed += now; printf("parse %f [s]\ntri reorder %f [s]\nconvert %f [s]\n# %d, g %d, p %d, v %d, i %d\n" , double(parseElapsed)/bx::getHPFrequency() , double(triReorderElapsed)/bx::getHPFrequency() , double(convertElapsed)/bx::getHPFrequency() , num , uint32_t(groups.size() ) , numPrimitives , numVertices , numIndices ); return EXIT_SUCCESS; }
static gint OssoDbusCallback(const gchar *interface, const gchar *method, GArray *arguments, gpointer data, osso_rpc_t *retval) { retval->type = DBUS_TYPE_INVALID; // The "top_application" method just wants us to focus the top-most window. if (!strcmp("top_application", method)) { nsCOMPtr<nsIDOMWindow> window; GetMostRecentWindow(NS_LITERAL_STRING("").get(), getter_AddRefs(window)); if (window) window->Focus(); return OSSO_OK; } if (!strcmp("quit", method)) { nsCOMPtr<nsIAppStartup> appService = do_GetService("@mozilla.org/toolkit/app-startup;1"); if (appService) appService->Quit(nsIAppStartup::eForceQuit); return OSSO_OK; } // Other methods can have arguments, which we convert and send to commandline // handlers. nsCOMPtr<nsICommandLineRunner> cmdLine (do_CreateInstance("@mozilla.org/toolkit/command-line;1")); nsCOMPtr<nsIFile> workingDir; NS_GetSpecialDirectory(NS_XPCOM_CURRENT_PROCESS_DIR, getter_AddRefs(workingDir)); char** argv = 0; int argc = 0; // Not all DBus methods pass arguments if (arguments && arguments->len > 0) { // Create argument list with a dummy argv[0] argc = arguments->len + 1; argv = (char**)calloc(1, argc * sizeof(*argv)); // Start at 1 to skip the dummy argv[0] for (int i = 1; i < argc; i++) { osso_rpc_t* entry = (osso_rpc_t*)&g_array_index(arguments, osso_rpc_t, i - 1); if (entry->type != DBUS_TYPE_STRING) continue; argv[i] = strdup(entry->value.s); } } cmdLine->Init(argc, argv, workingDir, nsICommandLine::STATE_REMOTE_AUTO); // Cleanup argument list while (argc) { free(argv[--argc]); } free(argv); cmdLine->Run(); return OSSO_OK; }
bool LaunchUnelevated(int aArgc, wchar_t* aArgv[]) { // We require a single-threaded apartment to talk to Explorer. mscom::STARegion sta; if (!sta.IsValid()) { return false; } // NB: Explorer is a local server, not an inproc server RefPtr<IShellWindows> shellWindows; HRESULT hr = ::CoCreateInstance(CLSID_ShellWindows, nullptr, CLSCTX_LOCAL_SERVER, IID_IShellWindows, getter_AddRefs(shellWindows)); if (FAILED(hr)) { return false; } // 1. Find the shell view for the desktop. _variant_t loc(CSIDL_DESKTOP); _variant_t empty; long hwnd; RefPtr<IDispatch> dispDesktop; hr = shellWindows->FindWindowSW(&loc, &empty, SWC_DESKTOP, &hwnd, SWFO_NEEDDISPATCH, getter_AddRefs(dispDesktop)); if (FAILED(hr)) { return false; } RefPtr<IServiceProvider> servProv; hr = dispDesktop->QueryInterface(IID_IServiceProvider, getter_AddRefs(servProv)); if (FAILED(hr)) { return false; } RefPtr<IShellBrowser> browser; hr = servProv->QueryService(SID_STopLevelBrowser, IID_IShellBrowser, getter_AddRefs(browser)); if (FAILED(hr)) { return false; } RefPtr<IShellView> activeShellView; hr = browser->QueryActiveShellView(getter_AddRefs(activeShellView)); if (FAILED(hr)) { return false; } // 2. Get the automation object for the desktop. RefPtr<IDispatch> dispView; hr = activeShellView->GetItemObject(SVGIO_BACKGROUND, IID_IDispatch, getter_AddRefs(dispView)); if (FAILED(hr)) { return false; } RefPtr<IShellFolderViewDual> folderView; hr = dispView->QueryInterface(IID_IShellFolderViewDual, getter_AddRefs(folderView)); if (FAILED(hr)) { return false; } // 3. Get the interface to IShellDispatch2 RefPtr<IDispatch> dispShell; hr = folderView->get_Application(getter_AddRefs(dispShell)); if (FAILED(hr)) { return false; } RefPtr<IShellDispatch2> shellDisp; hr = dispShell->QueryInterface(IID_IShellDispatch2, getter_AddRefs(shellDisp)); if (FAILED(hr)) { return false; } // 4. Now call IShellDispatch2::ShellExecute to ask Explorer to re-launch us. // Omit argv[0] because ShellExecute doesn't need it in params UniquePtr<wchar_t[]> cmdLine(MakeCommandLine(aArgc - 1, aArgv + 1)); if (!cmdLine) { return false; } _bstr_t exe(aArgv[0]); _variant_t args(cmdLine.get()); _variant_t operation(L"open"); _variant_t directory; _variant_t showCmd(SW_SHOWNORMAL); hr = shellDisp->ShellExecute(exe, args, operation, directory, showCmd); return SUCCEEDED(hr); }
int main( int argc, char* argv[] ) { // the following is mandatory for a console app. bool r = ::wxInitialize(); if ( !r ) { printf( "FATAL ERROR: cannot init wxBase library\n"); return 1; } // write output to STDOUT gs_cout = new wxFFile( stdout ); #if wxCHECK_VERSION( 2, 9, 0 ) // I got compile errors in wxW 2.9 if the string constants of the wxCmdLineDescEntry // class were enclosed in the _T() macro but it seems that wxW 2.8 needs that macro // so I conditionally compile this piece of code wxCmdLineEntryDesc cmdLineDesc[] = { { wxCMD_LINE_SWITCH, "s", "nostop", "do not stop on test\'s failure" }, { wxCMD_LINE_SWITCH, "l", "list", "list test\'s descriptions" }, { wxCMD_LINE_OPTION, "r", "reader", "use the specified flags for the reader", wxCMD_LINE_VAL_STRING }, { wxCMD_LINE_OPTION, "w", "writer", "use the specified flags for the writer", wxCMD_LINE_VAL_STRING }, { wxCMD_LINE_OPTION, "f", "file", "the filename to be read (test #15)", wxCMD_LINE_VAL_STRING }, { wxCMD_LINE_PARAM, NULL, NULL, "test [sub-test]", wxCMD_LINE_VAL_NUMBER, wxCMD_LINE_PARAM_OPTIONAL | wxCMD_LINE_PARAM_MULTIPLE }, { wxCMD_LINE_NONE }, }; wxCmdLineParser cmdLine( cmdLineDesc, argc, argv ); int result = cmdLine.Parse(); if ( result > 0 ) { return 1; // error } else if ( result < 0 ) { return 1; // '-h' } if ( cmdLine.Found( _T("nostop" ))) { gs_nostop = true; } if ( cmdLine.Found( _T("list" ))) { gs_list = true; } wxString flags; // get a option's argument and store in static variables. This arguments are only usefull for test // nr. 2.7 (write to the specified file) and 4.7 (read from the specified file) cmdLine.Found( _T("file"), &gs_fileName ); cmdLine.Found( _T("reader"), &flags ); cmdLine.Found( _T("writer"), &flags ); #else wxCmdLineEntryDesc cmdLineDesc[] = { { wxCMD_LINE_SWITCH, _T("s"), _T("nostop"), _T("do not stop on test\'s failure") }, { wxCMD_LINE_SWITCH, _T("l"), _T("list"), _T("list test\'s descriptions") }, { wxCMD_LINE_OPTION, _T("r"), _T("reader"), _T("use the specified flags for the reader"), wxCMD_LINE_VAL_STRING }, { wxCMD_LINE_OPTION, _T("w"), _T("writer"), _T("use the specified flags for the writer"), wxCMD_LINE_VAL_STRING }, { wxCMD_LINE_OPTION, _T("f"), _T("file"), _T("the filename to be read (test #15)"), wxCMD_LINE_VAL_STRING }, { wxCMD_LINE_PARAM, NULL, NULL, _T("test [sub-test]"), wxCMD_LINE_VAL_NUMBER, wxCMD_LINE_PARAM_OPTIONAL | wxCMD_LINE_PARAM_MULTIPLE }, { wxCMD_LINE_NONE }, }; wxCmdLineParser cmdLine( cmdLineDesc, argc, argv ); int result = cmdLine.Parse(); if ( result > 0 ) { return 1; // error } else if ( result < 0 ) { return 1; // '-h' } if ( cmdLine.Found( _T("nostop" ))) { gs_nostop = true; } if ( cmdLine.Found( _T("list" ))) { gs_list = true; } wxString flags; // get a option's argument and store in static variables. This arguments are only usefull for test // nr. 2.7 (write to the specified file) and 4.7 (read from the specified file) cmdLine.Found( _T("file"), &gs_fileName ); cmdLine.Found( _T("reader"), &flags ); cmdLine.Found( _T("writer"), &flags ); #endif TestStruc testArray[] = { // family #0 does not exist { 0, // m_funcPtr false, // m_auto _T( "family #0 does not exist" ) // m_testDesc }, { 0 },{ 0 },{ 0 },{ 0 },{ 0 },{ 0 },{ 0 },{ 0 },{ 0 }, // family #1 (test1.cpp) { 0, // test #0: description of the family 3, // m_auto _T( "test ctors, dtor and member functions" ) }, { Test1_1, 3, _T( "test if 64-bits INTs is supported" ) }, { Test1_2, 3, _T( "test wxJSONValue ctors and JSON value's types" ) }, { Test1_3, 3, _T( "test the wxJSONValue::AsString() function" ) }, { Test1_4, 3, _T( "test wxJSONValue::GetInfo() and ::Dump() functions" ) }, { Test1_5, 3, _T( "test access methods and other functions" ) }, { 0 },{ 0 },{ 0 },{ 0 }, // family #2 (test1.cpp) { 0, // test #0: description of the family 3, // m_auto _T( "test the wxJSONValue::ISSameAs() function" ) }, { Test2_1, 3, _T( "comparing fundamental types" ) }, { Test2_2, 3, _T( "comparing short, long and long-long" ) }, { Test2_3, 3, _T( "comparing ints and doubles" ) }, { Test2_4, 3, _T( "comparing objects" ) }, { Test2_5, 3, _T( "comparing arrays" ) }, { Test2_6, 3, _T( "comparing objects: special case of NULL values" ) }, { Test2_7, 3, _T( "comparing incompatible types" ) }, { Test2_8, 3, _T( "comparing data structure of positive INT and UINT" ) }, { 0 }, // family #3 (test3.cpp) { 0, // test #0: description of the family 1, // Unicode _T( "testing wxString::ToUTF8() and wxString::FromUTF8()" ) }, { Test3_1, 1, _T( "converting a US-ASCII UTF-8 buffer to wxString" ) }, { Test3_2, 1, _T( "converting a latin,greek,cyrillic UTF-8 buffer to wxString" ) }, { Test3_3, 1, _T( "converting a US-ASCII wxString to UTF-8" ) }, { Test3_4, 1, _T( "converting a latin1.greek,cyrillic wxString to UTF-8" ) }, { Test3_5, 3, _T( "converting UTF-8 buffer to wchar_t and wxString" ) }, { 0 },{ 0 },{ 0 },{ 0 }, // family #4 (test3.cpp) { 0, // test #0: description of the family 3, // m_auto _T( "testing the wxJSONWriter class" ) }, { Test4_1, 3, _T( "wxJSONWriter: a simple write test" ) }, { Test4_2, 3, _T( "wxJSONWriter: test escaped characters" ) }, { Test4_3, 3, _T( "wxJSONWriter: writes empty, invalid and null objects" ) }, { Test4_4, 3, _T( "wxJSONWriter: an array of objects as root" ) }, { Test4_5, 3, _T( "wxJSONWriter: how much simple is wxJSON" ) }, { Test4_6, 3, _T( "wxJSONWriter: test control characters" ) }, { Test4_7, 3, _T( "wxJSONWriter: test an array of doubles" ) }, { Test4_8, 3, _T( "test the printf function with doubles" ) }, { 0 }, // family #5 (test4.cpp) { 0, // test #0: description of the family 3, // m_auto _T( "testing the wxJSONWriter class with various flags" ) }, { Test5_1, 3, _T( "writing an array of values using wxJSONWRITER_NONE" ) }, { Test5_2, 3, _T( "writing an array of values using wxJSONWRITER_STYLED" ) }, { Test5_3, 3, _T( "writing an array of values using wxJSONWRITER_WRITE_COMMENTS" ) }, { Test5_4, 3, _T( "writing an array of values using wxJSONWRITER_NO_LINEFEEDS" ) }, { Test5_5, 3, _T( "writing an array of values using wxJSONWRITER_SPLIT_STRING" ) }, { Test5_6, 3, _T( "writing an array of values using wxJSONWRITER_MULTILINE_STRING" ) }, { // this test fails: see the source code for details Test5_7, 0, _T( "checking the wxJSONWRITER_SPLIT_STRING (long strings)" ) }, { Test5_8, 3, _T( "checking the wxJSONWRITER_SPLIT_STRING (value > column 50" ) }, { Test5_9, 3, _T( "checking the wxJSONWRITER_TAB_INDENT" ) }, // family #6 (test4.cpp) { 0, // test #0: description of the family 1, // m_auto 1=unicode, not applicable in ANSI builds _T( "testing the wxJSONWriter class with Unicode" ) }, { Test6_1, 1, _T( "write to wxString an array of strings from different charsets" ) }, { Test6_2, 1, _T( "writing to stream an array of strings from different charsets" ) }, { 0 },{ 0 },{ 0 },{ 0 },{ 0 },{ 0 },{ 0 }, // family #7 (test5.cpp) { 0, // test #0: description of the family 1, // m_auto 1=unicode, not applicable in ANSI builds _T( "testing the wxJSONReader class (only US-ASCII input)" ) }, { Test7_1, 3, _T( "a well-formed array of values without comments" ) }, { Test7_2, 3, _T( "a well-formed simple key/value pairs of values" ) }, { Test7_3, 3, _T( "an array of escaped string values" ) }, { Test7_4, 3, _T( "nested objects and arrays" ) }, { Test7_5, 3, _T( "many errors and warnings" ) }, { Test7_6, 0, _T( "read the specified JSON text file (need -f option)" ) }, { Test7_7, 3, _T( "missing close object/array on EOF" ) }, { Test7_8, 3, _T( "non-JSON text before and after top-level start/end chars" ) }, { Test7_9, 3, _T( "missing close array character" ) }, // family #8 (test5.cpp) { 0, // test #0: description of the family 3, // m_auto _T( "testing the wxJSONReader class (strings use different charsets)" ) }, { Test8_1, 1, _T( "(Unicode) an array of strings read from a UTF-8 stream" ) }, { Test8_2, 1, _T( "(Unicode) an array of strings read from a wxString" ) }, { Test8_3, 2, _T( "(ANSI) an array of strings read from a UTF-8 stream" ) }, { Test8_4, 2, _T( "(ANSI) an array of strings read from a wxString" ) }, { Test8_5, 2, _T( "(ANSI) read a latin-1 string from UTF-8 buffer" ) }, { 0 },{ 0 },{ 0 },{ 0 }, // family #9 (test6.cpp) { 0, // test #0: description of the family 0, // m_auto (none) _T( "testing the wxJSON reader and writer speed" ) }, { Test9_1, 3, _T( "writing 40,000 values to a string object" ) }, { Test9_2, 3, _T( "writing 40,000 values to a string object" ) }, { Test9_3, 3, _T( "writing 40,000 values to a string object" ) }, { Test9_4, 3, _T( "writing 40,000 values to a string object" ) }, { 0 },{ 0 },{ 0 },{ 0 },{ 0 }, // family #10 (test7.cpp) { 0, // test #0: description of the family 3, // m_auto (all) _T( "test the comment related functions (writer)" ) }, { Test10_1, 3, _T( "test the wxJSONValue's memberfunctions" ) }, { Test10_2, 3, _T( "write a commented value using style wxJSONWRITER_STYLED" ) }, { Test10_3, 3, _T( "write a commented value using style wxJSONWRITER_NONE" ) }, { Test10_4, 3, _T( "write a commented value using style wxJSONWRITER_WRITE_COMMENTS" ) }, { Test10_5, 3, _T( "write a commented value using style wxJSONWRITER_COMMENTS_BEFORE" ) }, { Test10_6, 3, _T( "write a commented value using style wxJSONWRITER_COMMENTS_AFTER" ) }, { 0 },{ 0 },{ 0 }, // family #11 (test8.cpp) { 0, // test #0: description of the family 3, // m_auto (all) _T( "test the comment related functions (reader)" ) }, { Test11_1, 3, _T( "first test without storing comments" ) }, { Test11_2, 3, _T( "second test storing comments (COMMENTS_BEFORE)" ) }, { Test11_3, 3, _T( "third test storing comments (COMMENTS_BEFORE)" ) }, { Test11_4, 3, _T( "first test without comments (COMMENTS_AFTER)" ) }, { Test11_5, 3, _T( "second test storing comments (COMMENTS_AFTER)" ) }, { 0 },{ 0 },{ 0 },{ 0 }, // family #12 (test9.cpp) { 0, // test #0: description of the family 3, // m_auto (all) _T( "test the copy-on-write implementation" ) }, { Test12_1, 3, _T( "test some copies of the value and unref" ) }, { Test12_2, 3, _T( "a test used in DDD for getting hardcopy" ) }, { Test12_3, 3, _T( "copy, write and test of sub-levels" ) }, { 0 },{ 0 },{ 0 },{ 0 },{ 0 },{ 0 }, // family #13 (test10.cpp) { 0, // test #0: description of the family 3, // m_auto (all) _T( "test the 64-bit integer support" ) }, { Test13_1, 3, _T( "test the wxWidgets definitions and macros" ) }, { Test13_2, 3, _T( "test return values from INT, SHORT, LONG and LLONG" ) }, { Test13_3, 3, _T( "test the wxString::To(U)LongLong() function" ) }, { Test13_4, 3, _T( "test the wxString::To(U)Long() function" ) }, { Test13_5, 3, _T( "test the writer class for various integer types" ) }, { Test13_6, 3, _T( "test the reader class for 64-bits integers" ) }, { Test13_7, 3, _T( "test the wxJSONReader::Strto(u)ll function" ) }, { 0 },{ 0 }, // family #14 (test11.cpp) { 0, // test #0: description of the family 3, // m_auto (all) _T( "test the use of STL for array and object types" ) }, { Test14_1, 3, _T( "test the wxWidgets definitions and macros" ) }, { Test14_2, 3, _T( "test a JSON array type" ) }, { Test14_3, 3, _T( "test a JSON key/value type" ) }, { 0 },{ 0 },{ 0 },{ 0 },{ 0 },{ 0 }, // family #15 (test12.cpp) { 0, // test #0: description of the family 3, // m_auto (all) _T( "test the new wxJSON type: memory buffer" ) }, { Test15_1, 3, _T( "testing some wxMemoryBuffer member functions" ) }, { Test15_2, 3, _T( "testing ctors, copy ctors, assignment op etc" ) }, { Test15_3, 3, _T( "test the conversion static functions" ) }, { Test15_4, 3, _T( "test the comparison static functions" ) }, { Test15_5, 3, _T( "test the writer for memory buffer types" ) }, { Test15_6, 3, _T( "test the reader for memory buffer types" ) }, { 0 },{ 0 },{ 0 }, // END OF TABLE {0} }; int numParams = cmdLine.GetParamCount(); int numTestStart = 1; int numTestEnd = NUM_TESTS; int numSubTestStart = 1; int numSubTestEnd = NUM_SUBTESTS - 1; // sets the starting test and sub-test numbers for every parameter // parameters are in the form XX [YY] wxString p1, p2; if ( numParams > 0 ) { p1 = cmdLine.GetParam( 0 ); // p1 = test number (the family) long l; bool r = p1.ToLong( &l ); if ( r ) { numTestStart = numTestEnd = (int) l; } } if ( numParams > 1 ) { p2 = cmdLine.GetParam( 1 ); // p2 = subtest numero long l; bool r = p2.ToLong( &l ); if ( r ) { numSubTestStart = numSubTestEnd = (int) l; } } for ( int x = numTestStart; x <= numTestEnd; x++ ) { // compute the family index int idx = x * NUM_SUBTESTS; if ( gs_list ) { TestCout( _T("Test number: " )); } else { TestCout( _T("\nPerforming test number: " )); } TestCout( x ); // print the description of the TEST TestCout( _T( " - ")); TestCout( testArray[idx].m_testDesc ); TestCout( (wxChar) '\n', false ); bool runFamily = false; #if defined( wxJSON_USE_UNICODE ) if ( ( testArray[idx].m_auto & 1 ) || !p1.empty() ) { runFamily = true; } #else if ( ( testArray[idx].m_auto & 2 ) || !p1.empty() ) { runFamily = true; } #endif if ( !runFamily ) { continue; } // subtests for ( int y = numSubTestStart; y <= numSubTestEnd; y++ ) { int idx = ( x * NUM_SUBTESTS ) + y; TestFunc funcPtr = testArray[idx].m_funcPtr; if ( funcPtr ) { if ( gs_list ) { TestCout( _T("Subtest #" )); TestCout( y ); // print the description of the TEST TestCout( _T( " - ")); TestCout( testArray[idx].m_testDesc ); //TestCout( _T( " AUTO=" )); //TestCout( ( testArray[idx].m_auto ? _T( "YES" ) : _T( "NO" ))); TestCout( (wxChar) '\n', false ); continue; } else { TestCout( _T("\nPerforming Subtest #" )); } TestCout( x ); TestCout( (wxChar) '.', false ); TestCout( y ); // print the description of the TEST TestCout( _T( "\nDescription: ")); TestCout( testArray[idx].m_testDesc ); TestCout( (wxChar) '\n', false ); // the test is actually done if m_auto is TRUE or if 'p2' is not empty // depending the m_auto value and the build mode (Unicode,ANSI) bool runTest = false; #if defined( wxJSON_USE_UNICODE ) if ( ( testArray[idx].m_auto & 1 ) || !p2.empty() ) { runTest = true; } #else if ( ( testArray[idx].m_auto & 2 ) || !p2.empty() ) { runTest = true; } #endif if ( runTest ) { result = funcPtr(); TestCout( _T("<-- END TEST: result=" )); TestCout( result ); TestCout( _T(" -->\n" )); } // if the test fails, stop the program if ( result > 0 && !gs_nostop ) { return result; } } } } TestCout( _T( "\nTEST application successfully completed\n\n" )); ::wxUninitialize(); return 0; }
jint Java_com_example_VoiceRecognize_VoiceRecognize_TrainWorld1(JNIEnv* env, jobject thiz, jstring jfilename) { const char *nativefilename = env->GetStringUTFChars(jfilename,0); ConfigChecker cc; cc.addIntegerParam("verboseLevel",false,true,"level of the verbose information 0=no verbose, 1=normal, 2=more"); cc.addStringParam("inputFeatureFilename",false, true,"feature filename or filename of a text file with the list of feature filenames"); cc.addStringParam("inputStreamList",false, true,"filename of a text file with the filename of input streams"); cc.addStringParam("weightStreamList",false,true,"filename of a text file with the weight of each input stream - default=equal weights"); cc.addStringParam("outputWorldFilename",true,true,"output worldmodel filename"); cc.addStringParam("inputWorldFilename",false,true,"if set, the init is based on a model get from this file, else frrom scratch"); cc.addStringParam("saveInitModel",false,true,"if set (default), save the initial model"); cc.addStringParam("labelSelectedFrames",true,true,"the segments with this label are used for training the worldmodel"); cc.addFloatParam("baggedFrameProbability",true,true,"defines the % of frames taken for each iterations"); cc.addFloatParam("baggedFrameProbabilityInit",false,true,"NOT LONGER USED IN TRAINWORLD !! deprecated and remplaced by nbFrameToSelect (defines the % of frames taken BY COMPONENT for the initializing of the mixture- mandatory if init from scratch)"); cc.addIntegerParam("nbFrameToSelect",false,true,"Defines the number of frames selected to initialise one component, default=50 "); cc.addIntegerParam("baggedMinimalLength",false,true,"minimum length for selected segments in bagged (default=3)"); cc.addIntegerParam("baggedMaximalLength",false,true,"maximal length for selected segments in bagged (default=7)"); cc.addFloatParam("initVarianceFlooring",true,true,"variance control parameters - relative to global data variance - initial value (moved during the it)"); cc.addFloatParam("initVarianceCeiling",true,true,"variance control parameters - relative to global data variance - initial value (moved during the it)"); cc.addFloatParam("finalVarianceFlooring",true,true,"variance control parameters - relative to global data variance - final value"); cc.addFloatParam("finalVarianceCeiling",true,true,"variance control parameters - relative to global data variance - final value"); cc.addIntegerParam("nbTrainIt",true,true,"number of it, the ceiling and flooring are moved and the baggedFrameProbability is used"); cc.addBooleanParam("normalizeModel",false,true,"if set to true, normalize the world (at each iteration)"); cc.addBooleanParam("normalizeModelMeanOnly",false,true,"used only if normalizeModel is On, says if only mean parameters should be normalized"); cc.addIntegerParam("normalizeModelNbIt",false,true,"used only if noramlizeModelMeanOnly is set, nb of normalization it"); cc.addBooleanParam("use01",false,true,"if set at true, don't compute the global mean and cov but uses 0 mean and 1 cov"); cc.addBooleanParam("componentReduction",false,true,"if set reduce the number of components at each it, selecting the best weights until targetDistribCount (default false)"); cc.addIntegerParam("targetMixtureDistribCount",false,true,"final number of components if componentReduction is selected"); cc.addIntegerParam("initRand",false,true,"initialisation of the random generator for bagged set of data (default=0)"); cout << "++++++++++++++++++++++++++++++++++++++++" << endl; int argc=3; char* argv[3]; argv[0]=new char[3]; strcpy(argv[0],"TW"); argv[1]=new char[9]; strcpy(argv[1],"--config"); argv[2]=new char[strlen(nativefilename)+1]; strcpy(argv[2], nativefilename); try { CmdLine cmdLine(argc, argv); //Now free the array int i; for(i=0;i<argc;i++) delete [] argv[i]; env->ReleaseStringUTFChars(jfilename, nativefilename); cout << "+++++++++++++++++++++++++++++++++++++++++" << endl; if (cmdLine.displayHelpRequired()){ cout <<"TrainWorld.exe"<<endl<<"This program is used for training a world model from scratch or from a model" <<endl<<cc.getParamList()<<endl; return 0; } if (cmdLine.displayVersionRequired()){ cout <<"Version 2-beta"<<endl; } Config tmp; cmdLine.copyIntoConfig(tmp); Config config; if (tmp.existsParam("config")) config.load(tmp.getParam("config")); cmdLine.copyIntoConfig(config); cc.check(config); debug=config.getParam_debug(); if (config.existsParam("verbose"))verbose=config.getParam("verbose").toBool();else verbose=false; if (verbose) verboseLevel=1;else verboseLevel=0; if (config.existsParam("verboseLevel"))verboseLevel=config.getParam("verboseLevel").toLong(); if (verboseLevel>0) verbose=true; trainWorld(config); } catch (alize::Exception& e) {cout << e.toString() << endl << cc.getParamList()<< endl;} return 0; }
// // UNIX main program // int appwebMain(int argc, char *argv[]) { MprCmdLine cmdLine("appweb -r . -f appweb.conf", cmdSpec); return realMain(&cmdLine); }
MainWindow::MainWindow(Main * main) : mMain(main) { setCorner( Qt::BottomLeftCorner, Qt::LeftDockWidgetArea ); // Construct status bar: mLangStatus = new StatusLabel(); mLangStatus->setText("Inactive"); mSynthStatus = new StatusLabel(); mSynthStatus->setText("Inactive"); QStatusBar *status = statusBar(); status->addPermanentWidget( new QLabel("Interpreter:") ); status->addPermanentWidget( mLangStatus ); status->addPermanentWidget( new QLabel("Synth:") ); status->addPermanentWidget( mSynthStatus ); // Code editor mEditors = new MultiEditor(main); // Docks mDocListDock = new DocumentsDock(main->documentManager(), this); mPostDock = new PostDock(this); // Layout // use a layout for tool widgets, to provide for separate margin control QVBoxLayout *tool_box = new QVBoxLayout; tool_box->addWidget(cmdLine()); tool_box->setContentsMargins(5,2,5,2); QVBoxLayout *center_box = new QVBoxLayout; center_box->setContentsMargins(0,0,0,0); center_box->setSpacing(0); center_box->addWidget(mEditors); center_box->addLayout(tool_box); QWidget *central = new QWidget; central->setLayout(center_box); setCentralWidget(central); addDockWidget(Qt::LeftDockWidgetArea, mDocListDock); addDockWidget(Qt::BottomDockWidgetArea, mPostDock); // A system for easy evaluation of pre-defined code: connect(&mCodeEvalMapper, SIGNAL(mapped(QString)), this, SIGNAL(evaluateCode(QString))); connect(this, SIGNAL(evaluateCode(QString,bool)), main->scProcess(), SLOT(evaluateCode(QString,bool))); // Interpreter: post output connect(main->scProcess(), SIGNAL( scPost(QString) ), mPostDock->mPostWindow, SLOT( post(QString) ) ); // Interpreter: monitor running state connect(main->scProcess(), SIGNAL( stateChanged(QProcess::ProcessState) ), this, SLOT( onInterpreterStateChanged(QProcess::ProcessState) ) ); // Interpreter: forward status messages connect(main->scProcess(), SIGNAL(statusMessage(const QString&)), status, SLOT(showMessage(const QString&))); // Document list interaction connect(mDocListDock->list(), SIGNAL(clicked(Document*)), mEditors, SLOT(setCurrent(Document*))); connect(mEditors, SIGNAL(currentChanged(Document*)), mDocListDock->list(), SLOT(setCurrent(Document*)), Qt::QueuedConnection); createMenus(); QIcon icon; icon.addFile(":/icons/sc-cube-128"); icon.addFile(":/icons/sc-cube-48"); icon.addFile(":/icons/sc-cube-32"); icon.addFile(":/icons/sc-cube-16"); QApplication::setWindowIcon(icon); }
int main(int argc, char *argv[]) { double elapsed; char *programName, *argp, *logSpec; int c, errflg, start; #if BLD_FEATURE_LOG MprLogToFile *logger; #endif #if BLD_FEATURE_MULTITHREAD MprThread *threadp; #endif programName = mprGetBaseName(argv[0]); method = "GET"; fileList = cmpDir = writeDir = 0; verbose = continueOnErrors = outputHeader = errflg = 0; poolThreads = 4; // Need at least one to run efficiently httpVersion = 1; // HTTP/1.1 success = 1; trace = 0; host = "localhost"; logSpec = "stdout:1"; postData = 0; postLen = 0; retries = MPR_HTTP_CLIENT_RETRIES; iterations = HTTP_DEFAULT_ITERATIONS; loadThreads = HTTP_DEFAULT_LOAD_THREADS; timeout = MPR_HTTP_CLIENT_TIMEOUT; #if BLD_FEATURE_MULTITHREAD mutex = new MprMutex(); #endif // // FUTURE: switch to GNU style --args with a better usage message // MprCmdLine cmdLine(argc, argv, "bC:cDd:f:Hh:i:l:M:mqo:r:st:T:vV:w:"); while ((c = cmdLine.next(&argp)) != EOF) { switch(c) { case 'b': benchmark++; break; case 'c': continueOnErrors++; break; case 'C': cmpDir = argp; break; case 'd': postData = argp; postLen = strlen(postData); break; case 'D': mprSetDebugMode(1); break; case 'f': fileList = argp; break; case 'h': host = argp; break; case 'H': outputHeader++; break; case 'i': iterations = atoi(argp); break; case 'l': logSpec = argp; break; case 'm': mprRequestMemStats(1); break; case 'M': method = argp; break; case 'o': timeout = atoi(argp); break; case 'q': quietMode++; break; case 'r': retries = atoi(argp); break; case 's': singleStep++; break; case 't': loadThreads = atoi(argp); break; case 'T': poolThreads = atoi(argp); break; case 'v': verbose++; trace++; break; case 'V': httpVersion = atoi(argp); break; case 'w': writeDir = argp; break; default: errflg++; break; } } if (writeDir && (loadThreads > 1)) { errflg++; } if (errflg) { mprFprintf(MPR_STDERR, "usage: %s [-bcHMmqsTv] [-C cmpDir] [-d postData] [-f fileList]\n" " [-i iterations] [-l logSpec] [-M method] [-o timeout]\n" " [-h host] [-r retries] [-t threads] [-T poolThreads]\n" " [-V httpVersion] [-w writeDir] [urls...]\n", programName); exit(2); } saveArgc = argc - cmdLine.firstArg(); saveArgv = &argv[cmdLine.firstArg()]; mpr = new Mpr(programName); #if BLD_FEATURE_LOG tMod = new MprLogModule("httpClient"); logger = new MprLogToFile(); mpr->addListener(logger); if (mpr->setLogSpec(logSpec) < 0) { mprFprintf(MPR_STDERR, "Can't open log file %s\n", logSpec); exit(2); } #endif // // Alternatively, set the configuration manually // mpr->setAppTitle("Embedthis HTTP Client"); #if BLD_FEATURE_MULTITHREAD mpr->setMaxPoolThreads(poolThreads); #endif // // Start the Timer, Socket and Pool services // if (mpr->start(MPR_SERVICE_THREAD) < 0) { mprError(MPR_L, MPR_USER, "Can't start MPR for %s", mpr->getAppTitle()); delete mpr; exit(2); } // // Create extra test threads to run the tests as required. We use // the main thread also (so start with j==1) // start = mprGetTime(0); #if BLD_FEATURE_MULTITHREAD activeLoadThreads = loadThreads; for (int j = 1; j < loadThreads; j++) { char name[64]; mprSprintf(name, sizeof(name), "t.%d", j - 1); threadp = new MprThread(doTests, MPR_NORMAL_PRIORITY, (void*) j, name); threadp->start(); } #endif doTests(0, 0); // // Wait for all the threads to complete (simple but effective). Keep // servicing events as we wind down. // while (activeLoadThreads > 1) { mprSleep(100); } if (benchmark && success) { elapsed = (mprGetTime(0) - start); if (fetchCount == 0) { elapsed = 0; fetchCount = 1; } mprPrintf("\tThreads %d, Pool Threads %d \t%13.2f\t%12.2f\t%6d\n", loadThreads, poolThreads, elapsed * 1000.0 / fetchCount, elapsed / 1000.0, fetchCount); mprPrintf("\nTime elapsed: %13.4f sec\n", elapsed / 1000.0); mprPrintf("Time per request: %13.4f sec\n", elapsed / 1000.0 / fetchCount); mprPrintf("Requests per second: %13.4f\n", fetchCount * 1.0 / (elapsed / 1000.0)); } if (! quietMode) { mprPrintf("\n"); } mpr->stop(0); #if BLD_FEATURE_MULTITHREAD delete mutex; #endif #if BLD_FEATURE_LOG delete tMod; #endif delete mpr; #if BLD_FEATURE_LOG delete logger; #endif mprMemClose(); return (success) ? 0 : 255; }
int APIENTRY wWinMain(_In_ HINSTANCE hInstance, _In_opt_ HINSTANCE hPrevInstance, _In_ LPWSTR lpCmdLine, _In_ int nCmdShow) { // Attempt to mitigate http://textslashplain.com/2015/12/18/dll-hijacking-just-wont-die HMODULE hKernel32 = LoadLibrary(L"kernel32.dll"); ATLASSERT(hKernel32 != NULL); SetDefaultDllDirectoriesFunction pfn = (SetDefaultDllDirectoriesFunction) GetProcAddress(hKernel32, "SetDefaultDllDirectories"); if (pfn) { (*pfn)(LOAD_LIBRARY_SEARCH_SYSTEM32); } int exitCode = -1; CString cmdLine(lpCmdLine); if (cmdLine.Find(L"--checkInstall") >= 0) { // If we're already installed, exit as fast as possible if (!MachineInstaller::ShouldSilentInstall()) { exitCode = 0; goto out; } // Make sure update.exe gets silent wcscat(lpCmdLine, L" --silent"); } HRESULT hr = ::CoInitialize(NULL); ATLASSERT(SUCCEEDED(hr)); AtlInitCommonControls(ICC_COOL_CLASSES | ICC_BAR_CLASSES); hr = _Module.Init(NULL, hInstance); bool isQuiet = (cmdLine.Find(L"-s") >= 0); bool weAreUACElevated = CUpdateRunner::AreWeUACElevated() == S_OK; bool attemptingToRerun = (cmdLine.Find(L"--rerunningWithoutUAC") >= 0); if (weAreUACElevated && attemptingToRerun) { CUpdateRunner::DisplayErrorMessage(CString(L"Please re-run this installer as a normal user instead of \"Run as Administrator\"."), NULL); exitCode = E_FAIL; goto out; } if (!CFxHelper::CanInstallDotNet4_5()) { // Explain this as nicely as possible and give up. MessageBox(0L, L"This program cannot run on Windows XP or before; it requires a later version of Windows.", L"Incompatible Operating System", 0); exitCode = E_FAIL; goto out; } if (!CFxHelper::IsDotNet45OrHigherInstalled()) { hr = CFxHelper::InstallDotNetFramework(isQuiet); if (FAILED(hr)) { exitCode = hr; // #yolo CUpdateRunner::DisplayErrorMessage(CString(L"Failed to install the .NET Framework, try installing .NET 4.5 or higher manually"), NULL); goto out; } // S_FALSE isn't failure, but we still shouldn't try to install if (hr != S_OK) { exitCode = 0; goto out; } } // If we're UAC-elevated, we shouldn't be because it will give us permissions // problems later. Just silently rerun ourselves. if (weAreUACElevated) { wchar_t buf[4096]; HMODULE hMod = GetModuleHandle(NULL); GetModuleFileNameW(hMod, buf, 4096); wcscat(lpCmdLine, L" --rerunningWithoutUAC"); CUpdateRunner::ShellExecuteFromExplorer(buf, lpCmdLine); exitCode = 0; goto out; } exitCode = CUpdateRunner::ExtractUpdaterAndRun(lpCmdLine, false); out: _Module.Term(); ::CoUninitialize(); return exitCode; }
int _main_(int _argc, char** _argv) { bx::CommandLine cmdLine(_argc, _argv); if (cmdLine.hasArg('h', "help") ) { help(); return EXIT_FAILURE; } else if (cmdLine.hasArg("associate") ) { associate(); return EXIT_FAILURE; } uint32_t width = 1280; uint32_t height = 720; uint32_t debug = BGFX_DEBUG_TEXT; uint32_t reset = BGFX_RESET_VSYNC; inputAddBindings(s_bindingName[Binding::App], s_binding[Binding::App]); inputAddBindings(s_bindingName[Binding::View], s_binding[Binding::View]); View view; cmdAdd("view", cmdView, &view); bgfx::init(); bgfx::reset(width, height, reset); // Set view 0 clear state. bgfx::setViewClear(0 , BGFX_CLEAR_COLOR|BGFX_CLEAR_DEPTH , 0x101010ff , 1.0f , 0 ); imguiCreate(); PosUvColorVertex::init(); bgfx::RendererType::Enum type = bgfx::getRendererType(); bgfx::ShaderHandle vsTexture = bgfx::createEmbeddedShader(s_embeddedShaders, type, "vs_texture"); bgfx::ShaderHandle fsTexture = bgfx::createEmbeddedShader(s_embeddedShaders, type, "fs_texture"); bgfx::ShaderHandle fsTextureArray = bgfx::createEmbeddedShader(s_embeddedShaders, type, "fs_texture_array"); bgfx::ProgramHandle textureProgram = bgfx::createProgram( vsTexture , fsTexture , true ); bgfx::ProgramHandle textureArrayProgram = bgfx::createProgram( vsTexture , bgfx::isValid(fsTextureArray) ? fsTextureArray : fsTexture , true ); bgfx::ProgramHandle textureCubeProgram = bgfx::createProgram( bgfx::createEmbeddedShader(s_embeddedShaders, type, "vs_texture_cube") , bgfx::createEmbeddedShader(s_embeddedShaders, type, "fs_texture_cube") , true ); bgfx::ProgramHandle textureSDFProgram = bgfx::createProgram( vsTexture , bgfx::createEmbeddedShader(s_embeddedShaders, type, "fs_texture_sdf") , true); bgfx::UniformHandle s_texColor = bgfx::createUniform("s_texColor", bgfx::UniformType::Int1); bgfx::UniformHandle u_mtx = bgfx::createUniform("u_mtx", bgfx::UniformType::Mat4); bgfx::UniformHandle u_params = bgfx::createUniform("u_params", bgfx::UniformType::Vec4); float speed = 0.37f; float time = 0.0f; Interpolator mip(0.0f); Interpolator layer(0.0f); Interpolator zoom(1.0f); Interpolator scale(1.0f); const char* filePath = _argc < 2 ? "" : _argv[1]; bool directory = false; bx::FileInfo fi; bx::stat(filePath, fi); directory = bx::FileInfo::Directory == fi.m_type; std::string path = filePath; if (!directory) { const char* fileName = directory ? filePath : bx::baseName(filePath); path.assign(filePath, fileName); view.updateFileList(path.c_str(), fileName); } else { view.updateFileList(path.c_str() ); } int exitcode = EXIT_SUCCESS; bgfx::TextureHandle texture = BGFX_INVALID_HANDLE; if (view.m_fileList.empty() ) { exitcode = EXIT_FAILURE; if (2 > _argc) { help("File path is not specified."); } else { fprintf(stderr, "Unable to load '%s' texture.\n", filePath); } } else { uint32_t fileIndex = 0; entry::MouseState mouseState; while (!entry::processEvents(width, height, debug, reset, &mouseState) ) { imguiBeginFrame(mouseState.m_mx , mouseState.m_my , (mouseState.m_buttons[entry::MouseButton::Left ] ? IMGUI_MBUT_LEFT : 0) | (mouseState.m_buttons[entry::MouseButton::Right ] ? IMGUI_MBUT_RIGHT : 0) | (mouseState.m_buttons[entry::MouseButton::Middle] ? IMGUI_MBUT_MIDDLE : 0) , mouseState.m_mz , width , height ); static bool help = false; if (help == false && help != view.m_help) { ImGui::OpenPopup("Help"); } if (ImGui::BeginPopupModal("Help", NULL, ImGuiWindowFlags_AlwaysAutoResize) ) { ImGui::SetWindowFontScale(1.0f); ImGui::Text( "texturev, bgfx texture viewer tool " ICON_KI_WRENCH "\n" "Copyright 2011-2017 Branimir Karadzic. All rights reserved.\n" "License: https://github.com/bkaradzic/bgfx#license-bsd-2-clause\n" ); ImGui::Separator(); ImGui::NextLine(); ImGui::Text("Key bindings:\n\n"); ImGui::PushFont(ImGui::Font::Mono); ImGui::TextColored(ImVec4(1.0f, 1.0f, 0.0f, 1.0f), "ESC"); ImGui::SameLine(64); ImGui::Text("Exit."); ImGui::TextColored(ImVec4(1.0f, 1.0f, 0.0f, 1.0f), "h"); ImGui::SameLine(64); ImGui::Text("Toggle help screen."); ImGui::TextColored(ImVec4(1.0f, 1.0f, 0.0f, 1.0f), "f"); ImGui::SameLine(64); ImGui::Text("Toggle full-screen."); ImGui::NextLine(); ImGui::TextColored(ImVec4(1.0f, 1.0f, 0.0f, 1.0f), "-"); ImGui::SameLine(64); ImGui::Text("Zoom out."); ImGui::TextColored(ImVec4(1.0f, 1.0f, 0.0f, 1.0f), "="); ImGui::SameLine(64); ImGui::Text("Zoom in."); ImGui::NextLine(); ImGui::TextColored(ImVec4(1.0f, 1.0f, 0.0f, 1.0f), ","); ImGui::SameLine(64); ImGui::Text("MIP level up."); ImGui::TextColored(ImVec4(1.0f, 1.0f, 0.0f, 1.0f), "."); ImGui::SameLine(64); ImGui::Text("MIP level down."); ImGui::TextColored(ImVec4(1.0f, 1.0f, 0.0f, 1.0f), "/"); ImGui::SameLine(64); ImGui::Text("Toggle linear/point texture sampling."); ImGui::NextLine(); ImGui::TextColored(ImVec4(1.0f, 1.0f, 0.0f, 1.0f), "left"); ImGui::SameLine(64); ImGui::Text("Previous layer in texture array."); ImGui::TextColored(ImVec4(1.0f, 1.0f, 0.0f, 1.0f), "right"); ImGui::SameLine(64); ImGui::Text("Next layer in texture array."); ImGui::NextLine(); ImGui::TextColored(ImVec4(1.0f, 1.0f, 0.0f, 1.0f), "up"); ImGui::SameLine(64); ImGui::Text("Previous texture."); ImGui::TextColored(ImVec4(1.0f, 1.0f, 0.0f, 1.0f), "down"); ImGui::SameLine(64); ImGui::Text("Next texture."); ImGui::NextLine(); ImGui::TextColored(ImVec4(1.0f, 1.0f, 0.0f, 1.0f), "r/g/b"); ImGui::SameLine(64); ImGui::Text("Toggle R, G, or B color channel."); ImGui::TextColored(ImVec4(1.0f, 1.0f, 0.0f, 1.0f), "a"); ImGui::SameLine(64); ImGui::Text("Toggle alpha blending."); ImGui::NextLine(); ImGui::TextColored(ImVec4(1.0f, 1.0f, 0.0f, 1.0f), "s"); ImGui::SameLine(64); ImGui::Text("Toggle Multi-channel SDF rendering"); ImGui::PopFont(); ImGui::NextLine(); ImGui::Dummy(ImVec2(0.0f, 0.0f) ); ImGui::SameLine(ImGui::GetWindowWidth() - 136.0f); if (ImGui::Button("Close", ImVec2(128.0f, 0.0f) ) || !view.m_help) { view.m_help = false; ImGui::CloseCurrentPopup(); } ImGui::EndPopup(); } help = view.m_help; imguiEndFrame(); if (!bgfx::isValid(texture) || view.m_fileIndex != fileIndex) { if (bgfx::isValid(texture) ) { bgfx::destroyTexture(texture); } fileIndex = view.m_fileIndex; filePath = view.m_fileList[view.m_fileIndex].c_str(); texture = loadTexture(filePath , 0 | BGFX_TEXTURE_U_CLAMP | BGFX_TEXTURE_V_CLAMP | BGFX_TEXTURE_W_CLAMP , 0 , &view.m_info ); std::string title; bx::stringPrintf(title, "%s (%d x %d%s, %s)" , filePath , view.m_info.width , view.m_info.height , view.m_info.cubeMap ? " CubeMap" : "" , bgfx::getName(view.m_info.format) ); entry::WindowHandle handle = { 0 }; entry::setWindowTitle(handle, title.c_str() ); } int64_t now = bx::getHPCounter(); static int64_t last = now; const int64_t frameTime = now - last; last = now; const double freq = double(bx::getHPFrequency() ); time += (float)(frameTime*speed/freq); float ortho[16]; bx::mtxOrtho(ortho, 0.0f, (float)width, (float)height, 0.0f, 0.0f, 1000.0f); bgfx::setViewTransform(0, NULL, ortho); bgfx::setViewRect(0, 0, 0, width, height); bgfx::touch(0); bgfx::dbgTextClear(); scale.set( bx::fmin( float(width) / float(view.m_info.width) , float(height) / float(view.m_info.height) ) , 0.1f ); zoom.set(view.m_zoom, 0.25); float ss = scale.getValue() * zoom.getValue(); screenQuad( int(width - view.m_info.width * ss)/2 , int(height - view.m_info.height * ss)/2 , int(view.m_info.width * ss) , int(view.m_info.height * ss) , view.m_abgr ); float mtx[16]; bx::mtxRotateXY(mtx, 0.0f, time); bgfx::setUniform(u_mtx, mtx); mip.set(float(view.m_mip), 0.5f); layer.set(float(view.m_layer), 0.25f); float params[4] = { mip.getValue(), layer.getValue(), 0.0f, 0.0f }; bgfx::setUniform(u_params, params); bgfx::setTexture(0 , s_texColor , texture , view.m_filter ? BGFX_TEXTURE_NONE : 0 | BGFX_TEXTURE_MIN_POINT | BGFX_TEXTURE_MIP_POINT | BGFX_TEXTURE_MAG_POINT ); bgfx::setState(0 | BGFX_STATE_RGB_WRITE | BGFX_STATE_ALPHA_WRITE | (view.m_alpha ? BGFX_STATE_BLEND_ALPHA : BGFX_STATE_NONE) ); bgfx::submit(0 , view.m_info.cubeMap ? textureCubeProgram : 1 < view.m_info.numLayers ? textureArrayProgram : view.m_sdf ? textureSDFProgram : textureProgram ); bgfx::frame(); } } if (bgfx::isValid(texture) ) { bgfx::destroyTexture(texture); } bgfx::destroyUniform(s_texColor); bgfx::destroyUniform(u_mtx); bgfx::destroyUniform(u_params); bgfx::destroyProgram(textureProgram); bgfx::destroyProgram(textureArrayProgram); bgfx::destroyProgram(textureCubeProgram); imguiDestroy(); bgfx::shutdown(); return exitcode; }
int main(int argc, char* argv[]){ ConfigChecker cc; cc.addStringParam("config", false, true, "default config filename"); cc.addIntegerParam("verboseLevel",false,true,"level of the berose information 0=no verbose, 1=normal, 2=more"); cc.addStringParam("inputFeatureFilename",false, true,"feature filename or filename of a text file with the list of feature filenames"); cc.addStringParam("targetIdList",true,true,"The file with the list of models to train. A line is composed by client_id file1 file2 ..."); cc.addStringParam("inputWorldFilename",false,true,"if set, the init is based on a model get from this file, else from scratch"); cc.addStringParam("labelSelectedFrames",false,true,"The segments with this label are used for training the worldmodel (if UseIdForSelectedFrame is not used)"); cc.addBooleanParam("info",false,false,"If info is requested, just info on the train set is outputed"); cc.addStringParam("saveVectorFilesPath",true,true,"Directory to store i-vectors after extraction"); cc.addStringParam("mode",false,true,"Mode of i-vector extraction, classic (default) | ubmWeight | eigenDecomposition"); cc.addBooleanParam("loadUbmWeightParam",false,true,"If true, load pre-computed parameters for ubmWeight approximation"); try{ CmdLine cmdLine(argc, argv); if (cmdLine.displayHelpRequired()){ cout <<"IvExtractor.exe"<<endl<<"This program is used for extracting i-vectors" <<endl<<cc.getParamList()<<endl; return 0; } if (cmdLine.displayVersionRequired()){ cout <<"Version 1.0"<<endl; } Config tmp; cmdLine.copyIntoConfig(tmp); Config config; if (tmp.existsParam("config")) config.load(tmp.getParam("config")); cmdLine.copyIntoConfig(config); cc.check(config); debug=config.getParam_debug(); if (config.existsParam("verbose"))verbose=config.getParam("verbose").toBool();else verbose=false; if (verbose) verboseLevel=1;else verboseLevel=0; if (config.existsParam("verboseLevel"))verboseLevel=config.getParam("verboseLevel").toLong(); if (verboseLevel>0) verbose=true; bool train=true; // Training the target models if (config.existsParam("info")) // Information on the data available for the targets and output a file with good amount of data train=false; String mode = "classic"; if(config.existsParam("mode")) mode = config.getParam("mode"); if (train){ // if (config.existsParam("byLabelModel")) // if the paramter is present, for each client, we train one model for each cluster // TrainTargetByLabel(config); // (a cluster is a set of segments with the same label) if(mode == "classic") IvExtractor(config); else if(mode == "ubmWeight") IvExtractorUbmWeigth(config); else if(mode == "eigenDecomposition") IvExtractorEigenDecomposition(config); else{ InfoTarget(config); } } else InfoTarget(config); return 0; } catch(alize::Exception & e){ cout <<"IvExtractor "<< e.toString() << endl << cc.getParamList()<<endl;} }
int main(int argc, char *argv[]) { std::string meshname = ""; bool noViewer = true; bool bufferImages = false; bool useColor = true; bool volumeColor = true; bool useLoopClosures = false; unsigned int startimage = 0; unsigned int endimage = 1000000; unsigned int imageStep = 1; float maxCamDistance = MAXCAMDISTANCE; float scale = DEFAULT_SCALE; float threshold = DEFAULT_SCALE; float imageDepthScale = DEPTHSCALE; std::string intrinsics = ""; bool threadMeshing = true; bool threadFusion = false; bool threadImageReading = false; bool performIncrementalMeshing = true; int depthConstistencyChecks = 0; TCLAP::CmdLine cmdLine("onlinefusion"); TCLAP::ValueArg<std::string> loadMeshArg("l","loadmesh","Loads this mesh",false,meshname,"string"); TCLAP::SwitchArg threadMeshingArg("","thread-meshing","Thread the Meshing inside the Fusion",threadMeshing); TCLAP::SwitchArg threadFusionArg("","thread-fusion","Thread the Fusion inside the Viewer",threadFusion); TCLAP::SwitchArg threadImageReadingArg("","thread-image","Thread reading the Images from Hard Disk",threadImageReading); TCLAP::SwitchArg viewerArg("v","viewer","Show a Viewer after Fusion",!noViewer); TCLAP::SwitchArg bufferArg("b","buffer","Buffer all Images",bufferImages); TCLAP::SwitchArg useLoopClosuresArg("c","loopclosures","Read Multiple Trajectories and perform Loop Closures",useLoopClosures); TCLAP::SwitchArg performIncrementalMeshingArg("","incremental-meshing","Perform incremental Meshing",performIncrementalMeshing); TCLAP::ValueArg<int> startimageArg("s","startimage","Number of the Start Image",false,startimage,"int"); TCLAP::ValueArg<int> endimageArg("e","endimage","Number of the End Image",false,endimage,"int"); TCLAP::ValueArg<int> imageStepArg("k","imagestep","Use every kth step",false,imageStep,"int"); TCLAP::ValueArg<int> depthConsistencyChecksArg("","consistency-checks","Number of Depth Consistency Checks",false,depthConstistencyChecks,"int"); TCLAP::ValueArg<float> maxCamDistanceArg("","max-camera-distance","Maximum Camera Distance to Surface",false,maxCamDistance,"float"); TCLAP::ValueArg<float> scaleArg("","scale","Size of the Voxel",false,scale,"float"); TCLAP::ValueArg<float> thresholdArg("","threshold","Threshold",false,threshold,"float"); TCLAP::ValueArg<float> imageDepthScaleArg("","imagescale","Image Depth Scale",false,imageDepthScale,"float"); TCLAP::ValueArg<std::string> intrinsicsArg("","intrinsics","File with Camera Matrix",false,intrinsics,"string"); TCLAP::UnlabeledMultiArg<std::string> associationfilenamesArg("filenames", "The File Names",false,"string"); cmdLine.add(loadMeshArg); cmdLine.add(threadMeshingArg); cmdLine.add(threadFusionArg); cmdLine.add(threadImageReadingArg); cmdLine.add(viewerArg); cmdLine.add(bufferArg); cmdLine.add(useLoopClosuresArg); cmdLine.add(performIncrementalMeshingArg); cmdLine.add(startimageArg); cmdLine.add(endimageArg); cmdLine.add(imageStepArg); cmdLine.add(depthConsistencyChecksArg); cmdLine.add(maxCamDistanceArg); cmdLine.add(scaleArg); cmdLine.add(thresholdArg); cmdLine.add(imageDepthScaleArg); cmdLine.add(intrinsicsArg); cmdLine.add(associationfilenamesArg); cmdLine.parse(argc,argv); meshname = loadMeshArg.getValue(); threadMeshing = threadMeshingArg.getValue(); threadFusion = threadFusionArg.getValue(); threadImageReading = threadImageReadingArg.getValue(); noViewer = !viewerArg.getValue(); bufferImages = bufferArg.getValue(); useLoopClosures = useLoopClosuresArg.getValue(); performIncrementalMeshing = performIncrementalMeshingArg.getValue(); startimage = startimageArg.getValue(); endimage = endimageArg.getValue(); imageStep = imageStepArg.getValue(); if(imageStep < 1) imageStep = 1; depthConstistencyChecks = depthConsistencyChecksArg.getValue(); maxCamDistance = maxCamDistanceArg.getValue(); scale = scaleArg.getValue(); threshold = thresholdArg.getValue(); imageDepthScale = imageDepthScaleArg.getValue(); intrinsics = intrinsicsArg.getValue(); float fx = 525.0f; float fy = 525.0f; float cx = 319.5f; float cy = 239.5f; if (intrinsics != "") { fprintf(stderr,"\nReading intrinsic camera parameters from %s",intrinsics.c_str()); std::fstream intrinsicsfile; intrinsicsfile.open(intrinsics.c_str(),std::ios::in); if(!intrinsicsfile.is_open()){ fprintf(stderr,"\nERROR: Could not open File %s for reading!",intrinsics.c_str()); } else { float temp; fx = fy = cx = cy = -1.0f; intrinsicsfile >> fx; intrinsicsfile >> temp; intrinsicsfile >> cx; intrinsicsfile >> temp; intrinsicsfile >> fy; intrinsicsfile >> cy; intrinsicsfile.close(); fprintf(stderr,"\nCamera Intrinsics from File: %f %f %f %f",fx,fy,cx,cy); } }
int main(int _argc, const char* _argv[]) { bx::CommandLine cmdLine(_argc, _argv); uint16_t port = 1337; const char* portOpt = cmdLine.findOption('p'); if (NULL != portOpt) { port = atoi(portOpt); } bool server = cmdLine.hasArg('s', "server"); if (server) { bnet::init(10, 1, s_certs); uint32_t ip = bnet::toIpv4("localhost"); bnet::listen(ip, port, false, s_certs[0], s_key); } else { bnet::init(1, 0, s_certs); const char* host = cmdLine.findOption('h', "host"); uint32_t ip = bnet::toIpv4(NULL == host ? "localhost" : host); bnet::Handle handle = bnet::connect(ip, port, false, true); const char* hello = "hello there!"; uint16_t len = (uint16_t)strlen(hello); bnet::Message* msg = bnet::alloc(handle, len+1); msg->data[0] = bnet::MessageId::UserDefined; bx::memCopy(&msg->data[1], hello, len); bnet::send(msg); } bool cont = true; while (server || cont) { bnet::Message* msg = bnet::recv(); if (NULL != msg) { if (bnet::MessageId::UserDefined > msg->data[0]) { switch (msg->data[0]) { case bnet::MessageId::ListenFailed: printf("Listen failed port is already in use?\n"); cont = server = false; break; case bnet::MessageId::IncomingConnection: { { bnet::Handle listen = { *( (uint16_t*)&msg->data[1]) }; uint32_t rip = *( (uint32_t*)&msg->data[3]); uint16_t rport = *( (uint16_t*)&msg->data[7]); printf("%d.%d.%d.%d:%d connected\n" , rip>>24 , (rip>>16)&0xff , (rip>>8)&0xff , rip&0xff , rport ); bnet::stop(listen); } uint32_t ip = bnet::toIpv4("localhost"); bnet::listen(ip, port, false, s_certs[0], s_key); } break; case bnet::MessageId::LostConnection: printf("disconnected\n"); cont = false; break; case bnet::MessageId::ConnectFailed: printf("%d\n", msg->data[0]); cont = false; bnet::disconnect(msg->handle); break; case bnet::MessageId::RawData: break; default: // fail... break; } } else { printMsg(msg); bnet::Handle handle = msg->handle; { const char* ping = "ping!"; const char* pong = "pong!"; const char* hello = server ? ping : pong; uint16_t len = (uint16_t)strlen(hello); bnet::Message* omsg = bnet::alloc(handle, len+1); omsg->data[0] = bnet::MessageId::UserDefined+1; bx::memCopy(&omsg->data[1], hello, len); bnet::send(omsg); } } bnet::release(msg); } }