text
stringlengths
54
60.6k
<commit_before><commit_msg>Fix formatting "Ggp command line process failed with error"<commit_after><|endoftext|>
<commit_before>/*********************************************************************** filename: CEGUIOpenGLApplePBTextureTarget.cpp created: Sun Feb 1 2009 author: Paul D Turner *************************************************************************/ /*************************************************************************** * Copyright (C) 2004 - 2009 Paul D Turner & The CEGUI Development Team * * 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 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 "GL/glew.h" #include "CEGUIOpenGLApplePBTextureTarget.h" #include "CEGUIExceptions.h" #include "CEGUIRenderQueue.h" #include "CEGUIGeometryBuffer.h" #include "CEGUIOpenGLRenderer.h" #include "CEGUIOpenGLTexture.h" // Start of CEGUI namespace section namespace CEGUI { //----------------------------------------------------------------------------// const float OpenGLApplePBTextureTarget::DEFAULT_SIZE = 128.0f; //----------------------------------------------------------------------------// static CGLPixelFormatAttribute fmtAttrs[] = { kCGLPFAAccelerated, kCGLPFAPBuffer, kCGLPFAColorSize, static_cast<CGLPixelFormatAttribute>(24), kCGLPFAAlphaSize, static_cast<CGLPixelFormatAttribute>(8), static_cast<CGLPixelFormatAttribute>(0) }; //----------------------------------------------------------------------------// OpenGLApplePBTextureTarget::OpenGLApplePBTextureTarget(OpenGLRenderer& owner) : OpenGLRenderTarget(owner), d_pbuffer(0), d_context(0), d_texture(0) { if (!GLEW_APPLE_pixel_buffer) throw RendererException("GL_APPLE_pixel_buffer extension is needed to " "use OpenGLApplePBTextureTarget!"); initialiseTexture(); // create CEGUI::Texture to wrap GL texture d_CEGUITexture = &static_cast<OpenGLTexture&>( d_owner.createTexture(d_texture, d_area.getSize())); CGLError err; CGLContextObj cctx = CGLGetCurrentContext(); if (err = CGLGetVirtualScreen(cctx, &d_screen)) throw RendererException("OpenGLApplePBTextureTarget - " "CGLGetVirtualScreen failed: " + String(CGLErrorString(err))); long fmt_count; CGLPixelFormatObj pix_fmt; if (err = CGLChoosePixelFormat(fmtAttrs, &pix_fmt, &fmt_count)) throw RendererException("OpenGLApplePBTextureTarget - " "CGLChoosePixelFormat failed: " + String(CGLErrorString(err))); err = CGLCreateContext(pix_fmt, cctx, &d_context); CGLDestroyPixelFormat(pix_fmt); if (err) throw RendererException("OpenGLApplePBTextureTarget - " "CGLCreateContext failed: " + String(CGLErrorString(err))); // set default size (and cause initialisation of the pbuffer) try { declareRenderSize(Size(DEFAULT_SIZE, DEFAULT_SIZE)); } catch(...) { CGLDestroyContext(d_context); throw; } // set these states one-time since we have our own context enablePBuffer(); glEnable(GL_SCISSOR_TEST); glEnable(GL_TEXTURE_2D); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glDepthFunc(GL_ALWAYS); disablePBuffer(); } //----------------------------------------------------------------------------// OpenGLApplePBTextureTarget::~OpenGLApplePBTextureTarget() { if (d_context) CGLDestroyContext(d_context); if (d_pbuffer) CGLDestroyPBuffer(d_pbuffer); d_owner.destroyTexture(*d_CEGUITexture); } //----------------------------------------------------------------------------// void OpenGLApplePBTextureTarget::activate() { enablePBuffer(); OpenGLRenderTarget::activate(); } //----------------------------------------------------------------------------// void OpenGLApplePBTextureTarget::deactivate() { glFlush(); OpenGLRenderTarget::deactivate(); disablePBuffer(); } //----------------------------------------------------------------------------// bool OpenGLApplePBTextureTarget::isImageryCache() const { return true; } //----------------------------------------------------------------------------// void OpenGLApplePBTextureTarget::clear() { enablePBuffer(); glClearColor(0,0,0,0); glClear(GL_COLOR_BUFFER_BIT); disablePBuffer(); } //----------------------------------------------------------------------------// Texture& OpenGLApplePBTextureTarget::getTexture() const { return *d_CEGUITexture; } //----------------------------------------------------------------------------// void OpenGLApplePBTextureTarget::declareRenderSize(const Size& sz) { // exit if current size is enough if ((d_area.getWidth() >= sz.d_width) && (d_area.getHeight() >= sz.d_height)) return; setArea(Rect(d_area.getPosition(), sz)); // dump any previous pbuffer if (d_pbuffer) { CGLDestroyPBuffer(d_pbuffer); d_pbuffer = 0; } CGLError err; if (err = CGLCreatePBuffer(d_area.getWidth(), d_area.getHeight(), GL_TEXTURE_2D, GL_RGBA, 0, &d_pbuffer)) { throw RendererException("OpenGLApplePBTextureTarget::declareRenderSize " "- CGLCreatePBuffer failed: " + String(CGLErrorString(err))); } if (err = CGLSetPBuffer(d_context, d_pbuffer, 0, 0, d_screen)) throw RendererException("OpenGLApplePBTextureTarget::declareRenderSize " "- CGLSetPBuffer failed: " + String(CGLErrorString(err))); // make d_texture use the pbuffer as it's data source enablePBuffer(); glBindTexture(GL_TEXTURE_2D, d_texture); err = CGLTexImagePBuffer(d_context, d_pbuffer, GL_FRONT); disablePBuffer(); if (err) throw RendererException("OpenGLApplePBTextureTarget::declareRenderSize " "- CGLTexImagePBuffer failed: " + String(CGLErrorString(err))); // ensure CEGUI::Texture is wrapping real GL texture and has correct size d_CEGUITexture->setOpenGLTexture(d_texture, d_area.getSize()); } //----------------------------------------------------------------------------// void OpenGLApplePBTextureTarget::initialiseTexture() { // create and setup texture which pbuffer content will be loaded to glGenTextures(1, &d_texture); glBindTexture(GL_TEXTURE_2D, d_texture); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); } //----------------------------------------------------------------------------// void OpenGLApplePBTextureTarget::enablePBuffer() const { if (CGLGetCurrentContext() != d_context) { d_prevContext = CGLGetCurrentContext(); CGLSetCurrentContext(d_context); } } //----------------------------------------------------------------------------// void OpenGLApplePBTextureTarget::disablePBuffer() const { if (CGLGetCurrentContext() == d_context) CGLSetCurrentContext(d_prevContext); } //----------------------------------------------------------------------------// bool OpenGLApplePBTextureTarget::isRenderingInverted() const { return true; } //----------------------------------------------------------------------------// } // End of CEGUI namespace section <commit_msg>Fix texture target using Apple's pixel buffer support.<commit_after>/*********************************************************************** filename: CEGUIOpenGLApplePBTextureTarget.cpp created: Sun Feb 1 2009 author: Paul D Turner *************************************************************************/ /*************************************************************************** * Copyright (C) 2004 - 2009 Paul D Turner & The CEGUI Development Team * * 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 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 "GL/glew.h" #include "CEGUIOpenGLApplePBTextureTarget.h" #include "CEGUIExceptions.h" #include "CEGUIRenderQueue.h" #include "CEGUIGeometryBuffer.h" #include "CEGUIOpenGLRenderer.h" #include "CEGUIOpenGLTexture.h" // Start of CEGUI namespace section namespace CEGUI { //----------------------------------------------------------------------------// const float OpenGLApplePBTextureTarget::DEFAULT_SIZE = 128.0f; //----------------------------------------------------------------------------// static CGLPixelFormatAttribute fmtAttrs[] = { kCGLPFAAccelerated, kCGLPFAPBuffer, kCGLPFAColorSize, static_cast<CGLPixelFormatAttribute>(24), kCGLPFAAlphaSize, static_cast<CGLPixelFormatAttribute>(8), static_cast<CGLPixelFormatAttribute>(0) }; //----------------------------------------------------------------------------// OpenGLApplePBTextureTarget::OpenGLApplePBTextureTarget(OpenGLRenderer& owner) : OpenGLRenderTarget(owner), d_pbuffer(0), d_context(0), d_texture(0) { if (!GLEW_APPLE_pixel_buffer) throw RendererException("GL_APPLE_pixel_buffer extension is needed to " "use OpenGLApplePBTextureTarget!"); initialiseTexture(); // create CEGUI::Texture to wrap GL texture d_CEGUITexture = &static_cast<OpenGLTexture&>( d_owner.createTexture(d_texture, d_area.getSize())); CGLError err; CGLContextObj cctx = CGLGetCurrentContext(); if (err = CGLGetVirtualScreen(cctx, &d_screen)) throw RendererException("OpenGLApplePBTextureTarget - " "CGLGetVirtualScreen failed: " + String(CGLErrorString(err))); long fmt_count; CGLPixelFormatObj pix_fmt; if (err = CGLChoosePixelFormat(fmtAttrs, &pix_fmt, &fmt_count)) throw RendererException("OpenGLApplePBTextureTarget - " "CGLChoosePixelFormat failed: " + String(CGLErrorString(err))); err = CGLCreateContext(pix_fmt, cctx, &d_context); CGLDestroyPixelFormat(pix_fmt); if (err) throw RendererException("OpenGLApplePBTextureTarget - " "CGLCreateContext failed: " + String(CGLErrorString(err))); // set default size (and cause initialisation of the pbuffer) try { declareRenderSize(Size(DEFAULT_SIZE, DEFAULT_SIZE)); } catch(...) { CGLDestroyContext(d_context); throw; } // set these states one-time since we have our own context enablePBuffer(); glEnable(GL_SCISSOR_TEST); glEnable(GL_TEXTURE_2D); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glEnableClientState(GL_VERTEX_ARRAY); glEnableClientState(GL_COLOR_ARRAY); glEnableClientState(GL_TEXTURE_COORD_ARRAY); glDisableClientState(GL_SECONDARY_COLOR_ARRAY); glDisableClientState(GL_INDEX_ARRAY); glDisableClientState(GL_NORMAL_ARRAY); glDisableClientState(GL_FOG_COORDINATE_ARRAY); glDisableClientState(GL_EDGE_FLAG_ARRAY); glClearColor(0,0,0,0); disablePBuffer(); } //----------------------------------------------------------------------------// OpenGLApplePBTextureTarget::~OpenGLApplePBTextureTarget() { if (d_context) CGLDestroyContext(d_context); if (d_pbuffer) CGLDestroyPBuffer(d_pbuffer); d_owner.destroyTexture(*d_CEGUITexture); } //----------------------------------------------------------------------------// void OpenGLApplePBTextureTarget::activate() { enablePBuffer(); OpenGLRenderTarget::activate(); } //----------------------------------------------------------------------------// void OpenGLApplePBTextureTarget::deactivate() { glFlush(); OpenGLRenderTarget::deactivate(); disablePBuffer(); } //----------------------------------------------------------------------------// bool OpenGLApplePBTextureTarget::isImageryCache() const { return true; } //----------------------------------------------------------------------------// void OpenGLApplePBTextureTarget::clear() { enablePBuffer(); glDisable(GL_SCISSOR_TEST); glClear(GL_COLOR_BUFFER_BIT); glEnable(GL_SCISSOR_TEST); disablePBuffer(); } //----------------------------------------------------------------------------// Texture& OpenGLApplePBTextureTarget::getTexture() const { return *d_CEGUITexture; } //----------------------------------------------------------------------------// void OpenGLApplePBTextureTarget::declareRenderSize(const Size& sz) { // exit if current size is enough if ((d_area.getWidth() >= sz.d_width) && (d_area.getHeight() >= sz.d_height)) return; setArea(Rect(d_area.getPosition(), sz)); // dump any previous pbuffer if (d_pbuffer) { CGLDestroyPBuffer(d_pbuffer); d_pbuffer = 0; } CGLError err; if (err = CGLCreatePBuffer(d_area.getWidth(), d_area.getHeight(), GL_TEXTURE_2D, GL_RGBA, 0, &d_pbuffer)) { throw RendererException("OpenGLApplePBTextureTarget::declareRenderSize " "- CGLCreatePBuffer failed: " + String(CGLErrorString(err))); } if (err = CGLSetPBuffer(d_context, d_pbuffer, 0, 0, d_screen)) throw RendererException("OpenGLApplePBTextureTarget::declareRenderSize " "- CGLSetPBuffer failed: " + String(CGLErrorString(err))); clear(); // make d_texture use the pbuffer as it's data source glBindTexture(GL_TEXTURE_2D, d_texture); err = CGLTexImagePBuffer(CGLGetCurrentContext(), d_pbuffer, GL_FRONT); if (err) throw RendererException("OpenGLApplePBTextureTarget::declareRenderSize " "- CGLTexImagePBuffer failed: " + String(CGLErrorString(err))); // ensure CEGUI::Texture is wrapping real GL texture and has correct size d_CEGUITexture->setOpenGLTexture(d_texture, d_area.getSize()); } //----------------------------------------------------------------------------// void OpenGLApplePBTextureTarget::initialiseTexture() { // create and setup texture which pbuffer content will be loaded to glGenTextures(1, &d_texture); glBindTexture(GL_TEXTURE_2D, d_texture); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); } //----------------------------------------------------------------------------// void OpenGLApplePBTextureTarget::enablePBuffer() const { if (CGLGetCurrentContext() != d_context) { d_prevContext = CGLGetCurrentContext(); CGLSetCurrentContext(d_context); } } //----------------------------------------------------------------------------// void OpenGLApplePBTextureTarget::disablePBuffer() const { if (CGLGetCurrentContext() == d_context) CGLSetCurrentContext(d_prevContext); } //----------------------------------------------------------------------------// bool OpenGLApplePBTextureTarget::isRenderingInverted() const { return true; } //----------------------------------------------------------------------------// } // End of CEGUI namespace section <|endoftext|>
<commit_before> #define WIN32_LEAN_AND_MEAN #include <windows.h> #include <stdio.h> bool Cavern; BYTE Version; CHAR Config[MAX_PATH], LandFile[MAX_PATH]; SHORT SWidth, SHeight, GlobalEatLimit, TargetWidth, TargetHeight; SHORT ScreenX, ScreenY; DWORD OfflineCavernFloodFix; DWORD ActualWidth, HorizontalSidesBox, RenderFromLeft; DWORD LandWaterCriticalZone, CavernWaterEatLimit, ActualHeight, HUnk4, HUnk5, RenderFromTop, VerticalSidesBox; DWORD LeftOffset, CenterCursorX, CenterCursorY; DWORD AL_WUnk2, AL_HorizontalSidesBox, AL_RenderFromLeft, AL_RenderFromTop, AL_TopInfidelBox, AL_SWUnk1, AL_LeftOffset; DWORD TopOffset; DWORD GetPETimestamp(LPCTSTR lpModuleName) { DWORD ImageBase = (DWORD)GetModuleHandle(lpModuleName); DWORD PEOffset = *(DWORD*)(ImageBase + 0x3C); return *(DWORD*)(ImageBase + PEOffset + 0x08); } BYTE CheckVersion() { DWORD PETime = GetPETimestamp(0); if (PETime >= 0x352118A5 && PETime <= 0x352118FD) return Version = 1; return Version = 0; } BOOL WritePrivateProfileIntA(LPCSTR lpAppName, LPCSTR lpKeyName, int nInteger, LPCSTR lpFileName) { CHAR lpString[32]; sprintf_s(lpString, "%d", nInteger); return WritePrivateProfileStringA(lpAppName, lpKeyName, lpString, lpFileName); } LPSTR GetPathUnderExeA(LPSTR OutBuf, LPCSTR FileName) { GetModuleFileNameA(NULL, OutBuf, MAX_PATH); CHAR* dirend = strrchr(OutBuf, '\\') + 1; strcpy_s(dirend, MAX_PATH, FileName); return OutBuf; } BOOL Unprotect(ULONG addr, SIZE_T dwSize = sizeof(WORD)) { DWORD uselessDword; return VirtualProtect((void*)addr, dwSize, PAGE_READWRITE, &uselessDword); } BOOL CavernCheck() { FILE* land; char cavc; Cavern = false; if (fopen_s(&land, GetPathUnderExeA(LandFile, "Data\\land.dat"), "r") == ERROR_SUCCESS) { fseek(land, 0x10, SEEK_SET); cavc = fgetc(land); if (cavc) Cavern = true; fclose(land); } else MessageBoxA(NULL, "Warning: failed to open the \"Data\\land.dat\" file. " "Your game will most likely crash.", "ReSolution warning", MB_OK | MB_ICONWARNING); return Cavern; } void GetTargetScreenSize(SHORT nWidth, SHORT nHeight) { if (Cavern) { TargetWidth = nWidth > 1920 ? 1920 : nWidth; TargetHeight = nHeight > 856 ? 856 : nHeight; } else { TargetWidth = nWidth > 6012 ? 6012 : nWidth; TargetHeight = nHeight > 2902 ? 2902 : nHeight; } } void GetAddresses() { //credits for these go to S*natch and des; labels described by StepS LandWaterCriticalZone = 0x000279E9 + 0x400C00; CavernWaterEatLimit = 0x000279F6 + 0x400C00; ActualHeight = 0x0003328A + 0x400C00; ActualWidth = 0x00033292 + 0x400C00; TopOffset = 0x00045B38 + 0x400C00; HorizontalSidesBox = 0x00045B40 + 0x400C00; LeftOffset = 0x00045B4D + 0x400C00; VerticalSidesBox = 0x00045B55 + 0x400C00; RenderFromTop = 0x00045B73 + 0x400C00; RenderFromLeft = 0x00045B78 + 0x400C00; AL_SWUnk1 = 0x00045A9C + 0x400C00; AL_WUnk2 = 0x00045AB3 + 0x400C00; AL_HorizontalSidesBox = 0x00045AD7 + 0x400C00; AL_TopInfidelBox = 0x00045ADC + 0x400C00; AL_LeftOffset = 0x00045B07 + 0x400C00; AL_RenderFromTop = 0x00045B18 + 0x400C00; AL_RenderFromLeft = 0x00045B1D + 0x400C00; // HUnk4 = 0x000363F6 + 0x400C00; // HUnk5 = 0x0004000C + 0x400C00; //new things discovered by StepS CenterCursorX = 0x00077878 + 0x401C00; CenterCursorY = 0x0007787C + 0x401C00; } void UnprotectAddresses() { Unprotect(ActualWidth); Unprotect(CavernWaterEatLimit); Unprotect(TopOffset); } void PatchMem(SHORT nWidth, SHORT nHeight) { GetTargetScreenSize(nWidth, nHeight); *(WORD*)LandWaterCriticalZone = GlobalEatLimit; *(WORD*)CavernWaterEatLimit = GlobalEatLimit; *(WORD*)ActualWidth = SWidth; *(WORD*)ActualHeight = SHeight; *(WORD*)RenderFromLeft = TargetWidth; *(WORD*)RenderFromTop = TargetHeight; *(WORD*)HorizontalSidesBox = TargetWidth; *(WORD*)VerticalSidesBox = TargetHeight; *(WORD*)LeftOffset = TargetWidth / 2; *(WORD*)TopOffset = TargetHeight / 2; *(WORD*)CenterCursorX = SWidth / 2 > ScreenX / 2 ? ScreenX / 2 : SWidth / 2; *(WORD*)CenterCursorY = SHeight / 2 > ScreenY / 2 ? ScreenY / 2 : SHeight / 2; *(WORD*)AL_WUnk2 = SWidth; *(WORD*)AL_HorizontalSidesBox = TargetWidth; *(WORD*)AL_RenderFromLeft = TargetWidth; *(WORD*)AL_TopInfidelBox = TargetHeight; *(WORD*)AL_RenderFromTop = SHeight; *(WORD*)AL_SWUnk1 = TargetWidth / 2; *(WORD*)AL_LeftOffset = TargetWidth / 2; // *(WORD*)HUnk4 = SHeight; // *(WORD*)HUnk5 = SHeight; // unknown, readonly values } void LoadConfig() { GetPathUnderExeA(Config, "W2.ini"); SWidth = GetPrivateProfileIntA("Resolution", "ScreenWidth", -1, Config); SHeight = GetPrivateProfileIntA("Resolution", "ScreenHeight", -1, Config); OfflineCavernFloodFix = GetPrivateProfileIntA("Resolution", "OfflineCavernFloodFix", -1, Config); ScreenX = (SHORT)GetSystemMetrics(SM_CXSCREEN); ScreenY = (SHORT)GetSystemMetrics(SM_CYSCREEN); if (OfflineCavernFloodFix < 0) { OfflineCavernFloodFix = 1; WritePrivateProfileIntA("Resolution", "OfflineCavernFloodFix", 1, Config); } if (SWidth <= 0 || SHeight <= 0) { SWidth = ScreenX; SHeight = ScreenY; WritePrivateProfileIntA("Resolution", "ScreenWidth", SWidth, Config); WritePrivateProfileIntA("Resolution", "ScreenHeight", SHeight, Config); } if (OfflineCavernFloodFix) GlobalEatLimit = 854; else GlobalEatLimit = 480; } BOOL APIENTRY DllMain(HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReserved) { if (ul_reason_for_call == DLL_PROCESS_ATTACH) { if (!CheckVersion()) { MessageBoxA(NULL, "Sorry, but your Worms2.exe version has to be 1.05 for wkReSolution to work. " "Please patch your game to 1.05 and try again.", "ReSolution error", MB_OK | MB_ICONERROR); return 1; } LoadConfig(); CavernCheck(); GetAddresses(); UnprotectAddresses(); PatchMem(SWidth, SHeight); } return 1; } <commit_msg>Experimental live window resize<commit_after> #define WIN32_LEAN_AND_MEAN #include <windows.h> #include <stdio.h> bool Cavern; BYTE Version; CHAR Config[MAX_PATH], LandFile[MAX_PATH]; HHOOK wHook; SHORT SWidth, SHeight, GlobalEatLimit, TargetWidth, TargetHeight; SHORT ScreenX, ScreenY; DWORD OfflineCavernFloodFix; DWORD ActualWidth, HorizontalSidesBox, RenderFromLeft; DWORD LandWaterCriticalZone, CavernWaterEatLimit, ActualHeight, HUnk4, HUnk5, RenderFromTop, VerticalSidesBox; DWORD LeftOffset, CenterCursorX, CenterCursorY; DWORD AL_WUnk2, AL_HorizontalSidesBox, AL_RenderFromLeft, AL_RenderFromTop, AL_TopInfidelBox, AL_SWUnk1, AL_LeftOffset; DWORD TopOffset; LRESULT __declspec(dllexport)__stdcall CALLBACK CallWndProc(int nCode, WPARAM wParam, LPARAM lParam) { if (nCode == HC_ACTION) { CWPSTRUCT* pwp = (CWPSTRUCT*)lParam; if (pwp->message == WM_EXITSIZEMOVE) { if (HWND W2Wnd = FindWindow("Worms2", NULL)) { if (pwp->hwnd == W2Wnd) { RECT W2rect; GetClientRect(W2Wnd, &W2rect); ClientToScreen(W2Wnd, (POINT*)&W2rect); SHORT width = (SHORT)(W2rect.right - W2rect.left); SHORT height = (SHORT)(W2rect.bottom - W2rect.top); PatchMem(width, height); } } } } return CallNextHookEx(wHook, nCode, wParam, lParam); } DWORD GetPETimestamp(LPCTSTR lpModuleName) { DWORD ImageBase = (DWORD)GetModuleHandle(lpModuleName); DWORD PEOffset = *(DWORD*)(ImageBase + 0x3C); return *(DWORD*)(ImageBase + PEOffset + 0x08); } BYTE CheckVersion() { DWORD PETime = GetPETimestamp(0); if (PETime >= 0x352118A5 && PETime <= 0x352118FD) return Version = 1; return Version = 0; } BOOL WritePrivateProfileIntA(LPCSTR lpAppName, LPCSTR lpKeyName, int nInteger, LPCSTR lpFileName) { CHAR lpString[32]; sprintf_s(lpString, "%d", nInteger); return WritePrivateProfileStringA(lpAppName, lpKeyName, lpString, lpFileName); } LPSTR GetPathUnderExeA(LPSTR OutBuf, LPCSTR FileName) { GetModuleFileNameA(NULL, OutBuf, MAX_PATH); CHAR* dirend = strrchr(OutBuf, '\\') + 1; strcpy_s(dirend, MAX_PATH, FileName); return OutBuf; } BOOL Unprotect(ULONG addr, SIZE_T dwSize = sizeof(WORD)) { DWORD uselessDword; return VirtualProtect((void*)addr, dwSize, PAGE_READWRITE, &uselessDword); } BOOL CavernCheck() { FILE* land; char cavc; Cavern = false; if (fopen_s(&land, GetPathUnderExeA(LandFile, "Data\\land.dat"), "r") == ERROR_SUCCESS) { fseek(land, 0x10, SEEK_SET); cavc = fgetc(land); if (cavc) Cavern = true; fclose(land); } else MessageBoxA(NULL, "Warning: failed to open the \"Data\\land.dat\" file. " "Your game will most likely crash.", "ReSolution warning", MB_OK | MB_ICONWARNING); return Cavern; } void GetTargetScreenSize(SHORT nWidth, SHORT nHeight) { if (Cavern) { TargetWidth = nWidth > 1920 ? 1920 : nWidth; TargetHeight = nHeight > 856 ? 856 : nHeight; } else { TargetWidth = nWidth > 6012 ? 6012 : nWidth; TargetHeight = nHeight > 2902 ? 2902 : nHeight; } } void GetAddresses() { //credits for these go to S*natch and des; labels described by StepS LandWaterCriticalZone = 0x000279E9 + 0x400C00; CavernWaterEatLimit = 0x000279F6 + 0x400C00; ActualHeight = 0x0003328A + 0x400C00; ActualWidth = 0x00033292 + 0x400C00; TopOffset = 0x00045B38 + 0x400C00; HorizontalSidesBox = 0x00045B40 + 0x400C00; LeftOffset = 0x00045B4D + 0x400C00; VerticalSidesBox = 0x00045B55 + 0x400C00; RenderFromTop = 0x00045B73 + 0x400C00; RenderFromLeft = 0x00045B78 + 0x400C00; AL_SWUnk1 = 0x00045A9C + 0x400C00; AL_WUnk2 = 0x00045AB3 + 0x400C00; AL_HorizontalSidesBox = 0x00045AD7 + 0x400C00; AL_TopInfidelBox = 0x00045ADC + 0x400C00; AL_LeftOffset = 0x00045B07 + 0x400C00; AL_RenderFromTop = 0x00045B18 + 0x400C00; AL_RenderFromLeft = 0x00045B1D + 0x400C00; // HUnk4 = 0x000363F6 + 0x400C00; // HUnk5 = 0x0004000C + 0x400C00; //new things discovered by StepS CenterCursorX = 0x00077878 + 0x401C00; CenterCursorY = 0x0007787C + 0x401C00; } void UnprotectAddresses() { Unprotect(ActualWidth); Unprotect(CavernWaterEatLimit); Unprotect(TopOffset); } void PatchMem(SHORT nWidth, SHORT nHeight) { GetTargetScreenSize(nWidth, nHeight); *(WORD*)LandWaterCriticalZone = GlobalEatLimit; *(WORD*)CavernWaterEatLimit = GlobalEatLimit; *(WORD*)ActualWidth = SWidth; *(WORD*)ActualHeight = SHeight; *(WORD*)RenderFromLeft = TargetWidth; *(WORD*)RenderFromTop = TargetHeight; *(WORD*)HorizontalSidesBox = TargetWidth; *(WORD*)VerticalSidesBox = TargetHeight; *(WORD*)LeftOffset = TargetWidth / 2; *(WORD*)TopOffset = TargetHeight / 2; *(WORD*)CenterCursorX = SWidth / 2 > ScreenX / 2 ? ScreenX / 2 : SWidth / 2; *(WORD*)CenterCursorY = SHeight / 2 > ScreenY / 2 ? ScreenY / 2 : SHeight / 2; *(WORD*)AL_WUnk2 = SWidth; *(WORD*)AL_HorizontalSidesBox = TargetWidth; *(WORD*)AL_RenderFromLeft = TargetWidth; *(WORD*)AL_TopInfidelBox = TargetHeight; *(WORD*)AL_RenderFromTop = SHeight; *(WORD*)AL_SWUnk1 = TargetWidth / 2; *(WORD*)AL_LeftOffset = TargetWidth / 2; // *(WORD*)HUnk4 = SHeight; // *(WORD*)HUnk5 = SHeight; // unknown, readonly values } void LoadConfig() { GetPathUnderExeA(Config, "W2.ini"); SWidth = GetPrivateProfileIntA("Resolution", "ScreenWidth", -1, Config); SHeight = GetPrivateProfileIntA("Resolution", "ScreenHeight", -1, Config); OfflineCavernFloodFix = GetPrivateProfileIntA("Resolution", "OfflineCavernFloodFix", -1, Config); ScreenX = (SHORT)GetSystemMetrics(SM_CXSCREEN); ScreenY = (SHORT)GetSystemMetrics(SM_CYSCREEN); if (OfflineCavernFloodFix < 0) { OfflineCavernFloodFix = 1; WritePrivateProfileIntA("Resolution", "OfflineCavernFloodFix", 1, Config); } if (SWidth <= 0 || SHeight <= 0) { SWidth = ScreenX; SHeight = ScreenY; WritePrivateProfileIntA("Resolution", "ScreenWidth", SWidth, Config); WritePrivateProfileIntA("Resolution", "ScreenHeight", SHeight, Config); } if (OfflineCavernFloodFix) GlobalEatLimit = 854; else GlobalEatLimit = 480; } BOOL APIENTRY DllMain(HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReserved) { if (ul_reason_for_call == DLL_PROCESS_ATTACH) { if (!CheckVersion()) { MessageBoxA(NULL, "Sorry, but your Worms2.exe version has to be 1.05 for wkReSolution to work. " "Please patch your game to 1.05 and try again.", "ReSolution error", MB_OK | MB_ICONERROR); return 1; } LoadConfig(); CavernCheck(); GetAddresses(); UnprotectAddresses(); PatchMem(SWidth, SHeight); wHook = SetWindowsHookEx(WH_CALLWNDPROC, (HOOKPROC)CallWndProc, hModule, GetCurrentThreadId()); } else if (ul_reason_for_call == DLL_PROCESS_DETACH) { UnhookWindowsHookEx(wHook); } return 1; } <|endoftext|>
<commit_before>/*========================================================================= Program: Visualization Toolkit Module: vtkPipelineGraphSource.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 "vtkAbstractArray.h" #include "vtkAlgorithmOutput.h" #include "vtkAnnotationLink.h" #include "vtkArrayData.h" #include "vtkCollection.h" #include "vtkDataRepresentation.h" #include "vtkDataSetAttributes.h" #include "vtkEdgeListIterator.h" #include "vtkGraph.h" #include "vtkGraph.h" #include "vtkInformation.h" #include "vtkMutableDirectedGraph.h" #include "vtkObjectFactory.h" #include "vtkPipelineGraphSource.h" #include "vtkSmartPointer.h" #include "vtkStringArray.h" #include "vtkTable.h" #include "vtkTree.h" #include "vtkVariantArray.h" #include "vtkView.h" #include <vtksys/stl/map> #include <vtksys/stl/stack> #include <vtksys/ios/sstream> using vtksys_stl::map; using vtksys_stl::stack; using vtksys_ios::ostringstream; #define VTK_CREATE(type, name) \ vtkSmartPointer<type> name = vtkSmartPointer<type>::New() vtkStandardNewMacro(vtkPipelineGraphSource); // ---------------------------------------------------------------------- vtkPipelineGraphSource::vtkPipelineGraphSource() { this->SetNumberOfInputPorts(0); this->SetNumberOfOutputPorts(1); this->Sinks = vtkCollection::New(); } // ---------------------------------------------------------------------- vtkPipelineGraphSource::~vtkPipelineGraphSource() { if (this->Sinks) { this->Sinks->Delete(); this->Sinks = NULL; } } // ---------------------------------------------------------------------- void vtkPipelineGraphSource::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os, indent); } // ---------------------------------------------------------------------- void vtkPipelineGraphSource::AddSink(vtkObject* sink) { if (sink != NULL && !this->Sinks->IsItemPresent(sink)) { this->Sinks->AddItem(sink); this->Modified(); } } void vtkPipelineGraphSource::RemoveSink(vtkObject* sink) { if (sink != NULL && this->Sinks->IsItemPresent(sink)) { this->Sinks->RemoveItem(sink); this->Modified(); } } // ---------------------------------------------------------------------- static void InsertObject( vtkObject* object, map<vtkObject*, vtkIdType>& object_map, vtkMutableDirectedGraph* builder, vtkStringArray* vertex_class_name_array, vtkVariantArray* vertex_object_array, vtkStringArray* edge_output_port_array, vtkStringArray* edge_input_port_array, vtkStringArray* edge_class_name_array, vtkVariantArray* edge_object_array) { if(!object) return; if(object_map.count(object)) return; // Insert pipeline algorithms ... if(vtkAlgorithm* const algorithm = vtkAlgorithm::SafeDownCast(object)) { object_map[algorithm] = builder->AddVertex(); vertex_class_name_array->InsertNextValue(algorithm->GetClassName()); vertex_object_array->InsertNextValue(algorithm); // Recursively insert algorithm inputs ... for(int i = 0; i != algorithm->GetNumberOfInputPorts(); ++i) { for(int j = 0; j != algorithm->GetNumberOfInputConnections(i); ++j) { vtkAlgorithm* const input_algorithm = algorithm->GetInputConnection(i, j)->GetProducer(); InsertObject(input_algorithm, object_map, builder, vertex_class_name_array, vertex_object_array, edge_output_port_array, edge_input_port_array, edge_class_name_array, edge_object_array); builder->AddEdge(object_map[input_algorithm], object_map[algorithm]); vtkDataObject* input_data = input_algorithm->GetOutputDataObject(algorithm->GetInputConnection(i, j)->GetIndex()); edge_output_port_array->InsertNextValue(vtkVariant(algorithm->GetInputConnection(i, j)->GetIndex()).ToString()); edge_input_port_array->InsertNextValue(vtkVariant(i).ToString()); edge_class_name_array->InsertNextValue(input_data ? input_data->GetClassName() : ""); edge_object_array->InsertNextValue(input_data); } } // Special-case: if this is a representation, insert its annotation link ... if(vtkDataRepresentation* const data_representation = vtkDataRepresentation::SafeDownCast(algorithm)) { if(vtkAnnotationLink* const annotation_link = data_representation->GetAnnotationLink()) { InsertObject(annotation_link, object_map, builder, vertex_class_name_array, vertex_object_array, edge_output_port_array, edge_input_port_array, edge_class_name_array, edge_object_array); builder->AddEdge(object_map[annotation_link], object_map[algorithm]); edge_output_port_array->InsertNextValue(""); edge_input_port_array->InsertNextValue(""); edge_class_name_array->InsertNextValue("vtkAnnotationLayers"); edge_object_array->InsertNextValue(annotation_link->GetOutput()); } } } // Insert pipeline views ... else if(vtkView* const view = vtkView::SafeDownCast(object)) { object_map[view] = builder->AddVertex(); vertex_class_name_array->InsertNextValue(view->GetClassName()); vertex_object_array->InsertNextValue(view); // Recursively insert view inputs ... for(int i = 0; i != view->GetNumberOfRepresentations(); ++i) { vtkDataRepresentation* const input_representation = view->GetRepresentation(i); InsertObject(input_representation, object_map, builder, vertex_class_name_array, vertex_object_array, edge_output_port_array, edge_input_port_array, edge_class_name_array, edge_object_array); builder->AddEdge(object_map[input_representation], object_map[view]); edge_output_port_array->InsertNextValue(""); edge_input_port_array->InsertNextValue(vtkVariant(i).ToString()); edge_class_name_array->InsertNextValue(""); edge_object_array->InsertNextValue(0); } } } int vtkPipelineGraphSource::RequestData( vtkInformation*, vtkInformationVector**, vtkInformationVector* outputVector) { // Setup the graph data structure ... VTK_CREATE(vtkMutableDirectedGraph, builder); vtkStringArray* vertex_class_name_array = vtkStringArray::New(); vertex_class_name_array->SetName("class_name"); builder->GetVertexData()->AddArray(vertex_class_name_array); vertex_class_name_array->Delete(); vtkVariantArray* vertex_object_array = vtkVariantArray::New(); vertex_object_array->SetName("object"); builder->GetVertexData()->AddArray(vertex_object_array); vertex_object_array->Delete(); vtkStringArray* edge_output_port_array = vtkStringArray::New(); edge_output_port_array->SetName("output_port"); builder->GetEdgeData()->AddArray(edge_output_port_array); edge_output_port_array->Delete(); vtkStringArray* edge_input_port_array = vtkStringArray::New(); edge_input_port_array->SetName("input_port"); builder->GetEdgeData()->AddArray(edge_input_port_array); edge_input_port_array->Delete(); vtkStringArray* edge_class_name_array = vtkStringArray::New(); edge_class_name_array->SetName("class_name"); builder->GetEdgeData()->AddArray(edge_class_name_array); edge_class_name_array->Delete(); vtkVariantArray* edge_object_array = vtkVariantArray::New(); edge_object_array->SetName("object"); builder->GetEdgeData()->AddArray(edge_object_array); edge_object_array->Delete(); // Recursively insert pipeline components into the graph ... map<vtkObject*, vtkIdType> object_map; for(vtkIdType i = 0; i != this->Sinks->GetNumberOfItems(); ++i) { InsertObject(this->Sinks->GetItemAsObject(i), object_map, builder, vertex_class_name_array, vertex_object_array, edge_output_port_array, edge_input_port_array, edge_class_name_array, edge_object_array); } // Finish creating the output graph ... vtkDirectedGraph* const output_graph = vtkDirectedGraph::GetData(outputVector); if(!output_graph->CheckedShallowCopy(builder)) { vtkErrorMacro(<<"Invalid graph structure"); return 0; } return 1; } void vtkPipelineGraphSource::PipelineToDot(vtkAlgorithm* sink, ostream& output, const vtkStdString& graph_name) { vtkSmartPointer<vtkCollection> sinks = vtkSmartPointer<vtkCollection>::New(); sinks->AddItem(sink); PipelineToDot(sinks, output, graph_name); } namespace { void replace_all(std::string& str, std::string oldStr, std::string newStr) { size_t pos = 0; while((pos = str.find(oldStr, pos)) != std::string::npos) { str.replace(pos, oldStr.length(), newStr); pos += newStr.length(); } } } void vtkPipelineGraphSource::PipelineToDot(vtkCollection* sinks, ostream& output, const vtkStdString& graph_name) { // Create a graph representation of the pipeline ... vtkSmartPointer<vtkPipelineGraphSource> pipeline = vtkSmartPointer<vtkPipelineGraphSource>::New(); for(vtkIdType i = 0; i != sinks->GetNumberOfItems(); ++i) { pipeline->AddSink(sinks->GetItemAsObject(i)); } pipeline->Update(); vtkGraph* const pipeline_graph = pipeline->GetOutput(); vtkAbstractArray* const vertex_object_array = pipeline_graph->GetVertexData()->GetAbstractArray("object"); vtkAbstractArray* const edge_output_port_array = pipeline_graph->GetEdgeData()->GetAbstractArray("output_port"); vtkAbstractArray* const edge_input_port_array = pipeline_graph->GetEdgeData()->GetAbstractArray("input_port"); vtkAbstractArray* const edge_object_array = pipeline_graph->GetEdgeData()->GetAbstractArray("object"); output << "digraph \"" << graph_name << "\"\n"; output << "{\n"; // Do some standard formatting ... output << " node [ fontname=\"helvetica\" fontsize=\"10\" shape=\"record\" style=\"filled\" ]\n"; output << " edge [ fontname=\"helvetica\" fontsize=\"9\" ]\n\n"; // Write-out vertices ... for(vtkIdType i = 0; i != pipeline_graph->GetNumberOfVertices(); ++i) { vtkObjectBase* const object = vertex_object_array->GetVariantValue(i).ToVTKObject(); std::stringstream buffer; object->PrintSelf(buffer, vtkIndent()); std::string line; std::string object_state; for(std::getline(buffer, line); buffer; std::getline(buffer, line)) { replace_all(line, "\"", "'"); replace_all(line, "\r", ""); replace_all(line, "\n", ""); if(0 == line.find("Debug:")) continue; if(0 == line.find("Modified Time:")) continue; if(0 == line.find("Reference Count:")) continue; if(0 == line.find("Registered Events:")) continue; if(0 == line.find("Executive:")) continue; if(0 == line.find("ErrorCode:")) continue; if(0 == line.find("Information:")) continue; if(0 == line.find("AbortExecute:")) continue; if(0 == line.find("Progress:")) continue; if(0 == line.find("Progress Text:")) continue; if(0 == line.find(" ")) continue; object_state += line + "\\n"; } std::string fillcolor = "#ccffcc"; if(vtkView::SafeDownCast(object)) { fillcolor = "#ffffcc"; } else if(vtkAnnotationLink::SafeDownCast(object)) { fillcolor = "#ccccff"; } output << " " << "node_" << object << " [ fillcolor=\"" << fillcolor << "\" label=\"{" << object->GetClassName() << "|" << object_state << "}\" vtk_class_name=\"" << object->GetClassName() << "\" ]\n"; } // Write-out edges ... vtkSmartPointer<vtkEdgeListIterator> edges = vtkSmartPointer<vtkEdgeListIterator>::New(); edges->SetGraph(pipeline_graph); while(edges->HasNext()) { vtkEdgeType edge = edges->Next(); vtkObjectBase* const source = vertex_object_array->GetVariantValue(edge.Source).ToVTKObject(); vtkObjectBase* const target = vertex_object_array->GetVariantValue(edge.Target).ToVTKObject(); const vtkStdString output_port = edge_output_port_array->GetVariantValue(edge.Id).ToString(); const vtkStdString input_port = edge_input_port_array->GetVariantValue(edge.Id).ToString(); vtkObjectBase* const object = edge_object_array->GetVariantValue(edge.Id).ToVTKObject(); std::string color = "black"; if(vtkTree::SafeDownCast(object)) { color = "#00bb00"; } else if(vtkTable::SafeDownCast(object)) { color = "blue"; } else if(vtkArrayData* const array_data = vtkArrayData::SafeDownCast(object)) { if(array_data->GetNumberOfArrays()) { color = ""; for(vtkIdType i = 0; i != array_data->GetNumberOfArrays(); ++i) { if(i) color += ":"; if(array_data->GetArray(i)->IsDense()) color += "purple"; else color += "red"; } } } else if(vtkGraph::SafeDownCast(object)) { color = "#cc6600"; } output << " " << "node_" << source << " -> " << "node_" << target; output << " ["; output << " color=\"" << color << "\" fontcolor=\"" << color << "\""; output << " label=\"" << (object ? object->GetClassName() : "") << "\""; output << " headlabel=\"" << input_port << "\""; output << " taillabel=\"" << output_port << "\""; output << " ]\n"; } output << "}\n"; } <commit_msg>Removing dependency on vtkDataRepresentation<commit_after>/*========================================================================= Program: Visualization Toolkit Module: vtkPipelineGraphSource.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 "vtkAbstractArray.h" #include "vtkAlgorithmOutput.h" #include "vtkAnnotationLink.h" #include "vtkArrayData.h" #include "vtkCollection.h" #include "vtkDataSetAttributes.h" #include "vtkEdgeListIterator.h" #include "vtkGraph.h" #include "vtkGraph.h" #include "vtkInformation.h" #include "vtkMutableDirectedGraph.h" #include "vtkObjectFactory.h" #include "vtkPipelineGraphSource.h" #include "vtkSmartPointer.h" #include "vtkStringArray.h" #include "vtkTable.h" #include "vtkTree.h" #include "vtkVariantArray.h" #include "vtkView.h" #include <vtksys/stl/map> #include <vtksys/stl/stack> #include <vtksys/ios/sstream> using vtksys_stl::map; using vtksys_stl::stack; using vtksys_ios::ostringstream; #define VTK_CREATE(type, name) \ vtkSmartPointer<type> name = vtkSmartPointer<type>::New() vtkStandardNewMacro(vtkPipelineGraphSource); // ---------------------------------------------------------------------- vtkPipelineGraphSource::vtkPipelineGraphSource() { this->SetNumberOfInputPorts(0); this->SetNumberOfOutputPorts(1); this->Sinks = vtkCollection::New(); } // ---------------------------------------------------------------------- vtkPipelineGraphSource::~vtkPipelineGraphSource() { if (this->Sinks) { this->Sinks->Delete(); this->Sinks = NULL; } } // ---------------------------------------------------------------------- void vtkPipelineGraphSource::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os, indent); } // ---------------------------------------------------------------------- void vtkPipelineGraphSource::AddSink(vtkObject* sink) { if (sink != NULL && !this->Sinks->IsItemPresent(sink)) { this->Sinks->AddItem(sink); this->Modified(); } } void vtkPipelineGraphSource::RemoveSink(vtkObject* sink) { if (sink != NULL && this->Sinks->IsItemPresent(sink)) { this->Sinks->RemoveItem(sink); this->Modified(); } } // ---------------------------------------------------------------------- static void InsertObject( vtkObject* object, map<vtkObject*, vtkIdType>& object_map, vtkMutableDirectedGraph* builder, vtkStringArray* vertex_class_name_array, vtkVariantArray* vertex_object_array, vtkStringArray* edge_output_port_array, vtkStringArray* edge_input_port_array, vtkStringArray* edge_class_name_array, vtkVariantArray* edge_object_array) { if(!object) return; if(object_map.count(object)) return; // Insert pipeline algorithms ... if(vtkAlgorithm* const algorithm = vtkAlgorithm::SafeDownCast(object)) { object_map[algorithm] = builder->AddVertex(); vertex_class_name_array->InsertNextValue(algorithm->GetClassName()); vertex_object_array->InsertNextValue(algorithm); // Recursively insert algorithm inputs ... for(int i = 0; i != algorithm->GetNumberOfInputPorts(); ++i) { for(int j = 0; j != algorithm->GetNumberOfInputConnections(i); ++j) { vtkAlgorithm* const input_algorithm = algorithm->GetInputConnection(i, j)->GetProducer(); InsertObject(input_algorithm, object_map, builder, vertex_class_name_array, vertex_object_array, edge_output_port_array, edge_input_port_array, edge_class_name_array, edge_object_array); builder->AddEdge(object_map[input_algorithm], object_map[algorithm]); vtkDataObject* input_data = input_algorithm->GetOutputDataObject(algorithm->GetInputConnection(i, j)->GetIndex()); edge_output_port_array->InsertNextValue(vtkVariant(algorithm->GetInputConnection(i, j)->GetIndex()).ToString()); edge_input_port_array->InsertNextValue(vtkVariant(i).ToString()); edge_class_name_array->InsertNextValue(input_data ? input_data->GetClassName() : ""); edge_object_array->InsertNextValue(input_data); } } } } int vtkPipelineGraphSource::RequestData( vtkInformation*, vtkInformationVector**, vtkInformationVector* outputVector) { // Setup the graph data structure ... VTK_CREATE(vtkMutableDirectedGraph, builder); vtkStringArray* vertex_class_name_array = vtkStringArray::New(); vertex_class_name_array->SetName("class_name"); builder->GetVertexData()->AddArray(vertex_class_name_array); vertex_class_name_array->Delete(); vtkVariantArray* vertex_object_array = vtkVariantArray::New(); vertex_object_array->SetName("object"); builder->GetVertexData()->AddArray(vertex_object_array); vertex_object_array->Delete(); vtkStringArray* edge_output_port_array = vtkStringArray::New(); edge_output_port_array->SetName("output_port"); builder->GetEdgeData()->AddArray(edge_output_port_array); edge_output_port_array->Delete(); vtkStringArray* edge_input_port_array = vtkStringArray::New(); edge_input_port_array->SetName("input_port"); builder->GetEdgeData()->AddArray(edge_input_port_array); edge_input_port_array->Delete(); vtkStringArray* edge_class_name_array = vtkStringArray::New(); edge_class_name_array->SetName("class_name"); builder->GetEdgeData()->AddArray(edge_class_name_array); edge_class_name_array->Delete(); vtkVariantArray* edge_object_array = vtkVariantArray::New(); edge_object_array->SetName("object"); builder->GetEdgeData()->AddArray(edge_object_array); edge_object_array->Delete(); // Recursively insert pipeline components into the graph ... map<vtkObject*, vtkIdType> object_map; for(vtkIdType i = 0; i != this->Sinks->GetNumberOfItems(); ++i) { InsertObject(this->Sinks->GetItemAsObject(i), object_map, builder, vertex_class_name_array, vertex_object_array, edge_output_port_array, edge_input_port_array, edge_class_name_array, edge_object_array); } // Finish creating the output graph ... vtkDirectedGraph* const output_graph = vtkDirectedGraph::GetData(outputVector); if(!output_graph->CheckedShallowCopy(builder)) { vtkErrorMacro(<<"Invalid graph structure"); return 0; } return 1; } void vtkPipelineGraphSource::PipelineToDot(vtkAlgorithm* sink, ostream& output, const vtkStdString& graph_name) { vtkSmartPointer<vtkCollection> sinks = vtkSmartPointer<vtkCollection>::New(); sinks->AddItem(sink); PipelineToDot(sinks, output, graph_name); } namespace { void replace_all(std::string& str, std::string oldStr, std::string newStr) { size_t pos = 0; while((pos = str.find(oldStr, pos)) != std::string::npos) { str.replace(pos, oldStr.length(), newStr); pos += newStr.length(); } } } void vtkPipelineGraphSource::PipelineToDot(vtkCollection* sinks, ostream& output, const vtkStdString& graph_name) { // Create a graph representation of the pipeline ... vtkSmartPointer<vtkPipelineGraphSource> pipeline = vtkSmartPointer<vtkPipelineGraphSource>::New(); for(vtkIdType i = 0; i != sinks->GetNumberOfItems(); ++i) { pipeline->AddSink(sinks->GetItemAsObject(i)); } pipeline->Update(); vtkGraph* const pipeline_graph = pipeline->GetOutput(); vtkAbstractArray* const vertex_object_array = pipeline_graph->GetVertexData()->GetAbstractArray("object"); vtkAbstractArray* const edge_output_port_array = pipeline_graph->GetEdgeData()->GetAbstractArray("output_port"); vtkAbstractArray* const edge_input_port_array = pipeline_graph->GetEdgeData()->GetAbstractArray("input_port"); vtkAbstractArray* const edge_object_array = pipeline_graph->GetEdgeData()->GetAbstractArray("object"); output << "digraph \"" << graph_name << "\"\n"; output << "{\n"; // Do some standard formatting ... output << " node [ fontname=\"helvetica\" fontsize=\"10\" shape=\"record\" style=\"filled\" ]\n"; output << " edge [ fontname=\"helvetica\" fontsize=\"9\" ]\n\n"; // Write-out vertices ... for(vtkIdType i = 0; i != pipeline_graph->GetNumberOfVertices(); ++i) { vtkObjectBase* const object = vertex_object_array->GetVariantValue(i).ToVTKObject(); std::stringstream buffer; object->PrintSelf(buffer, vtkIndent()); std::string line; std::string object_state; for(std::getline(buffer, line); buffer; std::getline(buffer, line)) { replace_all(line, "\"", "'"); replace_all(line, "\r", ""); replace_all(line, "\n", ""); if(0 == line.find("Debug:")) continue; if(0 == line.find("Modified Time:")) continue; if(0 == line.find("Reference Count:")) continue; if(0 == line.find("Registered Events:")) continue; if(0 == line.find("Executive:")) continue; if(0 == line.find("ErrorCode:")) continue; if(0 == line.find("Information:")) continue; if(0 == line.find("AbortExecute:")) continue; if(0 == line.find("Progress:")) continue; if(0 == line.find("Progress Text:")) continue; if(0 == line.find(" ")) continue; object_state += line + "\\n"; } std::string fillcolor = "#ccffcc"; if(vtkView::SafeDownCast(object)) { fillcolor = "#ffffcc"; } else if(vtkAnnotationLink::SafeDownCast(object)) { fillcolor = "#ccccff"; } output << " " << "node_" << object << " [ fillcolor=\"" << fillcolor << "\" label=\"{" << object->GetClassName() << "|" << object_state << "}\" vtk_class_name=\"" << object->GetClassName() << "\" ]\n"; } // Write-out edges ... vtkSmartPointer<vtkEdgeListIterator> edges = vtkSmartPointer<vtkEdgeListIterator>::New(); edges->SetGraph(pipeline_graph); while(edges->HasNext()) { vtkEdgeType edge = edges->Next(); vtkObjectBase* const source = vertex_object_array->GetVariantValue(edge.Source).ToVTKObject(); vtkObjectBase* const target = vertex_object_array->GetVariantValue(edge.Target).ToVTKObject(); const vtkStdString output_port = edge_output_port_array->GetVariantValue(edge.Id).ToString(); const vtkStdString input_port = edge_input_port_array->GetVariantValue(edge.Id).ToString(); vtkObjectBase* const object = edge_object_array->GetVariantValue(edge.Id).ToVTKObject(); std::string color = "black"; if(vtkTree::SafeDownCast(object)) { color = "#00bb00"; } else if(vtkTable::SafeDownCast(object)) { color = "blue"; } else if(vtkArrayData* const array_data = vtkArrayData::SafeDownCast(object)) { if(array_data->GetNumberOfArrays()) { color = ""; for(vtkIdType i = 0; i != array_data->GetNumberOfArrays(); ++i) { if(i) color += ":"; if(array_data->GetArray(i)->IsDense()) color += "purple"; else color += "red"; } } } else if(vtkGraph::SafeDownCast(object)) { color = "#cc6600"; } output << " " << "node_" << source << " -> " << "node_" << target; output << " ["; output << " color=\"" << color << "\" fontcolor=\"" << color << "\""; output << " label=\"" << (object ? object->GetClassName() : "") << "\""; output << " headlabel=\"" << input_port << "\""; output << " taillabel=\"" << output_port << "\""; output << " ]\n"; } output << "}\n"; } <|endoftext|>
<commit_before>// Copyright (c) 2010 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/sync/notifier/base/async_network_alive.h" #include <sys/socket.h> #include <asm/types.h> #include <linux/netlink.h> #include <linux/rtnetlink.h> #include "base/logging.h" #include "talk/base/physicalsocketserver.h" namespace notifier { class AsyncNetworkAliveLinux : public AsyncNetworkAlive { public: AsyncNetworkAliveLinux() { if (pipe(exit_pipe_) == -1) { PLOG(ERROR) << "Could not create pipe for exit signal."; exit_pipe_[0] = 0; exit_pipe_[1] = 0; } } virtual ~AsyncNetworkAliveLinux() { if (exit_pipe_[1]) { close(exit_pipe_[1]); } } protected: // SignalThread Interface virtual void DoWork() { if (!exit_pipe_[0]) { // If we don't have an exit flag to listen for, set the error flag and // abort. error_ = true; return; } // This function listens for changes to network interfaces, and link state. // It's copied from syncapi.cc. struct sockaddr_nl socket_address; memset(&socket_address, 0, sizeof(socket_address)); socket_address.nl_family = AF_NETLINK; socket_address.nl_groups = RTMGRP_LINK | RTMGRP_IPV4_IFADDR; // NETLINK_ROUTE is the protocol used to update the kernel routing table. int fd = socket(AF_NETLINK, SOCK_RAW, NETLINK_ROUTE); bind(fd, (struct sockaddr *) &socket_address, sizeof(socket_address)); fd_set rdfs; FD_ZERO(&rdfs); FD_SET(fd, &rdfs); FD_SET(exit_pipe_[0], &rdfs); int max_fd = fd > exit_pipe_[0] ? fd : exit_pipe_[0]; int result = select(max_fd + 1, &rdfs, NULL, NULL, NULL); if (result <= 0) { error_ = true; PLOG(ERROR) << "select() returned unexpected result " << result; close(fd); close(exit_pipe_[0]); return; } // Since we received a change from the socket, read the change in. if (FD_ISSET(fd, &rdfs)) { char buf[4096]; struct iovec iov = { buf, sizeof(buf) }; struct sockaddr_nl sa; struct msghdr msg = { (void *)&sa, sizeof(sa), &iov, 1, NULL, 0, 0 }; recvmsg(fd, &msg, 0); } close(fd); // If exit_pipe was written to, we must be shutting down. if (FD_ISSET(exit_pipe_[0], &rdfs)) { alive_ = false; error_ = true; close(exit_pipe_[0]); return; } // If there is an active connection, check that talk.google.com:5222 // is reachable. talk_base::PhysicalSocketServer physical; scoped_ptr<talk_base::Socket> socket(physical.CreateSocket(SOCK_STREAM)); if (socket->Connect(talk_base::SocketAddress("talk.google.com", 5222))) { alive_ = false; } else { alive_ = true; } } virtual void OnWorkStop() { if (exit_pipe_[1]) { char data = 0; // We can't ignore the return value on write(), since that generates a // compile warning. However, since we're exiting, there's nothing we can // do if this fails except to log it. if (write(exit_pipe_[1], &data, 1) == -1) { PLOG(WARNING) << "Error sending error signal to AsyncNetworkAliveLinux"; } } } private: int exit_pipe_[2]; DISALLOW_COPY_AND_ASSIGN(AsyncNetworkAliveLinux); }; AsyncNetworkAlive* AsyncNetworkAlive::Create() { return new AsyncNetworkAliveLinux(); } } // namespace notifier <commit_msg>Clean up read FDs in async network alive. This prevents chrome from eating all FDs.<commit_after>// Copyright (c) 2010 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/sync/notifier/base/async_network_alive.h" #include <sys/socket.h> #include <asm/types.h> #include <linux/netlink.h> #include <linux/rtnetlink.h> #include "base/logging.h" #include "talk/base/physicalsocketserver.h" namespace notifier { class AsyncNetworkAliveLinux : public AsyncNetworkAlive { public: AsyncNetworkAliveLinux() { if (pipe(exit_pipe_) == -1) { PLOG(ERROR) << "Could not create pipe for exit signal."; exit_pipe_[0] = 0; exit_pipe_[1] = 0; } } virtual ~AsyncNetworkAliveLinux() { if (exit_pipe_[1]) { // Ensure that we've signalled the thread to quit. char data = 0; if (write(exit_pipe_[1], &data, 1) == -1) { PLOG(WARNING) << "Error sending error signal to AsyncNetworkAliveLinux"; } close(exit_pipe_[1]); exit_pipe_[1] = 0; } if (exit_pipe_[0]) { close(exit_pipe_[0]); exit_pipe_[0] = 0; } } protected: // SignalThread Interface virtual void DoWork() { if (!exit_pipe_[0]) { PLOG(ERROR) << "No exit flag to listen for."; // If we don't have an exit flag to listen for, set the error flag and // abort. error_ = true; return; } // This function listens for changes to network interfaces, and link state. // It's copied from syncapi.cc. struct sockaddr_nl socket_address; memset(&socket_address, 0, sizeof(socket_address)); socket_address.nl_family = AF_NETLINK; socket_address.nl_groups = RTMGRP_LINK | RTMGRP_IPV4_IFADDR; // NETLINK_ROUTE is the protocol used to update the kernel routing table. int fd = socket(AF_NETLINK, SOCK_RAW, NETLINK_ROUTE); bind(fd, (struct sockaddr *) &socket_address, sizeof(socket_address)); fd_set rdfs; FD_ZERO(&rdfs); FD_SET(fd, &rdfs); FD_SET(exit_pipe_[0], &rdfs); int max_fd = fd > exit_pipe_[0] ? fd : exit_pipe_[0]; int result = select(max_fd + 1, &rdfs, NULL, NULL, NULL); if (result <= 0) { error_ = true; PLOG(ERROR) << "select() returned unexpected result " << result; close(fd); close(exit_pipe_[0]); exit_pipe_[0] = 0; return; } // Since we received a change from the socket, read the change in. if (FD_ISSET(fd, &rdfs)) { char buf[4096]; struct iovec iov = { buf, sizeof(buf) }; struct sockaddr_nl sa; struct msghdr msg = { (void *)&sa, sizeof(sa), &iov, 1, NULL, 0, 0 }; recvmsg(fd, &msg, 0); } close(fd); // If exit_pipe was written to, we must be shutting down. if (exit_pipe_[0] == 0 || FD_ISSET(exit_pipe_[0], &rdfs)) { alive_ = false; error_ = true; close(exit_pipe_[0]); exit_pipe_[0] = 0; return; } // If there is an active connection, check that talk.google.com:5222 // is reachable. talk_base::PhysicalSocketServer physical; scoped_ptr<talk_base::Socket> socket(physical.CreateSocket(SOCK_STREAM)); if (socket->Connect(talk_base::SocketAddress("talk.google.com", 5222))) { alive_ = false; } else { alive_ = true; } close(exit_pipe_[0]); exit_pipe_[0] = 0; } virtual void OnWorkStop() { if (exit_pipe_[1]) { char data = 0; // We can't ignore the return value on write(), since that generates a // compile warning. However, since we're exiting, there's nothing we can // do if this fails except to log it. if (write(exit_pipe_[1], &data, 1) == -1) { PLOG(WARNING) << "Error sending error signal to AsyncNetworkAliveLinux"; } } } private: int exit_pipe_[2]; DISALLOW_COPY_AND_ASSIGN(AsyncNetworkAliveLinux); }; AsyncNetworkAlive* AsyncNetworkAlive::Create() { return new AsyncNetworkAliveLinux(); } } // namespace notifier <|endoftext|>
<commit_before>// // This file is part of the Marble Virtual Globe. // // This program is free software licensed under the GNU LGPL. You can // find a copy of this license in LICENSE.txt in the top directory of // the source code. // // Copyright 2008 Torsten Rahn <[email protected]> // Copyright 2012 Illya Kovalevskyy <[email protected]> // #include "MapScaleFloatItem.h" #include <QtCore/QDebug> #include <QtCore/QRect> #include <QtGui/QPixmap> #include <QtGui/QApplication> #include <QtGui/QPainter> #include <QtGui/QPushButton> #include <QtGui/QMenu> #include <QtGui/QToolTip> #include "ui_MapScaleConfigWidget.h" #include "MarbleDebug.h" #include "MarbleGlobal.h" #include "Projections/AbstractProjection.h" #include "MarbleLocale.h" #include "MarbleModel.h" #include "ViewportParams.h" namespace Marble { MapScaleFloatItem::MapScaleFloatItem() : AbstractFloatItem( 0 ), m_configDialog( 0 ), ui_configWidget( 0 ) { } MapScaleFloatItem::MapScaleFloatItem( const MarbleModel *marbleModel ) : AbstractFloatItem( marbleModel, QPointF( 10.5, -10.5 ), QSizeF( 0.0, 40.0 ) ), m_configDialog(0), m_radius(0), m_target(QString()), m_leftBarMargin(0), m_rightBarMargin(0), m_scaleBarWidth(0), m_viewportWidth(0), m_scaleBarHeight(5), m_scaleBarDistance(0.0), m_bestDivisor(0), m_pixelInterval(0), m_valueInterval(0), m_scaleInitDone( false ), m_showRatioScale( false ), m_contextMenu( 0 ), m_minimized(false), m_widthScaleFactor(2) { #ifdef Q_WS_MAEMO_5 setPosition( QPointF( 220.0, 10.5 ) ); #endif // Q_WS_MAEMO_5 m_minimizeAction = new QAction(tr("Minimize"), this); m_minimizeAction->setCheckable(true); m_minimizeAction->setChecked(m_minimized); connect(m_minimizeAction, SIGNAL(triggered()), this, SLOT(toggleMinimized())); } MapScaleFloatItem::~MapScaleFloatItem() { } QStringList MapScaleFloatItem::backendTypes() const { return QStringList( "mapscale" ); } QString MapScaleFloatItem::name() const { return tr("Scale Bar"); } QString MapScaleFloatItem::guiString() const { return tr("&Scale Bar"); } QString MapScaleFloatItem::nameId() const { return QString( "scalebar" ); } QString MapScaleFloatItem::version() const { return "1.1"; } QString MapScaleFloatItem::description() const { return tr("This is a float item that provides a map scale."); } QString MapScaleFloatItem::copyrightYears() const { return "2008, 2010, 2012"; } QList<PluginAuthor> MapScaleFloatItem::pluginAuthors() const { return QList<PluginAuthor>() << PluginAuthor( "Torsten Rahn", "[email protected]", tr( "Original Developer" ) ) << PluginAuthor( "Khanh-Nhan Nguyen", "[email protected]" ) << PluginAuthor( "Illya Kovalevskyy", "[email protected]" ); } QIcon MapScaleFloatItem::icon () const { return QIcon(":/icons/scalebar.png"); } void MapScaleFloatItem::initialize () { } bool MapScaleFloatItem::isInitialized () const { return true; } void MapScaleFloatItem::changeViewport( ViewportParams *viewport ) { int viewportWidth = viewport->width(); QString target = marbleModel()->planetId(); if ( !( m_radius == viewport->radius() && viewportWidth == m_viewportWidth && m_target == target && m_scaleInitDone ) ) { int fontHeight = QFontMetrics( font() ).ascent(); if (m_showRatioScale) { setContentSize( QSizeF( viewport->width() / m_widthScaleFactor, fontHeight + 3 + m_scaleBarHeight + fontHeight + 7 ) ); } else { setContentSize( QSizeF( viewport->width() / m_widthScaleFactor, fontHeight + 3 + m_scaleBarHeight ) ); } m_leftBarMargin = QFontMetrics( font() ).boundingRect( "0" ).width() / 2; m_rightBarMargin = QFontMetrics( font() ).boundingRect( "0000" ).width() / 2; m_scaleBarWidth = contentSize().width() - m_leftBarMargin - m_rightBarMargin; m_viewportWidth = viewport->width(); m_radius = viewport->radius(); m_scaleInitDone = true; m_pixel2Length = marbleModel()->planetRadius() / (qreal)(viewport->radius()); if ( viewport->currentProjection()->surfaceType() == AbstractProjection::Cylindrical ) { qreal centerLatitude = viewport->viewLatLonAltBox().center().latitude(); // For flat maps we calculate the length of the 90 deg section of the // central latitude circle. For flat maps this distance matches // the pixel based radius propertyy. m_pixel2Length *= M_PI / 2 * cos( centerLatitude ); } update(); } } void MapScaleFloatItem::paintContent( QPainter *painter ) { painter->save(); painter->setRenderHint( QPainter::Antialiasing, true ); int fontHeight = QFontMetrics( font() ).ascent(); //calculate scale ratio qreal displayMMPerPixel = 1.0 * painter->device()->widthMM() / painter->device()->width(); qreal ratio = m_pixel2Length / (displayMMPerPixel * MM2M); //round ratio to 3 most significant digits, assume that ratio >= 1, otherwise it may display "1 : 0" //i made this assumption because as the primary use case we do not need to zoom in that much qreal power = 1; int iRatio = (int)(ratio + 0.5); //round ratio to the nearest integer while (iRatio >= 1000) { iRatio /= 10; power *= 10; } iRatio *= power; m_ratioString.setNum(iRatio); m_ratioString = m_ratioString = "1 : " + m_ratioString; m_scaleBarDistance = (qreal)(m_scaleBarWidth) * m_pixel2Length; const QLocale::MeasurementSystem measurementSystem = MarbleGlobal::getInstance()->locale()->measurementSystem(); if ( measurementSystem == QLocale::ImperialSystem ) { m_scaleBarDistance *= KM2MI; } calcScaleBar(); painter->setPen( QColor( Qt::darkGray ) ); painter->setBrush( QColor( Qt::darkGray ) ); painter->drawRect( m_leftBarMargin, fontHeight + 3, m_scaleBarWidth, m_scaleBarHeight ); painter->setPen( QColor( Qt::black ) ); painter->setBrush( QColor( Qt::white ) ); painter->drawRect( m_leftBarMargin, fontHeight + 3, m_bestDivisor * m_pixelInterval, m_scaleBarHeight ); painter->setPen( QColor( Oxygen::aluminumGray4 ) ); painter->drawLine( m_leftBarMargin + 1, fontHeight + 2 + m_scaleBarHeight, m_leftBarMargin + m_bestDivisor * m_pixelInterval - 1, fontHeight + 2 + m_scaleBarHeight ); painter->setPen( QColor( Qt::black ) ); painter->setBrush( QColor( Qt::black ) ); QString intervalStr; int lastStringEnds = 0; int currentStringBegin = 0; for ( int j = 0; j <= m_bestDivisor; j += 2 ) { if ( j < m_bestDivisor ) { painter->drawRect( m_leftBarMargin + j * m_pixelInterval, fontHeight + 3, m_pixelInterval - 1, m_scaleBarHeight ); painter->setPen( QColor( Oxygen::aluminumGray5 ) ); painter->drawLine( m_leftBarMargin + j * m_pixelInterval + 1, fontHeight + 4, m_leftBarMargin + (j + 1) * m_pixelInterval - 1, fontHeight + 4 ); painter->setPen( QColor( Qt::black ) ); } QLocale::MeasurementSystem distanceUnit; distanceUnit = MarbleGlobal::getInstance()->locale()->measurementSystem(); QString unit = tr("km"); switch ( distanceUnit ) { case QLocale::MetricSystem: if ( m_bestDivisor * m_valueInterval > 10000 ) { unit = tr("km"); intervalStr.setNum( j * m_valueInterval / 1000 ); } else { unit = tr("m"); intervalStr.setNum( j * m_valueInterval ); } break; case QLocale::ImperialSystem: unit = tr("mi"); intervalStr.setNum( j * m_valueInterval / 1000 ); if ( m_bestDivisor * m_valueInterval > 3800 ) { intervalStr.setNum( j * m_valueInterval / 1000 ); } else { intervalStr.setNum( qreal(j * m_valueInterval ) / 1000.0, 'f', 2 ); } break; } painter->setFont( font() ); if ( j == 0 ) { painter->drawText( 0, fontHeight, "0 " + unit ); lastStringEnds = QFontMetrics( font() ).width( "0 " + unit ); continue; } if( j == m_bestDivisor ) { currentStringBegin = ( j * m_pixelInterval - QFontMetrics( font() ).boundingRect( intervalStr ).width() ); } else { currentStringBegin = ( j * m_pixelInterval - QFontMetrics( font() ).width( intervalStr ) / 2 ); } if ( lastStringEnds < currentStringBegin ) { painter->drawText( currentStringBegin, fontHeight, intervalStr ); lastStringEnds = currentStringBegin + QFontMetrics( font() ).width( intervalStr ); } } int leftRatioIndent = m_leftBarMargin + (m_scaleBarWidth - QFontMetrics( font() ).width(m_ratioString) ) / 2; painter->drawText( leftRatioIndent, fontHeight + 3 + m_scaleBarHeight + fontHeight + 5, m_ratioString ); painter->restore(); } void MapScaleFloatItem::calcScaleBar() { qreal magnitude = 1; // First we calculate the exact length of the whole area that is possibly // available to the scalebar in kilometers int magValue = (int)( m_scaleBarDistance ); // We calculate the two most significant digits of the km-scalebar-length // and store them in magValue. while ( magValue >= 100 ) { magValue /= 10; magnitude *= 10; } m_bestDivisor = 4; int bestMagValue = 1; for ( int i = 0; i < magValue; i++ ) { // We try to find the lowest divisor between 4 and 8 that // divides magValue without remainder. for ( int j = 4; j < 9; j++ ) { if ( ( magValue - i ) % j == 0 ) { // We store the very first result we find and store // m_bestDivisor and bestMagValue as a final result. m_bestDivisor = j; bestMagValue = magValue - i; // Stop all for loops and end search i = magValue; j = 9; } } // If magValue doesn't divide through values between 4 and 8 // (e.g. because it's a prime number) try again with magValue // decreased by i. } m_pixelInterval = (int)( m_scaleBarWidth * (qreal)( bestMagValue ) / (qreal)( magValue ) / m_bestDivisor ); m_valueInterval = (int)( bestMagValue * magnitude / m_bestDivisor ); } QDialog *MapScaleFloatItem::configDialog() { if ( !m_configDialog ) { // Initializing configuration dialog m_configDialog = new QDialog(); ui_configWidget = new Ui::MapScaleConfigWidget; ui_configWidget->setupUi( m_configDialog ); readSettings(); connect( ui_configWidget->m_buttonBox, SIGNAL(accepted()), SLOT(writeSettings()) ); connect( ui_configWidget->m_buttonBox, SIGNAL(rejected()), SLOT(readSettings()) ); QPushButton *applyButton = ui_configWidget->m_buttonBox->button( QDialogButtonBox::Apply ); connect( applyButton, SIGNAL(clicked()) , this, SLOT(writeSettings()) ); } return m_configDialog; } void MapScaleFloatItem::contextMenuEvent( QWidget *w, QContextMenuEvent *e ) { if ( !m_contextMenu ) { m_contextMenu = contextMenu(); foreach( QAction *action, m_contextMenu->actions() ) { if ( action->text() == tr( "&Configure..." ) ) { m_contextMenu->removeAction( action ); break; } } QAction *toggleAction = m_contextMenu->addAction( tr("&Ratio Scale"), this, SLOT(toggleRatioScaleVisibility()) ); toggleAction->setCheckable( true ); toggleAction->setChecked( m_showRatioScale ); m_contextMenu->addAction(m_minimizeAction); } Q_ASSERT( m_contextMenu ); m_contextMenu->exec( w->mapToGlobal( e->pos() ) ); } void MapScaleFloatItem::toolTipEvent( QHelpEvent *e ) { QToolTip::showText( e->globalPos(), m_ratioString ); } void MapScaleFloatItem::readSettings() { if ( !m_configDialog ) return; if ( m_showRatioScale ) { ui_configWidget->m_showRatioScaleCheckBox->setCheckState( Qt::Checked ); } else { ui_configWidget->m_showRatioScaleCheckBox->setCheckState( Qt::Unchecked ); } ui_configWidget->m_minimizeCheckBox->setChecked(m_minimized); } void MapScaleFloatItem::writeSettings() { if ( ui_configWidget->m_showRatioScaleCheckBox->checkState() == Qt::Checked ) { m_showRatioScale = true; } else { m_showRatioScale = false; } if (m_minimized != ui_configWidget->m_minimizeCheckBox->isChecked()) { toggleMinimized(); } emit settingsChanged( nameId() ); } void MapScaleFloatItem::toggleRatioScaleVisibility() { m_showRatioScale = !m_showRatioScale; readSettings(); emit settingsChanged( nameId() ); } void MapScaleFloatItem::toggleMinimized() { m_minimized = !m_minimized; ui_configWidget->m_minimizeCheckBox->setChecked(m_minimized); m_minimizeAction->setChecked(m_minimized); readSettings(); emit settingsChanged( nameId() ); if (m_minimized == true) { m_widthScaleFactor = 4; } else { m_widthScaleFactor = 2; } } } Q_EXPORT_PLUGIN2(MapScaleFloatItem, Marble::MapScaleFloatItem) #include "MapScaleFloatItem.moc" <commit_msg>calculate m_scaleBarDistance when bounding box changes rather than during painting<commit_after>// // This file is part of the Marble Virtual Globe. // // This program is free software licensed under the GNU LGPL. You can // find a copy of this license in LICENSE.txt in the top directory of // the source code. // // Copyright 2008 Torsten Rahn <[email protected]> // Copyright 2012 Illya Kovalevskyy <[email protected]> // #include "MapScaleFloatItem.h" #include <QtCore/QDebug> #include <QtCore/QRect> #include <QtGui/QPixmap> #include <QtGui/QApplication> #include <QtGui/QPainter> #include <QtGui/QPushButton> #include <QtGui/QMenu> #include <QtGui/QToolTip> #include "ui_MapScaleConfigWidget.h" #include "MarbleDebug.h" #include "MarbleGlobal.h" #include "Projections/AbstractProjection.h" #include "MarbleLocale.h" #include "MarbleModel.h" #include "ViewportParams.h" namespace Marble { MapScaleFloatItem::MapScaleFloatItem() : AbstractFloatItem( 0 ), m_configDialog( 0 ), ui_configWidget( 0 ) { } MapScaleFloatItem::MapScaleFloatItem( const MarbleModel *marbleModel ) : AbstractFloatItem( marbleModel, QPointF( 10.5, -10.5 ), QSizeF( 0.0, 40.0 ) ), m_configDialog(0), m_radius(0), m_target(QString()), m_leftBarMargin(0), m_rightBarMargin(0), m_scaleBarWidth(0), m_viewportWidth(0), m_scaleBarHeight(5), m_scaleBarDistance(0.0), m_bestDivisor(0), m_pixelInterval(0), m_valueInterval(0), m_scaleInitDone( false ), m_showRatioScale( false ), m_contextMenu( 0 ), m_minimized(false), m_widthScaleFactor(2) { #ifdef Q_WS_MAEMO_5 setPosition( QPointF( 220.0, 10.5 ) ); #endif // Q_WS_MAEMO_5 m_minimizeAction = new QAction(tr("Minimize"), this); m_minimizeAction->setCheckable(true); m_minimizeAction->setChecked(m_minimized); connect(m_minimizeAction, SIGNAL(triggered()), this, SLOT(toggleMinimized())); } MapScaleFloatItem::~MapScaleFloatItem() { } QStringList MapScaleFloatItem::backendTypes() const { return QStringList( "mapscale" ); } QString MapScaleFloatItem::name() const { return tr("Scale Bar"); } QString MapScaleFloatItem::guiString() const { return tr("&Scale Bar"); } QString MapScaleFloatItem::nameId() const { return QString( "scalebar" ); } QString MapScaleFloatItem::version() const { return "1.1"; } QString MapScaleFloatItem::description() const { return tr("This is a float item that provides a map scale."); } QString MapScaleFloatItem::copyrightYears() const { return "2008, 2010, 2012"; } QList<PluginAuthor> MapScaleFloatItem::pluginAuthors() const { return QList<PluginAuthor>() << PluginAuthor( "Torsten Rahn", "[email protected]", tr( "Original Developer" ) ) << PluginAuthor( "Khanh-Nhan Nguyen", "[email protected]" ) << PluginAuthor( "Illya Kovalevskyy", "[email protected]" ); } QIcon MapScaleFloatItem::icon () const { return QIcon(":/icons/scalebar.png"); } void MapScaleFloatItem::initialize () { } bool MapScaleFloatItem::isInitialized () const { return true; } void MapScaleFloatItem::changeViewport( ViewportParams *viewport ) { int viewportWidth = viewport->width(); QString target = marbleModel()->planetId(); if ( !( m_radius == viewport->radius() && viewportWidth == m_viewportWidth && m_target == target && m_scaleInitDone ) ) { int fontHeight = QFontMetrics( font() ).ascent(); if (m_showRatioScale) { setContentSize( QSizeF( viewport->width() / m_widthScaleFactor, fontHeight + 3 + m_scaleBarHeight + fontHeight + 7 ) ); } else { setContentSize( QSizeF( viewport->width() / m_widthScaleFactor, fontHeight + 3 + m_scaleBarHeight ) ); } m_leftBarMargin = QFontMetrics( font() ).boundingRect( "0" ).width() / 2; m_rightBarMargin = QFontMetrics( font() ).boundingRect( "0000" ).width() / 2; m_scaleBarWidth = contentSize().width() - m_leftBarMargin - m_rightBarMargin; m_viewportWidth = viewport->width(); m_radius = viewport->radius(); m_scaleInitDone = true; m_pixel2Length = marbleModel()->planetRadius() / (qreal)(viewport->radius()); if ( viewport->currentProjection()->surfaceType() == AbstractProjection::Cylindrical ) { qreal centerLatitude = viewport->viewLatLonAltBox().center().latitude(); // For flat maps we calculate the length of the 90 deg section of the // central latitude circle. For flat maps this distance matches // the pixel based radius propertyy. m_pixel2Length *= M_PI / 2 * cos( centerLatitude ); } m_scaleBarDistance = (qreal)(m_scaleBarWidth) * m_pixel2Length; const QLocale::MeasurementSystem measurementSystem = MarbleGlobal::getInstance()->locale()->measurementSystem(); if ( measurementSystem == QLocale::ImperialSystem ) { m_scaleBarDistance *= KM2MI; } calcScaleBar(); update(); } } void MapScaleFloatItem::paintContent( QPainter *painter ) { painter->save(); painter->setRenderHint( QPainter::Antialiasing, true ); int fontHeight = QFontMetrics( font() ).ascent(); //calculate scale ratio qreal displayMMPerPixel = 1.0 * painter->device()->widthMM() / painter->device()->width(); qreal ratio = m_pixel2Length / (displayMMPerPixel * MM2M); //round ratio to 3 most significant digits, assume that ratio >= 1, otherwise it may display "1 : 0" //i made this assumption because as the primary use case we do not need to zoom in that much qreal power = 1; int iRatio = (int)(ratio + 0.5); //round ratio to the nearest integer while (iRatio >= 1000) { iRatio /= 10; power *= 10; } iRatio *= power; m_ratioString.setNum(iRatio); m_ratioString = m_ratioString = "1 : " + m_ratioString; painter->setPen( QColor( Qt::darkGray ) ); painter->setBrush( QColor( Qt::darkGray ) ); painter->drawRect( m_leftBarMargin, fontHeight + 3, m_scaleBarWidth, m_scaleBarHeight ); painter->setPen( QColor( Qt::black ) ); painter->setBrush( QColor( Qt::white ) ); painter->drawRect( m_leftBarMargin, fontHeight + 3, m_bestDivisor * m_pixelInterval, m_scaleBarHeight ); painter->setPen( QColor( Oxygen::aluminumGray4 ) ); painter->drawLine( m_leftBarMargin + 1, fontHeight + 2 + m_scaleBarHeight, m_leftBarMargin + m_bestDivisor * m_pixelInterval - 1, fontHeight + 2 + m_scaleBarHeight ); painter->setPen( QColor( Qt::black ) ); painter->setBrush( QColor( Qt::black ) ); QString intervalStr; int lastStringEnds = 0; int currentStringBegin = 0; for ( int j = 0; j <= m_bestDivisor; j += 2 ) { if ( j < m_bestDivisor ) { painter->drawRect( m_leftBarMargin + j * m_pixelInterval, fontHeight + 3, m_pixelInterval - 1, m_scaleBarHeight ); painter->setPen( QColor( Oxygen::aluminumGray5 ) ); painter->drawLine( m_leftBarMargin + j * m_pixelInterval + 1, fontHeight + 4, m_leftBarMargin + (j + 1) * m_pixelInterval - 1, fontHeight + 4 ); painter->setPen( QColor( Qt::black ) ); } QLocale::MeasurementSystem distanceUnit; distanceUnit = MarbleGlobal::getInstance()->locale()->measurementSystem(); QString unit = tr("km"); switch ( distanceUnit ) { case QLocale::MetricSystem: if ( m_bestDivisor * m_valueInterval > 10000 ) { unit = tr("km"); intervalStr.setNum( j * m_valueInterval / 1000 ); } else { unit = tr("m"); intervalStr.setNum( j * m_valueInterval ); } break; case QLocale::ImperialSystem: unit = tr("mi"); intervalStr.setNum( j * m_valueInterval / 1000 ); if ( m_bestDivisor * m_valueInterval > 3800 ) { intervalStr.setNum( j * m_valueInterval / 1000 ); } else { intervalStr.setNum( qreal(j * m_valueInterval ) / 1000.0, 'f', 2 ); } break; } painter->setFont( font() ); if ( j == 0 ) { painter->drawText( 0, fontHeight, "0 " + unit ); lastStringEnds = QFontMetrics( font() ).width( "0 " + unit ); continue; } if( j == m_bestDivisor ) { currentStringBegin = ( j * m_pixelInterval - QFontMetrics( font() ).boundingRect( intervalStr ).width() ); } else { currentStringBegin = ( j * m_pixelInterval - QFontMetrics( font() ).width( intervalStr ) / 2 ); } if ( lastStringEnds < currentStringBegin ) { painter->drawText( currentStringBegin, fontHeight, intervalStr ); lastStringEnds = currentStringBegin + QFontMetrics( font() ).width( intervalStr ); } } int leftRatioIndent = m_leftBarMargin + (m_scaleBarWidth - QFontMetrics( font() ).width(m_ratioString) ) / 2; painter->drawText( leftRatioIndent, fontHeight + 3 + m_scaleBarHeight + fontHeight + 5, m_ratioString ); painter->restore(); } void MapScaleFloatItem::calcScaleBar() { qreal magnitude = 1; // First we calculate the exact length of the whole area that is possibly // available to the scalebar in kilometers int magValue = (int)( m_scaleBarDistance ); // We calculate the two most significant digits of the km-scalebar-length // and store them in magValue. while ( magValue >= 100 ) { magValue /= 10; magnitude *= 10; } m_bestDivisor = 4; int bestMagValue = 1; for ( int i = 0; i < magValue; i++ ) { // We try to find the lowest divisor between 4 and 8 that // divides magValue without remainder. for ( int j = 4; j < 9; j++ ) { if ( ( magValue - i ) % j == 0 ) { // We store the very first result we find and store // m_bestDivisor and bestMagValue as a final result. m_bestDivisor = j; bestMagValue = magValue - i; // Stop all for loops and end search i = magValue; j = 9; } } // If magValue doesn't divide through values between 4 and 8 // (e.g. because it's a prime number) try again with magValue // decreased by i. } m_pixelInterval = (int)( m_scaleBarWidth * (qreal)( bestMagValue ) / (qreal)( magValue ) / m_bestDivisor ); m_valueInterval = (int)( bestMagValue * magnitude / m_bestDivisor ); } QDialog *MapScaleFloatItem::configDialog() { if ( !m_configDialog ) { // Initializing configuration dialog m_configDialog = new QDialog(); ui_configWidget = new Ui::MapScaleConfigWidget; ui_configWidget->setupUi( m_configDialog ); readSettings(); connect( ui_configWidget->m_buttonBox, SIGNAL(accepted()), SLOT(writeSettings()) ); connect( ui_configWidget->m_buttonBox, SIGNAL(rejected()), SLOT(readSettings()) ); QPushButton *applyButton = ui_configWidget->m_buttonBox->button( QDialogButtonBox::Apply ); connect( applyButton, SIGNAL(clicked()) , this, SLOT(writeSettings()) ); } return m_configDialog; } void MapScaleFloatItem::contextMenuEvent( QWidget *w, QContextMenuEvent *e ) { if ( !m_contextMenu ) { m_contextMenu = contextMenu(); foreach( QAction *action, m_contextMenu->actions() ) { if ( action->text() == tr( "&Configure..." ) ) { m_contextMenu->removeAction( action ); break; } } QAction *toggleAction = m_contextMenu->addAction( tr("&Ratio Scale"), this, SLOT(toggleRatioScaleVisibility()) ); toggleAction->setCheckable( true ); toggleAction->setChecked( m_showRatioScale ); m_contextMenu->addAction(m_minimizeAction); } Q_ASSERT( m_contextMenu ); m_contextMenu->exec( w->mapToGlobal( e->pos() ) ); } void MapScaleFloatItem::toolTipEvent( QHelpEvent *e ) { QToolTip::showText( e->globalPos(), m_ratioString ); } void MapScaleFloatItem::readSettings() { if ( !m_configDialog ) return; if ( m_showRatioScale ) { ui_configWidget->m_showRatioScaleCheckBox->setCheckState( Qt::Checked ); } else { ui_configWidget->m_showRatioScaleCheckBox->setCheckState( Qt::Unchecked ); } ui_configWidget->m_minimizeCheckBox->setChecked(m_minimized); } void MapScaleFloatItem::writeSettings() { if ( ui_configWidget->m_showRatioScaleCheckBox->checkState() == Qt::Checked ) { m_showRatioScale = true; } else { m_showRatioScale = false; } if (m_minimized != ui_configWidget->m_minimizeCheckBox->isChecked()) { toggleMinimized(); } emit settingsChanged( nameId() ); } void MapScaleFloatItem::toggleRatioScaleVisibility() { m_showRatioScale = !m_showRatioScale; readSettings(); emit settingsChanged( nameId() ); } void MapScaleFloatItem::toggleMinimized() { m_minimized = !m_minimized; ui_configWidget->m_minimizeCheckBox->setChecked(m_minimized); m_minimizeAction->setChecked(m_minimized); readSettings(); emit settingsChanged( nameId() ); if (m_minimized == true) { m_widthScaleFactor = 4; } else { m_widthScaleFactor = 2; } } } Q_EXPORT_PLUGIN2(MapScaleFloatItem, Marble::MapScaleFloatItem) #include "MapScaleFloatItem.moc" <|endoftext|>
<commit_before>/* * Copyright (C) 2018 The Android Open Source Project * * 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 "gtest/gtest.h" #include "perfetto/base/build_config.h" #include "src/base/test/test_task_runner.h" #include "test/test_helper.h" #include "src/profiling/memory/heapprofd_producer.h" #include "src/tracing/ipc/default_socket.h" #include <sys/system_properties.h> // This test only works when run on Android using an Android Q version of // Bionic. #if !PERFETTO_BUILDFLAG(PERFETTO_OS_ANDROID) #error "This test can only be used on Android." #endif // If we're building on Android and starting the daemons ourselves, // create the sockets in a world-writable location. #if PERFETTO_BUILDFLAG(PERFETTO_START_DAEMONS) #define TEST_PRODUCER_SOCK_NAME "/data/local/tmp/traced_producer" #else #define TEST_PRODUCER_SOCK_NAME ::perfetto::GetProducerSocket() #endif namespace perfetto { namespace profiling { namespace { void WaitForHeapprofd(uint64_t timeout_ms) { constexpr uint64_t kSleepMs = 10; std::vector<std::string> cmdlines{"heapprofd"}; std::set<pid_t> pids; for (size_t i = 0; i < timeout_ms / kSleepMs && pids.empty(); ++i) { FindPidsForCmdlines(cmdlines, &pids); usleep(kSleepMs * 1000); } } class HeapprofdDelegate : public ThreadDelegate { public: HeapprofdDelegate(const std::string& producer_socket) : producer_socket_(producer_socket) {} ~HeapprofdDelegate() override = default; void Initialize(base::TaskRunner* task_runner) override { producer_.reset( new HeapprofdProducer(HeapprofdMode::kCentral, task_runner)); producer_->ConnectWithRetries(producer_socket_.c_str()); } private: std::string producer_socket_; std::unique_ptr<HeapprofdProducer> producer_; }; constexpr const char* kEnableHeapprofdProperty = "persist.heapprofd.enable"; int __attribute__((unused)) SetProperty(std::string* value) { if (value) { __system_property_set(kEnableHeapprofdProperty, value->c_str()); delete value; } return 0; } base::ScopedResource<std::string*, SetProperty, nullptr> StartSystemHeapprofdIfRequired() { base::ignore_result(TEST_PRODUCER_SOCK_NAME); std::string prev_property_value = "0"; const prop_info* pi = __system_property_find(kEnableHeapprofdProperty); if (pi) { __system_property_read_callback( pi, [](void* cookie, const char*, const char* value, uint32_t) { *reinterpret_cast<std::string*>(cookie) = value; }, &prev_property_value); } __system_property_set(kEnableHeapprofdProperty, "1"); WaitForHeapprofd(5000); return base::ScopedResource<std::string*, SetProperty, nullptr>( new std::string(prev_property_value)); } pid_t ForkContinousMalloc(size_t bytes) { pid_t pid = fork(); switch (pid) { case -1: PERFETTO_FATAL("Failed to fork."); case 0: for (;;) { // This volatile is needed to prevent the compiler from trying to be // helpful and compiling a "useless" malloc + free into a noop. volatile char* x = static_cast<char*>(malloc(bytes)); if (x) { x[1] = 'x'; free(const_cast<char*>(x)); } } default: break; } return pid; } class HeapprofdEndToEnd : public ::testing::Test { public: HeapprofdEndToEnd() { // This is not needed for correctness, but works around a init behavior that // makes this test take much longer. If persist.heapprofd.enable is set to 0 // and then set to 1 again too quickly, init decides that the service is // "restarting" and waits before restarting it. usleep(50000); helper.StartServiceIfRequired(); unset_property = StartSystemHeapprofdIfRequired(); helper.ConnectConsumer(); helper.WaitForConsumerConnect(); } protected: base::TestTaskRunner task_runner; TestHelper helper{&task_runner}; #if PERFETTO_BUILDFLAG(PERFETTO_START_DAEMONS) TaskRunnerThread producer_thread("perfetto.prd"); producer_thread.Start(std::unique_ptr<HeapprofdDelegate>( new HeapprofdDelegate(TEST_PRODUCER_SOCK_NAME))); #else base::ScopedResource<std::string*, SetProperty, nullptr> unset_property; #endif }; // TODO(b/121352331): deflake and re-enable this test. TEST_F(HeapprofdEndToEnd, DISABLED_Smoke) { constexpr size_t kAllocSize = 1024; pid_t pid = ForkContinousMalloc(kAllocSize); TraceConfig trace_config; trace_config.add_buffers()->set_size_kb(10 * 1024); trace_config.set_duration_ms(1000); auto* ds_config = trace_config.add_data_sources()->mutable_config(); ds_config->set_name("android.heapprofd"); ds_config->set_target_buffer(0); auto* heapprofd_config = ds_config->mutable_heapprofd_config(); heapprofd_config->set_sampling_interval_bytes(1); *heapprofd_config->add_pid() = static_cast<uint64_t>(pid); heapprofd_config->set_all(false); heapprofd_config->mutable_continuous_dump_config()->set_dump_phase_ms(0); heapprofd_config->mutable_continuous_dump_config()->set_dump_interval_ms(100); helper.StartTracing(trace_config); helper.WaitForTracingDisabled(5000); helper.ReadData(); helper.WaitForReadData(); PERFETTO_CHECK(kill(pid, SIGKILL) == 0); PERFETTO_CHECK(waitpid(pid, nullptr, 0) == pid); const auto& packets = helper.trace(); ASSERT_GT(packets.size(), 0u); size_t profile_packets = 0; size_t samples = 0; uint64_t last_allocated = 0; uint64_t last_freed = 0; for (const protos::TracePacket& packet : packets) { if (packet.has_profile_packet() && packet.profile_packet().process_dumps().size() > 0) { const auto& dumps = packet.profile_packet().process_dumps(); ASSERT_EQ(dumps.size(), 1); const protos::ProfilePacket_ProcessHeapSamples& dump = dumps.Get(0); EXPECT_EQ(dump.pid(), pid); EXPECT_EQ(dump.samples().size(), 1); for (const auto& sample : dump.samples()) { samples++; EXPECT_EQ(sample.self_allocated() % kAllocSize, 0); EXPECT_EQ(sample.self_freed() % kAllocSize, 0); last_allocated = sample.self_allocated(); last_freed = sample.self_freed(); } profile_packets++; } } EXPECT_GT(profile_packets, 0); EXPECT_GT(samples, 0); EXPECT_GT(last_allocated, 0); EXPECT_GT(last_freed, 0); } // TODO(b/121352331): deflake and re-enable this test. TEST_F(HeapprofdEndToEnd, DISABLED_FinalFlush) { constexpr size_t kAllocSize = 1024; pid_t pid = ForkContinousMalloc(kAllocSize); TraceConfig trace_config; trace_config.add_buffers()->set_size_kb(10 * 1024); trace_config.set_duration_ms(1000); auto* ds_config = trace_config.add_data_sources()->mutable_config(); ds_config->set_name("android.heapprofd"); ds_config->set_target_buffer(0); auto* heapprofd_config = ds_config->mutable_heapprofd_config(); heapprofd_config->set_sampling_interval_bytes(1); *heapprofd_config->add_pid() = static_cast<uint64_t>(pid); heapprofd_config->set_all(false); helper.StartTracing(trace_config); helper.WaitForTracingDisabled(5000); helper.ReadData(); helper.WaitForReadData(); PERFETTO_CHECK(kill(pid, SIGKILL) == 0); PERFETTO_CHECK(waitpid(pid, nullptr, 0) == pid); const auto& packets = helper.trace(); ASSERT_GT(packets.size(), 0u); size_t profile_packets = 0; size_t samples = 0; uint64_t last_allocated = 0; uint64_t last_freed = 0; for (const protos::TracePacket& packet : packets) { if (packet.has_profile_packet() && packet.profile_packet().process_dumps().size() > 0) { const auto& dumps = packet.profile_packet().process_dumps(); ASSERT_EQ(dumps.size(), 1); const protos::ProfilePacket_ProcessHeapSamples& dump = dumps.Get(0); EXPECT_EQ(dump.pid(), pid); EXPECT_EQ(dump.samples().size(), 1); for (const auto& sample : dump.samples()) { samples++; EXPECT_EQ(sample.self_allocated() % kAllocSize, 0); EXPECT_EQ(sample.self_freed() % kAllocSize, 0); last_allocated = sample.self_allocated(); last_freed = sample.self_freed(); } profile_packets++; } } EXPECT_EQ(profile_packets, 1); EXPECT_GT(samples, 0); EXPECT_GT(last_allocated, 0); EXPECT_GT(last_freed, 0); } // TODO(b/121352331): deflake and re-enable this test. TEST_F(HeapprofdEndToEnd, DISABLED_NativeStartup) { TraceConfig trace_config; trace_config.add_buffers()->set_size_kb(10 * 1024); trace_config.set_duration_ms(5000); auto* ds_config = trace_config.add_data_sources()->mutable_config(); ds_config->set_name("android.heapprofd"); auto* heapprofd_config = ds_config->mutable_heapprofd_config(); heapprofd_config->set_sampling_interval_bytes(1); *heapprofd_config->add_process_cmdline() = "find"; heapprofd_config->set_all(false); helper.StartTracing(trace_config); // Wait to guarantee that the process forked below is hooked by the profiler // by virtue of the startup check, and not by virtue of being seen as a // runnning process. This sleep is here to prevent that, accidentally, the // test gets to the fork()+exec() too soon, before the heap profiling daemon // has received the trace config. sleep(1); pid_t pid = fork(); switch (pid) { case -1: PERFETTO_FATAL("Failed to fork."); case 0: { int null = open("/dev/null", O_RDWR); dup2(null, STDIN_FILENO); dup2(null, STDOUT_FILENO); dup2(null, STDERR_FILENO); // TODO(fmayer): Use a dedicated test binary rather than relying on find // doing allocations. PERFETTO_CHECK(execl("/system/bin/find", "find", "/", nullptr) == 0); break; } default: break; } helper.WaitForTracingDisabled(10000); helper.ReadData(); helper.WaitForReadData(); PERFETTO_CHECK(kill(pid, SIGKILL) == 0); PERFETTO_CHECK(waitpid(pid, nullptr, 0) == pid); const auto& packets = helper.trace(); ASSERT_GT(packets.size(), 0u); size_t profile_packets = 0; size_t samples = 0; uint64_t total_allocated = 0; uint64_t total_freed = 0; for (const protos::TracePacket& packet : packets) { if (packet.has_profile_packet() && packet.profile_packet().process_dumps().size() > 0) { const auto& dumps = packet.profile_packet().process_dumps(); ASSERT_EQ(dumps.size(), 1); const protos::ProfilePacket_ProcessHeapSamples& dump = dumps.Get(0); EXPECT_EQ(dump.pid(), pid); profile_packets++; for (const auto& sample : dump.samples()) { samples++; total_allocated += sample.self_allocated(); total_freed += sample.self_freed(); } } } EXPECT_EQ(profile_packets, 1); EXPECT_GT(samples, 0); EXPECT_GT(total_allocated, 0); EXPECT_GT(total_freed, 0); } } // namespace } // namespace profiling } // namespace perfetto <commit_msg>profiling: Re-enable end to end tests. am: b10161389f am: 6d1dea6861<commit_after>/* * Copyright (C) 2018 The Android Open Source Project * * 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 "gtest/gtest.h" #include "perfetto/base/build_config.h" #include "src/base/test/test_task_runner.h" #include "test/test_helper.h" #include "src/profiling/memory/heapprofd_producer.h" #include "src/tracing/ipc/default_socket.h" #include <sys/system_properties.h> // This test only works when run on Android using an Android Q version of // Bionic. #if !PERFETTO_BUILDFLAG(PERFETTO_OS_ANDROID) #error "This test can only be used on Android." #endif // If we're building on Android and starting the daemons ourselves, // create the sockets in a world-writable location. #if PERFETTO_BUILDFLAG(PERFETTO_START_DAEMONS) #define TEST_PRODUCER_SOCK_NAME "/data/local/tmp/traced_producer" #else #define TEST_PRODUCER_SOCK_NAME ::perfetto::GetProducerSocket() #endif namespace perfetto { namespace profiling { namespace { void WaitForHeapprofd(uint64_t timeout_ms) { constexpr uint64_t kSleepMs = 10; std::vector<std::string> cmdlines{"heapprofd"}; std::set<pid_t> pids; for (size_t i = 0; i < timeout_ms / kSleepMs && pids.empty(); ++i) { FindPidsForCmdlines(cmdlines, &pids); usleep(kSleepMs * 1000); } } class HeapprofdDelegate : public ThreadDelegate { public: HeapprofdDelegate(const std::string& producer_socket) : producer_socket_(producer_socket) {} ~HeapprofdDelegate() override = default; void Initialize(base::TaskRunner* task_runner) override { producer_.reset( new HeapprofdProducer(HeapprofdMode::kCentral, task_runner)); producer_->ConnectWithRetries(producer_socket_.c_str()); } private: std::string producer_socket_; std::unique_ptr<HeapprofdProducer> producer_; }; constexpr const char* kEnableHeapprofdProperty = "persist.heapprofd.enable"; int __attribute__((unused)) SetProperty(std::string* value) { if (value) { __system_property_set(kEnableHeapprofdProperty, value->c_str()); delete value; } return 0; } base::ScopedResource<std::string*, SetProperty, nullptr> StartSystemHeapprofdIfRequired() { base::ignore_result(TEST_PRODUCER_SOCK_NAME); std::string prev_property_value = "0"; const prop_info* pi = __system_property_find(kEnableHeapprofdProperty); if (pi) { __system_property_read_callback( pi, [](void* cookie, const char*, const char* value, uint32_t) { *reinterpret_cast<std::string*>(cookie) = value; }, &prev_property_value); } __system_property_set(kEnableHeapprofdProperty, "1"); WaitForHeapprofd(5000); return base::ScopedResource<std::string*, SetProperty, nullptr>( new std::string(prev_property_value)); } pid_t ForkContinousMalloc(size_t bytes) { pid_t pid = fork(); switch (pid) { case -1: PERFETTO_FATAL("Failed to fork."); case 0: for (;;) { // This volatile is needed to prevent the compiler from trying to be // helpful and compiling a "useless" malloc + free into a noop. volatile char* x = static_cast<char*>(malloc(bytes)); if (x) { x[1] = 'x'; free(const_cast<char*>(x)); } } default: break; } return pid; } class HeapprofdEndToEnd : public ::testing::Test { public: HeapprofdEndToEnd() { // This is not needed for correctness, but works around a init behavior that // makes this test take much longer. If persist.heapprofd.enable is set to 0 // and then set to 1 again too quickly, init decides that the service is // "restarting" and waits before restarting it. usleep(50000); helper.StartServiceIfRequired(); unset_property = StartSystemHeapprofdIfRequired(); helper.ConnectConsumer(); helper.WaitForConsumerConnect(); } protected: base::TestTaskRunner task_runner; TestHelper helper{&task_runner}; #if PERFETTO_BUILDFLAG(PERFETTO_START_DAEMONS) TaskRunnerThread producer_thread("perfetto.prd"); producer_thread.Start(std::unique_ptr<HeapprofdDelegate>( new HeapprofdDelegate(TEST_PRODUCER_SOCK_NAME))); #else base::ScopedResource<std::string*, SetProperty, nullptr> unset_property; #endif }; // TODO(b/121352331): deflake and re-enable this test. TEST_F(HeapprofdEndToEnd, Smoke) { constexpr size_t kAllocSize = 1024; pid_t pid = ForkContinousMalloc(kAllocSize); TraceConfig trace_config; trace_config.add_buffers()->set_size_kb(10 * 1024); trace_config.set_duration_ms(1000); auto* ds_config = trace_config.add_data_sources()->mutable_config(); ds_config->set_name("android.heapprofd"); ds_config->set_target_buffer(0); auto* heapprofd_config = ds_config->mutable_heapprofd_config(); heapprofd_config->set_sampling_interval_bytes(1); *heapprofd_config->add_pid() = static_cast<uint64_t>(pid); heapprofd_config->set_all(false); heapprofd_config->mutable_continuous_dump_config()->set_dump_phase_ms(0); heapprofd_config->mutable_continuous_dump_config()->set_dump_interval_ms(100); helper.StartTracing(trace_config); helper.WaitForTracingDisabled(10000); helper.ReadData(); helper.WaitForReadData(); PERFETTO_CHECK(kill(pid, SIGKILL) == 0); PERFETTO_CHECK(waitpid(pid, nullptr, 0) == pid); const auto& packets = helper.trace(); ASSERT_GT(packets.size(), 0u); size_t profile_packets = 0; size_t samples = 0; uint64_t last_allocated = 0; uint64_t last_freed = 0; for (const protos::TracePacket& packet : packets) { if (packet.has_profile_packet() && packet.profile_packet().process_dumps().size() > 0) { const auto& dumps = packet.profile_packet().process_dumps(); ASSERT_EQ(dumps.size(), 1); const protos::ProfilePacket_ProcessHeapSamples& dump = dumps.Get(0); EXPECT_EQ(dump.pid(), pid); for (const auto& sample : dump.samples()) { samples++; EXPECT_EQ(sample.self_allocated() % kAllocSize, 0); EXPECT_EQ(sample.self_freed() % kAllocSize, 0); last_allocated = sample.self_allocated(); last_freed = sample.self_freed(); } profile_packets++; } } EXPECT_GT(profile_packets, 0); EXPECT_GT(samples, 0); EXPECT_GT(last_allocated, 0); EXPECT_GT(last_freed, 0); } // TODO(b/121352331): deflake and re-enable this test. TEST_F(HeapprofdEndToEnd, FinalFlush) { constexpr size_t kAllocSize = 1024; pid_t pid = ForkContinousMalloc(kAllocSize); TraceConfig trace_config; trace_config.add_buffers()->set_size_kb(10 * 1024); trace_config.set_duration_ms(1000); auto* ds_config = trace_config.add_data_sources()->mutable_config(); ds_config->set_name("android.heapprofd"); ds_config->set_target_buffer(0); auto* heapprofd_config = ds_config->mutable_heapprofd_config(); heapprofd_config->set_sampling_interval_bytes(1); *heapprofd_config->add_pid() = static_cast<uint64_t>(pid); heapprofd_config->set_all(false); helper.StartTracing(trace_config); helper.WaitForTracingDisabled(10000); helper.ReadData(); helper.WaitForReadData(); PERFETTO_CHECK(kill(pid, SIGKILL) == 0); PERFETTO_CHECK(waitpid(pid, nullptr, 0) == pid); const auto& packets = helper.trace(); ASSERT_GT(packets.size(), 0u); size_t profile_packets = 0; size_t samples = 0; uint64_t last_allocated = 0; uint64_t last_freed = 0; for (const protos::TracePacket& packet : packets) { if (packet.has_profile_packet() && packet.profile_packet().process_dumps().size() > 0) { const auto& dumps = packet.profile_packet().process_dumps(); ASSERT_EQ(dumps.size(), 1); const protos::ProfilePacket_ProcessHeapSamples& dump = dumps.Get(0); EXPECT_EQ(dump.pid(), pid); EXPECT_EQ(dump.samples().size(), 1); for (const auto& sample : dump.samples()) { samples++; EXPECT_EQ(sample.self_allocated() % kAllocSize, 0); EXPECT_EQ(sample.self_freed() % kAllocSize, 0); last_allocated = sample.self_allocated(); last_freed = sample.self_freed(); } profile_packets++; } } EXPECT_EQ(profile_packets, 1); EXPECT_GT(samples, 0); EXPECT_GT(last_allocated, 0); EXPECT_GT(last_freed, 0); } // TODO(b/121352331): deflake and re-enable this test. TEST_F(HeapprofdEndToEnd, NativeStartup) { TraceConfig trace_config; trace_config.add_buffers()->set_size_kb(10 * 1024); trace_config.set_duration_ms(5000); auto* ds_config = trace_config.add_data_sources()->mutable_config(); ds_config->set_name("android.heapprofd"); auto* heapprofd_config = ds_config->mutable_heapprofd_config(); heapprofd_config->set_sampling_interval_bytes(1); *heapprofd_config->add_process_cmdline() = "find"; heapprofd_config->set_all(false); helper.StartTracing(trace_config); // Wait to guarantee that the process forked below is hooked by the profiler // by virtue of the startup check, and not by virtue of being seen as a // runnning process. This sleep is here to prevent that, accidentally, the // test gets to the fork()+exec() too soon, before the heap profiling daemon // has received the trace config. sleep(1); pid_t pid = fork(); switch (pid) { case -1: PERFETTO_FATAL("Failed to fork."); case 0: { int null = open("/dev/null", O_RDWR); dup2(null, STDIN_FILENO); dup2(null, STDOUT_FILENO); dup2(null, STDERR_FILENO); // TODO(fmayer): Use a dedicated test binary rather than relying on find // doing allocations. PERFETTO_CHECK(execl("/system/bin/find", "find", "/", nullptr) == 0); break; } default: break; } helper.WaitForTracingDisabled(10000); helper.ReadData(); helper.WaitForReadData(); PERFETTO_CHECK(kill(pid, SIGKILL) == 0); PERFETTO_CHECK(waitpid(pid, nullptr, 0) == pid); const auto& packets = helper.trace(); ASSERT_GT(packets.size(), 0u); size_t profile_packets = 0; size_t samples = 0; uint64_t total_allocated = 0; uint64_t total_freed = 0; for (const protos::TracePacket& packet : packets) { if (packet.has_profile_packet() && packet.profile_packet().process_dumps().size() > 0) { const auto& dumps = packet.profile_packet().process_dumps(); ASSERT_EQ(dumps.size(), 1); const protos::ProfilePacket_ProcessHeapSamples& dump = dumps.Get(0); EXPECT_EQ(dump.pid(), pid); profile_packets++; for (const auto& sample : dump.samples()) { samples++; total_allocated += sample.self_allocated(); total_freed += sample.self_freed(); } } } EXPECT_EQ(profile_packets, 1); EXPECT_GT(samples, 0); EXPECT_GT(total_allocated, 0); EXPECT_GT(total_freed, 0); } } // namespace } // namespace profiling } // namespace perfetto <|endoftext|>
<commit_before>#pragma once #include <stdint.h> namespace autocxxpy { template <size_t ... vals> inline constexpr int64_t tsum() noexcept { if constexpr (sizeof...(vals) == 0) return 0; else return (vals + ...); } static_assert(tsum<1, 2, 3>() == 6); template <class ... T> inline constexpr int64_t tsum(const T& ... vals) noexcept { if constexpr (sizeof...(vals) == 0) return 0; else return (vals + ...); } static_assert(tsum(1, 2, 3) == 6); } <commit_msg>Delete algorithm.hpp<commit_after><|endoftext|>
<commit_before>#include "pch.h" #include "MainWindow.h" #include "Items.h" #include "Resources\resource.h" #include "Person.h" #include "FlashImageScene.h" #include "LuckyScene.h" #include "Box2dScene.h" #include "DxRes.h" using D2D1::ColorF; using D2D1::Matrix3x2F; using namespace std; const UINT ControlCombox = 1; const UINT MenuLotteryStart = 2; const UINT MenuLotteryLast() { return MenuLotteryStart + GetItems().size(); } const UINT MenuStatusStart() { return MenuLotteryLast() + 1; }; const UINT MenuStatusLast() { return MenuStatusStart() + GetItems().size(); }; const UINT MenuStatusClear() { return MenuStatusLast() + 1; }; BEGIN_MESSAGE_MAP(MainWindow, CFrameWnd) ON_COMMAND_RANGE(MenuLotteryStart, MenuLotteryLast(), OnLottery) ON_COMMAND_RANGE(MenuStatusStart(), MenuStatusLast(), OnStatus) ON_COMMAND(MenuStatusClear(), OnLotteryClear) ON_WM_CREATE() ON_WM_SIZE() ON_REGISTERED_MESSAGE(AFX_WM_DRAW2D, OnDraw2D) ON_REGISTERED_MESSAGE(AFX_WM_RECREATED2DRESOURCES, CreateDeviceResources) ON_WM_KEYUP() END_MESSAGE_MAP() MainWindow::MainWindow() { Create(nullptr, L"Lottery 2017", WS_OVERLAPPEDWINDOW, { 100, 100, 800, 600 }); } void MainWindow::Update() { for (auto& scene : _scenes) { scene->Update(); } } void MainWindow::OnKeyUp(UINT nChar, UINT nRepCnt, UINT nFlags) { for (auto& scene : _scenes) { scene->KeyUp(nChar); } } void MainWindow::OnSize(UINT nType, int cx, int cy) { if (nType != SIZE_MINIMIZED && GetRenderTarget()) { _dxRes.CreateDeviceSizeResources(GetRenderTarget()); } } void MainWindow::OnLottery(UINT id) { auto itemId = id - MenuLotteryStart; auto item = GetItems()[itemId]; auto unluckyIds = GetUnluckyPersonIds(itemId); auto needCount = item.Count; if (unluckyIds.empty()) { MessageBoxW(L""); return; } if (needCount > (int)unluckyIds.size()) { CString str; str.Format(L"ʣ(%d)(%s)Ҫ(%d),ǷΪ(%d)˲?", unluckyIds.size(), item.Name, needCount, unluckyIds.size()); if (MessageBoxW(str, nullptr, MB_YESNO) == IDNO) { return; } needCount = (int)unluckyIds.size(); } auto luckyCount = GetLuckyPersonIds(itemId).size(); if (luckyCount > 0) { CString str; str.Format(L" %d ˳ %s, Ƿ?", luckyCount, item.Name); if (MessageBoxW(str, nullptr, MB_YESNO) == IDNO) { return; } } _menu.CheckMenuRadioItem(MenuLotteryStart, MenuLotteryLast(), id, MF_BYCOMMAND); _scenes.clear(); CreateScene(needCount, itemId, unluckyIds); } void MainWindow::OnStatus(UINT id) { auto itemId = id - MenuStatusStart(); auto ids = GetLuckyPersonIds(itemId); _scenes.clear(); CreateScene(-1, itemId, ids); } int MainWindow::OnCreate(LPCREATESTRUCT cs) { // setup menu _menu.LoadMenuW(IDR_MENU1); for (size_t i = 0; i < GetItems().size(); ++i) { auto item = GetItems()[i]; auto lotteryMenu = _menu.GetSubMenu(1); auto statusMenu = _menu.GetSubMenu(2); CString str; str.Format(L"%s(&%d)", item.Name, i + 1); lotteryMenu->AppendMenuW(MF_STRING, MenuLotteryStart + i, str); statusMenu->AppendMenuW(MF_STRING, MenuStatusStart() + i, str); } _menu.GetSubMenu(1)->RemoveMenu(0, 0); _menu.GetSubMenu(2)->RemoveMenu(0, 0); _menu.GetSubMenu(2)->AppendMenuW(MF_SEPARATOR); _menu.GetSubMenu(2)->AppendMenuW(MF_STRING, MenuStatusClear(), L"״̬(&C)"); _menu.CheckMenuRadioItem(MenuLotteryStart, MenuLotteryLast(), MenuLotteryStart, MF_BYCOMMAND); SetMenu(&_menu); // d2d EnableD2DSupport(); _dxRes.CreateDeviceResources(GetRenderTarget()); _dxRes.CreateDeviceSizeResources(GetRenderTarget()); CreateScene(GetItems()[0].Count, 0, GetUnluckyPersonIds(0)); return TRUE; } void MainWindow::OnLotteryClear() { if (MessageBoxW(L"ȷҪճ齱״̬?", nullptr, MB_YESNO) == IDYES) { DeleteLuckyPersons(); MessageBoxW(L"г齱״̬"); } } LRESULT MainWindow::OnDraw2D(WPARAM, LPARAM lparam) { Update(); auto target = (CHwndRenderTarget*)lparam; ASSERT_VALID(target); RECT rect; GetClientRect(&rect); CD2DRectF d2dRect{ (float)rect.left, (float)rect.top, (float)rect.right, (float)rect.bottom }; target->DrawBitmap(_dxRes.Background, d2dRect); { auto bmp = _dxRes.LotteryBitmaps[GetLotteryId()]; auto width = d2dRect.right - d2dRect.left; auto height = d2dRect.bottom - d2dRect.top; auto scale = 1.f / 3; target->SetTransform( Matrix3x2F::Scale(scale, scale) * Matrix3x2F::Translation(width * (1 - scale) - 10, height * (1 - scale) - 10) ); target->DrawBitmap(bmp, d2dRect); target->SetTransform(Matrix3x2F::Identity()); } for (auto& scene : _scenes) { scene->Render(target, &_dxRes); } return TRUE; } LRESULT MainWindow::CreateDeviceResources(WPARAM, LPARAM lparam) { _dxRes.ClearDeviceResources(); _dxRes.CreateDeviceResources((CHwndRenderTarget*)lparam); return 0; } void MainWindow::CreateScene(int count, int itemId, const std::vector<int>& personIds) { if (count == -1) { _scenes.emplace_back(make_unique<LuckyScene>(itemId, personIds)); } else if (count <= 10) { _scenes.emplace_back(make_unique<Box2dScene>(count, itemId, personIds)); } else { _scenes.emplace_back(make_unique<FlashImageScene>(count, itemId, personIds)); } } size_t MainWindow::GetLotteryId() { for (size_t i = 0; i < GetItems().size(); ++i) { if (_menu.GetMenuState(UINT(i + MenuLotteryStart), MF_BYCOMMAND) & MF_CHECKED) { return i; } } return 0; }<commit_msg>switch number to 5<commit_after>#include "pch.h" #include "MainWindow.h" #include "Items.h" #include "Resources\resource.h" #include "Person.h" #include "FlashImageScene.h" #include "LuckyScene.h" #include "Box2dScene.h" #include "DxRes.h" using D2D1::ColorF; using D2D1::Matrix3x2F; using namespace std; const UINT ControlCombox = 1; const UINT MenuLotteryStart = 2; const UINT MenuLotteryLast() { return MenuLotteryStart + GetItems().size(); } const UINT MenuStatusStart() { return MenuLotteryLast() + 1; }; const UINT MenuStatusLast() { return MenuStatusStart() + GetItems().size(); }; const UINT MenuStatusClear() { return MenuStatusLast() + 1; }; BEGIN_MESSAGE_MAP(MainWindow, CFrameWnd) ON_COMMAND_RANGE(MenuLotteryStart, MenuLotteryLast(), OnLottery) ON_COMMAND_RANGE(MenuStatusStart(), MenuStatusLast(), OnStatus) ON_COMMAND(MenuStatusClear(), OnLotteryClear) ON_WM_CREATE() ON_WM_SIZE() ON_REGISTERED_MESSAGE(AFX_WM_DRAW2D, OnDraw2D) ON_REGISTERED_MESSAGE(AFX_WM_RECREATED2DRESOURCES, CreateDeviceResources) ON_WM_KEYUP() END_MESSAGE_MAP() MainWindow::MainWindow() { Create(nullptr, L"Lottery 2017", WS_OVERLAPPEDWINDOW, { 100, 100, 800, 600 }); } void MainWindow::Update() { for (auto& scene : _scenes) { scene->Update(); } } void MainWindow::OnKeyUp(UINT nChar, UINT nRepCnt, UINT nFlags) { for (auto& scene : _scenes) { scene->KeyUp(nChar); } } void MainWindow::OnSize(UINT nType, int cx, int cy) { if (nType != SIZE_MINIMIZED && GetRenderTarget()) { _dxRes.CreateDeviceSizeResources(GetRenderTarget()); } } void MainWindow::OnLottery(UINT id) { auto itemId = id - MenuLotteryStart; auto item = GetItems()[itemId]; auto unluckyIds = GetUnluckyPersonIds(itemId); auto needCount = item.Count; if (unluckyIds.empty()) { MessageBoxW(L""); return; } if (needCount > (int)unluckyIds.size()) { CString str; str.Format(L"ʣ(%d)(%s)Ҫ(%d),ǷΪ(%d)˲?", unluckyIds.size(), item.Name, needCount, unluckyIds.size()); if (MessageBoxW(str, nullptr, MB_YESNO) == IDNO) { return; } needCount = (int)unluckyIds.size(); } auto luckyCount = GetLuckyPersonIds(itemId).size(); if (luckyCount > 0) { CString str; str.Format(L" %d ˳ %s, Ƿ?", luckyCount, item.Name); if (MessageBoxW(str, nullptr, MB_YESNO) == IDNO) { return; } } _menu.CheckMenuRadioItem(MenuLotteryStart, MenuLotteryLast(), id, MF_BYCOMMAND); _scenes.clear(); CreateScene(needCount, itemId, unluckyIds); } void MainWindow::OnStatus(UINT id) { auto itemId = id - MenuStatusStart(); auto ids = GetLuckyPersonIds(itemId); _scenes.clear(); CreateScene(-1, itemId, ids); } int MainWindow::OnCreate(LPCREATESTRUCT cs) { // setup menu _menu.LoadMenuW(IDR_MENU1); for (size_t i = 0; i < GetItems().size(); ++i) { auto item = GetItems()[i]; auto lotteryMenu = _menu.GetSubMenu(1); auto statusMenu = _menu.GetSubMenu(2); CString str; str.Format(L"%s(&%d)", item.Name, i + 1); lotteryMenu->AppendMenuW(MF_STRING, MenuLotteryStart + i, str); statusMenu->AppendMenuW(MF_STRING, MenuStatusStart() + i, str); } _menu.GetSubMenu(1)->RemoveMenu(0, 0); _menu.GetSubMenu(2)->RemoveMenu(0, 0); _menu.GetSubMenu(2)->AppendMenuW(MF_SEPARATOR); _menu.GetSubMenu(2)->AppendMenuW(MF_STRING, MenuStatusClear(), L"״̬(&C)"); _menu.CheckMenuRadioItem(MenuLotteryStart, MenuLotteryLast(), MenuLotteryStart, MF_BYCOMMAND); SetMenu(&_menu); // d2d EnableD2DSupport(); _dxRes.CreateDeviceResources(GetRenderTarget()); _dxRes.CreateDeviceSizeResources(GetRenderTarget()); CreateScene(GetItems()[0].Count, 0, GetUnluckyPersonIds(0)); return TRUE; } void MainWindow::OnLotteryClear() { if (MessageBoxW(L"ȷҪճ齱״̬?", nullptr, MB_YESNO) == IDYES) { DeleteLuckyPersons(); MessageBoxW(L"г齱״̬"); } } LRESULT MainWindow::OnDraw2D(WPARAM, LPARAM lparam) { Update(); auto target = (CHwndRenderTarget*)lparam; ASSERT_VALID(target); RECT rect; GetClientRect(&rect); CD2DRectF d2dRect{ (float)rect.left, (float)rect.top, (float)rect.right, (float)rect.bottom }; target->DrawBitmap(_dxRes.Background, d2dRect); { auto bmp = _dxRes.LotteryBitmaps[GetLotteryId()]; auto width = d2dRect.right - d2dRect.left; auto height = d2dRect.bottom - d2dRect.top; auto scale = 1.f / 3; target->SetTransform( Matrix3x2F::Scale(scale, scale) * Matrix3x2F::Translation(width * (1 - scale) - 10, height * (1 - scale) - 10) ); target->DrawBitmap(bmp, d2dRect); target->SetTransform(Matrix3x2F::Identity()); } for (auto& scene : _scenes) { scene->Render(target, &_dxRes); } return TRUE; } LRESULT MainWindow::CreateDeviceResources(WPARAM, LPARAM lparam) { _dxRes.ClearDeviceResources(); _dxRes.CreateDeviceResources((CHwndRenderTarget*)lparam); return 0; } void MainWindow::CreateScene(int count, int itemId, const std::vector<int>& personIds) { if (count == -1) { _scenes.emplace_back(make_unique<LuckyScene>(itemId, personIds)); } else if (count <= 5) { _scenes.emplace_back(make_unique<Box2dScene>(count, itemId, personIds)); } else { _scenes.emplace_back(make_unique<FlashImageScene>(count, itemId, personIds)); } } size_t MainWindow::GetLotteryId() { for (size_t i = 0; i < GetItems().size(); ++i) { if (_menu.GetMenuState(UINT(i + MenuLotteryStart), MF_BYCOMMAND) & MF_CHECKED) { return i; } } return 0; }<|endoftext|>
<commit_before>/* * Copyright 2010 MQWeb - Franky Braem * * Licensed under the EUPL, Version 1.1 or – as soon they * will be approved by the European Commission - subsequent * versions of the EUPL (the "Licence"); * You may not use this work except in compliance with the * Licence. * You may obtain a copy of the Licence at: * * http://joinup.ec.europa.eu/software/page/eupl * * Unless required by applicable law or agreed to in * writing, software distributed under the Licence is * distributed on an "AS IS" basis, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. * See the Licence for the specific language governing * permissions and limitations under the Licence. */ #include "Poco/Util/Application.h" #include "Poco/Dynamic/Struct.h" #include "Poco/JSON/Object.h" #include "MQ/MQSubsystem.h" #include "MQ/MQException.h" #include "MQ/Web/MQController.h" #include "MQ/Web/MQMapper.h" namespace MQ { namespace Web { MQController::MQController() : Controller(), _meta(new Poco::JSON::Object()), _commandServer(NULL) { set("meta", _meta); } MQController::~MQController() { } void MQController::beforeAction() { _stopwatch.start(); Poco::JSON::Object::Ptr date = new Poco::JSON::Object(); _meta->set("date", date); date->set("start", Poco::DateTimeFormatter::format(Poco::Timestamp(), Poco::DateTimeFormat::HTTP_FORMAT)); MQSubsystem& mqSystem = Poco::Util::Application::instance().getSubsystem<MQSubsystem>(); Poco::Util::LayeredConfiguration& config = Poco::Util::Application::instance().config(); _meta->set("client", mqSystem.client()); std::string qmgrName; if ( config.hasProperty("mq.web.qmgr") ) { // When a queuemanager is passed on the command line, we always // connect to this queuemanager. When the user specified another // queuemanager on the URL, it will be ignored. qmgrName = config.getString("mq.web.qmgr"); } else { const std::vector<std::string>& parameters = getParameters(); if ( parameters.size() > 0 ) { qmgrName = parameters[0]; } else if ( mqSystem.client() ) { qmgrName = config.getString("mq.web.defaultQmgr", "*"); } } Poco::SharedPtr<QueueManagerPool> qmgrPool = QueueManagerPoolCache::instance()->getQueueManagerPool(qmgrName); if ( qmgrPool.isNull() ) { setResponseStatus(Poco::Net::HTTPServerResponse::HTTP_INTERNAL_SERVER_ERROR, "Out of memory: can't create a pool for queuemanager."); return; } QueueManager::Ptr qmgr = qmgrPool->borrowObject(); if ( qmgr.isNull() ) { setResponseStatus(Poco::Net::HTTPServerResponse::HTTP_INTERNAL_SERVER_ERROR, "No queuemanager available in the pool. Check the connection pool configuration."); return; } _qmgrPoolGuard = new QueueManagerPoolGuard(qmgrPool, qmgr); _meta->set("qmgr", qmgr->name()); _meta->set("zos", qmgr->zos()); _meta->set("qmgrId", qmgr->id()); _commandServer = qmgr->commandServer(); if ( _commandServer == NULL ) { std::string qmgrConfigReplyQ = "mq.web.qmgr." + qmgrName + ".reply"; std::string replyQ; if ( config.has(qmgrConfigReplyQ) ) { replyQ = config.getString(qmgrConfigReplyQ); } else { replyQ = config.getString("mq.web.reply", "SYSTEM.DEFAULT.MODEL.QUEUE"); } _commandServer = qmgr->createCommandServer(replyQ); } if ( _commandServer != NULL ) { _meta->set("replyq", _commandServer->replyQName()); _meta->set("cmdq", _commandServer->commandQName()); } } void MQController::handleException(const MQException& mqe) { Poco::JSON::Object::Ptr error = new Poco::JSON::Object(); set("error", error); error->set("object", mqe.object()); error->set("fn", mqe.function()); switch(mqe.code()) { case MQCC_OK: error->set("code", "OK"); break; case MQCC_WARNING: error->set("code", "WARNING"); break; case MQCC_FAILED: error->set("code", "ERROR"); break; } Poco::JSON::Object::Ptr reason = new Poco::JSON::Object(); error->set("reason", reason); reason->set("code", mqe.reason()); reason->set("desc", MQMapper::getReasonString(mqe.reason())); } void MQController::afterAction() { Poco::JSON::Object::Ptr date = _meta->getObject("date"); if ( ! date.isNull() ) { date->set("end", Poco::DateTimeFormatter::format(Poco::Timestamp(), Poco::DateTimeFormat::HTTP_FORMAT)); } _stopwatch.stop(); _meta->set("elapsed", (double) _stopwatch.elapsed() / 1000000 ); Controller::afterAction(); } void MQController::handle(const std::vector<std::string>& parameters, Poco::Net::HTTPServerRequest& request, Poco::Net::HTTPServerResponse& response) { try { Controller::handle(parameters, request, response); } catch(MQException& mqe) { handleException(mqe); afterAction(); } catch(...) { //TODO: redirect to an error page } } void MQController::handleFilterForm(Poco::JSON::Object::Ptr pcfParameters) { if ( form().has("Filter") && form().has("FilterParam") && form().has("FilterValue") ) { Poco::JSON::Object::Ptr filter = new Poco::JSON::Object(); filter->set("Parameter", form().get("FilterParam")); filter->set("Operator", form().get("FilterOp", "EQ")); filter->set("FilterValue", form().get("FilterVlue")); std::string filterType = form().get("Filter"); if ( Poco::icompare(filterType, "I") == 0 ) { pcfParameters->set("IntegerFilterCommand", filter); } else if ( Poco::icompare(filterType, "S") == 0 ) { pcfParameters->set("StringFilterCommand", filter); } } } }} // namespace MQ::Web <commit_msg>Change error message when no queuemanager pool is returned<commit_after>/* * Copyright 2010 MQWeb - Franky Braem * * Licensed under the EUPL, Version 1.1 or – as soon they * will be approved by the European Commission - subsequent * versions of the EUPL (the "Licence"); * You may not use this work except in compliance with the * Licence. * You may obtain a copy of the Licence at: * * http://joinup.ec.europa.eu/software/page/eupl * * Unless required by applicable law or agreed to in * writing, software distributed under the Licence is * distributed on an "AS IS" basis, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. * See the Licence for the specific language governing * permissions and limitations under the Licence. */ #include "Poco/Util/Application.h" #include "Poco/Dynamic/Struct.h" #include "Poco/JSON/Object.h" #include "MQ/MQSubsystem.h" #include "MQ/MQException.h" #include "MQ/Web/MQController.h" #include "MQ/Web/MQMapper.h" namespace MQ { namespace Web { MQController::MQController() : Controller(), _meta(new Poco::JSON::Object()), _commandServer(NULL) { set("meta", _meta); } MQController::~MQController() { } void MQController::beforeAction() { _stopwatch.start(); Poco::JSON::Object::Ptr date = new Poco::JSON::Object(); _meta->set("date", date); date->set("start", Poco::DateTimeFormatter::format(Poco::Timestamp(), Poco::DateTimeFormat::HTTP_FORMAT)); MQSubsystem& mqSystem = Poco::Util::Application::instance().getSubsystem<MQSubsystem>(); Poco::Util::LayeredConfiguration& config = Poco::Util::Application::instance().config(); _meta->set("client", mqSystem.client()); std::string qmgrName; if ( config.hasProperty("mq.web.qmgr") ) { // When a queuemanager is passed on the command line, we always // connect to this queuemanager. When the user specified another // queuemanager on the URL, it will be ignored. qmgrName = config.getString("mq.web.qmgr"); } else { const std::vector<std::string>& parameters = getParameters(); if ( parameters.size() > 0 ) { qmgrName = parameters[0]; } else if ( mqSystem.client() ) { qmgrName = config.getString("mq.web.defaultQmgr", "*"); } } Poco::SharedPtr<QueueManagerPool> qmgrPool = QueueManagerPoolCache::instance()->getQueueManagerPool(qmgrName); if ( qmgrPool.isNull() ) { setResponseStatus(Poco::Net::HTTPServerResponse::HTTP_INTERNAL_SERVER_ERROR, "Can't create a pool for queuemanager. Check your configuration or memory limitations."); return; } QueueManager::Ptr qmgr = qmgrPool->borrowObject(); if ( qmgr.isNull() ) { setResponseStatus(Poco::Net::HTTPServerResponse::HTTP_INTERNAL_SERVER_ERROR, "No queuemanager available in the pool. Check the connection pool configuration."); return; } _qmgrPoolGuard = new QueueManagerPoolGuard(qmgrPool, qmgr); _meta->set("qmgr", qmgr->name()); _meta->set("zos", qmgr->zos()); _meta->set("qmgrId", qmgr->id()); _commandServer = qmgr->commandServer(); if ( _commandServer == NULL ) { std::string qmgrConfigReplyQ = "mq.web.qmgr." + qmgrName + ".reply"; std::string replyQ; if ( config.has(qmgrConfigReplyQ) ) { replyQ = config.getString(qmgrConfigReplyQ); } else { replyQ = config.getString("mq.web.reply", "SYSTEM.DEFAULT.MODEL.QUEUE"); } _commandServer = qmgr->createCommandServer(replyQ); } if ( _commandServer != NULL ) { _meta->set("replyq", _commandServer->replyQName()); _meta->set("cmdq", _commandServer->commandQName()); } } void MQController::handleException(const MQException& mqe) { Poco::JSON::Object::Ptr error = new Poco::JSON::Object(); set("error", error); error->set("object", mqe.object()); error->set("fn", mqe.function()); switch(mqe.code()) { case MQCC_OK: error->set("code", "OK"); break; case MQCC_WARNING: error->set("code", "WARNING"); break; case MQCC_FAILED: error->set("code", "ERROR"); break; } Poco::JSON::Object::Ptr reason = new Poco::JSON::Object(); error->set("reason", reason); reason->set("code", mqe.reason()); reason->set("desc", MQMapper::getReasonString(mqe.reason())); } void MQController::afterAction() { Poco::JSON::Object::Ptr date = _meta->getObject("date"); if ( ! date.isNull() ) { date->set("end", Poco::DateTimeFormatter::format(Poco::Timestamp(), Poco::DateTimeFormat::HTTP_FORMAT)); } _stopwatch.stop(); _meta->set("elapsed", (double) _stopwatch.elapsed() / 1000000 ); Controller::afterAction(); } void MQController::handle(const std::vector<std::string>& parameters, Poco::Net::HTTPServerRequest& request, Poco::Net::HTTPServerResponse& response) { try { Controller::handle(parameters, request, response); } catch(MQException& mqe) { handleException(mqe); afterAction(); } catch(...) { //TODO: redirect to an error page } } void MQController::handleFilterForm(Poco::JSON::Object::Ptr pcfParameters) { if ( form().has("Filter") && form().has("FilterParam") && form().has("FilterValue") ) { Poco::JSON::Object::Ptr filter = new Poco::JSON::Object(); filter->set("Parameter", form().get("FilterParam")); filter->set("Operator", form().get("FilterOp", "EQ")); filter->set("FilterValue", form().get("FilterVlue")); std::string filterType = form().get("Filter"); if ( Poco::icompare(filterType, "I") == 0 ) { pcfParameters->set("IntegerFilterCommand", filter); } else if ( Poco::icompare(filterType, "S") == 0 ) { pcfParameters->set("StringFilterCommand", filter); } } } }} // namespace MQ::Web <|endoftext|>
<commit_before>// This file is part of the dune-gdt project: // http://users.dune-project.org/projects/dune-gdt // Copyright holders: Felix Schindler // License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) #ifndef DUNE_GDT_SPACES_CONTINUOUSLAGRANGE_FEM_LOCALFUNCTIONS_HH #define DUNE_GDT_SPACES_CONTINUOUSLAGRANGE_FEM_LOCALFUNCTIONS_HH #include <memory> #include <type_traits> #include <dune/common/typetraits.hh> #include <dune/common/static_assert.hh> #include <dune/common/exceptions.hh> #include <dune/geometry/referenceelements.hh> #include <dune/geometry/genericgeometry/topologytypes.hh> #include <dune/grid/common/capabilities.hh> #if HAVE_DUNE_FEM_LOCALFUNCTIONS # include <dune/localfunctions/lagrange/equidistantpoints.hh> # include <dune/localfunctions/lagrange.hh> # include <dune/fem_localfunctions/localfunctions/transformations.hh> # include <dune/fem_localfunctions/basefunctions/genericbasefunctionsetstorage.hh> # include <dune/fem_localfunctions/basefunctionsetmap/basefunctionsetmap.hh> # include <dune/fem_localfunctions/space/genericdiscretefunctionspace.hh> #endif // HAVE_DUNE_FEM_LOCALFUNCTIONS #include "../../mapper/fem.hh" #include "../../basefunctionset/fem-localfunctions.hh" #include "base.hh" namespace Dune { namespace GDT { namespace Spaces { namespace ContinuousLagrange { #if HAVE_DUNE_FEM_LOCALFUNCTIONS // forward, to be used in the traits and to allow for specialization template< class GridPartImp, int polynomialOrder, class RangeFieldImp, int rangeDim, int rangeDimCols = 1 > class FemLocalfunctionsBased { static_assert(Dune::AlwaysFalse< GridPartImp >::value, "Untested for these dimensions!"); }; template< class GridPartImp, int polynomialOrder, class RangeFieldImp, int rangeDim, int rangeDimCols > class FemLocalfunctionsBasedTraits { public: typedef GridPartImp GridPartType; typedef typename GridPartType::GridViewType GridViewType; static const int polOrder = polynomialOrder; static_assert(polOrder >= 1, "Wrong polOrder given!"); private: typedef typename GridPartType::ctype DomainFieldType; public: static const unsigned int dimDomain = GridPartType::dimension; typedef RangeFieldImp RangeFieldType; static const unsigned int dimRange = rangeDim; static const unsigned int dimRangeCols = rangeDimCols; typedef FemLocalfunctionsBased< GridPartType, polOrder, RangeFieldType, dimRange, dimRangeCols > derived_type; private: typedef typename GridPartType::GridType GridType; static_assert(dimDomain == 1 || Dune::Capabilities::hasSingleGeometryType< GridType >::v, "This space is only implemented for fully simplicial grids!"); static_assert(dimDomain == 1 || (Dune::Capabilities::hasSingleGeometryType< GridType >::topologyId == GenericGeometry::SimplexTopology< dimDomain >::type::id), "This space is only implemented for fully simplicial grids!"); typedef FemLocalfunctionsBasedTraits< GridPartType, polOrder, RangeFieldType, dimRange, dimRangeCols > ThisType; public: typedef Dune::LagrangeLocalFiniteElement< Dune::EquidistantPointSet, dimDomain, DomainFieldType, RangeFieldType > FiniteElementType; private: typedef Dune::FemLocalFunctions::BaseFunctionSetMap< GridPartType, FiniteElementType, Dune::FemLocalFunctions::NoTransformation, Dune::FemLocalFunctions::SimpleStorage, polOrder, polOrder > BaseFunctionSetMapType; public: typedef Dune::FemLocalFunctions::DiscreteFunctionSpace< BaseFunctionSetMapType > BackendType; typedef Mapper::FemDofWrapper< typename BackendType::MapperType > MapperType; typedef BaseFunctionSet::FemLocalfunctionsWrapper< BaseFunctionSetMapType, DomainFieldType, dimDomain, RangeFieldType, dimRange, dimRangeCols > BaseFunctionSetType; typedef typename BaseFunctionSetType::EntityType EntityType; static const Stuff::Grid::ChoosePartView part_view_type = Stuff::Grid::ChoosePartView::part; static const bool needs_grid_view = false; typedef double CommunicatorType; private: template< class G, int p, class R, int r, int rC > friend class FemLocalfunctionsBased; }; // class FemLocalfunctionsBasedTraits template< class GridPartImp, int polynomialOrder, class RangeFieldImp > class FemLocalfunctionsBased< GridPartImp, polynomialOrder, RangeFieldImp, 1, 1 > : public Spaces::ContinuousLagrangeBase< FemLocalfunctionsBasedTraits< GridPartImp, polynomialOrder, RangeFieldImp, 1, 1 > , GridPartImp::dimension, RangeFieldImp, 1, 1 > { typedef Spaces::ContinuousLagrangeBase< FemLocalfunctionsBasedTraits< GridPartImp, polynomialOrder, RangeFieldImp, 1, 1 > , GridPartImp::dimension, RangeFieldImp, 1, 1 > BaseType; typedef FemLocalfunctionsBased< GridPartImp, polynomialOrder, RangeFieldImp, 1, 1 > ThisType; public: typedef FemLocalfunctionsBasedTraits< GridPartImp, polynomialOrder, RangeFieldImp, 1, 1 > Traits; typedef typename Traits::GridPartType GridPartType; typedef typename Traits::GridViewType GridViewType; static const int polOrder = Traits::polOrder; typedef typename GridPartType::ctype DomainFieldType; static const unsigned int dimDomain = GridPartType::dimension; typedef FieldVector< DomainFieldType, dimDomain > DomainType; typedef typename Traits::RangeFieldType RangeFieldType; static const unsigned int dimRange = Traits::dimRange; static const unsigned int dimRangeCols = Traits::dimRangeCols; typedef typename Traits::BackendType BackendType; typedef typename Traits::MapperType MapperType; typedef typename Traits::BaseFunctionSetType BaseFunctionSetType; typedef typename Traits::EntityType EntityType; typedef Dune::Stuff::LA::SparsityPatternDefault PatternType; private: typedef typename Traits::BaseFunctionSetMapType BaseFunctionSetMapType; public: FemLocalfunctionsBased(std::shared_ptr< const GridPartType > gridP) : gridPart_(gridP) , gridView_(std::make_shared< GridViewType >(gridPart_->gridView())) , baseFunctionSetMap_(new BaseFunctionSetMapType(*gridPart_)) , backend_(new BackendType(const_cast< GridPartType& >(*gridPart_), *baseFunctionSetMap_)) , mapper_(new MapperType(backend_->mapper())) , tmp_global_indices_(mapper_->maxNumDofs()) , communicator_(0.0) {} FemLocalfunctionsBased(const ThisType& other) : gridPart_(other.gridPart_) , gridView_(other.gridView_) , baseFunctionSetMap_(other.baseFunctionSetMap_) , backend_(other.backend_) , mapper_(other.mapper_) , tmp_global_indices_(mapper_->maxNumDofs()) , communicator_(0.0) {} ThisType& operator=(const ThisType& other) { if (this != &other) { gridPart_ = other.gridPart_; gridView_ = other.gridView_; baseFunctionSetMap_ = other.baseFunctionSetMap_; backend_ = other.backend_; mapper_ = other.mapper_; tmp_global_indices_.resize(mapper_->maxNumDofs()); } return *this; } const std::shared_ptr< const GridPartType >& grid_part() const { return gridPart_; } const std::shared_ptr< const GridViewType >& grid_view() const { return gridView_; } const BackendType& backend() const { return *backend_; } bool continuous() const { return true; } const MapperType& mapper() const { return *mapper_; } BaseFunctionSetType base_function_set(const EntityType& entity) const { return BaseFunctionSetType(*baseFunctionSetMap_, entity); } double& communicator() const { return communicator_; } private: std::shared_ptr< const GridPartType > gridPart_; std::shared_ptr< const GridViewType > gridView_; std::shared_ptr< BaseFunctionSetMapType > baseFunctionSetMap_; std::shared_ptr< const BackendType > backend_; std::shared_ptr< const MapperType > mapper_; mutable Dune::DynamicVector< size_t > tmp_global_indices_; mutable double communicator_; }; // class FemLocalfunctionsBased< ..., 1, 1 > #else // HAVE_DUNE_FEM_LOCALFUNCTIONS template< class GridPartImp, int polynomialOrder, class RangeFieldImp, int rangeDim, int rangeDimCols = 1 > class FemLocalfunctionsBased { static_assert(Dune::AlwaysFalse< GridPartImp >::value, "You are missing dune-fem-localfunctions!"); }; #endif // HAVE_DUNE_FEM_LOCALFUNCTIONS } // namespace ContinuousLagrange } // namespace Spaces } // namespace GDT } // namespace Dune #endif // DUNE_GDT_SPACES_CONTINUOUSLAGRANGE_FEM_LOCALFUNCTIONS_HH <commit_msg>[spaces.continuouslagrange] remove fem-localfunctions.hh<commit_after><|endoftext|>
<commit_before>// dune-multiscale // Copyright Holders: Patrick Henning, Rene Milk // License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) #ifndef MSFEM_ELLIPTIC_DiscreteEllipticMSFEMOperator_HH #define MSFEM_ELLIPTIC_DiscreteEllipticMSFEMOperator_HH #ifdef HAVE_CMAKE_CONFIG #include "cmake_config.h" #elif defined (HAVE_CONFIG_H) #include <config.h> #endif // ifdef HAVE_CMAKE_CONFIG #include <type_traits> #include <dune/common/fmatrix.hh> #include <dune/fem/quadrature/cachingquadrature.hh> #include <dune/fem/operator/common/operator.hh> #include <dune/fem/operator/2order/lagrangematrixsetup.hh> #include <dune/multiscale/msfem/localproblems/subgrid-list.hh> #include <dune/multiscale/msfem/localproblems/localproblemsolver.hh> #include <dune/multiscale/msfem/localproblems/localsolutionmanager.hh> #include <dune/multiscale/msfem/msfem_grid_specifier.hh> #include <dune/multiscale/msfem/msfem_traits.hh> #include <dune/multiscale/tools/misc.hh> #include <dune/multiscale/tools/discretefunctionwriter.hh> #include <dune/multiscale/hmm/cell_problem_numbering.hh> #include <dune/multiscale/problems/base.hh> #include <dune/stuff/fem/functions/checks.hh> #include <dune/stuff/fem/localmatrix_proxy.hh> namespace Dune { namespace Multiscale { namespace MsFEM { /** * \todo docme */ class DiscreteEllipticMsFEMOperator : boost::noncopyable { private: typedef CommonTraits::DiscreteFunctionType CoarseDiscreteFunction; typedef CommonTraits::DiscreteFunctionType FineDiscreteFunction; typedef MacroMicroGridSpecifier MacroMicroGridSpecifierType; typedef CommonTraits::DiffusionType DiffusionModel; typedef CommonTraits::DiffusionType Dummy; typedef typename CoarseDiscreteFunction::DiscreteFunctionSpaceType CoarseDiscreteFunctionSpace; typedef typename FineDiscreteFunction::DiscreteFunctionSpaceType FineDiscreteFunctionSpace; typedef typename FineDiscreteFunctionSpace::FunctionSpaceType FunctionSpace; typedef typename FineDiscreteFunctionSpace::GridPartType FineGridPart; typedef typename FineDiscreteFunctionSpace::GridType FineGrid; typedef typename FineDiscreteFunctionSpace::RangeFieldType RangeFieldType; typedef typename FineDiscreteFunctionSpace::DomainType DomainType; typedef typename FineDiscreteFunctionSpace::RangeType RangeType; typedef typename FineDiscreteFunctionSpace::JacobianRangeType JacobianRangeType; typedef MsFEMLocalProblemSolver MsFEMLocalProblemSolverType; static const int dimension = FineGridPart::GridType::dimension; static const int polynomialOrder = FineDiscreteFunctionSpace::polynomialOrder; typedef typename FineDiscreteFunction::LocalFunctionType FineLocalFunction; typedef typename FineDiscreteFunctionSpace::BasisFunctionSetType FineBaseFunctionSet; typedef typename FineDiscreteFunctionSpace::LagrangePointSetType FineLagrangePointSet; typedef typename FineLagrangePointSet::Codim< 1 >::SubEntityIteratorType FineFaceDofIterator; typedef typename FineGrid::Traits::LeafIndexSet FineGridLeafIndexSet; typedef typename FineDiscreteFunctionSpace::IteratorType FineIterator; typedef typename FineIterator::Entity FineEntity; typedef typename FineEntity::EntityPointer FineEntityPointer; typedef typename FineEntity::Geometry FineGeometry; typedef typename FineGridPart::IntersectionIteratorType FineIntersectionIterator; typedef typename FineIntersectionIterator::Intersection FineIntersection; typedef Fem::CachingQuadrature< FineGridPart, 0 > FineQuadrature; typedef typename CoarseDiscreteFunctionSpace::GridPartType CoarseGridPart; typedef typename CoarseDiscreteFunctionSpace::GridType CoarseGrid; typedef typename CoarseDiscreteFunction::LocalFunctionType CoarseLocalFunction; typedef typename CoarseDiscreteFunctionSpace::BasisFunctionSetType CoarseBaseFunctionSet; typedef typename CoarseDiscreteFunctionSpace::LagrangePointSetType CoarseLagrangePointSet; typedef typename CoarseLagrangePointSet::Codim< 1 >::SubEntityIteratorType CoarseFaceDofIterator; typedef typename CoarseDiscreteFunctionSpace::IteratorType CoarseIterator; typedef typename CoarseGrid::Traits::LeafIndexSet CoarseGridLeafIndexSet; typedef typename CoarseIterator::Entity CoarseEntity; typedef typename CoarseEntity::Geometry CoarseGeometry; typedef typename CoarseGridPart::IntersectionIteratorType CoarseIntersectionIterator; typedef typename CoarseIntersectionIterator::Intersection CoarseIntersection; typedef Fem::CachingQuadrature< CoarseGridPart, 0 > CoarseQuadrature; //! ---------------- typedefs for the SubgridDiscreteFunctionSpace ----------------------- // ( typedefs for the local grid and the corresponding local ('sub') )discrete space ) //! type of grid part typedef Fem::LeafGridPart< MsFEMTraits::SubGridType > SubGridPart; //! type of subgrid discrete function space typedef Fem::LagrangeDiscreteFunctionSpace< FunctionSpace, SubGridPart, 1 > // 1=POLORDER LocalDiscreteFunctionSpace; //! type of subgrid discrete function typedef Fem::AdaptiveDiscreteFunction< LocalDiscreteFunctionSpace > LocalDiscreteFunction; typedef typename LocalDiscreteFunctionSpace::IteratorType LocalGridIterator; typedef typename LocalGridIterator::Entity LocalGridEntity; typedef typename LocalGridEntity::EntityPointer LocalGridEntityPointer; typedef typename LocalDiscreteFunction::LocalFunctionType LocalGridLocalFunction; typedef typename LocalDiscreteFunctionSpace::LagrangePointSetType LGLagrangePointSet; typedef typename LocalDiscreteFunctionSpace::BasisFunctionSetType LocalGridBaseFunctionSet; typedef typename LocalGridEntity::Geometry LocalGridGeometry; typedef Fem::CachingQuadrature< SubGridPart, 0 > LocalGridQuadrature; //!----------------------------------------------------------------------------------------- public: DiscreteEllipticMsFEMOperator(MacroMicroGridSpecifierType& specifier, const CoarseDiscreteFunctionSpace& coarseDiscreteFunctionSpace, // number of layers per coarse grid entity T: U(T) is created by enrichting T with // n(T)-layers: MsFEMTraits::SubGridListType& subgrid_list, const DiffusionModel& diffusion_op); template < class SPMatrixObject > void assemble_matrix(SPMatrixObject& global_matrix) const; private: MacroMicroGridSpecifierType& specifier_; const CoarseDiscreteFunctionSpace& coarseDiscreteFunctionSpace_; MsFEMTraits::SubGridListType& subgrid_list_; const DiffusionModel& diffusion_operator_; const bool petrovGalerkin_; }; template < class SPMatrixObject > void DiscreteEllipticMsFEMOperator::assemble_matrix(SPMatrixObject& global_matrix) const { // the local problem: // Let 'T' denote a coarse grid element and // let 'U(T)' denote the environment of 'T' that corresponds with the subgrid. // if Petrov-Galerkin-MsFEM if ( petrovGalerkin_ ) DSC_LOG_INFO << "Assembling Petrov-Galerkin-MsFEM Matrix." << std::endl; else // if classical (symmetric) MsFEM DSC_LOG_INFO << "Assembling MsFEM Matrix." << std::endl; global_matrix.reserve(); global_matrix.clear(); const auto& coarseGridLeafIndexSet = coarseDiscreteFunctionSpace_.gridPart().grid().leafIndexSet(); for (const CoarseEntity& coarse_grid_entity : coarseDiscreteFunctionSpace_) { const CoarseGeometry& coarse_grid_geometry = coarse_grid_entity.geometry(); assert(coarse_grid_entity.partitionType() == InteriorEntity); const int global_index_entity = coarseGridLeafIndexSet.index(coarse_grid_entity); DSFe::LocalMatrixProxy<SPMatrixObject> local_matrix(global_matrix, coarse_grid_entity, coarse_grid_entity); const CoarseBaseFunctionSet& coarse_grid_baseSet = local_matrix.domainBasisFunctionSet(); const unsigned int numMacroBaseFunctions = coarse_grid_baseSet.size(); // Load local solutions Multiscale::MsFEM::LocalSolutionManager localSolutionManager(coarse_grid_entity, subgrid_list_, specifier_); localSolutionManager.loadLocalSolutions(); Multiscale::MsFEM::LocalSolutionManager::LocalSolutionVectorType& localSolutions = localSolutionManager.getLocalSolutions(); assert(localSolutions.size()>0); std::vector< typename CoarseBaseFunctionSet::JacobianRangeType > gradientPhi(numMacroBaseFunctions); const int localQuadratureOrder = 2 * localSolutionManager.getLocalDiscreteFunctionSpace().order() + 2; for (unsigned int i = 0; i < numMacroBaseFunctions; ++i) { for (unsigned int j = 0; j < numMacroBaseFunctions; ++j) { // iterator for the micro grid ( grid for the reference element T_0 ) for (const auto& localGridEntity : localSolutionManager.getLocalDiscreteFunctionSpace()) { // check if "localGridEntity" (which is an entity of U(T)) is in T: // ------------------------------------------------------------------- const auto& hostEntity = localSolutionManager.getSubGridPart().grid().template getHostEntity< 0 >(localGridEntity); // ignore overlay elements if (global_index_entity==subgrid_list_.getEnclosingMacroCellIndex(hostEntity)) { assert(hostEntity->partitionType() == InteriorEntity); RangeType local_integral(0.0); const LocalGridGeometry& local_grid_geometry = localGridEntity.geometry(); // higher order quadrature, since A^{\epsilon} is highly variable LocalGridQuadrature localQuadrature(localGridEntity, localQuadratureOrder); const size_t numQuadraturePoints = localQuadrature.nop(); // evaluate the jacobians of all local solutions in all quadrature points std::vector<std::vector<JacobianRangeType> > allLocalSolutionEvaluations(localSolutions.size(), std::vector<JacobianRangeType>(localQuadrature.nop(), JacobianRangeType(0.0))); for (int lsNum=0; lsNum < localSolutions.size(); ++lsNum) { LocalGridLocalFunction localFunction = localSolutions[lsNum]->localFunction(localGridEntity); localFunction.evaluateQuadrature(localQuadrature, allLocalSolutionEvaluations[lsNum]); } for (size_t localQuadraturePoint = 0; localQuadraturePoint < numQuadraturePoints; ++localQuadraturePoint) { // local (barycentric) coordinates (with respect to entity) const typename LocalGridQuadrature::CoordinateType& local_subgrid_point = localQuadrature.point( localQuadraturePoint); DomainType global_point_in_U_T = local_grid_geometry.global(local_subgrid_point); const double weight_local_quadrature = localQuadrature.weight(localQuadraturePoint) * local_grid_geometry.integrationElement( local_subgrid_point); // evaluate the jacobian of the coarse grid base set const DomainType& local_coarse_point = coarse_grid_geometry.local(global_point_in_U_T); coarse_grid_baseSet.jacobianAll(local_coarse_point, gradientPhi); // Compute the gradients of the i'th and j'th local problem solutions JacobianRangeType gradLocProbSoli(0.0),gradLocProbSolj(0.0); if (specifier_.simplexCoarseGrid()) { assert(localSolutions.size()==dimension); // ∇ Phi_H + ∇ Q( Phi_H ) = ∇ Phi_H + ∂_x1 Phi_H ∇Q( e_1 ) + ∂_x2 Phi_H ∇Q( e_2 ) for (int k = 0; k < dimension; ++k) { gradLocProbSoli.axpy(gradientPhi[i][0][k], allLocalSolutionEvaluations[k][localQuadraturePoint]); gradLocProbSolj.axpy(gradientPhi[j][0][k], allLocalSolutionEvaluations[k][localQuadraturePoint]); } } else { gradLocProbSoli = allLocalSolutionEvaluations[i][localQuadraturePoint]; gradLocProbSolj = allLocalSolutionEvaluations[j][localQuadraturePoint]; } JacobianRangeType reconstructionGradPhii(gradientPhi[i]); reconstructionGradPhii += gradLocProbSoli; JacobianRangeType reconstructionGradPhij(gradientPhi[j]); reconstructionGradPhij += gradLocProbSolj; JacobianRangeType diffusive_flux(0.0); diffusion_operator_.diffusiveFlux(global_point_in_U_T, reconstructionGradPhii, diffusive_flux); if (petrovGalerkin_) local_integral += weight_local_quadrature * (diffusive_flux[0] * gradientPhi[j][0]); else local_integral += weight_local_quadrature * (diffusive_flux[0] * reconstructionGradPhij[0]); } // add entries local_matrix.add(j, i, local_integral); } } } } } // boundary treatment //!TODO use function call const CoarseGridPart& coarseGridPart = coarseDiscreteFunctionSpace_.gridPart(); for (CoarseIterator it = coarseDiscreteFunctionSpace_.begin(); it != coarseDiscreteFunctionSpace_.end(); ++it) { const CoarseEntity& entity = *it; if ( entity.hasBoundaryIntersections() ) { auto local_matrix = global_matrix.localMatrix(entity, entity); const CoarseLagrangePointSet& lagrangePointSet = coarseDiscreteFunctionSpace_.lagrangePointSet(entity); const CoarseIntersectionIterator iend = coarseGridPart.iend(entity); for (CoarseIntersectionIterator iit = coarseGridPart.ibegin(entity); iit != iend; ++iit) { const CoarseIntersection& intersection = *iit; if ( intersection.boundary() ) { const int face = intersection.indexInInside(); const CoarseFaceDofIterator fdend = lagrangePointSet.template endSubEntity< 1 >(face); for (CoarseFaceDofIterator fdit = lagrangePointSet.template beginSubEntity< 1 >(face); fdit != fdend; ++fdit) { local_matrix.unitRow(*fdit); } } } } } } // assemble_matrix } //namespace MsFEM { } //namespace Multiscale { } //namespace Dune { #endif // #ifndef MSFEM_ELLIPTIC_DiscreteElliptic_HH <commit_msg>Rearranged loops in coarse matrix assembler to speed up<commit_after>// dune-multiscale // Copyright Holders: Patrick Henning, Rene Milk // License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) #ifndef MSFEM_ELLIPTIC_DiscreteEllipticMSFEMOperator_HH #define MSFEM_ELLIPTIC_DiscreteEllipticMSFEMOperator_HH #ifdef HAVE_CMAKE_CONFIG #include "cmake_config.h" #elif defined (HAVE_CONFIG_H) #include <config.h> #endif // ifdef HAVE_CMAKE_CONFIG #include <type_traits> #include <dune/common/fmatrix.hh> #include <dune/fem/quadrature/cachingquadrature.hh> #include <dune/fem/operator/common/operator.hh> #include <dune/fem/operator/2order/lagrangematrixsetup.hh> #include <dune/multiscale/msfem/localproblems/subgrid-list.hh> #include <dune/multiscale/msfem/localproblems/localproblemsolver.hh> #include <dune/multiscale/msfem/localproblems/localsolutionmanager.hh> #include <dune/multiscale/msfem/msfem_grid_specifier.hh> #include <dune/multiscale/msfem/msfem_traits.hh> #include <dune/multiscale/tools/misc.hh> #include <dune/multiscale/tools/discretefunctionwriter.hh> #include <dune/multiscale/hmm/cell_problem_numbering.hh> #include <dune/multiscale/problems/base.hh> #include <dune/stuff/fem/functions/checks.hh> #include <dune/stuff/fem/localmatrix_proxy.hh> namespace Dune { namespace Multiscale { namespace MsFEM { /** * \todo docme */ class DiscreteEllipticMsFEMOperator : boost::noncopyable { private: typedef CommonTraits::DiscreteFunctionType CoarseDiscreteFunction; typedef CommonTraits::DiscreteFunctionType FineDiscreteFunction; typedef MacroMicroGridSpecifier MacroMicroGridSpecifierType; typedef CommonTraits::DiffusionType DiffusionModel; typedef CommonTraits::DiffusionType Dummy; typedef typename CoarseDiscreteFunction::DiscreteFunctionSpaceType CoarseDiscreteFunctionSpace; typedef typename FineDiscreteFunction::DiscreteFunctionSpaceType FineDiscreteFunctionSpace; typedef typename FineDiscreteFunctionSpace::FunctionSpaceType FunctionSpace; typedef typename FineDiscreteFunctionSpace::GridPartType FineGridPart; typedef typename FineDiscreteFunctionSpace::GridType FineGrid; typedef typename FineDiscreteFunctionSpace::RangeFieldType RangeFieldType; typedef typename FineDiscreteFunctionSpace::DomainType DomainType; typedef typename FineDiscreteFunctionSpace::RangeType RangeType; typedef typename FineDiscreteFunctionSpace::JacobianRangeType JacobianRangeType; typedef MsFEMLocalProblemSolver MsFEMLocalProblemSolverType; static const int dimension = FineGridPart::GridType::dimension; static const int polynomialOrder = FineDiscreteFunctionSpace::polynomialOrder; typedef typename FineDiscreteFunction::LocalFunctionType FineLocalFunction; typedef typename FineDiscreteFunctionSpace::BasisFunctionSetType FineBaseFunctionSet; typedef typename FineDiscreteFunctionSpace::LagrangePointSetType FineLagrangePointSet; typedef typename FineLagrangePointSet::Codim< 1 >::SubEntityIteratorType FineFaceDofIterator; typedef typename FineGrid::Traits::LeafIndexSet FineGridLeafIndexSet; typedef typename FineDiscreteFunctionSpace::IteratorType FineIterator; typedef typename FineIterator::Entity FineEntity; typedef typename FineEntity::EntityPointer FineEntityPointer; typedef typename FineEntity::Geometry FineGeometry; typedef typename FineGridPart::IntersectionIteratorType FineIntersectionIterator; typedef typename FineIntersectionIterator::Intersection FineIntersection; typedef Fem::CachingQuadrature< FineGridPart, 0 > FineQuadrature; typedef typename CoarseDiscreteFunctionSpace::GridPartType CoarseGridPart; typedef typename CoarseDiscreteFunctionSpace::GridType CoarseGrid; typedef typename CoarseDiscreteFunction::LocalFunctionType CoarseLocalFunction; typedef typename CoarseDiscreteFunctionSpace::BasisFunctionSetType CoarseBaseFunctionSet; typedef typename CoarseDiscreteFunctionSpace::LagrangePointSetType CoarseLagrangePointSet; typedef typename CoarseLagrangePointSet::Codim< 1 >::SubEntityIteratorType CoarseFaceDofIterator; typedef typename CoarseDiscreteFunctionSpace::IteratorType CoarseIterator; typedef typename CoarseGrid::Traits::LeafIndexSet CoarseGridLeafIndexSet; typedef typename CoarseIterator::Entity CoarseEntity; typedef typename CoarseEntity::Geometry CoarseGeometry; typedef typename CoarseGridPart::IntersectionIteratorType CoarseIntersectionIterator; typedef typename CoarseIntersectionIterator::Intersection CoarseIntersection; typedef Fem::CachingQuadrature< CoarseGridPart, 0 > CoarseQuadrature; //! ---------------- typedefs for the SubgridDiscreteFunctionSpace ----------------------- // ( typedefs for the local grid and the corresponding local ('sub') )discrete space ) //! type of grid part typedef Fem::LeafGridPart< MsFEMTraits::SubGridType > SubGridPart; //! type of subgrid discrete function space typedef Fem::LagrangeDiscreteFunctionSpace< FunctionSpace, SubGridPart, 1 > // 1=POLORDER LocalDiscreteFunctionSpace; //! type of subgrid discrete function typedef Fem::AdaptiveDiscreteFunction< LocalDiscreteFunctionSpace > LocalDiscreteFunction; typedef typename LocalDiscreteFunctionSpace::IteratorType LocalGridIterator; typedef typename LocalGridIterator::Entity LocalGridEntity; typedef typename LocalGridEntity::EntityPointer LocalGridEntityPointer; typedef typename LocalDiscreteFunction::LocalFunctionType LocalGridLocalFunction; typedef typename LocalDiscreteFunctionSpace::LagrangePointSetType LGLagrangePointSet; typedef typename LocalDiscreteFunctionSpace::BasisFunctionSetType LocalGridBaseFunctionSet; typedef typename LocalGridEntity::Geometry LocalGridGeometry; typedef Fem::CachingQuadrature< SubGridPart, 0 > LocalGridQuadrature; //!----------------------------------------------------------------------------------------- public: DiscreteEllipticMsFEMOperator(MacroMicroGridSpecifierType& specifier, const CoarseDiscreteFunctionSpace& coarseDiscreteFunctionSpace, // number of layers per coarse grid entity T: U(T) is created by enrichting T with // n(T)-layers: MsFEMTraits::SubGridListType& subgrid_list, const DiffusionModel& diffusion_op); template < class SPMatrixObject > void assemble_matrix(SPMatrixObject& global_matrix) const; private: MacroMicroGridSpecifierType& specifier_; const CoarseDiscreteFunctionSpace& coarseDiscreteFunctionSpace_; MsFEMTraits::SubGridListType& subgrid_list_; const DiffusionModel& diffusion_operator_; const bool petrovGalerkin_; }; template < class SPMatrixObject > void DiscreteEllipticMsFEMOperator::assemble_matrix(SPMatrixObject& global_matrix) const { // the local problem: // Let 'T' denote a coarse grid element and // let 'U(T)' denote the environment of 'T' that corresponds with the subgrid. // if Petrov-Galerkin-MsFEM if ( petrovGalerkin_ ) DSC_LOG_INFO << "Assembling Petrov-Galerkin-MsFEM Matrix." << std::endl; else // if classical (symmetric) MsFEM DSC_LOG_INFO << "Assembling MsFEM Matrix." << std::endl; global_matrix.reserve(); global_matrix.clear(); const auto& coarseGridLeafIndexSet = coarseDiscreteFunctionSpace_.gridPart().grid().leafIndexSet(); for (const CoarseEntity& coarse_grid_entity : coarseDiscreteFunctionSpace_) { const CoarseGeometry& coarse_grid_geometry = coarse_grid_entity.geometry(); assert(coarse_grid_entity.partitionType() == InteriorEntity); const int global_index_entity = coarseGridLeafIndexSet.index(coarse_grid_entity); DSFe::LocalMatrixProxy<SPMatrixObject> local_matrix(global_matrix, coarse_grid_entity, coarse_grid_entity); const CoarseBaseFunctionSet& coarse_grid_baseSet = local_matrix.domainBasisFunctionSet(); const unsigned int numMacroBaseFunctions = coarse_grid_baseSet.size(); // Load local solutions Multiscale::MsFEM::LocalSolutionManager localSolutionManager(coarse_grid_entity, subgrid_list_, specifier_); localSolutionManager.loadLocalSolutions(); Multiscale::MsFEM::LocalSolutionManager::LocalSolutionVectorType& localSolutions = localSolutionManager.getLocalSolutions(); assert(localSolutions.size()>0); std::vector< typename CoarseBaseFunctionSet::JacobianRangeType > gradientPhi(numMacroBaseFunctions); const int localQuadratureOrder = 2 * localSolutionManager.getLocalDiscreteFunctionSpace().order() + 2; // iterator for the micro grid ( grid for the reference element T_0 ) for (const auto& localGridEntity : localSolutionManager.getLocalDiscreteFunctionSpace()) { // check if "localGridEntity" (which is an entity of U(T)) is in T: // ------------------------------------------------------------------- const auto& hostEntity = localSolutionManager.getSubGridPart().grid().template getHostEntity< 0 >(localGridEntity); // ignore overlay elements if (global_index_entity==subgrid_list_.getEnclosingMacroCellIndex(hostEntity)) { assert(hostEntity->partitionType() == InteriorEntity); const LocalGridGeometry& local_grid_geometry = localGridEntity.geometry(); // higher order quadrature, since A^{\epsilon} is highly variable LocalGridQuadrature localQuadrature(localGridEntity, localQuadratureOrder); const size_t numQuadraturePoints = localQuadrature.nop(); // evaluate the jacobians of all local solutions in all quadrature points std::vector<std::vector<JacobianRangeType> > allLocalSolutionEvaluations(localSolutions.size(), std::vector<JacobianRangeType>(localQuadrature.nop(), JacobianRangeType(0.0))); for (int lsNum=0; lsNum < localSolutions.size(); ++lsNum) { LocalGridLocalFunction localFunction = localSolutions[lsNum]->localFunction(localGridEntity); localFunction.evaluateQuadrature(localQuadrature, allLocalSolutionEvaluations[lsNum]); } for (size_t localQuadraturePoint = 0; localQuadraturePoint < numQuadraturePoints; ++localQuadraturePoint) { // local (barycentric) coordinates (with respect to entity) const typename LocalGridQuadrature::CoordinateType& local_subgrid_point = localQuadrature.point( localQuadraturePoint); DomainType global_point_in_U_T = local_grid_geometry.global(local_subgrid_point); const double weight_local_quadrature = localQuadrature.weight(localQuadraturePoint) * local_grid_geometry.integrationElement( local_subgrid_point); // evaluate the jacobian of the coarse grid base set const DomainType& local_coarse_point = coarse_grid_geometry.local(global_point_in_U_T); coarse_grid_baseSet.jacobianAll(local_coarse_point, gradientPhi); for (unsigned int i = 0; i < numMacroBaseFunctions; ++i) { for (unsigned int j = 0; j < numMacroBaseFunctions; ++j) { RangeType local_integral(0.0); // Compute the gradients of the i'th and j'th local problem solutions JacobianRangeType gradLocProbSoli(0.0),gradLocProbSolj(0.0); if (specifier_.simplexCoarseGrid()) { assert(localSolutions.size()==dimension); // ∇ Phi_H + ∇ Q( Phi_H ) = ∇ Phi_H + ∂_x1 Phi_H ∇Q( e_1 ) + ∂_x2 Phi_H ∇Q( e_2 ) for (int k = 0; k < dimension; ++k) { gradLocProbSoli.axpy(gradientPhi[i][0][k], allLocalSolutionEvaluations[k][localQuadraturePoint]); gradLocProbSolj.axpy(gradientPhi[j][0][k], allLocalSolutionEvaluations[k][localQuadraturePoint]); } } else { gradLocProbSoli = allLocalSolutionEvaluations[i][localQuadraturePoint]; gradLocProbSolj = allLocalSolutionEvaluations[j][localQuadraturePoint]; } JacobianRangeType reconstructionGradPhii(gradientPhi[i]); reconstructionGradPhii += gradLocProbSoli; JacobianRangeType reconstructionGradPhij(gradientPhi[j]); reconstructionGradPhij += gradLocProbSolj; JacobianRangeType diffusive_flux(0.0); diffusion_operator_.diffusiveFlux(global_point_in_U_T, reconstructionGradPhii, diffusive_flux); if (petrovGalerkin_) local_integral += weight_local_quadrature * (diffusive_flux[0] * gradientPhi[j][0]); else local_integral += weight_local_quadrature * (diffusive_flux[0] * reconstructionGradPhij[0]); // add entries local_matrix.add(j, i, local_integral); } } } } } } // boundary treatment //!TODO use function call const CoarseGridPart& coarseGridPart = coarseDiscreteFunctionSpace_.gridPart(); for (CoarseIterator it = coarseDiscreteFunctionSpace_.begin(); it != coarseDiscreteFunctionSpace_.end(); ++it) { const CoarseEntity& entity = *it; if ( entity.hasBoundaryIntersections() ) { auto local_matrix = global_matrix.localMatrix(entity, entity); const CoarseLagrangePointSet& lagrangePointSet = coarseDiscreteFunctionSpace_.lagrangePointSet(entity); const CoarseIntersectionIterator iend = coarseGridPart.iend(entity); for (CoarseIntersectionIterator iit = coarseGridPart.ibegin(entity); iit != iend; ++iit) { const CoarseIntersection& intersection = *iit; if ( intersection.boundary() ) { const int face = intersection.indexInInside(); const CoarseFaceDofIterator fdend = lagrangePointSet.template endSubEntity< 1 >(face); for (CoarseFaceDofIterator fdit = lagrangePointSet.template beginSubEntity< 1 >(face); fdit != fdend; ++fdit) { local_matrix.unitRow(*fdit); } } } } } } // assemble_matrix } //namespace MsFEM { } //namespace Multiscale { } //namespace Dune { #endif // #ifndef MSFEM_ELLIPTIC_DiscreteElliptic_HH <|endoftext|>
<commit_before>/////////////////////////////////////////////////////////////////////////////// // This source file is part of Hect. // // Copyright (c) 2016 Colin Hill // // 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 "Hect/Core/Exception.h" namespace hect { template <typename T> Optional<T>::Optional() { } template <typename T> Optional<T>::Optional(const T& value) : _hasValue(true), _value(value) { } template <typename T> Optional<T>::Optional(const Optional<T>& optional) : _hasValue(optional._hasValue), _value(optional._value) { } template <typename T> Optional<T>::Optional(Optional<T>&& optional) : _hasValue(optional._hasValue), _value(std::move(optional._value)) { } template <typename T> bool Optional<T>::hasValue() const { return _hasValue; } template <typename T> T& Optional<T>::value() { if (!_hasValue) { throw InvalidOperation("No value in optional container"); } return _value; } template <typename T> const T& Optional<T>::value() const { return const_cast<Optional<T>*>(this)->value(); } template <typename T> Optional<T>::operator bool() const { return hasValue(); } template <typename T> T& Optional<T>::operator*() { return value(); } template <typename T> const T& Optional<T>::operator*() const { return value(); } template <typename T> T* Optional<T>::operator->() { return &value(); } template <typename T> const T* Optional<T>::operator->() const { return &value(); } template <typename T> typename Optional<T>& Optional<T>::operator=(const T& value) { _hasValue = true; _value = value; return *this; } template <typename T> typename Optional<T>& Optional<T>::operator=(T&& value) { _hasValue = true; _value = std::move(value); return *this; } template <typename T> typename Optional<T>& Optional<T>::operator=(const Optional<T>& optional) { _hasValue = optional._hasValue; if (_hasValue) { _value = optional._value; } return *this; } template <typename T> typename Optional<T>& Optional<T>::operator=(Optional<T>&& optional) { _hasValue = optional._hasValue; if (_hasValue) { _value = std::move(optional._value); } return *this; } } <commit_msg>Attempt to fix GCC/Clang warning<commit_after>/////////////////////////////////////////////////////////////////////////////// // This source file is part of Hect. // // Copyright (c) 2016 Colin Hill // // 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 "Hect/Core/Exception.h" namespace hect { template <typename T> Optional<T>::Optional() { } template <typename T> Optional<T>::Optional(const T& value) : _hasValue(true), _value(value) { } template <typename T> Optional<T>::Optional(const Optional<T>& optional) : _hasValue(optional._hasValue), _value(optional._value) { } template <typename T> Optional<T>::Optional(Optional<T>&& optional) : _hasValue(optional._hasValue), _value(std::move(optional._value)) { } template <typename T> bool Optional<T>::hasValue() const { return _hasValue; } template <typename T> T& Optional<T>::value() { if (!_hasValue) { throw InvalidOperation("No value in optional container"); } return _value; } template <typename T> const T& Optional<T>::value() const { return const_cast<Optional<T>*>(this)->value(); } template <typename T> Optional<T>::operator bool() const { return hasValue(); } template <typename T> T& Optional<T>::operator*() { return value(); } template <typename T> const T& Optional<T>::operator*() const { return value(); } template <typename T> T* Optional<T>::operator->() { return &value(); } template <typename T> const T* Optional<T>::operator->() const { return &value(); } template <typename T> Optional<T>& Optional<T>::operator=(const T& value) { _hasValue = true; _value = value; return *this; } template <typename T> Optional<T>& Optional<T>::operator=(T&& value) { _hasValue = true; _value = std::move(value); return *this; } template <typename T> Optional<T>& Optional<T>::operator=(const Optional<T>& optional) { _hasValue = optional._hasValue; if (_hasValue) { _value = optional._value; } return *this; } template <typename T> Optional<T>& Optional<T>::operator=(Optional<T>&& optional) { _hasValue = optional._hasValue; if (_hasValue) { _value = std::move(optional._value); } return *this; } } <|endoftext|>
<commit_before>/* * Copyright (c) 2015, 2016, 2017, Intel Corporation * * 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 Intel Corporation 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 LOG OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef CIRCULARBUFFER_HPP_INCLUDE #define CIRCULARBUFFER_HPP_INCLUDE #include <stdlib.h> #include <vector> #include "Exception.hpp" namespace geopm { /// @brief Templated container for a circular buffer implementation. /// /// The CircularBuffer container implements a fixed size buffer. Once /// at capacity, any new insertions cause the oldest entry to be dropped. template <class type> class ICircularBuffer { public: ICircularBuffer() {} virtual ~ICircularBuffer() {} /// @brief Re-size the circular buffer. /// /// Resets the capacity of the circular buffer without /// modifying it's current contents. /// /// @param [in] size Requested capacity for the buffer. virtual void set_capacity(const unsigned int size) = 0; /// @brief Clears all entries from the buffer. virtual void clear(void) = 0; /// @brief Size of the buffer contents. /// /// Returns the number of items in the buffer. This /// value will be less than or equal to the current /// capacity of the buffer. // /// @return Size of the buffer contents. virtual int size(void) const = 0; /// @brief Capacity of the buffer. /// /// Returns the current size of the circular buffer at /// the time of the call. /// /// @return Capacity of the buffer. virtual int capacity(void) const = 0; /// @brief Insert a value into the buffer. /// /// If the buffer is not full, the new value is simply /// added to the buffer. It the buffer is at capacity, /// The head of the buffer is dropped and moved to the /// next oldest entry and the new value is then inserted /// at the end of the buffer. /// /// @param [in] value The value to be inserted. virtual void insert(const type value) = 0; /// @brief Returns a constant refernce to the value from the buffer. /// /// Accesses the contents of the circular buffer /// at a particular index. Valid indices range /// from 0 to [size-1]. Where size is the number /// of valid entries in the buffer. An attempt to /// retrieve a value for an out of bound index a /// geopm::Exception will be thrown with an /// error_value() of GEOPM_ERROR_INVALID. /// /// @param [in] index Buffer index to retrieve. /// /// @return Value from the specified buffer index. virtual const type& value(const unsigned int index) const = 0; }; /// @brief Templated container for a circular buffer implementation. /// /// The CircularBuffer container implements a fixed size buffer. Once /// at capacity, any new insertions cause the oldest entry to be dropped. template <class type> class CircularBuffer : public ICircularBuffer <type> { public: /// @brief Constructor for the CircularBuffer template. /// /// Creates an empty circular buffer with a set capacity. /// /// @param [in] size Requested capacity for the buffer. CircularBuffer(unsigned int size); /// @brief CircularBuffer destructor, virtual virtual ~CircularBuffer(); void set_capacity(const unsigned int size); void clear(void); int size(void) const; int capacity(void) const; void insert(const type value); const type& value(const unsigned int index) const; protected: /// @brief Vector holding the buffer data. std::vector<type> m_buffer; /// @brief Index of the current head of the buffer. unsigned long m_head; /// @brief The number of valid entries in the buffer. unsigned long m_count; /// @brief Current capacity of the buffer. size_t m_max_size; }; template <class type> CircularBuffer<type>::CircularBuffer(unsigned int size) : m_buffer(size) , m_head(0) , m_count(0) , m_max_size(size) { } template <class type> CircularBuffer<type>::~CircularBuffer() { } template <class type> int CircularBuffer<type>::size() const { return m_count; } template <class type> int CircularBuffer<type>::capacity() const { return m_max_size; } template <class type> void CircularBuffer<type>::clear() { m_head = 0; m_count = 0; } template <class type> void CircularBuffer<type>::set_capacity(const unsigned int size) { if (size < m_count) { int size_diff = m_count - size; std::vector<type> temp; //Copy newest data into temporary vector for (unsigned int i = m_head + size_diff; i < ((m_head + m_count) % m_max_size); i = ((i + 1) % m_max_size)) { temp.push_back(m_buffer[i]); } //now re-size and swap out with tmp vector data m_buffer.resize(size); m_buffer.swap(temp); m_count = size; } else { m_buffer.resize(size); } m_head = 0; m_max_size = size; } template <class type> void CircularBuffer<type>::insert(const type value) { if (m_max_size < 1) { throw Exception("CircularBuffer::insert(): Cannot insert into a buffer of 0 size", GEOPM_ERROR_RUNTIME, __FILE__, __LINE__); } if (m_count < m_max_size) { m_buffer[m_count] = value; m_count++; } else { m_buffer[m_head] = value; m_head = ((m_head + 1) % m_max_size); } } template <class type> const type& CircularBuffer<type>::value(const unsigned int index) const { if (index >= m_count) { throw Exception("CircularBuffer::value(): index is out of bounds", GEOPM_ERROR_INVALID, __FILE__, __LINE__); } return m_buffer[(m_head + index) % m_max_size]; } } #endif <commit_msg>Update doxygen comments for CircularBuffer.<commit_after>/* * Copyright (c) 2015, 2016, 2017, Intel Corporation * * 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 Intel Corporation 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 LOG OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef CIRCULARBUFFER_HPP_INCLUDE #define CIRCULARBUFFER_HPP_INCLUDE #include <stdlib.h> #include <vector> #include "Exception.hpp" namespace geopm { /// @brief Templated container for a circular buffer implementation. /// /// The CircularBuffer container implements a fixed size buffer. Once /// at capacity, any new insertions cause the oldest entry to be dropped. template <class type> class ICircularBuffer { public: ICircularBuffer() {} virtual ~ICircularBuffer() {} /// @brief Re-size the circular buffer. /// /// Resets the capacity of the circular buffer without /// modifying its current contents. /// /// @param [in] size Requested capacity for the buffer. virtual void set_capacity(const unsigned int size) = 0; /// @brief Clears all entries from the buffer. virtual void clear(void) = 0; /// @brief Size of the buffer contents. /// /// Returns the number of items in the buffer. This /// value will be less than or equal to the current /// capacity of the buffer. // /// @return Size of the buffer contents. virtual int size(void) const = 0; /// @brief Capacity of the buffer. /// /// Returns the current size of the circular buffer at /// the time of the call. /// /// @return Capacity of the buffer. virtual int capacity(void) const = 0; /// @brief Insert a value into the buffer. /// /// If the buffer is not full, the new value is simply /// added to the buffer. It the buffer is at capacity, /// The head of the buffer is dropped and moved to the /// next oldest entry and the new value is then inserted /// at the end of the buffer. /// /// @param [in] value The value to be inserted. virtual void insert(const type value) = 0; /// @brief Returns a constant reference to the value from the buffer. /// /// Accesses the contents of the circular buffer /// at a particular index. Valid indices range /// from 0 to [size-1]. Where size is the number /// of valid entries in the buffer. An attempt to /// retrieve a value for an out of bound index /// will throw a geopm::Exception with an /// error_value() of GEOPM_ERROR_INVALID. /// /// @param [in] index Buffer index to retrieve. /// /// @return Value from the specified buffer index. virtual const type& value(const unsigned int index) const = 0; }; /// @brief Templated container for a circular buffer implementation. /// /// The CircularBuffer container implements a fixed size buffer. Once /// at capacity, any new insertions cause the oldest entry to be dropped. template <class type> class CircularBuffer : public ICircularBuffer <type> { public: /// @brief Constructor for the CircularBuffer template. /// /// Creates an empty circular buffer with a set capacity. /// /// @param [in] size Requested capacity for the buffer. CircularBuffer(unsigned int size); /// @brief CircularBuffer destructor, virtual virtual ~CircularBuffer(); void set_capacity(const unsigned int size); void clear(void); int size(void) const; int capacity(void) const; void insert(const type value); const type& value(const unsigned int index) const; protected: /// @brief Vector holding the buffer data. std::vector<type> m_buffer; /// @brief Index of the current head of the buffer. unsigned long m_head; /// @brief The number of valid entries in the buffer. unsigned long m_count; /// @brief Current capacity of the buffer. size_t m_max_size; }; template <class type> CircularBuffer<type>::CircularBuffer(unsigned int size) : m_buffer(size) , m_head(0) , m_count(0) , m_max_size(size) { } template <class type> CircularBuffer<type>::~CircularBuffer() { } template <class type> int CircularBuffer<type>::size() const { return m_count; } template <class type> int CircularBuffer<type>::capacity() const { return m_max_size; } template <class type> void CircularBuffer<type>::clear() { m_head = 0; m_count = 0; } template <class type> void CircularBuffer<type>::set_capacity(const unsigned int size) { if (size < m_count) { int size_diff = m_count - size; std::vector<type> temp; //Copy newest data into temporary vector for (unsigned int i = m_head + size_diff; i < ((m_head + m_count) % m_max_size); i = ((i + 1) % m_max_size)) { temp.push_back(m_buffer[i]); } //now re-size and swap out with tmp vector data m_buffer.resize(size); m_buffer.swap(temp); m_count = size; } else { m_buffer.resize(size); } m_head = 0; m_max_size = size; } template <class type> void CircularBuffer<type>::insert(const type value) { if (m_max_size < 1) { throw Exception("CircularBuffer::insert(): Cannot insert into a buffer of 0 size", GEOPM_ERROR_RUNTIME, __FILE__, __LINE__); } if (m_count < m_max_size) { m_buffer[m_count] = value; m_count++; } else { m_buffer[m_head] = value; m_head = ((m_head + 1) % m_max_size); } } template <class type> const type& CircularBuffer<type>::value(const unsigned int index) const { if (index >= m_count) { throw Exception("CircularBuffer::value(): index is out of bounds", GEOPM_ERROR_INVALID, __FILE__, __LINE__); } return m_buffer[(m_head + index) % m_max_size]; } } #endif <|endoftext|>
<commit_before>// // ZX8081.cpp // Clock Signal // // Created by Thomas Harte on 04/06/2017. // Copyright © 2017 Thomas Harte. All rights reserved. // #include "ZX8081.hpp" using namespace ZX8081; Machine::Machine() : vertical_sync_(false), ram_(65536) { // run at 3.25 Mhz set_clock_rate(3250000); } int Machine::perform_machine_cycle(const CPU::Z80::MachineCycle &cycle) { cycles_since_display_update_ += cycle.length; uint8_t r; switch(cycle.operation) { case CPU::Z80::BusOperation::Output: if(*cycle.address == 0xff) { update_display(); set_sync(false); } break; case CPU::Z80::BusOperation::Input: if(*cycle.address == 0xfe) { update_display(); set_sync(true); } break; case CPU::Z80::BusOperation::Interrupt: *cycle.value = 0xff; break; case CPU::Z80::BusOperation::ReadOpcode: r = (uint8_t)get_value_of_register(CPU::Z80::Register::R); set_interrupt_line(!(r & 0x40)); case CPU::Z80::BusOperation::Read: if(*cycle.address < rom_.size()) *cycle.value = rom_[*cycle.address]; else { uint8_t value = ram_[*cycle.address]; if(*cycle.address > 32768 && !(value & 0x40) && cycle.operation == CPU::Z80::BusOperation::ReadOpcode) { // TODO: character lookup. output_byte(value); *cycle.value = 0; } else *cycle.value = value; } break; case CPU::Z80::BusOperation::Write: ram_[*cycle.address] = *cycle.value; break; default: break; } return 0; } void Machine::setup_output(float aspect_ratio) { crt_.reset(new Outputs::CRT::CRT(207, 1, Outputs::CRT::DisplayType::PAL50, 1)); crt_->set_rgb_sampling_function( "vec3 rgb_sample(usampler2D sampler, vec2 coordinate, vec2 icoordinate)" "{" "return vec3(1.0);" "}"); } void Machine::flush() { update_display(); } void Machine::close_output() { } std::shared_ptr<Outputs::CRT::CRT> Machine::get_crt() { return crt_; } std::shared_ptr<Outputs::Speaker> Machine::get_speaker() { return nullptr; } void Machine::run_for_cycles(int number_of_cycles) { } void Machine::configure_as_target(const StaticAnalyser::Target &target) { // TODO: pay attention to the target rom_ = zx80_rom_; } void Machine::set_rom(ROMType type, std::vector<uint8_t> data) { switch(type) { case ZX80: zx80_rom_ = data; break; case ZX81: zx81_rom_ = data; break; } } #pragma mark - Video void Machine::update_display() { // TODO. cycles_since_display_update_ = 0; } void Machine::set_sync(bool sync) { } void Machine::output_byte(uint8_t byte) { } <commit_msg>Wired up actually to run.<commit_after>// // ZX8081.cpp // Clock Signal // // Created by Thomas Harte on 04/06/2017. // Copyright © 2017 Thomas Harte. All rights reserved. // #include "ZX8081.hpp" using namespace ZX8081; Machine::Machine() : vertical_sync_(false), ram_(65536) { // run at 3.25 Mhz set_clock_rate(3250000); } int Machine::perform_machine_cycle(const CPU::Z80::MachineCycle &cycle) { cycles_since_display_update_ += cycle.length; uint8_t r; switch(cycle.operation) { case CPU::Z80::BusOperation::Output: if(*cycle.address == 0xff) { update_display(); set_sync(false); } break; case CPU::Z80::BusOperation::Input: if(*cycle.address == 0xfe) { update_display(); set_sync(true); } break; case CPU::Z80::BusOperation::Interrupt: *cycle.value = 0xff; break; case CPU::Z80::BusOperation::ReadOpcode: r = (uint8_t)get_value_of_register(CPU::Z80::Register::R); set_interrupt_line(!(r & 0x40)); case CPU::Z80::BusOperation::Read: if(*cycle.address < rom_.size()) *cycle.value = rom_[*cycle.address]; else { uint8_t value = ram_[*cycle.address]; if(*cycle.address > 32768 && !(value & 0x40) && cycle.operation == CPU::Z80::BusOperation::ReadOpcode) { // TODO: character lookup. output_byte(value); *cycle.value = 0; } else *cycle.value = value; } break; case CPU::Z80::BusOperation::Write: ram_[*cycle.address] = *cycle.value; break; default: break; } return 0; } void Machine::setup_output(float aspect_ratio) { crt_.reset(new Outputs::CRT::CRT(207, 1, Outputs::CRT::DisplayType::PAL50, 1)); crt_->set_rgb_sampling_function( "vec3 rgb_sample(usampler2D sampler, vec2 coordinate, vec2 icoordinate)" "{" "return vec3(1.0);" "}"); } void Machine::flush() { update_display(); } void Machine::close_output() { } std::shared_ptr<Outputs::CRT::CRT> Machine::get_crt() { return crt_; } std::shared_ptr<Outputs::Speaker> Machine::get_speaker() { return nullptr; } void Machine::run_for_cycles(int number_of_cycles) { CPU::Z80::Processor<Machine>::run_for_cycles(number_of_cycles); } void Machine::configure_as_target(const StaticAnalyser::Target &target) { // TODO: pay attention to the target rom_ = zx80_rom_; } void Machine::set_rom(ROMType type, std::vector<uint8_t> data) { switch(type) { case ZX80: zx80_rom_ = data; break; case ZX81: zx81_rom_ = data; break; } } #pragma mark - Video void Machine::update_display() { // TODO. cycles_since_display_update_ = 0; } void Machine::set_sync(bool sync) { } void Machine::output_byte(uint8_t byte) { } <|endoftext|>
<commit_before> #include "potentialfunctioncbspl.h" PotentialFunctionCBSPL::PotentialFunctionCBSPL(const int nlam_, const int ncutcoeff_, const double min_, const double max_) : PotentialFunction(nlam_,min_,max_) { /* Here nlam_ is the total number of coeff values that are to be optimized * To ensure that potential and force go to zero smoothly near cut-off, * as suggested in Ref. PCCP, 11, 1901, 2009, coeff values leading up to * cut-off and beyond take a value of zero. * * Since region less than rmin is not sampled sufficiently for stability * first _nexcl coefficients are not optimized instead their values are * extrapolated from first statistically significant knot values near rmin */ // number of break points = _lam.size() - 2 _nbreak = _lam.size() - 2; double _dr = ( _cut_off )/( double (_nbreak - 1) ); // break point locations // since ncoeff = nbreak +2 , r values for last two coefficients are also // computed _rbreak.resize(_lam.size(),false); _rbreak.clear(); for( int i = 0; i < _lam.size(); i++) _rbreak(i) = i*_dr; _nexcl = min( int( ( _min )/_dr ), _nbreak - 2 ); _ncutcoeff = ncutcoeff_; _M.resize(4,4,false); _M.clear(); _M(0,0) = 1.0; _M(0,1) = 4.0; _M(0,2) = 1.0; _M(0,3) = 0.0; _M(1,0) = -3.0; _M(1,1) = 0.0; _M(1,2) = 3.0; _M(1,3) = 0.0; _M(2,0) = 3.0; _M(2,1) = -6.0; _M(2,2) = 3.0; _M(2,3) = 0.0; _M(3,0) = -1.0; _M(3,1) = 3.0; _M(3,2) = -3.0; _M(3,3) = 1.0; _M /= 6.0; } int PotentialFunctionCBSPL::getOptParamSize() const { return _lam.size() - _nexcl - _ncutcoeff; } void PotentialFunctionCBSPL::setParam(string filename) { Table param; param.Load(filename); if( param.size() != _lam.size()) { throw std::runtime_error("Potential parameters size mismatch!\n" "Check input parameter file \"" + filename + "\" \nThere should be " + boost::lexical_cast<string>( _lam.size() ) + " parameters"); } else { for( int i = 0; i < _lam.size(); i++){ _rbreak(i) = param.x(i); _lam(i) = param.y(i); } } } void PotentialFunctionCBSPL::SaveParam(const string& filename){ Table param; param.SetHasYErr(false); param.resize(_lam.size(), false); // extrapolate first _nexcl knot values using exponential extrapolation // u(r) = a * exp( b * r) // a = u0 * exp ( - m * r0/u0 ) // b = m/u0 // m = (u1-u0)/(r1-r0) double u0 = _lam(_nexcl); double r0 = _rbreak(_nexcl); double m = ( _lam(_nexcl+1) - _lam(_nexcl) ) / ( _rbreak(_nexcl+1) - _rbreak(_nexcl) ); double a0 = u0 * exp ( - m * r0/u0 ); double b = m/u0; for (int i = 0; i < _nexcl; i++){ double r = _rbreak(i); double u = a * exp( b * r); _lam(i) = u; param.set(i, r, u, 'o'); } for (int i = _nexcl; i < _lam.size(); i++){ param.set(i, _rbreak(i), _lam(i), 'i'); } param.Save(filename); } double PotentialFunctionCBSPL::CalculateF (const double r) const { if( r >= _min && r <= _cut_off){ ub::vector<double> R; ub::vector<double> B; int indx = min( int( r /_dr ) , _nbreak-2 ); double rk = indx*_dr; double t = ( r - rk)/_dr; R.resize(4,false); R.clear(); R(0) = 1.0; R(1) = t; R(2) = t*t; R(3) = t*t*t; ub::vector<double> RM = ub::prod(R,_M); B.resize(4,false); B.clear(); B(0) = _lam(indx); B(1) = _lam(indx+1); B(2) = _lam(indx+2); B(3) = _lam(indx+3); double u = ub::inner_prod(B,RM); return u; } else { return 0.0; } } // calculate first derivative w.r.t. ith parameter double PotentialFunctionCBSPL::CalculateDF(const int i, const double r) const{ // since first _nexcl parameters are not optimized for stability reasons //i = i + _nexcl; if ( r >= _min && r <= _cut_off ) { int indx = min( int( ( r )/_dr ), _nbreak-2 ); if ( i + _nexcl >= indx && i + _nexcl <= indx+3 ){ ub::vector<double> R; double rk = indx*_dr; double t = ( r - rk)/_dr; R.resize(4,false); R.clear(); R(0) = 1.0; R(1) = t; R(2) = t*t; R(3) = t*t*t; ub::vector<double> RM = ub::prod(R,_M); return RM(i + _nexcl-indx); }else{ return 0.0; } } else { return 0; } } // calculate second derivative w.r.t. ith parameter double PotentialFunctionCBSPL::CalculateD2F(const int i, const int j, const double r) const { // for cubic B-SPlines D2F is zero for all lamdas return 0.0; } <commit_msg>corrected compilation errors<commit_after> #include "potentialfunctioncbspl.h" PotentialFunctionCBSPL::PotentialFunctionCBSPL(const int nlam_, const int ncutcoeff_, const double min_, const double max_) : PotentialFunction(nlam_,min_,max_) { /* Here nlam_ is the total number of coeff values that are to be optimized * To ensure that potential and force go to zero smoothly near cut-off, * as suggested in Ref. PCCP, 11, 1901, 2009, coeff values leading up to * cut-off and beyond take a value of zero. * * Since region less than rmin is not sampled sufficiently for stability * first _nexcl coefficients are not optimized instead their values are * extrapolated from first statistically significant knot values near rmin */ // number of break points = _lam.size() - 2 _nbreak = _lam.size() - 2; double _dr = ( _cut_off )/( double (_nbreak - 1) ); // break point locations // since ncoeff = nbreak +2 , r values for last two coefficients are also // computed _rbreak.resize(_lam.size(),false); _rbreak.clear(); for( int i = 0; i < _lam.size(); i++) _rbreak(i) = i*_dr; _nexcl = min( int( ( _min )/_dr ), _nbreak - 2 ); _ncutcoeff = ncutcoeff_; _M.resize(4,4,false); _M.clear(); _M(0,0) = 1.0; _M(0,1) = 4.0; _M(0,2) = 1.0; _M(0,3) = 0.0; _M(1,0) = -3.0; _M(1,1) = 0.0; _M(1,2) = 3.0; _M(1,3) = 0.0; _M(2,0) = 3.0; _M(2,1) = -6.0; _M(2,2) = 3.0; _M(2,3) = 0.0; _M(3,0) = -1.0; _M(3,1) = 3.0; _M(3,2) = -3.0; _M(3,3) = 1.0; _M /= 6.0; } int PotentialFunctionCBSPL::getOptParamSize() const { return _lam.size() - _nexcl - _ncutcoeff; } void PotentialFunctionCBSPL::setParam(string filename) { Table param; param.Load(filename); if( param.size() != _lam.size()) { throw std::runtime_error("Potential parameters size mismatch!\n" "Check input parameter file \"" + filename + "\" \nThere should be " + boost::lexical_cast<string>( _lam.size() ) + " parameters"); } else { for( int i = 0; i < _lam.size(); i++){ _rbreak(i) = param.x(i); _lam(i) = param.y(i); } } } void PotentialFunctionCBSPL::SaveParam(const string& filename){ Table param; param.SetHasYErr(false); param.resize(_lam.size(), false); // extrapolate first _nexcl knot values using exponential extrapolation // u(r) = a * exp( b * r) // a = u0 * exp ( - m * r0/u0 ) // b = m/u0 // m = (u1-u0)/(r1-r0) double u0 = _lam(_nexcl); double r0 = _rbreak(_nexcl); double m = ( _lam(_nexcl+1) - _lam(_nexcl) ) / ( _rbreak(_nexcl+1) - _rbreak(_nexcl) ); double a = u0 * exp ( - m * r0/u0 ); double b = m/u0; for (int i = 0; i < _nexcl; i++){ double r = _rbreak(i); double u = a * exp( b * r); _lam(i) = u; param.set(i, r, u, 'o'); } for (int i = _nexcl; i < _lam.size(); i++){ param.set(i, _rbreak(i), _lam(i), 'i'); } param.Save(filename); } double PotentialFunctionCBSPL::CalculateF (const double r) const { if( r >= _min && r <= _cut_off){ ub::vector<double> R; ub::vector<double> B; int indx = min( int( r /_dr ) , _nbreak-2 ); double rk = indx*_dr; double t = ( r - rk)/_dr; R.resize(4,false); R.clear(); R(0) = 1.0; R(1) = t; R(2) = t*t; R(3) = t*t*t; ub::vector<double> RM = ub::prod(R,_M); B.resize(4,false); B.clear(); B(0) = _lam(indx); B(1) = _lam(indx+1); B(2) = _lam(indx+2); B(3) = _lam(indx+3); double u = ub::inner_prod(B,RM); return u; } else { return 0.0; } } // calculate first derivative w.r.t. ith parameter double PotentialFunctionCBSPL::CalculateDF(const int i, const double r) const{ // since first _nexcl parameters are not optimized for stability reasons //i = i + _nexcl; if ( r >= _min && r <= _cut_off ) { int indx = min( int( ( r )/_dr ), _nbreak-2 ); if ( i + _nexcl >= indx && i + _nexcl <= indx+3 ){ ub::vector<double> R; double rk = indx*_dr; double t = ( r - rk)/_dr; R.resize(4,false); R.clear(); R(0) = 1.0; R(1) = t; R(2) = t*t; R(3) = t*t*t; ub::vector<double> RM = ub::prod(R,_M); return RM(i + _nexcl-indx); }else{ return 0.0; } } else { return 0; } } // calculate second derivative w.r.t. ith parameter double PotentialFunctionCBSPL::CalculateD2F(const int i, const int j, const double r) const { // for cubic B-SPlines D2F is zero for all lamdas return 0.0; } <|endoftext|>
<commit_before>#include <QtCore> #include <QtNetwork> #include <obs.h> #include "nicolive.h" // class NicoLive class NicoLive : public QObject { // Q_OBJECT public: static const QUrl LOGIN_URL; // static const QUrl MYLIVE_URL; static const QUrl PUBSTAT_URL; static const QString FMEPROF_URL_PRE; private: QString session; QString mail; QString password; QString live_id; QString live_url; QString live_key; QNetworkAccessManager* qnam; public: NicoLive(); void setSession(const char *session); void setAccount(const char *mail, const char *password); const char *getSession(); const char *getLiveId(); const char *getLiveUrl(const char *live_id); const char *getLiveKey(const char *live_id); bool checkSession(); QVariant makeCookieData(const QString &session_id); QByteArray getWeb(const QUrl); // Access Niconico Site bool siteLogin(); bool sitePubStat(); bool siteLiveProf(); }; const QUrl NicoLive::LOGIN_URL = QUrl("https://secure.nicovideo.jp/secure/login?site=nicolive"); // const QUrl NicoLive::MYLIVE_URL = // QUrl("http://live.nicovideo.jp/my"); const QUrl NicoLive::PUBSTAT_URL = QUrl("http://live.nicovideo.jp/api/getpublishstatus"); const QString NicoLive::FMEPROF_URL_PRE = "http://live.nicovideo.jp/api/getfmeprofile?v="; NicoLive::NicoLive() { qnam = new QNetworkAccessManager(this); } void NicoLive::setSession(const char *session) { debug_call_func(); this->session = session; } void NicoLive::setAccount(const char *mail, const char *password) { debug_call_func(); this->mail = mail; this->password = password; } const char *NicoLive::getSession() { debug_call_func(); return this->session.toStdString().c_str(); } const char *NicoLive::getLiveId() { debug_call_func(); if (this->sitePubStat()) { if (this->siteLiveProf()) { debug("nioclive.live_id: %s", this->live_id.toStdString().c_str()); return this->live_id.toStdString().c_str(); } } return NULL; } const char *NicoLive::getLiveUrl(const char *live_id) { debug_call_func(); debug("check live_id: '%s'", live_id); debug("check this->live_id: '%s'", this->live_id.toStdString().c_str()); debug("same? %d", this->live_id == live_id); // if (this->live_id == live_id) { debug("nioclive.live_url: %s", this->live_url.toStdString().c_str()); return this->live_url.toStdString().c_str(); // } return NULL; } const char *NicoLive::getLiveKey(const char *live_id) { debug_call_func(); debug("check live_id: '%s'", live_id); debug("check this->live_id: '%s'", this->live_id.toStdString().c_str()); debug("same? %d", this->live_id == live_id); // if (this->live_id == live_id) { debug("nioclive.live_key: %s", this->live_key.toStdString().c_str()); return this->live_key.toStdString().c_str(); // } // NG Connecting to RTMP URL rtmp://nlpoc // OK Connection to rtmp://nlpoca147. // return NULL; } bool NicoLive::checkSession() { debug_call_func(); return this->sitePubStat(); } /* original code by https://github.com/diginatu/Viqo file: src/NicoLiveManager/nicolivemanager.cpp Licensed under the MIT License Copyright (c) 2014 diginatu see https://github.com/diginatu/Viqo/raw/master/LICENSE */ QVariant NicoLive::makeCookieData(const QString &session_id) { debug_call_func(); QVariant cookieData; // make cookies QList <QNetworkCookie> cookies; QNetworkCookie ck; ck.toRawForm(QNetworkCookie::NameAndValueOnly); ck.setName("user_session"); QByteArray user_id_ba; user_id_ba.append(session_id); ck.setValue(user_id_ba); cookies.append(ck); cookieData.setValue(cookies); return cookieData; } /* original code by https://github.com/diginatu/Viqo file: src/NicoLiveManager/loginapi.cpp Licensed under the MIT License Copyright (c) 2014 diginatu see https://github.com/diginatu/Viqo/raw/master/LICENSE */ bool NicoLive::siteLogin() { debug_call_func(); QNetworkRequest rq(NicoLive::LOGIN_URL); rq.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded"); QUrlQuery params; params.addQueryItem("next_url", ""); params.addQueryItem("show_button_facebook", "0"); params.addQueryItem("show_button_twitter", "0"); params.addQueryItem("nolinks", "0"); params.addQueryItem("_use_valid_error_code", "0"); params.addQueryItem("mail", QUrl::toPercentEncoding(this->mail)); params.addQueryItem("password", QUrl::toPercentEncoding(this->password)); QNetworkReply *netReply = qnam->post(rq, params.toString(QUrl::FullyEncoded).toUtf8()); info("login start"); // wait reply QEventLoop loop; connect(netReply, SIGNAL(finished()), &loop, SLOT(quit())); loop.exec(); info("login finished"); // finished reply auto headers = netReply->rawHeaderPairs(); bool success = false; foreach (auto header, headers) { if (header.first == "Set-Cookie") { auto cookies = QNetworkCookie::parseCookies(header.second); foreach (auto cookie, cookies) { if (cookie.name() == "user_session" && cookie.value() != "deleted" && cookie.value() != "") { this->session = cookie.value(); success = true; // info("login succeeded: %s", this->session.toStdString().c_str()); info("login succeeded: %s", "secret"); break; } } break; } } if (!success) { warn("[nicolive] login failed"); } netReply->deleteLater(); return success; } /* original code by https://github.com/diginatu/Viqo file: src/NicoLiveManager/rawmylivewaku.cpp Licensed under the MIT License Copyright (c) 2014 diginatu see https://github.com/diginatu/Viqo/raw/master/LICENSE */ QByteArray NicoLive::getWeb(const QUrl url) { debug_call_func(); if (this->session.isEmpty()) { return ""; } // make request QNetworkRequest rq; QVariant cookieData = this->makeCookieData(this->session); rq.setHeader(QNetworkRequest::CookieHeader, cookieData); rq.setUrl(url); QNetworkReply * netReply = qnam->get(rq); info("web get start"); // wait reply QEventLoop loop; connect(netReply, SIGNAL(finished()), &loop, SLOT(quit())); loop.exec(); info("web get finished"); // finished reply QByteArray repdata = netReply->readAll(); netReply->deleteLater(); return repdata; } bool NicoLive::sitePubStat() { debug_call_func(); if (this->session.isEmpty()) { debug("this->session is empty."); this->live_id = QString(); return false; } QXmlStreamReader reader(this->getWeb(NicoLive::PUBSTAT_URL)); bool success = false; this->live_id = QString(); QString status; QString error_code; while (!reader.atEnd()) { debug("read token: %s", reader.tokenString().toStdString().c_str()); if (reader.isStartElement() && reader.name() == "getpublishstatus") { status = reader.attributes().value("status").toString(); if (status == "ok") { reader.readNext(); // <stream> reader.readNext(); // <id> reader.readNext(); // content of code this->live_id = reader.text().toString(); info("live waku: %s", this->live_id.toStdString().c_str()); success = true; break; } else if (status == "fail") { reader.readNext(); // <error> reader.readNext(); // <code> reader.readNext(); // content of code error_code = reader.text().toString(); if (error_code == "notfound") { info("no live waku"); success = true; } else if (error_code == "unknown") { warn("login session failed"); } else { error("unknow error code: %s", error_code.toStdString().c_str()); } break; } else { error("unknow status: %s", status.toStdString().c_str()); break; } } reader.readNext(); } if (reader.hasError()) { error("read error: %s", reader.errorString().toStdString().c_str()); } return success; } bool NicoLive::siteLiveProf() { debug_call_func(); if (this->live_id.isEmpty()) { debug("this->live_id is empty."); this->live_url = QString(); this->live_key = QString(); return false; } QString live_prof_url; live_prof_url += NicoLive::FMEPROF_URL_PRE; live_prof_url += this->live_id; QXmlStreamReader reader(this->getWeb(QUrl(live_prof_url))); bool success = false; while (!reader.atEnd()) { debug("read token: %s", reader.tokenString().toStdString().c_str()); if (reader.isStartElement() && reader.name() == "rtmp") { while (!reader.atEnd()) { if (reader.isStartElement() && reader.name() == "url") { reader.readNext(); if (reader.isCharacters()) { this->live_url = reader.text().toString(); this->live_key = this->live_id; // same stream key and live id success = true; info("found live url"); break; } else { error("invalid xml: rtmp->url next not contents"); break; } // } else if (reader.isStartElement() && reader.name() == "stream") { // if (reader.isCharacters()) { // this->live_key = reader.text().toString(); // success_key = true; // info("found live key"); // debug("live key: %s", this->live_key.toStdString().c_str()); // } else { // error("invalid xml: rtmp->stream next not contents"); // break; // } } else if (reader.isEndElement() && reader.name() == "rtmp") { error("invalid xml: rtmp end before url"); break; } reader.atEnd() || reader.readNext(); } break; } reader.atEnd() || reader.readNext(); } // end while if (reader.hasError()) { error("read error: %s", reader.errorString().toStdString().c_str()); } if (success) { return true; } else { warn("not found rtmp url"); this->live_url = QString(); this->live_key = QString(); return false; } } // end of NicoLive class static NicoLive nicolive; extern "C" bool nicolive_chek_session_n(const char *session) { debug_call_func(); nicolive.setSession(session); return nicolive.checkSession(); } extern "C" const char *nicolive_get_session(const char *mail, const char *password) { debug_call_func(); nicolive.setAccount(mail, password); if (nicolive.siteLogin()) { return nicolive.getSession(); } else { return NULL; } } extern "C" const char *nicolive_get_live_id(const char *session) { debug_call_func(); nicolive.setSession(session); return nicolive.getLiveId(); } extern "C" const char *nicolive_get_live_url(const char *session, const char *live_id) { debug_call_func(); nicolive.setSession(session); return nicolive.getLiveUrl(live_id); } extern "C" const char *nicolive_get_live_key(const char *session, const char *live_id) { debug_call_func(); nicolive.setSession(session); return nicolive.getLiveKey(live_id); } <commit_msg>QString.toStdString()が関数抜けると破棄されちゃうのでbuffで持つようにした。 でも、テストはあまりしてない。いつものこと?<commit_after>#include <cstdlib> #include <cstring> #include <QtCore> #include <QtNetwork> #include <obs.h> #include "nicolive.h" // class NicoLive class NicoLive : public QObject { // Q_OBJECT public: static const QUrl LOGIN_URL; // static const QUrl MYLIVE_URL; static const QUrl PUBSTAT_URL; static const QString FMEPROF_URL_PRE; private: QString session; QString mail; QString password; QString live_id; QString live_url; QString live_key; QNetworkAccessManager* qnam; char *buff = NULL; size_t buff_size = 256; const char *buff_str(const char * str); public: NicoLive(); void setSession(const char *session); void setAccount(const char *mail, const char *password); const char *getSession(); const char *getLiveId(); const char *getLiveUrl(const char *live_id); const char *getLiveKey(const char *live_id); bool checkSession(); QVariant makeCookieData(const QString &session_id); QByteArray getWeb(const QUrl); // Access Niconico Site bool siteLogin(); bool sitePubStat(); bool siteLiveProf(); }; const QUrl NicoLive::LOGIN_URL = QUrl("https://secure.nicovideo.jp/secure/login?site=nicolive"); // const QUrl NicoLive::MYLIVE_URL = // QUrl("http://live.nicovideo.jp/my"); const QUrl NicoLive::PUBSTAT_URL = QUrl("http://live.nicovideo.jp/api/getpublishstatus"); const QString NicoLive::FMEPROF_URL_PRE = "http://live.nicovideo.jp/api/getfmeprofile?v="; NicoLive::NicoLive() { qnam = new QNetworkAccessManager(this); buff = (char *)malloc(sizeof(char) * buff_size); if (buff == NULL) { error("failed malloc buff"); } } const char *NicoLive::buff_str(const char *str) { debug_call_func(); size_t len = strlen(str); if (len + 1 > buff_size) { buff_size = (len + 1) * 2; // double size !! buff = (char *)realloc(buff, sizeof(char) * buff_size); if (buff == NULL) { error("failed malloc buff"); return NULL; } } return strcpy(buff, str); } void NicoLive::setSession(const char *session) { debug_call_func(); this->session = session; } void NicoLive::setAccount(const char *mail, const char *password) { debug_call_func(); this->mail = mail; this->password = password; } const char *NicoLive::getSession() { debug_call_func(); return buff_str(this->session.toStdString().c_str()); } const char *NicoLive::getLiveId() { debug_call_func(); if (this->sitePubStat()) { if (this->siteLiveProf()) { debug("nioclive.live_id: %s", this->live_id.toStdString().c_str()); return buff_str(this->live_id.toStdString().c_str()); } } return NULL; } const char *NicoLive::getLiveUrl(const char *live_id) { debug_call_func(); debug("check live_id: '%s'", live_id); debug("check this->live_id: '%s'", this->live_id.toStdString().c_str()); debug("same? %d", this->live_id == live_id); // if (this->live_id == live_id) { debug("nioclive.live_url: %s", this->live_url.toStdString().c_str()); return buff_str(this->live_url.toStdString().c_str()); // } return NULL; } const char *NicoLive::getLiveKey(const char *live_id) { debug_call_func(); debug("check live_id: '%s'", live_id); debug("check this->live_id: '%s'", this->live_id.toStdString().c_str()); debug("same? %d", this->live_id == live_id); // if (this->live_id == live_id) { debug("nioclive.live_key: %s", this->live_key.toStdString().c_str()); return buff_str(this->live_key.toStdString().c_str()); // } // NG Connecting to RTMP URL rtmp://nlpoc // OK Connection to rtmp://nlpoca147. // return NULL; } bool NicoLive::checkSession() { debug_call_func(); return this->sitePubStat(); } /* original code by https://github.com/diginatu/Viqo file: src/NicoLiveManager/nicolivemanager.cpp Licensed under the MIT License Copyright (c) 2014 diginatu see https://github.com/diginatu/Viqo/raw/master/LICENSE */ QVariant NicoLive::makeCookieData(const QString &session_id) { debug_call_func(); QVariant cookieData; // make cookies QList <QNetworkCookie> cookies; QNetworkCookie ck; ck.toRawForm(QNetworkCookie::NameAndValueOnly); ck.setName("user_session"); QByteArray user_id_ba; user_id_ba.append(session_id); ck.setValue(user_id_ba); cookies.append(ck); cookieData.setValue(cookies); return cookieData; } /* original code by https://github.com/diginatu/Viqo file: src/NicoLiveManager/loginapi.cpp Licensed under the MIT License Copyright (c) 2014 diginatu see https://github.com/diginatu/Viqo/raw/master/LICENSE */ bool NicoLive::siteLogin() { debug_call_func(); QNetworkRequest rq(NicoLive::LOGIN_URL); rq.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded"); QUrlQuery params; params.addQueryItem("next_url", ""); params.addQueryItem("show_button_facebook", "0"); params.addQueryItem("show_button_twitter", "0"); params.addQueryItem("nolinks", "0"); params.addQueryItem("_use_valid_error_code", "0"); params.addQueryItem("mail", QUrl::toPercentEncoding(this->mail)); params.addQueryItem("password", QUrl::toPercentEncoding(this->password)); QNetworkReply *netReply = qnam->post(rq, params.toString(QUrl::FullyEncoded).toUtf8()); info("login start"); // wait reply QEventLoop loop; connect(netReply, SIGNAL(finished()), &loop, SLOT(quit())); loop.exec(); info("login finished"); // finished reply auto headers = netReply->rawHeaderPairs(); bool success = false; foreach (auto header, headers) { if (header.first == "Set-Cookie") { auto cookies = QNetworkCookie::parseCookies(header.second); foreach (auto cookie, cookies) { if (cookie.name() == "user_session" && cookie.value() != "deleted" && cookie.value() != "") { this->session = cookie.value(); success = true; // info("login succeeded: %s", this->session.toStdString().c_str()); info("login succeeded: %s", "secret"); break; } } break; } } if (!success) { warn("[nicolive] login failed"); } netReply->deleteLater(); return success; } /* original code by https://github.com/diginatu/Viqo file: src/NicoLiveManager/rawmylivewaku.cpp Licensed under the MIT License Copyright (c) 2014 diginatu see https://github.com/diginatu/Viqo/raw/master/LICENSE */ QByteArray NicoLive::getWeb(const QUrl url) { debug_call_func(); if (this->session.isEmpty()) { return ""; } // make request QNetworkRequest rq; QVariant cookieData = this->makeCookieData(this->session); rq.setHeader(QNetworkRequest::CookieHeader, cookieData); rq.setUrl(url); QNetworkReply * netReply = qnam->get(rq); info("web get start"); // wait reply QEventLoop loop; connect(netReply, SIGNAL(finished()), &loop, SLOT(quit())); loop.exec(); info("web get finished"); // finished reply QByteArray repdata = netReply->readAll(); netReply->deleteLater(); return repdata; } bool NicoLive::sitePubStat() { debug_call_func(); if (this->session.isEmpty()) { debug("this->session is empty."); this->live_id = QString(); return false; } QXmlStreamReader reader(this->getWeb(NicoLive::PUBSTAT_URL)); bool success = false; this->live_id = QString(); QString status; QString error_code; while (!reader.atEnd()) { debug("read token: %s", reader.tokenString().toStdString().c_str()); if (reader.isStartElement() && reader.name() == "getpublishstatus") { status = reader.attributes().value("status").toString(); if (status == "ok") { reader.readNext(); // <stream> reader.readNext(); // <id> reader.readNext(); // content of code this->live_id = reader.text().toString(); info("live waku: %s", this->live_id.toStdString().c_str()); success = true; break; } else if (status == "fail") { reader.readNext(); // <error> reader.readNext(); // <code> reader.readNext(); // content of code error_code = reader.text().toString(); if (error_code == "notfound") { info("no live waku"); success = true; } else if (error_code == "unknown") { warn("login session failed"); } else { error("unknow error code: %s", error_code.toStdString().c_str()); } break; } else { error("unknow status: %s", status.toStdString().c_str()); break; } } reader.readNext(); } if (reader.hasError()) { error("read error: %s", reader.errorString().toStdString().c_str()); } return success; } bool NicoLive::siteLiveProf() { debug_call_func(); if (this->live_id.isEmpty()) { debug("this->live_id is empty."); this->live_url = QString(); this->live_key = QString(); return false; } QString live_prof_url; live_prof_url += NicoLive::FMEPROF_URL_PRE; live_prof_url += this->live_id; QXmlStreamReader reader(this->getWeb(QUrl(live_prof_url))); bool success = false; while (!reader.atEnd()) { debug("read token: %s", reader.tokenString().toStdString().c_str()); if (reader.isStartElement() && reader.name() == "rtmp") { while (!reader.atEnd()) { if (reader.isStartElement() && reader.name() == "url") { reader.readNext(); if (reader.isCharacters()) { this->live_url = reader.text().toString(); this->live_key = this->live_id; // same stream key and live id success = true; info("found live url"); break; } else { error("invalid xml: rtmp->url next not contents"); break; } // } else if (reader.isStartElement() && reader.name() == "stream") { // if (reader.isCharacters()) { // this->live_key = reader.text().toString(); // success_key = true; // info("found live key"); // debug("live key: %s", this->live_key.toStdString().c_str()); // } else { // error("invalid xml: rtmp->stream next not contents"); // break; // } } else if (reader.isEndElement() && reader.name() == "rtmp") { error("invalid xml: rtmp end before url"); break; } reader.atEnd() || reader.readNext(); } break; } reader.atEnd() || reader.readNext(); } // end while if (reader.hasError()) { error("read error: %s", reader.errorString().toStdString().c_str()); } if (success) { return true; } else { warn("not found rtmp url"); this->live_url = QString(); this->live_key = QString(); return false; } } // end of NicoLive class static NicoLive nicolive; extern "C" bool nicolive_chek_session_n(const char *session) { debug_call_func(); nicolive.setSession(session); return nicolive.checkSession(); } extern "C" const char *nicolive_get_session(const char *mail, const char *password) { debug_call_func(); nicolive.setAccount(mail, password); if (nicolive.siteLogin()) { return nicolive.getSession(); } else { return NULL; } } extern "C" const char *nicolive_get_live_id(const char *session) { debug_call_func(); nicolive.setSession(session); return nicolive.getLiveId(); } extern "C" const char *nicolive_get_live_url(const char *session, const char *live_id) { debug_call_func(); nicolive.setSession(session); return nicolive.getLiveUrl(live_id); } extern "C" const char *nicolive_get_live_key(const char *session, const char *live_id) { debug_call_func(); nicolive.setSession(session); return nicolive.getLiveKey(live_id); } <|endoftext|>
<commit_before>/* * File: main_voctreeLocalizer.cpp * Author: sgaspari * * Created on September 12, 2015, 3:16 PM */ #include <openMVG/localization/VoctreeLocalizer.hpp> #include <openMVG/localization/CCTagLocalizer.hpp> #include <openMVG/localization/optimization.hpp> #include <openMVG/sfm/pipelines/localization/SfM_Localizer.hpp> #include <openMVG/image/image_io.hpp> #include <openMVG/dataio/FeedProvider.hpp> #include <openMVG/localization/LocalizationResult.hpp> #include <boost/filesystem.hpp> #include <boost/progress.hpp> #include <boost/program_options.hpp> #include <boost/accumulators/accumulators.hpp> #include <boost/accumulators/statistics/stats.hpp> #include <boost/accumulators/statistics/mean.hpp> #include <boost/accumulators/statistics/min.hpp> #include <boost/accumulators/statistics/max.hpp> #include <boost/accumulators/statistics/sum.hpp> #include <iostream> #include <string> #include <chrono> #if HAVE_ALEMBIC #include <openMVG/dataio/AlembicExporter.hpp> #endif // HAVE_ALEMBIC #define POPART_COUT(x) std::cout << x << std::endl #define POPART_CERR(x) std::cerr << x << std::endl namespace bfs = boost::filesystem; namespace bacc = boost::accumulators; namespace po = boost::program_options; using namespace openMVG; std::string myToString(std::size_t i, std::size_t zeroPadding) { std::stringstream ss; ss << std::setw(zeroPadding) << std::setfill('0') << i; return ss.str(); } int main(int argc, char** argv) { std::string calibFile; //< the calibration file std::string sfmFilePath; //< the OpenMVG .json data file std::string descriptorsFolder; //< the OpenMVG .json data file std::string mediaFilepath; //< the media file to localize localization::CCTagLocalizer::Parameters param = localization::CCTagLocalizer::Parameters(); std::string preset = features::describerPreset_enumToString(param._featurePreset); //< the preset for the feature extractor #if HAVE_ALEMBIC std::string exportFile = "trackedcameras.abc"; //!< the export file #endif bool globalBundle = false; //< If !param._refineIntrinsics it can run a final global budndle to refine the scene po::options_description desc( "This program takes as input a media (image, image sequence, video) and a database (voctree, 3D structure data) \n" "and returns for each frame a pose estimation for the camera."); desc.add_options() ("help,h", "Print this message") ("results,r", po::value<size_t>(&param._nNearestKeyFrames)->default_value(param._nNearestKeyFrames), "Number of images to retrieve in database") ("preset", po::value<std::string>(&preset)->default_value(preset), "Preset for the feature extractor when localizing a new image {LOW,NORMAL,HIGH,ULTRA}") ("calibration,c", po::value<std::string>(&calibFile)/*->required( )*/, "Calibration file") ("sfmdata,d", po::value<std::string>(&sfmFilePath)->required(), "The sfm_data.json kind of file generated by OpenMVG [it could be also a bundle.out to use an older version of OpenMVG]") ("siftPath,s", po::value<std::string>(&descriptorsFolder), "Folder containing the .desc. If not provided, it will be assumed to be parent(sfmdata)/matches [for the older version of openMVG it is the list.txt]") ("mediafile,m", po::value<std::string>(&mediaFilepath)->required(), "The folder path or the filename for the media to track") ("refineIntrinsics", po::bool_switch(&param._refineIntrinsics), "Enable/Disable camera intrinsics refinement for each localized image") ("globalBundle", po::bool_switch(&globalBundle), "If --refineIntrinsics is not set, this option allows to run a final global budndle adjustment to refine the scene") ("visualDebug", po::value<std::string>(&param._visualDebug), "If a directory is provided it enables visual debug and saves all the debugging info in that directory") #if HAVE_ALEMBIC ("export,e", po::value<std::string>(&exportFile)->default_value(exportFile), "Filename for the SfM_Data export file (where camera poses will be stored). Default : trackedcameras.json If Alambic is enable it will also export an .abc file of the scene with the same name") #endif ; po::variables_map vm; try { po::store(po::parse_command_line(argc, argv, desc), vm); if(vm.count("help") || (argc == 1)) { POPART_COUT(desc); return EXIT_SUCCESS; } po::notify(vm); } catch(boost::program_options::required_option& e) { POPART_CERR("ERROR: " << e.what() << std::endl); POPART_COUT("Usage:\n\n" << desc); return EXIT_FAILURE; } catch(boost::program_options::error& e) { POPART_CERR("ERROR: " << e.what() << std::endl); POPART_COUT("Usage:\n\n" << desc); return EXIT_FAILURE; } if(vm.count("preset")) { param._featurePreset = features::describerPreset_stringToEnum(preset); } { // the bundle adjustment can be run for now only if the refine intrinsics option is not set globalBundle = (globalBundle && !param._refineIntrinsics); POPART_COUT("Program called with the following parameters:"); POPART_COUT("\tcalibration: " << calibFile); POPART_COUT("\tsfmdata: " << sfmFilePath); POPART_COUT("\tmediafile: " << mediaFilepath); POPART_COUT("\tsiftPath: " << descriptorsFolder); POPART_COUT("\tresults: " << param._nNearestKeyFrames); POPART_COUT("\trefineIntrinsics: " << param._refineIntrinsics); POPART_COUT("\tpreset: " << features::describerPreset_enumToString(param._featurePreset)); POPART_COUT("\tglobalBundle: " << globalBundle); POPART_COUT("\tvisual debug: " << param._visualDebug); } if(!bfs::exists(param._visualDebug) && param._visualDebug != "") { bfs::create_directories(param._visualDebug); } // init the localizer localization::CCTagLocalizer localizer(sfmFilePath, descriptorsFolder); if(!localizer.isInit()) { POPART_CERR("ERROR while initializing the localizer!"); return EXIT_FAILURE; } // create the feedProvider dataio::FeedProvider feed(mediaFilepath, calibFile); if(!feed.isInit()) { POPART_CERR("ERROR while initializing the FeedProvider!"); return EXIT_FAILURE; } bool feedIsVideo = feed.isVideo(); #if HAVE_ALEMBIC dataio::AlembicExporter exporter(exportFile); exporter.addPoints(localizer.getSfMData().GetLandmarks()); #endif image::Image<unsigned char> imageGrey; cameras::Pinhole_Intrinsic_Radial_K3 queryIntrinsics; bool hasIntrinsics = false; size_t frameCounter = 0; size_t goodFrameCounter = 0; vector<string> goodFrameList; std::string currentImgName; // Define an accumulator set for computing the mean and the // standard deviation of the time taken for localization bacc::accumulator_set<double, bacc::stats<bacc::tag::mean, bacc::tag::min, bacc::tag::max, bacc::tag::sum > > stats; std::vector<localization::LocalizationResult> vec_localizationResults; while(feed.next(imageGrey, queryIntrinsics, currentImgName, hasIntrinsics)) { POPART_COUT("******************************"); POPART_COUT("FRAME " << myToString(frameCounter, 4)); POPART_COUT("******************************"); auto detect_start = std::chrono::steady_clock::now(); localization::LocalizationResult localizationResult; localizer.localize(imageGrey, &param, hasIntrinsics/*useInputIntrinsics*/, queryIntrinsics, // todo: put as const and use the intrinsic result store in localizationResult afterward localizationResult, (feedIsVideo) ? "" : currentImgName); auto detect_end = std::chrono::steady_clock::now(); auto detect_elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(detect_end - detect_start); POPART_COUT("\nLocalization took " << detect_elapsed.count() << " [ms]"); stats(detect_elapsed.count()); // save data if(localizationResult.isValid()) { #if HAVE_ALEMBIC exporter.appendCamera("camera." + myToString(frameCounter, 4), localizationResult.getPose(), &queryIntrinsics, mediaFilepath, frameCounter, frameCounter); #endif goodFrameCounter++; goodFrameList.push_back(currentImgName + " : " + std::to_string(localizationResult.getIndMatch3D2D().size()) ); if(globalBundle) { vec_localizationResults.emplace_back(localizationResult); } } else { #if HAVE_ALEMBIC // @fixme for now just add a fake camera so that it still can be see in MAYA exporter.appendCamera("camera.V." + myToString(frameCounter, 4), geometry::Pose3(), &queryIntrinsics, mediaFilepath, frameCounter, frameCounter); #endif POPART_CERR("Unable to localize frame " << frameCounter); } ++frameCounter; } if(globalBundle) { // run a bundle adjustment const bool BAresult = localization::refineSequence(&queryIntrinsics, vec_localizationResults); if(!BAresult) { POPART_CERR("Bundle Adjustment failed!"); } else { #if HAVE_ALEMBIC // now copy back in a new abc with the same name file and BUNDLE appended at the end dataio::AlembicExporter exporterBA(bfs::path(exportFile).stem().string() + ".BUNDLE.abc"); size_t idx = 0; for(const localization::LocalizationResult &res : vec_localizationResults) { if(res.isValid()) { assert(idx < vec_localizationResults.size()); exporterBA.appendCamera("camera." + myToString(idx, 4), res.getPose(), &queryIntrinsics, mediaFilepath, frameCounter, frameCounter); } else { exporterBA.appendCamera("camera.V." + myToString(idx, 4), geometry::Pose3(), &queryIntrinsics, mediaFilepath, frameCounter, frameCounter); } idx++; } exporterBA.addPoints(localizer.getSfMData().GetLandmarks()); #endif } } // print out some time stats POPART_COUT("\n\n******************************"); POPART_COUT("Localized " << goodFrameCounter << "/" << frameCounter << " images"); POPART_COUT("Images localized with the number of 2D/3D matches during localization :"); for(int i = 0; i < goodFrameList.size(); i++) POPART_COUT(goodFrameList[i]); POPART_COUT("Processing took " << bacc::sum(stats)/1000 << " [s] overall"); POPART_COUT("Mean time for localization: " << bacc::mean(stats) << " [ms]"); POPART_COUT("Max time for localization: " << bacc::max(stats) << " [ms]"); POPART_COUT("Min time for localization: " << bacc::min(stats) << " [ms]"); } <commit_msg>[localization] improve condition for visual debug folder creation<commit_after>/* * File: main_voctreeLocalizer.cpp * Author: sgaspari * * Created on September 12, 2015, 3:16 PM */ #include <openMVG/localization/VoctreeLocalizer.hpp> #include <openMVG/localization/CCTagLocalizer.hpp> #include <openMVG/localization/optimization.hpp> #include <openMVG/sfm/pipelines/localization/SfM_Localizer.hpp> #include <openMVG/image/image_io.hpp> #include <openMVG/dataio/FeedProvider.hpp> #include <openMVG/localization/LocalizationResult.hpp> #include <boost/filesystem.hpp> #include <boost/progress.hpp> #include <boost/program_options.hpp> #include <boost/accumulators/accumulators.hpp> #include <boost/accumulators/statistics/stats.hpp> #include <boost/accumulators/statistics/mean.hpp> #include <boost/accumulators/statistics/min.hpp> #include <boost/accumulators/statistics/max.hpp> #include <boost/accumulators/statistics/sum.hpp> #include <iostream> #include <string> #include <chrono> #if HAVE_ALEMBIC #include <openMVG/dataio/AlembicExporter.hpp> #endif // HAVE_ALEMBIC #define POPART_COUT(x) std::cout << x << std::endl #define POPART_CERR(x) std::cerr << x << std::endl namespace bfs = boost::filesystem; namespace bacc = boost::accumulators; namespace po = boost::program_options; using namespace openMVG; std::string myToString(std::size_t i, std::size_t zeroPadding) { std::stringstream ss; ss << std::setw(zeroPadding) << std::setfill('0') << i; return ss.str(); } int main(int argc, char** argv) { std::string calibFile; //< the calibration file std::string sfmFilePath; //< the OpenMVG .json data file std::string descriptorsFolder; //< the OpenMVG .json data file std::string mediaFilepath; //< the media file to localize localization::CCTagLocalizer::Parameters param = localization::CCTagLocalizer::Parameters(); std::string preset = features::describerPreset_enumToString(param._featurePreset); //< the preset for the feature extractor #if HAVE_ALEMBIC std::string exportFile = "trackedcameras.abc"; //!< the export file #endif bool globalBundle = false; //< If !param._refineIntrinsics it can run a final global budndle to refine the scene po::options_description desc( "This program takes as input a media (image, image sequence, video) and a database (voctree, 3D structure data) \n" "and returns for each frame a pose estimation for the camera."); desc.add_options() ("help,h", "Print this message") ("results,r", po::value<size_t>(&param._nNearestKeyFrames)->default_value(param._nNearestKeyFrames), "Number of images to retrieve in database") ("preset", po::value<std::string>(&preset)->default_value(preset), "Preset for the feature extractor when localizing a new image {LOW,NORMAL,HIGH,ULTRA}") ("calibration,c", po::value<std::string>(&calibFile)/*->required( )*/, "Calibration file") ("sfmdata,d", po::value<std::string>(&sfmFilePath)->required(), "The sfm_data.json kind of file generated by OpenMVG [it could be also a bundle.out to use an older version of OpenMVG]") ("siftPath,s", po::value<std::string>(&descriptorsFolder), "Folder containing the .desc. If not provided, it will be assumed to be parent(sfmdata)/matches [for the older version of openMVG it is the list.txt]") ("mediafile,m", po::value<std::string>(&mediaFilepath)->required(), "The folder path or the filename for the media to track") ("refineIntrinsics", po::bool_switch(&param._refineIntrinsics), "Enable/Disable camera intrinsics refinement for each localized image") ("globalBundle", po::bool_switch(&globalBundle), "If --refineIntrinsics is not set, this option allows to run a final global budndle adjustment to refine the scene") ("visualDebug", po::value<std::string>(&param._visualDebug), "If a directory is provided it enables visual debug and saves all the debugging info in that directory") #if HAVE_ALEMBIC ("export,e", po::value<std::string>(&exportFile)->default_value(exportFile), "Filename for the SfM_Data export file (where camera poses will be stored). Default : trackedcameras.json If Alambic is enable it will also export an .abc file of the scene with the same name") #endif ; po::variables_map vm; try { po::store(po::parse_command_line(argc, argv, desc), vm); if(vm.count("help") || (argc == 1)) { POPART_COUT(desc); return EXIT_SUCCESS; } po::notify(vm); } catch(boost::program_options::required_option& e) { POPART_CERR("ERROR: " << e.what() << std::endl); POPART_COUT("Usage:\n\n" << desc); return EXIT_FAILURE; } catch(boost::program_options::error& e) { POPART_CERR("ERROR: " << e.what() << std::endl); POPART_COUT("Usage:\n\n" << desc); return EXIT_FAILURE; } if(vm.count("preset")) { param._featurePreset = features::describerPreset_stringToEnum(preset); } { // the bundle adjustment can be run for now only if the refine intrinsics option is not set globalBundle = (globalBundle && !param._refineIntrinsics); POPART_COUT("Program called with the following parameters:"); POPART_COUT("\tcalibration: " << calibFile); POPART_COUT("\tsfmdata: " << sfmFilePath); POPART_COUT("\tmediafile: " << mediaFilepath); POPART_COUT("\tsiftPath: " << descriptorsFolder); POPART_COUT("\tresults: " << param._nNearestKeyFrames); POPART_COUT("\trefineIntrinsics: " << param._refineIntrinsics); POPART_COUT("\tpreset: " << features::describerPreset_enumToString(param._featurePreset)); POPART_COUT("\tglobalBundle: " << globalBundle); POPART_COUT("\tvisual debug: " << param._visualDebug); } if(!param._visualDebug.empty() && !bfs::exists(param._visualDebug)) { bfs::create_directories(param._visualDebug); } // init the localizer localization::CCTagLocalizer localizer(sfmFilePath, descriptorsFolder); if(!localizer.isInit()) { POPART_CERR("ERROR while initializing the localizer!"); return EXIT_FAILURE; } // create the feedProvider dataio::FeedProvider feed(mediaFilepath, calibFile); if(!feed.isInit()) { POPART_CERR("ERROR while initializing the FeedProvider!"); return EXIT_FAILURE; } bool feedIsVideo = feed.isVideo(); #if HAVE_ALEMBIC dataio::AlembicExporter exporter(exportFile); exporter.addPoints(localizer.getSfMData().GetLandmarks()); #endif image::Image<unsigned char> imageGrey; cameras::Pinhole_Intrinsic_Radial_K3 queryIntrinsics; bool hasIntrinsics = false; size_t frameCounter = 0; size_t goodFrameCounter = 0; vector<string> goodFrameList; std::string currentImgName; // Define an accumulator set for computing the mean and the // standard deviation of the time taken for localization bacc::accumulator_set<double, bacc::stats<bacc::tag::mean, bacc::tag::min, bacc::tag::max, bacc::tag::sum > > stats; std::vector<localization::LocalizationResult> vec_localizationResults; while(feed.next(imageGrey, queryIntrinsics, currentImgName, hasIntrinsics)) { POPART_COUT("******************************"); POPART_COUT("FRAME " << myToString(frameCounter, 4)); POPART_COUT("******************************"); auto detect_start = std::chrono::steady_clock::now(); localization::LocalizationResult localizationResult; localizer.localize(imageGrey, &param, hasIntrinsics/*useInputIntrinsics*/, queryIntrinsics, // todo: put as const and use the intrinsic result store in localizationResult afterward localizationResult, (feedIsVideo) ? "" : currentImgName); auto detect_end = std::chrono::steady_clock::now(); auto detect_elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(detect_end - detect_start); POPART_COUT("\nLocalization took " << detect_elapsed.count() << " [ms]"); stats(detect_elapsed.count()); // save data if(localizationResult.isValid()) { #if HAVE_ALEMBIC exporter.appendCamera("camera." + myToString(frameCounter, 4), localizationResult.getPose(), &queryIntrinsics, mediaFilepath, frameCounter, frameCounter); #endif goodFrameCounter++; goodFrameList.push_back(currentImgName + " : " + std::to_string(localizationResult.getIndMatch3D2D().size()) ); if(globalBundle) { vec_localizationResults.emplace_back(localizationResult); } } else { #if HAVE_ALEMBIC // @fixme for now just add a fake camera so that it still can be see in MAYA exporter.appendCamera("camera.V." + myToString(frameCounter, 4), geometry::Pose3(), &queryIntrinsics, mediaFilepath, frameCounter, frameCounter); #endif POPART_CERR("Unable to localize frame " << frameCounter); } ++frameCounter; } if(globalBundle) { // run a bundle adjustment const bool BAresult = localization::refineSequence(&queryIntrinsics, vec_localizationResults); if(!BAresult) { POPART_CERR("Bundle Adjustment failed!"); } else { #if HAVE_ALEMBIC // now copy back in a new abc with the same name file and BUNDLE appended at the end dataio::AlembicExporter exporterBA(bfs::path(exportFile).stem().string() + ".BUNDLE.abc"); size_t idx = 0; for(const localization::LocalizationResult &res : vec_localizationResults) { if(res.isValid()) { assert(idx < vec_localizationResults.size()); exporterBA.appendCamera("camera." + myToString(idx, 4), res.getPose(), &queryIntrinsics, mediaFilepath, frameCounter, frameCounter); } else { exporterBA.appendCamera("camera.V." + myToString(idx, 4), geometry::Pose3(), &queryIntrinsics, mediaFilepath, frameCounter, frameCounter); } idx++; } exporterBA.addPoints(localizer.getSfMData().GetLandmarks()); #endif } } // print out some time stats POPART_COUT("\n\n******************************"); POPART_COUT("Localized " << goodFrameCounter << "/" << frameCounter << " images"); POPART_COUT("Images localized with the number of 2D/3D matches during localization :"); for(int i = 0; i < goodFrameList.size(); i++) POPART_COUT(goodFrameList[i]); POPART_COUT("Processing took " << bacc::sum(stats)/1000 << " [s] overall"); POPART_COUT("Mean time for localization: " << bacc::mean(stats) << " [ms]"); POPART_COUT("Max time for localization: " << bacc::max(stats) << " [ms]"); POPART_COUT("Min time for localization: " << bacc::min(stats) << " [ms]"); } <|endoftext|>
<commit_before>#include "CameraViewer.h" //============================================================== // SETUP / UPDATE / DRAW //============================================================== //-------------------------------------------------------------- // void CameraViewer::_setup() { int camWidth = 320; int camHeight = 240; _vidGrabber.setDeviceID(0); // _vidGrabber.setDesiredFrameRate(60); _vidGrabber.initGrabber(camWidth, camHeight); _videoTexture.allocate(camWidth, camHeight, GL_RGBA); flGraphics* g; g = graphics(); g->clear(); g->beginFill(0x888888, 0.8); g->drawRect(-10, -10, camWidth + 20, camHeight + 20); g->endFill(); flBitmap* bitmap = new flBitmap(_videoTexture); // bitmap->alpha(0.5); addChild(bitmap); } //-------------------------------------------------------------- // void CameraViewer::_update() { _vidGrabber.update(); if(_vidGrabber.isFrameNew()){ ofPixels& pixels = _vidGrabber.getPixels(); _videoTexture.loadData(pixels); } } //-------------------------------------------------------------- // void CameraViewer::_draw() { } <commit_msg>no message<commit_after><|endoftext|>
<commit_before>/* Copyright 2014-2015 QReal Research Group, Dmitry Chernov, Dmitry Mordvinov * * 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 "scriptAPI.h" #include <QtCore/QPropertyAnimation> #include <QtGui/QWidgetList> #include <QtWidgets/QApplication> #include <QtWidgets/QComboBox> #include <qrkernel/exception/exception.h> #include <qrutils/inFile.h> #include <editor/editorView.h> #include <models/commands/createElementCommand.h> #include "qrgui/mainWindow/mainWindow.h" #include "guiFacade.h" #include "virtualCursor.h" #include "virtualKeyboard.h" #include "hintAPI.h" #include "sceneAPI.h" #include "paletteAPI.h" using namespace qReal; using namespace gui; using namespace utils; ScriptAPI::ScriptAPI() : mGuiFacade(nullptr) , mVirtualCursor(nullptr) , mVirtualKeyboard(nullptr) , mSceneAPI(nullptr) , mPaletteAPI(nullptr) , mHintAPI(nullptr) , mScriptEngine(new QScriptEngine) { } ScriptAPI::~ScriptAPI() { } void ScriptAPI::init(MainWindow &mainWindow) { mGuiFacade.reset(new GuiFacade(mainWindow)); mVirtualCursor.reset(new VirtualCursor(*this, &mainWindow)); mVirtualKeyboard.reset(new VirtualKeyboard(*this)); mSceneAPI.reset(new SceneAPI(*this, mainWindow)); mPaletteAPI.reset(new PaletteAPI(*this, mainWindow)); mHintAPI.reset(new HintAPI); const QScriptValue scriptAPI = mScriptEngine.newQObject(this); // This instance will be available in scripts by writing something like "api.wait(100)" mScriptEngine.globalObject().setProperty("api", scriptAPI); } void ScriptAPI::evaluate() { const QString fileName(SettingsManager::value("scriptName").toString()); const QString fileContent = InFile::readAll(fileName); mVirtualCursor->show(); mVirtualCursor->raise(); mScriptEngine.setProcessEventsInterval(20); mScriptEngine.evaluate(fileContent, fileName); abortEvaluation(); } void ScriptAPI::pickComboBoxItem(QComboBox *comboBox, const QString &name, int duration) { const int comboBoxHeight = comboBox->height() / 2; const int rowHeight = (comboBox->view()->height() - comboBoxHeight) / comboBox->count(); int index = 1; for (; index <= comboBox->count(); ++index) { if (comboBox->itemData(index, Qt::DisplayRole).toString() == name) { break; } } const QRect itemRect = comboBox->view()->visualRect(comboBox->view()->indexAt(QPoint(0, rowHeight * index))); const QRect target = QRect(itemRect.center(), itemRect.size()); QWidget *parent = mVirtualCursor->parentWidget(); QPoint newPos = comboBox->mapFrom(parent, mVirtualCursor->pos()); mVirtualCursor->setParent(comboBox->view()); mVirtualCursor->move(newPos); mVirtualCursor->raise(); mVirtualCursor->show(); QTimer *timer = new QTimer(); timer->setInterval(100); connect(timer, &QTimer::timeout , [this, comboBox]() { mVirtualCursor->moved(comboBox->view()->viewport()); }); timer->start(); mVirtualCursor->moveToRect(target, duration); timer->stop(); delete timer; QEvent *pressEvent = new QMouseEvent(QMouseEvent::MouseButtonPress , mVirtualCursor->pos() , Qt::LeftButton , Qt::LeftButton , Qt::NoModifier); QEvent *releaseEvent = new QMouseEvent(QMouseEvent::MouseButtonRelease , mVirtualCursor->pos() , Qt::LeftButton , Qt::LeftButton , Qt::NoModifier); QApplication::postEvent(comboBox->view()->viewport(), pressEvent); QApplication::postEvent(comboBox->view()->viewport(), releaseEvent); newPos = comboBox->mapTo(parent, mVirtualCursor->pos()); mVirtualCursor->setParent(parent); mVirtualCursor->move(newPos); mVirtualCursor->show(); } void ScriptAPI::wait(int duration) { if (duration != -1) { QTimer::singleShot(duration, &mEventLoop, SLOT(quit())); } mEventLoop.exec(); } void ScriptAPI::breakWaiting() { mEventLoop.quit(); } void ScriptAPI::changeWindow(QWidget *parent) { mVirtualCursor->setParent(parent); mVirtualCursor->show(); mVirtualCursor->leftButtonPress(parent); mVirtualCursor->leftButtonRelease(parent); } QScriptValue ScriptAPI::pluginUi(const QString &pluginName) { return mScriptEngine.newQObject(mGuiFacade->pluginGuiFacade(pluginName), QScriptEngine::ScriptOwnership); } void ScriptAPI::abortEvaluation() { mScriptEngine.abortEvaluation(); } GuiFacade &ScriptAPI::guiFacade() { return *mGuiFacade; } VirtualCursor &ScriptAPI::virtualCursor() { return *mVirtualCursor; } SceneAPI &ScriptAPI::sceneAPI() { return *mSceneAPI; } void ScriptAPI::scroll(QAbstractScrollArea *area, QWidget *widget, int duration) { const int xcoord = area->verticalScrollBar()->parentWidget()->mapToGlobal(area->verticalScrollBar()->pos()).x(); int ycoord = area->verticalScrollBar()->parentWidget()->mapToGlobal(area->verticalScrollBar()->pos()).y(); mVirtualCursor->moveToPoint(xcoord, ycoord, duration / 2); const int diff = area->verticalScrollBar()->height() - area->verticalScrollBar()->pageStep() + widget->pos().y() * area->verticalScrollBar()->maximum() / widget->parentWidget()->height(); ycoord = ycoord + diff * area->verticalScrollBar()->height() / area->verticalScrollBar()->maximum(); const QPoint target = mVirtualCursor->parentWidget()->mapFromGlobal(QPoint(xcoord, ycoord)); QPropertyAnimation *anim = new QPropertyAnimation(area->verticalScrollBar(), "value"); anim->setDuration(duration / 2); anim->setStartValue(0); anim->setEndValue(diff); connect(anim, &QPropertyAnimation::finished, this, &ScriptAPI::breakWaiting); anim->start(QAbstractAnimation::DeleteWhenStopped); mVirtualCursor->moveToPoint(target.x(), target.y(), duration / 2); } QScriptValue ScriptAPI::ui() { return mScriptEngine.newQObject(mGuiFacade.data(), QScriptEngine::ScriptOwnership); } QScriptValue ScriptAPI::hints() { return mScriptEngine.newQObject(mHintAPI.data(), QScriptEngine::ScriptOwnership); } QScriptValue ScriptAPI::palette() { return mScriptEngine.newQObject(mPaletteAPI.data(), QScriptEngine::ScriptOwnership); } QScriptValue ScriptAPI::scene() { return mScriptEngine.newQObject(mSceneAPI.data(), QScriptEngine::ScriptOwnership); } QScriptValue ScriptAPI::cursor() { return mScriptEngine.newQObject(mVirtualCursor.data(), QScriptEngine::ScriptOwnership); } QScriptValue ScriptAPI::keyboard() { return mScriptEngine.newQObject(mVirtualKeyboard.data(), QScriptEngine::ScriptOwnership); } <commit_msg>Fixed scripting facade objects ownership<commit_after>/* Copyright 2014-2015 QReal Research Group, Dmitry Chernov, Dmitry Mordvinov * * 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 "scriptAPI.h" #include <QtCore/QPropertyAnimation> #include <QtGui/QWidgetList> #include <QtWidgets/QApplication> #include <QtWidgets/QComboBox> #include <qrkernel/exception/exception.h> #include <qrutils/inFile.h> #include <editor/editorView.h> #include <models/commands/createElementCommand.h> #include "qrgui/mainWindow/mainWindow.h" #include "guiFacade.h" #include "virtualCursor.h" #include "virtualKeyboard.h" #include "hintAPI.h" #include "sceneAPI.h" #include "paletteAPI.h" using namespace qReal; using namespace gui; using namespace utils; ScriptAPI::ScriptAPI() : mGuiFacade(nullptr) , mVirtualCursor(nullptr) , mVirtualKeyboard(nullptr) , mSceneAPI(nullptr) , mPaletteAPI(nullptr) , mHintAPI(nullptr) , mScriptEngine(new QScriptEngine) { } ScriptAPI::~ScriptAPI() { } void ScriptAPI::init(MainWindow &mainWindow) { mGuiFacade.reset(new GuiFacade(mainWindow)); mVirtualCursor.reset(new VirtualCursor(*this, &mainWindow)); mVirtualKeyboard.reset(new VirtualKeyboard(*this)); mSceneAPI.reset(new SceneAPI(*this, mainWindow)); mPaletteAPI.reset(new PaletteAPI(*this, mainWindow)); mHintAPI.reset(new HintAPI); const QScriptValue scriptAPI = mScriptEngine.newQObject(this); // This instance will be available in scripts by writing something like "api.wait(100)" mScriptEngine.globalObject().setProperty("api", scriptAPI); } void ScriptAPI::evaluate() { const QString fileName(SettingsManager::value("scriptName").toString()); const QString fileContent = InFile::readAll(fileName); mVirtualCursor->show(); mVirtualCursor->raise(); mScriptEngine.setProcessEventsInterval(20); mScriptEngine.evaluate(fileContent, fileName); abortEvaluation(); } void ScriptAPI::pickComboBoxItem(QComboBox *comboBox, const QString &name, int duration) { const int comboBoxHeight = comboBox->height() / 2; const int rowHeight = (comboBox->view()->height() - comboBoxHeight) / comboBox->count(); int index = 1; for (; index <= comboBox->count(); ++index) { if (comboBox->itemData(index, Qt::DisplayRole).toString() == name) { break; } } const QRect itemRect = comboBox->view()->visualRect(comboBox->view()->indexAt(QPoint(0, rowHeight * index))); const QRect target = QRect(itemRect.center(), itemRect.size()); QWidget *parent = mVirtualCursor->parentWidget(); QPoint newPos = comboBox->mapFrom(parent, mVirtualCursor->pos()); mVirtualCursor->setParent(comboBox->view()); mVirtualCursor->move(newPos); mVirtualCursor->raise(); mVirtualCursor->show(); QTimer *timer = new QTimer(); timer->setInterval(100); connect(timer, &QTimer::timeout , [this, comboBox]() { mVirtualCursor->moved(comboBox->view()->viewport()); }); timer->start(); mVirtualCursor->moveToRect(target, duration); timer->stop(); delete timer; QEvent *pressEvent = new QMouseEvent(QMouseEvent::MouseButtonPress , mVirtualCursor->pos() , Qt::LeftButton , Qt::LeftButton , Qt::NoModifier); QEvent *releaseEvent = new QMouseEvent(QMouseEvent::MouseButtonRelease , mVirtualCursor->pos() , Qt::LeftButton , Qt::LeftButton , Qt::NoModifier); QApplication::postEvent(comboBox->view()->viewport(), pressEvent); QApplication::postEvent(comboBox->view()->viewport(), releaseEvent); newPos = comboBox->mapTo(parent, mVirtualCursor->pos()); mVirtualCursor->setParent(parent); mVirtualCursor->move(newPos); mVirtualCursor->show(); } void ScriptAPI::wait(int duration) { if (duration != -1) { QTimer::singleShot(duration, &mEventLoop, SLOT(quit())); } mEventLoop.exec(); } void ScriptAPI::breakWaiting() { mEventLoop.quit(); } void ScriptAPI::changeWindow(QWidget *parent) { mVirtualCursor->setParent(parent); mVirtualCursor->show(); mVirtualCursor->leftButtonPress(parent); mVirtualCursor->leftButtonRelease(parent); } QScriptValue ScriptAPI::pluginUi(const QString &pluginName) { return mScriptEngine.newQObject(mGuiFacade->pluginGuiFacade(pluginName), QScriptEngine::QtOwnership); } void ScriptAPI::abortEvaluation() { mScriptEngine.abortEvaluation(); } GuiFacade &ScriptAPI::guiFacade() { return *mGuiFacade; } VirtualCursor &ScriptAPI::virtualCursor() { return *mVirtualCursor; } SceneAPI &ScriptAPI::sceneAPI() { return *mSceneAPI; } void ScriptAPI::scroll(QAbstractScrollArea *area, QWidget *widget, int duration) { const int xcoord = area->verticalScrollBar()->parentWidget()->mapToGlobal(area->verticalScrollBar()->pos()).x(); int ycoord = area->verticalScrollBar()->parentWidget()->mapToGlobal(area->verticalScrollBar()->pos()).y(); mVirtualCursor->moveToPoint(xcoord, ycoord, duration / 2); const int diff = area->verticalScrollBar()->height() - area->verticalScrollBar()->pageStep() + widget->pos().y() * area->verticalScrollBar()->maximum() / widget->parentWidget()->height(); ycoord = ycoord + diff * area->verticalScrollBar()->height() / area->verticalScrollBar()->maximum(); const QPoint target = mVirtualCursor->parentWidget()->mapFromGlobal(QPoint(xcoord, ycoord)); QPropertyAnimation *anim = new QPropertyAnimation(area->verticalScrollBar(), "value"); anim->setDuration(duration / 2); anim->setStartValue(0); anim->setEndValue(diff); connect(anim, &QPropertyAnimation::finished, this, &ScriptAPI::breakWaiting); anim->start(QAbstractAnimation::DeleteWhenStopped); mVirtualCursor->moveToPoint(target.x(), target.y(), duration / 2); } QScriptValue ScriptAPI::ui() { return mScriptEngine.newQObject(mGuiFacade.data(), QScriptEngine::QtOwnership); } QScriptValue ScriptAPI::hints() { return mScriptEngine.newQObject(mHintAPI.data(), QScriptEngine::QtOwnership); } QScriptValue ScriptAPI::palette() { return mScriptEngine.newQObject(mPaletteAPI.data(), QScriptEngine::QtOwnership); } QScriptValue ScriptAPI::scene() { return mScriptEngine.newQObject(mSceneAPI.data(), QScriptEngine::QtOwnership); } QScriptValue ScriptAPI::cursor() { return mScriptEngine.newQObject(mVirtualCursor.data(), QScriptEngine::QtOwnership); } QScriptValue ScriptAPI::keyboard() { return mScriptEngine.newQObject(mVirtualKeyboard.data(), QScriptEngine::QtOwnership); } <|endoftext|>
<commit_before>// Copyright 2019 DeepMind Technologies Ltd. All rights reserved. // // 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<functional> #include <map> #include <string> #include <vector> #include "open_spiel/abseil-cpp/absl/algorithm/container.h" #include "open_spiel/abseil-cpp/absl/strings/str_cat.h" #include "open_spiel/abseil-cpp/absl/strings/str_join.h" #include "open_spiel/algorithms/mcts.h" #include "open_spiel/abseil-cpp/absl/flags/flag.h" #include "open_spiel/abseil-cpp/absl/flags/parse.h" #include "open_spiel/spiel.h" #include "open_spiel/spiel_utils.h" ABSL_FLAG(std::string, game, "tic_tac_toe", "The name of the game to play."); std::string Success() { return "=\n\n"; } std::string Success(const std::string& s) { return absl::StrCat("= ", s, "\n\n"); } std::string Failure(const std::string& s) { return absl::StrCat("? ", s, "\n\n"); } std::unique_ptr<open_spiel::Bot> MakeBot( const open_spiel::Game& game, std::shared_ptr<open_spiel::algorithms::Evaluator> evaluator) { return std::make_unique<open_spiel::algorithms::MCTSBot>( game, evaluator, /*uct_c=*/2, /*max_simulations=*/1000, /*max_memory_mb=*/0, /*solve=*/true, /*seed=*/0, /*verbose=*/false); } // Implements the Go Text Protocol, GTP, which is a text based protocol for // communication with computer Go programs // (https://www.lysator.liu.se/~gunnar/gtp/). This offers the open_spiel games // and the mcts bot as a command line gtp server, which can be played against // third party programs, or used on the command line directly. int main(int argc, char** argv) { absl::ParseCommandLine(argc, argv); std::string game_name = absl::GetFlag(FLAGS_game); std::shared_ptr<const open_spiel::Game> game = open_spiel::LoadGame(game_name); std::unique_ptr<open_spiel::State> state = game->NewInitialState(); auto evaluator = std::make_shared<open_spiel::algorithms::RandomRolloutEvaluator>( /*n_rollouts=*/1, /*seed=*/0); std::unique_ptr<open_spiel::Bot> bot = MakeBot(*game, evaluator); using Args = std::vector<std::string>; std::map<std::string, std::function<std::string(const Args&)>> cmds = { {"name", [](const Args&) { return Success("open_spiel"); }}, {"version", [](const Args&) { return Success("unknown"); }}, {"protocol_version", [](const Args&) { return Success("2"); }}, {"quit", [](const Args&) { return Success(); }}, {"list_commands", [&cmds](const Args& args) { std::vector<std::string> keys; keys.reserve(cmds.size()); for (auto const& item : cmds) { keys.push_back(item.first); } return Success(absl::StrJoin(keys, " ")); }}, {"known_command", [&cmds](const Args& args) { if (args.empty()) { return Failure("Not enough args"); } return Success(cmds.find(args[0]) == cmds.end() ? "false" : "true"); }}, {"known_games", [](const Args& args) { return Success(absl::StrJoin(open_spiel::RegisteredGames(), " ")); }}, {"game", [&bot, &game, &state, &evaluator](const Args& args) { if (args.empty()) { return Success(game->ToString()); } game = open_spiel::LoadGame(args[0]); state = game->NewInitialState(); bot = MakeBot(*game, evaluator); return Success(game->ToString()); }}, {"boardsize", [&bot, &game, &state, &evaluator](const Args& args) { open_spiel::GameParameters params = game->GetParameters(); if (params.find("board_size") == params.end()) { return Failure("Game doesn't support setting the board size"); } if (args.empty()) { return Success(params["board_size"].ToString()); } int board_size; if (!absl::SimpleAtoi(args[0], &board_size)) { return Failure("Failed to parse first arg as an int"); } params["board_size"] = open_spiel::GameParameter(board_size); game = open_spiel::LoadGame(game->GetType().short_name, params); state = game->NewInitialState(); bot = MakeBot(*game, evaluator); return Success(); }}, {"play", [&bot, &state](const Args& args) { if (args.size() < 2) { return Failure("Not enough args"); } // Ignore player arg, assume it's always the current player. const std::string& action_str = args[1]; for (const open_spiel::Action action : state->LegalActions()) { if (action_str == state->ActionToString(action)) { bot->InformAction(*state, state->CurrentPlayer(), action); state->ApplyAction(action); return Success(); } } return Failure("Invalid action"); }}, {"genmove", [&bot, &state](const Args& args) { if (state->IsTerminal()) { return Failure("Game is already over"); } // Ignore player arg, assume it's always the current player. open_spiel::Action action = bot->Step(*state); std::string action_str = state->ActionToString(action); state->ApplyAction(action); return Success(action_str); }}, {"clear_board", [&bot, &game, &state](const Args& args) { state = game->NewInitialState(); bot->Restart(); return Success(); }}, {"undo", [&bot, &game, &state](const Args& args) { std::vector<open_spiel::Action> history = state->History(); int count = 1; if (!args.empty() && !absl::SimpleAtoi(args[0], &count)) { return Failure("Failed to parse first arg as an int"); } if (history.size() < count) { return Failure(absl::StrCat( "Can't undo ", count, " moves from game of length ", history.size())); } state = game->NewInitialState(); bot->Restart(); for (int i = 0; i < history.size() - count; ++i) { bot->InformAction(*state, state->CurrentPlayer(), history[i]); state->ApplyAction(history[i]); } return Success(); }}, {"showboard", [&state](const Args& args) { return Success("\n" + state->ToString()); }}, {"history", [&state](const Args& args) { return Success(state->HistoryString()); }}, {"is_terminal", [&state](const Args& args) { return Success(state->IsTerminal() ? "true" : "false"); }}, {"current_player", [&state](const Args& args) { return Success(absl::StrCat(state->CurrentPlayer())); }}, {"returns", [&state](const Args& args) { return Success(absl::StrJoin(state->Returns(), " ")); }}, {"legal_actions", [&state](const Args& args) { std::vector<std::string> actions; std::vector<open_spiel::Action> legal_actions = state->LegalActions(); actions.reserve(legal_actions.size()); for (const open_spiel::Action action : legal_actions) { actions.push_back(state->ActionToString(action)); } return Success(absl::StrJoin(actions, " ")); }}, }; std::cerr << "Welcome to OpenSpiel GTP interface. Try `list_commands`." << std::endl << std::endl; for (std::string line; std::getline(std::cin, line);) { std::vector<std::string> parts = absl::StrSplit(line, ' '); if (parts.empty()) continue; std::string& cmd = parts[0]; auto cmd_it = cmds.find(cmd); if (cmd_it == cmds.end()) { std::cout << Failure("unknown command"); continue; } Args args(parts.begin() + 1, parts.end()); std::cout << cmd_it->second(args); if (cmd == "quit") { break; } } return 0; } <commit_msg>Reinstate std::move that was mistakenly removed in https://github.com/deepmind/open_spiel/commit/5c7c38d696052262080a3e4dca96cbeebce55cbc<commit_after>// Copyright 2019 DeepMind Technologies Ltd. All rights reserved. // // 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<functional> #include <map> #include <string> #include <vector> #include "open_spiel/abseil-cpp/absl/algorithm/container.h" #include "open_spiel/abseil-cpp/absl/strings/str_cat.h" #include "open_spiel/abseil-cpp/absl/strings/str_join.h" #include "open_spiel/algorithms/mcts.h" #include "open_spiel/abseil-cpp/absl/flags/flag.h" #include "open_spiel/abseil-cpp/absl/flags/parse.h" #include "open_spiel/spiel.h" #include "open_spiel/spiel_utils.h" ABSL_FLAG(std::string, game, "tic_tac_toe", "The name of the game to play."); std::string Success() { return "=\n\n"; } std::string Success(const std::string& s) { return absl::StrCat("= ", s, "\n\n"); } std::string Failure(const std::string& s) { return absl::StrCat("? ", s, "\n\n"); } std::unique_ptr<open_spiel::Bot> MakeBot( const open_spiel::Game& game, std::shared_ptr<open_spiel::algorithms::Evaluator> evaluator) { return std::make_unique<open_spiel::algorithms::MCTSBot>( game, std::move(evaluator), /*uct_c=*/2, /*max_simulations=*/1000, /*max_memory_mb=*/0, /*solve=*/true, /*seed=*/0, /*verbose=*/false); } // Implements the Go Text Protocol, GTP, which is a text based protocol for // communication with computer Go programs // (https://www.lysator.liu.se/~gunnar/gtp/). This offers the open_spiel games // and the mcts bot as a command line gtp server, which can be played against // third party programs, or used on the command line directly. int main(int argc, char** argv) { absl::ParseCommandLine(argc, argv); std::string game_name = absl::GetFlag(FLAGS_game); std::shared_ptr<const open_spiel::Game> game = open_spiel::LoadGame(game_name); std::unique_ptr<open_spiel::State> state = game->NewInitialState(); auto evaluator = std::make_shared<open_spiel::algorithms::RandomRolloutEvaluator>( /*n_rollouts=*/1, /*seed=*/0); std::unique_ptr<open_spiel::Bot> bot = MakeBot(*game, evaluator); using Args = std::vector<std::string>; std::map<std::string, std::function<std::string(const Args&)>> cmds = { {"name", [](const Args&) { return Success("open_spiel"); }}, {"version", [](const Args&) { return Success("unknown"); }}, {"protocol_version", [](const Args&) { return Success("2"); }}, {"quit", [](const Args&) { return Success(); }}, {"list_commands", [&cmds](const Args& args) { std::vector<std::string> keys; keys.reserve(cmds.size()); for (auto const& item : cmds) { keys.push_back(item.first); } return Success(absl::StrJoin(keys, " ")); }}, {"known_command", [&cmds](const Args& args) { if (args.empty()) { return Failure("Not enough args"); } return Success(cmds.find(args[0]) == cmds.end() ? "false" : "true"); }}, {"known_games", [](const Args& args) { return Success(absl::StrJoin(open_spiel::RegisteredGames(), " ")); }}, {"game", [&bot, &game, &state, &evaluator](const Args& args) { if (args.empty()) { return Success(game->ToString()); } game = open_spiel::LoadGame(args[0]); state = game->NewInitialState(); bot = MakeBot(*game, evaluator); return Success(game->ToString()); }}, {"boardsize", [&bot, &game, &state, &evaluator](const Args& args) { open_spiel::GameParameters params = game->GetParameters(); if (params.find("board_size") == params.end()) { return Failure("Game doesn't support setting the board size"); } if (args.empty()) { return Success(params["board_size"].ToString()); } int board_size; if (!absl::SimpleAtoi(args[0], &board_size)) { return Failure("Failed to parse first arg as an int"); } params["board_size"] = open_spiel::GameParameter(board_size); game = open_spiel::LoadGame(game->GetType().short_name, params); state = game->NewInitialState(); bot = MakeBot(*game, evaluator); return Success(); }}, {"play", [&bot, &state](const Args& args) { if (args.size() < 2) { return Failure("Not enough args"); } // Ignore player arg, assume it's always the current player. const std::string& action_str = args[1]; for (const open_spiel::Action action : state->LegalActions()) { if (action_str == state->ActionToString(action)) { bot->InformAction(*state, state->CurrentPlayer(), action); state->ApplyAction(action); return Success(); } } return Failure("Invalid action"); }}, {"genmove", [&bot, &state](const Args& args) { if (state->IsTerminal()) { return Failure("Game is already over"); } // Ignore player arg, assume it's always the current player. open_spiel::Action action = bot->Step(*state); std::string action_str = state->ActionToString(action); state->ApplyAction(action); return Success(action_str); }}, {"clear_board", [&bot, &game, &state](const Args& args) { state = game->NewInitialState(); bot->Restart(); return Success(); }}, {"undo", [&bot, &game, &state](const Args& args) { std::vector<open_spiel::Action> history = state->History(); int count = 1; if (!args.empty() && !absl::SimpleAtoi(args[0], &count)) { return Failure("Failed to parse first arg as an int"); } if (history.size() < count) { return Failure(absl::StrCat( "Can't undo ", count, " moves from game of length ", history.size())); } state = game->NewInitialState(); bot->Restart(); for (int i = 0; i < history.size() - count; ++i) { bot->InformAction(*state, state->CurrentPlayer(), history[i]); state->ApplyAction(history[i]); } return Success(); }}, {"showboard", [&state](const Args& args) { return Success("\n" + state->ToString()); }}, {"history", [&state](const Args& args) { return Success(state->HistoryString()); }}, {"is_terminal", [&state](const Args& args) { return Success(state->IsTerminal() ? "true" : "false"); }}, {"current_player", [&state](const Args& args) { return Success(absl::StrCat(state->CurrentPlayer())); }}, {"returns", [&state](const Args& args) { return Success(absl::StrJoin(state->Returns(), " ")); }}, {"legal_actions", [&state](const Args& args) { std::vector<std::string> actions; std::vector<open_spiel::Action> legal_actions = state->LegalActions(); actions.reserve(legal_actions.size()); for (const open_spiel::Action action : legal_actions) { actions.push_back(state->ActionToString(action)); } return Success(absl::StrJoin(actions, " ")); }}, }; std::cerr << "Welcome to OpenSpiel GTP interface. Try `list_commands`." << std::endl << std::endl; for (std::string line; std::getline(std::cin, line);) { std::vector<std::string> parts = absl::StrSplit(line, ' '); if (parts.empty()) continue; std::string& cmd = parts[0]; auto cmd_it = cmds.find(cmd); if (cmd_it == cmds.end()) { std::cout << Failure("unknown command"); continue; } Args args(parts.begin() + 1, parts.end()); std::cout << cmd_it->second(args); if (cmd == "quit") { break; } } return 0; } <|endoftext|>
<commit_before>#include "DataLikelihood.h" #include "multichoose.h" #include "multipermute.h" long double probObservedAllelesGivenGenotype( Sample& sample, Genotype& genotype, double dependenceFactor, bool useMapQ, Bias& observationBias, bool standardGLs, vector<Allele>& genotypeAlleles, Contamination& contaminations, map<string, double>& freqs ) { cerr << "P(" << genotype << " given" << endl << sample; int observationCount = sample.observationCount(); vector<long double> alleleProbs = genotype.alleleProbabilities(observationBias); vector<int> observationCounts = genotype.alleleObservationCounts(sample); int countOut = 0; double countIn = 0; long double prodQout = 0; // the probability that the reads not in the genotype are all wrong long double prodSample = 0; // X me long double probObsGivenGt = 0; if (standardGLs) { for (Sample::iterator s = sample.begin(); s != sample.end(); ++s) { const string& base = s->first; if (!genotype.containsAllele(base)) { vector<Allele*>& alleles = s->second; if (useMapQ) { for (vector<Allele*>::iterator a = alleles.begin(); a != alleles.end(); ++a) { // take the lesser of mapping quality and base quality (in log space) prodQout += max((*a)->lnquality, (*a)->lnmapQuality); } } else { for (vector<Allele*>::iterator a = alleles.begin(); a != alleles.end(); ++a) { prodQout += (*a)->lnquality; } } countOut += alleles.size(); } } } else { vector<Allele*> emptyA; vector<Allele*> emptyB; for (set<string>::iterator c = sample.supportedAlleles.begin(); c != sample.supportedAlleles.end(); ++c) { vector<Allele*>* alleles = &emptyA; Sample::iterator si = sample.find(*c); if (si != sample.end()) alleles = &si->second; vector<Allele*>* partials = &emptyB; map<string, vector<Allele*> >::iterator pi = sample.partialSupport.find(*c); if (pi != sample.partialSupport.end()) partials = &pi->second; bool onPartials = false; vector<Allele*>::iterator a = alleles->begin(); bool hasPartials = !partials->empty(); for ( ; (!hasPartials && a != alleles->end()) || a != partials->end(); ++a) { if (a == alleles->end()) { if (hasPartials) { a = partials->begin(); onPartials = true; } else { break; } } Allele& obs = **a; cerr << "observation: " << obs << endl; long double probi = 0; ContaminationEstimate& contamination = contaminations.of(obs.readGroupID); double scale = 1; // note that this will underflow if we have mapping quality = 0 // we guard against this externally, by ignoring such alignments (quality has to be > MQL0) long double qual = (1.0 - exp(obs.lnquality)) * (1.0 - exp(obs.lnmapQuality)); //cerr << "qual = " << qual << endl; if (onPartials) { map<Allele*, set<Allele*> >::iterator r = sample.reversePartials.find(*a); if (r != sample.reversePartials.end()) { if (sample.reversePartials[*a].empty()) { //cerr << "partial " << *a << " has empty reverse" << endl; exit(1); } //cerr << "partial " << *a << " supports potentially " << sample.reversePartials[*a].size() << " alleles : "; /* for (set<Allele*>::iterator m = sample.reversePartials[*a].begin(); m != sample.reversePartials[*a].end(); ++m) cerr << **m << " "; cerr << endl; */ scale = (double)1/(double)sample.reversePartials[*a].size(); } } // TODO add partial obs, now that we have them recorded // how does this work? // each partial obs is recorded as supporting, but with observation probability scaled by the number of possible haplotypes it supports bool isInGenotype = false; long double q = 0; // for each of the unique genotype alleles for (vector<Allele>::iterator b = genotypeAlleles.begin(); b != genotypeAlleles.end(); ++b) { Allele& allele = *b; const string& base = b->currentBase; if (obs.currentBase == base || (onPartials && sample.observationSupports(*a, &*b))) { isInGenotype = true; // here qual represents: // // p(correct base ∧ correct mapping) // or // qual = (1.0 - exp(obs.lnquality)) * (1.0 - exp(obs.lnmapQuality)) // // we assign it to q when obs.currentBase // is the same as the base of the genotype //q = qual; } else { // and when the two disagree, we take a penalty //q = 1 - qual; } } long double asampl = genotype.alleleSamplingProb(obs); cerr << genotype << ".alleleSamplingProb(" << obs << ") = " << asampl << endl; if (asampl == 0) { // scale by frequency of (this) possibly contaminating allele asampl = contamination.probRefGivenHomAlt; } else if (asampl == 1) { // scale by frequency of (other) possibly contaminating alleles asampl = 1 - contamination.probRefGivenHomAlt; } else { //if (genotype.ploidy == 2) { // to deal with polyploids // note that this reduces to 1 for diploid heterozygotes //double scale = asampl / 0.5; // this term captures reference bias if (obs.isReference()) { asampl *= (contamination.probRefGivenHet / 0.5); } else { asampl *= ((1 - contamination.probRefGivenHet) / 0.5); } } if (!isInGenotype) { if (onPartials) { q *= scale; // distribute partial support evenly across supported haplotypes } //double freq = freqs[base]; cerr << q << endl; //probi += log(1 - q); prodQout += log(1 - q); //cerr << "prodQout = " << prodQout << endl; } else { //cerr << "asampl = " << asampl << endl; //cerr << "q = " << q << endl; // here we make P(read|genotype) = p(allele|genotype) * p(read|allele) //cerr << "probi = " << probi << endl; cerr << asampl << endl; prodSample += log(asampl); //cerr << "prodSample = " << prodSample << endl; } if (isInGenotype) { countIn += scale; } //long double lnprobi = log(min(probi, (long double) 1.0)); //probObsGivenGt += lnprobi; //cerr << "countIn = " << countIn << endl; // bound to (0,1] if (probi < 0) { long double lnprobi = probi; //log(min(probi, (long double) 1.0)); //cerr << "lnprobi = " << lnprobi << endl; probObsGivenGt += lnprobi; cerr << "probObsGivenGt = " << probObsGivenGt << endl; } } } } // read dependence factor, asymptotically downgrade quality values of // successive reads to dependenceFactor * quality if (standardGLs) { if (countOut > 1) { prodQout *= (1 + (countOut - 1) * dependenceFactor) / countOut; } if (sum(observationCounts) == 0) { return prodQout; } else { cerr << "P(obs|" << genotype << ") = " << prodQout + multinomialSamplingProbLn(alleleProbs, observationCounts) << endl << endl << string(80, '@') << endl << endl; return prodQout + multinomialSamplingProbLn(alleleProbs, observationCounts); //return prodQout + samplingProbLn(alleleProbs, observationCounts); } } else { // read dependence factor, but inverted to deal with the new GL implementation /* if (countIn > 1) { probObsGivenGt *= (1 + (countIn - 1) * dependenceFactor) / countIn; } */ //cerr << "_ P(obs|" << genotype << ") = " << probObsGivenGt << endl << endl << string(80, '@') << endl << endl; cerr << "->P(obs|"<<genotype << ") = " << prodQout << " + " << prodSample << " = " << prodQout + prodSample << endl; return prodQout + prodSample; return isinf(probObsGivenGt) ? 0 : probObsGivenGt; } } vector<pair<Genotype*, long double> > probObservedAllelesGivenGenotypes( Sample& sample, vector<Genotype*>& genotypes, double dependenceFactor, bool useMapQ, Bias& observationBias, bool standardGLs, vector<Allele>& genotypeAlleles, Contamination& contaminations, map<string, double>& freqs ) { vector<pair<Genotype*, long double> > results; for (vector<Genotype*>::iterator g = genotypes.begin(); g != genotypes.end(); ++g) { results.push_back( make_pair(*g, probObservedAllelesGivenGenotype( sample, **g, dependenceFactor, useMapQ, observationBias, standardGLs, genotypeAlleles, contaminations, freqs))); } return results; } <commit_msg>comment out debugging lines<commit_after>#include "DataLikelihood.h" #include "multichoose.h" #include "multipermute.h" long double probObservedAllelesGivenGenotype( Sample& sample, Genotype& genotype, double dependenceFactor, bool useMapQ, Bias& observationBias, bool standardGLs, vector<Allele>& genotypeAlleles, Contamination& contaminations, map<string, double>& freqs ) { // cerr << "P(" << genotype << " given" << endl << sample; int observationCount = sample.observationCount(); vector<long double> alleleProbs = genotype.alleleProbabilities(observationBias); vector<int> observationCounts = genotype.alleleObservationCounts(sample); int countOut = 0; double countIn = 0; long double prodQout = 0; // the probability that the reads not in the genotype are all wrong long double prodSample = 0; // X me long double probObsGivenGt = 0; if (standardGLs) { for (Sample::iterator s = sample.begin(); s != sample.end(); ++s) { const string& base = s->first; if (!genotype.containsAllele(base)) { vector<Allele*>& alleles = s->second; if (useMapQ) { for (vector<Allele*>::iterator a = alleles.begin(); a != alleles.end(); ++a) { // take the lesser of mapping quality and base quality (in log space) prodQout += max((*a)->lnquality, (*a)->lnmapQuality); } } else { for (vector<Allele*>::iterator a = alleles.begin(); a != alleles.end(); ++a) { prodQout += (*a)->lnquality; } } countOut += alleles.size(); } } } else { vector<Allele*> emptyA; vector<Allele*> emptyB; for (set<string>::iterator c = sample.supportedAlleles.begin(); c != sample.supportedAlleles.end(); ++c) { vector<Allele*>* alleles = &emptyA; Sample::iterator si = sample.find(*c); if (si != sample.end()) alleles = &si->second; vector<Allele*>* partials = &emptyB; map<string, vector<Allele*> >::iterator pi = sample.partialSupport.find(*c); if (pi != sample.partialSupport.end()) partials = &pi->second; bool onPartials = false; vector<Allele*>::iterator a = alleles->begin(); bool hasPartials = !partials->empty(); for ( ; (!hasPartials && a != alleles->end()) || a != partials->end(); ++a) { if (a == alleles->end()) { if (hasPartials) { a = partials->begin(); onPartials = true; } else { break; } } Allele& obs = **a; //cerr << "observation: " << obs << endl; long double probi = 0; ContaminationEstimate& contamination = contaminations.of(obs.readGroupID); double scale = 1; // note that this will underflow if we have mapping quality = 0 // we guard against this externally, by ignoring such alignments (quality has to be > MQL0) long double qual = (1.0 - exp(obs.lnquality)) * (1.0 - exp(obs.lnmapQuality)); //cerr << "qual = " << qual << endl; if (onPartials) { map<Allele*, set<Allele*> >::iterator r = sample.reversePartials.find(*a); if (r != sample.reversePartials.end()) { if (sample.reversePartials[*a].empty()) { //cerr << "partial " << *a << " has empty reverse" << endl; exit(1); } //cerr << "partial " << *a << " supports potentially " << sample.reversePartials[*a].size() << " alleles : "; /* for (set<Allele*>::iterator m = sample.reversePartials[*a].begin(); m != sample.reversePartials[*a].end(); ++m) cerr << **m << " "; cerr << endl; */ scale = (double)1/(double)sample.reversePartials[*a].size(); } } // TODO add partial obs, now that we have them recorded // how does this work? // each partial obs is recorded as supporting, but with observation probability scaled by the number of possible haplotypes it supports bool isInGenotype = false; long double q = 0; // for each of the unique genotype alleles for (vector<Allele>::iterator b = genotypeAlleles.begin(); b != genotypeAlleles.end(); ++b) { Allele& allele = *b; const string& base = b->currentBase; if (obs.currentBase == base || (onPartials && sample.observationSupports(*a, &*b))) { isInGenotype = true; // here qual represents: // // p(correct base ∧ correct mapping) // or // qual = (1.0 - exp(obs.lnquality)) * (1.0 - exp(obs.lnmapQuality)) // // we assign it to q when obs.currentBase // is the same as the base of the genotype //q = qual; } else { // and when the two disagree, we take a penalty //q = 1 - qual; } } long double asampl = genotype.alleleSamplingProb(obs); //cerr << genotype << ".alleleSamplingProb(" << obs << ") = " << asampl << endl; if (asampl == 0) { // scale by frequency of (this) possibly contaminating allele asampl = contamination.probRefGivenHomAlt; } else if (asampl == 1) { // scale by frequency of (other) possibly contaminating alleles asampl = 1 - contamination.probRefGivenHomAlt; } else { //if (genotype.ploidy == 2) { // to deal with polyploids // note that this reduces to 1 for diploid heterozygotes //double scale = asampl / 0.5; // this term captures reference bias if (obs.isReference()) { asampl *= (contamination.probRefGivenHet / 0.5); } else { asampl *= ((1 - contamination.probRefGivenHet) / 0.5); } } if (!isInGenotype) { if (onPartials) { q *= scale; // distribute partial support evenly across supported haplotypes } //double freq = freqs[base]; //cerr << q << endl; //probi += log(1 - q); prodQout += log(1 - q); //cerr << "prodQout = " << prodQout << endl; } else { //cerr << "asampl = " << asampl << endl; //cerr << "q = " << q << endl; // here we make P(read|genotype) = p(allele|genotype) * p(read|allele) //cerr << "probi = " << probi << endl; //cerr << asampl << endl; prodSample += log(asampl); //cerr << "prodSample = " << prodSample << endl; } if (isInGenotype) { countIn += scale; } //long double lnprobi = log(min(probi, (long double) 1.0)); //probObsGivenGt += lnprobi; //cerr << "countIn = " << countIn << endl; // bound to (0,1] if (probi < 0) { long double lnprobi = probi; //log(min(probi, (long double) 1.0)); //cerr << "lnprobi = " << lnprobi << endl; probObsGivenGt += lnprobi; //cerr << "probObsGivenGt = " << probObsGivenGt << endl; } } } } // read dependence factor, asymptotically downgrade quality values of // successive reads to dependenceFactor * quality if (standardGLs) { if (countOut > 1) { prodQout *= (1 + (countOut - 1) * dependenceFactor) / countOut; } if (sum(observationCounts) == 0) { return prodQout; } else { //cerr << "P(obs|" << genotype << ") = " << prodQout + multinomialSamplingProbLn(alleleProbs, observationCounts) << endl << endl << string(80, '@') << endl << endl; return prodQout + multinomialSamplingProbLn(alleleProbs, observationCounts); //return prodQout + samplingProbLn(alleleProbs, observationCounts); } } else { // read dependence factor, but inverted to deal with the new GL implementation /* if (countIn > 1) { probObsGivenGt *= (1 + (countIn - 1) * dependenceFactor) / countIn; } */ //cerr << "_ P(obs|" << genotype << ") = " << probObsGivenGt << endl << endl << string(80, '@') << endl << endl; //cerr << "->P(obs|"<<genotype << ") = " << prodQout << " + " << prodSample << " = " << prodQout + prodSample << endl; return prodQout + prodSample; return isinf(probObsGivenGt) ? 0 : probObsGivenGt; } } vector<pair<Genotype*, long double> > probObservedAllelesGivenGenotypes( Sample& sample, vector<Genotype*>& genotypes, double dependenceFactor, bool useMapQ, Bias& observationBias, bool standardGLs, vector<Allele>& genotypeAlleles, Contamination& contaminations, map<string, double>& freqs ) { vector<pair<Genotype*, long double> > results; for (vector<Genotype*>::iterator g = genotypes.begin(); g != genotypes.end(); ++g) { results.push_back( make_pair(*g, probObservedAllelesGivenGenotype( sample, **g, dependenceFactor, useMapQ, observationBias, standardGLs, genotypeAlleles, contaminations, freqs))); } return results; } <|endoftext|>
<commit_before>/* * Software License Agreement (BSD License) * * Copyright (c) 2011, Willow Garage, Inc. * 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 Willow Garage, Inc. 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 <boost/thread/thread.hpp> #include <boost/date_time/posix_time/posix_time.hpp> #include <pcl/point_cloud.h> #include <pcl/point_types.h> #include <pcl/io/openni_grabber.h> #include <pcl/visualization/cloud_viewer.h> #include <pcl/io/openni_camera/openni_driver.h> #include <pcl/keypoints/uniform_sampling.h> #include <pcl/console/parse.h> #include <pcl/common/time.h> #define FPS_CALC(_WHAT_) \ do \ { \ static unsigned count = 0;\ static double last = pcl::getTime ();\ double now = pcl::getTime (); \ ++count; \ if (now - last >= 1.0) \ { \ std::cout << "Average framerate("<< _WHAT_ << "): " << double(count)/double(now - last) << " Hz" << std::endl; \ count = 0; \ last = now; \ } \ }while(false) class OpenNIUniformSampling { public: typedef pcl::PointCloud<pcl::PointXYZRGB> Cloud; typedef typename Cloud::Ptr CloudPtr; typedef typename Cloud::ConstPtr CloudConstPtr; OpenNIUniformSampling (const std::string& device_id = "", float leaf_size = 0.05) : viewer ("PCL OpenNI PassThrough Viewer") , device_id_(device_id) { pass_.setRadiusSearch (leaf_size); } void cloud_cb_ (const CloudConstPtr& cloud) { boost::mutex::scoped_lock lock (mtx_); FPS_CALC ("computation"); cloud_.reset (new Cloud); indices_.reset (new pcl::PointCloud<int>); keypoints_.reset (new pcl::PointCloud<pcl::PointXYZ>); // Computation goes here pass_.setInputCloud (cloud); pass_.compute (*indices_); *cloud_ = *cloud; pcl::copyPointCloud<pcl::PointXYZRGB, pcl::PointXYZ> (*cloud, indices_->points, *keypoints_); } void viz_cb (pcl::visualization::PCLVisualizer& viz) { boost::mutex::scoped_lock lock (mtx_); if (!keypoints_ && !cloud_) { boost::this_thread::sleep(boost::posix_time::seconds(1)); return; } FPS_CALC ("visualization"); viz.removePointCloud ("raw"); pcl::visualization::PointCloudColorHandlerRGBField<pcl::PointXYZRGB> color_handler (cloud_); viz.addPointCloud<pcl::PointXYZRGB> (cloud_, color_handler, "raw"); if (!viz.updatePointCloud<pcl::PointXYZ> (keypoints_, "keypoints")) { viz.addPointCloud<pcl::PointXYZ> (keypoints_, "keypoints"); viz.setPointCloudRenderingProperties (pcl::visualization::PCL_VISUALIZER_POINT_SIZE, 5.0, "keypoints"); viz.resetCameraViewpoint ("keypoints"); } } void run () { pcl::Grabber* interface = new pcl::OpenNIGrabber (device_id_); boost::function<void (const CloudConstPtr&)> f = boost::bind (&OpenNIUniformSampling::cloud_cb_, this, _1); boost::signals2::connection c = interface->registerCallback (f); viewer.runOnVisualizationThread (boost::bind(&OpenNIUniformSampling::viz_cb, this, _1), "viz_cb"); interface->start (); while (!viewer.wasStopped ()) { boost::this_thread::sleep(boost::posix_time::seconds(1)); } interface->stop (); } pcl::UniformSampling<pcl::PointXYZRGB> pass_; pcl::visualization::CloudViewer viewer; std::string device_id_; boost::mutex mtx_; CloudPtr cloud_; pcl::PointCloud<pcl::PointXYZ>::Ptr keypoints_; pcl::PointCloud<int>::Ptr indices_; }; void usage (char ** argv) { std::cout << "usage: " << argv[0] << " <device_id> <options>\n\n" << "where options are:\n" << " -leaf X :: set the UniformSampling leaf size (default: 0.01)\n"; openni_wrapper::OpenNIDriver& driver = openni_wrapper::OpenNIDriver::getInstance (); if (driver.getNumberDevices () > 0) { for (unsigned deviceIdx = 0; deviceIdx < driver.getNumberDevices (); ++deviceIdx) { cout << "Device: " << deviceIdx + 1 << ", vendor: " << driver.getVendorName (deviceIdx) << ", product: " << driver.getProductName (deviceIdx) << ", connected: " << (int)driver.getBus (deviceIdx) << " @ " << (int)driver.getAddress (deviceIdx) << ", serial number: \'" << driver.getSerialNumber (deviceIdx) << "\'" << endl; cout << "device_id may be #1, #2, ... for the first second etc device in the list or" << endl << " bus@address for the device connected to a specific usb-bus / address combination (works only in Linux) or" << endl << " <serial-number> (only in Linux and for devices which provide serial numbers)" << endl; } } else cout << "No devices connected." << endl; } int main (int argc, char ** argv) { if (argc < 2) { usage (argv); return 1; } std::string arg (argv[1]); if (arg == "--help" || arg == "-h") { usage (argv); return 1; } double leaf_res = 0.05; pcl::console::parse_argument (argc, argv, "-leaf", leaf_res); PCL_INFO ("Using %f as a leaf size for UniformSampling.\n", leaf_res); pcl::OpenNIGrabber grabber (arg); OpenNIUniformSampling v (arg, leaf_res); v.run (); return (0); } <commit_msg>forgot to fix typename declarations<commit_after>/* * Software License Agreement (BSD License) * * Copyright (c) 2011, Willow Garage, Inc. * 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 Willow Garage, Inc. 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 <boost/thread/thread.hpp> #include <boost/date_time/posix_time/posix_time.hpp> #include <pcl/point_cloud.h> #include <pcl/point_types.h> #include <pcl/io/openni_grabber.h> #include <pcl/visualization/cloud_viewer.h> #include <pcl/io/openni_camera/openni_driver.h> #include <pcl/keypoints/uniform_sampling.h> #include <pcl/console/parse.h> #include <pcl/common/time.h> #define FPS_CALC(_WHAT_) \ do \ { \ static unsigned count = 0;\ static double last = pcl::getTime ();\ double now = pcl::getTime (); \ ++count; \ if (now - last >= 1.0) \ { \ std::cout << "Average framerate("<< _WHAT_ << "): " << double(count)/double(now - last) << " Hz" << std::endl; \ count = 0; \ last = now; \ } \ }while(false) class OpenNIUniformSampling { public: typedef pcl::PointCloud<pcl::PointXYZRGB> Cloud; typedef Cloud::Ptr CloudPtr; typedef Cloud::ConstPtr CloudConstPtr; OpenNIUniformSampling (const std::string& device_id = "", float leaf_size = 0.05) : viewer ("PCL OpenNI PassThrough Viewer") , device_id_(device_id) { pass_.setRadiusSearch (leaf_size); } void cloud_cb_ (const CloudConstPtr& cloud) { boost::mutex::scoped_lock lock (mtx_); FPS_CALC ("computation"); cloud_.reset (new Cloud); indices_.reset (new pcl::PointCloud<int>); keypoints_.reset (new pcl::PointCloud<pcl::PointXYZ>); // Computation goes here pass_.setInputCloud (cloud); pass_.compute (*indices_); *cloud_ = *cloud; pcl::copyPointCloud<pcl::PointXYZRGB, pcl::PointXYZ> (*cloud, indices_->points, *keypoints_); } void viz_cb (pcl::visualization::PCLVisualizer& viz) { boost::mutex::scoped_lock lock (mtx_); if (!keypoints_ && !cloud_) { boost::this_thread::sleep(boost::posix_time::seconds(1)); return; } FPS_CALC ("visualization"); viz.removePointCloud ("raw"); pcl::visualization::PointCloudColorHandlerRGBField<pcl::PointXYZRGB> color_handler (cloud_); viz.addPointCloud<pcl::PointXYZRGB> (cloud_, color_handler, "raw"); if (!viz.updatePointCloud<pcl::PointXYZ> (keypoints_, "keypoints")) { viz.addPointCloud<pcl::PointXYZ> (keypoints_, "keypoints"); viz.setPointCloudRenderingProperties (pcl::visualization::PCL_VISUALIZER_POINT_SIZE, 5.0, "keypoints"); viz.resetCameraViewpoint ("keypoints"); } } void run () { pcl::Grabber* interface = new pcl::OpenNIGrabber (device_id_); boost::function<void (const CloudConstPtr&)> f = boost::bind (&OpenNIUniformSampling::cloud_cb_, this, _1); boost::signals2::connection c = interface->registerCallback (f); viewer.runOnVisualizationThread (boost::bind(&OpenNIUniformSampling::viz_cb, this, _1), "viz_cb"); interface->start (); while (!viewer.wasStopped ()) { boost::this_thread::sleep(boost::posix_time::seconds(1)); } interface->stop (); } pcl::UniformSampling<pcl::PointXYZRGB> pass_; pcl::visualization::CloudViewer viewer; std::string device_id_; boost::mutex mtx_; CloudPtr cloud_; pcl::PointCloud<pcl::PointXYZ>::Ptr keypoints_; pcl::PointCloud<int>::Ptr indices_; }; void usage (char ** argv) { std::cout << "usage: " << argv[0] << " <device_id> <options>\n\n" << "where options are:\n" << " -leaf X :: set the UniformSampling leaf size (default: 0.01)\n"; openni_wrapper::OpenNIDriver& driver = openni_wrapper::OpenNIDriver::getInstance (); if (driver.getNumberDevices () > 0) { for (unsigned deviceIdx = 0; deviceIdx < driver.getNumberDevices (); ++deviceIdx) { cout << "Device: " << deviceIdx + 1 << ", vendor: " << driver.getVendorName (deviceIdx) << ", product: " << driver.getProductName (deviceIdx) << ", connected: " << (int)driver.getBus (deviceIdx) << " @ " << (int)driver.getAddress (deviceIdx) << ", serial number: \'" << driver.getSerialNumber (deviceIdx) << "\'" << endl; cout << "device_id may be #1, #2, ... for the first second etc device in the list or" << endl << " bus@address for the device connected to a specific usb-bus / address combination (works only in Linux) or" << endl << " <serial-number> (only in Linux and for devices which provide serial numbers)" << endl; } } else cout << "No devices connected." << endl; } int main (int argc, char ** argv) { if (argc < 2) { usage (argv); return 1; } std::string arg (argv[1]); if (arg == "--help" || arg == "-h") { usage (argv); return 1; } double leaf_res = 0.05; pcl::console::parse_argument (argc, argv, "-leaf", leaf_res); PCL_INFO ("Using %f as a leaf size for UniformSampling.\n", leaf_res); pcl::OpenNIGrabber grabber (arg); OpenNIUniformSampling v (arg, leaf_res); v.run (); return (0); } <|endoftext|>
<commit_before>//////////////////////////////////////////////////////////////////////////////// /// DISCLAIMER /// /// Copyright 2019 ArangoDB GmbH, Cologne, Germany /// /// 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. /// /// Copyright holder is ArangoDB GmbH, Cologne, Germany /// /// @author Markus Pfeiffer //////////////////////////////////////////////////////////////////////////////// #include "ModificationExecutor.h" #include "Aql/AllRowsFetcher.h" #include "Aql/AqlValue.h" #include "Aql/Collection.h" #include "Aql/OutputAqlItemRow.h" #include "Aql/SingleRowFetcher.h" #include "Basics/Common.h" #include "Basics/VelocyPackHelper.h" #include "StorageEngine/TransactionState.h" #include "Transaction/Methods.h" #include "VocBase/LogicalCollection.h" #include "Aql/InsertModifier.h" #include "Aql/RemoveModifier.h" #include "Aql/SimpleModifier.h" #include "Aql/UpdateReplaceModifier.h" #include "Aql/UpsertModifier.h" #include "Logger/LogMacros.h" #include <algorithm> #include "velocypack/velocypack-aliases.h" using namespace arangodb; using namespace arangodb::aql; using namespace arangodb::basics; namespace arangodb { namespace aql { ModifierOutput::ModifierOutput(InputAqlItemRow const& inputRow, Type type) : _inputRow(std::move(inputRow)), _type(type), _oldValue(), _newValue() {} ModifierOutput::ModifierOutput(InputAqlItemRow&& inputRow, Type type) : _inputRow(std::move(inputRow)), _type(type), _oldValue(), _newValue() {} ModifierOutput::ModifierOutput(InputAqlItemRow const& inputRow, Type type, AqlValue const& oldValue, AqlValue const& newValue) : _inputRow(std::move(inputRow)), _type(type), _oldValue(oldValue), _oldValueGuard(std::in_place, _oldValue.value(), true), _newValue(newValue), _newValueGuard(std::in_place, _newValue.value(), true) {} ModifierOutput::ModifierOutput(InputAqlItemRow&& inputRow, Type type, AqlValue const& oldValue, AqlValue const& newValue) : _inputRow(std::move(inputRow)), _type(type), _oldValue(oldValue), _oldValueGuard(std::in_place, _oldValue.value(), true), _newValue(newValue), _newValueGuard(std::in_place, _newValue.value(), true) {} InputAqlItemRow ModifierOutput::getInputRow() const { return _inputRow; } ModifierOutput::Type ModifierOutput::getType() const { return _type; } bool ModifierOutput::hasOldValue() const { return _oldValue.has_value(); } AqlValue const& ModifierOutput::getOldValue() const { TRI_ASSERT(_oldValue.has_value()); return _oldValue.value(); } bool ModifierOutput::hasNewValue() const { return _newValue.has_value(); } AqlValue const& ModifierOutput::getNewValue() const { TRI_ASSERT(_newValue.has_value()); return _newValue.value(); } template <typename FetcherType, typename ModifierType> ModificationExecutor<FetcherType, ModifierType>::ModificationExecutor(Fetcher& fetcher, Infos& infos) : _lastState(ExecutionState::HASMORE), _infos(infos), _fetcher(fetcher), _modifier(infos) {} // Fetches as many rows as possible from upstream using the fetcher's fetchRow // method and accumulates results through the modifier template <typename FetcherType, typename ModifierType> auto ModificationExecutor<FetcherType, ModifierType>::doCollect(AqlItemBlockInputRange& input, size_t maxOutputs) -> void { // for fetchRow InputAqlItemRow row{CreateInvalidInputRowHint{}}; ExecutionState state = ExecutionState::HASMORE; // Maximum number of rows we can put into output // So we only ever produce this many here while (_modifier.nrOfOperations() < maxOutputs && input.hasDataRow()) { auto [state, row] = input.nextDataRow(); // Make sure we have a valid row TRI_ASSERT(row.isInitialized()); _modifier.accumulate(row); } TRI_ASSERT(state == ExecutionState::DONE || state == ExecutionState::HASMORE); } // Outputs accumulated results, and counts the statistics template <typename FetcherType, typename ModifierType> void ModificationExecutor<FetcherType, ModifierType>::doOutput(OutputAqlItemRow& output, Stats& stats) { typename ModifierType::OutputIterator modifierOutputIterator(_modifier); // We only accumulated as many items as we can output, so this // should be correct for (auto const& modifierOutput : modifierOutputIterator) { TRI_ASSERT(!output.isFull()); bool written = false; switch (modifierOutput.getType()) { case ModifierOutput::Type::ReturnIfRequired: if (_infos._options.returnOld) { output.cloneValueInto(_infos._outputOldRegisterId, modifierOutput.getInputRow(), modifierOutput.getOldValue()); written = true; } if (_infos._options.returnNew) { output.cloneValueInto(_infos._outputNewRegisterId, modifierOutput.getInputRow(), modifierOutput.getNewValue()); written = true; } [[fallthrough]]; case ModifierOutput::Type::CopyRow: if (!written) { output.copyRow(modifierOutput.getInputRow()); } output.advanceRow(); break; case ModifierOutput::Type::SkipRow: // nothing. break; } } } template <typename FetcherType, typename ModifierType> [[nodiscard]] auto ModificationExecutor<FetcherType, ModifierType>::produceRows( typename FetcherType::DataRange& input, OutputAqlItemRow& output) -> std::tuple<ExecutorState, ModificationStats, AqlCall> { TRI_ASSERT(_infos._trx); AqlCall upstreamCall{}; if constexpr (std::is_same_v<ModifierType, UpsertModifier> && !std::is_same_v<FetcherType, AllRowsFetcher>) { upstreamCall.softLimit = _modifier.getBatchSize(); } auto stats = ModificationStats{}; _modifier.reset(); if (!input.hasDataRow()) { // Input is empty return {input.upstreamState(), stats, upstreamCall}; } TRI_IF_FAILURE("ModificationBlock::getSome") { THROW_ARANGO_EXCEPTION(TRI_ERROR_DEBUG); } // only produce at most output.numRowsLeft() many results ExecutorState upstreamState = ExecutorState::HASMORE; if constexpr (std::is_same_v<typename FetcherType::DataRange, AqlItemBlockInputMatrix>) { auto& range = input.getInputRange(); doCollect(range, output.numRowsLeft()); upstreamState = range.upstreamState(); if (upstreamState == ExecutorState::DONE) { // We are done with this input. // We need to forward it to the last ShadowRow. input.skipAllRemainingDataRows(); } } else { doCollect(input, output.numRowsLeft()); upstreamState = input.upstreamState(); } if (_modifier.nrOfOperations() > 0) { _modifier.transact(); if (_infos._doCount) { stats.addWritesExecuted(_modifier.nrOfWritesExecuted()); stats.addWritesIgnored(_modifier.nrOfWritesIgnored()); } doOutput(output, stats); } return {upstreamState, stats, upstreamCall}; } template <typename FetcherType, typename ModifierType> [[nodiscard]] auto ModificationExecutor<FetcherType, ModifierType>::skipRowsRange( typename FetcherType::DataRange& input, AqlCall& call) -> std::tuple<ExecutorState, Stats, size_t, AqlCall> { AqlCall upstreamCall{}; if constexpr (std::is_same_v<ModifierType, UpsertModifier> && !std::is_same_v<FetcherType, AllRowsFetcher>) { upstreamCall.softLimit = _modifier.getBatchSize(); } auto stats = ModificationStats{}; TRI_IF_FAILURE("ModificationBlock::getSome") { THROW_ARANGO_EXCEPTION(TRI_ERROR_DEBUG); } // only produce at most output.numRowsLeft() many results ExecutorState upstreamState = input.upstreamState(); while (input.hasDataRow() && call.needSkipMore()) { _modifier.reset(); size_t toSkip = call.getOffset(); if (call.getLimit() == 0 && call.hasHardLimit()) { // We need to produce all modification operations. // If we are bound by limits or not! toSkip = ExecutionBlock::SkipAllSize(); } if constexpr (std::is_same_v<typename FetcherType::DataRange, AqlItemBlockInputMatrix>) { auto& range = input.getInputRange(); if (range.hasDataRow()) { doCollect(range, toSkip); } upstreamState = range.upstreamState(); if (upstreamState == ExecutorState::DONE) { // We are done with this input. // We need to forward it to the last ShadowRow. input.skipAllRemainingDataRows(); TRI_ASSERT(input.upstreamState() == ExecutorState::DONE); } } else { doCollect(input, toSkip); upstreamState = input.upstreamState(); } if (_modifier.nrOfOperations() > 0) { _modifier.transact(); if (_infos._doCount) { stats.addWritesExecuted(_modifier.nrOfWritesExecuted()); stats.addWritesIgnored(_modifier.nrOfWritesIgnored()); } call.didSkip(_modifier.nrOfOperations()); } } return {upstreamState, stats, call.getSkipCount(), upstreamCall}; } using NoPassthroughSingleRowFetcher = SingleRowFetcher<BlockPassthrough::Disable>; template class ::arangodb::aql::ModificationExecutor<NoPassthroughSingleRowFetcher, InsertModifier>; template class ::arangodb::aql::ModificationExecutor<AllRowsFetcher, InsertModifier>; template class ::arangodb::aql::ModificationExecutor<NoPassthroughSingleRowFetcher, RemoveModifier>; template class ::arangodb::aql::ModificationExecutor<AllRowsFetcher, RemoveModifier>; template class ::arangodb::aql::ModificationExecutor<NoPassthroughSingleRowFetcher, UpdateReplaceModifier>; template class ::arangodb::aql::ModificationExecutor<AllRowsFetcher, UpdateReplaceModifier>; template class ::arangodb::aql::ModificationExecutor<NoPassthroughSingleRowFetcher, UpsertModifier>; template class ::arangodb::aql::ModificationExecutor<AllRowsFetcher, UpsertModifier>; } // namespace aql } // namespace arangodb <commit_msg>fix lame compile error<commit_after>//////////////////////////////////////////////////////////////////////////////// /// DISCLAIMER /// /// Copyright 2019 ArangoDB GmbH, Cologne, Germany /// /// 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. /// /// Copyright holder is ArangoDB GmbH, Cologne, Germany /// /// @author Markus Pfeiffer //////////////////////////////////////////////////////////////////////////////// #include "ModificationExecutor.h" #include "Aql/AllRowsFetcher.h" #include "Aql/AqlValue.h" #include "Aql/Collection.h" #include "Aql/OutputAqlItemRow.h" #include "Aql/SingleRowFetcher.h" #include "Basics/Common.h" #include "Basics/VelocyPackHelper.h" #include "StorageEngine/TransactionState.h" #include "Transaction/Methods.h" #include "VocBase/LogicalCollection.h" #include "Aql/InsertModifier.h" #include "Aql/RemoveModifier.h" #include "Aql/SimpleModifier.h" #include "Aql/UpdateReplaceModifier.h" #include "Aql/UpsertModifier.h" #include "Logger/LogMacros.h" #include <algorithm> #include "velocypack/velocypack-aliases.h" using namespace arangodb; using namespace arangodb::aql; using namespace arangodb::basics; namespace arangodb { namespace aql { ModifierOutput::ModifierOutput(InputAqlItemRow const& inputRow, Type type) : _inputRow(std::move(inputRow)), _type(type), _oldValue(), _newValue() {} ModifierOutput::ModifierOutput(InputAqlItemRow&& inputRow, Type type) : _inputRow(std::move(inputRow)), _type(type), _oldValue(), _newValue() {} ModifierOutput::ModifierOutput(InputAqlItemRow const& inputRow, Type type, AqlValue const& oldValue, AqlValue const& newValue) : _inputRow(std::move(inputRow)), _type(type), _oldValue(oldValue), _oldValueGuard(std::in_place, _oldValue.value(), true), _newValue(newValue), _newValueGuard(std::in_place, _newValue.value(), true) {} ModifierOutput::ModifierOutput(InputAqlItemRow&& inputRow, Type type, AqlValue const& oldValue, AqlValue const& newValue) : _inputRow(std::move(inputRow)), _type(type), _oldValue(oldValue), _oldValueGuard(std::in_place, _oldValue.value(), true), _newValue(newValue), _newValueGuard(std::in_place, _newValue.value(), true) {} InputAqlItemRow ModifierOutput::getInputRow() const { return _inputRow; } ModifierOutput::Type ModifierOutput::getType() const { return _type; } bool ModifierOutput::hasOldValue() const { return _oldValue.has_value(); } AqlValue const& ModifierOutput::getOldValue() const { TRI_ASSERT(_oldValue.has_value()); return _oldValue.value(); } bool ModifierOutput::hasNewValue() const { return _newValue.has_value(); } AqlValue const& ModifierOutput::getNewValue() const { TRI_ASSERT(_newValue.has_value()); return _newValue.value(); } template <typename FetcherType, typename ModifierType> ModificationExecutor<FetcherType, ModifierType>::ModificationExecutor(Fetcher& fetcher, Infos& infos) : _lastState(ExecutionState::HASMORE), _infos(infos), _modifier(infos) {} // Fetches as many rows as possible from upstream using the fetcher's fetchRow // method and accumulates results through the modifier template <typename FetcherType, typename ModifierType> auto ModificationExecutor<FetcherType, ModifierType>::doCollect(AqlItemBlockInputRange& input, size_t maxOutputs) -> void { // for fetchRow InputAqlItemRow row{CreateInvalidInputRowHint{}}; ExecutionState state = ExecutionState::HASMORE; // Maximum number of rows we can put into output // So we only ever produce this many here while (_modifier.nrOfOperations() < maxOutputs && input.hasDataRow()) { auto [state, row] = input.nextDataRow(); // Make sure we have a valid row TRI_ASSERT(row.isInitialized()); _modifier.accumulate(row); } TRI_ASSERT(state == ExecutionState::DONE || state == ExecutionState::HASMORE); } // Outputs accumulated results, and counts the statistics template <typename FetcherType, typename ModifierType> void ModificationExecutor<FetcherType, ModifierType>::doOutput(OutputAqlItemRow& output, Stats& stats) { typename ModifierType::OutputIterator modifierOutputIterator(_modifier); // We only accumulated as many items as we can output, so this // should be correct for (auto const& modifierOutput : modifierOutputIterator) { TRI_ASSERT(!output.isFull()); bool written = false; switch (modifierOutput.getType()) { case ModifierOutput::Type::ReturnIfRequired: if (_infos._options.returnOld) { output.cloneValueInto(_infos._outputOldRegisterId, modifierOutput.getInputRow(), modifierOutput.getOldValue()); written = true; } if (_infos._options.returnNew) { output.cloneValueInto(_infos._outputNewRegisterId, modifierOutput.getInputRow(), modifierOutput.getNewValue()); written = true; } [[fallthrough]]; case ModifierOutput::Type::CopyRow: if (!written) { output.copyRow(modifierOutput.getInputRow()); } output.advanceRow(); break; case ModifierOutput::Type::SkipRow: // nothing. break; } } } template <typename FetcherType, typename ModifierType> [[nodiscard]] auto ModificationExecutor<FetcherType, ModifierType>::produceRows( typename FetcherType::DataRange& input, OutputAqlItemRow& output) -> std::tuple<ExecutorState, ModificationStats, AqlCall> { TRI_ASSERT(_infos._trx); AqlCall upstreamCall{}; if constexpr (std::is_same_v<ModifierType, UpsertModifier> && !std::is_same_v<FetcherType, AllRowsFetcher>) { upstreamCall.softLimit = _modifier.getBatchSize(); } auto stats = ModificationStats{}; _modifier.reset(); if (!input.hasDataRow()) { // Input is empty return {input.upstreamState(), stats, upstreamCall}; } TRI_IF_FAILURE("ModificationBlock::getSome") { THROW_ARANGO_EXCEPTION(TRI_ERROR_DEBUG); } // only produce at most output.numRowsLeft() many results ExecutorState upstreamState = ExecutorState::HASMORE; if constexpr (std::is_same_v<typename FetcherType::DataRange, AqlItemBlockInputMatrix>) { auto& range = input.getInputRange(); doCollect(range, output.numRowsLeft()); upstreamState = range.upstreamState(); if (upstreamState == ExecutorState::DONE) { // We are done with this input. // We need to forward it to the last ShadowRow. input.skipAllRemainingDataRows(); } } else { doCollect(input, output.numRowsLeft()); upstreamState = input.upstreamState(); } if (_modifier.nrOfOperations() > 0) { _modifier.transact(); if (_infos._doCount) { stats.addWritesExecuted(_modifier.nrOfWritesExecuted()); stats.addWritesIgnored(_modifier.nrOfWritesIgnored()); } doOutput(output, stats); } return {upstreamState, stats, upstreamCall}; } template <typename FetcherType, typename ModifierType> [[nodiscard]] auto ModificationExecutor<FetcherType, ModifierType>::skipRowsRange( typename FetcherType::DataRange& input, AqlCall& call) -> std::tuple<ExecutorState, Stats, size_t, AqlCall> { AqlCall upstreamCall{}; if constexpr (std::is_same_v<ModifierType, UpsertModifier> && !std::is_same_v<FetcherType, AllRowsFetcher>) { upstreamCall.softLimit = _modifier.getBatchSize(); } auto stats = ModificationStats{}; TRI_IF_FAILURE("ModificationBlock::getSome") { THROW_ARANGO_EXCEPTION(TRI_ERROR_DEBUG); } // only produce at most output.numRowsLeft() many results ExecutorState upstreamState = input.upstreamState(); while (input.hasDataRow() && call.needSkipMore()) { _modifier.reset(); size_t toSkip = call.getOffset(); if (call.getLimit() == 0 && call.hasHardLimit()) { // We need to produce all modification operations. // If we are bound by limits or not! toSkip = ExecutionBlock::SkipAllSize(); } if constexpr (std::is_same_v<typename FetcherType::DataRange, AqlItemBlockInputMatrix>) { auto& range = input.getInputRange(); if (range.hasDataRow()) { doCollect(range, toSkip); } upstreamState = range.upstreamState(); if (upstreamState == ExecutorState::DONE) { // We are done with this input. // We need to forward it to the last ShadowRow. input.skipAllRemainingDataRows(); TRI_ASSERT(input.upstreamState() == ExecutorState::DONE); } } else { doCollect(input, toSkip); upstreamState = input.upstreamState(); } if (_modifier.nrOfOperations() > 0) { _modifier.transact(); if (_infos._doCount) { stats.addWritesExecuted(_modifier.nrOfWritesExecuted()); stats.addWritesIgnored(_modifier.nrOfWritesIgnored()); } call.didSkip(_modifier.nrOfOperations()); } } return {upstreamState, stats, call.getSkipCount(), upstreamCall}; } using NoPassthroughSingleRowFetcher = SingleRowFetcher<BlockPassthrough::Disable>; template class ::arangodb::aql::ModificationExecutor<NoPassthroughSingleRowFetcher, InsertModifier>; template class ::arangodb::aql::ModificationExecutor<AllRowsFetcher, InsertModifier>; template class ::arangodb::aql::ModificationExecutor<NoPassthroughSingleRowFetcher, RemoveModifier>; template class ::arangodb::aql::ModificationExecutor<AllRowsFetcher, RemoveModifier>; template class ::arangodb::aql::ModificationExecutor<NoPassthroughSingleRowFetcher, UpdateReplaceModifier>; template class ::arangodb::aql::ModificationExecutor<AllRowsFetcher, UpdateReplaceModifier>; template class ::arangodb::aql::ModificationExecutor<NoPassthroughSingleRowFetcher, UpsertModifier>; template class ::arangodb::aql::ModificationExecutor<AllRowsFetcher, UpsertModifier>; } // namespace aql } // namespace arangodb <|endoftext|>
<commit_before>#ifndef CACHEALIGNED_HPP_INCLUDED #define CACHEALIGNED_HPP_INCLUDED #include <cstddef> #include "CacheAlignedBase.hpp" template<typename T> class CacheAligned : public Aligned<T>, CacheAlignedBase<T> { public: template<typename... Args> CacheAligned(Args &&... args) : Aligned(cacheLineSize()) {} }; template<typename T> class CacheAligned<T[]> : public Aligned<T[]>, CacheAlignedBase<T> { public: CacheAligned(std::size_t size) : Aligned(cacheLineSize(), size) {} }; #endif<commit_msg>forward construction args<commit_after>#ifndef CACHEALIGNED_HPP_INCLUDED #define CACHEALIGNED_HPP_INCLUDED #include <cstddef> #include "Aligned.hpp" #include "CacheAlignedBase.hpp" template<typename T> class CacheAligned : public Aligned<T>, CacheAlignedBase<T> { public: template<typename... Args> CacheAligned(Args &&... args) : Aligned(cacheLineSize(), args...) {} }; template<typename T> class CacheAligned<T[]> : public Aligned<T[]>, CacheAlignedBase<T> { public: CacheAligned(std::size_t size) : Aligned(cacheLineSize(), size) {} }; #endif<|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: dependency.cxx,v $ * * $Revision: 1.5 $ * * last change: $Author: rt $ $Date: 2005-09-09 05:03:42 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * 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 * ************************************************************************/ #ifndef _OSL_INTERLOCK_H_ #include <osl/interlck.h> #endif #ifndef _RTL_ALLOC_H_ #include <rtl/alloc.h> #endif #ifndef _CODEMAKER_DEPENDENCY_HXX_ #include <codemaker/dependency.hxx> #endif using namespace rtl; TypeDependency::TypeDependency() { m_pImpl = new TypeDependencyImpl(); acquire(); } TypeDependency::~TypeDependency() { release(); } void TypeDependency::acquire() { osl_incrementInterlockedCount(&m_pImpl->m_refCount); } void TypeDependency::release() { if (0 == osl_decrementInterlockedCount(&m_pImpl->m_refCount)) { delete m_pImpl; } } sal_Bool TypeDependency::insert(const OString& type, const OString& depend, sal_uInt16 use) { sal_Bool ret = sal_False; if (type.getLength() > 0 && depend.getLength() > 0) { if (m_pImpl->m_dependencies.count(type) > 0) { TypeUsing typeUsing(depend, use); TypeUsingSet::iterator iter; if ((iter = m_pImpl->m_dependencies[type].find(typeUsing)) != m_pImpl->m_dependencies[type].end()) { (((TypeUsing *) &(*iter))->m_use) = (*iter).m_use | use; } else { m_pImpl->m_dependencies[type].insert(typeUsing); } } else { TypeUsing typeUsing(depend, use); TypeUsingSet tmpSet; tmpSet.insert(typeUsing); m_pImpl->m_dependencies[type]=tmpSet; } } return ret; } TypeUsingSet TypeDependency::getDependencies(const OString& type) { if (type.getLength() > 0) { if (m_pImpl->m_dependencies.count(type) > 0) { return m_pImpl->m_dependencies[type]; } } return TypeUsingSet(); } sal_Bool TypeDependency::lookupDependency(const OString& type, const OString& depend, sal_uInt16 use) { sal_Bool ret = sal_False; if (type.getLength() > 0 && depend.getLength() > 0) { if (m_pImpl->m_dependencies.count(type) > 0) { TypeUsingSet::const_iterator iter = m_pImpl->m_dependencies[type].begin(); while (iter != m_pImpl->m_dependencies[type].end()) { if (depend == (*iter).m_type && (use & (*iter).m_use)) { ret = sal_True; break; } iter++; } } else { ret = sal_False; } } return ret; } sal_Bool TypeDependency::hasDependencies(const OString& type) { if (type.getLength() > 0) { if (m_pImpl->m_dependencies.count(type) > 0) { return sal_True; } } return sal_False; } void TypeDependency::setGenerated(const OString& type, sal_uInt16 genFlag) { // m_pImpl->m_generatedTypes.insert(type); if (m_pImpl->m_generatedTypes.count(type) > 0) m_pImpl->m_generatedTypes[type]= m_pImpl->m_generatedTypes[type] | genFlag; else m_pImpl->m_generatedTypes[type]=genFlag; } sal_Bool TypeDependency::isGenerated(const OString& type, sal_uInt16 genFlag) { /* if (m_pImpl->m_generatedTypes.count(type) > 0) return sal_True; return sal_False; */ if (m_pImpl->m_generatedTypes.count(type) > 0 && m_pImpl->m_generatedTypes[type] & genFlag) { return sal_True; } return sal_False; } static sal_Bool checkFieldDependencies(TypeManager& typeMgr, TypeDependency& dependencies, TypeReader& reader, const OString& type) { sal_uInt32 count = reader.getFieldCount(); if (count == 0 || reader.getTypeClass() == RT_TYPE_ENUM) return sal_True; OString fieldType; for (sal_uInt16 i=0; i < count; i++) { fieldType = reader.getFieldType(i); if (fieldType.getLength() > 0) { dependencies.insert(type, fieldType, TYPEUSE_MEMBER); checkTypeDependencies(typeMgr, dependencies, fieldType); } } return sal_True; } static sal_Bool checkMethodDependencies(TypeManager& typeMgr, TypeDependency& dependencies, TypeReader& reader, const OString& type) { sal_uInt32 count = reader.getMethodCount(); if (count == 0) return sal_True; OString returnType, paramType, excType; sal_uInt32 paramCount = 0; sal_uInt32 excCount = 0; RTParamMode paramMode = RT_PARAM_INVALID; for (sal_uInt16 i=0; i < count; i++) { returnType = reader.getMethodReturnType(i); dependencies.insert(type, returnType, TYPEUSE_RETURN); checkTypeDependencies(typeMgr, dependencies, returnType); paramCount = reader.getMethodParamCount(i); excCount = reader.getMethodExcCount(i); sal_uInt16 j; for (j=0; j < paramCount; j++) { paramType = reader.getMethodParamType(i, j); paramMode = reader.getMethodParamMode(i, j); switch (paramMode) { case RT_PARAM_IN: dependencies.insert(type, paramType, TYPEUSE_INPARAM); break; case RT_PARAM_OUT: dependencies.insert(type, paramType, TYPEUSE_OUTPARAM); break; case RT_PARAM_INOUT: dependencies.insert(type, paramType, TYPEUSE_INOUTPARAM); break; } checkTypeDependencies(typeMgr, dependencies, paramType); } for (j=0; j < excCount; j++) { excType = reader.getMethodExcType(i, j); dependencies.insert(type, excType, TYPEUSE_EXCEPTION); checkTypeDependencies(typeMgr, dependencies, excType); } } return sal_True; } static sal_Bool checkReferenceDependencies(TypeManager& typeMgr, TypeDependency& dependencies, TypeReader& reader, const OString& type) { sal_uInt32 count = reader.getReferenceCount(); if (count == 0) return sal_True; OString referenceName; for (sal_uInt16 i=0; i < count; i++) { referenceName = reader.getReferenceName(i); dependencies.insert(type, referenceName, TYPEUSE_NORMAL); checkTypeDependencies(typeMgr, dependencies, referenceName); } return sal_True; } sal_Bool checkTypeDependencies(TypeManager& typeMgr, TypeDependency& dependencies, const OString& type, sal_Bool bDepend) { if (!typeMgr.isValidType(type)) return sal_False; if (dependencies.hasDependencies(type)) return sal_True; TypeReader reader = typeMgr.getTypeReader(type); if ( !reader.isValid() ) { if (type.equals("/")) return sal_True; else return sal_False; } if ( bDepend && reader.getTypeClass() == RT_TYPE_MODULE) { checkFieldDependencies(typeMgr, dependencies, reader, type); return sal_True; } for (sal_uInt16 i = 0; i < reader.getSuperTypeCount(); ++i) { OString superType(reader.getSuperTypeName(i)); dependencies.insert(type, superType, TYPEUSE_SUPER); checkTypeDependencies(typeMgr, dependencies, superType); } if (reader.getTypeClass() == RT_TYPE_INTERFACE) { dependencies.insert(type, "com/sun/star/uno/RuntimeException", TYPEUSE_EXCEPTION); dependencies.insert(type, "com/sun/star/uno/TypeClass", TYPEUSE_NORMAL); checkTypeDependencies(typeMgr, dependencies, "com/sun/star/uno/RuntimeException", bDepend); } checkFieldDependencies(typeMgr, dependencies, reader, type); checkMethodDependencies(typeMgr, dependencies, reader, type); checkReferenceDependencies(typeMgr, dependencies, reader, type); // make the scope modules as dependencies sal_Int32 nPos = type.lastIndexOf( '/' ); if ( nPos >= 0 ) { OString aScope( type.copy( 0, nPos ) ); OStringBuffer tmpBuf(aScope.getLength()); nPos = 0; do { tmpBuf.append(aScope.getToken(0, '/', nPos)); dependencies.insert(type, tmpBuf.getStr(), TYPEUSE_SCOPE); tmpBuf.append('/'); } while( nPos != -1 ); } return sal_True; } <commit_msg>INTEGRATION: CWS warnings01 (1.4.18); FILE MERGED 2005/09/23 00:23:50 sb 1.4.18.2: RESYNC: (1.4-1.5); FILE MERGED 2005/09/01 07:48:38 sb 1.4.18.1: #i53898# Made code warning-free.<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: dependency.cxx,v $ * * $Revision: 1.6 $ * * last change: $Author: hr $ $Date: 2006-06-20 04:09:32 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * 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 * ************************************************************************/ #ifndef _OSL_INTERLOCK_H_ #include <osl/interlck.h> #endif #ifndef _RTL_ALLOC_H_ #include <rtl/alloc.h> #endif #ifndef _CODEMAKER_DEPENDENCY_HXX_ #include <codemaker/dependency.hxx> #endif using namespace rtl; TypeDependency::TypeDependency() { m_pImpl = new TypeDependencyImpl(); acquire(); } TypeDependency::~TypeDependency() { release(); } void TypeDependency::acquire() { osl_incrementInterlockedCount(&m_pImpl->m_refCount); } void TypeDependency::release() { if (0 == osl_decrementInterlockedCount(&m_pImpl->m_refCount)) { delete m_pImpl; } } sal_Bool TypeDependency::insert(const OString& type, const OString& depend, sal_uInt16 use) { sal_Bool ret = sal_False; if (type.getLength() > 0 && depend.getLength() > 0) { if (m_pImpl->m_dependencies.count(type) > 0) { TypeUsing typeUsing(depend, use); TypeUsingSet::iterator iter; if ((iter = m_pImpl->m_dependencies[type].find(typeUsing)) != m_pImpl->m_dependencies[type].end()) { (((TypeUsing *) &(*iter))->m_use) = (*iter).m_use | use; } else { m_pImpl->m_dependencies[type].insert(typeUsing); } } else { TypeUsing typeUsing(depend, use); TypeUsingSet tmpSet; tmpSet.insert(typeUsing); m_pImpl->m_dependencies[type]=tmpSet; } } return ret; } TypeUsingSet TypeDependency::getDependencies(const OString& type) { if (type.getLength() > 0) { if (m_pImpl->m_dependencies.count(type) > 0) { return m_pImpl->m_dependencies[type]; } } return TypeUsingSet(); } sal_Bool TypeDependency::lookupDependency(const OString& type, const OString& depend, sal_uInt16 use) { sal_Bool ret = sal_False; if (type.getLength() > 0 && depend.getLength() > 0) { if (m_pImpl->m_dependencies.count(type) > 0) { TypeUsingSet::const_iterator iter = m_pImpl->m_dependencies[type].begin(); while (iter != m_pImpl->m_dependencies[type].end()) { if (depend == (*iter).m_type && (use & (*iter).m_use)) { ret = sal_True; break; } iter++; } } else { ret = sal_False; } } return ret; } sal_Bool TypeDependency::hasDependencies(const OString& type) { if (type.getLength() > 0) { if (m_pImpl->m_dependencies.count(type) > 0) { return sal_True; } } return sal_False; } void TypeDependency::setGenerated(const OString& type, sal_uInt16 genFlag) { // m_pImpl->m_generatedTypes.insert(type); if (m_pImpl->m_generatedTypes.count(type) > 0) m_pImpl->m_generatedTypes[type]= m_pImpl->m_generatedTypes[type] | genFlag; else m_pImpl->m_generatedTypes[type]=genFlag; } sal_Bool TypeDependency::isGenerated(const OString& type, sal_uInt16 genFlag) { /* if (m_pImpl->m_generatedTypes.count(type) > 0) return sal_True; return sal_False; */ if (m_pImpl->m_generatedTypes.count(type) > 0 && m_pImpl->m_generatedTypes[type] & genFlag) { return sal_True; } return sal_False; } static sal_Bool checkFieldDependencies(TypeManager& typeMgr, TypeDependency& dependencies, TypeReader& reader, const OString& type) { sal_uInt32 count = reader.getFieldCount(); if (count == 0 || reader.getTypeClass() == RT_TYPE_ENUM) return sal_True; OString fieldType; for (sal_uInt16 i=0; i < count; i++) { fieldType = reader.getFieldType(i); if (fieldType.getLength() > 0) { dependencies.insert(type, fieldType, TYPEUSE_MEMBER); checkTypeDependencies(typeMgr, dependencies, fieldType); } } return sal_True; } static sal_Bool checkMethodDependencies(TypeManager& typeMgr, TypeDependency& dependencies, TypeReader& reader, const OString& type) { sal_uInt32 count = reader.getMethodCount(); if (count == 0) return sal_True; OString returnType, paramType, excType; sal_uInt32 paramCount = 0; sal_uInt32 excCount = 0; RTParamMode paramMode = RT_PARAM_INVALID; for (sal_uInt16 i=0; i < count; i++) { returnType = reader.getMethodReturnType(i); dependencies.insert(type, returnType, TYPEUSE_RETURN); checkTypeDependencies(typeMgr, dependencies, returnType); paramCount = reader.getMethodParamCount(i); excCount = reader.getMethodExcCount(i); sal_uInt16 j; for (j=0; j < paramCount; j++) { paramType = reader.getMethodParamType(i, j); paramMode = reader.getMethodParamMode(i, j); switch (paramMode) { case RT_PARAM_IN: dependencies.insert(type, paramType, TYPEUSE_INPARAM); break; case RT_PARAM_OUT: dependencies.insert(type, paramType, TYPEUSE_OUTPARAM); break; case RT_PARAM_INOUT: dependencies.insert(type, paramType, TYPEUSE_INOUTPARAM); break; default: break; } checkTypeDependencies(typeMgr, dependencies, paramType); } for (j=0; j < excCount; j++) { excType = reader.getMethodExcType(i, j); dependencies.insert(type, excType, TYPEUSE_EXCEPTION); checkTypeDependencies(typeMgr, dependencies, excType); } } return sal_True; } static sal_Bool checkReferenceDependencies(TypeManager& typeMgr, TypeDependency& dependencies, TypeReader& reader, const OString& type) { sal_uInt32 count = reader.getReferenceCount(); if (count == 0) return sal_True; OString referenceName; for (sal_uInt16 i=0; i < count; i++) { referenceName = reader.getReferenceName(i); dependencies.insert(type, referenceName, TYPEUSE_NORMAL); checkTypeDependencies(typeMgr, dependencies, referenceName); } return sal_True; } sal_Bool checkTypeDependencies(TypeManager& typeMgr, TypeDependency& dependencies, const OString& type, sal_Bool bDepend) { if (!typeMgr.isValidType(type)) return sal_False; if (dependencies.hasDependencies(type)) return sal_True; TypeReader reader = typeMgr.getTypeReader(type); if ( !reader.isValid() ) { if (type.equals("/")) return sal_True; else return sal_False; } if ( bDepend && reader.getTypeClass() == RT_TYPE_MODULE) { checkFieldDependencies(typeMgr, dependencies, reader, type); return sal_True; } for (sal_uInt16 i = 0; i < reader.getSuperTypeCount(); ++i) { OString superType(reader.getSuperTypeName(i)); dependencies.insert(type, superType, TYPEUSE_SUPER); checkTypeDependencies(typeMgr, dependencies, superType); } if (reader.getTypeClass() == RT_TYPE_INTERFACE) { dependencies.insert(type, "com/sun/star/uno/RuntimeException", TYPEUSE_EXCEPTION); dependencies.insert(type, "com/sun/star/uno/TypeClass", TYPEUSE_NORMAL); checkTypeDependencies(typeMgr, dependencies, "com/sun/star/uno/RuntimeException", bDepend); } checkFieldDependencies(typeMgr, dependencies, reader, type); checkMethodDependencies(typeMgr, dependencies, reader, type); checkReferenceDependencies(typeMgr, dependencies, reader, type); // make the scope modules as dependencies sal_Int32 nPos = type.lastIndexOf( '/' ); if ( nPos >= 0 ) { OString aScope( type.copy( 0, nPos ) ); OStringBuffer tmpBuf(aScope.getLength()); nPos = 0; do { tmpBuf.append(aScope.getToken(0, '/', nPos)); dependencies.insert(type, tmpBuf.getStr(), TYPEUSE_SCOPE); tmpBuf.append('/'); } while( nPos != -1 ); } return sal_True; } <|endoftext|>
<commit_before>// Copyright 2014 Toggl Desktop developers. #include "./timeentrycellwidget.h" #include "./ui_timeentrycellwidget.h" #include "./toggl.h" TimeEntryCellWidget::TimeEntryCellWidget() : QWidget(0), ui(new Ui::TimeEntryCellWidget), guid("") { ui->setupUi(this); } void TimeEntryCellWidget::display(TimeEntryView *view) { guid = view->GUID; QString description = (view->Description.length() > 0) ? view->Description : "(no description)"; ui->description->setText(description); ui->project->setText(view->ProjectAndTaskLabel); ui->project->setStyleSheet("color: '" + getProjectColor(view->Color) + "'"); ui->duration->setText(view->Duration); ui->billable->setVisible(view->Billable); ui->tags->setVisible(!view->Tags.isEmpty()); ui->headerFrame->setVisible(view->IsHeader); ui->date->setText(view->DateHeader); ui->dateDuration->setText(view->DateDuration); if (view->StartTimeString.length() > 0 && view->EndTimeString.length() > 0) { ui->duration->setToolTip( QString("<p style='color:black;background-color:white;'>" + view->StartTimeString + " - " + view->EndTimeString+"</p>")); } ui->tags->setToolTip( QString("<p style='color:white;background-color:black;'>" + (view->Tags).replace(QString("\t"), QString(", ")) + "</p>")); if (view->Description.length() > 0) { ui->description->setToolTip( QString("<p style='color:white;background-color:black;'>" + view->Description + "</p>")); } if (view->ProjectAndTaskLabel.length() > 0) { ui->project->setToolTip( QString("<p style='color:white;background-color:black;'>" + view->ProjectAndTaskLabel + "</p>")); } } void TimeEntryCellWidget::labelClicked(QString field_name) { TogglApi::instance->editTimeEntry(guid, field_name); } TimeEntryCellWidget::~TimeEntryCellWidget() { delete ui; } QSize TimeEntryCellWidget::getSizeHint(bool is_header) { if (is_header) { return QSize(minimumWidth(), sizeHint().height()); } return QSize(minimumWidth(), ui->dataFrame->height()); } void TimeEntryCellWidget::mousePressEvent(QMouseEvent *event) { TogglApi::instance->editTimeEntry(guid, ""); QWidget::mousePressEvent(event); } void TimeEntryCellWidget::on_continueButton_clicked() { TogglApi::instance->continueTimeEntry(guid); } QString TimeEntryCellWidget::getProjectColor(QString color) { if (color.length() == 0) { return QString("#9d9d9d"); } return color; } <commit_msg>Fixed tag Tooltip colors (linux)<commit_after>// Copyright 2014 Toggl Desktop developers. #include "./timeentrycellwidget.h" #include "./ui_timeentrycellwidget.h" #include "./toggl.h" TimeEntryCellWidget::TimeEntryCellWidget() : QWidget(0), ui(new Ui::TimeEntryCellWidget), guid("") { ui->setupUi(this); } void TimeEntryCellWidget::display(TimeEntryView *view) { guid = view->GUID; QString description = (view->Description.length() > 0) ? view->Description : "(no description)"; ui->description->setText(description); ui->project->setText(view->ProjectAndTaskLabel); ui->project->setStyleSheet("color: '" + getProjectColor(view->Color) + "'"); ui->duration->setText(view->Duration); ui->billable->setVisible(view->Billable); ui->tags->setVisible(!view->Tags.isEmpty()); ui->headerFrame->setVisible(view->IsHeader); ui->date->setText(view->DateHeader); ui->dateDuration->setText(view->DateDuration); if (view->StartTimeString.length() > 0 && view->EndTimeString.length() > 0) { ui->duration->setToolTip( QString("<p style='color:black;background-color:white;'>" + view->StartTimeString + " - " + view->EndTimeString+"</p>")); } ui->tags->setToolTip( QString("<p style='color:black;background-color:white;'>" + (view->Tags).replace(QString("\t"), QString(", ")) + "</p>")); if (view->Description.length() > 0) { ui->description->setToolTip( QString("<p style='color:white;background-color:black;'>" + view->Description + "</p>")); } if (view->ProjectAndTaskLabel.length() > 0) { ui->project->setToolTip( QString("<p style='color:white;background-color:black;'>" + view->ProjectAndTaskLabel + "</p>")); } } void TimeEntryCellWidget::labelClicked(QString field_name) { TogglApi::instance->editTimeEntry(guid, field_name); } TimeEntryCellWidget::~TimeEntryCellWidget() { delete ui; } QSize TimeEntryCellWidget::getSizeHint(bool is_header) { if (is_header) { return QSize(minimumWidth(), sizeHint().height()); } return QSize(minimumWidth(), ui->dataFrame->height()); } void TimeEntryCellWidget::mousePressEvent(QMouseEvent *event) { TogglApi::instance->editTimeEntry(guid, ""); QWidget::mousePressEvent(event); } void TimeEntryCellWidget::on_continueButton_clicked() { TogglApi::instance->continueTimeEntry(guid); } QString TimeEntryCellWidget::getProjectColor(QString color) { if (color.length() == 0) { return QString("#9d9d9d"); } return color; } <|endoftext|>
<commit_before>#include "FileRepositoryDB.h" #include "utils.h" #include "FileRepositoryDBImpl.h" #include "Poco/TemporaryFile.h" using namespace boost::filesystem; static std::shared_ptr<ILogger> logger = LoggerFactory::getLogger("application.FileRepositoryDB"); FileRepositoryDB::FileRepositoryDB(std::shared_ptr<IStorageHandler> fileHandler, boost::filesystem::path dbPath, long long smallFileThreshold, long long bulkSize) { this->fileHandler = fileHandler; this->db = getOrCreateDb(dbPath, Text_Resource::FileRepository); this->smallFileBulkThreshold = smallFileThreshold; this->bulkSize = bulkSize; logger->DebugFormat("FileRepositoryDB::FileRepositoryDB() path:[%s] ", to_utf8(dbPath).c_str()); } IFileRepositoryDB::RepoHandle FileRepositoryDB::AddFile(boost::filesystem::path file, const std::string& digestType, const std::string& digest) { logger->DebugFormat("FileRepositoryDB::AddFile() path:[%s] digestType:[%s] digest:[%s]", file.string().c_str(), digestType.c_str(), digest.c_str()); std::string key = digest; if (!this->HasFile(key)) { if (!this->multiFile.HasFile(key)) { auto fileSize = (long long)boost::filesystem::file_size(file); if (fileSize < this->smallFileBulkThreshold) { logger->DebugFormat("FileRepositoryDB::AddFile() small file size:[%ld] digest:[%s]", fileSize, digest.c_str()); this->multiFile.AddFile(file, digest); if (this->multiFile.GetSize() > this->bulkSize) { logger->DebugFormat("FileRepositoryDB::AddFile() zipFile is large enough sending fileSize:[%d] zipfileSize:[%d]", fileSize, this->multiFile.GetSize()); this->SendMultiFile(); } else { logger->DebugFormat("FileRepositoryDB::AddFile() zipFile is not enough fileSize:[%d]", fileSize); } } else { logger->DebugFormat("FileRepositoryDB::AddFile() key [%s] is missing -> adding", key.c_str()); if (this->fileHandler->CopyFileToRepository(digest, file) == false) { logger->ErrorFormat("FileRepositoryDB::AddFile() key [%s] Failed", key.c_str()); } auto insertQuery = db->CreateStatement("INSERT INTO Files (Path, Size, Added, DigestType, DigestValue) VALUES (:path,:size,:added,:digestType,:digestValue)"); insertQuery->bind(":path", to_utf8(key)); insertQuery->bind(":size", fileSize); insertQuery->bind(":added", return_current_time_and_date()); insertQuery->bind(":digestType", digestType); insertQuery->bind(":digestValue", key); insertQuery->exec(); } } else { logger->DebugFormat("FileRepositoryDB::AddFile() key:[%s] exists in multiFile", key.c_str()); } } else { logger->DebugFormat("FileRepositoryDB::AddFile() key:[%s] exists", key.c_str()); } return key; } bool FileRepositoryDB::HasFile(const RepoHandle& handle) { bool retValue = this->GetFileLocalPath(handle, nullptr); logger->DebugFormat("FileRepositoryDB::HasFile() handle:[%s], retValue:[%d]", handle.c_str(), retValue); return retValue; } bool FileRepositoryDB::GetFile(const RepoHandle& handle, boost::filesystem::path outFilePath) { logger->DebugFormat("FileRepositoryDB::GetFile() handle:[%s] destination:[%s]", handle.c_str(), outFilePath.string().c_str()); std::string key = handle; boost::filesystem::path srcPath; bool retValue = false; if (this->GetFileLocalPath(key, &srcPath)) { boost::filesystem::create_directories(outFilePath.branch_path()); if (copy_file_logged(srcPath, outFilePath) == false) { logger->WarningFormat("FileRepositoryDB::GetFile() handle:[%s] destination:[%s] Failed", handle.c_str(), outFilePath.string().c_str()); } } else { logger->WarningFormat("FileRepositoryDB::GetFile() handle:[%s] destination:[%s] Failed Missing in repository", handle.c_str(), outFilePath.string().c_str()); } return retValue; } void FileRepositoryDB::Complete() { logger->DebugFormat("FileRepositoryDB::Complete()"); if (this->multiFile.GetSize() != 0) { SendMultiFile(); } } bool FileRepositoryDB::GetFileLocalPath(const RepoHandle& handle, boost::filesystem::path* path) { std::string key = handle; auto query = db->CreateStatement("SELECT Path,MultiFileHostDigest FROM Files WHERE DigestValue=:key"); query->bind(":key", key); bool retValue = false; if (query->executeStep()) { if (path != nullptr) { auto pathColumn = query->getColumn("Path"); if (pathColumn->isNull() == false) { auto tempFileName = Poco::TemporaryFile::tempName(); this->fileHandler->CopyFileFromRepository(pathColumn->getString(), tempFileName); *path = tempFileName; } else { auto hostDigest = query->getColumn("MultiFileHostDigest")->getString(); if (this->zipFiles.find(hostDigest) == this->zipFiles.end()) { auto ziptempFileName = Poco::TemporaryFile::tempName(); this->fileHandler->CopyFileFromRepository(hostDigest, ziptempFileName); this->zipFiles[hostDigest] = std::make_shared<ZipWrapper>(ziptempFileName); } auto tempFileName = Poco::TemporaryFile::tempName(); auto multiFile = this->zipFiles[hostDigest]; multiFile->ExtractFile(key, tempFileName); *path = tempFileName; } } retValue = true; } logger->DebugFormat("FileRepositoryDB::GetFileLocalPath() handle:[%s] path:[%s] retValue:[%d]", handle.c_str(), (path == nullptr) ? L"null" : path->c_str(), retValue); return retValue; } void FileRepositoryDB::SendMultiFile() { logger->DebugFormat("FileRepositoryDB::SendMultiFile() Closing db:[%p]", db.get()); this->multiFile.Close(); logger->DebugFormat("FileRepositoryDB::SendMultiFile() Creating Transaction db:[%p]", db.get()); auto transaction = db->CreateTransaction(); logger->DebugFormat("FileRepositoryDB::SendMultiFile()"); auto digest = calcHash(this->multiFile.zipFile); for (std::map<std::string, MultiFile::fileEntry>::iterator iter = this->multiFile.entries.begin(); iter != this->multiFile.entries.end(); ++iter) { auto currEntry = (*iter).second; auto insertQuery = db->CreateStatement("INSERT INTO Files (Size, Added, DigestType, DigestValue, MultiFileHostDigest) VALUES (:size,:added,:digestType,:digestValue,:hostDigest)"); insertQuery->bind(":size", currEntry.size); insertQuery->bind(":added", return_current_time_and_date()); insertQuery->bind(":digestType", "SHA1"); insertQuery->bind(":digestValue", currEntry.digest); insertQuery->bind(":hostDigest", digest); insertQuery->exec(); } auto fileSize = (long long)boost::filesystem::file_size(this->multiFile.zipFile); auto key = digest; if (this->fileHandler->CopyFileToRepository(digest, this->multiFile.zipFile) == false) { logger->ErrorFormat("FileRepositoryDB::AddFile() key:[%s] Failed", key.c_str()); } auto insertQuery = db->CreateStatement("INSERT INTO Files (Path, Size, Added, DigestType, DigestValue) VALUES (:path,:size,:added,:digestType,:digestValue)"); insertQuery->bind(":path", to_utf8(digest)); insertQuery->bind(":size", fileSize); insertQuery->bind(":added", return_current_time_and_date()); insertQuery->bind(":digestType", "SHA1"); insertQuery->bind(":digestValue", digest); insertQuery->exec(); transaction->commit(); this->multiFile = MultiFile(); } std::shared_ptr<IFileRepositoryDB> CreateFileRepositoryDB( std::shared_ptr<IStorageHandler> storageHander, boost::filesystem::path dbPath, long maxSizeToBulk, long bulkSize) { logger->DebugFormat("Creating FileRepositoryDB dbPath:[%s] minFileToBulk:[%lld] fileBulkSize:[%lld]", dbPath.string().c_str(), maxSizeToBulk, bulkSize); return std::make_shared<FileRepositoryDB>( storageHander, dbPath, maxSizeToBulk, bulkSize); } <commit_msg>fix linux compilation<commit_after>#include "FileRepositoryDB.h" #include "utils.h" #include "FileRepositoryDBImpl.h" #include "Poco/TemporaryFile.h" using namespace boost::filesystem; static std::shared_ptr<ILogger> logger = LoggerFactory::getLogger("application.FileRepositoryDB"); FileRepositoryDB::FileRepositoryDB(std::shared_ptr<IStorageHandler> fileHandler, boost::filesystem::path dbPath, long long smallFileThreshold, long long bulkSize) { this->fileHandler = fileHandler; this->db = getOrCreateDb(dbPath, Text_Resource::FileRepository); this->smallFileBulkThreshold = smallFileThreshold; this->bulkSize = bulkSize; logger->DebugFormat("FileRepositoryDB::FileRepositoryDB() path:[%s] ", to_utf8(dbPath).c_str()); } IFileRepositoryDB::RepoHandle FileRepositoryDB::AddFile(boost::filesystem::path file, const std::string& digestType, const std::string& digest) { logger->DebugFormat("FileRepositoryDB::AddFile() path:[%s] digestType:[%s] digest:[%s]", file.string().c_str(), digestType.c_str(), digest.c_str()); std::string key = digest; if (!this->HasFile(key)) { if (!this->multiFile.HasFile(key)) { auto fileSize = (long long)boost::filesystem::file_size(file); if (fileSize < this->smallFileBulkThreshold) { logger->DebugFormat("FileRepositoryDB::AddFile() small file size:[%ld] digest:[%s]", fileSize, digest.c_str()); this->multiFile.AddFile(file, digest); if (this->multiFile.GetSize() > this->bulkSize) { logger->DebugFormat("FileRepositoryDB::AddFile() zipFile is large enough sending fileSize:[%d] zipfileSize:[%d]", fileSize, this->multiFile.GetSize()); this->SendMultiFile(); } else { logger->DebugFormat("FileRepositoryDB::AddFile() zipFile is not enough fileSize:[%d]", fileSize); } } else { logger->DebugFormat("FileRepositoryDB::AddFile() key [%s] is missing -> adding", key.c_str()); if (this->fileHandler->CopyFileToRepository(digest, file) == false) { logger->ErrorFormat("FileRepositoryDB::AddFile() key [%s] Failed", key.c_str()); } auto insertQuery = db->CreateStatement("INSERT INTO Files (Path, Size, Added, DigestType, DigestValue) VALUES (:path,:size,:added,:digestType,:digestValue)"); insertQuery->bind(":path", to_utf8(key)); insertQuery->bind(":size", fileSize); insertQuery->bind(":added", return_current_time_and_date()); insertQuery->bind(":digestType", digestType); insertQuery->bind(":digestValue", key); insertQuery->exec(); } } else { logger->DebugFormat("FileRepositoryDB::AddFile() key:[%s] exists in multiFile", key.c_str()); } } else { logger->DebugFormat("FileRepositoryDB::AddFile() key:[%s] exists", key.c_str()); } return key; } bool FileRepositoryDB::HasFile(const RepoHandle& handle) { bool retValue = this->GetFileLocalPath(handle, nullptr); logger->DebugFormat("FileRepositoryDB::HasFile() handle:[%s], retValue:[%d]", handle.c_str(), retValue); return retValue; } bool FileRepositoryDB::GetFile(const RepoHandle& handle, boost::filesystem::path outFilePath) { logger->DebugFormat("FileRepositoryDB::GetFile() handle:[%s] destination:[%s]", handle.c_str(), outFilePath.string().c_str()); std::string key = handle; boost::filesystem::path srcPath; bool retValue = false; if (this->GetFileLocalPath(key, &srcPath)) { boost::filesystem::create_directories(outFilePath.branch_path()); if (copy_file_logged(srcPath, outFilePath) == false) { logger->WarningFormat("FileRepositoryDB::GetFile() handle:[%s] destination:[%s] Failed", handle.c_str(), outFilePath.string().c_str()); } } else { logger->WarningFormat("FileRepositoryDB::GetFile() handle:[%s] destination:[%s] Failed Missing in repository", handle.c_str(), outFilePath.string().c_str()); } return retValue; } void FileRepositoryDB::Complete() { logger->DebugFormat("FileRepositoryDB::Complete()"); if (this->multiFile.GetSize() != 0) { SendMultiFile(); } } bool FileRepositoryDB::GetFileLocalPath(const RepoHandle& handle, boost::filesystem::path* path) { std::string key = handle; auto query = db->CreateStatement("SELECT Path,MultiFileHostDigest FROM Files WHERE DigestValue=:key"); query->bind(":key", key); bool retValue = false; if (query->executeStep()) { if (path != nullptr) { auto pathColumn = query->getColumn("Path"); if (pathColumn->isNull() == false) { auto tempFileName = Poco::TemporaryFile::tempName(); this->fileHandler->CopyFileFromRepository(pathColumn->getString(), tempFileName); *path = tempFileName; } else { auto hostDigest = query->getColumn("MultiFileHostDigest")->getString(); if (this->zipFiles.find(hostDigest) == this->zipFiles.end()) { auto ziptempFileName = Poco::TemporaryFile::tempName(); this->fileHandler->CopyFileFromRepository(hostDigest, ziptempFileName); this->zipFiles[hostDigest] = std::make_shared<ZipWrapper>(ziptempFileName); } auto tempFileName = Poco::TemporaryFile::tempName(); auto multiFile = this->zipFiles[hostDigest]; multiFile->ExtractFile(key, tempFileName); *path = tempFileName; } } retValue = true; } logger->DebugFormat("FileRepositoryDB::GetFileLocalPath() handle:[%s] path:[%ws] retValue:[%d]", handle.c_str(), (path == nullptr) ? L"null" : path->generic_wstring().c_str(), retValue); return retValue; } void FileRepositoryDB::SendMultiFile() { logger->DebugFormat("FileRepositoryDB::SendMultiFile() Closing db:[%p]", db.get()); this->multiFile.Close(); logger->DebugFormat("FileRepositoryDB::SendMultiFile() Creating Transaction db:[%p]", db.get()); auto transaction = db->CreateTransaction(); logger->DebugFormat("FileRepositoryDB::SendMultiFile()"); auto digest = calcHash(this->multiFile.zipFile); for (std::map<std::string, MultiFile::fileEntry>::iterator iter = this->multiFile.entries.begin(); iter != this->multiFile.entries.end(); ++iter) { auto currEntry = (*iter).second; auto insertQuery = db->CreateStatement("INSERT INTO Files (Size, Added, DigestType, DigestValue, MultiFileHostDigest) VALUES (:size,:added,:digestType,:digestValue,:hostDigest)"); insertQuery->bind(":size", currEntry.size); insertQuery->bind(":added", return_current_time_and_date()); insertQuery->bind(":digestType", "SHA1"); insertQuery->bind(":digestValue", currEntry.digest); insertQuery->bind(":hostDigest", digest); insertQuery->exec(); } auto fileSize = (long long)boost::filesystem::file_size(this->multiFile.zipFile); auto key = digest; if (this->fileHandler->CopyFileToRepository(digest, this->multiFile.zipFile) == false) { logger->ErrorFormat("FileRepositoryDB::AddFile() key:[%s] Failed", key.c_str()); } auto insertQuery = db->CreateStatement("INSERT INTO Files (Path, Size, Added, DigestType, DigestValue) VALUES (:path,:size,:added,:digestType,:digestValue)"); insertQuery->bind(":path", to_utf8(digest)); insertQuery->bind(":size", fileSize); insertQuery->bind(":added", return_current_time_and_date()); insertQuery->bind(":digestType", "SHA1"); insertQuery->bind(":digestValue", digest); insertQuery->exec(); transaction->commit(); this->multiFile = MultiFile(); } std::shared_ptr<IFileRepositoryDB> CreateFileRepositoryDB( std::shared_ptr<IStorageHandler> storageHander, boost::filesystem::path dbPath, long maxSizeToBulk, long bulkSize) { logger->DebugFormat("Creating FileRepositoryDB dbPath:[%s] minFileToBulk:[%lld] fileBulkSize:[%lld]", dbPath.string().c_str(), maxSizeToBulk, bulkSize); return std::make_shared<FileRepositoryDB>( storageHander, dbPath, maxSizeToBulk, bulkSize); } <|endoftext|>
<commit_before>/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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. */ /* * $Id$ */ // --------------------------------------------------------------------------- // Includes // --------------------------------------------------------------------------- #include <xercesc/framework/XMLBuffer.hpp> #include <xercesc/validators/common/ContentSpecNode.hpp> #include <xercesc/validators/schema/SchemaSymbols.hpp> XERCES_CPP_NAMESPACE_BEGIN // --------------------------------------------------------------------------- // ContentSpecNode: Copy Constructor // // Note: this copy constructor has dependency on various get*() methods // and shall be placed after those method's declaration. // aka inline function compilation error on AIX 4.2, xlC 3 r ev.1 // --------------------------------------------------------------------------- ContentSpecNode::ContentSpecNode(const ContentSpecNode& toCopy) : XSerializable(toCopy) , XMemory(toCopy) , fMemoryManager(toCopy.fMemoryManager) , fElement(0) , fElementDecl(toCopy.fElementDecl) , fFirst(0) , fSecond(0) , fType(toCopy.fType) , fAdoptFirst(true) , fAdoptSecond(true) , fMinOccurs(toCopy.fMinOccurs) , fMaxOccurs(toCopy.fMaxOccurs) { const QName* tempElement = toCopy.getElement(); if (tempElement) fElement = new (fMemoryManager) QName(*tempElement); const ContentSpecNode *tmp = toCopy.getFirst(); if (tmp) fFirst = new (fMemoryManager) ContentSpecNode(*tmp); tmp = toCopy.getSecond(); if (tmp) fSecond = new (fMemoryManager) ContentSpecNode(*tmp); } // --------------------------------------------------------------------------- // Local methods // --------------------------------------------------------------------------- static void formatNode( const ContentSpecNode* const curNode , const ContentSpecNode::NodeTypes parentType , XMLBuffer& bufToFill) { if (!curNode) return; const ContentSpecNode* first = curNode->getFirst(); const ContentSpecNode* second = curNode->getSecond(); const ContentSpecNode::NodeTypes curType = curNode->getType(); // Get the type of the first node const ContentSpecNode::NodeTypes firstType = first ? first->getType() : ContentSpecNode::Leaf; // Calculate the parens flag for the rep nodes bool doRepParens = false; if (((firstType != ContentSpecNode::Leaf) && (parentType != ContentSpecNode::UnknownType)) || ((firstType == ContentSpecNode::Leaf) && (parentType == ContentSpecNode::UnknownType))) { doRepParens = true; } // Now handle our type switch(curType & 0x0f) { case ContentSpecNode::Leaf : if (curNode->getElement()->getURI() == XMLElementDecl::fgPCDataElemId) bufToFill.append(XMLElementDecl::fgPCDataElemName); else { bufToFill.append(curNode->getElement()->getRawName()); // show the + and * modifiers also when we have a non-infinite number of repetitions if(curNode->getMinOccurs()==0 && (curNode->getMaxOccurs()==-1 || curNode->getMaxOccurs()>1)) bufToFill.append(chAsterisk); else if(curNode->getMinOccurs()==0 && curNode->getMaxOccurs()==1) bufToFill.append(chQuestion); else if(curNode->getMinOccurs()==1 && (curNode->getMaxOccurs()==-1 || curNode->getMaxOccurs()>1)) bufToFill.append(chPlus); } break; case ContentSpecNode::ZeroOrOne : if (doRepParens) bufToFill.append(chOpenParen); formatNode(first, curType, bufToFill); if (doRepParens) bufToFill.append(chCloseParen); bufToFill.append(chQuestion); break; case ContentSpecNode::ZeroOrMore : if (doRepParens) bufToFill.append(chOpenParen); formatNode(first, curType, bufToFill); if (doRepParens) bufToFill.append(chCloseParen); bufToFill.append(chAsterisk); break; case ContentSpecNode::OneOrMore : if (doRepParens) bufToFill.append(chOpenParen); formatNode(first, curType, bufToFill); if (doRepParens) bufToFill.append(chCloseParen); bufToFill.append(chPlus); break; case ContentSpecNode::Choice : if ((parentType & 0x0f) != (curType & 0x0f)) bufToFill.append(chOpenParen); formatNode(first, curType, bufToFill); if(second!=NULL) { bufToFill.append(chPipe); formatNode(second, curType, bufToFill); } if ((parentType & 0x0f) != (curType & 0x0f)) bufToFill.append(chCloseParen); break; case ContentSpecNode::Sequence : if ((parentType & 0x0f) != (curType & 0x0f)) bufToFill.append(chOpenParen); formatNode(first, curType, bufToFill); if(second!=NULL) { bufToFill.append(chComma); formatNode(second, curType, bufToFill); } if ((parentType & 0x0f) != (curType & 0x0f)) bufToFill.append(chCloseParen); break; case ContentSpecNode::All : if ((parentType & 0x0f) != (curType & 0x0f)) { bufToFill.append(chLatin_A); bufToFill.append(chLatin_l); bufToFill.append(chLatin_l); bufToFill.append(chOpenParen); } formatNode(first, curType, bufToFill); bufToFill.append(chComma); formatNode(second, curType, bufToFill); if ((parentType & 0x0f) != (curType & 0x0f)) bufToFill.append(chCloseParen); break; } } // --------------------------------------------------------------------------- // ContentSpecNode: Miscellaneous // --------------------------------------------------------------------------- void ContentSpecNode::formatSpec(XMLBuffer& bufToFill) const { // Clean out the buffer first bufToFill.reset(); if (fType == ContentSpecNode::Leaf) bufToFill.append(chOpenParen); formatNode ( this , UnknownType , bufToFill ); if (fType == ContentSpecNode::Leaf) bufToFill.append(chCloseParen); } int ContentSpecNode::getMinTotalRange() const { int min = fMinOccurs; if ((fType & 0x0f) == ContentSpecNode::Sequence || fType == ContentSpecNode::All || (fType & 0x0f) == ContentSpecNode::Choice) { int minFirst = fFirst->getMinTotalRange(); if (fSecond) { int minSecond = fSecond->getMinTotalRange(); if ((fType & 0x0f) == ContentSpecNode::Choice) { min = min * ((minFirst < minSecond)? minFirst : minSecond); } else { min = min * (minFirst + minSecond); } } else min = min * minFirst; } return min; } int ContentSpecNode::getMaxTotalRange() const { int max = fMaxOccurs; if (max == SchemaSymbols::XSD_UNBOUNDED) { return SchemaSymbols::XSD_UNBOUNDED; } if ((fType & 0x0f) == ContentSpecNode::Sequence || fType == ContentSpecNode::All || (fType & 0x0f) == ContentSpecNode::Choice) { int maxFirst = fFirst->getMaxTotalRange(); if (maxFirst == SchemaSymbols::XSD_UNBOUNDED) { return SchemaSymbols::XSD_UNBOUNDED; } if (fSecond) { int maxSecond = fSecond->getMaxTotalRange(); if (maxSecond == SchemaSymbols::XSD_UNBOUNDED) { return SchemaSymbols::XSD_UNBOUNDED; } else { if ((fType & 0x0f) == ContentSpecNode::Choice) { max = max * (maxFirst > maxSecond) ? maxFirst : maxSecond; } else { max = max * (maxFirst + maxSecond); } } } else { max = max * maxFirst; } } return max; } /*** * Support for Serialization/De-serialization ***/ IMPL_XSERIALIZABLE_TOCREATE(ContentSpecNode) void ContentSpecNode::serialize(XSerializeEngine& serEng) { /*** * Since fElement, fFirst, fSecond are NOT created by the default * constructor, we need to create them dynamically. ***/ if (serEng.isStoring()) { serEng<<fElement; XMLElementDecl::storeElementDecl(serEng, fElementDecl); serEng<<fFirst; serEng<<fSecond; serEng<<(int)fType; serEng<<fAdoptFirst; serEng<<fAdoptSecond; serEng<<fMinOccurs; serEng<<fMaxOccurs; } else { serEng>>fElement; fElementDecl = XMLElementDecl::loadElementDecl(serEng); serEng>>fFirst; serEng>>fSecond; int type; serEng>>type; fType = (NodeTypes)type; serEng>>fAdoptFirst; serEng>>fAdoptSecond; serEng>>fMinOccurs; serEng>>fMaxOccurs; } } XERCES_CPP_NAMESPACE_END <commit_msg>XERCESC-1994<commit_after>/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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. */ /* * $Id$ */ // --------------------------------------------------------------------------- // Includes // --------------------------------------------------------------------------- #include <xercesc/framework/XMLBuffer.hpp> #include <xercesc/validators/common/ContentSpecNode.hpp> #include <xercesc/validators/schema/SchemaSymbols.hpp> XERCES_CPP_NAMESPACE_BEGIN // --------------------------------------------------------------------------- // ContentSpecNode: Copy Constructor // // Note: this copy constructor has dependency on various get*() methods // and shall be placed after those method's declaration. // aka inline function compilation error on AIX 4.2, xlC 3 r ev.1 // --------------------------------------------------------------------------- ContentSpecNode::ContentSpecNode(const ContentSpecNode& toCopy) : XSerializable(toCopy) , XMemory(toCopy) , fMemoryManager(toCopy.fMemoryManager) , fElement(0) , fElementDecl(toCopy.fElementDecl) , fFirst(0) , fSecond(0) , fType(toCopy.fType) , fAdoptFirst(true) , fAdoptSecond(true) , fMinOccurs(toCopy.fMinOccurs) , fMaxOccurs(toCopy.fMaxOccurs) { const QName* tempElement = toCopy.getElement(); if (tempElement) fElement = new (fMemoryManager) QName(*tempElement); const ContentSpecNode *tmp = toCopy.getFirst(); if (tmp) fFirst = new (fMemoryManager) ContentSpecNode(*tmp); tmp = toCopy.getSecond(); if (tmp) fSecond = new (fMemoryManager) ContentSpecNode(*tmp); } // --------------------------------------------------------------------------- // Local methods // --------------------------------------------------------------------------- static void formatNode( const ContentSpecNode* const curNode , const ContentSpecNode::NodeTypes parentType , XMLBuffer& bufToFill) { if (!curNode) return; const ContentSpecNode* first = curNode->getFirst(); const ContentSpecNode* second = curNode->getSecond(); const ContentSpecNode::NodeTypes curType = curNode->getType(); // Get the type of the first node const ContentSpecNode::NodeTypes firstType = first ? first->getType() : ContentSpecNode::Leaf; // Calculate the parens flag for the rep nodes bool doRepParens = false; if (((firstType != ContentSpecNode::Leaf) && (parentType != ContentSpecNode::UnknownType)) || ((firstType == ContentSpecNode::Leaf) && (parentType == ContentSpecNode::UnknownType))) { doRepParens = true; } // Now handle our type switch(curType & 0x0f) { case ContentSpecNode::Leaf : if (curNode->getElement()->getURI() == XMLElementDecl::fgPCDataElemId) bufToFill.append(XMLElementDecl::fgPCDataElemName); else { bufToFill.append(curNode->getElement()->getRawName()); // show the + and * modifiers also when we have a non-infinite number of repetitions if(curNode->getMinOccurs()==0 && (curNode->getMaxOccurs()==-1 || curNode->getMaxOccurs()>1)) bufToFill.append(chAsterisk); else if(curNode->getMinOccurs()==0 && curNode->getMaxOccurs()==1) bufToFill.append(chQuestion); else if(curNode->getMinOccurs()==1 && (curNode->getMaxOccurs()==-1 || curNode->getMaxOccurs()>1)) bufToFill.append(chPlus); } break; case ContentSpecNode::ZeroOrOne : if (doRepParens) bufToFill.append(chOpenParen); formatNode(first, curType, bufToFill); if (doRepParens) bufToFill.append(chCloseParen); bufToFill.append(chQuestion); break; case ContentSpecNode::ZeroOrMore : if (doRepParens) bufToFill.append(chOpenParen); formatNode(first, curType, bufToFill); if (doRepParens) bufToFill.append(chCloseParen); bufToFill.append(chAsterisk); break; case ContentSpecNode::OneOrMore : if (doRepParens) bufToFill.append(chOpenParen); formatNode(first, curType, bufToFill); if (doRepParens) bufToFill.append(chCloseParen); bufToFill.append(chPlus); break; case ContentSpecNode::Choice : if ((parentType & 0x0f) != (curType & 0x0f)) bufToFill.append(chOpenParen); formatNode(first, curType, bufToFill); if(second!=NULL) { bufToFill.append(chPipe); formatNode(second, curType, bufToFill); } if ((parentType & 0x0f) != (curType & 0x0f)) bufToFill.append(chCloseParen); break; case ContentSpecNode::Sequence : if ((parentType & 0x0f) != (curType & 0x0f)) bufToFill.append(chOpenParen); formatNode(first, curType, bufToFill); if(second!=NULL) { bufToFill.append(chComma); formatNode(second, curType, bufToFill); } if ((parentType & 0x0f) != (curType & 0x0f)) bufToFill.append(chCloseParen); break; case ContentSpecNode::All : if ((parentType & 0x0f) != (curType & 0x0f)) { bufToFill.append(chLatin_A); bufToFill.append(chLatin_l); bufToFill.append(chLatin_l); bufToFill.append(chOpenParen); } formatNode(first, curType, bufToFill); bufToFill.append(chComma); formatNode(second, curType, bufToFill); if ((parentType & 0x0f) != (curType & 0x0f)) bufToFill.append(chCloseParen); break; } } // --------------------------------------------------------------------------- // ContentSpecNode: Miscellaneous // --------------------------------------------------------------------------- void ContentSpecNode::formatSpec(XMLBuffer& bufToFill) const { // Clean out the buffer first bufToFill.reset(); if (fType == ContentSpecNode::Leaf) bufToFill.append(chOpenParen); formatNode ( this , UnknownType , bufToFill ); if (fType == ContentSpecNode::Leaf) bufToFill.append(chCloseParen); } int ContentSpecNode::getMinTotalRange() const { int min = fMinOccurs; if ((fType & 0x0f) == ContentSpecNode::Sequence || fType == ContentSpecNode::All || (fType & 0x0f) == ContentSpecNode::Choice) { int minFirst = fFirst->getMinTotalRange(); if (fSecond) { int minSecond = fSecond->getMinTotalRange(); if ((fType & 0x0f) == ContentSpecNode::Choice) { min = min * ((minFirst < minSecond)? minFirst : minSecond); } else { min = min * (minFirst + minSecond); } } else min = min * minFirst; } return min; } int ContentSpecNode::getMaxTotalRange() const { int max = fMaxOccurs; if (max == SchemaSymbols::XSD_UNBOUNDED) { return SchemaSymbols::XSD_UNBOUNDED; } if ((fType & 0x0f) == ContentSpecNode::Sequence || fType == ContentSpecNode::All || (fType & 0x0f) == ContentSpecNode::Choice) { int maxFirst = fFirst->getMaxTotalRange(); if (maxFirst == SchemaSymbols::XSD_UNBOUNDED) { return SchemaSymbols::XSD_UNBOUNDED; } if (fSecond) { int maxSecond = fSecond->getMaxTotalRange(); if (maxSecond == SchemaSymbols::XSD_UNBOUNDED) { return SchemaSymbols::XSD_UNBOUNDED; } else { if ((fType & 0x0f) == ContentSpecNode::Choice) { max = max * ((maxFirst > maxSecond) ? maxFirst : maxSecond); } else { max = max * (maxFirst + maxSecond); } } } else { max = max * maxFirst; } } return max; } /*** * Support for Serialization/De-serialization ***/ IMPL_XSERIALIZABLE_TOCREATE(ContentSpecNode) void ContentSpecNode::serialize(XSerializeEngine& serEng) { /*** * Since fElement, fFirst, fSecond are NOT created by the default * constructor, we need to create them dynamically. ***/ if (serEng.isStoring()) { serEng<<fElement; XMLElementDecl::storeElementDecl(serEng, fElementDecl); serEng<<fFirst; serEng<<fSecond; serEng<<(int)fType; serEng<<fAdoptFirst; serEng<<fAdoptSecond; serEng<<fMinOccurs; serEng<<fMaxOccurs; } else { serEng>>fElement; fElementDecl = XMLElementDecl::loadElementDecl(serEng); serEng>>fFirst; serEng>>fSecond; int type; serEng>>type; fType = (NodeTypes)type; serEng>>fAdoptFirst; serEng>>fAdoptSecond; serEng>>fMinOccurs; serEng>>fMaxOccurs; } } XERCES_CPP_NAMESPACE_END <|endoftext|>
<commit_before>/* * Copyright 2001,2004 The Apache Software Foundation. * * 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. */ /** * $Id$ */ #if !defined(GRAMMARRESOLVER_HPP) #define GRAMMARRESOLVER_HPP #include <xercesc/framework/XMLGrammarPool.hpp> #include <xercesc/util/RefHashTableOf.hpp> #include <xercesc/util/StringPool.hpp> #include <xercesc/validators/common/Grammar.hpp> XERCES_CPP_NAMESPACE_BEGIN class DatatypeValidator; class DatatypeValidatorFactory; class XMLGrammarDescription; /** * This class embodies the representation of a Grammar pool Resolver. * This class is called from the validator. * */ class VALIDATORS_EXPORT GrammarResolver : public XMemory { public: /** @name Constructor and Destructor */ //@{ /** * * Default Constructor */ GrammarResolver( XMLGrammarPool* const gramPool , MemoryManager* const manager = XMLPlatformUtils::fgMemoryManager ); /** * Destructor */ ~GrammarResolver(); //@} /** @name Getter methods */ //@{ /** * Retrieve the DatatypeValidator * * @param uriStr the namespace URI * @param typeName the type name * @return the DatatypeValidator associated with namespace & type name */ DatatypeValidator* getDatatypeValidator(const XMLCh* const uriStr, const XMLCh* const typeName); /** * Retrieve the grammar that is associated with the specified namespace key * * @param gramDesc grammar description for the grammar * @return Grammar abstraction associated with the grammar description */ Grammar* getGrammar( XMLGrammarDescription* const gramDesc ) ; /** * Retrieve the grammar that is associated with the specified namespace key * * @param namespaceKey Namespace key into Grammar pool * @return Grammar abstraction associated with the NameSpace key. */ Grammar* getGrammar( const XMLCh* const namespaceKey ) ; /** * Get an enumeration of Grammar in the Grammar pool * * @return enumeration of Grammar in Grammar pool */ RefHashTableOfEnumerator<Grammar> getGrammarEnumerator() const; /** * Get an enumeration of the referenced Grammars * * @return enumeration of referenced Grammars */ RefHashTableOfEnumerator<Grammar> getReferencedGrammarEnumerator() const; /** * Get an enumeration of the cached Grammars in the Grammar pool * * @return enumeration of the cached Grammars in Grammar pool */ RefHashTableOfEnumerator<Grammar> getCachedGrammarEnumerator() const; /** * Get a string pool of schema grammar element/attribute names/prefixes * (used by TraverseSchema) * * @return a string pool of schema grammar element/attribute names/prefixes */ XMLStringPool* getStringPool(); /** * Is the specified Namespace key in Grammar pool? * * @param nameSpaceKey Namespace key * @return True if Namespace key association is in the Grammar pool. */ bool containsNameSpace( const XMLCh* const nameSpaceKey ); inline XMLGrammarPool* getGrammarPool() const; inline MemoryManager* getGrammarPoolMemoryManager() const; //@} /** @name Setter methods */ //@{ /** * Set the 'Grammar caching' flag */ void cacheGrammarFromParse(const bool newState); /** * Set the 'Use cached grammar' flag */ void useCachedGrammarInParse(const bool newState); //@} /** @name GrammarResolver methods */ //@{ /** * Add the Grammar with Namespace Key associated to the Grammar Pool. * The Grammar will be owned by the Grammar Pool. * * @param grammarToAdopt Grammar abstraction used by validator. */ void putGrammar(Grammar* const grammarToAdopt ); /** * Returns the Grammar with Namespace Key associated from the Grammar Pool * The Key entry is removed from the table (grammar is not deleted if * adopted - now owned by caller). * * @param nameSpaceKey Key to associate with Grammar abstraction */ Grammar* orphanGrammar(const XMLCh* const nameSpaceKey); /** * Cache the grammars in fGrammarBucket to fCachedGrammarRegistry. * If a grammar with the same key is already cached, an exception is * thrown and none of the grammars will be cached. */ void cacheGrammars(); /** * Reset internal Namespace/Grammar registry. */ void reset(); void resetCachedGrammar(); /** * Returns an XSModel, either from the GrammarPool or by creating one */ XSModel* getXSModel(); ValueVectorOf<SchemaGrammar*>* getGrammarsToAddToXSModel(); //@} private: // ----------------------------------------------------------------------- // Unimplemented constructors and operators // ----------------------------------------------------------------------- GrammarResolver(const GrammarResolver&); GrammarResolver& operator=(const GrammarResolver&); // ----------------------------------------------------------------------- // Private data members // // fStringPool The string pool used by TraverseSchema to store // element/attribute names and prefixes. // Always owned by Grammar pool implementation // // fGrammarBucket The parsed Grammar Pool, if no caching option. // // fGrammarFromPool Referenced Grammar Set, not owned // // fGrammarPool The Grammar Set either plugged or created. // // fDataTypeReg DatatypeValidatorFactory registery // // fMemoryManager Pluggable memory manager for dynamic memory // allocation/deallocation // ----------------------------------------------------------------------- bool fCacheGrammar; bool fUseCachedGrammar; bool fGrammarPoolFromExternalApplication; XMLStringPool* fStringPool; RefHashTableOf<Grammar>* fGrammarBucket; RefHashTableOf<Grammar>* fGrammarFromPool; DatatypeValidatorFactory* fDataTypeReg; MemoryManager* fMemoryManager; XMLGrammarPool* fGrammarPool; XSModel* fXSModel; XSModel* fGrammarPoolXSModel; ValueVectorOf<SchemaGrammar*>* fGrammarsToAddToXSModel; }; inline XMLStringPool* GrammarResolver::getStringPool() { return fStringPool; } inline void GrammarResolver::useCachedGrammarInParse(const bool aValue) { fUseCachedGrammar = aValue; } inline XMLGrammarPool* GrammarResolver::getGrammarPool() const { return fGrammarPool; } inline MemoryManager* GrammarResolver::getGrammarPoolMemoryManager() const { return fGrammarPool->getMemoryManager(); } inline ValueVectorOf<SchemaGrammar*>* GrammarResolver::getGrammarsToAddToXSModel() { return fGrammarsToAddToXSModel; } XERCES_CPP_NAMESPACE_END #endif <commit_msg>Added method to expose data member<commit_after>/* * Copyright 2001,2004 The Apache Software Foundation. * * 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. */ /** * $Id$ */ #if !defined(GRAMMARRESOLVER_HPP) #define GRAMMARRESOLVER_HPP #include <xercesc/framework/XMLGrammarPool.hpp> #include <xercesc/util/RefHashTableOf.hpp> #include <xercesc/util/StringPool.hpp> #include <xercesc/validators/common/Grammar.hpp> XERCES_CPP_NAMESPACE_BEGIN class DatatypeValidator; class DatatypeValidatorFactory; class XMLGrammarDescription; /** * This class embodies the representation of a Grammar pool Resolver. * This class is called from the validator. * */ class VALIDATORS_EXPORT GrammarResolver : public XMemory { public: /** @name Constructor and Destructor */ //@{ /** * * Default Constructor */ GrammarResolver( XMLGrammarPool* const gramPool , MemoryManager* const manager = XMLPlatformUtils::fgMemoryManager ); /** * Destructor */ ~GrammarResolver(); //@} /** @name Getter methods */ //@{ /** * Retrieve the DatatypeValidator * * @param uriStr the namespace URI * @param typeName the type name * @return the DatatypeValidator associated with namespace & type name */ DatatypeValidator* getDatatypeValidator(const XMLCh* const uriStr, const XMLCh* const typeName); /** * Retrieve the DatatypeValidatorFactory used for built-in schema types * * @return the DatatypeValidator associated with namespace for XMLSchema */ DatatypeValidatorFactory* getBuiltinDatatypeValidatorFactory(); /** * Retrieve the grammar that is associated with the specified namespace key * * @param gramDesc grammar description for the grammar * @return Grammar abstraction associated with the grammar description */ Grammar* getGrammar( XMLGrammarDescription* const gramDesc ) ; /** * Retrieve the grammar that is associated with the specified namespace key * * @param namespaceKey Namespace key into Grammar pool * @return Grammar abstraction associated with the NameSpace key. */ Grammar* getGrammar( const XMLCh* const namespaceKey ) ; /** * Get an enumeration of Grammar in the Grammar pool * * @return enumeration of Grammar in Grammar pool */ RefHashTableOfEnumerator<Grammar> getGrammarEnumerator() const; /** * Get an enumeration of the referenced Grammars * * @return enumeration of referenced Grammars */ RefHashTableOfEnumerator<Grammar> getReferencedGrammarEnumerator() const; /** * Get an enumeration of the cached Grammars in the Grammar pool * * @return enumeration of the cached Grammars in Grammar pool */ RefHashTableOfEnumerator<Grammar> getCachedGrammarEnumerator() const; /** * Get a string pool of schema grammar element/attribute names/prefixes * (used by TraverseSchema) * * @return a string pool of schema grammar element/attribute names/prefixes */ XMLStringPool* getStringPool(); /** * Is the specified Namespace key in Grammar pool? * * @param nameSpaceKey Namespace key * @return True if Namespace key association is in the Grammar pool. */ bool containsNameSpace( const XMLCh* const nameSpaceKey ); inline XMLGrammarPool* getGrammarPool() const; inline MemoryManager* getGrammarPoolMemoryManager() const; //@} /** @name Setter methods */ //@{ /** * Set the 'Grammar caching' flag */ void cacheGrammarFromParse(const bool newState); /** * Set the 'Use cached grammar' flag */ void useCachedGrammarInParse(const bool newState); //@} /** @name GrammarResolver methods */ //@{ /** * Add the Grammar with Namespace Key associated to the Grammar Pool. * The Grammar will be owned by the Grammar Pool. * * @param grammarToAdopt Grammar abstraction used by validator. */ void putGrammar(Grammar* const grammarToAdopt ); /** * Returns the Grammar with Namespace Key associated from the Grammar Pool * The Key entry is removed from the table (grammar is not deleted if * adopted - now owned by caller). * * @param nameSpaceKey Key to associate with Grammar abstraction */ Grammar* orphanGrammar(const XMLCh* const nameSpaceKey); /** * Cache the grammars in fGrammarBucket to fCachedGrammarRegistry. * If a grammar with the same key is already cached, an exception is * thrown and none of the grammars will be cached. */ void cacheGrammars(); /** * Reset internal Namespace/Grammar registry. */ void reset(); void resetCachedGrammar(); /** * Returns an XSModel, either from the GrammarPool or by creating one */ XSModel* getXSModel(); ValueVectorOf<SchemaGrammar*>* getGrammarsToAddToXSModel(); //@} private: // ----------------------------------------------------------------------- // Unimplemented constructors and operators // ----------------------------------------------------------------------- GrammarResolver(const GrammarResolver&); GrammarResolver& operator=(const GrammarResolver&); // ----------------------------------------------------------------------- // Private data members // // fStringPool The string pool used by TraverseSchema to store // element/attribute names and prefixes. // Always owned by Grammar pool implementation // // fGrammarBucket The parsed Grammar Pool, if no caching option. // // fGrammarFromPool Referenced Grammar Set, not owned // // fGrammarPool The Grammar Set either plugged or created. // // fDataTypeReg DatatypeValidatorFactory registery // // fMemoryManager Pluggable memory manager for dynamic memory // allocation/deallocation // ----------------------------------------------------------------------- bool fCacheGrammar; bool fUseCachedGrammar; bool fGrammarPoolFromExternalApplication; XMLStringPool* fStringPool; RefHashTableOf<Grammar>* fGrammarBucket; RefHashTableOf<Grammar>* fGrammarFromPool; DatatypeValidatorFactory* fDataTypeReg; MemoryManager* fMemoryManager; XMLGrammarPool* fGrammarPool; XSModel* fXSModel; XSModel* fGrammarPoolXSModel; ValueVectorOf<SchemaGrammar*>* fGrammarsToAddToXSModel; }; inline XMLStringPool* GrammarResolver::getStringPool() { return fStringPool; } inline void GrammarResolver::useCachedGrammarInParse(const bool aValue) { fUseCachedGrammar = aValue; } inline XMLGrammarPool* GrammarResolver::getGrammarPool() const { return fGrammarPool; } inline MemoryManager* GrammarResolver::getGrammarPoolMemoryManager() const { return fGrammarPool->getMemoryManager(); } inline ValueVectorOf<SchemaGrammar*>* GrammarResolver::getGrammarsToAddToXSModel() { return fGrammarsToAddToXSModel; } inline DatatypeValidatorFactory* GrammarResolver::getBuiltinDatatypeValidatorFactory() { return fDataTypeReg; } XERCES_CPP_NAMESPACE_END #endif <|endoftext|>
<commit_before>/* * The Apache Software License, Version 1.1 * * Copyright (c) 2001 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. 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. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Xerces" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact apache\@apache.org. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR * ITS 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. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation, and was * originally based on software copyright (c) 1999, International * Business Machines, Inc., http://www.ibm.com . For more information * on the Apache Software Foundation, please see * <http://www.apache.org/>. */ /* * $Log$ * Revision 1.8 2003/10/17 21:17:12 peiyongz * using XTemplateSerializer * * Revision 1.7 2003/10/14 15:22:28 peiyongz * Implementation of Serialization/Deserialization * * Revision 1.6 2003/05/18 14:02:08 knoaman * Memory manager implementation: pass per instance manager. * * Revision 1.5 2003/05/15 18:57:27 knoaman * Partial implementation of the configurable memory manager. * * Revision 1.4 2002/11/04 14:49:42 tng * C++ Namespace Support. * * Revision 1.3 2002/04/01 15:47:06 knoaman * Move Element Consistency checking (ref to global declarations) to SchemaValidator. * * Revision 1.2 2002/03/25 20:25:32 knoaman * Move particle derivation checking from TraverseSchema to SchemaValidator. * * Revision 1.1.1.1 2002/02/01 22:22:50 peiyongz * sane_include * * Revision 1.2 2001/08/24 20:36:37 knoaman * Add support for <redefine>. * * Revision 1.1 2001/07/24 18:33:46 knoaman * Added support for <group> + extra constraint checking for complexType * */ // --------------------------------------------------------------------------- // Includes // --------------------------------------------------------------------------- #include <xercesc/validators/schema/XercesGroupInfo.hpp> #include <xercesc/validators/common/ContentSpecNode.hpp> #include <xercesc/validators/schema/XSDLocator.hpp> #include <xercesc/internal/XTemplateSerializer.hpp> XERCES_CPP_NAMESPACE_BEGIN // --------------------------------------------------------------------------- // XercesGroupInfo: Constructors and Destructor // --------------------------------------------------------------------------- XercesGroupInfo::XercesGroupInfo(MemoryManager* const manager) : fCheckElementConsistency(true) , fScope(-1) , fContentSpec(0) , fElements(0) , fBaseGroup(0) , fLocator(0) { fElements = new (manager) RefVectorOf<SchemaElementDecl>(4, false, manager); } XercesGroupInfo::~XercesGroupInfo() { delete fElements; delete fContentSpec; delete fLocator; } // --------------------------------------------------------------------------- // XercesGroupInfo: Constructors and Destructor // --------------------------------------------------------------------------- void XercesGroupInfo::setLocator(XSDLocator* const aLocator) { if (fLocator) delete fLocator; fLocator = aLocator; } /*** * Support for Serialization/De-serialization ***/ IMPL_XSERIALIZABLE_TOCREATE(XercesGroupInfo) void XercesGroupInfo::serialize(XSerializeEngine& serEng) { if (serEng.isStoring()) { serEng<<fCheckElementConsistency; serEng<<fScope; serEng<<fContentSpec; /*** * * Serialize RefVectorOf<SchemaElementDecl>* fElements; * ***/ XTemplateSerializer::storeObject(fElements, serEng); serEng<<fBaseGroup; //don't serialize XSDLocator* fLocator; } else { serEng>>fCheckElementConsistency; serEng>>fScope; serEng>>fContentSpec; /*** * * Deserialize RefVectorOf<SchemaElementDecl>* fElements; * ***/ XTemplateSerializer::loadObject(&fElements, 8, true, serEng); serEng>>fBaseGroup; //don't serialize XSDLocator* fLocator; fLocator = 0; } } XERCES_CPP_NAMESPACE_END /** * End of file XercesGroupInfo.cpp */ <commit_msg>don't own the element list pointed to by fElements<commit_after>/* * The Apache Software License, Version 1.1 * * Copyright (c) 2001 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. 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. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Xerces" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact apache\@apache.org. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR * ITS 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. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation, and was * originally based on software copyright (c) 1999, International * Business Machines, Inc., http://www.ibm.com . For more information * on the Apache Software Foundation, please see * <http://www.apache.org/>. */ /* * $Log$ * Revision 1.9 2003/10/29 16:21:52 peiyongz * don't own the element list pointed to by fElements * * Revision 1.8 2003/10/17 21:17:12 peiyongz * using XTemplateSerializer * * Revision 1.7 2003/10/14 15:22:28 peiyongz * Implementation of Serialization/Deserialization * * Revision 1.6 2003/05/18 14:02:08 knoaman * Memory manager implementation: pass per instance manager. * * Revision 1.5 2003/05/15 18:57:27 knoaman * Partial implementation of the configurable memory manager. * * Revision 1.4 2002/11/04 14:49:42 tng * C++ Namespace Support. * * Revision 1.3 2002/04/01 15:47:06 knoaman * Move Element Consistency checking (ref to global declarations) to SchemaValidator. * * Revision 1.2 2002/03/25 20:25:32 knoaman * Move particle derivation checking from TraverseSchema to SchemaValidator. * * Revision 1.1.1.1 2002/02/01 22:22:50 peiyongz * sane_include * * Revision 1.2 2001/08/24 20:36:37 knoaman * Add support for <redefine>. * * Revision 1.1 2001/07/24 18:33:46 knoaman * Added support for <group> + extra constraint checking for complexType * */ // --------------------------------------------------------------------------- // Includes // --------------------------------------------------------------------------- #include <xercesc/validators/schema/XercesGroupInfo.hpp> #include <xercesc/validators/common/ContentSpecNode.hpp> #include <xercesc/validators/schema/XSDLocator.hpp> #include <xercesc/internal/XTemplateSerializer.hpp> XERCES_CPP_NAMESPACE_BEGIN // --------------------------------------------------------------------------- // XercesGroupInfo: Constructors and Destructor // --------------------------------------------------------------------------- XercesGroupInfo::XercesGroupInfo(MemoryManager* const manager) : fCheckElementConsistency(true) , fScope(-1) , fContentSpec(0) , fElements(0) , fBaseGroup(0) , fLocator(0) { fElements = new (manager) RefVectorOf<SchemaElementDecl>(4, false, manager); } XercesGroupInfo::~XercesGroupInfo() { delete fElements; delete fContentSpec; delete fLocator; } // --------------------------------------------------------------------------- // XercesGroupInfo: Constructors and Destructor // --------------------------------------------------------------------------- void XercesGroupInfo::setLocator(XSDLocator* const aLocator) { if (fLocator) delete fLocator; fLocator = aLocator; } /*** * Support for Serialization/De-serialization ***/ IMPL_XSERIALIZABLE_TOCREATE(XercesGroupInfo) void XercesGroupInfo::serialize(XSerializeEngine& serEng) { if (serEng.isStoring()) { serEng<<fCheckElementConsistency; serEng<<fScope; serEng<<fContentSpec; /*** * * Serialize RefVectorOf<SchemaElementDecl>* fElements; * ***/ XTemplateSerializer::storeObject(fElements, serEng); serEng<<fBaseGroup; //don't serialize XSDLocator* fLocator; } else { serEng>>fCheckElementConsistency; serEng>>fScope; serEng>>fContentSpec; /*** * * Deserialize RefVectorOf<SchemaElementDecl>* fElements; * ***/ XTemplateSerializer::loadObject(&fElements, 8, false, serEng); serEng>>fBaseGroup; //don't serialize XSDLocator* fLocator; fLocator = 0; } } XERCES_CPP_NAMESPACE_END /** * End of file XercesGroupInfo.cpp */ <|endoftext|>
<commit_before>/* * This file is a part of Xpiks - cross platform application for * keywording and uploading images for microstocks * Copyright (C) 2014-2015 Taras Kushnir <[email protected]> * * Xpiks is distributed under the GNU General Public License, version 3.0 * * 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 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <QDebug> #include <QUrlQuery> #include <QJsonDocument> #include <QJsonObject> #include <QByteArray> #include <QString> #include <QThread> #include "suggestionqueryengine.h" #include "suggestionartwork.h" #include "keywordssuggestor.h" #include "../Encryption/aes-qt.h" #include "libraryqueryworker.h" #include "locallibrary.h" #define MAX_LOCAL_RESULTS 100 namespace Suggestion { SuggestionQueryEngine::SuggestionQueryEngine(KeywordsSuggestor *keywordsSuggestor): QObject(keywordsSuggestor), m_NetworkManager(this), m_Suggestor(keywordsSuggestor) { m_ClientId = "28a2a9b917961a0cbc343c81b2dd0f6618377f9210aa3182e5cc9f5588f914d918ede1533c9e06b91769c89e80909743"; m_ClientSecret = "5092d9a967c2f19b57aac29bc09ac3b9e6ae5baec1a371331b73ff24f1625d95c4f3fef90bdacfbe9b0b3803b48c269192bc55f14bb9c2b5a16d650cd641b746eb384fcf9dbd53a96f1f81215921b04409f3635ecf846ffdf01ee04ba76624c9"; QObject::connect(&m_NetworkManager, SIGNAL(finished(QNetworkReply*)), this, SLOT(replyReceived(QNetworkReply*))); } void SuggestionQueryEngine::submitQuery(const QStringList &queryKeywords) { QUrl url = buildQuery(queryKeywords); QNetworkRequest request(url); QString decodedClientId = Encryption::decodeText(m_ClientId, "MasterPassword"); QString decodedClientSecret = Encryption::decodeText(m_ClientSecret, "MasterPassword"); QString authStr = QString("%1:%2").arg(decodedClientId).arg(decodedClientSecret); QString headerData = "Basic " + authStr.toLocal8Bit().toBase64(); request.setRawHeader("Authorization", headerData.toLocal8Bit()); QNetworkReply *reply = m_NetworkManager.get(request); QObject::connect(this, SIGNAL(cancelAllQueries()), reply, SLOT(abort())); } void SuggestionQueryEngine::submitLocalQuery(LocalLibrary *localLibrary, const QStringList &queryKeywords) { LibraryQueryWorker *worker = new LibraryQueryWorker(localLibrary, queryKeywords, MAX_LOCAL_RESULTS); QThread *thread = new QThread(); worker->moveToThread(thread); QObject::connect(thread, SIGNAL(started()), worker, SLOT(process())); QObject::connect(worker, SIGNAL(stopped()), thread, SLOT(quit())); QObject::connect(worker, SIGNAL(stopped()), worker, SLOT(deleteLater())); QObject::connect(thread, SIGNAL(finished()), thread, SLOT(deleteLater())); QObject::connect(this, SIGNAL(cancelAllQueries()), worker, SLOT(cancel())); QObject::connect(worker, SIGNAL(resultsFound(QVector<SuggestionArtwork*> *)), this, SLOT(artworksFound(QVector<SuggestionArtwork*> *))); thread->start(); } void SuggestionQueryEngine::cancelQueries() { emit cancelAllQueries(); } void SuggestionQueryEngine::replyReceived(QNetworkReply *networkReply) { if (networkReply->error() == QNetworkReply::NoError) { QJsonDocument document = QJsonDocument::fromJson(networkReply->readAll()); QJsonObject jsonObject = document.object(); QJsonValue dataValue = jsonObject["data"]; if (dataValue.isArray()) { QVector<SuggestionArtwork*> suggestionArtworks; parseResponse(dataValue.toArray(), suggestionArtworks); m_Suggestor->setSuggestedArtworks(suggestionArtworks); } } else { qDebug() << networkReply->errorString(); } m_Suggestor->unsetInProgress(); networkReply->deleteLater(); } void SuggestionQueryEngine::artworksFound(QVector<SuggestionArtwork *> *suggestions) { m_Suggestor->setSuggestedArtworks(*suggestions); delete suggestions; } void SuggestionQueryEngine::parseResponse(const QJsonArray &jsonArray, QVector<SuggestionArtwork*> &suggestionArtworks) { foreach (const QJsonValue &value, jsonArray) { QJsonObject imageResult = value.toObject(); if (imageResult.contains("assets")) { QJsonObject assetsObject = imageResult["assets"].toObject(); if (assetsObject.contains("large_thumb")) { QJsonObject thumb = assetsObject["large_thumb"].toObject(); if (thumb.contains("url")) { QString url = thumb["url"].toString(); QStringList keywordsList; if (imageResult["keywords"].isArray()) { foreach (const QJsonValue &keyword, imageResult["keywords"].toArray()) { keywordsList.append(keyword.toString()); } } SuggestionArtwork *artwork = new SuggestionArtwork(url, keywordsList); suggestionArtworks.append(artwork); } } } } } QUrl SuggestionQueryEngine::buildQuery(const QStringList &queryKeywords) const { QUrlQuery urlQuery; QString queryString = QString("https://api.shutterstock.com/v2/images/search"); urlQuery.addQueryItem("language", "en"); urlQuery.addQueryItem("view", "full"); urlQuery.addQueryItem("per_page", "75"); urlQuery.addQueryItem("query", queryKeywords.join(' ')); QUrl url; url.setUrl(queryString); url.setQuery(urlQuery); return url; } } <commit_msg>Increased number of suggestions from shutterstock. closes #171<commit_after>/* * This file is a part of Xpiks - cross platform application for * keywording and uploading images for microstocks * Copyright (C) 2014-2015 Taras Kushnir <[email protected]> * * Xpiks is distributed under the GNU General Public License, version 3.0 * * 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 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <QDebug> #include <QUrlQuery> #include <QJsonDocument> #include <QJsonObject> #include <QByteArray> #include <QString> #include <QThread> #include "suggestionqueryengine.h" #include "suggestionartwork.h" #include "keywordssuggestor.h" #include "../Encryption/aes-qt.h" #include "libraryqueryworker.h" #include "locallibrary.h" #define MAX_LOCAL_RESULTS 100 namespace Suggestion { SuggestionQueryEngine::SuggestionQueryEngine(KeywordsSuggestor *keywordsSuggestor): QObject(keywordsSuggestor), m_NetworkManager(this), m_Suggestor(keywordsSuggestor) { m_ClientId = "28a2a9b917961a0cbc343c81b2dd0f6618377f9210aa3182e5cc9f5588f914d918ede1533c9e06b91769c89e80909743"; m_ClientSecret = "5092d9a967c2f19b57aac29bc09ac3b9e6ae5baec1a371331b73ff24f1625d95c4f3fef90bdacfbe9b0b3803b48c269192bc55f14bb9c2b5a16d650cd641b746eb384fcf9dbd53a96f1f81215921b04409f3635ecf846ffdf01ee04ba76624c9"; QObject::connect(&m_NetworkManager, SIGNAL(finished(QNetworkReply*)), this, SLOT(replyReceived(QNetworkReply*))); } void SuggestionQueryEngine::submitQuery(const QStringList &queryKeywords) { QUrl url = buildQuery(queryKeywords); QNetworkRequest request(url); QString decodedClientId = Encryption::decodeText(m_ClientId, "MasterPassword"); QString decodedClientSecret = Encryption::decodeText(m_ClientSecret, "MasterPassword"); QString authStr = QString("%1:%2").arg(decodedClientId).arg(decodedClientSecret); QString headerData = "Basic " + authStr.toLocal8Bit().toBase64(); request.setRawHeader("Authorization", headerData.toLocal8Bit()); QNetworkReply *reply = m_NetworkManager.get(request); QObject::connect(this, SIGNAL(cancelAllQueries()), reply, SLOT(abort())); } void SuggestionQueryEngine::submitLocalQuery(LocalLibrary *localLibrary, const QStringList &queryKeywords) { LibraryQueryWorker *worker = new LibraryQueryWorker(localLibrary, queryKeywords, MAX_LOCAL_RESULTS); QThread *thread = new QThread(); worker->moveToThread(thread); QObject::connect(thread, SIGNAL(started()), worker, SLOT(process())); QObject::connect(worker, SIGNAL(stopped()), thread, SLOT(quit())); QObject::connect(worker, SIGNAL(stopped()), worker, SLOT(deleteLater())); QObject::connect(thread, SIGNAL(finished()), thread, SLOT(deleteLater())); QObject::connect(this, SIGNAL(cancelAllQueries()), worker, SLOT(cancel())); QObject::connect(worker, SIGNAL(resultsFound(QVector<SuggestionArtwork*> *)), this, SLOT(artworksFound(QVector<SuggestionArtwork*> *))); thread->start(); } void SuggestionQueryEngine::cancelQueries() { emit cancelAllQueries(); } void SuggestionQueryEngine::replyReceived(QNetworkReply *networkReply) { if (networkReply->error() == QNetworkReply::NoError) { QJsonDocument document = QJsonDocument::fromJson(networkReply->readAll()); QJsonObject jsonObject = document.object(); QJsonValue dataValue = jsonObject["data"]; if (dataValue.isArray()) { QVector<SuggestionArtwork*> suggestionArtworks; parseResponse(dataValue.toArray(), suggestionArtworks); m_Suggestor->setSuggestedArtworks(suggestionArtworks); } } else { qDebug() << networkReply->errorString(); } m_Suggestor->unsetInProgress(); networkReply->deleteLater(); } void SuggestionQueryEngine::artworksFound(QVector<SuggestionArtwork *> *suggestions) { m_Suggestor->setSuggestedArtworks(*suggestions); delete suggestions; } void SuggestionQueryEngine::parseResponse(const QJsonArray &jsonArray, QVector<SuggestionArtwork*> &suggestionArtworks) { foreach (const QJsonValue &value, jsonArray) { QJsonObject imageResult = value.toObject(); if (imageResult.contains("assets")) { QJsonObject assetsObject = imageResult["assets"].toObject(); if (assetsObject.contains("large_thumb")) { QJsonObject thumb = assetsObject["large_thumb"].toObject(); if (thumb.contains("url")) { QString url = thumb["url"].toString(); QStringList keywordsList; if (imageResult["keywords"].isArray()) { foreach (const QJsonValue &keyword, imageResult["keywords"].toArray()) { keywordsList.append(keyword.toString()); } } SuggestionArtwork *artwork = new SuggestionArtwork(url, keywordsList); suggestionArtworks.append(artwork); } } } } } QUrl SuggestionQueryEngine::buildQuery(const QStringList &queryKeywords) const { QUrlQuery urlQuery; QString queryString = QString("https://api.shutterstock.com/v2/images/search"); urlQuery.addQueryItem("language", "en"); urlQuery.addQueryItem("view", "full"); urlQuery.addQueryItem("per_page", "100"); urlQuery.addQueryItem("query", queryKeywords.join(' ')); QUrl url; url.setUrl(queryString); url.setQuery(urlQuery); return url; } } <|endoftext|>
<commit_before>#include <errno.h> #include <dlfcn.h> #include <fcntl.h> #include <stdio.h> #include <string.h> #include <sys/epoll.h> #include <unistd.h> #include "coroutine.h" // stack size static const int kProtectStackSize = 10 * 1024; static const int kDefaulaStackSize = 100 * 1024; // coroutine num static const int kCoroNum = 256; // allocate free id num static const int kAllocateFreeNum = 100; static const int kStatusDead = 0; static const int kStatusReady = 1; static const int kStatusRunning = 2; static const int kStatusSuspend = 3; typedef int (*sysAccept)(int, struct sockaddr *, socklen_t *); typedef ssize_t (*sysRecv)(int fd, void *buf, size_t len, int flags); typedef ssize_t (*sysSend)(int fd, const void *buf, size_t len, int flags); typedef int (*sysClose)(int fd); static sysAccept gSysAccept; static sysRecv gSysRecv; static sysSend gSysSend; static sysClose gSysClose; Scheduler gSched; struct Coroutine { void *arg_; cfunc fun_; int id_; char *stack_; int status_; ucontext_t ctx_; Coroutine(void *arg, cfunc fun, int id) : arg_(arg), fun_(fun), id_(id), stack_(NULL), status_(kStatusReady) { stack_ = new char[kProtectStackSize + kDefaulaStackSize]; } ~Coroutine() { delete [] stack_; } }; struct Socket { int fd_; Coroutine* coro_; }; Scheduler::Scheduler() : epfd_(-1), running_(-1), num_(0), free_count_(0) { coros_.resize(kCoroNum, NULL); socks_.resize(kCoroNum, NULL); epfd_ = epoll_create(1024); gSysAccept = (sysAccept)dlsym(RTLD_NEXT, "accept"); gSysRecv = (sysRecv)dlsym(RTLD_NEXT, "recv"); gSysSend = (sysSend)dlsym(RTLD_NEXT, "send"); gSysClose = (sysClose)dlsym(RTLD_NEXT, "close"); } Scheduler::~Scheduler() { size_t i; for (i = 0; i < coros_.size(); ++i) { if (coros_[i]) { delete coros_[i]; } if (socks_[i]) { delete socks_[i]; } } } void Scheduler::AllocateFreeIds() { int i; for (i = 1; i <= kAllocateFreeNum; ++i) { free_ids_.push_back(i + free_count_); } free_count_ += kAllocateFreeNum; } int Scheduler::NewId() { int i; if (free_ids_.empty()) { AllocateFreeIds(); } i = free_ids_.front(); free_ids_.pop_front(); return i; } int Scheduler::Spawn(void *arg, cfunc fun) { int id; Coroutine *coro; id = NewId(); coro = new Coroutine(arg, fun, id); coros_[id] = coro; active_.push_back(coro); return id; } void Scheduler::Yield() { int id; Coroutine *coro; id = running_; coro = coros_[id]; coro->status_ = kStatusSuspend; running_ = -1; swapcontext(&coro->ctx_, &main_); } int Scheduler::Status(int id) { Coroutine *coro; coro = coros_[id]; if (coro == NULL) { return kStatusDead; } return coro->status_; } void mainfunc(void *) { Scheduler *sched = &gSched; int id = sched->running_; Coroutine *coro = sched->coros_[id]; coro->fun_(coro->arg_); sched->free_ids_.push_back(coro->id_); delete coro; sched->coros_[id] = NULL; --sched->num_; sched->running_ = -1; } void Scheduler::Resume(int id) { Coroutine *coro = coros_[id]; if (coro == NULL) { return; } int status = coro->status_; switch(status) { case kStatusReady: getcontext(&coro->ctx_); coro->ctx_.uc_stack.ss_sp = coro->stack_; coro->ctx_.uc_stack.ss_size = kDefaulaStackSize; coro->ctx_.uc_link = &main_; running_ = id; coro->status_ = kStatusRunning; makecontext(&coro->ctx_, (void (*)(void))mainfunc, 1, this); swapcontext(&main_, &coro->ctx_); break; case kStatusSuspend: running_ = id; coro->status_ = kStatusRunning; swapcontext(&main_, &coro->ctx_); break; default: break; } } void Scheduler::Run() { while (1) { list<Coroutine*>::iterator iter; for (iter = active_.begin(); iter != active_.end(); ++iter) { Resume((*iter)->id_); } CheckNetwork(); } } int Scheduler::Accept(int fd, struct sockaddr *addr, socklen_t *addrlen) { Coroutine *coro = coros_[running_]; epoll_event ev; memset(&ev, 0, sizeof(struct epoll_event)); Socket *sock = socks_[fd]; if (sock == NULL) { sock = new Socket(); socks_[fd] = sock; sock->fd_ = fd; sock->coro_ = coro; } ev.data.ptr = (void*)sock; ev.events = EPOLLIN; if (epoll_ctl(epfd_, EPOLL_CTL_ADD, fd, &ev) != 0) { printf("epoll_ctl error:%s\n", strerror(errno)); return -1; } swap: coro->status_ = kStatusSuspend; swapcontext(&coro->ctx_, &main_); epoll_ctl(epfd_, EPOLL_CTL_DEL, fd, &ev); int s; do { s = gSysAccept(fd, addr, addrlen); if (s < 0) { if (errno == EAGAIN || errno == EWOULDBLOCK) { goto swap; } else if (errno != EINTR) { printf("accept errno: %s\n", strerror(errno)); return -1; } else { // EINTR continue; } } fcntl(s, F_SETFL, fcntl(fd, F_GETFL) | O_NONBLOCK); break; } while(true); return s; } void Scheduler::CheckNetwork() { epoll_event events[1024]; int nfds = epoll_wait(epfd_, events, 1024, -1); if (nfds > 0) { int i; Socket *sock; for(i = 0 ; i < nfds ; ++i) { if(events[i].events & (EPOLLIN || EPOLLOUT)) { sock = (Socket*)events[i].data.ptr; active_.push_back(sock->coro_); continue; } } } else { printf("epoll error: %s:%d\n", strerror(errno), errno); } } ssize_t Scheduler::Recv(int fd, void *buf, size_t len, int flags) { ssize_t ret; Coroutine *coro = coros_[running_]; epoll_event ev; memset(&ev, 0, sizeof(struct epoll_event)); Socket *sock = socks_[fd]; if (sock == NULL) { sock = new Socket(); socks_[fd] = sock; sock->fd_ = fd; sock->coro_ = coro; } ev.data.ptr = (void*)sock; ev.events = EPOLLIN; if (epoll_ctl(epfd_, EPOLL_CTL_ADD, fd, &ev) != 0) { printf("recv add epoll error: %s\n", strerror(errno)); return -1; } ret = 0; swap: coro->status_ = kStatusSuspend; swapcontext(&coro->ctx_, &main_); epoll_ctl(epfd_, EPOLL_CTL_DEL, fd, &ev); while (ret < (ssize_t)len) { ssize_t nbytes = gSysRecv(fd, (char*)buf + ret, len - ret, flags); if (nbytes == -1) { if (errno == EAGAIN || errno == EWOULDBLOCK) { goto swap; } else if (errno != EINTR) { return -1; } else { // EINTR continue; } } if (nbytes == 0) { return -1; } ret += nbytes; if (nbytes < (ssize_t)len - ret) { break; } } return ret; } ssize_t Scheduler::Send(int fd, const void *buf, size_t len, int flags) { Coroutine *coro = coros_[running_]; ssize_t ret; epoll_event ev; memset(&ev, 0, sizeof(struct epoll_event)); Socket *sock = socks_[fd]; if (sock == NULL) { sock = new Socket(); socks_[fd] = sock; sock->fd_ = fd; sock->coro_ = coro; } ev.data.ptr = (void*)sock; ev.events = EPOLLOUT; if (epoll_ctl(epfd_, EPOLL_CTL_ADD, fd, &ev) != 0) { return -1; } ret = 0; swap: coro->status_ = kStatusSuspend; swapcontext(&coro->ctx_, &main_); epoll_ctl(epfd_, EPOLL_CTL_DEL, fd, &ev); while (ret < (ssize_t)len) { ssize_t nbytes = gSysSend(fd, (char*)buf + ret, len - ret, flags | MSG_NOSIGNAL); if (nbytes == -1) { if (errno == EAGAIN || errno == EWOULDBLOCK) { goto swap; } else if (errno != EINTR) { return -1; } else { // EINTR continue; } } if (nbytes == 0) { return -1; } ret += nbytes; if (ret == (ssize_t)len) { break; } } return ret; } int Scheduler::Close(int fd) { if (socks_[fd]) { delete socks_[fd]; socks_[fd] = NULL; } return gSysClose(fd); } <commit_msg>refactor newid algo<commit_after>#include <errno.h> #include <dlfcn.h> #include <fcntl.h> #include <stdio.h> #include <string.h> #include <sys/epoll.h> #include <unistd.h> #include "coroutine.h" // stack size static const int kProtectStackSize = 10 * 1024; static const int kDefaulaStackSize = 100 * 1024; // coroutine num static const int kCoroNum = 256; // allocate free id num static const int kAllocateFreeNum = 100; static const int kStatusDead = 0; static const int kStatusReady = 1; static const int kStatusRunning = 2; static const int kStatusSuspend = 3; typedef int (*sysAccept)(int, struct sockaddr *, socklen_t *); typedef ssize_t (*sysRecv)(int fd, void *buf, size_t len, int flags); typedef ssize_t (*sysSend)(int fd, const void *buf, size_t len, int flags); typedef int (*sysClose)(int fd); static sysAccept gSysAccept; static sysRecv gSysRecv; static sysSend gSysSend; static sysClose gSysClose; Scheduler gSched; struct Coroutine { void *arg_; cfunc fun_; int id_; char *stack_; int status_; ucontext_t ctx_; Coroutine(void *arg, cfunc fun, int id) : arg_(arg), fun_(fun), id_(id), stack_(NULL), status_(kStatusReady) { stack_ = new char[kProtectStackSize + kDefaulaStackSize]; } ~Coroutine() { delete [] stack_; } }; struct Socket { int fd_; Coroutine* coro_; }; Scheduler::Scheduler() : epfd_(-1), running_(-1), num_(0), free_count_(0) { coros_.resize(kCoroNum, NULL); socks_.resize(kCoroNum, NULL); AllocateFreeIds(); epfd_ = epoll_create(1024); gSysAccept = (sysAccept)dlsym(RTLD_NEXT, "accept"); gSysRecv = (sysRecv)dlsym(RTLD_NEXT, "recv"); gSysSend = (sysSend)dlsym(RTLD_NEXT, "send"); gSysClose = (sysClose)dlsym(RTLD_NEXT, "close"); } Scheduler::~Scheduler() { size_t i; for (i = 0; i < coros_.size(); ++i) { if (coros_[i]) { delete coros_[i]; } if (socks_[i]) { delete socks_[i]; } } } void Scheduler::AllocateFreeIds() { int i; for (i = 1; i <= kAllocateFreeNum; ++i) { free_ids_.push_back(i + free_count_); } free_count_ += kAllocateFreeNum; } int Scheduler::NewId() { int i; if (free_ids_.empty()) { AllocateFreeIds(); } i = free_ids_.front(); free_ids_.pop_front(); return i; } int Scheduler::Spawn(void *arg, cfunc fun) { int id; Coroutine *coro; id = NewId(); coro = new Coroutine(arg, fun, id); coros_[id] = coro; active_.push_back(coro); return id; } void Scheduler::Yield() { int id; Coroutine *coro; id = running_; coro = coros_[id]; coro->status_ = kStatusSuspend; running_ = -1; swapcontext(&coro->ctx_, &main_); } int Scheduler::Status(int id) { Coroutine *coro; coro = coros_[id]; if (coro == NULL) { return kStatusDead; } return coro->status_; } void mainfunc(void *) { Scheduler *sched = &gSched; int id = sched->running_; Coroutine *coro = sched->coros_[id]; coro->fun_(coro->arg_); sched->free_ids_.push_back(coro->id_); delete coro; sched->coros_[id] = NULL; --sched->num_; sched->running_ = -1; } void Scheduler::Resume(int id) { Coroutine *coro = coros_[id]; if (coro == NULL) { return; } int status = coro->status_; switch(status) { case kStatusReady: getcontext(&coro->ctx_); coro->ctx_.uc_stack.ss_sp = coro->stack_; coro->ctx_.uc_stack.ss_size = kDefaulaStackSize; coro->ctx_.uc_link = &main_; running_ = id; coro->status_ = kStatusRunning; makecontext(&coro->ctx_, (void (*)(void))mainfunc, 1, this); swapcontext(&main_, &coro->ctx_); break; case kStatusSuspend: running_ = id; coro->status_ = kStatusRunning; swapcontext(&main_, &coro->ctx_); break; default: break; } } void Scheduler::Run() { while (1) { list<Coroutine*>::iterator iter; for (iter = active_.begin(); iter != active_.end(); ++iter) { Resume((*iter)->id_); } CheckNetwork(); } } int Scheduler::Accept(int fd, struct sockaddr *addr, socklen_t *addrlen) { Coroutine *coro = coros_[running_]; epoll_event ev; memset(&ev, 0, sizeof(struct epoll_event)); Socket *sock = socks_[fd]; if (sock == NULL) { sock = new Socket(); socks_[fd] = sock; sock->fd_ = fd; sock->coro_ = coro; } ev.data.ptr = (void*)sock; ev.events = EPOLLIN; if (epoll_ctl(epfd_, EPOLL_CTL_ADD, fd, &ev) != 0) { printf("epoll_ctl error:%s\n", strerror(errno)); return -1; } swap: coro->status_ = kStatusSuspend; swapcontext(&coro->ctx_, &main_); epoll_ctl(epfd_, EPOLL_CTL_DEL, fd, &ev); int s; do { s = gSysAccept(fd, addr, addrlen); if (s < 0) { if (errno == EAGAIN || errno == EWOULDBLOCK) { goto swap; } else if (errno != EINTR) { printf("accept errno: %s\n", strerror(errno)); return -1; } else { // EINTR continue; } } fcntl(s, F_SETFL, fcntl(fd, F_GETFL) | O_NONBLOCK); break; } while(true); return s; } void Scheduler::CheckNetwork() { epoll_event events[1024]; int nfds = epoll_wait(epfd_, events, 1024, -1); if (nfds > 0) { int i; Socket *sock; for(i = 0 ; i < nfds ; ++i) { if(events[i].events & (EPOLLIN || EPOLLOUT)) { sock = (Socket*)events[i].data.ptr; active_.push_back(sock->coro_); continue; } } } else { printf("epoll error: %s:%d\n", strerror(errno), errno); } } ssize_t Scheduler::Recv(int fd, void *buf, size_t len, int flags) { ssize_t ret; Coroutine *coro = coros_[running_]; epoll_event ev; memset(&ev, 0, sizeof(struct epoll_event)); Socket *sock = socks_[fd]; if (sock == NULL) { sock = new Socket(); socks_[fd] = sock; sock->fd_ = fd; sock->coro_ = coro; } ev.data.ptr = (void*)sock; ev.events = EPOLLIN; if (epoll_ctl(epfd_, EPOLL_CTL_ADD, fd, &ev) != 0) { printf("recv add epoll error: %s\n", strerror(errno)); return -1; } ret = 0; swap: coro->status_ = kStatusSuspend; swapcontext(&coro->ctx_, &main_); epoll_ctl(epfd_, EPOLL_CTL_DEL, fd, &ev); while (ret < (ssize_t)len) { ssize_t nbytes = gSysRecv(fd, (char*)buf + ret, len - ret, flags); if (nbytes == -1) { if (errno == EAGAIN || errno == EWOULDBLOCK) { goto swap; } else if (errno != EINTR) { return -1; } else { // EINTR continue; } } if (nbytes == 0) { return -1; } ret += nbytes; if (nbytes < (ssize_t)len - ret) { break; } } return ret; } ssize_t Scheduler::Send(int fd, const void *buf, size_t len, int flags) { Coroutine *coro = coros_[running_]; ssize_t ret; epoll_event ev; memset(&ev, 0, sizeof(struct epoll_event)); Socket *sock = socks_[fd]; if (sock == NULL) { sock = new Socket(); socks_[fd] = sock; sock->fd_ = fd; sock->coro_ = coro; } ev.data.ptr = (void*)sock; ev.events = EPOLLOUT; if (epoll_ctl(epfd_, EPOLL_CTL_ADD, fd, &ev) != 0) { return -1; } ret = 0; swap: coro->status_ = kStatusSuspend; swapcontext(&coro->ctx_, &main_); epoll_ctl(epfd_, EPOLL_CTL_DEL, fd, &ev); while (ret < (ssize_t)len) { ssize_t nbytes = gSysSend(fd, (char*)buf + ret, len - ret, flags | MSG_NOSIGNAL); if (nbytes == -1) { if (errno == EAGAIN || errno == EWOULDBLOCK) { goto swap; } else if (errno != EINTR) { return -1; } else { // EINTR continue; } } if (nbytes == 0) { return -1; } ret += nbytes; if (ret == (ssize_t)len) { break; } } return ret; } int Scheduler::Close(int fd) { if (socks_[fd]) { delete socks_[fd]; socks_[fd] = NULL; } return gSysClose(fd); } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: e3dsceneproperties.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: pjunck $ $Date: 2004-11-03 10:31:06 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * 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 * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (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.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _SDR_PROPERTIES_E3DSCENEPROPERTIES_HXX #define _SDR_PROPERTIES_E3DSCENEPROPERTIES_HXX #ifndef _SDR_PROPERTIES_E3DPROPERTIES_HXX #include <svx/sdr/properties/e3dproperties.hxx> #endif // predeclarations class B3dLightGroup; ////////////////////////////////////////////////////////////////////////////// namespace sdr { namespace properties { class E3dSceneProperties : public E3dProperties { protected: // Called after ItemChange() is done for all items. virtual void PostItemChange(const sal_uInt16 nWhich); public: // basic constructor E3dSceneProperties(SdrObject& rObj); // constructor for copying, but using new object E3dSceneProperties(const E3dSceneProperties& rProps, SdrObject& rObj); // destructor virtual ~E3dSceneProperties(); // Clone() operator, normally just calls the local copy constructor virtual BaseProperties& Clone(SdrObject& rObj) const; // get itemset virtual const SfxItemSet& GetObjectItemSet() const; // get merged ItemSet. Normappl, this maps directly to GetObjectItemSet(), but may // be overloaded e.g for group objects to return a merged ItemSet of the object. // When using this method the returned ItemSet may contain items in the state // SFX_ITEM_DONTCARE which means there were several such items with different // values. virtual const SfxItemSet& GetMergedItemSet() const; // Set merged ItemSet. Normally, this maps to SetObjectItemSet(). virtual void SetMergedItemSet(const SfxItemSet& rSet, sal_Bool bClearAllItems = sal_False); // Set a single item, iterate over hierarchies if necessary. virtual void SetMergedItem(const SfxPoolItem& rItem); // Clear a single item, iterate over hierarchies if necessary. virtual void ClearMergedItem(const sal_uInt16 nWhich = 0); // set a new StyleSheet and broadcast virtual void SetStyleSheet(SfxStyleSheet* pNewStyleSheet, sal_Bool bDontRemoveHardAttr); // get the installed StyleSheet virtual SfxStyleSheet* GetStyleSheet() const; // pre/post-process saving //BFS01virtual void PreProcessSave(); //BFS01virtual void PostProcessSave(); // Move properties to a new ItemPool. Default implementation does nothing. virtual void MoveToItemPool(SfxItemPool* pSrcPool, SfxItemPool* pDestPool, SdrModel* pNewModel = 0L); // Special for scene: void SetLightItemsFromLightGroup(B3dLightGroup& rLightGroup); void SetSceneItemsFromCamera(); }; } // end of namespace properties } // end of namespace sdr ////////////////////////////////////////////////////////////////////////////// #endif // _SDR_PROPERTIES_E3DSCENEPROPERTIES_HXX // eof <commit_msg>INTEGRATION: CWS ooo19126 (1.3.598); FILE MERGED 2005/09/05 14:18:32 rt 1.3.598.1: #i54170# Change license header: remove SISSL<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: e3dsceneproperties.hxx,v $ * * $Revision: 1.4 $ * * last change: $Author: rt $ $Date: 2005-09-08 20:06:32 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * 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 * ************************************************************************/ #ifndef _SDR_PROPERTIES_E3DSCENEPROPERTIES_HXX #define _SDR_PROPERTIES_E3DSCENEPROPERTIES_HXX #ifndef _SDR_PROPERTIES_E3DPROPERTIES_HXX #include <svx/sdr/properties/e3dproperties.hxx> #endif // predeclarations class B3dLightGroup; ////////////////////////////////////////////////////////////////////////////// namespace sdr { namespace properties { class E3dSceneProperties : public E3dProperties { protected: // Called after ItemChange() is done for all items. virtual void PostItemChange(const sal_uInt16 nWhich); public: // basic constructor E3dSceneProperties(SdrObject& rObj); // constructor for copying, but using new object E3dSceneProperties(const E3dSceneProperties& rProps, SdrObject& rObj); // destructor virtual ~E3dSceneProperties(); // Clone() operator, normally just calls the local copy constructor virtual BaseProperties& Clone(SdrObject& rObj) const; // get itemset virtual const SfxItemSet& GetObjectItemSet() const; // get merged ItemSet. Normappl, this maps directly to GetObjectItemSet(), but may // be overloaded e.g for group objects to return a merged ItemSet of the object. // When using this method the returned ItemSet may contain items in the state // SFX_ITEM_DONTCARE which means there were several such items with different // values. virtual const SfxItemSet& GetMergedItemSet() const; // Set merged ItemSet. Normally, this maps to SetObjectItemSet(). virtual void SetMergedItemSet(const SfxItemSet& rSet, sal_Bool bClearAllItems = sal_False); // Set a single item, iterate over hierarchies if necessary. virtual void SetMergedItem(const SfxPoolItem& rItem); // Clear a single item, iterate over hierarchies if necessary. virtual void ClearMergedItem(const sal_uInt16 nWhich = 0); // set a new StyleSheet and broadcast virtual void SetStyleSheet(SfxStyleSheet* pNewStyleSheet, sal_Bool bDontRemoveHardAttr); // get the installed StyleSheet virtual SfxStyleSheet* GetStyleSheet() const; // pre/post-process saving //BFS01virtual void PreProcessSave(); //BFS01virtual void PostProcessSave(); // Move properties to a new ItemPool. Default implementation does nothing. virtual void MoveToItemPool(SfxItemPool* pSrcPool, SfxItemPool* pDestPool, SdrModel* pNewModel = 0L); // Special for scene: void SetLightItemsFromLightGroup(B3dLightGroup& rLightGroup); void SetSceneItemsFromCamera(); }; } // end of namespace properties } // end of namespace sdr ////////////////////////////////////////////////////////////////////////////// #endif // _SDR_PROPERTIES_E3DSCENEPROPERTIES_HXX // eof <|endoftext|>
<commit_before>/* Copyright 2020 The TensorFlow Authors. All Rights Reserved. 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 "tensorflow/compiler/xla/shape_util.h" #include "tensorflow/compiler/tf2xla/xla_op_kernel.h" #include "tensorflow/compiler/tf2xla/xla_op_registry.h" #include "tensorflow/compiler/tf2xla/xla_helpers.h" #include "tensorflow/compiler/xla/client/lib/comparators.h" #include "tensorflow/compiler/xla/client/lib/constants.h" #include "tensorflow/compiler/xla/client/lib/arithmetic.h" #include "tensorflow/compiler/xla/client/xla_computation.h" namespace tensorflow { namespace { // TODO: This is only a dummy kernel class DenseBincountOp : public XlaOpKernel { public: explicit DenseBincountOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) { DataType dtype; } void Compile(XlaOpKernelContext* ctx) override { // Dumb implementation for the simplest test case xla::XlaOp input = ctx->Input(0); int64_t output_size; ctx->ConstantInputAsIntScalar("size", &output_size); StatusOr<xla::Shape> input_shape_or = ctx->builder()->GetShape(input); OP_REQUIRES_OK(ctx, input_shape_or.status()); auto input_shape = input_shape_or.ValueOrDie(); auto size = input_shape.dimensions(0); auto dim = 1; auto rank = input_shape.rank(); auto counter_shape = xla::ShapeUtil::MakeShape(xla::S32, {}); const xla::Shape data_shape = xla::ShapeUtil::MakeShape(xla::S32, {input_shape.dimensions()}); xla::Shape output_shape = xla::ShapeUtil::MakeShape(xla::S32, {output_size}); if (rank == 2) { output_shape = xla::ShapeUtil::MakeShape(xla::S32, {rank, output_size}); dim = input_shape.dimensions(1); } auto loop_shape = xla::ShapeUtil::MakeTupleShape( {counter_shape, data_shape, output_shape}); // Create a computation for the condition xla::XlaComputation condition; { std::unique_ptr<xla::XlaBuilder> builder = ctx->builder()->CreateSubBuilder("condition"); auto param = xla::Parameter(builder.get(), 0, loop_shape, "param"); auto counter = xla::GetTupleElement(param, 0); xla::Gt(xla::ConstantR0<int32_t>(builder.get(), size*dim), counter); condition = builder->Build().ConsumeValueOrDie(); } // Create a computation for the body xla::XlaComputation body; { std::unique_ptr<xla::XlaBuilder> builder = ctx->builder()->CreateSubBuilder("body"); auto param = Parameter(builder.get(), 0, loop_shape, "param"); auto counter = xla::GetTupleElement(param, 0); auto data_stack = xla::GetTupleElement(param, 1); auto accum_stack = xla::GetTupleElement(param, 2); if (rank == 1) { auto data = xla::DynamicSlice(data_stack, {counter}, {1}); auto accum = xla::DynamicSlice(accum_stack, {data}, {1}); auto data_scalar = xla::Reshape(data, {0}, {}); auto condition_shape = xla::ShapeUtil::MakeTupleShape( {counter_shape, counter_shape, output_shape}); xla::XlaComputation update; { std::unique_ptr<xla::XlaBuilder> true_builder = builder->CreateSubBuilder("update"); auto param = Parameter(true_builder.get(), 0, condition_shape, "param"); auto data_scalar = xla::GetTupleElement(param, 0); auto accum = xla::GetTupleElement(param, 1); auto accum_stack = xla::GetTupleElement(param, 2); accum = accum + xla::One(true_builder.get(), xla::S32); accum_stack = xla::DynamicUpdateSlice( accum_stack, xla::Reshape(accum, {1}), {data_scalar}); xla::Tuple(true_builder.get(), {accum, accum_stack}); auto update = true_builder->Build().ValueOrDie(); } xla::XlaComputation no_update; { std::unique_ptr<xla::XlaBuilder> false_builder = builder->CreateSubBuilder("no_update"); auto param = Parameter(false_builder.get(), 0, condition_shape, "param"); auto data = xla::GetTupleElement(param, 0); auto accum = xla::GetTupleElement(param, 1); auto accum_stack = xla::GetTupleElement(param, 2); xla::Tuple(false_builder.get(), {accum, accum_stack}); auto no_update = false_builder->Build().ValueOrDie(); } std::unique_ptr<xla::XlaBuilder> cond_builder = builder->CreateSubBuilder("cond"); auto output_size_xla = xla::ConstantR0<int32_t>(cond_builder.get(), output_size); auto pred = xla::Lt(data_scalar, output_size_xla); auto tuple = xla::Tuple(cond_builder.get(), {data_scalar, accum, accum_stack}); auto cond = xla::Conditional(pred, tuple, update, tuple, no_update); accum = xla::GetTupleElement(cond, 0); accum_stack = xla::GetTupleElement(cond, 1); } else { auto condition_shape = xla::ShapeUtil::MakeTupleShape( {counter_shape, counter_shape, output_shape, counter_shape}); auto dim_xla = xla::ConstantR0<int32_t>(builder.get(), dim); auto idx_1 = xla::Div(counter, dim_xla); auto idx_2 = counter % dim_xla; auto data = xla::DynamicSlice(data_stack, {idx_1, idx_2}, {1, 1}); auto data_scalar = xla::Reshape(data, {0,1}, {}); auto accum = xla::DynamicSlice(accum_stack, {idx_1, data_scalar}, {1, 1}); xla::XlaComputation update; { std::unique_ptr<xla::XlaBuilder> true_builder = builder->CreateSubBuilder("update_rank2"); auto param = Parameter(true_builder.get(), 0, condition_shape, "param"); auto data_scalar = xla::GetTupleElement(param, 0); auto idx_1 = xla::GetTupleElement(param, 1); auto accum_stack = xla::GetTupleElement(param, 2); auto accum = xla::GetTupleElement(param, 3); accum = accum + xla::One(true_builder.get(), xla::S32); accum_stack = xla::DynamicUpdateSlice( accum_stack, xla::Reshape(accum, {1, 1}), {idx_1, data_scalar}); xla::Tuple(true_builder.get(), {accum, accum_stack}); auto update = true_builder->Build().ValueOrDie(); } xla::XlaComputation no_update; { std::unique_ptr<xla::XlaBuilder> false_builder = builder->CreateSubBuilder("no_update_rank2"); auto param = Parameter(false_builder.get(), 0, condition_shape, "param"); auto data_scalar = xla::GetTupleElement(param, 0); auto idx_1 = xla::GetTupleElement(param, 1); auto accum_stack = xla::GetTupleElement(param, 2); auto accum = xla::GetTupleElement(param, 3); xla::Tuple(false_builder.get(), {accum, accum_stack}); auto no_update = false_builder->Build().ValueOrDie(); } std::unique_ptr<xla::XlaBuilder> cond_builder = builder->CreateSubBuilder("cond_rank2"); auto output_size_xla = xla::ConstantR0<int32_t>(builder.get(), output_size); auto pred = xla::Lt(data_scalar, output_size_xla); auto tuple = xla::Tuple(cond_builder.get(), {data_scalar, idx_1, accum_stack, accum}); auto cond = xla::Conditional(pred, tuple, update, tuple, no_update); accum = xla::GetTupleElement(cond, 0); accum_stack = xla::GetTupleElement(cond, 1); } counter = counter + xla::One(builder.get(), xla::S32); xla::Tuple(builder.get(), {counter, data_stack, accum_stack}); body = builder->Build().ConsumeValueOrDie(); } // Create a While node with computations for the condition and the body. auto zero = xla::Zero(ctx->builder(), xla::S32); auto zero_broadcast = xla::Broadcast(zero, {output_shape.dimensions()}); auto init = xla::Tuple(ctx->builder(), {zero, input, zero_broadcast}); auto result = xla::While(condition, body, init); auto output = xla::GetTupleElement(result,2); ctx->SetOutput(0, output); } }; REGISTER_XLA_OP(Name("DenseBincount").CompileTimeConstantInput("size"), DenseBincountOp); } // namespace } // namespace tensorflow <commit_msg>Small fix<commit_after>/* Copyright 2020 The TensorFlow Authors. All Rights Reserved. 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 "tensorflow/compiler/xla/shape_util.h" #include "tensorflow/compiler/tf2xla/xla_op_kernel.h" #include "tensorflow/compiler/tf2xla/xla_op_registry.h" #include "tensorflow/compiler/tf2xla/xla_helpers.h" #include "tensorflow/compiler/xla/client/lib/comparators.h" #include "tensorflow/compiler/xla/client/lib/constants.h" #include "tensorflow/compiler/xla/client/lib/arithmetic.h" #include "tensorflow/compiler/xla/client/xla_computation.h" namespace tensorflow { namespace { // TODO: This is only a dummy kernel class DenseBincountOp : public XlaOpKernel { public: explicit DenseBincountOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) { DataType dtype; } void Compile(XlaOpKernelContext* ctx) override { // Dumb implementation for the simplest test case xla::XlaOp input = ctx->Input(0); int64_t output_size; ctx->ConstantInputAsIntScalar("size", &output_size); StatusOr<xla::Shape> input_shape_or = ctx->builder()->GetShape(input); OP_REQUIRES_OK(ctx, input_shape_or.status()); auto input_shape = input_shape_or.ValueOrDie(); auto size = input_shape.dimensions(0); auto dim = 1; auto rank = input_shape.rank(); auto counter_shape = xla::ShapeUtil::MakeShape(xla::S32, {}); const xla::Shape data_shape = xla::ShapeUtil::MakeShape(xla::S32, {input_shape.dimensions()}); xla::Shape output_shape = xla::ShapeUtil::MakeShape(xla::S32, {output_size}); if (rank == 2) { output_shape = xla::ShapeUtil::MakeShape(xla::S32, {rank, output_size}); dim = input_shape.dimensions(1); } auto loop_shape = xla::ShapeUtil::MakeTupleShape( {counter_shape, data_shape, output_shape}); // Create a computation for the condition xla::XlaComputation condition; { std::unique_ptr<xla::XlaBuilder> builder = ctx->builder()->CreateSubBuilder("condition"); auto param = xla::Parameter(builder.get(), 0, loop_shape, "param"); auto counter = xla::GetTupleElement(param, 0); xla::Gt(xla::ConstantR0<int32_t>(builder.get(), size*dim), counter); condition = builder->Build().ConsumeValueOrDie(); } // Create a computation for the body xla::XlaComputation body; { std::unique_ptr<xla::XlaBuilder> builder = ctx->builder()->CreateSubBuilder("body"); auto param = Parameter(builder.get(), 0, loop_shape, "param"); auto counter = xla::GetTupleElement(param, 0); auto data_stack = xla::GetTupleElement(param, 1); auto accum_stack = xla::GetTupleElement(param, 2); if (rank == 1) { auto data = xla::DynamicSlice(data_stack, {counter}, {1}); auto accum = xla::DynamicSlice(accum_stack, {data}, {1}); auto data_scalar = xla::Reshape(data, {0}, {}); auto condition_shape = xla::ShapeUtil::MakeTupleShape( {counter_shape, counter_shape, output_shape}); xla::XlaComputation update; { std::unique_ptr<xla::XlaBuilder> true_builder = builder->CreateSubBuilder("update"); auto param = Parameter(true_builder.get(), 0, condition_shape, "param"); auto data_scalar = xla::GetTupleElement(param, 0); auto accum = xla::GetTupleElement(param, 1); auto accum_stack = xla::GetTupleElement(param, 2); accum = accum + xla::One(true_builder.get(), xla::S32); accum_stack = xla::DynamicUpdateSlice( accum_stack, xla::Reshape(accum, {1}), {data_scalar}); xla::Tuple(true_builder.get(), {accum, accum_stack}); update = true_builder->Build().ValueOrDie(); } xla::XlaComputation no_update; { std::unique_ptr<xla::XlaBuilder> false_builder = builder->CreateSubBuilder("no_update"); auto param = Parameter(false_builder.get(), 0, condition_shape, "param"); auto data = xla::GetTupleElement(param, 0); auto accum = xla::GetTupleElement(param, 1); auto accum_stack = xla::GetTupleElement(param, 2); xla::Tuple(false_builder.get(), {accum, accum_stack}); no_update = false_builder->Build().ValueOrDie(); } std::unique_ptr<xla::XlaBuilder> cond_builder = builder->CreateSubBuilder("cond"); auto output_size_xla = xla::ConstantR0<int32_t>(cond_builder.get(), output_size); auto pred = xla::Lt(data_scalar, output_size_xla); auto tuple = xla::Tuple(cond_builder.get(), {data_scalar, accum, accum_stack}); auto cond = xla::Conditional(pred, tuple, update, tuple, no_update); accum = xla::GetTupleElement(cond, 0); accum_stack = xla::GetTupleElement(cond, 1); } else { auto condition_shape = xla::ShapeUtil::MakeTupleShape( {counter_shape, counter_shape, output_shape, counter_shape}); auto dim_xla = xla::ConstantR0<int32_t>(builder.get(), dim); auto idx_1 = xla::Div(counter, dim_xla); auto idx_2 = counter % dim_xla; auto data = xla::DynamicSlice(data_stack, {idx_1, idx_2}, {1, 1}); auto data_scalar = xla::Reshape(data, {0,1}, {}); auto accum = xla::DynamicSlice(accum_stack, {idx_1, data_scalar}, {1, 1}); xla::XlaComputation update; { std::unique_ptr<xla::XlaBuilder> true_builder = builder->CreateSubBuilder("update_rank2"); auto param = Parameter(true_builder.get(), 0, condition_shape, "param"); auto data_scalar = xla::GetTupleElement(param, 0); auto idx_1 = xla::GetTupleElement(param, 1); auto accum_stack = xla::GetTupleElement(param, 2); auto accum = xla::GetTupleElement(param, 3); accum = accum + xla::One(true_builder.get(), xla::S32); accum_stack = xla::DynamicUpdateSlice( accum_stack, xla::Reshape(accum, {1, 1}), {idx_1, data_scalar}); xla::Tuple(true_builder.get(), {accum, accum_stack}); update = true_builder->Build().ValueOrDie(); } xla::XlaComputation no_update; { std::unique_ptr<xla::XlaBuilder> false_builder = builder->CreateSubBuilder("no_update_rank2"); auto param = Parameter(false_builder.get(), 0, condition_shape, "param"); auto data_scalar = xla::GetTupleElement(param, 0); auto idx_1 = xla::GetTupleElement(param, 1); auto accum_stack = xla::GetTupleElement(param, 2); auto accum = xla::GetTupleElement(param, 3); xla::Tuple(false_builder.get(), {accum, accum_stack}); no_update = false_builder->Build().ValueOrDie(); } std::unique_ptr<xla::XlaBuilder> cond_builder = builder->CreateSubBuilder("cond_rank2"); auto output_size_xla = xla::ConstantR0<int32_t>(builder.get(), output_size); auto pred = xla::Lt(data_scalar, output_size_xla); auto tuple = xla::Tuple(cond_builder.get(), {data_scalar, idx_1, accum_stack, accum}); auto cond = xla::Conditional(pred, tuple, update, tuple, no_update); accum = xla::GetTupleElement(cond, 0); accum_stack = xla::GetTupleElement(cond, 1); } counter = counter + xla::One(builder.get(), xla::S32); xla::Tuple(builder.get(), {counter, data_stack, accum_stack}); body = builder->Build().ConsumeValueOrDie(); } // Create a While node with computations for the condition and the body. auto zero = xla::Zero(ctx->builder(), xla::S32); auto zero_broadcast = xla::Broadcast(zero, {output_shape.dimensions()}); auto init = xla::Tuple(ctx->builder(), {zero, input, zero_broadcast}); auto result = xla::While(condition, body, init); auto output = xla::GetTupleElement(result,2); ctx->SetOutput(0, output); } }; REGISTER_XLA_OP(Name("DenseBincount").CompileTimeConstantInput("size"), DenseBincountOp); } // namespace } // namespace tensorflow <|endoftext|>
<commit_before>/* * This file is part of WinSparkle (https://winsparkle.org) * * Copyright (C) 2009-2017 Vaclav Slavik * * 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 "download.h" #include "error.h" #include "settings.h" #include "utils.h" #include "winsparkle-version.h" #include <string> #include <windows.h> #include <wininet.h> namespace winsparkle { /*--------------------------------------------------------------------------* helpers *--------------------------------------------------------------------------*/ namespace { struct InetHandle { InetHandle(HINTERNET handle = 0) : m_handle(handle), m_callback(NULL) {} ~InetHandle() { Close(); } InetHandle& operator=(HINTERNET handle) { Close(); m_handle = handle; return *this; } void SetStatusCallback(INTERNET_STATUS_CALLBACK callback) { m_callback = callback; InternetSetStatusCallback(m_handle, m_callback); } void Close() { if (m_handle) { if (m_callback) InternetSetStatusCallback(m_handle, NULL); InternetCloseHandle(m_handle); m_handle = NULL; } } operator HINTERNET() const { return m_handle; } HINTERNET m_handle; INTERNET_STATUS_CALLBACK m_callback; }; std::wstring MakeUserAgent() { std::wstring userAgent = Settings::GetAppName() + L"/" + Settings::GetAppVersion() + L" WinSparkle/" + AnsiToWide(WIN_SPARKLE_VERSION_STRING); #ifdef _WIN64 userAgent += L" (Win64)"; #else // If we're running a 32bit process, check if we're on 64bit Windows OS: auto f_IsWow64Process = LOAD_DYNAMIC_FUNC(IsWow64Process, kernel32); if( f_IsWow64Process ) { BOOL wow64 = FALSE; f_IsWow64Process(GetCurrentProcess(), &wow64); if ( wow64 ) userAgent += L" (WOW64)"; } #endif return userAgent; } bool GetHttpHeader(HINTERNET handle, DWORD whatToGet, DWORD& output) { DWORD outputSize = sizeof(output); DWORD headerIndex = 0; return HttpQueryInfoA ( handle, whatToGet | HTTP_QUERY_FLAG_NUMBER, &output, &outputSize, &headerIndex ) == TRUE; } std::wstring GetURLFileName(const char *url) { const char *lastSlash = strrchr(url, '/'); std::string fn(lastSlash ? lastSlash + 1 : url); if (fn.find_first_of('?') != std::string::npos) fn = fn.substr(0, fn.find_first_of('?')); return AnsiToWide(fn); } struct DownloadCallbackContext { DownloadCallbackContext(InetHandle *conn_) : conn(conn_), wasClosed(false) {} InetHandle *conn; bool wasClosed; Event eventRequestComplete; }; void CALLBACK DownloadInternetStatusCallback(_In_ HINTERNET hInternet, _In_ DWORD_PTR dwContext, _In_ DWORD dwInternetStatus, _In_ LPVOID lpvStatusInformation, _In_ DWORD dwStatusInformationLength) { DownloadCallbackContext *context = (DownloadCallbackContext*)dwContext; INTERNET_ASYNC_RESULT *res = (INTERNET_ASYNC_RESULT*)lpvStatusInformation; switch (dwInternetStatus) { case INTERNET_STATUS_HANDLE_CREATED: context->conn->m_handle = (HINTERNET)(res->dwResult); break; case INTERNET_STATUS_REQUEST_COMPLETE: context->eventRequestComplete.Signal(); break; case INTERNET_STATUS_CONNECTION_CLOSED: // Mark the connection as closed, but don't close the handle yet. // This is because this may happen in at least two different // situations: // 1. Connection prematurely closed, we need to report an error. // 2. Redirect to another site (WinInet closes connection, starts // another one), in which case we DON'T want to error out. context->wasClosed = true; break; case INTERNET_STATUS_REDIRECT: // Activity like this following INTERNET_STATUS_CONNECTION_CLOSED // implies that the handle is still doing useful work, so unflag // it. Otherwise we'd get an error at the very end of download. // // See https://github.com/vslavik/winsparkle/pull/139 for what this // mess is about. context->wasClosed = false; break; } } void WaitUntilSignaledWithTerminationCheck(Event& event, Thread *thread) { for (;;) { if (thread) thread->CheckShouldTerminate(); if (event.WaitUntilSignaled(100)) return; } } } // anonymous namespace /*--------------------------------------------------------------------------* public functions *--------------------------------------------------------------------------*/ void DownloadFile(const std::string& url, IDownloadSink *sink, Thread *onThread, int flags) { char url_path[2048]; URL_COMPONENTSA urlc; memset(&urlc, 0, sizeof(urlc)); urlc.dwStructSize = sizeof(urlc); urlc.lpszUrlPath = url_path; urlc.dwUrlPathLength = sizeof(url_path); if ( !InternetCrackUrlA(url.c_str(), 0, ICU_DECODE, &urlc) ) throw Win32Exception(); InetHandle inet = InternetOpen ( MakeUserAgent().c_str(), INTERNET_OPEN_TYPE_PRECONFIG, NULL, // lpszProxyName NULL, // lpszProxyBypass INTERNET_FLAG_ASYNC // dwFlags ); if ( !inet ) throw Win32Exception(); // Never allow local caching, always contact the server for both // appcast feeds and downloads. This is useful in case of // misconfigured servers. DWORD dwFlags = INTERNET_FLAG_NO_CACHE_WRITE | INTERNET_FLAG_RELOAD; // For some requests (appcast feeds), don't even allow proxies to cache, // as we need the most up-to-date information. if ( flags & Download_BypassProxies ) dwFlags |= INTERNET_FLAG_PRAGMA_NOCACHE; if ( urlc.nScheme == INTERNET_SCHEME_HTTPS ) dwFlags |= INTERNET_FLAG_SECURE; InetHandle conn; DownloadCallbackContext context(&conn); inet.SetStatusCallback(&DownloadInternetStatusCallback); HINTERNET conn_raw = InternetOpenUrlA ( inet, url.c_str(), NULL, // lpszHeaders -1, // dwHeadersLength dwFlags, (DWORD_PTR)&context // dwContext ); // InternetOpenUrl() may return NULL handle and then fill it in asynchronously from // DownloadInternetStatusCallback. We must make sure we don't overwrite the handle // in that case, or throw an error. if (conn_raw) { conn = conn_raw; } else { if (GetLastError() != ERROR_IO_PENDING) throw Win32Exception(); } WaitUntilSignaledWithTerminationCheck(context.eventRequestComplete, onThread); // Check returned status code - we need to detect 404 instead of // downloading the human-readable 404 page: DWORD statusCode; if ( GetHttpHeader(conn, HTTP_QUERY_STATUS_CODE, statusCode) && statusCode >= 400 ) { throw std::runtime_error("Update file not found on the server."); } // Get content length if possible: DWORD contentLength; if ( GetHttpHeader(conn, HTTP_QUERY_CONTENT_LENGTH, contentLength) ) sink->SetLength(contentLength); // Get filename fron Content-Disposition, if available char contentDisposition[512]; DWORD cdSize = 512; bool filename_set = false; if ( HttpQueryInfoA(conn, HTTP_QUERY_CONTENT_DISPOSITION, contentDisposition, &cdSize, NULL) ) { char *ptr = strstr(contentDisposition, "filename="); if ( ptr ) { char c_filename[512]; ptr += 9; while ( *ptr == ' ' ) ptr++; bool quoted = false; if ( *ptr == '"' || *ptr == '\'') { quoted = true; ptr++; } char *ptr2 = c_filename; while ( *ptr != ';' && *ptr != 0) *ptr2++ = *ptr++; if ( quoted ) *(ptr2 - 1) = 0; else *ptr2 = 0; sink->SetFilename(AnsiToWide(c_filename)); filename_set = true; } } if ( !filename_set ) { DWORD ousize = 0; InternetQueryOptionA(conn, INTERNET_OPTION_URL, NULL, &ousize); if (GetLastError() == ERROR_INSUFFICIENT_BUFFER) { DataBuffer<char> optionurl(ousize); if ( InternetQueryOptionA(conn, INTERNET_OPTION_URL, optionurl, &ousize) ) sink->SetFilename(GetURLFileName(optionurl)); else sink->SetFilename(GetURLFileName(urlc.lpszUrlPath)); } else { sink->SetFilename(GetURLFileName(urlc.lpszUrlPath)); } } // Download the data: char buffer[10240]; for ( ;; ) { INTERNET_BUFFERS ibuf = { 0 }; ibuf.dwStructSize = sizeof(ibuf); ibuf.lpvBuffer = buffer; ibuf.dwBufferLength = sizeof(buffer); if (!InternetReadFileEx(conn, &ibuf, IRF_ASYNC | IRF_NO_WAIT, NULL)) { if (GetLastError() != ERROR_IO_PENDING) throw Win32Exception(); WaitUntilSignaledWithTerminationCheck(context.eventRequestComplete, onThread); continue; } if (ibuf.dwBufferLength == 0) { // This check is required in case the INTERNET_STATUS_CONNECTION_CLOSED event was // received (and the handle was closed) during the call to InternetReadFileEx() if (context.wasClosed) throw Win32Exception(); else break; // all of the file was downloaded } sink->Add(ibuf.lpvBuffer, ibuf.dwBufferLength); } } } // namespace winsparkle <commit_msg>Check for download errors properly<commit_after>/* * This file is part of WinSparkle (https://winsparkle.org) * * Copyright (C) 2009-2017 Vaclav Slavik * * 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 "download.h" #include "error.h" #include "settings.h" #include "utils.h" #include "winsparkle-version.h" #include <string> #include <windows.h> #include <wininet.h> namespace winsparkle { /*--------------------------------------------------------------------------* helpers *--------------------------------------------------------------------------*/ namespace { struct InetHandle { InetHandle(HINTERNET handle = 0) : m_handle(handle), m_callback(NULL) {} ~InetHandle() { Close(); } InetHandle& operator=(HINTERNET handle) { Close(); m_handle = handle; return *this; } void SetStatusCallback(INTERNET_STATUS_CALLBACK callback) { m_callback = callback; InternetSetStatusCallback(m_handle, m_callback); } void Close() { if (m_handle) { if (m_callback) InternetSetStatusCallback(m_handle, NULL); InternetCloseHandle(m_handle); m_handle = NULL; } } operator HINTERNET() const { return m_handle; } HINTERNET m_handle; INTERNET_STATUS_CALLBACK m_callback; }; std::wstring MakeUserAgent() { std::wstring userAgent = Settings::GetAppName() + L"/" + Settings::GetAppVersion() + L" WinSparkle/" + AnsiToWide(WIN_SPARKLE_VERSION_STRING); #ifdef _WIN64 userAgent += L" (Win64)"; #else // If we're running a 32bit process, check if we're on 64bit Windows OS: auto f_IsWow64Process = LOAD_DYNAMIC_FUNC(IsWow64Process, kernel32); if( f_IsWow64Process ) { BOOL wow64 = FALSE; f_IsWow64Process(GetCurrentProcess(), &wow64); if ( wow64 ) userAgent += L" (WOW64)"; } #endif return userAgent; } bool GetHttpHeader(HINTERNET handle, DWORD whatToGet, DWORD& output) { DWORD outputSize = sizeof(output); DWORD headerIndex = 0; return HttpQueryInfoA ( handle, whatToGet | HTTP_QUERY_FLAG_NUMBER, &output, &outputSize, &headerIndex ) == TRUE; } std::wstring GetURLFileName(const char *url) { const char *lastSlash = strrchr(url, '/'); std::string fn(lastSlash ? lastSlash + 1 : url); if (fn.find_first_of('?') != std::string::npos) fn = fn.substr(0, fn.find_first_of('?')); return AnsiToWide(fn); } struct DownloadCallbackContext { DownloadCallbackContext(InetHandle *conn_) : conn(conn_), lastError(ERROR_SUCCESS) {} InetHandle *conn; DWORD lastError; Event eventRequestComplete; }; void CALLBACK DownloadInternetStatusCallback(_In_ HINTERNET hInternet, _In_ DWORD_PTR dwContext, _In_ DWORD dwInternetStatus, _In_ LPVOID lpvStatusInformation, _In_ DWORD dwStatusInformationLength) { DownloadCallbackContext *context = (DownloadCallbackContext*)dwContext; INTERNET_ASYNC_RESULT *res = (INTERNET_ASYNC_RESULT*)lpvStatusInformation; switch (dwInternetStatus) { case INTERNET_STATUS_HANDLE_CREATED: context->conn->m_handle = (HINTERNET)(res->dwResult); break; case INTERNET_STATUS_REQUEST_COMPLETE: context->lastError = res->dwError; context->eventRequestComplete.Signal(); break; } } void WaitUntilSignaledWithTerminationCheck(Event& event, Thread *thread) { for (;;) { if (thread) thread->CheckShouldTerminate(); if (event.WaitUntilSignaled(100)) return; } } } // anonymous namespace /*--------------------------------------------------------------------------* public functions *--------------------------------------------------------------------------*/ void DownloadFile(const std::string& url, IDownloadSink *sink, Thread *onThread, int flags) { char url_path[2048]; URL_COMPONENTSA urlc; memset(&urlc, 0, sizeof(urlc)); urlc.dwStructSize = sizeof(urlc); urlc.lpszUrlPath = url_path; urlc.dwUrlPathLength = sizeof(url_path); if ( !InternetCrackUrlA(url.c_str(), 0, ICU_DECODE, &urlc) ) throw Win32Exception(); InetHandle inet = InternetOpen ( MakeUserAgent().c_str(), INTERNET_OPEN_TYPE_PRECONFIG, NULL, // lpszProxyName NULL, // lpszProxyBypass INTERNET_FLAG_ASYNC // dwFlags ); if ( !inet ) throw Win32Exception(); // Never allow local caching, always contact the server for both // appcast feeds and downloads. This is useful in case of // misconfigured servers. DWORD dwFlags = INTERNET_FLAG_NO_CACHE_WRITE | INTERNET_FLAG_RELOAD; // For some requests (appcast feeds), don't even allow proxies to cache, // as we need the most up-to-date information. if ( flags & Download_BypassProxies ) dwFlags |= INTERNET_FLAG_PRAGMA_NOCACHE; if ( urlc.nScheme == INTERNET_SCHEME_HTTPS ) dwFlags |= INTERNET_FLAG_SECURE; InetHandle conn; DownloadCallbackContext context(&conn); inet.SetStatusCallback(&DownloadInternetStatusCallback); HINTERNET conn_raw = InternetOpenUrlA ( inet, url.c_str(), NULL, // lpszHeaders -1, // dwHeadersLength dwFlags, (DWORD_PTR)&context // dwContext ); // InternetOpenUrl() may return NULL handle and then fill it in asynchronously from // DownloadInternetStatusCallback. We must make sure we don't overwrite the handle // in that case, or throw an error. if (conn_raw) { conn = conn_raw; } else { if (GetLastError() != ERROR_IO_PENDING) throw Win32Exception(); } WaitUntilSignaledWithTerminationCheck(context.eventRequestComplete, onThread); // Check returned status code - we need to detect 404 instead of // downloading the human-readable 404 page: DWORD statusCode; if ( GetHttpHeader(conn, HTTP_QUERY_STATUS_CODE, statusCode) && statusCode >= 400 ) { throw std::runtime_error("Update file not found on the server."); } // Get content length if possible: DWORD contentLength; if ( GetHttpHeader(conn, HTTP_QUERY_CONTENT_LENGTH, contentLength) ) sink->SetLength(contentLength); // Get filename fron Content-Disposition, if available char contentDisposition[512]; DWORD cdSize = 512; bool filename_set = false; if ( HttpQueryInfoA(conn, HTTP_QUERY_CONTENT_DISPOSITION, contentDisposition, &cdSize, NULL) ) { char *ptr = strstr(contentDisposition, "filename="); if ( ptr ) { char c_filename[512]; ptr += 9; while ( *ptr == ' ' ) ptr++; bool quoted = false; if ( *ptr == '"' || *ptr == '\'') { quoted = true; ptr++; } char *ptr2 = c_filename; while ( *ptr != ';' && *ptr != 0) *ptr2++ = *ptr++; if ( quoted ) *(ptr2 - 1) = 0; else *ptr2 = 0; sink->SetFilename(AnsiToWide(c_filename)); filename_set = true; } } if ( !filename_set ) { DWORD ousize = 0; InternetQueryOptionA(conn, INTERNET_OPTION_URL, NULL, &ousize); if (GetLastError() == ERROR_INSUFFICIENT_BUFFER) { DataBuffer<char> optionurl(ousize); if ( InternetQueryOptionA(conn, INTERNET_OPTION_URL, optionurl, &ousize) ) sink->SetFilename(GetURLFileName(optionurl)); else sink->SetFilename(GetURLFileName(urlc.lpszUrlPath)); } else { sink->SetFilename(GetURLFileName(urlc.lpszUrlPath)); } } // Download the data: char buffer[10240]; for ( ;; ) { INTERNET_BUFFERS ibuf = { 0 }; ibuf.dwStructSize = sizeof(ibuf); ibuf.lpvBuffer = buffer; ibuf.dwBufferLength = sizeof(buffer); if (!InternetReadFileEx(conn, &ibuf, IRF_ASYNC | IRF_NO_WAIT, NULL)) { if (GetLastError() != ERROR_IO_PENDING) throw Win32Exception(); WaitUntilSignaledWithTerminationCheck(context.eventRequestComplete, onThread); continue; } if (ibuf.dwBufferLength == 0) { if (context.lastError != ERROR_SUCCESS) throw Win32Exception(); else break; // all of the file was downloaded } sink->Add(ibuf.lpvBuffer, ibuf.dwBufferLength); } } } // namespace winsparkle <|endoftext|>
<commit_before>#ifndef INTRUMENTATION_HPP #define INTRUMENTATION_HPP #define ESC(...) __VA_ARGS__ #ifdef USE_VALUE_SUMMARY #include "PathConstraint.hpp" #include "ValueSummary.hpp" #define BEGIN_BLOCK() \ do { #define END_BLOCK() \ } while(false); #define FUNCTION_DECL(ReturnType, functionName, args) \ ReturnType functionName args { \ typename ReturnType::Builder __ret; \ Bdd __oldPc = PathConstraint::pc(); \ BEGIN_BLOCK() #define END_FUNCTION() \ END_BLOCK() \ PathConstraint::pc() = __oldPc; \ return __ret.build(); \ } #define VOID_FUNCTION_DECL(functionName, args) \ void functionName args { \ Bdd __oldPc = PathConstraint::pc(); \ BEGIN_BLOCK() #define END_VOID_FUNCTION() \ END_BLOCK() \ PathConstraint::pc() = __oldPc; \ } #define IF(_condition...) \ { \ const Bool& condition = (_condition); \ Bdd&& falseBranch = PathConstraint::pc() & condition.F; \ Bdd mergePointPc = falseBranch; #define THEN() \ PathConstraint::pc() &= condition.T; \ if(PathConstraint::isNotZero()) { \ BEGIN_BLOCK(); #define ELSE() \ END_BLOCK(); \ } \ mergePointPc = PathConstraint::pc(); \ PathConstraint::pc() = falseBranch; \ if(PathConstraint::isNotZero()) { \ BEGIN_BLOCK(); #define ENDIF() \ END_BLOCK(); \ } \ PathConstraint::pc() |= mergePointPc; \ if(PathConstraint::isZero()) { \ break; \ } \ } #define IF_ONLY(condition...) \ if(__if_only(condition)) #define WHILE(_condition...) \ { \ Bdd loopMergePointPc; \ while(true) { \ const Bool& condition = (_condition); \ loopMergePointPc |= condition.F; \ if(condition.T.isZero()) { \ break; \ } else { \ PathConstraint::pc() = condition.T; \ BEGIN_BLOCK(); #define ENDWHILE() \ END_BLOCK(); \ if(PathConstraint::isZero()) { \ break; \ } \ } \ } \ PathConstraint::pc() |= loopMergePointPc; \ if(PathConstraint::isZero()) { \ break; \ } \ } #define ENDWHILE_NC() \ END_BLOCK(); \ if(PathConstraint::isZero()) { \ break; \ } \ } \ } \ PathConstraint::pc() |= loopMergePointPc; \ } #define FOR(initializer, condition, increment, block...) \ { \ initializer; \ WHILE(condition) { \ block; \ increment; \ } #define ENDFOR() \ ENDWHILE() \ } #define ENDFOR_NC() \ ENDWHILE_NC() \ } #define BREAK() \ { \ loopMergePointPc |= PathConstraint::pc(); \ PathConstraint::pc() = Bdd::bddZero(); \ break; \ } #define RETURN_VOID() \ { \ PathConstraint::pc() = Bdd::bddZero(); \ break; \ } #define RETURN(val...) \ { \ __ret.addValue(PathConstraint::pc(), val); \ PathConstraint::pc() = Bdd::bddZero(); \ break; \ } static inline bool __if_only(const RUNTIME_NAMESPACE::ValueSummary<bool>& condition) { Bdd&& pred = RUNTIME_NAMESPACE::PathConstraint::pc() & condition.T; if(!pred.isZero()) { RUNTIME_NAMESPACE::PathConstraint::pc() = pred; return true; } else { return false; } } #else #define BEGIN_BLOCK() { #define END_BLOCK() } #define FUNCTION_DECL(ReturnType, functionName, args) \ ReturnType functionName args { \ #define END_FUNCTION() \ } #define VOID_FUNCTION_DECL(functionName, args) \ void functionName args { #define END_VOID_FUNCTION() \ } #define IF(condition...) \ if(condition) #define THEN() \ { #define ELSE() \ } else { #define ENDIF() \ } #define IF_ONLY(condition...) \ if(condition) #define WHILE(condition...) \ while(condition) { #define ENDWHILE() \ } #define ENDWHILE_NC() \ } #define FOR(initializer, condition, increment, block...) \ for(initializer; condition; increment) { \ block #define ENDFOR() \ } #define ENDFOR_NC() \ } #define BREAK() break; #define RETURN_VOID() return; #define RETURN(val...) return val; #endif #endif<commit_msg>add documentation<commit_after>#ifndef INTRUMENTATION_HPP #define INTRUMENTATION_HPP #define ESC(...) __VA_ARGS__ #ifdef USE_VALUE_SUMMARY #include "PathConstraint.hpp" #include "ValueSummary.hpp" #define BEGIN_BLOCK() \ do { #define END_BLOCK() \ } while(false); #define FUNCTION_DECL(ReturnType, functionName, args) \ ReturnType functionName args { \ typename ReturnType::Builder __ret; \ Bdd __oldPc = PathConstraint::pc(); \ BEGIN_BLOCK() #define END_FUNCTION() \ END_BLOCK() \ PathConstraint::pc() = __oldPc; \ return __ret.build(); \ } #define VOID_FUNCTION_DECL(functionName, args) \ void functionName args { \ Bdd __oldPc = PathConstraint::pc(); \ BEGIN_BLOCK() #define END_VOID_FUNCTION() \ END_BLOCK() \ PathConstraint::pc() = __oldPc; \ } #define IF(_condition...) \ { \ const Bool& condition = (_condition); \ Bdd&& falseBranch = PathConstraint::pc() & condition.F; \ Bdd mergePointPc = falseBranch; #define THEN() \ PathConstraint::pc() &= condition.T; \ if(PathConstraint::isNotZero()) { \ BEGIN_BLOCK(); #define ELSE() \ END_BLOCK(); \ } \ mergePointPc = PathConstraint::pc(); \ PathConstraint::pc() = falseBranch; \ if(PathConstraint::isNotZero()) { \ BEGIN_BLOCK(); #define ENDIF() \ END_BLOCK(); \ } \ PathConstraint::pc() |= mergePointPc; \ if(PathConstraint::isZero()) { \ break; \ } \ } #define IF_ONLY(condition...) \ if(__if_only(condition)) #define WHILE(_condition...) \ { \ Bdd loopMergePointPc; \ while(true) { \ const Bool& condition = (_condition); \ loopMergePointPc |= condition.F; \ if(condition.T.isZero()) { \ break; \ } else { \ PathConstraint::pc() = condition.T; \ BEGIN_BLOCK(); #define ENDWHILE() \ END_BLOCK(); \ if(PathConstraint::isZero()) { \ break; \ } \ } \ } \ PathConstraint::pc() |= loopMergePointPc; \ if(PathConstraint::isZero()) { \ break; \ } \ } #define ENDWHILE_NC() \ END_BLOCK(); \ if(PathConstraint::isZero()) { \ break; \ } \ } \ } \ PathConstraint::pc() |= loopMergePointPc; \ } #define FOR(initializer, condition, increment, block...) \ { \ initializer; \ WHILE(condition) { \ block; \ increment; \ } #define ENDFOR() \ ENDWHILE() \ } #define ENDFOR_NC() \ ENDWHILE_NC() \ } #define BREAK() \ { \ loopMergePointPc |= PathConstraint::pc(); \ PathConstraint::pc() = Bdd::bddZero(); \ break; \ } #define RETURN_VOID() \ { \ PathConstraint::pc() = Bdd::bddZero(); \ break; \ } #define RETURN(val...) \ { \ __ret.addValue(PathConstraint::pc(), val); \ PathConstraint::pc() = Bdd::bddZero(); \ break; \ } /* * IF_ONLY: * evaluate condition, * if condition exist a true path, execute the true path assuming the branch does no need to merge * (i.e. true branch throws exception, control flow interrupt) * otherwise condition must be all false, don't change current PathConstraint::pc() * and continue execution to the false branch */ static inline bool __if_only(const RUNTIME_NAMESPACE::ValueSummary<bool>& condition) { Bdd&& pred = RUNTIME_NAMESPACE::PathConstraint::pc() & condition.T; if(!pred.isZero()) { RUNTIME_NAMESPACE::PathConstraint::pc() = pred; return true; } else { return false; } } #else #define BEGIN_BLOCK() { #define END_BLOCK() } #define FUNCTION_DECL(ReturnType, functionName, args) \ ReturnType functionName args { \ #define END_FUNCTION() \ } #define VOID_FUNCTION_DECL(functionName, args) \ void functionName args { #define END_VOID_FUNCTION() \ } #define IF(condition...) \ if(condition) #define THEN() \ { #define ELSE() \ } else { #define ENDIF() \ } #define IF_ONLY(condition...) \ if(condition) #define WHILE(condition...) \ while(condition) { #define ENDWHILE() \ } #define ENDWHILE_NC() \ } #define FOR(initializer, condition, increment, block...) \ for(initializer; condition; increment) { \ block #define ENDFOR() \ } #define ENDFOR_NC() \ } #define BREAK() break; #define RETURN_VOID() return; #define RETURN(val...) return val; #endif #endif<|endoftext|>
<commit_before>#include <sstream> #include <string> #include <vector> #include <map> #include <algorithm> #include <iostream> #include <utility> #include <set> #include <cctype> #include <queue> #include <stack> #include <cstdio> #include <cstdlib> #include <cmath> #include <fstream> #include <functional> #include <locale> #include <ctime> #include <iomanip> #include <assert.h> using namespace std; // // Lightweight graph lib // // graph struct Node { Node *next; size_t vertex; Node(size_t to) : vertex(to), next(NULL) {} }; struct Info { char base; // ATCG size_t start; // start pos on reference DNA size_t end; // end pos on reference DNA Info(char base, size_t start, size_t end) : base(base), start(start), end(end) {} }; // vertex0 = root class Graph { private: vector<Node *> outwards; vector<Info> info; public: size_t root; Graph() { root = addVertex('*', 0, 0); } size_t addVertex(char base, size_t start, size_t end) { size_t idx = outwards.size(); outwards.push_back(NULL); info.push_back(Info(base, start, end)); return idx; } size_t countVertex() { return outwards.size(); } void addOutwardsVertex(size_t from, size_t to) { Node *next = new Node(to); Node *node = outwards[from]; if (node == NULL) { outwards[from] = next; } else { while (node->next != NULL) { node = node->next; } node->next = next; } } void addEdge(size_t from, size_t to) { assert(0 <= from && from < countVertex()); assert(0 <= to && to < countVertex()); addOutwardsVertex(from, to); } bool existOutwardEdge(size_t v, char base) { assert(0 <= v && v < countVertex()); Node *node = outwards[v]; while (node) { if (info[node->vertex].base == base) { return true; } node = node->next; } return false; } size_t findOutwardVertex(size_t v, char base, bool& found) { assert(0 <= v && v < countVertex()); Node *node = outwards[v]; while (node) { if (info[node->vertex].base == base) { found = true; return node->vertex; } node = node->next; } found = false; return 0; } }; // // end // // trim from start (in place) static inline void ltrim(string &s) { s.erase(s.begin(), std::find_if(s.begin(), s.end(), std::not1(std::ptr_fun<int, int>(std::isspace)))); } // trim from end (in place) static inline void rtrim(string &s) { s.erase(std::find_if(s.rbegin(), s.rend(), std::not1(std::ptr_fun<int, int>(std::isspace))).base(), s.end()); } // trim from both ends (in place) static inline void trim(std::string &s) { ltrim(s); rtrim(s); } struct Result { string readName; int chromatidSequenceId; size_t startPos; size_t endPos; bool strand; float score; Result(string readName, int chromatidSequenceId, bool strand) : readName(readName), strand(strand), chromatidSequenceId(chromatidSequenceId), startPos(0), endPos(0), score(-1) { } }; // utils string createReverseRead(string read) { string s; size_t len = read.size(); s.resize(len); reverse_copy(read.begin(), read.end(), s.begin()); for (size_t i = 0; i < len; ++i) { switch (s[i]) { case 'T': s[i] = 'A'; break; case 'A': s[i] = 'T'; break; case 'C': s[i] = 'G'; break; case 'G': s[i] = 'C'; break; } } return s; } string toResultStr(Result& r) { stringstream ss; ss << r.readName << "," << r.chromatidSequenceId << "," << (r.startPos + 1) << "," << (r.endPos + 1) << "," << (r.strand ? '+' : '-') << "," << fixed << setprecision(2) << r.score; return ss.str(); } class DNASequencing { vector<string> results; int currentChromatidSequenceId; string currentChromatid; Graph g; public: int passReferenceGenome(int chromatidSequenceId, vector<string> chromatidSequence) { currentChromatid = ""; for (int i = 0; i < chromatidSequence.size(); ++i) { trim(chromatidSequence[i]); currentChromatid += chromatidSequence[i]; } currentChromatidSequenceId = chromatidSequenceId; cerr << "passReferenceGenome: id=" << chromatidSequenceId << endl; return 0; } int initTest(int) { return 0; } int preProcessing() { cerr << "building graph for Chromatid" << currentChromatidSequenceId << endl; size_t cnt = 0; size_t lenDNA = currentChromatid.size(); for (size_t start = 0; start < lenDNA - 150; ++start) { if (currentChromatid[start] == 'N') { continue; } size_t curr = g.root; for (size_t i = 0; i < 150; ++i) { size_t pos = start + i; char base = currentChromatid[pos]; bool found; size_t v = g.findOutwardVertex(curr, base, found); if (found) { curr = v; } else { size_t v = g.addVertex(base, start, pos); g.addEdge(curr, v); curr = v; } } if (++cnt % 100000 == 0) cerr << "(" << (start * 100 / lenDNA) << "%) " << g.countVertex() << endl; } return 0; } vector<string> getAlignment(int n, double normA, double normS, vector<string> readNames, vector<string> reads) { for (int i = 0; i < n; ++i) { cerr << "read" << i << endl; string normalRead = reads[i]; string reverseRead = createReverseRead(normalRead); Result normalResult(readNames[i], currentChromatidSequenceId, true); Result reverseResult(readNames[i], currentChromatidSequenceId, false); align(normalResult, normalRead); if (normalResult.score >= 0.99) { results.push_back(toResultStr(normalResult)); } else { align(reverseResult, reverseRead); if (normalResult.score > reverseResult.score) { results.push_back(toResultStr(normalResult)); } else { results.push_back(toResultStr(reverseResult)); } } } return results; } private: float calcMatchRate(string& chroma, size_t pos, size_t len, string& read) { size_t cnt = 0; size_t lim = 15; for (size_t i = 0; i < len; ++i) { if (chroma[pos + i] == read[i]) ++cnt; else { if (--lim <= 0) { cnt = 0; break; } } } return (float)cnt / len; } // readは正順のみ void align(Result& result, string& r) { string& c = currentChromatid; size_t len = r.size(); size_t bestPos = -1; float bestRate = 0.0; for (size_t pos = 0; pos < c.size() - len;) { if (c[pos] == r[0] && c[pos + 1] == r[1] && c[pos + 2] == r[2]) { float rate = calcMatchRate(c, pos, len, r); if (rate > bestRate) { bestRate = rate; bestPos = pos; cerr << "best pos=" << pos << " score=" << rate << endl; } if (rate == 1.0) { break; } } pos += 1; } result.startPos = bestPos; result.endPos = bestPos + len; result.score = bestRate; } }; /********************************************************************************************** test bench ***********************************************************************************************/ bool loadChromatidSequence(vector<string>& v) { const char *filename = "chromatid20.fa"; std::ifstream ifs(filename); std::string str; if (ifs.fail()) { std::cerr << "失敗" << std::endl; return false; } int lines = 0; getline(ifs, str); // skip header while (getline(ifs, str)) { if (++lines % 10000 == 0) std::cerr << "."; v.push_back(str); } std::cerr << " loaded" << std::endl; return true; } bool loadReads(vector<string>& readNames, vector<string>& reads) { const char *basename = "small5"; string name1(basename); string name2(basename); name1.append(".fa1"); name2.append(".fa2"); std::ifstream ifs1(name1); std::ifstream ifs2(name2); if (ifs1.fail() || ifs2.fail()) { std::cerr << "失敗" << std::endl; return false; } int lines = 0; std::string str1; std::string str2; while (getline(ifs1, str1) && getline(ifs2, str2)) { if (++lines % 10000 == 0) std::cerr << "."; readNames.push_back(str1.substr(1)); readNames.push_back(str2.substr(1)); getline(ifs1, str1) && getline(ifs2, str2); reads.push_back(str1); reads.push_back(str2); if (reads.size() >= 10) break; } std::cerr << " loaded " << reads.size() << "reads" << std::endl; return true; } int main() { vector<string> chromatidSequence; if (!loadChromatidSequence(chromatidSequence)) return 0; vector<string> readNames; vector<string> reads; if (!loadReads(readNames, reads)) return 0; DNASequencing dnaSequencing; dnaSequencing.passReferenceGenome(20, chromatidSequence); dnaSequencing.initTest(0); dnaSequencing.preProcessing(); clock_t begin = clock(); vector<string> results = dnaSequencing.getAlignment(reads.size(), 1.0, 1.0, readNames, reads); clock_t end = clock(); cerr << "*** results *** " << (end - begin) / 1000 << "(K clocks)" << endl; cout << "*** results *** " << (end - begin) / 1000 << "(K clocks)" << endl; for (vector<string>::iterator it = results.begin(); it != results.end(); ++it) { cout << *it << endl; } return 1; } <commit_msg>read長のグラフを作るのは無理筋だった。<commit_after>#include <sstream> #include <string> #include <vector> #include <map> #include <algorithm> #include <iostream> #include <utility> #include <set> #include <cctype> #include <queue> #include <stack> #include <cstdio> #include <cstdlib> #include <cmath> #include <fstream> #include <functional> #include <locale> #include <ctime> #include <iomanip> #include <assert.h> using namespace std; // // Lightweight graph lib // // graph struct Node { size_t nextT; size_t nextA; size_t nextG; size_t nextC; char base; Node(char base) : nextT(0), nextC(0), nextG(0), nextA(0), base(base) {} }; // vertex0 = root class Graph { private: vector<Node> outwards; public: size_t root; Graph() { root = addVertex('N'); } size_t addVertex(char aBase) { size_t idx = outwards.size(); outwards.push_back(Node(aBase)); return idx; } size_t countVertex() { return outwards.size(); } void addEdge(size_t from, size_t to) { assert(0 <= from && from < countVertex()); assert(0 <= to && to < countVertex()); Node& node = outwards[from]; char toBase = outwards[to].base; switch (toBase) { case 'T': node.nextT = to; break; case 'A': node.nextA = to; break; case 'G': node.nextG = to; break; case 'C': node.nextC = to; break; } } size_t findOutwardVertex(size_t v, char aBase) { assert(0 <= v && v < countVertex()); Node& node = outwards[v]; switch (aBase) { case 'T': return node.nextT; case 'A': return node.nextA; case 'G': return node.nextG; case 'C': return node.nextC; } return 0; } }; // // end // // trim from start (in place) static inline void ltrim(string &s) { s.erase(s.begin(), std::find_if(s.begin(), s.end(), std::not1(std::ptr_fun<int, int>(std::isspace)))); } // trim from end (in place) static inline void rtrim(string &s) { s.erase(std::find_if(s.rbegin(), s.rend(), std::not1(std::ptr_fun<int, int>(std::isspace))).base(), s.end()); } // trim from both ends (in place) static inline void trim(std::string &s) { ltrim(s); rtrim(s); } struct Result { string readName; int chromatidSequenceId; size_t startPos; size_t endPos; bool strand; float score; Result(string readName, int chromatidSequenceId, bool strand) : readName(readName), strand(strand), chromatidSequenceId(chromatidSequenceId), startPos(0), endPos(0), score(-1) { } }; // utils string createReverseRead(string read) { string s; size_t len = read.size(); s.resize(len); reverse_copy(read.begin(), read.end(), s.begin()); for (size_t i = 0; i < len; ++i) { switch (s[i]) { case 'T': s[i] = 'A'; break; case 'A': s[i] = 'T'; break; case 'C': s[i] = 'G'; break; case 'G': s[i] = 'C'; break; } } return s; } string toResultStr(Result& r) { stringstream ss; ss << r.readName << "," << r.chromatidSequenceId << "," << (r.startPos + 1) << "," << (r.endPos + 1) << "," << (r.strand ? '+' : '-') << "," << fixed << setprecision(2) << r.score; return ss.str(); } class DNASequencing { vector<string> results; int currentChromatidSequenceId; string currentChromatid; Graph g; public: int passReferenceGenome(int chromatidSequenceId, vector<string> chromatidSequence) { currentChromatid = ""; for (int i = 0; i < chromatidSequence.size(); ++i) { trim(chromatidSequence[i]); currentChromatid += chromatidSequence[i]; } currentChromatidSequenceId = chromatidSequenceId; cerr << "passReferenceGenome: id=" << chromatidSequenceId << endl; return 0; } int initTest(int) { return 0; } int preProcessing() { cerr << "building graph for Chromatid" << currentChromatidSequenceId << endl; size_t cnt = 0; size_t lenDNA = currentChromatid.size(); size_t lenRead = 15; for (size_t start = 0; start < lenDNA - lenRead; ++start) { if (currentChromatid[start] == 'N') { continue; } size_t curr = g.root; for (size_t i = 0; i < lenRead; ++i) { size_t pos = start + i; char base = currentChromatid[pos]; size_t v = g.findOutwardVertex(curr, base); if (v) { curr = v; } else { size_t v = g.addVertex(base); g.addEdge(curr, v); curr = v; } } if (++cnt % 10000 == 0) cerr << "(" << (start * 100 / lenDNA) << "%) " << g.countVertex() << endl; } // debug return 0; } vector<string> getAlignment(int n, double normA, double normS, vector<string> readNames, vector<string> reads) { for (int i = 0; i < n; ++i) { cerr << "read" << i << endl; string normalRead = reads[i]; string reverseRead = createReverseRead(normalRead); Result normalResult(readNames[i], currentChromatidSequenceId, true); Result reverseResult(readNames[i], currentChromatidSequenceId, false); align(normalResult, normalRead); if (normalResult.score >= 0.99) { results.push_back(toResultStr(normalResult)); } else { align(reverseResult, reverseRead); if (normalResult.score > reverseResult.score) { results.push_back(toResultStr(normalResult)); } else { results.push_back(toResultStr(reverseResult)); } } } return results; } private: float calcMatchRate(string& chroma, size_t pos, size_t len, string& read) { size_t cnt = 0; size_t lim = 15; for (size_t i = 0; i < len; ++i) { if (chroma[pos + i] == read[i]) ++cnt; else { if (--lim <= 0) { cnt = 0; break; } } } return (float)cnt / len; } // readは正順のみ void align(Result& result, string& r) { string& c = currentChromatid; size_t len = r.size(); size_t bestPos = -1; float bestRate = 0.0; for (size_t pos = 0; pos < c.size() - len;) { if (c[pos] == r[0] && c[pos + 1] == r[1] && c[pos + 2] == r[2]) { float rate = calcMatchRate(c, pos, len, r); if (rate > bestRate) { bestRate = rate; bestPos = pos; cerr << "best pos=" << pos << " score=" << rate << endl; } if (rate == 1.0) { break; } } pos += 1; } result.startPos = bestPos; result.endPos = bestPos + len; result.score = bestRate; } }; /********************************************************************************************** test bench ***********************************************************************************************/ bool loadChromatidSequence(vector<string>& v) { const char *filename = "chromatid20.fa"; std::ifstream ifs(filename); std::string str; if (ifs.fail()) { std::cerr << "失敗" << std::endl; return false; } int lines = 0; getline(ifs, str); // skip header while (getline(ifs, str)) { if (++lines % 10000 == 0) std::cerr << "."; v.push_back(str); } std::cerr << " loaded" << std::endl; return true; } bool loadReads(vector<string>& readNames, vector<string>& reads) { const char *basename = "small5"; string name1(basename); string name2(basename); name1.append(".fa1"); name2.append(".fa2"); std::ifstream ifs1(name1); std::ifstream ifs2(name2); if (ifs1.fail() || ifs2.fail()) { std::cerr << "失敗" << std::endl; return false; } int lines = 0; std::string str1; std::string str2; while (getline(ifs1, str1) && getline(ifs2, str2)) { if (++lines % 10000 == 0) std::cerr << "."; readNames.push_back(str1.substr(1)); readNames.push_back(str2.substr(1)); getline(ifs1, str1) && getline(ifs2, str2); reads.push_back(str1); reads.push_back(str2); if (reads.size() >= 10) break; } std::cerr << " loaded " << reads.size() << "reads" << std::endl; return true; } int main() { vector<string> chromatidSequence; if (!loadChromatidSequence(chromatidSequence)) return 0; vector<string> readNames; vector<string> reads; if (!loadReads(readNames, reads)) return 0; DNASequencing dnaSequencing; dnaSequencing.passReferenceGenome(20, chromatidSequence); dnaSequencing.initTest(0); dnaSequencing.preProcessing(); clock_t begin = clock(); vector<string> results = dnaSequencing.getAlignment(reads.size(), 1.0, 1.0, readNames, reads); clock_t end = clock(); cerr << "*** results *** " << (end - begin) / 1000 << "(K clocks)" << endl; cout << "*** results *** " << (end - begin) / 1000 << "(K clocks)" << endl; for (vector<string>::iterator it = results.begin(); it != results.end(); ++it) { cout << *it << endl; } return 1; } <|endoftext|>
<commit_before>#include "ics3/eepparam.hpp" ics::EepParam ics::EepParam::strech() noexcept { static const EepParam STRECH(2, 2, 2, 254, &ics::EepParam::setEven, 60); return STRECH; } ics::EepParam ics::EepParam::speed() noexcept { static const EepParam SPEED(4, 2, 1, 127, &ics::EepParam::setNormal, 127); return SPEED; } ics::EepParam ics::EepParam::punch() noexcept { static const EepParam PUNCH(6, 2, 0, 10, &ics::EepParam::setNormal, 1); return PUNCH; } ics::EepParam ics::EepParam::deadBand() noexcept { static const EepParam DEAD_BAND(8, 2, 0, 5, &ics::EepParam::setNormal, 2); return DEAD_BAND; } ics::EepParam ics::EepParam::dumping() noexcept { static const EepParam DUMPING(10, 2, 1, 255, &ics::EepParam::setNormal, 40); return DUMPING; } ics::EepParam ics::EepParam::selfTimer() noexcept { static const EepParam SELF_TIMER(12, 2, 10, 255, &ics::EepParam::setNormal, 250); return SELF_TIMER; } ics::EepParam ics::EepParam::flag() noexcept { static const EepParam FLAG(14, 2, 0, 255, &ics::EepParam::setFlag, 0x8C); return FLAG; } ics::EepParam ics::EepParam::pulseMax() noexcept { static const EepParam PULSE_MAX(16, 4, 3500, 11500, &ics::EepParam::setNormal, 11500); return PULSE_MAX; } ics::EepParam ics::EepParam::pulseMin() noexcept { static const EepParam PULSE_MIN(20, 4, 3500, 11500, &ics::EepParam::setNormal, 3500); return PULSE_MIN; } ics::EepParam ics::EepParam::baudrate() noexcept { static const EepParam BAUDRATE(26, 2, 0, 10, &ics::EepParam::setBaudrate, 10); return BAUDRATE; } ics::EepParam ics::EepParam::temperature() noexcept { static const EepParam TEMPERATURE(28, 2, 1, 127, &ics::EepParam::setNormal, 80); return TEMPERATURE; } ics::EepParam ics::EepParam::current() noexcept { static const EepParam CURRENT(30, 2, 1, 63, &ics::EepParam::setNormal, 63); return CURRENT; } ics::EepParam ics::EepParam::response() noexcept { static const EepParam RESPONSE(50, 2, 1, 5, &ics::EepParam::setNormal, 3); return RESPONSE; } ics::EepParam ics::EepParam::userOffset() noexcept { static const EepParam USER_OFFSET(52, 2, -127, 127, &ics::EepParam::setOffset, 0); return USER_OFFSET; } ics::EepParam ics::EepParam::id() noexcept { static const EepParam ID(56, 2, 0, 31, &ics::EepParam::setNormal, 0); return ID; } ics::EepParam ics::EepParam::strech1() noexcept { static const EepParam STRECH1(58, 2, 2, 254, &ics::EepParam::setEven, 60); return STRECH1; } ics::EepParam ics::EepParam::strech2() noexcept { static const EepParam STRECH2(60, 2, 2, 254, &ics::EepParam::setEven, 60); return STRECH2; } ics::EepParam ics::EepParam::strech3() noexcept { static const EepParam STRECH3(62, 2, 2, 254, &ics::EepParam::setEven, 60); return STRECH3; } uint16_t ics::EepParam::get() const noexcept { return data; } void ics::EepParam::set(uint16_t input) throw(std::invalid_argument) { try { (this->*setFunc)(input); } catch (std::invalid_argument e) { throw e; } } void ics::EepParam::write(std::array<unsigned char, 64> &dest) const noexcept { int mask = 0xF; for (size_t i = offset + length - 1; i >= offset; i--) { dest[i] = data & mask; mask <<= 4; } } void ics::EepParam::read(const std::array<unsigned char, 64> &src) throw(std::invalid_argument) { int result = 0; int mask = 0xF; for (size_t i = offset + length - 1; i >= offset; i--) { result |= src[i] & mask; mask <<= 4; } try { set(result); } catch (std::invalid_argument e) { throw e; } } ics::EepParam::EepParam(size_t offset, size_t length, uint16_t min, uint16_t max, void (EepParam::*setFunc)(uint16_t) throw(std::invalid_argument), uint16_t default_data ) noexcept : offset(offset), length(length), min(min), max(max), setFunc(setFunc), data(default_data) {} void ics::EepParam::setNormal(uint16_t input) throw(std::invalid_argument) { if (input < min) throw std::invalid_argument("Too small value"); if (max < input) throw std::invalid_argument("Too big value"); data = input; } void ics::EepParam::setEven(uint16_t input) throw(std::invalid_argument) { if (input % 2) throw std::invalid_argument("Must even value"); try { setNormal(input); } catch (std::invalid_argument e) { throw e; } } void ics::EepParam::setFlag(uint16_t input) throw(std::invalid_argument) { input &= 010011111; input |= 000001000; data = input; } void ics::EepParam::setBaudrate(uint16_t input) throw(std::invalid_argument) { EepBaudrate const buf = static_cast<EepBaudrate>(input); switch (buf) { case RATE115200: case RATE625000: case RATE1250000: break; default: throw std::invalid_argument("this baudrate not exist"); } data = input; } void ics::EepParam::setOffset(uint16_t input) throw(std::invalid_argument) { static const int8_t minBuf = min; // I expect stand 0x8000 input cast to minus value int8_t inputBuf = input; // I expect stand 0x8000 input cast to minus value if (inputBuf < minBuf) throw std::invalid_argument("Too small value"); if (max < inputBuf) throw std::invalid_argument("Too big value"); data = static_cast<uint8_t>(inputBuf); } <commit_msg>Fix bugs on Eepparam class<commit_after>#include "ics3/eepparam.hpp" ics::EepParam ics::EepParam::strech() noexcept { static const EepParam STRECH(2, 2, 2, 254, &ics::EepParam::setEven, 60); return STRECH; } ics::EepParam ics::EepParam::speed() noexcept { static const EepParam SPEED(4, 2, 1, 127, &ics::EepParam::setNormal, 127); return SPEED; } ics::EepParam ics::EepParam::punch() noexcept { static const EepParam PUNCH(6, 2, 0, 10, &ics::EepParam::setNormal, 1); return PUNCH; } ics::EepParam ics::EepParam::deadBand() noexcept { static const EepParam DEAD_BAND(8, 2, 0, 5, &ics::EepParam::setNormal, 2); return DEAD_BAND; } ics::EepParam ics::EepParam::dumping() noexcept { static const EepParam DUMPING(10, 2, 1, 255, &ics::EepParam::setNormal, 40); return DUMPING; } ics::EepParam ics::EepParam::selfTimer() noexcept { static const EepParam SELF_TIMER(12, 2, 10, 255, &ics::EepParam::setNormal, 250); return SELF_TIMER; } ics::EepParam ics::EepParam::flag() noexcept { static const EepParam FLAG(14, 2, 0, 255, &ics::EepParam::setFlag, 0x8C); return FLAG; } ics::EepParam ics::EepParam::pulseMax() noexcept { static const EepParam PULSE_MAX(16, 4, 3500, 11500, &ics::EepParam::setNormal, 11500); return PULSE_MAX; } ics::EepParam ics::EepParam::pulseMin() noexcept { static const EepParam PULSE_MIN(20, 4, 3500, 11500, &ics::EepParam::setNormal, 3500); return PULSE_MIN; } ics::EepParam ics::EepParam::baudrate() noexcept { static const EepParam BAUDRATE(26, 2, 0, 10, &ics::EepParam::setBaudrate, 10); return BAUDRATE; } ics::EepParam ics::EepParam::temperature() noexcept { static const EepParam TEMPERATURE(28, 2, 1, 127, &ics::EepParam::setNormal, 80); return TEMPERATURE; } ics::EepParam ics::EepParam::current() noexcept { static const EepParam CURRENT(30, 2, 1, 63, &ics::EepParam::setNormal, 63); return CURRENT; } ics::EepParam ics::EepParam::response() noexcept { static const EepParam RESPONSE(50, 2, 1, 5, &ics::EepParam::setNormal, 3); return RESPONSE; } ics::EepParam ics::EepParam::userOffset() noexcept { static const EepParam USER_OFFSET(52, 2, -127, 127, &ics::EepParam::setOffset, 0); return USER_OFFSET; } ics::EepParam ics::EepParam::id() noexcept { static const EepParam ID(56, 2, 0, 31, &ics::EepParam::setNormal, 0); return ID; } ics::EepParam ics::EepParam::strech1() noexcept { static const EepParam STRECH1(58, 2, 2, 254, &ics::EepParam::setEven, 60); return STRECH1; } ics::EepParam ics::EepParam::strech2() noexcept { static const EepParam STRECH2(60, 2, 2, 254, &ics::EepParam::setEven, 60); return STRECH2; } ics::EepParam ics::EepParam::strech3() noexcept { static const EepParam STRECH3(62, 2, 2, 254, &ics::EepParam::setEven, 60); return STRECH3; } uint16_t ics::EepParam::get() const noexcept { return data; } void ics::EepParam::set(uint16_t input) throw(std::invalid_argument) { try { (this->*setFunc)(input); } catch (std::invalid_argument e) { throw e; } } void ics::EepParam::write(std::array<unsigned char, 64> &dest) const noexcept { uint16_t mask = 0xF; for (size_t i = offset + length - 1; i >= offset; i--) { dest[i] = data & mask; mask <<= 4; } } void ics::EepParam::read(const std::array<unsigned char, 64> &src) throw(std::invalid_argument) { uint16_t result = 0; uint16_t mask = 0xF; for (size_t i = offset + length - 1; i >= offset; i--) { result |= src[i] & mask; mask <<= 4; } try { set(result); } catch (std::invalid_argument e) { throw e; } } ics::EepParam::EepParam(size_t offset, size_t length, uint16_t min, uint16_t max, void (EepParam::*setFunc)(uint16_t) throw(std::invalid_argument), uint16_t default_data ) noexcept : offset(offset), length(length), min(min), max(max), setFunc(setFunc), data(default_data) {} void ics::EepParam::setNormal(uint16_t input) throw(std::invalid_argument) { if (input < min) throw std::invalid_argument("Too small value"); if (max < input) throw std::invalid_argument("Too big value"); data = input; } void ics::EepParam::setEven(uint16_t input) throw(std::invalid_argument) { if (input % 2) throw std::invalid_argument("Must even value"); try { setNormal(input); } catch (std::invalid_argument e) { throw e; } } void ics::EepParam::setFlag(uint16_t input) throw(std::invalid_argument) { input &= 010011111; input |= 000001000; data = input; } void ics::EepParam::setBaudrate(uint16_t input) throw(std::invalid_argument) { EepBaudrate const buf = static_cast<EepBaudrate>(input); switch (buf) { case RATE115200: case RATE625000: case RATE1250000: break; default: throw std::invalid_argument("this baudrate not exist"); } data = buf; } void ics::EepParam::setOffset(uint16_t input) throw(std::invalid_argument) { static const int8_t minBuf = min; // I expect stand 0x8000 input cast to minus value int8_t inputBuf = input; // I expect stand 0x8000 input cast to minus value if (inputBuf < minBuf) throw std::invalid_argument("Too small value"); if (max < inputBuf) throw std::invalid_argument("Too big value"); data = static_cast<uint8_t>(inputBuf); } <|endoftext|>
<commit_before>/* This file is part of the PhantomJS project from Ofi Labs. Copyright (C) 2011 Ariya Hidayat <[email protected]> Copyright (C) 2011 execjosh, http://execjosh.blogspot.com 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 the <organization> 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 <COPYRIGHT HOLDER> 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 "encoding.h" Encoding::Encoding() { QTextCodec* codec = QTextCodec::codecForName(DEFAULT_CODEC_NAME); // Fall back to locale codec if (!codec) { codec = QTextCodec::codecForLocale(); } m_codec = codec; } Encoding::Encoding(const QString& encoding) { setEncoding(encoding); } Encoding::~Encoding() { m_codec = (QTextCodec*)NULL; } QString Encoding::decode(const QByteArray& bytes) const { return getCodec()->toUnicode(bytes); } QByteArray Encoding::encode(const QString& string) const { return getCodec()->fromUnicode(string); } QString Encoding::getName() const { // TODO Is it safe to assume UTF-8 here? return QString::fromUtf8(getCodec()->name()); } void Encoding::setEncoding(const QString& encoding) { if (!encoding.isEmpty()) { QTextCodec* codec = QTextCodec::codecForName(encoding.toLatin1()); if (!codec) { m_codec = codec; } } } const Encoding Encoding::UTF8 = Encoding("UTF-8"); // private: QTextCodec* Encoding::getCodec() const { QTextCodec* codec = m_codec; if (!codec) { codec = QTextCodec::codecForLocale(); } return codec; } const QByteArray Encoding::DEFAULT_CODEC_NAME = "UTF-8"; <commit_msg>Fix regression in setEncoding introduced in 9d1c6b9 (#14633)<commit_after>/* This file is part of the PhantomJS project from Ofi Labs. Copyright (C) 2011 Ariya Hidayat <[email protected]> Copyright (C) 2011 execjosh, http://execjosh.blogspot.com 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 the <organization> 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 <COPYRIGHT HOLDER> 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 "encoding.h" Encoding::Encoding() { QTextCodec* codec = QTextCodec::codecForName(DEFAULT_CODEC_NAME); // Fall back to locale codec if (!codec) { codec = QTextCodec::codecForLocale(); } m_codec = codec; } Encoding::Encoding(const QString& encoding) { setEncoding(encoding); } Encoding::~Encoding() { m_codec = (QTextCodec*)NULL; } QString Encoding::decode(const QByteArray& bytes) const { return getCodec()->toUnicode(bytes); } QByteArray Encoding::encode(const QString& string) const { return getCodec()->fromUnicode(string); } QString Encoding::getName() const { // TODO Is it safe to assume UTF-8 here? return QString::fromUtf8(getCodec()->name()); } void Encoding::setEncoding(const QString& encoding) { if (!encoding.isEmpty()) { QTextCodec* codec = QTextCodec::codecForName(encoding.toLatin1()); if (codec) { m_codec = codec; } } } const Encoding Encoding::UTF8 = Encoding("UTF-8"); // private: QTextCodec* Encoding::getCodec() const { QTextCodec* codec = m_codec; if (!codec) { codec = QTextCodec::codecForLocale(); } return codec; } const QByteArray Encoding::DEFAULT_CODEC_NAME = "UTF-8"; <|endoftext|>
<commit_before>//////////////////////////////////////////////////////////// // // DAGON - An Adventure Game Engine // Copyright (c) 2012 Senscape s.r.l. // All rights reserved. // // NOTICE: Senscape permits you to use, modify, and // distribute this file in accordance with the terms of the // license agreement accompanying it. // //////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////// // Headers //////////////////////////////////////////////////////////// #include "DGAudio.h" #include "DGNode.h" #include "DGSpot.h" #include "DGTexture.h" using namespace std; //////////////////////////////////////////////////////////// // Implementation - Constructor //////////////////////////////////////////////////////////// DGNode::DGNode() { _hasBundleName = false; _isSlide = false; _slideReturn = 0; this->setType(DGObjectNode); } //////////////////////////////////////////////////////////// // Implementation - Destructor //////////////////////////////////////////////////////////// DGNode::~DGNode() { // Note that we only delete spots automatically created by this class, not the ones by the user _it = _arrayOfSpots.begin(); while (_it != _arrayOfSpots.end()) { /*DGSpot* spot = (*_it); // FIXME: This causes a crash on Windows if (spot->hasFlag(DGSpotClass)) delete spot;*/ _it++; } } //////////////////////////////////////////////////////////// // Implementation - Checks //////////////////////////////////////////////////////////// bool DGNode::hasBundleName() { return _hasBundleName; } bool DGNode::hasFootstep() { return _hasFootstep; } bool DGNode::hasSpots() { // This should never happen (zero spots) but we check it anyway to // avoid any crashes return !_arrayOfSpots.empty(); } bool DGNode::isSlide() { return _isSlide; } int DGNode::slideReturn() { return _slideReturn; } //////////////////////////////////////////////////////////// // Implementation - Gets //////////////////////////////////////////////////////////// DGSpot* DGNode::currentSpot() { return *_it; } char* DGNode::bundleName() { return _bundleName; } DGAudio* DGNode::footstep() { return _footstep; } const char* DGNode::description() { return _description.c_str(); } DGNode* DGNode::previousNode() { return _previousNode; } //////////////////////////////////////////////////////////// // Implementation - Sets //////////////////////////////////////////////////////////// void DGNode::setBundleName(const char* name) { strncpy(_bundleName, name, DGMaxObjectName); _hasBundleName = true; } void DGNode::setDescription(const char* description) { _description = description; } void DGNode::setFootstep(DGAudio* theFootstep) { _footstep = theFootstep; _hasFootstep = true; } void DGNode::setPreviousNode(DGNode* node) { _previousNode = node; } void DGNode::setSlide(bool enabled) { _isSlide = enabled; } void DGNode::setSlideReturn(int luaHandler) { _slideReturn = luaHandler; } //////////////////////////////////////////////////////////// // Implementation - State changes //////////////////////////////////////////////////////////// void DGNode::addCustomLink(unsigned withDirection, int luaHandler) { DGAction action; action.type = DGActionFunction; action.cursor = DGCursorForward; action.luaHandler = luaHandler; _link(withDirection, &action); } void DGNode::addLink(unsigned int withDirection, DGObject* theTarget) { DGAction action; action.type = DGActionSwitch; action.cursor = DGCursorForward; action.target = theTarget; _link(withDirection, &action); } DGSpot* DGNode::addSpot(DGSpot* aSpot) { _arrayOfSpots.push_back(aSpot); return aSpot; } void DGNode::beginIteratingSpots() { _it = _arrayOfSpots.begin(); } bool DGNode::iterateSpots() { _it++; if (_it == _arrayOfSpots.end()) return false; else return true; } //////////////////////////////////////////////////////////// // Implementation - Private methods //////////////////////////////////////////////////////////// void DGNode::_link(unsigned int direction, DGAction* action) { // We ensure the texture is properly stretched, so we take the default cube size // TODO: This setting should be obtained directly from the DGConfig class int minorBound = (int)(DGDefTexSize / 3); int majorBound = (int)(DGDefTexSize / 1.5f); int offset = (int)(DGDefTexSize/3); // We always have four corners here, hence eight elements since they are squared spots std::vector<int> arrayOfCoordinates; int coordsNormal[] = {minorBound, minorBound, majorBound, minorBound, majorBound, majorBound, minorBound, majorBound}; int coordsShiftRight[] = {minorBound+offset, minorBound, majorBound+offset, minorBound, majorBound+offset, majorBound, minorBound+offset, majorBound}; int coordsShiftLeft[] = {minorBound-offset, minorBound, majorBound-offset, minorBound, majorBound-offset, majorBound, minorBound-offset, majorBound}; DGSpot* newSpot = NULL; DGSpot* auxSpot = NULL; switch (direction) { case DGNorth: case DGEast: case DGSouth: case DGWest: arrayOfCoordinates.assign(coordsNormal, coordsNormal + 8); newSpot = new DGSpot(arrayOfCoordinates, direction, DGSpotClass); break; case DGNorthEast: arrayOfCoordinates.assign(coordsShiftRight, coordsShiftRight + 8); newSpot = new DGSpot(arrayOfCoordinates, DGNorth, DGSpotClass); arrayOfCoordinates.assign(coordsShiftLeft, coordsShiftLeft + 8); auxSpot = new DGSpot(arrayOfCoordinates, DGEast, DGSpotClass); break; case DGSouthEast: arrayOfCoordinates.assign(coordsShiftRight, coordsShiftRight + 8); newSpot = new DGSpot(arrayOfCoordinates, DGEast, DGSpotClass); arrayOfCoordinates.assign(coordsShiftLeft, coordsShiftLeft + 8); auxSpot = new DGSpot(arrayOfCoordinates, DGSouth, DGSpotClass); break; case DGSouthWest: arrayOfCoordinates.assign(coordsShiftRight, coordsShiftRight + 8); newSpot = new DGSpot(arrayOfCoordinates, DGSouth, DGSpotClass); arrayOfCoordinates.assign(coordsShiftLeft, coordsShiftLeft + 8); auxSpot = new DGSpot(arrayOfCoordinates, DGWest, DGSpotClass); break; case DGNorthWest: arrayOfCoordinates.assign(coordsShiftRight, coordsShiftRight + 8); newSpot = new DGSpot(arrayOfCoordinates, DGWest, DGSpotClass); arrayOfCoordinates.assign(coordsShiftLeft, coordsShiftLeft + 8); auxSpot = new DGSpot(arrayOfCoordinates, DGNorth, DGSpotClass); break; } newSpot->setAction(action); newSpot->setColor(0); // Color is set automatically _arrayOfSpots.push_back(newSpot); if (auxSpot) { auxSpot->setAction(action); auxSpot->setColor(0); _arrayOfSpots.push_back(auxSpot); } } <commit_msg>Fix potential crash when switching nodes.<commit_after>//////////////////////////////////////////////////////////// // // DAGON - An Adventure Game Engine // Copyright (c) 2012 Senscape s.r.l. // All rights reserved. // // NOTICE: Senscape permits you to use, modify, and // distribute this file in accordance with the terms of the // license agreement accompanying it. // //////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////// // Headers //////////////////////////////////////////////////////////// #include "DGAudio.h" #include "DGNode.h" #include "DGSpot.h" #include "DGTexture.h" using namespace std; //////////////////////////////////////////////////////////// // Implementation - Constructor //////////////////////////////////////////////////////////// DGNode::DGNode() { _hasBundleName = false; _hasFootstep = false; _isSlide = false; _slideReturn = 0; this->setType(DGObjectNode); } //////////////////////////////////////////////////////////// // Implementation - Destructor //////////////////////////////////////////////////////////// DGNode::~DGNode() { // Note that we only delete spots automatically created by this class, not the ones by the user _it = _arrayOfSpots.begin(); while (_it != _arrayOfSpots.end()) { /*DGSpot* spot = (*_it); // FIXME: This causes a crash on Windows if (spot->hasFlag(DGSpotClass)) delete spot;*/ _it++; } } //////////////////////////////////////////////////////////// // Implementation - Checks //////////////////////////////////////////////////////////// bool DGNode::hasBundleName() { return _hasBundleName; } bool DGNode::hasFootstep() { return _hasFootstep; } bool DGNode::hasSpots() { // This should never happen (zero spots) but we check it anyway to // avoid any crashes return !_arrayOfSpots.empty(); } bool DGNode::isSlide() { return _isSlide; } int DGNode::slideReturn() { return _slideReturn; } //////////////////////////////////////////////////////////// // Implementation - Gets //////////////////////////////////////////////////////////// DGSpot* DGNode::currentSpot() { return *_it; } char* DGNode::bundleName() { return _bundleName; } DGAudio* DGNode::footstep() { return _footstep; } const char* DGNode::description() { return _description.c_str(); } DGNode* DGNode::previousNode() { return _previousNode; } //////////////////////////////////////////////////////////// // Implementation - Sets //////////////////////////////////////////////////////////// void DGNode::setBundleName(const char* name) { strncpy(_bundleName, name, DGMaxObjectName); _hasBundleName = true; } void DGNode::setDescription(const char* description) { _description = description; } void DGNode::setFootstep(DGAudio* theFootstep) { _footstep = theFootstep; _hasFootstep = true; } void DGNode::setPreviousNode(DGNode* node) { _previousNode = node; } void DGNode::setSlide(bool enabled) { _isSlide = enabled; } void DGNode::setSlideReturn(int luaHandler) { _slideReturn = luaHandler; } //////////////////////////////////////////////////////////// // Implementation - State changes //////////////////////////////////////////////////////////// void DGNode::addCustomLink(unsigned withDirection, int luaHandler) { DGAction action; action.type = DGActionFunction; action.cursor = DGCursorForward; action.luaHandler = luaHandler; _link(withDirection, &action); } void DGNode::addLink(unsigned int withDirection, DGObject* theTarget) { DGAction action; action.type = DGActionSwitch; action.cursor = DGCursorForward; action.target = theTarget; _link(withDirection, &action); } DGSpot* DGNode::addSpot(DGSpot* aSpot) { _arrayOfSpots.push_back(aSpot); return aSpot; } void DGNode::beginIteratingSpots() { _it = _arrayOfSpots.begin(); } bool DGNode::iterateSpots() { _it++; if (_it == _arrayOfSpots.end()) return false; else return true; } //////////////////////////////////////////////////////////// // Implementation - Private methods //////////////////////////////////////////////////////////// void DGNode::_link(unsigned int direction, DGAction* action) { // We ensure the texture is properly stretched, so we take the default cube size // TODO: This setting should be obtained directly from the DGConfig class int minorBound = (int)(DGDefTexSize / 3); int majorBound = (int)(DGDefTexSize / 1.5f); int offset = (int)(DGDefTexSize/3); // We always have four corners here, hence eight elements since they are squared spots std::vector<int> arrayOfCoordinates; int coordsNormal[] = {minorBound, minorBound, majorBound, minorBound, majorBound, majorBound, minorBound, majorBound}; int coordsShiftRight[] = {minorBound+offset, minorBound, majorBound+offset, minorBound, majorBound+offset, majorBound, minorBound+offset, majorBound}; int coordsShiftLeft[] = {minorBound-offset, minorBound, majorBound-offset, minorBound, majorBound-offset, majorBound, minorBound-offset, majorBound}; DGSpot* newSpot = NULL; DGSpot* auxSpot = NULL; switch (direction) { case DGNorth: case DGEast: case DGSouth: case DGWest: arrayOfCoordinates.assign(coordsNormal, coordsNormal + 8); newSpot = new DGSpot(arrayOfCoordinates, direction, DGSpotClass); break; case DGNorthEast: arrayOfCoordinates.assign(coordsShiftRight, coordsShiftRight + 8); newSpot = new DGSpot(arrayOfCoordinates, DGNorth, DGSpotClass); arrayOfCoordinates.assign(coordsShiftLeft, coordsShiftLeft + 8); auxSpot = new DGSpot(arrayOfCoordinates, DGEast, DGSpotClass); break; case DGSouthEast: arrayOfCoordinates.assign(coordsShiftRight, coordsShiftRight + 8); newSpot = new DGSpot(arrayOfCoordinates, DGEast, DGSpotClass); arrayOfCoordinates.assign(coordsShiftLeft, coordsShiftLeft + 8); auxSpot = new DGSpot(arrayOfCoordinates, DGSouth, DGSpotClass); break; case DGSouthWest: arrayOfCoordinates.assign(coordsShiftRight, coordsShiftRight + 8); newSpot = new DGSpot(arrayOfCoordinates, DGSouth, DGSpotClass); arrayOfCoordinates.assign(coordsShiftLeft, coordsShiftLeft + 8); auxSpot = new DGSpot(arrayOfCoordinates, DGWest, DGSpotClass); break; case DGNorthWest: arrayOfCoordinates.assign(coordsShiftRight, coordsShiftRight + 8); newSpot = new DGSpot(arrayOfCoordinates, DGWest, DGSpotClass); arrayOfCoordinates.assign(coordsShiftLeft, coordsShiftLeft + 8); auxSpot = new DGSpot(arrayOfCoordinates, DGNorth, DGSpotClass); break; } newSpot->setAction(action); newSpot->setColor(0); // Color is set automatically _arrayOfSpots.push_back(newSpot); if (auxSpot) { auxSpot->setAction(action); auxSpot->setColor(0); _arrayOfSpots.push_back(auxSpot); } } <|endoftext|>
<commit_before>/******************************************************************************* * example2.cpp * Measure time to write to containers in one of 2 modes: * 1. using the standard STL allocator * 2. using ArenaAlloc * * This software is distributed under the terms of the MIT license. * Don't panic!!!! Share and enjoy. *****************************************************************************/ #include <thread> #include <condition_variable> #include <mutex> #include <chrono> #include <iostream> #include <vector> #include <algorithm> #include <map> #include "arenaalloc.h" // As promised in example1.cpp, this example requires c++11 // compile as: g++ -O2 -DARENA_ALLOCATOR_TEST -std=c++11 -o example2-arena example2.cpp -lpthread // to test the arena allocator logic // compile as: g++ -O2 -std=c++11 -o example2-stdalloc example2.cpp -lpthread // to test the standard allocator. // If tcmalloc is available try this also: // g++ -O2 -std=c++11 -fno-builtin-malloc -o example2-stdtcmalloc example2.cpp -ltcmalloc -lpthread // g++ -O2 -DARENA_ALLOCATOR_TEST -std=c++11 -fno-builtin-malloc -o example2-arenatcmalloc example2.cpp -ltcmalloc -lpthread // In my testing of this not perfectly scientific example, the standard allocator + tcmalloc was faster by // a little bit over the arena allocator with the standard malloc. Both of those were significantly // faster than the standard allocator by itself. I kept getting a core dump when // running the arena allocator with tcmalloc so I cannot present results on that. Give it a try though. // It's possible there may be a problem in how my code is structured for tcmalloc to work with the arena allocator. typedef std::chrono::high_resolution_clock::time_point hres_t; typedef std::chrono::duration<size_t, std::ratio<1,1000000> > duration_t; // duration in micro-seconds struct task { std::mutex& m_mutexRef; std::condition_variable& m_condVarRef; bool& m_run; task( std::mutex& m, std::condition_variable& condVar, bool& runVar ): m_mutexRef( m ), m_run( runVar ), m_condVarRef( condVar ) { } void operator()() { // barrier synchronize the threads as much as possible to start them as close as possible // to the same time. { std::unique_lock<std::mutex> lk( m_mutexRef ); std::cout << "Thread=" << std::this_thread::get_id() << " is waiting..." << std::endl; m_condVarRef.wait( lk, [this] { return m_run == true; } ); // wait until the lambda condition is true } hres_t start = std::chrono::high_resolution_clock::now(); // do map insert doWork(); hres_t end = std::chrono::high_resolution_clock::now(); duration_t timespan = std::chrono::duration_cast< duration_t >( end - start ); { // report timing results w/ lock held so that the output isn't all munged std::lock_guard<std::mutex> lg( m_mutexRef ); std::cout << "threadid: " << std::this_thread::get_id() << " clicks: " << timespan.count() << std::endl; } } void doWork() { // insert a million values into a map<int,strtype> using the specified map type #ifdef ARENA_ALLOCATOR_TEST typedef std::basic_string<char, std::char_traits<char>, ArenaAlloc::Alloc<char> > strtype; ArenaAlloc::Alloc< char > charAllocator( 65536 ); strtype answerToEverything( "42", charAllocator ); ArenaAlloc::Alloc< std::pair< const int, strtype > > alloc( 65536 ); std::map< int, strtype , std::less<int>, ArenaAlloc::Alloc<std::pair<const int,strtype> > > intToStrMap( std::less<int>(), alloc ); #else typedef std::string strtype; std::map<int, strtype> intToStrMap; std::string answerToEverything( "42" ); #endif for( int i = 0; i < 10000000; i++ ) { intToStrMap.insert( std::pair< const int, strtype >( i, answerToEverything ) ); // The answer to everything } // Note: time to clear allocator is included in the runtime. } }; int main() { size_t concurrency = std::thread::hardware_concurrency(); std::cout << "Running with " << concurrency << " threads" << std::endl; std::vector< std::thread > threads; std::mutex m; std::condition_variable cv; bool runBool = false; for( size_t i = 0; i < concurrency; i++ ) { task t( m, cv, runBool ); threads.push_back( std::thread( t ) ); } std::cout << "Waiting a bit before waking the stalled threads" << std::endl; std::this_thread::sleep_for( std::chrono::seconds( 5 ) ); std::cout << "And there off...!" << std::endl; runBool = true; cv.notify_all(); std::for_each( threads.begin(), threads.end(), std::mem_fn( &std::thread::join ) ); return 0; } <commit_msg>fixed comment and spacing<commit_after>/******************************************************************************* * example2.cpp * Measure time to write to containers in one of 2 modes: * 1. using the standard STL allocator * 2. using ArenaAlloc * * This software is distributed under the terms of the MIT license. * Don't panic!!!! Share and enjoy. *****************************************************************************/ #include <thread> #include <condition_variable> #include <mutex> #include <chrono> #include <iostream> #include <vector> #include <algorithm> #include <map> #include "arenaalloc.h" // As promised in example1.cpp, this example requires c++11 // compile as: g++ -O2 -DARENA_ALLOCATOR_TEST -std=c++11 -o example2-arena example2.cpp -lpthread // to test the arena allocator logic // compile as: g++ -O2 -std=c++11 -o example2-stdalloc example2.cpp -lpthread // to test the standard allocator. // If tcmalloc is available try this also: // g++ -O2 -std=c++11 -fno-builtin-malloc -o example2-stdtcmalloc example2.cpp -ltcmalloc -lpthread // g++ -O2 -DARENA_ALLOCATOR_TEST -std=c++11 -fno-builtin-malloc -o example2-arenatcmalloc example2.cpp -ltcmalloc -lpthread // In my testing of this not perfectly scientific example, the standard allocator + tcmalloc was faster by // a little bit over the arena allocator with the standard malloc. Both of those were significantly // faster than the standard allocator with the standard malloc. I kept getting a core dump when // running the arena allocator with tcmalloc so I cannot present results on that. Give it a try though. // It's possible there may be a problem in how my code is structured for tcmalloc to work with the arena allocator. typedef std::chrono::high_resolution_clock::time_point hres_t; typedef std::chrono::duration<size_t, std::ratio<1,1000000> > duration_t; // duration in micro-seconds struct task { std::mutex& m_mutexRef; std::condition_variable& m_condVarRef; bool& m_run; task( std::mutex& m, std::condition_variable& condVar, bool& runVar ): m_mutexRef( m ), m_run( runVar ), m_condVarRef( condVar ) { } void operator()() { // barrier synchronize the threads as much as possible to start them as close as possible // to the same time. { std::unique_lock<std::mutex> lk( m_mutexRef ); std::cout << "Thread=" << std::this_thread::get_id() << " is waiting..." << std::endl; m_condVarRef.wait( lk, [this] { return m_run == true; } ); // wait until the lambda condition is true } hres_t start = std::chrono::high_resolution_clock::now(); // do map insert doWork(); hres_t end = std::chrono::high_resolution_clock::now(); duration_t timespan = std::chrono::duration_cast< duration_t >( end - start ); { // report timing results w/ lock held so that the output isn't all munged std::lock_guard<std::mutex> lg( m_mutexRef ); std::cout << "threadid: " << std::this_thread::get_id() << " clicks: " << timespan.count() << std::endl; } } void doWork() { // insert a million values into a map<int,strtype> using the specified map type #ifdef ARENA_ALLOCATOR_TEST typedef std::basic_string<char, std::char_traits<char>, ArenaAlloc::Alloc<char> > strtype; ArenaAlloc::Alloc< char > charAllocator( 65536 ); strtype answerToEverything( "42", charAllocator ); ArenaAlloc::Alloc< std::pair< const int, strtype > > alloc( 65536 ); std::map< int, strtype , std::less<int>, ArenaAlloc::Alloc<std::pair<const int,strtype> > > intToStrMap( std::less<int>(), alloc ); #else typedef std::string strtype; std::map<int, strtype> intToStrMap; std::string answerToEverything( "42" ); #endif for( int i = 0; i < 10000000; i++ ) { intToStrMap.insert( std::pair< const int, strtype >( i, answerToEverything ) ); // The answer to everything } // Note: time to clear allocator is included in the runtime. } }; int main() { size_t concurrency = std::thread::hardware_concurrency(); std::cout << "Running with " << concurrency << " threads" << std::endl; std::vector< std::thread > threads; std::mutex m; std::condition_variable cv; bool runBool = false; for( size_t i = 0; i < concurrency; i++ ) { task t( m, cv, runBool ); threads.push_back( std::thread( t ) ); } std::cout << "Waiting a bit before waking the stalled threads" << std::endl; std::this_thread::sleep_for( std::chrono::seconds( 5 ) ); std::cout << "And there off...!" << std::endl; runBool = true; cv.notify_all(); std::for_each( threads.begin(), threads.end(), std::mem_fn( &std::thread::join ) ); return 0; } <|endoftext|>
<commit_before>// RUN: %clangxx -O0 -g %s -o %t && %run %t 2>&1 | FileCheck %s // // UNSUPPORTED: linux, solaris #include <assert.h> #include <errno.h> #include <stdio.h> #include <string.h> #include <fstab.h> int main(void) { printf("getfsent\n"); setfsent(); struct fstab *fentry = getfsent(); assert(fentry); setfsent(); struct fstab *pentry = getfsspec(fentry->fs_spec); assert(pentry); setfsent(); struct fstab *wentry = getfsfile(fentry->fs_file); assert(wentry); assert(!memcmp(fentry, wentry, sizeof(*wentry))); assert(!memcmp(pentry, wentry, sizeof(*pentry))); printf("First entry: device block '%s', mounted with '%s'\n", fentry->fs_spec, fentry->fs_mntops); endfsent(); return 0; // CHECK: getfsent // CHECK: First entry: device block '{{.*}}', mounted with '{{.*}}' } <commit_msg>Re-disable the sanitizer_common/TestCases/Posix/getfsent.cc test. Recent macOS versions don't have the /etc/fstab file any more so we cannot test getfsent/setfsent APIs on Darwin.<commit_after>// RUN: %clangxx -O0 -g %s -o %t && %run %t 2>&1 | FileCheck %s // // UNSUPPORTED: linux, darwin, solaris #include <assert.h> #include <errno.h> #include <stdio.h> #include <string.h> #include <fstab.h> int main(void) { printf("getfsent\n"); setfsent(); struct fstab *fentry = getfsent(); assert(fentry); setfsent(); struct fstab *pentry = getfsspec(fentry->fs_spec); assert(pentry); setfsent(); struct fstab *wentry = getfsfile(fentry->fs_file); assert(wentry); assert(!memcmp(fentry, wentry, sizeof(*wentry))); assert(!memcmp(pentry, wentry, sizeof(*pentry))); printf("First entry: device block '%s', mounted with '%s'\n", fentry->fs_spec, fentry->fs_mntops); endfsent(); return 0; // CHECK: getfsent // CHECK: First entry: device block '{{.*}}', mounted with '{{.*}}' } <|endoftext|>
<commit_before>#include <ros/ros.h> #include <sensor_msgs/Imu.h> #include <gazebo_msgs/GetModelState.h> #include <message_filters/subscriber.h> #include <geometry_msgs/PoseStamped.h> namespace { using namespace std; using namespace geometry_msgs; static const double FREQUENCY = 0.01; static const double BASE_X_DEFAULT = 0.4; class FakeIMU { private: //! Publisher for the pose ros::Publisher posePub; //! Node handle ros::NodeHandle nh; //! Private nh ros::NodeHandle pnh; //! Frequency at which to publish the humanoid state ros::Timer timer; //! Cached service client. ros::ServiceClient modelStateServ; //! Publisher for the pose visualization ros::Publisher poseVizPub; //! Model name string modelName; public: FakeIMU() : pnh("~") { posePub = nh.advertise<sensor_msgs::Imu>( "out", 1); ros::service::waitForService("/gazebo/get_model_state"); modelStateServ = nh.serviceClient<gazebo_msgs::GetModelState>("/gazebo/get_model_state", true /* persistent */); pnh.param<string>("modelName", modelName, "human"); poseVizPub = nh.advertise<geometry_msgs::PoseStamped>("imu/pose", 1); timer = nh.createTimer(ros::Duration(FREQUENCY), &FakeIMU::callback, this); timer.start(); } private: void visualizeOrientation(const std_msgs::Header& header, const geometry_msgs::Quaternion& orientation) { PoseStamped ps; ps.header = header; ps.pose.orientation = orientation; ps.pose.position.x = BASE_X_DEFAULT; poseVizPub.publish(ps); } sensor_msgs::Imu getIMUData() { gazebo_msgs::GetModelState modelState; modelState.request.model_name = modelName; modelStateServ.call(modelState); sensor_msgs::Imu data; data.header.stamp = ros::Time::now(); data.header.frame_id = "/odom_combined"; data.angular_velocity = modelState.response.twist.angular; data.orientation = modelState.response.pose.orientation; return data; } void callback(const ros::TimerEvent& event) { // Lookup the current IMU data for the human sensor_msgs::Imu data = getIMUData(); visualizeOrientation(data.header, data.orientation); // Publish the event ROS_DEBUG_STREAM("Publishing an IMU event: " << data); posePub.publish(data); } }; } int main(int argc, char** argv) { ros::init(argc, argv, "fake_imu"); FakeIMU fi; ros::spin(); } <commit_msg>Fix error message when fetching model state prior to model being fully initialized<commit_after>#include <ros/ros.h> #include <sensor_msgs/Imu.h> #include <gazebo_msgs/GetModelState.h> #include <gazebo_msgs/GetWorldProperties.h> #include <message_filters/subscriber.h> #include <geometry_msgs/PoseStamped.h> namespace { using namespace std; using namespace geometry_msgs; static const double FREQUENCY = 0.01; static const double BASE_X_DEFAULT = 0.4; class FakeIMU { private: //! Publisher for the pose ros::Publisher posePub; //! Node handle ros::NodeHandle nh; //! Private nh ros::NodeHandle pnh; //! Frequency at which to publish the humanoid state ros::Timer timer; //! Cached service client. ros::ServiceClient modelStateServ; //! Cached service client. ros::ServiceClient worldStateServ; //! Publisher for the pose visualization ros::Publisher poseVizPub; //! Model name string modelName; //! Whether the model is initialized bool isModelInitialized; public: FakeIMU() : pnh("~") { posePub = nh.advertise<sensor_msgs::Imu>( "out", 1); ros::service::waitForService("/gazebo/get_world_properties"); worldStateServ = nh.serviceClient<gazebo_msgs::GetWorldProperties>("/gazebo/get_world_properties", true /* persistent */); ros::service::waitForService("/gazebo/get_model_state"); modelStateServ = nh.serviceClient<gazebo_msgs::GetModelState>("/gazebo/get_model_state", true /* persistent */); pnh.param<string>("modelName", modelName, "human"); poseVizPub = nh.advertise<geometry_msgs::PoseStamped>("imu/pose", 1); isModelInitialized = false; timer = nh.createTimer(ros::Duration(FREQUENCY), &FakeIMU::callback, this); timer.start(); ROS_INFO("Fake human IMU initialized successfully"); } private: void visualizeOrientation(const std_msgs::Header& header, const geometry_msgs::Quaternion& orientation) { PoseStamped ps; ps.header = header; ps.pose.orientation = orientation; ps.pose.position.x = BASE_X_DEFAULT; poseVizPub.publish(ps); } sensor_msgs::Imu getIMUData() { gazebo_msgs::GetModelState modelState; modelState.request.model_name = modelName; modelStateServ.call(modelState); sensor_msgs::Imu data; data.header.stamp = ros::Time::now(); data.header.frame_id = "/odom_combined"; data.angular_velocity = modelState.response.twist.angular; data.orientation = modelState.response.pose.orientation; return data; } void callback(const ros::TimerEvent& event) { if (!isModelInitialized) { gazebo_msgs::GetWorldProperties worldProperties; if (!worldStateServ.call(worldProperties)) { ROS_ERROR("Failed to get world properties"); return; } for (unsigned int i = 0; i < worldProperties.response.model_names.size(); ++i) { if (worldProperties.response.model_names[i] == modelName) { ROS_INFO("Human model is available"); isModelInitialized = true; } } } if (!isModelInitialized) { ROS_DEBUG("Human model not initialized"); return; } // Lookup the current IMU data for the human sensor_msgs::Imu data = getIMUData(); visualizeOrientation(data.header, data.orientation); // Publish the event ROS_DEBUG_STREAM("Publishing an IMU event: " << data); posePub.publish(data); } }; } int main(int argc, char** argv) { ros::init(argc, argv, "fake_imu"); FakeIMU fi; ros::spin(); } <|endoftext|>
<commit_before>/* * FaultHandler.cpp * Copyright (c) 2013 Collin Kidder, Michael Neuweiler, Charles Galpin 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 "FaultHandler.h" FaultHandler::FaultHandler() { } void FaultHandler::setup() { TickHandler::getInstance()->detach(this); Logger::info("Initializing Fault Handler", CODAUQM, this); loadFromEEPROM(); //Use the heartbeat interval because it's slow and already exists so we can piggyback on the interrupt //so as to not create more timers than necessary. TickHandler::getInstance()->attach(this, CFG_TICK_INTERVAL_HEARTBEAT); } //Every tick update the global time and save it to EEPROM (delayed saving) void FaultHandler::handleTick() { globalTime = baseTime + (millis() / 100); memCache->Write(EE_FAULT_LOG + EEFAULT_RUNTIME, globalTime); } uint16_t FaultHandler::raiseFault(uint16_t device, uint16_t code) { bool incPtr = false; globalTime = baseTime + (millis() / 100); uint16_t tempIdx = faultWritePointer; if (tempIdx > 0) tempIdx--; else tempIdx = CFG_FAULT_HISTORY_SIZE - 1; //if this is the same as the previously registered fault then just update the time if (faultList[tempIdx].device == device && faultList[tempIdx].faultCode == code) { faultList[tempIdx].timeStamp = globalTime; } else { faultList[faultWritePointer].timeStamp = globalTime; faultList[faultWritePointer].ack = false; faultList[faultWritePointer].device = device; faultList[faultWritePointer].faultCode = code; faultList[faultWritePointer].ongoing = false; incPtr = true; } memCache->Write(EE_FAULT_LOG + EEFAULT_FAULTS_START + sizeof(FAULT) * faultWritePointer, &faultList[faultWritePointer], sizeof(FAULT)); //Cause the memory caching system to immediately write the page memCache->InvalidateAddress(EE_FAULT_LOG + EEFAULT_FAULTS_START + sizeof(FAULT)* faultWritePointer); if (incPtr) faultWritePointer = (faultWritePointer + 1) % CFG_FAULT_HISTORY_SIZE; memCache->Write(EE_FAULT_LOG + EEFAULT_WRITEPTR , faultWritePointer); //Cause the page to be immediately fully aged so that it is written very soon. memCache->AgeFullyAddress(EE_FAULT_LOG + EEFAULT_WRITEPTR); } uint16_t FaultHandler::getFaultCount() { int count = 0; for (int i = 0; i < CFG_FAULT_HISTORY_SIZE; i++) { if (faultList[i].ack == false) { count++; } } return count; } //the fault handler isn't a device per se and uses more memory than a device would normally be allocated so //it does not use PrefHandler void FaultHandler::loadFromEEPROM() { uint8_t validByte; memCache->Read(EE_FAULT_LOG, &validByte); if (validByte == 0xB2) //magic byte value for a valid fault cache { memCache->Read(EE_FAULT_LOG + EEFAULT_READPTR, &faultReadPointer); memCache->Read(EE_FAULT_LOG + EEFAULT_WRITEPTR, &faultWritePointer); memCache->Read(EE_FAULT_LOG + EEFAULT_RUNTIME, &globalTime); baseTime = globalTime; for (int i = 0; i < CFG_FAULT_HISTORY_SIZE; i++) { memCache->Read(EE_FAULT_LOG + EEFAULT_FAULTS_START + sizeof(FAULT) * i, &faultList[i], sizeof(FAULT)); } } else //reinitialize the fault cache storage { validByte = 0xB2; memCache->Write(EE_FAULT_LOG, validByte); memCache->Write(EE_FAULT_LOG + EEFAULT_READPTR, (uint16_t)0); memCache->Write(EE_FAULT_LOG + EEFAULT_WRITEPTR, (uint16_t)0); globalTime = baseTime = millis() / 100; memCache->Write(EE_FAULT_LOG + EEFAULT_RUNTIME, globalTime); FAULT tempFault; tempFault.ack = true; tempFault.device = 0xFFFF; tempFault.faultCode = 0xFFFF; tempFault.ongoing = false; tempFault.timeStamp = 0; for (int i = 0; i < CFG_FAULT_HISTORY_SIZE; i++) { faultList[i] = tempFault; } saveToEEPROM(); } } void FaultHandler::saveToEEPROM() { memCache->Write(EE_FAULT_LOG + EEFAULT_READPTR, faultReadPointer); memCache->Write(EE_FAULT_LOG + EEFAULT_WRITEPTR, faultWritePointer); memCache->Write(EE_FAULT_LOG + EEFAULT_RUNTIME, globalTime); for (int i = 0; i < CFG_FAULT_HISTORY_SIZE; i++) { memCache->Write(EE_FAULT_LOG + EEFAULT_FAULTS_START + sizeof(FAULT) * i, &faultList[i], sizeof(FAULT)); } } bool FaultHandler::getNextFault(FAULT *fault) { uint16_t j; for (int i = 0; i < CFG_FAULT_HISTORY_SIZE; i++) { j = faultReadPointer + i; if (faultList[j].ack == false) { fault = &faultList[j]; return true; } } return false; } bool FaultHandler::getFault(uint16_t fault, FAULT *outFault) { if (fault > 0 && fault < CFG_FAULT_HISTORY_SIZE) { outFault = &faultList[fault]; return true; } return false; } uint16_t FaultHandler::setFaultACK(uint16_t fault) { if (fault > 0 && fault < CFG_FAULT_HISTORY_SIZE) { faultList[fault].ack = 1; } } uint16_t FaultHandler::setFaultOngoing(uint16_t fault, bool ongoing) { if (fault > 0 && fault < CFG_FAULT_HISTORY_SIZE) { faultList[fault].ongoing = ongoing; } } FaultHandler faultHandler; <commit_msg>Added an include that is needed to even be able to compile (whoops...)<commit_after>/* * FaultHandler.cpp * Copyright (c) 2013 Collin Kidder, Michael Neuweiler, Charles Galpin 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 "FaultHandler.h" #include "eeprom_layout.h" FaultHandler::FaultHandler() { } void FaultHandler::setup() { TickHandler::getInstance()->detach(this); Logger::info("Initializing Fault Handler", CODAUQM, this); loadFromEEPROM(); //Use the heartbeat interval because it's slow and already exists so we can piggyback on the interrupt //so as to not create more timers than necessary. TickHandler::getInstance()->attach(this, CFG_TICK_INTERVAL_HEARTBEAT); } //Every tick update the global time and save it to EEPROM (delayed saving) void FaultHandler::handleTick() { globalTime = baseTime + (millis() / 100); memCache->Write(EE_FAULT_LOG + EEFAULT_RUNTIME, globalTime); } uint16_t FaultHandler::raiseFault(uint16_t device, uint16_t code) { bool incPtr = false; globalTime = baseTime + (millis() / 100); uint16_t tempIdx = faultWritePointer; if (tempIdx > 0) tempIdx--; else tempIdx = CFG_FAULT_HISTORY_SIZE - 1; //if this is the same as the previously registered fault then just update the time if (faultList[tempIdx].device == device && faultList[tempIdx].faultCode == code) { faultList[tempIdx].timeStamp = globalTime; } else { faultList[faultWritePointer].timeStamp = globalTime; faultList[faultWritePointer].ack = false; faultList[faultWritePointer].device = device; faultList[faultWritePointer].faultCode = code; faultList[faultWritePointer].ongoing = false; incPtr = true; } memCache->Write(EE_FAULT_LOG + EEFAULT_FAULTS_START + sizeof(FAULT) * faultWritePointer, &faultList[faultWritePointer], sizeof(FAULT)); //Cause the memory caching system to immediately write the page memCache->InvalidateAddress(EE_FAULT_LOG + EEFAULT_FAULTS_START + sizeof(FAULT)* faultWritePointer); if (incPtr) faultWritePointer = (faultWritePointer + 1) % CFG_FAULT_HISTORY_SIZE; memCache->Write(EE_FAULT_LOG + EEFAULT_WRITEPTR , faultWritePointer); //Cause the page to be immediately fully aged so that it is written very soon. memCache->AgeFullyAddress(EE_FAULT_LOG + EEFAULT_WRITEPTR); } uint16_t FaultHandler::getFaultCount() { int count = 0; for (int i = 0; i < CFG_FAULT_HISTORY_SIZE; i++) { if (faultList[i].ack == false) { count++; } } return count; } //the fault handler isn't a device per se and uses more memory than a device would normally be allocated so //it does not use PrefHandler void FaultHandler::loadFromEEPROM() { uint8_t validByte; memCache->Read(EE_FAULT_LOG, &validByte); if (validByte == 0xB2) //magic byte value for a valid fault cache { memCache->Read(EE_FAULT_LOG + EEFAULT_READPTR, &faultReadPointer); memCache->Read(EE_FAULT_LOG + EEFAULT_WRITEPTR, &faultWritePointer); memCache->Read(EE_FAULT_LOG + EEFAULT_RUNTIME, &globalTime); baseTime = globalTime; for (int i = 0; i < CFG_FAULT_HISTORY_SIZE; i++) { memCache->Read(EE_FAULT_LOG + EEFAULT_FAULTS_START + sizeof(FAULT) * i, &faultList[i], sizeof(FAULT)); } } else //reinitialize the fault cache storage { validByte = 0xB2; memCache->Write(EE_FAULT_LOG, validByte); memCache->Write(EE_FAULT_LOG + EEFAULT_READPTR, (uint16_t)0); memCache->Write(EE_FAULT_LOG + EEFAULT_WRITEPTR, (uint16_t)0); globalTime = baseTime = millis() / 100; memCache->Write(EE_FAULT_LOG + EEFAULT_RUNTIME, globalTime); FAULT tempFault; tempFault.ack = true; tempFault.device = 0xFFFF; tempFault.faultCode = 0xFFFF; tempFault.ongoing = false; tempFault.timeStamp = 0; for (int i = 0; i < CFG_FAULT_HISTORY_SIZE; i++) { faultList[i] = tempFault; } saveToEEPROM(); } } void FaultHandler::saveToEEPROM() { memCache->Write(EE_FAULT_LOG + EEFAULT_READPTR, faultReadPointer); memCache->Write(EE_FAULT_LOG + EEFAULT_WRITEPTR, faultWritePointer); memCache->Write(EE_FAULT_LOG + EEFAULT_RUNTIME, globalTime); for (int i = 0; i < CFG_FAULT_HISTORY_SIZE; i++) { memCache->Write(EE_FAULT_LOG + EEFAULT_FAULTS_START + sizeof(FAULT) * i, &faultList[i], sizeof(FAULT)); } } bool FaultHandler::getNextFault(FAULT *fault) { uint16_t j; for (int i = 0; i < CFG_FAULT_HISTORY_SIZE; i++) { j = faultReadPointer + i; if (faultList[j].ack == false) { fault = &faultList[j]; return true; } } return false; } bool FaultHandler::getFault(uint16_t fault, FAULT *outFault) { if (fault > 0 && fault < CFG_FAULT_HISTORY_SIZE) { outFault = &faultList[fault]; return true; } return false; } uint16_t FaultHandler::setFaultACK(uint16_t fault) { if (fault > 0 && fault < CFG_FAULT_HISTORY_SIZE) { faultList[fault].ack = 1; } } uint16_t FaultHandler::setFaultOngoing(uint16_t fault, bool ongoing) { if (fault > 0 && fault < CFG_FAULT_HISTORY_SIZE) { faultList[fault].ongoing = ongoing; } } FaultHandler faultHandler; <|endoftext|>
<commit_before>/* * bacteria-ui, GUI for cellular automaton * Copyright (C) 2016 Pavel Dolgov * * See the LICENSE file for terms of use. */ #include <exception> #include <QtGui> #include "MainWindow.hpp" class MyApplication : public QApplication { public: MyApplication(int& argc, char* argv[]): QApplication(argc, argv) { } bool notify(QObject* receiver, QEvent* event) { try { return QApplication::notify(receiver, event); } catch (const std::exception& error) { QString what = QString::fromStdString(error.what()); QString message = "<b>The error occurred</b>." "<br/><br/>Contact developers! " "<b>[email protected]</b>"; what = what.replace("&", "&amp;"); what = what.replace("'", "&apos;"); what = what.replace("<", "&lt;"); what = what.replace(">", "&gt;"); what = what.replace("\"", "&quot;"); QString m = message + "<br/><br/>" + what; QErrorMessage::qtHandler()->resize(400, 300); QErrorMessage::qtHandler()->showMessage(m); return false; } } }; int main(int argc, char* argv[]) { MyApplication a(argc, argv); MainWindow w; w.showMaximized(); return a.exec(); } <commit_msg>srand(time(NULL)) in main()<commit_after>/* * bacteria-ui, GUI for cellular automaton * Copyright (C) 2016 Pavel Dolgov * * See the LICENSE file for terms of use. */ #include <cstdlib> #include <ctime> #include <exception> #include <QtGui> #include "MainWindow.hpp" class MyApplication : public QApplication { public: MyApplication(int& argc, char* argv[]): QApplication(argc, argv) { } bool notify(QObject* receiver, QEvent* event) { try { return QApplication::notify(receiver, event); } catch (const std::exception& error) { QString what = QString::fromStdString(error.what()); QString message = "<b>The error occurred</b>." "<br/><br/>Contact developers! " "<b>[email protected]</b>"; what = what.replace("&", "&amp;"); what = what.replace("'", "&apos;"); what = what.replace("<", "&lt;"); what = what.replace(">", "&gt;"); what = what.replace("\"", "&quot;"); QString m = message + "<br/><br/>" + what; QErrorMessage::qtHandler()->resize(400, 300); QErrorMessage::qtHandler()->showMessage(m); return false; } } }; int main(int argc, char* argv[]) { srand(time(NULL)); MyApplication a(argc, argv); MainWindow w; w.showMaximized(); return a.exec(); } <|endoftext|>
<commit_before>#include <QApplication> #include <QFontDatabase> #include <QtGlobal> #include <QFile> #include <QCommandLineParser> #include <QFileInfo> #include <QDir> #include "neovimconnector.h" #include "mainwindow.h" #include "app.h" /// A log handler for Qt messages, all messages are dumped into the file /// passed via the NVIM_QT_LOG variable. Some information is only available /// in debug builds (e.g. qDebug is only called in debug builds). /// /// In UNIX Qt prints messages to the console output, but in Windows this is /// the only way to get Qt's debug/warning messages. void logger(QtMsgType type, const QMessageLogContext& ctx, const QString& msg) { QFile logFile(qgetenv("NVIM_QT_LOG")); if (logFile.open(QIODevice::Append | QIODevice::Text)) { QTextStream stream(&logFile); stream << msg << "\n"; } } #ifdef Q_OS_MAC bool getLoginEnvironment(const QString& path) { QProcess proc; proc.start(path, {"-l", "-c", "env", "-i"}); if (!proc.waitForFinished()) { qDebug() << "Failed to execute shell to get environemnt" << path; return false; } QByteArray out = proc.readAllStandardOutput(); foreach(const QByteArray& item, out.split('\n')) { int index = item.indexOf('='); if (index > 0) { qputenv(item.mid(0, index), item.mid(index+1)); qDebug() << item.mid(0, index) << item.mid(index+1); } } return true; } void loadLoginEnvironmen() { QByteArray shellPath = qgetenv("SHELL"); if (!getLoginEnvironment(shellPath)) { getLoginEnvironment("/bin/bash"); } } #endif int main(int argc, char **argv) { NeovimQt::App app(argc, argv); app.setApplicationDisplayName("Neovim"); app.setWindowIcon(QIcon(":/neovim.png")); if (!qgetenv("NVIM_QT_LOG").isEmpty()) { qInstallMessageHandler(logger); } QCommandLineParser parser; parser.addOption(QCommandLineOption("embed", QCoreApplication::translate("main", "Communicate with Neovim over stdin/out"))); parser.addOption(QCommandLineOption("server", QCoreApplication::translate("main", "Connect to existing Neovim instance"), QCoreApplication::translate("main", "addr"))); parser.addOption(QCommandLineOption("geometry", QCoreApplication::translate("main", "Initial window geometry"), QCoreApplication::translate("main", "geometry"))); parser.addOption(QCommandLineOption("maximized", QCoreApplication::translate("main", "Maximize the window on startup"))); parser.addOption(QCommandLineOption("fullscreen", QCoreApplication::translate("main", "Open the window in fullscreen on startup"))); parser.addPositionalArgument("file", QCoreApplication::translate("main", "Edit specified file(s)"), "[file...]"); parser.addPositionalArgument("...", "Additional arguments are fowarded to Neovim", "[-- ...]"); parser.addHelpOption(); int sep = app.arguments().indexOf("--"); QStringList neovimArgs; if (sep != -1) { QStringList args = app.arguments().mid(0, sep); neovimArgs += app.arguments().mid(sep+1); parser.process(args); } else { parser.process(app.arguments()); } if (parser.isSet("help")) { parser.showHelp(); } #ifdef Q_OS_MAC // In Mac OS X we can be running off a bundle in which case the user // shell environment variabls ($PATH, etc) are not set - try to load them loadLoginEnvironmen(); #endif NeovimQt::NeovimConnector *c; if (parser.isSet("embed")) { c = NeovimQt::NeovimConnector::fromStdinOut(); } else { if (parser.isSet("server")) { QString server = parser.value("server"); c = NeovimQt::NeovimConnector::connectToNeovim(server); } else { auto path = qgetenv("NVIM_QT_RUNTIME_PATH"); if (QFileInfo(path).isDir()) { neovimArgs.insert(0, "--cmd"); neovimArgs.insert(1, QString("set rtp+=%1") .arg(QString::fromLocal8Bit(path))); } #ifdef NVIM_QT_RUNTIME_PATH else if (QFileInfo(NVIM_QT_RUNTIME_PATH).isDir()) { neovimArgs.insert(0, "--cmd"); neovimArgs.insert(1, QString("set rtp+=%1") .arg(NVIM_QT_RUNTIME_PATH)); } else #endif { // Look for the runtime relative to the nvim-qt binary QDir d = QFileInfo(QCoreApplication::applicationDirPath()).dir(); #ifdef Q_OS_MAC // within the bundle at ../Resources/runtime d.cd("Resources"); d.cd("runtime"); #else // ../share/nvim-qt/runtime d.cd("share"); d.cd("nvim-qt"); d.cd("runtime"); #endif if (d.exists()) { neovimArgs.insert(0, "--cmd"); neovimArgs.insert(1, QString("set rtp+=%1") .arg(d.path())); } } // Pass positional file arguments to Neovim neovimArgs.append(parser.positionalArguments()); c = NeovimQt::NeovimConnector::spawn(neovimArgs); } } #ifdef NEOVIMQT_GUI_WIDGET NeovimQt::Shell *win = new NeovimQt::Shell(c); win->show(); if (parser.isSet("fullscreen")) { win->showFullScreen(); } else if (parser.isSet("maximized")) { win->showMaximized(); } else { win->show(); } #else NeovimQt::MainWindow *win = new NeovimQt::MainWindow(c); QObject::connect(&app, SIGNAL(openFilesTriggered(const QList<QUrl>)), win->shell(), SLOT(openFiles(const QList<QUrl>))); if (parser.isSet("fullscreen")) { win->delayedShow(NeovimQt::MainWindow::DelayedShow::FullScreen); } else if (parser.isSet("maximized")) { win->delayedShow(NeovimQt::MainWindow::DelayedShow::Maximized); } else { win->delayedShow(); } #endif return app.exec(); } <commit_msg>GUI: set termguicolors on spawn<commit_after>#include <QApplication> #include <QFontDatabase> #include <QtGlobal> #include <QFile> #include <QCommandLineParser> #include <QFileInfo> #include <QDir> #include "neovimconnector.h" #include "mainwindow.h" #include "app.h" /// A log handler for Qt messages, all messages are dumped into the file /// passed via the NVIM_QT_LOG variable. Some information is only available /// in debug builds (e.g. qDebug is only called in debug builds). /// /// In UNIX Qt prints messages to the console output, but in Windows this is /// the only way to get Qt's debug/warning messages. void logger(QtMsgType type, const QMessageLogContext& ctx, const QString& msg) { QFile logFile(qgetenv("NVIM_QT_LOG")); if (logFile.open(QIODevice::Append | QIODevice::Text)) { QTextStream stream(&logFile); stream << msg << "\n"; } } #ifdef Q_OS_MAC bool getLoginEnvironment(const QString& path) { QProcess proc; proc.start(path, {"-l", "-c", "env", "-i"}); if (!proc.waitForFinished()) { qDebug() << "Failed to execute shell to get environemnt" << path; return false; } QByteArray out = proc.readAllStandardOutput(); foreach(const QByteArray& item, out.split('\n')) { int index = item.indexOf('='); if (index > 0) { qputenv(item.mid(0, index), item.mid(index+1)); qDebug() << item.mid(0, index) << item.mid(index+1); } } return true; } void loadLoginEnvironmen() { QByteArray shellPath = qgetenv("SHELL"); if (!getLoginEnvironment(shellPath)) { getLoginEnvironment("/bin/bash"); } } #endif int main(int argc, char **argv) { NeovimQt::App app(argc, argv); app.setApplicationDisplayName("Neovim"); app.setWindowIcon(QIcon(":/neovim.png")); if (!qgetenv("NVIM_QT_LOG").isEmpty()) { qInstallMessageHandler(logger); } QCommandLineParser parser; parser.addOption(QCommandLineOption("embed", QCoreApplication::translate("main", "Communicate with Neovim over stdin/out"))); parser.addOption(QCommandLineOption("server", QCoreApplication::translate("main", "Connect to existing Neovim instance"), QCoreApplication::translate("main", "addr"))); parser.addOption(QCommandLineOption("geometry", QCoreApplication::translate("main", "Initial window geometry"), QCoreApplication::translate("main", "geometry"))); parser.addOption(QCommandLineOption("maximized", QCoreApplication::translate("main", "Maximize the window on startup"))); parser.addOption(QCommandLineOption("fullscreen", QCoreApplication::translate("main", "Open the window in fullscreen on startup"))); parser.addPositionalArgument("file", QCoreApplication::translate("main", "Edit specified file(s)"), "[file...]"); parser.addPositionalArgument("...", "Additional arguments are fowarded to Neovim", "[-- ...]"); parser.addHelpOption(); int sep = app.arguments().indexOf("--"); QStringList neovimArgs; neovimArgs << "--cmd"; neovimArgs << "set termguicolors"; if (sep != -1) { QStringList args = app.arguments().mid(0, sep); neovimArgs += app.arguments().mid(sep+1); parser.process(args); } else { parser.process(app.arguments()); } if (parser.isSet("help")) { parser.showHelp(); } #ifdef Q_OS_MAC // In Mac OS X we can be running off a bundle in which case the user // shell environment variabls ($PATH, etc) are not set - try to load them loadLoginEnvironmen(); #endif NeovimQt::NeovimConnector *c; if (parser.isSet("embed")) { c = NeovimQt::NeovimConnector::fromStdinOut(); } else { if (parser.isSet("server")) { QString server = parser.value("server"); c = NeovimQt::NeovimConnector::connectToNeovim(server); } else { auto path = qgetenv("NVIM_QT_RUNTIME_PATH"); if (QFileInfo(path).isDir()) { neovimArgs.insert(0, "--cmd"); neovimArgs.insert(1, QString("set rtp+=%1") .arg(QString::fromLocal8Bit(path))); } #ifdef NVIM_QT_RUNTIME_PATH else if (QFileInfo(NVIM_QT_RUNTIME_PATH).isDir()) { neovimArgs.insert(0, "--cmd"); neovimArgs.insert(1, QString("set rtp+=%1") .arg(NVIM_QT_RUNTIME_PATH)); } else #endif { // Look for the runtime relative to the nvim-qt binary QDir d = QFileInfo(QCoreApplication::applicationDirPath()).dir(); #ifdef Q_OS_MAC // within the bundle at ../Resources/runtime d.cd("Resources"); d.cd("runtime"); #else // ../share/nvim-qt/runtime d.cd("share"); d.cd("nvim-qt"); d.cd("runtime"); #endif if (d.exists()) { neovimArgs.insert(0, "--cmd"); neovimArgs.insert(1, QString("set rtp+=%1") .arg(d.path())); } } // Pass positional file arguments to Neovim neovimArgs.append(parser.positionalArguments()); c = NeovimQt::NeovimConnector::spawn(neovimArgs); } } #ifdef NEOVIMQT_GUI_WIDGET NeovimQt::Shell *win = new NeovimQt::Shell(c); win->show(); if (parser.isSet("fullscreen")) { win->showFullScreen(); } else if (parser.isSet("maximized")) { win->showMaximized(); } else { win->show(); } #else NeovimQt::MainWindow *win = new NeovimQt::MainWindow(c); QObject::connect(&app, SIGNAL(openFilesTriggered(const QList<QUrl>)), win->shell(), SLOT(openFiles(const QList<QUrl>))); if (parser.isSet("fullscreen")) { win->delayedShow(NeovimQt::MainWindow::DelayedShow::FullScreen); } else if (parser.isSet("maximized")) { win->delayedShow(NeovimQt::MainWindow::DelayedShow::Maximized); } else { win->delayedShow(); } #endif return app.exec(); } <|endoftext|>
<commit_before>#include "hardware.h" Pad Hardware::_pad; Stylus Hardware::_stylus; FrameBuffer* Hardware::_topBuffer = NULL; FrameBuffer* Hardware::_bottomBuffer = NULL; WoopsiGfx::Graphics* Hardware::_topGfx = NULL; WoopsiGfx::Graphics* Hardware::_bottomGfx = NULL; #ifdef USING_SDL SDL_Window* Hardware::_window = NULL; SDL_Renderer* Hardware::_renderer = NULL; SDL_Texture* Hardware::_texture = NULL; u16* Hardware::_topBitmap = NULL; u16* Hardware::_bottomBitmap = NULL; #else s32 Hardware::_topBackgroundBase = 0; #endif void Hardware::init() { #ifndef USING_SDL powerOn(POWER_ALL_2D); videoSetMode(MODE_5_2D | DISPLAY_BG3_ACTIVE); videoSetModeSub(MODE_5_2D | DISPLAY_BG3_ACTIVE); vramSetBankA(VRAM_A_MAIN_BG_0x06000000); vramSetBankB(VRAM_B_MAIN_BG_0x06020000); vramSetBankC(VRAM_C_SUB_BG); // Initialise backgrounds bgInit(3, BgType_Bmp16, BgSize_B16_256x256, 0, 0); bgInitSub(3, BgType_Bmp16, BgSize_B16_256x256, 0, 0); _topBuffer = new FrameBuffer((u16*)BG_BMP_RAM(6), (u16*)BG_BMP_RAM(0), SCREEN_WIDTH, SCREEN_HEIGHT); _bottomBuffer = new FrameBuffer((u16*)BG_BMP_RAM_SUB(0), SCREEN_WIDTH, SCREEN_HEIGHT); #else Uint32 initflags = SDL_INIT_VIDEO; // Initialize the SDL library if (SDL_Init(initflags) < 0) { fprintf(stderr, "Couldn't initialize SDL: %s\n", SDL_GetError()); exit(1); } // Set video mode _window = SDL_CreateWindow("Really Bad Eggs", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, SCREEN_WIDTH, SCREEN_HEIGHT * 2, 0); _renderer = SDL_CreateRenderer(_window, -1, 0); SDL_SetRenderDrawColor(_renderer, 0, 0, 0, 255); SDL_RenderClear(_renderer); SDL_RenderPresent(_renderer); _texture = SDL_CreateTexture(_renderer, SDL_PIXELFORMAT_ABGR1555, SDL_TEXTUREACCESS_STREAMING, SCREEN_WIDTH, SCREEN_HEIGHT * 2); _topBitmap = new u16[SCREEN_WIDTH * SCREEN_HEIGHT]; _bottomBitmap = new u16[SCREEN_WIDTH * SCREEN_HEIGHT]; _topBuffer = new FrameBuffer(_topBitmap, SCREEN_WIDTH, SCREEN_HEIGHT); _bottomBuffer = new FrameBuffer(_bottomBitmap, SCREEN_WIDTH, SCREEN_HEIGHT); #endif _topGfx = _topBuffer->newGraphics(); _bottomGfx = _bottomBuffer->newGraphics(); } void Hardware::shutdown() { delete _topGfx; delete _bottomGfx; delete _topBuffer; delete _bottomBuffer; #ifdef USING_SDL SDL_DestroyRenderer(_renderer); SDL_DestroyTexture(_texture); SDL_DestroyWindow(_window); delete _topBitmap; delete _bottomBitmap; #endif } void Hardware::waitForVBlank() { #ifndef USING_SDL swiWaitForVBlank(); _topBuffer->flipBuffer(); // Manually flip the background control register. There must be a better // way of doing this, but all documentation around double buffering is // several versions out of date and the example provided with libnds is // weird. _topBackgroundBase = _topBackgroundBase == 0 ? 6 : 0; REG_BG3CNT = BG_BMP16_256x256 | BG_BMP_BASE(_topBackgroundBase); #else SDL_Delay(15); SDL_Rect rect; rect.x = 0; rect.y = 0; rect.w = SCREEN_WIDTH; rect.h = SCREEN_HEIGHT; SDL_UpdateTexture(_texture, &rect, _topBitmap, SCREEN_WIDTH * sizeof(u16)); rect.y = SCREEN_HEIGHT; SDL_UpdateTexture(_texture, &rect, _bottomBitmap, SCREEN_WIDTH * sizeof(u16)); SDL_RenderClear(_renderer); SDL_RenderCopy(_renderer, _texture, NULL, NULL); SDL_RenderPresent(_renderer); // SDL event pump SDL_Event event; // Check for SDL quit while (SDL_PollEvent(&event)) { switch (event.type) { case SDL_QUIT: exit(0); return; case SDL_KEYDOWN: if (event.key.keysym.scancode == 53) { // Escape pressed exit(0); return; } break; } } #endif _pad.update(); _stylus.update(); } <commit_msg>Removed unnecessary SDL call.<commit_after>#include "hardware.h" Pad Hardware::_pad; Stylus Hardware::_stylus; FrameBuffer* Hardware::_topBuffer = NULL; FrameBuffer* Hardware::_bottomBuffer = NULL; WoopsiGfx::Graphics* Hardware::_topGfx = NULL; WoopsiGfx::Graphics* Hardware::_bottomGfx = NULL; #ifdef USING_SDL SDL_Window* Hardware::_window = NULL; SDL_Renderer* Hardware::_renderer = NULL; SDL_Texture* Hardware::_texture = NULL; u16* Hardware::_topBitmap = NULL; u16* Hardware::_bottomBitmap = NULL; #else s32 Hardware::_topBackgroundBase = 0; #endif void Hardware::init() { #ifndef USING_SDL powerOn(POWER_ALL_2D); videoSetMode(MODE_5_2D | DISPLAY_BG3_ACTIVE); videoSetModeSub(MODE_5_2D | DISPLAY_BG3_ACTIVE); vramSetBankA(VRAM_A_MAIN_BG_0x06000000); vramSetBankB(VRAM_B_MAIN_BG_0x06020000); vramSetBankC(VRAM_C_SUB_BG); // Initialise backgrounds bgInit(3, BgType_Bmp16, BgSize_B16_256x256, 0, 0); bgInitSub(3, BgType_Bmp16, BgSize_B16_256x256, 0, 0); _topBuffer = new FrameBuffer((u16*)BG_BMP_RAM(6), (u16*)BG_BMP_RAM(0), SCREEN_WIDTH, SCREEN_HEIGHT); _bottomBuffer = new FrameBuffer((u16*)BG_BMP_RAM_SUB(0), SCREEN_WIDTH, SCREEN_HEIGHT); #else Uint32 initflags = SDL_INIT_VIDEO; // Initialize the SDL library if (SDL_Init(initflags) < 0) { fprintf(stderr, "Couldn't initialize SDL: %s\n", SDL_GetError()); exit(1); } // Set video mode _window = SDL_CreateWindow("Really Bad Eggs", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, SCREEN_WIDTH, SCREEN_HEIGHT * 2, 0); _renderer = SDL_CreateRenderer(_window, -1, 0); SDL_SetRenderDrawColor(_renderer, 0, 0, 0, 255); SDL_RenderClear(_renderer); SDL_RenderPresent(_renderer); _texture = SDL_CreateTexture(_renderer, SDL_PIXELFORMAT_ABGR1555, SDL_TEXTUREACCESS_STREAMING, SCREEN_WIDTH, SCREEN_HEIGHT * 2); _topBitmap = new u16[SCREEN_WIDTH * SCREEN_HEIGHT]; _bottomBitmap = new u16[SCREEN_WIDTH * SCREEN_HEIGHT]; _topBuffer = new FrameBuffer(_topBitmap, SCREEN_WIDTH, SCREEN_HEIGHT); _bottomBuffer = new FrameBuffer(_bottomBitmap, SCREEN_WIDTH, SCREEN_HEIGHT); #endif _topGfx = _topBuffer->newGraphics(); _bottomGfx = _bottomBuffer->newGraphics(); } void Hardware::shutdown() { delete _topGfx; delete _bottomGfx; delete _topBuffer; delete _bottomBuffer; #ifdef USING_SDL SDL_DestroyRenderer(_renderer); SDL_DestroyTexture(_texture); SDL_DestroyWindow(_window); delete _topBitmap; delete _bottomBitmap; #endif } void Hardware::waitForVBlank() { #ifndef USING_SDL swiWaitForVBlank(); _topBuffer->flipBuffer(); // Manually flip the background control register. There must be a better // way of doing this, but all documentation around double buffering is // several versions out of date and the example provided with libnds is // weird. _topBackgroundBase = _topBackgroundBase == 0 ? 6 : 0; REG_BG3CNT = BG_BMP16_256x256 | BG_BMP_BASE(_topBackgroundBase); #else SDL_Delay(15); SDL_Rect rect; rect.x = 0; rect.y = 0; rect.w = SCREEN_WIDTH; rect.h = SCREEN_HEIGHT; SDL_UpdateTexture(_texture, &rect, _topBitmap, SCREEN_WIDTH * sizeof(u16)); rect.y = SCREEN_HEIGHT; SDL_UpdateTexture(_texture, &rect, _bottomBitmap, SCREEN_WIDTH * sizeof(u16)); SDL_RenderCopy(_renderer, _texture, NULL, NULL); SDL_RenderPresent(_renderer); // SDL event pump SDL_Event event; // Check for SDL quit while (SDL_PollEvent(&event)) { switch (event.type) { case SDL_QUIT: exit(0); return; case SDL_KEYDOWN: if (event.key.keysym.scancode == 53) { // Escape pressed exit(0); return; } break; } } #endif _pad.update(); _stylus.update(); } <|endoftext|>
<commit_before>/* -------------------------------------------------------------------------- */ /* Copyright 2002-2009, Distributed Systems Architecture Group, Universidad */ /* Complutense de Madrid (dsa-research.org) */ /* */ /* 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 <limits.h> #include <string.h> #include <iostream> #include <sstream> #include "Host.h" /* ************************************************************************** */ /* Host :: Constructor/Destructor */ /* ************************************************************************** */ Host::Host( int id, string _hostname, string _im_mad_name, string _vmm_mad_name, string _tm_mad_name, bool _managed): PoolObjectSQL(id), hostname(_hostname), state(INIT), im_mad_name(_im_mad_name), vmm_mad_name(_vmm_mad_name), tm_mad_name(_tm_mad_name), last_monitored(time(0)), managed(_managed), host_template(id), host_share(id){}; Host::~Host(){}; /* ************************************************************************** */ /* Host :: Database Access Functions */ /* ************************************************************************** */ const char * Host::table = "host_pool"; const char * Host::db_names = "(oid,host_name,state,im_mad,vm_mad," "tm_mad,last_mon_time,managed)"; const char * Host::db_bootstrap = "CREATE TABLE host_pool (" "oid INTEGER PRIMARY KEY,host_name TEXT,state INTEGER," "im_mad TEXT,vm_mad TEXT,tm_mad TEXT,last_mon_time INTEGER," "managed INTEGER)"; /* -------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------- */ int Host::unmarshall(int num, char **names, char ** values) { if ((values[OID] == 0) || (values[HOST_NAME] == 0) || (values[STATE] == 0) || (values[IM_MAD] == 0) || (values[VM_MAD] == 0) || (values[TM_MAD] == 0) || (values[LAST_MON_TIME] == 0) || (values[MANAGED] == 0) || (num != LIMIT )) { return -1; } oid = atoi(values[OID]); hostname = values[HOST_NAME]; state = static_cast<HostState>(atoi(values[STATE])); im_mad_name = values[IM_MAD]; vmm_mad_name = values[VM_MAD]; tm_mad_name = values[TM_MAD]; last_monitored = static_cast<time_t>(atoi(values[LAST_MON_TIME])); managed = atoi(values[MANAGED]) == 1?true:false; host_template.id = oid; host_share.hsid = oid; return 0; } /* -------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------- */ extern "C" int host_select_cb ( void * _host, int num, char ** values, char ** names) { Host * host; host = static_cast<Host *>(_host); if (host == 0) { return -1; } return host->unmarshall(num,names,values); }; /* -------------------------------------------------------------------------- */ int Host::select(SqliteDB *db) { ostringstream oss; int rc; int boid; oss << "SELECT * FROM " << table << " WHERE oid = " << oid; boid = oid; oid = -1; rc = db->exec(oss, host_select_cb, (void *) this); if ((rc != 0) || (oid != boid )) { return -1; } // Get the template rc = host_template.select(db); if ( rc != 0 ) { return -1; } // Select the host shares from the DB rc = host_share.select(db); if ( rc != 0 ) { return rc; } return 0; } /* -------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------- */ int Host::insert(SqliteDB *db) { int rc; map<int,HostShare *>::iterator iter; // Set up the template ID, to insert it if ( host_template.id == -1 ) { host_template.id = oid; } // Set up the share ID, to insert it if ( host_share.hsid == -1 ) { host_share.hsid = oid; } //Insert the Host and its template rc = update(db); if ( rc != 0 ) { return rc; } return 0; } /* -------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------- */ int Host::update(SqliteDB *db) { ostringstream oss; int rc; int managed_i = managed?1:0; char * sql_hostname; char * sql_im_mad_name; char * sql_tm_mad_name; char * sql_vmm_mad_name; //Update template. rc = host_template.update(db); if ( rc != 0 ) { return rc; } // Let's get the HostShares before the host rc = host_share.update(db); if ( rc != 0 ) { return rc; } sql_hostname = sqlite3_mprintf("%q",hostname.c_str()); if ( sql_hostname == 0 ) { goto error_hostname; } sql_im_mad_name = sqlite3_mprintf("%q",im_mad_name.c_str()); if ( sql_im_mad_name == 0 ) { goto error_im; } sql_tm_mad_name = sqlite3_mprintf("%q",tm_mad_name.c_str()); if ( sql_tm_mad_name == 0 ) { goto error_tm; } sql_vmm_mad_name = sqlite3_mprintf("%q",vmm_mad_name.c_str()); if ( sql_vmm_mad_name == 0 ) { goto error_vmm; } // Construct the SQL statement to Insert or Replace (effectively, update) oss << "INSERT OR REPLACE INTO " << table << " "<< db_names <<" VALUES ("<< oid << "," << "'" << sql_hostname << "'," << state << "," << "'" << sql_im_mad_name << "'," << "'" << sql_vmm_mad_name << "'," << "'" << sql_tm_mad_name << "'," << last_monitored << "," << managed_i << ")"; rc = db->exec(oss); sqlite3_free(sql_hostname); sqlite3_free(sql_im_mad_name); sqlite3_free(sql_im_mad_name); sqlite3_free(sql_vmm_mad_name); return rc; error_vmm: sqlite3_free(sql_tm_mad_name); error_tm: sqlite3_free(sql_im_mad_name); error_im: sqlite3_free(sql_hostname); error_hostname: return -1; } /* -------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------- */ int Host::drop(SqliteDB * db) { ostringstream oss; map<int,HostShare *>::iterator iter; // First, drop the template host_template.drop(db); // Second, drop the host_shares host_share.drop(db); // Third, drop the host itself oss << "DELETE FROM " << table << " WHERE oid=" << oid; return db->exec(oss); } /* -------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------- */ int Host::update_info(string &parse_str) { char * error_msg; int rc; // If we have a default rc = host_template.parse(parse_str, &error_msg); if ( rc != 0 ) { /* Nebula::log("ONE", Log::ERROR, error_msg); */ free(error_msg); return -1; } get_template_attribute("TOTALCPU",host_share.max_cpu); get_template_attribute("TOTALMEMORY",host_share.max_mem); return 0; } /* ************************************************************************** */ /* Host :: Misc */ /* ************************************************************************** */ ostream& operator<<(ostream& os, Host& host) { os << "HID = " << host.oid << endl; os << "HOSTNAME = " << host.hostname << endl; os << "IM MAD = " << host.im_mad_name << endl; os << "VMM MAD = " << host.vmm_mad_name << endl; os << "TM MAD = " << host.tm_mad_name << endl; os << "MANAGED = " << host.managed << endl; os << "ATTRIBUTES" << endl << host.host_template<< endl; os << "HOST SHARES" << endl << host.host_share <<endl; return os; }; /* ************************************************************************** */ /* Host :: Parse functions to compute rank and evaluate requirements */ /* ************************************************************************** */ pthread_mutex_t Host::lex_mutex = PTHREAD_MUTEX_INITIALIZER; extern "C" { typedef struct yy_buffer_state * YY_BUFFER_STATE; int host_requirements_parse(Host * host, bool& result, char ** errmsg); int host_rank_parse(Host * host, int& result, char ** errmsg); int host_lex_destroy(); YY_BUFFER_STATE host__scan_string(const char * str); void host__delete_buffer(YY_BUFFER_STATE); } /* -------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------- */ int Host::match(const string& requirements, bool& result, char **errmsg) { YY_BUFFER_STATE str_buffer = 0; const char * str; int rc; pthread_mutex_lock(&lex_mutex); *errmsg = 0; str = requirements.c_str(); str_buffer = host__scan_string(str); if (str_buffer == 0) { goto error_yy; } rc = host_requirements_parse(this,result,errmsg); host__delete_buffer(str_buffer); host_lex_destroy(); pthread_mutex_unlock(&lex_mutex); return rc; error_yy: *errmsg=strdup("Error setting scan buffer"); pthread_mutex_unlock(&lex_mutex); return -1; } /* -------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------- */ int Host::rank(const string& rank, int& result, char **errmsg) { YY_BUFFER_STATE str_buffer = 0; const char * str; int rc; pthread_mutex_lock(&lex_mutex); *errmsg = 0; str = rank.c_str(); str_buffer = host__scan_string(str); if (str_buffer == 0) { goto error_yy; } rc = host_rank_parse(this,result,errmsg); host__delete_buffer(str_buffer); host_lex_destroy(); pthread_mutex_unlock(&lex_mutex); return rc; error_yy: *errmsg=strdup("Error setting scan buffer"); pthread_mutex_unlock(&lex_mutex); return -1; } /* -------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------- */ <commit_msg>fix minor bug <commit_after>/* -------------------------------------------------------------------------- */ /* Copyright 2002-2009, Distributed Systems Architecture Group, Universidad */ /* Complutense de Madrid (dsa-research.org) */ /* */ /* 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 <limits.h> #include <string.h> #include <iostream> #include <sstream> #include "Host.h" /* ************************************************************************** */ /* Host :: Constructor/Destructor */ /* ************************************************************************** */ Host::Host( int id, string _hostname, string _im_mad_name, string _vmm_mad_name, string _tm_mad_name, bool _managed): PoolObjectSQL(id), hostname(_hostname), state(INIT), im_mad_name(_im_mad_name), vmm_mad_name(_vmm_mad_name), tm_mad_name(_tm_mad_name), last_monitored(time(0)), managed(_managed), host_template(id), host_share(id){}; Host::~Host(){}; /* ************************************************************************** */ /* Host :: Database Access Functions */ /* ************************************************************************** */ const char * Host::table = "host_pool"; const char * Host::db_names = "(oid,host_name,state,im_mad,vm_mad," "tm_mad,last_mon_time,managed)"; const char * Host::db_bootstrap = "CREATE TABLE host_pool (" "oid INTEGER PRIMARY KEY,host_name TEXT,state INTEGER," "im_mad TEXT,vm_mad TEXT,tm_mad TEXT,last_mon_time INTEGER," "managed INTEGER)"; /* -------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------- */ int Host::unmarshall(int num, char **names, char ** values) { if ((values[OID] == 0) || (values[HOST_NAME] == 0) || (values[STATE] == 0) || (values[IM_MAD] == 0) || (values[VM_MAD] == 0) || (values[TM_MAD] == 0) || (values[LAST_MON_TIME] == 0) || (values[MANAGED] == 0) || (num != LIMIT )) { return -1; } oid = atoi(values[OID]); hostname = values[HOST_NAME]; state = static_cast<HostState>(atoi(values[STATE])); im_mad_name = values[IM_MAD]; vmm_mad_name = values[VM_MAD]; tm_mad_name = values[TM_MAD]; last_monitored = static_cast<time_t>(atoi(values[LAST_MON_TIME])); managed = atoi(values[MANAGED]) == 1?true:false; host_template.id = oid; host_share.hsid = oid; return 0; } /* -------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------- */ extern "C" int host_select_cb ( void * _host, int num, char ** values, char ** names) { Host * host; host = static_cast<Host *>(_host); if (host == 0) { return -1; } return host->unmarshall(num,names,values); }; /* -------------------------------------------------------------------------- */ int Host::select(SqliteDB *db) { ostringstream oss; int rc; int boid; oss << "SELECT * FROM " << table << " WHERE oid = " << oid; boid = oid; oid = -1; rc = db->exec(oss, host_select_cb, (void *) this); if ((rc != 0) || (oid != boid )) { return -1; } // Get the template rc = host_template.select(db); if ( rc != 0 ) { return -1; } // Select the host shares from the DB rc = host_share.select(db); if ( rc != 0 ) { return rc; } return 0; } /* -------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------- */ int Host::insert(SqliteDB *db) { int rc; map<int,HostShare *>::iterator iter; // Set up the template ID, to insert it if ( host_template.id == -1 ) { host_template.id = oid; } // Set up the share ID, to insert it if ( host_share.hsid == -1 ) { host_share.hsid = oid; } //Insert the Host and its template rc = update(db); if ( rc != 0 ) { return rc; } return 0; } /* -------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------- */ int Host::update(SqliteDB *db) { ostringstream oss; int rc; int managed_i = managed?1:0; char * sql_hostname; char * sql_im_mad_name; char * sql_tm_mad_name; char * sql_vmm_mad_name; //Update template. rc = host_template.update(db); if ( rc != 0 ) { return rc; } // Let's get the HostShares before the host rc = host_share.update(db); if ( rc != 0 ) { return rc; } sql_hostname = sqlite3_mprintf("%q",hostname.c_str()); if ( sql_hostname == 0 ) { goto error_hostname; } sql_im_mad_name = sqlite3_mprintf("%q",im_mad_name.c_str()); if ( sql_im_mad_name == 0 ) { goto error_im; } sql_tm_mad_name = sqlite3_mprintf("%q",tm_mad_name.c_str()); if ( sql_tm_mad_name == 0 ) { goto error_tm; } sql_vmm_mad_name = sqlite3_mprintf("%q",vmm_mad_name.c_str()); if ( sql_vmm_mad_name == 0 ) { goto error_vmm; } // Construct the SQL statement to Insert or Replace (effectively, update) oss << "INSERT OR REPLACE INTO " << table << " "<< db_names <<" VALUES ("<< oid << "," << "'" << sql_hostname << "'," << state << "," << "'" << sql_im_mad_name << "'," << "'" << sql_vmm_mad_name << "'," << "'" << sql_tm_mad_name << "'," << last_monitored << "," << managed_i << ")"; rc = db->exec(oss); sqlite3_free(sql_hostname); sqlite3_free(sql_im_mad_name); sqlite3_free(sql_tm_mad_name); sqlite3_free(sql_vmm_mad_name); return rc; error_vmm: sqlite3_free(sql_tm_mad_name); error_tm: sqlite3_free(sql_im_mad_name); error_im: sqlite3_free(sql_hostname); error_hostname: return -1; } /* -------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------- */ int Host::drop(SqliteDB * db) { ostringstream oss; map<int,HostShare *>::iterator iter; // First, drop the template host_template.drop(db); // Second, drop the host_shares host_share.drop(db); // Third, drop the host itself oss << "DELETE FROM " << table << " WHERE oid=" << oid; return db->exec(oss); } /* -------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------- */ int Host::update_info(string &parse_str) { char * error_msg; int rc; // If we have a default rc = host_template.parse(parse_str, &error_msg); if ( rc != 0 ) { /* Nebula::log("ONE", Log::ERROR, error_msg); */ free(error_msg); return -1; } get_template_attribute("TOTALCPU",host_share.max_cpu); get_template_attribute("TOTALMEMORY",host_share.max_mem); return 0; } /* ************************************************************************** */ /* Host :: Misc */ /* ************************************************************************** */ ostream& operator<<(ostream& os, Host& host) { os << "HID = " << host.oid << endl; os << "HOSTNAME = " << host.hostname << endl; os << "IM MAD = " << host.im_mad_name << endl; os << "VMM MAD = " << host.vmm_mad_name << endl; os << "TM MAD = " << host.tm_mad_name << endl; os << "MANAGED = " << host.managed << endl; os << "ATTRIBUTES" << endl << host.host_template<< endl; os << "HOST SHARES" << endl << host.host_share <<endl; return os; }; /* ************************************************************************** */ /* Host :: Parse functions to compute rank and evaluate requirements */ /* ************************************************************************** */ pthread_mutex_t Host::lex_mutex = PTHREAD_MUTEX_INITIALIZER; extern "C" { typedef struct yy_buffer_state * YY_BUFFER_STATE; int host_requirements_parse(Host * host, bool& result, char ** errmsg); int host_rank_parse(Host * host, int& result, char ** errmsg); int host_lex_destroy(); YY_BUFFER_STATE host__scan_string(const char * str); void host__delete_buffer(YY_BUFFER_STATE); } /* -------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------- */ int Host::match(const string& requirements, bool& result, char **errmsg) { YY_BUFFER_STATE str_buffer = 0; const char * str; int rc; pthread_mutex_lock(&lex_mutex); *errmsg = 0; str = requirements.c_str(); str_buffer = host__scan_string(str); if (str_buffer == 0) { goto error_yy; } rc = host_requirements_parse(this,result,errmsg); host__delete_buffer(str_buffer); host_lex_destroy(); pthread_mutex_unlock(&lex_mutex); return rc; error_yy: *errmsg=strdup("Error setting scan buffer"); pthread_mutex_unlock(&lex_mutex); return -1; } /* -------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------- */ int Host::rank(const string& rank, int& result, char **errmsg) { YY_BUFFER_STATE str_buffer = 0; const char * str; int rc; pthread_mutex_lock(&lex_mutex); *errmsg = 0; str = rank.c_str(); str_buffer = host__scan_string(str); if (str_buffer == 0) { goto error_yy; } rc = host_rank_parse(this,result,errmsg); host__delete_buffer(str_buffer); host_lex_destroy(); pthread_mutex_unlock(&lex_mutex); return rc; error_yy: *errmsg=strdup("Error setting scan buffer"); pthread_mutex_unlock(&lex_mutex); return -1; } /* -------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------- */ <|endoftext|>
<commit_before>/* * Copyright 2014 Real Logic 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. */ #include <util/MemoryMappedFile.h> #include <concurrent/CountersManager.h> #include <util/CommandOptionParser.h> #include <iostream> #include <atomic> #include <thread> #include <signal.h> #include <Context.h> #define __STDC_FORMAT_MACROS #include <inttypes.h> using namespace aeron; using namespace aeron::common; using namespace aeron::common::util; using namespace aeron::common::concurrent; using namespace std::chrono; std::atomic<bool> running (true); void sigIntHandler (int param) { running = false; } static const char optHelp = 'h'; static const char optPath = 'p'; static const char optPeriod = 'u'; struct Settings { std::string basePath = Context::defaultAeronPath(); int updateIntervalms = 1000; }; Settings parseCmdLine(CommandOptionParser& cp, int argc, char** argv) { cp.parse(argc, argv); if (cp.getOption(optHelp).isPresent()) { cp.displayOptionsHelp(std::cout); exit(0); } Settings s; s.basePath = cp.getOption(optPath).getParam(0, s.basePath); s.updateIntervalms = cp.getOption(optPeriod).getParamAsInt(0, 1, 1000000, s.updateIntervalms); return s; } int main (int argc, char** argv) { CommandOptionParser cp; cp.addOption(CommandOption (optHelp, 0, 0, " Displays help information.")); cp.addOption(CommandOption (optPath, 1, 1, "basePath Base Path to shared memory. Default: " + Context::defaultAeronPath())); cp.addOption(CommandOption (optPeriod, 1, 1, "update period Update period in millseconds. Default: 1000ms")); signal (SIGINT, sigIntHandler); try { Settings settings = parseCmdLine(cp, argc, argv); MemoryMappedFile::ptr_t cncFile = MemoryMappedFile::mapExisting((settings.basePath + "/conductor/" + CncFileDescriptor::CNC_FILE).c_str()); AtomicBuffer labelsBuffer = CncFileDescriptor::createCounterLabelsBuffer(cncFile); AtomicBuffer valuesBuffer = CncFileDescriptor::createCounterValuesBuffer(cncFile); CountersManager counters(labelsBuffer, valuesBuffer); while(running) { time_t rawtime; char currentTime[80]; ::time(&rawtime); ::strftime(currentTime, sizeof(currentTime) - 1, "%H:%M:%S", localtime(&rawtime)); ::printf("\033[H\033[2J"); ::printf("%s - Aeron Stat\n", currentTime); ::printf("===========================\n"); ::setlocale(LC_NUMERIC, ""); counters.forEach([&](int id, const std::string l) { std::int64_t value = valuesBuffer.getInt64Volatile(counters.counterOffset(id)); ::printf("%3d: %'20" PRId64 " - %s\n", id, value, l.c_str()); }); std::this_thread::sleep_for(std::chrono::milliseconds(settings.updateIntervalms)); } std::cout << "Exiting..." << std::endl; } catch (CommandOptionException& e) { std::cerr << "ERROR: " << e.what() << std::endl << std::endl; cp.displayOptionsHelp(std::cerr); return -1; } catch (SourcedException& e) { std::cerr << "FAILED: " << e.what() << " : " << e.where() << std::endl; return -1; } catch (std::exception& e) { std::cerr << "FAILED: " << e.what() << " : " << std::endl; return -1; } return 0; }<commit_msg>[C++]: more standards based changes<commit_after>/* * Copyright 2014 Real Logic 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. */ #include <util/MemoryMappedFile.h> #include <concurrent/CountersManager.h> #include <util/CommandOptionParser.h> #include <iostream> #include <atomic> #include <thread> #include <signal.h> #include <Context.h> #define __STDC_FORMAT_MACROS #include <inttypes.h> using namespace aeron; using namespace aeron::common; using namespace aeron::common::util; using namespace aeron::common::concurrent; using namespace std::chrono; std::atomic<bool> running (true); void sigIntHandler (int param) { running = false; } static const char optHelp = 'h'; static const char optPath = 'p'; static const char optPeriod = 'u'; struct Settings { std::string basePath = Context::defaultAeronPath(); int updateIntervalms = 1000; }; Settings parseCmdLine(CommandOptionParser& cp, int argc, char** argv) { cp.parse(argc, argv); if (cp.getOption(optHelp).isPresent()) { cp.displayOptionsHelp(std::cout); exit(0); } Settings s; s.basePath = cp.getOption(optPath).getParam(0, s.basePath); s.updateIntervalms = cp.getOption(optPeriod).getParamAsInt(0, 1, 1000000, s.updateIntervalms); return s; } int main (int argc, char** argv) { CommandOptionParser cp; cp.addOption(CommandOption (optHelp, 0, 0, " Displays help information.")); cp.addOption(CommandOption (optPath, 1, 1, "basePath Base Path to shared memory. Default: " + Context::defaultAeronPath())); cp.addOption(CommandOption (optPeriod, 1, 1, "update period Update period in millseconds. Default: 1000ms")); signal (SIGINT, sigIntHandler); try { Settings settings = parseCmdLine(cp, argc, argv); MemoryMappedFile::ptr_t cncFile = MemoryMappedFile::mapExisting((settings.basePath + "/conductor/" + CncFileDescriptor::CNC_FILE).c_str()); AtomicBuffer labelsBuffer = CncFileDescriptor::createCounterLabelsBuffer(cncFile); AtomicBuffer valuesBuffer = CncFileDescriptor::createCounterValuesBuffer(cncFile); CountersManager counters(labelsBuffer, valuesBuffer); while(running) { time_t rawtime; char currentTime[80]; std::time(&rawtime); std::strftime(currentTime, sizeof(currentTime) - 1, "%H:%M:%S", localtime(&rawtime)); std::printf("\033[H\033[2J"); std::printf("%s - Aeron Stat\n", currentTime); std::printf("===========================\n"); ::setlocale(LC_NUMERIC, ""); counters.forEach([&](int id, const std::string l) { std::int64_t value = valuesBuffer.getInt64Volatile(counters.counterOffset(id)); std::printf("%3d: %'20" PRId64 " - %s\n", id, value, l.c_str()); }); std::this_thread::sleep_for(std::chrono::milliseconds(settings.updateIntervalms)); } std::cout << "Exiting..." << std::endl; } catch (CommandOptionException& e) { std::cerr << "ERROR: " << e.what() << std::endl << std::endl; cp.displayOptionsHelp(std::cerr); return -1; } catch (SourcedException& e) { std::cerr << "FAILED: " << e.what() << " : " << e.where() << std::endl; return -1; } catch (std::exception& e) { std::cerr << "FAILED: " << e.what() << " : " << std::endl; return -1; } return 0; }<|endoftext|>
<commit_before>#include <stdio.h> #include <stdlib.h> #include "App.h" #include <Directory.h> #include <NodeMonitor.h> #include <Entry.h> #include <Path.h> #include <String.h> #include <File.h> /* * Runs a command in the terminal, given the string you'd type */ BString* run_script(const char *cmd) { char buf[BUFSIZ]; FILE *ptr; BString *output = new BString; if ((ptr = popen(cmd, "r")) != NULL) while (fgets(buf, BUFSIZ, ptr) != NULL) output->Append(buf); (void) pclose(ptr); return output; } /* enum { DELETE_EVERYTHING; CREATE_FOLDER; CREATE_FILE; DELETE_THIS; } */ int parse_command(const char* command) { if(command[0] == 'R' && command[1] == 'E' && command[2] == 'S' && command[3] == 'E' && command[4] == 'T') { printf("Burn Everything. 8D\n"); } else { printf("Something more specific.\n"); } return 0; } /* * Sets up the Node Monitoring for Dropbox folder and contents * and creates data structure for determining which files are deleted or edited */ App::App(void) : BApplication("application/x-vnd.lh-MyDropboxClient") { //ask Dropbox for deltas! BString *delta_commands = run_script("python db_delta.py"); (void) parse_command(delta_commands->String()); //start watching ~/Dropbox folder contents (create, delete, move) BDirectory dir("/boot/home/Dropbox"); //don't use ~ here node_ref nref; status_t err; if(dir.InitCheck() == B_OK){ dir.GetNodeRef(&nref); err = watch_node(&nref, B_WATCH_DIRECTORY, BMessenger(this)); if(err != B_OK) printf("Watch Node: Not OK\n"); } // record each file in the folder so that we know the name on deletion BEntry *entry = new BEntry; status_t err2; err = dir.GetNextEntry(entry); BPath *path; BFile *file; while(err == B_OK) //loop over files { file = new BFile(entry, B_READ_ONLY); this->tracked_files.AddItem((void*)(file)); //add file to my list path = new BPath; entry->GetPath(path); printf("tracking: %s\n",path->Path()); this->tracked_filepaths.AddItem((void*)path); err2 = entry->GetNodeRef(&nref); if(err2 == B_OK) { err2 = watch_node(&nref, B_WATCH_STAT, be_app_messenger); //watch for edits if(err2 != B_OK) printf("Watch file Node: Not OK\n"); } entry = new BEntry; err = dir.GetNextEntry(entry); } //delete that last BEntry... } /* * Given a local file path, * call the script to delete the corresponding Dropbox file */ void delete_file_on_dropbox(const char * filepath) { printf("Telling Dropbox to Delete\n"); BString s, dbfp; s = BString(filepath); s.RemoveFirst("/boot/home/Dropbox"); dbfp << "python db_rm.py " << s; printf("%s\n",dbfp.String()); run_script(dbfp); } /* * Convert a local absolute filepath to a Dropbox one * by removing the <path to Dropbox> from the beginning */ BString local_to_db_filepath(const char * local_path) { BString s; s = BString(local_path); s.RemoveFirst("/boot/home/Dropbox/"); return s; } /* * Given the local file path of a new file, * run the script to upload it to Dropbox */ void add_file_to_dropbox(const char * filepath) { BString s, dbfp; dbfp = local_to_db_filepath(filepath); s << "python db_put.py " << BString(filepath) << " " << dbfp; printf("local filepath:%s\n",filepath); printf("dropbox filepath:%s\n",dbfp.String()); run_script(s.String()); } /* * Given the local file path of a new folder, * run the script to mkdir on Dropbox */ void add_folder_to_dropbox(const char * filepath) { BString s; s << "python db_mkdir.py " << local_to_db_filepath(filepath); printf("local filepath: %s\n", filepath); printf("db filepath: %s\n", local_to_db_filepath(filepath).String()); run_script(s.String()); } /* * TODO * Given a "file/folder moved" message, * figure out whether to call add or delete * and with what file path * and then call add/delete. */ void moved_file(BMessage *msg) { //is this file being move into or out of ~/Dropbox? run_script("python db_ls.py"); } /* * Given a local file path, * update the corresponding file on Dropbox */ void update_file_in_dropbox(const char * filepath) { printf("Putting %s to Dropbox.\n", filepath); add_file_to_dropbox(filepath); //just put it? } /* * Message Handling Function * If it's a node monitor message, * then figure out what to do based on it. * Otherwise, let BApplication handle it. */ void App::MessageReceived(BMessage *msg) { switch(msg->what) { case B_NODE_MONITOR: { printf("Received Node Monitor Alert\n"); status_t err; int32 opcode; err = msg->FindInt32("opcode",&opcode); if(err == B_OK) { printf("what:%d\topcode:%d\n",msg->what, opcode); switch(opcode) { case B_ENTRY_CREATED: { printf("NEW FILE\n"); entry_ref ref; BPath path; const char * name; // unpack the message msg->FindInt32("device",&ref.device); msg->FindInt64("directory",&ref.directory); msg->FindString("name",&name); printf("name:%s\n",name); ref.set_name(name); BEntry new_file = BEntry(&ref); // add the new file to Dropbox new_file.GetPath(&path); add_file_to_dropbox(path.Path()); // add the new file to global tracking lists BFile *file = new BFile(&new_file, B_READ_ONLY); this->tracked_files.AddItem((void*)file); BPath *path2 = new BPath; new_file.GetPath(path2); this->tracked_filepaths.AddItem((void*)path2); // listen for EDIT alerts on the new file node_ref nref; err = new_file.GetNodeRef(&nref); if(err == B_OK) { err = watch_node(&nref, B_WATCH_STAT, be_app_messenger); if(err != B_OK) printf("Watch new file %s: Not Ok.\n", path2->Path()); } break; } case B_ENTRY_MOVED: { printf("MOVED FILE\n"); moved_file(msg); break; } case B_ENTRY_REMOVED: { printf("DELETED FILE\n"); node_ref nref, cref; msg->FindInt32("device",&nref.device); msg->FindInt64("node",&nref.node); BFile *filePtr; int32 ktr = 0; int32 limit = this->tracked_files.CountItems(); printf("About to loop %d times\n", limit); while((filePtr = (BFile*)this->tracked_files.ItemAt(ktr))&&(ktr<limit)) { printf("In loop.\n"); filePtr->GetNodeRef(&cref); printf("GotNodeRef\n"); if(nref == cref) { printf("Deleting it\n"); BPath *path = (BPath*)this->tracked_filepaths.ItemAt(ktr); printf("%s\n",path->Path()); delete_file_on_dropbox(path->Path()); this->tracked_files.RemoveItem(ktr); this->tracked_filepaths.RemoveItem(ktr); break; //break out of loop } ktr++; } break; } case B_STAT_CHANGED: { printf("EDITED FILE\n"); node_ref nref1,nref2; msg->FindInt32("device",&nref1.device); msg->FindInt64("node",&nref1.node); BFile * filePtr; int32 ktr = 0; while((filePtr = (BFile *)this->tracked_files.ItemAt(ktr++))) { filePtr->GetNodeRef(&nref2); if(nref1 == nref2) { BPath *path; path = (BPath*)this->tracked_filepaths.ItemAt(ktr-1); update_file_in_dropbox(path->Path()); break; } } break; } default: { printf("default case opcode...\n"); } } } break; } default: { printf("default msg\n"); BApplication::MessageReceived(msg); break; } } } int main(void) { //set up application (watch Dropbox folder & contents) App *app = new App(); //start the application app->Run(); //clean up now that we're shutting down delete app; return 0; } <commit_msg>grab just the first line of the commands<commit_after>#include <stdio.h> #include <stdlib.h> #include "App.h" #include <Directory.h> #include <NodeMonitor.h> #include <Entry.h> #include <Path.h> #include <String.h> #include <File.h> /* * Runs a command in the terminal, given the string you'd type */ BString* run_script(const char *cmd) { char buf[BUFSIZ]; FILE *ptr; BString *output = new BString; if ((ptr = popen(cmd, "r")) != NULL) while (fgets(buf, BUFSIZ, ptr) != NULL) output->Append(buf); (void) pclose(ptr); return output; } /* enum { DELETE_EVERYTHING; CREATE_FOLDER; CREATE_FILE; DELETE_THIS; } */ int parse_command(const char* command) { if(command[0] == 'R' && command[1] == 'E' && command[2] == 'S' && command[3] == 'E' && command[4] == 'T') { printf("Burn Everything. 8D\n"); } else { printf("Something more specific.\n"); } return 0; } /* * Sets up the Node Monitoring for Dropbox folder and contents * and creates data structure for determining which files are deleted or edited */ App::App(void) : BApplication("application/x-vnd.lh-MyDropboxClient") { //ask Dropbox for deltas! BString *delta_commands = run_script("python db_delta.py"); int32 index = delta_commands->FindFirst('\n'); BString line; delta_commands->MoveInto(line,0,index); (void) parse_command(line.String()); //start watching ~/Dropbox folder contents (create, delete, move) BDirectory dir("/boot/home/Dropbox"); //don't use ~ here node_ref nref; status_t err; if(dir.InitCheck() == B_OK){ dir.GetNodeRef(&nref); err = watch_node(&nref, B_WATCH_DIRECTORY, BMessenger(this)); if(err != B_OK) printf("Watch Node: Not OK\n"); } // record each file in the folder so that we know the name on deletion BEntry *entry = new BEntry; status_t err2; err = dir.GetNextEntry(entry); BPath *path; BFile *file; while(err == B_OK) //loop over files { file = new BFile(entry, B_READ_ONLY); this->tracked_files.AddItem((void*)(file)); //add file to my list path = new BPath; entry->GetPath(path); printf("tracking: %s\n",path->Path()); this->tracked_filepaths.AddItem((void*)path); err2 = entry->GetNodeRef(&nref); if(err2 == B_OK) { err2 = watch_node(&nref, B_WATCH_STAT, be_app_messenger); //watch for edits if(err2 != B_OK) printf("Watch file Node: Not OK\n"); } entry = new BEntry; err = dir.GetNextEntry(entry); } //delete that last BEntry... } /* * Given a local file path, * call the script to delete the corresponding Dropbox file */ void delete_file_on_dropbox(const char * filepath) { printf("Telling Dropbox to Delete\n"); BString s, dbfp; s = BString(filepath); s.RemoveFirst("/boot/home/Dropbox"); dbfp << "python db_rm.py " << s; printf("%s\n",dbfp.String()); run_script(dbfp); } /* * Convert a local absolute filepath to a Dropbox one * by removing the <path to Dropbox> from the beginning */ BString local_to_db_filepath(const char * local_path) { BString s; s = BString(local_path); s.RemoveFirst("/boot/home/Dropbox/"); return s; } /* * Given the local file path of a new file, * run the script to upload it to Dropbox */ void add_file_to_dropbox(const char * filepath) { BString s, dbfp; dbfp = local_to_db_filepath(filepath); s << "python db_put.py " << BString(filepath) << " " << dbfp; printf("local filepath:%s\n",filepath); printf("dropbox filepath:%s\n",dbfp.String()); run_script(s.String()); } /* * Given the local file path of a new folder, * run the script to mkdir on Dropbox */ void add_folder_to_dropbox(const char * filepath) { BString s; s << "python db_mkdir.py " << local_to_db_filepath(filepath); printf("local filepath: %s\n", filepath); printf("db filepath: %s\n", local_to_db_filepath(filepath).String()); run_script(s.String()); } /* * TODO * Given a "file/folder moved" message, * figure out whether to call add or delete * and with what file path * and then call add/delete. */ void moved_file(BMessage *msg) { //is this file being move into or out of ~/Dropbox? run_script("python db_ls.py"); } /* * Given a local file path, * update the corresponding file on Dropbox */ void update_file_in_dropbox(const char * filepath) { printf("Putting %s to Dropbox.\n", filepath); add_file_to_dropbox(filepath); //just put it? } /* * Message Handling Function * If it's a node monitor message, * then figure out what to do based on it. * Otherwise, let BApplication handle it. */ void App::MessageReceived(BMessage *msg) { switch(msg->what) { case B_NODE_MONITOR: { printf("Received Node Monitor Alert\n"); status_t err; int32 opcode; err = msg->FindInt32("opcode",&opcode); if(err == B_OK) { printf("what:%d\topcode:%d\n",msg->what, opcode); switch(opcode) { case B_ENTRY_CREATED: { printf("NEW FILE\n"); entry_ref ref; BPath path; const char * name; // unpack the message msg->FindInt32("device",&ref.device); msg->FindInt64("directory",&ref.directory); msg->FindString("name",&name); printf("name:%s\n",name); ref.set_name(name); BEntry new_file = BEntry(&ref); // add the new file to Dropbox new_file.GetPath(&path); add_file_to_dropbox(path.Path()); // add the new file to global tracking lists BFile *file = new BFile(&new_file, B_READ_ONLY); this->tracked_files.AddItem((void*)file); BPath *path2 = new BPath; new_file.GetPath(path2); this->tracked_filepaths.AddItem((void*)path2); // listen for EDIT alerts on the new file node_ref nref; err = new_file.GetNodeRef(&nref); if(err == B_OK) { err = watch_node(&nref, B_WATCH_STAT, be_app_messenger); if(err != B_OK) printf("Watch new file %s: Not Ok.\n", path2->Path()); } break; } case B_ENTRY_MOVED: { printf("MOVED FILE\n"); moved_file(msg); break; } case B_ENTRY_REMOVED: { printf("DELETED FILE\n"); node_ref nref, cref; msg->FindInt32("device",&nref.device); msg->FindInt64("node",&nref.node); BFile *filePtr; int32 ktr = 0; int32 limit = this->tracked_files.CountItems(); printf("About to loop %d times\n", limit); while((filePtr = (BFile*)this->tracked_files.ItemAt(ktr))&&(ktr<limit)) { printf("In loop.\n"); filePtr->GetNodeRef(&cref); printf("GotNodeRef\n"); if(nref == cref) { printf("Deleting it\n"); BPath *path = (BPath*)this->tracked_filepaths.ItemAt(ktr); printf("%s\n",path->Path()); delete_file_on_dropbox(path->Path()); this->tracked_files.RemoveItem(ktr); this->tracked_filepaths.RemoveItem(ktr); break; //break out of loop } ktr++; } break; } case B_STAT_CHANGED: { printf("EDITED FILE\n"); node_ref nref1,nref2; msg->FindInt32("device",&nref1.device); msg->FindInt64("node",&nref1.node); BFile * filePtr; int32 ktr = 0; while((filePtr = (BFile *)this->tracked_files.ItemAt(ktr++))) { filePtr->GetNodeRef(&nref2); if(nref1 == nref2) { BPath *path; path = (BPath*)this->tracked_filepaths.ItemAt(ktr-1); update_file_in_dropbox(path->Path()); break; } } break; } default: { printf("default case opcode...\n"); } } } break; } default: { printf("default msg\n"); BApplication::MessageReceived(msg); break; } } } int main(void) { //set up application (watch Dropbox folder & contents) App *app = new App(); //start the application app->Run(); //clean up now that we're shutting down delete app; return 0; } <|endoftext|>
<commit_before>int main(){ return 0; }<commit_msg>Stuff<commit_after>int main(){ //Comments return 0; }<|endoftext|>
<commit_before>#include <cstdio> #include <vector> #include <list> #include <ctime> #include <algorithm> #include <iterator> #include <fstream> // include & define dependent libraries and types #include <map> #include <utility> typedef struct { float left, top, right, bottom; } rect_t; // include the mamdani matrix generated with gen_cleaned.pl #include <mamdani.ixx> int main(int argc, char* argv[]) { // time i/o separately since it takes a while volatile clock_t cstartio = clock(); #pragma warning(disable:4996) FILE* f = fopen("date-big.txt", "r"); std::fstream g("output.txt", std::ios::out); // store the input in a vector for faster processing std::vector<float> inputs; inputs.reserve(10002); while (!feof(f)) { float d; fscanf(f, "%f", &d); inputs.push_back(d); } std::vector<float> outputs(inputs.size()); volatile clock_t cstopio = clock(); volatile double spentio = (double)(cstopio - cstartio) / CLOCKS_PER_SEC; printf("Took %fs to _read_ %ld values\n", spentio, inputs.size()); // time the computation volatile clock_t cstart = clock(); // state variables float lastErr = 0.0; // previous error; initially 0 auto func = [&](float err) -> float { float derr = err - lastErr; // locate the partition the current point falls in auto found = std::find_if(g_mamdani.begin(), g_mamdani.end(), [&derr, &err](decltype(g_mamdani.front())& o) -> bool { return o.first.left <= err && o.first.right > err && o.first.top <= derr && o.first.bottom > derr; }); float val = 0.0; if (found != g_mamdani.end()) val = found->second; // print out the result //fprintf(g, "(%9.5lf, %9.5lf) -> %9.5lf\n", err, derr, val); return val; // update state lastErr = err; }; // process all inputs with our stateful function std::transform(inputs.begin(), inputs.end(), outputs.begin(), func); volatile clock_t cend = clock(); // report spent time volatile double spent = (double)(cend - cstart) / CLOCKS_PER_SEC; printf("Took %fs to process %ld values\n", spent, inputs.size()); cstartio = clock(); std::copy(outputs.begin(), outputs.end(), std::ostream_iterator<double>(g, "\n")); cstopio = clock(); spentio = (double)(cstopio - cstartio) / CLOCKS_PER_SEC; printf("Took %fs to write %ld values to disk\n", spentio, outputs.size()); return 0; }<commit_msg>use date.txt<commit_after>#include <cstdio> #include <vector> #include <list> #include <ctime> #include <algorithm> #include <iterator> #include <fstream> // include & define dependent libraries and types #include <map> #include <utility> typedef struct { float left, top, right, bottom; } rect_t; // include the mamdani matrix generated with gen_cleaned.pl #include <mamdani.ixx> int main(int argc, char* argv[]) { // time i/o separately since it takes a while volatile clock_t cstartio = clock(); #pragma warning(disable:4996) FILE* f = fopen("date.txt", "r"); std::fstream g("output.txt", std::ios::out); // store the input in a vector for faster processing std::vector<float> inputs; inputs.reserve(10002); while (!feof(f)) { float d; fscanf(f, "%f", &d); inputs.push_back(d); } std::vector<float> outputs(inputs.size()); volatile clock_t cstopio = clock(); volatile double spentio = (double)(cstopio - cstartio) / CLOCKS_PER_SEC; printf("Took %fs to _read_ %ld values\n", spentio, inputs.size()); // time the computation volatile clock_t cstart = clock(); // state variables float lastErr = 0.0; // previous error; initially 0 auto func = [&](float err) -> float { float derr = err - lastErr; // locate the partition the current point falls in auto found = std::find_if(g_mamdani.begin(), g_mamdani.end(), [&derr, &err](decltype(g_mamdani.front())& o) -> bool { return o.first.left <= err && o.first.right > err && o.first.top <= derr && o.first.bottom > derr; }); float val = 0.0; if (found != g_mamdani.end()) val = found->second; // print out the result //fprintf(g, "(%9.5lf, %9.5lf) -> %9.5lf\n", err, derr, val); return val; // update state lastErr = err; }; // process all inputs with our stateful function std::transform(inputs.begin(), inputs.end(), outputs.begin(), func); volatile clock_t cend = clock(); // report spent time volatile double spent = (double)(cend - cstart) / CLOCKS_PER_SEC; printf("Took %fs to process %ld values\n", spent, inputs.size()); cstartio = clock(); std::copy(outputs.begin(), outputs.end(), std::ostream_iterator<double>(g, "\n")); cstopio = clock(); spentio = (double)(cstopio - cstartio) / CLOCKS_PER_SEC; printf("Took %fs to write %ld values to disk\n", spentio, outputs.size()); return 0; }<|endoftext|>
<commit_before>/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Module: FGEngine.cpp Author: Jon Berndt Date started: 01/21/99 Called by: FGAircraft ------------- Copyright (C) 1999 Jon S. Berndt ([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. Further information about the GNU General Public License can also be found on the world wide web at http://www.gnu.org. FUNCTIONAL DESCRIPTION -------------------------------------------------------------------------------- See header file. HISTORY -------------------------------------------------------------------------------- 01/21/99 JSB Created 09/03/99 JSB Changed Rocket thrust equation to correct -= Thrust instead of += Thrust (thanks to Tony Peden) %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% INCLUDES %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/ #ifdef FGFS # include <simgear/compiler.h> # ifdef SG_HAVE_STD_INCLUDES # include <fstream> # else # include <fstream.h> # endif #else # if defined(sgi) && !defined(__GNUC__) # include <fstream.h> # else # include <fstream> # endif #endif #include "FGEngine.h" #include "FGTank.h" namespace JSBSim { static const char *IdSrc = "$Id: FGEngine.cpp,v 1.54 2003/08/11 08:33:57 ehofman Exp $"; static const char *IdHdr = ID_ENGINE; /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% CLASS IMPLEMENTATION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/ FGEngine::FGEngine(FGFDMExec* exec) : Name(""), Type(etUnknown), X(0), Y(0), Z(0), EnginePitch(0), EngineYaw(0), SLFuelFlowMax(0), SLOxiFlowMax(0), MaxThrottle(1.0), MinThrottle(0.0), Thrust(0.0), Throttle(0.0), Mixture(1.0), Magnetos(0), Starter(false), FuelNeed(0.0), OxidizerNeed(0.0), Starved(false), Flameout(false), Running(false), Cranking(false), Augmentation(false), Injection(false), Ignition(false), Reversed(false), Cutoff(true), Nitrous(false), PctPower(0.0), EngineNumber(-1), TrimMode(false), FuelFlow_gph(0.0), ManifoldPressure_inHg(0.0), ExhaustGasTemp_degK(0.0), CylinderHeadTemp_degK(0.0), OilPressure_psi(0.0), OilTemp_degK(0.0), FuelFlow_pph(0.0), N1(0.0), N2(0.0), EGT_degC(0.0), InletPosition(0.0), NozzlePosition(0.0), FDMExec(exec), State(FDMExec->GetState()), Atmosphere(FDMExec->GetAtmosphere()), FCS(FDMExec->GetFCS()), Propulsion(FDMExec->GetPropulsion()), Aircraft(FDMExec->GetAircraft()), Translation(FDMExec->GetTranslation()), Rotation(FDMExec->GetRotation()), Position(FDMExec->GetPosition()), Auxiliary(FDMExec->GetAuxiliary()), Output(FDMExec->GetOutput()) { Debug(0); } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% FGEngine::~FGEngine() { Debug(1); } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% // This base class function should be called from within the // derived class' Calculate() function before any other calculations are done. // This base class method removes fuel from the fuel tanks as appropriate, // and sets the starved flag if necessary. void FGEngine::ConsumeFuel(void) { double Fshortage, Oshortage; FGTank* Tank; if (TrimMode) return; Fshortage = Oshortage = 0.0; for (unsigned int i=0; i<SourceTanks.size(); i++) { Tank = Propulsion->GetTank(i); if (Tank->GetType() == FGTank::ttFUEL) { Fshortage += Tank->Reduce(CalcFuelNeed()/Propulsion->GetnumSelectedFuelTanks()); } else { Oshortage += Tank->Reduce(CalcOxidizerNeed()/Propulsion->GetnumSelectedOxiTanks()); } } if (Fshortage < 0.00 || Oshortage < 0.00) Starved = true; else Starved = false; } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% double FGEngine::CalcFuelNeed(void) { FuelNeed = SLFuelFlowMax*PctPower*State->Getdt()*Propulsion->GetRate(); return FuelNeed; } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% double FGEngine::CalcOxidizerNeed(void) { OxidizerNeed = SLOxiFlowMax*PctPower*State->Getdt()*Propulsion->GetRate(); return OxidizerNeed; } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% void FGEngine::SetPlacement(double x, double y, double z, double pitch, double yaw) { X = x; Y = y; Z = z; EnginePitch = pitch; EngineYaw = yaw; } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% void FGEngine::AddFeedTank(int tkID) { SourceTanks.push_back(tkID); } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% // 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 FGEngine::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: FGEngine" << endl; if (from == 1) cout << "Destroyed: FGEngine" << 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; } } } } <commit_msg>Fixed fuel tank bug 810651<commit_after>/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Module: FGEngine.cpp Author: Jon Berndt Date started: 01/21/99 Called by: FGAircraft ------------- Copyright (C) 1999 Jon S. Berndt ([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. Further information about the GNU General Public License can also be found on the world wide web at http://www.gnu.org. FUNCTIONAL DESCRIPTION -------------------------------------------------------------------------------- See header file. HISTORY -------------------------------------------------------------------------------- 01/21/99 JSB Created 09/03/99 JSB Changed Rocket thrust equation to correct -= Thrust instead of += Thrust (thanks to Tony Peden) %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% INCLUDES %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/ #ifdef FGFS # include <simgear/compiler.h> # ifdef SG_HAVE_STD_INCLUDES # include <fstream> # else # include <fstream.h> # endif #else # if defined(sgi) && !defined(__GNUC__) # include <fstream.h> # else # include <fstream> # endif #endif #include "FGEngine.h" #include "FGTank.h" namespace JSBSim { static const char *IdSrc = "$Id: FGEngine.cpp,v 1.55 2003/09/23 04:44:01 jberndt Exp $"; static const char *IdHdr = ID_ENGINE; /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% CLASS IMPLEMENTATION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/ FGEngine::FGEngine(FGFDMExec* exec) : Name(""), Type(etUnknown), X(0), Y(0), Z(0), EnginePitch(0), EngineYaw(0), SLFuelFlowMax(0), SLOxiFlowMax(0), MaxThrottle(1.0), MinThrottle(0.0), Thrust(0.0), Throttle(0.0), Mixture(1.0), Magnetos(0), Starter(false), FuelNeed(0.0), OxidizerNeed(0.0), Starved(false), Flameout(false), Running(false), Cranking(false), Augmentation(false), Injection(false), Ignition(false), Reversed(false), Cutoff(true), Nitrous(false), PctPower(0.0), EngineNumber(-1), TrimMode(false), FuelFlow_gph(0.0), ManifoldPressure_inHg(0.0), ExhaustGasTemp_degK(0.0), CylinderHeadTemp_degK(0.0), OilPressure_psi(0.0), OilTemp_degK(0.0), FuelFlow_pph(0.0), N1(0.0), N2(0.0), EGT_degC(0.0), InletPosition(0.0), NozzlePosition(0.0), FDMExec(exec), State(FDMExec->GetState()), Atmosphere(FDMExec->GetAtmosphere()), FCS(FDMExec->GetFCS()), Propulsion(FDMExec->GetPropulsion()), Aircraft(FDMExec->GetAircraft()), Translation(FDMExec->GetTranslation()), Rotation(FDMExec->GetRotation()), Position(FDMExec->GetPosition()), Auxiliary(FDMExec->GetAuxiliary()), Output(FDMExec->GetOutput()) { Debug(0); } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% FGEngine::~FGEngine() { Debug(1); } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% // This base class function should be called from within the // derived class' Calculate() function before any other calculations are done. // This base class method removes fuel from the fuel tanks as appropriate, // and sets the starved flag if necessary. void FGEngine::ConsumeFuel(void) { double Fshortage, Oshortage; FGTank* Tank; if (TrimMode) return; Fshortage = Oshortage = 0.0; for (unsigned int i=0; i<SourceTanks.size(); i++) { Tank = Propulsion->GetTank(SourceTanks[i]); if (Tank->GetType() == FGTank::ttFUEL) { Fshortage += Tank->Reduce(CalcFuelNeed()/Propulsion->GetnumSelectedFuelTanks()); } else { Oshortage += Tank->Reduce(CalcOxidizerNeed()/Propulsion->GetnumSelectedOxiTanks()); } } if (Fshortage < 0.00 || Oshortage < 0.00) Starved = true; else Starved = false; } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% double FGEngine::CalcFuelNeed(void) { FuelNeed = SLFuelFlowMax*PctPower*State->Getdt()*Propulsion->GetRate(); return FuelNeed; } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% double FGEngine::CalcOxidizerNeed(void) { OxidizerNeed = SLOxiFlowMax*PctPower*State->Getdt()*Propulsion->GetRate(); return OxidizerNeed; } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% void FGEngine::SetPlacement(double x, double y, double z, double pitch, double yaw) { X = x; Y = y; Z = z; EnginePitch = pitch; EngineYaw = yaw; } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% void FGEngine::AddFeedTank(int tkID) { SourceTanks.push_back(tkID); } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% // 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 FGEngine::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: FGEngine" << endl; if (from == 1) cout << "Destroyed: FGEngine" << 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; } } } } <|endoftext|>
<commit_before>#include <stdio.h> #include <unistd.h> #include <vector> #include <iostream> #include <fstream> #include <sstream> #include <string> #include "opencv2/core.hpp" #include "opencv2/imgproc.hpp" #include "opencv2/highgui.hpp" #define SHOW_IMAGE 1 using namespace cv; using namespace std; void readFile(string&, vector<string>&, vector<string>&); int getImgSize(vector<string>&); Mat mergeMatrix(int, vector<string>&); Mat subtractMatrix(Mat, Mat); Mat getAverageVector(Mat, int); Mat getBestEigenVectors(Mat, Mat, int); Mat getBestEigenVectors(Mat covar, Mat difference, int imgRows) { //Get all eigenvalues and eigenvectors from covariance matrix Mat allEigenValues, allEigenVectors; eigen(covar, allEigenValues, allEigenVectors); Mat eigenVec = allEigenVectors * (difference.t()); //Normalize eigenvectors for(int i = 0; i < eigenVec.rows; i++ ) { Mat tempVec = eigenVec.row(i); normalize(tempVec, tempVec); } if (SHOW_IMAGE) { //Display eigen face Mat eigenFaces, allEigenFaces; for (int i = 0; i < eigenVec.rows; i++) { eigenVec.row(i).reshape(0, imgRows).copyTo(eigenFaces); normalize(eigenFaces, eigenFaces, 0, 1, cv::NORM_MINMAX); if(i == 0){ allEigenFaces = eigenFaces; }else{ hconcat(allEigenFaces, eigenFaces, allEigenFaces); } } namedWindow("EigenFaces", CV_WINDOW_NORMAL); imshow("EigenFaces", allEigenFaces); } return eigenVec; } Mat getAverageVector(Mat facesMatrix, int imgRows) { //To calculate average face, 1 means that the matrix is reduced to a single column. //vector is 1D column vector, face is 2D Mat Mat vector, face; reduce(facesMatrix, vector, 1, CV_REDUCE_AVG); if (SHOW_IMAGE) { vector.reshape(0, imgRows).copyTo(face); //Just for display face normalize(face, face, 0, 1, cv::NORM_MINMAX); namedWindow("AverageFace", CV_WINDOW_NORMAL); imshow("AverageFace", face); } return vector; } Mat subtractMatrix(Mat facesMatrix, Mat avgVector) { Mat resultMatrix; facesMatrix.copyTo(resultMatrix); for (int i = 0; i < resultMatrix.cols; i++) { subtract(resultMatrix.col(i), avgVector, resultMatrix.col(i)); } return resultMatrix; } Mat mergeMatrix(int row, vector<string>& facesPath) { int col = int(facesPath.size()); Mat mergedMatrix(row, col, CV_32FC1); for (int i = 0; i < col; i++) { Mat tmpMatrix = mergedMatrix.col(i); //Load grayscale image 0 Mat tmpImg; imread(facesPath[i], 0).convertTo(tmpImg, CV_32FC1); //convert to 1D matrix tmpImg.reshape(1, row).copyTo(tmpMatrix); } //cout << "Merged Matix(Width, Height): " << mergedMatrix.size() << endl; return mergedMatrix; } int getImgSize(vector<string>& facesPath) { Mat sampleImg = imread(facesPath[0], 0); if (sampleImg.empty()) { cout << "Fail to Load Image" << endl; exit(1); } //Dimession of Features int size = sampleImg.rows * sampleImg.cols; //cout << "Per Image Size is: " << size << endl; return size; } void readFile(string& listFilePath, vector<string>& facesPath, vector<int>& facesID) { ifstream file(listFilePath.c_str(), ifstream::in); if (!file) { cout << "Fail to open file: " << listFilePath << endl; exit(0); } string line, path, id; while (getline(file, line)) { stringstream lines(line); getline(lines, id, ';'); getline(lines, path); path.erase(remove(path.begin(), path.end(), '\r'), path.end()); path.erase(remove(path.begin(), path.end(), '\n'), path.end()); path.erase(remove(path.begin(), path.end(), ' '), path.end()); facesPath.push_back(path); facesID.push_back(atoi(id.c_str())); } for(int i = 0; i < facesPath.size(); i++) { cout << facesID[i] << " : " << facesPath[i] << endl; } } int main(int argc, char** argv) { string trainListFilePath = "/Users/zichun/Documents/Assignment/FaceRecognition/FRG/train_list.txt"; vector<string> trainFacesPath; vector<int> trainFacesID; //Load training sets' ID and path to vector readFile(trainListFilePath, trainFacesPath, trainFacesID); //Get dimession of features for single image int imgSize = getImgSize(trainFacesPath); int imgRows = imread(trainFacesPath[0],0).rows; //Create a (imgSize X #ofSamples) floating 2D Matrix to store training data Mat trainFacesMatrix = mergeMatrix(imgSize, trainFacesPath); //Get average face vector Mat trainAvgVector = getAverageVector(trainFacesMatrix, imgRows); //Subtract average face from faces matrix Mat subTrainFaceMatrix = subtractMatrix(trainFacesMatrix, trainAvgVector); //Get covariance matrix Mat covarMatrix = (subTrainFaceMatrix.t()) * subTrainFaceMatrix; //Get eigenvectors Mat eigenVectors = getBestEigenVectors(covarMatrix, subTrainFaceMatrix, imgRows); cout << "Eigenvectors(W, H): " <<eigenVectors.size() << endl; waitKey(); return 0; } <commit_msg>add project function<commit_after>#include <stdio.h> #include <unistd.h> #include <vector> #include <iostream> #include <fstream> #include <sstream> #include <string> #include "opencv2/core.hpp" #include "opencv2/imgproc.hpp" #include "opencv2/highgui.hpp" #define SHOW_IMAGE 1 using namespace cv; using namespace std; void readFile(string&, vector<string>&, vector<string>&); int getImgSize(vector<string>&); Mat mergeMatrix(int, vector<string>&); Mat subtractMatrix(Mat, Mat); Mat getAverageVector(Mat, int); Mat getBestEigenVectors(Mat, Mat, int); Mat getProjectedFaces(Mat, Mat, Mat); Mat getProjectedFaces(Mat inputFaceVec, Mat meanFaceVec, Mat eigenVecs){ Mat prjFace, tmpData; if (inputFaceVec.cols != 1 || meanFaceVec.cols != 1 || inputFaceVec.rows != meanFaceVec.rows) { cout << "Wrong Input in getProjectedFaces!" << endl; exit(1); } subtract(inputFaceVec, meanFaceVec, tmpData); prjFace = eigenVecs * tmpData; cout << "Projected Face(W, H):" <<prjFace.size() << endl; //cout << prjFace.at<float>(0) << endl; return prjFace; } Mat getBestEigenVectors(Mat covar, Mat difference, int imgRows) { //Get all eigenvalues and eigenvectors from covariance matrix Mat allEigenValues, allEigenVectors; eigen(covar, allEigenValues, allEigenVectors); Mat eigenVec = allEigenVectors * (difference.t()); //Normalize eigenvectors for(int i = 0; i < eigenVec.rows; i++ ) { Mat tempVec = eigenVec.row(i); normalize(tempVec, tempVec); } if (SHOW_IMAGE) { //Display eigen face Mat eigenFaces, allEigenFaces; for (int i = 0; i < eigenVec.rows; i++) { eigenVec.row(i).reshape(0, imgRows).copyTo(eigenFaces); normalize(eigenFaces, eigenFaces, 0, 1, cv::NORM_MINMAX); if(i == 0){ allEigenFaces = eigenFaces; }else{ hconcat(allEigenFaces, eigenFaces, allEigenFaces); } } namedWindow("EigenFaces", CV_WINDOW_NORMAL); imshow("EigenFaces", allEigenFaces); } return eigenVec; } Mat getAverageVector(Mat facesMatrix, int imgRows) { //To calculate average face, 1 means that the matrix is reduced to a single column. //vector is 1D column vector, face is 2D Mat Mat vector, face; reduce(facesMatrix, vector, 1, CV_REDUCE_AVG); if (SHOW_IMAGE) { vector.reshape(0, imgRows).copyTo(face); //Just for display face normalize(face, face, 0, 1, cv::NORM_MINMAX); namedWindow("AverageFace", CV_WINDOW_NORMAL); imshow("AverageFace", face); } return vector; } Mat subtractMatrix(Mat facesMatrix, Mat avgVector) { Mat resultMatrix; facesMatrix.copyTo(resultMatrix); for (int i = 0; i < resultMatrix.cols; i++) { subtract(resultMatrix.col(i), avgVector, resultMatrix.col(i)); } return resultMatrix; } Mat mergeMatrix(int row, vector<string>& facesPath) { int col = int(facesPath.size()); Mat mergedMatrix(row, col, CV_32FC1); for (int i = 0; i < col; i++) { Mat tmpMatrix = mergedMatrix.col(i); //Load grayscale image 0 Mat tmpImg; imread(facesPath[i], 0).convertTo(tmpImg, CV_32FC1); //convert to 1D matrix tmpImg.reshape(1, row).copyTo(tmpMatrix); } //cout << "Merged Matix(Width, Height): " << mergedMatrix.size() << endl; return mergedMatrix; } int getImgSize(vector<string>& facesPath) { Mat sampleImg = imread(facesPath[0], 0); if (sampleImg.empty()) { cout << "Fail to Load Image" << endl; exit(1); } //Dimession of Features int size = sampleImg.rows * sampleImg.cols; //cout << "Per Image Size is: " << size << endl; return size; } void readFile(string& listFilePath, vector<string>& facesPath, vector<int>& facesID) { ifstream file(listFilePath.c_str(), ifstream::in); if (!file) { cout << "Fail to open file: " << listFilePath << endl; exit(0); } string line, path, id; while (getline(file, line)) { stringstream lines(line); getline(lines, id, ';'); getline(lines, path); path.erase(remove(path.begin(), path.end(), '\r'), path.end()); path.erase(remove(path.begin(), path.end(), '\n'), path.end()); path.erase(remove(path.begin(), path.end(), ' '), path.end()); facesPath.push_back(path); facesID.push_back(atoi(id.c_str())); } for(int i = 0; i < facesPath.size(); i++) { cout << facesID[i] << " : " << facesPath[i] << endl; } } int main(int argc, char** argv) { string trainListFilePath = "/Users/zichun/Documents/Assignment/FaceRecognition/FRG/train_list.txt"; vector<string> trainFacesPath; vector<int> trainFacesID; //Load training sets' ID and path to vector readFile(trainListFilePath, trainFacesPath, trainFacesID); //Get dimession of features for single image int imgSize = getImgSize(trainFacesPath); int imgRows = imread(trainFacesPath[0],0).rows; //Create a (imgSize X #ofSamples) floating 2D Matrix to store training data Mat trainFacesMatrix = mergeMatrix(imgSize, trainFacesPath); //Get average face vector Mat trainAvgVector = getAverageVector(trainFacesMatrix, imgRows); //Subtract average face from faces matrix Mat subTrainFaceMatrix = subtractMatrix(trainFacesMatrix, trainAvgVector); //Get covariance matrix Mat covarMatrix = (subTrainFaceMatrix.t()) * subTrainFaceMatrix; //Get eigenvectors Mat eigenVectors = getBestEigenVectors(covarMatrix, subTrainFaceMatrix, imgRows); cout << "Eigenvectors(W, H): " <<eigenVectors.size() << endl; //cout << eigenVectors.at<float>(0,0) << "--" << eigenVectors.at<float>(0,1) << endl; /* PCA pca = PCA(trainFacesMatrix, Mat(), CV_PCA_DATA_AS_COL); cout << pca.eigenvectors.at<float>(0, 0) << "--" << pca.eigenvectors.at<float>(0,1) << endl; Mat tempFace1 = pca.project(trainFacesMatrix.col(0)); cout << tempFace1.size() << endl; cout << tempFace1.at<float>(0) << endl; */ //Project input face to eigen space Mat projectedFace = getProjectedFaces(trainFacesMatrix.col(0), trainAvgVector, eigenVectors); waitKey(); return 0; } <|endoftext|>
<commit_before>#include <stdio.h> #include <unistd.h> #include <vector> #include <iostream> #include <fstream> #include <sstream> #include <string> #include "opencv2/core.hpp" #include "opencv2/imgproc.hpp" #include "opencv2/highgui.hpp" using namespace cv; using namespace std; void readFile(string&, vector<string>&, vector<string>&); int getImgSize(vector<string>&); Mat mergeMatrix(int, vector<string>&); Mat mergeMatrix(int row, vector<string>& facesPath) { int col = int(facesPath.size()); Mat mergedMatrix(row, col, CV_32FC1); for (int i = 0; i < col; i++) { Mat tmpMatrix = mergedMatrix.col(i); //Load grayscale image 0 Mat tmpImg = imread(facesPath[i], 0); tmpImg.convertTo(tmpImg, CV_32FC1); cout << "pixcel: " << tmpImg.at<float>(2,4) << endl; //convert to (row x 1) matrix tmpImg.reshape(1, row); tmpImg.copyTo(tmpMatrix); } cout << "Merged Matix(row, col): " << mergedMatrix.rows << " X " << mergedMatrix.cols << endl; cout << "pixcel: " << mergedMatrix.at<float>(5,4) << endl; return mergedMatrix; } int getImgSize(vector<string>& facesPath) { Mat sampleImg = imread(facesPath[0], 0); if (sampleImg.empty()) { cout << "Fail to Load Image" << endl; exit(1); } //Dimession of Features int size = sampleImg.rows * sampleImg.cols; cout << "Per Image Size is: " << size << endl; return size; } void readFile(string& listFilePath, vector<string>& facesPath, vector<int>& facesID) { std::ifstream file(listFilePath.c_str(), ifstream::in); if (!file) { cout << "Fail to open file: " << listFilePath << endl; exit(0); } std::string line, path, id; while (std::getline(file, line)) { std::stringstream lines(line); std::getline(lines, id, ';'); std::getline(lines, path); path.erase(std::remove(path.begin(), path.end(), '\r'), path.end()); path.erase(std::remove(path.begin(), path.end(), '\n'), path.end()); path.erase(std::remove(path.begin(), path.end(), ' '), path.end()); facesPath.push_back(path); facesID.push_back(atoi(id.c_str())); } } int main(int argc, char** argv) { string trainListFilePath = "/Users/zichun/Documents/Assignment/FaceRecognition/FRG/train_list.txt"; vector<string> trainFacesPath; vector<int> trainFacesID; //load training sets' ID and path to vector readFile(trainListFilePath, trainFacesPath, trainFacesID); for(int i = 0; i < trainFacesPath.size(); i++) { cout << trainFacesID[i] << " : " << trainFacesPath[i] << endl; } //get dimession of each image int imgSize = getImgSize(trainFacesPath); //Create a (imgSize X #ofSamples) floating 2D Matrix to store training data Mat trainFacesMatrix = mergeMatrix(imgSize, trainFacesPath); //cout << "pixcel: " << trainFacesMatrix.at<float>(1,1) << endl; waitKey(); return 0; } <commit_msg>fix mergeMatrix Bug<commit_after>#include <stdio.h> #include <unistd.h> #include <vector> #include <iostream> #include <fstream> #include <sstream> #include <string> #include "opencv2/core.hpp" #include "opencv2/imgproc.hpp" #include "opencv2/highgui.hpp" using namespace cv; using namespace std; void readFile(string&, vector<string>&, vector<string>&); int getImgSize(vector<string>&); Mat mergeMatrix(int, vector<string>&); Mat mergeMatrix(int row, vector<string>& facesPath) { int col = int(facesPath.size()); Mat mergedMatrix(row, col, CV_32FC1); for (int i = 0; i < col; i++) { Mat tmpMatrix = mergedMatrix.col(i); //Load grayscale image 0 Mat tmpImg; imread(facesPath[i], 0).convertTo(tmpImg, CV_32FC1); //convert to 1D matrix tmpImg.reshape(1, row).copyTo(tmpMatrix); } cout << "Merged Matix(row, col): " << mergedMatrix.rows << " X " << mergedMatrix.cols << endl; return mergedMatrix; } int getImgSize(vector<string>& facesPath) { Mat sampleImg = imread(facesPath[0], 0); if (sampleImg.empty()) { cout << "Fail to Load Image" << endl; exit(1); } //Dimession of Features int size = sampleImg.rows * sampleImg.cols; cout << "Per Image Size is: " << size << endl; return size; } void readFile(string& listFilePath, vector<string>& facesPath, vector<int>& facesID) { std::ifstream file(listFilePath.c_str(), ifstream::in); if (!file) { cout << "Fail to open file: " << listFilePath << endl; exit(0); } std::string line, path, id; while (std::getline(file, line)) { std::stringstream lines(line); std::getline(lines, id, ';'); std::getline(lines, path); path.erase(std::remove(path.begin(), path.end(), '\r'), path.end()); path.erase(std::remove(path.begin(), path.end(), '\n'), path.end()); path.erase(std::remove(path.begin(), path.end(), ' '), path.end()); facesPath.push_back(path); facesID.push_back(atoi(id.c_str())); } } int main(int argc, char** argv) { string trainListFilePath = "/Users/zichun/Documents/Assignment/FaceRecognition/FRG/train_list.txt"; vector<string> trainFacesPath; vector<int> trainFacesID; //load training sets' ID and path to vector readFile(trainListFilePath, trainFacesPath, trainFacesID); for(int i = 0; i < trainFacesPath.size(); i++) { cout << trainFacesID[i] << " : " << trainFacesPath[i] << endl; } //get dimession of each image int imgSize = getImgSize(trainFacesPath); //Create a (imgSize X #ofSamples) floating 2D Matrix to store training data Mat trainFacesMatrix = mergeMatrix(imgSize, trainFacesPath); //To calculate average face waitKey(); return 0; } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: officeloader.cxx,v $ * * $Revision: 1.14 $ * * last change: $Author: obo $ $Date: 2008-01-04 16:22:37 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * 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 * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_desktop.hxx" #define UNICODE #define _UNICODE #define WIN32_LEAN_AND_MEAN #if defined _MSC_VER #pragma warning(push, 1) #endif #include <windows.h> #include <shellapi.h> #if defined _MSC_VER #pragma warning(pop) #endif #include <tchar.h> #include <malloc.h> #include <string.h> #include <stdlib.h> #include <systools/win32/uwinapi.h> #include "rtl/string.h" #include "../../../source/inc/exithelper.hxx" #include "../extendloaderenvironment.hxx" #define PIPE_PREFIX TEXT("\\\\.\\pipe\\OSL_PIPE_") #define PIPE_POSTFIX TEXT("_SingleOfficeIPC_") #define PIPE_TERMINATION_SEQUENCE "InternalIPC::ProcessingDone" BOOL WINAPI ConvertSidToStringSid( PSID pSid, LPTSTR* StringSid ) { PSID_IDENTIFIER_AUTHORITY psia; DWORD dwSubAuthorities; DWORD dwSidRev=SID_REVISION; DWORD dwCounter; DWORD dwSidSize; // Validate the binary SID. if(!IsValidSid(pSid)) return FALSE; // Get the identifier authority value from the SID. psia = GetSidIdentifierAuthority(pSid); // Get the number of subauthorities in the SID. dwSubAuthorities = *GetSidSubAuthorityCount(pSid); // Compute the buffer length. // S-SID_REVISION- + IdentifierAuthority- + subauthorities- + NULL dwSidSize=(15 + 12 + (12 * dwSubAuthorities) + 1) * sizeof(TCHAR); *StringSid = (LPTSTR)LocalAlloc( LMEM_FIXED, dwSidSize ); // Add 'S' prefix and revision number to the string. dwSidSize=wsprintf(*StringSid, TEXT("S-%lu-"), dwSidRev ); // Add a SID identifier authority to the string. if ( (psia->Value[0] != 0) || (psia->Value[1] != 0) ) { dwSidSize+=wsprintf(*StringSid + lstrlen(*StringSid), TEXT("0x%02hx%02hx%02hx%02hx%02hx%02hx"), (USHORT)psia->Value[0], (USHORT)psia->Value[1], (USHORT)psia->Value[2], (USHORT)psia->Value[3], (USHORT)psia->Value[4], (USHORT)psia->Value[5]); } else { dwSidSize+=wsprintf(*StringSid + lstrlen(*StringSid), TEXT("%lu"), (ULONG)(psia->Value[5] ) + (ULONG)(psia->Value[4] << 8) + (ULONG)(psia->Value[3] << 16) + (ULONG)(psia->Value[2] << 24) ); } // Add SID subauthorities to the string. // for (dwCounter=0 ; dwCounter < dwSubAuthorities ; dwCounter++) { dwSidSize+=wsprintf(*StringSid + dwSidSize, TEXT("-%lu"), *GetSidSubAuthority(pSid, dwCounter) ); } return TRUE; } //--------------------------------------------------------------------------- static LPTSTR *GetCommandArgs( int *pArgc ) { #ifdef UNICODE return CommandLineToArgvW( GetCommandLineW(), pArgc ); #else *pArgc = __argc; return __argv; #endif } //--------------------------------------------------------------------------- #ifdef __MINGW32__ int WINAPI WinMain( HINSTANCE hInstance, HINSTANCE, LPSTR, int ) #else int WINAPI _tWinMain( HINSTANCE, HINSTANCE, LPTSTR, int ) #endif { TCHAR szTargetFileName[MAX_PATH] = TEXT(""); TCHAR szPerfTuneIniFile[MAX_PATH] = TEXT(""); STARTUPINFO aStartupInfo; ZeroMemory( &aStartupInfo, sizeof(aStartupInfo) ); aStartupInfo.cb = sizeof(aStartupInfo); GetStartupInfo( &aStartupInfo ); // Get image path with same name but with .bin extension TCHAR szModuleFileName[MAX_PATH]; GetModuleFileName( NULL, szModuleFileName, MAX_PATH ); _TCHAR *lpLastDot = _tcsrchr( szModuleFileName, '.' ); if ( lpLastDot && 0 == _tcsicmp( lpLastDot, _T(".EXE") ) ) { size_t len = lpLastDot - szModuleFileName; _tcsncpy( szTargetFileName, szModuleFileName, len ); _tcsncpy( szTargetFileName + len, _T(".BIN"), sizeof(szTargetFileName)/sizeof(szTargetFileName[0]) - len ); } _TCHAR *lpLastSlash = _tcsrchr( szModuleFileName, '\\' ); if ( lpLastSlash ) { size_t len = lpLastSlash - szModuleFileName + 1; _tcsncpy( szPerfTuneIniFile, szModuleFileName, len ); _tcsncpy( szPerfTuneIniFile + len, _T("perftune.ini"), sizeof(szPerfTuneIniFile)/sizeof(szPerfTuneIniFile[0]) - len ); } #ifndef __MINGW32__ desktop_win32::extendLoaderEnvironment(); #endif // Create process with same command line, environment and stdio handles which // are directed to the created pipes DWORD dwExitCode = (DWORD)-1; // FALSE indicates first start BOOL fSuccess = FALSE; LPTSTR lpCommandLine = NULL; do { TCHAR szKey[32]; GetPrivateProfileString( TEXT("PerformanceTuning"), TEXT("FastPipeCommunication"), TEXT("0"), szKey, elementsof(szKey), szPerfTuneIniFile ); if ( 0 == _tcscmp( szKey, TEXT("1") ) ) { HANDLE hProcessToken; if ( OpenProcessToken( GetCurrentProcess(), TOKEN_QUERY, &hProcessToken ) ) { TCHAR szPipeName[4096]; DWORD dwTokenLength = 0; fSuccess = GetTokenInformation( hProcessToken, TokenUser, NULL, dwTokenLength, &dwTokenLength ); PVOID pTokenInfo = _alloca(dwTokenLength); fSuccess = GetTokenInformation( hProcessToken, TokenUser, pTokenInfo, dwTokenLength, &dwTokenLength ); CloseHandle( hProcessToken ); PSID pSid = ((PTOKEN_USER)pTokenInfo)->User.Sid; LPTSTR szUserIdent = NULL; TCHAR szSUPD[11] = TEXT("0"); fSuccess = ConvertSidToStringSid( pSid, &szUserIdent ); _tcsncpy( szPipeName, PIPE_PREFIX, elementsof(szPipeName) ); _tcsncat( szPipeName, szUserIdent, elementsof(szPipeName) - _tcslen(szPipeName) - 1 ); _tcsncat( szPipeName, PIPE_POSTFIX, elementsof(szPipeName) - _tcslen(szPipeName) - 1 ); _tcsncat( szPipeName, _ultot( SUPD, szSUPD, 10), elementsof(szPipeName) - _tcslen(szPipeName) - 1 ); LocalFree( szUserIdent ); HANDLE hPipe = CreateFile( szPipeName, GENERIC_READ|GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); if ( INVALID_HANDLE_VALUE != hPipe ) { DWORD dwBytesWritten; int argc = 0; LPWSTR *argv = CommandLineToArgvW( GetCommandLine(), &argc ); fSuccess = WriteFile( hPipe, RTL_CONSTASCII_STRINGPARAM("InternalIPC::Arguments"), &dwBytesWritten, NULL ); for ( int argn = 1; fSuccess && argn < argc; argn++ ) { CHAR szBuffer[4096]; int n = WideCharToMultiByte( CP_UTF8, 0, argv[argn], -1, szBuffer, sizeof(szBuffer), NULL, NULL ); char b[RTL_CONSTASCII_LENGTH(",") + 2 * ((sizeof szBuffer) - 1)] = ","; // hopefully does not overflow char * p = b + RTL_CONSTASCII_LENGTH(","); for (int i = 0; i < n - 1; ++i) // cannot underflow (n >= 0) { char c = szBuffer[i]; switch (c) { case '\0': *p++ = '\\'; *p++ = '0'; break; case ',': *p++ = '\\'; *p++ = ','; break; case '\\': *p++ = '\\'; *p++ = '\\'; break; default: *p++ = c; break; } } fSuccess = WriteFile( hPipe, b, p - b, &dwBytesWritten, NULL ); } if ( fSuccess ) { fSuccess = WriteFile( hPipe, "", 1, &dwBytesWritten, NULL ); if ( fSuccess ) { DWORD dwBytesRead = 0; char *pBuffer = (char *)_alloca( sizeof(PIPE_TERMINATION_SEQUENCE) ); fSuccess = ReadFile( hPipe, pBuffer, sizeof(PIPE_TERMINATION_SEQUENCE) - 1, &dwBytesRead, NULL ); if ( fSuccess ) { pBuffer[dwBytesRead] = 0; if ( 0 != strcmp( PIPE_TERMINATION_SEQUENCE, pBuffer ) ) fSuccess = FALSE; } } } CloseHandle( hPipe ); return fSuccess ? 0 : -1; } } } if ( fSuccess && !lpCommandLine ) { int argc; LPTSTR *argv = GetCommandArgs( &argc ); if ( argc > 1 ) { int n; int nBufferChars = _tcslen( argv[0] ) + 2; for ( n = 1; n < argc; n++ ) { if ( 0 == _tcsnicmp( argv[n], _T("-env:"), 5 ) ) nBufferChars += _tcslen( argv[n] ) + 3; } if ( nBufferChars ) { lpCommandLine = new TCHAR[nBufferChars + 1]; _tcscpy( lpCommandLine, _T("\"") ); _tcscat( lpCommandLine, argv[0] ); _tcscat( lpCommandLine, _T("\"") ); for ( n = 1; n < argc; n++ ) { if ( 0 == _tcsnicmp( argv[n], _T("-env:"), 5 ) ) { _tcscat( lpCommandLine, _T(" ") ); _tcscat( lpCommandLine, _T("\"") ); _tcscat( lpCommandLine, argv[n] ); _tcscat( lpCommandLine, _T("\"") ); } } } } } TCHAR szParentProcessId[64]; // This is more than large enough for a 128 bit decimal value BOOL bHeadlessMode( FALSE ); { // Check command line arguments for "-headless" parameter. We only // set the environment variable "ATTACHED_PARENT_PROCESSID" for the headless // mode as self-destruction of the soffice.bin process can lead to // certain side-effects (log-off can result in data-loss, ".lock" is not deleted. // See 138244 for more information. int argc; LPTSTR *argv = GetCommandArgs( &argc ); if ( argc > 1 ) { int n; for ( n = 1; n < argc; n++ ) { if ( 0 == _tcsnicmp( argv[n], _T("-headless"), 9 ) ) bHeadlessMode = TRUE; } } } if ( _ltot( (long)GetCurrentProcessId(),szParentProcessId, 10 ) && bHeadlessMode ) SetEnvironmentVariable( TEXT("ATTACHED_PARENT_PROCESSID"), szParentProcessId ); PROCESS_INFORMATION aProcessInfo; fSuccess = FALSE; fSuccess = CreateProcess( szTargetFileName, // When restarting office process only reuse bootstrap parameters fSuccess ? lpCommandLine : GetCommandLine(), NULL, NULL, TRUE, 0, NULL, NULL, &aStartupInfo, &aProcessInfo ); if ( fSuccess ) { DWORD dwWaitResult; do { // On Windows XP it seems as the desktop calls WaitForInputIdle after "OpenWidth" so we have to do so // as if we where processing any messages dwWaitResult = MsgWaitForMultipleObjects( 1, &aProcessInfo.hProcess, FALSE, INFINITE, QS_ALLEVENTS ); if ( WAIT_OBJECT_0 + 1 == dwWaitResult ) { MSG msg; PeekMessage( &msg, NULL, 0, 0, PM_REMOVE ); } } while ( WAIT_OBJECT_0 + 1 == dwWaitResult ); dwExitCode = 0; GetExitCodeProcess( aProcessInfo.hProcess, &dwExitCode ); CloseHandle( aProcessInfo.hProcess ); CloseHandle( aProcessInfo.hThread ); if ( lpCommandLine ) { delete lpCommandLine; lpCommandLine = 0; } } } while ( fSuccess && ::desktop::ExitHelper::E_CRASH_WITH_RESTART == dwExitCode ); return fSuccess ? dwExitCode : -1; } <commit_msg>INTEGRATION: CWS sb83 (1.14.2); FILE MERGED 2008/01/29 14:43:46 sb 1.14.2.1: #i84200# cuiloader was not used at all, cuiloader/genericloader.cxx has been moved to guiloader/genericloader.cxx' cuiloader"<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: officeloader.cxx,v $ * * $Revision: 1.15 $ * * last change: $Author: vg $ $Date: 2008-03-18 13:54:14 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * 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 * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_desktop.hxx" #define UNICODE #define _UNICODE #include <cstddef> #define WIN32_LEAN_AND_MEAN #if defined _MSC_VER #pragma warning(push, 1) #endif #include <windows.h> #include <shellapi.h> #if defined _MSC_VER #pragma warning(pop) #endif #include <tchar.h> #include <malloc.h> #include <string.h> #include <stdlib.h> #include <systools/win32/uwinapi.h> #include "rtl/string.h" #include "../../../source/inc/exithelper.hxx" #include "../extendloaderenvironment.hxx" #define PIPE_PREFIX TEXT("\\\\.\\pipe\\OSL_PIPE_") #define PIPE_POSTFIX TEXT("_SingleOfficeIPC_") #define PIPE_TERMINATION_SEQUENCE "InternalIPC::ProcessingDone" BOOL WINAPI ConvertSidToStringSid( PSID pSid, LPTSTR* StringSid ) { PSID_IDENTIFIER_AUTHORITY psia; DWORD dwSubAuthorities; DWORD dwSidRev=SID_REVISION; DWORD dwCounter; DWORD dwSidSize; // Validate the binary SID. if(!IsValidSid(pSid)) return FALSE; // Get the identifier authority value from the SID. psia = GetSidIdentifierAuthority(pSid); // Get the number of subauthorities in the SID. dwSubAuthorities = *GetSidSubAuthorityCount(pSid); // Compute the buffer length. // S-SID_REVISION- + IdentifierAuthority- + subauthorities- + NULL dwSidSize=(15 + 12 + (12 * dwSubAuthorities) + 1) * sizeof(TCHAR); *StringSid = (LPTSTR)LocalAlloc( LMEM_FIXED, dwSidSize ); // Add 'S' prefix and revision number to the string. dwSidSize=wsprintf(*StringSid, TEXT("S-%lu-"), dwSidRev ); // Add a SID identifier authority to the string. if ( (psia->Value[0] != 0) || (psia->Value[1] != 0) ) { dwSidSize+=wsprintf(*StringSid + lstrlen(*StringSid), TEXT("0x%02hx%02hx%02hx%02hx%02hx%02hx"), (USHORT)psia->Value[0], (USHORT)psia->Value[1], (USHORT)psia->Value[2], (USHORT)psia->Value[3], (USHORT)psia->Value[4], (USHORT)psia->Value[5]); } else { dwSidSize+=wsprintf(*StringSid + lstrlen(*StringSid), TEXT("%lu"), (ULONG)(psia->Value[5] ) + (ULONG)(psia->Value[4] << 8) + (ULONG)(psia->Value[3] << 16) + (ULONG)(psia->Value[2] << 24) ); } // Add SID subauthorities to the string. // for (dwCounter=0 ; dwCounter < dwSubAuthorities ; dwCounter++) { dwSidSize+=wsprintf(*StringSid + dwSidSize, TEXT("-%lu"), *GetSidSubAuthority(pSid, dwCounter) ); } return TRUE; } //--------------------------------------------------------------------------- static LPTSTR *GetCommandArgs( int *pArgc ) { #ifdef UNICODE return CommandLineToArgvW( GetCommandLineW(), pArgc ); #else *pArgc = __argc; return __argv; #endif } //--------------------------------------------------------------------------- #ifdef __MINGW32__ int WINAPI WinMain( HINSTANCE hInstance, HINSTANCE, LPSTR, int ) #else int WINAPI _tWinMain( HINSTANCE, HINSTANCE, LPTSTR, int ) #endif { TCHAR szTargetFileName[MAX_PATH] = TEXT(""); TCHAR szIniDirectory[MAX_PATH]; TCHAR szPerfTuneIniFile[MAX_PATH] = TEXT(""); STARTUPINFO aStartupInfo; desktop_win32::extendLoaderEnvironment(szTargetFileName, szIniDirectory); ZeroMemory( &aStartupInfo, sizeof(aStartupInfo) ); aStartupInfo.cb = sizeof(aStartupInfo); GetStartupInfo( &aStartupInfo ); // Get image path with same name but with .bin extension TCHAR szModuleFileName[MAX_PATH]; GetModuleFileName( NULL, szModuleFileName, MAX_PATH ); _TCHAR *lpLastSlash = _tcsrchr( szModuleFileName, '\\' ); if ( lpLastSlash ) { size_t len = lpLastSlash - szModuleFileName + 1; _tcsncpy( szPerfTuneIniFile, szModuleFileName, len ); _tcsncpy( szPerfTuneIniFile + len, _T("perftune.ini"), sizeof(szPerfTuneIniFile)/sizeof(szPerfTuneIniFile[0]) - len ); } // Create process with same command line, environment and stdio handles which // are directed to the created pipes DWORD dwExitCode = (DWORD)-1; BOOL fSuccess = FALSE; LPTSTR lpCommandLine = NULL; int argc = 0; LPTSTR * argv = NULL; bool first = true; do { TCHAR szKey[32]; GetPrivateProfileString( TEXT("PerformanceTuning"), TEXT("FastPipeCommunication"), TEXT("0"), szKey, elementsof(szKey), szPerfTuneIniFile ); if ( 0 == _tcscmp( szKey, TEXT("1") ) ) { HANDLE hProcessToken; if ( OpenProcessToken( GetCurrentProcess(), TOKEN_QUERY, &hProcessToken ) ) { TCHAR szPipeName[4096]; DWORD dwTokenLength = 0; fSuccess = GetTokenInformation( hProcessToken, TokenUser, NULL, dwTokenLength, &dwTokenLength ); PVOID pTokenInfo = _alloca(dwTokenLength); fSuccess = GetTokenInformation( hProcessToken, TokenUser, pTokenInfo, dwTokenLength, &dwTokenLength ); CloseHandle( hProcessToken ); PSID pSid = ((PTOKEN_USER)pTokenInfo)->User.Sid; LPTSTR szUserIdent = NULL; TCHAR szSUPD[11] = TEXT("0"); fSuccess = ConvertSidToStringSid( pSid, &szUserIdent ); _tcsncpy( szPipeName, PIPE_PREFIX, elementsof(szPipeName) ); _tcsncat( szPipeName, szUserIdent, elementsof(szPipeName) - _tcslen(szPipeName) - 1 ); _tcsncat( szPipeName, PIPE_POSTFIX, elementsof(szPipeName) - _tcslen(szPipeName) - 1 ); _tcsncat( szPipeName, _ultot( SUPD, szSUPD, 10), elementsof(szPipeName) - _tcslen(szPipeName) - 1 ); LocalFree( szUserIdent ); HANDLE hPipe = CreateFile( szPipeName, GENERIC_READ|GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); if ( INVALID_HANDLE_VALUE != hPipe ) { DWORD dwBytesWritten; int argc = 0; LPWSTR *argv = CommandLineToArgvW( GetCommandLine(), &argc ); fSuccess = WriteFile( hPipe, RTL_CONSTASCII_STRINGPARAM("InternalIPC::Arguments"), &dwBytesWritten, NULL ); for ( int argn = 1; fSuccess && argn < argc; argn++ ) { CHAR szBuffer[4096]; int n = WideCharToMultiByte( CP_UTF8, 0, argv[argn], -1, szBuffer, sizeof(szBuffer), NULL, NULL ); char b[RTL_CONSTASCII_LENGTH(",") + 2 * ((sizeof szBuffer) - 1)] = ","; // hopefully does not overflow char * p = b + RTL_CONSTASCII_LENGTH(","); for (int i = 0; i < n - 1; ++i) // cannot underflow (n >= 0) { char c = szBuffer[i]; switch (c) { case '\0': *p++ = '\\'; *p++ = '0'; break; case ',': *p++ = '\\'; *p++ = ','; break; case '\\': *p++ = '\\'; *p++ = '\\'; break; default: *p++ = c; break; } } fSuccess = WriteFile( hPipe, b, p - b, &dwBytesWritten, NULL ); } if ( fSuccess ) { fSuccess = WriteFile( hPipe, "", 1, &dwBytesWritten, NULL ); if ( fSuccess ) { DWORD dwBytesRead = 0; char *pBuffer = (char *)_alloca( sizeof(PIPE_TERMINATION_SEQUENCE) ); fSuccess = ReadFile( hPipe, pBuffer, sizeof(PIPE_TERMINATION_SEQUENCE) - 1, &dwBytesRead, NULL ); if ( fSuccess ) { pBuffer[dwBytesRead] = 0; if ( 0 != strcmp( PIPE_TERMINATION_SEQUENCE, pBuffer ) ) fSuccess = FALSE; } } } CloseHandle( hPipe ); return fSuccess ? 0 : -1; } } } if (first) { argv = GetCommandArgs(&argc); std::size_t n = _tcslen(argv[0]) + 2; for (int i = 1; i < argc; ++i) { n += _tcslen(argv[i]) + 3; } n += MY_LENGTH(" \"-env:INIFILEPATH=") + _tcslen(szIniDirectory) + MY_LENGTH("soffice.ini\""); lpCommandLine = new TCHAR[n + 1]; } _tcscpy(lpCommandLine, _T("\"")); _tcscat(lpCommandLine, argv[0]); for (int i = 1; i < argc; ++i) { if (first || _tcsncmp(argv[i], MY_STRING(_T("-env:"))) == 0) { _tcscat(lpCommandLine, _T("\" \"")); _tcscat(lpCommandLine, argv[i]); } } _tcscat(lpCommandLine, _T("\" \"-env:INIFILEPATH=")); _tcscat(lpCommandLine, szIniDirectory); _tcscat(lpCommandLine, _T("soffice.ini\"")); first = false; TCHAR szParentProcessId[64]; // This is more than large enough for a 128 bit decimal value BOOL bHeadlessMode( FALSE ); { // Check command line arguments for "-headless" parameter. We only // set the environment variable "ATTACHED_PARENT_PROCESSID" for the headless // mode as self-destruction of the soffice.bin process can lead to // certain side-effects (log-off can result in data-loss, ".lock" is not deleted. // See 138244 for more information. int argc; LPTSTR *argv = GetCommandArgs( &argc ); if ( argc > 1 ) { int n; for ( n = 1; n < argc; n++ ) { if ( 0 == _tcsnicmp( argv[n], _T("-headless"), 9 ) ) bHeadlessMode = TRUE; } } } if ( _ltot( (long)GetCurrentProcessId(),szParentProcessId, 10 ) && bHeadlessMode ) SetEnvironmentVariable( TEXT("ATTACHED_PARENT_PROCESSID"), szParentProcessId ); PROCESS_INFORMATION aProcessInfo; fSuccess = CreateProcess( szTargetFileName, lpCommandLine, NULL, NULL, TRUE, 0, NULL, NULL, &aStartupInfo, &aProcessInfo ); if ( fSuccess ) { DWORD dwWaitResult; do { // On Windows XP it seems as the desktop calls WaitForInputIdle after "OpenWidth" so we have to do so // as if we where processing any messages dwWaitResult = MsgWaitForMultipleObjects( 1, &aProcessInfo.hProcess, FALSE, INFINITE, QS_ALLEVENTS ); if ( WAIT_OBJECT_0 + 1 == dwWaitResult ) { MSG msg; PeekMessage( &msg, NULL, 0, 0, PM_REMOVE ); } } while ( WAIT_OBJECT_0 + 1 == dwWaitResult ); dwExitCode = 0; GetExitCodeProcess( aProcessInfo.hProcess, &dwExitCode ); CloseHandle( aProcessInfo.hProcess ); CloseHandle( aProcessInfo.hThread ); } } while ( fSuccess && ::desktop::ExitHelper::E_CRASH_WITH_RESTART == dwExitCode ); delete[] lpCommandLine; return fSuccess ? dwExitCode : -1; } <|endoftext|>
<commit_before>#include "systick.h" #include "peripheraltypes.h" #include "nvic.h" #include "clocks.h" #include "minimath.h" //safe division functions #include "tableofpointers.h" MakeRefTable(SystemTicker); namespace SystemTimer { //when the following were simple static's Rowley would not show them. u32 milliTime(0); //storage for global tick time. u32 macroTime(0); //extended range tick time } using namespace SystemTimer; HandleFault(15){ //15: system tick ++milliTime; if(milliTime == 0) { //we have rolled over and anything waiting on a particular value will have failed ++macroTime;//but rollover of this is not going to happen for decades. } ForRefs(SystemTicker){ (**it)(); } } struct SysTicker { volatile unsigned int enableCounting : 1; //enable counting unsigned int enableInterrupt : 1; //enable interrupt unsigned int fullspeed : 1; //1: main clock, 0: that divided by 8 (St's choice, ignore their naming) unsigned int : 16 - 3; volatile unsigned int rolledOver : 1; //indicates rollover, clears on read unsigned int : 32 - 17; u32 reload; //(only 24 bits are implemented) cycle = this+1. u32 value; // //following is info chip provides to user, unsigned int tenms : 24; //value to get 100Hz unsigned int : 30 - 24; unsigned int refIsApproximate : 1; unsigned int noref : 1; //1= no ref clock bool start(u32 reloader){ enableInterrupt = 0; enableCounting = 0; fullspeed = 1; reload = reloader - 1; //for more precise periodicity bool hack = rolledOver; //reading clears it enableCounting = 1; enableInterrupt = 1; return hack; //just to ensure optimizer doesn't eliminate read of rolledOver } /* start */ u32 ticksPerSecond(void){ u32 effectiveDivider = reload + 1; if(!fullspeed) { effectiveDivider *= 8; } return rate(clockRate(-1), effectiveDivider); } u32 ticksForMicros(u32 us){ return (us * ticksPerSecond()) / 1000000; } u32 ticksForMillis(u32 ms){ return (ms * ticksPerSecond()) / 1000; } u32 ticksForHertz(float hz){ return ratio(ticksPerSecond(), hz); } }; soliton(SysTicker, 0xE000E010); namespace SystemTimer { /** start ticking at the given rate.*/ void startPeriodicTimer(u32 persecond){ //todo:2 fullspeed is hardcoded to 1 downstream of here, need to take care of that. theSysTicker.fullspeed = 1; if(!theSysTicker.fullspeed) { persecond *= 8; // times 8 here instead of /8 in the rate computation. } u32 num=clockRate(-1); theSysTicker.start(rate(num, persecond)); } double secondsForTicks(u32 ticks){ return ratio(double(ticks), double(theSysTicker.ticksPerSecond())); } double secondsForLongTime(u64 ticks){ return ratio(double(ticks), double(theSysTicker.ticksPerSecond())); } u32 ticksForSeconds(float sec){ if(sec<=0){ return 0; } return theSysTicker.ticksForMillis(u32(sec * 1000)); } u32 ticksForMillis(int ms){ if(ms<=0){ return 0; } return theSysTicker.ticksForMillis(ms); } u32 ticksForMicros(int ms){ if(ms<=0){ return 0; } return theSysTicker.ticksForMicros(ms); } u32 ticksForHertz(float hz){ return theSysTicker.ticksForHertz(hz); } /** time since last rollover, must look at clock configuration to know what the unit is. */ u32 snapTime(void){ return theSysTicker.reload - theSysTicker.value; //'tis a downcounter, want time since reload. } u32 snapTickTime(void){ u32 snapms; u32 snaptick; theSysTicker.enableCounting = 0; //can't use bitlock on a field in a struct :( snapms=milliTime; snaptick=theSysTicker.value; theSysTicker.enableCounting = 1; //add some to systick to compensate for the dead time of this routine. snaptick-=6;//counted clocks between the disable and enable operations //todo: might have skipped a tick, and failed to execute the isr which could cause some usages to have an unexpected delay or extension. return ((snapms + 1) * (theSysTicker.reload + 1)) - snaptick; } u64 snapLongTime(void){//this presumes little endian 64 bit integer. theSysTicker.enableCounting = 0; //can't use bitlock on a field in a struct :( u64 retval=milliTime |(u64(macroTime)<<32);//need a hack to get compiler to be efficient here. theSysTicker.enableCounting = 1; //todo:3 add some to systick to compensate for the dead time of this routine. return retval; } } //end of file <commit_msg>commentary<commit_after>#include "systick.h" #include "peripheraltypes.h" #include "nvic.h" #include "clocks.h" #include "minimath.h" //safe division functions #include "tableofpointers.h" MakeRefTable(SystemTicker); namespace SystemTimer { //when the following were simple static's Rowley would not show them. static u32 milliTime(0); //storage for global tick time. static u32 macroTime(0); //extended range tick time } using namespace SystemTimer; HandleFault(15){ //15: system tick ++milliTime; if(milliTime == 0) { //we have rolled over and anything waiting on a particular value will have failed ++macroTime;//but rollover of this is not going to happen for decades. } ForRefs(SystemTicker){ (**it)(); } } struct SysTicker { volatile unsigned int enableCounting : 1; //enable counting unsigned int enableInterrupt : 1; //enable interrupt //note: some implementation do NOT implement this bit! Hopefully it read back as 0 even if you try to set it. unsigned int fullspeed : 1; //1: main clock, 0: that divided by 8 (St's choice, ignore their naming) unsigned int : 16 - 3; volatile unsigned int rolledOver : 1; //indicates rollover, clears on read unsigned int : 32 - 17; u32 reload; //(only 24 bits are implemented) cycle = this+1. u32 value; // //following is info chip provides to user, some manufacturers are off by a power of 10 here. unsigned int tenms : 24; //value to get 100Hz unsigned int : 30 - 24; unsigned int refIsApproximate : 1; unsigned int noref : 1; //1= no ref clock bool start(u32 reloader){ enableInterrupt = 0; enableCounting = 0; fullspeed = 1; reload = reloader - 1; //for more precise periodicity bool hack = rolledOver; //reading clears it enableCounting = 1; enableInterrupt = 1; return hack; //just to ensure optimizer doesn't eliminate read of rolledOver } /* start */ u32 ticksPerSecond(void){ u32 effectiveDivider = reload + 1; if(!fullspeed) { effectiveDivider *= 8; } return rate(clockRate(-1), effectiveDivider); } u32 ticksForMicros(u32 us){ return (us * ticksPerSecond()) / 1000000; } u32 ticksForMillis(u32 ms){ return (ms * ticksPerSecond()) / 1000; } u32 ticksForHertz(float hz){ return ratio(ticksPerSecond(), hz); } }; soliton(SysTicker, 0xE000E010); namespace SystemTimer { /** start ticking at the given rate.*/ void startPeriodicTimer(u32 persecond){ //todo:2 fullspeed is hardcoded to 1 downstream of here, need to take care of that. theSysTicker.fullspeed = 1; if(!theSysTicker.fullspeed) { persecond *= 8; // times 8 here instead of /8 in the rate computation. } u32 num=clockRate(-1); theSysTicker.start(rate(num, persecond)); } double secondsForTicks(u32 ticks){ return ratio(double(ticks), double(theSysTicker.ticksPerSecond())); } double secondsForLongTime(u64 ticks){ return ratio(double(ticks), double(theSysTicker.ticksPerSecond())); } u32 ticksForSeconds(float sec){ if(sec<=0){ return 0; } return theSysTicker.ticksForMillis(u32(sec * 1000)); } u32 ticksForMillis(int ms){ if(ms<=0){ return 0; } return theSysTicker.ticksForMillis(ms); } u32 ticksForMicros(int ms){ if(ms<=0){ return 0; } return theSysTicker.ticksForMicros(ms); } u32 ticksForHertz(float hz){ return theSysTicker.ticksForHertz(hz); } /** time since last rollover, must look at clock configuration to know what the unit is. */ u32 snapTime(void){ return theSysTicker.reload - theSysTicker.value; //'tis a downcounter, want time since reload. } u32 snapTickTime(void){ //#some of the superficially gratuitous stuff in here exists to minimize the clocks spent with counting disabled. u32 snapms; u32 snaptick; theSysTicker.enableCounting = 0; //can't use bitlock on a field in a struct :( snapms=milliTime; snaptick=theSysTicker.value; theSysTicker.enableCounting = 1; //add some to systick to compensate for the dead time of this routine. snaptick-=6;//counted clocks between the disable and enable operations //todo: might have skipped a tick, and failed to execute the isr which could cause some usages to have an unexpected delay or extension. return ((snapms + 1) * (theSysTicker.reload + 1)) - snaptick; } u64 snapLongTime(void){//this presumes little endian 64 bit integer. theSysTicker.enableCounting = 0; //can't use bitlock on a field in a struct :( u64 retval=milliTime |(u64(macroTime)<<32);//need a hack to get compiler to be efficient here. theSysTicker.enableCounting = 1; //todo:3 add some to systick to compensate for the dead time of this routine. return retval; } } //end of file <|endoftext|>
<commit_before>#include <iostream> #include <iomanip> // << fixed << setprecision(xxx) #include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ; #include <vector> #include <string> // to_string(nnn) // substr(m, n) // stoi(nnn) #include <complex> #include <tuple> // get<n>(xxx) #include <queue> #include <stack> #include <map> // if (M.find(key) != M.end()) { } #include <set> // S.insert(M); // if (S.find(key) != S.end()) { } // for (auto it=S.begin(); it != S.end(); it++) { } // auto it = S.lower_bound(M); #include <random> // random_device rd; mt19937 mt(rd()); #include <cctype> #include <cassert> #include <cmath> #include <cstdio> #include <cstdlib> // atoi(xxx) using namespace std; #define DEBUG 0 // change 0 -> 1 if we need debug. // insert #if<tab> by my emacs. #if DEBUG == 1 ... #end typedef long long ll; // const int dx[4] = {1, 0, -1, 0}; // const int dy[4] = {0, 1, 0, -1}; // const int C = 1e6+10; // const ll M = 1000000007; int N, M; int X[100010]; int cnt[100010]; int mod[100010][2]; int get_cnt(int x) { return mod[x][0] + 2 * mod[x][1]; } int same(int x) { int c = get_cnt(x); return c/2; } int odd(int x) { int c = get_cnt(x); int d = get_cnt(M - x); if (c < d) { swap(c, d); x = M - x; } int ans = d; int sa = c - d; if (sa <= mod[x][0]) { ans += mod[x][1]; return ans; } else { ans += (mod[x][1] * 2 - sa)/2; return ans; } } int main () { cin >> N >> M; for (auto i = 0; i < N; ++i) { cin >> X[i]; } fill(cnt, cnt+100010, 0); for (auto i = 0; i < N; ++i) { cnt[X[i]]++; } fill(&mod[0][0], &mod[0][0]+100010*2, 0); for (auto i = 0; i < 100010; ++i) { mod[i%M][0] += cnt[i]%2; mod[i%M][1] += cnt[i]/2; } int ans = 0; ans += same(0); if (M%2 == 0) { ans += same(M/2); } for (auto i = 1; i < M/2; ++i) { ans += odd(i); } cout << ans << endl; } <commit_msg>tried D.cpp to 'D'<commit_after>#include <iostream> #include <iomanip> // << fixed << setprecision(xxx) #include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ; #include <vector> #include <string> // to_string(nnn) // substr(m, n) // stoi(nnn) #include <complex> #include <tuple> // get<n>(xxx) #include <queue> #include <stack> #include <map> // if (M.find(key) != M.end()) { } #include <set> // S.insert(M); // if (S.find(key) != S.end()) { } // for (auto it=S.begin(); it != S.end(); it++) { } // auto it = S.lower_bound(M); #include <random> // random_device rd; mt19937 mt(rd()); #include <cctype> #include <cassert> #include <cmath> #include <cstdio> #include <cstdlib> // atoi(xxx) using namespace std; #define DEBUG 0 // change 0 -> 1 if we need debug. // insert #if<tab> by my emacs. #if DEBUG == 1 ... #end typedef long long ll; // const int dx[4] = {1, 0, -1, 0}; // const int dy[4] = {0, 1, 0, -1}; // const int C = 1e6+10; // const ll M = 1000000007; int N, M; int X[100010]; int cnt[100010]; int mod[100010][2]; int get_cnt(int x) { return mod[x][0] + 2 * mod[x][1]; } int same(int x) { int c = get_cnt(x); return c/2; } int odd(int x) { int c = get_cnt(x); int d = get_cnt(M - x); if (c < d) { swap(c, d); x = M - x; } int ans = d; if (d <= mod[x][0]) { ans += mod[x][1]; return ans; } else { ans += (mod[x][1] * 2 - (d - mod[x][0]))/2; return ans; } } int main () { cin >> N >> M; for (auto i = 0; i < N; ++i) { cin >> X[i]; } fill(cnt, cnt+100010, 0); for (auto i = 0; i < N; ++i) { cnt[X[i]]++; } fill(&mod[0][0], &mod[0][0]+100010*2, 0); for (auto i = 0; i < 100010; ++i) { mod[i%M][0] += cnt[i]%2; mod[i%M][1] += cnt[i]/2; } int ans = 0; ans += same(0); if (M%2 == 0) { ans += same(M/2); } for (auto i = 1; i < M/2; ++i) { ans += odd(i); } cout << ans << endl; } <|endoftext|>
<commit_before> #include <stdlib.h> /* srand, rand */ #include <chrono> #include <iostream> #include <fstream> #include <string> #include <algorithm> #include <unsupported/Eigen/SparseExtra> #include "bpmf.h" using namespace std; using namespace Eigen; typedef SparseMatrix<double> SparseMatrixD; const int num_feat = 32; const int alpha = 2; const int nsims = 20; const int burnin = 5; double mean_rating = .0; SparseMatrixD M, P; typedef Matrix<double, num_feat, 1> VectorNd; typedef Matrix<double, num_feat, num_feat> MatrixNNd; typedef Matrix<double, num_feat, Dynamic> MatrixNXd; VectorNd mu_u; VectorNd mu_m; MatrixNNd Lambda_u; MatrixNNd Lambda_m; MatrixNXd sample_u; MatrixNXd sample_m; // parameters of Inv-Whishart distribution (see paper for details) MatrixNNd WI_u; const int b0_u = 2; const int df_u = num_feat; VectorNd mu0_u; MatrixNNd WI_m; const int b0_m = 2; const int df_m = num_feat; VectorNd mu0_m; void init() { mean_rating = M.sum() / M.nonZeros(); Lambda_u.setIdentity(); Lambda_m.setIdentity(); sample_u = MatrixNXd(num_feat,M.rows()); sample_m = MatrixNXd(num_feat,M.cols()); sample_u.setZero(); sample_m.setZero(); // parameters of Inv-Whishart distribution (see paper for details) WI_u.setIdentity(); mu0_u.setZero(); WI_m.setIdentity(); mu0_m.setZero(); } pair<double,double> eval_probe_vec(const MatrixNXd &sample_m, const MatrixNXd &sample_u, double mean_rating) { unsigned n = P.nonZeros(); unsigned correct = 0; double diff = .0; for (int k=0; k<P.outerSize(); ++k) for (SparseMatrix<double>::InnerIterator it(P,k); it; ++it) { double prediction = sample_m.col(it.col()).dot(sample_u.col(it.row())) + mean_rating; //cout << "prediction: " << prediction - mean_rating << " + " << mean_rating << " = " << prediction << endl; //cout << "actual: " << it.value() << endl; correct += (it.value() < log10(200)) == (prediction < log10(200)); diff += abs(it.value() - prediction); } return std::make_pair((double)correct / n, diff / n); } void sample_movie(MatrixNXd &s, int mm, const SparseMatrixD &mat, double mean_rating, const MatrixNXd &samples, int alpha, const VectorNd &mu_u, const MatrixNNd &Lambda_u) { int i = 0; MatrixNNd MM; MM.setZero(); VectorNd rr; rr.setZero(); for (SparseMatrixD::InnerIterator it(mat,mm); it; ++it, ++i) { // cout << "M[" << it.row() << "," << it.col() << "] = " << it.value() << endl; auto col = samples.col(it.row()); MM += col * col.transpose(); rr += col * ((it.value() - mean_rating) * alpha); } auto MMs = alpha * MM; MatrixNNd covar = (Lambda_u + MMs).inverse(); auto U = Lambda_u * mu_u; auto mu = covar * (rr + U); MatrixNNd chol = covar.llt().matrixL(); auto r = nrandn(num_feat); s.col(mm) = chol * r + mu; #ifdef TEST_SAMPLE cout << "movie " << mm << ":" << result.cols() << " x" << result.rows() << endl; cout << "mean rating " << mean_rating << endl; cout << "E = [" << E << "]" << endl; cout << "rr = [" << rr << "]" << endl; cout << "MM = [" << MM << "]" << endl; cout << "Lambda_u = [" << Lambda_u << "]" << endl; cout << "covar = [" << covar << "]" << endl; cout << "mu = [" << mu << "]" << endl; cout << "chol = [" << chol << "]" << endl; cout << "rand = [" << r <<"]" << endl; cout << "result = [" << result << "]" << endl; #endif } #ifdef TEST_SAMPLE void test() { MatrixNXd sample_u(M.rows()); MatrixNXd sample_m(M.cols()); mu_m.setZero(); Lambda_m.setIdentity(); sample_u.setConstant(2.0); Lambda_m *= 0.5; sample_m.col(0) = sample_movie(0, M, mean_rating, sample_u, alpha, mu_m, Lambda_m); } #else void run() { auto start = chrono::duration_cast<chrono::duration<double>>(chrono::high_resolution_clock::now().time_since_epoch()).count(); SparseMatrixD Mt = M.transpose(); std::cout << "Sampling" << endl; for(int i=0; i<nsims; ++i) { // Sample from movie hyperparams tie(mu_m, Lambda_m) = CondNormalWishart(sample_m, mu0_m, b0_m, WI_m, df_m); // Sample from user hyperparams tie(mu_u, Lambda_u) = CondNormalWishart(sample_u, mu0_u, b0_u, WI_u, df_u); #pragma omp parallel for for(int mm = 0; mm < M.cols(); ++mm) { sample_movie(sample_m, mm, M, mean_rating, sample_u, alpha, mu_m, Lambda_m); } #pragma omp parallel for for(int uu = 0; uu < M.rows(); ++uu) { sample_movie(sample_u, uu, Mt, mean_rating, sample_m, alpha, mu_u, Lambda_u); } auto eval = eval_probe_vec(sample_m, sample_u, mean_rating); double norm_u = sample_u.norm(); double norm_m = sample_m.norm(); auto end = chrono::duration_cast<chrono::duration<double>>(chrono::high_resolution_clock::now().time_since_epoch()).count(); auto elapsed = end - start; double samples_per_sec = (i + 1) * (M.rows() + M.cols()) / elapsed; printf("Iteration %d:\t num_correct: %3.2f%%\tavg_diff: %3.2f\tFU(%6.2f)\tFM(%6.2f)\tSamples/sec: %6.2f\n", i, 100*eval.first, eval.second, norm_u, norm_m, samples_per_sec); } } #endif int main(int argc, char *argv[]) { assert(argv[1] && argv[2] && "filename missing"); Eigen::initParallel(); Eigen::setNbThreads(1); loadMarket(M, argv[1]); loadMarket(P, argv[2]); init(); #ifdef TEST_SAMPLE test(); #else run(); #endif return 0; } <commit_msg>c++: random number generator as Eigen expr<commit_after> #include <stdlib.h> /* srand, rand */ #include <chrono> #include <iostream> #include <fstream> #include <string> #include <algorithm> #include <unsupported/Eigen/SparseExtra> #include "bpmf.h" using namespace std; using namespace Eigen; typedef SparseMatrix<double> SparseMatrixD; const int num_feat = 32; const int alpha = 2; const int nsims = 20; const int burnin = 5; double mean_rating = .0; SparseMatrixD M, P; typedef Matrix<double, num_feat, 1> VectorNd; typedef Matrix<double, num_feat, num_feat> MatrixNNd; typedef Matrix<double, num_feat, Dynamic> MatrixNXd; VectorNd mu_u; VectorNd mu_m; MatrixNNd Lambda_u; MatrixNNd Lambda_m; MatrixNXd sample_u; MatrixNXd sample_m; // parameters of Inv-Whishart distribution (see paper for details) MatrixNNd WI_u; const int b0_u = 2; const int df_u = num_feat; VectorNd mu0_u; MatrixNNd WI_m; const int b0_m = 2; const int df_m = num_feat; VectorNd mu0_m; void init() { mean_rating = M.sum() / M.nonZeros(); Lambda_u.setIdentity(); Lambda_m.setIdentity(); sample_u = MatrixNXd(num_feat,M.rows()); sample_m = MatrixNXd(num_feat,M.cols()); sample_u.setZero(); sample_m.setZero(); // parameters of Inv-Whishart distribution (see paper for details) WI_u.setIdentity(); mu0_u.setZero(); WI_m.setIdentity(); mu0_m.setZero(); } pair<double,double> eval_probe_vec(const MatrixNXd &sample_m, const MatrixNXd &sample_u, double mean_rating) { unsigned n = P.nonZeros(); unsigned correct = 0; double diff = .0; for (int k=0; k<P.outerSize(); ++k) for (SparseMatrix<double>::InnerIterator it(P,k); it; ++it) { double prediction = sample_m.col(it.col()).dot(sample_u.col(it.row())) + mean_rating; //cout << "prediction: " << prediction - mean_rating << " + " << mean_rating << " = " << prediction << endl; //cout << "actual: " << it.value() << endl; correct += (it.value() < log10(200)) == (prediction < log10(200)); diff += abs(it.value() - prediction); } return std::make_pair((double)correct / n, diff / n); } double randn(double) { static mt19937 rng; static normal_distribution<> nd; return nd(rng); } void sample_movie(MatrixNXd &s, int mm, const SparseMatrixD &mat, double mean_rating, const MatrixNXd &samples, int alpha, const VectorNd &mu_u, const MatrixNNd &Lambda_u) { int i = 0; MatrixNNd MM; MM.setZero(); VectorNd rr; rr.setZero(); for (SparseMatrixD::InnerIterator it(mat,mm); it; ++it, ++i) { // cout << "M[" << it.row() << "," << it.col() << "] = " << it.value() << endl; auto col = samples.col(it.row()); MM += col * col.transpose(); rr += col * ((it.value() - mean_rating) * alpha); } auto MMs = alpha * MM; MatrixNNd covar = (Lambda_u + MMs).inverse(); auto U = Lambda_u * mu_u; auto mu = covar * (rr + U); MatrixNNd chol = covar.llt().matrixL(); auto r = VectorXd::NullaryExpr(num_feat, ptr_fun(randn)); s.col(mm) = chol * r + mu; #ifdef TEST_SAMPLE cout << "movie " << mm << ":" << result.cols() << " x" << result.rows() << endl; cout << "mean rating " << mean_rating << endl; cout << "E = [" << E << "]" << endl; cout << "rr = [" << rr << "]" << endl; cout << "MM = [" << MM << "]" << endl; cout << "Lambda_u = [" << Lambda_u << "]" << endl; cout << "covar = [" << covar << "]" << endl; cout << "mu = [" << mu << "]" << endl; cout << "chol = [" << chol << "]" << endl; cout << "rand = [" << r <<"]" << endl; cout << "result = [" << result << "]" << endl; #endif } #ifdef TEST_SAMPLE void test() { MatrixNXd sample_u(M.rows()); MatrixNXd sample_m(M.cols()); mu_m.setZero(); Lambda_m.setIdentity(); sample_u.setConstant(2.0); Lambda_m *= 0.5; sample_m.col(0) = sample_movie(0, M, mean_rating, sample_u, alpha, mu_m, Lambda_m); } #else void run() { auto start = chrono::duration_cast<chrono::duration<double>>(chrono::high_resolution_clock::now().time_since_epoch()).count(); SparseMatrixD Mt = M.transpose(); std::cout << "Sampling" << endl; for(int i=0; i<nsims; ++i) { // Sample from movie hyperparams tie(mu_m, Lambda_m) = CondNormalWishart(sample_m, mu0_m, b0_m, WI_m, df_m); // Sample from user hyperparams tie(mu_u, Lambda_u) = CondNormalWishart(sample_u, mu0_u, b0_u, WI_u, df_u); #pragma omp parallel for for(int mm = 0; mm < M.cols(); ++mm) { sample_movie(sample_m, mm, M, mean_rating, sample_u, alpha, mu_m, Lambda_m); } #pragma omp parallel for for(int uu = 0; uu < M.rows(); ++uu) { sample_movie(sample_u, uu, Mt, mean_rating, sample_m, alpha, mu_u, Lambda_u); } auto eval = eval_probe_vec(sample_m, sample_u, mean_rating); double norm_u = sample_u.norm(); double norm_m = sample_m.norm(); auto end = chrono::duration_cast<chrono::duration<double>>(chrono::high_resolution_clock::now().time_since_epoch()).count(); auto elapsed = end - start; double samples_per_sec = (i + 1) * (M.rows() + M.cols()) / elapsed; printf("Iteration %d:\t num_correct: %3.2f%%\tavg_diff: %3.2f\tFU(%6.2f)\tFM(%6.2f)\tSamples/sec: %6.2f\n", i, 100*eval.first, eval.second, norm_u, norm_m, samples_per_sec); } } #endif int main(int argc, char *argv[]) { assert(argv[1] && argv[2] && "filename missing"); Eigen::initParallel(); Eigen::setNbThreads(1); loadMarket(M, argv[1]); loadMarket(P, argv[2]); init(); #ifdef TEST_SAMPLE test(); #else run(); #endif return 0; } <|endoftext|>
<commit_before>#include <iostream> #include <vector> // other function style int square1(int x) { return x * x; } auto square(int x) -> int { return x * x; } // no return void disp(const std::string& s) { std::string buf = "disp: " + s + "\n"; printf(buf.c_str()); } int abs1(int x) { if (x >= 0) { return x; } return -x; } int abs(int x) { return x >= 0 ? x : -x; } template <class T> std::string to_str(T t) { return std::to_string(t); } int main() { /* * comment */ std::cout << "Hello, World!" << std::endl; // comment const int a = square(3); const std::string s = "abc"; std::cout << a << std::endl; disp("Hello World"); int one = 1; int& b = one; b = 2; disp(to_str(one)); disp(to_str(abs(-3))); const std::vector<int> v = {1, 2, 3}; // normal for (int i = 0; i < v.size(); ++i) { disp(to_str(v[i])); } // simple for (const int x: v) { disp(to_str(x)); } return 0; }<commit_msg>Add mutable vector<commit_after>#include <iostream> #include <vector> // other function style int square1(int x) { return x * x; } auto square(int x) -> int { return x * x; } // no return void disp(const std::string& s) { std::string buf = "disp: " + s + "\n"; printf(buf.c_str()); } int abs1(int x) { if (x >= 0) { return x; } return -x; } int abs(int x) { return x >= 0 ? x : -x; } template <class T> std::string to_str(T t) { return std::to_string(t); } int main() { /* * comment */ std::cout << "Hello, World!" << std::endl; // comment const int a = square(3); const std::string s = "abc"; std::cout << a << std::endl; disp("Hello World"); int one = 1; int& b = one; b = 2; disp(to_str(one)); disp(to_str(abs(-3))); const std::vector<int> v = {1, 2, 3}; // get first disp(to_str(v.front())); // get last disp(to_str(v.back())); // cannot const std::vector<int> vv = {1,2,3}; vv.push_back(4); disp(to_str(vv.back())); vv.pop_back(); disp(to_str(vv.back())); vv.assign({4,5,6}); disp(to_str(vv.back())); // normal for (int i = 0; i < v.size(); ++i) { disp(to_str(v[i])); } // simple for (const int x: v) { disp(to_str(x)); } return 0; }<|endoftext|>
<commit_before>#include "special_la.h" #include "fastlib/fastlib_int.h" int main(int argc, char *argv[]){ fx_init(argc,argv,NULL); Vector diag_mat; Matrix lower_triang; Matrix usual_mat; diag_mat.Init(3); diag_mat[0]=1; diag_mat[1]=1; diag_mat[2]=3; lower_triang.Init(2,2); lower_triang.SetZero(); lower_triang.set(0,0,1); lower_triang.set(1,0,2);; lower_triang.set(1,1,4); usual_mat.Init(3,2); usual_mat.set(0,0,1); usual_mat.set(1,0,2); usual_mat.set(2,0,3); usual_mat.set(0,1,3); usual_mat.set(1,1,4); usual_mat.set(2,1,5); Matrix upper_triang_mat; upper_triang_mat.Init(2,3); upper_triang_mat.set(0,0,1); upper_triang_mat.set(1,0,0); upper_triang_mat.set(0,1,2); upper_triang_mat.set(1,1,4); upper_triang_mat.set(0,2,3); upper_triang_mat.set(1,2,5); printf("Upper triangular matrix is..\n"); upper_triang_mat.PrintDebug(); printf("usual matrix is...\n"); usual_mat.PrintDebug(); //PostMultiply with lower triangular //special_la::PreMultiplyLowerTriangMatrixInit(lower_triang,usual_mat,&res_mat); //printf("Will call the function...\n"); // printf("The result is...\n"); // res_mat.PrintDebug(); //Post Multiply with upper triang matrix //special_la::PostMultiplyUpperTriangMatrixInit(usual_mat,upper_triang_mat, // &res_mat); Matrix L_mat; L_mat.Init(3,1); L_mat.set(0,0,1); L_mat.set(1,0,2); L_mat.set(2,0,3); ArrayList <index_t> perm; perm.Init(3); perm[0]=0; perm[1]=1; perm[2]=2; Vector diag; diag.Init(3); diag[0]=2; diag[1]=2; diag[2]=2; Vector alpha; alpha.Init(3); alpha[0]=1; alpha[1]=2; alpha[2]=3; printf("Everything initialized. Will do matrix inverse vector calculation...\n"); Vector res; //special_la::MatrixInverseTimesVectorInit(L_mat,diag,alpha,&res); Matrix chol_factor; chol_factor.Init(3,1); chol_factor.set(0,0,2); chol_factor.set(1,0,3); chol_factor.set(2,0,1); ArrayList <index_t > perm_mat; perm_mat.Init(3); perm_mat[0]=2; perm_mat[1]=0; perm_mat[2]=1; special_la::PostMultiplyMatrixWithVectorGivenCholeskyInit(chol_factor,perm_mat,alpha,&res); Vector test; test.Init(3); test[0]=1; test[1]=2; test[2]=3; test.PrintDebug(); } <commit_msg>Working codes<commit_after>#include "special_la.h" #include "fastlib/fastlib_int.h" int main(int argc, char *argv[]){ fx_init(argc,argv,NULL); Vector diag_mat; Matrix lower_triang; Matrix usual_mat; diag_mat.Init(3); diag_mat[0]=1; diag_mat[1]=1; diag_mat[2]=3; lower_triang.Init(2,2); lower_triang.SetZero(); lower_triang.set(0,0,1); lower_triang.set(1,0,2);; lower_triang.set(1,1,4); usual_mat.Init(3,3); usual_mat.set(0,0,1); usual_mat.set(1,0,2); usual_mat.set(2,0,3); usual_mat.set(0,1,3); usual_mat.set(1,1,4); usual_mat.set(2,1,5); usual_mat.set(0,2,4); usual_mat.set(1,2,5); usual_mat.set(2,2,6); Matrix upper_triang_mat; upper_triang_mat.Init(2,3); upper_triang_mat.set(0,0,1); upper_triang_mat.set(1,0,0); upper_triang_mat.set(0,1,2); upper_triang_mat.set(1,1,4); upper_triang_mat.set(0,2,3); upper_triang_mat.set(1,2,5); //printf("Upper triangular matrix is..\n"); //upper_triang_mat.PrintDebug(); printf("usual matrix is...\n"); usual_mat.PrintDebug(); //PostMultiply with lower triangular //special_la::PreMultiplyLowerTriangMatrixInit(lower_triang,usual_mat,&res_mat); //printf("Will call the function...\n"); // printf("The result is...\n"); // res_mat.PrintDebug(); //Post Multiply with upper triang matrix //special_la::PostMultiplyUpperTriangMatrixInit(usual_mat,upper_triang_mat, // &res_mat); Matrix L_mat; L_mat.Init(3,1); L_mat.set(0,0,1); L_mat.set(1,0,2); L_mat.set(2,0,3); ArrayList <index_t> perm; Vector diag; diag.Init(3); diag[0]=2; diag[1]=2; diag[2]=2; Vector alpha; alpha.Init(3); alpha[0]=1; alpha[1]=2; alpha[2]=3; //printf("Everything initialized. Will do matrix inverse vector calculation...\n"); //special_la::MatrixInverseTimesVectorInit(L_mat,diag,alpha,&res); Matrix chol_factor; chol_factor.Init(3,1); chol_factor.set(0,0,2); chol_factor.set(1,0,3); chol_factor.set(2,0,1); ArrayList <index_t > perm_mat; perm_mat.Init(3); perm_mat[0]=2; perm_mat[1]=0; perm_mat[2]=1; //special_la::PostMultiplyMatrixWithVectorGivenCholeskyInit(chol_factor,perm_mat,alpha,&res); Vector test; test.Init(3); test[0]=1; test[1]=2; test[2]=3; test.PrintDebug(); usual_mat.PrintDebug(); Matrix res; special_la::PreMultiplyMatrixWithPermutationMatrixInit(perm_mat,usual_mat,&res); printf("Result of pre multiplication with a permutation matrix is...\n"); res.PrintDebug(); } <|endoftext|>
<commit_before>//------------------------------------------------------------------------------ // Dragons.cc //------------------------------------------------------------------------------ #include "Pre.h" #include "Core/Main.h" #include "Gfx/Gfx.h" #include "Input/Input.h" #include "IO/IO.h" #include "Anim/Anim.h" #include "HttpFS/HTTPFileSystem.h" #include "Core/Containers/InlineArray.h" #include "Common/CameraHelper.h" #include "Common/OrbLoader.h" #include "glm/gtc/matrix_transform.hpp" #include "shaders.h" using namespace Oryol; class Dragons : public App { public: AppState::Code OnInit(); AppState::Code OnRunning(); AppState::Code OnCleanup(); void loadModel(const Locator& loc); void addInstance(const glm::vec3& pos, int animClipIndex); static const int MaxNumInstances = 128; static const int BoneTextureWidth = 1024; static const int BoneTextureHeight = 128; GfxSetup gfxSetup; CameraHelper camera; Id shader; OrbModel orbModel; DrawState drawState; Shader::vsParams vsParams; struct Instance { Id animInstance; glm::mat4 modelMatrix; }; InlineArray<Instance, MaxNumInstances> instances; // xxxx,yyyy,zzzz is transposed model matrix // boneInfo is position in bone texture VertexLayout instanceMeshLayout; struct InstanceVertex { float xxxx[4]; float yyyy[4]; float zzzz[4]; float boneInfo[4]; }; InstanceVertex InstanceData[MaxNumInstances]; }; OryolMain(Dragons); //------------------------------------------------------------------------------ AppState::Code Dragons::OnInit() { IOSetup ioSetup; ioSetup.FileSystems.Add("http", HTTPFileSystem::Creator()); // ioSetup.Assigns.Add("orb:", ORYOL_SAMPLE_URL); ioSetup.Assigns.Add("orb:", "http://localhost:8000/"); IO::Setup(ioSetup); this->gfxSetup = GfxSetup::WindowMSAA4(1024, 640, "Dragons"); this->gfxSetup.DefaultPassAction = PassAction::Clear(glm::vec4(0.2f, 0.3f, 0.5f, 1.0f)); Gfx::Setup(this->gfxSetup); AnimSetup animSetup; animSetup.MaxNumActiveInstances = MaxNumInstances; animSetup.SkinMatrixTableWidth = BoneTextureWidth; animSetup.SkinMatrixTableHeight = BoneTextureHeight; Anim::Setup(animSetup); Input::Setup(); this->camera.Setup(false); this->camera.Center = glm::vec3(0.0f, 0.0f, -2.5f); this->camera.Distance = 10.0f; this->camera.Orbital = glm::vec2(glm::radians(25.0f), 0.0f); // can setup the shader before loading any assets this->shader = Gfx::CreateResource(Shader::Setup()); // RGBA32F texture for the animated skeleton bone info auto texSetup = TextureSetup::Empty2D(BoneTextureWidth, BoneTextureHeight, 1, PixelFormat::RGBA32F, Usage::Stream); texSetup.Sampler.MinFilter = TextureFilterMode::Nearest; texSetup.Sampler.MagFilter = TextureFilterMode::Nearest; texSetup.Sampler.WrapU = TextureWrapMode::ClampToEdge; texSetup.Sampler.WrapV = TextureWrapMode::ClampToEdge; this->drawState.VSTexture[Shader::boneTex] = Gfx::CreateResource(texSetup); // vertex buffer for per-instance info auto meshSetup = MeshSetup::Empty(MaxNumInstances, Usage::Stream); meshSetup.Layout = { { VertexAttr::Instance0, VertexFormat::Float4 }, { VertexAttr::Instance1, VertexFormat::Float4 }, { VertexAttr::Instance2, VertexFormat::Float4 }, { VertexAttr::Instance3, VertexFormat::Float4 } }; meshSetup.Layout.EnableInstancing(); this->instanceMeshLayout = meshSetup.Layout; this->drawState.Mesh[1] = Gfx::CreateResource(meshSetup); // load the dragon.orb file and add the first model instance this->loadModel("orb:dragon.orb"); return App::OnInit(); } //------------------------------------------------------------------------------ AppState::Code Dragons::OnRunning() { this->camera.Update(); // update the animation system if (this->orbModel.IsValid) { Anim::NewFrame(); for (const auto& inst : this->instances) { Anim::AddActiveInstance(inst.animInstance); } Anim::Evaluate(1.0/60.0); // upload bone info to GPU texture const AnimSkinMatrixInfo& boneInfo = Anim::SkinMatrixInfo(); ImageDataAttrs imgAttrs; imgAttrs.NumFaces = 1; imgAttrs.NumMipMaps = 1; imgAttrs.Offsets[0][0] = 0; imgAttrs.Sizes[0][0] = boneInfo.SkinMatrixTableByteSize; Gfx::UpdateTexture(this->drawState.VSTexture[Shader::boneTex], boneInfo.SkinMatrixTable, imgAttrs); // update the instance vertex buffer int instIndex = 0; for (const auto& inst : this->instances) { const glm::mat4& m = inst.modelMatrix; const auto& shdInfo = boneInfo.InstanceInfos[instIndex].ShaderInfo; auto& vtx = this->InstanceData[instIndex]; for (int i = 0; i < 4; i++) { vtx.xxxx[i] = m[i][0]; vtx.yyyy[i] = m[i][1]; vtx.zzzz[i] = m[i][2]; vtx.boneInfo[i] = shdInfo[i]; } instIndex++; } Gfx::UpdateVertices(this->drawState.Mesh[1], this->InstanceData, sizeof(InstanceVertex)*instIndex); } Gfx::BeginPass(); if (this->orbModel.IsValid) { const AnimSkinMatrixInfo& boneInfo = Anim::SkinMatrixInfo(); Gfx::ApplyDrawState(this->drawState); this->vsParams.view_proj = this->camera.ViewProj; Gfx::ApplyUniformBlock(this->vsParams); Gfx::Draw(1, this->instances.Size()); } Gfx::EndPass(); Gfx::CommitFrame(); return Gfx::QuitRequested() ? AppState::Cleanup : AppState::Running; } //------------------------------------------------------------------------------ AppState::Code Dragons::OnCleanup() { Input::Discard(); Anim::Discard(); Gfx::Discard(); IO::Discard(); return App::OnCleanup(); } //------------------------------------------------------------------------------ void Dragons::loadModel(const Locator& loc) { // start loading the .n3o file IO::Load(loc.Location(), [this](IO::LoadResult res) { if (OrbLoader::Load(res.Data, "model", this->orbModel)) { this->drawState.Mesh[0] = this->orbModel.Mesh; auto pipSetup = PipelineSetup::FromShader(this->shader); pipSetup.Layouts[0] = this->orbModel.Layout; pipSetup.Layouts[1] = this->instanceMeshLayout; pipSetup.DepthStencilState.DepthWriteEnabled = true; pipSetup.DepthStencilState.DepthCmpFunc = CompareFunc::LessEqual; pipSetup.RasterizerState.CullFaceEnabled = true; pipSetup.RasterizerState.SampleCount = this->gfxSetup.SampleCount; pipSetup.BlendState.ColorFormat = this->gfxSetup.ColorFormat; pipSetup.BlendState.DepthFormat = this->gfxSetup.DepthFormat; this->drawState.Pipeline = Gfx::CreateResource(pipSetup); this->addInstance(glm::vec3(2.5f, 0.0f, 0.0f), 0); this->addInstance(glm::vec3(-5.0f, 0.0f, 0.0f), 6); } }, [](const URL& url, IOStatus::Code ioStatus) { // loading failed, just display an error message and carry on Log::Error("Failed to load file '%s' with '%s'\n", url.AsCStr(), IOStatus::ToString(ioStatus)); }); } //------------------------------------------------------------------------------ void Dragons::addInstance(const glm::vec3& pos, int clipIndex) { if (!this->orbModel.IsValid) { return; } auto& inst = this->instances.Add(); inst.modelMatrix = glm::translate(glm::mat4(), pos); inst.animInstance = Anim::Create(AnimInstanceSetup::FromLibraryAndSkeleton( this->orbModel.AnimLib, this->orbModel.Skeleton)); AnimJob job; job.ClipIndex = clipIndex; job.TrackIndex = 0; Anim::Play(inst.animInstance, job); } <commit_msg>Dragons: added hardware instancing<commit_after>//------------------------------------------------------------------------------ // Dragons.cc //------------------------------------------------------------------------------ #include "Pre.h" #include "Core/Main.h" #include "Gfx/Gfx.h" #include "Input/Input.h" #include "IO/IO.h" #include "Anim/Anim.h" #include "HttpFS/HTTPFileSystem.h" #include "Core/Containers/InlineArray.h" #include "Common/CameraHelper.h" #include "Common/OrbLoader.h" #include "glm/gtc/matrix_transform.hpp" #include "shaders.h" using namespace Oryol; class Dragons : public App { public: AppState::Code OnInit(); AppState::Code OnRunning(); AppState::Code OnCleanup(); void loadModel(const Locator& loc); void addInstance(const glm::vec3& pos, int animClipIndex); static const int MaxNumInstances = 128; static const int BoneTextureWidth = 1024; static const int BoneTextureHeight = MaxNumInstances/3 + 1; GfxSetup gfxSetup; CameraHelper camera; Id shader; OrbModel orbModel; DrawState drawState; Shader::vsParams vsParams; InlineArray<Id, MaxNumInstances> instances; // xxxx,yyyy,zzzz is transposed model matrix // boneInfo is position in bone texture VertexLayout instanceMeshLayout; struct InstanceVertex { float xxxx[4]; float yyyy[4]; float zzzz[4]; float boneInfo[4]; }; InstanceVertex InstanceData[MaxNumInstances]; }; OryolMain(Dragons); //------------------------------------------------------------------------------ AppState::Code Dragons::OnInit() { IOSetup ioSetup; ioSetup.FileSystems.Add("http", HTTPFileSystem::Creator()); // ioSetup.Assigns.Add("orb:", ORYOL_SAMPLE_URL); ioSetup.Assigns.Add("orb:", "http://localhost:8000/"); IO::Setup(ioSetup); this->gfxSetup = GfxSetup::WindowMSAA4(1024, 640, "Dragons"); this->gfxSetup.DefaultPassAction = PassAction::Clear(glm::vec4(0.2f, 0.3f, 0.5f, 1.0f)); Gfx::Setup(this->gfxSetup); AnimSetup animSetup; animSetup.MaxNumActiveInstances = MaxNumInstances; animSetup.SkinMatrixTableWidth = BoneTextureWidth; animSetup.SkinMatrixTableHeight = BoneTextureHeight; Anim::Setup(animSetup); Input::Setup(); this->camera.Setup(false); this->camera.Center = glm::vec3(0.0f, 0.0f, -2.5f); this->camera.Distance = 10.0f; this->camera.Orbital = glm::vec2(glm::radians(25.0f), 0.0f); // setup the shader now, pipeline setup happens when model file has loaded this->shader = Gfx::CreateResource(Shader::Setup()); // RGBA32F texture for the animated skeleton bones auto texSetup = TextureSetup::Empty2D(BoneTextureWidth, BoneTextureHeight, 1, PixelFormat::RGBA32F, Usage::Stream); texSetup.Sampler.MinFilter = TextureFilterMode::Nearest; texSetup.Sampler.MagFilter = TextureFilterMode::Nearest; texSetup.Sampler.WrapU = TextureWrapMode::ClampToEdge; texSetup.Sampler.WrapV = TextureWrapMode::ClampToEdge; this->drawState.VSTexture[Shader::boneTex] = Gfx::CreateResource(texSetup); // vertex buffer for per-instance info auto meshSetup = MeshSetup::Empty(MaxNumInstances, Usage::Stream); meshSetup.Layout = { { VertexAttr::Instance0, VertexFormat::Float4 }, // transposes model matrix xxxx { VertexAttr::Instance1, VertexFormat::Float4 }, // transposes model matrix yyyy { VertexAttr::Instance2, VertexFormat::Float4 }, // transposes model matrix zzzz { VertexAttr::Instance3, VertexFormat::Float4 } // bone texture location }; meshSetup.Layout.EnableInstancing(); this->instanceMeshLayout = meshSetup.Layout; this->drawState.Mesh[1] = Gfx::CreateResource(meshSetup); // load the dragon.orb file and add the first model instance this->loadModel("orb:dragon.orb"); return App::OnInit(); } //------------------------------------------------------------------------------ AppState::Code Dragons::OnRunning() { this->camera.Update(); if (this->orbModel.IsValid) { // update the animation system Anim::NewFrame(); for (const auto& inst : this->instances) { Anim::AddActiveInstance(inst); } Anim::Evaluate(1.0/60.0); // upload animated skeleton bone info to GPU texture const AnimSkinMatrixInfo& boneInfo = Anim::SkinMatrixInfo(); ImageDataAttrs imgAttrs; imgAttrs.NumFaces = 1; imgAttrs.NumMipMaps = 1; imgAttrs.Offsets[0][0] = 0; imgAttrs.Sizes[0][0] = boneInfo.SkinMatrixTableByteSize; Gfx::UpdateTexture(this->drawState.VSTexture[Shader::boneTex], boneInfo.SkinMatrixTable, imgAttrs); // update the instance vertex buffer with bone texture locations int instIndex = 0; for (const auto& inst : this->instances) { const auto& shdInfo = boneInfo.InstanceInfos[instIndex].ShaderInfo; auto& vtx = this->InstanceData[instIndex]; for (int i = 0; i < 4; i++) { vtx.boneInfo[i] = shdInfo[i]; } instIndex++; } Gfx::UpdateVertices(this->drawState.Mesh[1], this->InstanceData, sizeof(InstanceVertex)*instIndex); } // all dragons rendered in a single draw call via hardware instancing Gfx::BeginPass(); if (this->orbModel.IsValid) { const AnimSkinMatrixInfo& boneInfo = Anim::SkinMatrixInfo(); Gfx::ApplyDrawState(this->drawState); this->vsParams.view_proj = this->camera.ViewProj; Gfx::ApplyUniformBlock(this->vsParams); Gfx::Draw(1, this->instances.Size()); } Gfx::EndPass(); Gfx::CommitFrame(); return Gfx::QuitRequested() ? AppState::Cleanup : AppState::Running; } //------------------------------------------------------------------------------ AppState::Code Dragons::OnCleanup() { Input::Discard(); Anim::Discard(); Gfx::Discard(); IO::Discard(); return App::OnCleanup(); } //------------------------------------------------------------------------------ void Dragons::loadModel(const Locator& loc) { // start loading the .n3o file IO::Load(loc.Location(), [this](IO::LoadResult res) { if (OrbLoader::Load(res.Data, "model", this->orbModel)) { this->drawState.Mesh[0] = this->orbModel.Mesh; auto pipSetup = PipelineSetup::FromShader(this->shader); pipSetup.Layouts[0] = this->orbModel.Layout; pipSetup.Layouts[1] = this->instanceMeshLayout; pipSetup.DepthStencilState.DepthWriteEnabled = true; pipSetup.DepthStencilState.DepthCmpFunc = CompareFunc::LessEqual; pipSetup.RasterizerState.CullFaceEnabled = true; pipSetup.RasterizerState.SampleCount = this->gfxSetup.SampleCount; pipSetup.BlendState.ColorFormat = this->gfxSetup.ColorFormat; pipSetup.BlendState.DepthFormat = this->gfxSetup.DepthFormat; this->drawState.Pipeline = Gfx::CreateResource(pipSetup); this->addInstance(glm::vec3(-5.0f, 0.0f, 0.0f), 0); this->addInstance(glm::vec3(0.0f, 0.0f, 0.0f), 6); this->addInstance(glm::vec3(+5.0f, 0.0f, 0.0f), 4); } }, [](const URL& url, IOStatus::Code ioStatus) { // loading failed, just display an error message and carry on Log::Error("Failed to load file '%s' with '%s'\n", url.AsCStr(), IOStatus::ToString(ioStatus)); }); } //------------------------------------------------------------------------------ void Dragons::addInstance(const glm::vec3& pos, int clipIndex) { if (!this->orbModel.IsValid) { return; } // write the model matrix directly into the per-instance vertex buffer const int instIndex = this->instances.Size(); glm::mat4 m = glm::translate(glm::mat4(), pos); for (int i = 0; i < 4; i++) { this->InstanceData[instIndex].xxxx[i] = m[i][0]; this->InstanceData[instIndex].yyyy[i] = m[i][1]; this->InstanceData[instIndex].zzzz[i] = m[i][2]; } // setup a new anim instance, and start the anim clip on it Id inst = Anim::Create(AnimInstanceSetup::FromLibraryAndSkeleton( this->orbModel.AnimLib, this->orbModel.Skeleton)); this->instances.Add(inst); AnimJob job; job.ClipIndex = clipIndex; job.TrackIndex = 0; Anim::Play(inst, job); } <|endoftext|>
<commit_before>#pragma once #include <mbed.h> #include <rtos.h> #include "rj-macros.hpp" #include "rtp.hpp" #include "helper-funcs.hpp" #include "rtos-mgmt/mail-helper.hpp" #include "CommModule.hpp" #define COMM_LINK_SIGNAL_START_THREAD 0x01 #define COMM_LINK_SIGNAL_RX_TRIGGER 0x02 #define FOREACH_COMM_ERR(ERR) \ ERR(COMM_SUCCESS) \ ERR(COMM_FAILURE) \ ERR(COMM_DEV_BUF_ERR) \ ERR(COMM_FUNC_BUF_ERR) \ ERR(COMM_FALSE_TRIG) \ ERR(COMM_NO_DATA) /** * CommLink Error Levels. */ enum { FOREACH_COMM_ERR(GENERATE_ENUM) }; /** * CommLink Class used as the hal (hardware abstraction layer) module for * interfacing communication links to the higher-level firmware */ class CommLink { public: /// Defautl Constructor CommLink(){}; /// Constructor CommLink(PinName, PinName, PinName, PinName = NC, PinName = NC); /// Virtual deconstructor /// Always define and call CommLink::cleanup() in a derived class's deconstructor! virtual ~CommLink(); // Class constants for data queues static const size_t RX_QUEUE_SIZE = 3; static const size_t BUFFER_SIZE = 64; // The pure virtual methods for making CommLink an abstract class /// Perform a soft reset for a communication link's hardware device virtual void reset(void) = 0; /// Perform tests to determine if the hardware is able to properly function virtual int32_t selfTest(void) = 0; /// Determine if communication can occur with another device virtual bool isConnected(void) = 0; /// Send & Receive through the rtp structure void sendPacket(rtp::packet*); void receivePacket(rtp::packet*); protected: virtual int32_t sendData( uint8_t*, uint8_t) = 0; // write data out to the radio device using SPI virtual int32_t getData( uint8_t*, uint8_t*) = 0; // read data in from the radio device using SPI /// Kill any threads and free the allocated stack. /// Always call in any derived class's deconstructors! void cleanup(); void ISR(); void toggle_cs(); /// Used for giving derived classes a standaradized way to inform the base /// class that it is ready for communication and to begin the threads // // Always call CommLink::ready() after derived class is ready void ready(); void setup_spi(int baudrate = DEFAULT_BAUD); uint8_t twos_compliment(uint8_t val); // The data queues for temporarily holding received packets osMailQId _rxQueue; // SPI bus pins PinName _miso_pin; PinName _mosi_pin; PinName _sck_pin; PinName _cs_pin; // CS pin PinName _int_pin; // Interrupt pin SPI* _spi; // SPI pointer DigitalOut* _cs; // Chip Select pointer InterruptIn* _int_in; // Interrupt pin static const int DEFAULT_BAUD = 5000000; private: // Used to help define the class's threads in the constructor friend void define_thread(osThreadDef_t&, void (*task)(void const* arg), osPriority, uint32_t); /** * Data queue helper for RX queue. */ MailHelper<rtp::packet, RX_QUEUE_SIZE> _rxQueueHelper; // Thread definitions and IDs osThreadDef_t _rxDef; osThreadId _rxID; // The working threads for handeling RX data queue operations static void rxThread(void const*); // Methods for initializing a transceiver's pins for communication void setup(void); void setup_pins(PinName = NC, PinName = NC, PinName = NC, PinName = NC, PinName = NC); void setup_cs(void); void setup_interrupt(void); // Used for tracking the number of link-level communication interfaces static unsigned int _nbr_links; uint8_t buf[BUFFER_SIZE]; }; <commit_msg>running make pretty<commit_after>#pragma once #include <mbed.h> #include <rtos.h> #include "rj-macros.hpp" #include "rtp.hpp" #include "helper-funcs.hpp" #include "rtos-mgmt/mail-helper.hpp" #include "CommModule.hpp" #define COMM_LINK_SIGNAL_START_THREAD 0x01 #define COMM_LINK_SIGNAL_RX_TRIGGER 0x02 #define FOREACH_COMM_ERR(ERR) \ ERR(COMM_SUCCESS) \ ERR(COMM_FAILURE) \ ERR(COMM_DEV_BUF_ERR) \ ERR(COMM_FUNC_BUF_ERR) \ ERR(COMM_FALSE_TRIG) \ ERR(COMM_NO_DATA) /** * CommLink Error Levels. */ enum { FOREACH_COMM_ERR(GENERATE_ENUM) }; /** * CommLink Class used as the hal (hardware abstraction layer) module for * interfacing communication links to the higher-level firmware */ class CommLink { public: /// Defautl Constructor CommLink(){}; /// Constructor CommLink(PinName, PinName, PinName, PinName = NC, PinName = NC); /// Virtual deconstructor /// Always define and call CommLink::cleanup() in a derived class's /// deconstructor! virtual ~CommLink(); // Class constants for data queues static const size_t RX_QUEUE_SIZE = 3; static const size_t BUFFER_SIZE = 64; // The pure virtual methods for making CommLink an abstract class /// Perform a soft reset for a communication link's hardware device virtual void reset(void) = 0; /// Perform tests to determine if the hardware is able to properly function virtual int32_t selfTest(void) = 0; /// Determine if communication can occur with another device virtual bool isConnected(void) = 0; /// Send & Receive through the rtp structure void sendPacket(rtp::packet*); void receivePacket(rtp::packet*); protected: virtual int32_t sendData( uint8_t*, uint8_t) = 0; // write data out to the radio device using SPI virtual int32_t getData( uint8_t*, uint8_t*) = 0; // read data in from the radio device using SPI /// Kill any threads and free the allocated stack. /// Always call in any derived class's deconstructors! void cleanup(); void ISR(); void toggle_cs(); /// Used for giving derived classes a standaradized way to inform the base /// class that it is ready for communication and to begin the threads // // Always call CommLink::ready() after derived class is ready void ready(); void setup_spi(int baudrate = DEFAULT_BAUD); uint8_t twos_compliment(uint8_t val); // The data queues for temporarily holding received packets osMailQId _rxQueue; // SPI bus pins PinName _miso_pin; PinName _mosi_pin; PinName _sck_pin; PinName _cs_pin; // CS pin PinName _int_pin; // Interrupt pin SPI* _spi; // SPI pointer DigitalOut* _cs; // Chip Select pointer InterruptIn* _int_in; // Interrupt pin static const int DEFAULT_BAUD = 5000000; private: // Used to help define the class's threads in the constructor friend void define_thread(osThreadDef_t&, void (*task)(void const* arg), osPriority, uint32_t); /** * Data queue helper for RX queue. */ MailHelper<rtp::packet, RX_QUEUE_SIZE> _rxQueueHelper; // Thread definitions and IDs osThreadDef_t _rxDef; osThreadId _rxID; // The working threads for handeling RX data queue operations static void rxThread(void const*); // Methods for initializing a transceiver's pins for communication void setup(void); void setup_pins(PinName = NC, PinName = NC, PinName = NC, PinName = NC, PinName = NC); void setup_cs(void); void setup_interrupt(void); // Used for tracking the number of link-level communication interfaces static unsigned int _nbr_links; uint8_t buf[BUFFER_SIZE]; }; <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: XMLIndexBibliographySourceContext.cxx,v $ * * $Revision: 1.2 $ * * last change: $Author: dvo $ $Date: 2001-06-29 21:07:21 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * 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 * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (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.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _XMLOFF_XMLINDEXBIBLIOGRAPHYSOURCECONTEXT_HXX_ #include "XMLIndexBibliographySourceContext.hxx" #endif #ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_ #include <com/sun/star/beans/XPropertySet.hpp> #endif #ifndef _COM_SUN_STAR_CONTAINER_XINDEXREPLACE_HPP_ #include <com/sun/star/container/XIndexReplace.hpp> #endif #ifndef _XMLOFF_XMLINDEXTEMPLATECONTEXT_HXX_ #include "XMLIndexTemplateContext.hxx" #endif #ifndef _XMLOFF_XMLINDEXTITLETEMPLATECONTEXT_HXX_ #include "XMLIndexTitleTemplateContext.hxx" #endif #ifndef _XMLOFF_XMLINDEXTOCSTYLESCONTEXT_HXX_ #include "XMLIndexTOCStylesContext.hxx" #endif #ifndef _XMLOFF_XMLICTXT_HXX #include "xmlictxt.hxx" #endif #ifndef _XMLOFF_XMLIMP_HXX #include "xmlimp.hxx" #endif #ifndef _XMLOFF_TEXTIMP_HXX_ #include "txtimp.hxx" #endif #ifndef _XMLOFF_XMLNMSPE_HXX #include "xmlnmspe.hxx" #endif #ifndef _XMLOFF_NMSPMAP_HXX #include "nmspmap.hxx" #endif #ifndef _XMLOFF_XMLTOKEN_HXX #include "xmltoken.hxx" #endif #ifndef _XMLOFF_XMLUCONV_HXX #include "xmluconv.hxx" #endif #ifndef _TOOLS_DEBUG_HXX #include <tools/debug.hxx> #endif #ifndef _RTL_USTRING_HXX_ #include <rtl/ustring.hxx> #endif using namespace ::xmloff::token; using ::rtl::OUString; using ::com::sun::star::beans::XPropertySet; using ::com::sun::star::uno::Reference; using ::com::sun::star::uno::Any; using ::com::sun::star::xml::sax::XAttributeList; TYPEINIT1(XMLIndexBibliographySourceContext, XMLIndexSourceBaseContext); XMLIndexBibliographySourceContext::XMLIndexBibliographySourceContext( SvXMLImport& rImport, sal_uInt16 nPrfx, const OUString& rLocalName, Reference<XPropertySet> & rPropSet) : XMLIndexSourceBaseContext(rImport, nPrfx, rLocalName, rPropSet, sal_False) { } XMLIndexBibliographySourceContext::~XMLIndexBibliographySourceContext() { } void XMLIndexBibliographySourceContext::ProcessAttribute( enum IndexSourceParamEnum eParam, const OUString& rValue) { // We have no attributes. Who wants attributes, anyway? } void XMLIndexBibliographySourceContext::EndElement() { // No attributes, no properties. } SvXMLImportContext* XMLIndexBibliographySourceContext::CreateChildContext( sal_uInt16 nPrefix, const OUString& rLocalName, const Reference<XAttributeList> & xAttrList ) { if ( ( XML_NAMESPACE_TEXT == nPrefix ) && ( IsXMLToken( rLocalName, XML_BIBLIOGRAPHY_ENTRY_TEMPLATE ) ) ) { return new XMLIndexTemplateContext(GetImport(), rIndexPropertySet, nPrefix, rLocalName, aLevelNameBibliographyMap, XML_BIBLIOGRAPHY_TYPE, aLevelStylePropNameBibliographyMap, aAllowedTokenTypesBibliography); } else { return XMLIndexSourceBaseContext::CreateChildContext(nPrefix, rLocalName, xAttrList); } } <commit_msg>INTEGRATION: CWS ooo19126 (1.2.636); FILE MERGED 2005/09/05 14:39:49 rt 1.2.636.1: #i54170# Change license header: remove SISSL<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: XMLIndexBibliographySourceContext.cxx,v $ * * $Revision: 1.3 $ * * last change: $Author: rt $ $Date: 2005-09-09 15:03:58 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * 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 * ************************************************************************/ #ifndef _XMLOFF_XMLINDEXBIBLIOGRAPHYSOURCECONTEXT_HXX_ #include "XMLIndexBibliographySourceContext.hxx" #endif #ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_ #include <com/sun/star/beans/XPropertySet.hpp> #endif #ifndef _COM_SUN_STAR_CONTAINER_XINDEXREPLACE_HPP_ #include <com/sun/star/container/XIndexReplace.hpp> #endif #ifndef _XMLOFF_XMLINDEXTEMPLATECONTEXT_HXX_ #include "XMLIndexTemplateContext.hxx" #endif #ifndef _XMLOFF_XMLINDEXTITLETEMPLATECONTEXT_HXX_ #include "XMLIndexTitleTemplateContext.hxx" #endif #ifndef _XMLOFF_XMLINDEXTOCSTYLESCONTEXT_HXX_ #include "XMLIndexTOCStylesContext.hxx" #endif #ifndef _XMLOFF_XMLICTXT_HXX #include "xmlictxt.hxx" #endif #ifndef _XMLOFF_XMLIMP_HXX #include "xmlimp.hxx" #endif #ifndef _XMLOFF_TEXTIMP_HXX_ #include "txtimp.hxx" #endif #ifndef _XMLOFF_XMLNMSPE_HXX #include "xmlnmspe.hxx" #endif #ifndef _XMLOFF_NMSPMAP_HXX #include "nmspmap.hxx" #endif #ifndef _XMLOFF_XMLTOKEN_HXX #include "xmltoken.hxx" #endif #ifndef _XMLOFF_XMLUCONV_HXX #include "xmluconv.hxx" #endif #ifndef _TOOLS_DEBUG_HXX #include <tools/debug.hxx> #endif #ifndef _RTL_USTRING_HXX_ #include <rtl/ustring.hxx> #endif using namespace ::xmloff::token; using ::rtl::OUString; using ::com::sun::star::beans::XPropertySet; using ::com::sun::star::uno::Reference; using ::com::sun::star::uno::Any; using ::com::sun::star::xml::sax::XAttributeList; TYPEINIT1(XMLIndexBibliographySourceContext, XMLIndexSourceBaseContext); XMLIndexBibliographySourceContext::XMLIndexBibliographySourceContext( SvXMLImport& rImport, sal_uInt16 nPrfx, const OUString& rLocalName, Reference<XPropertySet> & rPropSet) : XMLIndexSourceBaseContext(rImport, nPrfx, rLocalName, rPropSet, sal_False) { } XMLIndexBibliographySourceContext::~XMLIndexBibliographySourceContext() { } void XMLIndexBibliographySourceContext::ProcessAttribute( enum IndexSourceParamEnum eParam, const OUString& rValue) { // We have no attributes. Who wants attributes, anyway? } void XMLIndexBibliographySourceContext::EndElement() { // No attributes, no properties. } SvXMLImportContext* XMLIndexBibliographySourceContext::CreateChildContext( sal_uInt16 nPrefix, const OUString& rLocalName, const Reference<XAttributeList> & xAttrList ) { if ( ( XML_NAMESPACE_TEXT == nPrefix ) && ( IsXMLToken( rLocalName, XML_BIBLIOGRAPHY_ENTRY_TEMPLATE ) ) ) { return new XMLIndexTemplateContext(GetImport(), rIndexPropertySet, nPrefix, rLocalName, aLevelNameBibliographyMap, XML_BIBLIOGRAPHY_TYPE, aLevelStylePropNameBibliographyMap, aAllowedTokenTypesBibliography); } else { return XMLIndexSourceBaseContext::CreateChildContext(nPrefix, rLocalName, xAttrList); } } <|endoftext|>
<commit_before>#include <ros/ros.h> #include <actionlib/client/simple_action_client.h> #include <actionlib/client/terminal_state.h> #include <motion_msgs/MoveToPositionAction.h> int main (int argc, char **argv) { ros::init(argc, argv, "test_movetoposition"); // create the action client // true causes the client to spin its own thread actionlib::SimpleActionClient<motion_msgs::MoveToPositionAction> ac("motion/move_to_position", true); ROS_INFO("Waiting for action server to start."); // wait for the action server to start ac.waitForServer(); //will wait for infinite time ROS_INFO("Action server started, sending goal."); // send a goal to the action motion_msgs::MoveToPositionGoal goal; goal.position.x = 0.12; goal.position.y = -0.15; goal.position.z = 0.21; ac.sendGoal(goal); actionlib::SimpleClientGoalState state = ac.getState(); ROS_INFO("Action state: %s",state.toString().c_str()); //exit return 0; }<commit_msg>removed lines to read state of action from client<commit_after>#include <ros/ros.h> #include <actionlib/client/simple_action_client.h> #include <actionlib/client/terminal_state.h> #include <motion_msgs/MoveToPositionAction.h> int main (int argc, char **argv) { ros::init(argc, argv, "test_movetoposition"); // create the action client // true causes the client to spin its own thread actionlib::SimpleActionClient<motion_msgs::MoveToPositionAction> ac("motion/move_to_position", true); ROS_INFO("Waiting for action server to start."); // wait for the action server to start ac.waitForServer(); //will wait for infinite time ROS_INFO("Action server started, sending goal."); // send a goal to the action motion_msgs::MoveToPositionGoal goal; goal.position.x = 0.12; goal.position.y = -0.15; goal.position.z = 0.21; ac.sendGoal(goal); //exit return 0; }<|endoftext|>
<commit_before>// // MarkdownParser.cc // markdownparser // // Created by Zdenek Nemec on 4/18/14. // Copyright (c) 2014 Apiary Inc. All rights reserved. // #include <cstring> #include <stdexcept> #include "MarkdownParser.h" using namespace mdp; const size_t MarkdownParser::OutputUnitSize = 64; const size_t MarkdownParser::MaxNesting = 128; const int MarkdownParser::ParserExtensions = MKDEXT_FENCED_CODE | MKDEXT_NO_INTRA_EMPHASIS | MKDEXT_LAX_SPACING /*| MKDEXT_TABLES */; #define NO_WORKING_NODE_ERR std::logic_error("no working node") #define WORKING_NODE_MISMATCH_ERR std::logic_error("working node mismatch") /** * \brief Create a byte buffer from a sundown buffer */ static ByteBuffer ByteBufferFromSundown(const struct buf* text) { if (!text || !text->data || !text->size) return ByteBuffer(); return ByteBuffer(reinterpret_cast<char*>(text->data), text->size); } MarkdownParser::MarkdownParser() : m_workingNode(NULL), m_listBlockContext(false), m_source(NULL), m_sourceLength(0) {} void MarkdownParser::parse(const ByteBuffer& source, MarkdownNode& ast) { ast = MarkdownNode(); m_workingNode = &ast; m_workingNode->type = RootMarkdownNodeType; m_workingNode->sourceMap.push_back(BytesRange(0, source.length())); m_source = &source; m_sourceLength = source.length(); m_listBlockContext = false; RenderCallbacks callbacks = renderCallbacks(); ::sd_markdown* sundown = ::sd_markdown_new(ParserExtensions, MaxNesting, &callbacks, renderCallbackData()); ::buf* output = ::bufnew(OutputUnitSize); ::sd_markdown_render(output, reinterpret_cast<const uint8_t*>(source.c_str()), source.length(), sundown); ::bufrelease(output); ::sd_markdown_free(sundown); m_workingNode = NULL; m_source = NULL; m_sourceLength = 0; m_listBlockContext = false; #ifdef DEBUG ast.printNode(); #endif } MarkdownParser::RenderCallbacks MarkdownParser::renderCallbacks() { RenderCallbacks callbacks; ::memset(&callbacks, 0, sizeof(RenderCallbacks)); callbacks.blockcode = &MarkdownParser::renderBlockCode; callbacks.blockquote = &MarkdownParser::renderQuote; callbacks.blockhtml = &MarkdownParser::renderHTML; callbacks.header = &MarkdownParser::renderHeader; callbacks.hrule = &MarkdownParser::renderHorizontalRule; callbacks.list = &MarkdownParser::renderList; callbacks.listitem = &MarkdownParser::renderListItem; callbacks.paragraph = &MarkdownParser::renderParagraph; callbacks.table = NULL; callbacks.table_row = NULL; callbacks.table_cell = NULL; callbacks.blockquote_begin = &MarkdownParser::beginQuote; callbacks.list_begin = &MarkdownParser::beginList; callbacks.listitem_begin = &MarkdownParser::beginListItem; callbacks.block_did_parse = &MarkdownParser::blockDidParse; return callbacks; } MarkdownParser::RenderCallbackData MarkdownParser::renderCallbackData() { return this; } void MarkdownParser::renderHeader(struct buf* ob, const struct buf* text, int level, void* opaque) { if (!opaque) return; MarkdownParser* p = static_cast<MarkdownParser*>(opaque); p->renderHeader(ByteBufferFromSundown(text), level); } void MarkdownParser::renderHeader(const ByteBuffer& text, int level) { if (!m_workingNode) throw NO_WORKING_NODE_ERR; MarkdownNode node(HeaderMarkdownNodeType, m_workingNode, text, level); m_workingNode->children().push_back(node); } void MarkdownParser::beginList(int flags, void* opaque) { if (!opaque) return; MarkdownParser* p = static_cast<MarkdownParser*>(opaque); p->beginList(flags); } void MarkdownParser::beginList(int flags) { if (!m_workingNode) throw NO_WORKING_NODE_ERR; } void MarkdownParser::renderList(struct buf* ob, const struct buf* text, int flags, void* opaque) { if (!opaque) return; MarkdownParser* p = static_cast<MarkdownParser*>(opaque); p->renderList(ByteBufferFromSundown(text), flags); } void MarkdownParser::renderList(const ByteBuffer& text, int flags) { m_listBlockContext = true; } void MarkdownParser::beginListItem(int flags, void* opaque) { if (!opaque) return; MarkdownParser* p = static_cast<MarkdownParser*>(opaque); p->beginListItem(flags); } void MarkdownParser::beginListItem(int flags) { if (!m_workingNode) throw NO_WORKING_NODE_ERR; MarkdownNode node(ListItemMarkdownNodeType, m_workingNode, ByteBuffer(), flags); m_workingNode->children().push_back(node); // Push context m_workingNode = &m_workingNode->children().back(); } void MarkdownParser::renderListItem(struct buf* ob, const struct buf* text, int flags, void* opaque) { if (!opaque) return; MarkdownParser* p = static_cast<MarkdownParser*>(opaque); p->renderListItem(ByteBufferFromSundown(text), flags); } void MarkdownParser::renderListItem(const ByteBuffer& text, int flags) { if (!m_workingNode) throw NO_WORKING_NODE_ERR; if (m_workingNode->type != ListItemMarkdownNodeType) throw WORKING_NODE_MISMATCH_ERR; // No "inline" list items: // Instead of storing the text on the list item // create the artificial paragraph node to store the text. if (m_workingNode->children().empty() || m_workingNode->children().front().type != ParagraphMarkdownNodeType) { MarkdownNode textNode(ParagraphMarkdownNodeType, m_workingNode, text); m_workingNode->children().push_front(textNode); } m_workingNode->data = flags; // Pop context m_workingNode = &m_workingNode->parent(); } void MarkdownParser::renderBlockCode(struct buf* ob, const struct buf* text, const struct buf* lang, void* opaque) { if (!opaque) return; MarkdownParser* p = static_cast<MarkdownParser*>(opaque); p->renderBlockCode(ByteBufferFromSundown(text), ByteBufferFromSundown(lang)); } void MarkdownParser::renderBlockCode(const ByteBuffer& text, const ByteBuffer& language) { if (!m_workingNode) throw NO_WORKING_NODE_ERR; MarkdownNode node(CodeMarkdownNodeType, m_workingNode, text); m_workingNode->children().push_back(node); } void MarkdownParser::renderParagraph(struct buf* ob, const struct buf* text, void* opaque) { if (!opaque) return; MarkdownParser* p = static_cast<MarkdownParser*>(opaque); p->renderParagraph(ByteBufferFromSundown(text)); } void MarkdownParser::renderParagraph(const ByteBuffer& text) { if (!m_workingNode) throw NO_WORKING_NODE_ERR; MarkdownNode node(ParagraphMarkdownNodeType, m_workingNode, text); m_workingNode->children().push_back(node); } void MarkdownParser::renderHorizontalRule(struct buf* ob, void* opaque) { if (!opaque) return; MarkdownParser* p = static_cast<MarkdownParser*>(opaque); p->renderHorizontalRule(); } void MarkdownParser::renderHorizontalRule() { if (!m_workingNode) throw NO_WORKING_NODE_ERR; MarkdownNode node(HRuleMarkdownNodeType, m_workingNode, ByteBuffer(), MarkdownNode::Data()); m_workingNode->children().push_back(node); } void MarkdownParser::renderHTML(struct buf* ob, const struct buf* text, void* opaque) { if (!opaque) return; MarkdownParser* p = static_cast<MarkdownParser*>(opaque); p->renderHTML(ByteBufferFromSundown(text)); } void MarkdownParser::renderHTML(const ByteBuffer& text) { if (!m_workingNode) throw NO_WORKING_NODE_ERR; MarkdownNode node(HTMLMarkdownNodeType, m_workingNode, text); m_workingNode->children().push_back(node); } void MarkdownParser::beginQuote(void* opaque) { if (!opaque) return; MarkdownParser* p = static_cast<MarkdownParser*>(opaque); p->beginQuote(); } void MarkdownParser::beginQuote() { if (!m_workingNode) throw NO_WORKING_NODE_ERR; MarkdownNode node(QuoteMarkdownNodeType, m_workingNode); m_workingNode->children().push_back(node); // Push context m_workingNode = &m_workingNode->children().back(); } void MarkdownParser::renderQuote(struct buf* ob, const struct buf* text, void* opaque) { if (!opaque) return; MarkdownParser* p = static_cast<MarkdownParser*>(opaque); p->renderQuote(ByteBufferFromSundown(text)); } void MarkdownParser::renderQuote(const ByteBuffer& text) { if (!m_workingNode) throw NO_WORKING_NODE_ERR; if (m_workingNode->type != QuoteMarkdownNodeType) throw WORKING_NODE_MISMATCH_ERR; m_workingNode->text = text; // Pop context m_workingNode = &m_workingNode->parent(); } void MarkdownParser::blockDidParse(const src_map* map, const uint8_t* txt_data, size_t size, void* opaque) { if (!opaque || !map) return; BytesRangeSet sourceMap; for (size_t i = 0; i < map->size; ++i) { BytesRange byteRange(((range*)map->item[i])->loc, ((range*)map->item[i])->len); sourceMap.push_back(byteRange); } MarkdownParser* p = static_cast<MarkdownParser*>(opaque); p->blockDidParse(sourceMap); } void MarkdownParser::blockDidParse(const BytesRangeSet& sourceMap) { if (m_listBlockContext) { m_listBlockContext = false; // ignore list blocks events return; } if (!m_workingNode) throw NO_WORKING_NODE_ERR; if (m_workingNode->children().empty()) return; MarkdownNode& lMarkdownNode = m_workingNode->children().back(); // Sundown +1 newline compensation // // If new source map would exceed the actual source size // this happens when sundown appends an artifical new line // truncate the source map length to match the actual size if (sourceMap.back().location + sourceMap.back().length > m_sourceLength) { size_t workMapLength = m_sourceLength - sourceMap.back().location; if (!workMapLength) return; // Ignore any artifical trailing new lines in source maps BytesRangeSet workMap = sourceMap; workMap.back().length = workMapLength; lMarkdownNode.sourceMap.append(workMap); } else { lMarkdownNode.sourceMap.append(sourceMap); } // No "inline" list items: // Share the list item source map with its artifical node, if exists. if (lMarkdownNode.type == ListItemMarkdownNodeType && !lMarkdownNode.children().empty() && lMarkdownNode.children().front().sourceMap.empty()) { ByteBuffer& buffer = lMarkdownNode.children().front().text; ByteBuffer mapped = MapBytesRangeSet(sourceMap, *m_source); size_t pos = mapped.find(buffer); if (pos != mapped.npos) { BytesRange range = sourceMap.front(); range.location += pos; range.length = buffer.length(); BytesRangeSet newMap; newMap.push_back(range); lMarkdownNode.children().front().sourceMap.append(newMap); } else { lMarkdownNode.children().front().sourceMap.append(sourceMap); } } } <commit_msg>refactor: disable markdown node debug printing by default<commit_after>// // MarkdownParser.cc // markdownparser // // Created by Zdenek Nemec on 4/18/14. // Copyright (c) 2014 Apiary Inc. All rights reserved. // #include <cstring> #include <stdexcept> #include "MarkdownParser.h" using namespace mdp; const size_t MarkdownParser::OutputUnitSize = 64; const size_t MarkdownParser::MaxNesting = 128; const int MarkdownParser::ParserExtensions = MKDEXT_FENCED_CODE | MKDEXT_NO_INTRA_EMPHASIS | MKDEXT_LAX_SPACING /*| MKDEXT_TABLES */; #define NO_WORKING_NODE_ERR std::logic_error("no working node") #define WORKING_NODE_MISMATCH_ERR std::logic_error("working node mismatch") /** * \brief Create a byte buffer from a sundown buffer */ static ByteBuffer ByteBufferFromSundown(const struct buf* text) { if (!text || !text->data || !text->size) return ByteBuffer(); return ByteBuffer(reinterpret_cast<char*>(text->data), text->size); } MarkdownParser::MarkdownParser() : m_workingNode(NULL), m_listBlockContext(false), m_source(NULL), m_sourceLength(0) {} void MarkdownParser::parse(const ByteBuffer& source, MarkdownNode& ast) { ast = MarkdownNode(); m_workingNode = &ast; m_workingNode->type = RootMarkdownNodeType; m_workingNode->sourceMap.push_back(BytesRange(0, source.length())); m_source = &source; m_sourceLength = source.length(); m_listBlockContext = false; RenderCallbacks callbacks = renderCallbacks(); ::sd_markdown* sundown = ::sd_markdown_new(ParserExtensions, MaxNesting, &callbacks, renderCallbackData()); ::buf* output = ::bufnew(OutputUnitSize); ::sd_markdown_render(output, reinterpret_cast<const uint8_t*>(source.c_str()), source.length(), sundown); ::bufrelease(output); ::sd_markdown_free(sundown); m_workingNode = NULL; m_source = NULL; m_sourceLength = 0; m_listBlockContext = false; } MarkdownParser::RenderCallbacks MarkdownParser::renderCallbacks() { RenderCallbacks callbacks; ::memset(&callbacks, 0, sizeof(RenderCallbacks)); callbacks.blockcode = &MarkdownParser::renderBlockCode; callbacks.blockquote = &MarkdownParser::renderQuote; callbacks.blockhtml = &MarkdownParser::renderHTML; callbacks.header = &MarkdownParser::renderHeader; callbacks.hrule = &MarkdownParser::renderHorizontalRule; callbacks.list = &MarkdownParser::renderList; callbacks.listitem = &MarkdownParser::renderListItem; callbacks.paragraph = &MarkdownParser::renderParagraph; callbacks.table = NULL; callbacks.table_row = NULL; callbacks.table_cell = NULL; callbacks.blockquote_begin = &MarkdownParser::beginQuote; callbacks.list_begin = &MarkdownParser::beginList; callbacks.listitem_begin = &MarkdownParser::beginListItem; callbacks.block_did_parse = &MarkdownParser::blockDidParse; return callbacks; } MarkdownParser::RenderCallbackData MarkdownParser::renderCallbackData() { return this; } void MarkdownParser::renderHeader(struct buf* ob, const struct buf* text, int level, void* opaque) { if (!opaque) return; MarkdownParser* p = static_cast<MarkdownParser*>(opaque); p->renderHeader(ByteBufferFromSundown(text), level); } void MarkdownParser::renderHeader(const ByteBuffer& text, int level) { if (!m_workingNode) throw NO_WORKING_NODE_ERR; MarkdownNode node(HeaderMarkdownNodeType, m_workingNode, text, level); m_workingNode->children().push_back(node); } void MarkdownParser::beginList(int flags, void* opaque) { if (!opaque) return; MarkdownParser* p = static_cast<MarkdownParser*>(opaque); p->beginList(flags); } void MarkdownParser::beginList(int flags) { if (!m_workingNode) throw NO_WORKING_NODE_ERR; } void MarkdownParser::renderList(struct buf* ob, const struct buf* text, int flags, void* opaque) { if (!opaque) return; MarkdownParser* p = static_cast<MarkdownParser*>(opaque); p->renderList(ByteBufferFromSundown(text), flags); } void MarkdownParser::renderList(const ByteBuffer& text, int flags) { m_listBlockContext = true; } void MarkdownParser::beginListItem(int flags, void* opaque) { if (!opaque) return; MarkdownParser* p = static_cast<MarkdownParser*>(opaque); p->beginListItem(flags); } void MarkdownParser::beginListItem(int flags) { if (!m_workingNode) throw NO_WORKING_NODE_ERR; MarkdownNode node(ListItemMarkdownNodeType, m_workingNode, ByteBuffer(), flags); m_workingNode->children().push_back(node); // Push context m_workingNode = &m_workingNode->children().back(); } void MarkdownParser::renderListItem(struct buf* ob, const struct buf* text, int flags, void* opaque) { if (!opaque) return; MarkdownParser* p = static_cast<MarkdownParser*>(opaque); p->renderListItem(ByteBufferFromSundown(text), flags); } void MarkdownParser::renderListItem(const ByteBuffer& text, int flags) { if (!m_workingNode) throw NO_WORKING_NODE_ERR; if (m_workingNode->type != ListItemMarkdownNodeType) throw WORKING_NODE_MISMATCH_ERR; // No "inline" list items: // Instead of storing the text on the list item // create the artificial paragraph node to store the text. if (m_workingNode->children().empty() || m_workingNode->children().front().type != ParagraphMarkdownNodeType) { MarkdownNode textNode(ParagraphMarkdownNodeType, m_workingNode, text); m_workingNode->children().push_front(textNode); } m_workingNode->data = flags; // Pop context m_workingNode = &m_workingNode->parent(); } void MarkdownParser::renderBlockCode(struct buf* ob, const struct buf* text, const struct buf* lang, void* opaque) { if (!opaque) return; MarkdownParser* p = static_cast<MarkdownParser*>(opaque); p->renderBlockCode(ByteBufferFromSundown(text), ByteBufferFromSundown(lang)); } void MarkdownParser::renderBlockCode(const ByteBuffer& text, const ByteBuffer& language) { if (!m_workingNode) throw NO_WORKING_NODE_ERR; MarkdownNode node(CodeMarkdownNodeType, m_workingNode, text); m_workingNode->children().push_back(node); } void MarkdownParser::renderParagraph(struct buf* ob, const struct buf* text, void* opaque) { if (!opaque) return; MarkdownParser* p = static_cast<MarkdownParser*>(opaque); p->renderParagraph(ByteBufferFromSundown(text)); } void MarkdownParser::renderParagraph(const ByteBuffer& text) { if (!m_workingNode) throw NO_WORKING_NODE_ERR; MarkdownNode node(ParagraphMarkdownNodeType, m_workingNode, text); m_workingNode->children().push_back(node); } void MarkdownParser::renderHorizontalRule(struct buf* ob, void* opaque) { if (!opaque) return; MarkdownParser* p = static_cast<MarkdownParser*>(opaque); p->renderHorizontalRule(); } void MarkdownParser::renderHorizontalRule() { if (!m_workingNode) throw NO_WORKING_NODE_ERR; MarkdownNode node(HRuleMarkdownNodeType, m_workingNode, ByteBuffer(), MarkdownNode::Data()); m_workingNode->children().push_back(node); } void MarkdownParser::renderHTML(struct buf* ob, const struct buf* text, void* opaque) { if (!opaque) return; MarkdownParser* p = static_cast<MarkdownParser*>(opaque); p->renderHTML(ByteBufferFromSundown(text)); } void MarkdownParser::renderHTML(const ByteBuffer& text) { if (!m_workingNode) throw NO_WORKING_NODE_ERR; MarkdownNode node(HTMLMarkdownNodeType, m_workingNode, text); m_workingNode->children().push_back(node); } void MarkdownParser::beginQuote(void* opaque) { if (!opaque) return; MarkdownParser* p = static_cast<MarkdownParser*>(opaque); p->beginQuote(); } void MarkdownParser::beginQuote() { if (!m_workingNode) throw NO_WORKING_NODE_ERR; MarkdownNode node(QuoteMarkdownNodeType, m_workingNode); m_workingNode->children().push_back(node); // Push context m_workingNode = &m_workingNode->children().back(); } void MarkdownParser::renderQuote(struct buf* ob, const struct buf* text, void* opaque) { if (!opaque) return; MarkdownParser* p = static_cast<MarkdownParser*>(opaque); p->renderQuote(ByteBufferFromSundown(text)); } void MarkdownParser::renderQuote(const ByteBuffer& text) { if (!m_workingNode) throw NO_WORKING_NODE_ERR; if (m_workingNode->type != QuoteMarkdownNodeType) throw WORKING_NODE_MISMATCH_ERR; m_workingNode->text = text; // Pop context m_workingNode = &m_workingNode->parent(); } void MarkdownParser::blockDidParse(const src_map* map, const uint8_t* txt_data, size_t size, void* opaque) { if (!opaque || !map) return; BytesRangeSet sourceMap; for (size_t i = 0; i < map->size; ++i) { BytesRange byteRange(((range*)map->item[i])->loc, ((range*)map->item[i])->len); sourceMap.push_back(byteRange); } MarkdownParser* p = static_cast<MarkdownParser*>(opaque); p->blockDidParse(sourceMap); } void MarkdownParser::blockDidParse(const BytesRangeSet& sourceMap) { if (m_listBlockContext) { m_listBlockContext = false; // ignore list blocks events return; } if (!m_workingNode) throw NO_WORKING_NODE_ERR; if (m_workingNode->children().empty()) return; MarkdownNode& lMarkdownNode = m_workingNode->children().back(); // Sundown +1 newline compensation // // If new source map would exceed the actual source size // this happens when sundown appends an artifical new line // truncate the source map length to match the actual size if (sourceMap.back().location + sourceMap.back().length > m_sourceLength) { size_t workMapLength = m_sourceLength - sourceMap.back().location; if (!workMapLength) return; // Ignore any artifical trailing new lines in source maps BytesRangeSet workMap = sourceMap; workMap.back().length = workMapLength; lMarkdownNode.sourceMap.append(workMap); } else { lMarkdownNode.sourceMap.append(sourceMap); } // No "inline" list items: // Share the list item source map with its artifical node, if exists. if (lMarkdownNode.type == ListItemMarkdownNodeType && !lMarkdownNode.children().empty() && lMarkdownNode.children().front().sourceMap.empty()) { ByteBuffer& buffer = lMarkdownNode.children().front().text; ByteBuffer mapped = MapBytesRangeSet(sourceMap, *m_source); size_t pos = mapped.find(buffer); if (pos != mapped.npos) { BytesRange range = sourceMap.front(); range.location += pos; range.length = buffer.length(); BytesRangeSet newMap; newMap.push_back(range); lMarkdownNode.children().front().sourceMap.append(newMap); } else { lMarkdownNode.children().front().sourceMap.append(sourceMap); } } } <|endoftext|>
<commit_before>/************************************************************************* * * 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: stillinteraction.cxx,v $ * $Revision: 1.6 $ * * 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_framework.hxx" #include "interaction/stillinteraction.hxx" //_________________________________________________________________________________________________________________ // my own includes //_________________________________________________________________________________________________________________ #include <threadhelp/readguard.hxx> #include <threadhelp/writeguard.hxx> #include <macros/generic.hxx> #include <macros/debug.hxx> //_________________________________________________________________________________________________________________ // interface includes //_________________________________________________________________________________________________________________ #include <com/sun/star/task/XInteractionAbort.hpp> #include <com/sun/star/task/XInteractionApprove.hpp> #include <com/sun/star/document/XInteractionFilterSelect.hpp> #include <com/sun/star/document/AmbigousFilterRequest.hpp> #include <com/sun/star/task/ErrorCodeRequest.hpp> //_________________________________________________________________________________________________________________ // other includes //_________________________________________________________________________________________________________________ #include <vcl/svapp.hxx> #ifndef __RSC #include <tools/errinf.hxx> #endif //_________________________________________________________________________________________________________________ // namespace //_________________________________________________________________________________________________________________ namespace framework{ //_________________________________________________________________________________________________________________ // exported const //_________________________________________________________________________________________________________________ //_________________________________________________________________________________________________________________ // exported definitions //_________________________________________________________________________________________________________________ DEFINE_XINTERFACE_2( StillInteraction , OWeakObject , DIRECT_INTERFACE(css::lang::XTypeProvider ) , DIRECT_INTERFACE(css::task::XInteractionHandler) ) DEFINE_XTYPEPROVIDER_2( StillInteraction , css::lang::XTypeProvider , css::task::XInteractionHandler ) //_________________________________________________________________________________________________________________ StillInteraction::StillInteraction() : ThreadHelpBase ( &Application::GetSolarMutex() ) , ::cppu::OWeakObject( ) , m_aRequest ( ) { } //_________________________________________________________________________________________________________________ void SAL_CALL StillInteraction::handle( const css::uno::Reference< css::task::XInteractionRequest >& xRequest ) throw( css::uno::RuntimeException ) { // safe the request for outside analyzing everytime! css::uno::Any aRequest = xRequest->getRequest(); /* SAFE { */ WriteGuard aWriteLock(m_aLock); m_aRequest = aRequest; aWriteLock.unlock(); /* } SAFE */ // analyze the request // We need XAbort as possible continuation as minimum! // An optional filter selection we can handle too. css::uno::Sequence< css::uno::Reference< css::task::XInteractionContinuation > > lContinuations = xRequest->getContinuations(); css::uno::Reference< css::task::XInteractionAbort > xAbort ; css::uno::Reference< css::task::XInteractionApprove > xApprove ; css::uno::Reference< css::document::XInteractionFilterSelect > xFilter ; sal_Int32 nCount=lContinuations.getLength(); for (sal_Int32 i=0; i<nCount; ++i) { if ( ! xAbort.is() ) xAbort = css::uno::Reference< css::task::XInteractionAbort >( lContinuations[i], css::uno::UNO_QUERY ); if( ! xApprove.is() ) xApprove = css::uno::Reference< css::task::XInteractionApprove >( lContinuations[i], css::uno::UNO_QUERY ); if ( ! xFilter.is() ) xFilter = css::uno::Reference< css::document::XInteractionFilterSelect >( lContinuations[i], css::uno::UNO_QUERY ); } // differ between abortable interactions (error, unknown filter ...) // and other ones (ambigous but not unknown filter ...) css::task::ErrorCodeRequest aErrorCodeRequest ; css::document::AmbigousFilterRequest aAmbigousFilterRequest; if (aRequest>>=aAmbigousFilterRequest) { if (xFilter.is()) { // user selected filter wins everytime! xFilter->setFilter( aAmbigousFilterRequest.SelectedFilter ); xFilter->select(); } } else if( aRequest >>= aErrorCodeRequest ) { // warnings can be ignored => approve // errors must break loading => abort sal_Bool bWarning = (aErrorCodeRequest.ErrCode & ERRCODE_WARNING_MASK) == ERRCODE_WARNING_MASK; if (xApprove.is() && bWarning) xApprove->select(); else if (xAbort.is()) xAbort->select(); } else if (xAbort.is()) xAbort->select(); } //_________________________________________________________________________________________________________________ css::uno::Any StillInteraction::getRequest() const { /* SAFE { */ ReadGuard aReadLock(m_aLock); return m_aRequest; /* } SAFE */ } //_________________________________________________________________________________________________________________ sal_Bool StillInteraction::wasUsed() const { /* SAFE { */ ReadGuard aReadLock(m_aLock); return m_aRequest.hasValue(); /* } SAFE */ } } // namespace framework <commit_msg>INTEGRATION: CWS calcshare2 (1.5.252); FILE MERGED 2008/03/25 10:41:56 mav 1.5.252.1: #i85794# set the default answer for the interaction in case of API call with no InteractionHandler<commit_after>/************************************************************************* * * 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: stillinteraction.cxx,v $ * $Revision: 1.7 $ * * 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_framework.hxx" #include "interaction/stillinteraction.hxx" //_________________________________________________________________________________________________________________ // my own includes //_________________________________________________________________________________________________________________ #include <threadhelp/readguard.hxx> #include <threadhelp/writeguard.hxx> #include <macros/generic.hxx> #include <macros/debug.hxx> //_________________________________________________________________________________________________________________ // interface includes //_________________________________________________________________________________________________________________ #include <com/sun/star/task/XInteractionAbort.hpp> #include <com/sun/star/task/XInteractionApprove.hpp> #include <com/sun/star/document/XInteractionFilterSelect.hpp> #include <com/sun/star/document/AmbigousFilterRequest.hpp> #include <com/sun/star/task/ErrorCodeRequest.hpp> #ifndef _COM_SUN_STAR_DOCUMENT_LOCKEDDOCUMENTREQUEST_HPP_ #include <com/sun/star/document/LockedDocumentRequest.hpp> #endif //_________________________________________________________________________________________________________________ // other includes //_________________________________________________________________________________________________________________ #include <vcl/svapp.hxx> #ifndef __RSC #include <tools/errinf.hxx> #endif //_________________________________________________________________________________________________________________ // namespace //_________________________________________________________________________________________________________________ namespace framework{ //_________________________________________________________________________________________________________________ // exported const //_________________________________________________________________________________________________________________ //_________________________________________________________________________________________________________________ // exported definitions //_________________________________________________________________________________________________________________ DEFINE_XINTERFACE_2( StillInteraction , OWeakObject , DIRECT_INTERFACE(css::lang::XTypeProvider ) , DIRECT_INTERFACE(css::task::XInteractionHandler) ) DEFINE_XTYPEPROVIDER_2( StillInteraction , css::lang::XTypeProvider , css::task::XInteractionHandler ) //_________________________________________________________________________________________________________________ StillInteraction::StillInteraction() : ThreadHelpBase ( &Application::GetSolarMutex() ) , ::cppu::OWeakObject( ) , m_aRequest ( ) { } //_________________________________________________________________________________________________________________ void SAL_CALL StillInteraction::handle( const css::uno::Reference< css::task::XInteractionRequest >& xRequest ) throw( css::uno::RuntimeException ) { // safe the request for outside analyzing everytime! css::uno::Any aRequest = xRequest->getRequest(); /* SAFE { */ WriteGuard aWriteLock(m_aLock); m_aRequest = aRequest; aWriteLock.unlock(); /* } SAFE */ // analyze the request // We need XAbort as possible continuation as minimum! // An optional filter selection we can handle too. css::uno::Sequence< css::uno::Reference< css::task::XInteractionContinuation > > lContinuations = xRequest->getContinuations(); css::uno::Reference< css::task::XInteractionAbort > xAbort ; css::uno::Reference< css::task::XInteractionApprove > xApprove ; css::uno::Reference< css::document::XInteractionFilterSelect > xFilter ; sal_Int32 nCount=lContinuations.getLength(); for (sal_Int32 i=0; i<nCount; ++i) { if ( ! xAbort.is() ) xAbort = css::uno::Reference< css::task::XInteractionAbort >( lContinuations[i], css::uno::UNO_QUERY ); if( ! xApprove.is() ) xApprove = css::uno::Reference< css::task::XInteractionApprove >( lContinuations[i], css::uno::UNO_QUERY ); if ( ! xFilter.is() ) xFilter = css::uno::Reference< css::document::XInteractionFilterSelect >( lContinuations[i], css::uno::UNO_QUERY ); } // differ between abortable interactions (error, unknown filter ...) // and other ones (ambigous but not unknown filter ...) css::task::ErrorCodeRequest aErrorCodeRequest ; css::document::AmbigousFilterRequest aAmbigousFilterRequest; css::document::LockedDocumentRequest aLockedDocumentRequest; if (aRequest>>=aAmbigousFilterRequest) { if (xFilter.is()) { // user selected filter wins everytime! xFilter->setFilter( aAmbigousFilterRequest.SelectedFilter ); xFilter->select(); } } else if( aRequest >>= aErrorCodeRequest ) { // warnings can be ignored => approve // errors must break loading => abort sal_Bool bWarning = (aErrorCodeRequest.ErrCode & ERRCODE_WARNING_MASK) == ERRCODE_WARNING_MASK; if (xApprove.is() && bWarning) xApprove->select(); else if (xAbort.is()) xAbort->select(); } else if( aRequest >>= aLockedDocumentRequest ) { // the locked document should be opened readonly by default if (xApprove.is()) xApprove->select(); else if (xAbort.is()) xAbort->select(); } else if (xAbort.is()) xAbort->select(); } //_________________________________________________________________________________________________________________ css::uno::Any StillInteraction::getRequest() const { /* SAFE { */ ReadGuard aReadLock(m_aLock); return m_aRequest; /* } SAFE */ } //_________________________________________________________________________________________________________________ sal_Bool StillInteraction::wasUsed() const { /* SAFE { */ ReadGuard aReadLock(m_aLock); return m_aRequest.hasValue(); /* } SAFE */ } } // namespace framework <|endoftext|>
<commit_before><commit_msg>Fix memory leak<commit_after><|endoftext|>
<commit_before><commit_msg>avoid to degenerate the view frustum if there is only a single point in the scene<commit_after><|endoftext|>
<commit_before>extern "C" { #include <lua.h> #include <lualib.h> #include <lauxlib.h> } int main() { lua_State *L = lua_open(); luaL_openlibs(L); luaL_loadfile(L, "hello_world.lua"); lua_pcall(L, 0, 0, 0); lua_getglobal(L, "hello"); lua_pcall(L, 0, 0, 0); } <commit_msg>Extended the function call with an argument and return value.<commit_after>extern "C" { #include <lua.h> #include <lualib.h> #include <lauxlib.h> } #include <iostream> int main() { lua_State *L = lua_open(); luaL_openlibs(L); luaL_loadfile(L, "hello_world.lua"); lua_pcall(L, 0, 0, 0); lua_getglobal(L, "square"); lua_pushnumber(L, 6); lua_pcall(L, 1, 1, 0); int result = lua_tonumber(L, -1); std::cout << "Returned " << result << std::endl; } <|endoftext|>
<commit_before>#include <DynamicMultiBody.h> #include <HumanoidDynamicMultiBody.h> #if 0 #define RESETDEBUG4(y) { ofstream DebugFile; DebugFile.open(y,ofstream::out); DebugFile.close();} #define ODEBUG4(x,y) { ofstream DebugFile; DebugFile.open(y,ofstream::app); DebugFile << "HumanoidDynamicMultiBody: " << x << endl; DebugFile.close();} #else #define RESETDEBUG4(y) #define ODEBUG4(x,y) #endif #define RESETDEBUG6(y) #define ODEBUG6(x,y) #define RESETDEBUG5(y) { ofstream DebugFile; DebugFile.open(y,ofstream::out); DebugFile.close();} #define ODEBUG5(x,y) { ofstream DebugFile; DebugFile.open(y,ofstream::app); DebugFile << "HumanoidDynamicMultiBody: " << x << endl; DebugFile.close();} #if 1 #define ODEBUG(x) #else #define ODEBUG(x) std::cout << x << endl; #endif #define ODEBUG3(x) std::cout << x << endl; using namespace dynamicsJRLJapan; HumanoidDynamicMultiBody::HumanoidDynamicMultiBody() { string aFileName = "HumanoidSpecificities.xml"; DynamicMultiBody *aDMB = new DynamicMultiBody(); m_DMB = aDMB; } HumanoidDynamicMultiBody::HumanoidDynamicMultiBody(CjrlDynamicRobot* aDMB, string aFileNameForHumanoidSpecificities) { m_DMB = aDMB; SetHumanoidSpecificitiesFile(aFileNameForHumanoidSpecificities); } void HumanoidDynamicMultiBody::SetHumanoidSpecificitiesFile(string &aFileNameForHumanoidSpecificities) { string aHumanoidName="HRP2JRL"; m_HS = new HumanoidSpecificities(); if (m_HS!=0) { m_HS->ReadXML(aFileNameForHumanoidSpecificities,aHumanoidName); double AnklePosition[3]; // Take the right ankle position (should be equivalent) m_HS->GetAnklePosition(-1,AnklePosition); m_AnkleSoilDistance = AnklePosition[2]; ODEBUG("AnkleSoilDistance =" << m_AnkleSoilDistance); // Lenght of the hip (necessary for double HipLength[3]; // Takes the left one. m_HS->GetHipLength(1,HipLength); ODEBUG(WaistToHip[0] << " " << WaistToHip[1] << " " << WaistToHip[2] << " "); m_Dt(0) = HipLength[0]; m_Dt(1) = HipLength[1]; m_Dt(2) = HipLength[2]; MAL_S3_VECTOR(StaticToTheLeftHip,double); MAL_S3_VECTOR(StaticToTheRightHip,double); // Displacement between the hip and the waist. double WaistToHip[3]; m_HS->GetWaistToHip(1,WaistToHip); m_StaticToTheLeftHip(0) = WaistToHip[0]; m_StaticToTheLeftHip(1) = WaistToHip[1]; m_StaticToTheLeftHip(2) = WaistToHip[2]; m_TranslationToTheLeftHip = m_StaticToTheLeftHip; m_HS->GetWaistToHip(-1,WaistToHip); m_StaticToTheRightHip(0) = WaistToHip[0]; m_StaticToTheRightHip(1) = WaistToHip[1]; m_StaticToTheRightHip(2) = WaistToHip[2]; m_TranslationToTheRightHip = m_StaticToTheRightHip; // If the Dynamic Multibody object is already loaded // create the link between the joints and the effector semantic. if (m_DMB->numberDof()!=0) LinkBetweenJointsAndEndEffectorSemantic(); } else { cerr << "Warning: No appropriate definition of Humanoid Specifities" << endl; cerr << "Use default value: " << 0.1 << endl; m_AnkleSoilDistance = 0.1; // Displacement between the hip and the waist. m_Dt(0) = 0.0; m_Dt(1) = 0.04; m_Dt(2) = 0.0; } } HumanoidDynamicMultiBody::~HumanoidDynamicMultiBody() { if (m_HS!=0) delete m_HS; } void HumanoidDynamicMultiBody::LinkBetweenJointsAndEndEffectorSemantic() { if (m_HS==0) return; // Link the correct joints. // Get the left hand. std::vector<int> JointForOneLimb = m_HS->GetArmJoints(1); int ListeJointsSize = JointForOneLimb.size(); int EndIndex = JointForOneLimb[ListeJointsSize-1]; DynamicMultiBody *m_SDMB = dynamic_cast<DynamicMultiBody *>(m_DMB); if (m_DMB!=0) m_LeftHandJoint = m_SDMB->GetJointFromVRMLID(EndIndex); // Get the right hand. JointForOneLimb.clear(); JointForOneLimb = m_HS->GetArmJoints(-1); ListeJointsSize = JointForOneLimb.size(); EndIndex = JointForOneLimb[ListeJointsSize-1]; if (m_SDMB!=0) m_RightHandJoint = m_SDMB->GetJointFromVRMLID(EndIndex); // Get the left foot. JointForOneLimb.clear(); JointForOneLimb = m_HS->GetFootJoints(1); ListeJointsSize = JointForOneLimb.size(); EndIndex = JointForOneLimb[ListeJointsSize-1]; ODEBUG("Joints for the left foot:" << EndIndex); if (m_SDMB!=0) m_LeftFootJoint = m_SDMB->GetJointFromVRMLID(EndIndex); // Get the right foot. JointForOneLimb.clear(); JointForOneLimb = m_HS->GetFootJoints(-1); ListeJointsSize = JointForOneLimb.size(); EndIndex = JointForOneLimb[ListeJointsSize-1]; ODEBUG("Joints for the right foot:" << EndIndex); if (m_SDMB!=0) m_RightFootJoint = m_SDMB->GetJointFromVRMLID(EndIndex); // Get the gaze joint (head) of the humanoid. JointForOneLimb.clear(); JointForOneLimb = m_HS->GetHeadJoints(); ListeJointsSize = JointForOneLimb.size(); EndIndex = JointForOneLimb[ListeJointsSize-1]; if (m_SDMB!=0) m_GazeJoint = m_SDMB->GetJointFromVRMLID(EndIndex); // Get the waist joint of the humanoid. std::vector<int> JointsForWaist = m_HS->GetWaistJoints(); if (JointsForWaist.size()==1) m_WaistJoint = m_SDMB->GetJointFromVRMLID(JointsForWaist[0]); } void HumanoidDynamicMultiBody::GetJointIDInConfigurationFromVRMLID(std::vector<int> &aVector) { DynamicMultiBody *a_SDMB = dynamic_cast<DynamicMultiBody *>(m_DMB); if (a_SDMB!=0) a_SDMB->GetJointIDInConfigurationFromVRMLID(aVector); } const MAL_S3_VECTOR(,double) & HumanoidDynamicMultiBody::zeroMomentumPoint() const { return m_ZeroMomentumPoint; } void HumanoidDynamicMultiBody::ComputingZeroMomentumPoint() { DynamicMultiBody * aDMB = (DynamicMultiBody *)m_DMB; m_ZeroMomentumPoint = aDMB->getZMP(); } /* Methods related to the fixed joints */ void HumanoidDynamicMultiBody::addFixedJoint(CjrlJoint *inFixedJoint) { m_VectorOfFixedJoints.insert(m_VectorOfFixedJoints.end(),inFixedJoint); } unsigned int HumanoidDynamicMultiBody::countFixedJoints() const { return m_VectorOfFixedJoints.size(); } void HumanoidDynamicMultiBody::removeFixedJoint(CjrlJoint * inFixedJoint) { std::vector<CjrlJoint *>::iterator it_Joint = m_VectorOfFixedJoints.begin(); while((*it_Joint!= inFixedJoint) && (it_Joint!=m_VectorOfFixedJoints.end())) it_Joint++; if (it_Joint!=m_VectorOfFixedJoints.end()) m_VectorOfFixedJoints.erase(it_Joint); } void HumanoidDynamicMultiBody::clearFixedJoints() { m_VectorOfFixedJoints.clear(); } CjrlJoint& HumanoidDynamicMultiBody::fixedJoint(unsigned int inJointRank) { if ((inJointRank>0) & (inJointRank<=m_VectorOfFixedJoints.size())) return *m_VectorOfFixedJoints[inJointRank]; } /* End of Methods related to the fixed joints */ /***************************************************/ /* Implementation of the proxy design pattern for */ /* the part inherited from jrlDynamicRobot. */ /***************************************************/ void HumanoidDynamicMultiBody::rootJoint(CjrlJoint &inJoint) { if (m_DMB!=0) m_DMB->rootJoint(inJoint); } CjrlJoint *HumanoidDynamicMultiBody::rootJoint() const { if (m_DMB==0) return 0; return m_DMB->rootJoint(); } std::vector< CjrlJoint* > HumanoidDynamicMultiBody::jointVector() { return m_DMB->jointVector(); } unsigned int HumanoidDynamicMultiBody::numberDof() const { return m_DMB->numberDof(); } bool HumanoidDynamicMultiBody::currentConfiguration(const MAL_VECTOR(,double) & inConfig) { return m_DMB->currentConfiguration(inConfig); } const MAL_VECTOR(,double) & HumanoidDynamicMultiBody::currentConfiguration() const { return m_DMB->currentConfiguration(); } bool HumanoidDynamicMultiBody::currentVelocity(const MAL_VECTOR(,double) & inVelocity) { return m_DMB->currentVelocity(inVelocity); } const MAL_VECTOR(,double) & HumanoidDynamicMultiBody::currentVelocity() const { return m_DMB->currentVelocity(); } bool HumanoidDynamicMultiBody::currentAcceleration(const MAL_VECTOR(,double) & inAcceleration) { return m_DMB->currentAcceleration(inAcceleration); } const MAL_VECTOR(,double) & HumanoidDynamicMultiBody::currentAcceleration() const { return m_DMB->currentAcceleration(); } bool HumanoidDynamicMultiBody::computeForwardKinematics() { bool r; r= m_DMB->computeForwardKinematics(); ComputingZeroMomentumPoint(); return r; } bool HumanoidDynamicMultiBody::computeCenterOfMassDynamics() { return m_DMB->computeCenterOfMassDynamics(); } const MAL_S3_VECTOR(,double) & HumanoidDynamicMultiBody::positionCenterOfMass() { return m_DMB->positionCenterOfMass(); } const MAL_S3_VECTOR(,double) & HumanoidDynamicMultiBody::velocityCenterOfMass() { return m_DMB->velocityCenterOfMass(); } const MAL_S3_VECTOR(,double) & HumanoidDynamicMultiBody::accelerationCenterOfMass() { return m_DMB->accelerationCenterOfMass(); } const MAL_S3_VECTOR(,double) & HumanoidDynamicMultiBody::linearMomentumRobot() { return m_DMB->linearMomentumRobot(); } const MAL_S3_VECTOR(,double) & HumanoidDynamicMultiBody::derivativeLinearMomentum() { return m_DMB->derivativeLinearMomentum(); } const MAL_S3_VECTOR(,double) & HumanoidDynamicMultiBody::angularMomentumRobot() { return m_DMB->angularMomentumRobot(); } const MAL_S3_VECTOR(,double) & HumanoidDynamicMultiBody::derivativeAngularMomentum() { return m_DMB->derivativeAngularMomentum(); } void HumanoidDynamicMultiBody::computeJacobianCenterOfMass() { return m_DMB->computeJacobianCenterOfMass(); } const MAL_MATRIX(,double) & HumanoidDynamicMultiBody::jacobianCenterOfMass() const { return m_DMB->jacobianCenterOfMass(); } bool HumanoidDynamicMultiBody::jacobianJointWrtFixedJoint(CjrlJoint* inJoint, MAL_MATRIX(,double) & outJacobian) { cerr<< " The method HumanoidDynamicMultiBody::jacobianJointWrtFixedJoint " <<endl << " is not implemented yet. " << endl; return true; } double HumanoidDynamicMultiBody::footHeight() const { cerr<< " HumanoidDynamicMultiBody::footHeight() implementation specific to HRP2" <<endl; return 0.105; } void HumanoidDynamicMultiBody::waist(CjrlJoint * inWaist) { // This method is ineffective regarding the internals. } CjrlJoint* HumanoidDynamicMultiBody::waist() { return m_WaistJoint; } double HumanoidDynamicMultiBody::mass() const { return m_DMB->mass(); } /***************************************************/ /* End of the implementation */ /***************************************************/ <commit_msg>fixed a bug in fixedJoints(unsigned int rank). (previous code commented)<commit_after>#include <DynamicMultiBody.h> #include <HumanoidDynamicMultiBody.h> #if 0 #define RESETDEBUG4(y) { ofstream DebugFile; DebugFile.open(y,ofstream::out); DebugFile.close();} #define ODEBUG4(x,y) { ofstream DebugFile; DebugFile.open(y,ofstream::app); DebugFile << "HumanoidDynamicMultiBody: " << x << endl; DebugFile.close();} #else #define RESETDEBUG4(y) #define ODEBUG4(x,y) #endif #define RESETDEBUG6(y) #define ODEBUG6(x,y) #define RESETDEBUG5(y) { ofstream DebugFile; DebugFile.open(y,ofstream::out); DebugFile.close();} #define ODEBUG5(x,y) { ofstream DebugFile; DebugFile.open(y,ofstream::app); DebugFile << "HumanoidDynamicMultiBody: " << x << endl; DebugFile.close();} #if 1 #define ODEBUG(x) #else #define ODEBUG(x) std::cout << x << endl; #endif #define ODEBUG3(x) std::cout << x << endl; using namespace dynamicsJRLJapan; HumanoidDynamicMultiBody::HumanoidDynamicMultiBody() { string aFileName = "HumanoidSpecificities.xml"; DynamicMultiBody *aDMB = new DynamicMultiBody(); m_DMB = aDMB; } HumanoidDynamicMultiBody::HumanoidDynamicMultiBody(CjrlDynamicRobot* aDMB, string aFileNameForHumanoidSpecificities) { m_DMB = aDMB; SetHumanoidSpecificitiesFile(aFileNameForHumanoidSpecificities); } void HumanoidDynamicMultiBody::SetHumanoidSpecificitiesFile(string &aFileNameForHumanoidSpecificities) { string aHumanoidName="HRP2JRL"; m_HS = new HumanoidSpecificities(); if (m_HS!=0) { m_HS->ReadXML(aFileNameForHumanoidSpecificities,aHumanoidName); double AnklePosition[3]; // Take the right ankle position (should be equivalent) m_HS->GetAnklePosition(-1,AnklePosition); m_AnkleSoilDistance = AnklePosition[2]; ODEBUG("AnkleSoilDistance =" << m_AnkleSoilDistance); // Lenght of the hip (necessary for double HipLength[3]; // Takes the left one. m_HS->GetHipLength(1,HipLength); ODEBUG(WaistToHip[0] << " " << WaistToHip[1] << " " << WaistToHip[2] << " "); m_Dt(0) = HipLength[0]; m_Dt(1) = HipLength[1]; m_Dt(2) = HipLength[2]; MAL_S3_VECTOR(StaticToTheLeftHip,double); MAL_S3_VECTOR(StaticToTheRightHip,double); // Displacement between the hip and the waist. double WaistToHip[3]; m_HS->GetWaistToHip(1,WaistToHip); m_StaticToTheLeftHip(0) = WaistToHip[0]; m_StaticToTheLeftHip(1) = WaistToHip[1]; m_StaticToTheLeftHip(2) = WaistToHip[2]; m_TranslationToTheLeftHip = m_StaticToTheLeftHip; m_HS->GetWaistToHip(-1,WaistToHip); m_StaticToTheRightHip(0) = WaistToHip[0]; m_StaticToTheRightHip(1) = WaistToHip[1]; m_StaticToTheRightHip(2) = WaistToHip[2]; m_TranslationToTheRightHip = m_StaticToTheRightHip; // If the Dynamic Multibody object is already loaded // create the link between the joints and the effector semantic. if (m_DMB->numberDof()!=0) LinkBetweenJointsAndEndEffectorSemantic(); } else { cerr << "Warning: No appropriate definition of Humanoid Specifities" << endl; cerr << "Use default value: " << 0.1 << endl; m_AnkleSoilDistance = 0.1; // Displacement between the hip and the waist. m_Dt(0) = 0.0; m_Dt(1) = 0.04; m_Dt(2) = 0.0; } } HumanoidDynamicMultiBody::~HumanoidDynamicMultiBody() { if (m_HS!=0) delete m_HS; } void HumanoidDynamicMultiBody::LinkBetweenJointsAndEndEffectorSemantic() { if (m_HS==0) return; // Link the correct joints. // Get the left hand. std::vector<int> JointForOneLimb = m_HS->GetArmJoints(1); int ListeJointsSize = JointForOneLimb.size(); int EndIndex = JointForOneLimb[ListeJointsSize-1]; DynamicMultiBody *m_SDMB = dynamic_cast<DynamicMultiBody *>(m_DMB); if (m_DMB!=0) m_LeftHandJoint = m_SDMB->GetJointFromVRMLID(EndIndex); // Get the right hand. JointForOneLimb.clear(); JointForOneLimb = m_HS->GetArmJoints(-1); ListeJointsSize = JointForOneLimb.size(); EndIndex = JointForOneLimb[ListeJointsSize-1]; if (m_SDMB!=0) m_RightHandJoint = m_SDMB->GetJointFromVRMLID(EndIndex); // Get the left foot. JointForOneLimb.clear(); JointForOneLimb = m_HS->GetFootJoints(1); ListeJointsSize = JointForOneLimb.size(); EndIndex = JointForOneLimb[ListeJointsSize-1]; ODEBUG("Joints for the left foot:" << EndIndex); if (m_SDMB!=0) m_LeftFootJoint = m_SDMB->GetJointFromVRMLID(EndIndex); // Get the right foot. JointForOneLimb.clear(); JointForOneLimb = m_HS->GetFootJoints(-1); ListeJointsSize = JointForOneLimb.size(); EndIndex = JointForOneLimb[ListeJointsSize-1]; ODEBUG("Joints for the right foot:" << EndIndex); if (m_SDMB!=0) m_RightFootJoint = m_SDMB->GetJointFromVRMLID(EndIndex); // Get the gaze joint (head) of the humanoid. JointForOneLimb.clear(); JointForOneLimb = m_HS->GetHeadJoints(); ListeJointsSize = JointForOneLimb.size(); EndIndex = JointForOneLimb[ListeJointsSize-1]; if (m_SDMB!=0) m_GazeJoint = m_SDMB->GetJointFromVRMLID(EndIndex); // Get the waist joint of the humanoid. std::vector<int> JointsForWaist = m_HS->GetWaistJoints(); if (JointsForWaist.size()==1) m_WaistJoint = m_SDMB->GetJointFromVRMLID(JointsForWaist[0]); } void HumanoidDynamicMultiBody::GetJointIDInConfigurationFromVRMLID(std::vector<int> &aVector) { DynamicMultiBody *a_SDMB = dynamic_cast<DynamicMultiBody *>(m_DMB); if (a_SDMB!=0) a_SDMB->GetJointIDInConfigurationFromVRMLID(aVector); } const MAL_S3_VECTOR(,double) & HumanoidDynamicMultiBody::zeroMomentumPoint() const { return m_ZeroMomentumPoint; } void HumanoidDynamicMultiBody::ComputingZeroMomentumPoint() { DynamicMultiBody * aDMB = (DynamicMultiBody *)m_DMB; m_ZeroMomentumPoint = aDMB->getZMP(); } /* Methods related to the fixed joints */ void HumanoidDynamicMultiBody::addFixedJoint(CjrlJoint *inFixedJoint) { m_VectorOfFixedJoints.insert(m_VectorOfFixedJoints.end(),inFixedJoint); } unsigned int HumanoidDynamicMultiBody::countFixedJoints() const { return m_VectorOfFixedJoints.size(); } void HumanoidDynamicMultiBody::removeFixedJoint(CjrlJoint * inFixedJoint) { std::vector<CjrlJoint *>::iterator it_Joint = m_VectorOfFixedJoints.begin(); while((*it_Joint!= inFixedJoint) && (it_Joint!=m_VectorOfFixedJoints.end())) it_Joint++; if (it_Joint!=m_VectorOfFixedJoints.end()) m_VectorOfFixedJoints.erase(it_Joint); } void HumanoidDynamicMultiBody::clearFixedJoints() { m_VectorOfFixedJoints.clear(); } CjrlJoint& HumanoidDynamicMultiBody::fixedJoint(unsigned int inJointRank) { //if ((inJointRank>0) & (inJointRank<=m_VectorOfFixedJoints.size())) if (inJointRank<m_VectorOfFixedJoints.size()) return *m_VectorOfFixedJoints[inJointRank]; } /* End of Methods related to the fixed joints */ /***************************************************/ /* Implementation of the proxy design pattern for */ /* the part inherited from jrlDynamicRobot. */ /***************************************************/ void HumanoidDynamicMultiBody::rootJoint(CjrlJoint &inJoint) { if (m_DMB!=0) m_DMB->rootJoint(inJoint); } CjrlJoint *HumanoidDynamicMultiBody::rootJoint() const { if (m_DMB==0) return 0; return m_DMB->rootJoint(); } std::vector< CjrlJoint* > HumanoidDynamicMultiBody::jointVector() { return m_DMB->jointVector(); } unsigned int HumanoidDynamicMultiBody::numberDof() const { return m_DMB->numberDof(); } bool HumanoidDynamicMultiBody::currentConfiguration(const MAL_VECTOR(,double) & inConfig) { return m_DMB->currentConfiguration(inConfig); } const MAL_VECTOR(,double) & HumanoidDynamicMultiBody::currentConfiguration() const { return m_DMB->currentConfiguration(); } bool HumanoidDynamicMultiBody::currentVelocity(const MAL_VECTOR(,double) & inVelocity) { return m_DMB->currentVelocity(inVelocity); } const MAL_VECTOR(,double) & HumanoidDynamicMultiBody::currentVelocity() const { return m_DMB->currentVelocity(); } bool HumanoidDynamicMultiBody::currentAcceleration(const MAL_VECTOR(,double) & inAcceleration) { return m_DMB->currentAcceleration(inAcceleration); } const MAL_VECTOR(,double) & HumanoidDynamicMultiBody::currentAcceleration() const { return m_DMB->currentAcceleration(); } bool HumanoidDynamicMultiBody::computeForwardKinematics() { bool r; r= m_DMB->computeForwardKinematics(); ComputingZeroMomentumPoint(); return r; } bool HumanoidDynamicMultiBody::computeCenterOfMassDynamics() { return m_DMB->computeCenterOfMassDynamics(); } const MAL_S3_VECTOR(,double) & HumanoidDynamicMultiBody::positionCenterOfMass() { return m_DMB->positionCenterOfMass(); } const MAL_S3_VECTOR(,double) & HumanoidDynamicMultiBody::velocityCenterOfMass() { return m_DMB->velocityCenterOfMass(); } const MAL_S3_VECTOR(,double) & HumanoidDynamicMultiBody::accelerationCenterOfMass() { return m_DMB->accelerationCenterOfMass(); } const MAL_S3_VECTOR(,double) & HumanoidDynamicMultiBody::linearMomentumRobot() { return m_DMB->linearMomentumRobot(); } const MAL_S3_VECTOR(,double) & HumanoidDynamicMultiBody::derivativeLinearMomentum() { return m_DMB->derivativeLinearMomentum(); } const MAL_S3_VECTOR(,double) & HumanoidDynamicMultiBody::angularMomentumRobot() { return m_DMB->angularMomentumRobot(); } const MAL_S3_VECTOR(,double) & HumanoidDynamicMultiBody::derivativeAngularMomentum() { return m_DMB->derivativeAngularMomentum(); } void HumanoidDynamicMultiBody::computeJacobianCenterOfMass() { return m_DMB->computeJacobianCenterOfMass(); } const MAL_MATRIX(,double) & HumanoidDynamicMultiBody::jacobianCenterOfMass() const { return m_DMB->jacobianCenterOfMass(); } bool HumanoidDynamicMultiBody::jacobianJointWrtFixedJoint(CjrlJoint* inJoint, MAL_MATRIX(,double) & outJacobian) { cerr<< " The method HumanoidDynamicMultiBody::jacobianJointWrtFixedJoint " <<endl << " is not implemented yet. " << endl; return true; } double HumanoidDynamicMultiBody::footHeight() const { cerr<< " HumanoidDynamicMultiBody::footHeight() implementation specific to HRP2" <<endl; return 0.105; } void HumanoidDynamicMultiBody::waist(CjrlJoint * inWaist) { // This method is ineffective regarding the internals. } CjrlJoint* HumanoidDynamicMultiBody::waist() { return m_WaistJoint; } double HumanoidDynamicMultiBody::mass() const { return m_DMB->mass(); } /***************************************************/ /* End of the implementation */ /***************************************************/ <|endoftext|>
<commit_before>// The MIT License (MIT) // Copyright (c) 2016, Microsoft // 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 <algorithm> #include <iostream> // TODO: Remove this temporary include. #include <math.h> #include "BitFunnel/Index/Factories.h" #include "BitFunnel/Term.h" #include "TermTreatments.h" namespace BitFunnel { //************************************************************************* // // Factory methods. // //************************************************************************* std::unique_ptr<ITermTreatment> Factories::CreateTreatmentPrivateRank0() { return std::unique_ptr<ITermTreatment>(new TreatmentPrivateRank0()); } std::unique_ptr<ITermTreatment> Factories::CreateTreatmentPrivateSharedRank0(double density, double snr) { return std::unique_ptr<ITermTreatment>( new TreatmentPrivateSharedRank0(density, snr)); } std::unique_ptr<ITermTreatment> Factories::CreateTreatmentPrivateSharedRank0And3(double density, double snr) { return std::unique_ptr<ITermTreatment>( new TreatmentPrivateSharedRank0And3(density, snr)); } std::unique_ptr<ITermTreatment> Factories::CreateTreatmentPrivateSharedRank0ToN(double density, double snr) { return std::unique_ptr<ITermTreatment>( new TreatmentPrivateSharedRank0ToN(density, snr)); } //************************************************************************* // // TreatmentPrivateRank0 // // All terms get the same treatment - a single, private, rank 0 row. // //************************************************************************* TreatmentPrivateRank0::TreatmentPrivateRank0() { // Same configuration for all terms - one private rank 0 row. m_configuration.push_front(RowConfiguration::Entry(0, 1, true)); //std::cout << "Single configuration: "; //m_configuration.Write(std::cout); //std::cout << std::endl; } RowConfiguration TreatmentPrivateRank0::GetTreatment(Term /*term*/) const { return m_configuration; } //************************************************************************* // // TreatmentPrivateSharedRank0 // // Terms get one or more rank 0 rows that could be private or shared, // depending on term frequency. // //************************************************************************* TreatmentPrivateSharedRank0::TreatmentPrivateSharedRank0(double density, double snr) { // Fill up vector of RowConfigurations. GetTreatment() will use the // IdfSum() value of the Term as an index into this vector. for (Term::IdfX10 idf = 0; idf <= Term::c_maxIdfX10Value; ++idf) { RowConfiguration configuration; double frequency = Term::IdfX10ToFrequency(idf); if (frequency >= density) { // This term is so common that it must be assigned a private row. configuration.push_front(RowConfiguration::Entry(0, 1, true)); } else { int k = Term::ComputeRowCount(frequency, density, snr); configuration.push_front(RowConfiguration::Entry(0, k, false)); } m_configurations.push_back(configuration); //std::cout << idf / 10.0 << ": "; //m_configurations.back().Write(std::cout); //std::cout << std::endl; } } RowConfiguration TreatmentPrivateSharedRank0::GetTreatment(Term term) const { // DESIGN NOTE: we can't c_maxIdfX10Value directly to min because min // takes a reference and the compiler has already turned it into a // constant, which we can't take a reference to. auto local = Term::c_maxIdfX10Value; Term::IdfX10 idf = std::min(term.GetIdfSum(), local); return m_configurations[idf]; } //************************************************************************* // // TreatmentPrivateSharedRank0And3 // // Terms get one or more rank 0 and rank 3 rows that could be private or // shared, depending on term frequency. // //************************************************************************* TreatmentPrivateSharedRank0And3::TreatmentPrivateSharedRank0And3(double density, double snr) { // Fill up vector of RowConfigurations. GetTreatment() will use the // IdfSum() value of the Term as an index into this vector. for (Term::IdfX10 idf = 0; idf <= Term::c_maxIdfX10Value; ++idf) { RowConfiguration configuration; double frequency = Term::IdfX10ToFrequency(idf); if (frequency > density) { // This term is so common that it must be assigned a private row. configuration.push_front(RowConfiguration::Entry(0, 1, true)); } else { // Determine the number of rows, k, required to reach the // desired signal to noise ratio, snr, given a certain bit // density. // TODO: consider checking for overflow? int k = Term::ComputeRowCount(frequency, density, snr); configuration.push_front(RowConfiguration::Entry(0, 2, false)); if (k > 2) { Rank rank = 3; double frequencyAtRank = Term::FrequencyAtRank(frequency, rank); if (frequencyAtRank >= density) { configuration.push_front(RowConfiguration::Entry(rank, 1, true)); } else { configuration.push_front(RowConfiguration::Entry(rank, k - 2, false)); } } } m_configurations.push_back(configuration); //std::cout << idf / 10.0 << ": "; //m_configurations.back().Write(std::cout); //std::cout << std::endl; } } RowConfiguration TreatmentPrivateSharedRank0And3::GetTreatment(Term term) const { // DESIGN NOTE: we can't c_maxIdfX10Value directly to min because min // takes a reference and the compiler has already turned it into a // constant, which we can't take a reference to. auto local = Term::c_maxIdfX10Value; Term::IdfX10 idf = std::min(term.GetIdfSum(), local); return m_configurations[idf]; } //************************************************************************* // // TreatmentPrivateSharedRank0ToN // // Two rank 0 rows followed by rows of increasing rank until the bit density // is > .5 or we run out of rows. Due to limitatons in other BitFunnel code, // we also top out at rank 6. // //************************************************************************* TreatmentPrivateSharedRank0ToN::TreatmentPrivateSharedRank0ToN(double density, double snr) { // TODO: what should maxDensity be? Note that this is different from the // density liimt that's passed in. const double maxDensity = 0.5; // Fill up vector of RowConfigurations. GetTreatment() will use the // IdfSum() value of the Term as an index into this vector. // // TODO: we should make sure we get "enough" rows if we end up with a // high rank private row. for (Term::IdfX10 idf = 0; idf <= Term::c_maxIdfX10Value; ++idf) { RowConfiguration configuration; double frequency = Term::IdfX10ToFrequency(idf); if (frequency > density) { // This term is so common that it must be assigned a private row. configuration.push_front(RowConfiguration::Entry(0, 1, true)); } else { // TODO: fix other limitations so this can be higher than 6? const Rank maxRank = (std::min)(Term::ComputeMaxRank(frequency, maxDensity), static_cast<Rank>(6u)); int numRows = Term::ComputeRowCount(frequency, density, snr); configuration.push_front(RowConfiguration::Entry(0, 2, false)); numRows -= 2; Rank rank = 1; while (rank < maxRank && numRows > 0) { double frequencyAtRank = Term::FrequencyAtRank(frequency, rank); if (frequencyAtRank >= density) { configuration.push_front(RowConfiguration::Entry(rank, 1, true)); } else { configuration.push_front(RowConfiguration::Entry(rank, 1, false)); } ++rank; --numRows; } if (numRows > 0) { double frequencyAtRank = Term::FrequencyAtRank(frequency, rank); if (frequencyAtRank >= density) { configuration.push_front(RowConfiguration::Entry(rank, 1, true)); } else { configuration.push_front(RowConfiguration::Entry(rank, numRows, false)); } } } m_configurations.push_back(configuration); //std::cout << idf / 10.0 << ": "; //m_configurations.back().Write(std::cout); //std::cout << std::endl; } } RowConfiguration TreatmentPrivateSharedRank0ToN::GetTreatment(Term term) const { // DESIGN NOTE: we can't c_maxIdfX10Value directly to min because min // takes a reference and the compiler has already turned it into a // constant, which we can't take a reference to. auto local = Term::c_maxIdfX10Value; Term::IdfX10 idf = std::min(term.GetIdfSum(), local); return m_configurations[idf]; } } <commit_msg>Tweak higher rank TermTreatment.<commit_after>// The MIT License (MIT) // Copyright (c) 2016, Microsoft // 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 <algorithm> #include <iostream> // TODO: Remove this temporary include. #include <math.h> #include "BitFunnel/Index/Factories.h" #include "BitFunnel/Term.h" #include "TermTreatments.h" namespace BitFunnel { //************************************************************************* // // Factory methods. // //************************************************************************* std::unique_ptr<ITermTreatment> Factories::CreateTreatmentPrivateRank0() { return std::unique_ptr<ITermTreatment>(new TreatmentPrivateRank0()); } std::unique_ptr<ITermTreatment> Factories::CreateTreatmentPrivateSharedRank0(double density, double snr) { return std::unique_ptr<ITermTreatment>( new TreatmentPrivateSharedRank0(density, snr)); } std::unique_ptr<ITermTreatment> Factories::CreateTreatmentPrivateSharedRank0And3(double density, double snr) { return std::unique_ptr<ITermTreatment>( new TreatmentPrivateSharedRank0And3(density, snr)); } std::unique_ptr<ITermTreatment> Factories::CreateTreatmentPrivateSharedRank0ToN(double density, double snr) { return std::unique_ptr<ITermTreatment>( new TreatmentPrivateSharedRank0ToN(density, snr)); } //************************************************************************* // // TreatmentPrivateRank0 // // All terms get the same treatment - a single, private, rank 0 row. // //************************************************************************* TreatmentPrivateRank0::TreatmentPrivateRank0() { // Same configuration for all terms - one private rank 0 row. m_configuration.push_front(RowConfiguration::Entry(0, 1, true)); //std::cout << "Single configuration: "; //m_configuration.Write(std::cout); //std::cout << std::endl; } RowConfiguration TreatmentPrivateRank0::GetTreatment(Term /*term*/) const { return m_configuration; } //************************************************************************* // // TreatmentPrivateSharedRank0 // // Terms get one or more rank 0 rows that could be private or shared, // depending on term frequency. // //************************************************************************* TreatmentPrivateSharedRank0::TreatmentPrivateSharedRank0(double density, double snr) { // Fill up vector of RowConfigurations. GetTreatment() will use the // IdfSum() value of the Term as an index into this vector. for (Term::IdfX10 idf = 0; idf <= Term::c_maxIdfX10Value; ++idf) { RowConfiguration configuration; double frequency = Term::IdfX10ToFrequency(idf); if (frequency >= density) { // This term is so common that it must be assigned a private row. configuration.push_front(RowConfiguration::Entry(0, 1, true)); } else { int k = Term::ComputeRowCount(frequency, density, snr); configuration.push_front(RowConfiguration::Entry(0, k, false)); } m_configurations.push_back(configuration); //std::cout << idf / 10.0 << ": "; //m_configurations.back().Write(std::cout); //std::cout << std::endl; } } RowConfiguration TreatmentPrivateSharedRank0::GetTreatment(Term term) const { // DESIGN NOTE: we can't c_maxIdfX10Value directly to min because min // takes a reference and the compiler has already turned it into a // constant, which we can't take a reference to. auto local = Term::c_maxIdfX10Value; Term::IdfX10 idf = std::min(term.GetIdfSum(), local); return m_configurations[idf]; } //************************************************************************* // // TreatmentPrivateSharedRank0And3 // // Terms get one or more rank 0 and rank 3 rows that could be private or // shared, depending on term frequency. // //************************************************************************* TreatmentPrivateSharedRank0And3::TreatmentPrivateSharedRank0And3(double density, double snr) { // Fill up vector of RowConfigurations. GetTreatment() will use the // IdfSum() value of the Term as an index into this vector. for (Term::IdfX10 idf = 0; idf <= Term::c_maxIdfX10Value; ++idf) { RowConfiguration configuration; double frequency = Term::IdfX10ToFrequency(idf); if (frequency > density) { // This term is so common that it must be assigned a private row. configuration.push_front(RowConfiguration::Entry(0, 1, true)); } else { // Determine the number of rows, k, required to reach the // desired signal to noise ratio, snr, given a certain bit // density. // TODO: consider checking for overflow? int k = Term::ComputeRowCount(frequency, density, snr); configuration.push_front(RowConfiguration::Entry(0, 2, false)); if (k > 2) { Rank rank = 3; double frequencyAtRank = Term::FrequencyAtRank(frequency, rank); if (frequencyAtRank >= density) { configuration.push_front(RowConfiguration::Entry(rank, 1, true)); } else { configuration.push_front(RowConfiguration::Entry(rank, k - 2, false)); } } } m_configurations.push_back(configuration); //std::cout << idf / 10.0 << ": "; //m_configurations.back().Write(std::cout); //std::cout << std::endl; } } RowConfiguration TreatmentPrivateSharedRank0And3::GetTreatment(Term term) const { // DESIGN NOTE: we can't c_maxIdfX10Value directly to min because min // takes a reference and the compiler has already turned it into a // constant, which we can't take a reference to. auto local = Term::c_maxIdfX10Value; Term::IdfX10 idf = std::min(term.GetIdfSum(), local); return m_configurations[idf]; } //************************************************************************* // // TreatmentPrivateSharedRank0ToN // // Two rank 0 rows followed by rows of increasing rank until the bit density // is > .5 or we run out of rows. Due to limitatons in other BitFunnel code, // we also top out at rank 6. // //************************************************************************* TreatmentPrivateSharedRank0ToN::TreatmentPrivateSharedRank0ToN(double density, double snr) { // TODO: what should maxDensity be? Note that this is different from the // density liimt that's passed in. const double maxDensity = 0.15; // Fill up vector of RowConfigurations. GetTreatment() will use the // IdfSum() value of the Term as an index into this vector. // // TODO: we should make sure we get "enough" rows if we end up with a // high rank private row. for (Term::IdfX10 idf = 0; idf <= Term::c_maxIdfX10Value; ++idf) { RowConfiguration configuration; double frequency = Term::IdfX10ToFrequency(idf); if (frequency > density) { // This term is so common that it must be assigned a private row. configuration.push_front(RowConfiguration::Entry(0, 1, true)); } else { // TODO: fix other limitations so this can be higher than 6? const Rank maxRank = (std::min)(Term::ComputeMaxRank(frequency, maxDensity), static_cast<Rank>(6u)); int numRows = Term::ComputeRowCount(frequency, density, snr); configuration.push_front(RowConfiguration::Entry(0, 2, false)); numRows -= 2; Rank rank = 1; while (rank < maxRank) { double frequencyAtRank = Term::FrequencyAtRank(frequency, rank); if (frequencyAtRank >= density) { configuration.push_front(RowConfiguration::Entry(rank, 1, true)); } else { configuration.push_front(RowConfiguration::Entry(rank, 1, false)); } ++rank; --numRows; } double frequencyAtRank = Term::FrequencyAtRank(frequency, rank); if (frequencyAtRank >= density) { configuration.push_front(RowConfiguration::Entry(rank, 1, true)); } else { if (numRows > 1) { configuration.push_front(RowConfiguration::Entry(rank, numRows, false)); } else { configuration.push_front(RowConfiguration::Entry(rank, 1, false)); } } } m_configurations.push_back(configuration); //std::cout << idf / 10.0 << ": "; //m_configurations.back().Write(std::cout); //std::cout << std::endl; } } RowConfiguration TreatmentPrivateSharedRank0ToN::GetTreatment(Term term) const { // DESIGN NOTE: we can't c_maxIdfX10Value directly to min because min // takes a reference and the compiler has already turned it into a // constant, which we can't take a reference to. auto local = Term::c_maxIdfX10Value; Term::IdfX10 idf = std::min(term.GetIdfSum(), local); return m_configurations[idf]; } } <|endoftext|>
<commit_before>/* Allocore Example: User App Template Description: This is a very stripped down App subclass that can be used as a starting template for projects. This is NOT an example of how to use the App class. See 'simpleApp.cpp' in the same directory as this file for a pedagogical overview of the App class. Author: Lance Putnam, 9/2012, [email protected] */ #include "allocore/io/al_App.hpp" using namespace al; class MyApp : public App{ public: MyApp(){ //lens().near(0.1).far(25).fovy(45); //nav().pos(0,0,4); //nav().quat().fromAxisAngle(0, 0,0,1); //initWindow(Window::Dim(600,400), "", 40, Window::DEFAULT_BUF); //stereo().clearColor(HSV(0,0,1)); //window().remove(navControl()); //initAudio(44100, 128, 2,1); } // Audio callback virtual void onSound(AudioIOData& io){ while(io()){ //float in = io.in(0); float out1 = 0; float out2 = 0; io.out(0) = out1; io.out(1) = out2; } } // Graphics callbacks virtual void onAnimate(double dt){} virtual void onDraw(Graphics& g, const Viewpoint& v){} // Keyboard/mouse input callbacks virtual void onKeyDown(const ViewpointWindow& w, const Keyboard& k){ switch(k.key()){ case 'n': break; } } virtual void onKeyUp(const ViewpointWindow& w, const Keyboard& k){} virtual void onMouseDown(const ViewpointWindow& w, const Mouse& m){} virtual void onMouseUp(const ViewpointWindow& w, const Mouse& m){} virtual void onMouseDrag(const ViewpointWindow& w, const Mouse& m){} virtual void onMouseMove(const ViewpointWindow& w, const Mouse& m){} // Window-related callbacks virtual void onCreate(const ViewpointWindow& win){} virtual void onDestroy(const ViewpointWindow& win){} virtual void onResize(const ViewpointWindow& win, int dw, int dh){} }; int main(){ MyApp().start(); } <commit_msg>moved App template to work/<commit_after><|endoftext|>
<commit_before>#include <stdio.h> #include <string.h> #include "NOD/DiscWii.hpp" #include "NOD/aes.hpp" namespace NOD { /* Not much of a secret anymore I suppose */ static const uint8_t COMMON_KEYS[2][16] = { /* Normal */ {0xeb, 0xe4, 0x2a, 0x22, 0x5e, 0x85, 0x93, 0xe4, 0x48, 0xd9, 0xc5, 0x45, 0x73, 0x81, 0xaa, 0xf7}, /* Korean */ {0x63, 0xb8, 0x2b, 0xb4, 0xf4, 0x61, 0x4e, 0x2e, 0x13, 0xf2, 0xfe, 0xfb, 0xba, 0x4c, 0x9b, 0x7e} }; class PartitionWii : public DiscBase::IPartition { enum SigType : uint32_t { SRSA_4096 = 0x00010000, SRSA_2048 = 0x00010001, SELIPTICAL_CURVE = 0x00010002 }; enum KeyType : uint32_t { KRSA_4096 = 0x00000000, KRSA_2048 = 0x00000001 }; struct Ticket { uint32_t sigType; char sig[256]; char padding[60]; char sigIssuer[64]; char ecdh[60]; char padding1[3]; unsigned char encKey[16]; char padding2; char ticketId[8]; char consoleId[4]; char titleId[8]; char padding3[2]; uint16_t ticketVersion; uint32_t permittedTitlesMask; uint32_t permitMask; char titleExportAllowed; char commonKeyIdx; char padding4[48]; char contentAccessPermissions[64]; char padding5[2]; struct TimeLimit { uint32_t enableTimeLimit; uint32_t timeLimit; } timeLimits[8]; void read(IDiscIO::IReadStream& s) { s.read(this, 676); sigType = SBig(sigType); ticketVersion = SBig(ticketVersion); permittedTitlesMask = SBig(permittedTitlesMask); permitMask = SBig(permitMask); for (size_t t=0 ; t<8 ; ++t) { timeLimits[t].enableTimeLimit = SBig(timeLimits[t].enableTimeLimit); timeLimits[t].timeLimit = SBig(timeLimits[t].timeLimit); } } } m_ticket; struct TMD { SigType sigType; char sig[256]; char padding[60]; char sigIssuer[64]; char version; char caCrlVersion; char signerCrlVersion; char padding1; uint32_t iosIdMajor; uint32_t iosIdMinor; uint32_t titleIdMajor; char titleIdMinor[4]; uint32_t titleType; uint16_t groupId; char padding2[62]; uint32_t accessFlags; uint16_t titleVersion; uint16_t numContents; uint16_t bootIdx; uint16_t padding3; struct Content { uint32_t id; uint16_t index; uint16_t type; uint64_t size; char hash[20]; void read(IDiscIO::IReadStream& s) { s.read(this, 36); id = SBig(id); index = SBig(index); type = SBig(type); size = SBig(size); } }; std::vector<Content> contents; void read(IDiscIO::IReadStream& s) { s.read(this, 484); sigType = (SigType)SBig(sigType); iosIdMajor = SBig(iosIdMajor); iosIdMinor = SBig(iosIdMinor); titleIdMajor = SBig(titleIdMajor); titleType = SBig(titleType); groupId = SBig(groupId); accessFlags = SBig(accessFlags); titleVersion = SBig(titleVersion); numContents = SBig(numContents); bootIdx = SBig(bootIdx); contents.clear(); contents.reserve(numContents); for (uint16_t c=0 ; c<numContents ; ++c) { contents.emplace_back(); contents.back().read(s); } } } m_tmd; struct Certificate { SigType sigType; char sig[512]; char issuer[64]; KeyType keyType; char subject[64]; char key[512]; uint32_t modulus; uint32_t pubExp; void read(IDiscIO::IReadStream& s) { s.read(&sigType, 4); sigType = (SigType)SBig(sigType); if (sigType == SRSA_4096) s.read(sig, 512); else if (sigType == SRSA_2048) s.read(sig, 256); else if (sigType == SELIPTICAL_CURVE) s.read(sig, 64); s.seek(60, SEEK_CUR); s.read(issuer, 64); s.read(&keyType, 4); s.read(subject, 64); keyType = (KeyType)SBig(keyType); if (keyType == KRSA_4096) s.read(key, 512); else if (keyType == KRSA_2048) s.read(key, 256); s.read(&modulus, 8); modulus = SBig(modulus); pubExp = SBig(pubExp); s.seek(52, SEEK_CUR); } }; Certificate m_caCert; Certificate m_tmdCert; Certificate m_ticketCert; uint64_t m_dataOff; uint8_t m_decKey[16]; public: PartitionWii(const DiscWii& parent, Kind kind, uint64_t offset) : IPartition(parent, kind, offset) { std::unique_ptr<IDiscIO::IReadStream> s = parent.getDiscIO().beginReadStream(offset); m_ticket.read(*s); uint32_t tmdSize; s->read(&tmdSize, 4); tmdSize = SBig(tmdSize); uint32_t tmdOff; s->read(&tmdOff, 4); tmdOff = SBig(tmdOff) << 2; uint32_t certChainSize; s->read(&certChainSize, 4); certChainSize = SBig(certChainSize); uint32_t certChainOff; s->read(&certChainOff, 4); certChainOff = SBig(certChainOff) << 2; uint32_t globalHashTableOff; s->read(&globalHashTableOff, 4); globalHashTableOff = SBig(globalHashTableOff) << 2; uint32_t dataOff; s->read(&dataOff, 4); dataOff = SBig(dataOff) << 2; m_dataOff = offset + dataOff; uint32_t dataSize; s->read(&dataSize, 4); dataSize = SBig(dataSize) << 2; s->seek(offset + tmdOff); m_tmd.read(*s); s->seek(offset + certChainOff); m_caCert.read(*s); m_tmdCert.read(*s); m_ticketCert.read(*s); /* Decrypt title key */ std::unique_ptr<IAES> aes = NewAES(); uint8_t iv[16] = {}; memcpy(iv, m_ticket.titleId, 8); aes->setKey(COMMON_KEYS[(int)m_ticket.commonKeyIdx]); aes->decrypt(iv, m_ticket.encKey, m_decKey, 16); /* Wii-specific header reads (now using title key to decrypt) */ std::unique_ptr<IPartReadStream> ds = beginReadStream(0x420); uint32_t vals[3]; ds->read(vals, 12); m_dolOff = SBig(vals[0]) << 2; m_fstOff = SBig(vals[1]) << 2; m_fstSz = SBig(vals[2]) << 2; ds->seek(0x2440 + 0x14); ds->read(vals, 8); m_apploaderSz = 32 + SBig(vals[0]) + SBig(vals[1]); /* Yay files!! */ parseFST(*ds); /* Also make DOL header and size handy */ ds->seek(m_dolOff); parseDOL(*ds); } class PartReadStream : public IPartReadStream { std::unique_ptr<IAES> m_aes; const PartitionWii& m_parent; uint64_t m_baseOffset; uint64_t m_offset; std::unique_ptr<IDiscIO::IReadStream> m_dio; size_t m_curBlock = SIZE_MAX; uint8_t m_encBuf[0x8000]; uint8_t m_decBuf[0x7c00]; void decryptBlock() { m_dio->read(m_encBuf, 0x8000); m_aes->decrypt(&m_encBuf[0x3d0], &m_encBuf[0x400], m_decBuf, 0x7c00); } public: PartReadStream(const PartitionWii& parent, uint64_t baseOffset, uint64_t offset) : m_aes(NewAES()), m_parent(parent), m_baseOffset(baseOffset), m_offset(offset) { m_aes->setKey(parent.m_decKey); size_t block = m_offset / 0x7c00; m_dio = m_parent.m_parent.getDiscIO().beginReadStream(m_baseOffset + block * 0x8000); decryptBlock(); m_curBlock = block; } void seek(int64_t offset, int whence) { if (whence == SEEK_SET) m_offset = offset; else if (whence == SEEK_CUR) m_offset += offset; else return; size_t block = m_offset / 0x7c00; if (block != m_curBlock) { m_dio->seek(m_baseOffset + block * 0x8000); decryptBlock(); m_curBlock = block; } } uint64_t position() const {return m_offset;} uint64_t read(void* buf, uint64_t length) { size_t block = m_offset / 0x7c00; size_t cacheOffset = m_offset % 0x7c00; uint64_t cacheSize; uint64_t rem = length; uint8_t* dst = (uint8_t*)buf; while (rem) { if (block != m_curBlock) { decryptBlock(); m_curBlock = block; } cacheSize = rem; if (cacheSize + cacheOffset > 0x7c00) cacheSize = 0x7c00 - cacheOffset; memcpy(dst, m_decBuf + cacheOffset, cacheSize); dst += cacheSize; rem -= cacheSize; cacheOffset = 0; ++block; } m_offset += length; return dst - (uint8_t*)buf; } }; std::unique_ptr<IPartReadStream> beginReadStream(uint64_t offset) const { return std::unique_ptr<IPartReadStream>(new PartReadStream(*this, m_dataOff, offset)); } uint64_t normalizeOffset(uint64_t anOffset) const {return anOffset << 2;} }; DiscWii::DiscWii(std::unique_ptr<IDiscIO>&& dio) : DiscBase(std::move(dio)) { /* Read partition info */ struct PartInfo { uint32_t partCount; uint32_t partInfoOff; struct Part { uint32_t partDataOff; enum Type : uint32_t { PART_DATA = 0, PART_UPDATE = 1, PART_CHANNEL = 2 } partType; } parts[4]; PartInfo(IDiscIO& dio) { std::unique_ptr<IDiscIO::IReadStream> s = dio.beginReadStream(0x40000); s->read(this, 32); partCount = SBig(partCount); partInfoOff = SBig(partInfoOff); s->seek(partInfoOff << 2); for (uint32_t p=0 ; p<partCount && p<4 ; ++p) { s->read(&parts[p], 8); parts[p].partDataOff = SBig(parts[p].partDataOff); parts[p].partType = (Part::Type)SBig(parts[p].partType); } } } partInfo(*m_discIO); /* Iterate for data partition */ m_partitions.reserve(partInfo.partCount); for (uint32_t p=0 ; p<partInfo.partCount && p<4 ; ++p) { PartInfo::Part& part = partInfo.parts[p]; IPartition::Kind kind; if (part.partType == PartInfo::Part::PART_DATA) kind = IPartition::PART_DATA; else if (part.partType == PartInfo::Part::PART_UPDATE) kind = IPartition::PART_UPDATE; else if (part.partType == PartInfo::Part::PART_CHANNEL) kind = IPartition::PART_CHANNEL; else LogModule.report(LogVisor::FatalError, "invalid partition type %s", part.partType); m_partitions.emplace_back(new PartitionWii(*this, kind, part.partDataOff << 2)); } } bool DiscWii::commit() { return false; } } <commit_msg>Init-safety<commit_after>#include <stdio.h> #include <string.h> #include "NOD/DiscWii.hpp" #include "NOD/aes.hpp" namespace NOD { /* Not much of a secret anymore I suppose */ static const uint8_t COMMON_KEYS[2][16] = { /* Normal */ {0xeb, 0xe4, 0x2a, 0x22, 0x5e, 0x85, 0x93, 0xe4, 0x48, 0xd9, 0xc5, 0x45, 0x73, 0x81, 0xaa, 0xf7}, /* Korean */ {0x63, 0xb8, 0x2b, 0xb4, 0xf4, 0x61, 0x4e, 0x2e, 0x13, 0xf2, 0xfe, 0xfb, 0xba, 0x4c, 0x9b, 0x7e} }; class PartitionWii : public DiscBase::IPartition { enum SigType : uint32_t { SRSA_4096 = 0x00010000, SRSA_2048 = 0x00010001, SELIPTICAL_CURVE = 0x00010002 }; enum KeyType : uint32_t { KRSA_4096 = 0x00000000, KRSA_2048 = 0x00000001 }; struct Ticket { uint32_t sigType; char sig[256]; char padding[60]; char sigIssuer[64]; char ecdh[60]; char padding1[3]; unsigned char encKey[16]; char padding2; char ticketId[8]; char consoleId[4]; char titleId[8]; char padding3[2]; uint16_t ticketVersion; uint32_t permittedTitlesMask; uint32_t permitMask; char titleExportAllowed; char commonKeyIdx; char padding4[48]; char contentAccessPermissions[64]; char padding5[2]; struct TimeLimit { uint32_t enableTimeLimit; uint32_t timeLimit; } timeLimits[8]; void read(IDiscIO::IReadStream& s) { s.read(this, 676); sigType = SBig(sigType); ticketVersion = SBig(ticketVersion); permittedTitlesMask = SBig(permittedTitlesMask); permitMask = SBig(permitMask); for (size_t t=0 ; t<8 ; ++t) { timeLimits[t].enableTimeLimit = SBig(timeLimits[t].enableTimeLimit); timeLimits[t].timeLimit = SBig(timeLimits[t].timeLimit); } } } m_ticket; struct TMD { SigType sigType; char sig[256]; char padding[60]; char sigIssuer[64]; char version; char caCrlVersion; char signerCrlVersion; char padding1; uint32_t iosIdMajor; uint32_t iosIdMinor; uint32_t titleIdMajor; char titleIdMinor[4]; uint32_t titleType; uint16_t groupId; char padding2[62]; uint32_t accessFlags; uint16_t titleVersion; uint16_t numContents; uint16_t bootIdx; uint16_t padding3; struct Content { uint32_t id; uint16_t index; uint16_t type; uint64_t size; char hash[20]; void read(IDiscIO::IReadStream& s) { s.read(this, 36); id = SBig(id); index = SBig(index); type = SBig(type); size = SBig(size); } }; std::vector<Content> contents; void read(IDiscIO::IReadStream& s) { s.read(this, 484); sigType = (SigType)SBig(sigType); iosIdMajor = SBig(iosIdMajor); iosIdMinor = SBig(iosIdMinor); titleIdMajor = SBig(titleIdMajor); titleType = SBig(titleType); groupId = SBig(groupId); accessFlags = SBig(accessFlags); titleVersion = SBig(titleVersion); numContents = SBig(numContents); bootIdx = SBig(bootIdx); contents.clear(); contents.reserve(numContents); for (uint16_t c=0 ; c<numContents ; ++c) { contents.emplace_back(); contents.back().read(s); } } } m_tmd; struct Certificate { SigType sigType; char sig[512]; char issuer[64]; KeyType keyType; char subject[64]; char key[512]; uint32_t modulus; uint32_t pubExp; void read(IDiscIO::IReadStream& s) { s.read(&sigType, 4); sigType = (SigType)SBig(sigType); if (sigType == SRSA_4096) s.read(sig, 512); else if (sigType == SRSA_2048) s.read(sig, 256); else if (sigType == SELIPTICAL_CURVE) s.read(sig, 64); s.seek(60, SEEK_CUR); s.read(issuer, 64); s.read(&keyType, 4); s.read(subject, 64); keyType = (KeyType)SBig(keyType); if (keyType == KRSA_4096) s.read(key, 512); else if (keyType == KRSA_2048) s.read(key, 256); s.read(&modulus, 8); modulus = SBig(modulus); pubExp = SBig(pubExp); s.seek(52, SEEK_CUR); } }; Certificate m_caCert; Certificate m_tmdCert; Certificate m_ticketCert; uint64_t m_dataOff; uint8_t m_decKey[16]; public: PartitionWii(const DiscWii& parent, Kind kind, uint64_t offset) : IPartition(parent, kind, offset) { std::unique_ptr<IDiscIO::IReadStream> s = parent.getDiscIO().beginReadStream(offset); m_ticket.read(*s); uint32_t tmdSize; s->read(&tmdSize, 4); tmdSize = SBig(tmdSize); uint32_t tmdOff; s->read(&tmdOff, 4); tmdOff = SBig(tmdOff) << 2; uint32_t certChainSize; s->read(&certChainSize, 4); certChainSize = SBig(certChainSize); uint32_t certChainOff; s->read(&certChainOff, 4); certChainOff = SBig(certChainOff) << 2; uint32_t globalHashTableOff; s->read(&globalHashTableOff, 4); globalHashTableOff = SBig(globalHashTableOff) << 2; uint32_t dataOff; s->read(&dataOff, 4); dataOff = SBig(dataOff) << 2; m_dataOff = offset + dataOff; uint32_t dataSize; s->read(&dataSize, 4); dataSize = SBig(dataSize) << 2; s->seek(offset + tmdOff); m_tmd.read(*s); s->seek(offset + certChainOff); m_caCert.read(*s); m_tmdCert.read(*s); m_ticketCert.read(*s); /* Decrypt title key */ std::unique_ptr<IAES> aes = NewAES(); uint8_t iv[16] = {}; memcpy(iv, m_ticket.titleId, 8); aes->setKey(COMMON_KEYS[(int)m_ticket.commonKeyIdx]); aes->decrypt(iv, m_ticket.encKey, m_decKey, 16); /* Wii-specific header reads (now using title key to decrypt) */ std::unique_ptr<IPartReadStream> ds = beginReadStream(0x420); uint32_t vals[3]; ds->read(vals, 12); m_dolOff = SBig(vals[0]) << 2; m_fstOff = SBig(vals[1]) << 2; m_fstSz = SBig(vals[2]) << 2; ds->seek(0x2440 + 0x14); ds->read(vals, 8); m_apploaderSz = 32 + SBig(vals[0]) + SBig(vals[1]); /* Yay files!! */ parseFST(*ds); /* Also make DOL header and size handy */ ds->seek(m_dolOff); parseDOL(*ds); } class PartReadStream : public IPartReadStream { std::unique_ptr<IAES> m_aes; const PartitionWii& m_parent; uint64_t m_baseOffset; uint64_t m_offset; std::unique_ptr<IDiscIO::IReadStream> m_dio; size_t m_curBlock = SIZE_MAX; uint8_t m_encBuf[0x8000]; uint8_t m_decBuf[0x7c00]; void decryptBlock() { m_dio->read(m_encBuf, 0x8000); m_aes->decrypt(&m_encBuf[0x3d0], &m_encBuf[0x400], m_decBuf, 0x7c00); } public: PartReadStream(const PartitionWii& parent, uint64_t baseOffset, uint64_t offset) : m_aes(NewAES()), m_parent(parent), m_baseOffset(baseOffset), m_offset(offset) { m_aes->setKey(parent.m_decKey); size_t block = m_offset / 0x7c00; m_dio = m_parent.m_parent.getDiscIO().beginReadStream(m_baseOffset + block * 0x8000); decryptBlock(); m_curBlock = block; } void seek(int64_t offset, int whence) { if (whence == SEEK_SET) m_offset = offset; else if (whence == SEEK_CUR) m_offset += offset; else return; size_t block = m_offset / 0x7c00; if (block != m_curBlock) { m_dio->seek(m_baseOffset + block * 0x8000); decryptBlock(); m_curBlock = block; } } uint64_t position() const {return m_offset;} uint64_t read(void* buf, uint64_t length) { size_t block = m_offset / 0x7c00; size_t cacheOffset = m_offset % 0x7c00; uint64_t cacheSize; uint64_t rem = length; uint8_t* dst = (uint8_t*)buf; while (rem) { if (block != m_curBlock) { decryptBlock(); m_curBlock = block; } cacheSize = rem; if (cacheSize + cacheOffset > 0x7c00) cacheSize = 0x7c00 - cacheOffset; memcpy(dst, m_decBuf + cacheOffset, cacheSize); dst += cacheSize; rem -= cacheSize; cacheOffset = 0; ++block; } m_offset += length; return dst - (uint8_t*)buf; } }; std::unique_ptr<IPartReadStream> beginReadStream(uint64_t offset) const { return std::unique_ptr<IPartReadStream>(new PartReadStream(*this, m_dataOff, offset)); } uint64_t normalizeOffset(uint64_t anOffset) const {return anOffset << 2;} }; DiscWii::DiscWii(std::unique_ptr<IDiscIO>&& dio) : DiscBase(std::move(dio)) { /* Read partition info */ struct PartInfo { uint32_t partCount; uint32_t partInfoOff; struct Part { uint32_t partDataOff; enum Type : uint32_t { PART_DATA = 0, PART_UPDATE = 1, PART_CHANNEL = 2 } partType; } parts[4]; PartInfo(IDiscIO& dio) { std::unique_ptr<IDiscIO::IReadStream> s = dio.beginReadStream(0x40000); s->read(this, 32); partCount = SBig(partCount); partInfoOff = SBig(partInfoOff); s->seek(partInfoOff << 2); for (uint32_t p=0 ; p<partCount && p<4 ; ++p) { s->read(&parts[p], 8); parts[p].partDataOff = SBig(parts[p].partDataOff); parts[p].partType = (Part::Type)SBig(parts[p].partType); } } } partInfo(*m_discIO); /* Iterate for data partition */ m_partitions.reserve(partInfo.partCount); for (uint32_t p=0 ; p<partInfo.partCount && p<4 ; ++p) { PartInfo::Part& part = partInfo.parts[p]; IPartition::Kind kind = IPartition::PART_DATA; if (part.partType == PartInfo::Part::PART_DATA) kind = IPartition::PART_DATA; else if (part.partType == PartInfo::Part::PART_UPDATE) kind = IPartition::PART_UPDATE; else if (part.partType == PartInfo::Part::PART_CHANNEL) kind = IPartition::PART_CHANNEL; else LogModule.report(LogVisor::FatalError, "invalid partition type %s", part.partType); m_partitions.emplace_back(new PartitionWii(*this, kind, part.partDataOff << 2)); } } bool DiscWii::commit() { return false; } } <|endoftext|>
<commit_before>#include <stdlib.h> #include <assert.h> #include <float.h> #include "estimator.h" #include "last_observation_estimator.h" #include "running_mean_estimator.h" #include "strategy_evaluator.h" #include "debug.h" namespace inst = instruments; #include <stdexcept> #include <string> #include <sstream> using std::runtime_error; using std::string; using std::ostringstream; Estimator * Estimator::create(string name) { return create(DEFAULT_TYPE, name); } Estimator * Estimator::create(EstimatorType type, string name) { Estimator *estimator = NULL; switch (type) { case LAST_OBSERVATION: estimator = new LastObservationEstimator(name); break; case RUNNING_MEAN: estimator = new RunningMeanEstimator(name); break; default: // TODO: implement more types abort(); } return estimator; } Estimator::Estimator(const string& name_) : name(name_), has_estimate(false), has_range_hints(false) { if (name.empty()) { throw runtime_error("Estimator name must not be empty"); } for (size_t i = 0; i < name.length(); ++i) { if (isspace(name[i])) { name[i] = '_'; } } } Estimator::~Estimator() { for (StrategyEvaluator *subscriber : subscribers) { subscriber->removeEstimator(this); } } bool estimate_is_valid(double estimate) { return estimate != DBL_MAX; } double invalid_estimate() { double e = DBL_MAX; ASSERT(!estimate_is_valid(e)); return e; } void Estimator::addObservation(double observation) { double old_estimate = invalid_estimate(), new_estimate = invalid_estimate(); if (has_estimate) { old_estimate = getEstimate(); } storeNewObservation(observation); has_estimate = true; new_estimate = getEstimate(); for (StrategyEvaluator *subscriber : subscribers) { subscriber->observationAdded(this, observation, old_estimate, new_estimate); } } bool Estimator::hasEstimate() { return has_estimate; } void Estimator::subscribe(StrategyEvaluator *subscriber) { subscribers.insert(subscriber); } void Estimator::unsubscribe(StrategyEvaluator *unsubscriber) { subscribers.erase(unsubscriber); } string Estimator::getName() { return name; } bool Estimator::hasRangeHints() { return has_range_hints; } EstimatorRangeHints Estimator::getRangeHints() { ASSERT(hasRangeHints()); return range_hints; } void Estimator::setRangeHints(double min, double max, size_t num_bins) { range_hints.min = min; range_hints.max = max; range_hints.num_bins = num_bins; has_range_hints = true; } void Estimator::setCondition(enum ConditionType type, double value) { conditions[type] = value; ConditionType other_type = (type == AT_MOST ? AT_LEAST : AT_MOST); if (conditions.count(other_type) > 0) { if (conditions[AT_LEAST] > conditions[AT_MOST]) { inst::dbgprintf(inst::ERROR, "Warning: tried to set impossible conditions [>= %f, <= %f] on estimator %s (both are now %f)\n", conditions[AT_LEAST], conditions[AT_MOST], name.c_str(), conditions[other_type]); conditions[type] = conditions[other_type]; } } for (StrategyEvaluator *subscriber : subscribers) { subscriber->estimatorConditionsChanged(this); } } void Estimator::clearConditions() { conditions.clear(); for (StrategyEvaluator *subscriber : subscribers) { subscriber->estimatorConditionsChanged(this); } } bool Estimator::valueMeetsConditions(double value) { return ((conditions.count(AT_LEAST) == 0 || value >= conditions[AT_LEAST]) && (conditions.count(AT_MOST) == 0 || value <= conditions[AT_MOST])); } double Estimator::getConditionalWeight(double value) { /* * The weighting is bogus. What's really going on here is just * a conditional probability expectation, which means that * the weights on out-of-bounds values should just be zero. if (conditions.count(AT_LEAST) > 0 && value < conditions[AT_LEAST]) { // further below bound = lower weight return value / conditions[AT_LEAST]; } else if (conditions.count(AT_MOST) > 0 && value > conditions[AT_MOST]) { // further above bound = lower weight return conditions[AT_MOST] / value; */ if ((conditions.count(AT_LEAST) > 0 && value < conditions[AT_LEAST]) || (conditions.count(AT_MOST) > 0 && value > conditions[AT_MOST])) { return 0.0; } else { // within bounds = even weight return 1.0; } } <commit_msg>Make sure not to end up with an empty error distribution; use fuzzy inequality with doubles.<commit_after>#include <stdlib.h> #include <assert.h> #include <float.h> #include <math.h> #include "estimator.h" #include "last_observation_estimator.h" #include "running_mean_estimator.h" #include "strategy_evaluator.h" #include "debug.h" namespace inst = instruments; #include <stdexcept> #include <string> #include <sstream> using std::runtime_error; using std::string; using std::ostringstream; Estimator * Estimator::create(string name) { return create(DEFAULT_TYPE, name); } Estimator * Estimator::create(EstimatorType type, string name) { Estimator *estimator = NULL; switch (type) { case LAST_OBSERVATION: estimator = new LastObservationEstimator(name); break; case RUNNING_MEAN: estimator = new RunningMeanEstimator(name); break; default: // TODO: implement more types abort(); } return estimator; } Estimator::Estimator(const string& name_) : name(name_), has_estimate(false), has_range_hints(false) { if (name.empty()) { throw runtime_error("Estimator name must not be empty"); } for (size_t i = 0; i < name.length(); ++i) { if (isspace(name[i])) { name[i] = '_'; } } } Estimator::~Estimator() { for (StrategyEvaluator *subscriber : subscribers) { subscriber->removeEstimator(this); } } bool estimate_is_valid(double estimate) { return estimate != DBL_MAX; } double invalid_estimate() { double e = DBL_MAX; ASSERT(!estimate_is_valid(e)); return e; } void Estimator::addObservation(double observation) { double old_estimate = invalid_estimate(), new_estimate = invalid_estimate(); if (has_estimate) { old_estimate = getEstimate(); } storeNewObservation(observation); has_estimate = true; new_estimate = getEstimate(); for (StrategyEvaluator *subscriber : subscribers) { subscriber->observationAdded(this, observation, old_estimate, new_estimate); } } bool Estimator::hasEstimate() { return has_estimate; } void Estimator::subscribe(StrategyEvaluator *subscriber) { subscribers.insert(subscriber); } void Estimator::unsubscribe(StrategyEvaluator *unsubscriber) { subscribers.erase(unsubscriber); } string Estimator::getName() { return name; } bool Estimator::hasRangeHints() { return has_range_hints; } EstimatorRangeHints Estimator::getRangeHints() { ASSERT(hasRangeHints()); return range_hints; } void Estimator::setRangeHints(double min, double max, size_t num_bins) { range_hints.min = min; range_hints.max = max; range_hints.num_bins = num_bins; has_range_hints = true; } void Estimator::setCondition(enum ConditionType type, double value) { conditions[type] = value; ConditionType other_type = (type == AT_MOST ? AT_LEAST : AT_MOST); if (conditions.count(other_type) > 0) { if (conditions[AT_LEAST] > conditions[AT_MOST]) { inst::dbgprintf(inst::ERROR, "Warning: tried to set impossible conditions [>= %f, <= %f] on estimator %s (both are now %f)\n", conditions[AT_LEAST], conditions[AT_MOST], name.c_str(), conditions[other_type]); conditions[type] = conditions[other_type]; } } for (StrategyEvaluator *subscriber : subscribers) { subscriber->estimatorConditionsChanged(this); } } void Estimator::clearConditions() { conditions.clear(); for (StrategyEvaluator *subscriber : subscribers) { subscriber->estimatorConditionsChanged(this); } } bool Estimator::valueMeetsConditions(double value) { return ((conditions.count(AT_LEAST) == 0 || value >= conditions[AT_LEAST]) && (conditions.count(AT_MOST) == 0 || value <= conditions[AT_MOST])); } #define THRESHOLD 0.0001 #define float_diff(a, cmp, b) \ ( (fabs((a) - (b)) > THRESHOLD) && ((a) cmp (b)) ) inline double float_greater(double a, double b) { return float_diff(a, >, b); } inline double float_less(double a, double b) { return float_diff(a, <, b); } double Estimator::getConditionalWeight(double value) { /* * The weighting is bogus. What's really going on here is just * a conditional probability expectation, which means that * the weights on out-of-bounds values should just be zero. if (conditions.count(AT_LEAST) > 0 && value < conditions[AT_LEAST]) { // further below bound = lower weight return value / conditions[AT_LEAST]; } else if (conditions.count(AT_MOST) > 0 && value > conditions[AT_MOST]) { // further above bound = lower weight return conditions[AT_MOST] / value; */ if ((conditions.count(AT_LEAST) > 0 && float_less(value, conditions[AT_LEAST])) || (conditions.count(AT_MOST) > 0 && float_greater(value, conditions[AT_MOST]))) { return 0.0; } else { // within bounds = even weight return 1.0; } } <|endoftext|>
<commit_before>#include "eyeballs.hpp" bool eyeballs_debug; eyeballs::eyeballs() { fd4 = -1; fd6 = -1; in4 = false; in6 = false; memset(&la4, 0, sizeof(la4)); memset(&la6, 0, sizeof(la6)); memset(&timeout, 0, sizeof(timeout)); linger.l_onoff = 1; linger.l_linger = 0; } eyeballs::~eyeballs() { } // if cloud not open fd4, return -1. int eyeballs::get_fd4() { return fd4; } // if cloud not open fd6, return -1. int eyeballs::get_fd6() { return fd6; } int eyeballs::stream_create(const char* host, const char* port) { return stream_create(std::string(host), std::string(port)); } int eyeballs::stream_create(const std::string& host, const std::string& port) { int on = 1; int off = 0; int error; struct addrinfo *res; struct addrinfo *res0; struct addrinfo hints; memset(&hints, 0, sizeof(hints)); hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_STREAM; hints.ai_flags = AI_ALL|AI_ADDRCONFIG; error = getaddrinfo(host.c_str(), port.c_str(), &hints, &res0); if (error) { if (eyeballs_debug) { fprintf(stderr, "%s(%d):getaddrinfo: %s\n", __FILE__, __LINE__, gai_strerror(error)); } return -1; } for (res = res0; res; res = res->ai_next) { if (in4 && in6) break; _cpy_addrinfo(res); } free(res0); signal(SIGPIPE, SIG_IGN); if (in4) { fd4 = socket(la4.family, la4.socktype, la4.protocol); if (fd4 == -1) { EYEBALLS_PERROR("socket"); return -1; } if (setsockopt(fd4, SOL_SOCKET, SO_REUSEADDR, (char*)&on, sizeof(on)) < 0) { EYEBALLS_PERROR("setsockopt"); close(fd4); return -1; } error = ioctl(fd4, FIONBIO, &on); if (error == -1) { EYEBALLS_PERROR("ioctl"); close(fd4); return -1; } } if (in6) { fd6 = socket(la6.family, la6.socktype, la6.protocol); if (fd6 == -1) { EYEBALLS_PERROR("socket"); return -1; } if (setsockopt(fd6, SOL_SOCKET, SO_REUSEADDR, (char*)&on, sizeof(on)) < 0) { EYEBALLS_PERROR("setsockopt"); close(fd6); return -1; } error = ioctl(fd6, FIONBIO, &on); if (error == -1) { EYEBALLS_PERROR("ioctl"); close(fd6); return -1; } } int max; fd_set r_fds; fd_set w_fds; fd_set e_fds; FD_ZERO(&r_fds); FD_ZERO(&w_fds); FD_ZERO(&e_fds); if (fd4 > fd6) { max = fd4; } else { max = fd6; } if (in6) { FD_SET(fd6, &r_fds); FD_SET(fd6, &w_fds); FD_SET(fd6, &e_fds); error = connect(fd6, (struct sockaddr*)&(la6.addr), la6.addrlen); perror("in6 connect"); printf("in6 connect errrno: %d\n", error); } if (in4) { FD_SET(fd4, &r_fds); FD_SET(fd4, &w_fds); FD_SET(fd4, &e_fds); error = connect(fd4, (struct sockaddr*)&(la4.addr), la4.addrlen); perror("in4 connect"); printf("in4 connect errrno: %d\n", error); } if (timeout.tv_sec == 0 && timeout.tv_usec == 0) { error = select(max+1, &r_fds, &w_fds, &e_fds, NULL); } else { error = select(max+1, &r_fds, &w_fds, &e_fds, &timeout); } if (error == -1) { // error EYEBALLS_PERROR("select"); close(fd4); close(fd6); return -1; } else if (error == 0) { // timeout is return 0 close(fd4); close(fd6); return 0; } else { if (FD_ISSET(fd6, &e_fds)) { close(fd6); } else if(FD_ISSET(fd4, &e_fds)) { close(fd4); } if (in6) { if (FD_ISSET(fd6, &r_fds) || FD_ISSET(fd6, &w_fds)) { if (in4) { if (setsockopt(fd4, SOL_SOCKET, SO_LINGER, (struct linger*)&linger, sizeof(linger)) < 0) { EYEBALLS_PERROR("setsockopt"); close(fd4); close(fd6); return -1; } } error = ioctl(fd6, FIONBIO, &off); if (error == -1) { EYEBALLS_PERROR("ioctl"); close(fd4); close(fd6); return -1; } close(fd4); return fd6; } } if (in4) { if (FD_ISSET(fd4, &r_fds) || FD_ISSET(fd4, &w_fds)) { if (in6) { if (setsockopt(fd6, SOL_SOCKET, SO_LINGER, (struct linger*)&linger, sizeof(linger)) < 0) { EYEBALLS_PERROR("setsockopt"); close(fd4); close(fd6); return -1; } } error = ioctl(fd4, FIONBIO, &off); if (error == -1) { EYEBALLS_PERROR("ioctl"); close(fd4); close(fd6); return -1; } close(fd6); return fd4; } } } return -1; } bool eyeballs::_cpy_addrinfo(struct addrinfo* ai) { if (ai->ai_family == AF_INET) { if (in4) { return false; } if (la4.family) { return false; } la4.flags = ai->ai_flags; la4.family = ai->ai_family; la4.socktype = ai->ai_socktype; la4.protocol = ai->ai_protocol; la4.addrlen = ai->ai_addrlen; memcpy(&(la4.addr), ai->ai_addr, ai->ai_addrlen); if (ai->ai_canonname) { memcpy(&(la4.canonname), ai->ai_canonname, strlen(ai->ai_canonname)); } in4 = true; return true; } else if (ai->ai_family == AF_INET6) { if (in6) { return false; } if (la6.family) { return false; } la6.flags = ai->ai_flags; la6.family = ai->ai_family; la6.socktype = ai->ai_socktype; la6.protocol = ai->ai_protocol; la6.addrlen = ai->ai_addrlen; memcpy(&(la6.addr), ai->ai_addr, ai->ai_addrlen); if (ai->ai_canonname) { memcpy(&(la6.canonname), ai->ai_canonname, strlen(ai->ai_canonname)); } in6 = true; return true; } else { return false; } return false; } void eyeballs::set_timeout(int sec, int usec) { timeout.tv_sec = sec; timeout.tv_usec = usec; return; } <commit_msg>update<commit_after>#include "eyeballs.hpp" bool eyeballs_debug; eyeballs::eyeballs() { fd4 = -1; fd6 = -1; in4 = false; in6 = false; memset(&la4, 0, sizeof(la4)); memset(&la6, 0, sizeof(la6)); memset(&timeout, 0, sizeof(timeout)); linger.l_onoff = 1; linger.l_linger = 0; } eyeballs::~eyeballs() { } // if cloud not open fd4, return -1. int eyeballs::get_fd4() { return fd4; } // if cloud not open fd6, return -1. int eyeballs::get_fd6() { return fd6; } int eyeballs::stream_create(const char* host, const char* port) { return stream_create(std::string(host), std::string(port)); } int eyeballs::stream_create(const std::string& host, const std::string& port) { int on = 1; int off = 0; int error; struct addrinfo *res; struct addrinfo *res0; struct addrinfo hints; memset(&hints, 0, sizeof(hints)); hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_STREAM; hints.ai_flags = AI_ALL|AI_ADDRCONFIG; error = getaddrinfo(host.c_str(), port.c_str(), &hints, &res0); if (error) { if (eyeballs_debug) { fprintf(stderr, "%s(%d):getaddrinfo: %s\n", __FILE__, __LINE__, gai_strerror(error)); } return -1; } for (res = res0; res; res = res->ai_next) { if (in4 && in6) break; _cpy_addrinfo(res); } free(res0); signal(SIGPIPE, SIG_IGN); if (in4) { fd4 = socket(la4.family, la4.socktype, la4.protocol); if (fd4 == -1) { EYEBALLS_PERROR("socket"); return -1; } if (setsockopt(fd4, SOL_SOCKET, SO_REUSEADDR, (char*)&on, sizeof(on)) < 0) { EYEBALLS_PERROR("setsockopt"); close(fd4); return -1; } error = ioctl(fd4, FIONBIO, &on); if (error == -1) { EYEBALLS_PERROR("ioctl"); close(fd4); return -1; } } if (in6) { fd6 = socket(la6.family, la6.socktype, la6.protocol); if (fd6 == -1) { EYEBALLS_PERROR("socket"); return -1; } if (setsockopt(fd6, SOL_SOCKET, SO_REUSEADDR, (char*)&on, sizeof(on)) < 0) { EYEBALLS_PERROR("setsockopt"); close(fd6); return -1; } error = ioctl(fd6, FIONBIO, &on); if (error == -1) { EYEBALLS_PERROR("ioctl"); close(fd6); return -1; } } int max; fd_set r_fds; fd_set w_fds; fd_set e_fds; FD_ZERO(&r_fds); FD_ZERO(&w_fds); FD_ZERO(&e_fds); if (fd4 > fd6) { max = fd4; } else { max = fd6; } if (in6) { FD_SET(fd6, &r_fds); FD_SET(fd6, &w_fds); FD_SET(fd6, &e_fds); connect(fd6, (struct sockaddr*)&(la6.addr), la6.addrlen); } if (in4) { FD_SET(fd4, &r_fds); FD_SET(fd4, &w_fds); FD_SET(fd4, &e_fds); connect(fd4, (struct sockaddr*)&(la4.addr), la4.addrlen); } if (timeout.tv_sec == 0 && timeout.tv_usec == 0) { error = select(max+1, &r_fds, &w_fds, &e_fds, NULL); } else { error = select(max+1, &r_fds, &w_fds, &e_fds, &timeout); } if (error == -1) { // error EYEBALLS_PERROR("select"); close(fd4); close(fd6); return -1; } else if (error == 0) { // timeout is return 0 close(fd4); close(fd6); return 0; } else { /* socklen_t len = sizeof(error); if (getsockopt(fd4, SOL_SOCKET, SO_ERROR, &error, &len) < 0) { printf("getsockopt error"); } if (getsockopt(fd6 SOL_SOCKET, SO_ERROR, &error, &len) < 0) { printf("getsockopt error"); } */ if (FD_ISSET(fd6, &e_fds)) { close(fd6); fd6 = -1; } else if(FD_ISSET(fd4, &e_fds)) { close(fd4); fd4 = -1; } if (in6 && fd6 != -1) { if (FD_ISSET(fd6, &r_fds) || FD_ISSET(fd6, &w_fds)) { if (in4) { if (setsockopt(fd4, SOL_SOCKET, SO_LINGER, (struct linger*)&linger, sizeof(linger)) < 0) { EYEBALLS_PERROR("setsockopt"); close(fd4); close(fd6); return -1; } } error = ioctl(fd6, FIONBIO, &off); if (error == -1) { EYEBALLS_PERROR("ioctl"); close(fd4); close(fd6); return -1; } close(fd4); return fd6; } } if (in4 && fd4 != -1) { if (FD_ISSET(fd4, &r_fds) || FD_ISSET(fd4, &w_fds)) { if (in6) { if (setsockopt(fd6, SOL_SOCKET, SO_LINGER, (struct linger*)&linger, sizeof(linger)) < 0) { EYEBALLS_PERROR("setsockopt"); close(fd4); close(fd6); return -1; } } error = ioctl(fd4, FIONBIO, &off); if (error == -1) { EYEBALLS_PERROR("ioctl"); close(fd4); close(fd6); return -1; } close(fd6); return fd4; } } } return -1; } bool eyeballs::_cpy_addrinfo(struct addrinfo* ai) { if (ai->ai_family == AF_INET) { if (in4) { return false; } if (la4.family) { return false; } la4.flags = ai->ai_flags; la4.family = ai->ai_family; la4.socktype = ai->ai_socktype; la4.protocol = ai->ai_protocol; la4.addrlen = ai->ai_addrlen; memcpy(&(la4.addr), ai->ai_addr, ai->ai_addrlen); if (ai->ai_canonname) { memcpy(&(la4.canonname), ai->ai_canonname, strlen(ai->ai_canonname)); } in4 = true; return true; } else if (ai->ai_family == AF_INET6) { if (in6) { return false; } if (la6.family) { return false; } la6.flags = ai->ai_flags; la6.family = ai->ai_family; la6.socktype = ai->ai_socktype; la6.protocol = ai->ai_protocol; la6.addrlen = ai->ai_addrlen; memcpy(&(la6.addr), ai->ai_addr, ai->ai_addrlen); if (ai->ai_canonname) { memcpy(&(la6.canonname), ai->ai_canonname, strlen(ai->ai_canonname)); } in6 = true; return true; } else { return false; } return false; } void eyeballs::set_timeout(int sec, int usec) { timeout.tv_sec = sec; timeout.tv_usec = usec; return; } <|endoftext|>
<commit_before>#include "PackAnimation.h" #include "PackNodeFactory.h" #include "PackAnchor.h" #include "PackClipbox.h" #include "Utility.h" #include "typedef.h" #include "AnimToLuaString.h" #include "AnimFromLua.h" #include "AnimToBin.h" #include "AnimFromBin.h" namespace librespacker { PackAnimation::PackAnimation(int id) : IPackNode(id) { } void PackAnimation::PackToLuaString(ebuilder::CodeGenerator& gen, const d2d::TexturePacker& tp, float scale) const { AnimToLuaString::Pack(this, gen); } void PackAnimation::UnpackFromLua(lua_State* L, const std::vector<d2d::Image*>& images) { AnimFromLua::Unpack(L, this); } int PackAnimation::SizeOfPackToBin() const { return AnimToBin::Size(this); } void PackAnimation::PackToBin(uint8_t** ptr, const d2d::TexturePacker& tp, float scale) const { AnimToBin::Pack(this, ptr); } int PackAnimation::SizeOfUnpackFromBin() const { return AnimFromBin::Size(this); } void PackAnimation::UnpackFromBin(uint8_t** ptr, const std::vector<d2d::Image*>& images) { AnimFromBin::Unpack(ptr, this); } void PackAnimation::CreateFramePart(const d2d::ISprite* spr, Frame& frame) { const IPackNode* node = PackNodeFactory::Instance()->Create(spr); PackAnimation::Part part; std::string name = ""; if (Utility::IsNameValid(spr->name)) { name = spr->name; } bool force_mat = AddComponent(node, name, part.comp_idx); PackAnimation::LoadSprTrans(spr, part.t, force_mat); frame.parts.push_back(part); } void PackAnimation::CreateClipboxFramePart(const PackClipbox* cb, Frame& frame) { PackAnimation::Part part; AddComponent(cb, "", part.comp_idx); part.t.mat[0] = part.t.mat[3] = 1024; part.t.mat[1] = part.t.mat[2] = 0; part.t.mat[4] = cb->x * SCALE; part.t.mat[5] = - cb->y * SCALE; frame.parts.push_back(part); } void PackAnimation::Clear() { export_name.clear(); components.clear(); actions.clear(); frames.clear(); } bool PackAnimation::AddComponent(const IPackNode* node, const std::string& name, int& comp_idx) { if (const PackAnchor* anchor = dynamic_cast<const PackAnchor*>(node)) { for (int i = 0, n = components.size(); i < n; ++i) { if (dynamic_cast<const PackAnchor*>(components[i].node) && components[i].name == name) { comp_idx = i; return true; } } } else { for (int i = 0, n = components.size(); i < n; ++i) { if (components[i].node == node && components[i].name == name) { comp_idx = i; return true; } } for (int i = 0, n = components.size(); i < n; ++i) { if (components[i].node->GetFilepath() == node->GetFilepath() && components[i].name == name && !name.empty()) { d2d::FileNameParser::Type type = d2d::FileNameParser::getFileType(node->GetFilepath()); if (type == d2d::FileNameParser::e_image || type == d2d::FileNameParser::e_complex || type == d2d::FileNameParser::e_anim) { comp_idx = i; return true; } } } } Component comp; comp.node = node; comp.name = name; components.push_back(comp); comp_idx = components.size() - 1; return !name.empty(); } void PackAnimation::LoadSprTrans(const d2d::ISprite* spr, SpriteTrans& trans, bool force_mat) { LoadSprMat(spr, trans, force_mat); LoadSprColor(spr, trans); } void PackAnimation::LoadSprMat(const d2d::ISprite* spr, SpriteTrans& trans, bool force) { if (!force && dynamic_cast<const d2d::ImageSprite*>(spr)) { return; } float mat[6]; // | 1 ky | | sx | | c s | | 1 | // | kx 1 | | sy | | -s c | | 1 | // | 1 | | 1 | | 1 | | x y 1 | // skew scale rotate move mat[1] = mat[2] = mat[4] = mat[5] = 0; mat[0] = mat[3] = 1; d2d::Vector center = spr->GetCenter(); bool xmir, ymir; spr->GetMirror(xmir, ymir); float sx = spr->GetScale().x, sy = spr->GetScale().y; if (xmir) { sx = -sx; } if (ymir) { sy = -sy; } float c = cos(-spr->GetAngle()), s = sin(-spr->GetAngle()); float kx = -spr->GetShear().x, ky = -spr->GetShear().y; mat[0] = sx*c - ky*sy*s; mat[1] = sx*s + ky*sy*c; mat[2] = kx*sx*c - sy*s; mat[3] = kx*sx*s + sy*c; mat[4] = center.x/* * m_scale*/; mat[5] = center.y/* * m_scale*/; for (size_t i = 0; i < 4; ++i) trans.mat[i] = floor(mat[i] * 1024 + 0.5f); for (size_t i = 4; i < 6; ++i) trans.mat[i] = floor(mat[i] * 16 + 0.5f); // flip y trans.mat[5] = -trans.mat[5]; } void PackAnimation::LoadSprColor(const d2d::ISprite* spr, SpriteTrans& trans) { trans.color = d2d::trans_color2int(spr->multiCol, d2d::PT_ARGB); trans.additive = d2d::trans_color2int(spr->addCol, d2d::PT_ARGB); trans.rmap = d2d::trans_color2int(spr->r_trans, d2d::PT_RGBA); trans.gmap = d2d::trans_color2int(spr->g_trans, d2d::PT_RGBA); trans.bmap = d2d::trans_color2int(spr->b_trans, d2d::PT_RGBA); } bool PackAnimation::IsMatrixIdentity(const int* mat) { return mat[0] == 1024 && mat[3] == 1024 && mat[1] == 0 && mat[2] == 0 && mat[4] == 0 && mat[5] == 0; } }<commit_msg>[FIXED] 打包image 判断是否有mat<commit_after>#include "PackAnimation.h" #include "PackNodeFactory.h" #include "PackAnchor.h" #include "PackClipbox.h" #include "Utility.h" #include "typedef.h" #include "AnimToLuaString.h" #include "AnimFromLua.h" #include "AnimToBin.h" #include "AnimFromBin.h" namespace librespacker { PackAnimation::PackAnimation(int id) : IPackNode(id) { } void PackAnimation::PackToLuaString(ebuilder::CodeGenerator& gen, const d2d::TexturePacker& tp, float scale) const { AnimToLuaString::Pack(this, gen); } void PackAnimation::UnpackFromLua(lua_State* L, const std::vector<d2d::Image*>& images) { AnimFromLua::Unpack(L, this); } int PackAnimation::SizeOfPackToBin() const { return AnimToBin::Size(this); } void PackAnimation::PackToBin(uint8_t** ptr, const d2d::TexturePacker& tp, float scale) const { AnimToBin::Pack(this, ptr); } int PackAnimation::SizeOfUnpackFromBin() const { return AnimFromBin::Size(this); } void PackAnimation::UnpackFromBin(uint8_t** ptr, const std::vector<d2d::Image*>& images) { AnimFromBin::Unpack(ptr, this); } void PackAnimation::CreateFramePart(const d2d::ISprite* spr, Frame& frame) { const IPackNode* node = PackNodeFactory::Instance()->Create(spr); PackAnimation::Part part; std::string name = ""; if (Utility::IsNameValid(spr->name)) { name = spr->name; } bool force_mat = AddComponent(node, name, part.comp_idx); PackAnimation::LoadSprTrans(spr, part.t, force_mat); frame.parts.push_back(part); } void PackAnimation::CreateClipboxFramePart(const PackClipbox* cb, Frame& frame) { PackAnimation::Part part; AddComponent(cb, "", part.comp_idx); part.t.mat[0] = part.t.mat[3] = 1024; part.t.mat[1] = part.t.mat[2] = 0; part.t.mat[4] = cb->x * SCALE; part.t.mat[5] = - cb->y * SCALE; frame.parts.push_back(part); } void PackAnimation::Clear() { export_name.clear(); components.clear(); actions.clear(); frames.clear(); } bool PackAnimation::AddComponent(const IPackNode* node, const std::string& name, int& comp_idx) { if (const PackAnchor* anchor = dynamic_cast<const PackAnchor*>(node)) { for (int i = 0, n = components.size(); i < n; ++i) { if (dynamic_cast<const PackAnchor*>(components[i].node) && components[i].name == name) { comp_idx = i; return true; } } } else { for (int i = 0, n = components.size(); i < n; ++i) { if (components[i].node == node && components[i].name == name) { comp_idx = i; return true; } } for (int i = 0, n = components.size(); i < n; ++i) { if (components[i].node->GetFilepath() == node->GetFilepath() && components[i].name == name && !name.empty()) { d2d::FileNameParser::Type type = d2d::FileNameParser::getFileType(node->GetFilepath()); if (type == d2d::FileNameParser::e_image || type == d2d::FileNameParser::e_complex || type == d2d::FileNameParser::e_anim) { comp_idx = i; return true; } } } } Component comp; comp.node = node; comp.name = name; components.push_back(comp); comp_idx = components.size() - 1; if (d2d::FileNameParser::isType(node->GetFilepath(), d2d::FileNameParser::e_image)) { return false; } else { return !name.empty(); } } void PackAnimation::LoadSprTrans(const d2d::ISprite* spr, SpriteTrans& trans, bool force_mat) { LoadSprMat(spr, trans, force_mat); LoadSprColor(spr, trans); } void PackAnimation::LoadSprMat(const d2d::ISprite* spr, SpriteTrans& trans, bool force) { if (!force && dynamic_cast<const d2d::ImageSprite*>(spr)) { return; } float mat[6]; // | 1 ky | | sx | | c s | | 1 | // | kx 1 | | sy | | -s c | | 1 | // | 1 | | 1 | | 1 | | x y 1 | // skew scale rotate move mat[1] = mat[2] = mat[4] = mat[5] = 0; mat[0] = mat[3] = 1; d2d::Vector center = spr->GetCenter(); bool xmir, ymir; spr->GetMirror(xmir, ymir); float sx = spr->GetScale().x, sy = spr->GetScale().y; if (xmir) { sx = -sx; } if (ymir) { sy = -sy; } float c = cos(-spr->GetAngle()), s = sin(-spr->GetAngle()); float kx = -spr->GetShear().x, ky = -spr->GetShear().y; mat[0] = sx*c - ky*sy*s; mat[1] = sx*s + ky*sy*c; mat[2] = kx*sx*c - sy*s; mat[3] = kx*sx*s + sy*c; mat[4] = center.x/* * m_scale*/; mat[5] = center.y/* * m_scale*/; for (size_t i = 0; i < 4; ++i) trans.mat[i] = floor(mat[i] * 1024 + 0.5f); for (size_t i = 4; i < 6; ++i) trans.mat[i] = floor(mat[i] * 16 + 0.5f); // flip y trans.mat[5] = -trans.mat[5]; } void PackAnimation::LoadSprColor(const d2d::ISprite* spr, SpriteTrans& trans) { trans.color = d2d::trans_color2int(spr->multiCol, d2d::PT_ARGB); trans.additive = d2d::trans_color2int(spr->addCol, d2d::PT_ARGB); trans.rmap = d2d::trans_color2int(spr->r_trans, d2d::PT_RGBA); trans.gmap = d2d::trans_color2int(spr->g_trans, d2d::PT_RGBA); trans.bmap = d2d::trans_color2int(spr->b_trans, d2d::PT_RGBA); } bool PackAnimation::IsMatrixIdentity(const int* mat) { return mat[0] == 1024 && mat[3] == 1024 && mat[1] == 0 && mat[2] == 0 && mat[4] == 0 && mat[5] == 0; } }<|endoftext|>
<commit_before>/******************************************************************************* FILE : cmgui.cpp LAST MODIFIED : 7 January 2003 DESCRIPTION : ==============================================================================*/ /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is cmgui. * * The Initial Developer of the Original Code is * Auckland Uniservices Ltd, Auckland, New Zealand. * Portions created by the Initial Developer are Copyright (C) 2005-2011 * the Initial Developer. All Rights Reserved. * * Contributor(s): * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ /*SAB I have concatenated the correct version file for each version externally in the shell with cat #include "version.h"*/ #include "configure/cmgui_configure.h" #include "configure/version.h" #include "context/context_app.h" #include "zinc/graphicsmodule.h" #include "command/cmiss.h" #include "context/context_app.h" #include "context/user_interface_module.h" #include "general/debug.h" #include "general/mystring.h" #include "general/message.h" #if defined (WX_USER_INTERFACE) # include "user_interface/user_interface_wx.hpp" # if defined (DARWIN) # include <ApplicationServices/ApplicationServices.h> # endif #endif #if defined (WX_USER_INTERFACE) #include <wx/wx.h> #include <wx/apptrait.h> #include <wx/xrc/xmlres.h> #endif /* Global functions ---------------- */ #if defined (WX_USER_INTERFACE) bool wxCmguiApp::OnInit() { return (true); } wxAppTraits * wxCmguiApp::CreateTraits() { return new wxGUIAppTraits; } void wxCmguiApp::OnIdle(wxIdleEvent& event) { if (event_dispatcher) { if (Event_dispatcher_process_idle_event(event_dispatcher)) { event.RequestMore(); } } } void wxCmguiApp::SetEventDispatcher(Event_dispatcher *event_dispatcher_in) { event_dispatcher = event_dispatcher_in; } BEGIN_EVENT_TABLE(wxCmguiApp, wxApp) EVT_IDLE(wxCmguiApp::OnIdle) END_EVENT_TABLE() IMPLEMENT_APP_NO_MAIN(wxCmguiApp) #endif /*defined (WX_USER_INTERFACE)*/ void ShortenPSN(int argc, char *argv[]) { int arg_count = argc; for(int i = 0; i < arg_count; i++) { if (strncmp(argv[i], "-psn", 4) == 0) { argv[i][4] = '\0'; } } } /** * Main program for the CMISS Graphical User Interface */ #if !defined (WIN32_USER_INTERFACE) && !defined (_MSC_VER) int main(int argc, char *argv[]) #else /* !defined (WIN32_USER_INTERFACE) && !defined (_MSC_VER)*/ int WINAPI WinMain(HINSTANCE current_instance,HINSTANCE previous_instance, LPSTR command_line,int initial_main_window_state) /* using WinMain as the entry point tells Windows that it is a gui and to use the graphics device interface functions for I/O */ /*???DB. WINDOWS a zero return code if WinMain does get into the message loop. Other application interfaces may expect something else. Should this failure code be #define'd ? */ /*???DB. Win32 SDK says that don't have to call it WinMain */ #endif /* !defined (WIN32_USER_INTERFACE) && !defined (_MSC_VER)*/ { int return_code = 0; struct Cmiss_context_app *context = NULL; struct User_interface_module *UI_module = NULL; struct Cmiss_command_data *command_data; #if !defined (WIN32_USER_INTERFACE) && !defined (_MSC_VER) ENTER(main); #else /* !defined (WIN32_USER_INTERFACE) && !defined (_MSC_VER)*/ ENTER(WinMain); //_CrtSetBreakAlloc(28336); int argc = 1; char *p, *q; for (p = command_line; p != NULL && *p != 0;) { p = strchr(p, ' '); if (p != NULL) p++; argc++; } char **argv = 0; ALLOCATE(argv, char *, argc); argv[0] = duplicate_string("cmgui"); int i = 1; for (p = command_line; p != NULL && *p != 0;) { q = strchr(p, ' '); if (q != NULL) *q++ = 0; if (p != NULL) argv[i++] = duplicate_string(p); p = q; } #endif /* !defined (WIN32_USER_INTERFACE) && !defined (_MSC_VER)*/ /* display the version */ display_message(INFORMATION_MESSAGE, "%s version %s %s\n%s\n" "Build information: %s %s\n", CMGUI_NAME_STRING, CMGUI_VERSION_STRING, CMGUI_DATETIME_STRING, CMGUI_COPYRIGHT_STRING, CMGUI_BUILD_STRING, CMGUI_SVN_REVISION_STRING); #if defined (CARBON_USER_INTERFACE) || (defined (WX_USER_INTERFACE) && defined (DARWIN)) ShortenPSN(argc, argv); // shorten the psn command line argument when launching from finder on os x to just -psn ProcessSerialNumber PSN; GetCurrentProcess(&PSN); TransformProcessType(&PSN,kProcessTransformToForegroundApplication); #endif context = Cmiss_context_app_create("default"); #if defined (WX_USER_INTERFACE) int wx_entry_started = 0; #endif if (context) { #if defined (WX_USER_INTERFACE) || (!defined (WIN32_USER_INTERFACE) && !defined (_MSC_VER)) UI_module = Cmiss_context_create_user_interface(context, argc, argv, NULL); #else /* !defined (WIN32_USER_INTERFACE) && !defined (_MSC_VER)*/ UI_module = Cmiss_context_create_user_interface(context, argc, argv, current_instance, previous_instance, command_line, initial_main_window_state, NULL); #endif /* !defined (WIN32_USER_INTERFACE) && !defined (_MSC_VER)*/ if (UI_module) { #if defined (WX_USER_INTERFACE) if (UI_module->user_interface) { if (wxEntryStart(argc, argv)) { wx_entry_started = 1; wxXmlResource::Get()->InitAllHandlers(); wxCmguiApp &app = wxGetApp(); if (&app) { app.SetEventDispatcher(UI_module->event_dispatcher); } else { display_message(ERROR_MESSAGE, "initialiseWxApp. wxCmguiApp not initialised."); } } else { display_message(ERROR_MESSAGE, "initialiseWxApp. Invalid arguments."); } } #endif if (NULL != (command_data = Cmiss_context_get_default_command_interpreter(context))) { Cmiss_command_data_set_cmgui_string(command_data, CMGUI_NAME_STRING, CMGUI_VERSION_STRING, "CMGUI_DATE_STRING", CMGUI_COPYRIGHT_STRING, CMGUI_BUILD_STRING, CMGUI_SVN_REVISION_STRING); Cmiss_command_data_main_loop(command_data); Cmiss_command_data_destroy(&command_data); return_code = 0; } else { return_code = 1; } User_interface_module_destroy(&UI_module); } else { return_code = 1; } Cmiss_context_app_destroy(&context); Context_internal_cleanup(); #if defined (WX_USER_INTERFACE) if (wx_entry_started) wxEntryCleanup(); #endif } else { return_code = 1; } #if defined (WIN32_USER_INTERFACE) || defined (_MSC_VER) if (argv) { for (int i = 0; i < argc; i++) { DEALLOCATE(argv[i]); } DEALLOCATE(argv); } #endif LEAVE; return (return_code); } /* main */ <commit_msg>Re-instating the time part of the version configuration for Cmgui, updating missing define from about dialog. https://tracker.physiomeproject.org/show_bug.cgi?id=3260<commit_after>/******************************************************************************* FILE : cmgui.cpp LAST MODIFIED : 7 January 2003 DESCRIPTION : ==============================================================================*/ /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is cmgui. * * The Initial Developer of the Original Code is * Auckland Uniservices Ltd, Auckland, New Zealand. * Portions created by the Initial Developer are Copyright (C) 2005-2011 * the Initial Developer. All Rights Reserved. * * Contributor(s): * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ /*SAB I have concatenated the correct version file for each version externally in the shell with cat #include "version.h"*/ #include "configure/cmgui_configure.h" #include "configure/version.h" #include "context/context_app.h" #include "zinc/graphicsmodule.h" #include "command/cmiss.h" #include "context/context_app.h" #include "context/user_interface_module.h" #include "general/debug.h" #include "general/mystring.h" #include "general/message.h" #if defined (WX_USER_INTERFACE) # include "user_interface/user_interface_wx.hpp" # if defined (DARWIN) # include <ApplicationServices/ApplicationServices.h> # endif #endif #if defined (WX_USER_INTERFACE) #include <wx/wx.h> #include <wx/apptrait.h> #include <wx/xrc/xmlres.h> #endif /* Global functions ---------------- */ #if defined (WX_USER_INTERFACE) bool wxCmguiApp::OnInit() { return (true); } wxAppTraits * wxCmguiApp::CreateTraits() { return new wxGUIAppTraits; } void wxCmguiApp::OnIdle(wxIdleEvent& event) { if (event_dispatcher) { if (Event_dispatcher_process_idle_event(event_dispatcher)) { event.RequestMore(); } } } void wxCmguiApp::SetEventDispatcher(Event_dispatcher *event_dispatcher_in) { event_dispatcher = event_dispatcher_in; } BEGIN_EVENT_TABLE(wxCmguiApp, wxApp) EVT_IDLE(wxCmguiApp::OnIdle) END_EVENT_TABLE() IMPLEMENT_APP_NO_MAIN(wxCmguiApp) #endif /*defined (WX_USER_INTERFACE)*/ void ShortenPSN(int argc, char *argv[]) { int arg_count = argc; for(int i = 0; i < arg_count; i++) { if (strncmp(argv[i], "-psn", 4) == 0) { argv[i][4] = '\0'; } } } /** * Main program for the CMISS Graphical User Interface */ #if !defined (WIN32_USER_INTERFACE) && !defined (_MSC_VER) int main(int argc, char *argv[]) #else /* !defined (WIN32_USER_INTERFACE) && !defined (_MSC_VER)*/ int WINAPI WinMain(HINSTANCE current_instance,HINSTANCE previous_instance, LPSTR command_line,int initial_main_window_state) /* using WinMain as the entry point tells Windows that it is a gui and to use the graphics device interface functions for I/O */ /*???DB. WINDOWS a zero return code if WinMain does get into the message loop. Other application interfaces may expect something else. Should this failure code be #define'd ? */ /*???DB. Win32 SDK says that don't have to call it WinMain */ #endif /* !defined (WIN32_USER_INTERFACE) && !defined (_MSC_VER)*/ { int return_code = 0; struct Cmiss_context_app *context = NULL; struct User_interface_module *UI_module = NULL; struct Cmiss_command_data *command_data; #if !defined (WIN32_USER_INTERFACE) && !defined (_MSC_VER) ENTER(main); #else /* !defined (WIN32_USER_INTERFACE) && !defined (_MSC_VER)*/ ENTER(WinMain); //_CrtSetBreakAlloc(28336); int argc = 1; char *p, *q; for (p = command_line; p != NULL && *p != 0;) { p = strchr(p, ' '); if (p != NULL) p++; argc++; } char **argv = 0; ALLOCATE(argv, char *, argc); argv[0] = duplicate_string("cmgui"); int i = 1; for (p = command_line; p != NULL && *p != 0;) { q = strchr(p, ' '); if (q != NULL) *q++ = 0; if (p != NULL) argv[i++] = duplicate_string(p); p = q; } #endif /* !defined (WIN32_USER_INTERFACE) && !defined (_MSC_VER)*/ /* display the version */ display_message(INFORMATION_MESSAGE, "%s version %s %s\n%s\n" "Build information: %s %s\n", CMGUI_NAME_STRING, CMGUI_VERSION_STRING, CMGUI_DATETIME_STRING, CMGUI_COPYRIGHT_STRING, CMGUI_BUILD_STRING, CMGUI_SVN_REVISION_STRING); #if defined (CARBON_USER_INTERFACE) || (defined (WX_USER_INTERFACE) && defined (DARWIN)) ShortenPSN(argc, argv); // shorten the psn command line argument when launching from finder on os x to just -psn ProcessSerialNumber PSN; GetCurrentProcess(&PSN); TransformProcessType(&PSN,kProcessTransformToForegroundApplication); #endif context = Cmiss_context_app_create("default"); #if defined (WX_USER_INTERFACE) int wx_entry_started = 0; #endif if (context) { #if defined (WX_USER_INTERFACE) || (!defined (WIN32_USER_INTERFACE) && !defined (_MSC_VER)) UI_module = Cmiss_context_create_user_interface(context, argc, argv, NULL); #else /* !defined (WIN32_USER_INTERFACE) && !defined (_MSC_VER)*/ UI_module = Cmiss_context_create_user_interface(context, argc, argv, current_instance, previous_instance, command_line, initial_main_window_state, NULL); #endif /* !defined (WIN32_USER_INTERFACE) && !defined (_MSC_VER)*/ if (UI_module) { #if defined (WX_USER_INTERFACE) if (UI_module->user_interface) { if (wxEntryStart(argc, argv)) { wx_entry_started = 1; wxXmlResource::Get()->InitAllHandlers(); wxCmguiApp &app = wxGetApp(); if (&app) { app.SetEventDispatcher(UI_module->event_dispatcher); } else { display_message(ERROR_MESSAGE, "initialiseWxApp. wxCmguiApp not initialised."); } } else { display_message(ERROR_MESSAGE, "initialiseWxApp. Invalid arguments."); } } #endif if (NULL != (command_data = Cmiss_context_get_default_command_interpreter(context))) { Cmiss_command_data_set_cmgui_string(command_data, CMGUI_NAME_STRING, CMGUI_VERSION_STRING, CMGUI_DATETIME_STRING, CMGUI_COPYRIGHT_STRING, CMGUI_BUILD_STRING, CMGUI_SVN_REVISION_STRING); Cmiss_command_data_main_loop(command_data); Cmiss_command_data_destroy(&command_data); return_code = 0; } else { return_code = 1; } User_interface_module_destroy(&UI_module); } else { return_code = 1; } Cmiss_context_app_destroy(&context); Context_internal_cleanup(); #if defined (WX_USER_INTERFACE) if (wx_entry_started) wxEntryCleanup(); #endif } else { return_code = 1; } #if defined (WIN32_USER_INTERFACE) || defined (_MSC_VER) if (argv) { for (int i = 0; i < argc; i++) { DEALLOCATE(argv[i]); } DEALLOCATE(argv); } #endif LEAVE; return (return_code); } /* main */ <|endoftext|>
<commit_before>#include "Simulation/EXIT/EXIT.hpp" #include <thread> #include <string> #include <iostream> #include "Factory/Module/Monitor/BFER/Monitor_BFER.hpp" #include "Factory/Module/Interleaver/Interleaver.hpp" #include "EXIT.hpp" using namespace aff3ct; using namespace aff3ct::launcher; template <typename B, typename R> EXIT<B,R> ::EXIT(const int argc, const char **argv, std::ostream &stream) : Launcher(argc, argv, params, stream) { params.set_src(new factory::Source ::parameters("src")); params.set_mdm(new factory::Modem ::parameters("mdm")); params.set_chn(new factory::Channel ::parameters("chn")); params.set_qnt(new factory::Quantizer ::parameters("qnt")); params.set_mnt(new factory::Monitor_EXIT ::parameters("mnt")); params.set_ter(new factory::Terminal_EXIT::parameters("ter")); } template <typename B, typename R> EXIT<B,R> ::~EXIT() { } template <typename B, typename R> void EXIT<B,R> ::build_args() { Launcher::build_args(); params. get_description(this->req_args, this->opt_args); params.src->get_description(this->req_args, this->opt_args); params.mdm->get_description(this->req_args, this->opt_args); params.chn->get_description(this->req_args, this->opt_args); params.mnt->get_description(this->req_args, this->opt_args); params.ter->get_description(this->req_args, this->opt_args); auto psrc = params.src ->get_prefix(); auto penc = params.cdc->enc->get_prefix(); auto ppct = std::string("pct"); auto pmdm = params.mdm ->get_prefix(); auto pchn = params.chn ->get_prefix(); auto pmnt = params.mnt ->get_prefix(); auto pter = params.ter ->get_prefix(); if (this->req_args.find({penc+"-info-bits", "K"}) != this->req_args.end() || this->req_args.find({ppct+"-info-bits", "K"}) != this->req_args.end()) this->req_args.erase({psrc+"-info-bits", "K"}); this->opt_args.erase({psrc+"-seed", "S"}); this->req_args.erase({pmdm+"-fra-size", "N"}); this->opt_args.erase({pmdm+"-fra", "F"}); this->opt_args.erase({pmdm+"-sigma" }); this->req_args.erase({pchn+"-fra-size", "N"}); this->opt_args.erase({pchn+"-fra", "F"}); this->opt_args.erase({pchn+"-sigma" }); this->opt_args.erase({pchn+"-seed", "S"}); this->opt_args.erase({pchn+"-add-users" }); this->opt_args.erase({pchn+"-complex" }); this->req_args.erase({pmnt+"-size", "K"}); this->opt_args.erase({pmnt+"-fra", "F"}); this->req_args.erase({pter+"-cw-size", "N"}); } template <typename B, typename R> void EXIT<B,R> ::store_args() { Launcher::store_args(); params.store(this->ar.get_args()); params.src->seed = params.local_seed; params.src->store(this->ar.get_args()); auto psrc = params.src->get_prefix(); auto K = this->req_args.find({psrc+"-info-bits", "K"}) != this->req_args.end() ? params.src->K : params.cdc->K; auto N = this->req_args.find({psrc+"-info-bits", "K"}) != this->req_args.end() ? params.src->K : params.cdc->N; params.src->K = params.src->K == 0 ? K : params.src->K; params.mdm->N = N; params.mdm->store(this->ar.get_args()); params.chn->N = params.mdm->N_mod; params.chn->complex = params.mdm->complex; params.chn->add_users = params.mdm->type == "SCMA"; params.chn->seed = params.local_seed; params.chn->store(this->ar.get_args()); params.mnt->size = K; params.mnt->store(this->ar.get_args()); params.ter->store(this->ar.get_args()); if (params.src->type == "AZCW" || params.cdc->enc->type == "AZCW") { params.src ->type = "AZCW"; params.cdc->enc->type = "AZCW"; } params.cdc->enc->seed = params.local_seed; params.mdm->n_frames = params.src->n_frames; params.chn->n_frames = params.src->n_frames; auto pmnt = params.mnt->get_prefix(); if (!this->ar.exist_arg({pmnt+"-trials", "n"})) params.mnt->n_trials = 200000 / params.cdc->K; } template <typename B, typename R> void EXIT<B,R> ::group_args() { Launcher::group_args(); this->arg_group.push_back({params. get_prefix(), "Simulation parameter(s)"}); this->arg_group.push_back({params.src->get_prefix(), params.src->get_short_name() + " parameter(s)"}); this->arg_group.push_back({params.mdm->get_prefix(), params.mdm->get_short_name() + " parameter(s)"}); this->arg_group.push_back({params.chn->get_prefix(), params.chn->get_short_name() + " parameter(s)"}); this->arg_group.push_back({params.mnt->get_prefix(), params.mnt->get_short_name() + " parameter(s)"}); this->arg_group.push_back({params.ter->get_prefix(), params.ter->get_short_name() + " parameter(s)"}); } template <typename B, typename R> void EXIT<B,R> ::print_header() { auto cpy_titles = this->titles; this->titles.clear(); auto pcde = "cde"; this->titles.push_back(std::make_pair(params. get_prefix(), "Simulation" )); this->titles.push_back(std::make_pair(pcde, "Code" )); this->titles.push_back(std::make_pair(params.src->get_prefix(), params.src->get_short_name())); this->titles.push_back(std::make_pair(params.mdm->get_prefix(), params.mdm->get_short_name())); for (auto t : cpy_titles) if (t.first.find("enc") == 0) this->titles.push_back(t); this->titles.push_back(std::make_pair(params.chn->get_prefix(), params.chn->get_short_name())); for (auto t : cpy_titles) if (t.first.find("dec") == 0) this->titles.push_back(t); this->titles.push_back(std::make_pair(params.mnt->get_prefix(), params.mnt->get_short_name())); this->titles.push_back(std::make_pair(params.ter->get_prefix(), params.ter->get_short_name())); params. get_headers(this->headers, false); params.src->get_headers(this->headers, false); params.mdm->get_headers(this->headers, false); params.chn->get_headers(this->headers, false); params.mnt->get_headers(this->headers, false); params.ter->get_headers(this->headers, false); this->headers[pcde].push_back(std::make_pair("Type", params.cde_type )); this->headers[pcde].push_back(std::make_pair("Info. bits (K)", std::to_string(params.cdc->K ))); this->headers[pcde].push_back(std::make_pair("Codeword size (N)", std::to_string(params.cdc->N ))); this->headers[pcde].push_back(std::make_pair("Code rate", std::to_string(params.cdc->enc->R))); Launcher::print_header(); } template <typename B, typename R> simulation::Simulation* EXIT<B,R> ::build_simu() { return factory::EXIT::build<B,R>(params); } // ==================================================================================== explicit template instantiation #include "Tools/types.h" #ifdef MULTI_PREC template class aff3ct::launcher::EXIT<B_32,R_32>; template class aff3ct::launcher::EXIT<B_64,R_64>; #else template class aff3ct::launcher::EXIT<B,R>; #endif // ==================================================================================== explicit template instantiation <commit_msg>Fix a div by 0 in the EXIT launcher.<commit_after>#include "Simulation/EXIT/EXIT.hpp" #include <thread> #include <string> #include <iostream> #include "Factory/Module/Monitor/BFER/Monitor_BFER.hpp" #include "Factory/Module/Interleaver/Interleaver.hpp" #include "EXIT.hpp" using namespace aff3ct; using namespace aff3ct::launcher; template <typename B, typename R> EXIT<B,R> ::EXIT(const int argc, const char **argv, std::ostream &stream) : Launcher(argc, argv, params, stream) { params.set_src(new factory::Source ::parameters("src")); params.set_mdm(new factory::Modem ::parameters("mdm")); params.set_chn(new factory::Channel ::parameters("chn")); params.set_qnt(new factory::Quantizer ::parameters("qnt")); params.set_mnt(new factory::Monitor_EXIT ::parameters("mnt")); params.set_ter(new factory::Terminal_EXIT::parameters("ter")); } template <typename B, typename R> EXIT<B,R> ::~EXIT() { } template <typename B, typename R> void EXIT<B,R> ::build_args() { Launcher::build_args(); params. get_description(this->req_args, this->opt_args); params.src->get_description(this->req_args, this->opt_args); params.mdm->get_description(this->req_args, this->opt_args); params.chn->get_description(this->req_args, this->opt_args); params.mnt->get_description(this->req_args, this->opt_args); params.ter->get_description(this->req_args, this->opt_args); auto psrc = params.src ->get_prefix(); auto penc = params.cdc->enc->get_prefix(); auto pmdm = params.mdm ->get_prefix(); auto pchn = params.chn ->get_prefix(); auto pmnt = params.mnt ->get_prefix(); auto pter = params.ter ->get_prefix(); if (this->req_args.find({penc+"-info-bits", "K"}) != this->req_args.end()) this->req_args.erase({psrc+"-info-bits", "K"}); this->opt_args.erase({psrc+"-seed", "S"}); this->req_args.erase({pmdm+"-fra-size", "N"}); this->opt_args.erase({pmdm+"-fra", "F"}); this->opt_args.erase({pmdm+"-sigma" }); this->req_args.erase({pchn+"-fra-size", "N"}); this->opt_args.erase({pchn+"-fra", "F"}); this->opt_args.erase({pchn+"-sigma" }); this->opt_args.erase({pchn+"-seed", "S"}); this->opt_args.erase({pchn+"-add-users" }); this->opt_args.erase({pchn+"-complex" }); this->req_args.erase({pmnt+"-size", "K"}); this->opt_args.erase({pmnt+"-fra", "F"}); this->req_args.erase({pter+"-cw-size", "N"}); } template <typename B, typename R> void EXIT<B,R> ::store_args() { Launcher::store_args(); params.store(this->ar.get_args()); params.src->seed = params.local_seed; params.src->store(this->ar.get_args()); auto psrc = params.src->get_prefix(); auto K = this->req_args.find({psrc+"-info-bits", "K"}) != this->req_args.end() ? params.src->K : params.cdc->K; auto N = this->req_args.find({psrc+"-info-bits", "K"}) != this->req_args.end() ? params.src->K : params.cdc->N; params.src->K = params.src->K == 0 ? K : params.src->K; params.mdm->N = N; params.mdm->store(this->ar.get_args()); params.chn->N = params.mdm->N_mod; params.chn->complex = params.mdm->complex; params.chn->add_users = params.mdm->type == "SCMA"; params.chn->seed = params.local_seed; params.chn->store(this->ar.get_args()); params.mnt->size = K; params.mnt->store(this->ar.get_args()); params.ter->store(this->ar.get_args()); if (params.src->type == "AZCW" || params.cdc->enc->type == "AZCW") { params.src ->type = "AZCW"; params.cdc->enc->type = "AZCW"; } params.cdc->enc->seed = params.local_seed; params.mdm->n_frames = params.src->n_frames; params.chn->n_frames = params.src->n_frames; auto pmnt = params.mnt->get_prefix(); if (!this->ar.exist_arg({pmnt+"-trials", "n"}) && params.cdc->K != 0) params.mnt->n_trials = 200000 / params.cdc->K; } template <typename B, typename R> void EXIT<B,R> ::group_args() { Launcher::group_args(); this->arg_group.push_back({params. get_prefix(), "Simulation parameter(s)"}); this->arg_group.push_back({params.src->get_prefix(), params.src->get_short_name() + " parameter(s)"}); this->arg_group.push_back({params.mdm->get_prefix(), params.mdm->get_short_name() + " parameter(s)"}); this->arg_group.push_back({params.chn->get_prefix(), params.chn->get_short_name() + " parameter(s)"}); this->arg_group.push_back({params.mnt->get_prefix(), params.mnt->get_short_name() + " parameter(s)"}); this->arg_group.push_back({params.ter->get_prefix(), params.ter->get_short_name() + " parameter(s)"}); } template <typename B, typename R> void EXIT<B,R> ::print_header() { auto cpy_titles = this->titles; this->titles.clear(); auto pcde = "cde"; this->titles.push_back(std::make_pair(params. get_prefix(), "Simulation" )); this->titles.push_back(std::make_pair(pcde, "Code" )); this->titles.push_back(std::make_pair(params.src->get_prefix(), params.src->get_short_name())); this->titles.push_back(std::make_pair(params.mdm->get_prefix(), params.mdm->get_short_name())); for (auto t : cpy_titles) if (t.first.find("enc") == 0) this->titles.push_back(t); this->titles.push_back(std::make_pair(params.chn->get_prefix(), params.chn->get_short_name())); for (auto t : cpy_titles) if (t.first.find("dec") == 0) this->titles.push_back(t); this->titles.push_back(std::make_pair(params.mnt->get_prefix(), params.mnt->get_short_name())); this->titles.push_back(std::make_pair(params.ter->get_prefix(), params.ter->get_short_name())); params. get_headers(this->headers, false); params.src->get_headers(this->headers, false); params.mdm->get_headers(this->headers, false); params.chn->get_headers(this->headers, false); params.mnt->get_headers(this->headers, false); params.ter->get_headers(this->headers, false); this->headers[pcde].push_back(std::make_pair("Type", params.cde_type )); this->headers[pcde].push_back(std::make_pair("Info. bits (K)", std::to_string(params.cdc->K ))); this->headers[pcde].push_back(std::make_pair("Codeword size (N)", std::to_string(params.cdc->N ))); this->headers[pcde].push_back(std::make_pair("Code rate", std::to_string(params.cdc->enc->R))); Launcher::print_header(); } template <typename B, typename R> simulation::Simulation* EXIT<B,R> ::build_simu() { return factory::EXIT::build<B,R>(params); } // ==================================================================================== explicit template instantiation #include "Tools/types.h" #ifdef MULTI_PREC template class aff3ct::launcher::EXIT<B_32,R_32>; template class aff3ct::launcher::EXIT<B_64,R_64>; #else template class aff3ct::launcher::EXIT<B,R>; #endif // ==================================================================================== explicit template instantiation <|endoftext|>
<commit_before> // -*- mode: c++; c-basic-offset:4 -*- // This file is part of libdap, A C++ implementation of the OPeNDAP Data // Access Protocol. // Copyright (c) 2002,2003 OPeNDAP, Inc. // Author: James Gallagher <[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) 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 // // You can contact OPeNDAP, Inc. at PO Box 112, Saunderstown, RI. 02874-0112. // (c) COPYRIGHT URI/MIT 1994-2002 // Please read the full copyright statement in the file COPYRIGHT_URI. // // Authors: // jhrg,jimg James Gallagher <[email protected]> #include "config.h" static char rcsid[] not_used = { "$Id$" }; #include <signal.h> #ifndef WIN32 #include <unistd.h> #endif #include <pthread.h> #include "SignalHandler.h" #include "util.h" EventHandler *SignalHandler::d_signal_handlers[NSIG]; Sigfunc *SignalHandler::d_old_handlers[NSIG]; SignalHandler *SignalHandler::d_instance = 0; // instance_control is used to ensure that in a MT environment d_instance is // correctly initialized. static pthread_once_t instance_control = PTHREAD_ONCE_INIT; /// Private static void method. void SignalHandler::initialize_instance() { // MT-Safe if called via pthread_once or similar SignalHandler::d_instance = new SignalHandler; atexit(SignalHandler::delete_instance); } /// Private static void method. void SignalHandler::delete_instance() { if (SignalHandler::d_instance) { for (int i = 0; i < NSIG; ++i) { d_signal_handlers[i] = 0; d_old_handlers[i] = 0; } delete SignalHandler::d_instance; SignalHandler::d_instance = 0; } } /** This private method is the adapter between the C-style interface of the signal sub-system and C++'s method interface. This uses the lookup table to find an instance of EventHandler and calls that instance's handle_signal method. @param signum The number of the signal. */ void SignalHandler::dispatcher(int signum) { // Perform a sanity check... if (SignalHandler::d_signal_handlers[signum] != 0) // Dispatch the handler's hook method. SignalHandler::d_signal_handlers[signum]->handle_signal(signum); Sigfunc *old_handler = SignalHandler::d_old_handlers[signum]; if (old_handler == SIG_IGN || old_handler == SIG_ERR) return; else if (old_handler == SIG_DFL) { switch (signum) { #ifndef WIN32 case SIGHUP: case SIGKILL: case SIGUSR1: case SIGUSR2: case SIGPIPE: case SIGALRM: #endif case SIGINT: case SIGTERM: _exit(EXIT_FAILURE); // register_handler() should never allow any fiddling with // signals other than those listed above. default: abort(); } } else old_handler(signum); } /** Get a pointer to the single instance of SignalHandler. */ SignalHandler* SignalHandler::instance() { pthread_once(&instance_control, initialize_instance); return d_instance; } /** Register an event handler. By default run any previously registered action/handler such as those installed using \c sigaction(). For signals such as SIGALRM (the alarm signal) this may not be what you want; see the \e override parameter. See also the class description. @param signum Bind the event handler to this signal number. Limited to those signals that, according to POSIX.1, cause process termination. @param eh A pointer to the EventHandler for \c signum. @param override If \c true, do not run the default handler/action. Instead run \e eh and then treat the signal as if the original action was SIG_IGN. Default is false. @return A pointer to the old EventHandler or null. */ EventHandler * SignalHandler::register_handler(int signum, EventHandler *eh, bool override) throw(InternalErr) { // Check first for improper use. switch (signum) { #ifndef WIN32 case SIGHUP: case SIGKILL: case SIGUSR1: case SIGUSR2 case SIGPIPE: case SIGALRM: #endif case SIGINT: case SIGTERM: break; default: throw InternalErr(__FILE__, __LINE__, string("Call to register_handler with unsupported signal (") + long_to_string(signum) + string(").")); } // Save the old EventHandler EventHandler *old_eh = SignalHandler::d_signal_handlers[signum]; SignalHandler::d_signal_handlers[signum] = eh; // Register the dispatcher to handle this signal. See Stevens, Advanced // Programming in the UNIX Environment, p.298. #ifndef WIN32 struct sigaction sa; sa.sa_handler = dispatcher; sigemptyset(&sa.sa_mask); sa.sa_flags = 0; // Try to suppress restarting system calls if we're handling an alarm. // This lets alarms block I/O calls that would normally restart. 07/18/03 // jhrg if (signum == SIGALRM) { #ifdef SA_INTERUPT sa.sa_flags |= SA_INTERUPT; #endif } else { #ifdef SA_RESTART sa.sa_flags |= SA_RESTART; #endif } struct sigaction osa; // extract the old handler/action if (sigaction(signum, &sa, &osa) < 0) throw InternalErr(__FILE__, __LINE__, "Could not register a signal handler."); // Take care of the case where this interface is used to register a // handler more than once. We want to make sure that the dispatcher is // not installed as the 'old handler' because that results in an infinite // loop. 02/10/04 jhrg if (override) SignalHandler::d_old_handlers[signum] = SIG_IGN; else if (osa.sa_handler != dispatcher) SignalHandler::d_old_handlers[signum] = osa.sa_handler; #endif return old_eh; } /** Remove the event hander. @param signum The signal number of the handler to remove. @return The old event handler */ EventHandler * SignalHandler::remove_handler(int signum) { EventHandler *old_eh = SignalHandler::d_signal_handlers[signum]; SignalHandler::d_signal_handlers[signum] = 0; return old_eh; } // $Log: SignalHandler.cc,v $ // Revision 1.6 2005/04/21 17:48:59 jimg // Removed PTHREADS compile-time switch. Also, checkpoint for the build // work. // // Revision 1.5 2004/07/07 21:08:48 jimg // Merged with release-3-4-8FCS // // Revision 1.4 2004/06/28 16:57:53 pwest // unix compiler issues // // Revision 1.1.2.12 2004/04/02 16:46:36 dan // Fixed aproblem with the Alpha build. Code didn't compile when HAVE_PTHREAD // was not defined. // // Revision 1.1.2.11 2004/03/11 18:21:59 jimg // Removed unneeded extra pthread_once_t mutex (was used for // re-initialization). // // Revision 1.1.2.10 2004/03/11 18:11:36 jimg // Ripped out the code in delete_instance that (tries to) reset(s) the // pthread_once_t mutex. We cannot do this in a portable way and it's needed // only for the unit tests, which I claim to have fixed so they don't require // it anymore. // // Revision 1.1.2.9 2004/03/07 23:17:44 rmorris // Make static initialization of PTHREAD_ONCE_INIT compatible cross platform. // // Revision 1.1.2.8 2004/02/27 17:25:12 edavis // adding { } for PTHREAD_ONCE_INIT parm // // Revision 1.1.2.7 2004/02/26 22:44:50 edavis // remove the platform dependent parm PTHREAD_ONCE_INIT // // Revision 1.1.2.6 2004/02/22 23:35:03 rmorris // Solved some problems regarding the differences in the pthread // implementation across OSX, Win32 and non-OSX unixes. Either we are using // pthreads in a manner that was not intended by the pthread 'standard' (??) // or pthread implementations vary across platform or (finally) perhaps we // are encountering different implementations of pthreads as a result of its // development over time. Regardless our pthread code is starting to become // less portable. See how pthread_once_t varies across the above-mentioned // platforms. These changes get it to compile. I'm crossing my fingers that // it will run correctly everywhere. // // Revision 1.3 2004/02/19 19:42:52 jimg // Merged with release-3-4-2FCS and resolved conflicts. // // Revision 1.1.2.5 2004/02/11 17:12:01 jimg // Changed how this class creates its instance. It now does the same thing as // RCReader and is much more in line with HTTPCache. // // Revision 1.1.2.4 2004/02/10 20:48:13 jimg // Added support for running old handlers/actions once the newly registered // handlers are executed. Also limited the signals to those that POSIX.1 defines // as terminating the process by default. The code won't try to work with other // signals. It's possible to get it to do so, but fairly involved. See Steven's // "Advanced Programming ..." book for the lowdown on signals. // // Revision 1.2 2003/12/08 18:02:29 edavis // Merge release-3-4 into trunk // // Revision 1.1.2.3 2003/12/05 15:59:52 dan // Fixed compile error in #if HAVE_PTHREAD_H, else clause. Was using // '_instance' when it should be 'd_instance'. // // Revision 1.1.2.2 2003/07/19 01:48:02 jimg // Fixed up some comments. // // Revision 1.1.2.1 2003/07/19 01:47:43 jimg // Added. // <commit_msg>Missing colon in switch from recent porting tweeks.<commit_after> // -*- mode: c++; c-basic-offset:4 -*- // This file is part of libdap, A C++ implementation of the OPeNDAP Data // Access Protocol. // Copyright (c) 2002,2003 OPeNDAP, Inc. // Author: James Gallagher <[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) 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 // // You can contact OPeNDAP, Inc. at PO Box 112, Saunderstown, RI. 02874-0112. // (c) COPYRIGHT URI/MIT 1994-2002 // Please read the full copyright statement in the file COPYRIGHT_URI. // // Authors: // jhrg,jimg James Gallagher <[email protected]> #include "config.h" static char rcsid[] not_used = { "$Id$" }; #include <signal.h> #ifndef WIN32 #include <unistd.h> #endif #include <pthread.h> #include "SignalHandler.h" #include "util.h" EventHandler *SignalHandler::d_signal_handlers[NSIG]; Sigfunc *SignalHandler::d_old_handlers[NSIG]; SignalHandler *SignalHandler::d_instance = 0; // instance_control is used to ensure that in a MT environment d_instance is // correctly initialized. static pthread_once_t instance_control = PTHREAD_ONCE_INIT; /// Private static void method. void SignalHandler::initialize_instance() { // MT-Safe if called via pthread_once or similar SignalHandler::d_instance = new SignalHandler; atexit(SignalHandler::delete_instance); } /// Private static void method. void SignalHandler::delete_instance() { if (SignalHandler::d_instance) { for (int i = 0; i < NSIG; ++i) { d_signal_handlers[i] = 0; d_old_handlers[i] = 0; } delete SignalHandler::d_instance; SignalHandler::d_instance = 0; } } /** This private method is the adapter between the C-style interface of the signal sub-system and C++'s method interface. This uses the lookup table to find an instance of EventHandler and calls that instance's handle_signal method. @param signum The number of the signal. */ void SignalHandler::dispatcher(int signum) { // Perform a sanity check... if (SignalHandler::d_signal_handlers[signum] != 0) // Dispatch the handler's hook method. SignalHandler::d_signal_handlers[signum]->handle_signal(signum); Sigfunc *old_handler = SignalHandler::d_old_handlers[signum]; if (old_handler == SIG_IGN || old_handler == SIG_ERR) return; else if (old_handler == SIG_DFL) { switch (signum) { #ifndef WIN32 case SIGHUP: case SIGKILL: case SIGUSR1: case SIGUSR2: case SIGPIPE: case SIGALRM: #endif case SIGINT: case SIGTERM: _exit(EXIT_FAILURE); // register_handler() should never allow any fiddling with // signals other than those listed above. default: abort(); } } else old_handler(signum); } /** Get a pointer to the single instance of SignalHandler. */ SignalHandler* SignalHandler::instance() { pthread_once(&instance_control, initialize_instance); return d_instance; } /** Register an event handler. By default run any previously registered action/handler such as those installed using \c sigaction(). For signals such as SIGALRM (the alarm signal) this may not be what you want; see the \e override parameter. See also the class description. @param signum Bind the event handler to this signal number. Limited to those signals that, according to POSIX.1, cause process termination. @param eh A pointer to the EventHandler for \c signum. @param override If \c true, do not run the default handler/action. Instead run \e eh and then treat the signal as if the original action was SIG_IGN. Default is false. @return A pointer to the old EventHandler or null. */ EventHandler * SignalHandler::register_handler(int signum, EventHandler *eh, bool override) throw(InternalErr) { // Check first for improper use. switch (signum) { #ifndef WIN32 case SIGHUP: case SIGKILL: case SIGUSR1: case SIGUSR2: case SIGPIPE: case SIGALRM: #endif case SIGINT: case SIGTERM: break; default: throw InternalErr(__FILE__, __LINE__, string("Call to register_handler with unsupported signal (") + long_to_string(signum) + string(").")); } // Save the old EventHandler EventHandler *old_eh = SignalHandler::d_signal_handlers[signum]; SignalHandler::d_signal_handlers[signum] = eh; // Register the dispatcher to handle this signal. See Stevens, Advanced // Programming in the UNIX Environment, p.298. #ifndef WIN32 struct sigaction sa; sa.sa_handler = dispatcher; sigemptyset(&sa.sa_mask); sa.sa_flags = 0; // Try to suppress restarting system calls if we're handling an alarm. // This lets alarms block I/O calls that would normally restart. 07/18/03 // jhrg if (signum == SIGALRM) { #ifdef SA_INTERUPT sa.sa_flags |= SA_INTERUPT; #endif } else { #ifdef SA_RESTART sa.sa_flags |= SA_RESTART; #endif } struct sigaction osa; // extract the old handler/action if (sigaction(signum, &sa, &osa) < 0) throw InternalErr(__FILE__, __LINE__, "Could not register a signal handler."); // Take care of the case where this interface is used to register a // handler more than once. We want to make sure that the dispatcher is // not installed as the 'old handler' because that results in an infinite // loop. 02/10/04 jhrg if (override) SignalHandler::d_old_handlers[signum] = SIG_IGN; else if (osa.sa_handler != dispatcher) SignalHandler::d_old_handlers[signum] = osa.sa_handler; #endif return old_eh; } /** Remove the event hander. @param signum The signal number of the handler to remove. @return The old event handler */ EventHandler * SignalHandler::remove_handler(int signum) { EventHandler *old_eh = SignalHandler::d_signal_handlers[signum]; SignalHandler::d_signal_handlers[signum] = 0; return old_eh; } // $Log: SignalHandler.cc,v $ // Revision 1.6 2005/04/21 17:48:59 jimg // Removed PTHREADS compile-time switch. Also, checkpoint for the build // work. // // Revision 1.5 2004/07/07 21:08:48 jimg // Merged with release-3-4-8FCS // // Revision 1.4 2004/06/28 16:57:53 pwest // unix compiler issues // // Revision 1.1.2.12 2004/04/02 16:46:36 dan // Fixed aproblem with the Alpha build. Code didn't compile when HAVE_PTHREAD // was not defined. // // Revision 1.1.2.11 2004/03/11 18:21:59 jimg // Removed unneeded extra pthread_once_t mutex (was used for // re-initialization). // // Revision 1.1.2.10 2004/03/11 18:11:36 jimg // Ripped out the code in delete_instance that (tries to) reset(s) the // pthread_once_t mutex. We cannot do this in a portable way and it's needed // only for the unit tests, which I claim to have fixed so they don't require // it anymore. // // Revision 1.1.2.9 2004/03/07 23:17:44 rmorris // Make static initialization of PTHREAD_ONCE_INIT compatible cross platform. // // Revision 1.1.2.8 2004/02/27 17:25:12 edavis // adding { } for PTHREAD_ONCE_INIT parm // // Revision 1.1.2.7 2004/02/26 22:44:50 edavis // remove the platform dependent parm PTHREAD_ONCE_INIT // // Revision 1.1.2.6 2004/02/22 23:35:03 rmorris // Solved some problems regarding the differences in the pthread // implementation across OSX, Win32 and non-OSX unixes. Either we are using // pthreads in a manner that was not intended by the pthread 'standard' (??) // or pthread implementations vary across platform or (finally) perhaps we // are encountering different implementations of pthreads as a result of its // development over time. Regardless our pthread code is starting to become // less portable. See how pthread_once_t varies across the above-mentioned // platforms. These changes get it to compile. I'm crossing my fingers that // it will run correctly everywhere. // // Revision 1.3 2004/02/19 19:42:52 jimg // Merged with release-3-4-2FCS and resolved conflicts. // // Revision 1.1.2.5 2004/02/11 17:12:01 jimg // Changed how this class creates its instance. It now does the same thing as // RCReader and is much more in line with HTTPCache. // // Revision 1.1.2.4 2004/02/10 20:48:13 jimg // Added support for running old handlers/actions once the newly registered // handlers are executed. Also limited the signals to those that POSIX.1 defines // as terminating the process by default. The code won't try to work with other // signals. It's possible to get it to do so, but fairly involved. See Steven's // "Advanced Programming ..." book for the lowdown on signals. // // Revision 1.2 2003/12/08 18:02:29 edavis // Merge release-3-4 into trunk // // Revision 1.1.2.3 2003/12/05 15:59:52 dan // Fixed compile error in #if HAVE_PTHREAD_H, else clause. Was using // '_instance' when it should be 'd_instance'. // // Revision 1.1.2.2 2003/07/19 01:48:02 jimg // Fixed up some comments. // // Revision 1.1.2.1 2003/07/19 01:47:43 jimg // Added. // <|endoftext|>
<commit_before>#include "SimpleSocket.h" #include <sys/types.h> // for data types #include <sys/socket.h> // for socket(), connect(), send(), and recv() #include <poll.h> #include <unistd.h> // for close() #include <cstring> // for strerror() #include <cerrno> // for errno using namespace NET; SocketException::SocketException( const std::string& message, bool inclSysMsg /* = true */) throw() : m_message(message) { if(inclSysMsg) { m_message += ": "; m_message += strerror(errno); } } SimpleSocket::SimpleSocket( int domain, int type, int protocol) : m_peerDisconnected(false) { if( (m_socket = socket( domain, type, protocol)) < 0) throw SocketException("Socket creation failed (socket)"); } SimpleSocket::SimpleSocket( int sockfd) : m_socket(sockfd) , m_peerDisconnected(false) {} SimpleSocket::~SimpleSocket() { ::close(m_socket); // on Windows do cleanup here } int SimpleSocket::send( const void* buffer, size_t len) { int sent; if( (sent = ::send( m_socket, (const raw_type*) buffer, len, 0)) < 0) throw SocketException("Send failed (send)"); return sent; } int SimpleSocket::receive( void* buffer, size_t len) { int ret = ::recv( m_socket, (raw_type*) buffer, len, 0); if( ret < 0) throw SocketException("Received failed (receive)"); if( !ret) m_peerDisconnected = true; return ret; } int SimpleSocket::timedReceive( void* buffer, size_t len, int timeout) { struct pollfd poll; poll.fd = m_socket; poll.events = POLLIN | POLLPRI | POLLRDHUP; int ret = ::poll( &poll, 1, timeout); if( ret == 0) return 0; if( ret < 0) throw SocketException("Receive failed (poll)"); if( poll.revents & POLLIN || poll.revents & POLLPRI) { ret = ::recv( m_socket, (raw_type*) buffer, len, 0); if( ret < 0) throw SocketException("Receive failed (recv)"); if( !ret) m_peerDisconnected = true; return ret; } if( poll.revents & POLLRDHUP) { m_peerDisconnected = true; } return 0; } void SimpleSocket::shutdown( ShutdownDirection type) { if( ::shutdown( m_socket, type) < 0) throw SocketException("Shutdown failed (shutdown)"); } bool SimpleSocket::peerDisconnected() { return m_peerDisconnected; } <commit_msg>rewrite send to handle UDP errors<commit_after>#include "SimpleSocket.h" #include <sys/types.h> // for data types #include <sys/socket.h> // for socket(), connect(), send(), and recv() #include <poll.h> #include <unistd.h> // for close() #include <cstring> // for strerror() #include <cerrno> // for errno using namespace NET; SocketException::SocketException( const std::string& message, bool inclSysMsg /* = true */) throw() : m_message(message) { if(inclSysMsg) { m_message += ": "; m_message += strerror(errno); } } SimpleSocket::SimpleSocket( int domain, int type, int protocol) : m_peerDisconnected(false) { if( (m_socket = socket( domain, type, protocol)) < 0) throw SocketException("Socket creation failed (socket)"); } SimpleSocket::SimpleSocket( int sockfd) : m_socket(sockfd) , m_peerDisconnected(false) {} SimpleSocket::~SimpleSocket() { ::close(m_socket); // on Windows do cleanup here } int SimpleSocket::send( const void* buffer, size_t len) { int sent = ::send( m_socket, (const raw_type*) buffer, len, 0); if( sent < 0) { if( errno != ECONNREFUSED) throw SocketException("Send failed (send)"); m_peerDisconnected = true; } return sent; } int SimpleSocket::receive( void* buffer, size_t len) { int ret = ::recv( m_socket, (raw_type*) buffer, len, 0); if( ret < 0) throw SocketException("Received failed (receive)"); if( !ret) m_peerDisconnected = true; return ret; } int SimpleSocket::timedReceive( void* buffer, size_t len, int timeout) { struct pollfd poll; poll.fd = m_socket; poll.events = POLLIN | POLLPRI | POLLRDHUP; int ret = ::poll( &poll, 1, timeout); if( ret == 0) return 0; if( ret < 0) throw SocketException("Receive failed (poll)"); if( poll.revents & POLLIN || poll.revents & POLLPRI) { ret = ::recv( m_socket, (raw_type*) buffer, len, 0); if( ret < 0) throw SocketException("Receive failed (recv)"); if( !ret) m_peerDisconnected = true; return ret; } if( poll.revents & POLLRDHUP) { m_peerDisconnected = true; } return 0; } void SimpleSocket::shutdown( ShutdownDirection type) { if( ::shutdown( m_socket, type) < 0) throw SocketException("Shutdown failed (shutdown)"); } bool SimpleSocket::peerDisconnected() { return m_peerDisconnected; } <|endoftext|>
<commit_before>// 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 "sandbox/linux/seccomp-bpf/sandbox_bpf.h" // Some headers on Android are missing cdefs: crbug.com/172337. // (We can't use OS_ANDROID here since build_config.h is not included). #if defined(ANDROID) #include <sys/cdefs.h> #endif #include <errno.h> #include <linux/filter.h> #include <sys/prctl.h> #include <sys/types.h> #include <unistd.h> #include "base/compiler_specific.h" #include "base/logging.h" #include "base/macros.h" #include "base/memory/scoped_ptr.h" #include "base/posix/eintr_wrapper.h" #include "sandbox/linux/bpf_dsl/dump_bpf.h" #include "sandbox/linux/bpf_dsl/policy.h" #include "sandbox/linux/bpf_dsl/policy_compiler.h" #include "sandbox/linux/seccomp-bpf/codegen.h" #include "sandbox/linux/seccomp-bpf/die.h" #include "sandbox/linux/seccomp-bpf/errorcode.h" #include "sandbox/linux/seccomp-bpf/linux_seccomp.h" #include "sandbox/linux/seccomp-bpf/syscall.h" #include "sandbox/linux/seccomp-bpf/syscall_iterator.h" #include "sandbox/linux/seccomp-bpf/trap.h" #include "sandbox/linux/seccomp-bpf/verifier.h" #include "sandbox/linux/services/linux_syscalls.h" #include "sandbox/linux/services/syscall_wrappers.h" #include "sandbox/linux/services/thread_helpers.h" namespace sandbox { namespace { bool IsSingleThreaded(int proc_task_fd) { return ThreadHelpers::IsSingleThreaded(proc_task_fd); } // Check if the kernel supports seccomp-filter (a.k.a. seccomp mode 2) via // prctl(). bool KernelSupportsSeccompBPF() { errno = 0; const int rv = prctl(PR_SET_SECCOMP, SECCOMP_MODE_FILTER, nullptr); if (rv == -1 && EFAULT == errno) { return true; } return false; } // Check if the kernel supports seccomp-filter via the seccomp system call // and the TSYNC feature to enable seccomp on all threads. bool KernelSupportsSeccompTsync() { errno = 0; const int rv = sys_seccomp(SECCOMP_SET_MODE_FILTER, SECCOMP_FILTER_FLAG_TSYNC, nullptr); if (rv == -1 && errno == EFAULT) { return true; } else { // TODO(jln): turn these into DCHECK after 417888 is considered fixed. CHECK_EQ(-1, rv); CHECK(ENOSYS == errno || EINVAL == errno); return false; } } } // namespace SandboxBPF::SandboxBPF() : proc_task_fd_(-1), sandbox_has_started_(false), policy_() { } SandboxBPF::~SandboxBPF() { if (proc_task_fd_ != -1) IGNORE_EINTR(close(proc_task_fd_)); } // static bool SandboxBPF::SupportsSeccompSandbox(SeccompLevel level) { switch (level) { case SeccompLevel::SINGLE_THREADED: return KernelSupportsSeccompBPF(); case SeccompLevel::MULTI_THREADED: return KernelSupportsSeccompTsync(); } NOTREACHED(); return false; } // Don't take a scoped_ptr here, polymorphism makes their use awkward. void SandboxBPF::SetSandboxPolicy(bpf_dsl::Policy* policy) { DCHECK(!policy_); if (sandbox_has_started_) { SANDBOX_DIE("Cannot change policy after sandbox has started"); } policy_.reset(policy); } bool SandboxBPF::StartSandbox(SeccompLevel seccomp_level) { CHECK(seccomp_level == SeccompLevel::SINGLE_THREADED || seccomp_level == SeccompLevel::MULTI_THREADED); if (sandbox_has_started_) { SANDBOX_DIE( "Cannot repeatedly start sandbox. Create a separate Sandbox " "object instead."); return false; } const bool supports_tsync = KernelSupportsSeccompTsync(); if (seccomp_level == SeccompLevel::SINGLE_THREADED) { if (!IsSingleThreaded(proc_task_fd_)) { SANDBOX_DIE("Cannot start sandbox; process is already multi-threaded"); return false; } } else if (seccomp_level == SeccompLevel::MULTI_THREADED) { if (IsSingleThreaded(proc_task_fd_)) { SANDBOX_DIE("Cannot start sandbox; " "process may be single-threaded when reported as not"); return false; } if (!supports_tsync) { SANDBOX_DIE("Cannot start sandbox; kernel does not support synchronizing " "filters for a threadgroup"); return false; } } // We no longer need access to any files in /proc. We want to do this // before installing the filters, just in case that our policy denies // close(). if (proc_task_fd_ >= 0) { if (IGNORE_EINTR(close(proc_task_fd_))) { SANDBOX_DIE("Failed to close file descriptor for /proc"); return false; } proc_task_fd_ = -1; } // Install the filters. InstallFilter(supports_tsync || seccomp_level == SeccompLevel::MULTI_THREADED); return true; } void SandboxBPF::set_proc_task_fd(int proc_task_fd) { proc_task_fd_ = proc_task_fd; } // static bool SandboxBPF::IsValidSyscallNumber(int sysnum) { return SyscallSet::IsValid(sysnum); } // static bool SandboxBPF::IsRequiredForUnsafeTrap(int sysno) { return bpf_dsl::PolicyCompiler::IsRequiredForUnsafeTrap(sysno); } // static intptr_t SandboxBPF::ForwardSyscall(const struct arch_seccomp_data& args) { return Syscall::Call( args.nr, static_cast<intptr_t>(args.args[0]), static_cast<intptr_t>(args.args[1]), static_cast<intptr_t>(args.args[2]), static_cast<intptr_t>(args.args[3]), static_cast<intptr_t>(args.args[4]), static_cast<intptr_t>(args.args[5])); } scoped_ptr<CodeGen::Program> SandboxBPF::AssembleFilter( bool force_verification) { #if !defined(NDEBUG) force_verification = true; #endif bpf_dsl::PolicyCompiler compiler(policy_.get(), Trap::Registry()); scoped_ptr<CodeGen::Program> program = compiler.Compile(); // Make sure compilation resulted in a BPF program that executes // correctly. Otherwise, there is an internal error in our BPF compiler. // There is really nothing the caller can do until the bug is fixed. if (force_verification) { // Verification is expensive. We only perform this step, if we are // compiled in debug mode, or if the caller explicitly requested // verification. const char* err = NULL; if (!Verifier::VerifyBPF(&compiler, *program, *policy_, &err)) { bpf_dsl::DumpBPF::PrintProgram(*program); SANDBOX_DIE(err); } } return program.Pass(); } void SandboxBPF::InstallFilter(bool must_sync_threads) { // We want to be very careful in not imposing any requirements on the // policies that are set with SetSandboxPolicy(). This means, as soon as // the sandbox is active, we shouldn't be relying on libraries that could // be making system calls. This, for example, means we should avoid // using the heap and we should avoid using STL functions. // Temporarily copy the contents of the "program" vector into a // stack-allocated array; and then explicitly destroy that object. // This makes sure we don't ex- or implicitly call new/delete after we // installed the BPF filter program in the kernel. Depending on the // system memory allocator that is in effect, these operators can result // in system calls to things like munmap() or brk(). CodeGen::Program* program = AssembleFilter(false).release(); struct sock_filter bpf[program->size()]; const struct sock_fprog prog = {static_cast<unsigned short>(program->size()), bpf}; memcpy(bpf, &(*program)[0], sizeof(bpf)); delete program; // Make an attempt to release memory that is no longer needed here, rather // than in the destructor. Try to avoid as much as possible to presume of // what will be possible to do in the new (sandboxed) execution environment. policy_.reset(); if (prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0)) { SANDBOX_DIE("Kernel refuses to enable no-new-privs"); } // Install BPF filter program. If the thread state indicates multi-threading // support, then the kernel hass the seccomp system call. Otherwise, fall // back on prctl, which requires the process to be single-threaded. if (must_sync_threads) { int rv = sys_seccomp(SECCOMP_SET_MODE_FILTER, SECCOMP_FILTER_FLAG_TSYNC, &prog); if (rv) { SANDBOX_DIE( "Kernel refuses to turn on and synchronize threads for BPF filters"); } } else { if (prctl(PR_SET_SECCOMP, SECCOMP_MODE_FILTER, &prog)) { SANDBOX_DIE("Kernel refuses to turn on BPF filters"); } } sandbox_has_started_ = true; } } // namespace sandbox <commit_msg>Linux sandbox: do not detect seccomp on Valgrind.<commit_after>// 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 "sandbox/linux/seccomp-bpf/sandbox_bpf.h" // Some headers on Android are missing cdefs: crbug.com/172337. // (We can't use OS_ANDROID here since build_config.h is not included). #if defined(ANDROID) #include <sys/cdefs.h> #endif #include <errno.h> #include <linux/filter.h> #include <sys/prctl.h> #include <sys/types.h> #include <unistd.h> #include "base/compiler_specific.h" #include "base/logging.h" #include "base/macros.h" #include "base/memory/scoped_ptr.h" #include "base/posix/eintr_wrapper.h" #include "base/third_party/valgrind/valgrind.h" #include "sandbox/linux/bpf_dsl/dump_bpf.h" #include "sandbox/linux/bpf_dsl/policy.h" #include "sandbox/linux/bpf_dsl/policy_compiler.h" #include "sandbox/linux/seccomp-bpf/codegen.h" #include "sandbox/linux/seccomp-bpf/die.h" #include "sandbox/linux/seccomp-bpf/errorcode.h" #include "sandbox/linux/seccomp-bpf/linux_seccomp.h" #include "sandbox/linux/seccomp-bpf/syscall.h" #include "sandbox/linux/seccomp-bpf/syscall_iterator.h" #include "sandbox/linux/seccomp-bpf/trap.h" #include "sandbox/linux/seccomp-bpf/verifier.h" #include "sandbox/linux/services/linux_syscalls.h" #include "sandbox/linux/services/syscall_wrappers.h" #include "sandbox/linux/services/thread_helpers.h" namespace sandbox { namespace { bool IsRunningOnValgrind() { return RUNNING_ON_VALGRIND; } bool IsSingleThreaded(int proc_task_fd) { return ThreadHelpers::IsSingleThreaded(proc_task_fd); } // Check if the kernel supports seccomp-filter (a.k.a. seccomp mode 2) via // prctl(). bool KernelSupportsSeccompBPF() { errno = 0; const int rv = prctl(PR_SET_SECCOMP, SECCOMP_MODE_FILTER, nullptr); if (rv == -1 && EFAULT == errno) { return true; } return false; } // Check if the kernel supports seccomp-filter via the seccomp system call // and the TSYNC feature to enable seccomp on all threads. bool KernelSupportsSeccompTsync() { errno = 0; const int rv = sys_seccomp(SECCOMP_SET_MODE_FILTER, SECCOMP_FILTER_FLAG_TSYNC, nullptr); if (rv == -1 && errno == EFAULT) { return true; } else { // TODO(jln): turn these into DCHECK after 417888 is considered fixed. CHECK_EQ(-1, rv); CHECK(ENOSYS == errno || EINVAL == errno); return false; } } } // namespace SandboxBPF::SandboxBPF() : proc_task_fd_(-1), sandbox_has_started_(false), policy_() { } SandboxBPF::~SandboxBPF() { if (proc_task_fd_ != -1) IGNORE_EINTR(close(proc_task_fd_)); } // static bool SandboxBPF::SupportsSeccompSandbox(SeccompLevel level) { // Never pretend to support seccomp with Valgrind, as it // throws the tool off. if (IsRunningOnValgrind()) { return false; } switch (level) { case SeccompLevel::SINGLE_THREADED: return KernelSupportsSeccompBPF(); case SeccompLevel::MULTI_THREADED: return KernelSupportsSeccompTsync(); } NOTREACHED(); return false; } // Don't take a scoped_ptr here, polymorphism makes their use awkward. void SandboxBPF::SetSandboxPolicy(bpf_dsl::Policy* policy) { DCHECK(!policy_); if (sandbox_has_started_) { SANDBOX_DIE("Cannot change policy after sandbox has started"); } policy_.reset(policy); } bool SandboxBPF::StartSandbox(SeccompLevel seccomp_level) { CHECK(seccomp_level == SeccompLevel::SINGLE_THREADED || seccomp_level == SeccompLevel::MULTI_THREADED); if (sandbox_has_started_) { SANDBOX_DIE( "Cannot repeatedly start sandbox. Create a separate Sandbox " "object instead."); return false; } const bool supports_tsync = KernelSupportsSeccompTsync(); if (seccomp_level == SeccompLevel::SINGLE_THREADED) { if (!IsSingleThreaded(proc_task_fd_)) { SANDBOX_DIE("Cannot start sandbox; process is already multi-threaded"); return false; } } else if (seccomp_level == SeccompLevel::MULTI_THREADED) { if (IsSingleThreaded(proc_task_fd_)) { SANDBOX_DIE("Cannot start sandbox; " "process may be single-threaded when reported as not"); return false; } if (!supports_tsync) { SANDBOX_DIE("Cannot start sandbox; kernel does not support synchronizing " "filters for a threadgroup"); return false; } } // We no longer need access to any files in /proc. We want to do this // before installing the filters, just in case that our policy denies // close(). if (proc_task_fd_ >= 0) { if (IGNORE_EINTR(close(proc_task_fd_))) { SANDBOX_DIE("Failed to close file descriptor for /proc"); return false; } proc_task_fd_ = -1; } // Install the filters. InstallFilter(supports_tsync || seccomp_level == SeccompLevel::MULTI_THREADED); return true; } void SandboxBPF::set_proc_task_fd(int proc_task_fd) { proc_task_fd_ = proc_task_fd; } // static bool SandboxBPF::IsValidSyscallNumber(int sysnum) { return SyscallSet::IsValid(sysnum); } // static bool SandboxBPF::IsRequiredForUnsafeTrap(int sysno) { return bpf_dsl::PolicyCompiler::IsRequiredForUnsafeTrap(sysno); } // static intptr_t SandboxBPF::ForwardSyscall(const struct arch_seccomp_data& args) { return Syscall::Call( args.nr, static_cast<intptr_t>(args.args[0]), static_cast<intptr_t>(args.args[1]), static_cast<intptr_t>(args.args[2]), static_cast<intptr_t>(args.args[3]), static_cast<intptr_t>(args.args[4]), static_cast<intptr_t>(args.args[5])); } scoped_ptr<CodeGen::Program> SandboxBPF::AssembleFilter( bool force_verification) { #if !defined(NDEBUG) force_verification = true; #endif bpf_dsl::PolicyCompiler compiler(policy_.get(), Trap::Registry()); scoped_ptr<CodeGen::Program> program = compiler.Compile(); // Make sure compilation resulted in a BPF program that executes // correctly. Otherwise, there is an internal error in our BPF compiler. // There is really nothing the caller can do until the bug is fixed. if (force_verification) { // Verification is expensive. We only perform this step, if we are // compiled in debug mode, or if the caller explicitly requested // verification. const char* err = NULL; if (!Verifier::VerifyBPF(&compiler, *program, *policy_, &err)) { bpf_dsl::DumpBPF::PrintProgram(*program); SANDBOX_DIE(err); } } return program.Pass(); } void SandboxBPF::InstallFilter(bool must_sync_threads) { // We want to be very careful in not imposing any requirements on the // policies that are set with SetSandboxPolicy(). This means, as soon as // the sandbox is active, we shouldn't be relying on libraries that could // be making system calls. This, for example, means we should avoid // using the heap and we should avoid using STL functions. // Temporarily copy the contents of the "program" vector into a // stack-allocated array; and then explicitly destroy that object. // This makes sure we don't ex- or implicitly call new/delete after we // installed the BPF filter program in the kernel. Depending on the // system memory allocator that is in effect, these operators can result // in system calls to things like munmap() or brk(). CodeGen::Program* program = AssembleFilter(false).release(); struct sock_filter bpf[program->size()]; const struct sock_fprog prog = {static_cast<unsigned short>(program->size()), bpf}; memcpy(bpf, &(*program)[0], sizeof(bpf)); delete program; // Make an attempt to release memory that is no longer needed here, rather // than in the destructor. Try to avoid as much as possible to presume of // what will be possible to do in the new (sandboxed) execution environment. policy_.reset(); if (prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0)) { SANDBOX_DIE("Kernel refuses to enable no-new-privs"); } // Install BPF filter program. If the thread state indicates multi-threading // support, then the kernel hass the seccomp system call. Otherwise, fall // back on prctl, which requires the process to be single-threaded. if (must_sync_threads) { int rv = sys_seccomp(SECCOMP_SET_MODE_FILTER, SECCOMP_FILTER_FLAG_TSYNC, &prog); if (rv) { SANDBOX_DIE( "Kernel refuses to turn on and synchronize threads for BPF filters"); } } else { if (prctl(PR_SET_SECCOMP, SECCOMP_MODE_FILTER, &prog)) { SANDBOX_DIE("Kernel refuses to turn on BPF filters"); } } sandbox_has_started_ = true; } } // namespace sandbox <|endoftext|>
<commit_before>#pragma once #include <tudocomp/compressors/esp/HashArray.hpp> namespace tdc {namespace esp { template<typename Pred, typename Update> struct Updater { Pred pred; Update update; }; template<typename Pred, typename Update> inline Updater<Pred, Update> make_updater(Pred pred, Update update) { return Updater<Pred, Update> { pred, update, }; } template<typename ipd_t> class GrammarRules { static constexpr std::array<size_t, 2> default_key() { return {{ size_t(-1), size_t(-1) }}; } using a2_t = typename ipd_t::template Map<Array<2>, size_t>; a2_t n2; size_t counter = 1; size_t m_initial_counter = 1; public: GrammarRules(size_t counter_start): n2(0, Array<2>(default_key())), counter(counter_start + 1), m_initial_counter(counter_start + 1) {} inline size_t add(in_t v) { const size_t vs = v.size(); DCHECK(vs == 2 || vs == 3); auto updater = [&](size_t& v) { if (v == 0) { v = counter++; } }; if (vs == 2) { return n2.access(v, updater) - 1; } else { Array<2> between; between.m_data[0] = add(v.slice(0, 2)); between.m_data[1] = v[2]; return n2.access(between, updater) - 1; } } inline size_t rules_count() const { return counter - m_initial_counter; } inline size_t initial_counter() const { return m_initial_counter; } template<typename F> void for_all(F f) const { n2.for_all(f); } inline void clear() { auto discard = std::move(n2); } }; }} <commit_msg>remove<commit_after>#pragma once #include <tudocomp/compressors/esp/HashArray.hpp> namespace tdc {namespace esp { template<typename ipd_t> class GrammarRules { static constexpr std::array<size_t, 2> default_key() { return {{ size_t(-1), size_t(-1) }}; } using a2_t = typename ipd_t::template Map<Array<2>, size_t>; a2_t n2; size_t counter = 1; size_t m_initial_counter = 1; public: GrammarRules(size_t counter_start): n2(0, Array<2>(default_key())), counter(counter_start + 1), m_initial_counter(counter_start + 1) {} inline size_t add(in_t v) { const size_t vs = v.size(); DCHECK(vs == 2 || vs == 3); auto updater = [&](size_t& v) { if (v == 0) { v = counter++; } }; if (vs == 2) { return n2.access(v, updater) - 1; } else { Array<2> between; between.m_data[0] = add(v.slice(0, 2)); between.m_data[1] = v[2]; return n2.access(between, updater) - 1; } } inline size_t rules_count() const { return counter - m_initial_counter; } inline size_t initial_counter() const { return m_initial_counter; } template<typename F> void for_all(F f) const { n2.for_all(f); } inline void clear() { auto discard = std::move(n2); } }; }} <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: linerenderer.hxx,v $ * * $Revision: 1.7 $ * * last change: $Author: obo $ $Date: 2006-10-12 13:46:41 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * 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 * ************************************************************************/ #ifndef INCLUDED_BASEBMP_LINERENDERER_HXX #define INCLUDED_BASEBMP_LINERENDERER_HXX #ifndef _BGFX_POINT_B2IPOINT_HXX #include <basegfx/point/b2ipoint.hxx> #endif #include <vigra/diff2d.hxx> #include <vigra/iteratortraits.hxx> /* Scan-converting lines */ namespace basebmp { /** Render line with Bresenham This function renders the line given by rPt1 and rPt2 using the Bresenham algorithm with the specified color value. Make sure rPt1 and rPt1 are valid coordinates in the image given by begin and end, since no clipping takes place. @param aPt1 Start point of the line @param aPt2 End point of the line @param color Color value to render the line with @param begin left-top image iterator @param end right-bottom image iterator @param acc Image accessor @param bRoundTowardsPt2 Rounding mode to use. Giving false here results in line pixel tend towards pt1, i.e. when a pixel exactly hits the middle between two pixel, the pixel closer to pt1 will be chosen. Giving true here makes renderClippedLine() choose pt2 in those cases. */ template< class Iterator, class Accessor > void renderLine( const basegfx::B2IPoint& rPt1, const basegfx::B2IPoint& rPt2, typename Accessor::value_type color, Iterator begin, Accessor acc, bool bRoundTowardsPt2=false ) { // code inspired by Paul Heckbert's Digital Line Drawing // (Graphics Gems, Academic Press 1990) const sal_Int32 x1 = rPt1.getX(); const sal_Int32 x2 = rPt2.getX(); const sal_Int32 y1 = rPt1.getY(); const sal_Int32 y2 = rPt2.getY(); // TODO(E1): This might overflow sal_Int32 adx = x2 - x1; int sx = 1; if( adx < 0 ) { adx *= -1; sx = -1; } // TODO(E1): This might overflow sal_Int32 ady = y2 - y1; int sy = 1; if( ady < 0 ) { ady *= -1; sy = -1; } // TODO(P3): handle horizontal and vertical lines specially sal_Int32 xs = x1; sal_Int32 ys = y1; if( adx >= ady ) { // semi-horizontal line sal_Int32 rem = 2*ady - adx - !bRoundTowardsPt2; adx *= 2; ady *= 2; Iterator currIter( begin + vigra::Diff2D(0,ys) ); typename vigra::IteratorTraits<Iterator>::row_iterator rowIter( currIter.rowIterator() + xs ); while(true) { acc.set(color, rowIter); if( xs == x2 ) return; if( rem >= 0 ) { ys += sy; xs += sx; currIter.y += sy; rowIter = currIter.rowIterator() + xs; rem -= adx; } else { xs += sx; rowIter += sx; } rem += ady; } } else { // semi-vertical line sal_Int32 rem = 2*adx - ady - !bRoundTowardsPt2; adx *= 2; ady *= 2; Iterator currIter( begin + vigra::Diff2D(xs,0) ); typename vigra::IteratorTraits<Iterator>::column_iterator colIter( currIter.columnIterator() + ys ); while(true) { acc.set(color, colIter); if( ys == y2 ) return; if( rem >= 0 ) { xs += sx; ys += sy; currIter.x += sx; colIter = currIter.columnIterator() + ys; rem -= ady; } else { ys += sy; colIter += sy; } rem += adx; } } } } // namespace basebmp #endif /* INCLUDED_BASEBMP_LINERENDERER_HXX */ <commit_msg>INTEGRATION: CWS changefileheader (1.7.42); FILE MERGED 2008/04/01 15:00:51 thb 1.7.42.2: #i85898# Stripping all external header guards 2008/03/31 13:07:56 rt 1.7.42.1: #i87441# Change license header to LPGL v3.<commit_after>/************************************************************************* * * 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: linerenderer.hxx,v $ * $Revision: 1.8 $ * * 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. * ************************************************************************/ #ifndef INCLUDED_BASEBMP_LINERENDERER_HXX #define INCLUDED_BASEBMP_LINERENDERER_HXX #include <basegfx/point/b2ipoint.hxx> #include <vigra/diff2d.hxx> #include <vigra/iteratortraits.hxx> /* Scan-converting lines */ namespace basebmp { /** Render line with Bresenham This function renders the line given by rPt1 and rPt2 using the Bresenham algorithm with the specified color value. Make sure rPt1 and rPt1 are valid coordinates in the image given by begin and end, since no clipping takes place. @param aPt1 Start point of the line @param aPt2 End point of the line @param color Color value to render the line with @param begin left-top image iterator @param end right-bottom image iterator @param acc Image accessor @param bRoundTowardsPt2 Rounding mode to use. Giving false here results in line pixel tend towards pt1, i.e. when a pixel exactly hits the middle between two pixel, the pixel closer to pt1 will be chosen. Giving true here makes renderClippedLine() choose pt2 in those cases. */ template< class Iterator, class Accessor > void renderLine( const basegfx::B2IPoint& rPt1, const basegfx::B2IPoint& rPt2, typename Accessor::value_type color, Iterator begin, Accessor acc, bool bRoundTowardsPt2=false ) { // code inspired by Paul Heckbert's Digital Line Drawing // (Graphics Gems, Academic Press 1990) const sal_Int32 x1 = rPt1.getX(); const sal_Int32 x2 = rPt2.getX(); const sal_Int32 y1 = rPt1.getY(); const sal_Int32 y2 = rPt2.getY(); // TODO(E1): This might overflow sal_Int32 adx = x2 - x1; int sx = 1; if( adx < 0 ) { adx *= -1; sx = -1; } // TODO(E1): This might overflow sal_Int32 ady = y2 - y1; int sy = 1; if( ady < 0 ) { ady *= -1; sy = -1; } // TODO(P3): handle horizontal and vertical lines specially sal_Int32 xs = x1; sal_Int32 ys = y1; if( adx >= ady ) { // semi-horizontal line sal_Int32 rem = 2*ady - adx - !bRoundTowardsPt2; adx *= 2; ady *= 2; Iterator currIter( begin + vigra::Diff2D(0,ys) ); typename vigra::IteratorTraits<Iterator>::row_iterator rowIter( currIter.rowIterator() + xs ); while(true) { acc.set(color, rowIter); if( xs == x2 ) return; if( rem >= 0 ) { ys += sy; xs += sx; currIter.y += sy; rowIter = currIter.rowIterator() + xs; rem -= adx; } else { xs += sx; rowIter += sx; } rem += ady; } } else { // semi-vertical line sal_Int32 rem = 2*adx - ady - !bRoundTowardsPt2; adx *= 2; ady *= 2; Iterator currIter( begin + vigra::Diff2D(xs,0) ); typename vigra::IteratorTraits<Iterator>::column_iterator colIter( currIter.columnIterator() + ys ); while(true) { acc.set(color, colIter); if( ys == y2 ) return; if( rem >= 0 ) { xs += sx; ys += sy; currIter.x += sx; colIter = currIter.columnIterator() + ys; rem -= ady; } else { ys += sy; colIter += sy; } rem += adx; } } } } // namespace basebmp #endif /* INCLUDED_BASEBMP_LINERENDERER_HXX */ <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: ScriptImpl.hxx,v $ * * $Revision: 1.2 $ * * last change: $Author: rt $ $Date: 2005-09-09 02:30:55 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * 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 * ************************************************************************/ #ifndef _FRAMEWORK_SCRIPT_PROVIDER_FUNCTIONIMPL_HXX_ #define _FRAMEWORK_SCRIPT_PROVIDER_FUNCTIONIMPL_HXX_ #include <cppuhelper/implbase1.hxx> // helper for XInterface, XTypeProvider etc. #include <osl/mutex.hxx> #include <com/sun/star/lang/IllegalArgumentException.hpp> #include <com/sun/star/uno/RuntimeException.hpp> #include <com/sun/star/script/CannotConvertException.hpp> #include <com/sun/star/beans/XPropertySet.hpp> #include <com/sun/star/reflection/InvocationTargetException.hpp> #include <drafts/com/sun/star/script/framework/provider/XScript.hpp> #include <drafts/com/sun/star/script/framework/runtime/XScriptInvocation.hpp> namespace func_provider { // for simplification #define css ::com::sun::star #define dcsssf ::drafts::com::sun::star::script::framework class ScriptImpl : public ::cppu::WeakImplHelper1 < dcsssf::provider::XScript > { public: /************************************************************* ScriptImpl Constructor @param runtimeMgr which is a service that implement a XScriptInvocation @param scriptURI the received ScriptURI that needs to be resolve and invoked */ ScriptImpl( const css::uno::Reference< css::beans::XPropertySet > & scriptingContext, const css::uno::Reference< dcsssf::runtime::XScriptInvocation > & runtimeMgr, const ::rtl::OUString& scriptURI ) throw ( css::uno::RuntimeException ); /************************************************************* ScriptImpl Destructor */ ~ScriptImpl(); /************************************************************* Invoke @param aParams all parameters; pure, out params are undefined in sequence, i.e., the value has to be ignored by the callee @param aOutParamIndex out indices @param aOutParam out parameters @returns the value returned from the function being invoked @throws IllegalArgumentException if there is no matching script name @throws CannotConvertException if args do not match or cannot be converted the those of the invokee @throws InvocationTargetException if the running script throws an exception this information is captured and rethrown as this exception type. */ virtual css::uno::Any SAL_CALL invoke( const css::uno::Sequence< css::uno::Any > & aParams, css::uno::Sequence< sal_Int16 > & aOutParamIndex, css::uno::Sequence< css::uno::Any > & aOutParam ) throw ( css::lang::IllegalArgumentException, css::script::CannotConvertException, css::reflection::InvocationTargetException, css::uno::RuntimeException ); private: css::uno::Reference< css::beans::XPropertySet > m_XScriptingContext; css::uno::Reference < dcsssf::runtime::XScriptInvocation > m_RunTimeManager; ::rtl::OUString m_ScriptURI; /* copy ctor disabled, i.e. not defined */ ScriptImpl( const ScriptImpl& ); /* assignment disabled, i.e. not defined */ ScriptImpl& operator = ( const ScriptImpl& ); }; } // namespace func_provider #endif //_FRAMEWORK_SCRIPT_PROVIDER_FUNCTIONIMPL_HXX_ <commit_msg>INTEGRATION: CWS changefileheader (1.2.108); FILE MERGED 2008/03/31 13:36:01 rt 1.2.108.1: #i87441# Change license header to LPGL v3.<commit_after>/************************************************************************* * * 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: ScriptImpl.hxx,v $ * $Revision: 1.3 $ * * 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. * ************************************************************************/ #ifndef _FRAMEWORK_SCRIPT_PROVIDER_FUNCTIONIMPL_HXX_ #define _FRAMEWORK_SCRIPT_PROVIDER_FUNCTIONIMPL_HXX_ #include <cppuhelper/implbase1.hxx> // helper for XInterface, XTypeProvider etc. #include <osl/mutex.hxx> #include <com/sun/star/lang/IllegalArgumentException.hpp> #include <com/sun/star/uno/RuntimeException.hpp> #include <com/sun/star/script/CannotConvertException.hpp> #include <com/sun/star/beans/XPropertySet.hpp> #include <com/sun/star/reflection/InvocationTargetException.hpp> #include <drafts/com/sun/star/script/framework/provider/XScript.hpp> #include <drafts/com/sun/star/script/framework/runtime/XScriptInvocation.hpp> namespace func_provider { // for simplification #define css ::com::sun::star #define dcsssf ::drafts::com::sun::star::script::framework class ScriptImpl : public ::cppu::WeakImplHelper1 < dcsssf::provider::XScript > { public: /************************************************************* ScriptImpl Constructor @param runtimeMgr which is a service that implement a XScriptInvocation @param scriptURI the received ScriptURI that needs to be resolve and invoked */ ScriptImpl( const css::uno::Reference< css::beans::XPropertySet > & scriptingContext, const css::uno::Reference< dcsssf::runtime::XScriptInvocation > & runtimeMgr, const ::rtl::OUString& scriptURI ) throw ( css::uno::RuntimeException ); /************************************************************* ScriptImpl Destructor */ ~ScriptImpl(); /************************************************************* Invoke @param aParams all parameters; pure, out params are undefined in sequence, i.e., the value has to be ignored by the callee @param aOutParamIndex out indices @param aOutParam out parameters @returns the value returned from the function being invoked @throws IllegalArgumentException if there is no matching script name @throws CannotConvertException if args do not match or cannot be converted the those of the invokee @throws InvocationTargetException if the running script throws an exception this information is captured and rethrown as this exception type. */ virtual css::uno::Any SAL_CALL invoke( const css::uno::Sequence< css::uno::Any > & aParams, css::uno::Sequence< sal_Int16 > & aOutParamIndex, css::uno::Sequence< css::uno::Any > & aOutParam ) throw ( css::lang::IllegalArgumentException, css::script::CannotConvertException, css::reflection::InvocationTargetException, css::uno::RuntimeException ); private: css::uno::Reference< css::beans::XPropertySet > m_XScriptingContext; css::uno::Reference < dcsssf::runtime::XScriptInvocation > m_RunTimeManager; ::rtl::OUString m_ScriptURI; /* copy ctor disabled, i.e. not defined */ ScriptImpl( const ScriptImpl& ); /* assignment disabled, i.e. not defined */ ScriptImpl& operator = ( const ScriptImpl& ); }; } // namespace func_provider #endif //_FRAMEWORK_SCRIPT_PROVIDER_FUNCTIONIMPL_HXX_ <|endoftext|>
<commit_before>// Copyright 2014 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 "ui/wm/core/nested_accelerator_dispatcher.h" #include "base/memory/scoped_ptr.h" #include "base/run_loop.h" #include "ui/base/accelerators/accelerator.h" #include "ui/events/event.h" #include "ui/events/platform/platform_event_dispatcher.h" #include "ui/events/platform/platform_event_source.h" #include "ui/events/platform/scoped_event_dispatcher.h" #include "ui/wm/core/accelerator_filter.h" #include "ui/wm/core/nested_accelerator_delegate.h" #if defined(USE_X11) #include <X11/Xlib.h> #endif namespace wm { namespace { #if defined(USE_OZONE) bool IsKeyEvent(const base::NativeEvent& native_event) { const ui::KeyEvent* event = static_cast<const ui::KeyEvent*>(native_event); return event->IsKeyEvent(); } #elif defined(USE_X11) bool IsKeyEvent(const XEvent* xev) { return xev->type == KeyPress || xev->type == KeyRelease; } #else #error Unknown build platform: you should have either use_ozone or use_x11. #endif scoped_ptr<ui::ScopedEventDispatcher> OverrideDispatcher( ui::PlatformEventDispatcher* dispatcher) { ui::PlatformEventSource* source = ui::PlatformEventSource::GetInstance(); return source ? source->OverrideDispatcher(dispatcher) : scoped_ptr<ui::ScopedEventDispatcher>(); } } // namespace class NestedAcceleratorDispatcherLinux : public NestedAcceleratorDispatcher, public ui::PlatformEventDispatcher { public: explicit NestedAcceleratorDispatcherLinux(NestedAcceleratorDelegate* delegate) : NestedAcceleratorDispatcher(delegate), restore_dispatcher_(OverrideDispatcher(this)) {} virtual ~NestedAcceleratorDispatcherLinux() {} private: // AcceleratorDispatcher: virtual scoped_ptr<base::RunLoop> CreateRunLoop() override { return scoped_ptr<base::RunLoop>(new base::RunLoop()); } // ui::PlatformEventDispatcher: virtual bool CanDispatchEvent(const ui::PlatformEvent& event) override { return true; } virtual uint32_t DispatchEvent(const ui::PlatformEvent& event) override { if (IsKeyEvent(event)) { ui::KeyEvent key_event(event); ui::Accelerator accelerator = CreateAcceleratorFromKeyEvent(key_event); switch (delegate_->ProcessAccelerator(accelerator)) { case NestedAcceleratorDelegate::RESULT_PROCESS_LATER: #if defined(USE_X11) XPutBackEvent(event->xany.display, event); #else NOTIMPLEMENTED(); #endif return ui::POST_DISPATCH_NONE; case NestedAcceleratorDelegate::RESULT_PROCESSED: return ui::POST_DISPATCH_NONE; case NestedAcceleratorDelegate::RESULT_NOT_PROCESSED: break; } } ui::PlatformEventDispatcher* prev = *restore_dispatcher_; return prev ? prev->DispatchEvent(event) : ui::POST_DISPATCH_PERFORM_DEFAULT; } scoped_ptr<ui::ScopedEventDispatcher> restore_dispatcher_; DISALLOW_COPY_AND_ASSIGN(NestedAcceleratorDispatcherLinux); }; scoped_ptr<NestedAcceleratorDispatcher> NestedAcceleratorDispatcher::Create( NestedAcceleratorDelegate* delegate, base::MessagePumpDispatcher* nested_dispatcher) { return scoped_ptr<NestedAcceleratorDispatcher>( new NestedAcceleratorDispatcherLinux(delegate)); } } // namespace wm <commit_msg>Explicitly coerce PostDispatchAction to uint32_t in DispatchEvent()<commit_after>// Copyright 2014 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 "ui/wm/core/nested_accelerator_dispatcher.h" #include "base/memory/scoped_ptr.h" #include "base/run_loop.h" #include "ui/base/accelerators/accelerator.h" #include "ui/events/event.h" #include "ui/events/platform/platform_event_dispatcher.h" #include "ui/events/platform/platform_event_source.h" #include "ui/events/platform/scoped_event_dispatcher.h" #include "ui/wm/core/accelerator_filter.h" #include "ui/wm/core/nested_accelerator_delegate.h" #if defined(USE_X11) #include <X11/Xlib.h> #endif namespace wm { namespace { #if defined(USE_OZONE) bool IsKeyEvent(const base::NativeEvent& native_event) { const ui::KeyEvent* event = static_cast<const ui::KeyEvent*>(native_event); return event->IsKeyEvent(); } #elif defined(USE_X11) bool IsKeyEvent(const XEvent* xev) { return xev->type == KeyPress || xev->type == KeyRelease; } #else #error Unknown build platform: you should have either use_ozone or use_x11. #endif scoped_ptr<ui::ScopedEventDispatcher> OverrideDispatcher( ui::PlatformEventDispatcher* dispatcher) { ui::PlatformEventSource* source = ui::PlatformEventSource::GetInstance(); return source ? source->OverrideDispatcher(dispatcher) : scoped_ptr<ui::ScopedEventDispatcher>(); } } // namespace class NestedAcceleratorDispatcherLinux : public NestedAcceleratorDispatcher, public ui::PlatformEventDispatcher { public: explicit NestedAcceleratorDispatcherLinux(NestedAcceleratorDelegate* delegate) : NestedAcceleratorDispatcher(delegate), restore_dispatcher_(OverrideDispatcher(this)) {} virtual ~NestedAcceleratorDispatcherLinux() {} private: // AcceleratorDispatcher: virtual scoped_ptr<base::RunLoop> CreateRunLoop() override { return scoped_ptr<base::RunLoop>(new base::RunLoop()); } // ui::PlatformEventDispatcher: virtual bool CanDispatchEvent(const ui::PlatformEvent& event) override { return true; } virtual uint32_t DispatchEvent(const ui::PlatformEvent& event) override { if (IsKeyEvent(event)) { ui::KeyEvent key_event(event); ui::Accelerator accelerator = CreateAcceleratorFromKeyEvent(key_event); switch (delegate_->ProcessAccelerator(accelerator)) { case NestedAcceleratorDelegate::RESULT_PROCESS_LATER: #if defined(USE_X11) XPutBackEvent(event->xany.display, event); #else NOTIMPLEMENTED(); #endif return ui::POST_DISPATCH_NONE; case NestedAcceleratorDelegate::RESULT_PROCESSED: return ui::POST_DISPATCH_NONE; case NestedAcceleratorDelegate::RESULT_NOT_PROCESSED: break; } } ui::PlatformEventDispatcher* prev = *restore_dispatcher_; uint32_t perform_default = ui::POST_DISPATCH_PERFORM_DEFAULT; return prev ? prev->DispatchEvent(event) : perform_default; } scoped_ptr<ui::ScopedEventDispatcher> restore_dispatcher_; DISALLOW_COPY_AND_ASSIGN(NestedAcceleratorDispatcherLinux); }; scoped_ptr<NestedAcceleratorDispatcher> NestedAcceleratorDispatcher::Create( NestedAcceleratorDelegate* delegate, base::MessagePumpDispatcher* nested_dispatcher) { return scoped_ptr<NestedAcceleratorDispatcher>( new NestedAcceleratorDispatcherLinux(delegate)); } } // namespace wm <|endoftext|>
<commit_before><commit_msg>Import: [skip ci] fixes #0003988: the function Import.readDXF doesn't import Bsplines<commit_after><|endoftext|>
<commit_before>//===--- MinGWToolChain.cpp - MinGWToolChain Implementation ---------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "ToolChains.h" #include "clang/Driver/Driver.h" #include "clang/Driver/Options.h" #include "llvm/Option/ArgList.h" #include "llvm/Support/FileSystem.h" #include "llvm/Support/Path.h" using namespace clang::diag; using namespace clang::driver; using namespace clang::driver::toolchains; using namespace clang; using namespace llvm::opt; namespace { // Simplified from Generic_GCC::GCCInstallationDetector::ScanLibDirForGCCTriple. bool findGccVersion(StringRef LibDir, std::string &GccLibDir, std::string &Ver) { Generic_GCC::GCCVersion Version = Generic_GCC::GCCVersion::Parse("0.0.0"); std::error_code EC; for (llvm::sys::fs::directory_iterator LI(LibDir, EC), LE; !EC && LI != LE; LI = LI.increment(EC)) { StringRef VersionText = llvm::sys::path::filename(LI->path()); Generic_GCC::GCCVersion CandidateVersion = Generic_GCC::GCCVersion::Parse(VersionText); if (CandidateVersion.Major == -1) continue; if (CandidateVersion <= Version) continue; Ver = VersionText; GccLibDir = LI->path(); } return Ver.size(); } } void MinGW::findGccLibDir() { llvm::SmallVector<llvm::SmallString<32>, 2> Archs; Archs.emplace_back(getTriple().getArchName()); Archs[0] += "-w64-mingw32"; Archs.emplace_back("mingw32"); Arch = Archs[0].str(); // lib: Arch Linux, Ubuntu, Windows // lib64: openSUSE Linux for (StringRef CandidateLib : {"lib", "lib64"}) { for (StringRef CandidateArch : Archs) { llvm::SmallString<1024> LibDir(Base); llvm::sys::path::append(LibDir, CandidateLib, "gcc", CandidateArch); if (findGccVersion(LibDir, GccLibDir, Ver)) { Arch = CandidateArch; return; } } } } MinGW::MinGW(const Driver &D, const llvm::Triple &Triple, const ArgList &Args) : ToolChain(D, Triple, Args) { getProgramPaths().push_back(getDriver().getInstalledDir()); // On Windows if there is no sysroot we search for gcc on the PATH. if (getDriver().SysRoot.size()) Base = getDriver().SysRoot; #ifdef LLVM_ON_WIN32 else if (llvm::ErrorOr<std::string> GPPName = llvm::sys::findProgramByName("gcc")) Base = llvm::sys::path::parent_path( llvm::sys::path::parent_path(GPPName.get())); #endif if (!Base.size()) Base = llvm::sys::path::parent_path(getDriver().getInstalledDir()); Base += llvm::sys::path::get_separator(); findGccLibDir(); // GccLibDir must precede Base/lib so that the // correct crtbegin.o ,cetend.o would be found. getFilePaths().push_back(GccLibDir); getFilePaths().push_back( (Base + Arch + llvm::sys::path::get_separator() + "lib").str()); getFilePaths().push_back(Base + "lib"); // openSUSE getFilePaths().push_back(Base + Arch + "/sys-root/mingw/lib"); } bool MinGW::IsIntegratedAssemblerDefault() const { return true; } Tool *MinGW::getTool(Action::ActionClass AC) const { switch (AC) { case Action::PreprocessJobClass: if (!Preprocessor) Preprocessor.reset(new tools::gcc::Preprocessor(*this)); return Preprocessor.get(); case Action::CompileJobClass: if (!Compiler) Compiler.reset(new tools::gcc::Compiler(*this)); return Compiler.get(); default: return ToolChain::getTool(AC); } } Tool *MinGW::buildAssembler() const { return new tools::MinGW::Assembler(*this); } Tool *MinGW::buildLinker() const { return new tools::MinGW::Linker(*this); } bool MinGW::IsUnwindTablesDefault() const { return getArch() == llvm::Triple::x86_64; } bool MinGW::isPICDefault() const { return getArch() == llvm::Triple::x86_64; } bool MinGW::isPIEDefault() const { return false; } bool MinGW::isPICDefaultForced() const { return getArch() == llvm::Triple::x86_64; } bool MinGW::UseSEHExceptions() const { return getArch() == llvm::Triple::x86_64; } // Include directories for various hosts: // Windows, mingw.org // c:\mingw\lib\gcc\mingw32\4.8.1\include\c++ // c:\mingw\lib\gcc\mingw32\4.8.1\include\c++\mingw32 // c:\mingw\lib\gcc\mingw32\4.8.1\include\c++\backward // c:\mingw\lib\gcc\mingw32\4.8.1\include // c:\mingw\include // c:\mingw\lib\gcc\mingw32\4.8.1\include-fixed // c:\mingw\mingw32\include // Windows, mingw-w64 mingw-builds // c:\mingw32\lib\gcc\i686-w64-mingw32\4.9.1\include // c:\mingw32\lib\gcc\i686-w64-mingw32\4.9.1\include-fixed // c:\mingw32\i686-w64-mingw32\include // c:\mingw32\i686-w64-mingw32\include\c++ // c:\mingw32\i686-w64-mingw32\include\c++\i686-w64-mingw32 // c:\mingw32\i686-w64-mingw32\include\c++\backward // Windows, mingw-w64 msys2 // c:\msys64\mingw32\lib\gcc\i686-w64-mingw32\4.9.2\include // c:\msys64\mingw32\include // c:\msys64\mingw32\lib\gcc\i686-w64-mingw32\4.9.2\include-fixed // c:\msys64\mingw32\i686-w64-mingw32\include // c:\msys64\mingw32\include\c++\4.9.2 // c:\msys64\mingw32\include\c++\4.9.2\i686-w64-mingw32 // c:\msys64\mingw32\include\c++\4.9.2\backward // openSUSE // /usr/lib64/gcc/x86_64-w64-mingw32/5.1.0/include/c++ // /usr/lib64/gcc/x86_64-w64-mingw32/5.1.0/include/c++/x86_64-w64-mingw32 // /usr/lib64/gcc/x86_64-w64-mingw32/5.1.0/include/c++/backward // /usr/lib64/gcc/x86_64-w64-mingw32/5.1.0/include // /usr/lib64/gcc/x86_64-w64-mingw32/5.1.0/include-fixed // /usr/x86_64-w64-mingw32/sys-root/mingw/include // Arch Linux // /usr/i686-w64-mingw32/include/c++/5.1.0 // /usr/i686-w64-mingw32/include/c++/5.1.0/i686-w64-mingw32 // /usr/i686-w64-mingw32/include/c++/5.1.0/backward // /usr/lib/gcc/i686-w64-mingw32/5.1.0/include // /usr/lib/gcc/i686-w64-mingw32/5.1.0/include-fixed // /usr/i686-w64-mingw32/include // Ubuntu // /usr/include/c++/4.8 // /usr/include/c++/4.8/x86_64-w64-mingw32 // /usr/include/c++/4.8/backward // /usr/lib/gcc/x86_64-w64-mingw32/4.8/include // /usr/lib/gcc/x86_64-w64-mingw32/4.8/include-fixed // /usr/x86_64-w64-mingw32/include void MinGW::AddClangSystemIncludeArgs(const ArgList &DriverArgs, ArgStringList &CC1Args) const { if (DriverArgs.hasArg(options::OPT_nostdinc)) return; if (!DriverArgs.hasArg(options::OPT_nobuiltininc)) { SmallString<1024> P(getDriver().ResourceDir); llvm::sys::path::append(P, "include"); addSystemInclude(DriverArgs, CC1Args, P.str()); } if (DriverArgs.hasArg(options::OPT_nostdlibinc)) return; if (GetRuntimeLibType(DriverArgs) == ToolChain::RLT_Libgcc) { llvm::SmallString<1024> IncludeDir(GccLibDir); llvm::sys::path::append(IncludeDir, "include"); addSystemInclude(DriverArgs, CC1Args, IncludeDir.c_str()); IncludeDir += "-fixed"; // openSUSE addSystemInclude(DriverArgs, CC1Args, Base + Arch + "/sys-root/mingw/include"); addSystemInclude(DriverArgs, CC1Args, IncludeDir.c_str()); } addSystemInclude(DriverArgs, CC1Args, Base + Arch + llvm::sys::path::get_separator() + "include"); addSystemInclude(DriverArgs, CC1Args, Base + "include"); } void MinGW::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs, ArgStringList &CC1Args) const { if (DriverArgs.hasArg(options::OPT_nostdlibinc) || DriverArgs.hasArg(options::OPT_nostdincxx)) return; switch (GetCXXStdlibType(DriverArgs)) { case ToolChain::CST_Libcxx: addSystemInclude(DriverArgs, CC1Args, Base + "include" + llvm::sys::path::get_separator() + "c++" + llvm::sys::path::get_separator() + "v1"); break; case ToolChain::CST_Libstdcxx: llvm::SmallVector<llvm::SmallString<1024>, 4> CppIncludeBases; CppIncludeBases.emplace_back(Base); llvm::sys::path::append(CppIncludeBases[0], Arch, "include", "c++"); CppIncludeBases.emplace_back(Base); llvm::sys::path::append(CppIncludeBases[1], Arch, "include", "c++", Ver); CppIncludeBases.emplace_back(Base); llvm::sys::path::append(CppIncludeBases[2], "include", "c++", Ver); CppIncludeBases.emplace_back(GccLibDir); llvm::sys::path::append(CppIncludeBases[3], "include", "c++"); for (auto &CppIncludeBase : CppIncludeBases) { addSystemInclude(DriverArgs, CC1Args, CppIncludeBase); CppIncludeBase += llvm::sys::path::get_separator(); addSystemInclude(DriverArgs, CC1Args, CppIncludeBase + Arch); addSystemInclude(DriverArgs, CC1Args, CppIncludeBase + "backward"); } break; } } <commit_msg>Fix alignment of r253898<commit_after>//===--- MinGWToolChain.cpp - MinGWToolChain Implementation ---------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "ToolChains.h" #include "clang/Driver/Driver.h" #include "clang/Driver/Options.h" #include "llvm/Option/ArgList.h" #include "llvm/Support/FileSystem.h" #include "llvm/Support/Path.h" using namespace clang::diag; using namespace clang::driver; using namespace clang::driver::toolchains; using namespace clang; using namespace llvm::opt; namespace { // Simplified from Generic_GCC::GCCInstallationDetector::ScanLibDirForGCCTriple. bool findGccVersion(StringRef LibDir, std::string &GccLibDir, std::string &Ver) { Generic_GCC::GCCVersion Version = Generic_GCC::GCCVersion::Parse("0.0.0"); std::error_code EC; for (llvm::sys::fs::directory_iterator LI(LibDir, EC), LE; !EC && LI != LE; LI = LI.increment(EC)) { StringRef VersionText = llvm::sys::path::filename(LI->path()); Generic_GCC::GCCVersion CandidateVersion = Generic_GCC::GCCVersion::Parse(VersionText); if (CandidateVersion.Major == -1) continue; if (CandidateVersion <= Version) continue; Ver = VersionText; GccLibDir = LI->path(); } return Ver.size(); } } void MinGW::findGccLibDir() { llvm::SmallVector<llvm::SmallString<32>, 2> Archs; Archs.emplace_back(getTriple().getArchName()); Archs[0] += "-w64-mingw32"; Archs.emplace_back("mingw32"); Arch = Archs[0].str(); // lib: Arch Linux, Ubuntu, Windows // lib64: openSUSE Linux for (StringRef CandidateLib : {"lib", "lib64"}) { for (StringRef CandidateArch : Archs) { llvm::SmallString<1024> LibDir(Base); llvm::sys::path::append(LibDir, CandidateLib, "gcc", CandidateArch); if (findGccVersion(LibDir, GccLibDir, Ver)) { Arch = CandidateArch; return; } } } } MinGW::MinGW(const Driver &D, const llvm::Triple &Triple, const ArgList &Args) : ToolChain(D, Triple, Args) { getProgramPaths().push_back(getDriver().getInstalledDir()); // On Windows if there is no sysroot we search for gcc on the PATH. if (getDriver().SysRoot.size()) Base = getDriver().SysRoot; #ifdef LLVM_ON_WIN32 else if (llvm::ErrorOr<std::string> GPPName = llvm::sys::findProgramByName("gcc")) Base = llvm::sys::path::parent_path( llvm::sys::path::parent_path(GPPName.get())); #endif if (!Base.size()) Base = llvm::sys::path::parent_path(getDriver().getInstalledDir()); Base += llvm::sys::path::get_separator(); findGccLibDir(); // GccLibDir must precede Base/lib so that the // correct crtbegin.o ,cetend.o would be found. getFilePaths().push_back(GccLibDir); getFilePaths().push_back( (Base + Arch + llvm::sys::path::get_separator() + "lib").str()); getFilePaths().push_back(Base + "lib"); // openSUSE getFilePaths().push_back(Base + Arch + "/sys-root/mingw/lib"); } bool MinGW::IsIntegratedAssemblerDefault() const { return true; } Tool *MinGW::getTool(Action::ActionClass AC) const { switch (AC) { case Action::PreprocessJobClass: if (!Preprocessor) Preprocessor.reset(new tools::gcc::Preprocessor(*this)); return Preprocessor.get(); case Action::CompileJobClass: if (!Compiler) Compiler.reset(new tools::gcc::Compiler(*this)); return Compiler.get(); default: return ToolChain::getTool(AC); } } Tool *MinGW::buildAssembler() const { return new tools::MinGW::Assembler(*this); } Tool *MinGW::buildLinker() const { return new tools::MinGW::Linker(*this); } bool MinGW::IsUnwindTablesDefault() const { return getArch() == llvm::Triple::x86_64; } bool MinGW::isPICDefault() const { return getArch() == llvm::Triple::x86_64; } bool MinGW::isPIEDefault() const { return false; } bool MinGW::isPICDefaultForced() const { return getArch() == llvm::Triple::x86_64; } bool MinGW::UseSEHExceptions() const { return getArch() == llvm::Triple::x86_64; } // Include directories for various hosts: // Windows, mingw.org // c:\mingw\lib\gcc\mingw32\4.8.1\include\c++ // c:\mingw\lib\gcc\mingw32\4.8.1\include\c++\mingw32 // c:\mingw\lib\gcc\mingw32\4.8.1\include\c++\backward // c:\mingw\lib\gcc\mingw32\4.8.1\include // c:\mingw\include // c:\mingw\lib\gcc\mingw32\4.8.1\include-fixed // c:\mingw\mingw32\include // Windows, mingw-w64 mingw-builds // c:\mingw32\lib\gcc\i686-w64-mingw32\4.9.1\include // c:\mingw32\lib\gcc\i686-w64-mingw32\4.9.1\include-fixed // c:\mingw32\i686-w64-mingw32\include // c:\mingw32\i686-w64-mingw32\include\c++ // c:\mingw32\i686-w64-mingw32\include\c++\i686-w64-mingw32 // c:\mingw32\i686-w64-mingw32\include\c++\backward // Windows, mingw-w64 msys2 // c:\msys64\mingw32\lib\gcc\i686-w64-mingw32\4.9.2\include // c:\msys64\mingw32\include // c:\msys64\mingw32\lib\gcc\i686-w64-mingw32\4.9.2\include-fixed // c:\msys64\mingw32\i686-w64-mingw32\include // c:\msys64\mingw32\include\c++\4.9.2 // c:\msys64\mingw32\include\c++\4.9.2\i686-w64-mingw32 // c:\msys64\mingw32\include\c++\4.9.2\backward // openSUSE // /usr/lib64/gcc/x86_64-w64-mingw32/5.1.0/include/c++ // /usr/lib64/gcc/x86_64-w64-mingw32/5.1.0/include/c++/x86_64-w64-mingw32 // /usr/lib64/gcc/x86_64-w64-mingw32/5.1.0/include/c++/backward // /usr/lib64/gcc/x86_64-w64-mingw32/5.1.0/include // /usr/lib64/gcc/x86_64-w64-mingw32/5.1.0/include-fixed // /usr/x86_64-w64-mingw32/sys-root/mingw/include // Arch Linux // /usr/i686-w64-mingw32/include/c++/5.1.0 // /usr/i686-w64-mingw32/include/c++/5.1.0/i686-w64-mingw32 // /usr/i686-w64-mingw32/include/c++/5.1.0/backward // /usr/lib/gcc/i686-w64-mingw32/5.1.0/include // /usr/lib/gcc/i686-w64-mingw32/5.1.0/include-fixed // /usr/i686-w64-mingw32/include // Ubuntu // /usr/include/c++/4.8 // /usr/include/c++/4.8/x86_64-w64-mingw32 // /usr/include/c++/4.8/backward // /usr/lib/gcc/x86_64-w64-mingw32/4.8/include // /usr/lib/gcc/x86_64-w64-mingw32/4.8/include-fixed // /usr/x86_64-w64-mingw32/include void MinGW::AddClangSystemIncludeArgs(const ArgList &DriverArgs, ArgStringList &CC1Args) const { if (DriverArgs.hasArg(options::OPT_nostdinc)) return; if (!DriverArgs.hasArg(options::OPT_nobuiltininc)) { SmallString<1024> P(getDriver().ResourceDir); llvm::sys::path::append(P, "include"); addSystemInclude(DriverArgs, CC1Args, P.str()); } if (DriverArgs.hasArg(options::OPT_nostdlibinc)) return; if (GetRuntimeLibType(DriverArgs) == ToolChain::RLT_Libgcc) { llvm::SmallString<1024> IncludeDir(GccLibDir); llvm::sys::path::append(IncludeDir, "include"); addSystemInclude(DriverArgs, CC1Args, IncludeDir.c_str()); IncludeDir += "-fixed"; // openSUSE addSystemInclude(DriverArgs, CC1Args, Base + Arch + "/sys-root/mingw/include"); addSystemInclude(DriverArgs, CC1Args, IncludeDir.c_str()); } addSystemInclude(DriverArgs, CC1Args, Base + Arch + llvm::sys::path::get_separator() + "include"); addSystemInclude(DriverArgs, CC1Args, Base + "include"); } void MinGW::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs, ArgStringList &CC1Args) const { if (DriverArgs.hasArg(options::OPT_nostdlibinc) || DriverArgs.hasArg(options::OPT_nostdincxx)) return; switch (GetCXXStdlibType(DriverArgs)) { case ToolChain::CST_Libcxx: addSystemInclude(DriverArgs, CC1Args, Base + "include" + llvm::sys::path::get_separator() + "c++" + llvm::sys::path::get_separator() + "v1"); break; case ToolChain::CST_Libstdcxx: llvm::SmallVector<llvm::SmallString<1024>, 4> CppIncludeBases; CppIncludeBases.emplace_back(Base); llvm::sys::path::append(CppIncludeBases[0], Arch, "include", "c++"); CppIncludeBases.emplace_back(Base); llvm::sys::path::append(CppIncludeBases[1], Arch, "include", "c++", Ver); CppIncludeBases.emplace_back(Base); llvm::sys::path::append(CppIncludeBases[2], "include", "c++", Ver); CppIncludeBases.emplace_back(GccLibDir); llvm::sys::path::append(CppIncludeBases[3], "include", "c++"); for (auto &CppIncludeBase : CppIncludeBases) { addSystemInclude(DriverArgs, CC1Args, CppIncludeBase); CppIncludeBase += llvm::sys::path::get_separator(); addSystemInclude(DriverArgs, CC1Args, CppIncludeBase + Arch); addSystemInclude(DriverArgs, CC1Args, CppIncludeBase + "backward"); } break; } } <|endoftext|>
<commit_before>/////////////////////////////////////////////////////////////////////// // structs.cpp -- Compile struct Definitions // Date: Wed Dec 4 07:44:18 2013 /////////////////////////////////////////////////////////////////////// #include <stdlib.h> #include <unistd.h> #include <errno.h> #include <string.h> #include <assert.h> #include <iostream> #include <fstream> #include <sstream> #include <unordered_map> #include "config.hpp" #include "comp.hpp" #include "glue.hpp" static std::unordered_map<std::string,std::string> c_ada_map; bool use_preferred_type(unsigned size,bool is_unsigned,const std::string pref_type) { { auto pit = config.sys_types.info.find(pref_type); if ( pit != config.sys_types.info.end() ) { const s_config::s_sys_types::s_sys_type& stype = pit->second; if ( size == stype.size && is_unsigned == stype.is_unsigned ) return true; } } // Try for a basic type { auto pit = config.basic_types.a2cmap.find(pref_type); if ( pit == config.basic_types.a2cmap.end() ) return false; const std::string& c_name = pit->second; const s_config::s_basic_types::s_basic_type& btype = config.basic_types.info[c_name]; return btype.size == size; } } const std::string std_type(unsigned bytes,bool is_signed,unsigned array) { std::stringstream s; if ( !is_signed ) s << "u"; if ( bytes <= 1 ) { s << "char"; } else { bytes /= (array < 1 ? 1 : array); if ( bytes <= 1 ) { s << "char"; } else { s << "int" << bytes * 8; } } if ( array < 1 ) { s << "_t"; } else { s << "_array(0.." << array-1 << ")"; } return s.str(); } static void emit_struct(s_config::s_structs::s_struct& node) { std::fstream c, ads; int genset = node.genset; bool as_typedef = false; std::cout << "Genset "; std::cout.width(4); std::cout.fill('0'); std::cout << genset << " struct " << node.c_name << "\n"; if ( !gcc_open(c,node.genset) ) exit(2); for ( auto it=node.includes.begin(); it != node.includes.end(); ++it ) { const std::string& incl = *it; if ( incl[0] != '.' ) c << "#include <" << incl << ">\n"; else c << "#include \"" << incl << "\"\n"; } c.close(); if ( !gcc_precomplex(genset) ) exit(2); parser_reset(); yytarget = node.c_name; yytarget_struct = 0; yyparse(); if ( yacc_dump ) std::cerr << "GOT STRUCT '" << yytarget << "' ID := " << yytarget_struct << "\n"; if ( yytarget_struct <= 0 ) { auto it = typedefs.find(yytarget); if ( it == typedefs.end() ) { std::cerr << "struct " << yytarget << " is unknown? (Genset " << genset << ")\n"; exit(3); } int nodeno = it->second; s_node& node = Get(nodeno); yytarget_struct = node.next; s_node& snode = Get(node.next); if ( snode.type != Struct ) { std::cerr << "struct " << yytarget << " is unknown? (Genset " << genset << ")\n"; exit(3); } as_typedef = true; // Do not name this as struct <whatever> if ( yacc_dump ) { std::cerr << "Found defn of " << yytarget << " as node " << nodeno << "\n"; dump(nodeno,yytarget.c_str()); } } if ( !gcc_open(c,++genset) ) exit(2); c << "#include <stdio.h>\n" << "#include <stdlib.h>\n" << "#include <string.h>\n"; std::unordered_map<std::string,std::string> typemap; for ( auto it=node.includes.begin(); it != node.includes.end(); ++it ) { const std::string& incl = *it; if ( incl[0] != '.' ) c << "#include <" << incl << ">\n"; else c << "#include \"" << incl << "\"\n"; } c << "\n" << "#define offsetof(member) (unsigned) (((char*)&test_struct.member) - ((char*)&test_struct))\n" << "\n"; if ( !as_typedef ) c << "static struct " << yytarget << " test_struct;\n\n"; else c << "static " << yytarget << " test_struct;\n\n"; c << "int main(int argc,char **argv) {\n" << "\n" << "\tmemset(&test_struct,0xFF,sizeof test_struct);\n\n"; s_node& snode = Get(yytarget_struct); s_node& node2 = Get(snode.next); assert(node2.type == List); c << "\tprintf(\"%u\\n\",(unsigned)(sizeof(test_struct))" << ");\n"; for ( auto it=node2.list.begin(); it != node2.list.end(); ++it ) { s_node& znode = Get(*it); std::string member; unsigned ptr = 0; bool struct_member = znode.type == Struct; bool array_ref = false; switch ( znode.type ) { case Ident : member = lex_revsym(znode.symbol); ptr = znode.ptr; break; case ArrayRef : { s_node& anode = Get(znode.next); assert(anode.type == Ident); member = lex_revsym(anode.symbol); } array_ref = true; break; case Struct : { s_node& nnode = Get(znode.next); assert(nnode.type == Ident); member = lex_revsym(nnode.symbol); typemap[member] = lex_revsym(znode.symbol); ptr = znode.ptr; } break; case Type : // (lldb) p nnode // (s_node) $0 = { // type = ArrayRef // symbol = 0 // ltoken = 0 // ptr = 0 // list = size=0 {} // next = 652 // next2 = 653 // next3 = 0 // } { s_node& nnode = Get(znode.next); switch ( nnode.type ) { case Ident : member = lex_revsym(nnode.symbol); ptr = znode.ptr; break; case ArrayRef : { // (s_node) a1 = { // type = Ident // symbol = 1463 // ltoken = 0 // ptr = 0 // list = size=0 {} // next = 0 // next2 = 0 // next3 = 0 // } s_node& a1 = Get(nnode.next); assert(a1.type == Ident); member = lex_revsym(a1.symbol); } array_ref = true; break; default : assert(0); } } break; default : assert(0); } if ( node.is_struct.find(member) != node.is_struct.end() ) { struct_member = node.is_struct[member]; } if ( !array_ref ) { c << "\tprintf(\"" << member << "|%lu|" << int(struct_member) << "|%u|%u|0|" << ptr << "\\n\",\n" << "\t\t(unsigned long)sizeof test_struct." << member << ",\n" << "\t\toffsetof(" << member << "),\n"; if ( !struct_member ) c << "\t\ttest_struct." << member << " <= 0 ? 1 : 0);\n"; else c << "\t\t0);\n"; } else { c << "\tprintf(\"" << member << "|%lu|" << int(struct_member) << "|%u|%u|%u|0\\n\",\n" << "\t\t(unsigned long)sizeof test_struct." << member << ",\n" << "\t\toffsetof(" << member << "),\n"; if ( !struct_member ) c << "\t\ttest_struct." << member << " <= 0 ? 1 : 0,\n"; else c << "\t\t0,\n"; c << "\t\t(unsigned)((sizeof test_struct." << member << ") / " << "sizeof test_struct." << member << "[0]));\n"; } } c << "\n\treturn 0;\n}\n"; c.close(); if ( !gcc_compile(c,genset) ) exit(4); std::string recd; if ( getline(c,recd) ) { node.size = stoul(recd); while ( getline(c,recd) ) { std::vector<std::string> fields; parse(fields,recd); s_config::s_structs::s_member mem; mem.name = fields[0]; mem.a_name = to_ada_name(mem.name); mem.msize = stoul(fields[1]); mem.union_struct = stoi(fields[2]); mem.moffset = stoul(fields[3]); mem.msigned = bool(stoi(fields[4])); mem.array = stoi(fields[5]); mem.ptr = stoi(fields[6]); auto it = typemap.find(mem.name); if ( it != typemap.end() ) mem.tname = it->second; // Named type/struct/union else mem.tname = ""; node.members.push_back(mem); } } c.close(); ////////////////////////////////////////////////////////////// // Generate Ada Structure ////////////////////////////////////////////////////////////// if ( !gcc_open(ads,genset,".ads") ) exit(5); ads << "\n" << " type " << node.a_name << " is\n" << " record\n"; for ( auto it=node.members.begin(); it != node.members.end(); ++it ) { s_config::s_structs::s_member& member = *it; std::stringstream s; if ( node.is_struct.find(member.name) != node.is_struct.end() ) { member.union_struct = node.is_struct[member.name]; if ( member.tname == "" ) { member.tname = node.prefs[member.name]; } } s << member.a_name << " :"; std::string fmt_name = s.str(); ads << " "; ads.width(32); ads << std::left << fmt_name << " "; if ( !member.union_struct ) { std::string ada_type; auto mit = node.prefs.find(member.name); if ( mit != node.prefs.end() ) { const std::string& pref_type = mit->second; if ( use_preferred_type(member.msize,!member.msigned,pref_type) ) ada_type = pref_type; } if ( !member.ptr ) { if ( ada_type == "" ) ada_type = std_type(member.msize,member.msigned,member.array); } else { ada_type = "System.Address"; } ads << ada_type; } else { auto cit = c_ada_map.find(member.tname); // Lookup C name if ( cit != c_ada_map.end() ) ads << cit->second; // Known Ada name else if ( member.union_struct == 2 ) ads << member.tname; // Cheat from config.xml else ads << "s_" << member.tname; // Unknown } ads << ";\n"; } ads << " end record;\n\n" << " for " << node.a_name << "'Size use " << node.size << "*8;\n\n" << " for " << node.a_name << " use\n" << " record\n"; for ( auto it=node.members.begin(); it != node.members.end(); ++it ) { const s_config::s_structs::s_member& member = *it; std::stringstream s; s << member.a_name; std::string fmt_name = s.str(); ads << " "; ads.width(32); ads << std::left << fmt_name << " at " << member.moffset << " range 0.." << member.msize*8-1 << ";\n"; } ads << " end record;\n"; ads.close(); } void emit_structs() { for ( auto it=config.structs.structvec.begin(); it != config.structs.structvec.end(); ++it ) { s_config::s_structs::s_struct& node = *it; c_ada_map[node.c_name] = node.a_name; } for ( auto it=config.structs.structvec.begin(); it != config.structs.structvec.end(); ++it ) { s_config::s_structs::s_struct& node = *it; emit_struct(node); } } // End structs.cpp <commit_msg>Do not emit struct members with zero size<commit_after>/////////////////////////////////////////////////////////////////////// // structs.cpp -- Compile struct Definitions // Date: Wed Dec 4 07:44:18 2013 /////////////////////////////////////////////////////////////////////// #include <stdlib.h> #include <unistd.h> #include <errno.h> #include <string.h> #include <assert.h> #include <iostream> #include <fstream> #include <sstream> #include <unordered_map> #include "config.hpp" #include "comp.hpp" #include "glue.hpp" static std::unordered_map<std::string,std::string> c_ada_map; bool use_preferred_type(unsigned size,bool is_unsigned,const std::string pref_type) { { auto pit = config.sys_types.info.find(pref_type); if ( pit != config.sys_types.info.end() ) { const s_config::s_sys_types::s_sys_type& stype = pit->second; if ( size == stype.size && is_unsigned == stype.is_unsigned ) return true; } } // Try for a basic type { auto pit = config.basic_types.a2cmap.find(pref_type); if ( pit == config.basic_types.a2cmap.end() ) return false; const std::string& c_name = pit->second; const s_config::s_basic_types::s_basic_type& btype = config.basic_types.info[c_name]; return btype.size == size; } } const std::string std_type(unsigned bytes,bool is_signed,unsigned array) { std::stringstream s; if ( !is_signed ) s << "u"; if ( bytes <= 1 ) { s << "char"; } else { bytes /= (array < 1 ? 1 : array); if ( bytes <= 1 ) { s << "char"; } else { s << "int" << bytes * 8; } } if ( array < 1 ) { s << "_t"; } else { s << "_array(0.." << array-1 << ")"; } return s.str(); } static void emit_struct(s_config::s_structs::s_struct& node) { std::fstream c, ads; int genset = node.genset; bool as_typedef = false; std::cout << "Genset "; std::cout.width(4); std::cout.fill('0'); std::cout << genset << " struct " << node.c_name << "\n"; if ( !gcc_open(c,node.genset) ) exit(2); for ( auto it=node.includes.begin(); it != node.includes.end(); ++it ) { const std::string& incl = *it; if ( incl[0] != '.' ) c << "#include <" << incl << ">\n"; else c << "#include \"" << incl << "\"\n"; } c.close(); if ( !gcc_precomplex(genset) ) exit(2); parser_reset(); yytarget = node.c_name; yytarget_struct = 0; yyparse(); if ( yacc_dump ) std::cerr << "GOT STRUCT '" << yytarget << "' ID := " << yytarget_struct << "\n"; if ( yytarget_struct <= 0 ) { auto it = typedefs.find(yytarget); if ( it == typedefs.end() ) { std::cerr << "struct " << yytarget << " is unknown? (Genset " << genset << ")\n"; exit(3); } int nodeno = it->second; s_node& node = Get(nodeno); yytarget_struct = node.next; s_node& snode = Get(node.next); if ( snode.type != Struct ) { std::cerr << "struct " << yytarget << " is unknown? (Genset " << genset << ")\n"; exit(3); } as_typedef = true; // Do not name this as struct <whatever> if ( yacc_dump ) { std::cerr << "Found defn of " << yytarget << " as node " << nodeno << "\n"; dump(nodeno,yytarget.c_str()); } } if ( !gcc_open(c,++genset) ) exit(2); c << "#include <stdio.h>\n" << "#include <stdlib.h>\n" << "#include <string.h>\n"; std::unordered_map<std::string,std::string> typemap; for ( auto it=node.includes.begin(); it != node.includes.end(); ++it ) { const std::string& incl = *it; if ( incl[0] != '.' ) c << "#include <" << incl << ">\n"; else c << "#include \"" << incl << "\"\n"; } c << "\n" << "#define offsetof(member) (unsigned) (((char*)&test_struct.member) - ((char*)&test_struct))\n" << "\n"; if ( !as_typedef ) c << "static struct " << yytarget << " test_struct;\n\n"; else c << "static " << yytarget << " test_struct;\n\n"; c << "int main(int argc,char **argv) {\n" << "\n" << "\tmemset(&test_struct,0xFF,sizeof test_struct);\n\n"; s_node& snode = Get(yytarget_struct); s_node& node2 = Get(snode.next); assert(node2.type == List); c << "\tprintf(\"%u\\n\",(unsigned)(sizeof(test_struct))" << ");\n"; for ( auto it=node2.list.begin(); it != node2.list.end(); ++it ) { s_node& znode = Get(*it); std::string member; unsigned ptr = 0; bool struct_member = znode.type == Struct; bool array_ref = false; switch ( znode.type ) { case Ident : member = lex_revsym(znode.symbol); ptr = znode.ptr; break; case ArrayRef : { s_node& anode = Get(znode.next); assert(anode.type == Ident); member = lex_revsym(anode.symbol); } array_ref = true; break; case Struct : { s_node& nnode = Get(znode.next); assert(nnode.type == Ident); member = lex_revsym(nnode.symbol); typemap[member] = lex_revsym(znode.symbol); ptr = znode.ptr; } break; case Type : // (lldb) p nnode // (s_node) $0 = { // type = ArrayRef // symbol = 0 // ltoken = 0 // ptr = 0 // list = size=0 {} // next = 652 // next2 = 653 // next3 = 0 // } { s_node& nnode = Get(znode.next); switch ( nnode.type ) { case Ident : member = lex_revsym(nnode.symbol); ptr = znode.ptr; break; case ArrayRef : { // (s_node) a1 = { // type = Ident // symbol = 1463 // ltoken = 0 // ptr = 0 // list = size=0 {} // next = 0 // next2 = 0 // next3 = 0 // } s_node& a1 = Get(nnode.next); assert(a1.type == Ident); member = lex_revsym(a1.symbol); } array_ref = true; break; default : assert(0); } } break; default : assert(0); } if ( node.is_struct.find(member) != node.is_struct.end() ) { struct_member = node.is_struct[member]; } if ( !array_ref ) { c << "\tprintf(\"" << member << "|%lu|" << int(struct_member) << "|%u|%u|0|" << ptr << "|S\\n\",\n" << "\t\t(unsigned long)sizeof test_struct." << member << ",\n" << "\t\toffsetof(" << member << "),\n"; if ( !struct_member ) c << "\t\ttest_struct." << member << " <= 0 ? 1 : 0);\n"; else c << "\t\t0);\n"; } else { c << "\tprintf(\"" << member << "|%lu|" << int(struct_member) << "|%u|%u|%u|0|A\\n\",\n" << "\t\t(unsigned long)sizeof test_struct." << member << ",\n" << "\t\toffsetof(" << member << "),\n"; if ( !struct_member ) c << "\t\ttest_struct." << member << " <= 0 ? 1 : 0,\n"; else c << "\t\t0,\n"; c << "\t\t(unsigned)((sizeof test_struct." << member << ") / " << "sizeof test_struct." << member << "[0]));\n"; } } c << "\n\treturn 0;\n}\n"; c.close(); if ( !gcc_compile(c,genset) ) exit(4); std::string recd; if ( getline(c,recd) ) { node.size = stoul(recd); while ( getline(c,recd) ) { std::vector<std::string> fields; parse(fields,recd); s_config::s_structs::s_member mem; bool is_array = false; mem.name = fields[0]; mem.a_name = to_ada_name(mem.name); mem.msize = stoul(fields[1]); mem.union_struct = stoi(fields[2]); mem.moffset = stoul(fields[3]); mem.msigned = bool(stoi(fields[4])); mem.array = stoi(fields[5]); mem.ptr = stoi(fields[6]); is_array = fields[7] == "A"; auto it = typemap.find(mem.name); if ( it != typemap.end() ) mem.tname = it->second; // Named type/struct/union else mem.tname = ""; if ( !is_array || (is_array && mem.array > 0 ) ) node.members.push_back(mem); } } c.close(); ////////////////////////////////////////////////////////////// // Generate Ada Structure ////////////////////////////////////////////////////////////// if ( !gcc_open(ads,genset,".ads") ) exit(5); ads << "\n" << " type " << node.a_name << " is\n" << " record\n"; for ( auto it=node.members.begin(); it != node.members.end(); ++it ) { s_config::s_structs::s_member& member = *it; std::stringstream s; if ( node.is_struct.find(member.name) != node.is_struct.end() ) { member.union_struct = node.is_struct[member.name]; if ( member.tname == "" ) { member.tname = node.prefs[member.name]; } } s << member.a_name << " :"; std::string fmt_name = s.str(); ads << " "; ads.width(32); ads << std::left << fmt_name << " "; if ( !member.union_struct ) { std::string ada_type; auto mit = node.prefs.find(member.name); if ( mit != node.prefs.end() ) { const std::string& pref_type = mit->second; if ( use_preferred_type(member.msize,!member.msigned,pref_type) ) ada_type = pref_type; } if ( !member.ptr ) { if ( ada_type == "" ) ada_type = std_type(member.msize,member.msigned,member.array); } else { ada_type = "System.Address"; } ads << ada_type; } else { auto cit = c_ada_map.find(member.tname); // Lookup C name if ( cit != c_ada_map.end() ) ads << cit->second; // Known Ada name else if ( member.union_struct == 2 ) ads << member.tname; // Cheat from config.xml else ads << "s_" << member.tname; // Unknown } ads << ";\n"; } ads << " end record;\n\n" << " for " << node.a_name << "'Size use " << node.size << "*8;\n\n" << " for " << node.a_name << " use\n" << " record\n"; for ( auto it=node.members.begin(); it != node.members.end(); ++it ) { const s_config::s_structs::s_member& member = *it; std::stringstream s; s << member.a_name; std::string fmt_name = s.str(); ads << " "; ads.width(32); ads << std::left << fmt_name << " at " << member.moffset << " range 0.." << member.msize*8-1 << ";\n"; } ads << " end record;\n"; ads.close(); } void emit_structs() { for ( auto it=config.structs.structvec.begin(); it != config.structs.structvec.end(); ++it ) { s_config::s_structs::s_struct& node = *it; c_ada_map[node.c_name] = node.a_name; } for ( auto it=config.structs.structvec.begin(); it != config.structs.structvec.end(); ++it ) { s_config::s_structs::s_struct& node = *it; emit_struct(node); } } // End structs.cpp <|endoftext|>
<commit_before>//===-- DynamicLibrary.cpp - Runtime link/load libraries --------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file was developed by Reid Spencer and is distributed under the // University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This header file implements the operating system DynamicLibrary concept. // //===----------------------------------------------------------------------===// #include "llvm/System/DynamicLibrary.h" #include "llvm/Config/config.h" #include <map> // Collection of symbol name/value pairs to be searched prior to any libraries. static std::map<std::string, void *> g_symbols; void llvm::sys::DynamicLibrary::AddSymbol(const char* symbolName, void *symbolValue) { g_symbols[symbolName] = symbolValue; } // It is not possible to use ltdl.c on VC++ builds as the terms of its LGPL // license and special exception would cause all of LLVM to be placed under // the LGPL. This is because the exception applies only when libtool is // used, and obviously libtool is not used with Visual Studio. An entirely // separate implementation is provided in win32/DynamicLibrary.cpp. #ifdef LLVM_ON_WIN32 #include "Win32/DynamicLibrary.inc" #else #include "ltdl.h" #include <cassert> using namespace llvm; using namespace llvm::sys; //===----------------------------------------------------------------------===// //=== WARNING: Implementation here must contain only TRULY operating system //=== independent code. //===----------------------------------------------------------------------===// static bool did_initialize_ltdl = false; static inline void check_ltdl_initialization() { if (!did_initialize_ltdl) { if (0 != lt_dlinit()) throw std::string(lt_dlerror()); did_initialize_ltdl = true; } } static std::vector<lt_dlhandle> OpenedHandles; DynamicLibrary::DynamicLibrary() : handle(0) { check_ltdl_initialization(); lt_dlhandle a_handle = lt_dlopen(0); if (a_handle == 0) throw std::string("Can't open program as dynamic library"); handle = a_handle; OpenedHandles.push_back(a_handle); } DynamicLibrary::DynamicLibrary(const char*filename) : handle(0) { check_ltdl_initialization(); lt_dlhandle a_handle = lt_dlopen(filename); if (a_handle == 0) a_handle = lt_dlopenext(filename); if (a_handle == 0) throw std::string("Can't open :") + filename + ": " + lt_dlerror(); handle = a_handle; OpenedHandles.push_back(a_handle); } DynamicLibrary::~DynamicLibrary() { lt_dlhandle a_handle = (lt_dlhandle) handle; if (a_handle) { lt_dlclose(a_handle); for (std::vector<lt_dlhandle>::iterator I = OpenedHandles.begin(), E = OpenedHandles.end(); I != E; ++I) { if (*I == a_handle) { // Note: don't use the swap/pop_back trick here. Order is important. OpenedHandles.erase(I); return; } } } } void DynamicLibrary::LoadLibraryPermanently(const char* filename) { check_ltdl_initialization(); lt_dlhandle a_handle = lt_dlopen(filename); if (a_handle == 0) a_handle = lt_dlopenext(filename); if (a_handle == 0) throw std::string("Can't open :") + filename + ": " + lt_dlerror(); lt_dlmakeresident(a_handle); OpenedHandles.push_back(a_handle); } void* DynamicLibrary::SearchForAddressOfSymbol(const char* symbolName) { check_ltdl_initialization(); // First check symbols added via AddSymbol(). std::map<std::string, void *>::iterator I = g_symbols.find(symbolName); if (I != g_symbols.end()) return I->second; // Now search the libraries. for (std::vector<lt_dlhandle>::iterator I = OpenedHandles.begin(), E = OpenedHandles.end(); I != E; ++I) { lt_ptr ptr = lt_dlsym(*I, symbolName); if (ptr) return ptr; } // If this is darwin, it has some funky issues, try to solve them here. Some // important symbols are marked 'private external' which doesn't allow // SearchForAddressOfSymbol to find them. As such, we special case them here, // there is only a small handful of them. #ifdef __APPLE__ { #define EXPLICIT_SYMBOL(SYM) \ extern void *SYM; if (!strcmp(symbolName, #SYM)) return &SYM EXPLICIT_SYMBOL(__ashldi3); EXPLICIT_SYMBOL(__ashrdi3); EXPLICIT_SYMBOL(__cmpdi2); EXPLICIT_SYMBOL(__divdi3); EXPLICIT_SYMBOL(__eprintf); EXPLICIT_SYMBOL(__fixdfdi); EXPLICIT_SYMBOL(__fixsfdi); EXPLICIT_SYMBOL(__fixunsdfdi); EXPLICIT_SYMBOL(__fixunssfdi); EXPLICIT_SYMBOL(__floatdidf); EXPLICIT_SYMBOL(__floatdisf); EXPLICIT_SYMBOL(__lshrdi3); EXPLICIT_SYMBOL(__moddi3); EXPLICIT_SYMBOL(__udivdi3); EXPLICIT_SYMBOL(__umoddi3); #undef EXPLICIT_SYMBOL } #endif return 0; } void *DynamicLibrary::GetAddressOfSymbol(const char *symbolName) { assert(handle != 0 && "Invalid DynamicLibrary handle"); return lt_dlsym((lt_dlhandle) handle, symbolName); } #endif // LLVM_ON_WIN32 <commit_msg>Bug noticed, by inspection. Filename can be null.<commit_after>//===-- DynamicLibrary.cpp - Runtime link/load libraries --------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file was developed by Reid Spencer and is distributed under the // University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This header file implements the operating system DynamicLibrary concept. // //===----------------------------------------------------------------------===// #include "llvm/System/DynamicLibrary.h" #include "llvm/Config/config.h" #include <map> // Collection of symbol name/value pairs to be searched prior to any libraries. static std::map<std::string, void *> g_symbols; void llvm::sys::DynamicLibrary::AddSymbol(const char* symbolName, void *symbolValue) { g_symbols[symbolName] = symbolValue; } // It is not possible to use ltdl.c on VC++ builds as the terms of its LGPL // license and special exception would cause all of LLVM to be placed under // the LGPL. This is because the exception applies only when libtool is // used, and obviously libtool is not used with Visual Studio. An entirely // separate implementation is provided in win32/DynamicLibrary.cpp. #ifdef LLVM_ON_WIN32 #include "Win32/DynamicLibrary.inc" #else #include "ltdl.h" #include <cassert> using namespace llvm; using namespace llvm::sys; //===----------------------------------------------------------------------===// //=== WARNING: Implementation here must contain only TRULY operating system //=== independent code. //===----------------------------------------------------------------------===// static bool did_initialize_ltdl = false; static inline void check_ltdl_initialization() { if (!did_initialize_ltdl) { if (0 != lt_dlinit()) throw std::string(lt_dlerror()); did_initialize_ltdl = true; } } static std::vector<lt_dlhandle> OpenedHandles; DynamicLibrary::DynamicLibrary() : handle(0) { check_ltdl_initialization(); lt_dlhandle a_handle = lt_dlopen(0); if (a_handle == 0) throw std::string("Can't open program as dynamic library"); handle = a_handle; OpenedHandles.push_back(a_handle); } DynamicLibrary::DynamicLibrary(const char*filename) : handle(0) { check_ltdl_initialization(); lt_dlhandle a_handle = lt_dlopen(filename); if (a_handle == 0) a_handle = lt_dlopenext(filename); if (a_handle == 0) throw std::string("Can't open :") + filename + ": " + lt_dlerror(); handle = a_handle; OpenedHandles.push_back(a_handle); } DynamicLibrary::~DynamicLibrary() { lt_dlhandle a_handle = (lt_dlhandle) handle; if (a_handle) { lt_dlclose(a_handle); for (std::vector<lt_dlhandle>::iterator I = OpenedHandles.begin(), E = OpenedHandles.end(); I != E; ++I) { if (*I == a_handle) { // Note: don't use the swap/pop_back trick here. Order is important. OpenedHandles.erase(I); return; } } } } void DynamicLibrary::LoadLibraryPermanently(const char* filename) { check_ltdl_initialization(); lt_dlhandle a_handle = lt_dlopen(filename); if (a_handle == 0) a_handle = lt_dlopenext(filename); if (a_handle == 0) throw std::string("Can't open :") + (filename ? filename : "<current process>") + ": " + lt_dlerror(); lt_dlmakeresident(a_handle); OpenedHandles.push_back(a_handle); } void* DynamicLibrary::SearchForAddressOfSymbol(const char* symbolName) { check_ltdl_initialization(); // First check symbols added via AddSymbol(). std::map<std::string, void *>::iterator I = g_symbols.find(symbolName); if (I != g_symbols.end()) return I->second; // Now search the libraries. for (std::vector<lt_dlhandle>::iterator I = OpenedHandles.begin(), E = OpenedHandles.end(); I != E; ++I) { lt_ptr ptr = lt_dlsym(*I, symbolName); if (ptr) return ptr; } // If this is darwin, it has some funky issues, try to solve them here. Some // important symbols are marked 'private external' which doesn't allow // SearchForAddressOfSymbol to find them. As such, we special case them here, // there is only a small handful of them. #ifdef __APPLE__ { #define EXPLICIT_SYMBOL(SYM) \ extern void *SYM; if (!strcmp(symbolName, #SYM)) return &SYM EXPLICIT_SYMBOL(__ashldi3); EXPLICIT_SYMBOL(__ashrdi3); EXPLICIT_SYMBOL(__cmpdi2); EXPLICIT_SYMBOL(__divdi3); EXPLICIT_SYMBOL(__eprintf); EXPLICIT_SYMBOL(__fixdfdi); EXPLICIT_SYMBOL(__fixsfdi); EXPLICIT_SYMBOL(__fixunsdfdi); EXPLICIT_SYMBOL(__fixunssfdi); EXPLICIT_SYMBOL(__floatdidf); EXPLICIT_SYMBOL(__floatdisf); EXPLICIT_SYMBOL(__lshrdi3); EXPLICIT_SYMBOL(__moddi3); EXPLICIT_SYMBOL(__udivdi3); EXPLICIT_SYMBOL(__umoddi3); #undef EXPLICIT_SYMBOL } #endif return 0; } void *DynamicLibrary::GetAddressOfSymbol(const char *symbolName) { assert(handle != 0 && "Invalid DynamicLibrary handle"); return lt_dlsym((lt_dlhandle) handle, symbolName); } #endif // LLVM_ON_WIN32 <|endoftext|>
<commit_before> /*========================================================================= Program: Visualization Toolkit Module: vtkDICOMImageReader.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 1993-2002 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 "vtkDICOMImageReader.h" #include "vtkImageData.h" #include "vtkObjectFactory.h" #include "vtkPointData.h" #include "vtkDirectory.h" #include "DICOMParser.h" #include "DICOMAppHelper.h" #include <vtkstd/vector> #include <vtkstd/string> vtkCxxRevisionMacro(vtkDICOMImageReader, "1.4"); vtkStandardNewMacro(vtkDICOMImageReader); class myvector : public vtkstd::vector<vtkstd::string> { }; vtkDICOMImageReader::vtkDICOMImageReader() { this->Parser = new DICOMParser(); this->AppHelper = new DICOMAppHelper(); this->DirectoryName = NULL; this->DICOMFileNames = new myvector(); } vtkDICOMImageReader::~vtkDICOMImageReader() { delete this->Parser; delete this->AppHelper; delete this->DICOMFileNames; } void vtkDICOMImageReader::PrintSelf(ostream& os, vtkIndent indent) { this->vtkImageReader2::PrintSelf(os, indent); } int vtkDICOMImageReader::CanReadFile(const char* fname) { bool canOpen = this->Parser->OpenFile((char*) fname); if (canOpen == false) { vtkErrorMacro("DICOMParser couldn't open : " << fname); return 0; } bool canRead = this->Parser->IsDICOMFile(); if (canRead == true) { return 1; } else { return 0; } } void vtkDICOMImageReader::ExecuteInformation() { if (this->FileName == NULL && this->DirectoryName == NULL) { return; } if (this->FileName) { this->DICOMFileNames->clear(); this->AppHelper->ClearSeriesUIDMap(); this->AppHelper->ClearSliceNumberMap(); this->Parser->ClearAllDICOMTagCallbacks(); this->Parser->OpenFile(this->FileName); this->AppHelper->SetFileName(this->FileName); this->AppHelper->RegisterCallbacks(this->Parser); this->Parser->ReadHeader(); this->SetupOutputInformation(1); } else if (this->DirectoryName) { vtkDirectory* dir = vtkDirectory::New(); int opened = dir->Open(this->DirectoryName); if (!opened) { vtkErrorMacro("Couldn't open " << this->DirectoryName); dir->Delete(); return; } int numFiles = dir->GetNumberOfFiles(); vtkDebugMacro( << "There are " << numFiles << " files in the directory."); this->DICOMFileNames->clear(); this->AppHelper->ClearSeriesUIDMap(); this->AppHelper->ClearSliceNumberMap(); for (int i = 0; i < numFiles; i++) { if (strcmp(dir->GetFile(i), ".") == 0 || strcmp(dir->GetFile(i), "..") == 0) { continue; } std::string temp = this->DirectoryName; std::string temp2 = dir->GetFile(i); std::string delim = "/"; std::string fileString = temp + delim + temp2; int val = this->CanReadFile(fileString.c_str()); if (val == 1) { vtkDebugMacro( << "Adding " << fileString.c_str() << " to DICOMFileNames."); this->DICOMFileNames->push_back(fileString); } else { vtkDebugMacro( << fileString.c_str() << " - DICOMParser CanReadFile returned : " << val); } } std::vector<std::string>::iterator iter; for (iter = this->DICOMFileNames->begin(); iter != this->DICOMFileNames->end(); iter++) { char* fn = (char*) (*iter).c_str(); vtkDebugMacro( << "Trying : " << fn); bool couldOpen = this->Parser->OpenFile(fn); if (!couldOpen) { dir->Delete(); return; } //HERE this->Parser->ClearAllDICOMTagCallbacks(); this->AppHelper->RegisterCallbacks(this->Parser); this->AppHelper->SetFileName(fn); this->Parser->ReadHeader(); vtkDebugMacro( << "File name : " << fn ); vtkDebugMacro( << "Slice number : " << this->AppHelper->GetSliceNumber()); } std::vector<std::pair<int, std::string> > sortedFiles; this->AppHelper->GetSliceNumberFilenamePairs(sortedFiles); this->SetupOutputInformation(sortedFiles.size()); //this->AppHelper->OutputSeries(); if (sortedFiles.size() > 0) { this->DICOMFileNames->clear(); std::vector<std::pair<int, std::string> >::iterator siter; for (siter = sortedFiles.begin(); siter != sortedFiles.end(); siter++) { vtkDebugMacro(<< "Sorted filename : " << (*siter).second.c_str()); vtkDebugMacro(<< "Adding file " << (*siter).second.c_str() << " at slice : " << (*siter).first); this->DICOMFileNames->push_back((*siter).second); } } else { vtkErrorMacro( << "Couldn't get sorted files. Slices may be in wrong order!"); } dir->Delete(); } } void vtkDICOMImageReader::ExecuteData(vtkDataObject *output) { vtkImageData *data = this->AllocateOutputData(output); data->GetPointData()->GetScalars()->SetName("DICOMImage"); if (this->FileName) { vtkDebugMacro( << "Single file : " << this->FileName); this->Parser->ClearAllDICOMTagCallbacks(); this->Parser->OpenFile(this->FileName); this->AppHelper->ClearSeriesUIDMap(); this->AppHelper->ClearSliceNumberMap(); this->AppHelper->SetFileName(this->FileName); this->AppHelper->RegisterCallbacks(this->Parser); this->AppHelper->RegisterPixelDataCallback(); this->Parser->ReadHeader(); void* imgData = NULL; DICOMParser::VRTypes dataType; unsigned long imageDataLength; this->AppHelper->GetImageData(imgData, dataType, imageDataLength); void* buffer = data->GetScalarPointer(); memcpy(buffer, imgData, imageDataLength); } else if (this->DICOMFileNames->size() > 0) { vtkDebugMacro( << "Multiple files (" << this->DICOMFileNames->size() << ")"); this->Parser->ClearAllDICOMTagCallbacks(); this->AppHelper->ClearSeriesUIDMap(); this->AppHelper->ClearSliceNumberMap(); this->AppHelper->RegisterCallbacks(this->Parser); this->AppHelper->RegisterPixelDataCallback(); void* buffer = data->GetScalarPointer(); std::vector<std::string>::iterator fiter; int count = 0; int numFiles = this->DICOMFileNames->size(); for (fiter = this->DICOMFileNames->begin(); fiter != this->DICOMFileNames->end(); fiter++) { count++; vtkDebugMacro( << "File : " << (*fiter).c_str()); this->Parser->OpenFile((char*)(*fiter).c_str()); this->AppHelper->SetFileName((char*)(*fiter).c_str()); this->Parser->ReadHeader(); void* imgData = NULL; DICOMParser::VRTypes dataType; unsigned long imageDataLengthInBytes; this->AppHelper->GetImageData(imgData, dataType, imageDataLengthInBytes); memcpy(buffer, imgData, imageDataLengthInBytes); buffer = ((char*) buffer) + imageDataLengthInBytes; this->UpdateProgress(float(count)/float(numFiles)); int len = strlen((char*) (*fiter).c_str()); char* filename = new char[len+1]; strcpy(filename, (char*) (*fiter).c_str()); this->SetProgressText(filename); } } else { vtkDebugMacro( << "Execute data -- no files!"); } } void vtkDICOMImageReader::SetupOutputInformation(int num_slices) { int width = this->AppHelper->GetWidth(); int height = this->AppHelper->GetHeight(); int bit_depth = this->AppHelper->GetBitsAllocated(); int num_comp = this->AppHelper->GetNumberOfComponents(); this->DataExtent[0] = 0; this->DataExtent[1] = width - 1; this->DataExtent[2] = 0; this->DataExtent[3] = height - 1; this->DataExtent[4] = 0; this->DataExtent[5] = num_slices - 1; bool isFloat = this->AppHelper->RescaledImageDataIsFloat(); bool sign = this->AppHelper->RescaledImageDataIsSigned(); if (isFloat) { this->SetDataScalarTypeToFloat(); } else if (bit_depth <= 8) { this->SetDataScalarTypeToUnsignedChar(); } else { if (sign) { this->SetDataScalarTypeToShort(); } else { this->SetDataScalarTypeToUnsignedShort(); } } this->SetNumberOfScalarComponents(num_comp); this->vtkImageReader2::ExecuteInformation(); } void vtkDICOMImageReader::SetDirectoryName(const char* dn) { if (dn == NULL) { return; } int len = strlen(dn); if (this->DirectoryName != NULL) { delete [] this->DirectoryName; } this->DirectoryName = new char[len+1]; strcpy(this->DirectoryName, dn); this->FileName = NULL; this->Modified(); } /* const char* vtkDICOMImageReader::GetDirectoryName() { return this->DirectoryName; } */ <commit_msg>Print ivars in PrintSelf<commit_after> /*========================================================================= Program: Visualization Toolkit Module: vtkDICOMImageReader.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 1993-2002 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 "vtkDICOMImageReader.h" #include "vtkImageData.h" #include "vtkObjectFactory.h" #include "vtkPointData.h" #include "vtkDirectory.h" #include "DICOMParser.h" #include "DICOMAppHelper.h" #include <vtkstd/vector> #include <vtkstd/string> vtkCxxRevisionMacro(vtkDICOMImageReader, "1.5"); vtkStandardNewMacro(vtkDICOMImageReader); class myvector : public vtkstd::vector<vtkstd::string> { }; vtkDICOMImageReader::vtkDICOMImageReader() { this->Parser = new DICOMParser(); this->AppHelper = new DICOMAppHelper(); this->DirectoryName = NULL; this->DICOMFileNames = new myvector(); } vtkDICOMImageReader::~vtkDICOMImageReader() { delete this->Parser; delete this->AppHelper; delete this->DICOMFileNames; } void vtkDICOMImageReader::PrintSelf(ostream& os, vtkIndent indent) { this->vtkImageReader2::PrintSelf(os, indent); if (this->DirectoryName) { os << "DirectoryName : " << this->DirectoryName << vtkstd::endl; } else { os << "DirectoryName : (NULL)" << vtkstd::endl; } if (this->FileName) { os << "FileName : " << this->FileName << vtkstd::endl; } else { os << "FileName : (NULL)" << vtkstd::endl; } } int vtkDICOMImageReader::CanReadFile(const char* fname) { bool canOpen = this->Parser->OpenFile((char*) fname); if (canOpen == false) { vtkErrorMacro("DICOMParser couldn't open : " << fname); return 0; } bool canRead = this->Parser->IsDICOMFile(); if (canRead == true) { return 1; } else { return 0; } } void vtkDICOMImageReader::ExecuteInformation() { if (this->FileName == NULL && this->DirectoryName == NULL) { return; } if (this->FileName) { this->DICOMFileNames->clear(); this->AppHelper->ClearSeriesUIDMap(); this->AppHelper->ClearSliceNumberMap(); this->Parser->ClearAllDICOMTagCallbacks(); this->Parser->OpenFile(this->FileName); this->AppHelper->SetFileName(this->FileName); this->AppHelper->RegisterCallbacks(this->Parser); this->Parser->ReadHeader(); this->SetupOutputInformation(1); } else if (this->DirectoryName) { vtkDirectory* dir = vtkDirectory::New(); int opened = dir->Open(this->DirectoryName); if (!opened) { vtkErrorMacro("Couldn't open " << this->DirectoryName); dir->Delete(); return; } int numFiles = dir->GetNumberOfFiles(); vtkDebugMacro( << "There are " << numFiles << " files in the directory."); this->DICOMFileNames->clear(); this->AppHelper->ClearSeriesUIDMap(); this->AppHelper->ClearSliceNumberMap(); for (int i = 0; i < numFiles; i++) { if (strcmp(dir->GetFile(i), ".") == 0 || strcmp(dir->GetFile(i), "..") == 0) { continue; } std::string temp = this->DirectoryName; std::string temp2 = dir->GetFile(i); std::string delim = "/"; std::string fileString = temp + delim + temp2; int val = this->CanReadFile(fileString.c_str()); if (val == 1) { vtkDebugMacro( << "Adding " << fileString.c_str() << " to DICOMFileNames."); this->DICOMFileNames->push_back(fileString); } else { vtkDebugMacro( << fileString.c_str() << " - DICOMParser CanReadFile returned : " << val); } } std::vector<std::string>::iterator iter; for (iter = this->DICOMFileNames->begin(); iter != this->DICOMFileNames->end(); iter++) { char* fn = (char*) (*iter).c_str(); vtkDebugMacro( << "Trying : " << fn); bool couldOpen = this->Parser->OpenFile(fn); if (!couldOpen) { dir->Delete(); return; } //HERE this->Parser->ClearAllDICOMTagCallbacks(); this->AppHelper->RegisterCallbacks(this->Parser); this->AppHelper->SetFileName(fn); this->Parser->ReadHeader(); vtkDebugMacro( << "File name : " << fn ); vtkDebugMacro( << "Slice number : " << this->AppHelper->GetSliceNumber()); } std::vector<std::pair<int, std::string> > sortedFiles; this->AppHelper->GetSliceNumberFilenamePairs(sortedFiles); this->SetupOutputInformation(sortedFiles.size()); //this->AppHelper->OutputSeries(); if (sortedFiles.size() > 0) { this->DICOMFileNames->clear(); std::vector<std::pair<int, std::string> >::iterator siter; for (siter = sortedFiles.begin(); siter != sortedFiles.end(); siter++) { vtkDebugMacro(<< "Sorted filename : " << (*siter).second.c_str()); vtkDebugMacro(<< "Adding file " << (*siter).second.c_str() << " at slice : " << (*siter).first); this->DICOMFileNames->push_back((*siter).second); } } else { vtkErrorMacro( << "Couldn't get sorted files. Slices may be in wrong order!"); } dir->Delete(); } } void vtkDICOMImageReader::ExecuteData(vtkDataObject *output) { vtkImageData *data = this->AllocateOutputData(output); data->GetPointData()->GetScalars()->SetName("DICOMImage"); if (this->FileName) { vtkDebugMacro( << "Single file : " << this->FileName); this->Parser->ClearAllDICOMTagCallbacks(); this->Parser->OpenFile(this->FileName); this->AppHelper->ClearSeriesUIDMap(); this->AppHelper->ClearSliceNumberMap(); this->AppHelper->SetFileName(this->FileName); this->AppHelper->RegisterCallbacks(this->Parser); this->AppHelper->RegisterPixelDataCallback(); this->Parser->ReadHeader(); void* imgData = NULL; DICOMParser::VRTypes dataType; unsigned long imageDataLength; this->AppHelper->GetImageData(imgData, dataType, imageDataLength); void* buffer = data->GetScalarPointer(); memcpy(buffer, imgData, imageDataLength); } else if (this->DICOMFileNames->size() > 0) { vtkDebugMacro( << "Multiple files (" << this->DICOMFileNames->size() << ")"); this->Parser->ClearAllDICOMTagCallbacks(); this->AppHelper->ClearSeriesUIDMap(); this->AppHelper->ClearSliceNumberMap(); this->AppHelper->RegisterCallbacks(this->Parser); this->AppHelper->RegisterPixelDataCallback(); void* buffer = data->GetScalarPointer(); std::vector<std::string>::iterator fiter; int count = 0; int numFiles = this->DICOMFileNames->size(); for (fiter = this->DICOMFileNames->begin(); fiter != this->DICOMFileNames->end(); fiter++) { count++; vtkDebugMacro( << "File : " << (*fiter).c_str()); this->Parser->OpenFile((char*)(*fiter).c_str()); this->AppHelper->SetFileName((char*)(*fiter).c_str()); this->Parser->ReadHeader(); void* imgData = NULL; DICOMParser::VRTypes dataType; unsigned long imageDataLengthInBytes; this->AppHelper->GetImageData(imgData, dataType, imageDataLengthInBytes); memcpy(buffer, imgData, imageDataLengthInBytes); buffer = ((char*) buffer) + imageDataLengthInBytes; this->UpdateProgress(float(count)/float(numFiles)); int len = strlen((char*) (*fiter).c_str()); char* filename = new char[len+1]; strcpy(filename, (char*) (*fiter).c_str()); this->SetProgressText(filename); } } else { vtkDebugMacro( << "Execute data -- no files!"); } } void vtkDICOMImageReader::SetupOutputInformation(int num_slices) { int width = this->AppHelper->GetWidth(); int height = this->AppHelper->GetHeight(); int bit_depth = this->AppHelper->GetBitsAllocated(); int num_comp = this->AppHelper->GetNumberOfComponents(); this->DataExtent[0] = 0; this->DataExtent[1] = width - 1; this->DataExtent[2] = 0; this->DataExtent[3] = height - 1; this->DataExtent[4] = 0; this->DataExtent[5] = num_slices - 1; bool isFloat = this->AppHelper->RescaledImageDataIsFloat(); bool sign = this->AppHelper->RescaledImageDataIsSigned(); if (isFloat) { this->SetDataScalarTypeToFloat(); } else if (bit_depth <= 8) { this->SetDataScalarTypeToUnsignedChar(); } else { if (sign) { this->SetDataScalarTypeToShort(); } else { this->SetDataScalarTypeToUnsignedShort(); } } this->SetNumberOfScalarComponents(num_comp); this->vtkImageReader2::ExecuteInformation(); } void vtkDICOMImageReader::SetDirectoryName(const char* dn) { if (dn == NULL) { return; } int len = strlen(dn); if (this->DirectoryName != NULL) { delete [] this->DirectoryName; } this->DirectoryName = new char[len+1]; strcpy(this->DirectoryName, dn); this->FileName = NULL; this->Modified(); } /* const char* vtkDICOMImageReader::GetDirectoryName() { return this->DirectoryName; } */ <|endoftext|>
<commit_before>name = "Pythia"; picture = "\@pythia\addons\pythia\logo.paa"; actionName = "Github"; action = "https://github.com/5sigmapoint2/arma-python-extension"; description = "Arma addon to use python"; logo = "\@pythia\addons\pythia\logo.paa"; logoOver = "\@pythia\addons\pythia\logo.paa"; tooltip = "Pythia"; tooltipOwned = "Pythia"; overview = "Arma addon to use python."; author = "Overfl0 & 5Sigma"; overviewPicture = "\@pythia\addons\pythia\logo.paa"; <commit_msg>Update the Github url in mod.cpp<commit_after>name = "Pythia"; picture = "\@pythia\addons\pythia\logo.paa"; actionName = "Github"; action = "https://github.com/overfl0/Pythia"; description = "Arma addon to use python"; logo = "\@pythia\addons\pythia\logo.paa"; logoOver = "\@pythia\addons\pythia\logo.paa"; tooltip = "Pythia"; tooltipOwned = "Pythia"; overview = "Arma addon to use python."; author = "Overfl0 & 5Sigma"; overviewPicture = "\@pythia\addons\pythia\logo.paa"; <|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */ /* * Copyright 2017 Couchbase, 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 <programs/engine_testapp/mock_server.h> #include <benchmark/benchmark.h> #include <engines/ep/src/bucket_logger.h> #include <logger/logger.h> #include "ep_time.h" static char allow_no_stats_env[] = "ALLOW_NO_STATS_UPDATE=yeah"; /** * main() function for ep_engine_benchmark. Sets up environment, then runs * all registered GoogleBenchmark benchmarks and GoogleTest tests. * * --gtest_filter and --benchmark_filter can be used to run a subset of * the tests / benchmarks. */ int main(int argc, char** argv) { putenv(allow_no_stats_env); cb::logger::createBlackholeLogger(); mock_init_alloc_hooks(); init_mock_server(); BucketLogger::setLoggerAPI(get_mock_server_api()->log); globalBucketLogger->set_level(spdlog::level::level_enum::critical); initialize_time_functions(get_mock_server_api()->core); ::benchmark::Initialize(&argc, argv); /* * Run the benchmarks. From benchmark.cc, 0 gets returned if * there is an error, else it returns the number of benchmark tests. * If we get a 0 return, then return 1 from main to signal an error * occurred. */ return ::benchmark::RunSpecifiedBenchmarks() == 0 ? 1 : 0; } <commit_msg>Shutdown globalBucketLogger at end of ep_engine_benchmarks<commit_after>/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */ /* * Copyright 2017 Couchbase, 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 <programs/engine_testapp/mock_server.h> #include <benchmark/benchmark.h> #include <engines/ep/src/bucket_logger.h> #include <logger/logger.h> #include "ep_time.h" static char allow_no_stats_env[] = "ALLOW_NO_STATS_UPDATE=yeah"; /** * main() function for ep_engine_benchmark. Sets up environment, then runs * all registered GoogleBenchmark benchmarks and GoogleTest tests. * * --gtest_filter and --benchmark_filter can be used to run a subset of * the tests / benchmarks. */ int main(int argc, char** argv) { putenv(allow_no_stats_env); cb::logger::createBlackholeLogger(); mock_init_alloc_hooks(); init_mock_server(); BucketLogger::setLoggerAPI(get_mock_server_api()->log); globalBucketLogger->set_level(spdlog::level::level_enum::critical); initialize_time_functions(get_mock_server_api()->core); ::benchmark::Initialize(&argc, argv); /* * Run the benchmarks. From benchmark.cc, 0 gets returned if * there is an error, else it returns the number of benchmark tests. * If we get a 0 return, then return 1 from main to signal an error * occurred. */ auto result = ::benchmark::RunSpecifiedBenchmarks(); globalBucketLogger.reset(); return result == 0 ? 1 : 0; } <|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */ /* * Copyright 2018 Couchbase, 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. */ /* * Benchmarks relating to the StatisticalCounter class. */ #include "statistical_counter.h" #include <benchmark/benchmark.h> #include <algorithm> #include <iostream> /** * Define the increment factor for the statisticalCounter being used for * the tests. 0.012 allows an 8-bit StatisticalCounter to mimic a uint16 * counter. */ static const double incFactor = 0.012; StatisticalCounter<uint8_t> statisticalCounter(incFactor); uint8_t counter{100}; // 100 is an arbitrary value between 0 and 255 static void BM_SaturateCounter(benchmark::State& state) { while (state.KeepRunning()) { // benchmark generateValue statisticalCounter.generateValue(counter); } } // Single-threaded version of the benchmark BENCHMARK(BM_SaturateCounter)->Threads(1); // Multi-threaded version of the benchmark BENCHMARK(BM_SaturateCounter)->Threads(8); <commit_msg>BM_SaturateCounter: Prevent generateValue from being optimized away<commit_after>/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */ /* * Copyright 2018 Couchbase, 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. */ /* * Benchmarks relating to the StatisticalCounter class. */ #include "statistical_counter.h" #include <benchmark/benchmark.h> #include <algorithm> #include <iostream> /** * Define the increment factor for the statisticalCounter being used for * the tests. 0.012 allows an 8-bit StatisticalCounter to mimic a uint16 * counter. */ static const double incFactor = 0.012; StatisticalCounter<uint8_t> statisticalCounter(incFactor); uint8_t counter{100}; // 100 is an arbitrary value between 0 and 255 static void BM_SaturateCounter(benchmark::State& state) { while (state.KeepRunning()) { // benchmark generateValue benchmark::DoNotOptimize(statisticalCounter.generateValue(counter)); } } // Single-threaded version of the benchmark BENCHMARK(BM_SaturateCounter)->Threads(1); // Multi-threaded version of the benchmark BENCHMARK(BM_SaturateCounter)->Threads(8); <|endoftext|>
<commit_before>#include "StorkApp.h" #include "MooseInit.h" #include "Moose.h" #include "MooseApp.h" #include "AppFactory.h" // Create a performance log PerfLog Moose::perf_log("Stork"); // Begin the main program. int main(int argc, char *argv[]) { // Initialize MPI, solvers and MOOSE MooseInit init(argc, argv); // Register this application's MooseApp and any it depends on StorkApp::registerApps(); // This creates dynamic memory that we're responsible for deleting MooseApp * app = AppFactory::createApp("StorkApp", argc, argv); // Execute the application app->run(); // Free up the memory we created earlier delete app; return 0; } <commit_msg>Small update to stork<commit_after>#include "StorkApp.h" #include "MooseInit.h" #include "Moose.h" #include "MooseApp.h" #include "AppFactory.h" // Create a performance log PerfLog Moose::perf_log("Stork"); // Begin the main program. int main(int argc, char *argv[]) { // Initialize MPI, solvers and MOOSE MooseInit init(argc, argv); // Register this application's MooseApp and any it depends on StorkApp::registerApps(); // This creates dynamic memory that we're responsible for deleting MooseApp * app = AppFactory::createApp("StorkApp", argc, argv); app->legacyUoInitializationDefault() = false; app->legacyUoAuxComputationDefault() = false; // Execute the application app->run(); // Free up the memory we created earlier delete app; return 0; } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: paralleltimecontainer.cxx,v $ * * $Revision: 1.4 $ * * last change: $Author: rt $ $Date: 2005-09-07 20:45:40 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * 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 <canvas/debug.hxx> #include <canvas/verbosetrace.hxx> #include <paralleltimecontainer.hxx> #include <tools.hxx> #include <nodetools.hxx> #ifndef BOOST_BIND_HPP_INCLUDED #include <boost/bind.hpp> #endif #ifndef BOOST_MEM_FN_HPP_INCLUDED #include <boost/mem_fn.hpp> #endif #include <algorithm> using namespace ::com::sun::star; namespace presentation { namespace internal { ParallelTimeContainer::ParallelTimeContainer( const uno::Reference< animations::XAnimationNode >& xNode, const BaseContainerNodeSharedPtr& rParent, const NodeContext& rContext ) : BaseContainerNode( xNode, rParent, rContext ) { } bool ParallelTimeContainer::activate() { if( getState() == ACTIVE ) return true; // avoid duplicate event generation if( !BaseContainerNode::activate() ) return false; // resolve all children, only return true, if _all_ // children were resolvable. return ::std::count_if( getChildren().begin(), getChildren().end(), ::boost::mem_fn(&AnimationNode::resolve) ) == static_cast<VectorOfNodes::difference_type>(getChildren().size()); } void ParallelTimeContainer::notifyDeactivating( const AnimationNodeSharedPtr& rNotifier ) { // early exit on invalid nodes if( getState() == INVALID ) return; // if we don't have indefinite duration, ignore this message if( !isDurationInfinite() ) return; // find given notifier in child vector const VectorOfNodes::const_iterator aBegin( getChildren().begin() ); const VectorOfNodes::const_iterator aEnd( getChildren().end() ); VectorOfNodes::const_iterator aIter; if( (aIter=::std::find( aBegin, aEnd, rNotifier )) == aEnd ) { OSL_ENSURE( false, "ParallelTimeContainer::notifyDeactivating(): unknown notifier" ); return; } const ::std::size_t nIndex( ::std::distance(aBegin, aIter) ); // prevent duplicate increments (for children that notify // more than once) if( getFinishedStates()[ nIndex ] == false ) ++getFinishedCount(); getFinishedStates()[ nIndex ] = true; // all children finished? if( getFinishedCount() == getChildren().size() ) { // yep. deactivate this node, too deactivate(); } } #if defined(VERBOSE) && defined(DBG_UTIL) const char* ParallelTimeContainer::getDescription() const { return "ParallelTimeContainer"; } #endif } } <commit_msg>INTEGRATION: CWS presfixes08 (1.3.16); FILE MERGED 2005/06/13 08:55:20 dbo 1.3.16.1: #i45197# skip effect event Issue number: Submitted by: Reviewed by:<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: paralleltimecontainer.cxx,v $ * * $Revision: 1.5 $ * * last change: $Author: obo $ $Date: 2005-10-11 08:44:01 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * 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 <canvas/debug.hxx> #include <canvas/verbosetrace.hxx> #include <paralleltimecontainer.hxx> #include <tools.hxx> #include <nodetools.hxx> #ifndef BOOST_BIND_HPP_INCLUDED #include <boost/bind.hpp> #endif #ifndef BOOST_MEM_FN_HPP_INCLUDED #include <boost/mem_fn.hpp> #endif #include <algorithm> using namespace ::com::sun::star; namespace presentation { namespace internal { ParallelTimeContainer::ParallelTimeContainer( const uno::Reference< animations::XAnimationNode >& xNode, const BaseContainerNodeSharedPtr& rParent, const NodeContext& rContext ) : BaseContainerNode( xNode, rParent, rContext ) { } bool ParallelTimeContainer::activate() { if( getState() == ACTIVE ) return true; // avoid duplicate event generation if( !BaseContainerNode::activate() ) return false; // resolve all children, only return true, if _all_ // children were resolvable. return ::std::count_if( getChildren().begin(), getChildren().end(), ::boost::mem_fn(&AnimationNode::resolve) ) == static_cast<VectorOfNodes::difference_type>(getChildren().size()); } void ParallelTimeContainer::notifyDeactivating( const AnimationNodeSharedPtr& rNotifier ) { // early exit on invalid nodes if( getState() == INVALID ) return; // if we don't have indefinite duration, ignore this message if( !isDurationInfinite() ) return; // find given notifier in child vector const VectorOfNodes::const_iterator aBegin( getChildren().begin() ); const VectorOfNodes::const_iterator aEnd( getChildren().end() ); VectorOfNodes::const_iterator aIter; if( (aIter=::std::find( aBegin, aEnd, rNotifier )) == aEnd ) { OSL_ENSURE( false, "ParallelTimeContainer::notifyDeactivating(): unknown notifier" ); return; } const ::std::size_t nIndex( ::std::distance(aBegin, aIter) ); // prevent duplicate increments (for children that notify // more than once) if( getFinishedStates()[ nIndex ] == false ) ++getFinishedCount(); getFinishedStates()[ nIndex ] = true; // all children finished? if( getFinishedCount() == getChildren().size() ) { // yep. deactivate this node, too deactivate(); } } #if defined(VERBOSE) && defined(DBG_UTIL) const char* ParallelTimeContainer::getDescription() const { return "ParallelTimeContainer"; } #endif } } <|endoftext|>
<commit_before>/** \file expand_DIN_ISO_3166_geographic_codes.cc * \author Dr Johannes Ruscheinski * * Converts codes stored in MARC field 044 and generates geographic fully-spelled-out * keyword chains in MARC field GEO */ /* Copyright (C) 2020, Library of the University of 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 <unordered_map> #include <cstdlib> #include "FileUtil.h" #include "MARC.h" #include "StringUtil.h" #include "UBTools.h" #include "util.h" namespace { void InitialiseCodesToKeywordChainsMap(std::unordered_map<std::string, std::string> * const codes_to_keyword_chains_map) { const auto MAP_FILENAME(UBTools::GetTuelibPath() + "DIN_ISO_3166_geographic_codes_in_German"); std::unordered_map<std::string, std::string> codes_to_keywords_map; unsigned line_no(0); constexpr char KEYWORD_SEPARATOR('/'); for (auto line : FileUtil::ReadLines(MAP_FILENAME)) { ++line_no; if (unlikely(line.empty())) continue; const auto FIRST_PIPE_POS(line.find('|')); auto keyword(line.substr(0, FIRST_PIPE_POS)); const auto codes(line.substr(FIRST_PIPE_POS + 1)); if (unlikely(keyword.empty() or codes.empty())) LOG_ERROR("malformed line #" + std::to_string(line_no) + " in \"" + MAP_FILENAME + "\"!"); codes_to_keywords_map[codes] = StringUtil::Map(&keyword, KEYWORD_SEPARATOR, ';'); // The mapping is probably unnecessary. } unsigned level(0); while (codes_to_keyword_chains_map->size() < codes_to_keywords_map.size()) { for (const auto &[codes, keyword] : codes_to_keywords_map) { if (StringUtil::CharCount(keyword, '-') != level) continue; if (level == 0) (*codes_to_keyword_chains_map)[codes] = keyword; else { const auto LAST_DASH_POS(codes.rfind('-')); const auto code_prefix(codes.substr(0, LAST_DASH_POS)); const auto code_and_keyword_prefix(codes_to_keyword_chains_map->find(code_prefix)); if (unlikely(code_and_keyword_prefix == codes_to_keyword_chains_map->end())) LOG_ERROR("code prefix \"" + code_prefix + "\" is missing!"); (*codes_to_keyword_chains_map)[codes] = code_and_keyword_prefix->second + std::string(1, KEYWORD_SEPARATOR) + keyword; } } ++level; } } void GenerateExpandedGeographicCodes(MARC::Reader * const reader, MARC::Writer * writer, const std::unordered_map<std::string, std::string> &codes_to_keyword_chains_map) { unsigned total_count(0), conversion_count(0); while (auto record = reader->read()) { ++total_count; const auto _044_field(record.findTag("044")); if (_044_field == record.end()) { writer->write(record); continue; } const auto codes(_044_field->getFirstSubfieldWithCode('c')); if (codes.empty()) { writer->write(record); continue; } const auto codes_and_keyword_chain(codes_to_keyword_chains_map.find(codes)); if (unlikely(codes_and_keyword_chain == codes_to_keyword_chains_map.cend())) LOG_ERROR("record w/ PPN " + record.getControlNumber() + " contains missing code \"" + codes + "\" in 044$c!"); record.insertField("GEO", 'a', codes_and_keyword_chain->second); ++conversion_count; writer->write(record); } LOG_INFO("Processed " + std::to_string(total_count) + " record(s) and converted " + std::to_string(conversion_count) + " codes to keyword chains."); } } // unnamed namespace int Main(int argc, char *argv[]) { if (argc != 3) ::Usage("marc_input marc_output"); std::unordered_map<std::string, std::string> codes_to_keyword_chains_map; InitialiseCodesToKeywordChainsMap(&codes_to_keyword_chains_map); const auto marc_reader(MARC::Reader::Factory(argv[1])); const auto marc_writer(MARC::Writer::Factory(argv[2])); GenerateExpandedGeographicCodes(marc_reader.get(), marc_writer.get(), codes_to_keyword_chains_map); return EXIT_SUCCESS; } <commit_msg>Fixed some bugs and improved the error reporting.<commit_after>/** \file expand_DIN_ISO_3166_geographic_codes.cc * \author Dr Johannes Ruscheinski * * Converts codes stored in MARC field 044 and generates geographic fully-spelled-out * keyword chains in MARC field GEO */ /* Copyright (C) 2020, Library of the University of 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 <unordered_map> #include <cstdlib> #include "FileUtil.h" #include "MARC.h" #include "StringUtil.h" #include "UBTools.h" #include "util.h" namespace { void InitialiseCodesToKeywordChainsMap(std::unordered_map<std::string, std::string> * const codes_to_keyword_chains_map) { const auto MAP_FILENAME(UBTools::GetTuelibPath() + "DIN_ISO_3166_geographic_codes_in_German"); std::unordered_map<std::string, std::string> codes_to_keywords_map; unsigned line_no(0); constexpr char KEYWORD_SEPARATOR('/'); for (auto line : FileUtil::ReadLines(MAP_FILENAME)) { ++line_no; if (unlikely(line.empty())) continue; const auto FIRST_PIPE_POS(line.find('|')); auto keyword(line.substr(0, FIRST_PIPE_POS)); const auto codes(line.substr(FIRST_PIPE_POS + 1)); if (unlikely(keyword.empty() or codes.empty())) LOG_ERROR("malformed line #" + std::to_string(line_no) + " in \"" + MAP_FILENAME + "\"!"); codes_to_keywords_map[codes] = StringUtil::Map(&keyword, KEYWORD_SEPARATOR, ';'); // The mapping is probably unnecessary. } LOG_INFO("Extracted " + std::to_string(codes_to_keywords_map.size()) + " mappings from \"" + MAP_FILENAME + "\"."); unsigned level(0); while (codes_to_keyword_chains_map->size() < codes_to_keywords_map.size()) { for (const auto &[codes, keyword] : codes_to_keywords_map) { if (StringUtil::CharCount(codes, '-') != level) continue; if (level == 0) (*codes_to_keyword_chains_map)[codes] = keyword; else { const auto LAST_DASH_POS(codes.rfind('-')); const auto code_prefix(codes.substr(0, LAST_DASH_POS)); const auto code_and_keyword_prefix(codes_to_keyword_chains_map->find(code_prefix)); if (unlikely(code_and_keyword_prefix == codes_to_keyword_chains_map->end())) LOG_ERROR("code prefix \"" + code_prefix + "\" needed for \"" + codes + "\" is missing!"); (*codes_to_keyword_chains_map)[codes] = code_and_keyword_prefix->second + std::string(1, KEYWORD_SEPARATOR) + keyword; } } ++level; } } void GenerateExpandedGeographicCodes(MARC::Reader * const reader, MARC::Writer * writer, const std::unordered_map<std::string, std::string> &codes_to_keyword_chains_map) { unsigned total_count(0), conversion_count(0); while (auto record = reader->read()) { ++total_count; const auto _044_field(record.findTag("044")); if (_044_field == record.end()) { writer->write(record); continue; } const auto codes(_044_field->getFirstSubfieldWithCode('c')); if (codes.empty()) { writer->write(record); continue; } const auto codes_and_keyword_chain(codes_to_keyword_chains_map.find(codes)); if (unlikely(codes_and_keyword_chain == codes_to_keyword_chains_map.cend())) LOG_WARNING("record w/ PPN " + record.getControlNumber() + " contains missing code \"" + codes + "\" in 044$c!"); record.insertField("GEO", 'a', codes_and_keyword_chain->second); ++conversion_count; writer->write(record); } LOG_INFO("Processed " + std::to_string(total_count) + " record(s) and converted " + std::to_string(conversion_count) + " codes to keyword chains."); } } // unnamed namespace int Main(int argc, char *argv[]) { if (argc != 3) ::Usage("marc_input marc_output"); std::unordered_map<std::string, std::string> codes_to_keyword_chains_map; InitialiseCodesToKeywordChainsMap(&codes_to_keyword_chains_map); const auto marc_reader(MARC::Reader::Factory(argv[1])); const auto marc_writer(MARC::Writer::Factory(argv[2])); GenerateExpandedGeographicCodes(marc_reader.get(), marc_writer.get(), codes_to_keyword_chains_map); return EXIT_SUCCESS; } <|endoftext|>
<commit_before>/* * Copyright (c) 2021 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. * */ /* * Copyright (C) 2017 The Android Open Source Project * * Modified by joogab yun([email protected]) */ // CLASS HEADER #include "focus-finder.h" // EXTERNAL INCLUDES #include <dali/devel-api/actors/actor-devel.h> #include <dali/integration-api/adaptor-framework/scene-holder.h> #include <dali/public-api/actors/layer.h> namespace Dali { namespace Toolkit { namespace FocusFinder { namespace { static constexpr float FULLY_TRANSPARENT(0.01f); ///< Alpha values must rise above this, before an object is considered to be visible. static int MajorAxisDistanceRaw(Dali::Toolkit::Control::KeyboardFocus::Direction direction, Dali::Rect<float> source, Dali::Rect<float> dest) { switch(direction) { case Dali::Toolkit::Control::KeyboardFocus::LEFT: { return source.left - dest.right; } case Dali::Toolkit::Control::KeyboardFocus::RIGHT: { return dest.left - source.right; } case Dali::Toolkit::Control::KeyboardFocus::UP: { return source.top - dest.bottom; } case Dali::Toolkit::Control::KeyboardFocus::DOWN: { return dest.top - source.bottom; } default: { return 0; } } } /** * @return The distance from the edge furthest in the given direction * of source to the edge nearest in the given direction of dest. * If the dest is not in the direction from source, return 0. */ static int MajorAxisDistance(Dali::Toolkit::Control::KeyboardFocus::Direction direction, Dali::Rect<float> source, Dali::Rect<float> dest) { return std::max(0, MajorAxisDistanceRaw(direction, source, dest)); } static int MajorAxisDistanceToFarEdgeRaw(Dali::Toolkit::Control::KeyboardFocus::Direction direction, Dali::Rect<float> source, Dali::Rect<float> dest) { switch(direction) { case Dali::Toolkit::Control::KeyboardFocus::LEFT: { return source.left - dest.left; } case Dali::Toolkit::Control::KeyboardFocus::RIGHT: { return dest.right - source.right; } case Dali::Toolkit::Control::KeyboardFocus::UP: { return source.top - dest.top; } case Dali::Toolkit::Control::KeyboardFocus::DOWN: { return dest.bottom - source.bottom; } default: { return 0; } } } /** * @return The distance along the major axis w.r.t the direction from the * edge of source to the far edge of dest. * If the dest is not in the direction from source, return 1 */ static int MajorAxisDistanceToFarEdge(Dali::Toolkit::Control::KeyboardFocus::Direction direction, Dali::Rect<float> source, Dali::Rect<float> dest) { return std::max(1, MajorAxisDistanceToFarEdgeRaw(direction, source, dest)); } /** * Find the distance on the minor axis w.r.t the direction to the nearest * edge of the destination rectangle. * @param direction the direction (up, down, left, right) * @param source The source rect. * @param dest The destination rect. * @return The distance. */ static int MinorAxisDistance(Dali::Toolkit::Control::KeyboardFocus::Direction direction, Dali::Rect<float> source, Dali::Rect<float> dest) { switch(direction) { case Dali::Toolkit::Control::KeyboardFocus::LEFT: case Dali::Toolkit::Control::KeyboardFocus::RIGHT: { // the distance between the center verticals return std::abs( (((source.top + source.bottom) * 0.5f) - (((dest.top + dest.bottom) * 0.5f)))); } case Dali::Toolkit::Control::KeyboardFocus::UP: case Dali::Toolkit::Control::KeyboardFocus::DOWN: { // the distance between the center horizontals return std::abs( (((source.left + source.right) * 0.5f) - (((dest.left + dest.right) * 0.5f)))); } default: { return 0; } } } /** * Calculate distance given major and minor axis distances. * @param majorAxisDistance The majorAxisDistance * @param minorAxisDistance The minorAxisDistance * @return The distance */ static int GetWeightedDistanceFor(int majorAxisDistance, int minorAxisDistance) { return 13 * majorAxisDistance * majorAxisDistance + minorAxisDistance * minorAxisDistance; } /** * Convert x,y,width,height coordinates into left, right, bottom, top coordinates. * @param[in,out] rect The rect */ static void ConvertCoordinate(Dali::Rect<float>& rect) { // convert x, y, width, height -> left, right, bottom, top float left = rect.x; float right = rect.x + rect.width; float bottom = rect.y + rect.height; float top = rect.y; rect.left = left; rect.right = right; rect.bottom = bottom; rect.top = top; } /** * Is destRect a candidate for the next focus given the direction? * @param srcRect The source rect. * @param destRect The dest rect. * @param direction The direction (up, down, left, right) * @return Whether destRect is a candidate. */ static bool IsCandidate(Dali::Rect<float> srcRect, Dali::Rect<float> destRect, Dali::Toolkit::Control::KeyboardFocus::Direction direction) { switch(direction) { case Dali::Toolkit::Control::KeyboardFocus::LEFT: { return (srcRect.right > destRect.right || srcRect.left >= destRect.right) && srcRect.left > destRect.left; } case Dali::Toolkit::Control::KeyboardFocus::RIGHT: { return (srcRect.left < destRect.left || srcRect.right <= destRect.left) && srcRect.right < destRect.right; } case Dali::Toolkit::Control::KeyboardFocus::UP: { return (srcRect.bottom > destRect.bottom || srcRect.top >= destRect.bottom) && srcRect.top > destRect.top; } case Dali::Toolkit::Control::KeyboardFocus::DOWN: { return (srcRect.top < destRect.top || srcRect.bottom <= destRect.top) && srcRect.bottom < destRect.bottom; } default: { return false; } } return false; } /** * Is dest in a given direction from src? * @param direction the direction (up, down, left, right) * @param src The source rect * @param dest The dest rect */ static bool IsToDirectionOf(Dali::Toolkit::Control::KeyboardFocus::Direction direction, Dali::Rect<float> src, Dali::Rect<float> dest) { switch(direction) { case Dali::Toolkit::Control::KeyboardFocus::LEFT: { return src.left >= dest.right; } case Dali::Toolkit::Control::KeyboardFocus::RIGHT: { return src.right <= dest.left; } case Dali::Toolkit::Control::KeyboardFocus::UP: { return src.top >= dest.bottom; } case Dali::Toolkit::Control::KeyboardFocus::DOWN: { return src.bottom <= dest.top; } default: { return false; } } } /** * Do the given direction's axis of rect1 and rect2 overlap? * @param direction the direction (up, down, left, right) * @param rect1 The first rect * @param rect2 The second rect * @return whether the beams overlap */ static bool BeamsOverlap(Dali::Toolkit::Control::KeyboardFocus::Direction direction, Dali::Rect<float> rect1, Dali::Rect<float> rect2) { switch(direction) { case Dali::Toolkit::Control::KeyboardFocus::LEFT: case Dali::Toolkit::Control::KeyboardFocus::RIGHT: { return (rect2.bottom >= rect1.top) && (rect2.top <= rect1.bottom); } case Dali::Toolkit::Control::KeyboardFocus::UP: case Dali::Toolkit::Control::KeyboardFocus::DOWN: { return (rect2.right >= rect1.left) && (rect2.left <= rect1.right); } default: { return false; } } } /** * One rectangle may be another candidate than another by virtue of being exclusively in the beam of the source rect. * @param direction The direction (up, down, left, right) * @param source The source rect * @param rect1 The first rect * @param rect2 The second rect * @return Whether rect1 is a better candidate than rect2 by virtue of it being in src's beam */ static bool BeamBeats(Dali::Toolkit::Control::KeyboardFocus::Direction direction, Dali::Rect<float> source, Dali::Rect<float> rect1, Dali::Rect<float> rect2) { const bool rect1InSrcBeam = BeamsOverlap(direction, source, rect1); const bool rect2InSrcBeam = BeamsOverlap(direction, source, rect2); // if rect1 isn't exclusively in the src beam, it doesn't win if(rect2InSrcBeam || !rect1InSrcBeam) { return false; } // we know rect1 is in the beam, and rect2 is not // if rect1 is to the direction of, and rect2 is not, rect1 wins. // for example, for direction left, if rect1 is to the left of the source // and rect2 is below, then we always prefer the in beam rect1, since rect2 // could be reached by going down. if(!IsToDirectionOf(direction, source, rect2)) { return true; } // for horizontal directions, being exclusively in beam always wins if((direction == Dali::Toolkit::Control::KeyboardFocus::LEFT || direction == Dali::Toolkit::Control::KeyboardFocus::RIGHT)) { return true; } // for vertical directions, beams only beat up to a point: // now, as long as rect2 isn't completely closer, rect1 wins // e.g for direction down, completely closer means for rect2's top // edge to be closer to the source's top edge than rect1's bottom edge. return (MajorAxisDistance(direction, source, rect1) < MajorAxisDistanceToFarEdge(direction, source, rect2)); } bool IsBetterCandidate(Toolkit::Control::KeyboardFocus::Direction direction, Rect<float>& focusedRect, Rect<float>& candidateRect, Rect<float>& bestCandidateRect) { // to be a better candidate, need to at least be a candidate in the first place if(!IsCandidate(focusedRect, candidateRect, direction)) { return false; } // we know that candidateRect is a candidate.. if bestCandidateRect is not a candidate, // candidateRect is better if(!IsCandidate(focusedRect, bestCandidateRect, direction)) { return true; } // if candidateRect is better by beam, it wins if(BeamBeats(direction, focusedRect, candidateRect, bestCandidateRect)) { return true; } // if bestCandidateRect is better, then candidateRect cant' be :) if(BeamBeats(direction, focusedRect, bestCandidateRect, candidateRect)) { return false; } // otherwise, do fudge-tastic comparison of the major and minor axis return (GetWeightedDistanceFor( MajorAxisDistance(direction, focusedRect, candidateRect), MinorAxisDistance(direction, focusedRect, candidateRect)) < GetWeightedDistanceFor(MajorAxisDistance(direction, focusedRect, bestCandidateRect), MinorAxisDistance(direction, focusedRect, bestCandidateRect))); } bool IsFocusable(Actor& actor) { return (actor.GetProperty<bool>(Actor::Property::KEYBOARD_FOCUSABLE) && actor.GetProperty<bool>(Actor::Property::VISIBLE) && actor.GetProperty<bool>(Actor::Property::SENSITIVE) && actor.GetProperty<Vector4>(Actor::Property::WORLD_COLOR).a > FULLY_TRANSPARENT); } Actor FindNextFocus(Actor& actor, Actor& focusedActor, Rect<float>& focusedRect, Rect<float>& bestCandidateRect, Toolkit::Control::KeyboardFocus::Direction direction) { Actor nearestActor; if(actor) { // Recursively children const auto childCount = actor.GetChildCount(); for(auto i = 0u; i < childCount; ++i) { Dali::Actor child = actor.GetChildAt(i); if(child && child != focusedActor && IsFocusable(child)) { Rect<float> candidateRect = DevelActor::CalculateScreenExtents(child); // convert x, y, width, height -> left, right, bottom, top ConvertCoordinate(candidateRect); if(IsBetterCandidate(direction, focusedRect, candidateRect, bestCandidateRect)) { bestCandidateRect = candidateRect; nearestActor = child; } } Actor nextActor = FindNextFocus(child, focusedActor, focusedRect, bestCandidateRect, direction); if(nextActor) { nearestActor = nextActor; } } } return nearestActor; } } // unnamed namespace Actor GetNearestFocusableActor(Actor focusedActor, Toolkit::Control::KeyboardFocus::Direction direction) { Actor nearestActor; if(!focusedActor) { return nearestActor; } Rect<float> focusedRect = DevelActor::CalculateScreenExtents(focusedActor); // initialize the best candidate to something impossible // (so the first plausible actor will become the best choice) Rect<float> bestCandidateRect = focusedRect; switch(direction) { case Toolkit::Control::KeyboardFocus::LEFT: { bestCandidateRect.x += 1; break; } case Toolkit::Control::KeyboardFocus::RIGHT: { bestCandidateRect.x -= 1; break; } case Toolkit::Control::KeyboardFocus::UP: { bestCandidateRect.y += 1; break; } case Toolkit::Control::KeyboardFocus::DOWN: { bestCandidateRect.y -= 1; break; } default: { break; } } ConvertCoordinate(bestCandidateRect); ConvertCoordinate(focusedRect); Integration::SceneHolder window = Integration::SceneHolder::Get(focusedActor); if(window) { Actor rootActor = window.GetRootLayer(); nearestActor = FindNextFocus(rootActor, focusedActor, focusedRect, bestCandidateRect, direction); } return nearestActor; } } // namespace FocusFinder } // namespace Toolkit } // namespace Dali <commit_msg>Fixed bug<commit_after>/* * Copyright (c) 2021 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. * */ /* * Copyright (C) 2017 The Android Open Source Project * * Modified by joogab yun([email protected]) */ // CLASS HEADER #include "focus-finder.h" // EXTERNAL INCLUDES #include <dali/devel-api/actors/actor-devel.h> #include <dali/integration-api/adaptor-framework/scene-holder.h> #include <dali/public-api/actors/layer.h> namespace Dali { namespace Toolkit { namespace FocusFinder { namespace { static constexpr float FULLY_TRANSPARENT(0.01f); ///< Alpha values must rise above this, before an object is considered to be visible. static int MajorAxisDistanceRaw(Dali::Toolkit::Control::KeyboardFocus::Direction direction, Dali::Rect<float> source, Dali::Rect<float> dest) { switch(direction) { case Dali::Toolkit::Control::KeyboardFocus::LEFT: { return source.left - dest.right; } case Dali::Toolkit::Control::KeyboardFocus::RIGHT: { return dest.left - source.right; } case Dali::Toolkit::Control::KeyboardFocus::UP: { return source.top - dest.bottom; } case Dali::Toolkit::Control::KeyboardFocus::DOWN: { return dest.top - source.bottom; } default: { return 0; } } } /** * @return The distance from the edge furthest in the given direction * of source to the edge nearest in the given direction of dest. * If the dest is not in the direction from source, return 0. */ static int MajorAxisDistance(Dali::Toolkit::Control::KeyboardFocus::Direction direction, Dali::Rect<float> source, Dali::Rect<float> dest) { return std::max(0, MajorAxisDistanceRaw(direction, source, dest)); } static int MajorAxisDistanceToFarEdgeRaw(Dali::Toolkit::Control::KeyboardFocus::Direction direction, Dali::Rect<float> source, Dali::Rect<float> dest) { switch(direction) { case Dali::Toolkit::Control::KeyboardFocus::LEFT: { return source.left - dest.left; } case Dali::Toolkit::Control::KeyboardFocus::RIGHT: { return dest.right - source.right; } case Dali::Toolkit::Control::KeyboardFocus::UP: { return source.top - dest.top; } case Dali::Toolkit::Control::KeyboardFocus::DOWN: { return dest.bottom - source.bottom; } default: { return 0; } } } /** * @return The distance along the major axis w.r.t the direction from the * edge of source to the far edge of dest. * If the dest is not in the direction from source, return 1 */ static int MajorAxisDistanceToFarEdge(Dali::Toolkit::Control::KeyboardFocus::Direction direction, Dali::Rect<float> source, Dali::Rect<float> dest) { return std::max(1, MajorAxisDistanceToFarEdgeRaw(direction, source, dest)); } /** * Find the distance on the minor axis w.r.t the direction to the nearest * edge of the destination rectangle. * @param direction the direction (up, down, left, right) * @param source The source rect. * @param dest The destination rect. * @return The distance. */ static int MinorAxisDistance(Dali::Toolkit::Control::KeyboardFocus::Direction direction, Dali::Rect<float> source, Dali::Rect<float> dest) { switch(direction) { case Dali::Toolkit::Control::KeyboardFocus::LEFT: case Dali::Toolkit::Control::KeyboardFocus::RIGHT: { // the distance between the center verticals return std::abs((source.top + (source.bottom - source.top) * 0.5f) - (dest.top + (dest.bottom - dest.top) * 0.5f)); } case Dali::Toolkit::Control::KeyboardFocus::UP: case Dali::Toolkit::Control::KeyboardFocus::DOWN: { // the distance between the center horizontals return std::abs((source.left + (source.right - source.left) * 0.5f) - (dest.left + (dest.right - dest.left) * 0.5f)); } default: { return 0; } } } /** * Calculate distance given major and minor axis distances. * @param majorAxisDistance The majorAxisDistance * @param minorAxisDistance The minorAxisDistance * @return The distance */ static int GetWeightedDistanceFor(int majorAxisDistance, int minorAxisDistance) { return 13 * majorAxisDistance * majorAxisDistance + minorAxisDistance * minorAxisDistance; } /** * Convert x,y,width,height coordinates into left, right, bottom, top coordinates. * @param[in,out] rect The rect */ static void ConvertCoordinate(Dali::Rect<float>& rect) { // convert x, y, width, height -> left, right, bottom, top float left = rect.x; float right = rect.x + rect.width; float bottom = rect.y + rect.height; float top = rect.y; rect.left = left; rect.right = right; rect.bottom = bottom; rect.top = top; } /** * Is destRect a candidate for the next focus given the direction? * @param srcRect The source rect. * @param destRect The dest rect. * @param direction The direction (up, down, left, right) * @return Whether destRect is a candidate. */ static bool IsCandidate(Dali::Rect<float> srcRect, Dali::Rect<float> destRect, Dali::Toolkit::Control::KeyboardFocus::Direction direction) { switch(direction) { case Dali::Toolkit::Control::KeyboardFocus::LEFT: { return (srcRect.right > destRect.right || srcRect.left >= destRect.right); } case Dali::Toolkit::Control::KeyboardFocus::RIGHT: { return (srcRect.left < destRect.left || srcRect.right <= destRect.left); } case Dali::Toolkit::Control::KeyboardFocus::UP: { return (srcRect.bottom > destRect.bottom || srcRect.top >= destRect.bottom); } case Dali::Toolkit::Control::KeyboardFocus::DOWN: { return (srcRect.top < destRect.top || srcRect.bottom <= destRect.top); } default: { return false; } } return false; } /** * Is dest in a given direction from src? * @param direction the direction (up, down, left, right) * @param src The source rect * @param dest The dest rect */ static bool IsToDirectionOf(Dali::Toolkit::Control::KeyboardFocus::Direction direction, Dali::Rect<float> src, Dali::Rect<float> dest) { switch(direction) { case Dali::Toolkit::Control::KeyboardFocus::LEFT: { return src.left >= dest.right; } case Dali::Toolkit::Control::KeyboardFocus::RIGHT: { return src.right <= dest.left; } case Dali::Toolkit::Control::KeyboardFocus::UP: { return src.top >= dest.bottom; } case Dali::Toolkit::Control::KeyboardFocus::DOWN: { return src.bottom <= dest.top; } default: { return false; } } } /** * Do the given direction's axis of rect1 and rect2 overlap? * @param direction the direction (up, down, left, right) * @param rect1 The first rect * @param rect2 The second rect * @return whether the beams overlap */ static bool BeamsOverlap(Dali::Toolkit::Control::KeyboardFocus::Direction direction, Dali::Rect<float> rect1, Dali::Rect<float> rect2) { switch(direction) { case Dali::Toolkit::Control::KeyboardFocus::LEFT: case Dali::Toolkit::Control::KeyboardFocus::RIGHT: { return (rect2.bottom >= rect1.top) && (rect2.top <= rect1.bottom); } case Dali::Toolkit::Control::KeyboardFocus::UP: case Dali::Toolkit::Control::KeyboardFocus::DOWN: { return (rect2.right >= rect1.left) && (rect2.left <= rect1.right); } default: { return false; } } } /** * One rectangle may be another candidate than another by virtue of being exclusively in the beam of the source rect. * @param direction The direction (up, down, left, right) * @param source The source rect * @param rect1 The first rect * @param rect2 The second rect * @return Whether rect1 is a better candidate than rect2 by virtue of it being in src's beam */ static bool BeamBeats(Dali::Toolkit::Control::KeyboardFocus::Direction direction, Dali::Rect<float> source, Dali::Rect<float> rect1, Dali::Rect<float> rect2) { const bool rect1InSrcBeam = BeamsOverlap(direction, source, rect1); const bool rect2InSrcBeam = BeamsOverlap(direction, source, rect2); // if rect1 isn't exclusively in the src beam, it doesn't win if(rect2InSrcBeam || !rect1InSrcBeam) { return false; } // we know rect1 is in the beam, and rect2 is not // if rect1 is to the direction of, and rect2 is not, rect1 wins. // for example, for direction left, if rect1 is to the left of the source // and rect2 is below, then we always prefer the in beam rect1, since rect2 // could be reached by going down. if(!IsToDirectionOf(direction, source, rect2)) { return true; } // for horizontal directions, being exclusively in beam always wins if((direction == Dali::Toolkit::Control::KeyboardFocus::LEFT || direction == Dali::Toolkit::Control::KeyboardFocus::RIGHT)) { return true; } // for vertical directions, beams only beat up to a point: // now, as long as rect2 isn't completely closer, rect1 wins // e.g for direction down, completely closer means for rect2's top // edge to be closer to the source's top edge than rect1's bottom edge. return (MajorAxisDistance(direction, source, rect1) < MajorAxisDistanceToFarEdge(direction, source, rect2)); } bool IsBetterCandidate(Toolkit::Control::KeyboardFocus::Direction direction, Rect<float>& focusedRect, Rect<float>& candidateRect, Rect<float>& bestCandidateRect) { // to be a better candidate, need to at least be a candidate in the first place if(!IsCandidate(focusedRect, candidateRect, direction)) { return false; } // we know that candidateRect is a candidate.. if bestCandidateRect is not a candidate, // candidateRect is better if(!IsCandidate(focusedRect, bestCandidateRect, direction)) { return true; } // if candidateRect is better by beam, it wins if(BeamBeats(direction, focusedRect, candidateRect, bestCandidateRect)) { return true; } // if bestCandidateRect is better, then candidateRect cant' be :) if(BeamBeats(direction, focusedRect, bestCandidateRect, candidateRect)) { return false; } // otherwise, do fudge-tastic comparison of the major and minor axis return (GetWeightedDistanceFor( MajorAxisDistance(direction, focusedRect, candidateRect), MinorAxisDistance(direction, focusedRect, candidateRect)) < GetWeightedDistanceFor(MajorAxisDistance(direction, focusedRect, bestCandidateRect), MinorAxisDistance(direction, focusedRect, bestCandidateRect))); } bool IsFocusable(Actor& actor) { return (actor.GetProperty<bool>(Actor::Property::KEYBOARD_FOCUSABLE) && actor.GetProperty<bool>(Actor::Property::VISIBLE) && actor.GetProperty<bool>(Actor::Property::SENSITIVE) && actor.GetProperty<Vector4>(Actor::Property::WORLD_COLOR).a > FULLY_TRANSPARENT); } Actor FindNextFocus(Actor& actor, Actor& focusedActor, Rect<float>& focusedRect, Rect<float>& bestCandidateRect, Toolkit::Control::KeyboardFocus::Direction direction) { Actor nearestActor; if(actor) { // Recursively children const auto childCount = actor.GetChildCount(); for(auto i = 0u; i < childCount; ++i) { Dali::Actor child = actor.GetChildAt(i); if(child && child != focusedActor && IsFocusable(child)) { Rect<float> candidateRect = DevelActor::CalculateScreenExtents(child); // convert x, y, width, height -> left, right, bottom, top ConvertCoordinate(candidateRect); if(IsBetterCandidate(direction, focusedRect, candidateRect, bestCandidateRect)) { bestCandidateRect = candidateRect; nearestActor = child; } } Actor nextActor = FindNextFocus(child, focusedActor, focusedRect, bestCandidateRect, direction); if(nextActor) { nearestActor = nextActor; } } } return nearestActor; } } // unnamed namespace Actor GetNearestFocusableActor(Actor focusedActor, Toolkit::Control::KeyboardFocus::Direction direction) { Actor nearestActor; if(!focusedActor) { return nearestActor; } Rect<float> focusedRect = DevelActor::CalculateScreenExtents(focusedActor); // initialize the best candidate to something impossible // (so the first plausible actor will become the best choice) Rect<float> bestCandidateRect = focusedRect; switch(direction) { case Toolkit::Control::KeyboardFocus::LEFT: { bestCandidateRect.x += 1; break; } case Toolkit::Control::KeyboardFocus::RIGHT: { bestCandidateRect.x -= 1; break; } case Toolkit::Control::KeyboardFocus::UP: { bestCandidateRect.y += 1; break; } case Toolkit::Control::KeyboardFocus::DOWN: { bestCandidateRect.y -= 1; break; } default: { break; } } ConvertCoordinate(bestCandidateRect); ConvertCoordinate(focusedRect); Integration::SceneHolder window = Integration::SceneHolder::Get(focusedActor); if(window) { Actor rootActor = window.GetRootLayer(); nearestActor = FindNextFocus(rootActor, focusedActor, focusedRect, bestCandidateRect, direction); } return nearestActor; } } // namespace FocusFinder } // namespace Toolkit } // namespace Dali <|endoftext|>
<commit_before>/* * jpegtran.c * * This file was part of the Independent JPEG Group's software: * Copyright (C) 1995-2010, Thomas G. Lane, Guido Vollbeding. * libjpeg-turbo Modifications: * Copyright (C) 2010, 2014, D. R. Commander. * mozjpeg Modifications: * Copyright (C) 2014, Mozilla Corporation. * For conditions of distribution and use, see the accompanying README file. * * This file contains a command-line user interface for JPEG transcoding. * It is very similar to cjpeg.c, and partly to djpeg.c, but provides * lossless transcoding between different JPEG file formats. It also * provides some lossless and sort-of-lossless transformations of JPEG data. */ /* Modified by Felix Hanau. */ #define JPEG_INTERNAL_OPTIONS /* cjpeg.c, djpeg.c need to see xxx_SUPPORTED */ #include "mozjpeg/jinclude.h" #include "mozjpeg/jpeglib.h" #include "main.h" #define INPUT_BUF_SIZE 4096 static void jcopy_markers_execute (j_decompress_ptr srcinfo, j_compress_ptr dstinfo) { for (jpeg_saved_marker_ptr marker = srcinfo->marker_list; marker != NULL; marker = marker->next) { if (dstinfo->write_JFIF_header && marker->marker == JPEG_APP0 && marker->data_length >= 5 && GETJOCTET(marker->data[0]) == 0x4A && GETJOCTET(marker->data[1]) == 0x46 && GETJOCTET(marker->data[2]) == 0x49 && GETJOCTET(marker->data[3]) == 0x46 && GETJOCTET(marker->data[4]) == 0) continue; /* reject duplicate JFIF */ if (dstinfo->write_Adobe_marker && marker->marker == JPEG_APP0+14 && marker->data_length >= 5 && GETJOCTET(marker->data[0]) == 0x41 && GETJOCTET(marker->data[1]) == 0x64 && GETJOCTET(marker->data[2]) == 0x6F && GETJOCTET(marker->data[3]) == 0x62 && GETJOCTET(marker->data[4]) == 0x65) continue; /* reject duplicate Adobe */ jpeg_write_marker(dstinfo, marker->marker, marker->data, marker->data_length); } } int mozjpegtran (bool arithmetic, bool progressive, bool strip, const char * Infile, const char * Outfile) { struct jpeg_decompress_struct srcinfo; struct jpeg_compress_struct dstinfo; struct jpeg_error_mgr jsrcerr, jdsterr; FILE * fp; unsigned char *inbuffer = NULL; unsigned long insize = 0; unsigned char *outbuffer = NULL; unsigned long outsize = 0; const char * progname = "ECT (JPEG)"; /* Initialize the JPEG decompression object with default error handling. */ srcinfo.err = jpeg_std_error(&jsrcerr); jpeg_create_decompress(&srcinfo); /* Initialize the JPEG compression object with default error handling. */ dstinfo.err = jpeg_std_error(&jdsterr); jpeg_create_compress(&dstinfo); if (!progressive){ jpeg_c_set_int_param(&dstinfo, JINT_COMPRESS_PROFILE, JCP_FASTEST); } /* Open the input file. */ if ((fp = fopen(Infile, "rb")) == NULL) { fprintf(stderr, "%s: can't open %s for reading\n", progname, Infile); return 2; } size_t nbytes; do { inbuffer = (unsigned char *)realloc(inbuffer, insize + INPUT_BUF_SIZE); if (inbuffer == NULL) { fprintf(stderr, "%s: memory allocation failure\n", progname); exit(1); } nbytes = JFREAD(fp, &inbuffer[insize], INPUT_BUF_SIZE); if (nbytes < INPUT_BUF_SIZE && ferror(fp)) { fprintf(stderr, "%s: can't read from %s\n", progname, Infile); } insize += (unsigned long)nbytes; } while (nbytes == INPUT_BUF_SIZE); fclose(fp); jpeg_mem_src(&srcinfo, inbuffer, insize); /* Enable saving of extra markers that we want to copy */ if (!strip) { jpeg_save_markers(&srcinfo, JPEG_COM, 0xFFFF); for (int m = 0; m < 16; m++) jpeg_save_markers(&srcinfo, JPEG_APP0 + m, 0xFFFF); } /* Read file header */ jpeg_read_header(&srcinfo, TRUE); /* Any space needed by a transform option must be requested before jpeg_read_coefficients so that memory allocation will be done right. */ /* Read source file as DCT coefficients */ jvirt_barray_ptr * coef_arrays = jpeg_read_coefficients(&srcinfo); /* Initialize destination compression parameters from source values */ jpeg_copy_critical_parameters(&srcinfo, &dstinfo); /* Adjust default compression parameters by re-parsing the options */ dstinfo.optimize_coding = !progressive && !arithmetic; if (dstinfo.num_scans && progressive) { jpeg_simple_progression(&dstinfo); } dstinfo.arith_code = arithmetic; /* Specify data destination for compression */ jpeg_mem_dest(&dstinfo, &outbuffer, &outsize); /* Start compressor (note no image data is actually written here) */ jpeg_write_coefficients(&dstinfo, coef_arrays); /* Copy to the output file any extra markers that we want to preserve */ jcopy_markers_execute(&srcinfo, &dstinfo); /* Finish compression and release memory */ jpeg_finish_compress(&dstinfo); free(inbuffer); int x = 0; if (insize < outsize || (progressive && insize == outsize)){ x = 1; } /* Better file than before */ else{ /* Open the output file. */ if ((fp = fopen(Outfile, "wb")) == NULL) { fprintf(stderr, "%s: can't open %s for writing\n", progname, Outfile); free(outbuffer); return 2; } /* Write new file. */ if (JFWRITE(fp, outbuffer, outsize) < outsize && ferror(fp)) { fprintf(stderr, "%s: can't write to %s\n", progname, Outfile); } } jpeg_destroy_compress(&dstinfo); jpeg_finish_decompress(&srcinfo); jpeg_destroy_decompress(&srcinfo); fclose(fp); free(outbuffer); return x; } <commit_msg>Make sure progressive encoding is only used when wanted<commit_after>/* * jpegtran.c * * This file was part of the Independent JPEG Group's software: * Copyright (C) 1995-2010, Thomas G. Lane, Guido Vollbeding. * libjpeg-turbo Modifications: * Copyright (C) 2010, 2014, D. R. Commander. * mozjpeg Modifications: * Copyright (C) 2014, Mozilla Corporation. * For conditions of distribution and use, see the accompanying README file. * * This file contains a command-line user interface for JPEG transcoding. * It is very similar to cjpeg.c, and partly to djpeg.c, but provides * lossless transcoding between different JPEG file formats. It also * provides some lossless and sort-of-lossless transformations of JPEG data. */ /* Modified by Felix Hanau. */ #define JPEG_INTERNAL_OPTIONS /* cjpeg.c, djpeg.c need to see xxx_SUPPORTED */ #include "mozjpeg/jinclude.h" #include "mozjpeg/jpeglib.h" #include "main.h" #define INPUT_BUF_SIZE 4096 static void jcopy_markers_execute (j_decompress_ptr srcinfo, j_compress_ptr dstinfo) { for (jpeg_saved_marker_ptr marker = srcinfo->marker_list; marker != NULL; marker = marker->next) { if (dstinfo->write_JFIF_header && marker->marker == JPEG_APP0 && marker->data_length >= 5 && GETJOCTET(marker->data[0]) == 0x4A && GETJOCTET(marker->data[1]) == 0x46 && GETJOCTET(marker->data[2]) == 0x49 && GETJOCTET(marker->data[3]) == 0x46 && GETJOCTET(marker->data[4]) == 0) continue; /* reject duplicate JFIF */ if (dstinfo->write_Adobe_marker && marker->marker == JPEG_APP0+14 && marker->data_length >= 5 && GETJOCTET(marker->data[0]) == 0x41 && GETJOCTET(marker->data[1]) == 0x64 && GETJOCTET(marker->data[2]) == 0x6F && GETJOCTET(marker->data[3]) == 0x62 && GETJOCTET(marker->data[4]) == 0x65) continue; /* reject duplicate Adobe */ jpeg_write_marker(dstinfo, marker->marker, marker->data, marker->data_length); } } int mozjpegtran (bool arithmetic, bool progressive, bool strip, const char * Infile, const char * Outfile) { struct jpeg_decompress_struct srcinfo; struct jpeg_compress_struct dstinfo; struct jpeg_error_mgr jsrcerr, jdsterr; FILE * fp; unsigned char *inbuffer = NULL; unsigned long insize = 0; unsigned char *outbuffer = NULL; unsigned long outsize = 0; const char * progname = "ECT (JPEG)"; /* Initialize the JPEG decompression object with default error handling. */ srcinfo.err = jpeg_std_error(&jsrcerr); jpeg_create_decompress(&srcinfo); /* Initialize the JPEG compression object with default error handling. */ dstinfo.err = jpeg_std_error(&jdsterr); jpeg_create_compress(&dstinfo); if (!progressive){ jpeg_c_set_int_param(&dstinfo, JINT_COMPRESS_PROFILE, JCP_FASTEST); } /* Open the input file. */ if ((fp = fopen(Infile, "rb")) == NULL) { fprintf(stderr, "%s: can't open %s for reading\n", progname, Infile); return 2; } size_t nbytes; do { inbuffer = (unsigned char *)realloc(inbuffer, insize + INPUT_BUF_SIZE); if (inbuffer == NULL) { fprintf(stderr, "%s: memory allocation failure\n", progname); exit(1); } nbytes = JFREAD(fp, &inbuffer[insize], INPUT_BUF_SIZE); if (nbytes < INPUT_BUF_SIZE && ferror(fp)) { fprintf(stderr, "%s: can't read from %s\n", progname, Infile); } insize += (unsigned long)nbytes; } while (nbytes == INPUT_BUF_SIZE); fclose(fp); jpeg_mem_src(&srcinfo, inbuffer, insize); /* Enable saving of extra markers that we want to copy */ if (!strip) { jpeg_save_markers(&srcinfo, JPEG_COM, 0xFFFF); for (int m = 0; m < 16; m++) jpeg_save_markers(&srcinfo, JPEG_APP0 + m, 0xFFFF); } /* Read file header */ jpeg_read_header(&srcinfo, TRUE); /* Any space needed by a transform option must be requested before jpeg_read_coefficients so that memory allocation will be done right. */ /* Read source file as DCT coefficients */ jvirt_barray_ptr * coef_arrays = jpeg_read_coefficients(&srcinfo); /* Initialize destination compression parameters from source values */ jpeg_copy_critical_parameters(&srcinfo, &dstinfo); /* Adjust default compression parameters by re-parsing the options */ dstinfo.optimize_coding = !progressive && !arithmetic; dstinfo.arith_code = arithmetic; if (dstinfo.num_scans && progressive) { jpeg_simple_progression(&dstinfo); } else{ dstinfo.num_scans = 0; dstinfo.scan_info = NULL; } /* Specify data destination for compression */ jpeg_mem_dest(&dstinfo, &outbuffer, &outsize); /* Start compressor (note no image data is actually written here) */ jpeg_write_coefficients(&dstinfo, coef_arrays); /* Copy to the output file any extra markers that we want to preserve */ jcopy_markers_execute(&srcinfo, &dstinfo); /* Finish compression and release memory */ jpeg_finish_compress(&dstinfo); free(inbuffer); int x = 0; if (insize < outsize || (progressive && insize == outsize)){ x = 1; } /* Better file than before */ else{ /* Open the output file. */ if ((fp = fopen(Outfile, "wb")) == NULL) { fprintf(stderr, "%s: can't open %s for writing\n", progname, Outfile); free(outbuffer); return 2; } /* Write new file. */ if (JFWRITE(fp, outbuffer, outsize) < outsize && ferror(fp)) { fprintf(stderr, "%s: can't write to %s\n", progname, Outfile); } } jpeg_destroy_compress(&dstinfo); jpeg_finish_decompress(&srcinfo); jpeg_destroy_decompress(&srcinfo); fclose(fp); free(outbuffer); return x; } <|endoftext|>