hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
109
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
48.5k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
e733c9ee77c621437afdbe5a4aa3be5902f3e1d4
18,686
cpp
C++
src/Toolbar.cpp
petterh/textedit
df59502fa5309834b2d2452af609ba6fb1dc97c2
[ "MIT" ]
6
2018-04-08T06:30:27.000Z
2021-12-19T12:52:28.000Z
src/Toolbar.cpp
petterh/textedit
df59502fa5309834b2d2452af609ba6fb1dc97c2
[ "MIT" ]
32
2017-11-03T09:39:48.000Z
2021-12-23T18:27:20.000Z
src/Toolbar.cpp
petterh/textedit
df59502fa5309834b2d2452af609ba6fb1dc97c2
[ "MIT" ]
1
2021-09-13T08:38:56.000Z
2021-09-13T08:38:56.000Z
/* * $Header: /Book/Toolbar.cpp 25 16.07.04 10:42 Oslph312 $ * * The toolbar automatically uses large icons when the user's * selected menu font gets above a suitable treshold. This treshold * is controlled by MenuFont::isLarge. */ #include "precomp.h" #include "String.h" #include "Exception.h" #include "Editor.h" // TODO: This is dirty. reorg! #include "Toolbar.h" #include "Registry.h" #include "MenuFont.h" #include "InstanceSubclasser.h" #include "mainwnd.h" #include "resource.h" #include "winUtils.h" #include "utils.h" #include "geometry.h" #include "themes.h" #include <uxtheme.h> //#include <Tmschema.h> PRIVATE LRESULT CALLBACK tabSubclassWndProc( HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam ); PRIVATE LRESULT CALLBACK toolbarParentSpy( HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam ); PRIVATE InstanceSubclasser s_tabSubclasser( tabSubclassWndProc ); PRIVATE InstanceSubclasser s_parentSubclasser( toolbarParentSpy ); void Toolbar::onCommand( int id, HWND hwndCtl, UINT codeNotify ) { switch ( id ) { case IDOK: FORWARD_WM_COMMAND( GetParent( *this ), ID_SET_TABS, 0, 0, PostMessage ); //*** FALL THROUGH case IDCANCEL: if ( BN_CLICKED == codeNotify ) { SetFocus( GetParent( *this ) ); } break; case IDC_READONLY: if ( BN_CLICKED == codeNotify ) { FORWARD_WM_COMMAND( GetParent( *this ), id, 0, 0, PostMessage ); } break; } } // LATER: If the toolbar doesn't support drowdown, don't drop down! bool onDropdown( HWND hwnd, NMTOOLBAR *pNmToolbar ) { assert( IsWindow( hwnd ) ); assert( isGoodPtr( pNmToolbar ) ); if ( ID_FILE_OPEN == pNmToolbar->iItem ) { HWND hwndToolbar = s_parentSubclasser.getUserDataAsHwnd( hwnd ); assert( IsWindow( hwndToolbar ) ); HMENU hmenu = CreatePopupMenu(); if ( 0 != hmenu ) { RECT rc; SNDMSG( hwndToolbar, TB_GETRECT, pNmToolbar->iItem, reinterpret_cast< LPARAM >( &rc ) ); POINT pt= { rc.left, rc.bottom }; ClientToScreen( pNmToolbar->hdr.hwndFrom, &pt ); // The main window's onInitMenu will add files. TrackPopupMenu( hmenu, TPM_LEFTALIGN | TPM_TOPALIGN | TPM_RIGHTBUTTON, pt.x, pt.y, 0, hwnd, 0 ); DestroyMenu( hmenu ); } else { trace( _T( "onDropdown.CreatePopupMenu failed: %s\n" ), WinException().what() ); } } return TBDDRET_DEFAULT; } /** * This is called when the spin buttons attached to the * tab field are spun (or if the up/down arrows are used). */ void Toolbar::onDeltaPos( NMUPDOWN *pUpDown ) { assert( isGoodPtr( pUpDown ) ); assert( IDC_TABUPDOWN == pUpDown->hdr.idFrom ); if ( pUpDown->iPos + pUpDown->iDelta <= 4 ) { ; } else if ( pUpDown->iPos - (pUpDown->iDelta < 0 ) < 8 ) { if ( pUpDown->iDelta < 0 ) { pUpDown->iDelta = 4 - pUpDown->iPos; } else { pUpDown->iDelta = 8 - pUpDown->iPos; } } else if ( pUpDown->iPos - (pUpDown->iDelta < 0 ) < 16 ) { if ( pUpDown->iDelta < 0 ) { pUpDown->iDelta = 8 - pUpDown->iPos; } else { pUpDown->iDelta = 16 - pUpDown->iPos; } } else { pUpDown->iDelta = 16 - pUpDown->iPos; } PostMessage( GetDlgItem( *this, IDC_TABEDIT ), EM_SETSEL, 0, -1 ); } /** * Get tooltip text. */ bool Toolbar::onGetDispInfo( NMTTDISPINFO *pDispInfo ) { assertValid(); assert( isGoodPtr( pDispInfo ) ); // NOTE: The hwndFrom member refers to the tooltip control. const HWND hwndCtl = reinterpret_cast< HWND >( pDispInfo->hdr.idFrom ); if ( GetDlgItem( *this, IDC_TABEDIT ) == hwndCtl ) { pDispInfo->lpszText = MAKEINTRESOURCE( IDS_TABS_TIP ); } else if ( GetDlgItem( *this, IDC_TABUPDOWN ) == hwndCtl ) { pDispInfo->lpszText = MAKEINTRESOURCE( IDS_TABS_UPDOWN_TIP ); } else if ( GetDlgItem( *this, IDC_READONLY ) == hwndCtl ) { pDispInfo->lpszText = MAKEINTRESOURCE( IDS_READ_ONLY_TIP ); } else { String strToolTip = loadToolTip( pDispInfo->hdr.idFrom ); pDispInfo->lpszText = pDispInfo->szText; _tcsncpy_s(pDispInfo->szText, strToolTip.c_str(), dim(pDispInfo->szText)); pDispInfo->hinst = 0; } return true; } LRESULT Toolbar::onNotify( const int id, const LPNMHDR pHdr ) { assert( isGoodPtr( pHdr ) ); switch ( pHdr->code ) { case UDN_DELTAPOS: onDeltaPos( reinterpret_cast< NMUPDOWN * >( pHdr ) ); return 0; // TODO: Document: If running with a manifest for Common controls 6, // we only get the unicode message. #ifndef UNICODE case TTN_GETDISPINFOW: return onGetDispInfoW( reinterpret_cast< NMTTDISPINFOW * >( pHdr ) ); #endif case TTN_GETDISPINFO: return onGetDispInfo( reinterpret_cast< NMTTDISPINFO * >( pHdr ) ); case TBN_DROPDOWN: // Never gets here; sent to parent, assert( false ); // intercepted in toolbarParentSpy. } return Window::onNotify( id, pHdr ); } int Toolbar::commandFromIndex( int index ) { assertValid(); TBBUTTON button = { 0 }; sendMessage( TB_GETBUTTON, index, reinterpret_cast< LPARAM >( &button ) ); return button.idCommand; } #ifndef TB_HITTEST #define TB_HITTEST (WM_USER + 69) #endif void Toolbar::onLButtonDown( BOOL fDoubleClick, int x, int y, UINT keyFlags ) { assertValid(); Window::onLButtonDown( fDoubleClick, x, y, keyFlags ); if ( fDoubleClick ) { POINT pt = { x, y }; const int index = sendMessage( TB_HITTEST, 0, reinterpret_cast< LPARAM >( &pt ) ); switch ( commandFromIndex( index ) ) { case ID_VIEW_PROPORTIONALFONT: FORWARD_WM_COMMAND( GetParent( *this ), ID_VIEW_SETPROPORTIONALFONT, 0, 0, PostMessage ); break; case ID_VIEW_FIXEDFONT: FORWARD_WM_COMMAND( GetParent( *this ), ID_VIEW_SETFIXEDFONT, 0, 0, PostMessage ); break; } } } PRIVATE LRESULT CALLBACK tabSubclassWndProc( HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam ) { Editor *pEditor = reinterpret_cast< Editor * >( s_tabSubclasser.getUserData( hwnd ) ); assert( isGoodPtr( pEditor ) ); // TODO: Should reorg this as a filter, or subclass both controls! if ( WM_KEYDOWN == msg || WM_KEYUP == msg ) { if ( VK_NEXT == wParam || VK_PRIOR == wParam ) { pEditor->getEditWnd()->sendMessage( msg, wParam, lParam ); } } LRESULT lResult = s_tabSubclasser.callOldProc( hwnd, msg, wParam, lParam ); if ( WM_GETDLGCODE == msg ) { lResult &= ~(DLGC_WANTTAB | DLGC_WANTALLKEYS); } else if ( WM_SETFOCUS == msg ) { pEditor->getStatusbar()->setMessage( IDS_TAB_PROMPT ); } else if ( WM_KILLFOCUS == msg ) { pEditor->getStatusbar()->update( pEditor->getEditWnd()->getCurPos() ); } return lResult; } // TODO: On leaving the field, set contents to actual tab PRIVATE LRESULT CALLBACK toolbarParentSpy( HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam ) { if ( WM_SIZE == msg ) { HWND hwndToolbar = s_parentSubclasser.getUserDataAsHwnd( hwnd ); assert( IsWindow( hwndToolbar ) ); SNDMSG( hwndToolbar, WM_SIZE, wParam, lParam ); } else if ( WM_NOTIFY == msg ) { NMHDR *pHdr = reinterpret_cast< NMHDR * >( lParam ); if ( TBN_DROPDOWN == pHdr->code ) { return onDropdown( hwnd, reinterpret_cast< NMTOOLBAR * >( pHdr ) ); } } return s_parentSubclasser.callOldProc( hwnd, msg, wParam, lParam ); } Toolbar::Toolbar( Editor *pEditor, UINT uiID, bool hasRedo, bool canSetTabs ) { assert( isGoodPtr( this ) ); const HINSTANCE hinst = getModuleHandle(); attach( CreateWindowEx( 0, TOOLBARCLASSNAME, 0, WS_CHILD | WS_VISIBLE | WS_TOOLBAR, 0, 0, 0, 0, pEditor->getMainWnd(), (HMENU) uiID, hinst, 0 ) ); assert( IsWindow( *this ) ); if ( !IsWindow( *this ) ) { throwException( _T( "Failed to create toolbar" ) ); } sendMessage( TB_BUTTONSTRUCTSIZE, sizeof( TBBUTTON ) ); sendMessage( TB_SETINDENT, GetSystemMetrics( SM_CXEDGE ) ); #if ( 0x0400 <= _WIN32_IE ) && defined( TBSTYLE_EX_DRAWDDARROWS ) sendMessage( TB_SETEXTENDEDSTYLE, 0, TBSTYLE_EX_DRAWDDARROWS ); #endif HWND hwndTabs = 0; HWND hwndUpDown = 0; if ( canSetTabs ) { #ifdef _DEBUG HWND hwndTabsLabel = #endif CreateWindowEx( 0, _T( "STATIC" ), loadString( IDS_TABS_LABEL ).c_str(), WS_CHILD | WS_VISIBLE | SS_LEFT, 0, 0, 0, 0, m_hwnd, (HMENU) IDC_TABLABEL, hinst, 0 ); assert( IsWindow( hwndTabsLabel ) ); hwndTabs = CreateWindowEx( WS_EX_CLIENTEDGE, _T( "EDIT" ), 0, WS_CHILD | WS_VISIBLE | WS_TABSTOP | WS_GROUP | ES_AUTOHSCROLL | ES_WANTRETURN | ES_MULTILINE | ES_RIGHT | ES_NUMBER, 0, 0, 0, 0, m_hwnd, (HMENU) IDC_TABEDIT, hinst, 0 ); assert( IsWindow( hwndTabs ) ); hwndUpDown = CreateWindowEx( 0, UPDOWN_CLASS, 0, WS_CHILD | WS_VISIBLE | WS_GROUP | UDS_AUTOBUDDY | UDS_SETBUDDYINT | UDS_ALIGNRIGHT | UDS_ARROWKEYS | UDS_HOTTRACK, 0, 0, 0, 0, m_hwnd, (HMENU) IDC_TABUPDOWN, hinst, 0 ); assert( IsWindow( hwndUpDown ) ); SNDMSG( hwndUpDown, UDM_SETRANGE, 0, (LPARAM) MAKELONG( 16, 1 ) ); SNDMSG( hwndUpDown, UDM_SETPOS , 0, (LPARAM) MAKELONG( 4, 0 ) ); } HWND hwndReadOnly = CreateWindowEx( 0, _T( "BUTTON" ), loadString( IDS_READ_ONLY ).c_str(), WS_CHILD | WS_VISIBLE | WS_TABSTOP | WS_GROUP | BS_AUTOCHECKBOX, 0, 0, 0, 0, m_hwnd, (HMENU) IDC_READONLY, hinst, 0 ); assert( IsWindow( hwndReadOnly ) ); // Add tool tips for the child controls: HWND hwndToolTip = reinterpret_cast< HWND >( sendMessage( TB_GETTOOLTIPS ) ); if ( IsWindow( hwndToolTip ) ) { TOOLINFO toolInfo = { sizeof( TOOLINFO ), TTF_CENTERTIP | TTF_IDISHWND | TTF_SUBCLASS | TTF_TRANSPARENT, *this, reinterpret_cast< UINT >( hwndReadOnly ), { 0 }, hinst, LPSTR_TEXTCALLBACK , }; SNDMSG( hwndToolTip, TTM_ADDTOOL, 0, reinterpret_cast< WPARAM >( &toolInfo ) ); if ( canSetTabs ) { toolInfo.uId = reinterpret_cast< UINT >( hwndTabs ); SNDMSG( hwndToolTip, TTM_ADDTOOL, 0, reinterpret_cast< WPARAM >( &toolInfo ) ); toolInfo.uId = reinterpret_cast< UINT >( hwndUpDown ); SNDMSG( hwndToolTip, TTM_ADDTOOL, 0, reinterpret_cast< WPARAM >( &toolInfo ) ); } #ifdef _DEBUG const LONG lToolTipWndProc = GetWindowLong( hwndToolTip, GWL_WNDPROC ); trace( _T( "lToolTipWndProc = %#x\n" ), lToolTipWndProc ); #endif } adjust( false, hasRedo, canSetTabs ); if ( canSetTabs ) { // This should be done *after* we've created the tool // tips. The tool tip window subclasses hwndTabs, but // does not detach on window destruction. It's better // if we're on top of the food chain. verify( s_tabSubclasser.subclass( hwndTabs, pEditor ) ); } // This may already be subclassed if we're recreating the toolbar, // which happens on WM_SETTINGCHANGE. Doesn't matter. s_parentSubclasser.subclass( pEditor->getMainWnd(), m_hwnd ); assertValid(); } void Toolbar::setButtons( bool hasRedo ) { assertValid(); TBADDBITMAP tbabmpStd = { HINST_COMMCTRL, (UINT_PTR) (MenuFont::isLarge() ? IDB_STD_LARGE_COLOR : IDB_STD_SMALL_COLOR), }; TBADDBITMAP tbabmpCustom = { getModuleHandle(), (UINT_PTR) (MenuFont::isLarge() ? IDR_TOOLBAR_LARGE : IDR_TOOLBAR), }; static const TBBUTTON tb[] = { { STD_FILENEW , ID_FILE_NEW , TBSTATE_ENABLED, TBSTYLE_BUTTON }, { 0 , 0 , 0 , TBSTYLE_SEP }, { STD_FILEOPEN, ID_FILE_OPEN , TBSTATE_ENABLED, TBSTYLE_DROPDOWN }, { 0 , 0 , 0 , TBSTYLE_SEP }, { STD_PRINT , ID_FILE_PRINT , TBSTATE_ENABLED }, { 0 , 0 , 0 , TBSTYLE_SEP }, { STD_DELETE , ID_EDIT_DELETE, TBSTATE_ENABLED }, { STD_CUT , ID_EDIT_CUT , TBSTATE_ENABLED, TBSTYLE_BUTTON }, { STD_COPY , ID_EDIT_COPY , TBSTATE_ENABLED, TBSTYLE_BUTTON }, { STD_PASTE , ID_EDIT_PASTE , TBSTATE_ENABLED, TBSTYLE_BUTTON }, { 0 , 0 , 0 , TBSTYLE_SEP }, { find_icon , ID_EDIT_FIND , TBSTATE_ENABLED }, { 0 , 0 , 0 , TBSTYLE_SEP }, { STD_UNDO , ID_EDIT_UNDO , 0 , TBSTYLE_BUTTON }, { STD_REDOW , ID_EDIT_REDO , 0 , TBSTYLE_BUTTON }, { 0 , 0 , 0 , TBSTYLE_SEP }, { prop_icon, ID_VIEW_PROPORTIONALFONT, TBSTATE_ENABLED, TBSTYLE_CHECKGROUP }, { fixed_icon , ID_VIEW_FIXEDFONT, TBSTATE_ENABLED, TBSTYLE_CHECKGROUP }, { 0 , 0 , 0 , TBSTYLE_SEP }, { wordwrap_icon,ID_VIEW_WORDWRAP, TBSTATE_ENABLED, TBSTYLE_CHECK }, { 0 , ID_TABPLACEHOLDER , 0 , TBSTYLE_SEP }, }; sendMessage( TB_ADDBITMAP, 15, reinterpret_cast< LPARAM >( &tbabmpStd ) ); sendMessage( TB_ADDBITMAP, 4, reinterpret_cast< LPARAM >( &tbabmpCustom ) ); sendMessage( TB_ADDBUTTONS, dim( tb ), reinterpret_cast< LPARAM >( tb ) ); if ( !hasRedo ) { const int index = sendMessage( TB_COMMANDTOINDEX, ID_EDIT_REDO ); assert( 0 <= index ); verify( sendMessage( TB_DELETEBUTTON, index ) ); } sendMessage( TB_AUTOSIZE ); } Toolbar::~Toolbar() { } SIZE measureDlgItem( HWND hwndCtl ) { assert( IsWindow( hwndCtl ) ); TCHAR szText[ 100 ] = { 0 }; GetWindowText( hwndCtl, szText, dim( szText ) ); return measureString( szText ); } SIZE getEditSize( HWND hwndEdit, LPCTSTR pszStipulatedContents ) { assert( IsWindow( hwndEdit ) ); assert( isGoodStringPtr( pszStipulatedContents ) ); SIZE size = measureString( pszStipulatedContents ); const int nXEdge2 = 2 * GetSystemMetrics( SM_CXEDGE ); const int nYEdge2 = 2 * GetSystemMetrics( SM_CYEDGE ); size.cx += 2 + nXEdge2; size.cy += 2 + nYEdge2; return size; } void Toolbar::adjust( bool bRepaint, bool hasRedo, bool canSetTabs ) { assertValid(); setButtons( hasRedo ); setFonts(); const int nPad = GetSystemMetrics( SM_CXDLGFRAME ); Rect rc = getWindowRect( *this ); const int nHeight = rc.height(); sendMessage( TB_GETRECT, ID_TABPLACEHOLDER, (LPARAM) &rc ); OffsetRect( &rc, nPad, 0 ); if ( canSetTabs ) { HWND hwndTabsLabel = GetDlgItem( *this, IDC_TABLABEL ); HWND hwndTabs = GetDlgItem( *this, IDC_TABEDIT ); HWND hwndUpDown = GetDlgItem( *this, IDC_TABUPDOWN ); const SIZE sizeTabsLabel = measureDlgItem( hwndTabsLabel ); const SIZE sizeTabs = getEditSize( hwndTabs, _T( "99999" ) ); Rect rcUpDown = getWindowRect( hwndUpDown ); const SIZE sizeUpDown = { rcUpDown.right - rcUpDown.left, rcUpDown.bottom - rcUpDown.top }; MoveWindow( hwndTabsLabel, rc.right, (nHeight - sizeTabsLabel.cy) / 2, sizeTabsLabel.cx, sizeTabsLabel.cy, bRepaint ); rc.left = rc.right; OffsetRect( &rc, sizeTabsLabel.cx + nPad, 0 ); const int nTabExtra = 4; MoveWindow( hwndTabs, rc.left, (nHeight - sizeTabs.cy) / 2, sizeTabs.cx + sizeUpDown.cx + nTabExtra, sizeTabs.cy, bRepaint ); SNDMSG( hwndUpDown, UDM_SETBUDDY, reinterpret_cast< WPARAM >( hwndTabs ), 0 ); OffsetRect( &rc, sizeTabs.cx + sizeUpDown.cx + 4 + nPad, 0 ); rcUpDown = getWindowRect( hwndUpDown ); const RECT rcEditRect = { 0, 0, sizeTabs.cx - rcUpDown.width(), sizeTabs.cy }; SNDMSG( hwndTabs, EM_SETRECT, 0, reinterpret_cast< LPARAM >( &rcEditRect ) ); } HWND hwndReadOnly = GetDlgItem( *this, IDC_READONLY ); SIZE sizeReadOnly = measureDlgItem( hwndReadOnly ); MoveWindow( hwndReadOnly, rc.left + 10, (nHeight - sizeReadOnly.cy) / 2, sizeReadOnly.cx + 50, sizeReadOnly.cy, bRepaint ); } int Toolbar::getTabs( void ) { assertValid(); BOOL bOK = false; int nTabs = GetDlgItemInt( *this, IDC_TABEDIT, &bOK, false ); return nTabs; } void Toolbar::setSpacesPerTab( int nSpacesPerTab ) { HWND hwndTabsUpDown = getChild( IDC_TABUPDOWN ); assert( IsWindow( hwndTabsUpDown ) ); SNDMSG( hwndTabsUpDown, UDM_SETPOS, 0, (LPARAM) MAKELONG( nSpacesPerTab, 0 ) ); } void Toolbar::setReadOnly( bool bReadOnly, bool bAccessDenied ) { HWND hwndReadOnly = getChild( IDC_READONLY ); assert( IsWindow( hwndReadOnly ) ); // If you really want to be paranoid, verify that it is, // indeed, a checkbox. Button_SetCheck( hwndReadOnly, bReadOnly ? 1 : 0 ); Button_Enable( hwndReadOnly, !bAccessDenied ); } bool Toolbar::getReadOnly( void ) const { HWND hwndReadOnly = getChild( IDC_READONLY ); return 0 != Button_GetCheck( hwndReadOnly ); } void Toolbar::setFonts( void ) { assertValid(); HFONT hfont = MenuFont::getFont(); assert( 0 != hfont ); //messageBox( HWND_DESKTOP, MB_OK | MB_TASKMODAL | MB_SETFOREGROUND, _T( "Toolbar::setFonts" ) ); //assert( FALSE ); #if 0 static int count = 0; ++count; if ( 1 < count ) { debugBreak(); } #endif for ( HWND hwndChild = GetTopWindow( *this ); IsWindow( hwndChild ); hwndChild = GetNextWindow( hwndChild, GW_HWNDNEXT ) ) { SetWindowFont( hwndChild, hfont, true ); } } void Toolbar::onSettingChange( LPCTSTR pszSection ) { assertValid(); //FORWARD_WM_SETTINGCHANGE( hwndChild, pszSection, SNDMSG ); if ( isGoodStringPtr( pszSection ) && 0 == _tcsicmp( _T( "WindowMetrics" ), pszSection ) ) { //adjust( true ); } } LRESULT Toolbar::dispatch( UINT msg, WPARAM wParam, LPARAM lParam ) { /*const*/ LRESULT result = Window::dispatch( msg, wParam, lParam ); #if 0 if ( WM_CTLCOLORSTATIC == msg ) { HTHEME ht = openThemeData( *this, L"Toolbar" ); // TOOLBARCLASSNAMEW if ( 0 != ht ) { COLORREF cr = 0; const HRESULT hres = getThemeColor( ht, TP_BUTTON, TS_NORMAL, TMT_COLOR, &cr ); if ( SUCCEEDED( hres ) ) { result = (LRESULT) CreateSolidBrush( cr ); } closeThemeData( ht ); } } #endif return result; } // end of file
30.937086
100
0.618003
petterh
e7341b14d0a5d906432ed8f7a93af66faecb3dc6
6,063
cpp
C++
pwiz/analysis/peakdetect/PeakExtractorTest.cpp
edyp-lab/pwiz-mzdb
d13ce17f4061596c7e3daf9cf5671167b5996831
[ "Apache-2.0" ]
11
2015-01-08T08:33:44.000Z
2019-07-12T06:14:54.000Z
pwiz/analysis/peakdetect/PeakExtractorTest.cpp
shze/pwizard-deb
4822829196e915525029a808470f02d24b8b8043
[ "Apache-2.0" ]
61
2015-05-27T11:20:11.000Z
2019-12-20T15:06:21.000Z
pwiz/analysis/peakdetect/PeakExtractorTest.cpp
shze/pwizard-deb
4822829196e915525029a808470f02d24b8b8043
[ "Apache-2.0" ]
4
2016-02-03T09:41:16.000Z
2021-08-01T18:42:36.000Z
// // $Id: PeakExtractorTest.cpp 4129 2012-11-20 00:05:37Z chambm $ // // // Original author: Darren Kessner <darren@proteowizard.org> // // Copyright 2009 Center for Applied Molecular Medicine // University of Southern California, Los Angeles, CA // // 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 "PeakExtractor.hpp" #include "pwiz/utility/misc/unit.hpp" #include "pwiz/utility/misc/Std.hpp" #include <cstring> using namespace pwiz::math; using namespace pwiz::util; using namespace pwiz::analysis; using namespace pwiz::data::peakdata; ostream* os_ = 0; const double testData_[] = { 807.9820, 0.0000, 807.9860, 0.0000, 807.9899, 0.0000, 807.9939, 0.0000, 808.9221, 0.0000, 808.9261, 0.0000, 808.9300, 0.0000, 808.9340, 0.0000, 808.9379, 46.1869, 808.9419, 68.1574, 808.9459, 74.2945, 808.9498, 67.5736, 808.9538, 55.4186, 808.9577, 0.0000, 808.9617, 0.0000, 808.9656, 0.0000, 808.9696, 0.0000, 810.3800, 0.0000, 810.3840, 0.0000, 810.3880, 0.0000, 810.3919, 0.0000, 810.3959, 0.0000, 810.3999, 72.5160, 810.4038, 450.4998, 810.4078, 1138.1459, 810.4118, 1834.3859, 810.4158, 2075.0105, 810.4197, 1699.1493, 810.4237, 1021.4493, 810.4277, 500.8886, 810.4316, 276.2554, 810.4356, 179.6894, 810.4396, 127.4826, 810.4435, 91.4053, 810.4475, 55.3596, 810.4515, 0.0000, 810.4554, 0.0000, 810.4594, 0.0000, 810.4634, 0.0000, 810.8248, 0.0000, 810.8288, 0.0000, 810.8327, 0.0000, 810.8367, 0.0000, 810.8407, 32.4939, 810.8447, 66.3772, 810.8486, 89.7902, 810.8526, 70.5686, 810.8566, 16.7061, 810.8605, 0.0000, 810.8645, 32.4340, 810.8685, 71.6267, 810.8725, 91.5372, 810.8764, 81.2383, 810.8804, 52.8255, 810.8844, 0.0000, 810.8884, 0.0000, 810.8923, 0.0000, 810.8963, 0.0000, 810.9003, 0.0000, 810.9043, 54.5496, 810.9082, 532.4702, 810.9122, 1171.1777, 810.9162, 1586.9846, 810.9202, 1490.4944, 810.9241, 979.2804, 810.9281, 434.2267, 810.9321, 162.3475, 810.9361, 128.5575, 810.9400, 134.1554, 810.9440, 123.5086, 810.9480, 88.7253, 810.9520, 48.2328, 810.9559, 0.0000, 810.9599, 0.0000, 810.9639, 0.0000, 810.9678, 0.0000, 811.3854, 0.0000, 811.3894, 0.0000, 811.3934, 0.0000, 811.3973, 0.0000, 811.4013, 9.2748, 811.4053, 133.5402, 811.4093, 298.1690, 811.4132, 463.7706, 811.4172, 554.1553, 811.4212, 503.8234, 811.4252, 333.9661, 811.4292, 149.2269, 811.4331, 48.4688, 811.4371, 0.0000, 811.4411, 0.0000, 811.4451, 0.0000, 811.4491, 0.0000, 811.7675, 0.0000, 811.7715, 0.0000, 811.7755, 0.0000, 811.7795, 0.0000, 811.7835, 41.8127, 811.7874, 69.9106, 811.7914, 87.5734, 811.7954, 91.7424, 811.7994, 90.7267, 811.8034, 87.8043, 811.8074, 74.6657, 811.8113, 46.1904, 811.8153, 0.0000, 811.8193, 0.0000, 811.8233, 0.0000, 811.8273, 0.0000, 812.3853, 0.0000, 812.3893, 0.0000, 812.3933, 0.0000, 812.3972, 0.0000, 812.4012, 23.7360, 812.4052, 85.1701, 812.4092, 124.7133, 812.4132, 118.7524, 812.4172, 69.4944, 812.4212, 9.8729, 812.4252, 0.0000, 812.4292, 0.0000, 812.4331, 0.0000, 812.4371, 0.0000 }; const size_t testDataSize_ = sizeof(testData_)/sizeof(double); void test() { if (os_) *os_ << "test()\n"; shared_ptr<NoiseCalculator> noiseCalculator(new NoiseCalculator_2Pass); PeakFinder_SNR::Config pfsnrConfig; pfsnrConfig.windowRadius = 2; pfsnrConfig.zValueThreshold = 2; shared_ptr<PeakFinder> peakFinder(new PeakFinder_SNR(noiseCalculator, pfsnrConfig)); PeakFitter_Parabola::Config pfpConfig; pfpConfig.windowRadius = 1; // (windowRadius != 1) is not good for real data shared_ptr<PeakFitter> peakFitter(new PeakFitter_Parabola(pfpConfig)); PeakExtractor peakExtractor(peakFinder, peakFitter); OrderedPairContainerRef data(testData_, testData_+testDataSize_); vector<Peak> peaks; peakExtractor.extractPeaks(data, peaks); if (os_) { *os_ << "peaks: " << peaks.size() << endl; copy(peaks.begin(), peaks.end(), ostream_iterator<Peak>(*os_, "\n")); } const double epsilon = .01; unit_assert(peaks.size() == 3); unit_assert_equal(peaks[0].mz, 810.41, epsilon); unit_assert_equal(peaks[1].mz, 810.91, epsilon); unit_assert_equal(peaks[2].mz, 811.41, epsilon); } int main(int argc, char* argv[]) { TEST_PROLOG(argc, argv) try { if (argc>1 && !strcmp(argv[1],"-v")) os_ = &cout; test(); } catch (exception& e) { TEST_FAILED(e.what()) } catch (...) { TEST_FAILED("Caught unknown exception.") } TEST_EPILOG }
26.709251
88
0.555995
edyp-lab
e737bacd8c6470f39a8318e7f801c4e5ea1caa0a
16,241
hpp
C++
extlibs/SSVUtilsJson/extlibs/SSVUtils/include/SSVUtils/HandleVector/HandleVector.hpp
questor/git-ws
4c6db1dd6586be21baf74d97e3caf1006a239aec
[ "AFL-3.0" ]
null
null
null
extlibs/SSVUtilsJson/extlibs/SSVUtils/include/SSVUtils/HandleVector/HandleVector.hpp
questor/git-ws
4c6db1dd6586be21baf74d97e3caf1006a239aec
[ "AFL-3.0" ]
null
null
null
extlibs/SSVUtilsJson/extlibs/SSVUtils/include/SSVUtils/HandleVector/HandleVector.hpp
questor/git-ws
4c6db1dd6586be21baf74d97e3caf1006a239aec
[ "AFL-3.0" ]
null
null
null
// Copyright (c) 2013-2014 Vittorio Romeo // License: Academic Free License ("AFL") v. 3.0 // AFL License page: http://opensource.org/licenses/AFL-3.0 #ifndef SSVU_HANDLEVECTOR #define SSVU_HANDLEVECTOR #include "SSVUtils/Core/Core.hpp" #include "SSVUtils/Range/Range.hpp" #include "SSVUtils/GrowableArray/GrowableArray.hpp" #include "SSVUtils/HandleVector/Internal/Common.hpp" #include "SSVUtils/HandleVector/Internal/Atom.hpp" #include "SSVUtils/HandleVector/Internal/Iterator.hpp" #include "SSVUtils/HandleVector/Handle.hpp" #include "SSVUtils/Internal/SharedFuncs.hpp" namespace ssvu { template<typename T> class HandleVector { template<typename> friend class Handle; private: using Stat = Internal::HVStat; using Mark = Internal::HVMark; public: /// @typedef Templatized `Internal::Atom<T>` type. using Atom = typename Internal::Atom<T>; /// @typedef Pointer-based fast iterator type. using ItrFast = Internal::HVecItrFast<T>; /// @typedef Index-based safe iterator type. using ItrIdx = Internal::HVecItrIdx<T>; /// @typedef Index-based safe atom iterator type. using ItrAtom = Internal::HVecItrAtom<T>; private: /// @brief Internal atom storage. GrowableArray<Atom> atoms; /// @brief Internal mark storage. GrowableArray<Mark> marks; /// @brief Current size. Does not take into account newly created atoms. SizeT size{0u}; /// @brief Next size. Takes into account newly created atoms. SizeT sizeNext{0u}; /// @brief Storage capacity for atoms/marks. SizeT capacity{0u}; /// @brief Increases internal storage capacity by mAmount. inline void growCapacityBy(SizeT mAmount) { auto capacityNew(capacity + mAmount); SSVU_ASSERT(capacityNew >= 0 && capacityNew >= capacity); atoms.grow(capacity, capacityNew); marks.grow(capacity, capacityNew); // Initialize resized storage for(; capacity < capacityNew; ++capacity) { atoms.initAt(capacity, capacity); marks.initAt(capacity, capacity); } } /// @brief Sets internal storage capacity to mCapacity. inline void growCapacityTo(SizeT mCapacityNew) { SSVU_ASSERT(capacity < mCapacityNew); growCapacityBy(mCapacityNew - capacity); } /// @brief Checks if the current capacity is enough - if it isn't, increases it. inline void growIfNeeded() { constexpr float growMultiplier{2.f}; constexpr SizeT growAmount{5}; if(capacity <= sizeNext) growCapacityTo((capacity + growAmount) * growMultiplier); } /// @brief Sets the status of the atom pointed by the mark at mMarkIdx to dead. inline void destroy(HIdx mMarkIdx) noexcept { getAtomFromMark(marks[mMarkIdx]).setDead(); } /// @brief Returns a reference to mAtom's controller mark. inline auto& getMarkFromAtom(const Atom& mAtom) noexcept { return marks[mAtom.getMarkIdx()]; } /// @brief Returns a reference to mMark's controlled atom. inline auto& getAtomFromMark(const Mark& mMark) noexcept { return atoms[mMark.atomIdx]; } inline bool isAliveAt(SizeT mI) const noexcept { return atoms[mI].isAlive(); } inline bool isDeadAt(SizeT mI) const noexcept { return !isAliveAt(mI); } public: inline HandleVector() { growCapacityBy(10); } inline ~HandleVector() noexcept(isNothrowDtor<T>()) { clear(); } inline HandleVector(const HandleVector&) = delete; inline HandleVector(HandleVector&&) = delete; inline auto& operator=(const HandleVector&) = delete; inline auto& operator=(HandleVector&&) = delete; /// @brief Clears the HandleVector, destroying all elements. /// @details Does not alter the capacity. inline void clear() noexcept(isNothrowDtor<T>()) { refresh(); for(auto i(0u); i < size; ++i) { auto& atom(atoms[i]); auto& mark(marks[i]); SSVU_ASSERT(atom.isAlive()); atom.setDead(); atom.deinitData(); ++mark.ctr; } size = sizeNext = 0u; } /// @brief Reserves storage, increasing the capacity. inline void reserve(SizeT mCapacityNew) { if(capacity < mCapacityNew) growCapacityTo(mCapacityNew); } /// @brief Creates and returns an handle pointing to mAtom. /// @details The created atom will not be used until the HandleVector is refreshed. inline auto createHandleFromAtom(Atom& mAtom) noexcept { return Handle<T>{*this, mAtom.getMarkIdx(), getMarkFromAtom(mAtom).ctr}; } /// @brief Creates an atom, returning a reference to it. /// @details The created atom will not be used until the HandleVector is refreshed. template<typename... TArgs> inline auto& createAtom(TArgs&&... mArgs) { // `sizeNext` may be greater than the sizes of the vectors - resize vectors if needed growIfNeeded(); // `sizeNext` now is the first empty valid index - we create our atom there auto& atom(atoms[sizeNext]); atom.initData(fwd<TArgs>(mArgs)...); atom.setAlive(); // Update the mark auto& mark(getMarkFromAtom(atom)); mark.atomIdx = sizeNext; // Update next size ++sizeNext; return atom; } /// @brief Creates an atom, returning an handle pointing to it. /// @details The created atom will not be used until the HandleVector is refreshed. template<typename... TArgs> inline auto create(TArgs&&... mArgs) { return createHandleFromAtom(createAtom(fwd<TArgs>(mArgs)...)); } /// @brief Refreshes the HandleVector. /// @details Dead atoms are deallocated and destroyed. Newly created atoms are now taken into account. inline void refresh() noexcept(isNothrowDtor<T>()) { Internal::refreshImpl(size, sizeNext, [this](SizeT mI){ return isAliveAt(mI); }, [this](SizeT mD, SizeT mA) { std::swap(atoms[mD], atoms[mA]); getMarkFromAtom(atoms[mD]).atomIdx = mD; }, [this](SizeT mD) { atoms[mD].deinitData(); ++(getMarkFromAtom(atoms[mD]).ctr); }); } /// @brief Iterates over alive data. Newly created atoms aren't taken into account. template<typename TFunc> inline void forEach(TFunc mFunc) { for(auto i(0u); i < size; ++i) mFunc(atoms[i].getData()); } /// @brief Iterates over alive atoms. Newly created atoms aren't taken into account. template<typename TFunc> inline void forEachAtom(TFunc mFunc) { for(auto i(0u); i < size; ++i) mFunc(atoms[i]); } /// @brief Returns a reference to the atom at mIdx. inline auto& getAtomAt(HIdx mIdx) noexcept { return atoms[mIdx]; } /// @brief Returns a const reference to the atom at mIdx. inline const auto& getAtomAt(HIdx mIdx) const noexcept { return atoms[mIdx]; } /// @brief Returns a reference to the data at mIdx. Assumes the data is initialized. inline T& getDataAt(HIdx mIdx) noexcept { return getAtomAt(mIdx).getData(); } /// @brief Returns a const reference to the data at mIdx. Assumes the data is initialized. inline const T& getDataAt(HIdx mIdx) const noexcept { return getAtomAt(mIdx).getData(); } /// @brief Returns the current size of the HandleVector. Newly created atoms aren't taken into account. inline auto getSize() const noexcept { return size; } /// @brief Returns the next size of the HandleVector. Newly created atoms are taken into account. inline auto getSizeNext() const noexcept { return sizeNext; } /// @brief Returns a reference to the internal atom storage. inline auto& getAtoms() noexcept { return atoms; } /// @brief Returns a const reference to the internal atom storage. inline const auto& getAtoms() const noexcept { return atoms; } /// @brief Returns a reference to `mData`'s atom. Assumes `mData` is a member of an atom. /// @details Will not work correctly if the HandleVector gets resized (either by reserving or adding elements). inline constexpr Atom& getAtomFromData(T& mData) noexcept { return *(Internal::Atom<T>::getAtomFromPtr(&mData)); } /// @brief Returns a reference to `mHandle`'s atom. inline constexpr Atom& getAtomFromHandle(Handle<T>& mHandle) noexcept { return getAtomFromData(*mHandle); } /// @brief Returns the capacity of the internal storage. inline auto getCapacity() const noexcept { return capacity; } // Fast iterators /// @brief Returns a fast iterator pointing to the first data. /// @details This iterator will be invalidated if the internal storage grows. inline auto begin() noexcept { return ItrFast{&atoms[0]}; } /// @brief Returns a fast iterator pointing one after the last data. Newly created atoms aren't taken into account. /// @details This iterator will be invalidated if the internal storage grows. inline auto end() noexcept { return ItrFast{&atoms[size]}; } /// @brief Returns a fast iterator pointing one after the last newly-created data. Newly created atoms are taken into account. /// @details This iterator will be invalidated if the internal storage grows. inline auto endNext() noexcept { return ItrFast{&atoms[sizeNext]}; } /// @brief Returns a fast iterator pointing to the first data. (const version) /// @details This iterator will be invalidated if the internal storage grows. inline auto begin() const noexcept { return ItrFast{&atoms[0]}; } /// @brief Returns a fast iterator pointing one after the last data. Newly created atoms aren't taken into account. (const version) /// @details This iterator will be invalidated if the internal storage grows. inline auto end() const noexcept { return ItrFast{&atoms[size]}; } /// @brief Returns a fast iterator pointing one after the last newly-created data. Newly created atoms are taken into account. (const version) /// @details This iterator will be invalidated if the internal storage grows. inline auto endNext() const noexcept { return ItrFast{&atoms[sizeNext]}; } // Idx iterators /// @brief Returns an index iterator pointing to the first data. /// @details This iterator won't be invalidated if the internal storage grows. inline auto beginIdx() noexcept { return ItrIdx{0, *this}; } /// @brief Returns an index iterator pointing one after the last data. Newly created atoms aren't taken into account. /// @details This iterator won't be invalidated if the internal storage grows. inline auto endIdx() noexcept { return ItrIdx{size, *this}; } /// @brief Returns an index iterator pointing one after the last newly-created data. Newly created atoms are taken into account. /// @details This iterator won't be invalidated if the internal storage grows. inline auto endIdxNext() noexcept { return ItrIdx{sizeNext, *this}; } /// @brief Returns an index iterator pointing to the first data. (const vesrion) /// @details This iterator won't be invalidated if the internal storage grows. inline auto beginIdx() const noexcept { return ItrIdx{0, *this}; } /// @brief Returns an index iterator pointing one after the last data. Newly created atoms aren't taken into account. (const version) /// @details This iterator won't be invalidated if the internal storage grows. inline auto endIdx() const noexcept { return ItrIdx{size, *this}; } /// @brief Returns an index iterator pointing one after the last newly-created data. Newly created atoms are taken into account. (const version) /// @details This iterator won't be invalidated if the internal storage grows. inline auto endIdxNext() const noexcept { return ItrIdx{sizeNext, *this}; } // Atom iterators /// @brief Returns an index iterator pointing to the first atom. /// @details This iterator won't be invalidated if the internal storage grows. inline auto beginAtom() noexcept { return ItrAtom{0, *this}; } /// @brief Returns an index iterator pointing one after the last atom. /// @details This iterator won't be invalidated if the internal storage grows. inline auto endAtom() noexcept { return ItrAtom{size, *this}; } /// @brief Returns an index iterator pointing to one after the last newly-created atom. /// @details This iterator won't be invalidated if the internal storage grows. inline auto endAtomNext() noexcept { return ItrAtom{sizeNext, *this}; } /// @brief Returns an index iterator pointing to the first atom. (const version) /// @details This iterator won't be invalidated if the internal storage grows. inline auto beginAtom() const noexcept { return ItrAtom{0, *this}; } /// @brief Returns an index iterator pointing one after the last atom. (const version) /// @details This iterator won't be invalidated if the internal storage grows. inline auto endAtom() const noexcept { return ItrAtom{size, *this}; } /// @brief Returns an index iterator pointing to one after the last newly-created atom. (const version) /// @details This iterator won't be invalidated if the internal storage grows. inline auto endAtomNext() const noexcept { return ItrAtom{sizeNext, *this}; } // Fast ranges /// @brief Returns a range using fast iterators. Newly created atoms aren't taken into account. /// @details This range will be invalidated if the internal storage grows. inline auto forFast() noexcept { return makeRange(begin(), end()); } /// @brief Returns a range using fast iterators. Newly created atoms aren't taken into account. (const version) /// @details This range will be invalidated if the internal storage grows. inline auto forFast() const noexcept { return makeRange(begin(), end()); } /// @brief Returns a range using fast iterators. Newly created atoms are taken into account. /// @details This range will be invalidated if the internal storage grows. inline auto forNextFast() noexcept { return makeRange(begin(), endNext()); } /// @brief Returns a range using fast iterators. Newly created atoms are taken into account. (const version) /// @details This range will be invalidated if the internal storage grows. inline auto forNextFast() const noexcept { return makeRange(begin(), endNext()); } // Idx ranges /// @brief Returns a range using idx iterators. Newly created atoms aren't taken into account. /// @details This range will be invalidated if the internal storage grows. inline auto forIdx() noexcept { return makeRange(beginIdx(), endIdx()); } /// @brief Returns a range using idx iterators. Newly created atoms aren't taken into account. (const version) /// @details This range will be invalidated if the internal storage grows. inline auto forIdx() const noexcept { return makeRange(beginIdx(), endIdx()); } /// @brief Returns a range using idx iterators. Newly created atoms are taken into account. /// @details This range will be invalidated if the internal storage gro-ws. inline auto forNextIdx() noexcept { return makeRange(beginIdx(), endIdxNext()); } /// @brief Returns a range using idx iterators. Newly created atoms are taken into account. (const version) /// @details This range will be invalidated if the internal storage gro-ws. inline auto forNextIdx() const noexcept { return makeRange(beginIdx(), endIdxNext()); } // Atom ranges /// @brief Returns a range for atom iteration. Newly created atoms aren't taken into account. /// @details This range will be invalidated if the internal storage grows. inline auto forAtom() noexcept { return makeRange(beginAtom(), endAtom()); } /// @brief Returns a range for atom iteration. Newly created atoms aren't taken into account. (const version) /// @details This range will be invalidated if the internal storage grows. inline auto forAtom() const noexcept { return makeRange(beginAtom(), endAtom()); } /// @brief Returns a range for atom iteration. Newly created atoms are taken into account. /// @details This range will be invalidated if the internal storage grows. inline auto forNextAtom() noexcept { return makeRange(beginAtom(), endAtomNext()); } /// @brief Returns a range for atom iteration. Newly created atoms are taken into account. (const version) /// @details This range will be invalidated if the internal storage grows. inline auto forNextAtom() const noexcept { return makeRange(beginAtom(), endAtomNext()); } }; } #include "SSVUtils/HandleVector/Handle.inl" #endif
41.750643
147
0.708885
questor
8d44ce46a7a7fa91e0b1a4883810718ac4c5a8b9
8,915
hpp
C++
src/core/solver.hpp
thomasfoetisch/tfel
c67acabaf4acf4a93edb55a9f415c87fe6b56e89
[ "BSD-3-Clause" ]
1
2019-07-09T09:31:09.000Z
2019-07-09T09:31:09.000Z
src/core/solver.hpp
thomashilke/tfel
c67acabaf4acf4a93edb55a9f415c87fe6b56e89
[ "BSD-3-Clause" ]
null
null
null
src/core/solver.hpp
thomashilke/tfel
c67acabaf4acf4a93edb55a9f415c87fe6b56e89
[ "BSD-3-Clause" ]
null
null
null
#ifndef SOLVER_H #define SOLVER_H #include <map> #include <string> #include <memory> #include <iostream> #include <iomanip> #include <vector> #include <spikes/array.hpp> #include <lapacke.h> #include <petscksp.h> #include <petsc/private/kspimpl.h> #include <petscdmshell.h> #include "meta.hpp" #include "dictionary.hpp" class matrix; class sparse_matrix; class dense_matrix; class crs_matrix; class skyline_matrix; namespace solver { class basic_solver { public: virtual ~basic_solver() {} void set_operator(const matrix& m); virtual void set_operator(const sparse_matrix& m) = 0; virtual void set_operator(const dense_matrix& m) = 0; virtual bool solve(const array<double>& rhs, array<double>& x, dictionary& report) = 0; }; namespace lapack { class lu: public basic_solver { public: lu(): data{1}, pivots{1}, valid_decomposition(false) {} virtual ~lu() {} void set_operator(const sparse_matrix& m); void set_operator(const dense_matrix& m); void set_operator_size(std::size_t n) { data = array<double>{n, n}; } void set(std::size_t i, std::size_t j, double v) { data.at(i, j) = v; } bool solve(const array<double>& rhs, array<double>& x, dictionary& report) { if (not valid_decomposition) { report = this->report; return false; } x = rhs; lapack_int n(data.get_size(0)); lapack_int info(LAPACKE_dgetrs(LAPACK_ROW_MAJOR, 'N', n, 1, data.get_data(), n, pivots.get_data(), x.get_data(), n)); if (info < 0) { report.set("error", "dgetrs invalid parameter"); return false; } return true; } private: array<double> data; array<lapack_int> pivots; bool valid_decomposition; dictionary report; private: void do_lu_decomposition(); }; } namespace petsc { class initialize { public: static initialize& instance() { if (not inst) inst = new initialize(); return *inst; } static void release() { delete inst; inst = nullptr; } private: initialize() { PetscInitialize(nullptr, nullptr, nullptr, nullptr); } ~initialize() { PetscFinalize(); } static initialize* inst; }; class gmres_ilu: public basic_solver { public: gmres_ilu(const dictionary& params) { std::vector<std::string> expected_keys { "maxits", "restart", "rtol", "atol", "dtol", "ilufill", }; if (not params.keys_exist(expected_keys.begin(), expected_keys.end())) throw std::string("solver::petsc::gmres_ilu: missing key(s) " "in parameter dictionary."); const auto& petsc_init(petsc::initialize::instance()); ignore_unused(petsc_init); PetscErrorCode ierr; ierr = MatCreate(PETSC_COMM_WORLD, &a);CHKERRV(ierr); ierr = MatSetType(a, MATSEQAIJ);CHKERRV(ierr); ierr = VecCreate(PETSC_COMM_WORLD, &b);CHKERRV(ierr); ierr = VecSetType(b, VECSEQ);CHKERRV(ierr); ierr = KSPCreate(PETSC_COMM_WORLD, &ksp);CHKERRV(ierr); ierr = KSPSetType(ksp, KSPGMRES);CHKERRV(ierr); ierr = KSPSetInitialGuessNonzero(ksp, PETSC_TRUE);CHKERRV(ierr); ierr = KSPSetTolerances(ksp, params.get<double>("rtol"), params.get<double>("atol"), params.get<double>("dtol"), params.get<unsigned int>("maxits"));CHKERRV(ierr); ierr = KSPGMRESSetOrthogonalization(ksp, KSPGMRESModifiedGramSchmidtOrthogonalization);CHKERRV(ierr); ierr = KSPGMRESSetRestart(ksp, params.get<unsigned int>("restart"));CHKERRV(ierr); ierr = KSPMonitorSet(ksp, monitor, nullptr, nullptr);CHKERRV(ierr); PC pc; ierr = KSPGetPC(ksp, &pc);CHKERRV(ierr); ierr = PCSetType(pc, PCILU);CHKERRV(ierr); ierr = PCFactorSetLevels(pc, params.get<unsigned int>("ilufill"));CHKERRV(ierr); } virtual ~gmres_ilu() { PetscErrorCode ierr; ierr = MatDestroy(&a);CHKERRV(ierr); ierr = VecDestroy(&b);CHKERRV(ierr); ierr = KSPDestroy(&ksp);CHKERRV(ierr); } virtual void set_operator(const sparse_matrix& m); virtual void set_operator(const dense_matrix& m); virtual bool solve(const array<double>& rhs, array<double>& x, dictionary& report); private: Mat a; Vec b; KSP ksp; static PetscErrorCode monitor(KSP ksp, PetscInt it, PetscReal rnorm, void*) { Vec resid; PetscReal truenorm,bnorm; char normtype[256]; if (it == 0 && ((PetscObject)ksp)->prefix) std::cout << "Residual norms for " << ((PetscObject)ksp)->prefix << " solve." << std::endl; KSPBuildResidual(ksp,NULL,NULL,&resid); VecNorm(resid,NORM_2,&truenorm); VecDestroy(&resid); VecNorm(ksp->vec_rhs,NORM_2,&bnorm); PetscStrncpy(normtype,KSPNormTypes[ksp->normtype],sizeof(normtype)); PetscStrtolower(normtype); std::cout << it << " KSP " << normtype << " resid norm " << std::setw(14) << std::right << rnorm << " true resid norm " << std::setw(14) << std::right << truenorm << "||r(i)||/||b||" << std::setw(14) << std::right << truenorm/bnorm << std::endl; return 0; } }; } } class matrix { public: virtual ~matrix() {} virtual void populate_solver(solver::basic_solver& s) const = 0; virtual std::size_t get_row_number() const = 0; virtual std::size_t get_column_number() const = 0; virtual std::size_t get_nz_element_number() const = 0; virtual void clear() = 0; virtual void set(std::size_t i, std::size_t j, double v) = 0; virtual void add(std::size_t i, std::size_t j, double v) = 0; virtual double get(std::size_t i, std::size_t j) const = 0; virtual double& get(std::size_t i, std::size_t j) = 0; }; class sparse_matrix: public matrix { public: friend class solver::lapack::lu; friend class solver::petsc::gmres_ilu; sparse_matrix(std::size_t n_row, std::size_t n_column) : n_row(n_row), n_column(n_column) {} virtual void populate_solver(solver::basic_solver& s) const { s.set_operator(*this); } virtual std::size_t get_row_number() const { return n_row; } virtual std::size_t get_column_number() const { return n_column; } virtual std::size_t get_nz_element_number() const { return values.size(); } virtual void clear() { values.clear(); } virtual void set(std::size_t i, std::size_t j, double v) { values[std::make_pair(i, j)] = v; } virtual void add(std::size_t i, std::size_t j, double v) { values[std::make_pair(i, j)] += v; } virtual double get(std::size_t i, std::size_t j) const { auto item(values.find(std::make_pair(i,j))); if (item == values.end()) return 0.0; else return item->second; } virtual double& get(std::size_t i, std::size_t j) { auto result(values.insert(std::make_pair(std::make_pair(i, j), 0.0))); return result.first->second; } private: std::size_t n_row, n_column; std::map<std::pair<std::size_t, std::size_t>, double> values; }; class dense_matrix: public matrix { public: friend class solver::lapack::lu; friend class solver::petsc::gmres_ilu; dense_matrix(std::size_t n_row, std::size_t n_column): values{n_row, n_column} {} virtual void populate_solver(solver::basic_solver& s) const { s.set_operator(*this); } virtual std::size_t get_row_number() const { return values.get_size(0); } virtual std::size_t get_column_number() const { return values.get_size(1); } virtual std::size_t get_nz_element_number() const { return values.get_size(0) * values.get_size(1); } virtual void clear() { values.fill(0.0); } virtual void set(std::size_t i, std::size_t j, double v) { values.at(i, j) = v; } virtual void add(std::size_t i, std::size_t j, double v) { values.at(i, j) += v; } virtual double get(std::size_t i, std::size_t j) const { return values.at(i, j); } virtual double& get(std::size_t i, std::size_t j) { return values.at(i, j); } private: array<double> values; }; #endif /* SOLVER_H */
27.179878
109
0.581716
thomasfoetisch
8d45013cfd2c507254705d6887b484cd16748f0c
6,394
cpp
C++
src/render/Pipeline/Texture2D.cpp
AluminiumRat/mtt
3052f8ad0ffabead05a1033e1d714a61e77d0aa8
[ "MIT" ]
null
null
null
src/render/Pipeline/Texture2D.cpp
AluminiumRat/mtt
3052f8ad0ffabead05a1033e1d714a61e77d0aa8
[ "MIT" ]
null
null
null
src/render/Pipeline/Texture2D.cpp
AluminiumRat/mtt
3052f8ad0ffabead05a1033e1d714a61e77d0aa8
[ "MIT" ]
null
null
null
#include <stdexcept> #include <mtt/render/Pipeline/Texture2D.h> #include <mtt/render/LogicalDevice.h> #include <mtt/render/PlainBuffer.h> #include <mtt/utilities/Abort.h> using namespace mtt; Texture2D::Texture2D(LogicalDevice& device) noexcept : AbstractTexture(TEXTURE_2D, device), _dataFormat(VK_FORMAT_R8G8B8A8_SRGB), _extent(1, 1), _samples(VK_SAMPLE_COUNT_1_BIT), _lodCount(1) { makeEmpty(_dataFormat, _extent, _samples, _lodCount); } void Texture2D::makeEmpty(VkFormat dataFormat, const glm::uvec2& extent, VkSampleCountFlagBits samples, uint32_t lodCount) { if(extent.x == 0 || extent.y == 0) Abort("Texture2D::makeEmpty: invalid extent."); if(lodCount == 0) Abort("Texture2D::makeEmpty: lodCount is 0."); Ref<Image> newImage = _buildImage(nullptr, 0, 0, dataFormat, extent, samples, lodCount); Ref<ImageView> newImageView = _buildImageView(*newImage, VK_IMAGE_ASPECT_COLOR_BIT); setView(newImageView.get()); _dataFormat = dataFormat; _extent = extent; _samples = samples; _lodCount = lodCount; } void Texture2D::setData(const void* data, size_t datasize, VkFormat dataFormat, const glm::uvec2& extent, VkSampleCountFlagBits samples, uint32_t srcRowLength, bool generateLods) { if (data == nullptr) Abort("Texture2D::setData: data is null."); if (datasize == 0) Abort("Texture2D::setData: datasize is null."); if (extent.x == 0 || extent.y == 0) Abort("Texture2D::setData: invalid extent."); uint32_t newLodCount; if (generateLods) newLodCount = Image::calculateMipNumber(extent); else newLodCount = 1; Ref<Image> newImage = _buildImage(data, datasize, srcRowLength, dataFormat, extent, samples, newLodCount); Ref<ImageView> newImageView = _buildImageView(*newImage, VK_IMAGE_ASPECT_COLOR_BIT); setView(newImageView.get()); _dataFormat = dataFormat; _extent = extent; _samples = samples; _lodCount = newLodCount; } Ref<Image> Texture2D::_buildImage(const void* data, size_t datasize, uint32_t srcRowLength, VkFormat dataFormat, const glm::uvec2& extent, VkSampleCountFlagBits samples, uint32_t lodCount) { if(datasize != 0) { Ref<Image> newImage(new Image(VK_IMAGE_TYPE_2D, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_SAMPLED_BIT, 0, dataFormat, glm::uvec3(extent, 1), samples, lodCount, VK_IMAGE_ASPECT_COLOR_BIT, data, datasize, srcRowLength, 0, device())); return newImage; } else { Ref<Image> newImage(new Image(VK_IMAGE_TYPE_2D, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_SAMPLED_BIT, 0, dataFormat, glm::uvec3(extent, 1), samples, 1, lodCount, VK_IMAGE_ASPECT_COLOR_BIT, device())); return newImage; } } void Texture2D::setImage(Image& newImage, VkImageAspectFlags dataAspect) { if(newImage.imageType() != VK_IMAGE_TYPE_2D) Abort("Texture2D::setImage: wrong image type."); Ref<ImageView> newImageView = _buildImageView(newImage, dataAspect); setView(newImageView.get()); _dataFormat = newImage.format(); _extent = newImage.extent(); _samples = newImage.samples(); _lodCount = newImage.mipmapCount(); } Ref<ImageView> Texture2D::_buildImageView(Image& image, VkImageAspectFlags dataAspect) { VkComponentMapping colorMapping; colorMapping.r = VK_COMPONENT_SWIZZLE_IDENTITY; colorMapping.g = VK_COMPONENT_SWIZZLE_IDENTITY; colorMapping.b = VK_COMPONENT_SWIZZLE_IDENTITY; colorMapping.a = VK_COMPONENT_SWIZZLE_IDENTITY; VkImageSubresourceRange subresourceRange; subresourceRange.aspectMask = dataAspect; subresourceRange.baseMipLevel = 0; subresourceRange.levelCount = image.mipmapCount(); subresourceRange.baseArrayLayer = 0; subresourceRange.layerCount = 1; Ref<ImageView> imageView(new ImageView( image, VK_IMAGE_VIEW_TYPE_2D, colorMapping, subresourceRange)); return imageView; } void Texture2D::setImageView(ImageView& newImageView) { if(newImageView.viewType() != VK_IMAGE_VIEW_TYPE_2D) { Abort("Texture2D::setImageView: wrong imageview type."); } setView(&newImageView); _extent = newImageView.extent(); _dataFormat = newImageView.image().format(); _samples = newImageView.image().samples(); _lodCount = newImageView.subresourceRange().levelCount; }
35.921348
95
0.514545
AluminiumRat
8d486df3bf2342d2543d9f85cd70e32330238dc5
4,647
hpp
C++
src/elona/enchantment.hpp
ElonaFoobar/ElonaFoobar
35864685dcca96c4c9ad683c4f5b3537e86bc06f
[ "MIT" ]
84
2018-03-03T02:44:32.000Z
2019-07-14T16:16:24.000Z
src/elona/enchantment.hpp
ki-foobar/ElonaFoobar
d251cf5bd8c21789db3b56b1c9b1302ce69b2c2e
[ "MIT" ]
685
2018-02-27T04:31:17.000Z
2019-07-12T13:43:00.000Z
src/elona/enchantment.hpp
ki-foobar/ElonaFoobar
d251cf5bd8c21789db3b56b1c9b1302ce69b2c2e
[ "MIT" ]
23
2019-07-26T08:52:38.000Z
2021-11-09T09:21:58.000Z
#pragma once #include <string> #include <vector> #include "../util/range.hpp" #include "enums.hpp" #include "eobject/forward.hpp" #include "optional.hpp" #include "serialization/concepts.hpp" namespace elona { struct Character; struct Item; struct Enchantment { int id = 0; int power = 0; bool operator==(const Enchantment& other) const noexcept { return id == other.id && power == other.power; } }; // Enchantments are sorted by ID (descending order). struct EnchantmentList { using storage_type = std::vector<Enchantment>; using iterator = storage_type::iterator; using const_iterator = storage_type::const_iterator; EnchantmentList() = default; Enchantment& operator[](size_t index) { return _enchantments.at(index); } const Enchantment& operator[](size_t index) const { return _enchantments.at(index); } size_t size() const noexcept { return _enchantments.size(); } bool empty() const noexcept { return _enchantments.empty(); } void clear() noexcept { _enchantments.clear(); } void add(int id, int power) { if (id == 0) return; for (size_t i = 0; i < size(); ++i) { auto& enc = _enchantments[i]; if (enc.id == id) { enc.power += power; return; } } _enchantments.push_back(Enchantment{id, power}); sort(); } void remove(int id, int power) { if (id == 0) return; for (size_t i = 0; i < size(); ++i) { auto& enc = _enchantments[i]; if (enc.id == id) { enc.power -= power; if (enc.power == 0) { // Remove the enchantment _enchantments.erase(_enchantments.begin() + i); } break; } } } void remove_last() { if (empty()) return; _enchantments.pop_back(); } bool has(int id) const noexcept { for (const auto& enc : _enchantments) { if (enc.id == id) return true; } return false; } void sort() { range::sort(_enchantments, [](const auto& e1, const auto& e2) { return e1.id > e2.id; // descending }); } // Range interface iterator begin() noexcept { return _enchantments.begin(); } iterator end() noexcept { return _enchantments.end(); } const_iterator begin() const noexcept { return _enchantments.begin(); } const_iterator end() const noexcept { return _enchantments.end(); } const_iterator cbegin() const noexcept { return _enchantments.cbegin(); } const_iterator cend() const noexcept { return _enchantments.cend(); } private: storage_type _enchantments; }; bool enchantment_add( const ItemRef& item, int type, int power, int flip_percentage = 0, bool not_halve = false, bool only_check = false, bool force = false); /** * Removes the enchantment or reduces its power from the item. * * @param item The item * @param id The enchantment ID * @param power The enchantment's power will be reduced by @a power. */ void enchantment_remove(const ItemRef& item, int id, int power); /** * Find enchantments from chara's equipments. * * @param chara The character * @param id The enchantment ID * @return The strongest power of the enchantment if found; otherwise, returns * none. */ optional<int> enchantment_find(const Character& chara, int id); /** * Find enchantments from the item. * * @param item The item * @param id The enchantment ID * @return The power of the enchantment if found; otherwise, returns none. */ optional<int> enchantment_find(const ItemRef& item, int id); int enchantment_generate(int rank); int enchantment_gen_level(int base_level); /** * Calculate power of random enchantment. * * @param multiplier The multiplier of the power (%) */ int enchantment_gen_p(int multiplier = 100); std::string enchantment_print_level(int level); void get_enchantment_description(int, int, ItemCategory, bool = false); void add_enchantments(const ItemRef& item); void initialize_ego_data(); /** * Initialize enchantment data. It called from init.cpp only once. */ void enchantment_init(); } // namespace elona
17.736641
78
0.581235
ElonaFoobar
8d4adae6f338d909989704e58826c1cf14bed604
961
cpp
C++
Plugins/Wwise/Source/AkAudio/Private/AkAuxBus.cpp
BeatItOtaku/Eclair3
a6129725918b63612fb4477d80305c930962974c
[ "MIT" ]
null
null
null
Plugins/Wwise/Source/AkAudio/Private/AkAuxBus.cpp
BeatItOtaku/Eclair3
a6129725918b63612fb4477d80305c930962974c
[ "MIT" ]
1
2019-08-18T15:57:03.000Z
2019-08-18T15:57:03.000Z
Plugins/Wwise/Source/AkAudio/Private/AkAuxBus.cpp
BeatItOtaku/Eclair3
a6129725918b63612fb4477d80305c930962974c
[ "MIT" ]
null
null
null
// Copyright (c) 2006-2012 Audiokinetic Inc. / All Rights Reserved /*============================================================================= AkReverbVolume.cpp: =============================================================================*/ #include "AkAuxBus.h" #include "AkAudioDevice.h" #include "AkAudioClasses.h" #include "Net/UnrealNetwork.h" /*------------------------------------------------------------------------------------ UAkAuxBus ------------------------------------------------------------------------------------*/ UAkAuxBus::UAkAuxBus(const class FObjectInitializer& ObjectInitializer) : Super(ObjectInitializer) { if (HasAnyFlags(RF_ClassDefaultObject)) { AuxBusId = AK_INVALID_AUX_ID; } else { // Property initialization FAkAudioDevice* AkAudioDevice = FAkAudioDevice::Get(); if (AkAudioDevice) { AuxBusId = AkAudioDevice->GetIDFromString(GetName()); } else { AuxBusId = AK_INVALID_AUX_ID; } } }
25.289474
86
0.478668
BeatItOtaku
8d4b6a97fd16279d753c84264d4a418ea8ee9ce1
483
cpp
C++
src/events/MyEndBaroCalCmd.cpp
LinuxDroneLab/MyDrone
33b8e9f15cebf79da0141e4d8aa5f4d57da73b3e
[ "Apache-2.0" ]
2
2021-05-31T09:46:39.000Z
2022-02-17T12:33:43.000Z
src/events/MyEndBaroCalCmd.cpp
LinuxDroneLab/MyLinuxDrone
33b8e9f15cebf79da0141e4d8aa5f4d57da73b3e
[ "Apache-2.0" ]
17
2018-09-03T05:41:37.000Z
2018-11-15T07:48:20.000Z
src/events/MyEndBaroCalCmd.cpp
LinuxDroneLab/MyLinuxDrone
33b8e9f15cebf79da0141e4d8aa5f4d57da73b3e
[ "Apache-2.0" ]
null
null
null
/* * MyEndBaroCalCmd.cpp * * Created on: 17 dic 2015 * Author: andrea */ #include <commons/MyPriority.h> #include <events/MyEndBaroCalCmd.h> MyEndBaroCalCmd::MyEndBaroCalCmd(boost::uuids::uuid origin, boost::uuids::uuid destination) : MyCmd(origin, destination) { this->setPriority(MyPriority::END_BARO_CALIBRATION_PRIORITY); } MyEndBaroCalCmd::~MyEndBaroCalCmd() { } MyEvent::EventType MyEndBaroCalCmd::getType() const { return MyEvent::EventType::EndBaroCalCmd; }
23
122
0.747412
LinuxDroneLab
8d4bedf1528008024ed841b677393df56cc9fed4
547
cpp
C++
src/im_colorutil.cpp
hleuwer/im
178a9614868487689529b56d9cb3daedd98fc593
[ "MIT" ]
2
2022-03-04T13:33:48.000Z
2022-03-04T13:33:49.000Z
src/im_colorutil.cpp
hleuwer/im
178a9614868487689529b56d9cb3daedd98fc593
[ "MIT" ]
null
null
null
src/im_colorutil.cpp
hleuwer/im
178a9614868487689529b56d9cb3daedd98fc593
[ "MIT" ]
null
null
null
/** \file * \brief Color Utilities * * See Copyright Notice in im_lib.h */ #include <stdlib.h> #include <memory.h> #include <string.h> #include "im.h" #include "im_util.h" long imColorEncode(unsigned char Red, unsigned char Green, unsigned char Blue) { return (((long)Red) << 16) | (((long)Green) << 8) | ((long)Blue); } void imColorDecode(unsigned char* Red, unsigned char* Green, unsigned char* Blue, long Color) { if (Red) *Red = (imbyte)(Color >> 16); if (Green) *Green = (imbyte)(Color >> 8); if (Blue) *Blue = (imbyte)Color; }
20.259259
93
0.648995
hleuwer
8d4c1695a3b9d5d473b044fdb1171a5c20fca83e
1,792
cpp
C++
4 - Roteadores/Roteadores.cpp
HomeniqueM/Atividades-LPA
1bc2f429d4d6afd807095be877145fbedf282329
[ "MIT" ]
null
null
null
4 - Roteadores/Roteadores.cpp
HomeniqueM/Atividades-LPA
1bc2f429d4d6afd807095be877145fbedf282329
[ "MIT" ]
null
null
null
4 - Roteadores/Roteadores.cpp
HomeniqueM/Atividades-LPA
1bc2f429d4d6afd807095be877145fbedf282329
[ "MIT" ]
null
null
null
#include <algorithm> #include <iostream> #include <vector> using namespace std; #define par pair<int, int> class Rede { private: vector<pair<int, par>> Rd; // Rede vector<pair<int, par>> mst; // mst int *parent; int V; // Numero de Vertice public: Rede(int V); void AddRoteadorComCusto(int u, int v, int w); int find_set(int i); void union_set(int u, int v); void kruskal(); void CalcularCustoTotal(); }; // Iniciar a classe de Rede Rede::Rede(int V) { parent = new int[V]; for (int i = 0; i < V; i++) parent[i] = i; Rd.clear(); mst.clear(); } // Adicionar roteador com o custo void Rede::AddRoteadorComCusto(int u, int v, int w) { Rd.push_back(make_pair(w, par(u, v))); } int Rede::find_set(int i) { if (i == parent[i]) { return i; } else { return find_set(parent[i]); } } void Rede::union_set(int u, int v) { parent[u] = parent[v]; } void Rede::kruskal() { int i, uRep, vRep; int size = Rd.size(); sort(Rd.begin(), Rd.end()); for (int i = 0; i < size; i++) { uRep = find_set(Rd[i].second.first); vRep = find_set(Rd[i].second.second); if (uRep != vRep) { mst.push_back(Rd[i]); // Adiciona a mst union_set(uRep, vRep); } } } void Rede::CalcularCustoTotal() { int total = 0; for (int i = 0; i < mst.size(); i++) { total += mst[i].first; } cout << total << endl; } int main() { int roteadorA, roteadorB, cabo; int R, C; // Roteadores, cabos cin >> R; cin >> C; Rede Rede(R); for (int i = 0; i < C; i++) { // Entrada de dado cin >> roteadorA; cin >> roteadorB; cin >> cabo; // Criancao de uma coneção Rede.AddRoteadorComCusto(roteadorA, roteadorB, cabo); } Rede.kruskal(); Rede.CalcularCustoTotal(); return 0; }
15.316239
57
0.580915
HomeniqueM
8d4cc09f6f9f31f08b5fe555eac52e05a458d094
2,096
cpp
C++
src/TestSwitching.cpp
paulherman/cvm
af85bc6ccdd2e5db66f2ce7e1e6a8fde2051ad83
[ "MIT" ]
null
null
null
src/TestSwitching.cpp
paulherman/cvm
af85bc6ccdd2e5db66f2ce7e1e6a8fde2051ad83
[ "MIT" ]
null
null
null
src/TestSwitching.cpp
paulherman/cvm
af85bc6ccdd2e5db66f2ce7e1e6a8fde2051ad83
[ "MIT" ]
null
null
null
#include <fstream> #include <cds/init.h> #include <iostream> #include <ctime> #include "Program.h" int main(int argc, char **argv) { cds::Initialize(); std::vector<Instr> instructions = { Instr(Opcode::Spawn, (int64_t)1), Instr(Opcode::Spawn, (int64_t)1), Instr(Opcode::Spawn, (int64_t)1), Instr(Opcode::Spawn, (int64_t)1), Instr(Opcode::Spawn, (int64_t)1), Instr(Opcode::Spawn, (int64_t)1), Instr(Opcode::Spawn, (int64_t)1), Instr(Opcode::Spawn, (int64_t)1), Instr(Opcode::Spawn, (int64_t)1), Instr(Opcode::Spawn, (int64_t)1), Instr(Opcode::Spawn, (int64_t)1), Instr(Opcode::Spawn, (int64_t)1), Instr(Opcode::Spawn, (int64_t)1), Instr(Opcode::Spawn, (int64_t)1), Instr(Opcode::Spawn, (int64_t)1), Instr(Opcode::Spawn, (int64_t)1), Instr(Opcode::Spawn, (int64_t)1), Instr(Opcode::Spawn, (int64_t)1), Instr(Opcode::Spawn, (int64_t)1), Instr(Opcode::Spawn, (int64_t)1), Instr(Opcode::Spawn, (int64_t)1), Instr(Opcode::Spawn, (int64_t)1), Instr(Opcode::Spawn, (int64_t)1), Instr(Opcode::Spawn, (int64_t)1), Instr(Opcode::Spawn, (int64_t)1), Instr(Opcode::Spawn, (int64_t)1), Instr(Opcode::Spawn, (int64_t)1), Instr(Opcode::Spawn, (int64_t)1), Instr(Opcode::Spawn, (int64_t)1), Instr(Opcode::Spawn, (int64_t)1), Instr(Opcode::Spawn, (int64_t)1), Instr(Opcode::Spawn, (int64_t)1), Instr(Opcode::Ret) }; std::shared_ptr<Function> f(new Function(0, 0, std::move(instructions))); std::vector<Instr> yieldInstrs; for (size_t i = 0; i < 512; i++) { yieldInstrs.push_back(Instr(Opcode::Yield)); } yieldInstrs.push_back(Instr(Opcode::Ret)); std::shared_ptr<Function> s(new Function(0, 0, std::move(yieldInstrs))); std::vector<std::shared_ptr<Function>> functions = { f, s }; std::vector<Type *> types = Type::primitives; types.push_back(new Type(TypeKind::Struct, { &Type::intType })); Program p(std::move(types), std::move(functions)); std::cout << "Total time " << p.runPool(1, true) << std::endl; cds::Terminate(); return 0; }
30.823529
75
0.640267
paulherman
8d4e3d593a512bd68dabb0f37f046c52ed1a6a28
1,162
cpp
C++
QInt/QInt/StringFunction.cpp
vominhtrieu/QInt
4f6cedf17c55f16e9d032150b8dd72f21d5aca1b
[ "MIT" ]
null
null
null
QInt/QInt/StringFunction.cpp
vominhtrieu/QInt
4f6cedf17c55f16e9d032150b8dd72f21d5aca1b
[ "MIT" ]
null
null
null
QInt/QInt/StringFunction.cpp
vominhtrieu/QInt
4f6cedf17c55f16e9d032150b8dd72f21d5aca1b
[ "MIT" ]
null
null
null
#pragma once #include "StringFunction.h" string divideBy2(string num) { if (num == "1" || num == "0") return "0"; string result; char remainder = 0, temp; int i = 0; if (num[0] == '1') { remainder = 1; i++; } for (; i < num.length(); i++) { temp = remainder * 10 + num[i] - '0'; result.push_back(temp / 2 + +'0'); //When divided by 2, the remainder can be only 0 or 1. //We can use & 1 to determine a number is even or odd. //If the number is even, the remainder is 1. Else remainder is 0. remainder = temp & 1; } return result; } string addStringNumber(string &a, string &b) { if (a.length() < b.length()) return addStringNumber(b, a); string result = ""; reverse(a.begin(), a.end()); reverse(b.begin(), b.end()); char carry = 0; int i; for (i = 0; i < b.length(); i++) { char temp = a[i] - '0' + b[i] - '0' + carry; result.push_back(temp % 10 + '0'); carry = temp / 10; } for (; i < a.length(); i++) { char temp = a[i] - '0' + carry; result.push_back(temp % 10 + '0'); carry = temp / 10; } if (carry) result.push_back(carry + '0'); reverse(result.begin(), result.end()); return result; }
18.15625
67
0.567986
vominhtrieu
8d4f758ada27559f95e9138e254a9c8188f44c18
2,859
hh
C++
gecode/int/exec.hh
Dekker1/gecode
bbefcea214fec798a0f5acc442581984555acd21
[ "MIT-feh" ]
null
null
null
gecode/int/exec.hh
Dekker1/gecode
bbefcea214fec798a0f5acc442581984555acd21
[ "MIT-feh" ]
null
null
null
gecode/int/exec.hh
Dekker1/gecode
bbefcea214fec798a0f5acc442581984555acd21
[ "MIT-feh" ]
null
null
null
/* -*- mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- */ /* * Main authors: * Christian Schulte <schulte@gecode.org> * * Copyright: * Christian Schulte, 2009 * * This file is part of Gecode, the generic constraint * development environment: * http://www.gecode.org * * 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. * */ #ifndef GECODE_INT_EXEC_HH #define GECODE_INT_EXEC_HH #include <gecode/int.hh> /** * \namespace Gecode::Int::Exec * \brief Synchronized execution */ namespace Gecode { namespace Int { namespace Exec { /** * \brief Conditional propagator * * Requires \code #include <gecode/int/exec.hh> \endcode * \ingroup FuncIntProp */ class When : public UnaryPropagator<BoolView,PC_BOOL_VAL> { protected: using UnaryPropagator<BoolView,PC_BOOL_VAL>::x0; /// Then function SharedData<std::function<void(Space& home)>> t; /// Else function pointer SharedData<std::function<void(Space& home)>> e; /// Constructor for cloning \a p When(Space& home, When& p); /// Constructor for creation When(Home home, BoolView x, std::function<void(Space& home)> t, std::function<void(Space& home)> e); public: /// Copy propagator during cloning GECODE_INT_EXPORT virtual Actor* copy(Space& home); /// Perform propagation GECODE_INT_EXPORT virtual ExecStatus propagate(Space& home, const ModEventDelta& med); /// Post propagator static ExecStatus post(Home home, BoolView x, std::function<void(Space& home)> t, std::function<void(Space& home)> e); /// Dispose propagator GECODE_INT_EXPORT virtual size_t dispose(Space& home); }; }}} #include <gecode/int/exec/when.hpp> #endif // STATISTICS: int-prop
32.123596
74
0.687303
Dekker1
8d512917c9c041c5c4429a8ca9dee0f74a78df04
2,032
cpp
C++
Singly Linked List/Reverse_in_groups_Recursive.cpp
susantabiswas/placementPrep
22a7574206ddc63eba89517f7b68a3d2f4d467f5
[ "MIT" ]
19
2018-12-02T05:59:44.000Z
2021-07-24T14:11:54.000Z
Singly Linked List/Reverse_in_groups_Recursive.cpp
susantabiswas/placementPrep
22a7574206ddc63eba89517f7b68a3d2f4d467f5
[ "MIT" ]
null
null
null
Singly Linked List/Reverse_in_groups_Recursive.cpp
susantabiswas/placementPrep
22a7574206ddc63eba89517f7b68a3d2f4d467f5
[ "MIT" ]
13
2019-04-25T16:20:00.000Z
2021-09-06T19:50:04.000Z
//Reverses the Linked List in Groups of K nodes using Recursion /*Example: Inputs: 1->2->3->4->5->6->7->8->NULL and k = 3 Output: 3->2->1->6->5->4->8->7->NULL. */ #include<iostream> using namespace std; struct Node { int data; Node *next; }; class List { public: Node *head; //head for the list List() { head = NULL; } Node* create(int); void InsertBegin(int); void Display(); Node* Reverse_group(int k,Node*,Node*); }; Node* List::create(int localData) //for creating a node { try { Node *node = new Node; if (node == NULL) { cout << "Allocation failure\n"; } node->data = localData; node->next = NULL; return node; } catch (bad_alloc xa) { cout << "Allocation failure\n"; return NULL; } } void List::InsertBegin(int dataItem) //for inserting the node in the of Beginning list { Node *node = create(dataItem); if (node!=NULL) { if (head == NULL) { head = node; node->next = NULL; } else { node->next = head; head = node; } } else { cout << "Can't create node\n"; } } //Reverses the Linked List in group of 'k' nodes //Returns the new head pointer Node* List::Reverse_group(int k,Node*prev,Node*head) { //base case //If the List is empty if(head==NULL) { return NULL; } Node *first=head; Node *nextNode=NULL; int c=1; while(c++<=k && head!=NULL) { nextNode=head->next; head->next=prev; prev=head; head=nextNode; } //if the list is not empty first->next=Reverse_group(k,prev,nextNode); //return the add. of first node of the group return prev; } void List::Display() //for displaying the list { cout << "\nContents of List:\n"; Node*temp = head; while (temp != NULL ) { cout << temp->data << " "; temp = temp->next; } } int main() { int k; List list1; for (int i = 8; i >0;--i) { list1.InsertBegin(i); } list1.Display(); cout<<"\nEnter the value of K\n"; cin>>k; List list2; list2.head=list1.Reverse_group(k,NULL,list1.head); list2.Display(); return 0; }
15.278195
88
0.605807
susantabiswas
8d53f8856b0eb55e51ea0c6ff7d2bbe3004c1978
16,642
hxx
C++
rutil/dns/DnsStub.hxx
dulton/reSipServer
ac4241df81c1e3eef2e678271ffef4dda1fc6747
[ "Apache-2.0" ]
1
2019-04-15T14:10:58.000Z
2019-04-15T14:10:58.000Z
rutil/dns/DnsStub.hxx
dulton/reSipServer
ac4241df81c1e3eef2e678271ffef4dda1fc6747
[ "Apache-2.0" ]
null
null
null
rutil/dns/DnsStub.hxx
dulton/reSipServer
ac4241df81c1e3eef2e678271ffef4dda1fc6747
[ "Apache-2.0" ]
2
2019-10-31T09:11:09.000Z
2021-09-17T01:00:49.000Z
#ifndef RESIP_DNS_STUB_HXX #define RESIP_DNS_STUB_HXX #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <vector> #include <list> #include <map> #include <set> #include "rutil/FdPoll.hxx" #include "rutil/Fifo.hxx" #include "rutil/GenericIPAddress.hxx" #include "rutil/SelectInterruptor.hxx" #include "rutil/Socket.hxx" #include "rutil/dns/DnsResourceRecord.hxx" #include "rutil/dns/DnsAAAARecord.hxx" #include "rutil/dns/DnsCnameRecord.hxx" #include "rutil/dns/DnsHostRecord.hxx" #include "rutil/dns/DnsNaptrRecord.hxx" #include "rutil/dns/DnsSrvRecord.hxx" #include "rutil/dns/RRCache.hxx" #include "rutil/dns/RROverlay.hxx" #include "rutil/dns/ExternalDns.hxx" #include "rutil/AsyncProcessHandler.hxx" namespace resip { class FdPollGrp; class GetDnsCacheDumpHandler { public: GetDnsCacheDumpHandler() {} virtual ~GetDnsCacheDumpHandler() {} virtual void onDnsCacheDumpRetrieved(std::pair<unsigned long, unsigned long> key, const Data& dnsCache) = 0; }; template<typename T> class DNSResult { public: Data domain; int status; Data msg; std::vector<T> records; EncodeStream& dump(EncodeStream& strm) const { if (status == 0) { for (typename std::vector<T>::const_iterator i=records.begin(); i != records.end(); ++i) { i->dump(strm); } } else { strm << domain << " lookup failed: " << msg; } return strm; } }; template<class T> EncodeStream& operator<<(EncodeStream& strm, const DNSResult<T>& r) { r.dump(strm); return strm; } class DnsResultSink { public: virtual ~DnsResultSink() {} virtual void onDnsResult(const DNSResult<DnsHostRecord>&) = 0; virtual void onLogDnsResult(const DNSResult<DnsHostRecord>&); // DnsAAAARecord will basically be non-functional if USE_IPV6 wasn't set in the // build. virtual void onDnsResult(const DNSResult<DnsAAAARecord>&) = 0; virtual void onLogDnsResult(const DNSResult<DnsAAAARecord>&); virtual void onDnsResult(const DNSResult<DnsSrvRecord>&) = 0; virtual void onLogDnsResult(const DNSResult<DnsSrvRecord>&); virtual void onDnsResult(const DNSResult<DnsNaptrRecord>&) = 0; virtual void onLogDnsResult(const DNSResult<DnsNaptrRecord>&); virtual void onDnsResult(const DNSResult<DnsCnameRecord>&) = 0; virtual void onLogDnsResult(const DNSResult<DnsCnameRecord>&); }; class DnsRawSink { public: virtual ~DnsRawSink() {} virtual void onDnsRaw(int statuts, const unsigned char* abuf, int len) = 0; }; class DnsStub : public ExternalDnsHandler { public: typedef RRCache::Protocol Protocol; typedef std::vector<Data> DataArr; typedef std::vector<DnsResourceRecord*> DnsResourceRecordsByPtr; typedef std::vector<GenericIPAddress> NameserverList; static NameserverList EmptyNameserverList; class ResultTransform { public: virtual ~ResultTransform() {} virtual void transform(const Data& target, int rrType, DnsResourceRecordsByPtr& src) = 0; }; class DnsStubException : public BaseException { public: DnsStubException(const Data& msg, const Data& file, const int line) : BaseException(msg, file, line) { } const char* name() const { return "DnsStubException"; } }; DnsStub(const NameserverList& additional = EmptyNameserverList, AfterSocketCreationFuncPtr socketFunc = 0, AsyncProcessHandler* asyncProcessHandler = 0, FdPollGrp *pollGrp = 0); ~DnsStub(); // call this method before you create SipStack if you'd like to change the // default DNS lookup timeout and number of retries. static void setDnsTimeoutAndTries(int timeoutInSec, int tries) { mDnsTimeout = timeoutInSec; mDnsTries = tries; } static void enableDnsFeatures(unsigned int features) {mDnsFeatures |= features;} // bit mask of ExternalDns::Features void setResultTransform(ResultTransform*); void removeResultTransform(); void setEnumSuffixes(const std::vector<Data>& suffixes); const std::vector<Data>& getEnumSuffixes() const; void setEnumDomains(const std::map<Data,Data>& domains); const std::map<Data,Data>& getEnumDomains() const; void clearDnsCache(); void logDnsCache(); void getDnsCacheDump(std::pair<unsigned long, unsigned long> key, GetDnsCacheDumpHandler* handler); void setDnsCacheTTL(int ttl); void setDnsCacheSize(int size); bool checkDnsChange(); bool supportedType(int); template<class QueryType> void lookup(const Data& target, DnsResultSink* sink) { lookup<QueryType>(target, Protocol::Reserved, sink); } // There are three pre-defined protocols (see RRList.hxx). Zero(0) is // reserved for internal use, so do not use 0. If you'd like to blacklist // for different types of protocols, just pass in any integer other than // those used for pre-defined protocols. // template<class QueryType> void lookup(const Data& target, int protocol, DnsResultSink* sink) { QueryCommand<QueryType>* command = new QueryCommand<QueryType>(target, protocol, sink, *this); mCommandFifo.add(command); if (mAsyncProcessHandler) { mAsyncProcessHandler->handleProcessNotification(); } } virtual void handleDnsRaw(ExternalDnsRawResult); virtual void process(FdSet& fdset); virtual unsigned int getTimeTillNextProcessMS(); virtual void buildFdSet(FdSet& fdset); void setPollGrp(FdPollGrp* pollGrp); void processTimers(); private: void processFifo(); protected: void cache(const Data& key, in_addr addr); void cache(const Data& key, const unsigned char* abuf, int alen); void cacheTTL(const Data& key, int rrType, int status, const unsigned char* abuf, int alen); private: class ResultConverter //.dcm. -- flyweight? { public: virtual void notifyUser(const Data& target, int status, const Data& msg, const DnsResourceRecordsByPtr& src, DnsResultSink* sink) = 0; virtual ~ResultConverter() {} }; template<class QueryType> class ResultConverterImpl : public ResultConverter { public: virtual void notifyUser(const Data& target, int status, const Data& msg, const DnsResourceRecordsByPtr& src, DnsResultSink* sink) { assert(sink); DNSResult<typename QueryType::Type> result; for (unsigned int i = 0; i < src.size(); ++i) { result.records.push_back(*(dynamic_cast<typename QueryType::Type*>(src[i]))); } result.domain = target; result.status = status; result.msg = msg; sink->onLogDnsResult(result); sink->onDnsResult(result); } }; class Query : public DnsRawSink { public: Query(DnsStub& stub, ResultTransform* transform, ResultConverter* resultConv, const Data& target, int rrType, bool followCname, int proto, DnsResultSink* s); virtual ~Query(); enum {MAX_REQUERIES = 5}; void go(); void process(int status, const unsigned char* abuf, const int alen); void onDnsRaw(int status, const unsigned char* abuf, int alen); void followCname(const unsigned char* aptr, const unsigned char*abuf, const int alen, bool& bGotAnswers, bool& bDeleteThis, Data& targetToQuery); private: static DnsResourceRecordsByPtr Empty; int mRRType; DnsStub& mStub; ResultTransform* mTransform; ResultConverter* mResultConverter; Data mTarget; int mProto; int mReQuery; DnsResultSink* mSink; bool mFollowCname; }; private: DnsStub(const DnsStub&); // disable copy ctor. DnsStub& operator=(const DnsStub&); public: // sailesh - due to a bug in CodeWarrior, // QueryCommand::execute() can only access this method // if it's public. Even using "friend" doesn't work. template<class QueryType> void query(const Data& target, int proto, DnsResultSink* sink) { Query* query = new Query(*this, mTransform, new ResultConverterImpl<QueryType>(), target, QueryType::getRRType(), QueryType::SupportsCName, proto, sink); mQueries.insert(query); query->go(); } private: class Command { public: virtual ~Command() {} virtual void execute() = 0; }; template<class QueryType> class QueryCommand : public Command { public: QueryCommand(const Data& target, int proto, DnsResultSink* sink, DnsStub& stub) : mTarget(target), mProto(proto), mSink(sink), mStub(stub) {} ~QueryCommand() {} void execute() { mStub.query<QueryType>(mTarget, mProto, mSink); } private: Data mTarget; int mProto; DnsResultSink* mSink; DnsStub& mStub; }; void doSetEnumSuffixes(const std::vector<Data>& suffixes); void doSetEnumDomains(const std::map<Data,Data>& domains); class SetEnumSuffixesCommand : public Command { public: SetEnumSuffixesCommand(DnsStub& stub, const std::vector<Data>& suffixes) : mStub(stub), mEnumSuffixes(suffixes) {} ~SetEnumSuffixesCommand() {} void execute() { mStub.doSetEnumSuffixes(mEnumSuffixes); } private: DnsStub& mStub; std::vector<Data> mEnumSuffixes; }; class SetEnumDomainsCommand : public Command { public: SetEnumDomainsCommand(DnsStub& stub, const std::map<Data,Data>& domains) : mStub(stub), mEnumDomains(domains) {} ~SetEnumDomainsCommand() {} void execute() { mStub.doSetEnumDomains(mEnumDomains); } private: DnsStub& mStub; std::map<Data,Data> mEnumDomains; }; void doClearDnsCache(); class ClearDnsCacheCommand : public Command { public: ClearDnsCacheCommand(DnsStub& stub) : mStub(stub) {} ~ClearDnsCacheCommand() {} void execute() { mStub.doClearDnsCache(); } private: DnsStub& mStub; }; void doLogDnsCache(); class LogDnsCacheCommand : public Command { public: LogDnsCacheCommand(DnsStub& stub) : mStub(stub) {} ~LogDnsCacheCommand() {} void execute() { mStub.doLogDnsCache(); } private: DnsStub& mStub; }; void doGetDnsCacheDump(std::pair<unsigned long, unsigned long> key, GetDnsCacheDumpHandler* handler); class GetDnsCacheDumpCommand : public Command { public: GetDnsCacheDumpCommand(DnsStub& stub, std::pair<unsigned long, unsigned long> key, GetDnsCacheDumpHandler* handler) : mStub(stub), mKey(key), mHandler(handler) {} ~GetDnsCacheDumpCommand() {} void execute() { mStub.doGetDnsCacheDump(mKey, mHandler); } private: DnsStub& mStub; std::pair<unsigned long, unsigned long> mKey; GetDnsCacheDumpHandler* mHandler; }; SelectInterruptor mSelectInterruptor; FdPollItemHandle mInterruptorHandle; resip::Fifo<Command> mCommandFifo; const unsigned char* skipDNSQuestion(const unsigned char *aptr, const unsigned char *abuf, int alen); const unsigned char* createOverlay(const unsigned char* abuf, const int alen, const unsigned char* aptr, std::vector<RROverlay>&, bool discard=false); void removeQuery(Query*); void lookupRecords(const Data& target, unsigned short type, DnsRawSink* sink); Data errorMessage(int status); ResultTransform* mTransform; ExternalDns* mDnsProvider; FdPollGrp* mPollGrp; std::set<Query*> mQueries; std::vector<Data> mEnumSuffixes; // where to do enum lookups std::map<Data,Data> mEnumDomains; static int mDnsTimeout; // in seconds static int mDnsTries; static unsigned int mDnsFeatures; // bit mask of ExternalDns::Features /// if this object exists, it gets notified when ApplicationMessage's get posted AsyncProcessHandler* mAsyncProcessHandler; /// Dns Cache RRCache mRRCache; }; typedef DnsStub::Protocol Protocol; } #endif /* ==================================================================== * The Vovida Software License, Version 1.0 * * Copyright (c) 2000-2005 Vovida Networks, Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The names "VOCAL", "Vovida Open Communication Application Library", * and "Vovida Open Communication Application Library (VOCAL)" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact vocal@vovida.org. * * 4. Products derived from this software may not be called "VOCAL", nor * may "VOCAL" appear in their name, without prior written * permission of Vovida Networks, Inc. * * THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, TITLE AND * NON-INFRINGEMENT ARE DISCLAIMED. IN NO EVENT SHALL VOVIDA * NETWORKS, INC. OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT DAMAGES * IN EXCESS OF $1,000, NOR FOR ANY INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH * DAMAGE. * * ==================================================================== * * This software consists of voluntary contributions made by Vovida * Networks, Inc. and many individuals on behalf of Vovida Networks, * Inc. For more information on Vovida Networks, Inc., please see * <http://www.vovida.org/>. * */
32.759843
157
0.589352
dulton
8d5acadbb783f3d5029c4a66a9171429822d0034
2,991
cpp
C++
src/Core/p2/iTRC.cpp
stravant/bfbbdecomp
2126be355a6bb8171b850f829c1f2731c8b5de08
[ "OLDAP-2.7" ]
1
2021-01-05T11:28:55.000Z
2021-01-05T11:28:55.000Z
src/Core/p2/iTRC.cpp
sonich2401/bfbbdecomp
5f58b62505f8929a72ccf2aa118a1539eb3a5bd6
[ "OLDAP-2.7" ]
null
null
null
src/Core/p2/iTRC.cpp
sonich2401/bfbbdecomp
5f58b62505f8929a72ccf2aa118a1539eb3a5bd6
[ "OLDAP-2.7" ]
1
2022-03-30T15:15:08.000Z
2022-03-30T15:15:08.000Z
#include "iTRC.h" #include <types.h> // func_80180038 #pragma GLOBAL_ASM("asm/Core/p2/iTRC.s", "Init__7ROMFontFv") // func_80180094 #pragma GLOBAL_ASM("asm/Core/p2/iTRC.s", "InitDisplay__7ROMFontFP16_GXRenderModeObj") // func_80180214 #pragma GLOBAL_ASM("asm/Core/p2/iTRC.s", "InitGX__7ROMFontFv") // func_80180338 #pragma GLOBAL_ASM("asm/Core/p2/iTRC.s", "InitVI__7ROMFontFv") // func_80180384 #pragma GLOBAL_ASM("asm/Core/p2/iTRC.s", "RenderBegin__7ROMFontFv") // func_80180450 #pragma GLOBAL_ASM("asm/Core/p2/iTRC.s", "RenderEnd__7ROMFontFv") // func_80180498 #pragma GLOBAL_ASM("asm/Core/p2/iTRC.s", "SwapBuffers__7ROMFontFv") // func_80180508 #pragma GLOBAL_ASM("asm/Core/p2/iTRC.s", "DrawCell__7ROMFontFiiii") // func_801805F4 #pragma GLOBAL_ASM("asm/Core/p2/iTRC.s", "GXEnd") // func_801805F8 #pragma GLOBAL_ASM("asm/Core/p2/iTRC.s", "GXTexCoord2s16") // func_80180608 #pragma GLOBAL_ASM("asm/Core/p2/iTRC.s", "GXPosition3s16") // func_8018061C #pragma GLOBAL_ASM("asm/Core/p2/iTRC.s", "LoadSheet__7ROMFontFPv") // func_80180708 #pragma GLOBAL_ASM("asm/Core/p2/iTRC.s", "GXSetTexCoordGen") // func_80180730 #pragma GLOBAL_ASM("asm/Core/p2/iTRC.s", "DrawString__7ROMFontFiiPc") // func_801807D4 #pragma GLOBAL_ASM("asm/Core/p2/iTRC.s", "GetWidth__7ROMFontFPc") // func_8018082C #pragma GLOBAL_ASM("asm/Core/p2/iTRC.s", "DrawTextBox__7ROMFontFiiiiPc") // func_80180920 #pragma GLOBAL_ASM("asm/Core/p2/iTRC.s", "EnableReset__11ResetButtonFv") // func_8018092C #pragma GLOBAL_ASM("asm/Core/p2/iTRC.s", "DisableReset__11ResetButtonFv") // func_80180938 #pragma GLOBAL_ASM("asm/Core/p2/iTRC.s", "SetSndKillFunction__11ResetButtonFPFv_v") // func_80180940 #pragma GLOBAL_ASM("asm/Core/p2/iTRC.s", "CheckResetButton__11ResetButtonFv") // func_80180A10 #pragma GLOBAL_ASM("asm/Core/p2/iTRC.s", "Init__8iTRCDiskFv") // func_80180A30 #pragma GLOBAL_ASM("asm/Core/p2/iTRC.s", "SetErrorMessage__8iTRCDiskFPCc") // func_80180A5C #pragma GLOBAL_ASM("asm/Core/p2/iTRC.s", "ResetMessage__8iTRCDiskFv") // func_80180A8C #pragma GLOBAL_ASM("asm/Core/p2/iTRC.s", "SetPadStopRumblingFunction__8iTRCDiskFPFv_v") // func_80180A94 #pragma GLOBAL_ASM("asm/Core/p2/iTRC.s", "SetSndSuspendFunction__8iTRCDiskFPFv_v") // func_80180A9C #pragma GLOBAL_ASM("asm/Core/p2/iTRC.s", "SetSndResumeFunction__8iTRCDiskFPFv_v") // func_80180AA4 #pragma GLOBAL_ASM("asm/Core/p2/iTRC.s", "SetSndKillFunction__8iTRCDiskFPFv_v") // func_80180AAC #pragma GLOBAL_ASM("asm/Core/p2/iTRC.s", "SetMovieSuspendFunction__8iTRCDiskFPFv_v") // func_80180AB4 #pragma GLOBAL_ASM("asm/Core/p2/iTRC.s", "SetMovieResumeFunction__8iTRCDiskFPFv_v") // func_80180ABC #pragma GLOBAL_ASM("asm/Core/p2/iTRC.s", "IsDiskIDed__8iTRCDiskFv") // func_80180B04 #pragma GLOBAL_ASM("asm/Core/p2/iTRC.s", "DisplayErrorMessage__8iTRCDiskFv") // func_80180BB4 #pragma GLOBAL_ASM("asm/Core/p2/iTRC.s", "SetDVDState__8iTRCDiskFv") // func_80180C8C #pragma GLOBAL_ASM("asm/Core/p2/iTRC.s", "CheckDVDAndResetState__8iTRCDiskFv")
29.038835
87
0.774992
stravant
8d619a4ec671230363838c0e6311f5d538ab9217
381
cpp
C++
11.13.8.cpp
cubhe/C_Primer_Plus
7edc4b4f5c1afad60797f8f1ea11fb47f6fcdf77
[ "MIT" ]
null
null
null
11.13.8.cpp
cubhe/C_Primer_Plus
7edc4b4f5c1afad60797f8f1ea11fb47f6fcdf77
[ "MIT" ]
null
null
null
11.13.8.cpp
cubhe/C_Primer_Plus
7edc4b4f5c1afad60797f8f1ea11fb47f6fcdf77
[ "MIT" ]
null
null
null
#include<stdio.h> #include<stdlib.h> #include<string.h> #define MAX 40 void revers(char * one); int main(){ char one[MAX]; gets(one); revers(one); puts(one); system("pause"); return 0; } void revers(char * one){ char temp; int j = strlen(one); for (size_t i = 0; i < j/2; i++) { temp = one[i]; one[i] = one[j - i-1]; one[j - i-1] = temp; } }
16.565217
34
0.545932
cubhe
8d62343482744e642fc44bcc082584c7dcf2c75c
2,463
cpp
C++
RFW/system/src/rfw/instance_ref.cpp
MeirBon/rendering-fw
dff775c816d19cd9e11eac2c2a2b3c608216ad4c
[ "Apache-2.0" ]
77
2020-01-03T18:32:47.000Z
2021-08-08T01:06:52.000Z
RFW/system/src/rfw/instance_ref.cpp
meirbon/rendering-fw
dff775c816d19cd9e11eac2c2a2b3c608216ad4c
[ "Apache-2.0" ]
1
2020-01-09T01:59:27.000Z
2020-01-09T08:47:28.000Z
RFW/system/src/rfw/instance_ref.cpp
MeirBon/rendering-fw
dff775c816d19cd9e11eac2c2a2b3c608216ad4c
[ "Apache-2.0" ]
2
2021-04-15T00:02:38.000Z
2021-08-08T01:06:47.000Z
#include "instance_ref.h" #include "system.h" namespace rfw { instance_ref::instance_ref(size_t index, geometry_ref reference, rfw::system &sys) { m_Members = std::make_shared<Members>(reference); m_Members->index = index; m_Members->geomReference = reference; m_Members->rSystem = &sys; assert(m_Members->rSystem); m_Members->translation = glm::vec3(0.0f); m_Members->rotation = glm::identity<glm::quat>(); m_Members->scaling = glm::vec3(1.0f); const auto &meshes = reference.get_meshes(); m_Members->instanceIDs.resize(meshes.size()); for (int i = 0, s = static_cast<int>(meshes.size()); i < s; i++) { const int instanceID = static_cast<int>(sys.request_instance_index()); sys.m_InverseInstanceMapping[instanceID] = std::make_tuple(static_cast<int>(index), static_cast<int>(reference.get_index()), i); m_Members->instanceIDs[i] = instanceID; } } void instance_ref::set_translation(const glm::vec3 value) { m_Members->translation = value; } void instance_ref::set_rotation(const float degrees, const glm::vec3 axis) { m_Members->rotation = glm::rotate(glm::identity<glm::quat>(), radians(degrees), axis); } void instance_ref::set_rotation(const glm::quat &q) { m_Members->rotation = q; } void instance_ref::set_rotation(const glm::vec3 &euler) { m_Members->rotation = glm::quat(euler); } void instance_ref::set_scaling(const glm::vec3 value) { m_Members->scaling = value; } void instance_ref::translate(const glm::vec3 offset) { m_Members->translation = offset; } void instance_ref::rotate(const float degrees, const glm::vec3 axis) { m_Members->rotation = glm::rotate(m_Members->rotation, radians(degrees), axis); } void instance_ref::scale(const glm::vec3 offset) { m_Members->scaling = offset; } void instance_ref::update() const { m_Members->rSystem->update_instance(*this, get_matrix().matrix); } rfw::simd::matrix4 instance_ref::get_matrix() const { const simd::matrix4 T = glm::translate(glm::mat4(1.0f), m_Members->translation); const simd::matrix4 R = glm::mat4(m_Members->rotation); const simd::matrix4 S = glm::scale(glm::mat4(1.0f), m_Members->scaling); return T * R * S; } glm::mat3 instance_ref::get_normal_matrix() const { const simd::matrix4 T = glm::translate(glm::mat4(1.0f), m_Members->translation); const simd::matrix4 R = glm::mat4(m_Members->rotation); return mat3((T * R).inversed().matrix); } instance_ref::Members::Members(const geometry_ref &ref) : geomReference(ref) {} } // namespace rfw
35.185714
102
0.727162
MeirBon
8d678641bc9dc290bcaf9078bcb26142ffedfc67
2,706
cpp
C++
c++/en/dropbox/class_president/class_president/class_president.cpp
aimldl/coding
70ddbfaa454ab92fd072ee8dc614ecc330b34a70
[ "MIT" ]
null
null
null
c++/en/dropbox/class_president/class_president/class_president.cpp
aimldl/coding
70ddbfaa454ab92fd072ee8dc614ecc330b34a70
[ "MIT" ]
null
null
null
c++/en/dropbox/class_president/class_president/class_president.cpp
aimldl/coding
70ddbfaa454ab92fd072ee8dc614ecc330b34a70
[ "MIT" ]
null
null
null
// class_president.cpp #include "pch.h" #include <iostream> #include <fstream> #define DEBUG 1 //#define DEBUG 0 void show1darray(int* arr, int N); void show2darray(int** arr, int N, int Y); //any_match(int** row1, int** row2, int column_size) bool any_match(int* row1, int* row2, int column_size) { for (int j = 0; j < column_size; j++) { if (row1[j] == row2[j]) { return true; } } return false; } int find_max(int* arr, int N) { int idx_max = 0; int max_val = arr[0]; for (int i = 1; i < N; i++) { if (max_val < arr[i]) { idx_max = i; max_val = arr[i]; } } return idx_max; } int main() { std::ifstream ifs("class_president_ex-1.txt"); // Input int N; ifs >> N; int Y = 5; // class years int ** tbl = new int *[N]; for (int i = 0; i < N; i++) tbl[i] = new int[Y]; for (int i = 0; i < N; i++) { for (int j = 0; j < Y; j++) { ifs >> tbl[i][j]; } } if (DEBUG) show2darray(tbl, N, Y); // Find the temporary class president int* hist_c_ptr; // pointer to the history of candidate int* hist_s_ptr; // pointer to the history of students int* num_classmates = new int[N]; for (int c = 0; c < N; c++) // c = candidate for the class president { hist_c_ptr = tbl[c]; num_classmates[c] = 0; // Compare with other students for (int s = 0; s < N; s++) { if ( c != s ) { hist_s_ptr = tbl[s]; if ( any_match( hist_c_ptr, hist_s_ptr, Y ) ) { num_classmates[c]++; } } } } if (DEBUG) show1darray(num_classmates, N); // Find the candidate with the max number of classmates int idx_president; idx_president = find_max(num_classmates, N); // Output std::cout << idx_president+1 << std::endl; // Note add 1 return 0; } void show1darray(int* arr, int N) { for (int i = 0; i < N; i++) { std::cout << arr[i] << " "; } std::cout << std::endl; } void show2darray(int** arr, int N, int Y) { for (int i = 0; i < N; i++) { for (int j = 0; j < Y; j++) { std::cout << arr[i][j] << " "; } std::cout << std::endl; } std::cout << std::endl; } /* // Find the temporary class president int** hist_c_ptr; // pointer to the history of candidate int** hist_s_ptr; // pointer to the history of students int* num_classmates = new int[N]; for (int c = 0; c < N; c++) // c = candidate for the class president { hist_c_ptr = &tbl[c]; num_classmates[c] = 0; // Compare with other students for (int s = 0; s < N; s++) { if ( c != s ) { hist_s_ptr = &tbl[s]; if ( any_match(hist_c_ptr, hist_s_ptr, Y) ) { num_classmates[c]++; } } } } */
17.571429
71
0.546563
aimldl
8d6a4fc48fc412bc7fe78d8ae17cd33bdacbd121
4,189
cpp
C++
src/QtlMovie/QtlMovieCcExtractorProcess.cpp
qtlmovie/qtlmovie
082ad5ea6522a02d5ac0d86f23cdd6152edff613
[ "BSD-2-Clause" ]
8
2016-08-09T14:05:58.000Z
2020-09-05T14:43:36.000Z
src/QtlMovie/QtlMovieCcExtractorProcess.cpp
qtlmovie/qtlmovie
082ad5ea6522a02d5ac0d86f23cdd6152edff613
[ "BSD-2-Clause" ]
15
2016-08-09T14:11:21.000Z
2022-01-15T23:39:07.000Z
src/QtlMovie/QtlMovieCcExtractorProcess.cpp
qtlmovie/qtlmovie
082ad5ea6522a02d5ac0d86f23cdd6152edff613
[ "BSD-2-Clause" ]
1
2017-08-26T22:08:58.000Z
2017-08-26T22:08:58.000Z
//---------------------------------------------------------------------------- // // Copyright (c) 2013-2017, Thierry Lelegard // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // //---------------------------------------------------------------------------- // // Define the class QtlMovieCcExtractorProcess. // //---------------------------------------------------------------------------- #include "QtlMovieCcExtractorProcess.h" #include "QtlStringList.h" #include "QtlStringUtils.h" //---------------------------------------------------------------------------- // Constructor. //---------------------------------------------------------------------------- QtlMovieCcExtractorProcess::QtlMovieCcExtractorProcess(const QStringList& arguments, const QtlMovieSettings* settings, QtlLogger* log, QObject* parent) : QtlMovieProcess(settings->ccextractor(), arguments, false, settings, log, parent) { } //---------------------------------------------------------------------------- // Process one text line from standard error or output. //---------------------------------------------------------------------------- void QtlMovieCcExtractorProcess::processOutputLine(QProcess::ProcessChannel channel, const QString& line) { // CCExtractor --gui_mode_reports outputs lines starting with ### // The progress lines are: ###PROGRESS#percent#minutes#seconds if (!line.startsWith("###")) { // Not a GUI event. Delegate to superclass. QtlMovieProcess::processOutputLine(channel, line); } else if (line.startsWith("###PROGRESS#")) { // This is a progress indicator. const QStringList fields(line.split(QChar('#'), QString::SkipEmptyParts)); if (fields.size() >= 2) { const int percent = qtlToInt(fields[1], -1, 0, 100); if (percent >= 0) { // Valid percentage, report progression. emitProgress(percent, 100); } } } } //---------------------------------------------------------------------------- // Build a list of options which limit the extraction duration. //---------------------------------------------------------------------------- QStringList QtlMovieCcExtractorProcess::durationOptions(int totalSeconds) { if (totalSeconds < 0) { // No limit, no option. return QStringList(); } else { // Build extraction duration as HH:MM:SS. const int hours = (totalSeconds / 3600) % 100; const int minutes = (totalSeconds % 3600) / 60; const int seconds = totalSeconds % 60; return QtlStringList("-endat", QStringLiteral("%1:%2:%3").arg(hours, 2, 10, QChar('0')).arg(minutes, 2, 10, QChar('0')).arg(seconds, 2, 10, QChar('0'))); } }
43.635417
161
0.553831
qtlmovie
8d712ffab02975e739efb021eba9e24470948991
19,712
cpp
C++
tcss/src/v20201101/model/DescribeAssetSummaryResponse.cpp
suluner/tencentcloud-sdk-cpp
a56c73cc3f488c4d1e10755704107bb15c5e000d
[ "Apache-2.0" ]
null
null
null
tcss/src/v20201101/model/DescribeAssetSummaryResponse.cpp
suluner/tencentcloud-sdk-cpp
a56c73cc3f488c4d1e10755704107bb15c5e000d
[ "Apache-2.0" ]
null
null
null
tcss/src/v20201101/model/DescribeAssetSummaryResponse.cpp
suluner/tencentcloud-sdk-cpp
a56c73cc3f488c4d1e10755704107bb15c5e000d
[ "Apache-2.0" ]
null
null
null
/* * Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <tencentcloud/tcss/v20201101/model/DescribeAssetSummaryResponse.h> #include <tencentcloud/core/utils/rapidjson/document.h> #include <tencentcloud/core/utils/rapidjson/writer.h> #include <tencentcloud/core/utils/rapidjson/stringbuffer.h> using TencentCloud::CoreInternalOutcome; using namespace TencentCloud::Tcss::V20201101::Model; using namespace std; DescribeAssetSummaryResponse::DescribeAssetSummaryResponse() : m_appCntHasBeenSet(false), m_containerCntHasBeenSet(false), m_containerPauseHasBeenSet(false), m_containerRunningHasBeenSet(false), m_containerStopHasBeenSet(false), m_createTimeHasBeenSet(false), m_dbCntHasBeenSet(false), m_imageCntHasBeenSet(false), m_hostOnlineHasBeenSet(false), m_hostCntHasBeenSet(false), m_imageHasRiskInfoCntHasBeenSet(false), m_imageHasVirusCntHasBeenSet(false), m_imageHasVulsCntHasBeenSet(false), m_imageUntrustCntHasBeenSet(false), m_listenPortCntHasBeenSet(false), m_processCntHasBeenSet(false), m_webServiceCntHasBeenSet(false), m_latestImageScanTimeHasBeenSet(false), m_imageUnsafeCntHasBeenSet(false) { } CoreInternalOutcome DescribeAssetSummaryResponse::Deserialize(const string &payload) { rapidjson::Document d; d.Parse(payload.c_str()); if (d.HasParseError() || !d.IsObject()) { return CoreInternalOutcome(Core::Error("response not json format")); } if (!d.HasMember("Response") || !d["Response"].IsObject()) { return CoreInternalOutcome(Core::Error("response `Response` is null or not object")); } rapidjson::Value &rsp = d["Response"]; if (!rsp.HasMember("RequestId") || !rsp["RequestId"].IsString()) { return CoreInternalOutcome(Core::Error("response `Response.RequestId` is null or not string")); } string requestId(rsp["RequestId"].GetString()); SetRequestId(requestId); if (rsp.HasMember("Error")) { if (!rsp["Error"].IsObject() || !rsp["Error"].HasMember("Code") || !rsp["Error"]["Code"].IsString() || !rsp["Error"].HasMember("Message") || !rsp["Error"]["Message"].IsString()) { return CoreInternalOutcome(Core::Error("response `Response.Error` format error").SetRequestId(requestId)); } string errorCode(rsp["Error"]["Code"].GetString()); string errorMsg(rsp["Error"]["Message"].GetString()); return CoreInternalOutcome(Core::Error(errorCode, errorMsg).SetRequestId(requestId)); } if (rsp.HasMember("AppCnt") && !rsp["AppCnt"].IsNull()) { if (!rsp["AppCnt"].IsUint64()) { return CoreInternalOutcome(Core::Error("response `AppCnt` IsUint64=false incorrectly").SetRequestId(requestId)); } m_appCnt = rsp["AppCnt"].GetUint64(); m_appCntHasBeenSet = true; } if (rsp.HasMember("ContainerCnt") && !rsp["ContainerCnt"].IsNull()) { if (!rsp["ContainerCnt"].IsUint64()) { return CoreInternalOutcome(Core::Error("response `ContainerCnt` IsUint64=false incorrectly").SetRequestId(requestId)); } m_containerCnt = rsp["ContainerCnt"].GetUint64(); m_containerCntHasBeenSet = true; } if (rsp.HasMember("ContainerPause") && !rsp["ContainerPause"].IsNull()) { if (!rsp["ContainerPause"].IsUint64()) { return CoreInternalOutcome(Core::Error("response `ContainerPause` IsUint64=false incorrectly").SetRequestId(requestId)); } m_containerPause = rsp["ContainerPause"].GetUint64(); m_containerPauseHasBeenSet = true; } if (rsp.HasMember("ContainerRunning") && !rsp["ContainerRunning"].IsNull()) { if (!rsp["ContainerRunning"].IsUint64()) { return CoreInternalOutcome(Core::Error("response `ContainerRunning` IsUint64=false incorrectly").SetRequestId(requestId)); } m_containerRunning = rsp["ContainerRunning"].GetUint64(); m_containerRunningHasBeenSet = true; } if (rsp.HasMember("ContainerStop") && !rsp["ContainerStop"].IsNull()) { if (!rsp["ContainerStop"].IsUint64()) { return CoreInternalOutcome(Core::Error("response `ContainerStop` IsUint64=false incorrectly").SetRequestId(requestId)); } m_containerStop = rsp["ContainerStop"].GetUint64(); m_containerStopHasBeenSet = true; } if (rsp.HasMember("CreateTime") && !rsp["CreateTime"].IsNull()) { if (!rsp["CreateTime"].IsString()) { return CoreInternalOutcome(Core::Error("response `CreateTime` IsString=false incorrectly").SetRequestId(requestId)); } m_createTime = string(rsp["CreateTime"].GetString()); m_createTimeHasBeenSet = true; } if (rsp.HasMember("DbCnt") && !rsp["DbCnt"].IsNull()) { if (!rsp["DbCnt"].IsUint64()) { return CoreInternalOutcome(Core::Error("response `DbCnt` IsUint64=false incorrectly").SetRequestId(requestId)); } m_dbCnt = rsp["DbCnt"].GetUint64(); m_dbCntHasBeenSet = true; } if (rsp.HasMember("ImageCnt") && !rsp["ImageCnt"].IsNull()) { if (!rsp["ImageCnt"].IsUint64()) { return CoreInternalOutcome(Core::Error("response `ImageCnt` IsUint64=false incorrectly").SetRequestId(requestId)); } m_imageCnt = rsp["ImageCnt"].GetUint64(); m_imageCntHasBeenSet = true; } if (rsp.HasMember("HostOnline") && !rsp["HostOnline"].IsNull()) { if (!rsp["HostOnline"].IsUint64()) { return CoreInternalOutcome(Core::Error("response `HostOnline` IsUint64=false incorrectly").SetRequestId(requestId)); } m_hostOnline = rsp["HostOnline"].GetUint64(); m_hostOnlineHasBeenSet = true; } if (rsp.HasMember("HostCnt") && !rsp["HostCnt"].IsNull()) { if (!rsp["HostCnt"].IsUint64()) { return CoreInternalOutcome(Core::Error("response `HostCnt` IsUint64=false incorrectly").SetRequestId(requestId)); } m_hostCnt = rsp["HostCnt"].GetUint64(); m_hostCntHasBeenSet = true; } if (rsp.HasMember("ImageHasRiskInfoCnt") && !rsp["ImageHasRiskInfoCnt"].IsNull()) { if (!rsp["ImageHasRiskInfoCnt"].IsUint64()) { return CoreInternalOutcome(Core::Error("response `ImageHasRiskInfoCnt` IsUint64=false incorrectly").SetRequestId(requestId)); } m_imageHasRiskInfoCnt = rsp["ImageHasRiskInfoCnt"].GetUint64(); m_imageHasRiskInfoCntHasBeenSet = true; } if (rsp.HasMember("ImageHasVirusCnt") && !rsp["ImageHasVirusCnt"].IsNull()) { if (!rsp["ImageHasVirusCnt"].IsUint64()) { return CoreInternalOutcome(Core::Error("response `ImageHasVirusCnt` IsUint64=false incorrectly").SetRequestId(requestId)); } m_imageHasVirusCnt = rsp["ImageHasVirusCnt"].GetUint64(); m_imageHasVirusCntHasBeenSet = true; } if (rsp.HasMember("ImageHasVulsCnt") && !rsp["ImageHasVulsCnt"].IsNull()) { if (!rsp["ImageHasVulsCnt"].IsUint64()) { return CoreInternalOutcome(Core::Error("response `ImageHasVulsCnt` IsUint64=false incorrectly").SetRequestId(requestId)); } m_imageHasVulsCnt = rsp["ImageHasVulsCnt"].GetUint64(); m_imageHasVulsCntHasBeenSet = true; } if (rsp.HasMember("ImageUntrustCnt") && !rsp["ImageUntrustCnt"].IsNull()) { if (!rsp["ImageUntrustCnt"].IsUint64()) { return CoreInternalOutcome(Core::Error("response `ImageUntrustCnt` IsUint64=false incorrectly").SetRequestId(requestId)); } m_imageUntrustCnt = rsp["ImageUntrustCnt"].GetUint64(); m_imageUntrustCntHasBeenSet = true; } if (rsp.HasMember("ListenPortCnt") && !rsp["ListenPortCnt"].IsNull()) { if (!rsp["ListenPortCnt"].IsUint64()) { return CoreInternalOutcome(Core::Error("response `ListenPortCnt` IsUint64=false incorrectly").SetRequestId(requestId)); } m_listenPortCnt = rsp["ListenPortCnt"].GetUint64(); m_listenPortCntHasBeenSet = true; } if (rsp.HasMember("ProcessCnt") && !rsp["ProcessCnt"].IsNull()) { if (!rsp["ProcessCnt"].IsUint64()) { return CoreInternalOutcome(Core::Error("response `ProcessCnt` IsUint64=false incorrectly").SetRequestId(requestId)); } m_processCnt = rsp["ProcessCnt"].GetUint64(); m_processCntHasBeenSet = true; } if (rsp.HasMember("WebServiceCnt") && !rsp["WebServiceCnt"].IsNull()) { if (!rsp["WebServiceCnt"].IsUint64()) { return CoreInternalOutcome(Core::Error("response `WebServiceCnt` IsUint64=false incorrectly").SetRequestId(requestId)); } m_webServiceCnt = rsp["WebServiceCnt"].GetUint64(); m_webServiceCntHasBeenSet = true; } if (rsp.HasMember("LatestImageScanTime") && !rsp["LatestImageScanTime"].IsNull()) { if (!rsp["LatestImageScanTime"].IsString()) { return CoreInternalOutcome(Core::Error("response `LatestImageScanTime` IsString=false incorrectly").SetRequestId(requestId)); } m_latestImageScanTime = string(rsp["LatestImageScanTime"].GetString()); m_latestImageScanTimeHasBeenSet = true; } if (rsp.HasMember("ImageUnsafeCnt") && !rsp["ImageUnsafeCnt"].IsNull()) { if (!rsp["ImageUnsafeCnt"].IsUint64()) { return CoreInternalOutcome(Core::Error("response `ImageUnsafeCnt` IsUint64=false incorrectly").SetRequestId(requestId)); } m_imageUnsafeCnt = rsp["ImageUnsafeCnt"].GetUint64(); m_imageUnsafeCntHasBeenSet = true; } return CoreInternalOutcome(true); } string DescribeAssetSummaryResponse::ToJsonString() const { rapidjson::Document value; value.SetObject(); rapidjson::Document::AllocatorType& allocator = value.GetAllocator(); if (m_appCntHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "AppCnt"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, m_appCnt, allocator); } if (m_containerCntHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "ContainerCnt"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, m_containerCnt, allocator); } if (m_containerPauseHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "ContainerPause"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, m_containerPause, allocator); } if (m_containerRunningHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "ContainerRunning"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, m_containerRunning, allocator); } if (m_containerStopHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "ContainerStop"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, m_containerStop, allocator); } if (m_createTimeHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "CreateTime"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_createTime.c_str(), allocator).Move(), allocator); } if (m_dbCntHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "DbCnt"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, m_dbCnt, allocator); } if (m_imageCntHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "ImageCnt"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, m_imageCnt, allocator); } if (m_hostOnlineHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "HostOnline"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, m_hostOnline, allocator); } if (m_hostCntHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "HostCnt"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, m_hostCnt, allocator); } if (m_imageHasRiskInfoCntHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "ImageHasRiskInfoCnt"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, m_imageHasRiskInfoCnt, allocator); } if (m_imageHasVirusCntHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "ImageHasVirusCnt"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, m_imageHasVirusCnt, allocator); } if (m_imageHasVulsCntHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "ImageHasVulsCnt"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, m_imageHasVulsCnt, allocator); } if (m_imageUntrustCntHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "ImageUntrustCnt"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, m_imageUntrustCnt, allocator); } if (m_listenPortCntHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "ListenPortCnt"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, m_listenPortCnt, allocator); } if (m_processCntHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "ProcessCnt"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, m_processCnt, allocator); } if (m_webServiceCntHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "WebServiceCnt"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, m_webServiceCnt, allocator); } if (m_latestImageScanTimeHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "LatestImageScanTime"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_latestImageScanTime.c_str(), allocator).Move(), allocator); } if (m_imageUnsafeCntHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "ImageUnsafeCnt"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, m_imageUnsafeCnt, allocator); } rapidjson::Value iKey(rapidjson::kStringType); string key = "RequestId"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value().SetString(GetRequestId().c_str(), allocator), allocator); rapidjson::StringBuffer buffer; rapidjson::Writer<rapidjson::StringBuffer> writer(buffer); value.Accept(writer); return buffer.GetString(); } uint64_t DescribeAssetSummaryResponse::GetAppCnt() const { return m_appCnt; } bool DescribeAssetSummaryResponse::AppCntHasBeenSet() const { return m_appCntHasBeenSet; } uint64_t DescribeAssetSummaryResponse::GetContainerCnt() const { return m_containerCnt; } bool DescribeAssetSummaryResponse::ContainerCntHasBeenSet() const { return m_containerCntHasBeenSet; } uint64_t DescribeAssetSummaryResponse::GetContainerPause() const { return m_containerPause; } bool DescribeAssetSummaryResponse::ContainerPauseHasBeenSet() const { return m_containerPauseHasBeenSet; } uint64_t DescribeAssetSummaryResponse::GetContainerRunning() const { return m_containerRunning; } bool DescribeAssetSummaryResponse::ContainerRunningHasBeenSet() const { return m_containerRunningHasBeenSet; } uint64_t DescribeAssetSummaryResponse::GetContainerStop() const { return m_containerStop; } bool DescribeAssetSummaryResponse::ContainerStopHasBeenSet() const { return m_containerStopHasBeenSet; } string DescribeAssetSummaryResponse::GetCreateTime() const { return m_createTime; } bool DescribeAssetSummaryResponse::CreateTimeHasBeenSet() const { return m_createTimeHasBeenSet; } uint64_t DescribeAssetSummaryResponse::GetDbCnt() const { return m_dbCnt; } bool DescribeAssetSummaryResponse::DbCntHasBeenSet() const { return m_dbCntHasBeenSet; } uint64_t DescribeAssetSummaryResponse::GetImageCnt() const { return m_imageCnt; } bool DescribeAssetSummaryResponse::ImageCntHasBeenSet() const { return m_imageCntHasBeenSet; } uint64_t DescribeAssetSummaryResponse::GetHostOnline() const { return m_hostOnline; } bool DescribeAssetSummaryResponse::HostOnlineHasBeenSet() const { return m_hostOnlineHasBeenSet; } uint64_t DescribeAssetSummaryResponse::GetHostCnt() const { return m_hostCnt; } bool DescribeAssetSummaryResponse::HostCntHasBeenSet() const { return m_hostCntHasBeenSet; } uint64_t DescribeAssetSummaryResponse::GetImageHasRiskInfoCnt() const { return m_imageHasRiskInfoCnt; } bool DescribeAssetSummaryResponse::ImageHasRiskInfoCntHasBeenSet() const { return m_imageHasRiskInfoCntHasBeenSet; } uint64_t DescribeAssetSummaryResponse::GetImageHasVirusCnt() const { return m_imageHasVirusCnt; } bool DescribeAssetSummaryResponse::ImageHasVirusCntHasBeenSet() const { return m_imageHasVirusCntHasBeenSet; } uint64_t DescribeAssetSummaryResponse::GetImageHasVulsCnt() const { return m_imageHasVulsCnt; } bool DescribeAssetSummaryResponse::ImageHasVulsCntHasBeenSet() const { return m_imageHasVulsCntHasBeenSet; } uint64_t DescribeAssetSummaryResponse::GetImageUntrustCnt() const { return m_imageUntrustCnt; } bool DescribeAssetSummaryResponse::ImageUntrustCntHasBeenSet() const { return m_imageUntrustCntHasBeenSet; } uint64_t DescribeAssetSummaryResponse::GetListenPortCnt() const { return m_listenPortCnt; } bool DescribeAssetSummaryResponse::ListenPortCntHasBeenSet() const { return m_listenPortCntHasBeenSet; } uint64_t DescribeAssetSummaryResponse::GetProcessCnt() const { return m_processCnt; } bool DescribeAssetSummaryResponse::ProcessCntHasBeenSet() const { return m_processCntHasBeenSet; } uint64_t DescribeAssetSummaryResponse::GetWebServiceCnt() const { return m_webServiceCnt; } bool DescribeAssetSummaryResponse::WebServiceCntHasBeenSet() const { return m_webServiceCntHasBeenSet; } string DescribeAssetSummaryResponse::GetLatestImageScanTime() const { return m_latestImageScanTime; } bool DescribeAssetSummaryResponse::LatestImageScanTimeHasBeenSet() const { return m_latestImageScanTimeHasBeenSet; } uint64_t DescribeAssetSummaryResponse::GetImageUnsafeCnt() const { return m_imageUnsafeCnt; } bool DescribeAssetSummaryResponse::ImageUnsafeCntHasBeenSet() const { return m_imageUnsafeCntHasBeenSet; }
30.896552
137
0.683391
suluner
8d74aff2f92c14364cde3642214e623a0d313d44
1,300
cpp
C++
tests/allegro_flare/allegro_color_attribute_datatype_test.cpp
MarkOates/allegro_flare
b454cb85eb5e43d19c23c0c6fd2dc11b96666ce7
[ "MIT" ]
25
2015-03-30T02:02:43.000Z
2019-03-04T22:29:12.000Z
tests/allegro_flare/allegro_color_attribute_datatype_test.cpp
MarkOates/allegro_flare
b454cb85eb5e43d19c23c0c6fd2dc11b96666ce7
[ "MIT" ]
122
2015-04-01T08:15:26.000Z
2019-10-16T20:31:22.000Z
tests/allegro_flare/allegro_color_attribute_datatype_test.cpp
MarkOates/allegro_flare
b454cb85eb5e43d19c23c0c6fd2dc11b96666ce7
[ "MIT" ]
4
2016-09-02T12:14:09.000Z
2018-11-23T20:38:49.000Z
#define BOOST_TEST_DYN_LINK #define BOOST_TEST_MODULE AllegroColorAttributeDatatypeTestModule #include <boost/test/unit_test.hpp> #include <allegro_flare/attributes.h> #include <allegro_flare/allegro_color_attribute_datatype.h> using namespace allegro_flare; BOOST_AUTO_TEST_CASE(allegro_color_custom_attribute_can_set_and_get_an_allegro_color) { Attributes::create_datatype_definition( AllegroColorAttributeDatatype::IDENTIFIER, AllegroColorAttributeDatatype::to_val_func, AllegroColorAttributeDatatype::to_str_func ); Attributes attributes; ALLEGRO_COLOR color_1 = al_map_rgba_f(0.123, 0.357, 0.876, 0.926); ALLEGRO_COLOR color_2 = al_map_rgb(0, 0, 0); BOOST_CHECK_EQUAL(true, attributes.set("the_color", AllegroColorAttributeDatatype::IDENTIFIER, &color_1)); BOOST_CHECK_EQUAL(true, attributes.get_as_custom(&color_2, AllegroColorAttributeDatatype::IDENTIFIER, "the_color")); BOOST_CHECK_CLOSE(0.123, color_2.r, 0.0001); BOOST_CHECK_CLOSE(0.357, color_2.g, 0.0001); BOOST_CHECK_CLOSE(0.876, color_2.b, 0.0001); BOOST_CHECK_CLOSE(0.926, color_2.a, 0.0001); } BOOST_AUTO_TEST_CASE(allegro_color_custom_attribute_has_the_expected_identifier) { BOOST_CHECK_EQUAL("ALLEGRO_COLOR", AllegroColorAttributeDatatype::IDENTIFIER); }
26.530612
119
0.797692
MarkOates
8d75ba28eb5e18b431b41f9605de3cfb2f9048c9
512
cpp
C++
CoreTest/src/FileVersionTest.cpp
ProtocolONE/cord.core
f8d16d095d3234144a1a6b46b5ed042363c4f549
[ "Apache-2.0" ]
1
2019-08-07T06:16:12.000Z
2019-08-07T06:16:12.000Z
CoreTest/src/FileVersionTest.cpp
ProtocolONE/cord.core
f8d16d095d3234144a1a6b46b5ed042363c4f549
[ "Apache-2.0" ]
null
null
null
CoreTest/src/FileVersionTest.cpp
ProtocolONE/cord.core
f8d16d095d3234144a1a6b46b5ed042363c4f549
[ "Apache-2.0" ]
null
null
null
#include <Core/System/FileInfo.h> #include <QtCore/QCoreApplication> #include <gtest/gtest.h> TEST(FileVersionTest, getSelfVersion) { QString selfExePath = QCoreApplication::applicationFilePath(); QString selfVersion = P1::Core::System::FileInfo::version(selfExePath); ASSERT_EQ("1.2.3.4", selfVersion); int hiVersion = 0; int loVersion = 0; P1::Core::System::FileInfo::version(selfExePath, hiVersion, loVersion); ASSERT_EQ(MAKELONG(2, 1), hiVersion); ASSERT_EQ(MAKELONG(4, 3), loVersion); }
26.947368
73
0.736328
ProtocolONE
8d7a20d11e39bb5f0d7f05f46b91c2d8fcd358ce
461
cpp
C++
Leetcode/Practice/Remove All Adjacent Duplicates In String.cpp
coderanant/Competitive-Programming
45076af7894251080ac616c9581fbf2dc49604af
[ "MIT" ]
4
2019-06-04T11:03:38.000Z
2020-06-19T23:37:32.000Z
Leetcode/Practice/Remove All Adjacent Duplicates In String.cpp
coderanant/Competitive-Programming
45076af7894251080ac616c9581fbf2dc49604af
[ "MIT" ]
null
null
null
Leetcode/Practice/Remove All Adjacent Duplicates In String.cpp
coderanant/Competitive-Programming
45076af7894251080ac616c9581fbf2dc49604af
[ "MIT" ]
null
null
null
class Solution { public: string removeDuplicates(string S) { stack<char> st; for(int i = 0; i < S.size(); i++) { if(!st.empty() and S[i] == st.top()) st.pop(); else st.push(S[i]); } string ans; while(!st.empty()) { ans += st.top(); st.pop(); } reverse(ans.begin(), ans.end()); return ans; } };
21.952381
48
0.37744
coderanant
8d7eae302f24679c43b7ad2a78ce5727d36e918b
1,549
cpp
C++
libs/geometry/test/core/assert.cpp
lijgame/boost
ec2214a19cdddd1048058321a8105dd0231dac47
[ "BSL-1.0" ]
1
2018-12-15T19:57:24.000Z
2018-12-15T19:57:24.000Z
thirdparty-cpp/boost_1_62_0/libs/geometry/test/core/assert.cpp
nxplatform/nx-mobile
0dc174c893f2667377cb2ef7e5ffeb212fa8b3e5
[ "Apache-2.0" ]
null
null
null
thirdparty-cpp/boost_1_62_0/libs/geometry/test/core/assert.cpp
nxplatform/nx-mobile
0dc174c893f2667377cb2ef7e5ffeb212fa8b3e5
[ "Apache-2.0" ]
1
2019-03-08T11:06:22.000Z
2019-03-08T11:06:22.000Z
// Boost.Geometry (aka GGL, Generic Geometry Library) // Unit Test // Copyright (c) 2015 Oracle and/or its affiliates. // Contributed and/or modified by Adam Wulkiewicz, on behalf of Oracle // 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 <geometry_test_common.hpp> #define BOOST_GEOMETRY_ENABLE_ASSERT_HANDLER #include <boost/geometry/core/assert.hpp> struct assert_failure_exception : std::exception { const char * what() const throw() { return "assertion failure"; } }; namespace boost { namespace geometry { inline void assertion_failed(char const * expr, char const * function, char const * file, long line) { throw assert_failure_exception(); } inline void assertion_failed_msg(char const * expr, char const * msg, char const * function, char const * file, long line) { throw assert_failure_exception(); } }} void fun1(bool condition) { BOOST_GEOMETRY_ASSERT(condition); } void fun2(bool condition, const char* msg = "") { BOOST_GEOMETRY_ASSERT_MSG(condition, msg); } bool is_ok(assert_failure_exception const& ) { return true; } int test_main(int, char* []) { int a = 1; fun1(a == 1); BOOST_CHECK_EXCEPTION(fun1(a == 2), assert_failure_exception, is_ok); fun2(a == 1); BOOST_CHECK_EXCEPTION(fun2(a == 2), assert_failure_exception, is_ok); return 0; }
24.203125
123
0.684958
lijgame
8d7f0170121e4b41be8607dcb9582e84d180b36b
727
cpp
C++
nowcoder/317-B.cpp
PIPIKAI/ACM
b8e4416a29c0619946c9b73b0fe5699b6e96e782
[ "MIT" ]
null
null
null
nowcoder/317-B.cpp
PIPIKAI/ACM
b8e4416a29c0619946c9b73b0fe5699b6e96e782
[ "MIT" ]
null
null
null
nowcoder/317-B.cpp
PIPIKAI/ACM
b8e4416a29c0619946c9b73b0fe5699b6e96e782
[ "MIT" ]
null
null
null
#include<bits/stdc++.h> using namespace std; typedef long long ll; #define inf 1e9+7 #define ffr(i,a,b) for(int i=a;i<b;i++) #define mem(a,b) memset( a,b,sizeof a) ll n,m; ll cnt[5]={0}; ll ans=0; int main() { std::ios::sync_with_stdio(false); cin>>n; ans=0; for(int i=1;i<=n;i++) { int t; cin>>t; cnt[t]++; } int pre=0; for(ll i=0;i<=n;i++) { ll sum=0,id; for(ll j=0;j<5;j++) { if(cnt[j]!=0&&sum<abs(j-pre)) { sum=abs(j-pre); id=j; } } /// cout<<sum<<endl; ans+=sum*sum; cnt[id]--; pre=id; } cout<<ans<<endl; return 0; }
17.731707
41
0.420908
PIPIKAI
8d89fe13e6f506e446486b79f31bddc496df98c1
1,014
cpp
C++
leetcode/HappyNumber.cpp
openluopworld/basic_algorithms
752de0c6b4899e657514f0228d6793b561a004de
[ "MIT" ]
1
2015-08-19T01:12:45.000Z
2015-08-19T01:12:45.000Z
leetcode/HappyNumber.cpp
openluopworld/Algorithms
752de0c6b4899e657514f0228d6793b561a004de
[ "MIT" ]
null
null
null
leetcode/HappyNumber.cpp
openluopworld/Algorithms
752de0c6b4899e657514f0228d6793b561a004de
[ "MIT" ]
null
null
null
/* * Problem: Happy Number * * Write an algorithm to determine if a number is "happy". * A happy number is a number defined by the following process: Starting with any positive integer, * replace the number by the sum of the squares of its digits, * and repeat the process until the number equals 1 (where it will stay), * or it loops endlessly in a cycle which does not include 1. * Those numbers for which this process ends in 1 are happy numbers. */ #include<stdio.h> #include<math.h> bool isHappy(int n) { int temp = 10; /* * If n is smaller than 10, you can get than only 1 or 7 will be true by computing. * There is a problem: will every number be smaller than 10 some time later? */ while ( temp >= 10) { temp = 0; while ( n != 0 ) { temp += (n%10)*(n%10); n = n/10; } n = temp; // printf("%d\n", temp); } return temp==7 || temp==1; } int main () { for ( int i = 0; i < 100; i++ ) { printf("%d, %s\n", i, (isHappy(i)==false)?"false":"true"); } return 0; }
26.684211
100
0.628205
openluopworld
8d8e0c867286fe8efe713bc790bb8ec0869f5c5d
1,067
cpp
C++
examples/00_helloworld/00_helloworld_qt.cpp
igor-krechetov/hsmcpp
5b0fcddacc43ad54a474c16767fa593ac0919393
[ "MIT" ]
10
2021-03-17T17:26:50.000Z
2022-03-30T17:33:23.000Z
examples/00_helloworld/00_helloworld_qt.cpp
igor-krechetov/hsmcpp
5b0fcddacc43ad54a474c16767fa593ac0919393
[ "MIT" ]
1
2022-03-30T16:29:01.000Z
2022-03-30T16:29:01.000Z
examples/00_helloworld/00_helloworld_qt.cpp
igor-krechetov/hsmcpp
5b0fcddacc43ad54a474c16767fa593ac0919393
[ "MIT" ]
null
null
null
#include <chrono> #include <thread> #include <hsmcpp/hsm.hpp> #include <hsmcpp/HsmEventDispatcherQt.hpp> #include <QCoreApplication> using namespace std::chrono_literals; using namespace hsmcpp; enum class States { OFF, ON }; enum class Events { SWITCH }; int main(int argc, char** argv) { QCoreApplication app(argc, argv); HierarchicalStateMachine<States, Events> hsm(States::OFF); hsm.registerState(States::OFF, [&hsm](const VariantVector_t& args) { printf("Off\n"); std::this_thread::sleep_for(1000ms); hsm.transition(Events::SWITCH); }); hsm.registerState(States::ON, [&hsm](const VariantVector_t& args) { printf("On\n"); std::this_thread::sleep_for(1000ms); hsm.transition(Events::SWITCH); }); hsm.registerTransition(States::OFF, States::ON, Events::SWITCH); hsm.registerTransition(States::ON, States::OFF, Events::SWITCH); hsm.initialize(std::make_shared<HsmEventDispatcherQt>()); hsm.transition(Events::SWITCH); app.exec(); return 0; }
22.229167
70
0.665417
igor-krechetov
8d916e89ea106d60c42e8471d3cecaf3d4fa72e3
3,110
cc
C++
src/flutter/shell/platform/linux_embedded/surface/context_egl_stream.cc
TomohideMorimoto/flutter-embedded-linux
e7b1e98e646e88aa52dc1abe9f14444c2b070a39
[ "BSD-3-Clause" ]
null
null
null
src/flutter/shell/platform/linux_embedded/surface/context_egl_stream.cc
TomohideMorimoto/flutter-embedded-linux
e7b1e98e646e88aa52dc1abe9f14444c2b070a39
[ "BSD-3-Clause" ]
null
null
null
src/flutter/shell/platform/linux_embedded/surface/context_egl_stream.cc
TomohideMorimoto/flutter-embedded-linux
e7b1e98e646e88aa52dc1abe9f14444c2b070a39
[ "BSD-3-Clause" ]
null
null
null
// Copyright 2021 Sony Corporation. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "flutter/shell/platform/linux_embedded/surface/context_egl_stream.h" #include "flutter/shell/platform/linux_embedded/logger.h" #include "flutter/shell/platform/linux_embedded/window/native_window_drm_eglstream.h" namespace flutter { ContextEglStream::ContextEglStream( std::unique_ptr<EnvironmentEglStream> environment) : ContextEgl(std::move(environment), EGL_STREAM_BIT_KHR) { if (!valid_) { return; } if (!SetEglExtensionFunctionPointers()) { LINUXES_LOG(ERROR) << "Failed to set extension function pointers"; valid_ = false; } } std::unique_ptr<LinuxesEGLSurface> ContextEglStream::CreateOnscreenSurface( NativeWindow* window) const { EGLint layer_count = 0; EGLOutputLayerEXT layer; EGLAttrib layer_attribs[] = { // clang-format off EGL_DRM_PLANE_EXT, static_cast<NativeWindowDrmEglstream*>(window)->PlaneId(), EGL_NONE // clang-format on }; if (eglGetOutputLayersEXT_(environment_->Display(), layer_attribs, &layer, 1, &layer_count) != EGL_TRUE) { LINUXES_LOG(ERROR) << "Failed to get EGL output layers"; } if (layer_count == 0 || layer == nullptr) { LINUXES_LOG(ERROR) << "No matching layers"; } EGLint stream_attribs[] = {EGL_NONE}; auto stream = eglCreateStreamKHR_(environment_->Display(), stream_attribs); if (stream == EGL_NO_STREAM_KHR) { LINUXES_LOG(ERROR) << "Failed to create EGL stream"; } if (eglStreamConsumerOutputEXT_(environment_->Display(), stream, layer) != EGL_TRUE) { LINUXES_LOG(ERROR) << "Failed to create EGL stream consumer output"; } EGLint surface_attribs[] = { // clang-format off EGL_WIDTH, window->Width(), EGL_HEIGHT, window->Height(), EGL_NONE // clang-format on }; auto surface = eglCreateStreamProducerSurfaceKHR_( environment_->Display(), config_, stream, surface_attribs); if (surface == EGL_NO_SURFACE) { LINUXES_LOG(ERROR) << "Failed to create EGL stream producer surface"; } return std::make_unique<LinuxesEGLSurface>(surface, environment_->Display(), context_); } bool ContextEglStream::SetEglExtensionFunctionPointers() { eglGetOutputLayersEXT_ = reinterpret_cast<PFNEGLGETOUTPUTLAYERSEXTPROC>( eglGetProcAddress("eglGetOutputLayersEXT")); eglCreateStreamKHR_ = reinterpret_cast<PFNEGLCREATESTREAMKHRPROC>( eglGetProcAddress("eglCreateStreamKHR")); eglStreamConsumerOutputEXT_ = reinterpret_cast<PFNEGLSTREAMCONSUMEROUTPUTEXTPROC>( eglGetProcAddress("eglStreamConsumerOutputEXT")); eglCreateStreamProducerSurfaceKHR_ = reinterpret_cast<PFNEGLCREATESTREAMPRODUCERSURFACEKHRPROC>( eglGetProcAddress("eglCreateStreamProducerSurfaceKHR")); return eglGetOutputLayersEXT_ && eglCreateStreamKHR_ && eglStreamConsumerOutputEXT_ && eglCreateStreamProducerSurfaceKHR_; } } // namespace flutter
35.340909
85
0.719614
TomohideMorimoto
8d92060bd9adab1f684310568b65baf7a549791c
885
cpp
C++
modules/complex-number/test/test_Elanskiy_Alexandr_complex_number.cpp
BalovaElena/devtools-course-practice
f8d5774dbb78ec50200c45fd17665ed40fc8c4c5
[ "CC-BY-4.0" ]
null
null
null
modules/complex-number/test/test_Elanskiy_Alexandr_complex_number.cpp
BalovaElena/devtools-course-practice
f8d5774dbb78ec50200c45fd17665ed40fc8c4c5
[ "CC-BY-4.0" ]
null
null
null
modules/complex-number/test/test_Elanskiy_Alexandr_complex_number.cpp
BalovaElena/devtools-course-practice
f8d5774dbb78ec50200c45fd17665ed40fc8c4c5
[ "CC-BY-4.0" ]
null
null
null
// Copyright 2022 Elanskiy Alexandr #include <gtest/gtest.h> #include "include/complex_number.h" TEST(Elanskiy_Alexandr_ComplexNumberTest, Create) { ASSERT_NO_THROW(ComplexNumber z(5.2, 1.7)); } TEST(Elanskiy_Alexandr_ComplexNumberTest, Subtraction) { double re1 = 5.0; double im1 = 1.0; double re2 = 2.0; double im2 = 1.5; ComplexNumber tmp1(re1, im1); ComplexNumber tmp2(re2, im2); ComplexNumber Subtraction = tmp1 - tmp2; EXPECT_EQ(re1 - re2, Subtraction.getRe()); EXPECT_EQ(im1 - im2, Subtraction.getIm()); } TEST(Elanskiy_Alexandr_ComplexNumberTest, Sum) { double re1 = 1.0; double im1 = 1.5; double re2 = 2.0; double im2 = 2.5; ComplexNumber tmp1(re1, im1); ComplexNumber tmp2(re2, im2); ComplexNumber Sum = tmp1 + tmp2; EXPECT_EQ(re1 + re2, Sum.getRe()); EXPECT_EQ(im1 + im2, Sum.getIm()); }
22.692308
56
0.666667
BalovaElena
8d95c94770b12b1c7c07e8c957fd95ed5b3942d0
6,303
hpp
C++
src/xsi_shm.hpp
lcTls/levin
7c3768ba96c752fe30b721fcc3af0f7202d5b6b3
[ "Apache-2.0" ]
1
2019-08-31T03:16:19.000Z
2019-08-31T03:16:19.000Z
src/xsi_shm.hpp
msdgwzhy6/levin
082a21d29ac19acbd16c5874367e77a424b7d255
[ "Apache-2.0" ]
null
null
null
src/xsi_shm.hpp
msdgwzhy6/levin
082a21d29ac19acbd16c5874367e77a424b7d255
[ "Apache-2.0" ]
null
null
null
#ifndef LEVIN_XSI_SHM_H #define LEVIN_XSI_SHM_H #include <fstream> #include <boost/interprocess/xsi_shared_memory.hpp> #include <boost/interprocess/mapped_region.hpp> #include <boost/algorithm/string.hpp> #include "shared_utils.h" namespace levin { namespace bip = boost::interprocess; const size_t MAX_MEM_SIZE = 60000000000; // Maximum limit 60G const std::string LEVIN("levin"); class SharedMemory { public: SharedMemory(const std::string &path, int id = 1, const size_t mem_size = 0) : _path(path), _mem_size(mem_size), _id(id) { } virtual ~SharedMemory() { SAFE_DELETE(_region_ptr); SAFE_DELETE(_shm_ptr); } bool remove_shared_memory() { try { if (_region_ptr && _shm_ptr) { SAFE_DELETE(_region_ptr); bip::xsi_shared_memory::remove(_shm_ptr->get_shmid()); SAFE_DELETE(_shm_ptr); } } catch(bip::interprocess_exception &e) { if (e.get_error_code() != bip::not_found_error) { LEVIN_CWARNING_LOG("remove shm failed, shmid: %d", _shm_ptr->get_shmid()); return false; } } return true; } static bool remove_shared_memory(int shmid) { try { bip::xsi_shared_memory::remove(shmid); } catch (bip::interprocess_exception &e) { if (e.get_error_code() != bip::not_found_error) { LEVIN_CWARNING_LOG("remove shm failed, shmid: %d", shmid); return false; } } return true; } //@brief get shmids from the system with identifier 'levin' //"no_attach" is for Whether to get no application attached shared memory //return file->shmid static bool get_all_shmid(std::vector<SharedMidInfo> &shmid_info, bool no_attach = true) { std::vector<int> vec_shmid; struct shmid_ds shm_info; struct shmid_ds shm_segment; int max_id = ::shmctl(0, SHM_INFO, &shm_info); for (int i=0; i<=max_id; ++i) { int shm_id = ::shmctl(i, SHM_STAT, &shm_segment); if (shm_id <= 0) continue; else { if (no_attach) { if (shm_segment.shm_nattch == 0) { vec_shmid.emplace_back(shm_id); } } else { vec_shmid.emplace_back(shm_id); } } } shmid_info.clear(); for (auto mid: vec_shmid) { try { bip::xsi_shared_memory shm(bip::open_only, mid); bip::mapped_region region(shm, bip::read_write); SharedMeta *meta = static_cast<SharedMeta *>(region.get_address()); if (std::string(meta->summary).find(LEVIN) != std::string::npos) { shmid_info.emplace_back(SharedMidInfo(meta->path, mid, meta->group, meta->id)); } else { LEVIN_CWARNING_LOG("maybe no levin create, shmid:%d",mid); } } catch (bip::interprocess_exception &ex) { LEVIN_CWARNING_LOG("get shm failed, code:%d, info:%s, mid:%d", ex.get_error_code(), ex.what(), mid); } catch (...) { LEVIN_CWARNING_LOG("unknown_exception, shmid:%d", mid); } } return true; } //@brief Returns the shared memory ID that identifies the shared memory inline int get_shmid() const { return _shm_ptr == nullptr ? 0:_shm_ptr->get_shmid(); } //@brief Returns the base address of the shared memory inline void* get_address() const { return _region_ptr == nullptr ? nullptr:_region_ptr->get_address(); } inline bool is_exist() const { return _is_exist; } inline std::size_t get_size() const { return _region_ptr == nullptr ? 0:_region_ptr->get_size(); } //@brief Open or Create System V shared memory //Returns false on error. inline uint32_t init(const size_t fixed_size = 0) { std::ifstream fin(_path, std::ios::in | std::ios::binary); if (!fin.is_open()) { return SC_RET_FILE_NOEXIST; } int proj_id = make_proj_id(_path, _id); bip::xsi_key key(_path.c_str(), proj_id); if (_mem_size == 0) { fin.read((char*)&_mem_size, sizeof(_mem_size)); if (!fin) { fin.close(); return SC_RET_READ_FAIL; } } _mem_size += fixed_size; if (_mem_size == 0 || _mem_size >= MAX_MEM_SIZE) { LEVIN_CWARNING_LOG("apply shm fail, mem size: %lu", _mem_size); fin.close(); return SC_RET_SHM_SIZE_ERR; } try { _shm_ptr = new bip::xsi_shared_memory(bip::create_only, key, _mem_size); } catch (bip::interprocess_exception &ex) { if (ex.get_error_code() == bip::already_exists_error) { _shm_ptr = new bip::xsi_shared_memory(bip::open_only, key); _is_exist = true; } } fin.close(); if (nullptr == _shm_ptr) { return SC_RET_OOM; } _region_ptr = new bip::mapped_region(*_shm_ptr, bip::read_write); if (nullptr == _region_ptr) { return SC_RET_OOM; } LEVIN_CINFO_LOG("shm init succ. path=%s, shmid=%d, size=%ld, region=[%p,%p)", _path.c_str(), get_shmid(), get_size(), get_address(), (void*)((size_t)get_address() + get_size())); return SC_RET_OK; } private: int make_proj_id(std::string path, int id){ std::hash<std::string> hashFunc; size_t hash_id = hashFunc(path); uint8_t proj_id = 0; const char *p = reinterpret_cast<const char*>(&hash_id); for (uint32_t i = 0; i<sizeof(hash_id); i++) { proj_id ^= p[i]; } return proj_id ^ id; } protected: std::string _path; size_t _mem_size; int _id; bip::xsi_shared_memory* _shm_ptr = nullptr; bip::mapped_region* _region_ptr = nullptr; bool _is_exist = false; }; } //endif levin #endif // LEVIN_XSI_SHM_H
34.07027
116
0.555291
lcTls
8d964f7efa18d3fac270bd72c4a14e418a555c02
2,731
cpp
C++
BinaryFiles.cpp
TheoRussell/Game-Engine
7cbb39012908c5bc9065fab9ccc6685b96bbc26e
[ "MIT" ]
null
null
null
BinaryFiles.cpp
TheoRussell/Game-Engine
7cbb39012908c5bc9065fab9ccc6685b96bbc26e
[ "MIT" ]
null
null
null
BinaryFiles.cpp
TheoRussell/Game-Engine
7cbb39012908c5bc9065fab9ccc6685b96bbc26e
[ "MIT" ]
null
null
null
#include "BinaryFiles.h" BinaryFiles::BinaryFiles() { } BinaryFiles::~BinaryFiles() { } std::string BinaryFiles::getString(std::ifstream &s) { unsigned int size = 0; //It reads the size of the string message to create the buffer. s.read(reinterpret_cast<char *>(&size), sizeof(size)); char *buffer = new char[size]; //It then reads the data into the buffer. s.read(buffer, size); std::string result = ""; //Appends the buffer into the string. result.append(buffer, size); delete[] buffer; return result; } BINARYWrite BinaryFiles::getBINARYType(std::ifstream &s) { //Binary Types will be used to identify what section of the file is being read (assists error handling). BINARYWrite writeType = BINARY_Label; s.read((char*)(&writeType), sizeof(BINARYWrite)); return writeType; } glm::vec2 BinaryFiles::getVec2(std::ifstream &s) { glm::vec2 writeType(0.0f); s.read((char*)(&writeType), sizeof(glm::vec2)); return writeType; } glm::vec3 BinaryFiles::getVec3(std::ifstream &s) { glm::vec3 writeType(0.0f); s.read((char*)(&writeType), sizeof(glm::vec3)); return writeType; } glm::vec4 BinaryFiles::getVec4(std::ifstream &s) { glm::vec4 val(0.0f); s.read((char*)(&val), sizeof(glm::vec4)); return val; } float BinaryFiles::getFloat(std::ifstream &s) { float val = 0.0f; s.read((char*)(&val), sizeof(float)); return val; } bool BinaryFiles::getBool(std::ifstream &s) { bool val = false; s.read((char*)(&val), sizeof(bool)); return val; } int BinaryFiles::getInt(std::ifstream &s) { int val = 0; s.read((char*)(&val), sizeof(int)); return val; } void BinaryFiles::writeString(std::ofstream &s, std::string &value) { unsigned int size = value.size(); //Writes the size of the string buffer to file. s.write(reinterpret_cast<char *>(&size), sizeof(size)); //Writes string. s.write(value.c_str(), size); } void BinaryFiles::writeFloat(std::ofstream &s, float &value) { s.write((char*)&value, sizeof(float)); } void BinaryFiles::writeBINARYType(std::ofstream &s, BINARYWrite &type) { s.write((char *)(&type), sizeof(BINARYWrite)); } void BinaryFiles::writeVec4(std::ofstream &s, glm::vec4 &value) { s.write((char*)&value[0], sizeof(glm::vec4)); } void BinaryFiles::writeVec3(std::ofstream &s, glm::vec3 &value) { s.write((char*)&value[0], sizeof(glm::vec3)); } void BinaryFiles::writeVec2(std::ofstream &s, glm::vec2 &value) { s.write((char*)&value[0], sizeof(glm::vec2)); } void BinaryFiles::writeBool(std::ofstream &s, bool &value) { s.write((char*)&value, sizeof(bool)); } void BinaryFiles::writeInt(std::ofstream &s, int &value) { s.write((char*)&value, sizeof(int)); }
26.009524
106
0.659832
TheoRussell
8d9f3da48e80e445a6b336d31ff2c84ecb9c6f5d
2,497
cpp
C++
3rdparty/OculusSDKv1_8/Samples/OculusRoomTiny_Advanced/ORT (Protected Content)/main.cpp
PlusToolkit/OvrvisionPro
ed64cade144ce47d17423369476fb43ea69b124d
[ "MIT" ]
1
2017-10-27T14:01:39.000Z
2017-10-27T14:01:39.000Z
OculusSDK/Samples/OculusRoomTiny_Advanced/ORT (Protected Content)/main.cpp
Ybalrid/AnnwvynDeps
3309b126e6e501df5bd7f617cf3c47941b0754e5
[ "CECILL-B" ]
null
null
null
OculusSDK/Samples/OculusRoomTiny_Advanced/ORT (Protected Content)/main.cpp
Ybalrid/AnnwvynDeps
3309b126e6e501df5bd7f617cf3c47941b0754e5
[ "CECILL-B" ]
null
null
null
/************************************************************************************ Filename : Win32_RoomTiny_Main.cpp Content : First-person view test application for Oculus Rift Created : 3rd June 2016 Authors : Tom Heath Copyright : Copyright 2012 Oculus, Inc. All Rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *************************************************************************************/ /// In this simple sample, we set the flag for protected content, /// as our application is initialising its VR swapchain. /// This then prevents other things like mirroring, capture buffers & APIs, /// and DVR apps from getting the data (they should get black). /// Specifically in this sample, the mirror window is thus black, /// whilst the HMD continues to display the scene as normal. /// Experiment by setting the value to false, and see the mirror /// window return. /// This works as long as the HMD connected supports HDCP (DK2, CV1 are fine, CrescentBay does not). #include "../Common/Win32_DirectXAppUtil.h" // DirectX #include "../Common/Win32_BasicVR.h" // Basic VR struct ProtectedContent : BasicVR { ProtectedContent(HINSTANCE hinst) : BasicVR(hinst, L"Protected Content") {} void MainLoop() { //When we initialise our VR layer, we send through a parameter that //will add the extra flag ovrTextureMisc_ProtectedContent to our misc_flags //when we are creating the swapchain. Layer[0] = new VRLayer(Session,0,1.0f,true); while (HandleMessages()) { ActionFromInput(); Layer[0]->GetEyePoses(); for (int eye = 0; eye < 2; ++eye) { Layer[0]->RenderSceneToEyeBuffer(MainCam, RoomScene, eye); } Layer[0]->PrepareLayerHeader(); DistortAndPresent(1); } } }; //------------------------------------------------------------------------------------- int WINAPI WinMain(HINSTANCE hinst, HINSTANCE, LPSTR, int) { ProtectedContent app(hinst); return app.Run(); }
37.833333
100
0.640368
PlusToolkit
8da0c6fc947e003b3d1c888b04b6c13caeb73a5a
4,455
cpp
C++
src/src/dial.cpp
mohistH/nanogui_from_dalerank
ae4b5e04b2d8e2e85ab63b737fd13f8882243526
[ "MIT" ]
2
2021-01-05T08:50:59.000Z
2021-08-17T09:09:55.000Z
src/src/dial.cpp
mohistH/nanogui_from_dalerank
ae4b5e04b2d8e2e85ab63b737fd13f8882243526
[ "MIT" ]
null
null
null
src/src/dial.cpp
mohistH/nanogui_from_dalerank
ae4b5e04b2d8e2e85ab63b737fd13f8882243526
[ "MIT" ]
1
2021-08-17T09:09:57.000Z
2021-08-17T09:09:57.000Z
/* nanogui/dial.cpp -- Fractional dial widget with mouse control NanoGUI was developed by Wenzel Jakob <wenzel.jakob@epfl.ch>. The widget drawing code is based on the NanoVG demo application by Mikko Mononen. All rights reserved. Use of this source code is governed by a BSD-style license that can be found in the LICENSE.txt file. */ #include <nanogui/dial.h> #include <nanogui/theme.h> #include <nanovg.h> #include <nanogui/saveload.h> NAMESPACE_BEGIN(nanogui) RTTI_IMPLEMENT_INFO(Dial, Widget) Dial::Dial(Widget *parent) : Widget(parent), mValue(0.0f), mRange(0.f, 1.f), mHighlightedRange(0.f, 0.f) { mHighlightColor = Color(255, 80, 80, 70); } Vector2i Dial::preferredSize(NVGcontext *) const { return Vector2i(40, 40); } bool Dial::mouseDragEvent(const Vector2i &p, const Vector2i & /* rel */, int /* button */, int /* modifiers */) { if (!mEnabled) return false; Vector2f pos = (p - mPos - mSize/2).cast<float>(); float value = 0.5f + 0.5f*atan2f(pos.x(), -pos.y())/NVG_PI; value = -0.1f + 1.2f*value; value = value * (mRange.second - mRange.first) + mRange.first; mValue = std::min(std::max(value, mRange.first), mRange.second); if (mCallback) mCallback(mValue); return true; } bool Dial::mouseButtonEvent(const Vector2i &p, int /* button */, bool down, int /* modifiers */) { if (!mEnabled) return false; if (down) { Vector2f pos = (p - mPos - mSize/2).cast<float>(); float kr = 0.5f * (mSize.y() * 0.4f); if (pos.squaredNorm() >= kr*kr) { float value = 0.5f + 0.5f*atan2f(pos.x(), -pos.y())/NVG_PI; value = -0.1f + 1.2f*value; value = value * (mRange.second - mRange.first) + mRange.first; mValue = std::min(std::max(value, mRange.first), mRange.second); } if (mCallback) mCallback(mValue); } else if (mFinalCallback) { mFinalCallback(mValue); } return true; } void Dial::draw(NVGcontext* ctx) { Vector2f center = mPos.cast<float>() + mSize.cast<float>() * 0.5f; float kr = (int) (mSize.y() * 0.4f), kshadow = 2; Vector2f dialPos(center.x(), center.y() + 0.5f); NVGpaint dial = nvgLinearGradient(ctx, mPos.x(), center.y() - kr, mPos.x(), center.y() + kr, mTheme->mBorderLight, mTheme->mBorderMedium); NVGpaint dialReverse = nvgLinearGradient(ctx, mPos.x(), center.y() - kr, mPos.x(), center.y() + kr, mTheme->mBorderMedium, mTheme->mBorderLight); NVGpaint dialFace = nvgRadialGradient(ctx, dialPos.x(), dialPos.y(), kr - kshadow, kr + kshadow, Color(150, mEnabled ? 255 : 100), mTheme->mTransparent); if (mHighlightedRange.second != mHighlightedRange.first) { float a0 = 0.5f*NVG_PI + 2.0f*NVG_PI*(0.1f + 0.8f * mHighlightedRange.first); float a1 = 0.5f*NVG_PI + 2.0f*NVG_PI*(0.1f + 0.8f * mHighlightedRange.second); nvgBeginPath(ctx); nvgArc(ctx, dialPos, kr, a0, a1, NVG_CW); nvgArc(ctx, dialPos, kr + 2*kshadow, a1, a0, NVG_CCW); nvgFillColor(ctx, mHighlightColor); nvgFill(ctx); } nvgBeginPath(ctx); nvgCircle(ctx, dialPos, kr); nvgStrokeColor(ctx, mTheme->mBorderDark); nvgFillPaint(ctx, dial); nvgStroke(ctx); nvgFill(ctx); nvgBeginPath(ctx); nvgCircle(ctx, dialPos, kr - kshadow); nvgFillPaint(ctx, dialFace); nvgStrokePaint(ctx, dialReverse); nvgStroke(ctx); nvgFill(ctx); Vector2f notchPos(0.0f, 0.8f*(kr - 1.5f*kshadow)); float value = (mValue - mRange.first)/(mRange.second - mRange.first); float theta = 2.0f*NVG_PI*(0.1f + 0.8f*value); notchPos.rotateBy(nvgRadToDeg(theta), Vector2f::Zero()); notchPos += dialPos + mPos.cast<float>(); nvgBeginPath(ctx); nvgCircle(ctx, notchPos, 0.15f*kr); nvgFillColor(ctx, Color(mEnabled ? 50 : 100, 150)); nvgStrokePaint(ctx, dial); nvgStroke(ctx); nvgFill(ctx); } void Dial::save(Json::value &s) const { Widget::save(s); auto obj = s.get_obj(); obj["value"] = json().set(mValue).name("Value"); obj["range"] = json().set(mRange).name("Range"); s = Json::value(s); } bool Dial::load(Json::value &save) { Widget::load(save); json s{ save.get_obj() }; mValue = s.get<float>("value"); mRange = s.get<decltype(mRange)>("range"); return true; } NAMESPACE_END(nanogui)
29.7
112
0.61459
mohistH
8da1236b715d2db4e5a8c5a262f13c6abecb5a7c
996
cpp
C++
niuke_HW/chapter4_HW/HW4-2.cpp
drt4243566/leetcode_learn
ef51f215079556895eec2252d84965cd1c3a7bf4
[ "MIT" ]
null
null
null
niuke_HW/chapter4_HW/HW4-2.cpp
drt4243566/leetcode_learn
ef51f215079556895eec2252d84965cd1c3a7bf4
[ "MIT" ]
null
null
null
niuke_HW/chapter4_HW/HW4-2.cpp
drt4243566/leetcode_learn
ef51f215079556895eec2252d84965cd1c3a7bf4
[ "MIT" ]
null
null
null
#include <unordered_map> #include <iostream> #include <vector> using namespace std; class Solution { public: vector<int> twoSum(vector<int> &numbers, int target) { // write code here int n = numbers.size(); vector<int> res; unordered_map<int, int> mp; // key值代表numbers数组中的元素,value表示对应索引 for (int i = 0; i < n; i++) { if (mp[target - numbers[i]] != 0) { res.push_back(mp[target - numbers[i]]); // 这里的次序,由于匹配的是先前存入的元素 res.push_back(i + 1); // 所以匹配项存在前面 break; } else { mp[numbers[i]] = i + 1; // 索引从1开始计算,因此需要+1 } } return res; } }; int main() { Solution sol; vector<int> numbers = {3, 2, 4}; int target = 6; vector<int> res = sol.twoSum(numbers, target); for (int i : res) { cout << i << " "; } cout << endl; return 0; }
22.133333
78
0.46988
drt4243566
8da90f2fc16acb3d8c68d11b3bb6c33508a5535e
1,415
cpp
C++
zappy/gfx_d/src/free.cpp
fflorens/portofolio42
4368c33460129beaebea0c983a133f717bc9fe13
[ "MIT" ]
null
null
null
zappy/gfx_d/src/free.cpp
fflorens/portofolio42
4368c33460129beaebea0c983a133f717bc9fe13
[ "MIT" ]
null
null
null
zappy/gfx_d/src/free.cpp
fflorens/portofolio42
4368c33460129beaebea0c983a133f717bc9fe13
[ "MIT" ]
null
null
null
// ************************************************************************** // // // // ::: :::::::: // // free.cpp :+: :+: :+: // // +:+ +:+ +:+ // // By: abanvill <abanvill@student.42.fr> +#+ +:+ +#+ // // +#+#+#+#+#+ +#+ // // Created: 2014/06/20 19:09:05 by abanvill #+# #+# // // Updated: 2014/06/20 19:09:06 by abanvill ### ########.fr // // // // ************************************************************************** // #include <zproject.h> #include <SDL/SDL.h> void freeAllAssets(void) { t_game *params; params = getGameParams(); if (params) { for (int i = 0; i < GROUNDS_HOLD_NUMBER; i++) SDL_FreeSurface(params->assets[GROUNDS_HOLD][i]); for (int i = 0; i < GROUNDS_NUMBER; i++) SDL_FreeSurface(params->assets[GROUNDS][i]); for (int i = 0; i < CHARACTERS_NUMBER; i++) SDL_FreeSurface(params->assets[CHARACTERS][i]); for (int i = 0; i < GEMS_SPRITE_NUMBER; i++) SDL_FreeSurface(params->assets[GEMS][i]); } }
44.21875
80
0.313074
fflorens
8dab25cce56947eaf5283ed7e37bd007d5fac664
2,250
hpp
C++
src/Time/StepChoosers/Increase.hpp
trami18/spectre
6b1f6497bf2e26d1474bfadf143b3321942c40b4
[ "MIT" ]
2
2021-04-11T04:07:42.000Z
2021-04-11T05:07:54.000Z
src/Time/StepChoosers/Increase.hpp
trami18/spectre
6b1f6497bf2e26d1474bfadf143b3321942c40b4
[ "MIT" ]
null
null
null
src/Time/StepChoosers/Increase.hpp
trami18/spectre
6b1f6497bf2e26d1474bfadf143b3321942c40b4
[ "MIT" ]
null
null
null
// Distributed under the MIT License. // See LICENSE.txt for details. #pragma once #include <cmath> #include <limits> #include <pup.h> #include <utility> #include "Options/Options.hpp" #include "Parallel/CharmPupable.hpp" #include "Time/StepChoosers/StepChooser.hpp" // IWYU pragma: keep #include "Time/Time.hpp" #include "Utilities/Registration.hpp" #include "Utilities/TMPL.hpp" /// \cond namespace Parallel { template <typename Metavariables> class GlobalCache; } // namespace Parallel /// \endcond namespace StepChoosers { template <typename StepChooserRegistrars> class Increase; namespace Registrars { using Increase = Registration::Registrar<StepChoosers::Increase>; } // namespace Registrars /// Suggests increasing the step size by a constant ratio. template <typename StepChooserRegistrars = tmpl::list<Registrars::Increase>> class Increase : public StepChooser<StepChooserRegistrars> { public: /// \cond Increase() = default; explicit Increase(CkMigrateMessage* /*unused*/) noexcept {} using PUP::able::register_constructor; WRAPPED_PUPable_decl_template(Increase); // NOLINT /// \endcond struct Factor { using type = double; static constexpr Options::String help{"Factor to increase by"}; static type lower_bound() noexcept { return 1.0; } }; static constexpr Options::String help{"Suggests a constant factor increase."}; using options = tmpl::list<Factor>; explicit Increase(const double factor) noexcept : factor_(factor) {} static constexpr UsableFor usable_for = UsableFor::AnyStepChoice; using argument_tags = tmpl::list<>; using return_tags = tmpl::list<>; template <typename Metavariables> std::pair<double, bool> operator()( const double last_step_magnitude, const Parallel::GlobalCache<Metavariables>& /*cache*/) const noexcept { return std::make_pair(last_step_magnitude * factor_, true); } // NOLINTNEXTLINE(google-runtime-references) void pup(PUP::er& p) noexcept override { p | factor_; } private: double factor_ = std::numeric_limits<double>::signaling_NaN(); }; /// \cond template <typename StepChooserRegistrars> PUP::able::PUP_ID Increase<StepChooserRegistrars>::my_PUP_ID = 0; // NOLINT /// \endcond } // namespace StepChoosers
28.481013
80
0.738222
trami18
8dab492cb9c1f662ad7ec67a37fb357e99409726
4,069
cpp
C++
src/dis7/Association.cpp
AlphaPixel/open-dis-cpp
90634cade32ac98e2108be8799bd2ec949c4337e
[ "BSD-2-Clause" ]
42
2017-02-22T07:23:06.000Z
2022-03-07T12:34:11.000Z
src/dis7/Association.cpp
AlphaPixel/open-dis-cpp
90634cade32ac98e2108be8799bd2ec949c4337e
[ "BSD-2-Clause" ]
62
2017-07-14T11:06:55.000Z
2022-01-22T02:32:45.000Z
src/dis7/Association.cpp
AlphaPixel/open-dis-cpp
90634cade32ac98e2108be8799bd2ec949c4337e
[ "BSD-2-Clause" ]
51
2017-08-10T16:44:32.000Z
2021-12-16T09:57:42.000Z
#include <dis7/Association.h> using namespace DIS; Association::Association(): _associationType(0), _padding4(0), _associatedEntityID(), _associatedLocation() { } Association::~Association() { } unsigned char Association::getAssociationType() const { return _associationType; } void Association::setAssociationType(unsigned char pX) { _associationType = pX; } unsigned char Association::getPadding4() const { return _padding4; } void Association::setPadding4(unsigned char pX) { _padding4 = pX; } EntityID& Association::getAssociatedEntityID() { return _associatedEntityID; } const EntityID& Association::getAssociatedEntityID() const { return _associatedEntityID; } void Association::setAssociatedEntityID(const EntityID &pX) { _associatedEntityID = pX; } Vector3Double& Association::getAssociatedLocation() { return _associatedLocation; } const Vector3Double& Association::getAssociatedLocation() const { return _associatedLocation; } void Association::setAssociatedLocation(const Vector3Double &pX) { _associatedLocation = pX; } void Association::marshal(DataStream& dataStream) const { dataStream << _associationType; dataStream << _padding4; _associatedEntityID.marshal(dataStream); _associatedLocation.marshal(dataStream); } void Association::unmarshal(DataStream& dataStream) { dataStream >> _associationType; dataStream >> _padding4; _associatedEntityID.unmarshal(dataStream); _associatedLocation.unmarshal(dataStream); } bool Association::operator ==(const Association& rhs) const { bool ivarsEqual = true; if( ! (_associationType == rhs._associationType) ) ivarsEqual = false; if( ! (_padding4 == rhs._padding4) ) ivarsEqual = false; if( ! (_associatedEntityID == rhs._associatedEntityID) ) ivarsEqual = false; if( ! (_associatedLocation == rhs._associatedLocation) ) ivarsEqual = false; return ivarsEqual; } int Association::getMarshalledSize() const { int marshalSize = 0; marshalSize = marshalSize + 1; // _associationType marshalSize = marshalSize + 1; // _padding4 marshalSize = marshalSize + _associatedEntityID.getMarshalledSize(); // _associatedEntityID marshalSize = marshalSize + _associatedLocation.getMarshalledSize(); // _associatedLocation return marshalSize; } // Copyright (c) 1995-2009 held by the author(s). All rights reserved. // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the names of the Naval Postgraduate School (NPS) // Modeling Virtual Environments and Simulation (MOVES) Institute // (http://www.nps.edu and http://www.MovesInstitute.org) // nor the names of its contributors may be used to endorse or // promote products derived from this software without specific // prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // AS IS AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE // COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, // BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT // LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN // ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE.
29.485507
95
0.751536
AlphaPixel
8dabf0105cb9ff5a991c82a164d08e74c8c5fb2b
692
cpp
C++
Source/HacknSlash/Pickups/ShieldPickup.cpp
Andrew199617/HacknSlash
60fb4eb857223769db835f138734c7857b2e654f
[ "MIT" ]
null
null
null
Source/HacknSlash/Pickups/ShieldPickup.cpp
Andrew199617/HacknSlash
60fb4eb857223769db835f138734c7857b2e654f
[ "MIT" ]
null
null
null
Source/HacknSlash/Pickups/ShieldPickup.cpp
Andrew199617/HacknSlash
60fb4eb857223769db835f138734c7857b2e654f
[ "MIT" ]
null
null
null
// Fill out your copyright notice in the Description page of Project Settings. #include "HacknSlash.h" #include "ShieldPickup.h" #include "HacknSlashCharacter.h" AShieldPickup::AShieldPickup() : ABasePickup() { } void AShieldPickup::OnPickup(AActor* OtherActor) { if (OtherActor->GetName() == playerCharacter->GetName()) { playerCharacter->Recharge(shieldAmountInt); } } void AShieldPickup::BeginPlay() { Super::BeginPlay(); switch (shieldAmount) { case EShieldAmount::SMALL_SHIELD: shieldAmountInt = 33; break; case EShieldAmount::MEDIUM_SHIELD: shieldAmountInt = 66; break; case EShieldAmount::FULL_SHIELD: shieldAmountInt = 100; break; default: break; } }
17.74359
78
0.735549
Andrew199617
8daca50c6c76e3c3acc1da3de88c110360f269df
4,035
cc
C++
s2client-api/include/google/protobuf/drop_unknown_fields_test.cc
songchaow/starcrat2-ai
ac6fbdb0e3d7839a76addea4e6aa50a4545841f3
[ "MIT" ]
null
null
null
s2client-api/include/google/protobuf/drop_unknown_fields_test.cc
songchaow/starcrat2-ai
ac6fbdb0e3d7839a76addea4e6aa50a4545841f3
[ "MIT" ]
null
null
null
s2client-api/include/google/protobuf/drop_unknown_fields_test.cc
songchaow/starcrat2-ai
ac6fbdb0e3d7839a76addea4e6aa50a4545841f3
[ "MIT" ]
null
null
null
// Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // https://developers.google.com/protocol-buffers/ // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include <memory> #ifndef _SHARED_PTR_H #include <google/protobuf/stubs/shared_ptr.h> #endif #include <google/protobuf/unittest_drop_unknown_fields.pb.h> #include <google/protobuf/dynamic_message.h> #include <gtest/gtest.h> namespace google { using unittest_drop_unknown_fields::Foo; using unittest_drop_unknown_fields::FooWithExtraFields; namespace protobuf { TEST(DropUnknownFieldsTest, GeneratedMessage) { FooWithExtraFields foo_with_extra_fields; foo_with_extra_fields.set_int32_value(1); foo_with_extra_fields.set_enum_value(FooWithExtraFields::QUX); foo_with_extra_fields.set_extra_int32_value(2); Foo foo; ASSERT_TRUE(foo.ParseFromString(foo_with_extra_fields.SerializeAsString())); EXPECT_EQ(1, foo.int32_value()); EXPECT_EQ(static_cast<int>(FooWithExtraFields::QUX), static_cast<int>(foo.enum_value())); // We don't generate unknown field accessors but the UnknownFieldSet is // still exposed through reflection API. EXPECT_TRUE(foo.GetReflection()->GetUnknownFields(foo).empty()); ASSERT_TRUE(foo_with_extra_fields.ParseFromString(foo.SerializeAsString())); EXPECT_EQ(1, foo_with_extra_fields.int32_value()); EXPECT_EQ(FooWithExtraFields::QUX, foo_with_extra_fields.enum_value()); // The "extra_int32_value" field should be lost. EXPECT_EQ(0, foo_with_extra_fields.extra_int32_value()); } TEST(DropUnknownFieldsTest, DynamicMessage) { FooWithExtraFields foo_with_extra_fields; foo_with_extra_fields.set_int32_value(1); foo_with_extra_fields.set_enum_value(FooWithExtraFields::QUX); foo_with_extra_fields.set_extra_int32_value(2); google::protobuf::DynamicMessageFactory factory; google::protobuf::scoped_ptr<google::protobuf::Message> foo( factory.GetPrototype(Foo::descriptor())->New()); ASSERT_TRUE(foo->ParseFromString(foo_with_extra_fields.SerializeAsString())); EXPECT_TRUE(foo->GetReflection()->GetUnknownFields(*foo).empty()); ASSERT_TRUE(foo_with_extra_fields.ParseFromString(foo->SerializeAsString())); EXPECT_EQ(1, foo_with_extra_fields.int32_value()); EXPECT_EQ(FooWithExtraFields::QUX, foo_with_extra_fields.enum_value()); // The "extra_int32_value" field should be lost. EXPECT_EQ(0, foo_with_extra_fields.extra_int32_value()); } } // namespace protobuf } // namespace google
45.337079
80
0.768773
songchaow
8db32893d035f244666876f00e69d2dd79676d1d
1,075
cpp
C++
cpp/euler056/euler056.cpp
marvins/ProjectEuler
55a377bb9702067bac6908c1316c578498402668
[ "MIT" ]
null
null
null
cpp/euler056/euler056.cpp
marvins/ProjectEuler
55a377bb9702067bac6908c1316c578498402668
[ "MIT" ]
null
null
null
cpp/euler056/euler056.cpp
marvins/ProjectEuler
55a377bb9702067bac6908c1316c578498402668
[ "MIT" ]
1
2020-12-16T09:25:19.000Z
2020-12-16T09:25:19.000Z
/** * @file euler56.cpp * @author Marvin Smith * @date 9/25/2013 */ // C++ Standard Libraries #include <iostream> // Common Libraries #include "../common/BigIntegerLibrary.hh" #include "../common/StringUtilities.hpp" using namespace std; /** * @brief Main Function */ int main( int argc, char* argv[] ){ BigInteger maxVal = 0; // iterate through the a for( size_t a=2; a<100; a++ ){ // iterate through b for( size_t b=2; b<100; b++ ){ // compute power BigInteger value = power( a, b ); // convert to string string value_string = bigIntegerToString( value ); // compute the sum of digits BigInteger sum = 0; for( size_t i=0; i<value_string.size(); i++ ){ sum += str2num<int>(value_string.substr(i,1)); } // compare sum if( maxVal < sum ){ maxVal = sum; } } } cout << maxVal << endl; return 0; }
19.545455
62
0.492093
marvins
8db6be9a0dc545ff059d720b8b62046e02af7a01
897
cpp
C++
src/test/operators/get_table_test.cpp
tjjordan/DYOD_SoSe21
9cf7af43f10caccbfa2b0583a43e991f24cd336c
[ "MIT" ]
1
2022-01-25T09:03:56.000Z
2022-01-25T09:03:56.000Z
src/test/operators/get_table_test.cpp
tjjordan/DYOD_SoSe21
9cf7af43f10caccbfa2b0583a43e991f24cd336c
[ "MIT" ]
2
2022-02-10T14:25:25.000Z
2022-03-12T20:19:12.000Z
src/test/operators/get_table_test.cpp
tjjordan/DYOD_SoSe21
9cf7af43f10caccbfa2b0583a43e991f24cd336c
[ "MIT" ]
null
null
null
#include <memory> #include "../base_test.hpp" #include "gtest/gtest.h" #include "operators/get_table.hpp" #include "storage/storage_manager.hpp" #include "storage/table.hpp" namespace opossum { class OperatorsGetTableTest : public BaseTest { protected: void SetUp() override { _test_table = std::make_shared<Table>(2); StorageManager::get().add_table("aNiceTestTable", _test_table); } std::shared_ptr<Table> _test_table; }; TEST_F(OperatorsGetTableTest, GetOutput) { auto gt = std::make_shared<GetTable>("aNiceTestTable"); gt->execute(); EXPECT_EQ(gt->get_output(), _test_table); } TEST_F(OperatorsGetTableTest, ThrowsUnknownTableName) { auto gt = std::make_shared<GetTable>("anUglyTestTable"); EXPECT_EQ(gt->table_name(), "anUglyTestTable"); EXPECT_THROW(gt->execute(), std::exception) << "Should throw unknown table name exception"; } } // namespace opossum
24.916667
93
0.732441
tjjordan
8db87de279588d10f3ae944e10afa44db6d3f6f1
2,625
cpp
C++
src/sbbs3/ctrl/EventsFormUnit.cpp
jonny290/synchronet
012a39d00a3160a593ef5923fdc1ee95e0497083
[ "Artistic-2.0" ]
1
2017-07-18T03:56:48.000Z
2017-07-18T03:56:48.000Z
src/sbbs3/ctrl/EventsFormUnit.cpp
jonny290/synchronet
012a39d00a3160a593ef5923fdc1ee95e0497083
[ "Artistic-2.0" ]
null
null
null
src/sbbs3/ctrl/EventsFormUnit.cpp
jonny290/synchronet
012a39d00a3160a593ef5923fdc1ee95e0497083
[ "Artistic-2.0" ]
null
null
null
/* Synchronet Control Panel (GUI Borland C++ Builder Project for Win32) */ /* $Id: EventsFormUnit.cpp,v 1.2 2004/10/18 00:04:40 rswindell Exp $ */ /**************************************************************************** * @format.tab-size 4 (Plain Text/Source Code File Header) * * @format.use-tabs true (see http://www.synchro.net/ptsc_hdr.html) * * * * Copyright 2004 Rob Swindell - http://www.synchro.net/copyright.html * * * * 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. * * See the GNU General Public License for more details: gpl.txt or * * http://www.fsf.org/copyleft/gpl.html * * * * Anonymous FTP access to the most recent released source is available at * * ftp://vert.synchro.net, ftp://cvs.synchro.net and ftp://ftp.synchro.net * * * * Anonymous CVS access to the development source and modification history * * is available at cvs.synchro.net:/cvsroot/sbbs, example: * * cvs -d :pserver:anonymous@cvs.synchro.net:/cvsroot/sbbs login * * (just hit return, no password is necessary) * * cvs -d :pserver:anonymous@cvs.synchro.net:/cvsroot/sbbs checkout src * * * * For Synchronet coding style and modification guidelines, see * * http://www.synchro.net/source.html * * * * You are encouraged to submit any modifications (preferably in Unix diff * * format) via e-mail to mods@synchro.net * * * * Note: If this box doesn't appear square, then you need to fix your tabs. * ****************************************************************************/ //--------------------------------------------------------------------------- #include <vcl.h> #pragma hdrstop #include "MainFormUnit.h" #include "EventsFormUnit.h" //--------------------------------------------------------------------------- #pragma package(smart_init) #pragma resource "*.dfm" TEventsForm *EventsForm; //--------------------------------------------------------------------------- __fastcall TEventsForm::TEventsForm(TComponent* Owner) : TForm(Owner) { } //--------------------------------------------------------------------------- void __fastcall TEventsForm::FormHide(TObject *Sender) { MainForm->ViewEvents->Checked=false; } //---------------------------------------------------------------------------
46.052632
78
0.518095
jonny290
8dbc305219738ae46896074c59e25e356e9115c5
2,389
hpp
C++
include/mantella_bits/randomNumberGenerator.hpp
OpusV/AstroMechanics
3fe7a5462fce575c465be372d1c69bf788784297
[ "MIT" ]
1
2019-11-08T22:06:56.000Z
2019-11-08T22:06:56.000Z
include/mantella_bits/randomNumberGenerator.hpp
OpusV/AstroMechanics
3fe7a5462fce575c465be372d1c69bf788784297
[ "MIT" ]
null
null
null
include/mantella_bits/randomNumberGenerator.hpp
OpusV/AstroMechanics
3fe7a5462fce575c465be372d1c69bf788784297
[ "MIT" ]
null
null
null
#pragma once // C++ standard library #include <array> #include <random> #include <stdexcept> // Armadillo #include <armadillo> // Mantella #include "mantella_bits/config.hpp" // IWYU pragma: keep namespace mant { class Rng { public: // The random number generator should act as a singleton, no need for default constructors. Rng() = delete; Rng(const Rng&) = delete; Rng(Rng&&) = delete; Rng& operator=(const Rng&) = delete; Rng& operator=(Rng&&) = delete; // This must be implemented within the header as we want to be able to readjust `MAXIMAL_NUMBER_OF_THREADS` simply by predefining it prior to including Mantella the first time, without the need to recompile the library. // Therefore, everything that depends on `MAXIMAL_NUMBER_OF_THREADS` in any way needs to be header-only. static std::mt19937_64& getGenerator() { // **Note:** C++ guarantees under 7.1.2/4 that even if multiple threads attempt to initialize the same static local variable concurrently, the initialisation occurs exactly once. static std::array<std::mt19937_64, MAXIMAL_NUMBER_OF_THREADS> generators_; if (threadNumber() >= generators_.size()) { throw std::runtime_error("Rng.getGenerator: The thread number exceeded the maximal number of threads to support."); } return generators_.at(threadNumber()); } // This must be implemented within the header as we want to be able to readjust `MAXIMAL_NUMBER_OF_THREADS` simply by predefining it prior to including Mantella the first time, without the need to recompile the library. // Therefore, everything that depends on `MAXIMAL_NUMBER_OF_THREADS` in any way needs to be header-only. static void setSeed( const std::random_device::result_type seed) { // Since we use a local static variable to hold all generators - which is only accessible by calling `.getGenerator()` for each thread - we use OpenMP to iterate over `.getGenerator()` once per thread. #pragma omp parallel num_threads(MAXIMAL_NUMBER_OF_THREADS) { #pragma omp for schedule(static) for (arma::uword n = 0; n < MAXIMAL_NUMBER_OF_THREADS; ++n) { // Uses a different seed for each generator, deterministically based on the provided one. getGenerator().seed(seed + n); } } } static std::random_device::result_type setRandomSeed(); }; }
43.436364
223
0.713269
OpusV
8dbf4c0aea31fc985301727077d5ba6e359997b2
8,136
cxx
C++
vtkm/filter/testing/UnitTestCrossProductFilter.cxx
rushah05/VTKm_FP16
487819a1dbdd8dc3f95cca2942e3f2706a2514b5
[ "BSD-3-Clause" ]
2
2021-07-07T22:53:19.000Z
2021-07-31T19:29:35.000Z
vtkm/filter/testing/UnitTestCrossProductFilter.cxx
rushah05/VTKm_FP16
487819a1dbdd8dc3f95cca2942e3f2706a2514b5
[ "BSD-3-Clause" ]
2
2020-11-18T16:50:34.000Z
2022-01-21T13:31:47.000Z
vtkm/filter/testing/UnitTestCrossProductFilter.cxx
rushah05/VTKm_FP16
487819a1dbdd8dc3f95cca2942e3f2706a2514b5
[ "BSD-3-Clause" ]
5
2020-10-02T10:14:35.000Z
2022-03-10T07:50:22.000Z
//============================================================================ // Copyright (c) Kitware, Inc. // All rights reserved. // See LICENSE.txt for details. // // This software is distributed WITHOUT ANY WARRANTY; without even // the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR // PURPOSE. See the above copyright notice for more information. //============================================================================ #include <vtkm/cont/testing/MakeTestDataSet.h> #include <vtkm/cont/testing/Testing.h> #include <vtkm/filter/CrossProduct.h> #include <random> #include <vector> namespace { std::mt19937 randGenerator; template <typename T> void createVectors(std::size_t numPts, int vecType, std::vector<vtkm::Vec<T, 3>>& vecs1, std::vector<vtkm::Vec<T, 3>>& vecs2) { if (vecType == 0) // X x Y { vecs1.resize(numPts, vtkm::make_Vec(1, 0, 0)); vecs2.resize(numPts, vtkm::make_Vec(0, 1, 0)); } else if (vecType == 1) // Y x Z { vecs1.resize(numPts, vtkm::make_Vec(0, 1, 0)); vecs2.resize(numPts, vtkm::make_Vec(0, 0, 1)); } else if (vecType == 2) // Z x X { vecs1.resize(numPts, vtkm::make_Vec(0, 0, 1)); vecs2.resize(numPts, vtkm::make_Vec(1, 0, 0)); } else if (vecType == 3) // Y x X { vecs1.resize(numPts, vtkm::make_Vec(0, 1, 0)); vecs2.resize(numPts, vtkm::make_Vec(1, 0, 0)); } else if (vecType == 4) // Z x Y { vecs1.resize(numPts, vtkm::make_Vec(0, 0, 1)); vecs2.resize(numPts, vtkm::make_Vec(0, 1, 0)); } else if (vecType == 5) // X x Z { vecs1.resize(numPts, vtkm::make_Vec(1, 0, 0)); vecs2.resize(numPts, vtkm::make_Vec(0, 0, 1)); } else if (vecType == 6) { //Test some other vector combinations std::uniform_real_distribution<vtkm::Float64> randomDist(-10.0, 10.0); vecs1.resize(numPts); vecs2.resize(numPts); for (std::size_t i = 0; i < numPts; i++) { vecs1[i] = vtkm::make_Vec( randomDist(randGenerator), randomDist(randGenerator), randomDist(randGenerator)); vecs2[i] = vtkm::make_Vec( randomDist(randGenerator), randomDist(randGenerator), randomDist(randGenerator)); } } } void CheckResult(const vtkm::cont::ArrayHandle<vtkm::Vec3f>& field1, const vtkm::cont::ArrayHandle<vtkm::Vec3f>& field2, const vtkm::cont::DataSet& result) { VTKM_TEST_ASSERT(result.HasPointField("crossproduct"), "Output field is missing."); vtkm::cont::ArrayHandle<vtkm::Vec3f> outputArray; result.GetPointField("crossproduct").GetData().CopyTo(outputArray); auto v1Portal = field1.ReadPortal(); auto v2Portal = field2.ReadPortal(); auto outPortal = outputArray.ReadPortal(); VTKM_TEST_ASSERT(outputArray.GetNumberOfValues() == field1.GetNumberOfValues(), "Field sizes wrong"); VTKM_TEST_ASSERT(outputArray.GetNumberOfValues() == field2.GetNumberOfValues(), "Field sizes wrong"); for (vtkm::Id j = 0; j < outputArray.GetNumberOfValues(); j++) { vtkm::Vec3f v1 = v1Portal.Get(j); vtkm::Vec3f v2 = v2Portal.Get(j); vtkm::Vec3f res = outPortal.Get(j); //Make sure result is orthogonal each input vector. Need to normalize to compare with zero. vtkm::Vec3f v1N(vtkm::Normal(v1)), v2N(vtkm::Normal(v1)), resN(vtkm::Normal(res)); VTKM_TEST_ASSERT(test_equal(vtkm::Dot(resN, v1N), vtkm::FloatDefault(0.0)), "Wrong result for cross product"); VTKM_TEST_ASSERT(test_equal(vtkm::Dot(resN, v2N), vtkm::FloatDefault(0.0)), "Wrong result for cross product"); vtkm::FloatDefault sinAngle = vtkm::Magnitude(res) * vtkm::RMagnitude(v1) * vtkm::RMagnitude(v2); vtkm::FloatDefault cosAngle = vtkm::Dot(v1, v2) * vtkm::RMagnitude(v1) * vtkm::RMagnitude(v2); VTKM_TEST_ASSERT(test_equal(sinAngle * sinAngle + cosAngle * cosAngle, vtkm::FloatDefault(1.0)), "Bad cross product length."); } } void TestCrossProduct() { std::cout << "Testing CrossProduct Filter" << std::endl; vtkm::cont::testing::MakeTestDataSet testDataSet; const int numCases = 7; for (int i = 0; i < numCases; i++) { std::cout << "Case " << i << std::endl; vtkm::cont::DataSet dataSet = testDataSet.Make3DUniformDataSet0(); vtkm::Id nVerts = dataSet.GetCoordinateSystem(0).GetNumberOfPoints(); std::vector<vtkm::Vec3f> vecs1, vecs2; createVectors(static_cast<std::size_t>(nVerts), i, vecs1, vecs2); vtkm::cont::ArrayHandle<vtkm::Vec3f> field1, field2; field1 = vtkm::cont::make_ArrayHandle(vecs1, vtkm::CopyFlag::On); field2 = vtkm::cont::make_ArrayHandle(vecs2, vtkm::CopyFlag::On); dataSet.AddPointField("vec1", field1); dataSet.AddPointField("vec2", field2); dataSet.AddCoordinateSystem(vtkm::cont::CoordinateSystem("vecA", field1)); dataSet.AddCoordinateSystem(vtkm::cont::CoordinateSystem("vecB", field2)); { std::cout << " Both vectors as normal fields" << std::endl; vtkm::filter::CrossProduct filter; filter.SetPrimaryField("vec1"); filter.SetSecondaryField("vec2", vtkm::cont::Field::Association::POINTS); // Check to make sure the fields are reported as correct. VTKM_TEST_ASSERT(filter.GetPrimaryFieldName() == "vec1", "Bad field name."); VTKM_TEST_ASSERT(filter.GetPrimaryFieldAssociation() == vtkm::cont::Field::Association::ANY, "Bad field association."); VTKM_TEST_ASSERT(filter.GetUseCoordinateSystemAsPrimaryField() == false, "Bad use coordinates."); VTKM_TEST_ASSERT(filter.GetSecondaryFieldName() == "vec2", "Bad field name."); VTKM_TEST_ASSERT(filter.GetSecondaryFieldAssociation() == vtkm::cont::Field::Association::POINTS, "Bad field association."); VTKM_TEST_ASSERT(filter.GetUseCoordinateSystemAsSecondaryField() == false, "Bad use coordinates."); vtkm::cont::DataSet result = filter.Execute(dataSet); CheckResult(field1, field2, result); } { std::cout << " First field as coordinates" << std::endl; vtkm::filter::CrossProduct filter; filter.SetUseCoordinateSystemAsPrimaryField(true); filter.SetPrimaryCoordinateSystem(1); filter.SetSecondaryField("vec2"); // Check to make sure the fields are reported as correct. VTKM_TEST_ASSERT(filter.GetUseCoordinateSystemAsPrimaryField() == true, "Bad use coordinates."); VTKM_TEST_ASSERT(filter.GetSecondaryFieldName() == "vec2", "Bad field name."); VTKM_TEST_ASSERT(filter.GetSecondaryFieldAssociation() == vtkm::cont::Field::Association::ANY, "Bad field association."); VTKM_TEST_ASSERT(filter.GetUseCoordinateSystemAsSecondaryField() == false, "Bad use coordinates."); vtkm::cont::DataSet result = filter.Execute(dataSet); CheckResult(field1, field2, result); } { std::cout << " Second field as coordinates" << std::endl; vtkm::filter::CrossProduct filter; filter.SetPrimaryField("vec1"); filter.SetUseCoordinateSystemAsSecondaryField(true); filter.SetSecondaryCoordinateSystem(2); // Check to make sure the fields are reported as correct. VTKM_TEST_ASSERT(filter.GetPrimaryFieldName() == "vec1", "Bad field name."); VTKM_TEST_ASSERT(filter.GetPrimaryFieldAssociation() == vtkm::cont::Field::Association::ANY, "Bad field association."); VTKM_TEST_ASSERT(filter.GetUseCoordinateSystemAsPrimaryField() == false, "Bad use coordinates."); VTKM_TEST_ASSERT(filter.GetUseCoordinateSystemAsSecondaryField() == true, "Bad use coordinates."); vtkm::cont::DataSet result = filter.Execute(dataSet); CheckResult(field1, field2, result); } } } } // anonymous namespace int UnitTestCrossProductFilter(int argc, char* argv[]) { return vtkm::cont::testing::Testing::Run(TestCrossProduct, argc, argv); }
38.197183
100
0.637537
rushah05
8dc5ee3062d82ad1f8e16a20c86f0f895e72e21f
423
hh
C++
mcg/src/external/BSR/include/config/safety.hh
mouthwater/rgb
3fafca24ecc133910923182581a2133b8568bf77
[ "BSD-2-Clause" ]
392
2015-01-14T13:19:40.000Z
2022-02-12T08:47:33.000Z
mcg/src/external/BSR/include/config/safety.hh
mouthwater/rgb
3fafca24ecc133910923182581a2133b8568bf77
[ "BSD-2-Clause" ]
45
2015-02-03T12:16:10.000Z
2022-03-07T00:25:09.000Z
mcg/src/external/BSR/include/config/safety.hh
mouthwater/rgb
3fafca24ecc133910923182581a2133b8568bf77
[ "BSD-2-Clause" ]
168
2015-01-05T02:29:53.000Z
2022-02-22T04:32:04.000Z
/* * Safety settings. */ #ifndef CONFIG__SAFETY_HH #define CONFIG__SAFETY_HH /* * Check smart pointer dereference? * If true, smart pointers should throw exceptions on null dereference. */ #define CONFIG__SAFETY__CHECK_DEREFERENCE (true) /* * Check bounds when accessing arrays? * If true, arrays should throw exceptions on access to an out of bounds index. */ #define CONFIG__SAFETY__CHECK_BOUNDS (true) #endif
21.15
79
0.761229
mouthwater
44ef487204d7a342be74d274dfdae403dacc75ce
3,596
hpp
C++
src/packet.hpp
GabrielLins64/custom-eoserv
4a08a4ff9dbdf6e5101eebd41573c0f2b6b412cf
[ "Zlib" ]
2
2021-12-10T17:17:45.000Z
2021-12-10T18:07:21.000Z
src/packet.hpp
GabrielLins64/custom-eoserv
4a08a4ff9dbdf6e5101eebd41573c0f2b6b412cf
[ "Zlib" ]
null
null
null
src/packet.hpp
GabrielLins64/custom-eoserv
4a08a4ff9dbdf6e5101eebd41573c0f2b6b412cf
[ "Zlib" ]
null
null
null
/* $Id: packet.hpp 490 2015-11-18 10:46:34Z sausage $ * EOSERV is released under the zlib license. * See LICENSE.txt for more info. */ #ifndef PACKET_HPP_INCLUDED #define PACKET_HPP_INCLUDED #include "fwd/packet.hpp" #include <array> #include <cstddef> #include <string> /** * Encodes and Decodes packets for a Client. * Each Client needs an instance of this because it holds connection-specific data required to function correctly. */ class PacketProcessor { protected: /** * "EMulti" variable for Encoding. */ unsigned char emulti_e; /** * "EMulti" variable for Decoding. */ unsigned char emulti_d; public: /** * Highest number EO can represent with 1 byte. */ static const unsigned int MAX1 = 253; /** * Highest number EO can represent with 2 bytes. */ static const unsigned int MAX2 = 64009; /** * Highest number EO can represent with 3 bytes. */ static const unsigned int MAX3 = 16194277; PacketProcessor(); /** * Return a string describing a packet's family ID. */ static std::string GetFamilyName(PacketFamily family); /** * Return a string describing a packet's action ID. */ static std::string GetActionName(PacketAction action); std::string Decode(const std::string &); std::string Encode(const std::string &); static std::string DickWinder(const std::string &, unsigned char emulti); std::string DickWinderE(const std::string &); std::string DickWinderD(const std::string &); void SetEMulti(unsigned char, unsigned char); static unsigned int Number(unsigned char, unsigned char = 254, unsigned char = 254, unsigned char = 254); static std::array<unsigned char, 4> ENumber(unsigned int); static std::array<unsigned char, 4> ENumber(unsigned int, std::size_t &size); static unsigned short PID(PacketFamily family, PacketAction action); static std::array<unsigned char, 2> EPID(unsigned short id); }; class PacketReader { protected: std::string data; std::size_t pos; public: PacketReader(const std::string &); std::size_t Length() const; std::size_t Remaining() const; PacketAction Action() const; PacketFamily Family() const; unsigned int GetNumber(std::size_t length); unsigned char GetByte(); unsigned char GetChar(); unsigned short GetShort(); unsigned int GetThree(); unsigned int GetInt(); std::string GetFixedString(std::size_t length); std::string GetBreakString(unsigned char breakchar = 0xFF); std::string GetEndString(); ~PacketReader(); }; class PacketBuilder { protected: unsigned short id; std::string data; std::size_t add_size; public: PacketBuilder(PacketFamily family = PACKET_F_INIT, PacketAction action = PACKET_A_INIT, std::size_t size_guess = 0); unsigned short SetID(unsigned short id); unsigned short SetID(PacketFamily family, PacketAction action); unsigned short GetID() const; std::size_t Length() const; std::size_t Capacity() const; void ReserveMore(std::size_t size_guess); PacketBuilder &AddByte(unsigned char); PacketBuilder &AddChar(unsigned char); PacketBuilder &AddShort(unsigned short); PacketBuilder &AddThree(unsigned int); PacketBuilder &AddInt(unsigned int); PacketBuilder &AddVar(int min, int max, unsigned int); PacketBuilder &AddString(const std::string &); PacketBuilder &AddBreakString(const std::string &, unsigned char breakchar = 0xFF); void AddSize(std::size_t size); void Reset(std::size_t size_guess = 0); std::string Get() const; operator std::string() const; ~PacketBuilder(); }; #endif // PACKET_HPP_INCLUDED
24.134228
118
0.713293
GabrielLins64
44f24f550807a79dda122e1e569313ecc57bb54b
1,280
hpp
C++
include/UnityEngine/RemoteConfigSettingsHelper.hpp
RedBrumbler/virtuoso-codegen
e83f6f0f9b47bec4b6dd976b21edc1d46bf3cfe3
[ "Unlicense" ]
null
null
null
include/UnityEngine/RemoteConfigSettingsHelper.hpp
RedBrumbler/virtuoso-codegen
e83f6f0f9b47bec4b6dd976b21edc1d46bf3cfe3
[ "Unlicense" ]
null
null
null
include/UnityEngine/RemoteConfigSettingsHelper.hpp
RedBrumbler/virtuoso-codegen
e83f6f0f9b47bec4b6dd976b21edc1d46bf3cfe3
[ "Unlicense" ]
1
2022-03-30T21:07:35.000Z
2022-03-30T21:07:35.000Z
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once // Begin includes #include "beatsaber-hook/shared/utils/typedefs.h" #include "beatsaber-hook/shared/utils/byref.hpp" // Completed includes // Begin forward declares // Forward declaring namespace: UnityEngine namespace UnityEngine { } // Completed forward declares // Type namespace: UnityEngine namespace UnityEngine { // Forward declaring type: RemoteConfigSettingsHelper class RemoteConfigSettingsHelper; } #include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp" NEED_NO_BOX(::UnityEngine::RemoteConfigSettingsHelper); DEFINE_IL2CPP_ARG_TYPE(::UnityEngine::RemoteConfigSettingsHelper*, "UnityEngine", "RemoteConfigSettingsHelper"); // Type namespace: UnityEngine namespace UnityEngine { // Size: 0x10 #pragma pack(push, 1) // Autogenerated type: UnityEngine.RemoteConfigSettingsHelper // [TokenAttribute] Offset: FFFFFFFF class RemoteConfigSettingsHelper : public ::Il2CppObject { public: // Nested type: ::UnityEngine::RemoteConfigSettingsHelper::Tag struct Tag; }; // UnityEngine.RemoteConfigSettingsHelper #pragma pack(pop) } #include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
35.555556
112
0.738281
RedBrumbler
44f39bcaed853494ae339afad053d71b936533f8
727
cpp
C++
test/openexr/bind/imf_imagechannel.cpp
luke-titley/cppmm
3c0dbc5539ab33706e63d4a518f85cb6a9a54ed7
[ "OLDAP-2.5", "OLDAP-2.3" ]
37
2020-11-03T19:51:36.000Z
2022-02-08T06:09:51.000Z
test/openexr/bind/imf_imagechannel.cpp
luke-titley/cppmm
3c0dbc5539ab33706e63d4a518f85cb6a9a54ed7
[ "OLDAP-2.5", "OLDAP-2.3" ]
61
2020-11-06T16:59:25.000Z
2021-09-08T20:48:47.000Z
test/openexr/bind/imf_imagechannel.cpp
luke-titley/cppmm
3c0dbc5539ab33706e63d4a518f85cb6a9a54ed7
[ "OLDAP-2.5", "OLDAP-2.3" ]
7
2020-11-05T04:53:22.000Z
2021-09-03T23:32:21.000Z
#include <OpenEXR/ImfImageChannel.h> #include <cppmm_bind.hpp> namespace cppmm_bind { namespace OPENEXR_IMF_INTERNAL_NAMESPACE { namespace Imf = ::OPENEXR_IMF_INTERNAL_NAMESPACE; struct ImageChannel { using BoundType = Imf::ImageChannel; // Inherited from ImageChannel virtual Imf::PixelType pixelType() const = 0; IMFUTIL_EXPORT Imf::Channel channel() const; int xSampling() const; int ySampling() const; bool pLinear() const; int pixelsPerRow() const; int pixelsPerColumn() const; size_t numPixels() const; Imf::ImageLevel& level(); const Imf::ImageLevel& level() const; } CPPMM_OPAQUEBYTES; } // namespace OPENEXR_IMF_INTERNAL_NAMESPACE } // namespace cppmm_bind
22.71875
49
0.723521
luke-titley
44fdc11aa287ae0c46ec9ab923a9ff8bd6695f92
183
cpp
C++
src/homework/01_variables/variables.cpp
acc-cosc-1337-spring-2022/acc-cosc-1337-spring-2022-veysto2
c09be3d82d5984a7c2ae89e46047cf475c423245
[ "MIT" ]
null
null
null
src/homework/01_variables/variables.cpp
acc-cosc-1337-spring-2022/acc-cosc-1337-spring-2022-veysto2
c09be3d82d5984a7c2ae89e46047cf475c423245
[ "MIT" ]
null
null
null
src/homework/01_variables/variables.cpp
acc-cosc-1337-spring-2022/acc-cosc-1337-spring-2022-veysto2
c09be3d82d5984a7c2ae89e46047cf475c423245
[ "MIT" ]
null
null
null
#include "variables.h" //example int add_numbers(int num1, int num2) { return num1 + num2; } // multiply int multiply_numbers(int num1) { int num2 = 5; return num1 * num2; }
9.631579
35
0.666667
acc-cosc-1337-spring-2022
44fe6e0e26a8d9ceb5c8c422b4406897d874f620
901
hh
C++
estp/base/at.hh
dpalchak/estoppel
921e29865a9a558ea70a2329f16428a96935a90b
[ "MIT" ]
2
2018-07-23T17:40:47.000Z
2018-08-03T20:06:40.000Z
estp/base/at.hh
dpalchak/estoppel
921e29865a9a558ea70a2329f16428a96935a90b
[ "MIT" ]
null
null
null
estp/base/at.hh
dpalchak/estoppel
921e29865a9a558ea70a2329f16428a96935a90b
[ "MIT" ]
null
null
null
#pragma once #include "estp/base/assert.hh" #include "estp/base/casting.hh" #include "estp/base/types.hh" #include <array> // Basic implementation of the at() function as described in the C++ GSL namespace estp { template<typename T, Index N> constexpr decltype(auto) at(T (&arr)[N], Index index) { EXPECTS(0 <= index && index < N); return arr[index]; } template<typename T, std::size_t N> constexpr decltype(auto) at(std::array<T, N> &arr, Index index) { EXPECTS(0 <= index && index < narrow_cast<Index>(N)); return arr[index]; } template<typename Container> constexpr decltype(auto) at(Container &c, Index index) { EXPECTS(0 <= index && index < narrow_cast<Index>(c.size())); return c[index]; } template<typename T> constexpr decltype(auto) at(std::initializer_list<T> c, Index index) { EXPECTS(0 < = index && index < narrow_cast<Index>(c.size())); return *(c.begin() + index); } }
23.710526
72
0.688124
dpalchak
7802db912c3fd545e1dd2173b98764eb844bda63
6,891
cpp
C++
src/bin/obsidian.cpp
divad-nhok/obsidian_fork
e5bee2b706f78249564f06c88a18be086b17c895
[ "MIT" ]
2
2021-03-08T16:28:45.000Z
2022-03-04T14:55:59.000Z
src/bin/obsidian.cpp
divad-nhok/obsidian_fork
e5bee2b706f78249564f06c88a18be086b17c895
[ "MIT" ]
1
2018-08-16T00:46:58.000Z
2018-08-16T00:46:58.000Z
src/bin/obsidian.cpp
divad-nhok/obsidian_fork
e5bee2b706f78249564f06c88a18be086b17c895
[ "MIT" ]
2
2018-02-26T01:03:13.000Z
2021-02-01T02:31:37.000Z
//! //! A delegator that runs parallel tempering on several workers to perform an inversion. //! //! \file obsidian.cpp //! \author Lachlan McCalman //! \author Darren Shen //! \author Nahid Akbar //! \date February, 2014 //! \license Affero General Public License version 3 or later //! \copyright (c) 2014, NICTA //! // Standard Library #include <random> #include <thread> #include <chrono> #include <numeric> #include <iostream> // Prerequisites #include <glog/logging.h> #include <boost/program_options.hpp> // Project #include "app/console.hpp" #include "app/settings.hpp" #include "input/input.hpp" #include "comms/delegator.hpp" #include "comms/requester.hpp" #include "serial/serial.hpp" #include "app/asyncdelegator.hpp" #include "app/signal.hpp" #include "infer/mcmc.hpp" #include "infer/metropolis.hpp" #include "infer/adaptive.hpp" #include "fwdmodel/fwd.hpp" #include "datatype/sensors.hpp" #include "detail.hpp" #include "distrib/multigaussian.hpp" #include "prior/world.hpp" using namespace obsidian; using namespace stateline; namespace ph = std::placeholders; // Command line options specific to obsidian po::options_description commandLineOptions() { po::options_description cmdLine("Delegator Command Line Options"); cmdLine.add_options() // ("port,p", po::value<uint>()->default_value(5555), "TCP port to accept connections") // ("configfile,c", po::value<std::string>()->default_value("obsidian_config"), "configuration file") // ("inputfile,i", po::value<std::string>()->default_value("input.obsidian"), "input file") // ("recover,r", po::bool_switch()->default_value(false), "force recovery") ("anneallength,a", po::value<uint>()->default_value(1000), "anneal chains with n samples before starting mcmc"); return cmdLine; } int main(int ac, char* av[]) { init::initialiseSignalHandler(); // Get the settings from the command line auto vm = init::initProgramOptions(ac, av, commandLineOptions()); // Set up a random generator here std::random_device rd; std::mt19937 gen(rd()); LOG(INFO)<< "Initialise the various settings and objects"; readConfigFile(vm["configfile"].as<std::string>(), vm); readInputFile(vm["inputfile"].as<std::string>(), vm); std::set<ForwardModel> sensorsEnabled = parseSensorsEnabled(vm); DelegatorSettings delegatorSettings = parseDelegatorSettings(vm); MCMCSettings mcmcSettings = parseMCMCSettings(vm); DBSettings dbSettings = parseDBSettings(vm); dbSettings.recover = vm["recover"].as<bool>(); WorldSpec worldSpec = parseSpec<WorldSpec>(vm, sensorsEnabled); GlobalPrior prior = parsePrior<GlobalPrior>(vm, sensorsEnabled); GlobalResults results = loadResults(worldSpec, vm, sensorsEnabled); LOG(INFO)<< "Create the specification data (serialised) for all the jobs"; std::string worldSpecData = obsidian::comms::serialise(worldSpec); std::vector<uint> sensorId; std::vector<std::string> sensorSpecData; std::vector<std::string> sensorReadings; applyToSensorsEnabled<getData>(sensorsEnabled, std::ref(sensorId), std::ref(sensorSpecData), std::ref(sensorReadings), std::cref(worldSpec), std::ref(results), std::cref(vm), std::cref(sensorsEnabled)); LOG(INFO)<< "Initialise comms"; stateline::comms::Delegator delegator(worldSpecData, sensorId, sensorSpecData, sensorReadings, delegatorSettings); delegator.start(); LOG(INFO)<< "Initialise parallel tempering mcmc"; GeoAsyncPolicy policy(delegator, prior, sensorsEnabled); // Start the sampling LOG(INFO)<< "Starting inversion: Run for " << mcmcSettings.wallTime << " seconds"; LOG(INFO)<< "Problem dimensionality: " << prior.size(); mcmc::Sampler mcmc(mcmcSettings, dbSettings, prior.size(), global::interruptedBySignal); std::vector<Eigen::VectorXd> initialThetas; LOG(INFO)<< "Loading / generating initial thetas for the chains"; for (uint s = 0; s < mcmcSettings.stacks; s++) { for (uint c = 0; c < mcmcSettings.chains; c++) { if (dbSettings.recover && !mcmc.chains().states(s * mcmcSettings.chains + c).empty()) { initialThetas.push_back(mcmc.chains().states(s * mcmcSettings.chains + c)[0].sample); } else { uint nSamples = vm["anneallength"].as<uint>(); std::vector<Eigen::VectorXd> thetas(nSamples); double lowestEnergy = std::numeric_limits<double>::max(); uint bestIndex = 0; for ( uint i=0; i<nSamples; i++) { Eigen::VectorXd cand = prior.sample(gen); thetas[i] = cand; policy.submit(i,cand); } for (uint i=0; i<nSamples; i++) { auto result = policy.retrieve(); uint id = result.first; double energy = result.second; if (energy < lowestEnergy) { bestIndex = id; lowestEnergy = energy; LOG(INFO) << "stack "<< s << " chain " << c << " best energy: " << lowestEnergy; } } initialThetas.push_back(thetas[bestIndex]); } } } LOG(INFO) << "initial samples generated"; if (mcmcSettings.distribution.compare("Normal") == 0) { LOG(INFO) << "normal proposal"; // RS 2018/08/23: Normal proposal is symmetric, so save some CPU // double (*pFn)(const Eigen::VectorXd&, const double, // const Eigen::VectorXd&, const Eigen::VectorXd&) = &mcmc::gaussianProposalPDF; // auto proposalPDF = std::bind( // pFn, // ph::_1, ph::_2, // prior.world.thetaMinBound(), prior.world.thetaMaxBound() // ); auto proposalPDF = [=](const Eigen::VectorXd& theta, const double sigma){return 1.0;}; auto proposal = std::bind( &mcmc::adaptiveGaussianProposal, ph::_1, ph::_2, ph::_3, prior.world.thetaMinBound(), prior.world.thetaMaxBound() ); mcmc.run(policy, initialThetas, proposal, proposalPDF, mcmcSettings.wallTime); } else if (mcmcSettings.distribution.compare("CrankNicolson") == 0) { LOG(INFO) << "crank nicolson proposal"; auto proposalPDF = [=](const Eigen::VectorXd& theta, const double sigma){return prior.evaluate(theta);}; auto proposal = std::bind( &mcmc::crankNicolsonProposal, ph::_1, ph::_2, ph::_3, prior ); mcmc.run(policy, initialThetas, proposal, proposalPDF, mcmcSettings.wallTime); } else if (mcmcSettings.distribution.compare("AdaptiveMulti") == 0) { LOG(INFO) << "adaptive multigaussian proposal"; // RS 2018/08/23: AdaptiveMulti proposal is symmetric, so save some CPU auto proposalPDF = [=](const Eigen::VectorXd& theta, const double sigma){return 1.0;}; auto proposal = std::bind( &mcmc::multiGaussianProposal, ph::_1, ph::_2, ph::_3 ); mcmc.run(policy, initialThetas, proposal, proposalPDF, mcmcSettings.wallTime); } else { LOG(INFO) << "no valid proposal string selected"; } // This will gracefully stop all delegators internal threads delegator.stop(); return 0; }
37.248649
120
0.679147
divad-nhok
780a910e89883b7a7bc3812ae710f25f15a681fe
64,448
cc
C++
third/libyuv/source/row_any.cc
onbings/bofstd
366ff7f7d8871d5fa5785d5690d90506a7714ecc
[ "MIT" ]
null
null
null
third/libyuv/source/row_any.cc
onbings/bofstd
366ff7f7d8871d5fa5785d5690d90506a7714ecc
[ "MIT" ]
1
2021-03-20T14:46:54.000Z
2021-03-20T14:47:10.000Z
third/libyuv/source/row_any.cc
onbings/bofstd
366ff7f7d8871d5fa5785d5690d90506a7714ecc
[ "MIT" ]
null
null
null
/* * Copyright 2012 The LibYuv Project Authors. All rights reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "libyuv/row.h" #include <string.h> // For memset. #include "libyuv/basic_types.h" #ifdef __cplusplus namespace libyuv { extern "C" { #endif // memset for temp is meant to clear the source buffer (not dest) so that // SIMD that reads full multiple of 16 bytes will not trigger msan errors. // memset is not needed for production, as the garbage values are processed but // not used, although there may be edge cases for subsampling. // The size of the buffer is based on the largest read, which can be inferred // by the source type (e.g. ARGB) and the mask (last parameter), or by examining // the source code for how much the source pointers are advanced. // Subsampled source needs to be increase by 1 of not even. #define SS(width, shift) (((width) + (1 << (shift)) - 1) >> (shift)) // Any 4 planes to 1 with yuvconstants #define ANY41C(NAMEANY, ANY_SIMD, UVSHIFT, DUVSHIFT, BPP, MASK) \ void NAMEANY(const uint8_t* y_buf, const uint8_t* u_buf, \ const uint8_t* v_buf, const uint8_t* a_buf, uint8_t* dst_ptr, \ const struct YuvConstants* yuvconstants, int width) { \ SIMD_ALIGNED(uint8_t temp[64 * 5]); \ memset(temp, 0, 64 * 4); /* for msan */ \ int r = width & MASK; \ int n = width & ~MASK; \ if (n > 0) { \ ANY_SIMD(y_buf, u_buf, v_buf, a_buf, dst_ptr, yuvconstants, n); \ } \ memcpy(temp, y_buf + n, r); \ memcpy(temp + 64, u_buf + (n >> UVSHIFT), SS(r, UVSHIFT)); \ memcpy(temp + 128, v_buf + (n >> UVSHIFT), SS(r, UVSHIFT)); \ memcpy(temp + 192, a_buf + n, r); \ ANY_SIMD(temp, temp + 64, temp + 128, temp + 192, temp + 256, \ yuvconstants, MASK + 1); \ memcpy(dst_ptr + (n >> DUVSHIFT) * BPP, temp + 256, \ SS(r, DUVSHIFT) * BPP); \ } #ifdef HAS_I422ALPHATOARGBROW_SSSE3 ANY41C(I422AlphaToARGBRow_Any_SSSE3, I422AlphaToARGBRow_SSSE3, 1, 0, 4, 7) #endif #ifdef HAS_I422ALPHATOARGBROW_AVX2 ANY41C(I422AlphaToARGBRow_Any_AVX2, I422AlphaToARGBRow_AVX2, 1, 0, 4, 15) #endif #ifdef HAS_I422ALPHATOARGBROW_NEON ANY41C(I422AlphaToARGBRow_Any_NEON, I422AlphaToARGBRow_NEON, 1, 0, 4, 7) #endif #ifdef HAS_I422ALPHATOARGBROW_MSA ANY41C(I422AlphaToARGBRow_Any_MSA, I422AlphaToARGBRow_MSA, 1, 0, 4, 7) #endif #ifdef HAS_I422ALPHATOARGBROW_MMI ANY41C(I422AlphaToARGBRow_Any_MMI, I422AlphaToARGBRow_MMI, 1, 0, 4, 7) #endif #undef ANY41C // Any 3 planes to 1. #define ANY31(NAMEANY, ANY_SIMD, UVSHIFT, DUVSHIFT, BPP, MASK) \ void NAMEANY(const uint8_t* y_buf, const uint8_t* u_buf, \ const uint8_t* v_buf, uint8_t* dst_ptr, int width) { \ SIMD_ALIGNED(uint8_t temp[64 * 4]); \ memset(temp, 0, 64 * 3); /* for YUY2 and msan */ \ int r = width & MASK; \ int n = width & ~MASK; \ if (n > 0) { \ ANY_SIMD(y_buf, u_buf, v_buf, dst_ptr, n); \ } \ memcpy(temp, y_buf + n, r); \ memcpy(temp + 64, u_buf + (n >> UVSHIFT), SS(r, UVSHIFT)); \ memcpy(temp + 128, v_buf + (n >> UVSHIFT), SS(r, UVSHIFT)); \ ANY_SIMD(temp, temp + 64, temp + 128, temp + 192, MASK + 1); \ memcpy(dst_ptr + (n >> DUVSHIFT) * BPP, temp + 192, \ SS(r, DUVSHIFT) * BPP); \ } // Merge functions. #ifdef HAS_MERGERGBROW_SSSE3 ANY31(MergeRGBRow_Any_SSSE3, MergeRGBRow_SSSE3, 0, 0, 3, 15) #endif #ifdef HAS_MERGERGBROW_NEON ANY31(MergeRGBRow_Any_NEON, MergeRGBRow_NEON, 0, 0, 3, 15) #endif #ifdef HAS_MERGERGBROW_MMI ANY31(MergeRGBRow_Any_MMI, MergeRGBRow_MMI, 0, 0, 3, 7) #endif #ifdef HAS_I422TOYUY2ROW_SSE2 ANY31(I422ToYUY2Row_Any_SSE2, I422ToYUY2Row_SSE2, 1, 1, 4, 15) ANY31(I422ToUYVYRow_Any_SSE2, I422ToUYVYRow_SSE2, 1, 1, 4, 15) #endif #ifdef HAS_I422TOYUY2ROW_AVX2 ANY31(I422ToYUY2Row_Any_AVX2, I422ToYUY2Row_AVX2, 1, 1, 4, 31) ANY31(I422ToUYVYRow_Any_AVX2, I422ToUYVYRow_AVX2, 1, 1, 4, 31) #endif #ifdef HAS_I422TOYUY2ROW_NEON ANY31(I422ToYUY2Row_Any_NEON, I422ToYUY2Row_NEON, 1, 1, 4, 15) #endif #ifdef HAS_I422TOYUY2ROW_MSA ANY31(I422ToYUY2Row_Any_MSA, I422ToYUY2Row_MSA, 1, 1, 4, 31) #endif #ifdef HAS_I422TOYUY2ROW_MMI ANY31(I422ToYUY2Row_Any_MMI, I422ToYUY2Row_MMI, 1, 1, 4, 7) #endif #ifdef HAS_I422TOUYVYROW_NEON ANY31(I422ToUYVYRow_Any_NEON, I422ToUYVYRow_NEON, 1, 1, 4, 15) #endif #ifdef HAS_I422TOUYVYROW_MSA ANY31(I422ToUYVYRow_Any_MSA, I422ToUYVYRow_MSA, 1, 1, 4, 31) #endif #ifdef HAS_I422TOUYVYROW_MMI ANY31(I422ToUYVYRow_Any_MMI, I422ToUYVYRow_MMI, 1, 1, 4, 7) #endif #ifdef HAS_BLENDPLANEROW_AVX2 ANY31(BlendPlaneRow_Any_AVX2, BlendPlaneRow_AVX2, 0, 0, 1, 31) #endif #ifdef HAS_BLENDPLANEROW_SSSE3 ANY31(BlendPlaneRow_Any_SSSE3, BlendPlaneRow_SSSE3, 0, 0, 1, 7) #endif #ifdef HAS_BLENDPLANEROW_MMI ANY31(BlendPlaneRow_Any_MMI, BlendPlaneRow_MMI, 0, 0, 1, 7) #endif #undef ANY31 // Note that odd width replication includes 444 due to implementation // on arm that subsamples 444 to 422 internally. // Any 3 planes to 1 with yuvconstants #define ANY31C(NAMEANY, ANY_SIMD, UVSHIFT, DUVSHIFT, BPP, MASK) \ void NAMEANY(const uint8_t* y_buf, const uint8_t* u_buf, \ const uint8_t* v_buf, uint8_t* dst_ptr, \ const struct YuvConstants* yuvconstants, int width) { \ SIMD_ALIGNED(uint8_t temp[128 * 4]); \ memset(temp, 0, 128 * 3); /* for YUY2 and msan */ \ int r = width & MASK; \ int n = width & ~MASK; \ if (n > 0) { \ ANY_SIMD(y_buf, u_buf, v_buf, dst_ptr, yuvconstants, n); \ } \ memcpy(temp, y_buf + n, r); \ memcpy(temp + 128, u_buf + (n >> UVSHIFT), SS(r, UVSHIFT)); \ memcpy(temp + 256, v_buf + (n >> UVSHIFT), SS(r, UVSHIFT)); \ if (width & 1) { \ temp[128 + SS(r, UVSHIFT)] = temp[128 + SS(r, UVSHIFT) - 1]; \ temp[256 + SS(r, UVSHIFT)] = temp[256 + SS(r, UVSHIFT) - 1]; \ } \ ANY_SIMD(temp, temp + 128, temp + 256, temp + 384, yuvconstants, \ MASK + 1); \ memcpy(dst_ptr + (n >> DUVSHIFT) * BPP, temp + 384, \ SS(r, DUVSHIFT) * BPP); \ } #ifdef HAS_I422TOARGBROW_SSSE3 ANY31C(I422ToARGBRow_Any_SSSE3, I422ToARGBRow_SSSE3, 1, 0, 4, 7) #endif #ifdef HAS_I422TOAR30ROW_SSSE3 ANY31C(I422ToAR30Row_Any_SSSE3, I422ToAR30Row_SSSE3, 1, 0, 4, 7) #endif #ifdef HAS_I422TOAR30ROW_AVX2 ANY31C(I422ToAR30Row_Any_AVX2, I422ToAR30Row_AVX2, 1, 0, 4, 15) #endif #ifdef HAS_I444TOARGBROW_SSSE3 ANY31C(I444ToARGBRow_Any_SSSE3, I444ToARGBRow_SSSE3, 0, 0, 4, 7) ANY31C(I422ToRGBARow_Any_SSSE3, I422ToRGBARow_SSSE3, 1, 0, 4, 7) ANY31C(I422ToARGB4444Row_Any_SSSE3, I422ToARGB4444Row_SSSE3, 1, 0, 2, 7) ANY31C(I422ToARGB1555Row_Any_SSSE3, I422ToARGB1555Row_SSSE3, 1, 0, 2, 7) ANY31C(I422ToRGB565Row_Any_SSSE3, I422ToRGB565Row_SSSE3, 1, 0, 2, 7) ANY31C(I422ToRGB24Row_Any_SSSE3, I422ToRGB24Row_SSSE3, 1, 0, 3, 15) #endif // HAS_I444TOARGBROW_SSSE3 #ifdef HAS_I422TORGB24ROW_AVX2 ANY31C(I422ToRGB24Row_Any_AVX2, I422ToRGB24Row_AVX2, 1, 0, 3, 31) #endif #ifdef HAS_I422TOARGBROW_AVX2 ANY31C(I422ToARGBRow_Any_AVX2, I422ToARGBRow_AVX2, 1, 0, 4, 15) #endif #ifdef HAS_I422TORGBAROW_AVX2 ANY31C(I422ToRGBARow_Any_AVX2, I422ToRGBARow_AVX2, 1, 0, 4, 15) #endif #ifdef HAS_I444TOARGBROW_AVX2 ANY31C(I444ToARGBRow_Any_AVX2, I444ToARGBRow_AVX2, 0, 0, 4, 15) #endif #ifdef HAS_I422TOARGB4444ROW_AVX2 ANY31C(I422ToARGB4444Row_Any_AVX2, I422ToARGB4444Row_AVX2, 1, 0, 2, 15) #endif #ifdef HAS_I422TOARGB1555ROW_AVX2 ANY31C(I422ToARGB1555Row_Any_AVX2, I422ToARGB1555Row_AVX2, 1, 0, 2, 15) #endif #ifdef HAS_I422TORGB565ROW_AVX2 ANY31C(I422ToRGB565Row_Any_AVX2, I422ToRGB565Row_AVX2, 1, 0, 2, 15) #endif #ifdef HAS_I422TOARGBROW_NEON ANY31C(I444ToARGBRow_Any_NEON, I444ToARGBRow_NEON, 0, 0, 4, 7) ANY31C(I422ToARGBRow_Any_NEON, I422ToARGBRow_NEON, 1, 0, 4, 7) ANY31C(I422ToRGBARow_Any_NEON, I422ToRGBARow_NEON, 1, 0, 4, 7) ANY31C(I422ToRGB24Row_Any_NEON, I422ToRGB24Row_NEON, 1, 0, 3, 7) ANY31C(I422ToARGB4444Row_Any_NEON, I422ToARGB4444Row_NEON, 1, 0, 2, 7) ANY31C(I422ToARGB1555Row_Any_NEON, I422ToARGB1555Row_NEON, 1, 0, 2, 7) ANY31C(I422ToRGB565Row_Any_NEON, I422ToRGB565Row_NEON, 1, 0, 2, 7) #endif #ifdef HAS_I422TOARGBROW_MSA ANY31C(I444ToARGBRow_Any_MSA, I444ToARGBRow_MSA, 0, 0, 4, 7) ANY31C(I422ToARGBRow_Any_MSA, I422ToARGBRow_MSA, 1, 0, 4, 7) ANY31C(I422ToRGBARow_Any_MSA, I422ToRGBARow_MSA, 1, 0, 4, 7) ANY31C(I422ToRGB24Row_Any_MSA, I422ToRGB24Row_MSA, 1, 0, 3, 15) ANY31C(I422ToARGB4444Row_Any_MSA, I422ToARGB4444Row_MSA, 1, 0, 2, 7) ANY31C(I422ToARGB1555Row_Any_MSA, I422ToARGB1555Row_MSA, 1, 0, 2, 7) ANY31C(I422ToRGB565Row_Any_MSA, I422ToRGB565Row_MSA, 1, 0, 2, 7) #endif #ifdef HAS_I422TOARGBROW_MMI ANY31C(I444ToARGBRow_Any_MMI, I444ToARGBRow_MMI, 0, 0, 4, 7) ANY31C(I422ToARGBRow_Any_MMI, I422ToARGBRow_MMI, 1, 0, 4, 7) ANY31C(I422ToRGB24Row_Any_MMI, I422ToRGB24Row_MMI, 1, 0, 3, 15) ANY31C(I422ToARGB4444Row_Any_MMI, I422ToARGB4444Row_MMI, 1, 0, 2, 7) ANY31C(I422ToARGB1555Row_Any_MMI, I422ToARGB1555Row_MMI, 1, 0, 2, 7) ANY31C(I422ToRGB565Row_Any_MMI, I422ToRGB565Row_MMI, 1, 0, 2, 7) ANY31C(I422ToRGBARow_Any_MMI, I422ToRGBARow_MMI, 1, 0, 4, 7) #endif #undef ANY31C // Any 3 planes of 16 bit to 1 with yuvconstants // TODO(fbarchard): consider sharing this code with ANY31C #define ANY31CT(NAMEANY, ANY_SIMD, UVSHIFT, DUVSHIFT, T, SBPP, BPP, MASK) \ void NAMEANY(const T* y_buf, const T* u_buf, const T* v_buf, \ uint8_t* dst_ptr, const struct YuvConstants* yuvconstants, \ int width) { \ SIMD_ALIGNED(T temp[16 * 3]); \ SIMD_ALIGNED(uint8_t out[64]); \ memset(temp, 0, 16 * 3 * SBPP); /* for YUY2 and msan */ \ int r = width & MASK; \ int n = width & ~MASK; \ if (n > 0) { \ ANY_SIMD(y_buf, u_buf, v_buf, dst_ptr, yuvconstants, n); \ } \ memcpy(temp, y_buf + n, r * SBPP); \ memcpy(temp + 16, u_buf + (n >> UVSHIFT), SS(r, UVSHIFT) * SBPP); \ memcpy(temp + 32, v_buf + (n >> UVSHIFT), SS(r, UVSHIFT) * SBPP); \ ANY_SIMD(temp, temp + 16, temp + 32, out, yuvconstants, MASK + 1); \ memcpy(dst_ptr + (n >> DUVSHIFT) * BPP, out, SS(r, DUVSHIFT) * BPP); \ } #ifdef HAS_I210TOAR30ROW_SSSE3 ANY31CT(I210ToAR30Row_Any_SSSE3, I210ToAR30Row_SSSE3, 1, 0, uint16_t, 2, 4, 7) #endif #ifdef HAS_I210TOARGBROW_SSSE3 ANY31CT(I210ToARGBRow_Any_SSSE3, I210ToARGBRow_SSSE3, 1, 0, uint16_t, 2, 4, 7) #endif #ifdef HAS_I210TOARGBROW_AVX2 ANY31CT(I210ToARGBRow_Any_AVX2, I210ToARGBRow_AVX2, 1, 0, uint16_t, 2, 4, 15) #endif #ifdef HAS_I210TOAR30ROW_AVX2 ANY31CT(I210ToAR30Row_Any_AVX2, I210ToAR30Row_AVX2, 1, 0, uint16_t, 2, 4, 15) #endif #ifdef HAS_I210TOARGBROW_MMI ANY31CT(I210ToARGBRow_Any_MMI, I210ToARGBRow_MMI, 1, 0, uint16_t, 2, 4, 7) #endif #undef ANY31CT // Any 2 planes to 1. #define ANY21(NAMEANY, ANY_SIMD, UVSHIFT, SBPP, SBPP2, BPP, MASK) \ void NAMEANY(const uint8_t* y_buf, const uint8_t* uv_buf, uint8_t* dst_ptr, \ int width) { \ SIMD_ALIGNED(uint8_t temp[64 * 3]); \ memset(temp, 0, 64 * 2); /* for msan */ \ int r = width & MASK; \ int n = width & ~MASK; \ if (n > 0) { \ ANY_SIMD(y_buf, uv_buf, dst_ptr, n); \ } \ memcpy(temp, y_buf + n * SBPP, r * SBPP); \ memcpy(temp + 64, uv_buf + (n >> UVSHIFT) * SBPP2, \ SS(r, UVSHIFT) * SBPP2); \ ANY_SIMD(temp, temp + 64, temp + 128, MASK + 1); \ memcpy(dst_ptr + n * BPP, temp + 128, r * BPP); \ } // Merge functions. #ifdef HAS_MERGEUVROW_SSE2 ANY21(MergeUVRow_Any_SSE2, MergeUVRow_SSE2, 0, 1, 1, 2, 15) #endif #ifdef HAS_MERGEUVROW_AVX2 ANY21(MergeUVRow_Any_AVX2, MergeUVRow_AVX2, 0, 1, 1, 2, 31) #endif #ifdef HAS_MERGEUVROW_NEON ANY21(MergeUVRow_Any_NEON, MergeUVRow_NEON, 0, 1, 1, 2, 15) #endif #ifdef HAS_MERGEUVROW_MSA ANY21(MergeUVRow_Any_MSA, MergeUVRow_MSA, 0, 1, 1, 2, 15) #endif #ifdef HAS_MERGEUVROW_MMI ANY21(MergeUVRow_Any_MMI, MergeUVRow_MMI, 0, 1, 1, 2, 7) #endif #ifdef HAS_NV21TOYUV24ROW_NEON ANY21(NV21ToYUV24Row_Any_NEON, NV21ToYUV24Row_NEON, 1, 1, 2, 3, 15) #endif #ifdef HAS_NV21TOYUV24ROW_AVX2 ANY21(NV21ToYUV24Row_Any_AVX2, NV21ToYUV24Row_AVX2, 1, 1, 2, 3, 31) #endif // Math functions. #ifdef HAS_ARGBMULTIPLYROW_SSE2 ANY21(ARGBMultiplyRow_Any_SSE2, ARGBMultiplyRow_SSE2, 0, 4, 4, 4, 3) #endif #ifdef HAS_ARGBADDROW_SSE2 ANY21(ARGBAddRow_Any_SSE2, ARGBAddRow_SSE2, 0, 4, 4, 4, 3) #endif #ifdef HAS_ARGBSUBTRACTROW_SSE2 ANY21(ARGBSubtractRow_Any_SSE2, ARGBSubtractRow_SSE2, 0, 4, 4, 4, 3) #endif #ifdef HAS_ARGBMULTIPLYROW_AVX2 ANY21(ARGBMultiplyRow_Any_AVX2, ARGBMultiplyRow_AVX2, 0, 4, 4, 4, 7) #endif #ifdef HAS_ARGBADDROW_AVX2 ANY21(ARGBAddRow_Any_AVX2, ARGBAddRow_AVX2, 0, 4, 4, 4, 7) #endif #ifdef HAS_ARGBSUBTRACTROW_AVX2 ANY21(ARGBSubtractRow_Any_AVX2, ARGBSubtractRow_AVX2, 0, 4, 4, 4, 7) #endif #ifdef HAS_ARGBMULTIPLYROW_NEON ANY21(ARGBMultiplyRow_Any_NEON, ARGBMultiplyRow_NEON, 0, 4, 4, 4, 7) #endif #ifdef HAS_ARGBADDROW_NEON ANY21(ARGBAddRow_Any_NEON, ARGBAddRow_NEON, 0, 4, 4, 4, 7) #endif #ifdef HAS_ARGBSUBTRACTROW_NEON ANY21(ARGBSubtractRow_Any_NEON, ARGBSubtractRow_NEON, 0, 4, 4, 4, 7) #endif #ifdef HAS_ARGBMULTIPLYROW_MSA ANY21(ARGBMultiplyRow_Any_MSA, ARGBMultiplyRow_MSA, 0, 4, 4, 4, 3) #endif #ifdef HAS_ARGBMULTIPLYROW_MMI ANY21(ARGBMultiplyRow_Any_MMI, ARGBMultiplyRow_MMI, 0, 4, 4, 4, 1) #endif #ifdef HAS_ARGBADDROW_MSA ANY21(ARGBAddRow_Any_MSA, ARGBAddRow_MSA, 0, 4, 4, 4, 7) #endif #ifdef HAS_ARGBADDROW_MMI ANY21(ARGBAddRow_Any_MMI, ARGBAddRow_MMI, 0, 4, 4, 4, 1) #endif #ifdef HAS_ARGBSUBTRACTROW_MSA ANY21(ARGBSubtractRow_Any_MSA, ARGBSubtractRow_MSA, 0, 4, 4, 4, 7) #endif #ifdef HAS_ARGBSUBTRACTROW_MMI ANY21(ARGBSubtractRow_Any_MMI, ARGBSubtractRow_MMI, 0, 4, 4, 4, 1) #endif #ifdef HAS_SOBELROW_SSE2 ANY21(SobelRow_Any_SSE2, SobelRow_SSE2, 0, 1, 1, 4, 15) #endif #ifdef HAS_SOBELROW_NEON ANY21(SobelRow_Any_NEON, SobelRow_NEON, 0, 1, 1, 4, 7) #endif #ifdef HAS_SOBELROW_MSA ANY21(SobelRow_Any_MSA, SobelRow_MSA, 0, 1, 1, 4, 15) #endif #ifdef HAS_SOBELROW_MMI ANY21(SobelRow_Any_MMI, SobelRow_MMI, 0, 1, 1, 4, 7) #endif #ifdef HAS_SOBELTOPLANEROW_SSE2 ANY21(SobelToPlaneRow_Any_SSE2, SobelToPlaneRow_SSE2, 0, 1, 1, 1, 15) #endif #ifdef HAS_SOBELTOPLANEROW_NEON ANY21(SobelToPlaneRow_Any_NEON, SobelToPlaneRow_NEON, 0, 1, 1, 1, 15) #endif #ifdef HAS_SOBELTOPLANEROW_MSA ANY21(SobelToPlaneRow_Any_MSA, SobelToPlaneRow_MSA, 0, 1, 1, 1, 31) #endif #ifdef HAS_SOBELTOPLANEROW_MMI ANY21(SobelToPlaneRow_Any_MMI, SobelToPlaneRow_MMI, 0, 1, 1, 1, 7) #endif #ifdef HAS_SOBELXYROW_SSE2 ANY21(SobelXYRow_Any_SSE2, SobelXYRow_SSE2, 0, 1, 1, 4, 15) #endif #ifdef HAS_SOBELXYROW_NEON ANY21(SobelXYRow_Any_NEON, SobelXYRow_NEON, 0, 1, 1, 4, 7) #endif #ifdef HAS_SOBELXYROW_MSA ANY21(SobelXYRow_Any_MSA, SobelXYRow_MSA, 0, 1, 1, 4, 15) #endif #ifdef HAS_SOBELXYROW_MMI ANY21(SobelXYRow_Any_MMI, SobelXYRow_MMI, 0, 1, 1, 4, 7) #endif #undef ANY21 // Any 2 planes to 1 with yuvconstants #define ANY21C(NAMEANY, ANY_SIMD, UVSHIFT, SBPP, SBPP2, BPP, MASK) \ void NAMEANY(const uint8_t* y_buf, const uint8_t* uv_buf, uint8_t* dst_ptr, \ const struct YuvConstants* yuvconstants, int width) { \ SIMD_ALIGNED(uint8_t temp[128 * 3]); \ memset(temp, 0, 128 * 2); /* for msan */ \ int r = width & MASK; \ int n = width & ~MASK; \ if (n > 0) { \ ANY_SIMD(y_buf, uv_buf, dst_ptr, yuvconstants, n); \ } \ memcpy(temp, y_buf + n * SBPP, r * SBPP); \ memcpy(temp + 128, uv_buf + (n >> UVSHIFT) * SBPP2, \ SS(r, UVSHIFT) * SBPP2); \ ANY_SIMD(temp, temp + 128, temp + 256, yuvconstants, MASK + 1); \ memcpy(dst_ptr + n * BPP, temp + 256, r * BPP); \ } // Biplanar to RGB. #ifdef HAS_NV12TOARGBROW_SSSE3 ANY21C(NV12ToARGBRow_Any_SSSE3, NV12ToARGBRow_SSSE3, 1, 1, 2, 4, 7) #endif #ifdef HAS_NV12TOARGBROW_AVX2 ANY21C(NV12ToARGBRow_Any_AVX2, NV12ToARGBRow_AVX2, 1, 1, 2, 4, 15) #endif #ifdef HAS_NV12TOARGBROW_NEON ANY21C(NV12ToARGBRow_Any_NEON, NV12ToARGBRow_NEON, 1, 1, 2, 4, 7) #endif #ifdef HAS_NV12TOARGBROW_MSA ANY21C(NV12ToARGBRow_Any_MSA, NV12ToARGBRow_MSA, 1, 1, 2, 4, 7) #endif #ifdef HAS_NV12TOARGBROW_MMI ANY21C(NV12ToARGBRow_Any_MMI, NV12ToARGBRow_MMI, 1, 1, 2, 4, 7) #endif #ifdef HAS_NV21TOARGBROW_SSSE3 ANY21C(NV21ToARGBRow_Any_SSSE3, NV21ToARGBRow_SSSE3, 1, 1, 2, 4, 7) #endif #ifdef HAS_NV21TOARGBROW_AVX2 ANY21C(NV21ToARGBRow_Any_AVX2, NV21ToARGBRow_AVX2, 1, 1, 2, 4, 15) #endif #ifdef HAS_NV21TOARGBROW_NEON ANY21C(NV21ToARGBRow_Any_NEON, NV21ToARGBRow_NEON, 1, 1, 2, 4, 7) #endif #ifdef HAS_NV21TOARGBROW_MSA ANY21C(NV21ToARGBRow_Any_MSA, NV21ToARGBRow_MSA, 1, 1, 2, 4, 7) #endif #ifdef HAS_NV21TOARGBROW_MMI ANY21C(NV21ToARGBRow_Any_MMI, NV21ToARGBRow_MMI, 1, 1, 2, 4, 7) #endif #ifdef HAS_NV12TORGB24ROW_NEON ANY21C(NV12ToRGB24Row_Any_NEON, NV12ToRGB24Row_NEON, 1, 1, 2, 3, 7) #endif #ifdef HAS_NV21TORGB24ROW_NEON ANY21C(NV21ToRGB24Row_Any_NEON, NV21ToRGB24Row_NEON, 1, 1, 2, 3, 7) #endif #ifdef HAS_NV12TORGB24ROW_SSSE3 ANY21C(NV12ToRGB24Row_Any_SSSE3, NV12ToRGB24Row_SSSE3, 1, 1, 2, 3, 15) #endif #ifdef HAS_NV12TORGB24ROW_MMI ANY21C(NV12ToRGB24Row_Any_MMI, NV12ToRGB24Row_MMI, 1, 1, 2, 3, 7) #endif #ifdef HAS_NV21TORGB24ROW_SSSE3 ANY21C(NV21ToRGB24Row_Any_SSSE3, NV21ToRGB24Row_SSSE3, 1, 1, 2, 3, 15) #endif #ifdef HAS_NV12TORGB24ROW_AVX2 ANY21C(NV12ToRGB24Row_Any_AVX2, NV12ToRGB24Row_AVX2, 1, 1, 2, 3, 31) #endif #ifdef HAS_NV21TORGB24ROW_AVX2 ANY21C(NV21ToRGB24Row_Any_AVX2, NV21ToRGB24Row_AVX2, 1, 1, 2, 3, 31) #endif #ifdef HAS_NV21TORGB24ROW_MMI ANY21C(NV21ToRGB24Row_Any_MMI, NV21ToRGB24Row_MMI, 1, 1, 2, 3, 7) #endif #ifdef HAS_NV12TORGB565ROW_SSSE3 ANY21C(NV12ToRGB565Row_Any_SSSE3, NV12ToRGB565Row_SSSE3, 1, 1, 2, 2, 7) #endif #ifdef HAS_NV12TORGB565ROW_AVX2 ANY21C(NV12ToRGB565Row_Any_AVX2, NV12ToRGB565Row_AVX2, 1, 1, 2, 2, 15) #endif #ifdef HAS_NV12TORGB565ROW_NEON ANY21C(NV12ToRGB565Row_Any_NEON, NV12ToRGB565Row_NEON, 1, 1, 2, 2, 7) #endif #ifdef HAS_NV12TORGB565ROW_MSA ANY21C(NV12ToRGB565Row_Any_MSA, NV12ToRGB565Row_MSA, 1, 1, 2, 2, 7) #endif #ifdef HAS_NV12TORGB565ROW_MMI ANY21C(NV12ToRGB565Row_Any_MMI, NV12ToRGB565Row_MMI, 1, 1, 2, 2, 7) #endif #undef ANY21C // Any 1 to 1. #define ANY11(NAMEANY, ANY_SIMD, UVSHIFT, SBPP, BPP, MASK) \ void NAMEANY(const uint8_t* src_ptr, uint8_t* dst_ptr, int width) { \ SIMD_ALIGNED(uint8_t temp[128 * 2]); \ memset(temp, 0, 128); /* for YUY2 and msan */ \ int r = width & MASK; \ int n = width & ~MASK; \ if (n > 0) { \ ANY_SIMD(src_ptr, dst_ptr, n); \ } \ memcpy(temp, src_ptr + (n >> UVSHIFT) * SBPP, SS(r, UVSHIFT) * SBPP); \ ANY_SIMD(temp, temp + 128, MASK + 1); \ memcpy(dst_ptr + n * BPP, temp + 128, r * BPP); \ } #ifdef HAS_COPYROW_AVX ANY11(CopyRow_Any_AVX, CopyRow_AVX, 0, 1, 1, 63) #endif #ifdef HAS_COPYROW_SSE2 ANY11(CopyRow_Any_SSE2, CopyRow_SSE2, 0, 1, 1, 31) #endif #ifdef HAS_COPYROW_NEON ANY11(CopyRow_Any_NEON, CopyRow_NEON, 0, 1, 1, 31) #endif #if defined(HAS_ARGBTORGB24ROW_SSSE3) ANY11(ARGBToRGB24Row_Any_SSSE3, ARGBToRGB24Row_SSSE3, 0, 4, 3, 15) ANY11(ARGBToRAWRow_Any_SSSE3, ARGBToRAWRow_SSSE3, 0, 4, 3, 15) ANY11(ARGBToRGB565Row_Any_SSE2, ARGBToRGB565Row_SSE2, 0, 4, 2, 3) ANY11(ARGBToARGB1555Row_Any_SSE2, ARGBToARGB1555Row_SSE2, 0, 4, 2, 3) ANY11(ARGBToARGB4444Row_Any_SSE2, ARGBToARGB4444Row_SSE2, 0, 4, 2, 3) #endif #if defined(HAS_ARGBTORGB24ROW_AVX2) ANY11(ARGBToRGB24Row_Any_AVX2, ARGBToRGB24Row_AVX2, 0, 4, 3, 31) #endif #if defined(HAS_ARGBTORGB24ROW_AVX512VBMI) ANY11(ARGBToRGB24Row_Any_AVX512VBMI, ARGBToRGB24Row_AVX512VBMI, 0, 4, 3, 31) #endif #if defined(HAS_ARGBTORAWROW_AVX2) ANY11(ARGBToRAWRow_Any_AVX2, ARGBToRAWRow_AVX2, 0, 4, 3, 31) #endif #if defined(HAS_ARGBTORGB565ROW_AVX2) ANY11(ARGBToRGB565Row_Any_AVX2, ARGBToRGB565Row_AVX2, 0, 4, 2, 7) #endif #if defined(HAS_ARGBTOARGB4444ROW_AVX2) ANY11(ARGBToARGB1555Row_Any_AVX2, ARGBToARGB1555Row_AVX2, 0, 4, 2, 7) ANY11(ARGBToARGB4444Row_Any_AVX2, ARGBToARGB4444Row_AVX2, 0, 4, 2, 7) #endif #if defined(HAS_ABGRTOAR30ROW_SSSE3) ANY11(ABGRToAR30Row_Any_SSSE3, ABGRToAR30Row_SSSE3, 0, 4, 4, 3) #endif #if defined(HAS_ARGBTOAR30ROW_SSSE3) ANY11(ARGBToAR30Row_Any_SSSE3, ARGBToAR30Row_SSSE3, 0, 4, 4, 3) #endif #if defined(HAS_ABGRTOAR30ROW_AVX2) ANY11(ABGRToAR30Row_Any_AVX2, ABGRToAR30Row_AVX2, 0, 4, 4, 7) #endif #if defined(HAS_ARGBTOAR30ROW_AVX2) ANY11(ARGBToAR30Row_Any_AVX2, ARGBToAR30Row_AVX2, 0, 4, 4, 7) #endif #if defined(HAS_J400TOARGBROW_SSE2) ANY11(J400ToARGBRow_Any_SSE2, J400ToARGBRow_SSE2, 0, 1, 4, 7) #endif #if defined(HAS_J400TOARGBROW_AVX2) ANY11(J400ToARGBRow_Any_AVX2, J400ToARGBRow_AVX2, 0, 1, 4, 15) #endif #if defined(HAS_RGB24TOARGBROW_SSSE3) ANY11(RGB24ToARGBRow_Any_SSSE3, RGB24ToARGBRow_SSSE3, 0, 3, 4, 15) ANY11(RAWToARGBRow_Any_SSSE3, RAWToARGBRow_SSSE3, 0, 3, 4, 15) ANY11(RGB565ToARGBRow_Any_SSE2, RGB565ToARGBRow_SSE2, 0, 2, 4, 7) ANY11(ARGB1555ToARGBRow_Any_SSE2, ARGB1555ToARGBRow_SSE2, 0, 2, 4, 7) ANY11(ARGB4444ToARGBRow_Any_SSE2, ARGB4444ToARGBRow_SSE2, 0, 2, 4, 7) #endif #if defined(HAS_RAWTORGBAROW_SSSE3) ANY11(RAWToRGBARow_Any_SSSE3, RAWToRGBARow_SSSE3, 0, 3, 4, 15) #endif #if defined(HAS_RAWTORGB24ROW_SSSE3) ANY11(RAWToRGB24Row_Any_SSSE3, RAWToRGB24Row_SSSE3, 0, 3, 3, 7) #endif #if defined(HAS_RGB565TOARGBROW_AVX2) ANY11(RGB565ToARGBRow_Any_AVX2, RGB565ToARGBRow_AVX2, 0, 2, 4, 15) #endif #if defined(HAS_ARGB1555TOARGBROW_AVX2) ANY11(ARGB1555ToARGBRow_Any_AVX2, ARGB1555ToARGBRow_AVX2, 0, 2, 4, 15) #endif #if defined(HAS_ARGB4444TOARGBROW_AVX2) ANY11(ARGB4444ToARGBRow_Any_AVX2, ARGB4444ToARGBRow_AVX2, 0, 2, 4, 15) #endif #if defined(HAS_ARGBTORGB24ROW_NEON) ANY11(ARGBToRGB24Row_Any_NEON, ARGBToRGB24Row_NEON, 0, 4, 3, 7) ANY11(ARGBToRAWRow_Any_NEON, ARGBToRAWRow_NEON, 0, 4, 3, 7) ANY11(ARGBToRGB565Row_Any_NEON, ARGBToRGB565Row_NEON, 0, 4, 2, 7) ANY11(ARGBToARGB1555Row_Any_NEON, ARGBToARGB1555Row_NEON, 0, 4, 2, 7) ANY11(ARGBToARGB4444Row_Any_NEON, ARGBToARGB4444Row_NEON, 0, 4, 2, 7) ANY11(J400ToARGBRow_Any_NEON, J400ToARGBRow_NEON, 0, 1, 4, 7) #endif #if defined(HAS_ARGBTORGB24ROW_MSA) ANY11(ARGBToRGB24Row_Any_MSA, ARGBToRGB24Row_MSA, 0, 4, 3, 15) ANY11(ARGBToRAWRow_Any_MSA, ARGBToRAWRow_MSA, 0, 4, 3, 15) ANY11(ARGBToRGB565Row_Any_MSA, ARGBToRGB565Row_MSA, 0, 4, 2, 7) ANY11(ARGBToARGB1555Row_Any_MSA, ARGBToARGB1555Row_MSA, 0, 4, 2, 7) ANY11(ARGBToARGB4444Row_Any_MSA, ARGBToARGB4444Row_MSA, 0, 4, 2, 7) ANY11(J400ToARGBRow_Any_MSA, J400ToARGBRow_MSA, 0, 1, 4, 15) #endif #if defined(HAS_ARGBTORGB24ROW_MMI) ANY11(ARGBToRGB24Row_Any_MMI, ARGBToRGB24Row_MMI, 0, 4, 3, 3) ANY11(ARGBToRAWRow_Any_MMI, ARGBToRAWRow_MMI, 0, 4, 3, 3) ANY11(ARGBToRGB565Row_Any_MMI, ARGBToRGB565Row_MMI, 0, 4, 2, 3) ANY11(ARGBToARGB1555Row_Any_MMI, ARGBToARGB1555Row_MMI, 0, 4, 2, 3) ANY11(ARGBToARGB4444Row_Any_MMI, ARGBToARGB4444Row_MMI, 0, 4, 2, 3) ANY11(J400ToARGBRow_Any_MMI, J400ToARGBRow_MMI, 0, 1, 4, 3) #endif #if defined(HAS_RAWTORGB24ROW_NEON) ANY11(RAWToRGB24Row_Any_NEON, RAWToRGB24Row_NEON, 0, 3, 3, 7) #endif #if defined(HAS_RAWTORGB24ROW_MSA) ANY11(RAWToRGB24Row_Any_MSA, RAWToRGB24Row_MSA, 0, 3, 3, 15) #endif #if defined(HAS_RAWTORGB24ROW_MMI) ANY11(RAWToRGB24Row_Any_MMI, RAWToRGB24Row_MMI, 0, 3, 3, 3) #endif #ifdef HAS_ARGBTOYROW_AVX2 ANY11(ARGBToYRow_Any_AVX2, ARGBToYRow_AVX2, 0, 4, 1, 31) #endif #ifdef HAS_ABGRTOYROW_AVX2 ANY11(ABGRToYRow_Any_AVX2, ABGRToYRow_AVX2, 0, 4, 1, 31) #endif #ifdef HAS_ARGBTOYJROW_AVX2 ANY11(ARGBToYJRow_Any_AVX2, ARGBToYJRow_AVX2, 0, 4, 1, 31) #endif #ifdef HAS_RGBATOYJROW_AVX2 ANY11(RGBAToYJRow_Any_AVX2, RGBAToYJRow_AVX2, 0, 4, 1, 31) #endif #ifdef HAS_UYVYTOYROW_AVX2 ANY11(UYVYToYRow_Any_AVX2, UYVYToYRow_AVX2, 0, 2, 1, 31) #endif #ifdef HAS_YUY2TOYROW_AVX2 ANY11(YUY2ToYRow_Any_AVX2, YUY2ToYRow_AVX2, 1, 4, 1, 31) #endif #ifdef HAS_ARGBTOYROW_SSSE3 ANY11(ARGBToYRow_Any_SSSE3, ARGBToYRow_SSSE3, 0, 4, 1, 15) #endif #ifdef HAS_BGRATOYROW_SSSE3 ANY11(BGRAToYRow_Any_SSSE3, BGRAToYRow_SSSE3, 0, 4, 1, 15) ANY11(ABGRToYRow_Any_SSSE3, ABGRToYRow_SSSE3, 0, 4, 1, 15) ANY11(RGBAToYRow_Any_SSSE3, RGBAToYRow_SSSE3, 0, 4, 1, 15) ANY11(YUY2ToYRow_Any_SSE2, YUY2ToYRow_SSE2, 1, 4, 1, 15) ANY11(UYVYToYRow_Any_SSE2, UYVYToYRow_SSE2, 1, 4, 1, 15) #endif #ifdef HAS_ARGBTOYJROW_SSSE3 ANY11(ARGBToYJRow_Any_SSSE3, ARGBToYJRow_SSSE3, 0, 4, 1, 15) #endif #ifdef HAS_RGBATOYJROW_SSSE3 ANY11(RGBAToYJRow_Any_SSSE3, RGBAToYJRow_SSSE3, 0, 4, 1, 15) #endif #ifdef HAS_ARGBTOYROW_NEON ANY11(ARGBToYRow_Any_NEON, ARGBToYRow_NEON, 0, 4, 1, 7) #endif #ifdef HAS_ARGBTOYROW_MSA ANY11(ARGBToYRow_Any_MSA, ARGBToYRow_MSA, 0, 4, 1, 15) #endif #ifdef HAS_ARGBTOYROW_MMI ANY11(ARGBToYRow_Any_MMI, ARGBToYRow_MMI, 0, 4, 1, 7) #endif #ifdef HAS_ARGBTOYJROW_NEON ANY11(ARGBToYJRow_Any_NEON, ARGBToYJRow_NEON, 0, 4, 1, 7) #endif #ifdef HAS_RGBATOYJROW_NEON ANY11(RGBAToYJRow_Any_NEON, RGBAToYJRow_NEON, 0, 4, 1, 7) #endif #ifdef HAS_ARGBTOYJROW_MSA ANY11(ARGBToYJRow_Any_MSA, ARGBToYJRow_MSA, 0, 4, 1, 15) #endif #ifdef HAS_ARGBTOYJROW_MMI ANY11(ARGBToYJRow_Any_MMI, ARGBToYJRow_MMI, 0, 4, 1, 7) #endif #ifdef HAS_BGRATOYROW_NEON ANY11(BGRAToYRow_Any_NEON, BGRAToYRow_NEON, 0, 4, 1, 7) #endif #ifdef HAS_BGRATOYROW_MSA ANY11(BGRAToYRow_Any_MSA, BGRAToYRow_MSA, 0, 4, 1, 15) #endif #ifdef HAS_BGRATOYROW_MMI ANY11(BGRAToYRow_Any_MMI, BGRAToYRow_MMI, 0, 4, 1, 7) #endif #ifdef HAS_ABGRTOYROW_NEON ANY11(ABGRToYRow_Any_NEON, ABGRToYRow_NEON, 0, 4, 1, 7) #endif #ifdef HAS_ABGRTOYROW_MSA ANY11(ABGRToYRow_Any_MSA, ABGRToYRow_MSA, 0, 4, 1, 7) #endif #ifdef HAS_ABGRTOYROW_MMI ANY11(ABGRToYRow_Any_MMI, ABGRToYRow_MMI, 0, 4, 1, 7) #endif #ifdef HAS_RGBATOYROW_NEON ANY11(RGBAToYRow_Any_NEON, RGBAToYRow_NEON, 0, 4, 1, 7) #endif #ifdef HAS_RGBATOYROW_MSA ANY11(RGBAToYRow_Any_MSA, RGBAToYRow_MSA, 0, 4, 1, 15) #endif #ifdef HAS_RGBATOYROW_MMI ANY11(RGBAToYRow_Any_MMI, RGBAToYRow_MMI, 0, 4, 1, 7) #endif #ifdef HAS_RGB24TOYROW_NEON ANY11(RGB24ToYRow_Any_NEON, RGB24ToYRow_NEON, 0, 3, 1, 7) #endif #ifdef HAS_RGB24TOYJROW_AVX2 ANY11(RGB24ToYJRow_Any_AVX2, RGB24ToYJRow_AVX2, 0, 3, 1, 31) #endif #ifdef HAS_RGB24TOYJROW_SSSE3 ANY11(RGB24ToYJRow_Any_SSSE3, RGB24ToYJRow_SSSE3, 0, 3, 1, 15) #endif #ifdef HAS_RGB24TOYJROW_NEON ANY11(RGB24ToYJRow_Any_NEON, RGB24ToYJRow_NEON, 0, 3, 1, 7) #endif #ifdef HAS_RGB24TOYROW_MSA ANY11(RGB24ToYRow_Any_MSA, RGB24ToYRow_MSA, 0, 3, 1, 15) #endif #ifdef HAS_RGB24TOYROW_MMI ANY11(RGB24ToYRow_Any_MMI, RGB24ToYRow_MMI, 0, 3, 1, 7) #endif #ifdef HAS_RAWTOYROW_NEON ANY11(RAWToYRow_Any_NEON, RAWToYRow_NEON, 0, 3, 1, 7) #endif #ifdef HAS_RAWTOYJROW_AVX2 ANY11(RAWToYJRow_Any_AVX2, RAWToYJRow_AVX2, 0, 3, 1, 31) #endif #ifdef HAS_RAWTOYJROW_SSSE3 ANY11(RAWToYJRow_Any_SSSE3, RAWToYJRow_SSSE3, 0, 3, 1, 15) #endif #ifdef HAS_RAWTOYJROW_NEON ANY11(RAWToYJRow_Any_NEON, RAWToYJRow_NEON, 0, 3, 1, 7) #endif #ifdef HAS_RAWTOYROW_MSA ANY11(RAWToYRow_Any_MSA, RAWToYRow_MSA, 0, 3, 1, 15) #endif #ifdef HAS_RAWTOYROW_MMI ANY11(RAWToYRow_Any_MMI, RAWToYRow_MMI, 0, 3, 1, 7) #endif #ifdef HAS_RGB565TOYROW_NEON ANY11(RGB565ToYRow_Any_NEON, RGB565ToYRow_NEON, 0, 2, 1, 7) #endif #ifdef HAS_RGB565TOYROW_MSA ANY11(RGB565ToYRow_Any_MSA, RGB565ToYRow_MSA, 0, 2, 1, 15) #endif #ifdef HAS_RGB565TOYROW_MMI ANY11(RGB565ToYRow_Any_MMI, RGB565ToYRow_MMI, 0, 2, 1, 7) #endif #ifdef HAS_ARGB1555TOYROW_NEON ANY11(ARGB1555ToYRow_Any_NEON, ARGB1555ToYRow_NEON, 0, 2, 1, 7) #endif #ifdef HAS_ARGB1555TOYROW_MSA ANY11(ARGB1555ToYRow_Any_MSA, ARGB1555ToYRow_MSA, 0, 2, 1, 15) #endif #ifdef HAS_ARGB1555TOYROW_MMI ANY11(ARGB1555ToYRow_Any_MMI, ARGB1555ToYRow_MMI, 0, 2, 1, 7) #endif #ifdef HAS_ARGB4444TOYROW_NEON ANY11(ARGB4444ToYRow_Any_NEON, ARGB4444ToYRow_NEON, 0, 2, 1, 7) #endif #ifdef HAS_ARGB4444TOYROW_MMI ANY11(ARGB4444ToYRow_Any_MMI, ARGB4444ToYRow_MMI, 0, 2, 1, 7) #endif #ifdef HAS_YUY2TOYROW_NEON ANY11(YUY2ToYRow_Any_NEON, YUY2ToYRow_NEON, 1, 4, 1, 15) #endif #ifdef HAS_UYVYTOYROW_NEON ANY11(UYVYToYRow_Any_NEON, UYVYToYRow_NEON, 1, 4, 1, 15) #endif #ifdef HAS_YUY2TOYROW_MSA ANY11(YUY2ToYRow_Any_MSA, YUY2ToYRow_MSA, 1, 4, 1, 31) #endif #ifdef HAS_YUY2TOYROW_MMI ANY11(YUY2ToYRow_Any_MMI, YUY2ToYRow_MMI, 1, 4, 1, 7) #endif #ifdef HAS_UYVYTOYROW_MSA ANY11(UYVYToYRow_Any_MSA, UYVYToYRow_MSA, 1, 4, 1, 31) #endif #ifdef HAS_UYVYTOYROW_MMI ANY11(UYVYToYRow_Any_MMI, UYVYToYRow_MMI, 1, 4, 1, 15) #endif #ifdef HAS_AYUVTOYROW_NEON ANY11(AYUVToYRow_Any_NEON, AYUVToYRow_NEON, 0, 4, 1, 15) #endif #ifdef HAS_SWAPUVROW_SSSE3 ANY11(SwapUVRow_Any_SSSE3, SwapUVRow_SSSE3, 0, 2, 2, 15) #endif #ifdef HAS_SWAPUVROW_AVX2 ANY11(SwapUVRow_Any_AVX2, SwapUVRow_AVX2, 0, 2, 2, 31) #endif #ifdef HAS_SWAPUVROW_NEON ANY11(SwapUVRow_Any_NEON, SwapUVRow_NEON, 0, 2, 2, 15) #endif #ifdef HAS_RGB24TOARGBROW_NEON ANY11(RGB24ToARGBRow_Any_NEON, RGB24ToARGBRow_NEON, 0, 3, 4, 7) #endif #ifdef HAS_RGB24TOARGBROW_MSA ANY11(RGB24ToARGBRow_Any_MSA, RGB24ToARGBRow_MSA, 0, 3, 4, 15) #endif #ifdef HAS_RGB24TOARGBROW_MMI ANY11(RGB24ToARGBRow_Any_MMI, RGB24ToARGBRow_MMI, 0, 3, 4, 3) #endif #ifdef HAS_RAWTOARGBROW_NEON ANY11(RAWToARGBRow_Any_NEON, RAWToARGBRow_NEON, 0, 3, 4, 7) #endif #ifdef HAS_RAWTORGBAROW_NEON ANY11(RAWToRGBARow_Any_NEON, RAWToRGBARow_NEON, 0, 3, 4, 7) #endif #ifdef HAS_RAWTOARGBROW_MSA ANY11(RAWToARGBRow_Any_MSA, RAWToARGBRow_MSA, 0, 3, 4, 15) #endif #ifdef HAS_RAWTOARGBROW_MMI ANY11(RAWToARGBRow_Any_MMI, RAWToARGBRow_MMI, 0, 3, 4, 3) #endif #ifdef HAS_RGB565TOARGBROW_NEON ANY11(RGB565ToARGBRow_Any_NEON, RGB565ToARGBRow_NEON, 0, 2, 4, 7) #endif #ifdef HAS_RGB565TOARGBROW_MSA ANY11(RGB565ToARGBRow_Any_MSA, RGB565ToARGBRow_MSA, 0, 2, 4, 15) #endif #ifdef HAS_RGB565TOARGBROW_MMI ANY11(RGB565ToARGBRow_Any_MMI, RGB565ToARGBRow_MMI, 0, 2, 4, 3) #endif #ifdef HAS_ARGB1555TOARGBROW_NEON ANY11(ARGB1555ToARGBRow_Any_NEON, ARGB1555ToARGBRow_NEON, 0, 2, 4, 7) #endif #ifdef HAS_ARGB1555TOARGBROW_MSA ANY11(ARGB1555ToARGBRow_Any_MSA, ARGB1555ToARGBRow_MSA, 0, 2, 4, 15) #endif #ifdef HAS_ARGB1555TOARGBROW_MMI ANY11(ARGB1555ToARGBRow_Any_MMI, ARGB1555ToARGBRow_MMI, 0, 2, 4, 3) #endif #ifdef HAS_ARGB4444TOARGBROW_NEON ANY11(ARGB4444ToARGBRow_Any_NEON, ARGB4444ToARGBRow_NEON, 0, 2, 4, 7) #endif #ifdef HAS_ARGB4444TOARGBROW_MSA ANY11(ARGB4444ToARGBRow_Any_MSA, ARGB4444ToARGBRow_MSA, 0, 2, 4, 15) #endif #ifdef HAS_ARGB4444TOARGBROW_MMI ANY11(ARGB4444ToARGBRow_Any_MMI, ARGB4444ToARGBRow_MMI, 0, 2, 4, 3) #endif #ifdef HAS_ARGBATTENUATEROW_SSSE3 ANY11(ARGBAttenuateRow_Any_SSSE3, ARGBAttenuateRow_SSSE3, 0, 4, 4, 3) #endif #ifdef HAS_ARGBUNATTENUATEROW_SSE2 ANY11(ARGBUnattenuateRow_Any_SSE2, ARGBUnattenuateRow_SSE2, 0, 4, 4, 3) #endif #ifdef HAS_ARGBATTENUATEROW_AVX2 ANY11(ARGBAttenuateRow_Any_AVX2, ARGBAttenuateRow_AVX2, 0, 4, 4, 7) #endif #ifdef HAS_ARGBUNATTENUATEROW_AVX2 ANY11(ARGBUnattenuateRow_Any_AVX2, ARGBUnattenuateRow_AVX2, 0, 4, 4, 7) #endif #ifdef HAS_ARGBATTENUATEROW_NEON ANY11(ARGBAttenuateRow_Any_NEON, ARGBAttenuateRow_NEON, 0, 4, 4, 7) #endif #ifdef HAS_ARGBATTENUATEROW_MSA ANY11(ARGBAttenuateRow_Any_MSA, ARGBAttenuateRow_MSA, 0, 4, 4, 7) #endif #ifdef HAS_ARGBATTENUATEROW_MMI ANY11(ARGBAttenuateRow_Any_MMI, ARGBAttenuateRow_MMI, 0, 4, 4, 1) #endif #ifdef HAS_ARGBEXTRACTALPHAROW_SSE2 ANY11(ARGBExtractAlphaRow_Any_SSE2, ARGBExtractAlphaRow_SSE2, 0, 4, 1, 7) #endif #ifdef HAS_ARGBEXTRACTALPHAROW_AVX2 ANY11(ARGBExtractAlphaRow_Any_AVX2, ARGBExtractAlphaRow_AVX2, 0, 4, 1, 31) #endif #ifdef HAS_ARGBEXTRACTALPHAROW_NEON ANY11(ARGBExtractAlphaRow_Any_NEON, ARGBExtractAlphaRow_NEON, 0, 4, 1, 15) #endif #ifdef HAS_ARGBEXTRACTALPHAROW_MSA ANY11(ARGBExtractAlphaRow_Any_MSA, ARGBExtractAlphaRow_MSA, 0, 4, 1, 15) #endif #ifdef HAS_ARGBEXTRACTALPHAROW_MMI ANY11(ARGBExtractAlphaRow_Any_MMI, ARGBExtractAlphaRow_MMI, 0, 4, 1, 7) #endif #undef ANY11 // Any 1 to 1 blended. Destination is read, modify, write. #define ANY11B(NAMEANY, ANY_SIMD, UVSHIFT, SBPP, BPP, MASK) \ void NAMEANY(const uint8_t* src_ptr, uint8_t* dst_ptr, int width) { \ SIMD_ALIGNED(uint8_t temp[64 * 2]); \ memset(temp, 0, 64 * 2); /* for msan */ \ int r = width & MASK; \ int n = width & ~MASK; \ if (n > 0) { \ ANY_SIMD(src_ptr, dst_ptr, n); \ } \ memcpy(temp, src_ptr + (n >> UVSHIFT) * SBPP, SS(r, UVSHIFT) * SBPP); \ memcpy(temp + 64, dst_ptr + n * BPP, r * BPP); \ ANY_SIMD(temp, temp + 64, MASK + 1); \ memcpy(dst_ptr + n * BPP, temp + 64, r * BPP); \ } #ifdef HAS_ARGBCOPYALPHAROW_AVX2 ANY11B(ARGBCopyAlphaRow_Any_AVX2, ARGBCopyAlphaRow_AVX2, 0, 4, 4, 15) #endif #ifdef HAS_ARGBCOPYALPHAROW_SSE2 ANY11B(ARGBCopyAlphaRow_Any_SSE2, ARGBCopyAlphaRow_SSE2, 0, 4, 4, 7) #endif #ifdef HAS_ARGBCOPYALPHAROW_MMI ANY11B(ARGBCopyAlphaRow_Any_MMI, ARGBCopyAlphaRow_MMI, 0, 4, 4, 1) #endif #ifdef HAS_ARGBCOPYYTOALPHAROW_AVX2 ANY11B(ARGBCopyYToAlphaRow_Any_AVX2, ARGBCopyYToAlphaRow_AVX2, 0, 1, 4, 15) #endif #ifdef HAS_ARGBCOPYYTOALPHAROW_SSE2 ANY11B(ARGBCopyYToAlphaRow_Any_SSE2, ARGBCopyYToAlphaRow_SSE2, 0, 1, 4, 7) #endif #ifdef HAS_ARGBCOPYYTOALPHAROW_MMI ANY11B(ARGBCopyYToAlphaRow_Any_MMI, ARGBCopyYToAlphaRow_MMI, 0, 1, 4, 7) #endif #undef ANY11B // Any 1 to 1 with parameter. #define ANY11P(NAMEANY, ANY_SIMD, T, SBPP, BPP, MASK) \ void NAMEANY(const uint8_t* src_ptr, uint8_t* dst_ptr, T param, int width) { \ SIMD_ALIGNED(uint8_t temp[64 * 2]); \ memset(temp, 0, 64); /* for msan */ \ int r = width & MASK; \ int n = width & ~MASK; \ if (n > 0) { \ ANY_SIMD(src_ptr, dst_ptr, param, n); \ } \ memcpy(temp, src_ptr + n * SBPP, r * SBPP); \ ANY_SIMD(temp, temp + 64, param, MASK + 1); \ memcpy(dst_ptr + n * BPP, temp + 64, r * BPP); \ } #if defined(HAS_I400TOARGBROW_SSE2) ANY11P(I400ToARGBRow_Any_SSE2, I400ToARGBRow_SSE2, const struct YuvConstants*, 1, 4, 7) #endif #if defined(HAS_I400TOARGBROW_AVX2) ANY11P(I400ToARGBRow_Any_AVX2, I400ToARGBRow_AVX2, const struct YuvConstants*, 1, 4, 15) #endif #if defined(HAS_I400TOARGBROW_NEON) ANY11P(I400ToARGBRow_Any_NEON, I400ToARGBRow_NEON, const struct YuvConstants*, 1, 4, 7) #endif #if defined(HAS_I400TOARGBROW_MSA) ANY11P(I400ToARGBRow_Any_MSA, I400ToARGBRow_MSA, const struct YuvConstants*, 1, 4, 15) #endif #if defined(HAS_I400TOARGBROW_MMI) ANY11P(I400ToARGBRow_Any_MMI, I400ToARGBRow_MMI, const struct YuvConstants*, 1, 4, 7) #endif #if defined(HAS_ARGBTORGB565DITHERROW_SSE2) ANY11P(ARGBToRGB565DitherRow_Any_SSE2, ARGBToRGB565DitherRow_SSE2, const uint32_t, 4, 2, 3) #endif #if defined(HAS_ARGBTORGB565DITHERROW_AVX2) ANY11P(ARGBToRGB565DitherRow_Any_AVX2, ARGBToRGB565DitherRow_AVX2, const uint32_t, 4, 2, 7) #endif #if defined(HAS_ARGBTORGB565DITHERROW_NEON) ANY11P(ARGBToRGB565DitherRow_Any_NEON, ARGBToRGB565DitherRow_NEON, const uint32_t, 4, 2, 7) #endif #if defined(HAS_ARGBTORGB565DITHERROW_MSA) ANY11P(ARGBToRGB565DitherRow_Any_MSA, ARGBToRGB565DitherRow_MSA, const uint32_t, 4, 2, 7) #endif #if defined(HAS_ARGBTORGB565DITHERROW_MMI) ANY11P(ARGBToRGB565DitherRow_Any_MMI, ARGBToRGB565DitherRow_MMI, const uint32_t, 4, 2, 3) #endif #ifdef HAS_ARGBSHUFFLEROW_SSSE3 ANY11P(ARGBShuffleRow_Any_SSSE3, ARGBShuffleRow_SSSE3, const uint8_t*, 4, 4, 7) #endif #ifdef HAS_ARGBSHUFFLEROW_AVX2 ANY11P(ARGBShuffleRow_Any_AVX2, ARGBShuffleRow_AVX2, const uint8_t*, 4, 4, 15) #endif #ifdef HAS_ARGBSHUFFLEROW_NEON ANY11P(ARGBShuffleRow_Any_NEON, ARGBShuffleRow_NEON, const uint8_t*, 4, 4, 3) #endif #ifdef HAS_ARGBSHUFFLEROW_MSA ANY11P(ARGBShuffleRow_Any_MSA, ARGBShuffleRow_MSA, const uint8_t*, 4, 4, 7) #endif #ifdef HAS_ARGBSHUFFLEROW_MMI ANY11P(ARGBShuffleRow_Any_MMI, ARGBShuffleRow_MMI, const uint8_t*, 4, 4, 1) #endif #undef ANY11P #undef ANY11P // Any 1 to 1 with parameter and shorts. BPP measures in shorts. #define ANY11C(NAMEANY, ANY_SIMD, SBPP, BPP, STYPE, DTYPE, MASK) \ void NAMEANY(const STYPE* src_ptr, DTYPE* dst_ptr, int scale, int width) { \ SIMD_ALIGNED(STYPE temp[32]); \ SIMD_ALIGNED(DTYPE out[32]); \ memset(temp, 0, 32 * SBPP); /* for msan */ \ int r = width & MASK; \ int n = width & ~MASK; \ if (n > 0) { \ ANY_SIMD(src_ptr, dst_ptr, scale, n); \ } \ memcpy(temp, src_ptr + n, r * SBPP); \ ANY_SIMD(temp, out, scale, MASK + 1); \ memcpy(dst_ptr + n, out, r * BPP); \ } #ifdef HAS_CONVERT16TO8ROW_SSSE3 ANY11C(Convert16To8Row_Any_SSSE3, Convert16To8Row_SSSE3, 2, 1, uint16_t, uint8_t, 15) #endif #ifdef HAS_CONVERT16TO8ROW_AVX2 ANY11C(Convert16To8Row_Any_AVX2, Convert16To8Row_AVX2, 2, 1, uint16_t, uint8_t, 31) #endif #ifdef HAS_CONVERT8TO16ROW_SSE2 ANY11C(Convert8To16Row_Any_SSE2, Convert8To16Row_SSE2, 1, 2, uint8_t, uint16_t, 15) #endif #ifdef HAS_CONVERT8TO16ROW_AVX2 ANY11C(Convert8To16Row_Any_AVX2, Convert8To16Row_AVX2, 1, 2, uint8_t, uint16_t, 31) #endif #undef ANY11C // Any 1 to 1 with parameter and shorts to byte. BPP measures in shorts. #define ANY11P16(NAMEANY, ANY_SIMD, ST, T, SBPP, BPP, MASK) \ void NAMEANY(const ST* src_ptr, T* dst_ptr, float param, int width) { \ SIMD_ALIGNED(ST temp[32]); \ SIMD_ALIGNED(T out[32]); \ memset(temp, 0, SBPP * 32); /* for msan */ \ int r = width & MASK; \ int n = width & ~MASK; \ if (n > 0) { \ ANY_SIMD(src_ptr, dst_ptr, param, n); \ } \ memcpy(temp, src_ptr + n, r * SBPP); \ ANY_SIMD(temp, out, param, MASK + 1); \ memcpy(dst_ptr + n, out, r * BPP); \ } #ifdef HAS_HALFFLOATROW_SSE2 ANY11P16(HalfFloatRow_Any_SSE2, HalfFloatRow_SSE2, uint16_t, uint16_t, 2, 2, 7) #endif #ifdef HAS_HALFFLOATROW_AVX2 ANY11P16(HalfFloatRow_Any_AVX2, HalfFloatRow_AVX2, uint16_t, uint16_t, 2, 2, 15) #endif #ifdef HAS_HALFFLOATROW_F16C ANY11P16(HalfFloatRow_Any_F16C, HalfFloatRow_F16C, uint16_t, uint16_t, 2, 2, 15) ANY11P16(HalfFloat1Row_Any_F16C, HalfFloat1Row_F16C, uint16_t, uint16_t, 2, 2, 15) #endif #ifdef HAS_HALFFLOATROW_NEON ANY11P16(HalfFloatRow_Any_NEON, HalfFloatRow_NEON, uint16_t, uint16_t, 2, 2, 7) ANY11P16(HalfFloat1Row_Any_NEON, HalfFloat1Row_NEON, uint16_t, uint16_t, 2, 2, 7) #endif #ifdef HAS_HALFFLOATROW_MSA ANY11P16(HalfFloatRow_Any_MSA, HalfFloatRow_MSA, uint16_t, uint16_t, 2, 2, 31) #endif #ifdef HAS_BYTETOFLOATROW_NEON ANY11P16(ByteToFloatRow_Any_NEON, ByteToFloatRow_NEON, uint8_t, float, 1, 3, 7) #endif #undef ANY11P16 // Any 1 to 1 with yuvconstants #define ANY11C(NAMEANY, ANY_SIMD, UVSHIFT, SBPP, BPP, MASK) \ void NAMEANY(const uint8_t* src_ptr, uint8_t* dst_ptr, \ const struct YuvConstants* yuvconstants, int width) { \ SIMD_ALIGNED(uint8_t temp[128 * 2]); \ memset(temp, 0, 128); /* for YUY2 and msan */ \ int r = width & MASK; \ int n = width & ~MASK; \ if (n > 0) { \ ANY_SIMD(src_ptr, dst_ptr, yuvconstants, n); \ } \ memcpy(temp, src_ptr + (n >> UVSHIFT) * SBPP, SS(r, UVSHIFT) * SBPP); \ ANY_SIMD(temp, temp + 128, yuvconstants, MASK + 1); \ memcpy(dst_ptr + n * BPP, temp + 128, r * BPP); \ } #if defined(HAS_YUY2TOARGBROW_SSSE3) ANY11C(YUY2ToARGBRow_Any_SSSE3, YUY2ToARGBRow_SSSE3, 1, 4, 4, 15) ANY11C(UYVYToARGBRow_Any_SSSE3, UYVYToARGBRow_SSSE3, 1, 4, 4, 15) #endif #if defined(HAS_YUY2TOARGBROW_AVX2) ANY11C(YUY2ToARGBRow_Any_AVX2, YUY2ToARGBRow_AVX2, 1, 4, 4, 31) ANY11C(UYVYToARGBRow_Any_AVX2, UYVYToARGBRow_AVX2, 1, 4, 4, 31) #endif #if defined(HAS_YUY2TOARGBROW_NEON) ANY11C(YUY2ToARGBRow_Any_NEON, YUY2ToARGBRow_NEON, 1, 4, 4, 7) ANY11C(UYVYToARGBRow_Any_NEON, UYVYToARGBRow_NEON, 1, 4, 4, 7) #endif #if defined(HAS_YUY2TOARGBROW_MSA) ANY11C(YUY2ToARGBRow_Any_MSA, YUY2ToARGBRow_MSA, 1, 4, 4, 7) ANY11C(UYVYToARGBRow_Any_MSA, UYVYToARGBRow_MSA, 1, 4, 4, 7) #endif #if defined(HAS_YUY2TOARGBROW_MMI) ANY11C(YUY2ToARGBRow_Any_MMI, YUY2ToARGBRow_MMI, 1, 4, 4, 7) ANY11C(UYVYToARGBRow_Any_MMI, UYVYToARGBRow_MMI, 1, 4, 4, 7) #endif #undef ANY11C // Any 1 to 1 interpolate. Takes 2 rows of source via stride. #define ANY11T(NAMEANY, ANY_SIMD, SBPP, BPP, MASK) \ void NAMEANY(uint8_t* dst_ptr, const uint8_t* src_ptr, \ ptrdiff_t src_stride_ptr, int width, int source_y_fraction) { \ SIMD_ALIGNED(uint8_t temp[64 * 3]); \ memset(temp, 0, 64 * 2); /* for msan */ \ int r = width & MASK; \ int n = width & ~MASK; \ if (n > 0) { \ ANY_SIMD(dst_ptr, src_ptr, src_stride_ptr, n, source_y_fraction); \ } \ memcpy(temp, src_ptr + n * SBPP, r * SBPP); \ memcpy(temp + 64, src_ptr + src_stride_ptr + n * SBPP, r * SBPP); \ ANY_SIMD(temp + 128, temp, 64, MASK + 1, source_y_fraction); \ memcpy(dst_ptr + n * BPP, temp + 128, r * BPP); \ } #ifdef HAS_INTERPOLATEROW_AVX2 ANY11T(InterpolateRow_Any_AVX2, InterpolateRow_AVX2, 1, 1, 31) #endif #ifdef HAS_INTERPOLATEROW_SSSE3 ANY11T(InterpolateRow_Any_SSSE3, InterpolateRow_SSSE3, 1, 1, 15) #endif #ifdef HAS_INTERPOLATEROW_NEON ANY11T(InterpolateRow_Any_NEON, InterpolateRow_NEON, 1, 1, 15) #endif #ifdef HAS_INTERPOLATEROW_MSA ANY11T(InterpolateRow_Any_MSA, InterpolateRow_MSA, 1, 1, 31) #endif #ifdef HAS_INTERPOLATEROW_MMI ANY11T(InterpolateRow_Any_MMI, InterpolateRow_MMI, 1, 1, 7) #endif #undef ANY11T // Any 1 to 1 mirror. #define ANY11M(NAMEANY, ANY_SIMD, BPP, MASK) \ void NAMEANY(const uint8_t* src_ptr, uint8_t* dst_ptr, int width) { \ SIMD_ALIGNED(uint8_t temp[64 * 2]); \ memset(temp, 0, 64); /* for msan */ \ int r = width & MASK; \ int n = width & ~MASK; \ if (n > 0) { \ ANY_SIMD(src_ptr + r * BPP, dst_ptr, n); \ } \ memcpy(temp, src_ptr, r* BPP); \ ANY_SIMD(temp, temp + 64, MASK + 1); \ memcpy(dst_ptr + n * BPP, temp + 64 + (MASK + 1 - r) * BPP, r * BPP); \ } #ifdef HAS_MIRRORROW_AVX2 ANY11M(MirrorRow_Any_AVX2, MirrorRow_AVX2, 1, 31) #endif #ifdef HAS_MIRRORROW_SSSE3 ANY11M(MirrorRow_Any_SSSE3, MirrorRow_SSSE3, 1, 15) #endif #ifdef HAS_MIRRORROW_NEON ANY11M(MirrorRow_Any_NEON, MirrorRow_NEON, 1, 31) #endif #ifdef HAS_MIRRORROW_MSA ANY11M(MirrorRow_Any_MSA, MirrorRow_MSA, 1, 63) #endif #ifdef HAS_MIRRORROW_MMI ANY11M(MirrorRow_Any_MMI, MirrorRow_MMI, 1, 7) #endif #ifdef HAS_MIRRORUVROW_AVX2 ANY11M(MirrorUVRow_Any_AVX2, MirrorUVRow_AVX2, 2, 15) #endif #ifdef HAS_MIRRORUVROW_SSSE3 ANY11M(MirrorUVRow_Any_SSSE3, MirrorUVRow_SSSE3, 2, 7) #endif #ifdef HAS_MIRRORUVROW_NEON ANY11M(MirrorUVRow_Any_NEON, MirrorUVRow_NEON, 2, 31) #endif #ifdef HAS_MIRRORUVROW_MSA ANY11M(MirrorUVRow_Any_MSA, MirrorUVRow_MSA, 2, 7) #endif #ifdef HAS_ARGBMIRRORROW_AVX2 ANY11M(ARGBMirrorRow_Any_AVX2, ARGBMirrorRow_AVX2, 4, 7) #endif #ifdef HAS_ARGBMIRRORROW_SSE2 ANY11M(ARGBMirrorRow_Any_SSE2, ARGBMirrorRow_SSE2, 4, 3) #endif #ifdef HAS_ARGBMIRRORROW_NEON ANY11M(ARGBMirrorRow_Any_NEON, ARGBMirrorRow_NEON, 4, 7) #endif #ifdef HAS_ARGBMIRRORROW_MSA ANY11M(ARGBMirrorRow_Any_MSA, ARGBMirrorRow_MSA, 4, 15) #endif #ifdef HAS_ARGBMIRRORROW_MMI ANY11M(ARGBMirrorRow_Any_MMI, ARGBMirrorRow_MMI, 4, 1) #endif #ifdef HAS_RGB24MIRRORROW_SSSE3 ANY11M(RGB24MirrorRow_Any_SSSE3, RGB24MirrorRow_SSSE3, 3, 15) #endif #ifdef HAS_RGB24MIRRORROW_NEON ANY11M(RGB24MirrorRow_Any_NEON, RGB24MirrorRow_NEON, 3, 15) #endif #undef ANY11M // Any 1 plane. (memset) #define ANY1(NAMEANY, ANY_SIMD, T, BPP, MASK) \ void NAMEANY(uint8_t* dst_ptr, T v32, int width) { \ SIMD_ALIGNED(uint8_t temp[64]); \ memset(temp, 0, 64); /* for msan */ \ int r = width & MASK; \ int n = width & ~MASK; \ if (n > 0) { \ ANY_SIMD(dst_ptr, v32, n); \ } \ ANY_SIMD(temp, v32, MASK + 1); \ memcpy(dst_ptr + n * BPP, temp, r * BPP); \ } #ifdef HAS_SETROW_X86 ANY1(SetRow_Any_X86, SetRow_X86, uint8_t, 1, 3) #endif #ifdef HAS_SETROW_NEON ANY1(SetRow_Any_NEON, SetRow_NEON, uint8_t, 1, 15) #endif #ifdef HAS_ARGBSETROW_NEON ANY1(ARGBSetRow_Any_NEON, ARGBSetRow_NEON, uint32_t, 4, 3) #endif #ifdef HAS_ARGBSETROW_MSA ANY1(ARGBSetRow_Any_MSA, ARGBSetRow_MSA, uint32_t, 4, 3) #endif #ifdef HAS_ARGBSETROW_MMI ANY1(ARGBSetRow_Any_MMI, ARGBSetRow_MMI, uint32_t, 4, 3) #endif #undef ANY1 // Any 1 to 2. Outputs UV planes. #define ANY12(NAMEANY, ANY_SIMD, UVSHIFT, BPP, DUVSHIFT, MASK) \ void NAMEANY(const uint8_t* src_ptr, uint8_t* dst_u, uint8_t* dst_v, \ int width) { \ SIMD_ALIGNED(uint8_t temp[128 * 3]); \ memset(temp, 0, 128); /* for msan */ \ int r = width & MASK; \ int n = width & ~MASK; \ if (n > 0) { \ ANY_SIMD(src_ptr, dst_u, dst_v, n); \ } \ memcpy(temp, src_ptr + (n >> UVSHIFT) * BPP, SS(r, UVSHIFT) * BPP); \ ANY_SIMD(temp, temp + 128, temp + 256, MASK + 1); \ memcpy(dst_u + (n >> DUVSHIFT), temp + 128, SS(r, DUVSHIFT)); \ memcpy(dst_v + (n >> DUVSHIFT), temp + 256, SS(r, DUVSHIFT)); \ } #ifdef HAS_SPLITUVROW_SSE2 ANY12(SplitUVRow_Any_SSE2, SplitUVRow_SSE2, 0, 2, 0, 15) #endif #ifdef HAS_SPLITUVROW_AVX2 ANY12(SplitUVRow_Any_AVX2, SplitUVRow_AVX2, 0, 2, 0, 31) #endif #ifdef HAS_SPLITUVROW_NEON ANY12(SplitUVRow_Any_NEON, SplitUVRow_NEON, 0, 2, 0, 15) #endif #ifdef HAS_SPLITUVROW_MSA ANY12(SplitUVRow_Any_MSA, SplitUVRow_MSA, 0, 2, 0, 31) #endif #ifdef HAS_SPLITUVROW_MMI ANY12(SplitUVRow_Any_MMI, SplitUVRow_MMI, 0, 2, 0, 7) #endif #ifdef HAS_ARGBTOUV444ROW_SSSE3 ANY12(ARGBToUV444Row_Any_SSSE3, ARGBToUV444Row_SSSE3, 0, 4, 0, 15) #endif #ifdef HAS_YUY2TOUV422ROW_AVX2 ANY12(YUY2ToUV422Row_Any_AVX2, YUY2ToUV422Row_AVX2, 1, 4, 1, 31) ANY12(UYVYToUV422Row_Any_AVX2, UYVYToUV422Row_AVX2, 1, 4, 1, 31) #endif #ifdef HAS_YUY2TOUV422ROW_SSE2 ANY12(YUY2ToUV422Row_Any_SSE2, YUY2ToUV422Row_SSE2, 1, 4, 1, 15) ANY12(UYVYToUV422Row_Any_SSE2, UYVYToUV422Row_SSE2, 1, 4, 1, 15) #endif #ifdef HAS_YUY2TOUV422ROW_NEON ANY12(ARGBToUV444Row_Any_NEON, ARGBToUV444Row_NEON, 0, 4, 0, 7) ANY12(YUY2ToUV422Row_Any_NEON, YUY2ToUV422Row_NEON, 1, 4, 1, 15) ANY12(UYVYToUV422Row_Any_NEON, UYVYToUV422Row_NEON, 1, 4, 1, 15) #endif #ifdef HAS_YUY2TOUV422ROW_MSA ANY12(ARGBToUV444Row_Any_MSA, ARGBToUV444Row_MSA, 0, 4, 0, 15) ANY12(YUY2ToUV422Row_Any_MSA, YUY2ToUV422Row_MSA, 1, 4, 1, 31) ANY12(UYVYToUV422Row_Any_MSA, UYVYToUV422Row_MSA, 1, 4, 1, 31) #endif #ifdef HAS_YUY2TOUV422ROW_MMI ANY12(ARGBToUV444Row_Any_MMI, ARGBToUV444Row_MMI, 0, 4, 0, 7) ANY12(UYVYToUV422Row_Any_MMI, UYVYToUV422Row_MMI, 1, 4, 1, 15) ANY12(YUY2ToUV422Row_Any_MMI, YUY2ToUV422Row_MMI, 1, 4, 1, 15) #endif #undef ANY12 // Any 1 to 3. Outputs RGB planes. #define ANY13(NAMEANY, ANY_SIMD, BPP, MASK) \ void NAMEANY(const uint8_t* src_ptr, uint8_t* dst_r, uint8_t* dst_g, \ uint8_t* dst_b, int width) { \ SIMD_ALIGNED(uint8_t temp[16 * 6]); \ memset(temp, 0, 16 * 3); /* for msan */ \ int r = width & MASK; \ int n = width & ~MASK; \ if (n > 0) { \ ANY_SIMD(src_ptr, dst_r, dst_g, dst_b, n); \ } \ memcpy(temp, src_ptr + n * BPP, r * BPP); \ ANY_SIMD(temp, temp + 16 * 3, temp + 16 * 4, temp + 16 * 5, MASK + 1); \ memcpy(dst_r + n, temp + 16 * 3, r); \ memcpy(dst_g + n, temp + 16 * 4, r); \ memcpy(dst_b + n, temp + 16 * 5, r); \ } #ifdef HAS_SPLITRGBROW_SSSE3 ANY13(SplitRGBRow_Any_SSSE3, SplitRGBRow_SSSE3, 3, 15) #endif #ifdef HAS_SPLITRGBROW_NEON ANY13(SplitRGBRow_Any_NEON, SplitRGBRow_NEON, 3, 15) #endif #ifdef HAS_SPLITRGBROW_MMI ANY13(SplitRGBRow_Any_MMI, SplitRGBRow_MMI, 3, 3) #endif // Any 1 to 2 with source stride (2 rows of source). Outputs UV planes. // 128 byte row allows for 32 avx ARGB pixels. #define ANY12S(NAMEANY, ANY_SIMD, UVSHIFT, BPP, MASK) \ void NAMEANY(const uint8_t* src_ptr, int src_stride_ptr, uint8_t* dst_u, \ uint8_t* dst_v, int width) { \ SIMD_ALIGNED(uint8_t temp[128 * 4]); \ memset(temp, 0, 128 * 2); /* for msan */ \ int r = width & MASK; \ int n = width & ~MASK; \ if (n > 0) { \ ANY_SIMD(src_ptr, src_stride_ptr, dst_u, dst_v, n); \ } \ memcpy(temp, src_ptr + (n >> UVSHIFT) * BPP, SS(r, UVSHIFT) * BPP); \ memcpy(temp + 128, src_ptr + src_stride_ptr + (n >> UVSHIFT) * BPP, \ SS(r, UVSHIFT) * BPP); \ if ((width & 1) && UVSHIFT == 0) { /* repeat last pixel for subsample */ \ memcpy(temp + SS(r, UVSHIFT) * BPP, temp + SS(r, UVSHIFT) * BPP - BPP, \ BPP); \ memcpy(temp + 128 + SS(r, UVSHIFT) * BPP, \ temp + 128 + SS(r, UVSHIFT) * BPP - BPP, BPP); \ } \ ANY_SIMD(temp, 128, temp + 256, temp + 384, MASK + 1); \ memcpy(dst_u + (n >> 1), temp + 256, SS(r, 1)); \ memcpy(dst_v + (n >> 1), temp + 384, SS(r, 1)); \ } #ifdef HAS_ARGBTOUVROW_AVX2 ANY12S(ARGBToUVRow_Any_AVX2, ARGBToUVRow_AVX2, 0, 4, 31) #endif #ifdef HAS_ABGRTOUVROW_AVX2 ANY12S(ABGRToUVRow_Any_AVX2, ABGRToUVRow_AVX2, 0, 4, 31) #endif #ifdef HAS_ARGBTOUVJROW_AVX2 ANY12S(ARGBToUVJRow_Any_AVX2, ARGBToUVJRow_AVX2, 0, 4, 31) #endif #ifdef HAS_ARGBTOUVROW_SSSE3 ANY12S(ARGBToUVRow_Any_SSSE3, ARGBToUVRow_SSSE3, 0, 4, 15) ANY12S(ARGBToUVJRow_Any_SSSE3, ARGBToUVJRow_SSSE3, 0, 4, 15) ANY12S(BGRAToUVRow_Any_SSSE3, BGRAToUVRow_SSSE3, 0, 4, 15) ANY12S(ABGRToUVRow_Any_SSSE3, ABGRToUVRow_SSSE3, 0, 4, 15) ANY12S(RGBAToUVRow_Any_SSSE3, RGBAToUVRow_SSSE3, 0, 4, 15) #endif #ifdef HAS_YUY2TOUVROW_AVX2 ANY12S(YUY2ToUVRow_Any_AVX2, YUY2ToUVRow_AVX2, 1, 4, 31) ANY12S(UYVYToUVRow_Any_AVX2, UYVYToUVRow_AVX2, 1, 4, 31) #endif #ifdef HAS_YUY2TOUVROW_SSE2 ANY12S(YUY2ToUVRow_Any_SSE2, YUY2ToUVRow_SSE2, 1, 4, 15) ANY12S(UYVYToUVRow_Any_SSE2, UYVYToUVRow_SSE2, 1, 4, 15) #endif #ifdef HAS_ARGBTOUVROW_NEON ANY12S(ARGBToUVRow_Any_NEON, ARGBToUVRow_NEON, 0, 4, 15) #endif #ifdef HAS_ARGBTOUVROW_MSA ANY12S(ARGBToUVRow_Any_MSA, ARGBToUVRow_MSA, 0, 4, 31) #endif #ifdef HAS_ARGBTOUVROW_MMI ANY12S(ARGBToUVRow_Any_MMI, ARGBToUVRow_MMI, 0, 4, 15) #endif #ifdef HAS_ARGBTOUVJROW_NEON ANY12S(ARGBToUVJRow_Any_NEON, ARGBToUVJRow_NEON, 0, 4, 15) #endif #ifdef HAS_ARGBTOUVJROW_MSA ANY12S(ARGBToUVJRow_Any_MSA, ARGBToUVJRow_MSA, 0, 4, 31) #endif #ifdef HAS_ARGBTOUVJROW_MMI ANY12S(ARGBToUVJRow_Any_MMI, ARGBToUVJRow_MMI, 0, 4, 15) #endif #ifdef HAS_BGRATOUVROW_NEON ANY12S(BGRAToUVRow_Any_NEON, BGRAToUVRow_NEON, 0, 4, 15) #endif #ifdef HAS_BGRATOUVROW_MSA ANY12S(BGRAToUVRow_Any_MSA, BGRAToUVRow_MSA, 0, 4, 15) #endif #ifdef HAS_BGRATOUVROW_MMI ANY12S(BGRAToUVRow_Any_MMI, BGRAToUVRow_MMI, 0, 4, 15) #endif #ifdef HAS_ABGRTOUVROW_NEON ANY12S(ABGRToUVRow_Any_NEON, ABGRToUVRow_NEON, 0, 4, 15) #endif #ifdef HAS_ABGRTOUVROW_MSA ANY12S(ABGRToUVRow_Any_MSA, ABGRToUVRow_MSA, 0, 4, 15) #endif #ifdef HAS_ABGRTOUVROW_MMI ANY12S(ABGRToUVRow_Any_MMI, ABGRToUVRow_MMI, 0, 4, 15) #endif #ifdef HAS_RGBATOUVROW_NEON ANY12S(RGBAToUVRow_Any_NEON, RGBAToUVRow_NEON, 0, 4, 15) #endif #ifdef HAS_RGBATOUVROW_MSA ANY12S(RGBAToUVRow_Any_MSA, RGBAToUVRow_MSA, 0, 4, 15) #endif #ifdef HAS_RGBATOUVROW_MMI ANY12S(RGBAToUVRow_Any_MMI, RGBAToUVRow_MMI, 0, 4, 15) #endif #ifdef HAS_RGB24TOUVROW_NEON ANY12S(RGB24ToUVRow_Any_NEON, RGB24ToUVRow_NEON, 0, 3, 15) #endif #ifdef HAS_RGB24TOUVROW_MSA ANY12S(RGB24ToUVRow_Any_MSA, RGB24ToUVRow_MSA, 0, 3, 15) #endif #ifdef HAS_RGB24TOUVROW_MMI ANY12S(RGB24ToUVRow_Any_MMI, RGB24ToUVRow_MMI, 0, 3, 15) #endif #ifdef HAS_RAWTOUVROW_NEON ANY12S(RAWToUVRow_Any_NEON, RAWToUVRow_NEON, 0, 3, 15) #endif #ifdef HAS_RAWTOUVROW_MSA ANY12S(RAWToUVRow_Any_MSA, RAWToUVRow_MSA, 0, 3, 15) #endif #ifdef HAS_RAWTOUVROW_MMI ANY12S(RAWToUVRow_Any_MMI, RAWToUVRow_MMI, 0, 3, 15) #endif #ifdef HAS_RGB565TOUVROW_NEON ANY12S(RGB565ToUVRow_Any_NEON, RGB565ToUVRow_NEON, 0, 2, 15) #endif #ifdef HAS_RGB565TOUVROW_MSA ANY12S(RGB565ToUVRow_Any_MSA, RGB565ToUVRow_MSA, 0, 2, 15) #endif #ifdef HAS_RGB565TOUVROW_MMI ANY12S(RGB565ToUVRow_Any_MMI, RGB565ToUVRow_MMI, 0, 2, 15) #endif #ifdef HAS_ARGB1555TOUVROW_NEON ANY12S(ARGB1555ToUVRow_Any_NEON, ARGB1555ToUVRow_NEON, 0, 2, 15) #endif #ifdef HAS_ARGB1555TOUVROW_MSA ANY12S(ARGB1555ToUVRow_Any_MSA, ARGB1555ToUVRow_MSA, 0, 2, 15) #endif #ifdef HAS_ARGB1555TOUVROW_MMI ANY12S(ARGB1555ToUVRow_Any_MMI, ARGB1555ToUVRow_MMI, 0, 2, 15) #endif #ifdef HAS_ARGB4444TOUVROW_NEON ANY12S(ARGB4444ToUVRow_Any_NEON, ARGB4444ToUVRow_NEON, 0, 2, 15) #endif #ifdef HAS_ARGB4444TOUVROW_MMI ANY12S(ARGB4444ToUVRow_Any_MMI, ARGB4444ToUVRow_MMI, 0, 2, 15) #endif #ifdef HAS_YUY2TOUVROW_NEON ANY12S(YUY2ToUVRow_Any_NEON, YUY2ToUVRow_NEON, 1, 4, 15) #endif #ifdef HAS_UYVYTOUVROW_NEON ANY12S(UYVYToUVRow_Any_NEON, UYVYToUVRow_NEON, 1, 4, 15) #endif #ifdef HAS_YUY2TOUVROW_MSA ANY12S(YUY2ToUVRow_Any_MSA, YUY2ToUVRow_MSA, 1, 4, 31) #endif #ifdef HAS_YUY2TOUVROW_MMI ANY12S(YUY2ToUVRow_Any_MMI, YUY2ToUVRow_MMI, 1, 4, 15) #endif #ifdef HAS_UYVYTOUVROW_MSA ANY12S(UYVYToUVRow_Any_MSA, UYVYToUVRow_MSA, 1, 4, 31) #endif #ifdef HAS_UYVYTOUVROW_MMI ANY12S(UYVYToUVRow_Any_MMI, UYVYToUVRow_MMI, 1, 4, 15) #endif #undef ANY12S // Any 1 to 1 with source stride (2 rows of source). Outputs UV plane. // 128 byte row allows for 32 avx ARGB pixels. #define ANY11S(NAMEANY, ANY_SIMD, UVSHIFT, BPP, MASK) \ void NAMEANY(const uint8_t* src_ptr, int src_stride_ptr, uint8_t* dst_vu, \ int width) { \ SIMD_ALIGNED(uint8_t temp[128 * 3]); \ memset(temp, 0, 128 * 2); /* for msan */ \ int r = width & MASK; \ int n = width & ~MASK; \ if (n > 0) { \ ANY_SIMD(src_ptr, src_stride_ptr, dst_vu, n); \ } \ memcpy(temp, src_ptr + (n >> UVSHIFT) * BPP, SS(r, UVSHIFT) * BPP); \ memcpy(temp + 128, src_ptr + src_stride_ptr + (n >> UVSHIFT) * BPP, \ SS(r, UVSHIFT) * BPP); \ if ((width & 1) && UVSHIFT == 0) { /* repeat last pixel for subsample */ \ memcpy(temp + SS(r, UVSHIFT) * BPP, temp + SS(r, UVSHIFT) * BPP - BPP, \ BPP); \ memcpy(temp + 128 + SS(r, UVSHIFT) * BPP, \ temp + 128 + SS(r, UVSHIFT) * BPP - BPP, BPP); \ } \ ANY_SIMD(temp, 128, temp + 256, MASK + 1); \ memcpy(dst_vu + (n >> 1) * 2, temp + 256, SS(r, 1) * 2); \ } #ifdef HAS_AYUVTOVUROW_NEON ANY11S(AYUVToUVRow_Any_NEON, AYUVToUVRow_NEON, 0, 4, 15) ANY11S(AYUVToVURow_Any_NEON, AYUVToVURow_NEON, 0, 4, 15) #endif #undef ANY11S #ifdef __cplusplus } // extern "C" } // namespace libyuv #endif
41.233525
81
0.618049
onbings
78142d53c21ca7dfea78155d55bdb6ca0c106423
395
cc
C++
accumulate.cc
tonioc987/ejemplos-blog
315f8e8049953b076a0a8275413ff4ad568a705a
[ "MIT" ]
null
null
null
accumulate.cc
tonioc987/ejemplos-blog
315f8e8049953b076a0a8275413ff4ad568a705a
[ "MIT" ]
null
null
null
accumulate.cc
tonioc987/ejemplos-blog
315f8e8049953b076a0a8275413ff4ad568a705a
[ "MIT" ]
null
null
null
#include <iostream> #include <algorithm> using namespace std; int main() { #define N_ELEMENTS 100000000UL long * values = new long[N_ELEMENTS]; iota(values, values+N_ELEMENTS, 1); long result = accumulate(values, values+N_ELEMENTS, 0); cout << "resultado= " << result << endl; result = accumulate(values, values+N_ELEMENTS, 0L); cout << "resultado= " << result << endl; }
21.944444
57
0.670886
tonioc987
7816595fcf9ea3de92ea24ec598290198e633ec6
1,731
cpp
C++
Sources/Internal/Platform/TemplateAndroid/FileListAndroid.cpp
Serviak/dava.engine
d51a26173a3e1b36403f846ca3b2e183ac298a1a
[ "BSD-3-Clause" ]
1
2020-11-14T10:18:24.000Z
2020-11-14T10:18:24.000Z
Sources/Internal/Platform/TemplateAndroid/FileListAndroid.cpp
Serviak/dava.engine
d51a26173a3e1b36403f846ca3b2e183ac298a1a
[ "BSD-3-Clause" ]
null
null
null
Sources/Internal/Platform/TemplateAndroid/FileListAndroid.cpp
Serviak/dava.engine
d51a26173a3e1b36403f846ca3b2e183ac298a1a
[ "BSD-3-Clause" ]
1
2020-09-05T21:16:17.000Z
2020-09-05T21:16:17.000Z
#include "Platform/TemplateAndroid/FileListAndroid.h" #if defined(__DAVAENGINE_ANDROID__) #include "Logger/Logger.h" namespace DAVA { JniFileList::JniFileList() : jniFileList("com/dava/framework/JNIFileList") { getFileList = jniFileList.GetStaticMethod<jobjectArray, jstring>("GetFileList"); } Vector<JniFileList::JniFileListEntry> JniFileList::GetFileList(const String& path) { Vector<JniFileList::JniFileListEntry> fileList; JNIEnv* env = JNI::GetEnv(); JNI::LocalRef<jstring> jPath = env->NewStringUTF(path.c_str()); JNI::LocalRef<jobjectArray> jArray = getFileList(jPath); if (jArray) { jsize size = env->GetArrayLength(jArray); for (jsize i = 0; i < size; ++i) { JNI::LocalRef<jobject> item = env->GetObjectArrayElement(jArray, i); JNI::LocalRef<jclass> cls = env->GetObjectClass(item); jfieldID jNameField = env->GetFieldID(cls, "name", JNI::TypeSignature<jstring>::value()); jfieldID jSizeField = env->GetFieldID(cls, "size", JNI::TypeSignature<jlong>::value()); jfieldID jIsDirectoryField = env->GetFieldID(cls, "isDirectory", JNI::TypeSignature<jboolean>::value()); jlong jSize = env->GetLongField(item, jSizeField); jboolean jIsDir = env->GetBooleanField(item, jIsDirectoryField); JNI::LocalRef<jstring> jName = static_cast<jstring>(env->GetObjectField(item, jNameField)); JniFileListEntry entry; entry.name = JNI::ToString(jName); entry.size = jSize; entry.isDirectory = jIsDir; fileList.push_back(entry); } } return fileList; } } //namespace DAVA #endif // __DAVAENGINE_ANDROID__
33.288462
116
0.659157
Serviak
78195397b8537f10606ec21487fc7bfbcde17408
5,522
cpp
C++
amr-wind/wind_energy/actuator/turbine/turbine_utils.cpp
tonyinme/amr-wind
d04841d20082236e8afed860fdcfb7a69cd5591c
[ "BSD-3-Clause" ]
null
null
null
amr-wind/wind_energy/actuator/turbine/turbine_utils.cpp
tonyinme/amr-wind
d04841d20082236e8afed860fdcfb7a69cd5591c
[ "BSD-3-Clause" ]
null
null
null
amr-wind/wind_energy/actuator/turbine/turbine_utils.cpp
tonyinme/amr-wind
d04841d20082236e8afed860fdcfb7a69cd5591c
[ "BSD-3-Clause" ]
null
null
null
#include "amr-wind/wind_energy/actuator/turbine/turbine_utils.H" #include "amr-wind/utilities/ncutils/nc_interface.H" #include "amr-wind/utilities/io_utils.H" namespace amr_wind { namespace actuator { namespace utils { void read_inputs( TurbineBaseData& tdata, TurbineInfo& tinfo, const utils::ActParser& pp) { pp.query("num_blades", tdata.num_blades); pp.get("num_points_blade", tdata.num_pts_blade); pp.get("num_points_tower", tdata.num_pts_tower); pp.query("nacelle_area", tdata.nacelle_area); pp.query("nacelle_drag_coeff", tdata.nacelle_cd); if (!pp.contains("epsilon") && !pp.contains("epsilon_chord")) { amrex::Abort( "Actuator turbine simulations require specification of one or both " "of 'epsilon' or 'epsilon_chord'"); } pp.query("epsilon", tdata.eps_inp); pp.query("epsilon_chord", tdata.eps_chord); pp.query("epsilon_min", tdata.eps_min); pp.query("epsilon_tower", tdata.eps_tower); pp.get("base_position", tinfo.base_pos); pp.get("rotor_diameter", tinfo.rotor_diameter); pp.get("hub_height", tinfo.hub_height); // clang-format off const auto& bp = tinfo.base_pos; const auto& rad = 0.5 * tinfo.rotor_diameter; const auto& hh = tinfo.hub_height; tinfo.bound_box = amrex::RealBox( bp.x() - 1.25 * rad, bp.y() - 1.25 * rad, bp.z() - 1.25 * rad, bp.x() + 1.25 * rad, bp.y() + 1.25 * rad, bp.z() + 1.25 * rad + hh ); // clang-format on } void prepare_netcdf_file( const std::string& ncfile, const TurbineBaseData& meta, const TurbineInfo& info, const ActGrid& grid) { #ifdef AMR_WIND_USE_NETCDF // Only root process handles I/O if (!info.is_root_proc) return; auto ncf = ncutils::NCFile::create(ncfile, NC_CLOBBER | NC_NETCDF4); const std::string nt_name = "num_time_steps"; const std::string np_name = "num_actuator_points"; const std::string nvel_name = "num_vel_points"; const std::vector<std::string> two_dim{nt_name, np_name}; ncf.enter_def_mode(); ncf.put_attr("title", "AMR-Wind turbine actuator output"); ncf.put_attr("version", ioutils::amr_wind_version()); ncf.put_attr("created_on", ioutils::timestamp()); ncf.def_dim(nt_name, NC_UNLIMITED); ncf.def_dim("ndim", AMREX_SPACEDIM); ncf.def_dim("mat_dim", AMREX_SPACEDIM * AMREX_SPACEDIM); auto grp = ncf.def_group(info.label); grp.put_attr("num_blades", std::vector<int>{meta.num_blades}); grp.put_attr("num_points_blade", std::vector<int>{meta.num_pts_blade}); grp.put_attr("num_points_tower", std::vector<int>{meta.num_pts_tower}); grp.put_attr("rotor_diameter", std::vector<double>{info.rotor_diameter}); grp.put_attr("hub_height", std::vector<double>{info.hub_height}); // clang-format off grp.put_attr("base_location", std::vector<double>{ info.base_pos.x(), info.base_pos.y(), info.base_pos.z()}); // clang-format on const size_t nfpts = grid.force.size(); const size_t nvpts = grid.vel.size(); grp.def_dim(np_name, nfpts); grp.def_dim(nvel_name, nvpts); grp.def_var("time", NC_DOUBLE, {nt_name}); grp.def_var("chord", NC_DOUBLE, {np_name}); grp.def_var("epsilon", NC_DOUBLE, {np_name, "ndim"}); grp.def_var("rot_center", NC_DOUBLE, {nt_name, "ndim"}); grp.def_var("rotor_frame", NC_DOUBLE, {nt_name, "mat_dim"}); grp.def_var("xyz", NC_DOUBLE, {nt_name, np_name, "ndim"}); grp.def_var("force", NC_DOUBLE, {nt_name, np_name, "ndim"}); grp.def_var("orientation", NC_DOUBLE, {nt_name, np_name, "mat_dim"}); grp.def_var("vel_xyz", NC_DOUBLE, {nt_name, nvel_name, "ndim"}); grp.def_var("vel", NC_DOUBLE, {nt_name, nvel_name, "ndim"}); ncf.exit_def_mode(); { auto chord = grp.var("chord"); chord.put(&(meta.chord[0]), {0}, {nfpts}); auto eps = grp.var("epsilon"); eps.put(&(grid.epsilon[0][0]), {0, 0}, {nfpts, AMREX_SPACEDIM}); } #else amrex::ignore_unused(ncfile, meta, info, grid); #endif } void write_netcdf( const std::string& ncfile, const TurbineBaseData& meta, const TurbineInfo& info, const ActGrid& grid, const amrex::Real time) { #ifdef AMR_WIND_USE_NETCDF // Only root process handles I/O if (!info.is_root_proc) return; auto ncf = ncutils::NCFile::open(ncfile, NC_WRITE); const std::string nt_name = "num_time_steps"; const std::string np_name = "num_actuator_points"; const std::string nvel_name = "num_vel_points"; // Index of next timestep const size_t nt = ncf.dim(nt_name).len(); const size_t nfpts = grid.force.size(); const size_t nvpts = grid.vel.size(); auto grp = ncf.group(info.label); grp.var("time").put(&time, {nt}, {1}); grp.var("rot_center").put(&(meta.rot_center[0]), {nt, 0}, {1, 3}); grp.var("rotor_frame").put(&(meta.rotor_frame[0]), {nt, 0}, {1, 9}); grp.var("xyz").put( &(grid.pos[0][0]), {nt, 0, 0}, {1, nfpts, AMREX_SPACEDIM}); grp.var("force").put( &(grid.force[0][0]), {nt, 0, 0}, {1, nfpts, AMREX_SPACEDIM}); grp.var("orientation") .put(&(grid.orientation[0][0]), {nt, 0, 0}, {1, nfpts, 9}); grp.var("vel_xyz").put( &(grid.vel_pos[0][0]), {nt, 0, 0}, {1, nvpts, AMREX_SPACEDIM}); grp.var("vel").put( &(grid.vel[0][0]), {nt, 0, 0}, {1, nvpts, AMREX_SPACEDIM}); #else amrex::ignore_unused(ncfile, meta, info, grid, time); #endif } } // namespace utils } // namespace actuator } // namespace amr_wind
37.060403
80
0.647954
tonyinme
781ecc2e7ba2332e24cb142ac2365bb59538bbdf
4,064
cc
C++
src/gpu-compute/register_manager.cc
fei-shan/gem5-experiment
70781db30d42b1fe50e495bd04f7755a4b0e0e59
[ "BSD-3-Clause" ]
1
2021-05-04T13:23:30.000Z
2021-05-04T13:23:30.000Z
src/gpu-compute/register_manager.cc
fei-shan/gem5-experiment
70781db30d42b1fe50e495bd04f7755a4b0e0e59
[ "BSD-3-Clause" ]
1
2021-04-17T17:13:56.000Z
2021-04-17T17:13:56.000Z
src/gpu-compute/register_manager.cc
fei-shan/gem5-experiment
70781db30d42b1fe50e495bd04f7755a4b0e0e59
[ "BSD-3-Clause" ]
1
2021-08-23T05:37:55.000Z
2021-08-23T05:37:55.000Z
/* * Copyright (c) 2016, 2017 Advanced Micro Devices, Inc. * All rights reserved. * * For use for simulation and test purposes only * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Author: Mark Wyse */ #include "gpu-compute/register_manager.hh" #include "config/the_gpu_isa.hh" #include "debug/GPURename.hh" #include "gpu-compute/compute_unit.hh" #include "gpu-compute/scalar_register_file.hh" #include "gpu-compute/static_register_manager_policy.hh" #include "gpu-compute/vector_register_file.hh" #include "gpu-compute/wavefront.hh" #include "params/RegisterManager.hh" RegisterManager::RegisterManager(const RegisterManagerParams &p) : SimObject(p), srfPoolMgrs(p.srf_pool_managers), vrfPoolMgrs(p.vrf_pool_managers) { if (p.policy == "static") { policy = new StaticRegisterManagerPolicy(); } else { fatal("Unimplemented Register Manager Policy"); } } RegisterManager::~RegisterManager() { for (auto mgr : srfPoolMgrs) { delete mgr; } for (auto mgr : vrfPoolMgrs) { delete mgr; } } void RegisterManager::exec() { policy->exec(); } void RegisterManager::setParent(ComputeUnit *cu) { computeUnit = cu; policy->setParent(computeUnit); for (int i = 0; i < srfPoolMgrs.size(); i++) { fatal_if(computeUnit->srf[i]->numRegs() % srfPoolMgrs[i]->minAllocation(), "Min SGPR allocation is not multiple of VRF size\n"); } for (int i = 0; i < vrfPoolMgrs.size(); i++) { fatal_if(computeUnit->vrf[i]->numRegs() % vrfPoolMgrs[i]->minAllocation(), "Min VGPG allocation is not multiple of VRF size\n"); } } // compute mapping for vector register int RegisterManager::mapVgpr(Wavefront* w, int vgprIndex) { return policy->mapVgpr(w, vgprIndex); } // compute mapping for scalar register int RegisterManager::mapSgpr(Wavefront* w, int sgprIndex) { return policy->mapSgpr(w, sgprIndex); } // check if we can allocate registers bool RegisterManager::canAllocateVgprs(int simdId, int nWfs, int demandPerWf) { return policy->canAllocateVgprs(simdId, nWfs, demandPerWf); } bool RegisterManager::canAllocateSgprs(int simdId, int nWfs, int demandPerWf) { return policy->canAllocateSgprs(simdId, nWfs, demandPerWf); } // allocate registers void RegisterManager::allocateRegisters(Wavefront *w, int vectorDemand, int scalarDemand) { policy->allocateRegisters(w, vectorDemand, scalarDemand); } void RegisterManager::freeRegisters(Wavefront* w) { policy->freeRegisters(w); }
30.787879
79
0.71752
fei-shan
781f10cbb0551618fe311ff6297cbb2bb7fdfdc2
6,102
hpp
C++
read-excel/record.hpp
AlexZaikaSay/read-excel
2d33f324dbffc97d04096a01a6429ab045fce97c
[ "MIT" ]
null
null
null
read-excel/record.hpp
AlexZaikaSay/read-excel
2d33f324dbffc97d04096a01a6429ab045fce97c
[ "MIT" ]
null
null
null
read-excel/record.hpp
AlexZaikaSay/read-excel
2d33f324dbffc97d04096a01a6429ab045fce97c
[ "MIT" ]
null
null
null
/*! \file \brief Excel Record. \author Igor Mironchik (igor.mironchik at gmail dot com). Copyright (c) 2011-2021 Igor Mironchik 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. */ #ifndef EXCEL__RECORD_HPP__INCLUDED #define EXCEL__RECORD_HPP__INCLUDED // Excel include. #include "stream.hpp" #include "exceptions.hpp" // C++ include. #include <vector> #include <sstream> namespace Excel { // // RecordSubstream // class RecordSubstream : public Stream { friend class Record; public: explicit RecordSubstream( Stream::ByteOrder byteOrder ); //! Read one byte from the stream. char getByte() override; //! \return true if EOF reached. bool eof() const override; //! Seek stream to new position. void seek( int32_t pos, SeekType type = FromBeginning ) override; //! \return Position in the stream. int32_t pos() override; protected: //! Write data to the stream. void write( const char * data, size_t size ); private: //! Stream. std::stringstream m_stream; }; // class RecordSubstream // // RecordType // //! Types of the Excel's records. enum RecordType { XL_BOF = 0x809, XL_EOF = 0x0A, XL_BOUNDSHEET = 0x85, XL_DIMENSION = 0x200, XL_ROW = 0x208, XL_NOTE = 0x1C, XL_TXO = 0x1B6, XL_RK = 0x7E, XL_RK2 = 0x27E, XL_MULRK = 0xBD, XL_INDEX = 0x20B, XL_SST = 0xFC, XL_EXTSST = 0xFF, XL_CONTINUE = 0x3C, XL_LABEL = 0x204, XL_LABELSST = 0xFD, XL_NUMBER = 0x203, XL_NAME = 0x18, XL_ARRAY = 0x221, XL_STRING = 0x207, XL_FORMULA = 0x06, XL_FORMAT = 0x41E, XL_XF = 0xE0, XL_BOOLERR = 0x205, XL_DATEMODE = 0x22, XL_FILEPASS = 0x2F, XL_UNKNOWN = 0xFFFF }; // enum RecordType // // Record // //! Record in the Excel file. class Record { public: Record( Stream & stream ); ~Record(); //! \return Record's code. uint16_t code() const; //! \return Record's length. uint32_t length() const; //! \return Stream with record's data. Stream & dataStream(); //! \return Borders indexes of the continue records. const std::vector< int32_t > & borders() const; private: //! Read record from the stream. void read( Stream & stream ); private: //! Record's code. uint16_t m_code; //! Record's length. uint32_t m_length; //! Record's substream. RecordSubstream m_stream; //! Borders indexes of the continue records. std::vector< int32_t > m_borders; }; // class Record // // RecordSubstream // inline RecordSubstream::RecordSubstream( Stream::ByteOrder byteOrder ) : Stream( byteOrder ) { } inline char RecordSubstream::getByte() { char ch; m_stream.get( ch ); return ch; } inline bool RecordSubstream::eof() const { return m_stream.eof(); } inline void RecordSubstream::seek( int32_t pos, SeekType type ) { std::ios::seekdir dir; if( type == Stream::FromBeginning ) dir = std::ios::beg; else if( type == Stream::FromCurrent ) dir = std::ios::cur; else dir = std::ios::end; m_stream.seekg( pos, dir ); } inline int32_t RecordSubstream::pos() { return static_cast< int32_t > ( m_stream.tellg() ); } inline void RecordSubstream::write( const char * data, size_t size ) { m_stream.write( data, size ); } // // Record // inline Record::Record( Stream & stream ) : m_code( 0 ) , m_length( 0 ) , m_stream( stream.byteOrder() ) { read( stream ); } inline Record::~Record() { } inline void Record::read( Stream & stream ) { stream.read( m_code, 2 ); stream.read( m_length, 2 ); uint16_t nextRecordCode = 0; uint16_t nextRecordLength = 0; std::vector< char > data; if( m_length ) { data.reserve( m_length ); for( size_t i = 0; i < m_length; ++i ) { data.push_back( stream.getByte() ); if( stream.eof() ) throw Exception( L"Unexpected end of file." ); } } try { stream.read( nextRecordCode, 2 ); } catch( const Exception & ) { nextRecordCode = XL_UNKNOWN; } while( nextRecordCode == XL_CONTINUE ) { m_borders.push_back( m_length ); stream.read( nextRecordLength, 2 ); data.reserve( data.size() + nextRecordLength ); if( nextRecordLength ) { for( uint16_t i = 0; i < nextRecordLength; ++i ) { data.push_back( stream.getByte() ); if( stream.eof() ) throw Exception( L"Unexpected end of file." ); } } m_length += nextRecordLength; try { stream.read( nextRecordCode, 2 ); } catch( const Exception & ) { nextRecordCode = XL_UNKNOWN; } } if( !stream.eof() ) stream.seek( -2, Stream::FromCurrent ); if( data.size() ) m_stream.write( &data[ 0 ], data.size() ); } inline uint16_t Record::code() const { return m_code; } inline uint32_t Record::length() const { return m_length; } inline Stream & Record::dataStream() { return m_stream; } inline const std::vector< int32_t > & Record::borders() const { return m_borders; } } /* namespace Excel */ #endif // EXCEL__RECORD_HPP__INCLUDED
19.009346
67
0.654703
AlexZaikaSay
782458cc510eaa4ce002c373d61d74af7fd518d6
22,080
cpp
C++
ME3/main.cpp
Erik-JS/masseffect-binkw32
1c80f3765f6290fc58aaa04b07b02cda3d12a5d4
[ "MIT" ]
128
2016-02-23T13:18:12.000Z
2021-10-09T21:43:32.000Z
ME3/main.cpp
Erik-JS/masseffect-binkw32
1c80f3765f6290fc58aaa04b07b02cda3d12a5d4
[ "MIT" ]
16
2016-02-06T20:57:50.000Z
2021-01-27T01:27:39.000Z
ME3/main.cpp
Erik-JS/masseffect-binkw32
1c80f3765f6290fc58aaa04b07b02cda3d12a5d4
[ "MIT" ]
41
2016-08-17T10:19:50.000Z
2022-02-12T19:36:14.000Z
// ME3 - binkw32 - main.cpp #include "header.h" #include <windows.h> #include <stdio.h> #include <ShlObj.h> HINSTANCE hOriginalBink = NULL; FARPROC p[72] = {0}; char exeBaseFolder[FILENAME_MAX]; BYTE pattern [] = { 0x8B, 0x11, 0x8B, 0x42, 0x0C, 0x57, 0x56, 0xFF, 0xD0, 0x8B, 0xC3, // <-- move eax,ebx; offset 0x9; will be replaced with 0xB0 0x01 to get mov al,1; 0x8B, 0x4D, 0xF4, 0x64, 0x89, 0x0D, 0x00, 0x00, 0x00, 0x00, 0x59, 0x5F, 0x5E, 0x5B, 0x8B, 0xE5, 0x5D, 0xC2, 0x08, 0x00, 0xCC, 0xCC, 0xCC, 0x8B, 0x41, 0x04, 0x56, 0x85, 0xC0 }; BYTE pattern2 [] = { 0x8B, 0x45, 0x0C, // mov eax, [ebp+arg_4] 0xC7, 0x00, 0x01, 0x00, 0x00, 0x00, // mov dword ptr [eax], 1 0x5D, // pop ebp 0xC2, 0x08, 0x00, // retn 8 0x8B, 0x4D, 0x0C, // mov ecx, [ebp+arg_4] 0xC7, 0x01, 0x01, 0x00, 0x00, 0x00, // mov dword ptr [ecx], 1 0x5D, // pop ebp 0xC2, 0x08, 0x00, // retn 8 0xCC, 0xCC, 0xCC, 0xCC, 0xCC }; BYTE pattern3 [] = { 0xB8, 0xE4, 0xFF, 0xFF, 0xFF, 0x5B, 0x59, 0xC3 }; FILE *Log = NULL; int ASIcount = 0; void logprintf(const char *format, ...) { if (Log == NULL) return; va_list arglist; va_start(arglist, format); vfprintf(Log, format, arglist); va_end(arglist); } // Sets exeBaseFolder to hold current executable's path, including "\" void SetExecutableFolder() { GetModuleFileName (NULL, exeBaseFolder, FILENAME_MAX); int x = strlen(exeBaseFolder) - 1; while (exeBaseFolder[x] != '\\') x--; exeBaseFolder[x + 1] = '\0'; } // --- Load Plugins --- void loadPlugins (const char *folder) { DWORD typeMask = 0x6973612e; // '.asi' WIN32_FIND_DATA fd; char targetfilter[FILENAME_MAX]; char currfile[FILENAME_MAX]; strcpy_s (targetfilter, exeBaseFolder); strcat_s (targetfilter, folder); strcat_s (targetfilter, "\\*.asi"); HANDLE asiFile = FindFirstFile (targetfilter, &fd); if (asiFile == INVALID_HANDLE_VALUE) return; do { if (!(fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) { int pos = 0; while (fd.cFileName[pos]) pos++; DWORD type = *(DWORD *)(fd.cFileName+pos-4); type |= 0x20202020; // convert letter to lowercase, "\0" to space if (type == typeMask) { strcpy_s (currfile, exeBaseFolder); strcat_s (currfile, folder); strcat_s (currfile, "\\"); strcat_s (currfile, fd.cFileName); if (LoadLibrary(currfile)) { logprintf("Plugin loaded: %s\n", currfile); ASIcount++; } else logprintf("Plugin error: %s\n", currfile); } } } while (FindNextFile (asiFile, &fd)); FindClose (asiFile); } bool DataCompare(const BYTE* OpCodes, const BYTE* Mask, const char* StrMask) { while (*StrMask) { if(*StrMask == 'x' && *OpCodes != *Mask ) return false; ++StrMask; ++OpCodes; ++Mask; } return true; } DWORD FindPattern(DWORD StartAddress, DWORD CodeLen, BYTE* Mask, char* StrMask, unsigned short ignore) { unsigned short Ign = 0; DWORD i = 0; while (Ign <= ignore) { if(DataCompare((BYTE*)(StartAddress + i++), Mask,StrMask)) ++Ign; else if (i>=CodeLen) return 0; } return StartAddress + i - 1; } void GetAddresses() { hOriginalBink = LoadLibrary("binkw23.dll"); if (hOriginalBink) { p[0] = GetProcAddress(hOriginalBink,"_BinkBufferBlit@12"); p[1] = GetProcAddress(hOriginalBink,"_BinkBufferCheckWinPos@12"); p[2] = GetProcAddress(hOriginalBink,"_BinkBufferClear@8"); p[3] = GetProcAddress(hOriginalBink,"_BinkBufferClose@4"); p[4] = GetProcAddress(hOriginalBink,"_BinkBufferGetDescription@4"); p[5] = GetProcAddress(hOriginalBink,"_BinkBufferGetError@0"); p[6] = GetProcAddress(hOriginalBink,"_BinkBufferLock@4"); p[7] = GetProcAddress(hOriginalBink,"_BinkBufferOpen@16"); p[8] = GetProcAddress(hOriginalBink,"_BinkBufferSetDirectDraw@8"); p[9] = GetProcAddress(hOriginalBink,"_BinkBufferSetHWND@8"); p[10] = GetProcAddress(hOriginalBink,"_BinkBufferSetOffset@12"); p[11] = GetProcAddress(hOriginalBink,"_BinkBufferSetResolution@12"); p[12] = GetProcAddress(hOriginalBink,"_BinkBufferSetScale@12"); p[13] = GetProcAddress(hOriginalBink,"_BinkBufferUnlock@4"); p[14] = GetProcAddress(hOriginalBink,"_BinkCheckCursor@20"); p[15] = GetProcAddress(hOriginalBink,"_BinkClose@4"); p[16] = GetProcAddress(hOriginalBink,"_BinkCloseTrack@4"); p[17] = GetProcAddress(hOriginalBink,"_BinkControlBackgroundIO@8"); p[18] = GetProcAddress(hOriginalBink,"_BinkControlPlatformFeatures@8"); p[19] = GetProcAddress(hOriginalBink,"_BinkCopyToBuffer@28"); p[20] = GetProcAddress(hOriginalBink,"_BinkCopyToBufferRect@44"); p[21] = GetProcAddress(hOriginalBink,"_BinkDDSurfaceType@4"); p[22] = GetProcAddress(hOriginalBink,"_BinkDX8SurfaceType@4"); p[23] = GetProcAddress(hOriginalBink,"_BinkDX9SurfaceType@4"); p[24] = GetProcAddress(hOriginalBink,"_BinkDoFrame@4"); p[25] = GetProcAddress(hOriginalBink,"_BinkDoFrameAsync@12"); p[26] = GetProcAddress(hOriginalBink,"_BinkDoFrameAsyncWait@8"); p[27] = GetProcAddress(hOriginalBink,"_BinkDoFramePlane@8"); p[28] = GetProcAddress(hOriginalBink,"_BinkGetError@0"); p[29] = GetProcAddress(hOriginalBink,"_BinkGetFrameBuffersInfo@8"); p[30] = GetProcAddress(hOriginalBink,"_BinkGetKeyFrame@12"); p[31] = GetProcAddress(hOriginalBink,"_BinkGetPalette@4"); p[32] = GetProcAddress(hOriginalBink,"_BinkGetRealtime@12"); p[33] = GetProcAddress(hOriginalBink,"_BinkGetRects@8"); p[34] = GetProcAddress(hOriginalBink,"_BinkGetSummary@8"); p[35] = GetProcAddress(hOriginalBink,"_BinkGetTrackData@8"); p[36] = GetProcAddress(hOriginalBink,"_BinkGetTrackID@8"); p[37] = GetProcAddress(hOriginalBink,"_BinkGetTrackMaxSize@8"); p[38] = GetProcAddress(hOriginalBink,"_BinkGetTrackType@8"); p[39] = GetProcAddress(hOriginalBink,"_BinkGoto@12"); p[40] = GetProcAddress(hOriginalBink,"_BinkIsSoftwareCursor@8"); p[41] = GetProcAddress(hOriginalBink,"_BinkLogoAddress@0"); p[42] = GetProcAddress(hOriginalBink,"_BinkNextFrame@4"); p[43] = GetProcAddress(hOriginalBink,"_BinkOpen@8"); p[44] = GetProcAddress(hOriginalBink,"_BinkOpenDirectSound@4"); p[45] = GetProcAddress(hOriginalBink,"_BinkOpenMiles@4"); p[46] = GetProcAddress(hOriginalBink,"_BinkOpenTrack@8"); p[47] = GetProcAddress(hOriginalBink,"_BinkOpenWaveOut@4"); p[48] = GetProcAddress(hOriginalBink,"_BinkPause@8"); p[49] = GetProcAddress(hOriginalBink,"_BinkRegisterFrameBuffers@8"); p[50] = GetProcAddress(hOriginalBink,"_BinkRequestStopAsyncThread@4"); p[51] = GetProcAddress(hOriginalBink,"_BinkRestoreCursor@4"); p[52] = GetProcAddress(hOriginalBink,"_BinkService@4"); p[53] = GetProcAddress(hOriginalBink,"_BinkSetError@4"); p[54] = GetProcAddress(hOriginalBink,"_BinkSetFrameRate@8"); p[55] = GetProcAddress(hOriginalBink,"_BinkSetIO@4"); p[56] = GetProcAddress(hOriginalBink,"_BinkSetIOSize@4"); p[57] = GetProcAddress(hOriginalBink,"_BinkSetMemory@8"); p[58] = GetProcAddress(hOriginalBink,"_BinkSetMixBinVolumes@20"); p[59] = GetProcAddress(hOriginalBink,"_BinkSetMixBins@16"); p[60] = GetProcAddress(hOriginalBink,"_BinkSetPan@12"); p[61] = GetProcAddress(hOriginalBink,"_BinkSetSimulate@4"); p[62] = GetProcAddress(hOriginalBink,"_BinkSetSoundOnOff@8"); p[63] = GetProcAddress(hOriginalBink,"_BinkSetSoundSystem@8"); p[64] = GetProcAddress(hOriginalBink,"_BinkSetSoundTrack@8"); p[65] = GetProcAddress(hOriginalBink,"_BinkSetVideoOnOff@8"); p[66] = GetProcAddress(hOriginalBink,"_BinkSetVolume@12"); p[67] = GetProcAddress(hOriginalBink,"_BinkShouldSkip@4"); p[68] = GetProcAddress(hOriginalBink,"_BinkStartAsyncThread@8"); p[69] = GetProcAddress(hOriginalBink,"_BinkWait@4"); p[70] = GetProcAddress(hOriginalBink,"_BinkWaitStopAsyncThread@4"); p[71] = GetProcAddress(hOriginalBink,"_RADTimerRead@0"); } } void OpenLogFile() { PWSTR docfolder; char logfilepath[MAX_PATH]; if (SHGetKnownFolderPath(FOLDERID_Documents, 0, 0, &docfolder) == S_OK) { wcstombs_s(NULL, logfilepath, docfolder, MAX_PATH); strcat_s(logfilepath, "\\binkw32-me3.log"); fopen_s(&Log, logfilepath, "w"); CoTaskMemFree(docfolder); return; } fopen_s(&Log, "binkw32-me3.log", "w"); } DWORD WINAPI Start(LPVOID lpParam) { OpenLogFile(); logprintf("ME3 Autopatcher by Warranty Voider\n"); logprintf("Enhancements by Erik JS\n"); GetAddresses(); if (hOriginalBink) { logprintf("binkw23.dll - loaded\n"); } else { logprintf("Error loading binkw23.dll!\n"); return 0; } DWORD patch1, patch2, patch3; DWORD dwProtect; BYTE *b; patch1 = FindPattern(0x401000, 0xE52000, pattern, "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",0); if(patch1) { VirtualProtect( (void*)(patch1 + 9), 0x2, PAGE_READWRITE, &dwProtect ); b = (BYTE*)(patch1 + 9); *b++ = 0xB0; *b = 0x01; VirtualProtect( (void*)(patch1 + 9), 0x2, dwProtect, &dwProtect ); logprintf("Patch position 1 (DLC): patched at 0x%X\n", patch1); } else { logprintf("Patch position 1 (DLC): byte pattern not found\n"); } patch2 = FindPattern(0x401000, 0xE52000, pattern2, "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",0); if(patch2) { VirtualProtect( (void*)patch2, 0x16, PAGE_READWRITE, &dwProtect ); b = (BYTE*)(patch2 + 5); *b++ = 0; *b++ = 0; *b++ = 0; *b = 0; b = (BYTE*)(patch2 + 0x12); *b++ = 0; *b++ = 0; *b++ = 0; *b = 0; VirtualProtect( (void*)patch2, 0x16, dwProtect, &dwProtect ); logprintf("Patch position 2 (console): patched at 0x%X\n", patch2); } else { logprintf("Patch position 2 (console): byte pattern not found\n"); } patch3 = FindPattern(0x401000, 0xE52000, pattern3, "xxxxxxxx", 0); if(patch3) { VirtualProtect( (void*)patch3, 0x8, PAGE_READWRITE, &dwProtect ); b = (BYTE*)(patch3 + 1); *b++ = 0; *b++ = 0; *b++ = 0; *b = 0; VirtualProtect( (void*)patch3, 0x8, dwProtect, &dwProtect ); logprintf("Patch position 3 (certcheck): patched at 0x%X\n", patch3); } else { logprintf("Patch position 3 (certcheck): byte pattern not found\n"); } SetExecutableFolder(); loadPlugins("asi"); if(!ASIcount) loadPlugins("."); if(Log) fclose(Log); return 0; } BOOL WINAPI DllMain(HINSTANCE hInst,DWORD reason,LPVOID) { if (reason == DLL_PROCESS_ATTACH) { DWORD dwThreadId, dwThrdParam = 1; HANDLE hThread; hThread = CreateThread(NULL,0, Start, &dwThrdParam, 0, &dwThreadId); } if (reason == DLL_PROCESS_DETACH) { FreeLibrary(hOriginalBink); } return 1; } // _BinkBufferBlit@12 extern "C" __declspec(dllexport) __declspec(naked) void __stdcall BinkBufferBlit(int a1, int a2, int a3) { __asm { jmp p[0*4]; } } // _BinkBufferCheckWinPos@12 extern "C" __declspec(dllexport) __declspec(naked) void __stdcall BinkBufferCheckWinPos(int a1, int a2, int a3) { __asm { jmp p[1*4]; } } // _BinkBufferClear@8 extern "C" __declspec(dllexport) __declspec(naked) void __stdcall BinkBufferClear(int a1, int a2) { __asm { jmp p[2*4]; } } // _BinkBufferClose@4 extern "C" __declspec(dllexport) __declspec(naked) void __stdcall BinkBufferClose(int a1) { __asm { jmp p[3*4]; } } // _BinkBufferGetDescription@4 extern "C" __declspec(dllexport) __declspec(naked) void __stdcall BinkBufferGetDescription(int a1) { __asm { jmp p[4*4]; } } // _BinkBufferGetError@0 extern "C" __declspec(dllexport) __declspec(naked) void __stdcall BinkBufferGetError() { __asm { jmp p[5*4]; } } // _BinkBufferLock@4 extern "C" __declspec(dllexport) __declspec(naked) void __stdcall BinkBufferLock(int a1) { __asm { jmp p[6*4]; } } // _BinkBufferOpen@16 extern "C" __declspec(dllexport) __declspec(naked) void __stdcall BinkBufferOpen(int a1,int a2,int a3,int a4) { __asm { jmp p[7*4]; } } // _BinkBufferSetDirectDraw@8 extern "C" __declspec(dllexport) __declspec(naked) void __stdcall BinkBufferSetDirectDraw(int a1, int a2) { __asm { jmp p[8*4]; } } // _BinkBufferSetHWND@8 extern "C" __declspec(dllexport) __declspec(naked) void __stdcall BinkBufferSetHWND(int a1, int a2) { __asm { jmp p[9*4]; } } // _BinkBufferSetOffset@12 extern "C" __declspec(dllexport) __declspec(naked) void __stdcall BinkBufferSetOffset(int a1, int a2, int a3) { __asm { jmp p[10*4]; } } // _BinkBufferSetResolution@12 extern "C" __declspec(dllexport) __declspec(naked) void __stdcall BinkBufferSetResolution(int a1, int a2, int a3) { __asm { jmp p[11*4]; } } // _BinkBufferSetScale@12 extern "C" __declspec(dllexport) __declspec(naked) void __stdcall BinkBufferSetScale(int a1, int a2, int a3) { __asm { jmp p[12*4]; } } // _BinkBufferUnlock@4 extern "C" __declspec(dllexport) __declspec(naked) void __stdcall BinkBufferUnlock(int a1) { __asm { jmp p[13*4]; } } // _BinkCheckCursor@20 extern "C" __declspec(dllexport) __declspec(naked) void __stdcall BinkCheckCursor(int a1,int a2,int a3,int a4,int a5) { __asm { jmp p[14*4]; } } // _BinkClose@4 extern "C" __declspec(dllexport) __declspec(naked) void __stdcall BinkClose(int a1) { __asm { jmp p[15*4]; } } // _BinkCloseTrack@4 extern "C" __declspec(dllexport) __declspec(naked) void __stdcall BinkCloseTrack(int a1) { __asm { jmp p[16*4]; } } // _BinkControlBackgroundIO@8 extern "C" __declspec(dllexport) __declspec(naked) void __stdcall BinkControlBackgroundIO(int a1, int a2) { __asm { jmp p[17*4]; } } // _BinkControlPlatformFeatures@8 extern "C" __declspec(dllexport) __declspec(naked) void __stdcall BinkControlPlatformFeatures(int a1, int a2) { __asm { jmp p[18*4]; } } // _BinkCopyToBuffer@28 extern "C" __declspec(dllexport) __declspec(naked) void __stdcall BinkCopyToBuffer(int a1,int a2,int a3,int a4,int a5,int a6,int a7) { __asm { jmp p[19*4]; } } // _BinkCopyToBufferRect@44 extern "C" __declspec(dllexport) __declspec(naked) void __stdcall BinkCopyToBufferRect(int a1,int a2,int a3,int a4,int a5,int a6,int a7,int a8,int a9,int a10,int a11) { __asm { jmp p[20*4]; } } // _BinkDDSurfaceType@4 extern "C" __declspec(dllexport) __declspec(naked) void __stdcall BinkDDSurfaceType(int a1) { __asm { jmp p[21*4]; } } // _BinkDX8SurfaceType@4 extern "C" __declspec(dllexport) __declspec(naked) void __stdcall BinkDX8SurfaceType(int a1) { __asm { jmp p[22*4]; } } // _BinkDX9SurfaceType@4 extern "C" __declspec(dllexport) __declspec(naked) void __stdcall BinkDX9SurfaceType(int a1) { __asm { jmp p[23*4]; } } // _BinkDoFrame@4 extern "C" __declspec(dllexport) __declspec(naked) void __stdcall BinkDoFrame(int a1) { __asm { jmp p[24*4]; } } // _BinkDoFrameAsync@12 extern "C" __declspec(dllexport) __declspec(naked) void __stdcall BinkDoFrameAsync(int a1, int a2, int a3) { __asm { jmp p[25*4]; } } // _BinkDoFrameAsyncWait@8 extern "C" __declspec(dllexport) __declspec(naked) void __stdcall BinkDoFrameAsyncWait(int a1, int a2) { __asm { jmp p[26*4]; } } // _BinkDoFramePlane@8 extern "C" __declspec(dllexport) __declspec(naked) void __stdcall BinkDoFramePlane(int a1, int a2) { __asm { jmp p[27*4]; } } // _BinkGetError@0 extern "C" __declspec(dllexport) __declspec(naked) void __stdcall BinkGetError() { __asm { jmp p[28*4]; } } // _BinkGetFrameBuffersInfo@8 extern "C" __declspec(dllexport) __declspec(naked) void __stdcall BinkGetFrameBuffersInfo(int a1, int a2) { __asm { jmp p[29*4]; } } // _BinkGetKeyFrame@12 extern "C" __declspec(dllexport) __declspec(naked) void __stdcall BinkGetKeyFrame(int a1, int a2, int a3) { __asm { jmp p[30*4]; } } // _BinkGetPalette@4 extern "C" __declspec(dllexport) __declspec(naked) void __stdcall BinkGetPalette(int a1) { __asm { jmp p[31*4]; } } // _BinkGetRealtime@12 extern "C" __declspec(dllexport) __declspec(naked) void __stdcall BinkGetRealtime(int a1, int a2, int a3) { __asm { jmp p[32*4]; } } // _BinkGetRects@8 extern "C" __declspec(dllexport) __declspec(naked) void __stdcall BinkGetRects(int a1, int a2) { __asm { jmp p[33*4]; } } // _BinkGetSummary@8 extern "C" __declspec(dllexport) __declspec(naked) void __stdcall BinkGetSummary(int a1, int a2) { __asm { jmp p[34*4]; } } // _BinkGetTrackData@8 extern "C" __declspec(dllexport) __declspec(naked) void __stdcall BinkGetTrackData(int a1, int a2) { __asm { jmp p[35*4]; } } // _BinkGetTrackID@8 extern "C" __declspec(dllexport) __declspec(naked) void __stdcall BinkGetTrackID(int a1, int a2) { __asm { jmp p[36*4]; } } // _BinkGetTrackMaxSize@8 extern "C" __declspec(dllexport) __declspec(naked) void __stdcall BinkGetTrackMaxSize(int a1, int a2) { __asm { jmp p[37*4]; } } // _BinkGetTrackType@8 extern "C" __declspec(dllexport) __declspec(naked) void __stdcall BinkGetTrackType(int a1, int a2) { __asm { jmp p[38*4]; } } // _BinkGoto@12 extern "C" __declspec(dllexport) __declspec(naked) void __stdcall BinkGoto(int a1, int a2, int a3) { __asm { jmp p[39*4]; } } // _BinkIsSoftwareCursor@8 extern "C" __declspec(dllexport) __declspec(naked) void __stdcall BinkIsSoftwareCursor(int a1, int a2) { __asm { jmp p[40*4]; } } // _BinkLogoAddress@0 extern "C" __declspec(dllexport) __declspec(naked) void __stdcall BinkLogoAddress() { __asm { jmp p[41*4]; } } // _BinkNextFrame@4 extern "C" __declspec(dllexport) __declspec(naked) void __stdcall BinkNextFrame(int a1) { __asm { jmp p[42*4]; } } // _BinkOpen@8 extern "C" __declspec(dllexport) __declspec(naked) void __stdcall BinkOpen(int a1, int a2) { __asm { jmp p[43*4]; } } // _BinkOpenDirectSound@4 extern "C" __declspec(dllexport) __declspec(naked) void __stdcall BinkOpenDirectSound(int a1) { __asm { jmp p[44*4]; } } // _BinkOpenMiles@4 extern "C" __declspec(dllexport) __declspec(naked) void __stdcall BinkOpenMiles(int a1) { __asm { jmp p[45*4]; } } // _BinkOpenTrack@8 extern "C" __declspec(dllexport) __declspec(naked) void __stdcall BinkOpenTrack(int a1, int a2) { __asm { jmp p[46*4]; } } // _BinkOpenWaveOut@4 extern "C" __declspec(dllexport) __declspec(naked) void __stdcall BinkOpenWaveOut(int a1) { __asm { jmp p[47*4]; } } // _BinkPause@8 extern "C" __declspec(dllexport) __declspec(naked) void __stdcall BinkPause(int a1, int a2) { __asm { jmp p[48*4]; } } // _BinkRegisterFrameBuffers@8 extern "C" __declspec(dllexport) __declspec(naked) void __stdcall BinkRegisterFrameBuffers(int a1, int a2) { __asm { jmp p[49*4]; } } // _BinkRequestStopAsyncThread@4 extern "C" __declspec(dllexport) __declspec(naked) void __stdcall BinkRequestStopAsyncThread(int a1) { __asm { jmp p[50*4]; } } // _BinkRestoreCursor@4 extern "C" __declspec(dllexport) __declspec(naked) void __stdcall BinkRestoreCursor(int a1) { __asm { jmp p[51*4]; } } // _BinkService@4 extern "C" __declspec(dllexport) __declspec(naked) void __stdcall BinkService(int a1) { __asm { jmp p[52*4]; } } // _BinkSetError@4 extern "C" __declspec(dllexport) __declspec(naked) void __stdcall BinkSetError(int a1) { __asm { jmp p[53*4]; } } // _BinkSetFrameRate@8 extern "C" __declspec(dllexport) __declspec(naked) void __stdcall BinkSetFrameRate(int a1, int a2) { __asm { jmp p[54*4]; } } // _BinkSetIO@4 extern "C" __declspec(dllexport) __declspec(naked) void __stdcall BinkSetIO(int a1) { __asm { jmp p[55*4]; } } // _BinkSetIOSize@4 extern "C" __declspec(dllexport) __declspec(naked) void __stdcall BinkSetIOSize(int a1) { __asm { jmp p[56*4]; } } // _BinkSetMemory@8 extern "C" __declspec(dllexport) __declspec(naked) void __stdcall BinkSetMemory(int a1, int a2) { __asm { jmp p[57*4]; } } // _BinkSetMixBinVolumes@20 extern "C" __declspec(dllexport) __declspec(naked) void __stdcall BinkSetMixBinVolumes(int a1,int a2,int a3,int a4,int a5) { __asm { jmp p[58*4]; } } // _BinkSetMixBins@16 extern "C" __declspec(dllexport) __declspec(naked) void __stdcall BinkSetMixBins(int a1,int a2,int a3,int a4) { __asm { jmp p[59*4]; } } // _BinkSetPan@12 extern "C" __declspec(dllexport) __declspec(naked) void __stdcall BinkSetPan(int a1, int a2, int a3) { __asm { jmp p[60*4]; } } // _BinkSetSimulate@4 extern "C" __declspec(dllexport) __declspec(naked) void __stdcall BinkSetSimulate(int a1) { __asm { jmp p[61*4]; } } // _BinkSetSoundOnOff@8 extern "C" __declspec(dllexport) __declspec(naked) void __stdcall BinkSetSoundOnOff(int a1, int a2) { __asm { jmp p[62*4]; } } // _BinkSetSoundSystem@8 extern "C" __declspec(dllexport) __declspec(naked) void __stdcall BinkSetSoundSystem(int a1, int a2) { __asm { jmp p[63*4]; } } // _BinkSetSoundTrack@8 extern "C" __declspec(dllexport) __declspec(naked) void __stdcall BinkSetSoundTrack(int a1, int a2) { __asm { jmp p[64*4]; } } // _BinkSetVideoOnOff@8 extern "C" __declspec(dllexport) __declspec(naked) void __stdcall BinkSetVideoOnOff(int a1, int a2) { __asm { jmp p[65*4]; } } // _BinkSetVolume@12 extern "C" __declspec(dllexport) __declspec(naked) void __stdcall BinkSetVolume(int a1, int a2, int a3) { __asm { jmp p[66*4]; } } // _BinkShouldSkip@4 extern "C" __declspec(dllexport) __declspec(naked) void __stdcall BinkShouldSkip(int a1) { __asm { jmp p[67*4]; } } // _BinkStartAsyncThread@8 extern "C" __declspec(dllexport) __declspec(naked) void __stdcall BinkStartAsyncThread(int a1, int a2) { __asm { jmp p[68*4]; } } // _BinkWait@4 extern "C" __declspec(dllexport) __declspec(naked) void __stdcall BinkWait(int a1) { __asm { jmp p[69*4]; } } // _BinkWaitStopAsyncThread@4 extern "C" __declspec(dllexport) __declspec(naked) void __stdcall BinkWaitStopAsyncThread(int a1) { __asm { jmp p[70*4]; } } // _RADTimerRead@0 extern "C" __declspec(dllexport) __declspec(naked) void __stdcall RADTimerRead() { __asm { jmp p[71*4]; } }
23.096234
166
0.686096
Erik-JS
78259b894a27624003d95494f668a97d706c10c0
5,577
cpp
C++
source/thirdparty/irrpoly/gf.cpp
jointpoints/tms-nets
8cefe1868d2e696c100594e66d57380243856e16
[ "BSL-1.0" ]
5
2019-10-14T18:49:36.000Z
2020-10-22T06:03:57.000Z
source/thirdparty/irrpoly/gf.cpp
jointpoints/tms-nets
8cefe1868d2e696c100594e66d57380243856e16
[ "BSL-1.0" ]
8
2019-11-10T17:23:20.000Z
2020-12-01T18:00:45.000Z
source/thirdparty/irrpoly/gf.cpp
jointpoints/tms-nets
8cefe1868d2e696c100594e66d57380243856e16
[ "BSL-1.0" ]
16
2019-10-25T13:50:59.000Z
2021-06-24T13:55:23.000Z
#include "../../../include/tms-nets/thirdparty/irrpoly/gf.hpp" // Comparison operators for <gf> objects auto irrpoly::operator==(const gf &lb, const gf &rb) -> bool { return lb->base() == rb->base(); } auto irrpoly::operator!=(const gf &lb, const gf &rb) -> bool { return lb->base() != rb->base(); } // Class <gfn> [[nodiscard]] auto irrpoly::gfn::value() const -> uintmax_t { return m_val; } irrpoly::gfn::gfn(const gf &field) : m_field(field), m_val(0) {} irrpoly::gfn::gfn(const gf &field, const uintmax_t val) : m_field(field), m_val(val % m_field->base()) {} irrpoly::gfn::gfn(const gfn &other) = default; irrpoly::gfn::gfn(gfn &&other) = default; auto irrpoly::gfn::operator=(const gfn &other) -> gfn & { if (this != &other) { // m_field == nullptr means that gfn instance is uninitialised // this happens during std::move, std::swap and inside some std::vector methods m_field = other.m_field; m_val = other.m_val; } return *this; } [[nodiscard]] auto irrpoly::gfn::base() const -> uintmax_t { return m_field->base(); } auto irrpoly::gfn::operator=(const uintmax_t other) -> gfn & { m_val = other % base(); return *this; } [[nodiscard]] auto irrpoly::gfn::field() const -> const gf & { return m_field; } [[nodiscard]] auto irrpoly::gfn::operator+() const -> gfn { return gfn{*this}; } [[nodiscard]] auto irrpoly::gfn::operator+(const gfn &other) const -> gfn { return gfn{m_field, m_val + other.m_val}; } [[nodiscard]] auto irrpoly::gfn::operator+(const uintmax_t other) const -> gfn { return gfn{m_field, m_val + (other % base())}; } auto irrpoly::gfn::operator+=(const gfn &other) -> gfn & { m_val = (m_val + other.m_val) % base(); return *this; } auto irrpoly::gfn::operator+=(const uintmax_t other) -> gfn { m_val = (m_val + (other % base())) % base(); return *this; } auto irrpoly::gfn::operator++() -> gfn & { m_val = (m_val + 1) % base(); return *this; } [[nodiscard]] auto irrpoly::gfn::operator++(int) & -> gfn { gfn tmp{*this}; m_val = (m_val + 1) % base(); return tmp; } [[nodiscard]] auto irrpoly::gfn::operator-() const -> gfn { gfn tmp{*this}; tmp.m_val = (base() - m_val) % base(); return tmp; } [[nodiscard]] auto irrpoly::gfn::operator-(const gfn &other) const -> gfn { return gfn{m_field, base() + m_val - other.m_val}; } [[nodiscard]] auto irrpoly::gfn::operator-(const uintmax_t other) const -> gfn { return gfn{m_field, base() + m_val - (other % base())}; } auto irrpoly::gfn::operator-=(const gfn &other) -> gfn & { m_val = (base() + m_val - other.m_val) % base(); return *this; } auto irrpoly::gfn::operator-=(const uintmax_t other) -> gfn { m_val = (base() + m_val - (other % base())) % base(); return *this; } auto irrpoly::gfn::operator--() -> gfn & { m_val = (base() + m_val - 1) % base(); return *this; } [[nodiscard]] auto irrpoly::gfn::operator--(int) & -> gfn { gfn tmp{*this}; m_val = (base() + m_val - 1) % base(); return tmp; } [[nodiscard]] auto irrpoly::gfn::operator*(const gfn &other) const -> gfn { return gfn{m_field, m_val * other.m_val}; } [[nodiscard]] auto irrpoly::gfn::operator*(const uintmax_t other) const -> gfn { return gfn{m_field, m_val * (other % base())}; } auto irrpoly::gfn::operator*=(const gfn &other) -> gfn & { m_val = (m_val * other.m_val) % base(); return *this; } auto irrpoly::gfn::operator*=(const uintmax_t other) -> gfn { m_val = (m_val * (other % base())) % base(); return *this; } [[maybe_unused]] [[nodiscard]] auto irrpoly::gfn::mul_inv() -> gfn { return gfn{m_field, m_field->mul_inv(m_val)}; } [[nodiscard]] auto irrpoly::gfn::operator/(const gfn &other) const -> gfn { switch (other.m_val) { case 0:throw std::invalid_argument("division by zero"); default:return gfn{m_field, m_val * m_field->mul_inv(other.m_val)}; } } [[nodiscard]] auto irrpoly::gfn::operator/(const uintmax_t other) const -> gfn { switch (other % base()) { case 0:throw std::invalid_argument("division by zero"); default: return gfn{m_field, m_val * m_field->mul_inv(other % base())}; } } auto irrpoly::gfn::operator/=(const gfn &other) -> gfn & { switch (other.m_val) { case 0:throw std::invalid_argument("division by zero"); default:m_val = (m_val * m_field->mul_inv(other.m_val)) % base(); return *this; } } auto irrpoly::gfn::operator/=(const uintmax_t other) -> gfn { switch (other % base()) { case 0:throw std::invalid_argument("division by zero"); default:m_val = (m_val * m_field->mul_inv(other % base())) % base(); return *this; } } [[nodiscard]] auto irrpoly::gfn::is_zero() const -> bool { return 0 == m_val; } irrpoly::gfn::operator bool() const { return 0 != m_val; } // External operators for <gfn> [[nodiscard]] auto irrpoly::operator+(const uintmax_t other, const gfn &curr) -> gfn { return gfn{curr.m_field, (other % curr.base()) + curr.m_val}; } [[nodiscard]] auto irrpoly::operator-(const uintmax_t other, const gfn &curr) -> gfn { return gfn{curr.m_field, curr.base() + (other % curr.base()) - curr.m_val}; } [[nodiscard]] auto irrpoly::operator*(const uintmax_t other, const gfn &curr) -> gfn { return gfn{curr.m_field, (other % curr.base()) * curr.m_val}; } [[nodiscard]] auto irrpoly::operator/(const uintmax_t other, const gfn &curr) -> gfn { switch (curr.m_val) { case 0:throw std::invalid_argument("division by zero"); default: return gfn{curr.m_field, (other % curr.base()) * curr.m_field->mul_inv(curr.m_val)}; } }
17.319876
81
0.628653
jointpoints
782d75ef444418e774b6c4905cac55e0925bf40d
1,384
cc
C++
source/extensions/filters/http/transformation/body_header_transformer.cc
solo-io/envoy-gloo
7f48ec3820134dd26dd3b8ac3c1c56b3a2a58cc3
[ "Apache-2.0" ]
17
2019-03-06T01:44:39.000Z
2022-01-17T15:17:05.000Z
source/extensions/filters/http/transformation/body_header_transformer.cc
solo-io/envoy-gloo
7f48ec3820134dd26dd3b8ac3c1c56b3a2a58cc3
[ "Apache-2.0" ]
95
2018-12-19T19:22:26.000Z
2022-03-31T15:07:56.000Z
source/extensions/filters/http/transformation/body_header_transformer.cc
solo-io/envoy-gloo
7f48ec3820134dd26dd3b8ac3c1c56b3a2a58cc3
[ "Apache-2.0" ]
11
2019-06-23T20:05:57.000Z
2021-02-17T18:25:29.000Z
#include "source/extensions/filters/http/transformation/body_header_transformer.h" #include "source/common/http/headers.h" #include "nlohmann/json.hpp" // For convenience using json = nlohmann::json; namespace Envoy { namespace Extensions { namespace HttpFilters { namespace Transformation { void BodyHeaderTransformer::transform( Http::RequestOrResponseHeaderMap &header_map, Http::RequestHeaderMap *, Buffer::Instance &body, Http::StreamFilterCallbacks &) const { json json_body; if (body.length() > 0) { json_body["body"] = body.toString(); } json &headers = json_body["headers"]; header_map.iterate( [&headers](const Http::HeaderEntry &header) -> Http::HeaderMap::Iterate { headers[std::string(header.key().getStringView())] = std::string(header.value().getStringView()); return Http::HeaderMap::Iterate::Continue; }); // remove content length, as we have new body. header_map.removeContentLength(); // we know that the new content type is json: header_map.removeContentType(); header_map.setReferenceContentType( Http::Headers::get().ContentTypeValues.Json); // replace body body.drain(body.length()); body.add(json_body.dump()); header_map.setContentLength(body.length()); } } // namespace Transformation } // namespace HttpFilters } // namespace Extensions } // namespace Envoy
28.244898
82
0.710983
solo-io
782eb9adde43d519b72f73c38b4915dca6a5f282
3,191
cpp
C++
09.05/main.cpp
AmaterasuOmikami/OOP-in-Cpp-book-exercises
7f7f02472446a9defd93e95de7e9c07048b5c400
[ "MIT" ]
null
null
null
09.05/main.cpp
AmaterasuOmikami/OOP-in-Cpp-book-exercises
7f7f02472446a9defd93e95de7e9c07048b5c400
[ "MIT" ]
null
null
null
09.05/main.cpp
AmaterasuOmikami/OOP-in-Cpp-book-exercises
7f7f02472446a9defd93e95de7e9c07048b5c400
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; const int LEN = 30; class Employee { private: char name[LEN]; unsigned long number; public: void getData() { cout << "Enter name:"; cin >> name; cout << "Enter number:"; cin >> number; } void putData() const { cout << "Name: " << name << endl; cout << "Number: " << number << endl; } }; class Manager : private Employee { private: char title[LEN]; double dues; public: void getData() { Employee::getData(); cout << "Enter title:"; cin >> title; cout << "Enter dues:"; cin >> dues; } void putData() const { Employee::putData(); cout << "Title: " << title << endl; cout << "Dues: " << dues << endl; } }; class Scientist : private Employee { private: int pubs; public: void getData() { Employee::getData(); cout << "Enter pubs:"; cin >> pubs; } void putData() const { Employee::putData(); cout << "Pubs: " << pubs << endl; } }; class Laborer : public Employee { }; class Compensation { private: double compensation; enum { none, hourly, weakly, monthly } period; public: void getData() { cout << "Enter compensation:"; cin >> compensation; char letter; cout << "Enter first letter form periods list:\n" "(hourly, weakly, monthly)" << endl; cin >> letter; switch (letter) { case 'h': period = hourly; break; case 'w': period = weakly; break; case 'm': period = monthly; break; default: cout << "Unknown period!"; period = none; } cout << endl; } void putData() const { cout << "Compensation: " << compensation << endl; cout << "Period: "; switch (period) { case hourly: cout << "hourly"; break; case weakly: cout << "weakly"; break; case monthly: cout << "monthly"; break; default: cout << "none"; break; } cout << endl; } }; class Manager2 : private Manager, private Compensation { public: void getData() { Manager::getData(); Compensation::getData(); } void putData() const { Manager::putData(); Compensation::putData(); } }; class Scientist2 : private Scientist, private Compensation { public: void getData() { Scientist::getData(); Compensation::getData(); } void putData() const { Scientist::putData(); Compensation::putData(); } }; class Laborer2 : private Laborer, private Compensation { public: void getData() { Laborer::getData(); Compensation::getData(); } void putData() const { Laborer::putData(); Compensation::putData(); } };
18.994048
60
0.474773
AmaterasuOmikami
7833f211d05dc6c9f02cd6a9fa6b9acac7108600
3,070
cpp
C++
src/freedman.cpp
jaihyunp/HE_clustering
b4e04a1468428805e35c0c55a8e590b00baafa03
[ "MIT" ]
null
null
null
src/freedman.cpp
jaihyunp/HE_clustering
b4e04a1468428805e35c0c55a8e590b00baafa03
[ "MIT" ]
null
null
null
src/freedman.cpp
jaihyunp/HE_clustering
b4e04a1468428805e35c0c55a8e590b00baafa03
[ "MIT" ]
null
null
null
#include "plain.h" std::vector<long> freedman_cluster(std::vector<Point> &points, long dim, long num_of_dusts, long num_of_shiftings, long zeta_ms, long gamma_ms) { long num_of_points = points.size(); double max = (double) dim, tmp, dist; std::vector<Point> dusts, dusts2; std::vector<long> closest, modes, clus; //Sample dusts dusts = sample_points(num_of_dusts, points, num_of_points); for(long i = 0; i < num_of_dusts; i ++){ Point dust; dust.resize(dim); for(long j = 0; j < dim; j ++) dust[j] = dusts[i][j]; dusts2.push_back(dust); } //Map backwards closest.resize(num_of_points); for(long i = 0; i < num_of_points; i ++){ closest[i] = 0; tmp = 9999; for(long j = 1; j < num_of_dusts; j ++){ dist = euclidean_distance_sqr(points[i], dusts[j]); if(tmp > dist){ tmp = dist; closest[i] = j; } } } //Mean-shift for(long i = 0; i < num_of_shiftings; i ++) dusts = meanshift(dusts, dusts2, max, zeta_ms, gamma_ms); //Monitor the dusts printf("Detected modes:\n"); for(long i = 0; i < num_of_dusts; i ++){ printf("%3ld: ( ", i); for(long j = 0; j < dim; j ++) printf("%f ", dusts2[i][j]); printf(")->("); for(long j = 0; j < dim; j ++) printf("%f ", dusts[i][j]); printf(")\n"); } //Set eps roughly double eps = 0; for(long i = 0; i < num_of_dusts; i ++){ for(long j = 0; j < num_of_dusts; j ++){ eps += euclidean_distance_sqr(dusts[i], dusts[j]); } } eps /= num_of_dusts * num_of_dusts * 8; printf("Epsilon: %f\n", eps); //Generate labels of dusts using eps nbhd modes.resize(num_of_dusts); for(long i = 0; i < num_of_dusts; i ++){ modes[i] = i; for(long j = 0; j < i; j ++){ if(euclidean_distance_sqr(dusts[i], dusts[j]) < eps){ modes[i] = modes[j]; break; } } printf("%ld: %ld\n", i, modes[i]); } //Print the labels of the data clus.resize(num_of_points); for(long i = 0; i < num_of_points; i ++){ printf("%ld: %ld\n", i, clus[i] = modes[closest[i]]); } //Calculate accuracy for the Tetra dataset int candidates[400], cnt = 0, cand; for(long i = 0; i < 4; i ++){ cand = 0; for(long j = 0; j < 400; j ++) candidates[j] = 0; for(long j = 0; j < 100; j ++){ candidates[modes[closest[100 * i + j]]] ++; } for(long j = 1; j < 400; j ++){ if(candidates[cand] < candidates[j]) cand = j; } for(long j = 0; j < 100; j ++){ if(modes[closest[100 * i + j]] != modes[cand]){ cnt ++; } } printf("after %ld cluster (cand: %d): %d\n", i, cand, cnt); } printf("%d / 400 errors\n", cnt); return clus; }
28.165138
143
0.485016
jaihyunp
783602c1d2af171e1a81b25008e1136feb0c0793
3,932
cpp
C++
Alfa-Back-Console/rezept.cpp
haikelassaker/Backstr
56a1b85d83f633f41250b690f840bb884916cd67
[ "MIT" ]
null
null
null
Alfa-Back-Console/rezept.cpp
haikelassaker/Backstr
56a1b85d83f633f41250b690f840bb884916cd67
[ "MIT" ]
null
null
null
Alfa-Back-Console/rezept.cpp
haikelassaker/Backstr
56a1b85d83f633f41250b690f840bb884916cd67
[ "MIT" ]
null
null
null
#include "stdafx.h" #include "rezept.h" using namespace std; rezept::rezept(string teigName, double plaetzchenAnzahl, string form, string groesse, double backTemperatur, double backZeit) { tgName = teigName; basisAnzahlPlaetzchen = plaetzchenAnzahl; plaetzchenForm = form; plaetzchenGroesse = groesse; backTemp = backTemperatur; backZt = backZeit; } void rezept::addZutat(zutat* ingredient) { zutaten.insert(pair<string, zutat*>(ingredient->getName(), ingredient)); } void rezept::addVerzierung(zutat* ingredient) { verzierungen.insert(pair<string, zutat*>(ingredient->getName(), ingredient)); } rezept* rezept::getKonfigdatei() { rezept* schokoPlaetzchen = new rezept("Schokokeks", 100.0, "Kreis", "mittel", 180.0, 40.0); schokoPlaetzchen->addZutat(new zutat("Backpulver", 100.0, "g")); schokoPlaetzchen->addZutat(new zutat("Eier", 0.9, "l")); schokoPlaetzchen->addZutat(new zutat("Kakao", 700.0, "g")); schokoPlaetzchen->addZutat(new zutat("Mehl", 900.0, "g")); schokoPlaetzchen->addZutat(new zutat("Milch", 4.0, "l")); schokoPlaetzchen->addZutat(new zutat("Pflanzenfett", 500.0, "g")); schokoPlaetzchen->addZutat(new zutat("Zucker", 1000.0, "g")); schokoPlaetzchen->addVerzierung(new zutat("Kakaoguss", 0.3, "l")); schokoPlaetzchen->addVerzierung(new zutat("Schokostreusel", 300.0, "g")); return schokoPlaetzchen; } string rezept::toString() { vector<string> config; config.push_back("teigname:" + getTeigName()); config.push_back("basisAnzahl:" + to_string(getBasisPlaetzchenAnzahl())); config.push_back("form:" + getForm()); config.push_back("groesse:" + getPlaetzchenGroesse()); config.push_back("backTemperatur:" + to_string(getBackTemperatur())); config.push_back("backZeit:" + to_string(getBackZeit())); config.push_back(getZutatenWriteStr()); config.push_back(getVerzierungenWriteStr()); return werkzeuge::join("\t", config); } void rezept::setTeigname(string tn) { tgName = tn; } void rezept::setAnzahl(double anz) { basisAnzahlPlaetzchen = anz; } void rezept::setForm(string frm) { plaetzchenForm = frm; } void rezept::setGroesse(string gr) { plaetzchenGroesse = gr; } void rezept::setBacktemperatur(double temp) { backTemp = temp; } void rezept::setBackzeit(double zeit) { backZt = zeit; } string rezept::getZutatenWriteStr() { vector<string> zuts; for (std::map<string, zutat*>::iterator it = zutaten.begin(); it != zutaten.end(); ++it) { zuts.push_back(it->second->toString()); } return string("Zutaten:" + werkzeuge::join("|", zuts)); } string rezept::getVerzierungenWriteStr() { vector<string> zuts; for (std::map<string, zutat*>::iterator it = verzierungen.begin(); it != verzierungen.end(); ++it) { zuts.push_back(it->second->toString()); } return string("Verzierungen:" + werkzeuge::join("|", zuts)); } map<string, zutat*> rezept::getZutatMenge() { return zutaten; } map<string, zutat*> rezept::getVerzierungsMenge() { return verzierungen; } string rezept::getTeigName() { return tgName; } double rezept::getBasisPlaetzchenAnzahl() { return basisAnzahlPlaetzchen; } string rezept::getPlaetzchenGroesse() { return string(); } string rezept::getForm() { return plaetzchenForm; } double rezept::getXBetrag( string groesse) { if (groesse == "gross") { return 80; } else if (groesse == "mittel") { return 40; } else { return 20; } } double rezept::getYBetrag(string groesse) { if (groesse == "gross") { return 80; } else if (groesse == "mittel") { return 40; } else { return 20; } } double rezept::getBackTemperatur() { return backTemp; } double rezept::getBackZeit() { return backZt; } rezept::rezept() {} rezept::~rezept() {}
21.604396
126
0.655646
haikelassaker
7838730eb7f6b0875c3175d899862e299fbe2180
760
hpp
C++
include/nexus/global_init.hpp
cbodley/nexus
6e5b19b6c6c74007a0643c55eb0775eb86e38f9b
[ "BSL-1.0" ]
6
2021-10-31T10:33:30.000Z
2022-03-25T20:54:58.000Z
include/nexus/global_init.hpp
cbodley/nexus
6e5b19b6c6c74007a0643c55eb0775eb86e38f9b
[ "BSL-1.0" ]
null
null
null
include/nexus/global_init.hpp
cbodley/nexus
6e5b19b6c6c74007a0643c55eb0775eb86e38f9b
[ "BSL-1.0" ]
null
null
null
#pragma once #include <nexus/global/context.hpp> /// global initialization namespace nexus::global { /// initialize the library for clients only /// \relatesalso context context init_client(error_code& ec); /// initialize the library for clients only /// \relatesalso context context init_client(); /// initialize the library for server only /// \relatesalso context context init_server(error_code& ec); /// initialize the library for server only /// \relatesalso context context init_server(); /// initialize the library for client and server use /// \relatesalso context context init_client_server(error_code& ec); /// initialize the library for client and server use /// \relatesalso context context init_client_server(); } // namespace nexus::global
25.333333
52
0.763158
cbodley
783af9f0aebf1e3ef1fe50f87d382cd310149fb1
1,291
cpp
C++
kernel/loader/elf64.cpp
qookei/quack
47808580dda218cb47d0c9ca04b51eb24f1e2266
[ "Zlib" ]
16
2019-06-25T15:18:03.000Z
2021-10-10T18:52:30.000Z
kernel/loader/elf64.cpp
qookei/quack
47808580dda218cb47d0c9ca04b51eb24f1e2266
[ "Zlib" ]
null
null
null
kernel/loader/elf64.cpp
qookei/quack
47808580dda218cb47d0c9ca04b51eb24f1e2266
[ "Zlib" ]
null
null
null
#include "elf64.h" #include <string.h> static bool elf64_check(elf64_ehdr *ehdr) { if(strncmp((const char *)ehdr->e_ident, ELF_MAGIC, 4)) { return false; } if(ehdr->e_ident[ELF_IDENT_CLASS] != ELF_CLASS_64) { return false; } if(ehdr->e_ident[ELF_IDENT_DATA] != ELF_DATA_LSB) { return false; } if(ehdr->e_version != ELF_VER_CURRENT){ return false; } if(ehdr->e_type != ELF_TYPE_EXEC) { return false; } return true; } bool elf64_load(void *file, thread &t) { elf64_ehdr *ehdr = (elf64_ehdr *)file; if (!elf64_check(ehdr)) return false; elf64_phdr *phdrs = (elf64_phdr *)((uintptr_t)file + ehdr->e_phoff); for(int i = 0; i < ehdr->e_phnum; i++) { if(phdrs[i].p_type != ELF_PHDR_TYPE_LOAD) { continue; } int flags = vm_perm::user; if (phdrs[i].p_flags & ELF_PHDR_FLAG_X) flags |= vm_perm::execute; if (phdrs[i].p_flags & ELF_PHDR_FLAG_R) flags |= vm_perm::read; if (phdrs[i].p_flags & ELF_PHDR_FLAG_W) flags |= vm_perm::write; size_t n_pages = (phdrs[i].p_memsz + vm_page_size - 1) / vm_page_size; t._addr_space->allocate_at(phdrs[i].p_vaddr, n_pages, flags); t._addr_space->load(phdrs[i].p_vaddr, (void *)((uintptr_t)file + phdrs[i].p_offset), phdrs[i].p_filesz); } t._task->ip() = ehdr->e_entry; return true; }
20.822581
72
0.664601
qookei
783b409c2f69adda9a17a21272ce2aaa41b56489
1,758
cpp
C++
BAC/exercises/ch7/UVa387.cpp
Anyrainel/aoapc-code
e787a01380698fb9236d933462052f97b20e6132
[ "Apache-2.0" ]
3
2017-08-15T06:00:01.000Z
2018-12-10T09:05:53.000Z
BAC/exercises/ch7/UVa387.cpp
Anyrainel/aoapc-related-code
e787a01380698fb9236d933462052f97b20e6132
[ "Apache-2.0" ]
null
null
null
BAC/exercises/ch7/UVa387.cpp
Anyrainel/aoapc-related-code
e787a01380698fb9236d933462052f97b20e6132
[ "Apache-2.0" ]
2
2017-09-16T18:46:27.000Z
2018-05-22T05:42:03.000Z
// UVa387 A Puzzling Problem // Rujia Liu // 题意:用n个积木块拼出一个4*4的正方形,要求每个块恰好用一次,不能旋转或者翻转。求任意一个方案 // 算法:本题写法有很多,由于规模非常小,这里给出一个效率不算高但较好实现的方法:每层搜索选一个可用积木,再枚举一个位置放上去 #include<cstdio> #include<cstring> const int maxn = 5; int n; int board[5][5]; // 要拼出的正方形 struct Piece { int r, c, size; char data[maxn][maxn]; void read() { size = 0; scanf("%d%d", &r, &c); for(int i = 0; i < r; i++) { scanf("%s", data[i]); for(int j = 0; j < c; j++) if(data[i][j] == '1') size++; } } bool can_place(int x, int y) { if(x+r > 4 || y+c > 4) return false; for(int i = 0; i < r; i++) for(int j = 0; j < c; j++) if(data[i][j] == '1' && board[x+i][y+j] != 0) return false; return true; } void fill(int x, int y, int v) { for(int i = 0; i < r; i++) for(int j = 0; j < c; j++) if(data[i][j] == '1') board[x+i][y+j] = v; } } pieces[5]; int vis[5]; bool dfs(int d) { if(d == n) return true; for(int i = 0; i < n; i++) if(!vis[i]) { vis[i] = 1; for(int x = 0; x < 4; x++) for(int y = 0; y < 4; y++) if(pieces[i].can_place(x, y)) { pieces[i].fill(x, y, i+1); if(dfs(d+1)) return true; pieces[i].fill(x, y, 0); } vis[i] = 0; } return false; } int main() { int kase = 0; while(scanf("%d", &n) == 1 && n) { if(kase++) printf("\n"); memset(board, 0, sizeof(board)); memset(vis, 0, sizeof(vis)); int tot = 0; for(int i = 0; i < n; i++) { pieces[i].read(); tot += pieces[i].size; } if(tot != 16 || !dfs(0)) printf("No solution possible\n"); else { for(int i = 0; i < 4; i++) printf("%d%d%d%d\n", board[i][0], board[i][1], board[i][2], board[i][3]); } } return 0; }
24.082192
81
0.481229
Anyrainel
783ec127fd1fc493383592f29519d3f028b52046
18,646
cpp
C++
src/print.cpp
Maelic/libqi
0a92452be48376004e5e5ebfe2bd0683725d033e
[ "BSD-3-Clause" ]
null
null
null
src/print.cpp
Maelic/libqi
0a92452be48376004e5e5ebfe2bd0683725d033e
[ "BSD-3-Clause" ]
null
null
null
src/print.cpp
Maelic/libqi
0a92452be48376004e5e5ebfe2bd0683725d033e
[ "BSD-3-Clause" ]
null
null
null
/* ** Copyright (C) 2017 SoftBank Robotics ** See COPYING for the license */ #include <qi/detail/print.hpp> #include <qi/iocolor.hpp> #include <qi/numeric.hpp> #include <qi/type/metaobject.hpp> #include <qi/type/metamethod.hpp> #include <qi/type/detail/structtypeinterface.hxx> #include <boost/range/adaptor/filtered.hpp> #include <boost/range/adaptor/transformed.hpp> #include <boost/algorithm/string/join.hpp> #include <boost/range/algorithm/max_element.hpp> #include <iomanip> #include <limits> namespace { /// (MetaMethod || MetaSignal || MetaProperty) M template <typename M> struct MustDisplay { bool operator()(const std::pair<unsigned int, M>& m) const { return displayHidden || !qi::MetaObject::isPrivateMember(m.second.name(), m.second.uid()); } bool displayHidden; }; /// std::pair<_, MetaMethod || MetaSignal || MetaProperty> MP template <typename MP> int memberNameSize(const MP& member) { return qi::numericConvertBound<int>(member.second.name().size()); } } namespace qi { namespace detail { using boost::optional; const boost::string_ref PrettyPrintStream::infoLabel = "Info"; const boost::string_ref PrettyPrintStream::methodsLabel = "Methods"; const boost::string_ref PrettyPrintStream::signalsLabel = "Signals"; const boost::string_ref PrettyPrintStream::propertiesLabel = "Properties"; const boost::string_ref PrettyPrintStream::membersLabel = "members"; const boost::string_ref PrettyPrintStream::returnTypeLabel = "return type"; const boost::string_ref PrettyPrintStream::returnDescrLabel = "returns"; const boost::string_ref PrettyPrintStream::elementTypeLabel = "element type"; const boost::string_ref PrettyPrintStream::keyTypeLabel = "key type"; const boost::string_ref PrettyPrintStream::parametersLabel = "parameters"; const boost::string_ref PrettyPrintStream::signalTypesLabel = "signal type(s)"; const int PrettyPrintStream::indentFactor(2); const int PrettyPrintStream::maxOffset(30); const int PrettyPrintStream::idColumnWidth(3); PrettyPrintStream::PrettyPrintStream(std::ostream& stream, DisplayHiddenMembers displayHidden, Options flags, int indentLevel) : _stream(&stream) , _displayHidden(displayHidden) , _options(flags) , _indentLevel(indentLevel) {} PrettyPrintStream::IndentLevelPtr PrettyPrintStream::makeIndentLevel() { return IndentLevelPtr(new IndentLevel(*this)); } void PrettyPrintStream::print(const Line& line) { auto& stream = *_stream; if (line.opts.test(Line::Option::Indent)) { stream << std::string(static_cast<std::string::size_type>(indentWidth()), ' '); } if (!line.columns.empty()) { auto it = begin(line.columns); print(*it++); for (; it != end(line.columns); ++it) { const auto& column = *it; if (column.opts.test(Column::Option::DelimitWithSpace)) { stream << ' '; } print(column); } } if (line.opts.test(Line::Option::NewLine)) { stream << '\n'; } else { stream << ' '; // print a blank instead } } PrettyPrintStream::Line PrettyPrintStream::makeSectionHeader(const Line& line) { Line header {{}, line.opts}; if (line.columns.empty()) { return header; } header.columns.reserve(line.columns.size() + 2); auto columnsIt = begin(line.columns); const auto count = [&] { const auto n = line.columns.size(); return n > 0u ? n - 1u : 0u; }(); std::copy_n(columnsIt, count, std::back_inserter(header.columns)); std::advance(columnsIt, count); auto lastColumn = *columnsIt; lastColumn.opts.reset(Column::Option::DelimitWithSpace); header.columns.push_back(Column("[")); header.columns.push_back(lastColumn); header.columns.push_back(Column("]", StreamColor_None, Column::Alignment::Left, Column::Options{/* no space */})); return header; } PrettyPrintStream::Line PrettyPrintStream::makeSubSectionHeader(const Line& line) { Line header {{}, line.opts}; header.columns.reserve(line.columns.size() + 1); header.columns.push_back(Column( "*", StreamColor_Green )); header.columns.insert(header.columns.end(), begin(line.columns), end(line.columns)); return header; } /// Linearizable<std::pair<_, MetaMethod || MetaSignal || MetaProperty>> L template <typename L> void PrettyPrintStream::printMetaObjectMembers(const L& members, string_ref headerLabel) { using V = typename L::value_type; using boost::range::max_element; using boost::algorithm::join; if (!boost::empty(members)) { print(makeSubSectionHeader(Line{ Column(headerLabel.to_string(), StreamColor_Fuchsia) })); IndentLevelPtr membersIndentLevel = makeIndentLevel(); const auto cmpMemberNameSize = [](const V& lhs, const V& rhs) { return memberNameSize(lhs) < memberNameSize(rhs); }; const auto maxMemberIt = max_element(members, cmpMemberNameSize); const auto offset = std::min(memberNameSize(*maxMemberIt), maxOffset); for (const auto& member: members) { print(member.second, offset, RecurseOption::DoNotRecurse); } } } void PrettyPrintStream::print(const MetaObject& mobj) { const bool displayHidden = (_displayHidden == DisplayHiddenMembers::Display); using boost::adaptors::filtered; { const auto unfilteredMethods = mobj.methodMap(); const auto methods = unfilteredMethods | filtered(MustDisplay<MetaMethod>{displayHidden}); printMetaObjectMembers(methods, methodsLabel); } { const auto unfilteredSignals = mobj.signalMap(); const auto signals = unfilteredSignals | filtered(MustDisplay<MetaSignal>{displayHidden}); printMetaObjectMembers(signals, signalsLabel); } { const auto unfilteredProps = mobj.propertyMap(); const auto props = unfilteredProps | filtered(MustDisplay<MetaProperty>{displayHidden}); printMetaObjectMembers(props, propertiesLabel); } } void PrettyPrintStream::print(const MetaMethod& method, int offsetLabel, RecurseOption recurse) { const bool showDoc = _options.test(Option::Documentation); // method info print(Line{ Column(method.uid(), StreamColor_Blue, Column::Alignment::Right, {}, idColumnWidth, '0'), Column(method.name(), StreamColor_None, Column::Alignment::Left, Column::Options{ Column::Option::DelimitWithSpace }, offsetLabel), Column(stringify(method.returnSignature()), StreamColor_Blue), Column(stringify(method.parametersSignature()), StreamColor_Yellow) }); if (showDoc && !method.description().empty()) { print(Line { Column(method.description(), StreamColor_DarkGreen) }); } // return type if (showDoc && !method.returnDescription().empty()) { print(Line{ Column(returnDescrLabel.to_string(), StreamColor_Brown), Column(method.returnDescription(), StreamColor_DarkGreen) }); } if (recurse == RecurseOption::Recurse) { const auto typeInterface = TypeInterface::fromSignature(method.returnSignature()); print(typeInterface, [](const std::string& typeName) -> optional<Line> { return Line({ Column(returnTypeLabel.to_string(), StreamColor_Teal), Column(typeName, StreamColor_Yellow) }); }); } // parameters const auto parameters = method.parameters(); printParameters(method.parametersSignature().children(), parametersLabel.to_string(), recurse, [&](int index) -> optional<Line> { if (!showDoc || index >= static_cast<int>(parameters.size())) { return {}; } const auto& param = parameters[static_cast<std::size_t>(index)]; return Line{ { Column(param.name(), StreamColor_Brown), Column(param.description(), StreamColor_DarkGreen) } }; }); } void PrettyPrintStream::print(const MetaSignal& signal, int offsetLabel, RecurseOption recurse) { print(Line{ Column(signal.uid(), StreamColor_Blue, Column::Alignment::Right, {}, idColumnWidth, '0'), Column(signal.name(), StreamColor_None, Column::Alignment::Left, Column::Options{ Column::Option::DelimitWithSpace }, offsetLabel), Column(stringify(signal.parametersSignature()), StreamColor_Yellow) }); printParameters(signal.parametersSignature().children(), signalTypesLabel.to_string(), recurse); } void PrettyPrintStream::print(const MetaProperty& property, int offsetLabel, RecurseOption recurse) { print(Line{ Column(property.uid(), StreamColor_Blue, Column::Alignment::Right, {}, idColumnWidth, '0'), Column(property.name(), StreamColor_None, Column::Alignment::Left, Column::Options{ Column::Option::DelimitWithSpace }, offsetLabel), Column(stringify(property.signature()), StreamColor_Yellow) }); if (recurse == RecurseOption::Recurse) { const auto type = TypeInterface::fromSignature(property.signature()); print(type, [](const std::string&) -> optional<Line> { return {}; }); // no header } } void PrettyPrintStream::print(TypeInterface* type) { print(type, [](const std::string& name) -> optional<Line> { return Line { Column(name, StreamColor_Yellow) }; }); } /// Procedure<optional<Line> (std::string)> Proc template <typename Proc> void PrettyPrintStream::print(TypeInterface* type, Proc makeHeaderLine) { const std::string typeName = type ? stringify(type->signature()) : "unknown"; const auto line = makeHeaderLine(typeName); if (line) { print(*line); } if (type) { auto typeIndentLevel = makeIndentLevel(); printDetails(*type); } } void PrettyPrintStream::printDetails(TypeInterface& type) { switch (type.kind()) { case TypeKind_Tuple: print(static_cast<StructTypeInterface&>(type)); break; case TypeKind_List: print(static_cast<ListTypeInterface&>(type)); break; case TypeKind_Map: print(static_cast<MapTypeInterface&>(type)); break; default: // no details to print for all other types break; } } void PrettyPrintStream::print(StructTypeInterface& structType) { using boost::range::max_element; const auto memberTypes = structType.memberTypes(); const auto elementNames = structType.elementsName(); const auto cmpStringSize = [](const std::string& lhs, const std::string& rhs) { return lhs.size() < rhs.size(); }; const auto offset = [&] { if (elementNames.empty()) return 0; const auto maxElemIt = max_element(elementNames, cmpStringSize); return std::min(numericConvertBound<int>(maxElemIt->size()), maxOffset); }(); if (!memberTypes.empty()) { print(Line{ { Column(membersLabel.to_string(), StreamColor_Teal) } }); } IndentLevelPtr membersLevelIndent = makeIndentLevel(); for (std::size_t memberIndex = 0; memberIndex < memberTypes.size(); ++memberIndex) { const auto elementName = (memberIndex < elementNames.size() ? elementNames[memberIndex] : os::to_string(memberIndex)); const auto memberType = memberTypes.at(memberIndex); print(Line{ { Column(elementName, StreamColor_None, Column::Alignment::Left, {}, offset), Column(stringify(memberType->signature()), StreamColor_Yellow) } }); } } void PrettyPrintStream::print(ListTypeInterface& listType) { TypeInterface* const elementType = listType.elementType(); print(elementType, [](const std::string& typeName) -> optional<Line> { return Line{ { Column(elementTypeLabel.to_string(), StreamColor_Teal), Column(typeName, StreamColor_Yellow) } }; }); } void PrettyPrintStream::print(MapTypeInterface& mapType) { using boost::range::max_element; const auto cmpStringSize = [](string_ref lhs, string_ref rhs) { return lhs.size() < rhs.size(); }; const std::vector<string_ref> labels {keyTypeLabel, elementTypeLabel}; const auto maxLabelIt = max_element(labels, cmpStringSize); const auto offset = std::min(numericConvertBound<int>(maxLabelIt->size()), maxOffset); TypeInterface* const keyType = mapType.keyType(); print(keyType, [&](const std::string& typeName) -> optional<Line> { return Line{ Column(labels.at(0).to_string(), StreamColor_Teal, Column::Alignment::Left, {}, offset), Column(typeName, StreamColor_Yellow) }; }); TypeInterface* const elementType = mapType.elementType(); print(elementType, [&](const std::string& typeName) -> optional<Line> { return Line{ Column(labels.at(1).to_string(), StreamColor_Teal, Column::Alignment::Left, {}, offset), Column(typeName, StreamColor_Yellow) }; }); } void PrettyPrintStream::increaseIndent() { const auto maxIndentLevel = std::numeric_limits<decltype(_indentLevel)>::max(); if (_indentLevel == maxIndentLevel) { return; } ++_indentLevel; } void PrettyPrintStream::decreaseIndent() { if (_indentLevel == 0) { return; } --_indentLevel; } StreamColor PrettyPrintStream::colorIfEnabled(StreamColor color) const { return qi::enabledColor(color, _options.test(Option::Colorized)); } std::string PrettyPrintStream::stringify(const Signature& signature) const { return _options.test(Option::RawSignatures) ? signature.toString() : signature.toPrettySignature(); } void PrettyPrintStream::print(const Column& column) const { auto& stream = *_stream; stream << colorIfEnabled(column.color); switch (column.alignment) { case Column::Alignment::Left: stream << std::left; break; case Column::Alignment::Right: stream << std::right; break; case Column::Alignment::Internal: stream << std::internal; break; default: throw std::runtime_error("unknown column alignement value"); } stream << std::setfill(column.fillChar) << std::setw(column.width) << column.value; // reset default config stream << std::left << std::setfill(' ') << std::setw(0) << colorIfEnabled(StreamColor_Reset); } void PrettyPrintStream::printParameters(const std::vector<Signature>& signatures, const std::string& label, RecurseOption recurse) { printParameters(signatures, label, recurse, [](int) -> boost::optional<Line> { return {}; }); } /// Procedure<optional<Line> (int)> Proc template <typename Proc> void PrettyPrintStream::printParameters(const std::vector<Signature>& signatures, const std::string& label, RecurseOption recurse, Proc makeExtraLine) { if (signatures.empty()) { return; } IndentLevelPtr paramsIndentLevel; if (recurse == RecurseOption::Recurse) { print(Line{ Column(std::move(label), StreamColor_Teal) }); paramsIndentLevel = makeIndentLevel(); } for (std::size_t index = 0; index < signatures.size(); ++index) { const auto& param = signatures[index]; const auto type = TypeInterface::fromSignature(param); if (recurse == RecurseOption::Recurse) { print(type, [&](const std::string& typeName) -> optional<Line> { return Line{ { Column(os::to_string(index + 1) + ":", StreamColor_Red), Column(typeName, StreamColor_Yellow) } }; }); } const auto line = makeExtraLine(numericConvertBound<int>(index)); if (line) { print(*line); } } } PrettyPrintStream::IndentLevel::IndentLevel(PrettyPrintStream& printer) : _printer(printer) { _printer.increaseIndent(); } PrettyPrintStream::IndentLevel::~IndentLevel() { _printer.decreaseIndent(); } PrettyPrintStream::Column::Column(PrettyPrintStream::Column::ValueType value, StreamColor color, Alignment alignment, Options opts, int width, char fillChar) : value(value) , color(color) , alignment(alignment) , opts(opts) , width(width) , fillChar(fillChar) {} PrettyPrintStream::Line::Line(const std::initializer_list<PrettyPrintStream::Column>& columns) : columns(columns) , opts({Option::NewLine, Option::Indent}) {} PrettyPrintStream::Line::Line(const Columns& columns, Options opts) : columns(columns) , opts(opts) {} ParseablePrintStream::ParseablePrintStream(std::ostream& stream, DisplayHiddenMembers displayHidden) : _stream(&stream) , _displayHidden(displayHidden) { } void ParseablePrintStream::print(const MetaObject& mobj) { const auto displayHidden = (_displayHidden == DisplayHiddenMembers::Display); using boost::adaptors::filtered; { const auto unfilteredMethods = mobj.methodMap(); const auto methods = unfilteredMethods | filtered(MustDisplay<MetaMethod>{ displayHidden }); printMetaObjectMembers(methods); } { const auto unfilteredSignals = mobj.signalMap(); const auto signals = unfilteredSignals | filtered(MustDisplay<MetaSignal>{ displayHidden }); printMetaObjectMembers(signals); } { const auto unfilteredProps = mobj.propertyMap(); const auto props = unfilteredProps | filtered(MustDisplay<MetaProperty>{ displayHidden }); printMetaObjectMembers(props); } } /// Linearizable<std::pair<_, MetaMethod || MetaSignal || MetaProperty>> L template <typename L> void ParseablePrintStream::printMetaObjectMembers(const L& members) { using V = typename L::value_type; using boost::adaptors::transformed; using boost::algorithm::join; *_stream << ":" << join(members | transformed([](const V& v) { return v.second.name(); }), ","); } } }
33.596396
118
0.641907
Maelic
7841344760bd042429bc06413fd888541321d7ab
2,282
cpp
C++
ODFAEG/src/odfaeg/Graphics/mesh.cpp
Cwc-Test/ODFAEG
5e5bd13e3145764c3d0182225aad591040691481
[ "Zlib" ]
5
2015-06-13T13:11:59.000Z
2020-04-17T23:10:23.000Z
ODFAEG/src/odfaeg/Graphics/mesh.cpp
Cwc-Test/ODFAEG
5e5bd13e3145764c3d0182225aad591040691481
[ "Zlib" ]
4
2019-01-07T11:46:21.000Z
2020-02-14T15:04:15.000Z
ODFAEG/src/odfaeg/Graphics/mesh.cpp
Cwc-Test/ODFAEG
5e5bd13e3145764c3d0182225aad591040691481
[ "Zlib" ]
4
2016-01-05T09:54:57.000Z
2021-01-06T18:52:26.000Z
#include "../../../include/odfaeg/Graphics/mesh.hpp" namespace odfaeg { namespace graphic { Mesh::Mesh() : Entity(math::Vec3f(0, 0, 0), math::Vec3f(0, 0, 0),math::Vec3f(0, 0, 0), "E_MESH") {} Mesh::Mesh(math::Vec3f position, math::Vec3f size, std::string type) : Entity(position, size, size*0.5f, type) {} bool Mesh::operator==(Entity& other) { Mesh *mesh = dynamic_cast<Mesh*>(&other); if (mesh == nullptr) return false; if (!(getPosition().x == other.getPosition().x && getPosition().y == other.getPosition().y && getPosition().z == other.getPosition().z && getSize().x == other.getSize().x && getSize().y == other.getSize().y)) return false; for (unsigned int i = 0; i < mesh->getNbFaces(); i++) { if(!(getFace(i)->getMaterial() == other.getFace(i)->getMaterial() && getFace(i)->getMaterial().getTexRect().left == other.getFace(i)->getMaterial().getTexRect().left && getFace(i)->getMaterial().getTexRect().top == other.getFace(i)->getMaterial().getTexRect().top && getFace(i)->getMaterial().getTexRect().height == other.getFace(i)->getMaterial().getTexRect().height && getFace(i)->getMaterial().getTexRect().width == other.getFace(i)->getMaterial().getTexRect().width)) return false; } return true; } bool Mesh::isAnimated() const { return false; } bool Mesh::isModel() const { return true; } bool Mesh::selectable() const { return true; } bool Mesh::isLight() const { return false; } bool Mesh::isShadow() const { return false; } bool Mesh::isLeaf() const { return true; } void Mesh::onDraw(RenderTarget& target, RenderStates states) { for (unsigned int i = 0; i < getFaces().size(); i++) { states.texture = getFaces()[i]->getMaterial().getTexture(); target.draw(getFaces()[i]->getVertexArray(), states); } } } }
43.884615
121
0.508764
Cwc-Test
7842ca9894501cc7da94c881f00315d3a03569d1
64
cpp
C++
src/base/database/models/relations/BelongsToMany.cpp
YuDe95/mcplayer
c43d7c6fcafef0f093efef9248e9cf69b56aee2f
[ "MIT" ]
18
2020-03-02T06:56:05.000Z
2022-03-31T11:05:40.000Z
src/base/database/models/relations/BelongsToMany.cpp
YuDe95/mcplayer
c43d7c6fcafef0f093efef9248e9cf69b56aee2f
[ "MIT" ]
1
2020-03-03T19:28:52.000Z
2020-03-03T19:28:52.000Z
src/base/database/models/relations/BelongsToMany.cpp
YuDe95/mcplayer
c43d7c6fcafef0f093efef9248e9cf69b56aee2f
[ "MIT" ]
4
2020-03-20T13:56:57.000Z
2021-06-16T09:48:23.000Z
#include "BelongsToMany.h" BelongsToMany::BelongsToMany() { }
9.142857
30
0.734375
YuDe95
7844838549efadd7bc71939e41512ec1930711eb
787
hpp
C++
src/datagrams/DatagramParserFactory.hpp
HugoValcourt/MBES-lib
1e3aaf873a03a2e57ebcd029a5f7461c26fc9bc8
[ "MIT" ]
null
null
null
src/datagrams/DatagramParserFactory.hpp
HugoValcourt/MBES-lib
1e3aaf873a03a2e57ebcd029a5f7461c26fc9bc8
[ "MIT" ]
null
null
null
src/datagrams/DatagramParserFactory.hpp
HugoValcourt/MBES-lib
1e3aaf873a03a2e57ebcd029a5f7461c26fc9bc8
[ "MIT" ]
null
null
null
/* * Copyright 2019 © Centre Interdisciplinaire de développement en Cartographie des Océans (CIDCO), Tous droits réservés */ #ifndef DATAGRAMPARSERFACTORY_HPP #define DATAGRAMPARSERFACTORY_HPP #include "DatagramParser.hpp" #include "kongsberg/KongsbergParser.hpp" #include "xtf/XtfParser.hpp" #include "s7k/S7kParser.hpp" #include "../utils/StringUtils.hpp" #include "../utils/Exception.hpp" /*! * \brief Datagram parser factory class * \author Guillaume Labbe-Morissette * * Creates an appropriate parser */ class DatagramParserFactory{ public: /** * Creates the appropriate parser for the given file. Throws exception for unknown formats * @param filename the name of the file */ static DatagramParser * build(std::string & fileName,DatagramEventHandler & handler); }; #endif
25.387097
118
0.772554
HugoValcourt
784535ea5b3d921b36d83a815b873d63f230d454
5,803
hpp
C++
FlexEngine/include/InputManager.hpp
ajweeks/Rendering-Engine
fe0f2cdb44a067fec875110572b3b91f5f4c659c
[ "MIT" ]
762
2017-11-07T23:40:58.000Z
2022-03-31T16:03:22.000Z
FlexEngine/include/InputManager.hpp
ajweeks/Rendering-Engine
fe0f2cdb44a067fec875110572b3b91f5f4c659c
[ "MIT" ]
5
2018-03-13T14:41:06.000Z
2020-11-01T12:02:29.000Z
FlexEngine/include/InputManager.hpp
ajweeks/Rendering-Engine
fe0f2cdb44a067fec875110572b3b91f5f4c659c
[ "MIT" ]
43
2017-11-17T11:22:37.000Z
2022-03-14T01:51:19.000Z
#pragma once #include "InputTypes.hpp" #include "Pair.hpp" #include <map> namespace flex { class ICallbackMouseButton; class ICallbackMouseMoved; class ICallbackKeyEvent; class ICallbackAction; enum class CursorMode; /* * There are three main ways of retrieving input: * 1. Call GetKey(Down/Pressed) with a key code value * - This is the fastest, but also least portable method. Good for debugging. * * 2. Call GetActionDown with an action type * - This requires setting up an abstract representation of the input * action, but allows for users to remap the key code to whatever they like * * 3. Register as a listener * - This is the most involved method, but allows for full input binding * and proper event consumption. This is the method all real game inputs * should use. */ class InputManager { public: void Initialize(); void Update(); void PostUpdate(); void UpdateGamepadState(i32 gamepadIndex, real axes[6], u8 buttons[15]); GamepadState& GetGamepadState(i32 gamepadIndex); i32 GetActionDown(Action action) const; bool GetActionPressed(Action action) const; bool GetActionReleased(Action action) const; real GetActionAxisValue(Action action) const; i32 GetKeyDown(KeyCode keyCode, bool bIgnoreImGui = false) const; bool GetKeyPressed(KeyCode keyCode, bool bIgnoreImGui = false) const; bool GetKeyReleased(KeyCode keyCode, bool bIgnoreImGui = false) const; bool IsGamepadButtonDown(i32 gamepadIndex, GamepadButton button) const; bool IsGamepadButtonPressed(i32 gamepadIndex, GamepadButton button) const; bool IsGamepadButtonReleased(i32 gamepadIndex, GamepadButton button) const; real GetPrevGamepadAxisValue(i32 gamepadIndex, GamepadAxis axis) const; real GetGamepadAxisValue(i32 gamepadIndex, GamepadAxis axis) const; // Axis-equivalent to button "press" bool HasGamepadAxisValueJustPassedThreshold(i32 gamepadIndex, GamepadAxis axis, real threshold) const; void CursorPosCallback(double x, double y); void MouseButtonCallback(MouseButton mouseButton, KeyAction keyAction, i32 mods); void ScrollCallback(double xOffset, double yOffset); void KeyCallback(KeyCode keyCode, KeyAction keyAction, i32 mods); void CharCallback(u32 character); bool DidMouseWrap() const; glm::vec2 GetMousePosition() const; void ClearMouseMovement(); // Returns distance mouse has moved since last frame glm::vec2 GetMouseMovement(bool bIgnoreImGui = false) const; void ClearMouseButton(MouseButton mouseButton); bool IsAnyMouseButtonDown(bool bIgnoreImGui = false) const; bool IsMouseButtonDown(MouseButton mouseButton, bool bIgnoreImGui = false) const; bool IsMouseButtonPressed(MouseButton mouseButton, bool bIgnoreImGui = false) const; bool IsMouseButtonReleased(MouseButton mouseButton, bool bIgnoreImGui = false) const; real GetVerticalScrollDistance(bool bIgnoreImGui = false) const; real GetHorizontalScrollDistance(bool bIgnoreImGui = false) const; void ClearVerticalScrollDistance(); void ClearHorizontalScrollDistance(); // posNorm: normalized position of center of the rect [-1, 1] (y = 1 at top of screen) // sizeNorm: normalized size of the rect [0, 1] bool IsMouseHoveringRect(const glm::vec2& posNorm, const glm::vec2& sizeNorm); glm::vec2 GetMouseDragDistance(MouseButton mouseButton); void ClearMouseDragDistance(MouseButton mouseButton); void ClearAllInputs(); void ClearMouseInput(); void ClearKeyboadInput(); void ClearGampadInput(i32 gamepadIndex); void BindMouseButtonCallback(ICallbackMouseButton* callback, i32 priority); void UnbindMouseButtonCallback(ICallbackMouseButton* callback); void BindMouseMovedCallback(ICallbackMouseMoved* callback, i32 priority); void UnbindMouseMovedCallback(ICallbackMouseMoved* callback); void BindKeyEventCallback(ICallbackKeyEvent* callback, i32 priority); void UnbindKeyEventCallback(ICallbackKeyEvent* callback); void BindActionCallback(ICallbackAction* callback, i32 priority); void UnbindActionCallback(ICallbackAction* callback); void DrawImGuiBindings(bool* bOpen); void OnWindowFocusChanged(bool bNowFocused); void OnCursorModeChanged(CursorMode newMode); static char GetShiftModifiedKeyCode(char c); static i32 s_JoystickDisconnected; private: void HandleRadialDeadZone(real* x, real* y); // Returns true if file was found and is complete bool LoadInputBindingsFromFile(); void SaveInputBindingsToFile(); Action GetActionFromKeyCode(KeyCode keyCode); Action GetActionFromMouseButton(MouseButton button); Action GetActionFromMouseAxis(MouseAxis axis); Action GetActionFromGamepadButton(GamepadButton button); static bool IsGamepadAxisInvertable(GamepadAxis gamepadAxis); static const i32 GAMEPAD_BUTTON_COUNT = (i32)GamepadButton::_NONE; static const i32 MOUSE_BUTTON_COUNT = (i32)MouseButton::_NONE; static const real MAX_JOYSTICK_ROTATION_SPEED; std::map<KeyCode, Key> m_Keys; // Contains one entry for each entry in the Action enum InputBinding m_InputBindings[(i32)Action::_NONE + 1]; std::vector<Pair<ICallbackMouseButton*, i32>> m_MouseButtonCallbacks; std::vector<Pair<ICallbackMouseMoved*, i32>> m_MouseMovedCallbacks; std::vector<Pair<ICallbackKeyEvent*, i32>> m_KeyEventCallbacks; std::vector<Pair<ICallbackAction*, i32>> m_ActionCallbacks; u32 m_MouseButtonStates; u32 m_MouseButtonsPressed; u32 m_MouseButtonsReleased; MouseDrag m_MouseButtonDrags[MOUSE_BUTTON_COUNT]; glm::vec2 m_MousePosition = { 0, 0 }; glm::vec2 m_PrevMousePosition = { 0, 0 }; real m_ScrollXOffset = 0; real m_ScrollYOffset = 0; bool m_bMouseWrapped = false; bool m_bInputBindingsDirty = false; GamepadState m_pGamepadStates[2]; GamepadState m_GamepadStates[2]; }; } // namespace flex
36.961783
104
0.780286
ajweeks
78466b67624df1034ca45b046750e0fe454b9261
509
cpp
C++
Non-Ideone/Spoj/NSTEPS/NSTEPS-20015764.cpp
beingsushant/BunnyKeCodes
018cae93935ee30ce02561d05cda091ebb6e9643
[ "MIT" ]
1
2018-02-18T13:59:42.000Z
2018-02-18T13:59:42.000Z
Non-Ideone/Spoj/NSTEPS/NSTEPS-20015764.cpp
beingsushant/BunnyKeCodes
018cae93935ee30ce02561d05cda091ebb6e9643
[ "MIT" ]
null
null
null
Non-Ideone/Spoj/NSTEPS/NSTEPS-20015764.cpp
beingsushant/BunnyKeCodes
018cae93935ee30ce02561d05cda091ebb6e9643
[ "MIT" ]
2
2019-10-31T17:28:17.000Z
2019-10-31T17:52:11.000Z
#include<iostream> #include<cstdio> using namespace std; int main() { int x,y,r,t; cin>>t; while(t--) { cin>>x>>y; if(x==y) { if(x%2==0) r=2*x; else r=2*x-1; cout<<r<<endl; } else if(x==y+2) { if(x%2==0) r=x+y; else r=x+y-1; cout<<r<<endl; } else cout<<"No Number"<<endl; } }
16.419355
36
0.308448
beingsushant
784730e35cf449d2abf1010b5b3bdc53fca63974
2,370
cpp
C++
Week9/ParticleText/src/TextUtilities.cpp
bakercp/ExperimentalMedia2013
b0e748104c327d14e2231a0a98282503712702ed
[ "MIT" ]
4
2015-01-19T03:26:26.000Z
2015-06-03T04:00:04.000Z
Week9/ParticleText/src/TextUtilities.cpp
bakercp/ExperimentalMedia2013
b0e748104c327d14e2231a0a98282503712702ed
[ "MIT" ]
null
null
null
Week9/ParticleText/src/TextUtilities.cpp
bakercp/ExperimentalMedia2013
b0e748104c327d14e2231a0a98282503712702ed
[ "MIT" ]
null
null
null
#include "TextUtilities.h" #include "Poco/RegularExpression.h" #include "Poco/StringTokenizer.h" #include "Poco/TextIterator.h" #include "Poco/TextConverter.h" #include "Poco/UTF8Encoding.h" #include "Poco/UnicodeConverter.h" #include "Poco/Unicode.h" #include "ofUtils.h" #include "ofFileUtils.h" // a simple function for loading text into a string std::string TextUtilities::loadFile(const std::string& textFile) { ofBuffer buffer = ofBufferFromFile(textFile); return ofBufferFromFile(textFile).getText(); } // a function that removes commas and periods (could be more) std::string TextUtilities::stripPunctuation(const std::string& buffer) { static Poco::RegularExpression regex("[,.]"); std::string output = buffer; regex.subst(output,"",Poco::RegularExpression::RE_GLOBAL); // replace with nothing return output; } // a function that splits a long string into words (by looking for spaces) std::vector<std::string> TextUtilities::splitIntoWords(const std::string& buffer) { std::vector<std::string> output; Poco::StringTokenizer tokenizer(buffer, " "); Poco::StringTokenizer::Iterator iter = tokenizer.begin(); while (iter != tokenizer.end()) { output.push_back(*iter); ++iter; } return output; } // a function that splits a word string into a series of letters // NOTE: this does not currently deal with unicode (multi-byte) text. // Casting to char (char) below, effectively destroys multi-byte text. // There are ways around this, but it's tricky. This will be solved in the // next version of openFrameworks. std::vector<std::string> TextUtilities::splitIntoLetters(const std::string& buffer) { std::vector<std::string> output; // google Poco::UTF8Encoding and take a look at // http:://pocoproject.org/slides/040-StringsAndFormatting.pdf Poco::UTF8Encoding utf8Encoding; std::string utf8String(buffer); Poco::TextIterator iter(utf8String, utf8Encoding); Poco::TextIterator end(utf8String); int n = 0; while (iter != end) { int unicodeCharacter = *iter; char asciiCharacter = (char) unicodeCharacter; // BAAAAD. Very bad. Very very bad. std::string outChar(1,asciiCharacter); output.push_back(outChar); ++n; // number of UTF8 characters ++iter; // iterator } return output; }
28.902439
92
0.69789
bakercp
7849c406df4ab3b10ea82ff1a083643a71f1194c
4,466
cpp
C++
test/src/test_cases/composite_state.cpp
fgoujeon/fgfsm
ab3a4b244fb68854431891e5f084362589a41fc3
[ "BSL-1.0" ]
null
null
null
test/src/test_cases/composite_state.cpp
fgoujeon/fgfsm
ab3a4b244fb68854431891e5f084362589a41fc3
[ "BSL-1.0" ]
null
null
null
test/src/test_cases/composite_state.cpp
fgoujeon/fgfsm
ab3a4b244fb68854431891e5f084362589a41fc3
[ "BSL-1.0" ]
null
null
null
//Copyright Florian Goujeon 2021 - 2022. //Distributed under the Boost Software License, Version 1.0. //(See accompanying file LICENSE or copy at //https://www.boost.org/LICENSE_1_0.txt) //Official repository: https://github.com/fgoujeon/awesm #include <awesm.hpp> #include <catch2/catch.hpp> namespace { struct sm_configuration; using sm_t = awesm::simple_sm<sm_configuration>; enum class led_color { off, red, green, blue }; struct context { led_color current_led_color = led_color::off; }; namespace events { struct power_button_press{}; struct color_button_press{}; } namespace actions { template<led_color Color> struct set_led_color { void execute() { ctx.current_led_color = Color; } context& ctx; }; }; namespace states { struct off{}; struct emitting_red { void on_entry() { ctx.current_led_color = led_color::red; } void on_exit() { } sm_t& sm; context& ctx; }; struct emitting_green { void on_entry() { ctx.current_led_color = led_color::green; } void on_exit() { } sm_t& sm; context& ctx; }; struct emitting_blue { void on_entry() { ctx.current_led_color = led_color::blue; } void on_exit() { } sm_t& sm; context& ctx; }; class on { public: on(sm_t& sm, context& ctx): subsm_(sm, ctx), ctx_(ctx) { } void on_entry() { subsm_.reset(); subsm_.start(); } template<class Event> void on_event(const Event& event) { subsm_.process_event(event); } void on_exit() { subsm_.stop(); ctx_.current_led_color = led_color::off; } private: struct subsm_configuration: awesm::simple_subsm_configuration { using transition_table = awesm::transition_table < awesm::row<states::emitting_red, events::color_button_press, states::emitting_green>, awesm::row<states::emitting_green, events::color_button_press, states::emitting_blue>, awesm::row<states::emitting_blue, events::color_button_press, states::emitting_red> >; }; using subsm_t = awesm::simple_subsm<subsm_configuration>; subsm_t subsm_; context& ctx_; }; } struct sm_configuration: awesm::simple_sm_configuration { using transition_table = awesm::transition_table < awesm::row<states::off, events::power_button_press, states::on>, awesm::row<states::on, events::power_button_press, states::off> >; }; } TEST_CASE("composite_state") { auto ctx = context{}; auto sm = sm_t{ctx}; REQUIRE(sm.is_active_state<states::off>()); REQUIRE(ctx.current_led_color == led_color::off); sm.process_event(events::power_button_press{}); REQUIRE(sm.is_active_state<states::on>()); REQUIRE(ctx.current_led_color == led_color::red); sm.process_event(events::color_button_press{}); REQUIRE(sm.is_active_state<states::on>()); REQUIRE(ctx.current_led_color == led_color::green); sm.process_event(events::color_button_press{}); REQUIRE(sm.is_active_state<states::on>()); REQUIRE(ctx.current_led_color == led_color::blue); sm.process_event(events::power_button_press{}); REQUIRE(sm.is_active_state<states::off>()); REQUIRE(ctx.current_led_color == led_color::off); sm.process_event(events::power_button_press{}); REQUIRE(sm.is_active_state<states::on>()); REQUIRE(ctx.current_led_color == led_color::red); }
24.811111
111
0.515226
fgoujeon
784b543203a3474c485250046f9613ea783d928f
2,362
cpp
C++
Ethereal/Private/Gear/Armor/Body/LeatherVest.cpp
SoveranceStudios/EtherealLegends
4d03aba462cc3a51988e2776e182cea05f0e4376
[ "Apache-2.0" ]
216
2016-08-28T18:22:06.000Z
2022-03-22T09:08:15.000Z
Ethereal/Private/Gear/Armor/Body/LeatherVest.cpp
SoveranceStudios/EtherealLegends
4d03aba462cc3a51988e2776e182cea05f0e4376
[ "Apache-2.0" ]
1
2017-08-10T06:14:32.000Z
2017-08-12T00:16:27.000Z
Ethereal/Private/Gear/Armor/Body/LeatherVest.cpp
SoveranceStudios/EtherealLegends
4d03aba462cc3a51988e2776e182cea05f0e4376
[ "Apache-2.0" ]
49
2016-08-28T18:22:31.000Z
2022-02-23T16:22:37.000Z
// ÀšÃ‚© 2014 - 2016 Soverance Studios // http://www.soverance.com // 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 "Ethereal.h" #include "LeatherVest.h" #define LOCTEXT_NAMESPACE "EtherealText" // Sets default values ALeatherVest::ALeatherVest(const FObjectInitializer& ObjectInitializer) : Super(ObjectInitializer) { // Get Assets, References Obtained Via Right Click in Editor static ConstructorHelpers::FObjectFinder<UTexture2D> LargeIconObject(TEXT("Texture2D'/Game/Blueprints/Widgets/UI-Images/Icons_Gear/ArmorIcon_LeatherVest.ArmorIcon_LeatherVest'")); static ConstructorHelpers::FObjectFinder<UTexture2D> SmallIconObject(TEXT("Texture2D'/Game/Blueprints/Widgets/UI-Images/Icons_Gear/ArmorIcon_LeatherVest-small.ArmorIcon_LeatherVest-small'")); static ConstructorHelpers::FObjectFinder<USkeletalMesh> ArmorMeshObject(TEXT("SkeletalMesh'/Game/EtherealParty/Morgan/Clothes/LeatherArmor/LeatherVest/LeatherVest.LeatherVest'")); // Set Default Objects LargeIcon = LargeIconObject.Object; SmallIcon = SmallIconObject.Object; SK_ArmorMesh = ArmorMeshObject.Object; ArmorMesh = ObjectInitializer.CreateDefaultSubobject<USkeletalMeshComponent>(this, TEXT("ArmorMesh")); ArmorMesh->SetSkeletalMesh(SK_ArmorMesh); ArmorMesh->SetupAttachment(RootComponent); UCommonLibrary::SetupSKComponentsWithCollision(ArmorMesh); // Set Default Values Name = EMasterGearList::GL_LeatherVest; NameText = LOCTEXT("LeatherVestName", "Leather Vest"); Type = EMasterGearTypes::GT_Body; TypeText = LOCTEXT("LeatherVestType", "Body"); Description = "Armor of Ethereal Warriors."; Price = 5000; MPCost = 0; ATK = 1; DEF = 2; SPD = 1; HP = 15; MP = 5; } // Called when the game starts or when spawned void ALeatherVest::BeginPlay() { Super::BeginPlay(); } #undef LOCTEXT_NAMESPACE
38.096774
193
0.762913
SoveranceStudios
785285a78295a6066131e1faebc441c976bf061a
1,094
hpp
C++
problems/03_nested_resources/ResourceRecover.hpp
ciscoruiz/emc2
2fb4c5f0ac3cf8f62938f2d2fd8b9b16c0686613
[ "MIT" ]
null
null
null
problems/03_nested_resources/ResourceRecover.hpp
ciscoruiz/emc2
2fb4c5f0ac3cf8f62938f2d2fd8b9b16c0686613
[ "MIT" ]
null
null
null
problems/03_nested_resources/ResourceRecover.hpp
ciscoruiz/emc2
2fb4c5f0ac3cf8f62938f2d2fd8b9b16c0686613
[ "MIT" ]
null
null
null
#ifndef ResourceRecover_hpp #define ResourceRecover_hpp #include <condition_variable> #include <ResourceContainer.hpp> class ResourceRecover : public ResourceContainer { public: ResourceRecover () : m_stop (false) {;} ResourceRecover (const ResourceRecover&) = delete; void requestStop () noexcept { std::unique_lock <std::mutex> r2 (m_mutex); m_stop = true; } bool stop (std::unique_lock <std::mutex>& guard) const noexcept { assert (guard.mutex () == &m_mutex); return m_stop; } void error (std::unique_lock <std::mutex>& guard, std::shared_ptr <Resource> resource) noexcept { assert (guard.mutex () == &m_mutex); insert (guard, resource); m_condition.notify_one (); } void wait (std::unique_lock <std::mutex>& guard) noexcept { assert (guard.mutex () == &m_mutex); auto now = std::chrono::system_clock::now(); m_condition.wait_until (guard, now + std::chrono::milliseconds(500)); } private: bool m_stop; std::condition_variable m_condition; }; #endif
24.311111
100
0.644424
ciscoruiz
7852964af8c36ecfa88637dc45283b1e20527be1
1,390
cpp
C++
Source/PakUtilities/Private/PakUtilitiesFunctionLibrary.cpp
calben/UnrealPakErrorDemoTmp
fa8d9124bad7e29e1387ca76a015ea021d566605
[ "MIT" ]
null
null
null
Source/PakUtilities/Private/PakUtilitiesFunctionLibrary.cpp
calben/UnrealPakErrorDemoTmp
fa8d9124bad7e29e1387ca76a015ea021d566605
[ "MIT" ]
null
null
null
Source/PakUtilities/Private/PakUtilitiesFunctionLibrary.cpp
calben/UnrealPakErrorDemoTmp
fa8d9124bad7e29e1387ca76a015ea021d566605
[ "MIT" ]
null
null
null
// Fill out your copyright notice in the Description page of Project Settings. #include "PakUtilitiesFunctionLibrary.h" //#include "Runtime/PakFile/Public/IPlatformFilePak.h" //TArray<FString> UPakUtilitiesFunctionLibrary::ListAvailablePakFiles() //{ // FPakPlatformFile* PakPlatformFile = new FPakPlatformFile(); // PakPlatformFile->Initialize(&InnerPlatformFile, TEXT("")); // // PakPlatformFile->Mount(*PakToLoad, 0, *(ModDir /*+ TEXT("/") + ModPakFileName*/)); // // TArray<FPakPlatformFile::FPakListEntry> MountedPaks; // PakPlatformFile->GetMountedPaks(MountedPaks); // // //ignore first pak, because it is default game pak and we don't need iterate over it // for (int32 i = 1; i < MountedPaks.Num(); i++) // { // const FPakPlatformFile::FPakListEntry& mountedPak = MountedPaks[i]; // const TMap<FString, FPakDirectory>& pakDirectoryMap = mountedPak.PakFile->GetIndex(); // // for (TMap<FString, FPakDirectory>::TConstIterator It(pakDirectoryMap); It; ++It) // { // FString Key = It.Key(); // const FPakDirectory& Val = It.Value(); // // for (FPakDirectory::TConstIterator It2(Val); It2; ++It2) // { // FString Key2 = It2.Key(); // FPakEntry* pakEntry = It2.Value(); // // if (Key2.Contains(TEXT(".umap"))) // { // //this is where you will get map name of course if your map have *.umap extension:) // Key2 = Key2; // } // } // } // } //}
30.888889
90
0.674101
calben
78546e5862873c9084c5869f33deafe64dff738c
239
cpp
C++
test/snippet/core/type_list/list_traits_front.cpp
marehr/nomchop
a88bfb6f5d4a291a71b6b3192eeac81fdc450d43
[ "CC-BY-4.0", "CC0-1.0" ]
1
2021-03-01T11:12:56.000Z
2021-03-01T11:12:56.000Z
test/snippet/core/type_list/list_traits_front.cpp
simonsasse/seqan3
0ff2e117952743f081735df9956be4c512f4ccba
[ "CC0-1.0", "CC-BY-4.0" ]
2
2017-05-17T07:16:19.000Z
2020-02-13T16:10:10.000Z
test/snippet/core/type_list/list_traits_front.cpp
simonsasse/seqan3
0ff2e117952743f081735df9956be4c512f4ccba
[ "CC0-1.0", "CC-BY-4.0" ]
null
null
null
#include <seqan3/core/type_list/traits.hpp> int main() { using list_t = seqan3::type_list<int, float, bool, int, float>; static_assert(std::same_as<int, seqan3::list_traits::front<list_t>>); // Check if the first value is int. }
26.555556
109
0.698745
marehr
7854e40f6861e6caf8a68aef05bcdf98f22a6ea8
734
cpp
C++
FlowGraph/FlowGraphWindow.cpp
grandpsykick/DataFlowGraph
d266d1706d800e9f414f809e9b5c116168667a56
[ "MIT" ]
1
2018-04-27T23:39:04.000Z
2018-04-27T23:39:04.000Z
FlowGraph/FlowGraphWindow.cpp
grandpsykick/DataFlowGraph
d266d1706d800e9f414f809e9b5c116168667a56
[ "MIT" ]
2
2017-05-23T15:33:01.000Z
2017-05-23T16:42:16.000Z
FlowGraph/FlowGraphWindow.cpp
grandpsykick/DataFlowGraph
d266d1706d800e9f414f809e9b5c116168667a56
[ "MIT" ]
null
null
null
#include "FlowGraphWindow.hpp" #include "ui_FlowGraphWindow.h" #include "FlowGraphScene.hpp" #include "FlowGraphView.hpp" #include "FlowGraphNode.hpp" FlowGraphWindow::FlowGraphWindow(FlowGraphScene * scene, FlowGraphView * view, QWidget * parent) : QMainWindow(parent), ui(new Ui::FlowGraphWindow), m_scene(scene), m_view(view) { ui->setupUi(this); if(this->m_scene == Q_NULLPTR) { this->m_view = new FlowGraphView(Q_NULLPTR, this); this->setCentralWidget(this->m_view); this->m_scene = dynamic_cast<FlowGraphScene*>(this->m_view->scene()); this->m_scene->addItem(new FlowGraphNode()); } } FlowGraphWindow::~FlowGraphWindow() { delete ui; }
28.230769
84
0.666213
grandpsykick
785bf036dd88891e6168766266da333fb05be748
501
cpp
C++
dbt/csv_i.cpp
aki-ph-chem/rot_const
7f05e252d15e4b30bfd9ec0627a239154f7fb468
[ "MIT" ]
null
null
null
dbt/csv_i.cpp
aki-ph-chem/rot_const
7f05e252d15e4b30bfd9ec0627a239154f7fb468
[ "MIT" ]
null
null
null
dbt/csv_i.cpp
aki-ph-chem/rot_const
7f05e252d15e4b30bfd9ec0627a239154f7fb468
[ "MIT" ]
null
null
null
# include "csv_i.h" #include <fstream> #include <string> #include <sstream> #include <vector> #include <iostream> using string = std::string; //std::vector<string> csv::split(string& reading_now,char delimiter) std::vector<string> csv::split(string& reading_now) { std::istringstream stream(reading_now); string field; std::vector<string> result; while (getline(stream, field, delimiter)) { result.push_back(field); } return result; }
20.04
69
0.646707
aki-ph-chem
785c7b6b61a629eac8e2f8eaa2b8406148ac7c9d
579
hpp
C++
src/main/include/StarDust/util/Math.hpp
4H-Botsmiths/InfiniteRecharge2020
811d71a49a50f38f44dcc7139786caaeaa99f739
[ "BSD-3-Clause" ]
null
null
null
src/main/include/StarDust/util/Math.hpp
4H-Botsmiths/InfiniteRecharge2020
811d71a49a50f38f44dcc7139786caaeaa99f739
[ "BSD-3-Clause" ]
1
2021-12-27T04:40:42.000Z
2021-12-27T04:40:42.000Z
src/main/include/StarDust/util/Math.hpp
4H-Botsmiths/InfiniteRecharge2020
811d71a49a50f38f44dcc7139786caaeaa99f739
[ "BSD-3-Clause" ]
null
null
null
//adds delta to value if positive. //subtracts delta from value if negative. double signedAdd(const double value, const double delta) { if (value < 0) { return value - delta; } else { return value + delta; } } //returns -1 if value is negative, 1 if value is positive. double signiness(const double value) { if (value < 0) { return -1; } else { return 1; } } //sets value to the signiness of "sign". double updateSign(double& const value, const double sign) { value*=signiness(sign); }
23.16
60
0.594128
4H-Botsmiths
785e93e5cf62dd7bfed42331151d4ccb759659c4
1,363
cpp
C++
tools/VMakeList/src/main.cpp
SergeyStrukov/CCore-3-xx
820507e78f8aa35ca05761e00e060c8f64c59af5
[ "BSL-1.0" ]
8
2017-12-21T07:00:16.000Z
2020-04-02T09:05:55.000Z
tools/VMakeList/src/main.cpp
SergeyStrukov/CCore-3-xx
820507e78f8aa35ca05761e00e060c8f64c59af5
[ "BSL-1.0" ]
null
null
null
tools/VMakeList/src/main.cpp
SergeyStrukov/CCore-3-xx
820507e78f8aa35ca05761e00e060c8f64c59af5
[ "BSL-1.0" ]
1
2020-03-30T09:54:18.000Z
2020-03-30T09:54:18.000Z
/* main.cpp */ //---------------------------------------------------------------------------------------- // // Project: VMakeList 1.00 // // License: Boost Software License - Version 1.0 - August 17th, 2003 // // see http://www.boost.org/LICENSE_1_0.txt or the local copy // // Copyright (c) 2019 Sergey Strukov. All rights reserved. // //---------------------------------------------------------------------------------------- #include <inc/Engine.h> #include <CCore/inc/Print.h> #include <CCore/inc/Exception.h> namespace App { /* Main() */ int Main(StrLen src_file_name,StrLen proj_file_name,StrLen prep_file_name) { DataFile data(src_file_name); Engine engine(data.getParam(),src_file_name,proj_file_name,prep_file_name); return engine.run(); } } // namespace App /* main() */ using namespace App; int usage() { Putobj(Con,"Usage: CCore-VMakeList <src-file-name> <proj-file-name> <prep-file-name>\n"); return 1; } int main(int argc,const char * argv[]) { try { ReportException report; int ret=0; { Putobj(Con,"--- VMakeList 1.00 ---\n--- Copyright (c) 2019 Sergey Strukov. All rights reserved. ---\n\n"); if( argc!=4 ) return usage(); ret=Main(argv[1],argv[2],argv[3]); } report.guard(); return ret; } catch(CatchType) { return 1; } }
19.197183
112
0.539252
SergeyStrukov
78603d7ec95558a3584503c770f965462b3dfd36
370
hpp
C++
include/hal/UART_base.hpp
suburbanembedded/emb_util
ded1f54e5c10ce962351416e6b6840dbedb112ba
[ "BSD-3-Clause" ]
null
null
null
include/hal/UART_base.hpp
suburbanembedded/emb_util
ded1f54e5c10ce962351416e6b6840dbedb112ba
[ "BSD-3-Clause" ]
null
null
null
include/hal/UART_base.hpp
suburbanembedded/emb_util
ded1f54e5c10ce962351416e6b6840dbedb112ba
[ "BSD-3-Clause" ]
null
null
null
#pragma once #include <cstdint> #include <cstddef> class UART_base { public: UART_base() { } virtual ~UART_base() { } virtual bool initialize() = 0; virtual bool open() = 0; virtual bool close() = 0; virtual size_t write(uint8_t const * const buf, const size_t len) = 0; virtual size_t read(uint8_t* const buf, const size_t len) = 0; protected: };
12.758621
72
0.667568
suburbanembedded
78639aea6d3d3699fa4bcfc13221885b88064e0f
5,081
cpp
C++
src/lib/ggpo/main.cpp
mangoes-git/ggpo
72d0219798ad058b8bdbcd7c78eec73a6b3d97d8
[ "MIT" ]
4
2021-11-16T19:37:28.000Z
2022-02-25T23:51:38.000Z
src/lib/ggpo/main.cpp
mangoes-git/ggpo-crossplatform
72d0219798ad058b8bdbcd7c78eec73a6b3d97d8
[ "MIT" ]
null
null
null
src/lib/ggpo/main.cpp
mangoes-git/ggpo-crossplatform
72d0219798ad058b8bdbcd7c78eec73a6b3d97d8
[ "MIT" ]
null
null
null
/* ----------------------------------------------------------------------- * GGPO.net (http://ggpo.net) - Copyright 2009 GroundStorm Studios, LLC. * * Use of this software is governed by the MIT license that can be found * in the LICENSE file. */ #include "types.h" #include "backends/p2p.h" #include "backends/synctest.h" #include "backends/spectator.h" #include "ggponet.h" void ggpo_log(GGPOSession *ggpo, const char *fmt, ...) { va_list args; va_start(args, fmt); ggpo_logv(ggpo, fmt, args); va_end(args); } void ggpo_logv(GGPOSession *ggpo, const char *fmt, va_list args) { if (ggpo) { ggpo->Logv(fmt, args); } } GGPOErrorCode ggpo_start_session(GGPOSession **session, GGPOSessionCallbacks *cb, const char *game, int num_players, int input_size, unsigned short localport) { *session= (GGPOSession *)new Peer2PeerBackend(cb, game, localport, num_players, input_size); return GGPO_OK; } GGPOErrorCode ggpo_add_player(GGPOSession *ggpo, GGPOPlayer *player, GGPOPlayerHandle *handle) { if (!ggpo) { return GGPO_ERRORCODE_INVALID_SESSION; } return ggpo->AddPlayer(player, handle); } GGPOErrorCode ggpo_start_synctest(GGPOSession **ggpo, GGPOSessionCallbacks *cb, char *game, int num_players, int input_size, int frames) { *ggpo = (GGPOSession *)new SyncTestBackend(cb, game, frames, num_players); return GGPO_OK; } GGPOErrorCode ggpo_set_frame_delay(GGPOSession *ggpo, GGPOPlayerHandle player, int frame_delay) { if (!ggpo) { return GGPO_ERRORCODE_INVALID_SESSION; } return ggpo->SetFrameDelay(player, frame_delay); } GGPOErrorCode ggpo_idle(GGPOSession *ggpo, int timeout) { if (!ggpo) { return GGPO_ERRORCODE_INVALID_SESSION; } return ggpo->DoPoll(timeout); } GGPOErrorCode ggpo_add_local_input(GGPOSession *ggpo, GGPOPlayerHandle player, void *values, int size) { if (!ggpo) { return GGPO_ERRORCODE_INVALID_SESSION; } return ggpo->AddLocalInput(player, values, size); } GGPOErrorCode ggpo_synchronize_input(GGPOSession *ggpo, void *values, int size, int *disconnect_flags) { if (!ggpo) { return GGPO_ERRORCODE_INVALID_SESSION; } return ggpo->SyncInput(values, size, disconnect_flags); } GGPOErrorCode ggpo_disconnect_player(GGPOSession *ggpo, GGPOPlayerHandle player) { if (!ggpo) { return GGPO_ERRORCODE_INVALID_SESSION; } return ggpo->DisconnectPlayer(player); } GGPOErrorCode ggpo_advance_frame(GGPOSession *ggpo) { if (!ggpo) { return GGPO_ERRORCODE_INVALID_SESSION; } return ggpo->IncrementFrame(); } GGPOErrorCode ggpo_client_chat(GGPOSession *ggpo, char *text) { if (!ggpo) { return GGPO_ERRORCODE_INVALID_SESSION; } return ggpo->Chat(text); } GGPOErrorCode ggpo_get_network_stats(GGPOSession *ggpo, GGPOPlayerHandle player, GGPONetworkStats *stats) { if (!ggpo) { return GGPO_ERRORCODE_INVALID_SESSION; } return ggpo->GetNetworkStats(stats, player); } GGPOErrorCode ggpo_close_session(GGPOSession *ggpo) { if (!ggpo) { return GGPO_ERRORCODE_INVALID_SESSION; } delete ggpo; return GGPO_OK; } GGPOErrorCode ggpo_set_disconnect_timeout(GGPOSession *ggpo, int timeout) { if (!ggpo) { return GGPO_ERRORCODE_INVALID_SESSION; } return ggpo->SetDisconnectTimeout(timeout); } GGPOErrorCode ggpo_set_disconnect_notify_start(GGPOSession *ggpo, int timeout) { if (!ggpo) { return GGPO_ERRORCODE_INVALID_SESSION; } return ggpo->SetDisconnectNotifyStart(timeout); } GGPOErrorCode ggpo_start_spectating(GGPOSession **session, GGPOSessionCallbacks *cb, const char *game, int num_players, int input_size, unsigned short local_port, char *host_ip, unsigned short host_port) { *session= (GGPOSession *)new SpectatorBackend(cb, game, local_port, num_players, input_size, host_ip, host_port); return GGPO_OK; }
25.153465
77
0.547727
mangoes-git
786a6f6cd2a60db27a7fe974a680e71e027ffabb
9,178
hpp
C++
stan/math/opencl/prim/normal_id_glm_lpdf.hpp
bayesmix-dev/math
3616f7195adc95ef8e719a2af845d61102bc9272
[ "BSD-3-Clause" ]
1
2020-06-14T14:33:37.000Z
2020-06-14T14:33:37.000Z
stan/math/opencl/prim/normal_id_glm_lpdf.hpp
bayesmix-dev/math
3616f7195adc95ef8e719a2af845d61102bc9272
[ "BSD-3-Clause" ]
null
null
null
stan/math/opencl/prim/normal_id_glm_lpdf.hpp
bayesmix-dev/math
3616f7195adc95ef8e719a2af845d61102bc9272
[ "BSD-3-Clause" ]
1
2020-05-10T12:55:07.000Z
2020-05-10T12:55:07.000Z
#ifndef STAN_MATH_OPENCL_PRIM_NORMAL_ID_GLM_LPDF_HPP #define STAN_MATH_OPENCL_PRIM_NORMAL_ID_GLM_LPDF_HPP #ifdef STAN_OPENCL #include <stan/math/opencl/prim/size.hpp> #include <stan/math/opencl/rev/operands_and_partials.hpp> #include <stan/math/opencl/copy.hpp> #include <stan/math/opencl/matrix_cl.hpp> #include <stan/math/opencl/prim/multiply.hpp> #include <stan/math/opencl/kernel_generator.hpp> #include <stan/math/prim/meta.hpp> #include <stan/math/prim/err.hpp> #include <stan/math/prim/fun/constants.hpp> #include <stan/math/prim/fun/elt_divide.hpp> #include <stan/math/prim/fun/size.hpp> #include <stan/math/prim/fun/size_zero.hpp> #include <stan/math/prim/fun/sum.hpp> #include <stan/math/prim/fun/to_ref.hpp> #include <stan/math/prim/fun/value_of_rec.hpp> #include <stan/math/prim/prob/normal_id_glm_lpdf.hpp> #include <cmath> namespace stan { namespace math { /** \ingroup opencl * Returns the log PDF of the Generalized Linear Model (GLM) * with Normal distribution and id link function. * If containers are supplied, returns the log sum of the probabilities. * This is an overload of the GLM in prim/prob/normal_id_glm_lpdf.hpp * that is implemented in OpenCL. * @tparam T_y_cl type of independent variable; * this can be a `matrix_cl` vector of intercepts or a single * value (wich will be broadcast - used for all instances); * @tparam T_x_cl type of the design matrix * @tparam T_alpha_cl type of the intercept(s); * this can be a (optionally `var_value` containing) `matrix_cl` column vector * (of the same length as y) of intercepts or a scalar (for models with * constant intercept) * @tparam T_beta_cl type of the weight vector; * (optionally `var_value` containing) `matrix_cl` column vector * @tparam T_sigma_cl type of the (positive) scale(s); * (optionally `var_value` containing) `matrix_cl` column vector (of the same * length as y, for heteroskedasticity) or a scalar. * @param y scalar or vector parameter on OpenCL device. If it is a scalar it * will be broadcast - used for all instances. * @param x design matrix on OpenCL device. This overload does not support * broadcasting of a row vector x! * @param alpha intercept (in log odds) * @param beta weight vector * @param sigma (Sequence of) scale parameters for the normal * distribution. * @return log probability or log sum of probabilities * @throw std::domain_error if x, beta or alpha is infinite. * @throw std::domain_error if the scale is not positive. * @throw std::invalid_argument if container sizes mismatch. */ template <bool propto, typename T_y_cl, typename T_x_cl, typename T_alpha_cl, typename T_beta_cl, typename T_sigma_cl, require_all_prim_or_rev_kernel_expression_t< T_x_cl, T_y_cl, T_alpha_cl, T_beta_cl, T_sigma_cl>* = nullptr> return_type_t<T_y_cl, T_x_cl, T_alpha_cl, T_beta_cl, T_sigma_cl> normal_id_glm_lpdf(const T_y_cl& y, const T_x_cl& x, const T_alpha_cl& alpha, const T_beta_cl& beta, const T_sigma_cl& sigma) { using T_partials_return = partials_return_t<T_y_cl, T_x_cl, T_alpha_cl, T_beta_cl, T_sigma_cl>; constexpr bool is_y_vector = !is_stan_scalar<T_y_cl>::value; constexpr bool is_sigma_vector = !is_stan_scalar<T_sigma_cl>::value; constexpr bool is_alpha_vector = !is_stan_scalar<T_alpha_cl>::value; using std::isfinite; static const char* function = "normal_id_glm_lpdf(OpenCL)"; const size_t N = x.rows(); const size_t M = x.cols(); if (is_y_vector) { check_size_match(function, "Rows of ", "x", N, "rows of ", "y", size(y)); } check_size_match(function, "Columns of ", "x_cl", M, "size of ", "beta", size(beta)); if (is_sigma_vector) { check_size_match(function, "Rows of ", "x", N, "size of ", "sigma", size(sigma)); } if (is_alpha_vector) { check_size_match(function, "Rows of ", "x", N, "size of ", "alpha", size(alpha)); } if (!include_summand<propto, T_y_cl, T_x_cl, T_alpha_cl, T_beta_cl, T_sigma_cl>::value) { return 0; } if (N == 0) { return 0; } const auto& y_val = value_of(y); const auto& x_val = value_of(x); const auto& alpha_val = value_of(alpha); const auto& beta_val = value_of(beta); const auto& sigma_val = value_of(sigma); auto inv_sigma_expr = elt_divide(1., sigma_val); auto y_scaled_expr = elt_multiply( (y_val - matrix_vector_multiply(x_val, beta_val) - alpha_val), inv_sigma_expr); auto mu_derivative_expr = elt_multiply(y_scaled_expr, inv_sigma_expr); auto mu_derivative_sum_expr = colwise_sum(mu_derivative_expr); auto y_scaled_sq_expr = elt_multiply(y_scaled_expr, y_scaled_expr); auto y_scaled_sq_sum_expr = colwise_sum(y_scaled_sq_expr); auto sigma_derivative_expr = elt_multiply((y_scaled_sq_expr - 1), inv_sigma_expr); auto log_sigma_sum_expr = colwise_sum(log(sigma_val)); const int wgs = y_scaled_sq_sum_expr.rows(); constexpr bool need_mu_derivative = !is_constant_all<T_x_cl, T_beta_cl>::value || (!is_constant<T_alpha_cl>::value && is_alpha_vector) || (!is_constant<T_y_cl>::value && is_y_vector); matrix_cl<double> mu_derivative_cl(need_mu_derivative ? N : 0, 1); constexpr bool need_mu_derivative_sum = (!is_constant<T_alpha_cl>::value && !is_alpha_vector) || (!is_constant<T_y_cl>::value && !is_y_vector); matrix_cl<double> mu_derivative_sum_cl(need_mu_derivative_sum ? wgs : 0, 1); matrix_cl<double> y_scaled_sq_sum_cl(wgs, 1); constexpr bool need_sigma_derivative = !is_constant_all<T_sigma_cl>::value; matrix_cl<double> sigma_derivative_cl(need_sigma_derivative ? N : 0, 1); constexpr bool need_log_sigma_sum = include_summand<propto, T_sigma_cl>::value && is_sigma_vector; matrix_cl<double> log_sigma_sum_cl(need_log_sigma_sum ? wgs : 0, 1); results(mu_derivative_cl, mu_derivative_sum_cl, y_scaled_sq_sum_cl, sigma_derivative_cl, log_sigma_sum_cl) = expressions(calc_if<need_mu_derivative>(mu_derivative_expr), calc_if<need_mu_derivative_sum>(mu_derivative_sum_expr), y_scaled_sq_sum_expr, calc_if<need_sigma_derivative>(sigma_derivative_expr), calc_if<need_log_sigma_sum>(log_sigma_sum_expr)); double y_scaled_sq_sum = sum(from_matrix_cl(y_scaled_sq_sum_cl)); operands_and_partials<T_y_cl, T_x_cl, T_alpha_cl, T_beta_cl, T_sigma_cl> ops_partials(y, x, alpha, beta, sigma); double mu_derivative_sum; if (need_mu_derivative_sum) { mu_derivative_sum = sum(from_matrix_cl(mu_derivative_sum_cl)); } if (!is_constant<T_y_cl>::value) { if (is_y_vector) { ops_partials.edge1_.partials_ = -mu_derivative_cl; } else { forward_as<internal::broadcast_array<double>>( ops_partials.edge1_.partials_)[0] = -mu_derivative_sum; } } if (!is_constant<T_x_cl>::value) { ops_partials.edge2_.partials_ = transpose(beta_val * transpose(mu_derivative_cl)); } if (!is_constant<T_alpha_cl>::value) { if (is_alpha_vector) { ops_partials.edge3_.partials_ = mu_derivative_cl; } else { forward_as<internal::broadcast_array<double>>( ops_partials.edge3_.partials_)[0] = mu_derivative_sum; } } if (!is_constant<T_beta_cl>::value) { // transposition of a vector can be done without copying const matrix_cl<double> mu_derivative_transpose_cl( mu_derivative_cl.buffer(), 1, mu_derivative_cl.rows()); matrix_cl<double>& edge4_partials = forward_as<matrix_cl<double>&>(ops_partials.edge4_.partials_); matrix_cl<double> edge4_partials_transpose_cl = mu_derivative_transpose_cl * x_val; edge4_partials = matrix_cl<double>(edge4_partials_transpose_cl.buffer(), edge4_partials_transpose_cl.cols(), 1); if (beta_val.rows() != 0) { edge4_partials.add_write_event( edge4_partials_transpose_cl.write_events().back()); } } if (!is_constant<T_sigma_cl>::value) { ops_partials.edge5_.partials_ = sigma_derivative_cl; } if (!std::isfinite(y_scaled_sq_sum)) { results( check_cl(function, "Vector of dependent variables", y_val, "finite"), check_cl(function, "Intercept", alpha_val, "finite"), check_cl(function, "Scale vector", sigma_val, "positive finite")) = expressions(isfinite(y_val), isfinite(alpha_val), isfinite(sigma_val) && sigma_val > 0); check_cl(function, "Weight vector", x_val, "finite") = isfinite(x_val); check_cl(function, "Weight vector", beta_val, "finite") = isfinite(beta_val); } // Compute log probability. T_partials_return logp(0.0); if (include_summand<propto>::value) { logp += NEG_LOG_SQRT_TWO_PI * N; } if (include_summand<propto, T_sigma_cl>::value) { if (is_sigma_vector) { logp -= sum(from_matrix_cl(log_sigma_sum_cl)); } else { logp -= N * log(forward_as<double>(sigma_val)); } } logp -= 0.5 * y_scaled_sq_sum; return ops_partials.build(logp); } } // namespace math } // namespace stan #endif #endif
41.156951
78
0.706908
bayesmix-dev
786b95d59c70f2d995fff2e905ad4c2c662d2b64
2,998
cpp
C++
Sources/Plugins/Image_DevIL/DevILImagePlugin.cpp
jdelezenne/Sonata
fb1b1b64a78874a0ab2809995be4b6f14f9e4d56
[ "MIT" ]
null
null
null
Sources/Plugins/Image_DevIL/DevILImagePlugin.cpp
jdelezenne/Sonata
fb1b1b64a78874a0ab2809995be4b6f14f9e4d56
[ "MIT" ]
null
null
null
Sources/Plugins/Image_DevIL/DevILImagePlugin.cpp
jdelezenne/Sonata
fb1b1b64a78874a0ab2809995be4b6f14f9e4d56
[ "MIT" ]
null
null
null
/*============================================================================= DevILImagePlugin.cpp Project: Sonata Engine Author: Julien Delezenne =============================================================================*/ #include "DevILImagePlugin.h" #include "DevILImageReader.h" #include "DevILImageWriter.h" #include <Core/Plugins/PluginManager.h> #include <Core/Plugins/ManagerPlugin.h> using namespace SonataEngine; namespace SE_DevIL { #ifdef SE_STATIC #define SE_EXPORT #else #define SE_EXPORT __declspec(dllexport) #endif PluginDescription g_PluginDescription[1]= { PluginDescription( SE_ID_DATAIMAGE_DEVIL, 0x01, "DevIL", "Julien Delezenne") }; class DevILImagePlugin : public ImageDataPlugin { public: DevILImagePlugin::DevILImagePlugin() : ImageDataPlugin() { } virtual DevILImagePlugin::~DevILImagePlugin() { } virtual PluginDescription* DevILImagePlugin::GetPluginDescription() const { return &g_PluginDescription[0]; } virtual void DevILImagePlugin::Load() { } virtual void DevILImagePlugin::Unload() { } virtual Array<String> DevILImagePlugin::GetExtensions() const { Array<String> extensions; extensions.Add("bmp"); extensions.Add("cut"); extensions.Add("dds"); extensions.Add("gif"); extensions.Add("ico"); extensions.Add("jpg"); extensions.Add("jpeg"); extensions.Add("lif"); extensions.Add("mng"); extensions.Add("pcx"); extensions.Add("pic"); extensions.Add("png"); extensions.Add("pnm"); extensions.Add("psd"); extensions.Add("psp"); extensions.Add("sgi"); extensions.Add("tga"); extensions.Add("tif"); extensions.Add("raw"); return extensions; } virtual bool DevILImagePlugin::CanRead() const { return true; } virtual bool DevILImagePlugin::CanWrite() const { return true; } virtual bool DevILImagePlugin::CanHandle(const Stream& stream) const { return true; } virtual ImageReader* DevILImagePlugin::CreateReader() { return new DevILImageReader(); } virtual ImageWriter* DevILImagePlugin::CreateWriter() { return new DevILImageWriter(); } virtual void DevILImagePlugin::DestroyReader(ImageReader* reader) { if (reader != NULL) { delete reader; } } virtual void DevILImagePlugin::DestroyWriter(ImageWriter* writer) { if (writer != NULL) { delete writer; } } }; #ifndef SE_STATIC extern "C" { #endif SE_EXPORT PluginDescription* GetPluginDescription(int index) { return &g_PluginDescription[index]; } SE_EXPORT Plugin* CreatePlugin(int index) { switch (index) { case 0: return new DevILImagePlugin(); } return NULL; } SE_EXPORT void DestroyPlugin(Plugin* plugin) { if (plugin != NULL) { delete plugin; } } #ifndef SE_STATIC } #endif #ifdef SE_STATIC PluginModule::PluginModule() { PluginSymbols symbols; symbols.GetPluginDescription = GetPluginDescription; symbols.CreatePlugin = CreatePlugin; symbols.DestroyPlugin = DestroyPlugin; PluginManager::Instance()->RegisterPluginLibrary(symbols); } #endif }
17.739645
79
0.688793
jdelezenne
786ece9c41a0add9481bf2399f1c2ae23209a055
1,289
hpp
C++
src/rynx/graphics/mesh/collection.hpp
Apodus/rynx
3e1babc2f2957702ba2b09d78be3a959f2f4ea18
[ "MIT" ]
11
2019-08-19T08:44:14.000Z
2020-09-22T20:04:46.000Z
src/rynx/graphics/mesh/collection.hpp
Apodus/rynx
3e1babc2f2957702ba2b09d78be3a959f2f4ea18
[ "MIT" ]
null
null
null
src/rynx/graphics/mesh/collection.hpp
Apodus/rynx
3e1babc2f2957702ba2b09d78be3a959f2f4ea18
[ "MIT" ]
null
null
null
#pragma once #include <rynx/graphics/mesh/id.hpp> #include <rynx/tech/unordered_map.hpp> #include <rynx/math/geometry/polygon.hpp> #include <memory> namespace rynx { namespace graphics { class mesh; class GPUTextures; struct mesh_entry { std::string name; rynx::graphics::mesh_id id; }; class mesh_collection { public: mesh_collection(std::shared_ptr<rynx::graphics::GPUTextures> gpuTextures); std::vector<mesh_entry> getListOfMeshes() const; mesh* get(mesh_id id); mesh_id findByName(std::string humanReadableName); mesh_id create_transient(std::unique_ptr<mesh> mesh); mesh_id create_transient(rynx::polygon shape); mesh_id create(std::unique_ptr<mesh> mesh); mesh_id create(rynx::polygon shape); mesh_id create(std::string human_readable_name, std::unique_ptr<mesh> mesh); mesh_id create(std::string human_readable_name, rynx::polygon shape); void erase(mesh_id id); void save_all_meshes_to_disk(std::string path); void save_mesh_to_disk(mesh_id, std::string path); void load_all_meshes_from_disk(std::string path); void clear(); private: mesh_id generate_mesh_id(); std::shared_ptr<rynx::graphics::GPUTextures> m_pGpuTextures; rynx::unordered_map<mesh_id, std::unique_ptr<mesh>> m_storage; }; } }
26.854167
79
0.737781
Apodus
78717488868197856f00716acf0d39ce09277e21
2,797
cpp
C++
src/marathon.cpp
dsparber/algolab
9781eb5c7444236f796f167f1f39fc9d913e5c53
[ "MIT" ]
13
2021-01-01T17:19:24.000Z
2022-02-09T12:27:57.000Z
src/marathon.cpp
dsparber/algolab
9781eb5c7444236f796f167f1f39fc9d913e5c53
[ "MIT" ]
null
null
null
src/marathon.cpp
dsparber/algolab
9781eb5c7444236f796f167f1f39fc9d913e5c53
[ "MIT" ]
1
2021-01-28T10:55:25.000Z
2021-01-28T10:55:25.000Z
#include <iostream> #include <vector> #include <queue> #include <limits> #include <cmath> #include <boost/graph/adjacency_list.hpp> #include <boost/graph/push_relabel_max_flow.hpp> #include <boost/graph/dijkstra_shortest_paths.hpp> typedef boost::adjacency_list_traits<boost::vecS, boost::vecS, boost::directedS> traits; typedef boost::adjacency_list<boost::vecS, boost::vecS, boost::directedS, boost::no_property, boost::property<boost::edge_capacity_t, long, boost::property<boost::edge_residual_capacity_t, long, boost::property<boost::edge_reverse_t, traits::edge_descriptor>>>> graph; typedef traits::vertex_descriptor vertex_desc; typedef traits::edge_descriptor edge_desc; typedef boost::adjacency_list<boost::vecS, boost::vecS, boost::undirectedS, boost::no_property, boost::property<boost::edge_weight_t, int> > weighted_graph; typedef boost::property_map<weighted_graph, boost::edge_weight_t>::type weight_map; // Custom edge adder class, highly recommended class edge_adder { graph &G; public: explicit edge_adder(graph &G) : G(G) {} void add_edge(int from, int to, long capacity) { auto c_map = boost::get(boost::edge_capacity, G); auto r_map = boost::get(boost::edge_reverse, G); const auto e = boost::add_edge(from, to, G).first; const auto rev_e = boost::add_edge(to, from, G).first; c_map[e] = capacity; c_map[rev_e] = 0; // reverse edge has no capacity! r_map[e] = rev_e; r_map[rev_e] = e; } }; using namespace std; struct edge { int u; int v; int length; int width; }; // Strategy: // - Find all edges that are part of some shortest path // - Run a max-flow algorithm on those edges void solve() { int n, m, s, f; cin >> n >> m >> s >> f; // Dijkstra Graph weighted_graph G(n); // Read neighbors vector<edge> edges; edges.reserve(m); int u, v, length, width; for (int i = 0; i < m; ++i) { cin >> u >> v >> width >> length; boost::add_edge(u, v, length, G); edges.push_back({u, v, length, width}); } // Run dijkstra std::vector<int> d(n); boost::dijkstra_shortest_paths(G, s, boost::distance_map(boost::make_iterator_property_map( d.begin(), boost::get(boost::vertex_index, G)))); // Flow graph graph gFlow(n); edge_adder adder(gFlow); // Find edges on a shortest path vector<edge> shortestPathEdges; for (auto e : edges) { int diff = d[e.v] - d[e.u]; if (e.length == diff) { adder.add_edge(e.u, e.v, e.width); } else if (e.length == -diff) { adder.add_edge(e.v, e.u, e.width); } } // Compute flow long flow = boost::push_relabel_max_flow(gFlow, s, f); cout << flow << endl; } int main() { ios_base::sync_with_stdio(false); int t; cin >> t; while (t--) { solve(); } return 0; }
26.638095
143
0.662853
dsparber
7871a98ae7712defd3df6155e7bcbc121b0c310c
8,495
cc
C++
code/render/physics/physx/physxcollider.cc
gscept/nebula-trifid
e7c0a0acb05eedad9ed37a72c1bdf2d658511b42
[ "BSD-2-Clause" ]
67
2015-03-30T19:56:16.000Z
2022-03-11T13:52:17.000Z
code/render/physics/physx/physxcollider.cc
gscept/nebula-trifid
e7c0a0acb05eedad9ed37a72c1bdf2d658511b42
[ "BSD-2-Clause" ]
5
2015-04-15T17:17:33.000Z
2016-02-11T00:40:17.000Z
code/render/physics/physx/physxcollider.cc
gscept/nebula-trifid
e7c0a0acb05eedad9ed37a72c1bdf2d658511b42
[ "BSD-2-Clause" ]
34
2015-03-30T15:08:00.000Z
2021-09-23T05:55:10.000Z
//------------------------------------------------------------------------------ // physxcollider.cc // (C) 2016 Individual contributors, see AUTHORS file //------------------------------------------------------------------------------ #include "stdneb.h" #include "physics/resource/managedphysicsmesh.h" #include "physics/physx/physxcollider.h" #include "resources/resourcemanager.h" #include "geometry/PxPlaneGeometry.h" #include "physxutils.h" #include "PxShape.h" #include "PxRigidActor.h" #include "geometry/PxBoxGeometry.h" #include "geometry/PxSphereGeometry.h" #include "geometry/PxCapsuleGeometry.h" #include "geometry/PxConvexMeshGeometry.h" #include "geometry/PxTriangleMeshGeometry.h" #include "../model/templates.h" #include "PxFiltering.h" #include "extensions/PxDefaultSimulationFilterShader.h" using namespace physx; using namespace Math; using namespace Physics; namespace PhysX { __ImplementClass(PhysX::PhysXCollider, 'PXCO', Physics::BaseCollider); //------------------------------------------------------------------------------ /** */ PhysXCollider::PhysXCollider() { /// empty } //------------------------------------------------------------------------------ /** */ PhysXCollider::~PhysXCollider() { ///empty } //------------------------------------------------------------------------------ /** */ void PhysXCollider::RenderDebug(const Math::matrix44& t) { } //------------------------------------------------------------------------------ /** */ void PhysXCollider::CreatePlane(PxRigidActor * target, const ColliderDescription & desc, const Math::float4 &scale, const Math::quaternion & quat, const Math::float4 &trans, const physx::PxMaterial& material) { PxPlaneGeometry * geom = n_new(PxPlaneGeometry); Math::float4 point = desc.plane.plane.get_point(); point *= scale; PxPlane pxplane(Neb2PxVec(point), Neb2PxVec(desc.plane.plane.get_normal())); PxTransform ptrans = PxTransformFromPlaneEquation(pxplane); if (!quat.isidentity()) { n_warning("ignoring local rotation with plane %s", desc.name.AsCharPtr()); } target->createShape(*geom, material, ptrans); } //------------------------------------------------------------------------------ /** */ void PhysXCollider::CreateBox(PxRigidActor * target, const ColliderDescription & desc, const Math::float4 &scale, const Math::quaternion & quat, const Math::float4 &trans, const physx::PxMaterial& material) { Math::float4 half = desc.box.halfWidth; half = Math::float4::maximize(half, Math::float4(0.01f, 0.01f, 0.01f, 1.0f)); half *= scale; PxBoxGeometry * geom = n_new(PxBoxGeometry(Neb2PxVec(half))); PxTransform ptrans(Neb2PxVec(trans), Neb2PxQuat(quat)); target->createShape(*geom, material, ptrans); } //------------------------------------------------------------------------------ /** */ void PhysXCollider::CreateSphere(PxRigidActor * target, const ColliderDescription & desc, const Math::float4 &scale, const Math::float4 &trans, const physx::PxMaterial& material) { float rscale = n_max(n_max(scale.x(), scale.y()), scale.z()); PxSphereGeometry * geom = n_new(PxSphereGeometry(desc.sphere.radius *rscale)); PxTransform ptrans(Neb2PxVec(trans)); target->createShape(*geom, material, ptrans); } //------------------------------------------------------------------------------ /** */ void PhysXCollider::CreateCapsule(PxRigidActor * target, const ColliderDescription & desc, const Math::float4 &scale, const Math::quaternion & quat, const Math::float4 &trans, const physx::PxMaterial& material) { PxCapsuleGeometry * geom = n_new(PxCapsuleGeometry(desc.capsule.radius * n_max(scale.x(),scale.z()), 0.5f * desc.capsule.height * scale.y())); PxTransform ptrans(Neb2PxVec(trans), Neb2PxQuat(quat)); target->createShape(*geom, material, ptrans); } //------------------------------------------------------------------------------ /** */ void PhysXCollider::CreatePhysicsMesh(PxRigidActor * target, const ColliderDescription & desc, const Math::float4 &scale, const Math::quaternion & quat, const Math::float4 &trans, const physx::PxMaterial& material) { Ptr<ManagedPhysicsMesh> colliderMesh = Resources::ResourceManager::Instance()->CreateManagedResource(PhysicsMesh::RTTI, desc.mesh.meshResource,0,true).cast<ManagedPhysicsMesh>(); Ptr<PhysXPhysicsMesh> mesh = colliderMesh->GetMesh().cast<PhysXPhysicsMesh>(); switch (desc.mesh.meshType) { case MeshConvex: { n_warning("using convex mesh as concave"); PxConvexMesh * cmesh = mesh->GetConvexHullMesh(desc.mesh.primGroup); PxConvexMeshGeometry* geom; if (!float4::nearequal3(scale, float4(1.0f, 1.0f, 1.0f, 1.0f), float4(0.01f, 0.01f, 0.01f, 0.01f))) { PxMeshScale pscale(Neb2PxVec(scale), PxQuat(PxIdentity)); geom = n_new(PxConvexMeshGeometry(cmesh, pscale)); } else { geom = n_new(PxConvexMeshGeometry(cmesh)); } PxTransform ptrans(Neb2PxVec(trans), Neb2PxQuat(quat)); target->createShape(*geom, material, ptrans); } break; case MeshConcave: case MeshStatic: { PxTriangleMesh * tmesh = mesh->GetMesh(desc.mesh.primGroup); PxTriangleMeshGeometry * geom; if (!float4::nearequal3(scale, float4(1.0f, 1.0f, 1.0f, 1.0f), float4(0.01f, 0.01f, 0.01f, 0.01f))) { PxMeshScale pscale(Neb2PxVec(scale), PxQuat(PxIdentity)); geom = n_new(PxTriangleMeshGeometry(tmesh, pscale)); } else { geom = n_new(PxTriangleMeshGeometry(tmesh)); } PxTransform ptrans(Neb2PxVec(trans), Neb2PxQuat(quat)); target->createShape(*geom, material, ptrans); } break; case MeshConvexHull: { PxConvexMesh * cmesh = mesh->GetConvexHullMesh(desc.mesh.primGroup); PxConvexMeshGeometry* geom; if (!float4::nearequal3(scale, float4(1.0f, 1.0f, 1.0f, 1.0f), float4(0.01f, 0.01f, 0.01f, 0.01f))) { PxMeshScale pscale(Neb2PxVec(scale), PxQuat(PxIdentity)); geom = n_new(PxConvexMeshGeometry(cmesh, pscale)); } else { geom = n_new(PxConvexMeshGeometry(cmesh)); } PxTransform ptrans(Neb2PxVec(trans), Neb2PxQuat(quat)); target->createShape(*geom, material, ptrans); } break; } } //------------------------------------------------------------------------------ /** */ void PhysXCollider::CreateInstance(PxRigidActor * target, Math::vector & xscale, const physx::PxMaterial& material) { for (int i = 0; i < this->descriptions.Size(); i++) { const ColliderDescription & desc = this->descriptions[i]; switch (desc.type) { default: break; case ColliderSphere: { Math::float4 scale; Math::quaternion quat; Math::float4 trans; desc.transform.decompose(scale, quat, trans); scale *= xscale; trans *= xscale; this->CreateSphere(target, desc, scale, trans, material); } break; case ColliderCube: { Math::float4 scale; Math::quaternion quat; Math::float4 trans; desc.transform.decompose(scale, quat, trans); scale *= xscale; trans *= xscale; this->CreateBox(target, desc, scale, quat, trans, material); } break; case ColliderCylinder: { Math::float4 scale; Math::quaternion quat; Math::float4 trans; Math::matrix44 rot = Math::matrix44::rotationz(1.57079632679489661923f); rot = Math::matrix44::multiply(rot, desc.transform); rot.decompose(scale, quat, trans); scale *= xscale; trans *= xscale; this->CreateCapsule(target, desc, scale, quat, trans, material); } break; case ColliderCapsule: { Math::float4 scale; Math::quaternion quat; Math::float4 trans; // physx has its capsule sitting on the side Math::matrix44 rot = Math::matrix44::rotationz(1.57079632679489661923f); rot = Math::matrix44::multiply(rot, desc.transform); rot.decompose(scale, quat, trans); scale *= xscale; trans *= xscale; this->CreateCapsule(target, desc, scale, quat, trans, material); } break; case ColliderPlane: { Math::float4 scale; Math::quaternion quat; Math::float4 trans; desc.transform.decompose(scale, quat, trans); scale *= xscale; trans *= xscale; this->CreatePlane(target, desc, scale, quat, trans, material); } break; case ColliderMesh: { Math::float4 scale; Math::quaternion quat; Math::float4 trans; desc.transform.decompose(scale, quat, trans); scale *= xscale; trans *= xscale; this->CreatePhysicsMesh(target, desc, scale, quat, trans, material); } break; } } } } // namespace PhysX
31.231618
209
0.623426
gscept
7874f3f8cc15c28f691459cc58dbdadc1cc29603
1,143
cpp
C++
util/MexWrapper.cpp
jacob-izr/drake
d8f0f1f231ecba83ed53b1a1c2f9f43da50396b9
[ "BSD-3-Clause" ]
4
2018-04-16T09:54:52.000Z
2021-03-29T21:59:27.000Z
util/MexWrapper.cpp
jacob-izr/drake
d8f0f1f231ecba83ed53b1a1c2f9f43da50396b9
[ "BSD-3-Clause" ]
null
null
null
util/MexWrapper.cpp
jacob-izr/drake
d8f0f1f231ecba83ed53b1a1c2f9f43da50396b9
[ "BSD-3-Clause" ]
1
2017-08-24T20:32:03.000Z
2017-08-24T20:32:03.000Z
#include "MexWrapper.h" #if defined(WIN32) || defined(WIN64) #else #include <dlfcn.h> #endif MexWrapper::MexWrapper(std::string const & filename) : m_mex_file(filename) { m_good = false; #if defined(WIN32) || defined(WIN64) #else //load the mexfile m_handle = dlopen(m_mex_file.c_str(), RTLD_NOW); if (!m_handle) { fprintf(stderr,"%s\n",dlerror()); return; } //locate and store the entry point in a function pointer char* error; *(void**) &(m_mexFunc) = dlsym(m_handle, "mexFunction"); if ((error = dlerror()) != NULL) { fprintf(stderr,"%s\n", error); dlclose(m_handle); return; } m_good = true; #endif } MexWrapper::~MexWrapper() { #if defined(WIN32) || defined(WIN64) #else if (m_good) { dlclose(m_handle); } #endif } //the caller is responsible for allocating all of the mxArray* memory and freeing it when // void MexWrapper::mexFunction(int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[]) const { if (m_good) { m_mexFunc(nlhs, plhs, nrhs, const_cast<const mxArray**>(prhs)); } } std::string MexWrapper::getMexFile() const { return m_mex_file; }
20.410714
94
0.653543
jacob-izr
787b49c0e7c6ae15fcc42bea673de136597a5e9b
41,784
cpp
C++
source/ics/photoevaporating_multiclumps.cpp
jfbucas/PION
e0a66aa301e4d94d581ba4df078f1a3b82faab99
[ "BSD-3-Clause" ]
4
2020-08-20T11:31:22.000Z
2020-12-05T13:30:03.000Z
source/ics/photoevaporating_multiclumps.cpp
Mapoet/PION
51559b18f700c372974ac8658a266b6a647ec764
[ "BSD-3-Clause" ]
null
null
null
source/ics/photoevaporating_multiclumps.cpp
Mapoet/PION
51559b18f700c372974ac8658a266b6a647ec764
[ "BSD-3-Clause" ]
4
2020-08-20T14:33:19.000Z
2022-03-07T10:29:34.000Z
/// \file photoevaporating_multiclumps.cc /// \author Jonathan Mackey /// /// File for setting up photo-evaporation of many random clumps and some /// strategically positioned clumps. /// /// Modifications:\n /// - 2010-01-20 JM: line 714, corrected mass to be rho*(1+delta) [from rho*delta] /// - 2010-01-27 JM: comments /// - 2010-02-08 JM: Changed tracer calculation in clumps_set_dens() so that /// it gives the right answer (if all clumps have the same tracer value). /// - 2010-02-10 JM: Added isothermal euler equations. /// - 2010.12.15 JM: Added get_alternate_ambient_params(rp, &amb_data) and /// add_alternate_ambient_data_to_grid(ggg, &amb_data) to allow for the /// nearest 10th of the grid to the negative x-boundary to have a /// different ambient medium property. Note this only works well if all /// clumps are well away from this region (otherwise the tracer values /// get overwritten with the other ambient medium values which can have /// unintended consequences!) /// - 2011.01.06 JM: fixed memory leak. /// - 2012.02.25 JM: Added optional velocity vector for clump. /// - 2012.04.23 JM: Added optional density gradient in ambient medium. /// - 2015.01.15 JM: Added new include statements for new PION version. #include "defines/functionality_flags.h" #include "defines/testing_flags.h" #include "tools/reporting.h" #include "tools/mem_manage.h" #include "constants.h" #ifdef TESTING #include "tools/command_line_interface.h" #endif // TESTING #include "ics/icgen_base.h" #include "ics/icgen.h" #include <sstream> #include <algorithm> // ################################################################## // ################################################################## IC_photevap_multi_clumps::IC_photevap_multi_clumps() { ndim = coords = eqns = -1; ambdens = gamma = ambdivider = -1.0e99; rc_data.used = false; sc_data.used = false; amb_data.used = false; } // ################################################################## // ################################################################## IC_photevap_multi_clumps::~IC_photevap_multi_clumps() { if (rc_data.used) { rc_data.border = mem.myfree(rc_data.border); rc_data.cl = mem.myfree(rc_data.cl); } if (sc_data.used) { sc_data.cl = mem.myfree(sc_data.cl); } if (amb_data.used) { amb_data.ambient = mem.myfree(amb_data.ambient); } } // ################################################################## // ################################################################## int IC_photevap_multi_clumps::setup_data( class ReadParams *rrp, ///< pointer to parameter list. class GridBaseClass *ggg ///< pointer to grid ) { int err=0; // // Set pointers to grid and read-params classes. // ICsetup_base::gg = ggg; if (!gg) rep.error("null pointer to grid!",ggg); ICsetup_base::rp = rrp; if (!rp) rep.error("null pointer to ReadParams",rp); // // Get general sim parameters: // ndim = SimPM->ndim; if (ndim!=1 && ndim!=2 && ndim!=3) rep.error("Photoevaporation problem must be 1-3D",ndim); coords = SimPM->coord_sys; if (coords!=COORD_CRT) { cout <<"WARNING! using cylindrical coords, so MAKE SURE SOURCE AND ALL CLUMPS ARE ON-AXIS!!\n"; //rep.error("Bad coord sys",coords); } eqns = SimPM->eqntype; if (eqns==EQEUL || eqns==EQEUL_ISO) eqns=1; else if (eqns==EQMHD || eqns==EQGLM || eqns==EQFCD) eqns=2; else rep.error("Bad equations",eqns); // // Get ambient data from p-file, and write it to grid cells. // err += get_ambient_params(rp, &amb_data); err += add_ambient_data_to_grid(ggg, &amb_data); // // Get info for a portion of the domain which may have a different // ambient medium value (e.g. inflowing boundary from source). // Then reset the ambient data to the original value (in case it is // used later for anything). // err += get_alternate_ambient_params(rp, &amb_data); err += add_alternate_ambient_data_to_grid(ggg, &amb_data); err += get_ambient_params(rp, &amb_data); // // Get Random data from p-file, and add random clumps to grid. // err += get_random_clump_params(rp, &rc_data); err += add_random_clumps_to_grid(ggg, &rc_data); // // Get Strategic clumps from p-file, and add them to the grid. // err += get_strategic_clump_params(rp, &sc_data); err += add_strategic_clumps_to_grid(ggg, &sc_data); return err; } // ################################################################## // ################################################################## int IC_photevap_multi_clumps::get_ambient_params( class ReadParams *rparams, struct ambient_data *amb ) { int err=0; if (!amb || !rparams) rep.error("Null pointer passed to get_ambient_params!",amb); cout <<"\t**** Getting Ambient Params..."; if (!amb->used) { amb->used = true; amb->ambient = mem.myalloc(amb->ambient, SimPM->nvar); for (int v=0;v<SimPM->nvar;v++) amb->ambient[v] = 0.0; } string seek, str; ostringstream temp; string v; v="RO"; temp.str(""); temp << "PERC_amb" << v; seek = temp.str(); str = rparams->find_parameter(seek); if (str!="") amb->ambient[RO] = atof(str.c_str()); else amb->ambient[RO] = -1.0e99; ambdens = amb->ambient[RO]; v="PG"; temp.str(""); temp << "PERC_amb" << v; seek = temp.str(); str = rparams->find_parameter(seek); if (str!="") amb->ambient[PG] = atof(str.c_str()); else amb->ambient[PG] = -1.0e99; v="VX"; temp.str(""); temp << "PERC_amb" << v; seek = temp.str(); str = rparams->find_parameter(seek); if (str!="") amb->ambient[VX] = atof(str.c_str()); else amb->ambient[VX] = -1.0e99; v="VY"; temp.str(""); temp << "PERC_amb" << v; seek = temp.str(); str = rparams->find_parameter(seek); if (str!="") amb->ambient[VY] = atof(str.c_str()); else amb->ambient[VY] = -1.0e99; v="VZ"; temp.str(""); temp << "PERC_amb" << v; seek = temp.str(); str = rparams->find_parameter(seek); if (str!="") amb->ambient[VZ] = atof(str.c_str()); else amb->ambient[VZ] = -1.0e99; if (eqns ==2) { // mhd sim v="BX"; temp.str(""); temp << "PERC_amb" << v; seek = temp.str(); str = rparams->find_parameter(seek); if (str!="") amb->ambient[BX] = atof(str.c_str()); else amb->ambient[BX] = -1.0e99; v="BY"; temp.str(""); temp << "PERC_amb" << v; seek = temp.str(); str = rparams->find_parameter(seek); if (str!="") amb->ambient[BY] = atof(str.c_str()); else amb->ambient[BY] = -1.0e99; v="BZ"; temp.str(""); temp << "PERC_amb" << v; seek = temp.str(); str = rparams->find_parameter(seek); if (str!="") amb->ambient[BZ] = atof(str.c_str()); else amb->ambient[BZ] = -1.0e99; #ifdef NEW_B_NORM // convert from CGS to internal units (no factors of 4pi) amb->ambient[BX] /= sqrt(4.0*M_PI); amb->ambient[BY] /= sqrt(4.0*M_PI); amb->ambient[BZ] /= sqrt(4.0*M_PI); #endif if (SimPM->eqntype==EQGLM) amb->ambient[SI] = 0.; } // if mhd vars // tracer variables for (int t=0; t<SimPM->ntracer; t++) { temp.str(""); temp << "PERC_ambTR" << t; seek = temp.str(); str = rparams->find_parameter(seek); if (str!="") amb->ambient[t+SimPM->ftr] = atof(str.c_str()); else amb->ambient[t+SimPM->ftr] = -1.0e99; } // // Radial slope is outwards from the origin, with a core radius of // "cloudradius" where density is contant, and a power-law slope // of "radialslope" beyond this distance. // temp.str(""); temp << "PERCradialslope"; seek = temp.str(); str = rparams->find_parameter(seek); if (str!="") amb->radial_profile = atoi(str.c_str()); else amb->radial_profile = 0; cout <<"\t\tradial_profile="<<amb->radial_profile<<"\n"; temp.str(""); temp << "PERCcloudradius"; seek = temp.str(); str = rparams->find_parameter(seek); if (str!="") { amb->cloudradius = atof(str.c_str()); // radius is given in units of y-dir range. if (ndim>1) amb->cloudradius *= SimPM->Range[YY]; else amb->cloudradius *= SimPM->Range[XX]; cout <<"Cloud Radius in cm is "<<amb->cloudradius<<endl; } else amb->cloudradius = 0.0; cout <<"\t\tcloudradius="<<amb->cloudradius<<"\n"; // // power-law slope in x-direction: // rho(x) = rho_0 * [(x-x_0)/l_0)]^alpha // temp.str(""); temp << "PERC_amb_xscale"; seek = temp.str(); str = rparams->find_parameter(seek); if (str=="true") { amb->xscale=true; //cout <<"Getting X0, L0, A0 for x-scale: "; // get parameters rho_0, x_0, l_0, alpha (rho_0 = PERC_ambRO // all in cgs units. temp.str(""); temp << "PERC_xscale_x0"; seek = temp.str(); str = rparams->find_parameter(seek); if (str!="") amb->xscale_x0 = atof(str.c_str()); else amb->xscale_x0 = 1.0; temp.str(""); temp << "PERC_xscale_l0"; seek = temp.str(); str = rparams->find_parameter(seek); if (str!="") amb->xscale_l0 = atof(str.c_str()); else amb->xscale_l0 = 1.0; temp.str(""); temp << "PERC_xscale_alpha"; seek = temp.str(); str = rparams->find_parameter(seek); if (str!="") amb->xscale_alpha = atof(str.c_str()); else amb->xscale_alpha = 1.0; //cout <<amb->xscale_x0<<", "; //cout <<amb->xscale_l0<<", "; //cout <<amb->xscale_alpha<<"\n"; } else { amb->xscale = false; } cout <<"\tGot Ambient Params. ****\n"; return err; } // ################################################################## // ################################################################## int IC_photevap_multi_clumps::get_alternate_ambient_params( class ReadParams *rparams, struct ambient_data *amb ) { int err=0; if (!amb || !rparams) rep.error("Null pointer passed to get_ambient_params!",amb); string seek, str; ostringstream temp; string v; v="RO"; temp.str(""); temp << "PERC_ALTamb" << v; seek = temp.str(); str = rparams->find_parameter(seek); if (str=="") { cout <<"\t**** No Alternate Ambient Params...\n"; return 0; } cout <<"\t**** Getting Alternate Ambient Params..."; if (!amb->ambient) { amb->ambient = mem.myalloc(amb->ambient, SimPM->nvar); amb->used = true; for (int v=0;v<SimPM->nvar;v++) amb->ambient[v] = 0.0; } v="RO"; temp.str(""); temp << "PERC_ALTamb" << v; seek = temp.str(); str = rparams->find_parameter(seek); if (str!="") amb->ambient[RO] = atof(str.c_str()); else amb->ambient[RO] = -1.0e99; ambdens = amb->ambient[RO]; v="PG"; temp.str(""); temp << "PERC_ALTamb" << v; seek = temp.str(); str = rparams->find_parameter(seek); if (str!="") amb->ambient[PG] = atof(str.c_str()); else amb->ambient[PG] = -1.0e99; v="VX"; temp.str(""); temp << "PERC_ALTamb" << v; seek = temp.str(); str = rparams->find_parameter(seek); if (str!="") amb->ambient[VX] = atof(str.c_str()); else amb->ambient[VX] = -1.0e99; v="VY"; temp.str(""); temp << "PERC_ALTamb" << v; seek = temp.str(); str = rparams->find_parameter(seek); if (str!="") amb->ambient[VY] = atof(str.c_str()); else amb->ambient[VY] = -1.0e99; v="VZ"; temp.str(""); temp << "PERC_ALTamb" << v; seek = temp.str(); str = rparams->find_parameter(seek); if (str!="") amb->ambient[VZ] = atof(str.c_str()); else amb->ambient[VZ] = -1.0e99; if (eqns ==2) { // mhd sim v="BX"; temp.str(""); temp << "PERC_ALTamb" << v; seek = temp.str(); str = rparams->find_parameter(seek); if (str!="") amb->ambient[BX] = atof(str.c_str()); else amb->ambient[BX] = -1.0e99; v="BY"; temp.str(""); temp << "PERC_ALTamb" << v; seek = temp.str(); str = rparams->find_parameter(seek); if (str!="") amb->ambient[BY] = atof(str.c_str()); else amb->ambient[BY] = -1.0e99; v="BZ"; temp.str(""); temp << "PERC_ALTamb" << v; seek = temp.str(); str = rparams->find_parameter(seek); if (str!="") amb->ambient[BZ] = atof(str.c_str()); else amb->ambient[BZ] = -1.0e99; #ifdef NEW_B_NORM // convert from CGS to internal units (no factors of 4pi) amb->ambient[BX] /= sqrt(4.0*M_PI); amb->ambient[BY] /= sqrt(4.0*M_PI); amb->ambient[BZ] /= sqrt(4.0*M_PI); #endif if (SimPM->eqntype==EQGLM) amb->ambient[SI] = 0.; } // if mhd vars // tracer variables for (int t=0; t<SimPM->ntracer; t++) { temp.str(""); temp << "PERC_ALTambTR" << t; seek = temp.str(); str = rparams->find_parameter(seek); if (str!="") amb->ambient[t+SimPM->ftr] = atof(str.c_str()); else amb->ambient[t+SimPM->ftr] = -1.0e99; } // // Divider between the first and (optional) second ambient medium. // temp.str(""); temp << "PERC_ALTdivider"; seek = temp.str(); str = rparams->find_parameter(seek); if (str!="") ambdivider = atof(str.c_str()); else ambdivider = SimPM->Xmin[XX]+0.1*SimPM->Range[XX]; cout <<"\t\tdivision between two media at "<<ambdivider<<"\n"; cout <<"\tGot Alternate Ambient Params. ****\n"; rep.printVec("\tAlt.Amb.",amb->ambient,SimPM->nvar); return err; } // ################################################################## // ################################################################## int IC_photevap_multi_clumps::add_ambient_data_to_grid( class GridBaseClass *ggg, struct ambient_data *amb ) { int err=0; if (!ggg || !amb) rep.error("Null pointer passed to add_ambient_data_to_grid()",ggg); class cell *c = ggg->FirstPt(); double cloudcentre[MAX_DIM]; for (int v=0;v<MAX_DIM;v++) cloudcentre[v]=0.0; double dist=0.0; double dpos[ggg->Ndim()]; do { // Set values of primitive variables. for (int v=0;v<SimPM->nvar;v++) c->P[v] = amb->ambient[v]; // // Now if we have a radial profile in the slope, we need to adjust rho // Note the radial profile is measured from cloudcentre, not neccessarily // centred on the source (srcpos). cloudcentre is set by (PEC_xpos,PEC_ypos,PEC_zpos). // if (amb->radial_profile!=0) { dist = gg->distance_vertex2cell(cloudcentre,c); //cout <<"dist="<<dist<<", rad="<<amb->cloudradius<<", rho="<<c->P[RO]; //cout <<", multiplier="<<exp(amb->radial_profile*log(amb->cloudradius/dist))<<"\n"; // // Following the Iliev et al 2009 test 6, we use rho=rho0(r0/r)^n if r>r0 // We also change the pressure so there is a constant temperature state. // if (dist>amb->cloudradius) { c->P[RO] *= exp(amb->radial_profile*log(amb->cloudradius/dist)); c->P[PG] *= exp(amb->radial_profile*log(amb->cloudradius/dist)); } } if (amb->xscale==true) { //cout <<"*#*#*#*#*#*# adding scaled X-data: "; //cout <<amb->xscale_x0<<", "<<amb->xscale_l0<<", "<<amb->xscale_alpha<<": "; CI.get_dpos(c,dpos); // scale factor: dist = exp(-pow(fabs(dpos[XX]-amb->xscale_x0)/amb->xscale_l0, amb->xscale_alpha)); //cout <<" x="<<dpos[XX]<<", and scale factor="<<dist<<"\n"; c->P[RO] = amb->ambient[RO] * dist; c->P[PG] = amb->ambient[PG] * dist; } } while ( (c=ggg->NextPt(c))!=0); return err; } // ################################################################## // ################################################################## int IC_photevap_multi_clumps::add_alternate_ambient_data_to_grid( class GridBaseClass *ggg, struct ambient_data *amb ) { int err=0; if (!ggg || !amb) rep.error("Null pointer passed to add_ambient_data_to_grid()",ggg); // // The default is to set only the most negative tenth of the // x-domain to the alternate ambient values, but it can be set by the // parameter PERC_ALTdivider // double cutoff = ambdivider; class cell *c = ggg->FirstPt(); // int xmin=; do { // Set values of primitive variables. if (CI.get_dpos(c,XX)<cutoff) { //cout <<"cutoff="<<cutoff<<"\tix="<<c->pos[XX]<<"\n"; //rep.printVec("P old",c->P,SimPM->nvar); for (int v=0;v<SimPM->nvar;v++) c->P[v] = amb->ambient[v]; //rep.printVec("P new",c->P,SimPM->nvar); //if (amb->radial_profile!=0) c->P[RO] *= exp(amb->radial_profile*log((c->pos[XX]-xmin) } } while ( (c=ggg->NextPt(c))!=0); return err; } // ################################################################## // ################################################################## int IC_photevap_multi_clumps::get_random_clump_params( class ReadParams *rparams, struct random_clump_data *rcd ) { int err=0; string seek, str; ostringstream temp; // // First see if we are doing random clumps: // seek = "PERC_addrandomclumps"; str = rparams->find_parameter(seek); if (str=="" || str=="NO" || str=="no" || str=="No") { cout <<seek<<"="<<str<<", so not doing random clumps...\n"; return 0; } else cout <<seek<<"="<<str<<", so continuing to add random clumps.\n"; rcd->used = true; // // Initialise border pointer, and get values for the non-clump regions. // Border values are as a fraction of the total domain in that dimension. // rcd->border = mem.myalloc(rcd->border, 2*MAX_DIM); double default_empty=0.05; seek = "PERCempty_xn"; str = rparams->find_parameter(seek); if (str=="") rcd->border[XN] = default_empty; else rcd->border[XN] = atof(str.c_str())*SimPM->Range[XX]; seek = "PERCempty_xp"; str = rparams->find_parameter(seek); if (str=="") rcd->border[XP] = default_empty; else rcd->border[XP] = atof(str.c_str())*SimPM->Range[XX]; if (ndim>1) { seek = "PERCempty_yn"; str = rparams->find_parameter(seek); if (str=="") rcd->border[YN] = default_empty; else rcd->border[YN] = atof(str.c_str())*SimPM->Range[YY]; seek = "PERCempty_yp"; str = rparams->find_parameter(seek); if (str=="") rcd->border[YP] = default_empty; else rcd->border[YP] = atof(str.c_str())*SimPM->Range[YY]; } if (ndim>2) { seek = "PERCempty_zn"; str = rparams->find_parameter(seek); if (str=="") rcd->border[ZN] = default_empty; else rcd->border[ZN] = atof(str.c_str())*SimPM->Range[ZZ]; seek = "PERCempty_zp"; str = rparams->find_parameter(seek); if (str=="") rcd->border[ZP] = default_empty; else rcd->border[ZP] = atof(str.c_str())*SimPM->Range[ZZ]; } // // Get mean density of matter to go into clumps, and convert this // to a total mass with the box volume. // seek = "PERC_mean_clump_density"; str = rparams->find_parameter(seek); if (str=="") rep.error("Failed to get mass to put into clumps", seek); else rcd->density = atof(str.c_str()); // // Can set the volume to be the total sim.volume, or just the fraction // of it we are putting clumps into. I think the 'R.C. mean density' // means more if it is the total volume. // double volume=1.0; volume *= SimPM->Range[XX]; //-rcd->border[XN]-rcd->border[XP]; //cout <<"\tvolume="<<volume; if (ndim>1) volume *= SimPM->Range[YY]; //-rcd->border[YN]-rcd->border[YP]; //cout <<"\tvolume="<<volume; if (ndim>2) volume *= SimPM->Range[ZZ]; //-rcd->border[ZN]-rcd->border[ZP]; //cout <<"\tvolume="<<volume; rcd->total_mass = rcd->density*volume*pconst.m_p(); cout <<"Mean number density for Random Clumps:"<<rcd->density<<", giving total mass="<<rcd->total_mass<<" grams.\n"; // // Get Random Seed from File // seek = "PERCrandomseed"; str = rparams->find_parameter(seek); if (str=="") rep.error("didn't find parameter",seek); else rcd->random_seed = atoi(str.c_str()); srand(rcd->random_seed); // // profile of clumps, and min/max size // seek = "PERCclump_profile"; str = rparams->find_parameter(seek); if (str=="") rep.error("didn't find parameter",seek); else rcd->profile = atoi(str.c_str()); seek = "PERCmin_size"; str = rparams->find_parameter(seek); if (str=="") rep.error("didn't find parameter",seek); rcd->min_size = atof(str.c_str()); seek = "PERCmax_size"; str = rparams->find_parameter(seek); if (str=="") rep.error("didn't find parameter",seek); rcd->max_size = atof(str.c_str()); // // Find out if "Fixed Mass Range Clumps" or "Fixed Number of Clumps". // Get Nclumps, and clump parameters, based on different criteria, so call // different functions. // // N.B. These functions will bug out if less than one random clump is generated, // so safe for following code to assume at least one random clump exists. // seek = "PERC_selection_criterion"; str = rparams->find_parameter(seek); if (str=="") { cout <<"WARNING! Parameter PERC_selection_criterion not found, assuming fixed mass range clumps.\n"; err += rc_fixed_mass_range_params(rparams, rcd); } else if (str=="Fixed_Mass_Range") { err += rc_fixed_mass_range_params(rparams, rcd); } else if (str=="Fixed_Number") { err += rc_fixed_number_params(rparams, rcd); } else rep.error("Bad parameter for PERC_selection_criterion", str); // // Tracer Values for Random Clumps: // for (int v=0;v<SimPM->ntracer;v++) { temp.str(""); temp<<"PERCcloudTR"<<v; seek = temp.str(); str = rparams->find_parameter(seek); for (int c=0; c<rcd->Nclumps; c++) { if (str=="") rcd->cl[c].tracer_vals[v] = 0.0; else rcd->cl[c].tracer_vals[v] = atof(str.c_str()); } cout <<"***********tracer["<<v<<"] = "<<rcd->cl[0].tracer_vals[v]<<endl; } // // Now we have Nclumps, and the clump properties, so select their properties: // err += rc_set_clump_properties(rcd); return err; } // ################################################################## // ################################################################## int IC_photevap_multi_clumps::rc_fixed_number_params( class ReadParams *rparams, struct random_clump_data *rcd ) { int err=0; string seek, str; ostringstream temp; // // Get Number of clumps, and initialise *cl with that number. // seek = "PERCnumclumps"; str = rparams->find_parameter(seek); if (str=="") rep.error("didn't find parameter",seek); rcd->Nclumps = atoi(str.c_str()); if (rcd->Nclumps<1) { cout <<"\tFound "<<rcd->Nclumps<<" Random Clumps, so not adding any clumps.\n"; rep.error("Need at least one clump for Fixed number of clumps.",rcd->Nclumps); } else { rcd->cl = mem.myalloc(rcd->cl, rcd->Nclumps); } // // choose N+1 random values on the interval [0,M_cl], and use them to get clump masses. // Note for large N this will give roughly equal mass clumps because random values have // uniform probability (this is why I moved away from this method...). // std::vector<double> masses; masses.push_back(0.0); for (int j=1;j<rcd->Nclumps;j++) { masses.push_back(random_frac()*rcd->total_mass); } masses.push_back(rcd->total_mass); std::sort( masses.begin(), masses.end() ); for (int j=0;j<rcd->Nclumps+1;j++) cout <<"masses: "<<masses[j]<<endl; for (int j=0;j<rcd->Nclumps;j++) { rcd->cl[j].mass = masses[j+1]-masses[j]; } return err; } // ################################################################## // ################################################################## int IC_photevap_multi_clumps::rc_fixed_mass_range_params( class ReadParams *rparams, struct random_clump_data *rcd ) { int err=0; // // Get min and max clump masses, as fraction of total mass. // string seek, str; seek = "PERCmin_mass"; str = rparams->find_parameter(seek); if (str=="") rep.error("Failed to get param",seek); else rcd->min_mass = atof(str.c_str())*rcd->total_mass; seek = "PERCmax_mass"; str = rparams->find_parameter(seek); if (str=="") rep.error("Failed to get param",seek); else rcd->max_mass = atof(str.c_str())*rcd->total_mass; cout <<"min/max masses: "<<rcd->min_mass<<", "<<rcd->max_mass<<", and total mass: "<<rcd->total_mass<<endl; // // Take a random chunk (between min and max) out of total mass, as store as a clump mass // std::vector<double> masses; double mass_remaining = rcd->total_mass, this_mass=0.0; int nnn=0; do { this_mass = rcd->min_mass +random_frac()*(rcd->max_mass-rcd->min_mass); this_mass = std::min(this_mass, mass_remaining); masses.push_back(this_mass); mass_remaining -= this_mass; nnn++; } while (mass_remaining > (rcd->total_mass*SMALLVALUE)); cout <<"Used up all the mass in "<<nnn<<" clumps (Nclumps was "<<rcd->Nclumps<<") Mass left over="<<mass_remaining<<"\n"; rcd->Nclumps = nnn; if (rcd->Nclumps<1) rep.error("Got less than one clump in fixed total mass routine!",rcd->Nclumps); // // set up clumps struct and add masses for each clump. // rcd->cl = mem.myalloc(rcd->cl, rcd->Nclumps); for (int j=0;j<rcd->Nclumps;j++) { rcd->cl[j].mass = masses[j]; } return err; } // ################################################################## // ################################################################## int IC_photevap_multi_clumps::rc_set_clump_properties( struct random_clump_data *rcd ) { int err=0; double xmax = SimPM->Range[XX], ymax = SimPM->Range[YY], zmax = SimPM->Range[ZZ]; for (int j=0;j<rcd->Nclumps;j++) { // // Set clump centres, allowing for empty regions. // If periodic BCs, we only have empty regions in the X-dir, since Y,Z are periodic // if (SimPM->BC_YN == "periodic") { //cout <<"find = "<<SimPM->typeofbc.find("YNper")<<endl; rcd->cl[j].centre[XX] = SimPM->Xmin[XX]+ rcd->border[XN] +(xmax-rcd->border[XP]-rcd->border[XN])*random_frac(); rcd->cl[j].centre[YY] = SimPM->Xmin[YY]+ ymax*random_frac(); rcd->cl[j].centre[ZZ] = SimPM->Xmin[ZZ]+ zmax*random_frac(); } else { //cout <<"not periodic bcs!\n"; rcd->cl[j].centre[XX] = SimPM->Xmin[XX]+ rcd->border[XN] +(xmax-rcd->border[XP]-rcd->border[XN])*random_frac(); rcd->cl[j].centre[YY] = SimPM->Xmin[YY]+ rcd->border[YN] +(ymax-rcd->border[YP]-rcd->border[YN])*random_frac(); rcd->cl[j].centre[ZZ] = SimPM->Xmin[ZZ]+ rcd->border[ZN] +(zmax-rcd->border[ZP]-rcd->border[ZN])*random_frac(); } // // radius of clumps // rcd->cl[j].size[XX] = rcd->min_size*ymax +(rcd->max_size-rcd->min_size)*ymax*random_frac(); rcd->cl[j].size[YY] = rcd->min_size*ymax +(rcd->max_size-rcd->min_size)*ymax*random_frac(); rcd->cl[j].size[ZZ] = rcd->min_size*ymax +(rcd->max_size-rcd->min_size)*ymax*random_frac(); // orientation from grid axes to principal axes. rcd->cl[j].ang[XX] = random_frac()*M_PI; rcd->cl[j].ang[YY] = random_frac()*M_PI; rcd->cl[j].ang[ZZ] = random_frac()*M_PI; // // zero the z-dir if 2d if (SimPM->ndim==2) { rcd->cl[j].ang[ZZ] = rcd->cl[j].ang[YY] = rcd->cl[j].size[ZZ] = rcd->cl[j].centre[ZZ] = 0.0; } // // set overdensity (FIX THIS SO THAT IT CAN DO OTHER THAN GAUSSIAN PROFILES!!!!) // rcd->cl[j].overdensity = rcd->cl[j].mass/ambdens; for (int v=0;v<SimPM->ndim;v++) rcd->cl[j].overdensity /= sqrt(2.0*M_PI)*rcd->cl[j].size[v]; // // print clump... print_clump(&rcd->cl[j]); // // now set up the rotation matrix. rcd->cl[j].rm[XX][XX] = cos(rcd->cl[j].ang[XX])*cos(rcd->cl[j].ang[YY])*cos(rcd->cl[j].ang[ZZ]) -sin(rcd->cl[j].ang[XX])*sin(rcd->cl[j].ang[ZZ]); rcd->cl[j].rm[XX][YY] = sin(rcd->cl[j].ang[XX])*cos(rcd->cl[j].ang[YY])*cos(rcd->cl[j].ang[ZZ]) +cos(rcd->cl[j].ang[XX])*sin(rcd->cl[j].ang[ZZ]); rcd->cl[j].rm[XX][ZZ] = -sin(rcd->cl[j].ang[YY])*cos(rcd->cl[j].ang[ZZ]); rcd->cl[j].rm[YY][XX] = -cos(rcd->cl[j].ang[XX])*cos(rcd->cl[j].ang[YY])*sin(rcd->cl[j].ang[ZZ]) -sin(rcd->cl[j].ang[XX])*cos(rcd->cl[j].ang[ZZ]); rcd->cl[j].rm[YY][YY] = -sin(rcd->cl[j].ang[XX])*cos(rcd->cl[j].ang[YY])*sin(rcd->cl[j].ang[ZZ]) +cos(rcd->cl[j].ang[XX])*cos(rcd->cl[j].ang[ZZ]); rcd->cl[j].rm[YY][ZZ] = sin(rcd->cl[j].ang[YY])*sin(rcd->cl[j].ang[ZZ]); rcd->cl[j].rm[ZZ][XX] = cos(rcd->cl[j].ang[XX])*sin(rcd->cl[j].ang[YY]); rcd->cl[j].rm[ZZ][YY] = sin(rcd->cl[j].ang[XX])*sin(rcd->cl[j].ang[YY]); rcd->cl[j].rm[ZZ][ZZ] = cos(rcd->cl[j].ang[YY]); // all done, move on to next clump. } return err; } // ################################################################## // ################################################################## int IC_photevap_multi_clumps::add_random_clumps_to_grid( class GridBaseClass *ggg, struct random_clump_data *rcd ) { int err=0; if (!rcd->used) { cout <<"\tnot using random clumps, so not adding any to grid.\n"; return 0; } cout <<"Adding random clumps to grid..."; cell *c = ggg->FirstPt(); do { err += clumps_set_dens(c, rcd->Nclumps, rcd->cl, rcd->profile); } while ( (c=ggg->NextPt(c))!=0); // // Set tracer values, assuming all random clumps have the same tracer value, and that it // is based on density compared to ambient density. Need to change it in future if I want // to change this. // //cout <<"ntracer = "<<SimPM->ntracer<<"\t amb[tr1]="<<ambient[SimPM->ftr+1]<<"\tcl[tr1]="<<cltr[1]; c=ggg->FirstPt(); cout <<"\tamb-density="<<ambdens<<" clump_mass="<<rcd->total_mass<<endl; do { for (int v=SimPM->ftr; v<SimPM->nvar;v++) { //cout <<"trval before="<<c->P[v]; c->P[v] = (ambdens/c->P[RO])*amb_data.ambient[v] +(1.0-ambdens/c->P[RO])*rcd->cl[0].tracer_vals[v-SimPM->ftr]; //cout <<"\tafter="<<c->P[v]<<endl; } } while ( (c=ggg->NextPt(c)) !=0); cout <<"\tFinished adding random clumps to grid.\n"; return err; } // ################################################################## // ################################################################## int IC_photevap_multi_clumps::get_strategic_clump_params( class ReadParams *rparams, struct strategic_clump_data *scd ) { int err=0; string seek, str; ostringstream temp; // // First see if we have strategic clumps to place: // seek = "PE_SC_addstrategicclumps"; str = rparams->find_parameter(seek); if (str=="" || str=="NO" || str=="no" || str=="No") { cout <<seek<<"="<<str<<", so not doing any strategic clumps...\n"; return 0; } else cout <<seek<<"="<<str<<", so continuing to add strategic clumps.\n"; scd->used = true; // // See how many clumps we need: // seek = "PE_SC_numclumps"; str = rparams->find_parameter(seek); if (str=="") rep.error("didn't find parameter",seek); scd->Nclumps = atoi(str.c_str()); if (scd->Nclumps<1) { cout <<"\tFound "<<scd->Nclumps<<" Strategic Clumps, so not adding any clumps.\n"; rep.error("Need at least one clump for strategic clumps.",scd->Nclumps); } else { scd->cl = mem.myalloc(scd->cl, scd->Nclumps); } // // profile of clumps, and min/max size // seek = "PE_SC_clump_profile"; str = rparams->find_parameter(seek); if (str=="") rep.error("didn't find parameter",seek); else scd->profile = atoi(str.c_str()); // // Now loop over all clumps, reading in data for each. // for (int c=0; c<scd->Nclumps; c++) { // // Clump Overdensity. // temp.str(""); temp<<"PE_SC"<<c<<"_overdensity"; seek = temp.str(); str = rp->find_parameter(seek); if (str=="") rep.error("no parameter found for clump",seek); else scd->cl[c].overdensity = atof(str.c_str()); // // Clump Position (read in as fraction of Y-Range). // temp.str(""); temp<<"PE_SC"<<c<<"_xpos"; seek=temp.str(); str = rp->find_parameter(seek); if (str=="") rep.error("didn't find parameter",seek); scd->cl[c].centre[XX] = SimPM->Xmin[XX] +atof(str.c_str())*SimPM->Range[YY]; if (ndim>1) { temp.str(""); temp<<"PE_SC"<<c<<"_ypos"; seek=temp.str(); str = rp->find_parameter(seek); if (str=="") rep.error("didn't find parameter",seek); scd->cl[c].centre[YY] = SimPM->Xmin[YY] +atof(str.c_str())*SimPM->Range[YY]; } if (ndim>2) { temp.str(""); temp<<"PE_SC"<<c<<"_zpos"; seek=temp.str(); str = rp->find_parameter(seek); if (str=="") rep.error("didn't find parameter",seek); scd->cl[c].centre[ZZ] = SimPM->Xmin[ZZ] +atof(str.c_str())*SimPM->Range[YY]; } // // Clump size: (note this is hard-coded to be circular, this param is as fraction // of the Y-Range). // temp.str(""); temp<<"PE_SC"<<c<<"_radius"; seek=temp.str(); str = rp->find_parameter(seek); if (str=="") rep.error("didn't find parameter",seek); for (int v=0;v<MAX_DIM;v++) scd->cl[c].size[v] = atof(str.c_str())*SimPM->Range[YY]; // // Clump Velocity (cm/s). // temp.str(""); temp<<"PE_SC"<<c<<"_vx"; seek=temp.str(); str = rp->find_parameter(seek); if (str=="") scd->cl[c].Vel[0] = 0.0; else {scd->cl[c].Vel[0] = atof(str.c_str()); cout <<"VX="<<scd->cl[c].Vel[0]<<"\n";} temp.str(""); temp<<"PE_SC"<<c<<"_vy"; seek=temp.str(); str = rp->find_parameter(seek); if (str=="") scd->cl[c].Vel[1] = 0.0; else scd->cl[c].Vel[1] = atof(str.c_str()); temp.str(""); temp<<"PE_SC"<<c<<"_vz"; seek=temp.str(); str = rp->find_parameter(seek); if (str=="") scd->cl[c].Vel[2] = 0.0; else scd->cl[c].Vel[2] = atof(str.c_str()); // // Tracer Values for each cloud (can be different for each!) // for (int v=0;v<SimPM->ntracer;v++) { temp.str(""); temp<<"PE_SC"<<c<<"_cloudTR"<<v; seek = temp.str(); str = rp->find_parameter(seek); if (str=="") scd->cl[c].tracer_vals[v] = 0.0; else scd->cl[c].tracer_vals[v] = atof(str.c_str()); } // orientation from grid axes to principal axes. scd->cl[c].ang[XX] = 0.0; scd->cl[c].ang[YY] = 0.0; scd->cl[c].ang[ZZ] = 0.0; // // zero the z-dir if 2d if (SimPM->ndim==2) { scd->cl[c].ang[ZZ] = scd->cl[c].ang[YY] = scd->cl[c].size[ZZ] = scd->cl[c].centre[ZZ] = 0.0; } // // Set Mass, based on profile. Note this is total mass, including ambient gas. // scd->cl[c].mass = ambdens*(1.0+scd->cl[c].overdensity); if (scd->profile==0) { // top hat profile: M=Volume*density scd->cl[c].mass *= 4.0*M_PI*scd->cl[c].size[XX]*scd->cl[c].size[XX]*scd->cl[c].size[XX]/3.0; } else if (scd->profile==1) { // Gaussian profile for (int v=0;v<SimPM->ndim;v++) scd->cl[c].mass *= sqrt(2.0*M_PI)*scd->cl[c].size[v]; // // If axisymmetric, then 3rd dimension is same as radial dimension, so multiply again. // if (SimPM->coord_sys==COORD_CYL) scd->cl[c].mass *= sqrt(2.0*M_PI)*scd->cl[c].size[Rcyl]; } else rep.error("Bad profile in get_strategic_clump_params()",scd->profile); // // print clump... print_clump(&scd->cl[c]); // // now set up the rotation matrix. // scd->cl[c].rm[XX][XX] = cos(scd->cl[c].ang[XX])*cos(scd->cl[c].ang[YY])*cos(scd->cl[c].ang[ZZ]) -sin(scd->cl[c].ang[XX])*sin(scd->cl[c].ang[ZZ]); scd->cl[c].rm[XX][YY] = sin(scd->cl[c].ang[XX])*cos(scd->cl[c].ang[YY])*cos(scd->cl[c].ang[ZZ]) +cos(scd->cl[c].ang[XX])*sin(scd->cl[c].ang[ZZ]); scd->cl[c].rm[XX][ZZ] = -sin(scd->cl[c].ang[YY])*cos(scd->cl[c].ang[ZZ]); scd->cl[c].rm[YY][XX] = -cos(scd->cl[c].ang[XX])*cos(scd->cl[c].ang[YY])*sin(scd->cl[c].ang[ZZ]) -sin(scd->cl[c].ang[XX])*cos(scd->cl[c].ang[ZZ]); scd->cl[c].rm[YY][YY] = -sin(scd->cl[c].ang[XX])*cos(scd->cl[c].ang[YY])*sin(scd->cl[c].ang[ZZ]) +cos(scd->cl[c].ang[XX])*cos(scd->cl[c].ang[ZZ]); scd->cl[c].rm[YY][ZZ] = sin(scd->cl[c].ang[YY])*sin(scd->cl[c].ang[ZZ]); scd->cl[c].rm[ZZ][XX] = cos(scd->cl[c].ang[XX])*sin(scd->cl[c].ang[YY]); scd->cl[c].rm[ZZ][YY] = sin(scd->cl[c].ang[XX])*sin(scd->cl[c].ang[YY]); scd->cl[c].rm[ZZ][ZZ] = cos(scd->cl[c].ang[YY]); // // all done, move on to next clump. // } cout <<"\tSet parameters for "<<scd->Nclumps<<" clumps. returning.\n"; return err; } // ################################################################## // ################################################################## int IC_photevap_multi_clumps::add_strategic_clumps_to_grid( class GridBaseClass *ggg, struct strategic_clump_data *scd ) { int err=0; if (!scd->used) { cout <<"\tnot using strategic clumps, so not adding any to grid.\n"; return 0; } cout <<"Adding strategic clumps to grid..."; cell *c = ggg->FirstPt(); do { err += clumps_set_dens(c, scd->Nclumps, scd->cl, scd->profile); } while ( (c=ggg->NextPt(c))!=0); cout <<"\tFinished adding strategic clumps to grid.\n"; return err; } // ################################################################## // ################################################################## double IC_photevap_multi_clumps::random_frac() { // // Returns a random value between 0 and 1. // return ((double) rand())/((double) RAND_MAX); } // ################################################################## // ################################################################## int IC_photevap_multi_clumps::clumps_set_dens(class cell *c, const int Nclumps, struct clump *cl, const int profile ) { int err=0; double x0[ndim],x1[ndim], dpos[ndim]; CI.get_dpos(c,dpos); for (int j=0;j<Nclumps;j++) { // // get distance from centre to clump. // If we have periodic BCs, need to do a bit more work... // //if (SimPM->typeofbc.find("YNper") != std::string::npos) { if (SimPM->BC_YN == "periodic") { x0[XX] = dpos[XX]-cl[j].centre[XX]; double temp; for (int i=1;i<ndim;i++) { temp = dpos[i]-cl[j].centre[i]; if (temp>0.0) { if (temp > SimPM->Range[i]/2.) x0[i] = temp -SimPM->Range[i]; else x0[i] = temp; } else { if (temp < -SimPM->Range[i]/2.) x0[i] = temp +SimPM->Range[i]; else x0[i] = temp; } } } else { // not periodic bcs. for (int i=0;i<ndim;i++) x0[i] = dpos[i]-cl[j].centre[i]; } // // rotate clump according to rotation matrix generated from random angles. // for (int u=0;u<ndim;u++) { x1[u] = 0.0; for (int v=0;v<ndim;v++) x1[u] += x0[v] *cl[j].rm[u][v]; } // // add density from clump onto existing density in cell. // double add_rho=0.0; if (profile==0) { // top-hat profile bool inside=true; double dist=0.0; for (int k=0;k<ndim;k++) dist += x1[k]*x1[k]/cl[j].size[k]/cl[j].size[k]; if (dist>1.0) inside=false; // for (int k=0;k<ndim;k++) if (fabs(x1[k])> cl[j].size[k]) inside=false; if (inside) { add_rho = ambdens*cl[j].overdensity; c->P[RO] += add_rho; } } else if (profile==1) { // // Gaussian Profile: Set exponential factor based on how far from centre we are. // Then set density based on that. // Note profile has factor of 2, so that size is easily related to normal distribution. // Set tracers according to fraction of mass that is ambient and clump: // double ef=0.0; for (int v=0;v<ndim;v++) ef += x1[v]*x1[v]/cl[j].size[v]/cl[j].size[v]/2.0; add_rho = ambdens*cl[j].overdensity*exp(-ef); c->P[RO] += add_rho; } else rep.error("Bad profile id in parameter-file",profile); // // Set tracer values: // (random clumps over-writes this later, because it is sketchy if clumps overlap) // Criterion: If we have added density>0.5*ambient to cell, label it with // clump's tracer values. //if (add_rho >= 0.1*ambdens*cl[j].overdensity) { // for (int v=SimPM->ftr; v<SimPM->nvar;v++) { // c->P[v] = cl[j].tracer_vals[v-SimPM->ftr]; // } //} // // Update 2010-02-08 JM: compare density to ambient and apply // tracer value appropriately. Note this only works if all the // clumps have the same tracer value (and also for ambient data!). // if (add_rho/c->P[RO] > 0.001 ) { for (int v=SimPM->ftr; v<SimPM->nvar;v++) { c->P[v] = cl[j].tracer_vals[v-SimPM->ftr] +ambdens/c->P[RO]*(amb_data.ambient[v]-cl[j].tracer_vals[v-SimPM->ftr]); } // // Update 2012.02.25 JM: Add clump velocity w.r.t. grid, smoothly varying // from the max value at the centre to the ambient value near the edge. // //cout <<"V=["<<cl[j].Vel[0]<<","<<cl[j].Vel[1]<<","<<cl[j].Vel[2]<<"\n"; c->P[VX] = cl[j].Vel[0]+ambdens/c->P[RO]*(amb_data.ambient[VX]-cl[j].Vel[0]); c->P[VY] = cl[j].Vel[1]+ambdens/c->P[RO]*(amb_data.ambient[VY]-cl[j].Vel[1]); c->P[VZ] = cl[j].Vel[2]+ambdens/c->P[RO]*(amb_data.ambient[VZ]-cl[j].Vel[2]); } // // Done with this clump, loop onto next... // } // // If we are using isothermal equations, then ambient[PG] is set // as the sound speed everywhere (assuming everywhere is neutral // initially), so we don't need to adjust it at all. // return err; } void IC_photevap_multi_clumps::print_clump(struct clump *rc) { cout <<"--clump overdensity:"<<rc->overdensity<<" mass/Msun:"<<rc->mass/pconst.Msun()<<endl; rep.printVec("Centre",rc->centre,SimPM->ndim); rep.printVec("Radius",rc->size,SimPM->ndim); rep.printVec("Angles",rc->ang,SimPM->ndim); cout <<"-------------------\n"; return; }
31.487566
150
0.560023
jfbucas
787f3d958f61285014387999a526f7112f9e64e0
1,042
hpp
C++
lib/libcpp/FadalightMesh/FadalightMesh/hangingnodeinfo.hpp
beckerrh/simfemsrc
d857eb6f6f8627412d4f9d89a871834c756537db
[ "MIT" ]
null
null
null
lib/libcpp/FadalightMesh/FadalightMesh/hangingnodeinfo.hpp
beckerrh/simfemsrc
d857eb6f6f8627412d4f9d89a871834c756537db
[ "MIT" ]
1
2019-01-31T10:59:11.000Z
2019-01-31T10:59:11.000Z
lib/libcpp/FadalightMesh/FadalightMesh/hangingnodeinfo.hpp
beckerrh/simfemsrc
d857eb6f6f8627412d4f9d89a871834c756537db
[ "MIT" ]
null
null
null
#ifndef __FadalightMesh_HangingNodeInfo_h #define __FadalightMesh_HangingNodeInfo_h #include "FadalightMesh/geometryobject.hpp" #include "Alat/sparsitypattern.hpp" /*---------------------------------------------------------*/ namespace FadalightMesh { class HangingNodeInfo : public FadalightMesh::GeometryObject, public alat::SparsityPattern { public: ~HangingNodeInfo(); HangingNodeInfo(); HangingNodeInfo(const HangingNodeInfo& hangingnodeinfo); HangingNodeInfo& operator=(const HangingNodeInfo& hangingnodeinfo); std::string getClassName() const; int getCellNumber(int i) const; int getLocalSide(int i) const; int getNumberOfHangingNodes(int i) const; int getHangingNodes(int i, int in) const; int& getCellNumber(int i); int& getLocalSide(int i); int& getHangingNodes(int i, int in); void set_size(int n_hanging, int n_local_data); void load(std::string filename ); void save(std::string filename, arma::file_type datatype = arma::arma_binary) const; }; } #endif
30.647059
92
0.701536
beckerrh
788034aa681e1bcfb9ac144e586d6560d159b5fc
17,258
cpp
C++
src/pyglue/PyDisplayTransform.cpp
mjmvisser/OpenColorIO
a557a85454ee1ffa8cb66f8a96238e079c452f08
[ "BSD-3-Clause" ]
4
2015-02-25T21:54:11.000Z
2020-12-22T13:58:27.000Z
src/pyglue/PyDisplayTransform.cpp
dictoon/OpenColorIO
64adcad300adfd166280d2e7b1fb5c3ce7dca482
[ "BSD-3-Clause" ]
null
null
null
src/pyglue/PyDisplayTransform.cpp
dictoon/OpenColorIO
64adcad300adfd166280d2e7b1fb5c3ce7dca482
[ "BSD-3-Clause" ]
null
null
null
/* Copyright (c) 2003-2010 Sony Pictures Imageworks Inc., et al. All Rights Reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Sony Pictures Imageworks nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <Python.h> #include <OpenColorIO/OpenColorIO.h> #include "PyUtil.h" #include "PyDoc.h" #define GetConstDisplayTransform(pyobject) GetConstPyOCIO<PyOCIO_Transform, \ ConstDisplayTransformRcPtr, DisplayTransform>(pyobject, \ PyOCIO_DisplayTransformType) #define GetEditableDisplayTransform(pyobject) GetEditablePyOCIO<PyOCIO_Transform, \ DisplayTransformRcPtr, DisplayTransform>(pyobject, \ PyOCIO_DisplayTransformType) OCIO_NAMESPACE_ENTER { namespace { /////////////////////////////////////////////////////////////////////// /// int PyOCIO_DisplayTransform_init(PyOCIO_Transform * self, PyObject * args, PyObject * kwds); PyObject * PyOCIO_DisplayTransform_getInputColorSpaceName(PyObject * self); PyObject * PyOCIO_DisplayTransform_setInputColorSpaceName(PyObject * self, PyObject * args); PyObject * PyOCIO_DisplayTransform_getLinearCC(PyObject * self); PyObject * PyOCIO_DisplayTransform_setLinearCC(PyObject * self, PyObject * args); PyObject * PyOCIO_DisplayTransform_getColorTimingCC(PyObject * self); PyObject * PyOCIO_DisplayTransform_setColorTimingCC(PyObject * self, PyObject * args); PyObject * PyOCIO_DisplayTransform_getChannelView(PyObject * self); PyObject * PyOCIO_DisplayTransform_setChannelView(PyObject * self, PyObject * args); PyObject * PyOCIO_DisplayTransform_getDisplay(PyObject * self); PyObject * PyOCIO_DisplayTransform_setDisplay(PyObject * self, PyObject * args); PyObject * PyOCIO_DisplayTransform_getView(PyObject * self); PyObject * PyOCIO_DisplayTransform_setView(PyObject * self, PyObject * args); PyObject * PyOCIO_DisplayTransform_getDisplayCC(PyObject * self); PyObject * PyOCIO_DisplayTransform_setDisplayCC(PyObject * self, PyObject * args ); PyObject * PyOCIO_DisplayTransform_getLooksOverride(PyObject * self ); PyObject * PyOCIO_DisplayTransform_setLooksOverride(PyObject * self, PyObject * args); PyObject * PyOCIO_DisplayTransform_getLooksOverrideEnabled(PyObject * self ); PyObject * PyOCIO_DisplayTransform_setLooksOverrideEnabled(PyObject * self, PyObject * args); /////////////////////////////////////////////////////////////////////// /// PyMethodDef PyOCIO_DisplayTransform_methods[] = { { "getInputColorSpaceName", (PyCFunction) PyOCIO_DisplayTransform_getInputColorSpaceName, METH_NOARGS, DISPLAYTRANSFORM_GETINPUTCOLORSPACENAME__DOC__ }, { "setInputColorSpaceName", PyOCIO_DisplayTransform_setInputColorSpaceName, METH_VARARGS, DISPLAYTRANSFORM_SETINPUTCOLORSPACENAME__DOC__ }, { "getLinearCC", (PyCFunction) PyOCIO_DisplayTransform_getLinearCC, METH_NOARGS, DISPLAYTRANSFORM_GETLINEARCC__DOC__ }, { "setLinearCC", PyOCIO_DisplayTransform_setLinearCC, METH_VARARGS, DISPLAYTRANSFORM_SETLINEARCC__DOC__ }, { "getColorTimingCC", (PyCFunction) PyOCIO_DisplayTransform_getColorTimingCC, METH_NOARGS, DISPLAYTRANSFORM_GETCOLORTIMINGCC__DOC__ }, { "setColorTimingCC", PyOCIO_DisplayTransform_setColorTimingCC, METH_VARARGS, DISPLAYTRANSFORM_SETCOLORTIMINGCC__DOC__ }, { "getChannelView", (PyCFunction) PyOCIO_DisplayTransform_getChannelView, METH_NOARGS, DISPLAYTRANSFORM_GETCHANNELVIEW__DOC__ }, { "setChannelView", PyOCIO_DisplayTransform_setChannelView, METH_VARARGS, DISPLAYTRANSFORM_SETCHANNELVIEW__DOC__ }, { "getDisplay", (PyCFunction) PyOCIO_DisplayTransform_getDisplay, METH_NOARGS, DISPLAYTRANSFORM_GETDISPLAY__DOC__ }, { "setDisplay", PyOCIO_DisplayTransform_setDisplay, METH_VARARGS, DISPLAYTRANSFORM_SETDISPLAY__DOC__ }, { "getView", (PyCFunction) PyOCIO_DisplayTransform_getView, METH_NOARGS, DISPLAYTRANSFORM_GETVIEW__DOC__ }, { "setView", PyOCIO_DisplayTransform_setView, METH_VARARGS, DISPLAYTRANSFORM_SETVIEW__DOC__ }, { "getDisplayCC", (PyCFunction) PyOCIO_DisplayTransform_getDisplayCC, METH_NOARGS, DISPLAYTRANSFORM_GETDISPLAYCC__DOC__ }, { "setDisplayCC", PyOCIO_DisplayTransform_setDisplayCC, METH_VARARGS, DISPLAYTRANSFORM_SETDISPLAYCC__DOC__ }, { "getLooksOverride", (PyCFunction) PyOCIO_DisplayTransform_getLooksOverride, METH_NOARGS, DISPLAYTRANSFORM_GETLOOKSOVERRIDE__DOC__ }, { "setLooksOverride", PyOCIO_DisplayTransform_setLooksOverride, METH_VARARGS, DISPLAYTRANSFORM_SETLOOKSOVERRIDE__DOC__ }, { "getLooksOverrideEnabled", (PyCFunction) PyOCIO_DisplayTransform_getLooksOverrideEnabled, METH_NOARGS, DISPLAYTRANSFORM_GETLOOKSOVERRIDEENABLED__DOC__ }, { "setLooksOverrideEnabled", PyOCIO_DisplayTransform_setLooksOverrideEnabled, METH_VARARGS, DISPLAYTRANSFORM_SETLOOKSOVERRIDEENABLED__DOC__ }, { NULL, NULL, 0, NULL } }; } /////////////////////////////////////////////////////////////////////////// /// PyTypeObject PyOCIO_DisplayTransformType = { PyVarObject_HEAD_INIT(NULL, 0) "OCIO.DisplayTransform", //tp_name sizeof(PyOCIO_Transform), //tp_basicsize 0, //tp_itemsize 0, //tp_dealloc 0, //tp_print 0, //tp_getattr 0, //tp_setattr 0, //tp_compare 0, //tp_repr 0, //tp_as_number 0, //tp_as_sequence 0, //tp_as_mapping 0, //tp_hash 0, //tp_call 0, //tp_str 0, //tp_getattro 0, //tp_setattro 0, //tp_as_buffer Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, //tp_flags DISPLAYTRANSFORM__DOC__, //tp_doc 0, //tp_traverse 0, //tp_clear 0, //tp_richcompare 0, //tp_weaklistoffset 0, //tp_iter 0, //tp_iternext PyOCIO_DisplayTransform_methods, //tp_methods 0, //tp_members 0, //tp_getset &PyOCIO_TransformType, //tp_base 0, //tp_dict 0, //tp_descr_get 0, //tp_descr_set 0, //tp_dictoffset (initproc) PyOCIO_DisplayTransform_init, //tp_init 0, //tp_alloc 0, //tp_new 0, //tp_free 0, //tp_is_gc }; namespace { /////////////////////////////////////////////////////////////////////// /// int PyOCIO_DisplayTransform_init(PyOCIO_Transform * self, PyObject * /*args*/, PyObject * /*kwds*/) { OCIO_PYTRY_ENTER() return BuildPyTransformObject<DisplayTransformRcPtr>(self, DisplayTransform::Create()); OCIO_PYTRY_EXIT(-1) } PyObject * PyOCIO_DisplayTransform_getInputColorSpaceName(PyObject * self) { OCIO_PYTRY_ENTER() ConstDisplayTransformRcPtr transform = GetConstDisplayTransform(self); return PyString_FromString(transform->getInputColorSpaceName()); OCIO_PYTRY_EXIT(NULL) } PyObject * PyOCIO_DisplayTransform_setInputColorSpaceName(PyObject * self, PyObject * args) { OCIO_PYTRY_ENTER() char* name = 0; if (!PyArg_ParseTuple(args, "s:setInputColorSpaceName", &name)) return NULL; DisplayTransformRcPtr transform = GetEditableDisplayTransform(self); transform->setInputColorSpaceName(name); Py_RETURN_NONE; OCIO_PYTRY_EXIT(NULL) } PyObject * PyOCIO_DisplayTransform_getLinearCC(PyObject * self) { OCIO_PYTRY_ENTER() ConstDisplayTransformRcPtr transform = GetConstDisplayTransform(self); return BuildConstPyTransform(transform->getLinearCC()); OCIO_PYTRY_EXIT(NULL) } PyObject * PyOCIO_DisplayTransform_setLinearCC(PyObject * self, PyObject * args) { OCIO_PYTRY_ENTER() PyObject * pyCC = 0; if (!PyArg_ParseTuple(args, "O:setLinearCC", &pyCC)) return NULL; DisplayTransformRcPtr transform = GetEditableDisplayTransform(self); ConstTransformRcPtr cc = GetConstTransform(pyCC, true); transform->setLinearCC(cc); Py_RETURN_NONE; OCIO_PYTRY_EXIT(NULL) } PyObject * PyOCIO_DisplayTransform_getColorTimingCC(PyObject * self) { OCIO_PYTRY_ENTER() ConstDisplayTransformRcPtr transform = GetConstDisplayTransform(self); return BuildConstPyTransform(transform->getColorTimingCC()); OCIO_PYTRY_EXIT(NULL) } PyObject * PyOCIO_DisplayTransform_setColorTimingCC(PyObject * self, PyObject * args) { OCIO_PYTRY_ENTER() PyObject* pyCC = 0; if (!PyArg_ParseTuple(args, "O:setColorTimingCC", &pyCC)) return NULL; DisplayTransformRcPtr transform = GetEditableDisplayTransform(self); ConstTransformRcPtr cc = GetConstTransform(pyCC, true); transform->setColorTimingCC(cc); Py_RETURN_NONE; OCIO_PYTRY_EXIT(NULL) } PyObject * PyOCIO_DisplayTransform_getChannelView(PyObject * self) { OCIO_PYTRY_ENTER() ConstDisplayTransformRcPtr transform = GetConstDisplayTransform(self); return BuildConstPyTransform(transform->getChannelView()); OCIO_PYTRY_EXIT(NULL) } PyObject * PyOCIO_DisplayTransform_setChannelView(PyObject * self, PyObject * args) { OCIO_PYTRY_ENTER() PyObject* pyCC = 0; if (!PyArg_ParseTuple(args, "O:setChannelView", &pyCC)) return NULL; DisplayTransformRcPtr transform = GetEditableDisplayTransform(self); ConstTransformRcPtr t = GetConstTransform(pyCC, true); transform->setChannelView(t); Py_RETURN_NONE; OCIO_PYTRY_EXIT(NULL) } PyObject * PyOCIO_DisplayTransform_getDisplay(PyObject * self) { OCIO_PYTRY_ENTER() ConstDisplayTransformRcPtr transform = GetConstDisplayTransform(self); return PyString_FromString(transform->getDisplay()); OCIO_PYTRY_EXIT(NULL) } PyObject * PyOCIO_DisplayTransform_setDisplay(PyObject * self, PyObject * args) { OCIO_PYTRY_ENTER() char* str = 0; if (!PyArg_ParseTuple(args, "s:setDisplay", &str)) return NULL; DisplayTransformRcPtr transform = GetEditableDisplayTransform(self); transform->setDisplay(str); Py_RETURN_NONE; OCIO_PYTRY_EXIT(NULL) } PyObject * PyOCIO_DisplayTransform_getView(PyObject * self) { OCIO_PYTRY_ENTER() ConstDisplayTransformRcPtr transform = GetConstDisplayTransform(self); return PyString_FromString(transform->getView()); OCIO_PYTRY_EXIT(NULL) } PyObject * PyOCIO_DisplayTransform_setView(PyObject * self, PyObject * args) { OCIO_PYTRY_ENTER() char* str = 0; if (!PyArg_ParseTuple(args, "s:setView", &str)) return NULL; DisplayTransformRcPtr transform = GetEditableDisplayTransform(self); transform->setView(str); Py_RETURN_NONE; OCIO_PYTRY_EXIT(NULL) } PyObject * PyOCIO_DisplayTransform_getDisplayCC(PyObject * self) { OCIO_PYTRY_ENTER() ConstDisplayTransformRcPtr transform = GetConstDisplayTransform(self); return BuildConstPyTransform(transform->getDisplayCC()); OCIO_PYTRY_EXIT(NULL) } PyObject * PyOCIO_DisplayTransform_setDisplayCC(PyObject * self, PyObject * args) { OCIO_PYTRY_ENTER() PyObject* pyCC = 0; if (!PyArg_ParseTuple(args,"O:setDisplayCC", &pyCC)) return NULL; DisplayTransformRcPtr transform = GetEditableDisplayTransform(self); ConstTransformRcPtr cc = GetConstTransform(pyCC, true); transform->setDisplayCC(cc); Py_RETURN_NONE; OCIO_PYTRY_EXIT(NULL) } PyObject * PyOCIO_DisplayTransform_getLooksOverride(PyObject * self) { OCIO_PYTRY_ENTER() ConstDisplayTransformRcPtr transform = GetConstDisplayTransform(self); return PyString_FromString(transform->getLooksOverride()); OCIO_PYTRY_EXIT(NULL) } PyObject * PyOCIO_DisplayTransform_setLooksOverride(PyObject * self, PyObject * args) { OCIO_PYTRY_ENTER() char* str = 0; if (!PyArg_ParseTuple(args,"s:setLooksOverride", &str)) return NULL; DisplayTransformRcPtr transform = GetEditableDisplayTransform(self); transform->setLooksOverride(str); Py_RETURN_NONE; OCIO_PYTRY_EXIT(NULL) } PyObject * PyOCIO_DisplayTransform_getLooksOverrideEnabled(PyObject * self) { OCIO_PYTRY_ENTER() ConstDisplayTransformRcPtr transform = GetConstDisplayTransform(self); return PyBool_FromLong(transform->getLooksOverrideEnabled()); OCIO_PYTRY_EXIT(NULL) } PyObject * PyOCIO_DisplayTransform_setLooksOverrideEnabled(PyObject * self, PyObject * args) { OCIO_PYTRY_ENTER() bool enabled = false; if (!PyArg_ParseTuple(args, "O&:setLooksOverrideEnabled", ConvertPyObjectToBool, &enabled)) return NULL; DisplayTransformRcPtr transform = GetEditableDisplayTransform(self); transform->setLooksOverrideEnabled(enabled); Py_RETURN_NONE; OCIO_PYTRY_EXIT(NULL) } } } OCIO_NAMESPACE_EXIT
47.5427
138
0.592653
mjmvisser
788985cc08b864e56b797e167946e9f51a63f653
764
cpp
C++
2020.09.24-Homework-2/Task3 Dynamic array/Task3 Dynamic array/Source.cpp
Atilin/1st-semester-SPBU
b6719d7cd2213aaded065d93ee000c4bb95568ad
[ "Apache-2.0" ]
null
null
null
2020.09.24-Homework-2/Task3 Dynamic array/Task3 Dynamic array/Source.cpp
Atilin/1st-semester-SPBU
b6719d7cd2213aaded065d93ee000c4bb95568ad
[ "Apache-2.0" ]
null
null
null
2020.09.24-Homework-2/Task3 Dynamic array/Task3 Dynamic array/Source.cpp
Atilin/1st-semester-SPBU
b6719d7cd2213aaded065d93ee000c4bb95568ad
[ "Apache-2.0" ]
1
2020-11-30T14:39:45.000Z
2020-11-30T14:39:45.000Z
#include <iostream> #include <clocale> using namespace std; void expandArray(int*& a, int& cap, int& count) { cap += 10; int* temp = new int[cap] {0}; for (int i = 0; i < count; ++i) { temp[i] = a[i]; } delete[] a; a = temp; } int main() { setlocale(LC_ALL, "Russian"); int cap = 10; int* a = new int[cap]; cout << "Введите последовательность чисел, завершите ее нулем\n\n"; int count = 0; while (true) { int x = 0; cin >> x; if (x == 0) { break; } if (count == cap) { expandArray(a, cap, count); } a[count] = x; ++count; } cout << endl; double sum = 0; for (int i = 0; i < count; ++i) { int x = 1; for (int j = 2; j <= a[i]; ++j) { x *= j; } sum += x; } cout << sum/count; delete[] a; return 0; }
14.148148
68
0.519634
Atilin
788d1286610f0ab0211d11becfb11fc32c09d40e
51,141
cc
C++
tests/core/test_core_playsync_manager.cc
JeanTracker/nugu-linux
28b5337b4f74442126ce5ec55001c2fe09271e40
[ "Apache-2.0" ]
null
null
null
tests/core/test_core_playsync_manager.cc
JeanTracker/nugu-linux
28b5337b4f74442126ce5ec55001c2fe09271e40
[ "Apache-2.0" ]
null
null
null
tests/core/test_core_playsync_manager.cc
JeanTracker/nugu-linux
28b5337b4f74442126ce5ec55001c2fe09271e40
[ "Apache-2.0" ]
1
2019-10-21T09:38:47.000Z
2019-10-21T09:38:47.000Z
/* * Copyright (c) 2019 SK Telecom Co., Ltd. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <algorithm> #include <chrono> #include <condition_variable> #include <functional> #include <glib.h> #include <map> #include <memory> #include <mutex> #include <set> #include <thread> #include "interaction_control_manager.hh" #include "playsync_manager.hh" using namespace NuguCore; const unsigned int TIMER_DOWNSCALE_FACTOR = 50; std::mutex mutex; std::condition_variable cv; class FakeStackTimer final : public IStackTimer { public: FakeStackTimer(std::mutex& mutex, std::condition_variable& cv) : _mutex(mutex) , _cv(cv) { } virtual ~FakeStackTimer() { stop(); } bool isStarted() override { return is_started; } void start(unsigned int sec = 0) override { if (is_started) return; setStarted(true); worker = std::thread { [&]() { std::this_thread::sleep_for(std::chrono::microseconds(getInterval() / TIMER_DOWNSCALE_FACTOR)); if (is_started) notifyCallback(); setStarted(false); _cv.notify_one(); } }; } void stop() override { setStarted(false); if (worker.joinable()) worker.join(); } unsigned int getPlayStackHoldTime() { return getInterval() / 1000; } bool isRestarted() { return started_count > 1; } void reset() { started_count = 0; if (worker.joinable()) worker.join(); } private: void setStarted(bool is_started) { std::lock_guard<std::mutex> lock(_mutex); this->is_started = is_started; if (is_started) started_count++; } std::thread worker; bool is_started = false; std::mutex& _mutex; std::condition_variable& _cv; int started_count = 0; }; struct DummyExtraInfo { std::string id; }; class PlaySyncManagerListener : public IPlaySyncManagerListener { public: void onSyncState(const std::string& ps_id, PlaySyncState state, void* extra_data) override { if (this->state != state) { this->state = state; this->extra_data = extra_data; same_state_call_count = 0; } else { same_state_call_count++; } sync_state_map[ps_id] = state; if (state == PlaySyncState::Released && inter_hook_func) inter_hook_func(); } void onDataChanged(const std::string& ps_id, std::pair<void*, void*> extra_datas) override { this->extra_data = extra_datas.second; } void onStackChanged(const std::pair<std::string, std::string>& ps_ids) override { if (!ps_ids.first.empty()) playstacks.emplace(ps_ids.first); if (!ps_ids.second.empty()) playstacks.erase(ps_ids.second); } PlaySyncState getSyncState(const std::string& ps_id) { try { return sync_state_map.at(ps_id); } catch (std::out_of_range& exception) { return PlaySyncState::None; } } bool hasPlayStack(const std::string& ps_id) { return sync_state_map.find(ps_id) != sync_state_map.cend(); } int getSameStateCallCount() { return same_state_call_count; } void* getExtraData() { return extra_data; } void setHookInonSyncState(std::function<void()>&& hook_func) { inter_hook_func = hook_func; } const std::set<std::string>& getPlaystacks() { return playstacks; } private: std::map<std::string, PlaySyncState> sync_state_map; std::set<std::string> playstacks; PlaySyncState state = PlaySyncState::None; void* extra_data = nullptr; int same_state_call_count = 0; std::function<void()> inter_hook_func = nullptr; }; class InteractionControlManagerListener : public IInteractionControlManagerListener { public: void onHasMultiTurn() override { has_multi_turn = true; } void onModeChanged(bool is_multi_turn) override { if (!is_multi_turn) has_multi_turn = false; } bool hasMultiTurn() { return has_multi_turn; } private: bool has_multi_turn = false; }; static NuguDirective* createDirective(const std::string& name_space, const std::string& name, const std::string& groups) { return nugu_directive_new(name_space.c_str(), name.c_str(), "1.0", "msg_1", "dlg_1", "ref_1", "{}", groups.c_str()); } typedef struct { std::shared_ptr<PlaySyncManager> playsync_manager; std::shared_ptr<PlaySyncManagerListener> playsync_manager_listener; std::shared_ptr<PlaySyncManagerListener> playsync_manager_listener_snd; std::shared_ptr<InteractionControlManager> ic_manager; std::shared_ptr<InteractionControlManagerListener> ic_manager_listener; FakeStackTimer* fake_timer; DummyExtraInfo* dummy_extra_data; DummyExtraInfo* dummy_extra_data_snd; NuguDirective* ndir_info_disp; NuguDirective* ndir_media; NuguDirective* ndir_expect_speech; NuguDirective* ndir_alerts; NuguDirective* ndir_disp_expect_speech; } TestFixture; static void setup(TestFixture* fixture, gconstpointer user_data) { fixture->playsync_manager = std::make_shared<PlaySyncManager>(); fixture->playsync_manager_listener = std::make_shared<PlaySyncManagerListener>(); fixture->playsync_manager_listener_snd = std::make_shared<PlaySyncManagerListener>(); fixture->ic_manager = std::make_shared<InteractionControlManager>(); fixture->ic_manager_listener = std::make_shared<InteractionControlManagerListener>(); fixture->fake_timer = new FakeStackTimer(mutex, cv); PlayStackManager* playstack_manager = new PlayStackManager(); playstack_manager->setTimer(fixture->fake_timer); playstack_manager->setPlayStackHoldTime({ 7, 60 }); fixture->ic_manager->addListener(fixture->ic_manager_listener.get()); fixture->playsync_manager->setPlayStackManager(playstack_manager); fixture->playsync_manager->setInteractionControlManager(fixture->ic_manager.get()); fixture->playsync_manager->addListener("TTS", fixture->playsync_manager_listener.get()); fixture->dummy_extra_data = new DummyExtraInfo(); fixture->dummy_extra_data_snd = new DummyExtraInfo(); fixture->ndir_info_disp = createDirective("TTS", "Speak", "{ \"directives\": [\"TTS.Speak\", \"Display.FullText1\"] }"); fixture->ndir_media = createDirective("AudioPlayer", "Play", "{ \"directives\": [\"TTS.Speak\", \"AudioPlayer.Play\"] }"); fixture->ndir_expect_speech = createDirective("ASR", "test", "{ \"directives\": [\"TTS.Speak\", \"ASR.ExpectSpeech\", \"Session.Set\"] }"); fixture->ndir_alerts = createDirective("Alerts", "SetAlert", "{ \"directives\": [\"Alerts.SetAlert\"] }"); fixture->ndir_disp_expect_speech = createDirective("Display", "test", "{ \"directives\": [\"Display.FullText1\", \"TTS.Speak\", \"ASR.ExpectSpeech\"] }"); } static void teardown(TestFixture* fixture, gconstpointer user_data) { nugu_directive_unref(fixture->ndir_info_disp); nugu_directive_unref(fixture->ndir_media); nugu_directive_unref(fixture->ndir_expect_speech); nugu_directive_unref(fixture->ndir_alerts); nugu_directive_unref(fixture->ndir_disp_expect_speech); fixture->playsync_manager_listener.reset(); fixture->playsync_manager_listener_snd.reset(); fixture->playsync_manager.reset(); fixture->ic_manager_listener.reset(); fixture->ic_manager.reset(); delete fixture->dummy_extra_data; delete fixture->dummy_extra_data_snd; fixture->dummy_extra_data = nullptr; fixture->dummy_extra_data_snd = nullptr; } static void onTimeElapsed(TestFixture* fixture) { std::unique_lock<std::mutex> lock(mutex); cv.wait(lock, [&] { return !fixture->fake_timer->isStarted(); }); fixture->fake_timer->reset(); } #define G_TEST_ADD_FUNC(name, func) \ g_test_add(name, TestFixture, nullptr, setup, func, teardown); static void test_playsync_manager_listener(TestFixture* fixture, gconstpointer ignored) { // It already has one listener which is added in setup. // check invalid parameter fixture->playsync_manager->addListener("", fixture->playsync_manager_listener.get()); g_assert(fixture->playsync_manager->getListenerCount() == 1); // check whether same listener is added duplicately fixture->playsync_manager->addListener("TTS", fixture->playsync_manager_listener.get()); g_assert(fixture->playsync_manager->getListenerCount() == 1); // check invalid parameter fixture->playsync_manager->addListener("Display", nullptr); g_assert(fixture->playsync_manager->getListenerCount() == 1); fixture->playsync_manager->addListener("Display", fixture->playsync_manager_listener_snd.get()); g_assert(fixture->playsync_manager->getListenerCount() == 2); // check invalid parameter fixture->playsync_manager->removeListener(""); g_assert(fixture->playsync_manager->getListenerCount() == 2); fixture->playsync_manager->removeListener("TTS"); g_assert(fixture->playsync_manager->getListenerCount() == 1); // check whether same listener is removed duplicately fixture->playsync_manager->removeListener("TTS"); g_assert(fixture->playsync_manager->getListenerCount() == 1); fixture->playsync_manager->removeListener("Display"); g_assert(fixture->playsync_manager->getListenerCount() == 0); } static void test_playsync_manager_prepare_sync(TestFixture* fixture, gconstpointer ignored) { const auto& playstacks = fixture->playsync_manager->getPlayStacks(); // check invalid parameter fixture->playsync_manager->prepareSync("", fixture->ndir_info_disp); g_assert(playstacks.empty()); // check invalid parameter fixture->playsync_manager->prepareSync("ps_id_1", nullptr); g_assert(playstacks.empty()); fixture->playsync_manager->prepareSync("ps_id_1", fixture->ndir_info_disp); const auto& playsync_container = playstacks.at("ps_id_1"); g_assert(playsync_container.at("TTS").first == PlaySyncState::Prepared); g_assert(playsync_container.at("Display").first == PlaySyncState::Prepared); g_assert(fixture->playsync_manager_listener->getSyncState("ps_id_1") == PlaySyncState::Prepared); } static void test_playsync_manager_start_sync(TestFixture* fixture, gconstpointer ignored) { const auto& playstacks = fixture->playsync_manager->getPlayStacks(); // try to start sync before prepare sync fixture->playsync_manager->startSync("ps_id_1", "TTS"); g_assert(playstacks.find("ps_id_1") == playstacks.cend()); g_assert(fixture->playsync_manager_listener->getSyncState("ps_id_1") == PlaySyncState::None); g_assert(!fixture->playsync_manager_listener->hasPlayStack("ps_id_1")); fixture->playsync_manager->prepareSync("ps_id_1", fixture->ndir_info_disp); const auto& playsync_container = playstacks.at("ps_id_1"); g_assert(fixture->playsync_manager_listener->getSyncState("ps_id_1") == PlaySyncState::Prepared); // check invalid parameter fixture->playsync_manager->startSync("", "TTS"); g_assert(playsync_container.at("TTS").first == PlaySyncState::Prepared); // check invalid parameter fixture->playsync_manager->startSync("ps_id_1", ""); g_assert(playsync_container.at("TTS").first == PlaySyncState::Prepared); // try to start sync not prepared play service id fixture->playsync_manager->startSync("ps_id_2", "TTS"); g_assert(playsync_container.at("TTS").first == PlaySyncState::Prepared); fixture->playsync_manager->startSync("ps_id_1", "TTS"); g_assert(playsync_container.at("TTS").first == PlaySyncState::Synced); g_assert(fixture->playsync_manager_listener->getSyncState("ps_id_1") == PlaySyncState::Prepared); g_assert(fixture->playsync_manager_listener->hasPlayStack("ps_id_1")); // try to start sync not prepared play service id fixture->playsync_manager->startSync("ps_id_2", "Display"); g_assert(playsync_container.at("Display").first == PlaySyncState::Prepared); fixture->playsync_manager->startSync("ps_id_1", "Display"); g_assert(playsync_container.at("Display").first == PlaySyncState::Synced); g_assert(fixture->playsync_manager_listener->getSyncState("ps_id_1") == PlaySyncState::Synced); g_assert(fixture->playsync_manager_listener->hasPlayStack("ps_id_1")); g_assert(fixture->playsync_manager_listener->getSameStateCallCount() == 0); // check whether onSyncState is called just one time when all items are synced fixture->playsync_manager->startSync("ps_id_1", "Display"); g_assert(fixture->playsync_manager_listener->getSyncState("ps_id_1") == PlaySyncState::Synced); g_assert(fixture->playsync_manager_listener->getSameStateCallCount() == 0); } static void test_playsync_manager_append_sync(TestFixture* fixture, gconstpointer ignored) { const auto& playstacks = fixture->playsync_manager->getPlayStacks(); fixture->playsync_manager->addListener("Display", fixture->playsync_manager_listener_snd.get()); /*************************************************************************** * 1) W / "call me" * 2) receive [TTS.Speak, ASR.ExpectSpeech, Session.Set] directives **************************************************************************/ fixture->playsync_manager->prepareSync("ps_id_1", fixture->ndir_expect_speech); const auto& playsync_container = playstacks.at("ps_id_1"); g_assert(playsync_container.at("TTS").first == PlaySyncState::Prepared); g_assert(fixture->playsync_manager_listener->getSyncState("ps_id_1") == PlaySyncState::Prepared); fixture->playsync_manager->startSync("ps_id_1", "TTS"); g_assert(playsync_container.at("TTS").first == PlaySyncState::Synced); g_assert(fixture->playsync_manager_listener->getSyncState("ps_id_1") == PlaySyncState::Synced); /*************************************************************************** * 3) DM / "contact 1" * 4) receive [PhoneCall.SendCandidates] directive * 5) send [PhoneCall.CandidatesListed] event * 6) receive [Display.FullText1, TTS.Speak, ASR.ExpectSpeech] directives **************************************************************************/ auto handle_display([&](PlaySyncState state, DummyExtraInfo&& extra_info) { fixture->playsync_manager->prepareSync("ps_id_1", fixture->ndir_disp_expect_speech); g_assert(playsync_container.at("Display").first == state); fixture->playsync_manager->startSync("ps_id_1", "Display", &extra_info); g_assert(playsync_container.at("Display").first == PlaySyncState::Synced); g_assert(fixture->playsync_manager_listener_snd->getSyncState("ps_id_1") == PlaySyncState::Synced); g_assert(fixture->playsync_manager_listener->getSameStateCallCount() == 0); auto listener_extra_info(fixture->playsync_manager_listener_snd->getExtraData()); g_assert(reinterpret_cast<DummyExtraInfo*>(listener_extra_info)->id == extra_info.id); }); handle_display(PlaySyncState::Appending, { "100" }); handle_display(PlaySyncState::Synced, { "200" }); // display already synced // release sync fixture->playsync_manager->releaseSyncImmediately("ps_id_1", "TTS"); g_assert(playstacks.find("ps_id_1") == playstacks.cend()); g_assert(fixture->playsync_manager_listener->getSyncState("ps_id_1") == PlaySyncState::Released); g_assert(fixture->playsync_manager_listener_snd->getSyncState("ps_id_1") == PlaySyncState::Released); } static void sub_test_playsync_manager_preset_sync(TestFixture* fixture, std::string&& ps_id) { const auto& playstacks = fixture->playsync_manager->getPlayStacks(); /*************************************************************************** * [1] handle in DisplayAgent **************************************************************************/ fixture->playsync_manager->prepareSync(ps_id, fixture->ndir_info_disp); const auto& playsync_container = playstacks.at(ps_id); g_assert(playsync_container.at("TTS").first == PlaySyncState::Prepared); g_assert(playsync_container.at("Display").first == PlaySyncState::Prepared); g_assert(fixture->playsync_manager_listener->getSyncState(ps_id) == PlaySyncState::Prepared); fixture->playsync_manager->startSync(ps_id, "Display"); g_assert(playsync_container.at("Display").first == PlaySyncState::Synced); g_assert(fixture->playsync_manager_listener->getSyncState(ps_id) == PlaySyncState::Prepared); /*************************************************************************** * [2] handle in TTSAgent **************************************************************************/ fixture->playsync_manager->prepareSync(ps_id, fixture->ndir_info_disp); g_assert(playsync_container.at("TTS").first == PlaySyncState::Prepared); g_assert(playsync_container.at("Display").first == PlaySyncState::Synced); g_assert(fixture->playsync_manager_listener->getSyncState(ps_id) == PlaySyncState::Prepared); fixture->playsync_manager->startSync(ps_id, "TTS"); g_assert(playsync_container.at("TTS").first == PlaySyncState::Synced); g_assert(fixture->playsync_manager_listener->getSyncState(ps_id) == PlaySyncState::Synced); } static void sub_test_playsync_manager_preset_media_stacked(TestFixture* fixture) { fixture->playsync_manager->prepareSync("ps_id_1", fixture->ndir_media); fixture->playsync_manager->startSync("ps_id_1", "TTS"); fixture->playsync_manager->startSync("ps_id_1", "AudioPlayer"); g_assert(fixture->playsync_manager_listener->getSyncState("ps_id_1") == PlaySyncState::Synced); fixture->playsync_manager->prepareSync("ps_id_2", fixture->ndir_info_disp); fixture->playsync_manager->startSync("ps_id_2", "TTS"); fixture->playsync_manager->startSync("ps_id_2", "Display"); g_assert(fixture->playsync_manager_listener->getSyncState("ps_id_2") == PlaySyncState::Synced); } static void test_playsync_manager_cancel_sync(TestFixture* fixture, gconstpointer ignored) { sub_test_playsync_manager_preset_sync(fixture, "ps_id_1"); const auto& playsync_container = fixture->playsync_manager->getPlayStacks().at("ps_id_1"); // check invalid parameter fixture->playsync_manager->cancelSync("", "Display"); g_assert(playsync_container.at("Display").first == PlaySyncState::Synced); // check invalid parameter fixture->playsync_manager->cancelSync("ps_id_1", ""); g_assert(playsync_container.at("TTS").first == PlaySyncState::Synced); g_assert(playsync_container.at("Display").first == PlaySyncState::Synced); // try to cancel sync not prepared play service id fixture->playsync_manager->cancelSync("ps_id_2", "Display"); g_assert(playsync_container.at("Display").first == PlaySyncState::Synced); // try to cancel sync not prepared requester fixture->playsync_manager->cancelSync("ps_id_1", "AudioPlayer"); g_assert(playsync_container.find("AudioPlayer") == playsync_container.cend()); fixture->playsync_manager->cancelSync("ps_id_1", "Display"); g_assert(playsync_container.at("TTS").first == PlaySyncState::Synced); g_assert(playsync_container.find("Display") == playsync_container.cend()); g_assert(fixture->playsync_manager_listener->getSyncState("ps_id_1") == PlaySyncState::Synced); } static void test_playsync_manager_release_sync_immediately(TestFixture* fixture, gconstpointer ignored) { sub_test_playsync_manager_preset_sync(fixture, "ps_id_2"); const auto& playstacks = fixture->playsync_manager->getPlayStacks(); const auto& playsync_container = playstacks.at("ps_id_2"); // check invalid parameter fixture->playsync_manager->releaseSyncImmediately("", "TTS"); g_assert(playsync_container.at("TTS").first == PlaySyncState::Synced); // check invalid parameter fixture->playsync_manager->releaseSyncImmediately("ps_id_2", ""); g_assert(playsync_container.at("TTS").first == PlaySyncState::Synced); // try to release sync not prepared play service id fixture->playsync_manager->releaseSyncImmediately("ps_id_1", "TTS"); g_assert(playsync_container.at("TTS").first == PlaySyncState::Synced); fixture->playsync_manager->releaseSyncImmediately("ps_id_2", "TTS"); g_assert(playstacks.find("ps_id_2") == playstacks.cend()); g_assert(fixture->playsync_manager_listener->getSyncState("ps_id_2") == PlaySyncState::Released); } static void test_playsync_manager_release_sync(TestFixture* fixture, gconstpointer ignored) { sub_test_playsync_manager_preset_sync(fixture, "ps_id_1"); const auto& playstacks = fixture->playsync_manager->getPlayStacks(); const auto& playsync_container = playstacks.at("ps_id_1"); // check invalid parameter fixture->playsync_manager->releaseSync("", "TTS"); g_assert(playsync_container.at("TTS").first == PlaySyncState::Synced); // check invalid parameter fixture->playsync_manager->releaseSync("ps_id_1", ""); g_assert(playsync_container.at("TTS").first == PlaySyncState::Synced); // try to release sync not prepared requester fixture->playsync_manager->releaseSync("ps_id_1", "AudioPlayer"); g_assert(playsync_container.find("AudioPlayer") == playsync_container.cend()); fixture->playsync_manager->releaseSync("ps_id_1", "TTS"); g_assert(playsync_container.at("TTS").first == PlaySyncState::Synced); g_assert(playsync_container.at("Display").first == PlaySyncState::Synced); onTimeElapsed(fixture); g_assert(playstacks.find("ps_id_1") == playstacks.cend()); g_assert(fixture->playsync_manager_listener->getSyncState("ps_id_1") == PlaySyncState::Released); // check whether onSyncState is called just one time when all items are released fixture->playsync_manager->releaseSync("ps_id_1", "Display"); onTimeElapsed(fixture); g_assert(fixture->playsync_manager_listener->getSameStateCallCount() == 0); } static void test_playsync_manager_release_sync_later(TestFixture* fixture, gconstpointer ignored) { auto execMediaSync = [&](std::function<void()>&& case_checker) { fixture->playsync_manager->prepareSync("ps_id_1", fixture->ndir_media); fixture->playsync_manager->startSync("ps_id_1", "TTS"); fixture->playsync_manager->startSync("ps_id_1", "AudioPlayer"); g_assert(fixture->playsync_manager_listener->getSyncState("ps_id_1") == PlaySyncState::Synced); fixture->playsync_manager->releaseSyncLater("ps_id_1", "AudioPlayer"); if (case_checker) case_checker(); g_assert(fixture->playsync_manager_listener->getSyncState("ps_id_1") == PlaySyncState::Released); }; // release by sdk execMediaSync([&] { onTimeElapsed(fixture); }); // release by app execMediaSync([&] { fixture->playsync_manager->releaseSyncImmediately("ps_id_1", "AudioPlayer"); }); } static void test_playsync_manager_implicit_release_sync_later(TestFixture* fixture, gconstpointer ignored) { fixture->playsync_manager->prepareSync("ps_id_1", fixture->ndir_media); fixture->playsync_manager->startSync("ps_id_1", "TTS"); fixture->playsync_manager->startSync("ps_id_1", "AudioPlayer"); g_assert(fixture->playsync_manager_listener->getSyncState("ps_id_1") == PlaySyncState::Synced); fixture->playsync_manager->postPoneRelease(); fixture->playsync_manager->continueRelease(); fixture->playsync_manager->releaseSyncLater("ps_id_1", "AudioPlayer"); fixture->playsync_manager->clearHolding(); g_assert(fixture->playsync_manager_listener->getSyncState("ps_id_1") == PlaySyncState::Synced); fixture->playsync_manager->postPoneRelease(); fixture->playsync_manager->continueRelease(); fixture->playsync_manager->releaseSyncLater("ps_id_1", "AudioPlayer"); onTimeElapsed(fixture); g_assert(fixture->playsync_manager_listener->getSyncState("ps_id_1") == PlaySyncState::Released); } static void test_playsync_manager_release_sync_later_in_stack_condition(TestFixture* fixture, gconstpointer ignored) { auto execMediaStackedSync = [&](std::function<void()> case_checker) { fixture->playsync_manager->prepareSync("ps_id_1", fixture->ndir_media); fixture->playsync_manager->startSync("ps_id_1", "TTS"); fixture->playsync_manager->startSync("ps_id_1", "AudioPlayer"); g_assert(fixture->playsync_manager_listener->getSyncState("ps_id_1") == PlaySyncState::Synced); fixture->playsync_manager->releaseSyncLater("ps_id_1", "AudioPlayer"); fixture->playsync_manager->prepareSync("ps_id_2", fixture->ndir_info_disp); fixture->playsync_manager->startSync("ps_id_2", "TTS"); fixture->playsync_manager->startSync("ps_id_2", "Display"); g_assert(fixture->playsync_manager_listener->getSyncState("ps_id_2") == PlaySyncState::Synced); if (case_checker) case_checker(); g_assert(fixture->playsync_manager_listener->getSyncState("ps_id_1") == PlaySyncState::Synced); onTimeElapsed(fixture); g_assert(fixture->playsync_manager_listener->getSyncState("ps_id_1") == PlaySyncState::Released); }; // close by sdk execMediaStackedSync([&] { fixture->playsync_manager->releaseSync("ps_id_2", "TTS"); g_assert(fixture->playsync_manager_listener->getSyncState("ps_id_2") == PlaySyncState::Released); }); // close by app execMediaStackedSync([&] { fixture->playsync_manager->releaseSyncImmediately("ps_id_2", "TTS"); g_assert(fixture->playsync_manager_listener->getSyncState("ps_id_2") == PlaySyncState::Released); }); // stop rendering timer before release execMediaStackedSync([&] { fixture->playsync_manager->postPoneRelease(); fixture->playsync_manager->stopHolding(); fixture->playsync_manager->releaseSync("ps_id_2", "TTS"); g_assert(fixture->playsync_manager_listener->getSyncState("ps_id_2") == PlaySyncState::Synced); }); } static void test_playsync_manager_release_sync_unconditionally(TestFixture* fixture, gconstpointer ignored) { sub_test_playsync_manager_preset_media_stacked(fixture); const auto& playstacks = fixture->playsync_manager->getPlayStacks(); g_assert(fixture->playsync_manager_listener->getSyncState("ps_id_1") == PlaySyncState::Synced); g_assert(fixture->playsync_manager_listener->getSyncState("ps_id_2") == PlaySyncState::Synced); g_assert(!playstacks.empty()); fixture->playsync_manager->releaseSyncUnconditionally(); g_assert(fixture->playsync_manager_listener->getSyncState("ps_id_1") == PlaySyncState::Released); g_assert(fixture->playsync_manager_listener->getSyncState("ps_id_2") == PlaySyncState::Released); g_assert(playstacks.empty()); } static void test_playsync_manager_normal_case(TestFixture* fixture, gconstpointer ignored) { sub_test_playsync_manager_preset_sync(fixture, "ps_id_1"); fixture->playsync_manager->releaseSync("ps_id_1", "TTS"); onTimeElapsed(fixture); g_assert(fixture->playsync_manager_listener->getSyncState("ps_id_1") == PlaySyncState::Released); } static void test_playsync_manager_stop_case(TestFixture* fixture, gconstpointer ignored) { sub_test_playsync_manager_preset_sync(fixture, "ps_id_1"); fixture->playsync_manager->releaseSyncImmediately("ps_id_1", "TTS"); g_assert(fixture->playsync_manager_listener->getSyncState("ps_id_1") == PlaySyncState::Released); } static void test_playsync_manager_ignore_render_case(TestFixture* fixture, gconstpointer ignored) { sub_test_playsync_manager_preset_sync(fixture, "ps_id_1"); const auto& playstacks = fixture->playsync_manager->getPlayStacks(); const auto& playsync_container = playstacks.at("ps_id_1"); fixture->playsync_manager->cancelSync("ps_id_1", "Display"); g_assert(playsync_container.at("TTS").first == PlaySyncState::Synced); g_assert(playsync_container.find("Display") == playsync_container.cend()); g_assert(fixture->playsync_manager_listener->getSyncState("ps_id_1") == PlaySyncState::Synced); fixture->playsync_manager->releaseSync("ps_id_1", "TTS"); onTimeElapsed(fixture); g_assert(fixture->playsync_manager_listener->getSyncState("ps_id_1") == PlaySyncState::Released); } static void test_playsync_manager_handle_info_layer(TestFixture* fixture, gconstpointer ignored) { fixture->playsync_manager->addListener("Display", fixture->playsync_manager_listener_snd.get()); /*************************************************************************** * [1] handle in DisplayAgent **************************************************************************/ fixture->playsync_manager->prepareSync("ps_id_1", fixture->ndir_info_disp); fixture->dummy_extra_data->id = "100"; fixture->playsync_manager->startSync("ps_id_1", "Display", fixture->dummy_extra_data); g_assert(fixture->playsync_manager_listener->getSyncState("ps_id_1") == PlaySyncState::Prepared); /*************************************************************************** * [2] handle in TTSAgent **************************************************************************/ fixture->playsync_manager->prepareSync("ps_id_1", fixture->ndir_info_disp); fixture->playsync_manager->startSync("ps_id_1", "TTS"); g_assert(fixture->playsync_manager_listener->getSyncState("ps_id_1") == PlaySyncState::Synced); g_assert(!fixture->playsync_manager_listener->getExtraData()); auto extra_data = fixture->playsync_manager_listener_snd->getExtraData(); g_assert(extra_data); g_assert(reinterpret_cast<DummyExtraInfo*>(extra_data)->id == "100"); fixture->playsync_manager->releaseSync("ps_id_1", "TTS"); onTimeElapsed(fixture); g_assert(fixture->playsync_manager_listener->getSyncState("ps_id_1") == PlaySyncState::Released); } static void test_playsync_manager_playstack_holding(TestFixture* fixture, gconstpointer ignored) { fixture->playsync_manager->prepareSync("ps_id_1", fixture->ndir_info_disp); fixture->playsync_manager->startSync("ps_id_1", "Display"); fixture->playsync_manager->startSync("ps_id_1", "TTS"); g_assert(fixture->playsync_manager_listener->getSyncState("ps_id_1") == PlaySyncState::Synced); fixture->playsync_manager->releaseSync("ps_id_1", "TTS"); fixture->playsync_manager->stopHolding(); g_assert(fixture->playsync_manager_listener->getSyncState("ps_id_1") == PlaySyncState::Synced); fixture->playsync_manager->resetHolding(); onTimeElapsed(fixture); g_assert(fixture->playsync_manager_listener->getSyncState("ps_id_1") == PlaySyncState::Released); } static void test_playsync_manager_adjust_playstack_hold_time(TestFixture* fixture, gconstpointer ignored) { const unsigned int DEFAULT_HOLD_TIME_SEC = 7; const unsigned int ADJUST_HOLD_TIME_SEC = 15; // check validation fixture->playsync_manager->adjustPlayStackHoldTime(-1); g_assert(fixture->playsync_manager->getPlayStackHoldTime() == DEFAULT_HOLD_TIME_SEC); fixture->playsync_manager->adjustPlayStackHoldTime(0); g_assert(fixture->playsync_manager->getPlayStackHoldTime() == DEFAULT_HOLD_TIME_SEC); auto execSyncProcess([&](std::string&& ps_id, unsigned int hold_time) { const auto& playstacks = fixture->playsync_manager->getPlayStacks(); // prepare fixture->playsync_manager->prepareSync(ps_id, fixture->ndir_info_disp); g_assert(fixture->playsync_manager_listener->getSyncState(ps_id) == PlaySyncState::Prepared); // adjust hold time if (hold_time != DEFAULT_HOLD_TIME_SEC) { fixture->playsync_manager->adjustPlayStackHoldTime(hold_time); g_assert(fixture->playsync_manager->getPlayStackHoldTime() == hold_time); } // start fixture->playsync_manager->startSync(ps_id, "Display"); fixture->playsync_manager->startSync(ps_id, "TTS"); g_assert(fixture->playsync_manager_listener->getSyncState(ps_id) == PlaySyncState::Synced); // release fixture->playsync_manager->releaseSync(ps_id, "Display"); g_assert(fixture->fake_timer->getPlayStackHoldTime() == hold_time); onTimeElapsed(fixture); g_assert(playstacks.find(ps_id) == playstacks.cend()); g_assert(fixture->playsync_manager_listener->getSyncState(ps_id) == PlaySyncState::Released); }); execSyncProcess("ps_id_1", ADJUST_HOLD_TIME_SEC); execSyncProcess("ps_id_2", DEFAULT_HOLD_TIME_SEC); } static void test_playsync_manager_set_default_playstack_hold_time(TestFixture* fixture, gconstpointer ignored) { const unsigned int DEFAULT_HOLD_TIME_SEC = 7; const unsigned int NEW_DEFAULT_HOLD_TIME_SEC = 3; const unsigned int ADJUST_HOLD_TIME_SEC = 15; // check validation g_assert(fixture->playsync_manager->getPlayStackHoldTime() == DEFAULT_HOLD_TIME_SEC); fixture->playsync_manager->setDefaultPlayStackHoldTime(-1); g_assert(fixture->playsync_manager->getPlayStackHoldTime() == DEFAULT_HOLD_TIME_SEC); fixture->playsync_manager->setDefaultPlayStackHoldTime(0); g_assert(fixture->playsync_manager->getPlayStackHoldTime() == DEFAULT_HOLD_TIME_SEC); // set new default playstack hold time fixture->playsync_manager->setDefaultPlayStackHoldTime(NEW_DEFAULT_HOLD_TIME_SEC); g_assert(fixture->playsync_manager->getPlayStackHoldTime() == NEW_DEFAULT_HOLD_TIME_SEC); // prepare fixture->playsync_manager->prepareSync("ps_id_1", fixture->ndir_info_disp); g_assert(fixture->playsync_manager_listener->getSyncState("ps_id_1") == PlaySyncState::Prepared); // adjust hold time fixture->playsync_manager->adjustPlayStackHoldTime(ADJUST_HOLD_TIME_SEC); g_assert(fixture->playsync_manager->getPlayStackHoldTime() == ADJUST_HOLD_TIME_SEC); // start fixture->playsync_manager->startSync("ps_id_1", "Display"); fixture->playsync_manager->startSync("ps_id_1", "TTS"); g_assert(fixture->playsync_manager_listener->getSyncState("ps_id_1") == PlaySyncState::Synced); // release fixture->playsync_manager->releaseSync("ps_id_1", "Display"); g_assert(fixture->fake_timer->getPlayStackHoldTime() == ADJUST_HOLD_TIME_SEC); onTimeElapsed(fixture); g_assert(fixture->playsync_manager_listener->getSyncState("ps_id_1") == PlaySyncState::Released); // reset to default hold time g_assert(fixture->playsync_manager->getPlayStackHoldTime() == NEW_DEFAULT_HOLD_TIME_SEC); } static void test_playsync_manager_restart_playstack_holding(TestFixture* fixture, gconstpointer ignored) { sub_test_playsync_manager_preset_sync(fixture, "ps_id_1"); const auto& playstacks = fixture->playsync_manager->getPlayStacks(); auto checkSynced([&] { const auto& playsync_container = playstacks.at("ps_id_1"); g_assert(playsync_container.at("Display").first == PlaySyncState::Synced); g_assert(playsync_container.at("TTS").first == PlaySyncState::Synced); g_assert(fixture->playsync_manager_listener->getSyncState("ps_id_1") == PlaySyncState::Synced); }); // try to release fixture->playsync_manager->releaseSync("ps_id_1", "Display"); checkSynced(); // reset holding g_assert(!fixture->fake_timer->isRestarted()); fixture->playsync_manager->restartHolding(); g_assert(fixture->fake_timer->isRestarted()); checkSynced(); // release finally onTimeElapsed(fixture); g_assert(playstacks.find("ps_id_1") == playstacks.cend()); g_assert(fixture->playsync_manager_listener->getSyncState("ps_id_1") == PlaySyncState::Released); } static void test_playsync_manager_stop_playstack_holding_after_timer(TestFixture* fixture, gconstpointer ignored) { sub_test_playsync_manager_preset_sync(fixture, "ps_id_1"); const auto& playstacks = fixture->playsync_manager->getPlayStacks(); // try to release fixture->playsync_manager->releaseSync("ps_id_1", "Display"); g_assert(fixture->playsync_manager_listener->getSyncState("ps_id_1") == PlaySyncState::Synced); // stop playstack holding fixture->playsync_manager->clearHolding(); onTimeElapsed(fixture); g_assert(fixture->playsync_manager_listener->getSyncState("ps_id_1") == PlaySyncState::Synced); // release by another dialog sub_test_playsync_manager_preset_sync(fixture, "ps_id_2"); g_assert(playstacks.find("ps_id_1") == playstacks.cend()); g_assert(fixture->playsync_manager_listener->getSyncState("ps_id_1") == PlaySyncState::Released); } static void test_playsync_manager_stop_playstack_holding_before_timer(TestFixture* fixture, gconstpointer ignored) { const auto& playstacks = fixture->playsync_manager->getPlayStacks(); auto setupStopHolding([&](bool is_media_stacked) { is_media_stacked ? sub_test_playsync_manager_preset_media_stacked(fixture) : sub_test_playsync_manager_preset_sync(fixture, "ps_id_2"); // stop playstack holding fixture->playsync_manager->postPoneRelease(); fixture->playsync_manager->releaseSync("ps_id_2", "Display"); onTimeElapsed(fixture); g_assert(fixture->playsync_manager_listener->getSyncState("ps_id_2") == PlaySyncState::Synced); }); for (const auto& type : { false, true }) { // false: info only, true: media stack // release by user setupStopHolding(type); fixture->playsync_manager->continueRelease(); fixture->playsync_manager->releaseSyncImmediately("ps_id_2", "Display"); g_assert(playstacks.find("ps_id_2") == playstacks.cend()); g_assert(fixture->playsync_manager_listener->getSyncState("ps_id_2") == PlaySyncState::Released); // release by another dialog setupStopHolding(type); sub_test_playsync_manager_preset_sync(fixture, "ps_id_3"); g_assert(playstacks.find("ps_id_2") == playstacks.cend()); g_assert(fixture->playsync_manager_listener->getSyncState("ps_id_2") == PlaySyncState::Released); } } static void test_playsync_manager_check_playstack_layer(TestFixture* fixture, gconstpointer ignored) { fixture->playsync_manager->prepareSync("ps_id_1", fixture->ndir_media); fixture->playsync_manager->startSync("ps_id_1", "TTS"); g_assert(!fixture->playsync_manager->hasActivity("", PlayStackActivity::Media)); g_assert(fixture->playsync_manager->hasActivity("ps_id_1", PlayStackActivity::Media)); g_assert(!fixture->playsync_manager->hasActivity("ps_id_1", PlayStackActivity::TTS)); } static void test_playsync_manager_recv_callback_only_participants(TestFixture* fixture, gconstpointer ignored) { fixture->playsync_manager->addListener("AudioPlayer", fixture->playsync_manager_listener_snd.get()); g_assert(fixture->playsync_manager->getListenerCount() == 2); fixture->playsync_manager->prepareSync("ps_id_1", fixture->ndir_info_disp); fixture->playsync_manager->startSync("ps_id_1", "TTS"); fixture->playsync_manager->startSync("ps_id_1", "Display"); g_assert(fixture->playsync_manager_listener->getSyncState("ps_id_1") == PlaySyncState::Synced); g_assert(fixture->playsync_manager_listener_snd->getSyncState("ps_id_1") == PlaySyncState::None); } static void test_playsync_manager_media_stacked_case(TestFixture* fixture, gconstpointer ignored) { sub_test_playsync_manager_preset_media_stacked(fixture); // It released TTS activity immediately if the media is stacked fixture->playsync_manager->releaseSync("ps_id_2", "TTS"); g_assert(fixture->playsync_manager_listener->getSyncState("ps_id_1") == PlaySyncState::Synced); g_assert(fixture->playsync_manager_listener->getSyncState("ps_id_2") == PlaySyncState::Released); fixture->playsync_manager->releaseSync("ps_id_1", "AudioPlayer"); onTimeElapsed(fixture); g_assert(fixture->playsync_manager_listener->getSyncState("ps_id_1") == PlaySyncState::Released); } static void test_playsync_manager_postpone_release(TestFixture* fixture, gconstpointer ignored) { sub_test_playsync_manager_preset_media_stacked(fixture); fixture->playsync_manager->postPoneRelease(); fixture->playsync_manager->releaseSync("ps_id_2", "TTS"); g_assert(fixture->playsync_manager_listener->getSyncState("ps_id_2") == PlaySyncState::Synced); fixture->playsync_manager->continueRelease(); g_assert(fixture->playsync_manager_listener->getSyncState("ps_id_2") == PlaySyncState::Released); } static void test_playsync_manager_check_to_process_previous_dialog(TestFixture* fixture, gconstpointer ignored) { fixture->playsync_manager->prepareSync("ps_id_1", fixture->ndir_media); fixture->playsync_manager->startSync("ps_id_1", "TTS"); fixture->playsync_manager->startSync("ps_id_1", "AudioPlayer"); g_assert(fixture->playsync_manager_listener->getSyncState("ps_id_1") == PlaySyncState::Synced); g_assert(fixture->playsync_manager->isConditionToHandlePrevDialog(fixture->ndir_media, fixture->ndir_info_disp)); g_assert(!fixture->playsync_manager->isConditionToHandlePrevDialog(fixture->ndir_expect_speech, fixture->ndir_info_disp)); } static void test_playsync_manager_refresh_extra_data(TestFixture* fixture, gconstpointer ignored) { fixture->playsync_manager->addListener("AudioPlayer", fixture->playsync_manager_listener_snd.get()); fixture->dummy_extra_data->id = "100"; fixture->playsync_manager->prepareSync("ps_id_1", fixture->ndir_media); fixture->playsync_manager->startSync("ps_id_1", "TTS"); fixture->playsync_manager->startSync("ps_id_1", "AudioPlayer", fixture->dummy_extra_data); g_assert(fixture->playsync_manager_listener->getSyncState("ps_id_1") == PlaySyncState::Synced); g_assert(reinterpret_cast<DummyExtraInfo*>(fixture->playsync_manager_listener_snd->getExtraData())->id == "100"); g_assert(!fixture->playsync_manager_listener->getExtraData()); fixture->dummy_extra_data_snd->id = "200"; fixture->playsync_manager->prepareSync("ps_id_1", fixture->ndir_media); fixture->playsync_manager->startSync("ps_id_1", "AudioPlayer", fixture->dummy_extra_data_snd); g_assert(fixture->playsync_manager_listener->getSyncState("ps_id_1") == PlaySyncState::Synced); g_assert(reinterpret_cast<DummyExtraInfo*>(fixture->playsync_manager_listener_snd->getExtraData())->id == "200"); g_assert(!fixture->playsync_manager_listener->getExtraData()); } static void test_playsync_manager_check_expect_speech(TestFixture* fixture, gconstpointer ignored) { fixture->playsync_manager->prepareSync("ps_id_1", fixture->ndir_info_disp); g_assert(fixture->playsync_manager_listener->getSyncState("ps_id_1") == PlaySyncState::Prepared); g_assert(!fixture->ic_manager_listener->hasMultiTurn()); fixture->playsync_manager->prepareSync("ps_id_2", fixture->ndir_expect_speech); g_assert(fixture->playsync_manager_listener->getSyncState("ps_id_2") == PlaySyncState::Prepared); g_assert(fixture->ic_manager_listener->hasMultiTurn()); } static void test_playsync_manager_reset(TestFixture* fixture, gconstpointer ignored) { sub_test_playsync_manager_preset_sync(fixture, "ps_id_1"); const auto& playstacks = fixture->playsync_manager->getPlayStacks(); g_assert(!playstacks.empty()); g_assert(!fixture->playsync_manager->getAllPlayStackItems().empty()); g_assert(!fixture->playsync_manager->hasPostPoneRelease()); fixture->playsync_manager->postPoneRelease(); fixture->playsync_manager->releaseSync("ps_id_1", "TTS"); g_assert(fixture->playsync_manager->hasPostPoneRelease()); fixture->playsync_manager->reset(); g_assert(playstacks.empty()); g_assert(fixture->playsync_manager->getAllPlayStackItems().empty()); g_assert(!fixture->playsync_manager->hasPostPoneRelease()); g_assert(fixture->playsync_manager->getListenerCount() == 1); } static void test_playsync_manager_register_capability_for_sync(TestFixture* fixture, gconstpointer ignored) { fixture->playsync_manager->addListener("Alerts", fixture->playsync_manager_listener_snd.get()); fixture->playsync_manager->registerCapabilityForSync("Alerts"); fixture->playsync_manager->prepareSync("ps_id_1", fixture->ndir_alerts); g_assert(fixture->playsync_manager_listener_snd->getSyncState("ps_id_1") == PlaySyncState::Prepared); fixture->playsync_manager->startSync("ps_id_1", "Alerts"); g_assert(fixture->playsync_manager_listener_snd->getSyncState("ps_id_1") == PlaySyncState::Synced); fixture->playsync_manager->releaseSyncImmediately("ps_id_1", "Alerts"); g_assert(fixture->playsync_manager_listener_snd->getSyncState("ps_id_1") == PlaySyncState::Released); } static void test_playsync_manager_check_next_playstack(TestFixture* fixture, gconstpointer ignored) { fixture->playsync_manager_listener->setHookInonSyncState([&]() { g_assert(fixture->playsync_manager->hasNextPlayStack()); }); fixture->playsync_manager->prepareSync("ps_id_1", fixture->ndir_info_disp); g_assert(fixture->playsync_manager_listener->getSyncState("ps_id_1") == PlaySyncState::Prepared); fixture->playsync_manager->prepareSync("ps_id_2", fixture->ndir_info_disp); g_assert(fixture->playsync_manager_listener->getSyncState("ps_id_2") == PlaySyncState::Prepared); g_assert(!fixture->playsync_manager->hasNextPlayStack()); } static void test_playsync_manager_check_on_stack_changed_callback(TestFixture* fixture, gconstpointer ignored) { sub_test_playsync_manager_preset_sync(fixture, "ps_id_1"); const auto& playstacks(fixture->playsync_manager_listener->getPlaystacks()); g_assert(playstacks.find("ps_id_1") != playstacks.end()); fixture->playsync_manager->releaseSyncImmediately("ps_id_1", "TTS"); g_assert(playstacks.find("ps_id_1") == playstacks.end()); } static void test_playsync_manager_clear(TestFixture* fixture, gconstpointer ignored) { sub_test_playsync_manager_preset_media_stacked(fixture); const auto& playstacks = fixture->playsync_manager->getPlayStacks(); g_assert(!playstacks.empty()); g_assert(!fixture->playsync_manager->getAllPlayStackItems().empty()); g_assert(!fixture->playsync_manager->hasPostPoneRelease()); fixture->playsync_manager->postPoneRelease(); g_assert(fixture->playsync_manager->hasPostPoneRelease()); fixture->playsync_manager->clear(); g_assert(playstacks.empty()); g_assert(fixture->playsync_manager->getAllPlayStackItems().empty()); g_assert(!fixture->playsync_manager->hasPostPoneRelease()); } int main(int argc, char* argv[]) { #if !GLIB_CHECK_VERSION(2, 36, 0) g_type_init(); #endif g_test_init(&argc, &argv, (void*)NULL); g_log_set_always_fatal((GLogLevelFlags)G_LOG_FATAL_MASK); G_TEST_ADD_FUNC("/core/PlaySyncManager/listener", test_playsync_manager_listener); G_TEST_ADD_FUNC("/core/PlaySyncManager/prepareSync", test_playsync_manager_prepare_sync); G_TEST_ADD_FUNC("/core/PlaySyncManager/startSync", test_playsync_manager_start_sync); G_TEST_ADD_FUNC("/core/PlaySyncManager/appendSync", test_playsync_manager_append_sync); G_TEST_ADD_FUNC("/core/PlaySyncManager/cancelSync", test_playsync_manager_cancel_sync); G_TEST_ADD_FUNC("/core/PlaySyncManager/releaseSyncImmediately", test_playsync_manager_release_sync_immediately); G_TEST_ADD_FUNC("/core/PlaySyncManager/releaseSync", test_playsync_manager_release_sync); G_TEST_ADD_FUNC("/core/PlaySyncManager/releaseSyncLater", test_playsync_manager_release_sync_later); G_TEST_ADD_FUNC("/core/PlaySyncManager/implicitReleaseSyncLater", test_playsync_manager_implicit_release_sync_later); G_TEST_ADD_FUNC("/core/PlaySyncManager/releaseSyncLaterInStackCondition", test_playsync_manager_release_sync_later_in_stack_condition); G_TEST_ADD_FUNC("/core/PlaySyncManager/releaseSyncUnconditionally", test_playsync_manager_release_sync_unconditionally); G_TEST_ADD_FUNC("/core/PlaySyncManager/normalCase", test_playsync_manager_normal_case); G_TEST_ADD_FUNC("/core/PlaySyncManager/stopCase", test_playsync_manager_stop_case); G_TEST_ADD_FUNC("/core/PlaySyncManager/ignoreRenderCase", test_playsync_manager_ignore_render_case); G_TEST_ADD_FUNC("/core/PlaySyncManager/handleInfoLayer", test_playsync_manager_handle_info_layer); G_TEST_ADD_FUNC("/core/PlaySyncManager/playstackHolding", test_playsync_manager_playstack_holding); G_TEST_ADD_FUNC("/core/PlaySyncManager/adjustPlaystackHoldTime", test_playsync_manager_adjust_playstack_hold_time); G_TEST_ADD_FUNC("/core/PlaySyncManager/setDefaultPlaystackHoldTime", test_playsync_manager_set_default_playstack_hold_time); G_TEST_ADD_FUNC("/core/PlaySyncManager/restartPlaystackHolding", test_playsync_manager_restart_playstack_holding); G_TEST_ADD_FUNC("/core/PlaySyncManager/stopPlaystackHoldingAfterTimer", test_playsync_manager_stop_playstack_holding_after_timer); G_TEST_ADD_FUNC("/core/PlaySyncManager/stopPlaystackHoldingBeforeTimer", test_playsync_manager_stop_playstack_holding_before_timer); G_TEST_ADD_FUNC("/core/PlaySyncManager/checkPlayStackActivity", test_playsync_manager_check_playstack_layer); G_TEST_ADD_FUNC("/core/PlaySyncManager/recvCallbackOnlyParticipants", test_playsync_manager_recv_callback_only_participants); G_TEST_ADD_FUNC("/core/PlaySyncManager/mediaStackedCase", test_playsync_manager_media_stacked_case); G_TEST_ADD_FUNC("/core/PlaySyncManager/postPoneRelease", test_playsync_manager_postpone_release); G_TEST_ADD_FUNC("/core/PlaySyncManager/checkToProcessPreviousDialog", test_playsync_manager_check_to_process_previous_dialog); G_TEST_ADD_FUNC("/core/PlaySyncManager/refreshExtraData", test_playsync_manager_refresh_extra_data); G_TEST_ADD_FUNC("/core/PlaySyncManager/checkExpectSpeech", test_playsync_manager_check_expect_speech); G_TEST_ADD_FUNC("/core/PlaySyncManager/reset", test_playsync_manager_reset); G_TEST_ADD_FUNC("/core/PlaySyncManager/registerCapabilityForSync", test_playsync_manager_register_capability_for_sync); G_TEST_ADD_FUNC("/core/PlaySyncManager/checkNextPlayStack", test_playsync_manager_check_next_playstack); G_TEST_ADD_FUNC("/core/PlaySyncManager/checkOnStackChangedCallback", test_playsync_manager_check_on_stack_changed_callback); G_TEST_ADD_FUNC("/core/PlaySyncManager/clear", test_playsync_manager_clear); return g_test_run(); }
44.625654
139
0.729356
JeanTracker
788e579c87b4ffe81350f00523e8d3862b21385c
582
cpp
C++
24_dynamic_1/6_largest_sum_subarray.cpp
meyash/dust
8f90d7f9cc42f61193c737cde14e9c4bb32884b4
[ "MIT" ]
1
2020-09-30T10:36:06.000Z
2020-09-30T10:36:06.000Z
24_dynamic_1/6_largest_sum_subarray.cpp
meyash/dust
8f90d7f9cc42f61193c737cde14e9c4bb32884b4
[ "MIT" ]
null
null
null
24_dynamic_1/6_largest_sum_subarray.cpp
meyash/dust
8f90d7f9cc42f61193c737cde14e9c4bb32884b4
[ "MIT" ]
null
null
null
#include<bits/stdc++.h> using namespace std; typedef long long ll; // this is kadane's algo // sample // 8 // -5 6 7 -20 3 5 8 -9 // output // 16 int kadane(int *a,int n){ int current_sum=0; int best_sum=0; for(int i=0;i<n;i++){ current_sum+=a[i]; if(best_sum<current_sum){ best_sum=current_sum; } if(current_sum<0){ current_sum=0; } } return best_sum; } int main(){ int n; cin>>n; int *a=new int[n]; for(int i=0;i<n;i++){ cin>>a[i]; } cout<<kadane(a,n)<<endl; }
17.117647
34
0.510309
meyash
788e852c032f48a781173c36fec2989d335d6a8e
22,555
cpp
C++
src/api/test/TestQuery.cpp
samprasyork/nebula
7184c4e76ef0cb65ca3dc4b6d98ca1ac66943928
[ "Apache-2.0" ]
null
null
null
src/api/test/TestQuery.cpp
samprasyork/nebula
7184c4e76ef0cb65ca3dc4b6d98ca1ac66943928
[ "Apache-2.0" ]
null
null
null
src/api/test/TestQuery.cpp
samprasyork/nebula
7184c4e76ef0cb65ca3dc4b6d98ca1ac66943928
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2017-present Shawn Cao * * 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 <fmt/format.h> #include <glog/logging.h> #include <gmock/gmock.h> #include <gtest/gtest.h> #include "Test.hpp" #include "api/dsl/Dsl.h" #include "api/dsl/Expressions.h" #include "common/Cursor.h" #include "common/Errors.h" #include "common/Evidence.h" #include "common/Folly.h" #include "common/Likely.h" #include "common/Memory.h" #include "execution/ExecutionPlan.h" #include "execution/core/ServerExecutor.h" #include "execution/meta/TableService.h" #include "meta/NBlock.h" #include "surface/DataSurface.h" #include "surface/MockSurface.h" #include "type/Serde.h" namespace nebula { namespace api { namespace test { using namespace nebula::api::dsl; using nebula::common::Cursor; using nebula::common::Evidence; using nebula::execution::QueryContext; using nebula::execution::core::ServerExecutor; using nebula::execution::meta::TableService; using nebula::surface::RowData; using nebula::type::Schema; using nebula::type::TypeSerializer; TEST(ApiTest, TestMultipleBlocks) { auto data = genData(); // query this table auto ms = TableService::singleton(); auto tableName = std::get<0>(data); auto start = std::get<1>(data); auto end = std::get<2>(data); auto query = table(tableName, ms) .where(col("_time_") > start && col("_time_") < end && like(col("event"), "NN%")) .select( col("event"), count(col("value")).as("total")) .groupby({ 1 }) .sortby({ 2 }, SortType::DESC) .limit(10); // compile the query into an execution plan auto plan = query.compile(QueryContext::def()); plan->setWindow({ start, end }); // print out the plan through logging plan->display(); nebula::common::Evidence::Duration tick; folly::CPUThreadPoolExecutor pool{ 8 }; // pass the query plan to a server to execute - usually it is itself auto result = ServerExecutor(nebula::meta::NNode::local().toString()).execute(pool, *plan); // query should have results EXPECT_GT(result->size(), 0); // print out result; LOG(INFO) << "----------------------------------------------------------------"; LOG(INFO) << "Get Results With Rows: " << result->size() << " using " << tick.elapsedMs() << " ms"; LOG(INFO) << fmt::format("col: {0:20} | {1:12}", "event", "Total"); while (result->hasNext()) { const auto& row = result->next(); LOG(INFO) << fmt::format("row: {0:20} | {1:12}", row.readString("event"), row.readInt("total")); } } TEST(ApiTest, TestStringEqEmpty) { auto data = genData(); // query this table auto ms = TableService::singleton(); auto tableName = std::get<0>(data); auto start = std::get<1>(data); auto end = std::get<2>(data); auto query = table(tableName, ms) .where(col("_time_") > start && col("_time_") < end && col("event") == "") .select( col("event"), count(col("event")).as("total")) .groupby({ 1 }) .sortby({ 2 }, SortType::DESC) .limit(10); // compile the query into an execution plan auto plan = query.compile(QueryContext::def()); plan->setWindow({ start, end }); // print out the plan through logging plan->display(); nebula::common::Evidence::Duration tick; // pass the query plan to a server to execute - usually it is itself folly::CPUThreadPoolExecutor pool{ 8 }; auto result = ServerExecutor(nebula::meta::NNode::local().toString()).execute(pool, *plan); // query should have results EXPECT_EQ(result->size(), 1); // print out result; LOG(INFO) << "----------------------------------------------------------------"; LOG(INFO) << "Get Results With Rows: " << result->size() << " using " << tick.elapsedMs() << " ms"; LOG(INFO) << fmt::format("col: {0:20} | {1:12}", "event", "Total"); while (result->hasNext()) { const auto& row = result->next(); LOG(INFO) << fmt::format("row: {0:20} | {1:12}", row.readString("event"), row.readInt("total")); } } TEST(ApiTest, TestBlockSkipByBloomfilter) { auto data = genData(); // we know we don't have an id larger than this number, so the query should skip all blocks auto ms = TableService::singleton(); auto tableName = std::get<0>(data); auto start = std::get<1>(data); auto end = std::get<2>(data); auto query = table(tableName, ms) .where(col("_time_") > start && col("_time_") < end && col("id") == 8989) .select( col("event"), count(col("value")).as("total")) .groupby({ 1 }) .sortby({ 2 }, SortType::DESC) .limit(10); // compile the query into an execution plan auto plan = query.compile(QueryContext::def()); plan->setWindow({ start, end }); // print out the plan through logging plan->display(); nebula::common::Evidence::Duration tick; // pass the query plan to a server to execute - usually it is itself folly::CPUThreadPoolExecutor pool{ 8 }; auto result = ServerExecutor(nebula::meta::NNode::local().toString()).execute(pool, *plan); // query should have results EXPECT_EQ(result->size(), 1); } TEST(ApiTest, TestBlockSkipByPartitionColumn) { auto data = genData(); // we know we don't have an id larger than this number, so the query should skip all blocks auto ms = TableService::singleton(); auto tableName = std::get<0>(data); auto start = std::get<1>(data); auto end = std::get<2>(data); auto query = table(tableName, ms) .where(col("_time_") > start && col("_time_") < end && col("tag") == "b") .select( col("tag"), count(col("value")).as("total")) .groupby({ 1 }) .sortby({ 2 }, SortType::DESC) .limit(10); // compile the query into an execution plan auto plan = query.compile(QueryContext::def()); plan->setWindow({ start, end }); // print out the plan through logging plan->display(); nebula::common::Evidence::Duration tick; // pass the query plan to a server to execute - usually it is itself folly::CPUThreadPoolExecutor pool{ 8 }; auto result = ServerExecutor(nebula::meta::NNode::local().toString()).execute(pool, *plan); // query should have results EXPECT_EQ(result->size(), 1); } TEST(ApiTest, TestAvgAggregation) { auto data = genData(); // we know we don't have an id larger than this number, so the query should skip all blocks auto ms = TableService::singleton(); auto tableName = std::get<0>(data); auto start = std::get<1>(data); auto end = std::get<2>(data); auto query = table(tableName, ms) .where(col("_time_") > start && col("_time_") < end) .select( col("event"), avg(col("value")).as("avg"), sum(col("value")).as("sum"), sum(col("stamp")).as("sint128"), count(1).as("count"), avg(col("weight")).as("davg")) .groupby({ 1 }) .sortby({ 2 }, SortType::DESC) .limit(10); // compile the query into an execution plan auto plan = query.compile(QueryContext::def()); plan->setWindow({ start, end }); // print out the plan through logging plan->display(); nebula::common::Evidence::Duration tick; // pass the query plan to a server to execute - usually it is itself folly::CPUThreadPoolExecutor pool{ 8 }; auto result = ServerExecutor(nebula::meta::NNode::local().toString()).execute(pool, *plan); // query should have results EXPECT_EQ(result->size(), 10); // print out result; LOG(INFO) << "----------------------------------------------------------------"; LOG(INFO) << "Get Results With Rows: " << result->size() << " using " << tick.elapsedMs() << " ms"; LOG(INFO) << fmt::format("col: {0:20} | {1:12} | {2:20} | {3:12} | {4:20} | {5:12}", "event", "v.avg", "w.avg", "v.sum", "s.sum", "v.count"); while (result->hasNext()) { const auto& row = result->next(); LOG(INFO) << fmt::format("row: {0:20} | {1:12} | {2:20} | {3:12} | {4:20} | {5:12}", row.readString("event"), row.readByte("avg"), row.readDouble("davg"), row.readLong("sum"), row.readLong("sint128"), row.readLong("count")); } } TEST(ApiTest, TestPercentile) { auto data = genData(); // query this table auto ms = TableService::singleton(); auto tableName = std::get<0>(data); auto start = std::get<1>(data); auto end = std::get<2>(data); auto query = table(tableName, ms) .where(col("_time_") > start && col("_time_") < end) .select( col("event"), pct(col("value"), 50).as("p50"), pct(col("value"), 90).as("p90"), pct(col("value"), 99).as("p99")) .groupby({ 1 }) .sortby({ 2 }, SortType::DESC) .limit(10); // compile the query into an execution plan auto plan = query.compile(QueryContext::def()); plan->setWindow({ start, end }); // print out the plan through logging plan->display(); nebula::common::Evidence::Duration tick; // pass the query plan to a server to execute - usually it is itself folly::CPUThreadPoolExecutor pool{ 8 }; auto result = ServerExecutor(nebula::meta::NNode::local().toString()).execute(pool, *plan); // print out result; LOG(INFO) << "----------------------------------------------------------------"; LOG(INFO) << "Get Results With Rows: " << result->size() << " using " << tick.elapsedMs() << " ms"; LOG(INFO) << fmt::format("col: {0:20} | {1:12} | {2:12} | {3:12}", "event", "v.p50", "v.p90", "v.p99"); while (result->hasNext()) { const auto& row = result->next(); LOG(INFO) << fmt::format("row: {0:20} | {1:12} | {2:12} | {3:12}", row.readString("event"), row.readByte("p50"), row.readByte("p90"), row.readByte("p99")); } } TEST(ApiTest, TestTreePathMerge) { auto data = genData(); // query this table auto ms = TableService::singleton(); auto tableName = std::get<0>(data); auto start = std::get<1>(data); auto end = std::get<2>(data); auto query = table(tableName, ms) .where(col("_time_") > start && col("_time_") < end) .select( col("tag"), tpm(col("stack")).as("stacks")) .groupby({ 1 }) .sortby({ 2 }, SortType::DESC) .limit(10); // compile the query into an execution plan auto plan = query.compile(QueryContext::def()); plan->setWindow({ start, end }); // print out the plan through logging plan->display(); nebula::common::Evidence::Duration tick; // pass the query plan to a server to execute - usually it is itself folly::CPUThreadPoolExecutor pool{ 8 }; auto result = ServerExecutor(nebula::meta::NNode::local().toString()).execute(pool, *plan); // print out result; LOG(INFO) << "----------------------------------------------------------------"; LOG(INFO) << "Get Results With Rows: " << result->size() << " using " << tick.elapsedMs() << " ms"; LOG(INFO) << fmt::format("col: {0:20} | {1:40}", "tag", "stacks"); while (result->hasNext()) { const auto& row = result->next(); LOG(INFO) << fmt::format("row: {0:20} | {1:40}", row.readString("tag"), row.readString("stacks")); } } TEST(ApiTest, TestCardinality) { auto data = genData(); // query this table auto ms = TableService::singleton(); auto tableName = std::get<0>(data); auto start = std::get<1>(data); auto end = std::get<2>(data); auto query = table(tableName, ms) .where(col("_time_") > start && col("_time_") < end) .select( col("flag"), card(col("tag")).as("tag_card")) .groupby({ 1 }) .sortby({ 2 }, SortType::DESC) .limit(10); // compile the query into an execution plan auto plan = query.compile(QueryContext::def()); plan->setWindow({ start, end }); // print out the plan through logging plan->display(); nebula::common::Evidence::Duration tick; // pass the query plan to a server to execute - usually it is itself folly::CPUThreadPoolExecutor pool{ 8 }; auto result = ServerExecutor(nebula::meta::NNode::local().toString()).execute(pool, *plan); // print out result; LOG(INFO) << "----------------------------------------------------------------"; LOG(INFO) << "Get Results With Rows: " << result->size() << " using " << tick.elapsedMs() << " ms"; LOG(INFO) << fmt::format("col: {0:20} | {1:40}", "flag", "tag-cardinality"); while (result->hasNext()) { const auto& row = result->next(); LOG(INFO) << fmt::format("row: {0:20} | {1:40}", row.readString("flag"), row.readLong("tag_card")); } } TEST(ApiTest, TestScript) { auto data = genData(); // query this table auto ms = TableService::singleton(); auto tableName = std::get<0>(data); auto start = std::get<1>(data); auto end = std::get<2>(data); auto expr = "const id2 = () => nebula.column(\"id\") - 2000;"; auto query = table(tableName, ms) .where(col("_time_") > start && col("_time_") < end) .select( col("id"), script<int32_t>("id2", expr)) .sortby({ 1 }, SortType::DESC) .limit(10); // compile the query into an execution plan auto plan = query.compile(QueryContext::def()); plan->setWindow({ start, end }); // print out the plan through logging plan->display(); nebula::common::Evidence::Duration tick; // pass the query plan to a server to execute - usually it is itself folly::CPUThreadPoolExecutor pool{ 8 }; auto result = ServerExecutor(nebula::meta::NNode::local().toString()).execute(pool, *plan); // print out result; LOG(INFO) << "----------------------------------------------------------------"; LOG(INFO) << "Get Results With Rows: " << result->size() << " using " << tick.elapsedMs() << " ms"; LOG(INFO) << fmt::format("col: {0:20} | {1:20}", "id", "id2"); while (result->hasNext()) { const auto& row = result->next(); auto id = row.readInt("id"); auto id2 = row.readInt("id2"); EXPECT_EQ(id - 2000, id2); LOG(INFO) << fmt::format("row: {0:20} | {1:20}", id, id2); } } TEST(ApiTest, TestScriptSamples) { auto data = genData(); // query this table auto ms = TableService::singleton(); auto tableName = std::get<0>(data); auto start = std::get<1>(data); auto end = std::get<2>(data); // TODO(cao) - figure out why it will fail script execution // when order by and limit are not specified auto expr = "const id2 = () => nebula.column(\"id\") - 2000;"; auto query = table(tableName, ms) .where(col("_time_") > start && col("_time_") < end) .apply("id2", nebula::type::Kind::INTEGER, expr) .select( col("id"), col("id2")); // compile the query into an execution plan auto plan = query.compile(QueryContext::def()); plan->setWindow({ start, end }); // print out the plan through logging plan->display(); nebula::common::Evidence::Duration tick; // pass the query plan to a server to execute - usually it is itself folly::CPUThreadPoolExecutor pool{ 8 }; auto result = ServerExecutor(nebula::meta::NNode::local().toString()).execute(pool, *plan); // print out result; LOG(INFO) << "----------------------------------------------------------------"; LOG(INFO) << "Get Results With Rows: " << result->size() << " using " << tick.elapsedMs() << " ms"; LOG(INFO) << fmt::format("col: {0:20} | {1:20}", "id", "id2"); while (result->hasNext()) { const auto& row = result->next(); auto id = row.readInt("id"); auto id2 = row.readInt("id2"); EXPECT_EQ(id - 2000, id2); LOG(INFO) << fmt::format("row: {0:20} | {1:20}", id, id2); } } // TODO(cao) - not support scripted column in nested expression yet. // such as: sum(script<int32_t>("id2", expr)), // to support that, we need to register the column first. TEST(ApiTest, TestScriptAggregate) { auto data = genData(); // query this table auto ms = TableService::singleton(); auto tableName = std::get<0>(data); auto start = std::get<1>(data); auto end = std::get<2>(data); auto expr = "const id2 = () => nebula.column(\"id\") % 5;"; auto query = table(tableName, ms) .where(col("_time_") > start && col("_time_") < end) .select( script<int32_t>("id2", expr), count(col("id")).as("count")) .groupby({ 1 }) .sortby({ 2 }, SortType::DESC) .limit(10); // compile the query into an execution plan auto plan = query.compile(QueryContext::def()); plan->setWindow({ start, end }); // print out the plan through logging plan->display(); nebula::common::Evidence::Duration tick; // pass the query plan to a server to execute - usually it is itself folly::CPUThreadPoolExecutor pool{ 8 }; auto result = ServerExecutor(nebula::meta::NNode::local().toString()).execute(pool, *plan); // print out result; LOG(INFO) << "----------------------------------------------------------------"; LOG(INFO) << "Get Results With Rows: " << result->size() << " using " << tick.elapsedMs() << " ms"; LOG(INFO) << fmt::format("col: {0:20} | {1:20}", "id2", "count"); while (result->hasNext()) { const auto& row = result->next(); LOG(INFO) << fmt::format("row: {0:20} | {1:20}", row.readInt("id2"), row.readInt("count")); } } // if a custom column is registered first, then it can be used like normal columns TEST(ApiTest, TestScriptRegisterColumn) { auto data = genData(); // query this table auto ms = TableService::singleton(); auto tableName = std::get<0>(data); auto start = std::get<1>(data); auto end = std::get<2>(data); auto expr = "const id2 = () => nebula.column(\"id\") % 5;"; auto query = table(tableName, ms) .apply("id2", nebula::type::Kind::INTEGER, expr) .where(col("_time_") > start && col("_time_") < end) .select( col("tag"), sum(col("id2")).as("sum")) .groupby({ 1 }) .sortby({ 2 }, SortType::DESC) .limit(10); // compile the query into an execution plan auto plan = query.compile(QueryContext::def()); plan->setWindow({ start, end }); // print out the plan through logging plan->display(); nebula::common::Evidence::Duration tick; // pass the query plan to a server to execute - usually it is itself folly::CPUThreadPoolExecutor pool{ 8 }; auto result = ServerExecutor(nebula::meta::NNode::local().toString()).execute(pool, *plan); // print out result; LOG(INFO) << "----------------------------------------------------------------"; LOG(INFO) << "Get Results With Rows: " << result->size() << " using " << tick.elapsedMs() << " ms"; LOG(INFO) << fmt::format("col: {0:20} | {1:20}", "tag", "sum"); while (result->hasNext()) { const auto& row = result->next(); LOG(INFO) << fmt::format("row: {0:20} | {1:20}", row.readString("tag"), row.readInt("sum")); } } TEST(ApiTest, TestAccessControl) { auto data = genData(); // we know we don't have an id larger than this number, so the query should skip all blocks auto ms = TableService::singleton(); auto tableName = std::get<0>(data); auto start = std::get<1>(data); auto end = std::get<2>(data); auto query = table(tableName, ms) .where(col("_time_") > start && col("_time_") < end) .select( col("event"), col("value"), col("weight")) .limit(10); // compile the query into an execution plan // test table require nebula-users to read event column, refer TestTable.h auto plan = query.compile(QueryContext::create("nebula", { "nebula-guest" })); plan->setWindow({ start, end }); // print out the plan through logging plan->display(); nebula::common::Evidence::Duration tick; // pass the query plan to a server to execute - usually it is itself folly::CPUThreadPoolExecutor pool{ 8 }; auto result = ServerExecutor(nebula::meta::NNode::local().toString()).execute(pool, *plan); // query should have results EXPECT_EQ(result->size(), 10); // print out result; LOG(INFO) << "----------------------------------------------------------------"; LOG(INFO) << "Get Results With Rows: " << result->size() << " using " << tick.elapsedMs() << " ms"; LOG(INFO) << fmt::format("col: {0:20} | {1:12} | {2:12}", "event", "value", "weight"); while (result->hasNext()) { const auto& row = result->next(); // expect event to be masked auto event = row.readString("event"); EXPECT_EQ(event, "***"); LOG(INFO) << fmt::format("row: {0:20} | {1:12} | {2:12}", event, row.readByte("value"), row.readDouble("weight")); } } } // namespace test } // namespace api } // namespace nebula
36.555916
143
0.550388
samprasyork
789260cfda9fcb54ccc257cdd2d0a0bb84b54268
8,557
cpp
C++
batch/src/v20170312/model/TaskTemplateView.cpp
sinjoywong/tencentcloud-sdk-cpp
1b931d20956a90b15a6720f924e5c69f8786f9f4
[ "Apache-2.0" ]
null
null
null
batch/src/v20170312/model/TaskTemplateView.cpp
sinjoywong/tencentcloud-sdk-cpp
1b931d20956a90b15a6720f924e5c69f8786f9f4
[ "Apache-2.0" ]
null
null
null
batch/src/v20170312/model/TaskTemplateView.cpp
sinjoywong/tencentcloud-sdk-cpp
1b931d20956a90b15a6720f924e5c69f8786f9f4
[ "Apache-2.0" ]
null
null
null
/* * Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <tencentcloud/batch/v20170312/model/TaskTemplateView.h> using TencentCloud::CoreInternalOutcome; using namespace TencentCloud::Batch::V20170312::Model; using namespace std; TaskTemplateView::TaskTemplateView() : m_taskTemplateIdHasBeenSet(false), m_taskTemplateNameHasBeenSet(false), m_taskTemplateDescriptionHasBeenSet(false), m_taskTemplateInfoHasBeenSet(false), m_createTimeHasBeenSet(false), m_tagsHasBeenSet(false) { } CoreInternalOutcome TaskTemplateView::Deserialize(const rapidjson::Value &value) { string requestId = ""; if (value.HasMember("TaskTemplateId") && !value["TaskTemplateId"].IsNull()) { if (!value["TaskTemplateId"].IsString()) { return CoreInternalOutcome(Error("response `TaskTemplateView.TaskTemplateId` IsString=false incorrectly").SetRequestId(requestId)); } m_taskTemplateId = string(value["TaskTemplateId"].GetString()); m_taskTemplateIdHasBeenSet = true; } if (value.HasMember("TaskTemplateName") && !value["TaskTemplateName"].IsNull()) { if (!value["TaskTemplateName"].IsString()) { return CoreInternalOutcome(Error("response `TaskTemplateView.TaskTemplateName` IsString=false incorrectly").SetRequestId(requestId)); } m_taskTemplateName = string(value["TaskTemplateName"].GetString()); m_taskTemplateNameHasBeenSet = true; } if (value.HasMember("TaskTemplateDescription") && !value["TaskTemplateDescription"].IsNull()) { if (!value["TaskTemplateDescription"].IsString()) { return CoreInternalOutcome(Error("response `TaskTemplateView.TaskTemplateDescription` IsString=false incorrectly").SetRequestId(requestId)); } m_taskTemplateDescription = string(value["TaskTemplateDescription"].GetString()); m_taskTemplateDescriptionHasBeenSet = true; } if (value.HasMember("TaskTemplateInfo") && !value["TaskTemplateInfo"].IsNull()) { if (!value["TaskTemplateInfo"].IsObject()) { return CoreInternalOutcome(Error("response `TaskTemplateView.TaskTemplateInfo` is not object type").SetRequestId(requestId)); } CoreInternalOutcome outcome = m_taskTemplateInfo.Deserialize(value["TaskTemplateInfo"]); if (!outcome.IsSuccess()) { outcome.GetError().SetRequestId(requestId); return outcome; } m_taskTemplateInfoHasBeenSet = true; } if (value.HasMember("CreateTime") && !value["CreateTime"].IsNull()) { if (!value["CreateTime"].IsString()) { return CoreInternalOutcome(Error("response `TaskTemplateView.CreateTime` IsString=false incorrectly").SetRequestId(requestId)); } m_createTime = string(value["CreateTime"].GetString()); m_createTimeHasBeenSet = true; } if (value.HasMember("Tags") && !value["Tags"].IsNull()) { if (!value["Tags"].IsArray()) return CoreInternalOutcome(Error("response `TaskTemplateView.Tags` is not array type")); const rapidjson::Value &tmpValue = value["Tags"]; for (rapidjson::Value::ConstValueIterator itr = tmpValue.Begin(); itr != tmpValue.End(); ++itr) { Tag item; CoreInternalOutcome outcome = item.Deserialize(*itr); if (!outcome.IsSuccess()) { outcome.GetError().SetRequestId(requestId); return outcome; } m_tags.push_back(item); } m_tagsHasBeenSet = true; } return CoreInternalOutcome(true); } void TaskTemplateView::ToJsonObject(rapidjson::Value &value, rapidjson::Document::AllocatorType& allocator) const { if (m_taskTemplateIdHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "TaskTemplateId"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_taskTemplateId.c_str(), allocator).Move(), allocator); } if (m_taskTemplateNameHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "TaskTemplateName"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_taskTemplateName.c_str(), allocator).Move(), allocator); } if (m_taskTemplateDescriptionHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "TaskTemplateDescription"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_taskTemplateDescription.c_str(), allocator).Move(), allocator); } if (m_taskTemplateInfoHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "TaskTemplateInfo"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(rapidjson::kObjectType).Move(), allocator); m_taskTemplateInfo.ToJsonObject(value[key.c_str()], allocator); } if (m_createTimeHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "CreateTime"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_createTime.c_str(), allocator).Move(), allocator); } if (m_tagsHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "Tags"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(rapidjson::kArrayType).Move(), allocator); int i=0; for (auto itr = m_tags.begin(); itr != m_tags.end(); ++itr, ++i) { value[key.c_str()].PushBack(rapidjson::Value(rapidjson::kObjectType).Move(), allocator); (*itr).ToJsonObject(value[key.c_str()][i], allocator); } } } string TaskTemplateView::GetTaskTemplateId() const { return m_taskTemplateId; } void TaskTemplateView::SetTaskTemplateId(const string& _taskTemplateId) { m_taskTemplateId = _taskTemplateId; m_taskTemplateIdHasBeenSet = true; } bool TaskTemplateView::TaskTemplateIdHasBeenSet() const { return m_taskTemplateIdHasBeenSet; } string TaskTemplateView::GetTaskTemplateName() const { return m_taskTemplateName; } void TaskTemplateView::SetTaskTemplateName(const string& _taskTemplateName) { m_taskTemplateName = _taskTemplateName; m_taskTemplateNameHasBeenSet = true; } bool TaskTemplateView::TaskTemplateNameHasBeenSet() const { return m_taskTemplateNameHasBeenSet; } string TaskTemplateView::GetTaskTemplateDescription() const { return m_taskTemplateDescription; } void TaskTemplateView::SetTaskTemplateDescription(const string& _taskTemplateDescription) { m_taskTemplateDescription = _taskTemplateDescription; m_taskTemplateDescriptionHasBeenSet = true; } bool TaskTemplateView::TaskTemplateDescriptionHasBeenSet() const { return m_taskTemplateDescriptionHasBeenSet; } Task TaskTemplateView::GetTaskTemplateInfo() const { return m_taskTemplateInfo; } void TaskTemplateView::SetTaskTemplateInfo(const Task& _taskTemplateInfo) { m_taskTemplateInfo = _taskTemplateInfo; m_taskTemplateInfoHasBeenSet = true; } bool TaskTemplateView::TaskTemplateInfoHasBeenSet() const { return m_taskTemplateInfoHasBeenSet; } string TaskTemplateView::GetCreateTime() const { return m_createTime; } void TaskTemplateView::SetCreateTime(const string& _createTime) { m_createTime = _createTime; m_createTimeHasBeenSet = true; } bool TaskTemplateView::CreateTimeHasBeenSet() const { return m_createTimeHasBeenSet; } vector<Tag> TaskTemplateView::GetTags() const { return m_tags; } void TaskTemplateView::SetTags(const vector<Tag>& _tags) { m_tags = _tags; m_tagsHasBeenSet = true; } bool TaskTemplateView::TagsHasBeenSet() const { return m_tagsHasBeenSet; }
30.891697
152
0.694052
sinjoywong
789490e223299f18f13ca8d2b02ad88be32468b2
605
cpp
C++
WnCC/Week1/unord_subseq.cpp
AkashCherukuri/CC
b9c1617c28831197a3bf5fe846949fc03ae15507
[ "MIT" ]
null
null
null
WnCC/Week1/unord_subseq.cpp
AkashCherukuri/CC
b9c1617c28831197a3bf5fe846949fc03ae15507
[ "MIT" ]
null
null
null
WnCC/Week1/unord_subseq.cpp
AkashCherukuri/CC
b9c1617c28831197a3bf5fe846949fc03ae15507
[ "MIT" ]
null
null
null
# include "bits/stdc++.h" using namespace std; # define rep(i,a,b) for(int i=a; i<b; i++) int main(){ int n; cin >> n; vector<int> dat(n); rep(i,0,n) cin >> dat[i]; int st = 0; bool ord = true; int x,y,z; rep(i,1,n){ if(st==0){ if(dat[i]>dat[i-1]){ st=1; x=i-1; } else if(dat[i]<dat[i-1]){ st=2; x=i-1; } } else if(st == 1){ if(dat[i]<dat[i-1]){y=i-1; z=i; ord=false; break;} } else if(st == 2){ if(dat[i]>dat[i-1]){y=i-1; z=i; ord=false; break;} } } if(ord==false) cout << 3 << endl << x+1 << " " << y+1 << " " << z+1 << endl; else cout << 0 << endl; return 0; }
18.90625
77
0.48595
AkashCherukuri