text
stringlengths
54
60.6k
<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: rtlproto.hxx,v $ * $Revision: 1.18 $ * * 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. * ************************************************************************/ #include <basic/sbstar.hxx> #define RTLFUNC( name ) void SbRtl_##name( StarBASIC* pBasic, SbxArray& rPar, BOOL bWrite ) #define RTLNAME( name ) &SbRtl_##name typedef void( *RtlCall ) ( StarBASIC* p, SbxArray& rArgs, BOOL bWrite ); // Properties extern RTLFUNC(Date); extern RTLFUNC(Err); extern RTLFUNC(Erl); extern RTLFUNC(False); extern RTLFUNC(Nothing); extern RTLFUNC(Null); extern RTLFUNC(True); extern RTLFUNC(ATTR_NORMAL); extern RTLFUNC(ATTR_READONLY); extern RTLFUNC(ATTR_HIDDEN); extern RTLFUNC(ATTR_SYSTEM); extern RTLFUNC(ATTR_VOLUME); extern RTLFUNC(ATTR_DIRECTORY); extern RTLFUNC(ATTR_ARCHIVE); extern RTLFUNC(V_EMPTY); extern RTLFUNC(V_NULL); extern RTLFUNC(V_INTEGER); extern RTLFUNC(V_LONG); extern RTLFUNC(V_SINGLE); extern RTLFUNC(V_DOUBLE); extern RTLFUNC(V_CURRENCY); extern RTLFUNC(V_DATE); extern RTLFUNC(V_STRING); extern RTLFUNC(MB_OK); extern RTLFUNC(MB_OKCANCEL); extern RTLFUNC(MB_ABORTRETRYIGNORE); extern RTLFUNC(MB_YESNOCANCEL); extern RTLFUNC(MB_YESNO); extern RTLFUNC(MB_RETRYCANCEL); extern RTLFUNC(MB_ICONSTOP); extern RTLFUNC(MB_ICONQUESTION); extern RTLFUNC(MB_ICONEXCLAMATION); extern RTLFUNC(MB_ICONINFORMATION); extern RTLFUNC(MB_DEFBUTTON1); extern RTLFUNC(MB_DEFBUTTON2); extern RTLFUNC(MB_DEFBUTTON3); extern RTLFUNC(MB_APPLMODAL); extern RTLFUNC(MB_SYSTEMMODAL); extern RTLFUNC(IDOK); extern RTLFUNC(IDCANCEL); extern RTLFUNC(IDABORT); extern RTLFUNC(IDRETRY); extern RTLFUNC(IDYES); extern RTLFUNC(IDNO); extern RTLFUNC(CF_TEXT); extern RTLFUNC(CF_BITMAP); extern RTLFUNC(CF_METAFILEPICT); extern RTLFUNC(PI); extern RTLFUNC(SET_OFF); extern RTLFUNC(SET_ON); extern RTLFUNC(TOGGLE); extern RTLFUNC(TYP_AUTHORFLD); extern RTLFUNC(TYP_CHAPTERFLD); extern RTLFUNC(TYP_CONDTXTFLD); extern RTLFUNC(TYP_DATEFLD); extern RTLFUNC(TYP_DBFLD); extern RTLFUNC(TYP_DBNAMEFLD); extern RTLFUNC(TYP_DBNEXTSETFLD); extern RTLFUNC(TYP_DBNUMSETFLD); extern RTLFUNC(TYP_DBSETNUMBERFLD); extern RTLFUNC(TYP_DDEFLD); extern RTLFUNC(TYP_DOCINFOFLD); extern RTLFUNC(TYP_DOCSTATFLD); extern RTLFUNC(TYP_EXTUSERFLD); extern RTLFUNC(TYP_FILENAMEFLD); extern RTLFUNC(TYP_FIXDATEFLD); extern RTLFUNC(TYP_FIXTIMEFLD); extern RTLFUNC(TYP_FORMELFLD); extern RTLFUNC(TYP_GETFLD); extern RTLFUNC(TYP_GETREFFLD); extern RTLFUNC(TYP_HIDDENPARAFLD); extern RTLFUNC(TYP_HIDDENTXTFLD); extern RTLFUNC(TYP_INPUTFLD); extern RTLFUNC(TYP_MACROFLD); extern RTLFUNC(TYP_NEXTPAGEFLD); extern RTLFUNC(TYP_PAGENUMBERFLD); extern RTLFUNC(TYP_POSTITFLD); extern RTLFUNC(TYP_PREVPAGEFLD); extern RTLFUNC(TYP_SEQFLD); extern RTLFUNC(TYP_SETFLD); extern RTLFUNC(TYP_SETINPFLD); extern RTLFUNC(TYP_SETREFFLD); extern RTLFUNC(TYP_TEMPLNAMEFLD); extern RTLFUNC(TYP_TIMEFLD); extern RTLFUNC(TYP_USERFLD); extern RTLFUNC(TYP_USRINPFLD); extern RTLFUNC(TYP_SETREFPAGEFLD); extern RTLFUNC(TYP_GETREFPAGEFLD); extern RTLFUNC(TYP_INTERNETFLD); extern RTLFUNC(TYP_JUMPEDITFLD); extern RTLFUNC(FRAMEANCHORPAGE); extern RTLFUNC(FRAMEANCHORPARA); extern RTLFUNC(FRAMEANCHORCHAR); extern RTLFUNC(CLEAR_ALLTABS); extern RTLFUNC(CLEAR_TAB); extern RTLFUNC(SET_TAB); extern RTLFUNC(LINEPROP); extern RTLFUNC(LINE_1); extern RTLFUNC(LINE_15); extern RTLFUNC(LINE_2); // Methoden extern RTLFUNC(CreateObject); extern RTLFUNC(Error); extern RTLFUNC(Sin); extern RTLFUNC(Abs); extern RTLFUNC(Asc); extern RTLFUNC(Atn); extern RTLFUNC(Chr); extern RTLFUNC(Cos); extern RTLFUNC(CurDir); extern RTLFUNC(ChDir); // JSM extern RTLFUNC(ChDrive); // JSM extern RTLFUNC(FileCopy); // JSM extern RTLFUNC(Kill); // JSM extern RTLFUNC(MkDir); // JSM extern RTLFUNC(RmDir); // JSM extern RTLFUNC(SendKeys); // JSM extern RTLFUNC(DimArray); extern RTLFUNC(Dir); extern RTLFUNC(Exp); extern RTLFUNC(FileLen); extern RTLFUNC(Fix); extern RTLFUNC(Hex); extern RTLFUNC(Input); extern RTLFUNC(InStr); extern RTLFUNC(InStrRev); extern RTLFUNC(Int); extern RTLFUNC(Join); extern RTLFUNC(LCase); extern RTLFUNC(Left); extern RTLFUNC(Log); extern RTLFUNC(LTrim); extern RTLFUNC(Mid); extern RTLFUNC(Oct); extern RTLFUNC(Right); extern RTLFUNC(RTrim); extern RTLFUNC(RTL); extern RTLFUNC(Sgn); extern RTLFUNC(Space); extern RTLFUNC(Split); extern RTLFUNC(Sqr); extern RTLFUNC(Str); extern RTLFUNC(StrComp); extern RTLFUNC(String); extern RTLFUNC(StrReverse); extern RTLFUNC(Tan); extern RTLFUNC(UCase); extern RTLFUNC(Val); extern RTLFUNC(Len); extern RTLFUNC(Spc); extern RTLFUNC(DateSerial); extern RTLFUNC(TimeSerial); extern RTLFUNC(DateValue); extern RTLFUNC(TimeValue); extern RTLFUNC(Day); extern RTLFUNC(Hour); extern RTLFUNC(Minute); extern RTLFUNC(Month); extern RTLFUNC(MonthName); extern RTLFUNC(Now); extern RTLFUNC(Second); extern RTLFUNC(Time); extern RTLFUNC(Timer); extern RTLFUNC(Weekday); extern RTLFUNC(WeekdayName); extern RTLFUNC(Year); extern RTLFUNC(Date); extern RTLFUNC(InputBox); extern RTLFUNC(Me); extern RTLFUNC(MsgBox); extern RTLFUNC(IsArray); extern RTLFUNC(IsDate); extern RTLFUNC(IsEmpty); extern RTLFUNC(IsError); extern RTLFUNC(IsNull); extern RTLFUNC(IsNumeric); extern RTLFUNC(IsObject); extern RTLFUNC(IsUnoStruct); extern RTLFUNC(FileDateTime); extern RTLFUNC(Format); extern RTLFUNC(GetAttr); extern RTLFUNC(Randomize); // JSM extern RTLFUNC(Round); extern RTLFUNC(Rnd); extern RTLFUNC(Shell); extern RTLFUNC(VarType); extern RTLFUNC(TypeName); extern RTLFUNC(TypeLen); extern RTLFUNC(EOF); extern RTLFUNC(FileAttr); extern RTLFUNC(Loc); extern RTLFUNC(Lof); extern RTLFUNC(Seek); extern RTLFUNC(SetAttr); // JSM extern RTLFUNC(Reset); // JSM extern RTLFUNC(DDEInitiate); extern RTLFUNC(DDETerminate); extern RTLFUNC(DDETerminateAll); extern RTLFUNC(DDERequest); extern RTLFUNC(DDEExecute); extern RTLFUNC(DDEPoke); extern RTLFUNC(FreeFile); extern RTLFUNC(IsMissing); extern RTLFUNC(LBound); extern RTLFUNC(UBound); extern RTLFUNC(RGB); extern RTLFUNC(QBColor); extern RTLFUNC(StrConv); extern RTLFUNC(Beep); extern RTLFUNC(Load); extern RTLFUNC(Unload); extern RTLFUNC(AboutStarBasic); extern RTLFUNC(LoadPicture); extern RTLFUNC(SavePicture); extern RTLFUNC(CBool); // JSM extern RTLFUNC(CByte); // JSM extern RTLFUNC(CCur); // JSM extern RTLFUNC(CDate); // JSM extern RTLFUNC(CDbl); // JSM extern RTLFUNC(CInt); // JSM extern RTLFUNC(CLng); // JSM extern RTLFUNC(CSng); // JSM extern RTLFUNC(CStr); // JSM extern RTLFUNC(CVar); // JSM extern RTLFUNC(CVErr); // JSM extern RTLFUNC(Iif); // JSM extern RTLFUNC(DumpAllObjects); extern RTLFUNC(GetSystemType); extern RTLFUNC(GetGUIType); extern RTLFUNC(Red); extern RTLFUNC(Green); extern RTLFUNC(Blue); extern RTLFUNC(Switch); extern RTLFUNC(Wait); //i#64882# add new WaitUntil extern RTLFUNC(WaitUntil); extern RTLFUNC(GetGUIVersion); extern RTLFUNC(Choose); extern RTLFUNC(Trim); extern RTLFUNC(DateAdd); extern RTLFUNC(DateDiff); extern RTLFUNC(DatePart); extern RTLFUNC(FormatDateTime); extern RTLFUNC(GetSolarVersion); extern RTLFUNC(TwipsPerPixelX); extern RTLFUNC(TwipsPerPixelY); extern RTLFUNC(FreeLibrary); extern RTLFUNC(Array); extern RTLFUNC(FindObject); extern RTLFUNC(FindPropertyObject); extern RTLFUNC(EnableReschedule); extern RTLFUNC(Put); extern RTLFUNC(Get); extern RTLFUNC(Environ); extern RTLFUNC(GetDialogZoomFactorX); extern RTLFUNC(GetDialogZoomFactorY); extern RTLFUNC(GetSystemTicks); extern RTLFUNC(GetPathSeparator); extern RTLFUNC(ResolvePath); extern RTLFUNC(CreateUnoStruct); extern RTLFUNC(CreateUnoService); extern RTLFUNC(CreateUnoValue); extern RTLFUNC(GetProcessServiceManager); extern RTLFUNC(GetDefaultContext); extern RTLFUNC(CreatePropertySet); extern RTLFUNC(CreateUnoListener); extern RTLFUNC(HasUnoInterfaces); extern RTLFUNC(EqualUnoObjects); extern RTLFUNC(CreateUnoDialog); extern RTLFUNC(GlobalScope); extern RTLFUNC(FileExists); extern RTLFUNC(ConvertToUrl); extern RTLFUNC(ConvertFromUrl); extern RTLFUNC(CDateToIso); extern RTLFUNC(CDateFromIso); extern RTLFUNC(CompatibilityMode); extern RTLFUNC(CDec); extern double Now_Impl(); extern void Wait_Impl( bool bDurationBased, SbxArray& rPar ); <commit_msg>INTEGRATION: CWS npower10 (1.17.64); FILE MERGED 2008/05/07 07:11:00 pflin 1.17.64.5: RESYNC: (1.17-1.18); FILE MERGED 2008/03/12 06:32:50 pflin 1.17.64.4: Issue number: i85039 Submitted by: pflin Reviewed by: npower, ab Fix some issues found by code review 2008/01/07 06:47:16 pflin 1.17.64.3: Issue number: #i85037# Submitted by: pflin Reviewed by: npower Support the partition function 2008/01/07 06:42:54 pflin 1.17.64.2: Issue number: #i85036# Submitted by: pflin Reviewed by: npower Support strconv function 2008/01/07 06:41:38 pflin 1.17.64.1: Issue number: #i85035# Submitted by: pflin Reviewed by: npower Support replace function<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: rtlproto.hxx,v $ * $Revision: 1.19 $ * * 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. * ************************************************************************/ #include <basic/sbstar.hxx> #define RTLFUNC( name ) void SbRtl_##name( StarBASIC* pBasic, SbxArray& rPar, BOOL bWrite ) #define RTLNAME( name ) &SbRtl_##name typedef void( *RtlCall ) ( StarBASIC* p, SbxArray& rArgs, BOOL bWrite ); // Properties extern RTLFUNC(Date); extern RTLFUNC(Err); extern RTLFUNC(Erl); extern RTLFUNC(False); extern RTLFUNC(Nothing); extern RTLFUNC(Null); extern RTLFUNC(True); extern RTLFUNC(ATTR_NORMAL); extern RTLFUNC(ATTR_READONLY); extern RTLFUNC(ATTR_HIDDEN); extern RTLFUNC(ATTR_SYSTEM); extern RTLFUNC(ATTR_VOLUME); extern RTLFUNC(ATTR_DIRECTORY); extern RTLFUNC(ATTR_ARCHIVE); extern RTLFUNC(V_EMPTY); extern RTLFUNC(V_NULL); extern RTLFUNC(V_INTEGER); extern RTLFUNC(V_LONG); extern RTLFUNC(V_SINGLE); extern RTLFUNC(V_DOUBLE); extern RTLFUNC(V_CURRENCY); extern RTLFUNC(V_DATE); extern RTLFUNC(V_STRING); extern RTLFUNC(MB_OK); extern RTLFUNC(MB_OKCANCEL); extern RTLFUNC(MB_ABORTRETRYIGNORE); extern RTLFUNC(MB_YESNOCANCEL); extern RTLFUNC(MB_YESNO); extern RTLFUNC(MB_RETRYCANCEL); extern RTLFUNC(MB_ICONSTOP); extern RTLFUNC(MB_ICONQUESTION); extern RTLFUNC(MB_ICONEXCLAMATION); extern RTLFUNC(MB_ICONINFORMATION); extern RTLFUNC(MB_DEFBUTTON1); extern RTLFUNC(MB_DEFBUTTON2); extern RTLFUNC(MB_DEFBUTTON3); extern RTLFUNC(MB_APPLMODAL); extern RTLFUNC(MB_SYSTEMMODAL); extern RTLFUNC(IDOK); extern RTLFUNC(IDCANCEL); extern RTLFUNC(IDABORT); extern RTLFUNC(IDRETRY); extern RTLFUNC(IDYES); extern RTLFUNC(IDNO); extern RTLFUNC(CF_TEXT); extern RTLFUNC(CF_BITMAP); extern RTLFUNC(CF_METAFILEPICT); extern RTLFUNC(PI); extern RTLFUNC(SET_OFF); extern RTLFUNC(SET_ON); extern RTLFUNC(TOGGLE); extern RTLFUNC(TYP_AUTHORFLD); extern RTLFUNC(TYP_CHAPTERFLD); extern RTLFUNC(TYP_CONDTXTFLD); extern RTLFUNC(TYP_DATEFLD); extern RTLFUNC(TYP_DBFLD); extern RTLFUNC(TYP_DBNAMEFLD); extern RTLFUNC(TYP_DBNEXTSETFLD); extern RTLFUNC(TYP_DBNUMSETFLD); extern RTLFUNC(TYP_DBSETNUMBERFLD); extern RTLFUNC(TYP_DDEFLD); extern RTLFUNC(TYP_DOCINFOFLD); extern RTLFUNC(TYP_DOCSTATFLD); extern RTLFUNC(TYP_EXTUSERFLD); extern RTLFUNC(TYP_FILENAMEFLD); extern RTLFUNC(TYP_FIXDATEFLD); extern RTLFUNC(TYP_FIXTIMEFLD); extern RTLFUNC(TYP_FORMELFLD); extern RTLFUNC(TYP_GETFLD); extern RTLFUNC(TYP_GETREFFLD); extern RTLFUNC(TYP_HIDDENPARAFLD); extern RTLFUNC(TYP_HIDDENTXTFLD); extern RTLFUNC(TYP_INPUTFLD); extern RTLFUNC(TYP_MACROFLD); extern RTLFUNC(TYP_NEXTPAGEFLD); extern RTLFUNC(TYP_PAGENUMBERFLD); extern RTLFUNC(TYP_POSTITFLD); extern RTLFUNC(TYP_PREVPAGEFLD); extern RTLFUNC(TYP_SEQFLD); extern RTLFUNC(TYP_SETFLD); extern RTLFUNC(TYP_SETINPFLD); extern RTLFUNC(TYP_SETREFFLD); extern RTLFUNC(TYP_TEMPLNAMEFLD); extern RTLFUNC(TYP_TIMEFLD); extern RTLFUNC(TYP_USERFLD); extern RTLFUNC(TYP_USRINPFLD); extern RTLFUNC(TYP_SETREFPAGEFLD); extern RTLFUNC(TYP_GETREFPAGEFLD); extern RTLFUNC(TYP_INTERNETFLD); extern RTLFUNC(TYP_JUMPEDITFLD); extern RTLFUNC(FRAMEANCHORPAGE); extern RTLFUNC(FRAMEANCHORPARA); extern RTLFUNC(FRAMEANCHORCHAR); extern RTLFUNC(CLEAR_ALLTABS); extern RTLFUNC(CLEAR_TAB); extern RTLFUNC(SET_TAB); extern RTLFUNC(LINEPROP); extern RTLFUNC(LINE_1); extern RTLFUNC(LINE_15); extern RTLFUNC(LINE_2); // Methoden extern RTLFUNC(CreateObject); extern RTLFUNC(Error); extern RTLFUNC(Sin); extern RTLFUNC(Abs); extern RTLFUNC(Asc); extern RTLFUNC(Atn); extern RTLFUNC(Chr); extern RTLFUNC(Cos); extern RTLFUNC(CurDir); extern RTLFUNC(ChDir); // JSM extern RTLFUNC(ChDrive); // JSM extern RTLFUNC(FileCopy); // JSM extern RTLFUNC(Kill); // JSM extern RTLFUNC(MkDir); // JSM extern RTLFUNC(RmDir); // JSM extern RTLFUNC(SendKeys); // JSM extern RTLFUNC(DimArray); extern RTLFUNC(Dir); extern RTLFUNC(Exp); extern RTLFUNC(FileLen); extern RTLFUNC(Fix); extern RTLFUNC(Hex); extern RTLFUNC(Input); extern RTLFUNC(InStr); extern RTLFUNC(InStrRev); extern RTLFUNC(Int); extern RTLFUNC(Join); extern RTLFUNC(LCase); extern RTLFUNC(Left); extern RTLFUNC(Log); extern RTLFUNC(LTrim); extern RTLFUNC(Mid); extern RTLFUNC(Oct); extern RTLFUNC(Replace); extern RTLFUNC(Right); extern RTLFUNC(RTrim); extern RTLFUNC(RTL); extern RTLFUNC(Sgn); extern RTLFUNC(Space); extern RTLFUNC(Split); extern RTLFUNC(Sqr); extern RTLFUNC(Str); extern RTLFUNC(StrComp); extern RTLFUNC(String); extern RTLFUNC(StrReverse); extern RTLFUNC(Tan); extern RTLFUNC(UCase); extern RTLFUNC(Val); extern RTLFUNC(Len); extern RTLFUNC(Spc); extern RTLFUNC(DateSerial); extern RTLFUNC(TimeSerial); extern RTLFUNC(DateValue); extern RTLFUNC(TimeValue); extern RTLFUNC(Day); extern RTLFUNC(Hour); extern RTLFUNC(Minute); extern RTLFUNC(Month); extern RTLFUNC(MonthName); extern RTLFUNC(Now); extern RTLFUNC(Second); extern RTLFUNC(Time); extern RTLFUNC(Timer); extern RTLFUNC(Weekday); extern RTLFUNC(WeekdayName); extern RTLFUNC(Year); extern RTLFUNC(Date); extern RTLFUNC(InputBox); extern RTLFUNC(Me); extern RTLFUNC(MsgBox); extern RTLFUNC(IsArray); extern RTLFUNC(IsDate); extern RTLFUNC(IsEmpty); extern RTLFUNC(IsError); extern RTLFUNC(IsNull); extern RTLFUNC(IsNumeric); extern RTLFUNC(IsObject); extern RTLFUNC(IsUnoStruct); extern RTLFUNC(FileDateTime); extern RTLFUNC(Format); extern RTLFUNC(GetAttr); extern RTLFUNC(Randomize); // JSM extern RTLFUNC(Round); extern RTLFUNC(Rnd); extern RTLFUNC(Shell); extern RTLFUNC(VarType); extern RTLFUNC(TypeName); extern RTLFUNC(TypeLen); extern RTLFUNC(EOF); extern RTLFUNC(FileAttr); extern RTLFUNC(Loc); extern RTLFUNC(Lof); extern RTLFUNC(Seek); extern RTLFUNC(SetAttr); // JSM extern RTLFUNC(Reset); // JSM extern RTLFUNC(DDEInitiate); extern RTLFUNC(DDETerminate); extern RTLFUNC(DDETerminateAll); extern RTLFUNC(DDERequest); extern RTLFUNC(DDEExecute); extern RTLFUNC(DDEPoke); extern RTLFUNC(FreeFile); extern RTLFUNC(IsMissing); extern RTLFUNC(LBound); extern RTLFUNC(UBound); extern RTLFUNC(RGB); extern RTLFUNC(QBColor); extern RTLFUNC(StrConv); extern RTLFUNC(Beep); extern RTLFUNC(Load); extern RTLFUNC(Unload); extern RTLFUNC(AboutStarBasic); extern RTLFUNC(LoadPicture); extern RTLFUNC(SavePicture); extern RTLFUNC(CBool); // JSM extern RTLFUNC(CByte); // JSM extern RTLFUNC(CCur); // JSM extern RTLFUNC(CDate); // JSM extern RTLFUNC(CDbl); // JSM extern RTLFUNC(CInt); // JSM extern RTLFUNC(CLng); // JSM extern RTLFUNC(CSng); // JSM extern RTLFUNC(CStr); // JSM extern RTLFUNC(CVar); // JSM extern RTLFUNC(CVErr); // JSM extern RTLFUNC(Iif); // JSM extern RTLFUNC(DumpAllObjects); extern RTLFUNC(GetSystemType); extern RTLFUNC(GetGUIType); extern RTLFUNC(Red); extern RTLFUNC(Green); extern RTLFUNC(Blue); extern RTLFUNC(Switch); extern RTLFUNC(Wait); //i#64882# add new WaitUntil extern RTLFUNC(WaitUntil); extern RTLFUNC(GetGUIVersion); extern RTLFUNC(Choose); extern RTLFUNC(Trim); extern RTLFUNC(DateAdd); extern RTLFUNC(DateDiff); extern RTLFUNC(DatePart); extern RTLFUNC(FormatDateTime); extern RTLFUNC(GetSolarVersion); extern RTLFUNC(TwipsPerPixelX); extern RTLFUNC(TwipsPerPixelY); extern RTLFUNC(FreeLibrary); extern RTLFUNC(Array); extern RTLFUNC(FindObject); extern RTLFUNC(FindPropertyObject); extern RTLFUNC(EnableReschedule); extern RTLFUNC(Put); extern RTLFUNC(Get); extern RTLFUNC(Environ); extern RTLFUNC(GetDialogZoomFactorX); extern RTLFUNC(GetDialogZoomFactorY); extern RTLFUNC(GetSystemTicks); extern RTLFUNC(GetPathSeparator); extern RTLFUNC(ResolvePath); extern RTLFUNC(CreateUnoStruct); extern RTLFUNC(CreateUnoService); extern RTLFUNC(CreateUnoValue); extern RTLFUNC(GetProcessServiceManager); extern RTLFUNC(GetDefaultContext); extern RTLFUNC(CreatePropertySet); extern RTLFUNC(CreateUnoListener); extern RTLFUNC(HasUnoInterfaces); extern RTLFUNC(EqualUnoObjects); extern RTLFUNC(CreateUnoDialog); extern RTLFUNC(GlobalScope); extern RTLFUNC(FileExists); extern RTLFUNC(ConvertToUrl); extern RTLFUNC(ConvertFromUrl); extern RTLFUNC(CDateToIso); extern RTLFUNC(CDateFromIso); extern RTLFUNC(CompatibilityMode); extern RTLFUNC(CDec); extern RTLFUNC(Partition); // Fong extern double Now_Impl(); extern void Wait_Impl( bool bDurationBased, SbxArray& rPar ); <|endoftext|>
<commit_before>/** * @file winmmshim.cpp * @brief controls volume level of process by intercepting calls to winmm.dll * * $LicenseInfo:firstyear=2010&license=viewerlgpl$ * Second Life Viewer Source Code * Copyright (C) 2010, Linden Research, Inc. * * 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; * version 2.1 of the License only. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA * $/LicenseInfo$ */ #include "forwarding_api.h" #include <xmmintrin.h> #include <map> #include <math.h> using std::wstring; static float sVolumeLevel = 1.f; static bool sMute = false; static CRITICAL_SECTION sCriticalSection; BOOL APIENTRY DllMain( HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReserved ) { InitializeCriticalSectionAndSpinCount(&sCriticalSection, 0x00000400); return TRUE; } void ll_winmm_shim_initialize(){ static bool initialized = false; // do this only once EnterCriticalSection(&sCriticalSection); if (!initialized) { // bind to original winmm.dll TCHAR system_path[MAX_PATH]; TCHAR dll_path[MAX_PATH]; ::GetSystemDirectory(system_path, MAX_PATH); // grab winmm.dll from system path, where it should live wsprintf(dll_path, "%s\\winmm.dll", system_path); HMODULE winmm_handle = ::LoadLibrary(dll_path); if (winmm_handle != NULL) { // we have a dll, let's get out pointers! initialized = true; init_function_pointers(winmm_handle); ::OutputDebugStringA("WINMM_SHIM.DLL: real winmm.dll initialized successfully\n"); return; } // failed to initialize real winmm.dll ::OutputDebugStringA("WINMM_SHIM.DLL: Failed to initialize real winmm.dll\n"); } LeaveCriticalSection(&sCriticalSection); } extern "C" { // tracks the requested format for a given waveout buffer struct WaveOutFormat { WaveOutFormat(int bits_per_sample) : mBitsPerSample(bits_per_sample) {} int mBitsPerSample; }; typedef std::map<HWAVEOUT, WaveOutFormat*> wave_out_map_t; static wave_out_map_t sWaveOuts; MMRESULT WINAPI waveOutOpen( LPHWAVEOUT phwo, UINT uDeviceID, LPCWAVEFORMATEX pwfx, DWORD_PTR dwCallback, DWORD_PTR dwInstance, DWORD fdwOpen) { ll_winmm_shim_initialize(); if (pwfx->wFormatTag != WAVE_FORMAT_PCM || (pwfx->wBitsPerSample != 8 && pwfx->wBitsPerSample != 16)) { // uncompressed 8 and 16 bit sound are the only types we support return WAVERR_BADFORMAT; } MMRESULT result = waveOutOpen_orig(phwo, uDeviceID, pwfx, dwCallback, dwInstance, fdwOpen); if (result == MMSYSERR_NOERROR && ((fdwOpen & WAVE_FORMAT_QUERY) == 0)) // not just querying for format support { // remember the requested bits per sample, and associate with the given handle WaveOutFormat* wave_outp = new WaveOutFormat(pwfx->wBitsPerSample); sWaveOuts.insert(std::make_pair(*phwo, wave_outp)); } return result; } MMRESULT WINAPI waveOutClose( HWAVEOUT hwo) { ll_winmm_shim_initialize(); wave_out_map_t::iterator found_it = sWaveOuts.find(hwo); if (found_it != sWaveOuts.end()) { // forget what we know about this handle delete found_it->second; sWaveOuts.erase(found_it); } return waveOutClose_orig( hwo); } MMRESULT WINAPI waveOutWrite( HWAVEOUT hwo, LPWAVEHDR pwh, UINT cbwh) { ll_winmm_shim_initialize(); MMRESULT result = MMSYSERR_NOERROR; if (sMute) { // zero out the audio buffer when muted memset(pwh->lpData, 0, pwh->dwBufferLength); } else if (sVolumeLevel != 1.f) { // need to apply volume level wave_out_map_t::iterator found_it = sWaveOuts.find(hwo); if (found_it != sWaveOuts.end()) { WaveOutFormat* formatp = found_it->second; switch (formatp->mBitsPerSample){ case 8: { char volume = (char)(sVolumeLevel * 127.f); for (unsigned int i = 0; i < pwh->dwBufferLength; i++) { // unsigned multiply doesn't use most significant bit, so shift by 7 bits // to get resulting value back into 8 bits pwh->lpData[i] = (pwh->lpData[i] * volume) >> 7; } break; } case 16: { short volume_16 = (short)(sVolumeLevel * 32767.f); // copy volume level 4 times into 64 bit MMX register __m64 volume_64 = _mm_set_pi16(volume_16, volume_16, volume_16, volume_16); __m64* sample_64; __m64* last_sample_64 = (__m64*)(pwh->lpData + pwh->dwBufferLength - sizeof(__m64)); // for everything that can be addressed in 64 bit multiples... for (sample_64 = (__m64*)pwh->lpData; sample_64 <= last_sample_64; ++sample_64) { //...multiply the samples by the volume... __m64 scaled_sample = _mm_mulhi_pi16(*sample_64, volume_64); // ...and shift left 1 bit since an unsigned multiple loses the most significant bit // 0x7FFF * 0x7FFF = 0x3fff0001 // 0x3fff0001 << 1 = 0x7ffe0002 // notice that the LSB is always 0...should consider dithering *sample_64 = _mm_slli_pi16(scaled_sample, 1); } // the captain has turned off the MMX sign, you are now free to use floating point registers _mm_empty(); // finish remaining samples that didn't fit into 64 bit register for (short* sample_16 = (short*)sample_64; sample_16 < (short*)(pwh->lpData + pwh->dwBufferLength); ++sample_16) { *sample_16 = (*sample_16 * volume_16) >> 15; } break; } default: // don't do anything break; } } } return waveOutWrite_orig( hwo, pwh, cbwh); } void WINAPI setPluginVolume(float volume) { sVolumeLevel = volume; } void WINAPI setPluginMute(bool mute) { sMute = mute; } } <commit_msg>STORM-1088: corrected fix loading of winmm.dll<commit_after>/** * @file winmmshim.cpp * @brief controls volume level of process by intercepting calls to winmm.dll * * $LicenseInfo:firstyear=2010&license=viewerlgpl$ * Second Life Viewer Source Code * Copyright (C) 2010, Linden Research, Inc. * * 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; * version 2.1 of the License only. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA * $/LicenseInfo$ */ #include "forwarding_api.h" #include <xmmintrin.h> #include <map> #include <math.h> using std::wstring; static float sVolumeLevel = 1.f; static bool sMute = false; static CRITICAL_SECTION sCriticalSection; BOOL APIENTRY DllMain( HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReserved ) { InitializeCriticalSection(&sCriticalSection); return TRUE; } void ll_winmm_shim_initialize(){ static bool initialized = false; // do this only once EnterCriticalSection(&sCriticalSection); if (!initialized) { // bind to original winmm.dll TCHAR system_path[MAX_PATH]; TCHAR dll_path[MAX_PATH]; ::GetSystemDirectory(system_path, MAX_PATH); // grab winmm.dll from system path, where it should live wsprintf(dll_path, "%s\\winmm.dll", system_path); HMODULE winmm_handle = ::LoadLibrary(dll_path); if (winmm_handle != NULL) { // we have a dll, let's get out pointers! initialized = true; init_function_pointers(winmm_handle); ::OutputDebugStringA("WINMM_SHIM.DLL: real winmm.dll initialized successfully\n"); } else { // failed to initialize real winmm.dll ::OutputDebugStringA("WINMM_SHIM.DLL: Failed to initialize real winmm.dll\n"); } } LeaveCriticalSection(&sCriticalSection); } extern "C" { // tracks the requested format for a given waveout buffer struct WaveOutFormat { WaveOutFormat(int bits_per_sample) : mBitsPerSample(bits_per_sample) {} int mBitsPerSample; }; typedef std::map<HWAVEOUT, WaveOutFormat*> wave_out_map_t; static wave_out_map_t sWaveOuts; MMRESULT WINAPI waveOutOpen( LPHWAVEOUT phwo, UINT uDeviceID, LPCWAVEFORMATEX pwfx, DWORD_PTR dwCallback, DWORD_PTR dwInstance, DWORD fdwOpen) { ll_winmm_shim_initialize(); if (pwfx->wFormatTag != WAVE_FORMAT_PCM || (pwfx->wBitsPerSample != 8 && pwfx->wBitsPerSample != 16)) { // uncompressed 8 and 16 bit sound are the only types we support return WAVERR_BADFORMAT; } MMRESULT result = waveOutOpen_orig(phwo, uDeviceID, pwfx, dwCallback, dwInstance, fdwOpen); if (result == MMSYSERR_NOERROR && ((fdwOpen & WAVE_FORMAT_QUERY) == 0)) // not just querying for format support { // remember the requested bits per sample, and associate with the given handle WaveOutFormat* wave_outp = new WaveOutFormat(pwfx->wBitsPerSample); sWaveOuts.insert(std::make_pair(*phwo, wave_outp)); } return result; } MMRESULT WINAPI waveOutClose( HWAVEOUT hwo) { ll_winmm_shim_initialize(); wave_out_map_t::iterator found_it = sWaveOuts.find(hwo); if (found_it != sWaveOuts.end()) { // forget what we know about this handle delete found_it->second; sWaveOuts.erase(found_it); } return waveOutClose_orig( hwo); } MMRESULT WINAPI waveOutWrite( HWAVEOUT hwo, LPWAVEHDR pwh, UINT cbwh) { ll_winmm_shim_initialize(); MMRESULT result = MMSYSERR_NOERROR; if (sMute) { // zero out the audio buffer when muted memset(pwh->lpData, 0, pwh->dwBufferLength); } else if (sVolumeLevel != 1.f) { // need to apply volume level wave_out_map_t::iterator found_it = sWaveOuts.find(hwo); if (found_it != sWaveOuts.end()) { WaveOutFormat* formatp = found_it->second; switch (formatp->mBitsPerSample){ case 8: { char volume = (char)(sVolumeLevel * 127.f); for (unsigned int i = 0; i < pwh->dwBufferLength; i++) { // unsigned multiply doesn't use most significant bit, so shift by 7 bits // to get resulting value back into 8 bits pwh->lpData[i] = (pwh->lpData[i] * volume) >> 7; } break; } case 16: { short volume_16 = (short)(sVolumeLevel * 32767.f); // copy volume level 4 times into 64 bit MMX register __m64 volume_64 = _mm_set_pi16(volume_16, volume_16, volume_16, volume_16); __m64* sample_64; __m64* last_sample_64 = (__m64*)(pwh->lpData + pwh->dwBufferLength - sizeof(__m64)); // for everything that can be addressed in 64 bit multiples... for (sample_64 = (__m64*)pwh->lpData; sample_64 <= last_sample_64; ++sample_64) { //...multiply the samples by the volume... __m64 scaled_sample = _mm_mulhi_pi16(*sample_64, volume_64); // ...and shift left 1 bit since an unsigned multiple loses the most significant bit // 0x7FFF * 0x7FFF = 0x3fff0001 // 0x3fff0001 << 1 = 0x7ffe0002 // notice that the LSB is always 0...should consider dithering *sample_64 = _mm_slli_pi16(scaled_sample, 1); } // the captain has turned off the MMX sign, you are now free to use floating point registers _mm_empty(); // finish remaining samples that didn't fit into 64 bit register for (short* sample_16 = (short*)sample_64; sample_16 < (short*)(pwh->lpData + pwh->dwBufferLength); ++sample_16) { *sample_16 = (*sample_16 * volume_16) >> 15; } break; } default: // don't do anything break; } } } return waveOutWrite_orig( hwo, pwh, cbwh); } void WINAPI setPluginVolume(float volume) { sVolumeLevel = volume; } void WINAPI setPluginMute(bool mute) { sMute = mute; } } <|endoftext|>
<commit_before>/*========================================================================= Program: Visualization Library Module: AppendP.cc Language: C++ Date: $Date$ Version: $Revision$ This file is part of the Visualization Library. No part of this file or its contents may be copied, reproduced or altered in any way without the express written consent of the authors. Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen 1993, 1994 =========================================================================*/ #include "AppendP.hh" vlAppendPolyData::vlAppendPolyData() { } vlAppendPolyData::~vlAppendPolyData() { } // Description: // Add a dataset to the list of data to append. void vlAppendPolyData::AddInput(vlPolyData *ds) { if ( ! this->InputList.IsItemPresent(ds) ) { this->Modified(); this->InputList.AddItem(ds); } } // Description: // Remove a dataset from the list of data to append. void vlAppendPolyData::RemoveInput(vlPolyData *ds) { if ( this->InputList.IsItemPresent(ds) ) { this->Modified(); this->InputList.RemoveItem(ds); } } void vlAppendPolyData::Update() { unsigned long int mtime, pdMtime; vlPolyData *pd; // make sure input is available if ( this->InputList.GetNumberOfItems() < 1 ) { vlErrorMacro(<< "No input!"); return; } // prevent chasing our tail if (this->Updating) return; this->Updating = 1; for (mtime=0, this->InputList.InitTraversal(); pd = this->InputList.GetNextItem(); ) { pd->Update(); pdMtime = pd->GetMTime(); if ( pdMtime > mtime ) mtime = pdMtime; } this->Updating = 0; if (mtime > this->GetMTime() || this->GetMTime() > this->ExecuteTime || this->GetDataReleased() ) { if ( this->StartMethod ) (*this->StartMethod)(this->StartMethodArg); this->Execute(); this->ExecuteTime.Modified(); this->SetDataReleased(0); if ( this->EndMethod ) (*this->EndMethod)(this->EndMethodArg); } for (this->InputList.InitTraversal(); pd = this->InputList.GetNextItem(); ) if ( pd->ShouldIReleaseData() ) pd->ReleaseData(); } // Append data sets into single unstructured grid void vlAppendPolyData::Execute() { int scalarsPresent, vectorsPresent, normalsPresent, tcoordsPresent; int tensorsPresent, userDefinedPresent; vlPolyData *ds; vlPoints *inPts; vlFloatPoints *newPts; vlCellArray *inVerts, *newVerts; vlCellArray *inLines, *newLines; vlCellArray *inPolys, *newPolys; vlCellArray *inStrips, *newStrips; int i, ptId, ptOffset; int numPts, numCells; vlPointData *pd; int npts, *pts, newPtIds[MAX_CELL_SIZE]; vlDebugMacro(<<"Appending data together"); this->Initialize(); // loop over all data sets, checking to see what point data is available. numPts = 0; numCells = 0; scalarsPresent = 1; vectorsPresent = 1; normalsPresent = 1; tcoordsPresent = 1; tensorsPresent = 1; userDefinedPresent = 1; for ( this->InputList.InitTraversal(); ds = this->InputList.GetNextItem(); ) { numPts += ds->GetNumberOfPoints(); numCells += ds->GetNumberOfCells(); pd = ds->GetPointData(); if ( pd->GetScalars() == NULL ) scalarsPresent &= 0; if ( pd->GetVectors() == NULL ) vectorsPresent &= 0; if ( pd->GetNormals() == NULL ) normalsPresent &= 0; if ( pd->GetTCoords() == NULL ) tcoordsPresent &= 0; if ( pd->GetTensors() == NULL ) tensorsPresent &= 0; if ( pd->GetUserDefined() == NULL ) userDefinedPresent &= 0; } if ( numPts < 1 || numCells < 1 ) { vlErrorMacro(<<"No data to append!"); return; } // Now can allocate memory if ( !scalarsPresent ) this->PointData.CopyScalarsOff(); if ( !vectorsPresent ) this->PointData.CopyVectorsOff(); if ( !normalsPresent ) this->PointData.CopyNormalsOff(); if ( !tcoordsPresent ) this->PointData.CopyTCoordsOff(); if ( !tensorsPresent ) this->PointData.CopyTensorsOff(); if ( !userDefinedPresent ) this->PointData.CopyUserDefinedOff(); this->PointData.CopyAllocate(pd,numPts); newPts = new vlFloatPoints(numPts); newVerts = new vlCellArray; newVerts->Allocate(numCells*4); newLines = new vlCellArray; newLines->Allocate(numCells*4); newPolys = new vlCellArray; newPolys->Allocate(numCells*4); newStrips = new vlCellArray; newStrips->Allocate(numCells*4); // loop over all input sets for ( ptOffset=0, this->InputList.InitTraversal(); ds = this->InputList.GetNextItem(); ptOffset+=numPts) { pd = ds->GetPointData(); numPts = ds->GetNumberOfPoints(); inPts = ds->GetPoints(); inVerts = ds->GetVerts(); inLines = ds->GetLines(); inPolys = ds->GetPolys(); inStrips = ds->GetStrips(); // copy points and point data for (ptId=0; ptId < numPts; ptId++) { newPts->SetPoint(ptId+ptOffset,inPts->GetPoint(ptId)); this->PointData.CopyData(pd,ptId,ptId+ptOffset); } for (inVerts->InitTraversal(); inVerts->GetNextCell(npts,pts); ) { for (i=0; i < npts; i++) newPtIds[i] = pts[i] + ptOffset; newVerts->InsertNextCell(npts,newPtIds); } for (inLines->InitTraversal(); inLines->GetNextCell(npts,pts); ) { for (i=0; i < npts; i++) newPtIds[i] = pts[i] + ptOffset; newLines->InsertNextCell(npts,newPtIds); } for (inPolys->InitTraversal(); inPolys->GetNextCell(npts,pts); ) { for (i=0; i < npts; i++) newPtIds[i] = pts[i] + ptOffset; newPolys->InsertNextCell(npts,newPtIds); } for (inStrips->InitTraversal(); inStrips->GetNextCell(npts,pts); ) { for (i=0; i < npts; i++) newPtIds[i] = pts[i] + ptOffset; newStrips->InsertNextCell(npts,newPtIds); } } // // Update ourselves // newVerts->Squeeze(); newLines->Squeeze(); newPolys->Squeeze(); newStrips->Squeeze(); this->SetPoints(newPts); this->SetVerts(newVerts); this->SetLines(newLines); this->SetPolys(newPolys); this->SetStrips(newStrips); } int vlAppendPolyData::GetDataReleased() { return this->DataReleased; } void vlAppendPolyData::SetDataReleased(int flag) { this->DataReleased = flag; } void vlAppendPolyData::PrintSelf(ostream& os, vlIndent indent) { vlPolyData::PrintSelf(os,indent); vlFilter::_PrintSelf(os,indent); os << indent << "Input DataSets:\n"; this->InputList.PrintSelf(os,indent.GetNextIndent()); } <commit_msg>*** empty log message ***<commit_after>/*========================================================================= Program: Visualization Library Module: AppendP.cc Language: C++ Date: $Date$ Version: $Revision$ This file is part of the Visualization Library. No part of this file or its contents may be copied, reproduced or altered in any way without the express written consent of the authors. Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen 1993, 1994 =========================================================================*/ #include "AppendP.hh" vlAppendPolyData::vlAppendPolyData() { } vlAppendPolyData::~vlAppendPolyData() { } // Description: // Add a dataset to the list of data to append. void vlAppendPolyData::AddInput(vlPolyData *ds) { if ( ! this->InputList.IsItemPresent(ds) ) { this->Modified(); this->InputList.AddItem(ds); } } // Description: // Remove a dataset from the list of data to append. void vlAppendPolyData::RemoveInput(vlPolyData *ds) { if ( this->InputList.IsItemPresent(ds) ) { this->Modified(); this->InputList.RemoveItem(ds); } } void vlAppendPolyData::Update() { unsigned long int mtime, pdMtime; vlPolyData *pd; // make sure input is available if ( this->InputList.GetNumberOfItems() < 1 ) { vlErrorMacro(<< "No input!"); return; } // prevent chasing our tail if (this->Updating) return; this->Updating = 1; for (mtime=0, this->InputList.InitTraversal(); pd = this->InputList.GetNextItem(); ) { pd->Update(); pdMtime = pd->GetMTime(); if ( pdMtime > mtime ) mtime = pdMtime; } this->Updating = 0; if (mtime > this->GetMTime() || this->GetMTime() > this->ExecuteTime || this->GetDataReleased() ) { if ( this->StartMethod ) (*this->StartMethod)(this->StartMethodArg); this->Execute(); this->ExecuteTime.Modified(); this->SetDataReleased(0); if ( this->EndMethod ) (*this->EndMethod)(this->EndMethodArg); } for (this->InputList.InitTraversal(); pd = this->InputList.GetNextItem(); ) if ( pd->ShouldIReleaseData() ) pd->ReleaseData(); } // Append data sets into single unstructured grid void vlAppendPolyData::Execute() { int scalarsPresent, vectorsPresent, normalsPresent, tcoordsPresent; int tensorsPresent, userDefinedPresent; vlPolyData *ds; vlPoints *inPts; vlFloatPoints *newPts; vlCellArray *inVerts, *newVerts; vlCellArray *inLines, *newLines; vlCellArray *inPolys, *newPolys; vlCellArray *inStrips, *newStrips; int i, ptId, ptOffset; int numPts, numCells; vlPointData *pd; int npts, *pts; vlDebugMacro(<<"Appending data together"); this->Initialize(); // loop over all data sets, checking to see what point data is available. numPts = 0; numCells = 0; scalarsPresent = 1; vectorsPresent = 1; normalsPresent = 1; tcoordsPresent = 1; tensorsPresent = 1; userDefinedPresent = 1; for ( this->InputList.InitTraversal(); ds = this->InputList.GetNextItem(); ) { numPts += ds->GetNumberOfPoints(); numCells += ds->GetNumberOfCells(); pd = ds->GetPointData(); if ( pd->GetScalars() == NULL ) scalarsPresent &= 0; if ( pd->GetVectors() == NULL ) vectorsPresent &= 0; if ( pd->GetNormals() == NULL ) normalsPresent &= 0; if ( pd->GetTCoords() == NULL ) tcoordsPresent &= 0; if ( pd->GetTensors() == NULL ) tensorsPresent &= 0; if ( pd->GetUserDefined() == NULL ) userDefinedPresent &= 0; } if ( numPts < 1 || numCells < 1 ) { vlErrorMacro(<<"No data to append!"); return; } // Now can allocate memory if ( !scalarsPresent ) this->PointData.CopyScalarsOff(); if ( !vectorsPresent ) this->PointData.CopyVectorsOff(); if ( !normalsPresent ) this->PointData.CopyNormalsOff(); if ( !tcoordsPresent ) this->PointData.CopyTCoordsOff(); if ( !tensorsPresent ) this->PointData.CopyTensorsOff(); if ( !userDefinedPresent ) this->PointData.CopyUserDefinedOff(); this->PointData.CopyAllocate(pd,numPts); newPts = new vlFloatPoints(numPts); newVerts = new vlCellArray; newVerts->Allocate(numCells*4); newLines = new vlCellArray; newLines->Allocate(numCells*4); newPolys = new vlCellArray; newPolys->Allocate(numCells*4); newStrips = new vlCellArray; newStrips->Allocate(numCells*4); // loop over all input sets for ( ptOffset=0, this->InputList.InitTraversal(); ds = this->InputList.GetNextItem(); ptOffset+=numPts) { pd = ds->GetPointData(); numPts = ds->GetNumberOfPoints(); inPts = ds->GetPoints(); inVerts = ds->GetVerts(); inLines = ds->GetLines(); inPolys = ds->GetPolys(); inStrips = ds->GetStrips(); // copy points and point data for (ptId=0; ptId < numPts; ptId++) { newPts->SetPoint(ptId+ptOffset,inPts->GetPoint(ptId)); this->PointData.CopyData(pd,ptId,ptId+ptOffset); } for (inVerts->InitTraversal(); inVerts->GetNextCell(npts,pts); ) { newVerts->InsertNextCell(npts); for (i=0; i < npts; i++) newVerts->InsertCellPoint(pts[i]+ptOffset); } for (inLines->InitTraversal(); inLines->GetNextCell(npts,pts); ) { newLines->InsertNextCell(npts); for (i=0; i < npts; i++) newLines->InsertCellPoint(pts[i]+ptOffset); } for (inPolys->InitTraversal(); inPolys->GetNextCell(npts,pts); ) { newPolys->InsertNextCell(npts); for (i=0; i < npts; i++) newPolys->InsertCellPoint(pts[i]+ptOffset); } for (inStrips->InitTraversal(); inStrips->GetNextCell(npts,pts); ) { newStrips->InsertNextCell(npts); for (i=0; i < npts; i++) newStrips->InsertCellPoint(pts[i]+ptOffset); } } // // Update ourselves // this->SetPoints(newPts); if ( newVerts->GetNumberOfCells() > 0 ) this->SetVerts(newVerts); else delete newVerts; if ( newLines->GetNumberOfCells() > 0 ) this->SetLines(newLines); else delete newLines; if ( newPolys->GetNumberOfCells() > 0 ) this->SetPolys(newPolys); else delete newPolys; if ( newStrips->GetNumberOfCells() > 0 ) this->SetStrips(newStrips); else delete newStrips; this->Squeeze(); } int vlAppendPolyData::GetDataReleased() { return this->DataReleased; } void vlAppendPolyData::SetDataReleased(int flag) { this->DataReleased = flag; } void vlAppendPolyData::PrintSelf(ostream& os, vlIndent indent) { vlPolyData::PrintSelf(os,indent); vlFilter::_PrintSelf(os,indent); os << indent << "Input DataSets:\n"; this->InputList.PrintSelf(os,indent.GetNextIndent()); } <|endoftext|>
<commit_before>/*************************************************************************/ /* audio_driver_javascript.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ /* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */ /* */ /* 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 "audio_driver_javascript.h" #include <emscripten.h> AudioDriverJavaScript *AudioDriverJavaScript::singleton = NULL; const char *AudioDriverJavaScript::get_name() const { return "JavaScript"; } extern "C" EMSCRIPTEN_KEEPALIVE void audio_driver_js_mix() { AudioDriverJavaScript::singleton->mix_to_js(); } extern "C" EMSCRIPTEN_KEEPALIVE void audio_driver_process_capture(float sample) { AudioDriverJavaScript::singleton->process_capture(sample); } void AudioDriverJavaScript::mix_to_js() { int channel_count = get_total_channels_by_speaker_mode(get_speaker_mode()); int sample_count = memarr_len(internal_buffer) / channel_count; int32_t *stream_buffer = reinterpret_cast<int32_t *>(internal_buffer); audio_server_process(sample_count, stream_buffer); for (int i = 0; i < sample_count * channel_count; i++) { internal_buffer[i] = float(stream_buffer[i] >> 16) / 32768.f; } } void AudioDriverJavaScript::process_capture(float sample) { int32_t sample32 = int32_t(sample * 32768.f) * (1U << 16); capture_buffer_write(sample32); } Error AudioDriverJavaScript::init() { /* clang-format off */ EM_ASM({ _audioDriver_audioContext = new (window.AudioContext || window.webkitAudioContext); _audioDriver_audioInput = null; _audioDriver_inputStream = null; _audioDriver_scriptNode = null; }); /* clang-format on */ int channel_count = get_total_channels_by_speaker_mode(get_speaker_mode()); /* clang-format off */ buffer_length = EM_ASM_INT({ var CHANNEL_COUNT = $0; var channelCount = _audioDriver_audioContext.destination.channelCount; try { // Try letting the browser recommend a buffer length. _audioDriver_scriptNode = _audioDriver_audioContext.createScriptProcessor(0, 2, channelCount); } catch (e) { // ...otherwise, default to 4096. _audioDriver_scriptNode = _audioDriver_audioContext.createScriptProcessor(4096, 2, channelCount); } _audioDriver_scriptNode.connect(_audioDriver_audioContext.destination); return _audioDriver_scriptNode.bufferSize; }, channel_count); /* clang-format on */ if (!buffer_length) { return FAILED; } if (!internal_buffer || (int)memarr_len(internal_buffer) != buffer_length * channel_count) { if (internal_buffer) memdelete_arr(internal_buffer); internal_buffer = memnew_arr(float, buffer_length *channel_count); } return internal_buffer ? OK : ERR_OUT_OF_MEMORY; } void AudioDriverJavaScript::start() { /* clang-format off */ EM_ASM({ var INTERNAL_BUFFER_PTR = $0; var audioDriverMixFunction = cwrap('audio_driver_js_mix'); var audioDriverProcessCapture = cwrap('audio_driver_process_capture', null, ['number']); _audioDriver_scriptNode.onaudioprocess = function(audioProcessingEvent) { audioDriverMixFunction(); var input = audioProcessingEvent.inputBuffer; var output = audioProcessingEvent.outputBuffer; var internalBuffer = HEAPF32.subarray( INTERNAL_BUFFER_PTR / HEAPF32.BYTES_PER_ELEMENT, INTERNAL_BUFFER_PTR / HEAPF32.BYTES_PER_ELEMENT + output.length * output.numberOfChannels); for (var channel = 0; channel < output.numberOfChannels; channel++) { var outputData = output.getChannelData(channel); // Loop through samples. for (var sample = 0; sample < outputData.length; sample++) { outputData[sample] = internalBuffer[sample * output.numberOfChannels + channel]; } } if (_audioDriver_audioInput) { var inputDataL = input.getChannelData(0); var inputDataR = input.getChannelData(1); for (var i = 0; i < inputDataL.length; i++) { audioDriverProcessCapture(inputDataL[i]); audioDriverProcessCapture(inputDataR[i]); } } }; }, internal_buffer); /* clang-format on */ } void AudioDriverJavaScript::resume() { /* clang-format off */ EM_ASM({ if (_audioDriver_audioContext.resume) _audioDriver_audioContext.resume(); }); /* clang-format on */ } int AudioDriverJavaScript::get_mix_rate() const { /* clang-format off */ return EM_ASM_INT_V({ return _audioDriver_audioContext.sampleRate; }); /* clang-format on */ } AudioDriver::SpeakerMode AudioDriverJavaScript::get_speaker_mode() const { /* clang-format off */ return get_speaker_mode_by_total_channels(EM_ASM_INT_V({ return _audioDriver_audioContext.destination.channelCount; })); /* clang-format on */ } // No locking, as threads are not supported. void AudioDriverJavaScript::lock() { } void AudioDriverJavaScript::unlock() { } void AudioDriverJavaScript::finish() { /* clang-format off */ EM_ASM({ _audioDriver_audioContext = null; _audioDriver_audioInput = null; _audioDriver_scriptNode = null; }); /* clang-format on */ if (internal_buffer) { memdelete_arr(internal_buffer); internal_buffer = NULL; } } Error AudioDriverJavaScript::capture_start() { capture_buffer_init(buffer_length); /* clang-format off */ EM_ASM({ function gotMediaInput(stream) { _audioDriver_inputStream = stream; _audioDriver_audioInput = _audioDriver_audioContext.createMediaStreamSource(stream); _audioDriver_audioInput.connect(_audioDriver_scriptNode); } function gotMediaInputError(e) { out(e); } if (navigator.mediaDevices.getUserMedia) { navigator.mediaDevices.getUserMedia({"audio": true}).then(gotMediaInput, gotMediaInputError); } else { if (!navigator.getUserMedia) navigator.getUserMedia = navigator.webkitGetUserMedia || navigator.mozGetUserMedia; navigator.getUserMedia({"audio": true}, gotMediaInput, gotMediaInputError); } }); /* clang-format on */ return OK; } Error AudioDriverJavaScript::capture_stop() { /* clang-format off */ EM_ASM({ if (_audioDriver_inputStream) { const tracks = _audioDriver_inputStream.getTracks(); for (var i = 0; i < tracks.length; i++) { tracks[i].stop(); } _audioDriver_inputStream = null; } if (_audioDriver_audioInput) { _audioDriver_audioInput.disconnect(); _audioDriver_audioInput = null; } }); /* clang-format on */ return OK; } AudioDriverJavaScript::AudioDriverJavaScript() { internal_buffer = NULL; singleton = this; } <commit_msg>Revert "Fix audio capture naming in Javascript"<commit_after>/*************************************************************************/ /* audio_driver_javascript.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ /* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */ /* */ /* 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 "audio_driver_javascript.h" #include <emscripten.h> AudioDriverJavaScript *AudioDriverJavaScript::singleton = NULL; const char *AudioDriverJavaScript::get_name() const { return "JavaScript"; } extern "C" EMSCRIPTEN_KEEPALIVE void audio_driver_js_mix() { AudioDriverJavaScript::singleton->mix_to_js(); } extern "C" EMSCRIPTEN_KEEPALIVE void audio_driver_process_capture(float sample) { AudioDriverJavaScript::singleton->process_capture(sample); } void AudioDriverJavaScript::mix_to_js() { int channel_count = get_total_channels_by_speaker_mode(get_speaker_mode()); int sample_count = memarr_len(internal_buffer) / channel_count; int32_t *stream_buffer = reinterpret_cast<int32_t *>(internal_buffer); audio_server_process(sample_count, stream_buffer); for (int i = 0; i < sample_count * channel_count; i++) { internal_buffer[i] = float(stream_buffer[i] >> 16) / 32768.f; } } void AudioDriverJavaScript::process_capture(float sample) { int32_t sample32 = int32_t(sample * 32768.f) * (1U << 16); input_buffer_write(sample32); } Error AudioDriverJavaScript::init() { /* clang-format off */ EM_ASM({ _audioDriver_audioContext = new (window.AudioContext || window.webkitAudioContext); _audioDriver_audioInput = null; _audioDriver_inputStream = null; _audioDriver_scriptNode = null; }); /* clang-format on */ int channel_count = get_total_channels_by_speaker_mode(get_speaker_mode()); /* clang-format off */ buffer_length = EM_ASM_INT({ var CHANNEL_COUNT = $0; var channelCount = _audioDriver_audioContext.destination.channelCount; try { // Try letting the browser recommend a buffer length. _audioDriver_scriptNode = _audioDriver_audioContext.createScriptProcessor(0, 2, channelCount); } catch (e) { // ...otherwise, default to 4096. _audioDriver_scriptNode = _audioDriver_audioContext.createScriptProcessor(4096, 2, channelCount); } _audioDriver_scriptNode.connect(_audioDriver_audioContext.destination); return _audioDriver_scriptNode.bufferSize; }, channel_count); /* clang-format on */ if (!buffer_length) { return FAILED; } if (!internal_buffer || (int)memarr_len(internal_buffer) != buffer_length * channel_count) { if (internal_buffer) memdelete_arr(internal_buffer); internal_buffer = memnew_arr(float, buffer_length *channel_count); } return internal_buffer ? OK : ERR_OUT_OF_MEMORY; } void AudioDriverJavaScript::start() { /* clang-format off */ EM_ASM({ var INTERNAL_BUFFER_PTR = $0; var audioDriverMixFunction = cwrap('audio_driver_js_mix'); var audioDriverProcessCapture = cwrap('audio_driver_process_capture', null, ['number']); _audioDriver_scriptNode.onaudioprocess = function(audioProcessingEvent) { audioDriverMixFunction(); var input = audioProcessingEvent.inputBuffer; var output = audioProcessingEvent.outputBuffer; var internalBuffer = HEAPF32.subarray( INTERNAL_BUFFER_PTR / HEAPF32.BYTES_PER_ELEMENT, INTERNAL_BUFFER_PTR / HEAPF32.BYTES_PER_ELEMENT + output.length * output.numberOfChannels); for (var channel = 0; channel < output.numberOfChannels; channel++) { var outputData = output.getChannelData(channel); // Loop through samples. for (var sample = 0; sample < outputData.length; sample++) { outputData[sample] = internalBuffer[sample * output.numberOfChannels + channel]; } } if (_audioDriver_audioInput) { var inputDataL = input.getChannelData(0); var inputDataR = input.getChannelData(1); for (var i = 0; i < inputDataL.length; i++) { audioDriverProcessCapture(inputDataL[i]); audioDriverProcessCapture(inputDataR[i]); } } }; }, internal_buffer); /* clang-format on */ } void AudioDriverJavaScript::resume() { /* clang-format off */ EM_ASM({ if (_audioDriver_audioContext.resume) _audioDriver_audioContext.resume(); }); /* clang-format on */ } int AudioDriverJavaScript::get_mix_rate() const { /* clang-format off */ return EM_ASM_INT_V({ return _audioDriver_audioContext.sampleRate; }); /* clang-format on */ } AudioDriver::SpeakerMode AudioDriverJavaScript::get_speaker_mode() const { /* clang-format off */ return get_speaker_mode_by_total_channels(EM_ASM_INT_V({ return _audioDriver_audioContext.destination.channelCount; })); /* clang-format on */ } // No locking, as threads are not supported. void AudioDriverJavaScript::lock() { } void AudioDriverJavaScript::unlock() { } void AudioDriverJavaScript::finish() { /* clang-format off */ EM_ASM({ _audioDriver_audioContext = null; _audioDriver_audioInput = null; _audioDriver_scriptNode = null; }); /* clang-format on */ if (internal_buffer) { memdelete_arr(internal_buffer); internal_buffer = NULL; } } Error AudioDriverJavaScript::capture_start() { input_buffer_init(buffer_length); /* clang-format off */ EM_ASM({ function gotMediaInput(stream) { _audioDriver_inputStream = stream; _audioDriver_audioInput = _audioDriver_audioContext.createMediaStreamSource(stream); _audioDriver_audioInput.connect(_audioDriver_scriptNode); } function gotMediaInputError(e) { out(e); } if (navigator.mediaDevices.getUserMedia) { navigator.mediaDevices.getUserMedia({"audio": true}).then(gotMediaInput, gotMediaInputError); } else { if (!navigator.getUserMedia) navigator.getUserMedia = navigator.webkitGetUserMedia || navigator.mozGetUserMedia; navigator.getUserMedia({"audio": true}, gotMediaInput, gotMediaInputError); } }); /* clang-format on */ return OK; } Error AudioDriverJavaScript::capture_stop() { /* clang-format off */ EM_ASM({ if (_audioDriver_inputStream) { const tracks = _audioDriver_inputStream.getTracks(); for (var i = 0; i < tracks.length; i++) { tracks[i].stop(); } _audioDriver_inputStream = null; } if (_audioDriver_audioInput) { _audioDriver_audioInput.disconnect(); _audioDriver_audioInput = null; } }); /* clang-format on */ input_buffer.clear(); return OK; } AudioDriverJavaScript::AudioDriverJavaScript() { internal_buffer = NULL; singleton = this; } <|endoftext|>
<commit_before>/* vim: set sw=4 ts=4: */ /* * BindingConverter.cpp * Implements an AST Consumer that outputs clay bindings * */ #include <iostream> #include <sstream> #include <vector> using namespace std; #include "llvm/Config/config.h" #include "llvm/Support/raw_ostream.h" #include "clang/AST/ASTConsumer.h" #include "clang/AST/ASTContext.h" #include "clang/AST/Decl.h" #include "clang/AST/DeclGroup.h" #include "llvm/ADT/Triple.h" #include "BindingsConverter.h" using namespace clang; using namespace llvm; BindingsConverter::BindingsConverter(ostream& out) : out(out) { } string BindingsConverter::allocateName(const string &base) { if (!allocatedNames.count(base)) { allocatedNames.insert(base); return base; } unsigned i = 2; string s; while (true) { ostringstream out; out << base << i; s = out.str(); if (!allocatedNames.count(s)) break; ++i; } allocatedNames.insert(s); return s; } string BindingsConverter::convertBuiltinType(const BuiltinType *type) { switch (type->getKind()) { case BuiltinType::Void : return "Void"; case BuiltinType::Bool : return "Bool"; case BuiltinType::Char_U : return "CUChar"; case BuiltinType::UChar : return "CUChar"; case BuiltinType::UShort : return "UShort"; case BuiltinType::UInt : return "UInt"; case BuiltinType::ULong : return "CULong"; case BuiltinType::ULongLong : return "UInt64"; case BuiltinType::Char_S : return "CChar"; case BuiltinType::SChar : return "CChar"; case BuiltinType::Short : return "Short"; case BuiltinType::Int : return "Int"; case BuiltinType::Long : return "CLong"; case BuiltinType::LongLong : return "Int64"; case BuiltinType::Float : return "Float"; case BuiltinType::Double : return "Double"; default : { ostringstream out; out << type->getKind(); return "UnsupportedCBuiltinType" + out.str(); } } } static const char *getCodePointerConstructor(FunctionType *ft) { switch (ft->getCallConv()) { case CC_X86StdCall : return "StdCallCodePointer"; case CC_X86FastCall : return "FastCallCodePointer"; default : return "CCodePointer"; } } string BindingsConverter::convertFPType(FunctionNoProtoType *type) { const Type *rt = type->getResultType().getTypePtr(); ostringstream sout; sout << getCodePointerConstructor(type); sout << "["; sout << convertType(rt); sout << "]"; return sout.str(); } string BindingsConverter::convertFPType(FunctionProtoType *type) { ostringstream sout; sout << getCodePointerConstructor(type); sout << "["; FunctionProtoType::arg_type_iterator i, e; for (i = type->arg_type_begin(), e = type->arg_type_end(); i != e; ++i) { const Type *argType = i->getTypePtr(); sout << convertType(argType) << ","; } const Type *rt = type->getResultType().getTypePtr(); sout << convertType(rt) << "]"; return sout.str(); } string BindingsConverter::convertType(const Type *type) { const Type *ctype = type->getCanonicalTypeUnqualified().getTypePtr(); if (ctype->getTypeClass() == Type::Builtin) return convertBuiltinType((const BuiltinType *)ctype); switch (type->getTypeClass()) { case Type::Typedef : { TypedefType *t = (TypedefType *)type; TypedefDecl *decl = t->getDecl(); string name = decl->getName().str(); const string &outName = typedefNames[name]; assert(!outName.empty()); return outName; } case Type::Record : { RecordType *t = (RecordType *)type; RecordDecl *decl = t->getDecl(); if (decl->isUnion()) return "AUnionType"; string name = decl->getName().str(); if (name.empty()) { if (!anonRecordNames.count(decl)) { pendingAnonRecords.push_back(decl); string outName = allocateName("UnnamedRecord"); anonRecordNames[decl] = outName; } return anonRecordNames[decl]; } if (recordBodies.count(name)) { return recordNames[name]; } return "Opaque"; } case Type::Enum : return "Int"; case Type::Pointer : { PointerType *t = (PointerType *)type; const Type *pt = t->getPointeeType().getTypePtr(); const Type *pt2 = pt->getCanonicalTypeUnqualified().getTypePtr(); switch (pt2->getTypeClass()) { case Type::FunctionNoProto : return convertFPType((FunctionNoProtoType *)pt2); case Type::FunctionProto : return convertFPType((FunctionProtoType *)pt2); default : break; } if (pt->getTypeClass() == Type::Record) { RecordType *rt = (RecordType *)pt; RecordDecl *decl = rt->getDecl(); string name = decl->getName().str(); if (!name.empty() && !recordBodies.count(name)) return "OpaquePointer"; } string inner = convertType(pt); if (inner == "Void") return "RawPointer"; return "Pointer[" + inner + "]"; } case Type::ConstantArray : { ConstantArrayType *t = (ConstantArrayType *)type; ostringstream sout; sout << "Array[" << convertType(t->getElementType().getTypePtr()); sout << "," << t->getSize().getZExtValue() << "]"; return sout.str(); } case Type::IncompleteArray : { IncompleteArrayType *t = (IncompleteArrayType *)type; const Type *et = t->getElementType().getTypePtr(); return "Array[" + convertType(et) + ",0]"; } default : { string str = type->getCanonicalTypeInternal().getAsString(); cerr << "unknown type: " << str << '\n'; return "UnknownType"; } } } // Handle top level declarations observed in the program void BindingsConverter::HandleTopLevelDecl(DeclGroupRef DG) { for (DeclGroupRef::iterator it = DG.begin(); it != DG.end(); ++it) { Decl *decl = *it; decls.push_back(decl); switch (decl->getKind()) { case Decl::Record : { RecordDecl *x = (RecordDecl *)decl; string name = x->getName().str(); if (!x->isUnion() && x->isDefinition()) { if (name.empty()) { string outName = allocateName("UnnamedStruct"); anonRecordNames[x] = outName; } else { assert(!recordBodies.count(name)); recordBodies[name] = x; string outName = allocateName("Struct_" + name); recordNames[name] = outName; } } break; } case Decl::Typedef : { TypedefDecl *x = (TypedefDecl *)decl; const Type *t = x->getTypeSourceInfo()->getType().getTypePtr(); if (!t->isFunctionType()) { string name = x->getName().str(); string outName = allocateName(name); typedefNames[name] = outName; } break; } default : break; } } } void BindingsConverter::generate() { generateHeader(); unsigned i = 0; while ((pendingAnonRecords.size() > 0) || (i < decls.size())) { if (pendingAnonRecords.size() > 0) { vector<RecordDecl*> pending = pendingAnonRecords; pendingAnonRecords.clear(); for (unsigned j = 0; j < pending.size(); ++j) generateDecl(pending[j]); } else if (i < decls.size()) { generateDecl(decls[i]); ++i; } } } void BindingsConverter::generateDecl(Decl *decl) { switch (decl->getKind()) { case Decl::Typedef : { TypedefDecl *x = (TypedefDecl *)decl; string name = x->getName().str(); const Type *t = x->getTypeSourceInfo()->getType().getTypePtr(); if (!t->isFunctionType()) { string type = convertType(t); out << '\n'; out << "static " << typedefNames[name] << " = " << convertType(t) << ";" << '\n'; } break; } case Decl::Enum : { EnumDecl *x = (EnumDecl *)decl; EnumDecl::enumerator_iterator i = x->enumerator_begin(); EnumDecl::enumerator_iterator e = x->enumerator_end(); out << '\n'; for (; i != e; ++i) { EnumConstantDecl *y = *i; out << "static " << y->getName().str() << " = " << y->getInitVal().getZExtValue() << ";\n"; } break; } case Decl::Record : { RecordDecl *x = (RecordDecl *)decl; string name = x->getName().str(); if (!x->isUnion() && x->isDefinition()) { string outName = name.empty() ? anonRecordNames[x] : recordNames[name]; out << '\n'; out << "record " << outName << " {\n"; RecordDecl::field_iterator i, e; int index = 0; for (i = x->field_begin(), e = x->field_end(); i != e; ++i) { FieldDecl *y = *i; string fname = y->getName().str(); const Type *t = y->getType().getTypePtr(); out << " "; if (fname.empty()) out << "unnamed_field" << index; else out << fname; out << " : " << convertType(t) << ";\n"; ++index; } out << "}\n"; } break; } case Decl::Function : { FunctionDecl *x = (FunctionDecl *)decl; string name = x->getName().str(); if (!x->isThisDeclarationADefinition() && !x->isInlineSpecified() && (x->getStorageClass() == FunctionDecl::Extern || x->getStorageClass() == FunctionDecl::None) && !externsDeclared.count(name)) { externsDeclared.insert(name); out << '\n'; out << "external "; bool attrDLLImport = x->hasAttr<DLLImportAttr>(); bool attrDLLExport = x->hasAttr<DLLExportAttr>(); const Type *t = x->getType().getTypePtr(); assert(t->isFunctionType()); FunctionType *ft = (FunctionType *)t; bool attrStdCall = ft->getCallConv() == CC_X86StdCall; bool attrFastCall = ft->getCallConv() == CC_X86FastCall; if (attrDLLImport || attrDLLExport || attrStdCall || attrFastCall) { out << "("; bool first = true; if (attrDLLImport) { if (first) first = false; else out << ","; out << "dllimport"; } if (attrDLLExport) { if (first) first = false; else out << ","; out << "dllexport"; } if (attrStdCall) { if (first) first = false; else out << ","; out << "stdcall"; } if (attrFastCall) { if (first) first = false; else out << ","; out << "fastcall"; } out << ") "; } out << name << "("; FunctionDecl::param_iterator i, e; int index = 0; for (i = x->param_begin(), e = x->param_end(); i != e; ++i) { ParmVarDecl *y = *i; string pname = y->getName().str(); if (index != 0) out << ","; out << "\n "; if (pname.empty()) out << "argument" << index; else out << pname; const Type *t = y->getType().getTypePtr(); out << " : " << convertType(t); ++index; } if (ft->getTypeClass() == Type::FunctionProto) { FunctionProtoType *fpt = (FunctionProtoType *)ft; if (fpt->isVariadic()) { if (index != 0) out << ","; out << "\n "; out << "..."; } } const Type *rt = x->getResultType().getTypePtr(); out << ") : " << convertType(rt) << ";\n"; } break; } case Decl::Var : { VarDecl *x = (VarDecl *)decl; string name = x->getName().str(); if ((x->getStorageClass() == VarDecl::Extern) && !x->hasInit() && !externsDeclared.count(name)) { externsDeclared.insert(name); const Type *t = x->getType().getTypePtr(); out << '\n'; out << "external "; bool attrDLLImport = x->hasAttr<DLLImportAttr>(); bool attrDLLExport = x->hasAttr<DLLExportAttr>(); if (attrDLLImport || attrDLLExport) { out << "("; bool first = true; if (attrDLLImport) { if (first) first = false; else out << ","; out << "dllimport"; } if (attrDLLExport) { if (first) first = false; else out << ","; out << "dllexport"; } out << ") "; } out << name << " : " << convertType(t) << ";\n"; } break; } default : break; } } void BindingsConverter::generateHeader() { out << "// Auto-Generated by BindingsGenerator\n"; out << '\n'; out << "import types.*;\n"; out << "import operators.*;\n"; out << "import numbers.*;\n"; out << "import pointers.*;\n"; out << '\n'; out << "private static OpaquePointer = RawPointer;\n"; out << "private static UnknownType = Int;\n"; out << "private static AUnionType = Int;\n"; out << '\n'; } <commit_msg>support asm labels in bindings generator.<commit_after>/* vim: set sw=4 ts=4: */ /* * BindingConverter.cpp * Implements an AST Consumer that outputs clay bindings * */ #include <iostream> #include <sstream> #include <vector> using namespace std; #include "llvm/Config/config.h" #include "llvm/Support/raw_ostream.h" #include "clang/AST/ASTConsumer.h" #include "clang/AST/ASTContext.h" #include "clang/AST/Decl.h" #include "clang/AST/DeclGroup.h" #include "llvm/ADT/Triple.h" #include "BindingsConverter.h" using namespace clang; using namespace llvm; BindingsConverter::BindingsConverter(ostream& out) : out(out) { } string BindingsConverter::allocateName(const string &base) { if (!allocatedNames.count(base)) { allocatedNames.insert(base); return base; } unsigned i = 2; string s; while (true) { ostringstream out; out << base << i; s = out.str(); if (!allocatedNames.count(s)) break; ++i; } allocatedNames.insert(s); return s; } string BindingsConverter::convertBuiltinType(const BuiltinType *type) { switch (type->getKind()) { case BuiltinType::Void : return "Void"; case BuiltinType::Bool : return "Bool"; case BuiltinType::Char_U : return "CUChar"; case BuiltinType::UChar : return "CUChar"; case BuiltinType::UShort : return "UShort"; case BuiltinType::UInt : return "UInt"; case BuiltinType::ULong : return "CULong"; case BuiltinType::ULongLong : return "UInt64"; case BuiltinType::Char_S : return "CChar"; case BuiltinType::SChar : return "CChar"; case BuiltinType::Short : return "Short"; case BuiltinType::Int : return "Int"; case BuiltinType::Long : return "CLong"; case BuiltinType::LongLong : return "Int64"; case BuiltinType::Float : return "Float"; case BuiltinType::Double : return "Double"; default : { ostringstream out; out << type->getKind(); return "UnsupportedCBuiltinType" + out.str(); } } } static const char *getCodePointerConstructor(FunctionType *ft) { switch (ft->getCallConv()) { case CC_X86StdCall : return "StdCallCodePointer"; case CC_X86FastCall : return "FastCallCodePointer"; default : return "CCodePointer"; } } string BindingsConverter::convertFPType(FunctionNoProtoType *type) { const Type *rt = type->getResultType().getTypePtr(); ostringstream sout; sout << getCodePointerConstructor(type); sout << "["; sout << convertType(rt); sout << "]"; return sout.str(); } string BindingsConverter::convertFPType(FunctionProtoType *type) { ostringstream sout; sout << getCodePointerConstructor(type); sout << "["; FunctionProtoType::arg_type_iterator i, e; for (i = type->arg_type_begin(), e = type->arg_type_end(); i != e; ++i) { const Type *argType = i->getTypePtr(); sout << convertType(argType) << ","; } const Type *rt = type->getResultType().getTypePtr(); sout << convertType(rt) << "]"; return sout.str(); } string BindingsConverter::convertType(const Type *type) { const Type *ctype = type->getCanonicalTypeUnqualified().getTypePtr(); if (ctype->getTypeClass() == Type::Builtin) return convertBuiltinType((const BuiltinType *)ctype); switch (type->getTypeClass()) { case Type::Typedef : { TypedefType *t = (TypedefType *)type; TypedefDecl *decl = t->getDecl(); string name = decl->getName().str(); const string &outName = typedefNames[name]; assert(!outName.empty()); return outName; } case Type::Record : { RecordType *t = (RecordType *)type; RecordDecl *decl = t->getDecl(); if (decl->isUnion()) return "AUnionType"; string name = decl->getName().str(); if (name.empty()) { if (!anonRecordNames.count(decl)) { pendingAnonRecords.push_back(decl); string outName = allocateName("UnnamedRecord"); anonRecordNames[decl] = outName; } return anonRecordNames[decl]; } if (recordBodies.count(name)) { return recordNames[name]; } return "Opaque"; } case Type::Enum : return "Int"; case Type::Pointer : { PointerType *t = (PointerType *)type; const Type *pt = t->getPointeeType().getTypePtr(); const Type *pt2 = pt->getCanonicalTypeUnqualified().getTypePtr(); switch (pt2->getTypeClass()) { case Type::FunctionNoProto : return convertFPType((FunctionNoProtoType *)pt2); case Type::FunctionProto : return convertFPType((FunctionProtoType *)pt2); default : break; } if (pt->getTypeClass() == Type::Record) { RecordType *rt = (RecordType *)pt; RecordDecl *decl = rt->getDecl(); string name = decl->getName().str(); if (!name.empty() && !recordBodies.count(name)) return "OpaquePointer"; } string inner = convertType(pt); if (inner == "Void") return "RawPointer"; return "Pointer[" + inner + "]"; } case Type::ConstantArray : { ConstantArrayType *t = (ConstantArrayType *)type; ostringstream sout; sout << "Array[" << convertType(t->getElementType().getTypePtr()); sout << "," << t->getSize().getZExtValue() << "]"; return sout.str(); } case Type::IncompleteArray : { IncompleteArrayType *t = (IncompleteArrayType *)type; const Type *et = t->getElementType().getTypePtr(); return "Array[" + convertType(et) + ",0]"; } default : { string str = type->getCanonicalTypeInternal().getAsString(); cerr << "unknown type: " << str << '\n'; return "UnknownType"; } } } // Handle top level declarations observed in the program void BindingsConverter::HandleTopLevelDecl(DeclGroupRef DG) { for (DeclGroupRef::iterator it = DG.begin(); it != DG.end(); ++it) { Decl *decl = *it; decls.push_back(decl); switch (decl->getKind()) { case Decl::Record : { RecordDecl *x = (RecordDecl *)decl; string name = x->getName().str(); if (!x->isUnion() && x->isDefinition()) { if (name.empty()) { string outName = allocateName("UnnamedStruct"); anonRecordNames[x] = outName; } else { assert(!recordBodies.count(name)); recordBodies[name] = x; string outName = allocateName("Struct_" + name); recordNames[name] = outName; } } break; } case Decl::Typedef : { TypedefDecl *x = (TypedefDecl *)decl; const Type *t = x->getTypeSourceInfo()->getType().getTypePtr(); if (!t->isFunctionType()) { string name = x->getName().str(); string outName = allocateName(name); typedefNames[name] = outName; } break; } default : break; } } } void BindingsConverter::generate() { generateHeader(); unsigned i = 0; while ((pendingAnonRecords.size() > 0) || (i < decls.size())) { if (pendingAnonRecords.size() > 0) { vector<RecordDecl*> pending = pendingAnonRecords; pendingAnonRecords.clear(); for (unsigned j = 0; j < pending.size(); ++j) generateDecl(pending[j]); } else if (i < decls.size()) { generateDecl(decls[i]); ++i; } } } void BindingsConverter::generateDecl(Decl *decl) { switch (decl->getKind()) { case Decl::Typedef : { TypedefDecl *x = (TypedefDecl *)decl; string name = x->getName().str(); const Type *t = x->getTypeSourceInfo()->getType().getTypePtr(); if (!t->isFunctionType()) { string type = convertType(t); out << '\n'; out << "static " << typedefNames[name] << " = " << convertType(t) << ";" << '\n'; } break; } case Decl::Enum : { EnumDecl *x = (EnumDecl *)decl; EnumDecl::enumerator_iterator i = x->enumerator_begin(); EnumDecl::enumerator_iterator e = x->enumerator_end(); out << '\n'; for (; i != e; ++i) { EnumConstantDecl *y = *i; out << "static " << y->getName().str() << " = " << y->getInitVal().getZExtValue() << ";\n"; } break; } case Decl::Record : { RecordDecl *x = (RecordDecl *)decl; string name = x->getName().str(); if (!x->isUnion() && x->isDefinition()) { string outName = name.empty() ? anonRecordNames[x] : recordNames[name]; out << '\n'; out << "record " << outName << " {\n"; RecordDecl::field_iterator i, e; int index = 0; for (i = x->field_begin(), e = x->field_end(); i != e; ++i) { FieldDecl *y = *i; string fname = y->getName().str(); const Type *t = y->getType().getTypePtr(); out << " "; if (fname.empty()) out << "unnamed_field" << index; else out << fname; out << " : " << convertType(t) << ";\n"; ++index; } out << "}\n"; } break; } case Decl::Function : { FunctionDecl *x = (FunctionDecl *)decl; string name = x->getName().str(); if (!x->isThisDeclarationADefinition() && !x->isInlineSpecified() && (x->getStorageClass() == FunctionDecl::Extern || x->getStorageClass() == FunctionDecl::None) && !externsDeclared.count(name)) { externsDeclared.insert(name); out << '\n'; out << "external "; vector<string> attributes; if (x->hasAttr<DLLImportAttr>()) attributes.push_back("dllimport"); if (x->hasAttr<DLLExportAttr>()) attributes.push_back("dllexport"); const Type *t = x->getType().getTypePtr(); assert(t->isFunctionType()); FunctionType *ft = (FunctionType *)t; if (ft->getCallConv() == CC_X86StdCall) attributes.push_back("stdcall"); if (ft->getCallConv() == CC_X86FastCall) attributes.push_back("fastcall"); if (x->hasAttr<AsmLabelAttr>()) { const AsmLabelAttr *attr = x->getAttr<AsmLabelAttr>(); string asmLabel(attr->getLabel()); attributes.push_back("\"" + asmLabel + "\""); } if (!attributes.empty()) { out << "("; for (unsigned i = 0; i < attributes.size(); ++i) { if (i != 0) out << ", "; out << attributes[i]; } out << ") "; } out << name << "("; FunctionDecl::param_iterator i, e; int index = 0; for (i = x->param_begin(), e = x->param_end(); i != e; ++i) { ParmVarDecl *y = *i; string pname = y->getName().str(); if (index != 0) out << ","; out << "\n "; if (pname.empty()) out << "argument" << index; else out << pname; const Type *t = y->getType().getTypePtr(); out << " : " << convertType(t); ++index; } if (ft->getTypeClass() == Type::FunctionProto) { FunctionProtoType *fpt = (FunctionProtoType *)ft; if (fpt->isVariadic()) { if (index != 0) out << ","; out << "\n "; out << "..."; } } const Type *rt = x->getResultType().getTypePtr(); out << ") : " << convertType(rt) << ";\n"; } break; } case Decl::Var : { VarDecl *x = (VarDecl *)decl; string name = x->getName().str(); if ((x->getStorageClass() == VarDecl::Extern) && !x->hasInit() && !externsDeclared.count(name)) { externsDeclared.insert(name); const Type *t = x->getType().getTypePtr(); out << '\n'; out << "external "; vector<string> attributes; if (x->hasAttr<DLLImportAttr>()) attributes.push_back("dllimport"); if (x->hasAttr<DLLExportAttr>()) attributes.push_back("dllexport"); if (!attributes.empty()) { out << "("; for (unsigned i = 0; i < attributes.size(); ++i) { if (i != 0) out << ", "; out << attributes[i]; } out << ") "; } out << name << " : " << convertType(t) << ";\n"; } break; } default : break; } } void BindingsConverter::generateHeader() { out << "// Auto-Generated by BindingsGenerator\n"; out << '\n'; out << "import types.*;\n"; out << "import operators.*;\n"; out << "import numbers.*;\n"; out << "import pointers.*;\n"; out << '\n'; out << "private static OpaquePointer = RawPointer;\n"; out << "private static UnknownType = Int;\n"; out << "private static AUnionType = Int;\n"; out << '\n'; } <|endoftext|>
<commit_before>// Copyright Andrew Resch 2008. Use, modification and distribution is // subject to the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #include <libtorrent/ip_filter.hpp> #include <boost/python.hpp> #include "gil.hpp" using namespace boost::python; using namespace libtorrent; namespace { void add_rule(ip_filter& filter, std::string start, std::string end, int flags) { return filter.add_rule(address::from_string(start), address::from_string(end), flags); } int _access(ip_filter& filter, std::string addr) { return filter.access(address::from_string(addr)); } } void bind_ip_filter() { class_<ip_filter>("ip_filter") .def("add_rule", add_rule) .def("access", _access) .def("export_filter", allow_threads(&ip_filter::export_filter)) ; } <commit_msg>Fix building in windows<commit_after>// Copyright Andrew Resch 2008. Use, modification and distribution is // subject to the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #include <libtorrent/ip_filter.hpp> #include <boost/python.hpp> #include "gil.hpp" using namespace boost::python; using namespace libtorrent; namespace { void add_rule(ip_filter& filter, std::string start, std::string end, int flags) { return filter.add_rule(address::from_string(start), address::from_string(end), flags); } int access0(ip_filter& filter, std::string addr) { return filter.access(address::from_string(addr)); } } void bind_ip_filter() { class_<ip_filter>("ip_filter") .def("add_rule", add_rule) .def("access", access0) .def("export_filter", allow_threads(&ip_filter::export_filter)) ; } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: viewaccess.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: rt $ $Date: 2003-04-17 13:33:29 $ * * 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 CONFIGMGR_VIEWACCESS_HXX_ #define CONFIGMGR_VIEWACCESS_HXX_ #ifndef CONFIGMGR_VIEWNODE_HXX_ #include "viewnode.hxx" #endif #ifndef CONFIGMGR_VIEWBEHAVIOR_HXX_ #include "viewstrategy.hxx" #endif #ifndef _RTL_REF_HXX_ #include <rtl/ref.hxx> #endif //----------------------------------------------------------------------------- namespace configmgr { //----------------------------------------------------------------------------- namespace configuration { class NodeRef; } //----------------------------------------------------------------------------- namespace view { //----------------------------------------------------------------------------- class ViewTreeAccess { rtl::Reference< ViewStrategy > m_xStrategy; Tree m_aTree; private: data::Accessor accessor() const { return m_aTree.accessor(); } public: explicit ViewTreeAccess(Tree const & _aTree); ViewTreeAccess(data::Accessor const & _aAccessor, configuration::TreeImpl& _rTree); rtl::Reference< view::ViewStrategy > getViewBehavior() { return m_xStrategy; } public: typedef configuration::NodeRef const& NodeArg; typedef configuration::NodeOffset NodeOffset; configuration::NodeData* nodeData(NodeArg _aNodeArg) const; configuration::NodeData* nodeData(NodeOffset _aNodePos) const; bool isValid(NodeArg _aNodeArg) const; Node makeNode(NodeArg _aNodeArg) const { return Node(m_aTree,nodeData(_aNodeArg)); } Node makeNode(NodeOffset _aNodePos) const { return Node(m_aTree,nodeData(_aNodePos)); } bool isSetNode (NodeArg _aNodeArg) const { return makeNode(_aNodeArg).isSetNode(); } bool isGroupNode(NodeArg _aNodeArg) const { return makeNode(_aNodeArg).isGroupNode(); } bool isValueNode(NodeArg _aNodeArg) const { return makeNode(_aNodeArg).isValueNode(); } bool isSetNodeAt (NodeOffset _aNodeArg) const { return makeNode(_aNodeArg).isSetNode(); } bool isGroupNodeAt(NodeOffset _aNodeArg) const { return makeNode(_aNodeArg).isGroupNode(); } bool isValueNodeAt(NodeOffset _aNodeArg) const { return makeNode(_aNodeArg).isValueNode(); } SetNode toSetNode (NodeArg _aNodeArg) const { return SetNode (makeNode(_aNodeArg)); } GroupNode toGroupNode(NodeArg _aNodeArg) const { return GroupNode(makeNode(_aNodeArg)); } ValueNode toValueNode(NodeArg _aNodeArg) const { return ValueNode(makeNode(_aNodeArg)); } SetNode getSetNodeAt (NodeOffset _aNodeArg) const { return SetNode (makeNode(_aNodeArg)); } GroupNode getGroupNodeAt(NodeOffset _aNodeArg) const { return GroupNode(makeNode(_aNodeArg)); } ValueNode getValueNodeAt(NodeOffset _aNodeArg) const { return ValueNode(makeNode(_aNodeArg)); } // node attributes public: /// retrieve the name of the node Name getName(NodeArg _aNode) const { return m_xStrategy->getName(makeNode(_aNode)); } /// retrieve the attributes of the node node::Attributes getAttributes(NodeArg _aNode) const { return m_xStrategy->getAttributes(makeNode(_aNode)); } /// retrieve the name of the tree root Name getRootName() const { return m_xStrategy->getName( getRootNode(m_aTree) ); } /// retrieve the attributes of the tree root node::Attributes getRootAttributes() const { return m_xStrategy->getAttributes( getRootNode(m_aTree) ); } // tracking pending changes public: void collectChanges(configuration::NodeChanges& rChanges) const { m_xStrategy->collectChanges(m_aTree,rChanges); } bool hasChanges() const { return m_xStrategy->hasChanges(m_aTree); } bool hasChanges(NodeArg _aNode) const { return m_xStrategy->hasChanges(makeNode(_aNode)); } void markChanged(NodeArg _aNode) { m_xStrategy->markChanged(makeNode(_aNode)); } // commit protocol public: std::auto_ptr<SubtreeChange> preCommitChanges(configuration::ElementList& _rRemovedElements) { return m_xStrategy->preCommitChanges(m_aTree,_rRemovedElements); } void finishCommit(SubtreeChange& rRootChange) { m_xStrategy->finishCommit(m_aTree,rRootChange); } void revertCommit(SubtreeChange& rRootChange) { m_xStrategy->revertCommit(m_aTree,rRootChange); } void recoverFailedCommit(SubtreeChange& rRootChange) { m_xStrategy->recoverFailedCommit(m_aTree,rRootChange); } // notification protocol public: /// Adjust the internal representation after external changes to the original data - build NodeChangeInformation objects for notification void adjustToChanges(configuration::NodeChangesInformation& rLocalChanges, NodeArg _aNode, SubtreeChange const& aExternalChange) { m_xStrategy->adjustToChanges(rLocalChanges,makeNode(_aNode), aExternalChange); } // visitor dispatch public: configuration::GroupMemberVisitor::Result dispatchToValues(GroupNode const& _aNode, configuration::GroupMemberVisitor& _aVisitor) const { return m_xStrategy->dispatchToValues(_aNode,_aVisitor); } /// Call <code>aVisitor.visit(aElement)</code> for each element in this set until SetNodeVisitor::DONE is returned. configuration::SetNodeVisitor::Result dispatchToElements(SetNode const& _aNode, configuration::SetNodeVisitor& _aVisitor) const { return m_xStrategy->dispatchToElements(_aNode,_aVisitor); } // value (element) node specific operations public: /// Does this node assume its default value /// retrieve the current value of this node UnoAny getValue(ValueNode const& _aNode) const { return m_xStrategy->getValue(_aNode); } /// get the type of this value UnoType getValueType(ValueNode const& _aNode) const { return m_xStrategy->getValueType(_aNode); } // group node specific operations public: /// does this hold a child value of the given name bool hasValue(GroupNode const& _aNode, Name const& _aName) const { return m_xStrategy->hasValue(_aNode,_aName); } /// does this hold a child value bool hasValue(GroupNode const& _aNode) const { return m_xStrategy->hasValue(_aNode); } /// are defaults for this node available ? bool areValueDefaultsAvailable(GroupNode const& _aNode) const { return m_xStrategy->areValueDefaultsAvailable(_aNode); } /// retrieve data for the child value of the given name configuration::ValueMemberNode getValue(GroupNode const& _aNode, Name const& _aName) const { return m_xStrategy->getValue(_aNode,_aName); } /// retrieve data for updating the child value of the given name configuration::ValueMemberUpdate getValueForUpdate(GroupNode const & _aNode, Name const& _aName) const { return m_xStrategy->getValueForUpdate(_aNode,_aName); } // set node specific operations public: /// does this set contain any elements (loads elements if needed) bool isEmpty(SetNode const& _aNode) const { return m_xStrategy->isEmpty(_aNode); } /// does this set contain an element named <var>aName</var> (loads elements if needed) configuration::SetEntry findElement(SetNode const& _aNode, Name const& aName) const { return m_xStrategy->findElement(_aNode,aName); } /// does this set contain an element named <var>aName</var> (and is that element loaded ?) configuration::SetEntry findAvailableElement(SetNode const& _aNode, Name const& aName) const { return m_xStrategy->findAvailableElement(_aNode,aName); } /// insert a new entry into this set void insertElement(SetNode const& _aNode, Name const& aName, configuration::SetEntry const& aNewEntry) { m_xStrategy->insertElement(_aNode,aName,aNewEntry); } /// remove an existing entry into this set void removeElement(SetNode const& _aNode, Name const& aName) { m_xStrategy->removeElement(_aNode,aName); } /** Create a Subtree change as 'diff' which allows transforming the set to its default state (given that <var>_rDefaultTree</var> points to a default instance of this set) <p>Ownership of added trees should be transferred to the SubtreeChange.</p> */ std::auto_ptr<SubtreeChange> differenceToDefaultState(SetNode const& _aNode, ISubtree& _rDefaultTree) { return m_xStrategy->differenceToDefaultState(_aNode,_rDefaultTree); } /// Get the template that describes elements of this set configuration::TemplateHolder getElementTemplate(SetNode const& _aNode) const { return m_xStrategy->getElementTemplate(_aNode); } /// Get a template provider that can create new elements for this set configuration::TemplateProvider getTemplateProvider(SetNode const& _aNode) const { return m_xStrategy->getTemplateProvider(_aNode); } // changing state/strategy public: // replace m_xStrategy by a direct ViewStrategy (commiting changes to the data), if possible // void makeDirect (); }; //----------------------------------------------------------------------------- inline ViewTreeAccess::ViewTreeAccess(Tree const & _aTree) : m_xStrategy() , m_aTree(_aTree) { m_xStrategy = _aTree.get_impl()->getViewBehavior(); } //----------------------------------------------------------------------------- inline ViewTreeAccess::ViewTreeAccess(data::Accessor const & _aAccessor, configuration::TreeImpl& _rTree) : m_xStrategy(_rTree.getViewBehavior()) , m_aTree(_aAccessor,_rTree) { } //----------------------------------------------------------------------------- } } #endif // CONFIGMGR_VIEWACCESS_HXX_ <commit_msg>INTEGRATION: CWS ooo19126 (1.3.180); FILE MERGED 2005/09/05 17:05:34 rt 1.3.180.1: #i54170# Change license header: remove SISSL<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: viewaccess.hxx,v $ * * $Revision: 1.4 $ * * last change: $Author: rt $ $Date: 2005-09-08 04:36:30 $ * * 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 CONFIGMGR_VIEWACCESS_HXX_ #define CONFIGMGR_VIEWACCESS_HXX_ #ifndef CONFIGMGR_VIEWNODE_HXX_ #include "viewnode.hxx" #endif #ifndef CONFIGMGR_VIEWBEHAVIOR_HXX_ #include "viewstrategy.hxx" #endif #ifndef _RTL_REF_HXX_ #include <rtl/ref.hxx> #endif //----------------------------------------------------------------------------- namespace configmgr { //----------------------------------------------------------------------------- namespace configuration { class NodeRef; } //----------------------------------------------------------------------------- namespace view { //----------------------------------------------------------------------------- class ViewTreeAccess { rtl::Reference< ViewStrategy > m_xStrategy; Tree m_aTree; private: data::Accessor accessor() const { return m_aTree.accessor(); } public: explicit ViewTreeAccess(Tree const & _aTree); ViewTreeAccess(data::Accessor const & _aAccessor, configuration::TreeImpl& _rTree); rtl::Reference< view::ViewStrategy > getViewBehavior() { return m_xStrategy; } public: typedef configuration::NodeRef const& NodeArg; typedef configuration::NodeOffset NodeOffset; configuration::NodeData* nodeData(NodeArg _aNodeArg) const; configuration::NodeData* nodeData(NodeOffset _aNodePos) const; bool isValid(NodeArg _aNodeArg) const; Node makeNode(NodeArg _aNodeArg) const { return Node(m_aTree,nodeData(_aNodeArg)); } Node makeNode(NodeOffset _aNodePos) const { return Node(m_aTree,nodeData(_aNodePos)); } bool isSetNode (NodeArg _aNodeArg) const { return makeNode(_aNodeArg).isSetNode(); } bool isGroupNode(NodeArg _aNodeArg) const { return makeNode(_aNodeArg).isGroupNode(); } bool isValueNode(NodeArg _aNodeArg) const { return makeNode(_aNodeArg).isValueNode(); } bool isSetNodeAt (NodeOffset _aNodeArg) const { return makeNode(_aNodeArg).isSetNode(); } bool isGroupNodeAt(NodeOffset _aNodeArg) const { return makeNode(_aNodeArg).isGroupNode(); } bool isValueNodeAt(NodeOffset _aNodeArg) const { return makeNode(_aNodeArg).isValueNode(); } SetNode toSetNode (NodeArg _aNodeArg) const { return SetNode (makeNode(_aNodeArg)); } GroupNode toGroupNode(NodeArg _aNodeArg) const { return GroupNode(makeNode(_aNodeArg)); } ValueNode toValueNode(NodeArg _aNodeArg) const { return ValueNode(makeNode(_aNodeArg)); } SetNode getSetNodeAt (NodeOffset _aNodeArg) const { return SetNode (makeNode(_aNodeArg)); } GroupNode getGroupNodeAt(NodeOffset _aNodeArg) const { return GroupNode(makeNode(_aNodeArg)); } ValueNode getValueNodeAt(NodeOffset _aNodeArg) const { return ValueNode(makeNode(_aNodeArg)); } // node attributes public: /// retrieve the name of the node Name getName(NodeArg _aNode) const { return m_xStrategy->getName(makeNode(_aNode)); } /// retrieve the attributes of the node node::Attributes getAttributes(NodeArg _aNode) const { return m_xStrategy->getAttributes(makeNode(_aNode)); } /// retrieve the name of the tree root Name getRootName() const { return m_xStrategy->getName( getRootNode(m_aTree) ); } /// retrieve the attributes of the tree root node::Attributes getRootAttributes() const { return m_xStrategy->getAttributes( getRootNode(m_aTree) ); } // tracking pending changes public: void collectChanges(configuration::NodeChanges& rChanges) const { m_xStrategy->collectChanges(m_aTree,rChanges); } bool hasChanges() const { return m_xStrategy->hasChanges(m_aTree); } bool hasChanges(NodeArg _aNode) const { return m_xStrategy->hasChanges(makeNode(_aNode)); } void markChanged(NodeArg _aNode) { m_xStrategy->markChanged(makeNode(_aNode)); } // commit protocol public: std::auto_ptr<SubtreeChange> preCommitChanges(configuration::ElementList& _rRemovedElements) { return m_xStrategy->preCommitChanges(m_aTree,_rRemovedElements); } void finishCommit(SubtreeChange& rRootChange) { m_xStrategy->finishCommit(m_aTree,rRootChange); } void revertCommit(SubtreeChange& rRootChange) { m_xStrategy->revertCommit(m_aTree,rRootChange); } void recoverFailedCommit(SubtreeChange& rRootChange) { m_xStrategy->recoverFailedCommit(m_aTree,rRootChange); } // notification protocol public: /// Adjust the internal representation after external changes to the original data - build NodeChangeInformation objects for notification void adjustToChanges(configuration::NodeChangesInformation& rLocalChanges, NodeArg _aNode, SubtreeChange const& aExternalChange) { m_xStrategy->adjustToChanges(rLocalChanges,makeNode(_aNode), aExternalChange); } // visitor dispatch public: configuration::GroupMemberVisitor::Result dispatchToValues(GroupNode const& _aNode, configuration::GroupMemberVisitor& _aVisitor) const { return m_xStrategy->dispatchToValues(_aNode,_aVisitor); } /// Call <code>aVisitor.visit(aElement)</code> for each element in this set until SetNodeVisitor::DONE is returned. configuration::SetNodeVisitor::Result dispatchToElements(SetNode const& _aNode, configuration::SetNodeVisitor& _aVisitor) const { return m_xStrategy->dispatchToElements(_aNode,_aVisitor); } // value (element) node specific operations public: /// Does this node assume its default value /// retrieve the current value of this node UnoAny getValue(ValueNode const& _aNode) const { return m_xStrategy->getValue(_aNode); } /// get the type of this value UnoType getValueType(ValueNode const& _aNode) const { return m_xStrategy->getValueType(_aNode); } // group node specific operations public: /// does this hold a child value of the given name bool hasValue(GroupNode const& _aNode, Name const& _aName) const { return m_xStrategy->hasValue(_aNode,_aName); } /// does this hold a child value bool hasValue(GroupNode const& _aNode) const { return m_xStrategy->hasValue(_aNode); } /// are defaults for this node available ? bool areValueDefaultsAvailable(GroupNode const& _aNode) const { return m_xStrategy->areValueDefaultsAvailable(_aNode); } /// retrieve data for the child value of the given name configuration::ValueMemberNode getValue(GroupNode const& _aNode, Name const& _aName) const { return m_xStrategy->getValue(_aNode,_aName); } /// retrieve data for updating the child value of the given name configuration::ValueMemberUpdate getValueForUpdate(GroupNode const & _aNode, Name const& _aName) const { return m_xStrategy->getValueForUpdate(_aNode,_aName); } // set node specific operations public: /// does this set contain any elements (loads elements if needed) bool isEmpty(SetNode const& _aNode) const { return m_xStrategy->isEmpty(_aNode); } /// does this set contain an element named <var>aName</var> (loads elements if needed) configuration::SetEntry findElement(SetNode const& _aNode, Name const& aName) const { return m_xStrategy->findElement(_aNode,aName); } /// does this set contain an element named <var>aName</var> (and is that element loaded ?) configuration::SetEntry findAvailableElement(SetNode const& _aNode, Name const& aName) const { return m_xStrategy->findAvailableElement(_aNode,aName); } /// insert a new entry into this set void insertElement(SetNode const& _aNode, Name const& aName, configuration::SetEntry const& aNewEntry) { m_xStrategy->insertElement(_aNode,aName,aNewEntry); } /// remove an existing entry into this set void removeElement(SetNode const& _aNode, Name const& aName) { m_xStrategy->removeElement(_aNode,aName); } /** Create a Subtree change as 'diff' which allows transforming the set to its default state (given that <var>_rDefaultTree</var> points to a default instance of this set) <p>Ownership of added trees should be transferred to the SubtreeChange.</p> */ std::auto_ptr<SubtreeChange> differenceToDefaultState(SetNode const& _aNode, ISubtree& _rDefaultTree) { return m_xStrategy->differenceToDefaultState(_aNode,_rDefaultTree); } /// Get the template that describes elements of this set configuration::TemplateHolder getElementTemplate(SetNode const& _aNode) const { return m_xStrategy->getElementTemplate(_aNode); } /// Get a template provider that can create new elements for this set configuration::TemplateProvider getTemplateProvider(SetNode const& _aNode) const { return m_xStrategy->getTemplateProvider(_aNode); } // changing state/strategy public: // replace m_xStrategy by a direct ViewStrategy (commiting changes to the data), if possible // void makeDirect (); }; //----------------------------------------------------------------------------- inline ViewTreeAccess::ViewTreeAccess(Tree const & _aTree) : m_xStrategy() , m_aTree(_aTree) { m_xStrategy = _aTree.get_impl()->getViewBehavior(); } //----------------------------------------------------------------------------- inline ViewTreeAccess::ViewTreeAccess(data::Accessor const & _aAccessor, configuration::TreeImpl& _rTree) : m_xStrategy(_rTree.getViewBehavior()) , m_aTree(_aAccessor,_rTree) { } //----------------------------------------------------------------------------- } } #endif // CONFIGMGR_VIEWACCESS_HXX_ <|endoftext|>
<commit_before>#include "StringfyHelper" #include "json/JSONIterator.h" namespace rho { namespace apiGenerator { using namespace rho::json; using namespace rho::common; void StringifyVector::push_back(const rho::String& value, bool escape) { m_bufferLen += 1; if (escape) { m_vector.push_back(CJSONEntry::quoteValue(value)); m_bufferLen += m_vector.back().length(); } else { m_vector.push_back(value); m_bufferLen += value.length(); } } void StringifyVector::push_back(const IStringSerializable& value) { rho::String buffer; value.toString(buffer); push_back(buffer, false); } void StringifyVector::toString(rho::String &buffer) const { buffer.clear(); buffer.reserve(m_bufferLen + 2); buffer += "["; for(rho::Vector<rho::String>::const_iterator it = m_vector.begin(); it != m_vector.end(); it++) { if(it != m_vector.begin()) { buffer += ","; } buffer += *it; } buffer += "]"; } void StringifyHash::set(const rho::String& key, const rho::String& value, bool escape) { m_bufferLen += 3; rho::String bk(CJSONEntry::quoteValue(key)); if (escape) { rho::String bv(CJSONEntry::quoteValue(value)); m_hash[bk] = bv; m_bufferLen += bk.length() + bv.length(); } else { m_hash[bk] = value; m_bufferLen += bk.length() + value.length(); } } void StringifyHash::set(const rho::String& key, const IStringSerializable& value) { rho::String buffer; value.toString(buffer); set(key, buffer, false); } void StringifyHash::toString(rho::String &buffer) const { buffer.clear(); buffer.reserve(m_bufferLen + 2); buffer += "{"; for(rho::Hashtable<rho::String, rho::String>::const_iterator it = m_hash.begin(); it != m_hash.end(); it++) { if(it != m_hash.begin()) { buffer += ","; } buffer += it->first; buffer += ":"; buffer += it->second; } buffer += "}"; } } } <commit_msg>add missing ".h"<commit_after>#include "StringfyHelper.h" #include "json/JSONIterator.h" namespace rho { namespace apiGenerator { using namespace rho::json; using namespace rho::common; void StringifyVector::push_back(const rho::String& value, bool escape) { m_bufferLen += 1; if (escape) { m_vector.push_back(CJSONEntry::quoteValue(value)); m_bufferLen += m_vector.back().length(); } else { m_vector.push_back(value); m_bufferLen += value.length(); } } void StringifyVector::push_back(const IStringSerializable& value) { rho::String buffer; value.toString(buffer); push_back(buffer, false); } void StringifyVector::toString(rho::String &buffer) const { buffer.clear(); buffer.reserve(m_bufferLen + 2); buffer += "["; for(rho::Vector<rho::String>::const_iterator it = m_vector.begin(); it != m_vector.end(); it++) { if(it != m_vector.begin()) { buffer += ","; } buffer += *it; } buffer += "]"; } void StringifyHash::set(const rho::String& key, const rho::String& value, bool escape) { m_bufferLen += 3; rho::String bk(CJSONEntry::quoteValue(key)); if (escape) { rho::String bv(CJSONEntry::quoteValue(value)); m_hash[bk] = bv; m_bufferLen += bk.length() + bv.length(); } else { m_hash[bk] = value; m_bufferLen += bk.length() + value.length(); } } void StringifyHash::set(const rho::String& key, const IStringSerializable& value) { rho::String buffer; value.toString(buffer); set(key, buffer, false); } void StringifyHash::toString(rho::String &buffer) const { buffer.clear(); buffer.reserve(m_bufferLen + 2); buffer += "{"; for(rho::Hashtable<rho::String, rho::String>::const_iterator it = m_hash.begin(); it != m_hash.end(); it++) { if(it != m_hash.begin()) { buffer += ","; } buffer += it->first; buffer += ":"; buffer += it->second; } buffer += "}"; } } } <|endoftext|>
<commit_before>// call from command line like, for instance: // root -l 'vincemark.cpp()' R__LOAD_LIBRARY(libRooFit) #include <chrono> #include <iostream> #include <sstream> #include <fstream> #include <string> #include <unistd.h> // usleep #include <sys/types.h> // for kill #include <signal.h> // for kill using namespace RooFit; std::string cut_between(std::string input, std::string before, std::string after) { auto before_pos = input.find(before); auto after_pos = input.find(after); auto cut_pos = before_pos + before.length(); auto cut_len = after_pos - cut_pos; std::string output = input.substr(cut_pos, cut_len); return output; } //////////////////////////////////////////////////////////////////////////////////////////////////// // timing_flag is used to activate only selected timing statements [1-7] // num_cpu: -1 is special option -> compare overhead communication protocol (wrt 1 cpu) // parallel_interleave: 0 = blocks of equal size, 1 = interleave, 2 = simultaneous pdfs mode // { BulkPartition=0, Interleave=1, SimComponents=2, Hybrid=3 } //////////////////////////////////////////////////////////////////////////////////////////////////// void vincemark(std::string workspace_filepath, int num_cpu=1, int optConst=0, int parallel_interleave=0, bool cpu_affinity=true, int seed=1, int timing_flag=1, bool time_num_ints=false, bool fork_timer = false, int fork_timer_sleep_us = 100000, int print_level=0, bool debug=false, bool total_cpu_timing=false, bool fix_binned_pdfs=false, bool zero_initial_POI=false ) { if (debug) { RooMsgService::instance().addStream(DEBUG); // extra possible options: Topic(Generation) Topic(RooFit::Eval), ClassName("RooAbsTestStatistic") } // int N_parameters(8); // must be even, means and sigmas have diff ranges if (timing_flag > 0) { RooJsonListFile outfile; outfile.open("timing_meta.json"); std::string names[13] = {"workspace_filepath", "N_chans", "N_bins", "N_nuisance_parameters", "N_events", "num_cpu", "parallel_interleave", "seed", "pid", "time_num_ints", "optConst", "print_level", "timing_flag"}; outfile.set_member_names(names, names + 13); auto workspace_fn = workspace_filepath.substr(workspace_filepath.rfind("/")); std::string N_channels = cut_between(workspace_fn, "workspace", "channels"); std::string N_events = cut_between(workspace_fn, "channels", "events"); std::string N_bins = cut_between(workspace_fn, "events", "bins"); std::string N_nuisance_parameters = cut_between(workspace_fn, "bins", "nps"); outfile << workspace_filepath << N_channels << N_bins << N_nuisance_parameters << N_events << num_cpu << parallel_interleave << seed << getpid() << time_num_ints << optConst << print_level << timing_flag; } RooTrace::timing_flag = timing_flag; if (time_num_ints) { RooTrace::set_time_numInts(kTRUE); } // plotting configuration int obs_plot_x(3); int obs_plot_y(2); int obs_plot_x_px(1200); int obs_plot_y_px(800); // other stuff int printlevel(print_level); int optimizeConst(optConst); // int N_timing_loops(3); // not used gRandom->SetSeed(seed); // Load the workspace data and pdf TFile *_file0 = TFile::Open(workspace_filepath.c_str()); RooWorkspace* w = static_cast<RooWorkspace*>(gDirectory->Get("BinnedWorkspace")); // Activate binned likelihood calculation for binned models if (fix_binned_pdfs) { RooFIter iter = w->components().fwdIterator(); RooAbsArg* component_arg; while((component_arg = iter.next())) { if (component_arg->IsA() == RooRealSumPdf::Class()) { component_arg->setAttribute("BinnedLikelihood"); std::cout << "component " << component_arg->GetName() << " is a binned likelihood" << std::endl; } } } RooStats::ModelConfig* mc = static_cast<RooStats::ModelConfig*>(w->genobj("ModelConfig")); RooAbsPdf* pdf = w->pdf(mc->GetPdf()->GetName()) ; RooAbsData * data = w->data("obsData"); // Manually set initial values of parameter of interest if (zero_initial_POI) { RooAbsRealLValue* POI = static_cast<RooAbsRealLValue *>(pdf->getParameters(data)->selectByName("SignalStrength")->first()); POI->setVal(0); } // --- Perform extended ML fit of composite PDF to data --- RooJsonListFile outfile; RooWallTimer timer; if (timing_flag == 1) { outfile.open("timing_full_minimize.json"); outfile.add_member_name("walltime_s") .add_member_name("segment") .add_member_name("pid"); } RooJsonListFile outfile_cpu; RooCPUTimer ctimer; if (total_cpu_timing) { outfile_cpu.open("timing_full_minimize_cpu.json"); outfile.add_member_name("cputime_s") .add_member_name("segment") .add_member_name("pid"); } Bool_t cpuAffinity; if (cpu_affinity) { cpuAffinity = kTRUE; } else { cpuAffinity = kFALSE; } // for (int it = 0; it < N_timing_loops; ++it) { RooAbsReal* nll = pdf->createNLL(*data, NumCPU(num_cpu, parallel_interleave), CPUAffinity(cpuAffinity));//, "Extended"); RooMinimizer m(*nll); // m.setVerbose(1); m.setStrategy(0); m.setProfile(1); m.setPrintLevel(printlevel); m.optimizeConst(optimizeConst); int pid = -1; if (fork_timer) { pid = fork(); } if (pid == 0) { /* child */ timer.start(); while (true) { timer.stop(); std::cout << "TIME: " << timer.timing_s() << "s" << std::endl; usleep(fork_timer_sleep_us); } } else { /* parent */ double time_migrad, time_hesse, time_minos; double ctime_migrad, ctime_hesse, ctime_minos; if (timing_flag == 1) { timer.start(); } if (total_cpu_timing) { ctimer.start(); } // m.hesse(); m.migrad(); if (timing_flag == 1) { timer.stop(); } if (total_cpu_timing) { ctimer.stop(); } if (timing_flag == 1) { std::cout << "TIME migrad: " << timer.timing_s() << "s" << std::endl; outfile << timer.timing_s() << "migrad" << getpid(); time_migrad = timer.timing_s(); } if (total_cpu_timing) { std::cout << "CPUTIME migrad: " << ctimer.timing_s() << "s" << std::endl; outfile_cpu << ctimer.timing_s() << "migrad" << getpid(); ctime_migrad = ctimer.timing_s(); } if (timing_flag == 1) { timer.start(); } if (total_cpu_timing) { ctimer.start(); } m.hesse(); if (timing_flag == 1) { timer.stop(); } if (total_cpu_timing) { ctimer.stop(); } if (timing_flag == 1) { std::cout << "TIME hesse: " << timer.timing_s() << "s" << std::endl; outfile << timer.timing_s() << "hesse" << getpid(); time_hesse = timer.timing_s(); } if (total_cpu_timing) { std::cout << "CPUTIME hesse: " << ctimer.timing_s() << "s" << std::endl; outfile_cpu << ctimer.timing_s() << "hesse" << getpid(); ctime_hesse = ctimer.timing_s(); } if (timing_flag == 1) { timer.start(); } if (total_cpu_timing) { ctimer.start(); } m.minos(*mc->GetParametersOfInterest()); if (timing_flag == 1) { timer.stop(); } if (total_cpu_timing) { ctimer.stop(); } if (timing_flag == 1) { std::cout << "TIME minos: " << timer.timing_s() << "s" << std::endl; outfile << timer.timing_s() << "minos" << getpid(); time_minos = timer.timing_s(); outfile << (time_migrad + time_hesse + time_minos) << "migrad+hesse+minos" << getpid(); } if (total_cpu_timing) { std::cout << "CPUTIME minos: " << ctimer.timing_s() << "s" << std::endl; outfile_cpu << ctimer.timing_s() << "minos" << getpid(); ctime_minos = ctimer.timing_s(); outfile_cpu << (ctime_migrad + ctime_hesse + ctime_minos) << "migrad+hesse+minos" << getpid(); } if (pid > 0) { // a child exists kill(pid, SIGKILL); } } } } <commit_msg>Fix CPU timing in vincemark<commit_after>// call from command line like, for instance: // root -l 'vincemark.cpp()' R__LOAD_LIBRARY(libRooFit) #include <chrono> #include <iostream> #include <sstream> #include <fstream> #include <string> #include <unistd.h> // usleep #include <sys/types.h> // for kill #include <signal.h> // for kill using namespace RooFit; std::string cut_between(std::string input, std::string before, std::string after) { auto before_pos = input.find(before); auto after_pos = input.find(after); auto cut_pos = before_pos + before.length(); auto cut_len = after_pos - cut_pos; std::string output = input.substr(cut_pos, cut_len); return output; } //////////////////////////////////////////////////////////////////////////////////////////////////// // timing_flag is used to activate only selected timing statements [1-7] // num_cpu: -1 is special option -> compare overhead communication protocol (wrt 1 cpu) // parallel_interleave: 0 = blocks of equal size, 1 = interleave, 2 = simultaneous pdfs mode // { BulkPartition=0, Interleave=1, SimComponents=2, Hybrid=3 } //////////////////////////////////////////////////////////////////////////////////////////////////// void vincemark(std::string workspace_filepath, int num_cpu=1, int optConst=0, int parallel_interleave=0, bool cpu_affinity=true, int seed=1, int timing_flag=1, bool time_num_ints=false, bool fork_timer = false, int fork_timer_sleep_us = 100000, int print_level=0, bool debug=false, bool total_cpu_timing=false, bool fix_binned_pdfs=false, bool zero_initial_POI=false ) { if (debug) { RooMsgService::instance().addStream(DEBUG); // extra possible options: Topic(Generation) Topic(RooFit::Eval), ClassName("RooAbsTestStatistic") } // int N_parameters(8); // must be even, means and sigmas have diff ranges if (timing_flag > 0) { RooJsonListFile outfile; outfile.open("timing_meta.json"); std::string names[13] = {"workspace_filepath", "N_chans", "N_bins", "N_nuisance_parameters", "N_events", "num_cpu", "parallel_interleave", "seed", "pid", "time_num_ints", "optConst", "print_level", "timing_flag"}; outfile.set_member_names(names, names + 13); auto workspace_fn = workspace_filepath.substr(workspace_filepath.rfind("/")); std::string N_channels = cut_between(workspace_fn, "workspace", "channels"); std::string N_events = cut_between(workspace_fn, "channels", "events"); std::string N_bins = cut_between(workspace_fn, "events", "bins"); std::string N_nuisance_parameters = cut_between(workspace_fn, "bins", "nps"); outfile << workspace_filepath << N_channels << N_bins << N_nuisance_parameters << N_events << num_cpu << parallel_interleave << seed << getpid() << time_num_ints << optConst << print_level << timing_flag; } RooTrace::timing_flag = timing_flag; if (time_num_ints) { RooTrace::set_time_numInts(kTRUE); } // plotting configuration int obs_plot_x(3); int obs_plot_y(2); int obs_plot_x_px(1200); int obs_plot_y_px(800); // other stuff int printlevel(print_level); int optimizeConst(optConst); // int N_timing_loops(3); // not used gRandom->SetSeed(seed); // Load the workspace data and pdf TFile *_file0 = TFile::Open(workspace_filepath.c_str()); RooWorkspace* w = static_cast<RooWorkspace*>(gDirectory->Get("BinnedWorkspace")); // Activate binned likelihood calculation for binned models if (fix_binned_pdfs) { RooFIter iter = w->components().fwdIterator(); RooAbsArg* component_arg; while((component_arg = iter.next())) { if (component_arg->IsA() == RooRealSumPdf::Class()) { component_arg->setAttribute("BinnedLikelihood"); std::cout << "component " << component_arg->GetName() << " is a binned likelihood" << std::endl; } } } RooStats::ModelConfig* mc = static_cast<RooStats::ModelConfig*>(w->genobj("ModelConfig")); RooAbsPdf* pdf = w->pdf(mc->GetPdf()->GetName()) ; RooAbsData * data = w->data("obsData"); // Manually set initial values of parameter of interest if (zero_initial_POI) { RooAbsRealLValue* POI = static_cast<RooAbsRealLValue *>(pdf->getParameters(data)->selectByName("SignalStrength")->first()); POI->setVal(0); } // --- Perform extended ML fit of composite PDF to data --- RooJsonListFile outfile; RooWallTimer timer; if (timing_flag == 1) { outfile.open("timing_full_minimize.json"); outfile.add_member_name("walltime_s") .add_member_name("segment") .add_member_name("pid"); } RooJsonListFile outfile_cpu; RooCPUTimer ctimer; if (total_cpu_timing) { outfile_cpu.open("timing_full_minimize_cpu.json"); outfile_cpu.add_member_name("cputime_s") .add_member_name("segment") .add_member_name("pid"); } Bool_t cpuAffinity; if (cpu_affinity) { cpuAffinity = kTRUE; } else { cpuAffinity = kFALSE; } // for (int it = 0; it < N_timing_loops; ++it) { RooAbsReal* nll = pdf->createNLL(*data, NumCPU(num_cpu, parallel_interleave), CPUAffinity(cpuAffinity));//, "Extended"); RooMinimizer m(*nll); // m.setVerbose(1); m.setStrategy(0); m.setProfile(1); m.setPrintLevel(printlevel); m.optimizeConst(optimizeConst); int pid = -1; if (fork_timer) { pid = fork(); } if (pid == 0) { /* child */ timer.start(); while (true) { timer.stop(); std::cout << "TIME: " << timer.timing_s() << "s" << std::endl; usleep(fork_timer_sleep_us); } } else { /* parent */ double time_migrad, time_hesse, time_minos; double ctime_migrad, ctime_hesse, ctime_minos; if (timing_flag == 1) { timer.start(); } if (total_cpu_timing) { ctimer.start(); } // m.hesse(); m.migrad(); if (timing_flag == 1) { timer.stop(); } if (total_cpu_timing) { ctimer.stop(); } if (timing_flag == 1) { std::cout << "TIME migrad: " << timer.timing_s() << "s" << std::endl; outfile << timer.timing_s() << "migrad" << getpid(); time_migrad = timer.timing_s(); } if (total_cpu_timing) { std::cout << "CPUTIME migrad: " << ctimer.timing_s() << "s" << std::endl; outfile_cpu << ctimer.timing_s() << "migrad" << getpid(); ctime_migrad = ctimer.timing_s(); } if (timing_flag == 1) { timer.start(); } if (total_cpu_timing) { ctimer.start(); } m.hesse(); if (timing_flag == 1) { timer.stop(); } if (total_cpu_timing) { ctimer.stop(); } if (timing_flag == 1) { std::cout << "TIME hesse: " << timer.timing_s() << "s" << std::endl; outfile << timer.timing_s() << "hesse" << getpid(); time_hesse = timer.timing_s(); } if (total_cpu_timing) { std::cout << "CPUTIME hesse: " << ctimer.timing_s() << "s" << std::endl; outfile_cpu << ctimer.timing_s() << "hesse" << getpid(); ctime_hesse = ctimer.timing_s(); } if (timing_flag == 1) { timer.start(); } if (total_cpu_timing) { ctimer.start(); } m.minos(*mc->GetParametersOfInterest()); if (timing_flag == 1) { timer.stop(); } if (total_cpu_timing) { ctimer.stop(); } if (timing_flag == 1) { std::cout << "TIME minos: " << timer.timing_s() << "s" << std::endl; outfile << timer.timing_s() << "minos" << getpid(); time_minos = timer.timing_s(); outfile << (time_migrad + time_hesse + time_minos) << "migrad+hesse+minos" << getpid(); } if (total_cpu_timing) { std::cout << "CPUTIME minos: " << ctimer.timing_s() << "s" << std::endl; outfile_cpu << ctimer.timing_s() << "minos" << getpid(); ctime_minos = ctimer.timing_s(); outfile_cpu << (ctime_migrad + ctime_hesse + ctime_minos) << "migrad+hesse+minos" << getpid(); } if (pid > 0) { // a child exists kill(pid, SIGKILL); } } } } <|endoftext|>
<commit_before>#include "io.hh" #include "conf.hh" #include "FeatureGenerator.hh" #include "SpeakerConfig.hh" conf::Config config; FeatureGenerator gen; bool raw_output = false; SpeakerConfig speaker_conf(gen); void print_feature(const FeatureVec &fea) { // Raw output if (raw_output) { for (int i = 0; i < fea.dim(); i++) { float tmp = fea[i]; fwrite(&tmp, sizeof(float), 1, stdout); } } // ASCII output else { for (int i=0; i < fea.dim(); i++) printf("%8.2f ", fea[i]); printf("\n"); } } int main(int argc, char *argv[]) { assert(sizeof(float) == 4); assert(sizeof(int) == 4); try { config("usage: feacat [OPTION...] FILE\n") ('h', "help", "", "", "display help") ('c', "config=FILE", "arg must", "", "read feature configuration") ('w', "write-config=FILE", "arg", "", "write feature configuration") ('R', "raw-input", "", "", "raw audio input") ('\0', "raw-output", "", "", "raw float output") ('H', "header", "", "", "write a header (feature dim, 32 bits) in raw output") ('s', "start-frame=INT", "arg", "", "audio start frame") ('e', "end-frame=INT", "arg", "", "audio end frame") ('S', "speakers=FILE", "arg", "", "speaker configuration file") ('d', "speaker-id=NAME", "arg", "", "speaker ID") ; config.default_parse(argc, argv); if (config.arguments.size() != 1) config.print_help(stderr, 1); raw_output = config["raw-output"].specified; if (config["header"].specified && !raw_output) { fprintf(stderr, "Warning: header is only written in raw output mode\n"); } gen.load_configuration(io::Stream(config["config"].get_str())); gen.open(config.arguments[0], config["raw-input"].specified); if (config["speakers"].specified) { speaker_conf.read_speaker_file(io::Stream(config["speakers"].get_str())); speaker_conf.set_speaker(config["speaker-id"].get_str()); } if (config["write-config"].specified) gen.write_configuration(io::Stream(config["write-config"].get_str(), "w")); if (raw_output && config["header"].specified) { int dim = gen.dim(); fwrite(&dim, sizeof(int), 1, stdout); } int start_frame = 0; int end_frame = INT_MAX; if (config["start-frame"].specified) start_frame = config["start-frame"].get_int(); if (config["end-frame"].specified) end_frame = config["end-frame"].get_int(); for (int f = start_frame; f < end_frame; f++) { const FeatureVec fea = gen.generate(f); if (end_frame == INT_MAX && gen.eof()) break; print_feature(fea); } gen.close(); } catch (std::exception &e) { fprintf(stderr, "exception: %s\n", e.what()); abort(); } catch (std::string &str) { fprintf(stderr, "exception: %s\n", str.c_str()); abort(); } } <commit_msg>audio input uses io::Stream<commit_after>#include "io.hh" #include "conf.hh" #include "FeatureGenerator.hh" #include "SpeakerConfig.hh" conf::Config config; FeatureGenerator gen; bool raw_output = false; SpeakerConfig speaker_conf(gen); void print_feature(const FeatureVec &fea) { // Raw output if (raw_output) { for (int i = 0; i < fea.dim(); i++) { float tmp = fea[i]; fwrite(&tmp, sizeof(float), 1, stdout); } } // ASCII output else { for (int i=0; i < fea.dim(); i++) printf("%8.2f ", fea[i]); printf("\n"); } } int main(int argc, char *argv[]) { assert(sizeof(float) == 4); assert(sizeof(int) == 4); try { config("usage: feacat [OPTION...] FILE\n") ('h', "help", "", "", "display help") ('c', "config=FILE", "arg must", "", "read feature configuration") ('w', "write-config=FILE", "arg", "", "write feature configuration") ('R', "raw-input", "", "", "raw audio input") ('\0', "raw-output", "", "", "raw float output") ('H', "header", "", "", "write a header (feature dim, 32 bits) in raw output") ('s', "start-frame=INT", "arg", "", "audio start frame") ('e', "end-frame=INT", "arg", "", "audio end frame") ('S', "speakers=FILE", "arg", "", "speaker configuration file") ('d', "speaker-id=NAME", "arg", "", "speaker ID") ; config.default_parse(argc, argv); if (config.arguments.size() != 1) config.print_help(stderr, 1); raw_output = config["raw-output"].specified; if (config["header"].specified && !raw_output) { fprintf(stderr, "Warning: header is only written in raw output mode\n"); } gen.load_configuration(io::Stream(config["config"].get_str())); io::Stream audio_stream(config.arguments[0]); gen.open(audio_stream, config["raw-input"].specified); if (config["speakers"].specified) { speaker_conf.read_speaker_file(io::Stream(config["speakers"].get_str())); speaker_conf.set_speaker(config["speaker-id"].get_str()); } if (config["write-config"].specified) gen.write_configuration(io::Stream(config["write-config"].get_str(), "w")); if (raw_output && config["header"].specified) { int dim = gen.dim(); fwrite(&dim, sizeof(int), 1, stdout); } int start_frame = 0; int end_frame = INT_MAX; if (config["start-frame"].specified) start_frame = config["start-frame"].get_int(); if (config["end-frame"].specified) end_frame = config["end-frame"].get_int(); for (int f = start_frame; f < end_frame; f++) { const FeatureVec fea = gen.generate(f); if (end_frame == INT_MAX && gen.eof()) break; print_feature(fea); } gen.close(); } catch (std::exception &e) { fprintf(stderr, "exception: %s\n", e.what()); abort(); } catch (std::string &str) { fprintf(stderr, "exception: %s\n", str.c_str()); abort(); } } <|endoftext|>
<commit_before>// The libMesh Finite Element Library. // Copyright (C) 2002-2018 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // C++ includes #include <fstream> #include <iomanip> #include <iostream> #include <deque> #include <map> // Local includes #include "libmesh/libmesh_config.h" #include "libmesh/fro_io.h" #include "libmesh/mesh_base.h" #include "libmesh/boundary_info.h" #include "libmesh/elem.h" namespace libMesh { // ------------------------------------------------------------ // FroIO members void FroIO::write (const std::string & fname) { // We may need to gather a DistributedMesh to output it, making that // const qualifier in our constructor a dirty lie MeshSerializer serialize(const_cast<MeshBase &>(this->mesh()), !_is_parallel_format); if (this->mesh().processor_id() == 0) { // Open the output file stream std::ofstream out_stream (fname.c_str()); libmesh_assert (out_stream.good()); // Make sure it opened correctly if (!out_stream.good()) libmesh_file_error(fname.c_str()); // Get a reference to the mesh const MeshBase & the_mesh = MeshOutput<MeshBase>::mesh(); // Write the header out_stream << the_mesh.n_elem() << " " << the_mesh.n_nodes() << " " << "0 0 " << the_mesh.get_boundary_info().n_boundary_ids() << " 1\n"; // Write the nodes -- 1-based! for (unsigned int n=0; n<the_mesh.n_nodes(); n++) out_stream << n+1 << " \t" << std::scientific << std::setprecision(12) << the_mesh.point(n)(0) << " \t" << the_mesh.point(n)(1) << " \t" << 0. << '\n'; // Write the elements -- 1-based! unsigned int e = 0; for (const auto & elem : the_mesh.active_element_ptr_range()) { // .fro likes TRI3's if (elem->type() != TRI3) libmesh_error_msg("ERROR: .fro format only valid for triangles!\n" \ << " writing of " << fname << " aborted."); out_stream << ++e << " \t"; for (unsigned int n=0; n<elem->n_nodes(); n++) out_stream << elem->node_id(n)+1 << " \t"; // // LHS -> RHS Mapping, for inverted triangles // out_stream << elem->node_id(0)+1 << " \t"; // out_stream << elem->node_id(2)+1 << " \t"; // out_stream << elem->node_id(1)+1 << " \t"; out_stream << "1\n"; } // Write BCs. { const std::set<boundary_id_type> & bc_ids = the_mesh.get_boundary_info().get_boundary_ids(); // Build a list of (elem, side, bc) tuples. auto bc_triples = the_mesh.get_boundary_info().build_side_list(); // Map the boundary ids into [1,n_bc_ids], // treat them one at a time. boundary_id_type bc_id=0; for (const auto & id : bc_ids) { std::deque<dof_id_type> node_list; std::map<dof_id_type, dof_id_type> forward_edges, backward_edges; // Get all sides on this element with the relevant BC id. for (const auto & t : bc_triples) if (std::get<2>(t) == id) { // need to build up node_list as a sorted array of edge nodes... // for the following: // a---b---c---d---e // node_list [ a b c d e]; // // the issue is just how to get this out of the elem/side based data structure. // the approach is to build up 'chain links' like this: // a---b b---c c---d d---e // and piece them together. // // so, for an arbitrary edge n0---n1, we build the // "forward_edges" map n0-->n1 // "backward_edges" map n1-->n0 // and then start with one chain link, and add on... // std::unique_ptr<const Elem> side = the_mesh.elem_ref(std::get<0>(t)).build_side_ptr(std::get<1>(t)); const dof_id_type n0 = side->node_id(0), n1 = side->node_id(1); // insert into forward-edge set forward_edges.insert (std::make_pair(n0, n1)); // insert into backward-edge set backward_edges.insert (std::make_pair(n1, n0)); // go ahead and add one edge to the list -- this will give us the beginning of a // chain to work from! if (node_list.empty()) { node_list.push_front(n0); node_list.push_back (n1); } } // we now have the node_list with one edge, the forward_edges, and the backward_edges // the node_list will be filled when (node_list.size() == (n_edges+1)) // until that is the case simply add on to the beginning and end of the node_list, // building up a chain of ordered nodes... const std::size_t n_edges = forward_edges.size(); while (node_list.size() != (n_edges+1)) { const dof_id_type front_node = node_list.front(), back_node = node_list.back(); // look for front_pair in the backward_edges list { std::map<dof_id_type, dof_id_type>::iterator pos = backward_edges.find(front_node); if (pos != backward_edges.end()) { node_list.push_front(pos->second); backward_edges.erase(pos); } } // look for back_pair in the forward_edges list { std::map<dof_id_type, dof_id_type>::iterator pos = forward_edges.find(back_node); if (pos != forward_edges.end()) { node_list.push_back(pos->second); forward_edges.erase(pos); } } // libMesh::out << "node_list.size()=" << node_list.size() // << ", n_edges+1=" << n_edges+1 << std::endl; } out_stream << ++bc_id << " " << node_list.size() << '\n'; std::deque<dof_id_type>::iterator pos = node_list.begin(); for ( ; pos != node_list.end(); ++pos) out_stream << *pos+1 << " \t0\n"; } } } } } // namespace libMesh <commit_msg>Remove iterator boilerplate in FroIO.<commit_after>// The libMesh Finite Element Library. // Copyright (C) 2002-2018 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // C++ includes #include <fstream> #include <iomanip> #include <iostream> #include <deque> #include <map> // Local includes #include "libmesh/libmesh_config.h" #include "libmesh/fro_io.h" #include "libmesh/mesh_base.h" #include "libmesh/boundary_info.h" #include "libmesh/elem.h" namespace libMesh { // ------------------------------------------------------------ // FroIO members void FroIO::write (const std::string & fname) { // We may need to gather a DistributedMesh to output it, making that // const qualifier in our constructor a dirty lie MeshSerializer serialize(const_cast<MeshBase &>(this->mesh()), !_is_parallel_format); if (this->mesh().processor_id() == 0) { // Open the output file stream std::ofstream out_stream (fname.c_str()); libmesh_assert (out_stream.good()); // Make sure it opened correctly if (!out_stream.good()) libmesh_file_error(fname.c_str()); // Get a reference to the mesh const MeshBase & the_mesh = MeshOutput<MeshBase>::mesh(); // Write the header out_stream << the_mesh.n_elem() << " " << the_mesh.n_nodes() << " " << "0 0 " << the_mesh.get_boundary_info().n_boundary_ids() << " 1\n"; // Write the nodes -- 1-based! for (unsigned int n=0; n<the_mesh.n_nodes(); n++) out_stream << n+1 << " \t" << std::scientific << std::setprecision(12) << the_mesh.point(n)(0) << " \t" << the_mesh.point(n)(1) << " \t" << 0. << '\n'; // Write the elements -- 1-based! unsigned int e = 0; for (const auto & elem : the_mesh.active_element_ptr_range()) { // .fro likes TRI3's if (elem->type() != TRI3) libmesh_error_msg("ERROR: .fro format only valid for triangles!\n" \ << " writing of " << fname << " aborted."); out_stream << ++e << " \t"; for (unsigned int n=0; n<elem->n_nodes(); n++) out_stream << elem->node_id(n)+1 << " \t"; // // LHS -> RHS Mapping, for inverted triangles // out_stream << elem->node_id(0)+1 << " \t"; // out_stream << elem->node_id(2)+1 << " \t"; // out_stream << elem->node_id(1)+1 << " \t"; out_stream << "1\n"; } // Write BCs. { const std::set<boundary_id_type> & bc_ids = the_mesh.get_boundary_info().get_boundary_ids(); // Build a list of (elem, side, bc) tuples. auto bc_triples = the_mesh.get_boundary_info().build_side_list(); // Map the boundary ids into [1,n_bc_ids], // treat them one at a time. boundary_id_type bc_id=0; for (const auto & id : bc_ids) { std::deque<dof_id_type> node_list; std::map<dof_id_type, dof_id_type> forward_edges, backward_edges; // Get all sides on this element with the relevant BC id. for (const auto & t : bc_triples) if (std::get<2>(t) == id) { // need to build up node_list as a sorted array of edge nodes... // for the following: // a---b---c---d---e // node_list [ a b c d e]; // // the issue is just how to get this out of the elem/side based data structure. // the approach is to build up 'chain links' like this: // a---b b---c c---d d---e // and piece them together. // // so, for an arbitrary edge n0---n1, we build the // "forward_edges" map n0-->n1 // "backward_edges" map n1-->n0 // and then start with one chain link, and add on... // std::unique_ptr<const Elem> side = the_mesh.elem_ref(std::get<0>(t)).build_side_ptr(std::get<1>(t)); const dof_id_type n0 = side->node_id(0), n1 = side->node_id(1); // insert into forward-edge set forward_edges.insert (std::make_pair(n0, n1)); // insert into backward-edge set backward_edges.insert (std::make_pair(n1, n0)); // go ahead and add one edge to the list -- this will give us the beginning of a // chain to work from! if (node_list.empty()) { node_list.push_front(n0); node_list.push_back (n1); } } // we now have the node_list with one edge, the forward_edges, and the backward_edges // the node_list will be filled when (node_list.size() == (n_edges+1)) // until that is the case simply add on to the beginning and end of the node_list, // building up a chain of ordered nodes... const std::size_t n_edges = forward_edges.size(); while (node_list.size() != (n_edges+1)) { const dof_id_type front_node = node_list.front(), back_node = node_list.back(); // look for front_pair in the backward_edges list { auto pos = backward_edges.find(front_node); if (pos != backward_edges.end()) { node_list.push_front(pos->second); backward_edges.erase(pos); } } // look for back_pair in the forward_edges list { auto pos = forward_edges.find(back_node); if (pos != forward_edges.end()) { node_list.push_back(pos->second); forward_edges.erase(pos); } } } out_stream << ++bc_id << " " << node_list.size() << '\n'; for (const auto & id : node_list) out_stream << id + 1 << " \t0\n"; } } } } } // namespace libMesh <|endoftext|>
<commit_before>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/hwpf/fapi2/include/error_info_defs.H $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2011,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ /// /// @file error_info_defs.H /// @brief Defines to support the Error Information class /// #ifndef FAPI2_ERRORINFO_DEFS_H_ #define FAPI2_ERRORINFO_DEFS_H_ #include <stdint.h> #include <target.H> #include <variable_buffer.H> #include <utility> namespace fapi2 { /// /// @brief Type to hold the ffdc element in the ffdc class /// Needed so that the size can be squirled away before the /// macro is called. /// class ffdc_t { public: ffdc_t(void) {} operator const void* () const { return iv_value.first; } operator uint8_t() const { return *(reinterpret_cast<const uint8_t*>(iv_value.first)); } int16_t size(void) const { return iv_value.second; } int16_t& size(void) { return iv_value.second; } const void* ptr(void) const { return iv_value.first; } const void*& ptr(void) { return iv_value.first; } private: std::pair<const void*, int16_t> iv_value; }; /// /// @brief Enumeration of ErrorInfo FFDC sizes that are used to indicate a /// special type that cannot simply be memcopied enum ErrorInfoFfdcSize { EI_FFDC_SIZE_BUF = 0xffff, // fapi2::buffer<T> EI_FFDC_SIZE_TARGET = 0xfffe, // fapi2::Target EI_FFDC_SIZE_VBUF = 0xfffd, // fapi2::variable_buffer EI_FFDC_MAX_SIZE = 0x1000, // Limit regular FFDC capture to 4kb }; /// /// @brief Enumeration of error log severity. /// enum errlSeverity_t { FAPI2_ERRL_SEV_UNDEFINED = 0x00, /// Used internally by ffdc mechanism FAPI2_ERRL_SEV_RECOVERED = 0x10, /// Not seen by customer FAPI2_ERRL_SEV_PREDICTIVE = 0x20, /// Error recovered but customer will see FAPI2_ERRL_SEV_UNRECOVERABLE = 0x40 /// Unrecoverable, general }; /// /// @brief Enumeration of ErrorInfo types /// enum ErrorInfoType { EI_TYPE_FFDC = 0, EI_TYPE_HW_CALLOUT = 1, EI_TYPE_PROCEDURE_CALLOUT = 2, EI_TYPE_BUS_CALLOUT = 3, EI_TYPE_CDG = 4, // Target Callout/Deconfig/GARD EI_TYPE_CHILDREN_CDG = 5, // Children Callout/Deconfig/GARD EI_TYPE_COLLECT_TRACE = 6, EI_LAST_TYPE = EI_TYPE_COLLECT_TRACE + 1, }; /// /// @enum HwCallout /// /// This enumeration defines the possible Hardware Callouts that are not /// represented by fapi2::Targets /// /// Note that platform code may depend on the enum values starting at 0 and /// incrementing in order to efficiently convert to a platform callout value /// so do not reorder without consulting all platforms /// namespace HwCallouts { enum HwCallout { // Where indicated, a HW Callout in FAPI Error XML must include a // reference target that is used to identify the HW. e.g. for // TOD_CLOCK, the proc chip that the clock is attached to must be // specified TOD_CLOCK = 0, // Include proc-chip ref (or child chiplet) MEM_REF_CLOCK = 1, // Include membuf-chip ref (or child chiplet) PROC_REF_CLOCK = 2, // Include proc-chip ref (or child chiplet) PCI_REF_CLOCK = 3, // Include proc-chip ref (or child chiplet) FLASH_CONTROLLER_PART = 4, PNOR_PART = 5, SBE_SEEPROM_PART = 6, VPD_PART = 7, LPC_SLAVE_PART = 8, GPIO_EXPANDER_PART = 9, SPIVID_SLAVE_PART = 10, }; } /// /// @enum ProcedureCallout /// /// This enumeration defines the possible Procedure Callouts /// These instruct the customer/customer-engineer what to do /// /// Note that platform code may depend on the enum values starting at 0 and /// incrementing in order to efficiently convert to a platform callout value /// so do not reorder without consulting all platforms /// namespace ProcedureCallouts { enum ProcedureCallout { CODE = 0, // Code problem LVL_SUPPORT = 1, // Call next level of support MEMORY_PLUGGING_ERROR = 2, // DIMM Plugging error BUS_CALLOUT = 3, // Bus Called Out }; } /// /// @enum CalloutPriority /// /// This enumeration defines the possible Procedure and Target callout priorities /// /// Note that platform code may depend on the enum values starting at 0 and /// incrementing in order to efficiently convert to a platform priority value /// so do not reorder without consulting all platforms /// namespace CalloutPriorities { enum CalloutPriority { LOW = 0, MEDIUM = 1, HIGH = 2, }; } /// /// @enum CollectTrace /// /// This enumeration defines the possible firmware traces to collect /// namespace CollectTraces { const uint32_t TRACE_SIZE = 256; // limit collected trace size enum CollectTrace { FSI = 1, SCOM = 2, SCAN = 3, MBOX = 4, }; } /// /// @brief Get FFDC Size /// /// This is called by the FAPI_SET_HWP_ERROR macro to find out the size of /// FFDC data. If the data is of a special type that is handled differently /// than types that are simply memcopied then it is handled by a template /// specialization. /// If this function template is instantiated with a pointer, the compile /// will fail. /// /// @return uint16_t. Size of the FFDC data /// template<typename T> inline uint16_t getErrorInfoFfdcSize(const T&) { static_assert(sizeof(T) <= EI_FFDC_MAX_SIZE, "FFDC too large to capture"); return sizeof(T); } /// /// @brief Compile error if caller tries to get the FFDC size of a pointer /// template<typename T> inline uint16_t getErrorInfoFfdcSize(const T*) { static_assert(std::is_pointer<T>::value, "pointer passed to getErrorInfoFfdcSize"); return 0; } /// /// @brief Get FFDC Size specialization for fapi2::Target /// template<fapi2::TargetType T> inline uint16_t getErrorInfoFfdcSize(const fapi2::Target<T>&) { return EI_FFDC_SIZE_TARGET; } /// /// @brief Get FFDC Size specialization for variable buffers /// template<> inline uint16_t getErrorInfoFfdcSize(const fapi2::variable_buffer& i_thing) { // Limit a variable buffer to 4kb bytes, and we can memcpy the storage. return std::min(static_cast<uint32_t>(EI_FFDC_MAX_SIZE), i_thing.getLength<uint8_t>()); } }; #endif // FAPI2_ERRORINFO_DEFS_H_ <commit_msg>fapi2: Update misc functions to honor platform value type.<commit_after>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/hwpf/fapi2/include/error_info_defs.H $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2011,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ /// /// @file error_info_defs.H /// @brief Defines to support the Error Information class /// #ifndef FAPI2_ERRORINFO_DEFS_H_ #define FAPI2_ERRORINFO_DEFS_H_ #include <stdint.h> #include <target.H> #include <variable_buffer.H> #include <utility> namespace fapi2 { /// /// @brief Type to hold the ffdc element in the ffdc class /// Needed so that the size can be squirled away before the /// macro is called. /// class ffdc_t { public: ffdc_t(void) {} operator const void* () const { return iv_value.first; } operator uint8_t() const { return *(reinterpret_cast<const uint8_t*>(iv_value.first)); } int16_t size(void) const { return iv_value.second; } int16_t& size(void) { return iv_value.second; } const void* ptr(void) const { return iv_value.first; } const void*& ptr(void) { return iv_value.first; } private: std::pair<const void*, int16_t> iv_value; }; /// /// @brief Enumeration of ErrorInfo FFDC sizes that are used to indicate a /// special type that cannot simply be memcopied enum ErrorInfoFfdcSize { EI_FFDC_SIZE_BUF = 0xffff, // fapi2::buffer<T> EI_FFDC_SIZE_TARGET = 0xfffe, // fapi2::Target EI_FFDC_SIZE_VBUF = 0xfffd, // fapi2::variable_buffer EI_FFDC_MAX_SIZE = 0x1000, // Limit regular FFDC capture to 4kb }; /// /// @brief Enumeration of error log severity. /// enum errlSeverity_t { FAPI2_ERRL_SEV_UNDEFINED = 0x00, /// Used internally by ffdc mechanism FAPI2_ERRL_SEV_RECOVERED = 0x10, /// Not seen by customer FAPI2_ERRL_SEV_PREDICTIVE = 0x20, /// Error recovered but customer will see FAPI2_ERRL_SEV_UNRECOVERABLE = 0x40 /// Unrecoverable, general }; /// /// @brief Enumeration of ErrorInfo types /// enum ErrorInfoType { EI_TYPE_FFDC = 0, EI_TYPE_HW_CALLOUT = 1, EI_TYPE_PROCEDURE_CALLOUT = 2, EI_TYPE_BUS_CALLOUT = 3, EI_TYPE_CDG = 4, // Target Callout/Deconfig/GARD EI_TYPE_CHILDREN_CDG = 5, // Children Callout/Deconfig/GARD EI_TYPE_COLLECT_TRACE = 6, EI_LAST_TYPE = EI_TYPE_COLLECT_TRACE + 1, }; /// /// @enum HwCallout /// /// This enumeration defines the possible Hardware Callouts that are not /// represented by fapi2::Targets /// /// Note that platform code may depend on the enum values starting at 0 and /// incrementing in order to efficiently convert to a platform callout value /// so do not reorder without consulting all platforms /// namespace HwCallouts { enum HwCallout { // Where indicated, a HW Callout in FAPI Error XML must include a // reference target that is used to identify the HW. e.g. for // TOD_CLOCK, the proc chip that the clock is attached to must be // specified TOD_CLOCK = 0, // Include proc-chip ref (or child chiplet) MEM_REF_CLOCK = 1, // Include membuf-chip ref (or child chiplet) PROC_REF_CLOCK = 2, // Include proc-chip ref (or child chiplet) PCI_REF_CLOCK = 3, // Include proc-chip ref (or child chiplet) FLASH_CONTROLLER_PART = 4, PNOR_PART = 5, SBE_SEEPROM_PART = 6, VPD_PART = 7, LPC_SLAVE_PART = 8, GPIO_EXPANDER_PART = 9, SPIVID_SLAVE_PART = 10, }; } /// /// @enum ProcedureCallout /// /// This enumeration defines the possible Procedure Callouts /// These instruct the customer/customer-engineer what to do /// /// Note that platform code may depend on the enum values starting at 0 and /// incrementing in order to efficiently convert to a platform callout value /// so do not reorder without consulting all platforms /// namespace ProcedureCallouts { enum ProcedureCallout { CODE = 0, // Code problem LVL_SUPPORT = 1, // Call next level of support MEMORY_PLUGGING_ERROR = 2, // DIMM Plugging error BUS_CALLOUT = 3, // Bus Called Out }; } /// /// @enum CalloutPriority /// /// This enumeration defines the possible Procedure and Target callout priorities /// /// Note that platform code may depend on the enum values starting at 0 and /// incrementing in order to efficiently convert to a platform priority value /// so do not reorder without consulting all platforms /// namespace CalloutPriorities { enum CalloutPriority { LOW = 0, MEDIUM = 1, HIGH = 2, }; } /// /// @enum CollectTrace /// /// This enumeration defines the possible firmware traces to collect /// namespace CollectTraces { const uint32_t TRACE_SIZE = 256; // limit collected trace size enum CollectTrace { FSI = 1, SCOM = 2, SCAN = 3, MBOX = 4, }; } /// /// @brief Get FFDC Size /// /// This is called by the FAPI_SET_HWP_ERROR macro to find out the size of /// FFDC data. If the data is of a special type that is handled differently /// than types that are simply memcopied then it is handled by a template /// specialization. /// If this function template is instantiated with a pointer, the compile /// will fail. /// /// @return uint16_t. Size of the FFDC data /// template<typename T> inline uint16_t getErrorInfoFfdcSize(const T&) { static_assert(sizeof(T) <= EI_FFDC_MAX_SIZE, "FFDC too large to capture"); return sizeof(T); } /// /// @brief Compile error if caller tries to get the FFDC size of a pointer /// template<typename T> inline uint16_t getErrorInfoFfdcSize(const T*) { static_assert(std::is_pointer<T>::value, "pointer passed to getErrorInfoFfdcSize"); return 0; } /// /// @brief Get FFDC Size specialization for fapi2::Target /// template<fapi2::TargetType T, typename V> inline uint16_t getErrorInfoFfdcSize(const fapi2::Target<T, V>&) { return EI_FFDC_SIZE_TARGET; } /// /// @brief Get FFDC Size specialization for variable buffers /// template<> inline uint16_t getErrorInfoFfdcSize(const fapi2::variable_buffer& i_thing) { // Limit a variable buffer to 4kb bytes, and we can memcpy the storage. return std::min(static_cast<uint32_t>(EI_FFDC_MAX_SIZE), i_thing.getLength<uint8_t>()); } }; #endif // FAPI2_ERRORINFO_DEFS_H_ <|endoftext|>
<commit_before>#include <iostream> #include "initConfig.h" #include "libconfig.h++" #include "getopt.h" using namespace watcher; using namespace libconfig; using namespace std; bool watcher::initConfig( libconfig::Config &config, int argc, char **argv, std::string &configFilename, const char configFileChar, const char *configFileString) { int c; // int digit_optind = 0; while (true) { // int this_option_optind = optind ? optind : 1; int option_index = 0; static struct option long_options[] = { {configFileString, required_argument, 0, configFileChar}, {0, 0, 0, 0} }; opterr=0; // Don't print message just because we see an option we don't understand. char args[] = { configFileChar, ':', '\n' }; c = getopt_long(argc, argv, args, long_options, &option_index); if (c == -1) break; if (c==configFileChar) { try { config.readFile(optarg); configFilename=optarg; return true; } catch (ParseException &e) { // Can't use logging here - if we're reading the config file we probably have not // init'd the logging mechanism. cerr << "Error reading configuration file " << optarg << ": " << e.what() << endl; cerr << "Error: \"" << e.getError() << "\" on line: " << e.getLine() << endl; } catch (FileIOException &e) { cerr << "Unable to read file " << optarg << " given as configuration file on the command line." << endl; } } // else - ignore things we don't understand } return false; } <commit_msg>initConfig: If not passed on the command line (-c file), then look for configuration file of the name argv[0].cfg (e.g. "watcherd.cfg") when loading the config file.<commit_after>#include <iostream> #include "initConfig.h" #include "libconfig.h++" #include "getopt.h" using namespace watcher; using namespace libconfig; using namespace std; static bool readConfig(libconfig::Config &config, const string &filename) { try { config.readFile(filename.c_str()); return true; } catch (ParseException &e) { // Can't use logging here - if we're reading the config file we probably have not // init'd the logging mechanism. cerr << "Error reading configuration file " << optarg << ": " << e.what() << endl; cerr << "Error: \"" << e.getError() << "\" on line: " << e.getLine() << endl; } catch (FileIOException &e) { cerr << "Unable to read file " << optarg << " given as configuration file on the command line." << endl; } return false; } bool watcher::initConfig( libconfig::Config &config, int argc, char **argv, std::string &configFilename, const char configFileChar, const char *configFileString) { int c; // int digit_optind = 0; bool retVal=false; while (true) { // int this_option_optind = optind ? optind : 1; int option_index = 0; static struct option long_options[] = { {configFileString, required_argument, 0, configFileChar}, {0, 0, 0, 0} }; opterr=0; // Don't print message just because we see an option we don't understand. char args[] = { configFileChar, ':', '\n' }; c = getopt_long(argc, argv, args, long_options, &option_index); if (c == -1) break; if (c==configFileChar) if(true==(retVal=readConfig(config, optarg))) configFilename=optarg; // else - ignore things we don't understand } // Last ditch: look for a file called `echo argv[0]`.cfg. if(retVal==false) { string fname(argv[0]); fname+=".cfg"; if(true==(retVal=readConfig(config, fname))) configFilename=fname; } return retVal; } <|endoftext|>
<commit_before>#include <iostream> #include <boost/asio.hpp> #include <google/protobuf/descriptor.h> #include <google/protobuf/service.h> #include "vtrc-common/vtrc-pool-pair.h" #include "vtrc-common/vtrc-connection-iface.h" #include "vtrc-common/vtrc-call-context.h" #include "vtrc-common/vtrc-exception.h" #include "vtrc-common/vtrc-protocol-layer.h" #include "vtrc-client-base/vtrc-client.h" #include "protocol/vtrc-rpc-lowlevel.pb.h" #include "protocol/vtrc-service.pb.h" #include "protocol/vtrc-errors.pb.h" #include <boost/random.hpp> #include <boost/random/random_device.hpp> #include "vtrc-thread.h" #include "vtrc-chrono.h" using namespace vtrc; void on_connect( const boost::system::error_code &err ) { std::cout << "connected " << err.value( ) << " " << err.message( ) << "\n"; } struct work_time { typedef boost::chrono::high_resolution_clock::time_point time_point; time_point start_; work_time( ) :start_(boost::chrono::high_resolution_clock::now( )) {} ~work_time( ) { time_point stop(boost::chrono::high_resolution_clock::now( )); std::cout << "call time: " << stop - start_ << "\n"; } }; class ping_impl: public vtrc_service::internal { client::vtrc_client *c_; public: ping_impl( client::vtrc_client *c ) :c_( c ) {} void ping(::google::protobuf::RpcController* controller, const ::vtrc_service::ping_req* request, ::vtrc_service::pong_res* response, ::google::protobuf::Closure* done) { common::closure_holder chold(done); std::cout << "ping event rcvd " << c_->connection( ) ->get_protocol( ).get_call_context( ) ->get_lowlevel_message( )->id( ) << " " << vtrc::this_thread::get_id( ) << " " //<< vtrc::chrono::high_resolution_clock::now( ) << "\n"; return; const vtrc::common::call_context *cc = vtrc::common::call_context::get( c_->connection( ) ); vtrc::shared_ptr<google::protobuf::RpcChannel> ch(c_->create_channel( false, true )); vtrc_rpc_lowlevel::message_info mi; vtrc_service::test_rpc::Stub s( ch.get( ) ); s.test2( NULL, &mi, &mi, NULL ); //if( done ) done->Run( ); } }; class test_ev: public vtrc_service::test_events { vtrc::common::connection_iface *c_; public: test_ev( vtrc::common::connection_iface *c ) :c_( c ) {} void test(::google::protobuf::RpcController* controller, const ::vtrc_rpc_lowlevel::message_info* request, ::vtrc_rpc_lowlevel::message_info* response, ::google::protobuf::Closure* done) { common::closure_holder ch(done); std::cout << "test event rcvd " << c_->get_protocol( ).get_call_context( )->get_lowlevel_message( )->id( ) << " " << vtrc::this_thread::get_id( ) << " " << "\n"; } }; void run_client( vtrc::shared_ptr<client::vtrc_client> cl, bool wait) { vtrc::shared_ptr<google::protobuf::RpcChannel> ch(cl->create_channel( wait, false )); vtrc_service::test_rpc::Stub s( ch.get( ) ); vtrc_rpc_lowlevel::message_info mi; size_t last = 0; std::cout << "this thread: " << vtrc::this_thread::get_id( ) << " " << "\n"; for( int i=0; i<29999999999; ++i ) { try { // if( wait ) // vtrc::this_thread::sleep_for( vtrc::chrono::milliseconds(1) ); work_time wt; s.test( NULL, &mi, &mi, NULL ); last = mi.message_type( ); std::cout << "response: " << last << "\n"; //cl.reset( ); } catch( const vtrc::common::exception &ex ) { std::cout << "call error: " << " code (" << ex.code( ) << ")" << " category (" << ex.category( ) << ")" << " what: " << ex.what( ) << " (" << ex.additional( ) << ")" << "\n"; //if( i % 100 == 0 ) std::cout << i << "\n"; if( ex.category( ) == vtrc_errors::CATEGORY_SYSTEM ) break; } catch( const std::exception &ex ) { //std::cout << "call error: " << ex.what( ) << "\n"; } } } int main( ) { common::pool_pair pp(2, 2); vtrc::shared_ptr<client::vtrc_client> cl(client::vtrc_client::create(pp)); //cl->connect( "/tmp/test" ); cl->connect( "192.168.56.101", "44667" ); //cl->connect( "127.0.0.1", "44667" ); //cl->connect( "::1", "44668" ); ///cl->async_connect( "127.0.0.1", "44667", on_connect ); cl->advise_handler( vtrc::shared_ptr<test_ev>(new test_ev(cl->connection( ).get( ))) ); cl->advise_handler( vtrc::shared_ptr<ping_impl>(new ping_impl(cl.get( ))) ); vtrc::this_thread::sleep_for( vtrc::chrono::milliseconds(2000) ); vtrc::thread( run_client, cl, true ).detach( ); vtrc::thread( run_client, cl, false ).join( ); pp.stop_all( ); pp.join_all( ); return 0; } <commit_msg>done handlers<commit_after>#include <iostream> #include <boost/asio.hpp> #include <google/protobuf/descriptor.h> #include <google/protobuf/service.h> #include "vtrc-common/vtrc-pool-pair.h" #include "vtrc-common/vtrc-connection-iface.h" #include "vtrc-common/vtrc-call-context.h" #include "vtrc-common/vtrc-exception.h" #include "vtrc-common/vtrc-protocol-layer.h" #include "vtrc-client-base/vtrc-client.h" #include "protocol/vtrc-rpc-lowlevel.pb.h" #include "protocol/vtrc-service.pb.h" #include "protocol/vtrc-errors.pb.h" #include <boost/random.hpp> #include <boost/random/random_device.hpp> #include "vtrc-thread.h" #include "vtrc-chrono.h" using namespace vtrc; void on_connect( const boost::system::error_code &err ) { std::cout << "connected " << err.value( ) << " " << err.message( ) << "\n"; } struct work_time { typedef boost::chrono::high_resolution_clock::time_point time_point; time_point start_; work_time( ) :start_(boost::chrono::high_resolution_clock::now( )) {} ~work_time( ) { time_point stop(boost::chrono::high_resolution_clock::now( )); std::cout << "call time: " << stop - start_ << "\n"; } }; class ping_impl: public vtrc_service::internal { client::vtrc_client *c_; public: ping_impl( client::vtrc_client *c ) :c_( c ) {} void ping(::google::protobuf::RpcController* controller, const ::vtrc_service::ping_req* request, ::vtrc_service::pong_res* response, ::google::protobuf::Closure* done) { common::closure_holder chold(done); std::cout << "ping event rcvd " << c_->connection( ) ->get_protocol( ).get_call_context( ) ->get_lowlevel_message( )->id( ) << " " << vtrc::this_thread::get_id( ) << " " //<< vtrc::chrono::high_resolution_clock::now( ) << "\n"; return; const vtrc::common::call_context *cc = vtrc::common::call_context::get( c_->connection( ) ); vtrc::shared_ptr<google::protobuf::RpcChannel> ch(c_->create_channel( false, true )); vtrc_rpc_lowlevel::message_info mi; vtrc_service::test_rpc::Stub s( ch.get( ) ); s.test2( NULL, &mi, &mi, NULL ); //if( done ) done->Run( ); } }; class test_ev: public vtrc_service::test_events { vtrc::common::connection_iface *c_; public: test_ev( vtrc::common::connection_iface *c ) :c_( c ) {} void test(::google::protobuf::RpcController* controller, const ::vtrc_rpc_lowlevel::message_info* request, ::vtrc_rpc_lowlevel::message_info* response, ::google::protobuf::Closure* done) { common::closure_holder ch(done); std::cout << "test event rcvd " << c_->get_protocol( ).get_call_context( )->get_lowlevel_message( )->id( ) << " " << vtrc::this_thread::get_id( ) << " " << "\n"; } }; void run_client( vtrc::shared_ptr<client::vtrc_client> cl, bool wait) { vtrc::shared_ptr<google::protobuf::RpcChannel> ch(cl->create_channel( wait, false )); vtrc_service::test_rpc::Stub s( ch.get( ) ); vtrc_rpc_lowlevel::message_info mi; size_t last = 0; std::cout << "this thread: " << vtrc::this_thread::get_id( ) << " " << "\n"; for( int i=0; i<29999999999; ++i ) { try { // if( wait ) // vtrc::this_thread::sleep_for( vtrc::chrono::milliseconds(1) ); work_time wt; s.test( NULL, &mi, &mi, NULL ); last = mi.message_type( ); std::cout << "response: " << last << "\n"; //cl.reset( ); } catch( const vtrc::common::exception &ex ) { std::cout << "call error: " << " code (" << ex.code( ) << ")" << " category (" << ex.category( ) << ")" << " what: " << ex.what( ) << " (" << ex.additional( ) << ")" << "\n"; //if( i % 100 == 0 ) std::cout << i << "\n"; if( ex.category( ) == vtrc_errors::CATEGORY_SYSTEM ) break; } catch( const std::exception &ex ) { //std::cout << "call error: " << ex.what( ) << "\n"; } } } int main( ) { common::pool_pair pp(2, 2); vtrc::shared_ptr<client::vtrc_client> cl(client::vtrc_client::create(pp)); //cl->connect( "/tmp/test" ); cl->connect( "192.168.56.101", "44667" ); //cl->connect( "127.0.0.1", "44667" ); //cl->connect( "::1", "44668" ); ///cl->async_connect( "127.0.0.1", "44667", on_connect ); cl->advise_handler( vtrc::shared_ptr<test_ev>(new test_ev(cl->connection( ).get( ))) ); cl->advise_handler( vtrc::shared_ptr<ping_impl>(new ping_impl(cl.get( ))) ); vtrc::this_thread::sleep_for( vtrc::chrono::milliseconds(2000) ); vtrc::thread( run_client, cl, false ).detach( ); vtrc::thread( run_client, cl, false ).join( ); pp.stop_all( ); pp.join_all( ); return 0; } <|endoftext|>
<commit_before>/** @file @brief Implementation @date 2015 @author Sensics, Inc. <http://sensics.com/osvr> */ // Copyright 2015 Sensics, 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. // Internal Includes #include "DirectShowToCV.h" #include "directx_camera_server.h" // Library/third-party includes #include <opencv2/highgui/highgui.hpp> // Standard includes #include <memory> #include <iostream> #include <chrono> /// @brief OpenCV's simple highgui module refers to windows by their name, so we /// make this global for a simpler demo. static const std::string windowNameAndInstructions( "OSVR tracking camera preview | q or esc to quit"); // This string begins the DevicePath provided by Windows for the HDK's camera. static const auto HDK_CAMERA_PATH_PREFIX = "\\\\?\\usb#vid_0bda&pid_57e8&mi_00"; class FrameCounter { public: FrameCounter() { reset(); } void gotFrame() { ++m_frames; auto now = clock::now(); if (now >= m_end) { auto duration = std::chrono::duration_cast<std::chrono::duration<double>>( now - m_begin); std::cout << m_frames / duration.count() << " FPS read from camera" << std::endl; reset(); } } void reset() { m_begin = clock::now(); m_end = m_begin + std::chrono::seconds(1); m_frames = 0; } private: using clock = std::chrono::system_clock; using time_point = std::chrono::time_point<clock>; time_point m_begin; time_point m_end; std::size_t m_frames = 0; }; int main() { auto cam = std::unique_ptr<directx_camera_server>{ new directx_camera_server(HDK_CAMERA_PATH_PREFIX)}; if (!cam->read_image_to_memory()) { std::cerr << "Couldn't find, open, or read from the OSVR HDK tracking camera." << std::endl; return -1; } auto frame = cv::Mat{}; FrameCounter counter; cv::namedWindow(windowNameAndInstructions); do { frame = retrieve(*cam); counter.gotFrame(); cv::imshow(windowNameAndInstructions, frame); char key = static_cast<char>(cv::waitKey(1)); // wait 1 ms for a key if ('q' == key || 'Q' == key || 27 /*esc*/ == key) { break; } } while (cam->read_image_to_memory()); return 0; } <commit_msg>Add display stride capability to the viewer app.<commit_after>/** @file @brief Implementation @date 2015 @author Sensics, Inc. <http://sensics.com/osvr> */ // Copyright 2015 Sensics, 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. // Internal Includes #include "DirectShowToCV.h" #include "directx_camera_server.h" // Library/third-party includes #include <opencv2/highgui/highgui.hpp> // Standard includes #include <memory> #include <iostream> #include <chrono> #include <sstream> /// @brief OpenCV's simple highgui module refers to windows by their name, so we /// make this global for a simpler demo. static const std::string windowNameAndInstructions( "OSVR tracking camera preview | q or esc to quit"); // This string begins the DevicePath provided by Windows for the HDK's camera. static const auto HDK_CAMERA_PATH_PREFIX = "\\\\?\\usb#vid_0bda&pid_57e8&mi_00"; class FrameCounter { public: FrameCounter() { reset(); } void gotFrame() { ++m_frames; auto now = clock::now(); if (now >= m_end) { auto duration = std::chrono::duration_cast<std::chrono::duration<double>>( now - m_begin); std::cout << m_frames / duration.count() << " FPS read from camera" << std::endl; reset(); } } void reset() { m_begin = clock::now(); m_end = m_begin + std::chrono::seconds(1); m_frames = 0; } private: using clock = std::chrono::system_clock; using time_point = std::chrono::time_point<clock>; time_point m_begin; time_point m_end; std::size_t m_frames = 0; }; int main(int argc, char *argv[]) { auto cam = std::unique_ptr<directx_camera_server>{ new directx_camera_server(HDK_CAMERA_PATH_PREFIX)}; if (!cam->read_image_to_memory()) { std::cerr << "Couldn't find, open, or read from the OSVR HDK tracking camera." << std::endl; return -1; } auto FRAME_DISPLAY_STRIDE = 3u; if (argc > 1) { auto is = std::istringstream{argv[1]}; if (is >> FRAME_DISPLAY_STRIDE) { std::cout << "Custom display stride passed: " << FRAME_DISPLAY_STRIDE << std::endl; } else { std::cout << "Could not parse first command-line argument as a " "display stride : '" << argv[1] << "' (will use default)" << std::endl; } } std::cout << "Will display 1 out of every " << FRAME_DISPLAY_STRIDE << " frames captured." << std::endl; auto frame = cv::Mat{}; FrameCounter counter; cv::namedWindow(windowNameAndInstructions); auto frameCount = std::size_t{0}; do { frame = retrieve(*cam); counter.gotFrame(); ++frameCount; if (frameCount % FRAME_DISPLAY_STRIDE == 0) { frameCount = 0; cv::imshow(windowNameAndInstructions, frame); char key = static_cast<char>(cv::waitKey(1)); // wait 1 ms for a key if ('q' == key || 'Q' == key || 27 /*esc*/ == key) { break; } } } while (cam->read_image_to_memory()); return 0; } <|endoftext|>
<commit_before>#include "State.h" using namespace std; // num_cols should be set in constructor State::State(MatrixD &data, vector<int> global_row_indices, vector<int> global_col_indices, int N_GRID) { crp_alpha = 0.8; int num_rows = data.size1(); construct_hyper_grids(data, N_GRID); vector<vector<int> > column_partition; column_partition = determine_crp_init(global_col_indices, crp_alpha, rng); vector<vector<int> >::iterator cp_it; for(cp_it=column_partition.begin(); cp_it!=column_partition.end(); cp_it++) { vector<int> column_indices = *cp_it; MatrixD data_subset = extract_columns(data, column_indices); View *p_v = new View(data_subset, global_row_indices, column_indices); views.insert(p_v); vector<int>::iterator ci_it; for(ci_it=column_indices.begin(); ci_it!=column_indices.end(); ci_it++) { int column_index = *ci_it; view_lookup[column_index] = p_v; } } } int State::get_num_cols() const { return view_lookup.size(); } int State::get_num_views() const { return views.size(); } vector<int> State::get_view_counts() const { vector<int> view_counts; set<View*>::iterator it; for(it=views.begin(); it!=views.end(); it++) { View &v = (**it); int view_num_cols = v.get_num_cols(); view_counts.push_back(view_num_cols); } return view_counts; } double State::insert_feature(int feature_idx, vector<double> feature_data, View &which_view) { double crp_logp_delta, data_logp_delta; double score_delta = calc_feature_view_predictive_logp(feature_data, which_view, crp_logp_delta, data_logp_delta); vector<int> data_global_row_indices = create_sequence(feature_data.size()); which_view.insert_col(feature_data, data_global_row_indices, feature_idx); view_lookup[feature_idx] = &which_view; crp_score += crp_logp_delta; data_score += data_logp_delta; return score_delta; } double State::sample_insert_feature(int feature_idx, vector<double> feature_data, View &singleton_view) { cout << "State::sample_insert_feature: view: " << views << endl; cout << "State::sample_insert_feature: view_counts: " << get_view_counts() << endl; vector<double> unorm_logps = calc_feature_view_predictive_logps(feature_data); cout << "State::sample_insert_feature: " << unorm_logps << endl; double rand_u = draw_rand_u(); int draw = numerics::draw_sample_unnormalized(unorm_logps, rand_u); View &which_view = get_view(draw); cout << "State::sample_insert_feature: which_view: " << &which_view << endl; double score_delta = insert_feature(feature_idx, feature_data, which_view); cout << score_delta << " = insert_feature(" << feature_idx << ", feature_data, " << &which_view << ")" << endl; remove_if_empty(singleton_view); return score_delta; } double State::remove_feature(int feature_idx, vector<double> feature_data, View** p_p_singleton_view) { map<int,View*>::iterator it = view_lookup.find(feature_idx); assert(it!=view_lookup.end()); View &which_view = *(it->second); view_lookup.erase(it); int view_num_cols = which_view.get_num_cols(); double data_logp_delta = which_view.remove_col(feature_idx); double crp_logp_delta, other_data_logp_delta; double score_delta = calc_feature_view_predictive_logp(feature_data, which_view, crp_logp_delta, other_data_logp_delta); // if(view_num_cols==1) { *p_p_singleton_view = &which_view; } else { *p_p_singleton_view = &get_new_view(); } //DON"T REMOVE HERE //remove_if_empty(which_view); crp_score -= crp_logp_delta; //data_score -= data_logp_delta; data_score -= other_data_logp_delta; // // FIXME : need to record partitioning and pass that in for scoring of state if(other_data_logp_delta!=data_logp_delta) { cout << "other_data_logp_delta: " << other_data_logp_delta; cout << ", data_logp_delta: " << data_logp_delta << endl; } cout << "get_marginal_logp(): " << get_marginal_logp() << endl; return score_delta; } double State::transition_feature(int feature_idx, vector<double> feature_data) { double score_delta = 0; View **p_p_singleton_view; *p_p_singleton_view = 0; score_delta += remove_feature(feature_idx, feature_data, p_p_singleton_view); score_delta += sample_insert_feature(feature_idx, feature_data, **p_p_singleton_view); return score_delta; } double State::transition_features(MatrixD &data) { double score_delta = 0; vector<int> feature_indices = create_sequence(data.size2()); vector<int>::iterator it; for(it=feature_indices.begin(); it!=feature_indices.end(); it++) { int feature_idx = *it; vector<double> feature_data = extract_col(data, feature_idx); score_delta += transition_feature(feature_idx, feature_data); } return score_delta; } View& State::get_new_view() { View *p_new_view = new View(); views.insert(p_new_view); return *p_new_view; } View& State::get_view(int view_idx) { assert(view_idx <= views.size()); bool not_new = view_idx < views.size(); if(not_new) { set<View*>::iterator it = views.begin(); std::advance(it, view_idx); return **it; } else { // This shouldn't happen anymore assert(1==0); return get_new_view(); } } void State::remove_if_empty(View& which_view) { if(which_view.get_num_cols()==0) { views.erase(views.find(&which_view)); delete &which_view; } } double State::get_crp_alpha() const { return crp_alpha; } double State::get_crp_score() const { return crp_score; } double State::get_data_score() const { return data_score; } double State::get_marginal_logp() const { return crp_score + data_score; } double State::transition_view_i(int which_view, map<int, vector<double> > row_data_map) { // assumes views set ordering stays constant between calls set<View*>::iterator it = views.begin(); std::advance(it, which_view); View &v = **it; double score_delta = v.transition(row_data_map); data_score += score_delta; return score_delta; } double State::transition_views(MatrixD &data) { vector<int> global_column_indices = create_sequence(data.size2()); // double score_delta = 0; // ordering doesn't matter, don't need to shuffle for(int view_idx=0; view_idx<get_num_views(); view_idx++) { View &v = get_view(view_idx); vector<int> view_cols = get_indices_to_reorder(global_column_indices, v.global_to_local); MatrixD data_subset = extract_columns(data, view_cols); map<int, vector<double> > data_subset_map = construct_data_map(data_subset); score_delta += transition_view_i(view_idx, data_subset_map); } return score_delta; } double State::calc_feature_view_predictive_logp(vector<double> col_data, View v, double &crp_log_delta, double &data_log_delta) const { int view_column_count = v.get_num_cols(); int num_columns = get_num_cols(); crp_log_delta = numerics::calc_cluster_crp_logp(view_column_count, num_columns, crp_alpha); // vector<int> data_global_row_indices = create_sequence(col_data.size()); data_log_delta = v.calc_column_predictive_logp(col_data, data_global_row_indices); // double score_delta = data_log_delta + crp_log_delta; return score_delta; } vector<double> State::calc_feature_view_predictive_logps(vector<double> col_data) const { vector<double> logps; set<View*>::iterator it; double crp_log_delta, data_log_delta; for(it=views.begin(); it!=views.end(); it++) { View &v = **it; double score_delta = calc_feature_view_predictive_logp(col_data, v, crp_log_delta, data_log_delta); logps.push_back(score_delta); } return logps; } double State::calc_crp_marginal() const { vector<int> view_counts = get_view_counts(); int num_cols = get_num_cols(); return numerics::calc_crp_alpha_conditional(view_counts, crp_alpha, num_cols, true); } vector<double> State::calc_crp_marginals(vector<double> alphas_to_score) const { vector<int> view_counts = get_view_counts(); vector<double> crp_scores; vector<double>::iterator it = alphas_to_score.begin(); int num_cols = get_num_cols(); for(; it!=alphas_to_score.end(); it++) { double alpha_to_score = *it; double this_crp_score = numerics::calc_crp_alpha_conditional(view_counts, alpha_to_score, num_cols, true); crp_scores.push_back(this_crp_score); } return crp_scores; } double State::transition_crp_alpha() { // to make score_crp not calculate absolute, need to track score deltas // and apply delta to crp_score double crp_score_0 = get_crp_score(); vector<double> unorm_logps = calc_crp_marginals(crp_alpha_grid); double rand_u = draw_rand_u(); int draw = numerics::draw_sample_unnormalized(unorm_logps, rand_u); crp_alpha = crp_alpha_grid[draw]; crp_score = unorm_logps[draw]; double crp_score_delta = crp_score - crp_score_0; return crp_score_delta; } double State::transition(MatrixD &data) { vector<int> which_transitions = create_sequence(3); //FIXME: use own shuffle so seed control is in effect std::random_shuffle(which_transitions.begin(), which_transitions.end()); double score_delta = 0; vector<int>::iterator it; cout << "view_lookup: " << view_lookup << endl; for(it=which_transitions.begin(); it!=which_transitions.end(); it++) { int which_transition = *it; if(which_transition==0) { score_delta += transition_views(data); } else if(which_transition==1) { score_delta += transition_features(data); } else if(which_transition==2) { score_delta += transition_crp_alpha(); } } return score_delta; } void State::construct_hyper_grids(MatrixD data, int N_GRID) { // some helper variables for hyper grids vector<double> paramRange = linspace(0.03, .97, N_GRID/2); int APPEND_N = (N_GRID + 1) / 2; int data_num_cols = data.size2(); // constrcut alpha grid vector<double> crp_alpha_grid_append = log_linspace(1., data_num_cols, APPEND_N); crp_alpha_grid = append(paramRange, crp_alpha_grid_append); } double State::draw_rand_u() { return rng.next(); } int State::draw_rand_i(int max) { return rng.nexti(max); } <commit_msg>remove some prints<commit_after>#include "State.h" using namespace std; // num_cols should be set in constructor State::State(MatrixD &data, vector<int> global_row_indices, vector<int> global_col_indices, int N_GRID) { crp_alpha = 0.8; int num_rows = data.size1(); construct_hyper_grids(data, N_GRID); vector<vector<int> > column_partition; column_partition = determine_crp_init(global_col_indices, crp_alpha, rng); vector<vector<int> >::iterator cp_it; for(cp_it=column_partition.begin(); cp_it!=column_partition.end(); cp_it++) { vector<int> column_indices = *cp_it; MatrixD data_subset = extract_columns(data, column_indices); View *p_v = new View(data_subset, global_row_indices, column_indices); views.insert(p_v); vector<int>::iterator ci_it; for(ci_it=column_indices.begin(); ci_it!=column_indices.end(); ci_it++) { int column_index = *ci_it; view_lookup[column_index] = p_v; } } } int State::get_num_cols() const { return view_lookup.size(); } int State::get_num_views() const { return views.size(); } vector<int> State::get_view_counts() const { vector<int> view_counts; set<View*>::iterator it; for(it=views.begin(); it!=views.end(); it++) { View &v = (**it); int view_num_cols = v.get_num_cols(); view_counts.push_back(view_num_cols); } return view_counts; } double State::insert_feature(int feature_idx, vector<double> feature_data, View &which_view) { double crp_logp_delta, data_logp_delta; double score_delta = calc_feature_view_predictive_logp(feature_data, which_view, crp_logp_delta, data_logp_delta); vector<int> data_global_row_indices = create_sequence(feature_data.size()); which_view.insert_col(feature_data, data_global_row_indices, feature_idx); view_lookup[feature_idx] = &which_view; crp_score += crp_logp_delta; data_score += data_logp_delta; return score_delta; } double State::sample_insert_feature(int feature_idx, vector<double> feature_data, View &singleton_view) { vector<double> unorm_logps = calc_feature_view_predictive_logps(feature_data); double rand_u = draw_rand_u(); int draw = numerics::draw_sample_unnormalized(unorm_logps, rand_u); View &which_view = get_view(draw); double score_delta = insert_feature(feature_idx, feature_data, which_view); remove_if_empty(singleton_view); return score_delta; } double State::remove_feature(int feature_idx, vector<double> feature_data, View** p_p_singleton_view) { map<int,View*>::iterator it = view_lookup.find(feature_idx); assert(it!=view_lookup.end()); View &which_view = *(it->second); view_lookup.erase(it); int view_num_cols = which_view.get_num_cols(); double data_logp_delta = which_view.remove_col(feature_idx); double crp_logp_delta, other_data_logp_delta; double score_delta = calc_feature_view_predictive_logp(feature_data, which_view, crp_logp_delta, other_data_logp_delta); // if(view_num_cols==1) { *p_p_singleton_view = &which_view; } else { *p_p_singleton_view = &get_new_view(); } //DON"T REMOVE HERE //remove_if_empty(which_view); crp_score -= crp_logp_delta; //data_score -= data_logp_delta; data_score -= other_data_logp_delta; // // FIXME : need to record partitioning and pass that in for scoring of state if(other_data_logp_delta!=data_logp_delta) { cout << "get_marginal_logp(): " << get_marginal_logp(); cout << ", other_data_logp_delta: " << other_data_logp_delta; cout << ", data_logp_delta: " << data_logp_delta << endl; } return score_delta; } double State::transition_feature(int feature_idx, vector<double> feature_data) { double score_delta = 0; View **p_p_singleton_view; *p_p_singleton_view = 0; score_delta += remove_feature(feature_idx, feature_data, p_p_singleton_view); score_delta += sample_insert_feature(feature_idx, feature_data, **p_p_singleton_view); return score_delta; } double State::transition_features(MatrixD &data) { double score_delta = 0; vector<int> feature_indices = create_sequence(data.size2()); vector<int>::iterator it; for(it=feature_indices.begin(); it!=feature_indices.end(); it++) { int feature_idx = *it; vector<double> feature_data = extract_col(data, feature_idx); score_delta += transition_feature(feature_idx, feature_data); } return score_delta; } View& State::get_new_view() { View *p_new_view = new View(); views.insert(p_new_view); return *p_new_view; } View& State::get_view(int view_idx) { assert(view_idx <= views.size()); bool not_new = view_idx < views.size(); if(not_new) { set<View*>::iterator it = views.begin(); std::advance(it, view_idx); return **it; } else { // This shouldn't happen anymore assert(1==0); return get_new_view(); } } void State::remove_if_empty(View& which_view) { if(which_view.get_num_cols()==0) { views.erase(views.find(&which_view)); delete &which_view; } } double State::get_crp_alpha() const { return crp_alpha; } double State::get_crp_score() const { return crp_score; } double State::get_data_score() const { return data_score; } double State::get_marginal_logp() const { return crp_score + data_score; } double State::transition_view_i(int which_view, map<int, vector<double> > row_data_map) { // assumes views set ordering stays constant between calls set<View*>::iterator it = views.begin(); std::advance(it, which_view); View &v = **it; double score_delta = v.transition(row_data_map); data_score += score_delta; return score_delta; } double State::transition_views(MatrixD &data) { vector<int> global_column_indices = create_sequence(data.size2()); // double score_delta = 0; // ordering doesn't matter, don't need to shuffle for(int view_idx=0; view_idx<get_num_views(); view_idx++) { View &v = get_view(view_idx); vector<int> view_cols = get_indices_to_reorder(global_column_indices, v.global_to_local); MatrixD data_subset = extract_columns(data, view_cols); map<int, vector<double> > data_subset_map = construct_data_map(data_subset); score_delta += transition_view_i(view_idx, data_subset_map); } return score_delta; } double State::calc_feature_view_predictive_logp(vector<double> col_data, View v, double &crp_log_delta, double &data_log_delta) const { int view_column_count = v.get_num_cols(); int num_columns = get_num_cols(); crp_log_delta = numerics::calc_cluster_crp_logp(view_column_count, num_columns, crp_alpha); // vector<int> data_global_row_indices = create_sequence(col_data.size()); data_log_delta = v.calc_column_predictive_logp(col_data, data_global_row_indices); // double score_delta = data_log_delta + crp_log_delta; return score_delta; } vector<double> State::calc_feature_view_predictive_logps(vector<double> col_data) const { vector<double> logps; set<View*>::iterator it; double crp_log_delta, data_log_delta; for(it=views.begin(); it!=views.end(); it++) { View &v = **it; double score_delta = calc_feature_view_predictive_logp(col_data, v, crp_log_delta, data_log_delta); logps.push_back(score_delta); } return logps; } double State::calc_crp_marginal() const { vector<int> view_counts = get_view_counts(); int num_cols = get_num_cols(); return numerics::calc_crp_alpha_conditional(view_counts, crp_alpha, num_cols, true); } vector<double> State::calc_crp_marginals(vector<double> alphas_to_score) const { vector<int> view_counts = get_view_counts(); vector<double> crp_scores; vector<double>::iterator it = alphas_to_score.begin(); int num_cols = get_num_cols(); for(; it!=alphas_to_score.end(); it++) { double alpha_to_score = *it; double this_crp_score = numerics::calc_crp_alpha_conditional(view_counts, alpha_to_score, num_cols, true); crp_scores.push_back(this_crp_score); } return crp_scores; } double State::transition_crp_alpha() { // to make score_crp not calculate absolute, need to track score deltas // and apply delta to crp_score double crp_score_0 = get_crp_score(); vector<double> unorm_logps = calc_crp_marginals(crp_alpha_grid); double rand_u = draw_rand_u(); int draw = numerics::draw_sample_unnormalized(unorm_logps, rand_u); crp_alpha = crp_alpha_grid[draw]; crp_score = unorm_logps[draw]; double crp_score_delta = crp_score - crp_score_0; return crp_score_delta; } double State::transition(MatrixD &data) { vector<int> which_transitions = create_sequence(3); //FIXME: use own shuffle so seed control is in effect std::random_shuffle(which_transitions.begin(), which_transitions.end()); double score_delta = 0; vector<int>::iterator it; cout << "view_lookup: " << view_lookup << endl; for(it=which_transitions.begin(); it!=which_transitions.end(); it++) { int which_transition = *it; if(which_transition==0) { score_delta += transition_views(data); } else if(which_transition==1) { score_delta += transition_features(data); } else if(which_transition==2) { score_delta += transition_crp_alpha(); } } return score_delta; } void State::construct_hyper_grids(MatrixD data, int N_GRID) { // some helper variables for hyper grids vector<double> paramRange = linspace(0.03, .97, N_GRID/2); int APPEND_N = (N_GRID + 1) / 2; int data_num_cols = data.size2(); // constrcut alpha grid vector<double> crp_alpha_grid_append = log_linspace(1., data_num_cols, APPEND_N); crp_alpha_grid = append(paramRange, crp_alpha_grid_append); } double State::draw_rand_u() { return rng.next(); } int State::draw_rand_i(int max) { return rng.nexti(max); } <|endoftext|>
<commit_before>#include "quering.hh" unsigned char * read_binary_file(const char * filename, size_t filesize) { //Get filesize int fd; unsigned char * map; fd = open(filename, O_RDONLY); if (fd == -1) { perror("Error opening file for reading"); exit(EXIT_FAILURE); } map = (unsigned char *)mmap(0, filesize, PROT_READ, MAP_SHARED, fd, 0); if (map == MAP_FAILED) { close(fd); perror("Error mmapping the file"); exit(EXIT_FAILURE); } return map; } QueryEngine::QueryEngine(const char * filepath) : decoder(filepath) { //Create filepaths std::string basepath(filepath); std::string path_to_hashtable = basepath + "/probing_hash.dat"; std::string path_to_data_bin = basepath + "/binfile.dat"; std::string path_to_source_vocabid = basepath + "/source_vocabids"; ///Source phrase vocabids read_map(&source_vocabids, path_to_source_vocabid.c_str()); //Target phrase vocabIDs vocabids = decoder.get_target_lookup_map(); //Read config file std::string line; std::ifstream config ((basepath + "/config").c_str()); //Check API version: getline(config, line); if (atoi(line.c_str()) != API_VERSION) { std::cerr << "The ProbingPT API has changed, please rebinarize your phrase tables." << std::endl; exit(EXIT_FAILURE); } //Get tablesize. getline(config, line); int tablesize = atoi(line.c_str()); //Number of scores getline(config, line); num_scores = atoi(line.c_str()); //do we have a reordering table getline(config, line); std::transform(line.begin(), line.end(), line.begin(), ::tolower); //Get the boolean in lowercase is_reordering = false; if (line == "true") { is_reordering = true; std::cerr << "WARNING. REORDERING TABLES NOT SUPPORTED YET." << std::endl; } config.close(); //Mmap binary table struct stat filestatus; stat(path_to_data_bin.c_str(), &filestatus); binary_filesize = filestatus.st_size; binary_mmaped = read_binary_file(path_to_data_bin.c_str(), binary_filesize); //Read hashtable size_t table_filesize = Table::Size(tablesize, 1.2); mem = readTable(path_to_hashtable.c_str(), table_filesize); Table table_init(mem, table_filesize); table = table_init; std::cerr << "Initialized successfully! " << std::endl; } QueryEngine::~QueryEngine() { //Clear mmap content from memory. munmap(binary_mmaped, binary_filesize); munmap(mem, table_filesize); } std::pair<bool, std::vector<target_text> > QueryEngine::query(std::vector<uint64_t> source_phrase) { bool found; std::vector<target_text> translation_entries; const Entry * entry; //TOO SLOW //uint64_t key = util::MurmurHashNative(&source_phrase[0], source_phrase.size()); uint64_t key = 0; for (int i = 0; i < source_phrase.size(); i++) { key += (source_phrase[i] << i); } found = table.Find(key, entry); if (found) { //The phrase that was searched for was found! We need to get the translation entries. //We will read the largest entry in bytes and then filter the unnecesarry with functions //from line_splitter uint64_t initial_index = entry -> GetValue(); unsigned int bytes_toread = entry -> bytes_toread; //ASK HIEU FOR MORE EFFICIENT WAY TO DO THIS! std::vector<unsigned char> encoded_text; //Assign to the vector the relevant portion of the array. encoded_text.reserve(bytes_toread); for (int i = 0; i < bytes_toread; i++) { encoded_text.push_back(binary_mmaped[i+initial_index]); } //Get only the translation entries necessary translation_entries = decoder.full_decode_line(encoded_text, num_scores); } std::pair<bool, std::vector<target_text> > output (found, translation_entries); return output; } std::pair<bool, std::vector<target_text> > QueryEngine::query(StringPiece source_phrase) { bool found; std::vector<target_text> translation_entries; const Entry * entry; //Convert source frase to VID std::vector<uint64_t> source_phrase_vid = getVocabIDs(source_phrase); //TOO SLOW //uint64_t key = util::MurmurHashNative(&source_phrase_vid[0], source_phrase_vid.size()); uint64_t key = 0; for (int i = 0; i < source_phrase_vid.size(); i++) { key += (source_phrase_vid[i] << i); } found = table.Find(key, entry); if (found) { //The phrase that was searched for was found! We need to get the translation entries. //We will read the largest entry in bytes and then filter the unnecesarry with functions //from line_splitter uint64_t initial_index = entry -> GetValue(); unsigned int bytes_toread = entry -> bytes_toread; //At the end of the file we can't readd + largest_entry cause we get a segfault. std::cerr << "Entry size is bytes is: " << bytes_toread << std::endl; //ASK HIEU FOR MORE EFFICIENT WAY TO DO THIS! std::vector<unsigned char> encoded_text; //Assign to the vector the relevant portion of the array. encoded_text.reserve(bytes_toread); for (int i = 0; i < bytes_toread; i++) { encoded_text.push_back(binary_mmaped[i+initial_index]); } //Get only the translation entries necessary translation_entries = decoder.full_decode_line(encoded_text, num_scores); } std::pair<bool, std::vector<target_text> > output (found, translation_entries); return output; } void QueryEngine::printTargetInfo(std::vector<target_text> target_phrases) { int entries = target_phrases.size(); for (int i = 0; i<entries; i++) { std::cout << "Entry " << i+1 << " of " << entries << ":" << std::endl; //Print text std::cout << getTargetWordsFromIDs(target_phrases[i].target_phrase, &vocabids) << "\t"; //Print probabilities: for (int j = 0; j<target_phrases[i].prob.size(); j++) { std::cout << target_phrases[i].prob[j] << " "; } std::cout << "\t"; //Print word_all1 for (int j = 0; j<target_phrases[i].word_all1.size(); j++) { if (j%2 == 0) { std::cout << (short)target_phrases[i].word_all1[j] << "-"; } else { std::cout << (short)target_phrases[i].word_all1[j] << " "; } } std::cout << std::endl; } } <commit_msg>local variable masking class variable<commit_after>#include "quering.hh" unsigned char * read_binary_file(const char * filename, size_t filesize) { //Get filesize int fd; unsigned char * map; fd = open(filename, O_RDONLY); if (fd == -1) { perror("Error opening file for reading"); exit(EXIT_FAILURE); } map = (unsigned char *)mmap(0, filesize, PROT_READ, MAP_SHARED, fd, 0); if (map == MAP_FAILED) { close(fd); perror("Error mmapping the file"); exit(EXIT_FAILURE); } return map; } QueryEngine::QueryEngine(const char * filepath) : decoder(filepath) { //Create filepaths std::string basepath(filepath); std::string path_to_hashtable = basepath + "/probing_hash.dat"; std::string path_to_data_bin = basepath + "/binfile.dat"; std::string path_to_source_vocabid = basepath + "/source_vocabids"; ///Source phrase vocabids read_map(&source_vocabids, path_to_source_vocabid.c_str()); //Target phrase vocabIDs vocabids = decoder.get_target_lookup_map(); //Read config file std::string line; std::ifstream config ((basepath + "/config").c_str()); //Check API version: getline(config, line); if (atoi(line.c_str()) != API_VERSION) { std::cerr << "The ProbingPT API has changed, please rebinarize your phrase tables." << std::endl; exit(EXIT_FAILURE); } //Get tablesize. getline(config, line); int tablesize = atoi(line.c_str()); //Number of scores getline(config, line); num_scores = atoi(line.c_str()); //do we have a reordering table getline(config, line); std::transform(line.begin(), line.end(), line.begin(), ::tolower); //Get the boolean in lowercase is_reordering = false; if (line == "true") { is_reordering = true; std::cerr << "WARNING. REORDERING TABLES NOT SUPPORTED YET." << std::endl; } config.close(); //Mmap binary table struct stat filestatus; stat(path_to_data_bin.c_str(), &filestatus); binary_filesize = filestatus.st_size; binary_mmaped = read_binary_file(path_to_data_bin.c_str(), binary_filesize); //Read hashtable table_filesize = Table::Size(tablesize, 1.2); mem = readTable(path_to_hashtable.c_str(), table_filesize); Table table_init(mem, table_filesize); table = table_init; std::cerr << "Initialized successfully! " << std::endl; } QueryEngine::~QueryEngine() { //Clear mmap content from memory. munmap(binary_mmaped, binary_filesize); munmap(mem, table_filesize); } std::pair<bool, std::vector<target_text> > QueryEngine::query(std::vector<uint64_t> source_phrase) { bool found; std::vector<target_text> translation_entries; const Entry * entry; //TOO SLOW //uint64_t key = util::MurmurHashNative(&source_phrase[0], source_phrase.size()); uint64_t key = 0; for (int i = 0; i < source_phrase.size(); i++) { key += (source_phrase[i] << i); } found = table.Find(key, entry); if (found) { //The phrase that was searched for was found! We need to get the translation entries. //We will read the largest entry in bytes and then filter the unnecesarry with functions //from line_splitter uint64_t initial_index = entry -> GetValue(); unsigned int bytes_toread = entry -> bytes_toread; //ASK HIEU FOR MORE EFFICIENT WAY TO DO THIS! std::vector<unsigned char> encoded_text; //Assign to the vector the relevant portion of the array. encoded_text.reserve(bytes_toread); for (int i = 0; i < bytes_toread; i++) { encoded_text.push_back(binary_mmaped[i+initial_index]); } //Get only the translation entries necessary translation_entries = decoder.full_decode_line(encoded_text, num_scores); } std::pair<bool, std::vector<target_text> > output (found, translation_entries); return output; } std::pair<bool, std::vector<target_text> > QueryEngine::query(StringPiece source_phrase) { bool found; std::vector<target_text> translation_entries; const Entry * entry; //Convert source frase to VID std::vector<uint64_t> source_phrase_vid = getVocabIDs(source_phrase); //TOO SLOW //uint64_t key = util::MurmurHashNative(&source_phrase_vid[0], source_phrase_vid.size()); uint64_t key = 0; for (int i = 0; i < source_phrase_vid.size(); i++) { key += (source_phrase_vid[i] << i); } found = table.Find(key, entry); if (found) { //The phrase that was searched for was found! We need to get the translation entries. //We will read the largest entry in bytes and then filter the unnecesarry with functions //from line_splitter uint64_t initial_index = entry -> GetValue(); unsigned int bytes_toread = entry -> bytes_toread; //At the end of the file we can't readd + largest_entry cause we get a segfault. std::cerr << "Entry size is bytes is: " << bytes_toread << std::endl; //ASK HIEU FOR MORE EFFICIENT WAY TO DO THIS! std::vector<unsigned char> encoded_text; //Assign to the vector the relevant portion of the array. encoded_text.reserve(bytes_toread); for (int i = 0; i < bytes_toread; i++) { encoded_text.push_back(binary_mmaped[i+initial_index]); } //Get only the translation entries necessary translation_entries = decoder.full_decode_line(encoded_text, num_scores); } std::pair<bool, std::vector<target_text> > output (found, translation_entries); return output; } void QueryEngine::printTargetInfo(std::vector<target_text> target_phrases) { int entries = target_phrases.size(); for (int i = 0; i<entries; i++) { std::cout << "Entry " << i+1 << " of " << entries << ":" << std::endl; //Print text std::cout << getTargetWordsFromIDs(target_phrases[i].target_phrase, &vocabids) << "\t"; //Print probabilities: for (int j = 0; j<target_phrases[i].prob.size(); j++) { std::cout << target_phrases[i].prob[j] << " "; } std::cout << "\t"; //Print word_all1 for (int j = 0; j<target_phrases[i].word_all1.size(); j++) { if (j%2 == 0) { std::cout << (short)target_phrases[i].word_all1[j] << "-"; } else { std::cout << (short)target_phrases[i].word_all1[j] << " "; } } std::cout << std::endl; } } <|endoftext|>
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "content/gpu/gpu_info_collector.h" #include <dlfcn.h> #include <vector> #include "base/file_util.h" #include "base/logging.h" #include "base/memory/scoped_ptr.h" #include "base/string_piece.h" #include "base/string_split.h" #include "base/string_tokenizer.h" #include "base/string_util.h" #include "ui/gfx/gl/gl_bindings.h" #include "ui/gfx/gl/gl_context.h" #include "ui/gfx/gl/gl_implementation.h" namespace { // PciDevice and PciAccess are defined to access libpci functions. Their // members match the corresponding structures defined by libpci in size up to // fields we may access. For those members we don't use, their names are // defined as "fieldX", etc., or, left out if they are declared after the // members we care about in libpci. struct PciDevice { PciDevice* next; uint16 field0; uint8 field1; uint8 field2; uint8 field3; int field4; uint16 vendor_id; uint16 device_id; uint16 device_class; }; struct PciAccess { unsigned int field0; int field1; int field2; char* field3; int field4; int field5; unsigned int field6; int field7; void (*function0)(); void (*function1)(); void (*function2)(); PciDevice* device_list; }; // Define function types. typedef PciAccess* (*FT_pci_alloc)(); typedef void (*FT_pci_init)(PciAccess*); typedef void (*FT_pci_cleanup)(PciAccess*); typedef void (*FT_pci_scan_bus)(PciAccess*); typedef void (*FT_pci_scan_bus)(PciAccess*); typedef int (*FT_pci_fill_info)(PciDevice*, int); typedef char* (*FT_pci_lookup_name)(PciAccess*, char*, int, int, ...); // This includes dynamically linked library handle and functions pointers from // libpci. struct PciInterface { void* lib_handle; FT_pci_alloc pci_alloc; FT_pci_init pci_init; FT_pci_cleanup pci_cleanup; FT_pci_scan_bus pci_scan_bus; FT_pci_fill_info pci_fill_info; FT_pci_lookup_name pci_lookup_name; }; // This checks if a system supports PCI bus. // We check the existence of /sys/bus/pci or /sys/bug/pci_express. bool IsPciSupported() { const FilePath pci_path("/sys/bus/pci/"); const FilePath pcie_path("/sys/bus/pci_express/"); return (file_util::PathExists(pci_path) || file_util::PathExists(pcie_path)); } // This dynamically opens libpci and get function pointers we need. Return // NULL if library fails to open or any functions can not be located. // Returned interface (if not NULL) should be deleted in FinalizeLibPci. PciInterface* InitializeLibPci(const char* lib_name) { void* handle = dlopen(lib_name, RTLD_LAZY); if (handle == NULL) { VLOG(1) << "Failed to dlopen " << lib_name; return NULL; } PciInterface* interface = new struct PciInterface; interface->lib_handle = handle; interface->pci_alloc = reinterpret_cast<FT_pci_alloc>( dlsym(handle, "pci_alloc")); interface->pci_init = reinterpret_cast<FT_pci_init>( dlsym(handle, "pci_init")); interface->pci_cleanup = reinterpret_cast<FT_pci_cleanup>( dlsym(handle, "pci_cleanup")); interface->pci_scan_bus = reinterpret_cast<FT_pci_scan_bus>( dlsym(handle, "pci_scan_bus")); interface->pci_fill_info = reinterpret_cast<FT_pci_fill_info>( dlsym(handle, "pci_fill_info")); interface->pci_lookup_name = reinterpret_cast<FT_pci_lookup_name>( dlsym(handle, "pci_lookup_name")); if (interface->pci_alloc == NULL || interface->pci_init == NULL || interface->pci_cleanup == NULL || interface->pci_scan_bus == NULL || interface->pci_fill_info == NULL || interface->pci_lookup_name == NULL) { VLOG(1) << "Missing required function(s) from " << lib_name; dlclose(handle); delete interface; return NULL; } return interface; } // This close the dynamically opened libpci and delete the interface. void FinalizeLibPci(PciInterface** interface) { DCHECK(interface && *interface && (*interface)->lib_handle); dlclose((*interface)->lib_handle); delete (*interface); *interface = NULL; } // Scan /etc/ati/amdpcsdb.default for "ReleaseVersion". // Return "" on failing. std::string CollectDriverVersionATI() { const FilePath::CharType kATIFileName[] = FILE_PATH_LITERAL("/etc/ati/amdpcsdb.default"); FilePath ati_file_path(kATIFileName); if (!file_util::PathExists(ati_file_path)) return ""; std::string contents; if (!file_util::ReadFileToString(ati_file_path, &contents)) return ""; StringTokenizer t(contents, "\r\n"); while (t.GetNext()) { std::string line = t.token(); if (StartsWithASCII(line, "ReleaseVersion=", true)) { size_t begin = line.find_first_of("0123456789"); if (begin != std::string::npos) { size_t end = line.find_first_not_of("0123456789.", begin); if (end == std::string::npos) return line.substr(begin); else return line.substr(begin, end - begin); } } } return ""; } } // namespace anonymous namespace gpu_info_collector { bool CollectGraphicsInfo(GPUInfo* gpu_info) { DCHECK(gpu_info); // TODO(zmo): need to consider the case where we are running on top of // desktop GL and GL_ARB_robustness extension is available. gpu_info->can_lose_context = (gfx::GetGLImplementation() == gfx::kGLImplementationEGLGLES2); gpu_info->finalized = true; return CollectGraphicsInfoGL(gpu_info); } bool CollectPreliminaryGraphicsInfo(GPUInfo* gpu_info) { DCHECK(gpu_info); bool rt = true; if (!CollectVideoCardInfo(gpu_info)) rt = false; if (gpu_info->vendor_id == 0x1002) { // ATI std::string ati_driver_version = CollectDriverVersionATI(); if (ati_driver_version != "") { gpu_info->driver_vendor = "ATI / AMD"; gpu_info->driver_version = ati_driver_version; } } return rt; } bool CollectVideoCardInfo(GPUInfo* gpu_info) { DCHECK(gpu_info); if (IsPciSupported() == false) { VLOG(1) << "PCI bus scanning is not supported"; return false; } // TODO(zmo): be more flexible about library name. PciInterface* interface = InitializeLibPci("libpci.so.3"); if (interface == NULL) interface = InitializeLibPci("libpci.so"); if (interface == NULL) { VLOG(1) << "Failed to locate libpci"; return false; } PciAccess* access = (interface->pci_alloc)(); DCHECK(access != NULL); (interface->pci_init)(access); (interface->pci_scan_bus)(access); std::vector<PciDevice*> gpu_list; PciDevice* gpu_active = NULL; for (PciDevice* device = access->device_list; device != NULL; device = device->next) { (interface->pci_fill_info)(device, 33); // Fill the IDs and class fields. // TODO(zmo): there might be other classes that qualify as display devices. if (device->device_class == 0x0300) { // Device class is DISPLAY_VGA. gpu_list.push_back(device); } } if (gpu_list.size() == 1) { gpu_active = gpu_list[0]; } else { // If more than one graphics card are identified, find the one that matches // gl VENDOR and RENDERER info. std::string gl_vendor_string = gpu_info->gl_vendor; std::string gl_renderer_string = gpu_info->gl_renderer; const int buffer_size = 255; scoped_array<char> buffer(new char[buffer_size]); std::vector<PciDevice*> candidates; for (size_t i = 0; i < gpu_list.size(); ++i) { PciDevice* gpu = gpu_list[i]; // The current implementation of pci_lookup_name returns the same pointer // as the passed in upon success, and a different one (NULL or a pointer // to an error message) upon failure. if ((interface->pci_lookup_name)(access, buffer.get(), buffer_size, 1, gpu->vendor_id) != buffer.get()) continue; std::string vendor_string = buffer.get(); const bool kCaseSensitive = false; if (!StartsWithASCII(gl_vendor_string, vendor_string, kCaseSensitive)) continue; if ((interface->pci_lookup_name)(access, buffer.get(), buffer_size, 2, gpu->vendor_id, gpu->device_id) != buffer.get()) continue; std::string device_string = buffer.get(); size_t begin = device_string.find_first_of('['); size_t end = device_string.find_last_of(']'); if (begin != std::string::npos && end != std::string::npos && begin < end) { device_string = device_string.substr(begin + 1, end - begin - 1); } if (StartsWithASCII(gl_renderer_string, device_string, kCaseSensitive)) { gpu_active = gpu; break; } // If a device's vendor matches gl VENDOR string, we want to consider the // possibility that libpci may not return the exact same name as gl // RENDERER string. candidates.push_back(gpu); } if (gpu_active == NULL && candidates.size() == 1) gpu_active = candidates[0]; } if (gpu_active != NULL) { gpu_info->vendor_id = gpu_active->vendor_id; gpu_info->device_id = gpu_active->device_id; } (interface->pci_cleanup)(access); FinalizeLibPci(&interface); return (gpu_active != NULL); } bool CollectDriverInfoGL(GPUInfo* gpu_info) { DCHECK(gpu_info); std::string gl_version_string = gpu_info->gl_version_string; std::vector<std::string> pieces; base::SplitStringAlongWhitespace(gl_version_string, &pieces); // In linux, the gl version string might be in the format of // GLVersion DriverVendor DriverVersion if (pieces.size() < 3) return false; std::string driver_version = pieces[2]; size_t pos = driver_version.find_first_not_of("0123456789."); if (pos == 0) return false; if (pos != std::string::npos) driver_version = driver_version.substr(0, pos); gpu_info->driver_vendor = pieces[1]; gpu_info->driver_version = driver_version; return true; } } // namespace gpu_info_collector <commit_msg>Collect driver vendor in linux through glXGetClientString.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "content/gpu/gpu_info_collector.h" #include <dlfcn.h> #include <vector> #include "base/file_util.h" #include "base/logging.h" #include "base/memory/scoped_ptr.h" #include "base/string_piece.h" #include "base/string_split.h" #include "base/string_tokenizer.h" #include "base/string_util.h" #include "ui/gfx/gl/gl_bindings.h" #include "ui/gfx/gl/gl_context.h" #include "ui/gfx/gl/gl_implementation.h" namespace { // PciDevice and PciAccess are defined to access libpci functions. Their // members match the corresponding structures defined by libpci in size up to // fields we may access. For those members we don't use, their names are // defined as "fieldX", etc., or, left out if they are declared after the // members we care about in libpci. struct PciDevice { PciDevice* next; uint16 field0; uint8 field1; uint8 field2; uint8 field3; int field4; uint16 vendor_id; uint16 device_id; uint16 device_class; }; struct PciAccess { unsigned int field0; int field1; int field2; char* field3; int field4; int field5; unsigned int field6; int field7; void (*function0)(); void (*function1)(); void (*function2)(); PciDevice* device_list; }; // Define function types. typedef PciAccess* (*FT_pci_alloc)(); typedef void (*FT_pci_init)(PciAccess*); typedef void (*FT_pci_cleanup)(PciAccess*); typedef void (*FT_pci_scan_bus)(PciAccess*); typedef void (*FT_pci_scan_bus)(PciAccess*); typedef int (*FT_pci_fill_info)(PciDevice*, int); typedef char* (*FT_pci_lookup_name)(PciAccess*, char*, int, int, ...); // This includes dynamically linked library handle and functions pointers from // libpci. struct PciInterface { void* lib_handle; FT_pci_alloc pci_alloc; FT_pci_init pci_init; FT_pci_cleanup pci_cleanup; FT_pci_scan_bus pci_scan_bus; FT_pci_fill_info pci_fill_info; FT_pci_lookup_name pci_lookup_name; }; // This checks if a system supports PCI bus. // We check the existence of /sys/bus/pci or /sys/bug/pci_express. bool IsPciSupported() { const FilePath pci_path("/sys/bus/pci/"); const FilePath pcie_path("/sys/bus/pci_express/"); return (file_util::PathExists(pci_path) || file_util::PathExists(pcie_path)); } // This dynamically opens libpci and get function pointers we need. Return // NULL if library fails to open or any functions can not be located. // Returned interface (if not NULL) should be deleted in FinalizeLibPci. PciInterface* InitializeLibPci(const char* lib_name) { void* handle = dlopen(lib_name, RTLD_LAZY); if (handle == NULL) { VLOG(1) << "Failed to dlopen " << lib_name; return NULL; } PciInterface* interface = new struct PciInterface; interface->lib_handle = handle; interface->pci_alloc = reinterpret_cast<FT_pci_alloc>( dlsym(handle, "pci_alloc")); interface->pci_init = reinterpret_cast<FT_pci_init>( dlsym(handle, "pci_init")); interface->pci_cleanup = reinterpret_cast<FT_pci_cleanup>( dlsym(handle, "pci_cleanup")); interface->pci_scan_bus = reinterpret_cast<FT_pci_scan_bus>( dlsym(handle, "pci_scan_bus")); interface->pci_fill_info = reinterpret_cast<FT_pci_fill_info>( dlsym(handle, "pci_fill_info")); interface->pci_lookup_name = reinterpret_cast<FT_pci_lookup_name>( dlsym(handle, "pci_lookup_name")); if (interface->pci_alloc == NULL || interface->pci_init == NULL || interface->pci_cleanup == NULL || interface->pci_scan_bus == NULL || interface->pci_fill_info == NULL || interface->pci_lookup_name == NULL) { VLOG(1) << "Missing required function(s) from " << lib_name; dlclose(handle); delete interface; return NULL; } return interface; } // This close the dynamically opened libpci and delete the interface. void FinalizeLibPci(PciInterface** interface) { DCHECK(interface && *interface && (*interface)->lib_handle); dlclose((*interface)->lib_handle); delete (*interface); *interface = NULL; } // Scan /etc/ati/amdpcsdb.default for "ReleaseVersion". // Return "" on failing. std::string CollectDriverVersionATI() { const FilePath::CharType kATIFileName[] = FILE_PATH_LITERAL("/etc/ati/amdpcsdb.default"); FilePath ati_file_path(kATIFileName); if (!file_util::PathExists(ati_file_path)) return ""; std::string contents; if (!file_util::ReadFileToString(ati_file_path, &contents)) return ""; StringTokenizer t(contents, "\r\n"); while (t.GetNext()) { std::string line = t.token(); if (StartsWithASCII(line, "ReleaseVersion=", true)) { size_t begin = line.find_first_of("0123456789"); if (begin != std::string::npos) { size_t end = line.find_first_not_of("0123456789.", begin); if (end == std::string::npos) return line.substr(begin); else return line.substr(begin, end - begin); } } } return ""; } // Use glXGetClientString to get driver vendor. // Return "" on failing. std::string CollectDriverVendorGlx() { // TODO(zmo): handle the EGL/GLES2 case. if (gfx::GetGLImplementation() != gfx::kGLImplementationDesktopGL) return ""; Display* display = XOpenDisplay(NULL); if (display == NULL) return ""; std::string vendor = glXGetClientString(display, GLX_VENDOR); XCloseDisplay(display); return vendor; } // Return 0 on unrecognized vendor. uint32 VendorStringToID(const std::string& vendor_string) { if (StartsWithASCII(vendor_string, "NVIDIA", true)) return 0x10de; if (StartsWithASCII(vendor_string, "ATI", true)) return 0x1002; // TODO(zmo): find a way to identify Intel cards. return 0; } } // namespace anonymous namespace gpu_info_collector { bool CollectGraphicsInfo(GPUInfo* gpu_info) { DCHECK(gpu_info); // TODO(zmo): need to consider the case where we are running on top of // desktop GL and GL_ARB_robustness extension is available. gpu_info->can_lose_context = (gfx::GetGLImplementation() == gfx::kGLImplementationEGLGLES2); gpu_info->finalized = true; return CollectGraphicsInfoGL(gpu_info); } bool CollectPreliminaryGraphicsInfo(GPUInfo* gpu_info) { DCHECK(gpu_info); bool rt = true; if (!CollectVideoCardInfo(gpu_info)) rt = false; if (gpu_info->vendor_id == 0x1002) { // ATI std::string ati_driver_version = CollectDriverVersionATI(); if (ati_driver_version != "") { gpu_info->driver_vendor = "ATI / AMD"; gpu_info->driver_version = ati_driver_version; } } return rt; } bool CollectVideoCardInfo(GPUInfo* gpu_info) { DCHECK(gpu_info); std::string driver_vendor = CollectDriverVendorGlx(); if (!driver_vendor.empty()) { gpu_info->driver_vendor = driver_vendor; uint32 vendor_id = VendorStringToID(driver_vendor); if (vendor_id != 0) gpu_info->vendor_id = vendor_id; } if (IsPciSupported() == false) { VLOG(1) << "PCI bus scanning is not supported"; return false; } // TODO(zmo): be more flexible about library name. PciInterface* interface = InitializeLibPci("libpci.so.3"); if (interface == NULL) interface = InitializeLibPci("libpci.so"); if (interface == NULL) { VLOG(1) << "Failed to locate libpci"; return false; } PciAccess* access = (interface->pci_alloc)(); DCHECK(access != NULL); (interface->pci_init)(access); (interface->pci_scan_bus)(access); std::vector<PciDevice*> gpu_list; PciDevice* gpu_active = NULL; for (PciDevice* device = access->device_list; device != NULL; device = device->next) { (interface->pci_fill_info)(device, 33); // Fill the IDs and class fields. // TODO(zmo): there might be other classes that qualify as display devices. if (device->device_class == 0x0300) { // Device class is DISPLAY_VGA. if (gpu_info->vendor_id == 0 || gpu_info->vendor_id == device->vendor_id) gpu_list.push_back(device); } } if (gpu_list.size() == 1) { gpu_active = gpu_list[0]; } else { // If more than one graphics card are identified, find the one that matches // gl VENDOR and RENDERER info. std::string gl_vendor_string = gpu_info->gl_vendor; std::string gl_renderer_string = gpu_info->gl_renderer; const int buffer_size = 255; scoped_array<char> buffer(new char[buffer_size]); std::vector<PciDevice*> candidates; for (size_t i = 0; i < gpu_list.size(); ++i) { PciDevice* gpu = gpu_list[i]; // The current implementation of pci_lookup_name returns the same pointer // as the passed in upon success, and a different one (NULL or a pointer // to an error message) upon failure. if ((interface->pci_lookup_name)(access, buffer.get(), buffer_size, 1, gpu->vendor_id) != buffer.get()) continue; std::string vendor_string = buffer.get(); const bool kCaseSensitive = false; if (!StartsWithASCII(gl_vendor_string, vendor_string, kCaseSensitive)) continue; if ((interface->pci_lookup_name)(access, buffer.get(), buffer_size, 2, gpu->vendor_id, gpu->device_id) != buffer.get()) continue; std::string device_string = buffer.get(); size_t begin = device_string.find_first_of('['); size_t end = device_string.find_last_of(']'); if (begin != std::string::npos && end != std::string::npos && begin < end) { device_string = device_string.substr(begin + 1, end - begin - 1); } if (StartsWithASCII(gl_renderer_string, device_string, kCaseSensitive)) { gpu_active = gpu; break; } // If a device's vendor matches gl VENDOR string, we want to consider the // possibility that libpci may not return the exact same name as gl // RENDERER string. candidates.push_back(gpu); } if (gpu_active == NULL && candidates.size() == 1) gpu_active = candidates[0]; } if (gpu_active != NULL) { gpu_info->vendor_id = gpu_active->vendor_id; gpu_info->device_id = gpu_active->device_id; } (interface->pci_cleanup)(access); FinalizeLibPci(&interface); return (gpu_active != NULL); } bool CollectDriverInfoGL(GPUInfo* gpu_info) { DCHECK(gpu_info); std::string gl_version_string = gpu_info->gl_version_string; std::vector<std::string> pieces; base::SplitStringAlongWhitespace(gl_version_string, &pieces); // In linux, the gl version string might be in the format of // GLVersion DriverVendor DriverVersion if (pieces.size() < 3) return false; std::string driver_version = pieces[2]; size_t pos = driver_version.find_first_not_of("0123456789."); if (pos == 0) return false; if (pos != std::string::npos) driver_version = driver_version.substr(0, pos); gpu_info->driver_vendor = pieces[1]; gpu_info->driver_version = driver_version; return true; } } // namespace gpu_info_collector <|endoftext|>
<commit_before>#ifndef ITER_TAKEWHILE_H_ #define ITER_TAKEWHILE_H_ #include "filter.hpp" #include "internal/iterator_wrapper.hpp" #include "internal/iterbase.hpp" #include <iterator> #include <utility> namespace iter { namespace impl { template <typename FilterFunc, typename Container> class Taker; using TakeWhileFn = IterToolFnOptionalBindFirst<Taker, BoolTester>; } constexpr impl::TakeWhileFn takewhile{}; } template <typename FilterFunc, typename Container> class iter::impl::Taker { private: Container container_; mutable FilterFunc filter_func_; friend TakeWhileFn; Taker(FilterFunc filter_func, Container&& container) : container_(std::forward<Container>(container)), filter_func_(filter_func) {} public: Taker(Taker&&) = default; template <typename ContainerT> class Iterator { private: template <typename> friend class Iterator; using Holder = DerefHolder<iterator_deref<ContainerT>>; IteratorWrapper<ContainerT> sub_iter_; IteratorWrapper<ContainerT> sub_end_; Holder item_; FilterFunc* filter_func_; void inc_sub_iter() { ++sub_iter_; if (sub_iter_ != sub_end_) { item_.reset(*sub_iter_); } } void check_current() { if (sub_iter_ != sub_end_ && !(*filter_func_)(item_.get())) { sub_iter_ = sub_end_; } } public: using iterator_category = std::input_iterator_tag; using value_type = iterator_traits_deref<ContainerT>; using difference_type = std::ptrdiff_t; using pointer = value_type*; using reference = value_type&; Iterator(IteratorWrapper<ContainerT>&& sub_iter, IteratorWrapper<ContainerT>&& sub_end, FilterFunc& filter_func) : sub_iter_{std::move(sub_iter)}, sub_end_{std::move(sub_end)}, filter_func_(&filter_func) { if (sub_iter_ != sub_end_) { item_.reset(*sub_iter_); } check_current(); } typename Holder::reference operator*() { return item_.get(); } typename Holder::pointer operator->() { return item_.get_ptr(); } Iterator& operator++() { inc_sub_iter(); check_current(); return *this; } Iterator operator++(int) { auto ret = *this; ++*this; return ret; } template <typename T> bool operator!=(const Iterator<T>& other) const { return sub_iter_ != other.sub_iter_; } template <typename T> bool operator==(const Iterator<T>& other) const { return !(*this != other); } }; Iterator<Container> begin() { return {get_begin(container_), get_end(container_), filter_func_}; } Iterator<Container> end() { return {get_end(container_), get_end(container_), filter_func_}; } Iterator<AsConst<Container>> begin() const { return {get_begin(std::as_const(container_)), get_end(std::as_const(container_)), filter_func_}; } Iterator<AsConst<Container>> end() const { return {get_end(std::as_const(container_)), get_end(std::as_const(container_)), filter_func_}; } }; #endif <commit_msg>Uses std::invoke in takewhile<commit_after>#ifndef ITER_TAKEWHILE_H_ #define ITER_TAKEWHILE_H_ #include "filter.hpp" #include "internal/iterator_wrapper.hpp" #include "internal/iterbase.hpp" #include <functional> #include <iterator> #include <utility> namespace iter { namespace impl { template <typename FilterFunc, typename Container> class Taker; using TakeWhileFn = IterToolFnOptionalBindFirst<Taker, BoolTester>; } constexpr impl::TakeWhileFn takewhile{}; } template <typename FilterFunc, typename Container> class iter::impl::Taker { private: Container container_; mutable FilterFunc filter_func_; friend TakeWhileFn; Taker(FilterFunc filter_func, Container&& container) : container_(std::forward<Container>(container)), filter_func_(filter_func) {} public: Taker(Taker&&) = default; template <typename ContainerT> class Iterator { private: template <typename> friend class Iterator; using Holder = DerefHolder<iterator_deref<ContainerT>>; IteratorWrapper<ContainerT> sub_iter_; IteratorWrapper<ContainerT> sub_end_; Holder item_; FilterFunc* filter_func_; void inc_sub_iter() { ++sub_iter_; if (sub_iter_ != sub_end_) { item_.reset(*sub_iter_); } } void check_current() { if (sub_iter_ != sub_end_ && !std::invoke(*filter_func_, item_.get())) { sub_iter_ = sub_end_; } } public: using iterator_category = std::input_iterator_tag; using value_type = iterator_traits_deref<ContainerT>; using difference_type = std::ptrdiff_t; using pointer = value_type*; using reference = value_type&; Iterator(IteratorWrapper<ContainerT>&& sub_iter, IteratorWrapper<ContainerT>&& sub_end, FilterFunc& filter_func) : sub_iter_{std::move(sub_iter)}, sub_end_{std::move(sub_end)}, filter_func_(&filter_func) { if (sub_iter_ != sub_end_) { item_.reset(*sub_iter_); } check_current(); } typename Holder::reference operator*() { return item_.get(); } typename Holder::pointer operator->() { return item_.get_ptr(); } Iterator& operator++() { inc_sub_iter(); check_current(); return *this; } Iterator operator++(int) { auto ret = *this; ++*this; return ret; } template <typename T> bool operator!=(const Iterator<T>& other) const { return sub_iter_ != other.sub_iter_; } template <typename T> bool operator==(const Iterator<T>& other) const { return !(*this != other); } }; Iterator<Container> begin() { return {get_begin(container_), get_end(container_), filter_func_}; } Iterator<Container> end() { return {get_end(container_), get_end(container_), filter_func_}; } Iterator<AsConst<Container>> begin() const { return {get_begin(std::as_const(container_)), get_end(std::as_const(container_)), filter_func_}; } Iterator<AsConst<Container>> end() const { return {get_end(std::as_const(container_)), get_end(std::as_const(container_)), filter_func_}; } }; #endif <|endoftext|>
<commit_before>/****************************************************************/ /* MOOSE - Multiphysics Object Oriented Simulation Environment */ /* */ /* All contents are licensed under LGPL V2.1 */ /* See LICENSE for full restrictions */ /****************************************************************/ #include "ElasticEnergyMaterial.h" #include "RankTwoTensor.h" #include "ElasticityTensorR4.h" template<> InputParameters validParams<ElasticEnergyMaterial>() { InputParameters params = validParams<DerivativeFunctionMaterialBase>(); params.addClassDescription("Free energy material for the elastic energy contributions."); params.addParam<std::string>("base_name", "Material property base name"); params.addRequiredCoupledVar("args", "Arguments of F() - use vector coupling"); return params; } ElasticEnergyMaterial::ElasticEnergyMaterial(const std::string & name, InputParameters parameters) : DerivativeFunctionMaterialBase(name, parameters), _base_name(isParamValid("base_name") ? getParam<std::string>("base_name") + "_" : "" ), _stress(getMaterialProperty<RankTwoTensor>(_base_name + "stress")), _elasticity_tensor(getMaterialProperty<ElasticityTensorR4>(_base_name + "elasticity_tensor")), _strain(getMaterialProperty<RankTwoTensor>(_base_name + "elastic_strain")) { _dstrain.resize(_nargs); _d2strain.resize(_nargs); _delasticity_tensor.resize(_nargs); _d2elasticity_tensor.resize(_nargs); // fetch stress and elasticity tensor derivatives (in simple eigenstrain models this is is only w.r.t. 'c') for (unsigned int i = 0; i < _nargs; ++i) { _dstrain[i] = &getMaterialPropertyDerivative<RankTwoTensor>(_base_name + "elastic_strain", _arg_names[i]); _delasticity_tensor[i] = &getMaterialPropertyDerivative<ElasticityTensorR4>(_base_name + "elasticity_tensor", _arg_names[i]); _d2strain[i].resize(_nargs); _d2elasticity_tensor[i].resize(_nargs); for (unsigned int j = 0; j < _nargs; ++j) { _d2strain[i][j] = &getMaterialPropertyDerivative<RankTwoTensor>(_base_name + "elastic_strain", _arg_names[i], _arg_names[j]); _d2elasticity_tensor[i][j] = &getMaterialPropertyDerivative<ElasticityTensorR4>(_base_name + "elasticity_tensor", _arg_names[i], _arg_names[j]); } } } Real ElasticEnergyMaterial::computeF() { return 0.5 * _stress[_qp].doubleContraction(_strain[_qp]); } Real ElasticEnergyMaterial::computeDF(unsigned int i_var) { unsigned int i = argIndex(i_var); // product rule d/di computeF return 0.5 * ( ( // dstress/di (*_delasticity_tensor[i])[_qp] * _strain[_qp] + _elasticity_tensor[_qp] * (*_dstrain[i])[_qp] ).doubleContraction(_strain[_qp]) + _stress[_qp].doubleContraction((*_dstrain[i])[_qp]) ); } Real ElasticEnergyMaterial::computeD2F(unsigned int i_var, unsigned int j_var) { unsigned int i = argIndex(i_var); unsigned int j = argIndex(j_var); // product rule d/dj computeDF return 0.5 * ( ( (*_d2elasticity_tensor[i][j])[_qp] * _strain[_qp] + (*_delasticity_tensor[i])[_qp] * (*_dstrain[j])[_qp] + (*_delasticity_tensor[j])[_qp] * (*_dstrain[i])[_qp] + _elasticity_tensor[_qp] * (*_d2strain[i][j])[_qp] ).doubleContraction(_strain[_qp]) + ( (*_delasticity_tensor[i])[_qp] * _strain[_qp] + _elasticity_tensor[_qp] * (*_dstrain[i])[_qp] ).doubleContraction((*_dstrain[j])[_qp]) + ( // dstress/dj (*_delasticity_tensor[j])[_qp] * _strain[_qp] + _elasticity_tensor[_qp] * (*_dstrain[j])[_qp] ).doubleContraction((*_dstrain[i])[_qp]) + _stress[_qp].doubleContraction((*_d2strain[i][j])[_qp]) ); } <commit_msg>Update ElStatEnergyMaterial.C<commit_after>/****************************************************************/ /* MOOSE - Multiphysics Object Oriented Simulation Environment */ /* */ /* All contents are licensed under LGPL V2.1 */ /* See LICENSE for full restrictions */ /****************************************************************/ //#include "ElasticEnergyMaterial.h" #include "ElStatEnergyMaterial.h" //#include "RankTwoTensor.h" //#include "ElasticityTensorR4.h" template<> InputParameters validParams<ElStatEnergyMaterial>() { InputParameters params = validParams<DerivativeFunctionMaterialBase>(); params.addClassDescription("Free energy material for the electrical energy contributions."); params.addParam<std::string>("base_name", "Material property base name"); //params.addRequiredCoupledVar("args", "Arguments of F() - use vector coupling"); return params; } ElasticEnergyMaterial::ElasticEnergyMaterial(const std::string & name, InputParameters parameters) : DerivativeFunctionMaterialBase(name, parameters), _base_name(isParamValid("base_name") ? getParam<std::string>("base_name") + "_" : "" ), _stress(getMaterialProperty<RankTwoTensor>(_base_name + "stress")), _elasticity_tensor(getMaterialProperty<ElasticityTensorR4>(_base_name + "elasticity_tensor")), _strain(getMaterialProperty<RankTwoTensor>(_base_name + "elastic_strain")) { _dstrain.resize(_nargs); _d2strain.resize(_nargs); _delasticity_tensor.resize(_nargs); _d2elasticity_tensor.resize(_nargs); // fetch stress and elasticity tensor derivatives (in simple eigenstrain models this is is only w.r.t. 'c') for (unsigned int i = 0; i < _nargs; ++i) { _dstrain[i] = &getMaterialPropertyDerivative<RankTwoTensor>(_base_name + "elastic_strain", _arg_names[i]); _delasticity_tensor[i] = &getMaterialPropertyDerivative<ElasticityTensorR4>(_base_name + "elasticity_tensor", _arg_names[i]); _d2strain[i].resize(_nargs); _d2elasticity_tensor[i].resize(_nargs); for (unsigned int j = 0; j < _nargs; ++j) { _d2strain[i][j] = &getMaterialPropertyDerivative<RankTwoTensor>(_base_name + "elastic_strain", _arg_names[i], _arg_names[j]); _d2elasticity_tensor[i][j] = &getMaterialPropertyDerivative<ElasticityTensorR4>(_base_name + "elasticity_tensor", _arg_names[i], _arg_names[j]); } } } Real ElasticEnergyMaterial::computeF() { return 0.5 * _stress[_qp].doubleContraction(_strain[_qp]); } Real ElasticEnergyMaterial::computeDF(unsigned int i_var) { unsigned int i = argIndex(i_var); // product rule d/di computeF return 0.5 * ( ( // dstress/di (*_delasticity_tensor[i])[_qp] * _strain[_qp] + _elasticity_tensor[_qp] * (*_dstrain[i])[_qp] ).doubleContraction(_strain[_qp]) + _stress[_qp].doubleContraction((*_dstrain[i])[_qp]) ); } Real ElasticEnergyMaterial::computeD2F(unsigned int i_var, unsigned int j_var) { unsigned int i = argIndex(i_var); unsigned int j = argIndex(j_var); // product rule d/dj computeDF return 0.5 * ( ( (*_d2elasticity_tensor[i][j])[_qp] * _strain[_qp] + (*_delasticity_tensor[i])[_qp] * (*_dstrain[j])[_qp] + (*_delasticity_tensor[j])[_qp] * (*_dstrain[i])[_qp] + _elasticity_tensor[_qp] * (*_d2strain[i][j])[_qp] ).doubleContraction(_strain[_qp]) + ( (*_delasticity_tensor[i])[_qp] * _strain[_qp] + _elasticity_tensor[_qp] * (*_dstrain[i])[_qp] ).doubleContraction((*_dstrain[j])[_qp]) + ( // dstress/dj (*_delasticity_tensor[j])[_qp] * _strain[_qp] + _elasticity_tensor[_qp] * (*_dstrain[j])[_qp] ).doubleContraction((*_dstrain[i])[_qp]) + _stress[_qp].doubleContraction((*_d2strain[i][j])[_qp]) ); } <|endoftext|>
<commit_before>// C++ General Utility Library (mailto:cgul@zethes.com) // Copyright (C) 2012-2014, Joshua Brookover and Amber Thrall // All rights reserved. /** @file Timer.cpp */ #include "Timer.hpp" #if defined(CGUL_LINUX) || defined(CGUL_MACOS) # include <sys/time.h> # include <unistd.h> #endif CGUL::Float64 CGUL::Timer::GetFrequency() { # ifdef CGUL_WINDOWS static UInt64 cachedFrequency = 0; if (cachedFrequency == 0) { LARGE_INTEGER frequency; QueryPerformanceFrequency(&frequency); cachedFrequency = frequency.QuadPart; } return (Float64)cachedFrequency; # else return 1000000.0; # endif } CGUL::UInt64 CGUL::Timer::GetTime() { # ifdef CGUL_WINDOWS LARGE_INTEGER counter; QueryPerformanceCounter(&counter); return counter.QuadPart; # else struct timeval time; gettimeofday(&time, NULL); return time.tv_sec * 1000000 + time.tv_usec; # endif } /** @details A program that never sleeps can cause CPU thrashing so its a good idea to call sleep * and let the CPU take care of other things for a short while. Sleeping will cause the currently * active thread to halt for the given amount of time. As little as 1 millisecond is enough to * take a huge load off of the CPU and its recommended that applications in a constant loop makes * a call each tick to the @ref Sleep method. It is not guaranteed (and in fact very unlikely) * that this method will halt the program for @em exactly the amount of milliseconds specified. * @param milliseconds The amount of time to sleep in milliseconds. */ _CGUL_EXPORT void CGUL::Timer::Sleep(UInt32 milliseconds) { # ifdef CGUL_WINDOWS ::Sleep(milliseconds); # else usleep(milliseconds * 1000); # endif } /** @details Same as the @ref GetMilliseconds method but in seconds. * @see GetMilliseconds * @returns An undefined time in seconds. */ _CGUL_EXPORT CGUL::Float64 CGUL::Timer::GetSeconds() { return (GetMilliseconds() / 1000.0); } /** @details Gets a time from the operating system in milliseconds. The time acquired is not * guaranteed to represent any significance aside from being incremental from a previous * @ref GetMilliseconds or @ref GetSeconds call. In other words, this time does not represent the * current time of day, the time the operating system has been up, or any other such data. The * only purpose of this method is to compare two time stamps to find a delta in time. * @returns An undefined time in milliseconds. */ _CGUL_EXPORT CGUL::Float64 CGUL::Timer::GetMilliseconds() { return (GetTime() / (GetFrequency() / 1000.0)); } /** @details The value here is practically guaranteed to be different everytime it's called. The * value is primarily useful for seeding random numbers. * @returns A high precision timestamp of little value to anyone. */ _CGUL_EXPORT CGUL::UInt64 CGUL::Timer::GetRawTime() { return GetTime(); } /** */ _CGUL_EXPORT CGUL::Timer::Timer() { running = false; startTime = GetTime(); storedTime = 0; } /** @details Acts just as the start would on a stop watch. If the clock is currently stopped it * will resume the last time recorded. If the clock is already started, it will do nothing. * @see Stop * @see Reset */ _CGUL_EXPORT void CGUL::Timer::Start() { startTime = GetTime() - storedTime; running = true; } /** @details Acts just as the stop would on a stop watch. The current time will be recorded and * the clock will stop progressing forward. This method will not reset the clock to zero, for * that the @ref Reset method must be called separately. If the clock is already stopped then this * method does nothing. * @see Start * @see Reset */ _CGUL_EXPORT void CGUL::Timer::Stop() { if (running) { UInt64 end = GetTime(); storedTime = end - startTime; running = false; } } /** @details Acts just as the reset would on a stop watch. The current time is set to zero but the * state of the clock is not changed. If the clock was running when this method was called then * it will continue to run starting from zero. In order to both stop and reset the clock, the * methods @ref Stop and @ref Reset must be called in that order. Calling the @ref Start method * after calling @ref Reset will cause the clock to pick up the time where it left off. * @see Start * @see Stop */ _CGUL_EXPORT void CGUL::Timer::Reset() { startTime = GetTime(); storedTime = 0; } /** @details Same as @ref GetElapsedMilliseconds method but in seconds. * @see GetElapsedMilliseconds * @returns Elapsed time in seconds. */ _CGUL_EXPORT CGUL::Float64 CGUL::Timer::GetElapsedSeconds() const { return GetElapsedMilliseconds() / 1000.0; } /** @details Represents the time currently recorded by this clock some time after a call to the * Start method. If a clock has not been started this method will simply return zero. * @returns Elapsed time in milliseconds. */ _CGUL_EXPORT CGUL::Float64 CGUL::Timer::GetElapsedMilliseconds() const { if (running) { UInt64 end = GetTime(); return (end - startTime) / GetFrequency(); } else { return storedTime / GetFrequency(); } } /** @details Determines time in between calls and returns a floating point (decimal) time in * seconds. It is recommended that this method be used instead of @ref Start, @ref Stop, and * @ref Reset for delta time calculations because it is better optimized for that purpose and will * yield more accurate results. Additionally, this method will reset the timer every time it is * called so the @ref GetElapsedSeconds and @ref GetElapsedMilliseconds methods will not give * accurate results. * @note The first time this method is called it will return the time between the creation of the * @ref Timer object and the time the method was called. For best use create the @ref Timer * immediately before it is to be used. * @returns A floating pointer decimal number representing the time in seconds since the last call * to this method. */ _CGUL_EXPORT CGUL::Float64 CGUL::Timer::GetDeltaTime() { UInt64 time = GetTime(); Float64 deltaTime = (time - startTime) / GetFrequency(); startTime = time; return deltaTime; } <commit_msg>Fixed silly logic error in timers. Needs to be double checked on unix.<commit_after>// C++ General Utility Library (mailto:cgul@zethes.com) // Copyright (C) 2012-2014, Joshua Brookover and Amber Thrall // All rights reserved. /** @file Timer.cpp */ #include "Timer.hpp" #if defined(CGUL_LINUX) || defined(CGUL_MACOS) # include <sys/time.h> # include <unistd.h> #endif CGUL::Float64 CGUL::Timer::GetFrequency() { # ifdef CGUL_WINDOWS static UInt64 cachedFrequency = 0; if (cachedFrequency == 0) { LARGE_INTEGER frequency; QueryPerformanceFrequency(&frequency); cachedFrequency = frequency.QuadPart; } return (Float64)cachedFrequency; # else return 1000000.0; # endif } CGUL::UInt64 CGUL::Timer::GetTime() { # ifdef CGUL_WINDOWS LARGE_INTEGER counter; QueryPerformanceCounter(&counter); return counter.QuadPart; # else struct timeval time; gettimeofday(&time, NULL); return time.tv_sec * 1000000 + time.tv_usec; # endif } /** @details A program that never sleeps can cause CPU thrashing so its a good idea to call sleep * and let the CPU take care of other things for a short while. Sleeping will cause the currently * active thread to halt for the given amount of time. As little as 1 millisecond is enough to * take a huge load off of the CPU and its recommended that applications in a constant loop makes * a call each tick to the @ref Sleep method. It is not guaranteed (and in fact very unlikely) * that this method will halt the program for @em exactly the amount of milliseconds specified. * @param milliseconds The amount of time to sleep in milliseconds. */ _CGUL_EXPORT void CGUL::Timer::Sleep(UInt32 milliseconds) { # ifdef CGUL_WINDOWS ::Sleep(milliseconds); # else usleep(milliseconds * 1000); # endif } /** @details Same as the @ref GetMilliseconds method but in seconds. * @see GetMilliseconds * @returns An undefined time in seconds. */ _CGUL_EXPORT CGUL::Float64 CGUL::Timer::GetSeconds() { return (GetMilliseconds() / 1000.0); } /** @details Gets a time from the operating system in milliseconds. The time acquired is not * guaranteed to represent any significance aside from being incremental from a previous * @ref GetMilliseconds or @ref GetSeconds call. In other words, this time does not represent the * current time of day, the time the operating system has been up, or any other such data. The * only purpose of this method is to compare two time stamps to find a delta in time. * @returns An undefined time in milliseconds. */ _CGUL_EXPORT CGUL::Float64 CGUL::Timer::GetMilliseconds() { return (GetTime() / (GetFrequency() / 1000.0)); } /** @details The value here is practically guaranteed to be different everytime it's called. The * value is primarily useful for seeding random numbers. * @returns A high precision timestamp of little value to anyone. */ _CGUL_EXPORT CGUL::UInt64 CGUL::Timer::GetRawTime() { return GetTime(); } /** */ _CGUL_EXPORT CGUL::Timer::Timer() { running = false; startTime = GetTime(); storedTime = 0; } /** @details Acts just as the start would on a stop watch. If the clock is currently stopped it * will resume the last time recorded. If the clock is already started, it will do nothing. * @see Stop * @see Reset */ _CGUL_EXPORT void CGUL::Timer::Start() { startTime = GetTime() - storedTime; running = true; } /** @details Acts just as the stop would on a stop watch. The current time will be recorded and * the clock will stop progressing forward. This method will not reset the clock to zero, for * that the @ref Reset method must be called separately. If the clock is already stopped then this * method does nothing. * @see Start * @see Reset */ _CGUL_EXPORT void CGUL::Timer::Stop() { if (running) { UInt64 end = GetTime(); storedTime = end - startTime; running = false; } } /** @details Acts just as the reset would on a stop watch. The current time is set to zero but the * state of the clock is not changed. If the clock was running when this method was called then * it will continue to run starting from zero. In order to both stop and reset the clock, the * methods @ref Stop and @ref Reset must be called in that order. Calling the @ref Start method * after calling @ref Reset will cause the clock to pick up the time where it left off. * @see Start * @see Stop */ _CGUL_EXPORT void CGUL::Timer::Reset() { startTime = GetTime(); storedTime = 0; } /** @details Same as @ref GetElapsedMilliseconds method but in seconds. * @see GetElapsedMilliseconds * @returns Elapsed time in seconds. */ _CGUL_EXPORT CGUL::Float64 CGUL::Timer::GetElapsedSeconds() const { return GetElapsedMilliseconds() / 1000.0; } /** @details Represents the time currently recorded by this clock some time after a call to the * Start method. If a clock has not been started this method will simply return zero. * @returns Elapsed time in milliseconds. */ _CGUL_EXPORT CGUL::Float64 CGUL::Timer::GetElapsedMilliseconds() const { if (running) { UInt64 end = GetTime(); return (end - startTime) / (GetFrequency() / 1000.0); } else { return storedTime / (GetFrequency() / 1000.0); } } /** @details Determines time in between calls and returns a floating point (decimal) time in * seconds. It is recommended that this method be used instead of @ref Start, @ref Stop, and * @ref Reset for delta time calculations because it is better optimized for that purpose and will * yield more accurate results. Additionally, this method will reset the timer every time it is * called so the @ref GetElapsedSeconds and @ref GetElapsedMilliseconds methods will not give * accurate results. * @note The first time this method is called it will return the time between the creation of the * @ref Timer object and the time the method was called. For best use create the @ref Timer * immediately before it is to be used. * @returns A floating pointer decimal number representing the time in seconds since the last call * to this method. */ _CGUL_EXPORT CGUL::Float64 CGUL::Timer::GetDeltaTime() { UInt64 time = GetTime(); Float64 deltaTime = (time - startTime) / GetFrequency(); startTime = time; return deltaTime; } <|endoftext|>
<commit_before> /* * * Copyright 2015 Telefonica Investigacion y Desarrollo, S.A.U * * This file is part of Orion Context Broker. * * Orion Context Broker 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. * * Orion Context Broker 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 Orion Context Broker. If not, see http://www.gnu.org/licenses/. * * For those usages not covered by this license please contact with * iot_support at tid dot es * * Author: Orion dev team */ #include "alarmMgr/alarmMgr.h" #include "mongoBackend/mongoSubscribeContext.h" #include "ngsi/ParseData.h" #include "ngsi10/SubscribeContextResponse.h" #include "common/statistics.h" #include "serviceRoutinesV2/postSubscriptions.h" /* **************************************************************************** * * postSubscriptions - */ extern std::string postSubscriptions ( ConnectionInfo* ciP, int components, std::vector<std::string>& compV, ParseData* parseDataP ) { SubscribeContextResponse scr; std::string answer; if (ciP->servicePathV.size() > 1) { const size_t MSG_SIZE = 96; // strlen(msg) + enough room for digits char errMsg[MSG_SIZE]; snprintf(errMsg, MSG_SIZE, "max *one* service-path allowed for subscriptions (%zd given)", ciP->servicePathV.size()); alarmMgr.badInput(clientIp, errMsg); scr.subscribeError.errorCode.fill(SccBadRequest, "max one service-path allowed for subscriptions"); TIMED_RENDER(answer = scr.render(SubscribeContext, ciP->outFormat, "")); return answer; } TIMED_MONGO(ciP->httpStatusCode = mongoSubscribeContext(&parseDataP->scr.res, &scr, ciP->tenant, ciP->uriParam, ciP->httpHeaders.xauthToken, ciP->servicePathV)); parseDataP->scr.res.release(); if (scr.subscribeError.errorCode.code != SccNone ) { TIMED_RENDER(answer = scr.render(SubscribeContext, JSON, "")); return answer; } std::string location = "/v2/subscriptions/" + scr.subscribeResponse.subscriptionId.string; ciP->httpHeader.push_back("Location"); ciP->httpHeaderValue.push_back(location); ciP->httpStatusCode = SccCreated; return ""; } <commit_msg>Fix style<commit_after> /* * * Copyright 2015 Telefonica Investigacion y Desarrollo, S.A.U * * This file is part of Orion Context Broker. * * Orion Context Broker 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. * * Orion Context Broker 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 Orion Context Broker. If not, see http://www.gnu.org/licenses/. * * For those usages not covered by this license please contact with * iot_support at tid dot es * * Author: Orion dev team */ #include "alarmMgr/alarmMgr.h" #include "mongoBackend/mongoSubscribeContext.h" #include "ngsi/ParseData.h" #include "ngsi10/SubscribeContextResponse.h" #include "common/statistics.h" #include "serviceRoutinesV2/postSubscriptions.h" /* **************************************************************************** * * postSubscriptions - */ extern std::string postSubscriptions ( ConnectionInfo* ciP, int components, std::vector<std::string>& compV, ParseData* parseDataP ) { SubscribeContextResponse scr; std::string answer; if (ciP->servicePathV.size() > 1) { const size_t MSG_SIZE = 96; // strlen(msg) + enough room for digits char errMsg[MSG_SIZE]; snprintf(errMsg, MSG_SIZE, "max *one* service-path allowed for subscriptions (%zd given)", ciP->servicePathV.size()); alarmMgr.badInput(clientIp, errMsg); scr.subscribeError.errorCode.fill(SccBadRequest, "max one service-path allowed for subscriptions"); TIMED_RENDER(answer = scr.render(SubscribeContext, ciP->outFormat, "")); return answer; } TIMED_MONGO(ciP->httpStatusCode = mongoSubscribeContext(&parseDataP->scr.res, &scr, ciP->tenant, ciP->uriParam, ciP->httpHeaders.xauthToken, ciP->servicePathV)); parseDataP->scr.res.release(); if (scr.subscribeError.errorCode.code != SccNone ) { TIMED_RENDER(answer = scr.render(SubscribeContext, JSON, "")); return answer; } std::string location = "/v2/subscriptions/" + scr.subscribeResponse.subscriptionId.string; ciP->httpHeader.push_back("Location"); ciP->httpHeaderValue.push_back(location); ciP->httpStatusCode = SccCreated; return ""; } <|endoftext|>
<commit_before>#define CATCH_CONFIG_RUNNER #include <QCanBusFrame> #include <QJsonArray> #include <QSignalSpy> #include <QStandardItemModel> #include <QTableView> #include <Qt> #include <QtWidgets/QApplication> #include <catch.hpp> #include <context.h> #include <fakeit.hpp> #include <canrawview.h> #include <gui/crvguiinterface.h> #include <log.h> #include <memory> #include <iostream> std::shared_ptr<spdlog::logger> kDefaultLogger; using namespace fakeit; #include <QStandardItemModel> class CanRawViewPrivate; TEST_CASE("Initialize table", "[canrawview]") { Mock<CRVGuiInterface> crvMock; Fake(Method(crvMock, setClearCbk)); Fake(Method(crvMock, setDockUndockCbk)); Fake(Method(crvMock, setSectionClikedCbk)); Fake(Method(crvMock, setFilterCbk)); Fake(Method(crvMock, setModel)); Fake(Method(crvMock, setSorting)); Fake(Method(crvMock, initTableView)); Fake(Method(crvMock, scrollToBottom)); When(Method(crvMock, mainWidget)).Return(NULL); When(Method(crvMock, isViewFrozen)).Return(false).Return(true).Return(true).Return(false).Return(true).Return(true); When(Method(crvMock, getSortOrder)).Return(Qt::AscendingOrder); When(Method(crvMock, getClickedColumn)).Return("rowID", "time", "id", "dir", "dlc", "data"); When(Method(crvMock, isColumnHidden)).Return(true, false, false, false, false, false); CRVGuiInterface& i = crvMock.get(); CanRawView canRawView{ CanRawViewCtx(&i) }; // Verify(Method(crvMock, setSorting).Using(0, Qt::AscendingOrder)); // Verify(Method(crvMock, getClickedColumn).Using(0)); // Verify(Method(crvMock, getClickedColumn).Using(0)); QCanBusFrame frame; frame.setPayload({ "123" }); REQUIRE_NOTHROW(canRawView.startSimulation()); REQUIRE_NOTHROW(canRawView.frameReceived(frame)); REQUIRE_NOTHROW(canRawView.frameSent(true, frame)); REQUIRE_NOTHROW(canRawView.frameSent(false, frame)); frame.setExtendedFrameFormat(true); REQUIRE_NOTHROW(canRawView.frameReceived(frame)); REQUIRE_NOTHROW(canRawView.frameSent(true, frame)); REQUIRE_NOTHROW(canRawView.frameSent(false, frame)); REQUIRE_NOTHROW(canRawView.stopSimulation()); REQUIRE_NOTHROW(canRawView.frameReceived(frame)); } TEST_CASE("setConfig using QObject", "[canrawview]") { CanRawView crv; QWidget config; config.setProperty("name", "CAN1"); config.setProperty("fake", "unsupported"); crv.setConfig(config); auto qConfig = crv.getQConfig(); REQUIRE(qConfig->property("name").toString() == "CAN1"); REQUIRE(qConfig->property("fake").isValid() == false); } TEST_CASE("Restore config paths", "[canrawview]") { CanRawView canRawView; QJsonObject json; QJsonArray columnArray; QJsonObject columnItem; // No viewColumns canRawView.setConfig(json); // ViewColumn is not an array json["viewColumns"] = ""; canRawView.setConfig(json); // Array size != 5 columnItem["dummy"] = 123; columnArray.append(columnItem); json["viewColumns"] = columnArray; canRawView.setConfig(json); // Array item is not an obj columnArray = QJsonArray(); QJsonValue val; columnArray.append(val); columnArray.append(val); columnArray.append(val); columnArray.append(val); columnArray.append(val); json["viewColumns"] = columnArray; canRawView.setConfig(json); // name does not exist columnArray = QJsonArray(); columnItem = QJsonObject(); columnItem["dummy"] = 123; columnItem["dummy2"] = 234; columnArray.append(columnItem); columnArray.append(columnItem); columnArray.append(columnItem); columnArray.append(columnItem); columnArray.append(columnItem); json["viewColumns"] = columnArray; canRawView.setConfig(json); // name is not a string columnArray = QJsonArray(); columnItem = QJsonObject(); columnItem["name"] = 123; columnItem["dummy2"] = 234; columnArray.append(columnItem); columnArray.append(columnItem); columnArray.append(columnItem); columnArray.append(columnItem); columnArray.append(columnItem); json["viewColumns"] = columnArray; canRawView.setConfig(json); // vIdx does not exist columnArray = QJsonArray(); columnItem = QJsonObject(); columnItem["name"] = "time"; columnItem["dummy2"] = 234; columnArray.append(columnItem); columnArray.append(columnItem); columnArray.append(columnItem); columnArray.append(columnItem); columnArray.append(columnItem); json["viewColumns"] = columnArray; canRawView.setConfig(json); // vIdx is not number columnArray = QJsonArray(); columnItem = QJsonObject(); columnItem["name"] = "time"; columnItem["vIdx"] = "dsds"; columnArray.append(columnItem); columnArray.append(columnItem); columnArray.append(columnItem); columnArray.append(columnItem); columnArray.append(columnItem); json["viewColumns"] = columnArray; canRawView.setConfig(json); // Column not found columnArray = QJsonArray(); columnItem = QJsonObject(); columnItem["name"] = "Blah"; columnItem["vIdx"] = 1; columnArray.append(columnItem); columnArray.append(columnItem); columnArray.append(columnItem); columnArray.append(columnItem); columnArray.append(columnItem); json["viewColumns"] = columnArray; canRawView.setConfig(json); // No scrolling item columnArray = QJsonArray(); columnItem = QJsonObject(); columnItem["name"] = "time"; columnItem["vIdx"] = 2; columnArray.append(columnItem); columnItem["name"] = "id"; columnItem["vIdx"] = 3; columnArray.append(columnItem); columnItem["name"] = "dir"; columnItem["vIdx"] = 4; columnArray.append(columnItem); columnItem["name"] = "dlc"; columnItem["vIdx"] = 5; columnArray.append(columnItem); columnItem["name"] = "data"; columnItem["vIdx"] = 6; columnArray.append(columnItem); json["viewColumns"] = columnArray; canRawView.setConfig(json); } TEST_CASE("Misc", "[canrawview]") { CanRawView canRawView; REQUIRE(canRawView.mainWidgetDocked() == true); REQUIRE(canRawView.mainWidget() != nullptr); } int main(int argc, char* argv[]) { bool haveDebug = std::getenv("CDS_DEBUG") != nullptr; kDefaultLogger = spdlog::stdout_color_mt("cds"); if (haveDebug) { kDefaultLogger->set_level(spdlog::level::debug); } cds_debug("Starting canrawview unit tests"); QApplication a(argc, argv); return Catch::Session().run(argc, argv); } TEST_CASE("Dock/Undock", "[canrawview]") { CRVGuiInterface::dockUndock_t dockUndock; Mock<CRVGuiInterface> crvMock; Fake(Method(crvMock, setClearCbk)); Fake(Method(crvMock, setSectionClikedCbk)); Fake(Method(crvMock, setFilterCbk)); When(Method(crvMock, setDockUndockCbk)).Do([&](auto&& fn) { dockUndock = fn; }); Fake(Method(crvMock, mainWidget)); Fake(Method(crvMock, setModel)); Fake(Method(crvMock, initTableView)); CanRawView canRawView{ CanRawViewCtx(&crvMock.get()) }; QSignalSpy dockSpy(&canRawView, &CanRawView::mainWidgetDockToggled); REQUIRE(canRawView.mainWidgetDocked() == true); dockUndock(); REQUIRE(dockSpy.count() == 1); REQUIRE(canRawView.mainWidgetDocked() == false); dockUndock(); REQUIRE(dockSpy.count() == 2); REQUIRE(canRawView.mainWidgetDocked() == true); } TEST_CASE("Section clicked", "[canrawview]") { CRVGuiInterface::sectionClicked_t sectionClicked; QAbstractItemModel* model = nullptr; Mock<CRVGuiInterface> crvMock; Fake(Method(crvMock, setClearCbk)); When(Method(crvMock, setSectionClikedCbk)).AlwaysDo([&](auto&& fn) { sectionClicked = fn; }); Fake(Method(crvMock, setFilterCbk)); Fake(Method(crvMock, setDockUndockCbk)); Fake(Method(crvMock, mainWidget)); When(Method(crvMock, setModel)).AlwaysDo([&](auto&& m) { model = m; }); When(Method(crvMock, setSorting)).AlwaysDo([&](int sortNdx, Qt::SortOrder order) { REQUIRE(model != nullptr); model->sort(sortNdx, order); }); Fake(Method(crvMock, initTableView)); When(Method(crvMock, getSortOrder)) .Return(Qt::AscendingOrder, Qt::DescendingOrder, Qt::AscendingOrder, Qt::AscendingOrder, Qt::AscendingOrder, Qt::AscendingOrder, Qt::AscendingOrder); Fake(Method(crvMock, isViewFrozen)); Fake(Method(crvMock, scrollToBottom)); CanRawView canRawView{ CanRawViewCtx(&crvMock.get()) }; QCanBusFrame frame; frame.setFrameId(11); frame.setPayload({ "123" }); REQUIRE_NOTHROW(canRawView.startSimulation()); REQUIRE_NOTHROW(canRawView.frameReceived(frame)); REQUIRE_NOTHROW(canRawView.frameReceived(frame)); frame.setFrameId(12); frame.setPayload({ "1234" }); REQUIRE_NOTHROW(canRawView.frameReceived(frame)); frame.setFrameId(123); frame.setPayload({ "12345" }); REQUIRE_NOTHROW(canRawView.frameReceived(frame)); frame.setFrameId(1234); frame.setPayload({ "" }); frame.setFrameType(QCanBusFrame::RemoteRequestFrame); sectionClicked(1); sectionClicked(1); sectionClicked(1); Verify(Method(crvMock, setSorting).Using(1, Qt::AscendingOrder), Method(crvMock, setSorting).Using(1, Qt::DescendingOrder), Method(crvMock, setSorting).Using(0, Qt::AscendingOrder)) .Exactly(Once); sectionClicked(1); sectionClicked(2); sectionClicked(3); sectionClicked(4); Verify(Method(crvMock, setSorting).Using(1, Qt::AscendingOrder), Method(crvMock, setSorting).Using(2, Qt::AscendingOrder), Method(crvMock, setSorting).Using(3, Qt::AscendingOrder), Method(crvMock, setSorting).Using(4, Qt::AscendingOrder)) .Exactly(Once); } TEST_CASE("Filter callback", "[canrawview]") { CRVGuiInterface::filter_t filter; QAbstractItemModel* model = nullptr; Mock<CRVGuiInterface> crvMock; Fake(Method(crvMock, setClearCbk)); When(Method(crvMock, setFilterCbk)).Do([&](auto&& fn) { filter = fn; }); Fake(Method(crvMock, setSectionClikedCbk)); Fake(Method(crvMock, setDockUndockCbk)); Fake(Method(crvMock, mainWidget)); When(Method(crvMock, setModel)).AlwaysDo([&](auto&& m) { model = m; }); Fake(Method(crvMock, setSorting)); Fake(Method(crvMock, initTableView)); When(Method(crvMock, getSortOrder)).Return(Qt::AscendingOrder, Qt::DescendingOrder, Qt::AscendingOrder); Fake(Method(crvMock, isViewFrozen)); Fake(Method(crvMock, scrollToBottom)); CanRawView canRawView{ CanRawViewCtx(&crvMock.get()) }; filter(true); REQUIRE_NOTHROW(canRawView.startSimulation()); REQUIRE(model != nullptr); model->sort(0, Qt::AscendingOrder); QCanBusFrame frame; frame.setFrameId(11); frame.setPayload({ "123" }); REQUIRE_NOTHROW(canRawView.frameReceived(frame)); REQUIRE_NOTHROW(canRawView.frameReceived(frame)); REQUIRE_NOTHROW(canRawView.frameSent(true, frame)); REQUIRE_NOTHROW(canRawView.frameSent(true, frame)); frame.setFrameId(12); frame.setPayload({ "1234" }); REQUIRE_NOTHROW(canRawView.frameReceived(frame)); REQUIRE_NOTHROW(canRawView.frameSent(true, frame)); frame.setFrameId(123); frame.setPayload({ "12345" }); REQUIRE_NOTHROW(canRawView.frameReceived(frame)); REQUIRE_NOTHROW(canRawView.frameSent(true, frame)); frame.setFrameId(1234); frame.setPayload({ "" }); frame.setFrameType(QCanBusFrame::RemoteRequestFrame); REQUIRE_NOTHROW(canRawView.frameReceived(frame)); REQUIRE_NOTHROW(canRawView.frameSent(true, frame)); filter(false); } TEST_CASE("Stress test", "[canrawview]") { CRVGuiInterface::filter_t filter; Mock<CRVGuiInterface> crvMock; Fake(Method(crvMock, setClearCbk)); When(Method(crvMock, setFilterCbk)).Do([&](auto&& fn) { filter = fn; }); Fake(Method(crvMock, setSectionClikedCbk)); Fake(Method(crvMock, setDockUndockCbk)); Fake(Method(crvMock, mainWidget)); Fake(Method(crvMock, setModel)); Fake(Method(crvMock, setSorting)); Fake(Method(crvMock, initTableView)); When(Method(crvMock, getSortOrder)).Return(Qt::AscendingOrder, Qt::DescendingOrder, Qt::AscendingOrder); Fake(Method(crvMock, isViewFrozen)); Fake(Method(crvMock, scrollToBottom)); CanRawView canRawView{ CanRawViewCtx(&crvMock.get()) }; filter(true); REQUIRE_NOTHROW(canRawView.startSimulation()); QCanBusFrame frame; frame.setPayload({ "123" }); for (int i = 0; i < 0x7ff; ++i) { frame.setFrameId(i); REQUIRE_NOTHROW(canRawView.frameReceived(frame)); REQUIRE_NOTHROW(canRawView.frameSent(true, frame)); } filter(false); } <commit_msg>Attempt to fix code coverage<commit_after>#define CATCH_CONFIG_RUNNER #include <QCanBusFrame> #include <QJsonArray> #include <QSignalSpy> #include <QStandardItemModel> #include <QTableView> #include <Qt> #include <QtWidgets/QApplication> #include <catch.hpp> #include <context.h> #include <fakeit.hpp> #include <canrawview.h> #include <gui/crvguiinterface.h> #include <log.h> #include <memory> #include <iostream> std::shared_ptr<spdlog::logger> kDefaultLogger; using namespace fakeit; #include <QStandardItemModel> class CanRawViewPrivate; TEST_CASE("Initialize table", "[canrawview]") { Mock<CRVGuiInterface> crvMock; Fake(Method(crvMock, setClearCbk)); Fake(Method(crvMock, setDockUndockCbk)); Fake(Method(crvMock, setSectionClikedCbk)); Fake(Method(crvMock, setFilterCbk)); Fake(Method(crvMock, setModel)); Fake(Method(crvMock, setSorting)); Fake(Method(crvMock, initTableView)); Fake(Method(crvMock, scrollToBottom)); When(Method(crvMock, mainWidget)).Return(NULL); When(Method(crvMock, isViewFrozen)).Return(false).Return(true).Return(true).Return(false).Return(true).Return(true); When(Method(crvMock, getSortOrder)).Return(Qt::AscendingOrder); When(Method(crvMock, getClickedColumn)).Return("rowID", "time", "id", "dir", "len", "data"); When(Method(crvMock, isColumnHidden)).Return(true, false, false, false, false, false); CRVGuiInterface& i = crvMock.get(); CanRawView canRawView{ CanRawViewCtx(&i) }; // Verify(Method(crvMock, setSorting).Using(0, Qt::AscendingOrder)); // Verify(Method(crvMock, getClickedColumn).Using(0)); // Verify(Method(crvMock, getClickedColumn).Using(0)); QCanBusFrame frame; frame.setPayload({ "123" }); REQUIRE_NOTHROW(canRawView.startSimulation()); REQUIRE_NOTHROW(canRawView.frameReceived(frame)); REQUIRE_NOTHROW(canRawView.frameSent(true, frame)); REQUIRE_NOTHROW(canRawView.frameSent(false, frame)); frame.setExtendedFrameFormat(true); REQUIRE_NOTHROW(canRawView.frameReceived(frame)); REQUIRE_NOTHROW(canRawView.frameSent(true, frame)); REQUIRE_NOTHROW(canRawView.frameSent(false, frame)); REQUIRE_NOTHROW(canRawView.stopSimulation()); REQUIRE_NOTHROW(canRawView.frameReceived(frame)); } TEST_CASE("setConfig using QObject", "[canrawview]") { CanRawView crv; QWidget config; config.setProperty("name", "CAN1"); config.setProperty("fake", "unsupported"); crv.setConfig(config); auto qConfig = crv.getQConfig(); REQUIRE(qConfig->property("name").toString() == "CAN1"); REQUIRE(qConfig->property("fake").isValid() == false); } TEST_CASE("Restore config paths", "[canrawview]") { CanRawView canRawView; QJsonObject json; QJsonArray columnArray; QJsonObject columnItem; // No viewColumns canRawView.setConfig(json); // ViewColumn is not an array json["viewColumns"] = ""; canRawView.setConfig(json); // Array size != 5 columnItem["dummy"] = 123; columnArray.append(columnItem); json["viewColumns"] = columnArray; canRawView.setConfig(json); // Array item is not an obj columnArray = QJsonArray(); QJsonValue val; columnArray.append(val); columnArray.append(val); columnArray.append(val); columnArray.append(val); columnArray.append(val); json["viewColumns"] = columnArray; canRawView.setConfig(json); // name does not exist columnArray = QJsonArray(); columnItem = QJsonObject(); columnItem["dummy"] = 123; columnItem["dummy2"] = 234; columnArray.append(columnItem); columnArray.append(columnItem); columnArray.append(columnItem); columnArray.append(columnItem); columnArray.append(columnItem); json["viewColumns"] = columnArray; canRawView.setConfig(json); // name is not a string columnArray = QJsonArray(); columnItem = QJsonObject(); columnItem["name"] = 123; columnItem["dummy2"] = 234; columnArray.append(columnItem); columnArray.append(columnItem); columnArray.append(columnItem); columnArray.append(columnItem); columnArray.append(columnItem); json["viewColumns"] = columnArray; canRawView.setConfig(json); // vIdx does not exist columnArray = QJsonArray(); columnItem = QJsonObject(); columnItem["name"] = "time"; columnItem["dummy2"] = 234; columnArray.append(columnItem); columnArray.append(columnItem); columnArray.append(columnItem); columnArray.append(columnItem); columnArray.append(columnItem); json["viewColumns"] = columnArray; canRawView.setConfig(json); // vIdx is not number columnArray = QJsonArray(); columnItem = QJsonObject(); columnItem["name"] = "time"; columnItem["vIdx"] = "dsds"; columnArray.append(columnItem); columnArray.append(columnItem); columnArray.append(columnItem); columnArray.append(columnItem); columnArray.append(columnItem); json["viewColumns"] = columnArray; canRawView.setConfig(json); // Column not found columnArray = QJsonArray(); columnItem = QJsonObject(); columnItem["name"] = "Blah"; columnItem["vIdx"] = 1; columnArray.append(columnItem); columnArray.append(columnItem); columnArray.append(columnItem); columnArray.append(columnItem); columnArray.append(columnItem); json["viewColumns"] = columnArray; canRawView.setConfig(json); // No scrolling item columnArray = QJsonArray(); columnItem = QJsonObject(); columnItem["name"] = "time"; columnItem["vIdx"] = 2; columnArray.append(columnItem); columnItem["name"] = "id"; columnItem["vIdx"] = 3; columnArray.append(columnItem); columnItem["name"] = "dir"; columnItem["vIdx"] = 4; columnArray.append(columnItem); columnItem["name"] = "len"; columnItem["vIdx"] = 5; columnArray.append(columnItem); columnItem["name"] = "data"; columnItem["vIdx"] = 6; columnArray.append(columnItem); json["viewColumns"] = columnArray; canRawView.setConfig(json); } TEST_CASE("Misc", "[canrawview]") { CanRawView canRawView; REQUIRE(canRawView.mainWidgetDocked() == true); REQUIRE(canRawView.mainWidget() != nullptr); } int main(int argc, char* argv[]) { bool haveDebug = std::getenv("CDS_DEBUG") != nullptr; kDefaultLogger = spdlog::stdout_color_mt("cds"); if (haveDebug) { kDefaultLogger->set_level(spdlog::level::debug); } cds_debug("Starting canrawview unit tests"); QApplication a(argc, argv); return Catch::Session().run(argc, argv); } TEST_CASE("Dock/Undock", "[canrawview]") { CRVGuiInterface::dockUndock_t dockUndock; Mock<CRVGuiInterface> crvMock; Fake(Method(crvMock, setClearCbk)); Fake(Method(crvMock, setSectionClikedCbk)); Fake(Method(crvMock, setFilterCbk)); When(Method(crvMock, setDockUndockCbk)).Do([&](auto&& fn) { dockUndock = fn; }); Fake(Method(crvMock, mainWidget)); Fake(Method(crvMock, setModel)); Fake(Method(crvMock, initTableView)); CanRawView canRawView{ CanRawViewCtx(&crvMock.get()) }; QSignalSpy dockSpy(&canRawView, &CanRawView::mainWidgetDockToggled); REQUIRE(canRawView.mainWidgetDocked() == true); dockUndock(); REQUIRE(dockSpy.count() == 1); REQUIRE(canRawView.mainWidgetDocked() == false); dockUndock(); REQUIRE(dockSpy.count() == 2); REQUIRE(canRawView.mainWidgetDocked() == true); } TEST_CASE("Section clicked", "[canrawview]") { CRVGuiInterface::sectionClicked_t sectionClicked; QAbstractItemModel* model = nullptr; Mock<CRVGuiInterface> crvMock; Fake(Method(crvMock, setClearCbk)); When(Method(crvMock, setSectionClikedCbk)).AlwaysDo([&](auto&& fn) { sectionClicked = fn; }); Fake(Method(crvMock, setFilterCbk)); Fake(Method(crvMock, setDockUndockCbk)); Fake(Method(crvMock, mainWidget)); When(Method(crvMock, setModel)).AlwaysDo([&](auto&& m) { model = m; }); When(Method(crvMock, setSorting)).AlwaysDo([&](int sortNdx, Qt::SortOrder order) { REQUIRE(model != nullptr); model->sort(sortNdx, order); }); Fake(Method(crvMock, initTableView)); When(Method(crvMock, getSortOrder)) .Return(Qt::AscendingOrder, Qt::DescendingOrder, Qt::AscendingOrder, Qt::AscendingOrder, Qt::AscendingOrder, Qt::AscendingOrder, Qt::AscendingOrder); Fake(Method(crvMock, isViewFrozen)); Fake(Method(crvMock, scrollToBottom)); CanRawView canRawView{ CanRawViewCtx(&crvMock.get()) }; QCanBusFrame frame; frame.setFrameId(11); frame.setPayload({ "123" }); REQUIRE_NOTHROW(canRawView.startSimulation()); REQUIRE_NOTHROW(canRawView.frameReceived(frame)); REQUIRE_NOTHROW(canRawView.frameReceived(frame)); frame.setFrameId(12); frame.setPayload({ "1234" }); REQUIRE_NOTHROW(canRawView.frameReceived(frame)); frame.setFrameId(123); frame.setPayload({ "12345" }); REQUIRE_NOTHROW(canRawView.frameReceived(frame)); frame.setFrameId(1234); frame.setPayload({ "" }); frame.setFrameType(QCanBusFrame::RemoteRequestFrame); sectionClicked(1); sectionClicked(1); sectionClicked(1); Verify(Method(crvMock, setSorting).Using(1, Qt::AscendingOrder), Method(crvMock, setSorting).Using(1, Qt::DescendingOrder), Method(crvMock, setSorting).Using(0, Qt::AscendingOrder)) .Exactly(Once); sectionClicked(1); sectionClicked(2); sectionClicked(3); sectionClicked(4); Verify(Method(crvMock, setSorting).Using(1, Qt::AscendingOrder), Method(crvMock, setSorting).Using(2, Qt::AscendingOrder), Method(crvMock, setSorting).Using(3, Qt::AscendingOrder), Method(crvMock, setSorting).Using(4, Qt::AscendingOrder)) .Exactly(Once); } TEST_CASE("Filter callback", "[canrawview]") { CRVGuiInterface::filter_t filter; QAbstractItemModel* model = nullptr; Mock<CRVGuiInterface> crvMock; Fake(Method(crvMock, setClearCbk)); When(Method(crvMock, setFilterCbk)).Do([&](auto&& fn) { filter = fn; }); Fake(Method(crvMock, setSectionClikedCbk)); Fake(Method(crvMock, setDockUndockCbk)); Fake(Method(crvMock, mainWidget)); When(Method(crvMock, setModel)).AlwaysDo([&](auto&& m) { model = m; }); Fake(Method(crvMock, setSorting)); Fake(Method(crvMock, initTableView)); When(Method(crvMock, getSortOrder)).Return(Qt::AscendingOrder, Qt::DescendingOrder, Qt::AscendingOrder); Fake(Method(crvMock, isViewFrozen)); Fake(Method(crvMock, scrollToBottom)); CanRawView canRawView{ CanRawViewCtx(&crvMock.get()) }; filter(true); REQUIRE_NOTHROW(canRawView.startSimulation()); REQUIRE(model != nullptr); model->sort(0, Qt::AscendingOrder); QCanBusFrame frame; frame.setFrameId(11); frame.setPayload({ "123" }); REQUIRE_NOTHROW(canRawView.frameReceived(frame)); REQUIRE_NOTHROW(canRawView.frameReceived(frame)); REQUIRE_NOTHROW(canRawView.frameSent(true, frame)); REQUIRE_NOTHROW(canRawView.frameSent(true, frame)); frame.setFrameId(12); frame.setPayload({ "1234" }); REQUIRE_NOTHROW(canRawView.frameReceived(frame)); REQUIRE_NOTHROW(canRawView.frameSent(true, frame)); frame.setFrameId(123); frame.setPayload({ "12345" }); REQUIRE_NOTHROW(canRawView.frameReceived(frame)); REQUIRE_NOTHROW(canRawView.frameSent(true, frame)); frame.setFrameId(1234); frame.setPayload({ "" }); frame.setFrameType(QCanBusFrame::RemoteRequestFrame); REQUIRE_NOTHROW(canRawView.frameReceived(frame)); REQUIRE_NOTHROW(canRawView.frameSent(true, frame)); filter(false); } TEST_CASE("Stress test", "[canrawview]") { CRVGuiInterface::filter_t filter; Mock<CRVGuiInterface> crvMock; Fake(Method(crvMock, setClearCbk)); When(Method(crvMock, setFilterCbk)).Do([&](auto&& fn) { filter = fn; }); Fake(Method(crvMock, setSectionClikedCbk)); Fake(Method(crvMock, setDockUndockCbk)); Fake(Method(crvMock, mainWidget)); Fake(Method(crvMock, setModel)); Fake(Method(crvMock, setSorting)); Fake(Method(crvMock, initTableView)); When(Method(crvMock, getSortOrder)).Return(Qt::AscendingOrder, Qt::DescendingOrder, Qt::AscendingOrder); Fake(Method(crvMock, isViewFrozen)); Fake(Method(crvMock, scrollToBottom)); CanRawView canRawView{ CanRawViewCtx(&crvMock.get()) }; filter(true); REQUIRE_NOTHROW(canRawView.startSimulation()); QCanBusFrame frame; frame.setPayload({ "123" }); for (int i = 0; i < 0x7ff; ++i) { frame.setFrameId(i); REQUIRE_NOTHROW(canRawView.frameReceived(frame)); REQUIRE_NOTHROW(canRawView.frameSent(true, frame)); } filter(false); } <|endoftext|>
<commit_before>#include "qmljscompletioncontextfinder.h" #include <QtCore/QDebug> #include <QtGui/QTextDocument> using namespace QmlJS; /* Saves and restores the state of the global linizer. This enables backtracking. Identical to the defines in qmljslineinfo.cpp */ #define YY_SAVE() LinizerState savedState = yyLinizerState #define YY_RESTORE() yyLinizerState = savedState CompletionContextFinder::CompletionContextFinder(const QTextCursor &cursor) : m_cursor(cursor) , m_colonCount(-1) , m_behaviorBinding(false) { QTextBlock lastBlock = cursor.block(); if (lastBlock.next().isValid()) lastBlock = lastBlock.next(); initialize(cursor.document()->begin(), lastBlock); m_startTokenIndex = yyLinizerState.tokens.size() - 1; for (; m_startTokenIndex >= 0; --m_startTokenIndex) { const Token &token = yyLinizerState.tokens.at(m_startTokenIndex); if (token.end() <= cursor.positionInBlock()) break; } if (m_startTokenIndex == yyLinizerState.tokens.size() - 1 && yyLinizerState.insertedSemicolon) --m_startTokenIndex; getQmlObjectTypeName(m_startTokenIndex); checkBinding(); } void CompletionContextFinder::getQmlObjectTypeName(int startTokenIndex) { YY_SAVE(); int tokenIndex = findOpeningBrace(startTokenIndex); if (tokenIndex != -1) { --tokenIndex; // can be one of // A.B on c.d // A.B bool identifierExpected = true; int i = tokenIndex; forever { if (i < 0) { if (!readLine()) break; else i = yyLinizerState.tokens.size() - 1; } const Token &token = yyLinizerState.tokens.at(i); if (!identifierExpected && token.kind == Token::Dot) { identifierExpected = true; } else if (token.kind == Token::Identifier) { const QString idText = yyLine->mid(token.begin(), token.length); if (identifierExpected) { m_qmlObjectTypeName.prepend(idText); identifierExpected = false; } else if (idText == QLatin1String("on")) { m_qmlObjectTypeName.clear(); identifierExpected = true; } else { break; } } else { break; } --i; } } YY_RESTORE(); } void CompletionContextFinder::checkBinding() { YY_SAVE(); //qDebug() << "Start line:" << *yyLine << m_startTokenIndex; int i = m_startTokenIndex; int colonCount = 0; bool delimiterFound = false; bool firstToken = true; bool identifierExpected = false; bool dotExpected = false; while (!delimiterFound) { if (i < 0) { if (!readLine()) break; else i = yyLinizerState.tokens.size() - 1; //qDebug() << "New Line" << *yyLine; } const Token &token = yyLinizerState.tokens.at(i); //qDebug() << "Token:" << yyLine->mid(token.begin(), token.length); switch (token.kind) { case Token::RightBrace: case Token::LeftBrace: case Token::Semicolon: delimiterFound = true; break; case Token::Colon: ++colonCount; identifierExpected = true; dotExpected = false; m_bindingPropertyName.clear(); break; case Token::Identifier: { QStringRef tokenString = yyLine->midRef(token.begin(), token.length); if (firstToken && tokenString == QLatin1String("on")) { m_behaviorBinding = true; } else if (identifierExpected) { m_bindingPropertyName.prepend(tokenString.toString()); identifierExpected = false; dotExpected = true; } else { dotExpected = false; } } break; case Token::Dot: if (dotExpected) { dotExpected = false; identifierExpected = true; } else { identifierExpected = false; } break; default: dotExpected = false; identifierExpected = false; break; } --i; firstToken = false; } YY_RESTORE(); if (delimiterFound) m_colonCount = colonCount; } QStringList CompletionContextFinder::qmlObjectTypeName() const { return m_qmlObjectTypeName; } bool CompletionContextFinder::isInQmlContext() const { return !qmlObjectTypeName().isEmpty(); } bool CompletionContextFinder::isInLhsOfBinding() const { return isInQmlContext() && m_colonCount == 0; } bool CompletionContextFinder::isInRhsOfBinding() const { return isInQmlContext() && m_colonCount >= 1; } QStringList CompletionContextFinder::bindingPropertyName() const { return m_bindingPropertyName; } /*! \return true if the cursor after "Type on" in the left hand side of a binding, false otherwise. */ bool CompletionContextFinder::isAfterOnInLhsOfBinding() const { return isInLhsOfBinding() && m_behaviorBinding; } int CompletionContextFinder::findOpeningBrace(int startTokenIndex) { YY_SAVE(); if (startTokenIndex == -1) readLine(); Token::Kind nestedClosing = Token::EndOfFile; int nestingCount = 0; for (int i = 0; i < BigRoof; ++i) { if (i != 0 || startTokenIndex == -1) startTokenIndex = yyLinizerState.tokens.size() - 1; for (int t = startTokenIndex; t >= 0; --t) { const Token &token = yyLinizerState.tokens.at(t); switch (token.kind) { case Token::LeftBrace: if (nestingCount > 0) { if (nestedClosing == Token::RightBrace) --nestingCount; } else { return t; } break; case Token::LeftParenthesis: if (nestingCount > 0) { if (nestedClosing == Token::RightParenthesis) --nestingCount; } else { YY_RESTORE(); return -1; } break; case Token::LeftBracket: if (nestingCount > 0) { if (nestedClosing == Token::RightBracket) --nestingCount; } else { YY_RESTORE(); return -1; } break; case Token::RightBrace: case Token::RightParenthesis: case Token::RightBracket: if (nestingCount == 0) { nestedClosing = token.kind; nestingCount = 1; } else if (nestedClosing == token.kind) { ++nestingCount; } break; default: break; } } if (! readLine()) break; } YY_RESTORE(); return -1; } <commit_msg>QmlJS: Fix completion context finder if cursor is on empty line.<commit_after>#include "qmljscompletioncontextfinder.h" #include <QtCore/QDebug> #include <QtGui/QTextDocument> using namespace QmlJS; /* Saves and restores the state of the global linizer. This enables backtracking. Identical to the defines in qmljslineinfo.cpp */ #define YY_SAVE() LinizerState savedState = yyLinizerState #define YY_RESTORE() yyLinizerState = savedState CompletionContextFinder::CompletionContextFinder(const QTextCursor &cursor) : m_cursor(cursor) , m_colonCount(-1) , m_behaviorBinding(false) { QTextBlock lastBlock = cursor.block(); if (lastBlock.next().isValid()) lastBlock = lastBlock.next(); initialize(cursor.document()->begin(), lastBlock); m_startTokenIndex = yyLinizerState.tokens.size() - 1; // Initialize calls readLine - which skips empty lines. We should only adjust // the start token index if the linizer still is in the same block as the cursor. if (yyLinizerState.iter == cursor.block()) { for (; m_startTokenIndex >= 0; --m_startTokenIndex) { const Token &token = yyLinizerState.tokens.at(m_startTokenIndex); if (token.end() <= cursor.positionInBlock()) break; } if (m_startTokenIndex == yyLinizerState.tokens.size() - 1 && yyLinizerState.insertedSemicolon) --m_startTokenIndex; } getQmlObjectTypeName(m_startTokenIndex); checkBinding(); } void CompletionContextFinder::getQmlObjectTypeName(int startTokenIndex) { YY_SAVE(); int tokenIndex = findOpeningBrace(startTokenIndex); if (tokenIndex != -1) { --tokenIndex; // can be one of // A.B on c.d // A.B bool identifierExpected = true; int i = tokenIndex; forever { if (i < 0) { if (!readLine()) break; else i = yyLinizerState.tokens.size() - 1; } const Token &token = yyLinizerState.tokens.at(i); if (!identifierExpected && token.kind == Token::Dot) { identifierExpected = true; } else if (token.kind == Token::Identifier) { const QString idText = yyLine->mid(token.begin(), token.length); if (identifierExpected) { m_qmlObjectTypeName.prepend(idText); identifierExpected = false; } else if (idText == QLatin1String("on")) { m_qmlObjectTypeName.clear(); identifierExpected = true; } else { break; } } else { break; } --i; } } YY_RESTORE(); } void CompletionContextFinder::checkBinding() { YY_SAVE(); //qDebug() << "Start line:" << *yyLine << m_startTokenIndex; int i = m_startTokenIndex; int colonCount = 0; bool delimiterFound = false; bool firstToken = true; bool identifierExpected = false; bool dotExpected = false; while (!delimiterFound) { if (i < 0) { if (!readLine()) break; else i = yyLinizerState.tokens.size() - 1; //qDebug() << "New Line" << *yyLine; } const Token &token = yyLinizerState.tokens.at(i); //qDebug() << "Token:" << yyLine->mid(token.begin(), token.length); switch (token.kind) { case Token::RightBrace: case Token::LeftBrace: case Token::Semicolon: delimiterFound = true; break; case Token::Colon: ++colonCount; identifierExpected = true; dotExpected = false; m_bindingPropertyName.clear(); break; case Token::Identifier: { QStringRef tokenString = yyLine->midRef(token.begin(), token.length); if (firstToken && tokenString == QLatin1String("on")) { m_behaviorBinding = true; } else if (identifierExpected) { m_bindingPropertyName.prepend(tokenString.toString()); identifierExpected = false; dotExpected = true; } else { dotExpected = false; } } break; case Token::Dot: if (dotExpected) { dotExpected = false; identifierExpected = true; } else { identifierExpected = false; } break; default: dotExpected = false; identifierExpected = false; break; } --i; firstToken = false; } YY_RESTORE(); if (delimiterFound) m_colonCount = colonCount; } QStringList CompletionContextFinder::qmlObjectTypeName() const { return m_qmlObjectTypeName; } bool CompletionContextFinder::isInQmlContext() const { return !qmlObjectTypeName().isEmpty(); } bool CompletionContextFinder::isInLhsOfBinding() const { return isInQmlContext() && m_colonCount == 0; } bool CompletionContextFinder::isInRhsOfBinding() const { return isInQmlContext() && m_colonCount >= 1; } QStringList CompletionContextFinder::bindingPropertyName() const { return m_bindingPropertyName; } /*! \return true if the cursor after "Type on" in the left hand side of a binding, false otherwise. */ bool CompletionContextFinder::isAfterOnInLhsOfBinding() const { return isInLhsOfBinding() && m_behaviorBinding; } int CompletionContextFinder::findOpeningBrace(int startTokenIndex) { YY_SAVE(); if (startTokenIndex == -1) readLine(); Token::Kind nestedClosing = Token::EndOfFile; int nestingCount = 0; for (int i = 0; i < BigRoof; ++i) { if (i != 0 || startTokenIndex == -1) startTokenIndex = yyLinizerState.tokens.size() - 1; for (int t = startTokenIndex; t >= 0; --t) { const Token &token = yyLinizerState.tokens.at(t); switch (token.kind) { case Token::LeftBrace: if (nestingCount > 0) { if (nestedClosing == Token::RightBrace) --nestingCount; } else { return t; } break; case Token::LeftParenthesis: if (nestingCount > 0) { if (nestedClosing == Token::RightParenthesis) --nestingCount; } else { YY_RESTORE(); return -1; } break; case Token::LeftBracket: if (nestingCount > 0) { if (nestedClosing == Token::RightBracket) --nestingCount; } else { YY_RESTORE(); return -1; } break; case Token::RightBrace: case Token::RightParenthesis: case Token::RightBracket: if (nestingCount == 0) { nestedClosing = token.kind; nestingCount = 1; } else if (nestedClosing == token.kind) { ++nestingCount; } break; default: break; } } if (! readLine()) break; } YY_RESTORE(); return -1; } <|endoftext|>
<commit_before>/*********************************************************************** dummy.cpp - Exists solely to fix a problem with Visual Studio: it won't show the C/C++ project settings unless there is a *.cpp file in the project. Rather than rename all the *.cc files, I'm just adding this to the projects for now. ***********************************************************************/<commit_msg>No longer needed.<commit_after><|endoftext|>
<commit_before>#pragma once #include <iostream> #include "binary.hxx" #include "bitnode.hxx" namespace despairagus { namespace bitwisetrie { using std::cout; using std::ostream; template <typename A> class bitwisetrie final { template<typename B> using conref = const B &; using bitA = std::bitset<sizeof(A) << 3>; using byte = unsigned char; using bit = bool; constexpr static const size_t limit{sizeof(A) << 3}; static inline bitnode<A>* navigate(bitnode<A>* currNode, conref<A> data) { return bitwisetrie<A>::navigate(currNode, data, 0); } static inline bitnode<A>* navigate(bitnode<A>* currNode, conref<A> data, conref<size_t> idx) { binary<A> bitHolder{data}; return bitwisetrie<A>::navigate(currNode, bitHolder, idx); } static bitnode<A>* navigate(bitnode<A>* currNode, conref<binary<A>> bits, conref<size_t> idx) { if (idx < limit) { if (bits.getBit(idx)) { if (currNode->getOne() == nullptr) { currNode->setOne(new bitnode<A>); } return bitwisetrie<A>::navigate(currNode->getOne(), bits, idx + 1); } else { if (currNode->getZero() == nullptr) { currNode->setZero(new bitnode<A>); } return bitwisetrie<A>::navigate(currNode->getZero(), bits, idx + 1); } } return currNode; } public: explicit bitwisetrie(void) : root{new bitnode<A>} {} inline bool insertOnEmpty(conref<A> a) noexcept { bitnode<A>* leafNode = bitwisetrie<A>::navigate(root, a); if (leafNode->isEmpty()) { leafNode->setData(a); return true; } return false; } inline bool insertOnNotEmpty(conref<A> a) noexcept { bitnode<A>* leafNode = bitwisetrie<A>::navigate(root, a); if (leafNode->isNotEmpty()) { leafNode->setData(a); return true; } return false; } private: bitnode<A>* root; }; } }<commit_msg>add existence checker<commit_after>#pragma once #include <iostream> #include "binary.hxx" #include "bitnode.hxx" namespace despairagus { namespace bitwisetrie { using std::cout; using std::ostream; template <typename A> class bitwisetrie final { template<typename B> using conref = const B &; using bitA = std::bitset<sizeof(A) << 3>; using byte = unsigned char; using bit = bool; constexpr static const size_t limit{sizeof(A) << 3}; static inline bitnode<A>* navigate(bitnode<A>* currNode, conref<A> data) { return bitwisetrie<A>::navigate(currNode, data, 0); } static inline bitnode<A>* navigate(bitnode<A>* currNode, conref<A> data, conref<size_t> idx) { binary<A> bitHolder{data}; return bitwisetrie<A>::navigate(currNode, bitHolder, idx); } static bitnode<A>* navigate(bitnode<A>* currNode, conref<binary<A>> bits, conref<size_t> idx) { if (idx < limit) { if (bits.getBit(idx)) { if (currNode->getOne() == nullptr) { currNode->setOne(new bitnode<A>); } return bitwisetrie<A>::navigate(currNode->getOne(), bits, idx + 1); } else { if (currNode->getZero() == nullptr) { currNode->setZero(new bitnode<A>); } return bitwisetrie<A>::navigate(currNode->getZero(), bits, idx + 1); } } return currNode; } public: explicit bitwisetrie(void) : root{new bitnode<A>} {} inline bool insertOnEmpty(conref<A> a) noexcept { bitnode<A>* leafNode = bitwisetrie<A>::navigate(root, a); if (leafNode->isEmpty()) { leafNode->setData(a); return true; } return false; } inline bool insertOnNotEmpty(conref<A> a) noexcept { bitnode<A>* leafNode = bitwisetrie<A>::navigate(root, a); if (leafNode->isNotEmpty()) { leafNode->setData(a); return true; } return false; } inline bool contains(conref<A> a) noexcept { bitnode<A>* leafNode = bitwisetrie::navigate(root, a); return leafNode->isNotEmpty(); } inline bool notContains(conref<A> a) noexcept { bitnode<A>* leafNode = bitwisetrie::navigate(root, a); return leafNode->isEmpty(); } private: bitnode<A>* root; }; } }<|endoftext|>
<commit_before>#include "render_graph_builder.hpp" #include <minitrace.h> #include <rx/core/algorithm/max.h> #include <rx/core/algorithm/min.h> #include <rx/core/log.h> #include "nova_renderer/constants.hpp" namespace nova::renderer::shaderpack { RX_LOG("RenderGraphBuilder", logger); /*! * \brief Adds all the passes that `pass_name` depends on to the list of ordered passes * * This method performs a depth-first traversal of the pass tree. It shouldn't matter whether we do depth or * breadth first, but depth first feels cleaner * * \param pass_name The passes that were just added to the list of ordered passes * \param passes A map from pass name to pass. Useful for the explicit dependencies of a pass * \param ordered_passes The passes in submissions order... almost. When this function adds to ordered_passes the * list has a lot of duplicates. They're removed in a later step * \param resource_to_write_pass A map from resource name to list of passes that write to that resource. Useful for * resolving the implicit dependencies of a pass * \param depth The depth in the tree that we're at. If this number ever grows bigger than the total number of * passes, there's a circular dependency somewhere in the render graph. This is Bad and we hate it */ void add_dependent_passes(const rx::string& pass_name, const rx::map<rx::string, RenderPassCreateInfo>& passes, rx::vector<rx::string>& ordered_passes, const rx::map<rx::string, rx::vector<rx::string>>& resource_to_write_pass, uint32_t depth); bool Range::has_writer() const { return first_write_pass <= last_write_pass; } bool Range::has_reader() const { return first_read_pass <= last_read_pass; } bool Range::is_used() const { return has_writer() || has_reader(); } bool Range::can_alias() const { // If we read before we have completely written to a resource we need to preserve it, so no alias is possible. return !(has_reader() && has_writer() && first_read_pass <= first_write_pass); } unsigned Range::last_used_pass() const { unsigned last_pass = 0; if(has_writer()) { last_pass = rx::algorithm::max(last_pass, last_write_pass); } if(has_reader()) { last_pass = rx::algorithm::max(last_pass, last_read_pass); } return last_pass; } unsigned Range::first_used_pass() const { unsigned first_pass = ~0U; if(has_writer()) { first_pass = rx::algorithm::min(first_pass, first_write_pass); } if(has_reader()) { first_pass = rx::algorithm::min(first_pass, first_read_pass); } return first_pass; } bool Range::is_disjoint_with(const Range& other) const { if(!is_used() || !other.is_used()) { return false; } if(!can_alias() || !other.can_alias()) { return false; } const bool left = last_used_pass() < other.first_used_pass(); const bool right = other.last_used_pass() < first_used_pass(); return left || right; } ntl::Result<rx::vector<RenderPassCreateInfo>> order_passes(const rx::vector<RenderPassCreateInfo>& passes) { MTR_SCOPE("Renderpass", "order_passes"); logger(rx::log::level::k_verbose, "Executing Pass Scheduler"); rx::map<rx::string, RenderPassCreateInfo> render_passes_to_order; passes.each_fwd([&](const RenderPassCreateInfo& create_info) { render_passes_to_order.insert(create_info.name, create_info); }); rx::vector<rx::string> ordered_passes; ordered_passes.reserve(passes.size()); /* * Build some acceleration structures */ logger(rx::log::level::k_verbose, "Collecting passes that write to each resource..."); // Maps from resource name to pass that writes to that resource, then from resource name to pass that reads from // that resource auto resource_to_write_pass = rx::map<rx::string, rx::vector<rx::string>>{}; passes.each_fwd([&](const RenderPassCreateInfo& pass) { pass.texture_outputs.each_fwd( [&](const TextureAttachmentInfo& output) { resource_to_write_pass.find(output.name)->push_back(pass.name); }); pass.output_buffers.each_fwd( [&](const rx::string& buffer_output) { resource_to_write_pass.find(buffer_output)->push_back(pass.name); }); }); /* * Initial ordering of passes */ logger(rx::log::level::k_verbose, "First pass at ordering passes..."); // The passes, in simple dependency order if(resource_to_write_pass.find(BACKBUFFER_NAME) == nullptr) { logger(rx::log::level::k_error, "This render graph does not write to the backbuffer. Unable to load this shaderpack because it can't render anything"); return ntl::Result<rx::vector<RenderPassCreateInfo>>(ntl::NovaError("Failed to order passes because no backbuffer was found")); } const auto& backbuffer_writes = *resource_to_write_pass.find(BACKBUFFER_NAME); ordered_passes += backbuffer_writes; backbuffer_writes.each_fwd([&](const rx::string& pass_name) { add_dependent_passes(pass_name, render_passes_to_order, ordered_passes, resource_to_write_pass, 1); }); // We're going to loop through the original list of passes and remove them from the original list of passes // We want to keep the original passes around // This code taken from `RenderGraph::filter_passes` in the Granite engine // It loops through the ordered passes. When it sees the name of a new pass, it writes the pass to // ordered_passes and increments the write position. After all the passes are written, we remove all the // passes after the last one we wrote to, shrinking the list of ordered passes to only include the exact passes we want rx::vector<rx::string> unique_passes; ordered_passes.each_rev([&](const rx::string& pass_name) { if(unique_passes.find(pass_name) == rx::vector<rx::string>::k_npos) { unique_passes.push_back(pass_name); } }); ordered_passes = unique_passes; // Granite does some reordering to try and find a submission order that has the fewest pipeline barriers. Not // gonna worry about that now rx::vector<RenderPassCreateInfo> passes_in_submission_order; passes_in_submission_order.reserve(ordered_passes.size()); ordered_passes.each_fwd( [&](const rx::string& pass_name) { passes_in_submission_order.push_back(*render_passes_to_order.find(pass_name)); }); return ntl::Result(passes_in_submission_order); } void add_dependent_passes(const rx::string& pass_name, const rx::map<rx::string, RenderPassCreateInfo>& passes, rx::vector<rx::string>& ordered_passes, const rx::map<rx::string, rx::vector<rx::string>>& resource_to_write_pass, const uint32_t depth) { if(depth > passes.size()) { logger(rx::log::level::k_error, "Circular render graph detected! Please fix your render graph to not have circular dependencies"); } const auto& pass = *passes.find(pass_name); pass.texture_inputs.each_fwd([&](const rx::string& texture_name) { if(const auto write_passes = resource_to_write_pass.find(texture_name); write_passes == nullptr) { // TODO: Ignore the implicitly defined resources logger(rx::log::level::k_error, "Pass %s reads from resource %s, but nothing writes to it", pass_name, texture_name); } else { ordered_passes += *write_passes; write_passes->each_fwd([&](const rx::string& write_pass) { add_dependent_passes(write_pass, passes, ordered_passes, resource_to_write_pass, depth + 1); }); } }); pass.input_buffers.each_fwd([&](const rx::string& buffer_name) { if(const auto& write_passes = resource_to_write_pass.find(buffer_name); write_passes == nullptr) { logger(rx::log::level::k_error, "Pass %s reads from buffer %s, but no passes write to it", pass_name, buffer_name); } else { ordered_passes += *write_passes; write_passes->each_fwd([&](const rx::string& write_pass) { add_dependent_passes(write_pass, passes, ordered_passes, resource_to_write_pass, depth + 1); }); } }); } void determine_usage_order_of_textures(const rx::vector<RenderPassCreateInfo>& passes, rx::map<rx::string, Range>& resource_used_range, rx::vector<rx::string>& resources_in_order) { uint32_t pass_idx = 0; passes.each_fwd([&](const RenderPassCreateInfo& pass) { // color attachments pass.texture_inputs.each_fwd([&](const rx::string& input) { const auto tex_range = resource_used_range.find(input); if(pass_idx < tex_range->first_write_pass) { tex_range->first_write_pass = pass_idx; } else if(pass_idx > tex_range->last_write_pass) { tex_range->last_write_pass = pass_idx; } if(resources_in_order.find(input) == rx::vector<rx::string>::k_npos) { resources_in_order.push_back(input); } }); pass.texture_outputs.each_fwd([&](const TextureAttachmentInfo& output) { const auto tex_range = resource_used_range.find(output.name); if(pass_idx < tex_range->first_write_pass) { tex_range->first_write_pass = pass_idx; } else if(pass_idx > tex_range->last_write_pass) { tex_range->last_write_pass = pass_idx; } if(resources_in_order.find(output.name) == rx::vector<rx::string>::k_npos) { resources_in_order.push_back(output.name); } }); pass_idx++; }); } rx::map<rx::string, rx::string> determine_aliasing_of_textures(const rx::map<rx::string, TextureCreateInfo>& textures, const rx::map<rx::string, Range>& resource_used_range, const rx::vector<rx::string>& resources_in_order) { rx::map<rx::string, rx::string> aliases; for(size_t i = 0; i < resources_in_order.size(); i++) { const auto& to_alias_name = resources_in_order[i]; logger(rx::log::level::k_verbose, "Determining if we can alias `%s`. Does it exist? %d", to_alias_name, (textures.find(to_alias_name) != nullptr)); if(to_alias_name == BACKBUFFER_NAME || to_alias_name == SCENE_OUTPUT_RT_NAME) { // Yay special cases! continue; } const auto& to_alias_format = textures.find(to_alias_name)->format; // Only try to alias with lower-indexed resources for(size_t j = 0; j < i; j++) { logger(rx::log::level::k_verbose, "Trying to alias it with resource at index %zu out of %zu", j, resources_in_order.size()); const rx::string& try_alias_name = resources_in_order[j]; if(resource_used_range.find(to_alias_name)->is_disjoint_with(*resource_used_range.find(try_alias_name))) { // They can be aliased if they have the same format const auto& try_alias_format = textures.find(try_alias_name)->format; if(to_alias_format == try_alias_format) { aliases.insert(to_alias_name, try_alias_name); } } } } return aliases; } } // namespace nova::renderer::shaderpack <commit_msg>[rendergraph] Initialize a vector before we push onto it<commit_after>#include "render_graph_builder.hpp" #include <minitrace.h> #include <rx/core/algorithm/max.h> #include <rx/core/algorithm/min.h> #include <rx/core/log.h> #include "nova_renderer/constants.hpp" namespace nova::renderer::shaderpack { RX_LOG("RenderGraphBuilder", logger); /*! * \brief Adds all the passes that `pass_name` depends on to the list of ordered passes * * This method performs a depth-first traversal of the pass tree. It shouldn't matter whether we do depth or * breadth first, but depth first feels cleaner * * \param pass_name The passes that were just added to the list of ordered passes * \param passes A map from pass name to pass. Useful for the explicit dependencies of a pass * \param ordered_passes The passes in submissions order... almost. When this function adds to ordered_passes the * list has a lot of duplicates. They're removed in a later step * \param resource_to_write_pass A map from resource name to list of passes that write to that resource. Useful for * resolving the implicit dependencies of a pass * \param depth The depth in the tree that we're at. If this number ever grows bigger than the total number of * passes, there's a circular dependency somewhere in the render graph. This is Bad and we hate it */ void add_dependent_passes(const rx::string& pass_name, const rx::map<rx::string, RenderPassCreateInfo>& passes, rx::vector<rx::string>& ordered_passes, const rx::map<rx::string, rx::vector<rx::string>>& resource_to_write_pass, uint32_t depth); bool Range::has_writer() const { return first_write_pass <= last_write_pass; } bool Range::has_reader() const { return first_read_pass <= last_read_pass; } bool Range::is_used() const { return has_writer() || has_reader(); } bool Range::can_alias() const { // If we read before we have completely written to a resource we need to preserve it, so no alias is possible. return !(has_reader() && has_writer() && first_read_pass <= first_write_pass); } unsigned Range::last_used_pass() const { unsigned last_pass = 0; if(has_writer()) { last_pass = rx::algorithm::max(last_pass, last_write_pass); } if(has_reader()) { last_pass = rx::algorithm::max(last_pass, last_read_pass); } return last_pass; } unsigned Range::first_used_pass() const { unsigned first_pass = ~0U; if(has_writer()) { first_pass = rx::algorithm::min(first_pass, first_write_pass); } if(has_reader()) { first_pass = rx::algorithm::min(first_pass, first_read_pass); } return first_pass; } bool Range::is_disjoint_with(const Range& other) const { if(!is_used() || !other.is_used()) { return false; } if(!can_alias() || !other.can_alias()) { return false; } const bool left = last_used_pass() < other.first_used_pass(); const bool right = other.last_used_pass() < first_used_pass(); return left || right; } ntl::Result<rx::vector<RenderPassCreateInfo>> order_passes(const rx::vector<RenderPassCreateInfo>& passes) { MTR_SCOPE("Renderpass", "order_passes"); logger(rx::log::level::k_verbose, "Executing Pass Scheduler"); rx::map<rx::string, RenderPassCreateInfo> render_passes_to_order; passes.each_fwd([&](const RenderPassCreateInfo& create_info) { render_passes_to_order.insert(create_info.name, create_info); }); rx::vector<rx::string> ordered_passes; ordered_passes.reserve(passes.size()); /* * Build some acceleration structures */ logger(rx::log::level::k_verbose, "Collecting passes that write to each resource..."); // Maps from resource name to pass that writes to that resource, then from resource name to pass that reads from // that resource auto resource_to_write_pass = rx::map<rx::string, rx::vector<rx::string>>{}; passes.each_fwd([&](const RenderPassCreateInfo& pass) { pass.texture_outputs.each_fwd([&](const TextureAttachmentInfo& output) { auto* write_pass_list = resource_to_write_pass.find(output.name); if(!write_pass_list) { write_pass_list = resource_to_write_pass.insert(output.name, {}); } write_pass_list->push_back(pass.name); }); pass.output_buffers.each_fwd( [&](const rx::string& buffer_name) { auto* write_pass_list = resource_to_write_pass.find(buffer_name); if(!write_pass_list) { write_pass_list = resource_to_write_pass.insert(buffer_name, {}); } write_pass_list->push_back(pass.name); }); }); /* * Initial ordering of passes */ logger(rx::log::level::k_verbose, "First pass at ordering passes..."); // The passes, in simple dependency order if(resource_to_write_pass.find(BACKBUFFER_NAME) == nullptr) { logger(rx::log::level::k_error, "This render graph does not write to the backbuffer. Unable to load this shaderpack because it can't render anything"); return ntl::Result<rx::vector<RenderPassCreateInfo>>(ntl::NovaError("Failed to order passes because no backbuffer was found")); } const auto& backbuffer_writes = *resource_to_write_pass.find(BACKBUFFER_NAME); ordered_passes += backbuffer_writes; backbuffer_writes.each_fwd([&](const rx::string& pass_name) { add_dependent_passes(pass_name, render_passes_to_order, ordered_passes, resource_to_write_pass, 1); }); // We're going to loop through the original list of passes and remove them from the original list of passes // We want to keep the original passes around // This code taken from `RenderGraph::filter_passes` in the Granite engine // It loops through the ordered passes. When it sees the name of a new pass, it writes the pass to // ordered_passes and increments the write position. After all the passes are written, we remove all the // passes after the last one we wrote to, shrinking the list of ordered passes to only include the exact passes we want rx::vector<rx::string> unique_passes; ordered_passes.each_rev([&](const rx::string& pass_name) { if(unique_passes.find(pass_name) == rx::vector<rx::string>::k_npos) { unique_passes.push_back(pass_name); } }); ordered_passes = unique_passes; // Granite does some reordering to try and find a submission order that has the fewest pipeline barriers. Not // gonna worry about that now rx::vector<RenderPassCreateInfo> passes_in_submission_order; passes_in_submission_order.reserve(ordered_passes.size()); ordered_passes.each_fwd( [&](const rx::string& pass_name) { passes_in_submission_order.push_back(*render_passes_to_order.find(pass_name)); }); return ntl::Result(passes_in_submission_order); } void add_dependent_passes(const rx::string& pass_name, const rx::map<rx::string, RenderPassCreateInfo>& passes, rx::vector<rx::string>& ordered_passes, const rx::map<rx::string, rx::vector<rx::string>>& resource_to_write_pass, const uint32_t depth) { if(depth > passes.size()) { logger(rx::log::level::k_error, "Circular render graph detected! Please fix your render graph to not have circular dependencies"); } const auto& pass = *passes.find(pass_name); pass.texture_inputs.each_fwd([&](const rx::string& texture_name) { if(const auto write_passes = resource_to_write_pass.find(texture_name); write_passes == nullptr) { // TODO: Ignore the implicitly defined resources logger(rx::log::level::k_error, "Pass %s reads from resource %s, but nothing writes to it", pass_name, texture_name); } else { ordered_passes += *write_passes; write_passes->each_fwd([&](const rx::string& write_pass) { add_dependent_passes(write_pass, passes, ordered_passes, resource_to_write_pass, depth + 1); }); } }); pass.input_buffers.each_fwd([&](const rx::string& buffer_name) { if(const auto& write_passes = resource_to_write_pass.find(buffer_name); write_passes == nullptr) { logger(rx::log::level::k_error, "Pass %s reads from buffer %s, but no passes write to it", pass_name, buffer_name); } else { ordered_passes += *write_passes; write_passes->each_fwd([&](const rx::string& write_pass) { add_dependent_passes(write_pass, passes, ordered_passes, resource_to_write_pass, depth + 1); }); } }); } void determine_usage_order_of_textures(const rx::vector<RenderPassCreateInfo>& passes, rx::map<rx::string, Range>& resource_used_range, rx::vector<rx::string>& resources_in_order) { uint32_t pass_idx = 0; passes.each_fwd([&](const RenderPassCreateInfo& pass) { // color attachments pass.texture_inputs.each_fwd([&](const rx::string& input) { const auto tex_range = resource_used_range.find(input); if(pass_idx < tex_range->first_write_pass) { tex_range->first_write_pass = pass_idx; } else if(pass_idx > tex_range->last_write_pass) { tex_range->last_write_pass = pass_idx; } if(resources_in_order.find(input) == rx::vector<rx::string>::k_npos) { resources_in_order.push_back(input); } }); pass.texture_outputs.each_fwd([&](const TextureAttachmentInfo& output) { const auto tex_range = resource_used_range.find(output.name); if(pass_idx < tex_range->first_write_pass) { tex_range->first_write_pass = pass_idx; } else if(pass_idx > tex_range->last_write_pass) { tex_range->last_write_pass = pass_idx; } if(resources_in_order.find(output.name) == rx::vector<rx::string>::k_npos) { resources_in_order.push_back(output.name); } }); pass_idx++; }); } rx::map<rx::string, rx::string> determine_aliasing_of_textures(const rx::map<rx::string, TextureCreateInfo>& textures, const rx::map<rx::string, Range>& resource_used_range, const rx::vector<rx::string>& resources_in_order) { rx::map<rx::string, rx::string> aliases; for(size_t i = 0; i < resources_in_order.size(); i++) { const auto& to_alias_name = resources_in_order[i]; logger(rx::log::level::k_verbose, "Determining if we can alias `%s`. Does it exist? %d", to_alias_name, (textures.find(to_alias_name) != nullptr)); if(to_alias_name == BACKBUFFER_NAME || to_alias_name == SCENE_OUTPUT_RT_NAME) { // Yay special cases! continue; } const auto& to_alias_format = textures.find(to_alias_name)->format; // Only try to alias with lower-indexed resources for(size_t j = 0; j < i; j++) { logger(rx::log::level::k_verbose, "Trying to alias it with resource at index %zu out of %zu", j, resources_in_order.size()); const rx::string& try_alias_name = resources_in_order[j]; if(resource_used_range.find(to_alias_name)->is_disjoint_with(*resource_used_range.find(try_alias_name))) { // They can be aliased if they have the same format const auto& try_alias_format = textures.find(try_alias_name)->format; if(to_alias_format == try_alias_format) { aliases.insert(to_alias_name, try_alias_name); } } } } return aliases; } } // namespace nova::renderer::shaderpack <|endoftext|>
<commit_before>#include <common/test.h> #include <common/thread/mutex.h> #include <common/thread/thread.h> #define NTHREAD 8 #define ROUNDS 1024 static LockClass test_lock_class("TestMutexClass"); static Mutex test_mtx(&test_lock_class, "TestMutex"); class TestThread : public Thread { Test *test_main_; Test *test_destroy_; public: TestThread(Test *test_main, Test *test_destroy) : Thread("TestThread"), test_main_(test_main), test_destroy_(test_destroy) { } ~TestThread() { test_destroy_->pass(); } void main(void) { test_main_->pass(); ASSERT_LOCK_NOT_OWNED(&test_mtx); { ASSERT_LOCK_NOT_OWNED(&test_mtx); ScopedLock testSL(&test_mtx); ASSERT_LOCK_OWNED(&test_mtx); testSL.drop(); ASSERT_LOCK_NOT_OWNED(&test_mtx); { ASSERT_LOCK_NOT_OWNED(&test_mtx); ScopedLock testSL2(&test_mtx); ASSERT_LOCK_OWNED(&test_mtx); } { ASSERT_LOCK_NOT_OWNED(&test_mtx); ScopedLock testSL3(&test_mtx); ASSERT_LOCK_OWNED(&test_mtx); testSL3.drop(); ASSERT_LOCK_NOT_OWNED(&test_mtx); } ASSERT_LOCK_NOT_OWNED(&test_mtx); testSL.acquire(&test_mtx); ASSERT_LOCK_OWNED(&test_mtx); } ASSERT_LOCK_NOT_OWNED(&test_mtx); } }; int main(void) { Thread *threads[NTHREAD]; Test *test_main[NTHREAD], *test_destroy[NTHREAD]; TestGroup g("/test/scopedlock1", "ScopedLock #1"); unsigned j; for (j = 0; j < ROUNDS; j++) { unsigned i; for (i = 0; i < NTHREAD; i++) { test_main[i] = new Test(g, "Main function called."); test_destroy[i] = new Test(g, "Destructor called."); threads[i] = new TestThread(test_main[i], test_destroy[i]); } for (i = 0; i < NTHREAD; i++) threads[i]->start(); for (i = 0; i < NTHREAD; i++) threads[i]->join(); for (i = 0; i < NTHREAD; i++) delete test_main[i]; for (i = 0; i < NTHREAD; i++) delete threads[i]; for (i = 0; i < NTHREAD; i++) delete test_destroy[i]; } return (0); } <commit_msg>Remove EOL whitespace.<commit_after>#include <common/test.h> #include <common/thread/mutex.h> #include <common/thread/thread.h> #define NTHREAD 8 #define ROUNDS 1024 static LockClass test_lock_class("TestMutexClass"); static Mutex test_mtx(&test_lock_class, "TestMutex"); class TestThread : public Thread { Test *test_main_; Test *test_destroy_; public: TestThread(Test *test_main, Test *test_destroy) : Thread("TestThread"), test_main_(test_main), test_destroy_(test_destroy) { } ~TestThread() { test_destroy_->pass(); } void main(void) { test_main_->pass(); ASSERT_LOCK_NOT_OWNED(&test_mtx); { ASSERT_LOCK_NOT_OWNED(&test_mtx); ScopedLock testSL(&test_mtx); ASSERT_LOCK_OWNED(&test_mtx); testSL.drop(); ASSERT_LOCK_NOT_OWNED(&test_mtx); { ASSERT_LOCK_NOT_OWNED(&test_mtx); ScopedLock testSL2(&test_mtx); ASSERT_LOCK_OWNED(&test_mtx); } { ASSERT_LOCK_NOT_OWNED(&test_mtx); ScopedLock testSL3(&test_mtx); ASSERT_LOCK_OWNED(&test_mtx); testSL3.drop(); ASSERT_LOCK_NOT_OWNED(&test_mtx); } ASSERT_LOCK_NOT_OWNED(&test_mtx); testSL.acquire(&test_mtx); ASSERT_LOCK_OWNED(&test_mtx); } ASSERT_LOCK_NOT_OWNED(&test_mtx); } }; int main(void) { Thread *threads[NTHREAD]; Test *test_main[NTHREAD], *test_destroy[NTHREAD]; TestGroup g("/test/scopedlock1", "ScopedLock #1"); unsigned j; for (j = 0; j < ROUNDS; j++) { unsigned i; for (i = 0; i < NTHREAD; i++) { test_main[i] = new Test(g, "Main function called."); test_destroy[i] = new Test(g, "Destructor called."); threads[i] = new TestThread(test_main[i], test_destroy[i]); } for (i = 0; i < NTHREAD; i++) threads[i]->start(); for (i = 0; i < NTHREAD; i++) threads[i]->join(); for (i = 0; i < NTHREAD; i++) delete test_main[i]; for (i = 0; i < NTHREAD; i++) delete threads[i]; for (i = 0; i < NTHREAD; i++) delete test_destroy[i]; } return (0); } <|endoftext|>
<commit_before>#pragma once /* MIT License Copyright (c) 2017 Blockchain-VCS 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 "platform.hpp" // Platform Specific Stuff NOTE: Must Always be the first include in a file #include <iostream> // std::cout #include <string> // std::string #include <algorithm> // std::find_if #include <vector> // std::vector #include <map> // std::map #include <stdexcept> // throw std::runtime_error() #include "constants.hpp" // MAX_BLOCK_SIZE namespace BlockchainCpp { template <class BlockType> class Blockchain { public: Blockchain(){ } Blockchain(std::map<std::string, BlockType*>, std::vector<Blockchain<BlockType>> orphanChains) : public Blockchain() { this->blocks = hashedBlocks; this->orphanChains = orphanChains; } template <class BlockType> bool add(BlockType* block) { if(block->getData() == nullptr) throw std::runtime_error("Can not add a null block to a blockchain"); block->setHeight(this->count + 1); block->setIndex(this->count); if(lastBlock == nullptr) block->setPreviousHash(""); else block->setPreviousHash(lastBlock->getHash()); block->mine(); block->lock(); std::string hash = block->getHash(); if(!containsBlockByHash(hash)) { this->blocks.insert( {hash, block} ); this->count++; lastBlock = block; return true; } std::cout << "[WARNING] Block with Hash: " << hash << " was already present in the blockchain Skipping" << std::endl; return false; } bool containsBlockByHash(std::string hash){ if(this->blocks.find(hash) == this->blocks.end()) return false; return true; } BlockType* getBlockByHash(std::string hash){ if(!this->containsBlockByHash(hash)) return nullptr; return this->blocks[hash]; } bool containsBlockByHeight(unsigned long height) { return height <= count + 1; } BlockType* getBlockByHeight(unsigned long height) { if(!this->containsBlockByHeight(height)) return nullptr; std::string hash = this->lastBlock->getHash(); BlockType* blk = this->lastBlock; while(hash != ""){ blk = getBlockByHash(hash); if(blk == nullptr) break; if(blk->getHeight() == height) return blk; hash = blk->getPreviousHash(); } return nullptr; } std::map<std::string, BlockType*> getBlocks() const { return this->blocks; } std::vector<Blockchain<BlockType>> getOrphanedChains() const { return this->orphanChains; } BlockType* getLastBlock() const { return this->lastBlock; } unsigned long getCount() const { return this->count; } virtual ~Blockchain() { // for(int i = 0; i < this->blocks->size() - 1; i++) { // delete this->blocks[i]; // } // delete this->blocks; // for(int i = 0; i < this->orphanChains->size(); i++) [ // delete this->orphanChains[i]; // ] // delete this->orphanChains; } protected: private: BlockType* lastBlock = nullptr; std::map<std::string, BlockType*> blocks = std::map<std::string, BlockType*>(); std::vector<Blockchain<BlockType>*> orphanChains = std::vector<Blockchain<BlockType>*>(); unsigned long count = 0; }; }<commit_msg>Allow blockchains to be written to a file<commit_after>#pragma once /* MIT License Copyright (c) 2017 Blockchain-VCS 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 "platform.hpp" // Platform Specific Stuff NOTE: Must Always be the first include in a file #include <iostream> // std::cout #include <string> // std::string #include <algorithm> // std::find_if #include <vector> // std::vector #include <map> // std::map #include <stdexcept> // throw std::runtime_error() #include "conversions.hpp" #include "operators.hpp" #include "constants.hpp" // MAX_BLOCK_SIZE namespace BlockchainCpp { template <class BlockType> class Blockchain { public: Blockchain(){ } Blockchain(std::map<std::string, BlockType*>, std::vector<Blockchain<BlockType>> orphanedChains) : public Blockchain() { this->blocks = hashedBlocks; this->orphanedChains = orphanedChains; } template <class BlockType> bool add(BlockType* block) { if(block->getData() == nullptr) throw std::runtime_error("Can not add a null block to a blockchain"); block->setHeight(this->count + 1); block->setIndex(this->count); if(lastBlock == nullptr) block->setPreviousHash(""); else block->setPreviousHash(lastBlock->getHash()); block->mine(); block->lock(); std::string hash = block->getHash(); if(!containsBlockByHash(hash)) { this->blocks.insert( {hash, block} ); this->count++; lastBlock = block; return true; } std::cout << "[WARNING] Block with Hash: " << hash << " was already present in the blockchain Skipping" << std::endl; return false; } bool containsBlockByHash(std::string hash){ if(this->blocks.find(hash) == this->blocks.end()) return false; return true; } BlockType* getBlockByHash(std::string hash){ if(!this->containsBlockByHash(hash)) return nullptr; return this->blocks[hash]; } bool containsBlockByHeight(unsigned long height) { return height <= count + 1; } BlockType* getBlockByHeight(unsigned long height) { if(!this->containsBlockByHeight(height)) return nullptr; std::string hash = this->lastBlock->getHash(); BlockType* blk = this->lastBlock; while(hash != ""){ blk = getBlockByHash(hash); if(blk == nullptr) break; if(blk->getHeight() == height) return blk; hash = blk->getPreviousHash(); } return nullptr; } std::vector<unsigned char> toBytes() { std::vector<unsigned char> bytes = std::vector<unsigned char>(sizeof(Blockchain<BlockType>)); if(this->lastBlock != nullptr){ // for(int i = 0 i < sizeof(BlockData) - 1; i++){ // bytes.push_back(static_cast<unsigned char>(*(this->lastBlock + i))); // } bytes += this->lastBlock->toBytes(); } for(std::map<std::string, BlockType*>::iterator it = this->blocks.begin(); it != this->blocks.end(); it++) { bytes += it->second->toBytes(); } if (this->orphanedChains.size() > 0) { for (int i = 0; i < this->orphanedChains.size() - 1; i++) { bytes += orphanedChains[i]->toBytes(); } } return bytes; } std::string toString() { return "TODO"; } std::map<std::string, BlockType*> getBlocks() const { return this->blocks; } std::vector<Blockchain<BlockType>> getOrphanedChains() const { return this->orphanedChains; } BlockType* getLastBlock() const { return this->lastBlock; } unsigned long getCount() const { return this->count; } virtual ~Blockchain() { // for(int i = 0; i < this->blocks->size() - 1; i++) { // delete this->blocks[i]; // } // delete this->blocks; // for(int i = 0; i < this->orphanedChains->size(); i++) [ // delete this->orphanedChains[i]; // ] // delete this->orphanedChains; } protected: private: BlockType* lastBlock = nullptr; std::map<std::string, BlockType*> blocks = std::map<std::string, BlockType*>(); std::vector<Blockchain<BlockType>*> orphanedChains = std::vector<Blockchain<BlockType>*>(); unsigned long count = 0; }; }<|endoftext|>
<commit_before>/* * #%L * %% * Copyright (C) 2016 BMW Car IT GmbH * %% * 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. * #L% */ #include "ShortCircuitTest.h" #include <boost/program_options.hpp> #ifdef JOYNR_ENABLE_DLT_LOGGING #include <dlt/dlt.h> #endif // JOYNR_ENABLE_DLT_LOGGING #include "../common/Enum.h" JOYNR_ENUM(TestCase, (SEND_STRING)(SEND_BYTEARRAY)(SEND_STRUCT)); int main(int argc, char* argv[]) { #ifdef JOYNR_ENABLE_DLT_LOGGING // Register app at the dlt-daemon for logging DLT_REGISTER_APP("JOYT", argv[0]); #endif // JOYNR_ENABLE_DLT_LOGGING namespace po = boost::program_options; std::size_t runs; TestCase testCase; auto validateRuns = [](std::size_t value) { if (value == 0) { throw po::validation_error( po::validation_error::invalid_option_value, "runs", std::to_string(value)); } }; po::options_description desc("Available options"); desc.add_options()("help,h", "produce help message")( "runs,r", po::value(&runs)->required()->notifier(validateRuns), "number of runs")( "testCase,t", po::value(&testCase)->required(), "SEND_STRING|SEND_BYTEARRAY|SEND_STRUCT"); try { po::variables_map vm; po::store(po::parse_command_line(argc, argv, desc), vm); po::notify(vm); if (vm.count("help")) { std::cout << desc << std::endl; return EXIT_FAILURE; } ShortCircuitTest test(runs); switch (testCase) { case TestCase::SEND_BYTEARRAY: test.roundTripByteArray(10000); test.roundTripByteArray(100000); break; case TestCase::SEND_STRING: test.roundTripString(36); break; case TestCase::SEND_STRUCT: test.roundTripStruct(29); break; } } catch (const std::exception& e) { std::cerr << e.what(); return EXIT_FAILURE; } return EXIT_SUCCESS; } <commit_msg>[benchmark, C++] set data size to 100 for short circuit test<commit_after>/* * #%L * %% * Copyright (C) 2016 BMW Car IT GmbH * %% * 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. * #L% */ #include "ShortCircuitTest.h" #include <boost/program_options.hpp> #ifdef JOYNR_ENABLE_DLT_LOGGING #include <dlt/dlt.h> #endif // JOYNR_ENABLE_DLT_LOGGING #include "../common/Enum.h" JOYNR_ENUM(TestCase, (SEND_STRING)(SEND_BYTEARRAY)(SEND_STRUCT)); int main(int argc, char* argv[]) { #ifdef JOYNR_ENABLE_DLT_LOGGING // Register app at the dlt-daemon for logging DLT_REGISTER_APP("JOYT", argv[0]); #endif // JOYNR_ENABLE_DLT_LOGGING namespace po = boost::program_options; std::size_t runs; TestCase testCase; auto validateRuns = [](std::size_t value) { if (value == 0) { throw po::validation_error( po::validation_error::invalid_option_value, "runs", std::to_string(value)); } }; po::options_description desc("Available options"); desc.add_options()("help,h", "produce help message")( "runs,r", po::value(&runs)->required()->notifier(validateRuns), "number of runs")( "testCase,t", po::value(&testCase)->required(), "SEND_STRING|SEND_BYTEARRAY|SEND_STRUCT"); try { po::variables_map vm; po::store(po::parse_command_line(argc, argv, desc), vm); po::notify(vm); if (vm.count("help")) { std::cout << desc << std::endl; return EXIT_FAILURE; } ShortCircuitTest test(runs); switch (testCase) { case TestCase::SEND_BYTEARRAY: test.roundTripByteArray(10000); test.roundTripByteArray(100000); break; case TestCase::SEND_STRING: test.roundTripString(100); break; case TestCase::SEND_STRUCT: test.roundTripStruct(100); break; } } catch (const std::exception& e) { std::cerr << e.what(); return EXIT_FAILURE; } return EXIT_SUCCESS; } <|endoftext|>
<commit_before>/* -------------------------------------------------------------------------- */ /* Copyright 2002-2013, OpenNebula Project (OpenNebula.org), C12G Labs */ /* */ /* 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 "RangedLeases.h" #include "Nebula.h" #include <cmath> /* ************************************************************************** */ /* Ranged Leases class */ /* ************************************************************************** */ RangedLeases::RangedLeases( SqlDB * db, int _oid, unsigned int _mac_prefix, unsigned int _global[], unsigned int _site[], unsigned int _ip_start, unsigned int _ip_end): Leases(db, _oid, 0, _mac_prefix, _global, _site), ip_start(_ip_start),ip_end(_ip_end),current(0) { size = ip_end - ip_start + 1; } /* ************************************************************************** */ /* Ranged Leases :: Methods */ /* ************************************************************************** */ static int get_template_size(VirtualNetwork* vn, unsigned int& host_bits, unsigned int& size) { string st_size = ""; vn->erase_template_attribute("NETWORK_SIZE", st_size); if ( st_size == "C" || st_size == "c" ) { host_bits = 8; size = 256; } else if ( st_size == "B" || st_size == "b" ) { host_bits = 16; size = 65536; } else if ( st_size == "A" || st_size == "a" ) { host_bits = 24; size = 16777216; } else { if (!st_size.empty())//Assume it's a number { istringstream iss(st_size); iss >> size; if (iss.fail()) { return -1; } } else { size = VirtualNetworkPool::default_size(); } host_bits = (int) ceil(log(size+2)/log(2)); } return 0; } /* -------------------------------------------------------------------------- */ int RangedLeases::process_template(VirtualNetwork* vn, unsigned int& ip_start, unsigned int& ip_end, string& error_str) { ostringstream oss; string st_addr = ""; string st_mask = ""; string st_ip_start = ""; string st_ip_end = ""; string st_mac_start = ""; unsigned int host_bits = 0; unsigned int network_bits; unsigned int size; unsigned int net_addr; unsigned int net_mask; size_t pos; unsigned int mac[2]; // ------------------------------------------------------------------------- // Pure IPv6 network definition based on MAC_START and NETWORK_SIZE // ------------------------------------------------------------------------- vn->erase_template_attribute("MAC_START", st_mac_start); if (!st_mac_start.empty()) { if ( Leases::Lease::mac_to_number(st_mac_start, mac) != 0 ) { goto error_mac_start; } ip_start = mac[0]; if (get_template_size(vn, host_bits, size) != 0) { goto error_size; } ip_end = ip_start + size; if ( ip_end < ip_start ) { goto error_greater_mac; } vn->remove_template_attribute("IP_START"); vn->remove_template_attribute("IP_END"); vn->remove_template_attribute("NETWORK_ADDRESS"); vn->remove_template_attribute("NETWORK_MASK"); vn->remove_template_attribute("NETWORK_SIZE"); return 0; } // ------------------------------------------------------------------------- // Initialize IP_START and IP_END to limit the IP range // ------------------------------------------------------------------------- ip_start = 0; ip_end = 0; vn->erase_template_attribute("IP_START", st_ip_start); vn->erase_template_attribute("IP_END", st_ip_end); if ( !st_ip_start.empty() ) { if ( Leases::Lease::ip_to_number(st_ip_start, ip_start) != 0 ) { goto error_ip_start; } } if ( !st_ip_end.empty() ) { if ( Leases::Lease::ip_to_number(st_ip_end, ip_end) != 0 ) { goto error_ip_end; } } // ------------------------------------------------------------------------- // Check for NETWORK_ADDRESS // ------------------------------------------------------------------------- vn->erase_template_attribute("NETWORK_ADDRESS", st_addr); if (st_addr.empty()) { if ( ip_start != 0 && ip_end != 0 ) //Manually range, exit { if ( ip_end < ip_start ) { goto error_greater; } return 0; } else { goto error_addr; } } // ------------------------------------------------------------------------- // Check for NETWORK_SIZE or NETWORK_ADDRESS // ------------------------------------------------------------------------- pos = st_addr.find("/"); if ( pos != string::npos ) // Check for CIDR network address { string st_network_bits; st_network_bits = st_addr.substr(pos+1); st_addr = st_addr.substr(0,pos); istringstream iss(st_network_bits); iss >> network_bits; if ( network_bits > 32 ) { goto error_prefix; } host_bits = 32 - network_bits; } else // Check for network mask in decimal-dot notation { vn->erase_template_attribute("NETWORK_MASK", st_mask); if ( !st_mask.empty() ) { // st_mask is in decimal format, e.g. 255.255.0.0 // The number of trailing 0s is needed if ( Leases::Lease::ip_to_number(st_mask, net_mask) != 0 ) { goto error_netmask; } host_bits = 0; while ( host_bits < 32 && ((net_mask >> host_bits) & 1) != 1 ) { host_bits++; } } else //No network mask, get NETWORK_SIZE { if (get_template_size(vn, host_bits, size) != 0) { goto error_size; } } } vn->remove_template_attribute("NETWORK_SIZE"); // ------------------------------------------------------------------------- // Generate NETWORK_MASK // ------------------------------------------------------------------------- net_mask = 0xFFFFFFFF << host_bits; Lease::ip_to_string(net_mask, st_mask); vn->replace_template_attribute("NETWORK_MASK", st_mask); // ------------------------------------------------------------------------- // Consistency Checks based on the network address, and range // ------------------------------------------------------------------------- if ( Leases::Lease::ip_to_number(st_addr,net_addr) != 0 ) { goto error_net_addr; } if (net_addr != (net_mask & net_addr) ) { goto error_not_base_addr; } // Set IP start/end if ( ip_start == 0 ) { ip_start = net_addr + 1; } if ( ip_end == 0 ) { ip_end = net_addr + (1 << host_bits) - 2; } // Check range restrictions if ( (ip_start & net_mask) != net_addr ) { goto error_range_ip_start; } if ( (ip_end & net_mask) != net_addr ) { goto error_range_ip_end; } if ( ip_end < ip_start ) { goto error_greater; } return 0; error_mac_start: oss << "MAC_START " << st_mac_start << " is not a valid MAC."; goto error_common; error_ip_start: oss << "IP_START " << st_ip_start << " is not a valid IP."; goto error_common; error_ip_end: oss << "IP_END " << st_ip_end << " is not a valid IP."; goto error_common; error_not_base_addr: oss << "NETWORK_ADDRESS " << st_addr << " is not a base address for the network mask " << st_mask << "."; goto error_common; error_net_addr: oss << "NETWORK_ADDRESS " << st_addr << " is not a valid IP."; goto error_common; error_netmask: oss << "NETWORK_MASK " << st_mask << " is not a valid network mask."; goto error_common; error_prefix: oss << "A CIDR prefix of " << network_bits << " bits is not valid."; goto error_common; error_addr: oss << "No NETWORK_ADDRESS in template for Virtual Network."; goto error_common; error_range_ip_start: oss << "IP_START " << st_ip_start << " is not part of the network " << st_addr << "/" << 32-host_bits << "."; goto error_common; error_size: oss << "NETWORK_SIZE is not an integer number."; goto error_common; error_range_ip_end: oss << "IP_END " << st_ip_end << " is not part of the network " << st_addr << "/" << 32-host_bits << "."; goto error_common; error_greater: Leases::Lease::ip_to_string(ip_start, st_ip_start); Leases::Lease::ip_to_string(ip_end, st_ip_end); oss << "IP_START " << st_ip_start << " cannot be greater than the IP_END " << st_ip_end << "."; goto error_common; error_greater_mac: oss << "Size too big, it will overflow MAC address space."; goto error_common; error_common: error_str = oss.str(); return -1; } /* -------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------- */ int RangedLeases::get(int vid, string& ip, string& mac, unsigned int eui64[]) { unsigned int num_ip; int rc = -1; for ( unsigned int i=0; i<size; i++, current = (current+1)%size ) { num_ip = ip_start + current; if (check(num_ip) == false) { unsigned int num_mac[2]; num_mac[1] = mac_prefix; num_mac[0] = num_ip; Leases::Lease::mac_to_eui64(num_mac, eui64); rc = add(num_ip,num_mac,vid); if (rc==0) { Leases::Lease::ip_to_string(num_ip,ip); Leases::Lease::mac_to_string(num_mac,mac); break; } } } return rc; } /* -------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------- */ int RangedLeases::set(int vid, const string& ip, string& mac, unsigned int eui64[]) { unsigned int num_ip; unsigned int num_mac[2]; int rc; rc = Leases::Lease::ip_to_number(ip,num_ip); if (rc != 0) { return -1; } if ( num_ip < ip_start || ip_end < num_ip ) { return -1; } if (check(num_ip) == true) { return -1; } num_mac[1] = mac_prefix; num_mac[0] = num_ip; Leases::Lease::mac_to_eui64(num_mac, eui64); rc = add(num_ip,num_mac,vid); if (rc != 0) { return -1; } Leases::Lease::mac_to_string(num_mac,mac); return 0; } /* -------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------- */ int RangedLeases::add( unsigned int ip, unsigned int mac[], int vid, bool used) { ostringstream oss; Lease * lease; string xml_body; char * sql_xml; int rc; lease = new Lease(ip,mac,vid,used); sql_xml = db->escape_str(lease->to_xml_db(xml_body).c_str()); if ( sql_xml == 0 ) { goto error_body; } oss << "INSERT INTO " << table << " ("<< db_names <<") VALUES (" << oid << "," << ip << "," << "'" << sql_xml << "')"; db->free_str(sql_xml); rc = db->exec(oss); if ( rc != 0 ) { goto error_db; } leases.insert( make_pair(ip,lease) ); n_used++; return rc; error_body: oss.str(""); oss << "Error inserting lease, marshall error"; goto error_common; error_db: oss.str(""); oss << "Error inserting lease in database."; error_common: NebulaLog::log("VNM", Log::ERROR, oss); return -1; } /* -------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------- */ int RangedLeases::del(const string& ip) { unsigned int _ip; ostringstream oss; int rc; map<unsigned int, Lease *>::iterator it_ip; // Remove lease from leases map if ( Lease::ip_to_number(ip,_ip) ) { return 0; } it_ip = leases.find(_ip); if (it_ip == leases.end()) { return 0; //Not in the map, not leased } // Erase it from DB oss << "DELETE FROM " << table << " WHERE oid='" << oid << "' AND ip='" << _ip << "'"; rc = db->exec(oss); if ( rc == 0 ) { n_used--; delete it_ip->second; leases.erase(it_ip); } return rc; } /* -------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------- */ <commit_msg>bug #1983: Keep NETWORK_ADDRESS for Ranged Networks<commit_after>/* -------------------------------------------------------------------------- */ /* Copyright 2002-2013, OpenNebula Project (OpenNebula.org), C12G Labs */ /* */ /* 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 "RangedLeases.h" #include "Nebula.h" #include <cmath> /* ************************************************************************** */ /* Ranged Leases class */ /* ************************************************************************** */ RangedLeases::RangedLeases( SqlDB * db, int _oid, unsigned int _mac_prefix, unsigned int _global[], unsigned int _site[], unsigned int _ip_start, unsigned int _ip_end): Leases(db, _oid, 0, _mac_prefix, _global, _site), ip_start(_ip_start),ip_end(_ip_end),current(0) { size = ip_end - ip_start + 1; } /* ************************************************************************** */ /* Ranged Leases :: Methods */ /* ************************************************************************** */ static int get_template_size(VirtualNetwork* vn, unsigned int& host_bits, unsigned int& size) { string st_size = ""; vn->erase_template_attribute("NETWORK_SIZE", st_size); if ( st_size == "C" || st_size == "c" ) { host_bits = 8; size = 256; } else if ( st_size == "B" || st_size == "b" ) { host_bits = 16; size = 65536; } else if ( st_size == "A" || st_size == "a" ) { host_bits = 24; size = 16777216; } else { if (!st_size.empty())//Assume it's a number { istringstream iss(st_size); iss >> size; if (iss.fail()) { return -1; } } else { size = VirtualNetworkPool::default_size(); } host_bits = (int) ceil(log(size+2)/log(2)); } return 0; } /* -------------------------------------------------------------------------- */ int RangedLeases::process_template(VirtualNetwork* vn, unsigned int& ip_start, unsigned int& ip_end, string& error_str) { ostringstream oss; string st_addr = ""; string st_mask = ""; string st_ip_start = ""; string st_ip_end = ""; string st_mac_start = ""; unsigned int host_bits = 0; unsigned int network_bits; unsigned int size; unsigned int net_addr; unsigned int net_mask; size_t pos; unsigned int mac[2]; // ------------------------------------------------------------------------- // Pure IPv6 network definition based on MAC_START and NETWORK_SIZE // ------------------------------------------------------------------------- vn->erase_template_attribute("MAC_START", st_mac_start); if (!st_mac_start.empty()) { if ( Leases::Lease::mac_to_number(st_mac_start, mac) != 0 ) { goto error_mac_start; } ip_start = mac[0]; if (get_template_size(vn, host_bits, size) != 0) { goto error_size; } ip_end = ip_start + size; if ( ip_end < ip_start ) { goto error_greater_mac; } vn->remove_template_attribute("IP_START"); vn->remove_template_attribute("IP_END"); vn->remove_template_attribute("NETWORK_ADDRESS"); vn->remove_template_attribute("NETWORK_MASK"); vn->remove_template_attribute("NETWORK_SIZE"); return 0; } // ------------------------------------------------------------------------- // Initialize IP_START and IP_END to limit the IP range // ------------------------------------------------------------------------- ip_start = 0; ip_end = 0; vn->erase_template_attribute("IP_START", st_ip_start); vn->erase_template_attribute("IP_END", st_ip_end); if ( !st_ip_start.empty() ) { if ( Leases::Lease::ip_to_number(st_ip_start, ip_start) != 0 ) { goto error_ip_start; } } if ( !st_ip_end.empty() ) { if ( Leases::Lease::ip_to_number(st_ip_end, ip_end) != 0 ) { goto error_ip_end; } } // ------------------------------------------------------------------------- // Check for NETWORK_ADDRESS // ------------------------------------------------------------------------- vn->get_template_attribute("NETWORK_ADDRESS", st_addr); if (st_addr.empty()) { if ( ip_start != 0 && ip_end != 0 ) //Manually range, exit { if ( ip_end < ip_start ) { goto error_greater; } return 0; } else { goto error_addr; } } // ------------------------------------------------------------------------- // Check for NETWORK_SIZE or NETWORK_ADDRESS // ------------------------------------------------------------------------- pos = st_addr.find("/"); if ( pos != string::npos ) // Check for CIDR network address { string st_network_bits; st_network_bits = st_addr.substr(pos+1); st_addr = st_addr.substr(0,pos); istringstream iss(st_network_bits); iss >> network_bits; if ( network_bits > 32 ) { goto error_prefix; } host_bits = 32 - network_bits; } else // Check for network mask in decimal-dot notation { vn->erase_template_attribute("NETWORK_MASK", st_mask); if ( !st_mask.empty() ) { // st_mask is in decimal format, e.g. 255.255.0.0 // The number of trailing 0s is needed if ( Leases::Lease::ip_to_number(st_mask, net_mask) != 0 ) { goto error_netmask; } host_bits = 0; while ( host_bits < 32 && ((net_mask >> host_bits) & 1) != 1 ) { host_bits++; } } else //No network mask, get NETWORK_SIZE { if (get_template_size(vn, host_bits, size) != 0) { goto error_size; } } } vn->remove_template_attribute("NETWORK_SIZE"); // ------------------------------------------------------------------------- // Generate NETWORK_MASK // ------------------------------------------------------------------------- net_mask = 0xFFFFFFFF << host_bits; Lease::ip_to_string(net_mask, st_mask); vn->replace_template_attribute("NETWORK_MASK", st_mask); // ------------------------------------------------------------------------- // Consistency Checks based on the network address, and range // ------------------------------------------------------------------------- if ( Leases::Lease::ip_to_number(st_addr,net_addr) != 0 ) { goto error_net_addr; } if (net_addr != (net_mask & net_addr) ) { goto error_not_base_addr; } // Set IP start/end if ( ip_start == 0 ) { ip_start = net_addr + 1; } if ( ip_end == 0 ) { ip_end = net_addr + (1 << host_bits) - 2; } // Check range restrictions if ( (ip_start & net_mask) != net_addr ) { goto error_range_ip_start; } if ( (ip_end & net_mask) != net_addr ) { goto error_range_ip_end; } if ( ip_end < ip_start ) { goto error_greater; } return 0; error_mac_start: oss << "MAC_START " << st_mac_start << " is not a valid MAC."; goto error_common; error_ip_start: oss << "IP_START " << st_ip_start << " is not a valid IP."; goto error_common; error_ip_end: oss << "IP_END " << st_ip_end << " is not a valid IP."; goto error_common; error_not_base_addr: oss << "NETWORK_ADDRESS " << st_addr << " is not a base address for the network mask " << st_mask << "."; goto error_common; error_net_addr: oss << "NETWORK_ADDRESS " << st_addr << " is not a valid IP."; goto error_common; error_netmask: oss << "NETWORK_MASK " << st_mask << " is not a valid network mask."; goto error_common; error_prefix: oss << "A CIDR prefix of " << network_bits << " bits is not valid."; goto error_common; error_addr: oss << "No NETWORK_ADDRESS in template for Virtual Network."; goto error_common; error_range_ip_start: oss << "IP_START " << st_ip_start << " is not part of the network " << st_addr << "/" << 32-host_bits << "."; goto error_common; error_size: oss << "NETWORK_SIZE is not an integer number."; goto error_common; error_range_ip_end: oss << "IP_END " << st_ip_end << " is not part of the network " << st_addr << "/" << 32-host_bits << "."; goto error_common; error_greater: Leases::Lease::ip_to_string(ip_start, st_ip_start); Leases::Lease::ip_to_string(ip_end, st_ip_end); oss << "IP_START " << st_ip_start << " cannot be greater than the IP_END " << st_ip_end << "."; goto error_common; error_greater_mac: oss << "Size too big, it will overflow MAC address space."; goto error_common; error_common: error_str = oss.str(); return -1; } /* -------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------- */ int RangedLeases::get(int vid, string& ip, string& mac, unsigned int eui64[]) { unsigned int num_ip; int rc = -1; for ( unsigned int i=0; i<size; i++, current = (current+1)%size ) { num_ip = ip_start + current; if (check(num_ip) == false) { unsigned int num_mac[2]; num_mac[1] = mac_prefix; num_mac[0] = num_ip; Leases::Lease::mac_to_eui64(num_mac, eui64); rc = add(num_ip,num_mac,vid); if (rc==0) { Leases::Lease::ip_to_string(num_ip,ip); Leases::Lease::mac_to_string(num_mac,mac); break; } } } return rc; } /* -------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------- */ int RangedLeases::set(int vid, const string& ip, string& mac, unsigned int eui64[]) { unsigned int num_ip; unsigned int num_mac[2]; int rc; rc = Leases::Lease::ip_to_number(ip,num_ip); if (rc != 0) { return -1; } if ( num_ip < ip_start || ip_end < num_ip ) { return -1; } if (check(num_ip) == true) { return -1; } num_mac[1] = mac_prefix; num_mac[0] = num_ip; Leases::Lease::mac_to_eui64(num_mac, eui64); rc = add(num_ip,num_mac,vid); if (rc != 0) { return -1; } Leases::Lease::mac_to_string(num_mac,mac); return 0; } /* -------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------- */ int RangedLeases::add( unsigned int ip, unsigned int mac[], int vid, bool used) { ostringstream oss; Lease * lease; string xml_body; char * sql_xml; int rc; lease = new Lease(ip,mac,vid,used); sql_xml = db->escape_str(lease->to_xml_db(xml_body).c_str()); if ( sql_xml == 0 ) { goto error_body; } oss << "INSERT INTO " << table << " ("<< db_names <<") VALUES (" << oid << "," << ip << "," << "'" << sql_xml << "')"; db->free_str(sql_xml); rc = db->exec(oss); if ( rc != 0 ) { goto error_db; } leases.insert( make_pair(ip,lease) ); n_used++; return rc; error_body: oss.str(""); oss << "Error inserting lease, marshall error"; goto error_common; error_db: oss.str(""); oss << "Error inserting lease in database."; error_common: NebulaLog::log("VNM", Log::ERROR, oss); return -1; } /* -------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------- */ int RangedLeases::del(const string& ip) { unsigned int _ip; ostringstream oss; int rc; map<unsigned int, Lease *>::iterator it_ip; // Remove lease from leases map if ( Lease::ip_to_number(ip,_ip) ) { return 0; } it_ip = leases.find(_ip); if (it_ip == leases.end()) { return 0; //Not in the map, not leased } // Erase it from DB oss << "DELETE FROM " << table << " WHERE oid='" << oid << "' AND ip='" << _ip << "'"; rc = db->exec(oss); if ( rc == 0 ) { n_used--; delete it_ip->second; leases.erase(it_ip); } return rc; } /* -------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------- */ <|endoftext|>
<commit_before>/* * SessionHttpConnectionUtils.cpp * * Copyright (C) 2020 by RStudio, PBC * * Unless you have received this program directly from RStudio pursuant * to the terms of a commercial license agreement with RStudio, then * this program is licensed to you under the terms of version 3 of the * GNU Affero General Public License. This program is distributed WITHOUT * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT, * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details. * */ #include "SessionHttpConnectionUtils.hpp" #include <boost/algorithm/string/predicate.hpp> #include <shared_core/FilePath.hpp> #include <core/Log.hpp> #include <shared_core/Error.hpp> #include <core/FileSerializer.hpp> #include <core/http/Response.hpp> #include <core/http/Request.hpp> #include <core/json/JsonRpc.hpp> #include <core/r_util/RSessionContext.hpp> #include <core/system/Interrupts.hpp> #include <r/RExec.hpp> #include <session/SessionMain.hpp> #include <session/SessionOptions.hpp> #include <session/projects/ProjectsSettings.hpp> namespace rstudio { namespace session { namespace console_input { bool executing(); } } } namespace rstudio { namespace session { void HttpConnection::sendJsonRpcError(const core::Error& error) { core::json::JsonRpcResponse jsonRpcResponse; jsonRpcResponse.setError(error); sendJsonRpcResponse(jsonRpcResponse); } void HttpConnection::sendJsonRpcResponse() { core::json::JsonRpcResponse jsonRpcResponse; sendJsonRpcResponse(jsonRpcResponse); } void HttpConnection::sendJsonRpcResponse( const core::json::JsonRpcResponse& jsonRpcResponse) { // setup response core::http::Response response; // automagic gzip support if (request().acceptsEncoding(core::http::kGzipEncoding)) response.setContentEncoding(core::http::kGzipEncoding); // set response core::json::setJsonRpcResponse(jsonRpcResponse, &response); // send the response sendResponse(response); } namespace connection { std::string rstudioRequestIdFromRequest(const core::http::Request& request) { return request.headerValue("X-RS-RID"); } bool isMethod(boost::shared_ptr<HttpConnection> ptrConnection, const std::string& method) { return boost::algorithm::ends_with(ptrConnection->request().uri(), "rpc/" + method); } bool isGetEvents(boost::shared_ptr<HttpConnection> ptrConnection) { return boost::algorithm::ends_with(ptrConnection->request().uri(), "events/get_events"); } void handleAbortNextProjParam( boost::shared_ptr<HttpConnection> ptrConnection) { std::string nextProj; core::json::JsonRpcRequest jsonRpcRequest; core::Error error = core::json::parseJsonRpcRequest( ptrConnection->request().body(), &jsonRpcRequest); if (!error) { error = core::json::readParam(jsonRpcRequest.params, 0, &nextProj); if (error) LOG_ERROR(error); if (!nextProj.empty()) { core::FilePath userScratch = session::options().userScratchPath(); projects::ProjectsSettings settings(userScratch); settings.setNextSessionProject(nextProj); } } else { LOG_ERROR(error); } } bool checkForAbort(boost::shared_ptr<HttpConnection> ptrConnection, const boost::function<void()> cleanupHandler) { if (isMethod(ptrConnection, "abort")) { // respond and log (try/catch so we are ALWAYS guaranteed to abort) try { // handle the nextProj param if it's specified handleAbortNextProjParam(ptrConnection); // respond ptrConnection->sendJsonRpcResponse(); // log LOG_WARNING_MESSAGE("Abort requested"); } catch(...) { } // cleanup (if we don't do this then the user may be locked out of // future requests). note that this should occur in the normal // course of a graceful shutdown but we do it here anyway just // to be paranoid try { if (cleanupHandler) cleanupHandler(); } catch(...) { } // kill child processes before going down terminateAllChildProcesses(); // abort the process // we no longer do this with ::abort because it generated unwanted exceptions // ::_Exit should perform the same functionality (not running destructors and exiting process) // without generating an exception std::_Exit(EXIT_SUCCESS); return true; } else { return false; } } // on windows we allow suspend_session to be handled on the foreground // thread since we don't have a way to ::kill on that that platform #ifdef _WIN32 bool checkForSuspend(boost::shared_ptr<HttpConnection> ptrConnection) { return false; } #else bool checkForSuspend(boost::shared_ptr<HttpConnection> ptrConnection) { using namespace rstudio::core::json; if (isMethod(ptrConnection, "suspend_session")) { bool force = false; JsonRpcRequest jsonRpcRequest; core::Error error = parseJsonRpcRequest(ptrConnection->request().body(), &jsonRpcRequest); if (error) { ptrConnection->sendJsonRpcError(error); } else if ((error = readParam(jsonRpcRequest.params, 0, &force))) { ptrConnection->sendJsonRpcError(error); } else { // send a signal to this process to suspend using namespace rstudio::core::system; sendSignalToSelf(force ? SigUsr2 : SigUsr1); // send response ptrConnection->sendJsonRpcResponse(); } return true; } else { return false; } } #endif bool checkForInterrupt(boost::shared_ptr<HttpConnection> ptrConnection) { using namespace rstudio::core; using namespace rstudio::core::json; if (!isMethod(ptrConnection, "interrupt")) return false; JsonRpcRequest request; Error error = parseJsonRpcRequest( ptrConnection->request().body(), &request); if (error) { ptrConnection->sendJsonRpcError(error); } else { // interrupt the session. note that we call core::system::interrupt() // as this will signal the interrupt to all processes in the same // process group, which implies that processes launched through e.g. // system() in R can be successfully interrupted. however, in some // cases, a running application in R might install their own interrupt // handler, thereby preventing us from receiving the signal we're now // broadcasting. (was observed with Shiny applications on Windows) // // to ensure that the R session always receives an interrupt, we explicitly // set the interrupt flag even though the normal interrupt handler would do // the same. bool busy = session::console_input::executing(); if (busy) { r::exec::setInterruptsPending(true); core::system::interrupt(); } // send response json::JsonRpcResponse response; response.setResult(busy); ptrConnection->sendJsonRpcResponse(response); } return true; } bool authenticate(boost::shared_ptr<HttpConnection> ptrConnection, const std::string& secret) { // allow all requests if no secret if (secret.empty()) return true; // validate against shared secret return secret == ptrConnection->request().headerValue("X-Shared-Secret"); } } // namespace connection } // namespace session } // namespace rstudio <commit_msg>document motivation<commit_after>/* * SessionHttpConnectionUtils.cpp * * Copyright (C) 2020 by RStudio, PBC * * Unless you have received this program directly from RStudio pursuant * to the terms of a commercial license agreement with RStudio, then * this program is licensed to you under the terms of version 3 of the * GNU Affero General Public License. This program is distributed WITHOUT * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT, * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details. * */ #include "SessionHttpConnectionUtils.hpp" #include <boost/algorithm/string/predicate.hpp> #include <shared_core/FilePath.hpp> #include <core/Log.hpp> #include <shared_core/Error.hpp> #include <core/FileSerializer.hpp> #include <core/http/Response.hpp> #include <core/http/Request.hpp> #include <core/json/JsonRpc.hpp> #include <core/r_util/RSessionContext.hpp> #include <core/system/Interrupts.hpp> #include <r/RExec.hpp> #include <session/SessionMain.hpp> #include <session/SessionOptions.hpp> #include <session/projects/ProjectsSettings.hpp> namespace rstudio { namespace session { namespace console_input { bool executing(); } } } namespace rstudio { namespace session { void HttpConnection::sendJsonRpcError(const core::Error& error) { core::json::JsonRpcResponse jsonRpcResponse; jsonRpcResponse.setError(error); sendJsonRpcResponse(jsonRpcResponse); } void HttpConnection::sendJsonRpcResponse() { core::json::JsonRpcResponse jsonRpcResponse; sendJsonRpcResponse(jsonRpcResponse); } void HttpConnection::sendJsonRpcResponse( const core::json::JsonRpcResponse& jsonRpcResponse) { // setup response core::http::Response response; // automagic gzip support if (request().acceptsEncoding(core::http::kGzipEncoding)) response.setContentEncoding(core::http::kGzipEncoding); // set response core::json::setJsonRpcResponse(jsonRpcResponse, &response); // send the response sendResponse(response); } namespace connection { std::string rstudioRequestIdFromRequest(const core::http::Request& request) { return request.headerValue("X-RS-RID"); } bool isMethod(boost::shared_ptr<HttpConnection> ptrConnection, const std::string& method) { return boost::algorithm::ends_with(ptrConnection->request().uri(), "rpc/" + method); } bool isGetEvents(boost::shared_ptr<HttpConnection> ptrConnection) { return boost::algorithm::ends_with(ptrConnection->request().uri(), "events/get_events"); } void handleAbortNextProjParam( boost::shared_ptr<HttpConnection> ptrConnection) { std::string nextProj; core::json::JsonRpcRequest jsonRpcRequest; core::Error error = core::json::parseJsonRpcRequest( ptrConnection->request().body(), &jsonRpcRequest); if (!error) { error = core::json::readParam(jsonRpcRequest.params, 0, &nextProj); if (error) LOG_ERROR(error); if (!nextProj.empty()) { core::FilePath userScratch = session::options().userScratchPath(); projects::ProjectsSettings settings(userScratch); settings.setNextSessionProject(nextProj); } } else { LOG_ERROR(error); } } bool checkForAbort(boost::shared_ptr<HttpConnection> ptrConnection, const boost::function<void()> cleanupHandler) { if (isMethod(ptrConnection, "abort")) { // respond and log (try/catch so we are ALWAYS guaranteed to abort) try { // handle the nextProj param if it's specified handleAbortNextProjParam(ptrConnection); // respond ptrConnection->sendJsonRpcResponse(); // log LOG_WARNING_MESSAGE("Abort requested"); } catch(...) { } // cleanup (if we don't do this then the user may be locked out of // future requests). note that this should occur in the normal // course of a graceful shutdown but we do it here anyway just // to be paranoid try { if (cleanupHandler) cleanupHandler(); } catch(...) { } // kill child processes before going down terminateAllChildProcesses(); // abort the process // we no longer do this with ::abort because it generated unwanted exceptions // ::_Exit should perform the same functionality (not running destructors and exiting process) // without generating an exception std::_Exit(EXIT_SUCCESS); return true; } else { return false; } } // on windows we allow suspend_session to be handled on the foreground // thread since we don't have a way to ::kill on that that platform #ifdef _WIN32 bool checkForSuspend(boost::shared_ptr<HttpConnection> ptrConnection) { return false; } #else bool checkForSuspend(boost::shared_ptr<HttpConnection> ptrConnection) { using namespace rstudio::core::json; if (isMethod(ptrConnection, "suspend_session")) { bool force = false; JsonRpcRequest jsonRpcRequest; core::Error error = parseJsonRpcRequest(ptrConnection->request().body(), &jsonRpcRequest); if (error) { ptrConnection->sendJsonRpcError(error); } else if ((error = readParam(jsonRpcRequest.params, 0, &force))) { ptrConnection->sendJsonRpcError(error); } else { // send a signal to this process to suspend using namespace rstudio::core::system; sendSignalToSelf(force ? SigUsr2 : SigUsr1); // send response ptrConnection->sendJsonRpcResponse(); } return true; } else { return false; } } #endif bool checkForInterrupt(boost::shared_ptr<HttpConnection> ptrConnection) { using namespace rstudio::core; using namespace rstudio::core::json; if (!isMethod(ptrConnection, "interrupt")) return false; JsonRpcRequest request; Error error = parseJsonRpcRequest( ptrConnection->request().body(), &request); if (error) { ptrConnection->sendJsonRpcError(error); } else { // interrupt the session. note that we call core::system::interrupt() // as this will signal the interrupt to all processes in the same // process group, which implies that processes launched through e.g. // system() in R can be successfully interrupted. however, in some // cases, a running application in R might install their own interrupt // handler, thereby preventing us from receiving the signal we're now // broadcasting. (was observed with Shiny applications on Windows) // // to ensure that the R session always receives an interrupt, we explicitly // set the interrupt flag even though the normal interrupt handler would do // the same. // // NOTE: if the R session is currently waiting for input via stdin, then // a plain interrupt will not be sufficient to stop the read. it's not // immediately clear why this is the case, but if we detect this case then // we avoid sending an interrupt, and instead tell the client that R is not // busy and it should instead send an explicit request to canncel the current // console read request. bool busy = session::console_input::executing(); if (busy) { r::exec::setInterruptsPending(true); core::system::interrupt(); } // send response json::JsonRpcResponse response; response.setResult(busy); ptrConnection->sendJsonRpcResponse(response); } return true; } bool authenticate(boost::shared_ptr<HttpConnection> ptrConnection, const std::string& secret) { // allow all requests if no secret if (secret.empty()) return true; // validate against shared secret return secret == ptrConnection->request().headerValue("X-Shared-Secret"); } } // namespace connection } // namespace session } // namespace rstudio <|endoftext|>
<commit_before>/* * Copyright (c) 2015 Mikhail Baranov * Copyright (c) 2015 Victor Gaydov * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include "roc_rtp/audio_format.h" #include "roc_rtp/headers.h" namespace roc { namespace rtp { extern const AudioFormat AudioFormat_L16_Stereo; extern const AudioFormat AudioFormat_L16_Mono; const AudioFormat* get_audio_format_pt(uint8_t pt) { switch (pt) { case RTP_PT_L16_STEREO: return &AudioFormat_L16_Stereo; case RTP_PT_L16_MONO: return &AudioFormat_L16_Mono; default: break; } return NULL; } const AudioFormat* get_audio_format_cr(packet::channel_mask_t ch, size_t rate) { switch (ch) { case 0x1: if (AudioFormat_L16_Mono.rate == rate) { return &AudioFormat_L16_Mono; } case 0x3: if (AudioFormat_L16_Stereo.rate == rate) { return &AudioFormat_L16_Stereo; } default: break; } return NULL; } } // namespace rtp } // namespace roc <commit_msg>Fix GCC7 warnings<commit_after>/* * Copyright (c) 2015 Mikhail Baranov * Copyright (c) 2015 Victor Gaydov * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include "roc_rtp/audio_format.h" #include "roc_rtp/headers.h" namespace roc { namespace rtp { extern const AudioFormat AudioFormat_L16_Stereo; extern const AudioFormat AudioFormat_L16_Mono; const AudioFormat* get_audio_format_pt(uint8_t pt) { switch (pt) { case RTP_PT_L16_STEREO: return &AudioFormat_L16_Stereo; case RTP_PT_L16_MONO: return &AudioFormat_L16_Mono; default: break; } return NULL; } const AudioFormat* get_audio_format_cr(packet::channel_mask_t ch, size_t rate) { switch (ch) { case 0x1: if (AudioFormat_L16_Mono.rate == rate) { return &AudioFormat_L16_Mono; } break; case 0x3: if (AudioFormat_L16_Stereo.rate == rate) { return &AudioFormat_L16_Stereo; } break; default: break; } return NULL; } } // namespace rtp } // namespace roc <|endoftext|>
<commit_before>/*========================================================================= Program: Visualization Toolkit Module: vtkShepardMethod.cc Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 1993-1996 Ken Martin, Will Schroeder, Bill Lorensen. This software is copyrighted by Ken Martin, Will Schroeder and Bill Lorensen. The following terms apply to all files associated with the software unless explicitly disclaimed in individual files. This copyright specifically does not apply to the related textbook "The Visualization Toolkit" ISBN 013199837-4 published by Prentice Hall which is covered by its own copyright. The authors hereby grant permission to use, copy, and distribute this software and its documentation for any purpose, provided that existing copyright notices are retained in all copies and that this notice is included verbatim in any distributions. Additionally, the authors grant permission to modify this software and its documentation for any purpose, provided that such modifications are not distributed without the explicit consent of the authors and that existing copyright notices are retained in all copies. Some of the algorithms implemented by this software are patented, observe all applicable patent law. IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF, EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. =========================================================================*/ #include "vtkShepardMethod.hh" #include "vtkMath.hh" // Description: // Construct with sample dimensions=(50,50,50) and so that model bounds are // automatically computed from input. Null value for each unvisited output // point is 0.0. Maximum distance is 0.25. vtkShepardMethod::vtkShepardMethod() { this->MaximumDistance = 0.25; this->ModelBounds[0] = 0.0; this->ModelBounds[1] = 0.0; this->ModelBounds[2] = 0.0; this->ModelBounds[3] = 0.0; this->ModelBounds[4] = 0.0; this->ModelBounds[5] = 0.0; this->SampleDimensions[0] = 50; this->SampleDimensions[1] = 50; this->SampleDimensions[2] = 50; this->NullValue = 0.0; } void vtkShepardMethod::SetModelBounds(float xmin, float xmax, float ymin, float ymax, float zmin, float zmax) { float bounds[6]; bounds[0] = xmin; bounds[1] = xmax; bounds[2] = ymin; bounds[3] = ymax; bounds[4] = zmin; bounds[5] = zmax; this->SetModelBounds(bounds); } // Description: // Compute ModelBounds from input geometry. float vtkShepardMethod::ComputeModelBounds(float origin[3], float ar[3]) { float *bounds, maxDist; int i, adjustBounds=0; // compute model bounds if not set previously if ( this->ModelBounds[0] >= this->ModelBounds[1] || this->ModelBounds[2] >= this->ModelBounds[3] || this->ModelBounds[4] >= this->ModelBounds[5] ) { adjustBounds = 1; bounds = this->Input->GetBounds(); } else { bounds = this->ModelBounds; } for (maxDist=0.0, i=0; i<3; i++) if ( (bounds[2*i+1] - bounds[2*i]) > maxDist ) maxDist = bounds[2*i+1] - bounds[2*i]; maxDist *= this->MaximumDistance; // adjust bounds so model fits strictly inside (only if not set previously) if ( adjustBounds ) { for (i=0; i<3; i++) { this->ModelBounds[2*i] = bounds[2*i] - maxDist; this->ModelBounds[2*i+1] = bounds[2*i+1] + maxDist; } } // Set volume origin and aspect ratio for (i=0; i<3; i++) { origin[i] = this->ModelBounds[2*i]; ar[i] = (this->ModelBounds[2*i+1] - this->ModelBounds[2*i]) / (this->SampleDimensions[i] - 1); } ((vtkStructuredPoints *)this->Output)->SetOrigin(origin); ((vtkStructuredPoints *)this->Output)->SetAspectRatio(ar); return maxDist; } void vtkShepardMethod::Execute() { int ptId, i, j, k; float *px, x[3], s, *sum, ar[3], origin[3]; float maxDistance, distance2, inScalar; vtkScalars *inScalars; vtkFloatScalars *newScalars; int numPts, numNewPts, idx; int min[3], max[3]; int jkFactor; vtkStructuredPoints *output=(vtkStructuredPoints *)this->Output; vtkDebugMacro(<< "Executing Shepard method"); // // Check input // if ( (numPts=this->Input->GetNumberOfPoints()) < 1 ) { vtkErrorMacro(<<"Points must be defined!"); return; } if ( (inScalars = this->Input->GetPointData()->GetScalars()) == NULL ) { vtkErrorMacro(<<"Scalars must be defined!"); return; } // // Allocate // numNewPts = this->SampleDimensions[0] * this->SampleDimensions[1] * this->SampleDimensions[2]; newScalars = new vtkFloatScalars(numNewPts); sum = new float[numNewPts]; for (i=0; i<numNewPts; i++) { newScalars->SetScalar(i,0.0); sum[i] = 0.0; } output->SetDimensions(this->GetSampleDimensions()); maxDistance = this->ComputeModelBounds(origin,ar); // // Traverse all input points. Each input point affects voxels within maxDistance. // for (ptId=0; ptId < numPts; ptId++) { px = this->Input->GetPoint(ptId); inScalar = inScalars->GetScalar(ptId); for (i=0; i<3; i++) //compute dimensional bounds in data set { min[i] = (int) ((float)((x[i] - maxDistance) - origin[i]) / ar[i]); max[i] = (int) ((float)((x[i] + maxDistance) - origin[i]) / ar[i]); if (min[i] < 0) min[i] = 0; if (max[i] >= this->SampleDimensions[i]) max[i] = this->SampleDimensions[i] - 1; } jkFactor = this->SampleDimensions[0]*this->SampleDimensions[1]; for (k = min[2]; k <= max[2]; k++) { x[2] = ar[2] * k + origin[2]; for (j = min[1]; j <= max[1]; j++) { x[1] = ar[1] * j + origin[1]; for (i = min[0]; i <= max[0]; i++) { x[0] = ar[0] * i + origin[0]; idx = jkFactor*k + this->SampleDimensions[0]*j + i; distance2 = vtkMath::Distance2BetweenPoints(x,px); if ( distance2 == 0.0 ) { sum[idx] = VTK_LARGE_FLOAT; newScalars->SetScalar(idx,VTK_LARGE_FLOAT); } else { s = newScalars->GetScalar(idx); sum[idx] = 1.0 / distance2; newScalars->SetScalar(idx,s+(inScalar/distance2)); } } } } } // // Run through scalars and compute final values // for (ptId=0; ptId<numNewPts; ptId++) { s = newScalars->GetScalar(ptId); if ( sum[ptId] != 0.0 ) newScalars->SetScalar(ptId,s/sum[ptId]); else newScalars->SetScalar(ptId,this->NullValue); } // // Update self // delete [] sum; output->GetPointData()->SetScalars(newScalars); newScalars->Delete(); } // Description: // Set the i-j-k dimensions on which to sample the distance function. void vtkShepardMethod::SetSampleDimensions(int i, int j, int k) { int dim[3]; dim[0] = i; dim[1] = j; dim[2] = k; this->SetSampleDimensions(dim); } // Description: // Set the i-j-k dimensions on which to sample the distance function. void vtkShepardMethod::SetSampleDimensions(int dim[3]) { int dataDim, i; vtkDebugMacro(<< " setting SampleDimensions to (" << dim[0] << "," << dim[1] << "," << dim[2] << ")"); if ( dim[0] != this->SampleDimensions[0] || dim[1] != SampleDimensions[1] || dim[2] != SampleDimensions[2] ) { if ( dim[0]<1 || dim[1]<1 || dim[2]<1 ) { vtkErrorMacro (<< "Bad Sample Dimensions, retaining previous values"); return; } for (dataDim=0, i=0; i<3 ; i++) if (dim[i] > 1) dataDim++; if ( dataDim < 3 ) { vtkErrorMacro(<<"Sample dimensions must define a volume!"); return; } for ( i=0; i<3; i++) this->SampleDimensions[i] = dim[i]; this->Modified(); } } void vtkShepardMethod::PrintSelf(ostream& os, vtkIndent indent) { vtkDataSetFilter::PrintSelf(os,indent); os << indent << "Maximum Distance: " << this->MaximumDistance << "\n"; os << indent << "Sample Dimensions: (" << this->SampleDimensions[0] << ", " << this->SampleDimensions[1] << ", " << this->SampleDimensions[2] << ")\n"; os << indent << "ModelBounds: \n"; os << indent << " Xmin,Xmax: (" << this->ModelBounds[0] << ", " << this->ModelBounds[1] << ")\n"; os << indent << " Ymin,Ymax: (" << this->ModelBounds[2] << ", " << this->ModelBounds[3] << ")\n"; os << indent << " Zmin,Zmax: (" << this->ModelBounds[4] << ", " << this->ModelBounds[5] << ")\n"; os << indent << "Null Value: " << this->NullValue << "\n"; } <commit_msg>ERR: Bug fix.<commit_after>/*========================================================================= Program: Visualization Toolkit Module: vtkShepardMethod.cc Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 1993-1996 Ken Martin, Will Schroeder, Bill Lorensen. This software is copyrighted by Ken Martin, Will Schroeder and Bill Lorensen. The following terms apply to all files associated with the software unless explicitly disclaimed in individual files. This copyright specifically does not apply to the related textbook "The Visualization Toolkit" ISBN 013199837-4 published by Prentice Hall which is covered by its own copyright. The authors hereby grant permission to use, copy, and distribute this software and its documentation for any purpose, provided that existing copyright notices are retained in all copies and that this notice is included verbatim in any distributions. Additionally, the authors grant permission to modify this software and its documentation for any purpose, provided that such modifications are not distributed without the explicit consent of the authors and that existing copyright notices are retained in all copies. Some of the algorithms implemented by this software are patented, observe all applicable patent law. IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF, EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. =========================================================================*/ #include "vtkShepardMethod.hh" #include "vtkMath.hh" // Description: // Construct with sample dimensions=(50,50,50) and so that model bounds are // automatically computed from input. Null value for each unvisited output // point is 0.0. Maximum distance is 0.25. vtkShepardMethod::vtkShepardMethod() { this->MaximumDistance = 0.25; this->ModelBounds[0] = 0.0; this->ModelBounds[1] = 0.0; this->ModelBounds[2] = 0.0; this->ModelBounds[3] = 0.0; this->ModelBounds[4] = 0.0; this->ModelBounds[5] = 0.0; this->SampleDimensions[0] = 50; this->SampleDimensions[1] = 50; this->SampleDimensions[2] = 50; this->NullValue = 0.0; } void vtkShepardMethod::SetModelBounds(float xmin, float xmax, float ymin, float ymax, float zmin, float zmax) { float bounds[6]; bounds[0] = xmin; bounds[1] = xmax; bounds[2] = ymin; bounds[3] = ymax; bounds[4] = zmin; bounds[5] = zmax; this->SetModelBounds(bounds); } // Description: // Compute ModelBounds from input geometry. float vtkShepardMethod::ComputeModelBounds(float origin[3], float ar[3]) { float *bounds, maxDist; int i, adjustBounds=0; // compute model bounds if not set previously if ( this->ModelBounds[0] >= this->ModelBounds[1] || this->ModelBounds[2] >= this->ModelBounds[3] || this->ModelBounds[4] >= this->ModelBounds[5] ) { adjustBounds = 1; bounds = this->Input->GetBounds(); } else { bounds = this->ModelBounds; } for (maxDist=0.0, i=0; i<3; i++) if ( (bounds[2*i+1] - bounds[2*i]) > maxDist ) maxDist = bounds[2*i+1] - bounds[2*i]; maxDist *= this->MaximumDistance; // adjust bounds so model fits strictly inside (only if not set previously) if ( adjustBounds ) { for (i=0; i<3; i++) { this->ModelBounds[2*i] = bounds[2*i] - maxDist; this->ModelBounds[2*i+1] = bounds[2*i+1] + maxDist; } } // Set volume origin and aspect ratio for (i=0; i<3; i++) { origin[i] = this->ModelBounds[2*i]; ar[i] = (this->ModelBounds[2*i+1] - this->ModelBounds[2*i]) / (this->SampleDimensions[i] - 1); } ((vtkStructuredPoints *)this->Output)->SetOrigin(origin); ((vtkStructuredPoints *)this->Output)->SetAspectRatio(ar); return maxDist; } void vtkShepardMethod::Execute() { int ptId, i, j, k; float *px, x[3], s, *sum, ar[3], origin[3]; float maxDistance, distance2, inScalar; vtkScalars *inScalars; vtkFloatScalars *newScalars; int numPts, numNewPts, idx; int min[3], max[3]; int jkFactor; vtkStructuredPoints *output=(vtkStructuredPoints *)this->Output; vtkDebugMacro(<< "Executing Shepard method"); // // Check input // if ( (numPts=this->Input->GetNumberOfPoints()) < 1 ) { vtkErrorMacro(<<"Points must be defined!"); return; } if ( (inScalars = this->Input->GetPointData()->GetScalars()) == NULL ) { vtkErrorMacro(<<"Scalars must be defined!"); return; } // // Allocate // numNewPts = this->SampleDimensions[0] * this->SampleDimensions[1] * this->SampleDimensions[2]; newScalars = new vtkFloatScalars(numNewPts); sum = new float[numNewPts]; for (i=0; i<numNewPts; i++) { newScalars->SetScalar(i,0.0); sum[i] = 0.0; } output->SetDimensions(this->GetSampleDimensions()); maxDistance = this->ComputeModelBounds(origin,ar); // // Traverse all input points. Each input point affects voxels within maxDistance. // for (ptId=0; ptId < numPts; ptId++) { px = this->Input->GetPoint(ptId); inScalar = inScalars->GetScalar(ptId); for (i=0; i<3; i++) //compute dimensional bounds in data set { min[i] = (int) ((float)((px[i] - maxDistance) - origin[i]) / ar[i]); max[i] = (int) ((float)((px[i] + maxDistance) - origin[i]) / ar[i]); if (min[i] < 0) min[i] = 0; if (max[i] >= this->SampleDimensions[i]) max[i] = this->SampleDimensions[i] - 1; } jkFactor = this->SampleDimensions[0]*this->SampleDimensions[1]; for (k = min[2]; k <= max[2]; k++) { x[2] = ar[2] * k + origin[2]; for (j = min[1]; j <= max[1]; j++) { x[1] = ar[1] * j + origin[1]; for (i = min[0]; i <= max[0]; i++) { x[0] = ar[0] * i + origin[0]; idx = jkFactor*k + this->SampleDimensions[0]*j + i; distance2 = vtkMath::Distance2BetweenPoints(x,px); if ( distance2 == 0.0 ) { sum[idx] = VTK_LARGE_FLOAT; newScalars->SetScalar(idx,VTK_LARGE_FLOAT); } else { s = newScalars->GetScalar(idx); sum[idx] += 1.0 / distance2; newScalars->SetScalar(idx,s+(inScalar/distance2)); } } } } } // // Run through scalars and compute final values // for (ptId=0; ptId<numNewPts; ptId++) { s = newScalars->GetScalar(ptId); if ( sum[ptId] != 0.0 ) newScalars->SetScalar(ptId,s/sum[ptId]); else newScalars->SetScalar(ptId,this->NullValue); } // // Update self // delete [] sum; output->GetPointData()->SetScalars(newScalars); newScalars->Delete(); } // Description: // Set the i-j-k dimensions on which to sample the distance function. void vtkShepardMethod::SetSampleDimensions(int i, int j, int k) { int dim[3]; dim[0] = i; dim[1] = j; dim[2] = k; this->SetSampleDimensions(dim); } // Description: // Set the i-j-k dimensions on which to sample the distance function. void vtkShepardMethod::SetSampleDimensions(int dim[3]) { int dataDim, i; vtkDebugMacro(<< " setting SampleDimensions to (" << dim[0] << "," << dim[1] << "," << dim[2] << ")"); if ( dim[0] != this->SampleDimensions[0] || dim[1] != SampleDimensions[1] || dim[2] != SampleDimensions[2] ) { if ( dim[0]<1 || dim[1]<1 || dim[2]<1 ) { vtkErrorMacro (<< "Bad Sample Dimensions, retaining previous values"); return; } for (dataDim=0, i=0; i<3 ; i++) if (dim[i] > 1) dataDim++; if ( dataDim < 3 ) { vtkErrorMacro(<<"Sample dimensions must define a volume!"); return; } for ( i=0; i<3; i++) this->SampleDimensions[i] = dim[i]; this->Modified(); } } void vtkShepardMethod::PrintSelf(ostream& os, vtkIndent indent) { vtkDataSetFilter::PrintSelf(os,indent); os << indent << "Maximum Distance: " << this->MaximumDistance << "\n"; os << indent << "Sample Dimensions: (" << this->SampleDimensions[0] << ", " << this->SampleDimensions[1] << ", " << this->SampleDimensions[2] << ")\n"; os << indent << "ModelBounds: \n"; os << indent << " Xmin,Xmax: (" << this->ModelBounds[0] << ", " << this->ModelBounds[1] << ")\n"; os << indent << " Ymin,Ymax: (" << this->ModelBounds[2] << ", " << this->ModelBounds[3] << ")\n"; os << indent << " Zmin,Zmax: (" << this->ModelBounds[4] << ", " << this->ModelBounds[5] << ")\n"; os << indent << "Null Value: " << this->NullValue << "\n"; } <|endoftext|>
<commit_before>// __BEGIN_LICENSE__ // Copyright (C) 2006-2009 United States Government as represented by // the Administrator of the National Aeronautics and Space Administration. // All Rights Reserved. // __END_LICENSE__ #include <fstream> #include <vw/config.h> #include <vw/Core/Thread.h> #include <vw/Core/Cache.h> #include <vw/Core/Settings.h> #include <vw/Core/ConfigParser.h> // Boost headers #include <boost/bind.hpp> #include <boost/thread/xtime.hpp> // C Standard Library headers ( for stat(2) and getpwuid() ) #include <sys/types.h> #include <sys/stat.h> #include <ctime> #include <vw/config.h> #ifdef VW_HAVE_UNISTD_H #include <unistd.h> #endif #ifdef VW_HAVE_PWD_H #include <pwd.h> #endif #ifdef WIN32 #define stat _stat typedef struct _stat struct_stat; #else typedef struct stat struct_stat; #endif namespace { // --------------------------------------------------- // Create a single instance of the Settings class // --------------------------------------------------- vw::RunOnce settings_once = VW_RUNONCE_INIT; boost::shared_ptr<vw::Settings> system_settings_ptr; void init_system_settings() { system_settings_ptr = boost::shared_ptr<vw::Settings>(new vw::Settings()); } } // --------------------------------------------------- // Settings Methods // --------------------------------------------------- // Every m_rc_poll_period seconds, this method polls the // m_rc_filename to see if it exists and to see if it has been // recently modified. If so, we reload the log ruleset from the file. void vw::Settings::reload_config() { #if VW_ENABLE_CONFIG_FILE // We CANNOT use the vw log infrastructure here, because it will // call reload_config and deadlock! boost::xtime xt; boost::xtime_get(&xt, boost::TIME_UTC); bool needs_reloading = false; // Every five seconds, we attempt to open the log config file to see // if there have been any changes. The mutex locking for querying // the time is handled separately from reading the file so that only // one thread takes the performance hit of reading the rc file // during any given reload. { Mutex::Lock time_lock(m_rc_time_mutex); if (xt.sec - m_rc_last_polltime > m_rc_poll_period) { m_rc_last_polltime = xt.sec; needs_reloading = true; } } if (needs_reloading) { Mutex::Lock lock(m_rc_file_mutex); // Check to see if the file has changed. If so, re-read the settings. struct_stat statbuf; if (stat(m_rc_filename.c_str(), &statbuf) != 0) return; #ifdef __APPLE__ time_t mtime = statbuf.st_mtimespec.tv_sec; #else // Linux / Windows time_t mtime = statbuf.st_mtime; #endif if (mtime > m_rc_last_modification) { m_rc_last_modification = mtime; // if it throws, let it bubble up. parse_config_file(m_rc_filename.c_str(), *this); } } #endif } void vw::Settings::set_rc_filename(std::string filename) { // limit the scope of the lock { // we grab both locks in the same order that reload_config does. Mutex::Lock time_lock(m_rc_time_mutex); Mutex::Lock file_lock(m_rc_file_mutex); if (filename != m_rc_filename) { m_rc_last_polltime = 0; m_rc_last_modification = 0; m_rc_filename = filename; } } // Okay, we might have changed the filename. Call reload_config() in order to // re-read it. It will grab time_lock and file_lock, so we need to make sure // we've released them before we re-read it (or we deadlock). reload_config(); } void vw::Settings::set_rc_poll_period(double period) { // limit the scope of the lock { // we only need the time lock here Mutex::Lock time_lock(m_rc_time_mutex); m_rc_poll_period = period; m_rc_last_polltime = 0; } reload_config(); } vw::Settings::Settings() : m_rc_last_polltime(0), m_rc_last_modification(0), m_rc_poll_period(5.0) { std::string homedir; #ifdef VW_HAVE_GETPWUID struct passwd *pw; pw = getpwuid( getuid() ); homedir = pw->pw_dir; #endif if (homedir.empty()) homedir = getenv("HOME"); m_rc_filename = homedir + "/.vwrc"; // Set defaults m_default_num_threads = VW_NUM_THREADS; m_system_cache_size = 1024 * 1024 * 1024; // Default cache size is 1024-MB m_default_tile_size = 1024; // By default, the .vwrc file has precedence, but the user can // override these settings by explicitly changing them using the // system_settings() API. m_default_num_threads_override = false; m_system_cache_size_override = false; m_default_tile_size_override = false; } vw::Settings& vw::vw_settings() { settings_once.run( init_system_settings ); return *system_settings_ptr; } // ----------------------------------------------------------------- // Settings API // ----------------------------------------------------------------- int vw::Settings::default_num_threads() { if (!m_default_num_threads_override) reload_config(); Mutex::Lock lock(m_settings_mutex); return m_default_num_threads; } void vw::Settings::set_default_num_threads(unsigned num) { { // Used to contain the lock from reload_config() Mutex::Lock lock(m_settings_mutex); if ( num == 0 ) { // Reset state m_default_num_threads_override = false; } else { m_default_num_threads_override = true; m_default_num_threads = num; } } if ( num == 0 ) reload_config(); } size_t vw::Settings::system_cache_size() { if (!m_system_cache_size_override) reload_config(); Mutex::Lock lock(m_settings_mutex); return m_system_cache_size; } void vw::Settings::set_system_cache_size(size_t size) { { Mutex::Lock lock(m_settings_mutex); m_system_cache_size_override = true; m_system_cache_size = size; } vw_system_cache().resize(size); } int vw::Settings::default_tile_size() { if (!m_default_tile_size) reload_config(); Mutex::Lock lock(m_settings_mutex); return m_default_tile_size; } void vw::Settings::set_default_tile_size(int num) { Mutex::Lock lock(m_settings_mutex); m_default_tile_size_override = true; m_default_tile_size = num; } <commit_msg>make it possible to disable config file at runtime<commit_after>// __BEGIN_LICENSE__ // Copyright (C) 2006-2009 United States Government as represented by // the Administrator of the National Aeronautics and Space Administration. // All Rights Reserved. // __END_LICENSE__ #include <fstream> #include <vw/config.h> #include <vw/Core/Thread.h> #include <vw/Core/Cache.h> #include <vw/Core/Settings.h> #include <vw/Core/ConfigParser.h> // Boost headers #include <boost/bind.hpp> #include <boost/thread/xtime.hpp> // C Standard Library headers ( for stat(2) and getpwuid() ) #include <sys/types.h> #include <sys/stat.h> #include <ctime> #include <vw/config.h> #ifdef VW_HAVE_UNISTD_H #include <unistd.h> #endif #ifdef VW_HAVE_PWD_H #include <pwd.h> #endif #ifdef WIN32 #define stat _stat typedef struct _stat struct_stat; #else typedef struct stat struct_stat; #endif namespace { // --------------------------------------------------- // Create a single instance of the Settings class // --------------------------------------------------- vw::RunOnce settings_once = VW_RUNONCE_INIT; boost::shared_ptr<vw::Settings> system_settings_ptr; void init_system_settings() { system_settings_ptr = boost::shared_ptr<vw::Settings>(new vw::Settings()); } } // --------------------------------------------------- // Settings Methods // --------------------------------------------------- // Every m_rc_poll_period seconds, this method polls the // m_rc_filename to see if it exists and to see if it has been // recently modified. If so, we reload the log ruleset from the file. void vw::Settings::reload_config() { #if VW_ENABLE_CONFIG_FILE // We CANNOT use the vw log infrastructure here, because it will // call reload_config and deadlock! boost::xtime xt; boost::xtime_get(&xt, boost::TIME_UTC); bool needs_reloading = false; // Every five seconds, we attempt to open the log config file to see // if there have been any changes. The mutex locking for querying // the time is handled separately from reading the file so that only // one thread takes the performance hit of reading the rc file // during any given reload. { Mutex::Lock time_lock(m_rc_time_mutex); if (xt.sec - m_rc_last_polltime > m_rc_poll_period) { m_rc_last_polltime = xt.sec; needs_reloading = true; } } if (needs_reloading) { Mutex::Lock lock(m_rc_file_mutex); // Check to see if the file has changed. If so, re-read the settings. struct_stat statbuf; if (stat(m_rc_filename.c_str(), &statbuf) != 0) return; #ifdef __APPLE__ time_t mtime = statbuf.st_mtimespec.tv_sec; #else // Linux / Windows time_t mtime = statbuf.st_mtime; #endif if (mtime > m_rc_last_modification) { m_rc_last_modification = mtime; // if it throws, let it bubble up. parse_config_file(m_rc_filename.c_str(), *this); } } #endif } void vw::Settings::set_rc_filename(std::string filename) { // limit the scope of the lock { // we grab both locks in the same order that reload_config does. Mutex::Lock time_lock(m_rc_time_mutex); Mutex::Lock file_lock(m_rc_file_mutex); if (filename != m_rc_filename) { if (filename.empty()) { // Set the last poll time and the last modification time to the death // of the universe. This is a little bit of a hack, but it lets us // disable the config file without making the locking in // reload_config() even more complex. m_rc_last_polltime = std::numeric_limits<long>::max(); m_rc_last_modification = std::numeric_limits<long>::max(); } else { m_rc_last_polltime = 0; m_rc_last_modification = 0; } m_rc_filename = filename; } } // Okay, we might have changed the filename. Call reload_config() in order to // re-read it. It will grab time_lock and file_lock, so we need to make sure // we've released them before we re-read it (or we deadlock). reload_config(); } void vw::Settings::set_rc_poll_period(double period) { // limit the scope of the lock { // we only need the time lock here Mutex::Lock time_lock(m_rc_time_mutex); m_rc_poll_period = period; m_rc_last_polltime = 0; } reload_config(); } vw::Settings::Settings() : m_rc_last_polltime(0), m_rc_last_modification(0), m_rc_poll_period(5.0) { std::string homedir; #ifdef VW_HAVE_GETPWUID struct passwd *pw; pw = getpwuid( getuid() ); homedir = pw->pw_dir; #endif if (homedir.empty()) homedir = getenv("HOME"); m_rc_filename = homedir + "/.vwrc"; // Set defaults m_default_num_threads = VW_NUM_THREADS; m_system_cache_size = 1024 * 1024 * 1024; // Default cache size is 1024-MB m_default_tile_size = 1024; // By default, the .vwrc file has precedence, but the user can // override these settings by explicitly changing them using the // system_settings() API. m_default_num_threads_override = false; m_system_cache_size_override = false; m_default_tile_size_override = false; } vw::Settings& vw::vw_settings() { settings_once.run( init_system_settings ); return *system_settings_ptr; } // ----------------------------------------------------------------- // Settings API // ----------------------------------------------------------------- int vw::Settings::default_num_threads() { if (!m_default_num_threads_override) reload_config(); Mutex::Lock lock(m_settings_mutex); return m_default_num_threads; } void vw::Settings::set_default_num_threads(unsigned num) { { // Used to contain the lock from reload_config() Mutex::Lock lock(m_settings_mutex); if ( num == 0 ) { // Reset state m_default_num_threads_override = false; } else { m_default_num_threads_override = true; m_default_num_threads = num; } } if ( num == 0 ) reload_config(); } size_t vw::Settings::system_cache_size() { if (!m_system_cache_size_override) reload_config(); Mutex::Lock lock(m_settings_mutex); return m_system_cache_size; } void vw::Settings::set_system_cache_size(size_t size) { { Mutex::Lock lock(m_settings_mutex); m_system_cache_size_override = true; m_system_cache_size = size; } vw_system_cache().resize(size); } int vw::Settings::default_tile_size() { if (!m_default_tile_size) reload_config(); Mutex::Lock lock(m_settings_mutex); return m_default_tile_size; } void vw::Settings::set_default_tile_size(int num) { Mutex::Lock lock(m_settings_mutex); m_default_tile_size_override = true; m_default_tile_size = num; } <|endoftext|>
<commit_before>#include <boost/asio.hpp> #include <boost/thread.hpp> #include <boost/lexical_cast.hpp> #include "client.h" #include <libwatcher/testMessage.h> #include "initConfig.h" #include "singletonConfig.h" using namespace std; using namespace watcher; using namespace watcher::event; using namespace boost; using namespace libconfig; int main(int argc, char **argv) { TRACE_ENTER(); string configFilename; Config &config=SingletonConfig::instance(); SingletonConfig::lock(); if (false==initConfig(config, argc, argv, configFilename)) { cerr << "Error reading configuration file, unable to continue." << endl; cerr << "Usage: " << basename(argv[0]) << " [-c|--configFile] configfile" << endl; return 1; } SingletonConfig::unlock(); string logConf("testCC.log.properties"); if (!config.lookupValue("logPropertiesFile", logConf)) { cout << "Unable to find logPropertiesFile setting in the configuration file, using default: " << logConf << " and adding it to the configuration file." << endl; config.getRoot().add("logPropertiesFile", libconfig::Setting::TypeString)=logConf; } LOAD_LOG_PROPS(logConf); LOG_INFO("Logger initialized from file \"" << logConf << "\""); int loopCount=1; if (!config.lookupValue("loopCount", loopCount)) { LOG_INFO("'loopCount' not found in the configuration file, using default: " << loopCount << " and adding this to the configuration file."); config.getRoot().add("loopCount", libconfig::Setting::TypeInt)=loopCount; } string serverName("glory"); if (!config.lookupValue("serverName", serverName)) { LOG_INFO("'serverName' not found in the configuration file, using default: " << serverName << " and adding this to the configuration file."); config.getRoot().add("serverName", libconfig::Setting::TypeString)=serverName; } try { asio::io_service ioserv; Client c(serverName); // ClientConnection c(ioserv, serverName, "watcherd"); vector<int> ints; string strVal = "from testCC"; for (int i = 0; i < loopCount; i++) { if(i<100) { ints.push_back(i+1); ints.push_back((i+1)*2); } LOG_INFO("Sending message number " << i); c.sendMessage(shared_ptr<TestMessage>(new TestMessage(strVal, ints))); } vector<MessagePtr> messages; for (int i = 0; i < loopCount; i++) { ints.push_back(i+1); ints.push_back((i+1)*2); MessagePtr m=MessagePtr(new TestMessage(strVal, ints)); messages.push_back(m); } c.sendMessages(messages); // ioserv.run(); // sleep(60); // c.close(); // t.join(); } catch (std::exception &e) { cerr << "Caught exception: " << e.what() << endl; } // Save any configuration changes made during the run. LOG_INFO("Saving last known configuration to " << configFilename); SingletonConfig::lock(); config.writeFile(configFilename.c_str()); return 0; } <commit_msg>wait for all messages to be sent before exiting.<commit_after>#include <boost/asio.hpp> #include <boost/thread.hpp> #include <boost/lexical_cast.hpp> #include "client.h" #include <libwatcher/testMessage.h> #include "initConfig.h" #include "singletonConfig.h" using namespace std; using namespace watcher; using namespace watcher::event; using namespace boost; using namespace libconfig; int main(int argc, char **argv) { TRACE_ENTER(); string configFilename; Config &config=SingletonConfig::instance(); SingletonConfig::lock(); if (false==initConfig(config, argc, argv, configFilename)) { cerr << "Error reading configuration file, unable to continue." << endl; cerr << "Usage: " << basename(argv[0]) << " [-c|--configFile] configfile" << endl; return 1; } SingletonConfig::unlock(); string logConf("testCC.log.properties"); if (!config.lookupValue("logPropertiesFile", logConf)) { cout << "Unable to find logPropertiesFile setting in the configuration file, using default: " << logConf << " and adding it to the configuration file." << endl; config.getRoot().add("logPropertiesFile", libconfig::Setting::TypeString)=logConf; } LOAD_LOG_PROPS(logConf); LOG_INFO("Logger initialized from file \"" << logConf << "\""); int loopCount=1; if (!config.lookupValue("loopCount", loopCount)) { LOG_INFO("'loopCount' not found in the configuration file, using default: " << loopCount << " and adding this to the configuration file."); config.getRoot().add("loopCount", libconfig::Setting::TypeInt)=loopCount; } string serverName("glory"); if (!config.lookupValue("serverName", serverName)) { LOG_INFO("'serverName' not found in the configuration file, using default: " << serverName << " and adding this to the configuration file."); config.getRoot().add("serverName", libconfig::Setting::TypeString)=serverName; } try { asio::io_service ioserv; Client c(serverName); vector<int> ints; string strVal = "from testCC"; for (int i = 0; i < loopCount; i++) { if(i<100) { ints.push_back(i+1); ints.push_back((i+1)*2); } LOG_INFO("Sending message number " << i); c.sendMessage(shared_ptr<TestMessage>(new TestMessage(strVal, ints))); } // vector<MessagePtr> messages; // for (int i = 0; i < loopCount; i++) // { // if(i<100) // { // ints.push_back(i+1); // ints.push_back((i+1)*2); // } // MessagePtr m=MessagePtr(new TestMessage(strVal, ints)); // messages.push_back(m); // } // c.sendMessages(messages); c.wait(); } catch (std::exception &e) { cerr << "Caught exception: " << e.what() << endl; } // Save any configuration changes made during the run. LOG_INFO("Saving last known configuration to " << configFilename); SingletonConfig::lock(); config.writeFile(configFilename.c_str()); return 0; } <|endoftext|>
<commit_before>#include <boost/asio.hpp> #include <boost/thread.hpp> #include <boost/lexical_cast.hpp> #include "client.h" #include <libwatcher/testMessage.h> #include "initConfig.h" #include "singletonConfig.h" using namespace std; using namespace watcher; using namespace watcher::event; using namespace boost; using namespace libconfig; int main(int argc, char **argv) { TRACE_ENTER(); string configFilename; Config &config=SingletonConfig::instance(); SingletonConfig::lock(); if (false==initConfig(config, argc, argv, configFilename)) { cerr << "Error reading configuration file, unable to continue." << endl; cerr << "Usage: " << basename(argv[0]) << " [-c|--configFile] configfile" << endl; return 1; } SingletonConfig::unlock(); string logConf("testCC.log.properties"); if (!config.lookupValue("logPropertiesFile", logConf)) { cout << "Unable to find logPropertiesFile setting in the configuration file, using default: " << logConf << " and adding it to the configuration file." << endl; config.getRoot().add("logPropertiesFile", libconfig::Setting::TypeString)=logConf; } LOAD_LOG_PROPS(logConf); LOG_INFO("Logger initialized from file \"" << logConf << "\""); int loopCount=1; if (!config.lookupValue("loopCount", loopCount)) { LOG_INFO("'loopCount' not found in the configuration file, using default: " << loopCount << " and adding this to the configuration file."); config.getRoot().add("loopCount", libconfig::Setting::TypeInt)=loopCount; } string serverName("glory"); if (!config.lookupValue("serverName", serverName)) { LOG_INFO("'serverName' not found in the configuration file, using default: " << serverName << " and adding this to the configuration file."); config.getRoot().add("serverName", libconfig::Setting::TypeString)=serverName; } try { asio::io_service ioserv; Client c(serverName); vector<int> ints; string strVal = "from testCC"; for (int i = 0; i < loopCount; i++) { if(i<100) { ints.push_back(i+1); ints.push_back((i+1)*2); } LOG_INFO("Sending message number " << i); c.sendMessage(shared_ptr<TestMessage>(new TestMessage(strVal, ints))); } // vector<MessagePtr> messages; // for (int i = 0; i < loopCount; i++) // { // if(i<100) // { // ints.push_back(i+1); // ints.push_back((i+1)*2); // } // MessagePtr m=MessagePtr(new TestMessage(strVal, ints)); // messages.push_back(m); // } // c.sendMessages(messages); c.wait(); } catch (std::exception &e) { cerr << "Caught exception: " << e.what() << endl; } // Save any configuration changes made during the run. LOG_INFO("Saving last known configuration to " << configFilename); SingletonConfig::lock(); config.writeFile(configFilename.c_str()); return 0; } <commit_msg>new commment added<commit_after>#include <boost/asio.hpp> #include <boost/thread.hpp> #include <boost/lexical_cast.hpp> #include "client.h" #include <libwatcher/testMessage.h> #include "initConfig.h" #include "singletonConfig.h" using namespace std; using namespace watcher; using namespace watcher::event; using namespace boost; using namespace libconfig; int main(int argc, char **argv) { TRACE_ENTER(); string configFilename; Config &config=SingletonConfig::instance(); SingletonConfig::lock(); if (false==initConfig(config, argc, argv, configFilename)) { cerr << "Error reading configuration file, unable to continue." << endl; cerr << "Usage: " << basename(argv[0]) << " [-c|--configFile] configfile" << endl; return 1; } SingletonConfig::unlock(); string logConf("testCC.log.properties"); if (!config.lookupValue("logPropertiesFile", logConf)) { cout << "Unable to find logPropertiesFile setting in the configuration file, using default: " << logConf << " and adding it to the configuration file." << endl; config.getRoot().add("logPropertiesFile", libconfig::Setting::TypeString)=logConf; } LOAD_LOG_PROPS(logConf); LOG_INFO("Logger initialized from file \"" << logConf << "\""); int loopCount=1; if (!config.lookupValue("loopCount", loopCount)) { LOG_INFO("'loopCount' not found in the configuration file, using default: " << loopCount << " and adding this to the configuration file."); config.getRoot().add("loopCount", libconfig::Setting::TypeInt)=loopCount; } string serverName("glory"); if (!config.lookupValue("serverName", serverName)) { LOG_INFO("'serverName' not found in the configuration file, using default: " << serverName << " and adding this to the configuration file."); config.getRoot().add("serverName", libconfig::Setting::TypeString)=serverName; } try { asio::io_service ioserv; Client c(serverName); vector<int> ints; string strVal = "from testCC"; for (int i = 0; i < loopCount; i++) { if(i<100) { ints.push_back(i+1); ints.push_back((i+1)*2); } LOG_INFO("Sending message number " << i); c.sendMessage(shared_ptr<TestMessage>(new TestMessage(strVal, ints))); } // This will quickly break things as the packet gets to be too large. // vector<MessagePtr> messages; // for (int i = 0; i < loopCount; i++) // { // if(i<100) // { // ints.push_back(i+1); // ints.push_back((i+1)*2); // } // MessagePtr m=MessagePtr(new TestMessage(strVal, ints)); // messages.push_back(m); // } // c.sendMessages(messages); c.wait(); } catch (std::exception &e) { cerr << "Caught exception: " << e.what() << endl; } // Save any configuration changes made during the run. LOG_INFO("Saving last known configuration to " << configFilename); SingletonConfig::lock(); config.writeFile(configFilename.c_str()); return 0; } <|endoftext|>
<commit_before>/* * Copyright 2007-2019 Content Management AG * All rights reserved. * * author: Max Kellermann <mk@cm4all.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. * * 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 * FOUNDATION 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 "Registry.hxx" #include "Class.hxx" #include "translation/Service.hxx" #include "translation/Handler.hxx" #include "translation/Request.hxx" #include "translation/Response.hxx" #include "translation/Transformation.hxx" #include "AllocatorPtr.hxx" #include "io/Logger.hxx" #include "util/Exception.hxx" #include "stopwatch.hxx" static void widget_registry_lookup(struct pool &caller_pool, struct pool &widget_pool, TranslationService &service, const char *widget_type, TranslateHandler &handler, CancellablePointer &cancel_ptr) noexcept { auto request = NewFromPool<TranslateRequest>(caller_pool); request->widget_type = widget_type; service.SendRequest(widget_pool, *request, nullptr, // TODO handler, cancel_ptr); } struct WidgetRegistryLookup final : TranslateHandler { struct pool &widget_pool; WidgetClassCache &cache; const char *const name; const WidgetRegistryCallback callback; WidgetRegistryLookup(struct pool &_widget_pool, WidgetClassCache &_cache, const char *_name, WidgetRegistryCallback _callback) noexcept :widget_pool(_widget_pool), cache(_cache), name(_name), callback(_callback) {} /* virtual methods from TranslateHandler */ void OnTranslateResponse(TranslateResponse &response) noexcept override; void OnTranslateError(std::exception_ptr error) noexcept override; }; void WidgetRegistryLookup::OnTranslateResponse(TranslateResponse &response) noexcept { assert(response.views != nullptr); if (response.status != 0) { callback(nullptr); return; } auto cls = NewFromPool<WidgetClass>(widget_pool); cls->local_uri = response.local_uri; cls->untrusted_host = response.untrusted; cls->untrusted_prefix = response.untrusted_prefix; cls->untrusted_site_suffix = response.untrusted_site_suffix; cls->untrusted_raw_site_suffix = response.untrusted_raw_site_suffix; if (cls->untrusted_host == nullptr) /* compatibility with v0.7.16 */ cls->untrusted_host = response.host; cls->cookie_host = response.cookie_host; cls->group = response.widget_group; cls->container_groups = std::move(response.container_groups); cls->direct_addressing = response.direct_addressing; cls->stateful = response.stateful; cls->require_csrf_token = response.require_csrf_token; cls->anchor_absolute = response.anchor_absolute; cls->info_headers = response.widget_info; cls->dump_headers = response.dump_headers; cls->views.CopyChainFrom(widget_pool, *response.views); cache.Put(name, *cls); callback(cls); } void WidgetRegistryLookup::OnTranslateError(std::exception_ptr ep) noexcept { LogConcat(2, "WidgetRegistry", ep); callback(nullptr); } void WidgetRegistry::LookupWidgetClass(struct pool &caller_pool, struct pool &widget_pool, const char *widget_type, WidgetRegistryCallback callback, CancellablePointer &cancel_ptr) noexcept { assert(widget_type != nullptr); const auto *cls = cache.Get(widget_type); if (cls != nullptr) { callback(NewFromPool<WidgetClass>(widget_pool, widget_pool, *cls)); return; } auto lookup = NewFromPool<WidgetRegistryLookup>(caller_pool, widget_pool, cache, widget_type, callback); widget_registry_lookup(caller_pool, widget_pool, translation_service, widget_type, *lookup, cancel_ptr); } <commit_msg>widget/Registry: convert WidgetRegistryLookup to class<commit_after>/* * Copyright 2007-2019 Content Management AG * All rights reserved. * * author: Max Kellermann <mk@cm4all.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. * * 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 * FOUNDATION 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 "Registry.hxx" #include "Class.hxx" #include "translation/Service.hxx" #include "translation/Handler.hxx" #include "translation/Request.hxx" #include "translation/Response.hxx" #include "translation/Transformation.hxx" #include "AllocatorPtr.hxx" #include "io/Logger.hxx" #include "util/Exception.hxx" #include "stopwatch.hxx" static void widget_registry_lookup(struct pool &caller_pool, struct pool &widget_pool, TranslationService &service, const char *widget_type, TranslateHandler &handler, CancellablePointer &cancel_ptr) noexcept { auto request = NewFromPool<TranslateRequest>(caller_pool); request->widget_type = widget_type; service.SendRequest(widget_pool, *request, nullptr, // TODO handler, cancel_ptr); } class WidgetRegistryLookup final : TranslateHandler { struct pool &widget_pool; WidgetClassCache &cache; const char *const name; const WidgetRegistryCallback callback; public: WidgetRegistryLookup(struct pool &_widget_pool, WidgetClassCache &_cache, const char *_name, WidgetRegistryCallback _callback) noexcept :widget_pool(_widget_pool), cache(_cache), name(_name), callback(_callback) {} void Start(struct pool &caller_pool, TranslationService &service, CancellablePointer &cancel_ptr) noexcept { widget_registry_lookup(caller_pool, widget_pool, service, name, *this, cancel_ptr); } private: /* virtual methods from TranslateHandler */ void OnTranslateResponse(TranslateResponse &response) noexcept override; void OnTranslateError(std::exception_ptr error) noexcept override; }; void WidgetRegistryLookup::OnTranslateResponse(TranslateResponse &response) noexcept { assert(response.views != nullptr); if (response.status != 0) { callback(nullptr); return; } auto cls = NewFromPool<WidgetClass>(widget_pool); cls->local_uri = response.local_uri; cls->untrusted_host = response.untrusted; cls->untrusted_prefix = response.untrusted_prefix; cls->untrusted_site_suffix = response.untrusted_site_suffix; cls->untrusted_raw_site_suffix = response.untrusted_raw_site_suffix; if (cls->untrusted_host == nullptr) /* compatibility with v0.7.16 */ cls->untrusted_host = response.host; cls->cookie_host = response.cookie_host; cls->group = response.widget_group; cls->container_groups = std::move(response.container_groups); cls->direct_addressing = response.direct_addressing; cls->stateful = response.stateful; cls->require_csrf_token = response.require_csrf_token; cls->anchor_absolute = response.anchor_absolute; cls->info_headers = response.widget_info; cls->dump_headers = response.dump_headers; cls->views.CopyChainFrom(widget_pool, *response.views); cache.Put(name, *cls); callback(cls); } void WidgetRegistryLookup::OnTranslateError(std::exception_ptr ep) noexcept { LogConcat(2, "WidgetRegistry", ep); callback(nullptr); } void WidgetRegistry::LookupWidgetClass(struct pool &caller_pool, struct pool &widget_pool, const char *widget_type, WidgetRegistryCallback callback, CancellablePointer &cancel_ptr) noexcept { assert(widget_type != nullptr); const auto *cls = cache.Get(widget_type); if (cls != nullptr) { callback(NewFromPool<WidgetClass>(widget_pool, widget_pool, *cls)); return; } auto lookup = NewFromPool<WidgetRegistryLookup>(caller_pool, widget_pool, cache, widget_type, callback); lookup->Start(caller_pool, translation_service, cancel_ptr); } <|endoftext|>
<commit_before>/** @file A brief file description @section license License 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. */ /************************************************************************** Connections Commonality across all platforms -- move out as required. **************************************************************************/ #include "ts/ink_platform.h" #include "P_Net.h" // set in the OS // #define RECV_BUF_SIZE (1024*64) // #define SEND_BUF_SIZE (1024*64) #define FIRST_RANDOM_PORT 16000 #define LAST_RANDOM_PORT 32000 #define ROUNDUP(x, y) ((((x) + ((y)-1)) / (y)) * (y)) #ifndef FD_CLOEXEC #define FD_CLOEXEC 1 #endif int get_listen_backlog(void) { int listen_backlog = 1024; REC_ReadConfigInteger(listen_backlog, "proxy.config.net.listen_backlog"); return listen_backlog; } // // Functions // char const * NetVCOptions::toString(addr_bind_style s) { return ANY_ADDR == s ? "any" : INTF_ADDR == s ? "interface" : "foreign"; } Connection::Connection() : fd(NO_FD), is_bound(false), is_connected(false), sock_type(0) { memset(&addr, 0, sizeof(addr)); } Connection::~Connection() { close(); } int Server::accept(Connection *c) { int res = 0; socklen_t sz = sizeof(c->addr); res = socketManager.accept(fd, &c->addr.sa, &sz); if (res < 0) return res; c->fd = res; if (is_debug_tag_set("iocore_net_server")) { ip_port_text_buffer ipb1, ipb2; Debug("iocore_net_server", "Connection accepted [Server]. %s -> %s\n", ats_ip_nptop(&c->addr, ipb2, sizeof(ipb2)), ats_ip_nptop(&addr, ipb1, sizeof(ipb1))); } #ifdef SET_CLOSE_ON_EXEC if ((res = safe_fcntl(fd, F_SETFD, FD_CLOEXEC)) < 0) goto Lerror; #endif if ((res = safe_nonblocking(c->fd)) < 0) goto Lerror; #ifdef SEND_BUF_SIZE socketManager.set_sndbuf_size(c->fd, SEND_BUF_SIZE); #endif return 0; Lerror: c->close(); return res; } int Connection::close() { is_connected = false; is_bound = false; // don't close any of the standards if (fd >= 2) { int fd_save = fd; fd = NO_FD; return socketManager.close(fd_save); } else { fd = NO_FD; return -EBADF; } } /** * Move control of the socket from the argument object orig to the current object. * Orig is marked as zombie, so when it is freed, the socket will not be closed */ void Connection::move(Connection &orig) { this->is_connected = orig.is_connected; this->is_bound = orig.is_bound; this->fd = orig.fd; // The target has taken ownership of the file descriptor orig.fd = NO_FD; this->addr = orig.addr; this->sock_type = orig.sock_type; } static int add_http_filter(int fd ATS_UNUSED) { int err = -1; #if defined(SOL_FILTER) && defined(FIL_ATTACH) err = setsockopt(fd, SOL_FILTER, FIL_ATTACH, "httpfilt", 9); #endif return err; } int Server::setup_fd_for_listen(bool non_blocking, int recv_bufsize, int send_bufsize, bool transparent) { int res = 0; int sockopt_flag_in = 0; REC_ReadConfigInteger(sockopt_flag_in, "proxy.config.net.sock_option_flag_in"); #ifdef TCP_FASTOPEN int tfo_queue_length = 0; REC_ReadConfigInteger(tfo_queue_length, "proxy.config.net.sock_option_tfo_queue_size_in"); #endif ink_assert(fd != NO_FD); if (http_accept_filter) { add_http_filter(fd); } #ifdef SEND_BUF_SIZE { int send_buf_size = SEND_BUF_SIZE; if ((res = safe_setsockopt(fd, SOL_SOCKET, SO_SNDBUF, (char *)&send_buf_size, sizeof(int)) < 0)) { goto Lerror; } } #endif #ifdef RECV_BUF_SIZE { int recv_buf_size = RECV_BUF_SIZE; if ((res = safe_setsockopt(fd, SOL_SOCKET, SO_RCVBUF, (char *)&recv_buf_size, sizeof(int))) < 0) { goto Lerror; } } #endif if (recv_bufsize) { if (socketManager.set_rcvbuf_size(fd, recv_bufsize)) { // Round down until success int rbufsz = ROUNDUP(recv_bufsize, 1024); while (rbufsz) { if (socketManager.set_rcvbuf_size(fd, rbufsz)) { rbufsz -= 1024; } else { break; } } } } if (send_bufsize) { if (socketManager.set_sndbuf_size(fd, send_bufsize)) { // Round down until success int sbufsz = ROUNDUP(send_bufsize, 1024); while (sbufsz) { if (socketManager.set_sndbuf_size(fd, sbufsz)) { sbufsz -= 1024; } else { break; } } } } #ifdef SET_CLOSE_ON_EXEC if ((res = safe_fcntl(fd, F_SETFD, FD_CLOEXEC)) < 0) { goto Lerror; } #endif { struct linger l; l.l_onoff = 0; l.l_linger = 0; if ((sockopt_flag_in & NetVCOptions::SOCK_OPT_LINGER_ON) && (res = safe_setsockopt(fd, SOL_SOCKET, SO_LINGER, (char *)&l, sizeof(l))) < 0) { goto Lerror; } } if (ats_is_ip6(&addr) && (res = safe_setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, SOCKOPT_ON, sizeof(int))) < 0) { goto Lerror; } if ((res = safe_setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, SOCKOPT_ON, sizeof(int))) < 0) { goto Lerror; } if ((sockopt_flag_in & NetVCOptions::SOCK_OPT_NO_DELAY) && (res = safe_setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, SOCKOPT_ON, sizeof(int))) < 0) { goto Lerror; } // enables 2 hour inactivity probes, also may fix IRIX FIN_WAIT_2 leak if ((sockopt_flag_in & NetVCOptions::SOCK_OPT_KEEP_ALIVE) && (res = safe_setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, SOCKOPT_ON, sizeof(int))) < 0) { goto Lerror; } #ifdef TCP_FASTOPEN if ((sockopt_flag_in & NetVCOptions::SOCK_OPT_TCP_FAST_OPEN) && (res = safe_setsockopt(fd, SOL_TCP, TCP_FASTOPEN, (char *)&tfo_queue_length, sizeof(int)))) { goto Lerror; } #endif if (transparent) { #if TS_USE_TPROXY Debug("http_tproxy", "Listen port inbound transparency enabled.\n"); if (safe_setsockopt(fd, SOL_IP, TS_IP_TRANSPARENT, SOCKOPT_ON, sizeof(int)) < 0) { Error("[Server::listen] Unable to set transparent socket option [%d] %s\n", errno, strerror(errno)); _exit(1); } #else Error("[Server::listen] Transparency requested but TPROXY not configured\n"); #endif } #if defined(TCP_MAXSEG) if (NetProcessor::accept_mss > 0) { if ((res = safe_setsockopt(fd, IPPROTO_TCP, TCP_MAXSEG, (char *)&NetProcessor::accept_mss, sizeof(int))) < 0) { goto Lerror; } } #endif if (non_blocking) { if ((res = safe_nonblocking(fd)) < 0) { goto Lerror; } } return 0; Lerror: res = -errno; // coverity[check_after_sink] if (fd != NO_FD) { close(); fd = NO_FD; } return res; } int Server::listen(bool non_blocking, int recv_bufsize, int send_bufsize, bool transparent) { ink_assert(fd == NO_FD); int res = 0; int namelen; if (!ats_is_ip(&accept_addr)) { ats_ip4_set(&addr, INADDR_ANY, 0); } else { ats_ip_copy(&addr, &accept_addr); } fd = res = socketManager.socket(addr.sa.sa_family, SOCK_STREAM, IPPROTO_TCP); if (res < 0) { goto Lerror; } res = setup_fd_for_listen(non_blocking, recv_bufsize, send_bufsize, transparent); if (res < 0) { goto Lerror; } if ((res = socketManager.ink_bind(fd, &addr.sa, ats_ip_size(&addr.sa), IPPROTO_TCP)) < 0) { goto Lerror; } if ((res = safe_listen(fd, get_listen_backlog())) < 0) { goto Lerror; } // Original just did this on port == 0. namelen = sizeof(addr); if ((res = safe_getsockname(fd, &addr.sa, &namelen))) { goto Lerror; } return 0; Lerror: if (fd != NO_FD) { close(); fd = NO_FD; } Error("Could not bind or listen to port %d (error: %d)", ats_ip_port_host_order(&addr), res); return res; } <commit_msg>TS-2520: fix OS X build<commit_after>/** @file A brief file description @section license License 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. */ /************************************************************************** Connections Commonality across all platforms -- move out as required. **************************************************************************/ #include "ts/ink_platform.h" #include "P_Net.h" // set in the OS // #define RECV_BUF_SIZE (1024*64) // #define SEND_BUF_SIZE (1024*64) #define FIRST_RANDOM_PORT 16000 #define LAST_RANDOM_PORT 32000 #define ROUNDUP(x, y) ((((x) + ((y)-1)) / (y)) * (y)) #ifndef FD_CLOEXEC #define FD_CLOEXEC 1 #endif int get_listen_backlog(void) { int listen_backlog = 1024; REC_ReadConfigInteger(listen_backlog, "proxy.config.net.listen_backlog"); return listen_backlog; } // // Functions // char const * NetVCOptions::toString(addr_bind_style s) { return ANY_ADDR == s ? "any" : INTF_ADDR == s ? "interface" : "foreign"; } Connection::Connection() : fd(NO_FD), is_bound(false), is_connected(false), sock_type(0) { memset(&addr, 0, sizeof(addr)); } Connection::~Connection() { close(); } int Server::accept(Connection *c) { int res = 0; socklen_t sz = sizeof(c->addr); res = socketManager.accept(fd, &c->addr.sa, &sz); if (res < 0) return res; c->fd = res; if (is_debug_tag_set("iocore_net_server")) { ip_port_text_buffer ipb1, ipb2; Debug("iocore_net_server", "Connection accepted [Server]. %s -> %s\n", ats_ip_nptop(&c->addr, ipb2, sizeof(ipb2)), ats_ip_nptop(&addr, ipb1, sizeof(ipb1))); } #ifdef SET_CLOSE_ON_EXEC if ((res = safe_fcntl(fd, F_SETFD, FD_CLOEXEC)) < 0) goto Lerror; #endif if ((res = safe_nonblocking(c->fd)) < 0) goto Lerror; #ifdef SEND_BUF_SIZE socketManager.set_sndbuf_size(c->fd, SEND_BUF_SIZE); #endif return 0; Lerror: c->close(); return res; } int Connection::close() { is_connected = false; is_bound = false; // don't close any of the standards if (fd >= 2) { int fd_save = fd; fd = NO_FD; return socketManager.close(fd_save); } else { fd = NO_FD; return -EBADF; } } /** * Move control of the socket from the argument object orig to the current object. * Orig is marked as zombie, so when it is freed, the socket will not be closed */ void Connection::move(Connection &orig) { this->is_connected = orig.is_connected; this->is_bound = orig.is_bound; this->fd = orig.fd; // The target has taken ownership of the file descriptor orig.fd = NO_FD; this->addr = orig.addr; this->sock_type = orig.sock_type; } static int add_http_filter(int fd ATS_UNUSED) { int err = -1; #if defined(SOL_FILTER) && defined(FIL_ATTACH) err = setsockopt(fd, SOL_FILTER, FIL_ATTACH, "httpfilt", 9); #endif return err; } int Server::setup_fd_for_listen(bool non_blocking, int recv_bufsize, int send_bufsize, bool transparent) { int res = 0; int sockopt_flag_in = 0; REC_ReadConfigInteger(sockopt_flag_in, "proxy.config.net.sock_option_flag_in"); #ifdef TCP_FASTOPEN int tfo_queue_length = 0; REC_ReadConfigInteger(tfo_queue_length, "proxy.config.net.sock_option_tfo_queue_size_in"); #endif ink_assert(fd != NO_FD); if (http_accept_filter) { add_http_filter(fd); } #ifdef SEND_BUF_SIZE { int send_buf_size = SEND_BUF_SIZE; if ((res = safe_setsockopt(fd, SOL_SOCKET, SO_SNDBUF, (char *)&send_buf_size, sizeof(int)) < 0)) { goto Lerror; } } #endif #ifdef RECV_BUF_SIZE { int recv_buf_size = RECV_BUF_SIZE; if ((res = safe_setsockopt(fd, SOL_SOCKET, SO_RCVBUF, (char *)&recv_buf_size, sizeof(int))) < 0) { goto Lerror; } } #endif if (recv_bufsize) { if (socketManager.set_rcvbuf_size(fd, recv_bufsize)) { // Round down until success int rbufsz = ROUNDUP(recv_bufsize, 1024); while (rbufsz) { if (socketManager.set_rcvbuf_size(fd, rbufsz)) { rbufsz -= 1024; } else { break; } } } } if (send_bufsize) { if (socketManager.set_sndbuf_size(fd, send_bufsize)) { // Round down until success int sbufsz = ROUNDUP(send_bufsize, 1024); while (sbufsz) { if (socketManager.set_sndbuf_size(fd, sbufsz)) { sbufsz -= 1024; } else { break; } } } } #ifdef SET_CLOSE_ON_EXEC if ((res = safe_fcntl(fd, F_SETFD, FD_CLOEXEC)) < 0) { goto Lerror; } #endif { struct linger l; l.l_onoff = 0; l.l_linger = 0; if ((sockopt_flag_in & NetVCOptions::SOCK_OPT_LINGER_ON) && (res = safe_setsockopt(fd, SOL_SOCKET, SO_LINGER, (char *)&l, sizeof(l))) < 0) { goto Lerror; } } if (ats_is_ip6(&addr) && (res = safe_setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, SOCKOPT_ON, sizeof(int))) < 0) { goto Lerror; } if ((res = safe_setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, SOCKOPT_ON, sizeof(int))) < 0) { goto Lerror; } if ((sockopt_flag_in & NetVCOptions::SOCK_OPT_NO_DELAY) && (res = safe_setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, SOCKOPT_ON, sizeof(int))) < 0) { goto Lerror; } // enables 2 hour inactivity probes, also may fix IRIX FIN_WAIT_2 leak if ((sockopt_flag_in & NetVCOptions::SOCK_OPT_KEEP_ALIVE) && (res = safe_setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, SOCKOPT_ON, sizeof(int))) < 0) { goto Lerror; } #ifdef TCP_FASTOPEN if ((sockopt_flag_in & NetVCOptions::SOCK_OPT_TCP_FAST_OPEN) && (res = safe_setsockopt(fd, IPPROTO_TCP, TCP_FASTOPEN, (char *)&tfo_queue_length, sizeof(int)))) { goto Lerror; } #endif if (transparent) { #if TS_USE_TPROXY Debug("http_tproxy", "Listen port inbound transparency enabled.\n"); if (safe_setsockopt(fd, SOL_IP, TS_IP_TRANSPARENT, SOCKOPT_ON, sizeof(int)) < 0) { Error("[Server::listen] Unable to set transparent socket option [%d] %s\n", errno, strerror(errno)); _exit(1); } #else Error("[Server::listen] Transparency requested but TPROXY not configured\n"); #endif } #if defined(TCP_MAXSEG) if (NetProcessor::accept_mss > 0) { if ((res = safe_setsockopt(fd, IPPROTO_TCP, TCP_MAXSEG, (char *)&NetProcessor::accept_mss, sizeof(int))) < 0) { goto Lerror; } } #endif if (non_blocking) { if ((res = safe_nonblocking(fd)) < 0) { goto Lerror; } } return 0; Lerror: res = -errno; // coverity[check_after_sink] if (fd != NO_FD) { close(); fd = NO_FD; } return res; } int Server::listen(bool non_blocking, int recv_bufsize, int send_bufsize, bool transparent) { ink_assert(fd == NO_FD); int res = 0; int namelen; if (!ats_is_ip(&accept_addr)) { ats_ip4_set(&addr, INADDR_ANY, 0); } else { ats_ip_copy(&addr, &accept_addr); } fd = res = socketManager.socket(addr.sa.sa_family, SOCK_STREAM, IPPROTO_TCP); if (res < 0) { goto Lerror; } res = setup_fd_for_listen(non_blocking, recv_bufsize, send_bufsize, transparent); if (res < 0) { goto Lerror; } if ((res = socketManager.ink_bind(fd, &addr.sa, ats_ip_size(&addr.sa), IPPROTO_TCP)) < 0) { goto Lerror; } if ((res = safe_listen(fd, get_listen_backlog())) < 0) { goto Lerror; } // Original just did this on port == 0. namelen = sizeof(addr); if ((res = safe_getsockname(fd, &addr.sa, &namelen))) { goto Lerror; } return 0; Lerror: if (fd != NO_FD) { close(); fd = NO_FD; } Error("Could not bind or listen to port %d (error: %d)", ats_ip_port_host_order(&addr), res); return res; } <|endoftext|>
<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "build/build_config.h" #include "ipc/ipc_tests.h" #if defined(OS_MACOSX) extern "C" { #include <sandbox.h> } #endif #include <fcntl.h> #include <sys/stat.h> #include "base/eintr_wrapper.h" #include "base/message_loop.h" #include "ipc/ipc_channel.h" #include "ipc/ipc_message_utils.h" #include "testing/multiprocess_func_list.h" #if defined(OS_POSIX) #include "base/file_descriptor_posix.h" namespace { const unsigned kNumFDsToSend = 20; const char* kDevZeroPath = "/dev/zero"; static void VerifyAndCloseDescriptor(int fd, ino_t inode_num) { // Check that we can read from the FD. char buf; ssize_t amt_read = read(fd, &buf, 1); ASSERT_EQ(amt_read, 1); ASSERT_EQ(buf, 0); // /dev/zero always reads NUL bytes. struct stat st; ASSERT_EQ(fstat(fd, &st), 0); ASSERT_EQ(close(fd), 0); // We compare iNode numbers to check that the file sent over the wire // was actually the same physical file as the one we were expecting. ASSERT_EQ(inode_num, st.st_ino); } class MyChannelDescriptorListener : public IPC::Channel::Listener { public: MyChannelDescriptorListener(ino_t expected_inode_num) : expected_inode_num_(expected_inode_num), num_fds_received_(0) {} virtual void OnMessageReceived(const IPC::Message& message) { void* iter = NULL; ++num_fds_received_; base::FileDescriptor descriptor; ASSERT_TRUE( IPC::ParamTraits<base::FileDescriptor>::Read( &message, &iter, &descriptor)); VerifyAndCloseDescriptor(descriptor.fd, expected_inode_num_); if (num_fds_received_ == kNumFDsToSend) { MessageLoop::current()->Quit(); } } virtual void OnChannelError() { MessageLoop::current()->Quit(); } private: ino_t expected_inode_num_; unsigned num_fds_received_; }; void TestDescriptorServer(IPC::Channel &chan, base::ProcessHandle process_handle) { ASSERT_TRUE(process_handle); for (unsigned i = 0; i < kNumFDsToSend; ++i) { base::FileDescriptor descriptor; const int fd = open(kDevZeroPath, O_RDONLY); ASSERT_GE(fd, 0); descriptor.auto_close = true; descriptor.fd = fd; IPC::Message* message = new IPC::Message(0, // routing_id 3, // message type IPC::Message::PRIORITY_NORMAL); IPC::ParamTraits<base::FileDescriptor>::Write(message, descriptor); chan.Send(message); } // Run message loop. MessageLoop::current()->Run(); // Close Channel so client gets its OnChannelError() callback fired. chan.Close(); // Cleanup child process. EXPECT_TRUE(base::WaitForSingleProcess(process_handle, 5000)); } int TestDescriptorClient(ino_t expected_inode_num) { MessageLoopForIO main_message_loop; MyChannelDescriptorListener listener(expected_inode_num); // Setup IPC channel. IPC::Channel chan(kTestClientChannel, IPC::Channel::MODE_CLIENT, &listener); CHECK(chan.Connect()); MessageLoop::current()->Run(); return 0; } } // namespace // --------------------------------------------------------------------------- #if defined(OS_MACOSX) // TODO(port): Make this test cross-platform. MULTIPROCESS_TEST_MAIN(RunTestDescriptorClientSandboxed) { struct stat st; const int fd = open(kDevZeroPath, O_RDONLY); fstat(fd, &st); if (HANDLE_EINTR(close(fd)) < 0) { return -1; } // Enable the Sandbox. char* error_buff = NULL; int error = sandbox_init(kSBXProfilePureComputation, SANDBOX_NAMED, &error_buff); bool success = (error == 0 && error_buff == NULL); if (!success) { return -1; } sandbox_free_error(error_buff); // Make sure Sandbox is really enabled. if (open(kDevZeroPath, O_RDONLY) != -1) { LOG(ERROR) << "Sandbox wasn't properly enabled"; return -1; } // See if we can receive a file descriptor. return TestDescriptorClient(st.st_ino); } // Test that FDs are correctly sent to a sandboxed process. TEST_F(IPCChannelTest, DescriptorTestSandboxed) { // Setup IPC channel. MyChannelDescriptorListener listener(-1); IPC::Channel chan(kTestClientChannel, IPC::Channel::MODE_SERVER, &listener); ASSERT_TRUE(chan.Connect()); base::ProcessHandle process_handle = SpawnChild( TEST_DESCRIPTOR_CLIENT_SANDBOXED, &chan); TestDescriptorServer(chan, process_handle); } #endif // defined(OS_MACOSX) MULTIPROCESS_TEST_MAIN(RunTestDescriptorClient) { struct stat st; const int fd = open(kDevZeroPath, O_RDONLY); fstat(fd, &st); EXPECT_GE(HANDLE_EINTR(close(fd)), 0); return TestDescriptorClient(st.st_ino); } TEST_F(IPCChannelTest, DescriptorTest) { // Setup IPC channel. MyChannelDescriptorListener listener(-1); IPC::Channel chan(kTestClientChannel, IPC::Channel::MODE_SERVER, &listener); ASSERT_TRUE(chan.Connect()); base::ProcessHandle process_handle = SpawnChild(TEST_DESCRIPTOR_CLIENT, &chan); TestDescriptorServer(chan, process_handle); } #endif // defined(OS_POSIX) <commit_msg>Verify file descriptor count.<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "build/build_config.h" #include "ipc/ipc_tests.h" #if defined(OS_MACOSX) extern "C" { #include <sandbox.h> } #endif #include <fcntl.h> #include <sys/stat.h> #include "base/eintr_wrapper.h" #include "base/message_loop.h" #include "ipc/ipc_channel.h" #include "ipc/ipc_message_utils.h" #include "testing/multiprocess_func_list.h" #if defined(OS_POSIX) #include "base/file_descriptor_posix.h" namespace { const unsigned kNumFDsToSend = 20; const char* kDevZeroPath = "/dev/zero"; static void VerifyAndCloseDescriptor(int fd, ino_t inode_num) { // Check that we can read from the FD. char buf; ssize_t amt_read = read(fd, &buf, 1); ASSERT_EQ(amt_read, 1); ASSERT_EQ(buf, 0); // /dev/zero always reads NUL bytes. struct stat st; ASSERT_EQ(fstat(fd, &st), 0); ASSERT_EQ(close(fd), 0); // We compare iNode numbers to check that the file sent over the wire // was actually the same physical file as the one we were expecting. ASSERT_EQ(inode_num, st.st_ino); } class MyChannelDescriptorListener : public IPC::Channel::Listener { public: MyChannelDescriptorListener(ino_t expected_inode_num) : expected_inode_num_(expected_inode_num), num_fds_received_(0) {} virtual void OnMessageReceived(const IPC::Message& message) { void* iter = NULL; ++num_fds_received_; base::FileDescriptor descriptor; ASSERT_TRUE( IPC::ParamTraits<base::FileDescriptor>::Read( &message, &iter, &descriptor)); VerifyAndCloseDescriptor(descriptor.fd, expected_inode_num_); if (num_fds_received_ == kNumFDsToSend) { MessageLoop::current()->Quit(); } } virtual void OnChannelError() { MessageLoop::current()->Quit(); } bool GotExpectedNumberOfDescriptors() { return kNumFDsToSend == num_fds_received_; } private: ino_t expected_inode_num_; unsigned num_fds_received_; }; void TestDescriptorServer(IPC::Channel &chan, base::ProcessHandle process_handle) { ASSERT_TRUE(process_handle); for (unsigned i = 0; i < kNumFDsToSend; ++i) { base::FileDescriptor descriptor; const int fd = open(kDevZeroPath, O_RDONLY); ASSERT_GE(fd, 0); descriptor.auto_close = true; descriptor.fd = fd; IPC::Message* message = new IPC::Message(0, // routing_id 3, // message type IPC::Message::PRIORITY_NORMAL); IPC::ParamTraits<base::FileDescriptor>::Write(message, descriptor); ASSERT_TRUE(chan.Send(message)); } // Run message loop. MessageLoop::current()->Run(); // Close Channel so client gets its OnChannelError() callback fired. chan.Close(); // Cleanup child process. EXPECT_TRUE(base::WaitForSingleProcess(process_handle, 5000)); } int TestDescriptorClient(ino_t expected_inode_num) { MessageLoopForIO main_message_loop; MyChannelDescriptorListener listener(expected_inode_num); // Setup IPC channel. IPC::Channel chan(kTestClientChannel, IPC::Channel::MODE_CLIENT, &listener); CHECK(chan.Connect()); // Run message loop so IPC Channel can handle message IO. MessageLoop::current()->Run(); // Verify that the message loop was exited due to getting the correct // number of descriptors, and not because the channel closing unexpectedly. CHECK(listener.GotExpectedNumberOfDescriptors()); return 0; } } // namespace // --------------------------------------------------------------------------- #if defined(OS_MACOSX) // TODO(port): Make this test cross-platform. MULTIPROCESS_TEST_MAIN(RunTestDescriptorClientSandboxed) { struct stat st; const int fd = open(kDevZeroPath, O_RDONLY); fstat(fd, &st); if (HANDLE_EINTR(close(fd)) < 0) { return -1; } // Enable the Sandbox. char* error_buff = NULL; int error = sandbox_init(kSBXProfilePureComputation, SANDBOX_NAMED, &error_buff); bool success = (error == 0 && error_buff == NULL); if (!success) { return -1; } sandbox_free_error(error_buff); // Make sure Sandbox is really enabled. if (open(kDevZeroPath, O_RDONLY) != -1) { LOG(ERROR) << "Sandbox wasn't properly enabled"; return -1; } // See if we can receive a file descriptor. return TestDescriptorClient(st.st_ino); } // Test that FDs are correctly sent to a sandboxed process. TEST_F(IPCChannelTest, DescriptorTestSandboxed) { // Setup IPC channel. MyChannelDescriptorListener listener(-1); IPC::Channel chan(kTestClientChannel, IPC::Channel::MODE_SERVER, &listener); ASSERT_TRUE(chan.Connect()); base::ProcessHandle process_handle = SpawnChild( TEST_DESCRIPTOR_CLIENT_SANDBOXED, &chan); TestDescriptorServer(chan, process_handle); } #endif // defined(OS_MACOSX) MULTIPROCESS_TEST_MAIN(RunTestDescriptorClient) { struct stat st; const int fd = open(kDevZeroPath, O_RDONLY); fstat(fd, &st); EXPECT_GE(HANDLE_EINTR(close(fd)), 0); return TestDescriptorClient(st.st_ino); } TEST_F(IPCChannelTest, DescriptorTest) { // Setup IPC channel. MyChannelDescriptorListener listener(-1); IPC::Channel chan(kTestClientChannel, IPC::Channel::MODE_SERVER, &listener); ASSERT_TRUE(chan.Connect()); base::ProcessHandle process_handle = SpawnChild(TEST_DESCRIPTOR_CLIENT, &chan); TestDescriptorServer(chan, process_handle); } #endif // defined(OS_POSIX) <|endoftext|>
<commit_before>//===-- tsan_suppressions.cc ----------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file is a part of ThreadSanitizer (TSan), a race detector. // //===----------------------------------------------------------------------===// #include "sanitizer_common/sanitizer_common.h" #include "sanitizer_common/sanitizer_libc.h" #include "tsan_suppressions.h" #include "tsan_rtl.h" #include "tsan_flags.h" #include "tsan_mman.h" #include "tsan_platform.h" // Can be overriden in frontend. #ifndef TSAN_GO extern "C" const char *WEAK __tsan_default_suppressions() { return 0; } #endif namespace __tsan { static Suppression *g_suppressions; static char *ReadFile(const char *filename) { if (filename == 0 || filename[0] == 0) return 0; InternalScopedBuffer<char> tmp(4*1024); if (filename[0] == '/' || GetPwd() == 0) internal_snprintf(tmp.data(), tmp.size(), "%s", filename); else internal_snprintf(tmp.data(), tmp.size(), "%s/%s", GetPwd(), filename); fd_t fd = OpenFile(tmp.data(), false); if (fd == kInvalidFd) { Printf("ThreadSanitizer: failed to open suppressions file '%s'\n", tmp.data()); Die(); } const uptr fsize = internal_filesize(fd); if (fsize == (uptr)-1) { Printf("ThreadSanitizer: failed to stat suppressions file '%s'\n", tmp.data()); Die(); } char *buf = (char*)internal_alloc(MBlockSuppression, fsize + 1); if (fsize != internal_read(fd, buf, fsize)) { Printf("ThreadSanitizer: failed to read suppressions file '%s'\n", tmp.data()); Die(); } internal_close(fd); buf[fsize] = 0; return buf; } bool SuppressionMatch(char *templ, const char *str) { if (str == 0 || str[0] == 0) return false; char *tpos; const char *spos; while (templ && templ[0]) { if (templ[0] == '*') { templ++; continue; } if (str[0] == 0) return false; tpos = (char*)internal_strchr(templ, '*'); if (tpos != 0) tpos[0] = 0; spos = internal_strstr(str, templ); str = spos + internal_strlen(templ); templ = tpos; if (tpos) tpos[0] = '*'; if (spos == 0) return false; } return true; } Suppression *SuppressionParse(Suppression *head, const char* supp) { const char *line = supp; while (line) { while (line[0] == ' ' || line[0] == '\t') line++; const char *end = internal_strchr(line, '\n'); if (end == 0) end = line + internal_strlen(line); if (line != end && line[0] != '#') { const char *end2 = end; while (line != end2 && (end2[-1] == ' ' || end2[-1] == '\t')) end2--; SuppressionType stype; if (0 == internal_strncmp(line, "race:", sizeof("race:") - 1)) { stype = SuppressionRace; line += sizeof("race:") - 1; } else if (0 == internal_strncmp(line, "thread:", sizeof("thread:") - 1)) { stype = SuppressionThread; line += sizeof("thread:") - 1; } else if (0 == internal_strncmp(line, "mutex:", sizeof("mutex:") - 1)) { stype = SuppressionMutex; line += sizeof("mutex:") - 1; } else if (0 == internal_strncmp(line, "signal:", sizeof("signal:") - 1)) { stype = SuppressionSignal; line += sizeof("signal:") - 1; } else { Printf("ThreadSanitizer: failed to parse suppressions file\n"); Die(); } Suppression *s = (Suppression*)internal_alloc(MBlockSuppression, sizeof(Suppression)); s->next = head; head = s; s->type = stype; s->templ = (char*)internal_alloc(MBlockSuppression, end2 - line + 1); internal_memcpy(s->templ, line, end2 - line); s->templ[end2 - line] = 0; } if (end[0] == 0) break; line = end + 1; } return head; } void InitializeSuppressions() { const char *supp = ReadFile(flags()->suppressions); g_suppressions = SuppressionParse(0, supp); #ifndef TSAN_GO supp = __tsan_default_suppressions(); g_suppressions = SuppressionParse(0, supp); #endif } uptr IsSuppressed(ReportType typ, const ReportStack *stack) { if (g_suppressions == 0 || stack == 0) return 0; SuppressionType stype; if (typ == ReportTypeRace) stype = SuppressionRace; else if (typ == ReportTypeThreadLeak) stype = SuppressionThread; else if (typ == ReportTypeMutexDestroyLocked) stype = SuppressionMutex; else if (typ == ReportTypeSignalUnsafe) stype = SuppressionSignal; else return 0; for (const ReportStack *frame = stack; frame; frame = frame->next) { for (Suppression *supp = g_suppressions; supp; supp = supp->next) { if (stype == supp->type && (SuppressionMatch(supp->templ, frame->func) || SuppressionMatch(supp->templ, frame->file) || SuppressionMatch(supp->templ, frame->module))) { DPrintf("ThreadSanitizer: matched suppression '%s'\n", supp->templ); return frame->pc; } } } return 0; } } // namespace __tsan <commit_msg>tsan: fix bug in suppression reading (suppressions from file were discarded)<commit_after>//===-- tsan_suppressions.cc ----------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file is a part of ThreadSanitizer (TSan), a race detector. // //===----------------------------------------------------------------------===// #include "sanitizer_common/sanitizer_common.h" #include "sanitizer_common/sanitizer_libc.h" #include "tsan_suppressions.h" #include "tsan_rtl.h" #include "tsan_flags.h" #include "tsan_mman.h" #include "tsan_platform.h" // Can be overriden in frontend. #ifndef TSAN_GO extern "C" const char *WEAK __tsan_default_suppressions() { return 0; } #endif namespace __tsan { static Suppression *g_suppressions; static char *ReadFile(const char *filename) { if (filename == 0 || filename[0] == 0) return 0; InternalScopedBuffer<char> tmp(4*1024); if (filename[0] == '/' || GetPwd() == 0) internal_snprintf(tmp.data(), tmp.size(), "%s", filename); else internal_snprintf(tmp.data(), tmp.size(), "%s/%s", GetPwd(), filename); fd_t fd = OpenFile(tmp.data(), false); if (fd == kInvalidFd) { Printf("ThreadSanitizer: failed to open suppressions file '%s'\n", tmp.data()); Die(); } const uptr fsize = internal_filesize(fd); if (fsize == (uptr)-1) { Printf("ThreadSanitizer: failed to stat suppressions file '%s'\n", tmp.data()); Die(); } char *buf = (char*)internal_alloc(MBlockSuppression, fsize + 1); if (fsize != internal_read(fd, buf, fsize)) { Printf("ThreadSanitizer: failed to read suppressions file '%s'\n", tmp.data()); Die(); } internal_close(fd); buf[fsize] = 0; return buf; } bool SuppressionMatch(char *templ, const char *str) { if (str == 0 || str[0] == 0) return false; char *tpos; const char *spos; while (templ && templ[0]) { if (templ[0] == '*') { templ++; continue; } if (str[0] == 0) return false; tpos = (char*)internal_strchr(templ, '*'); if (tpos != 0) tpos[0] = 0; spos = internal_strstr(str, templ); str = spos + internal_strlen(templ); templ = tpos; if (tpos) tpos[0] = '*'; if (spos == 0) return false; } return true; } Suppression *SuppressionParse(Suppression *head, const char* supp) { const char *line = supp; while (line) { while (line[0] == ' ' || line[0] == '\t') line++; const char *end = internal_strchr(line, '\n'); if (end == 0) end = line + internal_strlen(line); if (line != end && line[0] != '#') { const char *end2 = end; while (line != end2 && (end2[-1] == ' ' || end2[-1] == '\t')) end2--; SuppressionType stype; if (0 == internal_strncmp(line, "race:", sizeof("race:") - 1)) { stype = SuppressionRace; line += sizeof("race:") - 1; } else if (0 == internal_strncmp(line, "thread:", sizeof("thread:") - 1)) { stype = SuppressionThread; line += sizeof("thread:") - 1; } else if (0 == internal_strncmp(line, "mutex:", sizeof("mutex:") - 1)) { stype = SuppressionMutex; line += sizeof("mutex:") - 1; } else if (0 == internal_strncmp(line, "signal:", sizeof("signal:") - 1)) { stype = SuppressionSignal; line += sizeof("signal:") - 1; } else { Printf("ThreadSanitizer: failed to parse suppressions file\n"); Die(); } Suppression *s = (Suppression*)internal_alloc(MBlockSuppression, sizeof(Suppression)); s->next = head; head = s; s->type = stype; s->templ = (char*)internal_alloc(MBlockSuppression, end2 - line + 1); internal_memcpy(s->templ, line, end2 - line); s->templ[end2 - line] = 0; } if (end[0] == 0) break; line = end + 1; } return head; } void InitializeSuppressions() { const char *supp = ReadFile(flags()->suppressions); g_suppressions = SuppressionParse(0, supp); #ifndef TSAN_GO supp = __tsan_default_suppressions(); g_suppressions = SuppressionParse(g_suppressions, supp); #endif } uptr IsSuppressed(ReportType typ, const ReportStack *stack) { if (g_suppressions == 0 || stack == 0) return 0; SuppressionType stype; if (typ == ReportTypeRace) stype = SuppressionRace; else if (typ == ReportTypeThreadLeak) stype = SuppressionThread; else if (typ == ReportTypeMutexDestroyLocked) stype = SuppressionMutex; else if (typ == ReportTypeSignalUnsafe) stype = SuppressionSignal; else return 0; for (const ReportStack *frame = stack; frame; frame = frame->next) { for (Suppression *supp = g_suppressions; supp; supp = supp->next) { if (stype == supp->type && (SuppressionMatch(supp->templ, frame->func) || SuppressionMatch(supp->templ, frame->file) || SuppressionMatch(supp->templ, frame->module))) { DPrintf("ThreadSanitizer: matched suppression '%s'\n", supp->templ); return frame->pc; } } } return 0; } } // namespace __tsan <|endoftext|>
<commit_before>// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab /* * Ceph - scalable distributed file system * * Copyright (C) 2004-2006 Sage Weil <sage@newdream.net> * * This 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. See file COPYING. * */ #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <errno.h> #include <sys/stat.h> #include <iostream> #include <string> using namespace std; #include "common/config.h" #include "common/ceph_argparse.h" #include "common/common_init.h" #include "mon/MonMap.h" void usage() { cout << " usage: [--print] [--create [--clobber]] [--add name 1.2.3.4:567] [--rm name] <mapfilename>" << std::endl; exit(1); } int main(int argc, const char **argv) { vector<const char*> args; argv_to_vec(argc, argv, args); DEFINE_CONF_VARS(usage); const char *me = argv[0]; const char *fn = 0; bool print = false; bool create = false; bool clobber = false; bool modified = false; map<string,entity_addr_t> add; list<string> rm; common_init(args, CEPH_ENTITY_TYPE_CLIENT, CODE_ENVIRONMENT_UTILITY, CINIT_FLAG_NO_DEFAULT_CONFIG_FILE); common_init_finish(&g_ceph_context); FOR_EACH_ARG(args) { if (CEPH_ARGPARSE_EQ("print", '\0')) { CEPH_ARGPARSE_SET_ARG_VAL(&print, OPT_BOOL); } else if (CEPH_ARGPARSE_EQ("create", '\0')) { CEPH_ARGPARSE_SET_ARG_VAL(&create, OPT_BOOL); } else if (CEPH_ARGPARSE_EQ("clobber", '\0')) { CEPH_ARGPARSE_SET_ARG_VAL(&clobber, OPT_BOOL); } else if (CEPH_ARGPARSE_EQ("add", '\0')) { if (++i >= args.size()) usage(); string name = args[i]; if (++i >= args.size()) usage(); entity_addr_t addr; if (!addr.parse(args[i])) { cerr << me << ": invalid ip:port '" << args[i] << "'" << std::endl; return -1; } add[name] = addr; modified = true; } else if (CEPH_ARGPARSE_EQ("rm", '\0')) { if (++i >= args.size()) usage(); string name = args[i]; rm.push_back(name); modified = true; } else if (!fn) fn = args[i]; else { cout << "invalid argument: '" << args[i] << "'" << std::endl; usage(); } } if (!fn) usage(); MonMap monmap; cout << me << ": monmap file " << fn << std::endl; int r = 0; if (!(create && clobber)) { try { r = monmap.read(fn); } catch (...) { cerr << me << ": unable to read monmap file" << std::endl; return -1; } } char buf[80]; if (!create && r < 0) { cerr << me << ": couldn't open " << fn << ": " << strerror_r(-r, buf, sizeof(buf)) << std::endl; return -1; } else if (create && !clobber && r == 0) { cerr << me << ": " << fn << " exists, --clobber to overwrite" << std::endl; return -1; } if (create) { srand(getpid() + time(0)); monmap.generate_fsid(); cout << me << ": generated fsid " << monmap.fsid << std::endl; modified++; } for (map<string,entity_addr_t>::iterator p = add.begin(); p != add.end(); p++) { if (monmap.contains(p->first)) { cerr << me << ": map already contains mon." << p->first << std::endl; usage(); } if (monmap.contains(p->second)) { cerr << me << ": map already contains " << p->second << std::endl; usage(); } monmap.add(p->first, p->second); } for (list<string>::iterator p = rm.begin(); p != rm.end(); p++) { cout << me << ": removing " << *p << std::endl; if (!monmap.contains(*p)) { cerr << me << ": map does not contain " << *p << std::endl; usage(); } monmap.remove(*p); } if (!print && !modified) usage(); if (modified) monmap.epoch++; if (print) monmap.print(cout); if (modified) { // write it out cout << me << ": writing epoch " << monmap.epoch << " to " << fn << " (" << monmap.size() << " monitors)" << std::endl; int r = monmap.write(fn); if (r < 0) { cerr << "monmaptool: error writing to '" << fn << "': " << strerror_r(-r, buf, sizeof(buf)) << std::endl; return 1; } } return 0; } <commit_msg>monmaptool: use default mon port if not specified<commit_after>// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab /* * Ceph - scalable distributed file system * * Copyright (C) 2004-2006 Sage Weil <sage@newdream.net> * * This 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. See file COPYING. * */ #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <errno.h> #include <sys/stat.h> #include <iostream> #include <string> using namespace std; #include "common/config.h" #include "common/ceph_argparse.h" #include "common/common_init.h" #include "mon/MonMap.h" void usage() { cout << " usage: [--print] [--create [--clobber]] [--add name 1.2.3.4:567] [--rm name] <mapfilename>" << std::endl; exit(1); } int main(int argc, const char **argv) { vector<const char*> args; argv_to_vec(argc, argv, args); DEFINE_CONF_VARS(usage); const char *me = argv[0]; const char *fn = 0; bool print = false; bool create = false; bool clobber = false; bool modified = false; map<string,entity_addr_t> add; list<string> rm; common_init(args, CEPH_ENTITY_TYPE_CLIENT, CODE_ENVIRONMENT_UTILITY, CINIT_FLAG_NO_DEFAULT_CONFIG_FILE); common_init_finish(&g_ceph_context); FOR_EACH_ARG(args) { if (CEPH_ARGPARSE_EQ("print", '\0')) { CEPH_ARGPARSE_SET_ARG_VAL(&print, OPT_BOOL); } else if (CEPH_ARGPARSE_EQ("create", '\0')) { CEPH_ARGPARSE_SET_ARG_VAL(&create, OPT_BOOL); } else if (CEPH_ARGPARSE_EQ("clobber", '\0')) { CEPH_ARGPARSE_SET_ARG_VAL(&clobber, OPT_BOOL); } else if (CEPH_ARGPARSE_EQ("add", '\0')) { if (++i >= args.size()) usage(); string name = args[i]; if (++i >= args.size()) usage(); entity_addr_t addr; if (!addr.parse(args[i])) { cerr << me << ": invalid ip:port '" << args[i] << "'" << std::endl; return -1; } if (addr.get_port() == 0) addr.set_port(CEPH_MON_PORT); add[name] = addr; modified = true; } else if (CEPH_ARGPARSE_EQ("rm", '\0')) { if (++i >= args.size()) usage(); string name = args[i]; rm.push_back(name); modified = true; } else if (!fn) fn = args[i]; else { cout << "invalid argument: '" << args[i] << "'" << std::endl; usage(); } } if (!fn) usage(); MonMap monmap; cout << me << ": monmap file " << fn << std::endl; int r = 0; if (!(create && clobber)) { try { r = monmap.read(fn); } catch (...) { cerr << me << ": unable to read monmap file" << std::endl; return -1; } } char buf[80]; if (!create && r < 0) { cerr << me << ": couldn't open " << fn << ": " << strerror_r(-r, buf, sizeof(buf)) << std::endl; return -1; } else if (create && !clobber && r == 0) { cerr << me << ": " << fn << " exists, --clobber to overwrite" << std::endl; return -1; } if (create) { srand(getpid() + time(0)); monmap.generate_fsid(); cout << me << ": generated fsid " << monmap.fsid << std::endl; modified++; } for (map<string,entity_addr_t>::iterator p = add.begin(); p != add.end(); p++) { if (monmap.contains(p->first)) { cerr << me << ": map already contains mon." << p->first << std::endl; usage(); } if (monmap.contains(p->second)) { cerr << me << ": map already contains " << p->second << std::endl; usage(); } monmap.add(p->first, p->second); } for (list<string>::iterator p = rm.begin(); p != rm.end(); p++) { cout << me << ": removing " << *p << std::endl; if (!monmap.contains(*p)) { cerr << me << ": map does not contain " << *p << std::endl; usage(); } monmap.remove(*p); } if (!print && !modified) usage(); if (modified) monmap.epoch++; if (print) monmap.print(cout); if (modified) { // write it out cout << me << ": writing epoch " << monmap.epoch << " to " << fn << " (" << monmap.size() << " monitors)" << std::endl; int r = monmap.write(fn); if (r < 0) { cerr << "monmaptool: error writing to '" << fn << "': " << strerror_r(-r, buf, sizeof(buf)) << std::endl; return 1; } } return 0; } <|endoftext|>
<commit_before>#include "answer/Utils.hh" #include <string> #include <iostream> #include <sstream> #include <string.h> using namespace std; namespace anubis { namespace webservice { string encodeForXml( const string &sSrc, bool encode_special ) { ostringstream sRet; for ( string::const_iterator iter = sSrc.begin(); iter!=sSrc.end(); ++iter ) { unsigned char c = (unsigned char)*iter; switch ( c ) { case '&': sRet << "&amp;"; break; case '<': sRet << "&lt;"; break; case '>': sRet << "&gt;"; break; case '"': sRet << "&quot;"; break; case '\'': sRet << "&apos;"; break; default: sRet << c; } } return sRet.str(); } string decodeFromXml(const string &in) { static const struct entities_s { string name; int value; } entities[] = { {"quot", 34}, {"amp", 38}, {"apos", 39}, {"lt", 60}, {"gt", 62} }; #define NR_OF_ENTITIES 5 string _ent; int i = 0; string ret = ""; size_t pos = 0, wpos = 0, prev = 0; bool found_entity = false; bool found_num_ent = false; for(; pos < in.length() && wpos != string::npos;) { wpos = in.find('&', pos); prev = pos; pos = wpos; //found a '&' if(pos != string::npos) { //going to check if it is an html entity for(i = 0; i < NR_OF_ENTITIES; i++) { _ent = "&"; _ent.append(entities[i].name); _ent.append(";"); //if are equal if(in.compare(pos, _ent.length(), _ent) == 0) { found_entity = true; ret.append(in, prev, pos - prev); wchar_t c(entities[i].value); ret.push_back(c); prev = pos + _ent.length(); pos = prev - 1; break; } } if(!found_entity && in.at(pos + 1) == '#') { found_num_ent = true; size_t pos_aux = 0; char *num_ent; ret.append(in, prev, pos - prev); pos_aux = in.find(';', pos); num_ent = (char *) calloc(pos_aux - pos, sizeof(char)); in.copy(num_ent, (pos_aux - 1) - (pos + 1), pos + 2); wchar_t c(atoi(num_ent)); ret.push_back(c); prev = pos + strlen(num_ent) + 3; // add 3 because of the 3 characters we erased pos = prev - 1; if(num_ent) free(num_ent); } if(!found_entity && !found_num_ent) ret.append(in, prev, pos - prev); pos++; found_entity = false; found_num_ent = false; } } if(!ret.empty()) ret.append(in, prev, pos - prev); else ret.append(in); return ret; } } } <commit_msg>* Removed another old namespace<commit_after>#include "answer/Utils.hh" #include <string> #include <iostream> #include <sstream> #include <string.h> using namespace std; namespace answer { string encodeForXml( const string &sSrc, bool encode_special ) { ostringstream sRet; for ( string::const_iterator iter = sSrc.begin(); iter!=sSrc.end(); ++iter ) { unsigned char c = (unsigned char)*iter; switch ( c ) { case '&': sRet << "&amp;"; break; case '<': sRet << "&lt;"; break; case '>': sRet << "&gt;"; break; case '"': sRet << "&quot;"; break; case '\'': sRet << "&apos;"; break; default: sRet << c; } } return sRet.str(); } string decodeFromXml(const string &in) { static const struct entities_s { string name; int value; } entities[] = { {"quot", 34}, {"amp", 38}, {"apos", 39}, {"lt", 60}, {"gt", 62} }; #define NR_OF_ENTITIES 5 string _ent; int i = 0; string ret = ""; size_t pos = 0, wpos = 0, prev = 0; bool found_entity = false; bool found_num_ent = false; for(; pos < in.length() && wpos != string::npos;) { wpos = in.find('&', pos); prev = pos; pos = wpos; //found a '&' if(pos != string::npos) { //going to check if it is an html entity for(i = 0; i < NR_OF_ENTITIES; i++) { _ent = "&"; _ent.append(entities[i].name); _ent.append(";"); //if are equal if(in.compare(pos, _ent.length(), _ent) == 0) { found_entity = true; ret.append(in, prev, pos - prev); wchar_t c(entities[i].value); ret.push_back(c); prev = pos + _ent.length(); pos = prev - 1; break; } } if(!found_entity && in.at(pos + 1) == '#') { found_num_ent = true; size_t pos_aux = 0; char *num_ent; ret.append(in, prev, pos - prev); pos_aux = in.find(';', pos); num_ent = (char *) calloc(pos_aux - pos, sizeof(char)); in.copy(num_ent, (pos_aux - 1) - (pos + 1), pos + 2); wchar_t c(atoi(num_ent)); ret.push_back(c); prev = pos + strlen(num_ent) + 3; // add 3 because of the 3 characters we erased pos = prev - 1; if(num_ent) free(num_ent); } if(!found_entity && !found_num_ent) ret.append(in, prev, pos - prev); pos++; found_entity = false; found_num_ent = false; } } if(!ret.empty()) ret.append(in, prev, pos - prev); else ret.append(in); return ret; } } <|endoftext|>
<commit_before>// Copyright © 2014, German Neuroinformatics Node (G-Node) // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted under the terms of the BSD License. See // LICENSE file in the root of the Project. // // Author: Christian Kellner <kellner@bio.lmu.de> #include <nix/Value.hpp> #include <cassert> #include <cstdlib> namespace nix { void Value::maybe_deallocte_string() { if (dtype == DataType::String) { std::free(v_string); dtype = DataType::Nothing; } } /**************/ /* setters */ void Value::set(none_t) { maybe_deallocte_string(); dtype = DataType::Nothing; v_bool = false; } void Value::set(bool value) { maybe_deallocte_string(); dtype = DataType::Bool; v_bool = value; } void Value::set(int32_t value) { maybe_deallocte_string(); dtype = DataType::Int32; v_int32 = value; } void Value::set(uint32_t value) { maybe_deallocte_string(); dtype = DataType::UInt32; v_uint32 = value; } void Value::set(int64_t value) { maybe_deallocte_string(); dtype = DataType::Int64; v_int64 = value; } void Value::set(uint64_t value) { maybe_deallocte_string(); dtype = DataType::UInt64; v_uint64 = value; } void Value::set(double value) { maybe_deallocte_string(); dtype = DataType::Double; v_double = value; } void Value::set(const std::string &value) { size_t len = value.length(); size_t len_plus_null = len + 1; void *data; if (dtype != DataType::String) { dtype = DataType::String; data = std::malloc(len_plus_null); } else { data = std::realloc(v_string, len_plus_null); } std::memcpy(data, value.c_str(), len); v_string = static_cast<char *>(data); v_string[len] = '\0'; } /**************/ /* getters */ void Value::get(none_t &tag) const { check_argument_type(DataType::Nothing); } void Value::get(bool &value) const { check_argument_type(DataType::Bool); value = v_bool; } void Value::get(int32_t &value) const { check_argument_type(DataType::Int32); value = v_int32; } void Value::get(uint32_t &value) const { check_argument_type(DataType::UInt32); value = v_uint32; } void Value::get(int64_t &value) const { check_argument_type(DataType::Int64); value = v_int64; } void Value::get(uint64_t &value) const { check_argument_type(DataType::UInt64); value = v_uint64; } void Value::get(double &value) const { check_argument_type(DataType::Double); value = v_double; } void Value::get(std::string &value) const { check_argument_type(DataType::String); value = v_string; } /* swap and swap helpers */ #if 0 //set to one to check that all supported DataTypes are handled #define CHECK_SUPOORTED_VALUES #endif #define DATATYPE_SUPPORT_NOT_IMPLEMENTED false void Value::swap(Value &other) { using std::swap; swap(uncertainty, other.uncertainty); swap(reference, other.reference); swap(filename, other.filename); swap(encoder, other.encoder); swap(checksum, other.checksum); //now for the variant members if (dtype == other.dtype) { switch(dtype) { case DataType::Nothing: /* nothing to do, literally */ break; case DataType::Bool: swap(v_bool, other.v_bool); break; case DataType::Int32: swap(v_int32, other.v_int32); break; case DataType::UInt32: swap(v_uint32, other.v_uint32); break; case DataType::Int64: swap(v_int64, other.v_int64); break; case DataType::UInt64: swap(v_uint64, other.v_uint64); break; case DataType::Double: swap(v_double, other.v_double); break; case DataType::String: swap(v_string, other.v_string); break; #ifndef CHECK_SUPPORTED_VALUES default: assert(DATATYPE_SUPPORT_NOT_IMPLEMENTED); #endif } swap(dtype, other.dtype); } else { switch(dtype) { case DataType::Nothing: swap_helper<none_t>(other); break; case DataType::Bool: swap_helper<bool>(other); break; case DataType::Int32: swap_helper<int32_t>(other); break; case DataType::UInt32: swap_helper<uint32_t>(other); break; case DataType::Int64: swap_helper<int64_t>(other); break; case DataType::UInt64: swap_helper<uint64_t>(other); break; case DataType::Double: swap_helper<double>(other); break; case DataType::String: swap_helper<std::string>(other); break; #ifndef CHECK_SUPPORTED_VALUES default: assert(DATATYPE_SUPPORT_NOT_IMPLEMENTED); #endif } } } void Value::assign_variant_from(const Value &other) { switch (other.dtype) { case DataType::Bool: set(other.v_bool); break; case DataType::Int32: set(other.v_int32); break; case DataType::UInt32: set(other.v_uint32); break; case DataType::Int64: set(other.v_int64); break; case DataType::UInt64: set(other.v_uint64); break; case DataType::Double: set(other.v_double); break; case DataType::String: set(std::string(other.v_string)); break; case DataType::Nothing: set(none); break; #ifndef CHECK_SUPPORTED_VALUES default: assert(DATATYPE_SUPPORT_NOT_IMPLEMENTED); #endif } } bool Value::supports_type(DataType dtype) { switch (dtype) { case DataType::Bool: // we fall through here ... case DataType::Int32: // .oO ( what's happening ... case DataType::UInt32: // ... who am I ... case DataType::Int64: // ... why am I here ... case DataType::UInt64: // ... wind, is that a good name .. case DataType::Double: // ... lets call it tail ... case DataType::String: // ... round, ... ground, ... case DataType::Nothing: // ... hello ground ... return true; default: return false; } } /* operators and functions */ std::ostream& operator<<(std::ostream &out, const Value &value) { out << "Value{[" << value.type() << "] "; switch(value.type()) { case DataType::Bool: out << value.get<bool>(); break; case DataType::String: out << value.get<std::string>(); break; case DataType::Int32: out << value.get<int32_t>(); break; case DataType::UInt32: out << value.get<uint32_t>(); break; case DataType::Int64: out << value.get<int64_t>(); break; case DataType::UInt64: out << value.get<uint64_t>(); break; case DataType::Double: out << value.get<double>(); break; case DataType::Nothing: break; default: out << "IMPLEMENT ME"; break; } out << "}"; return out; } bool operator==(const Value &a, const Value &b) { if (a.type() != b.type()) { return false; } bool match = true; match = match & (a.reference == b.reference); match = match & (a.checksum == b.checksum); match = match & (a.uncertainty == b.uncertainty); match = match & (a.filename == b.filename); match = match & (a.encoder == b.encoder); if (!match) return match; switch(a.type()) { case DataType::Nothing: return true; case DataType::Bool: return a.get<bool>() == b.get<bool>(); case DataType::Int32: return a.get<int32_t>() == b.get<int32_t>(); case DataType::UInt32: return a.get<uint32_t>() == b.get<uint32_t>(); case DataType::Int64: return a.get<int64_t>() == b.get<int64_t>(); case DataType::UInt64: return a.get<uint64_t>() == b.get<uint64_t>(); case DataType::Double: return a.get<double>() == b.get<double>(); case DataType::String: return a.get<std::string>() == b.get<std::string>(); #ifndef CHECK_SUPPORTED_VALUES default: assert(DATATYPE_SUPPORT_NOT_IMPLEMENTED); return false; #endif } } void swap(Value &a, Value &b) { a.swap(b); } } <commit_msg>Value::set(str) make both size_t const<commit_after>// Copyright © 2014, German Neuroinformatics Node (G-Node) // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted under the terms of the BSD License. See // LICENSE file in the root of the Project. // // Author: Christian Kellner <kellner@bio.lmu.de> #include <nix/Value.hpp> #include <cassert> #include <cstdlib> namespace nix { void Value::maybe_deallocte_string() { if (dtype == DataType::String) { std::free(v_string); dtype = DataType::Nothing; } } /**************/ /* setters */ void Value::set(none_t) { maybe_deallocte_string(); dtype = DataType::Nothing; v_bool = false; } void Value::set(bool value) { maybe_deallocte_string(); dtype = DataType::Bool; v_bool = value; } void Value::set(int32_t value) { maybe_deallocte_string(); dtype = DataType::Int32; v_int32 = value; } void Value::set(uint32_t value) { maybe_deallocte_string(); dtype = DataType::UInt32; v_uint32 = value; } void Value::set(int64_t value) { maybe_deallocte_string(); dtype = DataType::Int64; v_int64 = value; } void Value::set(uint64_t value) { maybe_deallocte_string(); dtype = DataType::UInt64; v_uint64 = value; } void Value::set(double value) { maybe_deallocte_string(); dtype = DataType::Double; v_double = value; } void Value::set(const std::string &value) { const size_t len = value.length(); const size_t len_plus_null = len + 1; void *data; if (dtype != DataType::String) { dtype = DataType::String; data = std::malloc(len_plus_null); } else { data = std::realloc(v_string, len_plus_null); } std::memcpy(data, value.c_str(), len); v_string = static_cast<char *>(data); v_string[len] = '\0'; } /**************/ /* getters */ void Value::get(none_t &tag) const { check_argument_type(DataType::Nothing); } void Value::get(bool &value) const { check_argument_type(DataType::Bool); value = v_bool; } void Value::get(int32_t &value) const { check_argument_type(DataType::Int32); value = v_int32; } void Value::get(uint32_t &value) const { check_argument_type(DataType::UInt32); value = v_uint32; } void Value::get(int64_t &value) const { check_argument_type(DataType::Int64); value = v_int64; } void Value::get(uint64_t &value) const { check_argument_type(DataType::UInt64); value = v_uint64; } void Value::get(double &value) const { check_argument_type(DataType::Double); value = v_double; } void Value::get(std::string &value) const { check_argument_type(DataType::String); value = v_string; } /* swap and swap helpers */ #if 0 //set to one to check that all supported DataTypes are handled #define CHECK_SUPOORTED_VALUES #endif #define DATATYPE_SUPPORT_NOT_IMPLEMENTED false void Value::swap(Value &other) { using std::swap; swap(uncertainty, other.uncertainty); swap(reference, other.reference); swap(filename, other.filename); swap(encoder, other.encoder); swap(checksum, other.checksum); //now for the variant members if (dtype == other.dtype) { switch(dtype) { case DataType::Nothing: /* nothing to do, literally */ break; case DataType::Bool: swap(v_bool, other.v_bool); break; case DataType::Int32: swap(v_int32, other.v_int32); break; case DataType::UInt32: swap(v_uint32, other.v_uint32); break; case DataType::Int64: swap(v_int64, other.v_int64); break; case DataType::UInt64: swap(v_uint64, other.v_uint64); break; case DataType::Double: swap(v_double, other.v_double); break; case DataType::String: swap(v_string, other.v_string); break; #ifndef CHECK_SUPPORTED_VALUES default: assert(DATATYPE_SUPPORT_NOT_IMPLEMENTED); #endif } swap(dtype, other.dtype); } else { switch(dtype) { case DataType::Nothing: swap_helper<none_t>(other); break; case DataType::Bool: swap_helper<bool>(other); break; case DataType::Int32: swap_helper<int32_t>(other); break; case DataType::UInt32: swap_helper<uint32_t>(other); break; case DataType::Int64: swap_helper<int64_t>(other); break; case DataType::UInt64: swap_helper<uint64_t>(other); break; case DataType::Double: swap_helper<double>(other); break; case DataType::String: swap_helper<std::string>(other); break; #ifndef CHECK_SUPPORTED_VALUES default: assert(DATATYPE_SUPPORT_NOT_IMPLEMENTED); #endif } } } void Value::assign_variant_from(const Value &other) { switch (other.dtype) { case DataType::Bool: set(other.v_bool); break; case DataType::Int32: set(other.v_int32); break; case DataType::UInt32: set(other.v_uint32); break; case DataType::Int64: set(other.v_int64); break; case DataType::UInt64: set(other.v_uint64); break; case DataType::Double: set(other.v_double); break; case DataType::String: set(std::string(other.v_string)); break; case DataType::Nothing: set(none); break; #ifndef CHECK_SUPPORTED_VALUES default: assert(DATATYPE_SUPPORT_NOT_IMPLEMENTED); #endif } } bool Value::supports_type(DataType dtype) { switch (dtype) { case DataType::Bool: // we fall through here ... case DataType::Int32: // .oO ( what's happening ... case DataType::UInt32: // ... who am I ... case DataType::Int64: // ... why am I here ... case DataType::UInt64: // ... wind, is that a good name .. case DataType::Double: // ... lets call it tail ... case DataType::String: // ... round, ... ground, ... case DataType::Nothing: // ... hello ground ... return true; default: return false; } } /* operators and functions */ std::ostream& operator<<(std::ostream &out, const Value &value) { out << "Value{[" << value.type() << "] "; switch(value.type()) { case DataType::Bool: out << value.get<bool>(); break; case DataType::String: out << value.get<std::string>(); break; case DataType::Int32: out << value.get<int32_t>(); break; case DataType::UInt32: out << value.get<uint32_t>(); break; case DataType::Int64: out << value.get<int64_t>(); break; case DataType::UInt64: out << value.get<uint64_t>(); break; case DataType::Double: out << value.get<double>(); break; case DataType::Nothing: break; default: out << "IMPLEMENT ME"; break; } out << "}"; return out; } bool operator==(const Value &a, const Value &b) { if (a.type() != b.type()) { return false; } bool match = true; match = match & (a.reference == b.reference); match = match & (a.checksum == b.checksum); match = match & (a.uncertainty == b.uncertainty); match = match & (a.filename == b.filename); match = match & (a.encoder == b.encoder); if (!match) return match; switch(a.type()) { case DataType::Nothing: return true; case DataType::Bool: return a.get<bool>() == b.get<bool>(); case DataType::Int32: return a.get<int32_t>() == b.get<int32_t>(); case DataType::UInt32: return a.get<uint32_t>() == b.get<uint32_t>(); case DataType::Int64: return a.get<int64_t>() == b.get<int64_t>(); case DataType::UInt64: return a.get<uint64_t>() == b.get<uint64_t>(); case DataType::Double: return a.get<double>() == b.get<double>(); case DataType::String: return a.get<std::string>() == b.get<std::string>(); #ifndef CHECK_SUPPORTED_VALUES default: assert(DATATYPE_SUPPORT_NOT_IMPLEMENTED); return false; #endif } } void swap(Value &a, Value &b) { a.swap(b); } } <|endoftext|>
<commit_before>/* This file is part of KAddressBook. Copyright (c) 2002 Mike Pilone <mpilone@slac.com> 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. As a special exception, permission is given to link this program with any edition of Qt, and distribute the resulting executable, without including the source code for Qt in the source distribution. */ #include <qlayout.h> #include <qheader.h> #include <qvbox.h> #include <qlistbox.h> #include <qwidget.h> #include <qfile.h> #include <qimage.h> #include <qcombobox.h> #include <qapplication.h> #include <qdragobject.h> #include <qevent.h> #include <qurl.h> #include <qpixmap.h> #include <kabc/addressbook.h> #include <kapplication.h> #include <kconfig.h> #include <kcolorbutton.h> #include <kdebug.h> #include <kglobal.h> #include <kiconloader.h> #include <klineedit.h> #include <klocale.h> #include <kmessagebox.h> #include <kurl.h> #include <kurlrequester.h> #include <kimproxy.h> #include "configuretableviewdialog.h" #include "contactlistview.h" #include "core.h" #include "kabprefs.h" #include "undocmds.h" #include "kaddressbooktableview.h" class TableViewFactory : public ViewFactory { public: KAddressBookView *view( KAB::Core *core, QWidget *parent, const char *name ) { return new KAddressBookTableView( core, parent, name ); } QString type() const { return I18N_NOOP("Table"); } QString description() const { return i18n( "A listing of contacts in a table. Each cell of " "the table holds a field of the contact." ); } ViewConfigureWidget *configureWidget( KABC::AddressBook *ab, QWidget *parent, const char *name = 0 ) { return new ConfigureTableViewWidget( ab, parent, name ); } }; extern "C" { void *init_libkaddrbk_tableview() { return ( new TableViewFactory ); } } KAddressBookTableView::KAddressBookTableView( KAB::Core *core, QWidget *parent, const char *name ) : KAddressBookView( core, parent, name ) { mainLayout = new QVBoxLayout( viewWidget(), 2 ); // The list view will be created when the config is read. mListView = 0; mIMProxy = 0; } KAddressBookTableView::~KAddressBookTableView() { } void KAddressBookTableView::reconstructListView() { if (mListView) { disconnect(mListView, SIGNAL(selectionChanged()), this, SLOT(addresseeSelected())); disconnect(mListView, SIGNAL(executed(QListViewItem*)), this, SLOT(addresseeExecuted(QListViewItem*))); disconnect(mListView, SIGNAL(doubleClicked(QListViewItem*)), this, SLOT(addresseeExecuted(QListViewItem*))); disconnect(mListView, SIGNAL(startAddresseeDrag()), this, SIGNAL(startDrag())); disconnect(mListView, SIGNAL(addresseeDropped(QDropEvent*)), this, SIGNAL(dropped(QDropEvent*))); delete mListView; } mListView = new ContactListView( this, core()->addressBook(), viewWidget() ); mListView->setFullWidth( true ); mListView->setShowIM( mIMProxy != 0 ); // Add the columns KABC::Field::List fieldList = fields(); KABC::Field::List::ConstIterator it; int c = 0; for( it = fieldList.begin(); it != fieldList.end(); ++it ) { mListView->addColumn( (*it)->label() ); mListView->setColumnWidthMode(c++, QListView::Manual); } if ( mListView->showIM() ) { // IM presence is added separately, because it's not a KABC field. // If you want to make this appear as the leftmost column by default, move // this block immediately before the preceding for loop // after the declaration of c. mListView->addColumn( i18n( "Presence" ) ); mListView->setIMColumn( c++ ); } connect(mListView, SIGNAL(selectionChanged()), this, SLOT(addresseeSelected())); connect(mListView, SIGNAL(startAddresseeDrag()), this, SIGNAL(startDrag())); connect(mListView, SIGNAL(addresseeDropped(QDropEvent*)), this, SIGNAL(dropped(QDropEvent*))); connect( mListView, SIGNAL( contextMenu( KListView*, QListViewItem*, const QPoint& ) ), this, SLOT( rmbClicked( KListView*, QListViewItem*, const QPoint& ) ) ); connect( mListView->header(), SIGNAL( clicked(int) ), SIGNAL( sortFieldChanged() ) ); if ( KABPrefs::instance()->honorSingleClick() ) connect(mListView, SIGNAL(executed(QListViewItem*)), this, SLOT(addresseeExecuted(QListViewItem*))); else connect(mListView, SIGNAL(doubleClicked(QListViewItem*)), this, SLOT(addresseeExecuted(QListViewItem*))); refresh(); mListView->setSorting( 0, true ); mainLayout->addWidget( mListView ); mainLayout->activate(); mListView->show(); } KABC::Field *KAddressBookTableView::sortField() const { // we have hardcoded sorting, so we have to return a hardcoded field :( return ( mListView->sortColumn() == -1 ? fields()[ 0 ] : fields()[ mListView->sortColumn() ] ); } void KAddressBookTableView::writeConfig(KConfig *config) { KAddressBookView::writeConfig(config); mListView->saveLayout(config, config->group()); } void KAddressBookTableView::readConfig(KConfig *config) { KAddressBookView::readConfig( config ); if ( config->readBoolEntry( "InstantMessagingPresence", false ) ) { if ( !mIMProxy ) { mIMProxy = KIMProxy::instance( kapp->dcopClient() ); connect( mIMProxy, SIGNAL( sigContactPresenceChanged( const QString & ) ), this, SLOT( updatePresence( const QString & ) ) ); } } else { if ( mIMProxy ) { disconnect( mIMProxy, SIGNAL( sigContactPresenceChanged( const QString & ) ), this, SLOT( updatePresence( const QString & ) ) ); mIMProxy = 0; } } // The config could have changed the fields, so we need to reconstruct // the listview. reconstructListView(); // Set the list view options mListView->setAlternateBackgroundEnabled(config->readBoolEntry("ABackground", true)); mListView->setSingleLineEnabled(config->readBoolEntry("SingleLine", false)); mListView->setToolTipsEnabled(config->readBoolEntry("ToolTips", true)); if (config->readBoolEntry("Background", false)) mListView->setBackgroundPixmap(config->readPathEntry("BackgroundName")); // Restore the layout of the listview mListView->restoreLayout(config, config->group()); } void KAddressBookTableView::refresh(QString uid) { if (uid.isNull()) { // Clear the list view QString currentUID, nextUID; ContactListViewItem *currentItem = dynamic_cast<ContactListViewItem*>( mListView->currentItem() ); if ( currentItem ) { ContactListViewItem *nextItem = dynamic_cast<ContactListViewItem*>( currentItem->itemBelow() ); if ( nextItem ) nextUID = nextItem->addressee().uid(); currentUID = currentItem->addressee().uid(); } mListView->clear(); currentItem = 0; KABC::Addressee::List addresseeList = addressees(); KABC::Addressee::List::Iterator it; for (it = addresseeList.begin(); it != addresseeList.end(); ++it ) { ContactListViewItem *item = new ContactListViewItem(*it, mListView, core()->addressBook(), fields(), mIMProxy ); if ( (*it).uid() == currentUID ) currentItem = item; else if ( (*it).uid() == nextUID && !currentItem ) currentItem = item; } // Sometimes the background pixmap gets messed up when we add lots // of items. mListView->repaint(); if ( currentItem ) { mListView->setCurrentItem( currentItem ); mListView->ensureItemVisible( currentItem ); } } else { // Only need to update on entry. Iterate through and try to find it ContactListViewItem *ceItem; QPtrList<QListViewItem> selectedItems( mListView->selectedItems() ); QListViewItem *it; for ( it = selectedItems.first(); it; it = selectedItems.next() ) { ceItem = dynamic_cast<ContactListViewItem*>( it ); if ( ceItem && ceItem->addressee().uid() == uid ) { ceItem->refresh(); return; } } refresh( QString::null ); } } QStringList KAddressBookTableView::selectedUids() { QStringList uidList; QListViewItem *item; ContactListViewItem *ceItem; for(item = mListView->firstChild(); item; item = item->itemBelow()) { if (mListView->isSelected( item )) { ceItem = dynamic_cast<ContactListViewItem*>(item); if (ceItem != 0L) uidList << ceItem->addressee().uid(); } } return uidList; } void KAddressBookTableView::setSelected(QString uid, bool selected) { QListViewItem *item; ContactListViewItem *ceItem; if (uid.isNull()) { mListView->selectAll(selected); } else { for(item = mListView->firstChild(); item; item = item->itemBelow()) { ceItem = dynamic_cast<ContactListViewItem*>(item); if ((ceItem != 0L) && (ceItem->addressee().uid() == uid)) { mListView->setSelected(item, selected); if (selected) mListView->ensureItemVisible(item); } } } } void KAddressBookTableView::addresseeSelected() { // We need to try to find the first selected item. This might not be the // last selected item, but when QListView is in multiselection mode, // there is no way to figure out which one was // selected last. QListViewItem *item; bool found =false; for (item = mListView->firstChild(); item && !found; item = item->nextSibling()) { if (item->isSelected()) { found = true; ContactListViewItem *ceItem = dynamic_cast<ContactListViewItem*>(item); if ( ceItem ) emit selected(ceItem->addressee().uid()); } } if (!found) emit selected(QString::null); } void KAddressBookTableView::addresseeExecuted(QListViewItem *item) { if (item) { ContactListViewItem *ceItem = dynamic_cast<ContactListViewItem*>(item); if (ceItem) { emit executed(ceItem->addressee().uid()); } } else { emit executed(QString::null); } } void KAddressBookTableView::rmbClicked( KListView*, QListViewItem*, const QPoint &point ) { popup( point ); } void KAddressBookTableView::updatePresence( const QString &uid ) { // find the LVI to update and refresh() it QListViewItem *item; ContactListViewItem *ceItem; for ( item = mListView->firstChild(); item; item = item->itemBelow() ) { ceItem = dynamic_cast<ContactListViewItem*>(item); if ( ( ceItem != 0L ) && ( ceItem->addressee().uid() == uid ) ) { ceItem->setHasIM( true ); ceItem->refresh(); break; } } if ( mListView->sortColumn() == mListView->imColumn() ) mListView->sort(); } #include "kaddressbooktableview.moc" <commit_msg>Call setFullWidth() after all columns are added to avoid that the last column is streched too much.<commit_after>/* This file is part of KAddressBook. Copyright (c) 2002 Mike Pilone <mpilone@slac.com> 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. As a special exception, permission is given to link this program with any edition of Qt, and distribute the resulting executable, without including the source code for Qt in the source distribution. */ #include <qlayout.h> #include <qheader.h> #include <qvbox.h> #include <qlistbox.h> #include <qwidget.h> #include <qfile.h> #include <qimage.h> #include <qcombobox.h> #include <qapplication.h> #include <qdragobject.h> #include <qevent.h> #include <qurl.h> #include <qpixmap.h> #include <kabc/addressbook.h> #include <kapplication.h> #include <kconfig.h> #include <kcolorbutton.h> #include <kdebug.h> #include <kglobal.h> #include <kiconloader.h> #include <klineedit.h> #include <klocale.h> #include <kmessagebox.h> #include <kurl.h> #include <kurlrequester.h> #include <kimproxy.h> #include "configuretableviewdialog.h" #include "contactlistview.h" #include "core.h" #include "kabprefs.h" #include "undocmds.h" #include "kaddressbooktableview.h" class TableViewFactory : public ViewFactory { public: KAddressBookView *view( KAB::Core *core, QWidget *parent, const char *name ) { return new KAddressBookTableView( core, parent, name ); } QString type() const { return I18N_NOOP("Table"); } QString description() const { return i18n( "A listing of contacts in a table. Each cell of " "the table holds a field of the contact." ); } ViewConfigureWidget *configureWidget( KABC::AddressBook *ab, QWidget *parent, const char *name = 0 ) { return new ConfigureTableViewWidget( ab, parent, name ); } }; extern "C" { void *init_libkaddrbk_tableview() { return ( new TableViewFactory ); } } KAddressBookTableView::KAddressBookTableView( KAB::Core *core, QWidget *parent, const char *name ) : KAddressBookView( core, parent, name ) { mainLayout = new QVBoxLayout( viewWidget(), 2 ); // The list view will be created when the config is read. mListView = 0; mIMProxy = 0; } KAddressBookTableView::~KAddressBookTableView() { } void KAddressBookTableView::reconstructListView() { if (mListView) { disconnect(mListView, SIGNAL(selectionChanged()), this, SLOT(addresseeSelected())); disconnect(mListView, SIGNAL(executed(QListViewItem*)), this, SLOT(addresseeExecuted(QListViewItem*))); disconnect(mListView, SIGNAL(doubleClicked(QListViewItem*)), this, SLOT(addresseeExecuted(QListViewItem*))); disconnect(mListView, SIGNAL(startAddresseeDrag()), this, SIGNAL(startDrag())); disconnect(mListView, SIGNAL(addresseeDropped(QDropEvent*)), this, SIGNAL(dropped(QDropEvent*))); delete mListView; } mListView = new ContactListView( this, core()->addressBook(), viewWidget() ); mListView->setShowIM( mIMProxy != 0 ); // Add the columns KABC::Field::List fieldList = fields(); KABC::Field::List::ConstIterator it; int c = 0; for( it = fieldList.begin(); it != fieldList.end(); ++it ) { mListView->addColumn( (*it)->label() ); mListView->setColumnWidthMode(c++, QListView::Manual); } if ( mListView->showIM() ) { // IM presence is added separately, because it's not a KABC field. // If you want to make this appear as the leftmost column by default, move // this block immediately before the preceding for loop // after the declaration of c. mListView->addColumn( i18n( "Presence" ) ); mListView->setIMColumn( c++ ); } mListView->setFullWidth( true ); connect(mListView, SIGNAL(selectionChanged()), this, SLOT(addresseeSelected())); connect(mListView, SIGNAL(startAddresseeDrag()), this, SIGNAL(startDrag())); connect(mListView, SIGNAL(addresseeDropped(QDropEvent*)), this, SIGNAL(dropped(QDropEvent*))); connect( mListView, SIGNAL( contextMenu( KListView*, QListViewItem*, const QPoint& ) ), this, SLOT( rmbClicked( KListView*, QListViewItem*, const QPoint& ) ) ); connect( mListView->header(), SIGNAL( clicked(int) ), SIGNAL( sortFieldChanged() ) ); if ( KABPrefs::instance()->honorSingleClick() ) connect(mListView, SIGNAL(executed(QListViewItem*)), this, SLOT(addresseeExecuted(QListViewItem*))); else connect(mListView, SIGNAL(doubleClicked(QListViewItem*)), this, SLOT(addresseeExecuted(QListViewItem*))); refresh(); mListView->setSorting( 0, true ); mainLayout->addWidget( mListView ); mainLayout->activate(); mListView->show(); } KABC::Field *KAddressBookTableView::sortField() const { // we have hardcoded sorting, so we have to return a hardcoded field :( return ( mListView->sortColumn() == -1 ? fields()[ 0 ] : fields()[ mListView->sortColumn() ] ); } void KAddressBookTableView::writeConfig(KConfig *config) { KAddressBookView::writeConfig(config); mListView->saveLayout(config, config->group()); } void KAddressBookTableView::readConfig(KConfig *config) { KAddressBookView::readConfig( config ); if ( config->readBoolEntry( "InstantMessagingPresence", false ) ) { if ( !mIMProxy ) { mIMProxy = KIMProxy::instance( kapp->dcopClient() ); connect( mIMProxy, SIGNAL( sigContactPresenceChanged( const QString & ) ), this, SLOT( updatePresence( const QString & ) ) ); } } else { if ( mIMProxy ) { disconnect( mIMProxy, SIGNAL( sigContactPresenceChanged( const QString & ) ), this, SLOT( updatePresence( const QString & ) ) ); mIMProxy = 0; } } // The config could have changed the fields, so we need to reconstruct // the listview. reconstructListView(); // Set the list view options mListView->setAlternateBackgroundEnabled(config->readBoolEntry("ABackground", true)); mListView->setSingleLineEnabled(config->readBoolEntry("SingleLine", false)); mListView->setToolTipsEnabled(config->readBoolEntry("ToolTips", true)); if (config->readBoolEntry("Background", false)) mListView->setBackgroundPixmap(config->readPathEntry("BackgroundName")); // Restore the layout of the listview mListView->restoreLayout(config, config->group()); } void KAddressBookTableView::refresh(QString uid) { if (uid.isNull()) { // Clear the list view QString currentUID, nextUID; ContactListViewItem *currentItem = dynamic_cast<ContactListViewItem*>( mListView->currentItem() ); if ( currentItem ) { ContactListViewItem *nextItem = dynamic_cast<ContactListViewItem*>( currentItem->itemBelow() ); if ( nextItem ) nextUID = nextItem->addressee().uid(); currentUID = currentItem->addressee().uid(); } mListView->clear(); currentItem = 0; KABC::Addressee::List addresseeList = addressees(); KABC::Addressee::List::Iterator it; for (it = addresseeList.begin(); it != addresseeList.end(); ++it ) { ContactListViewItem *item = new ContactListViewItem(*it, mListView, core()->addressBook(), fields(), mIMProxy ); if ( (*it).uid() == currentUID ) currentItem = item; else if ( (*it).uid() == nextUID && !currentItem ) currentItem = item; } // Sometimes the background pixmap gets messed up when we add lots // of items. mListView->repaint(); if ( currentItem ) { mListView->setCurrentItem( currentItem ); mListView->ensureItemVisible( currentItem ); } } else { // Only need to update on entry. Iterate through and try to find it ContactListViewItem *ceItem; QPtrList<QListViewItem> selectedItems( mListView->selectedItems() ); QListViewItem *it; for ( it = selectedItems.first(); it; it = selectedItems.next() ) { ceItem = dynamic_cast<ContactListViewItem*>( it ); if ( ceItem && ceItem->addressee().uid() == uid ) { ceItem->refresh(); return; } } refresh( QString::null ); } } QStringList KAddressBookTableView::selectedUids() { QStringList uidList; QListViewItem *item; ContactListViewItem *ceItem; for(item = mListView->firstChild(); item; item = item->itemBelow()) { if (mListView->isSelected( item )) { ceItem = dynamic_cast<ContactListViewItem*>(item); if (ceItem != 0L) uidList << ceItem->addressee().uid(); } } return uidList; } void KAddressBookTableView::setSelected(QString uid, bool selected) { QListViewItem *item; ContactListViewItem *ceItem; if (uid.isNull()) { mListView->selectAll(selected); } else { for(item = mListView->firstChild(); item; item = item->itemBelow()) { ceItem = dynamic_cast<ContactListViewItem*>(item); if ((ceItem != 0L) && (ceItem->addressee().uid() == uid)) { mListView->setSelected(item, selected); if (selected) mListView->ensureItemVisible(item); } } } } void KAddressBookTableView::addresseeSelected() { // We need to try to find the first selected item. This might not be the // last selected item, but when QListView is in multiselection mode, // there is no way to figure out which one was // selected last. QListViewItem *item; bool found =false; for (item = mListView->firstChild(); item && !found; item = item->nextSibling()) { if (item->isSelected()) { found = true; ContactListViewItem *ceItem = dynamic_cast<ContactListViewItem*>(item); if ( ceItem ) emit selected(ceItem->addressee().uid()); } } if (!found) emit selected(QString::null); } void KAddressBookTableView::addresseeExecuted(QListViewItem *item) { if (item) { ContactListViewItem *ceItem = dynamic_cast<ContactListViewItem*>(item); if (ceItem) { emit executed(ceItem->addressee().uid()); } } else { emit executed(QString::null); } } void KAddressBookTableView::rmbClicked( KListView*, QListViewItem*, const QPoint &point ) { popup( point ); } void KAddressBookTableView::updatePresence( const QString &uid ) { // find the LVI to update and refresh() it QListViewItem *item; ContactListViewItem *ceItem; for ( item = mListView->firstChild(); item; item = item->itemBelow() ) { ceItem = dynamic_cast<ContactListViewItem*>(item); if ( ( ceItem != 0L ) && ( ceItem->addressee().uid() == uid ) ) { ceItem->setHasIM( true ); ceItem->refresh(); break; } } if ( mListView->sortColumn() == mListView->imColumn() ) mListView->sort(); } #include "kaddressbooktableview.moc" <|endoftext|>
<commit_before><commit_msg>Fix name of OBJ file in demo (capitalization)<commit_after><|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */ #include "config.h" #include <iostream> #include <cstdlib> #include <utility> #include <list> #include "common.hh" #include "item_pager.hh" #include "ep.hh" static const double EJECTION_RATIO_THRESHOLD(0.1); static const size_t MAX_PERSISTENCE_QUEUE_SIZE = 1000000; /** * As part of the ItemPager, visit all of the objects in memory and * eject some within a constrained probability */ class PagingVisitor : public VBucketVisitor { public: /** * Construct a PagingVisitor that will attempt to evict the given * percentage of objects. * * @param s the store that will handle the bulk removal * @param st the stats where we'll track what we've done * @param pcnt percentage of objects to attempt to evict (0-1) * @param sfin pointer to a bool to be set to true after run completes * @param pause flag indicating if PagingVisitor can pause between vbucket visits */ PagingVisitor(EventuallyPersistentStore *s, EPStats &st, double pcnt, bool *sfin, bool pause = false) : store(s), stats(st), percent(pcnt), ejected(0), totalEjected(0), totalEjectionAttempts(0), startTime(ep_real_time()), stateFinalizer(sfin), canPause(pause) {} void visit(StoredValue *v) { // Remember expired objects -- we're going to delete them. if ((v->isExpired(startTime) && !v->isDeleted()) || v->isTempItem()) { expired.push_back(std::make_pair(currentBucket->getId(), v->getKey())); return; } double r = static_cast<double>(std::rand()) / static_cast<double>(RAND_MAX); if (percent >= r) { ++totalEjectionAttempts; if (!v->eligibleForEviction()) { ++stats.numFailedEjects; return; } // Check if the key was already visited by all the cursors. bool can_evict = currentBucket->checkpointManager.eligibleForEviction(v->getKey()); if (can_evict && v->ejectValue(stats, currentBucket->ht)) { ++ejected; } } } bool visitBucket(RCPtr<VBucket> &vb) { update(); return VBucketVisitor::visitBucket(vb); } void update() { stats.expired.incr(expired.size()); store->deleteExpiredItems(expired); if (numEjected() > 0) { getLogger()->log(EXTENSION_LOG_INFO, NULL, "Paged out %ld values\n", numEjected()); } size_t num_expired = expired.size(); if (num_expired > 0) { getLogger()->log(EXTENSION_LOG_INFO, NULL, "Purged %ld expired items\n", num_expired); } totalEjected += (ejected + num_expired); ejected = 0; expired.clear(); } bool pauseVisitor() { size_t queueSize = stats.queue_size.get() + stats.flusher_todo.get(); return canPause && queueSize >= MAX_PERSISTENCE_QUEUE_SIZE; } void complete() { update(); if (stateFinalizer) { *stateFinalizer = true; } } /** * Get the number of items ejected during the visit. */ size_t numEjected() { return ejected; } /** * Get the total number of items whose values are ejected or removed due to * the expiry time. */ size_t getTotalEjected() { return totalEjected; } /** * Get the total number of ejection attempts. */ size_t getTotalEjectionAttempts() { return totalEjectionAttempts; } private: std::list<std::pair<uint16_t, std::string> > expired; EventuallyPersistentStore *store; EPStats &stats; double percent; size_t ejected; size_t totalEjected; size_t totalEjectionAttempts; time_t startTime; bool *stateFinalizer; bool canPause; }; bool ItemPager::callback(Dispatcher &d, TaskId t) { double current = static_cast<double>(stats.getTotalMemoryUsed()); double upper = static_cast<double>(stats.mem_high_wat); double lower = static_cast<double>(stats.mem_low_wat); if (available && current > upper) { ++stats.pagerRuns; double toKill = (current - static_cast<double>(lower)) / current; std::stringstream ss; ss << "Using " << stats.getTotalMemoryUsed() << " bytes of memory, paging out %0f%% of items." << std::endl; getLogger()->log(EXTENSION_LOG_INFO, NULL, ss.str().c_str(), (toKill*100.0)); available = false; shared_ptr<PagingVisitor> pv(new PagingVisitor(store, stats, toKill, &available)); store->visit(pv, "Item pager", &d, Priority::ItemPagerPriority); double total_eject_attms = static_cast<double>(pv->getTotalEjectionAttempts()); double total_ejected = static_cast<double>(pv->getTotalEjected()); double ejection_ratio = total_eject_attms > 0 ? total_ejected / total_eject_attms : 0; if (stats.getTotalMemoryUsed() > stats.mem_high_wat && ejection_ratio < EJECTION_RATIO_THRESHOLD) { const VBucketMap &vbuckets = store->getVBuckets(); size_t num_vbuckets = vbuckets.getSize(); for (size_t i = 0; i < num_vbuckets; ++i) { assert(i <= std::numeric_limits<uint16_t>::max()); uint16_t vbid = static_cast<uint16_t>(i); RCPtr<VBucket> vb = vbuckets.getBucket(vbid); if (!vb) { continue; } vb->checkpointManager.setCheckpointExtension(false); } } } d.snooze(t, 10); return true; } bool ExpiredItemPager::callback(Dispatcher &d, TaskId t) { if (available) { ++stats.expiryPagerRuns; available = false; shared_ptr<PagingVisitor> pv(new PagingVisitor(store, stats, -1, &available, true)); store->visit(pv, "Expired item remover", &d, Priority::ItemPagerPriority, true, 10); } d.snooze(t, sleepTime); return true; } void InvalidItemDbPager::addInvalidItem(Item *itm, uint16_t vbucket_version) { uint16_t vbucket_id = itm->getVBucketId(); std::map<uint16_t, uint16_t>::iterator version_it = vb_versions.find(vbucket_id); if (version_it == vb_versions.end() || version_it->second < vbucket_version) { vb_versions[vbucket_id] = vbucket_version; } std::map<uint16_t, std::vector<int64_t>* >::iterator item_it = vb_items.find(vbucket_id); if (item_it != vb_items.end()) { item_it->second->push_back(itm->getId()); } else { std::vector<int64_t> *item_list = new std::vector<int64_t>(chunk_size * 5); item_list->push_back(itm->getId()); vb_items[vbucket_id] = item_list; } } void InvalidItemDbPager::createRangeList() { std::map<uint16_t, std::vector<int64_t>* >::iterator vbit; for (vbit = vb_items.begin(); vbit != vb_items.end(); vbit++) { std::sort(vbit->second->begin(), vbit->second->end()); std::list<row_range_t> row_range_list; createChunkListFromArray<int64_t>(vbit->second, chunk_size, row_range_list); vb_row_ranges[vbit->first] = row_range_list; delete vbit->second; } vb_items.clear(); } bool InvalidItemDbPager::callback(Dispatcher &d, TaskId t) { BlockTimer timer(&stats.diskInvaidItemDelHisto); std::map<uint16_t, std::list<row_range_t> >::iterator it = vb_row_ranges.begin(); if (it == vb_row_ranges.end()) { stats.dbCleanerComplete.set(true); return false; } std::list<row_range_t>::iterator rit = it->second.begin(); uint16_t vbid = it->first; uint16_t vb_version = vb_versions[vbid]; if (store->getRWUnderlying()->delVBucket(vbid, vb_version, *rit)) { it->second.erase(rit); if (it->second.begin() == it->second.end()) { vb_row_ranges.erase(it); } } else { d.snooze(t, 10); getLogger()->log(EXTENSION_LOG_DEBUG, NULL, "Reschedule to delete the old chunk of vbucket %d with" " the version %d from disk\n", vbid, vb_version); } return true; } <commit_msg>MB-5723 Add rand seeding for item pager random item eviction<commit_after>/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */ #include "config.h" #include <iostream> #include <cstdlib> #include <utility> #include <list> #include "common.hh" #include "item_pager.hh" #include "ep.hh" static const double EJECTION_RATIO_THRESHOLD(0.1); static const size_t MAX_PERSISTENCE_QUEUE_SIZE = 1000000; /** * As part of the ItemPager, visit all of the objects in memory and * eject some within a constrained probability */ class PagingVisitor : public VBucketVisitor { public: /** * Construct a PagingVisitor that will attempt to evict the given * percentage of objects. * * @param s the store that will handle the bulk removal * @param st the stats where we'll track what we've done * @param pcnt percentage of objects to attempt to evict (0-1) * @param sfin pointer to a bool to be set to true after run completes * @param pause flag indicating if PagingVisitor can pause between vbucket visits */ PagingVisitor(EventuallyPersistentStore *s, EPStats &st, double pcnt, bool *sfin, bool pause = false) : store(s), stats(st), percent(pcnt), ejected(0), totalEjected(0), totalEjectionAttempts(0), startTime(ep_real_time()), stateFinalizer(sfin), canPause(pause) {} void visit(StoredValue *v) { // Remember expired objects -- we're going to delete them. if ((v->isExpired(startTime) && !v->isDeleted()) || v->isTempItem()) { expired.push_back(std::make_pair(currentBucket->getId(), v->getKey())); return; } double r = static_cast<double>(std::rand()) / static_cast<double>(RAND_MAX); if (percent >= r) { ++totalEjectionAttempts; if (!v->eligibleForEviction()) { ++stats.numFailedEjects; return; } // Check if the key was already visited by all the cursors. bool can_evict = currentBucket->checkpointManager.eligibleForEviction(v->getKey()); if (can_evict && v->ejectValue(stats, currentBucket->ht)) { ++ejected; } } } bool visitBucket(RCPtr<VBucket> &vb) { update(); return VBucketVisitor::visitBucket(vb); } void update() { stats.expired.incr(expired.size()); store->deleteExpiredItems(expired); if (numEjected() > 0) { getLogger()->log(EXTENSION_LOG_INFO, NULL, "Paged out %ld values\n", numEjected()); } size_t num_expired = expired.size(); if (num_expired > 0) { getLogger()->log(EXTENSION_LOG_INFO, NULL, "Purged %ld expired items\n", num_expired); } totalEjected += (ejected + num_expired); ejected = 0; expired.clear(); } bool pauseVisitor() { size_t queueSize = stats.queue_size.get() + stats.flusher_todo.get(); return canPause && queueSize >= MAX_PERSISTENCE_QUEUE_SIZE; } void complete() { update(); if (stateFinalizer) { *stateFinalizer = true; } } /** * Get the number of items ejected during the visit. */ size_t numEjected() { return ejected; } /** * Get the total number of items whose values are ejected or removed due to * the expiry time. */ size_t getTotalEjected() { return totalEjected; } /** * Get the total number of ejection attempts. */ size_t getTotalEjectionAttempts() { return totalEjectionAttempts; } private: std::list<std::pair<uint16_t, std::string> > expired; EventuallyPersistentStore *store; EPStats &stats; double percent; size_t ejected; size_t totalEjected; size_t totalEjectionAttempts; time_t startTime; bool *stateFinalizer; bool canPause; }; bool ItemPager::callback(Dispatcher &d, TaskId t) { double current = static_cast<double>(stats.getTotalMemoryUsed()); double upper = static_cast<double>(stats.mem_high_wat); double lower = static_cast<double>(stats.mem_low_wat); if (available && current > upper) { ++stats.pagerRuns; double toKill = (current - static_cast<double>(lower)) / current; std::stringstream ss; ss << "Using " << stats.getTotalMemoryUsed() << " bytes of memory, paging out %0f%% of items." << std::endl; getLogger()->log(EXTENSION_LOG_INFO, NULL, ss.str().c_str(), (toKill*100.0)); available = false; shared_ptr<PagingVisitor> pv(new PagingVisitor(store, stats, toKill, &available)); std::srand(ep_real_time()); store->visit(pv, "Item pager", &d, Priority::ItemPagerPriority); double total_eject_attms = static_cast<double>(pv->getTotalEjectionAttempts()); double total_ejected = static_cast<double>(pv->getTotalEjected()); double ejection_ratio = total_eject_attms > 0 ? total_ejected / total_eject_attms : 0; if (stats.getTotalMemoryUsed() > stats.mem_high_wat && ejection_ratio < EJECTION_RATIO_THRESHOLD) { const VBucketMap &vbuckets = store->getVBuckets(); size_t num_vbuckets = vbuckets.getSize(); for (size_t i = 0; i < num_vbuckets; ++i) { assert(i <= std::numeric_limits<uint16_t>::max()); uint16_t vbid = static_cast<uint16_t>(i); RCPtr<VBucket> vb = vbuckets.getBucket(vbid); if (!vb) { continue; } vb->checkpointManager.setCheckpointExtension(false); } } } d.snooze(t, 10); return true; } bool ExpiredItemPager::callback(Dispatcher &d, TaskId t) { if (available) { ++stats.expiryPagerRuns; available = false; shared_ptr<PagingVisitor> pv(new PagingVisitor(store, stats, -1, &available, true)); store->visit(pv, "Expired item remover", &d, Priority::ItemPagerPriority, true, 10); } d.snooze(t, sleepTime); return true; } void InvalidItemDbPager::addInvalidItem(Item *itm, uint16_t vbucket_version) { uint16_t vbucket_id = itm->getVBucketId(); std::map<uint16_t, uint16_t>::iterator version_it = vb_versions.find(vbucket_id); if (version_it == vb_versions.end() || version_it->second < vbucket_version) { vb_versions[vbucket_id] = vbucket_version; } std::map<uint16_t, std::vector<int64_t>* >::iterator item_it = vb_items.find(vbucket_id); if (item_it != vb_items.end()) { item_it->second->push_back(itm->getId()); } else { std::vector<int64_t> *item_list = new std::vector<int64_t>(chunk_size * 5); item_list->push_back(itm->getId()); vb_items[vbucket_id] = item_list; } } void InvalidItemDbPager::createRangeList() { std::map<uint16_t, std::vector<int64_t>* >::iterator vbit; for (vbit = vb_items.begin(); vbit != vb_items.end(); vbit++) { std::sort(vbit->second->begin(), vbit->second->end()); std::list<row_range_t> row_range_list; createChunkListFromArray<int64_t>(vbit->second, chunk_size, row_range_list); vb_row_ranges[vbit->first] = row_range_list; delete vbit->second; } vb_items.clear(); } bool InvalidItemDbPager::callback(Dispatcher &d, TaskId t) { BlockTimer timer(&stats.diskInvaidItemDelHisto); std::map<uint16_t, std::list<row_range_t> >::iterator it = vb_row_ranges.begin(); if (it == vb_row_ranges.end()) { stats.dbCleanerComplete.set(true); return false; } std::list<row_range_t>::iterator rit = it->second.begin(); uint16_t vbid = it->first; uint16_t vb_version = vb_versions[vbid]; if (store->getRWUnderlying()->delVBucket(vbid, vb_version, *rit)) { it->second.erase(rit); if (it->second.begin() == it->second.end()) { vb_row_ranges.erase(it); } } else { d.snooze(t, 10); getLogger()->log(EXTENSION_LOG_DEBUG, NULL, "Reschedule to delete the old chunk of vbucket %d with" " the version %d from disk\n", vbid, vb_version); } return true; } <|endoftext|>
<commit_before>//-----------------------------------------------------------------------bl- //-------------------------------------------------------------------------- // // GRINS - General Reacting Incompressible Navier-Stokes // // Copyright (C) 2010-2013 The PECOS Development Team // // This library is free software; you can redistribute it and/or // modify it under the terms of the Version 2.1 GNU Lesser General // Public License 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. 51 Franklin Street, Fifth Floor, // Boston, MA 02110-1301 USA // //-----------------------------------------------------------------------el- // This class #include "grins/error_estimation_factory.h" // libMesh #include "libmesh/adjoint_residual_error_estimator.h" #include "libmesh/getpot.h" #include "libmesh/patch_recovery_error_estimator.h" #include "libmesh/qoi_set.h" #include "libmesh/kelly_error_estimator.h" namespace GRINS { ErrorEstimatorFactory::ErrorEstimatorFactory() { return; } ErrorEstimatorFactory::~ErrorEstimatorFactory() { return; } std::tr1::shared_ptr<libMesh::ErrorEstimator> ErrorEstimatorFactory::build( const GetPot& input, const libMesh::QoISet& qoi_set ) { std::string estimator_type = input("MeshAdaptivity/estimator_type", "none"); ErrorEstimatorEnum estimator_enum = this->string_to_enum( estimator_type ); std::tr1::shared_ptr<libMesh::ErrorEstimator> error_estimator; switch( estimator_enum ) { case(ADJOINT_RESIDUAL): { error_estimator.reset( new libMesh::AdjointResidualErrorEstimator ); libMesh::AdjointResidualErrorEstimator* adjoint_error_estimator = libmesh_cast_ptr<libMesh::AdjointResidualErrorEstimator*>( error_estimator.get() ); adjoint_error_estimator->qoi_set() = qoi_set; libMesh::PatchRecoveryErrorEstimator *p1 = new libMesh::PatchRecoveryErrorEstimator; adjoint_error_estimator->primal_error_estimator().reset( p1 ); libMesh::PatchRecoveryErrorEstimator *p2 = new libMesh::PatchRecoveryErrorEstimator; adjoint_error_estimator->dual_error_estimator().reset( p2 ); bool patch_reuse = input( "MeshAdaptivity/patch_reuse", false ); adjoint_error_estimator->primal_error_estimator()->error_norm.set_type( 0, H1_SEMINORM ); p1->set_patch_reuse( patch_reuse ); adjoint_error_estimator->dual_error_estimator()->error_norm.set_type( 0, H1_SEMINORM ); p2->set_patch_reuse( patch_reuse ); } break; case(KELLY): { error_estimator.reset( new libMesh::KellyErrorEstimator ); } break; case(PATCH_RECOVERY): { error_estimator.reset( new libMesh::PatchRecoveryErrorEstimator ); } break; case(ADJOINT_REFINEMENT): case(WEIGHTED_PATCH_RECOVERY): case(UNIFORM_REFINEMENT): { libmesh_not_implemented(); } break; // wat?! default: { libmesh_error(); } } // switch( estimator_enum ) return error_estimator; } ErrorEstimatorFactory::ErrorEstimatorEnum ErrorEstimatorFactory::string_to_enum( const std::string& estimator_type ) const { ErrorEstimatorEnum value; if( estimator_type == std::string("adjoint_residual") ) { value = ADJOINT_RESIDUAL; } else if( estimator_type == std::string("adjoint_refinement") ) { value = ADJOINT_REFINEMENT; } else if( estimator_type == std::string("kelly") ) { value = KELLY; } else if( estimator_type == std::string("patch_recovery") ) { value = PATCH_RECOVERY; } else if( estimator_type == std::string("weighted_patch_recovery") ) { value = WEIGHTED_PATCH_RECOVERY; } else if( estimator_type == std::string("uniform_refinement") ) { value = UNIFORM_REFINEMENT; } else { std::cerr << "Error: Invalid error estimator type " << estimator_type << std::endl << "Valid error estimator types are: adjoint_residual" << std::endl << " adjoint_refinement" << std::endl << " kelly" << std::endl << " patch_recovery" << std::endl << " weighted_patch_recovery" << std::endl << " uniform_refinement" << std::endl; libmesh_error(); } return value; } } // namespace GRINS <commit_msg>Fix a ton of "make check" breakage<commit_after>//-----------------------------------------------------------------------bl- //-------------------------------------------------------------------------- // // GRINS - General Reacting Incompressible Navier-Stokes // // Copyright (C) 2010-2013 The PECOS Development Team // // This library is free software; you can redistribute it and/or // modify it under the terms of the Version 2.1 GNU Lesser General // Public License 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. 51 Franklin Street, Fifth Floor, // Boston, MA 02110-1301 USA // //-----------------------------------------------------------------------el- // This class #include "grins/error_estimation_factory.h" // libMesh #include "libmesh/adjoint_residual_error_estimator.h" #include "libmesh/getpot.h" #include "libmesh/patch_recovery_error_estimator.h" #include "libmesh/qoi_set.h" #include "libmesh/kelly_error_estimator.h" namespace GRINS { ErrorEstimatorFactory::ErrorEstimatorFactory() { return; } ErrorEstimatorFactory::~ErrorEstimatorFactory() { return; } std::tr1::shared_ptr<libMesh::ErrorEstimator> ErrorEstimatorFactory::build( const GetPot& input, const libMesh::QoISet& qoi_set ) { std::string estimator_type = input("MeshAdaptivity/estimator_type", "patch_recovery"); ErrorEstimatorEnum estimator_enum = this->string_to_enum( estimator_type ); std::tr1::shared_ptr<libMesh::ErrorEstimator> error_estimator; switch( estimator_enum ) { case(ADJOINT_RESIDUAL): { error_estimator.reset( new libMesh::AdjointResidualErrorEstimator ); libMesh::AdjointResidualErrorEstimator* adjoint_error_estimator = libmesh_cast_ptr<libMesh::AdjointResidualErrorEstimator*>( error_estimator.get() ); adjoint_error_estimator->qoi_set() = qoi_set; libMesh::PatchRecoveryErrorEstimator *p1 = new libMesh::PatchRecoveryErrorEstimator; adjoint_error_estimator->primal_error_estimator().reset( p1 ); libMesh::PatchRecoveryErrorEstimator *p2 = new libMesh::PatchRecoveryErrorEstimator; adjoint_error_estimator->dual_error_estimator().reset( p2 ); bool patch_reuse = input( "MeshAdaptivity/patch_reuse", false ); adjoint_error_estimator->primal_error_estimator()->error_norm.set_type( 0, H1_SEMINORM ); p1->set_patch_reuse( patch_reuse ); adjoint_error_estimator->dual_error_estimator()->error_norm.set_type( 0, H1_SEMINORM ); p2->set_patch_reuse( patch_reuse ); } break; case(KELLY): { error_estimator.reset( new libMesh::KellyErrorEstimator ); } break; case(PATCH_RECOVERY): { error_estimator.reset( new libMesh::PatchRecoveryErrorEstimator ); } break; case(ADJOINT_REFINEMENT): case(WEIGHTED_PATCH_RECOVERY): case(UNIFORM_REFINEMENT): { libmesh_not_implemented(); } break; // wat?! default: { libmesh_error(); } } // switch( estimator_enum ) return error_estimator; } ErrorEstimatorFactory::ErrorEstimatorEnum ErrorEstimatorFactory::string_to_enum( const std::string& estimator_type ) const { ErrorEstimatorEnum value; if( estimator_type == std::string("adjoint_residual") ) { value = ADJOINT_RESIDUAL; } else if( estimator_type == std::string("adjoint_refinement") ) { value = ADJOINT_REFINEMENT; } else if( estimator_type == std::string("kelly") ) { value = KELLY; } else if( estimator_type == std::string("patch_recovery") ) { value = PATCH_RECOVERY; } else if( estimator_type == std::string("weighted_patch_recovery") ) { value = WEIGHTED_PATCH_RECOVERY; } else if( estimator_type == std::string("uniform_refinement") ) { value = UNIFORM_REFINEMENT; } else { std::cerr << "Error: Invalid error estimator type " << estimator_type << std::endl << "Valid error estimator types are: adjoint_residual" << std::endl << " adjoint_refinement" << std::endl << " kelly" << std::endl << " patch_recovery" << std::endl << " weighted_patch_recovery" << std::endl << " uniform_refinement" << std::endl; libmesh_error(); } return value; } } // namespace GRINS <|endoftext|>
<commit_before>#include "fmwebdav.h" fmwebdav::fmwebdav(QObject *parent) : QNetworkAccessManager(parent) ,wdRootPath(), wdUsername(), wdUassword(), wdBaseUrl(), wdCurrentConnectionType(QWebdav::HTTP){ // typical Qnetwork connection stuff goes here // probably ssl parts too } fmwebdav::~fmwebdav(){ } QString fmwebdav::hostname() const{ return wdBaseUrl.host(); } int fmwebdav::port() const{ return wdBaseUrl.port(); } QString fmwebdav::rootPath() const{ return wdRootPath;} QString fmwebdav::username() const{ return wdUsername; } QString fmwebdav::password() const{ return wdPassword; } fmwebdav::QWebdavConnectionType : fmwebdav::connectionType() const{ return wdCurrentConnectionType; } bool fmwebdav::isSSL() const{ return (wdCurrentConnectionType==QWebdav::HTTPS); } <commit_msg>oops hadn't saved all my changes yet<commit_after>#include "fmwebdav.h" fmwebdav::fmwebdav(QObject *parent) : QNetworkAccessManager(parent) ,wdRootPath(), wdUsername(), wdUassword(), wdBaseUrl(), wdCurrentConnectionType(QWebdav::HTTP){ // typical Qnetwork connection stuff goes here // probably ssl parts too } fmwebdav::~fmwebdav(){ } QString fmwebdav::hostname() const{ return wdBaseUrl.host(); } int fmwebdav::port() const{ return wdBaseUrl.port(); } QString fmwebdav::rootPath() const{ return wdRootPath;} QString fmwebdav::username() const{ return wdUsername; } QString fmwebdav::password() const{ return wdPassword; } fmwebdav::QWebdavConnectionType : fmwebdav::connectionType() const{ return wdCurrentConnectionType; } bool fmwebdav::isSSL() const{ return (wdCurrentConnectionType==QWebdav::HTTPS); } void QWebdav::setConnectionSettings(const QWebdavConnectionType connectionType, const QString *hostname, const QString *rootPath, const QString *username, const QString *password, int *port){ wdRootPath = rootPath; if ((wdRootPath.endsWith("/")){ wdRootPath.chop(1); } wdCurrentConnectionType = connectionType; wdBaseUrl.setScheme(); wdBaseUrl.setHost(hostname); wdBaseUrl.setPath(rootPath); if (port != 0) { // use user-defined port number if not 80 or 443 if ( ! ( ( (port == 80) && (wdCurrentConnectionType==QWebdav::HTTP) ) || ( (port == 443) && (wdCurrentConnectionType==QWebdav::HTTPS) ) ) ){ wdBaseUrl.setPort(port); } wdUsername = username; wdPassword = password; } <|endoftext|>
<commit_before>/* For more information, please see: http://software.sci.utah.edu The MIT License Copyright (c) 2015 Scientific Computing and Imaging Institute, University of Utah. 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 <gtest/gtest.h> #include <Core/Datatypes/Legacy/Field/Field.h> #include <Core/Datatypes/Legacy/Field/VField.h> #include <Testing/Utils/SCIRunFieldSamples.h> #include <vector> using namespace SCIRun; using namespace SCIRun::TestUtils; TEST(VFieldTest, EmptyFieldConstantBasis) { FieldHandle field = EmptyTriSurfFieldConstantBasis(DOUBLE_E); ASSERT_TRUE(field.get() != nullptr); VMesh *vmesh = field->vmesh(); VField *vfield = field->vfield(); ASSERT_EQ(vfield->num_values(), 0); // VMesh::dimension_type dim; // vfield->get_values_dimension(dim); // //std::cerr << dim[0] << ", " << dim[1] << ", " << dim[2] << std::endl; // // ASSERT_EQ(dim[0], 0); // ASSERT_EQ(dim[1], 0); // ASSERT_EQ(dim[2], 0); } TEST(VFieldTest, EmptyFieldAddValuesConstantBasis) { FieldHandle field = EmptyTriSurfFieldConstantBasis(DOUBLE_E); ASSERT_TRUE(field.get() != nullptr); VMesh *vmesh = field->vmesh(); VField *vfield = field->vfield(); vfield->resize_values(); std::vector<double> values(1); values[0] = 10.0; vfield->set_values(values); ASSERT_EQ(vfield->num_values(), 0); } TEST(VFieldTest, EmptyFieldLinearBasis) { FieldHandle field = EmptyTriSurfFieldLinearBasis(DOUBLE_E); ASSERT_TRUE(field.get() != nullptr); VMesh *vmesh = field->vmesh(); VField *vfield = field->vfield(); ASSERT_EQ(vfield->num_values(), 0); } TEST(VFieldTest, EmptyFieldAddValuesLinearBasis) { FieldHandle field = EmptyTriSurfFieldLinearBasis(DOUBLE_E); ASSERT_TRUE(field.get() != nullptr); VMesh *vmesh = field->vmesh(); VField *vfield = field->vfield(); vfield->resize_values(); std::vector<double> values(1); values[0] = 10.0; vfield->set_values(values); ASSERT_EQ(vfield->num_values(), 0); } TEST(VFieldTest, TetVolMeshAddValuesConstantBasis) { FieldHandle field = TetrahedronTetVolConstantBasis(DOUBLE_E); ASSERT_TRUE(field.get() != nullptr); VMesh *vmesh = field->vmesh(); VField *vfield = field->vfield(); vfield->resize_values(); std::vector<double> values(1); values[0] = 1.0; vfield->set_values(values); ASSERT_EQ(vfield->num_values(), 1); } TEST(VFieldTest, TetVolMeshAddValuesLinearBasis) { FieldHandle field = TetrahedronTetVolLinearBasis(DOUBLE_E); ASSERT_TRUE(field.get() != nullptr); VMesh *vmesh = field->vmesh(); VField *vfield = field->vfield(); vfield->resize_values(); std::vector<double> values(4); values[0] = 1.0; values[1] = 2.0; values[2] = 3.0; values[3] = 4.0; vfield->set_values(values); ASSERT_EQ(vfield->num_values(), 4); } TEST(VFieldTest, TetVolMeshSetFieldValueTest_2) { FieldInformation fieldinfo("TetVolMesh", 0, "double"); FieldHandle field = CreateField(fieldinfo); ASSERT_TRUE(field.get() != nullptr); VMesh *vmesh = field->vmesh(); VField *vfield = field->vfield(); vfield->resize_values(); std::cout << "An error will appear in the next line. Why is that? 2/2" << std::endl; vfield->set_value(0, 1.0); vfield->set_value(1, 2.0); vfield->set_value(2, 3.0); vfield->set_value(3, 4.0); ASSERT_EQ(vfield->num_values(), 4); } TEST(VFieldTest, TetVolMeshSetFieldValueTest_1) { FieldInformation fieldinfo("TetVolMesh", 0, "double"); FieldHandle field = CreateField(fieldinfo); ASSERT_TRUE(field.get() != nullptr); VMesh *vmesh = field->vmesh(); VField *vfield = field->vfield(); vfield->resize_fdata(); std::cout << "An error will appear in the next line. Why is that? 1/2" << std::endl; vfield->set_value(0, 1.0); vfield->set_value(1, 2.0); vfield->set_value(2, 3.0); vfield->set_value(3, 4.0); ASSERT_EQ(vfield->num_values(), 4); } <commit_msg>unit_test_setvalue_function<commit_after>/* For more information, please see: http://software.sci.utah.edu The MIT License Copyright (c) 2015 Scientific Computing and Imaging Institute, University of Utah. 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 <gtest/gtest.h> #include <Core/Datatypes/Legacy/Field/Field.h> #include <Core/Datatypes/Legacy/Field/VField.h> #include <Core/GeometryPrimitives/Point.h> #include <Testing/Utils/SCIRunFieldSamples.h> #include <vector> using namespace SCIRun; using namespace SCIRun::TestUtils; TEST(VFieldTest, EmptyFieldConstantBasis) { FieldHandle field = EmptyTriSurfFieldConstantBasis(DOUBLE_E); ASSERT_TRUE(field.get() != nullptr); VMesh *vmesh = field->vmesh(); VField *vfield = field->vfield(); ASSERT_EQ(vfield->num_values(), 0); // VMesh::dimension_type dim; // vfield->get_values_dimension(dim); // //std::cerr << dim[0] << ", " << dim[1] << ", " << dim[2] << std::endl; // // ASSERT_EQ(dim[0], 0); // ASSERT_EQ(dim[1], 0); // ASSERT_EQ(dim[2], 0); } TEST(VFieldTest, EmptyFieldAddValuesConstantBasis) { FieldHandle field = EmptyTriSurfFieldConstantBasis(DOUBLE_E); ASSERT_TRUE(field.get() != nullptr); VMesh *vmesh = field->vmesh(); VField *vfield = field->vfield(); vfield->resize_values(); std::vector<double> values(1); values[0] = 10.0; vfield->set_values(values); ASSERT_EQ(vfield->num_values(), 0); } TEST(VFieldTest, EmptyFieldLinearBasis) { FieldHandle field = EmptyTriSurfFieldLinearBasis(DOUBLE_E); ASSERT_TRUE(field.get() != nullptr); VMesh *vmesh = field->vmesh(); VField *vfield = field->vfield(); ASSERT_EQ(vfield->num_values(), 0); } TEST(VFieldTest, EmptyFieldAddValuesLinearBasis) { FieldHandle field = EmptyTriSurfFieldLinearBasis(DOUBLE_E); ASSERT_TRUE(field.get() != nullptr); VMesh *vmesh = field->vmesh(); VField *vfield = field->vfield(); vfield->resize_values(); std::vector<double> values(1); values[0] = 10.0; vfield->set_values(values); ASSERT_EQ(vfield->num_values(), 0); } TEST(VFieldTest, TetVolMeshAddValuesConstantBasis) { FieldHandle field = TetrahedronTetVolConstantBasis(DOUBLE_E); ASSERT_TRUE(field.get() != nullptr); VMesh *vmesh = field->vmesh(); VField *vfield = field->vfield(); vfield->resize_values(); std::vector<double> values(1); values[0] = 1.0; vfield->set_values(values); ASSERT_EQ(vfield->num_values(), 1); } TEST(VFieldTest, TetVolMeshAddValuesLinearBasis) { FieldHandle field = TetrahedronTetVolLinearBasis(DOUBLE_E); ASSERT_TRUE(field.get() != nullptr); VMesh *vmesh = field->vmesh(); VField *vfield = field->vfield(); vfield->resize_values(); std::vector<double> values(4); values[0] = 1.0; values[1] = 2.0; values[2] = 3.0; values[3] = 4.0; vfield->set_values(values); ASSERT_EQ(vfield->num_values(), 4); } TEST(VFieldTest, TetVolMeshSetFieldValueTest1) { FieldInformation fieldinfo("TetVolMesh", 0, "double"); FieldHandle field = CreateField(fieldinfo); ASSERT_TRUE(field.get() != nullptr); VMesh *vmesh = field->vmesh(); VField *vfield = field->vfield(); VMesh::Node::array_type onodes(4); onodes[0]=0; onodes[1]=1; onodes[2]=2; onodes[3]=3; vmesh->add_elem(onodes); for(int i=0; i<4; i++) { vmesh->add_point(SCIRun::Core::Geometry::Point(1,2,3)); } vfield->resize_values(); vfield->set_value(1.234, 0); ASSERT_EQ(vfield->num_values(), 1); } TEST(VFieldTest, TetVolMeshSetFieldValueTest2) { FieldInformation fieldinfo("TetVolMesh", 1, "double"); FieldHandle field = CreateField(fieldinfo); ASSERT_TRUE(field.get() != nullptr); VMesh *vmesh = field->vmesh(); VField *vfield = field->vfield(); VMesh::Node::array_type onodes(4); onodes[0]=0; onodes[1]=1; onodes[2]=2; onodes[3]=3; vmesh->add_elem(onodes); for(int i=0; i<4; i++) { vmesh->add_point(SCIRun::Core::Geometry::Point(1,2,3)); vfield->resize_values(); vfield->set_value(1.234+i, i); } ASSERT_EQ(vfield->num_values(), 4); for(int i=0;i<4;i++) { double tmp; vfield->get_value(tmp,i); ASSERT_EQ(tmp, 1.234+i); } } <|endoftext|>
<commit_before>#include <algorithm> #include <cmath> #include "DcoConicConstraint.hpp" #include "DcoModel.hpp" class OsiRowCut; #define EPS1 1e-5 /** Default constructor. */ DcoConicConstraint::DcoConicConstraint() { members_ = 0; size_ = 0; // cone is lorentz cone by default. type_ = OSI_QUAD; } /** Useful constructor. */ DcoConicConstraint::DcoConicConstraint(int size, OsiLorentzConeType type, int const * members) { size_ = size; type_ = type; members_ = new int[size]; std::copy(members, members+size, members_); } /** Destructor. */ DcoConicConstraint::~DcoConicConstraint() { if (members_) { delete[] members_; } } /** Copy constructor. */ DcoConicConstraint::DcoConicConstraint(const DcoConicConstraint & rhs) { setData(rhs.getSize(), rhs.getType(), rhs.getMembers()); } double DcoConicConstraint::infeasibility(BcpsModel * m, int & preferredWay) const { DcoModel * model = dynamic_cast<DcoModel*>(m); double const * sol = model->getLpSolution(); double * par_sol = new double[size_]; for (int i=0; i<size_; ++i) { par_sol[i] = sol[members_[i]]; } double infeas; if (type_==OSI_QUAD) { double term1 = par_sol[0]; double term2 = std::inner_product(par_sol+1, par_sol+size_, par_sol+1, 0.0); term2 = sqrt(term2); infeas = term2-term1; if (infeas<EPS1) { infeas = 0.0; } } else if (type_==OSI_RQUAD) { double term1 = 2.0*par_sol[0]*par_sol[1]; double term2 = std::inner_product(par_sol+2, par_sol+size_, par_sol+2, 0.0); infeas = term2-term1; if (infeas<EPS1) { infeas = 0.0; } } else { std::cerr << "Unknown cone type!" << std::endl; throw std::exception(); } delete[] par_sol; return infeas; } /** Pack Dco part into an encoded object. */ AlpsReturnStatus DcoConicConstraint::encodeDco(AlpsEncoded *encoded) { std::cerr << "Not implemented yet!" << std::endl; throw std::exception(); } /** Unpack Dco part from a encode object. */ AlpsReturnStatus DcoConicConstraint::decodeDco(AlpsEncoded &encoded) { std::cerr << "Not implemented yet!" << std::endl; throw std::exception(); } /** Create a OsiRowCut based on this constraint. */ OsiRowCut * DcoConicConstraint::createOsiRowCut() { std::cerr << "Not implemented yet!" << std::endl; throw std::exception(); } /** Compute a hash key. */ void DcoConicConstraint::hashing(BcpsModel * model) { std::cerr << "Not implemented yet!" << std::endl; throw std::exception(); } /** Check if violates a given lp solution. */ double DcoConicConstraint::violation(double const * lpSolution) { double viol = 0.0; double * par_sol = new double[size_]; for (int j=0; j<size_; ++j) { par_sol[j] = lpSolution[members_[j]]; } if (type_==OSI_QUAD) { double term1 = par_sol[0]; double term2 = std::inner_product(par_sol+1, par_sol+size_, par_sol+1, 0.0); term2 = sqrt(term2); viol = term2 - term1; } else if (type_==OSI_RQUAD) { double term1 = 2.0*par_sol[0]*par_sol[1]; double term2 = std::inner_product(par_sol+2, par_sol+size_, par_sol+2, 0.0); viol = term2 - term1; } else { std::cerr << "Unknown cone type!" << std::endl; throw std::exception(); } delete[] par_sol; // todo(aykut) this epsilon should be a parameter if (viol<EPS1) { return 0.0; } return viol; } /** Pack into a encode object. */ AlpsReturnStatus DcoConicConstraint::encode(AlpsEncoded *encoded) { std::cerr << "Not implemented yet!" << std::endl; throw std::exception(); } /** Decode a constraint from an encoded object. */ AlpsKnowledge * DcoConicConstraint::decode(AlpsEncoded& encoded) const { std::cerr << "Not implemented yet!" << std::endl; throw std::exception(); } <commit_msg>Missing header added.<commit_after>#include <algorithm> #include <numeric> #include <cmath> #include "DcoConicConstraint.hpp" #include "DcoModel.hpp" class OsiRowCut; #define EPS1 1e-5 /** Default constructor. */ DcoConicConstraint::DcoConicConstraint() { members_ = 0; size_ = 0; // cone is lorentz cone by default. type_ = OSI_QUAD; } /** Useful constructor. */ DcoConicConstraint::DcoConicConstraint(int size, OsiLorentzConeType type, int const * members) { size_ = size; type_ = type; members_ = new int[size]; std::copy(members, members+size, members_); } /** Destructor. */ DcoConicConstraint::~DcoConicConstraint() { if (members_) { delete[] members_; } } /** Copy constructor. */ DcoConicConstraint::DcoConicConstraint(const DcoConicConstraint & rhs) { setData(rhs.getSize(), rhs.getType(), rhs.getMembers()); } double DcoConicConstraint::infeasibility(BcpsModel * m, int & preferredWay) const { DcoModel * model = dynamic_cast<DcoModel*>(m); double const * sol = model->getLpSolution(); double * par_sol = new double[size_]; for (int i=0; i<size_; ++i) { par_sol[i] = sol[members_[i]]; } double infeas; if (type_==OSI_QUAD) { double term1 = par_sol[0]; double term2 = std::inner_product(par_sol+1, par_sol+size_, par_sol+1, 0.0); term2 = sqrt(term2); infeas = term2-term1; if (infeas<EPS1) { infeas = 0.0; } } else if (type_==OSI_RQUAD) { double term1 = 2.0*par_sol[0]*par_sol[1]; double term2 = std::inner_product(par_sol+2, par_sol+size_, par_sol+2, 0.0); infeas = term2-term1; if (infeas<EPS1) { infeas = 0.0; } } else { std::cerr << "Unknown cone type!" << std::endl; throw std::exception(); } delete[] par_sol; return infeas; } /** Pack Dco part into an encoded object. */ AlpsReturnStatus DcoConicConstraint::encodeDco(AlpsEncoded *encoded) { std::cerr << "Not implemented yet!" << std::endl; throw std::exception(); } /** Unpack Dco part from a encode object. */ AlpsReturnStatus DcoConicConstraint::decodeDco(AlpsEncoded &encoded) { std::cerr << "Not implemented yet!" << std::endl; throw std::exception(); } /** Create a OsiRowCut based on this constraint. */ OsiRowCut * DcoConicConstraint::createOsiRowCut() { std::cerr << "Not implemented yet!" << std::endl; throw std::exception(); } /** Compute a hash key. */ void DcoConicConstraint::hashing(BcpsModel * model) { std::cerr << "Not implemented yet!" << std::endl; throw std::exception(); } /** Check if violates a given lp solution. */ double DcoConicConstraint::violation(double const * lpSolution) { double viol = 0.0; double * par_sol = new double[size_]; for (int j=0; j<size_; ++j) { par_sol[j] = lpSolution[members_[j]]; } if (type_==OSI_QUAD) { double term1 = par_sol[0]; double term2 = std::inner_product(par_sol+1, par_sol+size_, par_sol+1, 0.0); term2 = sqrt(term2); viol = term2 - term1; } else if (type_==OSI_RQUAD) { double term1 = 2.0*par_sol[0]*par_sol[1]; double term2 = std::inner_product(par_sol+2, par_sol+size_, par_sol+2, 0.0); viol = term2 - term1; } else { std::cerr << "Unknown cone type!" << std::endl; throw std::exception(); } delete[] par_sol; // todo(aykut) this epsilon should be a parameter if (viol<EPS1) { return 0.0; } return viol; } /** Pack into a encode object. */ AlpsReturnStatus DcoConicConstraint::encode(AlpsEncoded *encoded) { std::cerr << "Not implemented yet!" << std::endl; throw std::exception(); } /** Decode a constraint from an encoded object. */ AlpsKnowledge * DcoConicConstraint::decode(AlpsEncoded& encoded) const { std::cerr << "Not implemented yet!" << std::endl; throw std::exception(); } <|endoftext|>
<commit_before>// Copyright (C) 2017 roki #ifndef INCLUDED_SROOK_ALGORITHM_LCS_HPP #define INCLUDED_SROOK_ALGORITHM_LCS_HPP #include <srook/config.hpp> #include <srook/type_traits.hpp> #include <vector> namespace srook { namespace algorithm { SROOK_INLINE_NAMESPACE(v1) /* * * generic function logest common substring (lcs). * * This function is implemented by DP. * * R1 -> std::distance(first1, last1) * R2 -> std::distance(first2, last2) * computational complexity: O(R1 * R2) * */ template <class ForwardIteartor1, class ForwardIterator2> SROOK_DEDUCED_TYPENAME enable_if< is_convertible< SROOK_DEDUCED_TYPENAME std::iterator_traits<ForwardIteartor1>::value_type, SROOK_DEDUCED_TYPENAME std::iterator_traits<ForwardIterator2>::value_type >::value, std::pair<ForwardIteartor1, ForwardIteartor1> >::type lcs(ForwardIteartor1 first1, ForwardIteartor1 last1, ForwardIterator2 first2, ForwardIterator2 last2) { if (first1 == first2 && last1 == last2) return std::make_pair(first1, last1); typedef std::vector<std::size_t> vector; typedef SROOK_DEDUCED_TYPENAME vector::size_type size_type; const size_type leftrange_size = std::distance(first1, last1), rightrange_size = std::distance(first2, last2); const size_type tb_x = leftrange_size + 1, tb_y = rightrange_size + 1; vector length_table(tb_x * tb_y); size_type len = 0, row = 0, col = 0; for(size_type i = 0; i <= leftrange_size; ++i) { for(size_type j = 0; j <= rightrange_size; ++j) { if ((!i) || (!j)) { length_table[j * tb_x + i] = 0; } else if (*std::next(first1, i - 1) == *std::next(first2, j - 1)) { length_table[j * tb_x + i] = length_table[(j - 1) * tb_x + (i - 1)] + 1; if (len < length_table[j * tb_x + i]) { len = length_table[j * tb_x + i]; row = i; col = j; } } else { length_table[j * tb_x + i] = 0; } } } if (!len) return std::make_pair(last1, last1); ForwardIteartor1 result_begin, result_end = std::next(first1, row); for (; length_table[col * tb_x + row] != 0; --row, --col); result_begin = std::next(first1, row); return std::make_pair(result_begin, result_end); } SROOK_INLINE_NAMESPACE_END } // namespace algorithm using algorithm::lcs; } // namespace srook #endif <commit_msg>add concept and remove extra code<commit_after>// Copyright (C) 2017 roki #ifndef INCLUDED_SROOK_ALGORITHM_LCS_HPP #define INCLUDED_SROOK_ALGORITHM_LCS_HPP #include <srook/config.hpp> #include <srook/type_traits.hpp> #include <srook/cxx20/concepts/iterator/Iterator.hpp> #include <vector> namespace srook { namespace algorithm { SROOK_INLINE_NAMESPACE(v1) /* * * generic function longest common substring (lcs). * * This function is implemented by DP. * * R1 -> std::distance(first1, last1) * R2 -> std::distance(first2, last2) * computational complexity: O(R1 * R2) * */ #ifdef SROOK_ENABLE_CONCEPTS template <srook::concepts::Iterator ForwardIteartor1, srook::concepts::Iterator ForwardIterator2> #else template <class ForwardIteartor1, class ForwardIterator2> #endif SROOK_DEDUCED_TYPENAME enable_if< is_convertible< SROOK_DEDUCED_TYPENAME std::iterator_traits<ForwardIteartor1>::value_type, SROOK_DEDUCED_TYPENAME std::iterator_traits<ForwardIterator2>::value_type >::value, std::pair<ForwardIteartor1, ForwardIteartor1> >::type lcs(ForwardIteartor1 first1, ForwardIteartor1 last1, ForwardIterator2 first2, ForwardIterator2 last2) { if (first1 == first2 && last1 == last2) return std::make_pair(first1, last1); typedef std::vector<std::size_t> vector; typedef SROOK_DEDUCED_TYPENAME vector::size_type size_type; const size_type leftrange_size = std::distance(first1, last1), rightrange_size = std::distance(first2, last2); const size_type tb_x = leftrange_size + 1, tb_y = rightrange_size + 1; vector length_table(tb_x * tb_y, 0); size_type len = 0, row = 0, col = 0; for(size_type i = 0; i <= leftrange_size; ++i) { for(size_type j = 0; j <= rightrange_size; ++j) { if (!((!i) || (!j)) && *std::next(first1, i - 1) == *std::next(first2, j - 1)) { length_table[j * tb_x + i] = length_table[(j - 1) * tb_x + (i - 1)] + 1; if (len < length_table[j * tb_x + i]) { len = length_table[j * tb_x + i]; row = i; col = j; } } } } if (!len) return std::make_pair(last1, last1); ForwardIteartor1 result_end = std::next(first1, row); for (; length_table[col * tb_x + row] != 0; --row, --col); return std::make_pair(std::next(first1, row), result_end); } SROOK_INLINE_NAMESPACE_END } // namespace algorithm using algorithm::lcs; } // namespace srook #endif <|endoftext|>
<commit_before>#include <osg/Notify> #include <osg/Geometry> #include <osg/AnimationPath> #include <osgDB/Registry> #include <osgDB/Input> #include <osgDB/Output> using namespace osg; using namespace osgDB; // forward declare functions to use later. bool AnimationPath_readLocalData(osg::Object &obj, osgDB::Input &fr); bool AnimationPath_writeLocalData(const osg::Object &obj, osgDB::Output &fw); // register the read and write functions with the osgDB::Registry. osgDB::RegisterDotOsgWrapperProxy AnimationPath_Proxy ( new osg::AnimationPath, "AnimationPath", "Object AnimationPath", AnimationPath_readLocalData, AnimationPath_writeLocalData, DotOsgWrapper::READ_AND_WRITE ); bool AnimationPath_readLocalData(osg::Object &obj, osgDB::Input &fr) { osg::AnimationPath *ap = dynamic_cast<osg::AnimationPath*>(&obj); if (!ap) return false; bool itAdvanced = false; if (fr[0].matchWord("LoopMode")) { if (fr[1].matchWord("SWING")) { ap->setLoopMode(AnimationPath::SWING); fr += 2; itAdvanced = true; } else if (fr[1].matchWord("LOOP")) { ap->setLoopMode(AnimationPath::LOOP); fr += 2; itAdvanced = true; } else if (fr[1].matchWord("NO_LOOPING")) { ap->setLoopMode(AnimationPath::NO_LOOPING); fr += 2; itAdvanced = true; } } if (fr.matchSequence("ControlPoints {")) { int entry = fr[0].getNoNestedBrackets(); fr += 2; float time; Vec3 position,scale; Quat rotation; while (!fr.eof() && fr[0].getNoNestedBrackets()>entry) { if (fr[0].getFloat(time) && fr[1].getFloat(position[0]) && fr[2].getFloat(position[1]) && fr[3].getFloat(position[2]) && fr[4].getFloat(rotation[0]) && fr[5].getFloat(rotation[1]) && fr[6].getFloat(rotation[2]) && fr[7].getFloat(rotation[3]) && fr[8].getFloat(scale[0]) && fr[9].getFloat(scale[1]) && fr[10].getFloat(scale[2])) { osg::AnimationPath::ControlPoint ctrlPoint; ctrlPoint._position = position; ctrlPoint._rotation = rotation; ctrlPoint._scale = scale; ap->insert(time, ctrlPoint); fr+=11; } else fr.advanceOverCurrentFieldOrBlock(); } itAdvanced = true; } return itAdvanced; } bool AnimationPath_writeLocalData(const osg::Object &obj, osgDB::Output &fw) { const osg::AnimationPath* ap = dynamic_cast<const osg::AnimationPath*>(&obj); if (!ap) return false; fw.indent() << "LoopMode "; switch(ap->getLoopMode()) { case AnimationPath::SWING: fw << "SWING" <<std::endl; break; case AnimationPath::LOOP: fw << "LOOP"<<std::endl; break; case AnimationPath::NO_LOOPING: fw << "NO_LOOPING"<<std::endl; break; } const AnimationPath::TimeControlPointMap& tcpm = ap->getTimeControlPointMap(); fw.indent() << "ControlPoints {"<< std::endl; fw.moveIn(); for (AnimationPath::TimeControlPointMap::const_iterator itr=tcpm.begin(); itr!=tcpm.end(); ++itr) { fw.indent() << itr->first << " " << itr->second._position << " " << itr->second._rotation << " " << itr->second._scale << std::endl; } fw.moveOut(); fw.indent() << "}"<< std::endl; return true; } // forward declare functions to use later. bool AnimationPathCallback_readLocalData(osg::Object &obj, osgDB::Input &fr); bool AnimationPathCallback_writeLocalData(const osg::Object &obj, osgDB::Output &fw); // register the read and write functions with the osgDB::Registry. osgDB::RegisterDotOsgWrapperProxy AnimationPathCallback_Proxy ( new osg::AnimationPathCallback, "AnimationPathCallback", "Object AnimationPathCallback", AnimationPathCallback_readLocalData, AnimationPathCallback_writeLocalData, DotOsgWrapper::READ_AND_WRITE ); bool AnimationPathCallback_readLocalData(osg::Object &obj, osgDB::Input &fr) { osg::AnimationPathCallback *apc = dynamic_cast<osg::AnimationPathCallback*>(&obj); if (!apc) return false; bool iteratorAdvanced = false; if (fr.matchSequence("pivotPoint %f %f %f")) { osg::Vec3 pivot; fr[1].getFloat(pivot[0]); fr[2].getFloat(pivot[1]); fr[3].getFloat(pivot[2]); apc->setPivotPoint(pivot); fr += 4; iteratorAdvanced = true; } if (fr.matchSequence("timeOffset %f")) { fr[1].getFloat(apc->_timeOffset); fr+=2; iteratorAdvanced = true; } else if(fr.matchSequence("timeMultiplier %f")) { fr[1].getFloat(apc->_timeMultiplier); fr+=2; iteratorAdvanced = true; } static osg::ref_ptr<osg::AnimationPath> s_path = new osg::AnimationPath; ref_ptr<osg::Object> object = fr.readObjectOfType(*s_path); if (object.valid()) { osg::AnimationPath* animpath = dynamic_cast<osg::AnimationPath*>(object.get()); if (animpath) apc->setAnimationPath(animpath); iteratorAdvanced = true; } return iteratorAdvanced; } bool AnimationPathCallback_writeLocalData(const osg::Object &obj, osgDB::Output &fw) { const osg::AnimationPathCallback* apc = dynamic_cast<const osg::AnimationPathCallback*>(&obj); if (!apc) return false; fw.indent() <<"pivotPoint " <<apc->getPivotPoint()<<std::endl; fw.indent() <<"timeOffset " <<apc->_timeOffset<<std::endl; fw.indent() <<"timeMultiplier " <<apc->_timeMultiplier << std::endl; if (apc->getAnimationPath()) { fw.writeObject(*(apc->getAnimationPath())); } return true; } <commit_msg>Improved precision of AnimationPath IO.<commit_after>#include <osg/Notify> #include <osg/Geometry> #include <osg/AnimationPath> #include <osgDB/Registry> #include <osgDB/Input> #include <osgDB/Output> using namespace osg; using namespace osgDB; // forward declare functions to use later. bool AnimationPath_readLocalData(osg::Object &obj, osgDB::Input &fr); bool AnimationPath_writeLocalData(const osg::Object &obj, osgDB::Output &fw); // register the read and write functions with the osgDB::Registry. osgDB::RegisterDotOsgWrapperProxy AnimationPath_Proxy ( new osg::AnimationPath, "AnimationPath", "Object AnimationPath", AnimationPath_readLocalData, AnimationPath_writeLocalData, DotOsgWrapper::READ_AND_WRITE ); bool AnimationPath_readLocalData(osg::Object &obj, osgDB::Input &fr) { osg::AnimationPath *ap = dynamic_cast<osg::AnimationPath*>(&obj); if (!ap) return false; bool itAdvanced = false; if (fr[0].matchWord("LoopMode")) { if (fr[1].matchWord("SWING")) { ap->setLoopMode(AnimationPath::SWING); fr += 2; itAdvanced = true; } else if (fr[1].matchWord("LOOP")) { ap->setLoopMode(AnimationPath::LOOP); fr += 2; itAdvanced = true; } else if (fr[1].matchWord("NO_LOOPING")) { ap->setLoopMode(AnimationPath::NO_LOOPING); fr += 2; itAdvanced = true; } } if (fr.matchSequence("ControlPoints {")) { int entry = fr[0].getNoNestedBrackets(); fr += 2; double time; Vec3d position,scale; Quat rotation; while (!fr.eof() && fr[0].getNoNestedBrackets()>entry) { if (fr[0].getFloat(time) && fr[1].getFloat(position[0]) && fr[2].getFloat(position[1]) && fr[3].getFloat(position[2]) && fr[4].getFloat(rotation[0]) && fr[5].getFloat(rotation[1]) && fr[6].getFloat(rotation[2]) && fr[7].getFloat(rotation[3]) && fr[8].getFloat(scale[0]) && fr[9].getFloat(scale[1]) && fr[10].getFloat(scale[2])) { osg::AnimationPath::ControlPoint ctrlPoint; ctrlPoint._position = position; ctrlPoint._rotation = rotation; ctrlPoint._scale = scale; ap->insert(time, ctrlPoint); fr+=11; } else fr.advanceOverCurrentFieldOrBlock(); } itAdvanced = true; } return itAdvanced; } bool AnimationPath_writeLocalData(const osg::Object &obj, osgDB::Output &fw) { const osg::AnimationPath* ap = dynamic_cast<const osg::AnimationPath*>(&obj); if (!ap) return false; fw.indent() << "LoopMode "; switch(ap->getLoopMode()) { case AnimationPath::SWING: fw << "SWING" <<std::endl; break; case AnimationPath::LOOP: fw << "LOOP"<<std::endl; break; case AnimationPath::NO_LOOPING: fw << "NO_LOOPING"<<std::endl; break; } const AnimationPath::TimeControlPointMap& tcpm = ap->getTimeControlPointMap(); fw.indent() << "ControlPoints {"<< std::endl; fw.moveIn(); int prec = fw.precision(); fw.precision(15); for (AnimationPath::TimeControlPointMap::const_iterator itr=tcpm.begin(); itr!=tcpm.end(); ++itr) { fw.indent() << itr->first << " " << itr->second._position << " " << itr->second._rotation << " " << itr->second._scale << std::endl; } fw.precision(prec); fw.moveOut(); fw.indent() << "}"<< std::endl; return true; } // forward declare functions to use later. bool AnimationPathCallback_readLocalData(osg::Object &obj, osgDB::Input &fr); bool AnimationPathCallback_writeLocalData(const osg::Object &obj, osgDB::Output &fw); // register the read and write functions with the osgDB::Registry. osgDB::RegisterDotOsgWrapperProxy AnimationPathCallback_Proxy ( new osg::AnimationPathCallback, "AnimationPathCallback", "Object AnimationPathCallback", AnimationPathCallback_readLocalData, AnimationPathCallback_writeLocalData, DotOsgWrapper::READ_AND_WRITE ); bool AnimationPathCallback_readLocalData(osg::Object &obj, osgDB::Input &fr) { osg::AnimationPathCallback *apc = dynamic_cast<osg::AnimationPathCallback*>(&obj); if (!apc) return false; bool iteratorAdvanced = false; if (fr.matchSequence("pivotPoint %f %f %f")) { osg::Vec3 pivot; fr[1].getFloat(pivot[0]); fr[2].getFloat(pivot[1]); fr[3].getFloat(pivot[2]); apc->setPivotPoint(pivot); fr += 4; iteratorAdvanced = true; } if (fr.matchSequence("timeOffset %f")) { fr[1].getFloat(apc->_timeOffset); fr+=2; iteratorAdvanced = true; } else if(fr.matchSequence("timeMultiplier %f")) { fr[1].getFloat(apc->_timeMultiplier); fr+=2; iteratorAdvanced = true; } static osg::ref_ptr<osg::AnimationPath> s_path = new osg::AnimationPath; ref_ptr<osg::Object> object = fr.readObjectOfType(*s_path); if (object.valid()) { osg::AnimationPath* animpath = dynamic_cast<osg::AnimationPath*>(object.get()); if (animpath) apc->setAnimationPath(animpath); iteratorAdvanced = true; } return iteratorAdvanced; } bool AnimationPathCallback_writeLocalData(const osg::Object &obj, osgDB::Output &fw) { const osg::AnimationPathCallback* apc = dynamic_cast<const osg::AnimationPathCallback*>(&obj); if (!apc) return false; fw.indent() <<"pivotPoint " <<apc->getPivotPoint()<<std::endl; fw.indent() <<"timeOffset " <<apc->_timeOffset<<std::endl; fw.indent() <<"timeMultiplier " <<apc->_timeMultiplier << std::endl; if (apc->getAnimationPath()) { fw.writeObject(*(apc->getAnimationPath())); } return true; } <|endoftext|>
<commit_before>#include <iostream> #include <cmath> #include <fstream> #include <cstdio> #include <sstream> #include <cassert> #include <vector> #include <string> #include <cstdlib> #include <iomanip> #include "bond_length.h" using namespace std; extern int totalatoms; //referring to totalatoms in extraction.cpp extern vector< vector<string> > vector_coords; int bond_distance = 1.55; //average bond distance in Angstroms int i, j; string string_atom1, string_atom2; string string_x1, string_x2, string_y1, string_y2, string_z1, string_z2; //xyz coordinates as strings double double_x1, double_x2, double_y1, double_y2, double_z1, double_z2; //xyz coordinates as doubles vector<double> atomic_distance; //creation of 2D vector for interatomic distances extern vector< vector<int> > bond_exist; //creation of 2D vector: 1 for bond exists and 0 for bond does not exist void Bond_Length::atom_distance() { ofstream log; log.open("log.txt", ios::app); cout << "Interatomic distances (in Angstroms): " << endl; for(i = 0; i < i < totalatoms; i++) { for(j = i + 1; j < totalatoms; j++) { string_atom1 = (vector_coords[i][0]); string_atom2 = (vector_coords[j][0]); string_x1 = (vector_coords[i][2]); string_x2 = (vector_coords[j][2]); string_y1 = (vector_coords[i][3]); string_y2 = (vector_coords[j][3]); string_z1 = (vector_coords[i][4]); string_z2 = (vector_coords[j][4]); double_x1 = atof(string_x1.c_str()); //converting xyz coordinate strings to doubles double_x2 = atof(string_x2.c_str()); double_y1 = atof(string_y1.c_str()); double_y2 = atof(string_y2.c_str()); double_z1 = atof(string_z1.c_str()); double_z2 = atof(string_z2.c_str()); double distance = (sqrt( ((pow(double_x2 - double_x1, 2))) + ((pow(double_y2 - double_y1, 2))) + //calculation of interatomic distances ((pow(double_z2 - double_y2, 2))))); atomic_distance.push_back(distance); //temporary array for calculated distance cout << string_atom1 << " " << string_atom2 << " " << distance << endl; } } for(i = 0; i < totalatoms; i++) { for(j = i + 1; j < totalatoms; j++) { if(atomic_distance[i] > bond_distance) { //if interatomic distance is greater than 1.55 Angstroms bond_exist[i][j] = 0; //0 for non-bonding } else bond_exist[i][j] = 1; //1 for bonding } } } <commit_msg>Delete bond_length.cpp<commit_after><|endoftext|>
<commit_before>#pragma once #include <GLFW/glfw3.h> #include <json/json.h> #include <vector> class Input { public: ///The information needed to identify a button. struct Button { ///A string describing the action, e.g "Fire". char action[255]; ///The GLFW key to press. int key; ///The GLFW state of that key. int state; }; ///The buttons to register. std::vector<Button*> buttons; /// Gets the input singleton instance. /** * @return The input instance. */ static Input& GetInstance() { static Input instance; return instance; } /// Sets the window to check for input against. /** * @param window The target GLFWwindow. */ void SetWindow(GLFWwindow* window); /// Check if a button was activated this frame. /** * @param index The index of the button in the buttons array. */ bool CheckButton(int index) const; ///Saves the buttons to a Json value. /** * @return The saved json value. */ Json::Value Save() const; ///Saves the buttons to a Json value. /** * @param buttonsNode the json value to load. */ void Load(const Json::Value& buttonsNode); private: GLFWwindow* window; Input() {} Input(Input const&); void operator=(Input const&); }; <commit_msg>Fix indentation in Input<commit_after>#pragma once #include <GLFW/glfw3.h> #include <json/json.h> #include <vector> class Input { public: /// The information needed to identify a button. struct Button { /// A string describing the action, e.g "Fire". char action[255]; /// The GLFW key to press. int key; /// The GLFW state of that key. int state; }; /// The buttons to register. std::vector<Button*> buttons; /// Gets the input singleton instance. /** * @return The input instance. */ static Input& GetInstance() { static Input instance; return instance; } /// Sets the window to check for input against. /** * @param window The target GLFWwindow. */ void SetWindow(GLFWwindow* window); /// Check if a button was activated this frame. /** * @param index The index of the button in the buttons array. */ bool CheckButton(int index) const; ///Saves the buttons to a Json value. /** * @return The saved json value. */ Json::Value Save() const; ///Saves the buttons to a Json value. /** * @param buttonsNode the json value to load. */ void Load(const Json::Value& buttonsNode); private: GLFWwindow* window; Input() {} Input(Input const&); void operator=(Input const&); }; <|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #ifndef INCLUDED_STARMATH_INC_CURSOR_HXX #define INCLUDED_STARMATH_INC_CURSOR_HXX #include "node.hxx" #include "caret.hxx" /** Factor to multiple the squared horizontical distance with * Used for Up and Down movement. */ #define HORIZONTICAL_DISTANCE_FACTOR 10 /** Enum of direction for movement */ enum SmMovementDirection{ MoveUp, MoveDown, MoveLeft, MoveRight }; /** Enum of elements that can inserted into a formula */ enum SmFormulaElement{ BlankElement, FactorialElement, PlusElement, MinusElement, CDotElement, EqualElement, LessThanElement, GreaterThanElement, PercentElement }; /** Bracket types that can be inserted */ enum SmBracketType { /** None brackets, left command "none" */ NoneBrackets, /** Round brackets, left command "(" */ RoundBrackets, /**Square brackets, left command "[" */ SquareBrackets, /** Double square brackets, left command "ldbracket" */ DoubleSquareBrackets, /** Line brackets, left command "lline" */ LineBrackets, /** Double line brackets, left command "ldline" */ DoubleLineBrackets, /** Curly brackets, left command "lbrace" */ CurlyBrackets, /** Angle brackets, left command "langle" */ AngleBrackets, /** Ceiling brackets, left command "lceil" */ CeilBrackets, /** Floor brackets, left command "lfloor" */ FloorBrackets }; /** A list of nodes */ typedef std::list<SmNode*> SmNodeList; class SmDocShell; /** Formula cursor * * This class is used to represent a cursor in a formula, which can be used to manipulate * an formula programmatically. * @remarks This class is a very intimite friend of SmDocShell. */ class SmCursor{ public: SmCursor(SmNode* tree, SmDocShell* pShell) : anchor(NULL) , position(NULL) , pTree(tree) , pDocShell(pShell) , pGraph(NULL) , pClipboard(NULL) , nEditSections(0) , bIsEnabledSetModifiedSmDocShell(false) { //Build graph BuildGraph(); } ~SmCursor() { SetClipboard(); delete pGraph; pGraph = NULL; } /** Gets the anchor */ SmCaretPos GetAnchor(){ return anchor->CaretPos; } /** Get position */ SmCaretPos GetPosition() const { return position->CaretPos; } /** True, if the cursor has a selection */ bool HasSelection() { return anchor != position; } /** Move the position of this cursor */ void Move(OutputDevice* pDev, SmMovementDirection direction, bool bMoveAnchor = true); /** Move to the caret position closet to a given point */ void MoveTo(OutputDevice* pDev, Point pos, bool bMoveAnchor = true); /** Delete the current selection or do nothing */ void Delete(); /** Delete selection, previous element or merge lines * * This method implements the behaviour of backspace. */ void DeletePrev(OutputDevice* pDev); /** Insert text at the current position */ void InsertText(const OUString& aString); /** Insert an element into the formula */ void InsertElement(SmFormulaElement element); /** Insert a command specified in commands.src*/ void InsertCommand(sal_uInt16 nCommand); /** Insert command text translated into line entries at position * * Note: This method uses the parser to translate a command text into a * tree, then it copies line entries from this tree into the current tree. * Will not work for commands such as newline or ##, if position is in a matrix. * This will work for stuff like "A intersection B". But stuff spaning multiple lines * or dependent on the context which position is placed in will not work! */ void InsertCommandText(const OUString& aCommandText); /** Insert a special node created from aString * * Used for handling insert request from the "catalog" dialog. * The provided string should be formatet as the desired command: %phi * Note: this method ONLY supports commands defined in Math.xcu * * For more complex expressions use InsertCommandText, this method doesn't * use SmParser, this means that it's faster, but not as strong. */ void InsertSpecial(const OUString& aString); /** Create sub-/super script * * If there's a selection, it will be move into the appropriate sub-/super scription * of the node in front of it. If there's no node in front of position (or the selection), * a sub-/super scription of a new SmPlaceNode will be made. * * If there's is an existing subscription of the node, the caret will be moved into it, * and any selection will replace it. */ void InsertSubSup(SmSubSup eSubSup); /** Create a limit on an SmOperNode * * This this method only work if the caret is inside an SmOperNode, or to the right of one. * Notice also that this method ignores any selection made. * * @param bMoveCaret If true that caret will be moved into the limit. * * @returns True, if the caret was in a context where this operation was possible. */ bool InsertLimit(SmSubSup eSubSup, bool bMoveCaret = true); /** Insert a new row or newline * * Inserts a new row if position is in an matrix or stack command. * Otherwise a newline is inserted if we're in a toplevel line. * * @returns True, if a new row/line could be inserted. * * @remarks If the caret is placed in a subline of a command that doesn't support * this operator the method returns FALSE, and doesn't do anything. */ bool InsertRow(); /** Insert a fraction, use selection as numerator */ void InsertFraction(); /** Create brackets around current selection, or new SmPlaceNode */ void InsertBrackets(SmBracketType eBracketType); /** Copy the current selection */ void Copy(); /** Cut the current selection */ void Cut(){ Copy(); Delete(); } /** Paste the clipboard */ void Paste(); /** Returns true if more than one node is selected * * This method is used for implementing backspace and delete. * If one of these causes a complex selection, e.g. a node with * subnodes or similar, this should not be deleted imidiately. */ bool HasComplexSelection(); /** Finds the topmost node in a visual line * * If MoveUpIfSelected is true, this will move up to the parent line * if the parent of the current line is selected. */ static SmNode* FindTopMostNodeInLine(SmNode* pSNode, bool MoveUpIfSelected = false); /** Draw the caret */ void Draw(OutputDevice& pDev, Point Offset, bool isCaretVisible); bool IsAtTailOfBracket(SmBracketType eBracketType, SmBraceNode** ppBraceNode = NULL) const; void MoveAfterBracket(SmBraceNode* pBraceNode, bool bMoveAnchor = true); private: friend class SmDocShell; SmCaretPosGraphEntry *anchor, *position; /** Formula tree */ SmNode* pTree; /** Owner of the formula tree */ SmDocShell* pDocShell; /** Graph over caret position in the current tree */ SmCaretPosGraph* pGraph; /** Clipboard holder */ SmNodeList* pClipboard; /** Returns a node that is selected, if any could be found */ SmNode* FindSelectedNode(SmNode* pNode); /** Is this one of the nodes used to compose a line * * These are SmExpression, SmBinHorNode, SmUnHorNode etc. */ static bool IsLineCompositionNode(SmNode* pNode); /** Count number of selected nodes, excluding line composition nodes * * Note this function doesn't count line composition nodes and it * does count all subnodes as well as the owner nodes. * * Used by SmCursor::HasComplexSelection() */ int CountSelectedNodes(SmNode* pNode); /** Convert a visual line to a list * * Note this method will delete all the nodes that will no longer be needed. * that includes pLine! * This method also deletes SmErrorNode's as they're just meta info in the line. */ static SmNodeList* LineToList(SmStructureNode* pLine, SmNodeList* pList = new SmNodeList()); /** Auxiliary function for calling LineToList on a node * * This method sets pNode = NULL and remove it from it's parent. * (Assuming it has a parent, and is a child of it). */ static SmNodeList* NodeToList(SmNode*& rpNode, SmNodeList* pList = new SmNodeList()){ //Remove from parent and NULL rpNode SmNode* pNode = rpNode; if(rpNode && rpNode->GetParent()){ //Don't remove this, correctness relies on it int index = rpNode->GetParent()->IndexOfSubNode(rpNode); if(index != -1) rpNode->GetParent()->SetSubNode(index, NULL); } rpNode = NULL; //Create line from node if(pNode && IsLineCompositionNode(pNode)) return LineToList((SmStructureNode*)pNode, pList); if(pNode) pList->push_front(pNode); return pList; } /** Clone a visual line to a list * * Doesn't clone SmErrorNode's these are ignored, as they are context dependent metadata. */ static SmNodeList* CloneLineToList(SmStructureNode* pLine, bool bOnlyIfSelected = false, SmNodeList* pList = new SmNodeList()); /** Build pGraph over caret positions */ void BuildGraph(); /** Insert new nodes in the tree after position */ void InsertNodes(SmNodeList* pNewNodes); /** tries to set position to a specific SmCaretPos * * @returns false on failure to find the position in pGraph. */ bool SetCaretPosition(SmCaretPos pos, bool moveAnchor = false); /** Set selected on nodes of the tree */ void AnnotateSelection(); /** Set the clipboard, and release current clipboard * * Call this method with NULL to reset the clipboard * @remarks: This method takes ownership of pList. */ void SetClipboard(SmNodeList* pList = NULL); /** Clone list of nodes (creates a deep clone) */ static SmNodeList* CloneList(SmNodeList* pList); /** Find an iterator pointing to the node in pLineList following aCaretPos * * If aCaretPos::pSelectedNode cannot be found it is assumed that it's in front of pLineList, * thus not an element in pLineList. In this case this method returns an iterator to the * first element in pLineList. * * If the current position is inside an SmTextNode, this node will be split in two, for this * reason you should beaware that iterators to elements in pLineList may be invalidated, and * that you should call PatchLineList() with this iterator if no action is taken. */ static SmNodeList::iterator FindPositionInLineList(SmNodeList* pLineList, SmCaretPos aCaretPos); /** Patch a line list after modification, merge SmTextNode, remove SmPlaceNode etc. * * @param pLineList The line list to patch * @param aIter Iterator pointing to the element that needs to be patched with it's previous. * * When the list is patched text nodes before and after aIter will be merged. * If there's an, in the context, inappropriate SmPlaceNode before or after aIter it will also be * removed. * * @returns A caret position equivalent to one selecting the node before aIter, the method returns * an invalid SmCaretPos to indicate placement in front of the line. */ static SmCaretPos PatchLineList(SmNodeList* pLineList, SmNodeList::iterator aIter); /** Take selected nodes from a list * * Puts the selected nodes into pSelectedNodes, or if pSelectedNodes is NULL deletes * the selected nodes. * Note: If there's a selection inside an SmTextNode this node will be split, and it * will not be merged when the selection have been taken. Use PatchLineList on the * iterator returns to fix this. * * @returns An iterator pointing to the element following the selection taken. */ static SmNodeList::iterator TakeSelectedNodesFromList(SmNodeList *pLineList, SmNodeList *pSelectedNodes = NULL); /** Create an instance of SmMathSymbolNode usable for brackets */ static SmNode *CreateBracket(SmBracketType eBracketType, bool bIsLeft); /** The number of times BeginEdit have been called * Used to allow nesting of BeginEdit() and EndEdit() sections */ int nEditSections; /** Holds data for BeginEdit() and EndEdit() */ bool bIsEnabledSetModifiedSmDocShell; /** Begin edit section where the tree will be modified */ void BeginEdit(); /** End edit section where the tree will be modified */ void EndEdit(); /** Finish editing * * Finishes editing by parsing pLineList and inserting back into pParent at nParentIndex. * This method also rebuilts the graph, annotates the selection, sets caret position and * Calls EndEdit. * * @remarks Please note that this method will delete pLineList, as the elements are taken. * * @param pLineList List the constitutes the edited line. * @param pParent Parent to which the line should be inserted. * @param nParentIndex Index in parent where the line should be inserted. * @param PosAfterEdit Caret position to look for after rebuilding graph. * @param pStartLine Line to take first position in, if PosAfterEdit cannot be found, * leave it NULL for pLineList. */ void FinishEdit(SmNodeList* pLineList, SmStructureNode* pParent, int nParentIndex, SmCaretPos PosAfterEdit, SmNode* pStartLine = NULL); /** Request the formula is repainted */ void RequestRepaint(); }; /** Minimalistic recursive decent SmNodeList parser * * This parser is used to take a list of nodes that constitues a line * and parse them to a tree of SmBinHorNode, SmUnHorNode and SmExpression. * * Please note, this will not handle all kinds of nodes, only nodes that * constitues and entry in a line. * * Below is an EBNF representation of the grammar used for this parser: * \code * Expression -> Relation* * Relation -> Sum [(=|<|>|...) Sum]* * Sum -> Product [(+|-) Product]* * Product -> Factor [(*|/) Factor]* * Factor -> [+|-|-+|...]* Factor | Postfix * Postfix -> node [!]* * \endcode */ class SmNodeListParser{ public: /** Create an instance of SmNodeListParser */ SmNodeListParser(){ pList = NULL; } /** Parse a list of nodes to an expression * * If bDeleteErrorNodes is true, old error nodes will be deleted. */ SmNode* Parse(SmNodeList* list, bool bDeleteErrorNodes = true); /** True, if the token is an operator */ static bool IsOperator(const SmToken &token); /** True, if the token is a relation operator */ static bool IsRelationOperator(const SmToken &token); /** True, if the token is a sum operator */ static bool IsSumOperator(const SmToken &token); /** True, if the token is a product operator */ static bool IsProductOperator(const SmToken &token); /** True, if the token is a unary operator */ static bool IsUnaryOperator(const SmToken &token); /** True, if the token is a postfix operator */ static bool IsPostfixOperator(const SmToken &token); private: SmNodeList* pList; /** Get the current terminal */ SmNode* Terminal(){ if(pList->size() > 0) return pList->front(); return NULL; } /** Move to next terminal */ SmNode* Next(){ pList->pop_front(); return Terminal(); } /** Take the current terminal */ SmNode* Take(){ SmNode* pRetVal = Terminal(); Next(); return pRetVal; } SmNode* Expression(); SmNode* Relation(); SmNode* Sum(); SmNode* Product(); SmNode* Factor(); SmNode* Postfix(); SmNode* Error(); }; #endif // INCLUDED_STARMATH_INC_CURSOR_HXX /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <commit_msg>typo: formatet -> formated<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #ifndef INCLUDED_STARMATH_INC_CURSOR_HXX #define INCLUDED_STARMATH_INC_CURSOR_HXX #include "node.hxx" #include "caret.hxx" /** Factor to multiple the squared horizontical distance with * Used for Up and Down movement. */ #define HORIZONTICAL_DISTANCE_FACTOR 10 /** Enum of direction for movement */ enum SmMovementDirection{ MoveUp, MoveDown, MoveLeft, MoveRight }; /** Enum of elements that can inserted into a formula */ enum SmFormulaElement{ BlankElement, FactorialElement, PlusElement, MinusElement, CDotElement, EqualElement, LessThanElement, GreaterThanElement, PercentElement }; /** Bracket types that can be inserted */ enum SmBracketType { /** None brackets, left command "none" */ NoneBrackets, /** Round brackets, left command "(" */ RoundBrackets, /**Square brackets, left command "[" */ SquareBrackets, /** Double square brackets, left command "ldbracket" */ DoubleSquareBrackets, /** Line brackets, left command "lline" */ LineBrackets, /** Double line brackets, left command "ldline" */ DoubleLineBrackets, /** Curly brackets, left command "lbrace" */ CurlyBrackets, /** Angle brackets, left command "langle" */ AngleBrackets, /** Ceiling brackets, left command "lceil" */ CeilBrackets, /** Floor brackets, left command "lfloor" */ FloorBrackets }; /** A list of nodes */ typedef std::list<SmNode*> SmNodeList; class SmDocShell; /** Formula cursor * * This class is used to represent a cursor in a formula, which can be used to manipulate * an formula programmatically. * @remarks This class is a very intimite friend of SmDocShell. */ class SmCursor{ public: SmCursor(SmNode* tree, SmDocShell* pShell) : anchor(NULL) , position(NULL) , pTree(tree) , pDocShell(pShell) , pGraph(NULL) , pClipboard(NULL) , nEditSections(0) , bIsEnabledSetModifiedSmDocShell(false) { //Build graph BuildGraph(); } ~SmCursor() { SetClipboard(); delete pGraph; pGraph = NULL; } /** Gets the anchor */ SmCaretPos GetAnchor(){ return anchor->CaretPos; } /** Get position */ SmCaretPos GetPosition() const { return position->CaretPos; } /** True, if the cursor has a selection */ bool HasSelection() { return anchor != position; } /** Move the position of this cursor */ void Move(OutputDevice* pDev, SmMovementDirection direction, bool bMoveAnchor = true); /** Move to the caret position closet to a given point */ void MoveTo(OutputDevice* pDev, Point pos, bool bMoveAnchor = true); /** Delete the current selection or do nothing */ void Delete(); /** Delete selection, previous element or merge lines * * This method implements the behaviour of backspace. */ void DeletePrev(OutputDevice* pDev); /** Insert text at the current position */ void InsertText(const OUString& aString); /** Insert an element into the formula */ void InsertElement(SmFormulaElement element); /** Insert a command specified in commands.src*/ void InsertCommand(sal_uInt16 nCommand); /** Insert command text translated into line entries at position * * Note: This method uses the parser to translate a command text into a * tree, then it copies line entries from this tree into the current tree. * Will not work for commands such as newline or ##, if position is in a matrix. * This will work for stuff like "A intersection B". But stuff spaning multiple lines * or dependent on the context which position is placed in will not work! */ void InsertCommandText(const OUString& aCommandText); /** Insert a special node created from aString * * Used for handling insert request from the "catalog" dialog. * The provided string should be formated as the desired command: %phi * Note: this method ONLY supports commands defined in Math.xcu * * For more complex expressions use InsertCommandText, this method doesn't * use SmParser, this means that it's faster, but not as strong. */ void InsertSpecial(const OUString& aString); /** Create sub-/super script * * If there's a selection, it will be move into the appropriate sub-/super scription * of the node in front of it. If there's no node in front of position (or the selection), * a sub-/super scription of a new SmPlaceNode will be made. * * If there's is an existing subscription of the node, the caret will be moved into it, * and any selection will replace it. */ void InsertSubSup(SmSubSup eSubSup); /** Create a limit on an SmOperNode * * This this method only work if the caret is inside an SmOperNode, or to the right of one. * Notice also that this method ignores any selection made. * * @param bMoveCaret If true that caret will be moved into the limit. * * @returns True, if the caret was in a context where this operation was possible. */ bool InsertLimit(SmSubSup eSubSup, bool bMoveCaret = true); /** Insert a new row or newline * * Inserts a new row if position is in an matrix or stack command. * Otherwise a newline is inserted if we're in a toplevel line. * * @returns True, if a new row/line could be inserted. * * @remarks If the caret is placed in a subline of a command that doesn't support * this operator the method returns FALSE, and doesn't do anything. */ bool InsertRow(); /** Insert a fraction, use selection as numerator */ void InsertFraction(); /** Create brackets around current selection, or new SmPlaceNode */ void InsertBrackets(SmBracketType eBracketType); /** Copy the current selection */ void Copy(); /** Cut the current selection */ void Cut(){ Copy(); Delete(); } /** Paste the clipboard */ void Paste(); /** Returns true if more than one node is selected * * This method is used for implementing backspace and delete. * If one of these causes a complex selection, e.g. a node with * subnodes or similar, this should not be deleted imidiately. */ bool HasComplexSelection(); /** Finds the topmost node in a visual line * * If MoveUpIfSelected is true, this will move up to the parent line * if the parent of the current line is selected. */ static SmNode* FindTopMostNodeInLine(SmNode* pSNode, bool MoveUpIfSelected = false); /** Draw the caret */ void Draw(OutputDevice& pDev, Point Offset, bool isCaretVisible); bool IsAtTailOfBracket(SmBracketType eBracketType, SmBraceNode** ppBraceNode = NULL) const; void MoveAfterBracket(SmBraceNode* pBraceNode, bool bMoveAnchor = true); private: friend class SmDocShell; SmCaretPosGraphEntry *anchor, *position; /** Formula tree */ SmNode* pTree; /** Owner of the formula tree */ SmDocShell* pDocShell; /** Graph over caret position in the current tree */ SmCaretPosGraph* pGraph; /** Clipboard holder */ SmNodeList* pClipboard; /** Returns a node that is selected, if any could be found */ SmNode* FindSelectedNode(SmNode* pNode); /** Is this one of the nodes used to compose a line * * These are SmExpression, SmBinHorNode, SmUnHorNode etc. */ static bool IsLineCompositionNode(SmNode* pNode); /** Count number of selected nodes, excluding line composition nodes * * Note this function doesn't count line composition nodes and it * does count all subnodes as well as the owner nodes. * * Used by SmCursor::HasComplexSelection() */ int CountSelectedNodes(SmNode* pNode); /** Convert a visual line to a list * * Note this method will delete all the nodes that will no longer be needed. * that includes pLine! * This method also deletes SmErrorNode's as they're just meta info in the line. */ static SmNodeList* LineToList(SmStructureNode* pLine, SmNodeList* pList = new SmNodeList()); /** Auxiliary function for calling LineToList on a node * * This method sets pNode = NULL and remove it from it's parent. * (Assuming it has a parent, and is a child of it). */ static SmNodeList* NodeToList(SmNode*& rpNode, SmNodeList* pList = new SmNodeList()){ //Remove from parent and NULL rpNode SmNode* pNode = rpNode; if(rpNode && rpNode->GetParent()){ //Don't remove this, correctness relies on it int index = rpNode->GetParent()->IndexOfSubNode(rpNode); if(index != -1) rpNode->GetParent()->SetSubNode(index, NULL); } rpNode = NULL; //Create line from node if(pNode && IsLineCompositionNode(pNode)) return LineToList((SmStructureNode*)pNode, pList); if(pNode) pList->push_front(pNode); return pList; } /** Clone a visual line to a list * * Doesn't clone SmErrorNode's these are ignored, as they are context dependent metadata. */ static SmNodeList* CloneLineToList(SmStructureNode* pLine, bool bOnlyIfSelected = false, SmNodeList* pList = new SmNodeList()); /** Build pGraph over caret positions */ void BuildGraph(); /** Insert new nodes in the tree after position */ void InsertNodes(SmNodeList* pNewNodes); /** tries to set position to a specific SmCaretPos * * @returns false on failure to find the position in pGraph. */ bool SetCaretPosition(SmCaretPos pos, bool moveAnchor = false); /** Set selected on nodes of the tree */ void AnnotateSelection(); /** Set the clipboard, and release current clipboard * * Call this method with NULL to reset the clipboard * @remarks: This method takes ownership of pList. */ void SetClipboard(SmNodeList* pList = NULL); /** Clone list of nodes (creates a deep clone) */ static SmNodeList* CloneList(SmNodeList* pList); /** Find an iterator pointing to the node in pLineList following aCaretPos * * If aCaretPos::pSelectedNode cannot be found it is assumed that it's in front of pLineList, * thus not an element in pLineList. In this case this method returns an iterator to the * first element in pLineList. * * If the current position is inside an SmTextNode, this node will be split in two, for this * reason you should beaware that iterators to elements in pLineList may be invalidated, and * that you should call PatchLineList() with this iterator if no action is taken. */ static SmNodeList::iterator FindPositionInLineList(SmNodeList* pLineList, SmCaretPos aCaretPos); /** Patch a line list after modification, merge SmTextNode, remove SmPlaceNode etc. * * @param pLineList The line list to patch * @param aIter Iterator pointing to the element that needs to be patched with it's previous. * * When the list is patched text nodes before and after aIter will be merged. * If there's an, in the context, inappropriate SmPlaceNode before or after aIter it will also be * removed. * * @returns A caret position equivalent to one selecting the node before aIter, the method returns * an invalid SmCaretPos to indicate placement in front of the line. */ static SmCaretPos PatchLineList(SmNodeList* pLineList, SmNodeList::iterator aIter); /** Take selected nodes from a list * * Puts the selected nodes into pSelectedNodes, or if pSelectedNodes is NULL deletes * the selected nodes. * Note: If there's a selection inside an SmTextNode this node will be split, and it * will not be merged when the selection have been taken. Use PatchLineList on the * iterator returns to fix this. * * @returns An iterator pointing to the element following the selection taken. */ static SmNodeList::iterator TakeSelectedNodesFromList(SmNodeList *pLineList, SmNodeList *pSelectedNodes = NULL); /** Create an instance of SmMathSymbolNode usable for brackets */ static SmNode *CreateBracket(SmBracketType eBracketType, bool bIsLeft); /** The number of times BeginEdit have been called * Used to allow nesting of BeginEdit() and EndEdit() sections */ int nEditSections; /** Holds data for BeginEdit() and EndEdit() */ bool bIsEnabledSetModifiedSmDocShell; /** Begin edit section where the tree will be modified */ void BeginEdit(); /** End edit section where the tree will be modified */ void EndEdit(); /** Finish editing * * Finishes editing by parsing pLineList and inserting back into pParent at nParentIndex. * This method also rebuilts the graph, annotates the selection, sets caret position and * Calls EndEdit. * * @remarks Please note that this method will delete pLineList, as the elements are taken. * * @param pLineList List the constitutes the edited line. * @param pParent Parent to which the line should be inserted. * @param nParentIndex Index in parent where the line should be inserted. * @param PosAfterEdit Caret position to look for after rebuilding graph. * @param pStartLine Line to take first position in, if PosAfterEdit cannot be found, * leave it NULL for pLineList. */ void FinishEdit(SmNodeList* pLineList, SmStructureNode* pParent, int nParentIndex, SmCaretPos PosAfterEdit, SmNode* pStartLine = NULL); /** Request the formula is repainted */ void RequestRepaint(); }; /** Minimalistic recursive decent SmNodeList parser * * This parser is used to take a list of nodes that constitues a line * and parse them to a tree of SmBinHorNode, SmUnHorNode and SmExpression. * * Please note, this will not handle all kinds of nodes, only nodes that * constitues and entry in a line. * * Below is an EBNF representation of the grammar used for this parser: * \code * Expression -> Relation* * Relation -> Sum [(=|<|>|...) Sum]* * Sum -> Product [(+|-) Product]* * Product -> Factor [(*|/) Factor]* * Factor -> [+|-|-+|...]* Factor | Postfix * Postfix -> node [!]* * \endcode */ class SmNodeListParser{ public: /** Create an instance of SmNodeListParser */ SmNodeListParser(){ pList = NULL; } /** Parse a list of nodes to an expression * * If bDeleteErrorNodes is true, old error nodes will be deleted. */ SmNode* Parse(SmNodeList* list, bool bDeleteErrorNodes = true); /** True, if the token is an operator */ static bool IsOperator(const SmToken &token); /** True, if the token is a relation operator */ static bool IsRelationOperator(const SmToken &token); /** True, if the token is a sum operator */ static bool IsSumOperator(const SmToken &token); /** True, if the token is a product operator */ static bool IsProductOperator(const SmToken &token); /** True, if the token is a unary operator */ static bool IsUnaryOperator(const SmToken &token); /** True, if the token is a postfix operator */ static bool IsPostfixOperator(const SmToken &token); private: SmNodeList* pList; /** Get the current terminal */ SmNode* Terminal(){ if(pList->size() > 0) return pList->front(); return NULL; } /** Move to next terminal */ SmNode* Next(){ pList->pop_front(); return Terminal(); } /** Take the current terminal */ SmNode* Take(){ SmNode* pRetVal = Terminal(); Next(); return pRetVal; } SmNode* Expression(); SmNode* Relation(); SmNode* Sum(); SmNode* Product(); SmNode* Factor(); SmNode* Postfix(); SmNode* Error(); }; #endif // INCLUDED_STARMATH_INC_CURSOR_HXX /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <|endoftext|>
<commit_before>// This file is part of CAF, the C++ Actor Framework. See the file LICENSE in // the main distribution directory for license terms and copyright or visit // https://github.com/actor-framework/actor-framework/blob/master/LICENSE. #pragma once #include <cstdint> #include <cstring> #include <memory> #include "caf/byte.hpp" #include "caf/byte_span.hpp" #include "caf/detail/network_order.hpp" #include "caf/error.hpp" #include "caf/net/message_oriented_layer_ptr.hpp" #include "caf/net/receive_policy.hpp" #include "caf/sec.hpp" #include "caf/span.hpp" #include "caf/tag/message_oriented.hpp" #include "caf/tag/stream_oriented.hpp" namespace caf::net { /// Length-prefixed message framing for discretizing a Byte stream into messages /// of varying size. The framing uses 4 Bytes for the length prefix, but /// messages (including the 4 Bytes for the length prefix) are limited to a /// maximum size of INT32_MAX. This limitation comes from the POSIX API (recv) /// on 32-bit platforms. template <class UpperLayer> class length_prefix_framing { public: using input_tag = tag::stream_oriented; using output_tag = tag::message_oriented; using length_prefix_type = uint32_t; static constexpr size_t max_message_length = INT32_MAX - sizeof(uint32_t); static constexpr uint32_t default_receive_size = 4 * 1024; // 4kb. // -- constructors, destructors, and assignment operators -------------------- template <class... Ts> explicit length_prefix_framing(Ts&&... xs) : upper_layer_(std::forward<Ts>(xs)...) { // nop } // -- initialization --------------------------------------------------------- template <class LowerLayerPtr> error init(socket_manager* owner, LowerLayerPtr down, const settings& cfg) { down->configure_read( receive_policy::between(sizeof(uint32_t), default_receive_size)); return upper_layer_.init(owner, this_layer_ptr(down), cfg); } // -- properties ------------------------------------------------------------- auto& upper_layer() noexcept { return upper_layer_; } const auto& upper_layer() const noexcept { return upper_layer_; } // -- interface for the upper layer ------------------------------------------ template <class LowerLayerPtr> void begin_message(LowerLayerPtr down) { down->begin_output(); auto& buf = down->output_buffer(); message_offset_ = buf.size(); buf.insert(buf.end(), 4, byte{0}); } template <class LowerLayerPtr> byte_buffer& message_buffer(LowerLayerPtr down) { return down->output_buffer(); } template <class LowerLayerPtr> [[nodiscard]] bool end_message(LowerLayerPtr down) { using detail::to_network_order; auto& buf = down->output_buffer(); CAF_ASSERT(message_offset_ < buf.size()); auto msg_begin = buf.begin() + message_offset_; auto msg_size = std::distance(msg_begin + 4, buf.end()); if (msg_size > 0 && static_cast<size_t>(msg_size) < max_message_length) { auto u32_size = to_network_order(static_cast<uint32_t>(msg_size)); memcpy(std::addressof(*msg_begin), &u32_size, 4); return true; } else { auto err = make_error(sec::runtime_error, msg_size == 0 ? "logic error: message of size 0" : "maximum message size exceeded"); down->abort_reason(std::move(err)); return false; } } template <class LowerLayerPtr> static void abort_reason(LowerLayerPtr down, error reason) { return down->abort_reason(std::move(reason)); } template <class LowerLayerPtr> static const error& abort_reason(LowerLayerPtr down) { return down->abort_reason(); } // -- interface for the lower layer ------------------------------------------ template <class LowerLayerPtr> bool prepare_send(LowerLayerPtr down) { return upper_layer_.prepare_send(this_layer_ptr(down)); } template <class LowerLayerPtr> bool done_sending(LowerLayerPtr down) { return upper_layer_.done_sending(this_layer_ptr(down)); } template <class LowerLayerPtr> void abort(LowerLayerPtr down, const error& reason) { upper_layer_.abort(this_layer_ptr(down), reason); } template <class LowerLayerPtr> ptrdiff_t consume(LowerLayerPtr down, byte_span input, byte_span) { auto buffer = input; auto consumed = ptrdiff_t{0}; auto this_layer = this_layer_ptr(down); for (;;) { if (input.size() < sizeof(uint32_t)) { return consumed; } else { auto [msg_size, sub_buffer] = split(input); if (msg_size == 0) { consumed += static_cast<ptrdiff_t>(sizeof(uint32_t)); input = sub_buffer; } else if (msg_size > max_message_length) { auto err = make_error(sec::runtime_error, "maximum message size exceeded"); down->abort_reason(std::move(err)); return -1; } else if (msg_size > sub_buffer.size()) { if (msg_size + sizeof(uint32_t) > receive_buf_upper_bound_) { auto min_read_size = static_cast<uint32_t>(sizeof(uint32_t)); receive_buf_upper_bound_ = static_cast<uint32_t>(msg_size + sizeof(uint32_t)); down->configure_read( receive_policy::between(min_read_size, receive_buf_upper_bound_)); } return consumed; } else { auto msg = sub_buffer.subspan(0, msg_size); if (auto res = upper_layer_.consume(this_layer, msg); res >= 0) { consumed += static_cast<ptrdiff_t>(msg.size()) + sizeof(uint32_t); input = sub_buffer.subspan(msg_size); } else { return -1; } } } } } // -- convenience functions -------------------------------------------------- static std::pair<size_t, byte_span> split(byte_span buffer) noexcept { CAF_ASSERT(buffer.size() >= sizeof(uint32_t)); auto u32_size = uint32_t{0}; memcpy(&u32_size, buffer.data(), sizeof(uint32_t)); auto msg_size = static_cast<size_t>(detail::from_network_order(u32_size)); return std::make_pair(msg_size, buffer.subspan(sizeof(uint32_t))); } private: // -- implementation details ------------------------------------------------- template <class LowerLayerPtr> auto this_layer_ptr(LowerLayerPtr down) { return make_message_oriented_layer_ptr(this, down); } // -- member variables ------------------------------------------------------- UpperLayer upper_layer_; size_t message_offset_ = 0; uint32_t receive_buf_upper_bound_ = default_receive_size; }; } // namespace caf::net <commit_msg>Add missing member functions<commit_after>// This file is part of CAF, the C++ Actor Framework. See the file LICENSE in // the main distribution directory for license terms and copyright or visit // https://github.com/actor-framework/actor-framework/blob/master/LICENSE. #pragma once #include <cstdint> #include <cstring> #include <memory> #include "caf/byte.hpp" #include "caf/byte_span.hpp" #include "caf/detail/network_order.hpp" #include "caf/error.hpp" #include "caf/net/message_oriented_layer_ptr.hpp" #include "caf/net/receive_policy.hpp" #include "caf/sec.hpp" #include "caf/span.hpp" #include "caf/tag/message_oriented.hpp" #include "caf/tag/stream_oriented.hpp" namespace caf::net { /// Length-prefixed message framing for discretizing a Byte stream into messages /// of varying size. The framing uses 4 Bytes for the length prefix, but /// messages (including the 4 Bytes for the length prefix) are limited to a /// maximum size of INT32_MAX. This limitation comes from the POSIX API (recv) /// on 32-bit platforms. template <class UpperLayer> class length_prefix_framing { public: using input_tag = tag::stream_oriented; using output_tag = tag::message_oriented; using length_prefix_type = uint32_t; static constexpr size_t max_message_length = INT32_MAX - sizeof(uint32_t); static constexpr uint32_t default_receive_size = 4 * 1024; // 4kb. // -- constructors, destructors, and assignment operators -------------------- template <class... Ts> explicit length_prefix_framing(Ts&&... xs) : upper_layer_(std::forward<Ts>(xs)...) { // nop } // -- initialization --------------------------------------------------------- template <class LowerLayerPtr> error init(socket_manager* owner, LowerLayerPtr down, const settings& cfg) { down->configure_read( receive_policy::between(sizeof(uint32_t), default_receive_size)); return upper_layer_.init(owner, this_layer_ptr(down), cfg); } // -- properties ------------------------------------------------------------- auto& upper_layer() noexcept { return upper_layer_; } const auto& upper_layer() const noexcept { return upper_layer_; } // -- interface for the upper layer ------------------------------------------ template <class LowerLayerPtr> static bool can_send_more(LowerLayerPtr down) noexcept { return down->can_send_more(); } template <class LowerLayerPtr> static auto handle(LowerLayerPtr down) noexcept { return down->handle(); } template <class LowerLayerPtr> void begin_message(LowerLayerPtr down) { down->begin_output(); auto& buf = down->output_buffer(); message_offset_ = buf.size(); buf.insert(buf.end(), 4, byte{0}); } template <class LowerLayerPtr> byte_buffer& message_buffer(LowerLayerPtr down) { return down->output_buffer(); } template <class LowerLayerPtr> [[nodiscard]] bool end_message(LowerLayerPtr down) { using detail::to_network_order; auto& buf = down->output_buffer(); CAF_ASSERT(message_offset_ < buf.size()); auto msg_begin = buf.begin() + message_offset_; auto msg_size = std::distance(msg_begin + 4, buf.end()); if (msg_size > 0 && static_cast<size_t>(msg_size) < max_message_length) { auto u32_size = to_network_order(static_cast<uint32_t>(msg_size)); memcpy(std::addressof(*msg_begin), &u32_size, 4); return true; } else { auto err = make_error(sec::runtime_error, msg_size == 0 ? "logic error: message of size 0" : "maximum message size exceeded"); down->abort_reason(std::move(err)); return false; } } template <class LowerLayerPtr> static void abort_reason(LowerLayerPtr down, error reason) { return down->abort_reason(std::move(reason)); } template <class LowerLayerPtr> static const error& abort_reason(LowerLayerPtr down) { return down->abort_reason(); } // -- interface for the lower layer ------------------------------------------ template <class LowerLayerPtr> bool prepare_send(LowerLayerPtr down) { return upper_layer_.prepare_send(this_layer_ptr(down)); } template <class LowerLayerPtr> bool done_sending(LowerLayerPtr down) { return upper_layer_.done_sending(this_layer_ptr(down)); } template <class LowerLayerPtr> void abort(LowerLayerPtr down, const error& reason) { upper_layer_.abort(this_layer_ptr(down), reason); } template <class LowerLayerPtr> ptrdiff_t consume(LowerLayerPtr down, byte_span input, byte_span) { auto buffer = input; auto consumed = ptrdiff_t{0}; auto this_layer = this_layer_ptr(down); for (;;) { if (input.size() < sizeof(uint32_t)) { return consumed; } else { auto [msg_size, sub_buffer] = split(input); if (msg_size == 0) { consumed += static_cast<ptrdiff_t>(sizeof(uint32_t)); input = sub_buffer; } else if (msg_size > max_message_length) { auto err = make_error(sec::runtime_error, "maximum message size exceeded"); down->abort_reason(std::move(err)); return -1; } else if (msg_size > sub_buffer.size()) { if (msg_size + sizeof(uint32_t) > receive_buf_upper_bound_) { auto min_read_size = static_cast<uint32_t>(sizeof(uint32_t)); receive_buf_upper_bound_ = static_cast<uint32_t>(msg_size + sizeof(uint32_t)); down->configure_read( receive_policy::between(min_read_size, receive_buf_upper_bound_)); } return consumed; } else { auto msg = sub_buffer.subspan(0, msg_size); if (auto res = upper_layer_.consume(this_layer, msg); res >= 0) { consumed += static_cast<ptrdiff_t>(msg.size()) + sizeof(uint32_t); input = sub_buffer.subspan(msg_size); } else { return -1; } } } } } // -- convenience functions -------------------------------------------------- static std::pair<size_t, byte_span> split(byte_span buffer) noexcept { CAF_ASSERT(buffer.size() >= sizeof(uint32_t)); auto u32_size = uint32_t{0}; memcpy(&u32_size, buffer.data(), sizeof(uint32_t)); auto msg_size = static_cast<size_t>(detail::from_network_order(u32_size)); return std::make_pair(msg_size, buffer.subspan(sizeof(uint32_t))); } private: // -- implementation details ------------------------------------------------- template <class LowerLayerPtr> auto this_layer_ptr(LowerLayerPtr down) { return make_message_oriented_layer_ptr(this, down); } // -- member variables ------------------------------------------------------- UpperLayer upper_layer_; size_t message_offset_ = 0; uint32_t receive_buf_upper_bound_ = default_receive_size; }; } // namespace caf::net <|endoftext|>
<commit_before>/******************************************************************************\ * ___ __ * * /\_ \ __/\ \ * * \//\ \ /\_\ \ \____ ___ _____ _____ __ * * \ \ \ \/\ \ \ '__`\ /'___\/\ '__`\/\ '__`\ /'__`\ * * \_\ \_\ \ \ \ \L\ \/\ \__/\ \ \L\ \ \ \L\ \/\ \L\.\_ * * /\____\\ \_\ \_,__/\ \____\\ \ ,__/\ \ ,__/\ \__/.\_\ * * \/____/ \/_/\/___/ \/____/ \ \ \/ \ \ \/ \/__/\/_/ * * \ \_\ \ \_\ * * \/_/ \/_/ * * * * Copyright (C) 2011-2013 * * Dominik Charousset <dominik.charousset@haw-hamburg.de> * * Raphael Hiesgen <raphael.hiesgen@haw-hamburg.de> * * * * This file is part of libcppa. * * libcppa 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 3 of the License * * or (at your option) any later version. * * * * libcppa 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 libcppa. If not, see <http://www.gnu.org/licenses/>. * \******************************************************************************/ #include "cppa/opencl/opencl_metainfo.hpp" using namespace std; namespace cppa { namespace opencl { const std::vector<device_info> opencl_metainfo::get_devices() const { return m_devices; } void opencl_metainfo::initialize() { cl_int err{0}; // get number of available platforms cl_uint number_of_platforms; err = clGetPlatformIDs(0, nullptr, &number_of_platforms); if (err != CL_SUCCESS) { ostringstream oss; oss << "clGetPlatformIDs (getting number of platforms): " << get_opencl_error(err); CPPA_LOGMF(CPPA_ERROR, oss.str()); throw logic_error(oss.str()); } // get platform ids vector<cl_platform_id> ids(number_of_platforms); err = clGetPlatformIDs(ids.size(), ids.data(), nullptr); if (err != CL_SUCCESS) { ostringstream oss; oss << "clGetPlatformIDs (getting platform ids): " << get_opencl_error(err); CPPA_LOGMF(CPPA_ERROR, oss.str()); throw logic_error(oss.str()); } // find gpu devices on our platform int pid{0}; cl_uint num_devices{0}; cl_device_type dev_type{CL_DEVICE_TYPE_GPU}; err = clGetDeviceIDs(ids[pid], dev_type, 0, nullptr, &num_devices); if (err == CL_DEVICE_NOT_FOUND) { CPPA_LOG_TRACE("No gpu devices found. Looking for cpu devices."); cout << "No gpu devices found. Looking for cpu devices." << endl; dev_type = CL_DEVICE_TYPE_CPU; err = clGetDeviceIDs(ids[pid], dev_type, 0, nullptr, &num_devices); } if (err != CL_SUCCESS) { ostringstream oss; oss << "clGetDeviceIDs: " << get_opencl_error(err); CPPA_LOGMF(CPPA_ERROR, oss.str()); throw runtime_error(oss.str()); } vector<cl_device_id> devices(num_devices); err = clGetDeviceIDs(ids[pid], dev_type, num_devices, devices.data(), nullptr); if (err != CL_SUCCESS) { ostringstream oss; oss << "clGetDeviceIDs: " << get_opencl_error(err); CPPA_LOGMF(CPPA_ERROR, oss.str()); throw runtime_error(oss.str()); } auto pfn_notify = [](const char *errinfo, const void *, size_t, void *) { CPPA_LOG_ERROR("\n##### Error message via pfn_notify #####\n" + string(errinfo) + "\n########################################"); }; // create a context m_context.adopt(clCreateContext(0, devices.size(), devices.data(), pfn_notify, nullptr, &err)); if (err != CL_SUCCESS) { ostringstream oss; oss << "clCreateContext: " << get_opencl_error(err); CPPA_LOGMF(CPPA_ERROR, oss.str()); throw runtime_error(oss.str()); } for (auto& d : devices) { CPPA_LOG_TRACE("Creating command queue for device(s)."); device_ptr device; device.adopt(d); size_t return_size{0}; static constexpr size_t buf_size = 128; char buf[buf_size]; err = clGetDeviceInfo(device.get(), CL_DEVICE_NAME, buf_size, buf, &return_size); if (err != CL_SUCCESS) { CPPA_LOGMF(CPPA_ERROR, "clGetDeviceInfo (CL_DEVICE_NAME): " << get_opencl_error(err)); fill(buf, buf+buf_size, 0); } command_queue_ptr cmd_queue; cmd_queue.adopt(clCreateCommandQueue(m_context.get(), device.get(), CL_QUEUE_PROFILING_ENABLE, &err)); if (err != CL_SUCCESS) { CPPA_LOGMF(CPPA_DEBUG, "Could not create command queue for device " << buf << ": " << get_opencl_error(err)); } else { size_t max_work_group_size{0}; err = clGetDeviceInfo(device.get(), CL_DEVICE_MAX_WORK_GROUP_SIZE, sizeof(size_t), &max_work_group_size, &return_size); if (err != CL_SUCCESS) { ostringstream oss; oss << "clGetDeviceInfo (" << "CL_DEVICE_MAX_WORK_GROUP_SIZE): " << get_opencl_error(err); CPPA_LOGMF(CPPA_ERROR, oss.str()); throw runtime_error(oss.str()); } cl_uint max_work_item_dimensions = 0; err = clGetDeviceInfo(device.get(), CL_DEVICE_MAX_WORK_ITEM_DIMENSIONS, sizeof(cl_uint), &max_work_item_dimensions, &return_size); if (err != CL_SUCCESS) { ostringstream oss; oss << "clGetDeviceInfo (" << "CL_DEVICE_MAX_WORK_ITEM_DIMENSIONS): " << get_opencl_error(err); CPPA_LOGMF(CPPA_ERROR, oss.str()); throw runtime_error(oss.str()); } dim_vec max_work_items_per_dim(max_work_item_dimensions); err = clGetDeviceInfo(device.get(), CL_DEVICE_MAX_WORK_ITEM_SIZES, sizeof(size_t)*max_work_item_dimensions, max_work_items_per_dim.data(), &return_size); if (err != CL_SUCCESS) { ostringstream oss; oss << "clGetDeviceInfo (" << "CL_DEVICE_MAX_WORK_ITEM_SIZES): " << get_opencl_error(err); CPPA_LOGMF(CPPA_ERROR, oss.str()); throw runtime_error(oss.str()); } device_info dev_info{device, cmd_queue, max_work_group_size, max_work_item_dimensions, max_work_items_per_dim}; m_devices.push_back(move(dev_info)); } } if (m_devices.empty()) { ostringstream oss; oss << "Could not create a command queue for " << "any present device."; CPPA_LOGMF(CPPA_ERROR, oss.str()); throw runtime_error(oss.str()); } } void opencl_metainfo::destroy() { delete this; } void opencl_metainfo::dispose() { delete this; } opencl_metainfo* get_opencl_metainfo() { return detail::singleton_manager::get_opencl_metainfo(); } } } // namespace cppa::opencl <commit_msg>fixed logging issues in OpenCL build, closes #119<commit_after>/******************************************************************************\ * ___ __ * * /\_ \ __/\ \ * * \//\ \ /\_\ \ \____ ___ _____ _____ __ * * \ \ \ \/\ \ \ '__`\ /'___\/\ '__`\/\ '__`\ /'__`\ * * \_\ \_\ \ \ \ \L\ \/\ \__/\ \ \L\ \ \ \L\ \/\ \L\.\_ * * /\____\\ \_\ \_,__/\ \____\\ \ ,__/\ \ ,__/\ \__/.\_\ * * \/____/ \/_/\/___/ \/____/ \ \ \/ \ \ \/ \/__/\/_/ * * \ \_\ \ \_\ * * \/_/ \/_/ * * * * Copyright (C) 2011-2013 * * Dominik Charousset <dominik.charousset@haw-hamburg.de> * * Raphael Hiesgen <raphael.hiesgen@haw-hamburg.de> * * * * This file is part of libcppa. * * libcppa 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 3 of the License * * or (at your option) any later version. * * * * libcppa 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 libcppa. If not, see <http://www.gnu.org/licenses/>. * \******************************************************************************/ #include "cppa/opencl/opencl_metainfo.hpp" using namespace std; namespace cppa { namespace opencl { const std::vector<device_info> opencl_metainfo::get_devices() const { return m_devices; } void opencl_metainfo::initialize() { cl_int err{0}; // get number of available platforms cl_uint number_of_platforms; err = clGetPlatformIDs(0, nullptr, &number_of_platforms); if (err != CL_SUCCESS) { ostringstream oss; oss << "clGetPlatformIDs (getting number of platforms): " << get_opencl_error(err); CPPA_LOGMF(CPPA_ERROR, oss.str()); throw logic_error(oss.str()); } // get platform ids vector<cl_platform_id> ids(number_of_platforms); err = clGetPlatformIDs(ids.size(), ids.data(), nullptr); if (err != CL_SUCCESS) { ostringstream oss; oss << "clGetPlatformIDs (getting platform ids): " << get_opencl_error(err); CPPA_LOGMF(CPPA_ERROR, oss.str()); throw logic_error(oss.str()); } // find gpu devices on our platform int pid{0}; cl_uint num_devices{0}; cl_device_type dev_type{CL_DEVICE_TYPE_GPU}; err = clGetDeviceIDs(ids[pid], dev_type, 0, nullptr, &num_devices); if (err == CL_DEVICE_NOT_FOUND) { CPPA_LOG_TRACE("No gpu devices found. Looking for cpu devices."); cout << "No gpu devices found. Looking for cpu devices." << endl; dev_type = CL_DEVICE_TYPE_CPU; err = clGetDeviceIDs(ids[pid], dev_type, 0, nullptr, &num_devices); } if (err != CL_SUCCESS) { ostringstream oss; oss << "clGetDeviceIDs: " << get_opencl_error(err); CPPA_LOGMF(CPPA_ERROR, oss.str()); throw runtime_error(oss.str()); } vector<cl_device_id> devices(num_devices); err = clGetDeviceIDs(ids[pid], dev_type, num_devices, devices.data(), nullptr); if (err != CL_SUCCESS) { ostringstream oss; oss << "clGetDeviceIDs: " << get_opencl_error(err); CPPA_LOGMF(CPPA_ERROR, oss.str()); throw runtime_error(oss.str()); } auto pfn_notify = [](const char *errinfo, const void *, size_t, void *) { CPPA_LOGC_ERROR("cppa::opencl::opencl_metainfo", "initialize", "\n##### Error message via pfn_notify #####\n" + string(errinfo) + "\n########################################"); }; // create a context m_context.adopt(clCreateContext(0, devices.size(), devices.data(), pfn_notify, nullptr, &err)); if (err != CL_SUCCESS) { ostringstream oss; oss << "clCreateContext: " << get_opencl_error(err); CPPA_LOGMF(CPPA_ERROR, oss.str()); throw runtime_error(oss.str()); } for (auto& d : devices) { CPPA_LOG_TRACE("Creating command queue for device(s)."); device_ptr device; device.adopt(d); size_t return_size{0}; static constexpr size_t buf_size = 128; char buf[buf_size]; err = clGetDeviceInfo(device.get(), CL_DEVICE_NAME, buf_size, buf, &return_size); if (err != CL_SUCCESS) { CPPA_LOGMF(CPPA_ERROR, "clGetDeviceInfo (CL_DEVICE_NAME): " << get_opencl_error(err)); fill(buf, buf+buf_size, 0); } command_queue_ptr cmd_queue; cmd_queue.adopt(clCreateCommandQueue(m_context.get(), device.get(), CL_QUEUE_PROFILING_ENABLE, &err)); if (err != CL_SUCCESS) { CPPA_LOGMF(CPPA_DEBUG, "Could not create command queue for device " << buf << ": " << get_opencl_error(err)); } else { size_t max_work_group_size{0}; err = clGetDeviceInfo(device.get(), CL_DEVICE_MAX_WORK_GROUP_SIZE, sizeof(size_t), &max_work_group_size, &return_size); if (err != CL_SUCCESS) { ostringstream oss; oss << "clGetDeviceInfo (" << "CL_DEVICE_MAX_WORK_GROUP_SIZE): " << get_opencl_error(err); CPPA_LOGMF(CPPA_ERROR, oss.str()); throw runtime_error(oss.str()); } cl_uint max_work_item_dimensions = 0; err = clGetDeviceInfo(device.get(), CL_DEVICE_MAX_WORK_ITEM_DIMENSIONS, sizeof(cl_uint), &max_work_item_dimensions, &return_size); if (err != CL_SUCCESS) { ostringstream oss; oss << "clGetDeviceInfo (" << "CL_DEVICE_MAX_WORK_ITEM_DIMENSIONS): " << get_opencl_error(err); CPPA_LOGMF(CPPA_ERROR, oss.str()); throw runtime_error(oss.str()); } dim_vec max_work_items_per_dim(max_work_item_dimensions); err = clGetDeviceInfo(device.get(), CL_DEVICE_MAX_WORK_ITEM_SIZES, sizeof(size_t)*max_work_item_dimensions, max_work_items_per_dim.data(), &return_size); if (err != CL_SUCCESS) { ostringstream oss; oss << "clGetDeviceInfo (" << "CL_DEVICE_MAX_WORK_ITEM_SIZES): " << get_opencl_error(err); CPPA_LOGMF(CPPA_ERROR, oss.str()); throw runtime_error(oss.str()); } device_info dev_info{device, cmd_queue, max_work_group_size, max_work_item_dimensions, max_work_items_per_dim}; m_devices.push_back(move(dev_info)); } } if (m_devices.empty()) { ostringstream oss; oss << "Could not create a command queue for " << "any present device."; CPPA_LOGMF(CPPA_ERROR, oss.str()); throw runtime_error(oss.str()); } } void opencl_metainfo::destroy() { delete this; } void opencl_metainfo::dispose() { delete this; } opencl_metainfo* get_opencl_metainfo() { return detail::singleton_manager::get_opencl_metainfo(); } } } // namespace cppa::opencl <|endoftext|>
<commit_before>#pragma once #include <string> #include <fc/reflect/reflect.hpp> #include <iosfwd> namespace eosio::chain { struct name; } namespace fc { class variant; void to_variant(const eosio::chain::name& c, fc::variant& v); void from_variant(const fc::variant& v, eosio::chain::name& check); } // fc namespace eosio::chain { static constexpr uint64_t char_to_symbol( char c ) { if( c >= 'a' && c <= 'z' ) return (c - 'a') + 6; if( c >= '1' && c <= '5' ) return (c - '1') + 1; return 0; } static constexpr uint64_t string_to_uint64_t( std::string_view str ) { uint64_t n = 0; int i = 0; for ( ; str[i] && i < 12; ++i) { // NOTE: char_to_symbol() returns char type, and without this explicit // expansion to uint64 type, the compilation fails at the point of usage // of string_to_name(), where the usage requires constant (compile time) expression. n |= (char_to_symbol(str[i]) & 0x1f) << (64 - 5 * (i + 1)); } // The for-loop encoded up to 60 high bits into uint64 'name' variable, // if (strlen(str) > 12) then encode str[12] into the low (remaining) // 4 bits of 'name' if (i == 12) n |= char_to_symbol(str[12]) & 0x0F; return n; } /// Immutable except for fc::from_variant. struct name { private: uint64_t value = 0; friend struct fc::reflector<name>; friend void fc::from_variant(const fc::variant& v, eosio::chain::name& check); void set( std::string_view str ); public: constexpr bool empty()const { return 0 == value; } constexpr bool good()const { return !empty(); } explicit name( std::string_view str ) { set( str ); } constexpr explicit name( uint64_t v ) : value(v) {} constexpr name() = default; std::string to_string()const; constexpr uint64_t to_uint64_t()const { return value; } friend std::ostream& operator << ( std::ostream& out, const name& n ) { return out << n.to_string(); } friend constexpr bool operator < ( const name& a, const name& b ) { return a.value < b.value; } friend constexpr bool operator > ( const name& a, const name& b ) { return a.value > b.value; } friend constexpr bool operator <= ( const name& a, const name& b ) { return a.value <= b.value; } friend constexpr bool operator >= ( const name& a, const name& b ) { return a.value >= b.value; } friend constexpr bool operator == ( const name& a, const name& b ) { return a.value == b.value; } friend constexpr bool operator != ( const name& a, const name& b ) { return a.value != b.value; } friend constexpr bool operator == ( const name& a, uint64_t b ) { return a.value == b; } friend constexpr bool operator != ( const name& a, uint64_t b ) { return a.value != b; } constexpr explicit operator bool()const { return value != 0; } }; // Each char of the string is encoded into 5-bit chunk and left-shifted // to its 5-bit slot starting with the highest slot for the first char. // The 13th char, if str is long enough, is encoded into 4-bit chunk // and placed in the lowest 4 bits. 64 = 12 * 5 + 4 static constexpr name string_to_name( std::string_view str ) { return name( string_to_uint64_t( str ) ); } #define N(X) eosio::chain::string_to_name(#X) } // eosio::chain namespace std { template<> struct hash<eosio::chain::name> : private hash<uint64_t> { typedef eosio::chain::name argument_type; typedef typename hash<uint64_t>::result_type result_type; result_type operator()(const argument_type& name) const noexcept { return hash<uint64_t>::operator()(name.to_uint64_t()); } }; }; FC_REFLECT( eosio::chain::name, (value) ) <commit_msg>fix hash<>::result_type deprecation spam<commit_after>#pragma once #include <string> #include <fc/reflect/reflect.hpp> #include <iosfwd> namespace eosio::chain { struct name; } namespace fc { class variant; void to_variant(const eosio::chain::name& c, fc::variant& v); void from_variant(const fc::variant& v, eosio::chain::name& check); } // fc namespace eosio::chain { static constexpr uint64_t char_to_symbol( char c ) { if( c >= 'a' && c <= 'z' ) return (c - 'a') + 6; if( c >= '1' && c <= '5' ) return (c - '1') + 1; return 0; } static constexpr uint64_t string_to_uint64_t( std::string_view str ) { uint64_t n = 0; int i = 0; for ( ; str[i] && i < 12; ++i) { // NOTE: char_to_symbol() returns char type, and without this explicit // expansion to uint64 type, the compilation fails at the point of usage // of string_to_name(), where the usage requires constant (compile time) expression. n |= (char_to_symbol(str[i]) & 0x1f) << (64 - 5 * (i + 1)); } // The for-loop encoded up to 60 high bits into uint64 'name' variable, // if (strlen(str) > 12) then encode str[12] into the low (remaining) // 4 bits of 'name' if (i == 12) n |= char_to_symbol(str[12]) & 0x0F; return n; } /// Immutable except for fc::from_variant. struct name { private: uint64_t value = 0; friend struct fc::reflector<name>; friend void fc::from_variant(const fc::variant& v, eosio::chain::name& check); void set( std::string_view str ); public: constexpr bool empty()const { return 0 == value; } constexpr bool good()const { return !empty(); } explicit name( std::string_view str ) { set( str ); } constexpr explicit name( uint64_t v ) : value(v) {} constexpr name() = default; std::string to_string()const; constexpr uint64_t to_uint64_t()const { return value; } friend std::ostream& operator << ( std::ostream& out, const name& n ) { return out << n.to_string(); } friend constexpr bool operator < ( const name& a, const name& b ) { return a.value < b.value; } friend constexpr bool operator > ( const name& a, const name& b ) { return a.value > b.value; } friend constexpr bool operator <= ( const name& a, const name& b ) { return a.value <= b.value; } friend constexpr bool operator >= ( const name& a, const name& b ) { return a.value >= b.value; } friend constexpr bool operator == ( const name& a, const name& b ) { return a.value == b.value; } friend constexpr bool operator != ( const name& a, const name& b ) { return a.value != b.value; } friend constexpr bool operator == ( const name& a, uint64_t b ) { return a.value == b; } friend constexpr bool operator != ( const name& a, uint64_t b ) { return a.value != b; } constexpr explicit operator bool()const { return value != 0; } }; // Each char of the string is encoded into 5-bit chunk and left-shifted // to its 5-bit slot starting with the highest slot for the first char. // The 13th char, if str is long enough, is encoded into 4-bit chunk // and placed in the lowest 4 bits. 64 = 12 * 5 + 4 static constexpr name string_to_name( std::string_view str ) { return name( string_to_uint64_t( str ) ); } #define N(X) eosio::chain::string_to_name(#X) } // eosio::chain namespace std { template<> struct hash<eosio::chain::name> : private hash<uint64_t> { typedef eosio::chain::name argument_type; size_t operator()(const argument_type& name) const noexcept { return hash<uint64_t>::operator()(name.to_uint64_t()); } }; }; FC_REFLECT( eosio::chain::name, (value) ) <|endoftext|>
<commit_before>#pragma once #include <atomic> #include "Core/Core.hpp" // Allocated memory aligned to alignment. Supports any alignment and size. // This may cause more memory overhead than necessary. For smaller alignments, consider implementing small alignment versions. void* alignedMalloc(std::size_t alignment, std::size_t size); void alignedFree(void* pointer); inline bool isAligned(void* ptr, size_t alignment) { return uintptr_t(ptr) % alignment == 0; } // Allocates objects from a fixed size array. Unallocated objects are managed using a free list. template<typename ObjectType, int64 size> class FixedThreadSafePoolAllocator { static_assert(size > 0, "size must be greater than zero"); static_assert(sizeof(ObjectType) >= sizeof(void*), "ObjectType size has to be at least size of a pointer to allow free list management"); public: FixedThreadSafePoolAllocator() { freeListHead.store(reinterpret_cast<FreeListItem*>(pool), std::memory_order_relaxed); for (int64 i = 0; i < (size - 1); ++i) { FreeListItem* nextItem = reinterpret_cast<FreeListItem*>(&pool[(i + 1) * sizeof(ObjectType)]); reinterpret_cast<FreeListItem*>(&pool[i * sizeof(ObjectType)])->next = nextItem; } reinterpret_cast<FreeListItem*>(&pool[(size - 1) * sizeof(ObjectType)])->next = nullptr; } void* allocate() { FreeListItem* lastFreeListHead; do { lastFreeListHead = freeListHead.load(std::memory_order_relaxed); if (!lastFreeListHead) { logWarning("FixedThreadSafePoolAllocator ran out of preallocated pool objects."); if (alignof(ObjectType) > alignof(std::max_align_t)) { return alignedMalloc(alignof(ObjectType), sizeof(ObjectType)); } else { return malloc(sizeof(ObjectType)); } } } while (!freeListHead.compare_exchange_strong(lastFreeListHead, lastFreeListHead->next)); return lastFreeListHead; } void deallocate(ObjectType* toDeallocate) { if (!toDeallocate) { logError("Tried to deallocate nullptr in a FixedThreadSafePoolAllocator."); return; } FreeListItem* newFreeListHead = reinterpret_cast<FreeListItem*>(toDeallocate); FreeListItem* lastFreeListHead; do { lastFreeListHead = freeListHead.load(std::memory_order_relaxed); newFreeListHead->next = lastFreeListHead; } while(!freeListHead.compare_exchange_strong(lastFreeListHead, newFreeListHead)); } private: byte alignas(alignof(ObjectType)) pool[size * sizeof(ObjectType)]; // Is byte array to avoid default initialization of objects. struct FreeListItem { FreeListItem* next; }; std::atomic<FreeListItem*> alignas(CACHE_LINE_SIZE) freeListHead; // Keep on separate cache line to avoid false sharing. }; // Value type must implement ref() and unref() methods. template<typename ValueType> class Ref { public: Ref() = default; explicit Ref(ValueType* InPtr) : ptr(InPtr) { if (ptr) { ptr->ref(); } } Ref(const Ref& other) : ptr(other.ptr) { if (ptr) { ptr->ref(); } } Ref(Ref&& other) noexcept { swap(*this, other); } Ref& operator=(const Ref& rhs) { if (ptr) { ptr->unref(); } ptr = rhs.ptr; if (ptr) { ptr->ref(); } return *this; } Ref& operator=(Ref&& rhs) noexcept { swap(*this, rhs); return *this; } ~Ref() { if (ptr) { ptr->unref(); } } friend void swap(Ref& first, Ref& second) { using std::swap; swap(first.ptr, second.ptr); } bool isValid() const { return ptr != nullptr; } ValueType* operator->() { assert(ptr != nullptr); return ptr; } private: ValueType* ptr = nullptr; }; <commit_msg>Fixed wrong alignas placement (StructLayout's compiler reported errors)<commit_after>#pragma once #include <atomic> #include "Core/Core.hpp" // Allocated memory aligned to alignment. Supports any alignment and size. // This may cause more memory overhead than necessary. For smaller alignments, consider implementing small alignment versions. void* alignedMalloc(std::size_t alignment, std::size_t size); void alignedFree(void* pointer); inline bool isAligned(void* ptr, size_t alignment) { return uintptr_t(ptr) % alignment == 0; } // Allocates objects from a fixed size array. Unallocated objects are managed using a free list. template<typename ObjectType, int64 size> class FixedThreadSafePoolAllocator { static_assert(size > 0, "size must be greater than zero"); static_assert(sizeof(ObjectType) >= sizeof(void*), "ObjectType size has to be at least size of a pointer to allow free list management"); public: FixedThreadSafePoolAllocator() { freeListHead.store(reinterpret_cast<FreeListItem*>(pool), std::memory_order_relaxed); for (int64 i = 0; i < (size - 1); ++i) { FreeListItem* nextItem = reinterpret_cast<FreeListItem*>(&pool[(i + 1) * sizeof(ObjectType)]); reinterpret_cast<FreeListItem*>(&pool[i * sizeof(ObjectType)])->next = nextItem; } reinterpret_cast<FreeListItem*>(&pool[(size - 1) * sizeof(ObjectType)])->next = nullptr; } void* allocate() { FreeListItem* lastFreeListHead; do { lastFreeListHead = freeListHead.load(std::memory_order_relaxed); if (!lastFreeListHead) { logWarning("FixedThreadSafePoolAllocator ran out of preallocated pool objects."); if (alignof(ObjectType) > alignof(std::max_align_t)) { return alignedMalloc(alignof(ObjectType), sizeof(ObjectType)); } else { return malloc(sizeof(ObjectType)); } } } while (!freeListHead.compare_exchange_strong(lastFreeListHead, lastFreeListHead->next)); return lastFreeListHead; } void deallocate(ObjectType* toDeallocate) { if (!toDeallocate) { logError("Tried to deallocate nullptr in a FixedThreadSafePoolAllocator."); return; } FreeListItem* newFreeListHead = reinterpret_cast<FreeListItem*>(toDeallocate); FreeListItem* lastFreeListHead; do { lastFreeListHead = freeListHead.load(std::memory_order_relaxed); newFreeListHead->next = lastFreeListHead; } while(!freeListHead.compare_exchange_strong(lastFreeListHead, newFreeListHead)); } private: alignas(alignof(ObjectType)) byte pool[size * sizeof(ObjectType)]; // Is byte array to avoid default initialization of objects. struct FreeListItem { FreeListItem* next; }; alignas(CACHE_LINE_SIZE) std::atomic<FreeListItem*> freeListHead; // Keep on separate cache line to avoid false sharing. }; // Value type must implement ref() and unref() methods. template<typename ValueType> class Ref { public: Ref() = default; explicit Ref(ValueType* InPtr) : ptr(InPtr) { if (ptr) { ptr->ref(); } } Ref(const Ref& other) : ptr(other.ptr) { if (ptr) { ptr->ref(); } } Ref(Ref&& other) noexcept { swap(*this, other); } Ref& operator=(const Ref& rhs) { if (ptr) { ptr->unref(); } ptr = rhs.ptr; if (ptr) { ptr->ref(); } return *this; } Ref& operator=(Ref&& rhs) noexcept { swap(*this, rhs); return *this; } ~Ref() { if (ptr) { ptr->unref(); } } friend void swap(Ref& first, Ref& second) { using std::swap; swap(first.ptr, second.ptr); } bool isValid() const { return ptr != nullptr; } ValueType* operator->() { assert(ptr != nullptr); return ptr; } private: ValueType* ptr = nullptr; }; <|endoftext|>
<commit_before>/// Poset.hpp /// Shaun Harker /// 2015-05-15 #ifndef DSGRN_POSET_HPP #define DSGRN_POSET_HPP #ifndef INLINE_IF_HEADER_ONLY #define INLINE_IF_HEADER_ONLY #endif #include "Poset.h" INLINE_IF_HEADER_ONLY Poset:: Poset ( void ) { dataPoset_ . reset ( new Poset_ ); } INLINE_IF_HEADER_ONLY Poset:: Poset ( std::vector<std::vector<uint64_t>> & adjacencies ):Digraph(adjacencies) { dataPoset_ . reset ( new Poset_ ); } INLINE_IF_HEADER_ONLY void Poset:: reduction ( void ) { // Algorithm: Remove self-edges, and remove edges which // can be given by a double-hop // (Assumes the vertices are topologically sorted.) // (Assumes original state is transitively closed.) // uint64_t N = size (); dataPoset_ -> reachability_ = data_ -> adjacencies_; std::cout << "Reachability\n"; for ( uint64_t i=0; i<N; ++i ) { std::cout << i << " : "; for ( auto u : data_ -> adjacencies_ [ i ] ) { std::cout << u << " "; } std::cout << "\n"; } dataPoset_ -> parentsCount_ . resize ( N ); dataPoset_ -> childrenCount_ . resize ( N ); dataPoset_ -> ancestorsCount_ . resize ( N ); dataPoset_ -> descendantsCount_ . resize ( N ); computeNumberOfAncestors(); computeNumberOfDescendants(); // for ( uint64_t u = 0; u < N; ++ u ) { std::unordered_set<uint64_t> double_hop; double_hop . insert ( u ); for ( uint64_t v : data_ ->adjacencies_ [ u ] ) { if ( u == v ) continue; for ( uint64_t w : data_ ->adjacencies_ [ v ] ) { if ( v == w ) continue; double_hop . insert ( w ); } } auto removal_predicate = [&] (uint64_t v) { return double_hop . count ( v ) ? true : false; }; auto it = std::remove_if ( data_ ->adjacencies_[u].begin(), data_ ->adjacencies_[u].end(), removal_predicate ); data_ -> adjacencies_[u].erase ( it, data_ ->adjacencies_[u].end() ); } std::cout << "transitive closure\n"; for ( uint64_t i=0; i<N; ++i ) { std::cout << i << " : "; for ( auto u : data_ -> adjacencies_ [ i ] ) { std::cout << u << " "; } std::cout << "\n"; } computeNumberOfParents(); computeNumberOfChildren(); } INLINE_IF_HEADER_ONLY uint64_t Poset:: numberOfAncestors ( const uint64_t & i ) const { return dataPoset_ -> ancestorsCount_ [ i ]; } INLINE_IF_HEADER_ONLY uint64_t Poset:: numberOfDescendants ( const uint64_t & i ) const { return dataPoset_ -> descendantsCount_ [ i ]; } INLINE_IF_HEADER_ONLY uint64_t Poset:: numberOfParents ( const uint64_t & i ) const { return dataPoset_ -> parentsCount_ [ i ]; } INLINE_IF_HEADER_ONLY uint64_t Poset:: numberOfChildren ( const uint64_t & i ) const { return dataPoset_ -> childrenCount_ [ i ]; } INLINE_IF_HEADER_ONLY void Poset:: computeNumberOfAncestors ( void ) const { uint64_t N = size(); for ( uint64_t i=0; i<N; ++i ) { for ( auto u : dataPoset_ -> reachability_ [ i ] ) { ++ dataPoset_ -> ancestorsCount_ [ u ]; } } } INLINE_IF_HEADER_ONLY void Poset:: computeNumberOfDescendants ( void ) const { uint64_t N = size(); for ( uint64_t i=0; i<N; ++i ) { dataPoset_ -> descendantsCount_ [ i ] = dataPoset_ -> reachability_ [ i ] . size(); } } INLINE_IF_HEADER_ONLY void Poset:: computeNumberOfParents ( void ) const { uint64_t N = size(); for ( uint64_t i=0; i<N; ++i ) { for ( auto u : data_ -> adjacencies_ [ i ] ) { ++ dataPoset_ -> parentsCount_ [ u ]; } } } INLINE_IF_HEADER_ONLY void Poset:: computeNumberOfChildren ( void ) const { uint64_t N = size(); for ( uint64_t i=0; i<N; ++i ) { dataPoset_ -> childrenCount_ [ i ] = data_ -> adjacencies_ [ i ] . size(); } } INLINE_IF_HEADER_ONLY bool Poset:: reachable ( const uint64_t & n, const uint64_t & m ) const { for ( auto u : data_ -> adjacencies_ [ n ] ) { if ( u == m ) { return true; } } return false; } INLINE_IF_HEADER_ONLY Poset Poset:: reorder ( const std::vector<uint64_t> & ordering ) const { /// Reconstruct the list adjacencies from ordering std::vector< std::vector<uint64_t> > newAdjacencies; /// ordering [ 3 ] = 11 means node label 3 should become 11 /// uint64_t N = size(); newAdjacencies . resize ( N ); /// for ( uint64_t i=0; i<N; ++i ) { uint64_t newVertex1 = ordering [ i ]; for ( auto u : data_ -> adjacencies_ [ i ] ) { uint64_t newVertex2 = ordering [ u ]; newAdjacencies [ newVertex1 ] . push_back ( newVertex2 ); } } /// Poset newPoset ( newAdjacencies ); /// to recompute ancestors,descendants,parents,children newPoset . reduction (); /// return newPoset; } #endif <commit_msg>commented out debug code<commit_after>/// Poset.hpp /// Shaun Harker /// 2015-05-15 #ifndef DSGRN_POSET_HPP #define DSGRN_POSET_HPP #ifndef INLINE_IF_HEADER_ONLY #define INLINE_IF_HEADER_ONLY #endif #include "Poset.h" INLINE_IF_HEADER_ONLY Poset:: Poset ( void ) { dataPoset_ . reset ( new Poset_ ); } INLINE_IF_HEADER_ONLY Poset:: Poset ( std::vector<std::vector<uint64_t>> & adjacencies ):Digraph(adjacencies) { dataPoset_ . reset ( new Poset_ ); } INLINE_IF_HEADER_ONLY void Poset:: reduction ( void ) { // Algorithm: Remove self-edges, and remove edges which // can be given by a double-hop // (Assumes the vertices are topologically sorted.) // (Assumes original state is transitively closed.) // uint64_t N = size (); dataPoset_ -> reachability_ = data_ -> adjacencies_; // std::cout << "Reachability\n"; // for ( uint64_t i=0; i<N; ++i ) { // std::cout << i << " : "; // for ( auto u : data_ -> adjacencies_ [ i ] ) { // std::cout << u << " "; // } // std::cout << "\n"; // } dataPoset_ -> parentsCount_ . resize ( N ); dataPoset_ -> childrenCount_ . resize ( N ); dataPoset_ -> ancestorsCount_ . resize ( N ); dataPoset_ -> descendantsCount_ . resize ( N ); computeNumberOfAncestors(); computeNumberOfDescendants(); // for ( uint64_t u = 0; u < N; ++ u ) { std::unordered_set<uint64_t> double_hop; double_hop . insert ( u ); for ( uint64_t v : data_ ->adjacencies_ [ u ] ) { if ( u == v ) continue; for ( uint64_t w : data_ ->adjacencies_ [ v ] ) { if ( v == w ) continue; double_hop . insert ( w ); } } auto removal_predicate = [&] (uint64_t v) { return double_hop . count ( v ) ? true : false; }; auto it = std::remove_if ( data_ ->adjacencies_[u].begin(), data_ ->adjacencies_[u].end(), removal_predicate ); data_ -> adjacencies_[u].erase ( it, data_ ->adjacencies_[u].end() ); } // std::cout << "transitive closure\n"; // // for ( uint64_t i=0; i<N; ++i ) { // std::cout << i << " : "; // for ( auto u : data_ -> adjacencies_ [ i ] ) { // std::cout << u << " "; // } // std::cout << "\n"; // } computeNumberOfParents(); computeNumberOfChildren(); } INLINE_IF_HEADER_ONLY uint64_t Poset:: numberOfAncestors ( const uint64_t & i ) const { return dataPoset_ -> ancestorsCount_ [ i ]; } INLINE_IF_HEADER_ONLY uint64_t Poset:: numberOfDescendants ( const uint64_t & i ) const { return dataPoset_ -> descendantsCount_ [ i ]; } INLINE_IF_HEADER_ONLY uint64_t Poset:: numberOfParents ( const uint64_t & i ) const { return dataPoset_ -> parentsCount_ [ i ]; } INLINE_IF_HEADER_ONLY uint64_t Poset:: numberOfChildren ( const uint64_t & i ) const { return dataPoset_ -> childrenCount_ [ i ]; } INLINE_IF_HEADER_ONLY void Poset:: computeNumberOfAncestors ( void ) const { uint64_t N = size(); for ( uint64_t i=0; i<N; ++i ) { for ( auto u : dataPoset_ -> reachability_ [ i ] ) { ++ dataPoset_ -> ancestorsCount_ [ u ]; } } } INLINE_IF_HEADER_ONLY void Poset:: computeNumberOfDescendants ( void ) const { uint64_t N = size(); for ( uint64_t i=0; i<N; ++i ) { dataPoset_ -> descendantsCount_ [ i ] = dataPoset_ -> reachability_ [ i ] . size(); } } INLINE_IF_HEADER_ONLY void Poset:: computeNumberOfParents ( void ) const { uint64_t N = size(); for ( uint64_t i=0; i<N; ++i ) { for ( auto u : data_ -> adjacencies_ [ i ] ) { ++ dataPoset_ -> parentsCount_ [ u ]; } } } INLINE_IF_HEADER_ONLY void Poset:: computeNumberOfChildren ( void ) const { uint64_t N = size(); for ( uint64_t i=0; i<N; ++i ) { dataPoset_ -> childrenCount_ [ i ] = data_ -> adjacencies_ [ i ] . size(); } } INLINE_IF_HEADER_ONLY bool Poset:: reachable ( const uint64_t & n, const uint64_t & m ) const { for ( auto u : data_ -> adjacencies_ [ n ] ) { if ( u == m ) { return true; } } return false; } INLINE_IF_HEADER_ONLY Poset Poset:: reorder ( const std::vector<uint64_t> & ordering ) const { /// Reconstruct the list adjacencies from ordering std::vector< std::vector<uint64_t> > newAdjacencies; /// ordering [ 3 ] = 11 means node label 3 should become 11 /// uint64_t N = size(); newAdjacencies . resize ( N ); /// for ( uint64_t i=0; i<N; ++i ) { uint64_t newVertex1 = ordering [ i ]; for ( auto u : data_ -> adjacencies_ [ i ] ) { uint64_t newVertex2 = ordering [ u ]; newAdjacencies [ newVertex1 ] . push_back ( newVertex2 ); } } /// Poset newPoset ( newAdjacencies ); /// to recompute ancestors,descendants,parents,children newPoset . reduction (); /// return newPoset; } #endif <|endoftext|>
<commit_before>/** @file config.hpp @brief Configuration. @author Tim Howard @copyright 2013 Tim Howard under the MIT license; see @ref index or the accompanying LICENSE file for full text. */ #ifndef HORD_CONFIG_HPP_ #define HORD_CONFIG_HPP_ #include <cstddef> #include <cstdint> /** @addtogroup config @{ */ /** Allocator for auxiliary specializations. */ #define HORD_AUX_ALLOCATOR std::allocator /** @cond INTERNAL */ #define DUCT_CONFIG_ALLOCATOR HORD_AUX_ALLOCATOR #define MURK_AUX_ALLOCATOR HORD_AUX_ALLOCATOR #define HORD_STRINGIFY_INNER__(x) #x /** @endcond */ /** Stringify an identifier. */ #define HORD_STRINGIFY(x) \ HORD_STRINGIFY_INNER__(x) /** @name Error reporting These macros are for error reporting. A class implementation file should @code #define HORD_SCOPE_CLASS_IDENT__ ClassName @endcode and @code #undef HORD_SCOPE_CLASS_IDENT__ @endcode around its implementation space. Throwing functions should likewise define and undefine @c HORD_SCOPE_FUNC_IDENT__ within the body. All of these macros require these definitions. @note <Hord/String.hpp> and <Hord/Error.hpp> are required to use these. @note The throw macros encapsulate the final message in #HORD_STR_LIT (that is, @a m__ needn't be #HORD_STR_LIT-ized). @remarks I quite despise this method, but there is no @c __fqn__. Luckily, a nice a side-effect of this method is that it cuts down on both implementation complexity and dynamic allocation -- both good in my book, even if the cost is paid in 2 gnarly preprocessing directives per throwing function. @{ */ #ifdef DOXYGEN_CONSISTS_SOLELY_OF_UNICORNS_AND_CONFETTI /** Current class identifier. This is defined surrounding class implementations. */ #define HORD_SCOPE_CLASS_IDENT__ /** Current function identifier. This is defined surrounding function implementations. */ #define HORD_SCOPE_FUNC_IDENT__ #endif /** Returns the string literal of @c HORD_SCOPE_CLASS_IDENT__. */ #define HORD_SCOPE_CLASS \ HORD_STRINGIFY(HORD_SCOPE_CLASS_IDENT__) /** Returns the string literal of @c HORD_SCOPE_FUNC_IDENT__. */ #define HORD_SCOPE_FUNC \ HORD_STRINGIFY(HORD_SCOPE_FUNC_IDENT__) /** Returns the fully-qualified name of the current function. */ #define HORD_SCOPE_FQN \ HORD_SCOPE_CLASS "::" HORD_SCOPE_FUNC /** @cond INTERNAL */ #define HORD_THROW_ERROR_SCOPED_IMPL__(s__, e__, m__) \ throw std::move(::Hord::Error{ \ e__, \ ::Hord::String{HORD_STR_LIT( \ s__ ": " m__ \ )} \ }) /** @endcond */ /** Throw error with class scope. @param e__ ErrorCode. @param m__ Message. @sa HORD_THROW_ERROR_SCOPED_FUNC, HORD_THROW_ERROR_SCOPED_FQN */ #define HORD_THROW_ERROR_SCOPED_CLASS(e__, m__) \ HORD_THROW_ERROR_SCOPED_IMPL__(HORD_SCOPE_CLASS, e__, m__) /** Throw error with function scope. @param e__ ErrorCode. @param m__ Message. @sa HORD_THROW_ERROR_SCOPED_CLASS, HORD_THROW_ERROR_SCOPED_FQN */ #define HORD_THROW_ERROR_SCOPED_FUNC(e__, m__) \ HORD_THROW_ERROR_SCOPED_IMPL__(HORD_SCOPE_FUNC, e__, m__) /** Throw error with fully-qualified scope. @param e__ ErrorCode. @param m__ Message. @sa HORD_THROW_ERROR_SCOPED_CLASS, HORD_THROW_ERROR_SCOPED_FUNC */ #define HORD_THROW_ERROR_SCOPED_FQN(e__, m__) \ HORD_THROW_ERROR_SCOPED_IMPL__(HORD_SCOPE_FQN, e__, m__) /** @} */ // end of name-group Error reporting namespace Hord { } // namespace Hord /** @} */ // end of doc-group config #endif // HORD_CONFIG_HPP_ <commit_msg>config: added MSG_SCOPED defs, unscoped THROW_ERROR & String variant.<commit_after>/** @file config.hpp @brief Configuration. @author Tim Howard @copyright 2013 Tim Howard under the MIT license; see @ref index or the accompanying LICENSE file for full text. */ #ifndef HORD_CONFIG_HPP_ #define HORD_CONFIG_HPP_ #include <cstddef> #include <cstdint> /** @addtogroup config @{ */ /** Allocator for auxiliary specializations. */ #define HORD_AUX_ALLOCATOR std::allocator /** @cond INTERNAL */ #define DUCT_CONFIG_ALLOCATOR HORD_AUX_ALLOCATOR #define MURK_AUX_ALLOCATOR HORD_AUX_ALLOCATOR #define HORD_STRINGIFY_INNER__(x) #x /** @endcond */ /** Stringify an identifier. */ #define HORD_STRINGIFY(x) \ HORD_STRINGIFY_INNER__(x) /** @name Error reporting These macros are for error reporting. A class implementation file should @code #define HORD_SCOPE_CLASS_IDENT__ ClassName @endcode and @code #undef HORD_SCOPE_CLASS_IDENT__ @endcode around its implementation space. Throwing functions should likewise define and undefine @c HORD_SCOPE_FUNC_IDENT__ within the body. All of these macros require these definitions. @note <Hord/String.hpp> and <Hord/Error.hpp> are required to use these. @note All throw macros except for #HORD_THROW_ERROR_S encapsulate the final message in #HORD_STR_LIT (that is, @a m__ needn't be #HORD_STR_LIT-ized). @remarks I quite despise this method, but there is no @c __fqn__. Luckily, a nice a side-effect of this method is that it cuts down on both implementation complexity and dynamic allocation -- both good in my book, even if the cost is paid in 2 gnarly preprocessing directives per throwing function. @{ */ #ifdef DOXYGEN_CONSISTS_SOLELY_OF_UNICORNS_AND_CONFETTI /** Current class identifier. This is defined surrounding class implementations. */ #define HORD_SCOPE_CLASS_IDENT__ /** Current function identifier. This is defined surrounding function implementations. */ #define HORD_SCOPE_FUNC_IDENT__ #endif /** Returns the string literal of @c HORD_SCOPE_CLASS_IDENT__. */ #define HORD_SCOPE_CLASS \ HORD_STRINGIFY(HORD_SCOPE_CLASS_IDENT__) /** Returns the string literal of @c HORD_SCOPE_FUNC_IDENT__. */ #define HORD_SCOPE_FUNC \ HORD_STRINGIFY(HORD_SCOPE_FUNC_IDENT__) /** Returns the fully-qualified name of the current function. */ #define HORD_SCOPE_FQN \ HORD_SCOPE_CLASS "::" HORD_SCOPE_FUNC /** @cond INTERNAL */ #define HORD_MSG_SCOPED_IMPL__(s__, m__) \ HORD_STR_LIT(s__ ": " m__) /** @endcond */ /** Build message string literal with class scope. @param m__ Message. */ #define HORD_MSG_SCOPED_CLASS(m__) \ HORD_MSG_SCOPED_IMPL__(HORD_SCOPE_CLASS, m__) /** Build message string literal with function scope. @param m__ Message. */ #define HORD_MSG_SCOPED_FUNC(m__) \ HORD_MSG_SCOPED_IMPL__(HORD_SCOPE_FUNC, m__) /** Build message string literal with fully-qualified scope. @param m__ Message. */ #define HORD_MSG_SCOPED_FQN(m__) \ HORD_MSG_SCOPED_IMPL__(HORD_SCOPE_FQN, m__) /** @cond INTERNAL */ #define HORD_THROW_ERROR_IMPL__(e__, m__) \ throw std::move(::Hord::Error{ \ e__, \ ::Hord::String{m__} \ }) /** @endcond */ /** Throw error with message. @param e__ ErrorCode. @param m__ Message (string literal). */ #define HORD_THROW_ERROR(e__, m__) \ HORD_THROW_ERROR_IMPL__(e__, HORD_STR_LIT(m__)) /** Throw error with message. @param e__ ErrorCode. @param m__ Message (String). */ #define HORD_THROW_ERROR_S(e__, m__) \ HORD_THROW_ERROR_IMPL__(e__, m__) /** Throw error with class scope. @param e__ ErrorCode. @param m__ Message (string literal). @sa HORD_THROW_ERROR_SCOPED_FUNC, HORD_THROW_ERROR_SCOPED_FQN */ #define HORD_THROW_ERROR_SCOPED_CLASS(e__, m__) \ HORD_THROW_ERROR_IMPL__( \ e__, \ HORD_MSG_SCOPED_CLASS(m__) \ ) /** Throw error with function scope. @param e__ ErrorCode. @param m__ Message (string literal). @sa HORD_THROW_ERROR_SCOPED_CLASS, HORD_THROW_ERROR_SCOPED_FQN */ #define HORD_THROW_ERROR_SCOPED_FUNC(e__, m__) \ HORD_THROW_ERROR_IMPL__( \ e__, \ HORD_MSG_SCOPED_FUNC(m__) \ ) /** Throw error with fully-qualified scope. @param e__ ErrorCode. @param m__ Message (string literal). @sa HORD_THROW_ERROR_SCOPED_CLASS, HORD_THROW_ERROR_SCOPED_FUNC */ #define HORD_THROW_ERROR_SCOPED_FQN(e__, m__) \ HORD_THROW_ERROR_IMPL__( \ e__, \ HORD_MSG_SCOPED_FQN(m__) \ ) /** @} */ // end of name-group Error reporting namespace Hord { } // namespace Hord /** @} */ // end of doc-group config #endif // HORD_CONFIG_HPP_ <|endoftext|>
<commit_before>#pragma once #include "base/assert.hpp" #include <cstddef> #include <functional> #include <unordered_map> #include <boost/circular_buffer.hpp> template<class Key, class Value> class FifoCache { template <typename K, typename V> friend class FifoCacheTest; public: using Loader = std::function<void(Key const & key, Value & value)>; /// \param capacity maximum size of the cache in number of items. /// \param loader Function which is called if it's necessary to load a new item for the cache. FifoCache(size_t capacity, Loader const & loader) : m_fifo(capacity), m_capacity(capacity), m_loader(loader) { } /// \brief Loads value, if it's necessary, by |key| with |m_loader|, puts it to cache and /// returns the reference to the value to |m_map|. Value const & GetValue(const Key & key) { auto const it = m_map.find(key); if (it != m_map.cend()) return it->second; if (Size() >= m_capacity) { CHECK(!m_fifo.empty(), ()); m_map.erase(m_fifo.back()); } m_fifo.push_front(key); auto & v = m_map[key]; m_loader(key, v); return v; } private: size_t Size() const { return m_map.size(); } std::unordered_map<Key, Value> m_map; boost::circular_buffer<Key> m_fifo; size_t m_capacity; Loader m_loader; }; <commit_msg>[base] cpp minor fix, move const to another place.<commit_after>#pragma once #include "base/assert.hpp" #include <cstddef> #include <functional> #include <unordered_map> #include <boost/circular_buffer.hpp> template<class Key, class Value> class FifoCache { template <typename K, typename V> friend class FifoCacheTest; public: using Loader = std::function<void(Key const & key, Value & value)>; /// \param capacity maximum size of the cache in number of items. /// \param loader Function which is called if it's necessary to load a new item for the cache. FifoCache(size_t capacity, Loader const & loader) : m_fifo(capacity), m_capacity(capacity), m_loader(loader) { } /// \brief Loads value, if it's necessary, by |key| with |m_loader|, puts it to cache and /// returns the reference to the value to |m_map|. Value const & GetValue(Key const & key) { auto const it = m_map.find(key); if (it != m_map.cend()) return it->second; if (Size() >= m_capacity) { CHECK(!m_fifo.empty(), ()); m_map.erase(m_fifo.back()); } m_fifo.push_front(key); auto & v = m_map[key]; m_loader(key, v); return v; } private: size_t Size() const { return m_map.size(); } std::unordered_map<Key, Value> m_map; boost::circular_buffer<Key> m_fifo; size_t m_capacity; Loader m_loader; }; <|endoftext|>
<commit_before>// // For more information, please see: http://software.sci.utah.edu // // The MIT License // // Copyright (c) 2009 Scientific Computing and Imaging Institute, // University of Utah. // // // 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. // /// /// @file InterfaceWithTetGen.cc /// @author Martin Cole /// @date Wed Mar 22 07:56:22 2006 /// #include <Modules/Legacy/Fields/InterfaceWithTetGenImpl.h> #include <Core/Thread/Mutex.h> #include <Core/Datatypes/Legacy/Field/Field.h> #include <Core/Datatypes/Legacy/Field/FieldInformation.h> #define TETLIBRARY // Required definition for use of tetgen library #include <tetgen.h> #include <algorithm> #include <sstream> #include <sci_debug.h> #ifdef SCIRUN4_CODE_TO_BE_ENABLED_LATER namespace SCIRun { Mutex TetGenMutex("Protect TetGen from running in parallel"); /// @class InterfaceWithTetGen /// @brief This module interfaces with TetGen. class InterfaceWithTetGenImpl { public: // Constructor/destructor InterfaceWithTetGenImplImpl(); // to run the module virtual void executeImpl(); private: // translate the ui variables into the string with options // that TetGen uses void fillCommandOptions(std::string& commandLine, bool addPoints); GuiInt piecewiseFlag_; // -p GuiInt assignFlag_; // -A GuiInt setNonzeroAttributeFlag_; // -AA GuiInt suppressSplitFlag_; // -Y GuiInt setSplitFlag_; // -YY GuiInt qualityFlag_; // -q GuiInt setRatioFlag_; // -q GuiInt volConstraintFlag_; // -a GuiInt setMaxVolConstraintFlag_; // -a GuiDouble minRadius_; GuiDouble maxVolConstraint_; GuiInt detectIntersectionsFlag_; // -d GuiString moreSwitches_; // additional flags }; DECLARE_MAKER(InterfaceWithTetGen) InterfaceWithTetGen::InterfaceWithTetGen(GuiContext* ctx) : Module("InterfaceWithTetGen", ctx, Filter, "NewField", "SCIRun"), piecewiseFlag_(ctx->subVar("piecewiseFlag"), 1), assignFlag_(ctx->subVar("assignFlag"), 1), setNonzeroAttributeFlag_(ctx->subVar("setNonzeroAttributeFlag"), 0), suppressSplitFlag_(ctx->subVar("suppressSplitFlag"), 1), setSplitFlag_(ctx->subVar("setSplitFlag"), 0), qualityFlag_(ctx->subVar("qualityFlag"), 1), setRatioFlag_(ctx->subVar("setRatioFlag"), 0), volConstraintFlag_(ctx->subVar("volConstraintFlag"), 0), setMaxVolConstraintFlag_(ctx->subVar("setMaxVolConstraintFlag"), 0), // see TetGen documentation for "-q" switch: default is 2.0 minRadius_(ctx->subVar("minRadius"), 2.0), maxVolConstraint_(ctx->subVar("maxVolConstraint"), 0.1), detectIntersectionsFlag_(ctx->subVar("detectIntersectionsFlag"), 0), moreSwitches_(ctx->subVar("moreSwitches"), "") { } void InterfaceWithTetGen::fillCommandOptions(std::string& commandLine, bool addPoints) { // Collect the options in this output string stream std::ostringstream oss; commandLine.clear(); if (addPoints) { oss << "i"; } if (piecewiseFlag_.get()) { oss << "p"; } if (suppressSplitFlag_.get()) { if (setSplitFlag_.get()) { oss << "YY"; } else { oss << "Y"; } } // Always use zero indexing that is the only thing SCIRun knows.... oss << "z"; if (qualityFlag_.get()) { oss << "q"; if (setRatioFlag_.get()) { oss << minRadius_.get(); } } if (volConstraintFlag_.get()) { oss << "a"; if (setMaxVolConstraintFlag_.get()) { oss << maxVolConstraint_.get(); } } if (detectIntersectionsFlag_.get()) { oss << "d"; } if (assignFlag_.get()) { if (setNonzeroAttributeFlag_.get()) { oss << "AA"; } else { oss << "A"; } } // Add in whatever the user wants to add additionally. std::string s = moreSwitches_.get(); if (s.size() > 0) { oss << s; } commandLine = oss.str(); } void InterfaceWithTetGen::execute() { tetgenio in, addin, out; FieldHandle first_surface; std::vector<FieldHandle> surfaces, tsurfaces; get_input_handle("Main", first_surface, true); surfaces.push_back(first_surface); get_dynamic_input_handles("Regions", tsurfaces, false); for (size_t j=0; j< tsurfaces.size(); j++) surfaces.push_back(tsurfaces[j]); FieldHandle points; get_input_handle("Points", points, false); FieldHandle region_attribs; get_input_handle( "Region Attribs", region_attribs, false); if (inputs_changed_ || piecewiseFlag_.changed() || assignFlag_.changed() || setNonzeroAttributeFlag_.changed() || suppressSplitFlag_.changed() || setSplitFlag_.changed() || qualityFlag_.changed() || setRatioFlag_.changed() || volConstraintFlag_.changed() || setMaxVolConstraintFlag_.changed() || minRadius_.changed() || maxVolConstraint_.changed() || detectIntersectionsFlag_.changed() || moreSwitches_.changed() || !oport_cached("TetVol")) { // Tell SCIRun we are actually doing some work update_state(Executing); bool add_points = false; if (points.get_rep()) { VMesh* mesh = points->vmesh(); VMesh::Node::size_type num_nodes = mesh->num_nodes(); addin.numberofpoints = num_nodes; addin.pointlist = new REAL[num_nodes*3]; for(VMesh::Node::index_type idx=0; idx<num_nodes; idx++) { Point p; mesh->get_center(p, idx); addin.pointlist[idx * 3] = p.x(); addin.pointlist[idx * 3 + 1] = p.y(); addin.pointlist[idx * 3 + 2] = p.z(); } add_points = true; remark("Added extra interior points from Points port."); } if (region_attribs.get_rep()) { VMesh* mesh = region_attribs->vmesh(); VField* field = region_attribs->vfield(); VMesh::Node::size_type num_nodes = mesh->num_nodes(); in.regionlist = new REAL[num_nodes*5]; in.numberofregions = num_nodes; for(VMesh::Node::index_type idx=0; idx<num_nodes; idx++) { Point p; double val; mesh->get_center(p, idx); in.regionlist[idx * 5] = p.x(); in.regionlist[idx * 5 + 1] = p.y(); in.regionlist[idx * 5 + 2] = p.z(); in.regionlist[idx * 5 + 3] = idx; field->get_value(val, idx); in.regionlist[idx * 5 + 4] = val; } } // indices start from 0. in.firstnumber = 0; in.mesh_dim = 3; int marker = -10; VMesh::size_type tot_num_nodes = 0; VMesh::size_type tot_num_elems = 0; for (size_t j=0; j< surfaces.size(); j++) { VMesh* mesh = surfaces[j]->vmesh(); VMesh::Node::size_type num_nodes = mesh->num_nodes(); VMesh::Elem::size_type num_elems = mesh->num_elems(); tot_num_nodes += num_nodes; tot_num_elems += num_elems; } in.pointlist = new REAL[(tot_num_nodes) * 3]; in.numberofpoints = tot_num_nodes; in.facetlist = new tetgenio::facet[tot_num_elems]; in.facetmarkerlist = new int[tot_num_elems]; in.numberoffacets = tot_num_elems; VMesh::index_type idx = 0; VMesh::index_type fidx = 0; VMesh::index_type off = 0; for (size_t j=0; j< surfaces.size(); j++) { VMesh* mesh = surfaces[j]->vmesh(); VMesh::Node::size_type num_nodes = mesh->num_nodes(); VMesh::Elem::size_type num_elems = mesh->num_elems(); off = idx; for(VMesh::Node::index_type nidx=0; nidx<num_nodes; nidx++) { Point p; mesh->get_center(p, nidx); in.pointlist[idx * 3] = p.x(); in.pointlist[idx * 3 + 1] = p.y(); in.pointlist[idx * 3 + 2] = p.z(); ++idx; } unsigned int vert_per_face = mesh->num_nodes_per_elem(); // iterate over faces. VMesh::Node::array_type nodes; for(VMesh::Elem::index_type eidx=0; eidx<num_elems; eidx++) { tetgenio::facet *f = &in.facetlist[fidx]; f->numberofpolygons = 1; f->polygonlist = new tetgenio::polygon[1]; f->numberofholes = 0; f->holelist = 0; tetgenio::polygon *p = &f->polygonlist[0]; p->numberofvertices = vert_per_face; p->vertexlist = new int[p->numberofvertices]; mesh->get_nodes(nodes, eidx); for (size_t j=0; j<nodes.size(); j++) { p->vertexlist[j] = VMesh::index_type(nodes[j]) + off; } in.facetmarkerlist[fidx] = marker; ++fidx; } marker *= 2; } update_progress(.2); // Save files for later debugging. // std::string filename = std::string(sci_getenv("SCIRUN_TMP_DIR")) + "/tgIN"; // in.save_nodes((char*)filename.c_str()); // in.save_poly((char*)filename.c_str()); std::string cmmd_ln; fillCommandOptions(cmmd_ln, add_points); #if DEBUG std::cerr << "\nTetgen command line: " << cmmd_ln << std::endl; #endif tetgenio *addtgio = 0; if (add_points) { addtgio = &addin; } // Create the new mesh. // Make sure only one thread accesses TetGen // It is not thread safe :) TetGenMutex.lock(); try { tetrahedralize((char*)cmmd_ln.c_str(), &in, &out, addtgio); } catch(...) { TetGenMutex.unlock(); error("TetGen failed to generate a mesh"); return; } TetGenMutex.unlock(); update_progress(.9); FieldInformation fi(TETVOLMESH_E,CONSTANTDATA_E,DOUBLE_E); FieldHandle tetvol_out = CreateField(fi); // Convert to a SCIRun TetVol. VMesh* mesh = tetvol_out->vmesh(); VField* field = tetvol_out->vfield(); for (int i = 0; i < out.numberofpoints; i++) { Point p(out.pointlist[i*3], out.pointlist[i*3+1], out.pointlist[i*3+2]); mesh->add_point(p); } VMesh::Node::size_type numnodes = mesh->num_nodes(); VMesh::Node::array_type nodes(4); for (int i = 0; i < out.numberoftetrahedra; i++) { nodes[0] = out.tetrahedronlist[i*4]; nodes[1] = out.tetrahedronlist[i*4+1]; nodes[2] = out.tetrahedronlist[i*4+2]; nodes[3] = out.tetrahedronlist[i*4+3]; if (nodes[0] >= numnodes ||nodes[1] >= numnodes || nodes[2] >= numnodes ||nodes[3] >= numnodes ) { error("TetGen failed to produce a valid tetrahedralization"); return; } mesh->add_elem(nodes); } field->resize_values(); int atts = out.numberoftetrahedronattributes; for (int i = 0; i < out.numberoftetrahedra; i++) { for (int j = 0; j < atts; j++) { double val = out.tetrahedronattributelist[i * atts + j]; field->set_value(val, VMesh::Elem::index_type(i)); } } update_progress(1.0); // Send the output to SCIRun send_output_handle("TetVol", tetvol_out); } } } // end namespace SCIRun #endif<commit_msg>Include path issue<commit_after>// // For more information, please see: http://software.sci.utah.edu // // The MIT License // // Copyright (c) 2009 Scientific Computing and Imaging Institute, // University of Utah. // // // 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. // /// /// @file InterfaceWithTetGen.cc /// @author Martin Cole /// @date Wed Mar 22 07:56:22 2006 /// #include <Modules/Legacy/Fields/InterfaceWithTetGenImpl.h> #include <Core/Thread/Mutex.h> #include <Core/Datatypes/Legacy/Field/Field.h> #include <Core/Datatypes/Legacy/Field/FieldInformation.h> #define TETLIBRARY // Required definition for use of tetgen library #include <tetgen/tetgen.h> #include <algorithm> #include <sstream> #include <sci_debug.h> #ifdef SCIRUN4_CODE_TO_BE_ENABLED_LATER namespace SCIRun { Mutex TetGenMutex("Protect TetGen from running in parallel"); /// @class InterfaceWithTetGen /// @brief This module interfaces with TetGen. class InterfaceWithTetGenImpl { public: // Constructor/destructor InterfaceWithTetGenImplImpl(); // to run the module virtual void executeImpl(); private: // translate the ui variables into the string with options // that TetGen uses void fillCommandOptions(std::string& commandLine, bool addPoints); GuiInt piecewiseFlag_; // -p GuiInt assignFlag_; // -A GuiInt setNonzeroAttributeFlag_; // -AA GuiInt suppressSplitFlag_; // -Y GuiInt setSplitFlag_; // -YY GuiInt qualityFlag_; // -q GuiInt setRatioFlag_; // -q GuiInt volConstraintFlag_; // -a GuiInt setMaxVolConstraintFlag_; // -a GuiDouble minRadius_; GuiDouble maxVolConstraint_; GuiInt detectIntersectionsFlag_; // -d GuiString moreSwitches_; // additional flags }; DECLARE_MAKER(InterfaceWithTetGen) InterfaceWithTetGen::InterfaceWithTetGen(GuiContext* ctx) : Module("InterfaceWithTetGen", ctx, Filter, "NewField", "SCIRun"), piecewiseFlag_(ctx->subVar("piecewiseFlag"), 1), assignFlag_(ctx->subVar("assignFlag"), 1), setNonzeroAttributeFlag_(ctx->subVar("setNonzeroAttributeFlag"), 0), suppressSplitFlag_(ctx->subVar("suppressSplitFlag"), 1), setSplitFlag_(ctx->subVar("setSplitFlag"), 0), qualityFlag_(ctx->subVar("qualityFlag"), 1), setRatioFlag_(ctx->subVar("setRatioFlag"), 0), volConstraintFlag_(ctx->subVar("volConstraintFlag"), 0), setMaxVolConstraintFlag_(ctx->subVar("setMaxVolConstraintFlag"), 0), // see TetGen documentation for "-q" switch: default is 2.0 minRadius_(ctx->subVar("minRadius"), 2.0), maxVolConstraint_(ctx->subVar("maxVolConstraint"), 0.1), detectIntersectionsFlag_(ctx->subVar("detectIntersectionsFlag"), 0), moreSwitches_(ctx->subVar("moreSwitches"), "") { } void InterfaceWithTetGen::fillCommandOptions(std::string& commandLine, bool addPoints) { // Collect the options in this output string stream std::ostringstream oss; commandLine.clear(); if (addPoints) { oss << "i"; } if (piecewiseFlag_.get()) { oss << "p"; } if (suppressSplitFlag_.get()) { if (setSplitFlag_.get()) { oss << "YY"; } else { oss << "Y"; } } // Always use zero indexing that is the only thing SCIRun knows.... oss << "z"; if (qualityFlag_.get()) { oss << "q"; if (setRatioFlag_.get()) { oss << minRadius_.get(); } } if (volConstraintFlag_.get()) { oss << "a"; if (setMaxVolConstraintFlag_.get()) { oss << maxVolConstraint_.get(); } } if (detectIntersectionsFlag_.get()) { oss << "d"; } if (assignFlag_.get()) { if (setNonzeroAttributeFlag_.get()) { oss << "AA"; } else { oss << "A"; } } // Add in whatever the user wants to add additionally. std::string s = moreSwitches_.get(); if (s.size() > 0) { oss << s; } commandLine = oss.str(); } void InterfaceWithTetGen::execute() { tetgenio in, addin, out; FieldHandle first_surface; std::vector<FieldHandle> surfaces, tsurfaces; get_input_handle("Main", first_surface, true); surfaces.push_back(first_surface); get_dynamic_input_handles("Regions", tsurfaces, false); for (size_t j=0; j< tsurfaces.size(); j++) surfaces.push_back(tsurfaces[j]); FieldHandle points; get_input_handle("Points", points, false); FieldHandle region_attribs; get_input_handle( "Region Attribs", region_attribs, false); if (inputs_changed_ || piecewiseFlag_.changed() || assignFlag_.changed() || setNonzeroAttributeFlag_.changed() || suppressSplitFlag_.changed() || setSplitFlag_.changed() || qualityFlag_.changed() || setRatioFlag_.changed() || volConstraintFlag_.changed() || setMaxVolConstraintFlag_.changed() || minRadius_.changed() || maxVolConstraint_.changed() || detectIntersectionsFlag_.changed() || moreSwitches_.changed() || !oport_cached("TetVol")) { // Tell SCIRun we are actually doing some work update_state(Executing); bool add_points = false; if (points.get_rep()) { VMesh* mesh = points->vmesh(); VMesh::Node::size_type num_nodes = mesh->num_nodes(); addin.numberofpoints = num_nodes; addin.pointlist = new REAL[num_nodes*3]; for(VMesh::Node::index_type idx=0; idx<num_nodes; idx++) { Point p; mesh->get_center(p, idx); addin.pointlist[idx * 3] = p.x(); addin.pointlist[idx * 3 + 1] = p.y(); addin.pointlist[idx * 3 + 2] = p.z(); } add_points = true; remark("Added extra interior points from Points port."); } if (region_attribs.get_rep()) { VMesh* mesh = region_attribs->vmesh(); VField* field = region_attribs->vfield(); VMesh::Node::size_type num_nodes = mesh->num_nodes(); in.regionlist = new REAL[num_nodes*5]; in.numberofregions = num_nodes; for(VMesh::Node::index_type idx=0; idx<num_nodes; idx++) { Point p; double val; mesh->get_center(p, idx); in.regionlist[idx * 5] = p.x(); in.regionlist[idx * 5 + 1] = p.y(); in.regionlist[idx * 5 + 2] = p.z(); in.regionlist[idx * 5 + 3] = idx; field->get_value(val, idx); in.regionlist[idx * 5 + 4] = val; } } // indices start from 0. in.firstnumber = 0; in.mesh_dim = 3; int marker = -10; VMesh::size_type tot_num_nodes = 0; VMesh::size_type tot_num_elems = 0; for (size_t j=0; j< surfaces.size(); j++) { VMesh* mesh = surfaces[j]->vmesh(); VMesh::Node::size_type num_nodes = mesh->num_nodes(); VMesh::Elem::size_type num_elems = mesh->num_elems(); tot_num_nodes += num_nodes; tot_num_elems += num_elems; } in.pointlist = new REAL[(tot_num_nodes) * 3]; in.numberofpoints = tot_num_nodes; in.facetlist = new tetgenio::facet[tot_num_elems]; in.facetmarkerlist = new int[tot_num_elems]; in.numberoffacets = tot_num_elems; VMesh::index_type idx = 0; VMesh::index_type fidx = 0; VMesh::index_type off = 0; for (size_t j=0; j< surfaces.size(); j++) { VMesh* mesh = surfaces[j]->vmesh(); VMesh::Node::size_type num_nodes = mesh->num_nodes(); VMesh::Elem::size_type num_elems = mesh->num_elems(); off = idx; for(VMesh::Node::index_type nidx=0; nidx<num_nodes; nidx++) { Point p; mesh->get_center(p, nidx); in.pointlist[idx * 3] = p.x(); in.pointlist[idx * 3 + 1] = p.y(); in.pointlist[idx * 3 + 2] = p.z(); ++idx; } unsigned int vert_per_face = mesh->num_nodes_per_elem(); // iterate over faces. VMesh::Node::array_type nodes; for(VMesh::Elem::index_type eidx=0; eidx<num_elems; eidx++) { tetgenio::facet *f = &in.facetlist[fidx]; f->numberofpolygons = 1; f->polygonlist = new tetgenio::polygon[1]; f->numberofholes = 0; f->holelist = 0; tetgenio::polygon *p = &f->polygonlist[0]; p->numberofvertices = vert_per_face; p->vertexlist = new int[p->numberofvertices]; mesh->get_nodes(nodes, eidx); for (size_t j=0; j<nodes.size(); j++) { p->vertexlist[j] = VMesh::index_type(nodes[j]) + off; } in.facetmarkerlist[fidx] = marker; ++fidx; } marker *= 2; } update_progress(.2); // Save files for later debugging. // std::string filename = std::string(sci_getenv("SCIRUN_TMP_DIR")) + "/tgIN"; // in.save_nodes((char*)filename.c_str()); // in.save_poly((char*)filename.c_str()); std::string cmmd_ln; fillCommandOptions(cmmd_ln, add_points); #if DEBUG std::cerr << "\nTetgen command line: " << cmmd_ln << std::endl; #endif tetgenio *addtgio = 0; if (add_points) { addtgio = &addin; } // Create the new mesh. // Make sure only one thread accesses TetGen // It is not thread safe :) TetGenMutex.lock(); try { tetrahedralize((char*)cmmd_ln.c_str(), &in, &out, addtgio); } catch(...) { TetGenMutex.unlock(); error("TetGen failed to generate a mesh"); return; } TetGenMutex.unlock(); update_progress(.9); FieldInformation fi(TETVOLMESH_E,CONSTANTDATA_E,DOUBLE_E); FieldHandle tetvol_out = CreateField(fi); // Convert to a SCIRun TetVol. VMesh* mesh = tetvol_out->vmesh(); VField* field = tetvol_out->vfield(); for (int i = 0; i < out.numberofpoints; i++) { Point p(out.pointlist[i*3], out.pointlist[i*3+1], out.pointlist[i*3+2]); mesh->add_point(p); } VMesh::Node::size_type numnodes = mesh->num_nodes(); VMesh::Node::array_type nodes(4); for (int i = 0; i < out.numberoftetrahedra; i++) { nodes[0] = out.tetrahedronlist[i*4]; nodes[1] = out.tetrahedronlist[i*4+1]; nodes[2] = out.tetrahedronlist[i*4+2]; nodes[3] = out.tetrahedronlist[i*4+3]; if (nodes[0] >= numnodes ||nodes[1] >= numnodes || nodes[2] >= numnodes ||nodes[3] >= numnodes ) { error("TetGen failed to produce a valid tetrahedralization"); return; } mesh->add_elem(nodes); } field->resize_values(); int atts = out.numberoftetrahedronattributes; for (int i = 0; i < out.numberoftetrahedra; i++) { for (int j = 0; j < atts; j++) { double val = out.tetrahedronattributelist[i * atts + j]; field->set_value(val, VMesh::Elem::index_type(i)); } } update_progress(1.0); // Send the output to SCIRun send_output_handle("TetVol", tetvol_out); } } } // end namespace SCIRun #endif<|endoftext|>
<commit_before>/****************************************************************************** * _ _____ __________ * * | | / / _ | / __/_ __/ Visibility * * | |/ / __ |_\ \ / / Across * * |___/_/ |_/___/ /_/ Space and Time * * * * This file is part of VAST. It is subject to the license terms in the * * LICENSE file found in the top-level directory of this distribution and at * * http://vast.io/license. No part of VAST, including this file, may be * * copied, modified, propagated, or distributed except according to the terms * * contained in the LICENSE file. * ******************************************************************************/ #include "vast/system/default_configuration.hpp" #include <caf/timestamp.hpp> #include "vast/defaults.hpp" #include "vast/detail/system.hpp" #include "vast/error.hpp" #include "vast/filesystem.hpp" #include "vast/system/application.hpp" namespace vast::system { path make_log_dirname() { auto dir_name = caf::deep_to_string(caf::make_timestamp()); dir_name += '#'; dir_name += std::to_string(detail::process_id()); return path{"log"} / dir_name; } default_configuration::default_configuration(std::string application_name) : application_name{std::move(application_name)} { // Tweak default logging options. set("logger.component-filter", "vast"); set("logger.console", caf::atom("COLORED")); set("logger.file-verbosity", caf::atom("DEBUG")); // Allow VAST clusters to form a mesh. set("middleman.enable-automatic-connections", true); } caf::expected<path> default_configuration::setup_log_file(const path& base_dir) { auto log_dir = base_dir / make_log_dirname(); // Create the log directory first, which we need to create the symlink // afterwards. if (!exists(log_dir)) if (auto res = mkdir(log_dir); !res) return res.error(); // Create user-friendly symlink to current log directory. auto link_dir = log_dir.chop(-1) / "current"; if (exists(link_dir)) if (!rm(link_dir)) return make_error(ec::filesystem_error, "cannot remove log symlink"); create_symlink(log_dir.trim(-1), link_dir); return log_dir / application_name + ".log"; } // Parses the options from the root command and adds them to the global // configuration. caf::error default_configuration::merge_root_options(system::application& app) { // Delegate to the root command for argument parsing. caf::settings options; app.root.options.parse(options, command_line.begin(), command_line.end()); // Move everything into the system-wide options, but use "vast" as category // instead of the default "global" category. content["vast"].as_dictionary().insert(options.begin(), options.end()); if (!caf::get_if<std::string>(this, "logger.file-name")) { path dir = get_or(*this, "vast.dir", defaults::command::directory); if (auto log_file = setup_log_file(dir.complete()); !log_file) { std::cerr << "failed to setup log file: " << to_string(log_file.error()) << std::endl; return log_file.error(); } else { set("logger.file-name", log_file->str()); } } return caf::none; } } // namespace vast::system <commit_msg>Fix log file initialization<commit_after>/****************************************************************************** * _ _____ __________ * * | | / / _ | / __/_ __/ Visibility * * | |/ / __ |_\ \ / / Across * * |___/_/ |_/___/ /_/ Space and Time * * * * This file is part of VAST. It is subject to the license terms in the * * LICENSE file found in the top-level directory of this distribution and at * * http://vast.io/license. No part of VAST, including this file, may be * * copied, modified, propagated, or distributed except according to the terms * * contained in the LICENSE file. * ******************************************************************************/ #include "vast/system/default_configuration.hpp" #include <caf/defaults.hpp> #include <caf/timestamp.hpp> #include "vast/defaults.hpp" #include "vast/detail/system.hpp" #include "vast/error.hpp" #include "vast/filesystem.hpp" #include "vast/system/application.hpp" namespace vast::system { path make_log_dirname() { auto dir_name = caf::deep_to_string(caf::make_timestamp()); dir_name += '#'; dir_name += std::to_string(detail::process_id()); return path{"log"} / dir_name; } default_configuration::default_configuration(std::string application_name) : application_name{std::move(application_name)} { // Tweak default logging options. set("logger.component-filter", "vast"); set("logger.console", caf::atom("COLORED")); set("logger.file-verbosity", caf::atom("DEBUG")); // Allow VAST clusters to form a mesh. set("middleman.enable-automatic-connections", true); } caf::expected<path> default_configuration::setup_log_file(const path& base_dir) { auto log_dir = base_dir / make_log_dirname(); // Create the log directory first, which we need to create the symlink // afterwards. if (!exists(log_dir)) if (auto res = mkdir(log_dir); !res) return res.error(); // Create user-friendly symlink to current log directory. auto link_dir = log_dir.chop(-1) / "current"; if (exists(link_dir)) if (!rm(link_dir)) return make_error(ec::filesystem_error, "cannot remove log symlink"); create_symlink(log_dir.trim(-1), link_dir); return log_dir / application_name + ".log"; } // Parses the options from the root command and adds them to the global // configuration. caf::error default_configuration::merge_root_options(system::application& app) { // Delegate to the root command for argument parsing. caf::settings options; app.root.options.parse(options, command_line.begin(), command_line.end()); // Move everything into the system-wide options, but use "vast" as category // instead of the default "global" category. content["vast"].as_dictionary().insert(options.begin(), options.end()); auto default_fn = caf::defaults::logger::file_name; if (caf::get_or(*this, "logger.file-name", default_fn) == default_fn) { path dir = get_or(*this, "vast.dir", defaults::command::directory); if (auto log_file = setup_log_file(dir.complete()); !log_file) { std::cerr << "failed to setup log file: " << to_string(log_file.error()) << std::endl; return log_file.error(); } else { set("logger.file-name", log_file->str()); } } return caf::none; } } // namespace vast::system <|endoftext|>
<commit_before><commit_msg>Snapshot explorer hwp and xml from ekb/master<commit_after><|endoftext|>
<commit_before>#include <iostream> #include <array> #include <asio/steady_timer.hpp> #include <asio.hpp> #include <chrono> using namespace std; using asio::ip::udp; class server { public: server(asio::io_service& io_service, short listen_port, short send_port) : io_service_(io_service), socket_(io_service, udp::endpoint(udp::v4(), listen_port)), timer_(io_service) { if(send_port > 0) { udp::resolver resolver(io_service); udp::resolver::query query(udp::v4(), "localhost", std::to_string(send_port)); udp::endpoint send_point = *resolver.resolve(query); std::array<int, 1> data { 1 }; socket_.async_send_to(asio::buffer(data), send_point, [this](std::error_code /*ec*/, std::size_t /*bytes_sent*/) { std::cout << "Sent kickoff message." << std::endl; }); } do_receive(); } private: void do_receive() { socket_.async_receive_from( asio::buffer(data_), remote_endpoint_, [this](std::error_code ec, std::size_t bytes_recvd) { if(!ec && bytes_recvd > 0) { data_[0]++; std::cout << data_[0] << std::endl; timer_.expires_from_now(std::chrono::milliseconds(500)); timer_.wait(); do_send(bytes_recvd); } else { do_receive(); } }); } void do_send(std::size_t length) { socket_.async_send_to( asio::buffer(data_), remote_endpoint_, [this](std::error_code /*ec*/, std::size_t /*bytes_sent*/){ do_receive(); }); } asio::steady_timer timer_; asio::io_service &io_service_; udp::socket socket_; udp::endpoint remote_endpoint_; enum { max_length = 1024 }; std::array<int, 1> data_; }; int main(int argc, char* argv[]) { try { if(argc < 2 || argc > 3) { std::cerr << "Usage: node <port>\n"; return 1; } short send_port = -1; if(argc == 3) { send_port = std::atoi(argv[2]); } asio::io_service io_service; server c(io_service, std::atoi(argv[1]), send_port); io_service.run(); } catch(std::exception& e) { std::cerr << "Error" << std::endl; std::cerr << e.what() << std::endl; } return 0; }<commit_msg>Added state enum to server class.<commit_after>#include <iostream> #include <array> #include <asio/steady_timer.hpp> #include <asio.hpp> #include <chrono> using namespace std; using asio::ip::udp; class server { public: server(asio::io_service& io_service, short listen_port, short send_port) : io_service_(io_service), socket_(io_service, udp::endpoint(udp::v4(), listen_port)), timer_(io_service) { if(send_port > 0) { udp::resolver resolver(io_service); udp::resolver::query query(udp::v4(), "localhost", std::to_string(send_port)); udp::endpoint send_point = *resolver.resolve(query); std::array<int, 1> data { 1 }; socket_.async_send_to(asio::buffer(data), send_point, [this](std::error_code /*ec*/, std::size_t /*bytes_sent*/) { std::cout << "Sent kickoff message." << std::endl; }); } do_receive(); } private: enum class state{ Follower, Candidate, Leader }; void do_receive() { socket_.async_receive_from( asio::buffer(data_), remote_endpoint_, [this](std::error_code ec, std::size_t bytes_recvd) { if(!ec && bytes_recvd > 0) { data_[0]++; std::cout << data_[0] << std::endl; timer_.expires_from_now(std::chrono::milliseconds(500)); timer_.wait(); do_send(bytes_recvd); } else { do_receive(); } }); } void do_send(std::size_t length) { socket_.async_send_to( asio::buffer(data_), remote_endpoint_, [this](std::error_code /*ec*/, std::size_t /*bytes_sent*/){ do_receive(); }); } state state_; asio::steady_timer timer_; asio::io_service &io_service_; udp::socket socket_; udp::endpoint remote_endpoint_; enum { max_length = 1024 }; std::array<int, 1> data_; }; int main(int argc, char* argv[]) { try { if(argc < 2 || argc > 3) { std::cerr << "Usage: node <port>\n"; return 1; } short send_port = -1; if(argc == 3) { send_port = std::atoi(argv[2]); } asio::io_service io_service; server c(io_service, std::atoi(argv[1]), send_port); io_service.run(); } catch(std::exception& e) { std::cerr << "Error" << std::endl; std::cerr << e.what() << std::endl; } return 0; }<|endoftext|>
<commit_before>#ifndef CLPP_EXCEPTION2_H #define CLPP_EXCEPTION2_H #include "clpp/detail/common.hpp" #include <stdexcept> #include <string> namespace cl { namespace error { class AnyError : public std::runtime_error { public: using std::runtime_error::runtime_error; virtual auto what() const noexcept -> const char * = 0; virtual auto code() const noexcept -> RetCode = 0; }; #define EXCEPTION(ExceptionName, RetCode, Msg) \ class ExceptionName final : public AnyError { \ public: \ using AnyError::AnyError; \ auto what() const override noexcept -> const char*; \ auto code() const override noexcept -> RetCode; \ }; \ \ auto ExceptionName::what() const override noexcept \ -> const char * \ { \ return Msg; \ } \ \ auto ExceptionName::code() const override noexcept \ -> RetCode \ { \ return RetCode; \ } EXCEPTION(DeviceNotFound, RetCode::deviceNotFound, "device not found") EXCEPTION(DeviceNotAvailable, RetCode::deviceNotAvailable, "device not available") EXCEPTION(CompilerNotAvailable, RetCode::compilerNotAvailable, "compiler not available") EXCEPTION(MemoryObjectAllocFailure, RetCode::memoryObjectAllocationFailure, "memory object allocation failure") EXCEPTION(OutOfResources, RetCode::outOfResources, "out of resources") EXCEPTION(OutOfHostMemory, RetCode::outOfHostMemory, "out of host memory") EXCEPTION(ProfilingInfoNotAvailable, RetCode::profilingInfoNotAvailable, "profiling info not available") EXCEPTION(MemoryCopyOverlap, RetCode::memoryCopyOverlap, "memory copy overlap") EXCEPTION(ImageFormatMismatch, RetCode::imageFormatMismatch, "image format mismatch") EXCEPTION(ImageFormatNotSupported, RetCode::imageFormatNotSupported, "image format not supported") EXCEPTION(BuildProgramFailure, RetCode::buildProgramFailure, "build program failure") EXCEPTION(MapFailure, RetCode::mapFailure, "map failure") EXCEPTION(MisalignedSubBufferOffset, RetCode::misalignedSubBufferOffset, "misaligned sub buffer offset") EXCEPTION(ExecStatusErrorForEventsInWaitList, RetCode::executeStatusErrorForEventsInWaitList, "execute status error for events in wait list") EXCEPTION(CompileProgramFailure, RetCode::compileProgramFailure, "compile program failure") EXCEPTION(LinkerNotAvailable, RetCode::linkerNotAvailable, "linker not available") EXCEPTION(LinkProgramFailure, RetCode::linkProgramFailure, "link program failure") EXCEPTION(DevicePartitionFailure, RetCode::devicePartitionFailed, "device partition failure") EXCEPTION(KernelArgInfoNotAvailable, RetCode::kernelArgumentInfoNotAvailable, "kernel argument not available") EXCEPTION(InvalidValue, RetCode::invalidValue, "invalid value") EXCEPTION(InvalidDeviceType, RetCode::invalidDeviceType, "invalid device type") EXCEPTION(InvalidPlatform, RetCode::invalidPlatform, "invalid platform") EXCEPTION(InvalidDevice, RetCode::invalidDevice, "invalid device") EXCEPTION(InvalidContext, RetCode::invalidContext, "invalid context") EXCEPTION(InvalidQueueProperties, RetCode::invalidQueueProperties, "invalid command queue properties") EXCEPTION(InvalidCommandQueue, RetCode::invalidCommandQueue, "invalid command queue") EXCEPTION(InvalidHostPtr, RetCode::invalidHostPtr, "invalid host pointer") EXCEPTION(InvalidMemoryObject, RetCode::invalidMemoryObject, "invalid memory object") EXCEPTION(InvalidImageFormatDescriptor, RetCode::invalidImageFormatDescriptor, "invalid image format descriptor") EXCEPTION(InvalidImageSize, RetCode::invalidImageSize, "invalid image size") EXCEPTION(InvalidSampler, RetCode::invalidSampler, "invalid sampler") EXCEPTION(InvalidBinary, RetCode::invalidBinary, "invalid binary") EXCEPTION(InvalidBuildOptions, RetCode::invalidBuildOptions, "invalid build options") EXCEPTION(InvalidProgram, RetCode::invalidProgram, "invalid program") EXCEPTION(InvalidProgramExecutable, RetCode::invalidProgramExecutable, "invalid program executable") EXCEPTION(InvalidKernelName, RetCode::invalidKernelName, "invalid kernel name") EXCEPTION(InvalidKernelDefinition, RetCode::invalidKernelDefinition, "invalid kernel definition") EXCEPTION(InvalidKernel, RetCode::invalidKernel, "invalid kernel") EXCEPTION(InvalidArgIndex, RetCode::invalidArgumentIndex, "invalid argument index") EXCEPTION(InvalidArgValue, RetCode::invalidArgumentValue, "invalid argument value") EXCEPTION(InvalidArgSize, RetCode::invalidArgumentSize, "invalid argument size") EXCEPTION(InvalidKernelArgs, RetCode::invalidKernelArguments, "invalid kernel arguments") EXCEPTION(InvalidWorkDimension, RetCode::invalidWorkDimension, "invalid work dimension") EXCEPTION(InvalidWorkGroupSize, RetCode::invalidWorkGroupSize, "invalid work group size") EXCEPTION(InvalidWorkItemSize, RetCode::invalidWorkItemSize, "invalid work item size") EXCEPTION(InvalidGlobalOffset, RetCode::invalidGlobalOffset, "invalid global offset") EXCEPTION(InvalidEventWaitList, RetCode::invalidEventWaitList, "invalid event wait list") EXCEPTION(InvalidEvent, RetCode::invalidEvent, "invalid event") EXCEPTION(InvalidOperation, RetCode::invalidOperation, "invalid operation") EXCEPTION(InvalidGLObject, RetCode::invalidGlObject, "invalid OpenGL object") EXCEPTION(InvalidBufferSize, RetCode::invalidBufferSize, "invalid buffer size") EXCEPTION(InvalidMipLevel, RetCode::invalidMipLevel, "invalid MIP level") EXCEPTION(InvalidGlobalWorkSize, RetCode::invalidGlobalWorkSize, "invalid global work size") EXCEPTION(InvalidProperty, RetCode::invalidProperty, "invalid property") EXCEPTION(InvalidImageDescriptor, RetCode::invalidImageDescriptor, "invalid image descriptor") EXCEPTION(InvalidCompilerOptions, RetCode::invalidCompilerOptions, "invalid compiler options") EXCEPTION(InvalidLinkerOptions, RetCode::invalidLinkerOptions, "invalid linker options") EXCEPTION(InvalidDevicePartitionCount, RetCode::invalidDevicePartitionCount, "invalid device partition count") #undef EXCEPTION } } #endif <commit_msg>remade exceptions 2<commit_after>#ifndef CLPP_EXCEPTION2_H #define CLPP_EXCEPTION2_H #include "clpp/detail/common.hpp" #include <stdexcept> #include <string> namespace cl { namespace error { class AnyError : public std::runtime_error { public: using std::runtime_error::runtime_error; virtual auto what() const noexcept -> const char * = 0; virtual auto code() const noexcept -> RetCode = 0; }; #define EXCEPTION(ExceptionName, RetCode, Msg) \ class ExceptionName final : public AnyError { \ public: \ using AnyError::AnyError; \ auto what() const override noexcept -> const char*; \ auto code() const override noexcept -> RetCode; \ }; \ \ auto ExceptionName::what() const override noexcept \ -> const char * \ { \ return Msg; \ } \ \ auto ExceptionName::code() const override noexcept \ -> RetCode \ { \ return RetCode; \ } EXCEPTION(DeviceNotFound, RetCode::deviceNotFound, "device not found") EXCEPTION(DeviceNotAvailable, RetCode::deviceNotAvailable, "device not available") EXCEPTION(CompilerNotAvailable, RetCode::compilerNotAvailable, "compiler not available") EXCEPTION(MemoryObjectAllocFailure, RetCode::memoryObjectAllocationFailure, "memory object allocation failure") EXCEPTION(OutOfResources, RetCode::outOfResources, "out of resources") EXCEPTION(OutOfHostMemory, RetCode::outOfHostMemory, "out of host memory") EXCEPTION(ProfilingInfoNotAvailable, RetCode::profilingInfoNotAvailable, "profiling info not available") EXCEPTION(MemoryCopyOverlap, RetCode::memoryCopyOverlap, "memory copy overlap") EXCEPTION(ImageFormatMismatch, RetCode::imageFormatMismatch, "image format mismatch") EXCEPTION(ImageFormatNotSupported, RetCode::imageFormatNotSupported, "image format not supported") EXCEPTION(BuildProgramFailure, RetCode::buildProgramFailure, "build program failure") EXCEPTION(MapFailure, RetCode::mapFailure, "map failure") EXCEPTION(MisalignedSubBufferOffset, RetCode::misalignedSubBufferOffset, "misaligned sub buffer offset") EXCEPTION(ExecStatusErrorForEventsInWaitList, RetCode::executeStatusErrorForEventsInWaitList, "execute status error for events in wait list") EXCEPTION(CompileProgramFailure, RetCode::compileProgramFailure, "compile program failure") EXCEPTION(LinkerNotAvailable, RetCode::linkerNotAvailable, "linker not available") EXCEPTION(LinkProgramFailure, RetCode::linkProgramFailure, "link program failure") EXCEPTION(DevicePartitionFailure, RetCode::devicePartitionFailed, "device partition failure") EXCEPTION(KernelArgInfoNotAvailable, RetCode::kernelArgumentInfoNotAvailable, "kernel argument not available") EXCEPTION(InvalidValue, RetCode::invalidValue, "invalid value") EXCEPTION(InvalidDeviceType, RetCode::invalidDeviceType, "invalid device type") EXCEPTION(InvalidPlatform, RetCode::invalidPlatform, "invalid platform") EXCEPTION(InvalidDevice, RetCode::invalidDevice, "invalid device") EXCEPTION(InvalidContext, RetCode::invalidContext, "invalid context") EXCEPTION(InvalidQueueProperties, RetCode::invalidQueueProperties, "invalid command queue properties") EXCEPTION(InvalidCommandQueue, RetCode::invalidCommandQueue, "invalid command queue") EXCEPTION(InvalidHostPtr, RetCode::invalidHostPtr, "invalid host pointer") EXCEPTION(InvalidMemoryObject, RetCode::invalidMemoryObject, "invalid memory object") EXCEPTION(InvalidImageFormatDescriptor, RetCode::invalidImageFormatDescriptor, "invalid image format descriptor") EXCEPTION(InvalidImageSize, RetCode::invalidImageSize, "invalid image size") EXCEPTION(InvalidSampler, RetCode::invalidSampler, "invalid sampler") EXCEPTION(InvalidBinary, RetCode::invalidBinary, "invalid binary") EXCEPTION(InvalidBuildOptions, RetCode::invalidBuildOptions, "invalid build options") EXCEPTION(InvalidProgram, RetCode::invalidProgram, "invalid program") EXCEPTION(InvalidProgramExecutable, RetCode::invalidProgramExecutable, "invalid program executable") EXCEPTION(InvalidKernelName, RetCode::invalidKernelName, "invalid kernel name") EXCEPTION(InvalidKernelDefinition, RetCode::invalidKernelDefinition, "invalid kernel definition") EXCEPTION(InvalidKernel, RetCode::invalidKernel, "invalid kernel") EXCEPTION(InvalidArgIndex, RetCode::invalidArgumentIndex, "invalid argument index") EXCEPTION(InvalidArgValue, RetCode::invalidArgumentValue, "invalid argument value") EXCEPTION(InvalidArgSize, RetCode::invalidArgumentSize, "invalid argument size") EXCEPTION(InvalidKernelArgs, RetCode::invalidKernelArguments, "invalid kernel arguments") EXCEPTION(InvalidWorkDimension, RetCode::invalidWorkDimension, "invalid work dimension") EXCEPTION(InvalidWorkGroupSize, RetCode::invalidWorkGroupSize, "invalid work group size") EXCEPTION(InvalidWorkItemSize, RetCode::invalidWorkItemSize, "invalid work item size") EXCEPTION(InvalidGlobalOffset, RetCode::invalidGlobalOffset, "invalid global offset") EXCEPTION(InvalidEventWaitList, RetCode::invalidEventWaitList, "invalid event wait list") EXCEPTION(InvalidEvent, RetCode::invalidEvent, "invalid event") EXCEPTION(InvalidOperation, RetCode::invalidOperation, "invalid operation") EXCEPTION(InvalidGLObject, RetCode::invalidGlObject, "invalid OpenGL object") EXCEPTION(InvalidBufferSize, RetCode::invalidBufferSize, "invalid buffer size") EXCEPTION(InvalidMipLevel, RetCode::invalidMipLevel, "invalid MIP level") EXCEPTION(InvalidGlobalWorkSize, RetCode::invalidGlobalWorkSize, "invalid global work size") EXCEPTION(InvalidProperty, RetCode::invalidProperty, "invalid property") EXCEPTION(InvalidImageDescriptor, RetCode::invalidImageDescriptor, "invalid image descriptor") EXCEPTION(InvalidCompilerOptions, RetCode::invalidCompilerOptions, "invalid compiler options") EXCEPTION(InvalidLinkerOptions, RetCode::invalidLinkerOptions, "invalid linker options") EXCEPTION(InvalidDevicePartitionCount, RetCode::invalidDevicePartitionCount, "invalid device partition count") #undef EXCEPTION } } #endif <|endoftext|>
<commit_before>// This object is built with some original images. // Its job is to take transform parameters, // then build a volume and an associated mask. #ifndef STACK_HPP_ #define STACK_HPP_ #include "itkImage.h" #include "itkTileImageFilter.h" #include "itkResampleImageFilter.h" #include "itkVectorResampleImageFilter.h" #include "itkTransform.h" #include "itkLinearInterpolateImageFunction.h" #include "itkVectorLinearInterpolateImageFunction.h" #include "itkNearestNeighborInterpolateImageFunction.h" #include "itkChangeInformationImageFilter.h" #include "itkImageMaskSpatialObject.h" #include "itkImageRegionIterator.h" using namespace std; template <typename TPixel, template<typename TInputImage, typename TOutputImage, typename TInterpolatorPrecisionType> class ResampleImageFilterType, template<typename TInputImage, typename TCoordRep> class InterpolatorType > class Stack { public: typedef TPixel PixelType; typedef itk::Image< PixelType, 2 > SliceType; typedef itk::Image< unsigned char, 2 > MaskSliceType; typedef itk::ImageRegionIterator< MaskSliceType > MaskSliceIteratorType; typedef itk::Image< PixelType, 3 > VolumeType; typedef itk::Image< unsigned char, 3 > MaskVolumeType; typedef vector< typename SliceType::Pointer > SliceVectorType; typedef vector< MaskSliceType::Pointer > MaskSliceVectorType; typedef itk::Transform< double, 2, 2 > TransformType; typedef vector< TransformType::Pointer > TransformVectorType; typedef InterpolatorType< SliceType, double > LinearInterpolatorType; typedef itk::NearestNeighborInterpolateImageFunction< MaskSliceType, double > NearestNeighborInterpolatorType; typedef ResampleImageFilterType< SliceType, SliceType, double > ResamplerType; typedef itk::ResampleImageFilter< MaskSliceType, MaskSliceType, double > MaskResamplerType; typedef itk::TileImageFilter< SliceType, VolumeType > TileFilterType; typedef itk::TileImageFilter< MaskSliceType, MaskVolumeType > MaskTileFilterType; typedef itk::ChangeInformationImageFilter< SliceType > XYScaleType; typedef itk::ChangeInformationImageFilter< VolumeType > ZScaleType; typedef itk::ChangeInformationImageFilter< MaskVolumeType > MaskZScaleType; typedef itk::ImageMaskSpatialObject< 3 > MaskType3D; typedef itk::ImageMaskSpatialObject< 2 > MaskType2D; typedef vector< MaskType2D::Pointer > MaskVectorType2D; private: SliceVectorType originalImages; typename XYScaleType::Pointer xyScaler; SliceVectorType slices; typename VolumeType::Pointer volume; typename SliceType::SizeType maxSize; typename SliceType::SizeType resamplerSize; typename SliceType::SpacingType originalSpacings; typename VolumeType::SpacingType spacings; typename MaskType3D::Pointer mask3D; MaskVectorType2D original2DMasks; MaskVectorType2D resampled2DMasks; TransformVectorType transforms; typename LinearInterpolatorType::Pointer linearInterpolator; typename NearestNeighborInterpolatorType::Pointer nearestNeighborInterpolator; typename ResamplerType::Pointer resampler; typename MaskResamplerType::Pointer maskResampler; typename TileFilterType::Pointer tileFilter; typename TileFilterType::LayoutArrayType layout; typename MaskTileFilterType::Pointer maskTileFilter; typename ZScaleType::Pointer zScaler; typename MaskZScaleType::Pointer maskZScaler; vector< unsigned int > numberOfTimesTooBig; public: // constructor to center images and size stack to fit in the longest and widest image Stack(const SliceVectorType& images, const typename VolumeType::SpacingType& inputSpacings); // constructor to specify size and start index explicitly Stack(const SliceVectorType& images, const typename VolumeType::SpacingType& inputSpacings, const typename SliceType::SizeType& inputSize); // constructor to specify stack size and spacing, and spacing of original images Stack(const SliceVectorType& images, const typename SliceType::SpacingType& inputOriginalSpacings, const typename VolumeType::SpacingType& inputSpacings, const typename SliceType::SizeType& inputSize); protected: void initializeVectors(); void scaleOriginalSlices(); void buildOriginalMaskSlices(); void calculateMaxSize(); // Stack is just big enough to fit the longest and widest slices in void setResamplerSizeToMaxSize(); void initializeFilters(); public: void updateVolumes(); protected: void buildSlices(); void buildVolume(); void buildMaskSlices(); void buildMaskSlice(unsigned int slice_number); void buildMaskVolume(); void checkSliceNumber(unsigned int slice_number) const; public: // Getter methods unsigned short GetSize() const { return originalImages.size(); } const typename SliceType::SizeType& GetMaxSize() const { return maxSize; } const typename SliceType::SizeType& GetResamplerSize() const { return resamplerSize; } const typename VolumeType::SpacingType& GetSpacings() const { return spacings; } const typename SliceType::SpacingType& GetOriginalSpacings() const { return originalSpacings; } typename SliceType::Pointer GetOriginalImage(unsigned int slice_number) { checkSliceNumber(slice_number); return originalImages[slice_number]; } typename MaskType2D::Pointer GetOriginal2DMask(unsigned int slice_number) { checkSliceNumber(slice_number); return original2DMasks[slice_number]; } typename SliceType::Pointer GetResampledSlice(unsigned int slice_number) { checkSliceNumber(slice_number); return slices[slice_number]; } typename MaskType2D::Pointer GetResampled2DMask(unsigned int slice_number) { checkSliceNumber(slice_number); return resampled2DMasks[slice_number]; } typename VolumeType::Pointer GetVolume() { return volume; } typename MaskType3D::Pointer Get3DMask() { return mask3D; } TransformType::Pointer GetTransform(unsigned int slice_number) { checkSliceNumber(slice_number); return transforms[slice_number]; } const TransformVectorType& GetTransforms() { return transforms; } void SetTransforms(const TransformVectorType& inputTransforms) { transforms = inputTransforms; } bool ImageExists(unsigned int slice_number) { return GetOriginalImage(slice_number)->GetLargestPossibleRegion().GetSize()[0]; } void ShrinkMaskSlice(unsigned int slice_number); const vector< unsigned int >& GetNumberOfTimesTooBig() { return numberOfTimesTooBig; } void SetNumberOfTimesTooBig(const vector< unsigned int >& numbers); void SetDefaultPixelValue(PixelType p) { resampler->SetDefaultPixelValue(p); } protected: void GenerateMaskSlice(unsigned int slice_number); static bool fileExists(const string& strFilename); typename SliceType::SpacingType spacings2D() const { typename SliceType::SpacingType spacings2D; for(unsigned int i=0; i<2; i++) spacings2D[i] = spacings[i]; return spacings2D; } private: // Copy constructor and copy assignment operator deliberately not implemented // Made private so that nobody can use them Stack(const Stack&); Stack& operator=(const Stack&); }; #include "Stack.txx" #endif <commit_msg>Stacks can store basenames.<commit_after>// This object is built with some original images. // Its job is to take transform parameters, // then build a volume and an associated mask. #ifndef STACK_HPP_ #define STACK_HPP_ #include "itkImage.h" #include "itkTileImageFilter.h" #include "itkResampleImageFilter.h" #include "itkVectorResampleImageFilter.h" #include "itkTransform.h" #include "itkLinearInterpolateImageFunction.h" #include "itkVectorLinearInterpolateImageFunction.h" #include "itkNearestNeighborInterpolateImageFunction.h" #include "itkChangeInformationImageFilter.h" #include "itkImageMaskSpatialObject.h" #include "itkImageRegionIterator.h" using namespace std; template <typename TPixel, template<typename TInputImage, typename TOutputImage, typename TInterpolatorPrecisionType> class ResampleImageFilterType, template<typename TInputImage, typename TCoordRep> class InterpolatorType > class Stack { public: typedef TPixel PixelType; typedef itk::Image< PixelType, 2 > SliceType; typedef itk::Image< unsigned char, 2 > MaskSliceType; typedef itk::ImageRegionIterator< MaskSliceType > MaskSliceIteratorType; typedef itk::Image< PixelType, 3 > VolumeType; typedef itk::Image< unsigned char, 3 > MaskVolumeType; typedef vector< typename SliceType::Pointer > SliceVectorType; typedef vector< MaskSliceType::Pointer > MaskSliceVectorType; typedef itk::Transform< double, 2, 2 > TransformType; typedef vector< TransformType::Pointer > TransformVectorType; typedef InterpolatorType< SliceType, double > LinearInterpolatorType; typedef itk::NearestNeighborInterpolateImageFunction< MaskSliceType, double > NearestNeighborInterpolatorType; typedef ResampleImageFilterType< SliceType, SliceType, double > ResamplerType; typedef itk::ResampleImageFilter< MaskSliceType, MaskSliceType, double > MaskResamplerType; typedef itk::TileImageFilter< SliceType, VolumeType > TileFilterType; typedef itk::TileImageFilter< MaskSliceType, MaskVolumeType > MaskTileFilterType; typedef itk::ChangeInformationImageFilter< SliceType > XYScaleType; typedef itk::ChangeInformationImageFilter< VolumeType > ZScaleType; typedef itk::ChangeInformationImageFilter< MaskVolumeType > MaskZScaleType; typedef itk::ImageMaskSpatialObject< 3 > MaskType3D; typedef itk::ImageMaskSpatialObject< 2 > MaskType2D; typedef vector< MaskType2D::Pointer > MaskVectorType2D; private: SliceVectorType originalImages; typename XYScaleType::Pointer xyScaler; SliceVectorType slices; typename VolumeType::Pointer volume; typename SliceType::SizeType maxSize; typename SliceType::SizeType resamplerSize; typename SliceType::SpacingType originalSpacings; typename VolumeType::SpacingType spacings; typename MaskType3D::Pointer mask3D; MaskVectorType2D original2DMasks; MaskVectorType2D resampled2DMasks; TransformVectorType transforms; typename LinearInterpolatorType::Pointer linearInterpolator; typename NearestNeighborInterpolatorType::Pointer nearestNeighborInterpolator; typename ResamplerType::Pointer resampler; typename MaskResamplerType::Pointer maskResampler; typename TileFilterType::Pointer tileFilter; typename TileFilterType::LayoutArrayType layout; typename MaskTileFilterType::Pointer maskTileFilter; typename ZScaleType::Pointer zScaler; typename MaskZScaleType::Pointer maskZScaler; vector< unsigned int > numberOfTimesTooBig; vector< string > m_basenames; public: // constructor to center images and size stack to fit in the longest and widest image Stack(const SliceVectorType& images, const typename VolumeType::SpacingType& inputSpacings); // constructor to specify size and start index explicitly Stack(const SliceVectorType& images, const typename VolumeType::SpacingType& inputSpacings, const typename SliceType::SizeType& inputSize); // constructor to specify stack size and spacing, and spacing of original images Stack(const SliceVectorType& images, const typename SliceType::SpacingType& inputOriginalSpacings, const typename VolumeType::SpacingType& inputSpacings, const typename SliceType::SizeType& inputSize); protected: void initializeVectors(); void scaleOriginalSlices(); void buildOriginalMaskSlices(); void calculateMaxSize(); // Stack is just big enough to fit the longest and widest slices in void setResamplerSizeToMaxSize(); void initializeFilters(); public: void updateVolumes(); protected: void buildSlices(); void buildVolume(); void buildMaskSlices(); void buildMaskSlice(unsigned int slice_number); void buildMaskVolume(); void checkSliceNumber(unsigned int slice_number) const; public: // Getter methods unsigned short GetSize() const { return originalImages.size(); } const typename SliceType::SizeType& GetMaxSize() const { return maxSize; } const typename SliceType::SizeType& GetResamplerSize() const { return resamplerSize; } const typename VolumeType::SpacingType& GetSpacings() const { return spacings; } const typename SliceType::SpacingType& GetOriginalSpacings() const { return originalSpacings; } typename SliceType::Pointer GetOriginalImage(unsigned int slice_number) { checkSliceNumber(slice_number); return originalImages[slice_number]; } typename MaskType2D::Pointer GetOriginal2DMask(unsigned int slice_number) { checkSliceNumber(slice_number); return original2DMasks[slice_number]; } typename SliceType::Pointer GetResampledSlice(unsigned int slice_number) { checkSliceNumber(slice_number); return slices[slice_number]; } typename MaskType2D::Pointer GetResampled2DMask(unsigned int slice_number) { checkSliceNumber(slice_number); return resampled2DMasks[slice_number]; } typename VolumeType::Pointer GetVolume() { return volume; } typename MaskType3D::Pointer Get3DMask() { return mask3D; } TransformType::Pointer GetTransform(unsigned int slice_number) { checkSliceNumber(slice_number); return transforms[slice_number]; } const TransformVectorType& GetTransforms() { return transforms; } const vector< string > GetBasenames() { // if you're requesting basenames, // make sure you've sensibly set them first assert(m_basenames.size() == originalImages.size()); return m_basenames; } void SetBasenames(const vector< string >& basenames) { // sanity check assert(basenames.size() == originalImages.size()); m_basenames = basenames; } void SetTransforms(const TransformVectorType& inputTransforms) { transforms = inputTransforms; } bool ImageExists(unsigned int slice_number) { return GetOriginalImage(slice_number)->GetLargestPossibleRegion().GetSize()[0]; } void ShrinkMaskSlice(unsigned int slice_number); const vector< unsigned int >& GetNumberOfTimesTooBig() { return numberOfTimesTooBig; } void SetNumberOfTimesTooBig(const vector< unsigned int >& numbers); void SetDefaultPixelValue(PixelType p) { resampler->SetDefaultPixelValue(p); } protected: void GenerateMaskSlice(unsigned int slice_number); static bool fileExists(const string& strFilename); typename SliceType::SpacingType spacings2D() const { typename SliceType::SpacingType spacings2D; for(unsigned int i=0; i<2; i++) spacings2D[i] = spacings[i]; return spacings2D; } private: // Copy constructor and copy assignment operator deliberately not implemented // Made private so that nobody can use them Stack(const Stack&); Stack& operator=(const Stack&); }; #include "Stack.txx" #endif <|endoftext|>
<commit_before>/* Copyright (c) 2013-2015 Jeffrey Pfau * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include "AudioProcessorQt.h" #include "AudioDevice.h" #include <QAudioOutput> extern "C" { #include "gba/supervisor/thread.h" } using namespace QGBA; AudioProcessorQt::AudioProcessorQt(QObject* parent) : AudioProcessor(parent) , m_audioOutput(nullptr) , m_device(nullptr) { } void AudioProcessorQt::setInput(GBAThread* input) { AudioProcessor::setInput(input); if (m_device) { m_device->setInput(input); if (m_audioOutput) { m_device->setFormat(m_audioOutput->format()); } } } void AudioProcessorQt::start() { if (!m_device) { m_device = new AudioDevice(this); } if (!m_audioOutput) { QAudioFormat format; format.setSampleRate(44100); format.setChannelCount(2); format.setSampleSize(16); format.setCodec("audio/pcm"); format.setByteOrder(QAudioFormat::LittleEndian); format.setSampleType(QAudioFormat::SignedInt); m_audioOutput = new QAudioOutput(format, this); } m_device->setInput(input()); m_device->setFormat(m_audioOutput->format()); m_audioOutput->setBufferSize(input()->audioBuffers * 4); m_audioOutput->start(m_device); } void AudioProcessorQt::pause() { if (m_audioOutput) { m_audioOutput->stop(); } } void AudioProcessorQt::setBufferSamples(int samples) { AudioProcessor::setBufferSamples(samples); if (m_audioOutput) { m_audioOutput->stop(); m_audioOutput->setBufferSize(samples * 4); m_audioOutput->start(m_device); } } void AudioProcessorQt::inputParametersChanged() { if (m_device) { m_device->setFormat(m_audioOutput->format()); } } <commit_msg>Qt: Fix PulseAudio output with small buffer size<commit_after>/* Copyright (c) 2013-2015 Jeffrey Pfau * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include "AudioProcessorQt.h" #include "AudioDevice.h" #include <QAudioOutput> extern "C" { #include "gba/supervisor/thread.h" } using namespace QGBA; AudioProcessorQt::AudioProcessorQt(QObject* parent) : AudioProcessor(parent) , m_audioOutput(nullptr) , m_device(nullptr) { } void AudioProcessorQt::setInput(GBAThread* input) { AudioProcessor::setInput(input); if (m_device) { m_device->setInput(input); if (m_audioOutput) { m_device->setFormat(m_audioOutput->format()); } } } void AudioProcessorQt::start() { if (!m_device) { m_device = new AudioDevice(this); } if (!m_audioOutput) { QAudioFormat format; format.setSampleRate(44100); format.setChannelCount(2); format.setSampleSize(16); format.setCodec("audio/pcm"); format.setByteOrder(QAudioFormat::LittleEndian); format.setSampleType(QAudioFormat::SignedInt); m_audioOutput = new QAudioOutput(format, this); m_audioOutput->setCategory("game"); } m_device->setInput(input()); m_device->setFormat(m_audioOutput->format()); m_audioOutput->setBufferSize(input()->audioBuffers * 4); m_audioOutput->start(m_device); } void AudioProcessorQt::pause() { if (m_audioOutput) { m_audioOutput->stop(); } } void AudioProcessorQt::setBufferSamples(int samples) { AudioProcessor::setBufferSamples(samples); if (m_audioOutput) { m_audioOutput->stop(); m_audioOutput->setBufferSize(samples * 4); m_audioOutput->start(m_device); } } void AudioProcessorQt::inputParametersChanged() { if (m_device) { m_device->setFormat(m_audioOutput->format()); } } <|endoftext|>
<commit_before>/*************************************************************************** kalendarVariables.cpp - description ------------------- begin : Sun Jan 6 2002 copyright : (C) 2002 by Tuukka Pasanen email : illuusio@mailcity.com ***************************************************************************/ /*************************************************************************** * * * 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. * * * ***************************************************************************/ #include <qdatetime.h> #include <qstring.h> #include <kdebug.h> #include "konsolekalendarvariables.h" #include <stdlib.h> #include <iostream> #include <stdio.h> KonsoleKalendarVariables::KonsoleKalendarVariables() { m_bIsDate = false; m_bIsStartDate = false; m_bIsEndDate = false; m_bNext = false; m_bVerbose = false; } KonsoleKalendarVariables::~KonsoleKalendarVariables() { } void KonsoleKalendarVariables::setDate(QDateTime date) { m_bIsDate = true; m_date = date; } QDateTime KonsoleKalendarVariables::getDate() { return m_date; } bool KonsoleKalendarVariables::isDate() { return m_bIsDate; } void KonsoleKalendarVariables::setStartDate(QDateTime start) { m_bIsStartDate = true; m_startDate = start; } QDateTime KonsoleKalendarVariables::getStartDate() { return m_startDate; } bool KonsoleKalendarVariables::isStartDate() { return m_bIsStartDate; } void KonsoleKalendarVariables::setEndDate(QDateTime end) { m_bIsEndDate = true; m_endDate = end; } QDateTime KonsoleKalendarVariables::getEndDate() { return m_endDate; } bool KonsoleKalendarVariables::isEndDate() { return m_bIsEndDate; } void KonsoleKalendarVariables::setNext(bool next) { m_bNext = next; } bool KonsoleKalendarVariables::isNext() { return m_bNext; } void KonsoleKalendarVariables::setVerbose(bool verbose) { m_bVerbose = verbose; } bool KonsoleKalendarVariables::isVerbose() { return m_bVerbose; } void KonsoleKalendarVariables::setCalendarFile(QString calendar) { m_calendar = calendar; } QString KonsoleKalendarVariables::getCalendarFile() { return m_calendar; } bool KonsoleKalendarVariables::isAll() { return m_bAll; } void KonsoleKalendarVariables::setAll( bool all) { m_bAll = all; } bool KonsoleKalendarVariables::getAll() { return m_bAll; } QTime KonsoleKalendarVariables::parseTime( QString str ) { int strpos = 0; int startpos = 0; int nums[ 4 ]; unsigned int len = 0; printf("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! %d\r\n", str.length()); // Time is much simpler task than date. while( (len < 4) ) { printf("2##!"); // get to start position // nums[ len ++ ] = findNumber( str, strpos, startpos ); printf("Jes: %d",nums[len - 1]); } } QDate KonsoleKalendarVariables::parseDate(QString str) { int strpos=0, // actual position in string errpos=-1; // position of first error in string, or -1 for "no error" bool lookNumber, done; int numbers[3]; // the three numbers making up a date. Order depends on inputmode int numstart; char separator = '\0'; int actnum=0; // the index of the next number int cursorpos = 0; int actsep=0, // index of the next separator tottok=0, // how many items/tokens have been parsed? seppos; // position of last separator parsed int format = -1; /* For not having to call QString::length() frequently without knowing whether * that function starts to count it chars every time, we save that value */ str_length=str.length(); numbers[0]=numbers[1]=numbers[2]=-1; lookNumber=true; done=false; /* We parse the string until * - there is an error ( errpos!=-1 ), or * - we reach the end of the string ( strpos>=str.length() ), or * - we found everything that makes up a date */ while( (errpos==-1) && (strpos < str_length) && (!done)) { if( lookNumber ) { // We are currently looking for a number if(( numbers[actnum]=findNumber(str,strpos,numstart) )==-1) { // but be reached the end of the string done=true; } else { /* if num==-2, this means that there was anything else. * this could mean * that the user deleted the number in-between some separators * and is just about to enter a new number */ if(numbers[actnum]==-2) { numbers[actnum]=-1; } // since we found a number, we increase the counters actnum++; tottok++; /* if we found a total of three numbers, we're done. * if not, there should come a separator */ if(actnum==3) done=true; else lookNumber=false; } } else { // We are currently looking for a separator switch(actsep) { case 0: // It's the first sep, so look what the user preferres separator = findSeparator(str,strpos,seppos); switch(separator) { case '.': // german format 'dd.mm.yyyy' format = 1; break; case '-': format = 2; break; case '/': // normal format 'mm/dd/yyyy' or 'mm-dd-yyyy' format = 3; break; default: // anything else we did not expect errpos=seppos; } break; case 1: // The second sep must be the same as the first (Not 1-1/2000) if(separator!=findSeparator(str,strpos,seppos)) errpos=seppos; break; } // Increase all the counters actsep++; tottok++; lookNumber=true; }; } /* We're through parsing. * * If there was no error, this could mean that * 1) the string ended before we found a complete date * 2) We found a complete date * * In the second case, there could be non-whitespace garbage at the end of the * string, which leads to an error. * * The test does nothing in the first case, since the string is already used up. */ if(errpos==-1) { if(strpos<str_length) { skipWhiteSpace(str,strpos); if(strpos<str_length) { // There is garbage. ERROR!!! errpos=strpos; } } } // If there was an error, we can't do anymore. if(errpos!=-1) { cursorpos=errpos; return QDate::currentDate(); }; /* Now, we have anything the user gave us. * * So we can now check whether * - the user gave us enough * - he entered a real date * - he used a two-digit year which is not nice */ // First, we sort the three numbers into day, month and year switch(format) { case 1: //ddescr.day=numbers[0]; //ddescr.month=numbers[1]; //ddescr.year=numbers[2]; return QDate(numbers[2], numbers[1], numbers[0]); case 2: case 3: //ddescr.day=numbers[1]; //ddescr.month=numbers[0]; //ddescr.year=numbers[2]; return QDate(numbers[2], numbers[1], numbers[0]); default: break; }; return QDate::currentDate(); } // res: Number, -1 reached end, -2 garbage int KonsoleKalendarVariables::findNumber(const QString &str, int &pos, int &startpos) { skipWhiteSpace(str,pos); if(pos >= str_length) return -1; startpos=pos; while( (pos<str_length) && (str[pos]>='0') && (str[pos]<='9') ) pos++; if(startpos==pos) return -2; return str.mid(startpos,pos-startpos).toInt(); } // res: char, 0 reached end char KonsoleKalendarVariables::findSeparator(const QString &str, int &pos, int &seppos) { skipWhiteSpace(str,pos); if(pos>=str_length) { seppos=-1; return 0; }; seppos=pos; pos++; return str[seppos]; } #define ISWHITESPACE(c) ( ((c)==' ') || ((c)=='\t') || ((c)=='\n') || ((c)=='\r') ) void KonsoleKalendarVariables::skipWhiteSpace(const QString &str, int &pos) { while( (pos<str_length) && ISWHITESPACE(str[pos]) ) pos++; } <commit_msg>Basic time parsing is working now.<commit_after>/*************************************************************************** kalendarVariables.cpp - description ------------------- begin : Sun Jan 6 2002 copyright : (C) 2002 by Tuukka Pasanen email : illuusio@mailcity.com ***************************************************************************/ /*************************************************************************** * * * 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. * * * ***************************************************************************/ #include <qdatetime.h> #include <qstring.h> #include <kdebug.h> #include "konsolekalendarvariables.h" #include <stdlib.h> #include <iostream> #include <stdio.h> KonsoleKalendarVariables::KonsoleKalendarVariables() { m_bIsDate = false; m_bIsStartDate = false; m_bIsEndDate = false; m_bNext = false; m_bVerbose = false; } KonsoleKalendarVariables::~KonsoleKalendarVariables() { } void KonsoleKalendarVariables::setDate(QDateTime date) { m_bIsDate = true; m_date = date; } QDateTime KonsoleKalendarVariables::getDate() { return m_date; } bool KonsoleKalendarVariables::isDate() { return m_bIsDate; } void KonsoleKalendarVariables::setStartDate(QDateTime start) { m_bIsStartDate = true; m_startDate = start; } QDateTime KonsoleKalendarVariables::getStartDate() { return m_startDate; } bool KonsoleKalendarVariables::isStartDate() { return m_bIsStartDate; } void KonsoleKalendarVariables::setEndDate(QDateTime end) { m_bIsEndDate = true; m_endDate = end; } QDateTime KonsoleKalendarVariables::getEndDate() { return m_endDate; } bool KonsoleKalendarVariables::isEndDate() { return m_bIsEndDate; } void KonsoleKalendarVariables::setNext(bool next) { m_bNext = next; } bool KonsoleKalendarVariables::isNext() { return m_bNext; } void KonsoleKalendarVariables::setVerbose(bool verbose) { m_bVerbose = verbose; } bool KonsoleKalendarVariables::isVerbose() { return m_bVerbose; } void KonsoleKalendarVariables::setCalendarFile(QString calendar) { m_calendar = calendar; } QString KonsoleKalendarVariables::getCalendarFile() { return m_calendar; } bool KonsoleKalendarVariables::isAll() { return m_bAll; } void KonsoleKalendarVariables::setAll( bool all) { m_bAll = all; } bool KonsoleKalendarVariables::getAll() { return m_bAll; } QTime KonsoleKalendarVariables::parseTime( QString str ) { int strpos = 0; int startpos = 0; unsigned int hours; unsigned int mins; // Time is much simpler task than date. // TODO // CHECK THIS REALLY OUT! // User can add any times he/she like hours = findNumber( str, strpos, startpos ); strpos ++; mins = findNumber( str, strpos, startpos ); if( hours > 23 ) { hours = 0; } if( mins > 59 ) { mins = 0; } // printf("%d:%d\r\n",hours, mins); return QTime( hours, mins, 0, 0); } QDate KonsoleKalendarVariables::parseDate(QString str) { int strpos=0, // actual position in string errpos=-1; // position of first error in string, or -1 for "no error" bool lookNumber, done; int numbers[3]; // the three numbers making up a date. Order depends on inputmode int numstart; char separator = '\0'; int actnum=0; // the index of the next number int cursorpos = 0; int actsep=0, // index of the next separator tottok=0, // how many items/tokens have been parsed? seppos; // position of last separator parsed int format = -1; /* For not having to call QString::length() frequently without knowing whether * that function starts to count it chars every time, we save that value */ str_length=str.length(); numbers[0]=numbers[1]=numbers[2]=-1; lookNumber=true; done=false; /* We parse the string until * - there is an error ( errpos!=-1 ), or * - we reach the end of the string ( strpos>=str.length() ), or * - we found everything that makes up a date */ while( (errpos==-1) && (strpos < str_length) && (!done)) { if( lookNumber ) { // We are currently looking for a number if(( numbers[actnum]=findNumber(str,strpos,numstart) )==-1) { // but be reached the end of the string done=true; } else { /* if num==-2, this means that there was anything else. * this could mean * that the user deleted the number in-between some separators * and is just about to enter a new number */ if(numbers[actnum]==-2) { numbers[actnum]=-1; } // since we found a number, we increase the counters actnum++; tottok++; /* if we found a total of three numbers, we're done. * if not, there should come a separator */ if(actnum==3) done=true; else lookNumber=false; } } else { // We are currently looking for a separator switch(actsep) { case 0: // It's the first sep, so look what the user preferres separator = findSeparator(str,strpos,seppos); switch(separator) { case '.': // german format 'dd.mm.yyyy' format = 1; break; case '-': format = 2; break; case '/': // normal format 'mm/dd/yyyy' or 'mm-dd-yyyy' format = 3; break; default: // anything else we did not expect errpos=seppos; } break; case 1: // The second sep must be the same as the first (Not 1-1/2000) if(separator!=findSeparator(str,strpos,seppos)) errpos=seppos; break; } // Increase all the counters actsep++; tottok++; lookNumber=true; }; } /* We're through parsing. * * If there was no error, this could mean that * 1) the string ended before we found a complete date * 2) We found a complete date * * In the second case, there could be non-whitespace garbage at the end of the * string, which leads to an error. * * The test does nothing in the first case, since the string is already used up. */ if(errpos==-1) { if(strpos<str_length) { skipWhiteSpace(str,strpos); if(strpos<str_length) { // There is garbage. ERROR!!! errpos=strpos; } } } // If there was an error, we can't do anymore. if(errpos!=-1) { cursorpos=errpos; return QDate::currentDate(); }; /* Now, we have anything the user gave us. * * So we can now check whether * - the user gave us enough * - he entered a real date * - he used a two-digit year which is not nice */ // First, we sort the three numbers into day, month and year switch(format) { case 1: //ddescr.day=numbers[0]; //ddescr.month=numbers[1]; //ddescr.year=numbers[2]; return QDate(numbers[2], numbers[1], numbers[0]); case 2: case 3: //ddescr.day=numbers[1]; //ddescr.month=numbers[0]; //ddescr.year=numbers[2]; return QDate(numbers[2], numbers[1], numbers[0]); default: break; }; return QDate::currentDate(); } // res: Number, -1 reached end, -2 garbage int KonsoleKalendarVariables::findNumber(const QString &str, int &pos, int &startpos) { skipWhiteSpace(str,pos); if(pos >= str_length) return -1; startpos=pos; while( (pos<str_length) && (str[pos]>='0') && (str[pos]<='9') ) pos++; if(startpos==pos) return -2; return str.mid(startpos,pos-startpos).toInt(); } // res: char, 0 reached end char KonsoleKalendarVariables::findSeparator(const QString &str, int &pos, int &seppos) { skipWhiteSpace(str,pos); if(pos>=str_length) { seppos=-1; return 0; }; seppos=pos; pos++; return str[seppos]; } #define ISWHITESPACE(c) ( ((c)==' ') || ((c)=='\t') || ((c)=='\n') || ((c)=='\r') ) void KonsoleKalendarVariables::skipWhiteSpace(const QString &str, int &pos) { while( (pos<str_length) && ISWHITESPACE(str[pos]) ) pos++; } <|endoftext|>
<commit_before><commit_msg>Duplicated fileDesc is not closed when input file is not forward-lock content. Fix for bug 4606053.<commit_after><|endoftext|>
<commit_before>/* addcontactwizard.cpp - Kopete's Add Contact Wizard Copyright (c) 2002 by Nick Betcher <nbetcher@kde.org> Copyright (c) 2002 by Duncan Mac-Vicar Prett <duncan@kde.org> Kopete (c) 2002 by the Kopete developers <kopete-devel@kde.org> ************************************************************************* * * * 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. * * * ************************************************************************* */ // CONDITIONS FOR PROGRESSING: // Welcome page // true // | // V // Select Address Book Entry // ( Addressee is selected AND is not already associated with a contact ) // OR Do not use address book is checked // | // V // Select Display Name and Group // true // | // V // Select Account // ( Only 1 account ) OR ( An account is selected ) // | // V // (Each AddContactPage) // ( Own conditions) // | // V // Finish // true #include <qcheckbox.h> #include <klocale.h> #include <kiconloader.h> #include <kdeversion.h> #include <kinputdialog.h> #include <kinputdialog.h> #include <kpushbutton.h> #include <kdebug.h> #include <klistview.h> // used for its AddresseeItem class #include <kabc/addresseedialog.h> #include <kabc/addressbook.h> #include <kabc/stdaddressbook.h> #include <addcontactpage.h> #include "addcontactwizard.h" #include "kopetecontactlist.h" #include "kopetemetacontact.h" #include "kopeteaccountmanager.h" #include "kopeteaccount.h" #include "kopetegroup.h" AddContactWizard::AddContactWizard( QWidget *parent, const char *name ) : AddContactWizard_Base( parent, name ) { m_addressBook = 0L; // so we can tell if it's already loaded // Populate the groups list KopeteGroupList groups=KopeteContactList::contactList()->groups(); for( KopeteGroup *it = groups.first(); it; it = groups.next() ) { QString groupname = it->displayName(); if ( !groupname.isEmpty() ) m_groupItems.insert(new QCheckListItem( groupList, groupname, QCheckListItem::CheckBox) , it ) ; } protocolListView->clear(); m_accountItems.clear(); // Populate the accounts list QCheckListItem* accountLVI=0L; QPtrList<KopeteAccount> accounts = KopeteAccountManager::manager()->accounts(); for(KopeteAccount *i=accounts.first() ; i; i=accounts.next() ) { accountLVI= new QCheckListItem( protocolListView, i->accountId(), QCheckListItem::CheckBox); accountLVI->setText(1,i->protocol()->displayName() + QString::fromLatin1(" ") ); //FIXME - I'm not sure the column 1 is a right place for the colored icon -Olivier accountLVI->setPixmap( 1, i->accountIcon() ); m_accountItems.insert(accountLVI,i); } if ( accounts.count() == 1 ) { accountLVI->setOn( true ); setAppropriate( selectService, false ); } setNextEnabled( selectService, ( accounts.count() == 1 ) ); setNextEnabled( selectAddressee, false ); setFinishEnabled( finis, true ); // Addressee validation connections connect( addAddresseeButton, SIGNAL( clicked() ), SLOT( slotAddAddresseeClicked() ) ); connect( chkAddressee, SIGNAL( toggled( bool ) ), SLOT( slotCheckAddresseeChoice( bool ) ) ); connect( addresseeListView, SIGNAL( clicked(QListViewItem * ) ), SLOT( slotAddresseeListClicked( QListViewItem * ) ) ); connect( addresseeListView, SIGNAL( selectionChanged( QListViewItem * ) ), SLOT( slotAddresseeListClicked( QListViewItem * ) ) ); connect( addresseeListView, SIGNAL( spacePressed( QListViewItem * ) ), SLOT( slotAddresseeListClicked( QListViewItem * ) ) ); // Group manipulation connection connect( addGroupButton, SIGNAL(clicked()) , SLOT(slotAddGroupClicked()) ); // Account choice validation connections connect( protocolListView, SIGNAL(clicked(QListViewItem *)), this, SLOT(slotProtocolListClicked(QListViewItem *))); connect( protocolListView, SIGNAL(selectionChanged(QListViewItem *)), this, SLOT(slotProtocolListClicked(QListViewItem *))); connect( protocolListView, SIGNAL(spacePressed(QListViewItem *)), this, SLOT(slotProtocolListClicked(QListViewItem *))); } AddContactWizard::~AddContactWizard() { } void AddContactWizard::slotLoadAddressees() { addresseeListView->clear(); KABC::AddressBook::Iterator it; for( it = m_addressBook->begin(); it != m_addressBook->end(); ++it ) /*KABC::AddresseeItem *item =*/ new KABC::AddresseeItem( addresseeListView, (*it) ); } void AddContactWizard::slotAddAddresseeClicked() { // Pop up add addressee dialog #if KDE_IS_VERSION (3,1,90) QString addresseeName = KInputDialog::getText( i18n( "New Address Book Entry" ), i18n( "Name the new entry:" ), QString::null, 0, this ); #else QString addresseeName = KLineEditDlg::getText( i18n( "New Address Book Entry" ), i18n( "Name the new entry:" ), QString::null, 0, this ); #endif if ( !addresseeName.isEmpty() ) { KABC::Addressee addr; addr.setNameFromString( addresseeName ); m_addressBook->insertAddressee( addr ); KABC::Ticket *ticket = m_addressBook->requestSaveTicket(); if ( !ticket ) { kdError() << "Resource is locked by other application!" << endl; } else { if ( !m_addressBook->save( ticket ) ) { kdError() << "Saving failed!" << endl; #if KDE_IS_VERSION (3,1,90) m_addressBook->releaseSaveTicket( ticket ); #endif } } } } void AddContactWizard::slotCheckAddresseeChoice( bool on ) { setAppropriate( selectAddressee, on ); if ( on ) { // Get a reference to the address book if ( !m_addressBook ) { m_addressBook = KABC::StdAddressBook::self( true ); KABC::StdAddressBook::setAutomaticSave( false ); } disconnect( m_addressBook, SIGNAL( addressBookChanged( AddressBook * ) ), this, SLOT( slotLoadAddressees() ) ); connect( m_addressBook, SIGNAL( addressBookChanged( AddressBook * ) ), this, SLOT( slotLoadAddressees() ) ); } else disconnect( m_addressBook, SIGNAL( addressBookChanged( AddressBook * ) ), this, SLOT( slotLoadAddressees() ) ); } void AddContactWizard::slotAddresseeListClicked( QListViewItem *addressee ) { // enable next if a valid addressee is selected setNextEnabled( selectAddressee, addressee ? addressee->isSelected() : false ); } void AddContactWizard::slotAddGroupClicked() { QString groupName = KInputDialog::getText( i18n( "New Group" ), i18n( "Please enter the name for the new group:" ) ); if ( !groupName.isNull() ) ( new QCheckListItem( groupList, groupName, QCheckListItem::CheckBox ) )->setOn( true ); } void AddContactWizard::slotProtocolListClicked( QListViewItem *) { // Just makes sure a protocol is selected before allowing the user to continue bool oneIsChecked = false; for (QListViewItemIterator it(protocolListView); it.current(); ++it) { QCheckListItem *check = dynamic_cast<QCheckListItem *>(it.current()); if (check && check->isOn()) { oneIsChecked = true; break; } } setNextEnabled(selectService, oneIsChecked); } void AddContactWizard::accept() { KopeteMetaContact *metaContact = new KopeteMetaContact(); // set the display name if required if ( !mDisplayName->text().isEmpty() ) { metaContact->setTrackChildNameChanges( false ); metaContact->setDisplayName( mDisplayName->text() ); } // NOT SURE IF I MEANT TO TAKE THIS OUT - WILL //// set the KABC uid in the metacontact KABC::AddresseeItem *item = 0L; item = static_cast<KABC::AddresseeItem *>( addresseeListView->selectedItem() ); if ( addresseeListView->isEnabled() && item ) metaContact->setMetaContactId( item->addressee().uid() ); // set the metacontact's groups bool topLevel = true; for ( QListViewItemIterator it( groupList ); it.current(); ++it ) { QCheckListItem *check = dynamic_cast<QCheckListItem *>( it.current() ); if ( check && check->isOn() ) { if(m_groupItems.contains(check)) metaContact->addToGroup(m_groupItems[check]); else //it's a new group metaContact->addToGroup( KopeteContactList::contactList()->getGroup( check->text() ) ); topLevel = false; } } if(topLevel) metaContact->addToGroup( KopeteGroup::topLevel() ); bool ok = protocolPages.isEmpty(); // get each protocol's contact QMap <KopeteAccount*,AddContactPage*>::Iterator it; for ( it = protocolPages.begin(); it != protocolPages.end(); ++it ) ok |= it.data()->apply( it.key(), metaContact ); if ( ok ) { // set the KABC uid in the metacontact KABC::AddresseeItem* i = 0L; i = static_cast<KABC::AddresseeItem *>( addresseeListView->selectedItem() ); if ( addresseeListView->isEnabled() && i ) metaContact->setMetaContactId( i->addressee().uid() ); // add it to the contact list KopeteContactList::contactList()->addMetaContact( metaContact ); } else delete metaContact; disconnect( m_addressBook, SIGNAL( addressBookChanged( AddressBook * ) ), this, SLOT( slotLoadAddressees() ) ); deleteLater(); } void AddContactWizard::reject() { disconnect( m_addressBook, SIGNAL( addressBookChanged( AddressBook * ) ), this, SLOT( slotLoadAddressees() ) ); QWizard::reject(); } void AddContactWizard::next() { // If the we're on the select account page // follow it with the add contact pages for // the chosen protocols if (currentPage() == selectService || (currentPage() == intro && !appropriate( selectService ))) { QMap <KopeteAccount*,AddContactPage*>::Iterator it; for ( it = protocolPages.begin(); it != protocolPages.end(); ++it ) { delete it.data(); } protocolPages.clear(); // We don't keep track of this pointer because it gets deleted when the wizard does (which is what we want) for (QListViewItemIterator it(protocolListView); it.current(); ++it) { QCheckListItem *item = dynamic_cast<QCheckListItem *>(it.current()); if (item && item->isOn()) { // this shouldn't happen either, but I hate crashes if (!m_accountItems[item]) continue; AddContactPage *addPage = m_accountItems[item]->protocol()->createAddContactWidget(this, m_accountItems[item] ); if (!addPage) continue; QString title = i18n( "The account name is prepended here", "%1 contact information" ) .arg( item->text(0) ); addPage->show(); insertPage( addPage, title, indexOf( finis ) ); protocolPages.insert( m_accountItems[item] , addPage ); } } QWizard::next(); return; } // If we're not on any account specific pages, // we must be on an add account page, so make sure it validates if (currentPage() != intro && currentPage() != selectAddressee && currentPage() != selectService && currentPage() != selectGroup && currentPage() != finis) { AddContactPage *ePage = dynamic_cast<AddContactPage *>(currentPage()); if (!ePage || !ePage->validateData()) return; } QWizard::next(); } void AddContactWizard::showPage( QWidget *page ) { if ( page == intro ) { if ( chkAddressee->isChecked() ) // We must check this as we might be showing this page because the back button was pressed { // Get a reference to the address book if ( m_addressBook == 0L ) { m_addressBook = KABC::StdAddressBook::self( true ); KABC::StdAddressBook::setAutomaticSave( false ); } disconnect( m_addressBook, SIGNAL( addressBookChanged( AddressBook * ) ), this, SLOT( slotLoadAddressees() ) ); connect( m_addressBook, SIGNAL( addressBookChanged( AddressBook * ) ), this, SLOT( slotLoadAddressees() ) ); slotLoadAddressees(); } } if ( page == selectGroup ) { if ( addresseeListView->isEnabled() ) { if ( KABC::AddresseeItem* i = static_cast<KABC::AddresseeItem *>( addresseeListView->selectedItem() ) ) mDisplayName->setText( i->addressee().realName() ); else mDisplayName->setText( QString::null ); } } QWizard::showPage( page ); } #include "addcontactwizard.moc" // vim: set noet ts=4 sts=4 sw=4: <commit_msg>Two fixes to the AddContactWizard: 1) When going back to the page with display name, don't erase it 2) When going back to start, don't forget KAB contact and subsequently break CCMAIL: 75128@bugs.kde.org<commit_after>/* addcontactwizard.cpp - Kopete's Add Contact Wizard Copyright (c) 2002 by Nick Betcher <nbetcher@kde.org> Copyright (c) 2002 by Duncan Mac-Vicar Prett <duncan@kde.org> Kopete (c) 2002 by the Kopete developers <kopete-devel@kde.org> ************************************************************************* * * * 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. * * * ************************************************************************* */ // CONDITIONS FOR PROGRESSING: // Welcome page // true // | // V // Select Address Book Entry // ( Addressee is selected AND is not already associated with a contact ) // OR Do not use address book is checked // | // V // Select Display Name and Group // true // | // V // Select Account // ( Only 1 account ) OR ( An account is selected ) // | // V // (Each AddContactPage) // ( Own conditions) // | // V // Finish // true #include <qcheckbox.h> #include <klocale.h> #include <kiconloader.h> #include <kdeversion.h> #include <kinputdialog.h> #include <kinputdialog.h> #include <kpushbutton.h> #include <kdebug.h> #include <klistview.h> // used for its AddresseeItem class #include <kabc/addresseedialog.h> #include <kabc/addressbook.h> #include <kabc/stdaddressbook.h> #include <addcontactpage.h> #include "addcontactwizard.h" #include "kopetecontactlist.h" #include "kopetemetacontact.h" #include "kopeteaccountmanager.h" #include "kopeteaccount.h" #include "kopetegroup.h" AddContactWizard::AddContactWizard( QWidget *parent, const char *name ) : AddContactWizard_Base( parent, name ) { m_addressBook = 0L; // so we can tell if it's already loaded // Populate the groups list KopeteGroupList groups=KopeteContactList::contactList()->groups(); for( KopeteGroup *it = groups.first(); it; it = groups.next() ) { QString groupname = it->displayName(); if ( !groupname.isEmpty() ) m_groupItems.insert(new QCheckListItem( groupList, groupname, QCheckListItem::CheckBox) , it ) ; } protocolListView->clear(); m_accountItems.clear(); // Populate the accounts list QCheckListItem* accountLVI=0L; QPtrList<KopeteAccount> accounts = KopeteAccountManager::manager()->accounts(); for(KopeteAccount *i=accounts.first() ; i; i=accounts.next() ) { accountLVI= new QCheckListItem( protocolListView, i->accountId(), QCheckListItem::CheckBox); accountLVI->setText(1,i->protocol()->displayName() + QString::fromLatin1(" ") ); //FIXME - I'm not sure the column 1 is a right place for the colored icon -Olivier accountLVI->setPixmap( 1, i->accountIcon() ); m_accountItems.insert(accountLVI,i); } if ( accounts.count() == 1 ) { accountLVI->setOn( true ); setAppropriate( selectService, false ); } setNextEnabled( selectService, ( accounts.count() == 1 ) ); setNextEnabled( selectAddressee, false ); setFinishEnabled( finis, true ); // Addressee validation connections connect( addAddresseeButton, SIGNAL( clicked() ), SLOT( slotAddAddresseeClicked() ) ); connect( chkAddressee, SIGNAL( toggled( bool ) ), SLOT( slotCheckAddresseeChoice( bool ) ) ); connect( addresseeListView, SIGNAL( clicked(QListViewItem * ) ), SLOT( slotAddresseeListClicked( QListViewItem * ) ) ); connect( addresseeListView, SIGNAL( selectionChanged( QListViewItem * ) ), SLOT( slotAddresseeListClicked( QListViewItem * ) ) ); connect( addresseeListView, SIGNAL( spacePressed( QListViewItem * ) ), SLOT( slotAddresseeListClicked( QListViewItem * ) ) ); // Group manipulation connection connect( addGroupButton, SIGNAL(clicked()) , SLOT(slotAddGroupClicked()) ); // Account choice validation connections connect( protocolListView, SIGNAL(clicked(QListViewItem *)), this, SLOT(slotProtocolListClicked(QListViewItem *))); connect( protocolListView, SIGNAL(selectionChanged(QListViewItem *)), this, SLOT(slotProtocolListClicked(QListViewItem *))); connect( protocolListView, SIGNAL(spacePressed(QListViewItem *)), this, SLOT(slotProtocolListClicked(QListViewItem *))); } AddContactWizard::~AddContactWizard() { } void AddContactWizard::slotLoadAddressees() { addresseeListView->clear(); KABC::AddressBook::Iterator it; for( it = m_addressBook->begin(); it != m_addressBook->end(); ++it ) /*KABC::AddresseeItem *item =*/ new KABC::AddresseeItem( addresseeListView, (*it) ); } void AddContactWizard::slotAddAddresseeClicked() { // Pop up add addressee dialog #if KDE_IS_VERSION (3,1,90) QString addresseeName = KInputDialog::getText( i18n( "New Address Book Entry" ), i18n( "Name the new entry:" ), QString::null, 0, this ); #else QString addresseeName = KLineEditDlg::getText( i18n( "New Address Book Entry" ), i18n( "Name the new entry:" ), QString::null, 0, this ); #endif if ( !addresseeName.isEmpty() ) { KABC::Addressee addr; addr.setNameFromString( addresseeName ); m_addressBook->insertAddressee( addr ); KABC::Ticket *ticket = m_addressBook->requestSaveTicket(); if ( !ticket ) { kdError() << "Resource is locked by other application!" << endl; } else { if ( !m_addressBook->save( ticket ) ) { kdError() << "Saving failed!" << endl; #if KDE_IS_VERSION (3,1,90) m_addressBook->releaseSaveTicket( ticket ); #endif } } } } void AddContactWizard::slotCheckAddresseeChoice( bool on ) { setAppropriate( selectAddressee, on ); if ( on ) { // Get a reference to the address book if ( !m_addressBook ) { m_addressBook = KABC::StdAddressBook::self( true ); KABC::StdAddressBook::setAutomaticSave( false ); } disconnect( m_addressBook, SIGNAL( addressBookChanged( AddressBook * ) ), this, SLOT( slotLoadAddressees() ) ); connect( m_addressBook, SIGNAL( addressBookChanged( AddressBook * ) ), this, SLOT( slotLoadAddressees() ) ); } else disconnect( m_addressBook, SIGNAL( addressBookChanged( AddressBook * ) ), this, SLOT( slotLoadAddressees() ) ); } void AddContactWizard::slotAddresseeListClicked( QListViewItem *addressee ) { // enable next if a valid addressee is selected setNextEnabled( selectAddressee, addressee ? addressee->isSelected() : false ); if ( KABC::AddresseeItem* i = static_cast<KABC::AddresseeItem *>( addressee ) ) mDisplayName->setText( i->addressee().realName() ); } void AddContactWizard::slotAddGroupClicked() { QString groupName = KInputDialog::getText( i18n( "New Group" ), i18n( "Please enter the name for the new group:" ) ); if ( !groupName.isNull() ) ( new QCheckListItem( groupList, groupName, QCheckListItem::CheckBox ) )->setOn( true ); } void AddContactWizard::slotProtocolListClicked( QListViewItem *) { // Just makes sure a protocol is selected before allowing the user to continue bool oneIsChecked = false; for (QListViewItemIterator it(protocolListView); it.current(); ++it) { QCheckListItem *check = dynamic_cast<QCheckListItem *>(it.current()); if (check && check->isOn()) { oneIsChecked = true; break; } } setNextEnabled(selectService, oneIsChecked); } void AddContactWizard::accept() { KopeteMetaContact *metaContact = new KopeteMetaContact(); // set the display name if required if ( !mDisplayName->text().isEmpty() ) { metaContact->setTrackChildNameChanges( false ); metaContact->setDisplayName( mDisplayName->text() ); } // NOT SURE IF I MEANT TO TAKE THIS OUT - WILL //// set the KABC uid in the metacontact KABC::AddresseeItem *item = 0L; item = static_cast<KABC::AddresseeItem *>( addresseeListView->selectedItem() ); if ( addresseeListView->isEnabled() && item ) metaContact->setMetaContactId( item->addressee().uid() ); // set the metacontact's groups bool topLevel = true; for ( QListViewItemIterator it( groupList ); it.current(); ++it ) { QCheckListItem *check = dynamic_cast<QCheckListItem *>( it.current() ); if ( check && check->isOn() ) { if(m_groupItems.contains(check)) metaContact->addToGroup(m_groupItems[check]); else //it's a new group metaContact->addToGroup( KopeteContactList::contactList()->getGroup( check->text() ) ); topLevel = false; } } if(topLevel) metaContact->addToGroup( KopeteGroup::topLevel() ); bool ok = protocolPages.isEmpty(); // get each protocol's contact QMap <KopeteAccount*,AddContactPage*>::Iterator it; for ( it = protocolPages.begin(); it != protocolPages.end(); ++it ) ok |= it.data()->apply( it.key(), metaContact ); if ( ok ) { // set the KABC uid in the metacontact KABC::AddresseeItem* i = 0L; i = static_cast<KABC::AddresseeItem *>( addresseeListView->selectedItem() ); if ( addresseeListView->isEnabled() && i ) metaContact->setMetaContactId( i->addressee().uid() ); // add it to the contact list KopeteContactList::contactList()->addMetaContact( metaContact ); } else delete metaContact; disconnect( m_addressBook, SIGNAL( addressBookChanged( AddressBook * ) ), this, SLOT( slotLoadAddressees() ) ); deleteLater(); } void AddContactWizard::reject() { disconnect( m_addressBook, SIGNAL( addressBookChanged( AddressBook * ) ), this, SLOT( slotLoadAddressees() ) ); QWizard::reject(); } void AddContactWizard::next() { // If the we're on the select account page // follow it with the add contact pages for // the chosen protocols if (currentPage() == selectService || (currentPage() == intro && !appropriate( selectService ))) { QMap <KopeteAccount*,AddContactPage*>::Iterator it; for ( it = protocolPages.begin(); it != protocolPages.end(); ++it ) { delete it.data(); } protocolPages.clear(); // We don't keep track of this pointer because it gets deleted when the wizard does (which is what we want) for (QListViewItemIterator it(protocolListView); it.current(); ++it) { QCheckListItem *item = dynamic_cast<QCheckListItem *>(it.current()); if (item && item->isOn()) { // this shouldn't happen either, but I hate crashes if (!m_accountItems[item]) continue; AddContactPage *addPage = m_accountItems[item]->protocol()->createAddContactWidget(this, m_accountItems[item] ); if (!addPage) continue; QString title = i18n( "The account name is prepended here", "%1 contact information" ) .arg( item->text(0) ); addPage->show(); insertPage( addPage, title, indexOf( finis ) ); protocolPages.insert( m_accountItems[item] , addPage ); } } QWizard::next(); return; } // If we're not on any account specific pages, // we must be on an add account page, so make sure it validates if (currentPage() != intro && currentPage() != selectAddressee && currentPage() != selectService && currentPage() != selectGroup && currentPage() != finis) { AddContactPage *ePage = dynamic_cast<AddContactPage *>(currentPage()); if (!ePage || !ePage->validateData()) return; } QWizard::next(); } void AddContactWizard::showPage( QWidget *page ) { if ( page == intro ) { if ( chkAddressee->isChecked() && addresseeListView->firstChild() == 0 ) // We must check this as we might be showing this page because the back button was pressed { // Get a reference to the address book if ( m_addressBook == 0L ) { m_addressBook = KABC::StdAddressBook::self( true ); KABC::StdAddressBook::setAutomaticSave( false ); } disconnect( m_addressBook, SIGNAL( addressBookChanged( AddressBook * ) ), this, SLOT( slotLoadAddressees() ) ); connect( m_addressBook, SIGNAL( addressBookChanged( AddressBook * ) ), this, SLOT( slotLoadAddressees() ) ); slotLoadAddressees(); } } QWizard::showPage( page ); } #include "addcontactwizard.moc" // vim: set noet ts=4 sts=4 sw=4: <|endoftext|>
<commit_before>#include <lug/Graphics/Vulkan/Render/BufferPool/Light.hpp> #include <lug/Graphics/Scene/Node.hpp> #include <lug/Graphics/Vulkan/API/CommandBuffer.hpp> #include <lug/Graphics/Vulkan/Renderer.hpp> namespace lug { namespace Graphics { namespace Vulkan { namespace Render { namespace BufferPool { Light::Light(Renderer& renderer) : BufferPool(renderer, { renderer.getDevice().getQueueFamily(VK_QUEUE_GRAPHICS_BIT)->getIdx(), renderer.getDevice().getQueueFamily(VK_QUEUE_TRANSFER_BIT)->getIdx() }) {} const SubBuffer* Light::allocate(uint32_t currentFrame, const API::CommandBuffer& cmdBuffer, const std::vector<::lug::Graphics::Scene::Node*> nodes) { // Generate hash size_t hash = nodes.size() * 2; for (auto node : nodes) { hash ^= reinterpret_cast<size_t>(node) + 0x9e3779b9 + (hash << 6) + (hash >> 2); hash ^= node->getLight()->getHandle().value + 0x9e3779b9 + (hash << 6) + (hash >> 2); } const auto& result = BufferPool::allocate(hash, std::any_of(nodes.cbegin(), nodes.cend(), [&currentFrame](const ::lug::Graphics::Scene::Node* node) { return node->getLight()->isDirty(currentFrame) || node->isDirty(currentFrame); })); for (auto node : nodes) { node->getLight()->clearDirty(currentFrame); node->clearDirty(currentFrame); } if (std::get<0>(result) && std::get<1>(result)) { // Update the buffer if the BufferPool told us that we need to for (uint32_t i = 0; i < nodes.size(); ++i) { const auto& light = nodes[i]->getLight(); ::lug::Graphics::Render::Light::Data lightData; light->getData(lightData, *nodes[i]); cmdBuffer.updateBuffer( *std::get<1>(result)->getBuffer(), &lightData, sizeof(lightData), std::get<1>(result)->getOffset() + ::lug::Graphics::Render::Light::strideShader * i ); } const uint32_t lightsNb = static_cast<uint32_t>(nodes.size()); cmdBuffer.updateBuffer( *std::get<1>(result)->getBuffer(), &lightsNb, sizeof(uint32_t), std::get<1>(result)->getOffset() + ::lug::Graphics::Render::Light::strideShader * 50); } return std::get<1>(result); } } // BufferPool } // Render } // Vulkan } // Graphics } // lug <commit_msg>Choose correctly the queue families in BufferPool::Light<commit_after>#include <lug/Graphics/Vulkan/Render/BufferPool/Light.hpp> #include <lug/Graphics/Scene/Node.hpp> #include <lug/Graphics/Vulkan/API/CommandBuffer.hpp> #include <lug/Graphics/Vulkan/Renderer.hpp> namespace lug { namespace Graphics { namespace Vulkan { namespace Render { namespace BufferPool { Light::Light(Renderer& renderer) : BufferPool(renderer, { renderer.getDevice().getQueue("queue_graphics")->getQueueFamily()->getIdx(), renderer.getDevice().getQueue("queue_transfer")->getQueueFamily()->getIdx() }) {} const SubBuffer* Light::allocate(uint32_t currentFrame, const API::CommandBuffer& cmdBuffer, const std::vector<::lug::Graphics::Scene::Node*> nodes) { // Generate hash size_t hash = nodes.size() * 2; for (auto node : nodes) { hash ^= reinterpret_cast<size_t>(node) + 0x9e3779b9 + (hash << 6) + (hash >> 2); hash ^= node->getLight()->getHandle().value + 0x9e3779b9 + (hash << 6) + (hash >> 2); } const auto& result = BufferPool::allocate(hash, std::any_of(nodes.cbegin(), nodes.cend(), [&currentFrame](const ::lug::Graphics::Scene::Node* node) { return node->getLight()->isDirty(currentFrame) || node->isDirty(currentFrame); })); for (auto node : nodes) { node->getLight()->clearDirty(currentFrame); node->clearDirty(currentFrame); } if (std::get<0>(result) && std::get<1>(result)) { // Update the buffer if the BufferPool told us that we need to for (uint32_t i = 0; i < nodes.size(); ++i) { const auto& light = nodes[i]->getLight(); ::lug::Graphics::Render::Light::Data lightData; light->getData(lightData, *nodes[i]); cmdBuffer.updateBuffer( *std::get<1>(result)->getBuffer(), &lightData, sizeof(lightData), std::get<1>(result)->getOffset() + ::lug::Graphics::Render::Light::strideShader * i ); } const uint32_t lightsNb = static_cast<uint32_t>(nodes.size()); cmdBuffer.updateBuffer( *std::get<1>(result)->getBuffer(), &lightsNb, sizeof(uint32_t), std::get<1>(result)->getOffset() + ::lug::Graphics::Render::Light::strideShader * 50); } return std::get<1>(result); } } // BufferPool } // Render } // Vulkan } // Graphics } // lug <|endoftext|>
<commit_before>/* Highly Optimized Object-oriented Many-particle Dynamics -- Blue Edition (HOOMD-blue) Open Source Software License Copyright 2008-2011 Ames Laboratory Iowa State University and The Regents of the University of Michigan All rights reserved. HOOMD-blue may contain modifications ("Contributions") provided, and to which copyright is held, by various Contributors who have granted The Regents of the University of Michigan the right to modify and/or distribute such Contributions. You may redistribute, use, and create derivate works of HOOMD-blue, in source and binary forms, provided you abide by the following conditions: * Redistributions of source code must retain the above copyright notice, this list of conditions, and the following disclaimer both in the code and prominently in any materials provided with the distribution. * 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. * All publications and presentations based on HOOMD-blue, including any reports or published results obtained, in whole or in part, with HOOMD-blue, will acknowledge its use according to the terms posted at the time of submission on: http://codeblue.umich.edu/hoomd-blue/citations.html * Any electronic documents citing HOOMD-Blue will link to the HOOMD-Blue website: http://codeblue.umich.edu/hoomd-blue/ * Apart from the above required attributions, neither the name of the copyright holder nor the names of HOOMD-blue's contributors may be used to endorse or promote products derived from this software without specific prior written permission. Disclaimer THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND/OR ANY WARRANTIES THAT THIS SOFTWARE IS FREE OF INFRINGEMENT ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ // Maintainer: joaander /*! \file MSDAnalyzer.cc \brief Defines the MSDAnalyzer class */ #ifdef WIN32 #pragma warning( push ) #pragma warning( disable : 4244 ) #endif #include "MSDAnalyzer.h" #include "HOOMDInitializer.h" #ifdef ENABLE_MPI #include "Communicator.h" #endif #include <boost/python.hpp> #include <boost/filesystem/operations.hpp> #include <boost/filesystem/convenience.hpp> using namespace boost::python; using namespace boost::filesystem; #include <iomanip> using namespace std; /*! \param sysdef SystemDefinition containing the Particle data to analyze \param fname File name to write output to \param header_prefix String to print before the file header \param overwrite Will overwite an exiting file if true (default is to append) On construction, the initial coordinates of all parrticles in the system are recoreded. The file is opened (and overwritten if told to). Nothing is initially written to the file, that will occur on the first call to analyze() */ MSDAnalyzer::MSDAnalyzer(boost::shared_ptr<SystemDefinition> sysdef, std::string fname, const std::string& header_prefix, bool overwrite) : Analyzer(sysdef), m_delimiter("\t"), m_header_prefix(header_prefix), m_appending(false), m_columns_changed(false) { m_exec_conf->msg->notice(5) << "Constructing MSDAnalyzer: " << fname << " " << header_prefix << " " << overwrite << endl; // SnapshotParticleData snapshot(m_pdata->getNGlobal()); // m_pdata->takeSnapshot(snapshot); // open the file if (exists(fname) && !overwrite) { m_exec_conf->msg->notice(3) << "analyze.msd: Appending msd to existing file \"" << fname << "\"" << endl; m_file.open(fname.c_str(), ios_base::in | ios_base::out | ios_base::ate); m_appending = true; } else { m_exec_conf->msg->notice(3) << "analyze.msd: Creating new msd in file \"" << fname << "\"" << endl; m_file.open(fname.c_str(), ios_base::out); } if (!m_file.good()) { m_exec_conf->msg->error() << "analyze.msd: Unable to open file " << fname << endl; throw runtime_error("Error initializing analyze.msd"); } // record the initial particle positions by tag m_initial_x.resize(m_pdata->getNGlobal()); m_initial_y.resize(m_pdata->getNGlobal()); m_initial_z.resize(m_pdata->getNGlobal()); ArrayHandle<Scalar4> h_pos(m_pdata->getPositions(), access_location::host, access_mode::read); ArrayHandle<unsigned int> h_rtag(m_pdata->getRTags(), access_location::host, access_mode::read); ArrayHandle<int3> h_image(m_pdata->getImages(), access_location::host, access_mode::read); BoxDim box = m_pdata->getGlobalBox(); // for each particle in the data for (unsigned int tag = 0; tag < m_pdata->getNGlobal(); tag++) { // identify the index of the current particle tag unsigned int idx = h_rtag.data[tag]; // save its initial position Scalar3 pos = make_scalar3(h_pos.data[idx].x, h_pos.data[idx].y, h_pos.data[idx].z); Scalar3 unwrapped = box.shift(pos, h_image.data[idx]); // save its initial position // Scalar3 pos = snapshot.pos[tag]; // Scalar3 unwrapped = box.shift(pos, snapshot.image[tag]); m_initial_x[tag] = unwrapped.x; m_initial_y[tag] = unwrapped.y; m_initial_z[tag] = unwrapped.z; } } MSDAnalyzer::~MSDAnalyzer() { m_exec_conf->msg->notice(5) << "Destroying MSDAnalyzer" << endl; } /*!\param timestep Current time step of the simulation analyze() will first write out the file header if the columns have changed. On every call, analyze() will write calculate the MSD for each group and write out a row in the file. */ void MSDAnalyzer::analyze(unsigned int timestep) { if (m_prof) m_prof->push("Analyze MSD"); // take particle data snapshot SnapshotParticleData snapshot(m_pdata->getNGlobal()); m_pdata->takeSnapshot(snapshot); #ifdef ENABLE_MPI // if we are not the root processor, do not perform file I/O if (m_comm && !m_exec_conf->isRoot()) { if (m_prof) m_prof->pop(); return; } #endif // error check if (m_columns.size() == 0) { m_exec_conf->msg->warning() << "analyze.msd: No columns specified in the MSD analysis" << endl; return; } // ignore writing the header on the first call when appending the file if (m_columns_changed && m_appending) { m_appending = false; m_columns_changed = false; } // write out the header only once if the columns change if (m_columns_changed) { writeHeader(); m_columns_changed = false; } // write out the row every time writeRow(timestep); if (m_prof) m_prof->pop(); } /*! \param delimiter New delimiter to set The delimiter is printed between every element in the row of the output */ void MSDAnalyzer::setDelimiter(const std::string& delimiter) { m_delimiter = delimiter; } /*! \param group Particle group to calculate the MSD of \param name Name to print in the header of the file After a column is added with addColumn(), future calls to analyze() will calculate the MSD of the particles defined in \a group and print out an entry under the \a name header in the file. */ void MSDAnalyzer::addColumn(boost::shared_ptr<ParticleGroup> group, const std::string& name) { m_columns.push_back(column(group, name)); m_columns_changed = true; } /*! \param xml_fname Name of the XML file to read in to the r0 positions \post \a xml_fname is read and all initial r0 positions are assigned from that file. */ void MSDAnalyzer::setR0(const std::string& xml_fname) { // read in the xml file HOOMDInitializer xml(m_exec_conf,xml_fname); // take particle data snapshot SnapshotParticleData snapshot(m_pdata->getNGlobal()); m_pdata->takeSnapshot(snapshot); #ifdef ENABLE_MPI // if we are not the root processor, do not perform file I/O if (m_comm && !m_exec_conf->isRoot()) { return; } #endif // verify that the input matches the current system size unsigned int nparticles = m_pdata->getNGlobal(); if (nparticles != xml.getPos().size()) { m_exec_conf->msg->error() << "analyze.msd: Found " << xml.getPos().size() << " particles in " << xml_fname << ", but there are " << nparticles << " in the current simulation." << endl; throw runtime_error("Error setting r0 in analyze.msd"); } // determine if we have image data bool have_image = (xml.getImage().size() == nparticles); if (!have_image) { m_exec_conf->msg->warning() << "analyze.msd: Image data missing or corrupt in " << xml_fname << ". Computed msd values will not be correct." << endl; } // reset the initial positions BoxDim box = m_pdata->getGlobalBox(); // for each particle in the data for (unsigned int tag = 0; tag < nparticles; tag++) { // save its initial position HOOMDInitializer::vec pos = xml.getPos()[tag]; m_initial_x[tag] = pos.x; m_initial_y[tag] = pos.y; m_initial_z[tag] = pos.z; // adjust the positions by the image flags if we have them if (have_image) { HOOMDInitializer::vec_int image = xml.getImage()[tag]; Scalar3 pos = make_scalar3(m_initial_x[tag], m_initial_y[tag], m_initial_z[tag]); int3 image_i = make_int3(image.x, image.y, image.z); Scalar3 unwrapped = box.shift(pos, image_i); m_initial_x[tag] += unwrapped.x; m_initial_y[tag] += unwrapped.y; m_initial_z[tag] += unwrapped.z; } } } /*! The entire header row is written to the file. First, timestep is written as every file includes it and then the columns are looped through and their names printed, separated by the delimiter. */ void MSDAnalyzer::writeHeader() { // write out the header prefix m_file << m_header_prefix; // timestep is always output m_file << "timestep"; if (m_columns.size() == 0) { m_exec_conf->msg->warning() << "analyze.msd: No columns specified in the MSD analysis" << endl; return; } // only print the delimiter after the timestep if there are more columns m_file << m_delimiter; // write all but the last of the quantities separated by the delimiter for (unsigned int i = 0; i < m_columns.size()-1; i++) m_file << m_columns[i].m_name << m_delimiter; // write the last one with no delimiter after it m_file << m_columns[m_columns.size()-1].m_name << endl; m_file.flush(); } /*! \param group Particle group to calculate the MSD of Loop through all particles in the given group and calculate the MSD over them. \returns The calculated MSD */ Scalar MSDAnalyzer::calcMSD(boost::shared_ptr<ParticleGroup const> group, const SnapshotParticleData& snapshot) { BoxDim box = m_pdata->getGlobalBox(); // initial sum for the average Scalar msd = Scalar(0.0); // handle the case where there are 0 members gracefully if (group->getNumMembers() == 0) { m_exec_conf->msg->warning() << "analyze.msd: Group has 0 members, reporting a calculated msd of 0.0" << endl; return Scalar(0.0); } // for each particle in the group for (unsigned int group_idx = 0; group_idx < group->getNumMembers(); group_idx++) { // get the tag for the current group member from the group unsigned int tag = group->getMemberTag(group_idx); Scalar3 pos = snapshot.pos[tag]; int3 image = snapshot.image[tag]; Scalar3 unwrapped = box.shift(pos, image); Scalar dx = unwrapped.x - m_initial_x[tag]; Scalar dy = unwrapped.y - m_initial_y[tag]; Scalar dz = unwrapped.z - m_initial_z[tag]; msd += dx*dx + dy*dy + dz*dz; } // divide to complete the average msd /= Scalar(group->getNumMembers()); return msd; } /*! \param timestep current time step of the simulation Performs all the steps needed in order to calculate the MSDs for all the groups in the columns and writes out an entire row to the file. */ void MSDAnalyzer::writeRow(unsigned int timestep) { if (m_prof) m_prof->push("MSD"); // take particle data snapshot SnapshotParticleData snapshot(m_pdata->getNGlobal()); m_pdata->takeSnapshot(snapshot); // This will need to be changed based on calling function #ifdef ENABLE_MPI // if we are not the root processor, do not perform file I/O if (m_comm && !m_exec_conf->isRoot()) { if (m_prof) m_prof->pop(); return; } #endif // The timestep is always output m_file << setprecision(10) << timestep; // quit now if there is nothing to log if (m_columns.size() == 0) { return; } // only print the delimiter after the timestep if there are more columns m_file << m_delimiter; // write all but the last of the columns separated by the delimiter for (unsigned int i = 0; i < m_columns.size()-1; i++) m_file << setprecision(10) << calcMSD(m_columns[i].m_group, snapshot) << m_delimiter; // write the last one with no delimiter after it m_file << setprecision(10) << calcMSD(m_columns[m_columns.size()-1].m_group, snapshot) << endl; m_file.flush(); if (!m_file.good()) { m_exec_conf->msg->error() << "analyze.msd: I/O error while writing file" << endl; throw runtime_error("Error writting msd file"); } if (m_prof) m_prof->pop(); } void export_MSDAnalyzer() { class_<MSDAnalyzer, boost::shared_ptr<MSDAnalyzer>, bases<Analyzer>, boost::noncopyable> ("MSDAnalyzer", init< boost::shared_ptr<SystemDefinition>, const std::string&, const std::string&, bool >()) .def("setDelimiter", &MSDAnalyzer::setDelimiter) .def("addColumn", &MSDAnalyzer::addColumn) .def("setR0", &MSDAnalyzer::setR0) ; } #ifdef WIN32 #pragma warning( pop ) #endif <commit_msg>Reverting some changes<commit_after>/* Highly Optimized Object-oriented Many-particle Dynamics -- Blue Edition (HOOMD-blue) Open Source Software License Copyright 2008-2011 Ames Laboratory Iowa State University and The Regents of the University of Michigan All rights reserved. HOOMD-blue may contain modifications ("Contributions") provided, and to which copyright is held, by various Contributors who have granted The Regents of the University of Michigan the right to modify and/or distribute such Contributions. You may redistribute, use, and create derivate works of HOOMD-blue, in source and binary forms, provided you abide by the following conditions: * Redistributions of source code must retain the above copyright notice, this list of conditions, and the following disclaimer both in the code and prominently in any materials provided with the distribution. * 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. * All publications and presentations based on HOOMD-blue, including any reports or published results obtained, in whole or in part, with HOOMD-blue, will acknowledge its use according to the terms posted at the time of submission on: http://codeblue.umich.edu/hoomd-blue/citations.html * Any electronic documents citing HOOMD-Blue will link to the HOOMD-Blue website: http://codeblue.umich.edu/hoomd-blue/ * Apart from the above required attributions, neither the name of the copyright holder nor the names of HOOMD-blue's contributors may be used to endorse or promote products derived from this software without specific prior written permission. Disclaimer THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND/OR ANY WARRANTIES THAT THIS SOFTWARE IS FREE OF INFRINGEMENT ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ // Maintainer: joaander /*! \file MSDAnalyzer.cc \brief Defines the MSDAnalyzer class */ #ifdef WIN32 #pragma warning( push ) #pragma warning( disable : 4244 ) #endif #include "MSDAnalyzer.h" #include "HOOMDInitializer.h" #ifdef ENABLE_MPI #include "Communicator.h" #endif #include <boost/python.hpp> #include <boost/filesystem/operations.hpp> #include <boost/filesystem/convenience.hpp> using namespace boost::python; using namespace boost::filesystem; #include <iomanip> using namespace std; /*! \param sysdef SystemDefinition containing the Particle data to analyze \param fname File name to write output to \param header_prefix String to print before the file header \param overwrite Will overwite an exiting file if true (default is to append) On construction, the initial coordinates of all parrticles in the system are recoreded. The file is opened (and overwritten if told to). Nothing is initially written to the file, that will occur on the first call to analyze() */ MSDAnalyzer::MSDAnalyzer(boost::shared_ptr<SystemDefinition> sysdef, std::string fname, const std::string& header_prefix, bool overwrite) : Analyzer(sysdef), m_delimiter("\t"), m_header_prefix(header_prefix), m_appending(false), m_columns_changed(false) { m_exec_conf->msg->notice(5) << "Constructing MSDAnalyzer: " << fname << " " << header_prefix << " " << overwrite << endl; SnapshotParticleData snapshot(m_pdata->getNGlobal()); m_pdata->takeSnapshot(snapshot); // open the file if (exists(fname) && !overwrite) { m_exec_conf->msg->notice(3) << "analyze.msd: Appending msd to existing file \"" << fname << "\"" << endl; m_file.open(fname.c_str(), ios_base::in | ios_base::out | ios_base::ate); m_appending = true; } else { m_exec_conf->msg->notice(3) << "analyze.msd: Creating new msd in file \"" << fname << "\"" << endl; m_file.open(fname.c_str(), ios_base::out); } if (!m_file.good()) { m_exec_conf->msg->error() << "analyze.msd: Unable to open file " << fname << endl; throw runtime_error("Error initializing analyze.msd"); } // record the initial particle positions by tag m_initial_x.resize(m_pdata->getNGlobal()); m_initial_y.resize(m_pdata->getNGlobal()); m_initial_z.resize(m_pdata->getNGlobal()); BoxDim box = m_pdata->getGlobalBox(); // for each particle in the data for (unsigned int tag = 0; tag < snapshot.size; tag++) { // save its initial position Scalar3 pos = snapshot.pos[tag]; Scalar3 unwrapped = box.shift(pos, snapshot.image[tag]); m_initial_x[tag] = unwrapped.x; m_initial_y[tag] = unwrapped.y; m_initial_z[tag] = unwrapped.z; } } MSDAnalyzer::~MSDAnalyzer() { m_exec_conf->msg->notice(5) << "Destroying MSDAnalyzer" << endl; } /*!\param timestep Current time step of the simulation analyze() will first write out the file header if the columns have changed. On every call, analyze() will write calculate the MSD for each group and write out a row in the file. */ void MSDAnalyzer::analyze(unsigned int timestep) { if (m_prof) m_prof->push("Analyze MSD"); // take particle data snapshot SnapshotParticleData snapshot(m_pdata->getNGlobal()); m_pdata->takeSnapshot(snapshot); #ifdef ENABLE_MPI // if we are not the root processor, do not perform file I/O if (m_comm && !m_exec_conf->isRoot()) { if (m_prof) m_prof->pop(); return; } #endif // error check if (m_columns.size() == 0) { m_exec_conf->msg->warning() << "analyze.msd: No columns specified in the MSD analysis" << endl; return; } // ignore writing the header on the first call when appending the file if (m_columns_changed && m_appending) { m_appending = false; m_columns_changed = false; } // write out the header only once if the columns change if (m_columns_changed) { writeHeader(); m_columns_changed = false; } // write out the row every time writeRow(timestep); if (m_prof) m_prof->pop(); } /*! \param delimiter New delimiter to set The delimiter is printed between every element in the row of the output */ void MSDAnalyzer::setDelimiter(const std::string& delimiter) { m_delimiter = delimiter; } /*! \param group Particle group to calculate the MSD of \param name Name to print in the header of the file After a column is added with addColumn(), future calls to analyze() will calculate the MSD of the particles defined in \a group and print out an entry under the \a name header in the file. */ void MSDAnalyzer::addColumn(boost::shared_ptr<ParticleGroup> group, const std::string& name) { m_columns.push_back(column(group, name)); m_columns_changed = true; } /*! \param xml_fname Name of the XML file to read in to the r0 positions \post \a xml_fname is read and all initial r0 positions are assigned from that file. */ void MSDAnalyzer::setR0(const std::string& xml_fname) { // read in the xml file HOOMDInitializer xml(m_exec_conf,xml_fname); // take particle data snapshot SnapshotParticleData snapshot(m_pdata->getNGlobal()); m_pdata->takeSnapshot(snapshot); #ifdef ENABLE_MPI // if we are not the root processor, do not perform file I/O if (m_comm && !m_exec_conf->isRoot()) { return; } #endif // verify that the input matches the current system size unsigned int nparticles = m_pdata->getNGlobal(); if (nparticles != xml.getPos().size()) { m_exec_conf->msg->error() << "analyze.msd: Found " << xml.getPos().size() << " particles in " << xml_fname << ", but there are " << nparticles << " in the current simulation." << endl; throw runtime_error("Error setting r0 in analyze.msd"); } // determine if we have image data bool have_image = (xml.getImage().size() == nparticles); if (!have_image) { m_exec_conf->msg->warning() << "analyze.msd: Image data missing or corrupt in " << xml_fname << ". Computed msd values will not be correct." << endl; } // reset the initial positions BoxDim box = m_pdata->getGlobalBox(); // for each particle in the data for (unsigned int tag = 0; tag < nparticles; tag++) { // save its initial position HOOMDInitializer::vec pos = xml.getPos()[tag]; m_initial_x[tag] = pos.x; m_initial_y[tag] = pos.y; m_initial_z[tag] = pos.z; // adjust the positions by the image flags if we have them if (have_image) { HOOMDInitializer::vec_int image = xml.getImage()[tag]; Scalar3 pos = make_scalar3(m_initial_x[tag], m_initial_y[tag], m_initial_z[tag]); int3 image_i = make_int3(image.x, image.y, image.z); Scalar3 unwrapped = box.shift(pos, image_i); m_initial_x[tag] += unwrapped.x; m_initial_y[tag] += unwrapped.y; m_initial_z[tag] += unwrapped.z; } } } /*! The entire header row is written to the file. First, timestep is written as every file includes it and then the columns are looped through and their names printed, separated by the delimiter. */ void MSDAnalyzer::writeHeader() { // write out the header prefix m_file << m_header_prefix; // timestep is always output m_file << "timestep"; if (m_columns.size() == 0) { m_exec_conf->msg->warning() << "analyze.msd: No columns specified in the MSD analysis" << endl; return; } // only print the delimiter after the timestep if there are more columns m_file << m_delimiter; // write all but the last of the quantities separated by the delimiter for (unsigned int i = 0; i < m_columns.size()-1; i++) m_file << m_columns[i].m_name << m_delimiter; // write the last one with no delimiter after it m_file << m_columns[m_columns.size()-1].m_name << endl; m_file.flush(); } /*! \param group Particle group to calculate the MSD of Loop through all particles in the given group and calculate the MSD over them. \returns The calculated MSD */ Scalar MSDAnalyzer::calcMSD(boost::shared_ptr<ParticleGroup const> group, const SnapshotParticleData& snapshot) { BoxDim box = m_pdata->getGlobalBox(); // initial sum for the average Scalar msd = Scalar(0.0); // handle the case where there are 0 members gracefully if (group->getNumMembers() == 0) { m_exec_conf->msg->warning() << "analyze.msd: Group has 0 members, reporting a calculated msd of 0.0" << endl; return Scalar(0.0); } // for each particle in the group for (unsigned int group_idx = 0; group_idx < group->getNumMembers(); group_idx++) { // get the tag for the current group member from the group unsigned int tag = group->getMemberTag(group_idx); Scalar3 pos = snapshot.pos[tag]; int3 image = snapshot.image[tag]; Scalar3 unwrapped = box.shift(pos, image); Scalar dx = unwrapped.x - m_initial_x[tag]; Scalar dy = unwrapped.y - m_initial_y[tag]; Scalar dz = unwrapped.z - m_initial_z[tag]; msd += dx*dx + dy*dy + dz*dz; } // divide to complete the average msd /= Scalar(group->getNumMembers()); return msd; } /*! \param timestep current time step of the simulation Performs all the steps needed in order to calculate the MSDs for all the groups in the columns and writes out an entire row to the file. */ void MSDAnalyzer::writeRow(unsigned int timestep) { if (m_prof) m_prof->push("MSD"); // take particle data snapshot SnapshotParticleData snapshot(m_pdata->getNGlobal()); m_pdata->takeSnapshot(snapshot); // This will need to be changed based on calling function #ifdef ENABLE_MPI // if we are not the root processor, do not perform file I/O if (m_comm && !m_exec_conf->isRoot()) { if (m_prof) m_prof->pop(); return; } #endif // The timestep is always output m_file << setprecision(10) << timestep; // quit now if there is nothing to log if (m_columns.size() == 0) { return; } // only print the delimiter after the timestep if there are more columns m_file << m_delimiter; // write all but the last of the columns separated by the delimiter for (unsigned int i = 0; i < m_columns.size()-1; i++) m_file << setprecision(10) << calcMSD(m_columns[i].m_group, snapshot) << m_delimiter; // write the last one with no delimiter after it m_file << setprecision(10) << calcMSD(m_columns[m_columns.size()-1].m_group, snapshot) << endl; m_file.flush(); if (!m_file.good()) { m_exec_conf->msg->error() << "analyze.msd: I/O error while writing file" << endl; throw runtime_error("Error writting msd file"); } if (m_prof) m_prof->pop(); } void export_MSDAnalyzer() { class_<MSDAnalyzer, boost::shared_ptr<MSDAnalyzer>, bases<Analyzer>, boost::noncopyable> ("MSDAnalyzer", init< boost::shared_ptr<SystemDefinition>, const std::string&, const std::string&, bool >()) .def("setDelimiter", &MSDAnalyzer::setDelimiter) .def("addColumn", &MSDAnalyzer::addColumn) .def("setR0", &MSDAnalyzer::setR0) ; } #ifdef WIN32 #pragma warning( pop ) #endif <|endoftext|>
<commit_before>// Time: O(nlogn) // Space: O(n) class Solution { public: enum {start, end, height}; /** * @param buildings: A list of lists of integers * @return: Find the outline of those buildings */ vector<vector<int> > buildingOutline(vector<vector<int> > &buildings) { return ComputeSkylineInInterval(buildings, 0, buildings.size()); } // Divide and Conquer. vector<vector<int>> ComputeSkylineInInterval(const vector<vector<int>>& buildings, int left_endpoint, int right_endpoint) { if (right_endpoint - left_endpoint <= 1) { // 0 or 1 skyline, just copy it. return {buildings.cbegin() + left_endpoint, buildings.cbegin() + right_endpoint}; } int mid = left_endpoint + ((right_endpoint - left_endpoint) / 2); auto left_skyline = ComputeSkylineInInterval(buildings, left_endpoint, mid); auto right_skyline = ComputeSkylineInInterval(buildings, mid, right_endpoint); return MergeSkylines(left_skyline, right_skyline); } // Merge Sort vector<vector<int>> MergeSkylines(vector<vector<int>>& left_skyline, vector<vector<int>>& right_skyline) { int i = 0, j = 0; vector<vector<int>> merged; while (i < left_skyline.size() && j < right_skyline.size()) { if (left_skyline[i][end] < right_skyline[j][start]) { merged.emplace_back(left_skyline[i++]); } else if (right_skyline[j][end] < left_skyline[i][start]) { merged.emplace_back(right_skyline[j++]); } else if (left_skyline[i][start] <= right_skyline[j][start]) { MergeIntersectSkylines(merged, left_skyline[i], i, right_skyline[j], j); } else { // left_skyline[i][start] > right_skyline[j][start]. MergeIntersectSkylines(merged, right_skyline[j], j, left_skyline[i], i); } } // Insert the remaining skylines. merged.insert(merged.end(), left_skyline.begin() + i, left_skyline.end()); merged.insert(merged.end(), right_skyline.begin() + j, right_skyline.end()); return merged; } // a[start] <= b[start] void MergeIntersectSkylines(vector<vector<int>>& merged, vector<int>& a, int& a_idx, vector<int>& b, int& b_idx) { if (a[end] <= b[end]) { if (a[height] > b[height]) { // |aaa| if (b[end] != a[end]) { // |abb|b merged.emplace_back(a), ++a_idx; b[start] = a[end]; } else { // aaa ++b_idx; // abb } } else if (a[height] == b[height]) { // abb b[start] = a[start], ++a_idx; // abb } else { // a[height] < b[height]. if (a[start] != b[start]) { // bb merged.emplace_back(vector<int>{a[start], b[start], a[height]}); // |a|bb } ++a_idx; } } else { // a[end] > b[end]. if (a[height] >= b[height]) { // aaaa ++b_idx; // abba } else { // |bb| // |a||bb|a if (a[start] != b[start]) { merged.emplace_back(vector<int>{a[start], b[start], a[height]}); } a[start] = b[end]; merged.emplace_back(b), ++b_idx; } } } }; // Time: O(nlogn) // Space: O(n) class Solution2 { public: /** * @param buildings: A list of lists of integers * @return: Find the outline of those buildings */ vector<vector<int> > buildingOutline(vector<vector<int> > &buildings) { auto outline(move(getSkyline(buildings))); vector<vector<int>> res; int start = -1, height = 0; for (const auto& h : outline) { if (start == -1) { start = h.first, height = h.second; } else if (height != h.second) { if (height > 0) { res.emplace_back(move(vector<int>{start, h.first, height})); } start = h.first, height = h.second; } } return res; } vector<pair<int, int> > getSkyline(const vector<vector<int>>& buildings) { map<int, vector<int>> start_point_to_heights; map<int, vector<int>> end_point_to_heights; set<int> points; for (int i = 0; i < buildings.size(); ++i) { start_point_to_heights[buildings[i][0]].push_back(buildings[i][2]); end_point_to_heights[buildings[i][1]].push_back(buildings[i][2]); points.insert(buildings[i][0]); points.insert(buildings[i][1]); } vector<pair<int, int>> res; map<int, int> height_to_count; int curr_max = 0; // Enumerate each point in increasing order. for (auto it = points.begin(); it != points.end(); ++it) { vector<int> start_point_heights = start_point_to_heights[*it]; vector<int> end_point_heights = end_point_to_heights[*it]; for (int i = 0; i < start_point_heights.size(); ++i) { ++height_to_count[start_point_heights[i]]; } for (int i = 0; i < end_point_heights.size(); ++i) { --height_to_count[end_point_heights[i]]; if (height_to_count[end_point_heights[i]] == 0) { height_to_count.erase(end_point_heights[i]); } } if (height_to_count.empty()) { curr_max = 0; res.emplace_back(move(make_pair(*it, curr_max))); } else if (curr_max != height_to_count.rbegin()->first) { curr_max = height_to_count.rbegin()->first; res.emplace_back(move(make_pair(*it, curr_max))); } } return res; } }; <commit_msg>Update building-outline.cpp<commit_after>// Time: O(nlogn) // Space: O(n) class Solution { public: enum {start, end, height}; /** * @param buildings: A list of lists of integers * @return: Find the outline of those buildings */ vector<vector<int> > buildingOutline(vector<vector<int> > &buildings) { return ComputeSkylineInInterval(buildings, 0, buildings.size()); } // Divide and Conquer. vector<vector<int>> ComputeSkylineInInterval(const vector<vector<int>>& buildings, int left_endpoint, int right_endpoint) { if (right_endpoint - left_endpoint <= 1) { // 0 or 1 skyline, just copy it. return {buildings.cbegin() + left_endpoint, buildings.cbegin() + right_endpoint}; } int mid = left_endpoint + ((right_endpoint - left_endpoint) / 2); auto left_skyline = ComputeSkylineInInterval(buildings, left_endpoint, mid); auto right_skyline = ComputeSkylineInInterval(buildings, mid, right_endpoint); return MergeSkylines(left_skyline, right_skyline); } // Merge Sort vector<vector<int>> MergeSkylines(vector<vector<int>>& left_skyline, vector<vector<int>>& right_skyline) { int i = 0, j = 0; vector<vector<int>> merged; while (i < left_skyline.size() && j < right_skyline.size()) { if (left_skyline[i][end] < right_skyline[j][start]) { merged.emplace_back(left_skyline[i++]); } else if (right_skyline[j][end] < left_skyline[i][start]) { merged.emplace_back(right_skyline[j++]); } else if (left_skyline[i][start] <= right_skyline[j][start]) { MergeIntersectSkylines(merged, left_skyline[i], i, right_skyline[j], j); } else { // left_skyline[i][start] > right_skyline[j][start]. MergeIntersectSkylines(merged, right_skyline[j], j, left_skyline[i], i); } } // Insert the remaining skylines. merged.insert(merged.end(), left_skyline.begin() + i, left_skyline.end()); merged.insert(merged.end(), right_skyline.begin() + j, right_skyline.end()); return merged; } // a[start] <= b[start] void MergeIntersectSkylines(vector<vector<int>>& merged, vector<int>& a, int& a_idx, vector<int>& b, int& b_idx) { if (a[end] <= b[end]) { if (a[height] > b[height]) { // |aaa| if (b[end] != a[end]) { // |abb|b merged.emplace_back(a), ++a_idx; b[start] = a[end]; } else { // aaa ++b_idx; // abb } } else if (a[height] == b[height]) { // abb b[start] = a[start], ++a_idx; // abb } else { // a[height] < b[height]. if (a[start] != b[start]) { // bb merged.emplace_back(vector<int>{a[start], b[start], a[height]}); // |a|bb } ++a_idx; } } else { // a[end] > b[end]. if (a[height] >= b[height]) { // aaaa ++b_idx; // abba } else { // |bb| // |a||bb|a if (a[start] != b[start]) { merged.emplace_back(vector<int>{a[start], b[start], a[height]}); } a[start] = b[end]; merged.emplace_back(b), ++b_idx; } } } }; // Time: O(nlogn) // Space: O(n) class Solution2 { public: /** * @param buildings: A list of lists of integers * @return: Find the outline of those buildings */ vector<vector<int> > buildingOutline(vector<vector<int> > &buildings) { auto outline(move(getSkyline(buildings))); vector<vector<int>> res; int start = -1, height = 0; for (const auto& h : outline) { if (start == -1) { start = h.first, height = h.second; } else if (height != h.second) { if (height > 0) { res.emplace_back(move(vector<int>{start, h.first, height})); } start = h.first, height = h.second; } } return res; } vector<pair<int, int> > getSkyline(const vector<vector<int>>& buildings) { unordered_map<int, vector<int>> start_point_to_heights; unordered_map<int, vector<int>> end_point_to_heights; set<int> points; for (int i = 0; i < buildings.size(); ++i) { start_point_to_heights[buildings[i][0]].push_back(buildings[i][2]); end_point_to_heights[buildings[i][1]].push_back(buildings[i][2]); points.emplace(buildings[i][0]); points.emplace(buildings[i][1]); } vector<pair<int, int>> res; map<int, int> height_to_count; int curr_max = 0; // Enumerate each point in increasing order. for (auto it = points.begin(); it != points.end(); ++it) { vector<int> start_point_heights = start_point_to_heights[*it]; vector<int> end_point_heights = end_point_to_heights[*it]; for (int i = 0; i < start_point_heights.size(); ++i) { ++height_to_count[start_point_heights[i]]; } for (int i = 0; i < end_point_heights.size(); ++i) { --height_to_count[end_point_heights[i]]; if (height_to_count[end_point_heights[i]] == 0) { height_to_count.erase(end_point_heights[i]); } } if (height_to_count.empty()) { curr_max = 0; res.emplace_back(move(make_pair(*it, curr_max))); } else if (curr_max != height_to_count.rbegin()->first) { curr_max = height_to_count.rbegin()->first; res.emplace_back(move(make_pair(*it, curr_max))); } } return res; } }; <|endoftext|>
<commit_before> #include <iostream> using namespace std; void func1() { cout << "func1" << endl; } void func2() { cout << "func2" << endl; } void func3() { cout << "func3" << endl; } void main() { cout << "Hello World" << endl; func1(); func2(); func3(); } <commit_msg>Revert "update func3"<commit_after> #include <iostream> using namespace std; void func1() { cout << "func1" << endl; } void func2() { cout << "func2" << endl; } void main() { cout << "Hello World" << endl; func1(); func2(); } <|endoftext|>
<commit_before>/* ** Copyright (C) 2012 Aldebaran Robotics ** See COPYING for the license */ #include <qitype/genericvalue.hpp> #include <qimessaging/message.hpp> #include <qimessaging/datastream.hpp> #include <qi/log.hpp> #include <qi/types.hpp> #include <vector> #include <cstring> #include "src/buffer_p.hpp" #if 0 #include <qitype/signature.hpp> #define __QI_DEBUG_SERIALIZATION_DATA_R(x, d) { \ std::string sig = qi::signature< x >::value(); \ std::cout << "read (" << sig << "): " << d << std::endl; \ } #define __QI_DEBUG_SERIALIZATION_DATA_W(x, d) { \ std::string sig = qi::signature< x >::value(); \ std::cout << "write(" << sig << "): " << d << std::endl; \ } #else # define __QI_DEBUG_SERIALIZATION_DATA_R(x, d) # define __QI_DEBUG_SERIALIZATION_DATA_W(x, d) #endif namespace qi { template <typename T, typename T2, char S> static inline qi::IDataStream& deserialize(qi::IDataStream* ds, T &b) { T2 res; int ret = ds->read((void *)&res, sizeof(res)); if (ret != sizeof(res)) ds->setStatus(ds->Status_ReadPastEnd); __QI_DEBUG_SERIALIZATION_DATA_R(Type, b); b = res; return *ds; } template <typename T, typename T2, char S> static inline qi::ODataStream& serialize(qi::ODataStream* ds, T &b, bool inner) { T2 val = b; int ret = ds->write((const char*)&val, sizeof(val)); if (!inner) { ds->buffer().signature() += S; } if (ret == -1) ds->setStatus(ds->Status_WriteError); __QI_DEBUG_SERIALIZATION_DATA_W(Type, b); return *ds; } #define QI_SIMPLE_SERIALIZER_IMPL(Type, TypeCast, Signature) \ IDataStream& IDataStream::operator>>(Type &b) \ { \ return deserialize<Type, TypeCast, Signature>(this, b); \ } \ ODataStream& ODataStream::operator<<(Type b) \ { \ bool sig = _innerSerialization; \ ++_innerSerialization; \ serialize<Type, TypeCast, Signature>(this, b, sig); \ --_innerSerialization; \ return *this; \ } QI_SIMPLE_SERIALIZER_IMPL(bool, bool, 'b') QI_SIMPLE_SERIALIZER_IMPL(char, char, 'c') QI_SIMPLE_SERIALIZER_IMPL(signed char, signed char, 'c') QI_SIMPLE_SERIALIZER_IMPL(unsigned char, unsigned char, 'C') QI_SIMPLE_SERIALIZER_IMPL(short, short, 'w') QI_SIMPLE_SERIALIZER_IMPL(unsigned short, unsigned short, 'W') QI_SIMPLE_SERIALIZER_IMPL(int, int, 'i') QI_SIMPLE_SERIALIZER_IMPL(unsigned int, unsigned int, 'I') QI_SIMPLE_SERIALIZER_IMPL(long, qi::int64_t, 'l') QI_SIMPLE_SERIALIZER_IMPL(unsigned long, qi::uint64_t, 'L') QI_SIMPLE_SERIALIZER_IMPL(long long, long long, 'l') QI_SIMPLE_SERIALIZER_IMPL(unsigned long long, unsigned long long, 'L') QI_SIMPLE_SERIALIZER_IMPL(float, float, 'f') QI_SIMPLE_SERIALIZER_IMPL(double, double, 'd') IDataStream::IDataStream(const qi::Buffer& buffer) : _status(Status_Ok) , _reader(BufferReader(buffer)) { } ODataStream::ODataStream(qi::Buffer &buffer) : _status(Status_Ok), _innerSerialization(0) { if (!buffer._p) buffer._p = boost::shared_ptr<BufferPrivate>(new BufferPrivate()); _buffer = buffer; ++_buffer._p->nWriters; } ODataStream::~ODataStream() { --_buffer._p->nWriters; } IDataStream::~IDataStream() { } int ODataStream::write(const char *str, size_t len) { if (len) { if (!_innerSerialization) { buffer().signature() += 's'; } if (_buffer.write(str, len) < 0) { setStatus(Status_WriteError); __QI_DEBUG_SERIALIZATION_DATA_W(std::string, str); return -1; } } return len; } void ODataStream::writeString(const char *str, size_t len) { ++_innerSerialization; *this << (qi::uint32_t)len; --_innerSerialization; if (len) { if (!_innerSerialization) { buffer().signature() += 's'; } if (_buffer.write(str, len) != (int)len) setStatus(Status_WriteError); __QI_DEBUG_SERIALIZATION_DATA_W(std::string, str); } } // string IDataStream& IDataStream::operator>>(std::string &s) { qi::uint32_t sz = 0; *this >> sz; s.clear(); if (sz) { char *data = static_cast<char *>(read(sz)); if (!data) { qiLogError("datastream", "buffer empty"); setStatus(Status_ReadPastEnd); return *this; } s.append(data, sz); __QI_DEBUG_SERIALIZATION_DATA_R(std::string, s); } return *this; } ODataStream& ODataStream::operator<<(const std::string &s) { writeString(s.c_str(), s.length()); return *this; } ODataStream& ODataStream::operator<<(const char *s) { qi::uint32_t len = strlen(s); writeString(s, len); __QI_DEBUG_SERIALIZATION_DATA_W(char *, s); return *this; } ODataStream &ODataStream::operator<<(const qi::Buffer &meta) { if (!_innerSerialization) { buffer().signature() += "s"; } ++_innerSerialization; *this << (uint32_t)meta.size(); buffer().subBuffers().push_back(std::make_pair(buffer().size(), meta)); --_innerSerialization; qiLogDebug("DataStream") << "Serializing buffer " << meta.size() << " at " << buffer().size(); return *this; } IDataStream &IDataStream::operator>>(qi::Buffer &meta) { BufferReader& reader = bufferReader(); uint32_t sz; *this >> sz; if (reader.hasSubBuffer()) { meta = reader.subBuffer(); if (meta.size() != sz) qiLogWarning("DataStream") << "Buffer size mismatch " << sz << " " << meta.size(); } else { qiLogDebug("DataStream") << "Extracting buffer of size " << sz <<" at " << reader.position(); meta.clear(); void* ptr = meta.reserve(sz); memcpy(ptr, read(sz), sz); } return *this; } size_t IDataStream::read(void *data, size_t size) { return _reader.read(data, size); } void* IDataStream::read(size_t size) { return _reader.read(size); } IDataStream &IDataStream::operator>>(GenericValue &value) { std::string signature; *this >> signature; Type* type = 0; // Type::getCompatibleTypeWithSignature(signature); if (!type) qiLogError("qi.datastream") << "Could not find metatype for signature " << signature; else { value.type = type; value.value = 0; // value.type->deserialize(*this); } return *this; } ODataStream &ODataStream::operator<<(const GenericValue &value) { if (!_innerSerialization) buffer().signature() += "m"; ++_innerSerialization; *this << value.signature(); qi::details::serialize(value, *this); --_innerSerialization; return *this; } void ODataStream::beginList(uint32_t size, std::string elementSignature) { if (!_innerSerialization) buffer().signature() += "[" + elementSignature; ++_innerSerialization; *this << size; } void ODataStream::endList() { --_innerSerialization; if (!_innerSerialization) buffer().signature() += "]"; } void ODataStream::beginMap(uint32_t size, std::string keySignature, std::string valueSignature) { if (!_innerSerialization) buffer().signature() += "{" + keySignature + valueSignature + "}"; ++_innerSerialization; *this << size; } void ODataStream::endMap() { --_innerSerialization; if (!_innerSerialization) buffer().signature() += "}"; } void ODataStream::beginTuple(std::string sig) { if (!_innerSerialization) buffer().signature() += "(" + sig + ")"; ++_innerSerialization; } void ODataStream::endTuple() { --_innerSerialization; } } <commit_msg>datastream<commit_after>/* ** Copyright (C) 2012 Aldebaran Robotics ** See COPYING for the license */ #include <qitype/genericvalue.hpp> #include <qimessaging/message.hpp> #include <qimessaging/datastream.hpp> #include <qi/log.hpp> #include <qi/types.hpp> #include <vector> #include <cstring> #include "src/buffer_p.hpp" #if 0 #include <qitype/signature.hpp> #define __QI_DEBUG_SERIALIZATION_DATA_R(x, d) { \ std::string sig = qi::signature< x >::value(); \ std::cout << "read (" << sig << "): " << d << std::endl; \ } #define __QI_DEBUG_SERIALIZATION_DATA_W(x, d) { \ std::string sig = qi::signature< x >::value(); \ std::cout << "write(" << sig << "): " << d << std::endl; \ } #else # define __QI_DEBUG_SERIALIZATION_DATA_R(x, d) # define __QI_DEBUG_SERIALIZATION_DATA_W(x, d) #endif namespace qi { template <typename T, typename T2, char S> static inline qi::IDataStream& deserialize(qi::IDataStream* ds, T &b) { T2 res; int ret = ds->read((void *)&res, sizeof(res)); if (ret != sizeof(res)) ds->setStatus(ds->Status_ReadPastEnd); __QI_DEBUG_SERIALIZATION_DATA_R(Type, b); b = res; return *ds; } template <typename T, typename T2, char S> static inline qi::ODataStream& serialize(qi::ODataStream* ds, T &b, bool inner) { T2 val = b; int ret = ds->write((const char*)&val, sizeof(val)); if (!inner) { ds->buffer().signature() += S; } if (ret == -1) ds->setStatus(ds->Status_WriteError); __QI_DEBUG_SERIALIZATION_DATA_W(Type, b); return *ds; } #define QI_SIMPLE_SERIALIZER_IMPL(Type, TypeCast, Signature) \ IDataStream& IDataStream::operator>>(Type &b) \ { \ return deserialize<Type, TypeCast, Signature>(this, b); \ } \ ODataStream& ODataStream::operator<<(Type b) \ { \ bool sig = _innerSerialization; \ ++_innerSerialization; \ serialize<Type, TypeCast, Signature>(this, b, sig); \ --_innerSerialization; \ return *this; \ } QI_SIMPLE_SERIALIZER_IMPL(bool, bool, 'b') QI_SIMPLE_SERIALIZER_IMPL(char, char, 'c') QI_SIMPLE_SERIALIZER_IMPL(signed char, signed char, 'c') QI_SIMPLE_SERIALIZER_IMPL(unsigned char, unsigned char, 'C') QI_SIMPLE_SERIALIZER_IMPL(short, short, 'w') QI_SIMPLE_SERIALIZER_IMPL(unsigned short, unsigned short, 'W') QI_SIMPLE_SERIALIZER_IMPL(int, int, 'i') QI_SIMPLE_SERIALIZER_IMPL(unsigned int, unsigned int, 'I') QI_SIMPLE_SERIALIZER_IMPL(long, qi::int64_t, 'l') QI_SIMPLE_SERIALIZER_IMPL(unsigned long, qi::uint64_t, 'L') QI_SIMPLE_SERIALIZER_IMPL(long long, long long, 'l') QI_SIMPLE_SERIALIZER_IMPL(unsigned long long, unsigned long long, 'L') QI_SIMPLE_SERIALIZER_IMPL(float, float, 'f') QI_SIMPLE_SERIALIZER_IMPL(double, double, 'd') IDataStream::IDataStream(const qi::Buffer& buffer) : _status(Status_Ok) , _reader(BufferReader(buffer)) { } ODataStream::ODataStream(qi::Buffer &buffer) : _status(Status_Ok), _innerSerialization(0) { if (!buffer._p) buffer._p = boost::shared_ptr<BufferPrivate>(new BufferPrivate()); _buffer = buffer; ++_buffer._p->nWriters; } ODataStream::~ODataStream() { --_buffer._p->nWriters; } IDataStream::~IDataStream() { } int ODataStream::write(const char *str, size_t len) { if (len) { if (!_innerSerialization) { buffer().signature() += 's'; } if (_buffer.write(str, len) < 0) { setStatus(Status_WriteError); __QI_DEBUG_SERIALIZATION_DATA_W(std::string, str); return -1; } } return len; } void ODataStream::writeString(const char *str, size_t len) { ++_innerSerialization; *this << (qi::uint32_t)len; --_innerSerialization; if (len) { if (!_innerSerialization) { buffer().signature() += 's'; } if (_buffer.write(str, len) != (int)len) setStatus(Status_WriteError); __QI_DEBUG_SERIALIZATION_DATA_W(std::string, str); } } // string IDataStream& IDataStream::operator>>(std::string &s) { qi::uint32_t sz = 0; *this >> sz; s.clear(); if (sz) { char *data = static_cast<char *>(read(sz)); if (!data) { qiLogError("datastream", "buffer empty"); setStatus(Status_ReadPastEnd); return *this; } s.append(data, sz); __QI_DEBUG_SERIALIZATION_DATA_R(std::string, s); } return *this; } ODataStream& ODataStream::operator<<(const std::string &s) { writeString(s.c_str(), s.length()); return *this; } ODataStream& ODataStream::operator<<(const char *s) { qi::uint32_t len = strlen(s); writeString(s, len); __QI_DEBUG_SERIALIZATION_DATA_W(char *, s); return *this; } ODataStream &ODataStream::operator<<(const qi::Buffer &meta) { if (!_innerSerialization) { buffer().signature() += "s"; } ++_innerSerialization; *this << (uint32_t)meta.size(); buffer().subBuffers().push_back(std::make_pair(buffer().size(), meta)); --_innerSerialization; qiLogDebug("DataStream") << "Serializing buffer " << meta.size() << " at " << buffer().size(); return *this; } IDataStream &IDataStream::operator>>(qi::Buffer &meta) { BufferReader& reader = bufferReader(); uint32_t sz; *this >> sz; if (reader.hasSubBuffer()) { meta = reader.subBuffer(); if (meta.size() != sz) qiLogWarning("DataStream") << "Buffer size mismatch " << sz << " " << meta.size(); } else { qiLogDebug("DataStream") << "Extracting buffer of size " << sz <<" at " << reader.position(); meta.clear(); void* ptr = meta.reserve(sz); memcpy(ptr, read(sz), sz); } return *this; } size_t IDataStream::read(void *data, size_t size) { return _reader.read(data, size); } void* IDataStream::read(size_t size) { return _reader.read(size); } IDataStream &IDataStream::operator>>(GenericValue &value) { std::string signature; *this >> signature; Type* type = 0; // Type::getCompatibleTypeWithSignature(signature); if (!type) qiLogError("qi.datastream") << "Could not find metatype for signature " << signature; else { value.type = type; value.value = 0; // value.type->deserialize(*this); } return *this; } ODataStream &ODataStream::operator<<(const GenericValue &value) { if (!_innerSerialization) buffer().signature() += "m"; ++_innerSerialization; *this << value.signature(); qi::details::serialize(value, *this); --_innerSerialization; return *this; } void ODataStream::beginList(uint32_t size, std::string elementSignature) { if (!_innerSerialization) buffer().signature() += "[" + elementSignature; ++_innerSerialization; *this << size; } void ODataStream::endList() { --_innerSerialization; if (!_innerSerialization) buffer().signature() += "]"; } void ODataStream::beginMap(uint32_t size, std::string keySignature, std::string valueSignature) { if (!_innerSerialization) buffer().signature() += "{" + keySignature + valueSignature + "}"; ++_innerSerialization; *this << size; } void ODataStream::endMap() { --_innerSerialization; if (!_innerSerialization) buffer().signature() += "}"; } void ODataStream::beginTuple(std::string sig) { if (!_innerSerialization) buffer().signature() += "(" + sig + ")"; ++_innerSerialization; } void ODataStream::endTuple() { --_innerSerialization; } namespace details { void serialize(GenericValue val, ODataStream& out) { SerializeTypeVisitor stv(out); typeDispatch(stv, val.type, &val.value); } GenericValue deserialize(qi::Type *type, IDataStream& in) { void* storage = 0; DeserializeTypeVisitor dtv(in); typeDispatch(dtv, type, &storage); return dtv.result; } } } <|endoftext|>
<commit_before>inline void K_point::initialize() { PROFILE("sirius::K_point::initialize"); zil_.resize(ctx_.lmax_apw() + 1); for (int l = 0; l <= ctx_.lmax_apw(); l++) { zil_[l] = std::pow(double_complex(0, 1), l); } l_by_lm_ = Utils::l_by_lm(ctx_.lmax_apw()); int bs = ctx_.cyclic_block_size(); /* In case of collinear magnetism we store only non-zero spinor components. * * non magnetic case: * +---+ * | | * +---+ * * collinear case: * +---+ * |uu | * +---+---+ * |dd | * +---+ * * non collinear case: * +-------+ * | | * +-------+ * | | * +-------+ */ int nst = (ctx_.num_mag_dims() == 3) ? ctx_.num_bands() : ctx_.num_fv_states(); auto mem_type_evp = (ctx_.std_evp_solver_type() == ev_magma) ? memory_t::host_pinned : memory_t::host; auto mem_type_gevp = (ctx_.gen_evp_solver_type() == ev_magma) ? memory_t::host_pinned : memory_t::host; if (use_second_variation && ctx_.need_sv()) { /* in case of collinear magnetism store pure up and pure dn components, otherwise store the full matrix */ sv_eigen_vectors_[0] = dmatrix<double_complex>(nst, nst, ctx_.blacs_grid(), bs, bs, mem_type_evp); if (ctx_.num_mag_dims() == 1) { sv_eigen_vectors_[1] = dmatrix<double_complex>(nst, nst, ctx_.blacs_grid(), bs, bs, mem_type_evp); } } if (use_second_variation) { fv_eigen_values_.resize(ctx_.num_fv_states()); } /* Build a full list of G+k vectors for all MPI ranks */ generate_gkvec(ctx_.gk_cutoff()); /* build a list of basis functions */ generate_gklo_basis(); if (ctx_.esm_type() == electronic_structure_method_t::full_potential_lapwlo) { if (ctx_.iterative_solver_input().type_ == "exact") { alm_coeffs_row_ = std::unique_ptr<Matching_coefficients>( new Matching_coefficients(unit_cell_, ctx_.lmax_apw(), num_gkvec_row(), igk_row_, gkvec_)); alm_coeffs_col_ = std::unique_ptr<Matching_coefficients>( new Matching_coefficients(unit_cell_, ctx_.lmax_apw(), num_gkvec_col(), igk_col_, gkvec_)); } alm_coeffs_loc_ = std::unique_ptr<Matching_coefficients>( new Matching_coefficients(unit_cell_, ctx_.lmax_apw(), num_gkvec_loc(), igk_loc_, gkvec_)); } if (!ctx_.full_potential()) { /* compute |beta> projectors for atom types */ beta_projectors_ = std::unique_ptr<Beta_projectors>(new Beta_projectors(ctx_, comm_, gkvec_)); if (false) { p_mtrx_ = mdarray<double_complex, 3>(unit_cell_.max_mt_basis_size(), unit_cell_.max_mt_basis_size(), unit_cell_.num_atom_types()); p_mtrx_.zero(); for (int iat = 0; iat < unit_cell_.num_atom_types(); iat++) { auto& atom_type = unit_cell_.atom_type(iat); if (!atom_type.pp_desc().augment) { continue; } int nbf = atom_type.mt_basis_size(); int ofs = atom_type.offset_lo(); matrix<double_complex> qinv(nbf, nbf); for (int xi1 = 0; xi1 < nbf; xi1++) { for (int xi2 = 0; xi2 < nbf; xi2++) { qinv(xi2, xi1) = ctx_.augmentation_op(iat).q_mtrx(xi2, xi1); } } linalg<CPU>::geinv(nbf, qinv); /* compute P^{+}*P */ linalg<CPU>::gemm(2, 0, nbf, nbf, num_gkvec_loc(), beta_projectors_->beta_gk_t().at<CPU>(0, ofs), beta_projectors_->beta_gk_t().ld(), beta_projectors_->beta_gk_t().at<CPU>(0, ofs), beta_projectors_->beta_gk_t().ld(), &p_mtrx_(0, 0, iat), p_mtrx_.ld()); comm().allreduce(&p_mtrx_(0, 0, iat), unit_cell_.max_mt_basis_size() * unit_cell_.max_mt_basis_size()); for (int xi1 = 0; xi1 < nbf; xi1++) { for (int xi2 = 0; xi2 < nbf; xi2++) { qinv(xi2, xi1) += p_mtrx_(xi2, xi1, iat); } } /* compute (Q^{-1} + P^{+}*P)^{-1} */ linalg<CPU>::geinv(nbf, qinv); for (int xi1 = 0; xi1 < nbf; xi1++) { for (int xi2 = 0; xi2 < nbf; xi2++) { p_mtrx_(xi2, xi1, iat) = qinv(xi2, xi1); } } } } } if (ctx_.full_potential()) { if (use_second_variation) { /* allocate fv eien vectors */ fv_eigen_vectors_slab_ = std::unique_ptr<wave_functions>( new wave_functions(ctx_.processing_unit(), gkvec(), unit_cell_.num_atoms(), [this](int ia){return unit_cell_.atom(ia).mt_lo_basis_size();}, ctx_.num_fv_states())); fv_eigen_vectors_slab_->pw_coeffs().prime().zero(); fv_eigen_vectors_slab_->mt_coeffs().prime().zero(); /* starting guess for wave-functions */ for (int i = 0; i < ctx_.num_fv_states(); i++) { for (int igloc = 0; igloc < gkvec().gvec_count(comm().rank()); igloc++) { int ig = igloc + gkvec().gvec_offset(comm().rank()); if (ig == i) { fv_eigen_vectors_slab_->pw_coeffs().prime(igloc, i) = 1.0; } if (ig == i + 1) { fv_eigen_vectors_slab_->pw_coeffs().prime(igloc, i) = 0.5; } if (ig == i + 2) { fv_eigen_vectors_slab_->pw_coeffs().prime(igloc, i) = 0.125; } } } if (ctx_.iterative_solver_input().type_ == "exact") { fv_eigen_vectors_ = dmatrix<double_complex>(gklo_basis_size(), ctx_.num_fv_states(), ctx_.blacs_grid(), bs, bs, mem_type_gevp); } else { int ncomp = ctx_.iterative_solver_input().num_singular_; if (ncomp < 0) { ncomp = ctx_.num_fv_states(); } singular_components_ = std::unique_ptr<wave_functions>(new wave_functions(ctx_.processing_unit(), gkvec(), ncomp)); singular_components_->pw_coeffs().prime().zero(); /* starting guess for wave-functions */ for (int i = 0; i < ncomp; i++) { for (int igloc = 0; igloc < gkvec().gvec_count(comm().rank()); igloc++) { int ig = igloc + gkvec().gvec_offset(comm().rank()); if (ig == i) { singular_components_->pw_coeffs().prime(igloc, i) = 1.0; } if (ig == i + 1) { singular_components_->pw_coeffs().prime(igloc, i) = 0.5; } if (ig == i + 2) { singular_components_->pw_coeffs().prime(igloc, i) = 0.125; } singular_components_->pw_coeffs().prime(igloc, i) += 0.01 * type_wrapper<double_complex>::random(); } } } fv_states_ = std::unique_ptr<wave_functions>(new wave_functions(ctx_.processing_unit(), gkvec(), unit_cell_.num_atoms(), [this](int ia) { return unit_cell_.atom(ia).mt_basis_size(); }, ctx_.num_fv_states())); for (int ispn = 0; ispn < ctx_.num_spins(); ispn++) { spinor_wave_functions_[ispn] = std::unique_ptr<wave_functions>(new wave_functions(ctx_.processing_unit(), gkvec(), unit_cell_.num_atoms(), [this](int ia) { return unit_cell_.atom(ia).mt_basis_size(); }, nst)); } } else { TERMINATE_NOT_IMPLEMENTED } } else { assert(ctx_.num_fv_states() < num_gkvec()); for (int ispn = 0; ispn < ctx_.num_spins(); ispn++) { spinor_wave_functions_[ispn] = std::unique_ptr<wave_functions>(new wave_functions(ctx_.processing_unit(), gkvec(), nst)); } } } <commit_msg>comment unused code<commit_after>inline void K_point::initialize() { PROFILE("sirius::K_point::initialize"); zil_.resize(ctx_.lmax_apw() + 1); for (int l = 0; l <= ctx_.lmax_apw(); l++) { zil_[l] = std::pow(double_complex(0, 1), l); } l_by_lm_ = Utils::l_by_lm(ctx_.lmax_apw()); int bs = ctx_.cyclic_block_size(); /* In case of collinear magnetism we store only non-zero spinor components. * * non magnetic case: * +---+ * | | * +---+ * * collinear case: * +---+ * |uu | * +---+---+ * |dd | * +---+ * * non collinear case: * +-------+ * | | * +-------+ * | | * +-------+ */ int nst = (ctx_.num_mag_dims() == 3) ? ctx_.num_bands() : ctx_.num_fv_states(); auto mem_type_evp = (ctx_.std_evp_solver_type() == ev_magma) ? memory_t::host_pinned : memory_t::host; auto mem_type_gevp = (ctx_.gen_evp_solver_type() == ev_magma) ? memory_t::host_pinned : memory_t::host; if (use_second_variation && ctx_.need_sv()) { /* in case of collinear magnetism store pure up and pure dn components, otherwise store the full matrix */ sv_eigen_vectors_[0] = dmatrix<double_complex>(nst, nst, ctx_.blacs_grid(), bs, bs, mem_type_evp); if (ctx_.num_mag_dims() == 1) { sv_eigen_vectors_[1] = dmatrix<double_complex>(nst, nst, ctx_.blacs_grid(), bs, bs, mem_type_evp); } } if (use_second_variation) { fv_eigen_values_.resize(ctx_.num_fv_states()); } /* Build a full list of G+k vectors for all MPI ranks */ generate_gkvec(ctx_.gk_cutoff()); /* build a list of basis functions */ generate_gklo_basis(); if (ctx_.esm_type() == electronic_structure_method_t::full_potential_lapwlo) { if (ctx_.iterative_solver_input().type_ == "exact") { alm_coeffs_row_ = std::unique_ptr<Matching_coefficients>( new Matching_coefficients(unit_cell_, ctx_.lmax_apw(), num_gkvec_row(), igk_row_, gkvec_)); alm_coeffs_col_ = std::unique_ptr<Matching_coefficients>( new Matching_coefficients(unit_cell_, ctx_.lmax_apw(), num_gkvec_col(), igk_col_, gkvec_)); } alm_coeffs_loc_ = std::unique_ptr<Matching_coefficients>( new Matching_coefficients(unit_cell_, ctx_.lmax_apw(), num_gkvec_loc(), igk_loc_, gkvec_)); } if (!ctx_.full_potential()) { /* compute |beta> projectors for atom types */ beta_projectors_ = std::unique_ptr<Beta_projectors>(new Beta_projectors(ctx_, gkvec_)); //if (false) { // p_mtrx_ = mdarray<double_complex, 3>(unit_cell_.max_mt_basis_size(), unit_cell_.max_mt_basis_size(), unit_cell_.num_atom_types()); // p_mtrx_.zero(); // for (int iat = 0; iat < unit_cell_.num_atom_types(); iat++) { // auto& atom_type = unit_cell_.atom_type(iat); // if (!atom_type.pp_desc().augment) { // continue; // } // int nbf = atom_type.mt_basis_size(); // int ofs = atom_type.offset_lo(); // matrix<double_complex> qinv(nbf, nbf); // for (int xi1 = 0; xi1 < nbf; xi1++) { // for (int xi2 = 0; xi2 < nbf; xi2++) { // qinv(xi2, xi1) = ctx_.augmentation_op(iat).q_mtrx(xi2, xi1); // } // } // linalg<CPU>::geinv(nbf, qinv); // // /* compute P^{+}*P */ // linalg<CPU>::gemm(2, 0, nbf, nbf, num_gkvec_loc(), // beta_projectors_->beta_gk_t().at<CPU>(0, ofs), beta_projectors_->beta_gk_t().ld(), // beta_projectors_->beta_gk_t().at<CPU>(0, ofs), beta_projectors_->beta_gk_t().ld(), // &p_mtrx_(0, 0, iat), p_mtrx_.ld()); // comm().allreduce(&p_mtrx_(0, 0, iat), unit_cell_.max_mt_basis_size() * unit_cell_.max_mt_basis_size()); // for (int xi1 = 0; xi1 < nbf; xi1++) { // for (int xi2 = 0; xi2 < nbf; xi2++) { // qinv(xi2, xi1) += p_mtrx_(xi2, xi1, iat); // } // } // /* compute (Q^{-1} + P^{+}*P)^{-1} */ // linalg<CPU>::geinv(nbf, qinv); // for (int xi1 = 0; xi1 < nbf; xi1++) { // for (int xi2 = 0; xi2 < nbf; xi2++) { // p_mtrx_(xi2, xi1, iat) = qinv(xi2, xi1); // } // } // } //} } if (ctx_.full_potential()) { if (use_second_variation) { /* allocate fv eien vectors */ fv_eigen_vectors_slab_ = std::unique_ptr<wave_functions>( new wave_functions(ctx_.processing_unit(), gkvec(), unit_cell_.num_atoms(), [this](int ia){return unit_cell_.atom(ia).mt_lo_basis_size();}, ctx_.num_fv_states())); fv_eigen_vectors_slab_->pw_coeffs().prime().zero(); fv_eigen_vectors_slab_->mt_coeffs().prime().zero(); /* starting guess for wave-functions */ for (int i = 0; i < ctx_.num_fv_states(); i++) { for (int igloc = 0; igloc < gkvec().gvec_count(comm().rank()); igloc++) { int ig = igloc + gkvec().gvec_offset(comm().rank()); if (ig == i) { fv_eigen_vectors_slab_->pw_coeffs().prime(igloc, i) = 1.0; } if (ig == i + 1) { fv_eigen_vectors_slab_->pw_coeffs().prime(igloc, i) = 0.5; } if (ig == i + 2) { fv_eigen_vectors_slab_->pw_coeffs().prime(igloc, i) = 0.125; } } } if (ctx_.iterative_solver_input().type_ == "exact") { fv_eigen_vectors_ = dmatrix<double_complex>(gklo_basis_size(), ctx_.num_fv_states(), ctx_.blacs_grid(), bs, bs, mem_type_gevp); } else { int ncomp = ctx_.iterative_solver_input().num_singular_; if (ncomp < 0) { ncomp = ctx_.num_fv_states(); } singular_components_ = std::unique_ptr<wave_functions>(new wave_functions(ctx_.processing_unit(), gkvec(), ncomp)); singular_components_->pw_coeffs().prime().zero(); /* starting guess for wave-functions */ for (int i = 0; i < ncomp; i++) { for (int igloc = 0; igloc < gkvec().gvec_count(comm().rank()); igloc++) { int ig = igloc + gkvec().gvec_offset(comm().rank()); if (ig == i) { singular_components_->pw_coeffs().prime(igloc, i) = 1.0; } if (ig == i + 1) { singular_components_->pw_coeffs().prime(igloc, i) = 0.5; } if (ig == i + 2) { singular_components_->pw_coeffs().prime(igloc, i) = 0.125; } singular_components_->pw_coeffs().prime(igloc, i) += 0.01 * type_wrapper<double_complex>::random(); } } } fv_states_ = std::unique_ptr<wave_functions>(new wave_functions(ctx_.processing_unit(), gkvec(), unit_cell_.num_atoms(), [this](int ia) { return unit_cell_.atom(ia).mt_basis_size(); }, ctx_.num_fv_states())); for (int ispn = 0; ispn < ctx_.num_spins(); ispn++) { spinor_wave_functions_[ispn] = std::unique_ptr<wave_functions>(new wave_functions(ctx_.processing_unit(), gkvec(), unit_cell_.num_atoms(), [this](int ia) { return unit_cell_.atom(ia).mt_basis_size(); }, nst)); } } else { TERMINATE_NOT_IMPLEMENTED } } else { assert(ctx_.num_fv_states() < num_gkvec()); for (int ispn = 0; ispn < ctx_.num_spins(); ispn++) { spinor_wave_functions_[ispn] = std::unique_ptr<wave_functions>(new wave_functions(ctx_.processing_unit(), gkvec(), nst)); } } } <|endoftext|>
<commit_before>#pragma once /** @file @brief converter between integer and string @author MITSUNARI Shigeo(@herumi) */ #include <memory.h> #include <limits.h> #include <limits> #include <cybozu/exception.hpp> namespace cybozu { namespace atoi_local { template<typename T, size_t n> T convertToInt(bool *b, const char *p, size_t size, const char (&max)[n], T min, T overflow1, char overflow2) { if (size > 0 && *p) { bool isMinus = false; size_t i = 0; if (*p == '-') { isMinus = true; i++; } if (i < size && p[i]) { // skip leading zero while (i < size && p[i] == '0') i++; // check minimum if (isMinus && size - i >= n - 1 && memcmp(max, &p[i], n - 1) == 0) { if (b) *b = true; return min; } T x = 0; for (;;) { unsigned char c; if (i == size || (c = static_cast<unsigned char>(p[i])) == '\0') { if (b) *b = true; return isMinus ? -x : x; } unsigned int y = c - '0'; if (y > 9 || x > overflow1 || (x == overflow1 && c >= overflow2)) { break; } x = x * 10 + T(y); i++; } } } if (b) { *b = false; return 0; } else { throw cybozu::Exception("atoi::convertToInt") << cybozu::exception::makeString(p, size); } } template<typename T> T convertToUint(bool *b, const char *p, size_t size, T overflow1, char overflow2) { if (size > 0 && *p) { size_t i = 0; // skip leading zero while (i < size && p[i] == '0') i++; T x = 0; for (;;) { unsigned char c; if (i == size || (c = static_cast<unsigned char>(p[i])) == '\0') { if (b) *b = true; return x; } unsigned int y = c - '0'; if (y > 9 || x > overflow1 || (x == overflow1 && c >= overflow2)) { break; } x = x * 10 + T(y); i++; } } if (b) { *b = false; return 0; } else { throw cybozu::Exception("atoi::convertToUint") << cybozu::exception::makeString(p, size); } } template<typename T> T convertHexToInt(bool *b, const char *p, size_t size) { if (size > 0 && *p) { size_t i = 0; T x = 0; for (;;) { unsigned int c; if (i == size || (c = static_cast<unsigned char>(p[i])) == '\0') { if (b) *b = true; return x; } if (c - 'A' <= 'F' - 'A') { c = (c - 'A') + 10; } else if (c - 'a' <= 'f' - 'a') { c = (c - 'a') + 10; } else if (c - '0' <= '9' - '0') { c = c - '0'; } else { break; } // avoid overflow if (x > (std::numeric_limits<T>::max)() / 16) break; x = x * 16 + T(c); i++; } } if (b) { *b = false; return 0; } else { throw cybozu::Exception("atoi::convertHexToInt") << cybozu::exception::makeString(p, size); } } } // atoi_local /** auto detect return value class @note if you set bool pointer p then throw nothing and set *p = false if bad string */ class atoi { const char *p_; size_t size_; bool *b_; void set(bool *b, const char *p, size_t size) { b_ = b; p_ = p; size_ = size; } public: atoi(const char *p, size_t size = -1) { set(0, p, size); } atoi(bool *b, const char *p, size_t size = -1) { set(b, p, size); } atoi(const std::string& str) { set(0, str.c_str(), str.size()); } atoi(bool *b, const std::string& str) { set(b, str.c_str(), str.size()); } inline operator signed char() const { return atoi_local::convertToInt<signed char>(b_, p_, size_, "128", -128, 12, '8'); } inline operator unsigned char() const { return atoi_local::convertToUint<unsigned char>(b_, p_, size_, 25, '6'); } inline operator short() const { return atoi_local::convertToInt<short>(b_, p_, size_, "32768", -32768, 3276, '8'); } inline operator unsigned short() const { return atoi_local::convertToUint<unsigned short>(b_, p_, size_, 6553, '6'); } inline operator int() const { return atoi_local::convertToInt<int>(b_, p_, size_, "2147483648", INT_MIN, 214748364, '8'); } inline operator unsigned int() const { return atoi_local::convertToUint<unsigned int>(b_, p_, size_, 429496729, '6'); } inline operator long long() const { return atoi_local::convertToInt<long long>(b_, p_, size_, "9223372036854775808", LLONG_MIN, 922337203685477580LL, '8'); } inline operator unsigned long long() const { return atoi_local::convertToUint<unsigned long long>(b_, p_, size_, 1844674407370955161ULL, '6'); } #if defined(__SIZEOF_LONG__) && (__SIZEOF_LONG__ == 8) inline operator long() const { return static_cast<long>(static_cast<long long>(*this)); } inline operator unsigned long() const { return static_cast<unsigned long>(static_cast<unsigned long long>(*this)); } #else inline operator long() const { return static_cast<long>(static_cast<int>(*this)); } inline operator unsigned long() const { return static_cast<unsigned long>(static_cast<unsigned int>(*this)); } #endif }; class hextoi { const char *p_; size_t size_; bool *b_; void set(bool *b, const char *p, size_t size) { b_ = b; p_ = p; size_ = size; } public: hextoi(const char *p, size_t size = -1) { set(0, p, size); } hextoi(bool *b, const char *p, size_t size = -1) { set(b, p, size); } hextoi(const std::string& str) { set(0, str.c_str(), str.size()); } hextoi(bool *b, const std::string& str) { set(b, str.c_str(), str.size()); } operator unsigned char() const { return atoi_local::convertHexToInt<unsigned char>(b_, p_, size_); } operator unsigned short() const { return atoi_local::convertHexToInt<unsigned short>(b_, p_, size_); } operator unsigned int() const { return atoi_local::convertHexToInt<unsigned int>(b_, p_, size_); } operator unsigned long() const { return atoi_local::convertHexToInt<unsigned long>(b_, p_, size_); } operator unsigned long long() const { return atoi_local::convertHexToInt<unsigned long long>(b_, p_, size_); } operator char() const { return atoi_local::convertHexToInt<char>(b_, p_, size_); } operator signed char() const { return atoi_local::convertHexToInt<signed char>(b_, p_, size_); } operator short() const { return atoi_local::convertHexToInt<short>(b_, p_, size_); } operator int() const { return atoi_local::convertHexToInt<int>(b_, p_, size_); } operator long() const { return atoi_local::convertHexToInt<long>(b_, p_, size_); } operator long long() const { return atoi_local::convertHexToInt<long long>(b_, p_, size_); } }; } // cybozu <commit_msg>LLONG_MIN is not defined on some env<commit_after>#pragma once /** @file @brief converter between integer and string @author MITSUNARI Shigeo(@herumi) */ #include <memory.h> #include <limits> #include <cybozu/exception.hpp> namespace cybozu { namespace atoi_local { template<typename T, size_t n> T convertToInt(bool *b, const char *p, size_t size, const char (&max)[n], T min, T overflow1, char overflow2) { if (size > 0 && *p) { bool isMinus = false; size_t i = 0; if (*p == '-') { isMinus = true; i++; } if (i < size && p[i]) { // skip leading zero while (i < size && p[i] == '0') i++; // check minimum if (isMinus && size - i >= n - 1 && memcmp(max, &p[i], n - 1) == 0) { if (b) *b = true; return min; } T x = 0; for (;;) { unsigned char c; if (i == size || (c = static_cast<unsigned char>(p[i])) == '\0') { if (b) *b = true; return isMinus ? -x : x; } unsigned int y = c - '0'; if (y > 9 || x > overflow1 || (x == overflow1 && c >= overflow2)) { break; } x = x * 10 + T(y); i++; } } } if (b) { *b = false; return 0; } else { throw cybozu::Exception("atoi::convertToInt") << cybozu::exception::makeString(p, size); } } template<typename T> T convertToUint(bool *b, const char *p, size_t size, T overflow1, char overflow2) { if (size > 0 && *p) { size_t i = 0; // skip leading zero while (i < size && p[i] == '0') i++; T x = 0; for (;;) { unsigned char c; if (i == size || (c = static_cast<unsigned char>(p[i])) == '\0') { if (b) *b = true; return x; } unsigned int y = c - '0'; if (y > 9 || x > overflow1 || (x == overflow1 && c >= overflow2)) { break; } x = x * 10 + T(y); i++; } } if (b) { *b = false; return 0; } else { throw cybozu::Exception("atoi::convertToUint") << cybozu::exception::makeString(p, size); } } template<typename T> T convertHexToInt(bool *b, const char *p, size_t size) { if (size > 0 && *p) { size_t i = 0; T x = 0; for (;;) { unsigned int c; if (i == size || (c = static_cast<unsigned char>(p[i])) == '\0') { if (b) *b = true; return x; } if (c - 'A' <= 'F' - 'A') { c = (c - 'A') + 10; } else if (c - 'a' <= 'f' - 'a') { c = (c - 'a') + 10; } else if (c - '0' <= '9' - '0') { c = c - '0'; } else { break; } // avoid overflow if (x > (std::numeric_limits<T>::max)() / 16) break; x = x * 16 + T(c); i++; } } if (b) { *b = false; return 0; } else { throw cybozu::Exception("atoi::convertHexToInt") << cybozu::exception::makeString(p, size); } } } // atoi_local /** auto detect return value class @note if you set bool pointer p then throw nothing and set *p = false if bad string */ class atoi { const char *p_; size_t size_; bool *b_; void set(bool *b, const char *p, size_t size) { b_ = b; p_ = p; size_ = size; } public: atoi(const char *p, size_t size = -1) { set(0, p, size); } atoi(bool *b, const char *p, size_t size = -1) { set(b, p, size); } atoi(const std::string& str) { set(0, str.c_str(), str.size()); } atoi(bool *b, const std::string& str) { set(b, str.c_str(), str.size()); } inline operator signed char() const { return atoi_local::convertToInt<signed char>(b_, p_, size_, "128", -128, 12, '8'); } inline operator unsigned char() const { return atoi_local::convertToUint<unsigned char>(b_, p_, size_, 25, '6'); } inline operator short() const { return atoi_local::convertToInt<short>(b_, p_, size_, "32768", -32768, 3276, '8'); } inline operator unsigned short() const { return atoi_local::convertToUint<unsigned short>(b_, p_, size_, 6553, '6'); } inline operator int() const { return atoi_local::convertToInt<int>(b_, p_, size_, "2147483648", /*INT_MIN*/-2147483648, 214748364, '8'); } inline operator unsigned int() const { return atoi_local::convertToUint<unsigned int>(b_, p_, size_, 429496729, '6'); } inline operator long long() const { return atoi_local::convertToInt<long long>(b_, p_, size_, "9223372036854775808", /*LLONG_MIN*/-9223372036854775807ll-1, 922337203685477580LL, '8'); } inline operator unsigned long long() const { return atoi_local::convertToUint<unsigned long long>(b_, p_, size_, 1844674407370955161ULL, '6'); } #if defined(__SIZEOF_LONG__) && (__SIZEOF_LONG__ == 8) inline operator long() const { return static_cast<long>(static_cast<long long>(*this)); } inline operator unsigned long() const { return static_cast<unsigned long>(static_cast<unsigned long long>(*this)); } #else inline operator long() const { return static_cast<long>(static_cast<int>(*this)); } inline operator unsigned long() const { return static_cast<unsigned long>(static_cast<unsigned int>(*this)); } #endif }; class hextoi { const char *p_; size_t size_; bool *b_; void set(bool *b, const char *p, size_t size) { b_ = b; p_ = p; size_ = size; } public: hextoi(const char *p, size_t size = -1) { set(0, p, size); } hextoi(bool *b, const char *p, size_t size = -1) { set(b, p, size); } hextoi(const std::string& str) { set(0, str.c_str(), str.size()); } hextoi(bool *b, const std::string& str) { set(b, str.c_str(), str.size()); } operator unsigned char() const { return atoi_local::convertHexToInt<unsigned char>(b_, p_, size_); } operator unsigned short() const { return atoi_local::convertHexToInt<unsigned short>(b_, p_, size_); } operator unsigned int() const { return atoi_local::convertHexToInt<unsigned int>(b_, p_, size_); } operator unsigned long() const { return atoi_local::convertHexToInt<unsigned long>(b_, p_, size_); } operator unsigned long long() const { return atoi_local::convertHexToInt<unsigned long long>(b_, p_, size_); } operator char() const { return atoi_local::convertHexToInt<char>(b_, p_, size_); } operator signed char() const { return atoi_local::convertHexToInt<signed char>(b_, p_, size_); } operator short() const { return atoi_local::convertHexToInt<short>(b_, p_, size_); } operator int() const { return atoi_local::convertHexToInt<int>(b_, p_, size_); } operator long() const { return atoi_local::convertHexToInt<long>(b_, p_, size_); } operator long long() const { return atoi_local::convertHexToInt<long long>(b_, p_, size_); } }; } // cybozu <|endoftext|>
<commit_before>/* * Copyright 2016 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "gm.h" #include "Resources.h" #include "SkImageDecoder.h" #include "SkPixelXorXfermode.h" #include "SkStream.h" class PixelXorXfermodeGM : public skiagm::GM { public: PixelXorXfermodeGM() { } protected: SkString onShortName() override { return SkString("pixelxorxfermode"); } SkISize onISize() override { return SkISize::Make(512, 512); } void onOnceBeforeDraw() override { SkImageDecoder* codec = nullptr; SkString resourcePath = GetResourcePath("mandrill_512.png"); SkFILEStream stream(resourcePath.c_str()); if (stream.isValid()) { codec = SkImageDecoder::Factory(&stream); } if (codec) { stream.rewind(); codec->decode(&stream, &fBM, kN32_SkColorType, SkImageDecoder::kDecodePixels_Mode); delete codec; } else { fBM.allocN32Pixels(1, 1); fBM.eraseARGB(255, 255, 0 , 0); // red == bad } } void onDraw(SkCanvas* canvas) override { canvas->drawBitmap(fBM, 0, 0); SkRect r = SkRect::MakeIWH(256, 256); // Negate the red channel of the dst (via the ancillary color) but leave // the green & blue channels alone SkPaint p1; p1.setColor(SK_ColorBLACK); // noop p1.setXfermode(SkPixelXorXfermode::Create(SK_ColorRED)); canvas->drawRect(r, p1); r.offsetTo(256.0f, 0.0f); // Negate the dst color via the src color SkPaint p2; p2.setColor(SK_ColorWHITE); p2.setXfermode(SkPixelXorXfermode::Create(SK_ColorBLACK)); // noop canvas->drawRect(r, p2); r.offsetTo(0.0f, 256.0f); // Just return the original color SkPaint p3; p3.setColor(SK_ColorBLACK); // noop p3.setXfermode(SkPixelXorXfermode::Create(SK_ColorBLACK)); // noop canvas->drawRect(r, p3); r.offsetTo(256.0f, 256.0f); // Negate the red & green channels (via the ancillary color) but leave // the blue channel alone SkPaint p4; p4.setColor(SK_ColorBLACK); // noop p4.setXfermode(SkPixelXorXfermode::Create(SK_ColorYELLOW)); canvas->drawRect(r, p4); } private: SkBitmap fBM; typedef GM INHERITED; }; ////////////////////////////////////////////////////////////////////////////// DEF_GM(return new PixelXorXfermodeGM;) <commit_msg>Fix memory leak in pixelxorxfermode GM GOLD_TRYBOT_URL= https://gold.skia.org/search2?unt=true&query=source_type%3Dgm&master=false&issue=1633773002<commit_after>/* * Copyright 2016 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "gm.h" #include "Resources.h" #include "SkImageDecoder.h" #include "SkPixelXorXfermode.h" #include "SkStream.h" class PixelXorXfermodeGM : public skiagm::GM { public: PixelXorXfermodeGM() { } protected: SkString onShortName() override { return SkString("pixelxorxfermode"); } SkISize onISize() override { return SkISize::Make(512, 512); } void onOnceBeforeDraw() override { SkImageDecoder* codec = nullptr; SkString resourcePath = GetResourcePath("mandrill_512.png"); SkFILEStream stream(resourcePath.c_str()); if (stream.isValid()) { codec = SkImageDecoder::Factory(&stream); } if (codec) { stream.rewind(); codec->decode(&stream, &fBM, kN32_SkColorType, SkImageDecoder::kDecodePixels_Mode); delete codec; } else { fBM.allocN32Pixels(1, 1); fBM.eraseARGB(255, 255, 0 , 0); // red == bad } } void onDraw(SkCanvas* canvas) override { canvas->drawBitmap(fBM, 0, 0); SkRect r = SkRect::MakeIWH(256, 256); // Negate the red channel of the dst (via the ancillary color) but leave // the green & blue channels alone SkPaint p1; p1.setColor(SK_ColorBLACK); // noop p1.setXfermode(SkPixelXorXfermode::Create(SK_ColorRED))->unref(); canvas->drawRect(r, p1); r.offsetTo(256.0f, 0.0f); // Negate the dst color via the src color SkPaint p2; p2.setColor(SK_ColorWHITE); p2.setXfermode(SkPixelXorXfermode::Create(SK_ColorBLACK))->unref(); // noop canvas->drawRect(r, p2); r.offsetTo(0.0f, 256.0f); // Just return the original color SkPaint p3; p3.setColor(SK_ColorBLACK); // noop p3.setXfermode(SkPixelXorXfermode::Create(SK_ColorBLACK))->unref(); // noop canvas->drawRect(r, p3); r.offsetTo(256.0f, 256.0f); // Negate the red & green channels (via the ancillary color) but leave // the blue channel alone SkPaint p4; p4.setColor(SK_ColorBLACK); // noop p4.setXfermode(SkPixelXorXfermode::Create(SK_ColorYELLOW))->unref(); canvas->drawRect(r, p4); } private: SkBitmap fBM; typedef GM INHERITED; }; ////////////////////////////////////////////////////////////////////////////// DEF_GM(return new PixelXorXfermodeGM;) <|endoftext|>
<commit_before>/*ckwg +5 * Copyright 2011 by Kitware, Inc. All Rights Reserved. Please refer to * KITWARE_LICENSE.TXT for licensing information, or contact General Counsel, * Kitware, Inc., 28 Corporate Drive, Clifton Park, NY 12065. */ #include "image_helper.h" #include <vistk/pipeline_types/image_types.h> #include <vistk/pipeline/datum.h> #include <boost/cstdint.hpp> #include <vil/vil_convert.h> #include <vil/vil_crop.h> #include <vil/vil_image_view.h> #include <vil/vil_load.h> #include <vil/vil_save.h> /** * \file image_helper.cxx * * \brief Implementations of functions to help manage images in the pipeline. */ namespace vistk { pixtype_t const& pixtypes ::pixtype_byte() { static pixtype_t const type = pixtype_t("byte"); return type; } pixtype_t const& pixtypes ::pixtype_float() { static pixtype_t const type = pixtype_t("float"); return type; } template <> template <> process::port_type_t const image_helper<uint8_t>::port_types<false, true>::type = image_types::t_byte_rgb; template <> template <> process::port_type_t const image_helper<uint8_t>::port_types<false, false>::type = image_types::t_byte_rgb; template <> template <> process::port_type_t const image_helper<uint8_t>::port_types<true, true>::type = image_types::t_byte_grayscale; template <> template <> process::port_type_t const image_helper<uint8_t>::port_types<true, false>::type = image_types::t_byte_grayscale; template <> template <> process::port_type_t const image_helper<float>::port_types<false, true>::type = image_types::t_float_rgb; template <> template <> process::port_type_t const image_helper<float>::port_types<false, false>::type = image_types::t_float_rgb; template <> template <> process::port_type_t const image_helper<float>::port_types<true, true>::type = image_types::t_float_grayscale; template <> template <> process::port_type_t const image_helper<float>::port_types<true, false>::type = image_types::t_float_grayscale; template <typename PixType> template <bool Grayscale, bool Alpha> process::port_type_t const image_helper<PixType>::port_types<Grayscale, Alpha>::type = process::type_none; process::port_type_t port_type_for_pixtype(pixtype_t const& pixtype, bool grayscale, bool /*alpha*/) { /// \todo Handle alpha parameter. if (pixtype == pixtypes::pixtype_byte()) { if (grayscale) { return image_helper<uint8_t>::port_types<true>::type; } else { return image_helper<uint8_t>::port_types<false>::type; } } else if (pixtype == pixtypes::pixtypes::pixtype_float()) { if (grayscale) { return image_helper<float>::port_types<true>::type; } else { return image_helper<float>::port_types<false>::type; } } return process::type_none; } namespace { template <typename PixType> class vil_functions { public: static datum_t read(path_t const& dat); static void write(path_t const& path, datum_t const& dat); static datum_t convert_to_gray(datum_t const& dat); static datum_t crop(datum_t const& dat, size_t x_offset, size_t y_offset, size_t width, size_t height); protected: typedef vil_image_view<PixType> image_t; }; } read_func_t read_for_pixtype(pixtype_t const& pixtype) { if (pixtype == pixtypes::pixtype_byte()) { return vil_functions<uint8_t>::read; } else if (pixtype == pixtypes::pixtype_float()) { return vil_functions<float>::read; } return NULL; } write_func_t write_for_pixtype(pixtype_t const& pixtype) { if (pixtype == pixtypes::pixtype_byte()) { return vil_functions<uint8_t>::write; } else if (pixtype == pixtypes::pixtype_float()) { return vil_functions<float>::write; } return NULL; } gray_func_t gray_for_pixtype(pixtype_t const& pixtype) { if (pixtype == pixtypes::pixtype_byte()) { return vil_functions<uint8_t>::convert_to_gray; } else if (pixtype == pixtypes::pixtype_float()) { return vil_functions<float>::convert_to_gray; } return NULL; } crop_func_t crop_for_pixtype(pixtype_t const& pixtype) { if (pixtype == pixtypes::pixtype_byte()) { return vil_functions<uint8_t>::crop; } else if (pixtype == pixtypes::pixtype_float()) { return vil_functions<float>::crop; } return NULL; } namespace { template <typename PixType> datum_t vil_functions<PixType> ::read(path_t const& path) { path_t::string_type const fstr = path.native(); std::string const str(fstr.begin(), fstr.end()); image_t img = vil_load(str.c_str()); if (!img) { return datum::error_datum("Unable to load image."); } return datum::new_datum(img); } template <typename PixType> void vil_functions<PixType> ::write(path_t const& path, datum_t const& dat) { path_t::string_type const fpath = path.native(); std::string const str(fpath.begin(), fpath.end()); image_t const img = dat->get_datum<image_t>(); bool const succeed = vil_save(img, str.c_str()); if (!succeed) { /// \todo Log error. } } template <typename PixType> datum_t vil_functions<PixType> ::convert_to_gray(datum_t const& dat) { image_t const rgb_image = dat->get_datum<image_t>(); if (rgb_image.nplanes() == 1) { return datum::new_datum(rgb_image); } if (rgb_image.nplanes() != 3) { return datum::error_datum("Input image does not have three planes."); } image_t gray_image; vil_convert_planes_to_grey(rgb_image, gray_image); return datum::new_datum(gray_image); } template <typename PixType> datum_t vil_functions<PixType> ::crop(datum_t const& dat, size_t x_offset, size_t y_offset, size_t width, size_t height) { image_t const img = dat->get_datum<image_t>(); image_t const crop_img = vil_crop(img, x_offset, width, y_offset, height); if (!crop_img) { return datum::error_datum("Unable to crop the image."); } return datum::new_datum(crop_img); } } } <commit_msg>Add a TODO item when cropping images<commit_after>/*ckwg +5 * Copyright 2011 by Kitware, Inc. All Rights Reserved. Please refer to * KITWARE_LICENSE.TXT for licensing information, or contact General Counsel, * Kitware, Inc., 28 Corporate Drive, Clifton Park, NY 12065. */ #include "image_helper.h" #include <vistk/pipeline_types/image_types.h> #include <vistk/pipeline/datum.h> #include <boost/cstdint.hpp> #include <vil/vil_convert.h> #include <vil/vil_crop.h> #include <vil/vil_image_view.h> #include <vil/vil_load.h> #include <vil/vil_save.h> /** * \file image_helper.cxx * * \brief Implementations of functions to help manage images in the pipeline. */ namespace vistk { pixtype_t const& pixtypes ::pixtype_byte() { static pixtype_t const type = pixtype_t("byte"); return type; } pixtype_t const& pixtypes ::pixtype_float() { static pixtype_t const type = pixtype_t("float"); return type; } template <> template <> process::port_type_t const image_helper<uint8_t>::port_types<false, true>::type = image_types::t_byte_rgb; template <> template <> process::port_type_t const image_helper<uint8_t>::port_types<false, false>::type = image_types::t_byte_rgb; template <> template <> process::port_type_t const image_helper<uint8_t>::port_types<true, true>::type = image_types::t_byte_grayscale; template <> template <> process::port_type_t const image_helper<uint8_t>::port_types<true, false>::type = image_types::t_byte_grayscale; template <> template <> process::port_type_t const image_helper<float>::port_types<false, true>::type = image_types::t_float_rgb; template <> template <> process::port_type_t const image_helper<float>::port_types<false, false>::type = image_types::t_float_rgb; template <> template <> process::port_type_t const image_helper<float>::port_types<true, true>::type = image_types::t_float_grayscale; template <> template <> process::port_type_t const image_helper<float>::port_types<true, false>::type = image_types::t_float_grayscale; template <typename PixType> template <bool Grayscale, bool Alpha> process::port_type_t const image_helper<PixType>::port_types<Grayscale, Alpha>::type = process::type_none; process::port_type_t port_type_for_pixtype(pixtype_t const& pixtype, bool grayscale, bool /*alpha*/) { /// \todo Handle alpha parameter. if (pixtype == pixtypes::pixtype_byte()) { if (grayscale) { return image_helper<uint8_t>::port_types<true>::type; } else { return image_helper<uint8_t>::port_types<false>::type; } } else if (pixtype == pixtypes::pixtypes::pixtype_float()) { if (grayscale) { return image_helper<float>::port_types<true>::type; } else { return image_helper<float>::port_types<false>::type; } } return process::type_none; } namespace { template <typename PixType> class vil_functions { public: static datum_t read(path_t const& dat); static void write(path_t const& path, datum_t const& dat); static datum_t convert_to_gray(datum_t const& dat); static datum_t crop(datum_t const& dat, size_t x_offset, size_t y_offset, size_t width, size_t height); protected: typedef vil_image_view<PixType> image_t; }; } read_func_t read_for_pixtype(pixtype_t const& pixtype) { if (pixtype == pixtypes::pixtype_byte()) { return vil_functions<uint8_t>::read; } else if (pixtype == pixtypes::pixtype_float()) { return vil_functions<float>::read; } return NULL; } write_func_t write_for_pixtype(pixtype_t const& pixtype) { if (pixtype == pixtypes::pixtype_byte()) { return vil_functions<uint8_t>::write; } else if (pixtype == pixtypes::pixtype_float()) { return vil_functions<float>::write; } return NULL; } gray_func_t gray_for_pixtype(pixtype_t const& pixtype) { if (pixtype == pixtypes::pixtype_byte()) { return vil_functions<uint8_t>::convert_to_gray; } else if (pixtype == pixtypes::pixtype_float()) { return vil_functions<float>::convert_to_gray; } return NULL; } crop_func_t crop_for_pixtype(pixtype_t const& pixtype) { if (pixtype == pixtypes::pixtype_byte()) { return vil_functions<uint8_t>::crop; } else if (pixtype == pixtypes::pixtype_float()) { return vil_functions<float>::crop; } return NULL; } namespace { template <typename PixType> datum_t vil_functions<PixType> ::read(path_t const& path) { path_t::string_type const fstr = path.native(); std::string const str(fstr.begin(), fstr.end()); image_t img = vil_load(str.c_str()); if (!img) { return datum::error_datum("Unable to load image."); } return datum::new_datum(img); } template <typename PixType> void vil_functions<PixType> ::write(path_t const& path, datum_t const& dat) { path_t::string_type const fpath = path.native(); std::string const str(fpath.begin(), fpath.end()); image_t const img = dat->get_datum<image_t>(); bool const succeed = vil_save(img, str.c_str()); if (!succeed) { /// \todo Log error. } } template <typename PixType> datum_t vil_functions<PixType> ::convert_to_gray(datum_t const& dat) { image_t const rgb_image = dat->get_datum<image_t>(); if (rgb_image.nplanes() == 1) { return datum::new_datum(rgb_image); } if (rgb_image.nplanes() != 3) { return datum::error_datum("Input image does not have three planes."); } image_t gray_image; vil_convert_planes_to_grey(rgb_image, gray_image); return datum::new_datum(gray_image); } template <typename PixType> datum_t vil_functions<PixType> ::crop(datum_t const& dat, size_t x_offset, size_t y_offset, size_t width, size_t height) { image_t const img = dat->get_datum<image_t>(); /// \todo Sanity check the parameters. image_t const crop_img = vil_crop(img, x_offset, width, y_offset, height); if (!crop_img) { return datum::error_datum("Unable to crop the image."); } return datum::new_datum(crop_img); } } } <|endoftext|>
<commit_before>//----------------------------------------------------------------------------- // MurmurHash3 was written by Austin Appleby, and is placed in the public // domain. mmh3 Python module was written by Hajime Senuma, // and is also placed in the public domain. // The authors hereby disclaim copyright to these source codes. #include <stdio.h> #include <string.h> #include <Python.h> #include "MurmurHash3.h" #if defined(_MSC_VER) typedef signed char int8_t; typedef signed long int32_t; typedef signed __int64 int64_t; typedef unsigned char uint8_t; typedef unsigned long uint32_t; typedef unsigned __int64 uint64_t; // Other compilers #else // defined(_MSC_VER) #include <stdint.h> #endif // !defined(_MSC_VER) static PyObject * mmh3_hash(PyObject *self, PyObject *args, PyObject *keywds) { const char *target_str; int target_str_len; uint32_t seed = 0; int32_t result[1]; static char *kwlist[] = {(char *)"key", (char *)"seed", NULL}; if (!PyArg_ParseTupleAndKeywords(args, keywds, "s#|i", kwlist, &target_str, &target_str_len, &seed)) { return NULL; } MurmurHash3_x86_32(target_str, target_str_len, seed, result); #if PY_MAJOR_VERSION >= 3 return PyLong_FromLong(result[0]); #else return PyInt_FromLong(result[0]); #endif } static PyObject * mmh3_hash64(PyObject *self, PyObject *args, PyObject *keywds) { const char *target_str; int target_str_len; uint32_t seed = 0; int64_t result[2]; char x64arch = 1; static char *kwlist[] = {(char *)"key", (char *)"seed", (char *)"x64arch", NULL}; if (!PyArg_ParseTupleAndKeywords(args, keywds, "s#|i|B", kwlist, &target_str, &target_str_len, &seed, &x64arch)) { return NULL; } if (x64arch == 1) { MurmurHash3_x64_128(target_str, target_str_len, seed, result); } else { MurmurHash3_x86_128(target_str, target_str_len, seed, result); } PyObject *retval = Py_BuildValue("ll", result[0], result[1]); return retval; } static PyObject * mmh3_hash_bytes(PyObject *self, PyObject *args, PyObject *keywds) { const char *target_str; int target_str_len; uint32_t seed = 0; uint32_t result[4]; char x64arch = 1; static char *kwlist[] = {(char *)"key", (char *)"seed", (char *)"x64arch", NULL}; if (!PyArg_ParseTupleAndKeywords(args, keywds, "s#|i|B", kwlist, &target_str, &target_str_len, &seed, &x64arch)) { return NULL; } if (x64arch == 1) { MurmurHash3_x64_128(target_str, target_str_len, seed, result); } else { MurmurHash3_x86_128(target_str, target_str_len, seed, result); } char bytes[16]; memcpy(bytes, result, 16); return PyBytes_FromStringAndSize(bytes, 16); } struct module_state { PyObject *error; }; #if PY_MAJOR_VERSION >= 3 #define GETSTATE(m) ((struct module_state*)PyModule_GetState(m)) #else #define GETSTATE(m) (&_state) static struct module_state _state; #endif static PyMethodDef Mmh3Methods[] = { {"hash", (PyCFunction)mmh3_hash, METH_VARARGS | METH_KEYWORDS, "hash(key[, seed=0]) -> hash value\n Return a 32 bit integer for a string."}, {"hash64", (PyCFunction)mmh3_hash64, METH_VARARGS | METH_KEYWORDS, "hash64(key[, seed=0, x64arch=True]) -> (hash value 1, hash value 2)\n Return a tuple of two 64 bit integers for a string. Optimized for the x64 bit architecture when x64arch=True, otherwise for x86."}, {"hash_bytes", (PyCFunction)mmh3_hash_bytes, METH_VARARGS | METH_KEYWORDS, "hash_bytes(key[, seed=0, x64arch=True]) -> bytes\n Return a 128 bit hash value as bytes for a string. Optimized for the x64 bit architecture when x64arch=True, otherwise for the x86."}, {NULL, NULL, 0, NULL} }; #if PY_MAJOR_VERSION >= 3 static int mmh3_traverse(PyObject *m, visitproc visit, void *arg) { Py_VISIT(GETSTATE(m)->error); return 0; } static int mmh3_clear(PyObject *m) { Py_CLEAR(GETSTATE(m)->error); return 0; } static struct PyModuleDef mmh3module = { PyModuleDef_HEAD_INIT, "mmh3", "mmh3 is a Python frontend to MurmurHash3, a fast and robust hash library created by Austin Appleby (http://code.google.com/p/smhasher/).\n Ported by Hajime Senuma <hajime.senuma@gmail.com>\n Try hash('foobar') or hash('foobar', 1984).", sizeof(struct module_state), Mmh3Methods, NULL, mmh3_traverse, mmh3_clear, NULL }; #define INITERROR return NULL extern "C" { PyMODINIT_FUNC PyInit_mmh3(void) #else // PY_MAJOR_VERSION >= 3 #define INITERROR return extern "C" { void initmmh3(void) #endif // PY_MAJOR_VERSION >= 3 { #if PY_MAJOR_VERSION >= 3 PyObject *module = PyModule_Create(&mmh3module); #else PyObject *module = Py_InitModule("mmh3", Mmh3Methods); #endif if (module == NULL) INITERROR; PyModule_AddStringConstant(module, "__version__", "2.2"); struct module_state *st = GETSTATE(module); st->error = PyErr_NewException((char *) "mmh3.Error", NULL, NULL); if (st->error = NULL) { Py_DECREF(module); INITERROR; } #if PY_MAJOR_VERSION >= 3 return module; #endif } } // extern "C" <commit_msg>add hash128 to get a single python long<commit_after>//----------------------------------------------------------------------------- // MurmurHash3 was written by Austin Appleby, and is placed in the public // domain. mmh3 Python module was written by Hajime Senuma, // and is also placed in the public domain. // The authors hereby disclaim copyright to these source codes. #include <stdio.h> #include <string.h> #include <Python.h> #include "MurmurHash3.h" #if defined(_MSC_VER) typedef signed char int8_t; typedef signed long int32_t; typedef signed __int64 int64_t; typedef unsigned char uint8_t; typedef unsigned long uint32_t; typedef unsigned __int64 uint64_t; // Other compilers #else // defined(_MSC_VER) #include <stdint.h> #endif // !defined(_MSC_VER) static PyObject * mmh3_hash(PyObject *self, PyObject *args, PyObject *keywds) { const char *target_str; int target_str_len; uint32_t seed = 0; int32_t result[1]; static char *kwlist[] = {(char *)"key", (char *)"seed", NULL}; if (!PyArg_ParseTupleAndKeywords(args, keywds, "s#|i", kwlist, &target_str, &target_str_len, &seed)) { return NULL; } MurmurHash3_x86_32(target_str, target_str_len, seed, result); #if PY_MAJOR_VERSION >= 3 return PyLong_FromLong(result[0]); #else return PyInt_FromLong(result[0]); #endif } static PyObject * mmh3_hash64(PyObject *self, PyObject *args, PyObject *keywds) { const char *target_str; int target_str_len; uint32_t seed = 0; int64_t result[2]; char x64arch = 1; static char *kwlist[] = {(char *)"key", (char *)"seed", (char *)"x64arch", NULL}; if (!PyArg_ParseTupleAndKeywords(args, keywds, "s#|i|B", kwlist, &target_str, &target_str_len, &seed, &x64arch)) { return NULL; } if (x64arch == 1) { MurmurHash3_x64_128(target_str, target_str_len, seed, result); } else { MurmurHash3_x86_128(target_str, target_str_len, seed, result); } PyObject *retval = Py_BuildValue("ll", result[0], result[1]); return retval; } static PyObject * mmh3_hash128(PyObject *self, PyObject *args, PyObject *keywds) { const char *target_str; int target_str_len; uint32_t seed = 0; uint64_t result[2]; char x64arch = 1; static char *kwlist[] = {(char *)"key", (char *)"seed", (char *)"x64arch", NULL}; if (!PyArg_ParseTupleAndKeywords(args, keywds, "s#|i|B", kwlist, &target_str, &target_str_len, &seed, &x64arch)) { return NULL; } if (x64arch == 1) { MurmurHash3_x64_128(target_str, target_str_len, seed, result); } else { MurmurHash3_x86_128(target_str, target_str_len, seed, result); } PyObject *retval = _PyLong_FromByteArray((unsigned char *)result, 16, 1, 0); return retval; } static PyObject * mmh3_hash_bytes(PyObject *self, PyObject *args, PyObject *keywds) { const char *target_str; int target_str_len; uint32_t seed = 0; uint32_t result[4]; char x64arch = 1; static char *kwlist[] = {(char *)"key", (char *)"seed", (char *)"x64arch", NULL}; if (!PyArg_ParseTupleAndKeywords(args, keywds, "s#|i|B", kwlist, &target_str, &target_str_len, &seed, &x64arch)) { return NULL; } if (x64arch == 1) { MurmurHash3_x64_128(target_str, target_str_len, seed, result); } else { MurmurHash3_x86_128(target_str, target_str_len, seed, result); } char bytes[16]; memcpy(bytes, result, 16); return PyBytes_FromStringAndSize(bytes, 16); } struct module_state { PyObject *error; }; #if PY_MAJOR_VERSION >= 3 #define GETSTATE(m) ((struct module_state*)PyModule_GetState(m)) #else #define GETSTATE(m) (&_state) static struct module_state _state; #endif static PyMethodDef Mmh3Methods[] = { {"hash", (PyCFunction)mmh3_hash, METH_VARARGS | METH_KEYWORDS, "hash(key[, seed=0]) -> hash value\n Return a 32 bit integer."}, {"hash64", (PyCFunction)mmh3_hash64, METH_VARARGS | METH_KEYWORDS, "hash64(key[, seed=0, x64arch=True]) -> (hash value 1, hash value 2)\n Return a tuple of two 64 bit integers for a string. Optimized for the x64 bit architecture when x64arch=True, otherwise for x86."}, {"hash128", (PyCFunction)mmh3_hash128, METH_VARARGS | METH_KEYWORDS, "hash128(key[, seed=0]) -> hash value\n Return a 128 bit long integer."}, {"hash_bytes", (PyCFunction)mmh3_hash_bytes, METH_VARARGS | METH_KEYWORDS, "hash_bytes(key[, seed=0, x64arch=True]) -> bytes\n Return a 128 bit hash value as bytes for a string. Optimized for the x64 bit architecture when x64arch=True, otherwise for the x86."}, {NULL, NULL, 0, NULL} }; #if PY_MAJOR_VERSION >= 3 static int mmh3_traverse(PyObject *m, visitproc visit, void *arg) { Py_VISIT(GETSTATE(m)->error); return 0; } static int mmh3_clear(PyObject *m) { Py_CLEAR(GETSTATE(m)->error); return 0; } static struct PyModuleDef mmh3module = { PyModuleDef_HEAD_INIT, "mmh3", "mmh3 is a Python frontend to MurmurHash3, a fast and robust hash library created by Austin Appleby (http://code.google.com/p/smhasher/).\n Ported by Hajime Senuma <hajime.senuma@gmail.com>\n Try hash('foobar') or hash('foobar', 1984).", sizeof(struct module_state), Mmh3Methods, NULL, mmh3_traverse, mmh3_clear, NULL }; #define INITERROR return NULL extern "C" { PyMODINIT_FUNC PyInit_mmh3(void) #else // PY_MAJOR_VERSION >= 3 #define INITERROR return extern "C" { void initmmh3(void) #endif // PY_MAJOR_VERSION >= 3 { #if PY_MAJOR_VERSION >= 3 PyObject *module = PyModule_Create(&mmh3module); #else PyObject *module = Py_InitModule("mmh3", Mmh3Methods); #endif if (module == NULL) INITERROR; PyModule_AddStringConstant(module, "__version__", "2.2"); struct module_state *st = GETSTATE(module); st->error = PyErr_NewException((char *) "mmh3.Error", NULL, NULL); if (st->error = NULL) { Py_DECREF(module); INITERROR; } #if PY_MAJOR_VERSION >= 3 return module; #endif } } // extern "C" <|endoftext|>
<commit_before>/* * Copyright 2002-2005 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. */ /* * XSEC * * Configuration file for Windows platform * * Needs to be modified by hand * * Author(s): Berin Lautenbach * * $Id$ * */ #include <xercesc/util/XercesVersion.hpp> #define XSEC_VERSION "1.2.0" #define XSEC_VERSION_MAJOR 1 #define XSEC_VERSION_MEDIUM 2 #define XSEC_VERSION_MINOR 0 /* * Because we don't have a configure script, we need to rely on version * numbers to understand library idiosycracies */ #if (XERCES_VERSION_MAJOR >= 2) && (XERCES_VERSION_MINOR >= 3) /* * As of version 2.3, xerces requires a version parameter in XMLFormatter * constructors */ # define XSEC_XERCES_FORMATTER_REQUIRES_VERSION 1 /* 2.3 and above use a user defined Memory Manager. In some cases, this actually needs to be passed to functions */ # define XSEC_XERCES_REQUIRES_MEMMGR 1 /* Does XMLString::release() exist */ #define XSEC_XERCES_XMLSTRING_HAS_RELEASE 1 /* Is it possible to setIdAttributes? - DOM level 3 call */ #define XSEC_XERCES_HAS_SETIDATTRIBUTE 1 #else /* * In version 2.2, the XMLUri class was broken for relative URI de-referencing */ # define XSEC_XERCES_BROKEN_XMLURI 1 #endif /* * The following defines whether Xalan integration is required. * * Xalan is used for XSLT and complex XPath processing. * Activate this #define if Xalan is not required (or desired) */ #define XSEC_NO_XALAN #if !defined (XSEC_NO_XALAN) # include <xalanc/Include/XalanVersion.hpp> # if (_XALAN_VERSION <= 10800) # define XSEC_XSLEXCEPTION_RETURNS_DOMSTRING 1 # endif # if (_XALAN_VERSION >= 10900) /* 1.9 and above have XSLException::getType() returns XalanDOMChar *, not XalanDOMString */ # undef XSEC_XSLEXCEPTION_RETURNS_DOMSTRING /* 1.9 and above do not take a XercesDOMSupport as input to the ctor */ # undef XSEC_XERCESPARSERLIAISON_REQS_DOMSUPPORT /* 1.9 and above require a NodeRefList as input to XPathEvaluator:: selectNodeList */ # define XSEC_SELECTNODELIST_REQS_NODEREFLIST /* 1.9 and above use MemoryManager for the XPath Function classes */ # define XSEC_XALAN_REQS_MEMORYMANAGER # else /* 1.9 and above have XSLException::getType() returns XalanDOMChar *, not XalanDOMString */ # define XSEC_XSLEXCEPTION_RETURNS_DOMSTRING 1 /* 1.9 and above do not take a XercesDOMSupport as input to the ctor */ # define XSEC_XERCESPARSERLIAISON_REQS_DOMSUPPORT /* 1.9 and above require a NodeRefList as input to XPathEvaluator:: selectNodeList */ # undef XSEC_SELECTNODELIST_REQS_NODEREFLIST /* 1.9 and above use MemoryManager for the XPath Function classes */ # undef XSEC_XALAN_REQS_MEMORYMANAGER # endif #endif /* * Define presence of cryptographic providers */ //#define HAVE_OPENSSL 1 #define HAVE_WINCAPI 1 #define HAVE_NSS 1 /* * Some settings for OpenSSL if we have it * */ #if defined (HAVE_OPENSSL) # include <openssl/opensslv.h> # if (OPENSSL_VERSION_NUMBER >= 0x00907000) # define XSEC_OPENSSL_CONST_BUFFERS # define XSEC_OPENSSL_HAVE_AES # define XSEC_OPENSSL_CANSET_PADDING # define XSEC_OPENSSL_HAVE_CRYPTO_CLEANUP_ALL_EX_DATA # endif # if (OPENSSL_VERSION_NUMBER >= 0x00908000) # define XSEC_OPENSSL_D2IX509_CONST_BUFFER # endif #endif /* * Macros used to determine what header files exist on this * system */ /* Posix unistd.h */ /* #define HAVE_UNISTD_H */ /* Windows direct.h */ #define HAVE_DIRECT_H 1 <commit_msg>Added support for NSS crypto layer.<commit_after>/* * Copyright 2002-2005 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. */ /* * XSEC * * Configuration file for Windows platform * * Needs to be modified by hand * * Author(s): Berin Lautenbach * * $Id$ * */ #include <xercesc/util/XercesVersion.hpp> #define XSEC_VERSION "1.2.0" #define XSEC_VERSION_MAJOR 1 #define XSEC_VERSION_MEDIUM 2 #define XSEC_VERSION_MINOR 0 /* * Because we don't have a configure script, we need to rely on version * numbers to understand library idiosycracies */ #if (XERCES_VERSION_MAJOR >= 2) && (XERCES_VERSION_MINOR >= 3) /* * As of version 2.3, xerces requires a version parameter in XMLFormatter * constructors */ # define XSEC_XERCES_FORMATTER_REQUIRES_VERSION 1 /* 2.3 and above use a user defined Memory Manager. In some cases, this actually needs to be passed to functions */ # define XSEC_XERCES_REQUIRES_MEMMGR 1 /* Does XMLString::release() exist */ #define XSEC_XERCES_XMLSTRING_HAS_RELEASE 1 /* Is it possible to setIdAttributes? - DOM level 3 call */ #define XSEC_XERCES_HAS_SETIDATTRIBUTE 1 #else /* * In version 2.2, the XMLUri class was broken for relative URI de-referencing */ # define XSEC_XERCES_BROKEN_XMLURI 1 #endif /* * The following defines whether Xalan integration is required. * * Xalan is used for XSLT and complex XPath processing. * Activate this #define if Xalan is not required (or desired) */ // #define XSEC_NO_XALAN #if !defined (XSEC_NO_XALAN) # include <xalanc/Include/XalanVersion.hpp> # if (_XALAN_VERSION <= 10800) # define XSEC_XSLEXCEPTION_RETURNS_DOMSTRING 1 # endif # if (_XALAN_VERSION >= 10900) /* 1.9 and above have XSLException::getType() returns XalanDOMChar *, not XalanDOMString */ # undef XSEC_XSLEXCEPTION_RETURNS_DOMSTRING /* 1.9 and above do not take a XercesDOMSupport as input to the ctor */ # undef XSEC_XERCESPARSERLIAISON_REQS_DOMSUPPORT /* 1.9 and above require a NodeRefList as input to XPathEvaluator:: selectNodeList */ # define XSEC_SELECTNODELIST_REQS_NODEREFLIST /* 1.9 and above use MemoryManager for the XPath Function classes */ # define XSEC_XALAN_REQS_MEMORYMANAGER # else /* 1.9 and above have XSLException::getType() returns XalanDOMChar *, not XalanDOMString */ # define XSEC_XSLEXCEPTION_RETURNS_DOMSTRING 1 /* 1.9 and above do not take a XercesDOMSupport as input to the ctor */ # define XSEC_XERCESPARSERLIAISON_REQS_DOMSUPPORT /* 1.9 and above require a NodeRefList as input to XPathEvaluator:: selectNodeList */ # undef XSEC_SELECTNODELIST_REQS_NODEREFLIST /* 1.9 and above use MemoryManager for the XPath Function classes */ # undef XSEC_XALAN_REQS_MEMORYMANAGER # endif #endif /* * Define presence of cryptographic providers */ #define HAVE_OPENSSL 1 #define HAVE_WINCAPI 1 #define HAVE_NSS 1 /* * Some settings for OpenSSL if we have it * */ #if defined (HAVE_OPENSSL) # include <openssl/opensslv.h> # if (OPENSSL_VERSION_NUMBER >= 0x00907000) # define XSEC_OPENSSL_CONST_BUFFERS # define XSEC_OPENSSL_HAVE_AES # define XSEC_OPENSSL_CANSET_PADDING # define XSEC_OPENSSL_HAVE_CRYPTO_CLEANUP_ALL_EX_DATA # endif # if (OPENSSL_VERSION_NUMBER >= 0x00908000) # define XSEC_OPENSSL_D2IX509_CONST_BUFFER # endif #endif /* * Macros used to determine what header files exist on this * system */ /* Posix unistd.h */ /* #define HAVE_UNISTD_H */ /* Windows direct.h */ #define HAVE_DIRECT_H 1 <|endoftext|>
<commit_before>// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. #include "vm/bootstrap.h" #include "include/dart_api.h" #if !defined(DART_PRECOMPILED_RUNTIME) #include "vm/class_finalizer.h" #include "vm/compiler.h" #include "vm/kernel_reader.h" #endif #include "vm/object.h" #if !defined(DART_PRECOMPILED_RUNTIME) #include "vm/object_store.h" #endif namespace dart { #if !defined(DART_PRECOMPILED_RUNTIME) #define MAKE_PROPERTIES(CamelName, name) \ {ObjectStore::k##CamelName, "dart:" #name}, struct BootstrapLibProps { ObjectStore::BootstrapLibraryId index; const char* uri; }; static BootstrapLibProps bootstrap_libraries[] = { FOR_EACH_BOOTSTRAP_LIBRARY(MAKE_PROPERTIES)}; #undef MAKE_PROPERTIES static const intptr_t bootstrap_library_count = ARRAY_SIZE(bootstrap_libraries); void Finish(Thread* thread, bool from_kernel) { Bootstrap::SetupNativeResolver(); ClassFinalizer::ProcessPendingClasses(from_kernel); // Eagerly compile the _Closure class as it is the class of all closure // instances. This allows us to just finalize function types without going // through the hoops of trying to compile their scope class. ObjectStore* object_store = thread->isolate()->object_store(); Zone* zone = thread->zone(); Class& cls = Class::Handle(zone, object_store->closure_class()); Compiler::CompileClass(cls); #if defined(DEBUG) // Verify that closure field offsets are identical in Dart and C++. const Array& fields = Array::Handle(zone, cls.fields()); ASSERT(fields.Length() == 4); Field& field = Field::Handle(zone); field ^= fields.At(0); ASSERT(field.Offset() == Closure::instantiator_type_arguments_offset()); field ^= fields.At(1); ASSERT(field.Offset() == Closure::function_type_arguments_offset()); field ^= fields.At(2); ASSERT(field.Offset() == Closure::function_offset()); field ^= fields.At(3); ASSERT(field.Offset() == Closure::context_offset()); #endif // defined(DEBUG) // Eagerly compile Bool class, bool constants are used from within compiler. cls = object_store->bool_class(); Compiler::CompileClass(cls); } RawError* BootstrapFromKernel(Thread* thread, kernel::Program* program) { Zone* zone = thread->zone(); kernel::KernelReader reader(program); Isolate* isolate = thread->isolate(); // Mark the already-pending classes. This mark bit will be used to avoid // adding classes to the list more than once. GrowableObjectArray& pending_classes = GrowableObjectArray::Handle( zone, isolate->object_store()->pending_classes()); dart::Class& pending = dart::Class::Handle(zone); for (intptr_t i = 0; i < pending_classes.Length(); ++i) { pending ^= pending_classes.At(i); pending.set_is_marked_for_parsing(); } // Load the bootstrap libraries in order (see object_store.h). Library& library = Library::Handle(zone); String& dart_name = String::Handle(zone); for (intptr_t i = 0; i < bootstrap_library_count; ++i) { ObjectStore::BootstrapLibraryId id = bootstrap_libraries[i].index; library = isolate->object_store()->bootstrap_library(id); dart_name = library.url(); for (intptr_t j = 0; j < program->library_count(); ++j) { const String& kernel_name = reader.LibraryUri(j); if (kernel_name.Equals(dart_name)) { reader.ReadLibrary(reader.library_offset(j)); library.SetLoaded(); break; } } } // Finish bootstrapping, including class finalization. Finish(thread, /*from_kernel=*/true); // The platform binary may contain other libraries (e.g., dart:_builtin or // dart:io) that will not be bundled with application. Load them now. reader.ReadProgram(); // The builtin library should be registered with the VM. dart_name = String::New("dart:_builtin"); library = Library::LookupLibrary(thread, dart_name); isolate->object_store()->set_builtin_library(library); return Error::null(); } RawError* Bootstrap::DoBootstrapping(kernel::Program* program) { Thread* thread = Thread::Current(); Isolate* isolate = thread->isolate(); Zone* zone = thread->zone(); String& uri = String::Handle(zone); Library& lib = Library::Handle(zone); HANDLESCOPE(thread); // Ensure there are library objects for all the bootstrap libraries. for (intptr_t i = 0; i < bootstrap_library_count; ++i) { ObjectStore::BootstrapLibraryId id = bootstrap_libraries[i].index; uri = Symbols::New(thread, bootstrap_libraries[i].uri); lib = isolate->object_store()->bootstrap_library(id); ASSERT(lib.raw() == Library::LookupLibrary(thread, uri)); if (lib.IsNull()) { lib = Library::NewLibraryHelper(uri, false); lib.SetLoadRequested(); lib.Register(thread); isolate->object_store()->set_bootstrap_library(id, lib); } } return BootstrapFromKernel(thread, program); } #else RawError* Bootstrap::DoBootstrapping(kernel::Program* program) { UNREACHABLE(); return Error::null(); } #endif // !defined(DART_PRECOMPILED_RUNTIME) } // namespace dart <commit_msg>Correct assertions for validating layout of Closure objects<commit_after>// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. #include "vm/bootstrap.h" #include "include/dart_api.h" #if !defined(DART_PRECOMPILED_RUNTIME) #include "vm/class_finalizer.h" #include "vm/compiler.h" #include "vm/kernel_reader.h" #endif #include "vm/object.h" #if !defined(DART_PRECOMPILED_RUNTIME) #include "vm/object_store.h" #endif namespace dart { #if !defined(DART_PRECOMPILED_RUNTIME) #define MAKE_PROPERTIES(CamelName, name) \ {ObjectStore::k##CamelName, "dart:" #name}, struct BootstrapLibProps { ObjectStore::BootstrapLibraryId index; const char* uri; }; static BootstrapLibProps bootstrap_libraries[] = { FOR_EACH_BOOTSTRAP_LIBRARY(MAKE_PROPERTIES)}; #undef MAKE_PROPERTIES static const intptr_t bootstrap_library_count = ARRAY_SIZE(bootstrap_libraries); void Finish(Thread* thread, bool from_kernel) { Bootstrap::SetupNativeResolver(); ClassFinalizer::ProcessPendingClasses(from_kernel); // Eagerly compile the _Closure class as it is the class of all closure // instances. This allows us to just finalize function types without going // through the hoops of trying to compile their scope class. ObjectStore* object_store = thread->isolate()->object_store(); Zone* zone = thread->zone(); Class& cls = Class::Handle(zone, object_store->closure_class()); Compiler::CompileClass(cls); #if defined(DEBUG) // Verify that closure field offsets are identical in Dart and C++. const Array& fields = Array::Handle(zone, cls.fields()); ASSERT(fields.Length() == 5); Field& field = Field::Handle(zone); field ^= fields.At(0); ASSERT(field.Offset() == Closure::instantiator_type_arguments_offset()); field ^= fields.At(1); ASSERT(field.Offset() == Closure::function_type_arguments_offset()); field ^= fields.At(2); ASSERT(field.Offset() == Closure::function_offset()); field ^= fields.At(3); ASSERT(field.Offset() == Closure::context_offset()); field ^= fields.At(4); ASSERT(field.Offset() == Closure::hash_offset()); #endif // defined(DEBUG) // Eagerly compile Bool class, bool constants are used from within compiler. cls = object_store->bool_class(); Compiler::CompileClass(cls); } RawError* BootstrapFromKernel(Thread* thread, kernel::Program* program) { Zone* zone = thread->zone(); kernel::KernelReader reader(program); Isolate* isolate = thread->isolate(); // Mark the already-pending classes. This mark bit will be used to avoid // adding classes to the list more than once. GrowableObjectArray& pending_classes = GrowableObjectArray::Handle( zone, isolate->object_store()->pending_classes()); dart::Class& pending = dart::Class::Handle(zone); for (intptr_t i = 0; i < pending_classes.Length(); ++i) { pending ^= pending_classes.At(i); pending.set_is_marked_for_parsing(); } // Load the bootstrap libraries in order (see object_store.h). Library& library = Library::Handle(zone); String& dart_name = String::Handle(zone); for (intptr_t i = 0; i < bootstrap_library_count; ++i) { ObjectStore::BootstrapLibraryId id = bootstrap_libraries[i].index; library = isolate->object_store()->bootstrap_library(id); dart_name = library.url(); for (intptr_t j = 0; j < program->library_count(); ++j) { const String& kernel_name = reader.LibraryUri(j); if (kernel_name.Equals(dart_name)) { reader.ReadLibrary(reader.library_offset(j)); library.SetLoaded(); break; } } } // Finish bootstrapping, including class finalization. Finish(thread, /*from_kernel=*/true); // The platform binary may contain other libraries (e.g., dart:_builtin or // dart:io) that will not be bundled with application. Load them now. reader.ReadProgram(); // The builtin library should be registered with the VM. dart_name = String::New("dart:_builtin"); library = Library::LookupLibrary(thread, dart_name); isolate->object_store()->set_builtin_library(library); return Error::null(); } RawError* Bootstrap::DoBootstrapping(kernel::Program* program) { Thread* thread = Thread::Current(); Isolate* isolate = thread->isolate(); Zone* zone = thread->zone(); String& uri = String::Handle(zone); Library& lib = Library::Handle(zone); HANDLESCOPE(thread); // Ensure there are library objects for all the bootstrap libraries. for (intptr_t i = 0; i < bootstrap_library_count; ++i) { ObjectStore::BootstrapLibraryId id = bootstrap_libraries[i].index; uri = Symbols::New(thread, bootstrap_libraries[i].uri); lib = isolate->object_store()->bootstrap_library(id); ASSERT(lib.raw() == Library::LookupLibrary(thread, uri)); if (lib.IsNull()) { lib = Library::NewLibraryHelper(uri, false); lib.SetLoadRequested(); lib.Register(thread); isolate->object_store()->set_bootstrap_library(id, lib); } } return BootstrapFromKernel(thread, program); } #else RawError* Bootstrap::DoBootstrapping(kernel::Program* program) { UNREACHABLE(); return Error::null(); } #endif // !defined(DART_PRECOMPILED_RUNTIME) } // namespace dart <|endoftext|>
<commit_before>/* * Copyright (c) 2015 Novell, Inc. * Copyright (c) [2016-2018] SUSE LLC * * All Rights Reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of version 2 of the GNU General Public License as published * by the Free Software Foundation. * * 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, contact Novell, Inc. * * To contact Novell about this file by physical or electronic mail, you may * find current contact information at www.novell.com. */ #include "storage/Utils/Mockup.h" #include "storage/Utils/XmlFile.h" #include "storage/Utils/ExceptionImpl.h" #include "storage/Utils/LoggerImpl.h" namespace storage { void Mockup::load(const string& filename) { XmlFile xml(filename); const xmlNode* root_node = xml.getRootElement(); if (!root_node) ST_THROW(Exception("root node not found")); const xmlNode* mockup_node = getChildNode(root_node, "Mockup"); if (!mockup_node) ST_THROW(Exception("Mockup node not found")); const xmlNode* commands_node = getChildNode(mockup_node, "Commands"); if (!commands_node) ST_THROW(Exception("Commands node not found")); for (const xmlNode* command_node : getChildNodes(commands_node)) { string name; getChildValue(command_node, "name", name); Command command; getChildValue(command_node, "stdout", command.stdout); getChildValue(command_node, "stderr", command.stderr); getChildValue(command_node, "exit-code", command.exit_code); commands[name] = command; } const xmlNode* files_node = getChildNode(mockup_node, "Files"); if (!files_node) ST_THROW(Exception("Files node not found")); for (const xmlNode* file_node : getChildNodes(files_node)) { string name; getChildValue(file_node, "name", name); File file; getChildValue(file_node, "content", file.content); files[name] = file; } } void Mockup::save(const string& filename) { XmlFile xml; xmlNode* mockup_node = xmlNewNode("Mockup"); xml.setRootElement(mockup_node); xmlNode* comment = xmlNewComment(string(" " + generated_string() + " ").c_str()); xmlAddPrevSibling(mockup_node, comment); xmlNode* commands_node = xmlNewChild(mockup_node, "Commands"); for (const map<string, Command>::value_type& it : commands) { xmlNode* command_node = xmlNewChild(commands_node, "Command"); setChildValue(command_node, "name", it.first); setChildValue(command_node, "stdout", it.second.stdout); setChildValue(command_node, "stderr", it.second.stderr); setChildValueIf(command_node, "exit-code", it.second.exit_code, it.second.exit_code != 0); } xmlNode* files_node = xmlNewChild(mockup_node, "Files"); for (const map<string, File>::value_type& it : files) { xmlNode* file_node = xmlNewChild(files_node, "File"); setChildValue(file_node, "name", it.first); setChildValue(file_node, "content", it.second.content); } xml.save(filename); } bool Mockup::has_command(const string& name) { return commands.find(name) != commands.end(); } const Mockup::Command& Mockup::get_command(const string& name) { map<string, Command>::const_iterator it = commands.find(name); if (it == commands.end()) ST_THROW(Exception("no mockup found for command '" + name + "'")); #ifdef OCCAMS_RAZOR used_commands.insert(name); #endif return it->second; } void Mockup::set_command(const string& name, const Command& command) { commands[name] = command; } void Mockup::erase_command(const string& name) { commands.erase(name); } bool Mockup::has_file(const string& name) { return files.find(name) != files.end(); } const Mockup::File& Mockup::get_file(const string& name) { map<string, File>::const_iterator it = files.find(name); if (it == files.end()) ST_THROW(Exception("no mockup found for file '" + name + "'")); #ifdef OCCAMS_RAZOR used_files.insert(name); #endif return it->second; } void Mockup::set_file(const string& name, const File& file) { files[name] = file; } void Mockup::erase_file(const string& name) { files.erase(name); } void Mockup::occams_razor() { #ifdef OCCAMS_RAZOR bool ok = true; for (const map<string, Command>::value_type& tmp : commands) { if (used_commands.count(tmp.first) == 0) { y2err("unused command mockup '" << tmp.first << "'"); ok = false; } } for (const map<string, File>::value_type& tmp : files) { if (used_files.count(tmp.first) == 0) { y2err("unused file mockup '" << tmp.first << "'"); ok = false; } } if (!ok) ST_THROW(Exception("Occam's Razor")); #endif } Mockup::Mode Mockup::mode = Mockup::Mode::NONE; map<string, Mockup::Command> Mockup::commands; map<string, Mockup::File> Mockup::files; #ifdef OCCAMS_RAZOR set<string> Mockup::used_commands; set<string> Mockup::used_files; #endif } <commit_msg>- check for duplicate entries in mockup files<commit_after>/* * Copyright (c) 2015 Novell, Inc. * Copyright (c) [2016-2019] SUSE LLC * * All Rights Reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of version 2 of the GNU General Public License as published * by the Free Software Foundation. * * 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, contact Novell, Inc. * * To contact Novell about this file by physical or electronic mail, you may * find current contact information at www.novell.com. */ #include "storage/Utils/Mockup.h" #include "storage/Utils/XmlFile.h" #include "storage/Utils/ExceptionImpl.h" #include "storage/Utils/LoggerImpl.h" #include "storage/Utils/Format.h" namespace storage { void Mockup::load(const string& filename) { XmlFile xml(filename); const xmlNode* root_node = xml.getRootElement(); if (!root_node) ST_THROW(Exception("root node not found")); const xmlNode* mockup_node = getChildNode(root_node, "Mockup"); if (!mockup_node) ST_THROW(Exception("Mockup node not found")); const xmlNode* commands_node = getChildNode(mockup_node, "Commands"); if (!commands_node) ST_THROW(Exception("Commands node not found")); for (const xmlNode* command_node : getChildNodes(commands_node)) { string name; getChildValue(command_node, "name", name); Command command; getChildValue(command_node, "stdout", command.stdout); getChildValue(command_node, "stderr", command.stderr); getChildValue(command_node, "exit-code", command.exit_code); if (!commands.emplace(name, command).second) ST_THROW(Exception(sformat("command \"%s\" already loaded for mockup", name))); } const xmlNode* files_node = getChildNode(mockup_node, "Files"); if (!files_node) ST_THROW(Exception("Files node not found")); for (const xmlNode* file_node : getChildNodes(files_node)) { string name; getChildValue(file_node, "name", name); File file; getChildValue(file_node, "content", file.content); if (!files.emplace(name, file).second) ST_THROW(Exception(sformat("file \"%s\" already loaded for mockup", name))); } } void Mockup::save(const string& filename) { XmlFile xml; xmlNode* mockup_node = xmlNewNode("Mockup"); xml.setRootElement(mockup_node); xmlNode* comment = xmlNewComment(string(" " + generated_string() + " ").c_str()); xmlAddPrevSibling(mockup_node, comment); xmlNode* commands_node = xmlNewChild(mockup_node, "Commands"); for (const map<string, Command>::value_type& it : commands) { xmlNode* command_node = xmlNewChild(commands_node, "Command"); setChildValue(command_node, "name", it.first); setChildValue(command_node, "stdout", it.second.stdout); setChildValue(command_node, "stderr", it.second.stderr); setChildValueIf(command_node, "exit-code", it.second.exit_code, it.second.exit_code != 0); } xmlNode* files_node = xmlNewChild(mockup_node, "Files"); for (const map<string, File>::value_type& it : files) { xmlNode* file_node = xmlNewChild(files_node, "File"); setChildValue(file_node, "name", it.first); setChildValue(file_node, "content", it.second.content); } xml.save(filename); } bool Mockup::has_command(const string& name) { return commands.find(name) != commands.end(); } const Mockup::Command& Mockup::get_command(const string& name) { map<string, Command>::const_iterator it = commands.find(name); if (it == commands.end()) ST_THROW(Exception("no mockup found for command '" + name + "'")); #ifdef OCCAMS_RAZOR used_commands.insert(name); #endif return it->second; } void Mockup::set_command(const string& name, const Command& command) { commands[name] = command; } void Mockup::erase_command(const string& name) { commands.erase(name); } bool Mockup::has_file(const string& name) { return files.find(name) != files.end(); } const Mockup::File& Mockup::get_file(const string& name) { map<string, File>::const_iterator it = files.find(name); if (it == files.end()) ST_THROW(Exception("no mockup found for file '" + name + "'")); #ifdef OCCAMS_RAZOR used_files.insert(name); #endif return it->second; } void Mockup::set_file(const string& name, const File& file) { files[name] = file; } void Mockup::erase_file(const string& name) { files.erase(name); } void Mockup::occams_razor() { #ifdef OCCAMS_RAZOR bool ok = true; for (const map<string, Command>::value_type& tmp : commands) { if (used_commands.count(tmp.first) == 0) { y2err("unused command mockup '" << tmp.first << "'"); ok = false; } } for (const map<string, File>::value_type& tmp : files) { if (used_files.count(tmp.first) == 0) { y2err("unused file mockup '" << tmp.first << "'"); ok = false; } } if (!ok) ST_THROW(Exception("Occam's Razor")); #endif } Mockup::Mode Mockup::mode = Mockup::Mode::NONE; map<string, Mockup::Command> Mockup::commands; map<string, Mockup::File> Mockup::files; #ifdef OCCAMS_RAZOR set<string> Mockup::used_commands; set<string> Mockup::used_files; #endif } <|endoftext|>
<commit_before>/** * This file defines the core graph analysis algorithm. */ #ifndef D2_ANALYSIS_HPP #define D2_ANALYSIS_HPP #include <d2/types.hpp> #include <boost/assert.hpp> #include <boost/concept_check.hpp> #include <boost/foreach.hpp> #include <boost/graph/depth_first_search.hpp> #include <boost/graph/graph_traits.hpp> #include <boost/graph/graph_utility.hpp> #include <boost/graph/one_bit_color_map.hpp> #include <boost/range/begin.hpp> #include <boost/range/end.hpp> #include <boost/unordered_map.hpp> #include <deque> #include <set> #include <vector> namespace boost { namespace graph { /** * Return whether vertex `v` is reachable from vertex `u`. * @note This is an extension to the existing `is_reachable`, which * requires passing a property map. */ template <typename Graph> bool is_reachable(typename graph_traits<Graph>::vertex_descriptor u, typename graph_traits<Graph>::vertex_descriptor v, Graph const& g) { one_bit_color_map<> map(num_vertices(g)); return is_reachable(u, v, g, map); } } // end namespace graph } // end namespace boost namespace d2 { namespace detail { // Note: You can enable/disable this to debug the algorithm. #define D2_DEBUG_ALL_CYCLES_DUMB(statement) do { } while (false) // #define D2_DEBUG_ALL_CYCLES_DUMB(statement) do { statement; } while (false) /** * Wrapper visitor for use within the `all_cycles_dumb` algorith. It allows * the wrapped visitor to keep the same interface as for `tiernan_all_cycles`. */ template <typename Adapted, typename Graph> class all_cycles_dumb_wrapper : public boost::dfs_visitor<> { Adapted visitor_; typedef typename boost::graph_traits<Graph>::edge_descriptor Edge; typedef typename boost::graph_traits<Graph>::vertex_descriptor Vertex; typedef boost::unordered_map<Vertex, Edge> PredecessorMap; PredecessorMap predecessors_; std::set<std::deque<Edge> >& seen_cycles; public: explicit all_cycles_dumb_wrapper(Adapted const& v, Graph const&, std::set<std::deque<Edge> >& seen) : visitor_(v), seen_cycles(seen) { } void tree_edge(Edge e, Graph const& g) { D2_DEBUG_ALL_CYCLES_DUMB(std::cout << "tree edge: " << e << '\n' << "set predecessor of " << target(e, g) << " to " << e << '\n'); predecessors_[target(e, g)] = e; } void back_edge(Edge e, Graph const& g) { D2_DEBUG_ALL_CYCLES_DUMB(std::cout << "back edge: " << e << '\n' << "making sure " << source(e, g) << " has a predecessor\n"); BOOST_ASSERT_MSG( predecessors_.find(source(e,g)) != boost::end(predecessors_), "the predecessor edge of the source of the current edge is not " "defined, something's wrong"); // Using the predecessor map maintained by the // edge_predecessor_recorder, we create a path of the form: // (u, v) (v, w) (w, x) ... // Representing the edges forming the cycle. We then call the adapted // visitor with that path, which is much easier to manipulate. std::deque<Edge> cycle; cycle.push_front(e); typedef typename PredecessorMap::const_iterator PredecessorIterator; while (true) { PredecessorIterator it = predecessors_.find(source(e, g)); if (it == boost::end(predecessors_)) break; cycle.push_front(e = it->second); } // Since it is possible to have several connected components in the // graph, we must make sure we do not call the visitor with redundant // cycles that were already found in a previous search. if (seen_cycles.insert(cycle).second) visitor_.cycle(cycle, g); } }; /** * Bad algorithm to compute all the cycles in a graph. It first does a depth * first search and detects the cycles in the graph. Then, it starts over a * depth first search at each vertex implicated in a cycle found during the * first pass. */ template <typename Graph, typename Visitor> void all_cycles_dumb(Graph const& g, Visitor const& vis) { typedef typename boost::graph_traits<Graph>::vertex_descriptor Vertex; typedef typename boost::graph_traits<Graph>::vertex_iterator VertexIter; typedef typename boost::graph_traits<Graph>::edge_descriptor Edge; std::set<std::deque<Edge> > seen_cycles; all_cycles_dumb_wrapper<Visitor, Graph> wrapper(vis, g, seen_cycles); VertexIter first, last; boost::tie(first, last) = vertices(g); boost::depth_first_search(g, boost::root_vertex(*first).visitor(wrapper)); // Find all vertices implicated in cycles. std::set<Vertex> hot_vertices; BOOST_FOREACH(std::deque<Edge> const& cycle, seen_cycles) { hot_vertices.insert(source(cycle[0], g)); BOOST_FOREACH(Edge const& edge, cycle) hot_vertices.insert(target(edge, g)); } // Start over a depth-first search at every vertex implicated in a cycle. // This allows us to find all the different cycles in the directed graph. // Let's say the first dfs found a->b->a; // the subsequent searches will find b->a->b hot_vertices.erase(*first); // We already visited that. BOOST_FOREACH(Vertex v, hot_vertices) boost::depth_first_search(g, boost::root_vertex(v).visitor(wrapper)); } /** * Return whether two unordered containers have a non-empty intersection. */ template <typename Unordered1, typename Unordered2> bool unordered_intersects(Unordered1 const& a, Unordered2 const& b) { typedef typename Unordered1::const_iterator Iterator; typename Unordered2::const_iterator not_found(boost::end(b)); Iterator elem(boost::begin(a)), last(boost::end(a)); for (; elem != last; ++elem) if (b.find(*elem) == not_found) return false; return true; } /** * Wrap a `BinaryFunction` to implement a visitor for the goodlock algorithm. * @todo If we use an adjacency_matrix to store the segmentation graph, we * should compute its transitive closure to reduce the complexity of * the happens-before relation. */ template <typename LockGraph, typename SegmentationGraph, typename Function> class cycle_visitor { typedef typename boost::graph_traits<LockGraph>::edge_descriptor LockGraphEdgeDescriptor; typedef typename boost::graph_traits<LockGraph>::vertex_descriptor LockGraphVertexDescriptor; typedef std::vector<LockGraphEdgeDescriptor> EdgePath; // Property map to access the edge labels of the lock graph. typedef typename boost::property_map<LockGraph, boost::edge_bundle_t>::const_type EdgeLabelMap; SegmentationGraph const& sg_; Function& f_; /** * Return whether segment `u` happens before segment `v` according to * the segmentation graph. */ bool happens_before(Segment u, Segment v) const { return boost::graph::is_reachable(u, v, sg_); } public: cycle_visitor(SegmentationGraph const& sg, Function& f) : sg_(sg), f_(f) { } /** * Function called by `tiernan_all_cycles` whenever a cycle is found. * It calls the wrapped function with a sequence containing the edges * in the cycle and a constant reference to the lock graph, but only if * the cycle respects certain conditions, i.e. if the cycle represents a * deadlock in the lock graph. */ template <typename EdgePath> void cycle(EdgePath const& edge_path, LockGraph const& graph) const { D2_DEBUG_ALL_CYCLES_DUMB( std::cout << "Found cycle: "; std::copy(boost::begin(edge_path), boost::end(edge_path), std::ostream_iterator<typename EdgePath::value_type>( std::cout, " ")); std::cout << '\n'; ); // For any given pair of edges (e1, e2) EdgeLabelMap labels = get(boost::edge_bundle, graph); BOOST_FOREACH(LockGraphEdgeDescriptor e1, edge_path) { BOOST_FOREACH(LockGraphEdgeDescriptor e2, edge_path) { if (e1 == e2) continue; else if (!( // The threads must differ. labels[e1].t != labels[e2].t && // The guard sets must not overlap. !unordered_intersects(labels[e1].g, labels[e2].g) && // The segments must not be ordered. !happens_before(labels[e1].s2, labels[e2].s1) )) return; } } f_(edge_path, graph); } }; } // end namespace detail /** * Analyze the lock graph and the segmentation graph to determine whether the * program execution represented by them contains a deadlock. `f` is called * whenever a potential deadlock is detected. * @see `detail::cycle_visitor` for more details. */ template <typename LockGraph, typename SegmentationGraph, typename Function> void analyze(LockGraph const& lg, SegmentationGraph const& sg, Function f) { BOOST_CONCEPT_ASSERT((LockGraphConcept<LockGraph>)); detail::cycle_visitor<LockGraph, SegmentationGraph, Function> vis(sg, f); detail::all_cycles_dumb(lg, vis); } } // end namespace d2 #endif // !D2_ANALYSIS_HPP <commit_msg>Correct outdated comment.<commit_after>/** * This file defines the core graph analysis algorithm. */ #ifndef D2_ANALYSIS_HPP #define D2_ANALYSIS_HPP #include <d2/types.hpp> #include <boost/assert.hpp> #include <boost/concept_check.hpp> #include <boost/foreach.hpp> #include <boost/graph/depth_first_search.hpp> #include <boost/graph/graph_traits.hpp> #include <boost/graph/graph_utility.hpp> #include <boost/graph/one_bit_color_map.hpp> #include <boost/range/begin.hpp> #include <boost/range/end.hpp> #include <boost/unordered_map.hpp> #include <deque> #include <set> #include <vector> namespace boost { namespace graph { /** * Return whether vertex `v` is reachable from vertex `u`. * @note This is an extension to the existing `is_reachable`, which * requires passing a property map. */ template <typename Graph> bool is_reachable(typename graph_traits<Graph>::vertex_descriptor u, typename graph_traits<Graph>::vertex_descriptor v, Graph const& g) { one_bit_color_map<> map(num_vertices(g)); return is_reachable(u, v, g, map); } } // end namespace graph } // end namespace boost namespace d2 { namespace detail { // Note: You can enable/disable this to debug the algorithm. #define D2_DEBUG_ALL_CYCLES_DUMB(statement) do { } while (false) // #define D2_DEBUG_ALL_CYCLES_DUMB(statement) do { statement; } while (false) /** * Wrapper visitor for use within the `all_cycles_dumb` algorith. It allows * the wrapped visitor to keep the same interface as for `tiernan_all_cycles`. */ template <typename Adapted, typename Graph> class all_cycles_dumb_wrapper : public boost::dfs_visitor<> { Adapted visitor_; typedef typename boost::graph_traits<Graph>::edge_descriptor Edge; typedef typename boost::graph_traits<Graph>::vertex_descriptor Vertex; typedef boost::unordered_map<Vertex, Edge> PredecessorMap; PredecessorMap predecessors_; std::set<std::deque<Edge> >& seen_cycles; public: explicit all_cycles_dumb_wrapper(Adapted const& v, Graph const&, std::set<std::deque<Edge> >& seen) : visitor_(v), seen_cycles(seen) { } void tree_edge(Edge e, Graph const& g) { D2_DEBUG_ALL_CYCLES_DUMB(std::cout << "tree edge: " << e << '\n' << "set predecessor of " << target(e, g) << " to " << e << '\n'); predecessors_[target(e, g)] = e; } void back_edge(Edge e, Graph const& g) { D2_DEBUG_ALL_CYCLES_DUMB(std::cout << "back edge: " << e << '\n' << "making sure " << source(e, g) << " has a predecessor\n"); BOOST_ASSERT_MSG( predecessors_.find(source(e,g)) != boost::end(predecessors_), "the predecessor edge of the source of the current edge is not " "defined, something's wrong"); // Using the predecessor map maintained by the // edge_predecessor_recorder, we create a path of the form: // (u, v) (v, w) (w, x) ... // Representing the edges forming the cycle. We then call the adapted // visitor with that path, which is much easier to manipulate. std::deque<Edge> cycle; cycle.push_front(e); typedef typename PredecessorMap::const_iterator PredecessorIterator; while (true) { PredecessorIterator it = predecessors_.find(source(e, g)); if (it == boost::end(predecessors_)) break; cycle.push_front(e = it->second); } // Since it is possible to have several connected components in the // graph, we must make sure we do not call the visitor with redundant // cycles that were already found in a previous search. if (seen_cycles.insert(cycle).second) visitor_.cycle(cycle, g); } }; /** * Bad algorithm to compute all the cycles in a graph. It first does a depth * first search and detects the cycles in the graph. Then, it starts over a * depth first search at each vertex implicated in a cycle found during the * first pass. */ template <typename Graph, typename Visitor> void all_cycles_dumb(Graph const& g, Visitor const& vis) { typedef typename boost::graph_traits<Graph>::vertex_descriptor Vertex; typedef typename boost::graph_traits<Graph>::vertex_iterator VertexIter; typedef typename boost::graph_traits<Graph>::edge_descriptor Edge; std::set<std::deque<Edge> > seen_cycles; all_cycles_dumb_wrapper<Visitor, Graph> wrapper(vis, g, seen_cycles); VertexIter first, last; boost::tie(first, last) = vertices(g); boost::depth_first_search(g, boost::root_vertex(*first).visitor(wrapper)); // Find all vertices implicated in cycles. std::set<Vertex> hot_vertices; BOOST_FOREACH(std::deque<Edge> const& cycle, seen_cycles) { hot_vertices.insert(source(cycle[0], g)); BOOST_FOREACH(Edge const& edge, cycle) hot_vertices.insert(target(edge, g)); } // Start over a depth-first search at every vertex implicated in a cycle. // This allows us to find all the different cycles in the directed graph. // Let's say the first dfs found a->b->a; // the subsequent searches will find b->a->b hot_vertices.erase(*first); // We already visited that. BOOST_FOREACH(Vertex v, hot_vertices) boost::depth_first_search(g, boost::root_vertex(v).visitor(wrapper)); } /** * Return whether two unordered containers have a non-empty intersection. */ template <typename Unordered1, typename Unordered2> bool unordered_intersects(Unordered1 const& a, Unordered2 const& b) { typedef typename Unordered1::const_iterator Iterator; typename Unordered2::const_iterator not_found(boost::end(b)); Iterator elem(boost::begin(a)), last(boost::end(a)); for (; elem != last; ++elem) if (b.find(*elem) == not_found) return false; return true; } /** * Wrap a `BinaryFunction` to implement a visitor for the goodlock algorithm. * @todo If we use an adjacency_matrix to store the segmentation graph, we * should compute its transitive closure to reduce the complexity of * the happens-before relation. */ template <typename LockGraph, typename SegmentationGraph, typename Function> class cycle_visitor { typedef typename boost::graph_traits<LockGraph>::edge_descriptor LockGraphEdgeDescriptor; typedef typename boost::graph_traits<LockGraph>::vertex_descriptor LockGraphVertexDescriptor; typedef std::vector<LockGraphEdgeDescriptor> EdgePath; // Property map to access the edge labels of the lock graph. typedef typename boost::property_map<LockGraph, boost::edge_bundle_t>::const_type EdgeLabelMap; SegmentationGraph const& sg_; Function& f_; /** * Return whether segment `u` happens before segment `v` according to * the segmentation graph. */ bool happens_before(Segment u, Segment v) const { return boost::graph::is_reachable(u, v, sg_); } public: cycle_visitor(SegmentationGraph const& sg, Function& f) : sg_(sg), f_(f) { } /** * Function called whenever a cycle is found. It calls the wrapped * function with a sequence containing the edges in the cycle and a * constant reference to the lock graph, but only if the cycle respects * certain conditions, i.e. if the cycle represents a deadlock in the * lock graph. */ template <typename EdgePath> void cycle(EdgePath const& edge_path, LockGraph const& graph) const { D2_DEBUG_ALL_CYCLES_DUMB( std::cout << "Found cycle: "; std::copy(boost::begin(edge_path), boost::end(edge_path), std::ostream_iterator<typename EdgePath::value_type>( std::cout, " ")); std::cout << '\n'; ); // For any given pair of edges (e1, e2) EdgeLabelMap labels = get(boost::edge_bundle, graph); BOOST_FOREACH(LockGraphEdgeDescriptor e1, edge_path) { BOOST_FOREACH(LockGraphEdgeDescriptor e2, edge_path) { if (e1 == e2) continue; else if (!( // The threads must differ. labels[e1].t != labels[e2].t && // The guard sets must not overlap. !unordered_intersects(labels[e1].g, labels[e2].g) && // The segments must not be ordered. !happens_before(labels[e1].s2, labels[e2].s1) )) return; } } f_(edge_path, graph); } }; } // end namespace detail /** * Analyze the lock graph and the segmentation graph to determine whether the * program execution represented by them contains a deadlock. `f` is called * whenever a potential deadlock is detected. * @see `detail::cycle_visitor` for more details. */ template <typename LockGraph, typename SegmentationGraph, typename Function> void analyze(LockGraph const& lg, SegmentationGraph const& sg, Function f) { BOOST_CONCEPT_ASSERT((LockGraphConcept<LockGraph>)); detail::cycle_visitor<LockGraph, SegmentationGraph, Function> vis(sg, f); detail::all_cycles_dumb(lg, vis); } } // end namespace d2 #endif // !D2_ANALYSIS_HPP <|endoftext|>
<commit_before>// Scintilla source code edit control /** @file KeyMap.cxx ** Defines a mapping between keystrokes and commands. **/ // Copyright 1998-2003 by Neil Hodgson <neilh@scintilla.org> // The License.txt file describes the conditions under which this software may be distributed. #include "Platform.h" #include "Scintilla.h" #include "KeyMap.h" KeyMap::KeyMap() : kmap(0), len(0), alloc(0) { for (int i = 0; MapDefault[i].key; i++) { AssignCmdKey(MapDefault[i].key, MapDefault[i].modifiers, MapDefault[i].msg); } } KeyMap::~KeyMap() { Clear(); } void KeyMap::Clear() { delete []kmap; kmap = 0; len = 0; alloc = 0; } void KeyMap::AssignCmdKey(int key, int modifiers, unsigned int msg) { if ((len+1) >= alloc) { KeyToCommand *ktcNew = new KeyToCommand[alloc + 5]; if (!ktcNew) return; for (int k = 0; k < len; k++) ktcNew[k] = kmap[k]; alloc += 5; delete []kmap; kmap = ktcNew; } for (int keyIndex = 0; keyIndex < len; keyIndex++) { if ((key == kmap[keyIndex].key) && (modifiers == kmap[keyIndex].modifiers)) { kmap[keyIndex].msg = msg; return; } } kmap[len].key = key; kmap[len].modifiers = modifiers; kmap[len].msg = msg; len++; } unsigned int KeyMap::Find(int key, int modifiers) { for (int i = 0; i < len; i++) { if ((key == kmap[i].key) && (modifiers == kmap[i].modifiers)) { return kmap[i].msg; } } return 0; } const KeyToCommand KeyMap::MapDefault[] = { {SCK_DOWN, SCI_NORM, SCI_LINEDOWN}, {SCK_DOWN, SCI_SHIFT, SCI_LINEDOWNEXTEND}, {SCK_DOWN, SCI_CTRL, SCI_LINESCROLLDOWN}, {SCK_DOWN, SCI_ALT, SCI_PARADOWN}, // {SCK_DOWN, SCI_ASHIFT, SCI_PARADOWNEXTEND}, {SCK_DOWN, SCI_ASHIFT, SCI_LINEDOWNRECTEXTEND}, {SCK_UP, SCI_NORM, SCI_LINEUP}, {SCK_UP, SCI_SHIFT, SCI_LINEUPEXTEND}, {SCK_UP, SCI_CTRL, SCI_LINESCROLLUP}, {SCK_UP, SCI_ALT, SCI_PARAUP}, // {SCK_UP, SCI_ASHIFT, SCI_PARAUPEXTEND}, {SCK_UP, SCI_ASHIFT, SCI_LINEUPRECTEXTEND}, {SCK_LEFT, SCI_NORM, SCI_CHARLEFT}, {SCK_LEFT, SCI_SHIFT, SCI_CHARLEFTEXTEND}, {SCK_LEFT, SCI_CTRL, SCI_WORDLEFT}, {SCK_LEFT, SCI_CSHIFT, SCI_WORDLEFTEXTEND}, {SCK_LEFT, SCI_ALT, SCI_WORDPARTLEFT}, // {SCK_LEFT, SCI_ASHIFT, SCI_WORDPARTLEFTEXTEND}, {SCK_LEFT, SCI_ASHIFT, SCI_CHARLEFTRECTEXTEND}, {SCK_RIGHT, SCI_NORM, SCI_CHARRIGHT}, {SCK_RIGHT, SCI_SHIFT, SCI_CHARRIGHTEXTEND}, {SCK_RIGHT, SCI_CTRL, SCI_WORDRIGHT}, {SCK_RIGHT, SCI_CSHIFT, SCI_WORDRIGHTEXTEND}, {SCK_RIGHT, SCI_ALT, SCI_WORDPARTRIGHT}, // {SCK_RIGHT, SCI_ASHIFT, SCI_WORDPARTRIGHTEXTEND}, {SCK_RIGHT, SCI_ASHIFT, SCI_CHARRIGHTRECTEXTEND}, {SCK_HOME, SCI_NORM, SCI_VCHOME}, {SCK_HOME, SCI_SHIFT, SCI_VCHOMEEXTEND}, {SCK_HOME, SCI_CTRL, SCI_DOCUMENTSTART}, {SCK_HOME, SCI_CSHIFT, SCI_DOCUMENTSTARTEXTEND}, {SCK_HOME, SCI_ALT, SCI_HOMEDISPLAY}, // {SCK_HOME, SCI_ASHIFT, SCI_HOMEDISPLAYEXTEND}, {SCK_HOME, SCI_ASHIFT, SCI_VCHOMERECTEXTEND}, {SCK_END, SCI_NORM, SCI_LINEEND}, {SCK_END, SCI_SHIFT, SCI_LINEENDEXTEND}, {SCK_END, SCI_CTRL, SCI_DOCUMENTEND}, {SCK_END, SCI_CSHIFT, SCI_DOCUMENTENDEXTEND}, {SCK_END, SCI_ALT, SCI_LINEENDDISPLAY}, // {SCK_END, SCI_ASHIFT, SCI_LINEENDDISPLAYEXTEND}, {SCK_END, SCI_ASHIFT, SCI_LINEENDRECTEXTEND}, {SCK_PRIOR, SCI_NORM, SCI_PAGEUP}, {SCK_PRIOR, SCI_SHIFT, SCI_PAGEUPEXTEND}, {SCK_PRIOR, SCI_ASHIFT, SCI_PAGEUPRECTEXTEND}, {SCK_NEXT, SCI_NORM, SCI_PAGEDOWN}, {SCK_NEXT, SCI_SHIFT, SCI_PAGEDOWNEXTEND}, {SCK_NEXT, SCI_ASHIFT, SCI_PAGEDOWNRECTEXTEND}, {SCK_DELETE, SCI_NORM, SCI_CLEAR}, {SCK_DELETE, SCI_SHIFT, SCI_CUT}, {SCK_DELETE, SCI_CTRL, SCI_DELWORDRIGHT}, {SCK_DELETE, SCI_CSHIFT, SCI_DELLINERIGHT}, {SCK_INSERT, SCI_NORM, SCI_EDITTOGGLEOVERTYPE}, {SCK_INSERT, SCI_SHIFT, SCI_PASTE}, {SCK_INSERT, SCI_CTRL, SCI_COPY}, {SCK_ESCAPE, SCI_NORM, SCI_CANCEL}, {SCK_BACK, SCI_NORM, SCI_DELETEBACK}, {SCK_BACK, SCI_SHIFT, SCI_DELETEBACK}, {SCK_BACK, SCI_CTRL, SCI_DELWORDLEFT}, {SCK_BACK, SCI_ALT, SCI_UNDO}, {SCK_BACK, SCI_CSHIFT, SCI_DELLINELEFT}, {'Z', SCI_CTRL, SCI_UNDO}, {'Y', SCI_CTRL, SCI_REDO}, {'X', SCI_CTRL, SCI_CUT}, {'C', SCI_CTRL, SCI_COPY}, {'V', SCI_CTRL, SCI_PASTE}, {'A', SCI_CTRL, SCI_SELECTALL}, {SCK_TAB, SCI_NORM, SCI_TAB}, {SCK_TAB, SCI_SHIFT, SCI_BACKTAB}, {SCK_RETURN, SCI_NORM, SCI_NEWLINE}, {SCK_RETURN, SCI_SHIFT, SCI_NEWLINE}, {SCK_ADD, SCI_CTRL, SCI_ZOOMIN}, {SCK_SUBTRACT, SCI_CTRL, SCI_ZOOMOUT}, {SCK_DIVIDE, SCI_CTRL, SCI_SETZOOM}, //'L', SCI_CTRL, SCI_FORMFEED, {'L', SCI_CTRL, SCI_LINECUT}, {'L', SCI_CSHIFT, SCI_LINEDELETE}, {'T', SCI_CSHIFT, SCI_LINECOPY}, {'T', SCI_CTRL, SCI_LINETRANSPOSE}, {'D', SCI_CTRL, SCI_LINEDUPLICATE}, {'U', SCI_CTRL, SCI_LOWERCASE}, {'U', SCI_CSHIFT, SCI_UPPERCASE}, {0,0,0}, }; <commit_msg>Added key bindings to key map for functions displaced by rectangular selection.<commit_after>// Scintilla source code edit control /** @file KeyMap.cxx ** Defines a mapping between keystrokes and commands. **/ // Copyright 1998-2003 by Neil Hodgson <neilh@scintilla.org> // The License.txt file describes the conditions under which this software may be distributed. #include "Platform.h" #include "Scintilla.h" #include "KeyMap.h" KeyMap::KeyMap() : kmap(0), len(0), alloc(0) { for (int i = 0; MapDefault[i].key; i++) { AssignCmdKey(MapDefault[i].key, MapDefault[i].modifiers, MapDefault[i].msg); } } KeyMap::~KeyMap() { Clear(); } void KeyMap::Clear() { delete []kmap; kmap = 0; len = 0; alloc = 0; } void KeyMap::AssignCmdKey(int key, int modifiers, unsigned int msg) { if ((len+1) >= alloc) { KeyToCommand *ktcNew = new KeyToCommand[alloc + 5]; if (!ktcNew) return; for (int k = 0; k < len; k++) ktcNew[k] = kmap[k]; alloc += 5; delete []kmap; kmap = ktcNew; } for (int keyIndex = 0; keyIndex < len; keyIndex++) { if ((key == kmap[keyIndex].key) && (modifiers == kmap[keyIndex].modifiers)) { kmap[keyIndex].msg = msg; return; } } kmap[len].key = key; kmap[len].modifiers = modifiers; kmap[len].msg = msg; len++; } unsigned int KeyMap::Find(int key, int modifiers) { for (int i = 0; i < len; i++) { if ((key == kmap[i].key) && (modifiers == kmap[i].modifiers)) { return kmap[i].msg; } } return 0; } const KeyToCommand KeyMap::MapDefault[] = { {SCK_DOWN, SCI_NORM, SCI_LINEDOWN}, {SCK_DOWN, SCI_SHIFT, SCI_LINEDOWNEXTEND}, {SCK_DOWN, SCI_CTRL, SCI_LINESCROLLDOWN}, {SCK_DOWN, SCI_ASHIFT, SCI_LINEDOWNRECTEXTEND}, {SCK_UP, SCI_NORM, SCI_LINEUP}, {SCK_UP, SCI_SHIFT, SCI_LINEUPEXTEND}, {SCK_UP, SCI_CTRL, SCI_LINESCROLLUP}, {SCK_UP, SCI_ASHIFT, SCI_LINEUPRECTEXTEND}, {'[', SCI_CTRL, SCI_PARAUP}, {'[', SCI_CSHIFT, SCI_PARAUPEXTEND}, {']', SCI_CTRL, SCI_PARADOWN}, {']', SCI_CSHIFT, SCI_PARADOWNEXTEND}, {SCK_LEFT, SCI_NORM, SCI_CHARLEFT}, {SCK_LEFT, SCI_SHIFT, SCI_CHARLEFTEXTEND}, {SCK_LEFT, SCI_CTRL, SCI_WORDLEFT}, {SCK_LEFT, SCI_CSHIFT, SCI_WORDLEFTEXTEND}, {SCK_LEFT, SCI_ASHIFT, SCI_CHARLEFTRECTEXTEND}, {SCK_RIGHT, SCI_NORM, SCI_CHARRIGHT}, {SCK_RIGHT, SCI_SHIFT, SCI_CHARRIGHTEXTEND}, {SCK_RIGHT, SCI_CTRL, SCI_WORDRIGHT}, {SCK_RIGHT, SCI_CSHIFT, SCI_WORDRIGHTEXTEND}, {SCK_RIGHT, SCI_ASHIFT, SCI_CHARRIGHTRECTEXTEND}, {'/', SCI_CTRL, SCI_WORDPARTLEFT}, {'/', SCI_CSHIFT, SCI_WORDPARTLEFTEXTEND}, {'\\', SCI_CTRL, SCI_WORDPARTRIGHT}, {'\\', SCI_CSHIFT, SCI_WORDPARTRIGHTEXTEND}, {SCK_HOME, SCI_NORM, SCI_VCHOME}, {SCK_HOME, SCI_SHIFT, SCI_VCHOMEEXTEND}, {SCK_HOME, SCI_CTRL, SCI_DOCUMENTSTART}, {SCK_HOME, SCI_CSHIFT, SCI_DOCUMENTSTARTEXTEND}, {SCK_HOME, SCI_ALT, SCI_HOMEDISPLAY}, // {SCK_HOME, SCI_ASHIFT, SCI_HOMEDISPLAYEXTEND}, {SCK_HOME, SCI_ASHIFT, SCI_VCHOMERECTEXTEND}, {SCK_END, SCI_NORM, SCI_LINEEND}, {SCK_END, SCI_SHIFT, SCI_LINEENDEXTEND}, {SCK_END, SCI_CTRL, SCI_DOCUMENTEND}, {SCK_END, SCI_CSHIFT, SCI_DOCUMENTENDEXTEND}, {SCK_END, SCI_ALT, SCI_LINEENDDISPLAY}, // {SCK_END, SCI_ASHIFT, SCI_LINEENDDISPLAYEXTEND}, {SCK_END, SCI_ASHIFT, SCI_LINEENDRECTEXTEND}, {SCK_PRIOR, SCI_NORM, SCI_PAGEUP}, {SCK_PRIOR, SCI_SHIFT, SCI_PAGEUPEXTEND}, {SCK_PRIOR, SCI_ASHIFT, SCI_PAGEUPRECTEXTEND}, {SCK_NEXT, SCI_NORM, SCI_PAGEDOWN}, {SCK_NEXT, SCI_SHIFT, SCI_PAGEDOWNEXTEND}, {SCK_NEXT, SCI_ASHIFT, SCI_PAGEDOWNRECTEXTEND}, {SCK_DELETE, SCI_NORM, SCI_CLEAR}, {SCK_DELETE, SCI_SHIFT, SCI_CUT}, {SCK_DELETE, SCI_CTRL, SCI_DELWORDRIGHT}, {SCK_DELETE, SCI_CSHIFT, SCI_DELLINERIGHT}, {SCK_INSERT, SCI_NORM, SCI_EDITTOGGLEOVERTYPE}, {SCK_INSERT, SCI_SHIFT, SCI_PASTE}, {SCK_INSERT, SCI_CTRL, SCI_COPY}, {SCK_ESCAPE, SCI_NORM, SCI_CANCEL}, {SCK_BACK, SCI_NORM, SCI_DELETEBACK}, {SCK_BACK, SCI_SHIFT, SCI_DELETEBACK}, {SCK_BACK, SCI_CTRL, SCI_DELWORDLEFT}, {SCK_BACK, SCI_ALT, SCI_UNDO}, {SCK_BACK, SCI_CSHIFT, SCI_DELLINELEFT}, {'Z', SCI_CTRL, SCI_UNDO}, {'Y', SCI_CTRL, SCI_REDO}, {'X', SCI_CTRL, SCI_CUT}, {'C', SCI_CTRL, SCI_COPY}, {'V', SCI_CTRL, SCI_PASTE}, {'A', SCI_CTRL, SCI_SELECTALL}, {SCK_TAB, SCI_NORM, SCI_TAB}, {SCK_TAB, SCI_SHIFT, SCI_BACKTAB}, {SCK_RETURN, SCI_NORM, SCI_NEWLINE}, {SCK_RETURN, SCI_SHIFT, SCI_NEWLINE}, {SCK_ADD, SCI_CTRL, SCI_ZOOMIN}, {SCK_SUBTRACT, SCI_CTRL, SCI_ZOOMOUT}, {SCK_DIVIDE, SCI_CTRL, SCI_SETZOOM}, //'L', SCI_CTRL, SCI_FORMFEED, {'L', SCI_CTRL, SCI_LINECUT}, {'L', SCI_CSHIFT, SCI_LINEDELETE}, {'T', SCI_CSHIFT, SCI_LINECOPY}, {'T', SCI_CTRL, SCI_LINETRANSPOSE}, {'D', SCI_CTRL, SCI_LINEDUPLICATE}, {'U', SCI_CTRL, SCI_LOWERCASE}, {'U', SCI_CSHIFT, SCI_UPPERCASE}, {0,0,0}, }; <|endoftext|>
<commit_before>//-----------------------------------------------------------------------bl- //-------------------------------------------------------------------------- // // GRINS - General Reacting Incompressible Navier-Stokes // // Copyright (C) 2014-2015 Paul T. Bauman, Roy H. Stogner // Copyright (C) 2010-2013 The PECOS Development Team // // This library is free software; you can redistribute it and/or // modify it under the terms of the Version 2.1 GNU Lesser General // Public License 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. 51 Franklin Street, Fifth Floor, // Boston, MA 02110-1301 USA // //-----------------------------------------------------------------------el- // This class #include "grins/physics_factory_heat_transfer.h" // GRINS #include "grins/physics_factory_helper.h" #include "grins/constant_conductivity.h" #include "grins/parsed_conductivity.h" // Physics we're instantiating #include "grins/heat_conduction.h" #include "grins/heat_transfer.h" #include "grins/heat_transfer_adjoint_stab.h" #include "grins/heat_transfer_spgsm_stab.h" #include "grins/axisym_heat_transfer.h" namespace GRINS { template<template<typename> class DerivedPhysics> libMesh::UniquePtr<Physics> PhysicsFactoryHeatTransfer<DerivedPhysics>::build_physics( const GetPot& input, const std::string& physics_name ) { std::string core_physics = this->find_core_physics_name(physics_name); std::string conductivity; PhysicsFactoryHelper::parse_conductivity_model(input,core_physics,conductivity); libMesh::UniquePtr<Physics> new_physics; if( conductivity == "constant" ) new_physics.reset( new DerivedPhysics<ConstantConductivity>(physics_name,input) ); else if( conductivity == "parsed" ) new_physics.reset( new DerivedPhysics<ParsedConductivity>(physics_name,input) ); else this->cond_error_msg(physics_name, conductivity); libmesh_assert(new_physics); return new_physics; } template<template<typename> class DerivedPhysics> void PhysicsFactoryHeatTransfer<DerivedPhysics>::cond_error_msg( const std::string& physics, const std::string& conductivity ) const { std::string error = "================================================================\n"; error += "Invalid conductivity model for "+physics+"\n"; error += "Conductivity model = "+conductivity+"\n"; error += "================================================================\n"; libmesh_error_msg(error); } PhysicsFactoryHeatTransfer<HeatConduction> grins_factory_heat_conduction (PhysicsNaming::heat_conduction(),PhysicsNaming::heat_conduction()); PhysicsFactoryHeatTransfer<HeatTransfer> grins_factory_heat_transfer (PhysicsNaming::heat_transfer(),PhysicsNaming::heat_transfer()); PhysicsFactoryHeatTransfer<HeatTransferAdjointStabilization> grins_factory_heat_transfer_adjoint_stab (PhysicsNaming::heat_transfer_adjoint_stab(),PhysicsNaming::heat_transfer()); PhysicsFactoryHeatTransfer<HeatTransferAdjointStabilization> grins_factory_heat_transfer_spgsm_stab (PhysicsNaming::heat_transfer_spgsm_stab(),PhysicsNaming::heat_transfer()); // This needs to die. Axisymmetry should be handled within heat_transfer PhysicsFactoryHeatTransfer<AxisymmetricHeatTransfer> grins_factory_axi_heat_transfer (PhysicsNaming::axisymmetric_heat_transfer(),PhysicsNaming::heat_transfer()); } // end namespace GRINS <commit_msg>Fix copy-paste error in HeatTransferPhysicsFactory<commit_after>//-----------------------------------------------------------------------bl- //-------------------------------------------------------------------------- // // GRINS - General Reacting Incompressible Navier-Stokes // // Copyright (C) 2014-2015 Paul T. Bauman, Roy H. Stogner // Copyright (C) 2010-2013 The PECOS Development Team // // This library is free software; you can redistribute it and/or // modify it under the terms of the Version 2.1 GNU Lesser General // Public License 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. 51 Franklin Street, Fifth Floor, // Boston, MA 02110-1301 USA // //-----------------------------------------------------------------------el- // This class #include "grins/physics_factory_heat_transfer.h" // GRINS #include "grins/physics_factory_helper.h" #include "grins/constant_conductivity.h" #include "grins/parsed_conductivity.h" // Physics we're instantiating #include "grins/heat_conduction.h" #include "grins/heat_transfer.h" #include "grins/heat_transfer_adjoint_stab.h" #include "grins/heat_transfer_spgsm_stab.h" #include "grins/axisym_heat_transfer.h" namespace GRINS { template<template<typename> class DerivedPhysics> libMesh::UniquePtr<Physics> PhysicsFactoryHeatTransfer<DerivedPhysics>::build_physics( const GetPot& input, const std::string& physics_name ) { std::string core_physics = this->find_core_physics_name(physics_name); std::string conductivity; PhysicsFactoryHelper::parse_conductivity_model(input,core_physics,conductivity); libMesh::UniquePtr<Physics> new_physics; if( conductivity == "constant" ) new_physics.reset( new DerivedPhysics<ConstantConductivity>(physics_name,input) ); else if( conductivity == "parsed" ) new_physics.reset( new DerivedPhysics<ParsedConductivity>(physics_name,input) ); else this->cond_error_msg(physics_name, conductivity); libmesh_assert(new_physics); return new_physics; } template<template<typename> class DerivedPhysics> void PhysicsFactoryHeatTransfer<DerivedPhysics>::cond_error_msg( const std::string& physics, const std::string& conductivity ) const { std::string error = "================================================================\n"; error += "Invalid conductivity model for "+physics+"\n"; error += "Conductivity model = "+conductivity+"\n"; error += "================================================================\n"; libmesh_error_msg(error); } PhysicsFactoryHeatTransfer<HeatConduction> grins_factory_heat_conduction (PhysicsNaming::heat_conduction(),PhysicsNaming::heat_conduction()); PhysicsFactoryHeatTransfer<HeatTransfer> grins_factory_heat_transfer (PhysicsNaming::heat_transfer(),PhysicsNaming::heat_transfer()); PhysicsFactoryHeatTransfer<HeatTransferAdjointStabilization> grins_factory_heat_transfer_adjoint_stab (PhysicsNaming::heat_transfer_adjoint_stab(),PhysicsNaming::heat_transfer()); PhysicsFactoryHeatTransfer<HeatTransferAdjointStabilization> grins_factory_heat_transfer_spgsm_stab (PhysicsNaming::heat_transfer_spgsm_stab(),PhysicsNaming::heat_transfer()); // This needs to die. Axisymmetry should be handled within heat_transfer PhysicsFactoryHeatTransfer<AxisymmetricHeatTransfer> grins_factory_axi_heat_transfer (PhysicsNaming::axisymmetric_heat_transfer(),PhysicsNaming::axisymmetric_heat_transfer()); } // end namespace GRINS <|endoftext|>
<commit_before>#include <QGuiApplication> #include <QScreen> #include <QX11Info> #include "LinuxWindowCapture.h" #include <xcb/xcb_icccm.h> #define WM_WINDOW_INSTANCE "Hearthstone.exe" #define WM_CLASS "Hearthstone.exe" LinuxWindowCapture::LinuxWindowCapture() : mWindow( 0 ) { } bool LinuxWindowCapture::WindowFound() { if ( mWindow == 0 ) mWindow = FindWindow( WM_WINDOW_INSTANCE, WM_CLASS ); if ( mWindow != 0 && !WindowRect() ) mWindow = 0; return mWindow != 0; } int LinuxWindowCapture::Width() { return mRect.width(); } int LinuxWindowCapture::Height() { return mRect.height(); } int LinuxWindowCapture::Left() { return mRect.x(); } int LinuxWindowCapture::Top() { return mRect.y(); } QPixmap LinuxWindowCapture::Capture( int x, int y, int w, int h ) { LOG("Capturing window: %d, %d, %d, %d", x, y, h, w ); QScreen *screen = QGuiApplication::primaryScreen(); QPixmap pixmap = screen->grabWindow( mWindow, x, y, w, h ); return pixmap; } QList< xcb_window_t > LinuxWindowCapture::listWindowsRecursive( const xcb_window_t& window ) { QList< xcb_window_t > windows; xcb_query_tree_reply_t* queryR; xcb_connection_t* xcbConn = QX11Info::connection(); xcb_query_tree_cookie_t queryC = xcb_query_tree( xcbConn, window ); if( ( queryR = xcb_query_tree_reply( QX11Info::connection(), queryC, NULL ) ) ) { xcb_window_t* children = xcb_query_tree_children( queryR ); for( int c = 0; c < xcb_query_tree_children_length( queryR ); ++c ) { windows << children[ c ]; windows << listWindowsRecursive( children[ c ]); } free( queryR ); } return windows; } bool LinuxWindowCapture::WindowRect() { if( mWindow == 0 ) return false; xcb_connection_t* xcbConn = QX11Info::connection(); xcb_get_geometry_cookie_t geometryC = xcb_get_geometry( xcbConn, mWindow ); xcb_get_geometry_reply_t* geometryR = xcb_get_geometry_reply( xcbConn, geometryC, NULL ); if( !geometryR ) return false; // assume the parent window is the screen then we can just use the coordinates directly mRect.setRect( geometryR->x, geometryR->y, geometryR->width, geometryR->height ); free( geometryR ); xcb_query_tree_reply_t* treeR = xcb_query_tree_reply( xcbConn, xcb_query_tree( xcbConn, mWindow ), NULL ); if ( !treeR ) return false; // if the parent isn't screen translate coords if ( treeR->parent != QX11Info::appRootWindow() ) { free( treeR ); xcb_translate_coordinates_cookie_t translateC = xcb_translate_coordinates( xcbConn, mWindow, QX11Info::appRootWindow(), mRect.x(), mRect.y() ); xcb_translate_coordinates_reply_t* translateR = xcb_translate_coordinates_reply( xcbConn, translateC, NULL ); if ( !translateR ) return false; mRect.setTopLeft( QPoint( translateR->dst_x, translateR->dst_y ) ); free( translateR ); } else{ free(treeR); } return true; } xcb_window_t LinuxWindowCapture::FindWindow( const QString& instanceName, const QString& windowClass ) { xcb_window_t winID = static_cast< xcb_window_t > ( 0 ); QList< xcb_window_t > windows = listWindowsRecursive( static_cast< xcb_window_t >( QX11Info::appRootWindow() ) ); xcb_connection_t* xcbConn = QX11Info::connection(); foreach( const xcb_window_t& win, windows ) { xcb_icccm_get_wm_class_reply_t wmNameR; xcb_get_property_cookie_t wmClassC = xcb_icccm_get_wm_class( xcbConn, win ); if ( xcb_icccm_get_wm_class_reply( xcbConn, wmClassC, &wmNameR, NULL ) ) { if( !qstrcmp( wmNameR.class_name, windowClass.toStdString().c_str() ) || !qstrcmp( wmNameR.instance_name, instanceName.toStdString().c_str() ) ) { winID = win; break; } } } return winID; } bool LinuxWindowCapture::HasFocus() { if( mWindow ) { xcb_window_t focusW; xcb_connection_t* xcbConn = QX11Info::connection(); xcb_get_input_focus_cookie_t focusC = xcb_get_input_focus( xcbConn ); xcb_get_input_focus_reply_t* focusR = xcb_get_input_focus_reply( xcbConn, focusC, NULL ); focusW = focusR->focus; free( focusR ); return focusW == mWindow; } return false; } <commit_msg>Use existing variable<commit_after>#include <QGuiApplication> #include <QScreen> #include <QX11Info> #include "LinuxWindowCapture.h" #include <xcb/xcb_icccm.h> #define WM_WINDOW_INSTANCE "Hearthstone.exe" #define WM_CLASS "Hearthstone.exe" LinuxWindowCapture::LinuxWindowCapture() : mWindow( 0 ) { } bool LinuxWindowCapture::WindowFound() { if ( mWindow == 0 ) mWindow = FindWindow( WM_WINDOW_INSTANCE, WM_CLASS ); if ( mWindow != 0 && !WindowRect() ) mWindow = 0; return mWindow != 0; } int LinuxWindowCapture::Width() { return mRect.width(); } int LinuxWindowCapture::Height() { return mRect.height(); } int LinuxWindowCapture::Left() { return mRect.x(); } int LinuxWindowCapture::Top() { return mRect.y(); } QPixmap LinuxWindowCapture::Capture( int x, int y, int w, int h ) { LOG("Capturing window: %d, %d, %d, %d", x, y, h, w ); QScreen *screen = QGuiApplication::primaryScreen(); QPixmap pixmap = screen->grabWindow( mWindow, x, y, w, h ); return pixmap; } QList< xcb_window_t > LinuxWindowCapture::listWindowsRecursive( const xcb_window_t& window ) { QList< xcb_window_t > windows; xcb_query_tree_reply_t* queryR; xcb_connection_t* xcbConn = QX11Info::connection(); xcb_query_tree_cookie_t queryC = xcb_query_tree( xcbConn, window ); if( ( queryR = xcb_query_tree_reply( xcbConn, queryC, NULL ) ) ) { xcb_window_t* children = xcb_query_tree_children( queryR ); for( int c = 0; c < xcb_query_tree_children_length( queryR ); ++c ) { windows << children[ c ]; windows << listWindowsRecursive( children[ c ]); } free( queryR ); } return windows; } bool LinuxWindowCapture::WindowRect() { if( mWindow == 0 ) return false; xcb_connection_t* xcbConn = QX11Info::connection(); xcb_get_geometry_cookie_t geometryC = xcb_get_geometry( xcbConn, mWindow ); xcb_get_geometry_reply_t* geometryR = xcb_get_geometry_reply( xcbConn, geometryC, NULL ); if( !geometryR ) return false; // assume the parent window is the screen then we can just use the coordinates directly mRect.setRect( geometryR->x, geometryR->y, geometryR->width, geometryR->height ); free( geometryR ); xcb_query_tree_reply_t* treeR = xcb_query_tree_reply( xcbConn, xcb_query_tree( xcbConn, mWindow ), NULL ); if ( !treeR ) return false; // if the parent isn't screen translate coords if ( treeR->parent != QX11Info::appRootWindow() ) { free( treeR ); xcb_translate_coordinates_cookie_t translateC = xcb_translate_coordinates( xcbConn, mWindow, QX11Info::appRootWindow(), mRect.x(), mRect.y() ); xcb_translate_coordinates_reply_t* translateR = xcb_translate_coordinates_reply( xcbConn, translateC, NULL ); if ( !translateR ) return false; mRect.setTopLeft( QPoint( translateR->dst_x, translateR->dst_y ) ); free( translateR ); } else{ free(treeR); } return true; } xcb_window_t LinuxWindowCapture::FindWindow( const QString& instanceName, const QString& windowClass ) { xcb_window_t winID = static_cast< xcb_window_t > ( 0 ); QList< xcb_window_t > windows = listWindowsRecursive( static_cast< xcb_window_t >( QX11Info::appRootWindow() ) ); xcb_connection_t* xcbConn = QX11Info::connection(); foreach( const xcb_window_t& win, windows ) { xcb_icccm_get_wm_class_reply_t wmNameR; xcb_get_property_cookie_t wmClassC = xcb_icccm_get_wm_class( xcbConn, win ); if ( xcb_icccm_get_wm_class_reply( xcbConn, wmClassC, &wmNameR, NULL ) ) { if( !qstrcmp( wmNameR.class_name, windowClass.toStdString().c_str() ) || !qstrcmp( wmNameR.instance_name, instanceName.toStdString().c_str() ) ) { winID = win; break; } } } return winID; } bool LinuxWindowCapture::HasFocus() { if( mWindow ) { xcb_window_t focusW; xcb_connection_t* xcbConn = QX11Info::connection(); xcb_get_input_focus_cookie_t focusC = xcb_get_input_focus( xcbConn ); xcb_get_input_focus_reply_t* focusR = xcb_get_input_focus_reply( xcbConn, focusC, NULL ); focusW = focusR->focus; free( focusR ); return focusW == mWindow; } return false; } <|endoftext|>
<commit_before>#include "caffe2/core/common_cudnn.h" #include "caffe2/core/context_gpu.h" #include "caffe2/operators/conv_pool_op_base.h" namespace caffe2 { namespace { template <typename T> void setTensorDescriptor( const int size, const StorageOrder order, const int N, const int C, const int H, const int W, const int D, cudnnTensorDescriptor_t& desc) { if (size == 4) { CUDNN_ENFORCE(cudnnSetTensor4dDescriptor( desc, GetCudnnTensorFormat(order), cudnnTypeWrapper<T>::type, N, C, H, W)); } else { vector<int> dims = {N, C, H, W, D}; vector<int> strides; order == NCHW ? strides.insert(strides.end(), {C * H * W * D, H * W * D, W * D, D, 1}) : strides.insert( strides.end(), {H * W * D * C, 1, W * D * C, D * C, C}); CUDNN_ENFORCE(cudnnSetTensorNdDescriptor( desc, cudnnTypeWrapper<T>::type, size > 3 ? size : 4, dims.data(), strides.data())); } } } // namespace class CuDNNPoolOp : public ConvPoolOpBase<CUDAContext> { public: CuDNNPoolOp(const OperatorDef& operator_def, Workspace* ws) : ConvPoolOpBase<CUDAContext>(operator_def, ws), cudnn_wrapper_(&context_) { CUDNN_ENFORCE(cudnnCreateTensorDescriptor(&bottom_desc_)); CUDNN_ENFORCE(cudnnCreateTensorDescriptor(&top_desc_)); CUDNN_ENFORCE(cudnnCreatePoolingDescriptor(&pooling_desc_)); // Figure out the pooling descriptor. if (operator_def.type().substr(0, 7) == "MaxPool") { #if CUDNN_VERSION_MIN(6,0,0) mode_ = CUDNN_POOLING_MAX_DETERMINISTIC; #else mode_ = CUDNN_POOLING_MAX; #endif } else if (operator_def.type().substr(0, 11) == "AveragePool") { mode_ = CUDNN_POOLING_AVERAGE_COUNT_EXCLUDE_PADDING; } else { LOG(FATAL) << "Unsupported pooling method: " << operator_def.type(); } } ~CuDNNPoolOp() { CUDNN_ENFORCE(cudnnDestroyTensorDescriptor(bottom_desc_)); CUDNN_ENFORCE(cudnnDestroyTensorDescriptor(top_desc_)); CUDNN_ENFORCE(cudnnDestroyPoolingDescriptor(pooling_desc_)); } template <typename T, typename M> bool DoRunWithType() { auto& X = Input(0); auto* Y = Output(0); int N = 0, C = 0, H = 0, W = 0, D = 0; int H_out = 0, W_out = 0, D_out = 0; // cuDNN pooling support only 2 and 3 spatial dimensions. CAFFE_ENFORCE(X.ndim() >= 4 && X.ndim() <= 5); switch (order_) { case StorageOrder::NHWC: N = X.dim32(0); H = X.dim32(1); W = X.ndim() > 3 ? X.dim32(2) : 1; D = X.ndim() > 4 ? X.dim32(3) : 1; C = X.dim32(X.ndim() - 1); ConvPoolOpBase::SetOutputSize(X, Y, C); H_out = Y->dim32(1); W_out = Y->ndim() > 3 ? Y->dim32(2) : 1; D_out = Y->ndim() > 4 ? Y->dim32(3) : 1; break; case StorageOrder::NCHW: N = X.dim32(0); C = X.dim32(1); H = X.dim32(2); W = X.ndim() > 3 ? X.dim32(3) : 1; D = X.ndim() > 4 ? X.dim32(4) : 1; ConvPoolOpBase::SetOutputSize(X, Y, C); H_out = Y->dim32(2); W_out = Y->ndim() > 3 ? Y->dim32(3) : 1; D_out = Y->ndim() > 4 ? Y->dim32(4) : 1; break; default: LOG(FATAL) << "Unknown storage order: " << order_; } if (cudnn_input_dims_ != X.dims()) { // Dimensions changed; we will need to re-initialize things. VLOG(1) << "Changing the cudnn descriptor configurations."; cudnn_input_dims_ = X.dims(); setTensorDescriptor<T>(X.ndim(), order_, N, C, H, W, D, bottom_desc_); setTensorDescriptor<T>( Y->ndim(), order_, N, C, H_out, W_out, D_out, top_desc_); for (int i = 0; i < kernel_.size(); ++i) { if (pads_[i] != pads_[kernel_.size() + i]) { CAFFE_ENFORCE( legacy_pad_ == LegacyPadding::CAFFE_LEGACY_POOLING, "Cudnn pooling only supports even padding on both sides, with " "the only exception of the caffe legacy pooling case where we " "try to preserve backward compatibility with Caffe."); } } if (kernel_.size() == 2) { CUDNN_ENFORCE(cudnnSetPooling2dDescriptor( pooling_desc_, mode_, CUDNN_NOT_PROPAGATE_NAN, kernel_h(), kernel_w(), pad_t(), pad_l(), stride_h(), stride_w())); } else { CUDNN_ENFORCE(cudnnSetPoolingNdDescriptor( pooling_desc_, mode_, CUDNN_NOT_PROPAGATE_NAN, kernel_.size(), kernel_.data(), pads_.data(), stride_.data())); } } // Carry out the pooling computation. CUDNN_ENFORCE(cudnnPoolingForward( cudnn_wrapper_.inline_cudnn_handle(), pooling_desc_, cudnnTypeWrapper<T>::kOne(), bottom_desc_, X.template data<T>(), cudnnTypeWrapper<T>::kZero(), top_desc_, Y->template mutable_data<T>())); return true; } bool RunOnDevice() final { auto& X = Input(0); auto* Y = Output(0); if (X.IsType<float>()) { return DoRunWithType<float,float>(); } else if (X.IsType<float16>()) { return DoRunWithType<float16,float>(); } else { LOG(FATAL) << "Unsupported input types"; } return true; } protected: vector<TIndex> cudnn_input_dims_; CuDNNWrapper cudnn_wrapper_; cudnnTensorDescriptor_t bottom_desc_; cudnnTensorDescriptor_t top_desc_; cudnnPoolingDescriptor_t pooling_desc_; cudnnPoolingMode_t mode_; private: }; class CuDNNPoolGradientOp : public ConvPoolOpBase<CUDAContext> { public: CuDNNPoolGradientOp(const OperatorDef& operator_def, Workspace* ws) : ConvPoolOpBase<CUDAContext>(operator_def, ws), cudnn_wrapper_(&context_) { CUDNN_ENFORCE(cudnnCreateTensorDescriptor(&bottom_desc_)); CUDNN_ENFORCE(cudnnCreateTensorDescriptor(&top_desc_)); CUDNN_ENFORCE(cudnnCreatePoolingDescriptor(&pooling_desc_)); // Figure out the pooling descriptor. if (operator_def.type() == "MaxPoolGradient") { mode_ = CUDNN_POOLING_MAX; } else if (operator_def.type() == "AveragePoolGradient") { mode_ = CUDNN_POOLING_AVERAGE_COUNT_EXCLUDE_PADDING; } else { LOG(FATAL) << "Unsupported pooling method: " << operator_def.type(); } } ~CuDNNPoolGradientOp() { CUDNN_ENFORCE(cudnnDestroyTensorDescriptor(bottom_desc_)); CUDNN_ENFORCE(cudnnDestroyTensorDescriptor(top_desc_)); CUDNN_ENFORCE(cudnnDestroyPoolingDescriptor(pooling_desc_)); } template <typename T, typename M> bool DoRunWithType() { auto& X = Input(0); auto& Y = Input(1); auto& dY = Input(2); auto* dX = Output(0); // cuDNN pooling support only 2 and 3 spatial dimensions. CAFFE_ENFORCE(X.ndim() >= 4 && X.ndim() <= 5); dX->ResizeLike(X); int N = 0, C = 0, H = 0, W = 0, D = 0; int H_out = 0, W_out = 0, D_out = 0; switch (order_) { case StorageOrder::NHWC: N = X.dim32(0); H = X.dim32(1); W = X.ndim() > 3 ? X.dim32(2) : 1; D = X.ndim() > 4 ? X.dim32(3) : 1; C = X.dim32(X.ndim() - 1); H_out = Y.dim32(1); W_out = Y.ndim() > 3 ? Y.dim32(2) : 1; D_out = Y.ndim() > 4 ? Y.dim32(3) : 1; break; case StorageOrder::NCHW: N = X.dim32(0); C = X.dim32(1); H = X.dim32(2); W = X.ndim() > 3 ? X.dim32(3) : 1; D = X.ndim() > 4 ? X.dim32(4) : 1; H_out = Y.dim32(2); W_out = Y.ndim() > 3 ? Y.dim32(3) : 1; D_out = Y.ndim() > 4 ? Y.dim32(4) : 1; break; default: LOG(FATAL) << "Unknown storage order: " << order_; } if (kernel_.size() == 1) { ConvPoolOpBase<CUDAContext>::ComputePads({H}); } else if (kernel_.size() == 2) { ConvPoolOpBase<CUDAContext>::ComputePads({H, W}); } else if (kernel_.size() == 3) { ConvPoolOpBase<CUDAContext>::ComputePads({H, W, D}); } else { CAFFE_THROW("Unsupported kernel size :", kernel_.size()); } if (cudnn_input_dims_ != X.dims()) { // Dimensions changed; we will need to re-initialize things. VLOG(1) << "Changing the cudnn descriptor configurations."; cudnn_input_dims_ = X.dims(); setTensorDescriptor<T>(X.ndim(), order_, N, C, H, W, D, bottom_desc_); setTensorDescriptor<T>( Y.ndim(), order_, N, C, H_out, W_out, D_out, top_desc_); if (pad_t() != pad_l() || pad_l() != pad_r()) { CAFFE_ENFORCE( legacy_pad_ == LegacyPadding::CAFFE_LEGACY_POOLING, "Cudnn pooling only supports even padding on both sides, with " "the only exception of the caffe legacy pooling case where we " "try to preserve backward compatibility with Caffe."); } if (kernel_.size() == 2) { CUDNN_ENFORCE(cudnnSetPooling2dDescriptor( pooling_desc_, mode_, CUDNN_NOT_PROPAGATE_NAN, kernel_h(), kernel_w(), pad_t(), pad_l(), stride_h(), stride_w())); } else { CUDNN_ENFORCE(cudnnSetPoolingNdDescriptor( pooling_desc_, mode_, CUDNN_NOT_PROPAGATE_NAN, kernel_.size(), kernel_.data(), pads_.data(), stride_.data())); } } // Carry out the pooling computation. CUDNN_ENFORCE(cudnnPoolingBackward( cudnn_wrapper_.inline_cudnn_handle(), pooling_desc_, cudnnTypeWrapper<T>::kOne(), top_desc_, Y.template data<T>(), top_desc_, dY.template data<T>(), bottom_desc_, X.template data<T>(), cudnnTypeWrapper<T>::kZero(), bottom_desc_, dX->template mutable_data<T>())); return true; } bool RunOnDevice() final { auto& X = Input(0); auto& Y = Input(1); auto& dY = Input(2); auto* dX = Output(0); dX->ResizeLike(X); if (X.IsType<float>()) { return DoRunWithType<float,float>(); } else if (X.IsType<float16>()) { return DoRunWithType<float16,float>(); } else { LOG(FATAL) << "Unsupported input types"; } return true; } protected: vector<TIndex> cudnn_input_dims_; CuDNNWrapper cudnn_wrapper_; cudnnTensorDescriptor_t bottom_desc_; cudnnTensorDescriptor_t top_desc_; cudnnPoolingDescriptor_t pooling_desc_; cudnnPoolingMode_t mode_; // Input: X, Y, dY // Output: dX INPUT_TAGS(IN, OUT, OUT_GRAD); }; namespace { REGISTER_CUDNN_OPERATOR(AveragePool, CuDNNPoolOp); REGISTER_CUDNN_OPERATOR(AveragePoolGradient, CuDNNPoolGradientOp); REGISTER_CUDNN_OPERATOR(MaxPool, CuDNNPoolOp); REGISTER_CUDNN_OPERATOR(MaxPoolGradient, CuDNNPoolGradientOp); } // namespace } // namespace caffe2 <commit_msg>Fix NDPooling gradient non-symmetric padding check.<commit_after>#include "caffe2/core/common_cudnn.h" #include "caffe2/core/context_gpu.h" #include "caffe2/operators/conv_pool_op_base.h" namespace caffe2 { namespace { template <typename T> void setTensorDescriptor( const int size, const StorageOrder order, const int N, const int C, const int H, const int W, const int D, cudnnTensorDescriptor_t& desc) { if (size == 4) { CUDNN_ENFORCE(cudnnSetTensor4dDescriptor( desc, GetCudnnTensorFormat(order), cudnnTypeWrapper<T>::type, N, C, H, W)); } else { vector<int> dims = {N, C, H, W, D}; vector<int> strides; order == NCHW ? strides.insert(strides.end(), {C * H * W * D, H * W * D, W * D, D, 1}) : strides.insert( strides.end(), {H * W * D * C, 1, W * D * C, D * C, C}); CUDNN_ENFORCE(cudnnSetTensorNdDescriptor( desc, cudnnTypeWrapper<T>::type, size > 3 ? size : 4, dims.data(), strides.data())); } } } // namespace class CuDNNPoolOp : public ConvPoolOpBase<CUDAContext> { public: CuDNNPoolOp(const OperatorDef& operator_def, Workspace* ws) : ConvPoolOpBase<CUDAContext>(operator_def, ws), cudnn_wrapper_(&context_) { CUDNN_ENFORCE(cudnnCreateTensorDescriptor(&bottom_desc_)); CUDNN_ENFORCE(cudnnCreateTensorDescriptor(&top_desc_)); CUDNN_ENFORCE(cudnnCreatePoolingDescriptor(&pooling_desc_)); // Figure out the pooling descriptor. if (operator_def.type().substr(0, 7) == "MaxPool") { #if CUDNN_VERSION_MIN(6,0,0) mode_ = CUDNN_POOLING_MAX_DETERMINISTIC; #else mode_ = CUDNN_POOLING_MAX; #endif } else if (operator_def.type().substr(0, 11) == "AveragePool") { mode_ = CUDNN_POOLING_AVERAGE_COUNT_EXCLUDE_PADDING; } else { LOG(FATAL) << "Unsupported pooling method: " << operator_def.type(); } } ~CuDNNPoolOp() { CUDNN_ENFORCE(cudnnDestroyTensorDescriptor(bottom_desc_)); CUDNN_ENFORCE(cudnnDestroyTensorDescriptor(top_desc_)); CUDNN_ENFORCE(cudnnDestroyPoolingDescriptor(pooling_desc_)); } template <typename T, typename M> bool DoRunWithType() { auto& X = Input(0); auto* Y = Output(0); int N = 0, C = 0, H = 0, W = 0, D = 0; int H_out = 0, W_out = 0, D_out = 0; // cuDNN pooling support only 2 and 3 spatial dimensions. CAFFE_ENFORCE(X.ndim() >= 4 && X.ndim() <= 5); switch (order_) { case StorageOrder::NHWC: N = X.dim32(0); H = X.dim32(1); W = X.ndim() > 3 ? X.dim32(2) : 1; D = X.ndim() > 4 ? X.dim32(3) : 1; C = X.dim32(X.ndim() - 1); ConvPoolOpBase::SetOutputSize(X, Y, C); H_out = Y->dim32(1); W_out = Y->ndim() > 3 ? Y->dim32(2) : 1; D_out = Y->ndim() > 4 ? Y->dim32(3) : 1; break; case StorageOrder::NCHW: N = X.dim32(0); C = X.dim32(1); H = X.dim32(2); W = X.ndim() > 3 ? X.dim32(3) : 1; D = X.ndim() > 4 ? X.dim32(4) : 1; ConvPoolOpBase::SetOutputSize(X, Y, C); H_out = Y->dim32(2); W_out = Y->ndim() > 3 ? Y->dim32(3) : 1; D_out = Y->ndim() > 4 ? Y->dim32(4) : 1; break; default: LOG(FATAL) << "Unknown storage order: " << order_; } if (cudnn_input_dims_ != X.dims()) { // Dimensions changed; we will need to re-initialize things. VLOG(1) << "Changing the cudnn descriptor configurations."; cudnn_input_dims_ = X.dims(); setTensorDescriptor<T>(X.ndim(), order_, N, C, H, W, D, bottom_desc_); setTensorDescriptor<T>( Y->ndim(), order_, N, C, H_out, W_out, D_out, top_desc_); for (int i = 0; i < kernel_.size(); ++i) { if (pads_[i] != pads_[kernel_.size() + i]) { CAFFE_ENFORCE( legacy_pad_ == LegacyPadding::CAFFE_LEGACY_POOLING, "Cudnn pooling only supports even padding on both sides, with " "the only exception of the caffe legacy pooling case where we " "try to preserve backward compatibility with Caffe."); } } if (kernel_.size() == 2) { CUDNN_ENFORCE(cudnnSetPooling2dDescriptor( pooling_desc_, mode_, CUDNN_NOT_PROPAGATE_NAN, kernel_h(), kernel_w(), pad_t(), pad_l(), stride_h(), stride_w())); } else { CUDNN_ENFORCE(cudnnSetPoolingNdDescriptor( pooling_desc_, mode_, CUDNN_NOT_PROPAGATE_NAN, kernel_.size(), kernel_.data(), pads_.data(), stride_.data())); } } // Carry out the pooling computation. CUDNN_ENFORCE(cudnnPoolingForward( cudnn_wrapper_.inline_cudnn_handle(), pooling_desc_, cudnnTypeWrapper<T>::kOne(), bottom_desc_, X.template data<T>(), cudnnTypeWrapper<T>::kZero(), top_desc_, Y->template mutable_data<T>())); return true; } bool RunOnDevice() final { auto& X = Input(0); auto* Y = Output(0); if (X.IsType<float>()) { return DoRunWithType<float,float>(); } else if (X.IsType<float16>()) { return DoRunWithType<float16,float>(); } else { LOG(FATAL) << "Unsupported input types"; } return true; } protected: vector<TIndex> cudnn_input_dims_; CuDNNWrapper cudnn_wrapper_; cudnnTensorDescriptor_t bottom_desc_; cudnnTensorDescriptor_t top_desc_; cudnnPoolingDescriptor_t pooling_desc_; cudnnPoolingMode_t mode_; private: }; class CuDNNPoolGradientOp : public ConvPoolOpBase<CUDAContext> { public: CuDNNPoolGradientOp(const OperatorDef& operator_def, Workspace* ws) : ConvPoolOpBase<CUDAContext>(operator_def, ws), cudnn_wrapper_(&context_) { CUDNN_ENFORCE(cudnnCreateTensorDescriptor(&bottom_desc_)); CUDNN_ENFORCE(cudnnCreateTensorDescriptor(&top_desc_)); CUDNN_ENFORCE(cudnnCreatePoolingDescriptor(&pooling_desc_)); // Figure out the pooling descriptor. if (operator_def.type() == "MaxPoolGradient") { mode_ = CUDNN_POOLING_MAX; } else if (operator_def.type() == "AveragePoolGradient") { mode_ = CUDNN_POOLING_AVERAGE_COUNT_EXCLUDE_PADDING; } else { LOG(FATAL) << "Unsupported pooling method: " << operator_def.type(); } } ~CuDNNPoolGradientOp() { CUDNN_ENFORCE(cudnnDestroyTensorDescriptor(bottom_desc_)); CUDNN_ENFORCE(cudnnDestroyTensorDescriptor(top_desc_)); CUDNN_ENFORCE(cudnnDestroyPoolingDescriptor(pooling_desc_)); } template <typename T, typename M> bool DoRunWithType() { auto& X = Input(0); auto& Y = Input(1); auto& dY = Input(2); auto* dX = Output(0); // cuDNN pooling support only 2 and 3 spatial dimensions. CAFFE_ENFORCE(X.ndim() >= 4 && X.ndim() <= 5); dX->ResizeLike(X); int N = 0, C = 0, H = 0, W = 0, D = 0; int H_out = 0, W_out = 0, D_out = 0; switch (order_) { case StorageOrder::NHWC: N = X.dim32(0); H = X.dim32(1); W = X.ndim() > 3 ? X.dim32(2) : 1; D = X.ndim() > 4 ? X.dim32(3) : 1; C = X.dim32(X.ndim() - 1); H_out = Y.dim32(1); W_out = Y.ndim() > 3 ? Y.dim32(2) : 1; D_out = Y.ndim() > 4 ? Y.dim32(3) : 1; break; case StorageOrder::NCHW: N = X.dim32(0); C = X.dim32(1); H = X.dim32(2); W = X.ndim() > 3 ? X.dim32(3) : 1; D = X.ndim() > 4 ? X.dim32(4) : 1; H_out = Y.dim32(2); W_out = Y.ndim() > 3 ? Y.dim32(3) : 1; D_out = Y.ndim() > 4 ? Y.dim32(4) : 1; break; default: LOG(FATAL) << "Unknown storage order: " << order_; } if (kernel_.size() == 1) { ConvPoolOpBase<CUDAContext>::ComputePads({H}); } else if (kernel_.size() == 2) { ConvPoolOpBase<CUDAContext>::ComputePads({H, W}); } else if (kernel_.size() == 3) { ConvPoolOpBase<CUDAContext>::ComputePads({H, W, D}); } else { CAFFE_THROW("Unsupported kernel size :", kernel_.size()); } if (cudnn_input_dims_ != X.dims()) { // Dimensions changed; we will need to re-initialize things. VLOG(1) << "Changing the cudnn descriptor configurations."; cudnn_input_dims_ = X.dims(); setTensorDescriptor<T>(X.ndim(), order_, N, C, H, W, D, bottom_desc_); setTensorDescriptor<T>( Y.ndim(), order_, N, C, H_out, W_out, D_out, top_desc_); for (int i = 0; i < kernel_.size(); ++i) { if (pads_[i] != pads_[kernel_.size() + i]) { CAFFE_ENFORCE( legacy_pad_ == LegacyPadding::CAFFE_LEGACY_POOLING, "Cudnn pooling only supports even padding on both sides, with " "the only exception of the caffe legacy pooling case where we " "try to preserve backward compatibility with Caffe."); } } if (kernel_.size() == 2) { CUDNN_ENFORCE(cudnnSetPooling2dDescriptor( pooling_desc_, mode_, CUDNN_NOT_PROPAGATE_NAN, kernel_h(), kernel_w(), pad_t(), pad_l(), stride_h(), stride_w())); } else { CUDNN_ENFORCE(cudnnSetPoolingNdDescriptor( pooling_desc_, mode_, CUDNN_NOT_PROPAGATE_NAN, kernel_.size(), kernel_.data(), pads_.data(), stride_.data())); } } // Carry out the pooling computation. CUDNN_ENFORCE(cudnnPoolingBackward( cudnn_wrapper_.inline_cudnn_handle(), pooling_desc_, cudnnTypeWrapper<T>::kOne(), top_desc_, Y.template data<T>(), top_desc_, dY.template data<T>(), bottom_desc_, X.template data<T>(), cudnnTypeWrapper<T>::kZero(), bottom_desc_, dX->template mutable_data<T>())); return true; } bool RunOnDevice() final { auto& X = Input(0); auto& Y = Input(1); auto& dY = Input(2); auto* dX = Output(0); dX->ResizeLike(X); if (X.IsType<float>()) { return DoRunWithType<float,float>(); } else if (X.IsType<float16>()) { return DoRunWithType<float16,float>(); } else { LOG(FATAL) << "Unsupported input types"; } return true; } protected: vector<TIndex> cudnn_input_dims_; CuDNNWrapper cudnn_wrapper_; cudnnTensorDescriptor_t bottom_desc_; cudnnTensorDescriptor_t top_desc_; cudnnPoolingDescriptor_t pooling_desc_; cudnnPoolingMode_t mode_; // Input: X, Y, dY // Output: dX INPUT_TAGS(IN, OUT, OUT_GRAD); }; namespace { REGISTER_CUDNN_OPERATOR(AveragePool, CuDNNPoolOp); REGISTER_CUDNN_OPERATOR(AveragePoolGradient, CuDNNPoolGradientOp); REGISTER_CUDNN_OPERATOR(MaxPool, CuDNNPoolOp); REGISTER_CUDNN_OPERATOR(MaxPoolGradient, CuDNNPoolGradientOp); } // namespace } // namespace caffe2 <|endoftext|>
<commit_before>#include <osg/GL> #include <osg/GLU> #include <osg/Image> #include <osg/Notify> #include <osg/Geode> #include <osg/GeoSet> #include <osg/StateSet> #include <osg/Texture> using namespace osg; using namespace std; Image::Image() { _fileName = ""; _s = _t = _r = 0; _internalTextureFormat = 0; _pixelFormat = (unsigned int)0; _dataType = (unsigned int)0; _packing = 4; _data = (unsigned char *)0L; _modifiedTag = 0; } Image::Image(const Image& image,const CopyOp& copyop): Object(image,copyop), _fileName(image._fileName), _s(image._s), _t(image._t), _r(image._r), _internalTextureFormat(image._internalTextureFormat), _pixelFormat(image._pixelFormat), _dataType(image._dataType), _packing(image._packing), _data(0L), _mipmapData(image._mipmapData), _modifiedTag(image._modifiedTag) { if (image._data) { int num_components = _pixelFormat == GL_LUMINANCE ? 1 : _pixelFormat == GL_LUMINANCE_ALPHA ? 2 : _pixelFormat == GL_RGB ? 3 : _pixelFormat == GL_RGBA ? 4 : 4; int size = _s*_t*_r*num_components; _data = (unsigned char*) malloc(size); memcpy(_data,image._data,size); } } Image::~Image() { if (_data) ::free(_data); } void Image::setFileName(const std::string& fileName) { _fileName = fileName; } #ifndef GL_VERSION_1_2 /* 1.2 definitions...*/ #define GL_BGR 0x80E0 #define GL_BGRA 0x80E1 #define GL_UNSIGNED_BYTE_3_3_2 0x8032 #define GL_UNSIGNED_BYTE_2_3_3_REV 0x8362 #define GL_UNSIGNED_SHORT_5_6_5 0x8363 #define GL_UNSIGNED_SHORT_5_6_5_REV 0x8364 #define GL_UNSIGNED_SHORT_4_4_4_4 0x8033 #define GL_UNSIGNED_SHORT_4_4_4_4_REV 0x8365 #define GL_UNSIGNED_SHORT_5_5_5_1 0x8034 #define GL_UNSIGNED_SHORT_1_5_5_5_REV 0x8366 #define GL_UNSIGNED_INT_8_8_8_8 0x8035 #define GL_UNSIGNED_INT_8_8_8_8_REV 0x8367 #define GL_UNSIGNED_INT_10_10_10_2 0x8036 #define GL_UNSIGNED_INT_2_10_10_10_REV 0x8368 #endif const bool Image::isPackedType(GLenum format) { switch(format) { case(GL_UNSIGNED_BYTE_3_3_2): case(GL_UNSIGNED_BYTE_2_3_3_REV): case(GL_UNSIGNED_SHORT_5_6_5): case(GL_UNSIGNED_SHORT_5_6_5_REV): case(GL_UNSIGNED_SHORT_4_4_4_4): case(GL_UNSIGNED_SHORT_4_4_4_4_REV): case(GL_UNSIGNED_SHORT_5_5_5_1): case(GL_UNSIGNED_SHORT_1_5_5_5_REV): case(GL_UNSIGNED_INT_8_8_8_8): case(GL_UNSIGNED_INT_8_8_8_8_REV): case(GL_UNSIGNED_INT_10_10_10_2): case(GL_UNSIGNED_INT_2_10_10_10_REV): return true; default: return false; } } const unsigned int Image::computeNumComponents(GLenum type) { switch(type) { case(GL_COLOR_INDEX): return 1; case(GL_STENCIL_INDEX): return 1; case(GL_DEPTH_COMPONENT): return 1; case(GL_RED): return 1; case(GL_GREEN): return 1; case(GL_BLUE): return 1; case(GL_ALPHA): return 1; case(GL_RGB): return 3; case(GL_BGR): return 3; case(GL_RGBA): return 4; case(GL_BGRA): return 4; case(GL_LUMINANCE): return 1; case(GL_LUMINANCE_ALPHA): return 2; default: return 0; } } const unsigned int Image::computePixelSizeInBits(GLenum format,GLenum type) { switch(type) { case(GL_BITMAP): return computeNumComponents(format); case(GL_BYTE): case(GL_UNSIGNED_BYTE): return 8*computeNumComponents(format); case(GL_SHORT): case(GL_UNSIGNED_SHORT): return 16*computeNumComponents(format); case(GL_INT): case(GL_UNSIGNED_INT): case(GL_FLOAT): return 32*computeNumComponents(format); case(GL_UNSIGNED_BYTE_3_3_2): case(GL_UNSIGNED_BYTE_2_3_3_REV): return 8; case(GL_UNSIGNED_SHORT_5_6_5): case(GL_UNSIGNED_SHORT_5_6_5_REV): case(GL_UNSIGNED_SHORT_4_4_4_4): case(GL_UNSIGNED_SHORT_4_4_4_4_REV): case(GL_UNSIGNED_SHORT_5_5_5_1): case(GL_UNSIGNED_SHORT_1_5_5_5_REV): return 16; case(GL_UNSIGNED_INT_8_8_8_8): case(GL_UNSIGNED_INT_8_8_8_8_REV): case(GL_UNSIGNED_INT_10_10_10_2): case(GL_UNSIGNED_INT_2_10_10_10_REV): return 32; default: return 0; } } const unsigned int Image::computeRowWidthInBytes(int width,GLenum format,GLenum type,int packing) { unsigned int pixelSize = computePixelSizeInBits(format,type); int widthInBits = width*pixelSize; int packingInBits = packing*8; return (widthInBits/packingInBits + ((widthInBits%packingInBits)?1:0))*packing; } void Image::setInternalTextureFormat(GLint internalFormat) { // won't do any sanity checking right now, leave it to // OpenGL to make the call. _internalTextureFormat = internalFormat; } void Image::setPixelFormat(const GLenum format) { if (_pixelFormat==format) return; // do nothing if the same. if (computeNumComponents(_pixelFormat)==computeNumComponents(format)) { // if the two formats have the same number of componets then // we can do a straight swap. _pixelFormat = format; } else { notify(WARN)<<"Image::setPixelFormat(..) - warning, attempt to reset the pixel format with a different number of components."<<std::endl; } } void Image::createImage(int s,int t,int r, GLenum format,GLenum type, int packing) { _mipmapData.clear(); unsigned int previousTotalSize = computeRowWidthInBytes(_s,_pixelFormat,_dataType,_packing)*_t*_r; unsigned int newTotalSize = computeRowWidthInBytes(s,format,type,packing)*t*r; if (newTotalSize!=previousTotalSize) { if (_data) ::free(_data); if (newTotalSize) _data = (unsigned char *)osgMalloc (newTotalSize); else _data = 0L; } if (_data) { _s = s; _t = t; _r = r; _pixelFormat = format; _dataType = type; _packing = packing; } else { // throw exception?? not for now, will simply set values to 0. _s = 0; _t = 0; _r = 0; _pixelFormat = 0; _dataType = 0; _packing = 0; } ++_modifiedTag; } void Image::setImage(int s,int t,int r, GLint internalTextureFormat, GLenum format,GLenum type, unsigned char *data, int packing) { if (_data) ::free(_data); _mipmapData.clear(); _s = s; _t = t; _r = r; _internalTextureFormat = internalTextureFormat; _pixelFormat = format; _dataType = type; _data = data; _packing = packing; // test scaling... // scaleImageTo(16,16,_r); ++_modifiedTag; } void Image::readPixels(int x,int y,int width,int height, GLenum format,GLenum type) { createImage(width,height,1,format,type); glPixelStorei(GL_PACK_ALIGNMENT,_packing); glReadPixels(x,y,width,height,format,type,_data); } void Image::scaleImage(const int s,const int t,const int r) { if (_data==NULL) { notify(WARN) << "Error Image::scaleImage() do not succeed : cannot scale NULL image."<<std::endl; return; } if (_r!=1 || r!=1) { notify(WARN) << "Error Image::scaleImage() do not succeed : scaling of volumes not implemented."<<std::endl; return; } unsigned int newTotalSize = computeRowWidthInBytes(s,_pixelFormat,_dataType,_packing)*t; // need to sort out what size to really use... unsigned char* newData = (unsigned char *)osgMalloc(newTotalSize); if (!newData) { // should we throw an exception??? Just return for time being. notify(FATAL) << "Error Image::scaleImage() do not succeed : out of memory."<<std::endl; return; } glPixelStorei(GL_PACK_ALIGNMENT,_packing); glPixelStorei(GL_UNPACK_ALIGNMENT,_packing); GLint status = gluScaleImage(_pixelFormat, _s, _t, _dataType, _data, s, t, _dataType, newData); if (status==0) { // free old image. ::free(_data); _s = s; _t = t; _data = newData; } else { ::free(newData); notify(WARN) << "Error Image::scaleImage() do not succeed : errorString = "<<gluErrorString((GLenum)status)<<std::endl; } ++_modifiedTag; } void Image::ensureValidSizeForTexturing() { int new_s = _s; int new_t = _t; // check if _s is a power of 2 already. if ((_s & (_s-1))!=0) { // it isn't so lets find the closest power of two. // yes, logf and powf are slow, but this code should // only be called during scene graph initilization, // if at all, so not critical in the greater scheme. float p2 = logf((float)_s)/logf(2.0f); float rounded_p2 = floorf(p2+0.5f); new_s = (int)(powf(2.0f,rounded_p2)); } if ((_t & (_t-1))!=0) { // it isn't so lets find the closest power of two. // yes, logf and powf are slow, but this code should // only be called during scene graph initilization, // if at all, so not critical in the greater scheme. float p2 = logf((float)_t)/logf(2.0f); float rounded_p2 = floorf(p2+0.5f); new_t = (int)(powf(2.0f,rounded_p2)); } static GLint max_size=256; static bool init = true; if (init) { init = false; glGetIntegerv(GL_MAX_TEXTURE_SIZE,&max_size); notify(INFO) << "Max texture size "<<max_size<<std::endl; } //max_size = 64; if (new_s>max_size) new_s = max_size; if (new_t>max_size) new_t = max_size; if (new_s!=_s || new_t!=_t) { if (!_fileName.empty()) notify(NOTICE) << "Scaling image '"<<_fileName<<"' from ("<<_s<<","<<_t<<") to ("<<new_s<<","<<new_t<<")"<<std::endl; else notify(NOTICE) << "Scaling image from ("<<_s<<","<<_t<<") to ("<<new_s<<","<<new_t<<")"<<std::endl; scaleImage(new_s,new_t,_r); } } Geode* osg::createGeodeForImage(osg::Image* image) { return createGeodeForImage(image,image->s(),image->t()); } Geode* osg::createGeodeForImage(osg::Image* image,const float s,const float t) { if (image) { if (s>0 && t>0) { float y = 1.0; float x = y*(s/t); // set up the texture. osg::Texture* texture = osgNew osg::Texture; texture->setImage(image); // set up the drawstate. osg::StateSet* dstate = osgNew osg::StateSet; dstate->setMode(GL_CULL_FACE,osg::StateAttribute::OFF); dstate->setMode(GL_LIGHTING,osg::StateAttribute::OFF); dstate->setAttributeAndModes(texture,osg::StateAttribute::ON); // set up the geoset. osg::GeoSet* gset = osgNew osg::GeoSet; gset->setStateSet(dstate); osg::Vec3* coords = osgNew Vec3[4]; coords[0].set(-x,0.0f,y); coords[1].set(-x,0.0f,-y); coords[2].set(x,0.0f,-y); coords[3].set(x,0.0f,y); gset->setCoords(coords); osg::Vec2* tcoords = osgNew Vec2[4]; tcoords[0].set(0.0f,1.0f); tcoords[1].set(0.0f,0.0f); tcoords[2].set(1.0f,0.0f); tcoords[3].set(1.0f,1.0f); gset->setTextureCoords(tcoords); gset->setTextureBinding(osg::GeoSet::BIND_PERVERTEX); osg::Vec4* colours = osgNew Vec4[1]; colours->set(1.0f,1.0f,1.0,1.0f); gset->setColors(colours); gset->setColorBinding(osg::GeoSet::BIND_OVERALL); gset->setNumPrims(1); gset->setPrimType(osg::GeoSet::QUADS); // set up the geode. osg::Geode* geode = osgNew osg::Geode; geode->addDrawable(gset); return geode; } else { return NULL; } } else { return NULL; } } <commit_msg>Fixed ordering of paramters in osg::Image constructor to remove warning.<commit_after>#include <osg/GL> #include <osg/GLU> #include <osg/Image> #include <osg/Notify> #include <osg/Geode> #include <osg/GeoSet> #include <osg/StateSet> #include <osg/Texture> using namespace osg; using namespace std; Image::Image() { _fileName = ""; _s = _t = _r = 0; _internalTextureFormat = 0; _pixelFormat = (unsigned int)0; _dataType = (unsigned int)0; _packing = 4; _data = (unsigned char *)0L; _modifiedTag = 0; } Image::Image(const Image& image,const CopyOp& copyop): Object(image,copyop), _fileName(image._fileName), _s(image._s), _t(image._t), _r(image._r), _internalTextureFormat(image._internalTextureFormat), _pixelFormat(image._pixelFormat), _dataType(image._dataType), _packing(image._packing), _data(0L), _modifiedTag(image._modifiedTag), _mipmapData(image._mipmapData) { if (image._data) { int num_components = _pixelFormat == GL_LUMINANCE ? 1 : _pixelFormat == GL_LUMINANCE_ALPHA ? 2 : _pixelFormat == GL_RGB ? 3 : _pixelFormat == GL_RGBA ? 4 : 4; int size = _s*_t*_r*num_components; _data = (unsigned char*) malloc(size); memcpy(_data,image._data,size); } } Image::~Image() { if (_data) ::free(_data); } void Image::setFileName(const std::string& fileName) { _fileName = fileName; } #ifndef GL_VERSION_1_2 /* 1.2 definitions...*/ #define GL_BGR 0x80E0 #define GL_BGRA 0x80E1 #define GL_UNSIGNED_BYTE_3_3_2 0x8032 #define GL_UNSIGNED_BYTE_2_3_3_REV 0x8362 #define GL_UNSIGNED_SHORT_5_6_5 0x8363 #define GL_UNSIGNED_SHORT_5_6_5_REV 0x8364 #define GL_UNSIGNED_SHORT_4_4_4_4 0x8033 #define GL_UNSIGNED_SHORT_4_4_4_4_REV 0x8365 #define GL_UNSIGNED_SHORT_5_5_5_1 0x8034 #define GL_UNSIGNED_SHORT_1_5_5_5_REV 0x8366 #define GL_UNSIGNED_INT_8_8_8_8 0x8035 #define GL_UNSIGNED_INT_8_8_8_8_REV 0x8367 #define GL_UNSIGNED_INT_10_10_10_2 0x8036 #define GL_UNSIGNED_INT_2_10_10_10_REV 0x8368 #endif const bool Image::isPackedType(GLenum format) { switch(format) { case(GL_UNSIGNED_BYTE_3_3_2): case(GL_UNSIGNED_BYTE_2_3_3_REV): case(GL_UNSIGNED_SHORT_5_6_5): case(GL_UNSIGNED_SHORT_5_6_5_REV): case(GL_UNSIGNED_SHORT_4_4_4_4): case(GL_UNSIGNED_SHORT_4_4_4_4_REV): case(GL_UNSIGNED_SHORT_5_5_5_1): case(GL_UNSIGNED_SHORT_1_5_5_5_REV): case(GL_UNSIGNED_INT_8_8_8_8): case(GL_UNSIGNED_INT_8_8_8_8_REV): case(GL_UNSIGNED_INT_10_10_10_2): case(GL_UNSIGNED_INT_2_10_10_10_REV): return true; default: return false; } } const unsigned int Image::computeNumComponents(GLenum type) { switch(type) { case(GL_COLOR_INDEX): return 1; case(GL_STENCIL_INDEX): return 1; case(GL_DEPTH_COMPONENT): return 1; case(GL_RED): return 1; case(GL_GREEN): return 1; case(GL_BLUE): return 1; case(GL_ALPHA): return 1; case(GL_RGB): return 3; case(GL_BGR): return 3; case(GL_RGBA): return 4; case(GL_BGRA): return 4; case(GL_LUMINANCE): return 1; case(GL_LUMINANCE_ALPHA): return 2; default: return 0; } } const unsigned int Image::computePixelSizeInBits(GLenum format,GLenum type) { switch(type) { case(GL_BITMAP): return computeNumComponents(format); case(GL_BYTE): case(GL_UNSIGNED_BYTE): return 8*computeNumComponents(format); case(GL_SHORT): case(GL_UNSIGNED_SHORT): return 16*computeNumComponents(format); case(GL_INT): case(GL_UNSIGNED_INT): case(GL_FLOAT): return 32*computeNumComponents(format); case(GL_UNSIGNED_BYTE_3_3_2): case(GL_UNSIGNED_BYTE_2_3_3_REV): return 8; case(GL_UNSIGNED_SHORT_5_6_5): case(GL_UNSIGNED_SHORT_5_6_5_REV): case(GL_UNSIGNED_SHORT_4_4_4_4): case(GL_UNSIGNED_SHORT_4_4_4_4_REV): case(GL_UNSIGNED_SHORT_5_5_5_1): case(GL_UNSIGNED_SHORT_1_5_5_5_REV): return 16; case(GL_UNSIGNED_INT_8_8_8_8): case(GL_UNSIGNED_INT_8_8_8_8_REV): case(GL_UNSIGNED_INT_10_10_10_2): case(GL_UNSIGNED_INT_2_10_10_10_REV): return 32; default: return 0; } } const unsigned int Image::computeRowWidthInBytes(int width,GLenum format,GLenum type,int packing) { unsigned int pixelSize = computePixelSizeInBits(format,type); int widthInBits = width*pixelSize; int packingInBits = packing*8; return (widthInBits/packingInBits + ((widthInBits%packingInBits)?1:0))*packing; } void Image::setInternalTextureFormat(GLint internalFormat) { // won't do any sanity checking right now, leave it to // OpenGL to make the call. _internalTextureFormat = internalFormat; } void Image::setPixelFormat(const GLenum format) { if (_pixelFormat==format) return; // do nothing if the same. if (computeNumComponents(_pixelFormat)==computeNumComponents(format)) { // if the two formats have the same number of componets then // we can do a straight swap. _pixelFormat = format; } else { notify(WARN)<<"Image::setPixelFormat(..) - warning, attempt to reset the pixel format with a different number of components."<<std::endl; } } void Image::createImage(int s,int t,int r, GLenum format,GLenum type, int packing) { _mipmapData.clear(); unsigned int previousTotalSize = computeRowWidthInBytes(_s,_pixelFormat,_dataType,_packing)*_t*_r; unsigned int newTotalSize = computeRowWidthInBytes(s,format,type,packing)*t*r; if (newTotalSize!=previousTotalSize) { if (_data) ::free(_data); if (newTotalSize) _data = (unsigned char *)osgMalloc (newTotalSize); else _data = 0L; } if (_data) { _s = s; _t = t; _r = r; _pixelFormat = format; _dataType = type; _packing = packing; } else { // throw exception?? not for now, will simply set values to 0. _s = 0; _t = 0; _r = 0; _pixelFormat = 0; _dataType = 0; _packing = 0; } ++_modifiedTag; } void Image::setImage(int s,int t,int r, GLint internalTextureFormat, GLenum format,GLenum type, unsigned char *data, int packing) { if (_data) ::free(_data); _mipmapData.clear(); _s = s; _t = t; _r = r; _internalTextureFormat = internalTextureFormat; _pixelFormat = format; _dataType = type; _data = data; _packing = packing; // test scaling... // scaleImageTo(16,16,_r); ++_modifiedTag; } void Image::readPixels(int x,int y,int width,int height, GLenum format,GLenum type) { createImage(width,height,1,format,type); glPixelStorei(GL_PACK_ALIGNMENT,_packing); glReadPixels(x,y,width,height,format,type,_data); } void Image::scaleImage(const int s,const int t,const int r) { if (_data==NULL) { notify(WARN) << "Error Image::scaleImage() do not succeed : cannot scale NULL image."<<std::endl; return; } if (_r!=1 || r!=1) { notify(WARN) << "Error Image::scaleImage() do not succeed : scaling of volumes not implemented."<<std::endl; return; } unsigned int newTotalSize = computeRowWidthInBytes(s,_pixelFormat,_dataType,_packing)*t; // need to sort out what size to really use... unsigned char* newData = (unsigned char *)osgMalloc(newTotalSize); if (!newData) { // should we throw an exception??? Just return for time being. notify(FATAL) << "Error Image::scaleImage() do not succeed : out of memory."<<std::endl; return; } glPixelStorei(GL_PACK_ALIGNMENT,_packing); glPixelStorei(GL_UNPACK_ALIGNMENT,_packing); GLint status = gluScaleImage(_pixelFormat, _s, _t, _dataType, _data, s, t, _dataType, newData); if (status==0) { // free old image. ::free(_data); _s = s; _t = t; _data = newData; } else { ::free(newData); notify(WARN) << "Error Image::scaleImage() do not succeed : errorString = "<<gluErrorString((GLenum)status)<<std::endl; } ++_modifiedTag; } void Image::ensureValidSizeForTexturing() { int new_s = _s; int new_t = _t; // check if _s is a power of 2 already. if ((_s & (_s-1))!=0) { // it isn't so lets find the closest power of two. // yes, logf and powf are slow, but this code should // only be called during scene graph initilization, // if at all, so not critical in the greater scheme. float p2 = logf((float)_s)/logf(2.0f); float rounded_p2 = floorf(p2+0.5f); new_s = (int)(powf(2.0f,rounded_p2)); } if ((_t & (_t-1))!=0) { // it isn't so lets find the closest power of two. // yes, logf and powf are slow, but this code should // only be called during scene graph initilization, // if at all, so not critical in the greater scheme. float p2 = logf((float)_t)/logf(2.0f); float rounded_p2 = floorf(p2+0.5f); new_t = (int)(powf(2.0f,rounded_p2)); } static GLint max_size=256; static bool init = true; if (init) { init = false; glGetIntegerv(GL_MAX_TEXTURE_SIZE,&max_size); notify(INFO) << "Max texture size "<<max_size<<std::endl; } //max_size = 64; if (new_s>max_size) new_s = max_size; if (new_t>max_size) new_t = max_size; if (new_s!=_s || new_t!=_t) { if (!_fileName.empty()) notify(NOTICE) << "Scaling image '"<<_fileName<<"' from ("<<_s<<","<<_t<<") to ("<<new_s<<","<<new_t<<")"<<std::endl; else notify(NOTICE) << "Scaling image from ("<<_s<<","<<_t<<") to ("<<new_s<<","<<new_t<<")"<<std::endl; scaleImage(new_s,new_t,_r); } } Geode* osg::createGeodeForImage(osg::Image* image) { return createGeodeForImage(image,image->s(),image->t()); } Geode* osg::createGeodeForImage(osg::Image* image,const float s,const float t) { if (image) { if (s>0 && t>0) { float y = 1.0; float x = y*(s/t); // set up the texture. osg::Texture* texture = osgNew osg::Texture; texture->setImage(image); // set up the drawstate. osg::StateSet* dstate = osgNew osg::StateSet; dstate->setMode(GL_CULL_FACE,osg::StateAttribute::OFF); dstate->setMode(GL_LIGHTING,osg::StateAttribute::OFF); dstate->setAttributeAndModes(texture,osg::StateAttribute::ON); // set up the geoset. osg::GeoSet* gset = osgNew osg::GeoSet; gset->setStateSet(dstate); osg::Vec3* coords = osgNew Vec3[4]; coords[0].set(-x,0.0f,y); coords[1].set(-x,0.0f,-y); coords[2].set(x,0.0f,-y); coords[3].set(x,0.0f,y); gset->setCoords(coords); osg::Vec2* tcoords = osgNew Vec2[4]; tcoords[0].set(0.0f,1.0f); tcoords[1].set(0.0f,0.0f); tcoords[2].set(1.0f,0.0f); tcoords[3].set(1.0f,1.0f); gset->setTextureCoords(tcoords); gset->setTextureBinding(osg::GeoSet::BIND_PERVERTEX); osg::Vec4* colours = osgNew Vec4[1]; colours->set(1.0f,1.0f,1.0,1.0f); gset->setColors(colours); gset->setColorBinding(osg::GeoSet::BIND_OVERALL); gset->setNumPrims(1); gset->setPrimType(osg::GeoSet::QUADS); // set up the geode. osg::Geode* geode = osgNew osg::Geode; geode->addDrawable(gset); return geode; } else { return NULL; } } else { return NULL; } } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: fuspell.cxx,v $ * * $Revision: 1.8 $ * * last change: $Author: rt $ $Date: 2005-12-14 17:04:36 $ * * 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 * ************************************************************************/ #pragma hdrstop #include "fuspell.hxx" #include <svx/outliner.hxx> #ifndef _SFX_BINDINGS_HXX //autogen #include <sfx2/bindings.hxx> #endif #include <sfx2/viewfrm.hxx> #ifndef SD_FU_POOR_HXX #include "fupoor.hxx" #endif #ifndef SD_OUTLINER_HXX #include "Outliner.hxx" #endif #include "drawdoc.hxx" #ifndef SD_DRAW_VIEW_SHELL_HXX #include "DrawViewShell.hxx" #endif #ifndef SD_OUTLINE_VIEW_SHELL_HXX #include "OutlineViewShell.hxx" #endif #ifndef SD_VIEW_SHELL_BASE_HXX #include "ViewShellBase.hxx" #endif #include "app.hrc" class SfxRequest; namespace sd { USHORT SidArraySpell[] = { SID_DRAWINGMODE, SID_OUTLINEMODE, SID_DIAMODE, SID_NOTESMODE, SID_HANDOUTMODE, 0 }; TYPEINIT1( FuSpell, FuPoor ); /************************************************************************* |* |* Konstruktor |* \************************************************************************/ FuSpell::FuSpell ( ViewShell* pViewSh, ::sd::Window* pWin, ::sd::View* pView, SdDrawDocument* pDoc, SfxRequest& rReq ) : FuPoor(pViewSh, pWin, pView, pDoc, rReq), pSdOutliner(NULL), bOwnOutliner(FALSE) { } FunctionReference FuSpell::Create( ViewShell* pViewSh, ::sd::Window* pWin, ::sd::View* pView, SdDrawDocument* pDoc, SfxRequest& rReq ) { FunctionReference xFunc( new FuSpell( pViewSh, pWin, pView, pDoc, rReq ) ); xFunc->DoExecute(rReq); return xFunc; } void FuSpell::DoExecute( SfxRequest& rReq ) { pViewShell->GetViewFrame()->GetBindings().Invalidate( SidArraySpell ); if ( pViewShell->ISA(DrawViewShell) ) { bOwnOutliner = TRUE; pSdOutliner = new ::sd::Outliner( pDoc, OUTLINERMODE_TEXTOBJECT ); } else if ( pViewShell->ISA(OutlineViewShell) ) { bOwnOutliner = FALSE; pSdOutliner = pDoc->GetOutliner(); } if (pSdOutliner) pSdOutliner->PrepareSpelling(); } /************************************************************************* |* |* Destruktor |* \************************************************************************/ FuSpell::~FuSpell() { pDocSh->GetViewShell()->GetViewFrame()->GetBindings().Invalidate( SidArraySpell ); if (pSdOutliner) pSdOutliner->EndSpelling(); if (bOwnOutliner) delete pSdOutliner; } /************************************************************************* |* |* Pruefung starten |* \************************************************************************/ void FuSpell::StartSpelling() { // Get current main view shell. ViewShellBase* pBase (ViewShellBase::GetViewShellBase ( pDocSh->GetViewShell()->GetViewFrame())); if (pBase != NULL) pViewShell = pBase->GetMainViewShell (); else pViewShell = NULL; if (pViewShell != NULL) { if ( pSdOutliner && pViewShell->ISA(DrawViewShell) && !bOwnOutliner ) { pSdOutliner->EndSpelling(); bOwnOutliner = TRUE; pSdOutliner = new ::sd::Outliner( pDoc, OUTLINERMODE_TEXTOBJECT ); pSdOutliner->PrepareSpelling(); } else if ( pSdOutliner && pViewShell->ISA(OutlineViewShell) && bOwnOutliner ) { pSdOutliner->EndSpelling(); delete pSdOutliner; bOwnOutliner = FALSE; pSdOutliner = pDoc->GetOutliner(); pSdOutliner->PrepareSpelling(); } if (pSdOutliner) pSdOutliner->StartSpelling(); } } } // end of namespace sd <commit_msg>INTEGRATION: CWS pchfix02 (1.8.214); FILE MERGED 2006/09/01 17:37:10 kaib 1.8.214.1: #i68856# Added header markers and pch files<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: fuspell.cxx,v $ * * $Revision: 1.9 $ * * last change: $Author: obo $ $Date: 2006-09-16 18:56:29 $ * * 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_sd.hxx" #include "fuspell.hxx" #include <svx/outliner.hxx> #ifndef _SFX_BINDINGS_HXX //autogen #include <sfx2/bindings.hxx> #endif #include <sfx2/viewfrm.hxx> #ifndef SD_FU_POOR_HXX #include "fupoor.hxx" #endif #ifndef SD_OUTLINER_HXX #include "Outliner.hxx" #endif #include "drawdoc.hxx" #ifndef SD_DRAW_VIEW_SHELL_HXX #include "DrawViewShell.hxx" #endif #ifndef SD_OUTLINE_VIEW_SHELL_HXX #include "OutlineViewShell.hxx" #endif #ifndef SD_VIEW_SHELL_BASE_HXX #include "ViewShellBase.hxx" #endif #include "app.hrc" class SfxRequest; namespace sd { USHORT SidArraySpell[] = { SID_DRAWINGMODE, SID_OUTLINEMODE, SID_DIAMODE, SID_NOTESMODE, SID_HANDOUTMODE, 0 }; TYPEINIT1( FuSpell, FuPoor ); /************************************************************************* |* |* Konstruktor |* \************************************************************************/ FuSpell::FuSpell ( ViewShell* pViewSh, ::sd::Window* pWin, ::sd::View* pView, SdDrawDocument* pDoc, SfxRequest& rReq ) : FuPoor(pViewSh, pWin, pView, pDoc, rReq), pSdOutliner(NULL), bOwnOutliner(FALSE) { } FunctionReference FuSpell::Create( ViewShell* pViewSh, ::sd::Window* pWin, ::sd::View* pView, SdDrawDocument* pDoc, SfxRequest& rReq ) { FunctionReference xFunc( new FuSpell( pViewSh, pWin, pView, pDoc, rReq ) ); xFunc->DoExecute(rReq); return xFunc; } void FuSpell::DoExecute( SfxRequest& rReq ) { pViewShell->GetViewFrame()->GetBindings().Invalidate( SidArraySpell ); if ( pViewShell->ISA(DrawViewShell) ) { bOwnOutliner = TRUE; pSdOutliner = new ::sd::Outliner( pDoc, OUTLINERMODE_TEXTOBJECT ); } else if ( pViewShell->ISA(OutlineViewShell) ) { bOwnOutliner = FALSE; pSdOutliner = pDoc->GetOutliner(); } if (pSdOutliner) pSdOutliner->PrepareSpelling(); } /************************************************************************* |* |* Destruktor |* \************************************************************************/ FuSpell::~FuSpell() { pDocSh->GetViewShell()->GetViewFrame()->GetBindings().Invalidate( SidArraySpell ); if (pSdOutliner) pSdOutliner->EndSpelling(); if (bOwnOutliner) delete pSdOutliner; } /************************************************************************* |* |* Pruefung starten |* \************************************************************************/ void FuSpell::StartSpelling() { // Get current main view shell. ViewShellBase* pBase (ViewShellBase::GetViewShellBase ( pDocSh->GetViewShell()->GetViewFrame())); if (pBase != NULL) pViewShell = pBase->GetMainViewShell (); else pViewShell = NULL; if (pViewShell != NULL) { if ( pSdOutliner && pViewShell->ISA(DrawViewShell) && !bOwnOutliner ) { pSdOutliner->EndSpelling(); bOwnOutliner = TRUE; pSdOutliner = new ::sd::Outliner( pDoc, OUTLINERMODE_TEXTOBJECT ); pSdOutliner->PrepareSpelling(); } else if ( pSdOutliner && pViewShell->ISA(OutlineViewShell) && bOwnOutliner ) { pSdOutliner->EndSpelling(); delete pSdOutliner; bOwnOutliner = FALSE; pSdOutliner = pDoc->GetOutliner(); pSdOutliner->PrepareSpelling(); } if (pSdOutliner) pSdOutliner->StartSpelling(); } } } // end of namespace sd <|endoftext|>
<commit_before>/* This file is part of Magnum. Copyright © 2010, 2011, 2012, 2013, 2014, 2015 Vladimír Vondruš <mosra@centrum.cz> 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 "Framebuffer.h" #include <Corrade/Containers/Array.h> #include "Magnum/Context.h" #include "Magnum/DefaultFramebuffer.h" #include "Magnum/Extensions.h" #include "Magnum/Image.h" #include "Magnum/Renderbuffer.h" #include "Magnum/Texture.h" #ifndef MAGNUM_TARGET_GLES2 #include "Magnum/BufferImage.h" #include "Magnum/MultisampleTexture.h" #include "Magnum/TextureArray.h" #endif #ifndef MAGNUM_TARGET_GLES #include "Magnum/CubeMapTextureArray.h" #include "Magnum/RectangleTexture.h" #endif #include "Implementation/DebugState.h" #include "Implementation/State.h" #include "Implementation/FramebufferState.h" namespace Magnum { const Framebuffer::DrawAttachment Framebuffer::DrawAttachment::None = Framebuffer::DrawAttachment(GL_NONE); const Framebuffer::BufferAttachment Framebuffer::BufferAttachment::Depth = Framebuffer::BufferAttachment(GL_DEPTH_ATTACHMENT); const Framebuffer::BufferAttachment Framebuffer::BufferAttachment::Stencil = Framebuffer::BufferAttachment(GL_STENCIL_ATTACHMENT); #ifndef MAGNUM_TARGET_GLES2 const Framebuffer::BufferAttachment Framebuffer::BufferAttachment::DepthStencil = Framebuffer::BufferAttachment(GL_DEPTH_STENCIL_ATTACHMENT); #endif const Framebuffer::InvalidationAttachment Framebuffer::InvalidationAttachment::Depth = Framebuffer::InvalidationAttachment(GL_DEPTH_ATTACHMENT); const Framebuffer::InvalidationAttachment Framebuffer::InvalidationAttachment::Stencil = Framebuffer::InvalidationAttachment(GL_STENCIL_ATTACHMENT); Int Framebuffer::maxColorAttachments() { #ifdef MAGNUM_TARGET_GLES2 if(!Context::current()->isExtensionSupported<Extensions::GL::NV::fbo_color_attachments>()) return 0; #endif GLint& value = Context::current()->state().framebuffer->maxColorAttachments; if(value == 0) { #ifndef MAGNUM_TARGET_GLES2 glGetIntegerv(GL_MAX_COLOR_ATTACHMENTS, &value); #else glGetIntegerv(GL_MAX_COLOR_ATTACHMENTS_NV, &value); #endif } return value; } Framebuffer::Framebuffer(const Range2Di& viewport) { CORRADE_INTERNAL_ASSERT(viewport != Implementation::FramebufferState::DisengagedViewport); _viewport = viewport; (this->*Context::current()->state().framebuffer->createImplementation)(); CORRADE_INTERNAL_ASSERT(_id != Implementation::State::DisengagedBinding); } void Framebuffer::createImplementationDefault() { glGenFramebuffers(1, &_id); _created = false; } #ifndef MAGNUM_TARGET_GLES void Framebuffer::createImplementationDSA() { glCreateFramebuffers(1, &_id); _created = true; } #endif Framebuffer::~Framebuffer() { /* Moved out, nothing to do */ if(!_id) return; /* If bound, remove itself from state */ Implementation::FramebufferState& state = *Context::current()->state().framebuffer; if(state.readBinding == _id) state.readBinding = 0; /* For draw binding reset also viewport */ if(state.drawBinding == _id) { state.drawBinding = 0; /** * @todo Less ugly solution (need to call setViewportInternal() to * reset the viewport to size of default framebuffer) */ defaultFramebuffer.bind(); } glDeleteFramebuffers(1, &_id); } std::string Framebuffer::label() { createIfNotAlready(); return Context::current()->state().debug->getLabelImplementation(GL_FRAMEBUFFER, _id); } Framebuffer& Framebuffer::setLabelInternal(const Containers::ArrayReference<const char> label) { createIfNotAlready(); Context::current()->state().debug->labelImplementation(GL_FRAMEBUFFER, _id, label); return *this; } Framebuffer::Status Framebuffer::checkStatus(const FramebufferTarget target) { return Status((this->*Context::current()->state().framebuffer->checkStatusImplementation)(target)); } Framebuffer& Framebuffer::mapForDraw(std::initializer_list<std::pair<UnsignedInt, DrawAttachment>> attachments) { /* Max attachment location */ std::size_t max = 0; for(const auto& attachment: attachments) if(attachment.first > max) max = attachment.first; /* Create linear array from associative */ /** @todo C++14: use VLA to avoid heap allocation */ static_assert(GL_NONE == 0, "Expecting zero GL_NONE for zero-initialization"); auto _attachments = Containers::Array<GLenum>::zeroInitialized(max+1); for(const auto& attachment: attachments) _attachments[attachment.first] = GLenum(attachment.second); (this->*Context::current()->state().framebuffer->drawBuffersImplementation)(max+1, _attachments); return *this; } Framebuffer& Framebuffer::mapForDraw(const DrawAttachment attachment) { (this->*Context::current()->state().framebuffer->drawBufferImplementation)(GLenum(attachment)); return *this; } Framebuffer& Framebuffer::mapForRead(const ColorAttachment attachment) { (this->*Context::current()->state().framebuffer->readBufferImplementation)(GLenum(attachment)); return *this; } void Framebuffer::invalidate(std::initializer_list<InvalidationAttachment> attachments) { /** @todo C++14: use VLA to avoid heap allocation */ Containers::Array<GLenum> _attachments(attachments.size()); for(std::size_t i = 0; i != attachments.size(); ++i) _attachments[i] = GLenum(*(attachments.begin()+i)); (this->*Context::current()->state().framebuffer->invalidateImplementation)(attachments.size(), _attachments); } #ifndef MAGNUM_TARGET_GLES2 void Framebuffer::invalidate(std::initializer_list<InvalidationAttachment> attachments, const Range2Di& rectangle) { /** @todo C++14: use VLA to avoid heap allocation */ Containers::Array<GLenum> _attachments(attachments.size()); for(std::size_t i = 0; i != attachments.size(); ++i) _attachments[i] = GLenum(*(attachments.begin()+i)); (this->*Context::current()->state().framebuffer->invalidateSubImplementation)(attachments.size(), _attachments, rectangle); } #endif Framebuffer& Framebuffer::attachRenderbuffer(const BufferAttachment attachment, Renderbuffer& renderbuffer) { (this->*Context::current()->state().framebuffer->renderbufferImplementation)(attachment, renderbuffer); return *this; } #ifndef MAGNUM_TARGET_GLES Framebuffer& Framebuffer::attachTexture(const BufferAttachment attachment, Texture1D& texture, const Int level) { (this->*Context::current()->state().framebuffer->texture1DImplementation)(attachment, texture.id(), level); return *this; } #endif Framebuffer& Framebuffer::attachTexture(const BufferAttachment attachment, Texture2D& texture, const Int level) { (this->*Context::current()->state().framebuffer->texture2DImplementation)(attachment, GL_TEXTURE_2D, texture.id(), level); return *this; } #ifndef MAGNUM_TARGET_GLES Framebuffer& Framebuffer::attachTexture(const BufferAttachment attachment, RectangleTexture& texture) { (this->*Context::current()->state().framebuffer->texture2DImplementation)(attachment, GL_TEXTURE_RECTANGLE, texture.id(), 0); return *this; } #endif #ifndef MAGNUM_TARGET_GLES2 Framebuffer& Framebuffer::attachTexture(const BufferAttachment attachment, MultisampleTexture2D& texture) { (this->*Context::current()->state().framebuffer->texture2DImplementation)(attachment, GL_TEXTURE_2D_MULTISAMPLE, texture.id(), 0); return *this; } #endif Framebuffer& Framebuffer::attachCubeMapTexture(const BufferAttachment attachment, CubeMapTexture& texture, CubeMapTexture::Coordinate coordinate, const Int level) { (this->*Context::current()->state().framebuffer->texture2DImplementation)(attachment, GLenum(coordinate), texture.id(), level); return *this; } Framebuffer& Framebuffer::attachTextureLayer(Framebuffer::BufferAttachment attachment, Texture3D& texture, Int level, Int layer) { (this->*Context::current()->state().framebuffer->textureLayerImplementation)(attachment, texture.id(), level, layer); return *this; } #ifndef MAGNUM_TARGET_GLES Framebuffer& Framebuffer::attachTextureLayer(Framebuffer::BufferAttachment attachment, Texture1DArray& texture, Int level, Int layer) { (this->*Context::current()->state().framebuffer->textureLayerImplementation)(attachment, texture.id(), level, layer); return *this; } #endif #ifndef MAGNUM_TARGET_GLES2 Framebuffer& Framebuffer::attachTextureLayer(Framebuffer::BufferAttachment attachment, Texture2DArray& texture, Int level, Int layer) { (this->*Context::current()->state().framebuffer->textureLayerImplementation)(attachment, texture.id(), level, layer); return *this; } #endif #ifndef MAGNUM_TARGET_GLES Framebuffer& Framebuffer::attachTextureLayer(Framebuffer::BufferAttachment attachment, CubeMapTextureArray& texture, Int level, Int layer) { (this->*Context::current()->state().framebuffer->textureLayerImplementation)(attachment, texture.id(), level, layer); return *this; } Framebuffer& Framebuffer::attachTextureLayer(Framebuffer::BufferAttachment attachment, MultisampleTexture2DArray& texture, Int layer) { (this->*Context::current()->state().framebuffer->textureLayerImplementation)(attachment, texture.id(), 0, layer); return *this; } #endif #ifdef MAGNUM_BUILD_DEPRECATED Framebuffer& Framebuffer::attachTexture2D(BufferAttachment attachment, Texture2D& texture, Int mipLevel) { #ifdef __GNUC__ #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wdeprecated-declarations" #endif (this->*Context::current()->state().framebuffer->texture2DImplementation)(attachment, GLenum(texture.target()), texture.id(), mipLevel); #ifdef __GNUC__ #pragma GCC diagnostic pop #endif return *this; } #endif void Framebuffer::renderbufferImplementationDefault(BufferAttachment attachment, Renderbuffer& renderbuffer) { glFramebufferRenderbuffer(GLenum(bindInternal()), GLenum(attachment), GL_RENDERBUFFER, renderbuffer.id()); } #ifndef MAGNUM_TARGET_GLES void Framebuffer::renderbufferImplementationDSA(const BufferAttachment attachment, Renderbuffer& renderbuffer) { glNamedFramebufferRenderbuffer(_id, GLenum(attachment), GL_RENDERBUFFER, renderbuffer.id()); } void Framebuffer::renderbufferImplementationDSAEXT(BufferAttachment attachment, Renderbuffer& renderbuffer) { _created = true; glNamedFramebufferRenderbufferEXT(_id, GLenum(attachment), GL_RENDERBUFFER, renderbuffer.id()); } void Framebuffer::texture1DImplementationDefault(BufferAttachment attachment, GLuint textureId, GLint mipLevel) { glFramebufferTexture1D(GLenum(bindInternal()), GLenum(attachment), GL_TEXTURE_1D, textureId, mipLevel); } void Framebuffer::texture1DImplementationDSA(const BufferAttachment attachment, const GLuint textureId, const GLint mipLevel) { glNamedFramebufferTexture(_id, GLenum(attachment), textureId, mipLevel); } void Framebuffer::texture1DImplementationDSAEXT(BufferAttachment attachment, GLuint textureId, GLint mipLevel) { _created = true; glNamedFramebufferTexture1DEXT(_id, GLenum(attachment), GL_TEXTURE_1D, textureId, mipLevel); } #endif void Framebuffer::texture2DImplementationDefault(BufferAttachment attachment, GLenum textureTarget, GLuint textureId, GLint mipLevel) { glFramebufferTexture2D(GLenum(bindInternal()), GLenum(attachment), textureTarget, textureId, mipLevel); } #ifndef MAGNUM_TARGET_GLES void Framebuffer::texture2DImplementationDSA(const BufferAttachment attachment, GLenum, const GLuint textureId, const GLint mipLevel) { glNamedFramebufferTexture(_id, GLenum(attachment), textureId, mipLevel); } void Framebuffer::texture2DImplementationDSAEXT(BufferAttachment attachment, GLenum textureTarget, GLuint textureId, GLint mipLevel) { _created = true; glNamedFramebufferTexture2DEXT(_id, GLenum(attachment), textureTarget, textureId, mipLevel); } #endif void Framebuffer::textureLayerImplementationDefault(BufferAttachment attachment, GLuint textureId, GLint mipLevel, GLint layer) { #ifndef MAGNUM_TARGET_GLES2 glFramebufferTextureLayer(GLenum(bindInternal()), GLenum(attachment), textureId, mipLevel, layer); #elif !defined(CORRADE_TARGET_EMSCRIPTEN) && !defined(CORRADE_TARGET_NACL) glFramebufferTexture3DOES(GLenum(bindInternal()), GLenum(attachment), GL_TEXTURE_3D_OES, textureId, mipLevel, layer); #else static_cast<void>(attachment); static_cast<void>(textureId); static_cast<void>(mipLevel); static_cast<void>(layer); CORRADE_ASSERT_UNREACHABLE(); #endif } #ifndef MAGNUM_TARGET_GLES void Framebuffer::textureLayerImplementationDSA(const BufferAttachment attachment, const GLuint textureId, const GLint mipLevel, const GLint layer) { glNamedFramebufferTextureLayer(_id, GLenum(attachment), textureId, mipLevel, layer); } void Framebuffer::textureLayerImplementationDSAEXT(BufferAttachment attachment, GLuint textureId, GLint mipLevel, GLint layer) { _created = true; glNamedFramebufferTextureLayerEXT(_id, GLenum(attachment), textureId, mipLevel, layer); } #endif #ifndef DOXYGEN_GENERATING_OUTPUT Debug operator<<(Debug debug, const Framebuffer::Status value) { switch(value) { #define _c(value) case Framebuffer::Status::value: return debug << "Framebuffer::Status::" #value; _c(Complete) _c(IncompleteAttachment) _c(IncompleteMissingAttachment) #ifndef MAGNUM_TARGET_GLES _c(IncompleteDrawBuffer) _c(IncompleteReadBuffer) #endif _c(Unsupported) _c(IncompleteMultisample) #ifndef MAGNUM_TARGET_GLES _c(IncompleteLayerTargets) #endif #undef _c } return debug << "Framebuffer::Status::(invalid)"; } #endif } <commit_msg>Disable the deprecation warning also for MSVC.<commit_after>/* This file is part of Magnum. Copyright © 2010, 2011, 2012, 2013, 2014, 2015 Vladimír Vondruš <mosra@centrum.cz> 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 "Framebuffer.h" #include <Corrade/Containers/Array.h> #include "Magnum/Context.h" #include "Magnum/DefaultFramebuffer.h" #include "Magnum/Extensions.h" #include "Magnum/Image.h" #include "Magnum/Renderbuffer.h" #include "Magnum/Texture.h" #ifndef MAGNUM_TARGET_GLES2 #include "Magnum/BufferImage.h" #include "Magnum/MultisampleTexture.h" #include "Magnum/TextureArray.h" #endif #ifndef MAGNUM_TARGET_GLES #include "Magnum/CubeMapTextureArray.h" #include "Magnum/RectangleTexture.h" #endif #include "Implementation/DebugState.h" #include "Implementation/State.h" #include "Implementation/FramebufferState.h" namespace Magnum { const Framebuffer::DrawAttachment Framebuffer::DrawAttachment::None = Framebuffer::DrawAttachment(GL_NONE); const Framebuffer::BufferAttachment Framebuffer::BufferAttachment::Depth = Framebuffer::BufferAttachment(GL_DEPTH_ATTACHMENT); const Framebuffer::BufferAttachment Framebuffer::BufferAttachment::Stencil = Framebuffer::BufferAttachment(GL_STENCIL_ATTACHMENT); #ifndef MAGNUM_TARGET_GLES2 const Framebuffer::BufferAttachment Framebuffer::BufferAttachment::DepthStencil = Framebuffer::BufferAttachment(GL_DEPTH_STENCIL_ATTACHMENT); #endif const Framebuffer::InvalidationAttachment Framebuffer::InvalidationAttachment::Depth = Framebuffer::InvalidationAttachment(GL_DEPTH_ATTACHMENT); const Framebuffer::InvalidationAttachment Framebuffer::InvalidationAttachment::Stencil = Framebuffer::InvalidationAttachment(GL_STENCIL_ATTACHMENT); Int Framebuffer::maxColorAttachments() { #ifdef MAGNUM_TARGET_GLES2 if(!Context::current()->isExtensionSupported<Extensions::GL::NV::fbo_color_attachments>()) return 0; #endif GLint& value = Context::current()->state().framebuffer->maxColorAttachments; if(value == 0) { #ifndef MAGNUM_TARGET_GLES2 glGetIntegerv(GL_MAX_COLOR_ATTACHMENTS, &value); #else glGetIntegerv(GL_MAX_COLOR_ATTACHMENTS_NV, &value); #endif } return value; } Framebuffer::Framebuffer(const Range2Di& viewport) { CORRADE_INTERNAL_ASSERT(viewport != Implementation::FramebufferState::DisengagedViewport); _viewport = viewport; (this->*Context::current()->state().framebuffer->createImplementation)(); CORRADE_INTERNAL_ASSERT(_id != Implementation::State::DisengagedBinding); } void Framebuffer::createImplementationDefault() { glGenFramebuffers(1, &_id); _created = false; } #ifndef MAGNUM_TARGET_GLES void Framebuffer::createImplementationDSA() { glCreateFramebuffers(1, &_id); _created = true; } #endif Framebuffer::~Framebuffer() { /* Moved out, nothing to do */ if(!_id) return; /* If bound, remove itself from state */ Implementation::FramebufferState& state = *Context::current()->state().framebuffer; if(state.readBinding == _id) state.readBinding = 0; /* For draw binding reset also viewport */ if(state.drawBinding == _id) { state.drawBinding = 0; /** * @todo Less ugly solution (need to call setViewportInternal() to * reset the viewport to size of default framebuffer) */ defaultFramebuffer.bind(); } glDeleteFramebuffers(1, &_id); } std::string Framebuffer::label() { createIfNotAlready(); return Context::current()->state().debug->getLabelImplementation(GL_FRAMEBUFFER, _id); } Framebuffer& Framebuffer::setLabelInternal(const Containers::ArrayReference<const char> label) { createIfNotAlready(); Context::current()->state().debug->labelImplementation(GL_FRAMEBUFFER, _id, label); return *this; } Framebuffer::Status Framebuffer::checkStatus(const FramebufferTarget target) { return Status((this->*Context::current()->state().framebuffer->checkStatusImplementation)(target)); } Framebuffer& Framebuffer::mapForDraw(std::initializer_list<std::pair<UnsignedInt, DrawAttachment>> attachments) { /* Max attachment location */ std::size_t max = 0; for(const auto& attachment: attachments) if(attachment.first > max) max = attachment.first; /* Create linear array from associative */ /** @todo C++14: use VLA to avoid heap allocation */ static_assert(GL_NONE == 0, "Expecting zero GL_NONE for zero-initialization"); auto _attachments = Containers::Array<GLenum>::zeroInitialized(max+1); for(const auto& attachment: attachments) _attachments[attachment.first] = GLenum(attachment.second); (this->*Context::current()->state().framebuffer->drawBuffersImplementation)(max+1, _attachments); return *this; } Framebuffer& Framebuffer::mapForDraw(const DrawAttachment attachment) { (this->*Context::current()->state().framebuffer->drawBufferImplementation)(GLenum(attachment)); return *this; } Framebuffer& Framebuffer::mapForRead(const ColorAttachment attachment) { (this->*Context::current()->state().framebuffer->readBufferImplementation)(GLenum(attachment)); return *this; } void Framebuffer::invalidate(std::initializer_list<InvalidationAttachment> attachments) { /** @todo C++14: use VLA to avoid heap allocation */ Containers::Array<GLenum> _attachments(attachments.size()); for(std::size_t i = 0; i != attachments.size(); ++i) _attachments[i] = GLenum(*(attachments.begin()+i)); (this->*Context::current()->state().framebuffer->invalidateImplementation)(attachments.size(), _attachments); } #ifndef MAGNUM_TARGET_GLES2 void Framebuffer::invalidate(std::initializer_list<InvalidationAttachment> attachments, const Range2Di& rectangle) { /** @todo C++14: use VLA to avoid heap allocation */ Containers::Array<GLenum> _attachments(attachments.size()); for(std::size_t i = 0; i != attachments.size(); ++i) _attachments[i] = GLenum(*(attachments.begin()+i)); (this->*Context::current()->state().framebuffer->invalidateSubImplementation)(attachments.size(), _attachments, rectangle); } #endif Framebuffer& Framebuffer::attachRenderbuffer(const BufferAttachment attachment, Renderbuffer& renderbuffer) { (this->*Context::current()->state().framebuffer->renderbufferImplementation)(attachment, renderbuffer); return *this; } #ifndef MAGNUM_TARGET_GLES Framebuffer& Framebuffer::attachTexture(const BufferAttachment attachment, Texture1D& texture, const Int level) { (this->*Context::current()->state().framebuffer->texture1DImplementation)(attachment, texture.id(), level); return *this; } #endif Framebuffer& Framebuffer::attachTexture(const BufferAttachment attachment, Texture2D& texture, const Int level) { (this->*Context::current()->state().framebuffer->texture2DImplementation)(attachment, GL_TEXTURE_2D, texture.id(), level); return *this; } #ifndef MAGNUM_TARGET_GLES Framebuffer& Framebuffer::attachTexture(const BufferAttachment attachment, RectangleTexture& texture) { (this->*Context::current()->state().framebuffer->texture2DImplementation)(attachment, GL_TEXTURE_RECTANGLE, texture.id(), 0); return *this; } #endif #ifndef MAGNUM_TARGET_GLES2 Framebuffer& Framebuffer::attachTexture(const BufferAttachment attachment, MultisampleTexture2D& texture) { (this->*Context::current()->state().framebuffer->texture2DImplementation)(attachment, GL_TEXTURE_2D_MULTISAMPLE, texture.id(), 0); return *this; } #endif Framebuffer& Framebuffer::attachCubeMapTexture(const BufferAttachment attachment, CubeMapTexture& texture, CubeMapTexture::Coordinate coordinate, const Int level) { (this->*Context::current()->state().framebuffer->texture2DImplementation)(attachment, GLenum(coordinate), texture.id(), level); return *this; } Framebuffer& Framebuffer::attachTextureLayer(Framebuffer::BufferAttachment attachment, Texture3D& texture, Int level, Int layer) { (this->*Context::current()->state().framebuffer->textureLayerImplementation)(attachment, texture.id(), level, layer); return *this; } #ifndef MAGNUM_TARGET_GLES Framebuffer& Framebuffer::attachTextureLayer(Framebuffer::BufferAttachment attachment, Texture1DArray& texture, Int level, Int layer) { (this->*Context::current()->state().framebuffer->textureLayerImplementation)(attachment, texture.id(), level, layer); return *this; } #endif #ifndef MAGNUM_TARGET_GLES2 Framebuffer& Framebuffer::attachTextureLayer(Framebuffer::BufferAttachment attachment, Texture2DArray& texture, Int level, Int layer) { (this->*Context::current()->state().framebuffer->textureLayerImplementation)(attachment, texture.id(), level, layer); return *this; } #endif #ifndef MAGNUM_TARGET_GLES Framebuffer& Framebuffer::attachTextureLayer(Framebuffer::BufferAttachment attachment, CubeMapTextureArray& texture, Int level, Int layer) { (this->*Context::current()->state().framebuffer->textureLayerImplementation)(attachment, texture.id(), level, layer); return *this; } Framebuffer& Framebuffer::attachTextureLayer(Framebuffer::BufferAttachment attachment, MultisampleTexture2DArray& texture, Int layer) { (this->*Context::current()->state().framebuffer->textureLayerImplementation)(attachment, texture.id(), 0, layer); return *this; } #endif #ifdef MAGNUM_BUILD_DEPRECATED #ifdef _MSC_VER #pragma warning(push) #pragma warning(disable: 4996) /* deprecated warning */ #endif Framebuffer& Framebuffer::attachTexture2D(BufferAttachment attachment, Texture2D& texture, Int mipLevel) { #ifdef __GNUC__ #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wdeprecated-declarations" #endif (this->*Context::current()->state().framebuffer->texture2DImplementation)(attachment, GLenum(texture.target()), texture.id(), mipLevel); #ifdef __GNUC__ #pragma GCC diagnostic pop #endif return *this; } #ifdef _MSC_VER #pragma warning(pop) #endif #endif void Framebuffer::renderbufferImplementationDefault(BufferAttachment attachment, Renderbuffer& renderbuffer) { glFramebufferRenderbuffer(GLenum(bindInternal()), GLenum(attachment), GL_RENDERBUFFER, renderbuffer.id()); } #ifndef MAGNUM_TARGET_GLES void Framebuffer::renderbufferImplementationDSA(const BufferAttachment attachment, Renderbuffer& renderbuffer) { glNamedFramebufferRenderbuffer(_id, GLenum(attachment), GL_RENDERBUFFER, renderbuffer.id()); } void Framebuffer::renderbufferImplementationDSAEXT(BufferAttachment attachment, Renderbuffer& renderbuffer) { _created = true; glNamedFramebufferRenderbufferEXT(_id, GLenum(attachment), GL_RENDERBUFFER, renderbuffer.id()); } void Framebuffer::texture1DImplementationDefault(BufferAttachment attachment, GLuint textureId, GLint mipLevel) { glFramebufferTexture1D(GLenum(bindInternal()), GLenum(attachment), GL_TEXTURE_1D, textureId, mipLevel); } void Framebuffer::texture1DImplementationDSA(const BufferAttachment attachment, const GLuint textureId, const GLint mipLevel) { glNamedFramebufferTexture(_id, GLenum(attachment), textureId, mipLevel); } void Framebuffer::texture1DImplementationDSAEXT(BufferAttachment attachment, GLuint textureId, GLint mipLevel) { _created = true; glNamedFramebufferTexture1DEXT(_id, GLenum(attachment), GL_TEXTURE_1D, textureId, mipLevel); } #endif void Framebuffer::texture2DImplementationDefault(BufferAttachment attachment, GLenum textureTarget, GLuint textureId, GLint mipLevel) { glFramebufferTexture2D(GLenum(bindInternal()), GLenum(attachment), textureTarget, textureId, mipLevel); } #ifndef MAGNUM_TARGET_GLES void Framebuffer::texture2DImplementationDSA(const BufferAttachment attachment, GLenum, const GLuint textureId, const GLint mipLevel) { glNamedFramebufferTexture(_id, GLenum(attachment), textureId, mipLevel); } void Framebuffer::texture2DImplementationDSAEXT(BufferAttachment attachment, GLenum textureTarget, GLuint textureId, GLint mipLevel) { _created = true; glNamedFramebufferTexture2DEXT(_id, GLenum(attachment), textureTarget, textureId, mipLevel); } #endif void Framebuffer::textureLayerImplementationDefault(BufferAttachment attachment, GLuint textureId, GLint mipLevel, GLint layer) { #ifndef MAGNUM_TARGET_GLES2 glFramebufferTextureLayer(GLenum(bindInternal()), GLenum(attachment), textureId, mipLevel, layer); #elif !defined(CORRADE_TARGET_EMSCRIPTEN) && !defined(CORRADE_TARGET_NACL) glFramebufferTexture3DOES(GLenum(bindInternal()), GLenum(attachment), GL_TEXTURE_3D_OES, textureId, mipLevel, layer); #else static_cast<void>(attachment); static_cast<void>(textureId); static_cast<void>(mipLevel); static_cast<void>(layer); CORRADE_ASSERT_UNREACHABLE(); #endif } #ifndef MAGNUM_TARGET_GLES void Framebuffer::textureLayerImplementationDSA(const BufferAttachment attachment, const GLuint textureId, const GLint mipLevel, const GLint layer) { glNamedFramebufferTextureLayer(_id, GLenum(attachment), textureId, mipLevel, layer); } void Framebuffer::textureLayerImplementationDSAEXT(BufferAttachment attachment, GLuint textureId, GLint mipLevel, GLint layer) { _created = true; glNamedFramebufferTextureLayerEXT(_id, GLenum(attachment), textureId, mipLevel, layer); } #endif #ifndef DOXYGEN_GENERATING_OUTPUT Debug operator<<(Debug debug, const Framebuffer::Status value) { switch(value) { #define _c(value) case Framebuffer::Status::value: return debug << "Framebuffer::Status::" #value; _c(Complete) _c(IncompleteAttachment) _c(IncompleteMissingAttachment) #ifndef MAGNUM_TARGET_GLES _c(IncompleteDrawBuffer) _c(IncompleteReadBuffer) #endif _c(Unsupported) _c(IncompleteMultisample) #ifndef MAGNUM_TARGET_GLES _c(IncompleteLayerTargets) #endif #undef _c } return debug << "Framebuffer::Status::(invalid)"; } #endif } <|endoftext|>
<commit_before>/** * Templated default configuration */ const char* config_template = R"( static_resources: listeners: - name: base_api_listener address: socket_address: protocol: TCP address: 0.0.0.0 port_value: 10000 api_listener: api_listener: "@type": type.googleapis.com/envoy.extensions.filters.network.http_connection_manager.v3.HttpConnectionManager stat_prefix: hcm route_config: name: api_router virtual_hosts: - name: api domains: - "*" routes: - match: prefix: "/" route: cluster_header: x-envoy-mobile-cluster retry_policy: retry_back_off: base_interval: 0.25s max_interval: 60s http_filters: - name: envoy.filters.http.dynamic_forward_proxy typed_config: "@type": type.googleapis.com/envoy.extensions.filters.http.dynamic_forward_proxy.v3.FilterConfig dns_cache_config: &dns_cache_config name: dynamic_forward_proxy_cache_config dns_lookup_family: AUTO dns_refresh_rate: {{ dns_refresh_rate_seconds }}s dns_failure_refresh_rate: base_interval: {{ dns_failure_refresh_rate_seconds_base }}s max_interval: {{ dns_failure_refresh_rate_seconds_max }}s - name: envoy.router typed_config: "@type": type.googleapis.com/envoy.extensions.filters.http.router.v3.Router clusters: - name: base connect_timeout: {{ connect_timeout_seconds }}s lb_policy: CLUSTER_PROVIDED cluster_type: name: envoy.clusters.dynamic_forward_proxy typed_config: "@type": type.googleapis.com/envoy.extensions.clusters.dynamic_forward_proxy.v3.ClusterConfig dns_cache_config: *dns_cache_config transport_socket: &base_transport_socket name: envoy.transport_sockets.tls typed_config: "@type": type.googleapis.com/envoy.extensions.transport_sockets.tls.v3.UpstreamTlsContext common_tls_context: validation_context: trusted_ca: inline_string: | )" #include "certificates.inc" R"( upstream_connection_options: &upstream_opts tcp_keepalive: keepalive_interval: 10 keepalive_probes: 1 keepalive_time: 5 - name: base_wlan connect_timeout: {{ connect_timeout_seconds }}s lb_policy: CLUSTER_PROVIDED cluster_type: name: envoy.clusters.dynamic_forward_proxy typed_config: "@type": type.googleapis.com/envoy.extensions.clusters.dynamic_forward_proxy.v3.ClusterConfig dns_cache_config: *dns_cache_config transport_socket: *base_transport_socket upstream_connection_options: *upstream_opts - name: base_wwan connect_timeout: {{ connect_timeout_seconds }}s lb_policy: CLUSTER_PROVIDED cluster_type: name: envoy.clusters.dynamic_forward_proxy typed_config: "@type": type.googleapis.com/envoy.extensions.clusters.dynamic_forward_proxy.v3.ClusterConfig dns_cache_config: *dns_cache_config transport_socket: *base_transport_socket upstream_connection_options: *upstream_opts - name: base_h2 http2_protocol_options: {} connect_timeout: {{ connect_timeout_seconds }}s lb_policy: CLUSTER_PROVIDED cluster_type: name: envoy.clusters.dynamic_forward_proxy typed_config: "@type": type.googleapis.com/envoy.extensions.clusters.dynamic_forward_proxy.v3.ClusterConfig dns_cache_config: *dns_cache_config transport_socket: *base_transport_socket upstream_connection_options: *upstream_opts - name: base_wlan_h2 http2_protocol_options: {} connect_timeout: {{ connect_timeout_seconds }}s lb_policy: CLUSTER_PROVIDED cluster_type: name: envoy.clusters.dynamic_forward_proxy typed_config: "@type": type.googleapis.com/envoy.extensions.clusters.dynamic_forward_proxy.v3.ClusterConfig dns_cache_config: *dns_cache_config transport_socket: *base_transport_socket upstream_connection_options: *upstream_opts - name: base_wwan_h2 http2_protocol_options: {} connect_timeout: {{ connect_timeout_seconds }}s lb_policy: CLUSTER_PROVIDED cluster_type: name: envoy.clusters.dynamic_forward_proxy typed_config: "@type": type.googleapis.com/envoy.extensions.clusters.dynamic_forward_proxy.v3.ClusterConfig dns_cache_config: *dns_cache_config transport_socket: *base_transport_socket upstream_connection_options: *upstream_opts - name: stats connect_timeout: {{ connect_timeout_seconds }}s dns_refresh_rate: {{ dns_refresh_rate_seconds }}s http2_protocol_options: {} lb_policy: ROUND_ROBIN load_assignment: cluster_name: stats endpoints: - lb_endpoints: - endpoint: address: socket_address: {address: {{ stats_domain }}, port_value: 443} transport_socket: *base_transport_socket type: LOGICAL_DNS stats_flush_interval: {{ stats_flush_interval_seconds }}s stats_sinks: - name: envoy.metrics_service typed_config: "@type": type.googleapis.com/envoy.config.metrics.v3.MetricsServiceConfig grpc_service: envoy_grpc: cluster_name: stats stats_config: stats_matcher: inclusion_list: patterns: - safe_regex: google_re2: {} regex: 'cluster\.[\w]+?\.upstream_rq_total' - safe_regex: google_re2: {} regex: 'cluster\.[\w]+?\.upstream_cx_active' - safe_regex: google_re2: {} regex: 'cluster\.[\w]+?\.upstream_rq_time' watchdog: megamiss_timeout: 60s miss_timeout: 60s node: metadata: os: {{ device_os }} )"; <commit_msg>stats: emit stats for retries (#718)<commit_after>/** * Templated default configuration */ const char* config_template = R"( static_resources: listeners: - name: base_api_listener address: socket_address: protocol: TCP address: 0.0.0.0 port_value: 10000 api_listener: api_listener: "@type": type.googleapis.com/envoy.extensions.filters.network.http_connection_manager.v3.HttpConnectionManager stat_prefix: hcm route_config: name: api_router virtual_hosts: - name: api domains: - "*" routes: - match: prefix: "/" route: cluster_header: x-envoy-mobile-cluster retry_policy: retry_back_off: base_interval: 0.25s max_interval: 60s http_filters: - name: envoy.filters.http.dynamic_forward_proxy typed_config: "@type": type.googleapis.com/envoy.extensions.filters.http.dynamic_forward_proxy.v3.FilterConfig dns_cache_config: &dns_cache_config name: dynamic_forward_proxy_cache_config dns_lookup_family: AUTO dns_refresh_rate: {{ dns_refresh_rate_seconds }}s dns_failure_refresh_rate: base_interval: {{ dns_failure_refresh_rate_seconds_base }}s max_interval: {{ dns_failure_refresh_rate_seconds_max }}s - name: envoy.router typed_config: "@type": type.googleapis.com/envoy.extensions.filters.http.router.v3.Router clusters: - name: base connect_timeout: {{ connect_timeout_seconds }}s lb_policy: CLUSTER_PROVIDED cluster_type: name: envoy.clusters.dynamic_forward_proxy typed_config: "@type": type.googleapis.com/envoy.extensions.clusters.dynamic_forward_proxy.v3.ClusterConfig dns_cache_config: *dns_cache_config transport_socket: &base_transport_socket name: envoy.transport_sockets.tls typed_config: "@type": type.googleapis.com/envoy.extensions.transport_sockets.tls.v3.UpstreamTlsContext common_tls_context: validation_context: trusted_ca: inline_string: | )" #include "certificates.inc" R"( upstream_connection_options: &upstream_opts tcp_keepalive: keepalive_interval: 10 keepalive_probes: 1 keepalive_time: 5 - name: base_wlan connect_timeout: {{ connect_timeout_seconds }}s lb_policy: CLUSTER_PROVIDED cluster_type: name: envoy.clusters.dynamic_forward_proxy typed_config: "@type": type.googleapis.com/envoy.extensions.clusters.dynamic_forward_proxy.v3.ClusterConfig dns_cache_config: *dns_cache_config transport_socket: *base_transport_socket upstream_connection_options: *upstream_opts - name: base_wwan connect_timeout: {{ connect_timeout_seconds }}s lb_policy: CLUSTER_PROVIDED cluster_type: name: envoy.clusters.dynamic_forward_proxy typed_config: "@type": type.googleapis.com/envoy.extensions.clusters.dynamic_forward_proxy.v3.ClusterConfig dns_cache_config: *dns_cache_config transport_socket: *base_transport_socket upstream_connection_options: *upstream_opts - name: base_h2 http2_protocol_options: {} connect_timeout: {{ connect_timeout_seconds }}s lb_policy: CLUSTER_PROVIDED cluster_type: name: envoy.clusters.dynamic_forward_proxy typed_config: "@type": type.googleapis.com/envoy.extensions.clusters.dynamic_forward_proxy.v3.ClusterConfig dns_cache_config: *dns_cache_config transport_socket: *base_transport_socket upstream_connection_options: *upstream_opts - name: base_wlan_h2 http2_protocol_options: {} connect_timeout: {{ connect_timeout_seconds }}s lb_policy: CLUSTER_PROVIDED cluster_type: name: envoy.clusters.dynamic_forward_proxy typed_config: "@type": type.googleapis.com/envoy.extensions.clusters.dynamic_forward_proxy.v3.ClusterConfig dns_cache_config: *dns_cache_config transport_socket: *base_transport_socket upstream_connection_options: *upstream_opts - name: base_wwan_h2 http2_protocol_options: {} connect_timeout: {{ connect_timeout_seconds }}s lb_policy: CLUSTER_PROVIDED cluster_type: name: envoy.clusters.dynamic_forward_proxy typed_config: "@type": type.googleapis.com/envoy.extensions.clusters.dynamic_forward_proxy.v3.ClusterConfig dns_cache_config: *dns_cache_config transport_socket: *base_transport_socket upstream_connection_options: *upstream_opts - name: stats connect_timeout: {{ connect_timeout_seconds }}s dns_refresh_rate: {{ dns_refresh_rate_seconds }}s http2_protocol_options: {} lb_policy: ROUND_ROBIN load_assignment: cluster_name: stats endpoints: - lb_endpoints: - endpoint: address: socket_address: {address: {{ stats_domain }}, port_value: 443} transport_socket: *base_transport_socket type: LOGICAL_DNS stats_flush_interval: {{ stats_flush_interval_seconds }}s stats_sinks: - name: envoy.metrics_service typed_config: "@type": type.googleapis.com/envoy.config.metrics.v3.MetricsServiceConfig grpc_service: envoy_grpc: cluster_name: stats stats_config: stats_matcher: inclusion_list: patterns: - safe_regex: google_re2: {} regex: 'cluster\.[\w]+?\.upstream_cx_active' - safe_regex: google_re2: {} regex: 'cluster\.[\w]+?\.upstream_rq_retry' - safe_regex: google_re2: {} regex: 'cluster\.[\w]+?\.upstream_rq_retry_overflow' - safe_regex: google_re2: {} regex: 'cluster\.[\w]+?\.upstream_rq_retry_success' - safe_regex: google_re2: {} regex: 'cluster\.[\w]+?\.upstream_rq_time' - safe_regex: google_re2: {} regex: 'cluster\.[\w]+?\.upstream_rq_total' watchdog: megamiss_timeout: 60s miss_timeout: 60s node: metadata: os: {{ device_os }} )"; <|endoftext|>
<commit_before>#ifndef _SDD_VALUES_UNIQUE_FLAT_SET_HH_ #define _SDD_VALUES_UNIQUE_FLAT_SET_HH_ #include <algorithm> // copy, set_difference, set_intersection, set_union #include <functional> // hash #include <initializer_list> #include <iosfwd> #include <iterator> // inserter #include <utility> // pair #include <boost/container/flat_set.hpp> #include <boost/intrusive/unordered_set.hpp> #include "sdd/util/hash.hh" namespace sdd { namespace values { /*------------------------------------------------------------------------------------------------*/ /// @brief A unified set of values, implemented with a sorted vector. template <typename Value> class unique_flat_set { public: /// @brief The type of the real container. typedef boost::container::flat_set<Value> flat_set_type; /// @brief The type of the contained value. typedef Value value_type; private: /// @brief Faster, unsafe mode for Boost.Intrusive. typedef boost::intrusive::link_mode<boost::intrusive::normal_link> link_mode; /// @brief An entry in the unique table of set of values. struct entry : public boost::intrusive::unordered_set_base_hook<link_mode> { // Can't copy an entry. entry(const entry&) = delete; entry& operator=(const entry&) = delete; /// @brief The unified flat set. const flat_set_type data; /// @brief Constructor. template <typename... Args> entry(Args&&... args) : data(std::forward<Args>(args)...) { } /// @brief Comparison. bool operator==(const entry& other) const noexcept { return data == other.data; } }; /// @brief Hash an entry. struct hash { std::size_t operator()(const entry& e) const noexcept { std::size_t seed = 0; for (const auto& v : e.data) { util::hash_combine(seed, v); } return seed; } }; /// @brief The type of the set of flat sets. typedef typename boost::intrusive::make_unordered_set<entry, boost::intrusive::hash<hash>>::type set_type; typedef typename set_type::bucket_type bucket_type; typedef typename set_type::bucket_traits bucket_traits; /// @brief A pointer to the unified set of values. const flat_set_type* data_; public: /// @brief The type of an iterator on a flat set of values. typedef typename flat_set_type::const_iterator const_iterator; /// @brief Default constructor. unique_flat_set() : data_(empty_set()) { } /// @brief Constructor with a range. template <typename InputIterator> unique_flat_set(InputIterator begin, InputIterator end) : data_(unify(begin, end)) { } /// @brief Constructor with a initializer_list. unique_flat_set(std::initializer_list<Value> values) : unique_flat_set(values.begin(), values.end()) { } /// @brief Constructor from a temporary flat_set_type. unique_flat_set(flat_set_type&& fs) : data_(unify(std::move(fs))) { } unique_flat_set(const unique_flat_set&) = default; unique_flat_set& operator=(const unique_flat_set&) = default; unique_flat_set(unique_flat_set&&) = default; unique_flat_set& operator=(unique_flat_set&&) = default; /// @brief Insert a value. void insert(const Value& x) { flat_set_type s(*data_); const auto insertion = s.insert(x); if (insertion.second) { data_ = unify(std::move(s)); } } /// @brief Get the beginning of this set of values. const_iterator cbegin() const noexcept { return data_->cbegin(); } /// @brief Get the end of this set of values. const_iterator cend() const noexcept { return data_->cend(); } /// @brief Tell if this set of values is empty. bool empty() const noexcept { return data_->empty(); } /// @brief Get the number of contained values. std::size_t size() const noexcept { return data_->size(); } /// @brief Find a value. const_iterator find(const Value& x) const { return data_->find(x); } /// @brief Erase a value. std::size_t erase(const Value& x) { flat_set_type fs(*data_); const std::size_t nb_erased = fs.erase(x); unify(std::move(fs)); return nb_erased; } /// @internal /// @brief Get the pointer to the unified data. const flat_set_type* const data() const noexcept { return data_; } private: /// @brief Help cleaning the static set. struct set_disposer { bucket_type* buckets; set_type* set; set_disposer(std::size_t size) : buckets(new bucket_type[size]) , set(new set_type(bucket_traits(buckets, size))) { } ~set_disposer() { set->clear_and_dispose([](entry* e){delete e;}); delete set; delete[] buckets; } }; /// @brief Get the static set of flat sets. static set_type& set() { static set_disposer disposer(32000); return *disposer.set; } /// @brief Get the static empty flat set. static const flat_set_type* empty_set() { static auto e = unify(flat_set_type()); return e; } /// @brief Unify a flat_set_type using a unique table. template <typename... Args> static const flat_set_type* unify(Args&&... args) { entry* ptr = new entry(std::forward<Args>(args)...); const auto insertion = set().insert(*ptr); if (not insertion.second) { delete ptr; } return &(insertion.first->data); } }; /*------------------------------------------------------------------------------------------------*/ /// @brief Equality of unique_flat_set /// @related unique_flat_set template <typename Value> inline bool operator==(const unique_flat_set<Value>& lhs, const unique_flat_set<Value>& rhs) noexcept { // Pointer equality. return lhs.data() == rhs.data(); } /*------------------------------------------------------------------------------------------------*/ /// @brief Comparison of unique_flat_set /// @related unique_flat_set /// /// The order on unique_flat_set is arbitrary. template <typename Value> inline bool operator<(const unique_flat_set<Value>& lhs, const unique_flat_set<Value>& rhs) noexcept { // Pointer comparison. return lhs.data() < rhs.data(); } /*------------------------------------------------------------------------------------------------*/ /// @brief Textual output of a unique_flat_set /// @related unique_flat_set template <typename Value> std::ostream& operator<<(std::ostream& os, const unique_flat_set<Value>& fs) { os << "{"; if (not fs.empty()) { std::copy(fs.cbegin(), std::prev(fs.cend()), std::ostream_iterator<Value>(os, ",")); os << *std::prev(fs.cend()); } return os << "}"; } /*------------------------------------------------------------------------------------------------*/ /// @related unique_flat_set template <typename Value> inline unique_flat_set<Value> difference(const unique_flat_set<Value>& lhs, const unique_flat_set<Value>& rhs) noexcept { typename unique_flat_set<Value>::flat_set_type res; std::set_difference( lhs.cbegin(), lhs.cend(), rhs.cbegin(), rhs.cend() , std::inserter(res, res.begin())); return unique_flat_set<Value>(std::move(res)); } /*------------------------------------------------------------------------------------------------*/ /// @related unique_flat_set template <typename Value> inline unique_flat_set<Value> intersection(const unique_flat_set<Value>& lhs, const unique_flat_set<Value>& rhs) noexcept { typename unique_flat_set<Value>::flat_set_type res; std::set_intersection( lhs.cbegin(), lhs.cend(), rhs.cbegin(), rhs.cend() , std::inserter(res, res.begin())); return unique_flat_set<Value>(std::move(res)); } /*------------------------------------------------------------------------------------------------*/ /// @related unique_flat_set template <typename Value> inline unique_flat_set<Value> sum(const unique_flat_set<Value>& lhs, const unique_flat_set<Value>& rhs) noexcept { typename unique_flat_set<Value>::flat_set_type res; std::set_union( lhs.cbegin(), lhs.cend(), rhs.cbegin(), rhs.cend() , std::inserter(res, res.begin())); return unique_flat_set<Value>(std::move(res)); } /*------------------------------------------------------------------------------------------------*/ }} // namespace sdd::values namespace std { /// @brief Hash specialization for sdd::values::flat_set template <typename Value> struct hash<sdd::values::unique_flat_set<Value>> { std::size_t operator()(const sdd::values::unique_flat_set<Value>& fs) const noexcept { return std::hash<decltype(fs.data())>()(fs.data()); } }; } // namespace std /*------------------------------------------------------------------------------------------------*/ #endif // _SDD_VALUES_UNIQUE_FLAT_SET_HH_ <commit_msg>More methods for unique_flat_set.<commit_after>#ifndef _SDD_VALUES_UNIQUE_FLAT_SET_HH_ #define _SDD_VALUES_UNIQUE_FLAT_SET_HH_ #include <algorithm> // copy, set_difference, set_intersection, set_union #include <functional> // hash #include <initializer_list> #include <iosfwd> #include <iterator> // inserter #include <utility> // pair #include <boost/container/flat_set.hpp> #include <boost/intrusive/unordered_set.hpp> #include "sdd/util/hash.hh" namespace sdd { namespace values { /*------------------------------------------------------------------------------------------------*/ /// @brief A unified set of values, implemented with a sorted vector. template <typename Value> class unique_flat_set { public: /// @brief The type of the real container. typedef boost::container::flat_set<Value> flat_set_type; /// @brief The type of the contained value. typedef Value value_type; private: /// @brief Faster, unsafe mode for Boost.Intrusive. typedef boost::intrusive::link_mode<boost::intrusive::normal_link> link_mode; /// @brief An entry in the unique table of set of values. struct entry : public boost::intrusive::unordered_set_base_hook<link_mode> { // Can't copy an entry. entry(const entry&) = delete; entry& operator=(const entry&) = delete; /// @brief The unified flat set. const flat_set_type data; /// @brief Constructor. template <typename... Args> entry(Args&&... args) : data(std::forward<Args>(args)...) { } /// @brief Comparison. bool operator==(const entry& other) const noexcept { return data == other.data; } }; /// @brief Hash an entry. struct hash { std::size_t operator()(const entry& e) const noexcept { std::size_t seed = 0; for (const auto& v : e.data) { util::hash_combine(seed, v); } return seed; } }; /// @brief The type of the set of flat sets. typedef typename boost::intrusive::make_unordered_set<entry, boost::intrusive::hash<hash>>::type set_type; typedef typename set_type::bucket_type bucket_type; typedef typename set_type::bucket_traits bucket_traits; /// @brief A pointer to the unified set of values. const flat_set_type* data_; public: /// @brief The type of an iterator on a flat set of values. typedef typename flat_set_type::const_iterator const_iterator; /// @brief Default constructor. unique_flat_set() : data_(empty_set()) { } /// @brief Constructor with a range. template <typename InputIterator> unique_flat_set(InputIterator begin, InputIterator end) : data_(unify(begin, end)) { } /// @brief Constructor with a initializer_list. unique_flat_set(std::initializer_list<Value> values) : unique_flat_set(values.begin(), values.end()) { } /// @brief Constructor from a temporary flat_set_type. unique_flat_set(flat_set_type&& fs) : data_(unify(std::move(fs))) { } unique_flat_set(const unique_flat_set&) = default; unique_flat_set& operator=(const unique_flat_set&) = default; unique_flat_set(unique_flat_set&&) = default; unique_flat_set& operator=(unique_flat_set&&) = default; /// @brief Insert a value. std::pair<const_iterator, bool> insert(const Value& x) { flat_set_type s(*data_); const auto insertion = s.insert(x); if (insertion.second) { s.shrink_to_fit(); data_ = unify(std::move(s)); } return insertion; } /// @brief const_iterator insert(const_iterator position, const Value& x) { flat_set_type s(*data_); const auto cit = s.insert(position, x); s.shrink_to_fit(); data_ = unify(std::move(s)); return cit; } /// @brief Get the beginning of this set of values. const_iterator begin() const noexcept { return data_->cbegin(); } /// @brief Get the end of this set of values. const_iterator end() const noexcept { return data_->cend(); } /// @brief Get the beginning of this set of values. const_iterator cbegin() const noexcept { return data_->cbegin(); } /// @brief Get the end of this set of values. const_iterator cend() const noexcept { return data_->cend(); } /// @brief Tell if this set of values is empty. bool empty() const noexcept { return data_->empty(); } /// @brief Get the number of contained values. std::size_t size() const noexcept { return data_->size(); } /// @brief Find a value. const_iterator find(const Value& x) const { return data_->find(x); } /// @brief Erase a value. std::size_t erase(const Value& x) { flat_set_type fs(*data_); const std::size_t nb_erased = fs.erase(x); unify(std::move(fs)); return nb_erased; } /// @brief const_iterator lower_bound(const Value& x) const { return data_->lower_bound(x); } /// @internal /// @brief Get the pointer to the unified data. const flat_set_type* const data() const noexcept { return data_; } private: /// @brief Help cleaning the static set. struct set_disposer { bucket_type* buckets; set_type* set; set_disposer(std::size_t size) : buckets(new bucket_type[size]) , set(new set_type(bucket_traits(buckets, size))) { } ~set_disposer() { set->clear_and_dispose([](entry* e){delete e;}); delete set; delete[] buckets; } }; /// @brief Get the static set of flat sets. static set_type& set() { static set_disposer disposer(32000); return *disposer.set; } /// @brief Get the static empty flat set. static const flat_set_type* empty_set() { static auto e = unify(flat_set_type()); return e; } /// @brief Unify a flat_set_type using a unique table. template <typename... Args> static const flat_set_type* unify(Args&&... args) { entry* ptr = new entry(std::forward<Args>(args)...); const auto insertion = set().insert(*ptr); if (not insertion.second) { delete ptr; } return &(insertion.first->data); } }; /*------------------------------------------------------------------------------------------------*/ /// @brief Equality of unique_flat_set /// @related unique_flat_set template <typename Value> inline bool operator==(const unique_flat_set<Value>& lhs, const unique_flat_set<Value>& rhs) noexcept { // Pointer equality. return lhs.data() == rhs.data(); } /*------------------------------------------------------------------------------------------------*/ /// @brief Comparison of unique_flat_set /// @related unique_flat_set /// /// The order on unique_flat_set is arbitrary. template <typename Value> inline bool operator<(const unique_flat_set<Value>& lhs, const unique_flat_set<Value>& rhs) noexcept { // Pointer comparison. return lhs.data() < rhs.data(); } /*------------------------------------------------------------------------------------------------*/ /// @brief Textual output of a unique_flat_set /// @related unique_flat_set template <typename Value> std::ostream& operator<<(std::ostream& os, const unique_flat_set<Value>& fs) { os << "{"; if (not fs.empty()) { std::copy(fs.cbegin(), std::prev(fs.cend()), std::ostream_iterator<Value>(os, ",")); os << *std::prev(fs.cend()); } return os << "}"; } /*------------------------------------------------------------------------------------------------*/ /// @related unique_flat_set template <typename Value> inline unique_flat_set<Value> difference(const unique_flat_set<Value>& lhs, const unique_flat_set<Value>& rhs) noexcept { typename unique_flat_set<Value>::flat_set_type res; std::set_difference( lhs.cbegin(), lhs.cend(), rhs.cbegin(), rhs.cend() , std::inserter(res, res.begin())); return unique_flat_set<Value>(std::move(res)); } /*------------------------------------------------------------------------------------------------*/ /// @related unique_flat_set template <typename Value> inline unique_flat_set<Value> intersection(const unique_flat_set<Value>& lhs, const unique_flat_set<Value>& rhs) noexcept { typename unique_flat_set<Value>::flat_set_type res; std::set_intersection( lhs.cbegin(), lhs.cend(), rhs.cbegin(), rhs.cend() , std::inserter(res, res.begin())); return unique_flat_set<Value>(std::move(res)); } /*------------------------------------------------------------------------------------------------*/ /// @related unique_flat_set template <typename Value> inline unique_flat_set<Value> sum(const unique_flat_set<Value>& lhs, const unique_flat_set<Value>& rhs) noexcept { typename unique_flat_set<Value>::flat_set_type res; std::set_union( lhs.cbegin(), lhs.cend(), rhs.cbegin(), rhs.cend() , std::inserter(res, res.begin())); return unique_flat_set<Value>(std::move(res)); } /*------------------------------------------------------------------------------------------------*/ }} // namespace sdd::values namespace std { /// @brief Hash specialization for sdd::values::flat_set template <typename Value> struct hash<sdd::values::unique_flat_set<Value>> { std::size_t operator()(const sdd::values::unique_flat_set<Value>& fs) const noexcept { return std::hash<decltype(fs.data())>()(fs.data()); } }; } // namespace std /*------------------------------------------------------------------------------------------------*/ #endif // _SDD_VALUES_UNIQUE_FLAT_SET_HH_ <|endoftext|>
<commit_before>/* vim:set noet ts=4: */ /* * ibus - The Input Bus * * Copyright (c) 2007-2008 Huang Peng <shawn.p.huang@gmail.com> * * 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 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 program; if not, write to the * Free Software Foundation, Inc., 59 Temple Place, Suite 330, * Boston, MA 02111-1307 USA */ #include <config.h> #include "ibus-input-context.h" #include "ibus-client.h" #include <QtDebug> #include <QInputMethodEvent> #include <QTextCharFormat> typedef QInputMethodEvent::Attribute QAttribute; IBusInputContext::IBusInputContext (QObject *parent, IBusClient *client, QString &ic) : QInputContext (parent), client (client), ic (ic), preedit_visible (false), has_focus (false) { } IBusInputContext::~IBusInputContext () { client->releaseInputContext (this); } bool IBusInputContext::filterEvent (const QEvent *event) { #ifndef Q_WS_X11 if (client->filterEvent (this, event)) return true; return QInputContext::filterEvent (event); #else return QInputContext::filterEvent (event); #endif } QFont IBusInputContext::font () const { return QInputContext::font (); } QString IBusInputContext::identifierName () { return QString ("ibus"); } QString IBusInputContext::language() { return QString (""); } void IBusInputContext::mouseHandler (int x, QMouseEvent *event) { client->mouseHandler (this, x, event); QInputContext::mouseHandler (x, event); } void IBusInputContext::reset() { client->reset (this); } void IBusInputContext::update () { QWidget *widget; if ((widget = focusWidget ()) == NULL) return; QRect rect = widget->inputMethodQuery(Qt::ImMicroFocus).toRect (); QPoint topleft = widget->mapToGlobal(QPoint(0,0)); rect.translate (topleft); client->setCursorLocation (this, rect); #if 0 QVariant value; qDebug () << "== update == "; value = widget->inputMethodQuery(Qt::ImMicroFocus); qDebug () << "Qt::ImMicroFocus " << value; value = widget->inputMethodQuery(Qt::ImFont); qDebug () << "Qt::ImFont " <<value; value = widget->inputMethodQuery(Qt::ImCursorPosition); qDebug () << "Qt::ImCursorPosition " << value; value = widget->inputMethodQuery(Qt::ImSurroundingText); qDebug () << "Qt::ImSurroundingText " << value; value = widget->inputMethodQuery(Qt::ImCurrentSelection); qDebug () << "Qt::ImCurrentSelection " << value; #endif } bool IBusInputContext::isComposing() const { return (!preedit_string.isEmpty ()) && preedit_visible; } void IBusInputContext::setFocusWidget (QWidget *widget) { QInputContext::setFocusWidget (widget); if (widget == NULL) { has_focus = false; client->focusOut (this); } else { /* KateView can not support preedit well. */ if (widget->inherits("KateViewInternal")) client->setCapabilities (this, 0); else client->setCapabilities (this, 1); has_focus = true; client->focusIn (this); update (); } } void IBusInputContext::widgetDestroyed (QWidget *widget) { if (has_focus) { client->focusOut (this); has_focus = false; } QInputContext::widgetDestroyed (widget); update (); } #ifdef Q_WS_X11 bool IBusInputContext::x11FilterEvent (QWidget *keywidget, XEvent *xevent) { if (has_focus && client->x11FilterEvent (this, keywidget, xevent)) return true; return QInputContext::x11FilterEvent (keywidget, xevent); } #endif void IBusInputContext::setIC (QString ic) { this->ic = ic; if (has_focus && !ic.isEmpty ()) { client->focusIn (this); } } QString IBusInputContext::getIC () { return ic; } void IBusInputContext::commitString (QString text) { QInputMethodEvent event; event.setCommitString (text); sendEvent (event); update (); } void IBusInputContext::updatePreedit (QString text, QList <QList <quint32> > attr_list, int cursor_pos, bool visible) { // qDebug () << text << cursor_pos << show; QList <QAttribute> qattrs; if (visible) { // append cursor pos qattrs.append (QAttribute (QInputMethodEvent::Cursor, cursor_pos, true, 0)); // append attributes for (QList <QList <quint32> >::iterator it = attr_list.begin (); it != attr_list.end(); ++ it) { QList <quint32> attr = *it; QTextCharFormat format; switch (attr[0]) { case 1: // underline format.setUnderlineStyle (QTextCharFormat::SingleUnderline); break; case 2: // foreground format.setForeground (QBrush (QColor (attr[1]))); break; case 3: // background format.setBackground (QBrush (QColor (attr[1]))); break; default: break; } qattrs.append (QAttribute (QInputMethodEvent::TextFormat, attr[2], attr[3] - attr[2], QVariant (format))); // qDebug () << attr[0] << attr[2] << attr[3] - attr[2]; } } else { qattrs.append (QAttribute (QInputMethodEvent::Cursor, 0, true, 0)); text = ""; cursor_pos = 0; } preedit_string = text; preedit_visible = visible; preedit_attrs = attr_list; preedit_cursor_pos = cursor_pos; QInputMethodEvent event (text, qattrs); sendEvent (event); update (); } void IBusInputContext::showPreedit () { if (preedit_visible) return; updatePreedit (preedit_string, preedit_attrs, preedit_cursor_pos, TRUE); } void IBusInputContext::hidePreedit () { if (!preedit_visible) return; updatePreedit (preedit_string, preedit_attrs, preedit_cursor_pos, FALSE); } <commit_msg>Call setFocusWidget to replace focusOut<commit_after>/* vim:set noet ts=4: */ /* * ibus - The Input Bus * * Copyright (c) 2007-2008 Huang Peng <shawn.p.huang@gmail.com> * * 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 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 program; if not, write to the * Free Software Foundation, Inc., 59 Temple Place, Suite 330, * Boston, MA 02111-1307 USA */ #include <config.h> #include "ibus-input-context.h" #include "ibus-client.h" #include <QtDebug> #include <QInputMethodEvent> #include <QTextCharFormat> typedef QInputMethodEvent::Attribute QAttribute; IBusInputContext::IBusInputContext (QObject *parent, IBusClient *client, QString &ic) : QInputContext (parent), client (client), ic (ic), preedit_visible (false), has_focus (false) { } IBusInputContext::~IBusInputContext () { client->releaseInputContext (this); } bool IBusInputContext::filterEvent (const QEvent *event) { #ifndef Q_WS_X11 if (client->filterEvent (this, event)) return true; return QInputContext::filterEvent (event); #else return QInputContext::filterEvent (event); #endif } QFont IBusInputContext::font () const { return QInputContext::font (); } QString IBusInputContext::identifierName () { return QString ("ibus"); } QString IBusInputContext::language() { return QString (""); } void IBusInputContext::mouseHandler (int x, QMouseEvent *event) { client->mouseHandler (this, x, event); QInputContext::mouseHandler (x, event); } void IBusInputContext::reset() { client->reset (this); } void IBusInputContext::update () { QWidget *widget = focusWidget (); if (widget == NULL) return; QRect rect = widget->inputMethodQuery(Qt::ImMicroFocus).toRect (); QPoint topleft = widget->mapToGlobal(QPoint(0,0)); rect.translate (topleft); client->setCursorLocation (this, rect); #if 0 QVariant value; qDebug () << "== update == "; value = widget->inputMethodQuery(Qt::ImMicroFocus); qDebug () << "Qt::ImMicroFocus " << value; value = widget->inputMethodQuery(Qt::ImFont); qDebug () << "Qt::ImFont " <<value; value = widget->inputMethodQuery(Qt::ImCursorPosition); qDebug () << "Qt::ImCursorPosition " << value; value = widget->inputMethodQuery(Qt::ImSurroundingText); qDebug () << "Qt::ImSurroundingText " << value; value = widget->inputMethodQuery(Qt::ImCurrentSelection); qDebug () << "Qt::ImCurrentSelection " << value; #endif } bool IBusInputContext::isComposing() const { return (!preedit_string.isEmpty ()) && preedit_visible; } void IBusInputContext::setFocusWidget (QWidget *widget) { QInputContext::setFocusWidget (widget); if (widget == NULL) { has_focus = false; client->focusOut (this); } else { /* KateView can not support preedit well. */ if (widget->inherits("KateViewInternal")) client->setCapabilities (this, 0); else client->setCapabilities (this, 1); has_focus = true; client->focusIn (this); update (); } } void IBusInputContext::widgetDestroyed (QWidget *widget) { QInputContext::widgetDestroyed (widget); if (has_focus) setFocusWidget (NULL); update (); } #ifdef Q_WS_X11 bool IBusInputContext::x11FilterEvent (QWidget *keywidget, XEvent *xevent) { if (has_focus && client->x11FilterEvent (this, keywidget, xevent)) return true; return QInputContext::x11FilterEvent (keywidget, xevent); } #endif void IBusInputContext::setIC (QString ic) { this->ic = ic; if (has_focus && !ic.isEmpty ()) { client->focusIn (this); } } QString IBusInputContext::getIC () { return ic; } void IBusInputContext::commitString (QString text) { QInputMethodEvent event; event.setCommitString (text); sendEvent (event); update (); } void IBusInputContext::updatePreedit (QString text, QList <QList <quint32> > attr_list, int cursor_pos, bool visible) { // qDebug () << text << cursor_pos << show; QList <QAttribute> qattrs; if (visible) { // append cursor pos qattrs.append (QAttribute (QInputMethodEvent::Cursor, cursor_pos, true, 0)); // append attributes for (QList <QList <quint32> >::iterator it = attr_list.begin (); it != attr_list.end(); ++ it) { QList <quint32> attr = *it; QTextCharFormat format; switch (attr[0]) { case 1: // underline format.setUnderlineStyle (QTextCharFormat::SingleUnderline); break; case 2: // foreground format.setForeground (QBrush (QColor (attr[1]))); break; case 3: // background format.setBackground (QBrush (QColor (attr[1]))); break; default: break; } qattrs.append (QAttribute (QInputMethodEvent::TextFormat, attr[2], attr[3] - attr[2], QVariant (format))); // qDebug () << attr[0] << attr[2] << attr[3] - attr[2]; } } else { qattrs.append (QAttribute (QInputMethodEvent::Cursor, 0, true, 0)); text = ""; cursor_pos = 0; } preedit_string = text; preedit_visible = visible; preedit_attrs = attr_list; preedit_cursor_pos = cursor_pos; QInputMethodEvent event (text, qattrs); sendEvent (event); update (); } void IBusInputContext::showPreedit () { if (preedit_visible) return; updatePreedit (preedit_string, preedit_attrs, preedit_cursor_pos, TRUE); } void IBusInputContext::hidePreedit () { if (!preedit_visible) return; updatePreedit (preedit_string, preedit_attrs, preedit_cursor_pos, FALSE); } <|endoftext|>
<commit_before>// Scintilla source code edit control /** @file LexAsm.cxx ** Lexer for Assembler, just for the Masm Syntax ** Written by The Black Horus **/ // Copyright 1998-2002 by Neil Hodgson <neilh@scintilla.org> // The License.txt file describes the conditions under which this software may be distributed. #include <stdlib.h> #include <string.h> #include <ctype.h> #include <stdio.h> #include <stdarg.h> #include "Platform.h" #include "PropSet.h" #include "Accessor.h" #include "StyleContext.h" #include "KeyWords.h" #include "Scintilla.h" #include "SciLexer.h" static inline bool IsAWordChar(const int ch) { return (ch < 0x80) && (isalnum(ch) || ch == '.' || ch == '_' || ch =='\\'); } static inline bool IsAWordStart(const int ch) { return (ch < 0x80) && (isalnum(ch) || ch == '_' || ch == '.'); } inline bool isAsmOperator(char ch) { if (isalnum(ch)) return false; // '.' left out as it is used to make up numbers if (ch == '*' || ch == '/' || ch == '-' || ch == '+' || ch == '(' || ch == ')' || ch == '=' || ch == '[' || ch == ']' || ch == '<' || ch == '>' || ch == ',' || ch == '.' || ch == '%' || ch == ':') return true; return false; } static void ColouriseAsmDoc(unsigned int startPos, int length, int initStyle, WordList *keywordlists[], Accessor &styler) { WordList &cpuInstruction = *keywordlists[0]; WordList &mathInstruction = *keywordlists[1]; WordList &registers = *keywordlists[2]; WordList &directive = *keywordlists[3]; WordList &directiveOperand = *keywordlists[4]; StyleContext sc(startPos, length, initStyle, styler); for (; sc.More(); sc.Forward()) { // Handle line continuation generically. if (sc.ch == '\\') { if (sc.Match("\\\n")) { sc.Forward(); continue; } if (sc.Match("\\\r\n")) { sc.Forward(); sc.Forward(); continue; } } // Determine if the current state should terminate. if (sc.state == SCE_ASM_OPERATOR) { sc.SetState(SCE_ASM_DEFAULT); }else if (sc.state == SCE_ASM_NUMBER) { if (!IsAWordChar(sc.ch)) { sc.SetState(SCE_ASM_DEFAULT); } } else if (sc.state == SCE_ASM_IDENTIFIER) { if (!IsAWordChar(sc.ch) ) { char s[100]; sc.GetCurrentLowered(s, sizeof(s)); if (cpuInstruction.InList(s)) { sc.ChangeState(SCE_ASM_CPUINSTRUCTION); } else if (mathInstruction.InList(s)) { sc.ChangeState(SCE_ASM_MATHINSTRUCTION); } else if (registers.InList(s)) { sc.ChangeState(SCE_ASM_REGISTER); } else if (directive.InList(s)) { sc.ChangeState(SCE_ASM_DIRECTIVE); } else if (directiveOperand.InList(s)) { sc.ChangeState(SCE_ASM_DIRECTIVEOPERAND); } sc.SetState(SCE_ASM_DEFAULT); } } else if (sc.state == SCE_ASM_COMMENT ) { if (sc.atLineEnd) { sc.SetState(SCE_ASM_DEFAULT); } } else if (sc.state == SCE_ASM_STRING) { if (sc.ch == '\\') { if (sc.chNext == '\"' || sc.chNext == '\'' || sc.chNext == '\\') { sc.Forward(); } } else if (sc.ch == '\"') { sc.ForwardSetState(SCE_ASM_DEFAULT); } else if (sc.atLineEnd) { sc.ForwardSetState(SCE_ASM_DEFAULT); } } // Determine if a new state should be entered. else if (sc.state == SCE_ASM_DEFAULT) { if (sc.ch == ';'){ sc.SetState(SCE_ASM_COMMENT); } else if (isdigit(sc.ch) || (sc.ch == '.' && isdigit(sc.chNext))) { sc.SetState(SCE_ASM_NUMBER); } else if (IsAWordStart(sc.ch)) { sc.SetState(SCE_ASM_IDENTIFIER); } else if (sc.Match('\"')) { sc.SetState(SCE_ASM_STRING); } } } sc.Complete(); } static const char * const asmWordListDesc[] = { "CPU instructions", "FPU instructions", "Registers", "Directives", "Directive operands", 0 }; LexerModule lmAsm(SCLEX_ASM, ColouriseAsmDoc, "asm", 0, asmWordListDesc); <commit_msg>Enhancements to Asm lexer by Kein-Hong Man.<commit_after>// Scintilla source code edit control /** @file LexAsm.cxx ** Lexer for Assembler, just for the MASM syntax ** Written by The Black Horus ** Enhancements and NASM stuff by Kein-Hong Man, 2003-10 ** SCE_ASM_COMMENTBLOCK and SCE_ASM_CHARACTER are for future GNU as colouring **/ // Copyright 1998-2003 by Neil Hodgson <neilh@scintilla.org> // The License.txt file describes the conditions under which this software may be distributed. #include <stdlib.h> #include <string.h> #include <ctype.h> #include <stdio.h> #include <stdarg.h> #include "Platform.h" #include "PropSet.h" #include "Accessor.h" #include "StyleContext.h" #include "KeyWords.h" #include "Scintilla.h" #include "SciLexer.h" static inline bool IsAWordChar(const int ch) { return (ch < 0x80) && (isalnum(ch) || ch == '.' || ch == '_' || ch == '?'); } static inline bool IsAWordStart(const int ch) { return (ch < 0x80) && (isalnum(ch) || ch == '_' || ch == '.' || ch == '%' || ch == '@' || ch == '$' || ch == '?'); } static inline bool IsAsmOperator(char ch) { if (isalnum(ch)) return false; // '.' left out as it is used to make up numbers if (ch == '*' || ch == '/' || ch == '-' || ch == '+' || ch == '(' || ch == ')' || ch == '=' || ch == '^' || ch == '[' || ch == ']' || ch == '<' || ch == '&' || ch == '>' || ch == ',' || ch == '|' || ch == '~' || ch == '%' || ch == ':') return true; return false; } static void ColouriseAsmDoc(unsigned int startPos, int length, int initStyle, WordList *keywordlists[], Accessor &styler) { WordList &cpuInstruction = *keywordlists[0]; WordList &mathInstruction = *keywordlists[1]; WordList &registers = *keywordlists[2]; WordList &directive = *keywordlists[3]; WordList &directiveOperand = *keywordlists[4]; WordList &extInstruction = *keywordlists[5]; // Do not leak onto next line if (initStyle == SCE_ASM_STRINGEOL) initStyle = SCE_ASM_DEFAULT; StyleContext sc(startPos, length, initStyle, styler); for (; sc.More(); sc.Forward()) { // Prevent SCE_ASM_STRINGEOL from leaking back to previous line if (sc.atLineStart && (sc.state == SCE_ASM_STRING)) { sc.SetState(SCE_ASM_STRING); } else if (sc.atLineStart && (sc.state == SCE_ASM_CHARACTER)) { sc.SetState(SCE_ASM_CHARACTER); } // Handle line continuation generically. if (sc.ch == '\\') { if (sc.chNext == '\n' || sc.chNext == '\r') { sc.Forward(); if (sc.ch == '\r' && sc.chNext == '\n') { sc.Forward(); } continue; } } // Determine if the current state should terminate. if (sc.state == SCE_ASM_OPERATOR) { if (!IsAsmOperator(static_cast<char>(sc.ch))) { sc.SetState(SCE_ASM_DEFAULT); } }else if (sc.state == SCE_ASM_NUMBER) { if (!IsAWordChar(sc.ch)) { sc.SetState(SCE_ASM_DEFAULT); } } else if (sc.state == SCE_ASM_IDENTIFIER) { if (!IsAWordChar(sc.ch) ) { char s[100]; sc.GetCurrentLowered(s, sizeof(s)); if (cpuInstruction.InList(s)) { sc.ChangeState(SCE_ASM_CPUINSTRUCTION); } else if (mathInstruction.InList(s)) { sc.ChangeState(SCE_ASM_MATHINSTRUCTION); } else if (registers.InList(s)) { sc.ChangeState(SCE_ASM_REGISTER); } else if (directive.InList(s)) { sc.ChangeState(SCE_ASM_DIRECTIVE); } else if (directiveOperand.InList(s)) { sc.ChangeState(SCE_ASM_DIRECTIVEOPERAND); } else if (extInstruction.InList(s)) { sc.ChangeState(SCE_ASM_EXTINSTRUCTION); } sc.SetState(SCE_ASM_DEFAULT); } } else if (sc.state == SCE_ASM_COMMENT ) { if (sc.atLineEnd) { sc.SetState(SCE_ASM_DEFAULT); } } else if (sc.state == SCE_ASM_STRING) { if (sc.ch == '\\') { if (sc.chNext == '\"' || sc.chNext == '\'' || sc.chNext == '\\') { sc.Forward(); } } else if (sc.ch == '\"') { sc.ForwardSetState(SCE_ASM_DEFAULT); } else if (sc.atLineEnd) { sc.ChangeState(SCE_ASM_STRINGEOL); sc.ForwardSetState(SCE_ASM_DEFAULT); } } else if (sc.state == SCE_ASM_CHARACTER) { if (sc.ch == '\\') { if (sc.chNext == '\"' || sc.chNext == '\'' || sc.chNext == '\\') { sc.Forward(); } } else if (sc.ch == '\'') { sc.ForwardSetState(SCE_ASM_DEFAULT); } else if (sc.atLineEnd) { sc.ChangeState(SCE_ASM_STRINGEOL); sc.ForwardSetState(SCE_ASM_DEFAULT); } } // Determine if a new state should be entered. if (sc.state == SCE_ASM_DEFAULT) { if (sc.ch == ';'){ sc.SetState(SCE_ASM_COMMENT); } else if (isdigit(sc.ch) || (sc.ch == '.' && isdigit(sc.chNext))) { sc.SetState(SCE_ASM_NUMBER); } else if (IsAWordStart(sc.ch)) { sc.SetState(SCE_ASM_IDENTIFIER); } else if (sc.ch == '\"') { sc.SetState(SCE_ASM_STRING); } else if (sc.ch == '\'') { sc.SetState(SCE_ASM_CHARACTER); } else if (IsAsmOperator(static_cast<char>(sc.ch))) { sc.SetState(SCE_ASM_OPERATOR); } } } sc.Complete(); } static const char * const asmWordListDesc[] = { "CPU instructions", "FPU instructions", "Registers", "Directives", "Directive operands", "Extended instructions", 0 }; LexerModule lmAsm(SCLEX_ASM, ColouriseAsmDoc, "asm", 0, asmWordListDesc); <|endoftext|>
<commit_before>/*----------------------------------------------------------------------------- NeXus - Neutron & X-ray Common Data Format Utility to convert a NeXus file into HDF4/HDF5/XML/... Author: Freddie Akeroyd, Ray Osborn 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 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 For further information, see <http://www.nexusformat.org> $Id: nxconvert.c 991 2008-03-19 19:30:03Z Freddie Akeroyd $ -----------------------------------------------------------------------------*/ #include <stdio.h> #include <string.h> #include <stdlib.h> #include <iostream> #ifdef _MSC_VER #else #include <unistd.h> #endif #include "napi.h" #include "NeXusFile.hpp" #include "NeXusStream.hpp" #include "nxconvert_common.h" #include <vector> static int WriteGroup (int is_definition); static int WriteAttributes (int is_definition, int is_group); struct link_to_make { char from[1024]; /* path of directory with link */ char name[256]; /* name of link */ char to[1024]; /* path of real item */ link_to_make(const char* _from, const char* _name, const char* _to) { strcpy(from, _from); strcpy(name, _name); strcpy(to, _to); } link_to_make(const link_to_make& val) { strcpy(from, val.from); strcpy(name, val.name); strcpy(to, val.to); } link_to_make& operator=(const link_to_make& val) { if (this != &val) { strcpy(from, val.from); strcpy(name, val.name); strcpy(to, val.to); } return *this; } }; static std::vector<link_to_make> links_to_make; static char current_path[1024]; static int add_path(const char* path) { int i; if (path != NULL) { i = strlen(current_path); sprintf(current_path + i, "/%s", path); } return 0; } static int remove_path(const char* path) { char *tstr; tstr = strrchr(current_path, '/'); if (path != NULL && tstr != NULL && !strcmp(path, tstr+1)) { *tstr = '\0'; } else { printf("path error\n"); } return 0; } static NXhandle inId, outId; static const char* definition_name = NULL; int convert_file(int nx_format, const char* inFile, int nx_read_access, const char* outFile, int nx_write_access, const char* definition_name_) { int nx_is_definition = 0; if (definition_name_ != NULL && definition_name_[0] == '\0') { definition_name = NULL; } else { definition_name = definition_name_; } char* tstr; links_to_make.clear(); links_to_make.reserve(2000); current_path[0] = '\0'; NXlink link; if (nx_format == NX_DEFINITION) { nx_is_definition = 1; char env_var[] = "NX_IS_DEFINITION=1"; putenv(env_var); } /* Open NeXus input file and NeXus output file */ if (NXopen (inFile, nx_read_access, &inId) != NX_OK) { printf ("NX_ERROR: Can't open %s\n", inFile); return NX_ERROR; } if (NXopen (outFile, nx_write_access, &outId) != NX_OK) { printf ("NX_ERROR: Can't open %s\n", outFile); return NX_ERROR; } /* Output global attributes */ if (WriteAttributes (nx_is_definition, 1) != NX_OK) { return NX_ERROR; } /* Recursively cycle through the groups printing the contents */ if (WriteGroup (nx_is_definition) != NX_OK) { return NX_ERROR; } /* close input */ if (NXclose (&inId) != NX_OK) { return NX_ERROR; } /* now create any required links */ for(size_t i=0; i<links_to_make.size(); i++) { if (NXopenpath(outId, links_to_make[i].to) != NX_OK) return NX_ERROR; if (NXgetdataID(outId, &link) == NX_OK || NXgetgroupID(outId, &link) == NX_OK) { if (NXopenpath(outId, links_to_make[i].from) != NX_OK) return NX_ERROR; tstr = strrchr(links_to_make[i].to, '/'); if (tstr != NULL) { if (!strcmp(links_to_make[i].name, tstr+1)) { if (NXmakelink(outId, &link) != NX_OK) return NX_ERROR; } else { if (NXmakenamedlink(outId, links_to_make[i].name, &link) != NX_OK) return NX_ERROR; } } } else { return NX_ERROR; } } /* Close the input and output files */ if (NXclose (&outId) != NX_OK) { return NX_ERROR; } return NX_OK; } /* Prints the contents of each group as XML tags and values */ static int WriteGroup (int is_definition) { int i, status, dataType, dataRank, dataDimensions[NX_MAXRANK]; static const int slab_start[10] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; static const int MAX_DEF_ARRAY_ELEMENTS_PER_DIM = 3; /* doesn't work yet - only 1 element is written */ NXname name, nxclass; void *dataBuffer; NXlink link; std::string definition; using namespace NeXus; using namespace NeXus::Stream; File nfile_in(inId), nfile_out(outId); do { status = NXgetnextentry (inId, name, nxclass, &dataType); if (status == NX_ERROR) return NX_ERROR; if (status == NX_OK) { // std::cerr << "WriteGroup: " << name << "(" << nxclass << ")" << std::endl; if (!strncmp(nxclass,"SDS",3)) { add_path(name); if (NXopendata (inId, name) != NX_OK) return NX_ERROR; if (NXgetdataID(inId, &link) != NX_OK) return NX_ERROR; if (!strcmp(current_path, link.targetPath)) { if (NXgetinfo (inId, &dataRank, dataDimensions, &dataType) != NX_OK) return NX_ERROR; if (NXmakedata (outId, name, dataType, dataRank, dataDimensions) != NX_OK) return NX_ERROR; if (NXopendata (outId, name) != NX_OK) return NX_ERROR; if ( is_definition && (dataType != NX_CHAR) ) { for(i=0; i<dataRank; ++i) { if (dataDimensions[i] > MAX_DEF_ARRAY_ELEMENTS_PER_DIM) { dataDimensions[i] = MAX_DEF_ARRAY_ELEMENTS_PER_DIM; } } if (NXmalloc (&dataBuffer, dataRank, dataDimensions, dataType) != NX_OK) return NX_ERROR; if (NXgetslab (inId, dataBuffer, slab_start, dataDimensions) != NX_OK) return NX_ERROR; if (NXputslab (outId, dataBuffer, slab_start, dataDimensions) != NX_OK) return NX_ERROR; } else { if (NXmalloc (&dataBuffer, dataRank, dataDimensions, dataType) != NX_OK) return NX_ERROR; if (NXgetdata (inId, dataBuffer) != NX_OK) return NX_ERROR; if (NXputdata (outId, dataBuffer) != NX_OK) return NX_ERROR; } if (WriteAttributes (is_definition, 0) != NX_OK) return NX_ERROR; if (NXclosedata (outId) != NX_OK) return NX_ERROR; if (NXfree((void**)&dataBuffer) != NX_OK) return NX_ERROR; remove_path(name); } else { remove_path(name); links_to_make.push_back(link_to_make(current_path, name, link.targetPath)); } if (NXclosedata (inId) != NX_OK) return NX_ERROR; } /* napi4.c returns UNKNOWN for DFTAG_VH in groups */ else if (!strcmp(nxclass, "UNKNOWN") || !strncmp(nxclass, "CDF", 3)) { ; } else { if (NXopengroup (inId, name, nxclass) != NX_OK) return NX_ERROR; add_path(name); if (NXgetgroupID(inId, &link) != NX_OK) return NX_ERROR; if (!strcmp(current_path, link.targetPath)) { if (NXmakegroup (outId, name, nxclass) != NX_OK) return NX_ERROR; if (NXopengroup (outId, name, nxclass) != NX_OK) return NX_ERROR; if (WriteAttributes (is_definition, 1) != NX_OK) return NX_ERROR; if (is_definition && !strcmp(nxclass, "NXentry")) { if (definition_name != NULL) { nfile_out.putAttr("xsi:type", definition_name); } else { try { nfile_in.openData("definition"); definition = nfile_in.getStrData(); nfile_in.closeData(); nfile_out.putAttr("xsi:type", definition); } catch(std::exception& ex) { ; // definition not found } } } if (WriteGroup (is_definition) != NX_OK) return NX_ERROR; remove_path(name); } else { remove_path(name); links_to_make.push_back(link_to_make(current_path, name, link.targetPath)); if (NXclosegroup (inId) != NX_OK) return NX_ERROR; } } } else if (status == NX_EOD) { if (NXclosegroup (inId) != NX_OK) return NX_ERROR; if (NXclosegroup (outId) != NX_OK) return NX_ERROR; return NX_OK; } } while (status == NX_OK); return NX_OK; } static int WriteAttributes (int is_definition, int is_group) { int status, i, attrLen, attrType; NXname attrName; void *attrBuffer; int found_napitype = 0; i = 0; do { status = NXgetnextattr (inId, attrName, &attrLen, &attrType); if (status == NX_ERROR) return NX_ERROR; if (status == NX_OK) { if (strcmp(attrName, "NAPItype") == 0) { found_napitype = 1; } if (strcmp(attrName, "NeXus_version") && strcmp(attrName, "XML_version") && strcmp(attrName, "HDF_version") && strcmp(attrName, "HDF5_Version") && strcmp(attrName, "file_name") && strcmp(attrName, "file_time")) { attrLen++; /* Add space for string termination */ if (NXmalloc((void**)&attrBuffer, 1, &attrLen, attrType) != NX_OK) return NX_ERROR; if (NXgetattr (inId, attrName, attrBuffer, &attrLen , &attrType) != NX_OK) return NX_ERROR; if (NXputattr (outId, attrName, attrBuffer, attrLen , attrType) != NX_OK) return NX_ERROR; if (NXfree((void**)&attrBuffer) != NX_OK) return NX_ERROR; } i++; } } while (status != NX_EOD); // if we are creating a reduced file for definiiton purposes, // make sure we always have a NAPItype attribute if (is_definition && !is_group && !found_napitype) { // need to be cleverer - cannot do this //if (NXputattr (outId, "NAPItype", (void*)"NX_CHAR", strlen("NX_CHAR"), NX_CHAR) != NX_OK) return NX_ERROR; } return NX_OK; } <commit_msg>Trap non-printable characters in conversion to definition. Refs #320<commit_after>/*----------------------------------------------------------------------------- NeXus - Neutron & X-ray Common Data Format Utility to convert a NeXus file into HDF4/HDF5/XML/... Author: Freddie Akeroyd, Ray Osborn 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 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 For further information, see <http://www.nexusformat.org> $Id: nxconvert.c 991 2008-03-19 19:30:03Z Freddie Akeroyd $ -----------------------------------------------------------------------------*/ #include <stdio.h> #include <string.h> #include <stdlib.h> #include <iostream> #ifdef _MSC_VER #else #include <unistd.h> #endif #include "napi.h" #include "NeXusFile.hpp" #include "NeXusStream.hpp" #include "nxconvert_common.h" #include <vector> static int WriteGroup (int is_definition); static int WriteAttributes (int is_definition, int is_group); struct link_to_make { char from[1024]; /* path of directory with link */ char name[256]; /* name of link */ char to[1024]; /* path of real item */ link_to_make(const char* _from, const char* _name, const char* _to) { strcpy(from, _from); strcpy(name, _name); strcpy(to, _to); } link_to_make(const link_to_make& val) { strcpy(from, val.from); strcpy(name, val.name); strcpy(to, val.to); } link_to_make& operator=(const link_to_make& val) { if (this != &val) { strcpy(from, val.from); strcpy(name, val.name); strcpy(to, val.to); } return *this; } }; static std::vector<link_to_make> links_to_make; static char current_path[1024]; static int add_path(const char* path) { int i; if (path != NULL) { i = strlen(current_path); sprintf(current_path + i, "/%s", path); } return 0; } static int remove_path(const char* path) { char *tstr; tstr = strrchr(current_path, '/'); if (path != NULL && tstr != NULL && !strcmp(path, tstr+1)) { *tstr = '\0'; } else { printf("path error\n"); } return 0; } static NXhandle inId, outId; static const char* definition_name = NULL; int convert_file(int nx_format, const char* inFile, int nx_read_access, const char* outFile, int nx_write_access, const char* definition_name_) { int nx_is_definition = 0; if (definition_name_ != NULL && definition_name_[0] == '\0') { definition_name = NULL; } else { definition_name = definition_name_; } char* tstr; links_to_make.clear(); links_to_make.reserve(2000); current_path[0] = '\0'; NXlink link; if (nx_format == NX_DEFINITION) { nx_is_definition = 1; char env_var[] = "NX_IS_DEFINITION=1"; putenv(env_var); } /* Open NeXus input file and NeXus output file */ if (NXopen (inFile, nx_read_access, &inId) != NX_OK) { printf ("NX_ERROR: Can't open %s\n", inFile); return NX_ERROR; } if (NXopen (outFile, nx_write_access, &outId) != NX_OK) { printf ("NX_ERROR: Can't open %s\n", outFile); return NX_ERROR; } /* Output global attributes */ if (WriteAttributes (nx_is_definition, 1) != NX_OK) { return NX_ERROR; } /* Recursively cycle through the groups printing the contents */ if (WriteGroup (nx_is_definition) != NX_OK) { return NX_ERROR; } /* close input */ if (NXclose (&inId) != NX_OK) { return NX_ERROR; } /* now create any required links */ for(size_t i=0; i<links_to_make.size(); i++) { if (NXopenpath(outId, links_to_make[i].to) != NX_OK) return NX_ERROR; if (NXgetdataID(outId, &link) == NX_OK || NXgetgroupID(outId, &link) == NX_OK) { if (NXopenpath(outId, links_to_make[i].from) != NX_OK) return NX_ERROR; tstr = strrchr(links_to_make[i].to, '/'); if (tstr != NULL) { if (!strcmp(links_to_make[i].name, tstr+1)) { if (NXmakelink(outId, &link) != NX_OK) return NX_ERROR; } else { if (NXmakenamedlink(outId, links_to_make[i].name, &link) != NX_OK) return NX_ERROR; } } } else { return NX_ERROR; } } /* Close the input and output files */ if (NXclose (&outId) != NX_OK) { return NX_ERROR; } return NX_OK; } /* Prints the contents of each group as XML tags and values */ static int WriteGroup (int is_definition) { int i, n, status, dataType, dataRank, dataDimensions[NX_MAXRANK]; static const int slab_start[10] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; static const int MAX_DEF_ARRAY_ELEMENTS_PER_DIM = 3; /* doesn't work yet - only 1 element is written */ NXname name, nxclass; void *dataBuffer; NXlink link; std::string definition; using namespace NeXus; using namespace NeXus::Stream; File nfile_in(inId), nfile_out(outId); do { status = NXgetnextentry (inId, name, nxclass, &dataType); if (status == NX_ERROR) return NX_ERROR; if (status == NX_OK) { // std::cerr << "WriteGroup: " << name << "(" << nxclass << ")" << std::endl; if (!strncmp(nxclass,"SDS",3)) { add_path(name); if (NXopendata (inId, name) != NX_OK) return NX_ERROR; if (NXgetdataID(inId, &link) != NX_OK) return NX_ERROR; if (!strcmp(current_path, link.targetPath)) { if (NXgetinfo (inId, &dataRank, dataDimensions, &dataType) != NX_OK) return NX_ERROR; if (NXmakedata (outId, name, dataType, dataRank, dataDimensions) != NX_OK) return NX_ERROR; if (NXopendata (outId, name) != NX_OK) return NX_ERROR; if ( is_definition && (dataType != NX_CHAR) ) { for(i=0; i<dataRank; ++i) { if (dataDimensions[i] > MAX_DEF_ARRAY_ELEMENTS_PER_DIM) { dataDimensions[i] = MAX_DEF_ARRAY_ELEMENTS_PER_DIM; } } if (NXmalloc (&dataBuffer, dataRank, dataDimensions, dataType) != NX_OK) return NX_ERROR; if (NXgetslab (inId, dataBuffer, slab_start, dataDimensions) != NX_OK) return NX_ERROR; if (NXputslab (outId, dataBuffer, slab_start, dataDimensions) != NX_OK) return NX_ERROR; } else { if (NXmalloc (&dataBuffer, dataRank, dataDimensions, dataType) != NX_OK) return NX_ERROR; if (NXgetdata (inId, dataBuffer) != NX_OK) return NX_ERROR; /* fix potential non-UTF8 character issue */ if (is_definition && dataType == NX_CHAR) { n = 1; for(i=0; i<dataRank; ++i) { n *= dataDimensions[i]; } for(i=0; i<n; ++i) { if (!isprint(((const unsigned char*)dataBuffer)[i])) { ((char*)dataBuffer)[i] = '?'; } } } if (NXputdata (outId, dataBuffer) != NX_OK) return NX_ERROR; } if (WriteAttributes (is_definition, 0) != NX_OK) return NX_ERROR; if (NXclosedata (outId) != NX_OK) return NX_ERROR; if (NXfree((void**)&dataBuffer) != NX_OK) return NX_ERROR; remove_path(name); } else { remove_path(name); links_to_make.push_back(link_to_make(current_path, name, link.targetPath)); } if (NXclosedata (inId) != NX_OK) return NX_ERROR; } /* napi4.c returns UNKNOWN for DFTAG_VH in groups */ else if (!strcmp(nxclass, "UNKNOWN") || !strncmp(nxclass, "CDF", 3)) { ; } else { if (NXopengroup (inId, name, nxclass) != NX_OK) return NX_ERROR; add_path(name); if (NXgetgroupID(inId, &link) != NX_OK) return NX_ERROR; if (!strcmp(current_path, link.targetPath)) { if (NXmakegroup (outId, name, nxclass) != NX_OK) return NX_ERROR; if (NXopengroup (outId, name, nxclass) != NX_OK) return NX_ERROR; if (WriteAttributes (is_definition, 1) != NX_OK) return NX_ERROR; if (is_definition && !strcmp(nxclass, "NXentry")) { if (definition_name != NULL) { nfile_out.putAttr("xsi:type", definition_name); } else { try { nfile_in.openData("definition"); definition = nfile_in.getStrData(); nfile_in.closeData(); nfile_out.putAttr("xsi:type", definition); } catch(std::exception& ex) { ; // definition not found } } } if (WriteGroup (is_definition) != NX_OK) return NX_ERROR; remove_path(name); } else { remove_path(name); links_to_make.push_back(link_to_make(current_path, name, link.targetPath)); if (NXclosegroup (inId) != NX_OK) return NX_ERROR; } } } else if (status == NX_EOD) { if (NXclosegroup (inId) != NX_OK) return NX_ERROR; if (NXclosegroup (outId) != NX_OK) return NX_ERROR; return NX_OK; } } while (status == NX_OK); return NX_OK; } static int WriteAttributes (int is_definition, int is_group) { int status, i, attrLen, attrType; NXname attrName; void *attrBuffer; int found_napitype = 0; i = 0; do { status = NXgetnextattr (inId, attrName, &attrLen, &attrType); if (status == NX_ERROR) return NX_ERROR; if (status == NX_OK) { if (strcmp(attrName, "NAPItype") == 0) { found_napitype = 1; } if (strcmp(attrName, "NeXus_version") && strcmp(attrName, "XML_version") && strcmp(attrName, "HDF_version") && strcmp(attrName, "HDF5_Version") && strcmp(attrName, "file_name") && strcmp(attrName, "file_time")) { attrLen++; /* Add space for string termination */ if (NXmalloc((void**)&attrBuffer, 1, &attrLen, attrType) != NX_OK) return NX_ERROR; if (NXgetattr (inId, attrName, attrBuffer, &attrLen , &attrType) != NX_OK) return NX_ERROR; if (NXputattr (outId, attrName, attrBuffer, attrLen , attrType) != NX_OK) return NX_ERROR; if (NXfree((void**)&attrBuffer) != NX_OK) return NX_ERROR; } i++; } } while (status != NX_EOD); // if we are creating a reduced file for definiiton purposes, // make sure we always have a NAPItype attribute if (is_definition && !is_group && !found_napitype) { // need to be cleverer - cannot do this //if (NXputattr (outId, "NAPItype", (void*)"NX_CHAR", strlen("NX_CHAR"), NX_CHAR) != NX_OK) return NX_ERROR; } return NX_OK; } <|endoftext|>
<commit_before>/** -*- C++ -*- * union_dataset.cc * Mich, 2016-09-14 * This file is part of MLDB. Copyright 2016 Datacratic. All rights reserved. **/ #include "union_dataset.h" #include <thread> #include <math.h> #include "mldb/builtin/id_hash.h" #include "mldb/builtin/merge_hash_entries.h" #include "mldb/types/any_impl.h" #include "mldb/types/structure_description.h" #include "mldb/types/vector_description.h" using namespace std; namespace MLDB { /*****************************************************************************/ /* UNION DATASET CONFIG */ /*****************************************************************************/ DEFINE_STRUCTURE_DESCRIPTION(UnionDatasetConfig); UnionDatasetConfigDescription:: UnionDatasetConfigDescription() { nullAccepted = true; addField("datasets", &UnionDatasetConfig::datasets, "Datasets to unify together"); } static RegisterDatasetType<UnionDataset, UnionDatasetConfig> regUnion(builtinPackage(), "union", "Unify together several datasets", "datasets/UnionDataset.md.html"); std::shared_ptr<Dataset> createUnionDataset( MldbServer * server, vector<std::shared_ptr<Dataset> > datasets) { return std::make_shared<UnionDataset>(server, datasets); } struct UnionDataset::Itl : public MatrixView, public ColumnIndex { Lightweight_Hash<RowHash, pair<int, RowHash> > rowIndex; IdHashes columnIndex; // Datasets that it was constructed with vector<std::shared_ptr<Dataset> > datasets; Itl(MldbServer * server, vector<std::shared_ptr<Dataset> > datasets) { if (datasets.empty()) { throw MLDB::Exception("Attempt to unify no datasets together"); } this->datasets = datasets; int indexWidth = getIndexBinaryWidth(); if (indexWidth > 31) { throw MLDB::Exception("Too many datasets in the union"); } for (int i = 0; i < datasets.size(); ++i) { for (const auto & rowPath: datasets[i]->getMatrixView()->getRowPaths()) { rowIndex[RowHash(PathElement(i) + rowPath)] = make_pair(i, RowHash(rowPath)); } } auto getColumnHashes = [&] (int datasetIndex) { auto dataset = datasets[datasetIndex]; MergeHashEntries result; vector<ColumnPath> cols = dataset->getMatrixView()->getColumnPaths(); std::sort(cols.begin(), cols.end()); ExcAssert(std::unique(cols.begin(), cols.end()) == cols.end()); result.reserve(cols.size()); for (auto c: cols) result.add(c.hash(), 1ULL << datasetIndex); return result; }; auto initColumnBucket = [&] (int i, MergeHashEntryBucket & b) { auto & b2 = columnIndex.buckets[i]; b2.reserve(b.size()); for (auto & e: b) { uint64_t h = e.hash; uint32_t bm = e.bitmap; b2.insert(make_pair(h, bm)); } }; std::thread mergeColumns([&] () { extractAndMerge(datasets.size(), getColumnHashes, initColumnBucket); }); mergeColumns.join(); } int getIndexBinaryWidth() const { return ceil(log(datasets.size()) / log(2)); } int getIdxFromRowPath(const RowPath & rowPath) const { // Returns idx > -1 if the index is valid, -1 otherwise if (rowPath.size() < 2) { return -1; } int idx = static_cast<int>(rowPath.at(0).toIndex()); if (idx > datasets.size()) { return -1; } ExcAssert(idx == -1 || idx <= datasets.size()); return idx; } struct UnionRowStream : public RowStream { UnionRowStream(const UnionDataset::Itl* source) : source(source) { cerr << "UNIMPLEMENTED " << __FILE__ << ":" << __LINE__ << endl; //throw MLDB::Exception("Unimplemented %s : %d", __FILE__, __LINE__); } virtual std::shared_ptr<RowStream> clone() const override { return make_shared<UnionRowStream>(source); } /* set where the stream should start*/ virtual void initAt(size_t start) override { cerr << "UNIMPLEMENTED " << __FILE__ << ":" << __LINE__ << endl; //throw MLDB::Exception("Unimplemented %s : %d", __FILE__, __LINE__); } virtual RowPath next() override { cerr << "UNIMPLEMENTED " << __FILE__ << ":" << __LINE__ << endl; throw MLDB::Exception("Unimplemented %s : %d", __FILE__, __LINE__); uint64_t hash = (*it).first; ++it; return source->getRowPath(RowHash(hash)); } virtual const RowPath & rowName(RowPath & storage) const override { cerr << "UNIMPLEMENTED " << __FILE__ << ":" << __LINE__ << endl; throw MLDB::Exception("Unimplemented %s : %d", __FILE__, __LINE__); uint64_t hash = (*it).first; return storage = source->getRowPath(RowHash(hash)); } const UnionDataset::Itl* source; IdHashes::const_iterator it; }; virtual vector<Path> getRowPaths(ssize_t start = 0, ssize_t limit = -1) const { // Row names are idx.rowPath where idx is the index of the dataset // in the union and rowPath is the original rowPath. vector<RowPath> result; for (int i = 0; i < datasets.size(); ++i) { const auto & d = datasets[i]; for (const auto & name: d->getMatrixView()->getRowPaths()) { result.emplace_back(PathElement(i) + name); } } return result; } virtual vector<RowHash> getRowHashes(ssize_t start = 0, ssize_t limit = -1) const { std::vector<RowHash> result; for (const auto & it: rowIndex) { result.emplace_back(it.first); } return result; } virtual bool knownRow(const Path & rowPath) const { int idx = getIdxFromRowPath(rowPath); if (idx == -1) { return false; } return datasets[idx]->getMatrixView()->knownRow(rowPath.tail()); } virtual bool knownRowHash(const RowHash & rowHash) const { // Unused ? return rowIndex.find(rowHash) != rowIndex.end(); //return rowIndex.getDefault(rowHash, 0) != 0; } virtual RowPath getRowPath(const RowHash & rowHash) const { const auto & it = rowIndex.find(rowHash); if (it == rowIndex.end()) { throw MLDB::Exception("Row not known"); } const auto & idxAndHash = it->second; Path subRowName = datasets[idxAndHash.first]->getMatrixView()->getRowPath(idxAndHash.second); return PathElement(idxAndHash.second) + subRowName; } // DEPRECATED virtual MatrixNamedRow getRow(const RowPath & rowPath) const { throw MLDB::Exception("Unimplemented %s : %d", __FILE__, __LINE__); } virtual bool knownColumn(const Path & column) const { for (const auto & d: datasets) { if (d->getMatrixView()->knownColumn(column)) { return true; } } return false; } uint32_t getColumnBitmap(ColumnHash columnHash) const { return columnIndex.getDefault(columnHash, 0); } virtual ColumnPath getColumnPath(ColumnHash columnHash) const { uint32_t bitmap = getColumnBitmap(columnHash); if (bitmap == 0) throw MLDB::Exception("Column not found in union dataset"); int bit = ML::lowest_bit(bitmap, -1); return datasets[bit]->getMatrixView()->getColumnPath(columnHash); } /** Return a list of all columns. */ virtual vector<ColumnPath> getColumnPaths() const { std::set<ColumnPath> preResult; for (const auto & d: datasets) { auto columnPaths = d->getColumnPaths(); preResult.insert(columnPaths.begin(), columnPaths.end()); } return vector<ColumnPath>(preResult.begin(), preResult.end()); } virtual MatrixColumn getColumn(const ColumnPath & columnPath) const { MatrixColumn result; result.columnName = columnPath; result.columnHash = columnPath; vector<std::tuple<RowPath, CellValue> > res; for (int i = 0; i < datasets.size(); ++i) { const auto & d = datasets[i]; const auto & subCol = d->getColumnIndex()->getColumn(columnPath); for (const auto & curr: subCol.rows) { result.rows.emplace_back(PathElement(i) + std::get<0>(curr), std::get<1>(curr), std::get<2>(curr)); } } return result; } /** Return the value of the column for all rows and timestamps. */ virtual vector<std::tuple<RowPath, CellValue> > getColumnValues(const ColumnPath & columnPath, const std::function<bool (const CellValue &)> & filter) const { vector<std::tuple<RowPath, CellValue> > res; for (int i = 0; i < datasets.size(); ++i) { const auto & d = datasets[i]; for (const auto curr: d->getColumnIndex()->getColumnValues(columnPath)) { res.emplace_back( PathElement(i) + std::get<0>(curr).toUtf8String().rawString(), std::get<1>(curr)); } } return res; } virtual size_t getRowCount() const { size_t count = 0; for (const auto & d: datasets) { count += d->getRowCount(); } return count; } virtual size_t getColumnCount() const { return columnIndex.size(); } std::pair<Date, Date> getTimestampRange() const { std::pair<Date, Date> result(Date::notADate(), Date::notADate()); bool first = true; for (auto & d: datasets) { std::pair<Date, Date> dsRange = d->getTimestampRange(); if (!dsRange.first.isADate() || !dsRange.second.isADate()) { continue; } if (first) { result = dsRange; first = false; } else { result.first.setMin(dsRange.first); result.second.setMax(dsRange.second); } } return result; } }; UnionDataset:: UnionDataset(MldbServer * owner, PolyConfig config, const std::function<bool (const Json::Value &)> & onProgress) : Dataset(owner) { auto unionConfig = config.params.convert<UnionDatasetConfig>(); vector<std::shared_ptr<Dataset> > datasets; for (auto & d: unionConfig.datasets) { datasets.emplace_back(obtainDataset(owner, d, onProgress)); } itl.reset(new Itl(server, datasets)); } UnionDataset:: UnionDataset(MldbServer * owner, vector<std::shared_ptr<Dataset> > datasetsToMerge) : Dataset(owner) { itl.reset(new Itl(server, datasetsToMerge)); } UnionDataset:: ~UnionDataset() { } Any UnionDataset:: getStatus() const { vector<Any> result; for (auto & d: itl->datasets) { result.emplace_back(d->getStatus()); } return result; } std::pair<Date, Date> UnionDataset:: getTimestampRange() const { return itl->getTimestampRange(); } std::shared_ptr<MatrixView> UnionDataset:: getMatrixView() const { return itl; } std::shared_ptr<ColumnIndex> UnionDataset:: getColumnIndex() const { return itl; } std::shared_ptr<RowStream> UnionDataset:: getRowStream() const { return make_shared<UnionDataset::Itl::UnionRowStream>(itl.get()); } ExpressionValue UnionDataset:: getRowExpr(const RowPath & rowPath) const { int idx = itl->getIdxFromRowPath(rowPath); if (idx == -1) { return ExpressionValue{}; } return itl->datasets[idx]->getRowExpr( Path(rowPath.begin() + 1, rowPath.end())); } } // namespace MLDB <commit_msg>fix union dataset rowstream<commit_after>/** -*- C++ -*- * union_dataset.cc * Mich, 2016-09-14 * This file is part of MLDB. Copyright 2016 Datacratic. All rights reserved. **/ #include "union_dataset.h" #include <thread> #include <math.h> #include "mldb/builtin/id_hash.h" #include "mldb/builtin/merge_hash_entries.h" #include "mldb/types/any_impl.h" #include "mldb/types/structure_description.h" #include "mldb/types/vector_description.h" using namespace std; namespace MLDB { /*****************************************************************************/ /* UNION DATASET CONFIG */ /*****************************************************************************/ DEFINE_STRUCTURE_DESCRIPTION(UnionDatasetConfig); UnionDatasetConfigDescription:: UnionDatasetConfigDescription() { nullAccepted = true; addField("datasets", &UnionDatasetConfig::datasets, "Datasets to unify together"); } static RegisterDatasetType<UnionDataset, UnionDatasetConfig> regUnion(builtinPackage(), "union", "Unify together several datasets", "datasets/UnionDataset.md.html"); std::shared_ptr<Dataset> createUnionDataset( MldbServer * server, vector<std::shared_ptr<Dataset> > datasets) { return std::make_shared<UnionDataset>(server, datasets); } struct UnionDataset::Itl : public MatrixView, public ColumnIndex { Lightweight_Hash<RowHash, pair<int, RowHash> > rowIndex; IdHashes columnIndex; // Datasets that it was constructed with vector<std::shared_ptr<Dataset> > datasets; Itl(MldbServer * server, vector<std::shared_ptr<Dataset> > datasets) { if (datasets.empty()) { throw MLDB::Exception("Attempt to unify no datasets together"); } this->datasets = datasets; int indexWidth = getIndexBinaryWidth(); if (indexWidth > 31) { throw MLDB::Exception("Too many datasets in the union"); } for (int i = 0; i < datasets.size(); ++i) { for (const auto & rowPath: datasets[i]->getMatrixView()->getRowPaths()) { rowIndex[RowHash(PathElement(i) + rowPath)] = make_pair(i, RowHash(rowPath)); } } auto getColumnHashes = [&] (int datasetIndex) { auto dataset = datasets[datasetIndex]; MergeHashEntries result; vector<ColumnPath> cols = dataset->getMatrixView()->getColumnPaths(); std::sort(cols.begin(), cols.end()); ExcAssert(std::unique(cols.begin(), cols.end()) == cols.end()); result.reserve(cols.size()); for (auto c: cols) result.add(c.hash(), 1ULL << datasetIndex); return result; }; auto initColumnBucket = [&] (int i, MergeHashEntryBucket & b) { auto & b2 = columnIndex.buckets[i]; b2.reserve(b.size()); for (auto & e: b) { uint64_t h = e.hash; uint32_t bm = e.bitmap; b2.insert(make_pair(h, bm)); } }; std::thread mergeColumns([&] () { extractAndMerge(datasets.size(), getColumnHashes, initColumnBucket); }); mergeColumns.join(); } int getIndexBinaryWidth() const { return ceil(log(datasets.size()) / log(2)); } int getIdxFromRowPath(const RowPath & rowPath) const { // Returns idx > -1 if the index is valid, -1 otherwise if (rowPath.size() < 2) { return -1; } int idx = static_cast<int>(rowPath.at(0).toIndex()); if (idx > datasets.size()) { return -1; } ExcAssert(idx == -1 || idx <= datasets.size()); return idx; } struct UnionRowStream : public RowStream { UnionRowStream(const UnionDataset::Itl* source) : source(source), datasetIndex(0) { } virtual std::shared_ptr<RowStream> clone() const override { return make_shared<UnionRowStream>(source); } /* set where the stream should start*/ virtual void initAt(size_t start) override { datasetIndex = 0; size_t currentTotal = 0; std::shared_ptr<Dataset> currentDataset = source->datasets[0]; size_t currentRowCount = currentDataset->getRowCount(); while (currentTotal + currentRowCount < start) { currentTotal += currentRowCount; ++datasetIndex; currentDataset = source->datasets[datasetIndex]; currentRowCount = currentDataset->getRowCount(); } currentSubRowStream = currentDataset->getRowStream(); subRowIndex = start - currentTotal; currentSubRowStream->initAt(subRowIndex); subNumRow = currentRowCount; } virtual RowPath next() override { RowPath mynext = currentSubRowStream->next(); ++subRowIndex; if (subRowIndex == subNumRow) { ++datasetIndex; if (datasetIndex < source->datasets.size()) { currentSubRowStream = source->datasets[datasetIndex]->getRowStream(); currentSubRowStream->initAt(0); subRowIndex = 0; subNumRow = source->datasets[datasetIndex]->getRowCount(); } } return mynext; } virtual const RowPath & rowName(RowPath & storage) const override { cerr << "UNIMPLEMENTED " << __FILE__ << ":" << __LINE__ << endl; throw MLDB::Exception("Unimplemented %s : %d", __FILE__, __LINE__); } const UnionDataset::Itl* source; size_t datasetIndex; size_t subRowIndex; size_t subNumRow; std::shared_ptr<RowStream> currentSubRowStream; }; virtual vector<Path> getRowPaths(ssize_t start = 0, ssize_t limit = -1) const { // Row names are idx.rowPath where idx is the index of the dataset // in the union and rowPath is the original rowPath. vector<RowPath> result; for (int i = 0; i < datasets.size(); ++i) { const auto & d = datasets[i]; for (const auto & name: d->getMatrixView()->getRowPaths()) { result.emplace_back(PathElement(i) + name); } } return result; } virtual vector<RowHash> getRowHashes(ssize_t start = 0, ssize_t limit = -1) const { std::vector<RowHash> result; for (const auto & it: rowIndex) { result.emplace_back(it.first); } return result; } virtual bool knownRow(const Path & rowPath) const { int idx = getIdxFromRowPath(rowPath); if (idx == -1) { return false; } return datasets[idx]->getMatrixView()->knownRow(rowPath.tail()); } virtual bool knownRowHash(const RowHash & rowHash) const { // Unused ? return rowIndex.find(rowHash) != rowIndex.end(); //return rowIndex.getDefault(rowHash, 0) != 0; } virtual RowPath getRowPath(const RowHash & rowHash) const { const auto & it = rowIndex.find(rowHash); if (it == rowIndex.end()) { throw MLDB::Exception("Row not known"); } const auto & idxAndHash = it->second; Path subRowName = datasets[idxAndHash.first]->getMatrixView()->getRowPath(idxAndHash.second); return PathElement(idxAndHash.second) + subRowName; } // DEPRECATED virtual MatrixNamedRow getRow(const RowPath & rowPath) const { throw MLDB::Exception("Unimplemented %s : %d", __FILE__, __LINE__); } virtual bool knownColumn(const Path & column) const { for (const auto & d: datasets) { if (d->getMatrixView()->knownColumn(column)) { return true; } } return false; } uint32_t getColumnBitmap(ColumnHash columnHash) const { return columnIndex.getDefault(columnHash, 0); } virtual ColumnPath getColumnPath(ColumnHash columnHash) const { uint32_t bitmap = getColumnBitmap(columnHash); if (bitmap == 0) throw MLDB::Exception("Column not found in union dataset"); int bit = ML::lowest_bit(bitmap, -1); return datasets[bit]->getMatrixView()->getColumnPath(columnHash); } /** Return a list of all columns. */ virtual vector<ColumnPath> getColumnPaths() const { std::set<ColumnPath> preResult; for (const auto & d: datasets) { auto columnPaths = d->getColumnPaths(); preResult.insert(columnPaths.begin(), columnPaths.end()); } return vector<ColumnPath>(preResult.begin(), preResult.end()); } virtual MatrixColumn getColumn(const ColumnPath & columnPath) const { MatrixColumn result; result.columnName = columnPath; result.columnHash = columnPath; vector<std::tuple<RowPath, CellValue> > res; for (int i = 0; i < datasets.size(); ++i) { const auto & d = datasets[i]; const auto & subCol = d->getColumnIndex()->getColumn(columnPath); for (const auto & curr: subCol.rows) { result.rows.emplace_back(PathElement(i) + std::get<0>(curr), std::get<1>(curr), std::get<2>(curr)); } } return result; } /** Return the value of the column for all rows and timestamps. */ virtual vector<std::tuple<RowPath, CellValue> > getColumnValues(const ColumnPath & columnPath, const std::function<bool (const CellValue &)> & filter) const { vector<std::tuple<RowPath, CellValue> > res; for (int i = 0; i < datasets.size(); ++i) { const auto & d = datasets[i]; for (const auto curr: d->getColumnIndex()->getColumnValues(columnPath)) { res.emplace_back( PathElement(i) + std::get<0>(curr).toUtf8String().rawString(), std::get<1>(curr)); } } return res; } virtual size_t getRowCount() const { size_t count = 0; for (const auto & d: datasets) { count += d->getRowCount(); } return count; } virtual size_t getColumnCount() const { return columnIndex.size(); } std::pair<Date, Date> getTimestampRange() const { std::pair<Date, Date> result(Date::notADate(), Date::notADate()); bool first = true; for (auto & d: datasets) { std::pair<Date, Date> dsRange = d->getTimestampRange(); if (!dsRange.first.isADate() || !dsRange.second.isADate()) { continue; } if (first) { result = dsRange; first = false; } else { result.first.setMin(dsRange.first); result.second.setMax(dsRange.second); } } return result; } }; UnionDataset:: UnionDataset(MldbServer * owner, PolyConfig config, const std::function<bool (const Json::Value &)> & onProgress) : Dataset(owner) { auto unionConfig = config.params.convert<UnionDatasetConfig>(); vector<std::shared_ptr<Dataset> > datasets; for (auto & d: unionConfig.datasets) { datasets.emplace_back(obtainDataset(owner, d, onProgress)); } itl.reset(new Itl(server, datasets)); } UnionDataset:: UnionDataset(MldbServer * owner, vector<std::shared_ptr<Dataset> > datasetsToMerge) : Dataset(owner) { itl.reset(new Itl(server, datasetsToMerge)); } UnionDataset:: ~UnionDataset() { } Any UnionDataset:: getStatus() const { vector<Any> result; for (auto & d: itl->datasets) { result.emplace_back(d->getStatus()); } return result; } std::pair<Date, Date> UnionDataset:: getTimestampRange() const { return itl->getTimestampRange(); } std::shared_ptr<MatrixView> UnionDataset:: getMatrixView() const { return itl; } std::shared_ptr<ColumnIndex> UnionDataset:: getColumnIndex() const { return itl; } std::shared_ptr<RowStream> UnionDataset:: getRowStream() const { return make_shared<UnionDataset::Itl::UnionRowStream>(itl.get()); } ExpressionValue UnionDataset:: getRowExpr(const RowPath & rowPath) const { int idx = itl->getIdxFromRowPath(rowPath); if (idx == -1) { return ExpressionValue{}; } return itl->datasets[idx]->getRowExpr( Path(rowPath.begin() + 1, rowPath.end())); } } // namespace MLDB <|endoftext|>