commit
stringlengths
40
40
old_file
stringlengths
2
205
new_file
stringlengths
2
205
old_contents
stringlengths
0
32.9k
new_contents
stringlengths
1
38.9k
subject
stringlengths
3
9.4k
message
stringlengths
6
9.84k
lang
stringlengths
3
13
license
stringclasses
13 values
repos
stringlengths
6
115k
1bc0fbab83f1f377255fbdacace15db7a00c0b22
Settings/SettingsUI.cpp
Settings/SettingsUI.cpp
#include "SettingsUI.h" #include <iostream> #include "../3RVX/CommCtl.h" /* DLGTEMPLATEEX Structure */ #include <pshpack1.h> typedef struct DLGTEMPLATEEX { WORD dlgVer; WORD signature; DWORD helpID; DWORD exStyle; DWORD style; WORD cDlgItems; short x; short y; short cx; short cy; } DLGTEMPLATEEX, *LPDLGTEMPLATEEX; #include <poppack.h> /* Needed to determine whether the Apply button is enabled/disabled */ #define IDD_APPLYNOW 0x3021 #include "../3RVX/3RVX.h" #include "../3RVX/LanguageTranslator.h" #include "../3RVX/Logger.h" #include "../3RVX/Settings.h" #include "UITranslator.h" #include "Updater.h" #include "UpdaterWindow.h" /* Tabs*/ #include "Tabs/Tab.h" #include "Tabs/General.h" #include "Tabs/Display.h" #include "Tabs/Hotkeys.h" #include "Tabs/About.h" General general; Display display; Hotkeys hotkeys; About about; Tab *tabs[] = { &general, &display, &hotkeys, &about }; /* Startup x/y location offsets */ #define XOFFSET 70 #define YOFFSET 20 HANDLE mutex; HWND mainWnd = NULL; HWND tabWnd = NULL; HINSTANCE hInst; bool relaunch = false; int APIENTRY wWinMain( _In_ HINSTANCE hInstance, _In_opt_ HINSTANCE hPrevInstance, _In_ LPTSTR lpCmdLine, _In_ int nCmdShow) { hInst = hInstance; UNREFERENCED_PARAMETER(hPrevInstance); UNREFERENCED_PARAMETER(lpCmdLine); Logger::Start(); CLOG(L"Starting SettingsUI..."); std::wstring cmdLine(lpCmdLine); if (cmdLine.find(L"-update") != std::wstring::npos) { if (Updater::NewerVersionAvailable()) { CLOG(L"An update is available. Showing update icon."); UpdaterWindow uw; PostMessage( uw.Handle(), _3RVX::WM_3RVX_SETTINGSCTRL, _3RVX::MSG_UPDATEICON, NULL); MSG msg; while (GetMessage(&msg, NULL, 0, 0)) { TranslateMessage(&msg); DispatchMessage(&msg); } } else { #if defined(ENABLE_3RVX_LOG) && (defined(ENABLE_3RVX_LOGTOFILE) == FALSE) CLOG(L"No update available. Press [enter] to terminate"); std::cin.get(); #endif } return 0; } mutex = CreateMutex(NULL, FALSE, L"Local\\3RVXSettings"); if (GetLastError() == ERROR_ALREADY_EXISTS) { if (mutex) { ReleaseMutex(mutex); } HWND settingsWnd = _3RVX::MasterSettingsHwnd(); CLOG(L"A settings instance is already running. Moving window [%d] " L"to the foreground.", (int) settingsWnd); SetForegroundWindow(settingsWnd); SendMessage( settingsWnd, _3RVX::WM_3RVX_SETTINGSCTRL, _3RVX::MSG_ACTIVATE, NULL); #if defined(ENABLE_3RVX_LOG) && (defined(ENABLE_3RVX_LOGTOFILE) == FALSE) CLOG(L"Press [enter] to terminate"); std::cin.get(); #endif return EXIT_SUCCESS; } WNDCLASSEX wcex = { 0 }; wcex.cbSize = sizeof(WNDCLASSEX); wcex.lpfnWndProc = WndProc; wcex.hInstance = hInst; wcex.hIcon = LoadIcon(NULL, MAKEINTRESOURCE(IDI_SETTINGS)); wcex.hbrBackground = (HBRUSH) (COLOR_WINDOW); wcex.lpszClassName = _3RVX::CLASS_3RVX_SETTINGS; if (RegisterClassEx(&wcex) == 0) { CLOG(L"Could not register class: %d", GetLastError()); return EXIT_FAILURE; } mainWnd = CreateWindowEx( NULL, _3RVX::CLASS_3RVX_SETTINGS, _3RVX::CLASS_3RVX_SETTINGS, NULL, 0, 0, 0, 0, NULL, NULL, hInst, NULL); INT_PTR result; do { result = LaunchPropertySheet(); CLOG(L"RL: %s", relaunch ? L"TRUE" : L"FALSE"); } while (relaunch == true); return result; } INT_PTR LaunchPropertySheet() { Settings *settings = Settings::Instance(); settings->Load(); PROPSHEETPAGE psp[4]; LanguageTranslator *lt = settings->Translator(); std::wstring genTitle = lt->Translate(std::wstring(L"General")); std::wstring dispTitle = lt->Translate(std::wstring(L"Display")); std::wstring hkTitle = lt->Translate(std::wstring(L"Hotkeys")); std::wstring aboutTitle = lt->Translate(std::wstring(L"About")); psp[0] = { 0 }; psp[0].dwSize = sizeof(PROPSHEETPAGE); psp[0].dwFlags = PSP_USETITLE; psp[0].hInstance = hInst; psp[0].pszTemplate = MAKEINTRESOURCE(IDD_GENERAL); psp[0].pszIcon = NULL; psp[0].pfnDlgProc = (DLGPROC) GeneralTabProc; psp[0].pszTitle = &genTitle[0]; psp[0].lParam = NULL; psp[1] = { 0 }; psp[1].dwSize = sizeof(PROPSHEETPAGE); psp[1].dwFlags = PSP_USETITLE; psp[1].hInstance = hInst; psp[1].pszTemplate = MAKEINTRESOURCE(IDD_DISPLAY); psp[1].pszIcon = NULL; psp[1].pfnDlgProc = (DLGPROC) DisplayTabProc; psp[1].pszTitle = &dispTitle[0]; psp[1].lParam = 0; psp[2] = { 0 }; psp[2].dwSize = sizeof(PROPSHEETPAGE); psp[2].dwFlags = PSP_USETITLE; psp[2].hInstance = hInst; psp[2].pszTemplate = MAKEINTRESOURCE(IDD_HOTKEYS); psp[2].pszIcon = NULL; psp[2].pfnDlgProc = (DLGPROC) HotkeyTabProc; psp[2].pszTitle = &hkTitle[0]; psp[2].lParam = 0; psp[3] = { 0 }; psp[3].dwSize = sizeof(PROPSHEETPAGE); psp[3].dwFlags = PSP_USETITLE; psp[3].hInstance = hInst; psp[3].pszTemplate = MAKEINTRESOURCE(IDD_ABOUT); psp[3].pszIcon = NULL; psp[3].pfnDlgProc = (DLGPROC) AboutTabProc; psp[3].pszTitle = &aboutTitle[0]; psp[3].lParam = 0; PROPSHEETHEADER psh = { 0 }; psh.dwSize = sizeof(PROPSHEETHEADER); psh.dwFlags = PSH_PROPSHEETPAGE | PSH_USEICONID | PSH_USECALLBACK; psh.hwndParent = mainWnd; psh.hInstance = hInst; psh.pszIcon = MAKEINTRESOURCE(IDI_SETTINGS); psh.pszCaption = L"3RVX Settings"; psh.nStartPage = 0; psh.nPages = sizeof(psp) / sizeof(PROPSHEETPAGE); psh.ppsp = (LPCPROPSHEETPAGE) &psp; psh.pfnCallback = (PFNPROPSHEETCALLBACK) PropSheetProc; tabWnd = NULL; /* Position the window if this is the first launch */ if (relaunch == false) { POINT pt = { 0 }; GetCursorPos(&pt); MoveWindow(mainWnd, pt.x - XOFFSET, pt.y - YOFFSET, 0, 0, TRUE); } relaunch = false; CLOG(L"Launching modal property sheet."); return PropertySheet(&psh); } LRESULT CALLBACK WndProc( HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { PAINTSTRUCT ps; HDC hdc; switch (message) { case WM_PAINT: hdc = BeginPaint(hWnd, &ps); EndPaint(hWnd, &ps); break; case WM_DESTROY: PostQuitMessage(0); break; } if (message == _3RVX::WM_3RVX_SETTINGSCTRL) { switch (wParam) { case _3RVX::MSG_ACTIVATE: CLOG(L"Received request to activate window from external program"); SetActiveWindow(tabWnd); break; case _3RVX::MSG_LANGCHANGE: relaunch = true; break; } } return DefWindowProc(hWnd, message, wParam, lParam); } int CALLBACK PropSheetProc(HWND hWnd, UINT msg, LPARAM lParam) { switch (msg) { case PSCB_PRECREATE: /* Disable the help button: */ if (((LPDLGTEMPLATEEX) lParam)->signature == 0xFFFF) { ((LPDLGTEMPLATEEX) lParam)->style &= ~DS_CONTEXTHELP; } else { ((LPDLGTEMPLATE) lParam)->style &= ~DS_CONTEXTHELP; } /* Show window in the taskbar: */ ((LPDLGTEMPLATE) lParam)->dwExtendedStyle |= WS_EX_APPWINDOW; break; case PSCB_INITIALIZED: UITranslator::TranslateWindowText(hWnd); if (tabWnd == NULL) { tabWnd = hWnd; } /* These values are hard-coded in case the user has a non-english GUI but wants to change the program language */ UITranslator::TranslateControlText( hWnd, IDOK, std::wstring(L"OK")); UITranslator::TranslateControlText( hWnd, IDCANCEL, std::wstring(L"Cancel")); UITranslator::TranslateControlText( hWnd, IDD_APPLYNOW, std::wstring(L"Apply")); break; case PSCB_BUTTONPRESSED: if (lParam == PSBTN_OK || lParam == PSBTN_APPLYNOW) { HWND hApply = GetDlgItem(hWnd, IDD_APPLYNOW); if (IsWindowEnabled(hApply)) { /* Save settings*/ CLOG(L"Saving settings..."); for (Tab *tab : tabs) { tab->SaveSettings(); } Settings::Instance()->Save(); CLOG(L"Notifying 3RVX process of settings change"); _3RVX::Message(_3RVX::MSG_LOAD, NULL, true); if (lParam == PSBTN_APPLYNOW && relaunch == true) { /* Language was changed */ SendMessage(tabWnd, WM_CLOSE, NULL, NULL); } else { relaunch = false; } } } break; } return TRUE; } DLGPROC GeneralTabProc(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam) { return general.TabProc(hDlg, message, wParam, lParam); } DLGPROC DisplayTabProc(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam) { return display.TabProc(hDlg, message, wParam, lParam); } DLGPROC HotkeyTabProc(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam) { return hotkeys.TabProc(hDlg, message, wParam, lParam); } DLGPROC AboutTabProc(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam) { return about.TabProc(hDlg, message, wParam, lParam); }
#include "SettingsUI.h" #include <iostream> #include "../3RVX/CommCtl.h" /* DLGTEMPLATEEX Structure */ #include <pshpack1.h> typedef struct DLGTEMPLATEEX { WORD dlgVer; WORD signature; DWORD helpID; DWORD exStyle; DWORD style; WORD cDlgItems; short x; short y; short cx; short cy; } DLGTEMPLATEEX, *LPDLGTEMPLATEEX; #include <poppack.h> /* Needed to determine whether the Apply button is enabled/disabled */ #define IDD_APPLYNOW 0x3021 #include "../3RVX/3RVX.h" #include "../3RVX/LanguageTranslator.h" #include "../3RVX/Logger.h" #include "../3RVX/Settings.h" #include "UITranslator.h" #include "Updater.h" #include "UpdaterWindow.h" /* Tabs*/ #include "Tabs/Tab.h" #include "Tabs/General.h" #include "Tabs/Display.h" #include "Tabs/Hotkeys.h" #include "Tabs/About.h" General general; Display display; Hotkeys hotkeys; About about; Tab *tabs[] = { &general, &display, &hotkeys, &about }; /* Startup x/y location offsets */ #define XOFFSET 70 #define YOFFSET 20 HANDLE mutex; HWND mainWnd = NULL; HWND tabWnd = NULL; HINSTANCE hInst; bool relaunch = false; int APIENTRY wWinMain( _In_ HINSTANCE hInstance, _In_opt_ HINSTANCE hPrevInstance, _In_ LPTSTR lpCmdLine, _In_ int nCmdShow) { hInst = hInstance; UNREFERENCED_PARAMETER(hPrevInstance); UNREFERENCED_PARAMETER(lpCmdLine); Logger::Start(); CLOG(L"Starting SettingsUI..."); mutex = CreateMutex(NULL, FALSE, L"Local\\3RVXSettings"); if (GetLastError() == ERROR_ALREADY_EXISTS) { if (mutex) { ReleaseMutex(mutex); } HWND settingsWnd = _3RVX::MasterSettingsHwnd(); CLOG(L"A settings instance is already running. Moving window [%d] " L"to the foreground.", (int) settingsWnd); SetForegroundWindow(settingsWnd); SendMessage( settingsWnd, _3RVX::WM_3RVX_SETTINGSCTRL, _3RVX::MSG_ACTIVATE, NULL); #if defined(ENABLE_3RVX_LOG) && (defined(ENABLE_3RVX_LOGTOFILE) == FALSE) CLOG(L"Press [enter] to terminate"); std::cin.get(); #endif return EXIT_SUCCESS; } /* Inspect command line parameters to determine whether this settings * instance is being launched as an update checker. We do this *after* the * mutex check to avoid situations where the updater and usual settings app * are writing to the settings file at the same time. */ std::wstring cmdLine(lpCmdLine); if (cmdLine.find(L"-update") != std::wstring::npos) { if (Updater::NewerVersionAvailable()) { CLOG(L"An update is available. Showing update icon."); UpdaterWindow uw; PostMessage( uw.Handle(), _3RVX::WM_3RVX_SETTINGSCTRL, _3RVX::MSG_UPDATEICON, NULL); /* Do the standard message pump */ MSG msg; while (GetMessage(&msg, NULL, 0, 0)) { TranslateMessage(&msg); DispatchMessage(&msg); } } else { #if defined(ENABLE_3RVX_LOG) && (defined(ENABLE_3RVX_LOGTOFILE) == FALSE) CLOG(L"No update available. Press [enter] to terminate"); std::cin.get(); #endif } /* Process was used for updates; time to quit. */ return 0; } WNDCLASSEX wcex = { 0 }; wcex.cbSize = sizeof(WNDCLASSEX); wcex.lpfnWndProc = WndProc; wcex.hInstance = hInst; wcex.hIcon = LoadIcon(NULL, MAKEINTRESOURCE(IDI_SETTINGS)); wcex.hbrBackground = (HBRUSH) (COLOR_WINDOW); wcex.lpszClassName = _3RVX::CLASS_3RVX_SETTINGS; if (RegisterClassEx(&wcex) == 0) { CLOG(L"Could not register class: %d", GetLastError()); return EXIT_FAILURE; } mainWnd = CreateWindowEx( NULL, _3RVX::CLASS_3RVX_SETTINGS, _3RVX::CLASS_3RVX_SETTINGS, NULL, 0, 0, 0, 0, NULL, NULL, hInst, NULL); INT_PTR result; do { result = LaunchPropertySheet(); CLOG(L"RL: %s", relaunch ? L"TRUE" : L"FALSE"); } while (relaunch == true); return result; } INT_PTR LaunchPropertySheet() { Settings *settings = Settings::Instance(); settings->Load(); PROPSHEETPAGE psp[4]; LanguageTranslator *lt = settings->Translator(); std::wstring genTitle = lt->Translate(std::wstring(L"General")); std::wstring dispTitle = lt->Translate(std::wstring(L"Display")); std::wstring hkTitle = lt->Translate(std::wstring(L"Hotkeys")); std::wstring aboutTitle = lt->Translate(std::wstring(L"About")); psp[0] = { 0 }; psp[0].dwSize = sizeof(PROPSHEETPAGE); psp[0].dwFlags = PSP_USETITLE; psp[0].hInstance = hInst; psp[0].pszTemplate = MAKEINTRESOURCE(IDD_GENERAL); psp[0].pszIcon = NULL; psp[0].pfnDlgProc = (DLGPROC) GeneralTabProc; psp[0].pszTitle = &genTitle[0]; psp[0].lParam = NULL; psp[1] = { 0 }; psp[1].dwSize = sizeof(PROPSHEETPAGE); psp[1].dwFlags = PSP_USETITLE; psp[1].hInstance = hInst; psp[1].pszTemplate = MAKEINTRESOURCE(IDD_DISPLAY); psp[1].pszIcon = NULL; psp[1].pfnDlgProc = (DLGPROC) DisplayTabProc; psp[1].pszTitle = &dispTitle[0]; psp[1].lParam = 0; psp[2] = { 0 }; psp[2].dwSize = sizeof(PROPSHEETPAGE); psp[2].dwFlags = PSP_USETITLE; psp[2].hInstance = hInst; psp[2].pszTemplate = MAKEINTRESOURCE(IDD_HOTKEYS); psp[2].pszIcon = NULL; psp[2].pfnDlgProc = (DLGPROC) HotkeyTabProc; psp[2].pszTitle = &hkTitle[0]; psp[2].lParam = 0; psp[3] = { 0 }; psp[3].dwSize = sizeof(PROPSHEETPAGE); psp[3].dwFlags = PSP_USETITLE; psp[3].hInstance = hInst; psp[3].pszTemplate = MAKEINTRESOURCE(IDD_ABOUT); psp[3].pszIcon = NULL; psp[3].pfnDlgProc = (DLGPROC) AboutTabProc; psp[3].pszTitle = &aboutTitle[0]; psp[3].lParam = 0; PROPSHEETHEADER psh = { 0 }; psh.dwSize = sizeof(PROPSHEETHEADER); psh.dwFlags = PSH_PROPSHEETPAGE | PSH_USEICONID | PSH_USECALLBACK; psh.hwndParent = mainWnd; psh.hInstance = hInst; psh.pszIcon = MAKEINTRESOURCE(IDI_SETTINGS); psh.pszCaption = L"3RVX Settings"; psh.nStartPage = 0; psh.nPages = sizeof(psp) / sizeof(PROPSHEETPAGE); psh.ppsp = (LPCPROPSHEETPAGE) &psp; psh.pfnCallback = (PFNPROPSHEETCALLBACK) PropSheetProc; tabWnd = NULL; /* Position the window if this is the first launch */ if (relaunch == false) { POINT pt = { 0 }; GetCursorPos(&pt); MoveWindow(mainWnd, pt.x - XOFFSET, pt.y - YOFFSET, 0, 0, TRUE); } relaunch = false; CLOG(L"Launching modal property sheet."); return PropertySheet(&psh); } LRESULT CALLBACK WndProc( HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { PAINTSTRUCT ps; HDC hdc; switch (message) { case WM_PAINT: hdc = BeginPaint(hWnd, &ps); EndPaint(hWnd, &ps); break; case WM_DESTROY: PostQuitMessage(0); break; } if (message == _3RVX::WM_3RVX_SETTINGSCTRL) { switch (wParam) { case _3RVX::MSG_ACTIVATE: CLOG(L"Received request to activate window from external program"); SetActiveWindow(tabWnd); break; case _3RVX::MSG_LANGCHANGE: relaunch = true; break; } } return DefWindowProc(hWnd, message, wParam, lParam); } int CALLBACK PropSheetProc(HWND hWnd, UINT msg, LPARAM lParam) { switch (msg) { case PSCB_PRECREATE: /* Disable the help button: */ if (((LPDLGTEMPLATEEX) lParam)->signature == 0xFFFF) { ((LPDLGTEMPLATEEX) lParam)->style &= ~DS_CONTEXTHELP; } else { ((LPDLGTEMPLATE) lParam)->style &= ~DS_CONTEXTHELP; } /* Show window in the taskbar: */ ((LPDLGTEMPLATE) lParam)->dwExtendedStyle |= WS_EX_APPWINDOW; break; case PSCB_INITIALIZED: UITranslator::TranslateWindowText(hWnd); if (tabWnd == NULL) { tabWnd = hWnd; } /* These values are hard-coded in case the user has a non-english GUI but wants to change the program language */ UITranslator::TranslateControlText( hWnd, IDOK, std::wstring(L"OK")); UITranslator::TranslateControlText( hWnd, IDCANCEL, std::wstring(L"Cancel")); UITranslator::TranslateControlText( hWnd, IDD_APPLYNOW, std::wstring(L"Apply")); break; case PSCB_BUTTONPRESSED: if (lParam == PSBTN_OK || lParam == PSBTN_APPLYNOW) { HWND hApply = GetDlgItem(hWnd, IDD_APPLYNOW); if (IsWindowEnabled(hApply)) { /* Save settings*/ CLOG(L"Saving settings..."); for (Tab *tab : tabs) { tab->SaveSettings(); } Settings::Instance()->Save(); CLOG(L"Notifying 3RVX process of settings change"); _3RVX::Message(_3RVX::MSG_LOAD, NULL, true); if (lParam == PSBTN_APPLYNOW && relaunch == true) { /* Language was changed */ SendMessage(tabWnd, WM_CLOSE, NULL, NULL); } else { relaunch = false; } } } break; } return TRUE; } DLGPROC GeneralTabProc(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam) { return general.TabProc(hDlg, message, wParam, lParam); } DLGPROC DisplayTabProc(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam) { return display.TabProc(hDlg, message, wParam, lParam); } DLGPROC HotkeyTabProc(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam) { return hotkeys.TabProc(hDlg, message, wParam, lParam); } DLGPROC AboutTabProc(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam) { return about.TabProc(hDlg, message, wParam, lParam); }
Move update check to later in the startup process, add documentation
Move update check to later in the startup process, add documentation
C++
bsd-2-clause
malensek/3RVX,malensek/3RVX,malensek/3RVX
f0aaddb533b78643e4d773997185de29c48c22c8
TRD/qaRec/makeResults.C
TRD/qaRec/makeResults.C
// Usage: // makeResults.C("tasks?file_list") // tasks : "ALL" or one/more of the following separated by space: // "EFF" : TRD Tracking Efficiency // "EFFC" : TRD Tracking Efficiency Combined (barrel + stand alone) - only in case of simulations // "RES" : TRD tracking Resolution // "CAL" : TRD calibration // "PID" : TRD PID - pion efficiency // "PIDR" : TRD PID - reference data // "DET" : Basic TRD Detector checks // "NOFR" : Data set does not have AliESDfriends.root // "NOMC" : Data set does not have Monte Carlo Informations (real data), so all tasks which rely // on MC information are switched off // file_list : is the list of the files to be processed. // They should contain the full path. Here is an example: // /lustre_alpha/alice/TRDdata/HEAD/1.0GeV/RUN0/TRD.TaskResolution.root // /lustre_alpha/alice/TRDdata/HEAD/2.0GeV/RUN1/TRD.TaskResolution.root // /lustre_alpha/alice/TRDdata/HEAD/3.0GeV/RUN2/TRD.TaskResolution.root // /lustre_alpha/alice/TRDdata/HEAD/2.0GeV/RUN0/TRD.TaskDetChecker.root // /lustre_alpha/alice/TRDdata/HEAD/2.0GeV/RUN1/TRD.TaskDetChecker.root // /lustre_alpha/alice/TRDdata/HEAD/2.0GeV/RUN2/TRD.TaskDetChecker.root // /lustre_alpha/alice/TRDdata/HEAD/2.0GeV/RUN0/TRD.TaskTrackingEff.root // // The files which will be processed are the initersaction between the // condition on the tasks and the files iin the file list. // // Authors: // Alex Bercuci ([email protected]) // Markus Fasel ([email protected]) // #if ! defined (__CINT__) || defined (__MAKECINT__) #include <fstream> #include "TError.h" #include <TClass.h> #include <TFileMerger.h> #include <TCanvas.h> #include <TH1.h> #include <TGraph.h> #include <TObjArray.h> #include <TObjString.h> #include <TString.h> #include <TROOT.h> #include <TSystem.h> #include <TStyle.h> #include "qaRec/AliTRDrecoTask.h" #endif #include "run.h" Char_t *libs[] = {"libProofPlayer.so", "libANALYSIS.so", "libTRDqaRec.so"}; void makeResults(Char_t *opt = "ALL", const Char_t *files=0x0) { // Load Libraries in interactive mode Int_t nlibs = static_cast<Int_t>(sizeof(libs)/sizeof(Char_t *)); for(Int_t ilib=0; ilib<nlibs; ilib++){ if(gSystem->Load(libs[ilib]) >= 0) continue; printf("Failed to load %s.\n", libs[ilib]); return; } gStyle->SetOptStat(0); Bool_t mc = kTRUE; Bool_t friends = kTRUE; // select tasks to process; we should move it to an // individual function and move the task identifiers // outside the const space TString tasks(opt); TObjArray *tasksArray = tasks.Tokenize(" "); Int_t fSteerTask = 0; for(Int_t isel = 0; isel < tasksArray->GetEntriesFast(); isel++){ TString s = (dynamic_cast<TObjString *>(tasksArray->UncheckedAt(isel)))->String(); if(s.CompareTo("ALL") == 0){ for(Int_t itask = 1; itask < NQATASKS; itask++) SETBIT(fSteerTask, itask); continue; } else if(s.CompareTo("NOFR") == 0){ friends = kFALSE; } else if(s.CompareTo("NOMC") == 0){ mc = kFALSE; } else { Bool_t foundOpt = kFALSE; for(Int_t itask = 1; itask < NTRDTASKS; itask++){ if(s.CompareTo(fgkTRDtaskOpt[itask]) != 0) continue; SETBIT(fSteerTask, itask); foundOpt = kTRUE; break; } if(!foundOpt) Info("makeResults.C", Form("Task %s not implemented (yet).", s.Data())); } } // extra rules for calibration tasks if(TSTBIT(fSteerTask, kClErrParam)) SETBIT(fSteerTask, kResolution); if(TSTBIT(fSteerTask, kPIDRefMaker)) SETBIT(fSteerTask, kPIDChecker); if(TSTBIT(fSteerTask, kAlignment)) SETBIT(fSteerTask, kResolution); // file merger object TFileMerger *fFM = 0x0; TClass *ctask = new TClass; AliTRDrecoTask *task = 0x0; Int_t nFiles; if(gSystem->AccessPathName(Form("%s/merge", gSystem->ExpandPathName("$PWD")))) gSystem->Exec(Form("mkdir -v %s/merge", gSystem->ExpandPathName("$PWD"))); for(Int_t itask = 1; itask<NTRDTASKS; itask++){ if(!TSTBIT(fSteerTask, itask)) continue; new(ctask) TClass(fgkTRDtaskClassName[itask]); task = (AliTRDrecoTask*)ctask->New(); task->SetDebugLevel(0); task->SetMCdata(mc); task->SetFriends(friends); // setup filelist nFiles = 0; TString mark(Form("%s.root", task->GetName())); string filename; if(files){ ifstream filestream(files); while(getline(filestream, filename)){ if(Int_t(filename.find(mark.Data())) < 0) continue; nFiles++; } } else { nFiles = !gSystem->AccessPathName(Form("TRD.Task%s.root", task->GetName())); } if(!nFiles){ Info("makeResults.C", Form("No Files found for Task %s", task->GetName())); delete task; continue; } Info("makeResults.C", Form(" Processing %d files for task %s ...", nFiles, task->GetName())); if(files){ fFM = new TFileMerger(kTRUE); fFM->OutputFile(Form("%s/merge/TRD.Task%s.root", gSystem->ExpandPathName("$PWD"), task->GetName())); ifstream file(files); while(getline(file, filename)){ if(Int_t(filename.find(mark.Data())) < 0) continue; fFM->AddFile(filename.c_str()); } fFM->Merge(); delete fFM; if(!task->Load(Form("%s/merge/TRD.Task%s.root", gSystem->ExpandPathName("$PWD"), task->GetName()))){ delete task; break; } } else{ if(!task->Load(Form("%s/TRD.Task%s.root", gSystem->ExpandPathName("$PWD"), task->GetName()))){ delete task; break; } } printf("Processing ...\n"); task->PostProcess(); TCanvas *c=new TCanvas(); for(Int_t ipic=0; ipic<task->GetNRefFigures(); ipic++){ if(!task->GetRefFigure(ipic)) continue; c->SaveAs(Form("%s_fig%d.gif", task->GetName(), ipic)); c->Clear(); } delete c; delete task; } delete ctask; }
// Usage: // makeResults.C("tasks", "file_list", kGRID) // tasks : "ALL" or one/more of the following separated by space: // "EFF" : TRD Tracking Efficiency // "EFFC" : TRD Tracking Efficiency Combined (barrel + stand alone) - only in case of simulations // "RES" : TRD tracking Resolution // "CAL" : TRD calibration // "PID" : TRD PID - pion efficiency // "PIDR" : TRD PID - reference data // "DET" : Basic TRD Detector checks // "NOFR" : Data set does not have AliESDfriends.root // "NOMC" : Data set does not have Monte Carlo Informations (real data), so all tasks which rely // on MC information are switched off // file_list : is the list of the files to be processed. // They should contain the full path. Here is an example: // /lustre_alpha/alice/TRDdata/HEAD/1.0GeV/RUN0/TRD.TaskResolution.root // or for GRID alien:///alice/cern.ch/user/m/mfasel/MinBiasProd/results/ppMinBias80000/1/TRD.TaskDetChecker.root // kGRID : specify if files are comming from a GRID collection [default kFALSE] // // HOW TO BUILD THE FILE LIST // 1. locally // ls -1 BaseDir/TRD.Task*.root > files.lst // // 2. on Grid // char *BaseDir="/alice/cern.ch/user/m/mfasel/MinBiasProd/results/ppMinBias80000/"; // TGrid::Connect("alien://"); // TGridResult *res = gGrid->Query(BaseDir, "%/TRD.Task%.root"); // TGridCollection *col = gGrid->OpenCollectionQuery(res); // col->Reset(); // TMap *map = 0x0; // while(map = (TMap*)col->Next()){ // TIter it((TCollection*)map); // TObjString *info = 0x0; // while(info=(TObjString*)it()){ // printf("alien://%s\n", col->GetLFN(info->GetString().Data())); // } // } // // The files which will be processed are the intersection between the // condition on the tasks and the files in the file list. // // Authors: // Alex Bercuci ([email protected]) // Markus Fasel ([email protected]) // #if ! defined (__CINT__) || defined (__MAKECINT__) #include <fstream> #include "TError.h" #include <TClass.h> #include <TFileMerger.h> #include <TCanvas.h> #include <TH1.h> #include <TGraph.h> #include <TObjArray.h> #include <TObjString.h> #include <TString.h> #include <TROOT.h> #include <TSystem.h> #include <TStyle.h> #include "qaRec/AliTRDrecoTask.h" #endif #include "run.h" Char_t *libs[] = {"libProofPlayer.so", "libANALYSIS.so", "libTRDqaRec.so"}; void makeResults(Char_t *opt = "ALL", const Char_t *files=0x0, Bool_t kGRID=kFALSE) { if(kGRID){ if(!gSystem->Getenv("GSHELL_ROOT")){ printf("alien not initialized.\n"); return; } TGrid::Connect("alien://"); } // Load Libraries in interactive mode Int_t nlibs = static_cast<Int_t>(sizeof(libs)/sizeof(Char_t *)); for(Int_t ilib=0; ilib<nlibs; ilib++){ if(gSystem->Load(libs[ilib]) >= 0) continue; printf("Failed to load %s.\n", libs[ilib]); return; } gStyle->SetOptStat(0); Bool_t mc = kTRUE; Bool_t friends = kTRUE; // select tasks to process; we should move it to an // individual function and move the task identifiers // outside the const space TString tasks(opt); TObjArray *tasksArray = tasks.Tokenize(" "); Int_t fSteerTask = 0; for(Int_t isel = 0; isel < tasksArray->GetEntriesFast(); isel++){ TString s = (dynamic_cast<TObjString *>(tasksArray->UncheckedAt(isel)))->String(); if(s.CompareTo("ALL") == 0){ for(Int_t itask = 1; itask < NQATASKS; itask++) SETBIT(fSteerTask, itask); continue; } else if(s.CompareTo("NOFR") == 0){ friends = kFALSE; } else if(s.CompareTo("NOMC") == 0){ mc = kFALSE; } else { Bool_t foundOpt = kFALSE; for(Int_t itask = 1; itask < NTRDTASKS; itask++){ if(s.CompareTo(fgkTRDtaskOpt[itask]) != 0) continue; SETBIT(fSteerTask, itask); foundOpt = kTRUE; break; } if(!foundOpt) Info("makeResults.C", Form("Task %s not implemented (yet).", s.Data())); } } // extra rules for calibration tasks if(TSTBIT(fSteerTask, kClErrParam)) SETBIT(fSteerTask, kResolution); if(TSTBIT(fSteerTask, kPIDRefMaker)) SETBIT(fSteerTask, kPIDChecker); if(TSTBIT(fSteerTask, kAlignment)) SETBIT(fSteerTask, kResolution); // file merger object TFileMerger *fFM = 0x0; TClass *ctask = new TClass; AliTRDrecoTask *task = 0x0; Int_t nFiles; if(gSystem->AccessPathName(Form("%s/merge", gSystem->ExpandPathName("$PWD")))) gSystem->Exec(Form("mkdir -v %s/merge", gSystem->ExpandPathName("$PWD"))); for(Int_t itask = 1; itask<NTRDTASKS; itask++){ if(!TSTBIT(fSteerTask, itask)) continue; new(ctask) TClass(fgkTRDtaskClassName[itask]); task = (AliTRDrecoTask*)ctask->New(); task->SetDebugLevel(0); task->SetMCdata(mc); task->SetFriends(friends); // setup filelist nFiles = 0; TString mark(Form("%s.root", task->GetName())); string filename; if(files){ ifstream filestream(files); while(getline(filestream, filename)){ if(Int_t(filename.find(mark.Data())) < 0) continue; nFiles++; } } else { nFiles = !gSystem->AccessPathName(Form("TRD.Task%s.root", task->GetName())); } if(!nFiles){ Info("makeResults.C", Form("No Files found for Task %s", task->GetName())); delete task; continue; } Info("makeResults.C", Form(" Processing %d files for task %s ...", nFiles, task->GetName())); if(files){ fFM = new TFileMerger(kTRUE); fFM->OutputFile(Form("%s/merge/TRD.Task%s.root", gSystem->ExpandPathName("$PWD"), task->GetName())); ifstream file(files); while(getline(file, filename)){ if(Int_t(filename.find(mark.Data())) < 0) continue; fFM->AddFile(filename.c_str()); } fFM->Merge(); delete fFM; if(!task->Load(Form("%s/merge/TRD.Task%s.root", gSystem->ExpandPathName("$PWD"), task->GetName()))){ delete task; break; } } else{ if(!task->Load(Form("%s/TRD.Task%s.root", gSystem->ExpandPathName("$PWD"), task->GetName()))){ delete task; break; } } printf("Processing ...\n"); task->PostProcess(); TCanvas *c=new TCanvas(); for(Int_t ipic=0; ipic<task->GetNRefFigures(); ipic++){ if(!task->GetRefFigure(ipic)) continue; c->SaveAs(Form("%s_fig%d.gif", task->GetName(), ipic)); c->Clear(); } delete c; delete task; } delete ctask; }
update makeResults for GRID usage
update makeResults for GRID usage
C++
bsd-3-clause
shahor02/AliRoot,coppedis/AliRoot,sebaleh/AliRoot,ecalvovi/AliRoot,mkrzewic/AliRoot,miranov25/AliRoot,ecalvovi/AliRoot,jgrosseo/AliRoot,mkrzewic/AliRoot,ecalvovi/AliRoot,coppedis/AliRoot,mkrzewic/AliRoot,sebaleh/AliRoot,ALICEHLT/AliRoot,miranov25/AliRoot,ALICEHLT/AliRoot,jgrosseo/AliRoot,sebaleh/AliRoot,miranov25/AliRoot,ecalvovi/AliRoot,shahor02/AliRoot,alisw/AliRoot,shahor02/AliRoot,ecalvovi/AliRoot,jgrosseo/AliRoot,miranov25/AliRoot,mkrzewic/AliRoot,alisw/AliRoot,jgrosseo/AliRoot,miranov25/AliRoot,shahor02/AliRoot,coppedis/AliRoot,shahor02/AliRoot,coppedis/AliRoot,ecalvovi/AliRoot,ALICEHLT/AliRoot,jgrosseo/AliRoot,coppedis/AliRoot,coppedis/AliRoot,sebaleh/AliRoot,alisw/AliRoot,mkrzewic/AliRoot,shahor02/AliRoot,alisw/AliRoot,mkrzewic/AliRoot,sebaleh/AliRoot,ALICEHLT/AliRoot,jgrosseo/AliRoot,ALICEHLT/AliRoot,miranov25/AliRoot,sebaleh/AliRoot,shahor02/AliRoot,alisw/AliRoot,sebaleh/AliRoot,miranov25/AliRoot,miranov25/AliRoot,jgrosseo/AliRoot,alisw/AliRoot,ALICEHLT/AliRoot,mkrzewic/AliRoot,ecalvovi/AliRoot,alisw/AliRoot,coppedis/AliRoot,ALICEHLT/AliRoot,coppedis/AliRoot,alisw/AliRoot
52b998c5304db5c1511f3fc6fc0160a66dc8627a
Test/SegmentListTest.cc
Test/SegmentListTest.cc
#include <SegmentList.hh> #include "catch.hpp" SCENARIO("Kernel heap allocator SegmentList", "[kernelheap]") { GIVEN("A segment list") { SegmentList list; WHEN("The list is empty") { THEN("The count of the list is zero") { CHECK(list.count() == 0); } AND_WHEN("Creating an iterator") { auto i = list.getIterator(); THEN("The iterator has no next item") { CHECK(i.hasNext() == false); } } } WHEN("An item is added") { Segment* s1 = new Segment(); s1->setSize(1); list.add(s1); AND_WHEN("Creating an iterator") { auto i = list.getIterator(); THEN("Iterator has a next item") { CHECK(i.hasNext() == true); AND_THEN("The next item is the item added") { CHECK(&i.getNext() == s1); AND_THEN("The iterator has no next item") { CHECK(i.hasNext() == false); } } } } } WHEN("Three items are present") { Segment* s2 = new Segment(); Segment* s3 = new Segment(); s2->setSize(2); s3->setSize(3); list.add(s2); list.add(s3); } } }
#include <SegmentList.hh> #include "catch.hpp" SCENARIO("Kernel heap allocator SegmentList", "[kernelheap]") { GIVEN("A segment list") { SegmentList list; Segment* s2 = new Segment(); Segment* s3 = new Segment(); Segment* s1 = new Segment(); WHEN("The list is empty") { THEN("The count of the list is zero") { CHECK(list.count() == 0); } AND_WHEN("Creating an iterator") { auto i = list.getIterator(); THEN("The iterator has no next item") { CHECK(i.hasNext() == false); } } } WHEN("An item is added") { list.add(s1); AND_WHEN("An iterator is created") { auto i = list.getIterator(); THEN("Iterator has a next item") { CHECK(i.hasNext() == true); AND_THEN("The next item is the item added") { CHECK(&i.getNext() == s1); AND_THEN("The iterator has no next item") { CHECK(i.hasNext() == false); } } } } AND_WHEN("An iterator is created") { auto i = list.getIterator(); THEN("The item count is one") { REQUIRE(list.count() == 1); AND_WHEN("Calling remove on the iterator") { i.remove(); THEN("There is no next item") { REQUIRE(i.hasNext() == false); AND_THEN("The count is zero") { REQUIRE(list.count() == 0); } } } } } } WHEN("Three items are added to the list") { list.add(s1); list.add(s2); list.add(s3); AND_WHEN("An iterator is created") { auto i = list.getIterator(); THEN("The the items can be accessed in order") { REQUIRE(i.hasNext()); CHECK(&i.getNext() == s1); } } } } }
Add more tests
Add more tests
C++
bsd-2-clause
ahoka/esrtk,ahoka/esrtk,ahoka/esrtk
65c14d1520f3d1f3fdd09aeb65856f055b74828f
ros/src/sensing/filters/packages/points_preprocessor/nodes/points_concat_filter/points_concat_filter.cpp
ros/src/sensing/filters/packages/points_preprocessor/nodes/points_concat_filter/points_concat_filter.cpp
/* * Copyright (c) 2018, Nagoya University * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of Autoware nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <ros/ros.h> #include <sensor_msgs/PointCloud2.h> #include <message_filters/subscriber.h> #include <message_filters/synchronizer.h> #include <message_filters/sync_policies/approximate_time.h> #include <pcl_ros/point_cloud.h> #include <pcl_ros/transforms.h> #include <pcl_conversions/pcl_conversions.h> #include <pcl/point_types.h> #include <velodyne_pointcloud/point_types.h> #include <tf/tf.h> #include <tf/transform_listener.h> #include <yaml-cpp/yaml.h> class PointsConcatFilter { public: PointsConcatFilter(); private: typedef pcl::PointXYZI PointT; typedef pcl::PointCloud<PointT> PointCloudT; typedef sensor_msgs::PointCloud2 PointCloudMsgT; typedef message_filters::sync_policies::ApproximateTime<PointCloudMsgT, PointCloudMsgT, PointCloudMsgT, PointCloudMsgT, PointCloudMsgT, PointCloudMsgT, PointCloudMsgT, PointCloudMsgT> SyncPolicyT; ros::NodeHandle node_handle_, private_node_handle_; message_filters::Subscriber<PointCloudMsgT>* cloud_subscribers_[8]; message_filters::Synchronizer<SyncPolicyT>* cloud_synchronizer_; ros::Subscriber config_subscriber_; ros::Publisher cloud_publisher_; tf::TransformListener tf_listener_; size_t input_topics_size_; std::string input_topics_; std::string output_frame_id_; void pointcloud_callback(const PointCloudMsgT::ConstPtr& msg1, const PointCloudMsgT::ConstPtr& msg2, const PointCloudMsgT::ConstPtr& msg3, const PointCloudMsgT::ConstPtr& msg4, const PointCloudMsgT::ConstPtr& msg5, const PointCloudMsgT::ConstPtr& msg6, const PointCloudMsgT::ConstPtr& msg7, const PointCloudMsgT::ConstPtr& msg8); }; PointsConcatFilter::PointsConcatFilter() : node_handle_(), private_node_handle_("~"), tf_listener_() { private_node_handle_.param("input_topics", input_topics_, std::string("[ /points_alpha, /points_beta ]")); private_node_handle_.param("output_frame_id", output_frame_id_, std::string("velodyne")); YAML::Node topics = YAML::Load(input_topics_); input_topics_size_ = topics.size(); if (input_topics_size_ < 2 || 8 < input_topics_size_) { ROS_ERROR("The size of input_topics must be between 2 and 8"); ros::shutdown(); } for (size_t i = 0; i < 8; ++i) { if (i < topics.size()) cloud_subscribers_[i] = new message_filters::Subscriber<PointCloudMsgT>(node_handle_, topics[i].as<std::string>(), 1); else cloud_subscribers_[i] = new message_filters::Subscriber<PointCloudMsgT>(node_handle_, topics[0].as<std::string>(), 1); } cloud_synchronizer_ = new message_filters::Synchronizer<SyncPolicyT>(SyncPolicyT(10), *cloud_subscribers_[0], *cloud_subscribers_[1], *cloud_subscribers_[2], *cloud_subscribers_[3], *cloud_subscribers_[4], *cloud_subscribers_[5], *cloud_subscribers_[6], *cloud_subscribers_[7]); cloud_synchronizer_->registerCallback(boost::bind(&PointsConcatFilter::pointcloud_callback, this, _1, _2, _3, _4, _5, _6, _7, _8)); cloud_publisher_ = node_handle_.advertise<PointCloudMsgT>("/points_concat", 1); } void PointsConcatFilter::pointcloud_callback(const PointCloudMsgT::ConstPtr& msg1, const PointCloudMsgT::ConstPtr& msg2, const PointCloudMsgT::ConstPtr& msg3, const PointCloudMsgT::ConstPtr& msg4, const PointCloudMsgT::ConstPtr& msg5, const PointCloudMsgT::ConstPtr& msg6, const PointCloudMsgT::ConstPtr& msg7, const PointCloudMsgT::ConstPtr& msg8) { assert(2 < input_topics_size_ && input_topics_size_ < 8); PointCloudMsgT::ConstPtr msgs[8] = { msg1, msg2, msg3, msg4, msg5, msg6, msg7, msg8 }; PointCloudT::Ptr cloud_sources[8]; PointCloudT::Ptr cloud_concatenated(new PointCloudT); // transform points try { for (size_t i = 0; i < input_topics_size_; ++i) { // Note: If you use kinetic, you can directly receive messages as PointCloutT. cloud_sources[i] = PointCloudT().makeShared(); pcl::fromROSMsg(*msgs[i], *cloud_sources[i]); tf_listener_.waitForTransform(output_frame_id_, msgs[i]->header.frame_id, ros::Time(0), ros::Duration(1.0)); pcl_ros::transformPointCloud(output_frame_id_, *cloud_sources[i], *cloud_sources[i], tf_listener_); } } catch (tf::TransformException& ex) { ROS_ERROR("%s", ex.what()); return; } // merge points for (size_t i = 0; i < input_topics_size_; ++i) *cloud_concatenated += *cloud_sources[i]; // publsh points cloud_concatenated->header = pcl_conversions::toPCL(msgs[0]->header); cloud_concatenated->header.frame_id = output_frame_id_; cloud_publisher_.publish(cloud_concatenated); } int main(int argc, char** argv) { ros::init(argc, argv, "points_concat_filter"); PointsConcatFilter node; ros::spin(); return 0; }
/* * Copyright (c) 2018, Nagoya University * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of Autoware nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <ros/ros.h> #include <sensor_msgs/PointCloud2.h> #include <message_filters/subscriber.h> #include <message_filters/synchronizer.h> #include <message_filters/sync_policies/approximate_time.h> #include <pcl_ros/point_cloud.h> #include <pcl_ros/transforms.h> #include <pcl_conversions/pcl_conversions.h> #include <pcl/point_types.h> #include <velodyne_pointcloud/point_types.h> #include <tf/tf.h> #include <tf/transform_listener.h> #include <yaml-cpp/yaml.h> class PointsConcatFilter { public: PointsConcatFilter(); private: typedef pcl::PointXYZI PointT; typedef pcl::PointCloud<PointT> PointCloudT; typedef sensor_msgs::PointCloud2 PointCloudMsgT; typedef message_filters::sync_policies::ApproximateTime<PointCloudMsgT, PointCloudMsgT, PointCloudMsgT, PointCloudMsgT, PointCloudMsgT, PointCloudMsgT, PointCloudMsgT, PointCloudMsgT> SyncPolicyT; ros::NodeHandle node_handle_, private_node_handle_; message_filters::Subscriber<PointCloudMsgT>* cloud_subscribers_[8]; message_filters::Synchronizer<SyncPolicyT>* cloud_synchronizer_; ros::Subscriber config_subscriber_; ros::Publisher cloud_publisher_; tf::TransformListener tf_listener_; size_t input_topics_size_; std::string input_topics_; std::string output_frame_id_; void pointcloud_callback(const PointCloudMsgT::ConstPtr& msg1, const PointCloudMsgT::ConstPtr& msg2, const PointCloudMsgT::ConstPtr& msg3, const PointCloudMsgT::ConstPtr& msg4, const PointCloudMsgT::ConstPtr& msg5, const PointCloudMsgT::ConstPtr& msg6, const PointCloudMsgT::ConstPtr& msg7, const PointCloudMsgT::ConstPtr& msg8); }; PointsConcatFilter::PointsConcatFilter() : node_handle_(), private_node_handle_("~"), tf_listener_() { private_node_handle_.param("input_topics", input_topics_, std::string("[ /points_alpha, /points_beta ]")); private_node_handle_.param("output_frame_id", output_frame_id_, std::string("velodyne")); YAML::Node topics = YAML::Load(input_topics_); input_topics_size_ = topics.size(); if (input_topics_size_ < 2 || 8 < input_topics_size_) { ROS_ERROR("The size of input_topics must be between 2 and 8"); ros::shutdown(); } for (size_t i = 0; i < 8; ++i) { if (i < topics.size()) cloud_subscribers_[i] = new message_filters::Subscriber<PointCloudMsgT>(node_handle_, topics[i].as<std::string>(), 1); else cloud_subscribers_[i] = new message_filters::Subscriber<PointCloudMsgT>(node_handle_, topics[0].as<std::string>(), 1); } cloud_synchronizer_ = new message_filters::Synchronizer<SyncPolicyT>( SyncPolicyT(10), *cloud_subscribers_[0], *cloud_subscribers_[1], *cloud_subscribers_[2], *cloud_subscribers_[3], *cloud_subscribers_[4], *cloud_subscribers_[5], *cloud_subscribers_[6], *cloud_subscribers_[7]); cloud_synchronizer_->registerCallback( boost::bind(&PointsConcatFilter::pointcloud_callback, this, _1, _2, _3, _4, _5, _6, _7, _8)); cloud_publisher_ = node_handle_.advertise<PointCloudMsgT>("/points_concat", 1); } void PointsConcatFilter::pointcloud_callback(const PointCloudMsgT::ConstPtr& msg1, const PointCloudMsgT::ConstPtr& msg2, const PointCloudMsgT::ConstPtr& msg3, const PointCloudMsgT::ConstPtr& msg4, const PointCloudMsgT::ConstPtr& msg5, const PointCloudMsgT::ConstPtr& msg6, const PointCloudMsgT::ConstPtr& msg7, const PointCloudMsgT::ConstPtr& msg8) { assert(2 < input_topics_size_ && input_topics_size_ < 8); PointCloudMsgT::ConstPtr msgs[8] = { msg1, msg2, msg3, msg4, msg5, msg6, msg7, msg8 }; PointCloudT::Ptr cloud_sources[8]; PointCloudT::Ptr cloud_concatenated(new PointCloudT); // transform points try { for (size_t i = 0; i < input_topics_size_; ++i) { // Note: If you use kinetic, you can directly receive messages as PointCloutT. cloud_sources[i] = PointCloudT().makeShared(); pcl::fromROSMsg(*msgs[i], *cloud_sources[i]); tf_listener_.waitForTransform(output_frame_id_, msgs[i]->header.frame_id, ros::Time(0), ros::Duration(1.0)); pcl_ros::transformPointCloud(output_frame_id_, *cloud_sources[i], *cloud_sources[i], tf_listener_); } } catch (tf::TransformException& ex) { ROS_ERROR("%s", ex.what()); return; } // merge points for (size_t i = 0; i < input_topics_size_; ++i) *cloud_concatenated += *cloud_sources[i]; // publsh points cloud_concatenated->header = pcl_conversions::toPCL(msgs[0]->header); cloud_concatenated->header.frame_id = output_frame_id_; cloud_publisher_.publish(cloud_concatenated); } int main(int argc, char** argv) { ros::init(argc, argv, "points_concat_filter"); PointsConcatFilter node; ros::spin(); return 0; }
apply clang-format
apply clang-format
C++
apache-2.0
CPFL/Autoware,CPFL/Autoware,CPFL/Autoware,CPFL/Autoware,CPFL/Autoware,CPFL/Autoware,CPFL/Autoware
cfaef3d1a2e6067f9b684164bf4f03e8f0cd4d23
engine/storage/FileSystem.cpp
engine/storage/FileSystem.cpp
// Copyright 2015-2020 Elviss Strazdins. All rights reserved. #include "../core/Setup.h" #include <algorithm> #include <fstream> #if defined(_WIN32) # pragma push_macro("WIN32_LEAN_AND_MEAN") # pragma push_macro("NOMINMAX") # ifndef WIN32_LEAN_AND_MEAN # define WIN32_LEAN_AND_MEAN # endif # ifndef NOMINMAX # define NOMINMAX # endif # include <Windows.h> # include <ShlObj.h> # include <Shlwapi.h> # include <strsafe.h> # pragma pop_macro("WIN32_LEAN_AND_MEAN") # pragma pop_macro("NOMINMAX") #elif defined(__APPLE__) # include <TargetConditionals.h> # include <objc/message.h> # include <objc/NSObjCRuntime.h> # include <CoreFoundation/CoreFoundation.h> #elif defined(__ANDROID__) # include "../core/android/EngineAndroid.hpp" #elif defined(__linux__) # include <pwd.h> #endif #include "FileSystem.hpp" #include "Archive.hpp" #include "../core/Engine.hpp" #include "../utils/Log.hpp" #if defined(__APPLE__) # include "CfPointer.hpp" #endif namespace ouzel { namespace storage { FileSystem::FileSystem(Engine& initEngine): engine(initEngine) { #if defined(_WIN32) HINSTANCE instance = GetModuleHandleW(nullptr); if (!instance) throw std::system_error(GetLastError(), std::system_category(), "Failed to get module handle"); std::vector<WCHAR> buffer(MAX_PATH + 1); for (;;) { if (!GetModuleFileNameW(instance, buffer.data(), static_cast<DWORD>(buffer.size()))) throw std::system_error(GetLastError(), std::system_category(), "Failed to get module filename"); if (GetLastError() == ERROR_INSUFFICIENT_BUFFER) buffer.resize(buffer.size() * 2); else break; } const auto executablePath = Path{buffer.data(), Path::Format::native}; appPath = executablePath.getDirectory(); engine.log(Log::Level::info) << "Application directory: " << appPath; #elif defined(__APPLE__) CFBundleRef bundle = CFBundleGetMainBundle(); if (!bundle) throw std::runtime_error("Failed to get main bundle"); CfPointer<CFURLRef> relativePath = CFBundleCopyResourcesDirectoryURL(bundle); if (!relativePath) throw std::runtime_error("Failed to get resource directory"); CfPointer<CFURLRef> absolutePath = CFURLCopyAbsoluteURL(relativePath.get()); CfPointer<CFStringRef> path = CFURLCopyFileSystemPath(absolutePath.get(), kCFURLPOSIXPathStyle); const CFIndex maximumSize = CFStringGetMaximumSizeOfFileSystemRepresentation(path.get()); std::vector<char> resourceDirectory(static_cast<std::size_t>(maximumSize)); const Boolean result = CFStringGetFileSystemRepresentation(path.get(), resourceDirectory.data(), maximumSize); if (!result) throw std::runtime_error("Failed to get resource directory"); appPath = Path{resourceDirectory.data(), Path::Format::native}; engine.log(Log::Level::info) << "Application directory: " << appPath; #elif defined(__ANDROID__) // not available for Android #elif defined(__linux__) char executableDirectory[PATH_MAX]; ssize_t length; if ((length = readlink("/proc/self/exe", executableDirectory, sizeof(executableDirectory) - 1)) == -1) throw std::system_error(errno, std::system_category(), "Failed to get current directory"); executableDirectory[length] = '\0'; const auto executablePath = Path{executableDirectory, Path::Format::native}; appPath = executablePath.getDirectory(); engine.log(Log::Level::info) << "Application directory: " << appPath; #endif } Path FileSystem::getStorageDirectory(const bool user) const { #if defined(_WIN32) WCHAR appDataPath[MAX_PATH]; HRESULT hr; if (FAILED(hr = SHGetFolderPathW(nullptr, (user ? CSIDL_LOCAL_APPDATA : CSIDL_COMMON_APPDATA) | CSIDL_FLAG_CREATE, nullptr, SHGFP_TYPE_CURRENT, appDataPath))) throw std::system_error(hr, std::system_category(), "Failed to get the path of the AppData directory"); Path path = Path{appDataPath, Path::Format::native}; HINSTANCE instance = GetModuleHandleW(nullptr); if (!instance) throw std::system_error(GetLastError(), std::system_category(), "Failed to get module handle"); std::vector<WCHAR> buffer(MAX_PATH + 1); for (;;) { if (!GetModuleFileNameW(instance, buffer.data(), static_cast<DWORD>(buffer.size()))) throw std::system_error(GetLastError(), std::system_category(), "Failed to get module filename"); if (GetLastError() == ERROR_INSUFFICIENT_BUFFER) buffer.resize(buffer.size() * 2); else break; } const auto executablePath = Path{buffer.data(), Path::Format::native}; DWORD handle; const DWORD fileVersionSize = GetFileVersionInfoSizeW(executablePath.getNative().c_str(), &handle); if (!fileVersionSize) throw std::system_error(GetLastError(), std::system_category(), "Failed to get file version size"); auto fileVersionBuffer = std::make_unique<char[]>(fileVersionSize); if (!GetFileVersionInfoW(executablePath.getNative().c_str(), 0, fileVersionSize, fileVersionBuffer.get())) throw std::system_error(GetLastError(), std::system_category(), "Failed to get file version"); LPWSTR companyName = nullptr; LPWSTR productName = nullptr; struct LANGANDCODEPAGE final { WORD wLanguage; WORD wCodePage; }; LPVOID translationPointer; UINT translationLength; if (VerQueryValueW(fileVersionBuffer.get(), L"\\VarFileInfo\\Translation", &translationPointer, &translationLength)) { auto translation = static_cast<const LANGANDCODEPAGE*>(translationPointer); for (UINT i = 0; i < translationLength / sizeof(LANGANDCODEPAGE); ++i) { constexpr size_t subBlockSize = 37; WCHAR subBlock[subBlockSize]; StringCchPrintfW(subBlock, subBlockSize, L"\\StringFileInfo\\%04x%04x\\CompanyName", translation[i].wLanguage, translation[i].wCodePage); LPVOID companyNamePointer; UINT companyNameLength; if (VerQueryValueW(fileVersionBuffer.get(), subBlock, &companyNamePointer, &companyNameLength)) companyName = static_cast<LPWSTR>(companyNamePointer); StringCchPrintfW(subBlock, subBlockSize, L"\\StringFileInfo\\%04x%04x\\ProductName", translation[i].wLanguage, translation[i].wCodePage); LPVOID productNamePointer; UINT productNameLength; if (VerQueryValueW(fileVersionBuffer.get(), subBlock, &productNamePointer, &productNameLength)) productName = static_cast<LPWSTR>(productNamePointer); } } if (companyName) path /= companyName; else path /= OUZEL_DEVELOPER_NAME; if (getFileType(path) != FileType::directory) createDirectory(path); if (productName) path /= productName; else path /= OUZEL_APPLICATION_NAME; if (getFileType(path) != FileType::directory) createDirectory(path); return path; #elif TARGET_OS_IOS || TARGET_OS_TV id fileManager = reinterpret_cast<id (*)(Class, SEL)>(&objc_msgSend)(objc_getClass("NSFileManager"), sel_getUid("defaultManager")); constexpr NSUInteger NSDocumentDirectory = 9; constexpr NSUInteger NSUserDomainMask = 1; constexpr NSUInteger NSLocalDomainMask = 2; id documentDirectory = reinterpret_cast<id (*)(id, SEL, NSUInteger, NSUInteger, id, BOOL, id*)>(&objc_msgSend)(fileManager, sel_getUid("URLForDirectory:inDomain:appropriateForURL:create:error:"), NSDocumentDirectory, user ? NSUserDomainMask : NSLocalDomainMask, nil, YES, nil); if (!documentDirectory) throw std::runtime_error("Failed to get document directory"); id documentDirectoryString = reinterpret_cast<id (*)(id, SEL)>(&objc_msgSend)(documentDirectory, sel_getUid("path")); auto pathUtf8String = reinterpret_cast<const char* (*)(id, SEL)>(&objc_msgSend)(documentDirectoryString, sel_getUid("UTF8String")); return Path{pathUtf8String, Path::Format::native}; #elif TARGET_OS_MAC id fileManager = reinterpret_cast<id (*)(Class, SEL)>(&objc_msgSend)(objc_getClass("NSFileManager"), sel_getUid("defaultManager")); constexpr NSUInteger NSApplicationSupportDirectory = 14; constexpr NSUInteger NSUserDomainMask = 1; constexpr NSUInteger NSLocalDomainMask = 2; id applicationSupportDirectory = reinterpret_cast<id (*)(id, SEL, NSUInteger, NSUInteger, id, BOOL, id*)>(&objc_msgSend)(fileManager, sel_getUid("URLForDirectory:inDomain:appropriateForURL:create:error:"), NSApplicationSupportDirectory, user ? NSUserDomainMask : NSLocalDomainMask, nil, YES, nil); if (!applicationSupportDirectory) throw std::runtime_error("Failed to get application support directory"); CFBundleRef bundle = CFBundleGetMainBundle(); CFStringRef identifier = CFBundleGetIdentifier(bundle); if (!identifier) identifier = CFSTR(OUZEL_DEVELOPER_NAME "." OUZEL_APPLICATION_NAME); id path = reinterpret_cast<id (*)(id, SEL, CFStringRef)>(&objc_msgSend)(applicationSupportDirectory, sel_getUid("URLByAppendingPathComponent:"), identifier); reinterpret_cast<void (*)(id, SEL, id, BOOL, id, id)>(&objc_msgSend)(fileManager, sel_getUid("createDirectoryAtURL:withIntermediateDirectories:attributes:error:"), path, YES, nil, nil); id pathString = reinterpret_cast<id (*)(id, SEL)>(&objc_msgSend)(path, sel_getUid("path")); auto pathUtf8String = reinterpret_cast<const char* (*)(id, SEL)>(&objc_msgSend)(pathString, sel_getUid("UTF8String")); return Path{pathUtf8String, Path::Format::native}; #elif defined(__ANDROID__) static_cast<void>(user); auto& engineAndroid = static_cast<EngineAndroid&>(engine); return engineAndroid.getFilesDirectory(); #elif defined(__linux__) Path path; const char* homeDirectory = std::getenv("XDG_DATA_HOME"); if (homeDirectory) path = Path{homeDirectory, Path::Format::native}; else { struct passwd pwent; struct passwd* pwentp; std::vector<char> buffer(1024); int e; while ((e = getpwuid_r(getuid(), &pwent, buffer.data(), buffer.size(), &pwentp)) == ERANGE) buffer.resize(buffer.size() * 2); if (e != 0) throw std::runtime_error("Failed to get home directory"); else path = Path{pwent.pw_dir, Path::Format::native}; path /= ".local"; if (getFileType(path) != FileType::directory) createDirectory(path); path /= "share"; if (getFileType(path) != FileType::directory) createDirectory(path); } path /= OUZEL_DEVELOPER_NAME; if (getFileType(path) != FileType::directory) createDirectory(path); path /= OUZEL_APPLICATION_NAME; if (getFileType(path) != FileType::directory) createDirectory(path); return path; #else return Path{}; #endif } std::vector<std::uint8_t> FileSystem::readFile(const Path& filename, const bool searchResources) { if (searchResources) for (auto& archive : archives) if (archive.second.fileExists(filename)) return archive.second.readFile(filename); #if defined(__ANDROID__) if (!filename.isAbsolute()) { auto& engineAndroid = static_cast<EngineAndroid&>(engine); auto asset = AAssetManager_open(engineAndroid.getAssetManager(), filename.getNative().c_str(), AASSET_MODE_STREAMING); if (!asset) throw std::runtime_error("Failed to open file " + std::string(filename)); std::vector<std::uint8_t> data; std::uint8_t buffer[1024]; for (;;) { const int bytesRead = AAsset_read(asset, buffer, sizeof(buffer)); if (bytesRead < 0) throw std::runtime_error("Failed to read from file"); else if (bytesRead == 0) break; data.insert(data.end(), buffer, buffer + bytesRead); } AAsset_close(asset); return data; } #endif const auto path = getPath(filename, searchResources); // file does not exist if (path.isEmpty()) throw std::runtime_error("Failed to find file " + std::string(filename)); std::ifstream f(path, std::ios::binary); return {std::istreambuf_iterator<char>(f), std::istreambuf_iterator<char>()}; } bool FileSystem::resourceFileExists(const Path& filename) const { if (filename.isAbsolute()) return fileExists(filename); else { Path result = appPath / filename; if (fileExists(result)) return true; else for (const auto& path : resourcePaths) { if (path.isAbsolute()) // if resource path is absolute result = path / filename; else result = appPath / path / filename; if (fileExists(result)) return true; } return false; } } bool FileSystem::directoryExists(const Path& dirname) const { #if defined(__ANDROID__) auto& engineAndroid = static_cast<EngineAndroid&>(engine); auto assetDir = AAssetManager_openDir(engineAndroid.getAssetManager(), dirname.getNative().c_str()); const auto exists = AAssetDir_getNextFileName(assetDir) != nullptr; AAssetDir_close(assetDir); if (exists) return true; #endif return getFileType(dirname) == FileType::directory; } bool FileSystem::fileExists(const Path& filename) const { #if defined(__ANDROID__) auto& engineAndroid = static_cast<EngineAndroid&>(engine); auto asset = AAssetManager_open(engineAndroid.getAssetManager(), filename.getNative().c_str(), AASSET_MODE_STREAMING); if (asset) { AAsset_close(asset); return true; } #endif return getFileType(filename) == FileType::regular; } } // namespace storage } // namespace ouzel
// Copyright 2015-2020 Elviss Strazdins. All rights reserved. #include "../core/Setup.h" #include <algorithm> #include <fstream> #if defined(_WIN32) # pragma push_macro("WIN32_LEAN_AND_MEAN") # pragma push_macro("NOMINMAX") # ifndef WIN32_LEAN_AND_MEAN # define WIN32_LEAN_AND_MEAN # endif # ifndef NOMINMAX # define NOMINMAX # endif # include <Windows.h> # include <ShlObj.h> # include <Shlwapi.h> # include <strsafe.h> # pragma pop_macro("WIN32_LEAN_AND_MEAN") # pragma pop_macro("NOMINMAX") #elif defined(__APPLE__) # include <TargetConditionals.h> # include <objc/message.h> # include <objc/NSObjCRuntime.h> # include <CoreFoundation/CoreFoundation.h> #elif defined(__ANDROID__) # include "../core/android/EngineAndroid.hpp" #elif defined(__linux__) # include <pwd.h> #endif #include "FileSystem.hpp" #include "Archive.hpp" #include "../core/Engine.hpp" #include "../utils/Log.hpp" #if defined(__APPLE__) # include "CfPointer.hpp" #endif namespace ouzel { namespace storage { FileSystem::FileSystem(Engine& initEngine): engine(initEngine) { #if defined(_WIN32) HINSTANCE instance = GetModuleHandleW(nullptr); if (!instance) throw std::system_error(GetLastError(), std::system_category(), "Failed to get module handle"); std::vector<WCHAR> buffer(MAX_PATH + 1); for (;;) { if (!GetModuleFileNameW(instance, buffer.data(), static_cast<DWORD>(buffer.size()))) throw std::system_error(GetLastError(), std::system_category(), "Failed to get module filename"); if (GetLastError() == ERROR_INSUFFICIENT_BUFFER) buffer.resize(buffer.size() * 2); else break; } const auto executablePath = Path{buffer.data(), Path::Format::native}; appPath = executablePath.getDirectory(); engine.log(Log::Level::info) << "Application directory: " << appPath; #elif defined(__APPLE__) CFBundleRef bundle = CFBundleGetMainBundle(); if (!bundle) throw std::runtime_error("Failed to get main bundle"); CfPointer<CFURLRef> relativePath = CFBundleCopyResourcesDirectoryURL(bundle); if (!relativePath) throw std::runtime_error("Failed to get resource directory"); CfPointer<CFURLRef> absolutePath = CFURLCopyAbsoluteURL(relativePath.get()); CfPointer<CFStringRef> path = CFURLCopyFileSystemPath(absolutePath.get(), kCFURLPOSIXPathStyle); const CFIndex maximumSize = CFStringGetMaximumSizeOfFileSystemRepresentation(path.get()); std::vector<char> resourceDirectory(static_cast<std::size_t>(maximumSize)); const Boolean result = CFStringGetFileSystemRepresentation(path.get(), resourceDirectory.data(), maximumSize); if (!result) throw std::runtime_error("Failed to get resource directory"); appPath = Path{resourceDirectory.data(), Path::Format::native}; engine.log(Log::Level::info) << "Application directory: " << appPath; #elif defined(__ANDROID__) // not available for Android #elif defined(__linux__) char executableDirectory[PATH_MAX]; ssize_t length; if ((length = readlink("/proc/self/exe", executableDirectory, sizeof(executableDirectory) - 1)) == -1) throw std::system_error(errno, std::system_category(), "Failed to get current directory"); executableDirectory[length] = '\0'; const auto executablePath = Path{executableDirectory, Path::Format::native}; appPath = executablePath.getDirectory(); engine.log(Log::Level::info) << "Application directory: " << appPath; #endif } Path FileSystem::getStorageDirectory(const bool user) const { #if defined(_WIN32) WCHAR appDataPath[MAX_PATH]; HRESULT hr; if (FAILED(hr = SHGetFolderPathW(nullptr, (user ? CSIDL_LOCAL_APPDATA : CSIDL_COMMON_APPDATA) | CSIDL_FLAG_CREATE, nullptr, SHGFP_TYPE_CURRENT, appDataPath))) throw std::system_error(hr, std::system_category(), "Failed to get the path of the AppData directory"); Path path = Path{appDataPath, Path::Format::native}; HINSTANCE instance = GetModuleHandleW(nullptr); if (!instance) throw std::system_error(GetLastError(), std::system_category(), "Failed to get module handle"); std::vector<WCHAR> buffer(MAX_PATH + 1); for (;;) { if (!GetModuleFileNameW(instance, buffer.data(), static_cast<DWORD>(buffer.size()))) throw std::system_error(GetLastError(), std::system_category(), "Failed to get module filename"); if (GetLastError() == ERROR_INSUFFICIENT_BUFFER) buffer.resize(buffer.size() * 2); else break; } const auto executablePath = Path{buffer.data(), Path::Format::native}; DWORD handle; const DWORD fileVersionSize = GetFileVersionInfoSizeW(executablePath.getNative().c_str(), &handle); if (!fileVersionSize) throw std::system_error(GetLastError(), std::system_category(), "Failed to get file version size"); auto fileVersionBuffer = std::make_unique<char[]>(fileVersionSize); if (!GetFileVersionInfoW(executablePath.getNative().c_str(), 0, fileVersionSize, fileVersionBuffer.get())) throw std::system_error(GetLastError(), std::system_category(), "Failed to get file version"); LPWSTR companyName = nullptr; LPWSTR productName = nullptr; struct LANGANDCODEPAGE final { WORD wLanguage; WORD wCodePage; }; LPVOID translationPointer; UINT translationLength; if (VerQueryValueW(fileVersionBuffer.get(), L"\\VarFileInfo\\Translation", &translationPointer, &translationLength)) { auto translation = static_cast<const LANGANDCODEPAGE*>(translationPointer); for (UINT i = 0; i < translationLength / sizeof(LANGANDCODEPAGE); ++i) { constexpr size_t subBlockSize = 37; WCHAR subBlock[subBlockSize]; StringCchPrintfW(subBlock, subBlockSize, L"\\StringFileInfo\\%04x%04x\\CompanyName", translation[i].wLanguage, translation[i].wCodePage); LPVOID companyNamePointer; UINT companyNameLength; if (VerQueryValueW(fileVersionBuffer.get(), subBlock, &companyNamePointer, &companyNameLength)) companyName = static_cast<LPWSTR>(companyNamePointer); StringCchPrintfW(subBlock, subBlockSize, L"\\StringFileInfo\\%04x%04x\\ProductName", translation[i].wLanguage, translation[i].wCodePage); LPVOID productNamePointer; UINT productNameLength; if (VerQueryValueW(fileVersionBuffer.get(), subBlock, &productNamePointer, &productNameLength)) productName = static_cast<LPWSTR>(productNamePointer); } } if (companyName) path /= companyName; else path /= OUZEL_DEVELOPER_NAME; if (getFileType(path) != FileType::directory) createDirectory(path); if (productName) path /= productName; else path /= OUZEL_APPLICATION_NAME; if (getFileType(path) != FileType::directory) createDirectory(path); return path; #elif TARGET_OS_IOS || TARGET_OS_TV id fileManager = reinterpret_cast<id (*)(Class, SEL)>(&objc_msgSend)(objc_getClass("NSFileManager"), sel_getUid("defaultManager")); constexpr NSUInteger NSDocumentDirectory = 9; constexpr NSUInteger NSUserDomainMask = 1; constexpr NSUInteger NSLocalDomainMask = 2; id documentDirectory = reinterpret_cast<id (*)(id, SEL, NSUInteger, NSUInteger, id, BOOL, id*)>(&objc_msgSend)(fileManager, sel_getUid("URLForDirectory:inDomain:appropriateForURL:create:error:"), NSDocumentDirectory, user ? NSUserDomainMask : NSLocalDomainMask, nil, YES, nil); if (!documentDirectory) throw std::runtime_error("Failed to get document directory"); id documentDirectoryString = reinterpret_cast<id (*)(id, SEL)>(&objc_msgSend)(documentDirectory, sel_getUid("path")); auto pathUtf8String = reinterpret_cast<const char* (*)(id, SEL)>(&objc_msgSend)(documentDirectoryString, sel_getUid("UTF8String")); return Path{pathUtf8String, Path::Format::native}; #elif TARGET_OS_MAC id fileManager = reinterpret_cast<id (*)(Class, SEL)>(&objc_msgSend)(objc_getClass("NSFileManager"), sel_getUid("defaultManager")); constexpr NSUInteger NSApplicationSupportDirectory = 14; constexpr NSUInteger NSUserDomainMask = 1; constexpr NSUInteger NSLocalDomainMask = 2; id applicationSupportDirectory = reinterpret_cast<id (*)(id, SEL, NSUInteger, NSUInteger, id, BOOL, id*)>(&objc_msgSend)(fileManager, sel_getUid("URLForDirectory:inDomain:appropriateForURL:create:error:"), NSApplicationSupportDirectory, user ? NSUserDomainMask : NSLocalDomainMask, nil, YES, nil); if (!applicationSupportDirectory) throw std::runtime_error("Failed to get application support directory"); CFBundleRef bundle = CFBundleGetMainBundle(); CFStringRef identifier = CFBundleGetIdentifier(bundle); if (!identifier) identifier = CFSTR(OUZEL_DEVELOPER_NAME "." OUZEL_APPLICATION_NAME); id path = reinterpret_cast<id (*)(id, SEL, CFStringRef)>(&objc_msgSend)(applicationSupportDirectory, sel_getUid("URLByAppendingPathComponent:"), identifier); reinterpret_cast<void (*)(id, SEL, id, BOOL, id, id)>(&objc_msgSend)(fileManager, sel_getUid("createDirectoryAtURL:withIntermediateDirectories:attributes:error:"), path, YES, nil, nil); id pathString = reinterpret_cast<id (*)(id, SEL)>(&objc_msgSend)(path, sel_getUid("path")); auto pathUtf8String = reinterpret_cast<const char* (*)(id, SEL)>(&objc_msgSend)(pathString, sel_getUid("UTF8String")); return Path{pathUtf8String, Path::Format::native}; #elif defined(__ANDROID__) static_cast<void>(user); auto& engineAndroid = static_cast<EngineAndroid&>(engine); return engineAndroid.getFilesDirectory(); #elif defined(__linux__) Path path; const char* homeDirectory = std::getenv("XDG_DATA_HOME"); if (homeDirectory) path = Path{homeDirectory, Path::Format::native}; else { struct passwd pwent; struct passwd* pwentp; std::vector<char> buffer(1024); int e; while ((e = getpwuid_r(getuid(), &pwent, buffer.data(), buffer.size(), &pwentp)) == ERANGE) buffer.resize(buffer.size() * 2); if (e != 0) throw std::runtime_error("Failed to get home directory"); else path = Path{pwent.pw_dir, Path::Format::native}; path /= ".local"; if (getFileType(path) != FileType::directory) createDirectory(path); path /= "share"; if (getFileType(path) != FileType::directory) createDirectory(path); } path /= OUZEL_DEVELOPER_NAME; if (getFileType(path) != FileType::directory) createDirectory(path); path /= OUZEL_APPLICATION_NAME; if (getFileType(path) != FileType::directory) createDirectory(path); return path; #else return Path{}; #endif } std::vector<std::uint8_t> FileSystem::readFile(const Path& filename, const bool searchResources) { if (searchResources) for (auto& archive : archives) if (archive.second.fileExists(filename)) return archive.second.readFile(filename); #if defined(__ANDROID__) if (!filename.isAbsolute()) { auto& engineAndroid = static_cast<EngineAndroid&>(engine); auto asset = AAssetManager_open(engineAndroid.getAssetManager(), filename.getNative().c_str(), AASSET_MODE_STREAMING); if (!asset) throw std::runtime_error("Failed to open file " + std::string(filename)); std::vector<std::uint8_t> data; std::uint8_t buffer[1024]; for (;;) { const int bytesRead = AAsset_read(asset, buffer, sizeof(buffer)); if (bytesRead < 0) throw std::runtime_error("Failed to read from file"); else if (bytesRead == 0) break; data.insert(data.end(), buffer, buffer + bytesRead); } AAsset_close(asset); return data; } #endif const auto path = getPath(filename, searchResources); // file does not exist if (path.isEmpty()) throw std::runtime_error("Failed to find file " + std::string(filename)); std::ifstream file(path, std::ios::binary); file.seekg(0, std::ios::end); std::vector<std::uint8_t> data(static_cast<size_t>(file.tellg())); file.seekg(0, std::ios::beg); file.read(reinterpret_cast<char*>(data.data()), static_cast<std::streamsize>(data.size())); return data; } bool FileSystem::resourceFileExists(const Path& filename) const { if (filename.isAbsolute()) return fileExists(filename); else { Path result = appPath / filename; if (fileExists(result)) return true; else for (const auto& path : resourcePaths) { if (path.isAbsolute()) // if resource path is absolute result = path / filename; else result = appPath / path / filename; if (fileExists(result)) return true; } return false; } } bool FileSystem::directoryExists(const Path& dirname) const { #if defined(__ANDROID__) auto& engineAndroid = static_cast<EngineAndroid&>(engine); auto assetDir = AAssetManager_openDir(engineAndroid.getAssetManager(), dirname.getNative().c_str()); const auto exists = AAssetDir_getNextFileName(assetDir) != nullptr; AAssetDir_close(assetDir); if (exists) return true; #endif return getFileType(dirname) == FileType::directory; } bool FileSystem::fileExists(const Path& filename) const { #if defined(__ANDROID__) auto& engineAndroid = static_cast<EngineAndroid&>(engine); auto asset = AAssetManager_open(engineAndroid.getAssetManager(), filename.getNative().c_str(), AASSET_MODE_STREAMING); if (asset) { AAsset_close(asset); return true; } #endif return getFileType(filename) == FileType::regular; } } // namespace storage } // namespace ouzel
Read data directly into the vector
Read data directly into the vector
C++
unlicense
elnormous/ouzel,elnormous/ouzel,elnormous/ouzel
efa0781b47dbbdc10fe4bdfbd82892b8e3b39554
mimosa/channel.hh
mimosa/channel.hh
#ifndef MIMOSA_CHANNEL_HH # define MIMOSA_CHANNEL_HH # include <queue> # include "mutex.hh" # include "condition.hh" # include "ref-countable.hh" namespace mimosa { /** * @ingroup Sync */ template <typename T, typename QueueType = std::queue<T> > class Channel : public RefCountable<Channel<T, QueueType> >, private NonCopyable { public: inline Channel() : closed_(false), queue_(), mutex_(), cond_() { } inline bool push(const T & t) { Mutex::Locker locker(mutex_); if (closed_) return false; queue_.push(t); cond_.wakeOne(); return true; } inline bool pop(T & t) { Mutex::Locker locker(mutex_); while (true) { if (!queue_.empty()) { t = queue_.front(); queue_.pop(); return true; } else if (closed_) return false; cond_.wait(mutex_); } return false; } inline bool tryPop(T & t) { Mutex::Locker locker(mutex_); if (queue_.empty()) return false; t = queue_.front(); queue_.pop(); return true; } /** closes the push end, it is possible to pop * until the channel is empty */ inline void close() { Mutex::Locker locker(mutex_); closed_ = true; cond_.wakeAll(); } inline bool empty() const { return queue_.empty(); } bool closed_; QueueType queue_; Mutex mutex_; Condition cond_; }; } #endif /* !MIMOSA_CHANNEL_HH */
#ifndef MIMOSA_CHANNEL_HH # define MIMOSA_CHANNEL_HH # include <queue> # include <limits> # include "mutex.hh" # include "condition.hh" # include "ref-countable.hh" namespace mimosa { /** * @ingroup Sync */ template <typename T, typename QueueType = std::queue<T> > class Channel : public RefCountable<Channel<T, QueueType> >, private NonCopyable { public: inline Channel() : closed_(false), queue_(), mutex_(), cond_(), max_size_(std::numeric_limits<decltype (max_size_)>::max()) { } inline void setMaxSize(int max_size) { Mutex::Locker locker(mutex_); if (max_size_ < max_size && max_size_ <= queue_.size() && queue_.size() < max_size) push_cond_.wakeAll(); max_size_ = max_size; } inline void maxSize(int max_size) const { return max_size_; } inline bool push(const T & t) { Mutex::Locker locker(mutex_); do { if (closed_) return false; if (queue_.size() < max_size_) break; push_cond_.wait(mutex_); } while (true); queue_.push(t); cond_.wakeOne(); return true; } inline bool pop(T & t) { Mutex::Locker locker(mutex_); while (true) { if (!queue_.empty()) { t = queue_.front(); queue_.pop(); push_cond_.wakeOne(); return true; } else if (closed_) return false; cond_.wait(mutex_); } return false; } inline bool tryPop(T & t) { Mutex::Locker locker(mutex_); if (queue_.empty()) return false; t = queue_.front(); queue_.pop(); push_cond_.wakeOne(); return true; } /** closes the push end, it is possible to pop * until the channel is empty */ inline void close() { Mutex::Locker locker(mutex_); closed_ = true; cond_.wakeAll(); push_cond_.wakeAll(); } inline bool empty() const { return queue_.empty(); } bool closed_; QueueType queue_; Mutex mutex_; Condition cond_; Condition push_cond_; uint32_t max_size_; }; } #endif /* !MIMOSA_CHANNEL_HH */
add a maximum size
Channel: add a maximum size
C++
mit
abique/mimosa,abique/mimosa
93df083aa2b4f661fce45c6f86a7cb99a344b369
tools/gtfcompare/src/compare.cc
tools/gtfcompare/src/compare.cc
#include "compare.h" #include <cassert> bool compare_transcript_structure(const transcript &x, const transcript &y) { if(x.exons.size() != y.exons.size()) return false; for(int i = 0; i < x.exons.size(); i++) { if(x.exons[i].first != y.exons[i].first) return false; if(x.exons[i].second != y.exons[i].second) return false; } return true; } bool compare_transcript_expression(const transcript &x, const transcript &y) { if(x.expression == y.expression) return true; else return false; } bool compare_transcript(const transcript &x, const transcript &y) { if(compare_transcript_structure(x, y) == false) return false; if(compare_transcript_expression(x, y) == false) return false; return true; } int compare_gene(const gene &x, const gene &y) { int cnt = 0; vector<bool> v; v.assign(y.transcripts.size(), false); for(int i = 0; i < x.transcripts.size(); i++) { for(int j = 0; j < y.transcripts.size(); j++) { if(v[j] == true) continue; if(compare_transcript(x.transcripts[i], y.transcripts[j]) == false) continue; v[j] = true; cnt++; break; } } return cnt; } int compare_genome(const genome &x, const genome &y) { int gequal = 0; int tequal = 0; int gtotal = x.genes.size(); int ttotal = 0; for(int i = 0; i < x.genes.size(); i++) { const gene* gx = &(x.genes[i]); const gene* gy = y.get_gene(x.genes[i].get_gene_id()); if(gx == NULL || gy == NULL) continue; int tx = gx->transcripts.size(); int ty = gy->transcripts.size(); int t0 = compare_gene(*gx, *gy); assert(t0 <= tx); assert(t0 <= ty); ttotal += tx; tequal += t0; if(t0 == tx) gequal++; printf("%s %d and %d transcripts, %d are equal, %s\n", gx->get_gene_id().c_str(), tx, ty, t0, (t0 == tx) ? "TRUE" : "FALSE"); } printf("summary: %d out of %d genes are equal, %d out of %d transcripts are equal\n", gequal, gtotal, tequal, ttotal); return 0; }
#include "compare.h" #include <cassert> bool compare_transcript_structure(const transcript &x, const transcript &y) { if(x.exons.size() != y.exons.size()) return false; for(int i = 0; i < x.exons.size(); i++) { if(x.exons[i].first != y.exons[i].first) return false; if(x.exons[i].second != y.exons[i].second) return false; } return true; } bool compare_transcript_expression(const transcript &x, const transcript &y) { if(x.expression == y.expression) return true; else return false; } bool compare_transcript(const transcript &x, const transcript &y) { if(compare_transcript_structure(x, y) == false) return false; if(compare_transcript_expression(x, y) == false) return false; return true; } int compare_gene(const gene &x, const gene &y) { int cnt = 0; vector<bool> v; v.assign(y.transcripts.size(), false); for(int i = 0; i < x.transcripts.size(); i++) { for(int j = 0; j < y.transcripts.size(); j++) { if(v[j] == true) continue; if(compare_transcript(x.transcripts[i], y.transcripts[j]) == false) continue; v[j] = true; cnt++; break; } } return cnt; } int compare_genome(const genome &x, const genome &y) { int gequal = 0; int tequal = 0; int gtotal = x.genes.size(); int ttotal = 0; for(int i = 0; i < x.genes.size(); i++) { const gene* gx = &(x.genes[i]); const gene* gy = y.get_gene(x.genes[i].get_gene_id()); if(gx == NULL || gy == NULL) continue; int tx = gx->transcripts.size(); int ty = gy->transcripts.size(); int t0 = compare_gene(*gx, *gy); assert(t0 <= tx); assert(t0 <= ty); ttotal += tx; tequal += t0; if(t0 == tx) gequal++; string s; if(tx == ty) s = "EQUAL"; else if(tx > ty) s = "GREATER"; else s = "LESS"; printf("%s %d and %d transcripts, %d are equal, %s, %s\n", gx->get_gene_id().c_str(), tx, ty, t0, (t0 == tx) ? "TRUE" : "FALSE", s.c_str()); } printf("summary: %d out of %d genes are equal, %d out of %d transcripts are equal\n", gequal, gtotal, tequal, ttotal); return 0; }
add comparing #transcripts in gtfcompare
add comparing #transcripts in gtfcompare
C++
bsd-3-clause
Kingsford-Group/scallop
9b881deff522d3d394de6a1080b4304a6f31d7c4
osquery/core/query.cpp
osquery/core/query.cpp
/** * Copyright (c) 2014-present, Facebook, Inc. * All rights reserved. * * This source code is licensed in accordance with the terms specified in * the LICENSE file found in the root directory of this source tree. */ #include <algorithm> #include <string> #include <vector> #include <osquery/database.h> #include <osquery/flags.h> #include <osquery/logger.h> #include <osquery/query.h> #include <osquery/utils/json/json.h> namespace rj = rapidjson; namespace osquery { DECLARE_bool(decorations_top_level); /// Log numeric values as numbers (in JSON syntax) FLAG(bool, log_numerics_as_numbers, false, "Use numeric JSON syntax for numeric values"); uint64_t Query::getPreviousEpoch() const { uint64_t epoch = 0; std::string raw; auto status = getDatabaseValue(kQueries, name_ + "epoch", raw); if (status.ok()) { epoch = std::stoull(raw); } return epoch; } uint64_t Query::getQueryCounter(bool new_query) const { uint64_t counter = 0; if (new_query) { return counter; } std::string raw; auto status = getDatabaseValue(kQueries, name_ + "counter", raw); if (status.ok()) { counter = std::stoull(raw) + 1; } return counter; } Status Query::getPreviousQueryResults(QueryDataSet& results) const { std::string raw; auto status = getDatabaseValue(kQueries, name_, raw); if (!status.ok()) { return status; } status = deserializeQueryDataJSON(raw, results); if (!status.ok()) { return status; } return Status::success(); } std::vector<std::string> Query::getStoredQueryNames() { std::vector<std::string> results; scanDatabaseKeys(kQueries, results); return results; } bool Query::isQueryNameInDatabase() const { auto names = Query::getStoredQueryNames(); return std::find(names.begin(), names.end(), name_) != names.end(); } static inline void saveQuery(const std::string& name, const std::string& query) { setDatabaseValue(kQueries, "query." + name, query); } bool Query::isNewQuery() const { std::string query; getDatabaseValue(kQueries, "query." + name_, query); return (query != query_); } Status Query::addNewResults(QueryDataTyped qd, const uint64_t epoch, uint64_t& counter) const { DiffResults dr; return addNewResults(std::move(qd), epoch, counter, dr, false); } Status Query::addNewResults(QueryDataTyped current_qd, const uint64_t current_epoch, uint64_t& counter, DiffResults& dr, bool calculate_diff) const { // The current results are 'fresh' when not calculating a differential. bool fresh_results = !calculate_diff; bool new_query = false; if (!isQueryNameInDatabase()) { // This is the first encounter of the scheduled query. fresh_results = true; LOG(INFO) << "Storing initial results for new scheduled query: " << name_; saveQuery(name_, query_); } else if (getPreviousEpoch() != current_epoch) { fresh_results = true; LOG(INFO) << "New Epoch " << current_epoch << " for scheduled query " << name_; } else if (isNewQuery()) { // This query is 'new' in that the previous results may be invalid. new_query = true; LOG(INFO) << "Scheduled query has been updated: " + name_; saveQuery(name_, query_); } // Use a 'target' avoid copying the query data when serializing and saving. // If a differential is requested and needed the target remains the original // query data, otherwise the content is moved to the differential's added set. const auto* target_gd = &current_qd; bool update_db = true; if (!fresh_results && calculate_diff) { // Get the rows from the last run of this query name. QueryDataSet previous_qd; auto status = getPreviousQueryResults(previous_qd); if (!status.ok()) { return status; } // Calculate the differential between previous and current query results. dr = diff(previous_qd, current_qd); update_db = (!dr.added.empty() || !dr.removed.empty()); } else { dr.added = std::move(current_qd); target_gd = &dr.added; } counter = getQueryCounter(fresh_results || new_query); auto status = setDatabaseValue(kQueries, name_ + "counter", std::to_string(counter)); if (!status.ok()) { return status; } if (update_db) { // Replace the "previous" query data with the current. std::string json; status = serializeQueryDataJSON(*target_gd, json, FLAGS_log_numerics_as_numbers); if (!status.ok()) { return status; } status = setDatabaseValue(kQueries, name_, json); if (!status.ok()) { return status; } status = setDatabaseValue( kQueries, name_ + "epoch", std::to_string(current_epoch)); if (!status.ok()) { return status; } } return Status::success(); } Status deserializeDiffResults(const rj::Value& doc, DiffResults& dr) { if (!doc.IsObject()) { return Status(1); } if (doc.HasMember("removed")) { auto status = deserializeQueryData(doc["removed"], dr.removed); if (!status.ok()) { return status; } } if (doc.HasMember("added")) { auto status = deserializeQueryData(doc["added"], dr.added); if (!status.ok()) { return status; } } return Status(); } inline void addLegacyFieldsAndDecorations(const QueryLogItem& item, JSON& doc, rj::Document& obj) { // Apply legacy fields. doc.addRef("name", item.name, obj); doc.addRef("hostIdentifier", item.identifier, obj); doc.addRef("calendarTime", item.calendar_time, obj); doc.add("unixTime", item.time, obj); doc.add("epoch", static_cast<size_t>(item.epoch), obj); doc.add("counter", static_cast<size_t>(item.counter), obj); // Apply field indicatiting if numerics are serialized as numbers doc.add("logNumericsAsNumbers", FLAGS_log_numerics_as_numbers, obj); // Append the decorations. if (!item.decorations.empty()) { auto dec_obj = doc.getObject(); auto target_obj = std::ref(dec_obj); if (FLAGS_decorations_top_level) { target_obj = std::ref(obj); } for (const auto& name : item.decorations) { doc.addRef(name.first, name.second, target_obj); } if (!FLAGS_decorations_top_level) { doc.add("decorations", dec_obj, obj); } } } inline void getLegacyFieldsAndDecorations(const JSON& doc, QueryLogItem& item) { if (doc.doc().HasMember("decorations")) { if (doc.doc()["decorations"].IsObject()) { for (const auto& i : doc.doc()["decorations"].GetObject()) { item.decorations[i.name.GetString()] = i.value.GetString(); } } } item.name = doc.doc()["name"].GetString(); item.identifier = doc.doc()["hostIdentifier"].GetString(); item.calendar_time = doc.doc()["calendarTime"].GetString(); item.time = doc.doc()["unixTime"].GetUint64(); } Status serializeQueryLogItem(const QueryLogItem& item, JSON& doc) { if (item.results.added.size() > 0 || item.results.removed.size() > 0) { auto obj = doc.getObject(); auto status = serializeDiffResults( item.results, doc, obj, FLAGS_log_numerics_as_numbers); if (!status.ok()) { return status; } doc.add("diffResults", obj); } else { auto arr = doc.getArray(); auto status = serializeQueryData( item.snapshot_results, doc, arr, FLAGS_log_numerics_as_numbers); if (!status.ok()) { return status; } doc.add("snapshot", arr); doc.addRef("action", "snapshot"); } addLegacyFieldsAndDecorations(item, doc, doc.doc()); return Status(); } Status serializeEvent(const QueryLogItem& item, const rj::Value& event_obj, JSON& doc, rj::Document& obj) { addLegacyFieldsAndDecorations(item, doc, obj); auto columns_obj = doc.getObject(); for (const auto& i : event_obj.GetObject()) { // Yield results as a "columns." map to avoid namespace collisions. doc.add(i.name.GetString(), i.value, columns_obj); } doc.add("columns", columns_obj, obj); return Status::success(); } Status serializeQueryLogItemAsEvents(const QueryLogItem& item, JSON& doc) { auto temp_doc = JSON::newObject(); if (!item.results.added.empty() || !item.results.removed.empty()) { auto status = serializeDiffResults( item.results, temp_doc, temp_doc.doc(), FLAGS_log_numerics_as_numbers); if (!status.ok()) { return status; } } else if (!item.snapshot_results.empty()) { auto arr = doc.getArray(); auto status = serializeQueryData( item.snapshot_results, temp_doc, arr, FLAGS_log_numerics_as_numbers); if (!status.ok()) { return status; } temp_doc.add("snapshot", arr); } else { // This error case may also be represented in serializeQueryLogItem. return Status(1, "No differential or snapshot results"); } for (auto& action : temp_doc.doc().GetObject()) { for (auto& row : action.value.GetArray()) { auto obj = doc.getObject(); serializeEvent(item, row, doc, obj); doc.addCopy("action", action.name.GetString(), obj); doc.push(obj); } } return Status(); } Status serializeQueryLogItemJSON(const QueryLogItem& item, std::string& json) { auto doc = JSON::newObject(); auto status = serializeQueryLogItem(item, doc); if (!status.ok()) { return status; } return doc.toString(json); } Status serializeQueryLogItemAsEventsJSON(const QueryLogItem& item, std::vector<std::string>& items) { auto doc = JSON::newArray(); auto status = serializeQueryLogItemAsEvents(item, doc); if (!status.ok()) { return status; } // return doc.toString() for (auto& event : doc.doc().GetArray()) { rj::StringBuffer sb; rj::Writer<rj::StringBuffer> writer(sb); event.Accept(writer); items.push_back(sb.GetString()); } return Status(); } }
/** * Copyright (c) 2014-present, Facebook, Inc. * All rights reserved. * * This source code is licensed in accordance with the terms specified in * the LICENSE file found in the root directory of this source tree. */ #include <algorithm> #include <string> #include <vector> #include <osquery/database.h> #include <osquery/flags.h> #include <osquery/logger.h> #include <osquery/query.h> #include <osquery/utils/json/json.h> namespace rj = rapidjson; namespace osquery { DECLARE_bool(decorations_top_level); /// Log numeric values as numbers (in JSON syntax) FLAG(bool, log_numerics_as_numbers, false, "Use numeric JSON syntax for numeric values"); uint64_t Query::getPreviousEpoch() const { uint64_t epoch = 0; std::string raw; auto status = getDatabaseValue(kQueries, name_ + "epoch", raw); if (status.ok()) { epoch = std::stoull(raw); } return epoch; } uint64_t Query::getQueryCounter(bool new_query) const { uint64_t counter = 0; if (new_query) { return counter; } std::string raw; auto status = getDatabaseValue(kQueries, name_ + "counter", raw); if (status.ok()) { counter = std::stoull(raw) + 1; } return counter; } Status Query::getPreviousQueryResults(QueryDataSet& results) const { std::string raw; auto status = getDatabaseValue(kQueries, name_, raw); if (!status.ok()) { return status; } status = deserializeQueryDataJSON(raw, results); if (!status.ok()) { return status; } return Status::success(); } std::vector<std::string> Query::getStoredQueryNames() { std::vector<std::string> results; scanDatabaseKeys(kQueries, results); return results; } bool Query::isQueryNameInDatabase() const { auto names = Query::getStoredQueryNames(); return std::find(names.begin(), names.end(), name_) != names.end(); } static inline void saveQuery(const std::string& name, const std::string& query) { setDatabaseValue(kQueries, "query." + name, query); } bool Query::isNewQuery() const { std::string query; getDatabaseValue(kQueries, "query." + name_, query); return (query != query_); } Status Query::addNewResults(QueryDataTyped qd, const uint64_t epoch, uint64_t& counter) const { DiffResults dr; return addNewResults(std::move(qd), epoch, counter, dr, false); } Status Query::addNewResults(QueryDataTyped current_qd, const uint64_t current_epoch, uint64_t& counter, DiffResults& dr, bool calculate_diff) const { // The current results are 'fresh' when not calculating a differential. bool fresh_results = !calculate_diff; bool new_query = false; if (!isQueryNameInDatabase()) { // This is the first encounter of the scheduled query. fresh_results = true; LOG(INFO) << "Storing initial results for new scheduled query: " << name_; saveQuery(name_, query_); } else if (getPreviousEpoch() != current_epoch) { fresh_results = true; LOG(INFO) << "New Epoch " << current_epoch << " for scheduled query " << name_; } else if (isNewQuery()) { // This query is 'new' in that the previous results may be invalid. new_query = true; LOG(INFO) << "Scheduled query has been updated: " + name_; saveQuery(name_, query_); } // Use a 'target' avoid copying the query data when serializing and saving. // If a differential is requested and needed the target remains the original // query data, otherwise the content is moved to the differential's added set. const auto* target_gd = &current_qd; bool update_db = true; if (!fresh_results && calculate_diff) { // Get the rows from the last run of this query name. QueryDataSet previous_qd; auto status = getPreviousQueryResults(previous_qd); if (!status.ok()) { return status; } // Calculate the differential between previous and current query results. dr = diff(previous_qd, current_qd); update_db = (!dr.added.empty() || !dr.removed.empty()); } else { dr.added = std::move(current_qd); target_gd = &dr.added; } counter = getQueryCounter(fresh_results || new_query); auto status = setDatabaseValue(kQueries, name_ + "counter", std::to_string(counter)); if (!status.ok()) { return status; } if (update_db) { // Replace the "previous" query data with the current. std::string json; status = serializeQueryDataJSON(*target_gd, json, true); if (!status.ok()) { return status; } status = setDatabaseValue(kQueries, name_, json); if (!status.ok()) { return status; } status = setDatabaseValue( kQueries, name_ + "epoch", std::to_string(current_epoch)); if (!status.ok()) { return status; } } return Status::success(); } Status deserializeDiffResults(const rj::Value& doc, DiffResults& dr) { if (!doc.IsObject()) { return Status(1); } if (doc.HasMember("removed")) { auto status = deserializeQueryData(doc["removed"], dr.removed); if (!status.ok()) { return status; } } if (doc.HasMember("added")) { auto status = deserializeQueryData(doc["added"], dr.added); if (!status.ok()) { return status; } } return Status(); } inline void addLegacyFieldsAndDecorations(const QueryLogItem& item, JSON& doc, rj::Document& obj) { // Apply legacy fields. doc.addRef("name", item.name, obj); doc.addRef("hostIdentifier", item.identifier, obj); doc.addRef("calendarTime", item.calendar_time, obj); doc.add("unixTime", item.time, obj); doc.add("epoch", static_cast<size_t>(item.epoch), obj); doc.add("counter", static_cast<size_t>(item.counter), obj); // Apply field indicatiting if numerics are serialized as numbers doc.add("logNumericsAsNumbers", FLAGS_log_numerics_as_numbers, obj); // Append the decorations. if (!item.decorations.empty()) { auto dec_obj = doc.getObject(); auto target_obj = std::ref(dec_obj); if (FLAGS_decorations_top_level) { target_obj = std::ref(obj); } for (const auto& name : item.decorations) { doc.addRef(name.first, name.second, target_obj); } if (!FLAGS_decorations_top_level) { doc.add("decorations", dec_obj, obj); } } } inline void getLegacyFieldsAndDecorations(const JSON& doc, QueryLogItem& item) { if (doc.doc().HasMember("decorations")) { if (doc.doc()["decorations"].IsObject()) { for (const auto& i : doc.doc()["decorations"].GetObject()) { item.decorations[i.name.GetString()] = i.value.GetString(); } } } item.name = doc.doc()["name"].GetString(); item.identifier = doc.doc()["hostIdentifier"].GetString(); item.calendar_time = doc.doc()["calendarTime"].GetString(); item.time = doc.doc()["unixTime"].GetUint64(); } Status serializeQueryLogItem(const QueryLogItem& item, JSON& doc) { if (item.results.added.size() > 0 || item.results.removed.size() > 0) { auto obj = doc.getObject(); auto status = serializeDiffResults( item.results, doc, obj, FLAGS_log_numerics_as_numbers); if (!status.ok()) { return status; } doc.add("diffResults", obj); } else { auto arr = doc.getArray(); auto status = serializeQueryData( item.snapshot_results, doc, arr, FLAGS_log_numerics_as_numbers); if (!status.ok()) { return status; } doc.add("snapshot", arr); doc.addRef("action", "snapshot"); } addLegacyFieldsAndDecorations(item, doc, doc.doc()); return Status(); } Status serializeEvent(const QueryLogItem& item, const rj::Value& event_obj, JSON& doc, rj::Document& obj) { addLegacyFieldsAndDecorations(item, doc, obj); auto columns_obj = doc.getObject(); for (const auto& i : event_obj.GetObject()) { // Yield results as a "columns." map to avoid namespace collisions. doc.add(i.name.GetString(), i.value, columns_obj); } doc.add("columns", columns_obj, obj); return Status::success(); } Status serializeQueryLogItemAsEvents(const QueryLogItem& item, JSON& doc) { auto temp_doc = JSON::newObject(); if (!item.results.added.empty() || !item.results.removed.empty()) { auto status = serializeDiffResults( item.results, temp_doc, temp_doc.doc(), FLAGS_log_numerics_as_numbers); if (!status.ok()) { return status; } } else if (!item.snapshot_results.empty()) { auto arr = doc.getArray(); auto status = serializeQueryData( item.snapshot_results, temp_doc, arr, FLAGS_log_numerics_as_numbers); if (!status.ok()) { return status; } temp_doc.add("snapshot", arr); } else { // This error case may also be represented in serializeQueryLogItem. return Status(1, "No differential or snapshot results"); } for (auto& action : temp_doc.doc().GetObject()) { for (auto& row : action.value.GetArray()) { auto obj = doc.getObject(); serializeEvent(item, row, doc, obj); doc.addCopy("action", action.name.GetString(), obj); doc.push(obj); } } return Status(); } Status serializeQueryLogItemJSON(const QueryLogItem& item, std::string& json) { auto doc = JSON::newObject(); auto status = serializeQueryLogItem(item, doc); if (!status.ok()) { return status; } return doc.toString(json); } Status serializeQueryLogItemAsEventsJSON(const QueryLogItem& item, std::vector<std::string>& items) { auto doc = JSON::newArray(); auto status = serializeQueryLogItemAsEvents(item, doc); if (!status.ok()) { return status; } // return doc.toString() for (auto& event : doc.doc().GetArray()) { rj::StringBuffer sb; rj::Writer<rj::StringBuffer> writer(sb); event.Accept(writer); items.push_back(sb.GetString()); } return Status(); } }
Store results for differential queries serialized with types
Store results for differential queries serialized with types Summary: Every time a differential query runs we save the results to the database. We were serializing those results with or without types based on the `FLAGS_log_numerics_as_numbers` flag. However we always collect results with proper types therefore, on subsequent executions of the same query, the new results (typed) were being compared with the results retrieved from the DB (untyped if FLAGS_log_numerics_as_numbers == false), causing all results to be "different" and therefore osquery to report all results as "added" (and eventually all old results as "removed"). Reviewed By: SAlexandru Differential Revision: D14669476 fbshipit-source-id: 8abc68cbcac90c73bd92fc8d34572ba3ee2f2c75
C++
bsd-3-clause
hackgnar/osquery,hackgnar/osquery,hackgnar/osquery
63e6c058730149b7a711dd2229e08ba012bca36a
Utils/OutputPrinter.cpp
Utils/OutputPrinter.cpp
#include "OutputPrinter.h" OutputPrinter::OutputPrinter(const std::string& outputFileName) : m_outputFileName(outputFileName) { TiXmlDeclaration* decl = new TiXmlDeclaration("1.0", "", ""); m_document.LinkEndChild(decl); TiXmlElement* resultsElement = new TiXmlElement("results"); resultsElement->SetAttribute("version", "2"); m_document.LinkEndChild(resultsElement); TiXmlElement* colobotLintElement = new TiXmlElement("cppcheck"); colobotLintElement->SetAttribute("version", "1.69"); resultsElement->LinkEndChild(colobotLintElement); m_errorsElement = new TiXmlElement("errors"); resultsElement->LinkEndChild(m_errorsElement); } void OutputPrinter::Save() { m_document.SaveFile(m_outputFileName); } void OutputPrinter::PrintRuleViolation(const std::string& ruleName, Severity severity, const std::string& description, const clang::SourceLocation& location, clang::SourceManager& sourceManager) { TiXmlElement* errorElement = new TiXmlElement("error"); errorElement->SetAttribute("id", ruleName); errorElement->SetAttribute("severity", GetSeverityString(severity)); errorElement->SetAttribute("msg", description); errorElement->SetAttribute("verbose", description); TiXmlElement* locationElement = new TiXmlElement("location"); locationElement->SetAttribute("file", sourceManager.getFilename(location).str()); locationElement->SetAttribute("line", std::to_string(sourceManager.getSpellingLineNumber(location))); errorElement->LinkEndChild(locationElement); m_errorsElement->LinkEndChild(errorElement); } std::string OutputPrinter::GetSeverityString(Severity severity) { std::string str; switch (severity) { case Severity::Style: str = "style"; break; case Severity::Error: str = "error"; break; case Severity::Warning: str = "warning"; break; case Severity::Information: str = "information"; break; } return str; }
#include "OutputPrinter.h" OutputPrinter::OutputPrinter(const std::string& outputFileName) : m_outputFileName(outputFileName) { TiXmlDeclaration* decl = new TiXmlDeclaration("1.0", "", ""); m_document.LinkEndChild(decl); TiXmlElement* resultsElement = new TiXmlElement("results"); resultsElement->SetAttribute("version", "2"); m_document.LinkEndChild(resultsElement); TiXmlElement* colobotLintElement = new TiXmlElement("cppcheck"); colobotLintElement->SetAttribute("version", "colobot-lint"); resultsElement->LinkEndChild(colobotLintElement); m_errorsElement = new TiXmlElement("errors"); resultsElement->LinkEndChild(m_errorsElement); } void OutputPrinter::Save() { m_document.SaveFile(m_outputFileName); } void OutputPrinter::PrintRuleViolation(const std::string& ruleName, Severity severity, const std::string& description, const clang::SourceLocation& location, clang::SourceManager& sourceManager) { TiXmlElement* errorElement = new TiXmlElement("error"); errorElement->SetAttribute("id", ruleName); errorElement->SetAttribute("severity", GetSeverityString(severity)); errorElement->SetAttribute("msg", description); errorElement->SetAttribute("verbose", description); TiXmlElement* locationElement = new TiXmlElement("location"); locationElement->SetAttribute("file", sourceManager.getFilename(location).str()); locationElement->SetAttribute("line", std::to_string(sourceManager.getSpellingLineNumber(location))); errorElement->LinkEndChild(locationElement); m_errorsElement->LinkEndChild(errorElement); } std::string OutputPrinter::GetSeverityString(Severity severity) { std::string str; switch (severity) { case Severity::Style: str = "style"; break; case Severity::Error: str = "error"; break; case Severity::Warning: str = "warning"; break; case Severity::Information: str = "information"; break; } return str; }
Change XML version info to colobot-lint
Change XML version info to colobot-lint
C++
bsd-3-clause
colobot/colobot-lint,piotrdz/colobot-lint,piotrdz/colobot-lint,piotrdz/colobot-lint,piotrdz/colobot-lint,colobot/colobot-lint,colobot/colobot-lint,colobot/colobot-lint
a87a39e38e950de92b1f345e83cc717536d3d6e3
VL53L0X_sample/main.cpp
VL53L0X_sample/main.cpp
//=====================================================================// /*! @file @brief VL53L0X 距離センサー・サンプル @author 平松邦仁 ([email protected]) @copyright Copyright (C) 2017 Kunihito Hiramatsu @n Released under the MIT license @n https://github.com/hirakuni45/R8C/blob/master/LICENSE */ //=====================================================================// #include <cstring> #include "system.hpp" #include "clock.hpp" #include "port.hpp" #include "common/command.hpp" #include "common/format.hpp" #include "common/intr_utils.hpp" #include "common/port_map.hpp" #include "common/uart_io.hpp" #include "common/fifo.hpp" #include "common/trb_io.hpp" #include "chip/VL53L0X.hpp" namespace { typedef device::trb_io<utils::null_task, uint8_t> timer_b; timer_b timer_b_; typedef utils::fifo<uint8_t, 16> buffer; typedef device::uart_io<device::UART0, buffer, buffer> uart; uart uart_; // I2C ポートの定義クラス // P4_B5: SDA typedef device::PORT<device::PORT4, device::bitpos::B5> sda_port; // P1_B7: SCL typedef device::PORT<device::PORT1, device::bitpos::B7> scl_port; typedef device::iica_io<sda_port, scl_port> iica; iica i2c_; chip::VL53L0X<iica> vlx_(i2c_); utils::command<64> command_; } extern "C" { void sci_putch(char ch) { uart_.putch(ch); } char sci_getch(void) { return uart_.getch(); } uint16_t sci_length() { return uart_.length(); } void sci_puts(const char* str) { uart_.puts(str); } void TIMER_RB_intr(void) { timer_b_.itask(); } void UART0_TX_intr(void) { uart_.isend(); } void UART0_RX_intr(void) { uart_.irecv(); } } namespace { } // __attribute__ ((section (".exttext"))) int main(int argc, char *argv[]) { using namespace device; // クロック関係レジスタ・プロテクト解除 PRCR.PRC0 = 1; // 高速オンチップオシレーターへ切り替え(20MHz) // ※ F_CLK を設定する事(Makefile内) OCOCR.HOCOE = 1; utils::delay::micro_second(1); // >=30us(125KHz) SCKCR.HSCKSEL = 1; CKSTPR.SCKSEL = 1; // タイマーB初期化 { uint8_t ir_level = 2; timer_b_.start_timer(60, ir_level); } // UART の設定 (P1_4: TXD0[out], P1_5: RXD0[in]) // ※シリアルライターでは、RXD 端子は、P1_6 となっているので注意! { utils::PORT_MAP(utils::port_map::P14::TXD0); utils::PORT_MAP(utils::port_map::P15::RXD0); uint8_t ir_level = 1; uart_.start(57600, ir_level); } // I2C クラスの初期化 { i2c_.start(iica::speed::fast); } // VL53L0X を開始 { vlx_.start(); } sci_puts("Start R8C VL53L0X monitor\n"); command_.set_prompt("# "); // LED シグナル用ポートを出力 PD1.B0 = 1; uint8_t cnt = 0; while(1) { timer_b_.sync(); if(cnt >= 20) { cnt = 0; } if(cnt < 10) P1.B0 = 1; else P1.B0 = 0; ++cnt; #if 0 // コマンド入力と、コマンド解析 if(command_.service()) { uint8_t cmdn = command_.get_words(); if(cmdn >= 1) { if(command_.cmp_word(0, "date")) { if(cmdn == 1) { time_t t = get_time_(); if(t != 0) { disp_time_(t); } } else { set_time_date_(); } } else if(command_.cmp_word(0, "help")) { sci_puts("date\n"); sci_puts("date yyyy/mm/dd hh:mm[:ss]\n"); } else { char buff[12]; if(command_.get_word(0, sizeof(buff), buff)) { sci_puts("Command error: "); sci_puts(buff); sci_putch('\n'); } } } } #endif } }
//=====================================================================// /*! @file @brief VL53L0X 距離センサー・サンプル @author 平松邦仁 ([email protected]) @copyright Copyright (C) 2017 Kunihito Hiramatsu @n Released under the MIT license @n https://github.com/hirakuni45/R8C/blob/master/LICENSE */ //=====================================================================// #include <cstring> #include "system.hpp" #include "clock.hpp" #include "port.hpp" #include "common/command.hpp" #include "common/format.hpp" #include "common/intr_utils.hpp" #include "common/port_map.hpp" #include "common/uart_io.hpp" #include "common/fifo.hpp" #include "common/trb_io.hpp" #include "chip/VL53L0X.hpp" namespace { typedef device::trb_io<utils::null_task, uint8_t> timer_b; timer_b timer_b_; typedef utils::fifo<uint8_t, 16> buffer; typedef device::uart_io<device::UART0, buffer, buffer> uart; uart uart_; // I2C ポートの定義クラス // P4_B5 (12): SDA typedef device::PORT<device::PORT4, device::bitpos::B5> sda_port; // P1_B7 (13): SCL typedef device::PORT<device::PORT1, device::bitpos::B7> scl_port; typedef device::iica_io<sda_port, scl_port> iica; iica i2c_; typedef chip::VL53L0X<iica> VLX; VLX vlx_(i2c_); utils::command<64> command_; } extern "C" { void sci_putch(char ch) { uart_.putch(ch); } char sci_getch(void) { return uart_.getch(); } uint16_t sci_length() { return uart_.length(); } void sci_puts(const char* str) { uart_.puts(str); } void TIMER_RB_intr(void) { timer_b_.itask(); vlx_.add_millis(10); } void UART0_TX_intr(void) { uart_.isend(); } void UART0_RX_intr(void) { uart_.irecv(); } } namespace { } // __attribute__ ((section (".exttext"))) int main(int argc, char *argv[]) { using namespace device; // クロック関係レジスタ・プロテクト解除 PRCR.PRC0 = 1; // 高速オンチップオシレーターへ切り替え(20MHz) // ※ F_CLK を設定する事(Makefile内) OCOCR.HOCOE = 1; utils::delay::micro_second(1); // >=30us(125KHz) SCKCR.HSCKSEL = 1; CKSTPR.SCKSEL = 1; // タイマーB初期化 { uint8_t ir_level = 2; timer_b_.start_timer(100, ir_level); } // UART の設定 (P1_4: TXD0[out], P1_5: RXD0[in]) // ※シリアルライターでは、RXD 端子は、P1_6 となっているので注意! { utils::PORT_MAP(utils::port_map::P14::TXD0); utils::PORT_MAP(utils::port_map::P15::RXD0); uint8_t ir_level = 1; uart_.start(57600, ir_level); } // I2C クラスの初期化 { i2c_.start(iica::speed::fast); } // VL53L0X を開始 if(!vlx_.start()) { utils::format("VL53L0X start fail\n"); } else { // 20ms vlx_.set_measurement_timing_budget(200000); } sci_puts("Start R8C VL53L0X monitor\n"); command_.set_prompt("# "); // LED シグナル用ポートを出力 PD1.B0 = 1; uint8_t cnt = 0; uint8_t itv = 0; while(1) { timer_b_.sync(); if(cnt >= 20) { cnt = 0; } if(cnt < 10) P1.B0 = 1; else P1.B0 = 0; ++cnt; ++itv; if(itv >= 100) { auto len = vlx_.read_range_single_millimeters(); utils::format("Length: %d\n") % len; itv = 0; } // コマンド入力と、コマンド解析 if(command_.service()) { uint8_t cmdn = command_.get_words(); if(cmdn >= 1) { if(command_.cmp_word(0, "date")) { if(cmdn == 1) { } else { } } else if(command_.cmp_word(0, "help")) { // sci_puts("date\n"); // sci_puts("date yyyy/mm/dd hh:mm[:ss]\n"); } else { char buff[12]; if(command_.get_word(0, sizeof(buff), buff)) { utils::format("Command error: %s\n") % buff; } } } } } }
update management
update management
C++
bsd-3-clause
hirakuni45/R8C,hirakuni45/R8C,hirakuni45/R8C
1b0ee130d81aa3205d70c1c8957d6ea40184ca58
chrome/common/child_thread.cc
chrome/common/child_thread.cc
// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/common/child_thread.h" #include "base/command_line.h" #include "chrome/common/child_process.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/ipc_logging.h" #include "webkit/glue/webkit_glue.h" ChildThread::ChildThread(Thread::Options options) : Thread("Chrome_ChildThread"), owner_loop_(MessageLoop::current()), in_send_(0), options_(options) { DCHECK(owner_loop_); channel_name_ = CommandLine::ForCurrentProcess()->GetSwitchValue( switches::kProcessChannelID); if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kUserAgent)) { #if defined(OS_WIN) // TODO(port): calling this connects an, otherwise disconnected, subgraph // of symbols, causing huge numbers of linker errors. webkit_glue::SetUserAgent(WideToUTF8( CommandLine::ForCurrentProcess()->GetSwitchValue(switches::kUserAgent))); #endif } } ChildThread::~ChildThread() { } bool ChildThread::Run() { return StartWithOptions(options_); } void ChildThread::OnChannelError() { owner_loop_->PostTask(FROM_HERE, new MessageLoop::QuitTask()); } bool ChildThread::Send(IPC::Message* msg) { if (!channel_.get()) { delete msg; return false; } in_send_++; bool rv = channel_->Send(msg); in_send_--; return rv; } void ChildThread::AddRoute(int32 routing_id, IPC::Channel::Listener* listener) { DCHECK(MessageLoop::current() == message_loop()); router_.AddRoute(routing_id, listener); } void ChildThread::RemoveRoute(int32 routing_id) { DCHECK(MessageLoop::current() == message_loop()); router_.RemoveRoute(routing_id); } void ChildThread::OnMessageReceived(const IPC::Message& msg) { if (msg.routing_id() == MSG_ROUTING_CONTROL) { OnControlMessageReceived(msg); } else { router_.OnMessageReceived(msg); } } ChildThread* ChildThread::current() { return ChildProcess::current()->child_thread(); } void ChildThread::Init() { channel_.reset(new IPC::SyncChannel(channel_name_, IPC::Channel::MODE_CLIENT, this, NULL, owner_loop_, true, ChildProcess::current()->GetShutDownEvent())); #ifdef IPC_MESSAGE_LOG_ENABLED IPC::Logging::current()->SetIPCSender(this); #endif } void ChildThread::CleanUp() { #ifdef IPC_MESSAGE_LOG_ENABLED IPC::Logging::current()->SetIPCSender(NULL); #endif // Need to destruct the SyncChannel to the browser before we go away because // it caches a pointer to this thread. channel_.reset(); }
// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/common/child_thread.h" #include "base/command_line.h" #include "base/string_util.h" #include "chrome/common/child_process.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/ipc_logging.h" #include "webkit/glue/webkit_glue.h" ChildThread::ChildThread(Thread::Options options) : Thread("Chrome_ChildThread"), owner_loop_(MessageLoop::current()), in_send_(0), options_(options) { DCHECK(owner_loop_); channel_name_ = CommandLine::ForCurrentProcess()->GetSwitchValue( switches::kProcessChannelID); if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kUserAgent)) { #if defined(OS_WIN) // TODO(port): calling this connects an, otherwise disconnected, subgraph // of symbols, causing huge numbers of linker errors. webkit_glue::SetUserAgent(WideToUTF8( CommandLine::ForCurrentProcess()->GetSwitchValue(switches::kUserAgent))); #endif } } ChildThread::~ChildThread() { } bool ChildThread::Run() { return StartWithOptions(options_); } void ChildThread::OnChannelError() { owner_loop_->PostTask(FROM_HERE, new MessageLoop::QuitTask()); } bool ChildThread::Send(IPC::Message* msg) { if (!channel_.get()) { delete msg; return false; } in_send_++; bool rv = channel_->Send(msg); in_send_--; return rv; } void ChildThread::AddRoute(int32 routing_id, IPC::Channel::Listener* listener) { DCHECK(MessageLoop::current() == message_loop()); router_.AddRoute(routing_id, listener); } void ChildThread::RemoveRoute(int32 routing_id) { DCHECK(MessageLoop::current() == message_loop()); router_.RemoveRoute(routing_id); } void ChildThread::OnMessageReceived(const IPC::Message& msg) { if (msg.routing_id() == MSG_ROUTING_CONTROL) { OnControlMessageReceived(msg); } else { router_.OnMessageReceived(msg); } } ChildThread* ChildThread::current() { return ChildProcess::current()->child_thread(); } void ChildThread::Init() { channel_.reset(new IPC::SyncChannel(channel_name_, IPC::Channel::MODE_CLIENT, this, NULL, owner_loop_, true, ChildProcess::current()->GetShutDownEvent())); #ifdef IPC_MESSAGE_LOG_ENABLED IPC::Logging::current()->SetIPCSender(this); #endif } void ChildThread::CleanUp() { #ifdef IPC_MESSAGE_LOG_ENABLED IPC::Logging::current()->SetIPCSender(NULL); #endif // Need to destruct the SyncChannel to the browser before we go away because // it caches a pointer to this thread. channel_.reset(); }
Fix release build break
Fix release build break git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@10081 0039d316-1c4b-4281-b951-d872f2087c98
C++
bsd-3-clause
adobe/chromium,gavinp/chromium,yitian134/chromium,adobe/chromium,adobe/chromium,ropik/chromium,Crystalnix/house-of-life-chromium,adobe/chromium,adobe/chromium,ropik/chromium,Crystalnix/house-of-life-chromium,Crystalnix/house-of-life-chromium,ropik/chromium,Crystalnix/house-of-life-chromium,gavinp/chromium,Crystalnix/house-of-life-chromium,ropik/chromium,gavinp/chromium,gavinp/chromium,ropik/chromium,yitian134/chromium,yitian134/chromium,yitian134/chromium,Crystalnix/house-of-life-chromium,adobe/chromium,Crystalnix/house-of-life-chromium,gavinp/chromium,yitian134/chromium,adobe/chromium,adobe/chromium,gavinp/chromium,ropik/chromium,yitian134/chromium,adobe/chromium,Crystalnix/house-of-life-chromium,Crystalnix/house-of-life-chromium,ropik/chromium,gavinp/chromium,gavinp/chromium,yitian134/chromium,gavinp/chromium,yitian134/chromium,ropik/chromium,yitian134/chromium,Crystalnix/house-of-life-chromium,adobe/chromium,yitian134/chromium,gavinp/chromium,adobe/chromium,Crystalnix/house-of-life-chromium,ropik/chromium
b050e312f4ac4000356fdd4937efcdc283e52617
Source/RTSProject/Plugins/RealTimeStrategy/Source/RealTimeStrategy/Private/Libraries/RTSCollisionLibrary.cpp
Source/RTSProject/Plugins/RealTimeStrategy/Source/RealTimeStrategy/Private/Libraries/RTSCollisionLibrary.cpp
#include "Libraries/RTSCollisionLibrary.h" #include "Landscape.h" #include "Components/ShapeComponent.h" #include "GameFramework/Actor.h" #include "RTSLog.h" #include "Libraries/RTSGameplayLibrary.h" float URTSCollisionLibrary::GetActorDistance(AActor* First, AActor* Second, bool bConsiderCollisionSize) { if (!First || !Second) { return 0.0f; } float Distance = First->GetDistanceTo(Second); if (bConsiderCollisionSize) { Distance -= GetActorCollisionSize(First) / 2.0f; Distance -= GetActorCollisionSize(Second) / 2.0f; } return Distance; } float URTSCollisionLibrary::GetCollisionSize(TSubclassOf<AActor> ActorClass) { if (ActorClass == nullptr) { return 0.0; } AActor* DefaultActor = ActorClass->GetDefaultObject<AActor>(); return GetActorCollisionSize(DefaultActor) * DefaultActor->GetActorRelativeScale3D().X; } float URTSCollisionLibrary::GetCollisionHeight(TSubclassOf<AActor> ActorClass) { if (ActorClass == nullptr) { return 0.0; } AActor* DefaultActor = ActorClass->GetDefaultObject<AActor>(); return GetActorCollisionHeight(DefaultActor) * DefaultActor->GetActorRelativeScale3D().Z; } float URTSCollisionLibrary::GetActorCollisionSize(AActor* Actor) { if (!Actor) { return 0.0f; } UShapeComponent* ShapeComponent = Actor->FindComponentByClass<UShapeComponent>(); return GetShapeCollisionSize(ShapeComponent); } float URTSCollisionLibrary::GetActorCollisionHeight(AActor* Actor) { if (!Actor) { return 0.0f; } UShapeComponent* ShapeComponent = Actor->FindComponentByClass<UShapeComponent>(); return GetShapeCollisionHeight(ShapeComponent); } float URTSCollisionLibrary::GetShapeCollisionSize(UShapeComponent* ShapeComponent) { if (!ShapeComponent) { return 0.0f; } FCollisionShape CollisionShape = ShapeComponent->GetCollisionShape(); if (CollisionShape.IsBox()) { return FMath::Max(CollisionShape.Box.HalfExtentX, CollisionShape.Box.HalfExtentY) * 2; } else if (CollisionShape.IsCapsule()) { return CollisionShape.Capsule.Radius * 2; } else if (CollisionShape.IsSphere()) { return CollisionShape.Sphere.Radius * 2; } else { UE_LOG(LogRTS, Error, TEXT("Unknown collision shape type for %s."), *ShapeComponent->GetOwner()->GetName()); return 0.0f; } } float URTSCollisionLibrary::GetShapeCollisionHeight(UShapeComponent* ShapeComponent) { if (!ShapeComponent) { return 0.0f; } FCollisionShape CollisionShape = ShapeComponent->GetCollisionShape(); if (CollisionShape.IsBox()) { return CollisionShape.Box.HalfExtentZ * 2; } else if (CollisionShape.IsCapsule()) { return CollisionShape.Capsule.HalfHeight * 2; } else if (CollisionShape.IsSphere()) { return CollisionShape.Sphere.Radius * 2; } else { UE_LOG(LogRTS, Error, TEXT("Unknown collision shape type for %s."), *ShapeComponent->GetOwner()->GetName()); return 0.0f; } } FVector URTSCollisionLibrary::GetGroundLocation(UObject* WorldContextObject, FVector Location) { if (!WorldContextObject) { return Location; } // Cast ray to hit world. FCollisionObjectQueryParams Params(FCollisionObjectQueryParams::InitType::AllObjects); TArray<FHitResult> HitResults; WorldContextObject->GetWorld()->LineTraceMultiByObjectType( HitResults, FVector(Location.X, Location.Y, 10000.0f), FVector(Location.X, Location.Y, -10000.0f), Params); for (auto& HitResult : HitResults) { if (HitResult.Actor != nullptr) { ALandscape* Landscape = Cast<ALandscape>(HitResult.Actor.Get()); if (Landscape != nullptr) { return HitResult.Location; } continue; } return HitResult.Location; } return Location; } bool URTSCollisionLibrary::IsSuitableLocationForActor(UWorld* World, TSubclassOf<AActor> ActorClass, const FVector& Location) { if (!World) { return false; } UShapeComponent* ShapeComponent = URTSGameplayLibrary::FindDefaultComponentByClass<UShapeComponent>(ActorClass); if (!ShapeComponent) { return true; } FCollisionObjectQueryParams Params(FCollisionObjectQueryParams::AllDynamicObjects); return !World->OverlapAnyTestByObjectType( Location, FQuat::Identity, Params, ShapeComponent->GetCollisionShape()); }
#include "Libraries/RTSCollisionLibrary.h" #include "Landscape.h" #include "Components/ShapeComponent.h" #include "GameFramework/Actor.h" #include "RTSLog.h" #include "Libraries/RTSGameplayLibrary.h" float URTSCollisionLibrary::GetActorDistance(AActor* First, AActor* Second, bool bConsiderCollisionSize) { if (!First || !Second) { return 0.0f; } float Distance = First->GetDistanceTo(Second); if (bConsiderCollisionSize) { Distance -= GetActorCollisionSize(First) / 2.0f; Distance -= GetActorCollisionSize(Second) / 2.0f; } return Distance; } float URTSCollisionLibrary::GetCollisionSize(TSubclassOf<AActor> ActorClass) { if (ActorClass == nullptr) { return 0.0; } AActor* DefaultActor = ActorClass->GetDefaultObject<AActor>(); return GetActorCollisionSize(DefaultActor) * DefaultActor->GetActorRelativeScale3D().X; } float URTSCollisionLibrary::GetCollisionHeight(TSubclassOf<AActor> ActorClass) { if (ActorClass == nullptr) { return 0.0; } AActor* DefaultActor = ActorClass->GetDefaultObject<AActor>(); return GetActorCollisionHeight(DefaultActor) * DefaultActor->GetActorRelativeScale3D().Z; } float URTSCollisionLibrary::GetActorCollisionSize(AActor* Actor) { if (!Actor) { return 0.0f; } UShapeComponent* ShapeComponent = Actor->FindComponentByClass<UShapeComponent>(); if (!IsValid(ShapeComponent)) { const TSubclassOf<AActor> ActorClass = Actor->GetClass(); ShapeComponent = URTSGameplayLibrary::FindDefaultComponentByClass<UShapeComponent>(ActorClass); } return GetShapeCollisionSize(ShapeComponent); } float URTSCollisionLibrary::GetActorCollisionHeight(AActor* Actor) { if (!Actor) { return 0.0f; } UShapeComponent* ShapeComponent = Actor->FindComponentByClass<UShapeComponent>(); if (!IsValid(ShapeComponent)) { const TSubclassOf<AActor> ActorClass = Actor->GetClass(); ShapeComponent = URTSGameplayLibrary::FindDefaultComponentByClass<UShapeComponent>(ActorClass); } return GetShapeCollisionHeight(ShapeComponent); } float URTSCollisionLibrary::GetShapeCollisionSize(UShapeComponent* ShapeComponent) { if (!ShapeComponent) { return 0.0f; } FCollisionShape CollisionShape = ShapeComponent->GetCollisionShape(); if (CollisionShape.IsBox()) { return FMath::Max(CollisionShape.Box.HalfExtentX, CollisionShape.Box.HalfExtentY) * 2; } else if (CollisionShape.IsCapsule()) { return CollisionShape.Capsule.Radius * 2; } else if (CollisionShape.IsSphere()) { return CollisionShape.Sphere.Radius * 2; } else { UE_LOG(LogRTS, Error, TEXT("Unknown collision shape type for %s."), *ShapeComponent->GetOwner()->GetName()); return 0.0f; } } float URTSCollisionLibrary::GetShapeCollisionHeight(UShapeComponent* ShapeComponent) { if (!ShapeComponent) { return 0.0f; } FCollisionShape CollisionShape = ShapeComponent->GetCollisionShape(); if (CollisionShape.IsBox()) { return CollisionShape.Box.HalfExtentZ * 2; } else if (CollisionShape.IsCapsule()) { return CollisionShape.Capsule.HalfHeight * 2; } else if (CollisionShape.IsSphere()) { return CollisionShape.Sphere.Radius * 2; } else { UE_LOG(LogRTS, Error, TEXT("Unknown collision shape type for %s."), *ShapeComponent->GetOwner()->GetName()); return 0.0f; } } FVector URTSCollisionLibrary::GetGroundLocation(UObject* WorldContextObject, FVector Location) { if (!WorldContextObject) { return Location; } // Cast ray to hit world. FCollisionObjectQueryParams Params(FCollisionObjectQueryParams::InitType::AllObjects); TArray<FHitResult> HitResults; WorldContextObject->GetWorld()->LineTraceMultiByObjectType( HitResults, FVector(Location.X, Location.Y, 10000.0f), FVector(Location.X, Location.Y, -10000.0f), Params); for (auto& HitResult : HitResults) { if (HitResult.Actor != nullptr) { ALandscape* Landscape = Cast<ALandscape>(HitResult.Actor.Get()); if (Landscape != nullptr) { return HitResult.Location; } continue; } return HitResult.Location; } return Location; } bool URTSCollisionLibrary::IsSuitableLocationForActor(UWorld* World, TSubclassOf<AActor> ActorClass, const FVector& Location) { if (!World) { return false; } UShapeComponent* ShapeComponent = URTSGameplayLibrary::FindDefaultComponentByClass<UShapeComponent>(ActorClass); if (!ShapeComponent) { return true; } FCollisionObjectQueryParams Params(FCollisionObjectQueryParams::AllDynamicObjects); return !World->OverlapAnyTestByObjectType( Location, FQuat::Identity, Params, ShapeComponent->GetCollisionShape()); }
Fix missing sub-components when retrieved from default components (#127)
Fix missing sub-components when retrieved from default components (#127)
C++
mit
npruehs/ue4-rts,npruehs/ue4-rts,npruehs/ue4-rts
a7413619a879119100b0242ae010ba2340e43b79
eval/src/tests/instruction/mixed_simple_join_function/mixed_simple_join_function_test.cpp
eval/src/tests/instruction/mixed_simple_join_function/mixed_simple_join_function_test.cpp
// Copyright Verizon Media. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include <vespa/vespalib/testkit/test_kit.h> #include <vespa/eval/eval/fast_value.h> #include <vespa/eval/eval/simple_value.h> #include <vespa/eval/eval/tensor_function.h> #include <vespa/eval/instruction/mixed_simple_join_function.h> #include <vespa/eval/eval/test/eval_fixture.h> #include <vespa/eval/eval/test/gen_spec.h> #include <vespa/vespalib/util/stringfmt.h> using namespace vespalib; using namespace vespalib::eval; using namespace vespalib::eval::test; using namespace vespalib::eval::tensor_function; using vespalib::make_string_short::fmt; const ValueBuilderFactory &prod_factory = FastValueBuilderFactory::get(); const ValueBuilderFactory &test_factory = SimpleValueBuilderFactory::get(); using Primary = MixedSimpleJoinFunction::Primary; using Overlap = MixedSimpleJoinFunction::Overlap; namespace vespalib::eval { std::ostream &operator<<(std::ostream &os, Primary primary) { switch(primary) { case Primary::LHS: return os << "LHS"; case Primary::RHS: return os << "RHS"; } abort(); } std::ostream &operator<<(std::ostream &os, Overlap overlap) { switch(overlap) { case Overlap::FULL: return os << "FULL"; case Overlap::INNER: return os << "INNER"; case Overlap::OUTER: return os << "OUTER"; } abort(); } } struct FunInfo { using LookFor = MixedSimpleJoinFunction; Overlap overlap; size_t factor; std::optional<Primary> primary; bool l_mut; bool r_mut; std::optional<bool> inplace; void verify(const EvalFixture &fixture, const LookFor &fun) const { EXPECT_TRUE(fun.result_is_mutable()); EXPECT_EQUAL(fun.overlap(), overlap); EXPECT_EQUAL(fun.factor(), factor); if (primary.has_value()) { EXPECT_EQUAL(fun.primary(), primary.value()); } if (fun.primary_is_mutable()) { if (fun.primary() == Primary::LHS) { EXPECT_TRUE(l_mut); } if (fun.primary() == Primary::RHS) { EXPECT_TRUE(r_mut); } } if (inplace.has_value()) { EXPECT_EQUAL(fun.inplace(), inplace.value()); } if (fun.inplace()) { EXPECT_TRUE(fun.primary_is_mutable()); size_t idx = (fun.primary() == Primary::LHS) ? 0 : 1; EXPECT_EQUAL(fixture.result_value().cells().data, fixture.param_value(idx).cells().data); EXPECT_NOT_EQUAL(fixture.result_value().cells().data, fixture.param_value(1-idx).cells().data); } else { EXPECT_NOT_EQUAL(fixture.result_value().cells().data, fixture.param_value(0).cells().data); EXPECT_NOT_EQUAL(fixture.result_value().cells().data, fixture.param_value(1).cells().data); } } }; void verify_simple(const vespalib::string &expr, Primary primary, Overlap overlap, size_t factor, bool l_mut, bool r_mut, bool inplace) { TEST_STATE(expr.c_str()); CellTypeSpace just_double({CellType::DOUBLE}, 2); FunInfo details{overlap, factor, primary, l_mut, r_mut, inplace}; EvalFixture::verify<FunInfo>(expr, {details}, just_double); } void verify_optimized(const vespalib::string &expr, Primary primary, Overlap overlap, size_t factor, bool l_mut = false, bool r_mut = false) { TEST_STATE(expr.c_str()); CellTypeSpace all_types(CellTypeUtils::list_types(), 2); FunInfo details{overlap, factor, primary, l_mut, r_mut, std::nullopt}; EvalFixture::verify<FunInfo>(expr, {details}, all_types); } void verify_optimized(const vespalib::string &expr, Overlap overlap, size_t factor, bool l_mut = false, bool r_mut = false) { TEST_STATE(expr.c_str()); CellTypeSpace all_types(CellTypeUtils::list_types(), 2); FunInfo details{overlap, factor, std::nullopt, l_mut, r_mut, std::nullopt}; EvalFixture::verify<FunInfo>(expr, {details}, all_types); } void verify_not_optimized(const vespalib::string &expr) { TEST_STATE(expr.c_str()); CellTypeSpace just_double({CellType::DOUBLE}, 2); EvalFixture::verify<FunInfo>(expr, {}, just_double); } TEST("require that basic join is optimized") { TEST_DO(verify_optimized("y5+y5$2", Primary::RHS, Overlap::FULL, 1)); } TEST("require that inplace is preferred") { TEST_DO(verify_simple("y5+y5$2", Primary::RHS, Overlap::FULL, 1, false, false, false)); TEST_DO(verify_simple("y5+@y5$2", Primary::RHS, Overlap::FULL, 1, false, true, true)); TEST_DO(verify_simple("@y5+@y5$2", Primary::RHS, Overlap::FULL, 1, true, true, true)); TEST_DO(verify_simple("@y5+y5$2", Primary::LHS, Overlap::FULL, 1, true, false, true)); } TEST("require that unit join is optimized") { TEST_DO(verify_optimized("a1b1c1+x1y1z1", Primary::RHS, Overlap::FULL, 1)); } TEST("require that trivial dimensions do not affect overlap calculation") { TEST_DO(verify_optimized("c5d1+b1c5", Primary::RHS, Overlap::FULL, 1)); } TEST("require that outer nesting is preferred to inner nesting") { TEST_DO(verify_optimized("a1b1c1+y5", Primary::RHS, Overlap::OUTER, 5)); } TEST("require that non-subset join is not optimized") { TEST_DO(verify_not_optimized("y5+z3")); } TEST("require that subset join with complex overlap is not optimized") { TEST_DO(verify_not_optimized("x3y5z3+y5")); } struct LhsRhs { vespalib::string lhs; vespalib::string rhs; size_t lhs_size; size_t rhs_size; Overlap overlap; size_t factor; LhsRhs(const vespalib::string &lhs_in, const vespalib::string &rhs_in, size_t lhs_size_in, size_t rhs_size_in, Overlap overlap_in) noexcept : lhs(lhs_in), rhs(rhs_in), lhs_size(lhs_size_in), rhs_size(rhs_size_in), overlap(overlap_in), factor(1) { if (lhs_size > rhs_size) { ASSERT_EQUAL(lhs_size % rhs_size, 0u); factor = (lhs_size / rhs_size); } else { ASSERT_EQUAL(rhs_size % lhs_size, 0u); factor = (rhs_size / lhs_size); } } }; vespalib::string adjust_param(const vespalib::string &str, bool mut_cells, bool is_rhs) { vespalib::string result = str; if (mut_cells) { result = "@" + result; } if (is_rhs) { result += "$2"; } return result; } CellType join_ct(CellType lct, CellType rct) { if (lct == CellType::DOUBLE || rct == CellType::DOUBLE) { return CellType::DOUBLE; } else { return CellType::FLOAT; } } TEST("require that various parameter combinations work") { for (CellType lct : CellTypeUtils::list_types()) { for (CellType rct : CellTypeUtils::list_types()) { for (bool left_mut: {false, true}) { for (bool right_mut: {false, true}) { for (const char * expr: {"a+b", "a-b", "a*b"}) { for (const LhsRhs &params: { LhsRhs("y5", "y5", 5, 5, Overlap::FULL), LhsRhs("y5", "x3y5", 5, 15, Overlap::INNER), LhsRhs("y5", "y5z3", 5, 15, Overlap::OUTER), LhsRhs("x3y5", "y5", 15, 5, Overlap::INNER), LhsRhs("y5z3", "y5", 15, 5, Overlap::OUTER)}) { EvalFixture::ParamRepo param_repo; auto a_spec = GenSpec::from_desc(params.lhs).cells(lct).seq(AX_B(0.25, 1.125)); auto b_spec = GenSpec::from_desc(params.rhs).cells(rct).seq(AX_B(-0.25, 25.0)); if (left_mut) { param_repo.add_mutable("a", a_spec); } else { param_repo.add("a", a_spec); } if (right_mut) { param_repo.add_mutable("b", b_spec); } else { param_repo.add("b", b_spec); } TEST_STATE(expr); CellType result_ct = join_ct(lct, rct); Primary primary = Primary::RHS; if (params.overlap == Overlap::FULL) { bool w_lhs = (lct == result_ct) && left_mut; bool w_rhs = (rct == result_ct) && right_mut; if (w_lhs && !w_rhs) { primary = Primary::LHS; } } else if (params.lhs_size > params.rhs_size) { primary = Primary::LHS; } bool pri_mut = (primary == Primary::LHS) ? left_mut : right_mut; bool pri_same_ct = (primary == Primary::LHS) ? (lct == result_ct) : (rct == result_ct); bool inplace = (pri_mut && pri_same_ct); auto expect = EvalFixture::ref(expr, param_repo); EvalFixture slow_fixture(prod_factory, expr, param_repo, false); EvalFixture test_fixture(test_factory, expr, param_repo, true, true); EvalFixture fixture(prod_factory, expr, param_repo, true, true); EXPECT_EQUAL(fixture.result(), expect); EXPECT_EQUAL(slow_fixture.result(), expect); EXPECT_EQUAL(test_fixture.result(), expect); auto info = fixture.find_all<FunInfo::LookFor>(); ASSERT_EQUAL(info.size(), 1u); FunInfo details{params.overlap, params.factor, primary, left_mut, right_mut, inplace}; details.verify(fixture, *info[0]); } } } } } } } TEST("require that scalar values are not optimized") { TEST_DO(verify_not_optimized("reduce(v3,sum)+reduce(v4,sum)")); TEST_DO(verify_not_optimized("reduce(v3,sum)+y5")); TEST_DO(verify_not_optimized("y5+reduce(v3,sum)")); TEST_DO(verify_not_optimized("reduce(v3,sum)+x3_1")); TEST_DO(verify_not_optimized("x3_1+reduce(v3,sum)")); TEST_DO(verify_not_optimized("reduce(v3,sum)+x3_1y5z3")); TEST_DO(verify_not_optimized("x3_1y5z3+reduce(v3,sum)")); } TEST("require that sparse tensors are mostly not optimized") { TEST_DO(verify_not_optimized("x3_1+x3_1$2")); TEST_DO(verify_not_optimized("x3_1+y5")); TEST_DO(verify_not_optimized("y5+x3_1")); TEST_DO(verify_not_optimized("x3_1+x3_1y5z3")); TEST_DO(verify_not_optimized("x3_1y5z3+x3_1")); } TEST("require that sparse tensor joined with trivial dense tensor is optimized") { TEST_DO(verify_optimized("x3_1+a1b1c1", Primary::LHS, Overlap::FULL, 1)); TEST_DO(verify_optimized("a1b1c1+x3_1", Primary::RHS, Overlap::FULL, 1)); } TEST("require that primary tensor can be empty") { TEST_DO(verify_optimized("x0_1y5z3+y5z3", Primary::LHS, Overlap::FULL, 1)); TEST_DO(verify_optimized("y5z3+x0_1y5z3", Primary::RHS, Overlap::FULL, 1)); } TEST("require that mixed tensors can be optimized") { TEST_DO(verify_not_optimized("x3_1y5z3+x3_1y5z3$2")); TEST_DO(verify_optimized("x3_1y5z3+y5z3", Primary::LHS, Overlap::FULL, 1)); TEST_DO(verify_optimized("x3_1y5z3+y5", Primary::LHS, Overlap::OUTER, 3)); TEST_DO(verify_optimized("x3_1y5z3+z3", Primary::LHS, Overlap::INNER, 5)); TEST_DO(verify_optimized("y5z3+x3_1y5z3", Primary::RHS, Overlap::FULL, 1)); TEST_DO(verify_optimized("y5+x3_1y5z3", Primary::RHS, Overlap::OUTER, 3)); TEST_DO(verify_optimized("z3+x3_1y5z3", Primary::RHS, Overlap::INNER, 5)); } TEST("require that mixed tensors can be inplace") { TEST_DO(verify_optimized("@x3_1y5z3+y5z3", Primary::LHS, Overlap::FULL, 1, true, false)); TEST_DO(verify_optimized("@x3_1y5z3+y5", Primary::LHS, Overlap::OUTER, 3, true, false)); TEST_DO(verify_optimized("@x3_1y5z3+z3", Primary::LHS, Overlap::INNER, 5, true, false)); TEST_DO(verify_optimized("y5z3+@x3_1y5z3", Primary::RHS, Overlap::FULL, 1, false, true)); TEST_DO(verify_optimized("y5+@x3_1y5z3", Primary::RHS, Overlap::OUTER, 3, false, true)); TEST_DO(verify_optimized("z3+@x3_1y5z3", Primary::RHS, Overlap::INNER, 5, false, true)); } TEST_MAIN() { TEST_RUN_ALL(); }
// Copyright Verizon Media. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include <vespa/vespalib/testkit/test_kit.h> #include <vespa/eval/eval/fast_value.h> #include <vespa/eval/eval/simple_value.h> #include <vespa/eval/eval/tensor_function.h> #include <vespa/eval/instruction/mixed_simple_join_function.h> #include <vespa/eval/eval/test/eval_fixture.h> #include <vespa/eval/eval/test/gen_spec.h> #include <vespa/vespalib/util/stringfmt.h> using namespace vespalib; using namespace vespalib::eval; using namespace vespalib::eval::test; using namespace vespalib::eval::tensor_function; using vespalib::make_string_short::fmt; const ValueBuilderFactory &prod_factory = FastValueBuilderFactory::get(); const ValueBuilderFactory &test_factory = SimpleValueBuilderFactory::get(); using Primary = MixedSimpleJoinFunction::Primary; using Overlap = MixedSimpleJoinFunction::Overlap; namespace vespalib::eval { std::ostream &operator<<(std::ostream &os, Primary primary) { switch(primary) { case Primary::LHS: return os << "LHS"; case Primary::RHS: return os << "RHS"; } abort(); } std::ostream &operator<<(std::ostream &os, Overlap overlap) { switch(overlap) { case Overlap::FULL: return os << "FULL"; case Overlap::INNER: return os << "INNER"; case Overlap::OUTER: return os << "OUTER"; } abort(); } } struct FunInfo { using LookFor = MixedSimpleJoinFunction; Overlap overlap; size_t factor; std::optional<Primary> primary; bool l_mut; bool r_mut; std::optional<bool> inplace; void verify(const EvalFixture &fixture, const LookFor &fun) const { EXPECT_TRUE(fun.result_is_mutable()); EXPECT_EQUAL(fun.overlap(), overlap); EXPECT_EQUAL(fun.factor(), factor); if (primary.has_value()) { EXPECT_EQUAL(fun.primary(), primary.value()); } if (fun.primary_is_mutable()) { if (fun.primary() == Primary::LHS) { EXPECT_TRUE(l_mut); } if (fun.primary() == Primary::RHS) { EXPECT_TRUE(r_mut); } } if (inplace.has_value()) { EXPECT_EQUAL(fun.inplace(), inplace.value()); } if (fun.inplace()) { EXPECT_TRUE(fun.primary_is_mutable()); size_t idx = (fun.primary() == Primary::LHS) ? 0 : 1; EXPECT_EQUAL(fixture.result_value().cells().data, fixture.param_value(idx).cells().data); EXPECT_NOT_EQUAL(fixture.result_value().cells().data, fixture.param_value(1-idx).cells().data); } else { EXPECT_NOT_EQUAL(fixture.result_value().cells().data, fixture.param_value(0).cells().data); EXPECT_NOT_EQUAL(fixture.result_value().cells().data, fixture.param_value(1).cells().data); } } }; void verify_simple(const vespalib::string &expr, Primary primary, Overlap overlap, size_t factor, bool l_mut, bool r_mut, bool inplace) { TEST_STATE(expr.c_str()); CellTypeSpace just_double({CellType::DOUBLE}, 2); FunInfo details{overlap, factor, primary, l_mut, r_mut, inplace}; EvalFixture::verify<FunInfo>(expr, {details}, just_double); } void verify_optimized(const vespalib::string &expr, Primary primary, Overlap overlap, size_t factor, bool l_mut = false, bool r_mut = false) { TEST_STATE(expr.c_str()); CellTypeSpace all_types(CellTypeUtils::list_types(), 2); FunInfo details{overlap, factor, primary, l_mut, r_mut, std::nullopt}; EvalFixture::verify<FunInfo>(expr, {details}, all_types); } void verify_optimized(const vespalib::string &expr, Overlap overlap, size_t factor, bool l_mut = false, bool r_mut = false) { TEST_STATE(expr.c_str()); CellTypeSpace all_types(CellTypeUtils::list_types(), 2); FunInfo details{overlap, factor, std::nullopt, l_mut, r_mut, std::nullopt}; EvalFixture::verify<FunInfo>(expr, {details}, all_types); } void verify_not_optimized(const vespalib::string &expr) { TEST_STATE(expr.c_str()); CellTypeSpace just_double({CellType::DOUBLE}, 2); EvalFixture::verify<FunInfo>(expr, {}, just_double); } TEST("require that basic join is optimized") { TEST_DO(verify_optimized("y5+y5$2", Primary::RHS, Overlap::FULL, 1)); } TEST("require that inplace is preferred") { TEST_DO(verify_simple("y5+y5$2", Primary::RHS, Overlap::FULL, 1, false, false, false)); TEST_DO(verify_simple("y5+@y5$2", Primary::RHS, Overlap::FULL, 1, false, true, true)); TEST_DO(verify_simple("@y5+@y5$2", Primary::RHS, Overlap::FULL, 1, true, true, true)); TEST_DO(verify_simple("@y5+y5$2", Primary::LHS, Overlap::FULL, 1, true, false, true)); } TEST("require that unit join is optimized") { TEST_DO(verify_optimized("a1b1c1+x1y1z1", Primary::RHS, Overlap::FULL, 1)); } TEST("require that trivial dimensions do not affect overlap calculation") { TEST_DO(verify_optimized("c5d1+b1c5", Primary::RHS, Overlap::FULL, 1)); } TEST("require that outer nesting is preferred to inner nesting") { TEST_DO(verify_optimized("a1b1c1+y5", Primary::RHS, Overlap::OUTER, 5)); } TEST("require that non-subset join is not optimized") { TEST_DO(verify_not_optimized("y5+z3")); } TEST("require that subset join with complex overlap is not optimized") { TEST_DO(verify_not_optimized("x3y5z3+y5")); } struct LhsRhs { vespalib::string lhs; vespalib::string rhs; size_t lhs_size; size_t rhs_size; Overlap overlap; size_t factor; LhsRhs(const vespalib::string &lhs_in, const vespalib::string &rhs_in, size_t lhs_size_in, size_t rhs_size_in, Overlap overlap_in) noexcept : lhs(lhs_in), rhs(rhs_in), lhs_size(lhs_size_in), rhs_size(rhs_size_in), overlap(overlap_in), factor(1) { if (lhs_size > rhs_size) { ASSERT_EQUAL(lhs_size % rhs_size, 0u); factor = (lhs_size / rhs_size); } else { ASSERT_EQUAL(rhs_size % lhs_size, 0u); factor = (rhs_size / lhs_size); } } }; CellType join_ct(CellType lct, CellType rct) { if (lct == CellType::DOUBLE || rct == CellType::DOUBLE) { return CellType::DOUBLE; } else { return CellType::FLOAT; } } TEST("require that various parameter combinations work") { for (CellType lct : CellTypeUtils::list_types()) { for (CellType rct : CellTypeUtils::list_types()) { for (bool left_mut: {false, true}) { for (bool right_mut: {false, true}) { for (const char * expr: {"a+b", "a-b", "a*b"}) { for (const LhsRhs &params: { LhsRhs("y5", "y5", 5, 5, Overlap::FULL), LhsRhs("y5", "x3y5", 5, 15, Overlap::INNER), LhsRhs("y5", "y5z3", 5, 15, Overlap::OUTER), LhsRhs("x3y5", "y5", 15, 5, Overlap::INNER), LhsRhs("y5z3", "y5", 15, 5, Overlap::OUTER)}) { EvalFixture::ParamRepo param_repo; auto a_spec = GenSpec::from_desc(params.lhs).cells(lct).seq(AX_B(0.25, 1.125)); auto b_spec = GenSpec::from_desc(params.rhs).cells(rct).seq(AX_B(-0.25, 25.0)); if (left_mut) { param_repo.add_mutable("a", a_spec); } else { param_repo.add("a", a_spec); } if (right_mut) { param_repo.add_mutable("b", b_spec); } else { param_repo.add("b", b_spec); } TEST_STATE(expr); CellType result_ct = join_ct(lct, rct); Primary primary = Primary::RHS; if (params.overlap == Overlap::FULL) { bool w_lhs = (lct == result_ct) && left_mut; bool w_rhs = (rct == result_ct) && right_mut; if (w_lhs && !w_rhs) { primary = Primary::LHS; } } else if (params.lhs_size > params.rhs_size) { primary = Primary::LHS; } bool pri_mut = (primary == Primary::LHS) ? left_mut : right_mut; bool pri_same_ct = (primary == Primary::LHS) ? (lct == result_ct) : (rct == result_ct); bool inplace = (pri_mut && pri_same_ct); auto expect = EvalFixture::ref(expr, param_repo); EvalFixture slow_fixture(prod_factory, expr, param_repo, false); EvalFixture test_fixture(test_factory, expr, param_repo, true, true); EvalFixture fixture(prod_factory, expr, param_repo, true, true); EXPECT_EQUAL(fixture.result(), expect); EXPECT_EQUAL(slow_fixture.result(), expect); EXPECT_EQUAL(test_fixture.result(), expect); auto info = fixture.find_all<FunInfo::LookFor>(); ASSERT_EQUAL(info.size(), 1u); FunInfo details{params.overlap, params.factor, primary, left_mut, right_mut, inplace}; details.verify(fixture, *info[0]); } } } } } } } TEST("require that scalar values are not optimized") { TEST_DO(verify_not_optimized("reduce(v3,sum)+reduce(v4,sum)")); TEST_DO(verify_not_optimized("reduce(v3,sum)+y5")); TEST_DO(verify_not_optimized("y5+reduce(v3,sum)")); TEST_DO(verify_not_optimized("reduce(v3,sum)+x3_1")); TEST_DO(verify_not_optimized("x3_1+reduce(v3,sum)")); TEST_DO(verify_not_optimized("reduce(v3,sum)+x3_1y5z3")); TEST_DO(verify_not_optimized("x3_1y5z3+reduce(v3,sum)")); } TEST("require that sparse tensors are mostly not optimized") { TEST_DO(verify_not_optimized("x3_1+x3_1$2")); TEST_DO(verify_not_optimized("x3_1+y5")); TEST_DO(verify_not_optimized("y5+x3_1")); TEST_DO(verify_not_optimized("x3_1+x3_1y5z3")); TEST_DO(verify_not_optimized("x3_1y5z3+x3_1")); } TEST("require that sparse tensor joined with trivial dense tensor is optimized") { TEST_DO(verify_optimized("x3_1+a1b1c1", Primary::LHS, Overlap::FULL, 1)); TEST_DO(verify_optimized("a1b1c1+x3_1", Primary::RHS, Overlap::FULL, 1)); } TEST("require that primary tensor can be empty") { TEST_DO(verify_optimized("x0_1y5z3+y5z3", Primary::LHS, Overlap::FULL, 1)); TEST_DO(verify_optimized("y5z3+x0_1y5z3", Primary::RHS, Overlap::FULL, 1)); } TEST("require that mixed tensors can be optimized") { TEST_DO(verify_not_optimized("x3_1y5z3+x3_1y5z3$2")); TEST_DO(verify_optimized("x3_1y5z3+y5z3", Primary::LHS, Overlap::FULL, 1)); TEST_DO(verify_optimized("x3_1y5z3+y5", Primary::LHS, Overlap::OUTER, 3)); TEST_DO(verify_optimized("x3_1y5z3+z3", Primary::LHS, Overlap::INNER, 5)); TEST_DO(verify_optimized("y5z3+x3_1y5z3", Primary::RHS, Overlap::FULL, 1)); TEST_DO(verify_optimized("y5+x3_1y5z3", Primary::RHS, Overlap::OUTER, 3)); TEST_DO(verify_optimized("z3+x3_1y5z3", Primary::RHS, Overlap::INNER, 5)); } TEST("require that mixed tensors can be inplace") { TEST_DO(verify_optimized("@x3_1y5z3+y5z3", Primary::LHS, Overlap::FULL, 1, true, false)); TEST_DO(verify_optimized("@x3_1y5z3+y5", Primary::LHS, Overlap::OUTER, 3, true, false)); TEST_DO(verify_optimized("@x3_1y5z3+z3", Primary::LHS, Overlap::INNER, 5, true, false)); TEST_DO(verify_optimized("y5z3+@x3_1y5z3", Primary::RHS, Overlap::FULL, 1, false, true)); TEST_DO(verify_optimized("y5+@x3_1y5z3", Primary::RHS, Overlap::OUTER, 3, false, true)); TEST_DO(verify_optimized("z3+@x3_1y5z3", Primary::RHS, Overlap::INNER, 5, false, true)); } TEST_MAIN() { TEST_RUN_ALL(); }
drop unused code
drop unused code
C++
apache-2.0
vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa
6176ae28777fc6d2894485e38cc0e48cf7caf986
searchlib/src/vespa/searchlib/features/bm25_feature.cpp
searchlib/src/vespa/searchlib/features/bm25_feature.cpp
// Copyright 2019 Oath Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include "bm25_feature.h" #include <vespa/searchlib/fef/itermdata.h> #include <vespa/searchlib/fef/itermfielddata.h> #include <memory> namespace search::features { using fef::Blueprint; using fef::FeatureExecutor; using fef::FieldInfo; using fef::ITermData; using fef::ITermFieldData; Bm25Executor::Bm25Executor(const fef::FieldInfo& field, const fef::IQueryEnvironment& env) : FeatureExecutor(), _terms(), _avg_field_length(10), _k1_param(1.2), _b_param(0.75) { // TODO: Don't use hard coded avg_field_length // TODO: Add support for setting k1 and b for (size_t i = 0; i < env.getNumTerms(); ++i) { const ITermData* term = env.getTerm(i); for (size_t j = 0; j < term->numFields(); ++j) { const ITermFieldData& term_field = term->field(j); if (field.id() == term_field.getFieldId()) { // TODO: Add proper calculation of IDF _terms.emplace_back(term_field.getHandle(), 1.0); } } } } void Bm25Executor::handle_bind_match_data(const fef::MatchData& match_data) { for (auto& term : _terms) { term.tfmd = match_data.resolveTermField(term.handle); } } void Bm25Executor::execute(uint32_t doc_id) { feature_t score = 0; for (const auto& term : _terms) { if (term.tfmd->getDocId() == doc_id) { feature_t num_occs = term.tfmd->getNumOccs(); feature_t norm_field_length = ((feature_t)term.tfmd->getFieldLength()) / _avg_field_length; feature_t numerator = term.inverse_doc_freq * num_occs * (_k1_param + 1); feature_t denominator = num_occs + (_k1_param * (1 - _b_param + (_b_param * norm_field_length))); score += numerator / denominator; } } outputs().set_number(0, score); } Bm25Blueprint::Bm25Blueprint() : Blueprint("bm25"), _field(nullptr) { } void Bm25Blueprint::visitDumpFeatures(const fef::IIndexEnvironment& env, fef::IDumpFeatureVisitor& visitor) const { (void) env; (void) visitor; // TODO: Implement } fef::Blueprint::UP Bm25Blueprint::createInstance() const { return std::make_unique<Bm25Blueprint>(); } bool Bm25Blueprint::setup(const fef::IIndexEnvironment& env, const fef::ParameterList& params) { const auto& field_name = params[0].getValue(); _field = env.getFieldByName(field_name); describeOutput("score", "The bm25 score for all terms searching in the given index field"); return (_field != nullptr); } fef::FeatureExecutor& Bm25Blueprint::createExecutor(const fef::IQueryEnvironment& env, vespalib::Stash& stash) const { return stash.create<Bm25Executor>(*_field, env); } }
// Copyright 2019 Oath Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include "bm25_feature.h" #include <vespa/searchlib/fef/itermdata.h> #include <vespa/searchlib/fef/itermfielddata.h> #include <memory> namespace search::features { using fef::Blueprint; using fef::FeatureExecutor; using fef::FieldInfo; using fef::ITermData; using fef::ITermFieldData; using fef::MatchDataDetails; Bm25Executor::Bm25Executor(const fef::FieldInfo& field, const fef::IQueryEnvironment& env) : FeatureExecutor(), _terms(), _avg_field_length(10), _k1_param(1.2), _b_param(0.75) { // TODO: Don't use hard coded avg_field_length // TODO: Add support for setting k1 and b for (size_t i = 0; i < env.getNumTerms(); ++i) { const ITermData* term = env.getTerm(i); for (size_t j = 0; j < term->numFields(); ++j) { const ITermFieldData& term_field = term->field(j); if (field.id() == term_field.getFieldId()) { // TODO: Add proper calculation of IDF _terms.emplace_back(term_field.getHandle(MatchDataDetails::Cheap), 1.0); } } } } void Bm25Executor::handle_bind_match_data(const fef::MatchData& match_data) { for (auto& term : _terms) { term.tfmd = match_data.resolveTermField(term.handle); } } void Bm25Executor::execute(uint32_t doc_id) { feature_t score = 0; for (const auto& term : _terms) { if (term.tfmd->getDocId() == doc_id) { feature_t num_occs = term.tfmd->getNumOccs(); feature_t norm_field_length = ((feature_t)term.tfmd->getFieldLength()) / _avg_field_length; feature_t numerator = term.inverse_doc_freq * num_occs * (_k1_param + 1); feature_t denominator = num_occs + (_k1_param * (1 - _b_param + (_b_param * norm_field_length))); score += numerator / denominator; } } outputs().set_number(0, score); } Bm25Blueprint::Bm25Blueprint() : Blueprint("bm25"), _field(nullptr) { } void Bm25Blueprint::visitDumpFeatures(const fef::IIndexEnvironment& env, fef::IDumpFeatureVisitor& visitor) const { (void) env; (void) visitor; // TODO: Implement } fef::Blueprint::UP Bm25Blueprint::createInstance() const { return std::make_unique<Bm25Blueprint>(); } bool Bm25Blueprint::setup(const fef::IIndexEnvironment& env, const fef::ParameterList& params) { const auto& field_name = params[0].getValue(); _field = env.getFieldByName(field_name); describeOutput("score", "The bm25 score for all terms searching in the given index field"); return (_field != nullptr); } fef::FeatureExecutor& Bm25Blueprint::createExecutor(const fef::IQueryEnvironment& env, vespalib::Stash& stash) const { return stash.create<Bm25Executor>(*_field, env); } }
Trim down what to unpack for bm25 feature.
Trim down what to unpack for bm25 feature.
C++
apache-2.0
vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa
c375dc49d0dc51225631ae096cb036f4e43d33ba
corelib/PWSprefs.cpp
corelib/PWSprefs.cpp
#include "PWSprefs.h" #include <AfxWin.h> // for AfxGetApp() #include <strstream> using namespace std; #if defined(POCKET_PC) const LPCTSTR PWS_REG_POSITION = _T("Position"); const LPCTSTR PWS_REG_OPTIONS = _T("Options"); #else const LPCTSTR PWS_REG_POSITION = _T(""); const LPCTSTR PWS_REG_OPTIONS = _T(""); #endif PWSprefs *PWSprefs::self = NULL; // 1st parameter = name of preference // 2nd parameter = default value // 3rd parameter if 'true' means value stored in db, if 'false' means use registry only const PWSprefs::boolPref PWSprefs::m_bool_prefs[NumBoolPrefs] = { {_T("alwaysontop"), false, true}, {_T("showpwdefault"), false, true}, {_T("showpwinlist"), false, true}, {_T("sortascending"), true, true}, {_T("usedefuser"), false, true}, {_T("saveimmediately"), true, true}, {_T("pwuselowercase"), true, true}, {_T("pwuseuppercase"), true, true}, {_T("pwusedigits"), true, true}, {_T("pwusesymbols"), false, true}, {_T("pwusehexdigits"), false, true}, {_T("pweasyvision"), false, true}, {_T("dontaskquestion"), false, true}, {_T("deletequestion"), false, true}, {_T("DCShowsPassword"), false, true}, {_T("DontAskMinimizeClearYesNo"), true, true}, {_T("DatabaseClear"), false, true}, {_T("DontAskSaveMinimize"), false, true}, {_T("QuerySetDef"), true, true}, {_T("UseNewToolbar"), true, true}, {_T("UseSystemTray"), true, true}, {_T("LockOnWindowLock"), true, true}, {_T("LockOnIdleTimeout"), true, true}, {_T("EscExits"), true, true}, {_T("IsUTF8"), true, true}, // default true from 3.x for non-win9x {_T("HotKeyEnabled"), false, true}, {_T("MRUOnFileMenu"), true, true}, {_T("DisplayExpandedAddEditDlg"), true, true}, {_T("MaintainDateTimeStamps"), false, true}, {_T("SavePasswordHistory"), false, true}, {_T("FindWraps"), false, false}, {_T("ShowNotesDefault"), false, true}, }; // Defensive programming (the Registry & files are editable) // Set min and max values. If value outside this range, set to default. // "-1" means not set/do not check const PWSprefs::intPref PWSprefs::m_int_prefs[NumIntPrefs] = { {_T("column1width"), (unsigned int)-1, false, -1, -1}, // set @ runtime {_T("column2width"), (unsigned int)-1, false, -1, -1}, // set @ runtime {_T("column3width"), (unsigned int)-1, false, -1, -1}, // set @ runtime {_T("column4width"), (unsigned int)-1, false, -1, -1}, // set @ runtime {_T("sortedcolumn"), 0, true, 0, 7}, {_T("pwlendefault"), 8, true, 4, 1024}, // maxmruitems maximum = ID_FILE_MRU_ENTRYMAX - ID_FILE_MRU_ENTRY1 + 1 {_T("maxmruitems"), 4, true, 0, 20}, {_T("IdleTimeout"), 5, true, 1, 120}, {_T("DoubleClickAction"), PWSprefs::DoubleClickCopy, true, minDCA, maxDCA}, {_T("HotKey"), 0, false, 0, -1}, // zero means disabled, !=0 is key code. // MaxREItems maximum = ID_TRAYRECENT_ENTRYMAX - ID_TRAYRECENT_ENTRY1 + 1 {_T("MaxREItems"), 25, true, 0, 25}, {_T("TreeDisplayStatusAtOpen"), PWSprefs::AllCollapsed, true, minTDS, maxTDS}, {_T("NumPWHistoryDefault"), 3, true, 0, 255}, }; const PWSprefs::stringPref PWSprefs::m_string_prefs[NumStringPrefs] = { {_T("currentbackup"), _T(""), true}, {_T("currentfile"), _T(""), false}, {_T("lastview"), _T("tree"), true}, {_T("defusername"), _T(""), true}, {_T("treefont"), _T(""), true}, }; PWSprefs *PWSprefs::GetInstance() { if (self == NULL) self = new PWSprefs; return self; } void PWSprefs::DeleteInstance() { delete self; self = NULL; } PWSprefs::PWSprefs() : m_app(::AfxGetApp()), m_prefs_changed(false) { ASSERT(m_app != NULL); // Start by reading in from registry int i; // Defensive programming, if not "0", then "TRUE", all other values = FALSE for (i = 0; i < NumBoolPrefs; i++) m_boolValues[i] = m_app->GetProfileInt(PWS_REG_OPTIONS, m_bool_prefs[i].name, m_bool_prefs[i].defVal) != 0; // Defensive programming, if outside the permitted range, then set to default for (i = 0; i < NumIntPrefs; i++) { const int iVal = m_app->GetProfileInt(PWS_REG_OPTIONS, m_int_prefs[i].name, m_int_prefs[i].defVal); if (m_int_prefs[i].minVal != -1 && iVal < m_int_prefs[i].minVal) m_intValues[i] = m_int_prefs[i].defVal; else if (m_int_prefs[i].maxVal != -1 && iVal > m_int_prefs[i].maxVal) m_intValues[i] = m_int_prefs[i].defVal; else m_intValues[i] = iVal; } // Defensive programming not applicable. for (i = 0; i < NumStringPrefs; i++) m_stringValues[i] = CMyString(m_app->GetProfileString(PWS_REG_OPTIONS, m_string_prefs[i].name, m_string_prefs[i].defVal)); /* The following is "defensive" code because there was "a code ordering issue" in V3.02 and earlier. PWSprefs.cpp and PWSprefs.h differed in the order of the HotKey and DoubleClickAction preferences. This is to protect the application should a HotKey value be assigned to DoubleClickAction. Note: HotKey also made an "Application preference" from a "Database preference". */ if (m_intValues[HotKey] > 0 && m_intValues[HotKey] <= 3) { m_boolValues[HotKeyEnabled] = false; m_intValues[DoubleClickAction] = m_intValues[HotKey]; m_intValues[HotKey] = 0; m_app->WriteProfileInt(PWS_REG_OPTIONS, m_bool_prefs[HotKeyEnabled].name, 0); m_app->WriteProfileInt(PWS_REG_OPTIONS, m_int_prefs[HotKey].name, 0); m_app->WriteProfileInt(PWS_REG_OPTIONS, m_int_prefs[DoubleClickAction].name, m_intValues[DoubleClickAction]); } if (m_intValues[DoubleClickAction] > 3) { m_intValues[DoubleClickAction] = 1; m_app->WriteProfileInt(PWS_REG_OPTIONS, m_int_prefs[DoubleClickAction].name, 1); } // End of "defensive" code } bool PWSprefs::GetPref(BoolPrefs pref_enum) const { return m_bool_prefs[pref_enum].isPersistent ? m_boolValues[pref_enum] : GetBoolPref(m_bool_prefs[pref_enum].name, m_bool_prefs[pref_enum].defVal); } bool PWSprefs::GetBoolPref(const CMyString &name, bool defVal) const { return m_app->GetProfileInt(PWS_REG_OPTIONS, name, defVal) != 0; } unsigned int PWSprefs::GetPref(IntPrefs pref_enum) const { return m_int_prefs[pref_enum].isPersistent ? m_intValues[pref_enum] : GetIntPref(m_int_prefs[pref_enum].name, m_int_prefs[pref_enum].defVal); } unsigned int PWSprefs::GetPref(IntPrefs pref_enum, unsigned int defVal) const { if (m_int_prefs[pref_enum].isPersistent) return m_intValues[pref_enum] == (unsigned int)-1 ? defVal : m_intValues[pref_enum]; else return GetIntPref(m_int_prefs[pref_enum].name, defVal); } unsigned int PWSprefs::GetIntPref(const CMyString &name, unsigned int defVal) const { return m_app->GetProfileInt(PWS_REG_OPTIONS, name, defVal); } CMyString PWSprefs::GetPref(StringPrefs pref_enum) const { return m_string_prefs[pref_enum].isPersistent ? m_stringValues[pref_enum] : GetStringPref(m_string_prefs[pref_enum].name, m_string_prefs[pref_enum].defVal); } CMyString PWSprefs::GetStringPref(const CMyString &name, const CMyString &defVal) const { CMyString retval = m_app->GetProfileString(PWS_REG_OPTIONS, name, defVal); return retval; } void PWSprefs::GetPrefRect(long &top, long &bottom, long &left, long &right) const { // this is never store in db top = m_app->GetProfileInt(PWS_REG_POSITION, _T("top"), -1); bottom = m_app->GetProfileInt(PWS_REG_POSITION, _T("bottom"), -1); left = m_app->GetProfileInt(PWS_REG_POSITION, _T("left"), -1); right = m_app->GetProfileInt(PWS_REG_POSITION, _T("right"), -1); } void PWSprefs::SetPref(BoolPrefs pref_enum, bool value) { m_prefs_changed |= (m_boolValues[pref_enum] != value && m_bool_prefs[pref_enum].isPersistent); m_boolValues[pref_enum] = value; SetPref(m_bool_prefs[pref_enum].name, value); } void PWSprefs::SetPref(const CMyString &name, bool val) { m_app->WriteProfileInt(PWS_REG_OPTIONS, name, val ? 1 : 0); } void PWSprefs::SetPref(IntPrefs pref_enum, unsigned int value) { m_prefs_changed |= (m_intValues[pref_enum] != value && m_int_prefs[pref_enum].isPersistent); m_intValues[pref_enum] = value; SetPref(m_int_prefs[pref_enum].name, value); } void PWSprefs::SetPref(const CMyString &name, unsigned int val) { m_app->WriteProfileInt(PWS_REG_OPTIONS, name, val); } void PWSprefs::SetPref(StringPrefs pref_enum, const CMyString &value) { m_prefs_changed |= (m_stringValues[pref_enum] != value && m_string_prefs[pref_enum].isPersistent); m_stringValues[pref_enum] = value; SetPref(m_string_prefs[pref_enum].name, value); } void PWSprefs::SetPref(const CMyString &name, const CMyString &val) { m_app->WriteProfileString(PWS_REG_OPTIONS, name, val); } void PWSprefs::SetPrefRect(long top, long bottom, long left, long right) { m_app->WriteProfileInt(PWS_REG_POSITION, _T("top"), top); m_app->WriteProfileInt(PWS_REG_POSITION, _T("bottom"), bottom); m_app->WriteProfileInt(PWS_REG_POSITION, _T("left"), left); m_app->WriteProfileInt(PWS_REG_POSITION, _T("right"), right); } CMyString PWSprefs::Store() { /* * Create a string of values that are (1) different from the defaults, && (2) are isPersistent * String is of the form "X nn vv X nn vv..." Where X=[BIS] for binary, integer and string, resp., * nn is the numeric value of the enum, and vv is the value, {1.0} for bool, unsigned integer * for int, and quoted string for String. */ CMyString retval(_T("")); ostrstream os; int i; for (i = 0; i < NumBoolPrefs; i++) if (m_boolValues[i] != m_bool_prefs[i].defVal && m_bool_prefs[i].isPersistent) os << "B " << i << ' ' << (m_boolValues[i] ? 1 : 0) << ' '; for (i = 0; i < NumIntPrefs; i++) if (m_intValues[i] != m_int_prefs[i].defVal && m_int_prefs[i].isPersistent) os << "I " << i << ' ' << m_intValues[i] << ' '; for (i = 0; i < NumStringPrefs; i++) if (m_stringValues[i] != m_string_prefs[i].defVal && m_string_prefs[i].isPersistent) os << "S " << i << " \"" << LPCTSTR(m_stringValues[i]) << "\" "; os << ends; retval = os.str(); delete[] os.str(); // reports memory leaks in spite of this! return retval; } void PWSprefs::Load(const CMyString &prefString) { // parse prefString, updating current values istrstream is(prefString); char type; int index; while (is) { is >> type >> index; switch (type) { case 'B': if (index >= NumBoolPrefs) { continue; // forward compatibility } else { int val; is >> val; ASSERT(val == 0 || val == 1); m_boolValues[index] = (val != 0); } break; case 'I': if (index >= NumIntPrefs) { continue; // forward compatibility } else { unsigned int val; is >> val; m_intValues[index] = val; } break; case 'S': if (index >= NumStringPrefs) { continue; // forward compatibility } else { const int N = prefString.GetLength(); // safe upper limit on string size char *buf = new char[N]; is.ignore(2, '\"'); // skip over space and leading " is.get(buf, N, '\"'); // get string value CMyString val(buf); m_stringValues[index] = val; delete[] buf; } break; default: continue; // forward compatibility (also last space) } // switch } // while }
#include "PWSprefs.h" #include <AfxWin.h> // for AfxGetApp() #include <strstream> using namespace std; #if defined(POCKET_PC) const LPCTSTR PWS_REG_POSITION = _T("Position"); const LPCTSTR PWS_REG_OPTIONS = _T("Options"); #else const LPCTSTR PWS_REG_POSITION = _T(""); const LPCTSTR PWS_REG_OPTIONS = _T(""); #endif PWSprefs *PWSprefs::self = NULL; // 1st parameter = name of preference // 2nd parameter = default value // 3rd parameter if 'true' means value stored in db, if 'false' means use registry only const PWSprefs::boolPref PWSprefs::m_bool_prefs[NumBoolPrefs] = { {_T("alwaysontop"), false, true}, {_T("showpwdefault"), false, true}, {_T("showpwinlist"), false, true}, {_T("sortascending"), true, true}, {_T("usedefuser"), false, true}, {_T("saveimmediately"), true, true}, {_T("pwuselowercase"), true, true}, {_T("pwuseuppercase"), true, true}, {_T("pwusedigits"), true, true}, {_T("pwusesymbols"), false, true}, {_T("pwusehexdigits"), false, true}, {_T("pweasyvision"), false, true}, {_T("dontaskquestion"), false, true}, {_T("deletequestion"), false, true}, {_T("DCShowsPassword"), false, true}, {_T("DontAskMinimizeClearYesNo"), true, true}, {_T("DatabaseClear"), false, true}, {_T("DontAskSaveMinimize"), false, true}, {_T("QuerySetDef"), true, true}, {_T("UseNewToolbar"), true, true}, {_T("UseSystemTray"), true, true}, {_T("LockOnWindowLock"), true, true}, {_T("LockOnIdleTimeout"), true, true}, {_T("EscExits"), true, true}, {_T("IsUTF8"), true, true}, // default true from 3.x for non-win9x {_T("HotKeyEnabled"), false, true}, {_T("MRUOnFileMenu"), true, true}, {_T("DisplayExpandedAddEditDlg"), true, true}, {_T("MaintainDateTimeStamps"), false, true}, {_T("SavePasswordHistory"), false, true}, {_T("FindWraps"), false, false}, {_T("ShowNotesDefault"), false, true}, }; // Defensive programming (the Registry & files are editable) // Set min and max values. If value outside this range, set to default. // "-1" means not set/do not check const PWSprefs::intPref PWSprefs::m_int_prefs[NumIntPrefs] = { {_T("column1width"), (unsigned int)-1, false, -1, -1}, // set @ runtime {_T("column2width"), (unsigned int)-1, false, -1, -1}, // set @ runtime {_T("column3width"), (unsigned int)-1, false, -1, -1}, // set @ runtime {_T("column4width"), (unsigned int)-1, false, -1, -1}, // set @ runtime {_T("sortedcolumn"), 0, true, 0, 7}, {_T("pwlendefault"), 8, true, 4, 1024}, // maxmruitems maximum = ID_FILE_MRU_ENTRYMAX - ID_FILE_MRU_ENTRY1 + 1 {_T("maxmruitems"), 4, true, 0, 20}, {_T("IdleTimeout"), 5, true, 1, 120}, {_T("DoubleClickAction"), PWSprefs::DoubleClickCopy, true, minDCA, maxDCA}, {_T("HotKey"), 0, false, 0, -1}, // zero means disabled, !=0 is key code. // MaxREItems maximum = ID_TRAYRECENT_ENTRYMAX - ID_TRAYRECENT_ENTRY1 + 1 {_T("MaxREItems"), 25, true, 0, 25}, {_T("TreeDisplayStatusAtOpen"), PWSprefs::AllCollapsed, true, minTDS, maxTDS}, {_T("NumPWHistoryDefault"), 3, true, 0, 255}, }; const PWSprefs::stringPref PWSprefs::m_string_prefs[NumStringPrefs] = { {_T("currentbackup"), _T(""), true}, {_T("currentfile"), _T(""), false}, {_T("lastview"), _T("tree"), true}, {_T("defusername"), _T(""), true}, {_T("treefont"), _T(""), true}, }; PWSprefs *PWSprefs::GetInstance() { if (self == NULL) self = new PWSprefs; return self; } void PWSprefs::DeleteInstance() { delete self; self = NULL; } PWSprefs::PWSprefs() : m_app(::AfxGetApp()), m_prefs_changed(false) { ASSERT(m_app != NULL); // Start by reading in from registry int i; // Defensive programming, if not "0", then "TRUE", all other values = FALSE for (i = 0; i < NumBoolPrefs; i++) m_boolValues[i] = m_app->GetProfileInt(PWS_REG_OPTIONS, m_bool_prefs[i].name, m_bool_prefs[i].defVal) != 0; // Defensive programming, if outside the permitted range, then set to default for (i = 0; i < NumIntPrefs; i++) { const int iVal = m_app->GetProfileInt(PWS_REG_OPTIONS, m_int_prefs[i].name, m_int_prefs[i].defVal); if (m_int_prefs[i].minVal != -1 && iVal < m_int_prefs[i].minVal) m_intValues[i] = m_int_prefs[i].defVal; else if (m_int_prefs[i].maxVal != -1 && iVal > m_int_prefs[i].maxVal) m_intValues[i] = m_int_prefs[i].defVal; else m_intValues[i] = iVal; } // Defensive programming not applicable. for (i = 0; i < NumStringPrefs; i++) m_stringValues[i] = CMyString(m_app->GetProfileString(PWS_REG_OPTIONS, m_string_prefs[i].name, m_string_prefs[i].defVal)); /* The following is "defensive" code because there was "a code ordering issue" in V3.02 and earlier. PWSprefs.cpp and PWSprefs.h differed in the order of the HotKey and DoubleClickAction preferences. This is to protect the application should a HotKey value be assigned to DoubleClickAction. Note: HotKey also made an "Application preference" from a "Database preference". */ if (m_intValues[HotKey] > 0 && m_intValues[HotKey] <= 3) { m_boolValues[HotKeyEnabled] = false; m_intValues[DoubleClickAction] = m_intValues[HotKey]; m_intValues[HotKey] = 0; m_app->WriteProfileInt(PWS_REG_OPTIONS, m_bool_prefs[HotKeyEnabled].name, 0); m_app->WriteProfileInt(PWS_REG_OPTIONS, m_int_prefs[HotKey].name, 0); m_app->WriteProfileInt(PWS_REG_OPTIONS, m_int_prefs[DoubleClickAction].name, m_intValues[DoubleClickAction]); } if (m_intValues[DoubleClickAction] > 3) { m_intValues[DoubleClickAction] = 1; m_app->WriteProfileInt(PWS_REG_OPTIONS, m_int_prefs[DoubleClickAction].name, 1); } // End of "defensive" code } bool PWSprefs::GetPref(BoolPrefs pref_enum) const { return m_bool_prefs[pref_enum].isPersistent ? m_boolValues[pref_enum] : GetBoolPref(m_bool_prefs[pref_enum].name, m_bool_prefs[pref_enum].defVal); } bool PWSprefs::GetBoolPref(const CMyString &name, bool defVal) const { return m_app->GetProfileInt(PWS_REG_OPTIONS, name, defVal) != 0; } unsigned int PWSprefs::GetPref(IntPrefs pref_enum) const { return m_int_prefs[pref_enum].isPersistent ? m_intValues[pref_enum] : GetIntPref(m_int_prefs[pref_enum].name, m_int_prefs[pref_enum].defVal); } unsigned int PWSprefs::GetPref(IntPrefs pref_enum, unsigned int defVal) const { if (m_int_prefs[pref_enum].isPersistent) return m_intValues[pref_enum] == (unsigned int)-1 ? defVal : m_intValues[pref_enum]; else return GetIntPref(m_int_prefs[pref_enum].name, defVal); } unsigned int PWSprefs::GetIntPref(const CMyString &name, unsigned int defVal) const { return m_app->GetProfileInt(PWS_REG_OPTIONS, name, defVal); } CMyString PWSprefs::GetPref(StringPrefs pref_enum) const { return m_string_prefs[pref_enum].isPersistent ? m_stringValues[pref_enum] : GetStringPref(m_string_prefs[pref_enum].name, m_string_prefs[pref_enum].defVal); } CMyString PWSprefs::GetStringPref(const CMyString &name, const CMyString &defVal) const { CMyString retval = m_app->GetProfileString(PWS_REG_OPTIONS, name, defVal); return retval; } void PWSprefs::GetPrefRect(long &top, long &bottom, long &left, long &right) const { // this is never store in db top = m_app->GetProfileInt(PWS_REG_POSITION, _T("top"), -1); bottom = m_app->GetProfileInt(PWS_REG_POSITION, _T("bottom"), -1); left = m_app->GetProfileInt(PWS_REG_POSITION, _T("left"), -1); right = m_app->GetProfileInt(PWS_REG_POSITION, _T("right"), -1); } void PWSprefs::SetPref(BoolPrefs pref_enum, bool value) { m_prefs_changed |= (m_boolValues[pref_enum] != value && m_bool_prefs[pref_enum].isPersistent); m_boolValues[pref_enum] = value; SetPref(m_bool_prefs[pref_enum].name, value); } void PWSprefs::SetPref(const CMyString &name, bool val) { m_app->WriteProfileInt(PWS_REG_OPTIONS, name, val ? 1 : 0); } void PWSprefs::SetPref(IntPrefs pref_enum, unsigned int value) { m_prefs_changed |= (m_intValues[pref_enum] != value && m_int_prefs[pref_enum].isPersistent); m_intValues[pref_enum] = value; SetPref(m_int_prefs[pref_enum].name, value); } void PWSprefs::SetPref(const CMyString &name, unsigned int val) { m_app->WriteProfileInt(PWS_REG_OPTIONS, name, val); } void PWSprefs::SetPref(StringPrefs pref_enum, const CMyString &value) { m_prefs_changed |= (m_stringValues[pref_enum] != value && m_string_prefs[pref_enum].isPersistent); m_stringValues[pref_enum] = value; SetPref(m_string_prefs[pref_enum].name, value); } void PWSprefs::SetPref(const CMyString &name, const CMyString &val) { m_app->WriteProfileString(PWS_REG_OPTIONS, name, val); } void PWSprefs::SetPrefRect(long top, long bottom, long left, long right) { m_app->WriteProfileInt(PWS_REG_POSITION, _T("top"), top); m_app->WriteProfileInt(PWS_REG_POSITION, _T("bottom"), bottom); m_app->WriteProfileInt(PWS_REG_POSITION, _T("left"), left); m_app->WriteProfileInt(PWS_REG_POSITION, _T("right"), right); } CMyString PWSprefs::Store() { /* * Create a string of values that are (1) different from the defaults, && (2) are isPersistent * String is of the form "X nn vv X nn vv..." Where X=[BIS] for binary, integer and string, resp., * nn is the numeric value of the enum, and vv is the value, {1.0} for bool, unsigned integer * for int, and quoted string for String. */ CMyString retval(_T("")); ostrstream os; int i; for (i = 0; i < NumBoolPrefs; i++) if (m_boolValues[i] != m_bool_prefs[i].defVal && m_bool_prefs[i].isPersistent) os << "B " << i << ' ' << (m_boolValues[i] ? 1 : 0) << ' '; for (i = 0; i < NumIntPrefs; i++) if (m_intValues[i] != m_int_prefs[i].defVal && m_int_prefs[i].isPersistent) os << "I " << i << ' ' << m_intValues[i] << ' '; for (i = 0; i < NumStringPrefs; i++) if (m_stringValues[i] != m_string_prefs[i].defVal && m_string_prefs[i].isPersistent) os << "S " << i << " \"" << LPCTSTR(m_stringValues[i]) << "\" "; os << ends; retval = os.str(); delete[] os.str(); // reports memory leaks in spite of this! return retval; } void PWSprefs::Load(const CMyString &prefString) { // parse prefString, updating current values istrstream is(prefString); char type; int index, ival; unsigned int iuval; CMyString msval; const int N = prefString.GetLength(); // safe upper limit on string size char *buf = new char[N]; while (is) { is >> type >> index; switch (type) { case 'B': // Need to get value - even of not understood or wanted is >> ival; // forward compatibility and check whether still in DB if (index < NumBoolPrefs && m_bool_prefs[index].isPersistent) { ASSERT(ival == 0 || ival == 1); m_boolValues[index] = (ival != 0); } break; case 'I': // Need to get value - even of not understood or wanted is >> iuval; // forward compatibility and check whether still in DB if (index < NumIntPrefs && m_int_prefs[index].isPersistent) m_intValues[index] = iuval; break; case 'S': // Need to get value - even of not understood or wanted is.ignore(2, '\"'); // skip over space and leading " is.get(buf, N, '\"'); // get string value // forward compatibility and check whether still in DB if (index < NumStringPrefs && m_string_prefs[index].isPersistent) { msval= buf; m_stringValues[index] = msval; } break; default: continue; // forward compatibility (also last space) } // switch } // while delete[] buf; }
Make sure we only used DB pref. if still DB related Also need to input unused/unkown value to keep in step
Make sure we only used DB pref. if still DB related Also need to input unused/unkown value to keep in step git-svn-id: 6fc9ba494899942902f7488ac93c4c58960a7ec4@998 1f79f812-37fb-46fe-a122-30589dd2bf55
C++
artistic-2.0
sorinAche23/Psafe,ronys/pwsafe-test,Sp1l/pwsafe,sorinAche23/Psafe,Sp1l/pwsafe,gpmidi/pwsafe,sorinAche23/Psafe,sorinAche23/Psafe,ronys/pwsafe-test,Sp1l/pwsafe,Sp1l/pwsafe,Sp1l/pwsafe,ronys/pwsafe-test,gpmidi/pwsafe,Sp1l/pwsafe,gpmidi/pwsafe,gpmidi/pwsafe,gpmidi/pwsafe,sorinAche23/Psafe,ronys/pwsafe-test,ronys/pwsafe-test,ronys/pwsafe-test,sorinAche23/Psafe,gpmidi/pwsafe,ronys/pwsafe-test,Sp1l/pwsafe,sorinAche23/Psafe,Sp1l/pwsafe,sorinAche23/Psafe,ronys/pwsafe-test,gpmidi/pwsafe,gpmidi/pwsafe
e139fb6d7740751321527ce2c6f133c52b21b338
GitGud/GitGud/ImporterTexture.cpp
GitGud/GitGud/ImporterTexture.cpp
#include "ImporterTexture.h" #include "App.h" #include "M_FileSystem.h" #include "M_ResourceManager.h" #include "ResourceTexture.h" #include <il.h> #include <ilu.h> #include <ilut.h> ImporterTexture::ImporterTexture() { _LOG(LOG_INFO, "Texture importer: Created."); ilInit(); iluInit(); ilutInit(); ilutRenderer(ILUT_OPENGL); ILuint devilError = ilGetError(); if (devilError != IL_NO_ERROR) { _LOG(LOG_ERROR, "Error while Devil Init: %s\n", iluErrorString(devilError)); } } ImporterTexture::~ImporterTexture() { ilShutDown(); } bool ImporterTexture::Import(Path originalFile, Path & exportedFile, UID & resUID) { bool ret = false; if (originalFile.Empty()) return ret; char* buffer = nullptr; uint size = app->fs->Load(originalFile.GetFullPath(), &buffer); if (buffer && size > 0) ret = ImportBuff(buffer, size, exportedFile, resUID); RELEASE_ARRAY(buffer); if (!ret) _LOG(LOG_WARN, "Could not import texture %s.", originalFile.GetFullPath()); return ret; } bool ImporterTexture::ImportBuff(const void* buffer, uint size, Path& exportedFile, UID& resUID) { bool ret = false; /**First load the image */ //1-Gen the image and bind it ILuint image; ilGenImages(1, &image); ilBindImage(image); //2-Load the image from buffer if (ilLoadL(IL_TYPE_UNKNOWN, buffer, size)) { ilEnable(IL_FILE_OVERWRITE); ILuint _size; ILubyte* data = nullptr; //3-Set format (DDS, DDS compression) ilSetInteger(IL_DXTC_FORMAT, IL_DXT5); //4-Get size _size = ilSaveL(IL_DDS, nullptr, 0); if (_size > 0) { //5-If size is more than 0 create the image buffer data = new ILubyte[_size]; //6-Save the image with the correct format and save it with file system if (ilSaveL(IL_DDS, data, _size) > 0) { //Save it FS resUID = app->resources->GetNewUID(); exportedFile.Set(TEXTURE_SAVE_PATH, std::to_string(resUID).c_str(), TEXTURE_EXTENSION); if (app->fs->Save(exportedFile.GetFullPath(), (const char*)data, _size) == _size) ret = true; else _LOG(LOG_WARN, "Error importing texture."); } //7-Release the image buffer to avoid memory leaks RELEASE_ARRAY(data); } //8-Finally if the image was loaded destroy the image to avoid more memory leaks ilDeleteImages(1, &image); } return ret; } bool ImporterTexture::LoadResource(Resource * resource) { return false; } #define CHECKERS_WIDHT 64 #define CHECKERS_HEIGHT 64 bool ImporterTexture::LoadChequers(ResourceTexture * res) { if (!res)return false; res->originalFile.SetFileName("*checkers*"); res->exportedFile.SetFileName("*checkers*"); res->name = "Checkers"; GLubyte checkImage[CHECKERS_WIDHT][CHECKERS_HEIGHT][4]; for (int i = 0; i < CHECKERS_HEIGHT; ++i) { for (int j = 0; j < CHECKERS_WIDHT; ++j) { int c = ((((i & 0x8) == 0) ^ (((j & 0x8)) == 0))) * 255; checkImage[i][j][0] = (GLubyte)c; checkImage[i][j][1] = (GLubyte)c; checkImage[i][j][2] = (GLubyte)c; checkImage[i][j][3] = (GLubyte)255; } } uint imageName = 0; glPixelStorei(GL_UNPACK_ALIGNMENT, 1); glGenTextures(1, &imageName); glBindTexture(GL_TEXTURE_2D, imageName); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, CHECKERS_WIDHT, CHECKERS_HEIGHT, 0, GL_RGBA, GL_UNSIGNED_BYTE, checkImage); res->width = CHECKERS_WIDHT; res->height = CHECKERS_HEIGHT; res->bpp = 1; res->depth = 4; res->mips = 0; res->bytes = sizeof(GLubyte) * CHECKERS_WIDHT * CHECKERS_HEIGHT * 4; res->format = ResourceTexture::RGBA; res->texID = imageName; glBindTexture(GL_TEXTURE_2D, 0); return true; }
#include "ImporterTexture.h" #include "App.h" #include "M_FileSystem.h" #include "M_ResourceManager.h" #include "ResourceTexture.h" #include <il.h> #include <ilu.h> #include <ilut.h> ImporterTexture::ImporterTexture() { _LOG(LOG_INFO, "Texture importer: Created."); ilInit(); iluInit(); ilutInit(); ilutRenderer(ILUT_OPENGL); ILuint devilError = ilGetError(); if (devilError != IL_NO_ERROR) { _LOG(LOG_ERROR, "Error while Devil Init: %s\n", iluErrorString(devilError)); } } ImporterTexture::~ImporterTexture() { ilShutDown(); } bool ImporterTexture::Import(Path originalFile, Path & exportedFile, UID & resUID) { bool ret = false; if (originalFile.Empty()) return ret; char* buffer = nullptr; uint size = app->fs->Load(originalFile.GetFullPath(), &buffer); if (buffer && size > 0) ret = ImportBuff(buffer, size, exportedFile, resUID); RELEASE_ARRAY(buffer); if (!ret) _LOG(LOG_WARN, "Could not import texture %s.", originalFile.GetFullPath()); return ret; } bool ImporterTexture::ImportBuff(const void* buffer, uint size, Path& exportedFile, UID& resUID) { bool ret = false; /**First load the image */ //1-Gen the image and bind it ILuint image; ilGenImages(1, &image); ilBindImage(image); //2-Load the image from buffer if (ilLoadL(IL_TYPE_UNKNOWN, buffer, size)) { ilEnable(IL_FILE_OVERWRITE); ILuint _size; ILubyte* data = nullptr; //3-Set format (DDS, DDS compression) ilSetInteger(IL_DXTC_FORMAT, IL_DXT5); //4-Get size _size = ilSaveL(IL_DDS, nullptr, 0); if (_size > 0) { //5-If size is more than 0 create the image buffer data = new ILubyte[_size]; //6-Save the image with the correct format and save it with file system if (ilSaveL(IL_DDS, data, _size) > 0) { //Save it FS resUID = app->resources->GetNewUID(); exportedFile.Set(TEXTURE_SAVE_PATH, std::to_string(resUID).c_str(), TEXTURE_EXTENSION); if (app->fs->Save(exportedFile.GetFullPath(), (const char*)data, _size) == _size) ret = true; else _LOG(LOG_WARN, "Error importing texture."); } //7-Release the image buffer to avoid memory leaks RELEASE_ARRAY(data); } //8-Finally if the image was loaded destroy the image to avoid more memory leaks ilDeleteImages(1, &image); } return ret; } bool ImporterTexture::LoadResource(Resource * resource) { bool ret = false; if (!resource || resource->GetType() != RES_TEXTURE || resource->exportedFile.Empty()) return ret; ResourceTexture* res = (ResourceTexture*)resource; char* data = nullptr; uint size = app->fs->Load(res->GetExportedFileFullPath(), &data); if (data && size > 0) { ILuint image = 0; ilGenImages(1, &image); ilBindImage(image); if (ilLoadL(IL_DDS, (const void*)data, size)) { ILinfo info; iluGetImageInfo(&info); res->width = info.Width; res->height = info.Height; res->bpp = info.Bpp; res->depth = info.Depth; res->mips = info.NumMips; res->bytes = info.SizeOfData; switch (info.Format) { case IL_COLOUR_INDEX: res->format = ResourceTexture::COLOR_INDEX; break; case IL_RGB: res->format = ResourceTexture::RGB; break; case IL_RGBA: res->format = ResourceTexture::RGBA; break; case IL_BGR: res->format = ResourceTexture::BGR; break; case IL_BGRA: res->format = ResourceTexture::BGRA; break; case IL_LUMINANCE: res->format = ResourceTexture::LUMINANCE; break; default: res->format = ResourceTexture::UNKNOWN; break; } res->texID = ilutGLBindTexImage(); ilDeleteImages(1, &image); ret = true; } else { _LOG(LOG_ERROR, "Devil could not load the texture resource [%s] from file [%s].", res->GetResourceName(), res->GetExportedFile()); } } else { _LOG(LOG_ERROR, "Could not load texture resource [%s] from file [%s].", res->GetResourceName(), res->GetExportedFile()); } RELEASE_ARRAY(data); return ret; } #define CHECKERS_WIDHT 64 #define CHECKERS_HEIGHT 64 bool ImporterTexture::LoadChequers(ResourceTexture * res) { if (!res)return false; res->originalFile.SetFileName("*checkers*"); res->exportedFile.SetFileName("*checkers*"); res->name = "Checkers"; GLubyte checkImage[CHECKERS_WIDHT][CHECKERS_HEIGHT][4]; for (int i = 0; i < CHECKERS_HEIGHT; ++i) { for (int j = 0; j < CHECKERS_WIDHT; ++j) { int c = ((((i & 0x8) == 0) ^ (((j & 0x8)) == 0))) * 255; checkImage[i][j][0] = (GLubyte)c; checkImage[i][j][1] = (GLubyte)c; checkImage[i][j][2] = (GLubyte)c; checkImage[i][j][3] = (GLubyte)255; } } uint imageName = 0; glPixelStorei(GL_UNPACK_ALIGNMENT, 1); glGenTextures(1, &imageName); glBindTexture(GL_TEXTURE_2D, imageName); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, CHECKERS_WIDHT, CHECKERS_HEIGHT, 0, GL_RGBA, GL_UNSIGNED_BYTE, checkImage); res->width = CHECKERS_WIDHT; res->height = CHECKERS_HEIGHT; res->bpp = 1; res->depth = 4; res->mips = 0; res->bytes = sizeof(GLubyte) * CHECKERS_WIDHT * CHECKERS_HEIGHT * 4; res->format = ResourceTexture::RGBA; res->texID = imageName; glBindTexture(GL_TEXTURE_2D, 0); return true; }
Load texture resource
Load texture resource
C++
apache-2.0
Josef212/GitGud-Engine,Josef212/GitGud-Engine
5f58823331beb0cf823e7ac8f165797210fcde3e
cpp/fessa_detail.hpp
cpp/fessa_detail.hpp
// Fair Exponential Smoothing with Small Alpha by Juha Reunanen, 2015 #ifndef FESSA_ALPHA #define FESSA_ALPHA #include <limits> #include <assert.h> namespace fessa { namespace detail { // A is for the calculations; it must be floating-point // T is for time; essentially integer, need not be very wide template <typename A = double, typename T = unsigned short> class Alpha { public: Alpha(A baseAlpha, T t = 0) : baseAlpha(baseAlpha), t(t), a(1), d(0) { assert(baseAlpha > 0 && baseAlpha <= 1); assert(t >= 0 && t < std::numeric_limits<T>::max()); for (T tau = 0; tau <= t; ++tau) { d += a; a = a * (1 - baseAlpha); } } Alpha getNext() const { if (t < std::numeric_limits<A>::max()) { return Alpha(baseAlpha, t + 1, a * (1 - baseAlpha), d + a); } else { return *this; } } A getAlpha() const { return 1 / d; } A getBaseAlpha() const { return baseAlpha; } private: Alpha(A baseAlpha, T t, A a, A d) : baseAlpha(baseAlpha), t(t), a(a), d(d) {} A baseAlpha; T t; A a; A d; }; } } #endif // FESSA_ALPHA
// Fair Exponential Smoothing with Small Alpha by Juha Reunanen, 2015 #ifndef FESSA_ALPHA #define FESSA_ALPHA #include <limits> #include <assert.h> namespace fessa { namespace detail { // A is for the calculations; it must be floating-point // T is for time; essentially integer, need not be very wide template <typename A = double, typename T = unsigned short> class Alpha { public: Alpha(A baseAlpha, T t = 0) : baseAlpha(baseAlpha), t(t), a(1), d(0) { assert(baseAlpha > 0 && baseAlpha <= 1); assert(t >= 0 && t < std::numeric_limits<T>::max()); for (T tau = 0; tau <= t; ++tau) { d += a; a = a * (1 - baseAlpha); } } Alpha getNext() const { if (t < std::numeric_limits<T>::max()) { return Alpha(baseAlpha, t + 1, a * (1 - baseAlpha), d + a); } else { return *this; } } A getAlpha() const { return 1 / d; } A getBaseAlpha() const { return baseAlpha; } private: Alpha(A baseAlpha, T t, A a, A d) : baseAlpha(baseAlpha), t(t), a(a), d(d) {} A baseAlpha; T t; A a; A d; }; } } #endif // FESSA_ALPHA
Fix comparison
Fix comparison
C++
mit
reunanen/fessa
e2e497dc283cf1a33af2822f86ad4fdee620d9b5
cpp/jami/namedir.cpp
cpp/jami/namedir.cpp
// Vsevolod Ivanov #include <string> #include <iostream> #include <thread> #include "dring/dring.h" #include "dring/callmanager_interface.h" #include "dring/configurationmanager_interface.h" #include "dring/presencemanager_interface.h" // jamidht/namedirectory.h enum class Response : int { found = 0, invalidResponse, notFound, error }; enum class RegistrationResponse : int { success = 0, invalidName, alreadyTaken, error, incompleteRequest, signatureVerificationFailed }; int main(int argc, char * argv[]) { if (argc < 2){ printf("./run <lookup-name>\n"); return 1; } const std::string ns = "ns.jami.net"; using std::bind; using DRing::exportable_callback; using DRing::ConfigurationSignal; using SharedCallback = std::shared_ptr<DRing::CallbackWrapperBase>; auto registeredNameFoundCb = exportable_callback<ConfigurationSignal::RegisteredNameFound>([&] (const std::string& account_id, int state, const std::string& address, const std::string& name){ printf("\n=====================================================\n"); printf("account_id: %s state: %i name: %s\naddress: %s\n", account_id.c_str(), state, name.c_str(), address.c_str() ); printf("=====================================================\n"); }); const std::map<std::string, SharedCallback> configEvHandlers = { exportable_callback<ConfigurationSignal::IncomingAccountMessage>([] (const std::string& accountID, const std::string& from, const std::map<std::string, std::string>& payloads){ }), registeredNameFoundCb, }; if (!DRing::init(DRing::InitFlag(DRing::DRING_FLAG_DEBUG | DRing::DRING_FLAG_CONSOLE_LOG))) return -1; registerSignalHandlers(configEvHandlers); if (!DRing::start()) return -1; DRing::lookupName(""/*account*/, ns, argv[1]); while (true){ std::this_thread::sleep_for(std::chrono::seconds(1)); } return 0; }
// Vsevolod Ivanov #include <string> #include <iostream> #include <thread> #include "dring/dring.h" #include "dring/callmanager_interface.h" #include "dring/configurationmanager_interface.h" #include "dring/presencemanager_interface.h" // jamidht/namedirectory.h enum class Response : int { found = 0, invalidResponse, notFound, error }; enum class RegistrationResponse : int { success = 0, invalidName, alreadyTaken, error, incompleteRequest, signatureVerificationFailed }; int main(int argc, char * argv[]) { if (argc < 4){ printf("./run <address> <account> <password> <username>\n"); return 1; } auto address = argv[1]; auto account = argv[2]; auto password = argv[3]; auto username = argv[4]; const std::string ns = "ns.jami.net"; using std::bind; using DRing::exportable_callback; using DRing::ConfigurationSignal; using SharedCallback = std::shared_ptr<DRing::CallbackWrapperBase>; // registerName auto nameRegistrationEndedCb = exportable_callback<ConfigurationSignal::NameRegistrationEnded>([&] (const std::string& account_id, int state, const std::string& name){ printf("\n============== name register ======================\n"); printf("account_id: %s state: %i name: %s\n", account_id.c_str(), state, name.c_str() ); printf("=====================================================\n"); }); // lookupName & loopkupAddress auto registeredNameFoundCb = exportable_callback<ConfigurationSignal::RegisteredNameFound>([&] (const std::string& account_id, int state, const std::string& address, const std::string& name){ printf("\n================== lookup ended ===================\n"); printf("account_id: %s state: %i name: %s\naddress: %s\n", account_id.c_str(), state, name.c_str(), address.c_str() ); printf("=====================================================\n"); }); if (!DRing::init(DRing::InitFlag(DRing::DRING_FLAG_DEBUG | DRing::DRING_FLAG_CONSOLE_LOG))) return 1; const std::map<std::string, SharedCallback> configEvHandlers = { nameRegistrationEndedCb, registeredNameFoundCb }; registerSignalHandlers(configEvHandlers); if (!DRing::start()) return 1; // 0: lookup address DRing::lookupAddress(""/*account*/, ns, address); // 1: register an existing account printf("RegisterName: %s", DRing::registerName(account, password, username) ? "OK" : "FAIL"); // 2: look it up DRing::lookupName(account, ns, username); while (true){ std::this_thread::sleep_for(std::chrono::seconds(1)); } return 0; }
add register name to namedir
cpp/jami: add register name to namedir
C++
mit
sevaivanov/various,sevaivanov/various,sevaivanov/various,sevaivanov/various,sevaivanov/various,sevaivanov/various
6d162480ee8be3b393dd411042fc11dda7e5df2b
cpp/ztracker_tool.cc
cpp/ztracker_tool.cc
/** \file ztracker_tool.cc \brief A utility to inspeect and manipulate our Zotero tracker database. \author Dr. Johannes Ruscheinski \copyright 2018 Universitätsbibliothek Tübingen This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <iostream> #include "TimeUtil.h" #include "util.h" #include "RegexMatcher.h" #include "Zotero.h" namespace { void Usage() { std::cerr << "Usage: " << ::progname << " command\n" << " Possible commands are:\n" << " clear [url|zulu_timestamp] => if no arguments are provided, this empties the entire database\n" << " if a URL has been provided, just the entry with key \"url\"\n" << " will be erased, and if a Zulu (ISO 8601) timestamp has been\n" << " provided, all entries that are not newer are erased.\n" << " insert url [optional_message] => inserts or replaces the entry for \"url\".\n" << " lookup url => displays the timestamp and, if found, the optional message\n" << " for this URL.\n" << " list [pcre] => list either all entries in the database or, if the PCRE has\n" << " been provided, ony the ones with matching URL\'s.\n\n"; std::exit(EXIT_FAILURE); } void Clear(Zotero::DownloadTracker * const download_tracker, const std::string &url_or_zulu_timestamp) { time_t timestamp; std::string err_msg; if (url_or_zulu_timestamp.empty()) { std::cout << "Deleted " << download_tracker->clear() << " entries from the tracker database.\n"; } else if (TimeUtil::Iso8601StringToTimeT(url_or_zulu_timestamp, &timestamp, &err_msg)) std::cout << "Deleted " << download_tracker->clear(timestamp) << " entries from the tracker database.\n"; else { // Assume url_or_zulu_timestamp contains a URL. if (download_tracker->clearEntry(url_or_zulu_timestamp)) std::cout << "Deleted one entry from the tracker database.\n"; else std::cerr << "Entry for URL \"" << url_or_zulu_timestamp << "\" could not be deleted!\n"; } } void Insert(Zotero::DownloadTracker * const download_tracker, const std::string &url, const std::string &optional_message) { download_tracker->recordDownload(url, optional_message); std::cout << "Create an entry for the URL \"" << url << "\".\n"; } void Lookup(Zotero::DownloadTracker * const download_tracker, const std::string &url) { time_t timestamp; std::string optional_message; if (not download_tracker->lookup(url, &timestamp, &optional_message)) std::cerr << "Entry for URL \"" << url << "\" could not be found!\n"; else { if (optional_message.empty()) std::cout << url << ": " << TimeUtil::TimeTToLocalTimeString(timestamp) << '\n'; else std::cout << url << ": " << TimeUtil::TimeTToLocalTimeString(timestamp) << " (" << optional_message << ")\n"; } } void List(Zotero::DownloadTracker * const download_tracker, const std::string &pcre) { RegexMatcher *matcher(RegexMatcher::FactoryOrDie(pcre)); for (const auto &entry : *download_tracker) { const std::string &url(entry.getURL()); if (not matcher->matched(url)) continue; std::cout << url << ": " << TimeUtil::TimeTToLocalTimeString(entry.getRecodingTime()); const std::string &optional_message(entry.getOptionalMessage()); if (not optional_message.empty()) std::cout << ", " << optional_message; std::cout << '\n'; } } } // unnamed namespace int main(int argc, char *argv[]) { ::progname = argv[0]; if (argc < 2 or argc > 4) Usage(); try { Zotero::DownloadTracker download_tracker; if (std::strcmp(argv[1], "clear")) { if (argc > 3) LOG_ERROR("clear takes 0 or 1 arguments!"); Clear(&download_tracker, argc == 2 ? "" : argv[2]); } else if (std::strcmp(argv[1], "insert")) { if (argc < 3 or argc > 4) LOG_ERROR("insert takes 1 or 2 arguments!"); Insert(&download_tracker, argv[2], argc == 3 ? "" : argv[3]); } else if (std::strcmp(argv[1], "lookup")) { if (argc != 3) LOG_ERROR("lookup takes 1 argument!"); Lookup(&download_tracker, argv[2]); } else if (std::strcmp(argv[1], "list")) { if (argc > 3) LOG_ERROR("list takes 0 or 1 arguments!"); List(&download_tracker, argc == 2 ? ".*" : argv[2]); } else LOG_ERROR("unknown command: \"" + std::string(argv[1]) + "\"!"); } catch (const std::exception &x) { LOG_ERROR("caught exception: " + std::string(x.what())); } }
/** \file ztracker_tool.cc \brief A utility to inspect and manipulate our Zotero tracker database. \author Dr. Johannes Ruscheinski \copyright 2018 Universitätsbibliothek Tübingen This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <iostream> #include "TimeUtil.h" #include "util.h" #include "RegexMatcher.h" #include "Zotero.h" namespace { void Usage() { std::cerr << "Usage: " << ::progname << " command\n" << " Possible commands are:\n" << " clear [url|zulu_timestamp] => if no arguments are provided, this empties the entire database\n" << " if a URL has been provided, just the entry with key \"url\"\n" << " will be erased, and if a Zulu (ISO 8601) timestamp has been\n" << " provided, all entries that are not newer are erased.\n" << " insert url [optional_message] => inserts or replaces the entry for \"url\".\n" << " lookup url => displays the timestamp and, if found, the optional message\n" << " for this URL.\n" << " list [pcre] => list either all entries in the database or, if the PCRE has\n" << " been provided, ony the ones with matching URL\'s.\n\n"; std::exit(EXIT_FAILURE); } void Clear(Zotero::DownloadTracker * const download_tracker, const std::string &url_or_zulu_timestamp) { time_t timestamp; std::string err_msg; if (url_or_zulu_timestamp.empty()) { std::cout << "Deleted " << download_tracker->clear() << " entries from the tracker database.\n"; } else if (TimeUtil::Iso8601StringToTimeT(url_or_zulu_timestamp, &timestamp, &err_msg)) std::cout << "Deleted " << download_tracker->clear(timestamp) << " entries from the tracker database.\n"; else { // Assume url_or_zulu_timestamp contains a URL. if (download_tracker->clearEntry(url_or_zulu_timestamp)) std::cout << "Deleted one entry from the tracker database.\n"; else std::cerr << "Entry for URL \"" << url_or_zulu_timestamp << "\" could not be deleted!\n"; } } void Insert(Zotero::DownloadTracker * const download_tracker, const std::string &url, const std::string &optional_message) { download_tracker->recordDownload(url, optional_message); std::cout << "Create an entry for the URL \"" << url << "\".\n"; } void Lookup(Zotero::DownloadTracker * const download_tracker, const std::string &url) { time_t timestamp; std::string optional_message; if (not download_tracker->lookup(url, &timestamp, &optional_message)) std::cerr << "Entry for URL \"" << url << "\" could not be found!\n"; else { if (optional_message.empty()) std::cout << url << ": " << TimeUtil::TimeTToLocalTimeString(timestamp) << '\n'; else std::cout << url << ": " << TimeUtil::TimeTToLocalTimeString(timestamp) << " (" << optional_message << ")\n"; } } void List(Zotero::DownloadTracker * const download_tracker, const std::string &pcre) { RegexMatcher *matcher(RegexMatcher::FactoryOrDie(pcre)); for (const auto &entry : *download_tracker) { const std::string &url(entry.getURL()); if (not matcher->matched(url)) continue; std::cout << url << ": " << TimeUtil::TimeTToLocalTimeString(entry.getRecodingTime()); const std::string &optional_message(entry.getOptionalMessage()); if (not optional_message.empty()) std::cout << ", " << optional_message; std::cout << '\n'; } } } // unnamed namespace int main(int argc, char *argv[]) { ::progname = argv[0]; if (argc < 2 or argc > 4) Usage(); try { Zotero::DownloadTracker download_tracker; if (std::strcmp(argv[1], "clear")) { if (argc > 3) LOG_ERROR("clear takes 0 or 1 arguments!"); Clear(&download_tracker, argc == 2 ? "" : argv[2]); } else if (std::strcmp(argv[1], "insert")) { if (argc < 3 or argc > 4) LOG_ERROR("insert takes 1 or 2 arguments!"); Insert(&download_tracker, argv[2], argc == 3 ? "" : argv[3]); } else if (std::strcmp(argv[1], "lookup")) { if (argc != 3) LOG_ERROR("lookup takes 1 argument!"); Lookup(&download_tracker, argv[2]); } else if (std::strcmp(argv[1], "list")) { if (argc > 3) LOG_ERROR("list takes 0 or 1 arguments!"); List(&download_tracker, argc == 2 ? ".*" : argv[2]); } else LOG_ERROR("unknown command: \"" + std::string(argv[1]) + "\"!"); } catch (const std::exception &x) { LOG_ERROR("caught exception: " + std::string(x.what())); } }
Update ztracker_tool.cc
Update ztracker_tool.cc
C++
agpl-3.0
ubtue/ub_tools,ubtue/ub_tools,ubtue/ub_tools,ubtue/ub_tools,ubtue/ub_tools,ubtue/ub_tools,ubtue/ub_tools,ubtue/ub_tools
6b25ef4839b2e5941fda7ba8c68b4ed251519f78
dune/stuff/la/container/eigen/sparse.hh
dune/stuff/la/container/eigen/sparse.hh
// This file is part of the dune-stuff project: // https://github.com/wwu-numerik/dune-stuff/ // Copyright holders: Rene Milk, Felix Schindler // License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) #ifndef DUNE_STUFF_LA_CONTAINER_EIGEN_SPARSE_HH #define DUNE_STUFF_LA_CONTAINER_EIGEN_SPARSE_HH #include <memory> #include <type_traits> #include <vector> #include <boost/numeric/conversion/cast.hpp> #include <dune/stuff/common/disable_warnings.hh> # if HAVE_EIGEN # include <Eigen/SparseCore> # endif #include <dune/stuff/common/reenable_warnings.hh> #include <dune/common/typetraits.hh> #include <dune/stuff/aliases.hh> #include <dune/stuff/common/exceptions.hh> #include <dune/stuff/common/crtp.hh> #include <dune/stuff/common/float_cmp.hh> #include "dune/stuff/la/container/interfaces.hh" #include "dune/stuff/la/container/pattern.hh" #include "dense.hh" namespace Dune { namespace Stuff { namespace LA { // forwards template< class ScalarType > class EigenRowMajorSparseMatrix; class EigenMatrixInterfaceDynamic {}; #if HAVE_EIGEN namespace internal { /** * \brief Traits for EigenRowMajorSparseMatrix. */ template< class ScalarImp = double > class EigenRowMajorSparseMatrixTraits { public: typedef ScalarImp ScalarType; typedef EigenRowMajorSparseMatrix< ScalarType > derived_type; typedef typename ::Eigen::SparseMatrix< ScalarType, ::Eigen::RowMajor > BackendType; }; // class RowMajorSparseMatrixTraits } // namespace internal /** * \brief A sparse matrix implementation of the MatrixInterface with row major memory layout. */ template< class ScalarImp = double > class EigenRowMajorSparseMatrix : public MatrixInterface< internal::EigenRowMajorSparseMatrixTraits< ScalarImp >, ScalarImp > , public ProvidesBackend< internal::EigenRowMajorSparseMatrixTraits< ScalarImp > > { typedef EigenRowMajorSparseMatrix< ScalarImp > ThisType; typedef MatrixInterface< internal::EigenRowMajorSparseMatrixTraits< ScalarImp >,ScalarImp > MatrixInterfaceType; static_assert(!std::is_same< DUNE_STUFF_SSIZE_T, int >::value, "You have to manually disable the constructor below which uses DUNE_STUFF_SSIZE_T!"); public: typedef internal::EigenRowMajorSparseMatrixTraits< ScalarImp > Traits; typedef typename Traits::BackendType BackendType; typedef typename Traits::ScalarType ScalarType; private: typedef typename BackendType::Index EIGEN_size_t; public: /** * \brief This is the constructor of interest which creates a sparse matrix. */ EigenRowMajorSparseMatrix(const size_t rr, const size_t cc, const SparsityPatternDefault& pattern) { backend_ = std::make_shared< BackendType >(internal::boost_numeric_cast< EIGEN_size_t >(rr), internal::boost_numeric_cast< EIGEN_size_t >(cc)); if (rr > 0 && cc > 0) { if (size_t(pattern.size()) != rr) DUNE_THROW(Exceptions::shapes_do_not_match, "The size of the pattern (" << pattern.size() << ") does not match the number of rows of this (" << rr << ")!"); for (size_t row = 0; row < size_t(pattern.size()); ++row) { backend_->startVec(internal::boost_numeric_cast< EIGEN_size_t >(row)); const auto& columns = pattern.inner(row); for (auto& column : columns) { #ifndef NDEBUG if (column >= cc) DUNE_THROW(Exceptions::shapes_do_not_match, "The size of row " << row << " of the pattern does not match the number of columns of this (" << cc << ")!"); #endif // NDEBUG backend_->insertBackByOuterInner(internal::boost_numeric_cast< EIGEN_size_t >(row), internal::boost_numeric_cast< EIGEN_size_t >(column)); } // create entry (insertBackByOuterInner() can not handle empty rows) if (columns.size() == 0) backend_->insertBackByOuterInner(internal::boost_numeric_cast< EIGEN_size_t >(row), 0); } backend_->finalize(); backend_->makeCompressed(); } } // EigenRowMajorSparseMatrix(...) explicit EigenRowMajorSparseMatrix(const size_t rr = 0, const size_t cc = 0) { backend_ = std::make_shared<BackendType>(rr, cc); } /// This constructor is needed for the python bindings. explicit EigenRowMajorSparseMatrix(const DUNE_STUFF_SSIZE_T rr, const DUNE_STUFF_SSIZE_T cc = 0) : backend_(new BackendType(internal::boost_numeric_cast< EIGEN_size_t >(rr), internal::boost_numeric_cast< EIGEN_size_t >(cc))) {} explicit EigenRowMajorSparseMatrix(const int rr, const int cc = 0) : EigenRowMajorSparseMatrix(internal::boost_numeric_cast< EIGEN_size_t >(rr), internal::boost_numeric_cast< EIGEN_size_t >(cc)) {} EigenRowMajorSparseMatrix(const ThisType& other) : backend_(other.backend_) {} explicit EigenRowMajorSparseMatrix(const BackendType& other) : backend_(new BackendType(other)) {} /** * \note Takes ownership of backend_ptr in the sense that you must not delete it afterwards! */ explicit EigenRowMajorSparseMatrix(BackendType* backend_ptr) : backend_(backend_ptr) {} explicit EigenRowMajorSparseMatrix(std::shared_ptr< BackendType > backend_ptr) : backend_(backend_ptr) {} ThisType& operator=(const ThisType& other) { backend_ = other.backend_; return *this; } /** * \note Does a deep copy. */ ThisType& operator=(const BackendType& other) { backend_ = std::make_shared< BackendType >(other); return *this; } /// \name Required by the ProvidesBackend interface. /// \{ BackendType& backend() { ensure_uniqueness(); return *backend_; } const BackendType& backend() const { ensure_uniqueness(); return *backend_; } /// \} /// \name Required by ContainerInterface. /// \{ ThisType copy() const { return ThisType(*backend_); } void scal(const ScalarType& alpha) { backend() *= alpha; } // ... scal(...) void axpy(const ScalarType& alpha, const ThisType& xx) { if (!has_equal_shape(xx)) DUNE_THROW(Exceptions::shapes_do_not_match, "The shape of xx (" << xx.rows() << "x" << xx.cols() << ") does not match the shape of this (" << rows() << "x" << cols() << ")!"); const auto& xx_ref= *(xx.backend_); backend() += alpha * xx_ref; } // ... axpy(...) bool has_equal_shape(const ThisType& other) const { return (rows() == other.rows()) && (cols() == other.cols()); } /// \} /// \name Required by MatrixInterface. /// \{ inline size_t rows() const { return backend_->rows(); } inline size_t cols() const { return backend_->cols(); } template< class T1, class T2 > inline void mv(const EigenBaseVector< T1, ScalarType >& xx, EigenBaseVector< T2, ScalarType >& yy) const { yy.backend().transpose() = backend_->operator*(*xx.backend_); } void add_to_entry(const size_t ii, const size_t jj, const ScalarType& value) { assert(these_are_valid_indices(ii, jj)); backend().coeffRef(internal::boost_numeric_cast< EIGEN_size_t >(ii), internal::boost_numeric_cast< EIGEN_size_t >(jj)) += value; } void set_entry(const size_t ii, const size_t jj, const ScalarType& value) { assert(these_are_valid_indices(ii, jj)); backend().coeffRef(internal::boost_numeric_cast< EIGEN_size_t >(ii), internal::boost_numeric_cast< EIGEN_size_t >(jj)) = value; } ScalarType get_entry(const size_t ii, const size_t jj) const { assert(ii < rows()); assert(jj < cols()); return backend_->coeff(internal::boost_numeric_cast< EIGEN_size_t >(ii), internal::boost_numeric_cast< EIGEN_size_t >(jj)); } void clear_row(const size_t ii) { if (ii >= rows()) DUNE_THROW(Exceptions::index_out_of_range, "Given ii (" << ii << ") is larger than the rows of this (" << rows() << ")!"); backend().row(internal::boost_numeric_cast< EIGEN_size_t >(ii)) *= ScalarType(0); } void clear_col(const size_t jj) { if (jj >= cols()) DUNE_THROW(Exceptions::index_out_of_range, "Given jj (" << jj << ") is larger than the cols of this (" << cols() << ")!"); ensure_uniqueness(); for (size_t row = 0; internal::boost_numeric_cast< EIGEN_size_t >(row) < backend_->outerSize(); ++row) { for (typename BackendType::InnerIterator row_it(*backend_, internal::boost_numeric_cast< EIGEN_size_t >(row)); row_it; ++row_it) { const size_t col = row_it.col(); if (col == jj) { backend_->coeffRef(internal::boost_numeric_cast< EIGEN_size_t >(row), internal::boost_numeric_cast< EIGEN_size_t >(jj)) = ScalarType(0); break; } else if (col > jj) break; } } } // ... clear_col(...) void unit_row(const size_t ii) { if (ii >= cols()) DUNE_THROW(Exceptions::index_out_of_range, "Given ii (" << ii << ") is larger than the cols of this (" << cols() << ")!"); if (ii >= rows()) DUNE_THROW(Exceptions::index_out_of_range, "Given ii (" << ii << ") is larger than the rows of this (" << rows() << ")!"); if (!these_are_valid_indices(ii, ii)) DUNE_THROW(Exceptions::index_out_of_range, "Diagonal entry (" << ii << ", " << ii << ") is not contained in the sparsity pattern!"); backend().row(internal::boost_numeric_cast< EIGEN_size_t >(ii)) *= ScalarType(0); set_entry(ii, ii, ScalarType(1)); } // ... unit_row(...) void unit_col(const size_t jj) { if (jj >= cols()) DUNE_THROW(Exceptions::index_out_of_range, "Given jj (" << jj << ") is larger than the cols of this (" << cols() << ")!"); if (jj >= rows()) DUNE_THROW(Exceptions::index_out_of_range, "Given jj (" << jj << ") is larger than the rows of this (" << rows() << ")!"); ensure_uniqueness(); for (size_t row = 0; internal::boost_numeric_cast< EIGEN_size_t >(row) < backend_->outerSize(); ++row) { for (typename BackendType::InnerIterator row_it(*backend_, internal::boost_numeric_cast< EIGEN_size_t >(row)); row_it; ++row_it) { const size_t col = row_it.col(); if (col == jj) { if (col == row) backend_->coeffRef(internal::boost_numeric_cast< EIGEN_size_t >(row), internal::boost_numeric_cast< EIGEN_size_t >(col)) = ScalarType(1); else backend_->coeffRef(internal::boost_numeric_cast< EIGEN_size_t >(row), internal::boost_numeric_cast< EIGEN_size_t >(jj)) = ScalarType(0); break; } else if (col > jj) break; } } } // ... unit_col(...) bool valid() const { // serialize matrix (no copy done here) auto& non_const_ref = const_cast< BackendType& >(*backend_); return EigenMappedDenseVector< ScalarType >(non_const_ref.valuePtr(), non_const_ref.nonZeros()).valid(); } /// \} private: typedef typename BackendType::Index IndexType; bool these_are_valid_indices(const size_t ii, const size_t jj) const { if (ii >= rows()) return false; if (jj >= cols()) return false; for (size_t row = ii; internal::boost_numeric_cast< EIGEN_size_t >(row) < backend_->outerSize(); ++row) { for (typename BackendType::InnerIterator row_it(*backend_, internal::boost_numeric_cast< EIGEN_size_t >(row)); row_it; ++row_it) { const size_t col = row_it.col(); if ((ii == row) && (jj == col)) return true; else if ((row > ii) && (col > jj)) return false; } } return false; } // ... these_are_valid_indices(...) inline void ensure_uniqueness() const { if (!backend_.unique()) backend_ = std::make_shared< BackendType >(*backend_); } // ... ensure_uniqueness(...) mutable std::shared_ptr< BackendType > backend_; }; // class EigenRowMajorSparseMatrix #else // HAVE_EIGEN template< class ScalarImp > class EigenRowMajorSparseMatrix { static_assert(AlwaysFalse< ScalarImp >::value, "You are missing Eigen!"); }; #endif // HAVE_EIGEN } // namespace LA namespace Common { #if HAVE_EIGEN template< class T > struct MatrixAbstraction< LA::EigenRowMajorSparseMatrix< T > > : public LA::internal::MatrixAbstractionBase< LA::EigenRowMajorSparseMatrix< T > > {}; #endif // HAVE_EIGEN } // namespace Common } // namespace Stuff } // namespace Dune #endif // DUNE_STUFF_LA_CONTAINER_EIGEN_SPARSE_HH
// This file is part of the dune-stuff project: // https://github.com/wwu-numerik/dune-stuff/ // Copyright holders: Rene Milk, Felix Schindler // License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) #ifndef DUNE_STUFF_LA_CONTAINER_EIGEN_SPARSE_HH #define DUNE_STUFF_LA_CONTAINER_EIGEN_SPARSE_HH #include <memory> #include <type_traits> #include <vector> #include <boost/numeric/conversion/cast.hpp> #include <dune/stuff/common/disable_warnings.hh> # if HAVE_EIGEN # include <Eigen/SparseCore> # endif #include <dune/stuff/common/reenable_warnings.hh> #include <dune/common/typetraits.hh> #include <dune/stuff/aliases.hh> #include <dune/stuff/common/exceptions.hh> #include <dune/stuff/common/crtp.hh> #include <dune/stuff/common/float_cmp.hh> #include "dune/stuff/la/container/interfaces.hh" #include "dune/stuff/la/container/pattern.hh" #include "dense.hh" namespace Dune { namespace Stuff { namespace LA { // forwards template< class ScalarType > class EigenRowMajorSparseMatrix; class EigenMatrixInterfaceDynamic {}; #if HAVE_EIGEN namespace internal { /** * \brief Traits for EigenRowMajorSparseMatrix. */ template< class ScalarImp = double > class EigenRowMajorSparseMatrixTraits { public: typedef ScalarImp ScalarType; typedef EigenRowMajorSparseMatrix< ScalarType > derived_type; typedef typename ::Eigen::SparseMatrix< ScalarType, ::Eigen::RowMajor > BackendType; }; // class RowMajorSparseMatrixTraits } // namespace internal /** * \brief A sparse matrix implementation of the MatrixInterface with row major memory layout. */ template< class ScalarImp = double > class EigenRowMajorSparseMatrix : public MatrixInterface< internal::EigenRowMajorSparseMatrixTraits< ScalarImp >, ScalarImp > , public ProvidesBackend< internal::EigenRowMajorSparseMatrixTraits< ScalarImp > > { typedef EigenRowMajorSparseMatrix< ScalarImp > ThisType; typedef MatrixInterface< internal::EigenRowMajorSparseMatrixTraits< ScalarImp >,ScalarImp > MatrixInterfaceType; static_assert(!std::is_same< DUNE_STUFF_SSIZE_T, int >::value, "You have to manually disable the constructor below which uses DUNE_STUFF_SSIZE_T!"); public: typedef internal::EigenRowMajorSparseMatrixTraits< ScalarImp > Traits; typedef typename Traits::BackendType BackendType; typedef typename Traits::ScalarType ScalarType; private: typedef typename BackendType::Index EIGEN_size_t; public: /** * \brief This is the constructor of interest which creates a sparse matrix. */ EigenRowMajorSparseMatrix(const size_t rr, const size_t cc, const SparsityPatternDefault& pattern) { backend_ = std::make_shared< BackendType >(internal::boost_numeric_cast< EIGEN_size_t >(rr), internal::boost_numeric_cast< EIGEN_size_t >(cc)); if (rr > 0 && cc > 0) { if (size_t(pattern.size()) != rr) DUNE_THROW(Exceptions::shapes_do_not_match, "The size of the pattern (" << pattern.size() << ") does not match the number of rows of this (" << rr << ")!"); for (size_t row = 0; row < size_t(pattern.size()); ++row) { backend_->startVec(internal::boost_numeric_cast< EIGEN_size_t >(row)); const auto& columns = pattern.inner(row); for (auto& column : columns) { #ifndef NDEBUG if (column >= cc) DUNE_THROW(Exceptions::shapes_do_not_match, "The size of row " << row << " of the pattern does not match the number of columns of this (" << cc << ")!"); #endif // NDEBUG backend_->insertBackByOuterInner(internal::boost_numeric_cast< EIGEN_size_t >(row), internal::boost_numeric_cast< EIGEN_size_t >(column)); } // create entry (insertBackByOuterInner() can not handle empty rows) if (columns.size() == 0) backend_->insertBackByOuterInner(internal::boost_numeric_cast< EIGEN_size_t >(row), 0); } backend_->finalize(); backend_->makeCompressed(); } } // EigenRowMajorSparseMatrix(...) explicit EigenRowMajorSparseMatrix(const size_t rr = 0, const size_t cc = 0) { backend_ = std::make_shared<BackendType>(rr, cc); } /// This constructor is needed for the python bindings. explicit EigenRowMajorSparseMatrix(const DUNE_STUFF_SSIZE_T rr, const DUNE_STUFF_SSIZE_T cc = 0) : backend_(new BackendType(internal::boost_numeric_cast< EIGEN_size_t >(rr), internal::boost_numeric_cast< EIGEN_size_t >(cc))) {} explicit EigenRowMajorSparseMatrix(const int rr, const int cc = 0) : backend_(new BackendType(internal::boost_numeric_cast< EIGEN_size_t >(rr), internal::boost_numeric_cast< EIGEN_size_t >(cc))) {} EigenRowMajorSparseMatrix(const ThisType& other) : backend_(other.backend_) {} explicit EigenRowMajorSparseMatrix(const BackendType& other) : backend_(new BackendType(other)) {} /** * \note Takes ownership of backend_ptr in the sense that you must not delete it afterwards! */ explicit EigenRowMajorSparseMatrix(BackendType* backend_ptr) : backend_(backend_ptr) {} explicit EigenRowMajorSparseMatrix(std::shared_ptr< BackendType > backend_ptr) : backend_(backend_ptr) {} ThisType& operator=(const ThisType& other) { backend_ = other.backend_; return *this; } /** * \note Does a deep copy. */ ThisType& operator=(const BackendType& other) { backend_ = std::make_shared< BackendType >(other); return *this; } /// \name Required by the ProvidesBackend interface. /// \{ BackendType& backend() { ensure_uniqueness(); return *backend_; } const BackendType& backend() const { ensure_uniqueness(); return *backend_; } /// \} /// \name Required by ContainerInterface. /// \{ ThisType copy() const { return ThisType(*backend_); } void scal(const ScalarType& alpha) { backend() *= alpha; } // ... scal(...) void axpy(const ScalarType& alpha, const ThisType& xx) { if (!has_equal_shape(xx)) DUNE_THROW(Exceptions::shapes_do_not_match, "The shape of xx (" << xx.rows() << "x" << xx.cols() << ") does not match the shape of this (" << rows() << "x" << cols() << ")!"); const auto& xx_ref= *(xx.backend_); backend() += alpha * xx_ref; } // ... axpy(...) bool has_equal_shape(const ThisType& other) const { return (rows() == other.rows()) && (cols() == other.cols()); } /// \} /// \name Required by MatrixInterface. /// \{ inline size_t rows() const { return backend_->rows(); } inline size_t cols() const { return backend_->cols(); } template< class T1, class T2 > inline void mv(const EigenBaseVector< T1, ScalarType >& xx, EigenBaseVector< T2, ScalarType >& yy) const { yy.backend().transpose() = backend_->operator*(*xx.backend_); } void add_to_entry(const size_t ii, const size_t jj, const ScalarType& value) { assert(these_are_valid_indices(ii, jj)); backend().coeffRef(internal::boost_numeric_cast< EIGEN_size_t >(ii), internal::boost_numeric_cast< EIGEN_size_t >(jj)) += value; } void set_entry(const size_t ii, const size_t jj, const ScalarType& value) { assert(these_are_valid_indices(ii, jj)); backend().coeffRef(internal::boost_numeric_cast< EIGEN_size_t >(ii), internal::boost_numeric_cast< EIGEN_size_t >(jj)) = value; } ScalarType get_entry(const size_t ii, const size_t jj) const { assert(ii < rows()); assert(jj < cols()); return backend_->coeff(internal::boost_numeric_cast< EIGEN_size_t >(ii), internal::boost_numeric_cast< EIGEN_size_t >(jj)); } void clear_row(const size_t ii) { if (ii >= rows()) DUNE_THROW(Exceptions::index_out_of_range, "Given ii (" << ii << ") is larger than the rows of this (" << rows() << ")!"); backend().row(internal::boost_numeric_cast< EIGEN_size_t >(ii)) *= ScalarType(0); } void clear_col(const size_t jj) { if (jj >= cols()) DUNE_THROW(Exceptions::index_out_of_range, "Given jj (" << jj << ") is larger than the cols of this (" << cols() << ")!"); ensure_uniqueness(); for (size_t row = 0; internal::boost_numeric_cast< EIGEN_size_t >(row) < backend_->outerSize(); ++row) { for (typename BackendType::InnerIterator row_it(*backend_, internal::boost_numeric_cast< EIGEN_size_t >(row)); row_it; ++row_it) { const size_t col = row_it.col(); if (col == jj) { backend_->coeffRef(internal::boost_numeric_cast< EIGEN_size_t >(row), internal::boost_numeric_cast< EIGEN_size_t >(jj)) = ScalarType(0); break; } else if (col > jj) break; } } } // ... clear_col(...) void unit_row(const size_t ii) { if (ii >= cols()) DUNE_THROW(Exceptions::index_out_of_range, "Given ii (" << ii << ") is larger than the cols of this (" << cols() << ")!"); if (ii >= rows()) DUNE_THROW(Exceptions::index_out_of_range, "Given ii (" << ii << ") is larger than the rows of this (" << rows() << ")!"); if (!these_are_valid_indices(ii, ii)) DUNE_THROW(Exceptions::index_out_of_range, "Diagonal entry (" << ii << ", " << ii << ") is not contained in the sparsity pattern!"); backend().row(internal::boost_numeric_cast< EIGEN_size_t >(ii)) *= ScalarType(0); set_entry(ii, ii, ScalarType(1)); } // ... unit_row(...) void unit_col(const size_t jj) { if (jj >= cols()) DUNE_THROW(Exceptions::index_out_of_range, "Given jj (" << jj << ") is larger than the cols of this (" << cols() << ")!"); if (jj >= rows()) DUNE_THROW(Exceptions::index_out_of_range, "Given jj (" << jj << ") is larger than the rows of this (" << rows() << ")!"); ensure_uniqueness(); for (size_t row = 0; internal::boost_numeric_cast< EIGEN_size_t >(row) < backend_->outerSize(); ++row) { for (typename BackendType::InnerIterator row_it(*backend_, internal::boost_numeric_cast< EIGEN_size_t >(row)); row_it; ++row_it) { const size_t col = row_it.col(); if (col == jj) { if (col == row) backend_->coeffRef(internal::boost_numeric_cast< EIGEN_size_t >(row), internal::boost_numeric_cast< EIGEN_size_t >(col)) = ScalarType(1); else backend_->coeffRef(internal::boost_numeric_cast< EIGEN_size_t >(row), internal::boost_numeric_cast< EIGEN_size_t >(jj)) = ScalarType(0); break; } else if (col > jj) break; } } } // ... unit_col(...) bool valid() const { // serialize matrix (no copy done here) auto& non_const_ref = const_cast< BackendType& >(*backend_); return EigenMappedDenseVector< ScalarType >(non_const_ref.valuePtr(), non_const_ref.nonZeros()).valid(); } /// \} private: typedef typename BackendType::Index IndexType; bool these_are_valid_indices(const size_t ii, const size_t jj) const { if (ii >= rows()) return false; if (jj >= cols()) return false; for (size_t row = ii; internal::boost_numeric_cast< EIGEN_size_t >(row) < backend_->outerSize(); ++row) { for (typename BackendType::InnerIterator row_it(*backend_, internal::boost_numeric_cast< EIGEN_size_t >(row)); row_it; ++row_it) { const size_t col = row_it.col(); if ((ii == row) && (jj == col)) return true; else if ((row > ii) && (col > jj)) return false; } } return false; } // ... these_are_valid_indices(...) inline void ensure_uniqueness() const { if (!backend_.unique()) backend_ = std::make_shared< BackendType >(*backend_); } // ... ensure_uniqueness(...) mutable std::shared_ptr< BackendType > backend_; }; // class EigenRowMajorSparseMatrix #else // HAVE_EIGEN template< class ScalarImp > class EigenRowMajorSparseMatrix { static_assert(AlwaysFalse< ScalarImp >::value, "You are missing Eigen!"); }; #endif // HAVE_EIGEN } // namespace LA namespace Common { #if HAVE_EIGEN template< class T > struct MatrixAbstraction< LA::EigenRowMajorSparseMatrix< T > > : public LA::internal::MatrixAbstractionBase< LA::EigenRowMajorSparseMatrix< T > > {}; #endif // HAVE_EIGEN } // namespace Common } // namespace Stuff } // namespace Dune #endif // DUNE_STUFF_LA_CONTAINER_EIGEN_SPARSE_HH
fix ctor
[la.container.eigen.sparse] fix ctor
C++
bsd-2-clause
renemilk/DUNE-Stuff,renemilk/DUNE-Stuff,renemilk/DUNE-Stuff
6b33a468a02bec7418d3e130fcb61380d96dca6f
IslandMUD/npc_enemy_bodyguard.cpp
IslandMUD/npc_enemy_bodyguard.cpp
#include "npc_enemy_bodyguard.h" void Hostile_NPC_Bodyguard::update(World & world, map<string, shared_ptr<Character>> & actors) { // NPC bodyguards cheat by knowing their protect_target's location. Gameplay impact should be negligible. // idle if no protect_target has been set if (protect_target_id == "") return; // if the protect_target does not exist if (actors.find(protect_target_id) == actors.end()) { // reset and idle protect_target_id = ""; return; } // extract protect_target shared_ptr<Character> protect_target = actors.find(protect_target_id)->second; // if I have a kill_target if (kill_target_id != "") { // extract the kill_target shared_ptr<Character> kill_target = actors.find(kill_target_id)->second; // if the target is not in the actors list, the target is no longer in game if (kill_target == nullptr) { kill_target_id = ""; // reset target } else // the target is online { // if I am at the target's location, do combat logic if (kill_target->x == x && kill_target->y == y && kill_target->z == z) { return; // combat logic here } // else the target is online and I am not at the target's location // if the kill target is visible if (attempt_update_kill_target_last_known_location(kill_target)) { // if the path is empty or going the wrong direction, or the target has moved if (path.size() == 0 || stored_path_type != Stored_Path_Type::to_kill_target || kill_target->x != path.back()._x || kill_target->y != path.back()._y) { // generate a new path save_path_to(kill_target->x, kill_target->y, world); stored_path_type = Stored_Path_Type::to_kill_target; } // make the next movement make_path_movement(world); return; // action was used } // else the kill target is not visible // if have a last_known_location for kill_target if (kill_target_last_known_location._x != -1 && kill_target_last_known_location._y != -1) { // if my location is not last_known_location if (kill_target_last_known_location._x != x || kill_target_last_known_location._y != y || kill_target_last_known_location._z != z) { // if the path is empty or going to the wrong destination if (path.size() == 0 || stored_path_type != Stored_Path_Type::to_kill_target) { // generate a new path save_path_to(kill_target_last_known_location._x, kill_target_last_known_location._y, world); stored_path_type = Stored_Path_Type::to_kill_target; } // make the next make_path_movement(world); return; // action was used } // else I am at the last known location and cannot see the target (this condition is handled in the next block) } // kill target is not visible and I don't have a last known location for the kill target kill_target_last_known_location.reset(); // if the path is empty or going to the wrong destination if (path.size() == 0 || stored_path_type != Stored_Path_Type::to_protect_target) { // generate a new path save_path_to(protect_target->x, protect_target->y, world); stored_path_type = Stored_Path_Type::to_protect_target; } // make the next movement make_path_movement(world); // if the kill target is (now) visible if (attempt_update_kill_target_last_known_location(kill_target)) { save_path_to(kill_target_last_known_location._x, kill_target_last_known_location._y, world); // save a new path stored_path_type = Stored_Path_Type::to_kill_target; // update the stored path type } return; // action was used } } // else, I do not have a kill target // if I am out of guard range of my protect_target if (U::diagonal_distance(x, y, protect_target->x, protect_target->y) > guard_radius) { // if the path is empty or going to the wrong destination if (path.size() == 0 || stored_path_type != Stored_Path_Type::to_protect_target) { // generate a new path save_path_to(protect_target->x, protect_target->y, world); stored_path_type = Stored_Path_Type::to_protect_target; } // make the next movement make_path_movement(world); return; // action was used } // the NPC is in range of the protect target, check for a new kill target // if a new kill target can be found if (attempt_set_new_kill_target(world, actors)) { // if the path is empty or going to the wrong destination if (path.size() == 0 || stored_path_type != Stored_Path_Type::to_kill_target) { // generate a new path save_path_to(kill_target_last_known_location._x, kill_target_last_known_location._y, world); stored_path_type = Stored_Path_Type::to_kill_target; } // make the next movement make_path_movement(world); return; // action was used } // else, idle } void Hostile_NPC_Bodyguard::set_protect_target(const string & set_protect_target_id) { this->protect_target_id = set_protect_target_id; } bool Hostile_NPC_Bodyguard::attempt_set_new_kill_target(World & world, map<string, shared_ptr<Character>> & actors) { vector<string> hostile_ids; // for each visible room for (int cx = x - (int)C::VIEW_DISTANCE; cx <= x + (int)C::VIEW_DISTANCE; ++cx) { for (int cy = y - (int)C::VIEW_DISTANCE; cy <= y + (int)C::VIEW_DISTANCE; ++cy) { // for each actor in the room for (const string & actor_ID : world.room_at(cx, cy, z)->get_actor_ids()) { // if the actor is a player character if (U::is<PC>(actors.find(actor_ID)->second)) { // save the player character's ID hostile_ids.push_back(actor_ID); } } } } // if any player characters are in range if (hostile_ids.size() > 0) { // pick a random player character, save their ID this->kill_target_id = U::random_element_from(hostile_ids); // create a pointer to the player shared_ptr<Character> kill_target = actors.find(kill_target_id)->second; // save the player's current location as the player's last know location (in case they walk out of visible range) kill_target_last_known_location._x = kill_target->x; kill_target_last_known_location._y = kill_target->y; kill_target_last_known_location._z = kill_target->z; // we have a target return true; } // no players are visible, no target was found return false; } bool Hostile_NPC_Bodyguard::attempt_update_kill_target_last_known_location(const shared_ptr<Character> & kill_target) { // if the NPC can see the kill_target if (U::diagonal_distance(x, y, kill_target->x, kill_target->y) <= C::VIEW_DISTANCE) { // update kill_target_last_known_location kill_target_last_known_location._x = kill_target->x; kill_target_last_known_location._y = kill_target->y; kill_target_last_known_location._z = kill_target->z; return true; } // the NPC cannot see the kill target, the last_known_location was not updated return false; }
#include "npc_enemy_bodyguard.h" void Hostile_NPC_Bodyguard::update(World & world, map<string, shared_ptr<Character>> & actors) { // NPC bodyguards cheat by knowing their protect_target's location. Gameplay impact should be negligible. // idle if no protect_target has been set if (protect_target_id == "") return; // if the protect_target does not exist if (actors.find(protect_target_id) == actors.end()) { // reset and idle protect_target_id = ""; return; } // extract protect_target shared_ptr<Character> protect_target = actors.find(protect_target_id)->second; // if I have a kill_target if (kill_target_id != "") { // extract the kill_target shared_ptr<Character> kill_target = actors.find(kill_target_id)->second; // if the target is not in the actors list, the target is no longer in game if (kill_target == nullptr) { kill_target_id = ""; // reset target } else // the target is online { // if I am at the target's location, do combat logic if (kill_target->x == x && kill_target->y == y && kill_target->z == z) { return; // combat logic here } // else the target is online and I am not at the target's location // if the kill target is visible if (attempt_update_kill_target_last_known_location(kill_target)) { // if the path is empty or going the wrong direction, or the target has moved if (path.size() == 0 || stored_path_type != Stored_Path_Type::to_kill_target || kill_target->x != path.back()._x || kill_target->y != path.back()._y) { // generate a new path save_path_to(kill_target->x, kill_target->y, world); stored_path_type = Stored_Path_Type::to_kill_target; } // make the next movement make_path_movement(world); return; // action was used } // else the kill target is not visible // if have a last_known_location for kill_target if (kill_target_last_known_location._x != -1 && kill_target_last_known_location._y != -1) { // if my location is not last_known_location if (kill_target_last_known_location._x != x || kill_target_last_known_location._y != y || kill_target_last_known_location._z != z) { // if the path is empty or going to the wrong destination if (path.size() == 0 || stored_path_type != Stored_Path_Type::to_kill_target) { // generate a new path save_path_to(kill_target_last_known_location._x, kill_target_last_known_location._y, world); stored_path_type = Stored_Path_Type::to_kill_target; } // make the next make_path_movement(world); return; // action was used } // else I am at the last known location and cannot see the target (this condition is handled in the next block) } // kill target is not visible and I don't have a last known location for the kill target kill_target_last_known_location.reset(); // if the path is empty or going to the wrong destination if (path.size() == 0 || stored_path_type != Stored_Path_Type::to_protect_target) { // generate a new path save_path_to(protect_target->x, protect_target->y, world); stored_path_type = Stored_Path_Type::to_protect_target; } // make the next movement make_path_movement(world); // if the kill target is (now) visible if (attempt_update_kill_target_last_known_location(kill_target)) { save_path_to(kill_target_last_known_location._x, kill_target_last_known_location._y, world); // save a new path stored_path_type = Stored_Path_Type::to_kill_target; // update the stored path type } return; // action was used } } // else, I do not have a kill target // if I am out of guard range of my protect_target if (U::diagonal_distance(x, y, protect_target->x, protect_target->y) > guard_radius) { // if the path is empty or going to the wrong destination if (path.size() == 0 || stored_path_type != Stored_Path_Type::to_protect_target) { // generate a new path save_path_to(protect_target->x, protect_target->y, world); stored_path_type = Stored_Path_Type::to_protect_target; } // make the next movement make_path_movement(world); return; // action was used } // the NPC is in range of the protect target, check for a new kill target // if a new kill target can be found if (attempt_set_new_kill_target(world, actors)) { // if the path is empty or going to the wrong destination if (path.size() == 0 || stored_path_type != Stored_Path_Type::to_kill_target) { // generate a new path save_path_to(kill_target_last_known_location._x, kill_target_last_known_location._y, world); stored_path_type = Stored_Path_Type::to_kill_target; } // make the next movement make_path_movement(world); return; // action was used } // else, idle } void Hostile_NPC_Bodyguard::set_protect_target(const string & set_protect_target_id) { this->protect_target_id = set_protect_target_id; } bool Hostile_NPC_Bodyguard::attempt_set_new_kill_target(World & world, map<string, shared_ptr<Character>> & actors) { vector<string> hostile_ids; // for each visible room for (int cx = x - (int)C::VIEW_DISTANCE; cx <= x + (int)C::VIEW_DISTANCE; ++cx) { for (int cy = y - (int)C::VIEW_DISTANCE; cy <= y + (int)C::VIEW_DISTANCE; ++cy) { // for each actor in the room for (const string & actor_ID : world.room_at(cx, cy, z)->get_actor_ids()) { // if the actor is a player character if (U::is<PC>(actors.find(actor_ID)->second)) { // save the player character's ID hostile_ids.push_back(actor_ID); } } } } // no players are visible, no target was found if (hostile_ids.size() == 0) { return false; } // at least one player character is in range // pick a random player character, save their ID this->kill_target_id = U::random_element_from(hostile_ids); // create a pointer to the player shared_ptr<Character> kill_target = actors.find(kill_target_id)->second; // save the player's current location as the player's last know location (in case they walk out of visible range) kill_target_last_known_location._x = kill_target->x; kill_target_last_known_location._y = kill_target->y; kill_target_last_known_location._z = kill_target->z; // we have a target return true; } bool Hostile_NPC_Bodyguard::attempt_update_kill_target_last_known_location(const shared_ptr<Character> & kill_target) { // if the NPC can see the kill_target if (U::diagonal_distance(x, y, kill_target->x, kill_target->y) <= C::VIEW_DISTANCE) { // update kill_target_last_known_location kill_target_last_known_location._x = kill_target->x; kill_target_last_known_location._y = kill_target->y; kill_target_last_known_location._z = kill_target->z; return true; } // the NPC cannot see the kill target, the last_known_location was not updated return false; }
reduce nested bodyguard NPC code
reduce nested bodyguard NPC code See http://stackoverflow.com/a/764424 for a basic explanation on rationale.
C++
mit
JimViebke/IslandMUD,JimViebke/IslandMUD,JimViebke/IslandMUD,JimViebke/IslandMUD
2cb411fa630945dc37339a3007cc16bb29f32804
src/models/flight_control/FGAngles.cpp
src/models/flight_control/FGAngles.cpp
/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Module: FGAngles.cpp Author: Jon S. Berndt Date started: 6/2013 ------------- Copyright (C) 2013 Jon S. Berndt ([email protected]) ------------- This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. Further information about the GNU Lesser General Public License can also be found on the world wide web at http://www.gnu.org. FUNCTIONAL DESCRIPTION -------------------------------------------------------------------------------- HISTORY -------------------------------------------------------------------------------- Created: 6/2013 Jon S. Berndt %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% COMMENTS, REFERENCES, and NOTES %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% The Included Angle to Heading algorithm is used to find the smallest included angle (the angle less than or equal to 180 degrees) to a specified heading from the current heading. The sense of the rotation to get to that angle is also calculated (positive 1 for a clockwise rotation, negative 1 for counter- clockwise). The angle to the heading is calculated as follows: Given an angle phi: V = cos(phi)i + sin(phi)j (this is a unit vector) The dot product for two, 2D vectors is written: V1*V2 = |V1||V2|cos(phi) Since the magnitude of a unit vector is 1, we can write the equation as follows: V1*V2 = cos(phi) or, phi = acos(V1*V2) or, phi = acos[ cos(phi1)cos(phi2) + sin(phi1)sin(phi2) ] %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% INCLUDES %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/ #include "FGAngles.h" #include "input_output/FGXMLElement.h" #include "input_output/FGPropertyManager.h" using namespace std; namespace JSBSim { IDENT(IdSrc,"$Id: FGAngles.cpp,v 1.4 2014/01/13 10:46:07 ehofman Exp $"); IDENT(IdHdr,ID_ANGLES); /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% CLASS IMPLEMENTATION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/ //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% FGAngles::FGAngles(FGFCS* fcs, Element* element) : FGFCSComponent(fcs, element) { source_angle = 0.0; target_angle = 0.0; source_angle_unit = 1.0; target_angle_unit = 1.0; output_unit = 1.0; if (element->FindElement("target_angle") ) { target_angle_pNode = PropertyManager->GetNode(element->FindElementValue("target_angle")); if (element->FindElement("target_angle")->HasAttribute("unit")) { if (element->FindElement("target_angle")->GetAttributeValue("unit") == "DEG") { target_angle_unit = 0.017453293; } } } else { throw("Target angle is required for component: "+Name); } if (element->FindElement("source_angle") ) { source_angle_pNode = PropertyManager->GetNode(element->FindElementValue("source_angle")); if (element->FindElement("source_angle")->HasAttribute("unit")) { if (element->FindElement("source_angle")->GetAttributeValue("unit") == "DEG") { source_angle_unit = 0.017453293; } } } else { throw("Source latitude is required for Angles component: "+Name); } unit = element->GetAttributeValue("unit"); if (!unit.empty()) { if (unit == "DEG") output_unit = 180.0/M_PI; else if (unit == "RAD") output_unit = 1.0; else throw("Unknown unit "+unit+" in angle component, "+Name); } else { output_unit = 1.0; // Default is radians (1.0) if unspecified } FGFCSComponent::bind(); Debug(0); } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% FGAngles::~FGAngles() { Debug(1); } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% bool FGAngles::Run(void ) { source_angle = source_angle_pNode->getDoubleValue() * source_angle_unit; target_angle = target_angle_pNode->getDoubleValue() * target_angle_unit; double x1 = cos(source_angle); double y1 = sin(source_angle); double x2 = cos(target_angle); double y2 = sin(target_angle); double angle_to_heading_rad = acos(x1*x2 + y1*y2); double x1y2 = x1*y2; double x2y1 = x2*y1; if (x1y2 >= x2y1) Output = angle_to_heading_rad * output_unit; else Output = -angle_to_heading_rad * output_unit; Clip(); if (IsOutput) SetOutput(); return true; } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% // The bitmasked value choices are as follows: // unset: In this case (the default) JSBSim would only print // out the normally expected messages, essentially echoing // the config files as they are read. If the environment // variable is not set, debug_lvl is set to 1 internally // 0: This requests JSBSim not to output any messages // whatsoever. // 1: This value explicity requests the normal JSBSim // startup messages // 2: This value asks for a message to be printed out when // a class is instantiated // 4: When this value is set, a message is displayed when a // FGModel object executes its Run() method // 8: When this value is set, various runtime state variables // are printed out periodically // 16: When set various parameters are sanity checked and // a message is printed out when they go out of bounds void FGAngles::Debug(int from) { if (debug_lvl <= 0) return; if (debug_lvl & 1) { // Standard console startup message output if (from == 0) { // Constructor } } if (debug_lvl & 2 ) { // Instantiation/Destruction notification if (from == 0) cout << "Instantiated: FGAngles" << endl; if (from == 1) cout << "Destroyed: FGAngles" << endl; } if (debug_lvl & 4 ) { // Run() method entry print for FGModel-derived objects } if (debug_lvl & 8 ) { // Runtime state variables } if (debug_lvl & 16) { // Sanity checking } if (debug_lvl & 64) { if (from == 0) { // Constructor cout << IdSrc << endl; cout << IdHdr << endl; } } } }
/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Module: FGAngles.cpp Author: Jon S. Berndt Date started: 6/2013 ------------- Copyright (C) 2013 Jon S. Berndt ([email protected]) ------------- This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. Further information about the GNU Lesser General Public License can also be found on the world wide web at http://www.gnu.org. FUNCTIONAL DESCRIPTION -------------------------------------------------------------------------------- HISTORY -------------------------------------------------------------------------------- Created: 6/2013 Jon S. Berndt %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% COMMENTS, REFERENCES, and NOTES %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% The Included Angle to Heading algorithm is used to find the smallest included angle (the angle less than or equal to 180 degrees) to a specified heading from the current heading. The sense of the rotation to get to that angle is also calculated (positive 1 for a clockwise rotation, negative 1 for counter- clockwise). The angle to the heading is calculated as follows: Given an angle phi: V = cos(phi)i + sin(phi)j (this is a unit vector) The dot product for two, 2D vectors is written: V1*V2 = |V1||V2|cos(phi) Since the magnitude of a unit vector is 1, we can write the equation as follows: V1*V2 = cos(phi) or, phi = acos(V1*V2) or, phi = acos[ cos(phi1)cos(phi2) + sin(phi1)sin(phi2) ] %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% INCLUDES %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/ #include "FGAngles.h" #include "input_output/FGXMLElement.h" #include "input_output/FGPropertyManager.h" using namespace std; namespace JSBSim { IDENT(IdSrc,"$Id: FGAngles.cpp,v 1.5 2016/07/27 22:42:47 andgi Exp $"); IDENT(IdHdr,ID_ANGLES); /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% CLASS IMPLEMENTATION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/ //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% FGAngles::FGAngles(FGFCS* fcs, Element* element) : FGFCSComponent(fcs, element) { source_angle = 0.0; target_angle = 0.0; source_angle_unit = 1.0; target_angle_unit = 1.0; output_unit = 1.0; if (element->FindElement("target_angle") ) { target_angle_pNode = PropertyManager->GetNode(element->FindElementValue("target_angle")); if (element->FindElement("target_angle")->HasAttribute("unit")) { if (element->FindElement("target_angle")->GetAttributeValue("unit") == "DEG") { target_angle_unit = 0.017453293; } } } else { throw("Target angle is required for component: "+Name); } if (element->FindElement("source_angle") ) { source_angle_pNode = PropertyManager->GetNode(element->FindElementValue("source_angle")); if (element->FindElement("source_angle")->HasAttribute("unit")) { if (element->FindElement("source_angle")->GetAttributeValue("unit") == "DEG") { source_angle_unit = 0.017453293; } } } else { throw("Source latitude is required for Angles component: "+Name); } unit = element->GetAttributeValue("unit"); if (!unit.empty()) { if (unit == "DEG") output_unit = 180.0/M_PI; else if (unit == "RAD") output_unit = 1.0; else throw("Unknown unit "+unit+" in angle component, "+Name); } else { output_unit = 1.0; // Default is radians (1.0) if unspecified } FGFCSComponent::bind(); Debug(0); } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% FGAngles::~FGAngles() { Debug(1); } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% bool FGAngles::Run(void ) { source_angle = source_angle_pNode->getDoubleValue() * source_angle_unit; target_angle = target_angle_pNode->getDoubleValue() * target_angle_unit; double x1 = cos(source_angle); double y1 = sin(source_angle); double x2 = cos(target_angle); double y2 = sin(target_angle); double x1x2_y1y2 = max(-1.0, min(x1*x2 + y1*y2, 1.0)); double angle_to_heading_rad = acos(x1x2_y1y2); double x1y2 = x1*y2; double x2y1 = x2*y1; if (x1y2 >= x2y1) Output = angle_to_heading_rad * output_unit; else Output = -angle_to_heading_rad * output_unit; Clip(); if (IsOutput) SetOutput(); return true; } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% // The bitmasked value choices are as follows: // unset: In this case (the default) JSBSim would only print // out the normally expected messages, essentially echoing // the config files as they are read. If the environment // variable is not set, debug_lvl is set to 1 internally // 0: This requests JSBSim not to output any messages // whatsoever. // 1: This value explicity requests the normal JSBSim // startup messages // 2: This value asks for a message to be printed out when // a class is instantiated // 4: When this value is set, a message is displayed when a // FGModel object executes its Run() method // 8: When this value is set, various runtime state variables // are printed out periodically // 16: When set various parameters are sanity checked and // a message is printed out when they go out of bounds void FGAngles::Debug(int from) { if (debug_lvl <= 0) return; if (debug_lvl & 1) { // Standard console startup message output if (from == 0) { // Constructor } } if (debug_lvl & 2 ) { // Instantiation/Destruction notification if (from == 0) cout << "Instantiated: FGAngles" << endl; if (from == 1) cout << "Destroyed: FGAngles" << endl; } if (debug_lvl & 4 ) { // Run() method entry print for FGModel-derived objects } if (debug_lvl & 8 ) { // Runtime state variables } if (debug_lvl & 16) { // Sanity checking } if (debug_lvl & 64) { if (from == 0) { // Constructor cout << IdSrc << endl; cout << IdHdr << endl; } } } }
Make sure the argument to acos() is never out of bounds.
Make sure the argument to acos() is never out of bounds.
C++
lgpl-2.1
hrabcak/jsbsim,pmatigakis/jsbsim,hrabcak/jsbsim,tridge/jsbsim,hrabcak/jsbsim,Stonelinks/jsbsim,hrabcak/jsbsim,pmatigakis/jsbsim,Stonelinks/jsbsim,Stonelinks/jsbsim,pmatigakis/jsbsim,Stonelinks/jsbsim,pmatigakis/jsbsim,hrabcak/jsbsim,tridge/jsbsim,tridge/jsbsim,pmatigakis/jsbsim,Stonelinks/jsbsim,tridge/jsbsim,tridge/jsbsim,Stonelinks/jsbsim,pmatigakis/jsbsim,tridge/jsbsim,hrabcak/jsbsim,pmatigakis/jsbsim,hrabcak/jsbsim,tridge/jsbsim,Stonelinks/jsbsim
40d241c6b6d13fac8ce9ff606277b802f38a4861
mining/include/mframework.hpp
mining/include/mframework.hpp
//------------------------------------------------------------------------------ // File: mframework.hpp // // Desc: Data Mining Framework. // // Copyright (c) 2014-2018. veyesys.com All rights reserved. //------------------------------------------------------------------------------ #ifndef __M_FRAME_WORK_HPP__ #define __M_FRAME_WORK_HPP__ #include "utility.hpp" #include "debug.hpp" #include "videotype.hpp" #include "miningtype.hpp" #include "mmodule.hpp" #include "factory.hpp" #include <QThread> #include <qdebug.h> #include "cppkit/ck_string.h" #include "cppkit/ck_memory.h" #include "cppkit/ck_command_queue.h" #include "cppkit/ck_dynamic_library.h" #include "cppkit/ck_byte_ptr.h" #include "Poco/DirectoryIterator.h" #include "Poco/File.h" #include "Poco/Path.h" using Poco::DirectoryIterator; using Poco::File; using Poco::Path; using namespace std; using namespace cppkit; /* All the mining data will be post a queue to here, Then start a thread to peek the queue to post to each device in factory */ typedef command_queue<MiningRet> MModuleRetQueue; typedef std::map<int, MiningModule *> MModuleMap; class MFramework:public QThread { Q_OBJECT public: inline MFramework(Factory &pFactory); inline ~MFramework(); inline BOOL Init(); public: inline void run(); public: inline static BOOL RetHandler(s32 id, MiningRet& ret, void * pParam); inline BOOL RetHandler1(s32 id, MiningRet& ret); public: static BOOL DeviceChangeCallbackFunc(void* pData, FactoryDeviceChangeData change); BOOL DeviceChangeCallbackFunc1(FactoryDeviceChangeData change); private: MModuleMap m_MModules; MModuleRetQueue m_RetQueue; BOOL m_bExit; }; inline BOOL MFramework:Init() { /* Get all the modules list and init */ std::string dir; if (argc > 1) dir = argv[1]; else dir = Path::current(); try { DirectoryIterator it(dir); DirectoryIterator end; while (it != end) { Path p(it->path()); std::cout << (it->isDirectory() ? 'd' : '-') << (it->canRead() ? 'r' : '-') << (it->canWrite() ? 'w' : '-') << ' ' << DateTimeFormatter::format(it->getLastModified(), DateTimeFormat::SORTABLE_FORMAT) << ' ' << p.getFileName() << std::endl; ++it; } } catch (Poco::Exception& exc) { std::cerr << exc.displayText() << std::endl; return 1; } /* Get all the device and add channel to all the modules */ } BOOL MFramework::RetHandler(s32 id, MiningRet& ret, void * pParam) { int dummy = errno; MFramework *pMFramework = (MFramework)pParam; if (pMFramework) { return pMFramework->RetHandler1(id, ret); } return TRUE; } BOOL MFramework::RetHandler1(s32 id, MiningRet& ret) { m_RetQueue.post(ret); return TRUE; } void MFramework::run() { MiningRet ret; while (m_bExit != TRUE) { if (m_RetQueue.size() > 0) { ret = m_RetQueue.pop(); //send the ret va data to factory for showing continue; }else { ve_sleep(1000); } } return; } bool MFramework::DeviceChangeCallbackFunc(void* pData, FactoryDeviceChangeData change) { if (pData) { MFramework * pthread = (MFramework *)pData; pthread->DeviceChangeCallbackFunc1(change); } return true; } bool MFramework::DeviceChangeCallbackFunc1(FactoryDeviceChangeData change) { VDC_DEBUG( "Event Device Change Callback %d type %d Begin\n", change.id, change.type); if (change.type == FACTORY_DEVICE_OFFLINE) { } if (change.type == FACTORY_DEVICE_ONLINE) { } VDC_DEBUG( "Event Device Change Callback %d type %d End \n", change.id, change.type); return TRUE; } #endif /* __M_FRAME_WORK_HPP__ */
//------------------------------------------------------------------------------ // File: mframework.hpp // // Desc: Data Mining Framework. // // Copyright (c) 2014-2018. veyesys.com All rights reserved. //------------------------------------------------------------------------------ #ifndef __M_FRAME_WORK_HPP__ #define __M_FRAME_WORK_HPP__ #include "utility.hpp" #include "debug.hpp" #include "videotype.hpp" #include "miningtype.hpp" #include "mmodule.hpp" #include "factory.hpp" #include <QThread> #include <qdebug.h> #include "cppkit/ck_string.h" #include "cppkit/ck_memory.h" #include "cppkit/ck_command_queue.h" #include "cppkit/ck_dynamic_library.h" #include "cppkit/ck_byte_ptr.h" #include "Poco/DirectoryIterator.h" #include "Poco/File.h" #include "Poco/Path.h" using Poco::DirectoryIterator; using Poco::File; using Poco::Path; using namespace std; using namespace cppkit; /* All the mining data will be post a queue to here, Then start a thread to peek the queue to post to each device in factory */ typedef command_queue<MiningRet> MModuleRetQueue; typedef std::map<int, MiningModule *> MModuleMap; class MFramework:public QThread { Q_OBJECT public: inline MFramework(Factory &pFactory); inline ~MFramework(); inline BOOL Init(); public: inline void run(); public: inline static BOOL RetHandler(s32 id, MiningRet& ret, void * pParam); inline BOOL RetHandler1(s32 id, MiningRet& ret); public: inline static BOOL DeviceChangeCallbackFunc(void* pData, FactoryDeviceChangeData change); inline BOOL DeviceChangeCallbackFunc1(FactoryDeviceChangeData change); public: inline astring GetPluginPath(); private: MModuleMap m_MModules; MModuleRetQueue m_RetQueue; BOOL m_bExit; }; astring MFramework::GetPluginPath() { #ifdef WIN32 char exeFullPath[MAX_PATH]; // Full path string strPath = ""; GetModuleFileNameA(NULL,exeFullPath, MAX_PATH); strPath=(string)exeFullPath; // Get full path of the file int pos = strPath.find_last_of('\\', strPath.length()); return strPath.substr(0, pos); // Return the directory without the file name #else return "./"; #endif } inline BOOL MFramework::Init() { /* Get all the modules list and init */ std::string dir; //dir = Path::current(); std::string pluginPath = GetPluginPath() + "/mplugins/"; dir = pluginPath; try { DirectoryIterator it(dir); DirectoryIterator end; while (it != end) { /* loop for each dir */ if (it->isDirectory() == true) { try { DirectoryIterator it2(it->path()); DirectoryIterator end2; while (it2 != end2) { if (it2.name().find("mplugin") == 0) { //Find a plugin // Call mmodule to add } ++it2; } } catch (Poco::Exception& exc) { continue; } } #if 0 Path p(it->path()); if () std::cout << (it->isDirectory() ? 'd' : '-') << (it->canRead() ? 'r' : '-') << (it->canWrite() ? 'w' : '-') << ' ' << DateTimeFormatter::format(it->getLastModified(), DateTimeFormat::SORTABLE_FORMAT) << ' ' << p.getFileName() << std::endl; #endif ++it; } } catch (Poco::Exception& exc) { std::cerr << exc.displayText() << std::endl; VDC_DEBUG( "Plugin init error \n"); return ; } /* Get all the device and add channel to all the modules */ } BOOL MFramework::RetHandler(s32 id, MiningRet& ret, void * pParam) { int dummy = errno; MFramework *pMFramework = (MFramework)pParam; if (pMFramework) { return pMFramework->RetHandler1(id, ret); } return TRUE; } BOOL MFramework::RetHandler1(s32 id, MiningRet& ret) { m_RetQueue.post(ret); return TRUE; } void MFramework::run() { MiningRet ret; while (m_bExit != TRUE) { if (m_RetQueue.size() > 0) { ret = m_RetQueue.pop(); //send the ret va data to factory for showing continue; }else { ve_sleep(1000); } } return; } bool MFramework::DeviceChangeCallbackFunc(void* pData, FactoryDeviceChangeData change) { if (pData) { MFramework * pthread = (MFramework *)pData; pthread->DeviceChangeCallbackFunc1(change); } return true; } bool MFramework::DeviceChangeCallbackFunc1(FactoryDeviceChangeData change) { VDC_DEBUG( "Event Device Change Callback %d type %d Begin\n", change.id, change.type); if (change.type == FACTORY_DEVICE_OFFLINE) { } if (change.type == FACTORY_DEVICE_ONLINE) { } VDC_DEBUG( "Event Device Change Callback %d type %d End \n", change.id, change.type); return TRUE; } #endif /* __M_FRAME_WORK_HPP__ */
add module parse
add module parse
C++
mit
veyesys/opencvr,xsmart/opencvr,xiaojuntong/opencvr,veyesys/opencvr,xiaojuntong/opencvr,herocodemaster/opencvr,herocodemaster/opencvr,herocodemaster/opencvr,telecamera/opencvr,xsmart/opencvr,xiaojuntong/opencvr,xsmart/opencvr,telecamera/opencvr,telecamera/opencvr,xsmart/opencvr,telecamera/opencvr,xiaojuntong/opencvr,veyesys/opencvr,veyesys/opencvr,xsmart/opencvr,veyesys/opencvr,herocodemaster/opencvr
12eeeb6323694ef973a4669a907f94cc5c7f2a44
src/nerved/config/dump_config_yaml.cpp
src/nerved/config/dump_config_yaml.cpp
// Copyright (C) 2011, James Webber. // Distributed under a 3-clause BSD license. See COPYING. #include <map> #include "../util/asserts.hpp" #include "pipeline_configs.hpp" void config::dump_config_yaml(config::pipeline_config &pc) { using namespace config; typedef pipeline_config::job_iterator_type job_iter_t; typedef job_config::section_iterator_type section_iter_t; typedef section_config::stage_iterator_type stage_iter_t; std::map<job_config *, int> job_index; std::cout << "---" << std::endl; int thread_num = 1; for (job_iter_t job = pc.begin(); job != pc.end(); ++job) { std::cout << "- thread: " << thread_num << std::endl; std::cout << " sections:" << std::endl; section_config *sec = job->job_first(); do { NERVE_ASSERT(&(*job) == &(sec->parent_job()), "link order shouldn't go into another job"); std::cout << " - name: \"" << sec->name() << "\"" << std::endl; section_config *const prev = sec->pipeline_previous(); section_config *const next = sec->pipeline_next(); const char *from = prev ? prev->name() : ":start_pipe"; const char *to = next ? next->name() : ":end_pipe"; const char *to_delim = next ? "\"" : ""; const char *from_delim = prev ? "\"" : ""; std::cout << " prev: " << from_delim << from << from_delim << std::endl; std::cout << " next: " << to_delim << to << to_delim << std::endl; std::cout << " sequences:" << std::endl; stage_config::categories last_cat = stage_config::cat_unset; for (stage_iter_t stage = sec->begin(); stage != sec->end(); ++stage) { if (stage->category() != last_cat) { std::cout << " - type: \"" << stage->category_name() << '"' << std::endl; std::cout << " stages: " << std::endl; } std::cout << " - name: \"" << stage->name() << "\"" << std::endl; const char *where = ":internal"; const char *ldelim = ""; const char *rdelim = ""; if (! stage->internal()) { where = stage->path(); ldelim = "\""; rdelim = "\""; } std::cout << " location: " << ldelim << where << rdelim << std::endl; std::cout << " config: "; if (stage->configs_given()) { std::cout << std::endl; typedef stage_config::configs_type configs_type; typedef configs_type::pairs_type pairs_type; typedef pairs_type::const_iterator iter_t; configs_type &cf = *NERVE_CHECK_PTR(stage->configs()); pairs_type &pairs = cf.pairs(); for (iter_t conf = pairs.begin(); conf != pairs.end(); ++conf) { const char *const key = conf->field(); const char *const value = conf->value(); std::cout << " - [\"" << key << "\", \"" << value << "\"]" << std::endl;; } } else { std::cout << "[]" << std::endl; } } } while ((sec = sec->job_next()) != NULL); ++thread_num; } }
// Copyright (C) 2011, James Webber. // Distributed under a 3-clause BSD license. See COPYING. #include <map> #include "../util/asserts.hpp" #include "pipeline_configs.hpp" void config::dump_config_yaml(config::pipeline_config &pc) { using namespace config; typedef pipeline_config::job_iterator_type job_iter_t; typedef job_config::section_iterator_type section_iter_t; typedef section_config::stage_iterator_type stage_iter_t; std::cout << "---" << std::endl; int thread_num = 1; for (job_iter_t job = pc.begin(); job != pc.end(); ++job) { std::cout << "- thread: " << thread_num << std::endl; std::cout << " sections:" << std::endl; section_config *sec = job->job_first(); do { NERVE_ASSERT(&(*job) == &(sec->parent_job()), "link order shouldn't go into another job"); std::cout << " - name: \"" << sec->name() << "\"" << std::endl; section_config *const prev = sec->pipeline_previous(); section_config *const next = sec->pipeline_next(); const char *from = prev ? prev->name() : ":start_pipe"; const char *to = next ? next->name() : ":end_pipe"; const char *to_delim = next ? "\"" : ""; const char *from_delim = prev ? "\"" : ""; std::cout << " prev: " << from_delim << from << from_delim << std::endl; std::cout << " next: " << to_delim << to << to_delim << std::endl; std::cout << " sequences:" << std::endl; stage_config::categories last_cat = stage_config::cat_unset; for (stage_iter_t stage = sec->begin(); stage != sec->end(); ++stage) { if (stage->category() != last_cat) { std::cout << " - type: \"" << stage->category_name() << '"' << std::endl; std::cout << " stages: " << std::endl; } std::cout << " - name: \"" << stage->name() << "\"" << std::endl; const char *where = ":internal"; const char *ldelim = ""; const char *rdelim = ""; if (! stage->internal()) { where = stage->path(); ldelim = "\""; rdelim = "\""; } std::cout << " location: " << ldelim << where << rdelim << std::endl; std::cout << " config: "; if (stage->configs_given()) { std::cout << std::endl; typedef stage_config::configs_type configs_type; typedef configs_type::pairs_type pairs_type; typedef pairs_type::const_iterator iter_t; configs_type &cf = *NERVE_CHECK_PTR(stage->configs()); pairs_type &pairs = cf.pairs(); for (iter_t conf = pairs.begin(); conf != pairs.end(); ++conf) { const char *const key = conf->field(); const char *const value = conf->value(); std::cout << " - [\"" << key << "\", \"" << value << "\"]" << std::endl;; } } else { std::cout << "[]" << std::endl; } } } while ((sec = sec->job_next()) != NULL); ++thread_num; } }
Remove useless var.
Remove useless var.
C++
bsd-3-clause
bnkr/nerve,bnkr/nerve,bnkr/nerve
932b0ea2fd51defad33002e42bbed245e9cda4a2
src/numerics/trilinos_preconditioner.C
src/numerics/trilinos_preconditioner.C
// The libMesh Finite Element Library. // Copyright (C) 2002-2012 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA #include "libmesh_common.h" #ifdef LIBMESH_HAVE_TRILINOS // C++ includes // Local Includes #include "trilinos_preconditioner.h" #include "trilinos_epetra_matrix.h" #include "trilinos_epetra_vector.h" #include "libmesh_common.h" #include "Ifpack.h" #include "Ifpack_DiagPreconditioner.h" #include "Ifpack_AdditiveSchwarz.h" #include "Ifpack_ILU.h" #include "Ifpack_ILUT.h" #include "Ifpack_IC.h" #include "Ifpack_ICT.h" #ifdef LIBMESH_HAVE_ML #include "ml_MultiLevelPreconditioner.h" #endif namespace libMesh { template <typename T> void TrilinosPreconditioner<T>::apply(const NumericVector<T> & /* x */, NumericVector<T> & /* y */ ) { } template <typename T> void TrilinosPreconditioner<T>::init () { if(!this->_matrix) { libMesh::err << "ERROR: No matrix set for PetscPreconditioner, but init() called" << std::endl; libmesh_error(); } // Clear the preconditioner in case it has been created in the past if (!this->_is_initialized) { EpetraMatrix<T> * matrix = libmesh_cast_ptr<EpetraMatrix<T>*, SparseMatrix<T> >(this->_matrix); _mat = matrix->mat(); } set_preconditioner_type(this->_preconditioner_type); this->_is_initialized = true; } template <typename T> void TrilinosPreconditioner<T>::set_params(Teuchos::ParameterList & list) { _param_list = list; } template <typename T> void TrilinosPreconditioner<T>::compute() { Ifpack_Preconditioner * ifpack = NULL; ML_Epetra::MultiLevelPreconditioner * ml = NULL; switch (this->_preconditioner_type) { // IFPACK preconditioners case ILU_PRECOND: case SOR_PRECOND: ifpack = dynamic_cast<Ifpack_Preconditioner *>(_prec); ifpack->Compute(); break; #ifdef LIBMESH_HAVE_ML // ML preconditioners case AMG_PRECOND: ml = dynamic_cast<ML_Epetra::MultiLevelPreconditioner *>(_prec); ml->ComputePreconditioner(); break; #endif default: // no nothing here break; } } template <typename T> void TrilinosPreconditioner<T>::set_preconditioner_type (const PreconditionerType & preconditioner_type) { Ifpack_Preconditioner * pc = NULL; ML_Epetra::MultiLevelPreconditioner * ml = NULL; switch (preconditioner_type) { case IDENTITY_PRECOND: // pc = new Ifpack_DiagPreconditioner(); break; case CHOLESKY_PRECOND: break; case ICC_PRECOND: break; case ILU_PRECOND: pc = new Ifpack_ILU(_mat); pc->SetParameters(_param_list); pc->Initialize(); _prec = pc; break; case LU_PRECOND: break; case ASM_PRECOND: break; case JACOBI_PRECOND: break; case BLOCK_JACOBI_PRECOND: break; case SOR_PRECOND: break; case EISENSTAT_PRECOND: break; #ifdef LIBMESH_HAVE_ML case AMG_PRECOND: ml = new ML_Epetra::MultiLevelPreconditioner(*_mat, _param_list, false);; _prec = ml; break; #endif default: libMesh::err << "ERROR: Unsupported Trilinos Preconditioner: " << preconditioner_type << std::endl << "Continuing with Trilinos defaults" << std::endl; } } template <typename T> int TrilinosPreconditioner<T>::SetUseTranspose(bool UseTranspose) { return _prec->SetUseTranspose(UseTranspose); } template <typename T> int TrilinosPreconditioner<T>::Apply(const Epetra_MultiVector &X, Epetra_MultiVector &Y) const { return _prec->Apply(X, Y); } template <typename T> int TrilinosPreconditioner<T>::ApplyInverse(const Epetra_MultiVector &r, Epetra_MultiVector &z) const { return _prec->ApplyInverse(r, z); } template <typename T> double TrilinosPreconditioner<T>::NormInf() const { return _prec->NormInf(); } template <typename T> const char * TrilinosPreconditioner<T>::Label() const { return _prec->Label(); } template <typename T> bool TrilinosPreconditioner<T>::UseTranspose() const { return _prec->UseTranspose(); } template <typename T> bool TrilinosPreconditioner<T>::HasNormInf() const { return _prec->HasNormInf(); } template <typename T> const Epetra_Comm & TrilinosPreconditioner<T>::Comm() const { return _prec->Comm(); } template <typename T> const Epetra_Map & TrilinosPreconditioner<T>::OperatorDomainMap() const { return _prec->OperatorDomainMap(); } template <typename T> const Epetra_Map & TrilinosPreconditioner<T>::OperatorRangeMap() const { return _prec->OperatorRangeMap(); } //------------------------------------------------------------------ // Explicit instantiations template class TrilinosPreconditioner<Number>; } // namespace libMesh #endif // #ifdef LIBMESH_HAVE_TRILINOS
// The libMesh Finite Element Library. // Copyright (C) 2002-2012 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA #include "libmesh_common.h" #ifdef LIBMESH_HAVE_TRILINOS // C++ includes // Local Includes #include "trilinos_preconditioner.h" #include "trilinos_epetra_matrix.h" #include "trilinos_epetra_vector.h" #include "libmesh_common.h" #include "Ifpack.h" #include "Ifpack_DiagPreconditioner.h" #include "Ifpack_AdditiveSchwarz.h" #include "Ifpack_ILU.h" #include "Ifpack_ILUT.h" #include "Ifpack_IC.h" #include "Ifpack_ICT.h" #ifdef LIBMESH_HAVE_ML #include "ml_MultiLevelPreconditioner.h" #endif namespace libMesh { template <typename T> void TrilinosPreconditioner<T>::apply(const NumericVector<T> & /* x */, NumericVector<T> & /* y */ ) { } template <typename T> void TrilinosPreconditioner<T>::init () { if(!this->_matrix) { libMesh::err << "ERROR: No matrix set for PetscPreconditioner, but init() called" << std::endl; libmesh_error(); } // Clear the preconditioner in case it has been created in the past if (!this->_is_initialized) { EpetraMatrix<T> * matrix = libmesh_cast_ptr<EpetraMatrix<T>*, SparseMatrix<T> >(this->_matrix); _mat = matrix->mat(); } set_preconditioner_type(this->_preconditioner_type); this->_is_initialized = true; } template <typename T> void TrilinosPreconditioner<T>::set_params(Teuchos::ParameterList & list) { _param_list = list; } template <typename T> void TrilinosPreconditioner<T>::compute() { Ifpack_Preconditioner * ifpack = NULL; #ifdef LIBMESH_HAVE_ML ML_Epetra::MultiLevelPreconditioner * ml = NULL; #endif switch (this->_preconditioner_type) { // IFPACK preconditioners case ILU_PRECOND: case SOR_PRECOND: ifpack = dynamic_cast<Ifpack_Preconditioner *>(_prec); ifpack->Compute(); break; #ifdef LIBMESH_HAVE_ML // ML preconditioners case AMG_PRECOND: ml = dynamic_cast<ML_Epetra::MultiLevelPreconditioner *>(_prec); ml->ComputePreconditioner(); break; #endif default: // no nothing here break; } } template <typename T> void TrilinosPreconditioner<T>::set_preconditioner_type (const PreconditionerType & preconditioner_type) { Ifpack_Preconditioner * pc = NULL; #ifdef LIBMESH_HAVE_ML ML_Epetra::MultiLevelPreconditioner * ml = NULL; #endif switch (preconditioner_type) { case IDENTITY_PRECOND: // pc = new Ifpack_DiagPreconditioner(); break; case CHOLESKY_PRECOND: break; case ICC_PRECOND: break; case ILU_PRECOND: pc = new Ifpack_ILU(_mat); pc->SetParameters(_param_list); pc->Initialize(); _prec = pc; break; case LU_PRECOND: break; case ASM_PRECOND: break; case JACOBI_PRECOND: break; case BLOCK_JACOBI_PRECOND: break; case SOR_PRECOND: break; case EISENSTAT_PRECOND: break; #ifdef LIBMESH_HAVE_ML case AMG_PRECOND: ml = new ML_Epetra::MultiLevelPreconditioner(*_mat, _param_list, false);; _prec = ml; break; #endif default: libMesh::err << "ERROR: Unsupported Trilinos Preconditioner: " << preconditioner_type << std::endl << "Continuing with Trilinos defaults" << std::endl; } } template <typename T> int TrilinosPreconditioner<T>::SetUseTranspose(bool UseTranspose) { return _prec->SetUseTranspose(UseTranspose); } template <typename T> int TrilinosPreconditioner<T>::Apply(const Epetra_MultiVector &X, Epetra_MultiVector &Y) const { return _prec->Apply(X, Y); } template <typename T> int TrilinosPreconditioner<T>::ApplyInverse(const Epetra_MultiVector &r, Epetra_MultiVector &z) const { return _prec->ApplyInverse(r, z); } template <typename T> double TrilinosPreconditioner<T>::NormInf() const { return _prec->NormInf(); } template <typename T> const char * TrilinosPreconditioner<T>::Label() const { return _prec->Label(); } template <typename T> bool TrilinosPreconditioner<T>::UseTranspose() const { return _prec->UseTranspose(); } template <typename T> bool TrilinosPreconditioner<T>::HasNormInf() const { return _prec->HasNormInf(); } template <typename T> const Epetra_Comm & TrilinosPreconditioner<T>::Comm() const { return _prec->Comm(); } template <typename T> const Epetra_Map & TrilinosPreconditioner<T>::OperatorDomainMap() const { return _prec->OperatorDomainMap(); } template <typename T> const Epetra_Map & TrilinosPreconditioner<T>::OperatorRangeMap() const { return _prec->OperatorRangeMap(); } //------------------------------------------------------------------ // Explicit instantiations template class TrilinosPreconditioner<Number>; } // namespace libMesh #endif // #ifdef LIBMESH_HAVE_TRILINOS
Fix for Trilnos without ML case
Fix for Trilnos without ML case git-svn-id: ffc1bc5b3feaf8644044862cc38c386ade156493@5508 434f946d-2f3d-0410-ba4c-cb9f52fb0dbf
C++
lgpl-2.1
certik/libmesh,certik/libmesh,certik/libmesh,certik/libmesh,certik/libmesh,certik/libmesh,certik/libmesh
12c1fc0adedf2f2c2d01d06ee143a59a8cbda8fd
src/scenes/menkmanJPG1/menkmanJPG1.cpp
src/scenes/menkmanJPG1/menkmanJPG1.cpp
#include "menkmanJPG1.h" void menkmanJPG1::setup(){ ofSetLogLevel(OF_LOG_VERBOSE); srcPath = "menkmanJPG1/images/menkman.jpg"; dstPath = "menkmanJPG1/images/menkmanGlitch.jpg"; lineCount = getLineCount(srcPath); src.load(srcPath); dst.load(dstPath); // setup pramaters numberOfLines.set("numberOfLines", 1, 0, lineCount); startLine.set("startLine", 50, 0, lineCount); parameters.add(numberOfLines); parameters.add(startLine); loadCode("menkmanJPG1/exampleCode.cpp"); } void menkmanJPG1::update(){ glitchImage(startLine, numberOfLines); } void menkmanJPG1::draw(){ ofBackground(0); ofSetColor(255); dst.draw(0,0,dimensions.getWidth(),dimensions.getHeight()); } int menkmanJPG1::getLineCount(string path) { int count = 0; string line; std::ifstream file; // open file file.open(ofToDataPath(path).c_str()); // count lines one by one while(std::getline(file, line)) { ++count; } file.close(); return count; }; void menkmanJPG1::glitchImage(int start, int max) { // ofLogVerbose("glitch image: "+ofToString(start)+", "+ofToString(max)); ifstream fin; fin.open(ofToDataPath(srcPath).c_str()); ofstream fout; fout.open(ofToDataPath(dstPath).c_str() ); int i = 0; while(fin) { string str; std::getline(fin, str); if(i >= start && i < start + max) { // leave this line out // ofLogVerbose("leave out line "+ofToString(i)); } else { fout << str << "\n"; } i++; } fout.close(); fin.close(); ofLogVerbose("open in glitch"); dst.load(dstPath); }
#include "menkmanJPG1.h" void menkmanJPG1::setup(){ // ofSetLogLevel(OF_LOG_VERBOSE); srcPath = "menkmanJPG1/images/menkman.jpg"; dstPath = "menkmanJPG1/images/menkmanGlitch.jpg"; lineCount = getLineCount(srcPath); src.load(srcPath); dst.load(dstPath); // setup pramaters numberOfLines.set("numberOfLines", 1, 0, lineCount); startLine.set("startLine", 50, 0, lineCount); parameters.add(numberOfLines); parameters.add(startLine); loadCode("menkmanJPG1/exampleCode.cpp"); } void menkmanJPG1::update(){ glitchImage(startLine, numberOfLines); } void menkmanJPG1::draw(){ ofBackground(0); ofSetColor(255); dst.draw(0,0,dimensions.getWidth(),dimensions.getHeight()); } int menkmanJPG1::getLineCount(string path) { int count = 0; string line; std::ifstream file; // open file file.open(ofToDataPath(path).c_str()); // count lines one by one while(std::getline(file, line)) { ++count; } file.close(); return count; }; void menkmanJPG1::glitchImage(int start, int max) { // ofLogVerbose("glitch image: "+ofToString(start)+", "+ofToString(max)); ifstream fin; fin.open(ofToDataPath(srcPath).c_str()); ofstream fout; fout.open(ofToDataPath(dstPath).c_str() ); int i = 0; while(fin) { string str; std::getline(fin, str); if(i >= start && i < start + max) { // leave this line out // ofLogVerbose("leave out line "+ofToString(i)); } else { fout << str << "\n"; } i++; } fout.close(); fin.close(); // ofLogVerbose("open in glitch"); dst.load(dstPath); }
Remove extra logging stuff
Remove extra logging stuff
C++
mit
roymacdonald/dayForNightSFPC,quinkennedy/dayForNightSFPC,sh0w/recoded,sh0w/recoded,roymacdonald/dayForNightSFPC,ofZach/dayForNightSFPC,ofZach/dayForNightSFPC,sh0w/recoded,roymacdonald/dayForNightSFPC,ofZach/dayForNightSFPC,roymacdonald/dayForNightSFPC,quinkennedy/dayForNightSFPC,quinkennedy/dayForNightSFPC,quinkennedy/dayForNightSFPC,ofZach/dayForNightSFPC,sh0w/recoded
1a505baf302c5724ddf1573a886df9b2799af8b6
src/simplifier/PropagateEqualities.cpp
src/simplifier/PropagateEqualities.cpp
#include <string> #include "PropagateEqualities.h" #include "simplifier.h" #include "../AST/ArrayTransformer.h" namespace BEEV { /* The search functions look for variables that can be expressed in terms of variables. * The most obvious case it doesn't check for is NOT (OR (.. .. )). * I suspect this could take exponential time in the worst case, but on the benchmarks I've tested, * it finishes in reasonable time. * The obvious ways to speed it up (if required), are to create the RHS lazily. */ // The old XOR code used to use updateSolverMap instead of UpdateSubstitutionMap, I've no idea why. bool PropagateEqualities::searchXOR(const ASTNode& lhs, const ASTNode& rhs) { Kind k = lhs.GetKind(); if (k == SYMBOL) return simp->UpdateSubstitutionMap(lhs, rhs); // checks whether it's been solved for or loops. if (k == NOT) return searchXOR(lhs[0], nf->CreateNode(NOT, rhs)); bool result = false; if (k == XOR) for (int i = 0; i < lhs.Degree(); i++) { ASTVec others; for (int j = 0; j < lhs.Degree(); j++) if (j != i) others.push_back(lhs[j]); others.push_back(rhs); assert (others.size() > 1); ASTNode new_rhs = nf->CreateNode(XOR, others); result = searchXOR(lhs[i], new_rhs); if (result) return result; } if (k == EQ && lhs[0].GetValueWidth() ==1) { bool result = searchTerm(lhs[0], nf->CreateTerm(ITE, 1,rhs, lhs[1], nf->CreateTerm(BVNEG, 1,lhs[1]))); if (!result) result = searchTerm(lhs[1], nf->CreateTerm(ITE, 1,rhs, lhs[0], nf->CreateTerm(BVNEG, 1,lhs[0]))); } return result; } bool PropagateEqualities::searchTerm(const ASTNode& lhs, const ASTNode& rhs) { const int width = lhs.GetValueWidth(); if (lhs.GetKind() == SYMBOL) return simp->UpdateSubstitutionMap(lhs, rhs); // checks whether it's been solved for, or if the RHS contains the LHS. if (lhs.GetKind() == BVUMINUS) return searchTerm(lhs[0], nf->CreateTerm(BVUMINUS, width, rhs)); if (lhs.GetKind() == BVNEG) return searchTerm(lhs[0], nf->CreateTerm(BVNEG, width, rhs)); if (lhs.GetKind() == BVXOR || lhs.GetKind() == BVPLUS) for (int i = 0; i < lhs.Degree(); i++) { ASTVec others; for (int j = 0; j < lhs.Degree(); j++) if (j != i) others.push_back(lhs[j]); ASTNode new_rhs; if (lhs.GetKind() == BVXOR) { others.push_back(rhs); assert (others.size() > 1); new_rhs = nf->CreateTerm(lhs.GetKind(), width, others); } else if (lhs.GetKind() == BVPLUS) { if (others.size() >1) new_rhs = nf->CreateTerm(BVPLUS, width, others); else new_rhs = others[0]; new_rhs = nf->CreateTerm(BVUMINUS,width,new_rhs); new_rhs = nf->CreateTerm(BVPLUS,width,new_rhs, rhs); } else FatalError("sdafasfsdf2q3234423"); bool result = searchTerm(lhs[i], new_rhs); if (result) return true; } if (lhs.Degree() == 2 && lhs.GetKind() == BVMULT && lhs[0].isConstant() && simp->BVConstIsOdd(lhs[0])) return searchTerm(lhs[1], nf->CreateTerm(BVMULT, width, simp->MultiplicativeInverse(lhs[0]), rhs)); return false; } // This doesn't rewrite changes through properly so needs to have a substitution applied to its output. ASTNode PropagateEqualities::propagate(const ASTNode& a, ArrayTransformer*at) { ASTNode output; //if the variable has been solved for, then simply return it if (simp->CheckSubstitutionMap(a, output)) return output; if (!alreadyVisited.insert(a.GetNodeNum()).second) { return a; } output = a; //traverse a and populate the SubstitutionMap const Kind k = a.GetKind(); if (SYMBOL == k && BOOLEAN_TYPE == a.GetType()) { bool updated = simp->UpdateSubstitutionMap(a, ASTTrue); output = updated ? ASTTrue : a; } else if (NOT == k ) { bool updated = searchXOR(a[0], ASTFalse); output = updated ? ASTTrue : a; } else if (IFF == k || EQ == k) { const ASTVec& c = a.GetChildren(); if (c[0] == c[1]) return ASTTrue; bool updated = simp->UpdateSubstitutionMap(c[0], c[1]); if (updated) { //fill the arrayname readindices vector if e0 is a //READ(Arr,index) and index is a BVCONST int to; if ((to = TermOrder(c[0], c[1])) == 1 && c[0].GetKind() == READ) at->FillUp_ArrReadIndex_Vec(c[0], c[1]); else if (to == -1 && c[1].GetKind() == READ) at->FillUp_ArrReadIndex_Vec(c[1], c[0]); } if (!updated) updated = searchTerm(c[0],c[1]); if (!updated) updated = searchTerm(c[1],c[0]); output = updated ? ASTTrue : a; } else if (XOR == k) { bool updated = searchXOR(a, ASTTrue); output = updated ? ASTTrue : a; if (updated) return output; // The below block should be subsumed by the searchXOR function which generalises it. // So the below block should never do anything.. #ifndef NDEBUG if (a.Degree() != 2) return output; int to = TermOrder(a[0], a[1]); if (0 == to) { if (a[0].GetKind() == NOT && a[0][0].GetKind() == EQ && a[0][0][0].GetValueWidth() == 1 && a[0][0][1].GetKind() == SYMBOL) { // (XOR (NOT(= (1 v))) ... ) const ASTNode& symbol = a[0][0][1]; const ASTNode newN = nf->CreateTerm(ITE, 1, a[1], a[0][0][0], nf->CreateTerm(BVNEG, 1, a[0][0][0])); if (simp->UpdateSolverMap(symbol, newN)) { assert(false); output = ASTTrue; } } else if (a[1].GetKind() == NOT && a[1][0].GetKind() == EQ && a[1][0][0].GetValueWidth() == 1 && a[1][0][1].GetKind() == SYMBOL) { const ASTNode& symbol = a[1][0][1]; const ASTNode newN = nf->CreateTerm(ITE, 1, a[0], a[1][0][0], nf->CreateTerm(BVNEG, 1, a[1][0][0])); if (simp->UpdateSolverMap(symbol, newN)) { assert(false); output = ASTTrue; } } else if (a[0].GetKind() == EQ && a[0][0].GetValueWidth() == 1 && a[0][1].GetKind() == SYMBOL) { // XOR ((= 1 v) ... ) const ASTNode& symbol = a[0][1]; const ASTNode newN = nf->CreateTerm(ITE, 1, a[1], nf->CreateTerm(BVNEG, 1, a[0][0]), a[0][0]); if (simp->UpdateSolverMap(symbol, newN)) { assert(false); output = ASTTrue; } } else if (a[1].GetKind() == EQ && a[1][0].GetValueWidth() == 1 && a[1][1].GetKind() == SYMBOL) { const ASTNode& symbol = a[1][1]; const ASTNode newN = nf->CreateTerm(ITE, 1, a[0], nf->CreateTerm(BVNEG, 1, a[1][0]), a[1][0]); if (simp->UpdateSolverMap(symbol, newN)) { assert(false); output = ASTTrue; } } else return output; } else { ASTNode symbol, rhs; if (to == 1) { symbol = a[0]; rhs = a[1]; } else { symbol = a[1]; rhs = a[0]; } assert(symbol.GetKind() == SYMBOL); if (simp->UpdateSolverMap(symbol, nf->CreateNode(NOT, rhs))) { assert(false); output = ASTTrue; } } #endif } else if (AND == k) { const ASTVec& c = a.GetChildren(); ASTVec o; o.reserve(c.size()); for (ASTVec::const_iterator it = c.begin(), itend = c.end(); it != itend; it++) { if (always_true) simp->UpdateAlwaysTrueFormSet(*it); ASTNode aaa = propagate(*it, at); if (ASTTrue != aaa) { if (ASTFalse == aaa) return ASTFalse; else o.push_back(aaa); } } if (o.size() == 0) output = ASTTrue; else if (o.size() == 1) output = o[0]; else if (o != c) output = nf->CreateNode(AND, o); else output = a; } return output; } //end of CreateSubstitutionMap() } ;
#include <string> #include "PropagateEqualities.h" #include "simplifier.h" #include "../AST/ArrayTransformer.h" namespace BEEV { /* The search functions look for variables that can be expressed in terms of variables. * The most obvious case it doesn't check for is NOT (OR (.. .. )). * I suspect this could take exponential time in the worst case, but on the benchmarks I've tested, * it finishes in reasonable time. * The obvious ways to speed it up (if required), are to create the RHS lazily. */ // The old XOR code used to use updateSolverMap instead of UpdateSubstitutionMap, I've no idea why. bool PropagateEqualities::searchXOR(const ASTNode& lhs, const ASTNode& rhs) { Kind k = lhs.GetKind(); if (k == SYMBOL) { if (lhs == rhs) return true; return simp->UpdateSubstitutionMap(lhs, rhs); // checks whether it's been solved for or loops. } if (k == NOT) return searchXOR(lhs[0], nf->CreateNode(NOT, rhs)); bool result = false; if (k == XOR) for (int i = 0; i < lhs.Degree(); i++) { ASTVec others; for (int j = 0; j < lhs.Degree(); j++) if (j != i) others.push_back(lhs[j]); others.push_back(rhs); assert (others.size() > 1); ASTNode new_rhs = nf->CreateNode(XOR, others); result = searchXOR(lhs[i], new_rhs); if (result) return result; } if (k == EQ && lhs[0].GetValueWidth() ==1) { bool result = searchTerm(lhs[0], nf->CreateTerm(ITE, 1,rhs, lhs[1], nf->CreateTerm(BVNEG, 1,lhs[1]))); if (!result) result = searchTerm(lhs[1], nf->CreateTerm(ITE, 1,rhs, lhs[0], nf->CreateTerm(BVNEG, 1,lhs[0]))); } return result; } bool PropagateEqualities::searchTerm(const ASTNode& lhs, const ASTNode& rhs) { const int width = lhs.GetValueWidth(); if (lhs.GetKind() == SYMBOL) { if (lhs == rhs) return true; return simp->UpdateSubstitutionMap(lhs, rhs); // checks whether it's been solved for, or if the RHS contains the LHS. } if (lhs.GetKind() == BVUMINUS) return searchTerm(lhs[0], nf->CreateTerm(BVUMINUS, width, rhs)); if (lhs.GetKind() == BVNEG) return searchTerm(lhs[0], nf->CreateTerm(BVNEG, width, rhs)); if (lhs.GetKind() == BVXOR || lhs.GetKind() == BVPLUS) for (int i = 0; i < lhs.Degree(); i++) { ASTVec others; for (int j = 0; j < lhs.Degree(); j++) if (j != i) others.push_back(lhs[j]); ASTNode new_rhs; if (lhs.GetKind() == BVXOR) { others.push_back(rhs); assert (others.size() > 1); new_rhs = nf->CreateTerm(lhs.GetKind(), width, others); } else if (lhs.GetKind() == BVPLUS) { if (others.size() >1) new_rhs = nf->CreateTerm(BVPLUS, width, others); else new_rhs = others[0]; new_rhs = nf->CreateTerm(BVUMINUS,width,new_rhs); new_rhs = nf->CreateTerm(BVPLUS,width,new_rhs, rhs); } else FatalError("sdafasfsdf2q3234423"); bool result = searchTerm(lhs[i], new_rhs); if (result) return true; } if (lhs.Degree() == 2 && lhs.GetKind() == BVMULT && lhs[0].isConstant() && simp->BVConstIsOdd(lhs[0])) return searchTerm(lhs[1], nf->CreateTerm(BVMULT, width, simp->MultiplicativeInverse(lhs[0]), rhs)); return false; } // This doesn't rewrite changes through properly so needs to have a substitution applied to its output. ASTNode PropagateEqualities::propagate(const ASTNode& a, ArrayTransformer*at) { ASTNode output; //if the variable has been solved for, then simply return it if (simp->CheckSubstitutionMap(a, output)) return output; if (!alreadyVisited.insert(a.GetNodeNum()).second) { return a; } output = a; //traverse a and populate the SubstitutionMap const Kind k = a.GetKind(); if (SYMBOL == k && BOOLEAN_TYPE == a.GetType()) { bool updated = simp->UpdateSubstitutionMap(a, ASTTrue); output = updated ? ASTTrue : a; } else if (NOT == k ) { bool updated = searchXOR(a[0], ASTFalse); output = updated ? ASTTrue : a; } else if (IFF == k || EQ == k) { const ASTVec& c = a.GetChildren(); if (c[0] == c[1]) return ASTTrue; bool updated = simp->UpdateSubstitutionMap(c[0], c[1]); if (updated) { //fill the arrayname readindices vector if e0 is a //READ(Arr,index) and index is a BVCONST int to; if ((to = TermOrder(c[0], c[1])) == 1 && c[0].GetKind() == READ) at->FillUp_ArrReadIndex_Vec(c[0], c[1]); else if (to == -1 && c[1].GetKind() == READ) at->FillUp_ArrReadIndex_Vec(c[1], c[0]); } if (!updated) updated = searchTerm(c[0],c[1]); if (!updated) updated = searchTerm(c[1],c[0]); output = updated ? ASTTrue : a; } else if (XOR == k) { bool updated = searchXOR(a, ASTTrue); output = updated ? ASTTrue : a; if (updated) return output; // The below block should be subsumed by the searchXOR function which generalises it. // So the below block should never do anything.. #ifndef NDEBUG if (a.Degree() != 2) return output; int to = TermOrder(a[0], a[1]); if (0 == to) { if (a[0].GetKind() == NOT && a[0][0].GetKind() == EQ && a[0][0][0].GetValueWidth() == 1 && a[0][0][1].GetKind() == SYMBOL) { // (XOR (NOT(= (1 v))) ... ) const ASTNode& symbol = a[0][0][1]; const ASTNode newN = nf->CreateTerm(ITE, 1, a[1], a[0][0][0], nf->CreateTerm(BVNEG, 1, a[0][0][0])); if (simp->UpdateSolverMap(symbol, newN)) { assert(false); output = ASTTrue; } } else if (a[1].GetKind() == NOT && a[1][0].GetKind() == EQ && a[1][0][0].GetValueWidth() == 1 && a[1][0][1].GetKind() == SYMBOL) { const ASTNode& symbol = a[1][0][1]; const ASTNode newN = nf->CreateTerm(ITE, 1, a[0], a[1][0][0], nf->CreateTerm(BVNEG, 1, a[1][0][0])); if (simp->UpdateSolverMap(symbol, newN)) { assert(false); output = ASTTrue; } } else if (a[0].GetKind() == EQ && a[0][0].GetValueWidth() == 1 && a[0][1].GetKind() == SYMBOL) { // XOR ((= 1 v) ... ) const ASTNode& symbol = a[0][1]; const ASTNode newN = nf->CreateTerm(ITE, 1, a[1], nf->CreateTerm(BVNEG, 1, a[0][0]), a[0][0]); if (simp->UpdateSolverMap(symbol, newN)) { assert(false); output = ASTTrue; } } else if (a[1].GetKind() == EQ && a[1][0].GetValueWidth() == 1 && a[1][1].GetKind() == SYMBOL) { const ASTNode& symbol = a[1][1]; const ASTNode newN = nf->CreateTerm(ITE, 1, a[0], nf->CreateTerm(BVNEG, 1, a[1][0]), a[1][0]); if (simp->UpdateSolverMap(symbol, newN)) { assert(false); output = ASTTrue; } } else return output; } else { ASTNode symbol, rhs; if (to == 1) { symbol = a[0]; rhs = a[1]; } else { symbol = a[1]; rhs = a[0]; } assert(symbol.GetKind() == SYMBOL); if (simp->UpdateSolverMap(symbol, nf->CreateNode(NOT, rhs))) { assert(false); output = ASTTrue; } } #endif } else if (AND == k) { const ASTVec& c = a.GetChildren(); ASTVec o; o.reserve(c.size()); for (ASTVec::const_iterator it = c.begin(), itend = c.end(); it != itend; it++) { if (always_true) simp->UpdateAlwaysTrueFormSet(*it); ASTNode aaa = propagate(*it, at); if (ASTTrue != aaa) { if (ASTFalse == aaa) return ASTFalse; else o.push_back(aaa); } } if (o.size() == 0) output = ASTTrue; else if (o.size() == 1) output = o[0]; else if (o != c) output = nf->CreateNode(AND, o); else output = a; } return output; } //end of CreateSubstitutionMap() } ;
Fix an assertion error.
Fix an assertion error. git-svn-id: 5069ba8be4c997ee907bf46f8ec9a2bbfb655637@1535 e59a4935-1847-0410-ae03-e826735625c1
C++
mit
linpc/STP,linpc/STP,linpc/STP,linpc/STP,linpc/STP
e1e055e6e932e671fcd73ca0104f99b3a171e01e
Modules/DiffusionImaging/DiffusionCore/Algorithms/Registration/mitkDWIHeadMotionCorrectionFilter.cpp
Modules/DiffusionImaging/DiffusionCore/Algorithms/Registration/mitkDWIHeadMotionCorrectionFilter.cpp
/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef MITKDIFFUSIONIMAGETODIFFUSIONIMAGEFILTER_CPP #define MITKDIFFUSIONIMAGETODIFFUSIONIMAGEFILTER_CPP #include "mitkDWIHeadMotionCorrectionFilter.h" #include "itkSplitDWImageFilter.h" #include "itkB0ImageExtractionToSeparateImageFilter.h" #include "mitkImageTimeSelector.h" #include "mitkPyramidImageRegistrationMethod.h" #include "mitkImageToDiffusionImageSource.h" #include "mitkIOUtil.h" template< typename DiffusionPixelType> mitk::DWIHeadMotionCorrectionFilter<DiffusionPixelType> ::DWIHeadMotionCorrectionFilter() { } template< typename DiffusionPixelType> void mitk::DWIHeadMotionCorrectionFilter<DiffusionPixelType> ::GenerateData() { typedef itk::SplitDWImageFilter< DiffusionPixelType, DiffusionPixelType> SplitFilterType; DiffusionImageType* input = const_cast<DiffusionImageType*>(this->GetInput(0)); // // (1) Extract the b-zero images to a 3d+t image, register them by NCorr metric and // rigid registration : they will then be used are reference image for registering // the gradient images // typedef itk::B0ImageExtractionToSeparateImageFilter< DiffusionPixelType, DiffusionPixelType> B0ExtractorType; typename B0ExtractorType::Pointer b0_extractor = B0ExtractorType::New(); b0_extractor->SetInput( input->GetVectorImage() ); b0_extractor->SetDirections( input->GetDirections() ); b0_extractor->Update(); mitk::Image::Pointer b0Image = mitk::Image::New(); b0Image->InitializeByItk( b0_extractor->GetOutput() ); b0Image->SetImportChannel( b0_extractor->GetOutput()->GetBufferPointer(), mitk::Image::CopyMemory ); // (2.1) Use the extractor to access the extracted b0 volumes mitk::ImageTimeSelector::Pointer t_selector = mitk::ImageTimeSelector::New(); t_selector->SetInput( b0Image ); t_selector->SetTimeNr(0); t_selector->Update(); // first unweighted image as reference space for the registration mitk::Image::Pointer b0referenceImage = t_selector->GetOutput(); mitk::PyramidImageRegistrationMethod::Pointer registrationMethod = mitk::PyramidImageRegistrationMethod::New(); registrationMethod->SetFixedImage( b0referenceImage ); registrationMethod->SetTransformToRigid(); // the unweighted images are of same modality registrationMethod->SetCrossModalityOff(); // Initialize the temporary output image mitk::Image::Pointer registeredB0Image = b0Image->Clone(); const unsigned int numberOfb0Images = b0Image->GetTimeSteps(); mitk::ImageTimeSelector::Pointer t_selector2 = mitk::ImageTimeSelector::New(); t_selector2->SetInput( b0Image ); for( unsigned int i=1; i<numberOfb0Images; i++) { t_selector2->SetTimeNr(i); t_selector2->Update(); registrationMethod->SetMovingImage( t_selector2->GetOutput() ); try { MITK_INFO << " === (" << i <<"/"<< numberOfb0Images-1 << ") :: Starting registration"; registrationMethod->Update(); } catch( const itk::ExceptionObject& e) { mitkThrow() << "Failed to register the b0 images, the PyramidRegistration threw an exception: \n" << e.what(); } // import volume to the inter-results registeredB0Image->SetImportVolume( registrationMethod->GetResampledMovingImage()->GetData(), i, 0, mitk::Image::ReferenceMemory ); } // // (2) Split the diffusion image into a 3d+t regular image, extract only the weighted images // typename SplitFilterType::Pointer split_filter = SplitFilterType::New(); split_filter->SetInput (input->GetVectorImage() ); split_filter->SetExtractAllAboveThreshold(20, input->GetB_ValueMap() ); try { split_filter->Update(); } catch( const itk::ExceptionObject &e) { mitkThrow() << " Caught exception from SplitImageFilter : " << e.what(); } mitk::Image::Pointer splittedImage = mitk::Image::New(); splittedImage->InitializeByItk( split_filter->GetOutput() ); splittedImage->SetImportChannel( split_filter->GetOutput()->GetBufferPointer(), mitk::Image::CopyMemory ); // // (3) Use again the time-selector to access the components separately in order // to perform the registration of Image -> unweighted reference // mitk::PyramidImageRegistrationMethod::Pointer weightedRegistrationMethod = mitk::PyramidImageRegistrationMethod::New(); weightedRegistrationMethod->SetTransformToAffine(); weightedRegistrationMethod->SetCrossModalityOn(); // // - (3.1) Create a reference image by averaging the aligned b0 images // // !!!FIXME: For rapid prototyping using the first one // weightedRegistrationMethod->SetFixedImage( b0referenceImage ); // // - (3.2) Register all timesteps in the splitted image onto the first reference // unsigned int maxImageIdx = splittedImage->GetTimeSteps(); mitk::TimeSlicedGeometry* tsg = splittedImage->GetTimeSlicedGeometry(); tsg->ExpandToNumberOfTimeSteps( maxImageIdx+1 ); mitk::Image::Pointer registeredWeighted = mitk::Image::New(); registeredWeighted->Initialize( splittedImage->GetPixelType(0), *tsg ); // insert the first unweighted reference as the first volume registeredWeighted->SetImportVolume( b0referenceImage->GetData(), 0,0, mitk::Image::CopyMemory ); // mitk::Image::Pointer registeredWeighted = splittedImage->Clone(); // this time start at 0, we have only gradient images in the 3d+t file // the reference image comes form an other image mitk::ImageTimeSelector::Pointer t_selector_w = mitk::ImageTimeSelector::New(); t_selector_w->SetInput( splittedImage ); for( unsigned int i=0; i<maxImageIdx; i++) { t_selector_w->SetTimeNr(i); t_selector_w->Update(); weightedRegistrationMethod->SetMovingImage( t_selector_w->GetOutput() ); try { MITK_INFO << " === (" << i+1 <<"/"<< maxImageIdx << ") :: Starting registration"; weightedRegistrationMethod->Update(); } catch( const itk::ExceptionObject& e) { mitkThrow() << "Failed to register the b0 images, the PyramidRegistration threw an exception: \n" << e.what(); } // allow expansion registeredWeighted->SetImportVolume( weightedRegistrationMethod->GetResampledMovingImage()->GetData(), i+1, 0, mitk::Image::CopyMemory); } // // (4) Cast the resulting image back to an diffusion weighted image // typename DiffusionImageType::GradientDirectionContainerType *gradients = input->GetDirections(); typename DiffusionImageType::GradientDirectionContainerType::Pointer gradients_new = DiffusionImageType::GradientDirectionContainerType::New(); typename DiffusionImageType::GradientDirectionType bzero_vector; bzero_vector.fill(0); // compose the direction vector // - no direction for the first image // - correct ordering of the directions based on the index list gradients_new->push_back( bzero_vector ); typename SplitFilterType::IndexListType index_list = split_filter->GetIndexList(); typename SplitFilterType::IndexListType::const_iterator lIter = index_list.begin(); while( lIter != index_list.end() ) { gradients_new->push_back( gradients->at( *lIter ) ); ++lIter; } typename mitk::ImageToDiffusionImageSource< DiffusionPixelType >::Pointer caster = mitk::ImageToDiffusionImageSource< DiffusionPixelType >::New(); caster->SetImage( registeredWeighted ); caster->SetBValue( input->GetB_Value() ); caster->SetGradientDirections( gradients_new.GetPointer() ); try { caster->Update(); } catch( const itk::ExceptionObject& e) { MITK_ERROR << "Casting back to diffusion image failed: "; mitkThrow() << "Subprocess failed with exception: " << e.what(); } OutputImagePointerType output = this->GetOutput(); output = caster->GetOutput(); } template< typename DiffusionPixelType> void mitk::DWIHeadMotionCorrectionFilter<DiffusionPixelType> ::GenerateOutputInformation() { if( ! this->GetInput(0) ) { mitkThrow() << "No input specified!"; } } #endif // MITKDIFFUSIONIMAGETODIFFUSIONIMAGEFILTER_CPP
/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef MITKDIFFUSIONIMAGETODIFFUSIONIMAGEFILTER_CPP #define MITKDIFFUSIONIMAGETODIFFUSIONIMAGEFILTER_CPP #include "mitkDWIHeadMotionCorrectionFilter.h" #include "itkSplitDWImageFilter.h" #include "itkB0ImageExtractionToSeparateImageFilter.h" #include "mitkImageTimeSelector.h" #include "mitkPyramidImageRegistrationMethod.h" #include "mitkImageToDiffusionImageSource.h" #include "mitkIOUtil.h" template< typename DiffusionPixelType> mitk::DWIHeadMotionCorrectionFilter<DiffusionPixelType> ::DWIHeadMotionCorrectionFilter() { } template< typename DiffusionPixelType> void mitk::DWIHeadMotionCorrectionFilter<DiffusionPixelType> ::GenerateData() { typedef itk::SplitDWImageFilter< DiffusionPixelType, DiffusionPixelType> SplitFilterType; DiffusionImageType* input = const_cast<DiffusionImageType*>(this->GetInput(0)); // // (1) Extract the b-zero images to a 3d+t image, register them by NCorr metric and // rigid registration : they will then be used are reference image for registering // the gradient images // typedef itk::B0ImageExtractionToSeparateImageFilter< DiffusionPixelType, DiffusionPixelType> B0ExtractorType; typename B0ExtractorType::Pointer b0_extractor = B0ExtractorType::New(); b0_extractor->SetInput( input->GetVectorImage() ); b0_extractor->SetDirections( input->GetDirections() ); b0_extractor->Update(); mitk::Image::Pointer b0Image = mitk::Image::New(); b0Image->InitializeByItk( b0_extractor->GetOutput() ); b0Image->SetImportChannel( b0_extractor->GetOutput()->GetBufferPointer(), mitk::Image::CopyMemory ); // (2.1) Use the extractor to access the extracted b0 volumes mitk::ImageTimeSelector::Pointer t_selector = mitk::ImageTimeSelector::New(); t_selector->SetInput( b0Image ); t_selector->SetTimeNr(0); t_selector->Update(); // first unweighted image as reference space for the registration mitk::Image::Pointer b0referenceImage = t_selector->GetOutput(); mitk::PyramidImageRegistrationMethod::Pointer registrationMethod = mitk::PyramidImageRegistrationMethod::New(); registrationMethod->SetFixedImage( b0referenceImage ); registrationMethod->SetTransformToRigid(); // the unweighted images are of same modality registrationMethod->SetCrossModalityOff(); // Initialize the temporary output image mitk::Image::Pointer registeredB0Image = b0Image->Clone(); const unsigned int numberOfb0Images = b0Image->GetTimeSteps(); mitk::ImageTimeSelector::Pointer t_selector2 = mitk::ImageTimeSelector::New(); t_selector2->SetInput( b0Image ); for( unsigned int i=1; i<numberOfb0Images; i++) { t_selector2->SetTimeNr(i); t_selector2->Update(); registrationMethod->SetMovingImage( t_selector2->GetOutput() ); try { MITK_INFO << " === (" << i <<"/"<< numberOfb0Images-1 << ") :: Starting registration"; registrationMethod->Update(); } catch( const itk::ExceptionObject& e) { mitkThrow() << "Failed to register the b0 images, the PyramidRegistration threw an exception: \n" << e.what(); } // import volume to the inter-results registeredB0Image->SetImportVolume( registrationMethod->GetResampledMovingImage()->GetData(), i, 0, mitk::Image::ReferenceMemory ); } // // (2) Split the diffusion image into a 3d+t regular image, extract only the weighted images // typename SplitFilterType::Pointer split_filter = SplitFilterType::New(); split_filter->SetInput (input->GetVectorImage() ); split_filter->SetExtractAllAboveThreshold(20, input->GetB_ValueMap() ); try { split_filter->Update(); } catch( const itk::ExceptionObject &e) { mitkThrow() << " Caught exception from SplitImageFilter : " << e.what(); } mitk::Image::Pointer splittedImage = mitk::Image::New(); splittedImage->InitializeByItk( split_filter->GetOutput() ); splittedImage->SetImportChannel( split_filter->GetOutput()->GetBufferPointer(), mitk::Image::CopyMemory ); // // (3) Use again the time-selector to access the components separately in order // to perform the registration of Image -> unweighted reference // mitk::PyramidImageRegistrationMethod::Pointer weightedRegistrationMethod = mitk::PyramidImageRegistrationMethod::New(); weightedRegistrationMethod->SetTransformToAffine(); weightedRegistrationMethod->SetCrossModalityOn(); // // - (3.1) Create a reference image by averaging the aligned b0 images // // !!!FIXME: For rapid prototyping using the first one // weightedRegistrationMethod->SetFixedImage( b0referenceImage ); // // - (3.2) Register all timesteps in the splitted image onto the first reference // unsigned int maxImageIdx = splittedImage->GetTimeSteps(); mitk::TimeSlicedGeometry* tsg = splittedImage->GetTimeSlicedGeometry(); tsg->ExpandToNumberOfTimeSteps( maxImageIdx+1 ); mitk::Image::Pointer registeredWeighted = mitk::Image::New(); registeredWeighted->Initialize( splittedImage->GetPixelType(0), *tsg ); // insert the first unweighted reference as the first volume registeredWeighted->SetImportVolume( b0referenceImage->GetData(), 0,0, mitk::Image::CopyMemory ); // mitk::Image::Pointer registeredWeighted = splittedImage->Clone(); // this time start at 0, we have only gradient images in the 3d+t file // the reference image comes form an other image mitk::ImageTimeSelector::Pointer t_selector_w = mitk::ImageTimeSelector::New(); t_selector_w->SetInput( splittedImage ); for( unsigned int i=0; i<maxImageIdx; i++) { t_selector_w->SetTimeNr(i); t_selector_w->Update(); weightedRegistrationMethod->SetMovingImage( t_selector_w->GetOutput() ); try { MITK_INFO << " === (" << i+1 <<"/"<< maxImageIdx << ") :: Starting registration"; weightedRegistrationMethod->Update(); } catch( const itk::ExceptionObject& e) { mitkThrow() << "Failed to register the b0 images, the PyramidRegistration threw an exception: \n" << e.what(); } // allow expansion registeredWeighted->SetImportVolume( weightedRegistrationMethod->GetResampledMovingImage()->GetData(), i+1, 0, mitk::Image::CopyMemory); } // // (4) Cast the resulting image back to an diffusion weighted image // typename DiffusionImageType::GradientDirectionContainerType *gradients = input->GetDirections(); typename DiffusionImageType::GradientDirectionContainerType::Pointer gradients_new = DiffusionImageType::GradientDirectionContainerType::New(); typename DiffusionImageType::GradientDirectionType bzero_vector; bzero_vector.fill(0); // compose the direction vector // - no direction for the first image // - correct ordering of the directions based on the index list gradients_new->push_back( bzero_vector ); typename SplitFilterType::IndexListType index_list = split_filter->GetIndexList(); typename SplitFilterType::IndexListType::const_iterator lIter = index_list.begin(); while( lIter != index_list.end() ) { gradients_new->push_back( gradients->at( *lIter ) ); ++lIter; } typename mitk::ImageToDiffusionImageSource< DiffusionPixelType >::Pointer caster = mitk::ImageToDiffusionImageSource< DiffusionPixelType >::New(); caster->SetImage( registeredWeighted ); caster->SetBValue( input->GetB_Value() ); caster->SetGradientDirections( gradients_new.GetPointer() ); try { caster->Update(); } catch( const itk::ExceptionObject& e) { MITK_ERROR << "Casting back to diffusion image failed: "; mitkThrow() << "Subprocess failed with exception: " << e.what(); } OutputImagePointerType output = this->GetOutput(); output = caster->GetOutput(); std::cout << "Last line : Generate Data " << std::endl; } template< typename DiffusionPixelType> void mitk::DWIHeadMotionCorrectionFilter<DiffusionPixelType> ::GenerateOutputInformation() { if( ! this->GetInput(0) ) { mitkThrow() << "No input specified!"; } OutputImagePointerType output = this->GetOutput(); output->CopyInformation( this->GetInput(0) ); } #endif // MITKDIFFUSIONIMAGETODIFFUSIONIMAGEFILTER_CPP
Enhance generate output
Enhance generate output
C++
bsd-3-clause
NifTK/MITK,fmilano/mitk,RabadanLab/MITKats,rfloca/MITK,danielknorr/MITK,rfloca/MITK,iwegner/MITK,iwegner/MITK,lsanzdiaz/MITK-BiiG,RabadanLab/MITKats,lsanzdiaz/MITK-BiiG,danielknorr/MITK,nocnokneo/MITK,fmilano/mitk,fmilano/mitk,nocnokneo/MITK,RabadanLab/MITKats,danielknorr/MITK,RabadanLab/MITKats,MITK/MITK,danielknorr/MITK,MITK/MITK,nocnokneo/MITK,lsanzdiaz/MITK-BiiG,lsanzdiaz/MITK-BiiG,danielknorr/MITK,MITK/MITK,NifTK/MITK,NifTK/MITK,iwegner/MITK,nocnokneo/MITK,rfloca/MITK,rfloca/MITK,iwegner/MITK,iwegner/MITK,iwegner/MITK,nocnokneo/MITK,lsanzdiaz/MITK-BiiG,danielknorr/MITK,MITK/MITK,nocnokneo/MITK,RabadanLab/MITKats,nocnokneo/MITK,rfloca/MITK,lsanzdiaz/MITK-BiiG,RabadanLab/MITKats,lsanzdiaz/MITK-BiiG,fmilano/mitk,fmilano/mitk,NifTK/MITK,danielknorr/MITK,lsanzdiaz/MITK-BiiG,NifTK/MITK,rfloca/MITK,MITK/MITK,rfloca/MITK,fmilano/mitk,MITK/MITK,fmilano/mitk,NifTK/MITK
b29a602ee00cc2e8553d0e4acfe30b32f88fa7bb
libraries/chain/include/eosio/chain/webassembly/eos-vm.hpp
libraries/chain/include/eosio/chain/webassembly/eos-vm.hpp
#pragma once #include <eosio/chain/webassembly/common.hpp> #include <eosio/chain/webassembly/runtime_interface.hpp> #include <eosio/chain/exceptions.hpp> #include <eosio/chain/apply_context.hpp> #include <softfloat_types.h> //eos-vm includes /* #include <eosio/vm/host_function.hpp> namespace eosio { namespace vm { template <> struct registered_host_functions<eosio::chain::apply_context>; } } */ #include <eosio/vm/backend.hpp> // eosio specific specializations namespace eosio { namespace vm { template <typename T, std::size_t Align> struct aligned_array_wrapper { static_assert(Align % alignof(T) == 0, "Must align to at least the alignment of T"); aligned_array_wrapper(void* ptr, uint32_t size) : ptr(ptr), size(size) { if (reinterpret_cast<std::uintptr_t>(ptr) % Align != 0) { copy.reset(new std::remove_cv_t<T>[size]); memcpy( copy.get(), ptr, sizeof(T) * size ); } } ~aligned_array_wrapper() { if constexpr (!std::is_const_v<T>) if (copy) memcpy( ptr, copy.get(), sizeof(T) * size); } constexpr operator T*() const { if (copy) return copy.get(); else return static_cast<T*>(ptr); } constexpr operator eosio::chain::array_ptr<T>() const { return eosio::chain::array_ptr<T>{static_cast<T*>(*this)}; } void* ptr; std::unique_ptr<std::remove_cv_t<T>[]> copy = nullptr; std::size_t size; }; template<> struct wasm_type_converter<eosio::chain::name> { static auto from_wasm(uint64_t val) { return eosio::chain::name{val}; } static auto to_wasm(eosio::chain::name val) { return val.to_uint64_t(); } }; template<typename T> struct wasm_type_converter<T*> { static auto from_wasm(void* val) { return eosio::vm::aligned_ptr_wrapper<T, alignof(T)>{val}; } }; template<typename T> struct wasm_type_converter<T&> { static auto from_wasm(void* val) { return eosio::vm::aligned_ref_wrapper<T, alignof(T)>{val}; } }; template<typename T> struct wasm_type_converter<eosio::chain::array_ptr<T>> { static auto from_wasm(void* ptr, uint32_t size) { return aligned_array_wrapper<T, alignof(T)>(ptr, size); } }; template<> struct wasm_type_converter<eosio::chain::array_ptr<char>> { static auto from_wasm(void* ptr, uint32_t /*size*/) { return eosio::chain::array_ptr<char>((char*)ptr); } // memcpy/memmove static auto from_wasm(void* ptr, eosio::chain::array_ptr<const char> /*src*/, uint32_t /*size*/) { return eosio::chain::array_ptr<char>((char*)ptr); } // memset static auto from_wasm(void* ptr, int /*val*/, uint32_t /*size*/) { return eosio::chain::array_ptr<char>((char*)ptr); } }; template<> struct wasm_type_converter<eosio::chain::array_ptr<const char>> { static auto from_wasm(void* ptr, uint32_t /*size*/) { return eosio::chain::array_ptr<const char>((char*)ptr); } // memcmp static auto from_wasm(void* ptr, eosio::chain::array_ptr<const char> /*src*/, uint32_t /*size*/) { return eosio::chain::array_ptr<const char>((char*)ptr); } }; template <typename Ctx> struct construct_derived<eosio::chain::transaction_context, Ctx> { static auto &value(Ctx& ctx) { return ctx.trx_context; } }; template <> struct construct_derived<eosio::chain::apply_context, eosio::chain::apply_context> { static auto &value(eosio::chain::apply_context& ctx) { return ctx; } }; template<> struct wasm_type_converter<eosio::chain::null_terminated_ptr> { static auto from_wasm(char* ptr) { return eosio::chain::null_terminated_ptr{ ptr }; } }; }} // ns eosio::vm #if 0 namespace eosio { namespace vm { template <typename WAlloc, typename Cls, typename Cls2, auto F, typename R, typename Args, size_t... Is> auto create_logging_function(std::index_sequence<Is...>) { return std::function<void(Cls*, WAlloc*, operand_stack&)>{ [](Cls* self, WAlloc* walloc, operand_stack& os) { size_t i = sizeof...(Is) - 1; auto& intrinsic_log = self->control.get_intrinsic_debug_log(); /* if (intrinsic_log) { eosio::chain::digest_type::encoder enc; enc.write(walloc->template get_base_ptr<char>(), walloc->get_current_page() * 64 * 1024); intrinsic_log->record_intrinsic( eosio::chain::calc_arguments_hash( get_value<typename std::tuple_element<Is, Args>::type, Args>( walloc, get_value<to_wasm_t<typename std::tuple_element<Is, Args>::type>>()))...); os.get_back(i - Is)))...), enc.result()); } */ if constexpr (!std::is_same_v<R, void>) { if constexpr (std::is_same_v<Cls2, std::nullptr_t>) { R res = std::invoke(F, get_value<typename std::tuple_element<Is, Args>::type, Args>( walloc, std::move(os.get_back(i - Is).get<to_wasm_t<typename std::tuple_element<Is, Args>::type>>()))...); os.trim(sizeof...(Is)); os.push(resolve_result<R>(std::move(res), walloc)); } else { R res = std::invoke(F, construct_derived<Cls2, Cls>::value(*self), get_value<typename std::tuple_element<Is, Args>::type, Args>( walloc, std::move(os.get_back(i - Is).get<to_wasm_t<typename std::tuple_element<Is, Args>::type>>()))...); os.trim(sizeof...(Is)); os.push(resolve_result<R>(std::move(res), walloc)); } } else { if constexpr (std::is_same_v<Cls2, std::nullptr_t>) { std::invoke(F, get_value<typename std::tuple_element<Is, Args>::type, Args>( walloc, std::move(os.get_back(i - Is).get<to_wasm_t<typename std::tuple_element<Is, Args>::type>>()))...); } else { std::invoke(F, construct_derived<Cls2, Cls>::value(*self), get_value<typename std::tuple_element<Is, Args>::type, Args>( walloc, std::move(os.get_back(i - Is).get<to_wasm_t<typename std::tuple_element<Is, Args>::type>>()))...); } os.trim(sizeof...(Is)); } } }; } template <> struct registered_host_functions<eosio::chain::apply_context> { using Cls = eosio::chain::apply_context; template <typename WAlloc> struct mappings { std::unordered_map<std::pair<std::string, std::string>, uint32_t, host_func_pair_hash> named_mapping; std::vector<host_function> host_functions; std::vector<std::function<void(Cls*, WAlloc*, operand_stack&)>> functions; size_t current_index = 0; }; template <typename WAlloc> static mappings<WAlloc>& get_mappings() { static mappings<WAlloc> _mappings; return _mappings; } template <typename Cls2, auto Func, typename WAlloc> static void add(const std::string& mod, const std::string& name) { using deduced_full_ts = decltype(get_args_full(Func)); using deduced_ts = decltype(get_args(Func)); using res_t = typename decltype(get_return_t(Func))::type; static constexpr auto is = std::make_index_sequence<std::tuple_size<deduced_ts>::value>(); auto& current_mappings = get_mappings<WAlloc>(); current_mappings.named_mapping[{ mod, name }] = current_mappings.current_index++; current_mappings.functions.push_back(create_logging_function<WAlloc, Cls, Cls2, Func, res_t, deduced_full_ts>(is)); } template <typename Module> static void resolve(Module& mod) { decltype(mod.import_functions) imports = { mod.allocator, mod.get_imported_functions_size() }; auto& current_mappings = get_mappings<wasm_allocator>(); for (int i = 0; i < mod.imports.size(); i++) { std::string mod_name = std::string((char*)mod.imports[i].module_str.raw(), mod.imports[i].module_str.size()); std::string fn_name = std::string((char*)mod.imports[i].field_str.raw(), mod.imports[i].field_str.size()); EOS_WB_ASSERT(current_mappings.named_mapping.count({ mod_name, fn_name }), wasm_link_exception, "no mapping for imported function"); imports[i] = current_mappings.named_mapping[{ mod_name, fn_name }]; } mod.import_functions = std::move(imports); } template <typename Execution_Context> void operator()(Cls* host, Execution_Context& ctx, uint32_t index) { const auto& _func = get_mappings<wasm_allocator>().functions[index]; std::invoke(_func, host, ctx.get_wasm_allocator(), ctx.get_operand_stack()); } }; } } // eosio::vm #endif namespace eosio { namespace chain { namespace webassembly { namespace eos_vm_runtime { using namespace fc; using namespace eosio::vm; using namespace eosio::chain::webassembly::common; template<typename Backend> class eos_vm_runtime : public eosio::chain::wasm_runtime_interface { public: eos_vm_runtime(); std::unique_ptr<wasm_instantiated_module_interface> instantiate_module(const char* code_bytes, size_t code_size, std::vector<uint8_t>) override; void immediately_exit_currently_running_module() override { if (_bkend) _bkend->exit({}); } private: // todo: managing this will get more complicated with sync calls; // immediately_exit_currently_running_module() should probably // move from wasm_runtime_interface to wasm_instantiated_module_interface. backend<apply_context, Backend>* _bkend = nullptr; // non owning pointer to allow for immediate exit template<typename Impl> friend class eos_vm_instantiated_module; }; } } } }// eosio::chain::webassembly::wabt_runtime #define __EOS_VM_INTRINSIC_NAME(LBL, SUF) LBL##SUF #define _EOS_VM_INTRINSIC_NAME(LBL, SUF) __INTRINSIC_NAME(LBL, SUF) #define _REGISTER_EOS_VM_INTRINSIC(CLS, MOD, METHOD, WASM_SIG, NAME, SIG) \ eosio::vm::registered_function<eosio::chain::apply_context, CLS, &CLS::METHOD> _EOS_VM_INTRINSIC_NAME(__eos_vm_intrinsic_fn, __COUNTER__)(std::string(MOD), std::string(NAME));
#pragma once #include <eosio/chain/webassembly/common.hpp> #include <eosio/chain/webassembly/runtime_interface.hpp> #include <eosio/chain/exceptions.hpp> #include <eosio/chain/apply_context.hpp> #include <softfloat_types.h> //eos-vm includes /* #include <eosio/vm/host_function.hpp> namespace eosio { namespace vm { template <> struct registered_host_functions<eosio::chain::apply_context>; } } */ #include <eosio/vm/backend.hpp> // eosio specific specializations namespace eosio { namespace vm { template <typename T, std::size_t Align> struct aligned_array_wrapper { static_assert(Align % alignof(T) == 0, "Must align to at least the alignment of T"); aligned_array_wrapper(void* ptr, uint32_t size) : ptr(ptr), size(size) { validate_ptr<T>(ptr, size); if (reinterpret_cast<std::uintptr_t>(ptr) % Align != 0) { copy.reset(new std::remove_cv_t<T>[size]); memcpy( copy.get(), ptr, sizeof(T) * size ); } } ~aligned_array_wrapper() { if constexpr (!std::is_const_v<T>) if (copy) memcpy( ptr, copy.get(), sizeof(T) * size); } constexpr operator T*() const { if (copy) return copy.get(); else return static_cast<T*>(ptr); } constexpr operator eosio::chain::array_ptr<T>() const { return eosio::chain::array_ptr<T>{static_cast<T*>(*this)}; } void* ptr; std::unique_ptr<std::remove_cv_t<T>[]> copy = nullptr; std::size_t size; }; template<> struct wasm_type_converter<eosio::chain::name> { static auto from_wasm(uint64_t val) { return eosio::chain::name{val}; } static auto to_wasm(eosio::chain::name val) { return val.to_uint64_t(); } }; template<typename T> struct wasm_type_converter<T*> { static auto from_wasm(void* val) { return eosio::vm::aligned_ptr_wrapper<T, alignof(T)>{val}; } }; template<typename T> struct wasm_type_converter<T&> { static auto from_wasm(void* val) { return eosio::vm::aligned_ref_wrapper<T, alignof(T)>{val}; } }; template<typename T> struct wasm_type_converter<eosio::chain::array_ptr<T>> { static auto from_wasm(void* ptr, uint32_t size) { return aligned_array_wrapper<T, alignof(T)>(ptr, size); } }; template<> struct wasm_type_converter<eosio::chain::array_ptr<char>> { static auto from_wasm(void* ptr, uint32_t size) { validate_ptr<char>(ptr, size); return eosio::chain::array_ptr<char>((char*)ptr); } // memcpy/memmove static auto from_wasm(void* ptr, eosio::chain::array_ptr<const char> /*src*/, uint32_t size) { validate_ptr<char>(ptr, size); return eosio::chain::array_ptr<char>((char*)ptr); } // memset static auto from_wasm(void* ptr, int /*val*/, uint32_t size) { validate_ptr<char>(ptr, size); return eosio::chain::array_ptr<char>((char*)ptr); } }; template<> struct wasm_type_converter<eosio::chain::array_ptr<const char>> { static auto from_wasm(void* ptr, uint32_t size) { validate_ptr<char>(ptr, size); return eosio::chain::array_ptr<const char>((char*)ptr); } // memcmp static auto from_wasm(void* ptr, eosio::chain::array_ptr<const char> /*src*/, uint32_t size) { validate_ptr<char>(ptr, size); return eosio::chain::array_ptr<const char>((char*)ptr); } }; template <typename Ctx> struct construct_derived<eosio::chain::transaction_context, Ctx> { static auto &value(Ctx& ctx) { return ctx.trx_context; } }; template <> struct construct_derived<eosio::chain::apply_context, eosio::chain::apply_context> { static auto &value(eosio::chain::apply_context& ctx) { return ctx; } }; template<> struct wasm_type_converter<eosio::chain::null_terminated_ptr> { static auto from_wasm(void* ptr) { validate_c_str(ptr); return eosio::chain::null_terminated_ptr{ static_cast<char*>(ptr) }; } }; }} // ns eosio::vm #if 0 namespace eosio { namespace vm { template <typename WAlloc, typename Cls, typename Cls2, auto F, typename R, typename Args, size_t... Is> auto create_logging_function(std::index_sequence<Is...>) { return std::function<void(Cls*, WAlloc*, operand_stack&)>{ [](Cls* self, WAlloc* walloc, operand_stack& os) { size_t i = sizeof...(Is) - 1; auto& intrinsic_log = self->control.get_intrinsic_debug_log(); /* if (intrinsic_log) { eosio::chain::digest_type::encoder enc; enc.write(walloc->template get_base_ptr<char>(), walloc->get_current_page() * 64 * 1024); intrinsic_log->record_intrinsic( eosio::chain::calc_arguments_hash( get_value<typename std::tuple_element<Is, Args>::type, Args>( walloc, get_value<to_wasm_t<typename std::tuple_element<Is, Args>::type>>()))...); os.get_back(i - Is)))...), enc.result()); } */ if constexpr (!std::is_same_v<R, void>) { if constexpr (std::is_same_v<Cls2, std::nullptr_t>) { R res = std::invoke(F, get_value<typename std::tuple_element<Is, Args>::type, Args>( walloc, std::move(os.get_back(i - Is).get<to_wasm_t<typename std::tuple_element<Is, Args>::type>>()))...); os.trim(sizeof...(Is)); os.push(resolve_result<R>(std::move(res), walloc)); } else { R res = std::invoke(F, construct_derived<Cls2, Cls>::value(*self), get_value<typename std::tuple_element<Is, Args>::type, Args>( walloc, std::move(os.get_back(i - Is).get<to_wasm_t<typename std::tuple_element<Is, Args>::type>>()))...); os.trim(sizeof...(Is)); os.push(resolve_result<R>(std::move(res), walloc)); } } else { if constexpr (std::is_same_v<Cls2, std::nullptr_t>) { std::invoke(F, get_value<typename std::tuple_element<Is, Args>::type, Args>( walloc, std::move(os.get_back(i - Is).get<to_wasm_t<typename std::tuple_element<Is, Args>::type>>()))...); } else { std::invoke(F, construct_derived<Cls2, Cls>::value(*self), get_value<typename std::tuple_element<Is, Args>::type, Args>( walloc, std::move(os.get_back(i - Is).get<to_wasm_t<typename std::tuple_element<Is, Args>::type>>()))...); } os.trim(sizeof...(Is)); } } }; } template <> struct registered_host_functions<eosio::chain::apply_context> { using Cls = eosio::chain::apply_context; template <typename WAlloc> struct mappings { std::unordered_map<std::pair<std::string, std::string>, uint32_t, host_func_pair_hash> named_mapping; std::vector<host_function> host_functions; std::vector<std::function<void(Cls*, WAlloc*, operand_stack&)>> functions; size_t current_index = 0; }; template <typename WAlloc> static mappings<WAlloc>& get_mappings() { static mappings<WAlloc> _mappings; return _mappings; } template <typename Cls2, auto Func, typename WAlloc> static void add(const std::string& mod, const std::string& name) { using deduced_full_ts = decltype(get_args_full(Func)); using deduced_ts = decltype(get_args(Func)); using res_t = typename decltype(get_return_t(Func))::type; static constexpr auto is = std::make_index_sequence<std::tuple_size<deduced_ts>::value>(); auto& current_mappings = get_mappings<WAlloc>(); current_mappings.named_mapping[{ mod, name }] = current_mappings.current_index++; current_mappings.functions.push_back(create_logging_function<WAlloc, Cls, Cls2, Func, res_t, deduced_full_ts>(is)); } template <typename Module> static void resolve(Module& mod) { decltype(mod.import_functions) imports = { mod.allocator, mod.get_imported_functions_size() }; auto& current_mappings = get_mappings<wasm_allocator>(); for (int i = 0; i < mod.imports.size(); i++) { std::string mod_name = std::string((char*)mod.imports[i].module_str.raw(), mod.imports[i].module_str.size()); std::string fn_name = std::string((char*)mod.imports[i].field_str.raw(), mod.imports[i].field_str.size()); EOS_WB_ASSERT(current_mappings.named_mapping.count({ mod_name, fn_name }), wasm_link_exception, "no mapping for imported function"); imports[i] = current_mappings.named_mapping[{ mod_name, fn_name }]; } mod.import_functions = std::move(imports); } template <typename Execution_Context> void operator()(Cls* host, Execution_Context& ctx, uint32_t index) { const auto& _func = get_mappings<wasm_allocator>().functions[index]; std::invoke(_func, host, ctx.get_wasm_allocator(), ctx.get_operand_stack()); } }; } } // eosio::vm #endif namespace eosio { namespace chain { namespace webassembly { namespace eos_vm_runtime { using namespace fc; using namespace eosio::vm; using namespace eosio::chain::webassembly::common; template<typename Backend> class eos_vm_runtime : public eosio::chain::wasm_runtime_interface { public: eos_vm_runtime(); std::unique_ptr<wasm_instantiated_module_interface> instantiate_module(const char* code_bytes, size_t code_size, std::vector<uint8_t>) override; void immediately_exit_currently_running_module() override { if (_bkend) _bkend->exit({}); } private: // todo: managing this will get more complicated with sync calls; // immediately_exit_currently_running_module() should probably // move from wasm_runtime_interface to wasm_instantiated_module_interface. backend<apply_context, Backend>* _bkend = nullptr; // non owning pointer to allow for immediate exit template<typename Impl> friend class eos_vm_instantiated_module; }; } } } }// eosio::chain::webassembly::wabt_runtime #define __EOS_VM_INTRINSIC_NAME(LBL, SUF) LBL##SUF #define _EOS_VM_INTRINSIC_NAME(LBL, SUF) __INTRINSIC_NAME(LBL, SUF) #define _REGISTER_EOS_VM_INTRINSIC(CLS, MOD, METHOD, WASM_SIG, NAME, SIG) \ eosio::vm::registered_function<eosio::chain::apply_context, CLS, &CLS::METHOD> _EOS_VM_INTRINSIC_NAME(__eos_vm_intrinsic_fn, __COUNTER__)(std::string(MOD), std::string(NAME));
Add checking of pointers
Add checking of pointers
C++
mit
EOSIO/eos,EOSIO/eos,EOSIO/eos,EOSIO/eos,EOSIO/eos
a36166962a569dd37e738212f6bc53395a7b70d2
hoomd/md/MuellerPlatheFlowGPU.cc
hoomd/md/MuellerPlatheFlowGPU.cc
// Copyright (c) 2009-2021 The Regents of the University of Michigan // This file is part of the HOOMD-blue project, released under the BSD 3-Clause License. #include "MuellerPlatheFlowGPU.h" #include "hoomd/HOOMDMPI.h" namespace py = pybind11; using namespace std; //! \file MuellerPlatheFlowGPU.cc Implementation of GPU version of MuellerPlatheFlow. #ifdef ENABLE_HIP #include "MuellerPlatheFlowGPU.cuh" MuellerPlatheFlowGPU::MuellerPlatheFlowGPU(std::shared_ptr<SystemDefinition> sysdef, std::shared_ptr<ParticleGroup> group, std::shared_ptr<Variant> flow_target, const flow_enum::Direction slab_direction, const flow_enum::Direction flow_direction, const unsigned int N_slabs, const unsigned int min_slab, const unsigned int max_slab, Scalar flow_epsilon) : MuellerPlatheFlow(sysdef, group, flow_target, slab_direction, flow_direction, N_slabs, min_slab, max_slab, flow_epsilon) { m_exec_conf->msg->notice(5) << "Constructing MuellerPlatheFlowGPU " << endl; if (!m_exec_conf->isCUDAEnabled()) { m_exec_conf->msg->error() << "Creating a MuellerPlatheGPU with no GPU in the execution configuration" << endl; throw std::runtime_error("Error initializing MuellerPlatheFlowGPU"); } unsigned int warp_size = m_exec_conf->dev_prop.warpSize; m_tuner.reset(new Autotuner(warp_size, 1024, warp_size, 5, 100000, "muellerplatheflow", this->m_exec_conf)); } MuellerPlatheFlowGPU::~MuellerPlatheFlowGPU(void) { m_exec_conf->msg->notice(5) << "Destroying MuellerPlatheFlowGPU " << endl; } void MuellerPlatheFlowGPU::search_min_max_velocity(void) { const unsigned int group_size = m_group->getNumMembers(); if (group_size == 0) return; if (!this->has_max_slab() and !this->has_min_slab()) return; if (m_prof) m_prof->push("MuellerPlatheFlowGPU::search"); const ArrayHandle<Scalar4> d_vel(m_pdata->getVelocities(), access_location::device, access_mode::read); const ArrayHandle<Scalar4> d_pos(m_pdata->getPositions(), access_location::device, access_mode::read); const ArrayHandle<unsigned int> d_tag(m_pdata->getTags(), access_location::device, access_mode::read); const ArrayHandle<unsigned int> d_rtag(m_pdata->getRTags(), access_location::device, access_mode::read); const GlobalArray<unsigned int>& group_members = m_group->getIndexArray(); const ArrayHandle<unsigned int> d_group_members(group_members, access_location::device, access_mode::read); const BoxDim& gl_box = m_pdata->getGlobalBox(); m_tuner->begin(); gpu_search_min_max_velocity(group_size, d_vel.data, d_pos.data, d_tag.data, d_rtag.data, d_group_members.data, gl_box, this->get_N_slabs(), this->get_max_slab(), this->get_min_slab(), &m_last_max_vel, &m_last_min_vel, this->has_max_slab(), this->has_min_slab(), m_tuner->getParam(), m_flow_direction, m_slab_direction); m_tuner->end(); if (m_exec_conf->isCUDAErrorCheckingEnabled()) CHECK_CUDA_ERROR(); if (m_prof) m_prof->pop(); } void MuellerPlatheFlowGPU::update_min_max_velocity(void) { if (m_prof) m_prof->push("MuellerPlatheFlowGPU::update"); const ArrayHandle<unsigned int> d_rtag(m_pdata->getRTags(), access_location::device, access_mode::read); ArrayHandle<Scalar4> d_vel(m_pdata->getVelocities(), access_location::device, access_mode::readwrite); const unsigned int Ntotal = m_pdata->getN() + m_pdata->getNGhosts(); gpu_update_min_max_velocity(d_rtag.data, d_vel.data, Ntotal, m_last_max_vel, m_last_min_vel, m_flow_direction); if (m_exec_conf->isCUDAErrorCheckingEnabled()) CHECK_CUDA_ERROR(); if (m_prof) m_prof->pop(); } void export_MuellerPlatheFlowGPU(py::module& m) { py::class_<MuellerPlatheFlowGPU, MuellerPlatheFlow, std::shared_ptr<MuellerPlatheFlowGPU>>( m, "MuellerPlatheFlowGPU") .def(py::init<std::shared_ptr<SystemDefinition>, std::shared_ptr<ParticleGroup>, std::shared_ptr<Variant>, const flow_enum::Direction, const flow_enum::Direction, const unsigned int, const unsigned int, const unsigned int, Scalar>()); } #endif // ENABLE_HIP
// Copyright (c) 2009-2021 The Regents of the University of Michigan // This file is part of the HOOMD-blue project, released under the BSD 3-Clause License. #include "MuellerPlatheFlowGPU.h" #include "hoomd/HOOMDMPI.h" namespace py = pybind11; using namespace std; //! \file MuellerPlatheFlowGPU.cc Implementation of GPU version of MuellerPlatheFlow. #ifdef ENABLE_HIP #include "MuellerPlatheFlowGPU.cuh" MuellerPlatheFlowGPU::MuellerPlatheFlowGPU(std::shared_ptr<SystemDefinition> sysdef, std::shared_ptr<ParticleGroup> group, std::shared_ptr<Variant> flow_target, std::string slab_direction_str, std::string flow_direction_str, const unsigned int N_slabs, const unsigned int min_slab, const unsigned int max_slab, Scalar flow_epsilon) : MuellerPlatheFlow(sysdef, group, flow_target, slab_direction_str, flow_direction_str, N_slabs, min_slab, max_slab, flow_epsilon) { m_exec_conf->msg->notice(5) << "Constructing MuellerPlatheFlowGPU " << endl; if (!m_exec_conf->isCUDAEnabled()) { m_exec_conf->msg->error() << "Creating a MuellerPlatheGPU with no GPU in the execution configuration" << endl; throw std::runtime_error("Error initializing MuellerPlatheFlowGPU"); } unsigned int warp_size = m_exec_conf->dev_prop.warpSize; m_tuner.reset(new Autotuner(warp_size, 1024, warp_size, 5, 100000, "muellerplatheflow", this->m_exec_conf)); } MuellerPlatheFlowGPU::~MuellerPlatheFlowGPU(void) { m_exec_conf->msg->notice(5) << "Destroying MuellerPlatheFlowGPU " << endl; } void MuellerPlatheFlowGPU::search_min_max_velocity(void) { const unsigned int group_size = m_group->getNumMembers(); if (group_size == 0) return; if (!this->has_max_slab() and !this->has_min_slab()) return; if (m_prof) m_prof->push("MuellerPlatheFlowGPU::search"); const ArrayHandle<Scalar4> d_vel(m_pdata->getVelocities(), access_location::device, access_mode::read); const ArrayHandle<Scalar4> d_pos(m_pdata->getPositions(), access_location::device, access_mode::read); const ArrayHandle<unsigned int> d_tag(m_pdata->getTags(), access_location::device, access_mode::read); const ArrayHandle<unsigned int> d_rtag(m_pdata->getRTags(), access_location::device, access_mode::read); const GlobalArray<unsigned int>& group_members = m_group->getIndexArray(); const ArrayHandle<unsigned int> d_group_members(group_members, access_location::device, access_mode::read); const BoxDim& gl_box = m_pdata->getGlobalBox(); m_tuner->begin(); gpu_search_min_max_velocity(group_size, d_vel.data, d_pos.data, d_tag.data, d_rtag.data, d_group_members.data, gl_box, this->get_N_slabs(), this->get_max_slab(), this->get_min_slab(), &m_last_max_vel, &m_last_min_vel, this->has_max_slab(), this->has_min_slab(), m_tuner->getParam(), m_flow_direction, m_slab_direction); m_tuner->end(); if (m_exec_conf->isCUDAErrorCheckingEnabled()) CHECK_CUDA_ERROR(); if (m_prof) m_prof->pop(); } void MuellerPlatheFlowGPU::update_min_max_velocity(void) { if (m_prof) m_prof->push("MuellerPlatheFlowGPU::update"); const ArrayHandle<unsigned int> d_rtag(m_pdata->getRTags(), access_location::device, access_mode::read); ArrayHandle<Scalar4> d_vel(m_pdata->getVelocities(), access_location::device, access_mode::readwrite); const unsigned int Ntotal = m_pdata->getN() + m_pdata->getNGhosts(); gpu_update_min_max_velocity(d_rtag.data, d_vel.data, Ntotal, m_last_max_vel, m_last_min_vel, m_flow_direction); if (m_exec_conf->isCUDAErrorCheckingEnabled()) CHECK_CUDA_ERROR(); if (m_prof) m_prof->pop(); } void export_MuellerPlatheFlowGPU(py::module& m) { py::class_<MuellerPlatheFlowGPU, MuellerPlatheFlow, std::shared_ptr<MuellerPlatheFlowGPU>>( m, "MuellerPlatheFlowGPU") .def(py::init<std::shared_ptr<SystemDefinition>, std::shared_ptr<ParticleGroup>, std::shared_ptr<Variant>, const flow_enum::Direction, const flow_enum::Direction, const unsigned int, const unsigned int, const unsigned int, Scalar>()); } #endif // ENABLE_HIP
Update constructor arguments in GPU files
Update constructor arguments in GPU files
C++
bsd-3-clause
joaander/hoomd-blue,joaander/hoomd-blue,joaander/hoomd-blue,joaander/hoomd-blue,joaander/hoomd-blue,joaander/hoomd-blue
d74c77813eb087ca9d26b98aa7d5c0bea59d0080
examples/custom1.cpp
examples/custom1.cpp
/*********************************************************************** custom1.cpp - Example that produces the same results as simple1, but it uses a Specialized SQL Structure to store the results instead of a MySQL++ Result object. Copyright (c) 1998 by Kevin Atkinson, (c) 1999, 2000 and 2001 by MySQL AB, and (c) 2004, 2005 by Educational Technology Resources, Inc. Others may also hold copyrights on code in this file. See the CREDITS file in the top directory of the distribution for details. This file is part of MySQL++. MySQL++ is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. MySQL++ is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with MySQL++; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA ***********************************************************************/ #include "util.h" #include <mysql++.h> #include <custom.h> #include <iostream> #include <iomanip> #include <vector> using namespace std; using namespace mysqlpp; // The following is calling a very complex macro which will create // "struct stock", which has the member variables: // // string item // ... // Date sdate // // plus methods to help populate the class from a MySQL row // among other things that I'll get to in a later example. sql_create_5(stock, 1, 5, // explained in the user manual string, item, longlong, num, double, weight, double, price, Date, sdate) int main(int argc, char *argv[]) { try { // Establish the connection to the database server. Connection con(use_exceptions); if (!connect_to_db(argc, argv, con)) { return 1; } // Retrieve the entire contents of the stock table, and store // the data in a vector of 'stock' SSQLS structures. Query query = con.query(); query << "select * from stock"; vector<stock> res; query.storein(res); // Display the result set print_stock_header(res.size()); vector<stock>::iterator it; for (it = res.begin(); it != res.end(); ++it) { print_stock_row(it->item.c_str(), it->num, it->weight, it->price, it->sdate); } } catch (BadQuery& er) { // Handle any connection or query errors cerr << "Error: " << er.what() << endl; return -1; } catch (BadConversion& er) { // Handle bad conversions cerr << "Error: " << er.what() << "\"." << endl << "retrieved data size: " << er.retrieved << " actual data size: " << er.actual_size << endl; return -1; } catch (exception& er) { // Catch-all for any other standard C++ exceptions cerr << "Error: " << er.what() << endl; return -1; } return 0; }
/*********************************************************************** custom1.cpp - Example that produces the same results as simple1, but it uses a Specialized SQL Structure to store the results instead of a MySQL++ Result object. Copyright (c) 1998 by Kevin Atkinson, (c) 1999, 2000 and 2001 by MySQL AB, and (c) 2004, 2005 by Educational Technology Resources, Inc. Others may also hold copyrights on code in this file. See the CREDITS file in the top directory of the distribution for details. This file is part of MySQL++. MySQL++ is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. MySQL++ is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with MySQL++; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA ***********************************************************************/ #include "util.h" #include <mysql++.h> #include <custom.h> #include <iostream> #include <iomanip> #include <vector> using namespace std; using namespace mysqlpp; // The following is calling a very complex macro which will create // "struct stock", which has the member variables: // // string item // ... // Date sdate // // plus methods to help populate the class from a MySQL row // among other things that I'll get to in a later example. sql_create_5(stock, 1, 5, // explained in the user manual string, item, longlong, num, double, weight, double, price, Date, sdate) int main(int argc, char *argv[]) { // Wrap all MySQL++ interactions in one big try block, so any // errors are handled gracefully. try { // Establish the connection to the database server. Connection con(use_exceptions); if (!connect_to_db(argc, argv, con)) { return 1; } // Retrieve the entire contents of the stock table, and store // the data in a vector of 'stock' SSQLS structures. Query query = con.query(); query << "select * from stock"; vector<stock> res; query.storein(res); // Display the result set print_stock_header(res.size()); vector<stock>::iterator it; for (it = res.begin(); it != res.end(); ++it) { print_stock_row(it->item.c_str(), it->num, it->weight, it->price, it->sdate); } } catch (BadQuery& er) { // Handle any connection or query errors cerr << "Error: " << er.what() << endl; return -1; } catch (BadConversion& er) { // Handle bad conversions cerr << "Error: " << er.what() << "\"." << endl << "retrieved data size: " << er.retrieved << " actual data size: " << er.actual_size << endl; return -1; } catch (exception& er) { // Catch-all for any other standard C++ exceptions cerr << "Error: " << er.what() << endl; return -1; } return 0; }
Comment tweak
Comment tweak
C++
lgpl-2.1
winsock/mysqlpp,winsock/mysqlpp,winsock/mysqlpp
f36e2d1c7932391830e27a906134cc113768aa84
include/cereal/types/variant.hpp
include/cereal/types/variant.hpp
/*! \file variant.hpp \brief Support for std::variant \ingroup STLSupport */ /* Copyright (c) 2014, 2017, Randolph Voorhies, Shane Grant, Juan Pedro Bolivar Puente. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of cereal nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL RANDOLPH VOORHIES OR SHANE GRANT BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef CEREAL_TYPES_STD_VARIANT_HPP_ #define CEREAL_TYPES_STD_VARIANT_HPP_ #include "cereal/cereal.hpp" #include <variant> #include <cstdint> namespace cereal { namespace variant_detail { //! @internal template <class Archive> struct variant_save_visitor { variant_save_visitor(Archive & ar_) : ar(ar_) {} template<class T> void operator()(T const & value) const { ar( CEREAL_NVP_("data", value) ); } Archive & ar; }; //! @internal template<int N, class Variant, class ... Args, class Archive> typename std::enable_if<N == std::variant_size_v<Variant>, void>::type load_variant(Archive & /*ar*/, int /*target*/, Variant & /*variant*/) { throw ::cereal::Exception("Error traversing variant during load"); } //! @internal template<int N, class Variant, class H, class ... T, class Archive> typename std::enable_if<N < std::variant_size_v<Variant>, void>::type load_variant(Archive & ar, int target, Variant & variant) { if(N == target) { H value; ar( CEREAL_NVP_("data", value) ); variant = std::move(value); } else load_variant<N+1, Variant, T...>(ar, target, variant); } } // namespace variant_detail //! Saving for std::variant template <class Archive, typename VariantType1, typename... VariantTypes> inline void CEREAL_SAVE_FUNCTION_NAME( Archive & ar, std::variant<VariantType1, VariantTypes...> const & variant ) { std::int32_t index = static_cast<std::int32_t>(variant.index()); ar( CEREAL_NVP_("index", index) ); variant_detail::variant_save_visitor<Archive> visitor(ar); std::visit(visitor, variant); } //! Loading for std::variant template <class Archive, typename... VariantTypes> inline void CEREAL_LOAD_FUNCTION_NAME( Archive & ar, std::variant<VariantTypes...> & variant ) { using variant_t = typename std::variant<VariantTypes...>; std::int32_t index; ar( CEREAL_NVP_("index", index) ); if(index >= std::variant_size_v<variant_t>) throw Exception("Invalid 'index' selector when deserializing std::variant"); variant_detail::load_variant<0, variant_t, VariantTypes...>(ar, index, variant); } } // namespace cereal #endif // CEREAL_TYPES_STD_VARIANT_HPP_
/*! \file variant.hpp \brief Support for std::variant \ingroup STLSupport */ /* Copyright (c) 2014, 2017, Randolph Voorhies, Shane Grant, Juan Pedro Bolivar Puente. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of cereal nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL RANDOLPH VOORHIES OR SHANE GRANT BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef CEREAL_TYPES_STD_VARIANT_HPP_ #define CEREAL_TYPES_STD_VARIANT_HPP_ #include "cereal/cereal.hpp" #include <variant> #include <cstdint> namespace cereal { namespace variant_detail { //! @internal template <class Archive> struct variant_save_visitor { variant_save_visitor(Archive & ar_) : ar(ar_) {} template<class T> void operator()(T const & value) const { ar( CEREAL_NVP_("data", value) ); } Archive & ar; }; //! @internal template<int N, class Variant, class ... Args, class Archive> typename std::enable_if<N == std::variant_size_v<Variant>, void>::type load_variant(Archive & /*ar*/, int /*target*/, Variant & /*variant*/) { throw ::cereal::Exception("Error traversing variant during load"); } //! @internal template<int N, class Variant, class H, class ... T, class Archive> typename std::enable_if<N < std::variant_size_v<Variant>, void>::type load_variant(Archive & ar, int target, Variant & variant) { if(N == target) { H value; ar( CEREAL_NVP_("data", value) ); variant = std::move(value); } else load_variant<N+1, Variant, T...>(ar, target, variant); } } // namespace variant_detail //! Saving for std::variant template <class Archive, typename VariantType1, typename... VariantTypes> inline void CEREAL_SAVE_FUNCTION_NAME( Archive & ar, std::variant<VariantType1, VariantTypes...> const & variant ) { std::int32_t index = static_cast<std::int32_t>(variant.index()); ar( CEREAL_NVP_("index", index) ); variant_detail::variant_save_visitor<Archive> visitor(ar); std::visit(visitor, variant); } //! Loading for std::variant template <class Archive, typename... VariantTypes> inline void CEREAL_LOAD_FUNCTION_NAME( Archive & ar, std::variant<VariantTypes...> & variant ) { using variant_t = typename std::variant<VariantTypes...>; std::int32_t index; ar( CEREAL_NVP_("index", index) ); if(index >= static_cast<std::int32_t>(std::variant_size_v<variant_t>)) throw Exception("Invalid 'index' selector when deserializing std::variant"); variant_detail::load_variant<0, variant_t, VariantTypes...>(ar, index, variant); } } // namespace cereal #endif // CEREAL_TYPES_STD_VARIANT_HPP_
Fix signed/unsigned comparison warning on gcc-7
Fix signed/unsigned comparison warning on gcc-7
C++
bsd-3-clause
abutcher-gh/cereal,USCiLab/cereal,USCiLab/cereal,abutcher-gh/cereal
1135ca1592848ef8962f8cac0074bd5eaf72873a
examples/threads.cpp
examples/threads.cpp
// // Created by Ivan Shynkarenka on 23.07.2015. // #include "benchmark/cppbenchmark.h" #include <atomic> #include <mutex> const int iterations = 10000000; const auto settings = CppBenchmark::Settings().Iterations(iterations).ThreadsRange(1, 8, [](int from, int to, int& result) { int r = result; result *= 2; return r; }); class UnsynchronizedFixture { protected: int counter; UnsynchronizedFixture() : counter(0) {} }; class AtomicFixture { protected: std::atomic<int> counter; AtomicFixture() : counter(0) {} }; class MutexFixture { protected: std::mutex mutex; int counter; MutexFixture() : mutex(), counter(0) {} }; BENCHMARK_THREADS_FIXTURE(UnsynchronizedFixture, "unsynchronized++", settings) { ++counter; } BENCHMARK_THREADS_FIXTURE(AtomicFixture, "std::atomic++", settings) { ++counter; } BENCHMARK_THREADS_FIXTURE(MutexFixture, "std::mutex++", settings) { std::lock_guard<std::mutex> lock(mutex); ++counter; } BENCHMARK_MAIN()
// // Created by Ivan Shynkarenka on 23.07.2015. // #include "benchmark/cppbenchmark.h" #include <atomic> #include <mutex> const int iterations = 10000000; const auto settings = CppBenchmark::Settings().Iterations(iterations).ThreadsRange(1, 8, [](int from, int to, int& result) { int r = result; result *= 2; return r; }); class UnsynchronizedFixture { protected: int counter; }; class AtomicFixture { protected: std::atomic<int> counter; }; class MutexFixture { protected: std::mutex mutex; int counter; }; BENCHMARK_THREADS_FIXTURE(UnsynchronizedFixture, "unsynchronized++", settings) { ++counter; } BENCHMARK_THREADS_FIXTURE(AtomicFixture, "std::atomic++", settings) { ++counter; } BENCHMARK_THREADS_FIXTURE(MutexFixture, "std::mutex++", settings) { std::lock_guard<std::mutex> lock(mutex); ++counter; } BENCHMARK_MAIN()
Clean code
Clean code
C++
mit
chronoxor/CppBenchmark,chronoxor/CppBenchmark
5477321ce7cdcdf57d2d5b540f71215593b9c14a
examples/tsl2561.cxx
examples/tsl2561.cxx
/* * Author: Nandkishor Sonar <[email protected]> * Copyright (c) 2014 Intel Corporation. * * LIGHT-TO-DIGITAL CONVERTER [TAOS-TSL2561] * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include <unistd.h> #include "tsl2561.h" int main (int argc, char **argv) { mraa_result_t error = MRAA_SUCCESS; upm::TSL2561 *sensor = NULL; int loopCount = 100; //! [Interesting] if (argc < 2) { printf("Provide loop count \n"); } else { loopCount = atoi(argv[1]); } sensor = new upm::TSL2561(); //sensor = new upm::TSL2561(0, TSL2561_Address, GAIN_16X, INTEGRATION_TIME2_402MS); //sensor = new upm::TSL2561(0, TSL2561_Address, GAIN_16X, INTEGRATION_TIME1_101MS); //sensor = new upm::TSL2561(0, TSL2561_Address, GAIN_16X, INTEGRATION_TIME0_13MS); //sensor = new upm::TSL2561(0, TSL2561_Address, GAIN_0X, INTEGRATION_TIME2_402MS); for(int i=0; i< loopCount; i++){ fprintf(stdout, "Lux = %d\n", sensor->getLux()); } //! [Interesting] delete(sensor); return (0); }
/* * Author: Nandkishor Sonar <[email protected]> * Copyright (c) 2014 Intel Corporation. * * LIGHT-TO-DIGITAL CONVERTER [TAOS-TSL2561] * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include <unistd.h> #include "tsl2561.h" int main (int argc, char **argv) { mraa_result_t error = MRAA_SUCCESS; upm::TSL2561 *sensor = NULL; int loopCount = 100; //! [Interesting] if (argc < 2) { printf("Provide loop count \n"); } else { loopCount = atoi(argv[1]); } sensor = new upm::TSL2561(); for(int i=0; i< loopCount; i++){ fprintf(stdout, "Lux = %d\n", sensor->getLux()); } //! [Interesting] delete(sensor); return (0); }
fix indentation of example
tsl2561: fix indentation of example Signed-off-by: Brendan Le Foll <[email protected]>
C++
mit
mircea/upm,kissbac/upm,whbruce/upm,Propanu/upm,GSmurf/upm,jontrulson/upm,srware/upm,MakerCollider/upm,0xD34D/upm,jontrulson/upm,yoyojacky/upm,Jon-ICS/upm,Propanu/upm,malikabhi05/upm,srware/upm,sasmita/upm,g-vidal/upm,nitirohilla/upm,g-vidal/upm,pylbert/upm,noahchense/upm,ShawnHymel/upm,skiselev/upm,yoyojacky/upm,arfoll/upm,Jon-ICS/upm,malikabhi05/upm,malikabhi05/upm,spitfire88/upm,Vaghesh/upm,ShawnHymel/upm,jontrulson/upm,pylbert/upm,skiselev/upm,jontrulson/upm,sasmita/upm,Propanu/upm,intel-iot-devkit/upm,yoyojacky/upm,ShawnHymel/upm,rafaneri/upm,ShawnHymel/upm,Vaghesh/upm,g-vidal/upm,intel-iot-devkit/upm,sasmita/upm,intel-iot-devkit/upm,kissbac/upm,afmckinney/upm,tripzero/upm,srware/upm,tripzero/upm,srware/upm,GSmurf/upm,g-vidal/upm,MakerCollider/upm,jontrulson/upm,afmckinney/upm,rafaneri/upm,izard/upm,g-vidal/upm,spitfire88/upm,tylergibson/upm,tylergibson/upm,whbruce/upm,skiselev/upm,arfoll/upm,sasmita/upm,andreivasiliu2211/upm,Vaghesh/upm,stefan-andritoiu/upm,tripzero/upm,whbruce/upm,malikabhi05/upm,mircea/upm,0xD34D/upm,spitfire88/upm,andreivasiliu2211/upm,spitfire88/upm,Jon-ICS/upm,noahchense/upm,kissbac/upm,sasmita/upm,arfoll/upm,yoyojacky/upm,Vaghesh/upm,mircea/upm,rafaneri/upm,fieldhawker/upm,mircea/upm,MakerCollider/upm,srware/upm,nitirohilla/upm,tylergibson/upm,stefan-andritoiu/upm,ShawnHymel/upm,arfoll/upm,intel-iot-devkit/upm,fieldhawker/upm,izard/upm,stefan-andritoiu/upm,intel-iot-devkit/upm,GSmurf/upm,stefan-andritoiu/upm,izard/upm,andreivasiliu2211/upm,GSmurf/upm,tylergibson/upm,afmckinney/upm,noahchense/upm,kissbac/upm,mircea/upm,pylbert/upm,tripzero/upm,noahchense/upm,skiselev/upm,yoyojacky/upm,rafaneri/upm,pylbert/upm,fieldhawker/upm,0xD34D/upm,andreivasiliu2211/upm,stefan-andritoiu/upm,intel-iot-devkit/upm,afmckinney/upm,tripzero/upm,Propanu/upm,Jon-ICS/upm,kissbac/upm,nitirohilla/upm,nitirohilla/upm,nitirohilla/upm,whbruce/upm,tylergibson/upm,malikabhi05/upm,skiselev/upm,Propanu/upm,whbruce/upm,andreivasiliu2211/upm,afmckinney/upm,g-vidal/upm,malikabhi05/upm,fieldhawker/upm,rafaneri/upm,MakerCollider/upm,stefan-andritoiu/upm,pylbert/upm,pylbert/upm,spitfire88/upm,MakerCollider/upm,Jon-ICS/upm,skiselev/upm,0xD34D/upm,arfoll/upm,Propanu/upm
ba4c7cfc7b94ff7a3be604324854095eb9a3d69a
include/insertionfinder/cube.hpp
include/insertionfinder/cube.hpp
#pragma once #include <cstddef> #include <cstdint> #include <cstring> #include <array> #include <exception> #include <functional> #include <initializer_list> #include <istream> #include <optional> #include <ostream> #include <vector> #include <insertionfinder/algorithm.hpp> #include <insertionfinder/twist.hpp> namespace InsertionFinder {class Cube;}; template<> struct std::hash<InsertionFinder::Cube> { std::size_t operator()(const InsertionFinder::Cube& cube) const noexcept; }; namespace InsertionFinder { struct CubeStreamError: std::exception { const char* what() const noexcept override { return "Failed to read cube from stream"; } }; namespace CubeTwist { constexpr std::byte corners {1}; constexpr std::byte edges {2}; constexpr std::byte centers {4}; constexpr std::byte full = corners | edges | centers; }; class Cube { friend struct std::hash<Cube>; private: class RawConstructor {}; static constexpr RawConstructor raw_construct {}; public: static constexpr int center_cycles[24] = { 0, 2, 1, 2, 2, 1, 3, 1, 1, 3, 1, 3, 2, 1, 3, 1, 2, 1, 3, 1, 2, 1, 3, 1 }; private: unsigned corner[8]; unsigned edge[12]; Rotation _placement; public: Cube() noexcept: corner {0, 3, 6, 9, 12, 15, 18, 21}, edge {0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22}, _placement(0) {} Cube(const Cube&) = default; Cube(Cube&&) = default; Cube& operator=(const Cube&) = default; Cube& operator=(Cube&&) = default; ~Cube() = default; private: explicit Cube(RawConstructor) noexcept {} public: void save_to(std::ostream& out) const; void read_from(std::istream& in); public: static int compare(const Cube& lhs, const Cube& rhs) noexcept { return std::memcmp(&lhs, &rhs, sizeof(Cube)); } bool operator==(const Cube& rhs) const noexcept { return std::memcmp(this, &rhs, sizeof(Cube)) == 0; } bool operator!=(const Cube& rhs) const noexcept { return std::memcmp(this, &rhs, sizeof(Cube)) != 0; } private: static const std::array<Cube, 24> rotation_cube; static const std::vector<std::array<int, 24>> corner_cycle_transform; static const std::vector<std::array<int, 24>> edge_cycle_transform; private: static std::array<Cube, 24> generate_rotation_cube_table() noexcept; static std::vector<std::array<int, 24>> generate_corner_cycle_transform_table(); static std::vector<std::array<int, 24>> generate_edge_cycle_transform_table(); public: void twist(const Algorithm& algorithm, std::byte flags = CubeTwist::full) noexcept { this->twist(algorithm, 0, algorithm.length(), flags); if (static_cast<bool>(flags & CubeTwist::centers)) { this->rotate(algorithm.cube_rotation()); } } void twist_inverse(const Algorithm& algorithm, std::byte flags = CubeTwist::full) noexcept { if (static_cast<bool>(flags & CubeTwist::centers)) { this->rotate(algorithm.cube_rotation().inverse()); } this->twist_inverse(algorithm, 0, algorithm.length(), flags); } void twist(const Algorithm& algorithm, std::size_t begin, std::size_t end, std::byte flags = CubeTwist::full) { for (size_t i = begin; i < end; ++i) { this->twist(algorithm[i], flags); } } void twist_inverse( const Algorithm& algorithm, std::size_t begin, std::size_t end, std::byte flags = CubeTwist::full ) { for (size_t i = end; i-- != begin;) { this->twist(algorithm[i].inverse(), flags); } } void twist(Twist twist, std::byte flags = CubeTwist::full) noexcept; void twist(const Cube& cube, std::byte flags = CubeTwist::full) noexcept; void twist_before(Twist twist, std::byte flags = CubeTwist::full) noexcept; void twist_before(const Cube& cube, std::byte flags = CubeTwist::full) noexcept; static Cube twist(const Cube& lhs, const Cube& rhs, std::byte lhs_flags, std::byte rhs_flags) noexcept; void rotate(Rotation rotation) noexcept { if (rotation) { this->twist(Cube::rotation_cube[rotation]); } } public: Cube operator*(const Algorithm& algorithm) const noexcept { Cube cube = *this; cube.twist(algorithm); return cube; } Cube operator*(Twist twist) const noexcept; Cube operator*(const Cube& rhs) const noexcept; friend Cube operator*(const Algorithm& algorithm, const Cube& rhs) noexcept { Cube cube; cube.twist(algorithm); cube.twist(rhs); return cube; } friend Cube operator*(Twist twist, const Cube& rhs) noexcept; template<class T> Cube& operator*=(const T& rhs) noexcept(noexcept(this->twist(rhs))) { this->twist(rhs); return *this; } public: void inverse() noexcept; static Cube inverse(const Cube& cube) noexcept; std::uint32_t mask() const noexcept; public: bool has_parity() const noexcept; bool parity() const noexcept { return Cube::center_cycles[this->_placement] > 1 || this->has_parity(); } int corner_cycles() const noexcept; int edge_cycles() const noexcept; Rotation placement() const noexcept { return this->_placement; } private: static std::optional<Cube> corner_cycle_cube(unsigned index); static std::optional<Cube> edge_cycle_cube(unsigned index); public: int corner_cycle_index() const noexcept; int edge_cycle_index() const noexcept; Cube best_placement() const noexcept; public: static int next_corner_cycle_index(int index, Twist twist) { return Cube::corner_cycle_transform[index][twist]; } static int next_corner_cycle_index(int index, std::initializer_list<Twist> twists) { for (Twist twist: twists) { index = Cube::corner_cycle_transform[index][twist]; } return index; } static int next_edge_cycle_index(int index, Twist twist) { return Cube::edge_cycle_transform[index][twist]; } static int next_edge_cycle_index(int index, std::initializer_list<Twist> twists) { for (Twist twist: twists) { index = Cube::edge_cycle_transform[index][twist]; } return index; } }; template<class T> Cube operator*(Cube&& lhs, const T& rhs) noexcept(noexcept(lhs.twist(rhs))) { lhs.twist(rhs); return std::move(lhs); } };
#pragma once #include <cstddef> #include <cstdint> #include <cstring> #include <array> #include <exception> #include <functional> #include <initializer_list> #include <istream> #include <optional> #include <ostream> #include <vector> #include <insertionfinder/algorithm.hpp> #include <insertionfinder/twist.hpp> namespace InsertionFinder {class Cube;}; template<> struct std::hash<InsertionFinder::Cube> { std::size_t operator()(const InsertionFinder::Cube& cube) const noexcept; }; namespace InsertionFinder { struct CubeStreamError: std::exception { const char* what() const noexcept override { return "Failed to read cube from stream"; } }; namespace CubeTwist { constexpr std::byte corners {1}; constexpr std::byte edges {2}; constexpr std::byte centers {4}; constexpr std::byte full = corners | edges | centers; }; class Cube { friend struct std::hash<Cube>; private: class RawConstructor {}; static constexpr RawConstructor raw_construct {}; public: static constexpr int center_cycles[24] = { 0, 2, 1, 2, 2, 1, 3, 1, 1, 3, 1, 3, 2, 1, 3, 1, 2, 1, 3, 1, 2, 1, 3, 1 }; private: unsigned corner[8]; unsigned edge[12]; Rotation _placement; public: Cube() noexcept: corner {0, 3, 6, 9, 12, 15, 18, 21}, edge {0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22}, _placement(0) {} Cube(const Cube&) = default; Cube(Cube&&) = default; Cube& operator=(const Cube&) = default; Cube& operator=(Cube&&) = default; ~Cube() = default; private: explicit Cube(RawConstructor) noexcept {} public: void save_to(std::ostream& out) const; void read_from(std::istream& in); public: static int compare(const Cube& lhs, const Cube& rhs) noexcept { return std::memcmp(&lhs, &rhs, sizeof(Cube)); } bool operator==(const Cube& rhs) const noexcept { return std::memcmp(this, &rhs, sizeof(Cube)) == 0; } bool operator!=(const Cube& rhs) const noexcept { return std::memcmp(this, &rhs, sizeof(Cube)) != 0; } private: static const std::array<Cube, 24> rotation_cube; static const std::vector<std::array<int, 24>> corner_cycle_transform; static const std::vector<std::array<int, 24>> edge_cycle_transform; private: static std::array<Cube, 24> generate_rotation_cube_table() noexcept; static std::vector<std::array<int, 24>> generate_corner_cycle_transform_table(); static std::vector<std::array<int, 24>> generate_edge_cycle_transform_table(); public: void twist(const Algorithm& algorithm, std::byte flags = CubeTwist::full) noexcept { this->twist(algorithm, 0, algorithm.length(), flags); if (static_cast<bool>(flags & CubeTwist::centers)) { this->rotate(algorithm.cube_rotation()); } } void twist_inverse(const Algorithm& algorithm, std::byte flags = CubeTwist::full) noexcept { if (static_cast<bool>(flags & CubeTwist::centers)) { this->rotate(algorithm.cube_rotation().inverse()); } this->twist_inverse(algorithm, 0, algorithm.length(), flags); } void twist(const Algorithm& algorithm, std::size_t begin, std::size_t end, std::byte flags = CubeTwist::full) { for (size_t i = begin; i < end; ++i) { this->twist(algorithm[i], flags); } } void twist_inverse( const Algorithm& algorithm, std::size_t begin, std::size_t end, std::byte flags = CubeTwist::full ) { for (size_t i = end; i-- != begin;) { this->twist(algorithm[i].inverse(), flags); } } void twist(Twist twist, std::byte flags = CubeTwist::full) noexcept; void twist(const Cube& cube, std::byte flags = CubeTwist::full) noexcept; void twist_before(Twist twist, std::byte flags = CubeTwist::full) noexcept; void twist_before(const Cube& cube, std::byte flags = CubeTwist::full) noexcept; static Cube twist(const Cube& lhs, const Cube& rhs, std::byte lhs_flags, std::byte rhs_flags) noexcept; void rotate(Rotation rotation) noexcept { if (rotation) { this->twist(Cube::rotation_cube[rotation]); } } public: Cube operator*(const Algorithm& algorithm) const noexcept { Cube cube = *this; cube.twist(algorithm); return cube; } Cube operator*(Twist twist) const noexcept; Cube operator*(const Cube& rhs) const noexcept; friend Cube operator*(const Algorithm& algorithm, const Cube& rhs) noexcept { Cube cube; cube.twist(algorithm); cube.twist(rhs); return cube; } friend Cube operator*(Twist twist, const Cube& rhs) noexcept; template<class T> Cube& operator*=(const T& rhs) noexcept(noexcept(twist(rhs))) { this->twist(rhs); return *this; } public: void inverse() noexcept; static Cube inverse(const Cube& cube) noexcept; std::uint32_t mask() const noexcept; public: bool has_parity() const noexcept; bool parity() const noexcept { return Cube::center_cycles[this->_placement] > 1 || this->has_parity(); } int corner_cycles() const noexcept; int edge_cycles() const noexcept; Rotation placement() const noexcept { return this->_placement; } private: static std::optional<Cube> corner_cycle_cube(unsigned index); static std::optional<Cube> edge_cycle_cube(unsigned index); public: int corner_cycle_index() const noexcept; int edge_cycle_index() const noexcept; Cube best_placement() const noexcept; public: static int next_corner_cycle_index(int index, Twist twist) { return Cube::corner_cycle_transform[index][twist]; } static int next_corner_cycle_index(int index, std::initializer_list<Twist> twists) { for (Twist twist: twists) { index = Cube::corner_cycle_transform[index][twist]; } return index; } static int next_edge_cycle_index(int index, Twist twist) { return Cube::edge_cycle_transform[index][twist]; } static int next_edge_cycle_index(int index, std::initializer_list<Twist> twists) { for (Twist twist: twists) { index = Cube::edge_cycle_transform[index][twist]; } return index; } }; template<class T> Cube operator*(Cube&& lhs, const T& rhs) noexcept(noexcept(lhs.twist(rhs))) { lhs.twist(rhs); return std::move(lhs); } };
fix bug
fix bug
C++
mit
xuanyan0x7c7/insertionfinder
2bed35935d1e831eaaa944014d455bdb32e88d8a
tests/auto/declarative/examples/tst_examples.cpp
tests/auto/declarative/examples/tst_examples.cpp
/**************************************************************************** ** ** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation ([email protected]) ** ** This file is part of the test suite of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** GNU Lesser General Public License Usage ** This file may be used under the terms of the GNU Lesser General Public ** License version 2.1 as published by the Free Software Foundation and ** appearing in the file LICENSE.LGPL included in the packaging of this ** file. Please review the following information to ensure the GNU Lesser ** General Public License version 2.1 requirements will be met: ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU General ** Public License version 3.0 as published by the Free Software Foundation ** and appearing in the file LICENSE.GPL included in the packaging of this ** file. Please review the following information to ensure the GNU General ** Public License version 3.0 requirements will be met: ** http://www.gnu.org/copyleft/gpl.html. ** ** Other Usage ** Alternatively, this file may be used in accordance with the terms and ** conditions contained in a signed written agreement between you and Nokia. ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include <qtest.h> #include <QLibraryInfo> #include <QDir> #include <QProcess> #include <QDebug> #include <QSGView> #include <QDeclarativeError> class tst_examples : public QObject { Q_OBJECT public: tst_examples(); private slots: void sgexamples_data(); void sgexamples(); void namingConvention(); private: QStringList excludedDirs; void namingConvention(const QDir &); QStringList findQmlFiles(const QDir &); }; tst_examples::tst_examples() { // Add directories you want excluded here // Not run in QSGView excludedDirs << "examples/declarative/qtquick1"; // These snippets are not expected to run on their own. excludedDirs << "doc/src/snippets/declarative/visualdatamodel_rootindex"; excludedDirs << "doc/src/snippets/declarative/qtbinding"; excludedDirs << "doc/src/snippets/declarative/imports"; excludedDirs << "doc/src/snippets/qtquick1/visualdatamodel_rootindex"; excludedDirs << "doc/src/snippets/qtquick1/qtbinding"; excludedDirs << "doc/src/snippets/qtquick1/imports"; #ifdef QT_NO_WEBKIT excludedDirs << "examples/declarative/modelviews/webview"; excludedDirs << "examples/declarative/webbrowser"; excludedDirs << "doc/src/snippets/declarative/webview"; excludedDirs << "doc/src/snippets/qtquick1/webview"; #endif #ifdef QT_NO_XMLPATTERNS excludedDirs << "examples/declarative/xml/xmldata"; excludedDirs << "examples/declarative/twitter"; excludedDirs << "examples/declarative/flickr"; excludedDirs << "examples/declarative/photoviewer"; #endif } /* This tests that the examples follow the naming convention required to have them tested by the examples() test. */ void tst_examples::namingConvention(const QDir &d) { for (int ii = 0; ii < excludedDirs.count(); ++ii) { QString s = excludedDirs.at(ii); if (d.absolutePath().endsWith(s)) return; } QStringList files = d.entryList(QStringList() << QLatin1String("*.qml"), QDir::Files); bool seenQml = !files.isEmpty(); bool seenLowercase = false; foreach (const QString &file, files) { if (file.at(0).isLower()) seenLowercase = true; } if (!seenQml) { QStringList dirs = d.entryList(QDir::Dirs | QDir::NoDotAndDotDot | QDir::NoSymLinks); foreach (const QString &dir, dirs) { QDir sub = d; sub.cd(dir); namingConvention(sub); } } else if(!seenLowercase) { QFAIL(qPrintable(QString( "Directory %1 violates naming convention; expected at least one qml file " "starting with lower case, got: %2" ).arg(d.absolutePath()).arg(files.join(",")))); } } void tst_examples::namingConvention() { QString examples = QLibraryInfo::location(QLibraryInfo::ExamplesPath); namingConvention(QDir(examples)); } QStringList tst_examples::findQmlFiles(const QDir &d) { for (int ii = 0; ii < excludedDirs.count(); ++ii) { QString s = excludedDirs.at(ii); if (d.absolutePath().endsWith(s)) return QStringList(); } QStringList rv; QStringList cppfiles = d.entryList(QStringList() << QLatin1String("*.cpp"), QDir::Files); if (cppfiles.isEmpty()) { QStringList files = d.entryList(QStringList() << QLatin1String("*.qml"), QDir::Files); foreach (const QString &file, files) { if (file.at(0).isLower()) { rv << d.absoluteFilePath(file); } } } QStringList dirs = d.entryList(QDir::Dirs | QDir::NoDotAndDotDot | QDir::NoSymLinks); foreach (const QString &dir, dirs) { QDir sub = d; sub.cd(dir); rv << findQmlFiles(sub); } return rv; } /* This test runs all the examples in the declarative UI source tree and ensures that they start and exit cleanly. Examples are any .qml files under the examples/ directory that start with a lower case letter. */ static void silentErrorsMsgHandler(QtMsgType, const char *) { } void tst_examples::sgexamples_data() { QTest::addColumn<QString>("file"); QString examples = QLatin1String(SRCDIR) + "/../../../../examples/declarative/"; QString snippets = QLatin1String(SRCDIR) + "/../../../../doc/src/snippets/"; QStringList files; files << findQmlFiles(QDir(examples)); files << findQmlFiles(QDir(snippets)); foreach (const QString &file, files) QTest::newRow(qPrintable(file)) << file; } void tst_examples::sgexamples() { QFETCH(QString, file); QSGView view; QtMsgHandler old = qInstallMsgHandler(silentErrorsMsgHandler); view.setSource(file); qInstallMsgHandler(old); if (view.status() == QSGView::Error) qWarning() << view.errors(); QCOMPARE(view.status(), QSGView::Ready); view.show(); QTest::qWait(100); } QTEST_MAIN(tst_examples) #include "tst_examples.moc"
/**************************************************************************** ** ** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation ([email protected]) ** ** This file is part of the test suite of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** GNU Lesser General Public License Usage ** This file may be used under the terms of the GNU Lesser General Public ** License version 2.1 as published by the Free Software Foundation and ** appearing in the file LICENSE.LGPL included in the packaging of this ** file. Please review the following information to ensure the GNU Lesser ** General Public License version 2.1 requirements will be met: ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU General ** Public License version 3.0 as published by the Free Software Foundation ** and appearing in the file LICENSE.GPL included in the packaging of this ** file. Please review the following information to ensure the GNU General ** Public License version 3.0 requirements will be met: ** http://www.gnu.org/copyleft/gpl.html. ** ** Other Usage ** Alternatively, this file may be used in accordance with the terms and ** conditions contained in a signed written agreement between you and Nokia. ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include <qtest.h> #include <QLibraryInfo> #include <QDir> #include <QProcess> #include <QDebug> #include <QSGView> #include <QDeclarativeError> class tst_examples : public QObject { Q_OBJECT public: tst_examples(); private slots: void sgexamples_data(); void sgexamples(); void namingConvention(); private: QStringList excludedDirs; void namingConvention(const QDir &); QStringList findQmlFiles(const QDir &); }; tst_examples::tst_examples() { // Add directories you want excluded here #ifdef Q_WS_QPA excludedDirs << "examples/declarative/text/fonts/fonts.qml"; // QTBUG-21415 #endif // Not run in QSGView excludedDirs << "examples/declarative/qtquick1"; // These snippets are not expected to run on their own. excludedDirs << "doc/src/snippets/declarative/visualdatamodel_rootindex"; excludedDirs << "doc/src/snippets/declarative/qtbinding"; excludedDirs << "doc/src/snippets/declarative/imports"; excludedDirs << "doc/src/snippets/qtquick1/visualdatamodel_rootindex"; excludedDirs << "doc/src/snippets/qtquick1/qtbinding"; excludedDirs << "doc/src/snippets/qtquick1/imports"; #ifdef QT_NO_WEBKIT excludedDirs << "examples/declarative/modelviews/webview"; excludedDirs << "examples/declarative/webbrowser"; excludedDirs << "doc/src/snippets/declarative/webview"; excludedDirs << "doc/src/snippets/qtquick1/webview"; #endif #ifdef QT_NO_XMLPATTERNS excludedDirs << "examples/declarative/xml/xmldata"; excludedDirs << "examples/declarative/twitter"; excludedDirs << "examples/declarative/flickr"; excludedDirs << "examples/declarative/photoviewer"; #endif } /* This tests that the examples follow the naming convention required to have them tested by the examples() test. */ void tst_examples::namingConvention(const QDir &d) { for (int ii = 0; ii < excludedDirs.count(); ++ii) { QString s = excludedDirs.at(ii); if (d.absolutePath().endsWith(s)) return; } QStringList files = d.entryList(QStringList() << QLatin1String("*.qml"), QDir::Files); bool seenQml = !files.isEmpty(); bool seenLowercase = false; foreach (const QString &file, files) { if (file.at(0).isLower()) seenLowercase = true; } if (!seenQml) { QStringList dirs = d.entryList(QDir::Dirs | QDir::NoDotAndDotDot | QDir::NoSymLinks); foreach (const QString &dir, dirs) { QDir sub = d; sub.cd(dir); namingConvention(sub); } } else if(!seenLowercase) { QFAIL(qPrintable(QString( "Directory %1 violates naming convention; expected at least one qml file " "starting with lower case, got: %2" ).arg(d.absolutePath()).arg(files.join(",")))); } } void tst_examples::namingConvention() { QString examples = QLibraryInfo::location(QLibraryInfo::ExamplesPath); namingConvention(QDir(examples)); } QStringList tst_examples::findQmlFiles(const QDir &d) { for (int ii = 0; ii < excludedDirs.count(); ++ii) { QString s = excludedDirs.at(ii); if (d.absolutePath().endsWith(s)) return QStringList(); } QStringList rv; QStringList cppfiles = d.entryList(QStringList() << QLatin1String("*.cpp"), QDir::Files); if (cppfiles.isEmpty()) { QStringList files = d.entryList(QStringList() << QLatin1String("*.qml"), QDir::Files); foreach (const QString &file, files) { if (file.at(0).isLower()) { rv << d.absoluteFilePath(file); } } } QStringList dirs = d.entryList(QDir::Dirs | QDir::NoDotAndDotDot | QDir::NoSymLinks); foreach (const QString &dir, dirs) { QDir sub = d; sub.cd(dir); rv << findQmlFiles(sub); } return rv; } /* This test runs all the examples in the declarative UI source tree and ensures that they start and exit cleanly. Examples are any .qml files under the examples/ directory that start with a lower case letter. */ static void silentErrorsMsgHandler(QtMsgType, const char *) { } void tst_examples::sgexamples_data() { QTest::addColumn<QString>("file"); QString examples = QLatin1String(SRCDIR) + "/../../../../examples/declarative/"; QString snippets = QLatin1String(SRCDIR) + "/../../../../doc/src/snippets/"; QStringList files; files << findQmlFiles(QDir(examples)); files << findQmlFiles(QDir(snippets)); foreach (const QString &file, files) QTest::newRow(qPrintable(file)) << file; } void tst_examples::sgexamples() { QFETCH(QString, file); QSGView view; QtMsgHandler old = qInstallMsgHandler(silentErrorsMsgHandler); view.setSource(file); qInstallMsgHandler(old); if (view.status() == QSGView::Error) qWarning() << view.errors(); QCOMPARE(view.status(), QSGView::Ready); view.show(); QTest::qWait(100); } QTEST_MAIN(tst_examples) #include "tst_examples.moc"
Remove fonts example from qpa platform tests
Remove fonts example from qpa platform tests Task-number: QTBUG-21415 Change-Id: I82b1600fe74a50dee8651247fcd172f09ba45a64 Reviewed-on: http://codereview.qt-project.org/4724 Reviewed-by: Qt Sanity Bot <[email protected]> Reviewed-by: Rohan McGovern <[email protected]> Reviewed-by: Martin Jones <[email protected]>
C++
lgpl-2.1
matthewvogt/qtdeclarative,jfaust/qtdeclarative,corngood/qtdeclarative,corngood/qtdeclarative,jfaust/qtdeclarative,qmlc/qtdeclarative,mgrunditz/qtdeclarative-2d,qmlc/qtdeclarative,crobertd/qtdeclarative,corngood/qtdeclarative,crobertd/qtdeclarative,mgrunditz/qtdeclarative-2d,matthewvogt/qtdeclarative,matthewvogt/qtdeclarative,qmlc/qtdeclarative,mgrunditz/qtdeclarative-2d,crobertd/qtdeclarative,mgrunditz/qtdeclarative-2d,jfaust/qtdeclarative,qmlc/qtdeclarative,mgrunditz/qtdeclarative-2d,corngood/qtdeclarative,mgrunditz/qtdeclarative-2d,matthewvogt/qtdeclarative,matthewvogt/qtdeclarative,jfaust/qtdeclarative,jfaust/qtdeclarative,crobertd/qtdeclarative,crobertd/qtdeclarative,matthewvogt/qtdeclarative,qmlc/qtdeclarative,corngood/qtdeclarative,mgrunditz/qtdeclarative-2d,corngood/qtdeclarative,matthewvogt/qtdeclarative,qmlc/qtdeclarative,crobertd/qtdeclarative,qmlc/qtdeclarative,jfaust/qtdeclarative,crobertd/qtdeclarative,corngood/qtdeclarative,matthewvogt/qtdeclarative,jfaust/qtdeclarative,qmlc/qtdeclarative
2184731975c44f050dd569b1bb4370f3b8bdc21d
include/misc/matrix_ops/size.hpp
include/misc/matrix_ops/size.hpp
/*################################################################################ ## ## Copyright (C) 2016-2020 Keith O'Hara ## ## This file is part of the OptimLib C++ library. ## ## Licensed under the Apache License, Version 2.0 (the "License"); ## you may not use this file except in compliance with the License. ## You may obtain a copy of the License at ## ## http://www.apache.org/licenses/LICENSE-2.0 ## ## Unless required by applicable law or agreed to in writing, software ## distributed under the License is distributed on an "AS IS" BASIS, ## WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ## See the License for the specific language governing permissions and ## limitations under the License. ## ################################################################################*/ #ifndef OPTIM_MATOPS_SIZE // #ifdef OPTIM_ENABLE_ARMA_WRAPPERS #define OPTIM_MATOPS_SIZE(x) (x).n_elem #endif #ifdef OPTIM_ENABLE_EIGEN_WRAPPERS #define OPTIM_MATOPS_SIZE(x) (x).size() #endif // #endif
/*################################################################################ ## ## Copyright (C) 2016-2020 Keith O'Hara ## ## This file is part of the OptimLib C++ library. ## ## Licensed under the Apache License, Version 2.0 (the "License"); ## you may not use this file except in compliance with the License. ## You may obtain a copy of the License at ## ## http://www.apache.org/licenses/LICENSE-2.0 ## ## Unless required by applicable law or agreed to in writing, software ## distributed under the License is distributed on an "AS IS" BASIS, ## WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ## See the License for the specific language governing permissions and ## limitations under the License. ## ################################################################################*/ #ifndef OPTIM_MATOPS_SIZE // #ifdef OPTIM_ENABLE_ARMA_WRAPPERS #define OPTIM_MATOPS_SIZE(x) static_cast<size_t>((x).n_elem) #endif #ifdef OPTIM_ENABLE_EIGEN_WRAPPERS #define OPTIM_MATOPS_SIZE(x) static_cast<size_t>((x).size()) #endif // #endif
add static_cast to size
add static_cast to size
C++
apache-2.0
kthohr/optim,kthohr/optim
18817e8d1cff5c822b339d14fce837d99929a941
tests/db/qdjangocompiler/tst_qdjangocompiler.cpp
tests/db/qdjangocompiler/tst_qdjangocompiler.cpp
/* * Copyright (C) 2010-2014 Jeremy Lainé * Contact: https://github.com/jlaine/qdjango * * This file is part of the QDjango Library. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. */ #include <QSqlDriver> #include "QDjango.h" #include "QDjangoQuerySet.h" #include "QDjangoWhere.h" #include "util.h" static QString escapeField(const QSqlDatabase &db, const QString &name) { return db.driver()->escapeIdentifier(name, QSqlDriver::FieldName); } static QString escapeTable(const QSqlDatabase &db, const QString &name) { return db.driver()->escapeIdentifier(name, QSqlDriver::TableName); } class Item : public QDjangoModel { Q_OBJECT Q_PROPERTY(QString name READ name WRITE setName) public: Item(QObject *parent = 0); QString name() const; void setName(const QString &name); private: QString m_name; }; class Owner : public QDjangoModel { Q_OBJECT Q_PROPERTY(QString name READ name WRITE setName) Q_PROPERTY(Item* item1 READ item1 WRITE setItem1) Q_PROPERTY(Item* item2 READ item2 WRITE setItem2) public: Owner(QObject *parent = 0); QString name() const; void setName(const QString &name); Item *item1() const; void setItem1(Item *item1); Item *item2() const; void setItem2(Item *item2); private: QString m_name; }; class OwnerWithNullableItem : public QDjangoModel { Q_OBJECT Q_PROPERTY(QString name READ name WRITE setName) Q_PROPERTY(Item* item1 READ item1 WRITE setItem1) Q_PROPERTY(Item* item2 READ item2 WRITE setItem2) Q_CLASSINFO("item2", "null=true") public: OwnerWithNullableItem(QObject *parent = 0); QString name() const; void setName(const QString &name); Item *item1() const; void setItem1(Item *item1); Item *item2() const; void setItem2(Item *item2); private: QString m_name; }; class tst_QDjangoCompiler : public QObject { Q_OBJECT private slots: void initTestCase(); void fieldNames(); void fieldNamesRecursive(); void fieldNamesNullable(); void orderLimit(); void resolve(); }; Item::Item(QObject *parent) : QDjangoModel(parent) { } QString Item::name() const { return m_name; } void Item::setName(const QString &name) { m_name = name; } Owner::Owner(QObject *parent) : QDjangoModel(parent) { setForeignKey("item1", new Item(this)); setForeignKey("item2", new Item(this)); } QString Owner::name() const { return m_name; } void Owner::setName(const QString &name) { m_name = name; } Item* Owner::item1() const { return qobject_cast<Item*>(foreignKey("item1")); } void Owner::setItem1(Item *item1) { setForeignKey("item1", item1); } Item* Owner::item2() const { return qobject_cast<Item*>(foreignKey("item2")); } void Owner::setItem2(Item *item2) { setForeignKey("item2", item2); } OwnerWithNullableItem::OwnerWithNullableItem(QObject *parent) : QDjangoModel(parent) { setForeignKey("item1", new Item(this)); setForeignKey("item2", new Item(this)); } QString OwnerWithNullableItem::name() const { return m_name; } void OwnerWithNullableItem::setName(const QString &name) { m_name = name; } Item* OwnerWithNullableItem::item1() const { return qobject_cast<Item*>(foreignKey("item1")); } void OwnerWithNullableItem::setItem1(Item *item1) { setForeignKey("item1", item1); } Item* OwnerWithNullableItem::item2() const { return qobject_cast<Item*>(foreignKey("item2")); } void OwnerWithNullableItem::setItem2(Item *item2) { setForeignKey("item2", item2); } void tst_QDjangoCompiler::initTestCase() { QVERIFY(initialiseDatabase()); QDjango::registerModel<Item>(); QDjango::registerModel<Owner>(); QDjango::registerModel<OwnerWithNullableItem>(); } void tst_QDjangoCompiler::fieldNames() { QSqlDatabase db = QDjango::database(); QDjangoCompiler compiler("Owner", db); QCOMPARE(compiler.fieldNames(false), QStringList() << escapeTable(db, "owner") + "." + escapeField(db, "id") << escapeTable(db, "owner") + "." + escapeField(db, "name") << escapeTable(db, "owner") + "." + escapeField(db, "item1_id") << escapeTable(db, "owner") + "." + escapeField(db, "item2_id")); QCOMPARE(compiler.fromSql(), escapeTable(db, "owner")); } void tst_QDjangoCompiler::fieldNamesRecursive() { QSqlDatabase db = QDjango::database(); QDjangoCompiler compiler("Owner", db); QCOMPARE(compiler.fieldNames(true), QStringList() << escapeTable(db, "owner") + "." + escapeField(db, "id") << escapeTable(db, "owner") + "." + escapeField(db, "name") << escapeTable(db, "owner") + "." + escapeField(db, "item1_id") << escapeTable(db, "owner") + "." + escapeField(db, "item2_id") << "T0." + escapeField(db, "id") << "T0." + escapeField(db, "name") << "T1." + escapeField(db, "id") << "T1." + escapeField(db, "name")); QCOMPARE(compiler.fromSql(), QString("%1 INNER JOIN %2 T0 ON T0.%3 = %4.%5 INNER JOIN %6 T1 ON T1.%7 = %8.%9").arg( escapeTable(db, "owner"), escapeTable(db, "item"), escapeField(db, "id"), escapeTable(db, "owner"), escapeField(db, "item1_id"), escapeTable(db, "item"), escapeField(db, "id"), escapeTable(db, "owner"), escapeField(db, "item2_id"))); } void tst_QDjangoCompiler::fieldNamesNullable() { QSqlDatabase db = QDjango::database(); QDjangoCompiler compiler("OwnerWithNullableItem", db); QCOMPARE(compiler.fieldNames(true), QStringList() << escapeTable(db, "ownerwithnullableitem") + "." + escapeField(db, "id") << escapeTable(db, "ownerwithnullableitem") + "." + escapeField(db, "name") << escapeTable(db, "ownerwithnullableitem") + "." + escapeField(db, "item1_id") << escapeTable(db, "ownerwithnullableitem") + "." + escapeField(db, "item2_id") << "T0." + escapeField(db, "id") << "T0." + escapeField(db, "name") << "T1." + escapeField(db, "id") << "T1." + escapeField(db, "name")); QCOMPARE(compiler.fromSql(), QString("%1 INNER JOIN %2 T0 ON T0.%3 = %4.%5 LEFT OUTER JOIN %6 T1 ON T1.%7 = %8.%9").arg( escapeTable(db, "ownerwithnullableitem"), escapeTable(db, "item"), escapeField(db, "id"), escapeTable(db, "ownerwithnullableitem"), escapeField(db, "item1_id"), escapeTable(db, "item"), escapeField(db, "id"), escapeTable(db, "ownerwithnullableitem"), escapeField(db, "item2_id"))); } void tst_QDjangoCompiler::orderLimit() { QSqlDatabase db = QDjango::database(); QDjangoCompiler compiler("Owner", db); QCOMPARE(compiler.orderLimitSql(QStringList("name"), 0, 0), QString(" ORDER BY %1.%2 ASC").arg( escapeTable(db, "owner"), escapeField(db, "name"))); QCOMPARE(compiler.fromSql(), escapeTable(db, "owner")); compiler = QDjangoCompiler("Owner", db); QCOMPARE(compiler.orderLimitSql(QStringList("-name"), 0, 0), QString(" ORDER BY %1.%2 DESC").arg( escapeTable(db, "owner"), escapeField(db, "name"))); QCOMPARE(compiler.fromSql(), escapeTable(db, "owner")); compiler = QDjangoCompiler("Owner", db); QCOMPARE(compiler.orderLimitSql(QStringList("item1__name"), 0, 0), QString(" ORDER BY T0.%1 ASC").arg( escapeField(db, "name"))); QCOMPARE(compiler.fromSql(), QString("%1 INNER JOIN %2 T0 ON T0.%3 = %4.%5").arg( escapeTable(db, "owner"), escapeTable(db, "item"), escapeField(db, "id"), escapeTable(db, "owner"), escapeField(db, "item1_id"))); compiler = QDjangoCompiler("Owner", db); QCOMPARE(compiler.orderLimitSql(QStringList() << "item1__name" << "item2__name", 0, 0), QString(" ORDER BY T0.%1 ASC, T1.%2 ASC").arg( escapeField(db, "name"), escapeField(db, "name"))); QCOMPARE(compiler.fromSql(), QString("%1 INNER JOIN %2 T0 ON T0.%3 = %4.%5 INNER JOIN %6 T1 ON T1.%7 = %8.%9").arg( escapeTable(db, "owner"), escapeTable(db, "item"), escapeField(db, "id"), escapeTable(db, "owner"), escapeField(db, "item1_id"), escapeTable(db, "item"), escapeField(db, "id"), escapeTable(db, "owner"), escapeField(db, "item2_id"))); } void tst_QDjangoCompiler::resolve() { QSqlDatabase db = QDjango::database(); QDjangoCompiler compiler("Owner", db); QDjangoWhere where("name", QDjangoWhere::Equals, "foo"); compiler.resolve(where); CHECKWHERE(where, QLatin1String("\"owner\".\"name\" = ?"), QVariantList() << "foo"); QCOMPARE(compiler.fromSql(), escapeTable(db, "owner")); compiler = QDjangoCompiler("Owner", db); where = QDjangoWhere("item1__name", QDjangoWhere::Equals, "foo"); compiler.resolve(where); CHECKWHERE(where, QLatin1String("T0.\"name\" = ?"), QVariantList() << "foo"); QCOMPARE(compiler.fromSql(), QString("%1 INNER JOIN %2 T0 ON T0.%3 = %4.%5").arg( escapeTable(db, "owner"), escapeTable(db, "item"), escapeField(db, "id"), escapeTable(db, "owner"), escapeField(db, "item1_id"))); compiler = QDjangoCompiler("Owner", db); where = QDjangoWhere("item1__name", QDjangoWhere::Equals, "foo") && QDjangoWhere("item2__name", QDjangoWhere::Equals, "bar"); compiler.resolve(where); CHECKWHERE(where, QLatin1String("T0.\"name\" = ? AND T1.\"name\" = ?"), QVariantList() << "foo" << "bar"); QCOMPARE(compiler.fromSql(), QString("%1 INNER JOIN %2 T0 ON T0.%3 = %4.%5 INNER JOIN %6 T1 ON T1.%7 = %8.%9").arg( escapeTable(db, "owner"), escapeTable(db, "item"), escapeField(db, "id"), escapeTable(db, "owner"), escapeField(db, "item1_id"), escapeTable(db, "item"), escapeField(db, "id"), escapeTable(db, "owner"), escapeField(db, "item2_id"))); } QTEST_MAIN(tst_QDjangoCompiler) #include "tst_qdjangocompiler.moc"
/* * Copyright (C) 2010-2014 Jeremy Lainé * Contact: https://github.com/jlaine/qdjango * * This file is part of the QDjango Library. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. */ #include <QSqlDriver> #include "QDjango.h" #include "QDjangoQuerySet.h" #include "QDjangoWhere.h" #include "util.h" static QString escapeField(const QSqlDatabase &db, const QString &name) { return db.driver()->escapeIdentifier(name, QSqlDriver::FieldName); } static QString escapeTable(const QSqlDatabase &db, const QString &name) { return db.driver()->escapeIdentifier(name, QSqlDriver::TableName); } class Item : public QDjangoModel { Q_OBJECT Q_PROPERTY(QString name READ name WRITE setName) public: Item(QObject *parent = 0); QString name() const; void setName(const QString &name); private: QString m_name; }; class Owner : public QDjangoModel { Q_OBJECT Q_PROPERTY(QString name READ name WRITE setName) Q_PROPERTY(Item* item1 READ item1 WRITE setItem1) Q_PROPERTY(Item* item2 READ item2 WRITE setItem2) public: Owner(QObject *parent = 0); QString name() const; void setName(const QString &name); Item *item1() const; void setItem1(Item *item1); Item *item2() const; void setItem2(Item *item2); private: QString m_name; }; class OwnerWithNullableItem : public QDjangoModel { Q_OBJECT Q_PROPERTY(QString name READ name WRITE setName) Q_PROPERTY(Item* item1 READ item1 WRITE setItem1) Q_PROPERTY(Item* item2 READ item2 WRITE setItem2) Q_CLASSINFO("item2", "null=true") public: OwnerWithNullableItem(QObject *parent = 0); QString name() const; void setName(const QString &name); Item *item1() const; void setItem1(Item *item1); Item *item2() const; void setItem2(Item *item2); private: QString m_name; }; class tst_QDjangoCompiler : public QObject { Q_OBJECT private slots: void initTestCase(); void fieldNames_data(); void fieldNames(); void orderLimit(); void resolve(); }; Item::Item(QObject *parent) : QDjangoModel(parent) { } QString Item::name() const { return m_name; } void Item::setName(const QString &name) { m_name = name; } Owner::Owner(QObject *parent) : QDjangoModel(parent) { setForeignKey("item1", new Item(this)); setForeignKey("item2", new Item(this)); } QString Owner::name() const { return m_name; } void Owner::setName(const QString &name) { m_name = name; } Item* Owner::item1() const { return qobject_cast<Item*>(foreignKey("item1")); } void Owner::setItem1(Item *item1) { setForeignKey("item1", item1); } Item* Owner::item2() const { return qobject_cast<Item*>(foreignKey("item2")); } void Owner::setItem2(Item *item2) { setForeignKey("item2", item2); } OwnerWithNullableItem::OwnerWithNullableItem(QObject *parent) : QDjangoModel(parent) { setForeignKey("item1", new Item(this)); setForeignKey("item2", new Item(this)); } QString OwnerWithNullableItem::name() const { return m_name; } void OwnerWithNullableItem::setName(const QString &name) { m_name = name; } Item* OwnerWithNullableItem::item1() const { return qobject_cast<Item*>(foreignKey("item1")); } void OwnerWithNullableItem::setItem1(Item *item1) { setForeignKey("item1", item1); } Item* OwnerWithNullableItem::item2() const { return qobject_cast<Item*>(foreignKey("item2")); } void OwnerWithNullableItem::setItem2(Item *item2) { setForeignKey("item2", item2); } void tst_QDjangoCompiler::initTestCase() { QVERIFY(initialiseDatabase()); QDjango::registerModel<Item>(); QDjango::registerModel<Owner>(); QDjango::registerModel<OwnerWithNullableItem>(); } void tst_QDjangoCompiler::fieldNames_data() { QSqlDatabase db = QDjango::database(); QTest::addColumn<QByteArray>("modelName"); QTest::addColumn<bool>("recursive"); QTest::addColumn<QStringList>("fieldNames"); QTest::addColumn<QString>("fromSql"); QTest::newRow("non recursive") << QByteArray("Owner") << false << (QStringList() << escapeTable(db, "owner") + "." + escapeField(db, "id") << escapeTable(db, "owner") + "." + escapeField(db, "name") << escapeTable(db, "owner") + "." + escapeField(db, "item1_id") << escapeTable(db, "owner") + "." + escapeField(db, "item2_id")) << escapeTable(db, "owner"); QTest::newRow("recurse one level") << QByteArray("Owner") << true << (QStringList() << escapeTable(db, "owner") + "." + escapeField(db, "id") << escapeTable(db, "owner") + "." + escapeField(db, "name") << escapeTable(db, "owner") + "." + escapeField(db, "item1_id") << escapeTable(db, "owner") + "." + escapeField(db, "item2_id") << "T0." + escapeField(db, "id") << "T0." + escapeField(db, "name") << "T1." + escapeField(db, "id") << "T1." + escapeField(db, "name")) << QString("%1 INNER JOIN %2 T0 ON T0.%3 = %4.%5 INNER JOIN %6 T1 ON T1.%7 = %8.%9") .arg(escapeTable(db, "owner")) .arg(escapeTable(db, "item")) .arg(escapeField(db, "id")) .arg(escapeTable(db, "owner")) .arg(escapeField(db, "item1_id")) .arg(escapeTable(db, "item")) .arg(escapeField(db, "id")) .arg(escapeTable(db, "owner")) .arg(escapeField(db, "item2_id")); QTest::newRow("recurse with nullable") << QByteArray("OwnerWithNullableItem") << true << (QStringList() << escapeTable(db, "ownerwithnullableitem") + "." + escapeField(db, "id") << escapeTable(db, "ownerwithnullableitem") + "." + escapeField(db, "name") << escapeTable(db, "ownerwithnullableitem") + "." + escapeField(db, "item1_id") << escapeTable(db, "ownerwithnullableitem") + "." + escapeField(db, "item2_id") << "T0." + escapeField(db, "id") << "T0." + escapeField(db, "name") << "T1." + escapeField(db, "id") << "T1." + escapeField(db, "name")) << QString("%1 INNER JOIN %2 T0 ON T0.%3 = %4.%5 LEFT OUTER JOIN %6 T1 ON T1.%7 = %8.%9") .arg(escapeTable(db, "ownerwithnullableitem")) .arg(escapeTable(db, "item")) .arg(escapeField(db, "id")) .arg(escapeTable(db, "ownerwithnullableitem")) .arg(escapeField(db, "item1_id")) .arg(escapeTable(db, "item")) .arg(escapeField(db, "id")) .arg(escapeTable(db, "ownerwithnullableitem")) .arg(escapeField(db, "item2_id")); } void tst_QDjangoCompiler::fieldNames() { QFETCH(QByteArray, modelName); QFETCH(bool, recursive); QFETCH(QStringList, fieldNames); QFETCH(QString, fromSql); QSqlDatabase db = QDjango::database(); QDjangoCompiler compiler(modelName, db); QCOMPARE(compiler.fieldNames(recursive), fieldNames); QCOMPARE(compiler.fromSql(), fromSql); } void tst_QDjangoCompiler::orderLimit() { QSqlDatabase db = QDjango::database(); QDjangoCompiler compiler("Owner", db); QCOMPARE(compiler.orderLimitSql(QStringList("name"), 0, 0), QString(" ORDER BY %1.%2 ASC").arg( escapeTable(db, "owner"), escapeField(db, "name"))); QCOMPARE(compiler.fromSql(), escapeTable(db, "owner")); compiler = QDjangoCompiler("Owner", db); QCOMPARE(compiler.orderLimitSql(QStringList("-name"), 0, 0), QString(" ORDER BY %1.%2 DESC").arg( escapeTable(db, "owner"), escapeField(db, "name"))); QCOMPARE(compiler.fromSql(), escapeTable(db, "owner")); compiler = QDjangoCompiler("Owner", db); QCOMPARE(compiler.orderLimitSql(QStringList("item1__name"), 0, 0), QString(" ORDER BY T0.%1 ASC").arg( escapeField(db, "name"))); QCOMPARE(compiler.fromSql(), QString("%1 INNER JOIN %2 T0 ON T0.%3 = %4.%5").arg( escapeTable(db, "owner"), escapeTable(db, "item"), escapeField(db, "id"), escapeTable(db, "owner"), escapeField(db, "item1_id"))); compiler = QDjangoCompiler("Owner", db); QCOMPARE(compiler.orderLimitSql(QStringList() << "item1__name" << "item2__name", 0, 0), QString(" ORDER BY T0.%1 ASC, T1.%2 ASC").arg( escapeField(db, "name"), escapeField(db, "name"))); QCOMPARE(compiler.fromSql(), QString("%1 INNER JOIN %2 T0 ON T0.%3 = %4.%5 INNER JOIN %6 T1 ON T1.%7 = %8.%9").arg( escapeTable(db, "owner"), escapeTable(db, "item"), escapeField(db, "id"), escapeTable(db, "owner"), escapeField(db, "item1_id"), escapeTable(db, "item"), escapeField(db, "id"), escapeTable(db, "owner"), escapeField(db, "item2_id"))); } void tst_QDjangoCompiler::resolve() { QSqlDatabase db = QDjango::database(); QDjangoCompiler compiler("Owner", db); QDjangoWhere where("name", QDjangoWhere::Equals, "foo"); compiler.resolve(where); CHECKWHERE(where, QLatin1String("\"owner\".\"name\" = ?"), QVariantList() << "foo"); QCOMPARE(compiler.fromSql(), escapeTable(db, "owner")); compiler = QDjangoCompiler("Owner", db); where = QDjangoWhere("item1__name", QDjangoWhere::Equals, "foo"); compiler.resolve(where); CHECKWHERE(where, QLatin1String("T0.\"name\" = ?"), QVariantList() << "foo"); QCOMPARE(compiler.fromSql(), QString("%1 INNER JOIN %2 T0 ON T0.%3 = %4.%5").arg( escapeTable(db, "owner"), escapeTable(db, "item"), escapeField(db, "id"), escapeTable(db, "owner"), escapeField(db, "item1_id"))); compiler = QDjangoCompiler("Owner", db); where = QDjangoWhere("item1__name", QDjangoWhere::Equals, "foo") && QDjangoWhere("item2__name", QDjangoWhere::Equals, "bar"); compiler.resolve(where); CHECKWHERE(where, QLatin1String("T0.\"name\" = ? AND T1.\"name\" = ?"), QVariantList() << "foo" << "bar"); QCOMPARE(compiler.fromSql(), QString("%1 INNER JOIN %2 T0 ON T0.%3 = %4.%5 INNER JOIN %6 T1 ON T1.%7 = %8.%9").arg( escapeTable(db, "owner"), escapeTable(db, "item"), escapeField(db, "id"), escapeTable(db, "owner"), escapeField(db, "item1_id"), escapeTable(db, "item"), escapeField(db, "id"), escapeTable(db, "owner"), escapeField(db, "item2_id"))); } QTEST_MAIN(tst_QDjangoCompiler) #include "tst_qdjangocompiler.moc"
use data driven tests
use data driven tests
C++
lgpl-2.1
jlaine/qdjango,paradoxon82/qdjango,jlaine/qdjango,ericLemanissier/qdjango,jlaine/qdjango,ericLemanissier/qdjango,ericLemanissier/qdjango,jlaine/qdjango,paradoxon82/qdjango,jlaine/qdjango,paradoxon82/qdjango,paradoxon82/qdjango,ericLemanissier/qdjango,ericLemanissier/qdjango,paradoxon82/qdjango
40f7f513887cfa235988923285d42a0d11d1fcab
include/seastar/core/io_queue.hh
include/seastar/core/io_queue.hh
/* * This file is open source software, licensed to you under the terms * of the Apache License, Version 2.0 (the "License"). See the NOTICE file * distributed with this work for additional information regarding copyright * ownership. You may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /* * Copyright 2019 ScyllaDB */ #pragma once #include <boost/container/small_vector.hpp> #include <seastar/core/sstring.hh> #include <seastar/core/fair_queue.hh> #include <seastar/core/metrics_registration.hh> #include <seastar/core/future.hh> #include <seastar/core/internal/io_request.hh> #include <seastar/util/spinlock.hh> #include <mutex> #include <array> struct io_queue_for_tests; namespace seastar { class io_priority_class; [[deprecated("Use io_priority_class.rename")]] future<> rename_priority_class(io_priority_class pc, sstring new_name); class io_intent; namespace internal { class io_sink; namespace linux_abi { struct io_event; struct iocb; } } using shard_id = unsigned; using stream_id = unsigned; class io_priority_class; class io_desc_read_write; class queued_io_request; class io_group; using io_group_ptr = std::shared_ptr<io_group>; class io_queue { public: class priority_class_data; private: std::vector<std::unique_ptr<priority_class_data>> _priority_classes; io_group_ptr _group; boost::container::small_vector<fair_queue, 2> _streams; internal::io_sink& _sink; priority_class_data& find_or_create_class(const io_priority_class& pc); // The fields below are going away, they are just here so we can implement deprecated // functions that used to be provided by the fair_queue and are going away (from both // the fair_queue and the io_queue). Double-accounting for now will allow for easier // decoupling and is temporary size_t _queued_requests = 0; size_t _requests_executing = 0; public: using clock_type = std::chrono::steady_clock; // We want to represent the fact that write requests are (maybe) more expensive // than read requests. To avoid dealing with floating point math we will scale one // read request to be counted by this amount. // // A write request that is 30% more expensive than a read will be accounted as // (read_request_base_count * 130) / 100. // It is also technically possible for reads to be the expensive ones, in which case // writes will have an integer value lower than read_request_base_count. static constexpr unsigned read_request_base_count = 128; static constexpr unsigned block_size_shift = 9; struct config { dev_t devid; unsigned capacity = std::numeric_limits<unsigned>::max(); unsigned long req_count_rate = std::numeric_limits<int>::max(); unsigned long blocks_count_rate = std::numeric_limits<int>::max(); unsigned disk_req_write_to_read_multiplier = read_request_base_count; unsigned disk_blocks_write_to_read_multiplier = read_request_base_count; size_t disk_read_saturation_length = std::numeric_limits<size_t>::max(); size_t disk_write_saturation_length = std::numeric_limits<size_t>::max(); sstring mountpoint = "undefined"; bool duplex = false; float rate_factor = 1.0; std::chrono::duration<double> rate_limit_duration = std::chrono::milliseconds(1); }; io_queue(io_group_ptr group, internal::io_sink& sink); ~io_queue(); stream_id request_stream(internal::io_direction_and_length dnl) const noexcept; fair_queue_ticket request_fq_ticket(internal::io_direction_and_length dnl) const noexcept; future<size_t> queue_request(const io_priority_class& pc, size_t len, internal::io_request req, io_intent* intent) noexcept; void submit_request(io_desc_read_write* desc, internal::io_request req) noexcept; void cancel_request(queued_io_request& req) noexcept; void complete_cancelled_request(queued_io_request& req) noexcept; void complete_request(io_desc_read_write& desc) noexcept; [[deprecated("modern I/O queues should use a property file")]] size_t capacity() const; [[deprecated("I/O queue users should not track individual requests, but resources (weight, size) passing through the queue")]] size_t queued_requests() const { return _queued_requests; } // How many requests are sent to disk but not yet returned. [[deprecated("I/O queue users should not track individual requests, but resources (weight, size) passing through the queue")]] size_t requests_currently_executing() const { return _requests_executing; } // Dispatch requests that are pending in the I/O queue void poll_io_queue(); clock_type::time_point next_pending_aio() const noexcept; sstring mountpoint() const; dev_t dev_id() const noexcept; future<> update_shares_for_class(io_priority_class pc, size_t new_shares); future<> update_bandwidth_for_class(io_priority_class pc, uint64_t new_bandwidth); void rename_priority_class(io_priority_class pc, sstring new_name); void throttle_priority_class(const priority_class_data& pc) noexcept; void unthrottle_priority_class(const priority_class_data& pc) noexcept; struct request_limits { size_t max_read; size_t max_write; }; request_limits get_request_limits() const noexcept; private: static fair_queue::config make_fair_queue_config(const config& cfg, sstring label); void register_stats(sstring name, priority_class_data& pc); const config& get_config() const noexcept; }; class io_group { public: explicit io_group(io_queue::config io_cfg); ~io_group(); struct priority_class_data; private: friend class io_queue; friend struct ::io_queue_for_tests; const io_queue::config _config; size_t _max_request_length[2]; std::vector<std::unique_ptr<fair_group>> _fgs; std::vector<std::unique_ptr<priority_class_data>> _priority_classes; util::spinlock _lock; const shard_id _allocated_on; static fair_group::config make_fair_group_config(const io_queue::config& qcfg) noexcept; priority_class_data& find_or_create_class(io_priority_class pc); }; inline const io_queue::config& io_queue::get_config() const noexcept { return _group->_config; } inline size_t io_queue::capacity() const { return get_config().capacity; } inline sstring io_queue::mountpoint() const { return get_config().mountpoint; } inline dev_t io_queue::dev_id() const noexcept { return get_config().devid; } }
/* * This file is open source software, licensed to you under the terms * of the Apache License, Version 2.0 (the "License"). See the NOTICE file * distributed with this work for additional information regarding copyright * ownership. You may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /* * Copyright 2019 ScyllaDB */ #pragma once #include <boost/container/small_vector.hpp> #include <seastar/core/sstring.hh> #include <seastar/core/fair_queue.hh> #include <seastar/core/metrics_registration.hh> #include <seastar/core/future.hh> #include <seastar/core/internal/io_request.hh> #include <seastar/util/spinlock.hh> struct io_queue_for_tests; namespace seastar { class io_priority_class; [[deprecated("Use io_priority_class.rename")]] future<> rename_priority_class(io_priority_class pc, sstring new_name); class io_intent; namespace internal { class io_sink; namespace linux_abi { struct io_event; struct iocb; } } using shard_id = unsigned; using stream_id = unsigned; class io_desc_read_write; class queued_io_request; class io_group; using io_group_ptr = std::shared_ptr<io_group>; class io_queue { public: class priority_class_data; private: std::vector<std::unique_ptr<priority_class_data>> _priority_classes; io_group_ptr _group; boost::container::small_vector<fair_queue, 2> _streams; internal::io_sink& _sink; priority_class_data& find_or_create_class(const io_priority_class& pc); // The fields below are going away, they are just here so we can implement deprecated // functions that used to be provided by the fair_queue and are going away (from both // the fair_queue and the io_queue). Double-accounting for now will allow for easier // decoupling and is temporary size_t _queued_requests = 0; size_t _requests_executing = 0; public: using clock_type = std::chrono::steady_clock; // We want to represent the fact that write requests are (maybe) more expensive // than read requests. To avoid dealing with floating point math we will scale one // read request to be counted by this amount. // // A write request that is 30% more expensive than a read will be accounted as // (read_request_base_count * 130) / 100. // It is also technically possible for reads to be the expensive ones, in which case // writes will have an integer value lower than read_request_base_count. static constexpr unsigned read_request_base_count = 128; static constexpr unsigned block_size_shift = 9; struct config { dev_t devid; unsigned capacity = std::numeric_limits<unsigned>::max(); unsigned long req_count_rate = std::numeric_limits<int>::max(); unsigned long blocks_count_rate = std::numeric_limits<int>::max(); unsigned disk_req_write_to_read_multiplier = read_request_base_count; unsigned disk_blocks_write_to_read_multiplier = read_request_base_count; size_t disk_read_saturation_length = std::numeric_limits<size_t>::max(); size_t disk_write_saturation_length = std::numeric_limits<size_t>::max(); sstring mountpoint = "undefined"; bool duplex = false; float rate_factor = 1.0; std::chrono::duration<double> rate_limit_duration = std::chrono::milliseconds(1); }; io_queue(io_group_ptr group, internal::io_sink& sink); ~io_queue(); stream_id request_stream(internal::io_direction_and_length dnl) const noexcept; fair_queue_ticket request_fq_ticket(internal::io_direction_and_length dnl) const noexcept; future<size_t> queue_request(const io_priority_class& pc, size_t len, internal::io_request req, io_intent* intent) noexcept; void submit_request(io_desc_read_write* desc, internal::io_request req) noexcept; void cancel_request(queued_io_request& req) noexcept; void complete_cancelled_request(queued_io_request& req) noexcept; void complete_request(io_desc_read_write& desc) noexcept; [[deprecated("modern I/O queues should use a property file")]] size_t capacity() const; [[deprecated("I/O queue users should not track individual requests, but resources (weight, size) passing through the queue")]] size_t queued_requests() const { return _queued_requests; } // How many requests are sent to disk but not yet returned. [[deprecated("I/O queue users should not track individual requests, but resources (weight, size) passing through the queue")]] size_t requests_currently_executing() const { return _requests_executing; } // Dispatch requests that are pending in the I/O queue void poll_io_queue(); clock_type::time_point next_pending_aio() const noexcept; sstring mountpoint() const; dev_t dev_id() const noexcept; future<> update_shares_for_class(io_priority_class pc, size_t new_shares); future<> update_bandwidth_for_class(io_priority_class pc, uint64_t new_bandwidth); void rename_priority_class(io_priority_class pc, sstring new_name); void throttle_priority_class(const priority_class_data& pc) noexcept; void unthrottle_priority_class(const priority_class_data& pc) noexcept; struct request_limits { size_t max_read; size_t max_write; }; request_limits get_request_limits() const noexcept; private: static fair_queue::config make_fair_queue_config(const config& cfg, sstring label); void register_stats(sstring name, priority_class_data& pc); const config& get_config() const noexcept; }; class io_group { public: explicit io_group(io_queue::config io_cfg); ~io_group(); struct priority_class_data; private: friend class io_queue; friend struct ::io_queue_for_tests; const io_queue::config _config; size_t _max_request_length[2]; std::vector<std::unique_ptr<fair_group>> _fgs; std::vector<std::unique_ptr<priority_class_data>> _priority_classes; util::spinlock _lock; const shard_id _allocated_on; static fair_group::config make_fair_group_config(const io_queue::config& qcfg) noexcept; priority_class_data& find_or_create_class(io_priority_class pc); }; inline const io_queue::config& io_queue::get_config() const noexcept { return _group->_config; } inline size_t io_queue::capacity() const { return get_config().capacity; } inline sstring io_queue::mountpoint() const { return get_config().mountpoint; } inline dev_t io_queue::dev_id() const noexcept { return get_config().devid; } }
Remove unused code from io_queue.hh
io_queue: Remove unused code from io_queue.hh A couple of includes and double forward declaration of the io_priority_class. Signed-off-by: Pavel Emelyanov <[email protected]>
C++
apache-2.0
syuu1228/seastar,scylladb/seastar,avikivity/seastar,scylladb/seastar,syuu1228/seastar,avikivity/seastar,avikivity/seastar,scylladb/seastar,syuu1228/seastar
b827ef5f21845623380fccbd20cfa18d64d16897
tutorials/developers/tutorial_03/tutorial_03.cpp
tutorials/developers/tutorial_03/tutorial_03.cpp
/* This example defines the following sequence of computations. for (i = 0; i < M; i++) S0(i) = 4; S1(i) = 3; for (j = 0; j < N; j++) S2(i, j) = 2; S3(i) = 1; The goal of this tutorial is to show how one can indicate the order of computations in Tiramisu. */ #include <tiramisu/tiramisu.h> #define SIZE0 10 using namespace tiramisu; int main(int argc, char **argv) { tiramisu::init("sequence"); // ------------------------------------------------------- // Layer I // ------------------------------------------------------- constant M("M", expr((int32_t) SIZE0)); var i("i", 0, M), j("j", 0, M); // Declare the four computations: c0, c1, c2 and c3. computation c0({i}, expr((uint8_t) 4)); computation c1({i}, expr((uint8_t) 3)); computation c2({i,j}, expr((uint8_t) 2)); computation c3({i}, expr((uint8_t) 1)); // ------------------------------------------------------- // Layer II // ------------------------------------------------------- // By default computations are unordered in Tiramisu. The user has to specify // the order exlplicitely (automatic ordering is being developed and will be // available soon). // // The following calls define the order between the computations c3, c2, c1 and c0. // c1 is set to be after c0 in the loop level i. That is, both have the same outer loops // up to the loop level i (they share i also) but starting from i, all the // computations c1 are ordered after the computations c0. c1.after(c0, i); c2.after(c1, i); c3.after(c2, i); // ------------------------------------------------------- // Layer III // ------------------------------------------------------- buffer b0("b0", {expr(SIZE0)}, p_uint8, a_output); buffer b1("b1", {expr(SIZE0)}, p_uint8, a_output); buffer b2("b2", {expr(SIZE0), expr(SIZE0)}, p_uint8, a_output); buffer b3("b3", {expr(SIZE0)}, p_uint8, a_output); c0.store_in(&b0); c1.store_in(&b1); c2.store_in(&b2); c3.store_in(&b3); // ------------------------------------------------------- // Code Generator // ------------------------------------------------------- tiramisu::codegen({&b0, &b1, &b2, &b3}, "build/generated_fct_developers_tutorial_03.o"); return 0; }
/* This example defines the following sequence of computations. for (i = 0; i < M; i++) S0(i) = 4; S1(i) = 3; for (j = 0; j < N; j++) S2(i, j) = 2; S3(i) = 1; The goal of this tutorial is to show how one can indicate the order of computations in Tiramisu. */ #include <tiramisu/tiramisu.h> #define SIZE0 10 using namespace tiramisu; int main(int argc, char **argv) { tiramisu::init("sequence"); // ------------------------------------------------------- // Layer I // ------------------------------------------------------- constant M("M", expr((int32_t) SIZE0)); var i("i", 0, M), j("j", 0, M); // Declare the four computations: c0, c1, c2 and c3. computation c0("c0", {i}, expr((uint8_t) 4)); computation c1("c1", {i}, expr((uint8_t) 3)); computation c2("c2", {i,j}, expr((uint8_t) 2)); computation c3("c3", {i}, expr((uint8_t) 1)); // ------------------------------------------------------- // Layer II // ------------------------------------------------------- // By default computations are unordered in Tiramisu. The user has to specify // the order exlplicitely (automatic ordering is being developed and will be // available soon). // // The following calls define the order between the computations c3, c2, c1 and c0. // c1 is set to be after c0 in the loop level i. That is, both have the same outer loops // up to the loop level i (they share i also) but starting from i, all the // computations c1 are ordered after the computations c0. c1.after(c0, i); c2.after(c1, i); c3.after(c2, i); // ------------------------------------------------------- // Layer III // ------------------------------------------------------- buffer b0("b0", {expr(SIZE0)}, p_uint8, a_output); buffer b1("b1", {expr(SIZE0)}, p_uint8, a_output); buffer b2("b2", {expr(SIZE0), expr(SIZE0)}, p_uint8, a_output); buffer b3("b3", {expr(SIZE0)}, p_uint8, a_output); c0.store_in(&b0); c1.store_in(&b1); c2.store_in(&b2); c3.store_in(&b3); // ------------------------------------------------------- // Code Generator // ------------------------------------------------------- tiramisu::codegen({&b0, &b1, &b2, &b3}, "build/generated_fct_developers_tutorial_03.o"); return 0; }
Use new API in tuto 03
Use new API in tuto 03
C++
mit
rbaghdadi/COLi,rbaghdadi/tiramisu,rbaghdadi/tiramisu,rbaghdadi/ISIR,rbaghdadi/ISIR,rbaghdadi/COLi,rbaghdadi/tiramisu,rbaghdadi/tiramisu
502975ab8136f9712fdd012ddad45ca3ace95f8c
introduction/exp_apx/exp_eps.hpp
introduction/exp_apx/exp_eps.hpp
/* $Id$ */ # ifndef CPPAD_EXP_EPS_INCLUDED # define CPPAD_EXP_EPS_INCLUDED /* -------------------------------------------------------------------------- CppAD: C++ Algorithmic Differentiation: Copyright (C) 2003-07 Bradley M. Bell CppAD is distributed under multiple licenses. This distribution is under the terms of the Common Public License Version 1.0. A copy of this license is included in the COPYING file of this distribution. Please visit http://www.coin-or.org/CppAD/ for information on other licenses. -------------------------------------------------------------------------- */ /* $begin exp_eps$$ $spell cppad-%yyyymmdd% hpp Apx cpp const exp_eps bool $$ $section An Epsilon Accurate Exponential Approximation$$ $index exp_eps$$ $index example, algorithm$$ $index algorithm, example$$ $index exp, example$$ $head Syntax$$ $syntax%# include "exp_eps.hpp"%$$ $pre $$ $syntax%%y% = exp_eps(%x%, %epsilon%)%$$ $head Purpose$$ This is a an example algorithm that is used to demonstrate how Algorithmic Differentiation works with loops and boolean decision variables (see $cref/exp_2/$$ for a simpler example). $head Mathematical Function$$ The exponential function can be defined by $latex \[ \exp (x) = 1 + x^1 / 1 ! + x^2 / 2 ! + \cdots \] $$ We define $latex k ( x, \varepsilon ) $$ as the smallest non-negative integer such that $latex \varepsilon \geq x^k / k !$$; i.e., $latex \[ k( x, \varepsilon ) = \min \{ k \in {\rm Z}_+ \; | \; \varepsilon \geq x^k / k ! \} \] $$ The mathematical form for our approximation of the exponential function is $latex \[ \begin{array}{rcl} {\rm exp\_eps} (x , \varepsilon ) & = & \left\{ \begin{array}{ll} \frac{1}{ {\rm exp\_eps} (-x , \varepsilon ) } & {\rm if} \; x < 0 \\ 1 + x^1 / 1 ! + \cdots + x^{k( x, \varepsilon)} / k( x, \varepsilon ) ! & {\rm otherwise} \end{array} \right. \end{array} \] $$ $head include$$ The include command in the syntax is relative to $syntax% cppad-%yyyymmdd%/introduction/exp_apx %$$ where $syntax%cppad-%yyyymmdd%$$ is the distribution directory created during the beginning steps of the $cref%installation%Install%$$ of CppAD. $head x$$ The argument $italic x$$ has prototype $syntax% const %Type% &%x% %$$ (see $italic Type$$ below). It specifies the point at which to evaluate the approximation for the exponential function. $head epsilon$$ The argument $italic epsilon$$ has prototype $syntax% const %Type% &%epsilon% %$$ It specifies the accuracy with which to approximate the exponential function value; i.e., it is the value of $latex \varepsilon$$ in the exponential function approximation defined above. $head y$$ The result $italic y$$ has prototype $syntax% %Type% %y% %$$ It is the value of the exponential function approximation defined above. $head Type$$ If $italic u$$ and $italic v$$ are $italic Type$$ objects and $italic i$$ is an $code int$$: $table $bold Operation$$ $cnext $bold Result Type$$ $cnext $bold Description$$ $rnext $syntax%%Type%(%i%)%$$ $cnext $italic Type$$ $cnext object with value equal to $italic i$$ $rnext $syntax%%u% > %v%$$ $cnext $code bool$$ $cnext true, if $italic u$$ greater than $italic v$$, an false otherwise $rnext $syntax%%u% = %v%$$ $cnext $italic Type$$ $cnext new $italic u$$ (and result) is value of $italic v$$ $rnext $syntax%%u% * %v%$$ $cnext $italic Type$$ $cnext result is value of $latex u * v$$ $rnext $syntax%%u% / %v%$$ $cnext $italic Type$$ $cnext result is value of $latex u / v$$ $rnext $syntax%%u% + %v%$$ $cnext $italic Type$$ $cnext result is value of $latex u + v$$ $rnext $syntax%-%u%$$ $cnext $italic Type$$ $cnext result is value of $latex - u$$ $tend $children% introduction/exp_apx/exp_eps.omh% introduction/exp_apx/exp_eps_cppad.cpp %$$ $head Implementation$$ The file $xref/exp_eps.hpp/$$ contains a C++ implementation of this function. $head Test$$ The file $xref/exp_eps.cpp/$$ contains a test of this implementation. It returns true for success and false for failure. $head Exercises$$ $list number$$ Using the definition of $latex k( x, \varepsilon )$$ above, what is the value of $latex k(.5, 1)$$, $latex k(.5, .1)$$, and $latex k(.5, .01)$$ ? $lnext Suppose that we make the following call to $code exp_eps$$: $codep double x = 1.; double epsilon = .01; double y = exp_eps(x, epsilon); $$ What is the value assigned to $code k$$, $code temp$$, $code term$$, and $code sum$$ the first time through the $code while$$ loop in $cref/exp_eps.hpp/$$ ? $lnext Continuing the previous exercise, what is the value assigned to $code k$$, $code temp$$, $code term$$, and $code sum$$ the second time through the $code while$$ loop in $cref/exp_eps.hpp/$$ ? $lend $end ----------------------------------------------------------------------------- */ // BEGIN PROGRAM template <class Type> Type exp_eps(const Type &x, const Type &epsilon) { // abs_x = |x| Type abs_x = x; if( Type(0) > x ) abs_x = - x; // initialize int k = 0; // initial order Type term = 1.; // term = |x|^k / k ! Type sum = term; // initial sum while(term > epsilon) { k = k + 1; // order for next term Type temp = term * abs_x; // term = |x|^k / (k-1)! term = temp / Type(k); // term = |x|^k / k ! sum = sum + term; // sum = 1 + ... + |x|^k / k ! } // In the case where x is negative, use exp(x) = 1 / exp(-|x|) if( Type(0) > x ) sum = Type(1) / sum; return sum; } // END PROGRAM # endif
/* $Id$ */ # ifndef CPPAD_EXP_EPS_INCLUDED # define CPPAD_EXP_EPS_INCLUDED /* -------------------------------------------------------------------------- CppAD: C++ Algorithmic Differentiation: Copyright (C) 2003-07 Bradley M. Bell CppAD is distributed under multiple licenses. This distribution is under the terms of the Common Public License Version 1.0. A copy of this license is included in the COPYING file of this distribution. Please visit http://www.coin-or.org/CppAD/ for information on other licenses. -------------------------------------------------------------------------- */ /* $begin exp_eps$$ $spell cppad-%yyyymmdd% hpp Apx cpp const exp_eps bool $$ $section An Epsilon Accurate Exponential Approximation$$ $index exp_eps$$ $index example, algorithm$$ $index algorithm, example$$ $index exp, example$$ $head Syntax$$ $codei%# include "exp_eps.hpp"%$$ $pre $$ $icode%y% = exp_eps(%x%, %epsilon%)%$$ $head Purpose$$ This is a an example algorithm that is used to demonstrate how Algorithmic Differentiation works with loops and boolean decision variables (see $cref/exp_2/$$ for a simpler example). $head Mathematical Function$$ The exponential function can be defined by $latex \[ \exp (x) = 1 + x^1 / 1 ! + x^2 / 2 ! + \cdots \] $$ We define $latex k ( x, \varepsilon ) $$ as the smallest non-negative integer such that $latex \varepsilon \geq x^k / k !$$; i.e., $latex \[ k( x, \varepsilon ) = \min \{ k \in {\rm Z}_+ \; | \; \varepsilon \geq x^k / k ! \} \] $$ The mathematical form for our approximation of the exponential function is $latex \[ \begin{array}{rcl} {\rm exp\_eps} (x , \varepsilon ) & = & \left\{ \begin{array}{ll} \frac{1}{ {\rm exp\_eps} (-x , \varepsilon ) } & {\rm if} \; x < 0 \\ 1 + x^1 / 1 ! + \cdots + x^{k( x, \varepsilon)} / k( x, \varepsilon ) ! & {\rm otherwise} \end{array} \right. \end{array} \] $$ $head include$$ The include command in the syntax is relative to $codei% cppad-%yyyymmdd%/introduction/exp_apx %$$ where $codei%cppad-%yyyymmdd%$$ is the distribution directory created during the beginning steps of the $cref%installation%Install%$$ of CppAD. $head x$$ The argument $icode x$$ has prototype $codei% const %Type% &%x% %$$ (see $icode Type$$ below). It specifies the point at which to evaluate the approximation for the exponential function. $head epsilon$$ The argument $icode epsilon$$ has prototype $codei% const %Type% &%epsilon% %$$ It specifies the accuracy with which to approximate the exponential function value; i.e., it is the value of $latex \varepsilon$$ in the exponential function approximation defined above. $head y$$ The result $icode y$$ has prototype $codei% %Type% %y% %$$ It is the value of the exponential function approximation defined above. $head Type$$ If $icode u$$ and $italic v$$ are $italic Type$$ objects and $italic i$$ is an $code int$$: $table $bold Operation$$ $cnext $bold Result Type$$ $cnext $bold Description$$ $rnext $icode%Type%(%i%)%$$ $cnext $icode Type$$ $cnext object with value equal to $icode i$$ $rnext $icode%u% > %v%$$ $cnext $code bool$$ $cnext true, if $icode u$$ greater than $italic v$$, an false otherwise $rnext $icode%u% = %v%$$ $cnext $icode Type$$ $cnext new $icode u$$ (and result) is value of $italic v$$ $rnext $icode%u% * %v%$$ $cnext $icode Type$$ $cnext result is value of $latex u * v$$ $rnext $icode%u% / %v%$$ $cnext $icode Type$$ $cnext result is value of $latex u / v$$ $rnext $icode%u% + %v%$$ $cnext $icode Type$$ $cnext result is value of $latex u + v$$ $rnext $codei%-%u%$$ $cnext $icode Type$$ $cnext result is value of $latex - u$$ $tend $children% introduction/exp_apx/exp_eps.omh% introduction/exp_apx/exp_eps_cppad.cpp %$$ $head Implementation$$ The file $cref/exp_eps.hpp/$$ contains a C++ implementation of this function. $head Test$$ The file $cref/exp_eps.cpp/$$ contains a test of this implementation. It returns true for success and false for failure. $head Exercises$$ $list number$$ Using the definition of $latex k( x, \varepsilon )$$ above, what is the value of $latex k(.5, 1)$$, $latex k(.5, .1)$$, and $latex k(.5, .01)$$ ? $lnext Suppose that we make the following call to $code exp_eps$$: $codep double x = 1.; double epsilon = .01; double y = exp_eps(x, epsilon); $$ What is the value assigned to $code k$$, $code temp$$, $code term$$, and $code sum$$ the first time through the $code while$$ loop in $cref/exp_eps.hpp/$$ ? $lnext Continuing the previous exercise, what is the value assigned to $code k$$, $code temp$$, $code term$$, and $code sum$$ the second time through the $code while$$ loop in $cref/exp_eps.hpp/$$ ? $lend $end ----------------------------------------------------------------------------- */ // BEGIN PROGRAM template <class Type> Type exp_eps(const Type &x, const Type &epsilon) { // abs_x = |x| Type abs_x = x; if( Type(0) > x ) abs_x = - x; // initialize int k = 0; // initial order Type term = 1.; // term = |x|^k / k ! Type sum = term; // initial sum while(term > epsilon) { k = k + 1; // order for next term Type temp = term * abs_x; // term = |x|^k / (k-1)! term = temp / Type(k); // term = |x|^k / k ! sum = sum + term; // sum = 1 + ... + |x|^k / k ! } // In the case where x is negative, use exp(x) = 1 / exp(-|x|) if( Type(0) > x ) sum = Type(1) / sum; return sum; } // END PROGRAM # endif
convert exp_eps.hpp to more modern omhelp formatting
convert exp_eps.hpp to more modern omhelp formatting git-svn-id: 3f5418f4deb1796ec361794c2e3ca0aec3c9c1fd@1897 0e562018-b8fb-0310-a933-ecf073c7c197
C++
epl-1.0
wegamekinglc/CppAD,kaskr/CppAD,kaskr/CppAD,kaskr/CppAD,utke1/cppad,kaskr/CppAD,wegamekinglc/CppAD,utke1/cppad,wegamekinglc/CppAD,wegamekinglc/CppAD,kaskr/CppAD,utke1/cppad,wegamekinglc/CppAD,utke1/cppad
b732d667f13b0de4958d595ebb4ccc4788b8d084
QBrowseButton.cc
QBrowseButton.cc
/** \file * * \brief Implementation of \a QBrowseButton * * This file provides the implementation of the \a QBrowseButton class. * * \author Peter 'png' Hille <[email protected]> * * \version 1.0 */ #include <QHBoxLayout> #include <QDebug> #include <QMessageBox> #include "nullptr.h" #include "QBrowseButton.h" /** \brief Create new QBrowseButton instance * * Initializes a new QBrowseButton widget that can be used to browse for a * file. * * \param parent Parent QWidget that owns the newly created QBrowseButton */ QBrowseButton::QBrowseButton(QWidget *parent) : QFrame(parent), m_mode(QFileDialog::AnyFile), m_caption(tr("Browse for file")), m_selectedItem(""), m_completer(nullptr), m_fileSystemModel(nullptr), m_needsToExist(false) { setupUi(); } /** \brief Create new QBrowseButton for directories * * Initializes a QBrowseButton widget that can be used to browse for a * directory. * * \param dir Directory where the browser shall start * \param parent Parent QWidget that owns the newly created QBrowseButton */ QBrowseButton::QBrowseButton(QDir dir, QWidget *parent) : QFrame(parent), m_mode(QFileDialog::DirectoryOnly), m_caption(tr("Browse for directory")), m_selectedItem(dir.absolutePath()) { setupUi(); setSelectedItem(m_selectedItem); } /** \brief Initialize sub-widgets * * Initializes the sub-widgets that belong to the QBrowseButton instance. * * \internal This helper method is called from the class constructors to reduce code * redundancy for initializing all the child widgets of our button. */ void QBrowseButton::setupUi() { QHBoxLayout* hbox = nullptr; try { hbox = new QHBoxLayout(this); } catch (std::bad_alloc& ex) { qCritical() << "Caught exception when trying to allocate new QVBoxLayout in" << Q_FUNC_INFO << ":" << ex.what(); throw; } try { ui_leSelectedItem = new QLineEdit(m_selectedItem, this); ui_leSelectedItem->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Minimum); connect(ui_leSelectedItem, SIGNAL(textChanged(QString)), this, SLOT(leSelectedItem_textChanged(QString))); } catch (std::bad_alloc& ex) { qCritical() << "Caught exception when trying to allocate new QLineEdit in" << Q_FUNC_INFO << ":" << ex.what(); throw; } try { m_completer = new QCompleter(this); } catch (std::bad_alloc& ex) { qCritical() << "Caught exception when trying to allocate new QCompleter in" << Q_FUNC_INFO << ":" << ex.what(); QString message = tr("Caught exception when trying to allocate new QCompleter in %1: %2").arg(Q_FUNC_INFO, ex.what()); QMessageBox::critical(this, tr("Out of memory"), message, QMessageBox::Ok); throw; } try { m_fileSystemModel = new QFileSystemModel(m_completer); m_fileSystemModel->setRootPath(QDir::rootPath()); } catch (std::bad_alloc& ex) { qCritical() << "Caught exception when trying to allocate new QFileSystemModel in" << Q_FUNC_INFO << ":" << ex.what(); QString message = tr("Caught exception when trying to allocate new " "QFileSystemModel in %1: %2").arg(Q_FUNC_INFO, ex.what()); QMessageBox::critical(this, tr("Out of memory"), message, QMessageBox::Ok); throw; } m_completer->setModel(m_fileSystemModel); ui_leSelectedItem->setCompleter(m_completer); hbox->addWidget(ui_leSelectedItem); try { ui_btnBrowse = new QPushButton(tr("..."), this); if (m_mode == QFileDialog::AnyFile) ui_btnBrowse->setIcon(QIcon::fromTheme("document-open")); else ui_btnBrowse->setIcon(QIcon::fromTheme("folder-open")); ui_btnBrowse->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Minimum); connect(ui_btnBrowse, SIGNAL(clicked()), this, SLOT(btnBrowse_clicked())); hbox->addWidget(ui_btnBrowse); } catch (std::bad_alloc& ex) { qCritical() << "Caught exception when trying to allocate new QPushButton in" << Q_FUNC_INFO << ":" << ex.what(); throw; } QFrame::setFrameStyle(QFrame::StyledPanel | QFrame::Raised); QFrame::setLineWidth(1); QFrame::setLayout(hbox); } /** \brief Set open mode * * This can be used to specify wether the dialog that gets opened when the user clicks the 'browse' * button shall be a file or directory selection dialog by using either \a QFileDialog::AnyFile or * \a QFileDialog::DirectoryOnly as value for the \a mode parameter. * * \note Other values for \a mode are ignored and generate a \a qWarning message! * * \param mode New selection mode for this button */ void QBrowseButton::setMode(QFileDialog::FileMode mode) { if (!(mode == QFileDialog::AnyFile || QFileDialog::DirectoryOnly)) { qWarning() << "Unsupported open mode" << mode << "in" << Q_FUNC_INFO; return; } m_mode = mode; } /** \brief Set selection dialog caption * * Sets the caption for the selection dialog that is shown when the user clicks the 'browse' button. * * \param title New selection dialog caption */ void QBrowseButton::setCaption(QString title) { m_caption = title; } /** \brief Set selected item * * Sets the 'selected item' box of this button to a new value. * * \param path New path that shall be shown in the 'selected item' box */ void QBrowseButton::setSelectedItem(QString path) { m_selectedItem = path; ui_leSelectedItem->setText(path); } /** \brief Set icon for 'browse' button * * Sets the icon for the 'browse' button to a new QIcon. * * \param icon New icon for 'browse' button */ void QBrowseButton::setIcon(QIcon icon) { ui_btnBrowse->setIcon(icon); } /** \brief Set 'browse' button caption * * Sets the caption of the 'browse' button to a new value. * * \param text New caption for 'browse' button */ void QBrowseButton::setButtonText(QString text) { ui_btnBrowse->setText(text); } /** \brief Slot for \a clicked signal of 'browse' button * * \internal This slot is connected to the \a clicked() signal of \a ui_btnBrowse and shows * a file or directory selection dialog depending on the settings that have been * specified for this \a QBrowseButton instance. */ void QBrowseButton::btnBrowse_clicked() { QString selection; switch (m_mode) { case QFileDialog::DirectoryOnly: m_fileSystemModel->setFilter(QDir::Dirs); selection = QFileDialog::getExistingDirectory(this, m_caption, m_selectedItem); break; case QFileDialog::AnyFile: default: m_fileSystemModel->setFilter(QDir::Files); selection = QFileDialog::getOpenFileName(this, m_caption, m_selectedItem, m_nameFilters.join(";;")); break; } if (selection.isNull()) return; m_selectedItem = selection; ui_leSelectedItem->setText(selection); } void QBrowseButton::setNeedsToExist(bool needsToExist) { m_needsToExist = needsToExist; } void QBrowseButton::leSelectedItem_textChanged(QString text) { QFileInfo fileInfo(text); if (m_needsToExist && !fileInfo.exists()) return; switch (m_mode) { case QFileDialog::DirectoryOnly: if (!fileInfo.isDir()) return; break; default: case QFileDialog::AnyFile: if (!fileInfo.isFile()) return; break; } qDebug() << "Emitting new selection signal: " << text; m_selectedItem = text; emit newSelection(text); } void QBrowseButton::setNameFilters(QStringList filters) { m_nameFilters = filters; m_fileSystemModel->setNameFilters(filters); }
/** \file * * \brief Implementation of \a QBrowseButton * * This file provides the implementation of the \a QBrowseButton class. * * \author Peter 'png' Hille <[email protected]> * * \version 1.0 */ #include <QHBoxLayout> #include <QDebug> #include <QMessageBox> #include "nullptr.h" #include "QBrowseButton.h" /** \brief Create new QBrowseButton instance * * Initializes a new QBrowseButton widget that can be used to browse for a * file. * * \param parent Parent QWidget that owns the newly created QBrowseButton */ QBrowseButton::QBrowseButton(QWidget *parent) : QFrame(parent), m_mode(QFileDialog::AnyFile), m_caption(tr("Browse for file")), m_selectedItem(""), m_completer(nullptr), m_fileSystemModel(nullptr), m_needsToExist(false) { setupUi(); } /** \brief Create new QBrowseButton for directories * * Initializes a QBrowseButton widget that can be used to browse for a * directory. * * \param dir Directory where the browser shall start * \param parent Parent QWidget that owns the newly created QBrowseButton */ QBrowseButton::QBrowseButton(QDir dir, QWidget *parent) : QFrame(parent), m_mode(QFileDialog::DirectoryOnly), m_caption(tr("Browse for directory")), m_selectedItem(dir.absolutePath()) { setupUi(); setSelectedItem(m_selectedItem); } /** \brief Initialize sub-widgets * * Initializes the sub-widgets that belong to the QBrowseButton instance. * * \internal This helper method is called from the class constructors to reduce code * redundancy for initializing all the child widgets of our button. */ void QBrowseButton::setupUi() { QHBoxLayout* hbox = nullptr; try { hbox = new QHBoxLayout(this); } catch (std::bad_alloc& ex) { qCritical() << "Caught exception when trying to allocate new QVBoxLayout in" << Q_FUNC_INFO << ":" << ex.what(); throw; } try { ui_leSelectedItem = new QLineEdit(m_selectedItem, this); ui_leSelectedItem->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Minimum); connect(ui_leSelectedItem, SIGNAL(textChanged(QString)), this, SLOT(leSelectedItem_textChanged(QString))); } catch (std::bad_alloc& ex) { qCritical() << "Caught exception when trying to allocate new QLineEdit in" << Q_FUNC_INFO << ":" << ex.what(); throw; } try { m_completer = new QCompleter(this); } catch (std::bad_alloc& ex) { qCritical() << "Caught exception when trying to allocate new QCompleter in" << Q_FUNC_INFO << ":" << ex.what(); QString message = tr("Caught exception when trying to allocate new QCompleter in %1: %2").arg(Q_FUNC_INFO, ex.what()); QMessageBox::critical(this, tr("Out of memory"), message, QMessageBox::Ok); throw; } try { m_fileSystemModel = new QFileSystemModel(m_completer); m_fileSystemModel->setRootPath(QDir::rootPath()); } catch (std::bad_alloc& ex) { qCritical() << "Caught exception when trying to allocate new QFileSystemModel in" << Q_FUNC_INFO << ":" << ex.what(); QString message = tr("Caught exception when trying to allocate new " "QFileSystemModel in %1: %2").arg(Q_FUNC_INFO, ex.what()); QMessageBox::critical(this, tr("Out of memory"), message, QMessageBox::Ok); throw; } m_completer->setModel(m_fileSystemModel); ui_leSelectedItem->setCompleter(m_completer); hbox->addWidget(ui_leSelectedItem); try { ui_btnBrowse = new QPushButton(tr("..."), this); if (m_mode == QFileDialog::AnyFile) ui_btnBrowse->setIcon(QIcon::fromTheme("document-open")); else ui_btnBrowse->setIcon(QIcon::fromTheme("folder-open")); ui_btnBrowse->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Minimum); connect(ui_btnBrowse, SIGNAL(clicked()), this, SLOT(btnBrowse_clicked())); hbox->addWidget(ui_btnBrowse); } catch (std::bad_alloc& ex) { qCritical() << "Caught exception when trying to allocate new QPushButton in" << Q_FUNC_INFO << ":" << ex.what(); throw; } QFrame::setFrameStyle(QFrame::StyledPanel | QFrame::Raised); QFrame::setLineWidth(1); QFrame::setLayout(hbox); } /** \brief Set open mode * * This can be used to specify wether the dialog that gets opened when the user clicks the 'browse' * button shall be a file or directory selection dialog by using either \a QFileDialog::AnyFile or * \a QFileDialog::DirectoryOnly as value for the \a mode parameter. * * \note Other values for \a mode are ignored and generate a \a qWarning message! * * \param mode New selection mode for this button */ void QBrowseButton::setMode(QFileDialog::FileMode mode) { if (!(mode == QFileDialog::AnyFile || QFileDialog::DirectoryOnly)) { qWarning() << "Unsupported open mode" << mode << "in" << Q_FUNC_INFO; return; } m_mode = mode; } /** \brief Set selection dialog caption * * Sets the caption for the selection dialog that is shown when the user clicks the 'browse' button. * * \param title New selection dialog caption */ void QBrowseButton::setCaption(QString title) { m_caption = title; } /** \brief Set selected item * * Sets the 'selected item' box of this button to a new value. * * \param path New path that shall be shown in the 'selected item' box */ void QBrowseButton::setSelectedItem(QString path) { m_selectedItem = path; ui_leSelectedItem->setText(path); } /** \brief Set icon for 'browse' button * * Sets the icon for the 'browse' button to a new QIcon. * * \param icon New icon for 'browse' button */ void QBrowseButton::setIcon(QIcon icon) { ui_btnBrowse->setIcon(icon); } /** \brief Set 'browse' button caption * * Sets the caption of the 'browse' button to a new value. * * \param text New caption for 'browse' button */ void QBrowseButton::setButtonText(QString text) { ui_btnBrowse->setText(text); } /** \brief Slot for \a clicked signal of 'browse' button * * \internal This slot is connected to the \a clicked() signal of \a ui_btnBrowse and shows * a file or directory selection dialog depending on the settings that have been * specified for this \a QBrowseButton instance. */ void QBrowseButton::btnBrowse_clicked() { QString selection; switch (m_mode) { case QFileDialog::DirectoryOnly: m_fileSystemModel->setFilter(QDir::Dirs); selection = QFileDialog::getExistingDirectory(this, m_caption, m_selectedItem); break; case QFileDialog::AnyFile: default: m_fileSystemModel->setFilter(QDir::Files); selection = QFileDialog::getOpenFileName(this, m_caption, m_selectedItem, m_nameFilters.join(";;")); break; } if (selection.isNull()) return; m_selectedItem = selection; ui_leSelectedItem->setText(selection); } void QBrowseButton::setNeedsToExist(bool needsToExist) { m_needsToExist = needsToExist; } void QBrowseButton::leSelectedItem_textChanged(QString text) { QFileInfo fileInfo(text); if (m_needsToExist && !fileInfo.exists()) return; switch (m_mode) { case QFileDialog::DirectoryOnly: if (!fileInfo.isDir()) return; break; default: case QFileDialog::AnyFile: if (!fileInfo.isFile()) return; break; } m_selectedItem = text; emit newSelection(text); } void QBrowseButton::setNameFilters(QStringList filters) { m_nameFilters = filters; m_fileSystemModel->setNameFilters(filters); }
Remove debug message
Remove debug message
C++
bsd-3-clause
png85/QBrowseButton
f1e025dc6896774a21df8ab3eb9e555df0a486d0
modules/imgproc/src/gabor.cpp
modules/imgproc/src/gabor.cpp
/*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000-2008, Intel Corporation, all rights reserved. // Copyright (C) 2009-2012, Willow Garage Inc., all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) however caused // and on any theory of liability, whether in contract, strict liability, // or tort (including negligence or otherwise) arising in any way out of // the use of this software, even if advised of the possibility of such damage. // //M*/ #include "precomp.hpp" /* Gabor filters and such. To be greatly extended to have full texture analysis. For the formulas and the explanation of the parameters see: http://en.wikipedia.org/wiki/Gabor_filter */ cv::Mat cv::getGaborKernel( Size ksize, double sigma, double theta, double lambd, double gamma, double psi, int ktype ) { double sigma_x = sigma; double sigma_y = sigma/gamma; int nstds = 3; int xmin, xmax, ymin, ymax; double c = cos(theta), s = sin(theta); if( ksize.width > 0 ) xmax = ksize.width/2; else xmax = cvRound(std::max(fabs(nstds*sigma_x*c), fabs(nstds*sigma_y*s))); if( ksize.height > 0 ) ymax = ksize.height/2; else ymax = cvRound(std::max(fabs(nstds*sigma_x*s), fabs(nstds*sigma_y*c))); xmin = -xmax; ymin = -ymax; CV_Assert( ktype == CV_32F || ktype == CV_64F ); Mat kernel(ymax - ymin + 1, xmax - xmin + 1, ktype); double scale = 1/(2*CV_PI*sigma_x*sigma_y); double ex = -0.5/(sigma_x*sigma_x); double ey = -0.5/(sigma_y*sigma_y); double cscale = CV_PI*2/lambd; for( int y = ymin; y <= ymax; y++ ) for( int x = xmin; x <= xmax; x++ ) { double xr = x*c + y*s; double yr = -x*s + y*c; double v = scale*exp(ex*xr*xr + ey*yr*yr)*cos(cscale*xr + psi); if( ktype == CV_32F ) kernel.at<float>(ymax - y, xmax - x) = (float)v; else kernel.at<double>(ymax - y, xmax - x) = v; } return kernel; } /* End of file. */
/*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000-2008, Intel Corporation, all rights reserved. // Copyright (C) 2009-2012, Willow Garage Inc., all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) however caused // and on any theory of liability, whether in contract, strict liability, // or tort (including negligence or otherwise) arising in any way out of // the use of this software, even if advised of the possibility of such damage. // //M*/ #include "precomp.hpp" /* Gabor filters and such. To be greatly extended to have full texture analysis. For the formulas and the explanation of the parameters see: http://en.wikipedia.org/wiki/Gabor_filter */ cv::Mat cv::getGaborKernel( Size ksize, double sigma, double theta, double lambd, double gamma, double psi, int ktype ) { double sigma_x = sigma; double sigma_y = sigma/gamma; int nstds = 3; int xmin, xmax, ymin, ymax; double c = cos(theta), s = sin(theta); if( ksize.width > 0 ) xmax = ksize.width/2; else xmax = cvRound(std::max(fabs(nstds*sigma_x*c), fabs(nstds*sigma_y*s))); if( ksize.height > 0 ) ymax = ksize.height/2; else ymax = cvRound(std::max(fabs(nstds*sigma_x*s), fabs(nstds*sigma_y*c))); xmin = -xmax; ymin = -ymax; CV_Assert( ktype == CV_32F || ktype == CV_64F ); Mat kernel(ymax - ymin + 1, xmax - xmin + 1, ktype); double scale = 1; double ex = -0.5/(sigma_x*sigma_x); double ey = -0.5/(sigma_y*sigma_y); double cscale = CV_PI*2/lambd; for( int y = ymin; y <= ymax; y++ ) for( int x = xmin; x <= xmax; x++ ) { double xr = x*c + y*s; double yr = -x*s + y*c; double v = scale*exp(ex*xr*xr + ey*yr*yr)*cos(cscale*xr + psi); if( ktype == CV_32F ) kernel.at<float>(ymax - y, xmax - x) = (float)v; else kernel.at<double>(ymax - y, xmax - x) = v; } return kernel; } /* End of file. */
delete normalization in gabor kernel #1995
delete normalization in gabor kernel #1995
C++
apache-2.0
opencv/opencv,opencv/opencv,opencv/opencv,opencv/opencv,opencv/opencv,apavlenko/opencv,opencv/opencv,opencv/opencv,opencv/opencv,apavlenko/opencv,apavlenko/opencv,apavlenko/opencv,apavlenko/opencv,apavlenko/opencv,opencv/opencv,opencv/opencv
d394e163b50de4082b2acd498f0ac6c261ed3753
neon/data/loader/image.hpp
neon/data/loader/image.hpp
/* Copyright 2016 Nervana Systems Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include <string.h> #include <stdlib.h> #include <fstream> #include <vector> #include <opencv2/core/core.hpp> #include <opencv2/imgproc/imgproc.hpp> #include <opencv2/highgui/highgui.hpp> #include "media.hpp" using cv::Mat; using cv::Rect; using cv::Point2i; using cv::Size2i; using std::ofstream; using std::vector; class ImageParams : public MediaParams { public: ImageParams(int channelCount, int height, int width, bool augment, bool flip, int scaleMin, int scaleMax, int contrastMin, int contrastMax, int rotateMin, int rotateMax, int aspectRatio) : MediaParams(IMAGE), _channelCount(channelCount), _height(height), _width(width), _augment(augment), _flip(flip), _scaleMin(scaleMin), _scaleMax(scaleMax), _contrastMin(contrastMin), _contrastMax(contrastMax), _rotateMin(rotateMin), _rotateMax(rotateMax), _aspectRatio(aspectRatio) { } ImageParams() : ImageParams(3, 224, 224, false, false, 256, 256, 0, 0, 0, 0, 0) {} void dump() { MediaParams::dump(); printf("inner height %d\n", _height); printf("inner width %d\n", _width); printf("augment %d\n", _augment); printf("flip %d\n", _flip); printf("scale min %d\n", _scaleMin); printf("scale max %d\n", _scaleMax); printf("contrast min %d\n", _contrastMin); printf("contrast max %d\n", _contrastMax); printf("rotate min %d\n", _rotateMin); printf("rotate max %d\n", _rotateMax); printf("aspect ratio %d\n", _aspectRatio); } bool doRandomFlip(unsigned int& seed) { return _flip && (rand_r(&seed) % 2 == 0); } void getRandomCorner(unsigned int& seed, const Size2i &border, Point2i* point) { if (_augment) { point->x = rand_r(&seed) % (border.width + 1); point->y = rand_r(&seed) % (border.height + 1); } else { point->x = border.width / 2; point->y = border.height / 2; } } float getRandomContrast(unsigned int& seed) { if (_contrastMin == _contrastMax) { return 0; } return (_contrastMin + (rand_r(&seed) % (_contrastMax - _contrastMin))) / 100.0; } // adjust the square cropSize to be an inner rectangle void getRandomAspectRatio(unsigned int& seed, Size2i &cropSize) { int ratio = (101 + (rand_r(&seed) % (_aspectRatio - 100))); float ratio_f = 100.0 / (float) ratio; int orientation = rand_r(&(seed)) % 2; if (orientation) { cropSize.height *= ratio_f; } else { cropSize.width *= ratio_f; } } void getRandomCrop(unsigned int& seed, const Size2i &inputSize, Rect* cropBox) { if ((inputSize.width < _width) || (inputSize.height < _height)) { cropBox->x = cropBox->y = 0; cropBox->width = inputSize.width; cropBox->height = inputSize.height; return; } Point2i corner; Size2i cropSize(_width, _height); getRandomCorner(seed, inputSize - cropSize, &corner); cropBox->width = cropSize.width; cropBox->height = cropSize.height; cropBox->x = corner.x; cropBox->y = corner.y; } void getRandomScaledCrop(unsigned int& seed, const Size2i &inputSize, Rect* cropBox) { // Use the entire squashed image (Caffe style evaluation) if (_scaleMin == 0) { cropBox->x = cropBox->y = 0; cropBox->width = inputSize.width; cropBox->height = inputSize.height; return; } int scaleSize = (_scaleMin + (rand_r(&seed) % (_scaleMax + 1 - _scaleMin))); float scaleFactor = std::min(inputSize.width, inputSize.height) / (float) scaleSize; Point2i corner; Size2i cropSize(_width * scaleFactor, _height * scaleFactor); if (_aspectRatio > 100) { getRandomAspectRatio(seed, cropSize); } getRandomCorner(seed, inputSize - cropSize, &corner); cropBox->width = cropSize.width; cropBox->height = cropSize.height; cropBox->x = corner.x; cropBox->y = corner.y; return; } const Size2i getSize() { return Size2i(_width, _height); } public: int _channelCount; int _height; int _width; bool _augment; bool _flip; // Pixel scale to jitter at (image from which to crop will have // short side in [scaleMin, Max]) int _scaleMin; int _scaleMax; int _contrastMin; int _contrastMax; int _rotateMin; int _rotateMax; int _aspectRatio; }; class ImageIngestParams : public MediaParams { public: bool _resizeAtIngest; // Minimum value of the short side int _sideMin; // Maximum value of the short side int _sideMax; }; void resizeInput(vector<char> &jpgdata, int maxDim){ // Takes the buffer containing encoded jpg, determines if its shortest dimension // is greater than maxDim. If so, it scales it down so that the shortest dimension // is equal to maxDim. equivalent to "512x512^>" for maxDim=512 geometry argument in // imagemagick Mat image = Mat(1, jpgdata.size(), CV_8UC3, &jpgdata[0]); Mat decodedImage = cv::imdecode(image, CV_LOAD_IMAGE_COLOR); int minDim = std::min(decodedImage.rows, decodedImage.cols); // If no resizing necessary, just return, original image still in jpgdata; if (minDim <= maxDim) return; vector<int> param = {CV_IMWRITE_JPEG_QUALITY, 90}; double scaleFactor = (double) maxDim / (double) minDim; Mat resizedImage; cv::resize(decodedImage, resizedImage, Size2i(0, 0), scaleFactor, scaleFactor, CV_INTER_AREA); cv::imencode(".jpg", resizedImage, *(reinterpret_cast<vector<uchar>*>(&jpgdata)), param); return; } class Image: public Media { public: Image(ImageParams *params, ImageIngestParams* ingestParams) : _params(params), _ingestParams(ingestParams), _rngSeed(0) { assert(params->_mtype == IMAGE); } void transform(char* item, int itemSize, char* buf, int bufSize) { Mat decodedImage; decode(item, itemSize, &decodedImage); Rect cropBox; _params->getRandomCrop(_rngSeed, decodedImage.size(), &cropBox); Mat croppedImage = decodedImage(cropBox); _params->getRandomScaledCrop(_rngSeed, croppedImage.size(), &cropBox); croppedImage = croppedImage(cropBox); auto innerSize = _params->getSize(); Mat resizedImage; if (innerSize.width == cropBox.width && innerSize.height == cropBox.height) { resizedImage = croppedImage; } else { resize(croppedImage, resizedImage, innerSize); } Mat flippedImage; Mat *finalImage; if (_params->doRandomFlip(_rngSeed)) { cv::flip(resizedImage, flippedImage, 1); finalImage = &flippedImage; } else { finalImage = &resizedImage; } Mat newImage; float alpha = _params->getRandomContrast(_rngSeed); if (alpha) { finalImage->convertTo(newImage, -1, alpha); finalImage = &newImage; } split(*finalImage, buf, bufSize); } void ingest(char** dataBuf, int* dataBufLen, int* dataLen) { if (_ingestParams == 0) { return; } if (_ingestParams->_resizeAtIngest == false) { return; } if ((_ingestParams->_sideMin <= 0) && (_ingestParams->_sideMax <= 0)) { throw std::runtime_error("Invalid ingest parameters. Cannot resize."); } if (_ingestParams->_sideMin > _ingestParams->_sideMax) { throw std::runtime_error("Invalid ingest parameters. Cannot resize."); } // Decode Mat decodedImage; decode(*dataBuf, *dataLen, &decodedImage); // Resize int width = decodedImage.cols; int height = decodedImage.rows; int shortSide = std::min(width, height); if ((shortSide >= _ingestParams->_sideMin) && (shortSide <= _ingestParams->_sideMax)) { return; } if (width <= height) { if (width < _ingestParams->_sideMin) { height = height * _ingestParams->_sideMin / width; width = _ingestParams->_sideMin; } else if (width > _ingestParams->_sideMax) { height = height * _ingestParams->_sideMax / width; width = _ingestParams->_sideMax; } } else { if (height < _ingestParams->_sideMin) { width = width * _ingestParams->_sideMin / height; height = _ingestParams->_sideMin; } else if (height > _ingestParams->_sideMax) { width = width * _ingestParams->_sideMax / height; height = _ingestParams->_sideMax; } } Size2i size(width, height); Mat resizedImage; resize(decodedImage, resizedImage, size); // Re-encode vector<int> param = {CV_IMWRITE_PNG_COMPRESSION, 9}; vector<uchar> output; cv::imencode(".png", resizedImage, output, param); if (*dataBufLen < (int) output.size()) { delete[] *dataBuf; *dataBuf = new char[output.size()]; *dataBufLen = output.size(); } std::copy(output.begin(), output.end(), *dataBuf); *dataLen = output.size(); } void save_binary(char *filn, char* item, int itemSize, char* buf) { ofstream file(filn, ofstream::out | ofstream::binary); file.write((char*)(&itemSize), sizeof(int)); file.write((char*)item, itemSize); printf("wrote %s\n", filn); } private: void decode(char* item, int itemSize, Mat* dst) { if (_params->_channelCount == 1) { Mat image = Mat(1, itemSize, CV_8UC1, item); cv::imdecode(image, CV_LOAD_IMAGE_GRAYSCALE, dst); } else if (_params->_channelCount == 3) { Mat image = Mat(1, itemSize, CV_8UC3, item); cv::imdecode(image, CV_LOAD_IMAGE_COLOR, dst); } else { stringstream ss; ss << "Unsupported number of channels in image: " << _params->_channelCount; throw std::runtime_error(ss.str()); } } void resize(const Mat& input, Mat& output, const Size2i& size) { int inter = input.size().area() < size.area() ? CV_INTER_CUBIC : CV_INTER_AREA; cv::resize(input, output, size, 0, 0, inter); } void split(Mat& img, char* buf, int bufSize) { Size2i size = img.size(); if (img.channels() * img.total() > (uint) bufSize) { throw std::runtime_error("Decode failed - buffer too small"); } if (img.channels() == 1) { memcpy(buf, img.data, img.total()); return; } // Split into separate channels Mat ch_b(size, CV_8U, buf); Mat ch_g(size, CV_8U, buf + size.area()); Mat ch_r(size, CV_8U, buf + size.area() * 2); Mat channels[3] = {ch_b, ch_g, ch_r}; cv::split(img, channels); } private: ImageParams* _params; ImageIngestParams* _ingestParams; unsigned int _rngSeed; };
/* Copyright 2016 Nervana Systems Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include <string.h> #include <stdlib.h> #include <fstream> #include <vector> #include <opencv2/core/core.hpp> #include <opencv2/imgproc/imgproc.hpp> #include <opencv2/highgui/highgui.hpp> #include "media.hpp" using cv::Mat; using cv::Rect; using cv::Point2i; using cv::Size2i; using std::ofstream; using std::vector; class ImageParams : public MediaParams { public: ImageParams(int channelCount, int height, int width, bool augment, bool flip, int scaleMin, int scaleMax, int contrastMin, int contrastMax, int rotateMin, int rotateMax, int aspectRatio) : MediaParams(IMAGE), _channelCount(channelCount), _height(height), _width(width), _augment(augment), _flip(flip), _scaleMin(scaleMin), _scaleMax(scaleMax), _contrastMin(contrastMin), _contrastMax(contrastMax), _rotateMin(rotateMin), _rotateMax(rotateMax), _aspectRatio(aspectRatio) { } ImageParams() : ImageParams(3, 224, 224, false, false, 256, 256, 0, 0, 0, 0, 0) {} void dump() { MediaParams::dump(); printf("inner height %d\n", _height); printf("inner width %d\n", _width); printf("augment %d\n", _augment); printf("flip %d\n", _flip); printf("scale min %d\n", _scaleMin); printf("scale max %d\n", _scaleMax); printf("contrast min %d\n", _contrastMin); printf("contrast max %d\n", _contrastMax); printf("rotate min %d\n", _rotateMin); printf("rotate max %d\n", _rotateMax); printf("aspect ratio %d\n", _aspectRatio); } bool doRandomFlip(unsigned int& seed) { return _flip && (rand_r(&seed) % 2 == 0); } void getRandomCorner(unsigned int& seed, const Size2i &border, Point2i* point) { if (_augment) { point->x = rand_r(&seed) % (border.width + 1); point->y = rand_r(&seed) % (border.height + 1); } else { point->x = border.width / 2; point->y = border.height / 2; } } float getRandomContrast(unsigned int& seed) { if (_contrastMin == _contrastMax) { return 0; } return (_contrastMin + (rand_r(&seed) % (_contrastMax - _contrastMin))) / 100.0; } // adjust the square cropSize to be an inner rectangle void getRandomAspectRatio(unsigned int& seed, Size2i &cropSize) { int ratio = (101 + (rand_r(&seed) % (_aspectRatio - 100))); float ratio_f = 100.0 / (float) ratio; int orientation = rand_r(&(seed)) % 2; if (orientation) { cropSize.height *= ratio_f; } else { cropSize.width *= ratio_f; } } void getRandomCrop(unsigned int& seed, const Size2i &inputSize, Rect* cropBox) { if ((inputSize.width < _width) || (inputSize.height < _height)) { cropBox->x = cropBox->y = 0; cropBox->width = inputSize.width; cropBox->height = inputSize.height; return; } Point2i corner; Size2i cropSize(_width, _height); getRandomCorner(seed, inputSize - cropSize, &corner); cropBox->width = cropSize.width; cropBox->height = cropSize.height; cropBox->x = corner.x; cropBox->y = corner.y; } void getRandomAngle(unsigned int& seed, int& angle) { if (_augment == false) { angle = 0; return; } if (_rotateMax < _rotateMin) { throw std::runtime_error("Max angle is less than min angle"); } if (_rotateMax > 180) { throw std::runtime_error("Invalid max angle"); } if (_rotateMin < -180) { throw std::runtime_error("Invalid min angle"); } angle = (rand_r(&seed) % (_rotateMax + 1 - _rotateMin)) + _rotateMin; } void getRandomScaledCrop(unsigned int& seed, const Size2i &inputSize, Rect* cropBox) { // Use the entire squashed image (Caffe style evaluation) if (_scaleMin == 0) { cropBox->x = cropBox->y = 0; cropBox->width = inputSize.width; cropBox->height = inputSize.height; return; } int scaleSize = (_scaleMin + (rand_r(&seed) % (_scaleMax + 1 - _scaleMin))); float scaleFactor = std::min(inputSize.width, inputSize.height) / (float) scaleSize; Point2i corner; Size2i cropSize(_width * scaleFactor, _height * scaleFactor); if (_aspectRatio > 100) { getRandomAspectRatio(seed, cropSize); } getRandomCorner(seed, inputSize - cropSize, &corner); cropBox->width = cropSize.width; cropBox->height = cropSize.height; cropBox->x = corner.x; cropBox->y = corner.y; return; } const Size2i getSize() { return Size2i(_width, _height); } public: int _channelCount; int _height; int _width; bool _augment; bool _flip; // Pixel scale to jitter at (image from which to crop will have // short side in [scaleMin, Max]) int _scaleMin; int _scaleMax; int _contrastMin; int _contrastMax; int _rotateMin; int _rotateMax; int _aspectRatio; }; class ImageIngestParams : public MediaParams { public: bool _resizeAtIngest; // Minimum value of the short side int _sideMin; // Maximum value of the short side int _sideMax; }; void resizeInput(vector<char> &jpgdata, int maxDim){ // Takes the buffer containing encoded jpg, determines if its shortest dimension // is greater than maxDim. If so, it scales it down so that the shortest dimension // is equal to maxDim. equivalent to "512x512^>" for maxDim=512 geometry argument in // imagemagick Mat image = Mat(1, jpgdata.size(), CV_8UC3, &jpgdata[0]); Mat decodedImage = cv::imdecode(image, CV_LOAD_IMAGE_COLOR); int minDim = std::min(decodedImage.rows, decodedImage.cols); // If no resizing necessary, just return, original image still in jpgdata; if (minDim <= maxDim) return; vector<int> param = {CV_IMWRITE_JPEG_QUALITY, 90}; double scaleFactor = (double) maxDim / (double) minDim; Mat resizedImage; cv::resize(decodedImage, resizedImage, Size2i(0, 0), scaleFactor, scaleFactor, CV_INTER_AREA); cv::imencode(".jpg", resizedImage, *(reinterpret_cast<vector<uchar>*>(&jpgdata)), param); return; } class Image: public Media { public: Image(ImageParams *params, ImageIngestParams* ingestParams) : _params(params), _ingestParams(ingestParams), _rngSeed(0) { assert(params->_mtype == IMAGE); } void transform(char* item, int itemSize, char* buf, int bufSize) { Mat decodedImage; decode(item, itemSize, &decodedImage); int angle; _params->getRandomAngle(_rngSeed, angle); Mat rotatedImage; if (angle == 0) { rotatedImage = decodedImage; } else { rotate(decodedImage, rotatedImage, angle); } Rect cropBox; _params->getRandomCrop(_rngSeed, rotatedImage.size(), &cropBox); Mat croppedView = rotatedImage(cropBox); Mat croppedImage; croppedView.copyTo(croppedImage); _params->getRandomScaledCrop(_rngSeed, croppedImage.size(), &cropBox); croppedImage = croppedImage(cropBox); auto innerSize = _params->getSize(); Mat resizedImage; if (innerSize.width == cropBox.width && innerSize.height == cropBox.height) { resizedImage = croppedImage; } else { resize(croppedImage, resizedImage, innerSize); } Mat flippedImage; Mat *finalImage; if (_params->doRandomFlip(_rngSeed)) { cv::flip(resizedImage, flippedImage, 1); finalImage = &flippedImage; } else { finalImage = &resizedImage; } Mat newImage; float alpha = _params->getRandomContrast(_rngSeed); if (alpha) { finalImage->convertTo(newImage, -1, alpha); finalImage = &newImage; } split(*finalImage, buf, bufSize); } void ingest(char** dataBuf, int* dataBufLen, int* dataLen) { if (_ingestParams == 0) { return; } if (_ingestParams->_resizeAtIngest == false) { return; } if ((_ingestParams->_sideMin <= 0) && (_ingestParams->_sideMax <= 0)) { throw std::runtime_error("Invalid ingest parameters. Cannot resize."); } if (_ingestParams->_sideMin > _ingestParams->_sideMax) { throw std::runtime_error("Invalid ingest parameters. Cannot resize."); } // Decode Mat decodedImage; decode(*dataBuf, *dataLen, &decodedImage); // Resize int width = decodedImage.cols; int height = decodedImage.rows; int shortSide = std::min(width, height); if ((shortSide >= _ingestParams->_sideMin) && (shortSide <= _ingestParams->_sideMax)) { return; } if (width <= height) { if (width < _ingestParams->_sideMin) { height = height * _ingestParams->_sideMin / width; width = _ingestParams->_sideMin; } else if (width > _ingestParams->_sideMax) { height = height * _ingestParams->_sideMax / width; width = _ingestParams->_sideMax; } } else { if (height < _ingestParams->_sideMin) { width = width * _ingestParams->_sideMin / height; height = _ingestParams->_sideMin; } else if (height > _ingestParams->_sideMax) { width = width * _ingestParams->_sideMax / height; height = _ingestParams->_sideMax; } } Size2i size(width, height); Mat resizedImage; resize(decodedImage, resizedImage, size); // Re-encode vector<int> param = {CV_IMWRITE_PNG_COMPRESSION, 9}; vector<uchar> output; cv::imencode(".png", resizedImage, output, param); if (*dataBufLen < (int) output.size()) { delete[] *dataBuf; *dataBuf = new char[output.size()]; *dataBufLen = output.size(); } std::copy(output.begin(), output.end(), *dataBuf); *dataLen = output.size(); } void save_binary(char *filn, char* item, int itemSize, char* buf) { ofstream file(filn, ofstream::out | ofstream::binary); file.write((char*)(&itemSize), sizeof(int)); file.write((char*)item, itemSize); printf("wrote %s\n", filn); } private: void decode(char* item, int itemSize, Mat* dst) { if (_params->_channelCount == 1) { Mat image = Mat(1, itemSize, CV_8UC1, item); cv::imdecode(image, CV_LOAD_IMAGE_GRAYSCALE, dst); } else if (_params->_channelCount == 3) { Mat image = Mat(1, itemSize, CV_8UC3, item); cv::imdecode(image, CV_LOAD_IMAGE_COLOR, dst); } else { stringstream ss; ss << "Unsupported number of channels in image: " << _params->_channelCount; throw std::runtime_error(ss.str()); } } void rotate(const Mat& input, Mat& output, int angle) { Point2i pt(input.cols / 2, input.rows / 2); Mat rot = cv::getRotationMatrix2D(pt, angle, 1.0); cv::warpAffine(input, output, rot, input.size()); } void resize(const Mat& input, Mat& output, const Size2i& size) { int inter = input.size().area() < size.area() ? CV_INTER_CUBIC : CV_INTER_AREA; cv::resize(input, output, size, 0, 0, inter); } void split(Mat& img, char* buf, int bufSize) { Size2i size = img.size(); if (img.channels() * img.total() > (uint) bufSize) { throw std::runtime_error("Decode failed - buffer too small"); } if (img.channels() == 1) { memcpy(buf, img.data, img.total()); return; } // Split into separate channels Mat ch_b(size, CV_8U, buf); Mat ch_g(size, CV_8U, buf + size.area()); Mat ch_r(size, CV_8U, buf + size.area() * 2); Mat channels[3] = {ch_b, ch_g, ch_r}; cv::split(img, channels); } private: ImageParams* _params; ImageIngestParams* _ingestParams; unsigned int _rngSeed; };
Support random rotations on images
Support random rotations on images
C++
apache-2.0
NervanaSystems/neon,Jokeren/neon,NervanaSystems/neon,Jokeren/neon,NervanaSystems/neon,NervanaSystems/neon,Jokeren/neon,Jokeren/neon
a4309994fdd74e8db786ad43038ff6cd3dbf3a18
beast-gtk/bstparam-item-seq.cc
beast-gtk/bstparam-item-seq.cc
// Licensed GNU LGPL v2.1 or later: http://www.gnu.org/licenses/lgpl.html /* --- item sequence editors --- */ #include "bstitemseqdialog.hh" static void param_item_seq_changed (gpointer data, BseIt3mSeq *iseq, BstItemSeqDialog *isdialog) { GxkParam *param = (GxkParam*) data; SfiProxy proxy = bst_param_get_proxy (param); if (proxy) { SfiSeq *seq = bse_it3m_seq_to_seq (iseq); sfi_value_take_seq (&param->value, seq); gxk_param_apply_value (param); } } static void param_item_seq_popup_editor (GtkWidget *widget, GxkParam *param) { SfiProxy proxy = bst_param_get_proxy (param); if (proxy) { BsePropertyCandidates *pc = bse_item_get_property_candidates (proxy, param->pspec->name); SfiSeq *seq = (SfiSeq*) g_value_get_boxed (&param->value); BseIt3mSeq *iseq = bse_it3m_seq_from_seq (seq); bst_item_seq_dialog_popup (widget, proxy, pc->label, pc->tooltip, pc->items, g_param_spec_get_nick (param->pspec), g_param_spec_get_blurb (param->pspec), iseq, param_item_seq_changed, param, NULL); bse_it3m_seq_free (iseq); } } static GtkWidget* param_item_seq_create (GxkParam *param, const gchar *tooltip, guint variant) { /* create entry-look-alike dialog-popup button with "..." indicator */ GtkWidget *widget = (GtkWidget*) g_object_new (GTK_TYPE_BUTTON, "can-focus", 1, NULL); gxk_widget_set_tooltip (widget, tooltip); GtkWidget *box = (GtkWidget*) g_object_new (GTK_TYPE_HBOX, "parent", widget, "spacing", 3, NULL); GtkWidget *label = (GtkWidget*) g_object_new (GTK_TYPE_LABEL, "label", _("..."), NULL); gtk_box_pack_end (GTK_BOX (box), label, FALSE, TRUE, 0); GtkWidget *frame = (GtkWidget*) g_object_new (GTK_TYPE_FRAME, "shadow-type", GTK_SHADOW_IN, "border-width", 1, "parent", box, NULL); gxk_widget_modify_normal_bg_as_base (frame); GtkWidget *ebox = (GtkWidget*) g_object_new (GTK_TYPE_EVENT_BOX, "parent", frame, NULL); gxk_widget_modify_normal_bg_as_base (ebox); label = (GtkWidget*) g_object_new (GXK_TYPE_SIMPLE_LABEL, "parent", ebox, "auto-cut", TRUE, "xpad", 2, NULL); gxk_widget_modify_normal_bg_as_base (label); /* store handles */ g_object_set_data ((GObject*) widget, "beast-GxkParam", param); g_object_set_data ((GObject*) widget, "beast-GxkParam-label", label); /* connections */ g_object_connect (widget, "signal::clicked", param_item_seq_popup_editor, param, NULL); gtk_widget_show_all (widget); /* gxk_widget_add_option (box, "hexpand", "+"); */ return widget; } static void param_item_seq_update (GxkParam *param, GtkWidget *widget) { SfiProxy proxy = bst_param_get_proxy (param); gchar *content = NULL; if (proxy) { BsePropertyCandidates *pc = bse_item_get_property_candidates (proxy, param->pspec->name); SfiSeq *seq = (SfiSeq*) g_value_get_boxed (&param->value); BseIt3mSeq *iseq = seq ? bse_it3m_seq_from_seq (seq) : NULL; if (iseq) { if (iseq->n_items == 1) content = g_strdup_format ("%s", bse_item_get_name_or_type (iseq->items[0])); else if (iseq->n_items > 1 && (!pc->partitions || pc->partitions->n_types == 0)) content = g_strdup_format ("#%u", iseq->n_items); else if (iseq->n_items > 1) /* && partitions->n_types */ { guint i, j, other = 0, *partitions = g_newa (guint, pc->partitions->n_types); memset (partitions, 0, pc->partitions->n_types * sizeof (partitions[0])); for (i = 0; i < iseq->n_items; i++) { for (j = 0; j < pc->partitions->n_types; j++) if (bse_item_check_is_a (iseq->items[i], pc->partitions->types[j])) { partitions[j]++; break; } if (j >= pc->partitions->n_types) other++; } GString *gstring = g_string_new (""); for (j = 0; j < pc->partitions->n_types; j++) g_string_append_printf (gstring, "%s#%u", j ? " & " : "", partitions[j]); if (other) g_string_append_printf (gstring, " & #%u", other); content = g_string_free (gstring, FALSE); } bse_it3m_seq_free (iseq); } } GtkWidget *label = (GtkWidget*) g_object_get_data ((GObject*) widget, "beast-GxkParam-label"); g_object_set (label, "label", content ? content : "--", NULL); g_free (content); } static GxkParamEditor param_it3m_seq = { { "item-list", N_("Item List"), }, { G_TYPE_BOXED, "SfiSeq", }, { "item-sequence", +5, TRUE, }, /* options, rating, editing */ param_item_seq_create, param_item_seq_update, };
// Licensed GNU LGPL v2.1 or later: http://www.gnu.org/licenses/lgpl.html /* --- item sequence editors --- */ #include "bstitemseqdialog.hh" static void param_item_seq_changed (gpointer data, BseIt3mSeq *iseq, BstItemSeqDialog *isdialog) { GxkParam *param = (GxkParam*) data; SfiProxy proxy = bst_param_get_proxy (param); if (proxy) { SfiSeq *seq = bse_it3m_seq_to_seq (iseq); sfi_value_take_seq (&param->value, seq); gxk_param_apply_value (param); } } static void param_item_seq_popup_editor (GtkWidget *widget, GxkParam *param) { SfiProxy proxy = bst_param_get_proxy (param); if (proxy) { BsePropertyCandidates *pc = bse_item_get_property_candidates (proxy, param->pspec->name); SfiSeq *seq = (SfiSeq*) g_value_get_boxed (&param->value); BseIt3mSeq *iseq = bse_it3m_seq_from_seq (seq); bst_item_seq_dialog_popup (widget, proxy, pc->label, pc->tooltip, pc->items, g_param_spec_get_nick (param->pspec), g_param_spec_get_blurb (param->pspec), iseq, param_item_seq_changed, param, NULL); bse_it3m_seq_free (iseq); } } static GtkWidget* param_item_seq_create (GxkParam *param, const gchar *tooltip, guint variant) { /* create entry-look-alike dialog-popup button with "..." indicator */ GtkWidget *widget = (GtkWidget*) g_object_new (GTK_TYPE_BUTTON, "can-focus", 1, NULL); gxk_widget_set_tooltip (widget, tooltip); GtkWidget *box = (GtkWidget*) g_object_new (GTK_TYPE_HBOX, "parent", widget, "spacing", 3, NULL); GtkWidget *label = (GtkWidget*) g_object_new (GTK_TYPE_LABEL, "label", _("..."), NULL); gtk_box_pack_end (GTK_BOX (box), label, FALSE, TRUE, 0); GtkWidget *frame = (GtkWidget*) g_object_new (GTK_TYPE_FRAME, "shadow-type", GTK_SHADOW_IN, "border-width", 1, "parent", box, NULL); gxk_widget_modify_normal_bg_as_base (frame); GtkWidget *ebox = (GtkWidget*) g_object_new (GTK_TYPE_EVENT_BOX, "parent", frame, NULL); gxk_widget_modify_normal_bg_as_base (ebox); label = (GtkWidget*) g_object_new (GXK_TYPE_SIMPLE_LABEL, "parent", ebox, "auto-cut", TRUE, "xpad", 2, NULL); gxk_widget_modify_normal_bg_as_base (label); /* store handles */ g_object_set_data ((GObject*) widget, "beast-GxkParam", param); g_object_set_data ((GObject*) widget, "beast-GxkParam-label", label); /* connections */ g_object_connect (widget, "signal::clicked", param_item_seq_popup_editor, param, NULL); gtk_widget_show_all (widget); /* gxk_widget_add_option (box, "hexpand", "+"); */ return widget; } static void param_item_seq_update (GxkParam *param, GtkWidget *widget) { SfiProxy proxy = bst_param_get_proxy (param); gchar *content = NULL; if (proxy) { BsePropertyCandidates *pc = bse_item_get_property_candidates (proxy, param->pspec->name); SfiSeq *seq = (SfiSeq*) g_value_get_boxed (&param->value); BseIt3mSeq *iseq = seq ? bse_it3m_seq_from_seq (seq) : NULL; if (iseq) { if (iseq->n_items == 1) content = g_strdup_format ("%s", bse_item_get_name_or_type (iseq->items[0])); else if (iseq->n_items > 1 && (!pc->partitions || pc->partitions->n_types == 0)) content = g_strdup_format ("#%u", iseq->n_items); else if (iseq->n_items > 1) /* && partitions->n_types */ { guint i, j, other = 0, *partitions = g_newa (guint, pc->partitions->n_types); memset (partitions, 0, pc->partitions->n_types * sizeof (partitions[0])); for (i = 0; i < iseq->n_items; i++) { for (j = 0; j < pc->partitions->n_types; j++) { Bse::ItemH item = Bse::ItemH::down_cast (bse_server.from_proxy (iseq->items[i])); if (item.check_is_a (pc->partitions->types[j])) { partitions[j]++; break; } } if (j >= pc->partitions->n_types) other++; } GString *gstring = g_string_new (""); for (j = 0; j < pc->partitions->n_types; j++) g_string_append_printf (gstring, "%s#%u", j ? " & " : "", partitions[j]); if (other) g_string_append_printf (gstring, " & #%u", other); content = g_string_free (gstring, FALSE); } bse_it3m_seq_free (iseq); } } GtkWidget *label = (GtkWidget*) g_object_get_data ((GObject*) widget, "beast-GxkParam-label"); g_object_set (label, "label", content ? content : "--", NULL); g_free (content); } static GxkParamEditor param_it3m_seq = { { "item-list", N_("Item List"), }, { G_TYPE_BOXED, "SfiSeq", }, { "item-sequence", +5, TRUE, }, /* options, rating, editing */ param_item_seq_create, param_item_seq_update, };
adjust to use Item.check_is_a()
BST: adjust to use Item.check_is_a() Signed-off-by: Tim Janik <[email protected]>
C++
lgpl-2.1
tim-janik/beast,tim-janik/beast,tim-janik/beast,swesterfeld/beast,tim-janik/beast,GNOME/beast,swesterfeld/beast,GNOME/beast,tim-janik/beast,GNOME/beast,swesterfeld/beast,GNOME/beast,GNOME/beast,tim-janik/beast,GNOME/beast,swesterfeld/beast,GNOME/beast,tim-janik/beast,swesterfeld/beast,swesterfeld/beast,swesterfeld/beast
0436f43446c441027fb393288f20775c4cdb0b52
phonon/audiooutput.cpp
phonon/audiooutput.cpp
/* This file is part of the KDE project Copyright (C) 2005-2006 Matthias Kretz <[email protected]> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) version 3, or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), Nokia Corporation (or its successors, if any) and the KDE Free Qt Foundation, which shall act as a proxy defined in Section 6 of version 3 of the license. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see <http://www.gnu.org/licenses/>. */ #include "audiooutput.h" #include "audiooutput_p.h" #include "factory_p.h" #include "objectdescription.h" #include "audiooutputadaptor_p.h" #include "globalconfig_p.h" #include "audiooutputinterface.h" #include "phononnamespace_p.h" #include "platform_p.h" #include <qmath.h> #define PHONON_CLASSNAME AudioOutput #define IFACES2 AudioOutputInterface42 #define IFACES1 IFACES2 #define IFACES0 AudioOutputInterface40, IFACES1 #define PHONON_INTERFACENAME IFACES0 QT_BEGIN_NAMESPACE namespace Phonon { static inline bool callSetOutputDevice(MediaNodePrivate *const d, int index) { Iface<IFACES2> iface(d); if (iface) { return iface->setOutputDevice(AudioOutputDevice::fromIndex(index)); } return Iface<IFACES0>::cast(d)->setOutputDevice(index); } static inline bool callSetOutputDevice(MediaNodePrivate *const d, const AudioOutputDevice &dev) { Iface<IFACES2> iface(d); if (iface) { return iface->setOutputDevice(dev); } return Iface<IFACES0>::cast(d)->setOutputDevice(dev.index()); } AudioOutput::AudioOutput(Phonon::Category category, QObject *parent) : AbstractAudioOutput(*new AudioOutputPrivate, parent) { K_D(AudioOutput); d->init(category); } AudioOutput::AudioOutput(QObject *parent) : AbstractAudioOutput(*new AudioOutputPrivate, parent) { K_D(AudioOutput); d->init(NoCategory); } void AudioOutputPrivate::init(Phonon::Category c) { Q_Q(AudioOutput); #ifndef QT_NO_DBUS adaptor = new AudioOutputAdaptor(q); static unsigned int number = 0; const QString &path = QLatin1String("/AudioOutputs/") + QString::number(number++); QDBusConnection con = QDBusConnection::sessionBus(); con.registerObject(path, q); emit adaptor->newOutputAvailable(con.baseService(), path); q->connect(q, SIGNAL(volumeChanged(qreal)), adaptor, SIGNAL(volumeChanged(qreal))); q->connect(q, SIGNAL(mutedChanged(bool)), adaptor, SIGNAL(mutedChanged(bool))); #endif category = c; // select hardware device according to the category device = AudioOutputDevice::fromIndex(GlobalConfig().audioOutputDeviceFor(category, GlobalConfig::AdvancedDevicesFromSettings | GlobalConfig::HideUnavailableDevices)); createBackendObject(); q->connect(Factory::sender(), SIGNAL(availableAudioOutputDevicesChanged()), SLOT(_k_deviceListChanged())); } void AudioOutputPrivate::createBackendObject() { if (m_backendObject) return; Q_Q(AudioOutput); m_backendObject = Factory::createAudioOutput(q); if (m_backendObject) { setupBackendObject(); } } QString AudioOutput::name() const { K_D(const AudioOutput); return d->name; } void AudioOutput::setName(const QString &newName) { K_D(AudioOutput); if (d->name == newName) { return; } d->name = newName; setVolume(Platform::loadVolume(newName)); #ifndef QT_NO_DBUS if (d->adaptor) { emit d->adaptor->nameChanged(newName); } #endif } static const qreal LOUDNESS_TO_VOLTAGE_EXPONENT = qreal(0.67); static const qreal VOLTAGE_TO_LOUDNESS_EXPONENT = qreal(1.0/LOUDNESS_TO_VOLTAGE_EXPONENT); void AudioOutput::setVolume(qreal volume) { K_D(AudioOutput); d->volume = volume; if (k_ptr->backendObject() && !d->muted) { // using Stevens' power law loudness is proportional to (sound pressure)^0.67 // sound pressure is proportional to voltage: // p² \prop P \prop V² // => if a factor for loudness of x is requested INTERFACE_CALL(setVolume(pow(volume, VOLTAGE_TO_LOUDNESS_EXPONENT))); } else { emit volumeChanged(volume); } Platform::saveVolume(d->name, volume); } qreal AudioOutput::volume() const { K_D(const AudioOutput); if (d->muted || !d->m_backendObject) { return d->volume; } return pow(INTERFACE_CALL(volume()), LOUDNESS_TO_VOLTAGE_EXPONENT); } #ifndef PHONON_LOG10OVER20 #define PHONON_LOG10OVER20 static const qreal log10over20 = qreal(0.1151292546497022842); // ln(10) / 20 #endif // PHONON_LOG10OVER20 qreal AudioOutput::volumeDecibel() const { K_D(const AudioOutput); if (d->muted || !d->m_backendObject) { return log(d->volume) / log10over20; } return 0.67 * log(INTERFACE_CALL(volume())) / log10over20; } void AudioOutput::setVolumeDecibel(qreal newVolumeDecibel) { setVolume(exp(newVolumeDecibel * log10over20)); } bool AudioOutput::isMuted() const { K_D(const AudioOutput); return d->muted; } void AudioOutput::setMuted(bool mute) { K_D(AudioOutput); if (d->muted != mute) { if (mute) { d->muted = mute; if (k_ptr->backendObject()) { INTERFACE_CALL(setVolume(0.0)); } } else { if (k_ptr->backendObject()) { INTERFACE_CALL(setVolume(pow(d->volume, VOLTAGE_TO_LOUDNESS_EXPONENT))); } d->muted = mute; } emit mutedChanged(mute); } } Category AudioOutput::category() const { K_D(const AudioOutput); return d->category; } AudioOutputDevice AudioOutput::outputDevice() const { K_D(const AudioOutput); return d->device; } bool AudioOutput::setOutputDevice(const AudioOutputDevice &newAudioOutputDevice) { K_D(AudioOutput); if (!newAudioOutputDevice.isValid()) { d->outputDeviceOverridden = false; const int newIndex = GlobalConfig().audioOutputDeviceFor(d->category); if (newIndex == d->device.index()) { return true; } d->device = AudioOutputDevice::fromIndex(newIndex); } else { d->outputDeviceOverridden = true; if (d->device == newAudioOutputDevice) { return true; } d->device = newAudioOutputDevice; } if (k_ptr->backendObject()) { return callSetOutputDevice(k_ptr, d->device.index()); } return true; } bool AudioOutputPrivate::aboutToDeleteBackendObject() { if (m_backendObject) { volume = pINTERFACE_CALL(volume()); } return AbstractAudioOutputPrivate::aboutToDeleteBackendObject(); } void AudioOutputPrivate::setupBackendObject() { Q_Q(AudioOutput); Q_ASSERT(m_backendObject); AbstractAudioOutputPrivate::setupBackendObject(); QObject::connect(m_backendObject, SIGNAL(volumeChanged(qreal)), q, SLOT(_k_volumeChanged(qreal))); QObject::connect(m_backendObject, SIGNAL(audioDeviceFailed()), q, SLOT(_k_audioDeviceFailed())); // set up attributes pINTERFACE_CALL(setVolume(pow(volume, VOLTAGE_TO_LOUDNESS_EXPONENT))); // if the output device is not available and the device was not explicitly set if (!callSetOutputDevice(this, device) && !outputDeviceOverridden) { // fall back in the preference list of output devices QList<int> deviceList = GlobalConfig().audioOutputDeviceListFor(category, GlobalConfig::AdvancedDevicesFromSettings | GlobalConfig::HideUnavailableDevices); if (deviceList.isEmpty()) { return; } foreach (int devIndex, deviceList) { const AudioOutputDevice &dev = AudioOutputDevice::fromIndex(devIndex); if (callSetOutputDevice(this, dev)) { handleAutomaticDeviceChange(dev, AudioOutputPrivate::FallbackChange); return; // found one that works } } // if we get here there is no working output device. Tell the backend. const AudioOutputDevice none; callSetOutputDevice(this, none); handleAutomaticDeviceChange(none, FallbackChange); } } void AudioOutputPrivate::_k_volumeChanged(qreal newVolume) { if (!muted) { Q_Q(AudioOutput); emit q->volumeChanged(pow(newVolume, qreal(0.67))); } } void AudioOutputPrivate::_k_revertFallback() { if (deviceBeforeFallback == -1) { return; } device = AudioOutputDevice::fromIndex(deviceBeforeFallback); callSetOutputDevice(this, device); Q_Q(AudioOutput); emit q->outputDeviceChanged(device); #ifndef QT_NO_DBUS emit adaptor->outputDeviceIndexChanged(device.index()); #endif } void AudioOutputPrivate::_k_audioDeviceFailed() { pDebug() << Q_FUNC_INFO; // outputDeviceIndex identifies a failing device // fall back in the preference list of output devices QList<int> deviceList = GlobalConfig().audioOutputDeviceListFor(category, GlobalConfig::AdvancedDevicesFromSettings | GlobalConfig::HideUnavailableDevices); foreach (int devIndex, deviceList) { // if it's the same device as the one that failed, ignore it if (device.index() != devIndex) { const AudioOutputDevice &info = AudioOutputDevice::fromIndex(devIndex); if (callSetOutputDevice(this, info)) { handleAutomaticDeviceChange(info, FallbackChange); return; // found one that works } } } // if we get here there is no working output device. Tell the backend. const AudioOutputDevice none; callSetOutputDevice(this, none); handleAutomaticDeviceChange(none, FallbackChange); } void AudioOutputPrivate::_k_deviceListChanged() { pDebug() << Q_FUNC_INFO; // let's see if there's a usable device higher in the preference list QList<int> deviceList = GlobalConfig().audioOutputDeviceListFor(category, GlobalConfig::AdvancedDevicesFromSettings); DeviceChangeType changeType = HigherPreferenceChange; foreach (int devIndex, deviceList) { const AudioOutputDevice &info = AudioOutputDevice::fromIndex(devIndex); if (!info.property("available").toBool()) { if (device.index() == devIndex) { // we've reached the currently used device and it's not available anymore, so we // fallback to the next available device changeType = FallbackChange; } pDebug() << devIndex << "is not available"; continue; } pDebug() << devIndex << "is available"; if (device.index() == devIndex) { // we've reached the currently used device, nothing to change break; } if (callSetOutputDevice(this, info)) { handleAutomaticDeviceChange(info, changeType); break; // found one with higher preference that works } } } static struct { int first; int second; } g_lastFallback = { 0, 0 }; void AudioOutputPrivate::handleAutomaticDeviceChange(const AudioOutputDevice &device2, DeviceChangeType type) { Q_Q(AudioOutput); deviceBeforeFallback = device.index(); device = device2; emit q->outputDeviceChanged(device2); #ifndef QT_NO_DBUS emit adaptor->outputDeviceIndexChanged(device.index()); #endif const AudioOutputDevice &device1 = AudioOutputDevice::fromIndex(deviceBeforeFallback); switch (type) { case FallbackChange: if (g_lastFallback.first != device1.index() || g_lastFallback.second != device2.index()) { #ifndef QT_NO_PHONON_PLATFORMPLUGIN const QString &text = //device2.isValid() ? AudioOutput::tr("<html>The audio playback device <b>%1</b> does not work.<br/>" "Falling back to <b>%2</b>.</html>").arg(device1.name()).arg(device2.name()) /*: AudioOutput::tr("<html>The audio playback device <b>%1</b> does not work.<br/>" "No other device available.</html>").arg(device1.name())*/; Platform::notification("AudioDeviceFallback", text); #endif //QT_NO_PHONON_PLATFORMPLUGIN g_lastFallback.first = device1.index(); g_lastFallback.second = device2.index(); } break; case HigherPreferenceChange: { #ifndef QT_NO_PHONON_PLATFORMPLUGIN const QString text = AudioOutput::tr("<html>Switching to the audio playback device <b>%1</b><br/>" "which just became available and has higher preference.</html>").arg(device2.name()); Platform::notification("AudioDeviceFallback", text, QStringList(AudioOutput::tr("Revert back to device '%1'").arg(device1.name())), q, SLOT(_k_revertFallback())); #endif //QT_NO_PHONON_PLATFORMPLUGIN g_lastFallback.first = 0; g_lastFallback.second = 0; } break; } } AudioOutputPrivate::~AudioOutputPrivate() { #ifndef QT_NO_DBUS if (adaptor) { emit adaptor->outputDestroyed(); } #endif } } //namespace Phonon QT_END_NAMESPACE #include "moc_audiooutput.cpp" #undef PHONON_CLASSNAME #undef PHONON_INTERFACENAME #undef IFACES2 #undef IFACES1 #undef IFACES0
/* This file is part of the KDE project Copyright (C) 2005-2006 Matthias Kretz <[email protected]> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) version 3, or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), Nokia Corporation (or its successors, if any) and the KDE Free Qt Foundation, which shall act as a proxy defined in Section 6 of version 3 of the license. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see <http://www.gnu.org/licenses/>. */ #include "audiooutput.h" #include "audiooutput_p.h" #include "factory_p.h" #include "objectdescription.h" #include "audiooutputadaptor_p.h" #include "globalconfig_p.h" #include "audiooutputinterface.h" #include "phononnamespace_p.h" #include "platform_p.h" #include <QtCore/qmath.h> #define PHONON_CLASSNAME AudioOutput #define IFACES2 AudioOutputInterface42 #define IFACES1 IFACES2 #define IFACES0 AudioOutputInterface40, IFACES1 #define PHONON_INTERFACENAME IFACES0 QT_BEGIN_NAMESPACE namespace Phonon { static inline bool callSetOutputDevice(MediaNodePrivate *const d, int index) { Iface<IFACES2> iface(d); if (iface) { return iface->setOutputDevice(AudioOutputDevice::fromIndex(index)); } return Iface<IFACES0>::cast(d)->setOutputDevice(index); } static inline bool callSetOutputDevice(MediaNodePrivate *const d, const AudioOutputDevice &dev) { Iface<IFACES2> iface(d); if (iface) { return iface->setOutputDevice(dev); } return Iface<IFACES0>::cast(d)->setOutputDevice(dev.index()); } AudioOutput::AudioOutput(Phonon::Category category, QObject *parent) : AbstractAudioOutput(*new AudioOutputPrivate, parent) { K_D(AudioOutput); d->init(category); } AudioOutput::AudioOutput(QObject *parent) : AbstractAudioOutput(*new AudioOutputPrivate, parent) { K_D(AudioOutput); d->init(NoCategory); } void AudioOutputPrivate::init(Phonon::Category c) { Q_Q(AudioOutput); #ifndef QT_NO_DBUS adaptor = new AudioOutputAdaptor(q); static unsigned int number = 0; const QString &path = QLatin1String("/AudioOutputs/") + QString::number(number++); QDBusConnection con = QDBusConnection::sessionBus(); con.registerObject(path, q); emit adaptor->newOutputAvailable(con.baseService(), path); q->connect(q, SIGNAL(volumeChanged(qreal)), adaptor, SIGNAL(volumeChanged(qreal))); q->connect(q, SIGNAL(mutedChanged(bool)), adaptor, SIGNAL(mutedChanged(bool))); #endif category = c; // select hardware device according to the category device = AudioOutputDevice::fromIndex(GlobalConfig().audioOutputDeviceFor(category, GlobalConfig::AdvancedDevicesFromSettings | GlobalConfig::HideUnavailableDevices)); createBackendObject(); q->connect(Factory::sender(), SIGNAL(availableAudioOutputDevicesChanged()), SLOT(_k_deviceListChanged())); } void AudioOutputPrivate::createBackendObject() { if (m_backendObject) return; Q_Q(AudioOutput); m_backendObject = Factory::createAudioOutput(q); if (m_backendObject) { setupBackendObject(); } } QString AudioOutput::name() const { K_D(const AudioOutput); return d->name; } void AudioOutput::setName(const QString &newName) { K_D(AudioOutput); if (d->name == newName) { return; } d->name = newName; setVolume(Platform::loadVolume(newName)); #ifndef QT_NO_DBUS if (d->adaptor) { emit d->adaptor->nameChanged(newName); } #endif } static const qreal LOUDNESS_TO_VOLTAGE_EXPONENT = qreal(0.67); static const qreal VOLTAGE_TO_LOUDNESS_EXPONENT = qreal(1.0/LOUDNESS_TO_VOLTAGE_EXPONENT); void AudioOutput::setVolume(qreal volume) { K_D(AudioOutput); d->volume = volume; if (k_ptr->backendObject() && !d->muted) { // using Stevens' power law loudness is proportional to (sound pressure)^0.67 // sound pressure is proportional to voltage: // p² \prop P \prop V² // => if a factor for loudness of x is requested INTERFACE_CALL(setVolume(pow(volume, VOLTAGE_TO_LOUDNESS_EXPONENT))); } else { emit volumeChanged(volume); } Platform::saveVolume(d->name, volume); } qreal AudioOutput::volume() const { K_D(const AudioOutput); if (d->muted || !d->m_backendObject) { return d->volume; } return pow(INTERFACE_CALL(volume()), LOUDNESS_TO_VOLTAGE_EXPONENT); } #ifndef PHONON_LOG10OVER20 #define PHONON_LOG10OVER20 static const qreal log10over20 = qreal(0.1151292546497022842); // ln(10) / 20 #endif // PHONON_LOG10OVER20 qreal AudioOutput::volumeDecibel() const { K_D(const AudioOutput); if (d->muted || !d->m_backendObject) { return log(d->volume) / log10over20; } return 0.67 * log(INTERFACE_CALL(volume())) / log10over20; } void AudioOutput::setVolumeDecibel(qreal newVolumeDecibel) { setVolume(exp(newVolumeDecibel * log10over20)); } bool AudioOutput::isMuted() const { K_D(const AudioOutput); return d->muted; } void AudioOutput::setMuted(bool mute) { K_D(AudioOutput); if (d->muted != mute) { if (mute) { d->muted = mute; if (k_ptr->backendObject()) { INTERFACE_CALL(setVolume(0.0)); } } else { if (k_ptr->backendObject()) { INTERFACE_CALL(setVolume(pow(d->volume, VOLTAGE_TO_LOUDNESS_EXPONENT))); } d->muted = mute; } emit mutedChanged(mute); } } Category AudioOutput::category() const { K_D(const AudioOutput); return d->category; } AudioOutputDevice AudioOutput::outputDevice() const { K_D(const AudioOutput); return d->device; } bool AudioOutput::setOutputDevice(const AudioOutputDevice &newAudioOutputDevice) { K_D(AudioOutput); if (!newAudioOutputDevice.isValid()) { d->outputDeviceOverridden = false; const int newIndex = GlobalConfig().audioOutputDeviceFor(d->category); if (newIndex == d->device.index()) { return true; } d->device = AudioOutputDevice::fromIndex(newIndex); } else { d->outputDeviceOverridden = true; if (d->device == newAudioOutputDevice) { return true; } d->device = newAudioOutputDevice; } if (k_ptr->backendObject()) { return callSetOutputDevice(k_ptr, d->device.index()); } return true; } bool AudioOutputPrivate::aboutToDeleteBackendObject() { if (m_backendObject) { volume = pINTERFACE_CALL(volume()); } return AbstractAudioOutputPrivate::aboutToDeleteBackendObject(); } void AudioOutputPrivate::setupBackendObject() { Q_Q(AudioOutput); Q_ASSERT(m_backendObject); AbstractAudioOutputPrivate::setupBackendObject(); QObject::connect(m_backendObject, SIGNAL(volumeChanged(qreal)), q, SLOT(_k_volumeChanged(qreal))); QObject::connect(m_backendObject, SIGNAL(audioDeviceFailed()), q, SLOT(_k_audioDeviceFailed())); // set up attributes pINTERFACE_CALL(setVolume(pow(volume, VOLTAGE_TO_LOUDNESS_EXPONENT))); // if the output device is not available and the device was not explicitly set if (!callSetOutputDevice(this, device) && !outputDeviceOverridden) { // fall back in the preference list of output devices QList<int> deviceList = GlobalConfig().audioOutputDeviceListFor(category, GlobalConfig::AdvancedDevicesFromSettings | GlobalConfig::HideUnavailableDevices); if (deviceList.isEmpty()) { return; } foreach (int devIndex, deviceList) { const AudioOutputDevice &dev = AudioOutputDevice::fromIndex(devIndex); if (callSetOutputDevice(this, dev)) { handleAutomaticDeviceChange(dev, AudioOutputPrivate::FallbackChange); return; // found one that works } } // if we get here there is no working output device. Tell the backend. const AudioOutputDevice none; callSetOutputDevice(this, none); handleAutomaticDeviceChange(none, FallbackChange); } } void AudioOutputPrivate::_k_volumeChanged(qreal newVolume) { if (!muted) { Q_Q(AudioOutput); emit q->volumeChanged(pow(newVolume, qreal(0.67))); } } void AudioOutputPrivate::_k_revertFallback() { if (deviceBeforeFallback == -1) { return; } device = AudioOutputDevice::fromIndex(deviceBeforeFallback); callSetOutputDevice(this, device); Q_Q(AudioOutput); emit q->outputDeviceChanged(device); #ifndef QT_NO_DBUS emit adaptor->outputDeviceIndexChanged(device.index()); #endif } void AudioOutputPrivate::_k_audioDeviceFailed() { pDebug() << Q_FUNC_INFO; // outputDeviceIndex identifies a failing device // fall back in the preference list of output devices QList<int> deviceList = GlobalConfig().audioOutputDeviceListFor(category, GlobalConfig::AdvancedDevicesFromSettings | GlobalConfig::HideUnavailableDevices); foreach (int devIndex, deviceList) { // if it's the same device as the one that failed, ignore it if (device.index() != devIndex) { const AudioOutputDevice &info = AudioOutputDevice::fromIndex(devIndex); if (callSetOutputDevice(this, info)) { handleAutomaticDeviceChange(info, FallbackChange); return; // found one that works } } } // if we get here there is no working output device. Tell the backend. const AudioOutputDevice none; callSetOutputDevice(this, none); handleAutomaticDeviceChange(none, FallbackChange); } void AudioOutputPrivate::_k_deviceListChanged() { pDebug() << Q_FUNC_INFO; // let's see if there's a usable device higher in the preference list QList<int> deviceList = GlobalConfig().audioOutputDeviceListFor(category, GlobalConfig::AdvancedDevicesFromSettings); DeviceChangeType changeType = HigherPreferenceChange; foreach (int devIndex, deviceList) { const AudioOutputDevice &info = AudioOutputDevice::fromIndex(devIndex); if (!info.property("available").toBool()) { if (device.index() == devIndex) { // we've reached the currently used device and it's not available anymore, so we // fallback to the next available device changeType = FallbackChange; } pDebug() << devIndex << "is not available"; continue; } pDebug() << devIndex << "is available"; if (device.index() == devIndex) { // we've reached the currently used device, nothing to change break; } if (callSetOutputDevice(this, info)) { handleAutomaticDeviceChange(info, changeType); break; // found one with higher preference that works } } } static struct { int first; int second; } g_lastFallback = { 0, 0 }; void AudioOutputPrivate::handleAutomaticDeviceChange(const AudioOutputDevice &device2, DeviceChangeType type) { Q_Q(AudioOutput); deviceBeforeFallback = device.index(); device = device2; emit q->outputDeviceChanged(device2); #ifndef QT_NO_DBUS emit adaptor->outputDeviceIndexChanged(device.index()); #endif const AudioOutputDevice &device1 = AudioOutputDevice::fromIndex(deviceBeforeFallback); switch (type) { case FallbackChange: if (g_lastFallback.first != device1.index() || g_lastFallback.second != device2.index()) { #ifndef QT_NO_PHONON_PLATFORMPLUGIN const QString &text = //device2.isValid() ? AudioOutput::tr("<html>The audio playback device <b>%1</b> does not work.<br/>" "Falling back to <b>%2</b>.</html>").arg(device1.name()).arg(device2.name()) /*: AudioOutput::tr("<html>The audio playback device <b>%1</b> does not work.<br/>" "No other device available.</html>").arg(device1.name())*/; Platform::notification("AudioDeviceFallback", text); #endif //QT_NO_PHONON_PLATFORMPLUGIN g_lastFallback.first = device1.index(); g_lastFallback.second = device2.index(); } break; case HigherPreferenceChange: { #ifndef QT_NO_PHONON_PLATFORMPLUGIN const QString text = AudioOutput::tr("<html>Switching to the audio playback device <b>%1</b><br/>" "which just became available and has higher preference.</html>").arg(device2.name()); Platform::notification("AudioDeviceFallback", text, QStringList(AudioOutput::tr("Revert back to device '%1'").arg(device1.name())), q, SLOT(_k_revertFallback())); #endif //QT_NO_PHONON_PLATFORMPLUGIN g_lastFallback.first = 0; g_lastFallback.second = 0; } break; } } AudioOutputPrivate::~AudioOutputPrivate() { #ifndef QT_NO_DBUS if (adaptor) { emit adaptor->outputDestroyed(); } #endif } } //namespace Phonon QT_END_NAMESPACE #include "moc_audiooutput.cpp" #undef PHONON_CLASSNAME #undef PHONON_INTERFACENAME #undef IFACES2 #undef IFACES1 #undef IFACES0
Fix qmath.h include: should be written <QtCore/qmath.h> instead of <qmath.h> in order to be consistent with the rest of the code that use <QtCore/...>
Fix qmath.h include: should be written <QtCore/qmath.h> instead of <qmath.h> in order to be consistent with the rest of the code that use <QtCore/...>
C++
lgpl-2.1
KDE/phonon-gstreamer,shadeslayer/phonon-gstreamer,KDE/phonon-xine,KDE/phonon-xine,KDE/phonon-directshow,KDE/phonon-quicktime,KDE/phonon-mmf,shadeslayer/phonon-gstreamer,shadeslayer/phonon-gstreamer,KDE/phonon-gstreamer,KDE/phonon-waveout,KDE/phonon-xine,KDE/phonon-directshow
dcc414bdf52148b8f76d684505bb0a3fc997cecf
plugins/qt/context.cpp
plugins/qt/context.cpp
#include "context.h" #include <QMetaType> #include <QVariantList> /*! A meta method property for storing index */ #define DUK_QT_METAMETHOD_INDEX_PROPERTY "\1_____meta_method_index\1" /*! A meta method property for storing typename */ #define DUK_QT_METAMETHOD_TYPENAME_PROPERTY "\1_____meta_method_typename\1" /*! A meta method property for storing signature property */ #define DUK_QT_METAMETHOD_SIGNATURE_PROPERTY "\1_____meta_method_signature\1" #define HAS_QT5 ( QT_VERSION >= 0x050000 ) dukpp03::qt::Context::Context() { #define REGISTER_METATYPE(TYPE) \ if (QMetaType::type(#TYPE) == QMetaType::UnknownType) \ { \ qRegisterMetaType< DUKPP03_TYPE(TYPE) >(#TYPE); \ } REGISTER_METATYPE(long double) REGISTER_METATYPE(std::string) REGISTER_METATYPE(dukpp03::qt::ObjectWithOwnership) if (QMetaType::type("QPair<QObject*, dukpp03::qt::ValueOwnership>") == QMetaType::UnknownType) { qRegisterMetaType<QPair<QObject*, dukpp03::qt::ValueOwnership> >("QPair<QObject*, dukpp03::qt::ValueOwnership>"); } // Provice global finalizer functions to garbage collect and finalize QObjects duk_push_global_object(m_context); duk_push_c_function(m_context, dukpp03::qt::qobjectfinalizer, 1); duk_def_prop(m_context, -3, DUK_DEFPROP_HAVE_VALUE | DUK_DEFPROP_HAVE_WRITABLE | 0); duk_pop(m_context); } dukpp03::qt::Context::~Context() { } // Taken from https://gist.github.com/andref/2838534 static QVariant metamethod_call(QObject* object, QMetaMethod metaMethod, QVariantList args, QString* error) { // Convert the arguments QVariantList converted; // We need enough arguments to perform the conversion. QList<QByteArray> methodTypes = metaMethod.parameterTypes(); if (methodTypes.size() < args.size()) { *error = "Insufficient arguments to call "; #ifdef HAS_QT5 *error += metaMethod.methodSignature(); #else *error += metaMethod.signature(); #endif return QVariant(); } for (int i = 0; i < methodTypes.size(); i++) { const QVariant& arg = args.at(i); QByteArray methodTypeName = methodTypes.at(i); QByteArray argTypeName = arg.typeName(); QVariant::Type methodType = QVariant::nameToType(methodTypeName); // ReSharper disable once CppEntityNeverUsed QVariant::Type argType = arg.type(); QVariant copy = QVariant(arg); // If the types are not the same, attempt a conversion. If it // fails, we cannot proceed. if (copy.type() != methodType) { if (copy.canConvert(methodType)) { if (!copy.convert(methodType)) { *error = "Cannot convert "; *error += argTypeName; *error += " to "; *error += methodTypeName; return QVariant(); } } } converted << copy; } QList<QGenericArgument> arguments; for (int i = 0; i < converted.size(); i++) { // Notice that we have to take a reference to the argument, else // we'd be pointing to a copy that will be destroyed when this // loop exits. QVariant& argument = converted[i]; // A const_cast is needed because calling data() would detach // the QVariant. QGenericArgument genericArgument( QMetaType::typeName(argument.userType()), const_cast<void*>(argument.constData()) ); arguments << genericArgument; } QVariant returnValue(QMetaType::type(metaMethod.typeName()), static_cast<void*>(NULL)); QGenericReturnArgument returnArgument( metaMethod.typeName(), const_cast<void*>(returnValue.constData()) ); // Perform the call bool ok = metaMethod.invoke( object, Qt::DirectConnection, returnArgument, arguments.value(0), arguments.value(1), arguments.value(2), arguments.value(3), arguments.value(4), arguments.value(5), arguments.value(6), arguments.value(7), arguments.value(8), arguments.value(9) ); if (!ok) { *error = "Calling "; #ifdef HAS_QT5 *error += metaMethod.methodSignature(); #else *error += metaMethod.signature(); #endif *error = " failed."; return QVariant(); } else { return returnValue; } } static int dukqt_metamethod_call(duk_context *ctx) { duk_push_current_function(ctx); duk_get_prop_string(ctx, -1, DUK_QT_METAMETHOD_INDEX_PROPERTY); int index = duk_to_int(ctx, -1); duk_pop(ctx); duk_get_prop_string(ctx, -1, DUK_QT_METAMETHOD_TYPENAME_PROPERTY); QString typeName = duk_to_string(ctx, -1); duk_pop(ctx); duk_get_prop_string(ctx, -1, DUK_QT_METAMETHOD_SIGNATURE_PROPERTY); QString sourceSignature = duk_to_string(ctx, -1); duk_pop(ctx); duk_pop(ctx); dukpp03::Maybe< QObject* > maybethisobject; dukpp03::qt::Context* c = reinterpret_cast<dukpp03::qt::Context*>(dukpp03::qt::Context::getContext(ctx)); if (duk_is_constructor_call(ctx)) { c->throwFunctionCallShouldNotBeCalledAsConstructor(); return 0; } dukpp03::qt::Context::LocalCallable::CheckArgument< QObject* >::passedAsThis(c, maybethisobject); if (maybethisobject.exists()) { QObject* thisobj = maybethisobject.value(); const QMetaObject* obj = thisobj->metaObject(); bool error = true; if (index >= obj->methodOffset() && index < (obj->methodOffset() + obj->methodCount())) { QMetaMethod method = obj->method(index); QString signature; #ifdef HAS_QT5 signature = method.methodSignature(); #else signature = method.signature(); #endif if (method.typeName() == typeName && sourceSignature == signature) { error = false; QVariantList variants; for(size_t i = 0; i < c->getTop(); i++) { dukpp03::Maybe<QVariant> tmp = dukpp03::GetValue<QVariant, dukpp03::qt::Context>::perform(c, i); if (tmp.exists()) { variants << tmp.value(); } else { error = true; } } if (!error) { QString callerror; QVariant returnValue = metamethod_call(thisobj, method, variants, &callerror); // If error occured, throw it if (callerror.length()) { c->throwError(callerror.toStdString()); return 0; } // If method doesn't return anything, return it if (typeName.length() == 0) { return 0; } dukpp03::PushValue<QVariant, dukpp03::qt::Context>::perform(c, returnValue); return 1; } // If we reaches this point, then some attempt to construct type has failed c->throwError("Attempt to call a method on invalid arguments"); } } if (error) { c->throwError("Attempt to call non-existing method"); } } else { c->throwError("Cannot call a meta method: object passed as this is not an instance of QObject*"); } return 0; } void dukpp03::qt::Context::pushMetaMethod(int index, const QMetaMethod& meta_method) const { duk_push_c_function(m_context, dukqt_metamethod_call, meta_method.parameterTypes().size()); duk_push_string(m_context, DUK_QT_METAMETHOD_INDEX_PROPERTY); duk_push_int(m_context, index); duk_def_prop(m_context, -3, DUK_DEFPROP_HAVE_VALUE | DUK_DEFPROP_HAVE_WRITABLE | 0); duk_push_string(m_context, DUK_QT_METAMETHOD_TYPENAME_PROPERTY); duk_push_string(m_context, meta_method.typeName()); duk_def_prop(m_context, -3, DUK_DEFPROP_HAVE_VALUE | DUK_DEFPROP_HAVE_WRITABLE | 0); duk_push_string(m_context, DUK_QT_METAMETHOD_SIGNATURE_PROPERTY); #ifdef HAS_QT5 duk_push_string(m_context, meta_method.methodSignature()); #else duk_push_string(m_context, meta_method.signature()); #endif duk_def_prop(m_context, -3, DUK_DEFPROP_HAVE_VALUE | DUK_DEFPROP_HAVE_WRITABLE | 0); } void dukpp03::qt::Context::pushObject(QObject* o, dukpp03::qt::ValueOwnership p) { dukpp03::PushValue<dukpp03::qt::ObjectWithOwnership, dukpp03::qt::BasicContext>::perform(this, dukpp03::qt::ObjectWithOwnership(o, p)); } void dukpp03::qt::Context::registerGlobal(const QString& name, QObject* o, dukpp03::qt::ValueOwnership p) { duk_push_global_object(m_context); pushObject(o, p); duk_put_prop_string(m_context, -2, name.toStdString().c_str()); duk_pop(m_context); }
#include "context.h" #include <QMetaType> #include <QVariantList> /*! A meta method property for storing index */ #define DUK_QT_METAMETHOD_INDEX_PROPERTY "\1_____meta_method_index\1" /*! A meta method property for storing typename */ #define DUK_QT_METAMETHOD_TYPENAME_PROPERTY "\1_____meta_method_typename\1" /*! A meta method property for storing signature property */ #define DUK_QT_METAMETHOD_SIGNATURE_PROPERTY "\1_____meta_method_signature\1" #define HAS_QT5 ( QT_VERSION >= 0x050000 ) dukpp03::qt::Context::Context() { #define REGISTER_METATYPE(TYPE) \ if (QMetaType::type(#TYPE) == QMetaType::UnknownType) \ { \ qRegisterMetaType< DUKPP03_TYPE(TYPE) >(#TYPE); \ } REGISTER_METATYPE(long double) REGISTER_METATYPE(std::string) REGISTER_METATYPE(dukpp03::qt::ObjectWithOwnership) if (QMetaType::type("QPair<QObject*, dukpp03::qt::ValueOwnership>") == QMetaType::UnknownType) { qRegisterMetaType<QPair<QObject*, dukpp03::qt::ValueOwnership> >("QPair<QObject*, dukpp03::qt::ValueOwnership>"); } } dukpp03::qt::Context::~Context() { } // Taken from https://gist.github.com/andref/2838534 static QVariant metamethod_call(QObject* object, QMetaMethod metaMethod, QVariantList args, QString* error) { // Convert the arguments QVariantList converted; // We need enough arguments to perform the conversion. QList<QByteArray> methodTypes = metaMethod.parameterTypes(); if (methodTypes.size() < args.size()) { *error = "Insufficient arguments to call "; #ifdef HAS_QT5 *error += metaMethod.methodSignature(); #else *error += metaMethod.signature(); #endif return QVariant(); } for (int i = 0; i < methodTypes.size(); i++) { const QVariant& arg = args.at(i); QByteArray methodTypeName = methodTypes.at(i); QByteArray argTypeName = arg.typeName(); QVariant::Type methodType = QVariant::nameToType(methodTypeName); // ReSharper disable once CppEntityNeverUsed QVariant::Type argType = arg.type(); QVariant copy = QVariant(arg); // If the types are not the same, attempt a conversion. If it // fails, we cannot proceed. if (copy.type() != methodType) { if (copy.canConvert(methodType)) { if (!copy.convert(methodType)) { *error = "Cannot convert "; *error += argTypeName; *error += " to "; *error += methodTypeName; return QVariant(); } } } converted << copy; } QList<QGenericArgument> arguments; for (int i = 0; i < converted.size(); i++) { // Notice that we have to take a reference to the argument, else // we'd be pointing to a copy that will be destroyed when this // loop exits. QVariant& argument = converted[i]; // A const_cast is needed because calling data() would detach // the QVariant. QGenericArgument genericArgument( QMetaType::typeName(argument.userType()), const_cast<void*>(argument.constData()) ); arguments << genericArgument; } QVariant returnValue(QMetaType::type(metaMethod.typeName()), static_cast<void*>(NULL)); QGenericReturnArgument returnArgument( metaMethod.typeName(), const_cast<void*>(returnValue.constData()) ); // Perform the call bool ok = metaMethod.invoke( object, Qt::DirectConnection, returnArgument, arguments.value(0), arguments.value(1), arguments.value(2), arguments.value(3), arguments.value(4), arguments.value(5), arguments.value(6), arguments.value(7), arguments.value(8), arguments.value(9) ); if (!ok) { *error = "Calling "; #ifdef HAS_QT5 *error += metaMethod.methodSignature(); #else *error += metaMethod.signature(); #endif *error = " failed."; return QVariant(); } else { return returnValue; } } static int dukqt_metamethod_call(duk_context *ctx) { duk_push_current_function(ctx); duk_get_prop_string(ctx, -1, DUK_QT_METAMETHOD_INDEX_PROPERTY); int index = duk_to_int(ctx, -1); duk_pop(ctx); duk_get_prop_string(ctx, -1, DUK_QT_METAMETHOD_TYPENAME_PROPERTY); QString typeName = duk_to_string(ctx, -1); duk_pop(ctx); duk_get_prop_string(ctx, -1, DUK_QT_METAMETHOD_SIGNATURE_PROPERTY); QString sourceSignature = duk_to_string(ctx, -1); duk_pop(ctx); duk_pop(ctx); dukpp03::Maybe< QObject* > maybethisobject; dukpp03::qt::Context* c = reinterpret_cast<dukpp03::qt::Context*>(dukpp03::qt::Context::getContext(ctx)); if (duk_is_constructor_call(ctx)) { c->throwFunctionCallShouldNotBeCalledAsConstructor(); return 0; } dukpp03::qt::Context::LocalCallable::CheckArgument< QObject* >::passedAsThis(c, maybethisobject); if (maybethisobject.exists()) { QObject* thisobj = maybethisobject.value(); const QMetaObject* obj = thisobj->metaObject(); bool error = true; if (index >= obj->methodOffset() && index < (obj->methodOffset() + obj->methodCount())) { QMetaMethod method = obj->method(index); QString signature; #ifdef HAS_QT5 signature = method.methodSignature(); #else signature = method.signature(); #endif if (method.typeName() == typeName && sourceSignature == signature) { error = false; QVariantList variants; for(size_t i = 0; i < c->getTop(); i++) { dukpp03::Maybe<QVariant> tmp = dukpp03::GetValue<QVariant, dukpp03::qt::Context>::perform(c, i); if (tmp.exists()) { variants << tmp.value(); } else { error = true; } } if (!error) { QString callerror; QVariant returnValue = metamethod_call(thisobj, method, variants, &callerror); // If error occured, throw it if (callerror.length()) { c->throwError(callerror.toStdString()); return 0; } // If method doesn't return anything, return it if (typeName.length() == 0) { return 0; } dukpp03::PushValue<QVariant, dukpp03::qt::Context>::perform(c, returnValue); return 1; } // If we reaches this point, then some attempt to construct type has failed c->throwError("Attempt to call a method on invalid arguments"); } } if (error) { c->throwError("Attempt to call non-existing method"); } } else { c->throwError("Cannot call a meta method: object passed as this is not an instance of QObject*"); } return 0; } void dukpp03::qt::Context::pushMetaMethod(int index, const QMetaMethod& meta_method) const { duk_push_c_function(m_context, dukqt_metamethod_call, meta_method.parameterTypes().size()); duk_push_string(m_context, DUK_QT_METAMETHOD_INDEX_PROPERTY); duk_push_int(m_context, index); duk_def_prop(m_context, -3, DUK_DEFPROP_HAVE_VALUE | DUK_DEFPROP_HAVE_WRITABLE | 0); duk_push_string(m_context, DUK_QT_METAMETHOD_TYPENAME_PROPERTY); duk_push_string(m_context, meta_method.typeName()); duk_def_prop(m_context, -3, DUK_DEFPROP_HAVE_VALUE | DUK_DEFPROP_HAVE_WRITABLE | 0); duk_push_string(m_context, DUK_QT_METAMETHOD_SIGNATURE_PROPERTY); #ifdef HAS_QT5 duk_push_string(m_context, meta_method.methodSignature()); #else duk_push_string(m_context, meta_method.signature()); #endif duk_def_prop(m_context, -3, DUK_DEFPROP_HAVE_VALUE | DUK_DEFPROP_HAVE_WRITABLE | 0); } void dukpp03::qt::Context::pushObject(QObject* o, dukpp03::qt::ValueOwnership p) { dukpp03::PushValue<dukpp03::qt::ObjectWithOwnership, dukpp03::qt::BasicContext>::perform(this, dukpp03::qt::ObjectWithOwnership(o, p)); } void dukpp03::qt::Context::registerGlobal(const QString& name, QObject* o, dukpp03::qt::ValueOwnership p) { duk_push_global_object(m_context); pushObject(o, p); duk_put_prop_string(m_context, -2, name.toStdString().c_str()); duk_pop(m_context); }
Fix for removing function.
Fix for removing function.
C++
mit
mamontov-cpp/dukpp-03,mamontov-cpp/dukpp-03,mamontov-cpp/dukpp-03,mamontov-cpp/dukpp-03,mamontov-cpp/dukpp-03,mamontov-cpp/dukpp-03,mamontov-cpp/dukpp-03
2dac6f3e59b388fd2f4c129b92f7e11a1732424d
T0/MakeTrendT0.C
T0/MakeTrendT0.C
#include "TChain.h" #include "TTree.h" #include "TH1F.h" #include "TF1.h" #include "TH2F.h" #include "TCanvas.h" #include "TObjArray.h" #include "/home/alla/alice/AliRoot/AliRoot/STEER/STEERBase/TTreeStream.h" #define NPMTs 24 int MakeTrendT0( char *infile, int run) { char *outfile = "trending.root"; if(!infile) return -1; if(!outfile) return -1; TFile *f = TFile::Open(infile,"read"); if (!f) { printf("File %s not available\n", infile); return -1; } // LOAD HISTOGRAMS FROM QAresults.root TObjArray *fTzeroObject = (TObjArray*) f->Get("T0_Performance/QAT0chists"); TH1F* fTzeroORAplusORC =(TH1F*) ((TH1F*) fTzeroObject->FindObject("fTzeroORAplusORC"))->Clone("A"); TH1F* fResolution =(TH1F*) ((TH1F*) fTzeroObject->FindObject("fResolution"))->Clone("B"); TH1F* fTzeroORA =(TH1F*) ((TH1F*) fTzeroObject->FindObject("fTzeroORA"))->Clone("C"); TH1F* fTzeroORC =(TH1F*) ((TH1F*) fTzeroObject->FindObject("fTzeroORC"))->Clone("D"); TH2F *fTimeVSAmplitude[NPMTs];//counting PMTs from 0 TH1D *fAmplitude[NPMTs]; TH1D *fTime[NPMTs]; //-----> add new histogram here // sigma fit of resolution, mean T0A, T0C and T0C&A, mean amplitude for each PMT double resolutionSigma = -9999; //dummy init double tzeroOrAPlusOrC = -9999; //dummy init double tzeroOrA = -9999; //dummy init double tzeroOrC = -9999; //dummy init double meanAmplitude[NPMTs]; //dummy init double meanTime[NPMTs]; //dummy init double timeDelayOCDB[NPMTs]; //dummy init //................................................................................. for(int ipmt=1; ipmt<=NPMTs; ipmt++){ //loop over all PMTs fTimeVSAmplitude[ipmt-1] =(TH2F*) ((TH2F*) fTzeroObject->FindObject(Form("fTimeVSAmplitude%d",ipmt)))->Clone(Form("E%d",ipmt)); int nbinsX = fTimeVSAmplitude[ipmt-1]->GetNbinsX(); int nbinsY = fTimeVSAmplitude[ipmt-1]->GetNbinsY(); //Amplitude fAmplitude[ipmt-1] = (TH1D*) fTimeVSAmplitude[ipmt-1]->ProjectionX(Form("fAmplitude%d",ipmt), 1, nbinsY); meanAmplitude[ipmt-1] = -9999; //dummy init if(fAmplitude[ipmt-1]->GetEntries()>0){ meanAmplitude[ipmt-1] = fAmplitude[ipmt-1]->GetMean(); } //Time fTime[ipmt-1] = (TH1D*) fTimeVSAmplitude[ipmt-1]->ProjectionY(Form("fTime%d",ipmt), 1, nbinsX); meanTime[ipmt-1] = -9999; //dummy init if(fTime[ipmt-1]->GetEntries()>0){ if(fTime[ipmt-1]->GetEntries()>20){ meanTime[ipmt-1] = GetParameterGaus((TH1F*) fTime[ipmt-1], 1); // Mean Time }else if(fTime[ipmt-1]->GetEntries()>0){ meanTime[ipmt-1] = fTime[ipmt-1]->GetMean(); } } } if(fResolution->GetEntries()>20){ resolutionSigma = GetParameterGaus(fResolution, 2); //gaussian sigma }else if(fResolution->GetEntries()>0){ resolutionSigma = fResolution->GetRMS(); //gaussian sigma } if(fTzeroORAplusORC->GetEntries()>20){ tzeroOrAPlusOrC = GetParameterGaus(fTzeroORAplusORC, 1); //gaussian mean }else if(fTzeroORAplusORC->GetEntries()>0){ tzeroOrAPlusOrC = fTzeroORAplusORC->GetMean(); } if(fTzeroORA->GetEntries()>20){ tzeroOrA = GetParameterGaus(fTzeroORA, 1); //gaussian mean }else if(fTzeroORA->GetEntries()>0){ tzeroOrA = fTzeroORA->GetMean(); } if(fTzeroORC->GetEntries()>20){ tzeroOrC = GetParameterGaus(fTzeroORC, 1); //gaussian mean }else if(fTzeroORC->GetEntries()>0){ tzeroOrC = fTzeroORC->GetMean(); //gaussian mean } //-----> analyze the new histogram here and set mean/sigma f->Close(); //-------------------- READ OCDB TIME DELAYS --------------------------- // Arguments: AliCDBManager* man = AliCDBManager::Instance(); man->SetDefaultStorage("raw://"); man->SetRun(run); AliCDBEntry *entry = AliCDBManager::Instance()->Get("T0/Calib/TimeDelay"); AliT0CalibTimeEq *clb = (AliT0CalibTimeEq*)entry->GetObject(); for (Int_t i=0; i<NPMTs; i++){ timeDelayOCDB[i] = 0; if(clb) timeDelayOCDB[i] = clb->GetCFDvalue(i,0); } //--------------- write walues to the output ------------ TTreeSRedirector* pcstream = NULL; pcstream = new TTreeSRedirector(outfile); if (!pcstream) return; TFile *x = pcstream->GetFile(); x->cd(); TObjString runType; Int_t startTimeGRP=0; Int_t stopTimeGRP=0; Int_t time=0; Int_t duration=0; time = (startTimeGRP+stopTimeGRP)/2; duration = (stopTimeGRP-startTimeGRP); (*pcstream)<<"t0QA"<< "run="<<run;//<< //"time="<<time<< // "startTimeGRP="<<startTimeGRP<< // "stopTimeGRP="<<stopTimeGRP<< /// "duration="<<duration<< // "runType.="<<&runType; (*pcstream)<<"t0QA"<< "resolution="<< resolutionSigma<< "tzeroOrAPlusOrC="<< tzeroOrAPlusOrC<< "tzeroOrA="<< tzeroOrA<< "tzeroOrC="<< tzeroOrC<< "amplPMT1="<<meanAmplitude[0]<< "amplPMT2="<<meanAmplitude[1]<< "amplPMT3="<<meanAmplitude[2]<< "amplPMT4="<<meanAmplitude[3]<< "amplPMT5="<<meanAmplitude[4]<< "amplPMT6="<<meanAmplitude[5]<< "amplPMT7="<<meanAmplitude[6]<< "amplPMT8="<<meanAmplitude[7]<< "amplPMT9="<<meanAmplitude[8]<< "amplPMT10="<<meanAmplitude[9]<< "amplPMT11="<<meanAmplitude[10]<< "amplPMT12="<<meanAmplitude[11]<< "amplPMT13="<<meanAmplitude[12]<< "amplPMT14="<<meanAmplitude[13]<< "amplPMT15="<<meanAmplitude[14]<< "amplPMT16="<<meanAmplitude[15]<< "amplPMT17="<<meanAmplitude[16]<< "amplPMT18="<<meanAmplitude[17]<< "amplPMT19="<<meanAmplitude[18]<< "amplPMT20="<<meanAmplitude[19]<< "amplPMT21="<<meanAmplitude[20]<< "amplPMT22="<<meanAmplitude[21]<< "amplPMT23="<<meanAmplitude[22]<< "amplPMT24="<<meanAmplitude[23]<< "timePMT1="<<meanTime[0]<< "timePMT2="<<meanTime[1]<< "timePMT3="<<meanTime[2]<< "timePMT4="<<meanTime[3]<< "timePMT5="<<meanTime[4]<< "timePMT6="<<meanTime[5]<< "timePMT7="<<meanTime[6]<< "timePMT8="<<meanTime[7]<< "timePMT9="<<meanTime[8]<< "timePMT10="<<meanTime[9]<< "timePMT11="<<meanTime[10]<< "timePMT12="<<meanTime[11]<< "timePMT13="<<meanTime[12]<< "timePMT14="<<meanTime[13]<< "timePMT15="<<meanTime[14]<< "timePMT16="<<meanTime[15]<< "timePMT17="<<meanTime[16]<< "timePMT18="<<meanTime[17]<< "timePMT19="<<meanTime[18]<< "timePMT20="<<meanTime[19]<< "timePMT21="<<meanTime[20]<< "timePMT22="<<meanTime[21]<< "timePMT23="<<meanTime[22]<< "timePMT24="<<meanTime[23]; (*pcstream)<<"t0QA"<< "timeDelayPMT1="<<timeDelayOCDB[0]<< "timeDelayPMT2="<<timeDelayOCDB[1]<< "timeDelayPMT3="<<timeDelayOCDB[2]<< "timeDelayPMT4="<<timeDelayOCDB[3]<< "timeDelayPMT5="<<timeDelayOCDB[4]<< "timeDelayPMT6="<<timeDelayOCDB[5]<< "timeDelayPMT7="<<timeDelayOCDB[6]<< "timeDelayPMT8="<<timeDelayOCDB[7]<< "timeDelayPMT9="<<timeDelayOCDB[8]<< "timeDelayPMT10="<<timeDelayOCDB[9]<< "timeDelayPMT11="<<timeDelayOCDB[10]<< "timeDelayPMT12="<<timeDelayOCDB[11]<< "timeDelayPMT13="<<timeDelayOCDB[12]<< "timeDelayPMT14="<<timeDelayOCDB[13]<< "timeDelayPMT15="<<timeDelayOCDB[14]<< "timeDelayPMT16="<<timeDelayOCDB[15]<< "timeDelayPMT17="<<timeDelayOCDB[16]<< "timeDelayPMT18="<<timeDelayOCDB[17]<< "timeDelayPMT19="<<timeDelayOCDB[18]<< "timeDelayPMT20="<<timeDelayOCDB[19]<< "timeDelayPMT21="<<timeDelayOCDB[20]<< "timeDelayPMT22="<<timeDelayOCDB[21]<< "timeDelayPMT23="<<timeDelayOCDB[22]<< "timeDelayPMT24="<<timeDelayOCDB[23]; //-----> add the mean/sigma of the new histogram here (*pcstream)<<"t0QA"<<"\n"; pcstream->Close(); delete pcstream; return; } //_____________________________________________________________________________ double GetParameterGaus(TH1F *histo, int whichParameter){ int maxBin = histo->GetMaximumBin(); double max = (histo->GetBinContent(maxBin-1) + histo->GetBinContent(maxBin) + histo->GetBinContent(maxBin+1))/3; double mean = histo->GetBinCenter(maxBin); //mean double lowfwhm = histo->GetBinCenter(histo->FindFirstBinAbove(max/2)); double highfwhm = histo->GetBinCenter(histo->FindLastBinAbove(max/2)); double sigma = (highfwhm - lowfwhm)/2.35482; //estimate fwhm FWHM = 2.35482*sigma TF1 *gaussfit = new TF1("gaussfit","gaus", mean - 4*sigma, mean + 4*sigma); // fit in +- 4 sigma window gaussfit->SetParameters(max, mean, sigma); if(whichParameter==2) histo->Fit(gaussfit,"RQNI"); else histo->Fit(gaussfit,"RQN"); double parValue = gaussfit->GetParameter(whichParameter); delete gaussfit; return parValue; }
#include "TChain.h" #include "TTree.h" #include "TH1F.h" #include "TF1.h" #include "TH2F.h" #include "TCanvas.h" #include "TObjArray.h" #include "TTreeStream.h" #define NPMTs 24 int MakeTrendT0( char *infile, int run) { char *outfile = "trending.root"; if(!infile) return -1; if(!outfile) return -1; TFile *f = TFile::Open(infile,"read"); if (!f) { printf("File %s not available\n", infile); return -1; } // LOAD HISTOGRAMS FROM QAresults.root TObjArray *fTzeroObject = (TObjArray*) f->Get("T0_Performance/QAT0chists"); TH1F* fTzeroORAplusORC =(TH1F*) ((TH1F*) fTzeroObject->FindObject("fTzeroORAplusORC"))->Clone("A"); TH1F* fResolution =(TH1F*) ((TH1F*) fTzeroObject->FindObject("fResolution"))->Clone("B"); TH1F* fTzeroORA =(TH1F*) ((TH1F*) fTzeroObject->FindObject("fTzeroORA"))->Clone("C"); TH1F* fTzeroORC =(TH1F*) ((TH1F*) fTzeroObject->FindObject("fTzeroORC"))->Clone("D"); TH2F *fTimeVSAmplitude[NPMTs];//counting PMTs from 0 TH1D *fAmplitude[NPMTs]; TH1D *fTime[NPMTs]; //-----> add new histogram here // sigma fit of resolution, mean T0A, T0C and T0C&A, mean amplitude for each PMT double resolutionSigma = -9999; //dummy init double tzeroOrAPlusOrC = -9999; //dummy init double tzeroOrA = -9999; //dummy init double tzeroOrC = -9999; //dummy init double meanAmplitude[NPMTs]; //dummy init double meanTime[NPMTs]; //dummy init double timeDelayOCDB[NPMTs]; //dummy init //................................................................................. for(int ipmt=1; ipmt<=NPMTs; ipmt++){ //loop over all PMTs fTimeVSAmplitude[ipmt-1] =(TH2F*) ((TH2F*) fTzeroObject->FindObject(Form("fTimeVSAmplitude%d",ipmt)))->Clone(Form("E%d",ipmt)); int nbinsX = fTimeVSAmplitude[ipmt-1]->GetNbinsX(); int nbinsY = fTimeVSAmplitude[ipmt-1]->GetNbinsY(); //Amplitude fAmplitude[ipmt-1] = (TH1D*) fTimeVSAmplitude[ipmt-1]->ProjectionX(Form("fAmplitude%d",ipmt), 1, nbinsY); meanAmplitude[ipmt-1] = -9999; //dummy init if(fAmplitude[ipmt-1]->GetEntries()>0){ meanAmplitude[ipmt-1] = fAmplitude[ipmt-1]->GetMean(); } //Time fTime[ipmt-1] = (TH1D*) fTimeVSAmplitude[ipmt-1]->ProjectionY(Form("fTime%d",ipmt), 1, nbinsX); meanTime[ipmt-1] = -9999; //dummy init if(fTime[ipmt-1]->GetEntries()>0){ if(fTime[ipmt-1]->GetEntries()>20){ meanTime[ipmt-1] = GetParameterGaus((TH1F*) fTime[ipmt-1], 1); // Mean Time }else if(fTime[ipmt-1]->GetEntries()>0){ meanTime[ipmt-1] = fTime[ipmt-1]->GetMean(); } } } if(fResolution->GetEntries()>20){ resolutionSigma = GetParameterGaus(fResolution, 2); //gaussian sigma }else if(fResolution->GetEntries()>0){ resolutionSigma = fResolution->GetRMS(); //gaussian sigma } if(fTzeroORAplusORC->GetEntries()>20){ tzeroOrAPlusOrC = GetParameterGaus(fTzeroORAplusORC, 1); //gaussian mean }else if(fTzeroORAplusORC->GetEntries()>0){ tzeroOrAPlusOrC = fTzeroORAplusORC->GetMean(); } if(fTzeroORA->GetEntries()>20){ tzeroOrA = GetParameterGaus(fTzeroORA, 1); //gaussian mean }else if(fTzeroORA->GetEntries()>0){ tzeroOrA = fTzeroORA->GetMean(); } if(fTzeroORC->GetEntries()>20){ tzeroOrC = GetParameterGaus(fTzeroORC, 1); //gaussian mean }else if(fTzeroORC->GetEntries()>0){ tzeroOrC = fTzeroORC->GetMean(); //gaussian mean } //-----> analyze the new histogram here and set mean/sigma f->Close(); //-------------------- READ OCDB TIME DELAYS --------------------------- // Arguments: AliCDBManager* man = AliCDBManager::Instance(); man->SetDefaultStorage("raw://"); man->SetRun(run); AliCDBEntry *entry = AliCDBManager::Instance()->Get("T0/Calib/TimeDelay"); AliT0CalibTimeEq *clb = (AliT0CalibTimeEq*)entry->GetObject(); for (Int_t i=0; i<NPMTs; i++){ timeDelayOCDB[i] = 0; if(clb) timeDelayOCDB[i] = clb->GetCFDvalue(i,0); } //--------------- write walues to the output ------------ TTreeSRedirector* pcstream = NULL; pcstream = new TTreeSRedirector(outfile); if (!pcstream) return; TFile *x = pcstream->GetFile(); x->cd(); TObjString runType; Int_t startTimeGRP=0; Int_t stopTimeGRP=0; Int_t time=0; Int_t duration=0; time = (startTimeGRP+stopTimeGRP)/2; duration = (stopTimeGRP-startTimeGRP); (*pcstream)<<"t0QA"<< "run="<<run;//<< //"time="<<time<< // "startTimeGRP="<<startTimeGRP<< // "stopTimeGRP="<<stopTimeGRP<< /// "duration="<<duration<< // "runType.="<<&runType; (*pcstream)<<"t0QA"<< "resolution="<< resolutionSigma<< "tzeroOrAPlusOrC="<< tzeroOrAPlusOrC<< "tzeroOrA="<< tzeroOrA<< "tzeroOrC="<< tzeroOrC<< "amplPMT1="<<meanAmplitude[0]<< "amplPMT2="<<meanAmplitude[1]<< "amplPMT3="<<meanAmplitude[2]<< "amplPMT4="<<meanAmplitude[3]<< "amplPMT5="<<meanAmplitude[4]<< "amplPMT6="<<meanAmplitude[5]<< "amplPMT7="<<meanAmplitude[6]<< "amplPMT8="<<meanAmplitude[7]<< "amplPMT9="<<meanAmplitude[8]<< "amplPMT10="<<meanAmplitude[9]<< "amplPMT11="<<meanAmplitude[10]<< "amplPMT12="<<meanAmplitude[11]<< "amplPMT13="<<meanAmplitude[12]<< "amplPMT14="<<meanAmplitude[13]<< "amplPMT15="<<meanAmplitude[14]<< "amplPMT16="<<meanAmplitude[15]<< "amplPMT17="<<meanAmplitude[16]<< "amplPMT18="<<meanAmplitude[17]<< "amplPMT19="<<meanAmplitude[18]<< "amplPMT20="<<meanAmplitude[19]<< "amplPMT21="<<meanAmplitude[20]<< "amplPMT22="<<meanAmplitude[21]<< "amplPMT23="<<meanAmplitude[22]<< "amplPMT24="<<meanAmplitude[23]<< "timePMT1="<<meanTime[0]<< "timePMT2="<<meanTime[1]<< "timePMT3="<<meanTime[2]<< "timePMT4="<<meanTime[3]<< "timePMT5="<<meanTime[4]<< "timePMT6="<<meanTime[5]<< "timePMT7="<<meanTime[6]<< "timePMT8="<<meanTime[7]<< "timePMT9="<<meanTime[8]<< "timePMT10="<<meanTime[9]<< "timePMT11="<<meanTime[10]<< "timePMT12="<<meanTime[11]<< "timePMT13="<<meanTime[12]<< "timePMT14="<<meanTime[13]<< "timePMT15="<<meanTime[14]<< "timePMT16="<<meanTime[15]<< "timePMT17="<<meanTime[16]<< "timePMT18="<<meanTime[17]<< "timePMT19="<<meanTime[18]<< "timePMT20="<<meanTime[19]<< "timePMT21="<<meanTime[20]<< "timePMT22="<<meanTime[21]<< "timePMT23="<<meanTime[22]<< "timePMT24="<<meanTime[23]; (*pcstream)<<"t0QA"<< "timeDelayPMT1="<<timeDelayOCDB[0]<< "timeDelayPMT2="<<timeDelayOCDB[1]<< "timeDelayPMT3="<<timeDelayOCDB[2]<< "timeDelayPMT4="<<timeDelayOCDB[3]<< "timeDelayPMT5="<<timeDelayOCDB[4]<< "timeDelayPMT6="<<timeDelayOCDB[5]<< "timeDelayPMT7="<<timeDelayOCDB[6]<< "timeDelayPMT8="<<timeDelayOCDB[7]<< "timeDelayPMT9="<<timeDelayOCDB[8]<< "timeDelayPMT10="<<timeDelayOCDB[9]<< "timeDelayPMT11="<<timeDelayOCDB[10]<< "timeDelayPMT12="<<timeDelayOCDB[11]<< "timeDelayPMT13="<<timeDelayOCDB[12]<< "timeDelayPMT14="<<timeDelayOCDB[13]<< "timeDelayPMT15="<<timeDelayOCDB[14]<< "timeDelayPMT16="<<timeDelayOCDB[15]<< "timeDelayPMT17="<<timeDelayOCDB[16]<< "timeDelayPMT18="<<timeDelayOCDB[17]<< "timeDelayPMT19="<<timeDelayOCDB[18]<< "timeDelayPMT20="<<timeDelayOCDB[19]<< "timeDelayPMT21="<<timeDelayOCDB[20]<< "timeDelayPMT22="<<timeDelayOCDB[21]<< "timeDelayPMT23="<<timeDelayOCDB[22]<< "timeDelayPMT24="<<timeDelayOCDB[23]; //-----> add the mean/sigma of the new histogram here (*pcstream)<<"t0QA"<<"\n"; pcstream->Close(); delete pcstream; return; } //_____________________________________________________________________________ double GetParameterGaus(TH1F *histo, int whichParameter){ int maxBin = histo->GetMaximumBin(); double max = (histo->GetBinContent(maxBin-1) + histo->GetBinContent(maxBin) + histo->GetBinContent(maxBin+1))/3; double mean = histo->GetBinCenter(maxBin); //mean double lowfwhm = histo->GetBinCenter(histo->FindFirstBinAbove(max/2)); double highfwhm = histo->GetBinCenter(histo->FindLastBinAbove(max/2)); double sigma = (highfwhm - lowfwhm)/2.35482; //estimate fwhm FWHM = 2.35482*sigma TF1 *gaussfit = new TF1("gaussfit","gaus", mean - 4*sigma, mean + 4*sigma); // fit in +- 4 sigma window gaussfit->SetParameters(max, mean, sigma); if(whichParameter==2) histo->Fit(gaussfit,"RQNI"); else histo->Fit(gaussfit,"RQN"); double parValue = gaussfit->GetParameter(whichParameter); delete gaussfit; return parValue; }
remove wrong long path
remove wrong long path
C++
bsd-3-clause
miranov25/AliRoot,ecalvovi/AliRoot,ecalvovi/AliRoot,miranov25/AliRoot,ALICEHLT/AliRoot,mkrzewic/AliRoot,alisw/AliRoot,mkrzewic/AliRoot,mkrzewic/AliRoot,alisw/AliRoot,mkrzewic/AliRoot,shahor02/AliRoot,shahor02/AliRoot,coppedis/AliRoot,sebaleh/AliRoot,miranov25/AliRoot,ALICEHLT/AliRoot,sebaleh/AliRoot,sebaleh/AliRoot,jgrosseo/AliRoot,alisw/AliRoot,coppedis/AliRoot,miranov25/AliRoot,alisw/AliRoot,ecalvovi/AliRoot,coppedis/AliRoot,alisw/AliRoot,coppedis/AliRoot,alisw/AliRoot,ecalvovi/AliRoot,miranov25/AliRoot,coppedis/AliRoot,ALICEHLT/AliRoot,shahor02/AliRoot,miranov25/AliRoot,coppedis/AliRoot,sebaleh/AliRoot,shahor02/AliRoot,coppedis/AliRoot,sebaleh/AliRoot,miranov25/AliRoot,mkrzewic/AliRoot,ALICEHLT/AliRoot,miranov25/AliRoot,ecalvovi/AliRoot,ecalvovi/AliRoot,alisw/AliRoot,ALICEHLT/AliRoot,jgrosseo/AliRoot,jgrosseo/AliRoot,alisw/AliRoot,jgrosseo/AliRoot,shahor02/AliRoot,ecalvovi/AliRoot,sebaleh/AliRoot,shahor02/AliRoot,jgrosseo/AliRoot,shahor02/AliRoot,ALICEHLT/AliRoot,coppedis/AliRoot,mkrzewic/AliRoot,ALICEHLT/AliRoot,jgrosseo/AliRoot,mkrzewic/AliRoot,jgrosseo/AliRoot,sebaleh/AliRoot
82262a3f314f227b906e64d8a7c13957c9a4bb5a
Code/GraphMol/Fingerprints/Fingerprints.cpp
Code/GraphMol/Fingerprints/Fingerprints.cpp
// $Id$ // // Copyright (C) 2003-2008 Greg Landrum and Rational Discovery LLC // // @@ All Rights Reserved @@ // #include <GraphMol/RDKitBase.h> #include <DataStructs/ExplicitBitVect.h> #include <DataStructs/BitOps.h> #include "Fingerprints.h" #include <GraphMol/Subgraphs/Subgraphs.h> #include <GraphMol/Subgraphs/SubgraphUtils.h> #include <RDGeneral/Invariant.h> #include <boost/random.hpp> #include <limits.h> #include <boost/functional/hash.hpp> #include <algorithm> namespace RDKit{ // caller owns the result, it must be deleted ExplicitBitVect *DaylightFingerprintMol(const ROMol &mol,unsigned int minPath, unsigned int maxPath, unsigned int fpSize,unsigned int nBitsPerHash, bool useHs, double tgtDensity,unsigned int minSize){ PRECONDITION(minPath!=0,"minPath==0"); PRECONDITION(maxPath>=minPath,"maxPath<minPath"); PRECONDITION(fpSize!=0,"fpSize==0"); PRECONDITION(nBitsPerHash!=0,"nBitsPerHash==0"); typedef boost::minstd_rand rng_type; typedef boost::uniform_int<> distrib_type; typedef boost::variate_generator<rng_type &,distrib_type> source_type; rng_type generator(42u); // // if we generate arbitrarily sized ints then mod them down to the // appropriate size, we can guarantee that a fingerprint of // size x has the same bits set as one of size 2x that's been folded // in half. This is a nice guarantee to have. // distrib_type dist(0,INT_MAX); source_type randomSource(generator,dist); ExplicitBitVect *res = new ExplicitBitVect(fpSize); INT_PATH_LIST_MAP allPaths = findAllSubgraphsOfLengthsMtoN(mol,minPath,maxPath, useHs); for(INT_PATH_LIST_MAP_CI paths=allPaths.begin();paths!=allPaths.end();paths++){ for( PATH_LIST_CI pathIt=paths->second.begin(); pathIt!=paths->second.end(); pathIt++ ){ const PATH_TYPE &path=*pathIt; float balabanJ = static_cast<float>(MolOps::computeBalabanJ(mol,true,true, &path,false)); unsigned long seed = *(unsigned long *)(&balabanJ); generator.seed(seed); for(unsigned int i=0;i<nBitsPerHash;i++){ unsigned int bit = randomSource(); bit %= fpSize; res->SetBit(bit); } } } // EFF: this could be faster by folding by more than a factor // of 2 each time, but we're not going to be spending much // time here anyway while( static_cast<double>(res->GetNumOnBits())/res->GetNumBits() < tgtDensity && res->GetNumBits() >= 2*minSize ){ ExplicitBitVect *tmpV=FoldFingerprint(*res,2); delete res; res = tmpV; } return res; } // caller owns the result, it must be deleted ExplicitBitVect *RDKFingerprintMol2(const ROMol &mol,unsigned int minPath, unsigned int maxPath, unsigned int fpSize,unsigned int nBitsPerHash, bool useHs, double tgtDensity,unsigned int minSize){ PRECONDITION(minPath!=0,"minPath==0"); PRECONDITION(maxPath>=minPath,"maxPath<minPath"); PRECONDITION(fpSize!=0,"fpSize==0"); PRECONDITION(nBitsPerHash!=0,"nBitsPerHash==0"); typedef boost::minstd_rand rng_type; typedef boost::uniform_int<> distrib_type; typedef boost::variate_generator<rng_type &,distrib_type> source_type; rng_type generator(42u); // // if we generate arbitrarily sized ints then mod them down to the // appropriate size, we can guarantee that a fingerprint of // size x has the same bits set as one of size 2x that's been folded // in half. This is a nice guarantee to have. // distrib_type dist(0,INT_MAX); source_type randomSource(generator,dist); ExplicitBitVect *res = new ExplicitBitVect(fpSize); INT_PATH_LIST_MAP allPaths = findAllSubgraphsOfLengthsMtoN(mol,minPath,maxPath, useHs); for(INT_PATH_LIST_MAP_CI paths=allPaths.begin();paths!=allPaths.end();paths++){ for( PATH_LIST_CI pathIt=paths->second.begin(); pathIt!=paths->second.end(); pathIt++ ){ const PATH_TYPE &path=*pathIt; #ifdef VERBOSE_FINGERPRINTING std::cerr<<"Path: "; std::copy(path.begin(),path.end(),std::ostream_iterator<int>(std::cerr,", ")); std::cerr<<std::endl; #endif // initialize the bond hashes to the number of neighbors the bond has in the path: std::vector<unsigned int> bondNbrs(path.size()); std::fill(bondNbrs.begin(),bondNbrs.end(),0); std::set<unsigned int> atomsInPath; std::vector<unsigned int> bondHashes; bondHashes.reserve(path.size()+1); for(unsigned int i=0;i<path.size();++i){ const Bond *bi = mol.getBondWithIdx(path[i]); atomsInPath.insert(bi->getBeginAtomIdx()); atomsInPath.insert(bi->getEndAtomIdx()); for(unsigned int j=i+1;j<path.size();++j){ const Bond *bj = mol.getBondWithIdx(path[j]); if(bi->getBeginAtomIdx()==bj->getBeginAtomIdx() || bi->getBeginAtomIdx()==bj->getEndAtomIdx() || bi->getEndAtomIdx()==bj->getBeginAtomIdx() || bi->getEndAtomIdx()==bj->getEndAtomIdx() ){ ++bondNbrs[i]; ++bondNbrs[j]; } } #ifdef VERBOSE_FINGERPRINTING std::cerr<<" bond("<<i<<"):"<<bondNbrs[i]<<std::endl; #endif // we have the count of neighbors for bond bi, compute its hash: unsigned int a1Hash,a2Hash; a1Hash = (bi->getBeginAtom()->getAtomicNum()%128)<<1 | bi->getBeginAtom()->getIsAromatic(); a2Hash = (bi->getEndAtom()->getAtomicNum()%128)<<1 | bi->getEndAtom()->getIsAromatic(); if(a1Hash<a2Hash) std::swap(a1Hash,a2Hash); unsigned int bondHash; if(bi->getIsAromatic()){ // makes sure aromatic bonds always hash the same: bondHash = Bond::AROMATIC; } else { bondHash = bi->getBondType(); } unsigned int nBitsInHash=0; unsigned int ourHash=bondNbrs[i]%8; // 3 bits here nBitsInHash+=3; ourHash |= (bondHash%16)<<nBitsInHash; // 4 bits here nBitsInHash+=4; ourHash |= a1Hash<<nBitsInHash; // 8 bits nBitsInHash+=8; ourHash |= a2Hash<<nBitsInHash; // 8 bits bondHashes.insert(std::lower_bound(bondHashes.begin(),bondHashes.end(),ourHash),ourHash); } // finally, we will add the number of distinct atoms in the path at the end // of the vect. This allows us to distinguish C1CC1 from CC(C)C bondHashes.push_back(atomsInPath.size()); // hash the path to generate a seed: boost::hash<std::vector<unsigned int> > vectHasher; unsigned long seed = vectHasher(bondHashes); #ifdef VERBOSE_FINGERPRINTING std::cerr<<" hash: "<<seed<<std::endl; #endif // originally it seemed like a good idea to track hashes we've already // seen in order to avoid resetting them. In some benchmarking I did, that // seemed to actually result in a longer runtime (at least when using // an std::set to store the hashes) generator.seed(seed); for(unsigned int i=0;i<nBitsPerHash;i++){ unsigned int bit = randomSource(); bit %= fpSize; res->SetBit(bit); } } } // EFF: this could be faster by folding by more than a factor // of 2 each time, but we're not going to be spending much // time here anyway if(tgtDensity>0.0){ while( static_cast<double>(res->GetNumOnBits())/res->GetNumBits() < tgtDensity && res->GetNumBits() >= 2*minSize ){ ExplicitBitVect *tmpV=FoldFingerprint(*res,2); delete res; res = tmpV; } } return res; } }
// $Id$ // // Copyright (C) 2003-2008 Greg Landrum and Rational Discovery LLC // // @@ All Rights Reserved @@ // #include <GraphMol/RDKitBase.h> #include <DataStructs/ExplicitBitVect.h> #include <DataStructs/BitOps.h> #include "Fingerprints.h" #include <GraphMol/Subgraphs/Subgraphs.h> #include <GraphMol/Subgraphs/SubgraphUtils.h> #include <RDGeneral/Invariant.h> #include <boost/random.hpp> #include <limits.h> #include <boost/functional/hash.hpp> #include <algorithm> namespace RDKit{ // caller owns the result, it must be deleted ExplicitBitVect *DaylightFingerprintMol(const ROMol &mol, unsigned int minPath, unsigned int maxPath, unsigned int fpSize, unsigned int nBitsPerHash, bool useHs, double tgtDensity, unsigned int minSize){ PRECONDITION(minPath!=0,"minPath==0"); PRECONDITION(maxPath>=minPath,"maxPath<minPath"); PRECONDITION(fpSize!=0,"fpSize==0"); PRECONDITION(nBitsPerHash!=0,"nBitsPerHash==0"); typedef boost::mt19937 rng_type; typedef boost::uniform_int<> distrib_type; typedef boost::variate_generator<rng_type &,distrib_type> source_type; rng_type generator(42u); // // if we generate arbitrarily sized ints then mod them down to the // appropriate size, we can guarantee that a fingerprint of // size x has the same bits set as one of size 2x that's been folded // in half. This is a nice guarantee to have. // distrib_type dist(0,INT_MAX); source_type randomSource(generator,dist); ExplicitBitVect *res = new ExplicitBitVect(fpSize); INT_PATH_LIST_MAP allPaths = findAllSubgraphsOfLengthsMtoN(mol,minPath,maxPath, useHs); for(INT_PATH_LIST_MAP_CI paths=allPaths.begin();paths!=allPaths.end();paths++){ for( PATH_LIST_CI pathIt=paths->second.begin(); pathIt!=paths->second.end(); pathIt++ ){ const PATH_TYPE &path=*pathIt; float balabanJ = static_cast<float>(MolOps::computeBalabanJ(mol,true,true, &path,false)); boost::hash<float> floatHasher; unsigned long seed = floatHasher(balabanJ); generator.seed(static_cast<rng_type::result_type>(seed)); for(unsigned int i=0;i<nBitsPerHash;i++){ unsigned int bit = randomSource(); bit %= fpSize; res->SetBit(bit); } } } // EFF: this could be faster by folding by more than a factor // of 2 each time, but we're not going to be spending much // time here anyway while( static_cast<double>(res->GetNumOnBits())/res->GetNumBits() < tgtDensity && res->GetNumBits() >= 2*minSize ){ ExplicitBitVect *tmpV=FoldFingerprint(*res,2); delete res; res = tmpV; } return res; } // caller owns the result, it must be deleted ExplicitBitVect *RDKFingerprintMol2(const ROMol &mol,unsigned int minPath, unsigned int maxPath, unsigned int fpSize,unsigned int nBitsPerHash, bool useHs, double tgtDensity,unsigned int minSize){ PRECONDITION(minPath!=0,"minPath==0"); PRECONDITION(maxPath>=minPath,"maxPath<minPath"); PRECONDITION(fpSize!=0,"fpSize==0"); PRECONDITION(nBitsPerHash!=0,"nBitsPerHash==0"); typedef boost::mt19937 rng_type; typedef boost::uniform_int<> distrib_type; typedef boost::variate_generator<rng_type &,distrib_type> source_type; rng_type generator(42u); // // if we generate arbitrarily sized ints then mod them down to the // appropriate size, we can guarantee that a fingerprint of // size x has the same bits set as one of size 2x that's been folded // in half. This is a nice guarantee to have. // distrib_type dist(0,INT_MAX); source_type randomSource(generator,dist); ExplicitBitVect *res = new ExplicitBitVect(fpSize); INT_PATH_LIST_MAP allPaths = findAllSubgraphsOfLengthsMtoN(mol,minPath,maxPath, useHs); for(INT_PATH_LIST_MAP_CI paths=allPaths.begin();paths!=allPaths.end();paths++){ for( PATH_LIST_CI pathIt=paths->second.begin(); pathIt!=paths->second.end(); pathIt++ ){ const PATH_TYPE &path=*pathIt; #ifdef VERBOSE_FINGERPRINTING std::cerr<<"Path: "; std::copy(path.begin(),path.end(),std::ostream_iterator<int>(std::cerr,", ")); std::cerr<<std::endl; #endif // initialize the bond hashes to the number of neighbors the bond has in the path: std::vector<unsigned int> bondNbrs(path.size()); std::fill(bondNbrs.begin(),bondNbrs.end(),0); std::set<unsigned int> atomsInPath; std::vector<unsigned int> bondHashes; bondHashes.reserve(path.size()+1); for(unsigned int i=0;i<path.size();++i){ const Bond *bi = mol.getBondWithIdx(path[i]); atomsInPath.insert(bi->getBeginAtomIdx()); atomsInPath.insert(bi->getEndAtomIdx()); for(unsigned int j=i+1;j<path.size();++j){ const Bond *bj = mol.getBondWithIdx(path[j]); if(bi->getBeginAtomIdx()==bj->getBeginAtomIdx() || bi->getBeginAtomIdx()==bj->getEndAtomIdx() || bi->getEndAtomIdx()==bj->getBeginAtomIdx() || bi->getEndAtomIdx()==bj->getEndAtomIdx() ){ ++bondNbrs[i]; ++bondNbrs[j]; } } #ifdef VERBOSE_FINGERPRINTING std::cerr<<" bond("<<i<<"):"<<bondNbrs[i]<<std::endl; #endif // we have the count of neighbors for bond bi, compute its hash: unsigned int a1Hash,a2Hash; a1Hash = (bi->getBeginAtom()->getAtomicNum()%128)<<1 | bi->getBeginAtom()->getIsAromatic(); a2Hash = (bi->getEndAtom()->getAtomicNum()%128)<<1 | bi->getEndAtom()->getIsAromatic(); if(a1Hash<a2Hash) std::swap(a1Hash,a2Hash); unsigned int bondHash; if(bi->getIsAromatic()){ // makes sure aromatic bonds always hash the same: bondHash = Bond::AROMATIC; } else { bondHash = bi->getBondType(); } unsigned int nBitsInHash=0; unsigned int ourHash=bondNbrs[i]%8; // 3 bits here nBitsInHash+=3; ourHash |= (bondHash%16)<<nBitsInHash; // 4 bits here nBitsInHash+=4; ourHash |= a1Hash<<nBitsInHash; // 8 bits nBitsInHash+=8; ourHash |= a2Hash<<nBitsInHash; // 8 bits bondHashes.insert(std::lower_bound(bondHashes.begin(),bondHashes.end(),ourHash),ourHash); } // finally, we will add the number of distinct atoms in the path at the end // of the vect. This allows us to distinguish C1CC1 from CC(C)C bondHashes.push_back(atomsInPath.size()); // hash the path to generate a seed: boost::hash<std::vector<unsigned int> > vectHasher; unsigned long seed = vectHasher(bondHashes); #ifdef VERBOSE_FINGERPRINTING std::cerr<<" hash: "<<seed<<std::endl; #endif // originally it seemed like a good idea to track hashes we've already // seen in order to avoid resetting them. In some benchmarking I did, that // seemed to actually result in a longer runtime (at least when using // an std::set to store the hashes) generator.seed(static_cast<rng_type::result_type>(seed)); for(unsigned int i=0;i<nBitsPerHash;i++){ unsigned int bit = randomSource(); bit %= fpSize; res->SetBit(bit); } } } // EFF: this could be faster by folding by more than a factor // of 2 each time, but we're not going to be spending much // time here anyway if(tgtDensity>0.0){ while( static_cast<double>(res->GetNumOnBits())/res->GetNumBits() < tgtDensity && res->GetNumBits() >= 2*minSize ){ ExplicitBitVect *tmpV=FoldFingerprint(*res,2); delete res; res = tmpV; } } return res; } }
use a different RNG and different approach for generating seeds. NOTE: this breaks compatibility of fingerprints
use a different RNG and different approach for generating seeds. NOTE: this breaks compatibility of fingerprints
C++
bsd-3-clause
rdkit/rdkit,greglandrum/rdkit,jandom/rdkit,rdkit/rdkit,greglandrum/rdkit,soerendip42/rdkit,greglandrum/rdkit,strets123/rdkit,ptosco/rdkit,jandom/rdkit,adalke/rdkit,rdkit/rdkit,bp-kelley/rdkit,bp-kelley/rdkit,soerendip42/rdkit,rvianello/rdkit,ptosco/rdkit,strets123/rdkit,soerendip42/rdkit,AlexanderSavelyev/rdkit,ptosco/rdkit,rdkit/rdkit,AlexanderSavelyev/rdkit,strets123/rdkit,AlexanderSavelyev/rdkit,bp-kelley/rdkit,ptosco/rdkit,rvianello/rdkit,AlexanderSavelyev/rdkit,jandom/rdkit,adalke/rdkit,rvianello/rdkit,rvianello/rdkit,adalke/rdkit,bp-kelley/rdkit,jandom/rdkit,soerendip42/rdkit,bp-kelley/rdkit,ptosco/rdkit,adalke/rdkit,AlexanderSavelyev/rdkit,greglandrum/rdkit,strets123/rdkit,greglandrum/rdkit,soerendip42/rdkit,jandom/rdkit,adalke/rdkit,soerendip42/rdkit,rvianello/rdkit,greglandrum/rdkit,AlexanderSavelyev/rdkit,rvianello/rdkit,rvianello/rdkit,strets123/rdkit,greglandrum/rdkit,soerendip42/rdkit,soerendip42/rdkit,AlexanderSavelyev/rdkit,jandom/rdkit,AlexanderSavelyev/rdkit,rdkit/rdkit,ptosco/rdkit,bp-kelley/rdkit,adalke/rdkit,ptosco/rdkit,jandom/rdkit,bp-kelley/rdkit,rdkit/rdkit,strets123/rdkit,jandom/rdkit,AlexanderSavelyev/rdkit,strets123/rdkit,rdkit/rdkit,strets123/rdkit,ptosco/rdkit,adalke/rdkit,bp-kelley/rdkit,rdkit/rdkit,rvianello/rdkit,adalke/rdkit,greglandrum/rdkit
0a30a9e99fb83580af7b443b3b6c7d1f2dae5fe1
monte.cpp
monte.cpp
/* Copyright (c) 2015 Neil Babson and Gabe Stauth This source file is protected under the MIT License. Please see the file LICENSE in the distribution for license terms. */ /* This file contains the implementation of the Monte Carlo Search Tree which controls the computer AI. */ #include "board.h" //Recursive function that builds the Monte Carlo tree void gameBoard::MCcheckMoves(MCnode* n, int depth) { move_t temp, bestMoves[4]; int score, tempi, tempj; if (depth > 3) return; // Perform tree search to depth of 3 // Try passing bestMoves[3].wins = MCtryMove(0, 0, n -> color); for (int i = 1; i < 10; ++i) { for (int j = 1; j < 10; ++j) { score = MCtryMove(i, j, n -> color); n -> move.wins += PLAYOUTS - score; for (int k = 0; k < 4; ++k) { if (score > bestMoves[k].wins) // Bubble good moves through array { if (k == 0) { bestMoves[0].wins = score; bestMoves[0].x = i; bestMoves[0].y = j; } else { temp.wins = bestMoves[k].wins; temp.x = bestMoves[k].x; temp.y = bestMoves[k].y; bestMoves[k].wins = bestMoves[k-1].wins;; bestMoves[k].x = bestMoves[k-1].x; bestMoves[k].y = bestMoves[k-1].y;; bestMoves[k-1].wins = temp.wins; bestMoves[k-1].x = temp.x; bestMoves[k-1].y = temp.y; } } } /* cout << "BestMoves\n"; for (int i = 0; i < 4; ++i) cout <<bestMoves[i].wins<< " "; cout << endl; */ } } // Put four best moves on the tree for (int i = 0; i < 4; ++i) { n -> next[i] = new MCnode; n -> next[i] -> move.wins = bestMoves[i].wins; n -> next[i] -> move.x = bestMoves[i].x; n -> next[i] -> move.y = bestMoves[i].y; n -> next[i] -> board -> copy(n -> board); n -> next[i] -> board -> move(bestMoves[i].x, bestMoves[i].y, n -> color); n -> next[i] -> parent = n; n -> next[i] -> games = PLAYOUTS; n -> next[i] -> color = -(n -> color); n -> games += PLAYOUTS; // Keep total of black wins // if (n -> color == 1) // n -> move.wins += bestMoves[i].wins; // else n -> move.wins += PLAYOUTS - bestMoves[i].wins; if (DEBUG) { cout << "Parent's move: " << n->move.x << n->move.y << " Parents color: " << n->color << " Parent's wins: " << n->move.wins << endl ; cout << "Depth: " << depth << " Color: " << n->next[i]->color << " " <<n->next[i]->move.x<<n->next[i]->move.y<< " My wins: " << n->next[i]->move.wins<<endl; } } // Recursively search children ++depth; for (int i = 0; i < 4; ++i) MCcheckMoves(n -> next[i], depth); // Update parent if (n -> parent) { n -> parent -> games += n -> games; n -> parent -> move.wins += n-> games - n -> move.wins; } } //Find and play the most successful move from the second row of the tree int gameBoard::MCmove() { int bestMove, maxWins = -50000; MCnode *root = new MCnode(this); root -> color = 1; undoOn = false; MCcheckMoves(root, 1); for (int i = 0; i < 4; ++i) { if (root -> next[i] -> move.wins > maxWins) { maxWins = root -> next[i] -> move.wins; bestMove = i; } if (DEBUG) cout << "Children: " << root -> next[i] -> move.wins << " " << root->next[i]->move.x<<root->next[i]->move.y<<endl; } undoOn = true; if (root -> next[bestMove] -> move.x) // Best move isn't passing { this -> move(root->next[bestMove]->move.x, root->next[bestMove]->move.y, 1); // color = 1 cout << (char) (root->next[bestMove]->move.x + 96) << root->next[bestMove]->move.y << endl; deleteTree(root); return 1; } else // Pass { deleteTree(root); koFlag = false; } return 0; } //Delete the search tree after a move is selected void deleteTree(MCnode * root) { if (!root) return; for (int i = 0; i < 4; ++i) deleteTree(root -> next[i]); if (root -> board) { delete root -> board; root -> board = NULL; } delete root; root = NULL; } //Perform PLAYOUTS ranndom games from a given starting move and return //the total won by the color of the argument 'color' int gameBoard::MCtryMove(int firstx, int firsty, int color) { int wins = 0; gameBoard testBoard; testBoard.copy(this); if (firstx && !testBoard.move(firstx, firsty, color)) // If the first move is illegal return -1 return -1; for (int i = 0; i < PLAYOUTS; ++i) if (MCrandomGame(testBoard, -color, false)) ++wins; return wins; } //Plays a random game between two computer players. If a player attempts to //make an illegal move 6 times in a row she passes. If both players pass //in succession the game ends. bool gameBoard::MCrandomGame(gameBoard board, int color, bool display) { int startColor = color; int x, y; int misses, move = 0; bool passFlag = false; bool done = false; do { if (display) { cout << "Move " << move << endl; board.draw(); } misses = 0; do { x = (rand() % 9) + 1; y = (rand() % 9) + 1; if (board.move(x, y, color)) { passFlag = false; ++move; break; } else misses += 1; if (misses == 6) { if (passFlag) done = true; else passFlag = true; break; } ++move; } while (misses < 6); color *= -1; } while (!done); bool result = board.score(display); // If the first move in the random playout was black then the white player's move is // being evaluated and we return the opposite of the result from score, which // returns true if black won. if (startColor == 1) return !result; else return result; } //This function orchestrates a game between a human and the Monte Carlo tree algorithm void MCgame() { gameBoard board; char move[3]; int color = 1; bool passFlag = false; int choice; move[0] = '0'; do { board.draw(); if (color == 1) { if (!board.MCmove()) { if (passFlag) move[0] = 'q'; cout << "Computer pass\n"; passFlag = true; } } else { cout << "Enter a move (i.e. g3, p=pass, u=undo, q=quit) : "; cin.get(move, 10, '\n'); if (cin.fail()) cin.clear(); cin.ignore(10, '\n'); if (move[0] == 'u') board.undoAgainstAI(color); else if (move[0] == 'p') { if (passFlag) move[0] = 'q'; passFlag = true; } else if (move[0] != 'q') { if (!board.move((int)move[0] - 96,(int)move[1] - 48, color)) { cout << "Invalid move\n"; color *= -1; } else passFlag = false; } } color *= -1; } while (move[0] != 'q'); cout << "Game over\n"; board.removeDead(); board.score(true); }
/* Copyright (c) 2015 Neil Babson and Gabe Stauth This source file is protected under the MIT License. Please see the file LICENSE in the distribution for license terms. */ /* This file contains the implementation of the Monte Carlo Search Tree which controls the computer AI. */ #include "board.h" //Recursive function that builds the Monte Carlo tree void gameBoard::MCcheckMoves(MCnode* n, int depth) { move_t temp, bestMoves[4]; int score, tempi, tempj; if (depth > 3) return; // Perform tree search to depth of 3 // Try passing bestMoves[3].wins = MCtryMove(0, 0, n -> color); for (int i = 1; i < 10; ++i) { for (int j = 1; j < 10; ++j) { score = MCtryMove(i, j, n -> color); n -> move.wins += PLAYOUTS - score; for (int k = 0; k < 4; ++k) { if (score > bestMoves[k].wins) // Bubble good moves through array //This doesn't work { // if score is better than all the other scores it replaces all of them if (k == 0) { bestMoves[0].wins = score; bestMoves[0].x = i; bestMoves[0].y = j; //break; } else { temp.wins = bestMoves[k].wins; temp.x = bestMoves[k].x; temp.y = bestMoves[k].y; bestMoves[k].wins = bestMoves[k-1].wins;; bestMoves[k].x = bestMoves[k-1].x; bestMoves[k].y = bestMoves[k-1].y;; bestMoves[k-1].wins = temp.wins; bestMoves[k-1].x = temp.x; bestMoves[k-1].y = temp.y; //break; } } } /* cout << "BestMoves\n"; for (int i = 0; i < 4; ++i) cout <<bestMoves[i].wins<< " "; cout << endl; */ } } // Put four best moves on the tree for (int i = 0; i < 4; ++i) { n -> next[i] = new MCnode; n -> next[i] -> move.wins = bestMoves[i].wins; n -> next[i] -> move.x = bestMoves[i].x; n -> next[i] -> move.y = bestMoves[i].y; n -> next[i] -> board -> copy(n -> board); n -> next[i] -> board -> move(bestMoves[i].x, bestMoves[i].y, n -> color); n -> next[i] -> parent = n; n -> next[i] -> games = PLAYOUTS; n -> next[i] -> color = -(n -> color); n -> games += PLAYOUTS; // Keep total of black wins // if (n -> color == 1) // n -> move.wins += bestMoves[i].wins; // else n -> move.wins += PLAYOUTS - bestMoves[i].wins; if (DEBUG) { cout << "Parent's move: " << n->move.x << n->move.y << " Parents color: " << n->color << " Parent's wins: " << n->move.wins << endl ; cout << "Depth: " << depth << " Color: " << n->next[i]->color << " " <<n->next[i]->move.x<<n->next[i]->move.y<< " My wins: " << n->next[i]->move.wins<<endl; } } // Recursively search children ++depth; for (int i = 0; i < 4; ++i) MCcheckMoves(n -> next[i], depth); // Update parent if (n -> parent) { n -> parent -> games += n -> games; n -> parent -> move.wins += n-> games - n -> move.wins; } } //Find and play the most successful move from the second row of the tree int gameBoard::MCmove() { int bestMove, maxWins = -50000; MCnode *root = new MCnode(this); root -> color = 1; undoOn = false; MCcheckMoves(root, 1); for (int i = 0; i < 4; ++i) { if (root -> next[i] -> move.wins > maxWins) { maxWins = root -> next[i] -> move.wins; bestMove = i; } if (DEBUG) cout << "Children: " << root -> next[i] -> move.wins << " " << root->next[i]->move.x<<root->next[i]->move.y<<endl; } undoOn = true; if (root -> next[bestMove] -> move.x) // Best move isn't passing { this -> move(root->next[bestMove]->move.x, root->next[bestMove]->move.y, 1); // color = 1 cout << (char) (root->next[bestMove]->move.x + 96) << root->next[bestMove]->move.y << endl; deleteTree(root); return 1; } else // Pass { deleteTree(root); koFlag = false; } return 0; } //Delete the search tree after a move is selected void deleteTree(MCnode * root) { if (!root) return; for (int i = 0; i < 4; ++i) deleteTree(root -> next[i]); if (root -> board) { delete root -> board; root -> board = NULL; } delete root; root = NULL; } //Perform PLAYOUTS ranndom games from a given starting move and return //the total won by the color of the argument 'color' int gameBoard::MCtryMove(int firstx, int firsty, int color) { int wins = 0; gameBoard testBoard; testBoard.copy(this); if (firstx && !testBoard.move(firstx, firsty, color)) // If the first move is illegal return -1 return -1; for (int i = 0; i < PLAYOUTS; ++i) if (MCrandomGame(testBoard, -color, false)) ++wins; return wins; } //Plays a random game between two computer players. If a player attempts to //make an illegal move 6 times in a row she passes. If both players pass //in succession the game ends. bool gameBoard::MCrandomGame(gameBoard board, int color, bool display) { int startColor = color; int x, y; int misses, move = 0; bool passFlag = false; bool done = false; do { if (display) { cout << "Move " << move << endl; board.draw(); } misses = 0; do { x = (rand() % 9) + 1; y = (rand() % 9) + 1; if (board.move(x, y, color)) { passFlag = false; ++move; break; } else misses += 1; if (misses == 6) { if (passFlag) done = true; else passFlag = true; break; } ++move; } while (misses < 6); color *= -1; } while (!done); bool result = board.score(display); // If the first move in the random playout was black then the white player's move is // being evaluated and we return the opposite of the result from score, which // returns true if black won. if (startColor == 1) return !result; else return result; } //This function orchestrates a game between a human and the Monte Carlo tree algorithm void MCgame() { gameBoard board; char move[3]; int color = 1; bool passFlag = false; int choice; move[0] = '0'; do { board.draw(); if (color == 1) { if (!board.MCmove()) { if (passFlag) move[0] = 'q'; cout << "Computer pass\n"; passFlag = true; } } else { cout << "Enter a move (i.e. g3, p=pass, u=undo, q=quit) : "; cin.get(move, 10, '\n'); if (cin.fail()) cin.clear(); cin.ignore(10, '\n'); if (move[0] == 'u') board.undoAgainstAI(color); else if (move[0] == 'p') { if (passFlag) move[0] = 'q'; passFlag = true; } else if (move[0] != 'q') { if (!board.move((int)move[0] - 96,(int)move[1] - 48, color)) { cout << "Invalid move\n"; color *= -1; } else passFlag = false; } } color *= -1; } while (move[0] != 'q'); cout << "Game over\n"; board.removeDead(); board.score(true); }
Update monte.cpp
Update monte.cpp Bubbling bestmove be broken badly. Breaks be best bandage?
C++
mit
nbabson/MontyGo
3dcf13572ccb705ffa54f2fba09fb4f52447cdeb
src/tools/editor/src/halley_editor.cpp
src/tools/editor/src/halley_editor.cpp
#include "halley_editor.h" #include "editor_root_stage.h" #include "halley/tools/project/project.h" #include "preferences.h" #include "halley/core/game/environment.h" #include "halley/tools/file/filesystem.h" #include "halley/tools/project/project_loader.h" using namespace Halley; void initOpenGLPlugin(IPluginRegistry &registry); void initSDLSystemPlugin(IPluginRegistry &registry); void initSDLAudioPlugin(IPluginRegistry &registry); void initSDLInputPlugin(IPluginRegistry &registry); void initAsioPlugin(IPluginRegistry &registry); void initDX11Plugin(IPluginRegistry &registry); HalleyEditor::HalleyEditor() { } HalleyEditor::~HalleyEditor() { } int HalleyEditor::initPlugins(IPluginRegistry &registry) { initSDLSystemPlugin(registry); initAsioPlugin(registry); initSDLAudioPlugin(registry); initSDLInputPlugin(registry); #ifdef _WIN32 initDX11Plugin(registry); #else initOpenGLPlugin(registry); #endif return HalleyAPIFlags::Video | HalleyAPIFlags::Audio | HalleyAPIFlags::Input | HalleyAPIFlags::Network; } void HalleyEditor::initResourceLocator(const Path& gamePath, const Path& assetsPath, const Path& unpackedAssetsPath, ResourceLocator& locator) { locator.addFileSystem(unpackedAssetsPath); } String HalleyEditor::getName() const { return "Halley Editor"; } String HalleyEditor::getDataPath() const { return "halley/editor"; } bool HalleyEditor::isDevMode() const { return true; } bool HalleyEditor::shouldCreateSeparateConsole() const { #ifdef _DEBUG return isDevMode(); #else return false; #endif } Preferences& HalleyEditor::getPreferences() { return *preferences; } void HalleyEditor::init(const Environment& environment, const Vector<String>& args) { rootPath = environment.getProgramPath().parentPath(); parseArguments(args); } void HalleyEditor::parseArguments(const std::vector<String>& args) { platform = "pc"; gotProjectPath = false; for (auto& arg : args) { if (arg.startsWith("--")) { if (arg.startsWith("--platform=")) { platform = arg.mid(String("--platform=").length()); } else { std::cout << "Unknown argument \"" << arg << "\".\n"; } } else { if (!gotProjectPath) { projectPath = arg.cppStr(); gotProjectPath = true; } else { std::cout << "Unknown argument \"" << arg << "\".\n"; } } } } std::unique_ptr<Stage> HalleyEditor::startGame(const HalleyAPI* api) { preferences = std::make_unique<Preferences>(*api->system); projectLoader = std::make_unique<ProjectLoader>(api->core->getStatics(), rootPath); projectLoader->setPlatform(platform); std::unique_ptr<Project> project; if (gotProjectPath) { project = loadProject(Path(projectPath)); } api->video->setWindow(preferences->getWindowDefinition(), true); return std::make_unique<EditorRootStage>(*this, std::move(project)); } std::unique_ptr<Project> HalleyEditor::loadProject(Path path) { auto project = projectLoader->loadProject(path); if (!project) { throw Exception("Unable to load project at " + path.string()); } preferences->addRecent(path.string()); preferences->saveToFile(); return std::move(project); } std::unique_ptr<Project> HalleyEditor::createProject(Path path) { std::unique_ptr<Project> project; // TODO if (!project) { throw Exception("Unable to create project at " + path.string()); } preferences->addRecent(path.string()); preferences->saveToFile(); return std::move(project); } HalleyGame(HalleyEditor);
#include "halley_editor.h" #include "editor_root_stage.h" #include "halley/tools/project/project.h" #include "preferences.h" #include "halley/core/game/environment.h" #include "halley/tools/file/filesystem.h" #include "halley/tools/project/project_loader.h" using namespace Halley; void initOpenGLPlugin(IPluginRegistry &registry); void initSDLSystemPlugin(IPluginRegistry &registry); void initSDLAudioPlugin(IPluginRegistry &registry); void initSDLInputPlugin(IPluginRegistry &registry); void initAsioPlugin(IPluginRegistry &registry); void initDX11Plugin(IPluginRegistry &registry); HalleyEditor::HalleyEditor() { } HalleyEditor::~HalleyEditor() { } int HalleyEditor::initPlugins(IPluginRegistry &registry) { initSDLSystemPlugin(registry); initAsioPlugin(registry); initSDLAudioPlugin(registry); initSDLInputPlugin(registry); #ifdef _WIN32 initDX11Plugin(registry); #else initOpenGLPlugin(registry); #endif return HalleyAPIFlags::Video | HalleyAPIFlags::Audio | HalleyAPIFlags::Input | HalleyAPIFlags::Network; } void HalleyEditor::initResourceLocator(const Path& gamePath, const Path& assetsPath, const Path& unpackedAssetsPath, ResourceLocator& locator) { locator.addFileSystem(unpackedAssetsPath); } String HalleyEditor::getName() const { return "Halley Editor"; } String HalleyEditor::getDataPath() const { return "halley/editor"; } bool HalleyEditor::isDevMode() const { return true; } bool HalleyEditor::shouldCreateSeparateConsole() const { #ifdef _DEBUG return isDevMode(); #else return false; #endif } Preferences& HalleyEditor::getPreferences() { return *preferences; } void HalleyEditor::init(const Environment& environment, const Vector<String>& args) { rootPath = environment.getProgramPath().parentPath(); parseArguments(args); } void HalleyEditor::parseArguments(const std::vector<String>& args) { platform = "pc"; gotProjectPath = false; for (auto& arg : args) { if (arg.startsWith("--")) { if (arg.startsWith("--platform=")) { platform = arg.mid(String("--platform=").length()); } else { std::cout << "Unknown argument \"" << arg << "\".\n"; } } else { if (!gotProjectPath) { projectPath = arg.cppStr(); gotProjectPath = true; } else { std::cout << "Unknown argument \"" << arg << "\".\n"; } } } } std::unique_ptr<Stage> HalleyEditor::startGame(const HalleyAPI* api) { preferences = std::make_unique<Preferences>(*api->system); projectLoader = std::make_unique<ProjectLoader>(api->core->getStatics(), rootPath); projectLoader->setPlatform(platform); std::unique_ptr<Project> project; if (gotProjectPath) { project = loadProject(Path(projectPath)); } api->video->setWindow(preferences->getWindowDefinition()); api->video->setVsync(true); return std::make_unique<EditorRootStage>(*this, std::move(project)); } std::unique_ptr<Project> HalleyEditor::loadProject(Path path) { auto project = projectLoader->loadProject(path); if (!project) { throw Exception("Unable to load project at " + path.string()); } preferences->addRecent(path.string()); preferences->saveToFile(); return std::move(project); } std::unique_ptr<Project> HalleyEditor::createProject(Path path) { std::unique_ptr<Project> project; // TODO if (!project) { throw Exception("Unable to create project at " + path.string()); } preferences->addRecent(path.string()); preferences->saveToFile(); return std::move(project); } HalleyGame(HalleyEditor);
Fix editor.
Fix editor.
C++
apache-2.0
amzeratul/halley,amzeratul/halley,amzeratul/halley
5ba11bc90223b55eecd5da4cfbe86c8fc40637a5
src/mlpack/methods/sparse_coding/sparse_coding_main.cpp
src/mlpack/methods/sparse_coding/sparse_coding_main.cpp
/** * @file sparse_coding_main.cpp * @author Nishant Mehta * * Executable for Sparse Coding. */ #include <mlpack/core.hpp> #include "sparse_coding.hpp" PROGRAM_INFO("Sparse Coding", "An implementation of Sparse Coding with " "Dictionary Learning, which achieves sparsity via an l1-norm regularizer on" " the codes (LASSO) or an (l1+l2)-norm regularizer on the codes (the " "Elastic Net). Given a dense data matrix X with n points and d dimensions," " sparse coding seeks to find a dense dictionary matrix D with k atoms in " "d dimensions, and a sparse coding matrix Z with n points in k dimensions." "\n\n" "The original data matrix X can then be reconstructed as D * Z. Therefore," " this program finds a representation of each point in X as a sparse linear" " combination of atoms in the dictionary D." "\n\n" "The sparse coding is found with an algorithm which alternates between a " "dictionary step, which updates the dictionary D, and a sparse coding step," " which updates the sparse coding matrix." "\n\n" "Once a dictionary D is found, the sparse coding model may be used to " "encode other matrices, and saved for future usage." "\n\n" "To run this program, either an input matrix or an already-saved sparse " "coding model must be specified. An input matrix may be specified with the" " --training_file (-t) option, along with the number of atoms in the " "dictionary (--atoms, or -k). It is also possible to specify an initial " "dictionary for the optimization, with the --initial_dictionary (-i) " "option. An input model may be specified with the --input_model_file (-m) " "option. There are also other training options available." "\n\n" "As an example, to build a sparse coding model on the dataset in " "data.csv using 200 atoms and an l1-regularization parameter of 0.1, saving" " the model into model.xml, use " "\n\n" "$ sparse_coding -t data.csv -k 200 -l 0.1 -M model.xml" "\n\n" "Then, this model could be used to encode a new matrix, otherdata.csv, and " "save the output codes to codes.csv:" "\n\n" "$ sparse_coding -m model.xml -T otherdata.csv -c codes.csv"); // Train the model. PARAM_STRING("training_file", "Filename of the training data (X).", "t", ""); PARAM_INT("atoms", "Number of atoms in the dictionary.", "k", 0); PARAM_DOUBLE("lambda1", "Sparse coding l1-norm regularization parameter.", "l", 0); PARAM_DOUBLE("lambda2", "Sparse coding l2-norm regularization parameter.", "L", 0); PARAM_INT("max_iterations", "Maximum number of iterations for sparse coding (0 " "indicates no limit).", "n", 0); PARAM_STRING("initial_dictionary", "Filename for optional initial dictionary.", "i", ""); PARAM_FLAG("normalize", "If set, the input data matrix will be normalized " "before coding.", "N"); PARAM_INT("seed", "Random seed. If 0, 'std::time(NULL)' is used.", "s", 0); PARAM_DOUBLE("objective_tolerance", "Tolerance for convergence of the objective" " function.", "o", 0.01); PARAM_DOUBLE("newton_tolerance", "Tolerance for convergence of Newton method.", "w", 1e-6); // Load/save a model. PARAM_STRING("input_model_file", "File containing input sparse coding model.", "m", ""); PARAM_STRING("output_model_file", "File to save trained sparse coding model " "to.", "M", ""); PARAM_STRING("dictionary_file", "Filename to save the output dictionary to.", "d", ""); PARAM_STRING("codes_file", "Filename to save the output sparse codes to.", "c", ""); PARAM_STRING("test_file", "File containing data matrix to be encoded by trained" " model.", "T", ""); using namespace arma; using namespace std; using namespace mlpack; using namespace mlpack::math; using namespace mlpack::sparse_coding; int main(int argc, char* argv[]) { CLI::ParseCommandLine(argc, argv); if (CLI::GetParam<int>("seed") != 0) RandomSeed((size_t) CLI::GetParam<int>("seed")); else RandomSeed((size_t) time(NULL)); // Check for parameter validity. if (CLI::HasParam("input_model_file") && CLI::HasParam("initial_dictionary")) Log::Fatal << "Cannot specify both --input_model_file (-m) and " << "--initial_dictionary (-i)!" << endl; if (CLI::HasParam("training_file") && !CLI::HasParam("atoms")) Log::Fatal << "If --training_file is specified, the number of atoms in the " << "dictionary must be specified with --atoms (-k)!" << endl; if (!CLI::HasParam("training_file") && !CLI::HasParam("input_model_file")) Log::Fatal << "One of --training_file (-t) or --input_model_file (-m) must " << "be specified!" << endl; if (!CLI::HasParam("codes_file") && !CLI::HasParam("dictionary_file") && !CLI::HasParam("output_model_file")) Log::Warn << "Neither --codes_file (-c), --dictionary_file (-d), nor " << "--output_model_file (-M) are specified; no output will be saved." << endl; if (!CLI::HasParam("training_file")) { if (CLI::HasParam("atoms")) Log::Warn << "--atoms (-k) ignored because --training_file (-t) is not " << "specified." << endl; if (CLI::HasParam("lambda1")) Log::Warn << "--lambda1 (-l) ignored because --training_file (-t) is not " << "specified." << endl; if (CLI::HasParam("lambda2")) Log::Warn << "--lambda2 (-L) ignored because --training_file (-t) is not " << "specified." << endl; if (CLI::HasParam("initial_dictionary")) Log::Warn << "--initial_dictionary (-i) ignored because --training_file " << "(-t) is not specified." << endl; if (CLI::HasParam("max_iterations")) Log::Warn << "--max_iterations (-n) ignored because --training_file (-t) " << "is not specified." << endl; if (CLI::HasParam("normalize")) Log::Warn << "--normalize (-N) ignored because --training_file (-t) is " << "not specified." << endl; if (CLI::HasParam("objective_tolerance")) Log::Warn << "--objective_tolerance (-o) ignored because --training_file " << "(-t) is not specified." << endl; if (CLI::HasParam("newton_tolerance")) Log::Warn << "--newton_tolerance (-w) ignored because --training_file " << "(-t) is not specified." << endl; } // Do we have an existing model? SparseCoding sc(0, 0.0); if (CLI::HasParam("input_model_file")) { data::Load(CLI::GetParam<string>("input_model_file"), "sparse_coding_model", sc, true); } if (CLI::HasParam("training_file")) { mat matX; data::Load(CLI::GetParam<string>("training_file"), matX, true); // Normalize each point if the user asked for it. if (CLI::HasParam("normalize")) { Log::Info << "Normalizing data before coding..." << endl; for (size_t i = 0; i < matX.n_cols; ++i) matX.col(i) /= norm(matX.col(i), 2); } sc.Lambda1() = CLI::GetParam<double>("lambda1"); sc.Lambda2() = CLI::GetParam<double>("lambda2"); sc.MaxIterations() = (size_t) CLI::GetParam<int>("max_iterations"); sc.Atoms() = (size_t) CLI::GetParam<int>("atoms"); sc.ObjTolerance() = CLI::GetParam<double>("objective_tolerance"); sc.NewtonTolerance() = CLI::GetParam<double>("newton_tolerance"); // Inform the user if we are overwriting their model. if (CLI::HasParam("input_model_file")) { Log::Info << "Using dictionary from existing model in '" << CLI::GetParam<string>("input_model_file") << "' as initial " << "dictionary for training." << endl; sc.Train<NothingInitializer>(matX); } else if (CLI::HasParam("initial_dictionary")) { // Load initial dictionary directly into sparse coding object. data::Load(CLI::GetParam<string>("initial_dictionary"), sc.Dictionary(), true); // Validate size of initial dictionary. if (sc.Dictionary().n_cols != sc.Atoms()) { Log::Fatal << "The initial dictionary has " << sc.Dictionary().n_cols << " atoms, but the number of atoms was specified to be " << sc.Atoms() << "!" << endl; } if (sc.Dictionary().n_rows != matX.n_rows) { Log::Fatal << "The initial dictionary has " << sc.Dictionary().n_rows << " dimensions, but the data has " << matX.n_rows << " dimensions!" << endl; } // Run sparse coding. sc.Train<NothingInitializer>(matX); } else { // Run sparse coding with the default initialization. sc.Train(matX); } } // Now, de we have any matrix to encode? if (CLI::HasParam("test_file")) { mat matY; data::Load(CLI::GetParam<string>("test_file"), matY, true); if (matY.n_rows != sc.Dictionary().n_rows) Log::Fatal << "Model was trained with a dimensionality of " << sc.Dictionary().n_rows << ", but data in test file '" << CLI::GetParam<string>("test_file") << " has a dimensionality of " << matY.n_rows << "!" << endl; // Normalize each point if the user asked for it. if (CLI::HasParam("normalize")) { Log::Info << "Normalizing test data before coding..." << endl; for (size_t i = 0; i < matY.n_cols; ++i) matY.col(i) /= norm(matY.col(i), 2); } mat codes; sc.Encode(matY, codes); if (CLI::HasParam("codes_file")) data::Save(CLI::GetParam<string>("codes_file"), codes); } // Did the user want to save the dictionary? if (CLI::HasParam("dictionary_file")) data::Save(CLI::GetParam<string>("dictionary_file"), sc.Dictionary()); // Did the user want to save the model? if (CLI::HasParam("output_model_file")) data::Save(CLI::GetParam<string>("output_model_file"), "sparse_coding_model", sc, false); // Non-fatal on failure. }
/** * @file sparse_coding_main.cpp * @author Nishant Mehta * * Executable for Sparse Coding. */ #include <mlpack/core.hpp> #include "sparse_coding.hpp" PROGRAM_INFO("Sparse Coding", "An implementation of Sparse Coding with " "Dictionary Learning, which achieves sparsity via an l1-norm regularizer on" " the codes (LASSO) or an (l1+l2)-norm regularizer on the codes (the " "Elastic Net). Given a dense data matrix X with n points and d dimensions," " sparse coding seeks to find a dense dictionary matrix D with k atoms in " "d dimensions, and a sparse coding matrix Z with n points in k dimensions." "\n\n" "The original data matrix X can then be reconstructed as D * Z. Therefore," " this program finds a representation of each point in X as a sparse linear" " combination of atoms in the dictionary D." "\n\n" "The sparse coding is found with an algorithm which alternates between a " "dictionary step, which updates the dictionary D, and a sparse coding step," " which updates the sparse coding matrix." "\n\n" "Once a dictionary D is found, the sparse coding model may be used to " "encode other matrices, and saved for future usage." "\n\n" "To run this program, either an input matrix or an already-saved sparse " "coding model must be specified. An input matrix may be specified with the" " --training_file (-t) option, along with the number of atoms in the " "dictionary (--atoms, or -k). It is also possible to specify an initial " "dictionary for the optimization, with the --initial_dictionary (-i) " "option. An input model may be specified with the --input_model_file (-m) " "option. There are also other training options available." "\n\n" "As an example, to build a sparse coding model on the dataset in " "data.csv using 200 atoms and an l1-regularization parameter of 0.1, saving" " the model into model.xml, use " "\n\n" "$ sparse_coding -t data.csv -k 200 -l 0.1 -M model.xml" "\n\n" "Then, this model could be used to encode a new matrix, otherdata.csv, and " "save the output codes to codes.csv:" "\n\n" "$ sparse_coding -m model.xml -T otherdata.csv -c codes.csv"); // Train the model. PARAM_STRING("training_file", "Filename of the training data (X).", "t", ""); PARAM_INT("atoms", "Number of atoms in the dictionary.", "k", 0); PARAM_DOUBLE("lambda1", "Sparse coding l1-norm regularization parameter.", "l", 0); PARAM_DOUBLE("lambda2", "Sparse coding l2-norm regularization parameter.", "L", 0); PARAM_INT("max_iterations", "Maximum number of iterations for sparse coding (0 " "indicates no limit).", "n", 0); PARAM_STRING("initial_dictionary", "Filename for optional initial dictionary.", "i", ""); PARAM_FLAG("normalize", "If set, the input data matrix will be normalized " "before coding.", "N"); PARAM_INT("seed", "Random seed. If 0, 'std::time(NULL)' is used.", "s", 0); PARAM_DOUBLE("objective_tolerance", "Tolerance for convergence of the objective" " function.", "o", 0.01); PARAM_DOUBLE("newton_tolerance", "Tolerance for convergence of Newton method.", "w", 1e-6); // Load/save a model. PARAM_STRING("input_model_file", "File containing input sparse coding model.", "m", ""); PARAM_STRING("output_model_file", "File to save trained sparse coding model " "to.", "M", ""); PARAM_STRING("dictionary_file", "Filename to save the output dictionary to.", "d", ""); PARAM_STRING("codes_file", "Filename to save the output sparse codes to.", "c", ""); PARAM_STRING("test_file", "File containing data matrix to be encoded by trained" " model.", "T", ""); using namespace arma; using namespace std; using namespace mlpack; using namespace mlpack::math; using namespace mlpack::sparse_coding; int main(int argc, char* argv[]) { CLI::ParseCommandLine(argc, argv); if (CLI::GetParam<int>("seed") != 0) RandomSeed((size_t) CLI::GetParam<int>("seed")); else RandomSeed((size_t) time(NULL)); // Check for parameter validity. if (CLI::HasParam("input_model_file") && CLI::HasParam("initial_dictionary")) Log::Fatal << "Cannot specify both --input_model_file (-m) and " << "--initial_dictionary (-i)!" << endl; if (CLI::HasParam("training_file") && !CLI::HasParam("atoms")) Log::Fatal << "If --training_file is specified, the number of atoms in the " << "dictionary must be specified with --atoms (-k)!" << endl; if (!CLI::HasParam("training_file") && !CLI::HasParam("input_model_file")) Log::Fatal << "One of --training_file (-t) or --input_model_file (-m) must " << "be specified!" << endl; if (!CLI::HasParam("codes_file") && !CLI::HasParam("dictionary_file") && !CLI::HasParam("output_model_file")) Log::Warn << "Neither --codes_file (-c), --dictionary_file (-d), nor " << "--output_model_file (-M) are specified; no output will be saved." << endl; if (CLI::HasParam("codes_file") && !CLI::HasParam("test_file")) Log::Fatal << "--codes_file (-c) is specified, but no test matrix (" << "specified with --test_file or -T) is given to encode!" << endl; if (!CLI::HasParam("training_file")) { if (CLI::HasParam("atoms")) Log::Warn << "--atoms (-k) ignored because --training_file (-t) is not " << "specified." << endl; if (CLI::HasParam("lambda1")) Log::Warn << "--lambda1 (-l) ignored because --training_file (-t) is not " << "specified." << endl; if (CLI::HasParam("lambda2")) Log::Warn << "--lambda2 (-L) ignored because --training_file (-t) is not " << "specified." << endl; if (CLI::HasParam("initial_dictionary")) Log::Warn << "--initial_dictionary (-i) ignored because --training_file " << "(-t) is not specified." << endl; if (CLI::HasParam("max_iterations")) Log::Warn << "--max_iterations (-n) ignored because --training_file (-t) " << "is not specified." << endl; if (CLI::HasParam("normalize")) Log::Warn << "--normalize (-N) ignored because --training_file (-t) is " << "not specified." << endl; if (CLI::HasParam("objective_tolerance")) Log::Warn << "--objective_tolerance (-o) ignored because --training_file " << "(-t) is not specified." << endl; if (CLI::HasParam("newton_tolerance")) Log::Warn << "--newton_tolerance (-w) ignored because --training_file " << "(-t) is not specified." << endl; } // Do we have an existing model? SparseCoding sc(0, 0.0); if (CLI::HasParam("input_model_file")) { data::Load(CLI::GetParam<string>("input_model_file"), "sparse_coding_model", sc, true); } if (CLI::HasParam("training_file")) { mat matX; data::Load(CLI::GetParam<string>("training_file"), matX, true); // Normalize each point if the user asked for it. if (CLI::HasParam("normalize")) { Log::Info << "Normalizing data before coding..." << endl; for (size_t i = 0; i < matX.n_cols; ++i) matX.col(i) /= norm(matX.col(i), 2); } sc.Lambda1() = CLI::GetParam<double>("lambda1"); sc.Lambda2() = CLI::GetParam<double>("lambda2"); sc.MaxIterations() = (size_t) CLI::GetParam<int>("max_iterations"); sc.Atoms() = (size_t) CLI::GetParam<int>("atoms"); sc.ObjTolerance() = CLI::GetParam<double>("objective_tolerance"); sc.NewtonTolerance() = CLI::GetParam<double>("newton_tolerance"); // Inform the user if we are overwriting their model. if (CLI::HasParam("input_model_file")) { Log::Info << "Using dictionary from existing model in '" << CLI::GetParam<string>("input_model_file") << "' as initial " << "dictionary for training." << endl; sc.Train<NothingInitializer>(matX); } else if (CLI::HasParam("initial_dictionary")) { // Load initial dictionary directly into sparse coding object. data::Load(CLI::GetParam<string>("initial_dictionary"), sc.Dictionary(), true); // Validate size of initial dictionary. if (sc.Dictionary().n_cols != sc.Atoms()) { Log::Fatal << "The initial dictionary has " << sc.Dictionary().n_cols << " atoms, but the number of atoms was specified to be " << sc.Atoms() << "!" << endl; } if (sc.Dictionary().n_rows != matX.n_rows) { Log::Fatal << "The initial dictionary has " << sc.Dictionary().n_rows << " dimensions, but the data has " << matX.n_rows << " dimensions!" << endl; } // Run sparse coding. sc.Train<NothingInitializer>(matX); } else { // Run sparse coding with the default initialization. sc.Train(matX); } } // Now, de we have any matrix to encode? if (CLI::HasParam("test_file")) { mat matY; data::Load(CLI::GetParam<string>("test_file"), matY, true); if (matY.n_rows != sc.Dictionary().n_rows) Log::Fatal << "Model was trained with a dimensionality of " << sc.Dictionary().n_rows << ", but data in test file '" << CLI::GetParam<string>("test_file") << " has a dimensionality of " << matY.n_rows << "!" << endl; // Normalize each point if the user asked for it. if (CLI::HasParam("normalize")) { Log::Info << "Normalizing test data before coding..." << endl; for (size_t i = 0; i < matY.n_cols; ++i) matY.col(i) /= norm(matY.col(i), 2); } mat codes; sc.Encode(matY, codes); if (CLI::HasParam("codes_file")) data::Save(CLI::GetParam<string>("codes_file"), codes); } // Did the user want to save the dictionary? if (CLI::HasParam("dictionary_file")) data::Save(CLI::GetParam<string>("dictionary_file"), sc.Dictionary()); // Did the user want to save the model? if (CLI::HasParam("output_model_file")) data::Save(CLI::GetParam<string>("output_model_file"), "sparse_coding_model", sc, false); // Non-fatal on failure. }
Add additional parameter validation.
Add additional parameter validation.
C++
bsd-3-clause
ajjl/mlpack,palashahuja/mlpack,ranjan1990/mlpack,theranger/mlpack,ajjl/mlpack,darcyliu/mlpack,palashahuja/mlpack,darcyliu/mlpack,palashahuja/mlpack,ranjan1990/mlpack,darcyliu/mlpack,theranger/mlpack,theranger/mlpack,ranjan1990/mlpack,ajjl/mlpack
4336e39b60fa5617e582db98d4b0e6ed5170f3f3
Modules/Pharmacokinetics/test/mitkStandardToftsModelTest.cpp
Modules/Pharmacokinetics/test/mitkStandardToftsModelTest.cpp
/*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ // Testing #include "mitkTestingMacros.h" #include "mitkTestFixture.h" //MITK includes #include "mitkVector.h" #include "mitkStandardToftsModel.h" class mitkStandardToftsModelTestSuite : public mitk::TestFixture { CPPUNIT_TEST_SUITE(mitkStandardToftsModelTestSuite); MITK_TEST(GetModelDisplayNameTest); MITK_TEST(GetModelTypeTest); MITK_TEST(GetParameterNamesTest); MITK_TEST(GetNumberOfParametersTest); MITK_TEST(GetParameterUnitsTest); MITK_TEST(GetDerivedParameterNamesTest); MITK_TEST(GetNumberOfDerivedParametersTest); MITK_TEST(GetDerivedParameterUnitsTest); MITK_TEST(ComputeModelfunctionTest); MITK_TEST(ComputeDerivedParametersTest); CPPUNIT_TEST_SUITE_END(); private: mitk::StandardToftsModel::Pointer m_testmodel; mitk::ModelBase::ModelResultType m_output; mitk::ModelBase::DerivedParameterMapType m_derivedParameters; public: void setUp() override { mitk::ModelBase::TimeGridType m_grid(22); mitk::ModelBase::ParametersType m_testparameters(4); m_testparameters[mitk::StandardToftsModel::POSITION_PARAMETER_Ktrans] = 100.0; m_testparameters(mitk::StandardToftsModel::POSITION_PARAMETER_ve) = 0.3; for (int i = 0; i < 22; ++i) { // time grid in seconds, 14s between frames m_grid[i] = (double)14 * i; } //injection time in minutes --> 60s double m_injectiontime = 0.5; m_testmodel = mitk::StandardToftsModel::New(); m_testmodel->SetTimeGrid(m_grid); //m_testmodel->SetAterialInputFunctionValues(); //m_testmodel->SetAterialInputFunctionTimeGrid(); //ComputeModelfunction is called within GetSignal(), therefore no explicit testing of ComputeModelFunction() m_output = m_testmodel->GetSignal(m_testparameters); m_derivedParameters = m_testmodel->GetDerivedParameters(m_testparameters); } void tearDown() override { //m_testmodel = nullptr; } void GetModelDisplayNameTest() { //m_testmodel->GetModelDisplayName(); //CPPUNIT_ASSERT_MESSAGE("Checking model display name.", m_testmodel->GetModelDisplayName() == "Standard Tofts Model"); } void GetModelTypeTest() { //CPPUNIT_ASSERT_MESSAGE("Checking model type.", m_testmodel->GetModelType() == "Perfusion.MR"); } void GetParameterNamesTest() { //mitk::TwoStepLinearModel::ParameterNamesType parameterNames; //parameterNames.push_back("KTrans"); //parameterNames.push_back("ve"); //CPPUNIT_ASSERT_MESSAGE("Checking parameter names.", m_testmodel->GetParameterNames() == parameterNames); } void GetNumberOfParametersTest() { //CPPUNIT_ASSERT_MESSAGE("Checking number of parameters in model.", m_testmodel->GetNumberOfParameters() == 2); } void GetParameterUnitsTest() { //mitk::StandardToftsModel::ParamterUnitMapType parameterUnits; //parameterUnits.insert(std::make_pair("KTrans", "ml/min/100ml")); //parameterUnits.insert(std::make_pair("ve", "ml/ml")); //CPPUNIT_ASSERT_MESSAGE("Checking parameter units.", m_testmodel->GetParameterUnits() == parameterUnits); } void GetDerivedParameterNamesTest() { //mitk::StandardToftsModel::ParameterNamesType derivedParameterNames; //derivedParameterNames.push_back("kep"); //CPPUNIT_ASSERT_MESSAGE("Checking derived parameter names.", m_testmodel->GetDerivedParameterNames() == derivedParameterNames); } void GetNumberOfDerivedParametersTest() { //CPPUNIT_ASSERT_MESSAGE("Checking number of parameters in model.", m_testmodel->GetNumberOfDerivedParameters() == 1); } void GetDerivedParameterUnitsTest() { //mitk::StandardToftsModel::ParamterUnitMapType derivedParameterUnits; //derivedParameterUnits.insert(std::make_pair("kep", "1/min")); //CPPUNIT_ASSERT_MESSAGE("Checking parameter units.", m_testmodel->GetDerivedParameterUnits() == derivedParameterUnits); } void ComputeModelfunctionTest() { //CPPUNIT_ASSERT_MESSAGE("Checking signal at time frame 0.", mitk::Equal(0, m_output[0], 1e-6, true) == true); //CPPUNIT_ASSERT_MESSAGE("Checking signal at time frame 4.", mitk::Equal(280.0, m_output[4], 1e-6, true) == true); //CPPUNIT_ASSERT_MESSAGE("Checking signal at time frame 9.", mitk::Equal(552.0, m_output[9], 1e-6, true) == true); //CPPUNIT_ASSERT_MESSAGE("Checking signal at time frame 14.", mitk::Equal(692.0, m_output[14], 1e-6, true) == true); //CPPUNIT_ASSERT_MESSAGE("Checking signal at time frame 19.", mitk::Equal(832.0, m_output[19], 1e-6, true) == true); } void ComputeDerivedParametersTest() { } }; MITK_TEST_SUITE_REGISTRATION(mitkStandardToftsModel)
/*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ // Testing #include "mitkTestingMacros.h" #include "mitkTestFixture.h" //MITK includes #include "mitkVector.h" #include "mitkStandardToftsModel.h" #include "mitkAIFBasedModelBase.h" class mitkStandardToftsModelTestSuite : public mitk::TestFixture { CPPUNIT_TEST_SUITE(mitkStandardToftsModelTestSuite); MITK_TEST(GetModelDisplayNameTest); MITK_TEST(GetModelTypeTest); MITK_TEST(GetParameterNamesTest); MITK_TEST(GetNumberOfParametersTest); MITK_TEST(GetParameterUnitsTest); MITK_TEST(GetDerivedParameterNamesTest); MITK_TEST(GetNumberOfDerivedParametersTest); MITK_TEST(GetDerivedParameterUnitsTest); MITK_TEST(ComputeModelfunctionTest); MITK_TEST(ComputeDerivedParametersTest); CPPUNIT_TEST_SUITE_END(); private: mitk::StandardToftsModel::Pointer m_testmodel; mitk::ModelBase::ModelResultType m_output; mitk::ModelBase::DerivedParameterMapType m_derivedParameters; public: void setUp() override { mitk::ModelBase::TimeGridType m_grid(60); mitk::ModelBase::ParametersType m_testparameters(2); mitk::AIFBasedModelBase::AterialInputFunctionType m_arterialInputFunction (60); m_testparameters[mitk::StandardToftsModel::POSITION_PARAMETER_Ktrans] = 34.78; m_testparameters(mitk::StandardToftsModel::POSITION_PARAMETER_ve) = 0.5; m_arterialInputFunction.fill(0.0); m_arterialInputFunction[0] = 0.00000; m_arterialInputFunction[1] = -0.15248; m_arterialInputFunction[2] = -0.237782; m_arterialInputFunction[3] = -0.243189; m_arterialInputFunction[4] = -0.144531; m_arterialInputFunction[5] = -0.200168; m_arterialInputFunction[6] = 0.0922118; m_arterialInputFunction[7] = 3.51957; m_arterialInputFunction[8] = 9.62333; m_arterialInputFunction[9] = 9.07447; m_arterialInputFunction[10] = 5.97842; m_arterialInputFunction[11] = 4.96097; m_arterialInputFunction[12] = 5.76308; m_arterialInputFunction[13] = 5.17594; m_arterialInputFunction[14] = 4.41313; m_arterialInputFunction[15] = 4.38105; m_arterialInputFunction[16] = 4.87772; m_arterialInputFunction[17] = 4.5807; m_arterialInputFunction[18] = 4.53279; m_arterialInputFunction[19] = 4.35079; m_arterialInputFunction[20] = 4.29456; m_arterialInputFunction[21] = 3.99838; m_arterialInputFunction[22] = 4.42678; m_arterialInputFunction[23] = 4.0375; m_arterialInputFunction[24] = 4.03682; m_arterialInputFunction[25] = 3.86102; m_arterialInputFunction[26] = 3.60841; m_arterialInputFunction[27] = 3.79723; m_arterialInputFunction[28] = 3.82096; m_arterialInputFunction[29] = 3.81099; m_arterialInputFunction[30] = 3.43013; m_arterialInputFunction[31] = 3.48450; m_arterialInputFunction[32] = 4.10285; m_arterialInputFunction[33] = 3.57935; m_arterialInputFunction[34] = 3.59937; m_arterialInputFunction[35] = 3.79997; m_arterialInputFunction[36] = 3.55403; m_arterialInputFunction[37] = 2.90888; m_arterialInputFunction[38] = 3.60713; m_arterialInputFunction[39] = 3.73377; m_arterialInputFunction[40] = 3.31633; m_arterialInputFunction[41] = 3.62506; m_arterialInputFunction[42] = 3.12624; m_arterialInputFunction[43] = 3.41160; m_arterialInputFunction[44] = 3.20870; m_arterialInputFunction[45] = 2.94028; m_arterialInputFunction[46] = 3.43235; m_arterialInputFunction[47] = 3.23044; m_arterialInputFunction[48] = 3.03722; m_arterialInputFunction[49] = 3.11801; m_arterialInputFunction[50] = 3.25045; m_arterialInputFunction[51] = 3.23418; m_arterialInputFunction[52] = 3.0279; m_arterialInputFunction[53] = 2.95201; m_arterialInputFunction[54] = 3.03391; m_arterialInputFunction[55] = 3.19314; m_arterialInputFunction[56] = 3.24602; m_arterialInputFunction[57] = 2.9689; m_arterialInputFunction[58] = 2.88674; m_arterialInputFunction[59] = 3.39835; m_grid.fill(0.0); m_grid[0] = 0.00; m_grid[1] = 4.270; m_grid[2] = 8.541; m_grid[3] = 12.812; m_grid[4] = 17.082; m_grid[5] = 21.353; m_grid[6] = 25.624; m_grid[7] = 29.894; m_grid[8] = 34.165; m_grid[9] = 38.436; m_grid[10] = 42.706; m_grid[11] = 46.977; m_grid[12] = 51.248; m_grid[13] = 55.518; m_grid[14] = 59.789; m_grid[15] = 64.06; m_grid[16] = 68.331; m_grid[17] = 72.601; m_grid[18] = 76.872; m_grid[19] = 81.143; m_grid[20] = 85.413; m_grid[21] = 89.684; m_grid[22] = 93.955; m_grid[23] = 98.225; m_grid[24] = 102.496; m_grid[25] = 106.767; m_grid[26] = 111.037; m_grid[27] = 115.308; m_grid[28] = 119.579; m_grid[29] = 123.850; m_grid[30] = 128.120; m_grid[31] = 132.391; m_grid[32] = 136.662; m_grid[33] = 140.932; m_grid[34] = 145.203; m_grid[35] = 149.474; m_grid[36] = 153.744; m_grid[37] = 158.015; m_grid[38] = 162.286; m_grid[39] = 166.556; m_grid[40] = 170.827; m_grid[41] = 175.098; m_grid[42] = 179.369; m_grid[43] = 183.639; m_grid[44] = 187.910; m_grid[45] = 192.181; m_grid[46] = 196.451; m_grid[47] = 200.722; m_grid[48] = 204.993; m_grid[49] = 209.263; m_grid[50] = 213.534; m_grid[51] = 217.805; m_grid[52] = 222.075; m_grid[53] = 226.346; m_grid[54] = 230.617; m_grid[55] = 234.888; m_grid[56] = 239.158; m_grid[57] = 243.429; m_grid[58] = 247.700; m_grid[59] = 251.970; //injection time in minutes --> 60s //double m_injectiontime = 0.5; m_testmodel = mitk::StandardToftsModel::New(); m_testmodel->SetTimeGrid(m_grid); m_testmodel->SetAterialInputFunctionValues(m_arterialInputFunction); m_testmodel->SetAterialInputFunctionTimeGrid(m_grid); //ComputeModelfunction is called within GetSignal(), therefore no explicit testing of ComputeModelFunction() m_output = m_testmodel->GetSignal(m_testparameters); m_derivedParameters = m_testmodel->GetDerivedParameters(m_testparameters); } void tearDown() override { m_testmodel = nullptr; m_output.clear(); m_derivedParameters.clear(); } void GetModelDisplayNameTest() { m_testmodel->GetModelDisplayName(); CPPUNIT_ASSERT_MESSAGE("Checking model display name.", m_testmodel->GetModelDisplayName() == "Standard Tofts Model"); } void GetModelTypeTest() { CPPUNIT_ASSERT_MESSAGE("Checking model type.", m_testmodel->GetModelType() == "Perfusion.MR"); } void GetParameterNamesTest() { mitk::StandardToftsModel::ParameterNamesType parameterNames; parameterNames.push_back("KTrans"); parameterNames.push_back("ve"); CPPUNIT_ASSERT_MESSAGE("Checking parameter names.", m_testmodel->GetParameterNames() == parameterNames); } void GetNumberOfParametersTest() { CPPUNIT_ASSERT_MESSAGE("Checking number of parameters in model.", m_testmodel->GetNumberOfParameters() == 2); } void GetParameterUnitsTest() { mitk::StandardToftsModel::ParamterUnitMapType parameterUnits; parameterUnits.insert(std::make_pair("KTrans", "ml/min/100ml")); parameterUnits.insert(std::make_pair("ve", "ml/ml")); CPPUNIT_ASSERT_MESSAGE("Checking parameter units.", m_testmodel->GetParameterUnits() == parameterUnits); } void GetDerivedParameterNamesTest() { mitk::StandardToftsModel::ParameterNamesType derivedParameterNames; derivedParameterNames.push_back("kep"); CPPUNIT_ASSERT_MESSAGE("Checking derived parameter names.", m_testmodel->GetDerivedParameterNames() == derivedParameterNames); } void GetNumberOfDerivedParametersTest() { CPPUNIT_ASSERT_MESSAGE("Checking number of parameters in model.", m_testmodel->GetNumberOfDerivedParameters() == 1); } void GetDerivedParameterUnitsTest() { mitk::StandardToftsModel::ParamterUnitMapType derivedParameterUnits; derivedParameterUnits.insert(std::make_pair("kep", "1/min")); CPPUNIT_ASSERT_MESSAGE("Checking parameter units.", m_testmodel->GetDerivedParameterUnits() == derivedParameterUnits); } void ComputeModelfunctionTest() { CPPUNIT_ASSERT_MESSAGE("Checking signal at time frame 0.", mitk::Equal(0, m_output[0], 1e-6, true) == true); CPPUNIT_ASSERT_MESSAGE("Checking signal at time frame 10.", mitk::Equal(0.562266, m_output[10], 1e-6, true) == true); CPPUNIT_ASSERT_MESSAGE("Checking signal at time frame 20.", mitk::Equal(1.273072, m_output[20], 1e-6, true) == true); CPPUNIT_ASSERT_MESSAGE("Checking signal at time frame 30.", mitk::Equal(1.537241, m_output[30], 1e-6, true) == true); CPPUNIT_ASSERT_MESSAGE("Checking signal at time frame 40.", mitk::Equal(1.632757, m_output[40], 1e-6, true) == true); CPPUNIT_ASSERT_MESSAGE("Checking signal at time frame 50.", mitk::Equal(1.625615, m_output[50], 1e-6, true) == true); } void ComputeDerivedParametersTest() { CPPUNIT_ASSERT_MESSAGE("Checking kep.", mitk::Equal(69.56, m_derivedParameters["kep"], 1e-6, true) == true); } }; MITK_TEST_SUITE_REGISTRATION(mitkStandardToftsModel)
Add test data for AIF, time grid and paramters from real data. Add unit test for computeModelFunction and ComputeDerivedParameters.
Add test data for AIF, time grid and paramters from real data. Add unit test for computeModelFunction and ComputeDerivedParameters.
C++
bsd-3-clause
MITK/MITK,MITK/MITK,MITK/MITK,MITK/MITK,MITK/MITK,MITK/MITK
1338cbe754fef1ef6c35f9b0d779fdbf6c685079
exotica/src/Visualization.cpp
exotica/src/Visualization.cpp
/* * Author: Wolfgang Merkt * * Copyright (c) 2016, Wolfgang Merkt * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of nor the names of its contributors may be used to * endorse or promote products derived from this software without specific * prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ #include <exotica/Visualization.h> namespace exotica { Visualization::Visualization(Scene_ptr scene) : scene_(scene) { HIGHLIGHT_NAMED("Visualization", "Initialising visualizer"); Initialize(); } Visualization::~Visualization() = default; void Visualization::Initialize() { if (Server::isRos()) { trajectory_pub_ = Server::advertise<moveit_msgs::DisplayTrajectory>(scene_->getName() + (scene_->getName().empty() ? "" : "/") + "Trajectory", 1, true); } } void Visualization::displayTrajectory(Eigen::MatrixXdRefConst trajectory) { if (!Server::isRos()) return; if (trajectory.cols() != scene_->getSolver().getNumControlledJoints()) throw_pretty("Number of DoFs in trajectory does not match number of controlled joints of robot."); moveit_msgs::DisplayTrajectory traj_msg; traj_msg.model_id = scene_->getRobotModel()->getName(); // TODO: // http://docs.ros.org/melodic/api/moveit_msgs/html/msg/DisplayTrajectory.html // TODO: Support for fixed and floating base! - multi_dof_joint_trajectory // TODO: Support for uncontrolled joints: trajectory_start traj_msg.trajectory.resize(1); traj_msg.trajectory[0].joint_trajectory.header.frame_id = scene_->getRootFrameName(); traj_msg.trajectory[0].joint_trajectory.header.stamp = ros::Time::now(); traj_msg.trajectory[0].joint_trajectory.joint_names = scene_->getSolver().getJointNames(); traj_msg.trajectory[0].joint_trajectory.points.resize(trajectory.rows()); for (int i = 0; i < trajectory.rows(); i++) { traj_msg.trajectory[0].joint_trajectory.points[i].positions.resize(trajectory.cols()); for (int n = 0; n < trajectory.cols(); n++) { traj_msg.trajectory[0].joint_trajectory.points[i].positions[n] = trajectory(i, n); } } trajectory_pub_.publish(traj_msg); } }
/* * Author: Wolfgang Merkt * * Copyright (c) 2016, Wolfgang Merkt * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of nor the names of its contributors may be used to * endorse or promote products derived from this software without specific * prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ #include <exotica/Visualization.h> namespace exotica { Visualization::Visualization(Scene_ptr scene) : scene_(scene) { HIGHLIGHT_NAMED("Visualization", "Initialising visualizer"); Initialize(); } Visualization::~Visualization() = default; void Visualization::Initialize() { if (Server::isRos()) { trajectory_pub_ = Server::advertise<moveit_msgs::DisplayTrajectory>(scene_->getName() + (scene_->getName().empty() ? "" : "/") + "Trajectory", 1, true); } } void Visualization::displayTrajectory(Eigen::MatrixXdRefConst trajectory) { if (!Server::isRos()) return; if (trajectory.cols() != scene_->getSolver().getNumControlledJoints()) throw_pretty("Number of DoFs in trajectory does not match number of controlled joints of robot."); moveit_msgs::DisplayTrajectory traj_msg; traj_msg.model_id = scene_->getSolver().getRobotModel()->getName(); // TODO: // http://docs.ros.org/melodic/api/moveit_msgs/html/msg/DisplayTrajectory.html // TODO: Support for fixed and floating base! - multi_dof_joint_trajectory // TODO: Support for uncontrolled joints: trajectory_start traj_msg.trajectory.resize(1); traj_msg.trajectory[0].joint_trajectory.header.frame_id = scene_->getRootFrameName(); traj_msg.trajectory[0].joint_trajectory.header.stamp = ros::Time::now(); traj_msg.trajectory[0].joint_trajectory.joint_names = scene_->getSolver().getJointNames(); traj_msg.trajectory[0].joint_trajectory.points.resize(trajectory.rows()); for (int i = 0; i < trajectory.rows(); i++) { traj_msg.trajectory[0].joint_trajectory.points[i].positions.resize(trajectory.cols()); for (int n = 0; n < trajectory.cols(); n++) { traj_msg.trajectory[0].joint_trajectory.points[i].positions[n] = trajectory(i, n); } } trajectory_pub_.publish(traj_msg); } }
Fix for KinematicTree/Scene updates
[exotica] Visualization: Fix for KinematicTree/Scene updates
C++
bsd-3-clause
openhumanoids/exotica,openhumanoids/exotica,openhumanoids/exotica,openhumanoids/exotica
740fc5abb5cbdf6d89d1c915468381ec83d4f40e
DeviceAdapters/GigECamera/GigECameraAcq.cpp
DeviceAdapters/GigECamera/GigECameraAcq.cpp
/////////////////////////////////////////////////////////////////////////////// // FILE: GigECameraAcq.cpp // PROJECT: Micro-Manager // SUBSYSTEM: DeviceAdapters //----------------------------------------------------------------------------- // DESCRIPTION: An adapter for Gigbit-Ethernet cameras using an // SDK from JAI, Inc. Users and developers will // need to download and install the JAI SDK and control tool. // // AUTHOR: David Marshburn, UNC-CH, [email protected], Jan. 2011 // #include "GigECamera.h" #include "boost/lexical_cast.hpp" // this is/should be called only from JAI-started threads for image acquisition void CGigECamera::SnapImageCallback( J_tIMAGE_INFO* imageInfo ) { //LogMessage( (std::string) "SnapImageCallback: " // + boost::lexical_cast<std::string>( (int) J_BitsPerPixel( imageInfo->iPixelType ) ) + " bits/pixel, " // + boost::lexical_cast<std::string>( imageInfo->iSizeX ) + "w x " // + boost::lexical_cast<std::string>( imageInfo->iSizeY ) + "h" ); if( !( doContinuousAcquisition || snapOneImageOnly ) ) return; // no acquisition requested size_t numBytes = J_BitsPerPixel( imageInfo->iPixelType ) * imageInfo->iSizeX * imageInfo->iSizeY / 8; if( this->doContinuousAcquisition ) { if( buffer == NULL ) return; memcpy( buffer, imageInfo->pImageBuffer, min( numBytes, bufferSizeBytes ) ); int nRet; // process image /* NOTE: this is now done automatically in MMCore MM::ImageProcessor* ip = GetCoreCallback()->GetImageProcessor(this); if( ip != NULL ) { nRet = ip->Process( buffer, GetImageWidth(), GetImageHeight(), GetImageBytesPerPixel() ); if (nRet != DEVICE_OK) { LogMessage( (std::string) "process failure " ); } } */ // create metadata Metadata md; char label[MM::MaxStrLength]; GetLabel(label); MetadataSingleTag mstStartTime( MM::g_Keyword_Metadata_StartTime, label, true ); mstStartTime.SetValue( boost::lexical_cast< std::string >( imageInfo->iTimeStamp ).c_str() ); md.SetTag( mstStartTime ); nRet = GetCoreCallback()->InsertMultiChannel( this, buffer, 1, GetImageWidth(), GetImageHeight(), GetImageBytesPerPixel(), &md ); if( !stopOnOverflow_ && nRet == DEVICE_BUFFER_OVERFLOW ) { // do not stop on overflow - just reset the buffer GetCoreCallback()->ClearImageBuffer( this ); nRet = GetCoreCallback()->InsertMultiChannel( this, buffer, 1, GetImageWidth(), GetImageHeight(), GetImageBytesPerPixel(), &md ); } } // end if doContinuousAcquisition else if( this->snapOneImageOnly ) { unsigned char* pixels = img_.GetPixelsRW(); memcpy( pixels, imageInfo->pImageBuffer, min( numBytes, img_.Width() * img_.Height() * img_.Depth() ) ); } // in the case of snapImage-style acquisition, stop if( this->snapOneImageOnly || this->stopContinuousAcquisition ) { J_STATUS_TYPE retval = J_Camera_ExecuteCommand( hCamera, "AcquisitionStop" ); if( retval != J_ST_SUCCESS ) { LogMessage( (std::string) "SnapImageCallback: failed to stop acquisition" ); } snapOneImageOnly = false; snapImageDone = true; doContinuousAcquisition = false; stopContinuousAcquisition = false; continuousAcquisitionDone = true; } } J_STATUS_TYPE CGigECamera::setupImaging( ) { J_STATUS_TYPE retval; int64_t w, h; nodes->get( h, HEIGHT ); nodes->get( w, WIDTH ); retval = J_Image_OpenStream( hCamera, 0, reinterpret_cast<J_IMG_CALLBACK_OBJECT>(this), reinterpret_cast<J_IMG_CALLBACK_FUNCTION>(&CGigECamera::SnapImageCallback), &hThread, (uint32_t) ( w * h * LARGEST_PIXEL_IN_BYTES ) ); if( retval != J_ST_SUCCESS ) { LogMessage( (std::string) "setupImaging failed to open the image stream" ); return DEVICE_ERR; } return DEVICE_OK; } int CGigECamera::StartSequenceAcquisition( long numImages, double interval_ms, bool stopOnOverflow ) { LogMessage( (std::string) "Started camera streaming with an interval of " + boost::lexical_cast<std::string>( interval_ms ) + " ms, for " + boost::lexical_cast<std::string>( numImages ) + " images." ); if( doContinuousAcquisition ) return DEVICE_OK; if( IsCapturing() ) return DEVICE_CAMERA_BUSY_ACQUIRING; int ret = GetCoreCallback()->PrepareForAcq(this); if (ret != DEVICE_OK) return ret; // make sure the circular buffer is properly sized GetCoreCallback()->InitializeImageBuffer(GetNumberOfComponents(), 1, GetImageWidth(), GetImageHeight(), GetImageBytesPerPixel()); stopContinuousAcquisition = false; continuousAcquisitionDone = false; doContinuousAcquisition = true; stopOnOverflow_ = stopOnOverflow; setupImaging(); J_STATUS_TYPE retval = J_Camera_ExecuteCommand( hCamera, "AcquisitionStart" ); if( retval != J_ST_SUCCESS ) { LogMessage( (std::string) "SnapImage failed to start acquisition" ); J_Image_CloseStream( hThread ); return DEVICE_ERR; } return DEVICE_OK; } int CGigECamera::StopSequenceAcquisition() { if( !doContinuousAcquisition ) return DEVICE_OK; LogMessage( "StopSequenceAcquisition", true ); J_STATUS_TYPE retval; stopContinuousAcquisition = true; MM::MMTime startTime = GetCurrentMMTime(); double exp = GetExposure(); while( !continuousAcquisitionDone && !( GetCurrentMMTime() - startTime < MM::MMTime( 50 * exp * 1000 ) ) ) // x1000 scales ms to us. { CDeviceUtils::SleepMs( 1 ); } if( !continuousAcquisitionDone ) // didn't stop in time { LogMessage( (std::string) "StopSequenceAcquisition stopped the acquisition early because the JAI factory didn't stop soon enough" ); retval = J_Camera_ExecuteCommand( hCamera, "AcquisitionStop" ); if( retval != J_ST_SUCCESS ) { LogMessage( (std::string) "StopSequenceAcquisition failed to stop acquisition" ); } } retval = J_Image_CloseStream( hThread ); if( retval != J_ST_SUCCESS ) { LogMessage( (std::string) "StopSequenceAcquisition failed to close the image stream" ); return DEVICE_ERR; } snapOneImageOnly = false; doContinuousAcquisition = false; continuousAcquisitionDone = false; stopContinuousAcquisition = false; return DEVICE_OK; } /** * Performs exposure and grabs a single image. * This function should block during the actual exposure and return immediately afterwards * (i.e., before readout). This behavior is needed for proper synchronization with the shutter. * Required by the MM::Camera API. */ int CGigECamera::SnapImage() { if( snapOneImageOnly ) return DEVICE_OK; this->snapOneImageOnly = true; this->snapImageDone = false; setupImaging(); J_STATUS_TYPE retval = J_Camera_ExecuteCommand( hCamera, "AcquisitionStart" ); if( retval != J_ST_SUCCESS ) { LogMessage( (std::string) "SnapImage failed to start acquisition" ); J_Image_CloseStream( hThread ); return DEVICE_ERR; } else // retval == J_ST_SUCCESS { MM::MMTime startTime = GetCurrentMMTime(); double exp = GetExposure(); // wait until the image is acquired (or 20x the expected exposure time has passed) while( !snapImageDone && ( GetCurrentMMTime() - startTime < MM::MMTime( 20 * exp * 1000 ) ) ) // x1000 to scale ms -> us { CDeviceUtils::SleepMs( 1 ); } if( !snapImageDone ) // something happened and we didn't get an image { LogMessage( (std::string) "SnapImage stopped the acquisition because no image had been returned after a long while" ); retval = J_Camera_ExecuteCommand( hCamera, "AcquisitionStop" ); if( retval != J_ST_SUCCESS ) { LogMessage( (std::string) "SnapImage failed to stop acquisition" ); } snapOneImageOnly = false; } } retval = J_Image_CloseStream( hThread ); if( retval != J_ST_SUCCESS ) { LogMessage( (std::string) "SnapImage failed to close the image stream" ); return DEVICE_ERR; } readoutStartTime_ = GetCurrentMMTime(); return DEVICE_OK; } bool CGigECamera::IsCapturing() { return doContinuousAcquisition; }
/////////////////////////////////////////////////////////////////////////////// // FILE: GigECameraAcq.cpp // PROJECT: Micro-Manager // SUBSYSTEM: DeviceAdapters //----------------------------------------------------------------------------- // DESCRIPTION: An adapter for Gigbit-Ethernet cameras using an // SDK from JAI, Inc. Users and developers will // need to download and install the JAI SDK and control tool. // // AUTHOR: David Marshburn, UNC-CH, [email protected], Jan. 2011 // #include "GigECamera.h" #include "boost/lexical_cast.hpp" // this is/should be called only from JAI-started threads for image acquisition void CGigECamera::SnapImageCallback( J_tIMAGE_INFO* imageInfo ) { LogMessage( (std::string) "SnapImageCallback: " + boost::lexical_cast<std::string>( (int) J_BitsPerPixel( imageInfo->iPixelType ) ) + " bits/pixel, " + boost::lexical_cast<std::string>( imageInfo->iSizeX ) + "w x " + boost::lexical_cast<std::string>( imageInfo->iSizeY ) + "h", true ); if( !( doContinuousAcquisition || snapOneImageOnly ) ) return; // no acquisition requested size_t numBytes = J_BitsPerPixel( imageInfo->iPixelType ) * imageInfo->iSizeX * imageInfo->iSizeY / 8; if( this->doContinuousAcquisition ) { if( buffer == NULL ) return; memcpy( buffer, imageInfo->pImageBuffer, min( numBytes, bufferSizeBytes ) ); int nRet; // create metadata Metadata md; char label[MM::MaxStrLength]; GetLabel(label); MetadataSingleTag mstStartTime( MM::g_Keyword_Metadata_StartTime, label, true ); mstStartTime.SetValue( boost::lexical_cast< std::string >( imageInfo->iTimeStamp ).c_str() ); md.SetTag( mstStartTime ); nRet = GetCoreCallback()->InsertMultiChannel( this, buffer, 1, GetImageWidth(), GetImageHeight(), GetImageBytesPerPixel(), &md ); if( !stopOnOverflow_ && nRet == DEVICE_BUFFER_OVERFLOW ) { // do not stop on overflow - just reset the buffer GetCoreCallback()->ClearImageBuffer( this ); nRet = GetCoreCallback()->InsertMultiChannel( this, buffer, 1, GetImageWidth(), GetImageHeight(), GetImageBytesPerPixel(), &md ); } } // end if doContinuousAcquisition else if( this->snapOneImageOnly ) { unsigned char* pixels = img_.GetPixelsRW(); memcpy( pixels, imageInfo->pImageBuffer, min( numBytes, img_.Width() * img_.Height() * img_.Depth() ) ); } // in the case of snapImage-style acquisition, stop if( this->snapOneImageOnly || this->stopContinuousAcquisition ) { J_STATUS_TYPE retval = J_Camera_ExecuteCommand( hCamera, "AcquisitionStop" ); if( retval != J_ST_SUCCESS ) { LogMessage( (std::string) "SnapImageCallback: failed to stop acquisition" ); } snapOneImageOnly = false; snapImageDone = true; doContinuousAcquisition = false; stopContinuousAcquisition = false; continuousAcquisitionDone = true; } } J_STATUS_TYPE CGigECamera::setupImaging( ) { J_STATUS_TYPE retval; int64_t w, h; nodes->get( h, HEIGHT ); nodes->get( w, WIDTH ); retval = J_Image_OpenStream( hCamera, 0, reinterpret_cast<J_IMG_CALLBACK_OBJECT>(this), reinterpret_cast<J_IMG_CALLBACK_FUNCTION>(&CGigECamera::SnapImageCallback), &hThread, (uint32_t) ( w * h * LARGEST_PIXEL_IN_BYTES ) ); if( retval != J_ST_SUCCESS ) { LogMessage( (std::string) "setupImaging failed to open the image stream" ); return DEVICE_ERR; } return DEVICE_OK; } int CGigECamera::StartSequenceAcquisition( long numImages, double interval_ms, bool stopOnOverflow ) { LogMessage( (std::string) "Started camera streaming with an interval of " + boost::lexical_cast<std::string>( interval_ms ) + " ms, for " + boost::lexical_cast<std::string>( numImages ) + " images." ); if( doContinuousAcquisition ) return DEVICE_OK; if( IsCapturing() ) return DEVICE_CAMERA_BUSY_ACQUIRING; int ret = GetCoreCallback()->PrepareForAcq(this); if (ret != DEVICE_OK) return ret; // make sure the circular buffer is properly sized GetCoreCallback()->InitializeImageBuffer(GetNumberOfComponents(), 1, GetImageWidth(), GetImageHeight(), GetImageBytesPerPixel()); stopContinuousAcquisition = false; continuousAcquisitionDone = false; doContinuousAcquisition = true; stopOnOverflow_ = stopOnOverflow; setupImaging(); J_STATUS_TYPE retval = J_Camera_ExecuteCommand( hCamera, "AcquisitionStart" ); if( retval != J_ST_SUCCESS ) { LogMessage( (std::string) "SnapImage failed to start acquisition" ); J_Image_CloseStream( hThread ); return DEVICE_ERR; } return DEVICE_OK; } int CGigECamera::StopSequenceAcquisition() { if( !doContinuousAcquisition ) return DEVICE_OK; LogMessage( "StopSequenceAcquisition", true ); J_STATUS_TYPE retval; stopContinuousAcquisition = true; MM::MMTime startTime = GetCurrentMMTime(); double exp = GetExposure(); while( !continuousAcquisitionDone && !( GetCurrentMMTime() - startTime < MM::MMTime( 50 * exp * 1000 ) ) ) // x1000 scales ms to us. { CDeviceUtils::SleepMs( 1 ); } if( !continuousAcquisitionDone ) // didn't stop in time { LogMessage( (std::string) "StopSequenceAcquisition stopped the acquisition early because the JAI factory didn't stop soon enough" ); retval = J_Camera_ExecuteCommand( hCamera, "AcquisitionStop" ); if( retval != J_ST_SUCCESS ) { LogMessage( (std::string) "StopSequenceAcquisition failed to stop acquisition" ); } } retval = J_Image_CloseStream( hThread ); if( retval != J_ST_SUCCESS ) { LogMessage( (std::string) "StopSequenceAcquisition failed to close the image stream" ); return DEVICE_ERR; } snapOneImageOnly = false; doContinuousAcquisition = false; continuousAcquisitionDone = false; stopContinuousAcquisition = false; return DEVICE_OK; } /** * Performs exposure and grabs a single image. * This function should block during the actual exposure and return immediately afterwards * (i.e., before readout). This behavior is needed for proper synchronization with the shutter. * Required by the MM::Camera API. */ int CGigECamera::SnapImage() { if( snapOneImageOnly ) return DEVICE_OK; this->snapOneImageOnly = true; this->snapImageDone = false; setupImaging(); J_STATUS_TYPE retval = J_Camera_ExecuteCommand( hCamera, "AcquisitionStart" ); if( retval != J_ST_SUCCESS ) { LogMessage( (std::string) "SnapImage failed to start acquisition" ); J_Image_CloseStream( hThread ); return DEVICE_ERR; } else // retval == J_ST_SUCCESS { LogMessage( "SnapImage: acquisition started; waiting" ); MM::MMTime startTime = GetCurrentMMTime(); double exp = GetExposure(); // wait until the image is acquired (or 20x the expected exposure time has passed) while( !snapImageDone && ( GetCurrentMMTime() - startTime < MM::MMTime( 20 * exp * 1000 ) ) ) // x1000 to scale ms -> us { CDeviceUtils::SleepMs( 1 ); } if( !snapImageDone ) // something happened and we didn't get an image { LogMessage( (std::string) "SnapImage stopped the acquisition because no image had been returned after a long while" ); retval = J_Camera_ExecuteCommand( hCamera, "AcquisitionStop" ); if( retval != J_ST_SUCCESS ) { LogMessage( (std::string) "SnapImage failed to stop acquisition" ); } snapOneImageOnly = false; } } retval = J_Image_CloseStream( hThread ); if( retval != J_ST_SUCCESS ) { LogMessage( (std::string) "SnapImage failed to close the image stream" ); return DEVICE_ERR; } readoutStartTime_ = GetCurrentMMTime(); return DEVICE_OK; } bool CGigECamera::IsCapturing() { return doContinuousAcquisition; }
Add some debug logging.
GigECamera: Add some debug logging. git-svn-id: 03a8048b5ee8463be5048a3801110fb50f378627@11264 d0ab736e-dc22-4aeb-8dc9-08def0aa14fd
C++
mit
kmdouglass/Micro-Manager,kmdouglass/Micro-Manager
7572bc9673bafdd5cdeb5a3df067529897f3364d
desktop/source/app/langselect.cxx
desktop/source/app/langselect.cxx
/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: langselect.cxx,v $ * $Revision: 1.22 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_desktop.hxx" #include "app.hxx" #include "langselect.hxx" #include <stdio.h> #ifndef _RTL_STRING_HXX #include <rtl/string.hxx> #endif #ifndef _SVTOOLS_PATHOPTIONS_HXX #include <unotools/pathoptions.hxx> #endif #include <tools/resid.hxx> #include <i18npool/mslangid.hxx> #include <comphelper/processfactory.hxx> #include <com/sun/star/container/XNameAccess.hpp> #include <com/sun/star/lang/XComponent.hpp> #include <com/sun/star/beans/NamedValue.hpp> #include <com/sun/star/util/XChangesBatch.hpp> #include <com/sun/star/uno/Any.hxx> #include <com/sun/star/lang/XLocalizable.hpp> #include <com/sun/star/lang/Locale.hpp> #include "com/sun/star/util/XFlushable.hpp" #include <rtl/locale.hxx> #include <rtl/instance.hxx> #include <osl/process.h> using namespace rtl; using namespace com::sun::star::uno; using namespace com::sun::star::lang; using namespace com::sun::star::container; using namespace com::sun::star::beans; using namespace com::sun::star::util; namespace desktop { sal_Bool LanguageSelection::bFoundLanguage = sal_False; OUString LanguageSelection::aFoundLanguage; const OUString LanguageSelection::usFallbackLanguage = OUString::createFromAscii("en-US"); Locale LanguageSelection::IsoStringToLocale(const OUString& str) { Locale l; sal_Int32 index=0; l.Language = str.getToken(0, '-', index); if (index >= 0) l.Country = str.getToken(0, '-', index); if (index >= 0) l.Variant = str.getToken(0, '-', index); return l; } bool LanguageSelection::prepareLanguage() { OUString sConfigSrvc = OUString::createFromAscii("com.sun.star.configuration.ConfigurationProvider"); Reference< XMultiServiceFactory > theMSF = comphelper::getProcessServiceFactory(); Reference< XLocalizable > theConfigProvider; try { theConfigProvider = Reference< XLocalizable >(theMSF->createInstance( sConfigSrvc ),UNO_QUERY_THROW ); } catch(const Exception&) { } if(!theConfigProvider.is()) return false; sal_Bool bSuccess = sal_False; // #i42730#get the windows 16Bit locale - it should be preferred over the UI language try { Reference< XPropertySet > xProp(getConfigAccess("org.openoffice.System/L10N/", sal_False), UNO_QUERY_THROW); Any aWin16SysLocale = xProp->getPropertyValue(OUString::createFromAscii("SystemLocale")); ::rtl::OUString sWin16SysLocale; aWin16SysLocale >>= sWin16SysLocale; if( sWin16SysLocale.getLength()) setDefaultLanguage(sWin16SysLocale); } catch(const Exception&) { } // #i32939# use system locale to set document default locale try { OUString usLocale; Reference< XPropertySet > xLocaleProp(getConfigAccess( "org.openoffice.System/L10N", sal_True), UNO_QUERY_THROW); xLocaleProp->getPropertyValue(OUString::createFromAscii("Locale")) >>= usLocale; setDefaultLanguage(usLocale); } catch (Exception&) { } // get the selected UI language as string OUString aLocaleString = getLanguageString(); if ( aLocaleString.getLength() > 0 ) { try { // prepare default config provider by localizing it to the selected locale // this will ensure localized configuration settings to be selected accoring to the // UI language. Locale loc = LanguageSelection::IsoStringToLocale(aLocaleString); // flush any data already written to the configuration (which // currently uses independent caches for different locales and thus // would ignore data written to another cache): Reference< XFlushable >(theConfigProvider, UNO_QUERY_THROW)-> flush(); theConfigProvider->setLocale(loc); Reference< XPropertySet > xProp(getConfigAccess("org.openoffice.Setup/L10N/", sal_True), UNO_QUERY_THROW); xProp->setPropertyValue(OUString::createFromAscii("ooLocale"), makeAny(aLocaleString)); Reference< XChangesBatch >(xProp, UNO_QUERY_THROW)->commitChanges(); MsLangId::setConfiguredSystemUILanguage( MsLangId::convertLocaleToLanguage(loc) ); OUString sLocale; xProp->getPropertyValue(OUString::createFromAscii("ooSetupSystemLocale")) >>= sLocale; if ( sLocale.getLength() ) { loc = LanguageSelection::IsoStringToLocale(aLocaleString); MsLangId::setConfiguredSystemLanguage( MsLangId::convertLocaleToLanguage(loc) ); } else MsLangId::setConfiguredSystemLanguage( MsLangId::getSystemLanguage() ); bSuccess = sal_True; } catch ( PropertyVetoException& ) { // we are not allowed to change this } catch (Exception& e) { OString aMsg = OUStringToOString(e.Message, RTL_TEXTENCODING_ASCII_US); OSL_ENSURE(sal_False, aMsg.getStr()); } } // #i32939# setting of default document locale // #i32939# this should not be based on the UI language setDefaultLanguage(aLocaleString); return bSuccess; } void LanguageSelection::setDefaultLanguage(const OUString& sLocale) { // #i32939# setting of default document language // // See #i42730# for rules for determining source of settings // determine script type of locale LanguageType nLang = MsLangId::convertIsoStringToLanguage(sLocale); sal_uInt16 nScriptType = SvtLanguageOptions::GetScriptTypeOfLanguage(nLang); switch (nScriptType) { case SCRIPTTYPE_ASIAN: MsLangId::setConfiguredAsianFallback( nLang ); break; case SCRIPTTYPE_COMPLEX: MsLangId::setConfiguredComplexFallback( nLang ); break; default: MsLangId::setConfiguredWesternFallback( nLang ); break; } } OUString LanguageSelection::getLanguageString() { // did we already find a language? if (bFoundLanguage) return aFoundLanguage; // check whether the user has selected a specific language OUString aUserLanguage = getUserLanguage(); if (aUserLanguage.getLength() > 0 ) { if (isInstalledLanguage(aUserLanguage)) { // all is well bFoundLanguage = sal_True; aFoundLanguage = aUserLanguage; return aFoundLanguage; } else { // selected language is not/no longer installed resetUserLanguage(); } } // try to use system default aUserLanguage = getSystemLanguage(); if (aUserLanguage.getLength() > 0 ) { if (isInstalledLanguage(aUserLanguage, sal_False)) { // great, system default language is available bFoundLanguage = sal_True; aFoundLanguage = aUserLanguage; return aFoundLanguage; } } // fallback 1: en-US OUString usFB = usFallbackLanguage; if (isInstalledLanguage(usFB)) { bFoundLanguage = sal_True; aFoundLanguage = usFallbackLanguage; return aFoundLanguage; } // fallback didn't work use first installed language aUserLanguage = getFirstInstalledLanguage(); bFoundLanguage = sal_True; aFoundLanguage = aUserLanguage; return aFoundLanguage; } Reference< XNameAccess > LanguageSelection::getConfigAccess(const sal_Char* pPath, sal_Bool bUpdate) { Reference< XNameAccess > xNameAccess; try{ OUString sConfigSrvc = OUString::createFromAscii("com.sun.star.configuration.ConfigurationProvider"); OUString sAccessSrvc; if (bUpdate) sAccessSrvc = OUString::createFromAscii("com.sun.star.configuration.ConfigurationUpdateAccess"); else sAccessSrvc = OUString::createFromAscii("com.sun.star.configuration.ConfigurationAccess"); OUString sConfigURL = OUString::createFromAscii(pPath); // get configuration provider Reference< XMultiServiceFactory > theMSF = comphelper::getProcessServiceFactory(); if (theMSF.is()) { Reference< XMultiServiceFactory > theConfigProvider = Reference< XMultiServiceFactory > ( theMSF->createInstance( sConfigSrvc ),UNO_QUERY_THROW ); // access the provider Sequence< Any > theArgs(1); theArgs[ 0 ] <<= sConfigURL; xNameAccess = Reference< XNameAccess > ( theConfigProvider->createInstanceWithArguments( sAccessSrvc, theArgs ), UNO_QUERY_THROW ); } } catch (com::sun::star::uno::Exception& e) { OString aMsg = OUStringToOString(e.Message, RTL_TEXTENCODING_ASCII_US); OSL_ENSURE(sal_False, aMsg.getStr()); } return xNameAccess; } Sequence< OUString > LanguageSelection::getInstalledLanguages() { Sequence< OUString > seqLanguages; Reference< XNameAccess > xAccess = getConfigAccess("org.openoffice.Setup/Office/InstalledLocales", sal_False); if (!xAccess.is()) return seqLanguages; seqLanguages = xAccess->getElementNames(); return seqLanguages; } // FIXME // it's not very clever to handle language fallbacks here, but // right now, there is no place that handles those fallbacks globally static Sequence< OUString > _getFallbackLocales(const OUString& aIsoLang) { Sequence< OUString > seqFallbacks; if (aIsoLang.equalsAscii("zh-HK")) { seqFallbacks = Sequence< OUString >(1); seqFallbacks[0] = OUString::createFromAscii("zh-TW"); } return seqFallbacks; } sal_Bool LanguageSelection::isInstalledLanguage(OUString& usLocale, sal_Bool bExact) { sal_Bool bInstalled = sal_False; Sequence< OUString > seqLanguages = getInstalledLanguages(); for (sal_Int32 i=0; i<seqLanguages.getLength(); i++) { if (usLocale.equals(seqLanguages[i])) { bInstalled = sal_True; break; } } if (!bInstalled && !bExact) { // try fallback locales Sequence< OUString > seqFallbacks = _getFallbackLocales(usLocale); for (sal_Int32 j=0; j<seqFallbacks.getLength(); j++) { for (sal_Int32 i=0; i<seqLanguages.getLength(); i++) { if (seqFallbacks[j].equals(seqLanguages[i])) { bInstalled = sal_True; usLocale = seqFallbacks[j]; break; } } } } if (!bInstalled && !bExact) { // no exact match was found, well try to find a substitute OUString aInstalledLocale; for (sal_Int32 i=0; i<seqLanguages.getLength(); i++) { if (usLocale.indexOf(seqLanguages[i]) == 0) { // requested locale starts with the installed locale // (i.e. installed locale has index 0 in requested locale) bInstalled = sal_True; usLocale = seqLanguages[i]; break; } } } return bInstalled; } OUString LanguageSelection::getFirstInstalledLanguage() { OUString aLanguage; Sequence< OUString > seqLanguages = getInstalledLanguages(); if (seqLanguages.getLength() > 0) aLanguage = seqLanguages[0]; return aLanguage; } OUString LanguageSelection::getUserLanguage() { OUString aUserLanguage; Reference< XNameAccess > xAccess(getConfigAccess("org.openoffice.Office.Linguistic/General", sal_False)); if (xAccess.is()) { try { xAccess->getByName(OUString::createFromAscii("UILocale")) >>= aUserLanguage; } catch ( NoSuchElementException const & ) { return OUString(); } catch ( WrappedTargetException const & ) { return OUString(); } } return aUserLanguage; } OUString LanguageSelection::getSystemLanguage() { OUString aUserLanguage; Reference< XNameAccess > xAccess(getConfigAccess("org.openoffice.System/L10N", sal_False)); if (xAccess.is()) { try { xAccess->getByName(OUString::createFromAscii("UILocale")) >>= aUserLanguage; } catch ( NoSuchElementException const & ) { return OUString(); } catch ( WrappedTargetException const & ) { return OUString(); } } return aUserLanguage; } void LanguageSelection::resetUserLanguage() { try { Reference< XPropertySet > xProp(getConfigAccess("org.openoffice.Office.Linguistic/General", sal_True), UNO_QUERY_THROW); xProp->setPropertyValue(OUString::createFromAscii("UILocale"), makeAny(OUString::createFromAscii(""))); Reference< XChangesBatch >(xProp, UNO_QUERY_THROW)->commitChanges(); } catch ( PropertyVetoException& ) { // we are not allowed to change this } catch ( Exception& e) { OString aMsg = OUStringToOString(e.Message, RTL_TEXTENCODING_ASCII_US); OSL_ENSURE(sal_False, aMsg.getStr()); } } } // namespace desktop
/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: langselect.cxx,v $ * $Revision: 1.22 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_desktop.hxx" #include "app.hxx" #include "langselect.hxx" #include <stdio.h> #ifndef _RTL_STRING_HXX #include <rtl/string.hxx> #endif #ifndef _SVTOOLS_PATHOPTIONS_HXX #include <unotools/pathoptions.hxx> #endif #include <tools/resid.hxx> #include <i18npool/mslangid.hxx> #include <comphelper/processfactory.hxx> #include <com/sun/star/container/XNameAccess.hpp> #include <com/sun/star/lang/XComponent.hpp> #include <com/sun/star/beans/NamedValue.hpp> #include <com/sun/star/util/XChangesBatch.hpp> #include <com/sun/star/uno/Any.hxx> #include <com/sun/star/lang/XLocalizable.hpp> #include <com/sun/star/lang/Locale.hpp> #include "com/sun/star/util/XFlushable.hpp" #include <rtl/locale.hxx> #include <rtl/instance.hxx> #include <osl/process.h> using namespace rtl; using namespace com::sun::star::uno; using namespace com::sun::star::lang; using namespace com::sun::star::container; using namespace com::sun::star::beans; using namespace com::sun::star::util; namespace desktop { sal_Bool LanguageSelection::bFoundLanguage = sal_False; OUString LanguageSelection::aFoundLanguage; const OUString LanguageSelection::usFallbackLanguage = OUString::createFromAscii("en-US"); Locale LanguageSelection::IsoStringToLocale(const OUString& str) { Locale l; sal_Int32 index=0; l.Language = str.getToken(0, '-', index); if (index >= 0) l.Country = str.getToken(0, '-', index); if (index >= 0) l.Variant = str.getToken(0, '-', index); return l; } bool LanguageSelection::prepareLanguage() { OUString sConfigSrvc = OUString::createFromAscii("com.sun.star.configuration.ConfigurationProvider"); Reference< XMultiServiceFactory > theMSF = comphelper::getProcessServiceFactory(); Reference< XLocalizable > theConfigProvider; try { theConfigProvider = Reference< XLocalizable >(theMSF->createInstance( sConfigSrvc ),UNO_QUERY_THROW ); } catch(const Exception&) { } if(!theConfigProvider.is()) return false; sal_Bool bSuccess = sal_False; // #i42730#get the windows 16Bit locale - it should be preferred over the UI language try { Reference< XPropertySet > xProp(getConfigAccess("org.openoffice.System/L10N/", sal_False), UNO_QUERY_THROW); Any aWin16SysLocale = xProp->getPropertyValue(OUString::createFromAscii("SystemLocale")); ::rtl::OUString sWin16SysLocale; aWin16SysLocale >>= sWin16SysLocale; if( sWin16SysLocale.getLength()) setDefaultLanguage(sWin16SysLocale); } catch(const Exception&) { } // #i32939# use system locale to set document default locale try { OUString usLocale; Reference< XPropertySet > xLocaleProp(getConfigAccess( "org.openoffice.System/L10N", sal_True), UNO_QUERY_THROW); xLocaleProp->getPropertyValue(OUString::createFromAscii("Locale")) >>= usLocale; setDefaultLanguage(usLocale); } catch (Exception&) { } // get the selected UI language as string OUString aLocaleString = getLanguageString(); if ( aLocaleString.getLength() > 0 ) { try { // prepare default config provider by localizing it to the selected locale // this will ensure localized configuration settings to be selected accoring to the // UI language. Locale loc = LanguageSelection::IsoStringToLocale(aLocaleString); // flush any data already written to the configuration (which // currently uses independent caches for different locales and thus // would ignore data written to another cache): Reference< XFlushable >(theConfigProvider, UNO_QUERY_THROW)-> flush(); theConfigProvider->setLocale(loc); Reference< XPropertySet > xProp(getConfigAccess("org.openoffice.Setup/L10N/", sal_True), UNO_QUERY_THROW); xProp->setPropertyValue(OUString::createFromAscii("ooLocale"), makeAny(aLocaleString)); Reference< XChangesBatch >(xProp, UNO_QUERY_THROW)->commitChanges(); MsLangId::setConfiguredSystemUILanguage( MsLangId::convertLocaleToLanguage(loc) ); OUString sLocale; xProp->getPropertyValue(OUString::createFromAscii("ooSetupSystemLocale")) >>= sLocale; if ( sLocale.getLength() ) { loc = LanguageSelection::IsoStringToLocale(sLocale); MsLangId::setConfiguredSystemLanguage( MsLangId::convertLocaleToLanguage(loc) ); } else MsLangId::setConfiguredSystemLanguage( MsLangId::getSystemLanguage() ); bSuccess = sal_True; } catch ( PropertyVetoException& ) { // we are not allowed to change this } catch (Exception& e) { OString aMsg = OUStringToOString(e.Message, RTL_TEXTENCODING_ASCII_US); OSL_ENSURE(sal_False, aMsg.getStr()); } } // #i32939# setting of default document locale // #i32939# this should not be based on the UI language setDefaultLanguage(aLocaleString); return bSuccess; } void LanguageSelection::setDefaultLanguage(const OUString& sLocale) { // #i32939# setting of default document language // // See #i42730# for rules for determining source of settings // determine script type of locale LanguageType nLang = MsLangId::convertIsoStringToLanguage(sLocale); sal_uInt16 nScriptType = SvtLanguageOptions::GetScriptTypeOfLanguage(nLang); switch (nScriptType) { case SCRIPTTYPE_ASIAN: MsLangId::setConfiguredAsianFallback( nLang ); break; case SCRIPTTYPE_COMPLEX: MsLangId::setConfiguredComplexFallback( nLang ); break; default: MsLangId::setConfiguredWesternFallback( nLang ); break; } } OUString LanguageSelection::getLanguageString() { // did we already find a language? if (bFoundLanguage) return aFoundLanguage; // check whether the user has selected a specific language OUString aUserLanguage = getUserLanguage(); if (aUserLanguage.getLength() > 0 ) { if (isInstalledLanguage(aUserLanguage)) { // all is well bFoundLanguage = sal_True; aFoundLanguage = aUserLanguage; return aFoundLanguage; } else { // selected language is not/no longer installed resetUserLanguage(); } } // try to use system default aUserLanguage = getSystemLanguage(); if (aUserLanguage.getLength() > 0 ) { if (isInstalledLanguage(aUserLanguage, sal_False)) { // great, system default language is available bFoundLanguage = sal_True; aFoundLanguage = aUserLanguage; return aFoundLanguage; } } // fallback 1: en-US OUString usFB = usFallbackLanguage; if (isInstalledLanguage(usFB)) { bFoundLanguage = sal_True; aFoundLanguage = usFallbackLanguage; return aFoundLanguage; } // fallback didn't work use first installed language aUserLanguage = getFirstInstalledLanguage(); bFoundLanguage = sal_True; aFoundLanguage = aUserLanguage; return aFoundLanguage; } Reference< XNameAccess > LanguageSelection::getConfigAccess(const sal_Char* pPath, sal_Bool bUpdate) { Reference< XNameAccess > xNameAccess; try{ OUString sConfigSrvc = OUString::createFromAscii("com.sun.star.configuration.ConfigurationProvider"); OUString sAccessSrvc; if (bUpdate) sAccessSrvc = OUString::createFromAscii("com.sun.star.configuration.ConfigurationUpdateAccess"); else sAccessSrvc = OUString::createFromAscii("com.sun.star.configuration.ConfigurationAccess"); OUString sConfigURL = OUString::createFromAscii(pPath); // get configuration provider Reference< XMultiServiceFactory > theMSF = comphelper::getProcessServiceFactory(); if (theMSF.is()) { Reference< XMultiServiceFactory > theConfigProvider = Reference< XMultiServiceFactory > ( theMSF->createInstance( sConfigSrvc ),UNO_QUERY_THROW ); // access the provider Sequence< Any > theArgs(1); theArgs[ 0 ] <<= sConfigURL; xNameAccess = Reference< XNameAccess > ( theConfigProvider->createInstanceWithArguments( sAccessSrvc, theArgs ), UNO_QUERY_THROW ); } } catch (com::sun::star::uno::Exception& e) { OString aMsg = OUStringToOString(e.Message, RTL_TEXTENCODING_ASCII_US); OSL_ENSURE(sal_False, aMsg.getStr()); } return xNameAccess; } Sequence< OUString > LanguageSelection::getInstalledLanguages() { Sequence< OUString > seqLanguages; Reference< XNameAccess > xAccess = getConfigAccess("org.openoffice.Setup/Office/InstalledLocales", sal_False); if (!xAccess.is()) return seqLanguages; seqLanguages = xAccess->getElementNames(); return seqLanguages; } // FIXME // it's not very clever to handle language fallbacks here, but // right now, there is no place that handles those fallbacks globally static Sequence< OUString > _getFallbackLocales(const OUString& aIsoLang) { Sequence< OUString > seqFallbacks; if (aIsoLang.equalsAscii("zh-HK")) { seqFallbacks = Sequence< OUString >(1); seqFallbacks[0] = OUString::createFromAscii("zh-TW"); } return seqFallbacks; } sal_Bool LanguageSelection::isInstalledLanguage(OUString& usLocale, sal_Bool bExact) { sal_Bool bInstalled = sal_False; Sequence< OUString > seqLanguages = getInstalledLanguages(); for (sal_Int32 i=0; i<seqLanguages.getLength(); i++) { if (usLocale.equals(seqLanguages[i])) { bInstalled = sal_True; break; } } if (!bInstalled && !bExact) { // try fallback locales Sequence< OUString > seqFallbacks = _getFallbackLocales(usLocale); for (sal_Int32 j=0; j<seqFallbacks.getLength(); j++) { for (sal_Int32 i=0; i<seqLanguages.getLength(); i++) { if (seqFallbacks[j].equals(seqLanguages[i])) { bInstalled = sal_True; usLocale = seqFallbacks[j]; break; } } } } if (!bInstalled && !bExact) { // no exact match was found, well try to find a substitute OUString aInstalledLocale; for (sal_Int32 i=0; i<seqLanguages.getLength(); i++) { if (usLocale.indexOf(seqLanguages[i]) == 0) { // requested locale starts with the installed locale // (i.e. installed locale has index 0 in requested locale) bInstalled = sal_True; usLocale = seqLanguages[i]; break; } } } return bInstalled; } OUString LanguageSelection::getFirstInstalledLanguage() { OUString aLanguage; Sequence< OUString > seqLanguages = getInstalledLanguages(); if (seqLanguages.getLength() > 0) aLanguage = seqLanguages[0]; return aLanguage; } OUString LanguageSelection::getUserLanguage() { OUString aUserLanguage; Reference< XNameAccess > xAccess(getConfigAccess("org.openoffice.Office.Linguistic/General", sal_False)); if (xAccess.is()) { try { xAccess->getByName(OUString::createFromAscii("UILocale")) >>= aUserLanguage; } catch ( NoSuchElementException const & ) { return OUString(); } catch ( WrappedTargetException const & ) { return OUString(); } } return aUserLanguage; } OUString LanguageSelection::getSystemLanguage() { OUString aUserLanguage; Reference< XNameAccess > xAccess(getConfigAccess("org.openoffice.System/L10N", sal_False)); if (xAccess.is()) { try { xAccess->getByName(OUString::createFromAscii("UILocale")) >>= aUserLanguage; } catch ( NoSuchElementException const & ) { return OUString(); } catch ( WrappedTargetException const & ) { return OUString(); } } return aUserLanguage; } void LanguageSelection::resetUserLanguage() { try { Reference< XPropertySet > xProp(getConfigAccess("org.openoffice.Office.Linguistic/General", sal_True), UNO_QUERY_THROW); xProp->setPropertyValue(OUString::createFromAscii("UILocale"), makeAny(OUString::createFromAscii(""))); Reference< XChangesBatch >(xProp, UNO_QUERY_THROW)->commitChanges(); } catch ( PropertyVetoException& ) { // we are not allowed to change this } catch ( Exception& e) { OString aMsg = OUStringToOString(e.Message, RTL_TEXTENCODING_ASCII_US); OSL_ENSURE(sal_False, aMsg.getStr()); } } } // namespace desktop
fix typo
#i108067#: fix typo
C++
mpl-2.0
JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core
37df959f7ff627a91fb6f7110ce65780b29a3bcb
chrome/browser/printing/print_dialog_cloud_uitest.cc
chrome/browser/printing/print_dialog_cloud_uitest.cc
// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/printing/print_dialog_cloud.h" #include "chrome/browser/printing/print_dialog_cloud_internal.h" #include <functional> #include "base/bind.h" #include "base/file_path.h" #include "base/file_util.h" #include "base/memory/singleton.h" #include "base/path_service.h" #include "base/threading/thread_restrictions.h" #include "base/utf_string_conversions.h" #include "base/values.h" #include "chrome/browser/printing/cloud_print/cloud_print_url.h" #include "chrome/browser/ui/browser_list.h" #include "chrome/browser/ui/webui/chrome_url_data_manager.h" #include "chrome/common/chrome_paths.h" #include "chrome/common/url_constants.h" #include "chrome/test/base/in_process_browser_test.h" #include "chrome/test/base/ui_test_utils.h" #include "content/browser/renderer_host/render_view_host.h" #include "content/browser/tab_contents/tab_contents.h" #include "content/public/browser/notification_service.h" #include "content/public/browser/notification_types.h" #include "content/test/test_browser_thread.h" #include "net/url_request/url_request_filter.h" #include "net/url_request/url_request_test_job.h" #include "net/url_request/url_request_test_util.h" using content::BrowserThread; namespace { class TestData { public: static TestData* GetInstance() { return Singleton<TestData>::get(); } const char* GetTestData() { // Fetching this data blocks the IO thread, but we don't really care because // this is a test. base::ThreadRestrictions::ScopedAllowIO allow_io; if (test_data_.empty()) { FilePath test_data_directory; PathService::Get(chrome::DIR_TEST_DATA, &test_data_directory); FilePath test_file = test_data_directory.AppendASCII("printing/cloud_print_uitest.html"); file_util::ReadFileToString(test_file, &test_data_); } return test_data_.c_str(); } private: TestData() {} std::string test_data_; friend struct DefaultSingletonTraits<TestData>; }; // A simple test net::URLRequestJob. We don't care what it does, only that // whether it starts and finishes. class SimpleTestJob : public net::URLRequestTestJob { public: explicit SimpleTestJob(net::URLRequest* request) : net::URLRequestTestJob(request, test_headers(), TestData::GetInstance()->GetTestData(), true) {} virtual void GetResponseInfo(net::HttpResponseInfo* info) { net::URLRequestTestJob::GetResponseInfo(info); if (request_->url().SchemeIsSecure()) { // Make up a fake certificate for this response since we don't have // access to the real SSL info. const char* kCertIssuer = "Chrome Internal"; const int kLifetimeDays = 100; info->ssl_info.cert = new net::X509Certificate(request_->url().GetWithEmptyPath().spec(), kCertIssuer, base::Time::Now(), base::Time::Now() + base::TimeDelta::FromDays(kLifetimeDays)); info->ssl_info.cert_status = 0; info->ssl_info.security_bits = -1; } } private: ~SimpleTestJob() {} }; class TestController { public: static TestController* GetInstance() { return Singleton<TestController>::get(); } void set_result(bool value) { result_ = value; } bool result() { return result_; } void set_expected_url(const GURL& url) { expected_url_ = url; } const GURL expected_url() { return expected_url_; } void set_delegate(TestDelegate* delegate) { delegate_ = delegate; } TestDelegate* delegate() { return delegate_; } void set_use_delegate(bool value) { use_delegate_ = value; } bool use_delegate() { return use_delegate_; } private: TestController() : result_(false), use_delegate_(false), delegate_(NULL) {} bool result_; bool use_delegate_; GURL expected_url_; TestDelegate* delegate_; friend struct DefaultSingletonTraits<TestController>; }; } // namespace class PrintDialogCloudTest : public InProcessBrowserTest { public: PrintDialogCloudTest() : handler_added_(false) { PathService::Get(chrome::DIR_TEST_DATA, &test_data_directory_); } // Must be static for handing into AddHostnameHandler. static net::URLRequest::ProtocolFactory Factory; class AutoQuitDelegate : public TestDelegate { public: AutoQuitDelegate() {} virtual void OnResponseCompleted(net::URLRequest* request) { BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, MessageLoop::QuitClosure()); } }; virtual void SetUp() { TestController::GetInstance()->set_result(false); InProcessBrowserTest::SetUp(); } virtual void TearDown() { if (handler_added_) { net::URLRequestFilter* filter = net::URLRequestFilter::GetInstance(); filter->RemoveHostnameHandler(scheme_, host_name_); handler_added_ = false; TestController::GetInstance()->set_delegate(NULL); } InProcessBrowserTest::TearDown(); } // Normally this is something I would expect could go into SetUp(), // but there seems to be some timing or ordering related issue with // the test harness that made that flaky. Calling this from the // individual test functions seems to fix that. void AddTestHandlers() { if (!handler_added_) { net::URLRequestFilter* filter = net::URLRequestFilter::GetInstance(); GURL cloud_print_service_url = CloudPrintURL(browser()->profile()). GetCloudPrintServiceURL(); scheme_ = cloud_print_service_url.scheme(); host_name_ = cloud_print_service_url.host(); filter->AddHostnameHandler(scheme_, host_name_, &PrintDialogCloudTest::Factory); handler_added_ = true; GURL cloud_print_dialog_url = CloudPrintURL(browser()->profile()). GetCloudPrintServiceDialogURL(); TestController::GetInstance()->set_expected_url(cloud_print_dialog_url); TestController::GetInstance()->set_delegate(&delegate_); } CreateDialogForTest(); } void CreateDialogForTest() { FilePath path_to_pdf = test_data_directory_.AppendASCII("printing/cloud_print_uitest.pdf"); BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, base::Bind(&internal_cloud_print_helpers::CreateDialogImpl, path_to_pdf, string16(), string16(), std::string("application/pdf"), true, false)); } bool handler_added_; std::string scheme_; std::string host_name_; FilePath test_data_directory_; AutoQuitDelegate delegate_; }; net::URLRequestJob* PrintDialogCloudTest::Factory(net::URLRequest* request, const std::string& scheme) { if (TestController::GetInstance()->use_delegate()) request->set_delegate(TestController::GetInstance()->delegate()); if (request && (request->url() == TestController::GetInstance()->expected_url())) { TestController::GetInstance()->set_result(true); } return new SimpleTestJob(request); } #if defined(OS_WIN) // http://crbug.com/94864 for OS_WIN issue #define MAYBE_HandlersRegistered DISABLED_HandlersRegistered #else #define MAYBE_HandlersRegistered HandlersRegistered #endif IN_PROC_BROWSER_TEST_F(PrintDialogCloudTest, MAYBE_HandlersRegistered) { BrowserList::SetLastActive(browser()); ASSERT_TRUE(BrowserList::GetLastActive()); AddTestHandlers(); TestController::GetInstance()->set_use_delegate(true); ui_test_utils::RunMessageLoop(); ASSERT_TRUE(TestController::GetInstance()->result()); // Close the dialog before finishing the test. ui_test_utils::WindowedNotificationObserver signal( content::NOTIFICATION_TAB_CLOSED, content::NotificationService::AllSources()); EXPECT_TRUE(ui_test_utils::SendKeyPressSync(browser(), ui::VKEY_ESCAPE, false, false, false, false)); signal.Wait(); } #if defined(OS_CHROMEOS) // Disabled until the extern URL is live so that the Print menu item // can be enabled for Chromium OS. IN_PROC_BROWSER_TEST_F(PrintDialogCloudTest, DISABLED_DialogGrabbed) { BrowserList::SetLastActive(browser()); ASSERT_TRUE(BrowserList::GetLastActive()); AddTestHandlers(); // This goes back one step further for the Chrome OS case, to making // sure 'window.print()' gets to the right place. ASSERT_TRUE(browser()->GetSelectedTabContents()); ASSERT_TRUE(browser()->GetSelectedTabContents()->render_view_host()); string16 window_print = ASCIIToUTF16("window.print()"); browser()->GetSelectedTabContents()->render_view_host()-> ExecuteJavascriptInWebFrame(string16(), window_print); ui_test_utils::RunMessageLoop(); ASSERT_TRUE(TestController::GetInstance()->result()); } #endif
// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/printing/print_dialog_cloud.h" #include "chrome/browser/printing/print_dialog_cloud_internal.h" #include <functional> #include "base/bind.h" #include "base/file_path.h" #include "base/file_util.h" #include "base/memory/singleton.h" #include "base/path_service.h" #include "base/threading/thread_restrictions.h" #include "base/utf_string_conversions.h" #include "base/values.h" #include "chrome/browser/printing/cloud_print/cloud_print_url.h" #include "chrome/browser/ui/browser_list.h" #include "chrome/browser/ui/webui/chrome_url_data_manager.h" #include "chrome/common/chrome_paths.h" #include "chrome/common/url_constants.h" #include "chrome/test/base/in_process_browser_test.h" #include "chrome/test/base/ui_test_utils.h" #include "content/browser/renderer_host/render_view_host.h" #include "content/browser/tab_contents/tab_contents.h" #include "content/public/browser/notification_service.h" #include "content/public/browser/notification_types.h" #include "content/test/test_browser_thread.h" #include "net/url_request/url_request_filter.h" #include "net/url_request/url_request_test_job.h" #include "net/url_request/url_request_test_util.h" using content::BrowserThread; namespace { class TestData { public: static TestData* GetInstance() { return Singleton<TestData>::get(); } const char* GetTestData() { // Fetching this data blocks the IO thread, but we don't really care because // this is a test. base::ThreadRestrictions::ScopedAllowIO allow_io; if (test_data_.empty()) { FilePath test_data_directory; PathService::Get(chrome::DIR_TEST_DATA, &test_data_directory); FilePath test_file = test_data_directory.AppendASCII("printing/cloud_print_uitest.html"); file_util::ReadFileToString(test_file, &test_data_); } return test_data_.c_str(); } private: TestData() {} std::string test_data_; friend struct DefaultSingletonTraits<TestData>; }; // A simple test net::URLRequestJob. We don't care what it does, only that // whether it starts and finishes. class SimpleTestJob : public net::URLRequestTestJob { public: explicit SimpleTestJob(net::URLRequest* request) : net::URLRequestTestJob(request, test_headers(), TestData::GetInstance()->GetTestData(), true) {} virtual void GetResponseInfo(net::HttpResponseInfo* info) { net::URLRequestTestJob::GetResponseInfo(info); if (request_->url().SchemeIsSecure()) { // Make up a fake certificate for this response since we don't have // access to the real SSL info. const char* kCertIssuer = "Chrome Internal"; const int kLifetimeDays = 100; info->ssl_info.cert = new net::X509Certificate(request_->url().GetWithEmptyPath().spec(), kCertIssuer, base::Time::Now(), base::Time::Now() + base::TimeDelta::FromDays(kLifetimeDays)); info->ssl_info.cert_status = 0; info->ssl_info.security_bits = -1; } } private: ~SimpleTestJob() {} }; class TestController { public: static TestController* GetInstance() { return Singleton<TestController>::get(); } void set_result(bool value) { result_ = value; } bool result() { return result_; } void set_expected_url(const GURL& url) { expected_url_ = url; } const GURL expected_url() { return expected_url_; } void set_delegate(TestDelegate* delegate) { delegate_ = delegate; } TestDelegate* delegate() { return delegate_; } void set_use_delegate(bool value) { use_delegate_ = value; } bool use_delegate() { return use_delegate_; } private: TestController() : result_(false), use_delegate_(false), delegate_(NULL) {} bool result_; bool use_delegate_; GURL expected_url_; TestDelegate* delegate_; friend struct DefaultSingletonTraits<TestController>; }; } // namespace class PrintDialogCloudTest : public InProcessBrowserTest { public: PrintDialogCloudTest() : handler_added_(false) { PathService::Get(chrome::DIR_TEST_DATA, &test_data_directory_); } // Must be static for handing into AddHostnameHandler. static net::URLRequest::ProtocolFactory Factory; class AutoQuitDelegate : public TestDelegate { public: AutoQuitDelegate() {} virtual void OnResponseCompleted(net::URLRequest* request) { BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, MessageLoop::QuitClosure()); } }; virtual void SetUp() { TestController::GetInstance()->set_result(false); InProcessBrowserTest::SetUp(); } virtual void TearDown() { if (handler_added_) { net::URLRequestFilter* filter = net::URLRequestFilter::GetInstance(); filter->RemoveHostnameHandler(scheme_, host_name_); handler_added_ = false; TestController::GetInstance()->set_delegate(NULL); } InProcessBrowserTest::TearDown(); } // Normally this is something I would expect could go into SetUp(), // but there seems to be some timing or ordering related issue with // the test harness that made that flaky. Calling this from the // individual test functions seems to fix that. void AddTestHandlers() { if (!handler_added_) { net::URLRequestFilter* filter = net::URLRequestFilter::GetInstance(); GURL cloud_print_service_url = CloudPrintURL(browser()->profile()). GetCloudPrintServiceURL(); scheme_ = cloud_print_service_url.scheme(); host_name_ = cloud_print_service_url.host(); filter->AddHostnameHandler(scheme_, host_name_, &PrintDialogCloudTest::Factory); handler_added_ = true; GURL cloud_print_dialog_url = CloudPrintURL(browser()->profile()). GetCloudPrintServiceDialogURL(); TestController::GetInstance()->set_expected_url(cloud_print_dialog_url); TestController::GetInstance()->set_delegate(&delegate_); } CreateDialogForTest(); } void CreateDialogForTest() { FilePath path_to_pdf = test_data_directory_.AppendASCII("printing/cloud_print_uitest.pdf"); BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, base::Bind(&internal_cloud_print_helpers::CreateDialogImpl, path_to_pdf, string16(), string16(), std::string("application/pdf"), true, false)); } bool handler_added_; std::string scheme_; std::string host_name_; FilePath test_data_directory_; AutoQuitDelegate delegate_; }; net::URLRequestJob* PrintDialogCloudTest::Factory(net::URLRequest* request, const std::string& scheme) { if (TestController::GetInstance()->use_delegate()) request->set_delegate(TestController::GetInstance()->delegate()); if (request && (request->url() == TestController::GetInstance()->expected_url())) { TestController::GetInstance()->set_result(true); } return new SimpleTestJob(request); } #if defined(OS_WIN) || defined(USE_AURA) // http://crbug.com/94864 for OS_WIN issue // http://crbug.com/103497 for USE_AURA issue #define MAYBE_HandlersRegistered DISABLED_HandlersRegistered #else #define MAYBE_HandlersRegistered HandlersRegistered #endif IN_PROC_BROWSER_TEST_F(PrintDialogCloudTest, MAYBE_HandlersRegistered) { BrowserList::SetLastActive(browser()); ASSERT_TRUE(BrowserList::GetLastActive()); AddTestHandlers(); TestController::GetInstance()->set_use_delegate(true); ui_test_utils::RunMessageLoop(); ASSERT_TRUE(TestController::GetInstance()->result()); // Close the dialog before finishing the test. ui_test_utils::WindowedNotificationObserver signal( content::NOTIFICATION_TAB_CLOSED, content::NotificationService::AllSources()); EXPECT_TRUE(ui_test_utils::SendKeyPressSync(browser(), ui::VKEY_ESCAPE, false, false, false, false)); signal.Wait(); } #if defined(OS_CHROMEOS) // Disabled until the extern URL is live so that the Print menu item // can be enabled for Chromium OS. IN_PROC_BROWSER_TEST_F(PrintDialogCloudTest, DISABLED_DialogGrabbed) { BrowserList::SetLastActive(browser()); ASSERT_TRUE(BrowserList::GetLastActive()); AddTestHandlers(); // This goes back one step further for the Chrome OS case, to making // sure 'window.print()' gets to the right place. ASSERT_TRUE(browser()->GetSelectedTabContents()); ASSERT_TRUE(browser()->GetSelectedTabContents()->render_view_host()); string16 window_print = ASCIIToUTF16("window.print()"); browser()->GetSelectedTabContents()->render_view_host()-> ExecuteJavascriptInWebFrame(string16(), window_print); ui_test_utils::RunMessageLoop(); ASSERT_TRUE(TestController::GetInstance()->result()); } #endif
Disable PrintDialogloudTest.HandlerRegistered again This passes locally and was passing two days ago on aura bot, but now it's failing. Disabling again
Disable PrintDialogloudTest.HandlerRegistered again This passes locally and was passing two days ago on aura bot, but now it's failing. Disabling again [email protected] BUG=103497 TEST=none Review URL: http://codereview.chromium.org/8907030 git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@114498 0039d316-1c4b-4281-b951-d872f2087c98
C++
bsd-3-clause
yitian134/chromium,gavinp/chromium,adobe/chromium,adobe/chromium,adobe/chromium,yitian134/chromium,gavinp/chromium,yitian134/chromium,ropik/chromium,yitian134/chromium,yitian134/chromium,adobe/chromium,adobe/chromium,adobe/chromium,yitian134/chromium,adobe/chromium,yitian134/chromium,yitian134/chromium,adobe/chromium,ropik/chromium,gavinp/chromium,ropik/chromium,ropik/chromium,gavinp/chromium,ropik/chromium,gavinp/chromium,gavinp/chromium,gavinp/chromium,adobe/chromium,gavinp/chromium,ropik/chromium,ropik/chromium,adobe/chromium,ropik/chromium,gavinp/chromium,gavinp/chromium,yitian134/chromium,adobe/chromium,yitian134/chromium,ropik/chromium
0b8545bf5feeb7e5340eeff11279402c2d06a778
chrome/browser/ui/webui/print_preview_ui_unittest.cc
chrome/browser/ui/webui/print_preview_ui_unittest.cc
// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <vector> #include "base/command_line.h" #include "base/memory/ref_counted_memory.h" #include "chrome/browser/printing/print_preview_tab_controller.h" #include "chrome/browser/printing/print_view_manager.h" #include "chrome/browser/ui/browser_list.h" #include "chrome/browser/ui/constrained_window_tab_helper.h" #include "chrome/browser/ui/tab_contents/tab_contents_wrapper.h" #include "chrome/browser/ui/webui/print_preview_ui.h" #include "chrome/common/chrome_switches.h" #include "chrome/test/base/browser_with_test_window_test.h" #include "chrome/test/base/testing_profile.h" #include "content/public/browser/web_contents.h" #include "printing/print_job_constants.h" namespace { const unsigned char blob1[] = "12346102356120394751634516591348710478123649165419234519234512349134"; size_t GetConstrainedWindowCount(TabContentsWrapper* tab) { return tab->constrained_window_tab_helper()->constrained_window_count(); } } // namespace typedef BrowserWithTestWindowTest PrintPreviewUIUnitTest; // Create/Get a preview tab for initiator tab. TEST_F(PrintPreviewUIUnitTest, PrintPreviewData) { CommandLine::ForCurrentProcess()->AppendSwitch(switches::kEnablePrintPreview); ASSERT_TRUE(browser()); BrowserList::SetLastActive(browser()); ASSERT_TRUE(BrowserList::GetLastActive()); browser()->NewTab(); TabContentsWrapper* initiator_tab = browser()->GetSelectedTabContentsWrapper(); ASSERT_TRUE(initiator_tab); EXPECT_EQ(0U, GetConstrainedWindowCount(initiator_tab)); printing::PrintPreviewTabController* controller = printing::PrintPreviewTabController::GetInstance(); ASSERT_TRUE(controller); initiator_tab->print_view_manager()->PrintPreviewNow(); TabContentsWrapper* preview_tab = controller->GetOrCreatePreviewTab(initiator_tab); EXPECT_NE(initiator_tab, preview_tab); EXPECT_EQ(1, browser()->tab_count()); EXPECT_EQ(1U, GetConstrainedWindowCount(initiator_tab)); PrintPreviewUI* preview_ui = reinterpret_cast<PrintPreviewUI*>( preview_tab->web_contents()->GetWebUI()); ASSERT_TRUE(preview_ui != NULL); scoped_refptr<RefCountedBytes> data; preview_ui->GetPrintPreviewDataForIndex( printing::COMPLETE_PREVIEW_DOCUMENT_INDEX, &data); EXPECT_EQ(NULL, data.get()); std::vector<unsigned char> preview_data(blob1, blob1 + sizeof(blob1)); scoped_refptr<RefCountedBytes> dummy_data(new RefCountedBytes(preview_data)); preview_ui->SetPrintPreviewDataForIndex( printing::COMPLETE_PREVIEW_DOCUMENT_INDEX, dummy_data.get()); preview_ui->GetPrintPreviewDataForIndex( printing::COMPLETE_PREVIEW_DOCUMENT_INDEX, &data); EXPECT_EQ(dummy_data->size(), data->size()); EXPECT_EQ(dummy_data.get(), data.get()); // This should not cause any memory leaks. dummy_data = new RefCountedBytes(); preview_ui->SetPrintPreviewDataForIndex(printing::FIRST_PAGE_INDEX, dummy_data); // Clear the preview data. preview_ui->ClearAllPreviewData(); preview_ui->GetPrintPreviewDataForIndex( printing::COMPLETE_PREVIEW_DOCUMENT_INDEX, &data); EXPECT_EQ(NULL, data.get()); } // Set and get the individual draft pages. TEST_F(PrintPreviewUIUnitTest, PrintPreviewDraftPages) { #if !defined(GOOGLE_CHROME_BUILD) || defined(OS_CHROMEOS) CommandLine::ForCurrentProcess()->AppendSwitch(switches::kEnablePrintPreview); #endif ASSERT_TRUE(browser()); BrowserList::SetLastActive(browser()); ASSERT_TRUE(BrowserList::GetLastActive()); browser()->NewTab(); TabContentsWrapper* initiator_tab = browser()->GetSelectedTabContentsWrapper(); ASSERT_TRUE(initiator_tab); printing::PrintPreviewTabController* controller = printing::PrintPreviewTabController::GetInstance(); ASSERT_TRUE(controller); initiator_tab->print_view_manager()->PrintPreviewNow(); TabContentsWrapper* preview_tab = controller->GetOrCreatePreviewTab(initiator_tab); EXPECT_NE(initiator_tab, preview_tab); EXPECT_EQ(1, browser()->tab_count()); EXPECT_EQ(1U, GetConstrainedWindowCount(initiator_tab)); PrintPreviewUI* preview_ui = reinterpret_cast<PrintPreviewUI*>( preview_tab->web_contents()->GetWebUI()); ASSERT_TRUE(preview_ui != NULL); scoped_refptr<RefCountedBytes> data; preview_ui->GetPrintPreviewDataForIndex(printing::FIRST_PAGE_INDEX, &data); EXPECT_EQ(NULL, data.get()); std::vector<unsigned char> preview_data(blob1, blob1 + sizeof(blob1)); scoped_refptr<RefCountedBytes> dummy_data(new RefCountedBytes(preview_data)); preview_ui->SetPrintPreviewDataForIndex(printing::FIRST_PAGE_INDEX, dummy_data.get()); preview_ui->GetPrintPreviewDataForIndex(printing::FIRST_PAGE_INDEX, &data); EXPECT_EQ(dummy_data->size(), data->size()); EXPECT_EQ(dummy_data.get(), data.get()); // Set and get the third page data. preview_ui->SetPrintPreviewDataForIndex(printing::FIRST_PAGE_INDEX + 2, dummy_data.get()); preview_ui->GetPrintPreviewDataForIndex(printing::FIRST_PAGE_INDEX + 2, &data); EXPECT_EQ(dummy_data->size(), data->size()); EXPECT_EQ(dummy_data.get(), data.get()); // Get the second page data. preview_ui->GetPrintPreviewDataForIndex(printing::FIRST_PAGE_INDEX + 1, &data); EXPECT_EQ(NULL, data.get()); preview_ui->SetPrintPreviewDataForIndex(printing::FIRST_PAGE_INDEX + 1, dummy_data.get()); preview_ui->GetPrintPreviewDataForIndex(printing::FIRST_PAGE_INDEX + 1, &data); EXPECT_EQ(dummy_data->size(), data->size()); EXPECT_EQ(dummy_data.get(), data.get()); // Clear the preview data. preview_ui->ClearAllPreviewData(); preview_ui->GetPrintPreviewDataForIndex(printing::FIRST_PAGE_INDEX, &data); EXPECT_EQ(NULL, data.get()); } // Test the browser-side print preview cancellation functionality. TEST_F(PrintPreviewUIUnitTest, GetCurrentPrintPreviewStatus) { #if !defined(GOOGLE_CHROME_BUILD) || defined(OS_CHROMEOS) CommandLine::ForCurrentProcess()->AppendSwitch(switches::kEnablePrintPreview); #endif ASSERT_TRUE(browser()); BrowserList::SetLastActive(browser()); ASSERT_TRUE(BrowserList::GetLastActive()); browser()->NewTab(); TabContentsWrapper* initiator_tab = browser()->GetSelectedTabContentsWrapper(); ASSERT_TRUE(initiator_tab); printing::PrintPreviewTabController* controller = printing::PrintPreviewTabController::GetInstance(); ASSERT_TRUE(controller); initiator_tab->print_view_manager()->PrintPreviewNow(); TabContentsWrapper* preview_tab = controller->GetOrCreatePreviewTab(initiator_tab); EXPECT_NE(initiator_tab, preview_tab); EXPECT_EQ(1, browser()->tab_count()); EXPECT_EQ(1U, GetConstrainedWindowCount(initiator_tab)); PrintPreviewUI* preview_ui = reinterpret_cast<PrintPreviewUI*>( preview_tab->web_contents()->GetWebUI()); ASSERT_TRUE(preview_ui != NULL); // Test with invalid |preview_ui_addr|. bool cancel = false; preview_ui->GetCurrentPrintPreviewStatus("invalid", 0, &cancel); EXPECT_TRUE(cancel); const int kFirstRequestId = 1000; const int kSecondRequestId = 1001; const std::string preview_ui_addr = preview_ui->GetPrintPreviewUIAddress(); // Test with kFirstRequestId. preview_ui->OnPrintPreviewRequest(kFirstRequestId); cancel = true; preview_ui->GetCurrentPrintPreviewStatus(preview_ui_addr, kFirstRequestId, &cancel); EXPECT_FALSE(cancel); cancel = false; preview_ui->GetCurrentPrintPreviewStatus(preview_ui_addr, kSecondRequestId, &cancel); EXPECT_TRUE(cancel); // Test with kSecondRequestId. preview_ui->OnPrintPreviewRequest(kSecondRequestId); cancel = false; preview_ui->GetCurrentPrintPreviewStatus(preview_ui_addr, kFirstRequestId, &cancel); EXPECT_TRUE(cancel); cancel = true; preview_ui->GetCurrentPrintPreviewStatus(preview_ui_addr, kSecondRequestId, &cancel); EXPECT_FALSE(cancel); }
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <vector> #include "base/command_line.h" #include "base/memory/ref_counted_memory.h" #include "chrome/browser/printing/print_preview_tab_controller.h" #include "chrome/browser/printing/print_view_manager.h" #include "chrome/browser/ui/browser_list.h" #include "chrome/browser/ui/constrained_window_tab_helper.h" #include "chrome/browser/ui/tab_contents/tab_contents_wrapper.h" #include "chrome/browser/ui/webui/print_preview_ui.h" #include "chrome/common/chrome_switches.h" #include "chrome/test/base/browser_with_test_window_test.h" #include "chrome/test/base/testing_profile.h" #include "content/public/browser/web_contents.h" #include "printing/print_job_constants.h" namespace { const unsigned char blob1[] = "12346102356120394751634516591348710478123649165419234519234512349134"; size_t GetConstrainedWindowCount(TabContentsWrapper* tab) { return tab->constrained_window_tab_helper()->constrained_window_count(); } } // namespace typedef BrowserWithTestWindowTest PrintPreviewUIUnitTest; // Create/Get a preview tab for initiator tab. TEST_F(PrintPreviewUIUnitTest, PrintPreviewData) { CommandLine::ForCurrentProcess()->AppendSwitch(switches::kEnablePrintPreview); ASSERT_TRUE(browser()); BrowserList::SetLastActive(browser()); ASSERT_TRUE(BrowserList::GetLastActive()); browser()->NewTab(); TabContentsWrapper* initiator_tab = browser()->GetSelectedTabContentsWrapper(); ASSERT_TRUE(initiator_tab); EXPECT_EQ(0U, GetConstrainedWindowCount(initiator_tab)); printing::PrintPreviewTabController* controller = printing::PrintPreviewTabController::GetInstance(); ASSERT_TRUE(controller); initiator_tab->print_view_manager()->PrintPreviewNow(); TabContentsWrapper* preview_tab = controller->GetOrCreatePreviewTab(initiator_tab); EXPECT_NE(initiator_tab, preview_tab); EXPECT_EQ(1, browser()->tab_count()); EXPECT_EQ(1U, GetConstrainedWindowCount(initiator_tab)); PrintPreviewUI* preview_ui = reinterpret_cast<PrintPreviewUI*>( preview_tab->web_contents()->GetWebUI()); ASSERT_TRUE(preview_ui != NULL); scoped_refptr<RefCountedBytes> data; preview_ui->GetPrintPreviewDataForIndex( printing::COMPLETE_PREVIEW_DOCUMENT_INDEX, &data); EXPECT_EQ(NULL, data.get()); std::vector<unsigned char> preview_data(blob1, blob1 + sizeof(blob1)); scoped_refptr<RefCountedBytes> dummy_data(new RefCountedBytes(preview_data)); preview_ui->SetPrintPreviewDataForIndex( printing::COMPLETE_PREVIEW_DOCUMENT_INDEX, dummy_data.get()); preview_ui->GetPrintPreviewDataForIndex( printing::COMPLETE_PREVIEW_DOCUMENT_INDEX, &data); EXPECT_EQ(dummy_data->size(), data->size()); EXPECT_EQ(dummy_data.get(), data.get()); // This should not cause any memory leaks. dummy_data = new RefCountedBytes(); preview_ui->SetPrintPreviewDataForIndex(printing::FIRST_PAGE_INDEX, dummy_data); // Clear the preview data. preview_ui->ClearAllPreviewData(); preview_ui->GetPrintPreviewDataForIndex( printing::COMPLETE_PREVIEW_DOCUMENT_INDEX, &data); EXPECT_EQ(NULL, data.get()); } // Set and get the individual draft pages. TEST_F(PrintPreviewUIUnitTest, PrintPreviewDraftPages) { CommandLine::ForCurrentProcess()->AppendSwitch(switches::kEnablePrintPreview); ASSERT_TRUE(browser()); BrowserList::SetLastActive(browser()); ASSERT_TRUE(BrowserList::GetLastActive()); browser()->NewTab(); TabContentsWrapper* initiator_tab = browser()->GetSelectedTabContentsWrapper(); ASSERT_TRUE(initiator_tab); printing::PrintPreviewTabController* controller = printing::PrintPreviewTabController::GetInstance(); ASSERT_TRUE(controller); initiator_tab->print_view_manager()->PrintPreviewNow(); TabContentsWrapper* preview_tab = controller->GetOrCreatePreviewTab(initiator_tab); EXPECT_NE(initiator_tab, preview_tab); EXPECT_EQ(1, browser()->tab_count()); EXPECT_EQ(1U, GetConstrainedWindowCount(initiator_tab)); PrintPreviewUI* preview_ui = reinterpret_cast<PrintPreviewUI*>( preview_tab->web_contents()->GetWebUI()); ASSERT_TRUE(preview_ui != NULL); scoped_refptr<RefCountedBytes> data; preview_ui->GetPrintPreviewDataForIndex(printing::FIRST_PAGE_INDEX, &data); EXPECT_EQ(NULL, data.get()); std::vector<unsigned char> preview_data(blob1, blob1 + sizeof(blob1)); scoped_refptr<RefCountedBytes> dummy_data(new RefCountedBytes(preview_data)); preview_ui->SetPrintPreviewDataForIndex(printing::FIRST_PAGE_INDEX, dummy_data.get()); preview_ui->GetPrintPreviewDataForIndex(printing::FIRST_PAGE_INDEX, &data); EXPECT_EQ(dummy_data->size(), data->size()); EXPECT_EQ(dummy_data.get(), data.get()); // Set and get the third page data. preview_ui->SetPrintPreviewDataForIndex(printing::FIRST_PAGE_INDEX + 2, dummy_data.get()); preview_ui->GetPrintPreviewDataForIndex(printing::FIRST_PAGE_INDEX + 2, &data); EXPECT_EQ(dummy_data->size(), data->size()); EXPECT_EQ(dummy_data.get(), data.get()); // Get the second page data. preview_ui->GetPrintPreviewDataForIndex(printing::FIRST_PAGE_INDEX + 1, &data); EXPECT_EQ(NULL, data.get()); preview_ui->SetPrintPreviewDataForIndex(printing::FIRST_PAGE_INDEX + 1, dummy_data.get()); preview_ui->GetPrintPreviewDataForIndex(printing::FIRST_PAGE_INDEX + 1, &data); EXPECT_EQ(dummy_data->size(), data->size()); EXPECT_EQ(dummy_data.get(), data.get()); // Clear the preview data. preview_ui->ClearAllPreviewData(); preview_ui->GetPrintPreviewDataForIndex(printing::FIRST_PAGE_INDEX, &data); EXPECT_EQ(NULL, data.get()); } // Test the browser-side print preview cancellation functionality. TEST_F(PrintPreviewUIUnitTest, GetCurrentPrintPreviewStatus) { CommandLine::ForCurrentProcess()->AppendSwitch(switches::kEnablePrintPreview); ASSERT_TRUE(browser()); BrowserList::SetLastActive(browser()); ASSERT_TRUE(BrowserList::GetLastActive()); browser()->NewTab(); TabContentsWrapper* initiator_tab = browser()->GetSelectedTabContentsWrapper(); ASSERT_TRUE(initiator_tab); printing::PrintPreviewTabController* controller = printing::PrintPreviewTabController::GetInstance(); ASSERT_TRUE(controller); initiator_tab->print_view_manager()->PrintPreviewNow(); TabContentsWrapper* preview_tab = controller->GetOrCreatePreviewTab(initiator_tab); EXPECT_NE(initiator_tab, preview_tab); EXPECT_EQ(1, browser()->tab_count()); EXPECT_EQ(1U, GetConstrainedWindowCount(initiator_tab)); PrintPreviewUI* preview_ui = reinterpret_cast<PrintPreviewUI*>( preview_tab->web_contents()->GetWebUI()); ASSERT_TRUE(preview_ui != NULL); // Test with invalid |preview_ui_addr|. bool cancel = false; preview_ui->GetCurrentPrintPreviewStatus("invalid", 0, &cancel); EXPECT_TRUE(cancel); const int kFirstRequestId = 1000; const int kSecondRequestId = 1001; const std::string preview_ui_addr = preview_ui->GetPrintPreviewUIAddress(); // Test with kFirstRequestId. preview_ui->OnPrintPreviewRequest(kFirstRequestId); cancel = true; preview_ui->GetCurrentPrintPreviewStatus(preview_ui_addr, kFirstRequestId, &cancel); EXPECT_FALSE(cancel); cancel = false; preview_ui->GetCurrentPrintPreviewStatus(preview_ui_addr, kSecondRequestId, &cancel); EXPECT_TRUE(cancel); // Test with kSecondRequestId. preview_ui->OnPrintPreviewRequest(kSecondRequestId); cancel = false; preview_ui->GetCurrentPrintPreviewStatus(preview_ui_addr, kFirstRequestId, &cancel); EXPECT_TRUE(cancel); cancel = true; preview_ui->GetCurrentPrintPreviewStatus(preview_ui_addr, kSecondRequestId, &cancel); EXPECT_FALSE(cancel); }
Print Preview: Fixing more tests that were failing on official builds only.
Print Preview: Fixing more tests that were failing on official builds only. BUG=none TEST=unit_tests --gtest_filter=PrintPreviewUIUnitTest.* should pass on official builds Review URL: http://codereview.chromium.org/9127007 git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@116747 0039d316-1c4b-4281-b951-d872f2087c98
C++
bsd-3-clause
M4sse/chromium.src,robclark/chromium,Pluto-tv/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,pozdnyakov/chromium-crosswalk,dushu1203/chromium.src,axinging/chromium-crosswalk,dushu1203/chromium.src,hgl888/chromium-crosswalk,rogerwang/chromium,Fireblend/chromium-crosswalk,dednal/chromium.src,mohamed--abdel-maksoud/chromium.src,dednal/chromium.src,mohamed--abdel-maksoud/chromium.src,Jonekee/chromium.src,fujunwei/chromium-crosswalk,dushu1203/chromium.src,Fireblend/chromium-crosswalk,dushu1203/chromium.src,keishi/chromium,dushu1203/chromium.src,anirudhSK/chromium,dednal/chromium.src,chuan9/chromium-crosswalk,jaruba/chromium.src,keishi/chromium,chuan9/chromium-crosswalk,rogerwang/chromium,markYoungH/chromium.src,mogoweb/chromium-crosswalk,rogerwang/chromium,keishi/chromium,fujunwei/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,markYoungH/chromium.src,anirudhSK/chromium,Pluto-tv/chromium-crosswalk,fujunwei/chromium-crosswalk,timopulkkinen/BubbleFish,ltilve/chromium,nacl-webkit/chrome_deps,ltilve/chromium,nacl-webkit/chrome_deps,bright-sparks/chromium-spacewalk,jaruba/chromium.src,dednal/chromium.src,mogoweb/chromium-crosswalk,nacl-webkit/chrome_deps,patrickm/chromium.src,anirudhSK/chromium,anirudhSK/chromium,M4sse/chromium.src,dushu1203/chromium.src,bright-sparks/chromium-spacewalk,Jonekee/chromium.src,robclark/chromium,mogoweb/chromium-crosswalk,Fireblend/chromium-crosswalk,ChromiumWebApps/chromium,pozdnyakov/chromium-crosswalk,rogerwang/chromium,pozdnyakov/chromium-crosswalk,mogoweb/chromium-crosswalk,ChromiumWebApps/chromium,hgl888/chromium-crosswalk-efl,rogerwang/chromium,jaruba/chromium.src,Jonekee/chromium.src,junmin-zhu/chromium-rivertrail,Just-D/chromium-1,anirudhSK/chromium,littlstar/chromium.src,markYoungH/chromium.src,anirudhSK/chromium,bright-sparks/chromium-spacewalk,rogerwang/chromium,jaruba/chromium.src,junmin-zhu/chromium-rivertrail,ondra-novak/chromium.src,hgl888/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,Fireblend/chromium-crosswalk,fujunwei/chromium-crosswalk,Just-D/chromium-1,bright-sparks/chromium-spacewalk,hujiajie/pa-chromium,Jonekee/chromium.src,pozdnyakov/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,Chilledheart/chromium,hgl888/chromium-crosswalk-efl,M4sse/chromium.src,markYoungH/chromium.src,PeterWangIntel/chromium-crosswalk,jaruba/chromium.src,dushu1203/chromium.src,hgl888/chromium-crosswalk,timopulkkinen/BubbleFish,junmin-zhu/chromium-rivertrail,PeterWangIntel/chromium-crosswalk,krieger-od/nwjs_chromium.src,robclark/chromium,junmin-zhu/chromium-rivertrail,Just-D/chromium-1,hgl888/chromium-crosswalk-efl,Just-D/chromium-1,keishi/chromium,krieger-od/nwjs_chromium.src,hgl888/chromium-crosswalk,Jonekee/chromium.src,krieger-od/nwjs_chromium.src,PeterWangIntel/chromium-crosswalk,Chilledheart/chromium,crosswalk-project/chromium-crosswalk-efl,TheTypoMaster/chromium-crosswalk,axinging/chromium-crosswalk,hujiajie/pa-chromium,bright-sparks/chromium-spacewalk,keishi/chromium,crosswalk-project/chromium-crosswalk-efl,ltilve/chromium,axinging/chromium-crosswalk,ChromiumWebApps/chromium,fujunwei/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,pozdnyakov/chromium-crosswalk,Just-D/chromium-1,Fireblend/chromium-crosswalk,ondra-novak/chromium.src,M4sse/chromium.src,dushu1203/chromium.src,Fireblend/chromium-crosswalk,junmin-zhu/chromium-rivertrail,patrickm/chromium.src,ltilve/chromium,hgl888/chromium-crosswalk,ChromiumWebApps/chromium,mohamed--abdel-maksoud/chromium.src,axinging/chromium-crosswalk,axinging/chromium-crosswalk,Jonekee/chromium.src,robclark/chromium,fujunwei/chromium-crosswalk,mogoweb/chromium-crosswalk,markYoungH/chromium.src,patrickm/chromium.src,zcbenz/cefode-chromium,littlstar/chromium.src,junmin-zhu/chromium-rivertrail,mohamed--abdel-maksoud/chromium.src,ChromiumWebApps/chromium,M4sse/chromium.src,hgl888/chromium-crosswalk-efl,timopulkkinen/BubbleFish,nacl-webkit/chrome_deps,zcbenz/cefode-chromium,ChromiumWebApps/chromium,axinging/chromium-crosswalk,hujiajie/pa-chromium,dushu1203/chromium.src,chuan9/chromium-crosswalk,ondra-novak/chromium.src,zcbenz/cefode-chromium,ltilve/chromium,littlstar/chromium.src,keishi/chromium,ondra-novak/chromium.src,ondra-novak/chromium.src,junmin-zhu/chromium-rivertrail,crosswalk-project/chromium-crosswalk-efl,patrickm/chromium.src,markYoungH/chromium.src,jaruba/chromium.src,anirudhSK/chromium,nacl-webkit/chrome_deps,bright-sparks/chromium-spacewalk,pozdnyakov/chromium-crosswalk,Jonekee/chromium.src,robclark/chromium,fujunwei/chromium-crosswalk,ChromiumWebApps/chromium,TheTypoMaster/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,krieger-od/nwjs_chromium.src,M4sse/chromium.src,markYoungH/chromium.src,robclark/chromium,patrickm/chromium.src,littlstar/chromium.src,rogerwang/chromium,littlstar/chromium.src,Pluto-tv/chromium-crosswalk,pozdnyakov/chromium-crosswalk,rogerwang/chromium,ondra-novak/chromium.src,ChromiumWebApps/chromium,ChromiumWebApps/chromium,hujiajie/pa-chromium,zcbenz/cefode-chromium,nacl-webkit/chrome_deps,anirudhSK/chromium,axinging/chromium-crosswalk,hgl888/chromium-crosswalk-efl,keishi/chromium,Pluto-tv/chromium-crosswalk,krieger-od/nwjs_chromium.src,Pluto-tv/chromium-crosswalk,Just-D/chromium-1,axinging/chromium-crosswalk,rogerwang/chromium,robclark/chromium,bright-sparks/chromium-spacewalk,junmin-zhu/chromium-rivertrail,TheTypoMaster/chromium-crosswalk,zcbenz/cefode-chromium,hujiajie/pa-chromium,krieger-od/nwjs_chromium.src,bright-sparks/chromium-spacewalk,ltilve/chromium,keishi/chromium,Just-D/chromium-1,TheTypoMaster/chromium-crosswalk,zcbenz/cefode-chromium,Chilledheart/chromium,Chilledheart/chromium,jaruba/chromium.src,fujunwei/chromium-crosswalk,markYoungH/chromium.src,Fireblend/chromium-crosswalk,junmin-zhu/chromium-rivertrail,junmin-zhu/chromium-rivertrail,keishi/chromium,chuan9/chromium-crosswalk,krieger-od/nwjs_chromium.src,patrickm/chromium.src,hgl888/chromium-crosswalk-efl,M4sse/chromium.src,axinging/chromium-crosswalk,chuan9/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,patrickm/chromium.src,PeterWangIntel/chromium-crosswalk,hgl888/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,zcbenz/cefode-chromium,robclark/chromium,mohamed--abdel-maksoud/chromium.src,M4sse/chromium.src,TheTypoMaster/chromium-crosswalk,chuan9/chromium-crosswalk,mogoweb/chromium-crosswalk,nacl-webkit/chrome_deps,krieger-od/nwjs_chromium.src,mogoweb/chromium-crosswalk,hgl888/chromium-crosswalk-efl,timopulkkinen/BubbleFish,anirudhSK/chromium,dushu1203/chromium.src,crosswalk-project/chromium-crosswalk-efl,keishi/chromium,hujiajie/pa-chromium,Pluto-tv/chromium-crosswalk,ltilve/chromium,zcbenz/cefode-chromium,dednal/chromium.src,jaruba/chromium.src,hgl888/chromium-crosswalk-efl,hgl888/chromium-crosswalk-efl,axinging/chromium-crosswalk,hgl888/chromium-crosswalk,jaruba/chromium.src,crosswalk-project/chromium-crosswalk-efl,ondra-novak/chromium.src,dednal/chromium.src,timopulkkinen/BubbleFish,Pluto-tv/chromium-crosswalk,Jonekee/chromium.src,Chilledheart/chromium,rogerwang/chromium,ltilve/chromium,krieger-od/nwjs_chromium.src,hujiajie/pa-chromium,dednal/chromium.src,Chilledheart/chromium,junmin-zhu/chromium-rivertrail,fujunwei/chromium-crosswalk,robclark/chromium,TheTypoMaster/chromium-crosswalk,mogoweb/chromium-crosswalk,dushu1203/chromium.src,timopulkkinen/BubbleFish,dednal/chromium.src,Just-D/chromium-1,krieger-od/nwjs_chromium.src,zcbenz/cefode-chromium,ondra-novak/chromium.src,Pluto-tv/chromium-crosswalk,timopulkkinen/BubbleFish,dednal/chromium.src,ChromiumWebApps/chromium,hujiajie/pa-chromium,timopulkkinen/BubbleFish,dednal/chromium.src,mogoweb/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,pozdnyakov/chromium-crosswalk,nacl-webkit/chrome_deps,ChromiumWebApps/chromium,mohamed--abdel-maksoud/chromium.src,Chilledheart/chromium,Jonekee/chromium.src,PeterWangIntel/chromium-crosswalk,hgl888/chromium-crosswalk-efl,ChromiumWebApps/chromium,M4sse/chromium.src,keishi/chromium,littlstar/chromium.src,hgl888/chromium-crosswalk,Jonekee/chromium.src,markYoungH/chromium.src,ondra-novak/chromium.src,TheTypoMaster/chromium-crosswalk,krieger-od/nwjs_chromium.src,timopulkkinen/BubbleFish,anirudhSK/chromium,zcbenz/cefode-chromium,hujiajie/pa-chromium,mohamed--abdel-maksoud/chromium.src,crosswalk-project/chromium-crosswalk-efl,timopulkkinen/BubbleFish,littlstar/chromium.src,crosswalk-project/chromium-crosswalk-efl,PeterWangIntel/chromium-crosswalk,littlstar/chromium.src,jaruba/chromium.src,markYoungH/chromium.src,nacl-webkit/chrome_deps,bright-sparks/chromium-spacewalk,M4sse/chromium.src,pozdnyakov/chromium-crosswalk,hgl888/chromium-crosswalk,chuan9/chromium-crosswalk,jaruba/chromium.src,chuan9/chromium-crosswalk,zcbenz/cefode-chromium,anirudhSK/chromium,Chilledheart/chromium,anirudhSK/chromium,Chilledheart/chromium,Jonekee/chromium.src,hujiajie/pa-chromium,pozdnyakov/chromium-crosswalk,Just-D/chromium-1,TheTypoMaster/chromium-crosswalk,ltilve/chromium,Fireblend/chromium-crosswalk,patrickm/chromium.src,dednal/chromium.src,timopulkkinen/BubbleFish,pozdnyakov/chromium-crosswalk,Pluto-tv/chromium-crosswalk,axinging/chromium-crosswalk,M4sse/chromium.src,Fireblend/chromium-crosswalk,nacl-webkit/chrome_deps,chuan9/chromium-crosswalk,robclark/chromium,hujiajie/pa-chromium,markYoungH/chromium.src,patrickm/chromium.src,mogoweb/chromium-crosswalk,nacl-webkit/chrome_deps
f9e3dde240ede48387fe1ad5dc8ef7a51a2446b7
remoting/client/audio_player_unittest.cc
remoting/client/audio_player_unittest.cc
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "remoting/client/audio_player.h" #include "base/memory/scoped_ptr.h" #include "remoting/client/audio_player.h" #include "testing/gtest/include/gtest/gtest.h" namespace { const int kAudioSamplesPerFrame = 25; const int kAudioSampleBytes = 4; const int kAudioFrameBytes = kAudioSamplesPerFrame * kAudioSampleBytes; const int kPaddingBytes = 16; // TODO(garykac): Generate random audio data in the tests rather than having // a single constant value. const uint8 kDefaultBufferData = 0x5A; const uint8 kDummyAudioData = 0x8B; } // namespace namespace remoting { class FakeAudioPlayer : public AudioPlayer { public: FakeAudioPlayer() {}; bool ResetAudioPlayer(AudioPacket::SamplingRate) { return true; }; uint32 GetSamplesPerFrame() { return kAudioSamplesPerFrame; }; }; class AudioPlayerTest : public ::testing::Test { protected: virtual void SetUp() { audio_.reset(new FakeAudioPlayer()); buffer_.reset(new char[kAudioFrameBytes + kPaddingBytes]); } virtual void TearDown() {} void ConsumeAudioFrame() { uint8* buffer = reinterpret_cast<uint8*>(buffer_.get()); memset(buffer, kDefaultBufferData, kAudioFrameBytes + kPaddingBytes); AudioPlayer::AudioPlayerCallback(reinterpret_cast<void*>(buffer_.get()), kAudioFrameBytes, reinterpret_cast<void*>(audio_.get())); // Verify we haven't written beyond the end of the buffer. for (int i = 0; i < kPaddingBytes; i++) ASSERT_EQ(kDefaultBufferData, *(buffer + kAudioFrameBytes + i)); } // Check that the first |num_bytes| bytes are filled with audio data and // the rest of the buffer is zero-filled. void CheckAudioFrameBytes(int num_bytes) { uint8* buffer = reinterpret_cast<uint8*>(buffer_.get()); int i = 0; for (; i < num_bytes; i++) { ASSERT_EQ(kDummyAudioData, *(buffer + i)); } // Rest of audio frame must be filled with '0's. for (; i < kAudioFrameBytes; i++) { ASSERT_EQ(0, *(buffer + i)); } } void SetQueuedSamples(int num_samples) { audio_->queued_samples_ = num_samples; } int GetNumQueuedSamples() { return audio_->queued_samples_; } int GetNumQueuedPackets() { return static_cast<int>(audio_->queued_packets_.size()); } int GetBytesConsumed() { return static_cast<int>(audio_->bytes_consumed_); } scoped_ptr<AudioPlayer> audio_; scoped_array<char> buffer_; }; scoped_ptr<AudioPacket> CreatePacketWithSamplingRate( AudioPacket::SamplingRate rate, int samples) { scoped_ptr<AudioPacket> packet(new AudioPacket()); packet->set_encoding(AudioPacket::ENCODING_RAW); packet->set_sampling_rate(rate); packet->set_bytes_per_sample(AudioPacket::BYTES_PER_SAMPLE_2); packet->set_channels(AudioPacket::CHANNELS_STEREO); // The data must be a multiple of 4 bytes (channels x bytes_per_sample). std::string data; data.resize(samples * kAudioSampleBytes, kDummyAudioData); packet->add_data(data); return packet.Pass(); } scoped_ptr<AudioPacket> CreatePacket44100Hz(int samples) { return CreatePacketWithSamplingRate(AudioPacket::SAMPLING_RATE_44100, samples); } scoped_ptr<AudioPacket> CreatePacket48000Hz(int samples) { return CreatePacketWithSamplingRate(AudioPacket::SAMPLING_RATE_48000, samples); } TEST_F(AudioPlayerTest, Init) { ASSERT_EQ(0, GetNumQueuedPackets()); scoped_ptr<AudioPacket> packet(CreatePacket44100Hz(10)); audio_->ProcessAudioPacket(packet.Pass()); ASSERT_EQ(1, GetNumQueuedPackets()); } TEST_F(AudioPlayerTest, MultipleSamples) { scoped_ptr<AudioPacket> packet1(CreatePacket44100Hz(10)); audio_->ProcessAudioPacket(packet1.Pass()); ASSERT_EQ(10, GetNumQueuedSamples()); ASSERT_EQ(1, GetNumQueuedPackets()); scoped_ptr<AudioPacket> packet2(CreatePacket44100Hz(20)); audio_->ProcessAudioPacket(packet2.Pass()); ASSERT_EQ(30, GetNumQueuedSamples()); ASSERT_EQ(2, GetNumQueuedPackets()); } TEST_F(AudioPlayerTest, ChangeSampleRate) { scoped_ptr<AudioPacket> packet1(CreatePacket44100Hz(10)); audio_->ProcessAudioPacket(packet1.Pass()); ASSERT_EQ(10, GetNumQueuedSamples()); ASSERT_EQ(1, GetNumQueuedPackets()); // New packet with different sampling rate causes previous samples to // be removed. scoped_ptr<AudioPacket> packet2(CreatePacket48000Hz(20)); audio_->ProcessAudioPacket(packet2.Pass()); ASSERT_EQ(20, GetNumQueuedSamples()); ASSERT_EQ(1, GetNumQueuedPackets()); } TEST_F(AudioPlayerTest, ExceedLatency) { scoped_ptr<AudioPacket> packet1(CreatePacket44100Hz(10)); audio_->ProcessAudioPacket(packet1.Pass()); ASSERT_EQ(10, GetNumQueuedSamples()); ASSERT_EQ(1, GetNumQueuedPackets()); // Fake lots of queued samples. SetQueuedSamples(20000); // Previous sample should have been deleted because of latency (too many // unprocessed samples). scoped_ptr<AudioPacket> packet2(CreatePacket44100Hz(20)); audio_->ProcessAudioPacket(packet2.Pass()); ASSERT_EQ(20, GetNumQueuedSamples()); ASSERT_EQ(1, GetNumQueuedPackets()); } // Incoming packets: 100 // Consume: 25 (w/ 75 remaining, offset 25 into packet) TEST_F(AudioPlayerTest, ConsumePartialPacket) { int total_samples = 0; int bytes_consumed = 0; // Process 100 samples. int packet1_samples = 100; scoped_ptr<AudioPacket> packet(CreatePacket44100Hz(packet1_samples)); total_samples += packet1_samples; audio_->ProcessAudioPacket(packet.Pass()); ASSERT_EQ(total_samples, GetNumQueuedSamples()); ASSERT_EQ(1, GetNumQueuedPackets()); ASSERT_EQ(bytes_consumed, GetBytesConsumed()); // Consume one frame (=25) of samples. ConsumeAudioFrame(); total_samples -= kAudioSamplesPerFrame; bytes_consumed += kAudioFrameBytes; ASSERT_EQ(total_samples, GetNumQueuedSamples()); ASSERT_EQ(1, GetNumQueuedPackets()); ASSERT_EQ(bytes_consumed, GetBytesConsumed()); CheckAudioFrameBytes(kAudioFrameBytes); // Remaining samples. ASSERT_EQ(75, total_samples); ASSERT_EQ(25 * kAudioSampleBytes, bytes_consumed); } // Incoming packets: 20, 70 // Consume: 25, 25 (w/ 40 remaining, offset 30 into packet) TEST_F(AudioPlayerTest, ConsumeAcrossPackets) { int total_samples = 0; int bytes_consumed = 0; // Packet 1. int packet1_samples = 20; scoped_ptr<AudioPacket> packet1(CreatePacket44100Hz(packet1_samples)); total_samples += packet1_samples; audio_->ProcessAudioPacket(packet1.Pass()); ASSERT_EQ(total_samples, GetNumQueuedSamples()); // Packet 2. int packet2_samples = 70; scoped_ptr<AudioPacket> packet2(CreatePacket44100Hz(packet2_samples)); total_samples += packet2_samples; audio_->ProcessAudioPacket(packet2.Pass()); ASSERT_EQ(total_samples, GetNumQueuedSamples()); ASSERT_EQ(bytes_consumed, GetBytesConsumed()); // Consume 1st frame of 25 samples. // This will consume the entire 1st packet. ConsumeAudioFrame(); total_samples -= kAudioSamplesPerFrame; bytes_consumed += kAudioFrameBytes - (packet1_samples * kAudioSampleBytes); ASSERT_EQ(total_samples, GetNumQueuedSamples()); ASSERT_EQ(1, GetNumQueuedPackets()); ASSERT_EQ(bytes_consumed, GetBytesConsumed()); CheckAudioFrameBytes(kAudioFrameBytes); // Consume 2nd frame of 25 samples. ConsumeAudioFrame(); total_samples -= kAudioSamplesPerFrame; bytes_consumed += kAudioFrameBytes; ASSERT_EQ(total_samples, GetNumQueuedSamples()); ASSERT_EQ(1, GetNumQueuedPackets()); ASSERT_EQ(bytes_consumed, GetBytesConsumed()); CheckAudioFrameBytes(kAudioFrameBytes); // Remaining samples. ASSERT_EQ(40, total_samples); ASSERT_EQ(30 * kAudioSampleBytes, bytes_consumed); } // Incoming packets: 50, 30 // Consume: 25, 25, 25 (w/ 5 remaining, offset 25 into packet) TEST_F(AudioPlayerTest, ConsumeEntirePacket) { int total_samples = 0; int bytes_consumed = 0; // Packet 1. int packet1_samples = 50; scoped_ptr<AudioPacket> packet1(CreatePacket44100Hz(packet1_samples)); total_samples += packet1_samples; audio_->ProcessAudioPacket(packet1.Pass()); ASSERT_EQ(total_samples, GetNumQueuedSamples()); ASSERT_EQ(bytes_consumed, GetBytesConsumed()); // Packet 2. int packet2_samples = 30; scoped_ptr<AudioPacket> packet2(CreatePacket44100Hz(packet2_samples)); total_samples += packet2_samples; audio_->ProcessAudioPacket(packet2.Pass()); ASSERT_EQ(total_samples, GetNumQueuedSamples()); ASSERT_EQ(bytes_consumed, GetBytesConsumed()); // Consume 1st frame of 25 samples. ConsumeAudioFrame(); total_samples -= kAudioSamplesPerFrame; bytes_consumed += kAudioFrameBytes; ASSERT_EQ(total_samples, GetNumQueuedSamples()); ASSERT_EQ(2, GetNumQueuedPackets()); ASSERT_EQ(bytes_consumed, GetBytesConsumed()); CheckAudioFrameBytes(kAudioFrameBytes); // Consume 2nd frame of 25 samples. // This will consume the entire first packet (exactly), but the entry for // this packet will stick around (empty) until the next audio chunk is // consumed. ConsumeAudioFrame(); total_samples -= kAudioSamplesPerFrame; bytes_consumed += kAudioFrameBytes; ASSERT_EQ(total_samples, GetNumQueuedSamples()); ASSERT_EQ(2, GetNumQueuedPackets()); ASSERT_EQ(bytes_consumed, GetBytesConsumed()); CheckAudioFrameBytes(kAudioFrameBytes); // Consume 3rd frame of 25 samples. ConsumeAudioFrame(); total_samples -= kAudioSamplesPerFrame; bytes_consumed += kAudioFrameBytes - (packet1_samples * kAudioSampleBytes); ASSERT_EQ(total_samples, GetNumQueuedSamples()); ASSERT_EQ(1, GetNumQueuedPackets()); ASSERT_EQ(bytes_consumed, GetBytesConsumed()); CheckAudioFrameBytes(kAudioFrameBytes); // Remaining samples. ASSERT_EQ(5, total_samples); ASSERT_EQ(25 * kAudioSampleBytes, bytes_consumed); } // Incoming packets: <none> // Consume: 25 TEST_F(AudioPlayerTest, NoDataToConsume) { // Attempt to consume a frame of 25 samples. ConsumeAudioFrame(); ASSERT_EQ(0, GetNumQueuedSamples()); ASSERT_EQ(0, GetNumQueuedPackets()); ASSERT_EQ(0, GetBytesConsumed()); CheckAudioFrameBytes(0); } // Incoming packets: 10 // Consume: 25 TEST_F(AudioPlayerTest, NotEnoughDataToConsume) { int total_samples = 0; int bytes_consumed = 0; // Packet 1. int packet1_samples = 10; scoped_ptr<AudioPacket> packet1(CreatePacket44100Hz(packet1_samples)); total_samples += packet1_samples; audio_->ProcessAudioPacket(packet1.Pass()); ASSERT_EQ(total_samples, GetNumQueuedSamples()); ASSERT_EQ(bytes_consumed, GetBytesConsumed()); // Attempt to consume a frame of 25 samples. ConsumeAudioFrame(); ASSERT_EQ(0, GetNumQueuedSamples()); ASSERT_EQ(0, GetNumQueuedPackets()); ASSERT_EQ(0, GetBytesConsumed()); CheckAudioFrameBytes(packet1_samples * kAudioSampleBytes); } } // namespace remoting
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "remoting/client/audio_player.h" #include "base/compiler_specific.h" #include "base/memory/scoped_ptr.h" #include "testing/gtest/include/gtest/gtest.h" namespace { const int kAudioSamplesPerFrame = 25; const int kAudioSampleBytes = 4; const int kAudioFrameBytes = kAudioSamplesPerFrame * kAudioSampleBytes; const int kPaddingBytes = 16; // TODO(garykac): Generate random audio data in the tests rather than having // a single constant value. const uint8 kDefaultBufferData = 0x5A; const uint8 kDummyAudioData = 0x8B; } // namespace namespace remoting { class FakeAudioPlayer : public AudioPlayer { public: FakeAudioPlayer() {} bool ResetAudioPlayer(AudioPacket::SamplingRate) OVERRIDE { return true; }; uint32 GetSamplesPerFrame() OVERRIDE { return kAudioSamplesPerFrame; }; }; class AudioPlayerTest : public ::testing::Test { protected: virtual void SetUp() { audio_.reset(new FakeAudioPlayer()); buffer_.reset(new char[kAudioFrameBytes + kPaddingBytes]); } virtual void TearDown() { // Drain the samples from |audio_|. while (GetNumQueuedPackets() > 0) { ConsumeAudioFrame(); } } void ConsumeAudioFrame() { uint8* buffer = reinterpret_cast<uint8*>(buffer_.get()); memset(buffer, kDefaultBufferData, kAudioFrameBytes + kPaddingBytes); AudioPlayer::AudioPlayerCallback(reinterpret_cast<void*>(buffer_.get()), kAudioFrameBytes, reinterpret_cast<void*>(audio_.get())); // Verify we haven't written beyond the end of the buffer. for (int i = 0; i < kPaddingBytes; i++) ASSERT_EQ(kDefaultBufferData, *(buffer + kAudioFrameBytes + i)); } // Check that the first |num_bytes| bytes are filled with audio data and // the rest of the buffer is zero-filled. void CheckAudioFrameBytes(int num_bytes) { uint8* buffer = reinterpret_cast<uint8*>(buffer_.get()); int i = 0; for (; i < num_bytes; i++) { ASSERT_EQ(kDummyAudioData, *(buffer + i)); } // Rest of audio frame must be filled with '0's. for (; i < kAudioFrameBytes; i++) { ASSERT_EQ(0, *(buffer + i)); } } void SetQueuedSamples(int num_samples) { audio_->queued_samples_ = num_samples; } int GetNumQueuedSamples() { return audio_->queued_samples_; } int GetNumQueuedPackets() { return static_cast<int>(audio_->queued_packets_.size()); } int GetBytesConsumed() { return static_cast<int>(audio_->bytes_consumed_); } scoped_ptr<AudioPlayer> audio_; scoped_array<char> buffer_; }; scoped_ptr<AudioPacket> CreatePacketWithSamplingRate( AudioPacket::SamplingRate rate, int samples) { scoped_ptr<AudioPacket> packet(new AudioPacket()); packet->set_encoding(AudioPacket::ENCODING_RAW); packet->set_sampling_rate(rate); packet->set_bytes_per_sample(AudioPacket::BYTES_PER_SAMPLE_2); packet->set_channels(AudioPacket::CHANNELS_STEREO); // The data must be a multiple of 4 bytes (channels x bytes_per_sample). std::string data; data.resize(samples * kAudioSampleBytes, kDummyAudioData); packet->add_data(data); return packet.Pass(); } scoped_ptr<AudioPacket> CreatePacket44100Hz(int samples) { return CreatePacketWithSamplingRate(AudioPacket::SAMPLING_RATE_44100, samples); } scoped_ptr<AudioPacket> CreatePacket48000Hz(int samples) { return CreatePacketWithSamplingRate(AudioPacket::SAMPLING_RATE_48000, samples); } TEST_F(AudioPlayerTest, Init) { ASSERT_EQ(0, GetNumQueuedPackets()); scoped_ptr<AudioPacket> packet(CreatePacket44100Hz(10)); audio_->ProcessAudioPacket(packet.Pass()); ASSERT_EQ(1, GetNumQueuedPackets()); } TEST_F(AudioPlayerTest, MultipleSamples) { scoped_ptr<AudioPacket> packet1(CreatePacket44100Hz(10)); audio_->ProcessAudioPacket(packet1.Pass()); ASSERT_EQ(10, GetNumQueuedSamples()); ASSERT_EQ(1, GetNumQueuedPackets()); scoped_ptr<AudioPacket> packet2(CreatePacket44100Hz(20)); audio_->ProcessAudioPacket(packet2.Pass()); ASSERT_EQ(30, GetNumQueuedSamples()); ASSERT_EQ(2, GetNumQueuedPackets()); } TEST_F(AudioPlayerTest, ChangeSampleRate) { scoped_ptr<AudioPacket> packet1(CreatePacket44100Hz(10)); audio_->ProcessAudioPacket(packet1.Pass()); ASSERT_EQ(10, GetNumQueuedSamples()); ASSERT_EQ(1, GetNumQueuedPackets()); // New packet with different sampling rate causes previous samples to // be removed. scoped_ptr<AudioPacket> packet2(CreatePacket48000Hz(20)); audio_->ProcessAudioPacket(packet2.Pass()); ASSERT_EQ(20, GetNumQueuedSamples()); ASSERT_EQ(1, GetNumQueuedPackets()); } TEST_F(AudioPlayerTest, ExceedLatency) { scoped_ptr<AudioPacket> packet1(CreatePacket44100Hz(10)); audio_->ProcessAudioPacket(packet1.Pass()); ASSERT_EQ(10, GetNumQueuedSamples()); ASSERT_EQ(1, GetNumQueuedPackets()); // Fake lots of queued samples. SetQueuedSamples(20000); // Previous sample should have been deleted because of latency (too many // unprocessed samples). scoped_ptr<AudioPacket> packet2(CreatePacket44100Hz(20)); audio_->ProcessAudioPacket(packet2.Pass()); ASSERT_EQ(20, GetNumQueuedSamples()); ASSERT_EQ(1, GetNumQueuedPackets()); } // Incoming packets: 100 // Consume: 25 (w/ 75 remaining, offset 25 into packet) TEST_F(AudioPlayerTest, ConsumePartialPacket) { int total_samples = 0; int bytes_consumed = 0; // Process 100 samples. int packet1_samples = 100; scoped_ptr<AudioPacket> packet(CreatePacket44100Hz(packet1_samples)); total_samples += packet1_samples; audio_->ProcessAudioPacket(packet.Pass()); ASSERT_EQ(total_samples, GetNumQueuedSamples()); ASSERT_EQ(1, GetNumQueuedPackets()); ASSERT_EQ(bytes_consumed, GetBytesConsumed()); // Consume one frame (=25) of samples. ConsumeAudioFrame(); total_samples -= kAudioSamplesPerFrame; bytes_consumed += kAudioFrameBytes; ASSERT_EQ(total_samples, GetNumQueuedSamples()); ASSERT_EQ(1, GetNumQueuedPackets()); ASSERT_EQ(bytes_consumed, GetBytesConsumed()); CheckAudioFrameBytes(kAudioFrameBytes); // Remaining samples. ASSERT_EQ(75, total_samples); ASSERT_EQ(25 * kAudioSampleBytes, bytes_consumed); } // Incoming packets: 20, 70 // Consume: 25, 25 (w/ 40 remaining, offset 30 into packet) TEST_F(AudioPlayerTest, ConsumeAcrossPackets) { int total_samples = 0; int bytes_consumed = 0; // Packet 1. int packet1_samples = 20; scoped_ptr<AudioPacket> packet1(CreatePacket44100Hz(packet1_samples)); total_samples += packet1_samples; audio_->ProcessAudioPacket(packet1.Pass()); ASSERT_EQ(total_samples, GetNumQueuedSamples()); // Packet 2. int packet2_samples = 70; scoped_ptr<AudioPacket> packet2(CreatePacket44100Hz(packet2_samples)); total_samples += packet2_samples; audio_->ProcessAudioPacket(packet2.Pass()); ASSERT_EQ(total_samples, GetNumQueuedSamples()); ASSERT_EQ(bytes_consumed, GetBytesConsumed()); // Consume 1st frame of 25 samples. // This will consume the entire 1st packet. ConsumeAudioFrame(); total_samples -= kAudioSamplesPerFrame; bytes_consumed += kAudioFrameBytes - (packet1_samples * kAudioSampleBytes); ASSERT_EQ(total_samples, GetNumQueuedSamples()); ASSERT_EQ(1, GetNumQueuedPackets()); ASSERT_EQ(bytes_consumed, GetBytesConsumed()); CheckAudioFrameBytes(kAudioFrameBytes); // Consume 2nd frame of 25 samples. ConsumeAudioFrame(); total_samples -= kAudioSamplesPerFrame; bytes_consumed += kAudioFrameBytes; ASSERT_EQ(total_samples, GetNumQueuedSamples()); ASSERT_EQ(1, GetNumQueuedPackets()); ASSERT_EQ(bytes_consumed, GetBytesConsumed()); CheckAudioFrameBytes(kAudioFrameBytes); // Remaining samples. ASSERT_EQ(40, total_samples); ASSERT_EQ(30 * kAudioSampleBytes, bytes_consumed); } // Incoming packets: 50, 30 // Consume: 25, 25, 25 (w/ 5 remaining, offset 25 into packet) TEST_F(AudioPlayerTest, ConsumeEntirePacket) { int total_samples = 0; int bytes_consumed = 0; // Packet 1. int packet1_samples = 50; scoped_ptr<AudioPacket> packet1(CreatePacket44100Hz(packet1_samples)); total_samples += packet1_samples; audio_->ProcessAudioPacket(packet1.Pass()); ASSERT_EQ(total_samples, GetNumQueuedSamples()); ASSERT_EQ(bytes_consumed, GetBytesConsumed()); // Packet 2. int packet2_samples = 30; scoped_ptr<AudioPacket> packet2(CreatePacket44100Hz(packet2_samples)); total_samples += packet2_samples; audio_->ProcessAudioPacket(packet2.Pass()); ASSERT_EQ(total_samples, GetNumQueuedSamples()); ASSERT_EQ(bytes_consumed, GetBytesConsumed()); // Consume 1st frame of 25 samples. ConsumeAudioFrame(); total_samples -= kAudioSamplesPerFrame; bytes_consumed += kAudioFrameBytes; ASSERT_EQ(total_samples, GetNumQueuedSamples()); ASSERT_EQ(2, GetNumQueuedPackets()); ASSERT_EQ(bytes_consumed, GetBytesConsumed()); CheckAudioFrameBytes(kAudioFrameBytes); // Consume 2nd frame of 25 samples. // This will consume the entire first packet (exactly), but the entry for // this packet will stick around (empty) until the next audio chunk is // consumed. ConsumeAudioFrame(); total_samples -= kAudioSamplesPerFrame; bytes_consumed += kAudioFrameBytes; ASSERT_EQ(total_samples, GetNumQueuedSamples()); ASSERT_EQ(2, GetNumQueuedPackets()); ASSERT_EQ(bytes_consumed, GetBytesConsumed()); CheckAudioFrameBytes(kAudioFrameBytes); // Consume 3rd frame of 25 samples. ConsumeAudioFrame(); total_samples -= kAudioSamplesPerFrame; bytes_consumed += kAudioFrameBytes - (packet1_samples * kAudioSampleBytes); ASSERT_EQ(total_samples, GetNumQueuedSamples()); ASSERT_EQ(1, GetNumQueuedPackets()); ASSERT_EQ(bytes_consumed, GetBytesConsumed()); CheckAudioFrameBytes(kAudioFrameBytes); // Remaining samples. ASSERT_EQ(5, total_samples); ASSERT_EQ(25 * kAudioSampleBytes, bytes_consumed); } // Incoming packets: <none> // Consume: 25 TEST_F(AudioPlayerTest, NoDataToConsume) { // Attempt to consume a frame of 25 samples. ConsumeAudioFrame(); ASSERT_EQ(0, GetNumQueuedSamples()); ASSERT_EQ(0, GetNumQueuedPackets()); ASSERT_EQ(0, GetBytesConsumed()); CheckAudioFrameBytes(0); } // Incoming packets: 10 // Consume: 25 TEST_F(AudioPlayerTest, NotEnoughDataToConsume) { int total_samples = 0; int bytes_consumed = 0; // Packet 1. int packet1_samples = 10; scoped_ptr<AudioPacket> packet1(CreatePacket44100Hz(packet1_samples)); total_samples += packet1_samples; audio_->ProcessAudioPacket(packet1.Pass()); ASSERT_EQ(total_samples, GetNumQueuedSamples()); ASSERT_EQ(bytes_consumed, GetBytesConsumed()); // Attempt to consume a frame of 25 samples. ConsumeAudioFrame(); ASSERT_EQ(0, GetNumQueuedSamples()); ASSERT_EQ(0, GetNumQueuedPackets()); ASSERT_EQ(0, GetBytesConsumed()); CheckAudioFrameBytes(packet1_samples * kAudioSampleBytes); } } // namespace remoting
Fix leak in remoting AudioPlayerTests.
Valgrind/Heapchecker: Fix leak in remoting AudioPlayerTests. BUG=154986 TBR=garykac,eugenis Review URL: https://codereview.chromium.org/11087042 git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@161039 0039d316-1c4b-4281-b951-d872f2087c98
C++
bsd-3-clause
zcbenz/cefode-chromium,Pluto-tv/chromium-crosswalk,markYoungH/chromium.src,Chilledheart/chromium,dushu1203/chromium.src,crosswalk-project/chromium-crosswalk-efl,axinging/chromium-crosswalk,timopulkkinen/BubbleFish,chuan9/chromium-crosswalk,mogoweb/chromium-crosswalk,zcbenz/cefode-chromium,ltilve/chromium,hgl888/chromium-crosswalk,fujunwei/chromium-crosswalk,jaruba/chromium.src,axinging/chromium-crosswalk,nacl-webkit/chrome_deps,dednal/chromium.src,patrickm/chromium.src,anirudhSK/chromium,markYoungH/chromium.src,mohamed--abdel-maksoud/chromium.src,fujunwei/chromium-crosswalk,littlstar/chromium.src,ChromiumWebApps/chromium,hgl888/chromium-crosswalk,Pluto-tv/chromium-crosswalk,hujiajie/pa-chromium,hujiajie/pa-chromium,hgl888/chromium-crosswalk-efl,fujunwei/chromium-crosswalk,chuan9/chromium-crosswalk,ondra-novak/chromium.src,nacl-webkit/chrome_deps,patrickm/chromium.src,mogoweb/chromium-crosswalk,ltilve/chromium,junmin-zhu/chromium-rivertrail,ondra-novak/chromium.src,hujiajie/pa-chromium,M4sse/chromium.src,krieger-od/nwjs_chromium.src,anirudhSK/chromium,Just-D/chromium-1,Jonekee/chromium.src,markYoungH/chromium.src,krieger-od/nwjs_chromium.src,PeterWangIntel/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,Fireblend/chromium-crosswalk,Jonekee/chromium.src,timopulkkinen/BubbleFish,TheTypoMaster/chromium-crosswalk,axinging/chromium-crosswalk,hgl888/chromium-crosswalk-efl,anirudhSK/chromium,Jonekee/chromium.src,anirudhSK/chromium,hgl888/chromium-crosswalk-efl,littlstar/chromium.src,nacl-webkit/chrome_deps,Jonekee/chromium.src,junmin-zhu/chromium-rivertrail,Pluto-tv/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,Just-D/chromium-1,patrickm/chromium.src,junmin-zhu/chromium-rivertrail,bright-sparks/chromium-spacewalk,ChromiumWebApps/chromium,crosswalk-project/chromium-crosswalk-efl,axinging/chromium-crosswalk,ChromiumWebApps/chromium,dushu1203/chromium.src,M4sse/chromium.src,TheTypoMaster/chromium-crosswalk,pozdnyakov/chromium-crosswalk,axinging/chromium-crosswalk,Fireblend/chromium-crosswalk,littlstar/chromium.src,mohamed--abdel-maksoud/chromium.src,crosswalk-project/chromium-crosswalk-efl,axinging/chromium-crosswalk,hgl888/chromium-crosswalk-efl,Jonekee/chromium.src,axinging/chromium-crosswalk,ondra-novak/chromium.src,zcbenz/cefode-chromium,dednal/chromium.src,crosswalk-project/chromium-crosswalk-efl,krieger-od/nwjs_chromium.src,patrickm/chromium.src,pozdnyakov/chromium-crosswalk,Jonekee/chromium.src,mogoweb/chromium-crosswalk,markYoungH/chromium.src,ltilve/chromium,PeterWangIntel/chromium-crosswalk,Fireblend/chromium-crosswalk,M4sse/chromium.src,littlstar/chromium.src,jaruba/chromium.src,PeterWangIntel/chromium-crosswalk,ChromiumWebApps/chromium,hujiajie/pa-chromium,crosswalk-project/chromium-crosswalk-efl,mohamed--abdel-maksoud/chromium.src,mohamed--abdel-maksoud/chromium.src,anirudhSK/chromium,Pluto-tv/chromium-crosswalk,axinging/chromium-crosswalk,hujiajie/pa-chromium,jaruba/chromium.src,ltilve/chromium,Just-D/chromium-1,hgl888/chromium-crosswalk-efl,zcbenz/cefode-chromium,bright-sparks/chromium-spacewalk,dednal/chromium.src,M4sse/chromium.src,krieger-od/nwjs_chromium.src,zcbenz/cefode-chromium,Pluto-tv/chromium-crosswalk,littlstar/chromium.src,patrickm/chromium.src,hgl888/chromium-crosswalk-efl,mohamed--abdel-maksoud/chromium.src,bright-sparks/chromium-spacewalk,Jonekee/chromium.src,TheTypoMaster/chromium-crosswalk,ChromiumWebApps/chromium,hgl888/chromium-crosswalk,Just-D/chromium-1,pozdnyakov/chromium-crosswalk,Chilledheart/chromium,Pluto-tv/chromium-crosswalk,Just-D/chromium-1,zcbenz/cefode-chromium,TheTypoMaster/chromium-crosswalk,anirudhSK/chromium,ondra-novak/chromium.src,mogoweb/chromium-crosswalk,timopulkkinen/BubbleFish,dednal/chromium.src,Pluto-tv/chromium-crosswalk,junmin-zhu/chromium-rivertrail,M4sse/chromium.src,bright-sparks/chromium-spacewalk,pozdnyakov/chromium-crosswalk,markYoungH/chromium.src,junmin-zhu/chromium-rivertrail,Pluto-tv/chromium-crosswalk,timopulkkinen/BubbleFish,Chilledheart/chromium,nacl-webkit/chrome_deps,ChromiumWebApps/chromium,ondra-novak/chromium.src,hgl888/chromium-crosswalk-efl,zcbenz/cefode-chromium,markYoungH/chromium.src,mogoweb/chromium-crosswalk,M4sse/chromium.src,timopulkkinen/BubbleFish,dushu1203/chromium.src,mohamed--abdel-maksoud/chromium.src,crosswalk-project/chromium-crosswalk-efl,zcbenz/cefode-chromium,fujunwei/chromium-crosswalk,hujiajie/pa-chromium,ChromiumWebApps/chromium,junmin-zhu/chromium-rivertrail,ltilve/chromium,junmin-zhu/chromium-rivertrail,mogoweb/chromium-crosswalk,pozdnyakov/chromium-crosswalk,markYoungH/chromium.src,ondra-novak/chromium.src,ChromiumWebApps/chromium,M4sse/chromium.src,littlstar/chromium.src,Fireblend/chromium-crosswalk,hgl888/chromium-crosswalk,zcbenz/cefode-chromium,hgl888/chromium-crosswalk,dushu1203/chromium.src,zcbenz/cefode-chromium,PeterWangIntel/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,markYoungH/chromium.src,Fireblend/chromium-crosswalk,fujunwei/chromium-crosswalk,krieger-od/nwjs_chromium.src,Jonekee/chromium.src,TheTypoMaster/chromium-crosswalk,ondra-novak/chromium.src,nacl-webkit/chrome_deps,Jonekee/chromium.src,markYoungH/chromium.src,patrickm/chromium.src,axinging/chromium-crosswalk,krieger-od/nwjs_chromium.src,ChromiumWebApps/chromium,dednal/chromium.src,Just-D/chromium-1,ondra-novak/chromium.src,Fireblend/chromium-crosswalk,jaruba/chromium.src,Chilledheart/chromium,krieger-od/nwjs_chromium.src,ltilve/chromium,Just-D/chromium-1,Fireblend/chromium-crosswalk,Fireblend/chromium-crosswalk,jaruba/chromium.src,anirudhSK/chromium,jaruba/chromium.src,mohamed--abdel-maksoud/chromium.src,Fireblend/chromium-crosswalk,pozdnyakov/chromium-crosswalk,krieger-od/nwjs_chromium.src,junmin-zhu/chromium-rivertrail,anirudhSK/chromium,chuan9/chromium-crosswalk,hgl888/chromium-crosswalk-efl,TheTypoMaster/chromium-crosswalk,hujiajie/pa-chromium,mohamed--abdel-maksoud/chromium.src,anirudhSK/chromium,pozdnyakov/chromium-crosswalk,junmin-zhu/chromium-rivertrail,pozdnyakov/chromium-crosswalk,nacl-webkit/chrome_deps,ltilve/chromium,timopulkkinen/BubbleFish,crosswalk-project/chromium-crosswalk-efl,bright-sparks/chromium-spacewalk,dushu1203/chromium.src,jaruba/chromium.src,hujiajie/pa-chromium,bright-sparks/chromium-spacewalk,ondra-novak/chromium.src,krieger-od/nwjs_chromium.src,anirudhSK/chromium,dednal/chromium.src,krieger-od/nwjs_chromium.src,mohamed--abdel-maksoud/chromium.src,crosswalk-project/chromium-crosswalk-efl,jaruba/chromium.src,nacl-webkit/chrome_deps,dushu1203/chromium.src,jaruba/chromium.src,dednal/chromium.src,Jonekee/chromium.src,PeterWangIntel/chromium-crosswalk,chuan9/chromium-crosswalk,Chilledheart/chromium,nacl-webkit/chrome_deps,krieger-od/nwjs_chromium.src,hgl888/chromium-crosswalk,hujiajie/pa-chromium,hgl888/chromium-crosswalk,anirudhSK/chromium,fujunwei/chromium-crosswalk,zcbenz/cefode-chromium,dednal/chromium.src,markYoungH/chromium.src,PeterWangIntel/chromium-crosswalk,Jonekee/chromium.src,bright-sparks/chromium-spacewalk,timopulkkinen/BubbleFish,pozdnyakov/chromium-crosswalk,hgl888/chromium-crosswalk-efl,mohamed--abdel-maksoud/chromium.src,mogoweb/chromium-crosswalk,fujunwei/chromium-crosswalk,chuan9/chromium-crosswalk,Chilledheart/chromium,jaruba/chromium.src,hgl888/chromium-crosswalk,M4sse/chromium.src,dushu1203/chromium.src,M4sse/chromium.src,jaruba/chromium.src,hujiajie/pa-chromium,bright-sparks/chromium-spacewalk,nacl-webkit/chrome_deps,dednal/chromium.src,timopulkkinen/BubbleFish,anirudhSK/chromium,timopulkkinen/BubbleFish,TheTypoMaster/chromium-crosswalk,hgl888/chromium-crosswalk,Just-D/chromium-1,axinging/chromium-crosswalk,dushu1203/chromium.src,mogoweb/chromium-crosswalk,dednal/chromium.src,fujunwei/chromium-crosswalk,mogoweb/chromium-crosswalk,M4sse/chromium.src,patrickm/chromium.src,mogoweb/chromium-crosswalk,fujunwei/chromium-crosswalk,chuan9/chromium-crosswalk,chuan9/chromium-crosswalk,Pluto-tv/chromium-crosswalk,dednal/chromium.src,Chilledheart/chromium,TheTypoMaster/chromium-crosswalk,nacl-webkit/chrome_deps,Chilledheart/chromium,PeterWangIntel/chromium-crosswalk,timopulkkinen/BubbleFish,bright-sparks/chromium-spacewalk,ChromiumWebApps/chromium,hgl888/chromium-crosswalk-efl,dushu1203/chromium.src,crosswalk-project/chromium-crosswalk-efl,dushu1203/chromium.src,junmin-zhu/chromium-rivertrail,pozdnyakov/chromium-crosswalk,nacl-webkit/chrome_deps,markYoungH/chromium.src,pozdnyakov/chromium-crosswalk,littlstar/chromium.src,Chilledheart/chromium,patrickm/chromium.src,ChromiumWebApps/chromium,PeterWangIntel/chromium-crosswalk,patrickm/chromium.src,dushu1203/chromium.src,ltilve/chromium,timopulkkinen/BubbleFish,Just-D/chromium-1,M4sse/chromium.src,chuan9/chromium-crosswalk,ltilve/chromium,axinging/chromium-crosswalk,chuan9/chromium-crosswalk,hujiajie/pa-chromium,littlstar/chromium.src,junmin-zhu/chromium-rivertrail,ChromiumWebApps/chromium
fa2e28dd4d9096f8d57cadd9a286d6e683664a98
contrib/other-builds/moses2/PhraseBased/Sentence.cpp
contrib/other-builds/moses2/PhraseBased/Sentence.cpp
/* * Sentence.cpp * * Created on: 14 Dec 2015 * Author: hieu */ #include <boost/property_tree/ptree.hpp> #include <boost/property_tree/xml_parser.hpp> #include "Sentence.h" #include "../System.h" #include "../parameters/AllOptions.h" #include "../pugixml.hpp" #include "../legacy/Util2.h" using namespace std; namespace Moses2 { Sentence *Sentence::CreateFromString(MemPool &pool, FactorCollection &vocab, const System &system, const std::string &str, long translationId) { Sentence *ret; if (system.options.input.xml_policy) { // xml ret = CreateFromStringXML(pool, vocab, system, str, translationId); } else { // no xml //cerr << "PB Sentence" << endl; std::vector<std::string> toks = Tokenize(str); size_t size = toks.size(); ret = new (pool.Allocate<Sentence>()) Sentence(translationId, pool, size); ret->PhraseImplTemplate<Word>::CreateFromString(vocab, system, toks, false); } //cerr << "REORDERING CONSTRAINTS:" << ret->GetReorderingConstraint() << endl; return ret; } Sentence *Sentence::CreateFromStringXML(MemPool &pool, FactorCollection &vocab, const System &system, const std::string &str, long translationId) { Sentence *ret; vector<XMLOption*> xmlOptions; pugi::xml_document doc; string str2 = "<xml>" + str + "</xml>"; pugi::xml_parse_result result = doc.load(str2.c_str(), pugi::parse_default | pugi::parse_comments); pugi::xml_node topNode = doc.child("xml"); std::vector<std::string> toks; XMLParse(system, 0, topNode, toks, xmlOptions); // debug /* for (size_t i = 0; i < xmlOptions.size(); ++i) { cerr << *xmlOptions[i] << endl; } */ // create words size_t size = toks.size(); ret = new (pool.Allocate<Sentence>()) Sentence(translationId, pool, size); ret->PhraseImplTemplate<Word>::CreateFromString(vocab, system, toks, false); // xml ret->Init(size, system.options.reordering.max_distortion); ReorderingConstraint &reorderingConstraint = ret->GetReorderingConstraint(); // set reordering walls, if "-monotone-at-punction" is set if (system.options.reordering.monotone_at_punct && ret->GetSize()) { reorderingConstraint.SetMonotoneAtPunctuation(*ret); } // set walls obtained from xml for(size_t i=0; i<xmlOptions.size(); i++) { const XMLOption &xmlOption = *xmlOptions[i]; if(xmlOption.nodeName == "wall") { UTIL_THROW_IF2(xmlOption.startPos >= ret->GetSize(), "wall is beyond the sentence"); // no buggy walls, please reorderingConstraint.SetWall(xmlOption.startPos - 1, true); } else if (xmlOption.nodeName == "zone") { reorderingConstraint.SetZone( xmlOption.startPos, xmlOption.startPos + xmlOption.phraseSize -1 ); } else { // default - forced translation. Add to class variable ret->GetXMLOptions().push_back(new XMLOption(xmlOption)); } } reorderingConstraint.FinalizeWalls(); // clean up for (size_t i = 0; i < xmlOptions.size(); ++i) { delete xmlOptions[i]; } return ret; } void Sentence::XMLParse( const System &system, size_t depth, const pugi::xml_node &parentNode, std::vector<std::string> &toks, vector<XMLOption*> &xmlOptions) { // pugixml for (pugi::xml_node childNode = parentNode.first_child(); childNode; childNode = childNode.next_sibling()) { string nodeName = childNode.name(); //cerr << depth << " nodeName=" << nodeName << endl; int startPos = toks.size(); string value = childNode.value(); if (!value.empty()) { //cerr << depth << "childNode text=" << value << endl; std::vector<std::string> subPhraseToks = Tokenize(value); for (size_t i = 0; i < subPhraseToks.size(); ++i) { toks.push_back(subPhraseToks[i]); } } if (!nodeName.empty()) { XMLOption *xmlOption = new XMLOption(); xmlOption->nodeName = nodeName; xmlOption->startPos = startPos; pugi::xml_attribute attr = childNode.attribute("translation"); if (!attr.empty()) { xmlOption->translation = attr.as_string(); } attr = childNode.attribute("prob"); if (!attr.empty()) { xmlOption->prob = attr.as_float(); } xmlOptions.push_back(xmlOption); // recursively call this function. For proper recursive trees XMLParse(system, depth + 1, childNode, toks, xmlOptions); size_t endPos = toks.size(); xmlOption->phraseSize = endPos - startPos; cerr << "xmlOptions="; xmlOption->Debug(cerr, system); cerr << endl; } } } } /* namespace Moses2 */
/* * Sentence.cpp * * Created on: 14 Dec 2015 * Author: hieu */ #include <boost/property_tree/ptree.hpp> #include <boost/property_tree/xml_parser.hpp> #include "Sentence.h" #include "../System.h" #include "../parameters/AllOptions.h" #include "../pugixml.hpp" #include "../legacy/Util2.h" using namespace std; namespace Moses2 { Sentence *Sentence::CreateFromString(MemPool &pool, FactorCollection &vocab, const System &system, const std::string &str, long translationId) { Sentence *ret; if (system.options.input.xml_policy) { // xml ret = CreateFromStringXML(pool, vocab, system, str, translationId); } else { // no xml //cerr << "PB Sentence" << endl; std::vector<std::string> toks = Tokenize(str); size_t size = toks.size(); ret = new (pool.Allocate<Sentence>()) Sentence(translationId, pool, size); ret->PhraseImplTemplate<Word>::CreateFromString(vocab, system, toks, false); } //cerr << "REORDERING CONSTRAINTS:" << ret->GetReorderingConstraint() << endl; return ret; } Sentence *Sentence::CreateFromStringXML(MemPool &pool, FactorCollection &vocab, const System &system, const std::string &str, long translationId) { Sentence *ret; vector<XMLOption*> xmlOptions; pugi::xml_document doc; string str2 = "<xml>" + str + "</xml>"; pugi::xml_parse_result result = doc.load(str2.c_str(), pugi::parse_default | pugi::parse_comments); pugi::xml_node topNode = doc.child("xml"); std::vector<std::string> toks; XMLParse(system, 0, topNode, toks, xmlOptions); // debug /* for (size_t i = 0; i < xmlOptions.size(); ++i) { cerr << *xmlOptions[i] << endl; } */ // create words size_t size = toks.size(); ret = new (pool.Allocate<Sentence>()) Sentence(translationId, pool, size); ret->PhraseImplTemplate<Word>::CreateFromString(vocab, system, toks, false); // xml ret->Init(size, system.options.reordering.max_distortion); ReorderingConstraint &reorderingConstraint = ret->GetReorderingConstraint(); // set reordering walls, if "-monotone-at-punction" is set if (system.options.reordering.monotone_at_punct && ret->GetSize()) { reorderingConstraint.SetMonotoneAtPunctuation(*ret); } // set walls obtained from xml for(size_t i=0; i<xmlOptions.size(); i++) { const XMLOption &xmlOption = *xmlOptions[i]; if(xmlOption.nodeName == "wall") { UTIL_THROW_IF2(xmlOption.startPos >= ret->GetSize(), "wall is beyond the sentence"); // no buggy walls, please reorderingConstraint.SetWall(xmlOption.startPos - 1, true); } else if (xmlOption.nodeName == "zone") { reorderingConstraint.SetZone( xmlOption.startPos, xmlOption.startPos + xmlOption.phraseSize -1 ); } else { // default - forced translation. Add to class variable ret->GetXMLOptions().push_back(new XMLOption(xmlOption)); } } reorderingConstraint.FinalizeWalls(); // clean up for (size_t i = 0; i < xmlOptions.size(); ++i) { delete xmlOptions[i]; } return ret; } void Sentence::XMLParse( const System &system, size_t depth, const pugi::xml_node &parentNode, std::vector<std::string> &toks, vector<XMLOption*> &xmlOptions) { // pugixml for (pugi::xml_node childNode = parentNode.first_child(); childNode; childNode = childNode.next_sibling()) { string nodeName = childNode.name(); //cerr << depth << " nodeName=" << nodeName << endl; int startPos = toks.size(); string value = childNode.value(); if (!value.empty()) { //cerr << depth << "childNode text=" << value << endl; std::vector<std::string> subPhraseToks = Tokenize(value); for (size_t i = 0; i < subPhraseToks.size(); ++i) { toks.push_back(subPhraseToks[i]); } } if (!nodeName.empty()) { XMLOption *xmlOption = new XMLOption(); xmlOption->nodeName = nodeName; xmlOption->startPos = startPos; pugi::xml_attribute attr = childNode.attribute("translation"); if (!attr.empty()) { xmlOption->translation = attr.as_string(); } attr = childNode.attribute("prob"); if (!attr.empty()) { xmlOption->prob = attr.as_float(); } xmlOptions.push_back(xmlOption); // recursively call this function. For proper recursive trees XMLParse(system, depth + 1, childNode, toks, xmlOptions); size_t endPos = toks.size(); xmlOption->phraseSize = endPos - startPos; /* cerr << "xmlOptions="; xmlOption->Debug(cerr, system); cerr << endl; */ } } } } /* namespace Moses2 */
comment out debugging info
comment out debugging info
C++
lgpl-2.1
moses-smt/mosesdecoder,alvations/mosesdecoder,moses-smt/mosesdecoder,tofula/mosesdecoder,alvations/mosesdecoder,moses-smt/mosesdecoder,moses-smt/mosesdecoder,alvations/mosesdecoder,tofula/mosesdecoder,tofula/mosesdecoder,alvations/mosesdecoder,tofula/mosesdecoder,tofula/mosesdecoder,moses-smt/mosesdecoder,moses-smt/mosesdecoder,tofula/mosesdecoder,alvations/mosesdecoder,moses-smt/mosesdecoder,alvations/mosesdecoder,tofula/mosesdecoder,alvations/mosesdecoder,tofula/mosesdecoder,alvations/mosesdecoder,moses-smt/mosesdecoder,moses-smt/mosesdecoder,tofula/mosesdecoder,moses-smt/mosesdecoder,alvations/mosesdecoder,tofula/mosesdecoder,tofula/mosesdecoder,moses-smt/mosesdecoder,alvations/mosesdecoder,alvations/mosesdecoder
419dcb6b5688c6573fcba270ea6792f112985780
examples/graphics/frontBack.cpp
examples/graphics/frontBack.cpp
/* Allocore Example: Front and back views Description: This example demonstrates how to render both front and back views from a single navigation point. Author: Lance Putnam, 8/29/2011 */ #include "alloutil/al_World.hpp" using namespace al; class MyActor : public Actor{ public: virtual void onDraw(Graphics& g, const Viewpoint& v){ Mesh& m = g.mesh(); m.reset(); m.primitive(g.LINES); for(int j=0; j<4; ++j){ int Nv = addSphere(m, (j+1)*2, 20, 20); for(int i=0; i<Nv; ++i){ float v = float(i)/Nv; m.color(HSV(0.2*v, 1-v*0.5, 1)); } } g.draw(m); } }; World w("Front and Back Views"); Viewpoint vpF, vpB; MyActor myActor; ViewpointWindow win(0,0, 800,600, w.name()); int main(){ // Configure the front and back viewpoints vpF.parentTransform(w.nav()); vpB.parentTransform(w.nav()); vpF.stretch(1, 0.5).anchor(0, 0.5); vpB.stretch(1, 0.5).anchor(0, 0.0); vpB.transform().quat().fromAxisAngle(M_PI, 0,1,0); win.add(vpF).add(vpB); w.add(win, true); // Note: this will call our drawing routine for each viewpoint w.add(myActor); w.start(); return 0; }
/* Allocore Example: Front and back views Description: This example demonstrates how to render both front and back views from a single navigation point. Author: Lance Putnam, 8/29/2011 */ #include "alloutil/al_App.hpp" using namespace al; class MyApp : public App{ public: virtual void onDraw(Graphics& g, const Viewpoint& v){ Mesh& m = g.mesh(); m.reset(); m.primitive(g.LINES); for(int j=0; j<4; ++j){ int Nv = addSphere(m, (j+1)*2, 20, 20); for(int i=0; i<Nv; ++i){ float v = float(i)/Nv; m.color(HSV(0.2*v, 1-v*0.5, 1)); } } g.draw(m); } }; MyApp app; Viewpoint vpF, vpB; ViewpointWindow win(Window::Dim(800,600)); int main(){ // Configure the front and back viewpoints vpF.parentTransform(app.nav()); vpB.parentTransform(app.nav()); vpF.stretch(1, 0.5).anchor(0, 0.5); vpB.stretch(1, 0.5).anchor(0, 0.0); vpB.transform().quat().fromAxisAngle(M_PI, 0,1,0); win.add(vpF).add(vpB); app.add(win); app.start(); return 0; }
update to use App
update to use App
C++
bsd-3-clause
AlloSphere-Research-Group/AlloSystem,AlloSphere-Research-Group/AlloSystem,AlloSphere-Research-Group/AlloSystem,AlloSphere-Research-Group/AlloSystem,AlloSphere-Research-Group/AlloSystem
4726f5d6716b111e1adf80ab92e304fd4fc7475c
core/Core/ExperimentDataLoading/LoadingUtilities.cpp
core/Core/ExperimentDataLoading/LoadingUtilities.cpp
/** * LoadingUtilities.cpp * * Copyright (c) 2004 MIT. All rights reserved. */ #include "OpenGLContextManager.h" #include "Event.h" #include "LoadingUtilities.h" #include "Experiment.h" #include "PlatformDependentServices.h" #include "SystemEventFactory.h" #include "EventBuffer.h" #include "StandardVariables.h" #include "StandardStimuli.h" #include "OpenALContextManager.h" #include <string> #include <boost/filesystem/path.hpp> #include <boost/filesystem/operations.hpp> #include <boost/filesystem/convenience.hpp> #include <boost/pointer_cast.hpp> #include "ComponentRegistry.h" #include "XMLParser.h" #include "DataFileManager.h" #include <glob.h> #include <boost/scope_exit.hpp> BEGIN_NAMESPACE_MW // DDC: HOLY CRAP: WHY WAS HE QUIETLY REPLACING MISSING VALUES WITH DEFAULTS?!? // Datum checkLoadedValueAndReturnNewValuesWithLoadedValueOrDefaultIfNotNumber(const Datum main_window_values, // const Datum current_values, // const std::string &key, // const Datum default_values) { // Datum new_values(current_values); // if(!(main_window_values.getElement(key).isNumber())) { // merror(M_PARSER_MESSAGE_DOMAIN, "'%s' is either empty or has an illegal value, setting default to %f", key.c_str(), default_values.getFloat()); // new_values.addElement(key.c_str(), default_values); // } else { // new_values.addElement(key.c_str(), main_window_values.getElement(key)); // } // // return new_values; // } #define CHECK_DICT_VALUE_IS_NUMBER(dict, key) dict.getElement(key).isNumber() bool loadSetupVariables() { boost::filesystem::path setupPath(setupVariablesFile()); shared_ptr<ComponentRegistry> reg = ComponentRegistry::getSharedRegistry(); XMLParser parser(reg, setupPath.string()); parser.parse(); // check setup variables for validity shared_ptr<Variable> main_screen_info_variable = reg->getVariable(MAIN_SCREEN_INFO_TAGNAME); Datum main_screen_dict = main_screen_info_variable->getValue(); bool width_ok = CHECK_DICT_VALUE_IS_NUMBER(main_screen_dict, M_DISPLAY_WIDTH_KEY); bool height_ok = CHECK_DICT_VALUE_IS_NUMBER(main_screen_dict, M_DISPLAY_HEIGHT_KEY); bool dist_ok = CHECK_DICT_VALUE_IS_NUMBER(main_screen_dict, M_DISPLAY_DISTANCE_KEY); bool refresh_ok = CHECK_DICT_VALUE_IS_NUMBER(main_screen_dict, M_REFRESH_RATE_KEY); if (!(width_ok && height_ok && dist_ok && refresh_ok)) { string stem = "Invalid display info defined in setup_variables.xml (missing/invalid: "; if(!width_ok) stem = stem + M_DISPLAY_WIDTH_KEY + " "; if(!height_ok) stem = stem + M_DISPLAY_HEIGHT_KEY + " "; if(!dist_ok) stem = stem + M_DISPLAY_DISTANCE_KEY + " "; if(!refresh_ok) stem = stem + M_REFRESH_RATE_KEY + " "; stem += ")"; throw SimpleException(stem); } // TODO: more error checking. THESE SHOULD ALL THROW IF SOMETHING IS WRONG!!! // DDC: HOLY CRAP! Why was he quietly replacing missing values with defaults? This is a recipe for // serious errors quietly creeping in! //Datum loaded_values = main_screen_info->getValue(); // Datum new_values(M_DICTIONARY, 7); // // new_values = checkLoadedValueAndReturnNewValuesWithLoadedValueOrDefaultIfNotNumber(loaded_values, new_values, M_DISPLAY_WIDTH_KEY, 14.75); // new_values = checkLoadedValueAndReturnNewValuesWithLoadedValueOrDefaultIfNotNumber(loaded_values, new_values, M_DISPLAY_HEIGHT_KEY, 11.09); // new_values = checkLoadedValueAndReturnNewValuesWithLoadedValueOrDefaultIfNotNumber(loaded_values, new_values, M_DISPLAY_DISTANCE_KEY, 10.0); // new_values = checkLoadedValueAndReturnNewValuesWithLoadedValueOrDefaultIfNotNumber(loaded_values, new_values, M_REFRESH_RATE_KEY, 60L); // // if(!(loaded_values.getElement(M_ALWAYS_DISPLAY_MIRROR_WINDOW_KEY).isNumber())) { // merror(M_PARSER_MESSAGE_DOMAIN, "'always_display_mirror_window' is either empty or has an illegal value, setting default to 0"); // new_values.addElement(M_ALWAYS_DISPLAY_MIRROR_WINDOW_KEY, 0L); // } else { // long always_display_mirror_window = loaded_values.getElement(M_ALWAYS_DISPLAY_MIRROR_WINDOW_KEY).getInteger(); // if(!(always_display_mirror_window != 0 || always_display_mirror_window != 1)) { // merror(M_PARSER_MESSAGE_DOMAIN, "'always_display_mirror_window' has an illegal value (%d), setting default to 0", always_display_mirror_window); // new_values.addElement(M_ALWAYS_DISPLAY_MIRROR_WINDOW_KEY, 0L); // } else { // new_values.addElement(M_ALWAYS_DISPLAY_MIRROR_WINDOW_KEY, always_display_mirror_window); // // if(always_display_mirror_window == 1) { // // now check the base height // new_values = checkLoadedValueAndReturnNewValuesWithLoadedValueOrDefaultIfNotNumber(loaded_values, new_values, M_MIRROR_WINDOW_BASE_HEIGHT_KEY, 400L); // } // } // } // // if(!(loaded_values.getElement(M_DISPLAY_TO_USE_KEY).isInteger())) { // merror(M_PARSER_MESSAGE_DOMAIN, "'%s' is either empty or has an illegal value, setting default to 0", M_DISPLAY_TO_USE_KEY); // new_values.addElement(M_DISPLAY_TO_USE_KEY, 0L); // } else { // new_values.addElement(M_DISPLAY_TO_USE_KEY, loaded_values.getElement(M_DISPLAY_TO_USE_KEY)); // } // // main_screen_info->setValue(new_values); return true; } bool loadExperimentFromXMLParser(const boost::filesystem::path filepath) { const std::string substitutionDescriptor("%s"); try { unloadExperiment(false); // delete an experiment if one exists. } catch(std::exception& e){ merror(M_PARSER_MESSAGE_DOMAIN, "%s", e.what()); GlobalCurrentExperiment = shared_ptr<Experiment>(); global_outgoing_event_buffer->putEvent(SystemEventFactory::currentExperimentState()); return false; } shared_ptr<ComponentRegistry> reg = ComponentRegistry::getSharedRegistry(); std::vector<xmlChar> fileData; try { XMLParser parser(reg, filepath.string()); parser.parse(true); // Use getDocumentData to get the experiment file with any preprocessing and/or // XInclude substitutions already applied parser.getDocumentData(fileData); } catch(SimpleException& e){ // This is the "main" catch block for parsing display_extended_error_information(e); unloadExperiment(false); } catch(std::exception& e){ merror(M_PARSER_MESSAGE_DOMAIN, "An unanticipated error occurred. This is probably a bug, and someone will want to run this in a debugger. Error message was: \"%s\"", e.what()); unloadExperiment(false); } if(GlobalCurrentExperiment == NULL) { global_outgoing_event_buffer->putEvent(SystemEventFactory::currentExperimentState()); return false; } // Store the XML source of the experiment in #loadedExperiment, so that it will be // recorded in the event stream (unless the experiment itself has already set #loadedExperiment, // in which case leave it unchanged) if (loadedExperiment->getValue().getSize() == 0) { loadedExperiment->setValue(Datum(reinterpret_cast<char *>(fileData.data()), fileData.size())); } global_outgoing_event_buffer->putEvent(SystemEventFactory::componentCodecPackage()); global_outgoing_event_buffer->putEvent(SystemEventFactory::codecPackage()); global_outgoing_event_buffer->putEvent(SystemEventFactory::currentExperimentState()); global_outgoing_event_buffer->putEvent(SystemEventFactory::protocolPackage()); global_variable_registry->announceAll(); return true; } void parseIncludedFilesFromExperiment(const boost::filesystem::path filepath) { // DEPRECATED } void unloadExperiment(bool announce) { GlobalCurrentExperiment = shared_ptr<Experiment>(); shared_ptr<ComponentRegistry> component_registry = ComponentRegistry::getSharedRegistry(); component_registry->resetInstances(); if(global_variable_registry != NULL) { // exp. already loaded global_variable_registry->reset(); //global_variable_registry = shared_ptr<VariableRegistry>(new VariableRegistry(global_outgoing_event_buffer)); initializeStandardVariables(global_variable_registry); loadSetupVariables(); } shared_ptr<OpenGLContextManager> opengl_context_manager = OpenGLContextManager::instance(false); if(opengl_context_manager != NULL){ opengl_context_manager->releaseContexts(); //opengl_context_manager->destroy(); } OpenALContextManager::destroy(); shared_ptr<Component> openal_context_manager(new OpenALContextManager()); OpenALContextManager::registerInstance(openal_context_manager); if (auto dataFileManager = DataFileManager::instance(false)) { dataFileManager->closeFile(); dataFileManager->clearAutoOpenFilename(); } if(announce){ global_outgoing_event_buffer->putEvent(SystemEventFactory::componentCodecPackage()); global_outgoing_event_buffer->putEvent(SystemEventFactory::codecPackage()); global_outgoing_event_buffer->putEvent(SystemEventFactory::currentExperimentState()); global_variable_registry->announceAll(); } } boost::filesystem::path expandPath(std::string working_directory, std::string path, bool expandAbsolutePath) { boost::filesystem::path specific_path; boost::filesystem::path full_path; try { specific_path = boost::filesystem::path(path); } catch(std::exception& e){ cerr << "bad path" << endl; } if (path[0] == '/' && !expandAbsolutePath) { return specific_path; } else { try{ boost::filesystem::path working_path(working_directory); full_path = working_path / specific_path; } catch(std::exception& e){ cerr << "bad path" << endl; } return full_path; } } void modifyExperimentMediaPaths(const boost::filesystem::path filepath) { const std::string substitutionDescriptor("%s"); } void expandRangeReplicatorItems(const boost::filesystem::path filepath) { // TODO: deprecated } void createExperimentInstallDirectoryStructure(const std::string expFileName) { namespace bf = boost::filesystem; const std::string substitutionDescriptor("%s"); std::string expName(removeFileExtension(expFileName)); bf::path currExpStorageDir = getLocalExperimentStorageDir(expName); //bf::path expFileNamePath(expFileName); if(exists(currExpStorageDir)) { remove_all(currExpStorageDir); } bf::create_directories(currExpStorageDir); } std::string removeSpacesFromString(std::string s) { const std::string us("_"); const std::string space(" "); while(s.find_first_of(space) != std::string::npos) { s.replace(s.find_first_of(space), us.length(), us); } return s; } void getFilePaths(const std::string &workingPath, const std::string &directoryPath, std::vector<std::string> &filePaths, bool recursive) { const std::string fullPath(expandPath(workingPath, directoryPath).string()); getFilePaths(fullPath, filePaths, recursive); if (fullPath != directoryPath) { for (std::vector<std::string>::iterator iter = filePaths.begin(); iter != filePaths.end(); iter++) { (*iter).erase(0, workingPath.size() + 1); // +1 for the trailing forward-slash } } } static void getFilePathsInternal(const boost::filesystem::path &dirPath, std::vector<std::string> &filePaths, bool recursive) { namespace bf = boost::filesystem; bf::directory_iterator endIter; for (bf::directory_iterator iter(dirPath); iter != endIter; iter++) { // Include only regular files whose names don't start with "." const auto path = iter->path(); if (path.filename().string().find(".") != 0) { if (bf::is_regular_file(iter->status())) { filePaths.push_back(path.string()); } else if (recursive && bf::is_directory(iter->status())) { getFilePathsInternal(path, filePaths, true); } } } } void getFilePaths(const std::string &directoryPath, std::vector<std::string> &filePaths, bool recursive) { namespace bf = boost::filesystem; bf::path dirPath(directoryPath); if (!bf::is_directory(dirPath)) { throw SimpleException("Invalid directory path", directoryPath); } getFilePathsInternal(dirPath, filePaths, recursive); if (filePaths.size() == 0) { throw SimpleException("Directory contains no regular files", directoryPath); } } std::size_t getMatchingFilenames(const std::string &workingPath, const string &globPattern, std::vector<std::string> &filenames) { auto cwdfd = open(".", O_RDONLY); if (-1 == cwdfd) { throw SimpleException("Unable to open current working directory", strerror(errno)); } BOOST_SCOPE_EXIT( &cwdfd ) { (void)fchdir(cwdfd); (void)close(cwdfd); } BOOST_SCOPE_EXIT_END if (!(workingPath.empty())) { if (-1 == chdir(workingPath.c_str())) { throw SimpleException("Unable to change directory", strerror(errno)); } } glob_t globResults; auto globStatus = glob(globPattern.c_str(), 0, nullptr, &globResults); BOOST_SCOPE_EXIT( &globResults ) { globfree(&globResults); } BOOST_SCOPE_EXIT_END if ((0 != globStatus) && (GLOB_NOMATCH != globStatus)) { throw SimpleException("Unknown error when evaluating filenames pattern", globPattern); } for (std::size_t i = 0; i < globResults.gl_pathc; i++) { boost::filesystem::path filePath(globResults.gl_pathv[i]); filenames.push_back(filePath.string()); } return globResults.gl_pathc; } END_NAMESPACE_MW
/** * LoadingUtilities.cpp * * Copyright (c) 2004 MIT. All rights reserved. */ #include "OpenGLContextManager.h" #include "Event.h" #include "LoadingUtilities.h" #include "Experiment.h" #include "PlatformDependentServices.h" #include "SystemEventFactory.h" #include "EventBuffer.h" #include "StandardVariables.h" #include "StandardStimuli.h" #include "OpenALContextManager.h" #include <string> #include <boost/filesystem/path.hpp> #include <boost/filesystem/operations.hpp> #include <boost/filesystem/convenience.hpp> #include <boost/pointer_cast.hpp> #include "ComponentRegistry.h" #include "XMLParser.h" #include "DataFileManager.h" #include <glob.h> #include <boost/scope_exit.hpp> BEGIN_NAMESPACE_MW // DDC: HOLY CRAP: WHY WAS HE QUIETLY REPLACING MISSING VALUES WITH DEFAULTS?!? // Datum checkLoadedValueAndReturnNewValuesWithLoadedValueOrDefaultIfNotNumber(const Datum main_window_values, // const Datum current_values, // const std::string &key, // const Datum default_values) { // Datum new_values(current_values); // if(!(main_window_values.getElement(key).isNumber())) { // merror(M_PARSER_MESSAGE_DOMAIN, "'%s' is either empty or has an illegal value, setting default to %f", key.c_str(), default_values.getFloat()); // new_values.addElement(key.c_str(), default_values); // } else { // new_values.addElement(key.c_str(), main_window_values.getElement(key)); // } // // return new_values; // } #define CHECK_DICT_VALUE_IS_NUMBER(dict, key) dict.getElement(key).isNumber() bool loadSetupVariables() { boost::filesystem::path setupPath(setupVariablesFile()); shared_ptr<ComponentRegistry> reg = ComponentRegistry::getSharedRegistry(); XMLParser parser(reg, setupPath.string()); parser.parse(); // check setup variables for validity shared_ptr<Variable> main_screen_info_variable = reg->getVariable(MAIN_SCREEN_INFO_TAGNAME); Datum main_screen_dict = main_screen_info_variable->getValue(); bool width_ok = CHECK_DICT_VALUE_IS_NUMBER(main_screen_dict, M_DISPLAY_WIDTH_KEY); bool height_ok = CHECK_DICT_VALUE_IS_NUMBER(main_screen_dict, M_DISPLAY_HEIGHT_KEY); bool dist_ok = CHECK_DICT_VALUE_IS_NUMBER(main_screen_dict, M_DISPLAY_DISTANCE_KEY); bool refresh_ok = CHECK_DICT_VALUE_IS_NUMBER(main_screen_dict, M_REFRESH_RATE_KEY); if (!(width_ok && height_ok && dist_ok && refresh_ok)) { string stem = "Invalid display info defined in setup_variables.xml (missing/invalid: "; if(!width_ok) stem = stem + M_DISPLAY_WIDTH_KEY + " "; if(!height_ok) stem = stem + M_DISPLAY_HEIGHT_KEY + " "; if(!dist_ok) stem = stem + M_DISPLAY_DISTANCE_KEY + " "; if(!refresh_ok) stem = stem + M_REFRESH_RATE_KEY + " "; stem += ")"; throw SimpleException(stem); } // TODO: more error checking. THESE SHOULD ALL THROW IF SOMETHING IS WRONG!!! // DDC: HOLY CRAP! Why was he quietly replacing missing values with defaults? This is a recipe for // serious errors quietly creeping in! //Datum loaded_values = main_screen_info->getValue(); // Datum new_values(M_DICTIONARY, 7); // // new_values = checkLoadedValueAndReturnNewValuesWithLoadedValueOrDefaultIfNotNumber(loaded_values, new_values, M_DISPLAY_WIDTH_KEY, 14.75); // new_values = checkLoadedValueAndReturnNewValuesWithLoadedValueOrDefaultIfNotNumber(loaded_values, new_values, M_DISPLAY_HEIGHT_KEY, 11.09); // new_values = checkLoadedValueAndReturnNewValuesWithLoadedValueOrDefaultIfNotNumber(loaded_values, new_values, M_DISPLAY_DISTANCE_KEY, 10.0); // new_values = checkLoadedValueAndReturnNewValuesWithLoadedValueOrDefaultIfNotNumber(loaded_values, new_values, M_REFRESH_RATE_KEY, 60L); // // if(!(loaded_values.getElement(M_ALWAYS_DISPLAY_MIRROR_WINDOW_KEY).isNumber())) { // merror(M_PARSER_MESSAGE_DOMAIN, "'always_display_mirror_window' is either empty or has an illegal value, setting default to 0"); // new_values.addElement(M_ALWAYS_DISPLAY_MIRROR_WINDOW_KEY, 0L); // } else { // long always_display_mirror_window = loaded_values.getElement(M_ALWAYS_DISPLAY_MIRROR_WINDOW_KEY).getInteger(); // if(!(always_display_mirror_window != 0 || always_display_mirror_window != 1)) { // merror(M_PARSER_MESSAGE_DOMAIN, "'always_display_mirror_window' has an illegal value (%d), setting default to 0", always_display_mirror_window); // new_values.addElement(M_ALWAYS_DISPLAY_MIRROR_WINDOW_KEY, 0L); // } else { // new_values.addElement(M_ALWAYS_DISPLAY_MIRROR_WINDOW_KEY, always_display_mirror_window); // // if(always_display_mirror_window == 1) { // // now check the base height // new_values = checkLoadedValueAndReturnNewValuesWithLoadedValueOrDefaultIfNotNumber(loaded_values, new_values, M_MIRROR_WINDOW_BASE_HEIGHT_KEY, 400L); // } // } // } // // if(!(loaded_values.getElement(M_DISPLAY_TO_USE_KEY).isInteger())) { // merror(M_PARSER_MESSAGE_DOMAIN, "'%s' is either empty or has an illegal value, setting default to 0", M_DISPLAY_TO_USE_KEY); // new_values.addElement(M_DISPLAY_TO_USE_KEY, 0L); // } else { // new_values.addElement(M_DISPLAY_TO_USE_KEY, loaded_values.getElement(M_DISPLAY_TO_USE_KEY)); // } // // main_screen_info->setValue(new_values); return true; } bool loadExperimentFromXMLParser(const boost::filesystem::path filepath) { const std::string substitutionDescriptor("%s"); try { unloadExperiment(false); // delete an experiment if one exists. } catch(std::exception& e){ merror(M_PARSER_MESSAGE_DOMAIN, "%s", e.what()); GlobalCurrentExperiment = shared_ptr<Experiment>(); global_outgoing_event_buffer->putEvent(SystemEventFactory::currentExperimentState()); return false; } shared_ptr<ComponentRegistry> reg = ComponentRegistry::getSharedRegistry(); std::vector<xmlChar> fileData; try { XMLParser parser(reg, filepath.string()); parser.parse(true); // Use getDocumentData to get the experiment file with any preprocessing and/or // XInclude substitutions already applied parser.getDocumentData(fileData); } catch(SimpleException& e){ // This is the "main" catch block for parsing display_extended_error_information(e); unloadExperiment(false); } catch(std::exception& e){ merror(M_PARSER_MESSAGE_DOMAIN, "An unanticipated error occurred. This is probably a bug, and someone will want to run this in a debugger. Error message was: \"%s\"", e.what()); unloadExperiment(false); } auto experiment = GlobalCurrentExperiment; if (!experiment) { global_outgoing_event_buffer->putEvent(SystemEventFactory::currentExperimentState()); return false; } // At this point, the display is already cleared. However, by clearing it again now, *after* all the // stimuli have been created and (probably) loaded, we can "commit" any OpenGL and/or Metal actions // that have been taken. While it seems like this shouldn't matter much, it appears to have a definite, // beneficial influence on subsequent display-update performance, particularly on iOS. experiment->getStimulusDisplay()->clearDisplay(); // Store the XML source of the experiment in #loadedExperiment, so that it will be // recorded in the event stream (unless the experiment itself has already set #loadedExperiment, // in which case leave it unchanged) if (loadedExperiment->getValue().getSize() == 0) { loadedExperiment->setValue(Datum(reinterpret_cast<char *>(fileData.data()), fileData.size())); } global_outgoing_event_buffer->putEvent(SystemEventFactory::componentCodecPackage()); global_outgoing_event_buffer->putEvent(SystemEventFactory::codecPackage()); global_outgoing_event_buffer->putEvent(SystemEventFactory::currentExperimentState()); global_outgoing_event_buffer->putEvent(SystemEventFactory::protocolPackage()); global_variable_registry->announceAll(); return true; } void parseIncludedFilesFromExperiment(const boost::filesystem::path filepath) { // DEPRECATED } void unloadExperiment(bool announce) { GlobalCurrentExperiment = shared_ptr<Experiment>(); shared_ptr<ComponentRegistry> component_registry = ComponentRegistry::getSharedRegistry(); component_registry->resetInstances(); if(global_variable_registry != NULL) { // exp. already loaded global_variable_registry->reset(); //global_variable_registry = shared_ptr<VariableRegistry>(new VariableRegistry(global_outgoing_event_buffer)); initializeStandardVariables(global_variable_registry); loadSetupVariables(); } shared_ptr<OpenGLContextManager> opengl_context_manager = OpenGLContextManager::instance(false); if(opengl_context_manager != NULL){ opengl_context_manager->releaseContexts(); //opengl_context_manager->destroy(); } OpenALContextManager::destroy(); shared_ptr<Component> openal_context_manager(new OpenALContextManager()); OpenALContextManager::registerInstance(openal_context_manager); if (auto dataFileManager = DataFileManager::instance(false)) { dataFileManager->closeFile(); dataFileManager->clearAutoOpenFilename(); } if(announce){ global_outgoing_event_buffer->putEvent(SystemEventFactory::componentCodecPackage()); global_outgoing_event_buffer->putEvent(SystemEventFactory::codecPackage()); global_outgoing_event_buffer->putEvent(SystemEventFactory::currentExperimentState()); global_variable_registry->announceAll(); } } boost::filesystem::path expandPath(std::string working_directory, std::string path, bool expandAbsolutePath) { boost::filesystem::path specific_path; boost::filesystem::path full_path; try { specific_path = boost::filesystem::path(path); } catch(std::exception& e){ cerr << "bad path" << endl; } if (path[0] == '/' && !expandAbsolutePath) { return specific_path; } else { try{ boost::filesystem::path working_path(working_directory); full_path = working_path / specific_path; } catch(std::exception& e){ cerr << "bad path" << endl; } return full_path; } } void modifyExperimentMediaPaths(const boost::filesystem::path filepath) { const std::string substitutionDescriptor("%s"); } void expandRangeReplicatorItems(const boost::filesystem::path filepath) { // TODO: deprecated } void createExperimentInstallDirectoryStructure(const std::string expFileName) { namespace bf = boost::filesystem; const std::string substitutionDescriptor("%s"); std::string expName(removeFileExtension(expFileName)); bf::path currExpStorageDir = getLocalExperimentStorageDir(expName); //bf::path expFileNamePath(expFileName); if(exists(currExpStorageDir)) { remove_all(currExpStorageDir); } bf::create_directories(currExpStorageDir); } std::string removeSpacesFromString(std::string s) { const std::string us("_"); const std::string space(" "); while(s.find_first_of(space) != std::string::npos) { s.replace(s.find_first_of(space), us.length(), us); } return s; } void getFilePaths(const std::string &workingPath, const std::string &directoryPath, std::vector<std::string> &filePaths, bool recursive) { const std::string fullPath(expandPath(workingPath, directoryPath).string()); getFilePaths(fullPath, filePaths, recursive); if (fullPath != directoryPath) { for (std::vector<std::string>::iterator iter = filePaths.begin(); iter != filePaths.end(); iter++) { (*iter).erase(0, workingPath.size() + 1); // +1 for the trailing forward-slash } } } static void getFilePathsInternal(const boost::filesystem::path &dirPath, std::vector<std::string> &filePaths, bool recursive) { namespace bf = boost::filesystem; bf::directory_iterator endIter; for (bf::directory_iterator iter(dirPath); iter != endIter; iter++) { // Include only regular files whose names don't start with "." const auto path = iter->path(); if (path.filename().string().find(".") != 0) { if (bf::is_regular_file(iter->status())) { filePaths.push_back(path.string()); } else if (recursive && bf::is_directory(iter->status())) { getFilePathsInternal(path, filePaths, true); } } } } void getFilePaths(const std::string &directoryPath, std::vector<std::string> &filePaths, bool recursive) { namespace bf = boost::filesystem; bf::path dirPath(directoryPath); if (!bf::is_directory(dirPath)) { throw SimpleException("Invalid directory path", directoryPath); } getFilePathsInternal(dirPath, filePaths, recursive); if (filePaths.size() == 0) { throw SimpleException("Directory contains no regular files", directoryPath); } } std::size_t getMatchingFilenames(const std::string &workingPath, const string &globPattern, std::vector<std::string> &filenames) { auto cwdfd = open(".", O_RDONLY); if (-1 == cwdfd) { throw SimpleException("Unable to open current working directory", strerror(errno)); } BOOST_SCOPE_EXIT( &cwdfd ) { (void)fchdir(cwdfd); (void)close(cwdfd); } BOOST_SCOPE_EXIT_END if (!(workingPath.empty())) { if (-1 == chdir(workingPath.c_str())) { throw SimpleException("Unable to change directory", strerror(errno)); } } glob_t globResults; auto globStatus = glob(globPattern.c_str(), 0, nullptr, &globResults); BOOST_SCOPE_EXIT( &globResults ) { globfree(&globResults); } BOOST_SCOPE_EXIT_END if ((0 != globStatus) && (GLOB_NOMATCH != globStatus)) { throw SimpleException("Unknown error when evaluating filenames pattern", globPattern); } for (std::size_t i = 0; i < globResults.gl_pathc; i++) { boost::filesystem::path filePath(globResults.gl_pathv[i]); filenames.push_back(filePath.string()); } return globResults.gl_pathc; } END_NAMESPACE_MW
Clear the stimulus display after the experiment and all components have been loaded
Clear the stimulus display after the experiment and all components have been loaded This (hopefully!) eliminates the persistent display update "hiccups" that occur the first time an experiment is run.
C++
mit
mworks/mworks,mworks/mworks,mworks/mworks,mworks/mworks,mworks/mworks,mworks/mworks,mworks/mworks,mworks/mworks,mworks/mworks
05bda291ea7d7c6bb47af0470b93925b84c66965
examples/querymessages/main.cpp
examples/querymessages/main.cpp
/**************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation ([email protected]) ** ** This file is part of the Qt Mobility Components. ** ** $QT_BEGIN_LICENSE:BSD$ ** You may use this file under the terms of the BSD license as follows: ** ** "Redistribution and use in source and binary forms, with or without ** modification, are permitted provided that the following conditions are ** met: ** * Redistributions of source code must retain the above copyright ** notice, this list of conditions and the following disclaimer. ** * Redistributions in binary form must reproduce the above copyright ** notice, this list of conditions and the following disclaimer in ** the documentation and/or other materials provided with the ** distribution. ** * Neither the name of Nokia Corporation and its Subsidiary(-ies) nor ** the names of its contributors may be used to endorse or promote ** products derived from this software without specific prior written ** permission. ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." ** $QT_END_LICENSE$ ** ****************************************************************************/ #include <QCoreApplication> #include <qmessagemanager.h> #include <qdebug.h> #include <QMap> #ifdef Q_OS_SYMBIAN #include <iostream> #endif QTM_USE_NAMESPACE static void printMessage(const QString& msg) { #ifdef Q_OS_SYMBIAN std::cout << qPrintable(msg) << std::endl; #else qDebug() << qPrintable(msg); #endif } void usage() { QString msg("Usage: [<options>] [<datafields>]\n" " Where <options> limit the types of messages shown, valid choices: -all, -sms, -mms, -email, -instantmessage, -incoming, -read, -inboxfolder, -draftsfolder, -outboxfolder, -sentfolder, -trashfolder\n" " To join options by logical OR use +, for option, eg \"+sms +mms\" will return sms OR mms messages\n" " Where <datafields> specify what fields to print from matched messages, valid choices are: subject, date, receivedDate, status, size, priority, to, cc, bcc, from, type, body, attachments"); printMessage(msg); } // create message filter as requested by command line options QMessageFilter createFilter(QStringList args) { QMessageFilter filter(QMessageFilter::byStatus(QMessage::Incoming)); QMessageFilter customfilter; bool setCustomFilter = false; QMap<QString, QMessageFilter> filterMap; filterMap.insert(QLatin1String("all"), QMessageFilter()); filterMap.insert(QLatin1String("sms"), QMessageFilter::byType(QMessage::Sms)); filterMap.insert(QLatin1String("mms"), QMessageFilter::byType(QMessage::Mms)); filterMap.insert(QLatin1String("email"), QMessageFilter::byType(QMessage::Email)); filterMap.insert(QLatin1String("instantmessage"), QMessageFilter::byType(QMessage::InstantMessage)); filterMap.insert(QLatin1String("incoming"), QMessageFilter::byStatus(QMessage::Incoming)); filterMap.insert(QLatin1String("read"), QMessageFilter::byStatus(QMessage::Read)); filterMap.insert(QLatin1String("inboxfolder"), QMessageFilter::byStandardFolder(QMessage::InboxFolder)); filterMap.insert(QLatin1String("draftsfolder"), QMessageFilter::byStandardFolder(QMessage::DraftsFolder)); filterMap.insert(QLatin1String("outboxfolder"), QMessageFilter::byStandardFolder(QMessage::OutboxFolder)); filterMap.insert(QLatin1String("sentfolder"), QMessageFilter::byStandardFolder(QMessage::SentFolder)); filterMap.insert(QLatin1String("trashfolder"), QMessageFilter::byStandardFolder(QMessage::TrashFolder)); // process command line options after the application name foreach (const QString &arg, args.mid(1)){ QMap<QString, QMessageFilter>::const_iterator iterator = filterMap.find(arg.toLower().mid(1)); if (iterator != filterMap.end()){ setCustomFilter = true; // use AND logic when compounding filter? if (arg[0] == '-' ) customfilter = customfilter & iterator.value(); else customfilter = customfilter | iterator.value(); } } if (setCustomFilter) filter = customfilter; return filter; } int main(int argc, char *argv[]) { QCoreApplication app(argc, argv); printMessage("Querying messages..."); // determine what data options were requested and if help was requested // if no data options were provided default to "subject" QStringList dataOptions; QStringList validDataOptions = QStringList() << "subject" << "date" << "receivedDate" << "status" << "size" << "priority" << "to" << "cc" << "bcc" << "from" << "type" << "body" << "attachments"; foreach (const QString &arg, app.arguments()){ if (arg == "-help"){ usage(); exit(1); } if (validDataOptions.contains(arg)) dataOptions.append(arg); } if (dataOptions.isEmpty()) dataOptions.append("subject"); //! [setup-query] // Create filter to match required messages QMessageFilter filter = createFilter(app.arguments()); // instead of the above use the following for a simple filter of all messages whose status field have the Incoming flag to be set, eg incoming emails //QMessageFilter filter(QMessageFilter::byStatus(QMessage::Incoming)); // Order the matching results by their reception timestamp, in descending order QMessageSortOrder sortOrder(QMessageSortOrder::byReceptionTimeStamp(Qt::DescendingOrder)); //! [setup-query] //! [perform-query] // Acquire a handle to the message manager QMessageManager manager; // Find the matching message IDs, limiting our results to a managable number const int max = 100; const QMessageIdList matchingIds(manager.queryMessages(filter, sortOrder, max)); //! [perform-query] int n = 0; //! [iterate-results] // Retrieve each message and print requested details foreach (const QMessageId &id, matchingIds) { QMessage message(manager.message(id)); //! [iterate-results] if (manager.error() == QMessageManager::NoError) { QStringList result; //! [generate-output] // Extract the requested data items from this message foreach (const QString &arg, dataOptions) { if (arg == "subject") { result.append(message.subject()); } else if (arg == "date") { result.append(message.date().toLocalTime().toString()); //! [generate-output] } else if (arg == "receivedDate") { result.append(message.receivedDate().toLocalTime().toString()); } else if (arg == "size") { result.append(QString::number(message.size())); } else if (arg == "priority") { result.append(message.priority() == QMessage::HighPriority ? "High" : (message.priority() == QMessage::LowPriority ? "Low" : "Normal")); } else if ((arg == "to") || (arg == "cc") || (arg == "bcc")) { QStringList addresses; foreach (const QMessageAddress &addr, (arg == "to" ? message.to() : (arg == "cc" ? message.cc() : message.bcc()))) { addresses.append(addr.addressee()); } result.append(addresses.join(",")); } else if (arg == "from") { result.append(message.from().addressee()); } else if (arg == "type") { result.append(message.contentType() + '/' + message.contentSubType()); } else if (arg == "body") { result.append(message.find(message.bodyId()).textContent()); } else if (arg == "status") { result.append(QString("0x%1").arg(QString::number(message.status()))); } else if (arg == "attachments") { QStringList fileNames; foreach (const QMessageContentContainerId &id, message.attachmentIds()) { fileNames.append(message.find(id).suggestedFileName()); } result.append(fileNames.join(",")); } } //! [print-result] printMessage(QString::number(++n) + '\t' + result.join("\t")); //! [print-result] } } if(matchingIds.isEmpty()) printMessage("No matching messages!"); return 0; }
/**************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation ([email protected]) ** ** This file is part of the Qt Mobility Components. ** ** $QT_BEGIN_LICENSE:BSD$ ** You may use this file under the terms of the BSD license as follows: ** ** "Redistribution and use in source and binary forms, with or without ** modification, are permitted provided that the following conditions are ** met: ** * Redistributions of source code must retain the above copyright ** notice, this list of conditions and the following disclaimer. ** * Redistributions in binary form must reproduce the above copyright ** notice, this list of conditions and the following disclaimer in ** the documentation and/or other materials provided with the ** distribution. ** * Neither the name of Nokia Corporation and its Subsidiary(-ies) nor ** the names of its contributors may be used to endorse or promote ** products derived from this software without specific prior written ** permission. ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." ** $QT_END_LICENSE$ ** ****************************************************************************/ #include <QCoreApplication> #include <qmessagemanager.h> #include <qdebug.h> #include <QMap> #ifdef Q_OS_SYMBIAN #include <iostream> #endif QTM_USE_NAMESPACE static void printMessage(const QString& msg) { #ifdef Q_OS_SYMBIAN std::cout << qPrintable(msg) << std::endl; #else qDebug() << qPrintable(msg); #endif } void usage() { QString msg("Usage: [<options>] [<datafields>]\n" " Where <options> limit the types of messages shown, valid choices: -all, -sms, -mms, -email, -instantmessage, -incoming, -read, -inboxfolder, -draftsfolder, -outboxfolder, -sentfolder, -trashfolder\n" " To join options by logical OR use +, for option, eg \"+sms +mms\" will return sms OR mms messages\n" " Where <datafields> specify what fields to print from matched messages, valid choices are: subject, date, receivedDate, status, size, priority, to, cc, bcc, from, type, body, attachments"); printMessage(msg); } // create message filter as requested by command line options QMessageFilter createFilter(QStringList args) { QMessageFilter filter(QMessageFilter::byStatus(QMessage::Incoming)); QMessageFilter customfilter; bool setCustomFilter = false; QMap<QString, QMessageFilter> filterMap; filterMap.insert(QLatin1String("all"), QMessageFilter()); filterMap.insert(QLatin1String("sms"), QMessageFilter::byType(QMessage::Sms)); filterMap.insert(QLatin1String("mms"), QMessageFilter::byType(QMessage::Mms)); filterMap.insert(QLatin1String("email"), QMessageFilter::byType(QMessage::Email)); filterMap.insert(QLatin1String("instantmessage"), QMessageFilter::byType(QMessage::InstantMessage)); filterMap.insert(QLatin1String("incoming"), QMessageFilter::byStatus(QMessage::Incoming)); filterMap.insert(QLatin1String("read"), QMessageFilter::byStatus(QMessage::Read)); filterMap.insert(QLatin1String("inboxfolder"), QMessageFilter::byStandardFolder(QMessage::InboxFolder)); filterMap.insert(QLatin1String("draftsfolder"), QMessageFilter::byStandardFolder(QMessage::DraftsFolder)); filterMap.insert(QLatin1String("outboxfolder"), QMessageFilter::byStandardFolder(QMessage::OutboxFolder)); filterMap.insert(QLatin1String("sentfolder"), QMessageFilter::byStandardFolder(QMessage::SentFolder)); filterMap.insert(QLatin1String("trashfolder"), QMessageFilter::byStandardFolder(QMessage::TrashFolder)); // process command line options after the application name foreach (const QString &arg, args.mid(1)){ QMap<QString, QMessageFilter>::const_iterator iterator = filterMap.find(arg.toLower().mid(1)); if (iterator != filterMap.end()){ setCustomFilter = true; // use AND logic when compounding filter? if (arg[0] == '-' ) customfilter = customfilter & iterator.value(); else customfilter = customfilter | iterator.value(); } } if (setCustomFilter) filter = customfilter; return filter; } int main(int argc, char *argv[]) { QCoreApplication app(argc, argv); printMessage("Querying messages..."); // determine what data options were requested and if help was requested // if no data options were provided default to "subject" QStringList dataOptions; QStringList validDataOptions = QStringList() << "subject" << "date" << "receivedDate" << "status" << "size" << "priority" << "to" << "cc" << "bcc" << "from" << "type" << "body" << "attachments"; foreach (const QString &arg, app.arguments()){ if (arg == "-help"){ usage(); exit(1); } if (validDataOptions.contains(arg)) dataOptions.append(arg); } if (dataOptions.isEmpty()) dataOptions.append("subject"); //! [setup-query] // Create filter to match required messages QMessageFilter filter = createFilter(app.arguments()); // instead of the above use the following for a simple filter of all messages whose status field have the Incoming flag to be set, eg incoming emails //QMessageFilter filter(QMessageFilter::byStatus(QMessage::Incoming)); // Order the matching results by their reception timestamp, in descending order QMessageSortOrder sortOrder(QMessageSortOrder::byReceptionTimeStamp(Qt::DescendingOrder)); //! [setup-query] //! [perform-query] // Acquire a handle to the message manager QMessageManager manager; // Find the matching message IDs, limiting our results to a managable number const int max = 100; const QMessageIdList matchingIds(manager.queryMessages(filter, sortOrder, max)); //! [perform-query] int n = 0; //! [iterate-results] // Retrieve each message and print requested details foreach (const QMessageId &id, matchingIds) { QMessage message(manager.message(id)); //! [iterate-results] if (manager.error() == QMessageManager::NoError) { QStringList result; //! [generate-output] // Extract the requested data items from this message foreach (const QString &arg, dataOptions) { if (arg == "subject") { result.append(message.subject()); } else if (arg == "date") { result.append(message.date().toLocalTime().toString()); //! [generate-output] } else if (arg == "receivedDate") { result.append(message.receivedDate().toLocalTime().toString()); } else if (arg == "size") { result.append(QString::number(message.size())); } else if (arg == "priority") { result.append(message.priority() == QMessage::HighPriority ? "High" : (message.priority() == QMessage::LowPriority ? "Low" : "Normal")); } else if ((arg == "to") || (arg == "cc") || (arg == "bcc")) { QStringList addresses; foreach (const QMessageAddress &addr, (arg == "to" ? message.to() : (arg == "cc" ? message.cc() : message.bcc()))) { addresses.append(addr.addressee()); } result.append(addresses.join(",")); } else if (arg == "from") { result.append(message.from().addressee()); } else if (arg == "type") { result.append(message.contentType() + '/' + message.contentSubType()); } else if (arg == "body") { result.append(message.find(message.bodyId()).textContent()); } else if (arg == "status") { result.append(QString::number(message.status())); } else if (arg == "attachments") { QStringList fileNames; foreach (const QMessageContentContainerId &id, message.attachmentIds()) { fileNames.append(message.find(id).suggestedFileName()); } result.append(fileNames.join(",")); } } //! [print-result] printMessage(QString::number(++n) + '\t' + result.join("\t")); //! [print-result] } } if(matchingIds.isEmpty()) printMessage("No matching messages!"); return 0; }
Remove spurious 0x.
Remove spurious 0x.
C++
lgpl-2.1
tmcguire/qt-mobility,qtproject/qt-mobility,kaltsi/qt-mobility,KDE/android-qt-mobility,qtproject/qt-mobility,kaltsi/qt-mobility,KDE/android-qt-mobility,enthought/qt-mobility,kaltsi/qt-mobility,enthought/qt-mobility,qtproject/qt-mobility,kaltsi/qt-mobility,enthought/qt-mobility,qtproject/qt-mobility,tmcguire/qt-mobility,tmcguire/qt-mobility,enthought/qt-mobility,enthought/qt-mobility,tmcguire/qt-mobility,KDE/android-qt-mobility,qtproject/qt-mobility,qtproject/qt-mobility,KDE/android-qt-mobility,kaltsi/qt-mobility,kaltsi/qt-mobility,enthought/qt-mobility,tmcguire/qt-mobility
a4f40c1b2422573ce0d17c4074ac1f36f9066b43
python/brotlimodule.cc
python/brotlimodule.cc
#define PY_SSIZE_T_CLEAN 1 #include <Python.h> #include <bytesobject.h> #include "../enc/encode.h" #include "../dec/decode.h" #include "../tools/version.h" #if PY_MAJOR_VERSION >= 3 #define PyInt_Check PyLong_Check #define PyInt_AsLong PyLong_AsLong #endif using namespace brotli; static PyObject *BrotliError; static int mode_convertor(PyObject *o, BrotliParams::Mode *mode) { if (!PyInt_Check(o)) { PyErr_SetString(BrotliError, "Invalid mode"); return 0; } *mode = (BrotliParams::Mode) PyInt_AsLong(o); if (*mode != BrotliParams::MODE_GENERIC && *mode != BrotliParams::MODE_TEXT && *mode != BrotliParams::MODE_FONT) { PyErr_SetString(BrotliError, "Invalid mode"); return 0; } return 1; } static int quality_convertor(PyObject *o, int *quality) { if (!PyInt_Check(o)) { PyErr_SetString(BrotliError, "Invalid quality"); return 0; } *quality = PyInt_AsLong(o); if (*quality < 0 || *quality > 11) { PyErr_SetString(BrotliError, "Invalid quality. Range is 0 to 11."); return 0; } return 1; } static int lgwin_convertor(PyObject *o, int *lgwin) { if (!PyInt_Check(o)) { PyErr_SetString(BrotliError, "Invalid lgwin"); return 0; } *lgwin = PyInt_AsLong(o); if (*lgwin < 10 || *lgwin > 24) { PyErr_SetString(BrotliError, "Invalid lgwin. Range is 10 to 24."); return 0; } return 1; } static int lgblock_convertor(PyObject *o, int *lgblock) { if (!PyInt_Check(o)) { PyErr_SetString(BrotliError, "Invalid lgblock"); return 0; } *lgblock = PyInt_AsLong(o); if ((*lgblock != 0 && *lgblock < 16) || *lgblock > 24) { PyErr_SetString(BrotliError, "Invalid lgblock. Can be 0 or in range 16 to 24."); return 0; } return 1; } PyDoc_STRVAR(compress__doc__, "Compress a byte string.\n" "\n" "Signature:\n" " compress(string, mode=MODE_GENERIC, quality=11, lgwin=22, lgblock=0)\n" "\n" "Args:\n" " string (bytes): The input data.\n" " mode (int, optional): The compression mode can be MODE_GENERIC (default),\n" " MODE_TEXT (for UTF-8 format text input) or MODE_FONT (for WOFF 2.0). \n" " quality (int, optional): Controls the compression-speed vs compression-\n" " density tradeoff. The higher the quality, the slower the compression.\n" " Range is 0 to 11. Defaults to 11.\n" " lgwin (int, optional): Base 2 logarithm of the sliding window size. Range\n" " is 10 to 24. Defaults to 22.\n" " lgblock (int, optional): Base 2 logarithm of the maximum input block size.\n" " Range is 16 to 24. If set to 0, the value will be set based on the\n" " quality. Defaults to 0.\n" "\n" "Returns:\n" " The compressed byte string.\n" "\n" "Raises:\n" " brotli.error: If arguments are invalid, or compressor fails.\n"); static PyObject* brotli_compress(PyObject *self, PyObject *args, PyObject *keywds) { PyObject *ret = NULL; uint8_t *input, *output; size_t length, output_length; BrotliParams::Mode mode = (BrotliParams::Mode) -1; int quality = -1; int lgwin = -1; int lgblock = -1; int ok; static const char *kwlist[] = {"string", "mode", "quality", "lgwin", "lgblock", NULL}; ok = PyArg_ParseTupleAndKeywords(args, keywds, "s#|O&O&O&O&:compress", const_cast<char **>(kwlist), &input, &length, &mode_convertor, &mode, &quality_convertor, &quality, &lgwin_convertor, &lgwin, &lgblock_convertor, &lgblock); if (!ok) return NULL; output_length = 1.2 * length + 10240; output = new uint8_t[output_length]; BrotliParams params; if (mode != -1) params.mode = mode; if (quality != -1) params.quality = quality; if (lgwin != -1) params.lgwin = lgwin; if (lgblock != -1) params.lgblock = lgblock; ok = BrotliCompressBuffer(params, length, input, &output_length, output); if (ok) { ret = PyBytes_FromStringAndSize((char*)output, output_length); } else { PyErr_SetString(BrotliError, "BrotliCompressBuffer failed"); } delete[] output; return ret; } PyDoc_STRVAR(decompress__doc__, "Decompress a compressed byte string.\n" "\n" "Signature:\n" " decompress(string)\n" "\n" "Args:\n" " string (bytes): The compressed input data.\n" "\n" "Returns:\n" " The decompressed byte string.\n" "\n" "Raises:\n" " brotli.error: If decompressor fails.\n"); static PyObject* brotli_decompress(PyObject *self, PyObject *args) { PyObject *ret = NULL; const uint8_t *input; size_t length; int ok; ok = PyArg_ParseTuple(args, "s#:decompress", &input, &length); if (!ok) return NULL; std::vector<uint8_t> output; const size_t kBufferSize = 65536; uint8_t* buffer = new uint8_t[kBufferSize]; BrotliState state; BrotliStateInit(&state); BrotliResult result = BROTLI_RESULT_NEEDS_MORE_OUTPUT; while (result == BROTLI_RESULT_NEEDS_MORE_OUTPUT) { size_t available_out = kBufferSize; uint8_t* next_out = buffer; size_t total_out = 0; result = BrotliDecompressStream(&length, &input, &available_out, &next_out, &total_out, &state); size_t used_out = kBufferSize - available_out; if (used_out != 0) output.insert(output.end(), buffer, buffer + used_out); } ok = result == BROTLI_RESULT_SUCCESS; if (ok) { ret = PyBytes_FromStringAndSize((char*)(output.size() ? &output[0] : NULL), output.size()); } else { PyErr_SetString(BrotliError, "BrotliDecompress failed"); } BrotliStateCleanup(&state); delete[] buffer; return ret; } static PyMethodDef brotli_methods[] = { {"compress", (PyCFunction)brotli_compress, METH_VARARGS | METH_KEYWORDS, compress__doc__}, {"decompress", brotli_decompress, METH_VARARGS, decompress__doc__}, {NULL, NULL, 0, NULL} }; PyDoc_STRVAR(brotli__doc__, "The functions in this module allow compression and decompression using the\n" "Brotli library.\n\n"); #if PY_MAJOR_VERSION >= 3 #define INIT_BROTLI PyInit_brotli #define CREATE_BROTLI PyModule_Create(&brotli_module) #define RETURN_BROTLI return m static struct PyModuleDef brotli_module = { PyModuleDef_HEAD_INIT, "brotli", brotli__doc__, 0, brotli_methods, NULL, NULL, NULL }; #else #define INIT_BROTLI initbrotli #define CREATE_BROTLI Py_InitModule3("brotli", brotli_methods, brotli__doc__) #define RETURN_BROTLI return #endif PyMODINIT_FUNC INIT_BROTLI(void) { PyObject *m = CREATE_BROTLI; BrotliError = PyErr_NewException((char*) "brotli.error", NULL, NULL); if (BrotliError != NULL) { Py_INCREF(BrotliError); PyModule_AddObject(m, "error", BrotliError); } PyModule_AddIntConstant(m, "MODE_GENERIC", (int) BrotliParams::MODE_GENERIC); PyModule_AddIntConstant(m, "MODE_TEXT", (int) BrotliParams::MODE_TEXT); PyModule_AddIntConstant(m, "MODE_FONT", (int) BrotliParams::MODE_FONT); PyModule_AddStringConstant(m, "__version__", BROTLI_VERSION); RETURN_BROTLI; }
#define PY_SSIZE_T_CLEAN 1 #include <Python.h> #include <bytesobject.h> #include "../enc/encode.h" #include "../dec/decode.h" #include "../tools/version.h" #if PY_MAJOR_VERSION >= 3 #define PyInt_Check PyLong_Check #define PyInt_AsLong PyLong_AsLong #endif using namespace brotli; static PyObject *BrotliError; static int as_uint8(PyObject *o, int* result) { long value = PyInt_AsLong(o); if (value < 0 || value > 255) { return 0; } *result = (int) value; } static int mode_convertor(PyObject *o, BrotliParams::Mode *mode) { if (!PyInt_Check(o)) { PyErr_SetString(BrotliError, "Invalid mode"); return 0; } if (!as_uint8(o, mode) || (*mode != BrotliParams::MODE_GENERIC && *mode != BrotliParams::MODE_TEXT && *mode != BrotliParams::MODE_FONT)) { PyErr_SetString(BrotliError, "Invalid mode"); return 0; } return 1; } static int quality_convertor(PyObject *o, int *quality) { if (!PyInt_Check(o)) { PyErr_SetString(BrotliError, "Invalid quality"); return 0; } if (!as_uint8(o, quality) || *quality > 11) { PyErr_SetString(BrotliError, "Invalid quality. Range is 0 to 11."); return 0; } return 1; } static int lgwin_convertor(PyObject *o, int *lgwin) { if (!PyInt_Check(o)) { PyErr_SetString(BrotliError, "Invalid lgwin"); return 0; } if (!as_uint8(o, lgwin) || *lgwin < 10 || *lgwin > 24) { PyErr_SetString(BrotliError, "Invalid lgwin. Range is 10 to 24."); return 0; } return 1; } static int lgblock_convertor(PyObject *o, int *lgblock) { if (!PyInt_Check(o)) { PyErr_SetString(BrotliError, "Invalid lgblock"); return 0; } if (!as_uint8(o, lgblock) || (*lgblock != 0 && *lgblock < 16) || *lgblock > 24) { PyErr_SetString(BrotliError, "Invalid lgblock. Can be 0 or in range 16 to 24."); return 0; } return 1; } PyDoc_STRVAR(compress__doc__, "Compress a byte string.\n" "\n" "Signature:\n" " compress(string, mode=MODE_GENERIC, quality=11, lgwin=22, lgblock=0)\n" "\n" "Args:\n" " string (bytes): The input data.\n" " mode (int, optional): The compression mode can be MODE_GENERIC (default),\n" " MODE_TEXT (for UTF-8 format text input) or MODE_FONT (for WOFF 2.0). \n" " quality (int, optional): Controls the compression-speed vs compression-\n" " density tradeoff. The higher the quality, the slower the compression.\n" " Range is 0 to 11. Defaults to 11.\n" " lgwin (int, optional): Base 2 logarithm of the sliding window size. Range\n" " is 10 to 24. Defaults to 22.\n" " lgblock (int, optional): Base 2 logarithm of the maximum input block size.\n" " Range is 16 to 24. If set to 0, the value will be set based on the\n" " quality. Defaults to 0.\n" "\n" "Returns:\n" " The compressed byte string.\n" "\n" "Raises:\n" " brotli.error: If arguments are invalid, or compressor fails.\n"); static PyObject* brotli_compress(PyObject *self, PyObject *args, PyObject *keywds) { PyObject *ret = NULL; uint8_t *input, *output; size_t length, output_length; BrotliParams::Mode mode = (BrotliParams::Mode) -1; int quality = -1; int lgwin = -1; int lgblock = -1; int ok; static const char *kwlist[] = {"string", "mode", "quality", "lgwin", "lgblock", NULL}; ok = PyArg_ParseTupleAndKeywords(args, keywds, "s#|O&O&O&O&:compress", const_cast<char **>(kwlist), &input, &length, &mode_convertor, &mode, &quality_convertor, &quality, &lgwin_convertor, &lgwin, &lgblock_convertor, &lgblock); if (!ok) return NULL; output_length = length + (length >> 2) + 10240; output = new uint8_t[output_length]; BrotliParams params; if ((int) mode != -1) params.mode = mode; if (quality != -1) params.quality = quality; if (lgwin != -1) params.lgwin = lgwin; if (lgblock != -1) params.lgblock = lgblock; ok = BrotliCompressBuffer(params, length, input, &output_length, output); if (ok) { ret = PyBytes_FromStringAndSize((char*)output, output_length); } else { PyErr_SetString(BrotliError, "BrotliCompressBuffer failed"); } delete[] output; return ret; } PyDoc_STRVAR(decompress__doc__, "Decompress a compressed byte string.\n" "\n" "Signature:\n" " decompress(string)\n" "\n" "Args:\n" " string (bytes): The compressed input data.\n" "\n" "Returns:\n" " The decompressed byte string.\n" "\n" "Raises:\n" " brotli.error: If decompressor fails.\n"); static PyObject* brotli_decompress(PyObject *self, PyObject *args) { PyObject *ret = NULL; const uint8_t *input; size_t length; int ok; ok = PyArg_ParseTuple(args, "s#:decompress", &input, &length); if (!ok) return NULL; std::vector<uint8_t> output; const size_t kBufferSize = 65536; uint8_t* buffer = new uint8_t[kBufferSize]; BrotliState state; BrotliStateInit(&state); BrotliResult result = BROTLI_RESULT_NEEDS_MORE_OUTPUT; while (result == BROTLI_RESULT_NEEDS_MORE_OUTPUT) { size_t available_out = kBufferSize; uint8_t* next_out = buffer; size_t total_out = 0; result = BrotliDecompressStream(&length, &input, &available_out, &next_out, &total_out, &state); size_t used_out = kBufferSize - available_out; if (used_out != 0) output.insert(output.end(), buffer, buffer + used_out); } ok = result == BROTLI_RESULT_SUCCESS; if (ok) { ret = PyBytes_FromStringAndSize((char*)(output.size() ? &output[0] : NULL), output.size()); } else { PyErr_SetString(BrotliError, "BrotliDecompress failed"); } BrotliStateCleanup(&state); delete[] buffer; return ret; } static PyMethodDef brotli_methods[] = { {"compress", (PyCFunction)brotli_compress, METH_VARARGS | METH_KEYWORDS, compress__doc__}, {"decompress", brotli_decompress, METH_VARARGS, decompress__doc__}, {NULL, NULL, 0, NULL} }; PyDoc_STRVAR(brotli__doc__, "The functions in this module allow compression and decompression using the\n" "Brotli library.\n\n"); #if PY_MAJOR_VERSION >= 3 #define INIT_BROTLI PyInit_brotli #define CREATE_BROTLI PyModule_Create(&brotli_module) #define RETURN_BROTLI return m static struct PyModuleDef brotli_module = { PyModuleDef_HEAD_INIT, "brotli", brotli__doc__, 0, brotli_methods, NULL, NULL, NULL }; #else #define INIT_BROTLI initbrotli #define CREATE_BROTLI Py_InitModule3("brotli", brotli_methods, brotli__doc__) #define RETURN_BROTLI return #endif PyMODINIT_FUNC INIT_BROTLI(void) { PyObject *m = CREATE_BROTLI; BrotliError = PyErr_NewException((char*) "brotli.error", NULL, NULL); if (BrotliError != NULL) { Py_INCREF(BrotliError); PyModule_AddObject(m, "error", BrotliError); } PyModule_AddIntConstant(m, "MODE_GENERIC", (int) BrotliParams::MODE_GENERIC); PyModule_AddIntConstant(m, "MODE_TEXT", (int) BrotliParams::MODE_TEXT); PyModule_AddIntConstant(m, "MODE_FONT", (int) BrotliParams::MODE_FONT); PyModule_AddStringConstant(m, "__version__", BROTLI_VERSION); RETURN_BROTLI; }
Fix brotlimodule compilation warnings
Fix brotlimodule compilation warnings
C++
mit
google/brotli,anthrotype/brotli,smourier/brotli,szabadka/brotli,nicksay/brotli,nicksay/brotli,google/brotli,anthrotype/brotli,smourier/brotli,szabadka/brotli,smourier/brotli,nicksay/brotli,smourier/brotli,szabadka/brotli,nicksay/brotli,nicksay/brotli,anthrotype/brotli,nicksay/brotli,google/brotli,nicksay/brotli,anthrotype/brotli,google/brotli,google/brotli,szabadka/brotli,smourier/brotli,google/brotli,google/brotli,anthrotype/brotli,google/brotli
7c750a855a02eef9823eeab7360866206a65c17d
dali/internal/system/common/command-line-options.cpp
dali/internal/system/common/command-line-options.cpp
/* * Copyright (c) 2018 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ // CLASS HEADER #include <dali/internal/system/common/command-line-options.h> // EXTERNAL INCLUDES #include <getopt.h> #include <stdlib.h> #include <string.h> #include <iostream> #include <dali/public-api/common/dali-vector.h> namespace Dali { namespace Internal { namespace Adaptor { namespace { struct Argument { const char * const opt; const char * const optDescription; void Print() { const std::ios_base::fmtflags flags = std::cout.flags(); std::cout << std::left << " --"; std::cout.width( 18 ); std::cout << opt; std::cout << optDescription; std::cout << std::endl; std::cout.flags( flags ); } }; Argument EXPECTED_ARGS[] = { { "width", "Stage Width" }, { "height", "Stage Height" }, { "dpi", "Emulated DPI" }, { "help", "Help" }, { NULL, NULL } }; enum Option { OPTION_STAGE_WIDTH = 0, OPTION_STAGE_HEIGHT, OPTION_DPI, OPTION_HELP }; typedef Dali::Vector< int32_t > UnhandledContainer; void ShowHelp() { std::cout << "Available options:" << std::endl; Argument* arg = EXPECTED_ARGS; while ( arg->opt ) { arg->Print(); ++arg; } } } // unnamed namespace CommandLineOptions::CommandLineOptions(int32_t *argc, char **argv[]) : stageWidth(0), stageHeight(0) { // Exit gracefully if no arguments provided if ( !argc || !argv ) { return; } if ( *argc > 1 ) { // We do not want to print out errors. int32_t origOptErrValue( opterr ); opterr = 0; int32_t help( 0 ); const struct option options[]= { { EXPECTED_ARGS[OPTION_STAGE_WIDTH].opt, required_argument, NULL, 'w' }, // "--width" { EXPECTED_ARGS[OPTION_STAGE_HEIGHT].opt, required_argument, NULL, 'h' }, // "--height" { EXPECTED_ARGS[OPTION_DPI].opt, required_argument, NULL, 'd' }, // "--dpi" { EXPECTED_ARGS[OPTION_HELP].opt, no_argument, &help, '?' }, // "--help" { 0, 0, 0, 0 } // end of options }; int32_t shortOption( 0 ); int32_t optionIndex( 0 ); const char* optString = "-w:h:d:"; // The '-' ensures that argv is NOT permuted bool optionProcessed( false ); UnhandledContainer unhandledOptions; // We store indices of options we do not handle here do { shortOption = getopt_long( *argc, *argv, optString, options, &optionIndex ); switch ( shortOption ) { case 0: { // Check if we want help if ( help ) { ShowHelp(); optionProcessed = true; } break; } case 'w': { if ( optarg ) { stageWidth = atoi( optarg ); optionProcessed = true; } break; } case 'h': { if ( optarg ) { stageHeight = atoi( optarg ); optionProcessed = true; } break; } case 'd': { if ( optarg ) { stageDPI.assign( optarg ); optionProcessed = true; } break; } case -1: { // All command-line options have been parsed. break; } default: { unhandledOptions.PushBack( optind - 1 ); break; } } } while ( shortOption != -1 ); // Take out the options we have processed if ( optionProcessed ) { if ( unhandledOptions.Count() > 0 ) { int32_t index( 1 ); // Overwrite the argv with the values from the unhandled indices const UnhandledContainer::ConstIterator endIter = unhandledOptions.End(); for ( UnhandledContainer::Iterator iter = unhandledOptions.Begin(); iter != endIter; ++iter ) { (*argv)[ index++ ] = (*argv)[ *iter ]; } *argc = unhandledOptions.Count() + 1; // +1 for the program name } else { // There are no unhandled options, so we should just have the program name *argc = 1; } optind = 1; // Reset to start } opterr = origOptErrValue; // Reset opterr value. } } CommandLineOptions::~CommandLineOptions() { } } // namespace Adaptor } // namespace Internal } // namespace Dali
/* * Copyright (c) 2018 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ // CLASS HEADER #include <dali/internal/system/common/command-line-options.h> // EXTERNAL INCLUDES #include <stdlib.h> #include <string.h> #include <iostream> #include <dali/public-api/common/dali-vector.h> #include <getopt.h> namespace Dali { namespace Internal { namespace Adaptor { namespace { struct Argument { const char * const opt; const char * const optDescription; void Print() { const std::ios_base::fmtflags flags = std::cout.flags(); std::cout << std::left << " --"; std::cout.width( 18 ); std::cout << opt; std::cout << optDescription; std::cout << std::endl; std::cout.flags( flags ); } }; Argument EXPECTED_ARGS[] = { { "width", "Stage Width" }, { "height", "Stage Height" }, { "dpi", "Emulated DPI" }, { "help", "Help" }, { NULL, NULL } }; enum Option { OPTION_STAGE_WIDTH = 0, OPTION_STAGE_HEIGHT, OPTION_DPI, OPTION_HELP }; typedef Dali::Vector< int32_t > UnhandledContainer; void ShowHelp() { std::cout << "Available options:" << std::endl; Argument* arg = EXPECTED_ARGS; while ( arg->opt ) { arg->Print(); ++arg; } } } // unnamed namespace CommandLineOptions::CommandLineOptions(int32_t *argc, char **argv[]) : stageWidth(0), stageHeight(0) { // Exit gracefully if no arguments provided if ( !argc || !argv ) { return; } if ( *argc > 1 ) { // We do not want to print out errors. int32_t origOptErrValue( opterr ); opterr = 0; int32_t help( 0 ); const struct option options[]= { { EXPECTED_ARGS[OPTION_STAGE_WIDTH].opt, required_argument, NULL, 'w' }, // "--width" { EXPECTED_ARGS[OPTION_STAGE_HEIGHT].opt, required_argument, NULL, 'h' }, // "--height" { EXPECTED_ARGS[OPTION_DPI].opt, required_argument, NULL, 'd' }, // "--dpi" { EXPECTED_ARGS[OPTION_HELP].opt, no_argument, &help, '?' }, // "--help" { 0, 0, 0, 0 } // end of options }; int32_t shortOption( 0 ); int32_t optionIndex( 0 ); const char* optString = "-w:h:d:"; // The '-' ensures that argv is NOT permuted bool optionProcessed( false ); UnhandledContainer unhandledOptions; // We store indices of options we do not handle here do { shortOption = getopt_long( *argc, *argv, optString, options, &optionIndex ); switch ( shortOption ) { case 0: { // Check if we want help if ( help ) { ShowHelp(); optionProcessed = true; } break; } case 'w': { if ( optarg ) { stageWidth = atoi( optarg ); optionProcessed = true; } break; } case 'h': { if ( optarg ) { stageHeight = atoi( optarg ); optionProcessed = true; } break; } case 'd': { if ( optarg ) { stageDPI.assign( optarg ); optionProcessed = true; } break; } case -1: { // All command-line options have been parsed. break; } default: { unhandledOptions.PushBack( optind - 1 ); break; } } } while ( shortOption != -1 ); // Take out the options we have processed if ( optionProcessed ) { if ( unhandledOptions.Count() > 0 ) { int32_t index( 1 ); // Overwrite the argv with the values from the unhandled indices const UnhandledContainer::ConstIterator endIter = unhandledOptions.End(); for ( UnhandledContainer::Iterator iter = unhandledOptions.Begin(); iter != endIter; ++iter ) { (*argv)[ index++ ] = (*argv)[ *iter ]; } *argc = unhandledOptions.Count() + 1; // +1 for the program name } else { // There are no unhandled options, so we should just have the program name *argc = 1; } optind = 1; // Reset to start } opterr = origOptErrValue; // Reset opterr value. } } CommandLineOptions::~CommandLineOptions() { } } // namespace Adaptor } // namespace Internal } // namespace Dali
Move getopt.h include file to the bottom
windows: Move getopt.h include file to the bottom getopt-win32 defines the symbol _END_EXTERN_C and undefines at the end of the file. It turns out msvc standard library defines this same symbol. If getopt.h is included before C++ standard includes, it will undef _END_EXTERN_C and causes compilation errors under msvc. We move the getopt.h to the end of the list of include files so it can't mess up with internal msvcrt symbols. Change-Id: I404ca48d096703d0be6b5f466402fb2ca0223033
C++
apache-2.0
dalihub/dali-adaptor,dalihub/dali-adaptor,dalihub/dali-adaptor,dalihub/dali-adaptor,dalihub/dali-adaptor
819c5c9dcd4be568900ddde5567cfdcd2f47bdd2
sdc-plugin/clocks.cc
sdc-plugin/clocks.cc
/* * yosys -- Yosys Open SYnthesis Suite * * Copyright (C) 2020 The Symbiflow Authors * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include "clocks.h" #include <cassert> #include <cmath> #include <regex> #include "kernel/register.h" #include "propagation.h" void Clock::Add(const std::string& name, RTLIL::Wire* wire, float period, float rising_edge, float falling_edge) { wire->set_string_attribute(RTLIL::escape_id("CLOCK_SIGNAL"), "yes"); wire->set_string_attribute(RTLIL::escape_id("CLASS"), "clock"); wire->set_string_attribute(RTLIL::escape_id("NAME"), name); wire->set_string_attribute(RTLIL::escape_id("SOURCE_PINS"), Clock::WireName(wire)); wire->set_string_attribute(RTLIL::escape_id("PERIOD"), std::to_string(period)); std::string waveform(std::to_string(rising_edge) + " " + std::to_string(falling_edge)); wire->set_string_attribute(RTLIL::escape_id("WAVEFORM"), waveform); } void Clock::Add(const std::string& name, std::vector<RTLIL::Wire*> wires, float period, float rising_edge, float falling_edge) { std::for_each(wires.begin(), wires.end(), [&](RTLIL::Wire* wire) { Add(name, wire, period, rising_edge, falling_edge); }); } void Clock::Add(RTLIL::Wire* wire, float period, float rising_edge, float falling_edge) { Add(Clock::WireName(wire), wire, period, rising_edge, falling_edge); } float Clock::Period(RTLIL::Wire* clock_wire) { if (!clock_wire->has_attribute(RTLIL::escape_id("PERIOD"))) { log_warning( "Period has not been specified\n Default value 0 will be used\n"); return 0; } return std::stof( clock_wire->get_string_attribute(RTLIL::escape_id("PERIOD"))); } std::pair<float, float> Clock::Waveform(RTLIL::Wire* clock_wire) { if (!clock_wire->has_attribute(RTLIL::escape_id("WAVEFORM"))) { float period(Period(clock_wire)); if (!period) { log_cmd_error( "Neither PERIOD nor WAVEFORM has been specified for wire %s\n", WireName(clock_wire).c_str()); return std::make_pair(0, 0); } float falling_edge = period / 2; log_warning( "Waveform has not been specified\n Default value {0 %f} will be " "used\n", falling_edge); return std::make_pair(0, falling_edge); } float rising_edge(0); float falling_edge(0); std::string waveform( clock_wire->get_string_attribute(RTLIL::escape_id("WAVEFORM"))); std::sscanf(waveform.c_str(), "%f %f", &rising_edge, &falling_edge); return std::make_pair(rising_edge, falling_edge); } float Clock::RisingEdge(RTLIL::Wire* clock_wire) { return Waveform(clock_wire).first; } float Clock::FallingEdge(RTLIL::Wire* clock_wire) { return Waveform(clock_wire).second; } std::string Clock::Name(RTLIL::Wire* clock_wire) { if (clock_wire->has_attribute(RTLIL::escape_id("NAME"))) { return clock_wire->get_string_attribute(RTLIL::escape_id("NAME")); } return WireName(clock_wire); } std::string Clock::WireName(RTLIL::Wire* wire) { if (!wire) { return std::string(); } std::string wire_name(RTLIL::unescape_id(wire->name)); return std::regex_replace(wire_name, std::regex{"\\$"}, "\\$"); } const std::map<std::string, RTLIL::Wire*> Clocks::GetClocks(RTLIL::Design* design) { std::map<std::string, RTLIL::Wire*> clock_wires; RTLIL::Module* top_module = design->top_module(); for (auto& wire_obj : top_module->wires_) { auto& wire = wire_obj.second; if (wire->has_attribute(RTLIL::escape_id("CLOCK_SIGNAL"))) { if (wire->get_string_attribute(RTLIL::escape_id("CLOCK_SIGNAL")) == "yes") { clock_wires.insert(std::make_pair(Clock::WireName(wire), wire)); } } } return clock_wires; }
/* * yosys -- Yosys Open SYnthesis Suite * * Copyright (C) 2020 The Symbiflow Authors * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include "clocks.h" #include <cassert> #include <cmath> #include <regex> #include "kernel/register.h" #include "propagation.h" void Clock::Add(const std::string& name, RTLIL::Wire* wire, float period, float rising_edge, float falling_edge) { wire->set_string_attribute(RTLIL::escape_id("CLOCK_SIGNAL"), "yes"); wire->set_string_attribute(RTLIL::escape_id("CLASS"), "clock"); wire->set_string_attribute(RTLIL::escape_id("NAME"), name); wire->set_string_attribute(RTLIL::escape_id("SOURCE_PINS"), Clock::WireName(wire)); wire->set_string_attribute(RTLIL::escape_id("PERIOD"), std::to_string(period)); std::string waveform(std::to_string(rising_edge) + " " + std::to_string(falling_edge)); wire->set_string_attribute(RTLIL::escape_id("WAVEFORM"), waveform); } void Clock::Add(const std::string& name, std::vector<RTLIL::Wire*> wires, float period, float rising_edge, float falling_edge) { std::for_each(wires.begin(), wires.end(), [&](RTLIL::Wire* wire) { Add(name, wire, period, rising_edge, falling_edge); }); } void Clock::Add(RTLIL::Wire* wire, float period, float rising_edge, float falling_edge) { Add(Clock::WireName(wire), wire, period, rising_edge, falling_edge); } float Clock::Period(RTLIL::Wire* clock_wire) { if (!clock_wire->has_attribute(RTLIL::escape_id("PERIOD"))) { log_warning( "Period has not been specified\n Default value 0 will be used\n"); return 0; } float period(0); try { period = std::stof(clock_wire->get_string_attribute(RTLIL::escape_id("PERIOD"))); } catch (const std::invalid_argument& e) { log_cmd_error("Incorrect PERIOD format\n"); } return period; } std::pair<float, float> Clock::Waveform(RTLIL::Wire* clock_wire) { if (!clock_wire->has_attribute(RTLIL::escape_id("WAVEFORM"))) { float period(Period(clock_wire)); if (!period) { log_cmd_error( "Neither PERIOD nor WAVEFORM has been specified for wire %s\n", WireName(clock_wire).c_str()); return std::make_pair(0, 0); } float falling_edge = period / 2; log_warning( "Waveform has not been specified\n Default value {0 %f} will be " "used\n", falling_edge); return std::make_pair(0, falling_edge); } float rising_edge(0); float falling_edge(0); std::string waveform( clock_wire->get_string_attribute(RTLIL::escape_id("WAVEFORM"))); if (std::sscanf(waveform.c_str(), "%f %f", &rising_edge, &falling_edge) != 2) { log_cmd_error("Incorrect WAVEFORM format\n"); } return std::make_pair(rising_edge, falling_edge); } float Clock::RisingEdge(RTLIL::Wire* clock_wire) { return Waveform(clock_wire).first; } float Clock::FallingEdge(RTLIL::Wire* clock_wire) { return Waveform(clock_wire).second; } std::string Clock::Name(RTLIL::Wire* clock_wire) { if (clock_wire->has_attribute(RTLIL::escape_id("NAME"))) { return clock_wire->get_string_attribute(RTLIL::escape_id("NAME")); } return WireName(clock_wire); } std::string Clock::WireName(RTLIL::Wire* wire) { if (!wire) { return std::string(); } std::string wire_name(RTLIL::unescape_id(wire->name)); return std::regex_replace(wire_name, std::regex{"\\$"}, "\\$"); } const std::map<std::string, RTLIL::Wire*> Clocks::GetClocks(RTLIL::Design* design) { std::map<std::string, RTLIL::Wire*> clock_wires; RTLIL::Module* top_module = design->top_module(); for (auto& wire_obj : top_module->wires_) { auto& wire = wire_obj.second; if (wire->has_attribute(RTLIL::escape_id("CLOCK_SIGNAL"))) { if (wire->get_string_attribute(RTLIL::escape_id("CLOCK_SIGNAL")) == "yes") { clock_wires.insert(std::make_pair(Clock::WireName(wire), wire)); } } } return clock_wires; }
Add period and waveform format error checks
SDC: Add period and waveform format error checks Signed-off-by: Tomasz Michalak <[email protected]>
C++
apache-2.0
chipsalliance/yosys-f4pga-plugins,SymbiFlow/yosys-f4pga-plugins,chipsalliance/yosys-f4pga-plugins,SymbiFlow/yosys-symbiflow-plugins,SymbiFlow/yosys-f4pga-plugins,SymbiFlow/yosys-symbiflow-plugins,antmicro/yosys-symbiflow-plugins,antmicro/yosys-symbiflow-plugins,SymbiFlow/yosys-f4pga-plugins,antmicro/yosys-symbiflow-plugins,SymbiFlow/yosys-symbiflow-plugins
b79726cb41bd4c094d8b6f82e2faacd4cbd1d1e0
debug_layer/varun_gazebo/src/varun_motion_plugin.cpp
debug_layer/varun_gazebo/src/varun_motion_plugin.cpp
// Copyright 2016 AUV-IITK #include <gazebo/common/Plugin.hh> #include <geometry_msgs/Wrench.h> #include <std_msgs/Int32.h> #include <ros/ros.h> #include <gazebo/gazebo.hh> #include <gazebo/physics/physics.hh> #include <gazebo/transport/transport.hh> #include <gazebo/msgs/msgs.hh> #include <gazebo/math/gzmath.hh> const float THRUSTER_FORCE = 9.8; // each thruster applies 1kgf. Gazebo uses SI units const float FULL_FORCE = THRUSTER_FORCE * 2; namespace gazebo { class VarunMotionPlugin : public WorldPlugin { private: ros::NodeHandle* _nh; ros::Subscriber _subPwmForward; ros::Subscriber _subPwmSideward; ros::Subscriber _subPwmUpward; ros::Subscriber _subPwmTurn; gazebo::physics::ModelPtr _model; public: VarunMotionPlugin() : WorldPlugin() { _nh = new ros::NodeHandle(""); // subscribe to motion library _subPwmForward = _nh->subscribe("/pwm/forward", 1, &VarunMotionPlugin::PWMCbForward, this); _subPwmSideward = _nh->subscribe("/pwm/sideward", 1, &VarunMotionPlugin::PWMCbSideward, this); _subPwmUpward = _nh->subscribe("/pwm/upward", 1, &VarunMotionPlugin::PWMCbUpward, this); _subPwmTurn = _nh->subscribe("/pwm/turn", 1, &VarunMotionPlugin::PWMCbTurn, this); } void Load(physics::WorldPtr _world, sdf::ElementPtr _sdf) { // Make sure the ROS node for Gazebo has already been initialized if (!ros::isInitialized()) { ROS_FATAL_STREAM("A ROS node for Gazebo has not been initialized, unable to load plugin. " << "Load the Gazebo system plugin 'libgazebo_ros_api_plugin.so' in the gazebo_ros package)"); return; } ROS_INFO("Varun Motion Plugin loaded"); // Getting model for varun _model = _world->GetModel("varun"); } void PWMCbForward(const std_msgs::Int32& msg) { math::Vector3 force; math::Vector3 reset_force; int pwm = msg.data; force.x = FULL_FORCE * pwm / 255; _model->GetLink("body")->SetForce(reset_force); _model->GetLink("body")->AddRelativeForce(force); } void PWMCbSideward(const std_msgs::Int32& msg) { math::Vector3 force; math::Vector3 reset_force; int pwm = msg.data; pwm = -pwm; // this is because motionlibrary assumes right to be positive while gazebo y axis points to left. force.y = FULL_FORCE * pwm / 255; _model->GetLink("body")->SetForce(reset_force); _model->GetLink("body")->AddRelativeForce(force); } void PWMCbUpward(const std_msgs::Int32& msg) { math::Vector3 force; int pwm = msg.data; force.z = FULL_FORCE * pwm / 255; _model->GetLink("body")->SetForce(force); } void PWMCbTurn(const std_msgs::Int32& msg) { math::Vector3 torque; int pwm = msg.data; torque.z = FULL_FORCE * pwm / 255; _model->GetLink("body")->SetTorque(torque); } }; GZ_REGISTER_WORLD_PLUGIN(VarunMotionPlugin) } // namespace gazebo
// Copyright 2016 AUV-IITK #include <gazebo/common/Plugin.hh> #include <geometry_msgs/Wrench.h> #include <std_msgs/Int32.h> #include <ros/ros.h> #include <gazebo/gazebo.hh> #include <gazebo/physics/physics.hh> #include <gazebo/transport/transport.hh> #include <gazebo/msgs/msgs.hh> #include <gazebo/math/gzmath.hh> const float THRUSTER_FORCE = 9.8; // each thruster applies 1kgf. Gazebo uses SI units const float FULL_FORCE = THRUSTER_FORCE * 2; const float VARUN_SIDEWARD_LENGTH = 0.16; const float ERROR_FACTOR = 100; namespace gazebo { class VarunMotionPlugin : public WorldPlugin { private: ros::NodeHandle* _nh; ros::Subscriber _subPwmForward; ros::Subscriber _subPwmSideward; ros::Subscriber _subPwmUpward; ros::Subscriber _subPwmTurn; gazebo::physics::ModelPtr _model; public: VarunMotionPlugin() : WorldPlugin() { _nh = new ros::NodeHandle(""); // subscribe to motion library _subPwmForward = _nh->subscribe("/pwm/forward", 1, &VarunMotionPlugin::PWMCbForward, this); _subPwmSideward = _nh->subscribe("/pwm/sideward", 1, &VarunMotionPlugin::PWMCbSideward, this); _subPwmUpward = _nh->subscribe("/pwm/upward", 1, &VarunMotionPlugin::PWMCbUpward, this); _subPwmTurn = _nh->subscribe("/pwm/turn", 1, &VarunMotionPlugin::PWMCbTurn, this); } void Load(physics::WorldPtr _world, sdf::ElementPtr _sdf) { // Make sure the ROS node for Gazebo has already been initialized if (!ros::isInitialized()) { ROS_FATAL_STREAM("A ROS node for Gazebo has not been initialized, unable to load plugin. " << "Load the Gazebo system plugin 'libgazebo_ros_api_plugin.so' in the gazebo_ros package)"); return; } ROS_INFO("Varun Motion Plugin loaded"); // Getting model for varun _model = _world->GetModel("varun"); } void PWMCbForward(const std_msgs::Int32& msg) { math::Vector3 force; math::Vector3 reset_force; int pwm = msg.data; force.x = FULL_FORCE * pwm / 255 * ERROR_FACTOR; _model->GetLink("body")->SetForce(reset_force); _model->GetLink("body")->AddRelativeForce(force); } void PWMCbSideward(const std_msgs::Int32& msg) { math::Vector3 force; math::Vector3 reset_force; int pwm = msg.data; pwm = -pwm; // this is because motionlibrary assumes right to be positive while gazebo y axis points to left. force.y = FULL_FORCE * pwm / 255 * ERROR_FACTOR; _model->GetLink("body")->SetForce(reset_force); _model->GetLink("body")->AddRelativeForce(force); } void PWMCbUpward(const std_msgs::Int32& msg) { math::Vector3 force; int pwm = msg.data; force.z = FULL_FORCE * pwm / 255 * ERROR_FACTOR; _model->GetLink("body")->SetForce(force); } void PWMCbTurn(const std_msgs::Int32& msg) { math::Vector3 torque; int pwm = msg.data; torque.z = FULL_FORCE * (pwm / 255) * (VARUN_SIDEWARD_LENGTH / 2) * ERROR_FACTOR; _model->GetLink("body")->SetTorque(torque); } }; GZ_REGISTER_WORLD_PLUGIN(VarunMotionPlugin) } // namespace gazebo
Add error factor to varun motion plugin
Add error factor to varun motion plugin Calculated the expected linear acceleration and angular acceleration, added error factor so that imu output matched expected values. Error is because mass and inertia of varun in model.sdf have slight error.
C++
bsd-3-clause
AUV-IITK/auv,AUV-IITK/auv,AUV-IITK/auv,ShikherVerma/auv,ShikherVerma/auv,ShikherVerma/auv
c854daf6110644ba5dd0a29b101c1907f037783a
runtime/vm/thread_interrupter_fuchsia.cc
runtime/vm/thread_interrupter_fuchsia.cc
// Copyright (c) 2016, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. #include "platform/globals.h" #if defined(HOST_OS_FUCHSIA) #include "vm/thread_interrupter.h" #include <zircon/process.h> #include <zircon/status.h> #include <zircon/syscalls.h> #include <zircon/syscalls/debug.h> #include <zircon/syscalls/object.h> #include <zircon/types.h> #include "vm/flags.h" #include "vm/instructions.h" #include "vm/os.h" #include "vm/profiler.h" namespace dart { #ifndef PRODUCT DECLARE_FLAG(bool, thread_interrupter); DECLARE_FLAG(bool, trace_thread_interrupter); // TODO(ZX-430): Currently, CPU profiling for Fuchsia is arranged very similarly // to our Windows profiling. That is, the interrupter thread iterates over // all threads, suspends them, samples various things, and then resumes them. // When ZX-430 is resolved, the code below should be rewritten to use whatever // feature is added for it. // A scope within which a target thread is suspended. When the scope is exited, // the thread is resumed and its handle is closed. class ThreadSuspendScope { public: explicit ThreadSuspendScope(zx_handle_t thread_handle) : thread_handle_(thread_handle), suspended_(true) { zx_status_t status = zx_task_suspend(thread_handle); // If a thread is somewhere where suspend is impossible, zx_task_suspend() // can return ZX_ERR_NOT_SUPPORTED. if (status != ZX_OK) { if (FLAG_trace_thread_interrupter) { OS::PrintErr("ThreadInterrupter: zx_task_suspend failed: %s\n", zx_status_get_string(status)); } suspended_ = false; } } ~ThreadSuspendScope() { if (suspended_) { zx_status_t status = zx_task_resume(thread_handle_, 0); if (status != ZX_OK) { // If we fail to resume a thread, then it's likely the program will // hang. Crash instead. FATAL1("zx_task_resume failed: %s", zx_status_get_string(status)); } } zx_handle_close(thread_handle_); } bool suspended() const { return suspended_; } private: zx_handle_t thread_handle_; bool suspended_; DISALLOW_ALLOCATION(); DISALLOW_COPY_AND_ASSIGN(ThreadSuspendScope); }; class ThreadInterrupterFuchsia : public AllStatic { public: #if defined(TARGET_ARCH_X64) static bool GrabRegisters(zx_handle_t thread, InterruptedThreadState* state) { zx_x86_64_general_regs_t regs; uint32_t regset_size; zx_status_t status = zx_thread_read_state( thread, ZX_THREAD_STATE_REGSET0, &regs, sizeof(regs), &regset_size); if (status != ZX_OK) { if (FLAG_trace_thread_interrupter) { OS::PrintErr("ThreadInterrupter failed to get registers: %s\n", zx_status_get_string(status)); } return false; } state->pc = static_cast<uintptr_t>(regs.rip); state->fp = static_cast<uintptr_t>(regs.rbp); state->csp = static_cast<uintptr_t>(regs.rsp); state->dsp = static_cast<uintptr_t>(regs.rsp); return true; } #elif defined(TARGET_ARCH_ARM64) static bool GrabRegisters(zx_handle_t thread, InterruptedThreadState* state) { zx_arm64_general_regs_t regs; uint32_t regset_size; zx_status_t status = zx_thread_read_state( thread, ZX_THREAD_STATE_REGSET0, &regs, sizeof(regs), &regset_size); if (status != ZX_OK) { if (FLAG_trace_thread_interrupter) { OS::PrintErr("ThreadInterrupter failed to get registers: %s\n", zx_status_get_string(status)); } return false; } state->pc = static_cast<uintptr_t>(regs.pc); state->fp = static_cast<uintptr_t>(regs.r[FPREG]); state->csp = static_cast<uintptr_t>(regs.sp); state->dsp = static_cast<uintptr_t>(regs.r[SPREG]); state->lr = static_cast<uintptr_t>(regs.lr); return true; } #else #error "Unsupported architecture" #endif static void Interrupt(OSThread* os_thread) { ASSERT(os_thread->id() != ZX_KOID_INVALID); ASSERT(!OSThread::Compare(OSThread::GetCurrentThreadId(), os_thread->id())); zx_status_t status; // Get a handle on the target thread. const zx_koid_t target_thread_koid = os_thread->id(); if (FLAG_trace_thread_interrupter) { OS::PrintErr("ThreadInterrupter: interrupting thread with koid=%ld\n", target_thread_koid); } zx_handle_t target_thread_handle; status = zx_object_get_child(zx_process_self(), target_thread_koid, ZX_RIGHT_SAME_RIGHTS, &target_thread_handle); if (status != ZX_OK) { if (FLAG_trace_thread_interrupter) { OS::PrintErr("ThreadInterrupter: zx_object_get_child failed: %s\n", zx_status_get_string(status)); } return; } if (target_thread_handle == ZX_HANDLE_INVALID) { if (FLAG_trace_thread_interrupter) { OS::PrintErr( "ThreadInterrupter: zx_object_get_child gave an invalid " "thread handle!"); } return; } // This scope suspends the thread. When we exit the scope, the thread is // resumed, and the thread handle is closed. ThreadSuspendScope tss(target_thread_handle); if (!tss.suspended()) { return; } // Check that the thread is suspended. status = PollThreadUntilSuspended(target_thread_handle); if (status != ZX_OK) { return; } // Grab the target thread's registers. InterruptedThreadState its; if (!GrabRegisters(target_thread_handle, &its)) { return; } // Currently we sample only threads that are associated // with an isolate. It is safe to call 'os_thread->thread()' // here as the thread which is being queried is suspended. Thread* thread = os_thread->thread(); if (thread != NULL) { Profiler::SampleThread(thread, its); } } private: static const char* ThreadStateGetString(uint32_t state) { switch (state) { case ZX_THREAD_STATE_NEW: return "ZX_THREAD_STATE_NEW"; case ZX_THREAD_STATE_RUNNING: return "ZX_THREAD_STATE_RUNNING"; case ZX_THREAD_STATE_SUSPENDED: return "ZX_THREAD_STATE_SUSPENDED"; case ZX_THREAD_STATE_BLOCKED: return "ZX_THREAD_STATE_BLOCKED"; case ZX_THREAD_STATE_DYING: return "ZX_THREAD_STATE_DYING"; case ZX_THREAD_STATE_DEAD: return "ZX_THREAD_STATE_DEAD"; default: return "<Unknown>"; } } static zx_status_t PollThreadUntilSuspended(zx_handle_t thread_handle) { const intptr_t kMaxPollAttempts = 10; intptr_t poll_tries = 0; while (poll_tries < kMaxPollAttempts) { zx_info_thread_t thread_info; zx_status_t status = zx_object_get_info(thread_handle, ZX_INFO_THREAD, &thread_info, sizeof(thread_info), NULL, NULL); poll_tries++; if (status != ZX_OK) { if (FLAG_trace_thread_interrupter) { OS::PrintErr("ThreadInterrupter: zx_object_get_info failed: %s\n", zx_status_get_string(status)); } return status; } if (thread_info.state == ZX_THREAD_STATE_SUSPENDED) { // Success. return ZX_OK; } if (thread_info.state == ZX_THREAD_STATE_RUNNING) { // Poll. continue; } if (FLAG_trace_thread_interrupter) { OS::PrintErr("ThreadInterrupter: Thread is not suspended: %s\n", ThreadStateGetString(thread_info.state)); } return ZX_ERR_BAD_STATE; } if (FLAG_trace_thread_interrupter) { OS::PrintErr("ThreadInterrupter: Exceeded max suspend poll tries\n"); } return ZX_ERR_BAD_STATE; } }; bool ThreadInterrupter::IsDebuggerAttached() { return false; } void ThreadInterrupter::InterruptThread(OSThread* thread) { if (FLAG_trace_thread_interrupter) { OS::PrintErr("ThreadInterrupter suspending %p\n", reinterpret_cast<void*>(thread->id())); } ThreadInterrupterFuchsia::Interrupt(thread); if (FLAG_trace_thread_interrupter) { OS::PrintErr("ThreadInterrupter resuming %p\n", reinterpret_cast<void*>(thread->id())); } } void ThreadInterrupter::InstallSignalHandler() { // Nothing to do on Fuchsia. } void ThreadInterrupter::RemoveSignalHandler() { // Nothing to do on Fuchsia. } #endif // !PRODUCT } // namespace dart #endif // defined(HOST_OS_FUCHSIA)
// Copyright (c) 2016, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. #include "platform/globals.h" #if defined(HOST_OS_FUCHSIA) #include "vm/thread_interrupter.h" #include <zircon/process.h> #include <zircon/status.h> #include <zircon/syscalls.h> #include <zircon/syscalls/debug.h> #include <zircon/syscalls/object.h> #include <zircon/types.h> #include "vm/flags.h" #include "vm/instructions.h" #include "vm/os.h" #include "vm/profiler.h" namespace dart { #ifndef PRODUCT DECLARE_FLAG(bool, thread_interrupter); DECLARE_FLAG(bool, trace_thread_interrupter); // TODO(ZX-430): Currently, CPU profiling for Fuchsia is arranged very similarly // to our Windows profiling. That is, the interrupter thread iterates over // all threads, suspends them, samples various things, and then resumes them. // When ZX-430 is resolved, the code below should be rewritten to use whatever // feature is added for it. // A scope within which a target thread is suspended. When the scope is exited, // the thread is resumed and its handle is closed. class ThreadSuspendScope { public: explicit ThreadSuspendScope(zx_handle_t thread_handle) : thread_handle_(thread_handle), suspended_(true) { zx_status_t status = zx_task_suspend(thread_handle); // If a thread is somewhere where suspend is impossible, zx_task_suspend() // can return ZX_ERR_NOT_SUPPORTED. if (status != ZX_OK) { if (FLAG_trace_thread_interrupter) { OS::PrintErr("ThreadInterrupter: zx_task_suspend failed: %s\n", zx_status_get_string(status)); } suspended_ = false; } } ~ThreadSuspendScope() { if (suspended_) { zx_status_t status = zx_task_resume(thread_handle_, 0); if (status != ZX_OK) { // If we fail to resume a thread, then it's likely the program will // hang. Crash instead. FATAL1("zx_task_resume failed: %s", zx_status_get_string(status)); } } zx_handle_close(thread_handle_); } bool suspended() const { return suspended_; } private: zx_handle_t thread_handle_; bool suspended_; DISALLOW_ALLOCATION(); DISALLOW_COPY_AND_ASSIGN(ThreadSuspendScope); }; class ThreadInterrupterFuchsia : public AllStatic { public: #if defined(TARGET_ARCH_X64) static bool GrabRegisters(zx_handle_t thread, InterruptedThreadState* state) { zx_x86_64_general_regs_t regs; size_t regset_size; zx_status_t status = zx_thread_read_state( thread, ZX_THREAD_STATE_REGSET0, &regs, sizeof(regs), &regset_size); if (status != ZX_OK) { if (FLAG_trace_thread_interrupter) { OS::PrintErr("ThreadInterrupter failed to get registers: %s\n", zx_status_get_string(status)); } return false; } state->pc = static_cast<uintptr_t>(regs.rip); state->fp = static_cast<uintptr_t>(regs.rbp); state->csp = static_cast<uintptr_t>(regs.rsp); state->dsp = static_cast<uintptr_t>(regs.rsp); return true; } #elif defined(TARGET_ARCH_ARM64) static bool GrabRegisters(zx_handle_t thread, InterruptedThreadState* state) { zx_arm64_general_regs_t regs; uint32_t regset_size; zx_status_t status = zx_thread_read_state( thread, ZX_THREAD_STATE_REGSET0, &regs, sizeof(regs), &regset_size); if (status != ZX_OK) { if (FLAG_trace_thread_interrupter) { OS::PrintErr("ThreadInterrupter failed to get registers: %s\n", zx_status_get_string(status)); } return false; } state->pc = static_cast<uintptr_t>(regs.pc); state->fp = static_cast<uintptr_t>(regs.r[FPREG]); state->csp = static_cast<uintptr_t>(regs.sp); state->dsp = static_cast<uintptr_t>(regs.r[SPREG]); state->lr = static_cast<uintptr_t>(regs.lr); return true; } #else #error "Unsupported architecture" #endif static void Interrupt(OSThread* os_thread) { ASSERT(os_thread->id() != ZX_KOID_INVALID); ASSERT(!OSThread::Compare(OSThread::GetCurrentThreadId(), os_thread->id())); zx_status_t status; // Get a handle on the target thread. const zx_koid_t target_thread_koid = os_thread->id(); if (FLAG_trace_thread_interrupter) { OS::PrintErr("ThreadInterrupter: interrupting thread with koid=%ld\n", target_thread_koid); } zx_handle_t target_thread_handle; status = zx_object_get_child(zx_process_self(), target_thread_koid, ZX_RIGHT_SAME_RIGHTS, &target_thread_handle); if (status != ZX_OK) { if (FLAG_trace_thread_interrupter) { OS::PrintErr("ThreadInterrupter: zx_object_get_child failed: %s\n", zx_status_get_string(status)); } return; } if (target_thread_handle == ZX_HANDLE_INVALID) { if (FLAG_trace_thread_interrupter) { OS::PrintErr( "ThreadInterrupter: zx_object_get_child gave an invalid " "thread handle!"); } return; } // This scope suspends the thread. When we exit the scope, the thread is // resumed, and the thread handle is closed. ThreadSuspendScope tss(target_thread_handle); if (!tss.suspended()) { return; } // Check that the thread is suspended. status = PollThreadUntilSuspended(target_thread_handle); if (status != ZX_OK) { return; } // Grab the target thread's registers. InterruptedThreadState its; if (!GrabRegisters(target_thread_handle, &its)) { return; } // Currently we sample only threads that are associated // with an isolate. It is safe to call 'os_thread->thread()' // here as the thread which is being queried is suspended. Thread* thread = os_thread->thread(); if (thread != NULL) { Profiler::SampleThread(thread, its); } } private: static const char* ThreadStateGetString(uint32_t state) { switch (state) { case ZX_THREAD_STATE_NEW: return "ZX_THREAD_STATE_NEW"; case ZX_THREAD_STATE_RUNNING: return "ZX_THREAD_STATE_RUNNING"; case ZX_THREAD_STATE_SUSPENDED: return "ZX_THREAD_STATE_SUSPENDED"; case ZX_THREAD_STATE_BLOCKED: return "ZX_THREAD_STATE_BLOCKED"; case ZX_THREAD_STATE_DYING: return "ZX_THREAD_STATE_DYING"; case ZX_THREAD_STATE_DEAD: return "ZX_THREAD_STATE_DEAD"; default: return "<Unknown>"; } } static zx_status_t PollThreadUntilSuspended(zx_handle_t thread_handle) { const intptr_t kMaxPollAttempts = 10; intptr_t poll_tries = 0; while (poll_tries < kMaxPollAttempts) { zx_info_thread_t thread_info; zx_status_t status = zx_object_get_info(thread_handle, ZX_INFO_THREAD, &thread_info, sizeof(thread_info), NULL, NULL); poll_tries++; if (status != ZX_OK) { if (FLAG_trace_thread_interrupter) { OS::PrintErr("ThreadInterrupter: zx_object_get_info failed: %s\n", zx_status_get_string(status)); } return status; } if (thread_info.state == ZX_THREAD_STATE_SUSPENDED) { // Success. return ZX_OK; } if (thread_info.state == ZX_THREAD_STATE_RUNNING) { // Poll. continue; } if (FLAG_trace_thread_interrupter) { OS::PrintErr("ThreadInterrupter: Thread is not suspended: %s\n", ThreadStateGetString(thread_info.state)); } return ZX_ERR_BAD_STATE; } if (FLAG_trace_thread_interrupter) { OS::PrintErr("ThreadInterrupter: Exceeded max suspend poll tries\n"); } return ZX_ERR_BAD_STATE; } }; bool ThreadInterrupter::IsDebuggerAttached() { return false; } void ThreadInterrupter::InterruptThread(OSThread* thread) { if (FLAG_trace_thread_interrupter) { OS::PrintErr("ThreadInterrupter suspending %p\n", reinterpret_cast<void*>(thread->id())); } ThreadInterrupterFuchsia::Interrupt(thread); if (FLAG_trace_thread_interrupter) { OS::PrintErr("ThreadInterrupter resuming %p\n", reinterpret_cast<void*>(thread->id())); } } void ThreadInterrupter::InstallSignalHandler() { // Nothing to do on Fuchsia. } void ThreadInterrupter::RemoveSignalHandler() { // Nothing to do on Fuchsia. } #endif // !PRODUCT } // namespace dart #endif // defined(HOST_OS_FUCHSIA)
Update a type for a Fuchsia syscall.
Update a type for a Fuchsia syscall. Change-Id: I92993e5e7bc60fee02b9301b8069ac2b94995020 Reviewed-on: https://dart-review.googlesource.com/38440 Reviewed-by: Zach Anderson <[email protected]>
C++
bsd-3-clause
dart-archive/dart-sdk,dartino/dart-sdk,dart-archive/dart-sdk,dartino/dart-sdk,dart-archive/dart-sdk,dart-lang/sdk,dartino/dart-sdk,dartino/dart-sdk,dart-lang/sdk,dartino/dart-sdk,dart-archive/dart-sdk,dart-archive/dart-sdk,dart-archive/dart-sdk,dart-archive/dart-sdk,dart-lang/sdk,dart-archive/dart-sdk,dartino/dart-sdk,dartino/dart-sdk,dart-lang/sdk,dart-archive/dart-sdk,dartino/dart-sdk,dart-lang/sdk,dart-lang/sdk,dart-lang/sdk,dartino/dart-sdk,dart-lang/sdk
47a7e196979ec3edcfefdcf440b1caf96eb83928
Rendering/vtkPrimitivePainter.cxx
Rendering/vtkPrimitivePainter.cxx
/*========================================================================= Program: Visualization Toolkit Module: vtkPrimitivePainter.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "vtkPrimitivePainter.h" #include "vtkActor.h" #include "vtkCellData.h" #include "vtkDataSetAttributes.h" #include "vtkGarbageCollector.h" #include "vtkGenericVertexAttributeMapping.h" #include "vtkInformation.h" #include "vtkInformationIntegerKey.h" #include "vtkInformationObjectBaseKey.h" #include "vtkObjectFactory.h" #include "vtkPointData.h" #include "vtkPoints.h" #include "vtkPolyData.h" #include "vtkProperty.h" #include "vtkRenderer.h" #include "vtkRenderWindow.h" #include "vtkShaderDeviceAdapter.h" #include "vtkShaderProgram.h" #include "vtkTimerLog.h" #include "vtkUnsignedCharArray.h" #include "vtkShaderDeviceAdapter2.h" //--------------------------------------------------------------------------- vtkPrimitivePainter::vtkPrimitivePainter() { this->SupportedPrimitive = 0x0; // must be set by subclasses. No primitive // supported by default. this->DisableScalarColor = 0; this->OutputData = vtkPolyData::New(); this->GenericVertexAttributes = false; this->MultiTextureAttributes = false; } //--------------------------------------------------------------------------- vtkPrimitivePainter::~vtkPrimitivePainter() { if( this->OutputData ) { this->OutputData->Delete(); this->OutputData = 0; } } //--------------------------------------------------------------------------- void vtkPrimitivePainter::ReportReferences(vtkGarbageCollector *collector) { this->Superclass::ReportReferences(collector); vtkGarbageCollectorReport(collector, this->OutputData, "Output Data"); } //--------------------------------------------------------------------------- vtkDataObject* vtkPrimitivePainter::GetOutput() { return this->OutputData; } //--------------------------------------------------------------------------- void vtkPrimitivePainter::ProcessInformation(vtkInformation *info) { this->GenericVertexAttributes = false; if (info->Has(DATA_ARRAY_TO_VERTEX_ATTRIBUTE())) { vtkGenericVertexAttributeMapping *mappings = vtkGenericVertexAttributeMapping::SafeDownCast( info->Get(DATA_ARRAY_TO_VERTEX_ATTRIBUTE())); this->GenericVertexAttributes = mappings && (mappings->GetNumberOfMappings() > 0); this->MultiTextureAttributes = false; if (mappings) { for (unsigned int i = 0; i < mappings->GetNumberOfMappings(); ++i) { if (mappings->GetTextureUnit(i) >= 0) { this->MultiTextureAttributes = true; break; } } } } if (info->Has(DISABLE_SCALAR_COLOR()) && info->Get(DISABLE_SCALAR_COLOR()) == 1) { this->DisableScalarColor = 1; } else { this->DisableScalarColor = 0; } } //--------------------------------------------------------------------------- void vtkPrimitivePainter::PrepareForRendering(vtkRenderer* renderer, vtkActor* actor) { // Here, we don't use the this->StaticData flag to mean that the input // can never change, since the input may be the output of // some filtering painter that filter on actor/renderer properties // and not on the input polydata. Hence the input polydata // may get modified even if the input to the PolyDataMapper is // immutable. // If the input has changed update the output. if (this->OutputUpdateTime < this->MTime || this->OutputUpdateTime < this->GetInput()->GetMTime()) { this->OutputData->ShallowCopy(this->GetInputAsPolyData()); this->OutputUpdateTime.Modified(); } this->Superclass::PrepareForRendering(renderer, actor); } //--------------------------------------------------------------------------- void vtkPrimitivePainter::RenderInternal(vtkRenderer* renderer, vtkActor* act, unsigned long typeflags, bool forceCompileOnly) { unsigned long supported_typeflags = this->SupportedPrimitive & typeflags; if (!supported_typeflags) { // no supported primitive requested to be rendered. this->Superclass::RenderInternal(renderer, act, typeflags, forceCompileOnly); return; } if (!renderer->GetRenderWindow()->GetPainterDeviceAdapter()) { vtkErrorMacro("Painter Device Adapter is missing!"); return; } this->Timer->StartTimer(); int interpolation; float tran; vtkProperty *prop; vtkUnsignedCharArray *c=NULL; vtkDataArray *n; vtkDataArray *t; vtkDataArray *ef; int tDim; vtkPolyData *input = this->GetInputAsPolyData(); int cellNormals; int cellScalars = 0; int fieldScalars = 0; // get the property prop = act->GetProperty(); // get the transparency tran = prop->GetOpacity(); // if the primitives are invisible then get out of here if (tran <= 0.0) { return; } // get the shading interpolation interpolation = prop->GetInterpolation(); if (!this->DisableScalarColor) { // are they cell or point scalars c = vtkUnsignedCharArray::SafeDownCast(input->GetPointData()->GetScalars()); if (!c) { c = vtkUnsignedCharArray::SafeDownCast(input->GetCellData()->GetScalars()); cellScalars = 1; } if (!c) { c = vtkUnsignedCharArray::SafeDownCast(input->GetFieldData()-> GetArray("Color")); fieldScalars = 1; // note when fieldScalars == 1, also cellScalars == 1. // this ensures that primitive painters that do not distinguish between // fieldScalars and cellScalars (eg. Verts/Lines/Polys painters) can ignore // fieldScalars flag. } } n = input->GetPointData()->GetNormals(); if (interpolation == VTK_FLAT) { // shunt point normals. n = 0; if (this->OutputData->GetPointData()->GetNormals()) { this->OutputData->GetPointData()->SetNormals(0); } } cellNormals = 0; if (n == 0 && input->GetCellData()->GetNormals()) { cellNormals = 1; n = input->GetCellData()->GetNormals(); } unsigned long idx = 0; if (n && !cellNormals) { idx |= VTK_PDM_NORMALS; } if (c) { idx |= VTK_PDM_COLORS; if (!c->GetName()) { // If the array has a name (hence directly coming with MAP_SCALARS), // it means that it has 4 components and we should use the alpha. // Otherwise, we know that alpha is constant so we ignore it. idx |= VTK_PDM_OPAQUE_COLORS; } if (cellScalars) { idx |= VTK_PDM_CELL_COLORS; } if (fieldScalars) { idx |= VTK_PDM_FIELD_COLORS; } } if (cellNormals) { idx |= VTK_PDM_CELL_NORMALS; } // Texture and color by texture t = input->GetPointData()->GetTCoords(); if ( t ) { tDim = t->GetNumberOfComponents(); if (tDim > 3) { vtkDebugMacro(<< "Currently only 1d, 2d and 3d texture coordinates are supported.\n"); t = NULL; } } // Set the flags if (t) { idx |= VTK_PDM_TCOORDS; } // Edge flag ef = input->GetPointData()->GetAttribute(vtkDataSetAttributes::EDGEFLAG); if (ef) { if (ef->GetNumberOfComponents() != 1) { vtkDebugMacro(<< "Currently only 1d edge flags are supported."); ef = NULL; } if (!ef->IsA("vtkUnsignedCharArray")) { vtkDebugMacro(<< "Currently only unsigned char edge flags are suported."); ef = NULL; } } // Set the flags if (ef) { idx |= VTK_PDM_EDGEFLAGS; } if (!act) { vtkErrorMacro("No actor"); } vtkShaderDeviceAdapter *shaderDevice = NULL; vtkShaderDeviceAdapter2 *shaderDevice2 = NULL; if (prop->GetShading()) { if (prop->GetShaderProgram()) { shaderDevice = prop->GetShaderProgram()->GetShaderDeviceAdapter(); } shaderDevice2 = prop->GetShaderDeviceAdapter2(); } if (shaderDevice && this->GenericVertexAttributes) { idx |= VTK_PDM_GENERIC_VERTEX_ATTRIBUTES; } if (shaderDevice2 && this->GenericVertexAttributes) { idx |= VTK_PDM_GENERIC_VERTEX_ATTRIBUTES; } if (this->MultiTextureAttributes) { idx |= VTK_PDM_GENERIC_VERTEX_ATTRIBUTES; } if (this->RenderPrimitive(idx, n, c, t, renderer)) { // subclass rendered the supported primitive successfully. // The delegate need not render it. typeflags &= (~this->SupportedPrimitive); } this->Timer->StopTimer(); this->TimeToDraw = this->Timer->GetElapsedTime(); this->Superclass::RenderInternal(renderer, act, typeflags,forceCompileOnly); } //--------------------------------------------------------------------------- void vtkPrimitivePainter::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os, indent); os << indent << "SupportedPrimitive: " << this->SupportedPrimitive << endl; }
/*========================================================================= Program: Visualization Toolkit Module: vtkPrimitivePainter.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "vtkPrimitivePainter.h" #include "vtkActor.h" #include "vtkCellData.h" #include "vtkDataSetAttributes.h" #include "vtkGarbageCollector.h" #include "vtkGenericVertexAttributeMapping.h" #include "vtkInformation.h" #include "vtkInformationIntegerKey.h" #include "vtkInformationObjectBaseKey.h" #include "vtkObjectFactory.h" #include "vtkPointData.h" #include "vtkPoints.h" #include "vtkPolyData.h" #include "vtkProperty.h" #include "vtkRenderer.h" #include "vtkRenderWindow.h" #include "vtkShaderDeviceAdapter.h" #include "vtkShaderProgram.h" #include "vtkTimerLog.h" #include "vtkUnsignedCharArray.h" #include "vtkShaderDeviceAdapter2.h" //--------------------------------------------------------------------------- vtkPrimitivePainter::vtkPrimitivePainter() { this->SupportedPrimitive = 0x0; // must be set by subclasses. No primitive // supported by default. this->DisableScalarColor = 0; this->OutputData = vtkPolyData::New(); this->GenericVertexAttributes = false; this->MultiTextureAttributes = false; } //--------------------------------------------------------------------------- vtkPrimitivePainter::~vtkPrimitivePainter() { if( this->OutputData ) { this->OutputData->Delete(); this->OutputData = 0; } } //--------------------------------------------------------------------------- void vtkPrimitivePainter::ReportReferences(vtkGarbageCollector *collector) { this->Superclass::ReportReferences(collector); vtkGarbageCollectorReport(collector, this->OutputData, "Output Data"); } //--------------------------------------------------------------------------- vtkDataObject* vtkPrimitivePainter::GetOutput() { return this->OutputData; } //--------------------------------------------------------------------------- void vtkPrimitivePainter::ProcessInformation(vtkInformation *info) { this->GenericVertexAttributes = false; if (info->Has(DATA_ARRAY_TO_VERTEX_ATTRIBUTE())) { vtkGenericVertexAttributeMapping *mappings = vtkGenericVertexAttributeMapping::SafeDownCast( info->Get(DATA_ARRAY_TO_VERTEX_ATTRIBUTE())); this->GenericVertexAttributes = mappings && (mappings->GetNumberOfMappings() > 0); this->MultiTextureAttributes = false; if (mappings) { for (unsigned int i = 0; i < mappings->GetNumberOfMappings(); ++i) { if (mappings->GetTextureUnit(i) >= 0) { this->MultiTextureAttributes = true; break; } } } } if (info->Has(DISABLE_SCALAR_COLOR()) && info->Get(DISABLE_SCALAR_COLOR()) == 1) { this->DisableScalarColor = 1; } else { this->DisableScalarColor = 0; } } //--------------------------------------------------------------------------- void vtkPrimitivePainter::PrepareForRendering(vtkRenderer* renderer, vtkActor* actor) { // Here, we don't use the this->StaticData flag to mean that the input // can never change, since the input may be the output of // some filtering painter that filter on actor/renderer properties // and not on the input polydata. Hence the input polydata // may get modified even if the input to the PolyDataMapper is // immutable. // If the input has changed update the output. if (this->OutputUpdateTime < this->MTime || this->OutputUpdateTime < this->GetInput()->GetMTime()) { this->OutputData->ShallowCopy(this->GetInputAsPolyData()); this->OutputUpdateTime.Modified(); } this->Superclass::PrepareForRendering(renderer, actor); } //--------------------------------------------------------------------------- void vtkPrimitivePainter::RenderInternal(vtkRenderer* renderer, vtkActor* act, unsigned long typeflags, bool forceCompileOnly) { unsigned long supported_typeflags = this->SupportedPrimitive & typeflags; if (!supported_typeflags) { // no supported primitive requested to be rendered. this->Superclass::RenderInternal(renderer, act, typeflags, forceCompileOnly); return; } if (!renderer->GetRenderWindow()->GetPainterDeviceAdapter()) { vtkErrorMacro("Painter Device Adapter is missing!"); return; } this->Timer->StartTimer(); int interpolation; float tran; vtkProperty *prop; vtkUnsignedCharArray *c=NULL; vtkDataArray *n; vtkDataArray *t; vtkDataArray *ef; int tDim; vtkPolyData *input = this->GetInputAsPolyData(); int cellNormals; int cellScalars = 0; int fieldScalars = 0; // get the property prop = act->GetProperty(); // get the transparency tran = prop->GetOpacity(); // if the primitives are invisible then get out of here if (tran <= 0.0) { return; } // get the shading interpolation interpolation = prop->GetInterpolation(); if (!this->DisableScalarColor) { // are they cell or point scalars c = vtkUnsignedCharArray::SafeDownCast(input->GetPointData()->GetScalars()); if (!c) { c = vtkUnsignedCharArray::SafeDownCast(input->GetCellData()->GetScalars()); cellScalars = 1; } if (!c) { c = vtkUnsignedCharArray::SafeDownCast(input->GetFieldData()-> GetArray("Color")); fieldScalars = 1; // note when fieldScalars == 1, also cellScalars == 1. // this ensures that primitive painters that do not distinguish between // fieldScalars and cellScalars (eg. Verts/Lines/Polys painters) can ignore // fieldScalars flag. } } n = input->GetPointData()->GetNormals(); if (interpolation == VTK_FLAT) { // shunt point normals. n = 0; if (this->OutputData->GetPointData()->GetNormals()) { this->OutputData->GetPointData()->SetNormals(0); } } cellNormals = 0; if (n == 0 && input->GetCellData()->GetNormals()) { cellNormals = 1; n = input->GetCellData()->GetNormals(); } unsigned long idx = 0; if (n && !cellNormals) { idx |= VTK_PDM_NORMALS; } if (c) { idx |= VTK_PDM_COLORS; if (c->GetNumberOfComponents() == 4 && c->GetValueRange(3)[0] == 255) { // If the opacity is 255, don't bother send the opacity values to OpenGL. // Treat the colors are opaque colors (which they are). idx |= VTK_PDM_OPAQUE_COLORS; } if (cellScalars) { idx |= VTK_PDM_CELL_COLORS; } if (fieldScalars) { idx |= VTK_PDM_FIELD_COLORS; } } if (cellNormals) { idx |= VTK_PDM_CELL_NORMALS; } // Texture and color by texture t = input->GetPointData()->GetTCoords(); if ( t ) { tDim = t->GetNumberOfComponents(); if (tDim > 3) { vtkDebugMacro(<< "Currently only 1d, 2d and 3d texture coordinates are supported.\n"); t = NULL; } } // Set the flags if (t) { idx |= VTK_PDM_TCOORDS; } // Edge flag ef = input->GetPointData()->GetAttribute(vtkDataSetAttributes::EDGEFLAG); if (ef) { if (ef->GetNumberOfComponents() != 1) { vtkDebugMacro(<< "Currently only 1d edge flags are supported."); ef = NULL; } if (!ef->IsA("vtkUnsignedCharArray")) { vtkDebugMacro(<< "Currently only unsigned char edge flags are suported."); ef = NULL; } } // Set the flags if (ef) { idx |= VTK_PDM_EDGEFLAGS; } if (!act) { vtkErrorMacro("No actor"); } vtkShaderDeviceAdapter *shaderDevice = NULL; vtkShaderDeviceAdapter2 *shaderDevice2 = NULL; if (prop->GetShading()) { if (prop->GetShaderProgram()) { shaderDevice = prop->GetShaderProgram()->GetShaderDeviceAdapter(); } shaderDevice2 = prop->GetShaderDeviceAdapter2(); } if (shaderDevice && this->GenericVertexAttributes) { idx |= VTK_PDM_GENERIC_VERTEX_ATTRIBUTES; } if (shaderDevice2 && this->GenericVertexAttributes) { idx |= VTK_PDM_GENERIC_VERTEX_ATTRIBUTES; } if (this->MultiTextureAttributes) { idx |= VTK_PDM_GENERIC_VERTEX_ATTRIBUTES; } if (this->RenderPrimitive(idx, n, c, t, renderer)) { // subclass rendered the supported primitive successfully. // The delegate need not render it. typeflags &= (~this->SupportedPrimitive); } this->Timer->StopTimer(); this->TimeToDraw = this->Timer->GetElapsedTime(); this->Superclass::RenderInternal(renderer, act, typeflags,forceCompileOnly); } //--------------------------------------------------------------------------- void vtkPrimitivePainter::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os, indent); os << indent << "SupportedPrimitive: " << this->SupportedPrimitive << endl; }
Fix the condition to determine if colors have alpha < 1.
Fix the condition to determine if colors have alpha < 1. The condition to check if we can avoid passing alpha to the graphics card was incorrect. Previous commit broke traditional opacity with scalar coloring, while the code before that didn't respect alpha when scalars weren't mapped. The right fix is to look at the alpha value range to determine if the colors are truly opaque.
C++
bsd-3-clause
cjh1/VTK,spthaolt/VTK,aashish24/VTK-old,ashray/VTK-EVM,ashray/VTK-EVM,collects/VTK,msmolens/VTK,gram526/VTK,SimVascular/VTK,SimVascular/VTK,gram526/VTK,candy7393/VTK,demarle/VTK,berendkleinhaneveld/VTK,sankhesh/VTK,jmerkow/VTK,berendkleinhaneveld/VTK,sankhesh/VTK,msmolens/VTK,mspark93/VTK,candy7393/VTK,keithroe/vtkoptix,demarle/VTK,SimVascular/VTK,biddisco/VTK,sumedhasingla/VTK,candy7393/VTK,jmerkow/VTK,johnkit/vtk-dev,mspark93/VTK,ashray/VTK-EVM,hendradarwin/VTK,gram526/VTK,cjh1/VTK,spthaolt/VTK,SimVascular/VTK,sankhesh/VTK,sankhesh/VTK,demarle/VTK,keithroe/vtkoptix,jmerkow/VTK,msmolens/VTK,ashray/VTK-EVM,spthaolt/VTK,demarle/VTK,msmolens/VTK,candy7393/VTK,cjh1/VTK,biddisco/VTK,mspark93/VTK,aashish24/VTK-old,biddisco/VTK,sankhesh/VTK,sumedhasingla/VTK,collects/VTK,jmerkow/VTK,jmerkow/VTK,berendkleinhaneveld/VTK,jmerkow/VTK,collects/VTK,spthaolt/VTK,hendradarwin/VTK,SimVascular/VTK,sumedhasingla/VTK,keithroe/vtkoptix,spthaolt/VTK,sankhesh/VTK,keithroe/vtkoptix,SimVascular/VTK,gram526/VTK,aashish24/VTK-old,jmerkow/VTK,sumedhasingla/VTK,hendradarwin/VTK,collects/VTK,hendradarwin/VTK,sumedhasingla/VTK,berendkleinhaneveld/VTK,keithroe/vtkoptix,spthaolt/VTK,johnkit/vtk-dev,ashray/VTK-EVM,aashish24/VTK-old,mspark93/VTK,sumedhasingla/VTK,berendkleinhaneveld/VTK,demarle/VTK,biddisco/VTK,msmolens/VTK,collects/VTK,ashray/VTK-EVM,hendradarwin/VTK,biddisco/VTK,johnkit/vtk-dev,sumedhasingla/VTK,sankhesh/VTK,mspark93/VTK,cjh1/VTK,johnkit/vtk-dev,demarle/VTK,demarle/VTK,sankhesh/VTK,hendradarwin/VTK,gram526/VTK,spthaolt/VTK,cjh1/VTK,johnkit/vtk-dev,jmerkow/VTK,keithroe/vtkoptix,aashish24/VTK-old,gram526/VTK,msmolens/VTK,ashray/VTK-EVM,mspark93/VTK,collects/VTK,aashish24/VTK-old,biddisco/VTK,SimVascular/VTK,candy7393/VTK,keithroe/vtkoptix,msmolens/VTK,biddisco/VTK,johnkit/vtk-dev,candy7393/VTK,sumedhasingla/VTK,mspark93/VTK,msmolens/VTK,berendkleinhaneveld/VTK,johnkit/vtk-dev,ashray/VTK-EVM,berendkleinhaneveld/VTK,gram526/VTK,gram526/VTK,hendradarwin/VTK,candy7393/VTK,candy7393/VTK,demarle/VTK,keithroe/vtkoptix,SimVascular/VTK,mspark93/VTK,cjh1/VTK
958362e457c329d7915fc9f2d5c0d6a779bebd67
util/kd_tree.cc
util/kd_tree.cc
/* * Author: Dino Wernli */ #include "kd_tree.h" #include <glog/logging.h> #include "renderer/intersection_data.h" #include "scene/element.h" #include "util/ray.h" struct KdTree::Node { // Creates an empty leaf. Sets axis to X. Node(); // Only to be called on leaves. Expects depth to be the current depth of the // leaf before splitting. void Split(Axis axis, size_t depth, const BoundingBox* box); // It is theoretically possible for leaves to have empty element vectors. bool IsLeaf() const { return left.get() == NULL && right.get() == NULL; } size_t NumElements() const { return IsLeaf() ? elements->size() : left->NumElements() + right->NumElements(); } // Returns whether or not the ray intersects any of the elements. If data is // not NULL, data about the first intersection is stored. bool Intersect(const Ray& ray, Scalar t_near, Scalar t_far, IntersectionData* data = NULL) const; bool OwnRecursiveIntersect(const Ray& ray, Scalar t_near, Scalar t_far, IntersectionData* data = NULL) const; bool NevRecursiveIntersect(const Ray& ray, Scalar t_near, Scalar t_far, IntersectionData* data = NULL) const; std::unique_ptr<std::vector<const Element*>> elements; std::unique_ptr<Node> left; std::unique_ptr<Node> right; Scalar split_position; Axis split_axis; }; KdTree::Node::Node() : split_axis(Axis::x()) { this->elements.reset(new std::vector<const Element*>()); } void KdTree::Node::Split(Axis axis, size_t depth, const BoundingBox* box) { CHECK(IsLeaf()) << "Split() can only be called on leaf nodes"; if (box == NULL) { CHECK(elements->size() == 0) << "Invalid bounding box during split"; } if (depth > kTreeDepth || elements->size() < kLeafSizeThreshold) { return; } // TODO(dinow): Implement other strategies than MidPointSplit. split_position = (box->min()[axis] + box->max()[axis]) / 2.0; split_axis = axis; left.reset(new Node()); right.reset(new Node()); // Move elements to either 1 or 2 relevant children. for (size_t i = 0; i < elements->size(); ++i) { if (elements->at(i)->bounding_box()->min()[axis] <= split_position) { left->elements->push_back(elements->at(i)); } if (elements->at(i)->bounding_box()->max()[axis] >= split_position) { right->elements->push_back(elements->at(i)); } } // Recursively split children. Point3 left_max = box->max(); left_max[axis] = split_position; BoundingBox left_box(box->min(), left_max); left->Split(axis.Next(), depth + 1, &left_box); Point3 right_min = box->max(); right_min[axis] = split_position; BoundingBox right_box(right_min, box->max()); right->Split(axis.Next(), depth + 1, &right_box); // Clean up elements. elements.reset(); CHECK(!IsLeaf()) << "KdTree node still leaf after split"; } bool KdTree::Node::OwnRecursiveIntersect(const Ray& ray, Scalar t_near, Scalar t_far, IntersectionData* data) const { if (IsLeaf()) { bool intersected = false; for (size_t i = 0; i < elements->size(); ++i) { intersected = intersected | elements->at(i)->Intersect(ray, data); if (intersected && data == NULL) { return true; } } return intersected; } Scalar ray_direction_axis = ray.direction()[split_axis]; Scalar ray_origin_axis = ray.origin()[split_axis]; bool is_origin_left = (ray_origin_axis <= split_position); // If ray is parallel to split axis, anyting the ray intersects with will // have to be on the side of the origin. if (ray_direction_axis == 0) { if (is_origin_left) { return left->Intersect(ray, t_near, t_far, data); } else { return right->Intersect(ray, t_near, t_far, data); } } // The near child is the child which is closer to the ray's origin in split // coordinates. The far child is the other one. const Node* near = is_origin_left ? left.get() : right.get(); const Node* far = is_origin_left ? right.get() : left.get(); Scalar t_split = (split_position - ray_origin_axis) / ray_origin_axis; if (t_split > t_far) { return near->Intersect(ray, t_near, t_far, data); } else if (t_split < t_near) { // TODO(dinow): Divergence between nev's implementation and mine. Need to // investigate further. /* if (ray.PointAt(t_near)[split_axis] < split_position) { return left->Intersect(ray, t_near, t_far, data); } else { return right->Intersect(ray, t_near, t_far, data); } */ // TODO(dinow): It looks like the above is equivalent to the following // because this is simply the near/far test again using the point at t_near // instead of the origin. return far->Intersect(ray, t_near, t_far, data); } else { // This is the case t_near <= t_split <= t_far. Test both children. DVLOG(2) << "Intersecting both children"; bool intersected = false; if ((intersected = near->Intersect(ray, t_near, t_split)) && (data == NULL || data->t < t_split)) { return true; } else { return far->Intersect(ray, t_split, t_far, data) || intersected; } } } bool KdTree::Node::NevRecursiveIntersect(const Ray& ray, Scalar t_near, Scalar t_far, IntersectionData* data) const { if (IsLeaf()) { bool intersected = false; for (size_t i = 0; i < elements->size(); ++i) { intersected = intersected | elements->at(i)->Intersect(ray, data); if (intersected && data == NULL) { return true; } } return intersected; } Scalar ray_direction_axis = ray.direction()[split_axis]; Scalar ray_origin_axis = ray.origin()[split_axis]; // Ray not moving in direction of the split, so only intersections with one // side are possible. if (ray_direction_axis == 0) { if (ray_origin_axis <= split_position) { return left->Intersect(ray, t_near, t_far, data); } else { return right->Intersect(ray, t_near, t_far, data); } } bool intersected = false; // Determine where on the ray the split happens. Scalar t_split = (split_position - ray_origin_axis) / ray_direction_axis; // Determine which is the first child traversed by the ray. const Node* first = left.get(); const Node* second = right.get(); if (ray_direction_axis < 0) std::swap(first, second); // Call recursively. if (t_split > t_far) { return first->Intersect(ray, t_near, t_far, data); } else if (t_split < t_near) { return second->Intersect(ray, t_near, t_far, data); } else if ((intersected |= first->Intersect(ray, t_near, t_split, data))) { if (data == NULL || data->t < t_split) { return true; } } else { intersected = second->Intersect(ray, t_split, t_far, data) || intersected; } return intersected; } bool KdTree::Node::Intersect(const Ray& ray, Scalar t_near, Scalar t_far, IntersectionData* data) const { // TODO(dinow): Debug implementations and clean this up. return OwnRecursiveIntersect(ray, t_near, t_far, data); //return NevRecursiveIntersect(ray, t_near, t_far, data); } KdTree::KdTree() { } KdTree::~KdTree() { } size_t KdTree::NumElementsWithDuplicates() const { if (root_.get() == NULL) { return 0; } else { return root_->NumElements(); } } void KdTree::Init(const std::vector<std::unique_ptr<Element>>& elements) { root_.reset(new Node()); // Take the first bounded element as original box, and merge all the // following boxes. bool first = true; for (auto it = elements.begin(); it != elements.end(); ++it) { const Element* element = it->get(); if (element->IsBounded()) { const BoundingBox& box = *element->bounding_box(); if (first) { bounding_box_.reset(new BoundingBox(box)); first = false; } else { bounding_box_->Include(box); } root_->elements->push_back(element); } } LOG(INFO) << "Building KdTree for " << root_->elements->size() << " elements"; root_->Split(kInitialSplitAxis, 0, bounding_box_.get()); if (bounding_box_.get() != NULL) { DVLOG(2) << "Built KdTree with bounding box " << *bounding_box_; } } bool KdTree::Intersect(const Ray& ray, IntersectionData* data) const { if (root_.get() == NULL) { LOG(WARNING) << "Called intersect on uninitialized KdTree. Returning false"; } DVLOG(2) << "Intersecting with ray " << ray; Scalar t_near, t_far; if (!bounding_box_->Intersect(ray, &t_near, &t_far)) { //if (!bounding_box_->IntersectVoodoo(ray, &t_near, &t_far)) { DVLOG(2) << "Bounding box did not intersect"; return false; } return root_->Intersect(ray, t_near, t_far, data); } // static const Axis KdTree::kInitialSplitAxis = Axis::x(); // static const size_t KdTree::kTreeDepth = 20; // static const size_t KdTree::kLeafSizeThreshold = 40;
/* * Author: Dino Wernli */ #include "kd_tree.h" #include <glog/logging.h> #include "renderer/intersection_data.h" #include "scene/element.h" #include "util/ray.h" struct KdTree::Node { // Creates an empty leaf. Sets axis to X. Node(); // Only to be called on leaves. Expects depth to be the current depth of the // leaf before splitting. void Split(Axis axis, size_t depth, const BoundingBox* box); // It is theoretically possible for leaves to have empty element vectors. bool IsLeaf() const { return left.get() == NULL && right.get() == NULL; } size_t NumElements() const { return IsLeaf() ? elements->size() : left->NumElements() + right->NumElements(); } // Returns whether or not the ray intersects any of the elements. If data is // not NULL, data about the first intersection is stored. bool Intersect(const Ray& ray, Scalar t_near, Scalar t_far, IntersectionData* data = NULL) const; bool OwnRecursiveIntersect(const Ray& ray, Scalar t_near, Scalar t_far, IntersectionData* data = NULL) const; bool NevRecursiveIntersect(const Ray& ray, Scalar t_near, Scalar t_far, IntersectionData* data = NULL) const; std::unique_ptr<std::vector<const Element*>> elements; std::unique_ptr<Node> left; std::unique_ptr<Node> right; Scalar split_position; Axis split_axis; }; KdTree::Node::Node() : split_axis(Axis::x()) { this->elements.reset(new std::vector<const Element*>()); } void KdTree::Node::Split(Axis axis, size_t depth, const BoundingBox* box) { CHECK(IsLeaf()) << "Split() can only be called on leaf nodes"; if (box == NULL) { CHECK(elements->size() == 0) << "Invalid bounding box during split"; } if (depth > kTreeDepth || elements->size() < kLeafSizeThreshold) { return; } // TODO(dinow): Implement other strategies than MidPointSplit. split_position = (box->min()[axis] + box->max()[axis]) / 2.0; split_axis = axis; left.reset(new Node()); right.reset(new Node()); // Move elements to either 1 or 2 relevant children. for (size_t i = 0; i < elements->size(); ++i) { if (elements->at(i)->bounding_box()->min()[axis] <= split_position) { left->elements->push_back(elements->at(i)); } if (elements->at(i)->bounding_box()->max()[axis] >= split_position) { right->elements->push_back(elements->at(i)); } } // Recursively split children. Point3 left_max = box->max(); left_max[axis] = split_position; BoundingBox left_box(box->min(), left_max); left->Split(axis.Next(), depth + 1, &left_box); Point3 right_min = box->min(); right_min[axis] = split_position; BoundingBox right_box(right_min, box->max()); right->Split(axis.Next(), depth + 1, &right_box); // Clean up elements. elements.reset(); CHECK(!IsLeaf()) << "KdTree node still leaf after split"; } bool KdTree::Node::OwnRecursiveIntersect(const Ray& ray, Scalar t_near, Scalar t_far, IntersectionData* data) const { if (IsLeaf()) { bool intersected = false; for (size_t i = 0; i < elements->size(); ++i) { intersected = intersected | elements->at(i)->Intersect(ray, data); if (intersected && data == NULL) { return true; } } return intersected; } Scalar ray_direction_axis = ray.direction()[split_axis]; Scalar ray_origin_axis = ray.origin()[split_axis]; bool is_origin_left = (ray_origin_axis <= split_position); // If ray is parallel to split axis, anyting the ray intersects with will // have to be on the side of the origin. if (ray_direction_axis == 0) { if (is_origin_left) { return left->Intersect(ray, t_near, t_far, data); } else { return right->Intersect(ray, t_near, t_far, data); } } // The near child is the child which is closer to the ray's origin in split // coordinates. The far child is the other one. const Node* near = is_origin_left ? left.get() : right.get(); const Node* far = is_origin_left ? right.get() : left.get(); Scalar t_split = (split_position - ray_origin_axis) / ray_origin_axis; if (t_split > t_far) { return near->Intersect(ray, t_near, t_far, data); } else if (t_split < t_near) { // TODO(dinow): Divergence between nev's implementation and mine. Need to // investigate further. if (ray.PointAt(t_near)[split_axis] < split_position) { return left->Intersect(ray, t_near, t_far, data); } else { return right->Intersect(ray, t_near, t_far, data); } // TODO(dinow): It looks like the above is equivalent to the following // because this is simply the near/far test again using the point at t_near // instead of the origin. //return far->Intersect(ray, t_near, t_far, data); } else { // This is the case t_near <= t_split <= t_far. Test both children. DVLOG(2) << "Intersecting both children"; bool intersected = false; if ((intersected = near->Intersect(ray, t_near, t_split)) && (data == NULL || data->t < t_split)) { return true; } else { return far->Intersect(ray, t_split, t_far, data) || intersected; } } } bool KdTree::Node::NevRecursiveIntersect(const Ray& ray, Scalar t_near, Scalar t_far, IntersectionData* data) const { if (IsLeaf()) { bool intersected = false; for (size_t i = 0; i < elements->size(); ++i) { intersected = intersected | elements->at(i)->Intersect(ray, data); if (intersected && data == NULL) { return true; } } return intersected; } Scalar ray_direction_axis = ray.direction()[split_axis]; Scalar ray_origin_axis = ray.origin()[split_axis]; // Ray not moving in direction of the split, so only intersections with one // side are possible. if (ray_direction_axis == 0) { if (ray_origin_axis <= split_position) { return left->Intersect(ray, t_near, t_far, data); } else { return right->Intersect(ray, t_near, t_far, data); } } bool intersected = false; // Determine where on the ray the split happens. Scalar t_split = (split_position - ray_origin_axis) / ray_direction_axis; // Determine which is the first child traversed by the ray. const Node* first = left.get(); const Node* second = right.get(); if (ray_direction_axis < 0) std::swap(first, second); // Call recursively. if (t_split > t_far) { return first->Intersect(ray, t_near, t_far, data); } else if (t_split < t_near) { return second->Intersect(ray, t_near, t_far, data); } else if ((intersected = first->Intersect(ray, t_near, t_split, data)) && (data == NULL || data->t < t_split)) { return true; } else { return second->Intersect(ray, t_split, t_far, data) || intersected; } } bool KdTree::Node::Intersect(const Ray& ray, Scalar t_near, Scalar t_far, IntersectionData* data) const { // TODO(dinow): Debug implementations and clean this up. //return OwnRecursiveIntersect(ray, t_near, t_far, data); return NevRecursiveIntersect(ray, t_near, t_far, data); } KdTree::KdTree() { } KdTree::~KdTree() { } size_t KdTree::NumElementsWithDuplicates() const { if (root_.get() == NULL) { return 0; } else { return root_->NumElements(); } } void KdTree::Init(const std::vector<std::unique_ptr<Element>>& elements) { root_.reset(new Node()); // Take the first bounded element as original box, and merge all the // following boxes. bool first = true; for (auto it = elements.begin(); it != elements.end(); ++it) { const Element* element = it->get(); if (element->IsBounded()) { const BoundingBox& box = *element->bounding_box(); if (first) { bounding_box_.reset(new BoundingBox(box)); first = false; } else { bounding_box_->Include(box); } root_->elements->push_back(element); } } LOG(INFO) << "Building KdTree for " << root_->elements->size() << " elements"; root_->Split(kInitialSplitAxis, 0, bounding_box_.get()); if (bounding_box_.get() != NULL) { DVLOG(2) << "Built KdTree with bounding box " << *bounding_box_; } } bool KdTree::Intersect(const Ray& ray, IntersectionData* data) const { if (root_.get() == NULL) { LOG(WARNING) << "Called intersect on uninitialized KdTree. Returning false"; } DVLOG(2) << "Intersecting with ray " << ray; Scalar t_near, t_far; if (!bounding_box_->Intersect(ray, &t_near, &t_far)) { //if (!bounding_box_->IntersectVoodoo(ray, &t_near, &t_far)) { DVLOG(2) << "Bounding box did not intersect"; return false; } return root_->Intersect(ray, t_near, t_far, data); } // static const Axis KdTree::kInitialSplitAxis = Axis::x(); // static const size_t KdTree::kTreeDepth = 20; // static const size_t KdTree::kLeafSizeThreshold = 40;
Fix nasty bug in KdTree building.
Fix nasty bug in KdTree building.
C++
mit
dinowernli/raytracer,dinowernli/raytracer,dinowernli/raytracer,dinowernli/raytracer
9357a53a7daf9071fc7e46bb6b511c318f02fdbe
util/options.cc
util/options.cc
// Copyright (c) 2011 The LevelDB Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. See the AUTHORS file for names of contributors. #include "leveldb/options.h" #include <limits> #include "leveldb/cache.h" #include "leveldb/compaction_filter.h" #include "leveldb/comparator.h" #include "leveldb/env.h" #include "leveldb/filter_policy.h" #include "leveldb/merge_operator.h" namespace leveldb { Options::Options() : comparator(BytewiseComparator()), merge_operator(nullptr), compaction_filter(nullptr), create_if_missing(false), error_if_exists(false), paranoid_checks(false), env(Env::Default()), info_log(nullptr), write_buffer_size(4<<20), max_write_buffer_number(2), min_write_buffer_number_to_merge(1), max_open_files(1000), block_size(4096), block_restart_interval(16), compression(kSnappyCompression), filter_policy(nullptr), num_levels(7), level0_file_num_compaction_trigger(4), level0_slowdown_writes_trigger(8), level0_stop_writes_trigger(12), max_mem_compaction_level(2), target_file_size_base(2 * 1048576), target_file_size_multiplier(1), max_bytes_for_level_base(10 * 1048576), max_bytes_for_level_multiplier(10), max_bytes_for_level_multiplier_additional(num_levels, 1), expanded_compaction_factor(25), source_compaction_factor(1), max_grandparent_overlap_factor(10), disableDataSync(false), use_fsync(false), db_stats_log_interval(1800), db_log_dir(""), disable_seek_compaction(false), delete_obsolete_files_period_micros(0), max_background_compactions(1), max_log_file_size(0), log_file_time_to_roll(0), keep_log_file_num(1000), rate_limit(0.0), rate_limit_delay_milliseconds(1000), max_manifest_file_size(std::numeric_limits<uint64_t>::max()), no_block_cache(false), table_cache_numshardbits(4), disable_auto_compactions(false), WAL_ttl_seconds(0), manifest_preallocation_size(4 * 1024 * 1024), purge_redundant_kvs_while_flush(true), allow_os_buffer(true), allow_mmap_reads(false), allow_mmap_writes(true), is_fd_close_on_exec(true), skip_log_error_on_recovery(false), stats_dump_period_sec(3600), block_size_deviation (10), advise_random_on_open(true), access_hint_on_compaction_start(NORMAL), use_adaptive_mutex(false), bytes_per_sync(0), compaction_style(kCompactionStyleLevel) { deletes_check_filter_first(false) { } static const char* const access_hints[] = { "NONE", "NORMAL", "SEQUENTIAL", "WILLNEED" }; void Options::Dump(Logger* log) const { Log(log," Options.comparator: %s", comparator->Name()); Log(log," Options.merge_operator: %s", merge_operator? merge_operator->Name() : "None"); Log(log," Options.compaction_filter: %s", compaction_filter? compaction_filter->Name() : "None"); Log(log," Options.error_if_exists: %d", error_if_exists); Log(log," Options.paranoid_checks: %d", paranoid_checks); Log(log," Options.env: %p", env); Log(log," Options.info_log: %p", info_log.get()); Log(log," Options.write_buffer_size: %zd", write_buffer_size); Log(log," Options.max_write_buffer_number: %d", max_write_buffer_number); Log(log," Options.max_open_files: %d", max_open_files); Log(log," Options.block_cache: %p", block_cache.get()); if (block_cache) { Log(log," Options.block_cache_size: %zd", block_cache->GetCapacity()); } Log(log," Options.block_size: %zd", block_size); Log(log," Options.block_restart_interval: %d", block_restart_interval); if (!compression_per_level.empty()) { for (unsigned int i = 0; i < compression_per_level.size(); i++) { Log(log," Options.compression[%d]: %d", i, compression_per_level[i]); } } else { Log(log," Options.compression: %d", compression); } Log(log," Options.filter_policy: %s", filter_policy == nullptr ? "nullptr" : filter_policy->Name()); Log(log," Options.num_levels: %d", num_levels); Log(log," Options.disableDataSync: %d", disableDataSync); Log(log," Options.use_fsync: %d", use_fsync); Log(log," Options.max_log_file_size: %ld", max_log_file_size); Log(log,"Options.max_manifest_file_size: %ld", max_manifest_file_size); Log(log," Options.log_file_time_to_roll: %ld", log_file_time_to_roll); Log(log," Options.keep_log_file_num: %ld", keep_log_file_num); Log(log," Options.db_stats_log_interval: %d", db_stats_log_interval); Log(log," Options.allow_os_buffer: %d", allow_os_buffer); Log(log," Options.allow_mmap_reads: %d", allow_mmap_reads); Log(log," Options.allow_mmap_writes: %d", allow_mmap_writes); Log(log," Options.min_write_buffer_number_to_merge: %d", min_write_buffer_number_to_merge); Log(log," Options.purge_redundant_kvs_while_flush: %d", purge_redundant_kvs_while_flush); Log(log," Options.compression_opts.window_bits: %d", compression_opts.window_bits); Log(log," Options.compression_opts.level: %d", compression_opts.level); Log(log," Options.compression_opts.strategy: %d", compression_opts.strategy); Log(log," Options.level0_file_num_compaction_trigger: %d", level0_file_num_compaction_trigger); Log(log," Options.level0_slowdown_writes_trigger: %d", level0_slowdown_writes_trigger); Log(log," Options.level0_stop_writes_trigger: %d", level0_stop_writes_trigger); Log(log," Options.max_mem_compaction_level: %d", max_mem_compaction_level); Log(log," Options.target_file_size_base: %d", target_file_size_base); Log(log," Options.target_file_size_multiplier: %d", target_file_size_multiplier); Log(log," Options.max_bytes_for_level_base: %ld", max_bytes_for_level_base); Log(log," Options.max_bytes_for_level_multiplier: %d", max_bytes_for_level_multiplier); for (int i = 0; i < num_levels; i++) { Log(log,"Options.max_bytes_for_level_multiplier_addtl[%d]: %d", i, max_bytes_for_level_multiplier_additional[i]); } Log(log," Options.expanded_compaction_factor: %d", expanded_compaction_factor); Log(log," Options.source_compaction_factor: %d", source_compaction_factor); Log(log," Options.max_grandparent_overlap_factor: %d", max_grandparent_overlap_factor); Log(log," Options.db_log_dir: %s", db_log_dir.c_str()); Log(log," Options.disable_seek_compaction: %d", disable_seek_compaction); Log(log," Options.no_block_cache: %d", no_block_cache); Log(log," Options.table_cache_numshardbits: %d", table_cache_numshardbits); Log(log," Options.delete_obsolete_files_period_micros: %ld", delete_obsolete_files_period_micros); Log(log," Options.max_background_compactions: %d", max_background_compactions); Log(log," Options.rate_limit: %.2f", rate_limit); Log(log," Options.rate_limit_delay_milliseconds: %d", rate_limit_delay_milliseconds); Log(log," Options.disable_auto_compactions: %d", disable_auto_compactions); Log(log," Options.WAL_ttl_seconds: %ld", WAL_ttl_seconds); Log(log," Options.manifest_preallocation_size: %ld", manifest_preallocation_size); Log(log," Options.purge_redundant_kvs_while_flush: %d", purge_redundant_kvs_while_flush); Log(log," Options.allow_os_buffer: %d", allow_os_buffer); Log(log," Options.allow_mmap_reads: %d", allow_mmap_reads); Log(log," Options.allow_mmap_writes: %d", allow_mmap_writes); Log(log," Options.is_fd_close_on_exec: %d", is_fd_close_on_exec); Log(log," Options.skip_log_error_on_recovery: %d", skip_log_error_on_recovery); Log(log," Options.stats_dump_period_sec: %d", stats_dump_period_sec); Log(log," Options.block_size_deviation: %d", block_size_deviation); Log(log," Options.advise_random_on_open: %d", advise_random_on_open); Log(log," Options.access_hint_on_compaction_start: %s", access_hints[access_hint_on_compaction_start]); Log(log," Options.use_adaptive_mutex: %d", use_adaptive_mutex); Log(log," Options.bytes_per_sync: %ld", bytes_per_sync); Log(log," Options.compaction_style: %d", compaction_style); Log(log," Options.deletes_check_filter_first: %d", deletes_check_filter_first); Log(log," Options.compaction_options_universal.size_ratio: %d", compaction_options_universal.size_ratio); Log(log," Options.compaction_options_universal.min_merge_width: %d", compaction_options_universal.min_merge_width); Log(log," Options.compaction_options_universal.max_merge_width: %d", compaction_options_universal.max_merge_width); } // Options::Dump // // The goal of this method is to create a configuration that // allows an application to write all files into L0 and // then do a single compaction to output all files into L1. Options* Options::PrepareForBulkLoad() { // never slowdown ingest. level0_file_num_compaction_trigger = (1<<30); level0_slowdown_writes_trigger = (1<<30); level0_stop_writes_trigger = (1<<30); // no auto compactions please. The application should issue a // manual compaction after all data is loaded into L0. disable_auto_compactions = true; disable_seek_compaction = true; disableDataSync = true; // A manual compaction run should pick all files in L0 in // a single compaction run. source_compaction_factor = (1<<30); // It is better to have only 2 levels, otherwise a manual // compaction would compact at every possible level, thereby // increasing the total time needed for compactions. num_levels = 2; // Prevent a memtable flush to automatically promote files // to L1. This is helpful so that all files that are // input to the manual compaction are all at L0. max_background_compactions = 2; // The compaction would create large files in L1. target_file_size_base = 256 * 1024 * 1024; return this; } } // namespace leveldb
// Copyright (c) 2011 The LevelDB Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. See the AUTHORS file for names of contributors. #include "leveldb/options.h" #include <limits> #include "leveldb/cache.h" #include "leveldb/compaction_filter.h" #include "leveldb/comparator.h" #include "leveldb/env.h" #include "leveldb/filter_policy.h" #include "leveldb/merge_operator.h" namespace leveldb { Options::Options() : comparator(BytewiseComparator()), merge_operator(nullptr), compaction_filter(nullptr), create_if_missing(false), error_if_exists(false), paranoid_checks(false), env(Env::Default()), info_log(nullptr), write_buffer_size(4<<20), max_write_buffer_number(2), min_write_buffer_number_to_merge(1), max_open_files(1000), block_size(4096), block_restart_interval(16), compression(kSnappyCompression), filter_policy(nullptr), num_levels(7), level0_file_num_compaction_trigger(4), level0_slowdown_writes_trigger(8), level0_stop_writes_trigger(12), max_mem_compaction_level(2), target_file_size_base(2 * 1048576), target_file_size_multiplier(1), max_bytes_for_level_base(10 * 1048576), max_bytes_for_level_multiplier(10), max_bytes_for_level_multiplier_additional(num_levels, 1), expanded_compaction_factor(25), source_compaction_factor(1), max_grandparent_overlap_factor(10), disableDataSync(false), use_fsync(false), db_stats_log_interval(1800), db_log_dir(""), disable_seek_compaction(false), delete_obsolete_files_period_micros(0), max_background_compactions(1), max_log_file_size(0), log_file_time_to_roll(0), keep_log_file_num(1000), rate_limit(0.0), rate_limit_delay_milliseconds(1000), max_manifest_file_size(std::numeric_limits<uint64_t>::max()), no_block_cache(false), table_cache_numshardbits(4), disable_auto_compactions(false), WAL_ttl_seconds(0), manifest_preallocation_size(4 * 1024 * 1024), purge_redundant_kvs_while_flush(true), allow_os_buffer(true), allow_mmap_reads(false), allow_mmap_writes(true), is_fd_close_on_exec(true), skip_log_error_on_recovery(false), stats_dump_period_sec(3600), block_size_deviation (10), advise_random_on_open(true), access_hint_on_compaction_start(NORMAL), use_adaptive_mutex(false), bytes_per_sync(0), compaction_style(kCompactionStyleLevel), deletes_check_filter_first(false) { } static const char* const access_hints[] = { "NONE", "NORMAL", "SEQUENTIAL", "WILLNEED" }; void Options::Dump(Logger* log) const { Log(log," Options.comparator: %s", comparator->Name()); Log(log," Options.merge_operator: %s", merge_operator? merge_operator->Name() : "None"); Log(log," Options.compaction_filter: %s", compaction_filter? compaction_filter->Name() : "None"); Log(log," Options.error_if_exists: %d", error_if_exists); Log(log," Options.paranoid_checks: %d", paranoid_checks); Log(log," Options.env: %p", env); Log(log," Options.info_log: %p", info_log.get()); Log(log," Options.write_buffer_size: %zd", write_buffer_size); Log(log," Options.max_write_buffer_number: %d", max_write_buffer_number); Log(log," Options.max_open_files: %d", max_open_files); Log(log," Options.block_cache: %p", block_cache.get()); if (block_cache) { Log(log," Options.block_cache_size: %zd", block_cache->GetCapacity()); } Log(log," Options.block_size: %zd", block_size); Log(log," Options.block_restart_interval: %d", block_restart_interval); if (!compression_per_level.empty()) { for (unsigned int i = 0; i < compression_per_level.size(); i++) { Log(log," Options.compression[%d]: %d", i, compression_per_level[i]); } } else { Log(log," Options.compression: %d", compression); } Log(log," Options.filter_policy: %s", filter_policy == nullptr ? "nullptr" : filter_policy->Name()); Log(log," Options.num_levels: %d", num_levels); Log(log," Options.disableDataSync: %d", disableDataSync); Log(log," Options.use_fsync: %d", use_fsync); Log(log," Options.max_log_file_size: %ld", max_log_file_size); Log(log,"Options.max_manifest_file_size: %ld", max_manifest_file_size); Log(log," Options.log_file_time_to_roll: %ld", log_file_time_to_roll); Log(log," Options.keep_log_file_num: %ld", keep_log_file_num); Log(log," Options.db_stats_log_interval: %d", db_stats_log_interval); Log(log," Options.allow_os_buffer: %d", allow_os_buffer); Log(log," Options.allow_mmap_reads: %d", allow_mmap_reads); Log(log," Options.allow_mmap_writes: %d", allow_mmap_writes); Log(log," Options.min_write_buffer_number_to_merge: %d", min_write_buffer_number_to_merge); Log(log," Options.purge_redundant_kvs_while_flush: %d", purge_redundant_kvs_while_flush); Log(log," Options.compression_opts.window_bits: %d", compression_opts.window_bits); Log(log," Options.compression_opts.level: %d", compression_opts.level); Log(log," Options.compression_opts.strategy: %d", compression_opts.strategy); Log(log," Options.level0_file_num_compaction_trigger: %d", level0_file_num_compaction_trigger); Log(log," Options.level0_slowdown_writes_trigger: %d", level0_slowdown_writes_trigger); Log(log," Options.level0_stop_writes_trigger: %d", level0_stop_writes_trigger); Log(log," Options.max_mem_compaction_level: %d", max_mem_compaction_level); Log(log," Options.target_file_size_base: %d", target_file_size_base); Log(log," Options.target_file_size_multiplier: %d", target_file_size_multiplier); Log(log," Options.max_bytes_for_level_base: %ld", max_bytes_for_level_base); Log(log," Options.max_bytes_for_level_multiplier: %d", max_bytes_for_level_multiplier); for (int i = 0; i < num_levels; i++) { Log(log,"Options.max_bytes_for_level_multiplier_addtl[%d]: %d", i, max_bytes_for_level_multiplier_additional[i]); } Log(log," Options.expanded_compaction_factor: %d", expanded_compaction_factor); Log(log," Options.source_compaction_factor: %d", source_compaction_factor); Log(log," Options.max_grandparent_overlap_factor: %d", max_grandparent_overlap_factor); Log(log," Options.db_log_dir: %s", db_log_dir.c_str()); Log(log," Options.disable_seek_compaction: %d", disable_seek_compaction); Log(log," Options.no_block_cache: %d", no_block_cache); Log(log," Options.table_cache_numshardbits: %d", table_cache_numshardbits); Log(log," Options.delete_obsolete_files_period_micros: %ld", delete_obsolete_files_period_micros); Log(log," Options.max_background_compactions: %d", max_background_compactions); Log(log," Options.rate_limit: %.2f", rate_limit); Log(log," Options.rate_limit_delay_milliseconds: %d", rate_limit_delay_milliseconds); Log(log," Options.disable_auto_compactions: %d", disable_auto_compactions); Log(log," Options.WAL_ttl_seconds: %ld", WAL_ttl_seconds); Log(log," Options.manifest_preallocation_size: %ld", manifest_preallocation_size); Log(log," Options.purge_redundant_kvs_while_flush: %d", purge_redundant_kvs_while_flush); Log(log," Options.allow_os_buffer: %d", allow_os_buffer); Log(log," Options.allow_mmap_reads: %d", allow_mmap_reads); Log(log," Options.allow_mmap_writes: %d", allow_mmap_writes); Log(log," Options.is_fd_close_on_exec: %d", is_fd_close_on_exec); Log(log," Options.skip_log_error_on_recovery: %d", skip_log_error_on_recovery); Log(log," Options.stats_dump_period_sec: %d", stats_dump_period_sec); Log(log," Options.block_size_deviation: %d", block_size_deviation); Log(log," Options.advise_random_on_open: %d", advise_random_on_open); Log(log," Options.access_hint_on_compaction_start: %s", access_hints[access_hint_on_compaction_start]); Log(log," Options.use_adaptive_mutex: %d", use_adaptive_mutex); Log(log," Options.bytes_per_sync: %ld", bytes_per_sync); Log(log," Options.compaction_style: %d", compaction_style); Log(log," Options.deletes_check_filter_first: %d", deletes_check_filter_first); Log(log," Options.compaction_options_universal.size_ratio: %d", compaction_options_universal.size_ratio); Log(log," Options.compaction_options_universal.min_merge_width: %d", compaction_options_universal.min_merge_width); Log(log," Options.compaction_options_universal.max_merge_width: %d", compaction_options_universal.max_merge_width); } // Options::Dump // // The goal of this method is to create a configuration that // allows an application to write all files into L0 and // then do a single compaction to output all files into L1. Options* Options::PrepareForBulkLoad() { // never slowdown ingest. level0_file_num_compaction_trigger = (1<<30); level0_slowdown_writes_trigger = (1<<30); level0_stop_writes_trigger = (1<<30); // no auto compactions please. The application should issue a // manual compaction after all data is loaded into L0. disable_auto_compactions = true; disable_seek_compaction = true; disableDataSync = true; // A manual compaction run should pick all files in L0 in // a single compaction run. source_compaction_factor = (1<<30); // It is better to have only 2 levels, otherwise a manual // compaction would compact at every possible level, thereby // increasing the total time needed for compactions. num_levels = 2; // Prevent a memtable flush to automatically promote files // to L1. This is helpful so that all files that are // input to the manual compaction are all at L0. max_background_compactions = 2; // The compaction would create large files in L1. target_file_size_base = 256 * 1024 * 1024; return this; } } // namespace leveldb
Fix merge problems with options.
Fix merge problems with options. Summary: Fix merge problems with options. Test Plan: Reviewers: CC: Task ID: # Blame Rev:
C++
bsd-3-clause
wenduo/rocksdb,JohnPJenkins/rocksdb,zhangpng/rocksdb,vashstorm/rocksdb,caijieming-baidu/rocksdb,geraldoandradee/rocksdb,wenduo/rocksdb,fengshao0907/rocksdb,makelivedotnet/rocksdb,fengshao0907/rocksdb,hobinyoon/rocksdb,wlqGit/rocksdb,facebook/rocksdb,temicai/rocksdb,Andymic/rocksdb,vmx/rocksdb,Vaisman/rocksdb,wenduo/rocksdb,fengshao0907/rocksdb,sorphi/rocksdb,JackLian/rocksdb,ryneli/rocksdb,jalexanderqed/rocksdb,tschottdorf/rocksdb,tsheasha/rocksdb,amyvmiwei/rocksdb,JackLian/rocksdb,norton/rocksdb,luckywhu/rocksdb,Applied-Duality/rocksdb,tsheasha/rocksdb,RyanTech/rocksdb,bbiao/rocksdb,Applied-Duality/rocksdb,facebook/rocksdb,facebook/rocksdb,zhangpng/rocksdb,tizzybec/rocksdb,OverlordQ/rocksdb,ylong/rocksdb,dkorolev/rocksdb,wlqGit/rocksdb,wskplho/rocksdb,tschottdorf/rocksdb,wat-ze-hex/rocksdb,wlqGit/rocksdb,vmx/rocksdb,wskplho/rocksdb,flabby/rocksdb,norton/rocksdb,rDSN-Projects/rocksdb.replicated,temicai/rocksdb,norton/rocksdb,lgscofield/rocksdb,SunguckLee/RocksDB,ylong/rocksdb,makelivedotnet/rocksdb,biddyweb/rocksdb,tschottdorf/rocksdb,lgscofield/rocksdb,luckywhu/rocksdb,skunkwerks/rocksdb,tizzybec/rocksdb,biddyweb/rocksdb,virtdb/rocksdb,bbiao/rocksdb,kaschaeffer/rocksdb,flabby/rocksdb,dkorolev/rocksdb,temicai/rocksdb,wenduo/rocksdb,temicai/rocksdb,Andymic/rocksdb,lgscofield/rocksdb,OverlordQ/rocksdb,lgscofield/rocksdb,OverlordQ/rocksdb,biddyweb/rocksdb,Andymic/rocksdb,rDSN-Projects/rocksdb.replicated,JackLian/rocksdb,mbarbon/rocksdb,msb-at-yahoo/rocksdb,vashstorm/rocksdb,tsheasha/rocksdb,mbarbon/rocksdb,SunguckLee/RocksDB,amyvmiwei/rocksdb,jalexanderqed/rocksdb,caijieming-baidu/rocksdb,hobinyoon/rocksdb,wenduo/rocksdb,ryneli/rocksdb,tizzybec/rocksdb,makelivedotnet/rocksdb,ylong/rocksdb,wlqGit/rocksdb,mbarbon/rocksdb,Vaisman/rocksdb,bbiao/rocksdb,OverlordQ/rocksdb,wat-ze-hex/rocksdb,sorphi/rocksdb,flabby/rocksdb,Vaisman/rocksdb,norton/rocksdb,amyvmiwei/rocksdb,tizzybec/rocksdb,tsheasha/rocksdb,Applied-Duality/rocksdb,hobinyoon/rocksdb,OverlordQ/rocksdb,NickCis/rocksdb,msb-at-yahoo/rocksdb,dkorolev/rocksdb,tschottdorf/rocksdb,anagav/rocksdb,ryneli/rocksdb,ryneli/rocksdb,jalexanderqed/rocksdb,alihalabyah/rocksdb,Andymic/rocksdb,JohnPJenkins/rocksdb,dkorolev/rocksdb,JohnPJenkins/rocksdb,ryneli/rocksdb,vmx/rocksdb,dkorolev/rocksdb,Andymic/rocksdb,facebook/rocksdb,lgscofield/rocksdb,wlqGit/rocksdb,msb-at-yahoo/rocksdb,JohnPJenkins/rocksdb,NickCis/rocksdb,bbiao/rocksdb,siddhartharay007/rocksdb,makelivedotnet/rocksdb,dkorolev/rocksdb,JoeWoo/rocksdb,fengshao0907/rocksdb,kaschaeffer/rocksdb,siddhartharay007/rocksdb,skunkwerks/rocksdb,zhangpng/rocksdb,geraldoandradee/rocksdb,virtdb/rocksdb,Vaisman/rocksdb,ylong/rocksdb,Andymic/rocksdb,JoeWoo/rocksdb,anagav/rocksdb,caijieming-baidu/rocksdb,Applied-Duality/rocksdb,anagav/rocksdb,SunguckLee/RocksDB,JoeWoo/rocksdb,rDSN-Projects/rocksdb.replicated,temicai/rocksdb,alihalabyah/rocksdb,SunguckLee/RocksDB,vmx/rocksdb,luckywhu/rocksdb,NickCis/rocksdb,skunkwerks/rocksdb,tizzybec/rocksdb,flabby/rocksdb,hobinyoon/rocksdb,siddhartharay007/rocksdb,virtdb/rocksdb,IMCG/RcoksDB,JoeWoo/rocksdb,amyvmiwei/rocksdb,vashstorm/rocksdb,geraldoandradee/rocksdb,flabby/rocksdb,rDSN-Projects/rocksdb.replicated,kaschaeffer/rocksdb,anagav/rocksdb,anagav/rocksdb,IMCG/RcoksDB,vashstorm/rocksdb,makelivedotnet/rocksdb,makelivedotnet/rocksdb,bbiao/rocksdb,vmx/rocksdb,ryneli/rocksdb,norton/rocksdb,geraldoandradee/rocksdb,norton/rocksdb,jalexanderqed/rocksdb,SunguckLee/RocksDB,kaschaeffer/rocksdb,luckywhu/rocksdb,norton/rocksdb,ryneli/rocksdb,virtdb/rocksdb,wskplho/rocksdb,JackLian/rocksdb,wenduo/rocksdb,SunguckLee/RocksDB,JackLian/rocksdb,wskplho/rocksdb,mbarbon/rocksdb,vashstorm/rocksdb,temicai/rocksdb,sorphi/rocksdb,IMCG/RcoksDB,JohnPJenkins/rocksdb,alihalabyah/rocksdb,norton/rocksdb,Vaisman/rocksdb,wat-ze-hex/rocksdb,Applied-Duality/rocksdb,biddyweb/rocksdb,lgscofield/rocksdb,wenduo/rocksdb,wskplho/rocksdb,JohnPJenkins/rocksdb,Applied-Duality/rocksdb,biddyweb/rocksdb,tizzybec/rocksdb,facebook/rocksdb,amyvmiwei/rocksdb,jalexanderqed/rocksdb,amyvmiwei/rocksdb,wenduo/rocksdb,sorphi/rocksdb,zhangpng/rocksdb,wlqGit/rocksdb,JackLian/rocksdb,anagav/rocksdb,ylong/rocksdb,dkorolev/rocksdb,IMCG/RcoksDB,luckywhu/rocksdb,bbiao/rocksdb,temicai/rocksdb,IMCG/RcoksDB,tsheasha/rocksdb,SunguckLee/RocksDB,skunkwerks/rocksdb,luckywhu/rocksdb,JoeWoo/rocksdb,skunkwerks/rocksdb,rDSN-Projects/rocksdb.replicated,hobinyoon/rocksdb,flabby/rocksdb,mbarbon/rocksdb,skunkwerks/rocksdb,geraldoandradee/rocksdb,fengshao0907/rocksdb,SunguckLee/RocksDB,mbarbon/rocksdb,zhangpng/rocksdb,makelivedotnet/rocksdb,tschottdorf/rocksdb,kaschaeffer/rocksdb,facebook/rocksdb,OverlordQ/rocksdb,RyanTech/rocksdb,kaschaeffer/rocksdb,bbiao/rocksdb,alihalabyah/rocksdb,JackLian/rocksdb,ylong/rocksdb,virtdb/rocksdb,NickCis/rocksdb,wlqGit/rocksdb,hobinyoon/rocksdb,caijieming-baidu/rocksdb,tsheasha/rocksdb,jalexanderqed/rocksdb,alihalabyah/rocksdb,RyanTech/rocksdb,wat-ze-hex/rocksdb,wat-ze-hex/rocksdb,Vaisman/rocksdb,sorphi/rocksdb,wskplho/rocksdb,tsheasha/rocksdb,OverlordQ/rocksdb,jalexanderqed/rocksdb,JohnPJenkins/rocksdb,RyanTech/rocksdb,bbiao/rocksdb,rDSN-Projects/rocksdb.replicated,zhangpng/rocksdb,hobinyoon/rocksdb,rDSN-Projects/rocksdb.replicated,wat-ze-hex/rocksdb,wskplho/rocksdb,vmx/rocksdb,siddhartharay007/rocksdb,vmx/rocksdb,IMCG/RcoksDB,RyanTech/rocksdb,wat-ze-hex/rocksdb,zhangpng/rocksdb,wat-ze-hex/rocksdb,siddhartharay007/rocksdb,vmx/rocksdb,skunkwerks/rocksdb,tschottdorf/rocksdb,siddhartharay007/rocksdb,caijieming-baidu/rocksdb,alihalabyah/rocksdb,virtdb/rocksdb,JoeWoo/rocksdb,kaschaeffer/rocksdb,amyvmiwei/rocksdb,RyanTech/rocksdb,caijieming-baidu/rocksdb,vashstorm/rocksdb,alihalabyah/rocksdb,facebook/rocksdb,geraldoandradee/rocksdb,biddyweb/rocksdb,siddhartharay007/rocksdb,msb-at-yahoo/rocksdb,fengshao0907/rocksdb,Applied-Duality/rocksdb,mbarbon/rocksdb,msb-at-yahoo/rocksdb,ylong/rocksdb,caijieming-baidu/rocksdb,flabby/rocksdb,msb-at-yahoo/rocksdb,Andymic/rocksdb,vashstorm/rocksdb,IMCG/RcoksDB,anagav/rocksdb,Andymic/rocksdb,hobinyoon/rocksdb,virtdb/rocksdb,tizzybec/rocksdb,NickCis/rocksdb,NickCis/rocksdb,sorphi/rocksdb,JoeWoo/rocksdb,sorphi/rocksdb,tsheasha/rocksdb,fengshao0907/rocksdb,luckywhu/rocksdb,Vaisman/rocksdb,geraldoandradee/rocksdb,biddyweb/rocksdb,RyanTech/rocksdb,lgscofield/rocksdb,NickCis/rocksdb,facebook/rocksdb
de382903a709bcc62a84719eb97240b35ae23ea4
util/vector.cpp
util/vector.cpp
/* * vector.cpp * * Created on: 17/09/2013 * Author: drb */ #include "vector.h" #define _USE_MATH_DEFINES #include <cmath> #include <vector> /* * Rotation using point rotation around the origin ( more here http://en.wikipedia.org/wiki/Rotation_%28mathematics%29 ) * Angle in degrees */ std::vector<SDL_Point> translate (std::vector<SDL_Point> points, SDL_Point center , double angle, SDL_Point offset) { //Create output vector std::vector<SDL_Point> n_points; //Reserve the same amount of points n_points.reserve(points.size()); //Pre-calculate sin and cos as they will not change double a_sin = 0; double a_cos = 1; if (angle != 0) { a_sin = sin( (angle / 180.0) * M_PI ); a_cos = cos( (angle / 180.0) * M_PI ); } for (unsigned int i = 0; i < points.size(); i++) { SDL_Point pt; //Offset so the center is the origin of the points pt.x = (points[i].x - center.x); pt.y = (points[i].y - center.y); //No rotational translation needed if angle = 0 if (angle != 0) { //Rotate the point around the origin by angle degrees int py = pt.y; int px = pt.x; pt.x = round(px*a_cos - py*a_sin); pt.y = round(px*a_sin + py*a_cos); } //Returning the points back to before the origin change pt.x = pt.x + center.x + offset.x; pt.y = pt.y + center.y + offset.y; //Add them to the output list n_points.push_back(pt); } return n_points; } void translatept (std::vector<SDL_Point>* points, SDL_Point center , double angle, SDL_Point offset) { //Pre-calculate sin and cos as they will not change double a_sin = 0; double a_cos = 1; if (angle != 0) { a_sin = sin( (angle / 180.0) * M_PI ); a_cos = cos( (angle / 180.0) * M_PI ); } for (unsigned int i = 0; i < (*points).size(); i++) { SDL_Point pt; //Offset so the center is the origin of the points pt.x = ((*points)[i].x - center.x); pt.y = ((*points)[i].y - center.y); //No rotational translation needed if angle = 0 if (angle != 0) { //Rotate the point around the origin by angle degrees int py = pt.y; int px = pt.x; pt.x = round(px*a_cos - py*a_sin); pt.y = round(px*a_sin + py*a_cos); } //Returning the points back to before the origin change pt.x = pt.x + center.x + offset.x; pt.y = pt.y + center.y + offset.y; //Edit the points in the list (*points)[i].x = pt.x; (*points)[i].y = pt.y; } } /* * Tests if a given point is within a polygon * Using ray casting algorithm http://en.wikipedia.org/wiki/Point_in_polygon */ bool IsPointInsidePolygon (SDL_Point point , std::vector<SDL_Point>* points) { //Code converted from pseudo code from http://stackoverflow.com/questions/11716268/point-in-polygon-algorithm //Credit for this snippet goes to http://stackoverflow.com/users/1830407/josh int i, j, nvert = points->size(); bool c = false; for(i = 0, j = nvert - 1; i < nvert; j = i++) { if( ( ( (*points)[i].y ) >= point.y) != ( ((*points)[j].y >= point.y) ) && (point.x <= ((*points)[j].x - (*points)[i].x) * (point.y - (*points)[i].y) / ((*points)[j].y - (*points)[i].y) + (*points)[i].x)) c = !c; } return c; } bool IsPointInsidePolygon (SDL_Point point , std::vector<SDL_Point> points) { //Code converted from pseudo code from http://stackoverflow.com/questions/11716268/point-in-polygon-algorithm //Credit for this snippet goes to http://stackoverflow.com/users/1830407/josh int i, j, nvert = points.size(); bool c = false; for(i = 0, j = nvert - 1; i < nvert; j = i++) { if( ( ( (points)[i].y ) >= point.y) != ( ((points)[j].y >= point.y) ) && (point.x <= ((points)[j].x - (points)[i].x) * (point.y - (points)[i].y) / ((points)[j].y - (points)[i].y) + (points)[i].x)) c = !c; } return c; } bool isPolygonInsidePolygon(std::vector<SDL_Point>* pt , std::vector<SDL_Point>* polygon) { //Cycle through all the points of one polygon for (unsigned int i = 0; i < (*pt).size(); i++) { if ( IsPointInsidePolygon( (*pt)[i] , polygon) ) { return true; } } return false; } bool isPolygonInsidePolygon(std::vector<SDL_Point> pt , std::vector<SDL_Point> polygon) { //Cycle through all the points of one polygon for (unsigned int i = 0; i < (pt).size(); i++) { if ( IsPointInsidePolygon( (pt)[i] , polygon) ) { return true; } } return false; } bool isRectTouching (SDL_Rect aRect, SDL_Rect bRect) { /* * Point's for rectangle (x,y) , (x+w,y) , (x+w,y+h) , (x,y+h) * Checks if the points are in the bounds of each other */ if (aRect.x < (bRect.x + bRect.w) && (aRect.x + aRect.w) > bRect.x && aRect.y < (bRect.y + bRect.h) && (aRect.y + aRect.h) > bRect.y) { return true; } else { return false; } } bool isRectTouching (SDL_Rect* aRect, SDL_Rect* bRect) { /* * Point's for rectangle (x,y) , (x+w,y) , (x+w,y+h) , (x,y+h) * Checks if the points are in the bounds of each other * Pointers to SDL_rect's are used for faster(?) usage of properties */ if (aRect->x < (bRect->x + bRect->w) && (aRect->x + aRect->w) > bRect->x && aRect->y < (bRect->y + bRect->h) && (aRect->y + aRect->h) > bRect->y) { return true; } else { return false; } } bool isSpriteTouchingSprite (sprite sp1 , sprite sp2) { //if ( isRectTouching( sp1.getBounds() , sp2.getBounds() ) ) { bool touching = isPolygonInsidePolygon( sp1.getPointBounds() , sp2.getPointBounds() ); return touching; } return false; } std::vector<SDL_Point> RectToPoints (SDL_Rect rect , double angle) { std::vector<SDL_Point> points; points.reserve(4); SDL_Point pt , pos; pos.x = rect.x; pos.y = rect.y; pt.x = 0; pt.y = 0; points.push_back(pt); pt.x = rect.w; pt.y = 0; points.push_back(pt); pt.x = rect.w; pt.y = rect.h; points.push_back(pt); pt.x = 0; pt.y = rect.y + rect.h; points.push_back(pt); pt.x = rect.w / 2; pt.y = rect.h / 2; translatept( &points , pt , angle , pos); return points; } SDL_Rect RectSubtract (SDL_Rect rect, SDL_Point pt ) { SDL_Rect rt = rect; rect.x -= pt.x; rect.y -= pt.y; return rt; } SDL_Rect RectSubtract (SDL_Rect rect, SDL_Rect pt ) { SDL_Rect rt = rect; rect.x -= pt.x; rect.y -= pt.y; return rt; } SDL_Point PointSubtract (SDL_Point pt1 , SDL_Point pt2 ) { pt1.x = pt1.x - pt2.x; pt1.y = pt1.y - pt2.y; return pt1; } bool isWholeRectInside (SDL_Rect small, SDL_Rect big ) { if ( small.x > big.x && small.y > big.y && (small.x + small.w) < (big.x + big.w) && (small.y + small.h) < (big.y + big.h) ) { return true; } else { return false; } }
/* * vector.cpp * * Created on: 17/09/2013 * Author: drb */ #include "vector.h" #define _USE_MATH_DEFINES #include <cmath> #include <vector> /* * Rotation using point rotation around the origin ( more here http://en.wikipedia.org/wiki/Rotation_%28mathematics%29 ) * Angle in degrees */ std::vector<SDL_Point> translate (std::vector<SDL_Point> points, SDL_Point center , double angle, SDL_Point offset) { //Create output vector std::vector<SDL_Point> n_points; //Reserve the same amount of points n_points.reserve(points.size()); //Pre-calculate sin and cos as they will not change double a_sin = 0; double a_cos = 1; if (angle != 0) { a_sin = sin( (angle / 180.0) * M_PI ); a_cos = cos( (angle / 180.0) * M_PI ); } for (unsigned int i = 0; i < points.size(); i++) { SDL_Point pt; //Offset so the center is the origin of the points pt.x = (points[i].x - center.x); pt.y = (points[i].y - center.y); //No rotational translation needed if angle = 0 if (angle != 0) { //Rotate the point around the origin by angle degrees int py = pt.y; int px = pt.x; pt.x = round(px*a_cos - py*a_sin); pt.y = round(px*a_sin + py*a_cos); } //Returning the points back to before the origin change pt.x = pt.x + center.x + offset.x; pt.y = pt.y + center.y + offset.y; //Add them to the output list n_points.push_back(pt); } return n_points; } void translatept (std::vector<SDL_Point>* points, SDL_Point center , double angle, SDL_Point offset) { //Pre-calculate sin and cos as they will not change double a_sin = 0; double a_cos = 1; if (angle != 0) { a_sin = sin( (angle / 180.0) * M_PI ); a_cos = cos( (angle / 180.0) * M_PI ); } for (unsigned int i = 0; i < (*points).size(); i++) { SDL_Point pt; //Offset so the center is the origin of the points pt.x = ((*points)[i].x - center.x); pt.y = ((*points)[i].y - center.y); //No rotational translation needed if angle = 0 if (angle != 0) { //Rotate the point around the origin by angle degrees int py = pt.y; int px = pt.x; pt.x = round(px*a_cos - py*a_sin); pt.y = round(px*a_sin + py*a_cos); } //Returning the points back to before the origin change pt.x = pt.x + center.x + offset.x; pt.y = pt.y + center.y + offset.y; //Edit the points in the list (*points)[i].x = pt.x; (*points)[i].y = pt.y; } } /* * Tests if a given point is within a polygon * Using ray casting algorithm http://en.wikipedia.org/wiki/Point_in_polygon */ bool IsPointInsidePolygon (SDL_Point point , std::vector<SDL_Point>* points) { //Code converted from pseudo code from http://stackoverflow.com/questions/11716268/point-in-polygon-algorithm //Credit for this snippet goes to http://stackoverflow.com/users/1830407/josh int i, j, nvert = points->size(); bool c = false; for(i = 0, j = nvert - 1; i < nvert; j = i++) { if( ( ( (*points)[i].y ) >= point.y) != ( ((*points)[j].y >= point.y) ) && (point.x <= ((*points)[j].x - (*points)[i].x) * (point.y - (*points)[i].y) / ((*points)[j].y - (*points)[i].y) + (*points)[i].x)) c = !c; } return c; } bool IsPointInsidePolygon (SDL_Point point , std::vector<SDL_Point> points) { //Code converted from pseudo code from http://stackoverflow.com/questions/11716268/point-in-polygon-algorithm //Credit for this snippet goes to http://stackoverflow.com/users/1830407/josh int i, j, nvert = points.size(); bool c = false; for(i = 0, j = nvert - 1; i < nvert; j = i++) { if( ( ( (points)[i].y ) >= point.y) != ( ((points)[j].y >= point.y) ) && (point.x <= ((points)[j].x - (points)[i].x) * (point.y - (points)[i].y) / ((points)[j].y - (points)[i].y) + (points)[i].x)) c = !c; } return c; } bool isPolygonInsidePolygon(std::vector<SDL_Point>* pt , std::vector<SDL_Point>* polygon) { //Cycle through all the points of one polygon for (unsigned int i = 0; i < (*pt).size(); i++) { if ( IsPointInsidePolygon( (*pt)[i] , polygon) ) { return true; } } return false; } bool isPolygonInsidePolygon(std::vector<SDL_Point> pt , std::vector<SDL_Point> polygon) { //Cycle through all the points of one polygon for (unsigned int i = 0; i < (pt).size(); i++) { if ( IsPointInsidePolygon( (pt)[i] , polygon) ) { return true; } } return false; } bool isRectTouching (SDL_Rect aRect, SDL_Rect bRect) { /* * Point's for rectangle (x,y) , (x+w,y) , (x+w,y+h) , (x,y+h) * Checks if the points are in the bounds of each other */ if (aRect.x < (bRect.x + bRect.w) && (aRect.x + aRect.w) > bRect.x && aRect.y < (bRect.y + bRect.h) && (aRect.y + aRect.h) > bRect.y) { return true; } else { return false; } } bool isRectTouching (SDL_Rect* aRect, SDL_Rect* bRect) { /* * Point's for rectangle (x,y) , (x+w,y) , (x+w,y+h) , (x,y+h) * Checks if the points are in the bounds of each other * Pointers to SDL_rect's are used for faster(?) usage of properties */ if (aRect->x < (bRect->x + bRect->w) && (aRect->x + aRect->w) > bRect->x && aRect->y < (bRect->y + bRect->h) && (aRect->y + aRect->h) > bRect->y) { return true; } else { return false; } } bool isSpriteTouchingSprite (sprite sp1 , sprite sp2) { if ( isRectTouching( sp1.getBounds() , sp2.getBounds() ) ) { bool touching = isPolygonInsidePolygon( sp1.getPointBounds() , sp2.getPointBounds() ); return touching; } return false; } std::vector<SDL_Point> RectToPoints (SDL_Rect rect , double angle) { std::vector<SDL_Point> points; points.reserve(4); SDL_Point pt , pos; pos.x = rect.x; pos.y = rect.y; pt.x = 0; pt.y = 0; points.push_back(pt); pt.x = rect.w; pt.y = 0; points.push_back(pt); pt.x = rect.w; pt.y = rect.h; points.push_back(pt); pt.x = 0; pt.y = rect.y + rect.h; points.push_back(pt); pt.x = rect.w / 2; pt.y = rect.h / 2; translatept( &points , pt , angle , pos); return points; } SDL_Rect RectSubtract (SDL_Rect rect, SDL_Point pt ) { SDL_Rect rt = rect; rect.x -= pt.x; rect.y -= pt.y; return rt; } SDL_Rect RectSubtract (SDL_Rect rect, SDL_Rect pt ) { SDL_Rect rt = rect; rect.x -= pt.x; rect.y -= pt.y; return rt; } SDL_Point PointSubtract (SDL_Point pt1 , SDL_Point pt2 ) { pt1.x = pt1.x - pt2.x; pt1.y = pt1.y - pt2.y; return pt1; } bool isWholeRectInside (SDL_Rect small, SDL_Rect big ) { if ( small.x > big.x && small.y > big.y && (small.x + small.w) < (big.x + big.w) && (small.y + small.h) < (big.y + big.h) ) { return true; } else { return false; } }
Update vector.cpp
Update vector.cpp Turned Rect check in the polygon collision check.
C++
unlicense
zyphrus/asteroids,zyphrus/asteroids
817e54b1baa830b25979dd68c8b2c852aa864cbe
src/cpp/session/modules/zotero/ZoteroCollectionsWeb.cpp
src/cpp/session/modules/zotero/ZoteroCollectionsWeb.cpp
/* * ZoteroCollectionsWeb.cpp * * Copyright (C) 2009-20 by RStudio, Inc. * * Unless you have received this program directly from RStudio pursuant * to the terms of a commercial license agreement with RStudio, then * this program is licensed to you under the terms of version 3 of the * GNU Affero General Public License. This program is distributed WITHOUT * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT, * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details. * */ #include "ZoteroCollectionsWeb.hpp" #include <boost/bind.hpp> #include <boost/algorithm/algorithm.hpp> #include <boost/enable_shared_from_this.hpp> #include <shared_core/Error.hpp> #include <shared_core/json/Json.hpp> #include <core/system/Process.hpp> #include <session/SessionModuleContext.hpp> #include <session/SessionAsyncDownloadFile.hpp> using namespace rstudio::core; namespace rstudio { namespace session { namespace modules { namespace zotero { namespace collections { namespace { const char * const kZoteroApiHost = "https://api.zotero.org"; typedef boost::function<void(const core::Error&,int,core::json::Value)> ZoteroJsonResponseHandler; void zoteroJsonRequest(const std::string& key, const std::string& resource, http::Fields queryParams, const std::string& schema, const ZoteroJsonResponseHandler& handler) { // authorize using header or url param as required http::Fields headers; if (!key.empty()) { if (module_context::hasMinimumRVersion("3.6")) { boost::format fmt("Bearer %s"); headers.push_back(std::make_pair("Authorization", "Bearer " + key)); } else { queryParams.push_back(std::make_pair("key", key)); } } // build query string std::string queryString; core::http::util::buildQueryString(queryParams, &queryString); if (queryString.length() > 0) queryString = "?" + queryString; // build the url and make the request boost::format fmt("%s/%s%s"); const std::string url = boost::str(fmt % kZoteroApiHost % resource % queryString); asyncDownloadFile(url, headers, [handler, schema](const core::system::ProcessResult& result) { if (result.exitStatus == EXIT_SUCCESS) { json::Value resultJson; Error error; if (schema.length() > 0) error = resultJson.parseAndValidate(result.stdOut, schema); else error = resultJson.parse(result.stdOut); if (error) { handler(error, 500, json::Value()); } else { handler(Success(), 200, resultJson); } } else { Error error = systemError(boost::system::errc::state_not_recoverable, result.stdErr, ERROR_LOCATION); handler(error, 500, json::Value()); } }); } void zoteroItemRequest(const std::string& key, const std::string& path, const ZoteroJsonResponseHandler& handler) { std::string schema = module_context::resourceFileAsString("schema/zotero-items.json"); http::Fields params; params.push_back(std::make_pair("format", "json")); params.push_back(std::make_pair("include", "csljson")); params.push_back(std::make_pair("itemType", "-attachment")); zoteroJsonRequest(key, path, params, schema, handler); } void zoteroKeyInfo(const std::string& key, const ZoteroJsonResponseHandler& handler) { std::string schema = module_context::resourceFileAsString("schema/zotero-key.json"); boost::format fmt("keys/%s"); zoteroJsonRequest("", boost::str(fmt % key), http::Fields(), schema, handler); } void zoteroCollections(const std::string& key, int userID, const ZoteroJsonResponseHandler& handler) { std::string schema = module_context::resourceFileAsString("schema/zotero-collections.json"); http::Fields params; params.push_back(std::make_pair("format", "json")); boost::format fmt("users/%d/collections"); zoteroJsonRequest(key, boost::str(fmt % userID), params, schema, handler); } void zoteroItemsForCollection(const std::string& key, int userID, const std::string& collectionID, const ZoteroJsonResponseHandler& handler) { boost::format fmt("users/%d/collections/%s/items"); zoteroItemRequest(key, boost::str(fmt % userID % collectionID), handler); } // keep a persistent mapping of apiKey to userId so we don't need to do the lookup each time core::Settings s_userIdMap; // utility class to download a set of zotero collections class ZoteroCollectionsDownloader; typedef boost::shared_ptr<ZoteroCollectionsDownloader> ZoteroCollectionsDownloaderPtr; class ZoteroCollectionsDownloader : public boost::enable_shared_from_this<ZoteroCollectionsDownloader> { public: static ZoteroCollectionsDownloaderPtr create(const std::string& key, int userID, const std::vector<std::pair<std::string,ZoteroCollectionSpec> >& collections, ZoteroCollectionsHandler handler) { ZoteroCollectionsDownloaderPtr pDownloader(new ZoteroCollectionsDownloader(key, userID, collections, handler)); pDownloader->downloadNextCollection(); return pDownloader; } public: private: ZoteroCollectionsDownloader(const std::string& key, int userID, const std::vector<std::pair<std::string,ZoteroCollectionSpec> >& collections, ZoteroCollectionsHandler handler) : key_(key), userID_(userID), handler_(handler) { for (auto collection : collections) collectionQueue_.push(collection); } void downloadNextCollection() { if (collectionQueue_.size() > 0) { // get next queue item auto next = collectionQueue_.front(); collectionQueue_.pop(); // download it zoteroItemsForCollection(key_, userID_, next.first, boost::bind(&ZoteroCollectionsDownloader::handleCollectionDownload, ZoteroCollectionsDownloader::shared_from_this(), next.second, _1, _2, _3)); } else { handler_(Success(), collections_); } } void handleCollectionDownload(ZoteroCollectionSpec spec, const Error& error,int,json::Value jsonValue) { if (error) { handler_(error, std::vector<ZoteroCollection>()); } else { // create collection ZoteroCollection collection; collection.name = spec.name; collection.version = spec.version; json::Array itemsJson; json::Array resultItemsJson = jsonValue.getArray(); std::transform(resultItemsJson.begin(), resultItemsJson.end(), std::back_inserter(itemsJson), [](const json::Value& resultItemJson) { return resultItemJson.getObject()["csljson"]; }); collection.items = itemsJson; // append to our collections collections_.push_back(collection); // next collection downloadNextCollection(); } } private: std::string key_; int userID_; ZoteroCollectionsHandler handler_; std::queue<std::pair<std::string,ZoteroCollectionSpec> > collectionQueue_; ZoteroCollections collections_; }; void getWebCollectionsForUser(const std::string& key, int userID, const std::vector<std::string>& collections, const ZoteroCollectionSpecs& cacheSpecs, ZoteroCollectionsHandler handler) { // lookup all collections for the user zoteroCollections(key, userID, [key, userID, collections, cacheSpecs, handler](const Error& error,int,json::Value jsonValue) { if (error) { handler(error, std::vector<ZoteroCollection>()); return; } // divide collections into ones we need to do a download for, and one that // we already have an up to date version for ZoteroCollections upToDateCollections; std::vector<std::pair<std::string, ZoteroCollectionSpec>> downloadCollections; // download items for specified collections json::Array collectionsJson = jsonValue.getArray(); for (auto json : collectionsJson) { json::Object collectionJson = json.getObject()["data"].getObject(); std::string collectionID = collectionJson["key"].getString(); std::string name = collectionJson[kName].getString(); int version = collectionJson[kVersion].getInt(); // see if this is a requested collection bool requested = collections.size() == 0 || // all collections requested std::count_if(collections.begin(), collections.end(), [name](const std::string& str) { return boost::algorithm::iequals(name, str); }) > 0 ; if (requested) { // see if we need to do a download for this collection ZoteroCollectionSpecs::const_iterator it = std::find_if( cacheSpecs.begin(), cacheSpecs.end(), [name](ZoteroCollectionSpec spec) { return boost::algorithm::iequals(spec.name,name); } ); if (it != cacheSpecs.end()) { ZoteroCollectionSpec collectionSpec(name, version); if (it->version < version) downloadCollections.push_back(std::make_pair(collectionID, collectionSpec)); else upToDateCollections.push_back(collectionSpec); } else { downloadCollections.push_back(std::make_pair(collectionID, ZoteroCollectionSpec(name, version))); } } } // do the download ZoteroCollectionsDownloader::create(key, userID, downloadCollections, [handler, upToDateCollections](Error error,ZoteroCollections collections) { if (error) { handler(error, ZoteroCollections()); } else { // append downloaded collections to already up to date collections and return them std::copy(upToDateCollections.begin(), upToDateCollections.end(), std::back_inserter(collections)); handler(Success(), collections); } }); }); } void getWebCollections(const std::string& key, const std::vector<std::string>& collections, const ZoteroCollectionSpecs& cacheSpecs, ZoteroCollectionsHandler handler) { // see if we already have the user id if (s_userIdMap.contains(key)) { getWebCollectionsForUser(key, s_userIdMap.getInt(key), collections, cacheSpecs, handler); } else { // get the user id for this key zoteroKeyInfo(key, [key, handler, collections, cacheSpecs](const Error& error,int,json::Value jsonValue) { if (error) { handler(error, std::vector<ZoteroCollection>()); return; } // get the and cache it int userID = jsonValue.getObject()["userID"].getInt(); s_userIdMap.set(key, userID); // get the collections getWebCollectionsForUser(key, userID, collections, cacheSpecs, handler); }); } } } // end anonymous namespace void validateWebApiKey(const std::string& key, boost::function<void(bool)> handler) { zoteroKeyInfo(key, [handler](const Error& error,int,json::Value) { if (error) { std::string err = core::errorDescription(error); if (!is404Error(err)) LOG_ERROR(error); handler(false); } else { handler(true); } }); } ZoteroCollectionSource webCollections() { // one time initialization of user id map static bool initialized = false; if (!initialized) { Error error = s_userIdMap.initialize(module_context::userScratchPath().completeChildPath("zotero-userid")); if (error) LOG_ERROR(error); } ZoteroCollectionSource source; source.getCollections = getWebCollections; return source; } } // end namespace collections } // end namespace zotero } // end namespace modules } // end namespace session } // end namespace rstudio
/* * ZoteroCollectionsWeb.cpp * * Copyright (C) 2009-20 by RStudio, Inc. * * Unless you have received this program directly from RStudio pursuant * to the terms of a commercial license agreement with RStudio, then * this program is licensed to you under the terms of version 3 of the * GNU Affero General Public License. This program is distributed WITHOUT * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT, * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details. * */ #include "ZoteroCollectionsWeb.hpp" #include <boost/bind.hpp> #include <boost/algorithm/algorithm.hpp> #include <boost/enable_shared_from_this.hpp> #include <shared_core/Error.hpp> #include <shared_core/json/Json.hpp> #include <core/system/Process.hpp> #include <session/SessionModuleContext.hpp> #include <session/SessionAsyncDownloadFile.hpp> using namespace rstudio::core; namespace rstudio { namespace session { namespace modules { namespace zotero { namespace collections { namespace { const char * const kZoteroApiHost = "https://api.zotero.org"; const char * const kZoteroApiVersion = "3"; typedef boost::function<void(const core::Error&,int,core::json::Value)> ZoteroJsonResponseHandler; void zoteroJsonRequest(const std::string& key, const std::string& resource, http::Fields queryParams, const std::string& schema, const ZoteroJsonResponseHandler& handler) { // authorize using header or url param as required http::Fields headers; if (!key.empty()) { if (module_context::hasMinimumRVersion("3.6")) { boost::format fmt("Bearer %s"); headers.push_back(std::make_pair("Authorization", "Bearer " + key)); headers.push_back(std::make_pair("Zotero-API-Version", kZoteroApiVersion)); } else { queryParams.push_back(std::make_pair("key", key)); queryParams.push_back(std::make_pair("v", kZoteroApiVersion)); } } // build query string std::string queryString; core::http::util::buildQueryString(queryParams, &queryString); if (queryString.length() > 0) queryString = "?" + queryString; // build the url and make the request boost::format fmt("%s/%s%s"); const std::string url = boost::str(fmt % kZoteroApiHost % resource % queryString); asyncDownloadFile(url, headers, [handler, schema](const core::system::ProcessResult& result) { if (result.exitStatus == EXIT_SUCCESS) { json::Value resultJson; Error error; if (schema.length() > 0) error = resultJson.parseAndValidate(result.stdOut, schema); else error = resultJson.parse(result.stdOut); if (error) { handler(error, 500, json::Value()); } else { handler(Success(), 200, resultJson); } } else { Error error = systemError(boost::system::errc::state_not_recoverable, result.stdErr, ERROR_LOCATION); handler(error, 500, json::Value()); } }); } void zoteroItemRequest(const std::string& key, const std::string& path, const ZoteroJsonResponseHandler& handler) { std::string schema = module_context::resourceFileAsString("schema/zotero-items.json"); http::Fields params; params.push_back(std::make_pair("format", "json")); params.push_back(std::make_pair("include", "csljson")); params.push_back(std::make_pair("itemType", "-attachment")); zoteroJsonRequest(key, path, params, schema, handler); } void zoteroKeyInfo(const std::string& key, const ZoteroJsonResponseHandler& handler) { std::string schema = module_context::resourceFileAsString("schema/zotero-key.json"); boost::format fmt("keys/%s"); zoteroJsonRequest("", boost::str(fmt % key), http::Fields(), schema, handler); } void zoteroCollections(const std::string& key, int userID, const ZoteroJsonResponseHandler& handler) { std::string schema = module_context::resourceFileAsString("schema/zotero-collections.json"); http::Fields params; params.push_back(std::make_pair("format", "json")); boost::format fmt("users/%d/collections"); zoteroJsonRequest(key, boost::str(fmt % userID), params, schema, handler); } void zoteroItemsForCollection(const std::string& key, int userID, const std::string& collectionID, const ZoteroJsonResponseHandler& handler) { boost::format fmt("users/%d/collections/%s/items"); zoteroItemRequest(key, boost::str(fmt % userID % collectionID), handler); } // keep a persistent mapping of apiKey to userId so we don't need to do the lookup each time core::Settings s_userIdMap; // utility class to download a set of zotero collections class ZoteroCollectionsDownloader; typedef boost::shared_ptr<ZoteroCollectionsDownloader> ZoteroCollectionsDownloaderPtr; class ZoteroCollectionsDownloader : public boost::enable_shared_from_this<ZoteroCollectionsDownloader> { public: static ZoteroCollectionsDownloaderPtr create(const std::string& key, int userID, const std::vector<std::pair<std::string,ZoteroCollectionSpec> >& collections, ZoteroCollectionsHandler handler) { ZoteroCollectionsDownloaderPtr pDownloader(new ZoteroCollectionsDownloader(key, userID, collections, handler)); pDownloader->downloadNextCollection(); return pDownloader; } public: private: ZoteroCollectionsDownloader(const std::string& key, int userID, const std::vector<std::pair<std::string,ZoteroCollectionSpec> >& collections, ZoteroCollectionsHandler handler) : key_(key), userID_(userID), handler_(handler) { for (auto collection : collections) collectionQueue_.push(collection); } void downloadNextCollection() { if (collectionQueue_.size() > 0) { // get next queue item auto next = collectionQueue_.front(); collectionQueue_.pop(); // download it zoteroItemsForCollection(key_, userID_, next.first, boost::bind(&ZoteroCollectionsDownloader::handleCollectionDownload, ZoteroCollectionsDownloader::shared_from_this(), next.second, _1, _2, _3)); } else { handler_(Success(), collections_); } } void handleCollectionDownload(ZoteroCollectionSpec spec, const Error& error,int,json::Value jsonValue) { if (error) { handler_(error, std::vector<ZoteroCollection>()); } else { // create collection ZoteroCollection collection; collection.name = spec.name; collection.version = spec.version; json::Array itemsJson; json::Array resultItemsJson = jsonValue.getArray(); std::transform(resultItemsJson.begin(), resultItemsJson.end(), std::back_inserter(itemsJson), [](const json::Value& resultItemJson) { return resultItemJson.getObject()["csljson"]; }); collection.items = itemsJson; // append to our collections collections_.push_back(collection); // next collection downloadNextCollection(); } } private: std::string key_; int userID_; ZoteroCollectionsHandler handler_; std::queue<std::pair<std::string,ZoteroCollectionSpec> > collectionQueue_; ZoteroCollections collections_; }; void getWebCollectionsForUser(const std::string& key, int userID, const std::vector<std::string>& collections, const ZoteroCollectionSpecs& cacheSpecs, ZoteroCollectionsHandler handler) { // lookup all collections for the user zoteroCollections(key, userID, [key, userID, collections, cacheSpecs, handler](const Error& error,int,json::Value jsonValue) { if (error) { handler(error, std::vector<ZoteroCollection>()); return; } // divide collections into ones we need to do a download for, and one that // we already have an up to date version for ZoteroCollections upToDateCollections; std::vector<std::pair<std::string, ZoteroCollectionSpec>> downloadCollections; // download items for specified collections json::Array collectionsJson = jsonValue.getArray(); for (auto json : collectionsJson) { json::Object collectionJson = json.getObject()["data"].getObject(); std::string collectionID = collectionJson["key"].getString(); std::string name = collectionJson[kName].getString(); int version = collectionJson[kVersion].getInt(); // see if this is a requested collection bool requested = collections.size() == 0 || // all collections requested std::count_if(collections.begin(), collections.end(), [name](const std::string& str) { return boost::algorithm::iequals(name, str); }) > 0 ; if (requested) { // see if we need to do a download for this collection ZoteroCollectionSpecs::const_iterator it = std::find_if( cacheSpecs.begin(), cacheSpecs.end(), [name](ZoteroCollectionSpec spec) { return boost::algorithm::iequals(spec.name,name); } ); if (it != cacheSpecs.end()) { ZoteroCollectionSpec collectionSpec(name, version); if (it->version < version) downloadCollections.push_back(std::make_pair(collectionID, collectionSpec)); else upToDateCollections.push_back(collectionSpec); } else { downloadCollections.push_back(std::make_pair(collectionID, ZoteroCollectionSpec(name, version))); } } } // do the download ZoteroCollectionsDownloader::create(key, userID, downloadCollections, [handler, upToDateCollections](Error error,ZoteroCollections collections) { if (error) { handler(error, ZoteroCollections()); } else { // append downloaded collections to already up to date collections and return them std::copy(upToDateCollections.begin(), upToDateCollections.end(), std::back_inserter(collections)); handler(Success(), collections); } }); }); } void getWebCollections(const std::string& key, const std::vector<std::string>& collections, const ZoteroCollectionSpecs& cacheSpecs, ZoteroCollectionsHandler handler) { // see if we already have the user id if (s_userIdMap.contains(key)) { getWebCollectionsForUser(key, s_userIdMap.getInt(key), collections, cacheSpecs, handler); } else { // get the user id for this key zoteroKeyInfo(key, [key, handler, collections, cacheSpecs](const Error& error,int,json::Value jsonValue) { if (error) { handler(error, std::vector<ZoteroCollection>()); return; } // get the and cache it int userID = jsonValue.getObject()["userID"].getInt(); s_userIdMap.set(key, userID); // get the collections getWebCollectionsForUser(key, userID, collections, cacheSpecs, handler); }); } } } // end anonymous namespace void validateWebApiKey(const std::string& key, boost::function<void(bool)> handler) { zoteroKeyInfo(key, [handler](const Error& error,int,json::Value) { if (error) { std::string err = core::errorDescription(error); if (!is404Error(err)) LOG_ERROR(error); handler(false); } else { handler(true); } }); } ZoteroCollectionSource webCollections() { // one time initialization of user id map static bool initialized = false; if (!initialized) { Error error = s_userIdMap.initialize(module_context::userScratchPath().completeChildPath("zotero-userid")); if (error) LOG_ERROR(error); } ZoteroCollectionSource source; source.getCollections = getWebCollections; return source; } } // end namespace collections } // end namespace zotero } // end namespace modules } // end namespace session } // end namespace rstudio
include api version in zotero requests
include api version in zotero requests
C++
agpl-3.0
JanMarvin/rstudio,JanMarvin/rstudio,JanMarvin/rstudio,JanMarvin/rstudio,JanMarvin/rstudio,JanMarvin/rstudio,JanMarvin/rstudio,JanMarvin/rstudio,JanMarvin/rstudio
b9bf6191ee1cf40c81e6cc2c80c9c49d426f174b
utils/utils.hpp
utils/utils.hpp
/* * A Remote Debugger for SpiderMonkey Java Script engine. * Copyright (C) 2014-2015 Sławomir Wojtasiak * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef SRC_UTILS_H_ #define SRC_UTILS_H_ #include <stdexcept> #include <stddef.h> #include <vector> namespace Utils { /** * Base class for all events. */ class Event { public: Event( int code ); virtual ~Event(); public: virtual void setReturnCode( int code ); virtual int getReturnCode(); virtual int getCode(); private: int _code; int _returnCode; }; /** * Generic event handler which can be used to handle almost * every kind of events in the system environment. */ class EventHandler { public: EventHandler(); virtual ~EventHandler(); public: virtual void handle( Event &event ) = 0; }; class Mutex; /** * Inherit from this class in order to add events firing * related functionality to your own class. * @warning This class is thread safe. */ class EventEmitter { public: EventEmitter(); virtual ~EventEmitter(); public: /** * Adds new events handler. */ void addEventHandler( EventHandler *handler ); /** * Removed given event handler. */ void removeEventHandler( EventHandler *handler ); protected: /** * Fires given event to all the registered event handlers. * @param event Event to be fired. */ void fire( Event &event ); /** * Fires standard CodeEvent to all registered clients. * @param Code to be fired. */ void fire( int code ); private: // Registered event handlers. Mutex *_mutex; std::vector<EventHandler*> _eventHandlers; }; /** * Just inherit from this class to make your class non copyable. */ class NonCopyable { protected: NonCopyable() { } private: /** * @throw OperationNotSupportedException */ NonCopyable( const NonCopyable &cpy ) { throw std::runtime_error("Operation not supported."); } /** * @throw OperationNotSupportedException */ NonCopyable& operator=( const NonCopyable &exc ) { throw std::runtime_error("Operation not supported."); } }; template<typename T> class AutoPtr { public: AutoPtr( T* ptr = NULL ) : _ptr(ptr) { } ~AutoPtr() { if( _ptr ) { delete _ptr; } } AutoPtr& operator=(AutoPtr<T> &other) { if( &other != this ) { _ptr = other._ptr; } return *this; } AutoPtr& operator=(T* other) { if( other != _ptr ) { _ptr = other; } return *this; } T& operator*() const { return *_ptr; } T* operator&() const { return _ptr; } T* operator->() const { return _ptr; } operator bool() { return _ptr != NULL; } operator T*() { return _ptr; } operator T&() { return *_ptr; } void reset() { _ptr = NULL; } T* get() { return _ptr; } T* release() { T *tmp = NULL; if( _ptr ) { tmp = _ptr; _ptr = NULL; } return tmp; } private: T *_ptr; }; } #endif /* SRC_UTILS_H_ */
/* * A Remote Debugger for SpiderMonkey Java Script engine. * Copyright (C) 2014-2015 Sławomir Wojtasiak * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef SRC_UTILS_H_ #define SRC_UTILS_H_ #include <stddef.h> #include <assert.h> #include <stdexcept> #include <vector> #include <functional> namespace Utils { /** * Helper class for exception-safe code. */ class OnScopeExit final { public: template <typename Function> OnScopeExit(Function dtor) try : _func(std::move(dtor)) { } catch (std::exception&) { dtor(); } ~OnScopeExit() { if (_func) { try { _func(); } catch (std::exception&) { assert(false); } } } void release() { _func = nullptr; } private: std::function<void(void)> _func; OnScopeExit(); // n/a OnScopeExit(const OnScopeExit&); // n/a OnScopeExit& operator=(const OnScopeExit&); // n/a }; /** * Base class for all events. */ class Event { public: Event( int code ); virtual ~Event(); public: virtual void setReturnCode( int code ); virtual int getReturnCode(); virtual int getCode(); private: int _code; int _returnCode; }; /** * Generic event handler which can be used to handle almost * every kind of events in the system environment. */ class EventHandler { public: EventHandler(); virtual ~EventHandler(); public: virtual void handle( Event &event ) = 0; }; class Mutex; /** * Inherit from this class in order to add events firing * related functionality to your own class. * @warning This class is thread safe. */ class EventEmitter { public: EventEmitter(); virtual ~EventEmitter(); public: /** * Adds new events handler. */ void addEventHandler( EventHandler *handler ); /** * Removed given event handler. */ void removeEventHandler( EventHandler *handler ); protected: /** * Fires given event to all the registered event handlers. * @param event Event to be fired. */ void fire( Event &event ); /** * Fires standard CodeEvent to all registered clients. * @param Code to be fired. */ void fire( int code ); private: // Registered event handlers. Mutex *_mutex; std::vector<EventHandler*> _eventHandlers; }; /** * Just inherit from this class to make your class non copyable. */ class NonCopyable { protected: NonCopyable() { } private: /** * @throw OperationNotSupportedException */ NonCopyable( const NonCopyable &cpy ) { throw std::runtime_error("Operation not supported."); } /** * @throw OperationNotSupportedException */ NonCopyable& operator=( const NonCopyable &exc ) { throw std::runtime_error("Operation not supported."); } }; template<typename T> class AutoPtr { public: AutoPtr( T* ptr = NULL ) : _ptr(ptr) { } ~AutoPtr() { if( _ptr ) { delete _ptr; } } AutoPtr& operator=(AutoPtr<T> &other) { if( &other != this ) { _ptr = other._ptr; } return *this; } AutoPtr& operator=(T* other) { if( other != _ptr ) { _ptr = other; } return *this; } T& operator*() const { return *_ptr; } T* operator&() const { return _ptr; } T* operator->() const { return _ptr; } operator bool() { return _ptr != NULL; } operator T*() { return _ptr; } operator T&() { return *_ptr; } void reset() { _ptr = NULL; } T* get() { return _ptr; } T* release() { T *tmp = NULL; if( _ptr ) { tmp = _ptr; _ptr = NULL; } return tmp; } private: T *_ptr; }; } #endif /* SRC_UTILS_H_ */
add OnScopeExit helper class
utils: add OnScopeExit helper class
C++
lgpl-2.1
swojtasiak/jsrdbg,bkircher/jsrdbg,bkircher/jsrdbg,otris/jsrdbg,otris/jsrdbg,swojtasiak/jsrdbg,bkircher/jsrdbg,swojtasiak/jsrdbg,otris/jsrdbg,swojtasiak/jsrdbg,bkircher/jsrdbg
c2deb40189cbc762030fd1c11b84b6746bcb8621
finans/core_test/testcmdline.cc
finans/core_test/testcmdline.cc
// Copyright (2015) Gustav #include "finans/core/commandline.h" #include "gtest/gtest.h" #include "gmock/gmock.h" using namespace testing; class TestSubParser : public argparse::SubParser { public: TestSubParser() { } void AddParser(argparse::Parser& parser) override { parser.AddOption("-name", name); } void ParseCompleted() override { } std::string name; }; struct CommandlineTest : public Test { std::ostringstream output; std::ostringstream error; argparse::Parser parser; std::string animal; std::string another; TestSubParser sp1; TestSubParser sp2; argparse::Parser sub; CommandlineTest() : parser("description"), sub("description") { parser.AddOption("pos", animal); parser.AddOption("-op", another); sub.AddSubParser("one", &sp1); sub.AddSubParser("two", &sp2); } }; #define GTEST(x) TEST_F(CommandlineTest, x) GTEST(TestEmpty) { argparse::Parser parser("description"); const bool ok = argparse::Parser::ParseComplete == parser.ParseArgs(argparse::Arguments("app.exe", {}), output, error); EXPECT_EQ(true, ok); EXPECT_EQ("", error.str()); EXPECT_EQ("", output.str()); } GTEST(TestError) { argparse::Parser parser("description"); const bool ok = argparse::Parser::ParseComplete == parser.ParseArgs(argparse::Arguments("app.exe", { "hello", "world" }), output, error); EXPECT_EQ(false, ok); EXPECT_EQ("Usage: [-h]\n", output.str()); EXPECT_EQ("error: All positional arguments have been consumed: hello\n", error.str()); } GTEST(TestOptionalDefault) { int op = 2; argparse::Parser parser("description"); parser.AddOption("-op", op); const bool ok = argparse::Parser::ParseComplete == parser.ParseArgs(argparse::Arguments("app.exe", {}), output, error); EXPECT_EQ(true, ok); EXPECT_EQ("", error.str()); EXPECT_EQ("", output.str()); EXPECT_EQ(2, op); } GTEST(TestOptionalValue) { int op = 2; argparse::Parser parser("description"); parser.AddOption("-op", op); const bool ok = argparse::Parser::ParseComplete == parser.ParseArgs(argparse::Arguments("app.exe", { "-op", "42" }), output, error); EXPECT_EQ(true, ok); EXPECT_EQ("", error.str()); EXPECT_EQ("", output.str()); EXPECT_EQ(42, op); } GTEST(TestPositionalValue) { int op = 2; argparse::Parser parser("description"); parser.AddOption("op", op); const bool ok = argparse::Parser::ParseComplete == parser.ParseArgs(argparse::Arguments("app.exe", { "42" }), output, error); EXPECT_EQ(true, ok); EXPECT_EQ("", error.str()); EXPECT_EQ("", output.str()); EXPECT_EQ(42, op); } GTEST(TestPositionalValueErr) { int op = 42; argparse::Parser parser("description"); parser.AddOption("op", op); const bool ok = argparse::Parser::ParseComplete == parser.ParseArgs(argparse::Arguments("app.exe", {}), output, error); EXPECT_EQ(false, ok); EXPECT_EQ("error: too few arguments.\n", error.str()); EXPECT_EQ("Usage: [-h] op\n", output.str()); EXPECT_EQ(42, op); // not touched } GTEST(TestStdVector) { std::vector<std::string> strings; argparse::Parser parser("description"); parser.AddGreedy("-strings", strings, "string"); const bool ok = argparse::Parser::ParseComplete == parser.ParseArgs(argparse::Arguments("app.exe", { "-strings", "cat", "dog", "fish" }), output, error); EXPECT_EQ(true, ok); EXPECT_EQ("", error.str()); EXPECT_EQ("", output.str()); EXPECT_THAT(strings, ElementsAre("cat", "dog", "fish")); } GTEST(TestStdVectorInts) { std::vector<int> ints; argparse::Parser parser("description"); parser.AddGreedy("-ints", ints, "string"); const bool ok = argparse::Parser::ParseComplete == parser.ParseArgs(argparse::Arguments("app.exe", { "-ints", "2", "3", "-5", "4" }), output, error); EXPECT_EQ(true, ok); EXPECT_EQ("", error.str()); EXPECT_EQ("", output.str()); EXPECT_THAT(ints, ElementsAre(2, 3, -5, 4)); } GTEST(TestNonGreedyVector) { std::vector<std::string> strings; argparse::Parser parser("description"); parser.AddOption("-s", strings); const bool ok = argparse::Parser::ParseComplete == parser.ParseArgs(argparse::Arguments("app.exe", { "-s", "cat", "-s", "dog", "-s", "fish" }), output, error); EXPECT_EQ(true, ok); EXPECT_EQ("", error.str()); EXPECT_EQ("", output.str()); EXPECT_THAT(strings, ElementsAre("cat", "dog", "fish")); } enum class Day { TODAY, YESTERDAY, TOMORROW }; ARGPARSE_DEFINE_ENUM(Day, "day", ("Today", Day::TODAY)("Tomorrow", Day::TOMORROW)("Yesterday", Day::YESTERDAY)) GTEST(TestEnum) { Day op = Day::TOMORROW; argparse::Parser parser("description"); parser.AddOption("op", op); const bool ok = argparse::Parser::ParseComplete == parser.ParseArgs(argparse::Arguments("app.exe", { "tod" }), output, error); EXPECT_EQ(true, ok); EXPECT_EQ("", error.str()); EXPECT_EQ("", output.str()); EXPECT_EQ(Day::TODAY, op); } GTEST(TestCommaOp) { int op = 2; argparse::Parser parser("description"); parser.AddOption("-int,-i", op); const bool ok = argparse::Parser::ParseComplete == parser.ParseArgs(argparse::Arguments("app.exe", { "-int", "42" }), output, error); EXPECT_EQ(true, ok); EXPECT_EQ("", error.str()); EXPECT_EQ("", output.str()); EXPECT_EQ(42, op); } GTEST(TestSpecifyTwice) { int op = 2; argparse::Parser parser("description"); parser.AddOption("-int,-i", op); const bool ok = argparse::Parser::ParseComplete == parser.ParseArgs(argparse::Arguments("app.exe", { "-int", "42", "-i", "50" }), output, error); EXPECT_EQ(false, ok); EXPECT_EQ("error: All positional arguments have been consumed: -i\n", error.str()); EXPECT_EQ("Usage: [-h] [-int,-i int]\n", output.str()); EXPECT_EQ(42, op); } GTEST(TestPrecedencePos) { const bool ok = argparse::Parser::ParseComplete == parser.ParseArgs(argparse::Arguments("app.exe", { "dog" }), output, error); EXPECT_EQ(true, ok); EXPECT_EQ("", error.str()); EXPECT_EQ("", output.str()); EXPECT_EQ("dog", animal); EXPECT_EQ("", another); } GTEST(TestPrecedencePosOp) { const bool ok = argparse::Parser::ParseComplete == parser.ParseArgs(argparse::Arguments("app.exe", { "-dog", "-op", "cat" }), output, error); EXPECT_EQ(true, ok); EXPECT_EQ("", output.str()); EXPECT_EQ("", error.str()); EXPECT_EQ("-dog", animal); EXPECT_EQ("cat", another); } GTEST(TestPrecedenceOpPos) { const bool ok = argparse::Parser::ParseComplete == parser.ParseArgs(argparse::Arguments("app.exe", { "-op", "cat", "dog" }), output, error); EXPECT_EQ(true, ok); EXPECT_EQ("", error.str()); EXPECT_EQ("", output.str()); EXPECT_EQ("dog", animal); EXPECT_EQ("cat", another); } GTEST(TestStoreConstInt) { int op = 12; argparse::Parser parser("description"); parser.StoreConst("-store", op, 42); const bool ok = argparse::Parser::ParseComplete == parser.ParseArgs(argparse::Arguments("app.exe", { "-store" }), output, error); EXPECT_EQ(true, ok); EXPECT_EQ("", output.str()); EXPECT_EQ("", error.str()); EXPECT_EQ(42, op); } GTEST(TestStoreConstString) { std::string op = ""; argparse::Parser parser("description"); parser.StoreConst<std::string>("-store", op, "dog"); const bool ok = argparse::Parser::ParseComplete == parser.ParseArgs(argparse::Arguments("app.exe", { "-store" }), output, error); EXPECT_EQ(true, ok); EXPECT_EQ("", output.str()); EXPECT_EQ("", error.str()); EXPECT_EQ("dog", op); } GTEST(TestSubParserBasic) { const bool ok = argparse::Parser::ParseComplete == sub.ParseArgs(argparse::Arguments("app.exe", { "one", "-name", "dog" }), output, error); EXPECT_EQ(true, ok); EXPECT_EQ("", output.str()); EXPECT_EQ("", error.str()); EXPECT_EQ("dog", sp1.name); EXPECT_EQ("", sp2.name); } GTEST(TestSubParserOptional) { std::string op = ""; sub.AddOption("-op", op); const bool ok = argparse::Parser::ParseComplete == sub.ParseArgs(argparse::Arguments("app.exe", { "-op", "cat", "on", "-name", "dog" }), output, error); EXPECT_EQ(true, ok); EXPECT_EQ("", output.str()); EXPECT_EQ("", error.str()); EXPECT_EQ("cat", op); EXPECT_EQ("dog", sp1.name); EXPECT_EQ("", sp2.name); } GTEST(TestSubParserPositional) { std::string op = ""; sub.AddOption("op", op); const bool ok = argparse::Parser::ParseComplete == sub.ParseArgs(argparse::Arguments("app.exe", { "cat", "on", "-name", "dog" }), output, error); EXPECT_EQ(true, ok); EXPECT_EQ("", output.str()); EXPECT_EQ("", error.str()); EXPECT_EQ("cat", op); EXPECT_EQ("dog", sp1.name); EXPECT_EQ("", sp2.name); } GTEST(TestCallingSubParserWithBadArguments) { const bool ok = argparse::Parser::ParseComplete == sub.ParseArgs(argparse::Arguments("app.exe", { "on", "cat" }), output, error); EXPECT_EQ(false, ok); EXPECT_EQ("Usage: [-h] ONE [-h] [-name name]\n", output.str()); EXPECT_EQ("error: Failed to parse ONE:\nerror: All positional arguments have been consumed: cat\n", error.str()); EXPECT_EQ("", sp1.name); EXPECT_EQ("", sp2.name); } GTEST(TestCallingInvalidSubParser) { const bool ok = argparse::Parser::ParseComplete == sub.ParseArgs(argparse::Arguments("app.exe", { "dog", "cat" }), output, error); EXPECT_EQ(false, ok); EXPECT_EQ("Usage: [-h] {ONE|TWO}\n", output.str()); EXPECT_EQ("error: Unable to match DOG as a subparser.\n", error.str()); EXPECT_EQ("", sp1.name); EXPECT_EQ("", sp2.name); } // todo: test help string when calling -h GTEST(TestCallingHelpBasic) { argparse::Parser parser("Description of app."); const bool ok = argparse::Parser::ParseQuit == parser.ParseArgs(argparse::Arguments("app.exe", { "-h" }), output, error); EXPECT_EQ(true, ok); EXPECT_EQ("Usage: app.exe [-h]\n" "Description of app.\n" "\n" "Optional arguments:\n" " -h\tShow this help message and exit.\n" "\n", output.str()); EXPECT_EQ("", error.str()); } GTEST(TestCallingHelpBasicCustomName) { argparse::Parser parser("Description of app.", "awesome.exe"); const bool ok = argparse::Parser::ParseQuit == parser.ParseArgs(argparse::Arguments("app.exe", { "-h" }), output, error); EXPECT_EQ(true, ok); EXPECT_EQ("Usage: awesome.exe [-h]\n" "Description of app.\n" "\n" "Optional arguments:\n" " -h\tShow this help message and exit.\n" "\n", output.str()); EXPECT_EQ("", error.str()); } GTEST(TestCallingHelpOpOptional) { argparse::Parser parser("Description of app."); std::string op = ""; std::string ap = ""; parser.AddOption("-op", op); parser.AddOption("-ap", ap); const bool ok = argparse::Parser::ParseQuit == parser.ParseArgs(argparse::Arguments("app.exe", { "-h" }), output, error); EXPECT_EQ(true, ok); EXPECT_EQ("Usage: app.exe [-h] [-op op] [-ap ap]\n" "Description of app.\n" "\n" "Optional arguments:\n" " -ap ap\n" " -h\tShow this help message and exit.\n" " -op op\n" "\n", output.str()); EXPECT_EQ("", error.str()); } GTEST(TestCallingHelpOpPositional) { argparse::Parser parser("Description of app."); std::string op = ""; std::string ap = ""; parser.AddOption("op", op); parser.AddOption("ap", ap); const bool ok = argparse::Parser::ParseQuit == parser.ParseArgs(argparse::Arguments("app.exe", { "-h" }), output, error); EXPECT_EQ(true, ok); EXPECT_EQ("Usage: app.exe [-h] op ap\n" "Description of app.\n" "\n" "Positional arguments:\n" " op\n" " ap\n" "\n" "Optional arguments:\n" " -h\tShow this help message and exit.\n" "\n", output.str()); EXPECT_EQ("", error.str()); } // test commandline examples // test commandline detailed help
// Copyright (2015) Gustav #include "finans/core/commandline.h" #include "gtest/gtest.h" #include "gmock/gmock.h" using namespace testing; class TestSubParser : public argparse::SubParser { public: TestSubParser() { } void AddParser(argparse::Parser& parser) override { parser.AddOption("-name", name); } void ParseCompleted() override { } std::string name; }; struct CommandlineTest : public Test { std::ostringstream output; std::ostringstream error; argparse::Parser parser; std::string animal; std::string another; TestSubParser sp1; TestSubParser sp2; argparse::Parser sub; CommandlineTest() : parser("description"), sub("description") { parser.AddOption("pos", animal); parser.AddOption("-op", another); sub.AddSubParser("one", &sp1); sub.AddSubParser("two", &sp2); } }; #define GTEST(x) TEST_F(CommandlineTest, x) GTEST(TestEmpty) { argparse::Parser parser("description"); const bool ok = argparse::Parser::ParseComplete == parser.ParseArgs(argparse::Arguments("app.exe", {}), output, error); EXPECT_EQ(true, ok); EXPECT_EQ("", error.str()); EXPECT_EQ("", output.str()); } GTEST(TestError) { argparse::Parser parser("description"); const bool ok = argparse::Parser::ParseComplete == parser.ParseArgs(argparse::Arguments("app.exe", { "hello", "world" }), output, error); EXPECT_EQ(false, ok); EXPECT_EQ("Usage: [-h]\n", output.str()); EXPECT_EQ("error: All positional arguments have been consumed: hello\n", error.str()); } GTEST(TestOptionalDefault) { int op = 2; argparse::Parser parser("description"); parser.AddOption("-op", op); const bool ok = argparse::Parser::ParseComplete == parser.ParseArgs(argparse::Arguments("app.exe", {}), output, error); EXPECT_EQ(true, ok); EXPECT_EQ("", error.str()); EXPECT_EQ("", output.str()); EXPECT_EQ(2, op); } GTEST(TestOptionalValue) { int op = 2; argparse::Parser parser("description"); parser.AddOption("-op", op); const bool ok = argparse::Parser::ParseComplete == parser.ParseArgs(argparse::Arguments("app.exe", { "-op", "42" }), output, error); EXPECT_EQ(true, ok); EXPECT_EQ("", error.str()); EXPECT_EQ("", output.str()); EXPECT_EQ(42, op); } GTEST(TestPositionalValue) { int op = 2; argparse::Parser parser("description"); parser.AddOption("op", op); const bool ok = argparse::Parser::ParseComplete == parser.ParseArgs(argparse::Arguments("app.exe", { "42" }), output, error); EXPECT_EQ(true, ok); EXPECT_EQ("", error.str()); EXPECT_EQ("", output.str()); EXPECT_EQ(42, op); } GTEST(TestPositionalValueErr) { int op = 42; argparse::Parser parser("description"); parser.AddOption("op", op); const bool ok = argparse::Parser::ParseComplete == parser.ParseArgs(argparse::Arguments("app.exe", {}), output, error); EXPECT_EQ(false, ok); EXPECT_EQ("error: too few arguments.\n", error.str()); EXPECT_EQ("Usage: [-h] op\n", output.str()); EXPECT_EQ(42, op); // not touched } GTEST(TestStdVector) { std::vector<std::string> strings; argparse::Parser parser("description"); parser.AddGreedy("-strings", strings, "string"); const bool ok = argparse::Parser::ParseComplete == parser.ParseArgs(argparse::Arguments("app.exe", { "-strings", "cat", "dog", "fish" }), output, error); EXPECT_EQ(true, ok); EXPECT_EQ("", error.str()); EXPECT_EQ("", output.str()); EXPECT_THAT(strings, ElementsAre("cat", "dog", "fish")); } GTEST(TestStdVectorInts) { std::vector<int> ints; argparse::Parser parser("description"); parser.AddGreedy("-ints", ints, "string"); const bool ok = argparse::Parser::ParseComplete == parser.ParseArgs(argparse::Arguments("app.exe", { "-ints", "2", "3", "-5", "4" }), output, error); EXPECT_EQ(true, ok); EXPECT_EQ("", error.str()); EXPECT_EQ("", output.str()); EXPECT_THAT(ints, ElementsAre(2, 3, -5, 4)); } GTEST(TestNonGreedyVector) { std::vector<std::string> strings; argparse::Parser parser("description"); parser.AddOption("-s", strings); const bool ok = argparse::Parser::ParseComplete == parser.ParseArgs(argparse::Arguments("app.exe", { "-s", "cat", "-s", "dog", "-s", "fish" }), output, error); EXPECT_EQ(true, ok); EXPECT_EQ("", error.str()); EXPECT_EQ("", output.str()); EXPECT_THAT(strings, ElementsAre("cat", "dog", "fish")); } enum class Day { TODAY, YESTERDAY, TOMORROW }; ARGPARSE_DEFINE_ENUM(Day, "day", ("Today", Day::TODAY)("Tomorrow", Day::TOMORROW)("Yesterday", Day::YESTERDAY)) GTEST(TestEnum) { Day op = Day::TOMORROW; argparse::Parser parser("description"); parser.AddOption("op", op); const bool ok = argparse::Parser::ParseComplete == parser.ParseArgs(argparse::Arguments("app.exe", { "tod" }), output, error); EXPECT_EQ(true, ok); EXPECT_EQ("", error.str()); EXPECT_EQ("", output.str()); EXPECT_EQ(Day::TODAY, op); } GTEST(TestCommaOp) { int op = 2; argparse::Parser parser("description"); parser.AddOption("-int,-i", op); const bool ok = argparse::Parser::ParseComplete == parser.ParseArgs(argparse::Arguments("app.exe", { "-int", "42" }), output, error); EXPECT_EQ(true, ok); EXPECT_EQ("", error.str()); EXPECT_EQ("", output.str()); EXPECT_EQ(42, op); } GTEST(TestSpecifyTwice) { int op = 2; argparse::Parser parser("description"); parser.AddOption("-int,-i", op); const bool ok = argparse::Parser::ParseComplete == parser.ParseArgs(argparse::Arguments("app.exe", { "-int", "42", "-i", "50" }), output, error); EXPECT_EQ(false, ok); EXPECT_EQ("error: All positional arguments have been consumed: -i\n", error.str()); EXPECT_EQ("Usage: [-h] [-int,-i int]\n", output.str()); EXPECT_EQ(42, op); } GTEST(TestPrecedencePos) { const bool ok = argparse::Parser::ParseComplete == parser.ParseArgs(argparse::Arguments("app.exe", { "dog" }), output, error); EXPECT_EQ(true, ok); EXPECT_EQ("", error.str()); EXPECT_EQ("", output.str()); EXPECT_EQ("dog", animal); EXPECT_EQ("", another); } GTEST(TestPrecedencePosOp) { const bool ok = argparse::Parser::ParseComplete == parser.ParseArgs(argparse::Arguments("app.exe", { "-dog", "-op", "cat" }), output, error); EXPECT_EQ(true, ok); EXPECT_EQ("", output.str()); EXPECT_EQ("", error.str()); EXPECT_EQ("-dog", animal); EXPECT_EQ("cat", another); } GTEST(TestPrecedenceOpPos) { const bool ok = argparse::Parser::ParseComplete == parser.ParseArgs(argparse::Arguments("app.exe", { "-op", "cat", "dog" }), output, error); EXPECT_EQ(true, ok); EXPECT_EQ("", error.str()); EXPECT_EQ("", output.str()); EXPECT_EQ("dog", animal); EXPECT_EQ("cat", another); } GTEST(TestStoreConstInt) { int op = 12; argparse::Parser parser("description"); parser.StoreConst("-store", op, 42); const bool ok = argparse::Parser::ParseComplete == parser.ParseArgs(argparse::Arguments("app.exe", { "-store" }), output, error); EXPECT_EQ(true, ok); EXPECT_EQ("", output.str()); EXPECT_EQ("", error.str()); EXPECT_EQ(42, op); } GTEST(TestStoreConstString) { std::string op = ""; argparse::Parser parser("description"); parser.StoreConst<std::string>("-store", op, "dog"); const bool ok = argparse::Parser::ParseComplete == parser.ParseArgs(argparse::Arguments("app.exe", { "-store" }), output, error); EXPECT_EQ(true, ok); EXPECT_EQ("", output.str()); EXPECT_EQ("", error.str()); EXPECT_EQ("dog", op); } GTEST(TestSubParserBasic) { const bool ok = argparse::Parser::ParseComplete == sub.ParseArgs(argparse::Arguments("app.exe", { "one", "-name", "dog" }), output, error); EXPECT_EQ(true, ok); EXPECT_EQ("", output.str()); EXPECT_EQ("", error.str()); EXPECT_EQ("dog", sp1.name); EXPECT_EQ("", sp2.name); } GTEST(TestSubParserOptional) { std::string op = ""; sub.AddOption("-op", op); const bool ok = argparse::Parser::ParseComplete == sub.ParseArgs(argparse::Arguments("app.exe", { "-op", "cat", "on", "-name", "dog" }), output, error); EXPECT_EQ(true, ok); EXPECT_EQ("", output.str()); EXPECT_EQ("", error.str()); EXPECT_EQ("cat", op); EXPECT_EQ("dog", sp1.name); EXPECT_EQ("", sp2.name); } GTEST(TestSubParserPositional) { std::string op = ""; sub.AddOption("op", op); const bool ok = argparse::Parser::ParseComplete == sub.ParseArgs(argparse::Arguments("app.exe", { "cat", "on", "-name", "dog" }), output, error); EXPECT_EQ(true, ok); EXPECT_EQ("", output.str()); EXPECT_EQ("", error.str()); EXPECT_EQ("cat", op); EXPECT_EQ("dog", sp1.name); EXPECT_EQ("", sp2.name); } GTEST(TestCallingSubParserWithBadArguments) { const bool ok = argparse::Parser::ParseComplete == sub.ParseArgs(argparse::Arguments("app.exe", { "on", "cat" }), output, error); EXPECT_EQ(false, ok); EXPECT_EQ("Usage: [-h] ONE [-h] [-name name]\n", output.str()); EXPECT_EQ("error: Failed to parse ONE:\nerror: All positional arguments have been consumed: cat\n", error.str()); EXPECT_EQ("", sp1.name); EXPECT_EQ("", sp2.name); } GTEST(TestCallingInvalidSubParser) { const bool ok = argparse::Parser::ParseComplete == sub.ParseArgs(argparse::Arguments("app.exe", { "dog", "cat" }), output, error); EXPECT_EQ(false, ok); EXPECT_EQ("Usage: [-h] {ONE|TWO}\n", output.str()); EXPECT_EQ("error: Unable to match DOG as a subparser.\n", error.str()); EXPECT_EQ("", sp1.name); EXPECT_EQ("", sp2.name); } class VerifySubParserIsCalledParser : public argparse::SubParser { public: int dummy_arg; int pc_callcount; VerifySubParserIsCalledParser() : pc_callcount(0) { } virtual void AddParser(argparse::Parser& parser) override { parser.AddOption("-dummy", dummy_arg); } // called when parsing is done virtual void ParseCompleted() override { ++pc_callcount; } }; GTEST(VerifySubParserIsCalledWithoutArg) { argparse::Parser parser("Description of app."); VerifySubParserIsCalledParser dog; parser.AddSubParser("dog", &dog); const bool ok = argparse::Parser::ParseComplete == parser.ParseArgs(argparse::Arguments("app.exe", { "dog" }), output, error); EXPECT_EQ(true, ok); EXPECT_EQ("", output.str()); EXPECT_EQ("", error.str()); EXPECT_EQ(1, dog.pc_callcount); } GTEST(VerifySubParserIsCalledWithArg) { argparse::Parser parser("Description of app."); VerifySubParserIsCalledParser dog; parser.AddSubParser("dog", &dog); const bool ok = argparse::Parser::ParseComplete == parser.ParseArgs(argparse::Arguments("app.exe", { "dog", "-dummy", "3"}), output, error); EXPECT_EQ(true, ok); EXPECT_EQ("", output.str()); EXPECT_EQ("", error.str()); EXPECT_EQ(1, dog.pc_callcount); } // todo: test help string when calling -h GTEST(TestCallingHelpBasic) { argparse::Parser parser("Description of app."); const bool ok = argparse::Parser::ParseQuit == parser.ParseArgs(argparse::Arguments("app.exe", { "-h" }), output, error); EXPECT_EQ(true, ok); EXPECT_EQ("Usage: app.exe [-h]\n" "Description of app.\n" "\n" "Optional arguments:\n" " -h\tShow this help message and exit.\n" "\n", output.str()); EXPECT_EQ("", error.str()); } GTEST(TestCallingHelpBasicCustomName) { argparse::Parser parser("Description of app.", "awesome.exe"); const bool ok = argparse::Parser::ParseQuit == parser.ParseArgs(argparse::Arguments("app.exe", { "-h" }), output, error); EXPECT_EQ(true, ok); EXPECT_EQ("Usage: awesome.exe [-h]\n" "Description of app.\n" "\n" "Optional arguments:\n" " -h\tShow this help message and exit.\n" "\n", output.str()); EXPECT_EQ("", error.str()); } GTEST(TestCallingHelpOpOptional) { argparse::Parser parser("Description of app."); std::string op = ""; std::string ap = ""; parser.AddOption("-op", op); parser.AddOption("-ap", ap); const bool ok = argparse::Parser::ParseQuit == parser.ParseArgs(argparse::Arguments("app.exe", { "-h" }), output, error); EXPECT_EQ(true, ok); EXPECT_EQ("Usage: app.exe [-h] [-op op] [-ap ap]\n" "Description of app.\n" "\n" "Optional arguments:\n" " -ap ap\n" " -h\tShow this help message and exit.\n" " -op op\n" "\n", output.str()); EXPECT_EQ("", error.str()); } GTEST(TestCallingHelpOpPositional) { argparse::Parser parser("Description of app."); std::string op = ""; std::string ap = ""; parser.AddOption("op", op); parser.AddOption("ap", ap); const bool ok = argparse::Parser::ParseQuit == parser.ParseArgs(argparse::Arguments("app.exe", { "-h" }), output, error); EXPECT_EQ(true, ok); EXPECT_EQ("Usage: app.exe [-h] op ap\n" "Description of app.\n" "\n" "Positional arguments:\n" " op\n" " ap\n" "\n" "Optional arguments:\n" " -h\tShow this help message and exit.\n" "\n", output.str()); EXPECT_EQ("", error.str()); } // test commandline examples // test commandline detailed help
verify that the subparser function is called
verify that the subparser function is called
C++
mit
madeso/finans,madeso/finans
3619ec97dd338fea1979f18cc3407ca4dc4aefab
folly/test/ForeachBenchmark.cpp
folly/test/ForeachBenchmark.cpp
/* * Copyright 2016 Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <folly/Foreach.h> #include <folly/Benchmark.h> #include <gtest/gtest.h> #include <map> using namespace folly; using namespace folly::detail; // Benchmarks: // 1. Benchmark iterating through the man with FOR_EACH, and also assign // iter->first and iter->second to local vars inside the FOR_EACH loop. // 2. Benchmark iterating through the man with FOR_EACH, but use iter->first and // iter->second as is, without assigning to local variables. // 3. Use FOR_EACH_KV loop to iterate through the map. std::map<int, std::string> bmMap; // For use in benchmarks below. void setupBenchmark(size_t iters) { bmMap.clear(); for (size_t i = 0; i < iters; ++i) { bmMap[i] = "teststring"; } } BENCHMARK(ForEachKVNoMacroAssign, iters) { int sumKeys = 0; std::string sumValues; BENCHMARK_SUSPEND { setupBenchmark(iters); } FOR_EACH(iter, bmMap) { const int k = iter->first; const std::string v = iter->second; sumKeys += k; sumValues += v; } } BENCHMARK(ForEachKVNoMacroNoAssign, iters) { int sumKeys = 0; std::string sumValues; BENCHMARK_SUSPEND { setupBenchmark(iters); } FOR_EACH(iter, bmMap) { sumKeys += iter->first; sumValues += iter->second; } } BENCHMARK(ManualLoopNoAssign, iters) { int sumKeys = 0; std::string sumValues; BENCHMARK_SUSPEND { setupBenchmark(iters); } for (auto iter = bmMap.begin(); iter != bmMap.end(); ++iter) { sumKeys += iter->first; sumValues += iter->second; } } BENCHMARK(ForEachKVMacro, iters) { int sumKeys = 0; std::string sumValues; BENCHMARK_SUSPEND { setupBenchmark(iters); } FOR_EACH_KV(k, v, bmMap) { sumKeys += k; sumValues += v; } } BENCHMARK(ForEachManual, iters) { int sum = 1; for (size_t i = 1; i < iters; ++i) { sum *= i; } doNotOptimizeAway(sum); } BENCHMARK(ForEachRange, iters) { int sum = 1; FOR_EACH_RANGE(i, 1, iters) { sum *= i; } doNotOptimizeAway(sum); } BENCHMARK(ForEachDescendingManual, iters) { int sum = 1; for (size_t i = iters; i-- > 1;) { sum *= i; } doNotOptimizeAway(sum); } BENCHMARK(ForEachRangeR, iters) { int sum = 1; FOR_EACH_RANGE_R(i, 1U, iters) { sum *= i; } doNotOptimizeAway(sum); } int main(int argc, char** argv) { testing::InitGoogleTest(&argc, argv); auto r = RUN_ALL_TESTS(); if (r) { return r; } runBenchmarks(); return 0; }
/* * Copyright 2016 Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <folly/Foreach.h> #include <folly/Benchmark.h> #include <gtest/gtest.h> #include <map> using namespace folly; using namespace folly::detail; // Benchmarks: // 1. Benchmark iterating through the man with FOR_EACH, and also assign // iter->first and iter->second to local vars inside the FOR_EACH loop. // 2. Benchmark iterating through the man with FOR_EACH, but use iter->first and // iter->second as is, without assigning to local variables. // 3. Use FOR_EACH_KV loop to iterate through the map. std::map<int, std::string> bmMap; // For use in benchmarks below. void setupBenchmark(size_t iters) { bmMap.clear(); for (size_t i = 0; i < iters; ++i) { bmMap[i] = "teststring"; } } BENCHMARK(ForEachKVNoMacroAssign, iters) { int sumKeys = 0; std::string sumValues; BENCHMARK_SUSPEND { setupBenchmark(iters); } FOR_EACH(iter, bmMap) { const int k = iter->first; const std::string v = iter->second; sumKeys += k; sumValues += v; } } BENCHMARK(ForEachKVNoMacroNoAssign, iters) { int sumKeys = 0; std::string sumValues; BENCHMARK_SUSPEND { setupBenchmark(iters); } FOR_EACH(iter, bmMap) { sumKeys += iter->first; sumValues += iter->second; } } BENCHMARK(ManualLoopNoAssign, iters) { int sumKeys = 0; std::string sumValues; BENCHMARK_SUSPEND { setupBenchmark(iters); } for (auto iter = bmMap.begin(); iter != bmMap.end(); ++iter) { sumKeys += iter->first; sumValues += iter->second; } } BENCHMARK(ForEachKVMacro, iters) { int sumKeys = 0; std::string sumValues; BENCHMARK_SUSPEND { setupBenchmark(iters); } FOR_EACH_KV(k, v, bmMap) { sumKeys += k; sumValues += v; } } BENCHMARK(ForEachManual, iters) { int sum = 1; for (size_t i = 1; i < iters; ++i) { sum *= i; } doNotOptimizeAway(sum); } BENCHMARK(ForEachRange, iters) { int sum = 1; FOR_EACH_RANGE(i, 1, iters) { sum *= i; } doNotOptimizeAway(sum); } BENCHMARK(ForEachDescendingManual, iters) { int sum = 1; for (size_t i = iters; i-- > 1;) { sum *= i; } doNotOptimizeAway(sum); } BENCHMARK(ForEachRangeR, iters) { int sum = 1; FOR_EACH_RANGE_R(i, 1U, iters) { sum *= i; } doNotOptimizeAway(sum); } int main(int argc, char** argv) { testing::InitGoogleTest(&argc, argv); gflags::ParseCommandLineFlags(&argc, &argv, true); auto r = RUN_ALL_TESTS(); if (r) { return r; } runBenchmarks(); return 0; }
fix command line parsing
fix command line parsing Summary: parse command line flags to pick up -json flag Reviewed By: mzlee Differential Revision: D3405794 fbshipit-source-id: e2d216c74f04c15d7470c70abfc2bd25c2ceda98
C++
apache-2.0
brunomorishita/folly,facebook/folly,rklabs/folly,floxard/folly,brunomorishita/folly,floxard/folly,mqeizi/folly,rklabs/folly,floxard/folly,facebook/folly,rklabs/folly,mqeizi/folly,rklabs/folly,facebook/folly,charsyam/folly,mqeizi/folly,Orvid/folly,Orvid/folly,brunomorishita/folly,floxard/folly,Orvid/folly,brunomorishita/folly,charsyam/folly,rklabs/folly,Orvid/folly,charsyam/folly,Orvid/folly,floxard/folly,mqeizi/folly,mqeizi/folly,facebook/folly,facebook/folly,charsyam/folly,brunomorishita/folly
76280e87789c96f1c3ba8e283410fefbec3209f7
hardware/arduino/sam/cores/arduino/UARTClass.cpp
hardware/arduino/sam/cores/arduino/UARTClass.cpp
/* Copyright (c) 2011 Arduino. All right reserved. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include <stdlib.h> #include <stdio.h> #include <string.h> #include "UARTClass.h" // Constructors //////////////////////////////////////////////////////////////// UARTClass::UARTClass( Uart *pUart, IRQn_Type dwIrq, uint32_t dwId, RingBuffer *pRx_buffer, RingBuffer *pTx_buffer ) { _rx_buffer = pRx_buffer ; _tx_buffer = pTx_buffer; _pUart=pUart ; _dwIrq=dwIrq ; _dwId=dwId ; } // Public Methods ////////////////////////////////////////////////////////////// void UARTClass::begin( const uint32_t dwBaudRate ) { begin( dwBaudRate, UART_MR_PAR_NO | UART_MR_CHMODE_NORMAL ); } void UARTClass::begin( const uint32_t dwBaudRate, const uint32_t config ) { // Configure PMC pmc_enable_periph_clk( _dwId ) ; // Disable PDC channel _pUart->UART_PTCR = UART_PTCR_RXTDIS | UART_PTCR_TXTDIS ; // Reset and disable receiver and transmitter _pUart->UART_CR = UART_CR_RSTRX | UART_CR_RSTTX | UART_CR_RXDIS | UART_CR_TXDIS ; // Configure mode _pUart->UART_MR = config ; // Configure baudrate (asynchronous, no oversampling) _pUart->UART_BRGR = (SystemCoreClock / dwBaudRate) >> 4 ; // Configure interrupts _pUart->UART_IDR = 0xFFFFFFFF; _pUart->UART_IER = UART_IER_RXRDY | UART_IER_OVRE | UART_IER_FRAME; // Enable UART interrupt in NVIC NVIC_EnableIRQ(_dwIrq); //make sure both ring buffers are initialized back to empty. _rx_buffer->_iHead = _rx_buffer->_iTail = 0; _tx_buffer->_iHead = _tx_buffer->_iTail = 0; // Enable receiver and transmitter _pUart->UART_CR = UART_CR_RXEN | UART_CR_TXEN ; } void UARTClass::end( void ) { // clear any received data _rx_buffer->_iHead = _rx_buffer->_iTail ; while (_tx_buffer->_iHead != _tx_buffer->_iTail); //wait for transmit data to be sent // Disable UART interrupt in NVIC NVIC_DisableIRQ( _dwIrq ) ; // Wait for any outstanding data to be sent flush(); pmc_disable_periph_clk( _dwId ) ; } void UARTClass::setInterruptPriority(uint32_t priority) { NVIC_SetPriority(_dwIrq, priority & 0x0F); } uint32_t UARTClass::getInterruptPriority() { return NVIC_GetPriority(_dwIrq); } int UARTClass::available( void ) { return (uint32_t)(SERIAL_BUFFER_SIZE + _rx_buffer->_iHead - _rx_buffer->_iTail) % SERIAL_BUFFER_SIZE ; } int UARTClass::availableForWrite(void) { int head = _tx_buffer->_iHead; int tail = _tx_buffer->_iTail; if (head >= tail) return SERIAL_BUFFER_SIZE - 1 - head + tail; return tail - head - 1; } int UARTClass::peek( void ) { if ( _rx_buffer->_iHead == _rx_buffer->_iTail ) return -1 ; return _rx_buffer->_aucBuffer[_rx_buffer->_iTail] ; } int UARTClass::read( void ) { // if the head isn't ahead of the tail, we don't have any characters if ( _rx_buffer->_iHead == _rx_buffer->_iTail ) return -1 ; uint8_t uc = _rx_buffer->_aucBuffer[_rx_buffer->_iTail] ; _rx_buffer->_iTail = (unsigned int)(_rx_buffer->_iTail + 1) % SERIAL_BUFFER_SIZE ; return uc ; } void UARTClass::flush( void ) { // Wait for transmission to complete while ((_pUart->UART_SR & UART_SR_TXRDY) != UART_SR_TXRDY) ; } size_t UARTClass::write( const uint8_t uc_data ) { if ((_pUart->UART_SR & UART_SR_TXRDY) != UART_SR_TXRDY) //is the hardware currently busy? { //if busy we buffer unsigned int l = (_tx_buffer->_iHead + 1) % SERIAL_BUFFER_SIZE; while (_tx_buffer->_iTail == l); //spin locks if we're about to overwrite the buffer. This continues once the data is sent _tx_buffer->_aucBuffer[_tx_buffer->_iHead] = uc_data; _tx_buffer->_iHead = l; _pUart->UART_IER = UART_IER_TXRDY; //make sure TX interrupt is enabled } else { // Send character _pUart->UART_THR = uc_data ; } return 1; } void UARTClass::IrqHandler( void ) { uint32_t status = _pUart->UART_SR; // Did we receive data ? if ((status & UART_SR_RXRDY) == UART_SR_RXRDY) _rx_buffer->store_char(_pUart->UART_RHR); //Do we need to keep sending data? if ((status & UART_SR_TXRDY) == UART_SR_TXRDY) { if (_tx_buffer->_iTail != _tx_buffer->_iHead) { //just in case _pUart->UART_THR = _tx_buffer->_aucBuffer[_tx_buffer->_iTail]; _tx_buffer->_iTail = (unsigned int)(_tx_buffer->_iTail + 1) % SERIAL_BUFFER_SIZE; } else { _pUart->UART_IDR = UART_IDR_TXRDY; //mask off transmit interrupt so we don't get it anymore } } // Acknowledge errors if ((status & UART_SR_OVRE) == UART_SR_OVRE || (status & UART_SR_FRAME) == UART_SR_FRAME) { // TODO: error reporting outside ISR _pUart->UART_CR |= UART_CR_RSTSTA; } }
/* Copyright (c) 2011 Arduino. All right reserved. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include <stdlib.h> #include <stdio.h> #include <string.h> #include "UARTClass.h" // Constructors //////////////////////////////////////////////////////////////// UARTClass::UARTClass( Uart *pUart, IRQn_Type dwIrq, uint32_t dwId, RingBuffer *pRx_buffer, RingBuffer *pTx_buffer ) { _rx_buffer = pRx_buffer ; _tx_buffer = pTx_buffer; _pUart=pUart ; _dwIrq=dwIrq ; _dwId=dwId ; } // Public Methods ////////////////////////////////////////////////////////////// void UARTClass::begin( const uint32_t dwBaudRate ) { begin( dwBaudRate, UART_MR_PAR_NO | UART_MR_CHMODE_NORMAL ); } void UARTClass::begin( const uint32_t dwBaudRate, const uint32_t config ) { // Configure PMC pmc_enable_periph_clk( _dwId ) ; // Disable PDC channel _pUart->UART_PTCR = UART_PTCR_RXTDIS | UART_PTCR_TXTDIS ; // Reset and disable receiver and transmitter _pUart->UART_CR = UART_CR_RSTRX | UART_CR_RSTTX | UART_CR_RXDIS | UART_CR_TXDIS ; // Configure mode _pUart->UART_MR = config ; // Configure baudrate (asynchronous, no oversampling) _pUart->UART_BRGR = (SystemCoreClock / dwBaudRate) >> 4 ; // Configure interrupts _pUart->UART_IDR = 0xFFFFFFFF; _pUart->UART_IER = UART_IER_RXRDY | UART_IER_OVRE | UART_IER_FRAME; // Enable UART interrupt in NVIC NVIC_EnableIRQ(_dwIrq); //make sure both ring buffers are initialized back to empty. _rx_buffer->_iHead = _rx_buffer->_iTail = 0; _tx_buffer->_iHead = _tx_buffer->_iTail = 0; // Enable receiver and transmitter _pUart->UART_CR = UART_CR_RXEN | UART_CR_TXEN ; } void UARTClass::end( void ) { // clear any received data _rx_buffer->_iHead = _rx_buffer->_iTail ; while (_tx_buffer->_iHead != _tx_buffer->_iTail); //wait for transmit data to be sent // Disable UART interrupt in NVIC NVIC_DisableIRQ( _dwIrq ) ; // Wait for any outstanding data to be sent flush(); pmc_disable_periph_clk( _dwId ) ; } void UARTClass::setInterruptPriority(uint32_t priority) { NVIC_SetPriority(_dwIrq, priority & 0x0F); } uint32_t UARTClass::getInterruptPriority() { return NVIC_GetPriority(_dwIrq); } int UARTClass::available( void ) { return (uint32_t)(SERIAL_BUFFER_SIZE + _rx_buffer->_iHead - _rx_buffer->_iTail) % SERIAL_BUFFER_SIZE ; } int UARTClass::availableForWrite(void) { int head = _tx_buffer->_iHead; int tail = _tx_buffer->_iTail; if (head >= tail) return SERIAL_BUFFER_SIZE - 1 - head + tail; return tail - head - 1; } int UARTClass::peek( void ) { if ( _rx_buffer->_iHead == _rx_buffer->_iTail ) return -1 ; return _rx_buffer->_aucBuffer[_rx_buffer->_iTail] ; } int UARTClass::read( void ) { // if the head isn't ahead of the tail, we don't have any characters if ( _rx_buffer->_iHead == _rx_buffer->_iTail ) return -1 ; uint8_t uc = _rx_buffer->_aucBuffer[_rx_buffer->_iTail] ; _rx_buffer->_iTail = (unsigned int)(_rx_buffer->_iTail + 1) % SERIAL_BUFFER_SIZE ; return uc ; } void UARTClass::flush( void ) { // Wait for transmission to complete while ((_pUart->UART_SR & UART_SR_TXRDY) != UART_SR_TXRDY) ; } size_t UARTClass::write( const uint8_t uc_data ) { if (((_pUart->UART_SR & UART_SR_TXRDY) != UART_SR_TXRDY) | (_tx_buffer->_iTail != _tx_buffer->_iHead)) //is the hardware currently busy? { //if busy we buffer unsigned int l = (_tx_buffer->_iHead + 1) % SERIAL_BUFFER_SIZE; while (_tx_buffer->_iTail == l); //spin locks if we're about to overwrite the buffer. This continues once the data is sent _tx_buffer->_aucBuffer[_tx_buffer->_iHead] = uc_data; _tx_buffer->_iHead = l; _pUart->UART_IER = UART_IER_TXRDY; //make sure TX interrupt is enabled } else { // Send character _pUart->UART_THR = uc_data ; } return 1; } void UARTClass::IrqHandler( void ) { uint32_t status = _pUart->UART_SR; // Did we receive data ? if ((status & UART_SR_RXRDY) == UART_SR_RXRDY) _rx_buffer->store_char(_pUart->UART_RHR); //Do we need to keep sending data? if ((status & UART_SR_TXRDY) == UART_SR_TXRDY) { if (_tx_buffer->_iTail != _tx_buffer->_iHead) { //just in case _pUart->UART_THR = _tx_buffer->_aucBuffer[_tx_buffer->_iTail]; _tx_buffer->_iTail = (unsigned int)(_tx_buffer->_iTail + 1) % SERIAL_BUFFER_SIZE; } else { _pUart->UART_IDR = UART_IDR_TXRDY; //mask off transmit interrupt so we don't get it anymore } } // Acknowledge errors if ((status & UART_SR_OVRE) == UART_SR_OVRE || (status & UART_SR_FRAME) == UART_SR_FRAME) { // TODO: error reporting outside ISR _pUart->UART_CR |= UART_CR_RSTSTA; } }
Correct an issue where write could send data out of order.
Correct an issue where write could send data out of order.
C++
lgpl-2.1
gonium/Arduino,PaoloP74/Arduino,shannonshsu/Arduino,laylthe/Arduino,arunkuttiyara/Arduino,nkolban/Arduino,Cloudino/Cloudino-Arduino-IDE,jabezGit/Arduino,OpenDevice/Arduino,jomolinare/Arduino,arduino-org/Arduino,lukeWal/Arduino,talhaburak/Arduino,Alfredynho/AgroSis,arduino-org/Arduino,NeuralSpaz/Arduino,Cloudino/Cloudino-Arduino-IDE,Cloudino/Cloudino-Arduino-IDE,spapadim/Arduino,steamboating/Arduino,superboonie/Arduino,ntruchsess/Arduino-1,weera00/Arduino,garci66/Arduino,Chris--A/Arduino,ForestNymph/Arduino_sources,PaoloP74/Arduino,lulufei/Arduino,sanyaade-iot/Arduino-1,arduino-org/Arduino,zenmanenergy/Arduino,tbowmo/Arduino,fungxu/Arduino,smily77/Arduino,ntruchsess/Arduino-1,gurbrinder/Arduino,stevemarple/Arduino-org,superboonie/Arduino,adamkh/Arduino,eeijcea/Arduino-1,lukeWal/Arduino,wilhelmryan/Arduino,henningpohl/Arduino,zaiexx/Arduino,zaiexx/Arduino,mattvenn/Arduino,leftbrainstrain/Arduino-ESP8266,mattvenn/Arduino,zaiexx/Arduino,piersoft/esp8266-Arduino,damellis/Arduino,andyvand/Arduino-1,steamboating/Arduino,danielchalef/Arduino,talhaburak/Arduino,zenmanenergy/Arduino,myrtleTree33/Arduino,scdls/Arduino,adafruit/ESP8266-Arduino,ccoenen/Arduino,ektor5/Arduino,karlitxo/Arduino,me-no-dev/Arduino-1,PeterVH/Arduino,Cloudino/Arduino,onovy/Arduino,wilhelmryan/Arduino,gonium/Arduino,mboufos/esp8266-Arduino,ricklon/Arduino,stevemarple/Arduino-org,tbowmo/Arduino,shiitakeo/Arduino,ari-analytics/Arduino,paulo-raca/ESP8266-Arduino,sanyaade-iot/Arduino-1,weera00/Arduino,NaSymbol/Arduino,acosinwork/Arduino,stevemarple/Arduino-org,ogferreiro/Arduino,arduino-org/Arduino,stickbreaker/Arduino,gberl001/Arduino,adamkh/Arduino,mboufos/esp8266-Arduino,mattvenn/Arduino,arduino-org/Arduino,gonium/Arduino,onovy/Arduino,koltegirish/Arduino,superboonie/Arduino,shannonshsu/Arduino,andyvand/Arduino-1,garci66/Arduino,xxxajk/Arduino-1,onovy/Arduino,mateuszdw/Arduino,stevemarple/Arduino-org,lulufei/Arduino,byran/Arduino,me-no-dev/Arduino-1,aichi/Arduino-2,ntruchsess/Arduino-1,jamesrob4/Arduino,HCastano/Arduino,eduardocasarin/Arduino,me-no-dev/Arduino-1,lukeWal/Arduino,scdls/Arduino,NaSymbol/Arduino,vbextreme/Arduino,nandojve/Arduino,ForestNymph/Arduino_sources,mboufos/esp8266-Arduino,jaimemaretoli/Arduino,shannonshsu/Arduino,acosinwork/Arduino,wilhelmryan/Arduino,SmartArduino/Arduino-1,karlitxo/Arduino,gurbrinder/Arduino,HCastano/Arduino,paulmand3l/Arduino,NicoHood/Arduino,gberl001/Arduino,plaintea/esp8266-Arduino,HCastano/Arduino,shannonshsu/Arduino,mangelajo/Arduino,ikbelkirasan/Arduino,smily77/Arduino,probonopd/Arduino,xxxajk/Arduino-1,nandojve/Arduino,myrtleTree33/Arduino,mateuszdw/Arduino,mc-hamster/esp8266-Arduino,radut/Arduino,probonopd/Arduino,snargledorf/Arduino,jabezGit/Arduino,eduardocasarin/Arduino,kidswong999/Arduino,kidswong999/Arduino,tannewt/Arduino,danielchalef/Arduino,Cloudino/Arduino,ssvs111/Arduino,plinioseniore/Arduino,PeterVH/Arduino,kidswong999/Arduino,jaehong/Xmegaduino,jabezGit/Arduino,fungxu/Arduino,stevemayhew/Arduino,Cloudino/Arduino,wayoda/Arduino,ashwin713/Arduino,zaiexx/Arduino,andrealmeidadomingues/Arduino,cscenter/Arduino,drpjk/Arduino,ogahara/Arduino,ogferreiro/Arduino,raimohanska/Arduino,lulufei/Arduino,talhaburak/Arduino,nkolban/Arduino,talhaburak/Arduino,PeterVH/Arduino,damellis/Arduino,eddyst/Arduino-SourceCode,mc-hamster/esp8266-Arduino,mateuszdw/Arduino,gurbrinder/Arduino,tskurauskas/Arduino,fungxu/Arduino,danielchalef/Arduino,jabezGit/Arduino,ektor5/Arduino,OpenDevice/Arduino,bigjosh/Arduino,Alfredynho/AgroSis,damellis/Arduino,KlaasDeNys/Arduino,ikbelkirasan/Arduino,andyvand/Arduino-1,eggfly/arduino,Gourav2906/Arduino,ogferreiro/Arduino,jaimemaretoli/Arduino,laylthe/Arduino,OpenDevice/Arduino,koltegirish/Arduino,jaehong/Xmegaduino,shannonshsu/Arduino,mattvenn/Arduino,ikbelkirasan/Arduino,OpenDevice/Arduino,ogferreiro/Arduino,kidswong999/Arduino,paulo-raca/ESP8266-Arduino,ogferreiro/Arduino,ektor5/Arduino,OpenDevice/Arduino,PeterVH/Arduino,jabezGit/Arduino,radut/Arduino,cscenter/Arduino,Cloudino/Arduino,piersoft/esp8266-Arduino,garci66/Arduino,chaveiro/Arduino,ntruchsess/Arduino-1,chaveiro/Arduino,tskurauskas/Arduino,koltegirish/Arduino,noahchense/Arduino-1,bsmr-arduino/Arduino,kidswong999/Arduino,NeuralSpaz/Arduino,xxxajk/Arduino-1,eeijcea/Arduino-1,gestrem/Arduino,Chris--A/Arduino,eduardocasarin/Arduino,henningpohl/Arduino,zederson/Arduino,OpenDevice/Arduino,eduardocasarin/Arduino,acosinwork/Arduino,tommyli2014/Arduino,eeijcea/Arduino-1,toddtreece/esp8266-Arduino,pdNor/Arduino,ThoughtWorksIoTGurgaon/Arduino,ForestNymph/Arduino_sources,plaintea/esp8266-Arduino,scdls/Arduino,pdNor/Arduino,ccoenen/Arduino,paulo-raca/ESP8266-Arduino,damellis/Arduino,henningpohl/Arduino,ThoughtWorksIoTGurgaon/Arduino,spapadim/Arduino,EmuxEvans/Arduino,jamesrob4/Arduino,gestrem/Arduino,majenkotech/Arduino,tommyli2014/Arduino,noahchense/Arduino-1,mattvenn/Arduino,drpjk/Arduino,adamkh/Arduino,bsmr-arduino/Arduino,adafruit/ESP8266-Arduino,mateuszdw/Arduino,jmgonzalez00449/Arduino,tomkrus007/Arduino,ashwin713/Arduino,Alfredynho/AgroSis,ssvs111/Arduino,benwolfe/esp8266-Arduino,ari-analytics/Arduino,niggor/Arduino_cc,ThoughtWorksIoTGurgaon/Arduino,leftbrainstrain/Arduino-ESP8266,andrealmeidadomingues/Arduino,snargledorf/Arduino,weera00/Arduino,ogahara/Arduino,wdoganowski/Arduino,zederson/Arduino,pdNor/Arduino,lulufei/Arduino,paulmand3l/Arduino,KlaasDeNys/Arduino,HCastano/Arduino,niggor/Arduino_cc,jaimemaretoli/Arduino,zenmanenergy/Arduino,scdls/Arduino,fungxu/Arduino,jomolinare/Arduino,tommyli2014/Arduino,bigjosh/Arduino,me-no-dev/Arduino-1,garci66/Arduino,tbowmo/Arduino,leftbrainstrain/Arduino-ESP8266,eggfly/arduino,wayoda/Arduino,stevemayhew/Arduino,PeterVH/Arduino,ntruchsess/Arduino-1,mattvenn/Arduino,eduardocasarin/Arduino,Protoneer/Arduino,ntruchsess/Arduino-1,mangelajo/Arduino,vbextreme/Arduino,tskurauskas/Arduino,andrealmeidadomingues/Arduino,andyvand/Arduino-1,raimohanska/Arduino,Cloudino/Arduino,EmuxEvans/Arduino,arunkuttiyara/Arduino,ashwin713/Arduino,snargledorf/Arduino,plaintea/esp8266-Arduino,onovy/Arduino,eggfly/arduino,ogahara/Arduino,PaoloP74/Arduino,wdoganowski/Arduino,SmartArduino/Arduino-1,koltegirish/Arduino,jomolinare/Arduino,myrtleTree33/Arduino,tbowmo/Arduino,ogahara/Arduino,ntruchsess/Arduino-1,superboonie/Arduino,sanyaade-iot/Arduino-1,arduino-org/Arduino,vbextreme/Arduino,lukeWal/Arduino,myrtleTree33/Arduino,SmartArduino/Arduino-1,drpjk/Arduino,radut/Arduino,bigjosh/Arduino,jabezGit/Arduino,mangelajo/Arduino,adamkh/Arduino,jaehong/Xmegaduino,scdls/Arduino,ForestNymph/Arduino_sources,majenkotech/Arduino,jamesrob4/Arduino,Chris--A/Arduino,lulufei/Arduino,tannewt/Arduino,plaintea/esp8266-Arduino,ntruchsess/Arduino-1,garci66/Arduino,probonopd/Arduino,Cloudino/Cloudino-Arduino-IDE,jomolinare/Arduino,majenkotech/Arduino,andyvand/Arduino-1,mateuszdw/Arduino,lukeWal/Arduino,NaSymbol/Arduino,eduardocasarin/Arduino,gurbrinder/Arduino,chaveiro/Arduino,xxxajk/Arduino-1,NicoHood/Arduino,ari-analytics/Arduino,ogahara/Arduino,smily77/Arduino,stickbreaker/Arduino,myrtleTree33/Arduino,stickbreaker/Arduino,OpenDevice/Arduino,weera00/Arduino,mboufos/esp8266-Arduino,henningpohl/Arduino,drpjk/Arduino,Protoneer/Arduino,gberl001/Arduino,adafruit/ESP8266-Arduino,plaintea/esp8266-Arduino,mattvenn/Arduino,pdNor/Arduino,tannewt/Arduino,PaoloP74/Arduino,jmgonzalez00449/Arduino,henningpohl/Arduino,steamboating/Arduino,Alfredynho/AgroSis,wdoganowski/Arduino,bigjosh/Arduino,nandojve/Arduino,andrealmeidadomingues/Arduino,vbextreme/Arduino,Gourav2906/Arduino,ricklon/Arduino,eeijcea/Arduino-1,mc-hamster/esp8266-Arduino,noahchense/Arduino-1,cscenter/Arduino,aichi/Arduino-2,arduino-org/Arduino,chaveiro/Arduino,paulo-raca/ESP8266-Arduino,ricklon/Arduino,gberl001/Arduino,zenmanenergy/Arduino,stevemayhew/Arduino,eggfly/arduino,gurbrinder/Arduino,gestrem/Arduino,adafruit/ESP8266-Arduino,steamboating/Arduino,xxxajk/Arduino-1,tskurauskas/Arduino,scdls/Arduino,tommyli2014/Arduino,damellis/Arduino,plinioseniore/Arduino,probonopd/Arduino,NaSymbol/Arduino,paulo-raca/ESP8266-Arduino,tomkrus007/Arduino,Chris--A/Arduino,piersoft/esp8266-Arduino,talhaburak/Arduino,ikbelkirasan/Arduino,lukeWal/Arduino,Gourav2906/Arduino,karlitxo/Arduino,bsmr-arduino/Arduino,ThoughtWorksIoTGurgaon/Arduino,ThoughtWorksIoTGurgaon/Arduino,probonopd/Arduino,chaveiro/Arduino,mateuszdw/Arduino,me-no-dev/Arduino-1,jmgonzalez00449/Arduino,zederson/Arduino,ccoenen/Arduino,vbextreme/Arduino,NeuralSpaz/Arduino,danielchalef/Arduino,garci66/Arduino,Chris--A/Arduino,fungxu/Arduino,zederson/Arduino,paulmand3l/Arduino,tommyli2014/Arduino,plinioseniore/Arduino,ForestNymph/Arduino_sources,jaehong/Xmegaduino,Gourav2906/Arduino,EmuxEvans/Arduino,tomkrus007/Arduino,Gourav2906/Arduino,NaSymbol/Arduino,stevemayhew/Arduino,byran/Arduino,raimohanska/Arduino,smily77/Arduino,ogahara/Arduino,EmuxEvans/Arduino,laylthe/Arduino,ssvs111/Arduino,KlaasDeNys/Arduino,raimohanska/Arduino,byran/Arduino,shannonshsu/Arduino,PaoloP74/Arduino,ikbelkirasan/Arduino,zederson/Arduino,kidswong999/Arduino,probonopd/Arduino,Chris--A/Arduino,byran/Arduino,paulmand3l/Arduino,acosinwork/Arduino,nkolban/Arduino,bigjosh/Arduino,HCastano/Arduino,wilhelmryan/Arduino,paulo-raca/ESP8266-Arduino,nkolban/Arduino,smily77/Arduino,stevemayhew/Arduino,stevemayhew/Arduino,aichi/Arduino-2,piersoft/esp8266-Arduino,bsmr-arduino/Arduino,eduardocasarin/Arduino,garci66/Arduino,benwolfe/esp8266-Arduino,spapadim/Arduino,wayoda/Arduino,jamesrob4/Arduino,cscenter/Arduino,paulo-raca/ESP8266-Arduino,laylthe/Arduino,tbowmo/Arduino,niggor/Arduino_cc,ThoughtWorksIoTGurgaon/Arduino,acosinwork/Arduino,majenkotech/Arduino,gonium/Arduino,nandojve/Arduino,snargledorf/Arduino,arunkuttiyara/Arduino,HCastano/Arduino,wdoganowski/Arduino,noahchense/Arduino-1,KlaasDeNys/Arduino,garci66/Arduino,karlitxo/Arduino,NicoHood/Arduino,ccoenen/Arduino,radut/Arduino,danielchalef/Arduino,laylthe/Arduino,paulmand3l/Arduino,adamkh/Arduino,Gourav2906/Arduino,nkolban/Arduino,Protoneer/Arduino,zaiexx/Arduino,adamkh/Arduino,snargledorf/Arduino,radut/Arduino,tbowmo/Arduino,weera00/Arduino,eggfly/arduino,PeterVH/Arduino,bsmr-arduino/Arduino,niggor/Arduino_cc,NaSymbol/Arduino,stickbreaker/Arduino,koltegirish/Arduino,snargledorf/Arduino,me-no-dev/Arduino-1,ogferreiro/Arduino,gestrem/Arduino,zenmanenergy/Arduino,ektor5/Arduino,koltegirish/Arduino,KlaasDeNys/Arduino,wayoda/Arduino,gestrem/Arduino,leftbrainstrain/Arduino-ESP8266,ikbelkirasan/Arduino,bigjosh/Arduino,bsmr-arduino/Arduino,ari-analytics/Arduino,shannonshsu/Arduino,KlaasDeNys/Arduino,ccoenen/Arduino,laylthe/Arduino,eggfly/arduino,Cloudino/Arduino,bsmr-arduino/Arduino,zederson/Arduino,jmgonzalez00449/Arduino,jaimemaretoli/Arduino,acosinwork/Arduino,wdoganowski/Arduino,scdls/Arduino,drpjk/Arduino,ashwin713/Arduino,ektor5/Arduino,Alfredynho/AgroSis,eddyst/Arduino-SourceCode,onovy/Arduino,ccoenen/Arduino,tomkrus007/Arduino,sanyaade-iot/Arduino-1,stickbreaker/Arduino,eddyst/Arduino-SourceCode,damellis/Arduino,EmuxEvans/Arduino,zaiexx/Arduino,Protoneer/Arduino,aichi/Arduino-2,stickbreaker/Arduino,spapadim/Arduino,Cloudino/Arduino,Cloudino/Cloudino-Arduino-IDE,raimohanska/Arduino,Chris--A/Arduino,benwolfe/esp8266-Arduino,ssvs111/Arduino,probonopd/Arduino,Protoneer/Arduino,wilhelmryan/Arduino,EmuxEvans/Arduino,eeijcea/Arduino-1,drpjk/Arduino,lulufei/Arduino,jmgonzalez00449/Arduino,raimohanska/Arduino,majenkotech/Arduino,jaimemaretoli/Arduino,henningpohl/Arduino,nandojve/Arduino,Alfredynho/AgroSis,spapadim/Arduino,zenmanenergy/Arduino,damellis/Arduino,niggor/Arduino_cc,tskurauskas/Arduino,andrealmeidadomingues/Arduino,eggfly/arduino,tannewt/Arduino,gestrem/Arduino,radut/Arduino,tskurauskas/Arduino,mangelajo/Arduino,leftbrainstrain/Arduino-ESP8266,ari-analytics/Arduino,tbowmo/Arduino,superboonie/Arduino,plinioseniore/Arduino,KlaasDeNys/Arduino,ikbelkirasan/Arduino,majenkotech/Arduino,onovy/Arduino,arunkuttiyara/Arduino,HCastano/Arduino,henningpohl/Arduino,aichi/Arduino-2,spapadim/Arduino,jabezGit/Arduino,EmuxEvans/Arduino,jaimemaretoli/Arduino,lukeWal/Arduino,ari-analytics/Arduino,benwolfe/esp8266-Arduino,byran/Arduino,stevemarple/Arduino-org,cscenter/Arduino,wayoda/Arduino,mateuszdw/Arduino,andrealmeidadomingues/Arduino,eddyst/Arduino-SourceCode,Cloudino/Cloudino-Arduino-IDE,steamboating/Arduino,NeuralSpaz/Arduino,lukeWal/Arduino,jmgonzalez00449/Arduino,karlitxo/Arduino,Gourav2906/Arduino,ssvs111/Arduino,byran/Arduino,stevemayhew/Arduino,shiitakeo/Arduino,stevemarple/Arduino-org,kidswong999/Arduino,gonium/Arduino,stickbreaker/Arduino,sanyaade-iot/Arduino-1,plinioseniore/Arduino,ricklon/Arduino,jaehong/Xmegaduino,gestrem/Arduino,tomkrus007/Arduino,majenkotech/Arduino,andyvand/Arduino-1,zaiexx/Arduino,koltegirish/Arduino,ektor5/Arduino,bigjosh/Arduino,andyvand/Arduino-1,toddtreece/esp8266-Arduino,eggfly/arduino,ssvs111/Arduino,radut/Arduino,ari-analytics/Arduino,NaSymbol/Arduino,tomkrus007/Arduino,jaimemaretoli/Arduino,steamboating/Arduino,ashwin713/Arduino,zenmanenergy/Arduino,ricklon/Arduino,niggor/Arduino_cc,shiitakeo/Arduino,fungxu/Arduino,gurbrinder/Arduino,jmgonzalez00449/Arduino,ashwin713/Arduino,talhaburak/Arduino,adafruit/ESP8266-Arduino,niggor/Arduino_cc,mangelajo/Arduino,ccoenen/Arduino,andrealmeidadomingues/Arduino,jamesrob4/Arduino,paulmand3l/Arduino,stevemarple/Arduino-org,jomolinare/Arduino,eddyst/Arduino-SourceCode,mc-hamster/esp8266-Arduino,adafruit/ESP8266-Arduino,tbowmo/Arduino,PeterVH/Arduino,piersoft/esp8266-Arduino,ThoughtWorksIoTGurgaon/Arduino,wayoda/Arduino,eeijcea/Arduino-1,jomolinare/Arduino,shiitakeo/Arduino,PaoloP74/Arduino,NicoHood/Arduino,Protoneer/Arduino,jamesrob4/Arduino,shannonshsu/Arduino,vbextreme/Arduino,smily77/Arduino,nandojve/Arduino,henningpohl/Arduino,weera00/Arduino,wdoganowski/Arduino,ikbelkirasan/Arduino,eeijcea/Arduino-1,SmartArduino/Arduino-1,ForestNymph/Arduino_sources,noahchense/Arduino-1,gberl001/Arduino,SmartArduino/Arduino-1,ashwin713/Arduino,tomkrus007/Arduino,mc-hamster/esp8266-Arduino,chaveiro/Arduino,tannewt/Arduino,leftbrainstrain/Arduino-ESP8266,me-no-dev/Arduino-1,SmartArduino/Arduino-1,chaveiro/Arduino,pdNor/Arduino,Protoneer/Arduino,ogferreiro/Arduino,chaveiro/Arduino,vbextreme/Arduino,KlaasDeNys/Arduino,wilhelmryan/Arduino,toddtreece/esp8266-Arduino,bsmr-arduino/Arduino,Gourav2906/Arduino,tannewt/Arduino,superboonie/Arduino,PeterVH/Arduino,lulufei/Arduino,mangelajo/Arduino,wdoganowski/Arduino,ogahara/Arduino,danielchalef/Arduino,xxxajk/Arduino-1,fungxu/Arduino,spapadim/Arduino,karlitxo/Arduino,jabezGit/Arduino,raimohanska/Arduino,onovy/Arduino,plinioseniore/Arduino,shiitakeo/Arduino,vbextreme/Arduino,gberl001/Arduino,talhaburak/Arduino,ForestNymph/Arduino_sources,tomkrus007/Arduino,ashwin713/Arduino,superboonie/Arduino,paulmand3l/Arduino,nandojve/Arduino,tommyli2014/Arduino,benwolfe/esp8266-Arduino,gonium/Arduino,jaehong/Xmegaduino,eddyst/Arduino-SourceCode,shiitakeo/Arduino,arunkuttiyara/Arduino,myrtleTree33/Arduino,aichi/Arduino-2,mboufos/esp8266-Arduino,NicoHood/Arduino,danielchalef/Arduino,adamkh/Arduino,plinioseniore/Arduino,karlitxo/Arduino,tskurauskas/Arduino,jomolinare/Arduino,superboonie/Arduino,cscenter/Arduino,aichi/Arduino-2,noahchense/Arduino-1,wilhelmryan/Arduino,NeuralSpaz/Arduino,ari-analytics/Arduino,snargledorf/Arduino,tannewt/Arduino,ricklon/Arduino,adafruit/ESP8266-Arduino,Alfredynho/AgroSis,mangelajo/Arduino,smily77/Arduino,steamboating/Arduino,myrtleTree33/Arduino,wayoda/Arduino,weera00/Arduino,me-no-dev/Arduino-1,stevemayhew/Arduino,jaimemaretoli/Arduino,NeuralSpaz/Arduino,pdNor/Arduino,HCastano/Arduino,byran/Arduino,gurbrinder/Arduino,xxxajk/Arduino-1,eddyst/Arduino-SourceCode,nkolban/Arduino,NaSymbol/Arduino,ccoenen/Arduino,NicoHood/Arduino,Chris--A/Arduino,PaoloP74/Arduino,acosinwork/Arduino,ricklon/Arduino,drpjk/Arduino,nandojve/Arduino,xxxajk/Arduino-1,niggor/Arduino_cc,sanyaade-iot/Arduino-1,pdNor/Arduino,jaehong/Xmegaduino,leftbrainstrain/Arduino-ESP8266,pdNor/Arduino,laylthe/Arduino,tskurauskas/Arduino,arduino-org/Arduino,nkolban/Arduino,zaiexx/Arduino,bigjosh/Arduino,NicoHood/Arduino,jmgonzalez00449/Arduino,NicoHood/Arduino,byran/Arduino,sanyaade-iot/Arduino-1,cscenter/Arduino,wayoda/Arduino,jamesrob4/Arduino,arunkuttiyara/Arduino,eddyst/Arduino-SourceCode,Cloudino/Cloudino-Arduino-IDE,cscenter/Arduino,gonium/Arduino,adamkh/Arduino,gberl001/Arduino,tommyli2014/Arduino,SmartArduino/Arduino-1,kidswong999/Arduino,NeuralSpaz/Arduino,acosinwork/Arduino,arunkuttiyara/Arduino,talhaburak/Arduino,stevemarple/Arduino-org,niggor/Arduino_cc,ssvs111/Arduino,PaoloP74/Arduino,noahchense/Arduino-1,shiitakeo/Arduino,ThoughtWorksIoTGurgaon/Arduino,zederson/Arduino
eeddd58c1a68c2fd6842dc5708fcd263e976a5dd
kalarm/main.cpp
kalarm/main.cpp
/* * main.cpp * Program: kalarm * Copyright (C) 2001 - 2005 by David Jarvie <[email protected]> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include "kalarm.h" #include <stdlib.h> #include <kcmdlineargs.h> #include <kaboutdata.h> #include <klocale.h> #include <kdebug.h> #include "kalarmapp.h" #define PROGRAM_NAME "kalarm" static KCmdLineOptions options[] = { { "a", 0, 0 }, { "ack-confirm", I18N_NOOP("Prompt for confirmation when alarm is acknowledged"), 0 }, { "A", 0, 0 }, { "attach <url>", I18N_NOOP("Attach file to email (repeat as needed)"), 0 }, { "auto-close", I18N_NOOP("Auto-close alarm window after --late-cancel period"), 0 }, { "bcc", I18N_NOOP("Blind copy email to self"), 0 }, { "b", 0, 0 }, { "beep", I18N_NOOP("Beep when message is displayed"), 0 }, { "colour", 0, 0 }, { "c", 0, 0 }, { "color <color>", I18N_NOOP("Message background color (name or hex 0xRRGGBB)"), 0 }, { "colourfg", 0, 0 }, { "C", 0, 0 }, { "colorfg <color>", I18N_NOOP("Message foreground color (name or hex 0xRRGGBB)"), 0 }, { "calendarURL <url>", I18N_NOOP("URL of calendar file"), 0 }, { "cancelEvent <eventID>", I18N_NOOP("Cancel alarm with the specified event ID"), 0 }, { "d", 0, 0 }, { "disable", I18N_NOOP("Disable the alarm"), 0 }, { "e", 0, 0 }, { "exec <commandline>", I18N_NOOP("Execute a shell command line"), 0 }, { "f", 0, 0 }, { "file <url>", I18N_NOOP("File to display"), 0 }, { "F", 0, 0 }, { "from-id <ID>", I18N_NOOP("KMail identity to use as sender of email"), 0 }, { "handleEvent <eventID>", I18N_NOOP("Trigger or cancel alarm with the specified event ID"), 0 }, { "i", 0, 0 }, { "interval <period>", I18N_NOOP("Interval between alarm repetitions"), 0 }, { "k", 0, 0 }, { "korganizer", I18N_NOOP("Show alarm as an event in KOrganizer"), 0 }, { "l", 0, 0 }, { "late-cancel <period>", I18N_NOOP("Cancel alarm if more than 'period' late when triggered"), "1" }, { "L", 0, 0 }, { "login", I18N_NOOP("Repeat alarm at every login"), 0 }, { "m", 0, 0 }, { "mail <address>", I18N_NOOP("Send an email to the given address (repeat as needed)"), 0 }, { "p", 0, 0 }, { "play <url>", I18N_NOOP("Audio file to play once"), 0 }, #ifndef WITHOUT_ARTS { "P", 0, 0 }, { "play-repeat <url>", I18N_NOOP("Audio file to play repeatedly"), 0 }, #endif { "recurrence <spec>", I18N_NOOP("Specify alarm recurrence using iCalendar syntax"), 0 }, { "R", 0, 0 }, { "reminder <period>", I18N_NOOP("Display reminder in advance of alarm"), 0 }, { "reminder-once <period>", I18N_NOOP("Display reminder once, before first alarm recurrence"), 0 }, { "r", 0, 0 }, { "repeat <count>", I18N_NOOP("Number of times to repeat alarm (including initial occasion)"), 0 }, { "reset", I18N_NOOP("Reset the alarm scheduling daemon"), 0 }, { "s", 0, 0 }, { "speak", I18N_NOOP("Speak the message when it is displayed"), 0 }, { "stop", I18N_NOOP("Stop the alarm scheduling daemon"), 0 }, { "S", 0, 0 }, { "subject ", I18N_NOOP("Email subject line"), 0 }, { "t", 0, 0 }, { "time <time>", I18N_NOOP("Trigger alarm at time [[[yyyy-]mm-]dd-]hh:mm, or date yyyy-mm-dd"), 0 }, { "tray", I18N_NOOP("Display system tray icon"), 0 }, { "triggerEvent <eventID>", I18N_NOOP("Trigger alarm with the specified event ID"), 0 }, { "u", 0, 0 }, { "until <time>", I18N_NOOP("Repeat until time [[[yyyy-]mm-]dd-]hh:mm, or date yyyy-mm-dd"), 0 }, #ifndef WITHOUT_ARTS { "V", 0, 0 }, { "volume <percent>", I18N_NOOP("Volume to play audio file"), 0 }, #endif { "+[message]", I18N_NOOP("Message text to display"), 0 }, KCmdLineLastOption }; int main(int argc, char *argv[]) { KAboutData aboutData(PROGRAM_NAME, I18N_NOOP("KAlarm"), KALARM_VERSION, I18N_NOOP("Personal alarm message, command and email scheduler for KDE"), KAboutData::License_GPL, "(c) 2001 - 2005, David Jarvie", 0, "http://www.astrojar.org.uk/linux/kalarm.html"); aboutData.addAuthor("David Jarvie", 0, "[email protected]"); // Fetch all command line options/arguments after --exec and // concatenate them into a single argument. // This is necessary because the "!" indicator in the 'options' // array above doesn't work (on KDE2, at least) int newargc = argc; char** newargv = argv; for (int i = 0; i < argc; ++i) { if (!strcmp(argv[i], "-e") || !strcmp(argv[i], "--exec")) { // --exec has been found. Create a new args list. newargc = i + 1; newargv = (char**)malloc(newargc * sizeof(char*)); for (int j = 0; j < newargc; ++j) newargv[j] = argv[j]; // Concatenate the --exec arguments into one QCString execArguments; while (++i < argc) { execArguments += argv[i]; if (i < argc - 1) execArguments += ' '; } i = execArguments.length(); newargv[newargc] = (char*)malloc(i + 1); memcpy(newargv[newargc], static_cast<const char*>(execArguments), i); newargv[newargc][i] = 0; ++newargc; break; } } KCmdLineArgs::init(newargc, newargv, &aboutData); KCmdLineArgs::addCmdLineOptions(options); KUniqueApplication::addCmdLineOptions(); if (!KAlarmApp::start()) { // An instance of the application is already running exit(0); } // This is the first time through kdDebug(5950) << "main(): initialising\n"; KAlarmApp* app = KAlarmApp::getInstance(); app->restoreSession(); return app->exec(); }
/* * main.cpp * Program: kalarm * Copyright (C) 2001 - 2005 by David Jarvie <[email protected]> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include "kalarm.h" #include <stdlib.h> #include <kcmdlineargs.h> #include <kaboutdata.h> #include <klocale.h> #include <kdebug.h> #include "kalarmapp.h" #define PROGRAM_NAME "kalarm" static KCmdLineOptions options[] = { { "a", 0, 0 }, { "ack-confirm", I18N_NOOP("Prompt for confirmation when alarm is acknowledged"), 0 }, { "A", 0, 0 }, { "attach <url>", I18N_NOOP("Attach file to email (repeat as needed)"), 0 }, { "auto-close", I18N_NOOP("Auto-close alarm window after --late-cancel period"), 0 }, { "bcc", I18N_NOOP("Blind copy email to self"), 0 }, { "b", 0, 0 }, { "beep", I18N_NOOP("Beep when message is displayed"), 0 }, { "colour", 0, 0 }, { "c", 0, 0 }, { "color <color>", I18N_NOOP("Message background color (name or hex 0xRRGGBB)"), 0 }, { "colourfg", 0, 0 }, { "C", 0, 0 }, { "colorfg <color>", I18N_NOOP("Message foreground color (name or hex 0xRRGGBB)"), 0 }, { "calendarURL <url>", I18N_NOOP("URL of calendar file"), 0 }, { "cancelEvent <eventID>", I18N_NOOP("Cancel alarm with the specified event ID"), 0 }, { "d", 0, 0 }, { "disable", I18N_NOOP("Disable the alarm"), 0 }, { "e", 0, 0 }, { "!exec <commandline>", I18N_NOOP("Execute a shell command line"), 0 }, { "f", 0, 0 }, { "file <url>", I18N_NOOP("File to display"), 0 }, { "F", 0, 0 }, { "from-id <ID>", I18N_NOOP("KMail identity to use as sender of email"), 0 }, { "handleEvent <eventID>", I18N_NOOP("Trigger or cancel alarm with the specified event ID"), 0 }, { "i", 0, 0 }, { "interval <period>", I18N_NOOP("Interval between alarm repetitions"), 0 }, { "k", 0, 0 }, { "korganizer", I18N_NOOP("Show alarm as an event in KOrganizer"), 0 }, { "l", 0, 0 }, { "late-cancel <period>", I18N_NOOP("Cancel alarm if more than 'period' late when triggered"), "1" }, { "L", 0, 0 }, { "login", I18N_NOOP("Repeat alarm at every login"), 0 }, { "m", 0, 0 }, { "mail <address>", I18N_NOOP("Send an email to the given address (repeat as needed)"), 0 }, { "p", 0, 0 }, { "play <url>", I18N_NOOP("Audio file to play once"), 0 }, #ifndef WITHOUT_ARTS { "P", 0, 0 }, { "play-repeat <url>", I18N_NOOP("Audio file to play repeatedly"), 0 }, #endif { "recurrence <spec>", I18N_NOOP("Specify alarm recurrence using iCalendar syntax"), 0 }, { "R", 0, 0 }, { "reminder <period>", I18N_NOOP("Display reminder in advance of alarm"), 0 }, { "reminder-once <period>", I18N_NOOP("Display reminder once, before first alarm recurrence"), 0 }, { "r", 0, 0 }, { "repeat <count>", I18N_NOOP("Number of times to repeat alarm (including initial occasion)"), 0 }, { "reset", I18N_NOOP("Reset the alarm scheduling daemon"), 0 }, { "s", 0, 0 }, { "speak", I18N_NOOP("Speak the message when it is displayed"), 0 }, { "stop", I18N_NOOP("Stop the alarm scheduling daemon"), 0 }, { "S", 0, 0 }, { "subject ", I18N_NOOP("Email subject line"), 0 }, { "t", 0, 0 }, { "time <time>", I18N_NOOP("Trigger alarm at time [[[yyyy-]mm-]dd-]hh:mm, or date yyyy-mm-dd"), 0 }, { "tray", I18N_NOOP("Display system tray icon"), 0 }, { "triggerEvent <eventID>", I18N_NOOP("Trigger alarm with the specified event ID"), 0 }, { "u", 0, 0 }, { "until <time>", I18N_NOOP("Repeat until time [[[yyyy-]mm-]dd-]hh:mm, or date yyyy-mm-dd"), 0 }, #ifndef WITHOUT_ARTS { "V", 0, 0 }, { "volume <percent>", I18N_NOOP("Volume to play audio file"), 0 }, #endif { "+[message]", I18N_NOOP("Message text to display"), 0 }, KCmdLineLastOption }; int main(int argc, char *argv[]) { KAboutData aboutData(PROGRAM_NAME, I18N_NOOP("KAlarm"), KALARM_VERSION, I18N_NOOP("Personal alarm message, command and email scheduler for KDE"), KAboutData::License_GPL, "(c) 2001 - 2005, David Jarvie", 0, "http://www.astrojar.org.uk/linux/kalarm.html"); aboutData.addAuthor("David Jarvie", 0, "[email protected]"); KCmdLineArgs::init(argc, argv, &aboutData); KCmdLineArgs::addCmdLineOptions(options); KUniqueApplication::addCmdLineOptions(); if (!KAlarmApp::start()) { // An instance of the application is already running exit(0); } // This is the first time through kdDebug(5950) << "main(): initialising\n"; KAlarmApp* app = KAlarmApp::getInstance(); app->restoreSession(); return app->exec(); }
Remove KDE 2 compatibility code
Remove KDE 2 compatibility code svn path=/branches/KDE/3.5/kdepim/; revision=453902
C++
lgpl-2.1
lefou/kdepim-noakonadi,lefou/kdepim-noakonadi,lefou/kdepim-noakonadi,lefou/kdepim-noakonadi,lefou/kdepim-noakonadi,lefou/kdepim-noakonadi
74ea7b03b3237486a992201bd0244407a1e40636
test/instr/OptimizeEnumsTestVerify.cpp
test/instr/OptimizeEnumsTestVerify.cpp
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #include <unordered_set> #include "DexInstruction.h" #include "verify/VerifyUtil.h" namespace { constexpr const char* FOO = "Lcom/facebook/redextest/Foo;"; constexpr const char* FOO_ANONYMOUS = "Lcom/facebook/redextest/Foo$1;"; constexpr const char* ENUM_A = "Lcom/facebook/redextest/EnumA;"; constexpr const char* ENUM_B = "Lcom/facebook/redextest/EnumB;"; std::unordered_set<size_t> collect_switch_cases(DexMethodRef* method_ref) { auto method = static_cast<DexMethod*>(method_ref); method->balloon(); auto code = method->get_code(); std::unordered_set<size_t> switch_cases; IRInstruction* packed_switch_insn = nullptr; for (auto it = code->begin(); it != code->end(); ++it) { if (it->type == MFLOW_OPCODE) { auto insn = it->insn; if (insn->opcode() == OPCODE_PACKED_SWITCH || insn->opcode() == OPCODE_SPARSE_SWITCH) { // We assume there is only 1 switch statement. EXPECT_EQ(nullptr, packed_switch_insn); packed_switch_insn = it->insn; } } if (it->type == MFLOW_TARGET) { auto branch_target = static_cast<BranchTarget*>(it->target); if (branch_target->type == BRANCH_MULTI && branch_target->src != nullptr && branch_target->src->type == MFLOW_OPCODE && branch_target->src->insn == packed_switch_insn) { switch_cases.emplace(branch_target->case_key); } } } return switch_cases; } } // namespace TEST_F(PreVerify, GeneratedClass) { auto enumA = find_class_named(classes, ENUM_A); EXPECT_NE(nullptr, enumA); auto foo = find_class_named(classes, FOO); EXPECT_NE(nullptr, foo); auto foo_anonymous = find_class_named(classes, FOO_ANONYMOUS); EXPECT_NE(nullptr, foo_anonymous); auto enumB = find_class_named(classes, ENUM_B); EXPECT_NE(nullptr, enumB); auto method_use_enumA = DexMethod::get_method( "Lcom/facebook/redextest/Foo;.useEnumA:(Lcom/facebook/redextest/" "EnumA;)I"); auto switch_cases_A = collect_switch_cases(method_use_enumA); std::unordered_set<size_t> expected_switch_cases_A = {1, 2}; EXPECT_EQ(expected_switch_cases_A, switch_cases_A); auto method_use_enumB = DexMethod::get_method( "Lcom/facebook/redextest/Foo;.useEnumB:(Lcom/facebook/redextest/" "EnumB;)I"); auto switch_cases_B = collect_switch_cases(method_use_enumB); std::unordered_set<size_t> expected_switch_cases_B = {1, 2}; EXPECT_EQ(expected_switch_cases_B, switch_cases_B); auto method_use_enumA_again = DexMethod::get_method( "Lcom/facebook/redextest/Foo;.useEnumA_again:(Lcom/facebook/redextest/" "EnumA;)I"); auto switch_cases_A_again = collect_switch_cases(method_use_enumA_again); std::unordered_set<size_t> expected_switch_cases_A_again = {2, 1, 3}; EXPECT_EQ(expected_switch_cases_A_again, switch_cases_A_again); } TEST_F(PostVerify, GeneratedClass) { auto enumA = find_class_named(classes, ENUM_A); EXPECT_NE(nullptr, enumA); auto enumB = find_class_named(classes, ENUM_B); EXPECT_NE(nullptr, enumB); auto foo = find_class_named(classes, FOO); EXPECT_NE(nullptr, foo); auto foo_anonymous = find_class_named(classes, FOO_ANONYMOUS); EXPECT_EQ(nullptr, foo_anonymous); auto method_use_enumA = DexMethod::get_method( "Lcom/facebook/redextest/Foo;.useEnumA:(Lcom/facebook/redextest/" "EnumA;)I"); auto switch_cases_A = collect_switch_cases(method_use_enumA); std::unordered_set<size_t> expected_switch_cases_A = {0, 2}; EXPECT_EQ(expected_switch_cases_A, switch_cases_A); auto method_use_enumB = DexMethod::get_method( "Lcom/facebook/redextest/Foo;.useEnumB:(Lcom/facebook/redextest/" "EnumB;)I"); auto switch_cases_B = collect_switch_cases(method_use_enumB); std::unordered_set<size_t> expected_switch_cases_B = {0, 2}; EXPECT_EQ(expected_switch_cases_B, switch_cases_B); auto method_use_enumA_again = DexMethod::get_method( "Lcom/facebook/redextest/Foo;.useEnumA_again:(Lcom/facebook/redextest/" "EnumA;)I"); auto switch_cases_A_again = collect_switch_cases(method_use_enumA_again); std::unordered_set<size_t> expected_switch_cases_A_again = {2, 0, 1}; EXPECT_EQ(expected_switch_cases_A_again, switch_cases_A_again); }
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #include <unordered_set> #include "DexInstruction.h" #include "SwitchMap.h" #include "verify/VerifyUtil.h" namespace { constexpr const char* FOO = "Lcom/facebook/redextest/Foo;"; constexpr const char* FOO_ANONYMOUS = "Lcom/facebook/redextest/Foo$1;"; constexpr const char* ENUM_A = "Lcom/facebook/redextest/EnumA;"; constexpr const char* ENUM_B = "Lcom/facebook/redextest/EnumB;"; std::unordered_set<size_t> collect_switch_cases(DexMethodRef* method_ref) { auto method = static_cast<DexMethod*>(method_ref); method->balloon(); auto code = method->get_code(); std::unordered_set<size_t> switch_cases; SwitchMethodPartitioning smp(code, /* verify_default_case */ false); for (const auto& entry : smp.get_key_to_block()) { switch_cases.insert(entry.first); } return switch_cases; } } // namespace TEST_F(PreVerify, GeneratedClass) { auto enumA = find_class_named(classes, ENUM_A); EXPECT_NE(nullptr, enumA); auto foo = find_class_named(classes, FOO); EXPECT_NE(nullptr, foo); auto foo_anonymous = find_class_named(classes, FOO_ANONYMOUS); EXPECT_NE(nullptr, foo_anonymous); auto enumB = find_class_named(classes, ENUM_B); EXPECT_NE(nullptr, enumB); auto method_use_enumA = DexMethod::get_method( "Lcom/facebook/redextest/Foo;.useEnumA:(Lcom/facebook/redextest/" "EnumA;)I"); auto switch_cases_A = collect_switch_cases(method_use_enumA); std::unordered_set<size_t> expected_switch_cases_A = {1, 2}; EXPECT_EQ(expected_switch_cases_A, switch_cases_A); auto method_use_enumB = DexMethod::get_method( "Lcom/facebook/redextest/Foo;.useEnumB:(Lcom/facebook/redextest/" "EnumB;)I"); auto switch_cases_B = collect_switch_cases(method_use_enumB); std::unordered_set<size_t> expected_switch_cases_B = {1, 2}; EXPECT_EQ(expected_switch_cases_B, switch_cases_B); auto method_use_enumA_again = DexMethod::get_method( "Lcom/facebook/redextest/Foo;.useEnumA_again:(Lcom/facebook/redextest/" "EnumA;)I"); auto switch_cases_A_again = collect_switch_cases(method_use_enumA_again); std::unordered_set<size_t> expected_switch_cases_A_again = {1, 3}; auto code = static_cast<DexMethod*>(method_use_enumA_again)->get_code(); code->build_cfg(); EXPECT_EQ(expected_switch_cases_A_again, switch_cases_A_again) << show(code->cfg()); } TEST_F(PostVerify, GeneratedClass) { auto enumA = find_class_named(classes, ENUM_A); EXPECT_NE(nullptr, enumA); auto enumB = find_class_named(classes, ENUM_B); EXPECT_NE(nullptr, enumB); auto foo = find_class_named(classes, FOO); EXPECT_NE(nullptr, foo); auto foo_anonymous = find_class_named(classes, FOO_ANONYMOUS); EXPECT_EQ(nullptr, foo_anonymous); auto method_use_enumA = DexMethod::get_method( "Lcom/facebook/redextest/Foo;.useEnumA:(Lcom/facebook/redextest/" "EnumA;)I"); auto switch_cases_A = collect_switch_cases(method_use_enumA); std::unordered_set<size_t> expected_switch_cases_A = {0, 2}; EXPECT_EQ(expected_switch_cases_A, switch_cases_A); auto method_use_enumB = DexMethod::get_method( "Lcom/facebook/redextest/Foo;.useEnumB:(Lcom/facebook/redextest/" "EnumB;)I"); auto switch_cases_B = collect_switch_cases(method_use_enumB); std::unordered_set<size_t> expected_switch_cases_B = {0, 2}; EXPECT_EQ(expected_switch_cases_B, switch_cases_B); auto method_use_enumA_again = DexMethod::get_method( "Lcom/facebook/redextest/Foo;.useEnumA_again:(Lcom/facebook/redextest/" "EnumA;)I"); auto switch_cases_A_again = collect_switch_cases(method_use_enumA_again); std::unordered_set<size_t> expected_switch_cases_A_again = {0, 1}; EXPECT_EQ(expected_switch_cases_A_again, switch_cases_A_again); }
Handle if-else tree in SwitchMap
Handle if-else tree in SwitchMap Summary: SwitchMethodPartitioning was originally designed for methods that had a single switch statement, but this diff extends it to support methods that use an if-else tree to choose a case block (instead of a switch). These methods may have been switch-only in source code, but have been compiled into if-else trees (usually by d8). Reviewed By: int3 Differential Revision: D13872279 fbshipit-source-id: 8d403827d34db2610fb53811fdf6d8189e71ad25
C++
mit
facebook/redex,facebook/redex,facebook/redex,facebook/redex,facebook/redex,facebook/redex,facebook/redex,facebook/redex,facebook/redex
141a323c3410f9d65b75cd546af69715735db23a
paddle/operators/spp_op.cc
paddle/operators/spp_op.cc
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserve. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. Indicesou may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "paddle/operators/spp_op.h" namespace paddle { namespace operators { class SppOpMaker : public framework::OpProtoAndCheckerMaker { public: SppOpMaker(framework::OpProto* proto, framework::OpAttrChecker* op_checker) : OpProtoAndCheckerMaker(proto, op_checker) { AddInput( "X", "(Tensor) The input tensor of spp operator. " "The format of input tensor is NCHW. Where N is batch size, C is the " "number of channels, H and W is the height and width of feature."); AddOutput("Out", "(Tensor) The output tensor of spp operator." "N * M." "M = C * H * W"); AddAttr<int>("pyramid_height", "int", "multi level pooling"); AddComment(R"DOC( "Does spatial pyramid pooling on the input image by taking the max, etc. within regions so that the result vector of different sized images are of the same size Input shape: $(N, C_{in}, H_{in}, W_{in})$ Output shape: $(H_{out}, W_{out})$ Where $$ H_{out} = N \\ W_{out} = (((4^pyramid_height) - 1) / (4 - 1))$ * C_{in} $$ )DOC"); } }; class SppOp : public framework::OperatorWithKernel { public: using framework::OperatorWithKernel::OperatorWithKernel; void InferShape(framework::InferShapeContext* ctx) const override { PADDLE_ENFORCE(ctx->HasInput("X"), "Input(X) of SppOp" "should not be null."); PADDLE_ENFORCE(ctx->HasOutput("Out"), "Output(Out) of SppOp should not be null."); auto in_x_dims = ctx->GetInputDim("X"); int pyramid_height = ctx->Attrs().Get<int>("pyramid_height"); PADDLE_ENFORCE(in_x_dims.size() == 4, "Spping intput must be of 4-dimensional."); int outlen = ((std::pow(4, pyramid_height) - 1) / (4 - 1)) * in_x_dims[1]; std::vector<int64_t> output_shape({in_x_dims[0], outlen}); ctx->SetOutputDim("Out", framework::make_ddim(output_shape)); } }; class SppOpGrad : public framework::OperatorWithKernel { public: using framework::OperatorWithKernel::OperatorWithKernel; void InferShape(framework::InferShapeContext* ctx) const override { PADDLE_ENFORCE(ctx->HasInput("X"), "Input(X) must not be null."); PADDLE_ENFORCE(ctx->HasOutput(framework::GradVarName("X")), "Input(X@GRAD) should not be null."); ctx->SetOutputDim(framework::GradVarName("X"), ctx->GetInputDim("X")); } }; } // namespace operators } // namespace paddle namespace ops = paddle::operators; REGISTER_OP(spp, ops::SppOp, ops::SppOpMaker, spp_grad, ops::SppOpGrad); REGISTER_OP_CPU_KERNEL(spp, ops::SppKernel<paddle::platform::CPUPlace, float>, ops::SppKernel<paddle::platform::CPUPlace, double>); REGISTER_OP_CPU_KERNEL(spp_grad, ops::SppGradKernel<paddle::platform::CPUPlace, float>, ops::SppGradKernel<paddle::platform::CPUPlace, double>);
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserve. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. Indicesou may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "paddle/operators/spp_op.h" namespace paddle { namespace operators { class SppOpMaker : public framework::OpProtoAndCheckerMaker { public: SppOpMaker(framework::OpProto* proto, framework::OpAttrChecker* op_checker) : OpProtoAndCheckerMaker(proto, op_checker) { AddInput( "X", "(Tensor) The input tensor of spp operator. " "The format of input tensor is NCHW. Where N is batch size, C is the " "number of channels, H and W is the height and width of feature."); AddOutput("Out", "(Tensor) The output tensor of spp operator." "N * M." "M = C * H * W"); AddAttr<int>("pyramid_height", "(int), multi level pooling"); AddComment(R"DOC( "Does spatial pyramid pooling on the input image by taking the max, etc. within regions so that the result vector of different sized images are of the same size Input shape: $(N, C_{in}, H_{in}, W_{in})$ Output shape: $(H_{out}, W_{out})$ Where $$ H_{out} = N \\ W_{out} = (((4^pyramid_height) - 1) / (4 - 1))$ * C_{in} $$ )DOC"); } }; class SppOp : public framework::OperatorWithKernel { public: using framework::OperatorWithKernel::OperatorWithKernel; void InferShape(framework::InferShapeContext* ctx) const override { PADDLE_ENFORCE(ctx->HasInput("X"), "Input(X) of SppOp" "should not be null."); PADDLE_ENFORCE(ctx->HasOutput("Out"), "Output(Out) of SppOp should not be null."); auto in_x_dims = ctx->GetInputDim("X"); int pyramid_height = ctx->Attrs().Get<int>("pyramid_height"); PADDLE_ENFORCE(in_x_dims.size() == 4, "Spping intput must be of 4-dimensional."); int outlen = ((std::pow(4, pyramid_height) - 1) / (4 - 1)) * in_x_dims[1]; std::vector<int64_t> output_shape({in_x_dims[0], outlen}); ctx->SetOutputDim("Out", framework::make_ddim(output_shape)); } }; class SppOpGrad : public framework::OperatorWithKernel { public: using framework::OperatorWithKernel::OperatorWithKernel; void InferShape(framework::InferShapeContext* ctx) const override { PADDLE_ENFORCE(ctx->HasInput("X"), "Input(X) must not be null."); PADDLE_ENFORCE(ctx->HasOutput(framework::GradVarName("X")), "Input(X@GRAD) should not be null."); ctx->SetOutputDim(framework::GradVarName("X"), ctx->GetInputDim("X")); } }; } // namespace operators } // namespace paddle namespace ops = paddle::operators; REGISTER_OP(spp, ops::SppOp, ops::SppOpMaker, spp_grad, ops::SppOpGrad); REGISTER_OP_CPU_KERNEL(spp, ops::SppKernel<paddle::platform::CPUPlace, float>, ops::SppKernel<paddle::platform::CPUPlace, double>); REGISTER_OP_CPU_KERNEL(spp_grad, ops::SppGradKernel<paddle::platform::CPUPlace, float>, ops::SppGradKernel<paddle::platform::CPUPlace, double>);
fix a bug
fix a bug
C++
apache-2.0
PaddlePaddle/Paddle,PaddlePaddle/Paddle,lcy-seso/Paddle,tensor-tang/Paddle,reyoung/Paddle,Canpio/Paddle,lcy-seso/Paddle,Canpio/Paddle,jacquesqiao/Paddle,putcn/Paddle,reyoung/Paddle,tensor-tang/Paddle,luotao1/Paddle,PaddlePaddle/Paddle,pkuyym/Paddle,Canpio/Paddle,QiJune/Paddle,lcy-seso/Paddle,reyoung/Paddle,reyoung/Paddle,QiJune/Paddle,jacquesqiao/Paddle,chengduoZH/Paddle,Canpio/Paddle,luotao1/Paddle,tensor-tang/Paddle,chengduoZH/Paddle,putcn/Paddle,lcy-seso/Paddle,Canpio/Paddle,baidu/Paddle,Canpio/Paddle,baidu/Paddle,QiJune/Paddle,luotao1/Paddle,lcy-seso/Paddle,PaddlePaddle/Paddle,jacquesqiao/Paddle,jacquesqiao/Paddle,baidu/Paddle,chengduoZH/Paddle,pkuyym/Paddle,reyoung/Paddle,PaddlePaddle/Paddle,pkuyym/Paddle,pkuyym/Paddle,baidu/Paddle,putcn/Paddle,tensor-tang/Paddle,pkuyym/Paddle,QiJune/Paddle,luotao1/Paddle,PaddlePaddle/Paddle,putcn/Paddle,luotao1/Paddle,QiJune/Paddle,pkuyym/Paddle,lcy-seso/Paddle,Canpio/Paddle,jacquesqiao/Paddle,putcn/Paddle,PaddlePaddle/Paddle,putcn/Paddle,jacquesqiao/Paddle,baidu/Paddle,chengduoZH/Paddle,tensor-tang/Paddle,QiJune/Paddle,chengduoZH/Paddle,luotao1/Paddle,Canpio/Paddle,luotao1/Paddle,reyoung/Paddle
d744ab12d3a72169ef656fc6bcec6d9eadd1a3ec
test_rclcpp/test/test_subscription.cpp
test_rclcpp/test/test_subscription.cpp
// Copyright 2015 Open Source Robotics Foundation, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <chrono> #include <iostream> #include "gtest/gtest.h" #include "rclcpp/rclcpp.hpp" #include "test_rclcpp/msg/u_int32.hpp" #ifdef RMW_IMPLEMENTATION # define CLASSNAME_(NAME, SUFFIX) NAME ## __ ## SUFFIX # define CLASSNAME(NAME, SUFFIX) CLASSNAME_(NAME, SUFFIX) #else # define CLASSNAME(NAME, SUFFIX) NAME #endif static const std::chrono::milliseconds sleep_per_loop(10); static const int max_loops = 200; TEST(CLASSNAME(test_subscription, RMW_IMPLEMENTATION), subscription_and_spinning) { rclcpp::init(0, nullptr); auto node = rclcpp::Node::make_shared("test_subscription"); rmw_qos_profile_t custom_qos_profile = rmw_qos_profile_default; custom_qos_profile.depth = 10; auto publisher = node->create_publisher<test_rclcpp::msg::UInt32>( "test_subscription", custom_qos_profile); uint32_t counter = 0; auto callback = [&counter](const test_rclcpp::msg::UInt32::SharedPtr msg) -> void { ++counter; printf(" callback() %4u with message data %u\n", counter, msg->data); ASSERT_EQ(counter, msg->data); }; auto msg = std::make_shared<test_rclcpp::msg::UInt32>(); msg->data = 0; rclcpp::executors::SingleThreadedExecutor executor; { auto subscriber = node->create_subscription<test_rclcpp::msg::UInt32>( "test_subscription", callback, custom_qos_profile); // start condition ASSERT_EQ(0, counter); // nothing should be pending here printf("spin_node_once(nonblocking) - no callback expected\n"); executor.spin_node_once(node, std::chrono::milliseconds(0)); ASSERT_EQ(0, counter); printf("spin_node_some() - no callback expected\n"); executor.spin_node_some(node); ASSERT_EQ(0, counter); msg->data = 1; publisher->publish(msg); ASSERT_EQ(0, counter); // wait for the first callback printf("spin_node_once() - callback (1) expected\n"); executor.spin_node_once(node); ASSERT_EQ(1, counter); // nothing should be pending here printf("spin_node_once(nonblocking) - no callback expected\n"); executor.spin_node_once(node, std::chrono::milliseconds(0)); ASSERT_EQ(1, counter); printf("spin_node_some() - no callback expected\n"); executor.spin_node_some(node); ASSERT_EQ(1, counter); msg->data = 2; publisher->publish(msg); msg->data = 3; publisher->publish(msg); msg->data = 4; publisher->publish(msg); msg->data = 5; publisher->publish(msg); ASSERT_EQ(1, counter); // while four messages have been published one callback should be triggered here printf("spin_node_once(nonblocking) - callback (2) expected\n"); executor.spin_node_once(node, std::chrono::milliseconds(0)); if (counter == 1) { // give the executor thread time to process the event std::this_thread::sleep_for(std::chrono::milliseconds(25)); printf("spin_node_once(nonblocking) - callback (2) expected - trying again\n"); executor.spin_node_once(node, std::chrono::milliseconds(0)); } ASSERT_EQ(2, counter); // check for next pending call printf("spin_node_once(nonblocking) - callback (3) expected\n"); executor.spin_node_once(node, std::chrono::milliseconds(0)); if (counter == 2) { // give the executor thread time to process the event std::this_thread::sleep_for(std::chrono::milliseconds(25)); printf("spin_node_once(nonblocking) - callback (3) expected - trying again\n"); executor.spin_node_once(node, std::chrono::milliseconds(0)); } ASSERT_EQ(3, counter); // check for all remaning calls printf("spin_node_some() - callbacks (4 and 5) expected\n"); executor.spin_node_some(node); if (counter == 3 || counter == 4) { // give the executor thread time to process the event std::this_thread::sleep_for(std::chrono::milliseconds(25)); printf("spin_node_some() - callback (%s) expected - trying again\n", counter == 3 ? "4 and 5" : "5"); executor.spin_node_once(node, std::chrono::milliseconds(0)); } ASSERT_EQ(5, counter); } // the subscriber goes out of scope and should be not receive any callbacks anymore // wait a moment for everything to initialize // TODO(gerkey): fix nondeterministic startup behavior rclcpp::utilities::sleep_for(1_ms); msg->data = 6; publisher->publish(msg); std::this_thread::sleep_for(std::chrono::milliseconds(25)); // check that no further callbacks have been invoked printf("spin_node_some() - no callbacks expected\n"); executor.spin_node_some(node); ASSERT_EQ(5, counter); } // Shortened version of the test for the ConstSharedPtr callback signature TEST(CLASSNAME(test_subscription, RMW_IMPLEMENTATION), subscription_shared_ptr_const) { auto node = rclcpp::Node::make_shared("test_subscription"); auto publisher = node->create_publisher<test_rclcpp::msg::UInt32>( "test_subscription", rmw_qos_profile_default); uint32_t counter = 0; auto callback = [&counter](test_rclcpp::msg::UInt32::ConstSharedPtr msg) -> void { ++counter; printf(" callback() %4u with message data %u\n", counter, msg->data); ASSERT_EQ(counter, msg->data); }; auto msg = std::make_shared<test_rclcpp::msg::UInt32>(); msg->data = 0; rclcpp::executors::SingleThreadedExecutor executor; auto subscriber = node->create_subscription<test_rclcpp::msg::UInt32>( "test_subscription", callback, rmw_qos_profile_default); // wait a moment for everything to initialize // TODO(gerkey): fix nondeterministic startup behavior rclcpp::utilities::sleep_for(1_ms); // start condition ASSERT_EQ(0, counter); // nothing should be pending here executor.spin_node_some(node); ASSERT_EQ(0, counter); msg->data = 1; // Create a ConstSharedPtr message to publish test_rclcpp::msg::UInt32::ConstSharedPtr const_msg(msg); publisher->publish(const_msg); ASSERT_EQ(0, counter); // wait for the first callback printf("spin_node_some() - callback (1) expected\n"); executor.spin_node_some(node); // spin for up to 2s int loop = 0; while ((counter != 1) && (loop++ < max_loops)) { printf("callback not called, sleeping and trying again\n"); std::this_thread::sleep_for(sleep_per_loop); executor.spin_node_some(node); } ASSERT_EQ(1, counter); } class CallbackHolder { public: uint32_t counter; void callback(test_rclcpp::msg::UInt32::ConstSharedPtr msg) { ++counter; ASSERT_EQ(counter, msg->data); } CallbackHolder() : counter(0) {} }; // Shortened version of the test for the ConstSharedPtr callback signature in a method TEST(CLASSNAME(test_subscription, RMW_IMPLEMENTATION), subscription_shared_ptr_const_method_std_function) { CallbackHolder cb_holder; auto node = rclcpp::Node::make_shared("test_subscription"); auto publisher = node->create_publisher<test_rclcpp::msg::UInt32>( "test_subscription", rmw_qos_profile_default); std::function<void(test_rclcpp::msg::UInt32::ConstSharedPtr)> cb_std_function = std::bind( &CallbackHolder::callback, &cb_holder, std::placeholders::_1); auto msg = std::make_shared<test_rclcpp::msg::UInt32>(); msg->data = 0; rclcpp::executors::SingleThreadedExecutor executor; auto subscriber = node->create_subscription<test_rclcpp::msg::UInt32>( "test_subscription", cb_std_function, rmw_qos_profile_default); // wait a moment for everything to initialize // TODO(gerkey): fix nondeterministic startup behavior rclcpp::utilities::sleep_for(1_ms); // start condition ASSERT_EQ(0, cb_holder.counter); // nothing should be pending here executor.spin_node_some(node); ASSERT_EQ(0, cb_holder.counter); msg->data = 1; // Create a ConstSharedPtr message to publish test_rclcpp::msg::UInt32::ConstSharedPtr const_msg(msg); publisher->publish(const_msg); ASSERT_EQ(0, cb_holder.counter); // wait for the first callback printf("spin_node_some() - callback (1) expected\n"); executor.spin_node_some(node); // spin for up to 2s int loop = 0; while ((cb_holder.counter != 1) && (loop++ < max_loops)) { printf("callback not called, sleeping and trying again\n"); std::this_thread::sleep_for(sleep_per_loop); executor.spin_node_some(node); } ASSERT_EQ(1, cb_holder.counter); } // Shortened version of the test for the ConstSharedPtr callback signature in a method TEST(CLASSNAME(test_subscription, RMW_IMPLEMENTATION), subscription_shared_ptr_const_method_direct) { CallbackHolder cb_holder; auto node = rclcpp::Node::make_shared("test_subscription"); auto publisher = node->create_publisher<test_rclcpp::msg::UInt32>( "test_subscription", rmw_qos_profile_default); auto msg = std::make_shared<test_rclcpp::msg::UInt32>(); msg->data = 0; rclcpp::executors::SingleThreadedExecutor executor; auto subscriber = node->create_subscription<test_rclcpp::msg::UInt32>( "test_subscription", std::bind(&CallbackHolder::callback, &cb_holder, std::placeholders::_1), rmw_qos_profile_default); // wait a moment for everything to initialize // TODO(gerkey): fix nondeterministic startup behavior rclcpp::utilities::sleep_for(1_ms); // start condition ASSERT_EQ(0, cb_holder.counter); // nothing should be pending here executor.spin_node_some(node); ASSERT_EQ(0, cb_holder.counter); msg->data = 1; // Create a ConstSharedPtr message to publish test_rclcpp::msg::UInt32::ConstSharedPtr const_msg(msg); publisher->publish(const_msg); ASSERT_EQ(0, cb_holder.counter); // wait for the first callback printf("spin_node_some() - callback (1) expected\n"); executor.spin_node_some(node); // spin for up to 2s int loop = 0; while ((cb_holder.counter != 1) && (loop++ < max_loops)) { printf("callback not called, sleeping and trying again\n"); std::this_thread::sleep_for(std::chrono::milliseconds(sleep_per_loop)); executor.spin_node_some(node); } ASSERT_EQ(1, cb_holder.counter); } // Shortened version of the test for the ConstSharedPtr with info callback signature TEST(CLASSNAME(test_subscription, RMW_IMPLEMENTATION), subscription_shared_ptr_const_with_info) { auto node = rclcpp::Node::make_shared("test_subscription"); auto publisher = node->create_publisher<test_rclcpp::msg::UInt32>( "test_subscription", rmw_qos_profile_default); uint32_t counter = 0; auto callback = [&counter](test_rclcpp::msg::UInt32::ConstSharedPtr msg, const rmw_message_info_t & info) -> void { ++counter; printf(" callback() %4u with message data %u\n", counter, msg->data); ASSERT_EQ(counter, msg->data); ASSERT_FALSE(info.from_intra_process); }; auto msg = std::make_shared<test_rclcpp::msg::UInt32>(); msg->data = 0; rclcpp::executors::SingleThreadedExecutor executor; auto subscriber = node->create_subscription<test_rclcpp::msg::UInt32>( "test_subscription", callback, rmw_qos_profile_default); // wait a moment for everything to initialize // TODO(gerkey): fix nondeterministic startup behavior rclcpp::utilities::sleep_for(1_ms); // start condition ASSERT_EQ(0, counter); // nothing should be pending here executor.spin_node_some(node); ASSERT_EQ(0, counter); msg->data = 1; publisher->publish(msg); ASSERT_EQ(0, counter); // wait for the first callback printf("spin_node_some() - callback (1) expected\n"); executor.spin_node_some(node); // spin for up to 2s int loop = 0; while ((counter != 1) && (loop++ < max_loops)) { printf("callback not called, sleeping and trying again\n"); std::this_thread::sleep_for(sleep_per_loop); executor.spin_node_some(node); } ASSERT_EQ(1, counter); } // Test of the queue size create_subscription signature. TEST(CLASSNAME(test_subscription, RMW_IMPLEMENTATION), create_subscription_with_queue_size) { auto node = rclcpp::Node::make_shared("test_subscription"); // *INDENT-OFF* auto callback = [](test_rclcpp::msg::UInt32::ConstSharedPtr) -> void {}; // *INDENT-ON* auto subscriber = node->create_subscription<test_rclcpp::msg::UInt32>( "test_subscription", 10, callback); }
// Copyright 2015 Open Source Robotics Foundation, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <chrono> #include <iostream> #include "gtest/gtest.h" #include "rclcpp/rclcpp.hpp" #include "test_rclcpp/msg/u_int32.hpp" #ifdef RMW_IMPLEMENTATION # define CLASSNAME_(NAME, SUFFIX) NAME ## __ ## SUFFIX # define CLASSNAME(NAME, SUFFIX) CLASSNAME_(NAME, SUFFIX) #else # define CLASSNAME(NAME, SUFFIX) NAME #endif static const std::chrono::milliseconds sleep_per_loop(10); static const int max_loops = 200; TEST(CLASSNAME(test_subscription, RMW_IMPLEMENTATION), subscription_and_spinning) { rclcpp::init(0, nullptr); auto node = rclcpp::Node::make_shared("test_subscription"); rmw_qos_profile_t custom_qos_profile = rmw_qos_profile_default; custom_qos_profile.depth = 10; auto publisher = node->create_publisher<test_rclcpp::msg::UInt32>( "test_subscription", custom_qos_profile); uint32_t counter = 0; auto callback = [&counter](const test_rclcpp::msg::UInt32::SharedPtr msg) -> void { ++counter; printf(" callback() %4u with message data %u\n", counter, msg->data); ASSERT_EQ(counter, msg->data); }; auto msg = std::make_shared<test_rclcpp::msg::UInt32>(); msg->data = 0; rclcpp::executors::SingleThreadedExecutor executor; { auto subscriber = node->create_subscription<test_rclcpp::msg::UInt32>( "test_subscription", callback, custom_qos_profile); // start condition ASSERT_EQ(0, counter); // nothing should be pending here printf("spin_node_once(nonblocking) - no callback expected\n"); executor.spin_node_once(node, std::chrono::milliseconds(0)); ASSERT_EQ(0, counter); printf("spin_node_some() - no callback expected\n"); executor.spin_node_some(node); ASSERT_EQ(0, counter); msg->data = 1; publisher->publish(msg); ASSERT_EQ(0, counter); // wait for the first callback printf("spin_node_once() - callback (1) expected\n"); executor.spin_node_once(node); ASSERT_EQ(1, counter); // nothing should be pending here printf("spin_node_once(nonblocking) - no callback expected\n"); executor.spin_node_once(node, std::chrono::milliseconds(0)); ASSERT_EQ(1, counter); printf("spin_node_some() - no callback expected\n"); executor.spin_node_some(node); ASSERT_EQ(1, counter); msg->data = 2; publisher->publish(msg); msg->data = 3; publisher->publish(msg); msg->data = 4; publisher->publish(msg); msg->data = 5; publisher->publish(msg); ASSERT_EQ(1, counter); // while four messages have been published one callback should be triggered here printf("spin_node_once(nonblocking) - callback (2) expected\n"); executor.spin_node_once(node, std::chrono::milliseconds(0)); if (counter == 1) { // give the executor thread time to process the event std::this_thread::sleep_for(std::chrono::milliseconds(25)); printf("spin_node_once(nonblocking) - callback (2) expected - trying again\n"); executor.spin_node_once(node, std::chrono::milliseconds(0)); } ASSERT_EQ(2, counter); // check for next pending call printf("spin_node_once(nonblocking) - callback (3) expected\n"); executor.spin_node_once(node, std::chrono::milliseconds(0)); if (counter == 2) { // give the executor thread time to process the event std::this_thread::sleep_for(std::chrono::milliseconds(25)); printf("spin_node_once(nonblocking) - callback (3) expected - trying again\n"); executor.spin_node_once(node, std::chrono::milliseconds(0)); } ASSERT_EQ(3, counter); // check for all remaning calls printf("spin_node_some() - callbacks (4 and 5) expected\n"); executor.spin_node_some(node); if (counter == 3 || counter == 4) { // give the executor thread time to process the event std::this_thread::sleep_for(std::chrono::milliseconds(25)); printf("spin_node_some() - callback (%s) expected - trying again\n", counter == 3 ? "4 and 5" : "5"); executor.spin_node_once(node, std::chrono::milliseconds(0)); } ASSERT_EQ(5, counter); } // the subscriber goes out of scope and should be not receive any callbacks anymore // wait a moment for everything to initialize // TODO(gerkey): fix nondeterministic startup behavior rclcpp::utilities::sleep_for(1_ms); msg->data = 6; publisher->publish(msg); std::this_thread::sleep_for(std::chrono::milliseconds(25)); // check that no further callbacks have been invoked printf("spin_node_some() - no callbacks expected\n"); executor.spin_node_some(node); ASSERT_EQ(5, counter); } // Shortened version of the test for the ConstSharedPtr callback signature TEST(CLASSNAME(test_subscription, RMW_IMPLEMENTATION), subscription_shared_ptr_const) { auto node = rclcpp::Node::make_shared("test_subscription"); auto publisher = node->create_publisher<test_rclcpp::msg::UInt32>( "test_subscription", rmw_qos_profile_default); uint32_t counter = 0; auto callback = [&counter](test_rclcpp::msg::UInt32::ConstSharedPtr msg) -> void { ++counter; printf(" callback() %4u with message data %u\n", counter, msg->data); ASSERT_EQ(counter, msg->data); }; auto msg = std::make_shared<test_rclcpp::msg::UInt32>(); msg->data = 0; rclcpp::executors::SingleThreadedExecutor executor; auto subscriber = node->create_subscription<test_rclcpp::msg::UInt32>( "test_subscription", callback, rmw_qos_profile_default); // wait a moment for everything to initialize // TODO(gerkey): fix nondeterministic startup behavior rclcpp::utilities::sleep_for(1_ms); // start condition ASSERT_EQ(0, counter); // nothing should be pending here executor.spin_node_some(node); ASSERT_EQ(0, counter); msg->data = 1; // Create a ConstSharedPtr message to publish test_rclcpp::msg::UInt32::ConstSharedPtr const_msg(msg); publisher->publish(const_msg); ASSERT_EQ(0, counter); // wait for the first callback printf("spin_node_some() - callback (1) expected\n"); executor.spin_node_some(node); // spin for up to 2s int loop = 0; while ((counter != 1) && (loop++ < max_loops)) { printf("callback not called, sleeping and trying again\n"); std::this_thread::sleep_for(sleep_per_loop); executor.spin_node_some(node); } ASSERT_EQ(1, counter); } class CallbackHolder { public: uint32_t counter; void callback(test_rclcpp::msg::UInt32::ConstSharedPtr msg) { ++counter; ASSERT_EQ(counter, msg->data); } CallbackHolder() : counter(0) {} }; // Shortened version of the test for the ConstSharedPtr callback signature in a method TEST(CLASSNAME(test_subscription, RMW_IMPLEMENTATION), subscription_shared_ptr_const_method_std_function) { CallbackHolder cb_holder; auto node = rclcpp::Node::make_shared("test_subscription"); auto publisher = node->create_publisher<test_rclcpp::msg::UInt32>( "test_subscription", rmw_qos_profile_default); std::function<void(test_rclcpp::msg::UInt32::ConstSharedPtr)> cb_std_function = std::bind( &CallbackHolder::callback, &cb_holder, std::placeholders::_1); auto msg = std::make_shared<test_rclcpp::msg::UInt32>(); msg->data = 0; rclcpp::executors::SingleThreadedExecutor executor; auto subscriber = node->create_subscription<test_rclcpp::msg::UInt32>( "test_subscription", cb_std_function, rmw_qos_profile_default); // wait a moment for everything to initialize // TODO(gerkey): fix nondeterministic startup behavior rclcpp::utilities::sleep_for(1_ms); // start condition ASSERT_EQ(0, cb_holder.counter); // nothing should be pending here executor.spin_node_some(node); ASSERT_EQ(0, cb_holder.counter); msg->data = 1; // Create a ConstSharedPtr message to publish test_rclcpp::msg::UInt32::ConstSharedPtr const_msg(msg); publisher->publish(const_msg); ASSERT_EQ(0, cb_holder.counter); // wait for the first callback printf("spin_node_some() - callback (1) expected\n"); executor.spin_node_some(node); // spin for up to 2s int loop = 0; while ((cb_holder.counter != 1) && (loop++ < max_loops)) { printf("callback not called, sleeping and trying again\n"); std::this_thread::sleep_for(sleep_per_loop); executor.spin_node_some(node); } ASSERT_EQ(1, cb_holder.counter); } // Shortened version of the test for the ConstSharedPtr callback signature in a method TEST(CLASSNAME(test_subscription, RMW_IMPLEMENTATION), subscription_shared_ptr_const_method_direct) { CallbackHolder cb_holder; auto node = rclcpp::Node::make_shared("test_subscription"); auto publisher = node->create_publisher<test_rclcpp::msg::UInt32>( "test_subscription", rmw_qos_profile_default); auto msg = std::make_shared<test_rclcpp::msg::UInt32>(); msg->data = 0; rclcpp::executors::SingleThreadedExecutor executor; auto subscriber = node->create_subscription<test_rclcpp::msg::UInt32>( "test_subscription", std::bind(&CallbackHolder::callback, &cb_holder, std::placeholders::_1), rmw_qos_profile_default); // wait a moment for everything to initialize // TODO(gerkey): fix nondeterministic startup behavior rclcpp::utilities::sleep_for(1_ms); // start condition ASSERT_EQ(0, cb_holder.counter); // nothing should be pending here executor.spin_node_some(node); ASSERT_EQ(0, cb_holder.counter); msg->data = 1; // Create a ConstSharedPtr message to publish test_rclcpp::msg::UInt32::ConstSharedPtr const_msg(msg); publisher->publish(const_msg); ASSERT_EQ(0, cb_holder.counter); // wait for the first callback printf("spin_node_some() - callback (1) expected\n"); executor.spin_node_some(node); // spin for up to 2s int loop = 0; while ((cb_holder.counter != 1) && (loop++ < max_loops)) { printf("callback not called, sleeping and trying again\n"); std::this_thread::sleep_for(std::chrono::milliseconds(sleep_per_loop)); executor.spin_node_some(node); } ASSERT_EQ(1, cb_holder.counter); } // Shortened version of the test for the ConstSharedPtr with info callback signature TEST(CLASSNAME(test_subscription, RMW_IMPLEMENTATION), subscription_shared_ptr_const_with_info) { auto node = rclcpp::Node::make_shared("test_subscription"); auto publisher = node->create_publisher<test_rclcpp::msg::UInt32>( "test_subscription", rmw_qos_profile_default); uint32_t counter = 0; auto callback = [&counter](test_rclcpp::msg::UInt32::ConstSharedPtr msg, const rmw_message_info_t & info) -> void { ++counter; printf(" callback() %4u with message data %u\n", counter, msg->data); ASSERT_EQ(counter, msg->data); ASSERT_FALSE(info.from_intra_process); }; auto msg = std::make_shared<test_rclcpp::msg::UInt32>(); msg->data = 0; rclcpp::executors::SingleThreadedExecutor executor; auto subscriber = node->create_subscription<test_rclcpp::msg::UInt32>( "test_subscription", callback, rmw_qos_profile_default); // wait a moment for everything to initialize // TODO(gerkey): fix nondeterministic startup behavior rclcpp::utilities::sleep_for(1_ms); // start condition ASSERT_EQ(0, counter); // nothing should be pending here executor.spin_node_some(node); ASSERT_EQ(0, counter); msg->data = 1; publisher->publish(msg); ASSERT_EQ(0, counter); // wait for the first callback printf("spin_node_some() - callback (1) expected\n"); executor.spin_node_some(node); // spin for up to 2s int loop = 0; while ((counter != 1) && (loop++ < max_loops)) { printf("callback not called, sleeping and trying again\n"); std::this_thread::sleep_for(sleep_per_loop); executor.spin_node_some(node); } ASSERT_EQ(1, counter); } // Shortened version of the test for subscribing after spinning has started. TEST(CLASSNAME(test_subscription, RMW_IMPLEMENTATION), spin_before_subscription) { auto node = rclcpp::Node::make_shared("test_subscription"); auto publisher = node->create_publisher<test_rclcpp::msg::UInt32>( "test_subscription", rmw_qos_profile_default); uint32_t counter = 0; auto callback = [&counter](test_rclcpp::msg::UInt32::ConstSharedPtr msg) -> void { ++counter; printf(" callback() %4u with message data %u\n", counter, msg->data); ASSERT_EQ(counter, msg->data); }; auto msg = std::make_shared<test_rclcpp::msg::UInt32>(); msg->data = 0; rclcpp::executors::SingleThreadedExecutor executor; executor.add_node(node); std::thread executor_thread(std::bind(&rclcpp::executors::SingleThreadedExecutor::spin, &executor)); auto subscriber = node->create_subscription<test_rclcpp::msg::UInt32>( "test_subscription", callback, rmw_qos_profile_default); // start condition ASSERT_EQ(0, counter); msg->data = 1; // Create a ConstSharedPtr message to publish test_rclcpp::msg::UInt32::ConstSharedPtr const_msg(msg); publisher->publish(const_msg); // wait for the first callback printf("callback (1) expected\n"); std::this_thread::sleep_for(std::chrono::seconds(1)); ASSERT_EQ(1, counter); executor.cancel(); executor_thread.join(); } // Test of the queue size create_subscription signature. TEST(CLASSNAME(test_subscription, RMW_IMPLEMENTATION), create_subscription_with_queue_size) { auto node = rclcpp::Node::make_shared("test_subscription"); // *INDENT-OFF* auto callback = [](test_rclcpp::msg::UInt32::ConstSharedPtr) -> void {}; // *INDENT-ON* auto subscriber = node->create_subscription<test_rclcpp::msg::UInt32>( "test_subscription", 10, callback); }
test case for spinning before creating subscription
test case for spinning before creating subscription
C++
apache-2.0
ros2/system_tests,ros2/system_tests
ac8a1b75428a9fdff58d61d30044172a430123f6
karmaplugin.cpp
karmaplugin.cpp
/** * Copyright (c) Sjors Gielen, 2011-2012 * See LICENSE for license. */ #include <QtCore/QList> #include <QtCore/QDebug> #include <QtCore/QCoreApplication> #include "karmaplugin.h" int main(int argc, char *argv[]) { if(argc < 2) { qWarning() << "Usage: dazeus-plugin-karma socketfile"; return 1; } QString socketfile = argv[1]; QCoreApplication app(argc, argv); KarmaPlugin kp(socketfile); return app.exec(); } KarmaPlugin::KarmaPlugin(const QString &socketfile) : QObject() , d(new DaZeus()) { if(!d->open(socketfile) || !d->subscribe("PRIVMSG")) { qWarning() << d->error(); delete d; d = 0; return; } connect(d, SIGNAL(newEvent(DaZeus::Event*)), this, SLOT( newEvent(DaZeus::Event*))); connect(d, SIGNAL(connectionFailed()), this, SLOT( connectionFailed())); } KarmaPlugin::~KarmaPlugin() { delete d; } void KarmaPlugin::connectionFailed() { // TODO: handle this better qWarning() << "Error: connection failed: " << d->error(); delete d; d = 0; QCoreApplication::exit(1); } int KarmaPlugin::modifyKarma(const QString &network, const QString &object, bool increase) { DaZeus::Scope s(network); DaZeus::Scope g; QString qualifiedName = QLatin1String("perl.DazKarma.karma_") + object; int current = d->getProperty(qualifiedName, s).toInt(); if(current == 0 && !d->error().isNull()) { qWarning() << "Could not getProperty(): " << d->error(); } if(increase) ++current; else --current; bool res; if(current == 0) { res = d->unsetProperty(qualifiedName, s); // Also unset global property, in case one is left behind if(res) res = d->unsetProperty(qualifiedName, g); } else { res = d->setProperty(qualifiedName, QString::number(current), s); } if(!res) { qWarning() << "Could not (un)setProperty(): " << d->error(); } return current; } void KarmaPlugin::newEvent(DaZeus::Event *e) { if(e->event != "PRIVMSG") return; if(e->parameters.size() < 4) { qWarning() << "Incorrect parameter size for message received"; return; } QString network = e->parameters[0]; QString origin = e->parameters[1]; QString recv = e->parameters[2]; QString message = e->parameters[3]; DaZeus::Scope s(network); // TODO: use getNick() if(!recv.startsWith('#')) { // reply to PM recv = origin; } if(message.startsWith("}karma ")) { QString object = message.mid(7).trimmed(); int current = d->getProperty("perl.DazKarma.karma_" + object, s).toInt(); bool res; if(current == 0) { if(!d->error().isNull()) { qWarning() << "Failed to fetch karma: " << d->error(); } res = d->message(network, recv, object + " has neutral karma."); } else { res = d->message(network, recv, object + " has a karma of " + QString::number(current) + "."); } if(!res) { qWarning() << "Failed to send message: " << d->error(); } return; } // Walk through the message searching for -- and ++; upon finding // either, reconstruct what the object was. // Start searching from i=1 because a string starting with -- or // ++ means nothing anyway, and now we can always ask for b[i-1] // End search at one character from the end so we can always ask // for b[i+1] QList<int> hits; int len = message.length(); for(int i = 1; i < (len - 1); ++i) { bool wordEnd = i == len - 2 || message[i+2].isSpace(); if( message[i] == QLatin1Char('-') && message[i+1] == QLatin1Char('-') && wordEnd ) { hits.append(i); } else if( message[i] == QLatin1Char('+') && message[i+1] == QLatin1Char('+') && wordEnd ) { hits.append(i); } } QListIterator<int> i(hits); while(i.hasNext()) { int pos = i.next(); bool isIncrease = message[pos] == QLatin1Char('+'); QString object; int newVal; if(message[pos-1].isLetter()) { // only alphanumerics between startPos and pos-1 int startPos = pos - 1; for(; startPos >= 0; --startPos) { if(!message[startPos].isLetter() && !message[startPos].isDigit() && message[startPos] != QLatin1Char('-') && message[startPos] != QLatin1Char('_')) { // revert the negation startPos++; break; } } if(startPos > 0 && !message[startPos-1].isSpace()) { // non-alphanumerics would be in this object, ignore it continue; } object = message.mid(startPos, pos - startPos); newVal = modifyKarma(network, object, isIncrease); qDebug() << origin << (isIncrease ? "increased" : "decreased") << "karma of" << object << "to" << QString::number(newVal); continue; } char beginner; char ender; if(message[pos-1] == QLatin1Char(']')) { beginner = '['; ender = ']'; } else if(message[pos-1] == QLatin1Char(')')) { beginner = '('; ender = ')'; } else { continue; } // find the last $beginner before $ender int startPos = message.lastIndexOf(QLatin1Char(beginner), pos); // unless there's already an $ender between them if(message.indexOf(QLatin1Char(ender), startPos) < pos - 1) continue; object = message.mid(startPos + 1, pos - 2 - startPos); newVal = modifyKarma(network, object, isIncrease); QString message = origin + QLatin1String(isIncrease ? " increased" : " decreased") + QLatin1String(" karma of ") + object + QLatin1String(" to ") + QString::number(newVal) + QLatin1Char('.'); qDebug() << message; if(ender == ']') { // Verbose mode, print the result if(!d->message(network, recv, message)) { qWarning() << "Failed to send message: " << d->error(); } } } }
/** * Copyright (c) Sjors Gielen, 2011-2012 * See LICENSE for license. */ #include <QtCore/QList> #include <QtCore/QDebug> #include <QtCore/QCoreApplication> #include "karmaplugin.h" int main(int argc, char *argv[]) { if(argc < 2) { qWarning() << "Usage: dazeus-plugin-karma socketfile"; return 1; } QString socketfile = argv[1]; QCoreApplication app(argc, argv); KarmaPlugin kp(socketfile); return app.exec(); } KarmaPlugin::KarmaPlugin(const QString &socketfile) : QObject() , d(new DaZeus()) { if(!d->open(socketfile) || !d->subscribe("PRIVMSG")) { qWarning() << d->error(); delete d; d = 0; return; } connect(d, SIGNAL(newEvent(DaZeus::Event*)), this, SLOT( newEvent(DaZeus::Event*))); connect(d, SIGNAL(connectionFailed()), this, SLOT( connectionFailed())); } KarmaPlugin::~KarmaPlugin() { delete d; } void KarmaPlugin::connectionFailed() { // TODO: handle this better qWarning() << "Error: connection failed: " << d->error(); delete d; d = 0; QCoreApplication::exit(1); } int KarmaPlugin::modifyKarma(const QString &network, const QString &object, bool increase) { DaZeus::Scope s(network); DaZeus::Scope g; QString qualifiedName = QLatin1String("perl.DazKarma.karma_") + object.toLower(); int current = d->getProperty(qualifiedName, s).toInt(); if(current == 0 && !d->error().isNull()) { qWarning() << "Could not getProperty(): " << d->error(); } if(increase) ++current; else --current; bool res; if(current == 0) { res = d->unsetProperty(qualifiedName, s); // Also unset global property, in case one is left behind if(res) res = d->unsetProperty(qualifiedName, g); } else { res = d->setProperty(qualifiedName, QString::number(current), s); } if(!res) { qWarning() << "Could not (un)setProperty(): " << d->error(); } return current; } void KarmaPlugin::newEvent(DaZeus::Event *e) { if(e->event != "PRIVMSG") return; if(e->parameters.size() < 4) { qWarning() << "Incorrect parameter size for message received"; return; } QString network = e->parameters[0]; QString origin = e->parameters[1]; QString recv = e->parameters[2]; QString message = e->parameters[3]; DaZeus::Scope s(network); // TODO: use getNick() if(!recv.startsWith('#')) { // reply to PM recv = origin; } if(message.startsWith("}karma ")) { QString object = message.mid(7).trimmed(); int current = d->getProperty("perl.DazKarma.karma_" + object.toLower(), s).toInt(); bool res; if(current == 0) { if(!d->error().isNull()) { qWarning() << "Failed to fetch karma: " << d->error(); } res = d->message(network, recv, object + " has neutral karma."); } else { res = d->message(network, recv, object + " has a karma of " + QString::number(current) + "."); } if(!res) { qWarning() << "Failed to send message: " << d->error(); } return; } // Walk through the message searching for -- and ++; upon finding // either, reconstruct what the object was. // Start searching from i=1 because a string starting with -- or // ++ means nothing anyway, and now we can always ask for b[i-1] // End search at one character from the end so we can always ask // for b[i+1] QList<int> hits; int len = message.length(); for(int i = 1; i < (len - 1); ++i) { bool wordEnd = i == len - 2 || message[i+2].isSpace(); if( message[i] == QLatin1Char('-') && message[i+1] == QLatin1Char('-') && wordEnd ) { hits.append(i); } else if( message[i] == QLatin1Char('+') && message[i+1] == QLatin1Char('+') && wordEnd ) { hits.append(i); } } QListIterator<int> i(hits); while(i.hasNext()) { int pos = i.next(); bool isIncrease = message[pos] == QLatin1Char('+'); QString object; int newVal; if(message[pos-1].isLetter()) { // only alphanumerics between startPos and pos-1 int startPos = pos - 1; for(; startPos >= 0; --startPos) { if(!message[startPos].isLetter() && !message[startPos].isDigit() && message[startPos] != QLatin1Char('-') && message[startPos] != QLatin1Char('_')) { // revert the negation startPos++; break; } } if(startPos > 0 && !message[startPos-1].isSpace()) { // non-alphanumerics would be in this object, ignore it continue; } object = message.mid(startPos, pos - startPos); newVal = modifyKarma(network, object, isIncrease); qDebug() << origin << (isIncrease ? "increased" : "decreased") << "karma of" << object << "to" << QString::number(newVal); continue; } char beginner; char ender; if(message[pos-1] == QLatin1Char(']')) { beginner = '['; ender = ']'; } else if(message[pos-1] == QLatin1Char(')')) { beginner = '('; ender = ')'; } else { continue; } // find the last $beginner before $ender int startPos = message.lastIndexOf(QLatin1Char(beginner), pos); // unless there's already an $ender between them if(message.indexOf(QLatin1Char(ender), startPos) < pos - 1) continue; object = message.mid(startPos + 1, pos - 2 - startPos); newVal = modifyKarma(network, object, isIncrease); QString message = origin + QLatin1String(isIncrease ? " increased" : " decreased") + QLatin1String(" karma of ") + object + QLatin1String(" to ") + QString::number(newVal) + QLatin1Char('.'); qDebug() << message; if(ender == ']') { // Verbose mode, print the result if(!d->message(network, recv, message)) { qWarning() << "Failed to send message: " << d->error(); } } } }
Implement case insensitivity for karma objects
Implement case insensitivity for karma objects
C++
mit
dazeus/dazeus-plugin-karma,dazeus/dazeus-plugin-karma,dazeus/dazeus-plugin-karma
d3b8934c64526b7659dfb1a68869654f86664962
tests/concurrency/transaction_test.cpp
tests/concurrency/transaction_test.cpp
//===----------------------------------------------------------------------===// // // PelotonDB // // transaction_test.cpp // // Identification: tests/concurrency/transaction_test.cpp // // Copyright (c) 2015, Carnegie Mellon University Database Group // //===----------------------------------------------------------------------===// #include "harness.h" #include "concurrency/transaction_tests_util.h" namespace peloton { namespace test { //===--------------------------------------------------------------------===// // Transaction Tests //===--------------------------------------------------------------------===// class TransactionTests : public PelotonTest {}; #define TEST_TYPE CONCURRENCY_TYPE_2PL void TransactionTest(concurrency::TransactionManager *txn_manager) { uint64_t thread_id = TestingHarness::GetInstance().GetThreadId(); for (oid_t txn_itr = 1; txn_itr <= 50; txn_itr++) { txn_manager->BeginTransaction(); if (thread_id % 2 == 0) { std::chrono::microseconds sleep_time(1); std::this_thread::sleep_for(sleep_time); } if (txn_itr % 25 != 0) { txn_manager->CommitTransaction(); } else { txn_manager->AbortTransaction(); } } } void DirtyWriteTest() { auto &txn_manager = concurrency::TransactionManagerFactory::GetInstance(TEST_TYPE); std::unique_ptr<storage::DataTable> table( TransactionTestsUtil::CreateTable()); { TransactionScheduler scheduler(2, table.get(), &txn_manager); // T1 updates (0, ?) to (0, 1) // T2 updates (0, ?) to (0, 2) // T1 commits // T2 commits scheduler.AddUpdate(0, 0, 1); scheduler.AddUpdate(1, 0, 2); scheduler.AddCommit(0); scheduler.AddCommit(1); scheduler.Run(); auto &schedules = scheduler.schedules; // T1 and T2 can't both succeed EXPECT_FALSE(schedules[0].txn_result == RESULT_SUCCESS && schedules[1].txn_result == RESULT_SUCCESS); // For MVCC, actually one and only one T should succeed? EXPECT_TRUE((schedules[0].txn_result == RESULT_SUCCESS && schedules[1].txn_result == RESULT_ABORTED) || (schedules[0].txn_result == RESULT_ABORTED && schedules[1].txn_result == RESULT_SUCCESS)); schedules.clear(); } { TransactionScheduler scheduler(2, table.get(), &txn_manager); scheduler.AddUpdate(0, 0, 1); scheduler.AddUpdate(1, 0, 2); scheduler.AddCommit(1); scheduler.AddCommit(0); scheduler.Run(); auto &schedules = scheduler.schedules; // T1 and T2 can't both succeed EXPECT_FALSE(schedules[0].txn_result == RESULT_SUCCESS && schedules[1].txn_result == RESULT_SUCCESS); // For MVCC, actually one and only one T should succeed? EXPECT_TRUE((schedules[0].txn_result == RESULT_SUCCESS && schedules[1].txn_result == RESULT_ABORTED) || (schedules[0].txn_result == RESULT_ABORTED && schedules[1].txn_result == RESULT_SUCCESS)); } { TransactionScheduler scheduler(2, table.get(), &txn_manager); // T0 delete (0, ?) // T1 update (0, ?) to (0, 3) // T0 commit // T1 commit scheduler.AddDelete(0, 0); scheduler.AddUpdate(1, 0, 3); scheduler.AddCommit(0); scheduler.AddCommit(1); scheduler.Run(); auto &schedules = scheduler.schedules; // T1 and T2 can't both succeed EXPECT_FALSE(schedules[0].txn_result == RESULT_SUCCESS && schedules[1].txn_result == RESULT_SUCCESS); // For MVCC, actually one and only one T should succeed? EXPECT_TRUE((schedules[0].txn_result == RESULT_SUCCESS && schedules[1].txn_result == RESULT_ABORTED) || (schedules[0].txn_result == RESULT_ABORTED && schedules[1].txn_result == RESULT_SUCCESS)); schedules.clear(); } { TransactionScheduler scheduler(2, table.get(), &txn_manager); // T0 delete (1, ?) // T1 delete (1, ?) // T0 commit // T1 commit scheduler.AddDelete(0, 1); scheduler.AddDelete(1, 1); scheduler.AddCommit(0); scheduler.AddCommit(1); scheduler.Run(); auto &schedules = scheduler.schedules; // T1 and T2 can't both succeed EXPECT_FALSE(schedules[0].txn_result == RESULT_SUCCESS && schedules[1].txn_result == RESULT_SUCCESS); // For MVCC, actually one and only one T should succeed? EXPECT_TRUE((schedules[0].txn_result == RESULT_SUCCESS && schedules[1].txn_result == RESULT_ABORTED) || (schedules[0].txn_result == RESULT_ABORTED && schedules[1].txn_result == RESULT_SUCCESS)); schedules.clear(); } } void DirtyReadTest() { auto &txn_manager = concurrency::TransactionManagerFactory::GetInstance(TEST_TYPE); std::unique_ptr<storage::DataTable> table( TransactionTestsUtil::CreateTable()); { TransactionScheduler scheduler(2, table.get(), &txn_manager); // T1 updates (0, ?) to (0, 1) // T2 reads (0, ?) // T1 commit // T2 commit scheduler.AddUpdate(0, 0, 1); scheduler.AddRead(1, 0); scheduler.AddCommit(0); scheduler.AddCommit(1); scheduler.Run(); EXPECT_EQ(RESULT_SUCCESS, scheduler.schedules[0].txn_result); EXPECT_EQ(RESULT_ABORTED, scheduler.schedules[1].txn_result); } { TransactionScheduler scheduler(2, table.get(), &txn_manager); // T1 updates (0, ?) to (0, 1) // T2 reads (0, ?) // T2 commit // T1 commit scheduler.AddUpdate(0, 0, 1); scheduler.AddRead(1, 0); scheduler.AddCommit(1); scheduler.AddCommit(0); scheduler.Run(); EXPECT_EQ(RESULT_SUCCESS, scheduler.schedules[0].txn_result); EXPECT_EQ(RESULT_ABORTED, scheduler.schedules[1].txn_result); } { TransactionScheduler scheduler(2, table.get(), &txn_manager); // T0 delete (0, ?) // T1 read (0, ?) // T0 commit // T1 commit scheduler.AddDelete(0, 0); scheduler.AddRead(1, 0); scheduler.AddCommit(0); scheduler.AddCommit(1); scheduler.Run(); EXPECT_EQ(RESULT_SUCCESS, scheduler.schedules[0].txn_result); EXPECT_EQ(RESULT_ABORTED, scheduler.schedules[1].txn_result); } } void FuzzyReadTest() { auto &txn_manager = concurrency::TransactionManagerFactory::GetInstance(TEST_TYPE); std::unique_ptr<storage::DataTable> table( TransactionTestsUtil::CreateTable()); { // T0 read 0 // T1 update (0, 0) to (0, 1) // T1 commit // T0 commit TransactionScheduler scheduler(2, table.get(), &txn_manager); scheduler.AddRead(0, 0); scheduler.AddUpdate(1, 0, 1); scheduler.AddCommit(1); scheduler.AddCommit(0); scheduler.Run(); EXPECT_EQ(RESULT_ABORTED, scheduler.schedules[0].txn_result); EXPECT_EQ(RESULT_SUCCESS, scheduler.schedules[1].txn_result); } { // T0 read 0 // T1 update (0, 0) to (0, 1) // T0 commit // T1 commit TransactionScheduler scheduler(2, table.get(), &txn_manager); scheduler.AddRead(0, 0); scheduler.AddUpdate(1, 0, 1); scheduler.AddCommit(0); scheduler.AddCommit(1); scheduler.Run(); EXPECT_EQ(RESULT_ABORTED, scheduler.schedules[0].txn_result); EXPECT_EQ(RESULT_SUCCESS, scheduler.schedules[1].txn_result); } { // T0 read 0 // T1 delete 0 // T0 commit // T1 commit TransactionScheduler scheduler(2, table.get(), &txn_manager); scheduler.AddRead(0, 0); scheduler.AddDelete(1, 0); scheduler.AddCommit(0); scheduler.AddCommit(1); scheduler.Run(); EXPECT_EQ(RESULT_ABORTED, scheduler.schedules[0].txn_result); EXPECT_EQ(RESULT_SUCCESS, scheduler.schedules[1].txn_result); } } void PhantomTest() { auto &txn_manager = concurrency::TransactionManagerFactory::GetInstance(TEST_TYPE); std::unique_ptr<storage::DataTable> table( TransactionTestsUtil::CreateTable()); { TransactionScheduler scheduler(2, table.get(), &txn_manager); scheduler.AddScan(0, 0); scheduler.AddInsert(1, 5, 0); scheduler.AddCommit(1); scheduler.AddCommit(0); scheduler.Run(); EXPECT_EQ(RESULT_ABORTED, scheduler.schedules[0].txn_result); EXPECT_EQ(RESULT_SUCCESS, scheduler.schedules[1].txn_result); } { TransactionScheduler scheduler(2, table.get(), &txn_manager); scheduler.AddScan(0, 0); scheduler.AddDelete(1, 4); scheduler.AddCommit(1); scheduler.AddCommit(0); scheduler.Run(); EXPECT_EQ(RESULT_ABORTED, scheduler.schedules[0].txn_result); EXPECT_EQ(RESULT_SUCCESS, scheduler.schedules[1].txn_result); } } void WriteSkewTest() { auto &txn_manager = concurrency::TransactionManagerFactory::GetInstance(TEST_TYPE); std::unique_ptr<storage::DataTable> table( TransactionTestsUtil::CreateTable()); { TransactionScheduler scheduler(2, table.get(), &txn_manager); scheduler.AddRead(0, 0); scheduler.AddUpdate(0, 1, 1); scheduler.AddRead(1, 0); scheduler.AddUpdate(1, 1, 2); scheduler.AddCommit(0); scheduler.AddCommit(1); scheduler.Run(); // Can't all success EXPECT_FALSE(RESULT_SUCCESS == scheduler.schedules[0].txn_result && RESULT_SUCCESS == scheduler.schedules[1].txn_result); } { TransactionScheduler scheduler(2, table.get(), &txn_manager); scheduler.AddRead(0, 0); scheduler.AddUpdate(0, 1, 1); scheduler.AddRead(1, 0); scheduler.AddCommit(0); scheduler.AddUpdate(1, 1, 2); scheduler.AddCommit(1); scheduler.Run(); // First txn should success EXPECT_TRUE(RESULT_SUCCESS == scheduler.schedules[0].txn_result && RESULT_ABORTED == scheduler.schedules[1].txn_result); } } void ReadSkewTest() { auto &txn_manager = concurrency::TransactionManagerFactory::GetInstance(TEST_TYPE); std::unique_ptr<storage::DataTable> table( TransactionTestsUtil::CreateTable()); { TransactionScheduler scheduler(2, table.get(), &txn_manager); scheduler.AddRead(0, 0); scheduler.AddUpdate(1, 0, 1); scheduler.AddUpdate(1, 1, 1); scheduler.AddCommit(1); scheduler.AddRead(0, 1); scheduler.AddCommit(0); scheduler.Run(); EXPECT_EQ(RESULT_ABORTED, scheduler.schedules[0].txn_result); EXPECT_EQ(RESULT_SUCCESS, scheduler.schedules[1].txn_result); } } TEST_F(TransactionTests, TransactionTest) { auto &txn_manager = concurrency::TransactionManagerFactory::GetInstance(TEST_TYPE); LaunchParallelTest(8, TransactionTest, &txn_manager); std::cout << "next Commit Id :: " << txn_manager.GetNextCommitId() << "\n"; } TEST_F(TransactionTests, AbortTest) { auto &txn_manager = concurrency::TransactionManagerFactory::GetInstance(TEST_TYPE); std::unique_ptr<storage::DataTable> table( TransactionTestsUtil::CreateTable()); TransactionScheduler scheduler(2, table.get(), &txn_manager); scheduler.AddUpdate(0, 0, 100); scheduler.AddRead(1, 0); scheduler.AddAbort(0); scheduler.AddCommit(1); scheduler.Run(); EXPECT_EQ(RESULT_ABORTED, scheduler.schedules[0].txn_result); EXPECT_EQ(RESULT_SUCCESS, scheduler.schedules[1].txn_result); } TEST_F(TransactionTests, SerializableTest) { DirtyWriteTest(); DirtyReadTest(); FuzzyReadTest(); WriteSkewTest(); ReadSkewTest(); // PhantomTes(); } } // End test namespace } // End peloton namespace
//===----------------------------------------------------------------------===// // // PelotonDB // // transaction_test.cpp // // Identification: tests/concurrency/transaction_test.cpp // // Copyright (c) 2015, Carnegie Mellon University Database Group // //===----------------------------------------------------------------------===// #include "harness.h" #include "concurrency/transaction_tests_util.h" namespace peloton { namespace test { //===--------------------------------------------------------------------===// // Transaction Tests //===--------------------------------------------------------------------===// class TransactionTests : public PelotonTest {}; #define TEST_TYPE CONCURRENCY_TYPE_2PL void TransactionTest(concurrency::TransactionManager *txn_manager) { uint64_t thread_id = TestingHarness::GetInstance().GetThreadId(); for (oid_t txn_itr = 1; txn_itr <= 50; txn_itr++) { txn_manager->BeginTransaction(); if (thread_id % 2 == 0) { std::chrono::microseconds sleep_time(1); std::this_thread::sleep_for(sleep_time); } if (txn_itr % 25 != 0) { txn_manager->CommitTransaction(); } else { txn_manager->AbortTransaction(); } } } void DirtyWriteTest() { auto &txn_manager = concurrency::TransactionManagerFactory::GetInstance(TEST_TYPE); std::unique_ptr<storage::DataTable> table( TransactionTestsUtil::CreateTable()); { TransactionScheduler scheduler(2, table.get(), &txn_manager); // T1 updates (0, ?) to (0, 1) // T2 updates (0, ?) to (0, 2) // T1 commits // T2 commits scheduler.AddUpdate(0, 0, 1); scheduler.AddUpdate(1, 0, 2); scheduler.AddCommit(0); scheduler.AddCommit(1); scheduler.Run(); auto &schedules = scheduler.schedules; // T1 and T2 can't both succeed EXPECT_FALSE(schedules[0].txn_result == RESULT_SUCCESS && schedules[1].txn_result == RESULT_SUCCESS); // For MVCC, actually one and only one T should succeed? EXPECT_TRUE((schedules[0].txn_result == RESULT_SUCCESS && schedules[1].txn_result == RESULT_ABORTED) || (schedules[0].txn_result == RESULT_ABORTED && schedules[1].txn_result == RESULT_SUCCESS)); schedules.clear(); } { TransactionScheduler scheduler(2, table.get(), &txn_manager); scheduler.AddUpdate(0, 0, 1); scheduler.AddUpdate(1, 0, 2); scheduler.AddCommit(1); scheduler.AddCommit(0); scheduler.Run(); auto &schedules = scheduler.schedules; // T1 and T2 can't both succeed EXPECT_FALSE(schedules[0].txn_result == RESULT_SUCCESS && schedules[1].txn_result == RESULT_SUCCESS); // For MVCC, actually one and only one T should succeed? EXPECT_TRUE((schedules[0].txn_result == RESULT_SUCCESS && schedules[1].txn_result == RESULT_ABORTED) || (schedules[0].txn_result == RESULT_ABORTED && schedules[1].txn_result == RESULT_SUCCESS)); } { TransactionScheduler scheduler(2, table.get(), &txn_manager); // T0 delete (0, ?) // T1 update (0, ?) to (0, 3) // T0 commit // T1 commit scheduler.AddDelete(0, 0); scheduler.AddUpdate(1, 0, 3); scheduler.AddCommit(0); scheduler.AddCommit(1); scheduler.Run(); auto &schedules = scheduler.schedules; // T1 and T2 can't both succeed EXPECT_FALSE(schedules[0].txn_result == RESULT_SUCCESS && schedules[1].txn_result == RESULT_SUCCESS); // For MVCC, actually one and only one T should succeed? EXPECT_TRUE((schedules[0].txn_result == RESULT_SUCCESS && schedules[1].txn_result == RESULT_ABORTED) || (schedules[0].txn_result == RESULT_ABORTED && schedules[1].txn_result == RESULT_SUCCESS)); schedules.clear(); } { TransactionScheduler scheduler(2, table.get(), &txn_manager); // T0 delete (1, ?) // T1 delete (1, ?) // T0 commit // T1 commit scheduler.AddDelete(0, 1); scheduler.AddDelete(1, 1); scheduler.AddCommit(0); scheduler.AddCommit(1); scheduler.Run(); auto &schedules = scheduler.schedules; // T1 and T2 can't both succeed EXPECT_FALSE(schedules[0].txn_result == RESULT_SUCCESS && schedules[1].txn_result == RESULT_SUCCESS); // For MVCC, actually one and only one T should succeed? EXPECT_TRUE((schedules[0].txn_result == RESULT_SUCCESS && schedules[1].txn_result == RESULT_ABORTED) || (schedules[0].txn_result == RESULT_ABORTED && schedules[1].txn_result == RESULT_SUCCESS)); schedules.clear(); } } void DirtyReadTest() { auto &txn_manager = concurrency::TransactionManagerFactory::GetInstance(TEST_TYPE); std::unique_ptr<storage::DataTable> table( TransactionTestsUtil::CreateTable()); { TransactionScheduler scheduler(2, table.get(), &txn_manager); // T1 updates (0, ?) to (0, 1) // T2 reads (0, ?) // T1 commit // T2 commit scheduler.AddUpdate(0, 0, 1); scheduler.AddRead(1, 0); scheduler.AddCommit(0); scheduler.AddCommit(1); scheduler.Run(); EXPECT_EQ(RESULT_SUCCESS, scheduler.schedules[0].txn_result); EXPECT_EQ(RESULT_ABORTED, scheduler.schedules[1].txn_result); } { TransactionScheduler scheduler(2, table.get(), &txn_manager); // T1 updates (0, ?) to (0, 1) // T2 reads (0, ?) // T2 commit // T1 commit scheduler.AddUpdate(0, 0, 1); scheduler.AddRead(1, 0); scheduler.AddCommit(1); scheduler.AddCommit(0); scheduler.Run(); EXPECT_EQ(RESULT_SUCCESS, scheduler.schedules[0].txn_result); EXPECT_EQ(RESULT_ABORTED, scheduler.schedules[1].txn_result); } { TransactionScheduler scheduler(2, table.get(), &txn_manager); // T0 delete (0, ?) // T1 read (0, ?) // T0 commit // T1 commit scheduler.AddDelete(0, 0); scheduler.AddRead(1, 0); scheduler.AddCommit(0); scheduler.AddCommit(1); scheduler.Run(); EXPECT_EQ(RESULT_SUCCESS, scheduler.schedules[0].txn_result); EXPECT_EQ(RESULT_ABORTED, scheduler.schedules[1].txn_result); } } void FuzzyReadTest() { auto &txn_manager = concurrency::TransactionManagerFactory::GetInstance(TEST_TYPE); std::unique_ptr<storage::DataTable> table( TransactionTestsUtil::CreateTable()); { // T0 read 0 // T1 update (0, 0) to (0, 1) // T1 commit // T0 commit TransactionScheduler scheduler(2, table.get(), &txn_manager); scheduler.AddRead(0, 0); scheduler.AddUpdate(1, 0, 1); scheduler.AddCommit(1); scheduler.AddCommit(0); scheduler.Run(); EXPECT_EQ(RESULT_ABORTED, scheduler.schedules[0].txn_result); EXPECT_EQ(RESULT_SUCCESS, scheduler.schedules[1].txn_result); } { // T0 read 0 // T1 update (0, 0) to (0, 1) // T0 commit // T1 commit TransactionScheduler scheduler(2, table.get(), &txn_manager); scheduler.AddRead(0, 0); scheduler.AddUpdate(1, 0, 1); scheduler.AddCommit(0); scheduler.AddCommit(1); scheduler.Run(); EXPECT_EQ(RESULT_ABORTED, scheduler.schedules[0].txn_result); EXPECT_EQ(RESULT_SUCCESS, scheduler.schedules[1].txn_result); } { // T0 read 0 // T1 delete 0 // T0 commit // T1 commit TransactionScheduler scheduler(2, table.get(), &txn_manager); scheduler.AddRead(0, 0); scheduler.AddDelete(1, 0); scheduler.AddCommit(0); scheduler.AddCommit(1); scheduler.Run(); EXPECT_EQ(RESULT_ABORTED, scheduler.schedules[0].txn_result); EXPECT_EQ(RESULT_SUCCESS, scheduler.schedules[1].txn_result); } } void PhantomTest() { auto &txn_manager = concurrency::TransactionManagerFactory::GetInstance(TEST_TYPE); std::unique_ptr<storage::DataTable> table( TransactionTestsUtil::CreateTable()); { TransactionScheduler scheduler(2, table.get(), &txn_manager); scheduler.AddScan(0, 0); scheduler.AddInsert(1, 5, 0); scheduler.AddCommit(1); scheduler.AddCommit(0); scheduler.Run(); EXPECT_EQ(RESULT_ABORTED, scheduler.schedules[0].txn_result); EXPECT_EQ(RESULT_SUCCESS, scheduler.schedules[1].txn_result); } { TransactionScheduler scheduler(2, table.get(), &txn_manager); scheduler.AddScan(0, 0); scheduler.AddDelete(1, 4); scheduler.AddCommit(1); scheduler.AddCommit(0); scheduler.Run(); EXPECT_EQ(RESULT_ABORTED, scheduler.schedules[0].txn_result); EXPECT_EQ(RESULT_SUCCESS, scheduler.schedules[1].txn_result); } } void WriteSkewTest() { auto &txn_manager = concurrency::TransactionManagerFactory::GetInstance(TEST_TYPE); std::unique_ptr<storage::DataTable> table( TransactionTestsUtil::CreateTable()); { TransactionScheduler scheduler(2, table.get(), &txn_manager); scheduler.AddRead(0, 0); scheduler.AddUpdate(0, 1, 1); scheduler.AddRead(1, 0); scheduler.AddUpdate(1, 1, 2); scheduler.AddCommit(0); scheduler.AddCommit(1); scheduler.Run(); // Can't all success EXPECT_FALSE(RESULT_SUCCESS == scheduler.schedules[0].txn_result && RESULT_SUCCESS == scheduler.schedules[1].txn_result); } { TransactionScheduler scheduler(2, table.get(), &txn_manager); scheduler.AddRead(0, 0); scheduler.AddUpdate(0, 1, 1); scheduler.AddRead(1, 0); scheduler.AddCommit(0); scheduler.AddUpdate(1, 1, 2); scheduler.AddCommit(1); scheduler.Run(); // First txn should success EXPECT_TRUE(RESULT_SUCCESS == scheduler.schedules[0].txn_result && RESULT_ABORTED == scheduler.schedules[1].txn_result); } } void ReadSkewTest() { auto &txn_manager = concurrency::TransactionManagerFactory::GetInstance(TEST_TYPE); std::unique_ptr<storage::DataTable> table( TransactionTestsUtil::CreateTable()); { TransactionScheduler scheduler(2, table.get(), &txn_manager); scheduler.AddRead(0, 0); scheduler.AddUpdate(1, 0, 1); scheduler.AddUpdate(1, 1, 1); scheduler.AddCommit(1); scheduler.AddRead(0, 1); scheduler.AddCommit(0); scheduler.Run(); EXPECT_EQ(RESULT_ABORTED, scheduler.schedules[0].txn_result); EXPECT_EQ(RESULT_SUCCESS, scheduler.schedules[1].txn_result); } } TEST_F(TransactionTests, TransactionTest) { auto &txn_manager = concurrency::TransactionManagerFactory::GetInstance(TEST_TYPE); LaunchParallelTest(8, TransactionTest, &txn_manager); std::cout << "next Commit Id :: " << txn_manager.GetNextCommitId() << "\n"; } TEST_F(TransactionTests, AbortTest) { auto &txn_manager = concurrency::TransactionManagerFactory::GetInstance(TEST_TYPE); std::unique_ptr<storage::DataTable> table( TransactionTestsUtil::CreateTable()); { TransactionScheduler scheduler(2, table.get(), &txn_manager); scheduler.AddUpdate(0, 0, 100); scheduler.AddAbort(0); scheduler.AddRead(1, 0); scheduler.AddCommit(1); scheduler.Run(); EXPECT_EQ(RESULT_ABORTED, scheduler.schedules[0].txn_result); EXPECT_EQ(RESULT_SUCCESS, scheduler.schedules[1].txn_result); EXPECT_EQ(0, scheduler.schedules[1].results[0]); } { TransactionScheduler scheduler(2, table.get(), &txn_manager); scheduler.AddInsert(0, 100, 0); scheduler.AddAbort(0); scheduler.AddRead(1, 100); scheduler.AddCommit(1); scheduler.Run(); EXPECT_EQ(RESULT_ABORTED, scheduler.schedules[0].txn_result); EXPECT_EQ(RESULT_SUCCESS, scheduler.schedules[0].txn_result); EXPECT_EQ(-1, scheduler.schedules[1].results[0]); } } TEST_F(TransactionTests, SerializableTest) { DirtyWriteTest(); DirtyReadTest(); FuzzyReadTest(); WriteSkewTest(); ReadSkewTest(); // PhantomTes(); } } // End test namespace } // End peloton namespace
test abort insertion
test abort insertion
C++
apache-2.0
ranxian/peloton,larryxiao/peloton-1,amaliujia/CMUDB-peloton,ranxian/peloton,ranxian/peloton,omegaga/peloton,larryxiao/peloton-1,larryxiao/peloton,larryxiao/peloton,omegaga/peloton,larryxiao/peloton,amaliujia/CMUDB-peloton,amaliujia/CMUDB-peloton,larryxiao/peloton,omegaga/peloton,larryxiao/peloton-1,omegaga/peloton,larryxiao/peloton-1,larryxiao/peloton,ranxian/peloton,amaliujia/CMUDB-peloton,amaliujia/CMUDB-peloton,larryxiao/peloton-1,omegaga/peloton,larryxiao/peloton-1,omegaga/peloton,amaliujia/CMUDB-peloton,ranxian/peloton,ranxian/peloton,amaliujia/CMUDB-peloton,larryxiao/peloton,larryxiao/peloton-1,larryxiao/peloton,omegaga/peloton
48d2c96b3c5e08a1a028a946e1cba1a59c02f2dc
db/serializer.hh
db/serializer.hh
/* * Copyright 2015 Cloudius Systems */ #ifndef DB_SERIALIZER_HH_ #define DB_SERIALIZER_HH_ #include "utils/data_input.hh" #include "utils/data_output.hh" #include "bytes.hh" #include "mutation.hh" #include "keys.hh" #include "database_fwd.hh" #include "frozen_mutation.hh" namespace db { /** * Serialization objects for various types and using "internal" format. (Not CQL, origin whatnot). * The design rationale is that a "serializer" can be instantiated for an object, and will contain * the obj + size, and is usable as a functor. * * Serialization can also be done "explicitly" through the static method "write" * (Not using "serialize", because writing "serializer<apa>::serialize" all the time is tiring and redundant) * though care should be takes than data will fit of course. */ template<typename T> class serializer { public: typedef T type; typedef data_output output; typedef data_input input; typedef serializer<T> _MyType; serializer(const type&); // apply to memory, must be at least size() large. const _MyType& operator()(output& out) const { write(out, _item); return *this; } static void write(output&, const T&); static void read(T&, input&); static T read(input&); static void skip(input& in); size_t size() const { return _size; } private: const T& _item; size_t _size; }; template<> serializer<utils::UUID>::serializer(const utils::UUID &); template<> void serializer<utils::UUID>::write(output&, const type&); template<> void serializer<utils::UUID>::read(utils::UUID&, input&); template<> void serializer<utils::UUID>::skip(input&); template<> utils::UUID serializer<utils::UUID>::read(input&); template<> serializer<bytes>::serializer(const bytes &); template<> void serializer<bytes>::write(output&, const type&); template<> void serializer<bytes>::read(bytes&, input&); template<> serializer<bytes_view>::serializer(const bytes_view&); template<> void serializer<bytes_view>::write(output&, const type&); template<> void serializer<bytes_view>::read(bytes_view&, input&); template<> bytes_view serializer<bytes_view>::read(input&); template<> serializer<sstring>::serializer(const sstring&); template<> void serializer<sstring>::write(output&, const type&); template<> void serializer<sstring>::read(sstring&, input&); template<> serializer<tombstone>::serializer(const tombstone &); template<> void serializer<tombstone>::write(output&, const type&); template<> void serializer<tombstone>::read(tombstone&, input&); template<> serializer<atomic_cell_view>::serializer(const atomic_cell_view &); template<> void serializer<atomic_cell_view>::write(output&, const type&); template<> void serializer<atomic_cell_view>::read(atomic_cell_view&, input&); template<> atomic_cell_view serializer<atomic_cell_view>::read(input&); template<> serializer<collection_mutation::view>::serializer(const collection_mutation::view &); template<> void serializer<collection_mutation::view>::write(output&, const type&); template<> void serializer<collection_mutation::view>::read(collection_mutation::view&, input&); template<> serializer<frozen_mutation>::serializer(const frozen_mutation &); template<> void serializer<frozen_mutation>::write(output&, const type&); template<> void serializer<frozen_mutation>::read(frozen_mutation&, input&) = delete; template<> frozen_mutation serializer<frozen_mutation>::read(input&); template<> serializer<partition_key_view>::serializer(const partition_key_view &); template<> void serializer<partition_key_view>::write(output&, const partition_key_view&); template<> void serializer<partition_key_view>::read(partition_key_view&, input&); template<> partition_key_view serializer<partition_key_view>::read(input&); template<> void serializer<partition_key_view>::skip(input&); template<> serializer<clustering_key_view>::serializer(const clustering_key_view &); template<> void serializer<clustering_key_view>::write(output&, const clustering_key_view&); template<> void serializer<clustering_key_view>::read(clustering_key_view&, input&); template<> clustering_key_view serializer<clustering_key_view>::read(input&); template<> serializer<clustering_key_prefix_view>::serializer(const clustering_key_prefix_view &); template<> void serializer<clustering_key_prefix_view>::write(output&, const clustering_key_prefix_view&); template<> void serializer<clustering_key_prefix_view>::read(clustering_key_prefix_view&, input&); template<> clustering_key_prefix_view serializer<clustering_key_prefix_view>::read(input&); template<typename T> T serializer<T>::read(input& in) { type t; read(t, in); return t; } extern template class serializer<tombstone>; extern template class serializer<bytes>; extern template class serializer<bytes_view>; extern template class serializer<sstring>; extern template class serializer<utils::UUID>; extern template class serializer<partition_key_view>; extern template class serializer<clustering_key_view>; extern template class serializer<clustering_key_prefix_view>; typedef serializer<tombstone> tombstone_serializer; typedef serializer<bytes> bytes_serializer; // Compatible with bytes_view_serializer typedef serializer<bytes_view> bytes_view_serializer; // Compatible with bytes_serializer typedef serializer<sstring> sstring_serializer; typedef serializer<atomic_cell_view> atomic_cell_view_serializer; typedef serializer<collection_mutation::view> collection_mutation_view_serializer; typedef serializer<utils::UUID> uuid_serializer; typedef serializer<partition_key_view> partition_key_view_serializer; typedef serializer<clustering_key_view> clustering_key_view_serializer; typedef serializer<clustering_key_prefix_view> clustering_key_prefix_view_serializer; typedef serializer<frozen_mutation> frozen_mutation_serializer; } #endif /* DB_SERIALIZER_HH_ */
/* * Copyright 2015 Cloudius Systems */ #ifndef DB_SERIALIZER_HH_ #define DB_SERIALIZER_HH_ #include "utils/data_input.hh" #include "utils/data_output.hh" #include "bytes_ostream.hh" #include "bytes.hh" #include "mutation.hh" #include "keys.hh" #include "database_fwd.hh" #include "frozen_mutation.hh" namespace db { /** * Serialization objects for various types and using "internal" format. (Not CQL, origin whatnot). * The design rationale is that a "serializer" can be instantiated for an object, and will contain * the obj + size, and is usable as a functor. * * Serialization can also be done "explicitly" through the static method "write" * (Not using "serialize", because writing "serializer<apa>::serialize" all the time is tiring and redundant) * though care should be takes than data will fit of course. */ template<typename T> class serializer { public: typedef T type; typedef data_output output; typedef data_input input; typedef serializer<T> _MyType; serializer(const type&); // apply to memory, must be at least size() large. const _MyType& operator()(output& out) const { write(out, _item); return *this; } static void write(output&, const T&); static void read(T&, input&); static T read(input&); static void skip(input& in); size_t size() const { return _size; } void write(bytes_ostream& out) const { auto buf = out.write_place_holder(_size); data_output data_out((char*)buf, _size); write(data_out, _item); } void write(data_output& out) const { write(out, _item); } private: const T& _item; size_t _size; }; template<> serializer<utils::UUID>::serializer(const utils::UUID &); template<> void serializer<utils::UUID>::write(output&, const type&); template<> void serializer<utils::UUID>::read(utils::UUID&, input&); template<> void serializer<utils::UUID>::skip(input&); template<> utils::UUID serializer<utils::UUID>::read(input&); template<> serializer<bytes>::serializer(const bytes &); template<> void serializer<bytes>::write(output&, const type&); template<> void serializer<bytes>::read(bytes&, input&); template<> serializer<bytes_view>::serializer(const bytes_view&); template<> void serializer<bytes_view>::write(output&, const type&); template<> void serializer<bytes_view>::read(bytes_view&, input&); template<> bytes_view serializer<bytes_view>::read(input&); template<> serializer<sstring>::serializer(const sstring&); template<> void serializer<sstring>::write(output&, const type&); template<> void serializer<sstring>::read(sstring&, input&); template<> serializer<tombstone>::serializer(const tombstone &); template<> void serializer<tombstone>::write(output&, const type&); template<> void serializer<tombstone>::read(tombstone&, input&); template<> serializer<atomic_cell_view>::serializer(const atomic_cell_view &); template<> void serializer<atomic_cell_view>::write(output&, const type&); template<> void serializer<atomic_cell_view>::read(atomic_cell_view&, input&); template<> atomic_cell_view serializer<atomic_cell_view>::read(input&); template<> serializer<collection_mutation::view>::serializer(const collection_mutation::view &); template<> void serializer<collection_mutation::view>::write(output&, const type&); template<> void serializer<collection_mutation::view>::read(collection_mutation::view&, input&); template<> serializer<frozen_mutation>::serializer(const frozen_mutation &); template<> void serializer<frozen_mutation>::write(output&, const type&); template<> void serializer<frozen_mutation>::read(frozen_mutation&, input&) = delete; template<> frozen_mutation serializer<frozen_mutation>::read(input&); template<> serializer<partition_key_view>::serializer(const partition_key_view &); template<> void serializer<partition_key_view>::write(output&, const partition_key_view&); template<> void serializer<partition_key_view>::read(partition_key_view&, input&); template<> partition_key_view serializer<partition_key_view>::read(input&); template<> void serializer<partition_key_view>::skip(input&); template<> serializer<clustering_key_view>::serializer(const clustering_key_view &); template<> void serializer<clustering_key_view>::write(output&, const clustering_key_view&); template<> void serializer<clustering_key_view>::read(clustering_key_view&, input&); template<> clustering_key_view serializer<clustering_key_view>::read(input&); template<> serializer<clustering_key_prefix_view>::serializer(const clustering_key_prefix_view &); template<> void serializer<clustering_key_prefix_view>::write(output&, const clustering_key_prefix_view&); template<> void serializer<clustering_key_prefix_view>::read(clustering_key_prefix_view&, input&); template<> clustering_key_prefix_view serializer<clustering_key_prefix_view>::read(input&); template<typename T> T serializer<T>::read(input& in) { type t; read(t, in); return t; } extern template class serializer<tombstone>; extern template class serializer<bytes>; extern template class serializer<bytes_view>; extern template class serializer<sstring>; extern template class serializer<utils::UUID>; extern template class serializer<partition_key_view>; extern template class serializer<clustering_key_view>; extern template class serializer<clustering_key_prefix_view>; typedef serializer<tombstone> tombstone_serializer; typedef serializer<bytes> bytes_serializer; // Compatible with bytes_view_serializer typedef serializer<bytes_view> bytes_view_serializer; // Compatible with bytes_serializer typedef serializer<sstring> sstring_serializer; typedef serializer<atomic_cell_view> atomic_cell_view_serializer; typedef serializer<collection_mutation::view> collection_mutation_view_serializer; typedef serializer<utils::UUID> uuid_serializer; typedef serializer<partition_key_view> partition_key_view_serializer; typedef serializer<clustering_key_view> clustering_key_view_serializer; typedef serializer<clustering_key_prefix_view> clustering_key_prefix_view_serializer; typedef serializer<frozen_mutation> frozen_mutation_serializer; } #endif /* DB_SERIALIZER_HH_ */
Introduce write() which works with bytes_ostream
db/serializer: Introduce write() which works with bytes_ostream
C++
agpl-3.0
justintung/scylla,phonkee/scylla,capturePointer/scylla,scylladb/scylla,justintung/scylla,linearregression/scylla,wildinto/scylla,respu/scylla,capturePointer/scylla,gwicke/scylla,dwdm/scylla,raphaelsc/scylla,bowlofstew/scylla,kangkot/scylla,aruanruan/scylla,shaunstanislaus/scylla,guiquanz/scylla,phonkee/scylla,eklitzke/scylla,avikivity/scylla,linearregression/scylla,rentongzhang/scylla,duarten/scylla,asias/scylla,eklitzke/scylla,bowlofstew/scylla,dwdm/scylla,scylladb/scylla,rluta/scylla,duarten/scylla,gwicke/scylla,raphaelsc/scylla,justintung/scylla,dwdm/scylla,duarten/scylla,shaunstanislaus/scylla,guiquanz/scylla,avikivity/scylla,guiquanz/scylla,wildinto/scylla,stamhe/scylla,rentongzhang/scylla,rentongzhang/scylla,capturePointer/scylla,rluta/scylla,avikivity/scylla,scylladb/scylla,scylladb/scylla,victorbriz/scylla,shaunstanislaus/scylla,aruanruan/scylla,aruanruan/scylla,stamhe/scylla,kangkot/scylla,phonkee/scylla,acbellini/scylla,gwicke/scylla,asias/scylla,glommer/scylla,glommer/scylla,kangkot/scylla,senseb/scylla,raphaelsc/scylla,kjniemi/scylla,tempbottle/scylla,acbellini/scylla,wildinto/scylla,bowlofstew/scylla,victorbriz/scylla,victorbriz/scylla,kjniemi/scylla,stamhe/scylla,senseb/scylla,respu/scylla,senseb/scylla,linearregression/scylla,acbellini/scylla,rluta/scylla,tempbottle/scylla,asias/scylla,respu/scylla,tempbottle/scylla,eklitzke/scylla,glommer/scylla,kjniemi/scylla
61ea5383383346ad2a25bd725e2f5e1f003260eb
plugins/single_plugins/grid.cpp
plugins/single_plugins/grid.cpp
#include <output.hpp> #include <core.hpp> #include <debug.hpp> #include <view.hpp> #include <workspace-manager.hpp> #include <render-manager.hpp> #include <algorithm> #include <linux/input-event-codes.h> #include "signal-definitions.hpp" #include <nonstd/make_unique.hpp> #include <animation.hpp> #include "snap_signal.hpp" #include "../wobbly/wobbly-signal.hpp" const std::string grid_view_id = "grid-view"; class wayfire_grid_view : public wf_custom_view_data { wf_duration duration; bool is_active = true; wayfire_view view; wayfire_output *output; effect_hook_t pre_hook; signal_callback_t unmapped; bool tiled; wf_geometry target, initial; wayfire_grab_interface iface; wf_option animation_type; public: wayfire_grid_view(wayfire_view view, wayfire_grab_interface iface, wf_option animation_type, wf_option animation_duration) { this->view = view; this->output = view->get_output(); this->iface = iface; this->animation_type = animation_type; duration = wf_duration(animation_duration); if (!view->get_output()->activate_plugin(iface)) { is_active = false; return; } pre_hook = [=] () { adjust_geometry(); }; output->render->add_effect(&pre_hook, WF_OUTPUT_EFFECT_PRE); unmapped = [=] (signal_data *data) { if (get_signaled_view(data) == view) view->custom_data.erase(grid_view_id); }; output->render->auto_redraw(true); output->connect_signal("unmap-view", &unmapped); output->connect_signal("detach-view", &unmapped); } void destroy() { view->custom_data.erase(grid_view_id); } void adjust_target_geometry(wf_geometry geometry, bool tiled) { target = geometry; initial = view->get_wm_geometry(); this->tiled = tiled; log_info("adjust geometry"); auto type = animation_type->as_string(); if (output->is_plugin_active("wobbly") || !is_active) type = "wobbly"; if (type == "none") { view->set_maximized(tiled); view->set_geometry(geometry); return destroy(); } if (type == "wobbly") { snap_wobbly(view, geometry); view->set_maximized(tiled); view->set_geometry(geometry); if (!tiled) // release snap, so subsequent size changes don't bother us snap_wobbly(view, geometry, false); return destroy(); } view->set_maximized(1); view->set_moving(1); view->set_resizing(1); duration.start(); } void adjust_geometry() { log_info("adjust"); if (!duration.running()) { log_info("direct end %d", tiled); view->set_geometry(target); view->set_maximized(tiled); view->set_moving(0); view->set_resizing(0); return destroy(); } int cx = duration.progress(initial.x, target.x); int cy = duration.progress(initial.y, target.y); int cw = duration.progress(initial.width, target.width); int ch = duration.progress(initial.height, target.height); log_info("step %d@%d %dx%d", cx, cy, cw, ch); view->set_geometry({cx, cy, cw, ch}); } ~wayfire_grid_view() { if (!is_active) return; output->render->rem_effect(&pre_hook, WF_OUTPUT_EFFECT_PRE); output->deactivate_plugin(iface); output->render->auto_redraw(false); output->disconnect_signal("unmap-view", &unmapped); output->disconnect_signal("detach-view", &unmapped); } }; wayfire_grid_view *ensure_grid_view(wayfire_view view, wayfire_grab_interface iface, wf_option animation_type, wf_option animation_duration) { if (view->custom_data.count(grid_view_id)) return static_cast<wayfire_grid_view*> (view->custom_data[grid_view_id].get()); auto saved = nonstd::make_unique<wayfire_grid_view> (view, iface, animation_type, animation_duration); auto ret = saved.get(); view->custom_data[grid_view_id] = std::move(saved); return ret; } const std::string grid_saved_pos_id = "grid-saved-pos"; class saved_view_geometry : public wf_custom_view_data { public: wf_geometry geometry; bool was_maximized; // used by fullscreen-request }; bool has_saved_position(wayfire_view view, std::string suffix = "") { return view->custom_data.count(grid_saved_pos_id + suffix); } saved_view_geometry *ensure_saved_geometry(wayfire_view view, std::string suffix = "") { if (has_saved_position(view, suffix)) return static_cast<saved_view_geometry*> (view->custom_data[grid_saved_pos_id + suffix].get()); auto saved = nonstd::make_unique<saved_view_geometry> (); auto ret = saved.get(); view->custom_data[grid_saved_pos_id + suffix] = std::move(saved); return ret; } void erase_saved(wayfire_view view, std::string suffix = "") { view->custom_data.erase(grid_saved_pos_id + suffix); } class wayfire_grid : public wayfire_plugin_t { signal_callback_t output_resized_cb, view_destroyed_cb; std::vector<std::string> slots = {"unused", "bl", "b", "br", "l", "c", "r", "tl", "t", "tr"}; std::vector<std::string> default_keys = { "none", "<alt> <ctrl> KEY_KP1", "<alt> <ctrl> KEY_KP2", "<alt> <ctrl> KEY_KP3", "<alt> <ctrl> KEY_KP4", "<alt> <ctrl> KEY_KP5", "<alt> <ctrl> KEY_KP6", "<alt> <ctrl> KEY_KP7", "<alt> <ctrl> KEY_KP8", "<alt> <ctrl> KEY_KP9", }; key_callback bindings[10]; wf_option keys[10]; signal_callback_t snap_cb, maximized_cb, fullscreen_cb; wf_option animation_duration, animation_type; public: void init(wayfire_config *config) { grab_interface->name = "grid"; grab_interface->abilities_mask = WF_ABILITY_CHANGE_VIEW_GEOMETRY; auto section = config->get_section("grid"); animation_duration = section->get_option("duration", "300"); animation_type = section->get_option("type", "simple"); for (int i = 1; i < 10; i++) { keys[i] = section->get_option("slot_" + slots[i], default_keys[i]); bindings[i] = [=] (uint32_t key) { auto view = output->get_active_view(); if (view->role != WF_VIEW_ROLE_TOPLEVEL) return; handle_key(view, i); }; output->add_key(keys[i], &bindings[i]); } using namespace std::placeholders; snap_cb = std::bind(std::mem_fn(&wayfire_grid::snap_signal_cb), this, _1); output->connect_signal("view-snap", &snap_cb); maximized_cb = std::bind(std::mem_fn(&wayfire_grid::maximize_signal_cb), this, _1); output->connect_signal("view-maximized-request", &maximized_cb); fullscreen_cb = std::bind(std::mem_fn(&wayfire_grid::fullscreen_signal_cb), this, _1); output->connect_signal("view-fullscreen-request", &fullscreen_cb); } void handle_key(wayfire_view view, int key) { wf_geometry target = get_slot_dimensions(key, output->workspace->get_workarea()); bool tiled = true; if (view->maximized && view->get_wm_geometry() == target) { return; } else if (!has_saved_position(view) && key) { ensure_saved_geometry(view)->geometry = view->get_wm_geometry(); } else if (has_saved_position(view) && key == 0) { tiled = false; target = calculate_restored_geometry(ensure_saved_geometry(view)->geometry); erase_saved(view); } else if (!has_saved_position(view)) { return; } auto gv = ensure_grid_view(view, grab_interface, animation_type, animation_duration); gv->adjust_target_geometry(target, tiled); } /* calculates the target geometry so that it is centered around the pointer */ wf_geometry calculate_restored_geometry(wf_geometry base_restored) { GetTuple(cx, cy, output->get_cursor_position()); base_restored.x = cx - base_restored.width / 2; base_restored.y = cy - base_restored.height / 2; /* if the view goes outside of the workarea, try to move it back inside */ auto wa = output->workspace->get_workarea(); if (base_restored.x + base_restored.width > wa.x + wa.width) base_restored.x = wa.x + wa.width - base_restored.width; if (base_restored.y + base_restored.height > wa.y + wa.width) base_restored.y = wa.y + wa.height - base_restored.width; if (base_restored.x < wa.x) base_restored.x = wa.x; if (base_restored.y < wa.y) base_restored.y = wa.y; return base_restored; } /* * 7 8 9 * 4 5 6 * 1 2 3 * */ wf_geometry get_slot_dimensions(int n, wf_geometry area) { if (n == 0) // toggle off slot return {0, 0, 0, 0}; int w2 = area.width / 2; int h2 = area.height / 2; if (n % 3 == 1) area.width = w2; if (n % 3 == 0) area.width = w2, area.x += w2; if (n >= 7) area.height = h2; else if (n <= 3) area.height = h2, area.y += h2; return area; } void snap_signal_cb(signal_data *ddata) { snap_signal *data = static_cast<snap_signal*>(ddata); handle_key(data->view, data->tslot); } void maximize_signal_cb(signal_data *ddata) { auto data = static_cast<view_maximized_signal*> (ddata); handle_key(data->view, data->state ? 5 : 0); } void fullscreen_signal_cb(signal_data *ddata) { auto data = static_cast<view_fullscreen_signal*> (ddata); if (data->state) { if (!has_saved_position(data->view, "-fs")) { auto sg = ensure_saved_geometry(data->view, "-fs"); sg->geometry = data->view->get_wm_geometry(); sg->was_maximized = data->view->maximized; } auto gv = ensure_grid_view(data->view, grab_interface, animation_type, animation_duration); gv->adjust_target_geometry(output->get_relative_geometry(), true); data->view->set_fullscreen(true); } else { if (has_saved_position(data->view, "-fs")) { auto sg = ensure_saved_geometry(data->view, "-fs"); auto target_geometry = sg->geometry; auto maximized = sg->was_maximized; erase_saved(data->view, "-fs"); auto gv = ensure_grid_view(data->view, grab_interface, animation_type, animation_duration); gv->adjust_target_geometry(target_geometry, maximized); } data->view->set_fullscreen(false); } } void fini() { for (int i = 1; i < 10; i++) output->rem_key(&bindings[i]); output->disconnect_signal("view-snap", &snap_cb); output->disconnect_signal("view-maximized-request", &maximized_cb); output->disconnect_signal("view-fullscreen-request", &fullscreen_cb); output->disconnect_signal("output-resized", &output_resized_cb); output->disconnect_signal("unmap-view", &view_destroyed_cb); output->disconnect_signal("detach-view", &view_destroyed_cb); } }; extern "C" { wayfire_plugin_t *newInstance() { return new wayfire_grid; } }
#include <output.hpp> #include <core.hpp> #include <debug.hpp> #include <view.hpp> #include <workspace-manager.hpp> #include <render-manager.hpp> #include <algorithm> #include <linux/input-event-codes.h> #include "signal-definitions.hpp" #include <nonstd/make_unique.hpp> #include <animation.hpp> #include "snap_signal.hpp" #include "../wobbly/wobbly-signal.hpp" const std::string grid_view_id = "grid-view"; class wayfire_grid_view : public wf_custom_view_data { wf_duration duration; bool is_active = true; wayfire_view view; wayfire_output *output; effect_hook_t pre_hook; signal_callback_t unmapped; bool tiled; wf_geometry target, initial; wayfire_grab_interface iface; wf_option animation_type; public: wayfire_grid_view(wayfire_view view, wayfire_grab_interface iface, wf_option animation_type, wf_option animation_duration) { this->view = view; this->output = view->get_output(); this->iface = iface; this->animation_type = animation_type; duration = wf_duration(animation_duration); if (!view->get_output()->activate_plugin(iface)) { is_active = false; return; } pre_hook = [=] () { adjust_geometry(); }; output->render->add_effect(&pre_hook, WF_OUTPUT_EFFECT_PRE); unmapped = [=] (signal_data *data) { if (get_signaled_view(data) == view) view->custom_data.erase(grid_view_id); }; output->render->auto_redraw(true); output->connect_signal("unmap-view", &unmapped); output->connect_signal("detach-view", &unmapped); } void destroy() { view->custom_data.erase(grid_view_id); } void adjust_target_geometry(wf_geometry geometry, bool tiled) { target = geometry; initial = view->get_wm_geometry(); this->tiled = tiled; log_info("adjust geometry"); auto type = animation_type->as_string(); if (output->is_plugin_active("wobbly") || !is_active) type = "wobbly"; if (type == "none") { view->set_maximized(tiled); view->set_geometry(geometry); return destroy(); } if (type == "wobbly") { snap_wobbly(view, geometry); view->set_maximized(tiled); view->set_geometry(geometry); if (!tiled) // release snap, so subsequent size changes don't bother us snap_wobbly(view, geometry, false); return destroy(); } view->set_maximized(1); view->set_moving(1); view->set_resizing(1); duration.start(); } void adjust_geometry() { log_info("adjust"); if (!duration.running()) { log_info("direct end %d", tiled); view->set_geometry(target); view->set_maximized(tiled); view->set_moving(0); view->set_resizing(0); return destroy(); } int cx = duration.progress(initial.x, target.x); int cy = duration.progress(initial.y, target.y); int cw = duration.progress(initial.width, target.width); int ch = duration.progress(initial.height, target.height); log_info("step %d@%d %dx%d", cx, cy, cw, ch); view->set_geometry({cx, cy, cw, ch}); } ~wayfire_grid_view() { if (!is_active) return; output->render->rem_effect(&pre_hook, WF_OUTPUT_EFFECT_PRE); output->deactivate_plugin(iface); output->render->auto_redraw(false); output->disconnect_signal("unmap-view", &unmapped); output->disconnect_signal("detach-view", &unmapped); } }; wayfire_grid_view *ensure_grid_view(wayfire_view view, wayfire_grab_interface iface, wf_option animation_type, wf_option animation_duration) { if (view->custom_data.count(grid_view_id)) return static_cast<wayfire_grid_view*> (view->custom_data[grid_view_id].get()); auto saved = nonstd::make_unique<wayfire_grid_view> (view, iface, animation_type, animation_duration); auto ret = saved.get(); view->custom_data[grid_view_id] = std::move(saved); return ret; } const std::string grid_saved_pos_id = "grid-saved-pos"; class saved_view_geometry : public wf_custom_view_data { public: wf_geometry geometry; bool was_maximized; // used by fullscreen-request }; bool has_saved_position(wayfire_view view, std::string suffix = "") { return view->custom_data.count(grid_saved_pos_id + suffix); } saved_view_geometry *ensure_saved_geometry(wayfire_view view, std::string suffix = "") { if (has_saved_position(view, suffix)) return static_cast<saved_view_geometry*> (view->custom_data[grid_saved_pos_id + suffix].get()); auto saved = nonstd::make_unique<saved_view_geometry> (); auto ret = saved.get(); view->custom_data[grid_saved_pos_id + suffix] = std::move(saved); return ret; } void erase_saved(wayfire_view view, std::string suffix = "") { view->custom_data.erase(grid_saved_pos_id + suffix); } class wayfire_grid : public wayfire_plugin_t { signal_callback_t output_resized_cb, view_destroyed_cb; std::vector<std::string> slots = {"unused", "bl", "b", "br", "l", "c", "r", "tl", "t", "tr"}; std::vector<std::string> default_keys = { "none", "<alt> <ctrl> KEY_KP1", "<alt> <ctrl> KEY_KP2", "<alt> <ctrl> KEY_KP3", "<alt> <ctrl> KEY_KP4", "<alt> <ctrl> KEY_KP5", "<alt> <ctrl> KEY_KP6", "<alt> <ctrl> KEY_KP7", "<alt> <ctrl> KEY_KP8", "<alt> <ctrl> KEY_KP9", }; key_callback bindings[10]; wf_option keys[10]; signal_callback_t snap_cb, maximized_cb, fullscreen_cb; wf_option animation_duration, animation_type; public: void init(wayfire_config *config) { grab_interface->name = "grid"; grab_interface->abilities_mask = WF_ABILITY_CHANGE_VIEW_GEOMETRY; auto section = config->get_section("grid"); animation_duration = section->get_option("duration", "300"); animation_type = section->get_option("type", "simple"); for (int i = 1; i < 10; i++) { keys[i] = section->get_option("slot_" + slots[i], default_keys[i]); bindings[i] = [=] (uint32_t key) { auto view = output->get_active_view(); if (!view || view->role != WF_VIEW_ROLE_TOPLEVEL) return; handle_key(view, i); }; output->add_key(keys[i], &bindings[i]); } using namespace std::placeholders; snap_cb = std::bind(std::mem_fn(&wayfire_grid::snap_signal_cb), this, _1); output->connect_signal("view-snap", &snap_cb); maximized_cb = std::bind(std::mem_fn(&wayfire_grid::maximize_signal_cb), this, _1); output->connect_signal("view-maximized-request", &maximized_cb); fullscreen_cb = std::bind(std::mem_fn(&wayfire_grid::fullscreen_signal_cb), this, _1); output->connect_signal("view-fullscreen-request", &fullscreen_cb); } void handle_key(wayfire_view view, int key) { wf_geometry target = get_slot_dimensions(key, output->workspace->get_workarea()); bool tiled = true; if (view->maximized && view->get_wm_geometry() == target) { return; } else if (!has_saved_position(view) && key) { ensure_saved_geometry(view)->geometry = view->get_wm_geometry(); } else if (has_saved_position(view) && key == 0) { tiled = false; target = calculate_restored_geometry(ensure_saved_geometry(view)->geometry); erase_saved(view); } else if (!has_saved_position(view)) { return; } auto gv = ensure_grid_view(view, grab_interface, animation_type, animation_duration); gv->adjust_target_geometry(target, tiled); } /* calculates the target geometry so that it is centered around the pointer */ wf_geometry calculate_restored_geometry(wf_geometry base_restored) { GetTuple(cx, cy, output->get_cursor_position()); base_restored.x = cx - base_restored.width / 2; base_restored.y = cy - base_restored.height / 2; /* if the view goes outside of the workarea, try to move it back inside */ auto wa = output->workspace->get_workarea(); if (base_restored.x + base_restored.width > wa.x + wa.width) base_restored.x = wa.x + wa.width - base_restored.width; if (base_restored.y + base_restored.height > wa.y + wa.width) base_restored.y = wa.y + wa.height - base_restored.width; if (base_restored.x < wa.x) base_restored.x = wa.x; if (base_restored.y < wa.y) base_restored.y = wa.y; return base_restored; } /* * 7 8 9 * 4 5 6 * 1 2 3 * */ wf_geometry get_slot_dimensions(int n, wf_geometry area) { if (n == 0) // toggle off slot return {0, 0, 0, 0}; int w2 = area.width / 2; int h2 = area.height / 2; if (n % 3 == 1) area.width = w2; if (n % 3 == 0) area.width = w2, area.x += w2; if (n >= 7) area.height = h2; else if (n <= 3) area.height = h2, area.y += h2; return area; } void snap_signal_cb(signal_data *ddata) { snap_signal *data = static_cast<snap_signal*>(ddata); handle_key(data->view, data->tslot); } void maximize_signal_cb(signal_data *ddata) { auto data = static_cast<view_maximized_signal*> (ddata); handle_key(data->view, data->state ? 5 : 0); } void fullscreen_signal_cb(signal_data *ddata) { auto data = static_cast<view_fullscreen_signal*> (ddata); if (data->state) { if (!has_saved_position(data->view, "-fs")) { auto sg = ensure_saved_geometry(data->view, "-fs"); sg->geometry = data->view->get_wm_geometry(); sg->was_maximized = data->view->maximized; } auto gv = ensure_grid_view(data->view, grab_interface, animation_type, animation_duration); gv->adjust_target_geometry(output->get_relative_geometry(), true); data->view->set_fullscreen(true); } else { if (has_saved_position(data->view, "-fs")) { auto sg = ensure_saved_geometry(data->view, "-fs"); auto target_geometry = sg->geometry; auto maximized = sg->was_maximized; erase_saved(data->view, "-fs"); auto gv = ensure_grid_view(data->view, grab_interface, animation_type, animation_duration); gv->adjust_target_geometry(target_geometry, maximized); } data->view->set_fullscreen(false); } } void fini() { for (int i = 1; i < 10; i++) output->rem_key(&bindings[i]); output->disconnect_signal("view-snap", &snap_cb); output->disconnect_signal("view-maximized-request", &maximized_cb); output->disconnect_signal("view-fullscreen-request", &fullscreen_cb); output->disconnect_signal("output-resized", &output_resized_cb); output->disconnect_signal("unmap-view", &view_destroyed_cb); output->disconnect_signal("detach-view", &view_destroyed_cb); } }; extern "C" { wayfire_plugin_t *newInstance() { return new wayfire_grid; } }
check if there is active view before doing anything
grid: check if there is active view before doing anything
C++
mit
ammen99/wayfire,ammen99/wayfire
d695ee6573ad3b37952ef930b1608c9227dfe6f7
decoder/trule.cc
decoder/trule.cc
#include "trule.h" #include <sstream> #include "stringlib.h" #include "tdict.h" #include "rule_lexer.h" #include "threadlocal.h" using namespace std; ostream &operator<<(ostream &o,TRule const& r) { return o<<r.AsString(true); } bool TRule::IsGoal() const { static const int kGOAL(TD::Convert("Goal") * -1); // this will happen once, and after static init of trule.cc static dict. return GetLHS() == kGOAL; } static WordID ConvertTrgString(const string& w) { int len = w.size(); WordID id = 0; // [X,0] or [0] // for target rules, we ignore the category, just keep the index if (len > 2 && w[0]=='[' && w[len-1]==']' && w[len-2] > '0' && w[len-2] <= '9' && (len == 3 || (len > 4 && w[len-3] == ','))) { id = w[len-2] - '0'; id = 1 - id; } else { id = TD::Convert(w); } return id; } static WordID ConvertSrcString(const string& w, bool mono = false) { int len = w.size(); // [X,0] // for source rules, we keep the category and ignore the index (source rules are // always numbered 1, 2, 3... if (mono) { if (len > 2 && w[0]=='[' && w[len-1]==']') { if (len > 4 && w[len-3] == ',') { cerr << "[ERROR] Monolingual rules mut not have non-terminal indices:\n " << w << endl; exit(1); } // TODO check that source indices go 1,2,3,etc. return TD::Convert(w.substr(1, len-2)) * -1; } else { return TD::Convert(w); } } else { if (len > 4 && w[0]=='[' && w[len-1]==']' && w[len-3] == ',' && w[len-2] > '0' && w[len-2] <= '9') { return TD::Convert(w.substr(1, len-4)) * -1; } else { return TD::Convert(w); } } } static WordID ConvertLHS(const string& w) { if (w[0] == '[') { int len = w.size(); if (len < 3) { cerr << "Format error: " << w << endl; exit(1); } return TD::Convert(w.substr(1, len-2)) * -1; } else { return TD::Convert(w) * -1; } } TRule* TRule::CreateRuleSynchronous(const string& rule) { TRule* res = new TRule; if (res->ReadFromString(rule, true, false)) return res; cerr << "[ERROR] Failed to creating rule from: " << rule << endl; delete res; return NULL; } TRule* TRule::CreateRulePhrasetable(const string& rule) { // TODO make this faster // TODO add configuration for default NT type if (rule[0] == '[') { cerr << "Phrasetable rules shouldn't have a LHS / non-terminals:\n " << rule << endl; return NULL; } TRule* res = new TRule("[X] ||| " + rule, true, false); if (res->Arity() != 0) { cerr << "Phrasetable rules should have arity 0:\n " << rule << endl; delete res; return NULL; } return res; } TRule* TRule::CreateRuleMonolingual(const string& rule) { return new TRule(rule, false, true); } namespace { // callback for lexer THREADLOCAL int n_assigned=0; void assign_trule(const TRulePtr& new_rule, const unsigned int ctf_level, const TRulePtr& coarse_rule, void* extra) { TRule *assignto=(TRule *)extra; *assignto=*new_rule; ++n_assigned; } } bool TRule::ReadFromString(const string& line, bool strict, bool mono) { if (!is_single_line_stripped(line)) cerr<<"\nWARNING: building rule from multi-line string "<<line<<".\n"; // backed off of this: it's failing to parse TRulePtr glue(new TRule("[" + goal_nt + "] ||| [" + goal_nt + ",1] ["+ default_nt + ",2] ||| [1] [2] ||| Glue=1")); thinks [1] is the features! if (false && !(mono||strict)) { // use lexer istringstream il(line); n_assigned=0; RuleLexer::ReadRules(&il,assign_trule,this); if (n_assigned>1) cerr<<"\nWARNING: more than one rule parsed from multi-line string; kept last: "<<line<<".\n"; return n_assigned; } e_.clear(); f_.clear(); scores_.clear(); string w; istringstream is(line); int format = CountSubstrings(line, "|||"); if (strict && format < 2) { cerr << "Bad rule format in strict mode:\n" << line << endl; return false; } if (format >= 2 || (mono && format == 1)) { while(is>>w && w!="|||") { lhs_ = ConvertLHS(w); } while(is>>w && w!="|||") { f_.push_back(ConvertSrcString(w, mono)); } if (!mono) { while(is>>w && w!="|||") { e_.push_back(ConvertTrgString(w)); } } int fv = 0; if (is) { string ss; getline(is, ss); //cerr << "L: " << ss << endl; int start = 0; const int len = ss.size(); while (start < len) { while(start < len && (ss[start] == ' ' || ss[start] == ';')) ++start; if (start == len) break; int end = start + 1; while(end < len && (ss[end] != '=' && ss[end] != ' ' && ss[end] != ';')) ++end; if (end == len || ss[end] == ' ' || ss[end] == ';') { //cerr << "PROC: '" << ss.substr(start, end - start) << "'\n"; // non-named features if (end != len) { ss[end] = 0; } string fname = "PhraseModel_X"; if (fv > 9) { cerr << "Too many phrasetable scores - used named format\n"; abort(); } fname[12]='0' + fv; ++fv; // if the feature set is frozen, this may return zero, indicating an // undefined feature const int fid = FD::Convert(fname); if (fid) scores_.set_value(fid, atof(&ss[start])); //cerr << "F: " << fname << " VAL=" << scores_.value(FD::Convert(fname)) << endl; } else { const int fid = FD::Convert(ss.substr(start, end - start)); start = end + 1; end = start + 1; while(end < len && (ss[end] != ' ' && ss[end] != ';')) ++end; if (end < len) { ss[end] = 0; } assert(start < len); if (fid) scores_.set_value(fid, atof(&ss[start])); //cerr << "F: " << FD::Convert(fid) << " VAL=" << scores_.value(fid) << endl; } start = end + 1; } } } else if (format == 1) { while(is>>w && w!="|||") { lhs_ = ConvertLHS(w); } while(is>>w && w!="|||") { e_.push_back(ConvertTrgString(w)); } f_ = e_; int x = ConvertLHS("[X]"); for (int i = 0; i < f_.size(); ++i) if (f_[i] <= 0) { f_[i] = x; } } else { cerr << "F: " << format << endl; cerr << "[ERROR] Don't know how to read:\n" << line << endl; } if (mono) { e_ = f_; int ci = 0; for (int i = 0; i < e_.size(); ++i) if (e_[i] < 0) e_[i] = ci--; } ComputeArity(); return SanityCheck(); } bool TRule::SanityCheck() const { vector<int> used(f_.size(), 0); int ac = 0; for (int i = 0; i < e_.size(); ++i) { int ind = e_[i]; if (ind > 0) continue; ind = -ind; if ((++used[ind]) != 1) { cerr << "[ERROR] e-side variable index " << (ind+1) << " used more than once!\n"; return false; } ac++; } if (ac != Arity()) { cerr << "[ERROR] e-side arity mismatches f-side\n"; return false; } return true; } void TRule::ComputeArity() { int min = 1; for (vector<WordID>::const_iterator i = e_.begin(); i != e_.end(); ++i) if (*i < min) min = *i; arity_ = 1 - min; } static string AnonymousStrVar(int i) { string res("[v]"); if(!(i <= 0 && i >= -8)) { cerr << "Can't handle more than 9 non-terminals: index=" << (-i) << endl; abort(); } res[1] = '1' - i; return res; } string TRule::AsString(bool verbose) const { ostringstream os; int idx = 0; if (lhs_ && verbose) { os << '[' << TD::Convert(lhs_ * -1) << "] |||"; } for (int i = 0; i < f_.size(); ++i) { const WordID& w = f_[i]; if (w < 0) { int wi = w * -1; ++idx; os << " [" << TD::Convert(wi) << ',' << idx << ']'; } else { os << ' ' << TD::Convert(w); } } os << " ||| "; if (idx > 9) { cerr << "Too many non-terminals!\n partial: " << os.str() << endl; exit(1); } for (int i =0; i<e_.size(); ++i) { if (i) os << ' '; const WordID& w = e_[i]; if (w < 1) os << AnonymousStrVar(w); else os << TD::Convert(w); } if (!scores_.empty() && verbose) { os << " ||| " << scores_; } return os.str(); }
#include "trule.h" #include <sstream> #include "stringlib.h" #include "tdict.h" #include "rule_lexer.h" #include "threadlocal.h" using namespace std; ostream &operator<<(ostream &o,TRule const& r) { return o<<r.AsString(true); } bool TRule::IsGoal() const { static const int kGOAL(TD::Convert("Goal") * -1); // this will happen once, and after static init of trule.cc static dict. return GetLHS() == kGOAL; } static WordID ConvertTrgString(const string& w) { int len = w.size(); WordID id = 0; // [X,0] or [0] // for target rules, we ignore the category, just keep the index if (len > 2 && w[0]=='[' && w[len-1]==']' && w[len-2] > '0' && w[len-2] <= '9' && (len == 3 || (len > 4 && w[len-3] == ','))) { id = w[len-2] - '0'; id = 1 - id; } else { id = TD::Convert(w); } return id; } static WordID ConvertSrcString(const string& w, bool mono = false) { int len = w.size(); // [X,0] // for source rules, we keep the category and ignore the index (source rules are // always numbered 1, 2, 3... if (mono) { if (len > 2 && w[0]=='[' && w[len-1]==']') { if (len > 4 && w[len-3] == ',') { cerr << "[ERROR] Monolingual rules mut not have non-terminal indices:\n " << w << endl; exit(1); } // TODO check that source indices go 1,2,3,etc. return TD::Convert(w.substr(1, len-2)) * -1; } else { return TD::Convert(w); } } else { if (len > 4 && w[0]=='[' && w[len-1]==']' && w[len-3] == ',' && w[len-2] > '0' && w[len-2] <= '9') { return TD::Convert(w.substr(1, len-4)) * -1; } else { return TD::Convert(w); } } } static WordID ConvertLHS(const string& w) { if (w[0] == '[') { int len = w.size(); if (len < 3) { cerr << "Format error: " << w << endl; exit(1); } return TD::Convert(w.substr(1, len-2)) * -1; } else { return TD::Convert(w) * -1; } } TRule* TRule::CreateRuleSynchronous(const string& rule) { TRule* res = new TRule; if (res->ReadFromString(rule, true, false)) return res; cerr << "[ERROR] Failed to creating rule from: " << rule << endl; delete res; return NULL; } TRule* TRule::CreateRulePhrasetable(const string& rule) { // TODO make this faster // TODO add configuration for default NT type if (rule[0] == '[') { cerr << "Phrasetable rules shouldn't have a LHS / non-terminals:\n " << rule << endl; return NULL; } TRule* res = new TRule("[X] ||| " + rule, true, false); if (res->Arity() != 0) { cerr << "Phrasetable rules should have arity 0:\n " << rule << endl; delete res; return NULL; } return res; } TRule* TRule::CreateRuleMonolingual(const string& rule) { return new TRule(rule, false, true); } namespace { // callback for lexer THREADLOCAL int n_assigned=0; void assign_trule(const TRulePtr& new_rule, const unsigned int ctf_level, const TRulePtr& coarse_rule, void* extra) { TRule *assignto=(TRule *)extra; *assignto=*new_rule; ++n_assigned; } } bool TRule::ReadFromString(const string& line, bool strict, bool mono) { if (!is_single_line_stripped(line)) cerr<<"\nWARNING: building rule from multi-line string "<<line<<".\n"; // backed off of this: it's failing to parse TRulePtr glue(new TRule("[" + goal_nt + "] ||| [" + goal_nt + ",1] ["+ default_nt + ",2] ||| [1] [2] ||| Glue=1")); thinks [1] is the features! if (false && !(mono||strict)) { // use lexer istringstream il(line); n_assigned=0; RuleLexer::ReadRules(&il,assign_trule,this); if (n_assigned>1) cerr<<"\nWARNING: more than one rule parsed from multi-line string; kept last: "<<line<<".\n"; return n_assigned; } e_.clear(); f_.clear(); scores_.clear(); string w; istringstream is(line); int format = CountSubstrings(line, "|||"); if (strict && format < 2) { cerr << "Bad rule format in strict mode:\n" << line << endl; return false; } if (format >= 2 || (mono && format == 1)) { while(is>>w && w!="|||") { lhs_ = ConvertLHS(w); } while(is>>w && w!="|||") { f_.push_back(ConvertSrcString(w, mono)); } if (!mono) { while(is>>w && w!="|||") { e_.push_back(ConvertTrgString(w)); } } int fv = 0; if (is) { string ss; getline(is, ss); //cerr << "L: " << ss << endl; int start = 0; const int len = ss.size(); while (start < len) { while(start < len && (ss[start] == ' ' || ss[start] == ';')) ++start; if (start == len) break; int end = start + 1; while(end < len && (ss[end] != '=' && ss[end] != ' ' && ss[end] != ';')) ++end; if (end == len || ss[end] == ' ' || ss[end] == ';') { //cerr << "PROC: '" << ss.substr(start, end - start) << "'\n"; // non-named features if (end != len) { ss[end] = 0; } string fname = "PhraseModel_X"; if (fv > 9) { cerr << "Too many phrasetable scores - used named format\n"; abort(); } fname[12]='0' + fv; ++fv; // if the feature set is frozen, this may return zero, indicating an // undefined feature const int fid = FD::Convert(fname); if (fid) scores_.set_value(fid, atof(&ss[start])); //cerr << "F: " << fname << " VAL=" << scores_.value(FD::Convert(fname)) << endl; } else { const int fid = FD::Convert(ss.substr(start, end - start)); start = end + 1; end = start + 1; while(end < len && (ss[end] != ' ' && ss[end] != ';')) ++end; if (end < len) { ss[end] = 0; } assert(start < len); if (fid) scores_.set_value(fid, atof(&ss[start])); //cerr << "F: " << FD::Convert(fid) << " VAL=" << scores_.value(fid) << endl; } start = end + 1; } } } else if (format == 1) { while(is>>w && w!="|||") { lhs_ = ConvertLHS(w); } while(is>>w && w!="|||") { e_.push_back(ConvertTrgString(w)); } f_ = e_; int x = ConvertLHS("[X]"); for (int i = 0; i < f_.size(); ++i) if (f_[i] <= 0) { f_[i] = x; } } else { cerr << "F: " << format << endl; cerr << "[ERROR] Don't know how to read:\n" << line << endl; } if (mono) { e_ = f_; int ci = 0; for (int i = 0; i < e_.size(); ++i) if (e_[i] < 0) e_[i] = ci--; } ComputeArity(); return SanityCheck(); } bool TRule::SanityCheck() const { vector<int> used(f_.size(), 0); int ac = 0; for (int i = 0; i < e_.size(); ++i) { int ind = e_[i]; if (ind > 0) continue; ind = -ind; if ((++used[ind]) != 1) { cerr << "[ERROR] e-side variable index " << (ind+1) << " used more than once!\n"; return false; } ac++; } if (ac != Arity()) { cerr << "[ERROR] e-side arity mismatches f-side\n"; return false; } return true; } void TRule::ComputeArity() { int min = 1; for (vector<WordID>::const_iterator i = e_.begin(); i != e_.end(); ++i) if (*i < min) min = *i; arity_ = 1 - min; } static string AnonymousStrVar(int i) { string res("[v]"); if(!(i <= 0 && i >= -8)) { cerr << "Can't handle more than 9 non-terminals: index=" << (-i) << endl; abort(); } res[1] = '1' - i; return res; } string TRule::AsString(bool verbose) const { ostringstream os; int idx = 0; if (lhs_ && verbose) { os << '[' << TD::Convert(lhs_ * -1) << "] |||"; } for (int i = 0; i < f_.size(); ++i) { const WordID& w = f_[i]; if (w < 0) { int wi = w * -1; ++idx; os << " [" << TD::Convert(wi) << ',' << idx << ']'; } else { os << ' ' << TD::Convert(w); } } os << " ||| "; if (idx > 9) { cerr << "Too many non-terminals!\n partial: " << os.str() << endl; exit(1); } for (int i =0; i<e_.size(); ++i) { if (i) os << ' '; const WordID& w = e_[i]; if (w < 1) os << AnonymousStrVar(w); else os << TD::Convert(w); } if (!scores_.empty() && verbose) { os << " ||| " << scores_; if (!a_.empty()) { os << " |||"; for (int i = 0; i < a_.size(); ++i) os << ' ' << a_[i]; } } return os.str(); }
print word alignments in rule
print word alignments in rule
C++
apache-2.0
pks/cdec-dtrain,redpony/cdec,carhaas/cdec-semparse,m5w/atools,redpony/cdec,pks/cdec-dtrain,veer66/cdec,veer66/cdec,pks/cdec-dtrain,pks/cdec-dtrain,redpony/cdec,carhaas/cdec-semparse,pks/cdec-dtrain,m5w/atools,pks/cdec-dtrain,redpony/cdec,redpony/cdec,veer66/cdec,carhaas/cdec-semparse,veer66/cdec,carhaas/cdec-semparse,carhaas/cdec-semparse,redpony/cdec,veer66/cdec,m5w/atools,carhaas/cdec-semparse,veer66/cdec
639733baabd52a0bf286ba9651514e783d5bf5d6
targets/FreeRTOS/ESP32_DevKitC/nanoCLR/nanoFramework.Hardware.ESP32/nanoFramework_hardware_esp32_native.cpp
targets/FreeRTOS/ESP32_DevKitC/nanoCLR/nanoFramework.Hardware.ESP32/nanoFramework_hardware_esp32_native.cpp
// // Copyright (c) 2018 The nanoFramework project contributors // Portions Copyright (c) Microsoft Corporation. All rights reserved. // See LICENSE file in the project root for full license information. // #include "nanoFramework_hardware_esp32_native.h" static const CLR_RT_MethodHandler method_lookup[] = { NULL, NULL, NULL, Library_nanoFramework_hardware_esp32_native_nanoFramework_Hardware_Esp32_Logging::NativeSetLogLevel___STATIC__VOID__STRING__I4, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, Library_nanoFramework_hardware_esp32_native_nanoFramework_Hardware_Esp32_Sleep::NativeEnableWakeupByTimer___STATIC__nanoFrameworkHardwareEsp32EspNativeError__U8, Library_nanoFramework_hardware_esp32_native_nanoFramework_Hardware_Esp32_Sleep::NativeEnableWakeupByPin___STATIC__nanoFrameworkHardwareEsp32EspNativeError__nanoFrameworkHardwareEsp32SleepWakeupGpioPin__I4, Library_nanoFramework_hardware_esp32_native_nanoFramework_Hardware_Esp32_Sleep::NativeEnableWakeupByMultiPins___STATIC__nanoFrameworkHardwareEsp32EspNativeError__nanoFrameworkHardwareEsp32SleepWakeupGpioPin__nanoFrameworkHardwareEsp32SleepWakeupMode, Library_nanoFramework_hardware_esp32_native_nanoFramework_Hardware_Esp32_Sleep::NativeEnableWakeupByTouchPad___STATIC__nanoFrameworkHardwareEsp32EspNativeError, Library_nanoFramework_hardware_esp32_native_nanoFramework_Hardware_Esp32_Sleep::NativeStartLightSleep___STATIC__nanoFrameworkHardwareEsp32EspNativeError, Library_nanoFramework_hardware_esp32_native_nanoFramework_Hardware_Esp32_Sleep::NativeStartDeepSleep___STATIC__nanoFrameworkHardwareEsp32EspNativeError, Library_nanoFramework_hardware_esp32_native_nanoFramework_Hardware_Esp32_Sleep::NativeGetWakeupCause___STATIC__nanoFrameworkHardwareEsp32SleepWakeupCause, Library_nanoFramework_hardware_esp32_native_nanoFramework_Hardware_Esp32_Sleep::NativeGetWakeupGpioPin___STATIC__nanoFrameworkHardwareEsp32SleepWakeupGpioPin, Library_nanoFramework_hardware_esp32_native_nanoFramework_Hardware_Esp32_Sleep::NativeGetWakeupTouchpad___STATIC__nanoFrameworkHardwareEsp32SleepTouchPad, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, Library_nanoFramework_hardware_esp32_native_nanoFramework_Hardware_Esp32_HighResTimer::NativeEspTimerCreate___I4, Library_nanoFramework_hardware_esp32_native_nanoFramework_Hardware_Esp32_HighResTimer::NativeEspTimerDispose___VOID, Library_nanoFramework_hardware_esp32_native_nanoFramework_Hardware_Esp32_HighResTimer::NativeStop___VOID, Library_nanoFramework_hardware_esp32_native_nanoFramework_Hardware_Esp32_HighResTimer::NativeStartOneShot___VOID__U8, Library_nanoFramework_hardware_esp32_native_nanoFramework_Hardware_Esp32_HighResTimer::NativeStartPeriodic___VOID__U8, NULL, Library_nanoFramework_hardware_esp32_native_nanoFramework_Hardware_Esp32_HighResTimer::NativeGetCurrent___STATIC__U8, NULL, NULL, NULL, NULL, NULL, NULL, }; const CLR_RT_NativeAssemblyData g_CLR_AssemblyNative_nanoFramework_Hardware_Esp32 = { "nanoFramework.Hardware.Esp32", 0xFF4537C1, method_lookup, { 1, 0, 0, 0 } };
// // Copyright (c) 2018 The nanoFramework project contributors // Portions Copyright (c) Microsoft Corporation. All rights reserved. // See LICENSE file in the project root for full license information. // #include "nanoFramework_hardware_esp32_native.h" static const CLR_RT_MethodHandler method_lookup[] = { NULL, NULL, NULL, Library_nanoFramework_hardware_esp32_native_nanoFramework_Hardware_Esp32_Logging::NativeSetLogLevel___STATIC__VOID__STRING__I4, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, Library_nanoFramework_hardware_esp32_native_nanoFramework_Hardware_Esp32_Sleep::NativeEnableWakeupByTimer___STATIC__nanoFrameworkHardwareEsp32EspNativeError__U8, Library_nanoFramework_hardware_esp32_native_nanoFramework_Hardware_Esp32_Sleep::NativeEnableWakeupByPin___STATIC__nanoFrameworkHardwareEsp32EspNativeError__nanoFrameworkHardwareEsp32SleepWakeupGpioPin__I4, Library_nanoFramework_hardware_esp32_native_nanoFramework_Hardware_Esp32_Sleep::NativeEnableWakeupByMultiPins___STATIC__nanoFrameworkHardwareEsp32EspNativeError__nanoFrameworkHardwareEsp32SleepWakeupGpioPin__nanoFrameworkHardwareEsp32SleepWakeupMode, Library_nanoFramework_hardware_esp32_native_nanoFramework_Hardware_Esp32_Sleep::NativeEnableWakeupByTouchPad___STATIC__nanoFrameworkHardwareEsp32EspNativeError, Library_nanoFramework_hardware_esp32_native_nanoFramework_Hardware_Esp32_Sleep::NativeStartLightSleep___STATIC__nanoFrameworkHardwareEsp32EspNativeError, Library_nanoFramework_hardware_esp32_native_nanoFramework_Hardware_Esp32_Sleep::NativeStartDeepSleep___STATIC__nanoFrameworkHardwareEsp32EspNativeError, Library_nanoFramework_hardware_esp32_native_nanoFramework_Hardware_Esp32_Sleep::NativeGetWakeupCause___STATIC__nanoFrameworkHardwareEsp32SleepWakeupCause, Library_nanoFramework_hardware_esp32_native_nanoFramework_Hardware_Esp32_Sleep::NativeGetWakeupGpioPin___STATIC__nanoFrameworkHardwareEsp32SleepWakeupGpioPin, Library_nanoFramework_hardware_esp32_native_nanoFramework_Hardware_Esp32_Sleep::NativeGetWakeupTouchpad___STATIC__nanoFrameworkHardwareEsp32SleepTouchPad, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, Library_nanoFramework_hardware_esp32_native_nanoFramework_Hardware_Esp32_HighResTimer::NativeEspTimerCreate___I4, Library_nanoFramework_hardware_esp32_native_nanoFramework_Hardware_Esp32_HighResTimer::NativeEspTimerDispose___VOID, Library_nanoFramework_hardware_esp32_native_nanoFramework_Hardware_Esp32_HighResTimer::NativeStop___VOID, Library_nanoFramework_hardware_esp32_native_nanoFramework_Hardware_Esp32_HighResTimer::NativeStartOneShot___VOID__U8, Library_nanoFramework_hardware_esp32_native_nanoFramework_Hardware_Esp32_HighResTimer::NativeStartPeriodic___VOID__U8, NULL, Library_nanoFramework_hardware_esp32_native_nanoFramework_Hardware_Esp32_HighResTimer::NativeGetCurrent___STATIC__U8, NULL, NULL, NULL, NULL, NULL, NULL, }; const CLR_RT_NativeAssemblyData g_CLR_AssemblyNative_nanoFramework_Hardware_Esp32 = { "nanoFramework.Hardware.Esp32", 0xFF4537C1, method_lookup, { 1, 0, 2, 4 } };
Update nanoFramework.Hardware.Esp32 version to 1.0.2-preview-004 (#968)
Update nanoFramework.Hardware.Esp32 version to 1.0.2-preview-004 (#968)
C++
mit
nanoframework/nf-interpreter,Eclo/nf-interpreter,Eclo/nf-interpreter,nanoframework/nf-interpreter,Eclo/nf-interpreter,Eclo/nf-interpreter,nanoframework/nf-interpreter,nanoframework/nf-interpreter
8d11ec9820c3b46fd6d8aa0c34e1ec0085e3de31
physics/ephemeris_test.cpp
physics/ephemeris_test.cpp
#include "physics/ephemeris.hpp" #include "geometry/frame.hpp" #include "gtest/gtest.h" #include "integrators/symplectic_runge_kutta_nyström_integrator.hpp" #include "quantities/si.hpp" #include "serialization/geometry.pb.h" namespace principia { using integrators::BlanesMoan2002SRKN11B; using si::Metre; using si::Second; namespace physics { class EphemerisTest : public testing::Test { protected: using World = Frame<serialization::Frame::TestTag, serialization::Frame::TEST1, true>; EphemerisTest() : ephemeris_(std::vector<not_null<std::unique_ptr<MassiveBody>>>(), std::vector<DegreesOfFreedom<World>>(), t0_, BlanesMoan2002SRKN11B<Position<World>>(), 1 * Second, 1 * Metre, 10 * Metre) {} Ephemeris<World> ephemeris_; Instant t0_; }; TEST_F(EphemerisTest, Test) { ephemeris_.Prolong(t0_ + 2 * Second); } } // namespace physics } // namespace principia
#include "physics/ephemeris.hpp" #include "geometry/frame.hpp" #include "gtest/gtest.h" #include "integrators/symplectic_runge_kutta_nyström_integrator.hpp" #include "quantities/elementary_functions.hpp" #include "quantities/si.hpp" #include "serialization/geometry.pb.h" namespace principia { using integrators::McLachlanAtela1992Order5Optimal; using quantities::Pow; using quantities::Sqrt; using si::Kilogram; using si::Metre; using si::Second; namespace physics { class EphemerisTest : public testing::Test { protected: using EarthMoonOrbitPlane = Frame<serialization::Frame::TestTag, serialization::Frame::TEST, true>; EphemerisTest() : ephemeris_(std::vector<not_null<std::unique_ptr<MassiveBody>>>(), std::vector<DegreesOfFreedom<EarthMoonOrbitPlane>>(), t0_, McLachlanAtela1992Order5Optimal<Position<EarthMoonOrbitPlane>>(), 1 * Second, 1 * Metre, 10 * Metre) { } void SetUpEarthMoonSystem( not_null<std::vector<not_null<std::unique_ptr<MassiveBody>>>*> const bodies, not_null<std::vector<DegreesOfFreedom<EarthMoonOrbitPlane>>*> const initial_state, not_null<Position<EarthMoonOrbitPlane>*> const centre_of_mass, not_null<Time*> const period) { auto earth = std::make_unique<MassiveBody>(6E24 * Kilogram); auto moon = std::make_unique<MassiveBody>(7E22 * Kilogram); // The Earth-Moon system, roughly, with a circular orbit with velocities // in the centre-of-mass frame. Position<EarthMoonOrbitPlane> const q1( Vector<Length, EarthMoonOrbitPlane>({0 * Metre, 0 * Metre, 0 * Metre})); Position<EarthMoonOrbitPlane> const q2( Vector<Length, EarthMoonOrbitPlane>({0 * Metre, 4E8 * Metre, 0 * Metre})); Length const semi_major_axis = (q1 - q2).Norm(); *period = 2 * π * Sqrt(Pow<3>(semi_major_axis) / (earth->gravitational_parameter() + moon->gravitational_parameter())); *centre_of_mass = geometry::Barycentre<Vector<Length, EarthMoonOrbitPlane>, Mass>( {q1, q2}, {earth->mass(), moon->mass()}); Velocity<EarthMoonOrbitPlane> const v1( {-2 * π * (q1 - *centre_of_mass).Norm() / *period, 0 * SIUnit<Speed>(), 0 * SIUnit<Speed>()}); Velocity<EarthMoonOrbitPlane> const v2( {2 * π * (q2 - *centre_of_mass).Norm() / *period, 0 * SIUnit<Speed>(), 0 * SIUnit<Speed>()}); bodies->push_back(std::move(earth)); bodies->push_back(std::move(moon)); initial_state->push_back(DegreesOfFreedom<EarthMoonOrbitPlane>(q1, v1)); initial_state->push_back(DegreesOfFreedom<EarthMoonOrbitPlane>(q2, v2)); } Ephemeris<EarthMoonOrbitPlane> ephemeris_; Instant t0_; }; // The canonical Earth-Moon system, tuned to produce circular orbits. TEST_F(EphemerisTest, EarthMoon) { std::vector<Vector<Length, EarthMoonOrbitPlane>> positions; system_->Integrate(*integrator_, trajectory1_->last().time() + period_, period_ / 100, 1, // sampling_period false, // tmax_is_exact {trajectory1_.get(), trajectory2_.get()}); positions = ValuesOf(trajectory1_->Positions(), centre_of_mass_); EXPECT_THAT(positions.size(), Eq(101)); LOG(INFO) << ToMathematicaString(positions); EXPECT_THAT(Abs(positions[25].coordinates().y), Lt(3E-2 * SIUnit<Length>())); EXPECT_THAT(Abs(positions[50].coordinates().x), Lt(3E-2 * SIUnit<Length>())); EXPECT_THAT(Abs(positions[75].coordinates().y), Lt(3E-2 * SIUnit<Length>())); EXPECT_THAT(Abs(positions[100].coordinates().x), Lt(3E-2 * SIUnit<Length>())); positions = ValuesOf(trajectory2_->Positions(), centre_of_mass_); LOG(INFO) << ToMathematicaString(positions); EXPECT_THAT(positions.size(), Eq(101)); EXPECT_THAT(Abs(positions[25].coordinates().y), Lt(2 * SIUnit<Length>())); EXPECT_THAT(Abs(positions[50].coordinates().x), Lt(2 * SIUnit<Length>())); EXPECT_THAT(Abs(positions[75].coordinates().y), Lt(2 * SIUnit<Length>())); EXPECT_THAT(Abs(positions[100].coordinates().x), Lt(2 * SIUnit<Length>())); } TEST_F(EphemerisTest, Test) { ephemeris_.Prolong(t0_ + 2 * Second); } } // namespace physics } // namespace principia
Test skeleton.
Test skeleton.
C++
mit
eggrobin/Principia,pleroy/Principia,Norgg/Principia,pleroy/Principia,pleroy/Principia,mockingbirdnest/Principia,pleroy/Principia,mockingbirdnest/Principia,eggrobin/Principia,Norgg/Principia,mockingbirdnest/Principia,mockingbirdnest/Principia,Norgg/Principia,eggrobin/Principia,Norgg/Principia
9f381d6003bf97939897bb0899170a0aa05b0681
libcaf_net/caf/net/middleman.hpp
libcaf_net/caf/net/middleman.hpp
/****************************************************************************** * ____ _ _____ * * / ___| / \ | ___| C++ * * | | / _ \ | |_ Actor * * | |___ / ___ \| _| Framework * * \____/_/ \_|_| * * * * Copyright 2011-2019 Dominik Charousset * * * * Distributed under the terms and conditions of the BSD 3-Clause License or * * (at your option) under the terms and conditions of the Boost Software * * License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. * * * * If you did not receive a copy of the license files, see * * http://opensource.org/licenses/BSD-3-Clause and * * http://www.boost.org/LICENSE_1_0.txt. * ******************************************************************************/ #pragma once #include <thread> #include "caf/actor_system.hpp" #include "caf/detail/net_export.hpp" #include "caf/detail/type_list.hpp" #include "caf/fwd.hpp" #include "caf/net/fwd.hpp" namespace caf::net { class CAF_NET_EXPORT middleman : public actor_system::module { public: // -- member types ----------------------------------------------------------- using module = actor_system::module; using module_ptr = actor_system::module_ptr; using middleman_backend_list = std::vector<middleman_backend_ptr>; // -- static utility functions ----------------------------------------------- static void init_global_meta_objects(); // -- constructors, destructors, and assignment operators -------------------- ~middleman() override; // -- interface functions ---------------------------------------------------- void start() override; void stop() override; void init(actor_system_config&) override; id_t id() const override; void* subtype_ptr() override; // -- factory functions ------------------------------------------------------ template <class... Ts> static module* make(actor_system& sys, detail::type_list<Ts...> token) { std::unique_ptr<middleman> result{new middleman(sys)}; if (sizeof...(Ts) > 0) { result->backends_.reserve(sizeof...(Ts)); create_backends(*result, token); } return result.release(); } // -- remoting --------------------------------------------------------------- /// Resolves a path to a remote actor. void resolve(const uri& locator, const actor& listener); // -- properties ------------------------------------------------------------- actor_system& system() { return sys_; } const actor_system_config& config() const noexcept { return sys_.config(); } const multiplexer_ptr& mpx() const noexcept { return mpx_; } middleman_backend* backend(string_view scheme) const noexcept; private: // -- constructors, destructors, and assignment operators -------------------- explicit middleman(actor_system& sys); // -- utility functions ------------------------------------------------------ static void create_backends(middleman&, detail::type_list<>) { // End of recursion. } template <class T, class... Ts> static void create_backends(middleman& mm, detail::type_list<T, Ts...>) { mm.backends_.emplace_back(new T(mm)); create_backends(mm, detail::type_list<Ts...>{}); } // -- member variables ------------------------------------------------------- /// Points to the parent system. actor_system& sys_; /// Stores the global socket I/O multiplexer. multiplexer_ptr mpx_; /// Stores all available backends for managing peers. middleman_backend_list backends_; /// Runs the multiplexer's event loop std::thread mpx_thread_; }; } // namespace caf::net
/****************************************************************************** * ____ _ _____ * * / ___| / \ | ___| C++ * * | | / _ \ | |_ Actor * * | |___ / ___ \| _| Framework * * \____/_/ \_|_| * * * * Copyright 2011-2019 Dominik Charousset * * * * Distributed under the terms and conditions of the BSD 3-Clause License or * * (at your option) under the terms and conditions of the Boost Software * * License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. * * * * If you did not receive a copy of the license files, see * * http://opensource.org/licenses/BSD-3-Clause and * * http://www.boost.org/LICENSE_1_0.txt. * ******************************************************************************/ #pragma once #include <set> #include <string> #include <thread> #include "caf/actor_system.hpp" #include "caf/detail/net_export.hpp" #include "caf/detail/type_list.hpp" #include "caf/fwd.hpp" #include "caf/net/fwd.hpp" #include "caf/net/middleman_backend.hpp" #include "caf/scoped_actor.hpp" namespace caf::net { class CAF_NET_EXPORT middleman : public actor_system::module { public: // -- member types ----------------------------------------------------------- using module = actor_system::module; using module_ptr = actor_system::module_ptr; using middleman_backend_list = std::vector<middleman_backend_ptr>; // -- static utility functions ----------------------------------------------- static void init_global_meta_objects(); // -- constructors, destructors, and assignment operators -------------------- ~middleman() override; // -- interface functions ---------------------------------------------------- void start() override; void stop() override; void init(actor_system_config&) override; id_t id() const override; void* subtype_ptr() override; // -- factory functions ------------------------------------------------------ template <class... Ts> static module* make(actor_system& sys, detail::type_list<Ts...> token) { std::unique_ptr<middleman> result{new middleman(sys)}; if (sizeof...(Ts) > 0) { result->backends_.reserve(sizeof...(Ts)); create_backends(*result, token); } return result.release(); } // -- remoting --------------------------------------------------------------- // Publishes an actor. template <class Handle = actor> error publish(Handle whom, const uri& locator) { auto be = backend(locator.scheme()); be->publish(whom, locator); } /// Resolves a path to a remote actor. void resolve(const uri& locator, const actor& listener); template <class Handle> expected<Handle> remote_actor(const uri& locator) { // TODO: Use function view? scoped_actor self{sys_}; resolve(locator, self); strong_actor_ptr actor_ptr; error err = none; self->receive( [&actor_ptr](strong_actor_ptr& ptr, const std::set<std::string>&) { actor_ptr = ptr; }, [&err](const error& e) { err = e; }); if (err) return err; auto res = actor_cast<Handle>(actor_ptr); if (res) return res; else return make_error(sec::runtime_error, "cannot cast actor to specified type"); } // -- properties ------------------------------------------------------------- actor_system& system() { return sys_; } const actor_system_config& config() const noexcept { return sys_.config(); } const multiplexer_ptr& mpx() const noexcept { return mpx_; } middleman_backend* backend(string_view scheme) const noexcept; private: // -- constructors, destructors, and assignment operators -------------------- explicit middleman(actor_system& sys); // -- utility functions ------------------------------------------------------ static void create_backends(middleman&, detail::type_list<>) { // End of recursion. } template <class T, class... Ts> static void create_backends(middleman& mm, detail::type_list<T, Ts...>) { mm.backends_.emplace_back(new T(mm)); create_backends(mm, detail::type_list<Ts...>{}); } // -- member variables ------------------------------------------------------- /// Points to the parent system. actor_system& sys_; /// Stores the global socket I/O multiplexer. multiplexer_ptr mpx_; /// Stores all available backends for managing peers. middleman_backend_list backends_; /// Runs the multiplexer's event loop std::thread mpx_thread_; }; } // namespace caf::net
Implement missing api in middleman
Implement missing api in middleman
C++
bsd-3-clause
actor-framework/actor-framework,actor-framework/actor-framework,DavadDi/actor-framework,actor-framework/actor-framework,DavadDi/actor-framework,DavadDi/actor-framework,actor-framework/actor-framework,DavadDi/actor-framework
b07a404de42b4b0908f49df20679c31263def130
desktop/Pool.cpp
desktop/Pool.cpp
#include "Pool.h" #include <iostream> #include <math.h> const float Pool::BALL_RADIUS = 0.5/40; void Pool::setWhiteBall(Vec2 whiteBall) { this->whiteBall = whiteBall; } void Pool::setTargetBall(Vec2 targetBall) { this->targetBall = targetBall; } void Pool::setPocket(Vec2 pocket) { this->pocket = pocket; } float Pool::getHitAngle() { std::cout << whiteBall.getString() << std::endl; //Calculating the angle of the vector that the target needs to travel Vec2 targetDiff = pocket - targetBall; float targetAngle = targetDiff.getAngle(); //Calculating where the white needs to be when it hits Vec2 whiteTarget(BALL_RADIUS * cos(targetAngle - M_PI), BALL_RADIUS * sin(targetAngle - M_PI)); whiteTarget += targetBall; Vec2 finalDiff = whiteTarget - whiteBall; return finalDiff.getAngle(); } Vec2 Pool::getWhiteBall() { return whiteBall; }
#include "Pool.h" #include <iostream> #include <math.h> const float Pool::BALL_RADIUS = 0.5/40; void Pool::setWhiteBall(Vec2 whiteBall) { this->whiteBall = whiteBall; } void Pool::setTargetBall(Vec2 targetBall) { this->targetBall = targetBall; } void Pool::setPocket(Vec2 pocket) { this->pocket = pocket; } float Pool::getHitAngle() { std::cout << whiteBall.getString() << std::endl; //Calculating the angle of the vector that the target needs to travel Vec2 targetDiff = pocket - targetBall; float targetAngle = targetDiff.getAngle(); //Calculating where the white needs to be when it hits Vec2 whiteTarget(BALL_RADIUS * 2 * cos(targetAngle - M_PI), BALL_RADIUS * 2 * sin(targetAngle - M_PI)); whiteTarget += targetBall; Vec2 finalDiff = whiteTarget - whiteBall; return finalDiff.getAngle(); } Vec2 Pool::getWhiteBall() { return whiteBall; }
Fix bug in ball collision code where line would be placed incorrectly
Fix bug in ball collision code where line would be placed incorrectly
C++
mit
TheZoq2/Raspi-ImageProcessing,TheZoq2/Raspi-ImageProcessing,TheZoq2/Raspi-ImageProcessing
d9f1c9827485e5ccaa6d9d93c4427ae8b7c310fc
imaging/vtkImageFilter.cxx
imaging/vtkImageFilter.cxx
/*========================================================================= Program: Visualization Toolkit Module: vtkImageFilter.cxx Language: C++ Date: $Date$ Version: $Revision$ Thanks: Thanks to C. Charles Law who developed this class. Copyright (c) 1993-1995 Ken Martin, Will Schroeder, Bill Lorensen. This software is copyrighted by Ken Martin, Will Schroeder and Bill Lorensen. The following terms apply to all files associated with the software unless explicitly disclaimed in individual files. This copyright specifically does not apply to the related textbook "The Visualization Toolkit" ISBN 013199837-4 published by Prentice Hall which is covered by its own copyright. The authors hereby grant permission to use, copy, and distribute this software and its documentation for any purpose, provided that existing copyright notices are retained in all copies and that this notice is included verbatim in any distributions. Additionally, the authors grant permission to modify this software and its documentation for any purpose, provided that such modifications are not distributed without the explicit consent of the authors and that existing copyright notices are retained in all copies. Some of the algorithms implemented by this software are patented, observe all applicable patent law. IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF, EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. =========================================================================*/ #include "vtkTimerLog.h" #include "vtkImageRegion.h" #include "vtkImageCache.h" #include "vtkImageFilter.h" //---------------------------------------------------------------------------- vtkImageFilter::vtkImageFilter() { this->FilteredAxes[0] = VTK_IMAGE_X_AXIS; this->FilteredAxes[1] = VTK_IMAGE_Y_AXIS; this->FilteredAxes[2] = VTK_IMAGE_Z_AXIS; this->FilteredAxes[3] = VTK_IMAGE_TIME_AXIS; this->NumberOfFilteredAxes = 2; this->Input = NULL; this->SplitOrder[0] = VTK_IMAGE_COMPONENT_AXIS; this->SplitOrder[1] = VTK_IMAGE_TIME_AXIS; this->SplitOrder[2] = VTK_IMAGE_Z_AXIS; this->SplitOrder[3] = VTK_IMAGE_Y_AXIS; this->SplitOrder[4] = VTK_IMAGE_X_AXIS; this->NumberOfSplitAxes = 5; this->InputMemoryLimit = 5000000; // 5 GB this->Bypass = 0; this->Updating = 0; // invalid settings this->NumberOfExecutionAxes = -1; } //---------------------------------------------------------------------------- void vtkImageFilter::PrintSelf(ostream& os, vtkIndent indent) { int idx; os << indent << "FilteredAxes: "; if (this->NumberOfFilteredAxes == 0) { os << indent << "None\n"; } else { os << indent << "(" << vtkImageAxisNameMacro(this->FilteredAxes[0]); for (idx = 1; idx < this->NumberOfFilteredAxes; ++idx) { os << ", " << vtkImageAxisNameMacro(this->FilteredAxes[idx]); } os << ")\n"; } os << indent << "Bypass: " << this->Bypass << "\n"; os << indent << "Input: (" << this->Input << ").\n"; os << indent << "SplitOrder: ("<< vtkImageAxisNameMacro(this->SplitOrder[0]); for (idx = 1; idx < VTK_IMAGE_DIMENSIONS; ++idx) { os << ", " << vtkImageAxisNameMacro(this->SplitOrder[idx]); } os << ")\n"; vtkImageSource::PrintSelf(os,indent); } //---------------------------------------------------------------------------- void vtkImageFilter::SetFilteredAxes(int num, int *axes) { int idx; int modified = 0; if (num > 4) { vtkWarningMacro("SetFilteredAxes: Too many axes"); num = 4; } for (idx = 0; idx < num; ++idx) { if (this->FilteredAxes[idx] != axes[idx]) { modified = 1; this->FilteredAxes[idx] = axes[idx]; } } if (num != this->NumberOfFilteredAxes) { modified = 1; this->NumberOfFilteredAxes = num; } if (modified) { this->Modified(); } this->SetExecutionAxes(num, this->FilteredAxes); } //---------------------------------------------------------------------------- // Description: // This Method returns the MTime of the pipeline upto and including this filter // Note: current implementation may create a cascade of GetPipelineMTime calls. // Each GetPipelineMTime call propagates the call all the way to the original // source. unsigned long int vtkImageFilter::GetPipelineMTime() { unsigned long int time1, time2; // This objects MTime // (Super class considers cache in case cache did not originate message) time1 = this->vtkImageSource::GetPipelineMTime(); if ( ! this->Input) { vtkWarningMacro(<< "GetPipelineMTime: Input not set."); return time1; } // Pipeline mtime time2 = this->Input->GetPipelineMTime(); // Return the larger of the two if (time2 > time1) time1 = time2; return time1; } //---------------------------------------------------------------------------- // Description: // Set the Input of a filter. void vtkImageFilter::SetInput(vtkImageCache *input) { vtkDebugMacro(<< "SetInput: input = " << input->GetClassName() << " (" << input << ")"); // does this change anything? if (input == this->Input) { return; } this->Input = input; this->Modified(); } //---------------------------------------------------------------------------- // Description: // This method is called by the cache. It eventually calls the // Execute(vtkImageRegion *, vtkImageRegion *) method. // ImageInformation has already been updated by this point, // and outRegion is in local coordinates. // This method will stream to get the input, and loops over extra axes. // Only the UpdateExtent from output will get updated. void vtkImageFilter::InternalUpdate() { vtkImageRegion *outRegion; // Make sure the Input has been set. if ( ! this->Input) { vtkErrorMacro(<< "Input is not set."); return; } // prevent infinite update loops. if (this->Updating) { return; } this->Updating = 1; // Make sure there is an output. this->CheckCache(); // In case this update is called directly. this->UpdateImageInformation(); this->Output->ClipUpdateExtentWithWholeExtent(); // Handle bypass condition. if (this->Bypass) { this->Input->SetUpdateExtent(this->Output->GetUpdateExtent()); this->Input->Update(); this->Output->CacheScalarData(this->Input->GetScalarData()); this->Output->SetNumberOfScalarComponents( this->Input->GetNumberOfScalarComponents()); // release input data if (this->Input->ShouldIReleaseData()) { this->Input->ReleaseData(); } this->Updating = 0; return; } // Make sure the subclss has defined the execute dimensionality // It is needed to terminate recursion. if (this->NumberOfExecutionAxes < 0) { vtkErrorMacro(<< "Subclass has not set NumberOfExecutionAxes"); return; } // Get the output region. // Note: outRegion does not allocate until first "GetScalarPointer" call outRegion = this->Output->GetScalarRegion(); outRegion->SetAxes(5, this->ExecutionAxes); // If outBBox is empty return immediately. if (outRegion->IsEmpty()) { outRegion->Delete(); this->Updating = 0; return; } // Fill in image information (ComputeRequiredInputExtent may need it) this->Input->UpdateImageInformation(); // Pass on to a method that can be called recursively (for streaming). this->RecursiveStreamUpdate(outRegion); // free the output region (cache has a reference to the data.) outRegion->Delete(); this->Updating = 0; } //---------------------------------------------------------------------------- // Description: // This method can be called recursively for streaming. // The extent of the outRegion changes, dim remains the same. void vtkImageFilter::RecursiveStreamUpdate(vtkImageRegion *outRegion) { int memory; vtkImageRegion *inRegion; //vtkTimerLogMacro("Entering Update"); // Compute the required input region extent. // Copy to fill in extent of extra dimensions. this->Input->SetUpdateExtent(this->Output->GetUpdateExtent()); this->ComputeRequiredInputUpdateExtent(); // determine the amount of memory that will be used by the input region. memory = this->Input->GetUpdateExtentMemorySize(); // Split the outRegion if we are streaming. if ((memory > this->InputMemoryLimit)) { int splitAxisIdx, splitAxis; int min, max, mid; // We need to split the output into pieces. // It is convenient the outRegion has its own copy of output UpdateExtent. // Pick an axis to split. splitAxisIdx = 0; splitAxis = this->SplitOrder[splitAxisIdx]; outRegion->GetAxisExtent(splitAxis, min, max); while ( (min == max) && splitAxisIdx < this->NumberOfSplitAxes) { ++splitAxisIdx; splitAxis = this->SplitOrder[splitAxisIdx]; outRegion->GetAxisExtent(splitAxis, min, max); } // Make sure we can actually split the axis if (min < max) { // Set the first half to update mid = (min + max) / 2; vtkDebugMacro(<< "RecursiveStreamUpdate: Splitting " << vtkImageAxisNameMacro(splitAxis) << ": memory = " << memory << ", extent = " << min << "->" << mid << " | " << mid+1 << "->" << max); outRegion->SetAxisExtent(splitAxis, min, mid); this->Output->SetAxisUpdateExtent(splitAxis, min, mid); this->RecursiveStreamUpdate(outRegion); // Set the second half to update this->Output->SetAxisUpdateExtent(splitAxis, mid+1, max); outRegion->SetAxisExtent(splitAxis, mid+1, max); this->RecursiveStreamUpdate(outRegion); // Restore the original extent outRegion->SetAxisExtent(splitAxis, min, max); this->Output->SetAxisUpdateExtent(splitAxis, min, max); return; } else { // Cannot split any more. Ignore memory limit and continue. vtkWarningMacro(<< "UpdatePointData2: Cannot split. memory = " << memory << ", limit = " << this->InputMemoryLimit << ", " << vtkImageAxisNameMacro(splitAxis) << ": " << min << "->" << max); } } // No Streaming required. // Get the input region (Update extent was set at start of this method). this->Input->Update(); inRegion = this->Input->GetScalarRegion(); inRegion->SetAxes(5, this->ExecutionAxes); // Make sure we got the input. if ( ! inRegion->AreScalarsAllocated()) { vtkErrorMacro("RecursiveStreamUpdate: Could not get input"); inRegion->Delete(); return; } // The StartMethod call is placed here to be after updating the input. if ( this->StartMethod ) (*this->StartMethod)(this->StartMethodArg); // fill the output region this->RecursiveLoopExecute(VTK_IMAGE_DIMENSIONS, inRegion, outRegion); if ( this->EndMethod ) (*this->EndMethod)(this->EndMethodArg); // inRegion is just a handle to the data. inRegion->Delete(); // Like the graphics pipeline this source releases inputs data. if (this->Input->ShouldIReleaseData()) { this->Input->ReleaseData(); } } //---------------------------------------------------------------------------- // Description: // This method sets the WholeExtent, Spacing and Origin of the output. void vtkImageFilter::UpdateImageInformation() { // Make sure the Input has been set. if ( ! this->Input) { vtkErrorMacro(<< "UpdateImageInformation: Input is not set."); return; } // make sure we have an output this->CheckCache(); this->Input->UpdateImageInformation(); // Set up the defaults this->Output->SetWholeExtent(this->Input->GetWholeExtent()); this->Output->SetSpacing(this->Input->GetSpacing()); this->Output->SetOrigin(this->Input->GetOrigin()); this->Output->SetNumberOfScalarComponents( this->Input->GetNumberOfScalarComponents()); if ( ! this->Bypass) { // Let the subclass modify the default. this->ExecuteImageInformation(); } // If the ScalarType of the output has not been set yet, // set it to be the same as input. if (this->Output->GetScalarType() == VTK_VOID) { this->Output->SetScalarType(this->Input->GetScalarType()); } } //---------------------------------------------------------------------------- // Description: // This method can be overriden in a subclass to compute the output // ImageInformation: WholeExtent, Spacing and Origin. void vtkImageFilter::ExecuteImageInformation() { } //---------------------------------------------------------------------------- // Description: // This method can be overriden in a subclass to compute the input // UpdateExtent needed to generate the output UpdateExtent. // By default the input is set to the same as the output before this // method is called. void vtkImageFilter::ComputeRequiredInputUpdateExtent() { } //---------------------------------------------------------------------------- // Description: // This execute method recursively loops over extra dimensions and // calls the subclasses Execute method with lower dimensional regions. // NumberOfExecutionAxes is used to terminate the recursion. void vtkImageFilter::RecursiveLoopExecute(int dim, vtkImageRegion *inRegion, vtkImageRegion *outRegion) { // Terminate recursion? if (dim <= this->NumberOfExecutionAxes) { this->Execute(inRegion, outRegion); return; } else { int coordinate, axis; int inMin, inMax; int outMin, outMax; // Get the extent of the forth dimension to be eliminated. axis = this->ExecutionAxes[dim - 1]; inRegion->GetAxisExtent(axis, inMin, inMax); outRegion->GetAxisExtent(axis, outMin, outMax); // The axis should have the same extent. if (inMin != outMin || inMax != outMax) { vtkErrorMacro(<< "Execute: Extra axis " << vtkImageAxisNameMacro(axis) << " can not be eliminated"); return; } // loop over the samples along the extra axis. for (coordinate = inMin; coordinate <= inMax; ++coordinate) { // set up the lower dimensional regions. inRegion->SetAxisExtent(axis, coordinate, coordinate); outRegion->SetAxisExtent(axis, coordinate, coordinate); if (dim == 3) { this->UpdateProgress ((float) (coordinate - inMin + 1) / (float) (inMax - inMin + 1)); } this->RecursiveLoopExecute(dim - 1, inRegion, outRegion); } // restore the original extent inRegion->SetAxisExtent(axis, inMin, inMax); outRegion->SetAxisExtent(axis, outMin, outMax); } } //---------------------------------------------------------------------------- // Description: // The execute method created by the subclass. void vtkImageFilter::Execute(vtkImageRegion *inRegion, vtkImageRegion *outRegion) { inRegion = outRegion; vtkErrorMacro(<< "Subclass needs to supply an execute function."); } //---------------------------------------------------------------------------- void vtkImageFilter::SetSplitOrder(int num, int *axes) { int idx; // Error checking if (num < 0 || num > VTK_IMAGE_DIMENSIONS) { vtkErrorMacro(<< "SetSplitOrder: Bad num " << num); return; } for (idx = 0; idx < num; ++idx) { this->SplitOrder[idx] = axes[idx]; } this->NumberOfSplitAxes = num; } //---------------------------------------------------------------------------- void vtkImageFilter::GetSplitOrder(int num, int *axes) { int idx; // Error checking if (num < 0 || num > this->NumberOfSplitAxes) { vtkErrorMacro(<< "GetSplitOrder: Bad num " << num); return; } for (idx = 0; idx < num; ++idx) { axes[idx] = this->SplitOrder[idx]; } }
/*========================================================================= Program: Visualization Toolkit Module: vtkImageFilter.cxx Language: C++ Date: $Date$ Version: $Revision$ Thanks: Thanks to C. Charles Law who developed this class. Copyright (c) 1993-1995 Ken Martin, Will Schroeder, Bill Lorensen. This software is copyrighted by Ken Martin, Will Schroeder and Bill Lorensen. The following terms apply to all files associated with the software unless explicitly disclaimed in individual files. This copyright specifically does not apply to the related textbook "The Visualization Toolkit" ISBN 013199837-4 published by Prentice Hall which is covered by its own copyright. The authors hereby grant permission to use, copy, and distribute this software and its documentation for any purpose, provided that existing copyright notices are retained in all copies and that this notice is included verbatim in any distributions. Additionally, the authors grant permission to modify this software and its documentation for any purpose, provided that such modifications are not distributed without the explicit consent of the authors and that existing copyright notices are retained in all copies. Some of the algorithms implemented by this software are patented, observe all applicable patent law. IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF, EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. =========================================================================*/ #include "vtkTimerLog.h" #include "vtkImageRegion.h" #include "vtkImageCache.h" #include "vtkImageFilter.h" //---------------------------------------------------------------------------- vtkImageFilter::vtkImageFilter() { this->FilteredAxes[0] = VTK_IMAGE_X_AXIS; this->FilteredAxes[1] = VTK_IMAGE_Y_AXIS; this->FilteredAxes[2] = VTK_IMAGE_Z_AXIS; this->FilteredAxes[3] = VTK_IMAGE_TIME_AXIS; this->NumberOfFilteredAxes = 2; this->Input = NULL; this->SplitOrder[0] = VTK_IMAGE_COMPONENT_AXIS; this->SplitOrder[1] = VTK_IMAGE_TIME_AXIS; this->SplitOrder[2] = VTK_IMAGE_Z_AXIS; this->SplitOrder[3] = VTK_IMAGE_Y_AXIS; this->SplitOrder[4] = VTK_IMAGE_X_AXIS; this->NumberOfSplitAxes = 5; this->InputMemoryLimit = 5000000; // 5 GB this->Bypass = 0; this->Updating = 0; // invalid settings this->NumberOfExecutionAxes = -1; } //---------------------------------------------------------------------------- void vtkImageFilter::PrintSelf(ostream& os, vtkIndent indent) { int idx; os << indent << "FilteredAxes: "; if (this->NumberOfFilteredAxes == 0) { os << indent << "None\n"; } else { os << indent << "(" << vtkImageAxisNameMacro(this->FilteredAxes[0]); for (idx = 1; idx < this->NumberOfFilteredAxes; ++idx) { os << ", " << vtkImageAxisNameMacro(this->FilteredAxes[idx]); } os << ")\n"; } os << indent << "Bypass: " << this->Bypass << "\n"; os << indent << "Input: (" << this->Input << ").\n"; os << indent << "SplitOrder: ("<< vtkImageAxisNameMacro(this->SplitOrder[0]); for (idx = 1; idx < VTK_IMAGE_DIMENSIONS; ++idx) { os << ", " << vtkImageAxisNameMacro(this->SplitOrder[idx]); } os << ")\n"; vtkImageSource::PrintSelf(os,indent); } //---------------------------------------------------------------------------- void vtkImageFilter::SetFilteredAxes(int num, int *axes) { int idx; int modified = 0; if (num > 4) { vtkWarningMacro("SetFilteredAxes: Too many axes"); num = 4; } for (idx = 0; idx < num; ++idx) { if (this->FilteredAxes[idx] != axes[idx]) { modified = 1; this->FilteredAxes[idx] = axes[idx]; } } if (num != this->NumberOfFilteredAxes) { modified = 1; this->NumberOfFilteredAxes = num; } if (modified) { this->Modified(); } this->SetExecutionAxes(num, this->FilteredAxes); } //---------------------------------------------------------------------------- // Description: // This Method returns the MTime of the pipeline upto and including this filter // Note: current implementation may create a cascade of GetPipelineMTime calls. // Each GetPipelineMTime call propagates the call all the way to the original // source. unsigned long int vtkImageFilter::GetPipelineMTime() { unsigned long int time1, time2; // This objects MTime // (Super class considers cache in case cache did not originate message) time1 = this->vtkImageSource::GetPipelineMTime(); if ( ! this->Input) { vtkWarningMacro(<< "GetPipelineMTime: Input not set."); return time1; } // Pipeline mtime time2 = this->Input->GetPipelineMTime(); // Return the larger of the two if (time2 > time1) time1 = time2; return time1; } //---------------------------------------------------------------------------- // Description: // Set the Input of a filter. void vtkImageFilter::SetInput(vtkImageCache *input) { vtkDebugMacro(<< "SetInput: input = " << input->GetClassName() << " (" << input << ")"); // does this change anything? if (input == this->Input) { return; } this->Input = input; this->Modified(); } //---------------------------------------------------------------------------- // Description: // This method is called by the cache. It eventually calls the // Execute(vtkImageRegion *, vtkImageRegion *) method. // ImageInformation has already been updated by this point, // and outRegion is in local coordinates. // This method will stream to get the input, and loops over extra axes. // Only the UpdateExtent from output will get updated. void vtkImageFilter::InternalUpdate() { vtkImageRegion *outRegion; // Make sure the Input has been set. if ( ! this->Input) { vtkErrorMacro(<< "Input is not set."); return; } // prevent infinite update loops. if (this->Updating) { return; } this->Updating = 1; // Make sure there is an output. this->CheckCache(); // In case this update is called directly. this->UpdateImageInformation(); this->Output->ClipUpdateExtentWithWholeExtent(); // Handle bypass condition. if (this->Bypass) { this->Input->SetUpdateExtent(this->Output->GetUpdateExtent()); this->Input->Update(); this->Output->CacheScalarData(this->Input->GetScalarData()); this->Output->SetNumberOfScalarComponents( this->Input->GetNumberOfScalarComponents()); // release input data if (this->Input->ShouldIReleaseData()) { this->Input->ReleaseData(); } this->Updating = 0; return; } // Make sure the subclss has defined the execute dimensionality // It is needed to terminate recursion. if (this->NumberOfExecutionAxes < 0) { vtkErrorMacro(<< "Subclass has not set NumberOfExecutionAxes"); return; } // Get the output region. // Note: outRegion does not allocate until first "GetScalarPointer" call outRegion = this->Output->GetScalarRegion(); outRegion->SetAxes(5, this->ExecutionAxes); // If outBBox is empty return immediately. if (outRegion->IsEmpty()) { outRegion->Delete(); this->Updating = 0; return; } // Fill in image information (ComputeRequiredInputExtent may need it) this->Input->UpdateImageInformation(); // Pass on to a method that can be called recursively (for streaming). this->RecursiveStreamUpdate(outRegion); // free the output region (cache has a reference to the data.) outRegion->Delete(); this->Updating = 0; } //---------------------------------------------------------------------------- // Description: // This method can be called recursively for streaming. // The extent of the outRegion changes, dim remains the same. void vtkImageFilter::RecursiveStreamUpdate(vtkImageRegion *outRegion) { int memory; vtkImageRegion *inRegion; //vtkTimerLogMacro("Entering Update"); // Compute the required input region extent. // Copy to fill in extent of extra dimensions. this->Input->SetUpdateExtent(this->Output->GetUpdateExtent()); this->ComputeRequiredInputUpdateExtent(); // determine the amount of memory that will be used by the input region. memory = this->Input->GetUpdateExtentMemorySize(); // Split the outRegion if we are streaming. if ((memory > this->InputMemoryLimit)) { int splitAxisIdx, splitAxis; int min, max, mid; // We need to split the output into pieces. // It is convenient the outRegion has its own copy of output UpdateExtent. // Pick an axis to split. splitAxisIdx = 0; splitAxis = this->SplitOrder[splitAxisIdx]; outRegion->GetAxisExtent(splitAxis, min, max); while ( (min == max) && splitAxisIdx < this->NumberOfSplitAxes) { ++splitAxisIdx; splitAxis = this->SplitOrder[splitAxisIdx]; outRegion->GetAxisExtent(splitAxis, min, max); } // Make sure we can actually split the axis if (min < max) { // Set the first half to update mid = (min + max) / 2; vtkDebugMacro(<< "RecursiveStreamUpdate: Splitting " << vtkImageAxisNameMacro(splitAxis) << ": memory = " << memory << ", extent = " << min << "->" << mid << " | " << mid+1 << "->" << max); outRegion->SetAxisExtent(splitAxis, min, mid); this->Output->SetAxisUpdateExtent(splitAxis, min, mid); this->RecursiveStreamUpdate(outRegion); // Set the second half to update this->Output->SetAxisUpdateExtent(splitAxis, mid+1, max); outRegion->SetAxisExtent(splitAxis, mid+1, max); this->RecursiveStreamUpdate(outRegion); // Restore the original extent outRegion->SetAxisExtent(splitAxis, min, max); this->Output->SetAxisUpdateExtent(splitAxis, min, max); return; } else { // Cannot split any more. Ignore memory limit and continue. vtkWarningMacro(<< "UpdatePointData2: Cannot split. memory = " << memory << ", limit = " << this->InputMemoryLimit << ", " << vtkImageAxisNameMacro(splitAxis) << ": " << min << "->" << max); } } // No Streaming required. // Get the input region (Update extent was set at start of this method). this->Input->Update(); inRegion = this->Input->GetScalarRegion(); inRegion->SetAxes(5, this->ExecutionAxes); // Make sure we got the input. if ( ! inRegion->AreScalarsAllocated()) { vtkErrorMacro("RecursiveStreamUpdate: Could not get input"); inRegion->Delete(); return; } // The StartMethod call is placed here to be after updating the input. if ( this->StartMethod ) (*this->StartMethod)(this->StartMethodArg); // fill the output region this->RecursiveLoopExecute(VTK_IMAGE_DIMENSIONS, inRegion, outRegion); if ( this->EndMethod ) (*this->EndMethod)(this->EndMethodArg); // inRegion is just a handle to the data. inRegion->Delete(); // Like the graphics pipeline this source releases inputs data. if (this->Input->ShouldIReleaseData()) { this->Input->ReleaseData(); } } //---------------------------------------------------------------------------- // Description: // This method sets the WholeExtent, Spacing and Origin of the output. void vtkImageFilter::UpdateImageInformation() { // Make sure the Input has been set. if ( ! this->Input) { vtkErrorMacro(<< "UpdateImageInformation: Input is not set."); return; } // make sure we have an output this->CheckCache(); this->Input->UpdateImageInformation(); // Set up the defaults this->Output->SetWholeExtent(this->Input->GetWholeExtent()); this->Output->SetSpacing(this->Input->GetSpacing()); this->Output->SetOrigin(this->Input->GetOrigin()); this->Output->SetNumberOfScalarComponents( this->Input->GetNumberOfScalarComponents()); if ( ! this->Bypass) { // Let the subclass modify the default. this->ExecuteImageInformation(); } // If the ScalarType of the output has not been set yet, // set it to be the same as input. if (this->Output->GetScalarType() == VTK_VOID) { this->Output->SetScalarType(this->Input->GetScalarType()); } } //---------------------------------------------------------------------------- // Description: // This method can be overriden in a subclass to compute the output // ImageInformation: WholeExtent, Spacing and Origin. void vtkImageFilter::ExecuteImageInformation() { } //---------------------------------------------------------------------------- // Description: // This method can be overriden in a subclass to compute the input // UpdateExtent needed to generate the output UpdateExtent. // By default the input is set to the same as the output before this // method is called. void vtkImageFilter::ComputeRequiredInputUpdateExtent() { } //---------------------------------------------------------------------------- // Description: // This execute method recursively loops over extra dimensions and // calls the subclasses Execute method with lower dimensional regions. // NumberOfExecutionAxes is used to terminate the recursion. void vtkImageFilter::RecursiveLoopExecute(int dim, vtkImageRegion *inRegion, vtkImageRegion *outRegion) { // Terminate recursion? if (dim <= this->NumberOfExecutionAxes) { this->Execute(inRegion, outRegion); return; } else { int coordinate, axis; int inMin, inMax; int outMin, outMax; // Get the extent of the forth dimension to be eliminated. axis = this->ExecutionAxes[dim - 1]; inRegion->GetAxisExtent(axis, inMin, inMax); outRegion->GetAxisExtent(axis, outMin, outMax); // The axis should have the same extent. if (inMin != outMin || inMax != outMax) { vtkErrorMacro(<< "Execute: Extra axis " << vtkImageAxisNameMacro(axis) << " can not be eliminated"); return; } // loop over the samples along the extra axis. for (coordinate = inMin; coordinate <= inMax; ++coordinate) { // set up the lower dimensional regions. inRegion->SetAxisExtent(axis, coordinate, coordinate); outRegion->SetAxisExtent(axis, coordinate, coordinate); if (dim == 3) { this->UpdateProgress ((float) (coordinate - inMin + 1) / (float) (inMax - inMin + 1)); if (coordinate == inMax) { this->Progress = 0.0; } } this->RecursiveLoopExecute(dim - 1, inRegion, outRegion); } // restore the original extent inRegion->SetAxisExtent(axis, inMin, inMax); outRegion->SetAxisExtent(axis, outMin, outMax); } } //---------------------------------------------------------------------------- // Description: // The execute method created by the subclass. void vtkImageFilter::Execute(vtkImageRegion *inRegion, vtkImageRegion *outRegion) { inRegion = outRegion; vtkErrorMacro(<< "Subclass needs to supply an execute function."); } //---------------------------------------------------------------------------- void vtkImageFilter::SetSplitOrder(int num, int *axes) { int idx; // Error checking if (num < 0 || num > VTK_IMAGE_DIMENSIONS) { vtkErrorMacro(<< "SetSplitOrder: Bad num " << num); return; } for (idx = 0; idx < num; ++idx) { this->SplitOrder[idx] = axes[idx]; } this->NumberOfSplitAxes = num; } //---------------------------------------------------------------------------- void vtkImageFilter::GetSplitOrder(int num, int *axes) { int idx; // Error checking if (num < 0 || num > this->NumberOfSplitAxes) { vtkErrorMacro(<< "GetSplitOrder: Bad num " << num); return; } for (idx = 0; idx < num; ++idx) { axes[idx] = this->SplitOrder[idx]; } }
initialize progress
ENH: initialize progress
C++
bsd-3-clause
sankhesh/VTK,jeffbaumes/jeffbaumes-vtk,ashray/VTK-EVM,keithroe/vtkoptix,msmolens/VTK,sumedhasingla/VTK,ashray/VTK-EVM,SimVascular/VTK,sankhesh/VTK,SimVascular/VTK,keithroe/vtkoptix,naucoin/VTKSlicerWidgets,cjh1/VTK,berendkleinhaneveld/VTK,sgh/vtk,demarle/VTK,johnkit/vtk-dev,naucoin/VTKSlicerWidgets,Wuteyan/VTK,berendkleinhaneveld/VTK,SimVascular/VTK,demarle/VTK,daviddoria/PointGraphsPhase1,spthaolt/VTK,SimVascular/VTK,daviddoria/PointGraphsPhase1,sgh/vtk,ashray/VTK-EVM,cjh1/VTK,sankhesh/VTK,demarle/VTK,gram526/VTK,aashish24/VTK-old,biddisco/VTK,cjh1/VTK,candy7393/VTK,ashray/VTK-EVM,mspark93/VTK,sumedhasingla/VTK,spthaolt/VTK,candy7393/VTK,sumedhasingla/VTK,candy7393/VTK,collects/VTK,sankhesh/VTK,ashray/VTK-EVM,sankhesh/VTK,collects/VTK,sumedhasingla/VTK,daviddoria/PointGraphsPhase1,jeffbaumes/jeffbaumes-vtk,jmerkow/VTK,spthaolt/VTK,biddisco/VTK,mspark93/VTK,mspark93/VTK,keithroe/vtkoptix,gram526/VTK,biddisco/VTK,candy7393/VTK,berendkleinhaneveld/VTK,gram526/VTK,gram526/VTK,jmerkow/VTK,daviddoria/PointGraphsPhase1,jmerkow/VTK,sgh/vtk,msmolens/VTK,ashray/VTK-EVM,naucoin/VTKSlicerWidgets,jmerkow/VTK,gram526/VTK,aashish24/VTK-old,collects/VTK,Wuteyan/VTK,arnaudgelas/VTK,cjh1/VTK,sgh/vtk,demarle/VTK,sumedhasingla/VTK,collects/VTK,cjh1/VTK,msmolens/VTK,keithroe/vtkoptix,msmolens/VTK,jeffbaumes/jeffbaumes-vtk,msmolens/VTK,hendradarwin/VTK,hendradarwin/VTK,gram526/VTK,candy7393/VTK,johnkit/vtk-dev,candy7393/VTK,SimVascular/VTK,jmerkow/VTK,candy7393/VTK,sankhesh/VTK,sumedhasingla/VTK,msmolens/VTK,aashish24/VTK-old,jeffbaumes/jeffbaumes-vtk,berendkleinhaneveld/VTK,berendkleinhaneveld/VTK,Wuteyan/VTK,hendradarwin/VTK,candy7393/VTK,Wuteyan/VTK,sumedhasingla/VTK,hendradarwin/VTK,arnaudgelas/VTK,berendkleinhaneveld/VTK,daviddoria/PointGraphsPhase1,johnkit/vtk-dev,SimVascular/VTK,johnkit/vtk-dev,Wuteyan/VTK,mspark93/VTK,spthaolt/VTK,keithroe/vtkoptix,arnaudgelas/VTK,SimVascular/VTK,biddisco/VTK,naucoin/VTKSlicerWidgets,keithroe/vtkoptix,johnkit/vtk-dev,Wuteyan/VTK,msmolens/VTK,demarle/VTK,berendkleinhaneveld/VTK,jmerkow/VTK,sumedhasingla/VTK,arnaudgelas/VTK,johnkit/vtk-dev,jeffbaumes/jeffbaumes-vtk,biddisco/VTK,ashray/VTK-EVM,naucoin/VTKSlicerWidgets,mspark93/VTK,biddisco/VTK,demarle/VTK,jeffbaumes/jeffbaumes-vtk,collects/VTK,aashish24/VTK-old,aashish24/VTK-old,hendradarwin/VTK,hendradarwin/VTK,sankhesh/VTK,demarle/VTK,arnaudgelas/VTK,aashish24/VTK-old,sankhesh/VTK,ashray/VTK-EVM,cjh1/VTK,arnaudgelas/VTK,daviddoria/PointGraphsPhase1,spthaolt/VTK,gram526/VTK,naucoin/VTKSlicerWidgets,biddisco/VTK,jmerkow/VTK,keithroe/vtkoptix,jmerkow/VTK,SimVascular/VTK,keithroe/vtkoptix,Wuteyan/VTK,spthaolt/VTK,hendradarwin/VTK,gram526/VTK,spthaolt/VTK,msmolens/VTK,sgh/vtk,demarle/VTK,mspark93/VTK,mspark93/VTK,sgh/vtk,mspark93/VTK,johnkit/vtk-dev,collects/VTK
94dee0ca4b2e2b66926129d731d3fd0c6502bf15
dgl/src/pugl.cpp
dgl/src/pugl.cpp
/* * DISTRHO Plugin Framework (DPF) * Copyright (C) 2012-2021 Filipe Coelho <[email protected]> * * Permission to use, copy, modify, and/or distribute this software for any purpose with * or without fee is hereby granted, provided that the above copyright notice and this * permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD * TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN * NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER * IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include "pugl.hpp" /* we will include all header files used in pugl in their C++ friendly form, then pugl stuff in custom namespace */ #include <cassert> #include <cmath> #include <cstdlib> #include <cstring> #include <ctime> #if defined(DISTRHO_OS_HAIKU) #elif defined(DISTRHO_OS_MAC) # import <Cocoa/Cocoa.h> # include <dlfcn.h> # include <mach/mach_time.h> # ifdef DGL_CAIRO # include <cairo.h> # include <cairo-quartz.h> # endif # ifdef DGL_OPENGL # include <OpenGL/gl.h> # endif # ifdef DGL_VULKAN # import <QuartzCore/CAMetalLayer.h> # include <vulkan/vulkan_core.h> # include <vulkan/vulkan_macos.h> # endif #elif defined(DISTRHO_OS_WINDOWS) # include <wctype.h> # include <windows.h> # include <windowsx.h> # ifdef DGL_CAIRO # include <cairo.h> # include <cairo-win32.h> # endif # ifdef DGL_OPENGL # include <GL/gl.h> # endif # ifdef DGL_VULKAN # include <vulkan/vulkan.h> # include <vulkan/vulkan_win32.h> # endif #else # include <dlfcn.h> # include <sys/select.h> # include <sys/time.h> # include <X11/X.h> # include <X11/Xatom.h> # include <X11/Xlib.h> # include <X11/Xutil.h> # include <X11/keysym.h> # ifdef HAVE_XCURSOR # include <X11/Xcursor/Xcursor.h> # include <X11/cursorfont.h> # endif # ifdef HAVE_XRANDR # include <X11/extensions/Xrandr.h> # endif # ifdef HAVE_XSYNC # include <X11/extensions/sync.h> # include <X11/extensions/syncconst.h> # endif # ifdef DGL_CAIRO # include <cairo.h> # include <cairo-xlib.h> # endif # ifdef DGL_OPENGL # include <GL/gl.h> # include <GL/glx.h> # endif # ifdef DGL_VULKAN # include <vulkan/vulkan_core.h> # include <vulkan/vulkan_xlib.h> # endif #endif START_NAMESPACE_DGL // -------------------------------------------------------------------------------------------------------------------- #define PUGL_DISABLE_DEPRECATED #if defined(DISTRHO_OS_HAIKU) #elif defined(DISTRHO_OS_MAC) /* # define PuglWindow DISTRHO_JOIN_MACRO(PuglWindow, DGL_NAMESPACE) # define PuglOpenGLView DISTRHO_JOIN_MACRO(PuglOpenGLView, DGL_NAMESPACE) */ # import "pugl-upstream/src/mac.m" # import "pugl-upstream/src/mac_stub.m" # ifdef DGL_CAIRO # import "pugl-upstream/src/mac_cairo.m" # endif # ifdef DGL_OPENGL # import "pugl-upstream/src/mac_gl.m" # endif # ifdef DGL_VULKAN # import "pugl-upstream/src/mac_vulkan.m" # endif #elif defined(DISTRHO_OS_WINDOWS) # include "pugl-upstream/src/win.c" # include "pugl-upstream/src/win_stub.c" # ifdef DGL_CAIRO # include "pugl-upstream/src/win_cairo.c" # endif # ifdef DGL_OPENGL # include "pugl-upstream/src/win_gl.c" # endif # ifdef DGL_VULKAN # include "pugl-upstream/src/win_vulkan.c" # endif #else # include "pugl-upstream/src/x11.c" # include "pugl-upstream/src/x11_stub.c" # ifdef DGL_CAIRO # include "pugl-upstream/src/x11_cairo.c" # endif # ifdef DGL_OPENGL # include "pugl-upstream/src/x11_gl.c" # endif # ifdef DGL_VULKAN # include "pugl-upstream/src/x11_vulkan.c" # endif #endif #include "pugl-upstream/src/implementation.c" // -------------------------------------------------------------------------------------------------------------------- // expose backend enter void puglBackendEnter(PuglView* view) { view->backend->enter(view, NULL); } // -------------------------------------------------------------------------------------------------------------------- // missing in pugl, directly returns title char* pointer const char* puglGetWindowTitle(const PuglView* view) { return view->title; } // -------------------------------------------------------------------------------------------------------------------- // bring view window into the foreground, aka "raise" window void puglRaiseWindow(PuglView* view) { #if defined(DISTRHO_OS_HAIKU) || defined(DISTRHO_OS_MAC) // nothing here yet #elif defined(DISTRHO_OS_WINDOWS) SetForegroundWindow(view->impl->hwnd); SetActiveWindow(view->impl->hwnd); #else XRaiseWindow(view->impl->display, view->impl->win); #endif } // -------------------------------------------------------------------------------------------------------------------- // set backend that matches current build void puglSetMatchingBackendForCurrentBuild(PuglView* const view) { #ifdef DGL_CAIRO puglSetBackend(view, puglCairoBackend()); #endif #ifdef DGL_OPENGL puglSetBackend(view, puglGlBackend()); #endif #ifdef DGL_Vulkan puglSetBackend(view, puglVulkanBackend()); #endif } // -------------------------------------------------------------------------------------------------------------------- // Combine puglSetMinSize and puglSetAspectRatio PuglStatus puglSetGeometryConstraints(PuglView* const view, const uint width, const uint height, const bool aspect) { view->minWidth = width; view->minHeight = height; if (aspect) { view->minAspectX = width; view->minAspectY = height; view->maxAspectX = width; view->maxAspectY = height; } #if defined(DISTRHO_OS_HAIKU) // nothing? #elif defined(DISTRHO_OS_MAC) if (view->impl->window) { [view->impl->window setContentMinSize:sizePoints(view, view->minWidth, view->minHeight)]; if (aspect) [view->impl->window setContentAspectRatio:sizePoints(view, view->minAspectX, view->minAspectY)]; } #elif defined(DISTRHO_OS_WINDOWS) // nothing #else return updateSizeHints(view); #endif return PUGL_SUCCESS; } // -------------------------------------------------------------------------------------------------------------------- // set window size without changing frame x/y position PuglStatus puglSetWindowSize(PuglView* const view, const uint width, const uint height) { #if defined(DISTRHO_OS_HAIKU) || defined(DISTRHO_OS_MAC) // keep upstream behaviour const PuglRect frame = { view->frame.x, view->frame.y, (double)width, (double)height }; return puglSetFrame(view, frame); #elif defined(DISTRHO_OS_WINDOWS) // matches upstream pugl, except we add SWP_NOMOVE flag if (view->impl->hwnd) { const PuglRect frame = view->frame; RECT rect = { (long)frame.x, (long)frame.y, (long)frame.x + (long)frame.width, (long)frame.y + (long)frame.height }; AdjustWindowRectEx(&rect, puglWinGetWindowFlags(view), FALSE, puglWinGetWindowExFlags(view)); if (! SetWindowPos(view->impl->hwnd, HWND_TOP, rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top, SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOOWNERZORDER | SWP_NOZORDER)) return PUGL_UNKNOWN_ERROR; } #else // matches upstream pugl, except we use XResizeWindow instead of XMoveResizeWindow if (view->impl->win) { if (! XResizeWindow(view->world->impl->display, view->impl->win, width, height)) return PUGL_UNKNOWN_ERROR; } #endif view->frame.width = width; view->frame.height = height; return PUGL_SUCCESS; } // -------------------------------------------------------------------------------------------------------------------- // DGL specific, build-specific drawing prepare void puglOnDisplayPrepare(PuglView*) { #ifdef DGL_OPENGL glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glLoadIdentity(); #endif } // -------------------------------------------------------------------------------------------------------------------- // DGL specific, build-specific fallback resize void puglFallbackOnResize(PuglView* const view) { #ifdef DGL_OPENGL glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho(0.0, static_cast<GLdouble>(view->frame.width), static_cast<GLdouble>(view->frame.height), 0.0, 0.0, 1.0); glViewport(0, 0, static_cast<GLsizei>(view->frame.width), static_cast<GLsizei>(view->frame.height)); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); #endif } #ifdef DISTRHO_OS_WINDOWS // -------------------------------------------------------------------------------------------------------------------- // win32 specific, call ShowWindow with SW_RESTORE void puglWin32RestoreWindow(PuglView* const view) { PuglInternals* impl = view->impl; DISTRHO_SAFE_ASSERT_RETURN(impl->hwnd != nullptr,); ShowWindow(impl->hwnd, SW_RESTORE); SetFocus(impl->hwnd); } // -------------------------------------------------------------------------------------------------------------------- // win32 specific, center view based on parent coordinates (if there is one) void puglWin32ShowWindowCentered(PuglView* const view) { PuglInternals* impl = view->impl; DISTRHO_SAFE_ASSERT_RETURN(impl->hwnd != nullptr,); RECT rectChild, rectParent; if (view->transientParent != 0 && GetWindowRect(impl->hwnd, &rectChild) && GetWindowRect((HWND)view->transientParent, &rectParent)) { SetWindowPos(impl->hwnd, (HWND)view->transientParent, rectParent.left + (rectChild.right-rectChild.left)/2, rectParent.top + (rectChild.bottom-rectChild.top)/2, 0, 0, SWP_SHOWWINDOW|SWP_NOSIZE); } else { ShowWindow(impl->hwnd, SW_SHOWNORMAL); } SetFocus(impl->hwnd); } // -------------------------------------------------------------------------------------------------------------------- // win32 specific, set or unset WS_SIZEBOX style flag void puglWin32SetWindowResizable(PuglView* const view, const bool resizable) { PuglInternals* impl = view->impl; DISTRHO_SAFE_ASSERT_RETURN(impl->hwnd != nullptr,); const int winFlags = resizable ? GetWindowLong(impl->hwnd, GWL_STYLE) | WS_SIZEBOX : GetWindowLong(impl->hwnd, GWL_STYLE) & ~WS_SIZEBOX; SetWindowLong(impl->hwnd, GWL_STYLE, winFlags); } #endif // -------------------------------------------------------------------------------------------------------------------- END_NAMESPACE_DGL
/* * DISTRHO Plugin Framework (DPF) * Copyright (C) 2012-2021 Filipe Coelho <[email protected]> * * Permission to use, copy, modify, and/or distribute this software for any purpose with * or without fee is hereby granted, provided that the above copyright notice and this * permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD * TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN * NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER * IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include "pugl.hpp" /* we will include all header files used in pugl in their C++ friendly form, then pugl stuff in custom namespace */ #include <cassert> #include <cmath> #include <cstdlib> #include <cstring> #include <ctime> #if defined(DISTRHO_OS_HAIKU) #elif defined(DISTRHO_OS_MAC) # import <Cocoa/Cocoa.h> # include <dlfcn.h> # include <mach/mach_time.h> # ifdef DGL_CAIRO # include <cairo.h> # include <cairo-quartz.h> # endif # ifdef DGL_OPENGL # include <OpenGL/gl.h> # endif # ifdef DGL_VULKAN # import <QuartzCore/CAMetalLayer.h> # include <vulkan/vulkan_core.h> # include <vulkan/vulkan_macos.h> # endif #elif defined(DISTRHO_OS_WINDOWS) # include <wctype.h> # include <windows.h> # include <windowsx.h> # ifdef DGL_CAIRO # include <cairo.h> # include <cairo-win32.h> # endif # ifdef DGL_OPENGL # include <GL/gl.h> # endif # ifdef DGL_VULKAN # include <vulkan/vulkan.h> # include <vulkan/vulkan_win32.h> # endif #else # include <dlfcn.h> # include <sys/select.h> # include <sys/time.h> # include <X11/X.h> # include <X11/Xatom.h> # include <X11/Xlib.h> # include <X11/Xutil.h> # include <X11/keysym.h> # ifdef HAVE_XCURSOR # include <X11/Xcursor/Xcursor.h> # include <X11/cursorfont.h> # endif # ifdef HAVE_XRANDR # include <X11/extensions/Xrandr.h> # endif # ifdef HAVE_XSYNC # include <X11/extensions/sync.h> # include <X11/extensions/syncconst.h> # endif # ifdef DGL_CAIRO # include <cairo.h> # include <cairo-xlib.h> # endif # ifdef DGL_OPENGL # include <GL/gl.h> # include <GL/glx.h> # endif # ifdef DGL_VULKAN # include <vulkan/vulkan_core.h> # include <vulkan/vulkan_xlib.h> # endif #endif START_NAMESPACE_DGL // -------------------------------------------------------------------------------------------------------------------- #define PUGL_DISABLE_DEPRECATED #if defined(DISTRHO_OS_HAIKU) #elif defined(DISTRHO_OS_MAC) /* # define PuglWindow DISTRHO_JOIN_MACRO(PuglWindow, DGL_NAMESPACE) # define PuglOpenGLView DISTRHO_JOIN_MACRO(PuglOpenGLView, DGL_NAMESPACE) */ # import "pugl-upstream/src/mac.m" # import "pugl-upstream/src/mac_stub.m" # ifdef DGL_CAIRO # import "pugl-upstream/src/mac_cairo.m" # endif # ifdef DGL_OPENGL # import "pugl-upstream/src/mac_gl.m" # endif # ifdef DGL_VULKAN # import "pugl-upstream/src/mac_vulkan.m" # endif #elif defined(DISTRHO_OS_WINDOWS) # include "pugl-upstream/src/win.c" # include "pugl-upstream/src/win_stub.c" # ifdef DGL_CAIRO # include "pugl-upstream/src/win_cairo.c" # endif # ifdef DGL_OPENGL # include "pugl-upstream/src/win_gl.c" # endif # ifdef DGL_VULKAN # include "pugl-upstream/src/win_vulkan.c" # endif #else # include "pugl-upstream/src/x11.c" # include "pugl-upstream/src/x11_stub.c" # ifdef DGL_CAIRO # include "pugl-upstream/src/x11_cairo.c" # endif # ifdef DGL_OPENGL # include "pugl-upstream/src/x11_gl.c" # endif # ifdef DGL_VULKAN # include "pugl-upstream/src/x11_vulkan.c" # endif #endif #include "pugl-upstream/src/implementation.c" // -------------------------------------------------------------------------------------------------------------------- // expose backend enter void puglBackendEnter(PuglView* view) { view->backend->enter(view, NULL); } // -------------------------------------------------------------------------------------------------------------------- // missing in pugl, directly returns title char* pointer const char* puglGetWindowTitle(const PuglView* view) { return view->title; } // -------------------------------------------------------------------------------------------------------------------- // bring view window into the foreground, aka "raise" window void puglRaiseWindow(PuglView* view) { #if defined(DISTRHO_OS_HAIKU) || defined(DISTRHO_OS_MAC) // nothing here yet #elif defined(DISTRHO_OS_WINDOWS) SetForegroundWindow(view->impl->hwnd); SetActiveWindow(view->impl->hwnd); #else XRaiseWindow(view->impl->display, view->impl->win); #endif } // -------------------------------------------------------------------------------------------------------------------- // set backend that matches current build void puglSetMatchingBackendForCurrentBuild(PuglView* const view) { #ifdef DGL_CAIRO puglSetBackend(view, puglCairoBackend()); #endif #ifdef DGL_OPENGL puglSetBackend(view, puglGlBackend()); #endif #ifdef DGL_VULKAN puglSetBackend(view, puglVulkanBackend()); #endif if (view->backend == nullptr) puglSetBackend(view, puglStubBackend()); } // -------------------------------------------------------------------------------------------------------------------- // Combine puglSetMinSize and puglSetAspectRatio PuglStatus puglSetGeometryConstraints(PuglView* const view, const uint width, const uint height, const bool aspect) { view->minWidth = width; view->minHeight = height; if (aspect) { view->minAspectX = width; view->minAspectY = height; view->maxAspectX = width; view->maxAspectY = height; } #if defined(DISTRHO_OS_HAIKU) // nothing? #elif defined(DISTRHO_OS_MAC) if (view->impl->window) { [view->impl->window setContentMinSize:sizePoints(view, view->minWidth, view->minHeight)]; if (aspect) [view->impl->window setContentAspectRatio:sizePoints(view, view->minAspectX, view->minAspectY)]; } #elif defined(DISTRHO_OS_WINDOWS) // nothing #else return updateSizeHints(view); #endif return PUGL_SUCCESS; } // -------------------------------------------------------------------------------------------------------------------- // set window size without changing frame x/y position PuglStatus puglSetWindowSize(PuglView* const view, const uint width, const uint height) { #if defined(DISTRHO_OS_HAIKU) || defined(DISTRHO_OS_MAC) // keep upstream behaviour const PuglRect frame = { view->frame.x, view->frame.y, (double)width, (double)height }; return puglSetFrame(view, frame); #elif defined(DISTRHO_OS_WINDOWS) // matches upstream pugl, except we add SWP_NOMOVE flag if (view->impl->hwnd) { const PuglRect frame = view->frame; RECT rect = { (long)frame.x, (long)frame.y, (long)frame.x + (long)frame.width, (long)frame.y + (long)frame.height }; AdjustWindowRectEx(&rect, puglWinGetWindowFlags(view), FALSE, puglWinGetWindowExFlags(view)); if (! SetWindowPos(view->impl->hwnd, HWND_TOP, rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top, SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOOWNERZORDER | SWP_NOZORDER)) return PUGL_UNKNOWN_ERROR; } #else // matches upstream pugl, except we use XResizeWindow instead of XMoveResizeWindow if (view->impl->win) { if (! XResizeWindow(view->world->impl->display, view->impl->win, width, height)) return PUGL_UNKNOWN_ERROR; } #endif view->frame.width = width; view->frame.height = height; return PUGL_SUCCESS; } // -------------------------------------------------------------------------------------------------------------------- // DGL specific, build-specific drawing prepare void puglOnDisplayPrepare(PuglView*) { #ifdef DGL_OPENGL glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glLoadIdentity(); #endif } // -------------------------------------------------------------------------------------------------------------------- // DGL specific, build-specific fallback resize void puglFallbackOnResize(PuglView* const view) { #ifdef DGL_OPENGL glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho(0.0, static_cast<GLdouble>(view->frame.width), static_cast<GLdouble>(view->frame.height), 0.0, 0.0, 1.0); glViewport(0, 0, static_cast<GLsizei>(view->frame.width), static_cast<GLsizei>(view->frame.height)); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); #endif } #ifdef DISTRHO_OS_WINDOWS // -------------------------------------------------------------------------------------------------------------------- // win32 specific, call ShowWindow with SW_RESTORE void puglWin32RestoreWindow(PuglView* const view) { PuglInternals* impl = view->impl; DISTRHO_SAFE_ASSERT_RETURN(impl->hwnd != nullptr,); ShowWindow(impl->hwnd, SW_RESTORE); SetFocus(impl->hwnd); } // -------------------------------------------------------------------------------------------------------------------- // win32 specific, center view based on parent coordinates (if there is one) void puglWin32ShowWindowCentered(PuglView* const view) { PuglInternals* impl = view->impl; DISTRHO_SAFE_ASSERT_RETURN(impl->hwnd != nullptr,); RECT rectChild, rectParent; if (view->transientParent != 0 && GetWindowRect(impl->hwnd, &rectChild) && GetWindowRect((HWND)view->transientParent, &rectParent)) { SetWindowPos(impl->hwnd, (HWND)view->transientParent, rectParent.left + (rectChild.right-rectChild.left)/2, rectParent.top + (rectChild.bottom-rectChild.top)/2, 0, 0, SWP_SHOWWINDOW|SWP_NOSIZE); } else { ShowWindow(impl->hwnd, SW_SHOWNORMAL); } SetFocus(impl->hwnd); } // -------------------------------------------------------------------------------------------------------------------- // win32 specific, set or unset WS_SIZEBOX style flag void puglWin32SetWindowResizable(PuglView* const view, const bool resizable) { PuglInternals* impl = view->impl; DISTRHO_SAFE_ASSERT_RETURN(impl->hwnd != nullptr,); const int winFlags = resizable ? GetWindowLong(impl->hwnd, GWL_STYLE) | WS_SIZEBOX : GetWindowLong(impl->hwnd, GWL_STYLE) & ~WS_SIZEBOX; SetWindowLong(impl->hwnd, GWL_STYLE, winFlags); } #endif // -------------------------------------------------------------------------------------------------------------------- END_NAMESPACE_DGL
Fix a typo; set pugl backend as stub if it ends up being null
Fix a typo; set pugl backend as stub if it ends up being null
C++
isc
DISTRHO/DPF,DISTRHO/DPF,DISTRHO/DPF,DISTRHO/DPF
72d9c1db6266d41d817bb805180acc081d6569eb
include/tudocomp/Coder.hpp
include/tudocomp/Coder.hpp
#ifndef _INCLUDED_CODER_HPP_ #define _INCLUDED_CODER_HPP_ #include <tudocomp/io.hpp> #include <tudocomp/Algorithm.hpp> namespace tdc { /*abstract*/ class Encoder : public Algorithm { private: std::unique_ptr<io::OutputStream> m_outs; protected: std::unique_ptr<BitOStream> m_out; public: inline Encoder(Env&& env, Output& out) : Algorithm(std::move(env)) { m_outs = std::make_unique<io::OutputStream>(out.as_stream()); m_out = std::make_unique<BitOStream>(*m_outs); } inline ~Encoder() { finalize(); } inline void finalize() { m_out->flush(); } }; /*abstract*/ class Decoder : public Algorithm { private: std::unique_ptr<io::InputStream> m_ins; protected: std::unique_ptr<BitIStream> m_in; public: inline Decoder(Env&& env, Input& in) : Algorithm(std::move(env)) { m_ins = std::make_unique<io::InputStream>(in.as_stream()); m_in = std::make_unique<BitIStream>(*m_ins); } inline bool eof() const { return true; //TODO: return m_in->eof(); } }; } #endif
#ifndef _INCLUDED_CODER_HPP_ #define _INCLUDED_CODER_HPP_ #include <tudocomp/io.hpp> #include <tudocomp/Algorithm.hpp> namespace tdc { /*abstract*/ class Encoder : public Algorithm { private: std::unique_ptr<io::OutputStream> m_outs; protected: std::unique_ptr<BitOStream> m_out; public: inline Encoder(Env&& env, Output& out) : Algorithm(std::move(env)) { m_outs = std::make_unique<io::OutputStream>(out.as_stream()); m_out = std::make_unique<BitOStream>(*m_outs); } inline ~Encoder() { finalize(); } inline void finalize() { m_out->flush(); } }; /*abstract*/ class Decoder : public Algorithm { private: std::unique_ptr<io::InputStream> m_ins; protected: std::unique_ptr<BitIStream> m_in; public: inline Decoder(Env&& env, Input& in) : Algorithm(std::move(env)) { m_ins = std::make_unique<io::InputStream>(in.as_stream()); m_in = std::make_unique<BitIStream>(*m_ins); } inline bool eof() const { return m_in->eof(); } }; } #endif
Complete Decoder base class
Complete Decoder base class
C++
apache-2.0
tudocomp/tudocomp,tudocomp/tudocomp,tudocomp/tudocomp,tudocomp/tudocomp,tudocomp/tudocomp
635a34b6075ae6d2a33b96a6ba13bb9c455a9192
xchainer/backprop.cc
xchainer/backprop.cc
#include "xchainer/backprop.h" #include <functional> #include <memory> #include <queue> #include <unordered_map> #include <gsl/gsl> #include <nonstd/optional.hpp> #include "xchainer/array.h" #include "xchainer/array_node.h" #include "xchainer/op_node.h" namespace xchainer { namespace { class BackwardImpl { using Comparer = bool(*)(const std::shared_ptr<const OpNode>&, const std::shared_ptr<const OpNode>&); using CandidateOpNodes = std::priority_queue<std::shared_ptr<const OpNode>, std::vector<std::shared_ptr<const OpNode>>, Comparer>; using PreviousArrayNodeMap = std::unordered_map<std::shared_ptr<const OpNode>, std::shared_ptr<ArrayNode>>; public: BackwardImpl() : candidate_op_nodes_(BackwardImpl::Compare){}; void run(Array& output) { std::shared_ptr<ArrayNode> array_node = output.mutable_node(); if (!array_node->grad()) { array_node->set_grad(Array::OnesLike(output)); } PushNextOpNode(array_node); while (!candidate_op_nodes_.empty()) { std::shared_ptr<const OpNode> op_node = candidate_op_nodes_.top(); candidate_op_nodes_.pop(); std::vector<nonstd::optional<Array>> gxs = ComputeNextGradients(op_node); AccumulateNextGradients(op_node, gxs); for (const auto& next_array_node : op_node->next_nodes()) { PushNextOpNode(next_array_node); } } }; private: std::vector<nonstd::optional<Array>> ComputeNextGradients(const std::shared_ptr<const OpNode>& op_node) { const std::shared_ptr<ArrayNode>& previous_array_node = previous_array_node_map_.at(op_node); const nonstd::optional<Array>& gy = previous_array_node->grad(); assert(gy); std::vector<nonstd::optional<Array>> gxs; for (const auto& backward_function : op_node->backward_functions()) { if (backward_function) { gxs.emplace_back(backward_function(*gy)); } else { gxs.emplace_back(nonstd::nullopt); } } previous_array_node->ClearGrad(); return gxs; } void AccumulateNextGradients(const std::shared_ptr<const OpNode>& op_node, const std::vector<nonstd::optional<Array>>& gxs) { gsl::span<const std::shared_ptr<ArrayNode>> next_array_nodes = op_node->next_nodes(); auto next_size = next_array_nodes.size(); for (decltype(next_size) i = 0; i < next_size; ++i) { const nonstd::optional<Array>& gx = gxs[i]; const std::shared_ptr<ArrayNode>& next_array_node = next_array_nodes[i]; if (gx) { const nonstd::optional<Array>& grad = next_array_node->grad(); if (grad) { next_array_node->set_grad(*grad + *gx); } else { next_array_node->set_grad(std::move(*gx)); } } } } void PushNextOpNode(const std::shared_ptr<ArrayNode>& array_node) { const std::shared_ptr<const OpNode>& next_op_node = array_node->next_node(); if (next_op_node) { candidate_op_nodes_.push(next_op_node); previous_array_node_map_.emplace(next_op_node, array_node); } } static bool Compare(const std::shared_ptr<const OpNode>& lhs, const std::shared_ptr<const OpNode>& rhs) { return lhs->rank() < rhs->rank(); }; CandidateOpNodes candidate_op_nodes_; PreviousArrayNodeMap previous_array_node_map_; }; } // namespace void Backward(Array& output) { // TODO(takagi): Operations that have multiple outputs // TODO(takagi): Begin backprop from multiple outputs BackwardImpl impl; impl.run(output); } } // namespace xchainer
#include "xchainer/backprop.h" #include <functional> #include <memory> #include <queue> #include <unordered_map> #include <gsl/gsl> #include <nonstd/optional.hpp> #include "xchainer/array.h" #include "xchainer/array_node.h" #include "xchainer/op_node.h" namespace xchainer { namespace { class BackwardImpl { using Comparer = bool(*)(const std::shared_ptr<const OpNode>&, const std::shared_ptr<const OpNode>&); using CandidateOpNodes = std::priority_queue<std::shared_ptr<const OpNode>, std::vector<std::shared_ptr<const OpNode>>, Comparer>; using PreviousArrayNodeMap = std::unordered_map<std::shared_ptr<const OpNode>, std::shared_ptr<ArrayNode>>; public: BackwardImpl() : candidate_op_nodes_(BackwardImpl::Compare){}; void run(Array& output) { std::shared_ptr<ArrayNode> array_node = output.mutable_node(); if (!array_node->grad()) { array_node->set_grad(Array::OnesLike(output)); } PushNextOpNode(array_node); while (!candidate_op_nodes_.empty()) { std::shared_ptr<const OpNode> op_node = candidate_op_nodes_.top(); candidate_op_nodes_.pop(); std::vector<nonstd::optional<Array>> gxs = ComputeNextGradients(op_node); AccumulateNextGradients(op_node, gxs); for (const auto& next_array_node : op_node->next_nodes()) { PushNextOpNode(next_array_node); } } }; private: std::vector<nonstd::optional<Array>> ComputeNextGradients(const std::shared_ptr<const OpNode>& op_node) { const std::shared_ptr<ArrayNode>& previous_array_node = previous_array_node_map_.at(op_node); const nonstd::optional<Array>& gy = previous_array_node->grad(); assert(gy); std::vector<nonstd::optional<Array>> gxs; for (const auto& backward_function : op_node->backward_functions()) { if (backward_function) { gxs.emplace_back(backward_function(*gy)); } else { gxs.emplace_back(nonstd::nullopt); } } previous_array_node->ClearGrad(); return gxs; } void AccumulateNextGradients(const std::shared_ptr<const OpNode>& op_node, const std::vector<nonstd::optional<Array>>& gxs) { gsl::span<const std::shared_ptr<ArrayNode>> next_array_nodes = op_node->next_nodes(); assert(next_array_nodes.size() == gxs.size()); auto next_size = next_array_nodes.size(); for (decltype(next_size) i = 0; i < next_size; ++i) { const nonstd::optional<Array>& gx = gxs[i]; const std::shared_ptr<ArrayNode>& next_array_node = next_array_nodes[i]; if (gx) { const nonstd::optional<Array>& grad = next_array_node->grad(); if (grad) { next_array_node->set_grad(*grad + *gx); } else { next_array_node->set_grad(std::move(*gx)); } } } } void PushNextOpNode(const std::shared_ptr<ArrayNode>& array_node) { const std::shared_ptr<const OpNode>& next_op_node = array_node->next_node(); if (next_op_node) { candidate_op_nodes_.push(next_op_node); previous_array_node_map_.emplace(next_op_node, array_node); } } static bool Compare(const std::shared_ptr<const OpNode>& lhs, const std::shared_ptr<const OpNode>& rhs) { return lhs->rank() < rhs->rank(); }; CandidateOpNodes candidate_op_nodes_; PreviousArrayNodeMap previous_array_node_map_; }; } // namespace void Backward(Array& output) { // TODO(takagi): Operations that have multiple outputs // TODO(takagi): Begin backprop from multiple outputs BackwardImpl impl; impl.run(output); } } // namespace xchainer
Add assertion
Add assertion
C++
mit
chainer/chainer,niboshi/chainer,okuta/chainer,okuta/chainer,keisuke-umezawa/chainer,niboshi/chainer,keisuke-umezawa/chainer,jnishi/chainer,niboshi/chainer,chainer/chainer,wkentaro/chainer,niboshi/chainer,chainer/chainer,hvy/chainer,ktnyt/chainer,okuta/chainer,ktnyt/chainer,okuta/chainer,chainer/chainer,wkentaro/chainer,wkentaro/chainer,ktnyt/chainer,ktnyt/chainer,keisuke-umezawa/chainer,wkentaro/chainer,hvy/chainer,jnishi/chainer,tkerola/chainer,hvy/chainer,pfnet/chainer,jnishi/chainer,jnishi/chainer,keisuke-umezawa/chainer,hvy/chainer
38c8896499aa223b1c4593bceddcc3b2af25e413
zlreactor/net/TcpConnection.cpp
zlreactor/net/TcpConnection.cpp
#include "TcpConnection.h" #include "net/Socket.h" #include "base/ZLog.h" #include "net/EventLoop.h" #include "net/Channel.h" NAMESPACE_ZL_NET_START void defaultConnectionCallback(const TcpConnectionPtr& conn) { LOG_INFO("defaultConnectionCallback : [%s]<->[%s] [%s]\n", conn->localAddress().ipPort().c_str(), conn->peerAddress().ipPort().c_str(), conn->connected() ? "UP" : "DOWN"); } void defaultMessageCallback(const TcpConnectionPtr& conn, NetBuffer* buf, Timestamp receiveTime) { LOG_INFO("defaultMessageCallback : [%d][%s]", conn->fd(), buf->toString().c_str()); } TcpConnection::TcpConnection(EventLoop* loop, int sockfd, const InetAddress& localAddr, const InetAddress& peerAddr) : loop_(loop), state_(kConnecting), localAddr_(localAddr.getSockAddrInet()), peerAddr_(peerAddr.getSockAddrInet()) { socket_ = new Socket(sockfd); socket_->setKeepAlive(true); socket_->setNoDelay(true); socket_->setNonBlocking(); channel_ = new Channel(loop, sockfd); channel_->setReadCallback(std::bind(&TcpConnection::handleRead, this, std::placeholders::_1)); channel_->setWriteCallback(std::bind(&TcpConnection::handleWrite, this)); channel_->setCloseCallback(std::bind(&TcpConnection::handleClose, this)); channel_->setErrorCallback(std::bind(&TcpConnection::handleError, this)); LOG_INFO("TcpConnection::TcpConnection(), [%0x] [%d][%0x][%0x]", this, socket_->fd(), socket_, channel_); } TcpConnection::~TcpConnection() { LOG_INFO("TcpConnection::~TcpConnection(),[%0x] [%d][%0x][%0x]", this, socket_->fd(), socket_, channel_); assert(state_ == kDisconnected); Safe_Delete(socket_); Safe_Delete(channel_); } void TcpConnection::send(const void* data, size_t len) { if (state_ == kConnected) { if (loop_->isInLoopThread()) { sendInLoop(data, len); } else { loop_->runInLoop(std::bind(&TcpConnection::sendInLoop, this, data, len)); } } } void TcpConnection::send(const std::string& buffer) { send(buffer.data(), buffer.size()); } void TcpConnection::send(NetBuffer* buffer) { if (state_ == kConnected) { if (loop_->isInLoopThread()) { sendInLoop(buffer->peek(), buffer->readableBytes()); buffer->retrieveAll(); } else { loop_->runInLoop(std::bind(&TcpConnection::sendInLoop2, shared_from_this(), buffer->retrieveAllAsString())); } } } void TcpConnection::sendInLoop(const void* data, size_t len) { loop_->assertInLoopThread(); if (state_ == kDisconnected) { LOG_WARN("TcpConnection::sendInLoop [%d]disconnected, give up writing", socket_->fd()); return; } size_t nwrote = 0; size_t remaining = len; bool faultError = false; // 如果当前连接尚没有注册可写事件(比如直接调用send接口),并且发送缓冲区为空 // 就直接发送数据,发送成功则回调写完成实现; if (!channel_->isWriting() && outputBuffer_.readableBytes() == 0) { nwrote = socket_->send((const char*)data, len); if (nwrote >= 0) { remaining = len - nwrote; if (remaining == 0 && writeCompleteCallback_) { loop_->queueInLoop(std::bind(writeCompleteCallback_, shared_from_this())); } } else // nwrote < 0 { nwrote = 0; if (errno != EWOULDBLOCK) { LOG_ERROR("TcpConnection::sendInLoop error, fd[%d], error[%d]", socket_->fd(), errno); if (errno == EPIPE || errno == ECONNRESET) { faultError = true; } } } } if(remaining > len) { LOG_INFO("TcpConnection::sendInLoop [%d], remaining[%d], len[%d]", socket_->fd(), remaining, len); } assert(remaining <= len); //如果发送成功且数据尚未发送完毕,则将剩余数据存入缓冲区,并注册该channel上的可写事件 if (!faultError && remaining > 0) { outputBuffer_.write(static_cast<const char*>(data) + nwrote, remaining); if (!channel_->isWriting()) { channel_->enableWriting(); } } } void TcpConnection::sendInLoop2(const std::string& buffer) { sendInLoop(buffer.data(), buffer.size()); } void TcpConnection::shutdown() { if (state_ == kConnected) { setState(kDisconnecting); loop_->runInLoop(std::bind(&TcpConnection::shutdownInLoop, shared_from_this())); } } void TcpConnection::shutdownInLoop() { loop_->assertInLoopThread(); if (!channel_->isWriting()) // 如果不再关注可写事件,说明数据发送完毕 { SocketUtil::shutdownWrite(socket_->fd()); // 仅仅关闭写端,因为可能读端还有数据要读 } } void TcpConnection::connectEstablished() { loop_->assertInLoopThread(); assert(state_ == kConnecting); setState(kConnected); channel_->enableReading(); TcpConnectionPtr sp_this(shared_from_this()); connectionCallback_(sp_this); } void TcpConnection::connectDestroyed() { LOG_INFO("TcpConnection::connectDestroyed fd = %d, state = %d", socket_->fd(), state_); loop_->assertInLoopThread(); if (state_ == kConnected) { setState(kDisconnected); channel_->disableAll(); TcpConnectionPtr sp_this(shared_from_this()); connectionCallback_(sp_this); } //SocketUtil::closeSocket(socket_->fd()); channel_->remove(); } void TcpConnection::handleRead(Timestamp receiveTime) { LOG_INFO("TcpConnection::handleRead fd = %d, state = %d", socket_->fd(), state_); loop_->assertInLoopThread(); std::string data; size_t n = socket_->recv(data); inputBuffer_.write(data); if (n > 0) { messageCallback_(shared_from_this(), &inputBuffer_, receiveTime); } else if (n == 0) { handleClose(); } else { handleError(); } } void TcpConnection::handleWrite() { LOG_INFO("TcpConnection::handleWrite fd = %d, state = %d", socket_->fd(), state_); loop_->assertInLoopThread(); if (channel_->isWriting()) { size_t n = socket_->send(outputBuffer_.peek(), outputBuffer_.readableBytes()); if (n > 0) { outputBuffer_.retrieve(n); LOG_INFO("TcpConnection::handleWrite fd = %d, send = %d, reserve = %d", socket_->fd(), n, outputBuffer_.readableBytes()); if (outputBuffer_.readableBytes() == 0) // 缓冲区为空,数据发送完毕,删除该channel上的可写事件 { channel_->disableWriting(); if (writeCompleteCallback_) { loop_->queueInLoop(std::bind(writeCompleteCallback_, shared_from_this())); } if (state_ == kDisconnecting) // 数据发送完毕,且连接已断开 { shutdownInLoop(); // 关闭socket的可写 } } } else { LOG_ERROR("TcpConnection::handleWrite, send fail fd = %d, state = %d, send = %d", socket_->fd(), state_, n); if (state_ == kDisconnecting) { shutdownInLoop(); } } } else { LOG_ERROR("TcpConnection::handleWrite, no more writing, fd = %d, state = %d", socket_->fd(), state_); } } void TcpConnection::handleClose() { loop_->assertInLoopThread(); LOG_INFO("TcpConnection::handleClose fd = %d, state = %d", socket_->fd(), state_); assert(state_ == kConnected || state_ == kDisconnecting); setState(kDisconnected); channel_->disableAll(); connectionCallback_(shared_from_this()); closeCallback_(shared_from_this()); } void TcpConnection::handleError() { int err = SocketUtil::getSocketError(channel_->fd()); LOG_ERROR("TcpConnection::handleError [%d], SO_ERROR = %d", channel_->fd(), err); } NAMESPACE_ZL_NET_END
#include "TcpConnection.h" #include "net/Socket.h" #include "base/ZLog.h" #include "net/EventLoop.h" #include "net/Channel.h" NAMESPACE_ZL_NET_START void defaultConnectionCallback(const TcpConnectionPtr& conn) { LOG_INFO("defaultConnectionCallback : [%s]<->[%s] [%s]\n", conn->localAddress().ipPort().c_str(), conn->peerAddress().ipPort().c_str(), conn->connected() ? "UP" : "DOWN"); } void defaultMessageCallback(const TcpConnectionPtr& conn, NetBuffer* buf, Timestamp receiveTime) { LOG_INFO("defaultMessageCallback : [%d][%s]", conn->fd(), buf->toString().c_str()); } TcpConnection::TcpConnection(EventLoop* loop, int sockfd, const InetAddress& localAddr, const InetAddress& peerAddr) : loop_(loop), state_(kConnecting), localAddr_(localAddr.getSockAddrInet()), peerAddr_(peerAddr.getSockAddrInet()) { socket_ = new Socket(sockfd); socket_->setKeepAlive(true); socket_->setNoDelay(true); socket_->setNonBlocking(); channel_ = new Channel(loop, sockfd); channel_->setReadCallback(std::bind(&TcpConnection::handleRead, this, std::placeholders::_1)); channel_->setWriteCallback(std::bind(&TcpConnection::handleWrite, this)); channel_->setCloseCallback(std::bind(&TcpConnection::handleClose, this)); channel_->setErrorCallback(std::bind(&TcpConnection::handleError, this)); LOG_INFO("TcpConnection::TcpConnection(), [%0x] [%d][%0x][%0x]", this, socket_->fd(), socket_, channel_); } TcpConnection::~TcpConnection() { LOG_INFO("TcpConnection::~TcpConnection(),[%0x] [%d][%0x][%0x]", this, socket_->fd(), socket_, channel_); ZL_ASSERT(state_ == kDisconnected)(state_); Safe_Delete(socket_); Safe_Delete(channel_); } void TcpConnection::send(const void* data, size_t len) { if (state_ == kConnected) { if (loop_->isInLoopThread()) { sendInLoop(data, len); } else { loop_->runInLoop(std::bind(&TcpConnection::sendInLoop, this, data, len)); } } } void TcpConnection::send(const std::string& buffer) { send(buffer.data(), buffer.size()); } void TcpConnection::send(NetBuffer* buffer) { if (state_ == kConnected) { if (loop_->isInLoopThread()) { sendInLoop(buffer->peek(), buffer->readableBytes()); buffer->retrieveAll(); } else { loop_->runInLoop(std::bind(&TcpConnection::sendInLoop2, shared_from_this(), buffer->retrieveAllAsString())); } } } void TcpConnection::sendInLoop(const void* data, size_t len) { loop_->assertInLoopThread(); if (state_ == kDisconnected) { LOG_WARN("TcpConnection::sendInLoop [%d]disconnected, give up writing", socket_->fd()); return; } size_t nwrote = 0; size_t remaining = len; bool faultError = false; // 如果当前连接尚没有注册可写事件(比如直接调用send接口),并且发送缓冲区为空 // 就直接发送数据,发送成功则回调写完成实现; if (!channel_->isWriting() && outputBuffer_.readableBytes() == 0) { nwrote = socket_->send((const char*)data, len); if (nwrote >= 0) { remaining = len - nwrote; if (remaining == 0 && writeCompleteCallback_) { loop_->queueInLoop(std::bind(writeCompleteCallback_, shared_from_this())); } } else // nwrote < 0 { nwrote = 0; if (errno != EWOULDBLOCK) { LOG_ERROR("TcpConnection::sendInLoop error, fd[%d], error[%d]", socket_->fd(), errno); if (errno == EPIPE || errno == ECONNRESET) { faultError = true; } } } } ZL_ASSERT(remaining <= len)(remaining)(len)(socket_->fd()); //如果发送成功且数据尚未发送完毕,则将剩余数据存入缓冲区,并注册该channel上的可写事件 if (!faultError && remaining > 0) { outputBuffer_.write(static_cast<const char*>(data) + nwrote, remaining); if (!channel_->isWriting()) { channel_->enableWriting(); } } } void TcpConnection::sendInLoop2(const std::string& buffer) { sendInLoop(buffer.data(), buffer.size()); } void TcpConnection::shutdown() { if (state_ == kConnected) { setState(kDisconnecting); loop_->runInLoop(std::bind(&TcpConnection::shutdownInLoop, shared_from_this())); } } void TcpConnection::shutdownInLoop() { loop_->assertInLoopThread(); if (!channel_->isWriting()) // 如果不再关注可写事件,说明数据发送完毕 { SocketUtil::shutdownWrite(socket_->fd()); // 仅仅关闭写端,因为可能读端还有数据要读 } } void TcpConnection::connectEstablished() { loop_->assertInLoopThread(); ZL_ASSERT(state_ == kConnecting)(state_); setState(kConnected); channel_->enableReading(); TcpConnectionPtr sp_this(shared_from_this()); connectionCallback_(sp_this); } void TcpConnection::connectDestroyed() { LOG_INFO("TcpConnection::connectDestroyed fd = %d, state = %d", socket_->fd(), state_); loop_->assertInLoopThread(); if (state_ == kConnected) { setState(kDisconnected); channel_->disableAll(); TcpConnectionPtr sp_this(shared_from_this()); connectionCallback_(sp_this); } //SocketUtil::closeSocket(socket_->fd()); channel_->remove(); } void TcpConnection::handleRead(Timestamp receiveTime) { LOG_INFO("TcpConnection::handleRead fd = %d, state = %d", socket_->fd(), state_); loop_->assertInLoopThread(); std::string data; size_t n = socket_->recv(data); inputBuffer_.write(data); if (n > 0) { messageCallback_(shared_from_this(), &inputBuffer_, receiveTime); } else if (n == 0) { handleClose(); } else { handleError(); } } void TcpConnection::handleWrite() { LOG_INFO("TcpConnection::handleWrite fd = %d, state = %d", socket_->fd(), state_); loop_->assertInLoopThread(); if (channel_->isWriting()) { size_t n = socket_->send(outputBuffer_.peek(), outputBuffer_.readableBytes()); if (n > 0) { outputBuffer_.retrieve(n); LOG_INFO("TcpConnection::handleWrite fd = %d, send = %d, reserve = %d", socket_->fd(), n, outputBuffer_.readableBytes()); if (outputBuffer_.readableBytes() == 0) // 缓冲区为空,数据发送完毕,删除该channel上的可写事件 { channel_->disableWriting(); if (writeCompleteCallback_) { loop_->queueInLoop(std::bind(writeCompleteCallback_, shared_from_this())); } if (state_ == kDisconnecting) // 数据发送完毕,且连接已断开 { shutdownInLoop(); // 关闭socket的可写 } } } else { LOG_ERROR("TcpConnection::handleWrite, send fail fd = %d, state = %d, send = %d", socket_->fd(), state_, n); if (state_ == kDisconnecting) { shutdownInLoop(); } } } else { LOG_ERROR("TcpConnection::handleWrite, no more writing, fd = %d, state = %d", socket_->fd(), state_); } } void TcpConnection::handleClose() { loop_->assertInLoopThread(); ZL_ASSERT(state_ == kConnected || state_ == kDisconnecting)(state_)(socket_->fd()); setState(kDisconnected); channel_->disableAll(); connectionCallback_(shared_from_this()); closeCallback_(shared_from_this()); } void TcpConnection::handleError() { int err = SocketUtil::getSocketError(channel_->fd()); LOG_ERROR("TcpConnection::handleError [%d], SO_ERROR = %d", channel_->fd(), err); } NAMESPACE_ZL_NET_END
use ZL_ASSERT
[MOD] use ZL_ASSERT
C++
mit
lizhenghn123/zl_reactor,lizhenghn123/zl_reactor,lizhenghn123/zl_reactor
559946f2fcb276741ccc8e9196a8ce877d9f4d21
geometry/point2d.hpp
geometry/point2d.hpp
#pragma once #include "../base/assert.hpp" #include "../base/base.hpp" #include "../base/math.hpp" #include "../base/matrix.hpp" #include "../std/cmath.hpp" #include "../std/sstream.hpp" #include "../std/typeinfo.hpp" namespace m2 { template <typename T> class Point { public: typedef T value_type; T x, y; Point() {} Point(T x_, T y_) : x(x_), y(y_) {} template <typename U> Point(Point<U> const & u) : x(u.x), y(u.y) {} bool EqualDxDy(m2::Point<T> const & p, T eps) const { return ((fabs(x - p.x) < eps) && (fabs(y - p.y) < eps)); } double SquareLength(m2::Point<T> const & p) const { return math::sqr(x - p.x) + math::sqr(y - p.y); } double Length(m2::Point<T> const & p) const { return sqrt(SquareLength(p)); } m2::Point<T> Move(T len, T ang) const { return m2::Point<T>(x + len * cos(ang), y + len * sin(ang)); } m2::Point<T> Move(T len, T angSin, T angCos) const { return m2::Point<T>(x + len * angCos, y + len * angSin); } Point<T> const & operator-=(Point<T> const & a) { x -= a.x; y -= a.y; return *this; } Point<T> const & operator+=(Point<T> const & a) { x += a.x; y += a.y; return *this; } template <typename U> Point<T> const & operator*=(U const & k) { x = static_cast<T>(x * k); y = static_cast<T>(y * k); return *this; } template <typename U> Point<T> const & operator=(Point<U> const & a) { x = static_cast<T>(a.x); y = static_cast<T>(a.y); return *this; } bool operator == (m2::Point<T> const & p) const { return x == p.x && y == p.y; } bool operator != (m2::Point<T> const & p) const { return !(*this == p); } m2::Point<T> operator + (m2::Point<T> const & pt) const { return m2::Point<T>(x + pt.x, y + pt.y); } m2::Point<T> operator - (m2::Point<T> const & pt) const { return m2::Point<T>(x - pt.x, y - pt.y); } m2::Point<T> operator -() const { return m2::Point<T>(-x, -y); } m2::Point<T> operator * (T scale) const { return m2::Point<T>(x * scale, y * scale); } m2::Point<T> const operator * (math::Matrix<T, 3, 3> const & m) const { m2::Point<T> res; res.x = x * m(0, 0) + y * m(1, 0) + m(2, 0); res.y = x * m(0, 1) + y * m(1, 1) + m(2, 1); return res; } m2::Point<T> operator / (T scale) const { return m2::Point<T>(x / scale, y / scale); } m2::Point<T> const & operator *= (math::Matrix<T, 3, 3> const & m) { T tempX = x; x = tempX * m(0, 0) + y * m(1, 0) + m(2, 0); y = tempX * m(0, 1) + y * m(1, 1) + m(2, 1); return *this; } void Rotate(double angle) { T cosAngle = cos(angle); T sinAngle = sin(angle); T oldX = x; x = cosAngle * oldX - sinAngle * y; y = sinAngle * oldX + cosAngle * y; } void Transform(m2::Point<T> const & org, m2::Point<T> const & dx, m2::Point<T> const & dy) { T oldX = x; x = org.x + oldX * dx.x + y * dy.x; y = org.y + oldX * dx.y + y * dy.y; } }; template <typename T> inline Point<T> const operator- (Point<T> const & a, Point<T> const & b) { return Point<T>(a.x - b.x, a.y - b.y); } template <typename T> inline Point<T> const operator+ (Point<T> const & a, Point<T> const & b) { return Point<T>(a.x + b.x, a.y + b.y); } // Dot product of a and b, equals to |a|*|b|*cos(angle_between_a_and_b). template <typename T> T const DotProduct(Point<T> const & a, Point<T> const & b) { return a.x * b.x + a.y * b.y; } // Value of cross product of a and b, equals to |a|*|b|*sin(angle_between_a_and_b). template <typename T> T const CrossProduct(Point<T> const & a, Point<T> const & b) { return a.x * b.y - a.y * b.x; } template <typename T> Point<T> const Rotate(Point<T> const & pt, T a) { Point<T> res(pt); res.Rotate(a); return res; } template <typename T, typename U> Point<T> const Shift(Point<T> const & pt, U const & dx, U const & dy) { return Point<T>(pt.x + dx, pt.y + dy); } template <typename T, typename U> Point<T> const Shift(Point<T> const & pt, Point<U> const & offset) { return Shift(pt, offset.x, offset.y); } template <typename T> Point<T> const Floor(Point<T> const & pt) { Point<T> res; res.x = floor(pt.x); res.y = floor(pt.y); return res; } template <typename T> bool IsPointStrictlyInsideTriangle(Point<T> const & p, Point<T> const & a, Point<T> const & b, Point<T> const & c) { T const cpab = CrossProduct(b - a, p - a); T const cpbc = CrossProduct(c - b, p - b); T const cpca = CrossProduct(a - c, p - c); return (cpab < 0 && cpbc < 0 && cpca < 0) || (cpab > 0 && cpbc > 0 && cpca > 0); } template <typename T> bool SegmentsIntersect(Point<T> const & a, Point<T> const & b, Point<T> const & c, Point<T> const & d) { return max(a.x, b.x) >= min(c.x, d.x) && min(a.x, b.x) <= max(c.x, d.x) && max(a.y, b.y) >= min(c.y, d.y) && min(a.y, b.y) <= max(c.y, d.y) && CrossProduct(c - a, b - a) * CrossProduct(d - a, b - a) <= 0 && CrossProduct(a - c, d - c) * CrossProduct(b - c, d - c) <= 0; } /// Is segment (v, v1) in cone (vPrev, v, vNext)? /// @precondition Orientation CCW!!! template <typename PointT> bool IsSegmentInCone(PointT v, PointT v1, PointT vPrev, PointT vNext) { PointT const diff = v1 - v; PointT const edgeL = vPrev - v; PointT const edgeR = vNext - v; double const cpLR = CrossProduct(edgeR, edgeL); if (my::AlmostEqual(cpLR, 0.0)) { // Points vPrev, v, vNext placed on one line; // use property that polygon has CCW orientation. return CrossProduct(vNext - vPrev, v1 - vPrev) > 0.0; } if (cpLR > 0) { // vertex is convex return CrossProduct(diff, edgeR) < 0 && CrossProduct(diff, edgeL) > 0.0; } else { // vertex is reflex return CrossProduct(diff, edgeR) < 0 || CrossProduct(diff, edgeL) > 0.0; } } template <typename T> string DebugPrint(m2::Point<T> const & p) { ostringstream out; out.precision(20); out << "m2::Point<" << typeid(T).name() << ">(" << p.x << ", " << p.y << ")"; return out.str(); } template <typename T> bool AlmostEqual(m2::Point<T> const & a, m2::Point<T> const & b) { return my::AlmostEqual(a.x, b.x) && my::AlmostEqual(a.y, b.y); } template <class TArchive, class PointT> TArchive & operator >> (TArchive & ar, m2::Point<PointT> & pt) { ar >> pt.x; ar >> pt.y; return ar; } template <class TArchive, class PointT> TArchive & operator << (TArchive & ar, m2::Point<PointT> const & pt) { ar << pt.x; ar << pt.y; return ar; } template <typename T> bool operator< (Point<T> const & l, Point<T> const & r) { if (l.x != r.x) return l.x < r.x; return l.y < r.y; } typedef Point<float> PointF; typedef Point<double> PointD; typedef Point<uint32_t> PointU; typedef Point<uint64_t> PointU64; typedef Point<int32_t> PointI; typedef Point<int64_t> PointI64; }
#pragma once #include "../base/assert.hpp" #include "../base/base.hpp" #include "../base/math.hpp" #include "../base/matrix.hpp" #include "../std/cmath.hpp" #include "../std/sstream.hpp" #include "../std/typeinfo.hpp" namespace m2 { template <typename T> class Point { public: typedef T value_type; T x, y; Point() {} Point(T x_, T y_) : x(x_), y(y_) {} template <typename U> Point(Point<U> const & u) : x(u.x), y(u.y) {} bool EqualDxDy(m2::Point<T> const & p, T eps) const { return ((fabs(x - p.x) < eps) && (fabs(y - p.y) < eps)); } double SquareLength(m2::Point<T> const & p) const { return math::sqr(x - p.x) + math::sqr(y - p.y); } double Length(m2::Point<T> const & p) const { return sqrt(SquareLength(p)); } m2::Point<T> Move(T len, T ang) const { return m2::Point<T>(x + len * cos(ang), y + len * sin(ang)); } m2::Point<T> Move(T len, T angSin, T angCos) const { return m2::Point<T>(x + len * angCos, y + len * angSin); } Point<T> const & operator-=(Point<T> const & a) { x -= a.x; y -= a.y; return *this; } Point<T> const & operator+=(Point<T> const & a) { x += a.x; y += a.y; return *this; } template <typename U> Point<T> const & operator*=(U const & k) { x = static_cast<T>(x * k); y = static_cast<T>(y * k); return *this; } template <typename U> Point<T> const & operator=(Point<U> const & a) { x = static_cast<T>(a.x); y = static_cast<T>(a.y); return *this; } bool operator == (m2::Point<T> const & p) const { return x == p.x && y == p.y; } bool operator != (m2::Point<T> const & p) const { return !(*this == p); } m2::Point<T> operator + (m2::Point<T> const & pt) const { return m2::Point<T>(x + pt.x, y + pt.y); } m2::Point<T> operator - (m2::Point<T> const & pt) const { return m2::Point<T>(x - pt.x, y - pt.y); } m2::Point<T> operator -() const { return m2::Point<T>(-x, -y); } m2::Point<T> operator * (T scale) const { return m2::Point<T>(x * scale, y * scale); } m2::Point<T> const operator * (math::Matrix<T, 3, 3> const & m) const { m2::Point<T> res; res.x = x * m(0, 0) + y * m(1, 0) + m(2, 0); res.y = x * m(0, 1) + y * m(1, 1) + m(2, 1); return res; } m2::Point<T> operator / (T scale) const { return m2::Point<T>(x / scale, y / scale); } m2::Point<T> const & operator *= (math::Matrix<T, 3, 3> const & m) { T tempX = x; x = tempX * m(0, 0) + y * m(1, 0) + m(2, 0); y = tempX * m(0, 1) + y * m(1, 1) + m(2, 1); return *this; } void Rotate(double angle) { T cosAngle = cos(angle); T sinAngle = sin(angle); T oldX = x; x = cosAngle * oldX - sinAngle * y; y = sinAngle * oldX + cosAngle * y; } void Transform(m2::Point<T> const & org, m2::Point<T> const & dx, m2::Point<T> const & dy) { T oldX = x; x = org.x + oldX * dx.x + y * dy.x; y = org.y + oldX * dx.y + y * dy.y; } }; template <typename T> inline Point<T> const operator- (Point<T> const & a, Point<T> const & b) { return Point<T>(a.x - b.x, a.y - b.y); } template <typename T> inline Point<T> const operator+ (Point<T> const & a, Point<T> const & b) { return Point<T>(a.x + b.x, a.y + b.y); } // Dot product of a and b, equals to |a|*|b|*cos(angle_between_a_and_b). template <typename T> T const DotProduct(Point<T> const & a, Point<T> const & b) { return a.x * b.x + a.y * b.y; } // Value of cross product of a and b, equals to |a|*|b|*sin(angle_between_a_and_b). template <typename T> T const CrossProduct(Point<T> const & a, Point<T> const & b) { return a.x * b.y - a.y * b.x; } template <typename T> Point<T> const Rotate(Point<T> const & pt, T a) { Point<T> res(pt); res.Rotate(a); return res; } template <typename T, typename U> Point<T> const Shift(Point<T> const & pt, U const & dx, U const & dy) { return Point<T>(pt.x + dx, pt.y + dy); } template <typename T, typename U> Point<T> const Shift(Point<T> const & pt, Point<U> const & offset) { return Shift(pt, offset.x, offset.y); } template <typename T> Point<T> const Floor(Point<T> const & pt) { Point<T> res; res.x = floor(pt.x); res.y = floor(pt.y); return res; } template <typename T> bool IsPointInsideTriangle(Point<T> const & p, Point<T> const & a, Point<T> const & b, Point<T> const & c) { T const cpab = CrossProduct(b - a, p - a); T const cpbc = CrossProduct(c - b, p - b); T const cpca = CrossProduct(a - c, p - c); return (cpab <= 0 && cpbc <= 0 && cpca <= 0) || (cpab >= 0 && cpbc >= 0 && cpca >= 0); } template <typename T> bool IsPointStrictlyInsideTriangle(Point<T> const & p, Point<T> const & a, Point<T> const & b, Point<T> const & c) { T const cpab = CrossProduct(b - a, p - a); T const cpbc = CrossProduct(c - b, p - b); T const cpca = CrossProduct(a - c, p - c); return (cpab < 0 && cpbc < 0 && cpca < 0) || (cpab > 0 && cpbc > 0 && cpca > 0); } template <typename T> bool SegmentsIntersect(Point<T> const & a, Point<T> const & b, Point<T> const & c, Point<T> const & d) { return max(a.x, b.x) >= min(c.x, d.x) && min(a.x, b.x) <= max(c.x, d.x) && max(a.y, b.y) >= min(c.y, d.y) && min(a.y, b.y) <= max(c.y, d.y) && CrossProduct(c - a, b - a) * CrossProduct(d - a, b - a) <= 0 && CrossProduct(a - c, d - c) * CrossProduct(b - c, d - c) <= 0; } /// Is segment (v, v1) in cone (vPrev, v, vNext)? /// @precondition Orientation CCW!!! template <typename PointT> bool IsSegmentInCone(PointT v, PointT v1, PointT vPrev, PointT vNext) { PointT const diff = v1 - v; PointT const edgeL = vPrev - v; PointT const edgeR = vNext - v; double const cpLR = CrossProduct(edgeR, edgeL); if (my::AlmostEqual(cpLR, 0.0)) { // Points vPrev, v, vNext placed on one line; // use property that polygon has CCW orientation. return CrossProduct(vNext - vPrev, v1 - vPrev) > 0.0; } if (cpLR > 0) { // vertex is convex return CrossProduct(diff, edgeR) < 0 && CrossProduct(diff, edgeL) > 0.0; } else { // vertex is reflex return CrossProduct(diff, edgeR) < 0 || CrossProduct(diff, edgeL) > 0.0; } } template <typename T> string DebugPrint(m2::Point<T> const & p) { ostringstream out; out.precision(20); out << "m2::Point<" << typeid(T).name() << ">(" << p.x << ", " << p.y << ")"; return out.str(); } template <typename T> bool AlmostEqual(m2::Point<T> const & a, m2::Point<T> const & b) { return my::AlmostEqual(a.x, b.x) && my::AlmostEqual(a.y, b.y); } template <class TArchive, class PointT> TArchive & operator >> (TArchive & ar, m2::Point<PointT> & pt) { ar >> pt.x; ar >> pt.y; return ar; } template <class TArchive, class PointT> TArchive & operator << (TArchive & ar, m2::Point<PointT> const & pt) { ar << pt.x; ar << pt.y; return ar; } template <typename T> bool operator< (Point<T> const & l, Point<T> const & r) { if (l.x != r.x) return l.x < r.x; return l.y < r.y; } typedef Point<float> PointF; typedef Point<double> PointD; typedef Point<uint32_t> PointU; typedef Point<uint64_t> PointU64; typedef Point<int32_t> PointI; typedef Point<int64_t> PointI64; }
add IsPointInsideTriangle implementation
[geometry] add IsPointInsideTriangle implementation
C++
apache-2.0
vasilenkomike/omim,Komzpa/omim,Saicheg/omim,vng/omim,programming086/omim,Volcanoscar/omim,bykoianko/omim,vng/omim,bykoianko/omim,jam891/omim,trashkalmar/omim,mgsergio/omim,ygorshenin/omim,yunikkk/omim,augmify/omim,Endika/omim,goblinr/omim,mpimenov/omim,Komzpa/omim,stangls/omim,vladon/omim,therearesomewhocallmetim/omim,dkorolev/omim,65apps/omim,alexzatsepin/omim,programming086/omim,Transtech/omim,UdjinM6/omim,ygorshenin/omim,vng/omim,VladiMihaylenko/omim,albertshift/omim,mapsme/omim,AlexanderMatveenko/omim,augmify/omim,vladon/omim,andrewshadura/omim,AlexanderMatveenko/omim,syershov/omim,milchakov/omim,stangls/omim,stangls/omim,Volcanoscar/omim,65apps/omim,bykoianko/omim,lydonchandra/omim,goblinr/omim,matsprea/omim,sidorov-panda/omim,rokuz/omim,mpimenov/omim,Volcanoscar/omim,Transtech/omim,matsprea/omim,simon247/omim,65apps/omim,TimurTarasenko/omim,therearesomewhocallmetim/omim,victorbriz/omim,victorbriz/omim,sidorov-panda/omim,vng/omim,mpimenov/omim,wersoo/omim,kw217/omim,mpimenov/omim,victorbriz/omim,dobriy-eeh/omim,kw217/omim,jam891/omim,mgsergio/omim,Komzpa/omim,Volcanoscar/omim,milchakov/omim,syershov/omim,syershov/omim,syershov/omim,andrewshadura/omim,krasin/omim,dkorolev/omim,yunikkk/omim,sidorov-panda/omim,goblinr/omim,Volcanoscar/omim,alexzatsepin/omim,gardster/omim,Transtech/omim,ygorshenin/omim,edl00k/omim,guard163/omim,syershov/omim,vasilenkomike/omim,Zverik/omim,kw217/omim,syershov/omim,mapsme/omim,vng/omim,gardster/omim,sidorov-panda/omim,bykoianko/omim,simon247/omim,Endika/omim,syershov/omim,dkorolev/omim,guard163/omim,Zverik/omim,dobriy-eeh/omim,simon247/omim,TimurTarasenko/omim,vasilenkomike/omim,felipebetancur/omim,Saicheg/omim,goblinr/omim,sidorov-panda/omim,vng/omim,UdjinM6/omim,mpimenov/omim,vladon/omim,therearesomewhocallmetim/omim,Komzpa/omim,therearesomewhocallmetim/omim,UdjinM6/omim,vladon/omim,alexzatsepin/omim,TimurTarasenko/omim,alexzatsepin/omim,mapsme/omim,alexzatsepin/omim,Transtech/omim,darina/omim,yunikkk/omim,dobriy-eeh/omim,victorbriz/omim,simon247/omim,jam891/omim,jam891/omim,Endika/omim,guard163/omim,vng/omim,rokuz/omim,mgsergio/omim,TimurTarasenko/omim,sidorov-panda/omim,ygorshenin/omim,Saicheg/omim,dkorolev/omim,ygorshenin/omim,simon247/omim,victorbriz/omim,dobriy-eeh/omim,Volcanoscar/omim,bykoianko/omim,guard163/omim,goblinr/omim,dkorolev/omim,Endika/omim,mpimenov/omim,dkorolev/omim,Zverik/omim,darina/omim,dobriy-eeh/omim,kw217/omim,mgsergio/omim,sidorov-panda/omim,rokuz/omim,darina/omim,sidorov-panda/omim,goblinr/omim,milchakov/omim,guard163/omim,Zverik/omim,ygorshenin/omim,Transtech/omim,VladiMihaylenko/omim,victorbriz/omim,kw217/omim,lydonchandra/omim,65apps/omim,stangls/omim,albertshift/omim,ygorshenin/omim,augmify/omim,darina/omim,felipebetancur/omim,Transtech/omim,kw217/omim,UdjinM6/omim,stangls/omim,igrechuhin/omim,jam891/omim,Zverik/omim,UdjinM6/omim,trashkalmar/omim,rokuz/omim,matsprea/omim,bykoianko/omim,edl00k/omim,Endika/omim,Zverik/omim,VladiMihaylenko/omim,Zverik/omim,igrechuhin/omim,therearesomewhocallmetim/omim,TimurTarasenko/omim,felipebetancur/omim,wersoo/omim,ygorshenin/omim,Komzpa/omim,yunikkk/omim,mpimenov/omim,jam891/omim,jam891/omim,VladiMihaylenko/omim,mapsme/omim,Endika/omim,stangls/omim,UdjinM6/omim,VladiMihaylenko/omim,Zverik/omim,igrechuhin/omim,sidorov-panda/omim,wersoo/omim,mgsergio/omim,Volcanoscar/omim,jam891/omim,ygorshenin/omim,guard163/omim,stangls/omim,rokuz/omim,dobriy-eeh/omim,Komzpa/omim,felipebetancur/omim,dobriy-eeh/omim,programming086/omim,mapsme/omim,stangls/omim,simon247/omim,milchakov/omim,Volcanoscar/omim,felipebetancur/omim,guard163/omim,vladon/omim,vladon/omim,bykoianko/omim,matsprea/omim,felipebetancur/omim,krasin/omim,edl00k/omim,syershov/omim,vasilenkomike/omim,mpimenov/omim,Transtech/omim,trashkalmar/omim,goblinr/omim,matsprea/omim,stangls/omim,VladiMihaylenko/omim,mapsme/omim,UdjinM6/omim,mpimenov/omim,rokuz/omim,trashkalmar/omim,darina/omim,Saicheg/omim,wersoo/omim,andrewshadura/omim,victorbriz/omim,rokuz/omim,stangls/omim,UdjinM6/omim,VladiMihaylenko/omim,mpimenov/omim,therearesomewhocallmetim/omim,albertshift/omim,kw217/omim,UdjinM6/omim,wersoo/omim,simon247/omim,albertshift/omim,65apps/omim,albertshift/omim,simon247/omim,sidorov-panda/omim,trashkalmar/omim,mapsme/omim,AlexanderMatveenko/omim,Transtech/omim,dkorolev/omim,alexzatsepin/omim,milchakov/omim,goblinr/omim,yunikkk/omim,programming086/omim,dobriy-eeh/omim,mgsergio/omim,AlexanderMatveenko/omim,mgsergio/omim,trashkalmar/omim,augmify/omim,milchakov/omim,yunikkk/omim,krasin/omim,igrechuhin/omim,dobriy-eeh/omim,rokuz/omim,programming086/omim,AlexanderMatveenko/omim,andrewshadura/omim,vng/omim,milchakov/omim,edl00k/omim,augmify/omim,albertshift/omim,Komzpa/omim,programming086/omim,AlexanderMatveenko/omim,VladiMihaylenko/omim,krasin/omim,Komzpa/omim,edl00k/omim,vasilenkomike/omim,Volcanoscar/omim,vng/omim,igrechuhin/omim,gardster/omim,igrechuhin/omim,bykoianko/omim,mgsergio/omim,andrewshadura/omim,guard163/omim,syershov/omim,gardster/omim,jam891/omim,VladiMihaylenko/omim,Zverik/omim,rokuz/omim,Saicheg/omim,Transtech/omim,Saicheg/omim,augmify/omim,alexzatsepin/omim,yunikkk/omim,dkorolev/omim,Transtech/omim,ygorshenin/omim,darina/omim,lydonchandra/omim,jam891/omim,mapsme/omim,Saicheg/omim,matsprea/omim,therearesomewhocallmetim/omim,krasin/omim,vasilenkomike/omim,victorbriz/omim,alexzatsepin/omim,AlexanderMatveenko/omim,dobriy-eeh/omim,felipebetancur/omim,therearesomewhocallmetim/omim,igrechuhin/omim,vng/omim,lydonchandra/omim,gardster/omim,dkorolev/omim,stangls/omim,andrewshadura/omim,milchakov/omim,rokuz/omim,trashkalmar/omim,ygorshenin/omim,augmify/omim,matsprea/omim,lydonchandra/omim,alexzatsepin/omim,65apps/omim,edl00k/omim,igrechuhin/omim,edl00k/omim,goblinr/omim,wersoo/omim,felipebetancur/omim,andrewshadura/omim,syershov/omim,milchakov/omim,dobriy-eeh/omim,therearesomewhocallmetim/omim,mgsergio/omim,andrewshadura/omim,alexzatsepin/omim,darina/omim,edl00k/omim,bykoianko/omim,lydonchandra/omim,mgsergio/omim,trashkalmar/omim,Komzpa/omim,mapsme/omim,Endika/omim,mpimenov/omim,Saicheg/omim,krasin/omim,edl00k/omim,mpimenov/omim,TimurTarasenko/omim,Saicheg/omim,alexzatsepin/omim,matsprea/omim,VladiMihaylenko/omim,ygorshenin/omim,goblinr/omim,programming086/omim,mgsergio/omim,augmify/omim,wersoo/omim,vladon/omim,yunikkk/omim,syershov/omim,gardster/omim,programming086/omim,Transtech/omim,bykoianko/omim,krasin/omim,gardster/omim,vladon/omim,Zverik/omim,rokuz/omim,felipebetancur/omim,milchakov/omim,guard163/omim,andrewshadura/omim,milchakov/omim,alexzatsepin/omim,programming086/omim,darina/omim,wersoo/omim,Endika/omim,victorbriz/omim,milchakov/omim,darina/omim,guard163/omim,albertshift/omim,albertshift/omim,matsprea/omim,darina/omim,VladiMihaylenko/omim,trashkalmar/omim,TimurTarasenko/omim,gardster/omim,darina/omim,augmify/omim,yunikkk/omim,trashkalmar/omim,AlexanderMatveenko/omim,AlexanderMatveenko/omim,andrewshadura/omim,darina/omim,TimurTarasenko/omim,Komzpa/omim,Volcanoscar/omim,augmify/omim,krasin/omim,vasilenkomike/omim,mapsme/omim,TimurTarasenko/omim,kw217/omim,65apps/omim,therearesomewhocallmetim/omim,gardster/omim,simon247/omim,lydonchandra/omim,darina/omim,igrechuhin/omim,lydonchandra/omim,syershov/omim,programming086/omim,albertshift/omim,mpimenov/omim,Zverik/omim,matsprea/omim,yunikkk/omim,65apps/omim,vladon/omim,Endika/omim,lydonchandra/omim,Saicheg/omim,mapsme/omim,goblinr/omim,kw217/omim,syershov/omim,Transtech/omim,victorbriz/omim,milchakov/omim,bykoianko/omim,trashkalmar/omim,65apps/omim,krasin/omim,dobriy-eeh/omim,UdjinM6/omim,Endika/omim,rokuz/omim,kw217/omim,VladiMihaylenko/omim,VladiMihaylenko/omim,igrechuhin/omim,trashkalmar/omim,mapsme/omim,felipebetancur/omim,dobriy-eeh/omim,lydonchandra/omim,vasilenkomike/omim,vasilenkomike/omim,vasilenkomike/omim,bykoianko/omim,wersoo/omim,vladon/omim,gardster/omim,65apps/omim,rokuz/omim,goblinr/omim,krasin/omim,Zverik/omim,yunikkk/omim,mgsergio/omim,albertshift/omim,TimurTarasenko/omim,goblinr/omim,edl00k/omim,wersoo/omim,alexzatsepin/omim,simon247/omim,65apps/omim,bykoianko/omim,Zverik/omim,mapsme/omim,AlexanderMatveenko/omim,dkorolev/omim
b6969463304806938af9a9ec3eace1d8149b7157
sorting/heapSort.cpp
sorting/heapSort.cpp
/* Algorithm : Heap Sort Refer : CLRS Chapter on heap sort Author : manojpandey */ #include <iostream> #include <cstdio> #include <string> #include <utility> // pair #include <vector> #include <algorithm> #include <cmath> #include <cstring> //memset using namespace std; typedef vector<int> vi; typedef vector<vi> vvi; typedef pair<int,int> ii; typedef long long ll; #define sz(a) int((a).size()) #define pb push_back #define all(c) (c).begin(),(c).end() #define PRINTesent(c,x) ((c).find(x) != (c).end()) #define cPRINTesent(c,x) (find(all(c),x) != (c).end()) #define tr(container, it) for(typeof(container.begin()) it = container.begin(); it != container.end(); it++) #define rep(i,n) for (i=0; i<n ; i++) #define rep1(i,n) for (i=1; i<=n ; i++) #define MAX 1111111 #define parent(i) (i/2) #define left(i) (2*i) #define right(i) (2*i)+1 int a[MAX]; int N, heapSize; // Custom print function to // print in the form of tree void PRINT(int a[], int i) { if(i<=N/2) { for (int k = 1;k<=log2(2*i);k++) cout << " |"; cout << a[2*i] << "\n"; PRINT(a, 2*i); for (int k = 1;k<=log2(2*i+1);k++) cout << " |"; cout << a[2*i+1] << "\n"; PRINT(a,2*i+1); } } void maxHeapify(int a[], int i) { int l, r, largest, j; l = left(i); r = right(i); if(l <= heapSize && a[l] > a[i]) largest = l; else largest = i; if(r <= heapSize && a[r] > a[largest]) largest = r; if(largest != i) { swap(a[i], a[largest]); maxHeapify(a, largest); } } void buildMaxHeap(int a[]) { for (int i = N/2 ; i >0 ; i--) maxHeapify(a, i); } void HeapSort(int a[]) { buildMaxHeap(a); for (int i = N ; i > 1 ; i--) { swap(a[1], a[i]); heapSize--; maxHeapify(a, 1); } } int main() { freopen ("in.txt", "r", stdin); int i; cin >> N; heapSize = N; rep1(i, N) cin >> a[i]; cout << "INPUT:\n"; cout << a[1] << "\n"; PRINT(a,1); HeapSort(a); cout << "OUTPUT:\n"; cout << a[1] << "\n"; PRINT(a,1); return 0; } /* 10 4 1 3 2 16 9 10 14 8 7 INPUT: 4 |1 | |2 | | |14 | | |8 | |16 | | |7 | | |0 |3 | |9 | |10 OUTPUT: 1 |2 | |4 | | |10 | | |14 | |7 | | |16 | | |0 |3 | |8 | |9 */
/* Algorithm : Heap Sort Refer : CLRS Chapter on heap sort Author : manojpandey */ #include <iostream> #include <cstdio> #include <string> #include <utility> // pair #include <vector> #include <algorithm> #include <cmath> #include <cstring> //memset using namespace std; typedef vector<int> vi; typedef vector<vi> vvi; typedef pair<int,int> ii; typedef long long ll; #define sz(a) int((a).size()) #define pb push_back #define all(c) (c).begin(),(c).end() #define present(c,x) ((c).find(x) != (c).end()) #define cpresent(c,x) (find(all(c),x) != (c).end()) #define tr(container, it) for(typeof(container.begin()) it = container.begin(); it != container.end(); it++) #define rep(i,n) for (i=0; i<n ; i++) #define rep1(i,n) for (i=1; i<=n ; i++) #define MAX 1111111 #define parent(i) (i/2) #define left(i) (2*i) #define right(i) (2*i)+1 int a[MAX]; int N, heapSize; // Custom print function to // print in the form of tree void PRINT(int a[], int i) { if(i<=N/2) { for (int k = 1;k<=log2(2*i);k++) cout << " |"; cout << a[2*i] << "\n"; PRINT(a, 2*i); for (int k = 1;k<=log2(2*i+1);k++) cout << " |"; cout << a[2*i+1] << "\n"; PRINT(a,2*i+1); } } void maxHeapify(int a[], int i) { int l, r, largest, j; l = left(i); r = right(i); if(l <= heapSize && a[l] > a[i]) largest = l; else largest = i; if(r <= heapSize && a[r] > a[largest]) largest = r; if(largest != i) { swap(a[i], a[largest]); maxHeapify(a, largest); } } void buildMaxHeap(int a[]) { for (int i = N/2 ; i >0 ; i--) maxHeapify(a, i); } void HeapSort(int a[]) { buildMaxHeap(a); for (int i = N ; i > 1 ; i--) { swap(a[1], a[i]); heapSize--; maxHeapify(a, 1); } } int main() { freopen ("in.txt", "r", stdin); int i; cin >> N; heapSize = N; rep1(i, N) cin >> a[i]; cout << "INPUT:\n"; cout << a[1] << "\n"; PRINT(a,1); HeapSort(a); cout << "OUTPUT:\n"; cout << a[1] << "\n"; PRINT(a,1); return 0; } /* 10 4 1 3 2 16 9 10 14 8 7 INPUT: 4 |1 | |2 | | |14 | | |8 | |16 | | |7 | | |0 |3 | |9 | |10 OUTPUT: 1 |2 | |4 | | |10 | | |14 | |7 | | |16 | | |0 |3 | |8 | |9 */
Update heapSort.cpp
Update heapSort.cpp
C++
mit
manojpandey/utility
9a6de9f7ac243b67f237cabbd0f3cc544da4ad8b
include/Nazara/Math/Vector4.hpp
include/Nazara/Math/Vector4.hpp
// Copyright (C) 2015 Rémi Bèges - Jérôme Leclercq // This file is part of the "Nazara Engine - Mathematics module" // For conditions of distribution and use, see copyright notice in Config.hpp #pragma once #ifndef NAZARA_VECTOR4_HPP #define NAZARA_VECTOR4_HPP #include <Nazara/Core/String.hpp> namespace Nz { struct SerializationContext; template<typename T> class Vector2; template<typename T> class Vector3; template<typename T> class Vector4 { public: Vector4() = default; Vector4(T X, T Y, T Z, T W = 1.0); Vector4(T X, T Y, const Vector2<T>& vec); Vector4(T X, const Vector2<T>& vec, T W); Vector4(T X, const Vector3<T>& vec); explicit Vector4(T scale); Vector4(const T vec[4]); Vector4(const Vector2<T>& vec, T Z = 0.0, T W = 1.0); Vector4(const Vector3<T>& vec, T W = 0.0); template<typename U> explicit Vector4(const Vector4<U>& vec); Vector4(const Vector4& vec) = default; ~Vector4() = default; T AbsDotProduct(const Vector4& vec) const; T DotProduct(const Vector4& vec) const; Vector4 GetNormal(T* length = nullptr) const; Vector4& MakeUnitX(); Vector4& MakeUnitY(); Vector4& MakeUnitZ(); Vector4& MakeZero(); Vector4& Maximize(const Vector4& vec); Vector4& Minimize(const Vector4& vec); Vector4& Normalize(T* length = nullptr); Vector4& Set(T X, T Y, T Z, T W = 1.0); Vector4& Set(T X, T Y, const Vector2<T>& vec); Vector4& Set(T X, const Vector2<T>& vec, T W); Vector4& Set(T X, const Vector3<T>& vec); Vector4& Set(T scale); Vector4& Set(const T vec[4]); Vector4& Set(const Vector2<T>& vec, T Z = 0.0, T W = 1.0); Vector4& Set(const Vector3<T>& vec, T W = 1.0); Vector4& Set(const Vector4<T>& vec); template<typename U> Vector4& Set(const Vector4<U>& vec); String ToString() const; operator T* (); operator const T* () const; const Vector4& operator+() const; Vector4 operator-() const; Vector4 operator+(const Vector4& vec) const; Vector4 operator-(const Vector4& vec) const; Vector4 operator*(const Vector4& vec) const; Vector4 operator*(T scale) const; Vector4 operator/(const Vector4& vec) const; Vector4 operator/(T scale) const; Vector4& operator+=(const Vector4& vec); Vector4& operator-=(const Vector4& vec); Vector4& operator*=(const Vector4& vec); Vector4& operator*=(T scale); Vector4& operator/=(const Vector4& vec); Vector4& operator/=(T scale); bool operator==(const Vector4& vec) const; bool operator!=(const Vector4& vec) const; bool operator<(const Vector4& vec) const; bool operator<=(const Vector4& vec) const; bool operator>(const Vector4& vec) const; bool operator>=(const Vector4& vec) const; static T DotProduct(const Vector4& vec1, const Vector4& vec2); static Vector4 Lerp(const Vector4& from, const Vector4& to, T interpolation); static Vector4 Normalize(const Vector4& vec); static Vector4 UnitX(); static Vector4 UnitY(); static Vector4 UnitZ(); static Vector4 Zero(); T x, y, z, w; }; typedef Vector4<double> Vector4d; typedef Vector4<float> Vector4f; typedef Vector4<int> Vector4i; typedef Vector4<unsigned int> Vector4ui; typedef Vector4<Int32> Vector4i32; typedef Vector4<UInt32> Vector4ui32; template<typename T> bool Serialize(SerializationContext& context, const Vector4<T>& vector); template<typename T> bool Unserialize(SerializationContext& context, Vector4<T>* vector); } template<typename T> std::ostream& operator<<(std::ostream& out, const Nz::Vector4<T>& vec); template<typename T> Nz::Vector4<T> operator*(T scale, const Nz::Vector4<T>& vec); template<typename T> Nz::Vector4<T> operator/(T scale, const Nz::Vector4<T>& vec); #include <Nazara/Math/Vector4.inl> #endif // NAZARA_VECTOR4_HPP
// Copyright (C) 2015 Rémi Bèges - Jérôme Leclercq // This file is part of the "Nazara Engine - Mathematics module" // For conditions of distribution and use, see copyright notice in Config.hpp #pragma once #ifndef NAZARA_VECTOR4_HPP #define NAZARA_VECTOR4_HPP #include <Nazara/Core/String.hpp> namespace Nz { struct SerializationContext; template<typename T> class Vector2; template<typename T> class Vector3; template<typename T> class Vector4 { public: Vector4() = default; Vector4(T X, T Y, T Z, T W = 1.0); Vector4(T X, T Y, const Vector2<T>& vec); Vector4(T X, const Vector2<T>& vec, T W); Vector4(T X, const Vector3<T>& vec); explicit Vector4(T scale); Vector4(const T vec[4]); Vector4(const Vector2<T>& vec, T Z = 0.0, T W = 1.0); Vector4(const Vector3<T>& vec, T W = 1.0); template<typename U> explicit Vector4(const Vector4<U>& vec); Vector4(const Vector4& vec) = default; ~Vector4() = default; T AbsDotProduct(const Vector4& vec) const; T DotProduct(const Vector4& vec) const; Vector4 GetNormal(T* length = nullptr) const; Vector4& MakeUnitX(); Vector4& MakeUnitY(); Vector4& MakeUnitZ(); Vector4& MakeZero(); Vector4& Maximize(const Vector4& vec); Vector4& Minimize(const Vector4& vec); Vector4& Normalize(T* length = nullptr); Vector4& Set(T X, T Y, T Z, T W = 1.0); Vector4& Set(T X, T Y, const Vector2<T>& vec); Vector4& Set(T X, const Vector2<T>& vec, T W); Vector4& Set(T X, const Vector3<T>& vec); Vector4& Set(T scale); Vector4& Set(const T vec[4]); Vector4& Set(const Vector2<T>& vec, T Z = 0.0, T W = 1.0); Vector4& Set(const Vector3<T>& vec, T W = 1.0); Vector4& Set(const Vector4<T>& vec); template<typename U> Vector4& Set(const Vector4<U>& vec); String ToString() const; operator T* (); operator const T* () const; const Vector4& operator+() const; Vector4 operator-() const; Vector4 operator+(const Vector4& vec) const; Vector4 operator-(const Vector4& vec) const; Vector4 operator*(const Vector4& vec) const; Vector4 operator*(T scale) const; Vector4 operator/(const Vector4& vec) const; Vector4 operator/(T scale) const; Vector4& operator+=(const Vector4& vec); Vector4& operator-=(const Vector4& vec); Vector4& operator*=(const Vector4& vec); Vector4& operator*=(T scale); Vector4& operator/=(const Vector4& vec); Vector4& operator/=(T scale); bool operator==(const Vector4& vec) const; bool operator!=(const Vector4& vec) const; bool operator<(const Vector4& vec) const; bool operator<=(const Vector4& vec) const; bool operator>(const Vector4& vec) const; bool operator>=(const Vector4& vec) const; static T DotProduct(const Vector4& vec1, const Vector4& vec2); static Vector4 Lerp(const Vector4& from, const Vector4& to, T interpolation); static Vector4 Normalize(const Vector4& vec); static Vector4 UnitX(); static Vector4 UnitY(); static Vector4 UnitZ(); static Vector4 Zero(); T x, y, z, w; }; typedef Vector4<double> Vector4d; typedef Vector4<float> Vector4f; typedef Vector4<int> Vector4i; typedef Vector4<unsigned int> Vector4ui; typedef Vector4<Int32> Vector4i32; typedef Vector4<UInt32> Vector4ui32; template<typename T> bool Serialize(SerializationContext& context, const Vector4<T>& vector); template<typename T> bool Unserialize(SerializationContext& context, Vector4<T>* vector); } template<typename T> std::ostream& operator<<(std::ostream& out, const Nz::Vector4<T>& vec); template<typename T> Nz::Vector4<T> operator*(T scale, const Nz::Vector4<T>& vec); template<typename T> Nz::Vector4<T> operator/(T scale, const Nz::Vector4<T>& vec); #include <Nazara/Math/Vector4.inl> #endif // NAZARA_VECTOR4_HPP
Fix w value when converting from Vector3
Math/Vector4: Fix w value when converting from Vector3 Former-commit-id: 0ad39219de839bb1de859baac059441e36c04444 [formerly d2516303dd597418bd2939f737617f0fad1f0da4] Former-commit-id: 7d5223e4e34b50dbb4ec9e0d22c7801470099d2a
C++
mit
DigitalPulseSoftware/NazaraEngine
8424d1b41b50a0f43277d2609efa808e2b3ef524
include/cppurses/system/key.hpp
include/cppurses/system/key.hpp
#ifndef CPPURSES_SYSTEM_KEY_HPP #define CPPURSES_SYSTEM_KEY_HPP namespace cppurses { /// Enums for key codes from the keyboard with descriptive names. /** Names taken from ncurses. */ enum class Key : short { // Control Characters Null = 0, // Ctrl + Space, or Ctrl + 2, OR Ctrl + @ Ctrl_a, // Start of heading Ctrl_b, // Start of text Ctrl_c, // End of text Ctrl_d, // End of transmission Ctrl_e, // Enquiry Ctrl_f, // Acknowledge Ctrl_g, // Bell Backspace_, // Not used? ascii value 8 check with keypad Tab, // Ctrl + I Enter, // Ctrl + J, or Ctrl + M, AKA Line Feed, AKA Carriage Return Ctrl_k, // Vertical Tab Ctrl_l, // Form Feed Carriage_return_, // old, not on modern keyboards Ctrl_n, // Shift Out Ctrl_o, // Shift In Ctrl_p, // Data Link Escape Ctrl_q, // Device Control One Ctrl_r, // Device Control Two Ctrl_s, // Device Control Three Ctrl_t, // Device Control Four Ctrl_u, // Negative Acknowledge Ctrl_v, // Synchronous Idle Ctrl_w, // End of Transmission Block Ctrl_x, // Cancel Ctrl_y, // End of Medium Ctrl_z, // Substitute Escape, // Ctrl + [, or Ctrl + 3 Ctrl_backslash, // Ctrl + 4, File Separator Ctrl_closed_bracket, // Ctrl + 5, Group Separator Ctrl_caret, // Ctrl + 6, Record Separator Ctrl_underscore, // Ctrl + 7, Unit Separator Backspace = 127, // Ctrl + 8 // Printable Characters Space = 32, Exclamation_mark, Double_quotation, Hash, Dollar, Percent, Ampersand, Apostrophe, Left_parenthesis, Right_parenthesis, Asterisk, Plus, Comma, Minus, Period, Forward_slash, Zero, One, Two, Three, Four, Five, Six, Seven, Eight, Nine, Colon, Semicolon, Less_than, Equals, Greater_than, Question_mark, At_sign, A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z, Left_bracket, Backslash, Right_bracket, Caret, Underscore, Accent, a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z, Left_curly_bracket, Vertical_bar, Right_curly_bracket, Tilde, // Curses Specialty Characters Arrow_down = 258, Arrow_up, Arrow_left, Arrow_right, Home, Backspace_2, // unused? int 263 // Function keys, up to 63. // Add function number to enum for more. ex) F15 key = Key::Function + 15; Function = 264, Function1, Function2, Function3, Function4, Function5, Function6, Function7, Function8, Function9, Function10, Function11, Function12, Delete_line = 328, Insert_line, Delete_character, Insert_character, EIC, // sent by rmir or smir in insert mode Clear_screen, Clear_to_end_of_screen, Clear_to_end_of_line, Scroll_forward, Scroll_backward, Next_page, Previous_page, Set_tab, Clear_tab, Clear_all_tabs, Possibly_keypad_enter_, // int 343 Print = 346, Home_down, Keypad_7, Keypad_9, Keypad_5, Keypad_1, Keypad_3, Back_tab, Begin, Cancel_dup_, Close, Command, Copy, Create, End, Exit, Find, Help, Mark, Message, Move, Next, Open, Options, Previous, Redo, Reference, Refresh, Replace, Restart, Resume, Save, Shift_begin, Shift_cancel, Shift_command, Shift_copy, Shift_create, Shift_delete_character, Shift_delete_line, Select, Shift_end, Shift_clear_to_end_of_line, Shift_exit, Shift_find, Shift_help, Shift_home, Shift_insert_character, Shift_left_arrow, Shift_message, Shift_move, Shift_next, Shift_options, Shift_previous, Shift_print, Shift_redo, Shift_replace, Shift_right_arrow, Shift_resume, Shift_save, Shift_suspend, Shift_undo, Suspend, Undo }; /// Translate a keycode \p key into its char representation. /** Returns '\0' if \p key does not have a printable representation. */ char key_to_char(Key key); } // namespace cppurses #endif // CPPURSES_SYSTEM_KEY_HPP
#ifndef CPPURSES_SYSTEM_KEY_HPP #define CPPURSES_SYSTEM_KEY_HPP #include <cstddef> #include <functional> #include <type_traits> namespace cppurses { /// Enums for key codes from the keyboard with descriptive names. /** Names taken from ncurses. */ enum class Key : short { // Control Characters Null = 0, // Ctrl + Space, or Ctrl + 2, OR Ctrl + @ Ctrl_a, // Start of heading Ctrl_b, // Start of text Ctrl_c, // End of text Ctrl_d, // End of transmission Ctrl_e, // Enquiry Ctrl_f, // Acknowledge Ctrl_g, // Bell Backspace_, // Not used? ascii value 8 check with keypad Tab, // Ctrl + I Enter, // Ctrl + J, or Ctrl + M, AKA Line Feed, AKA Carriage Return Ctrl_k, // Vertical Tab Ctrl_l, // Form Feed Carriage_return_, // old, not on modern keyboards Ctrl_n, // Shift Out Ctrl_o, // Shift In Ctrl_p, // Data Link Escape Ctrl_q, // Device Control One Ctrl_r, // Device Control Two Ctrl_s, // Device Control Three Ctrl_t, // Device Control Four Ctrl_u, // Negative Acknowledge Ctrl_v, // Synchronous Idle Ctrl_w, // End of Transmission Block Ctrl_x, // Cancel Ctrl_y, // End of Medium Ctrl_z, // Substitute Escape, // Ctrl + [, or Ctrl + 3 Ctrl_backslash, // Ctrl + 4, File Separator Ctrl_closed_bracket, // Ctrl + 5, Group Separator Ctrl_caret, // Ctrl + 6, Record Separator Ctrl_underscore, // Ctrl + 7, Unit Separator Backspace = 127, // Ctrl + 8 // Printable Characters Space = 32, Exclamation_mark, Double_quotation, Hash, Dollar, Percent, Ampersand, Apostrophe, Left_parenthesis, Right_parenthesis, Asterisk, Plus, Comma, Minus, Period, Forward_slash, Zero, One, Two, Three, Four, Five, Six, Seven, Eight, Nine, Colon, Semicolon, Less_than, Equals, Greater_than, Question_mark, At_sign, A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z, Left_bracket, Backslash, Right_bracket, Caret, Underscore, Accent, a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z, Left_curly_bracket, Vertical_bar, Right_curly_bracket, Tilde, // Curses Specialty Characters Arrow_down = 258, Arrow_up, Arrow_left, Arrow_right, Home, Backspace_2, // unused? int 263 // Function keys, up to 63. // Add function number to enum for more. ex) F15 key = Key::Function + 15; Function = 264, Function1, Function2, Function3, Function4, Function5, Function6, Function7, Function8, Function9, Function10, Function11, Function12, Delete_line = 328, Insert_line, Delete_character, Insert_character, EIC, // sent by rmir or smir in insert mode Clear_screen, Clear_to_end_of_screen, Clear_to_end_of_line, Scroll_forward, Scroll_backward, Next_page, Previous_page, Set_tab, Clear_tab, Clear_all_tabs, Possibly_keypad_enter_, // int 343 Print = 346, Home_down, Keypad_7, Keypad_9, Keypad_5, Keypad_1, Keypad_3, Back_tab, Begin, Cancel_dup_, Close, Command, Copy, Create, End, Exit, Find, Help, Mark, Message, Move, Next, Open, Options, Previous, Redo, Reference, Refresh, Replace, Restart, Resume, Save, Shift_begin, Shift_cancel, Shift_command, Shift_copy, Shift_create, Shift_delete_character, Shift_delete_line, Select, Shift_end, Shift_clear_to_end_of_line, Shift_exit, Shift_find, Shift_help, Shift_home, Shift_insert_character, Shift_left_arrow, Shift_message, Shift_move, Shift_next, Shift_options, Shift_previous, Shift_print, Shift_redo, Shift_replace, Shift_right_arrow, Shift_resume, Shift_save, Shift_suspend, Shift_undo, Suspend, Undo }; /// Translate a keycode \p key into its char representation. /** Returns '\0' if \p key does not have a printable representation. */ char key_to_char(Key key); } // namespace cppurses // Required for gcc < 6.1 && sometimes clang 7? namespace std { template <> struct hash<cppurses::Key> { using argument_type = cppurses::Key; using result_type = std::size_t; using underlying_t = std::underlying_type_t<argument_type>; result_type operator()(const argument_type& key) const noexcept { return std::hash<underlying_t>{}(static_cast<underlying_t>(key)); } }; } // namespace std #endif // CPPURSES_SYSTEM_KEY_HPP
Add std::hash cppurses::Key specialization for older compilers.
Add std::hash cppurses::Key specialization for older compilers.
C++
mit
a-n-t-h-o-n-y/CPPurses
4db8fcb77315a5b913e453ffa92966963605847e
include/distortos/FifoQueue.hpp
include/distortos/FifoQueue.hpp
/** * \file * \brief FifoQueue class header * * \author Copyright (C) 2014 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info * * \par License * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not * distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. * * \date 2014-12-10 */ #ifndef INCLUDE_DISTORTOS_FIFOQUEUE_HPP_ #define INCLUDE_DISTORTOS_FIFOQUEUE_HPP_ #include "distortos/scheduler/FifoQueueBase.hpp" namespace distortos { /** * \brief FifoQueue class is a simple FIFO queue for thread-thread, thread-interrupt or interrupt-interrupt * communication. It supports multiple readers and multiple writers. It is implemented as a thin wrapper for * scheduler::FifoQueueBase. * * \param T is the type of data in queue */ template<typename T> class FifoQueue : private scheduler::FifoQueueBase { public: /// type of uninitialized storage for data using Storage = Storage<T>; /** * \brief FifoQueue's constructor * * \param [in] storage is an array of Storage elements * \param [in] maxElements is the number of elements in storage array */ FifoQueue(Storage* const storage, const size_t maxElements) : FifoQueueBase{storage, maxElements, TypeTag<T>{}} { } /** * \brief Pops the oldest (first) element from the queue. * * Wrapper for scheduler::FifoQueueBase::pop(T&) * * \param [out] value is a reference to object that will be used to return popped value, its contents are swapped * with the value in the queue's storage and destructed when no longer needed * * \return zero if element was popped successfully, error code otherwise: * - error codes returned by Semaphore::wait(); * - error codes returned by Semaphore::post(); */ int pop(T& value) { return FifoQueueBase::pop(value); } /** * \brief Pushes the element to the queue. * * Wrapper for scheduler::FifoQueueBase::push(const T&) * * \param [in] value is a reference to object that will be pushed, value in queue's storage is copy-constructed * * \return zero if element was pushed successfully, error code otherwise: * - error codes returned by Semaphore::wait(); * - error codes returned by Semaphore::post(); */ int push(const T& value) { return FifoQueueBase::push(value); } /** * \brief Pushes the element to the queue. * * Wrapper for scheduler::FifoQueueBase::push(T&&) * * \param [in] value is a rvalue reference to object that will be pushed, value in queue's storage is * move-constructed * * \return zero if element was pushed successfully, error code otherwise: * - error codes returned by Semaphore::wait(); * - error codes returned by Semaphore::post(); */ int push(T&& value) { return FifoQueueBase::push(std::move(value)); } /** * \brief Tries to pop the oldest (first) element from the queue. * * Wrapper for scheduler::FifoQueueBase::tryPop(T&) * * \param [out] value is a reference to object that will be used to return popped value, its contents are swapped * with the value in the queue's storage and destructed when no longer needed * * \return zero if element was popped successfully, error code otherwise: * - error codes returned by Semaphore::tryWait(); * - error codes returned by Semaphore::post(); */ int tryPop(T& value) { return FifoQueueBase::tryPop(value); } /** * \brief Tries to pop the oldest (first) element from the queue for a given duration of time. * * Wrapper for scheduler::FifoQueueBase::tryPopFor(TickClock::duration, T&) * * \param [in] duration is the duration after which the call will be terminated without popping the element * \param [out] value is a reference to object that will be used to return popped value, its contents are swapped * with the value in the queue's storage and destructed when no longer needed * * \return zero if element was popped successfully, error code otherwise: * - error codes returned by Semaphore::tryWaitFor(); * - error codes returned by Semaphore::post(); */ int tryPopFor(const TickClock::duration duration, T& value) { return FifoQueueBase::tryPopFor(duration, value); } /** * \brief Tries to pop the oldest (first) element from the queue until a given time point. * * Wrapper for scheduler::FifoQueueBase::tryPopUntil(TickClock::time_point, T&) * * \param [in] timePoint is the time point at which the call will be terminated without popping the element * \param [out] value is a reference to object that will be used to return popped value, its contents are swapped * with the value in the queue's storage and destructed when no longer needed * * \return zero if element was popped successfully, error code otherwise: * - error codes returned by Semaphore::tryWaitUntil(); * - error codes returned by Semaphore::post(); */ int tryPopUntil(const TickClock::time_point timePoint, T& value) { return FifoQueueBase::tryPopUntil(timePoint, value); } /** * \brief Tries to push the element to the queue. * * Wrapper for scheduler::FifoQueueBase::tryPush(const T&) * * \param [in] value is a reference to object that will be pushed, value in queue's storage is copy-constructed * * \return zero if element was pushed successfully, error code otherwise: * - error codes returned by Semaphore::tryWait(); * - error codes returned by Semaphore::post(); */ int tryPush(const T& value) { return FifoQueueBase::tryPush(value); } /** * \brief Tries to push the element to the queue. * * Wrapper for scheduler::FifoQueueBase::tryPush(T&&) * * \param [in] value is a rvalue reference to object that will be pushed, value in queue's storage is * move-constructed * * \return zero if element was pushed successfully, error code otherwise: * - error codes returned by Semaphore::tryWait(); * - error codes returned by Semaphore::post(); */ int tryPush(T&& value) { return FifoQueueBase::tryPush(std::move(value)); } /** * \brief Tries to push the element to the queue for a given duration of time. * * Wrapper for scheduler::FifoQueueBase::tryPushFor(TickClock::duration, const T&) * * \param [in] duration is the duration after which the wait will be terminated without pushing the element * \param [in] value is a reference to object that will be pushed, value in queue's storage is copy-constructed * * \return zero if element was pushed successfully, error code otherwise: * - error codes returned by Semaphore::tryWaitFor(); * - error codes returned by Semaphore::post(); */ int tryPushFor(const TickClock::duration duration, const T& value) { return FifoQueueBase::tryPushFor(duration, value); } /** * \brief Tries to push the element to the queue for a given duration of time. * * Wrapper for scheduler::FifoQueueBase::tryPushFor(TickClock::duration, T&&) * * \param [in] duration is the duration after which the call will be terminated without pushing the element * \param [in] value is a rvalue reference to object that will be pushed, value in queue's storage is * move-constructed * * \return zero if element was pushed successfully, error code otherwise: * - error codes returned by Semaphore::tryWaitFor(); * - error codes returned by Semaphore::post(); */ int tryPushFor(const TickClock::duration duration, T&& value) { return FifoQueueBase::tryPushFor(duration, std::move(value)); } /** * \brief Tries to push the element to the queue until a given time point. * * Wrapper for scheduler::FifoQueueBase::tryPushUntil(TickClock::time_point, const T&) * * \param [in] timePoint is the time point at which the call will be terminated without pushing the element * \param [in] value is a reference to object that will be pushed, value in queue's storage is copy-constructed * * \return zero if element was pushed successfully, error code otherwise: * - error codes returned by Semaphore::tryWaitUntil(); * - error codes returned by Semaphore::post(); */ int tryPushUntil(const TickClock::time_point timePoint, const T& value) { return FifoQueueBase::tryPushUntil(timePoint, value); } /** * \brief Tries to push the element to the queue until a given time point. * * Wrapper for scheduler::FifoQueueBase::tryPushUntil(TickClock::time_point, T&&) * * \param [in] timePoint is the time point at which the call will be terminated without pushing the element * \param [in] value is a rvalue reference to object that will be pushed, value in queue's storage is * move-constructed * * \return zero if element was pushed successfully, error code otherwise: * - error codes returned by Semaphore::tryWaitUntil(); * - error codes returned by Semaphore::post(); */ int tryPushUntil(const TickClock::time_point timePoint, T&& value) { return FifoQueueBase::tryPushUntil(timePoint, std::move(value)); } }; } // namespace distortos #endif // INCLUDE_DISTORTOS_FIFOQUEUE_HPP_
/** * \file * \brief FifoQueue class header * * \author Copyright (C) 2014 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info * * \par License * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not * distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. * * \date 2014-12-11 */ #ifndef INCLUDE_DISTORTOS_FIFOQUEUE_HPP_ #define INCLUDE_DISTORTOS_FIFOQUEUE_HPP_ #include "distortos/scheduler/FifoQueueBase.hpp" namespace distortos { /** * \brief FifoQueue class is a simple FIFO queue for thread-thread, thread-interrupt or interrupt-interrupt * communication. It supports multiple readers and multiple writers. It is implemented as a thin wrapper for * scheduler::FifoQueueBase. * * \param T is the type of data in queue */ template<typename T> class FifoQueue { public: /// type of uninitialized storage for data using Storage = scheduler::FifoQueueBase::Storage<T>; /** * \brief FifoQueue's constructor * * \param [in] storage is an array of Storage elements * \param [in] maxElements is the number of elements in storage array */ FifoQueue(Storage* const storage, const size_t maxElements) : fifoQueueBase_{storage, maxElements, scheduler::FifoQueueBase::TypeTag<T>{}} { } /** * \brief Pops the oldest (first) element from the queue. * * Wrapper for scheduler::FifoQueueBase::pop(T&) * * \param [out] value is a reference to object that will be used to return popped value, its contents are swapped * with the value in the queue's storage and destructed when no longer needed * * \return zero if element was popped successfully, error code otherwise: * - error codes returned by Semaphore::wait(); * - error codes returned by Semaphore::post(); */ int pop(T& value) { return fifoQueueBase_.pop(value); } /** * \brief Pushes the element to the queue. * * Wrapper for scheduler::FifoQueueBase::push(const T&) * * \param [in] value is a reference to object that will be pushed, value in queue's storage is copy-constructed * * \return zero if element was pushed successfully, error code otherwise: * - error codes returned by Semaphore::wait(); * - error codes returned by Semaphore::post(); */ int push(const T& value) { return fifoQueueBase_.push(value); } /** * \brief Pushes the element to the queue. * * Wrapper for scheduler::FifoQueueBase::push(T&&) * * \param [in] value is a rvalue reference to object that will be pushed, value in queue's storage is * move-constructed * * \return zero if element was pushed successfully, error code otherwise: * - error codes returned by Semaphore::wait(); * - error codes returned by Semaphore::post(); */ int push(T&& value) { return fifoQueueBase_.push(std::move(value)); } /** * \brief Tries to pop the oldest (first) element from the queue. * * Wrapper for scheduler::FifoQueueBase::tryPop(T&) * * \param [out] value is a reference to object that will be used to return popped value, its contents are swapped * with the value in the queue's storage and destructed when no longer needed * * \return zero if element was popped successfully, error code otherwise: * - error codes returned by Semaphore::tryWait(); * - error codes returned by Semaphore::post(); */ int tryPop(T& value) { return fifoQueueBase_.tryPop(value); } /** * \brief Tries to pop the oldest (first) element from the queue for a given duration of time. * * Wrapper for scheduler::FifoQueueBase::tryPopFor(TickClock::duration, T&) * * \param [in] duration is the duration after which the call will be terminated without popping the element * \param [out] value is a reference to object that will be used to return popped value, its contents are swapped * with the value in the queue's storage and destructed when no longer needed * * \return zero if element was popped successfully, error code otherwise: * - error codes returned by Semaphore::tryWaitFor(); * - error codes returned by Semaphore::post(); */ int tryPopFor(const TickClock::duration duration, T& value) { return fifoQueueBase_.tryPopFor(duration, value); } /** * \brief Tries to pop the oldest (first) element from the queue until a given time point. * * Wrapper for scheduler::FifoQueueBase::tryPopUntil(TickClock::time_point, T&) * * \param [in] timePoint is the time point at which the call will be terminated without popping the element * \param [out] value is a reference to object that will be used to return popped value, its contents are swapped * with the value in the queue's storage and destructed when no longer needed * * \return zero if element was popped successfully, error code otherwise: * - error codes returned by Semaphore::tryWaitUntil(); * - error codes returned by Semaphore::post(); */ int tryPopUntil(const TickClock::time_point timePoint, T& value) { return fifoQueueBase_.tryPopUntil(timePoint, value); } /** * \brief Tries to push the element to the queue. * * Wrapper for scheduler::FifoQueueBase::tryPush(const T&) * * \param [in] value is a reference to object that will be pushed, value in queue's storage is copy-constructed * * \return zero if element was pushed successfully, error code otherwise: * - error codes returned by Semaphore::tryWait(); * - error codes returned by Semaphore::post(); */ int tryPush(const T& value) { return fifoQueueBase_.tryPush(value); } /** * \brief Tries to push the element to the queue. * * Wrapper for scheduler::FifoQueueBase::tryPush(T&&) * * \param [in] value is a rvalue reference to object that will be pushed, value in queue's storage is * move-constructed * * \return zero if element was pushed successfully, error code otherwise: * - error codes returned by Semaphore::tryWait(); * - error codes returned by Semaphore::post(); */ int tryPush(T&& value) { return fifoQueueBase_.tryPush(std::move(value)); } /** * \brief Tries to push the element to the queue for a given duration of time. * * Wrapper for scheduler::FifoQueueBase::tryPushFor(TickClock::duration, const T&) * * \param [in] duration is the duration after which the wait will be terminated without pushing the element * \param [in] value is a reference to object that will be pushed, value in queue's storage is copy-constructed * * \return zero if element was pushed successfully, error code otherwise: * - error codes returned by Semaphore::tryWaitFor(); * - error codes returned by Semaphore::post(); */ int tryPushFor(const TickClock::duration duration, const T& value) { return fifoQueueBase_.tryPushFor(duration, value); } /** * \brief Tries to push the element to the queue for a given duration of time. * * Wrapper for scheduler::FifoQueueBase::tryPushFor(TickClock::duration, T&&) * * \param [in] duration is the duration after which the call will be terminated without pushing the element * \param [in] value is a rvalue reference to object that will be pushed, value in queue's storage is * move-constructed * * \return zero if element was pushed successfully, error code otherwise: * - error codes returned by Semaphore::tryWaitFor(); * - error codes returned by Semaphore::post(); */ int tryPushFor(const TickClock::duration duration, T&& value) { return fifoQueueBase_.tryPushFor(duration, std::move(value)); } /** * \brief Tries to push the element to the queue until a given time point. * * Wrapper for scheduler::FifoQueueBase::tryPushUntil(TickClock::time_point, const T&) * * \param [in] timePoint is the time point at which the call will be terminated without pushing the element * \param [in] value is a reference to object that will be pushed, value in queue's storage is copy-constructed * * \return zero if element was pushed successfully, error code otherwise: * - error codes returned by Semaphore::tryWaitUntil(); * - error codes returned by Semaphore::post(); */ int tryPushUntil(const TickClock::time_point timePoint, const T& value) { return fifoQueueBase_.tryPushUntil(timePoint, value); } /** * \brief Tries to push the element to the queue until a given time point. * * Wrapper for scheduler::FifoQueueBase::tryPushUntil(TickClock::time_point, T&&) * * \param [in] timePoint is the time point at which the call will be terminated without pushing the element * \param [in] value is a rvalue reference to object that will be pushed, value in queue's storage is * move-constructed * * \return zero if element was pushed successfully, error code otherwise: * - error codes returned by Semaphore::tryWaitUntil(); * - error codes returned by Semaphore::post(); */ int tryPushUntil(const TickClock::time_point timePoint, T&& value) { return fifoQueueBase_.tryPushUntil(timePoint, std::move(value)); } private: /// contained scheduler::FifoQueueBase object which implements whole functionality scheduler::FifoQueueBase fifoQueueBase_; }; } // namespace distortos #endif // INCLUDE_DISTORTOS_FIFOQUEUE_HPP_
use aggregation instead of inheritance
FifoQueue: use aggregation instead of inheritance
C++
mpl-2.0
jasmin-j/distortos,jasmin-j/distortos,DISTORTEC/distortos,CezaryGapinski/distortos,CezaryGapinski/distortos,jasmin-j/distortos,CezaryGapinski/distortos,jasmin-j/distortos,DISTORTEC/distortos,CezaryGapinski/distortos,DISTORTEC/distortos,jasmin-j/distortos,CezaryGapinski/distortos,DISTORTEC/distortos